odin.js 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069
  1. "use strict";
  2. (function() {
  3. function getElement(name) {
  4. if (name) {
  5. return document.getElementById(name);
  6. }
  7. return undefined;
  8. }
  9. function stripNewline(str) {
  10. return str.replace(/\n/, ' ')
  11. }
  12. class WasmMemoryInterface {
  13. constructor() {
  14. this.memory = null;
  15. this.exports = null;
  16. this.listenerMap = {};
  17. // Size (in bytes) of the integer type, should be 4 on `js_wasm32` and 8 on `js_wasm64p32`
  18. this.intSize = 4;
  19. }
  20. setIntSize(size) {
  21. this.intSize = size;
  22. }
  23. setMemory(memory) {
  24. this.memory = memory;
  25. }
  26. setExports(exports) {
  27. this.exports = exports;
  28. }
  29. get mem() {
  30. return new DataView(this.memory.buffer);
  31. }
  32. loadF32Array(addr, len) {
  33. let array = new Float32Array(this.memory.buffer, addr, len);
  34. return array;
  35. }
  36. loadF64Array(addr, len) {
  37. let array = new Float64Array(this.memory.buffer, addr, len);
  38. return array;
  39. }
  40. loadU32Array(addr, len) {
  41. let array = new Uint32Array(this.memory.buffer, addr, len);
  42. return array;
  43. }
  44. loadI32Array(addr, len) {
  45. let array = new Int32Array(this.memory.buffer, addr, len);
  46. return array;
  47. }
  48. loadU8(addr) { return this.mem.getUint8 (addr); }
  49. loadI8(addr) { return this.mem.getInt8 (addr); }
  50. loadU16(addr) { return this.mem.getUint16 (addr, true); }
  51. loadI16(addr) { return this.mem.getInt16 (addr, true); }
  52. loadU32(addr) { return this.mem.getUint32 (addr, true); }
  53. loadI32(addr) { return this.mem.getInt32 (addr, true); }
  54. loadU64(addr) {
  55. const lo = this.mem.getUint32(addr + 0, true);
  56. const hi = this.mem.getUint32(addr + 4, true);
  57. return lo + hi*4294967296;
  58. };
  59. loadI64(addr) {
  60. const lo = this.mem.getUint32(addr + 0, true);
  61. const hi = this.mem.getInt32 (addr + 4, true);
  62. return lo + hi*4294967296;
  63. };
  64. loadF32(addr) { return this.mem.getFloat32(addr, true); }
  65. loadF64(addr) { return this.mem.getFloat64(addr, true); }
  66. loadInt(addr) {
  67. if (this.intSize == 8) {
  68. return this.loadI64(addr);
  69. } else if (this.intSize == 4) {
  70. return this.loadI32(addr);
  71. } else {
  72. throw new Error('Unhandled `intSize`, expected `4` or `8`');
  73. }
  74. };
  75. loadUint(addr) {
  76. if (this.intSize == 8) {
  77. return this.loadU64(addr);
  78. } else if (this.intSize == 4) {
  79. return this.loadU32(addr);
  80. } else {
  81. throw new Error('Unhandled `intSize`, expected `4` or `8`');
  82. }
  83. };
  84. loadPtr(addr) { return this.loadU32(addr); }
  85. loadB32(addr) {
  86. return this.loadU32(addr) != 0;
  87. }
  88. loadBytes(ptr, len) {
  89. return new Uint8Array(this.memory.buffer, ptr, Number(len));
  90. }
  91. loadString(ptr, len) {
  92. const bytes = this.loadBytes(ptr, Number(len));
  93. return new TextDecoder().decode(bytes);
  94. }
  95. loadCstring(ptr) {
  96. return this.loadCstringDirect(this.loadPtr(ptr));
  97. }
  98. loadCstringDirect(start) {
  99. if (start == 0) {
  100. return null;
  101. }
  102. let len = 0;
  103. for (; this.mem.getUint8(start+len) != 0; len += 1) {}
  104. return this.loadString(start, len);
  105. }
  106. storeU8(addr, value) { this.mem.setUint8 (addr, value); }
  107. storeI8(addr, value) { this.mem.setInt8 (addr, value); }
  108. storeU16(addr, value) { this.mem.setUint16 (addr, value, true); }
  109. storeI16(addr, value) { this.mem.setInt16 (addr, value, true); }
  110. storeU32(addr, value) { this.mem.setUint32 (addr, value, true); }
  111. storeI32(addr, value) { this.mem.setInt32 (addr, value, true); }
  112. storeU64(addr, value) {
  113. this.mem.setUint32(addr + 0, Number(value), true);
  114. let div = 4294967296;
  115. if (typeof value == 'bigint') {
  116. div = BigInt(div);
  117. }
  118. this.mem.setUint32(addr + 4, Math.floor(Number(value / div)), true);
  119. }
  120. storeI64(addr, value) {
  121. this.mem.setUint32(addr + 0, Number(value), true);
  122. let div = 4294967296;
  123. if (typeof value == 'bigint') {
  124. div = BigInt(div);
  125. }
  126. this.mem.setInt32(addr + 4, Math.floor(Number(value / div)), true);
  127. }
  128. storeF32(addr, value) { this.mem.setFloat32(addr, value, true); }
  129. storeF64(addr, value) { this.mem.setFloat64(addr, value, true); }
  130. storeInt(addr, value) {
  131. if (this.intSize == 8) {
  132. this.storeI64(addr, value);
  133. } else if (this.intSize == 4) {
  134. this.storeI32(addr, value);
  135. } else {
  136. throw new Error('Unhandled `intSize`, expected `4` or `8`');
  137. }
  138. }
  139. storeUint(addr, value) {
  140. if (this.intSize == 8) {
  141. this.storeU64(addr, value);
  142. } else if (this.intSize == 4) {
  143. this.storeU32(addr, value);
  144. } else {
  145. throw new Error('Unhandled `intSize`, expected `4` or `8`');
  146. }
  147. }
  148. // Returned length might not be the same as `value.length` if non-ascii strings are given.
  149. storeString(addr, value) {
  150. const src = new TextEncoder().encode(value);
  151. const dst = new Uint8Array(this.memory.buffer, addr, src.length);
  152. dst.set(src);
  153. return src.length;
  154. }
  155. };
  156. class WebGLInterface {
  157. constructor(wasmMemoryInterface) {
  158. this.wasmMemoryInterface = wasmMemoryInterface;
  159. this.ctxElement = null;
  160. this.ctx = null;
  161. this.ctxVersion = 1.0;
  162. this.counter = 1;
  163. this.lastError = 0;
  164. this.buffers = [];
  165. this.mappedBuffers = {};
  166. this.programs = [];
  167. this.framebuffers = [];
  168. this.renderbuffers = [];
  169. this.textures = [];
  170. this.uniforms = [];
  171. this.shaders = [];
  172. this.vaos = [];
  173. this.contexts = [];
  174. this.currentContext = null;
  175. this.offscreenCanvases = {};
  176. this.timerQueriesEXT = [];
  177. this.queries = [];
  178. this.samplers = [];
  179. this.transformFeedbacks = [];
  180. this.syncs = [];
  181. this.programInfos = {};
  182. }
  183. get mem() {
  184. return this.wasmMemoryInterface
  185. }
  186. setCurrentContext(element, contextSettings) {
  187. if (!element) {
  188. return false;
  189. }
  190. if (this.ctxElement == element) {
  191. return true;
  192. }
  193. contextSettings = contextSettings ?? {};
  194. this.ctx = element.getContext("webgl2", contextSettings) || element.getContext("webgl", contextSettings);
  195. if (!this.ctx) {
  196. return false;
  197. }
  198. this.ctxElement = element;
  199. if (this.ctx.getParameter(0x1F02).indexOf("WebGL 2.0") !== -1) {
  200. this.ctxVersion = 2.0;
  201. } else {
  202. this.ctxVersion = 1.0;
  203. }
  204. return true;
  205. }
  206. assertWebGL2() {
  207. if (this.ctxVersion < 2) {
  208. throw new Error("WebGL2 procedure called in a canvas without a WebGL2 context");
  209. }
  210. }
  211. getNewId(table) {
  212. for (var ret = this.counter++, i = table.length; i < ret; i++) {
  213. table[i] = null;
  214. }
  215. return ret;
  216. }
  217. recordError(errorCode) {
  218. this.lastError || (this.lastError = errorCode);
  219. }
  220. populateUniformTable(program) {
  221. let p = this.programs[program];
  222. this.programInfos[program] = {
  223. uniforms: {},
  224. maxUniformLength: 0,
  225. maxAttributeLength: -1,
  226. maxUniformBlockNameLength: -1,
  227. };
  228. for (let ptable = this.programInfos[program], utable = ptable.uniforms, numUniforms = this.ctx.getProgramParameter(p, this.ctx.ACTIVE_UNIFORMS), i = 0; i < numUniforms; ++i) {
  229. let u = this.ctx.getActiveUniform(p, i);
  230. let name = u.name;
  231. if (ptable.maxUniformLength = Math.max(ptable.maxUniformLength, name.length + 1), name.indexOf("]", name.length - 1) !== -1) {
  232. name = name.slice(0, name.lastIndexOf("["));
  233. }
  234. let loc = this.ctx.getUniformLocation(p, name);
  235. if (loc !== null) {
  236. let id = this.getNewId(this.uniforms);
  237. utable[name] = [u.size, id], this.uniforms[id] = loc;
  238. for (let j = 1; j < u.size; ++j) {
  239. let n = name + "[" + j + "]";
  240. let loc = this.ctx.getUniformLocation(p, n);
  241. let id = this.getNewId(this.uniforms);
  242. this.uniforms[id] = loc;
  243. }
  244. }
  245. }
  246. }
  247. getSource(shader, strings_ptr, strings_length) {
  248. const stringSize = this.mem.intSize*2;
  249. let source = "";
  250. for (let i = 0; i < strings_length; i++) {
  251. let ptr = this.mem.loadPtr(strings_ptr + i*stringSize);
  252. let len = this.mem.loadPtr(strings_ptr + i*stringSize + 4);
  253. let str = this.mem.loadString(ptr, len);
  254. source += str;
  255. }
  256. return source;
  257. }
  258. getWebGL1Interface() {
  259. return {
  260. SetCurrentContextById: (name_ptr, name_len) => {
  261. let name = this.mem.loadString(name_ptr, name_len);
  262. let element = getElement(name);
  263. return this.setCurrentContext(element, {alpha: true, antialias: true, depth: true, premultipliedAlpha: true});
  264. },
  265. CreateCurrentContextById: (name_ptr, name_len, attributes) => {
  266. let name = this.mem.loadString(name_ptr, name_len);
  267. let element = getElement(name);
  268. let contextSettings = {
  269. alpha: !(attributes & (1<<0)),
  270. antialias: !(attributes & (1<<1)),
  271. depth: !(attributes & (1<<2)),
  272. failIfMajorPerformanceCaveat: !!(attributes & (1<<3)),
  273. premultipliedAlpha: !(attributes & (1<<4)),
  274. preserveDrawingBuffer: !!(attributes & (1<<5)),
  275. stencil: !!(attributes & (1<<6)),
  276. desynchronized: !!(attributes & (1<<7)),
  277. };
  278. return this.setCurrentContext(element, contextSettings);
  279. },
  280. GetCurrentContextAttributes: () => {
  281. if (!this.ctx) {
  282. return 0;
  283. }
  284. let attrs = this.ctx.getContextAttributes();
  285. let res = 0;
  286. if (!attrs.alpha) res |= 1<<0;
  287. if (!attrs.antialias) res |= 1<<1;
  288. if (!attrs.depth) res |= 1<<2;
  289. if (attrs.failIfMajorPerformanceCaveat) res |= 1<<3;
  290. if (!attrs.premultipliedAlpha) res |= 1<<4;
  291. if (attrs.preserveDrawingBuffer) res |= 1<<5;
  292. if (attrs.stencil) res |= 1<<6;
  293. if (attrs.desynchronized) res |= 1<<7;
  294. return res;
  295. },
  296. DrawingBufferWidth: () => this.ctx.drawingBufferWidth,
  297. DrawingBufferHeight: () => this.ctx.drawingBufferHeight,
  298. IsExtensionSupported: (name_ptr, name_len) => {
  299. let name = this.mem.loadString(name_ptr, name_len);
  300. let extensions = this.ctx.getSupportedExtensions();
  301. return extensions.indexOf(name) !== -1
  302. },
  303. GetError: () => {
  304. let err = this.lastError;
  305. this.recordError(0);
  306. if (err) {
  307. return err;
  308. }
  309. return this.ctx.getError();
  310. },
  311. GetWebGLVersion: (major_ptr, minor_ptr) => {
  312. let version = this.ctx.getParameter(0x1F02);
  313. if (version.indexOf("WebGL 2.0") !== -1) {
  314. this.mem.storeI32(major_ptr, 2);
  315. this.mem.storeI32(minor_ptr, 0);
  316. return;
  317. }
  318. this.mem.storeI32(major_ptr, 1);
  319. this.mem.storeI32(minor_ptr, 0);
  320. },
  321. GetESVersion: (major_ptr, minor_ptr) => {
  322. let version = this.ctx.getParameter(0x1F02);
  323. if (version.indexOf("OpenGL ES 3.0") !== -1) {
  324. this.mem.storeI32(major_ptr, 3);
  325. this.mem.storeI32(minor_ptr, 0);
  326. return;
  327. }
  328. this.mem.storeI32(major_ptr, 2);
  329. this.mem.storeI32(minor_ptr, 0);
  330. },
  331. ActiveTexture: (x) => {
  332. this.ctx.activeTexture(x);
  333. },
  334. AttachShader: (program, shader) => {
  335. this.ctx.attachShader(this.programs[program], this.shaders[shader]);
  336. },
  337. BindAttribLocation: (program, index, name_ptr, name_len) => {
  338. let name = this.mem.loadString(name_ptr, name_len);
  339. this.ctx.bindAttribLocation(this.programs[program], index, name)
  340. },
  341. BindBuffer: (target, buffer) => {
  342. let bufferObj = buffer ? this.buffers[buffer] : null;
  343. if (target == 35051) {
  344. this.ctx.currentPixelPackBufferBinding = buffer;
  345. } else {
  346. if (target == 35052) {
  347. this.ctx.currentPixelUnpackBufferBinding = buffer;
  348. }
  349. this.ctx.bindBuffer(target, bufferObj)
  350. }
  351. },
  352. BindFramebuffer: (target, framebuffer) => {
  353. this.ctx.bindFramebuffer(target, framebuffer ? this.framebuffers[framebuffer] : null)
  354. },
  355. BindTexture: (target, texture) => {
  356. this.ctx.bindTexture(target, texture ? this.textures[texture] : null)
  357. },
  358. BlendColor: (red, green, blue, alpha) => {
  359. this.ctx.blendColor(red, green, blue, alpha);
  360. },
  361. BlendEquation: (mode) => {
  362. this.ctx.blendEquation(mode);
  363. },
  364. BlendEquationSeparate: (modeRGB, modeAlpha) => {
  365. this.ctx.blendEquationSeparate(modeRGB, modeAlpha);
  366. },
  367. BlendFunc: (sfactor, dfactor) => {
  368. this.ctx.blendFunc(sfactor, dfactor);
  369. },
  370. BlendFuncSeparate: (srcRGB, dstRGB, srcAlpha, dstAlpha) => {
  371. this.ctx.blendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha);
  372. },
  373. BufferData: (target, size, data, usage) => {
  374. if (data) {
  375. this.ctx.bufferData(target, this.mem.loadBytes(data, size), usage);
  376. } else {
  377. this.ctx.bufferData(target, size, usage);
  378. }
  379. },
  380. BufferSubData: (target, offset, size, data) => {
  381. if (data) {
  382. this.ctx.bufferSubData(target, offset, this.mem.loadBytes(data, size));
  383. } else {
  384. this.ctx.bufferSubData(target, offset, null);
  385. }
  386. },
  387. Clear: (x) => {
  388. this.ctx.clear(x);
  389. },
  390. ClearColor: (r, g, b, a) => {
  391. this.ctx.clearColor(r, g, b, a);
  392. },
  393. ClearDepth: (x) => {
  394. this.ctx.clearDepth(x);
  395. },
  396. ClearStencil: (x) => {
  397. this.ctx.clearStencil(x);
  398. },
  399. ColorMask: (r, g, b, a) => {
  400. this.ctx.colorMask(!!r, !!g, !!b, !!a);
  401. },
  402. CompileShader: (shader) => {
  403. this.ctx.compileShader(this.shaders[shader]);
  404. },
  405. CompressedTexImage2D: (target, level, internalformat, width, height, border, imageSize, data) => {
  406. if (data) {
  407. this.ctx.compressedTexImage2D(target, level, internalformat, width, height, border, this.mem.loadBytes(data, imageSize));
  408. } else {
  409. this.ctx.compressedTexImage2D(target, level, internalformat, width, height, border, null);
  410. }
  411. },
  412. CompressedTexSubImage2D: (target, level, xoffset, yoffset, width, height, format, imageSize, data) => {
  413. if (data) {
  414. this.ctx.compressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, this.mem.loadBytes(data, imageSize));
  415. } else {
  416. this.ctx.compressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, null);
  417. }
  418. },
  419. CopyTexImage2D: (target, level, internalformat, x, y, width, height, border) => {
  420. this.ctx.copyTexImage2D(target, level, internalformat, x, y, width, height, border);
  421. },
  422. CopyTexSubImage2D: (target, level, xoffset, yoffset, x, y, width, height) => {
  423. this.ctx.copyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height);
  424. },
  425. CreateBuffer: () => {
  426. let buffer = this.ctx.createBuffer();
  427. if (!buffer) {
  428. this.recordError(1282);
  429. return 0;
  430. }
  431. let id = this.getNewId(this.buffers);
  432. buffer.name = id
  433. this.buffers[id] = buffer;
  434. return id;
  435. },
  436. CreateFramebuffer: () => {
  437. let buffer = this.ctx.createFramebuffer();
  438. let id = this.getNewId(this.framebuffers);
  439. buffer.name = id
  440. this.framebuffers[id] = buffer;
  441. return id;
  442. },
  443. CreateProgram: () => {
  444. let program = this.ctx.createProgram();
  445. let id = this.getNewId(this.programs);
  446. program.name = id;
  447. this.programs[id] = program;
  448. return id;
  449. },
  450. CreateRenderbuffer: () => {
  451. let buffer = this.ctx.createRenderbuffer();
  452. let id = this.getNewId(this.renderbuffers);
  453. buffer.name = id;
  454. this.renderbuffers[id] = buffer;
  455. return id;
  456. },
  457. CreateShader: (shaderType) => {
  458. let shader = this.ctx.createShader(shaderType);
  459. let id = this.getNewId(this.shaders);
  460. shader.name = id;
  461. this.shaders[id] = shader;
  462. return id;
  463. },
  464. CreateTexture: () => {
  465. let texture = this.ctx.createTexture();
  466. if (!texture) {
  467. this.recordError(1282)
  468. return 0;
  469. }
  470. let id = this.getNewId(this.textures);
  471. texture.name = id;
  472. this.textures[id] = texture;
  473. return id;
  474. },
  475. CullFace: (mode) => {
  476. this.ctx.cullFace(mode);
  477. },
  478. DeleteBuffer: (id) => {
  479. let obj = this.buffers[id];
  480. if (obj && id != 0) {
  481. this.ctx.deleteBuffer(obj);
  482. this.buffers[id] = null;
  483. }
  484. },
  485. DeleteFramebuffer: (id) => {
  486. let obj = this.framebuffers[id];
  487. if (obj && id != 0) {
  488. this.ctx.deleteFramebuffer(obj);
  489. this.framebuffers[id] = null;
  490. }
  491. },
  492. DeleteProgram: (id) => {
  493. let obj = this.programs[id];
  494. if (obj && id != 0) {
  495. this.ctx.deleteProgram(obj);
  496. this.programs[id] = null;
  497. }
  498. },
  499. DeleteRenderbuffer: (id) => {
  500. let obj = this.renderbuffers[id];
  501. if (obj && id != 0) {
  502. this.ctx.deleteRenderbuffer(obj);
  503. this.renderbuffers[id] = null;
  504. }
  505. },
  506. DeleteShader: (id) => {
  507. let obj = this.shaders[id];
  508. if (obj && id != 0) {
  509. this.ctx.deleteShader(obj);
  510. this.shaders[id] = null;
  511. }
  512. },
  513. DeleteTexture: (id) => {
  514. let obj = this.textures[id];
  515. if (obj && id != 0) {
  516. this.ctx.deleteTexture(obj);
  517. this.textures[id] = null;
  518. }
  519. },
  520. DepthFunc: (func) => {
  521. this.ctx.depthFunc(func);
  522. },
  523. DepthMask: (flag) => {
  524. this.ctx.depthMask(!!flag);
  525. },
  526. DepthRange: (zNear, zFar) => {
  527. this.ctx.depthRange(zNear, zFar);
  528. },
  529. DetachShader: (program, shader) => {
  530. this.ctx.detachShader(this.programs[program], this.shaders[shader]);
  531. },
  532. Disable: (cap) => {
  533. this.ctx.disable(cap);
  534. },
  535. DisableVertexAttribArray: (index) => {
  536. this.ctx.disableVertexAttribArray(index);
  537. },
  538. DrawArrays: (mode, first, count) => {
  539. this.ctx.drawArrays(mode, first, count);
  540. },
  541. DrawElements: (mode, count, type, indices) => {
  542. this.ctx.drawElements(mode, count, type, indices);
  543. },
  544. Enable: (cap) => {
  545. this.ctx.enable(cap);
  546. },
  547. EnableVertexAttribArray: (index) => {
  548. this.ctx.enableVertexAttribArray(index);
  549. },
  550. Finish: () => {
  551. this.ctx.finish();
  552. },
  553. Flush: () => {
  554. this.ctx.flush();
  555. },
  556. FramebufferRenderbuffer: (target, attachment, renderbuffertarget, renderbuffer) => {
  557. this.ctx.framebufferRenderbuffer(target, attachment, renderbuffertarget, this.renderbuffers[renderbuffer]);
  558. },
  559. FramebufferTexture2D: (target, attachment, textarget, texture, level) => {
  560. this.ctx.framebufferTexture2D(target, attachment, textarget, this.textures[texture], level);
  561. },
  562. FrontFace: (mode) => {
  563. this.ctx.frontFace(mode);
  564. },
  565. GenerateMipmap: (target) => {
  566. this.ctx.generateMipmap(target);
  567. },
  568. GetAttribLocation: (program, name_ptr, name_len) => {
  569. let name = this.mem.loadString(name_ptr, name_len);
  570. return this.ctx.getAttribLocation(this.programs[program], name);
  571. },
  572. GetParameter: (pname) => {
  573. return this.ctx.getParameter(pname);
  574. },
  575. GetParameter4i: (pname, v0, v1, v2, v3) => {
  576. const i4 = this.ctx.getParameter(pname);
  577. this.mem.storeI32(v0, i4[0]);
  578. this.mem.storeI32(v1, i4[1]);
  579. this.mem.storeI32(v2, i4[2]);
  580. this.mem.storeI32(v3, i4[3]);
  581. },
  582. GetProgramParameter: (program, pname) => {
  583. return this.ctx.getProgramParameter(this.programs[program], pname)
  584. },
  585. GetProgramInfoLog: (program, buf_ptr, buf_len, length_ptr) => {
  586. let log = this.ctx.getProgramInfoLog(this.programs[program]);
  587. if (log === null) {
  588. log = "(unknown error)";
  589. }
  590. if (buf_len > 0 && buf_ptr) {
  591. let n = Math.min(buf_len, log.length);
  592. log = log.substring(0, n);
  593. this.mem.loadBytes(buf_ptr, buf_len).set(new TextEncoder().encode(log))
  594. this.mem.storeInt(length_ptr, n);
  595. }
  596. },
  597. GetShaderInfoLog: (shader, buf_ptr, buf_len, length_ptr) => {
  598. let log = this.ctx.getShaderInfoLog(this.shaders[shader]);
  599. if (log === null) {
  600. log = "(unknown error)";
  601. }
  602. if (buf_len > 0 && buf_ptr) {
  603. let n = Math.min(buf_len, log.length);
  604. log = log.substring(0, n);
  605. this.mem.loadBytes(buf_ptr, buf_len).set(new TextEncoder().encode(log))
  606. this.mem.storeInt(length_ptr, n);
  607. }
  608. },
  609. GetShaderiv: (shader, pname, p) => {
  610. if (p) {
  611. if (pname == 35716) {
  612. let log = this.ctx.getShaderInfoLog(this.shaders[shader]);
  613. if (log === null) {
  614. log = "(unknown error)";
  615. }
  616. this.mem.storeInt(p, log.length+1);
  617. } else if (pname == 35720) {
  618. let source = this.ctx.getShaderSource(this.shaders[shader]);
  619. let sourceLength = (source === null || source.length == 0) ? 0 : source.length+1;
  620. this.mem.storeInt(p, sourceLength);
  621. } else {
  622. let param = this.ctx.getShaderParameter(this.shaders[shader], pname);
  623. this.mem.storeI32(p, param);
  624. }
  625. } else {
  626. this.recordError(1281);
  627. }
  628. },
  629. GetUniformLocation: (program, name_ptr, name_len) => {
  630. let name = this.mem.loadString(name_ptr, name_len);
  631. let arrayOffset = 0;
  632. if (name.indexOf("]", name.length - 1) !== -1) {
  633. let ls = name.lastIndexOf("["),
  634. arrayIndex = name.slice(ls + 1, -1);
  635. if (arrayIndex.length > 0 && (arrayOffset = parseInt(arrayIndex)) < 0) {
  636. return -1;
  637. }
  638. name = name.slice(0, ls)
  639. }
  640. var ptable = this.programInfos[program];
  641. if (!ptable) {
  642. return -1;
  643. }
  644. var uniformInfo = ptable.uniforms[name];
  645. return (uniformInfo && arrayOffset < uniformInfo[0]) ? uniformInfo[1] + arrayOffset : -1
  646. },
  647. GetVertexAttribOffset: (index, pname) => {
  648. return this.ctx.getVertexAttribOffset(index, pname);
  649. },
  650. Hint: (target, mode) => {
  651. this.ctx.hint(target, mode);
  652. },
  653. IsBuffer: (buffer) => this.ctx.isBuffer(this.buffers[buffer]),
  654. IsEnabled: (cap) => this.ctx.isEnabled(cap),
  655. IsFramebuffer: (framebuffer) => this.ctx.isFramebuffer(this.framebuffers[framebuffer]),
  656. IsProgram: (program) => this.ctx.isProgram(this.programs[program]),
  657. IsRenderbuffer: (renderbuffer) => this.ctx.isRenderbuffer(this.renderbuffers[renderbuffer]),
  658. IsShader: (shader) => this.ctx.isShader(this.shaders[shader]),
  659. IsTexture: (texture) => this.ctx.isTexture(this.textures[texture]),
  660. LineWidth: (width) => {
  661. this.ctx.lineWidth(width);
  662. },
  663. LinkProgram: (program) => {
  664. this.ctx.linkProgram(this.programs[program]);
  665. this.programInfos[program] = null;
  666. this.populateUniformTable(program);
  667. },
  668. PixelStorei: (pname, param) => {
  669. this.ctx.pixelStorei(pname, param);
  670. },
  671. PolygonOffset: (factor, units) => {
  672. this.ctx.polygonOffset(factor, units);
  673. },
  674. ReadnPixels: (x, y, width, height, format, type, bufSize, data) => {
  675. this.ctx.readPixels(x, y, width, height, format, type, this.mem.loadBytes(data, bufSize));
  676. },
  677. RenderbufferStorage: (target, internalformat, width, height) => {
  678. this.ctx.renderbufferStorage(target, internalformat, width, height);
  679. },
  680. SampleCoverage: (value, invert) => {
  681. this.ctx.sampleCoverage(value, !!invert);
  682. },
  683. Scissor: (x, y, width, height) => {
  684. this.ctx.scissor(x, y, width, height);
  685. },
  686. ShaderSource: (shader, strings_ptr, strings_length) => {
  687. let source = this.getSource(shader, strings_ptr, strings_length);
  688. this.ctx.shaderSource(this.shaders[shader], source);
  689. },
  690. StencilFunc: (func, ref, mask) => {
  691. this.ctx.stencilFunc(func, ref, mask);
  692. },
  693. StencilFuncSeparate: (face, func, ref, mask) => {
  694. this.ctx.stencilFuncSeparate(face, func, ref, mask);
  695. },
  696. StencilMask: (mask) => {
  697. this.ctx.stencilMask(mask);
  698. },
  699. StencilMaskSeparate: (face, mask) => {
  700. this.ctx.stencilMaskSeparate(face, mask);
  701. },
  702. StencilOp: (fail, zfail, zpass) => {
  703. this.ctx.stencilOp(fail, zfail, zpass);
  704. },
  705. StencilOpSeparate: (face, fail, zfail, zpass) => {
  706. this.ctx.stencilOpSeparate(face, fail, zfail, zpass);
  707. },
  708. TexImage2D: (target, level, internalformat, width, height, border, format, type, size, data) => {
  709. if (data) {
  710. this.ctx.texImage2D(target, level, internalformat, width, height, border, format, type, this.mem.loadBytes(data, size));
  711. } else {
  712. this.ctx.texImage2D(target, level, internalformat, width, height, border, format, type, null);
  713. }
  714. },
  715. TexParameterf: (target, pname, param) => {
  716. this.ctx.texParameterf(target, pname, param);
  717. },
  718. TexParameteri: (target, pname, param) => {
  719. this.ctx.texParameteri(target, pname, param);
  720. },
  721. TexSubImage2D: (target, level, xoffset, yoffset, width, height, format, type, size, data) => {
  722. this.ctx.texSubImage2D(target, level, xoffset, yoffset, width, height, format, type, this.mem.loadBytes(data, size));
  723. },
  724. Uniform1f: (location, v0) => { this.ctx.uniform1f(this.uniforms[location], v0); },
  725. Uniform2f: (location, v0, v1) => { this.ctx.uniform2f(this.uniforms[location], v0, v1); },
  726. Uniform3f: (location, v0, v1, v2) => { this.ctx.uniform3f(this.uniforms[location], v0, v1, v2); },
  727. Uniform4f: (location, v0, v1, v2, v3) => { this.ctx.uniform4f(this.uniforms[location], v0, v1, v2, v3); },
  728. Uniform1i: (location, v0) => { this.ctx.uniform1i(this.uniforms[location], v0); },
  729. Uniform2i: (location, v0, v1) => { this.ctx.uniform2i(this.uniforms[location], v0, v1); },
  730. Uniform3i: (location, v0, v1, v2) => { this.ctx.uniform3i(this.uniforms[location], v0, v1, v2); },
  731. Uniform4i: (location, v0, v1, v2, v3) => { this.ctx.uniform4i(this.uniforms[location], v0, v1, v2, v3); },
  732. UniformMatrix2fv: (location, addr) => {
  733. let array = this.mem.loadF32Array(addr, 2*2);
  734. this.ctx.uniformMatrix2fv(this.uniforms[location], false, array);
  735. },
  736. UniformMatrix3fv: (location, addr) => {
  737. let array = this.mem.loadF32Array(addr, 3*3);
  738. this.ctx.uniformMatrix3fv(this.uniforms[location], false, array);
  739. },
  740. UniformMatrix4fv: (location, addr) => {
  741. let array = this.mem.loadF32Array(addr, 4*4);
  742. this.ctx.uniformMatrix4fv(this.uniforms[location], false, array);
  743. },
  744. UseProgram: (program) => {
  745. if (program) this.ctx.useProgram(this.programs[program]);
  746. },
  747. ValidateProgram: (program) => {
  748. if (program) this.ctx.validateProgram(this.programs[program]);
  749. },
  750. VertexAttrib1f: (index, x) => {
  751. this.ctx.vertexAttrib1f(index, x);
  752. },
  753. VertexAttrib2f: (index, x, y) => {
  754. this.ctx.vertexAttrib2f(index, x, y);
  755. },
  756. VertexAttrib3f: (index, x, y, z) => {
  757. this.ctx.vertexAttrib3f(index, x, y, z);
  758. },
  759. VertexAttrib4f: (index, x, y, z, w) => {
  760. this.ctx.vertexAttrib4f(index, x, y, z, w);
  761. },
  762. VertexAttribPointer: (index, size, type, normalized, stride, ptr) => {
  763. this.ctx.vertexAttribPointer(index, size, type, !!normalized, stride, ptr);
  764. },
  765. Viewport: (x, y, w, h) => {
  766. this.ctx.viewport(x, y, w, h);
  767. },
  768. };
  769. }
  770. getWebGL2Interface() {
  771. return {
  772. /* Buffer objects */
  773. CopyBufferSubData: (readTarget, writeTarget, readOffset, writeOffset, size) => {
  774. this.assertWebGL2();
  775. this.ctx.copyBufferSubData(readTarget, writeTarget, readOffset, writeOffset, size);
  776. },
  777. GetBufferSubData: (target, srcByteOffset, dst_buffer_ptr, dst_buffer_len, dstOffset, length) => {
  778. this.assertWebGL2();
  779. this.ctx.getBufferSubData(target, srcByteOffset, this.mem.loadBytes(dst_buffer_ptr, dst_buffer_len), dstOffset, length);
  780. },
  781. /* Framebuffer objects */
  782. BlitFramebuffer: (srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter) => {
  783. this.assertWebGL2();
  784. this.ctx.blitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter);
  785. },
  786. FramebufferTextureLayer: (target, attachment, texture, level, layer) => {
  787. this.assertWebGL2();
  788. this.ctx.framebufferTextureLayer(target, attachment, this.textures[texture], level, layer);
  789. },
  790. InvalidateFramebuffer: (target, attachments_ptr, attachments_len) => {
  791. this.assertWebGL2();
  792. let attachments = this.mem.loadU32Array(attachments_ptr, attachments_len);
  793. this.ctx.invalidateFramebuffer(target, attachments);
  794. },
  795. InvalidateSubFramebuffer: (target, attachments_ptr, attachments_len, x, y, width, height) => {
  796. this.assertWebGL2();
  797. let attachments = this.mem.loadU32Array(attachments_ptr, attachments_len);
  798. this.ctx.invalidateSubFramebuffer(target, attachments, x, y, width, height);
  799. },
  800. ReadBuffer: (src) => {
  801. this.assertWebGL2();
  802. this.ctx.readBuffer(src);
  803. },
  804. /* Renderbuffer objects */
  805. RenderbufferStorageMultisample: (target, samples, internalformat, width, height) => {
  806. this.assertWebGL2();
  807. this.ctx.renderbufferStorageMultisample(target, samples, internalformat, width, height);
  808. },
  809. /* Texture objects */
  810. TexStorage3D: (target, levels, internalformat, width, height, depth) => {
  811. this.assertWebGL2();
  812. this.ctx.texStorage3D(target, levels, internalformat, width, height, depth);
  813. },
  814. TexImage3D: (target, level, internalformat, width, height, depth, border, format, type, size, data) => {
  815. this.assertWebGL2();
  816. if (data) {
  817. this.ctx.texImage3D(target, level, internalformat, width, height, depth, border, format, type, this.mem.loadBytes(data, size));
  818. } else {
  819. this.ctx.texImage3D(target, level, internalformat, width, height, depth, border, format, type, null);
  820. }
  821. },
  822. TexSubImage3D: (target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, size, data) => {
  823. this.assertWebGL2();
  824. this.ctx.texSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, this.mem.loadBytes(data, size));
  825. },
  826. CompressedTexImage3D: (target, level, internalformat, width, height, depth, border, imageSize, data) => {
  827. this.assertWebGL2();
  828. if (data) {
  829. this.ctx.compressedTexImage3D(target, level, internalformat, width, height, depth, border, this.mem.loadBytes(data, imageSize));
  830. } else {
  831. this.ctx.compressedTexImage3D(target, level, internalformat, width, height, depth, border, null);
  832. }
  833. },
  834. CompressedTexSubImage3D: (target, level, xoffset, yoffset, zoffset, width, height, depth, format, imageSize, data) => {
  835. this.assertWebGL2();
  836. if (data) {
  837. this.ctx.compressedTexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, this.mem.loadBytes(data, imageSize));
  838. } else {
  839. this.ctx.compressedTexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, null);
  840. }
  841. },
  842. CopyTexSubImage3D: (target, level, xoffset, yoffset, zoffset, x, y, width, height) => {
  843. this.assertWebGL2();
  844. this.ctx.copyTexSubImage3D(target, level, xoffset, yoffset, zoffset, x, y, width, height);
  845. },
  846. /* Programs and shaders */
  847. GetFragDataLocation: (program, name_ptr, name_len) => {
  848. this.assertWebGL2();
  849. return this.ctx.getFragDataLocation(this.programs[program], this.mem.loadString(name_ptr, name_len));
  850. },
  851. /* Uniforms */
  852. Uniform1ui: (location, v0) => {
  853. this.assertWebGL2();
  854. this.ctx.uniform1ui(this.uniforms[location], v0);
  855. },
  856. Uniform2ui: (location, v0, v1) => {
  857. this.assertWebGL2();
  858. this.ctx.uniform2ui(this.uniforms[location], v0, v1);
  859. },
  860. Uniform3ui: (location, v0, v1, v2) => {
  861. this.assertWebGL2();
  862. this.ctx.uniform3ui(this.uniforms[location], v0, v1, v2);
  863. },
  864. Uniform4ui: (location, v0, v1, v2, v3) => {
  865. this.assertWebGL2();
  866. this.ctx.uniform4ui(this.uniforms[location], v0, v1, v2, v3);
  867. },
  868. UniformMatrix3x2fv: (location, addr) => {
  869. this.assertWebGL2();
  870. let array = this.mem.loadF32Array(addr, 3*2);
  871. this.ctx.uniformMatrix3x2fv(this.uniforms[location], false, array);
  872. },
  873. UniformMatrix4x2fv: (location, addr) => {
  874. this.assertWebGL2();
  875. let array = this.mem.loadF32Array(addr, 4*2);
  876. this.ctx.uniformMatrix4x2fv(this.uniforms[location], false, array);
  877. },
  878. UniformMatrix2x3fv: (location, addr) => {
  879. this.assertWebGL2();
  880. let array = this.mem.loadF32Array(addr, 2*3);
  881. this.ctx.uniformMatrix2x3fv(this.uniforms[location], false, array);
  882. },
  883. UniformMatrix4x3fv: (location, addr) => {
  884. this.assertWebGL2();
  885. let array = this.mem.loadF32Array(addr, 4*3);
  886. this.ctx.uniformMatrix4x3fv(this.uniforms[location], false, array);
  887. },
  888. UniformMatrix2x4fv: (location, addr) => {
  889. this.assertWebGL2();
  890. let array = this.mem.loadF32Array(addr, 2*4);
  891. this.ctx.uniformMatrix2x4fv(this.uniforms[location], false, array);
  892. },
  893. UniformMatrix3x4fv: (location, addr) => {
  894. this.assertWebGL2();
  895. let array = this.mem.loadF32Array(addr, 3*4);
  896. this.ctx.uniformMatrix3x4fv(this.uniforms[location], false, array);
  897. },
  898. /* Vertex attribs */
  899. VertexAttribI4i: (index, x, y, z, w) => {
  900. this.assertWebGL2();
  901. this.ctx.vertexAttribI4i(index, x, y, z, w);
  902. },
  903. VertexAttribI4ui: (index, x, y, z, w) => {
  904. this.assertWebGL2();
  905. this.ctx.vertexAttribI4ui(index, x, y, z, w);
  906. },
  907. VertexAttribIPointer: (index, size, type, stride, offset) => {
  908. this.assertWebGL2();
  909. this.ctx.vertexAttribIPointer(index, size, type, stride, offset);
  910. },
  911. /* Writing to the drawing buffer */
  912. VertexAttribDivisor: (index, divisor) => {
  913. this.assertWebGL2();
  914. this.ctx.vertexAttribDivisor(index, divisor);
  915. },
  916. DrawArraysInstanced: (mode, first, count, instanceCount) => {
  917. this.assertWebGL2();
  918. this.ctx.drawArraysInstanced(mode, first, count, instanceCount);
  919. },
  920. DrawElementsInstanced: (mode, count, type, offset, instanceCount) => {
  921. this.assertWebGL2();
  922. this.ctx.drawElementsInstanced(mode, count, type, offset, instanceCount);
  923. },
  924. DrawRangeElements: (mode, start, end, count, type, offset) => {
  925. this.assertWebGL2();
  926. this.ctx.drawRangeElements(mode, start, end, count, type, offset);
  927. },
  928. /* Multiple Render Targets */
  929. DrawBuffers: (buffers_ptr, buffers_len) => {
  930. this.assertWebGL2();
  931. let array = this.mem.loadU32Array(buffers_ptr, buffers_len);
  932. this.ctx.drawBuffers(array);
  933. },
  934. ClearBufferfv: (buffer, drawbuffer, values_ptr, values_len) => {
  935. this.assertWebGL2();
  936. let array = this.mem.loadF32Array(values_ptr, values_len);
  937. this.ctx.clearBufferfv(buffer, drawbuffer, array);
  938. },
  939. ClearBufferiv: (buffer, drawbuffer, values_ptr, values_len) => {
  940. this.assertWebGL2();
  941. let array = this.mem.loadI32Array(values_ptr, values_len);
  942. this.ctx.clearBufferiv(buffer, drawbuffer, array);
  943. },
  944. ClearBufferuiv: (buffer, drawbuffer, values_ptr, values_len) => {
  945. this.assertWebGL2();
  946. let array = this.mem.loadU32Array(values_ptr, values_len);
  947. this.ctx.clearBufferuiv(buffer, drawbuffer, array);
  948. },
  949. ClearBufferfi: (buffer, drawbuffer, depth, stencil) => {
  950. this.assertWebGL2();
  951. this.ctx.clearBufferfi(buffer, drawbuffer, depth, stencil);
  952. },
  953. /* Query Objects */
  954. CreateQuery: () => {
  955. this.assertWebGL2();
  956. let query = this.ctx.createQuery();
  957. let id = this.getNewId(this.queries);
  958. query.name = id;
  959. this.queries[id] = query;
  960. return id;
  961. },
  962. DeleteQuery: (id) => {
  963. this.assertWebGL2();
  964. let obj = this.queries[id];
  965. if (obj && id != 0) {
  966. this.ctx.deleteQuery(obj);
  967. this.queries[id] = null;
  968. }
  969. },
  970. IsQuery: (query) => {
  971. this.assertWebGL2();
  972. return this.ctx.isQuery(this.queries[query]);
  973. },
  974. BeginQuery: (target, query) => {
  975. this.assertWebGL2();
  976. this.ctx.beginQuery(target, this.queries[query])
  977. },
  978. EndQuery: (target) => {
  979. this.assertWebGL2();
  980. this.ctx.endQuery(target);
  981. },
  982. GetQuery: (target, pname) => {
  983. this.assertWebGL2();
  984. let query = this.ctx.getQuery(target, pname);
  985. if (!query) {
  986. return 0;
  987. }
  988. if (this.queries.indexOf(query) !== -1) {
  989. return query.name;
  990. }
  991. let id = this.getNewId(this.queries);
  992. query.name = id;
  993. this.queries[id] = query;
  994. return id;
  995. },
  996. /* Sampler Objects */
  997. CreateSampler: () => {
  998. this.assertWebGL2();
  999. let sampler = this.ctx.createSampler();
  1000. let id = this.getNewId(this.samplers);
  1001. sampler.name = id;
  1002. this.samplers[id] = sampler;
  1003. return id;
  1004. },
  1005. DeleteSampler: (id) => {
  1006. this.assertWebGL2();
  1007. let obj = this.samplers[id];
  1008. if (obj && id != 0) {
  1009. this.ctx.deleteSampler(obj);
  1010. this.samplers[id] = null;
  1011. }
  1012. },
  1013. IsSampler: (sampler) => {
  1014. this.assertWebGL2();
  1015. return this.ctx.isSampler(this.samplers[sampler]);
  1016. },
  1017. BindSampler: (unit, sampler) => {
  1018. this.assertWebGL2();
  1019. this.ctx.bindSampler(unit, this.samplers[sampler]);
  1020. },
  1021. SamplerParameteri: (sampler, pname, param) => {
  1022. this.assertWebGL2();
  1023. this.ctx.samplerParameteri(this.samplers[sampler], pname, param);
  1024. },
  1025. SamplerParameterf: (sampler, pname, param) => {
  1026. this.assertWebGL2();
  1027. this.ctx.samplerParameterf(this.samplers[sampler], pname, param);
  1028. },
  1029. /* Sync objects */
  1030. FenceSync: (condition, flags) => {
  1031. this.assertWebGL2();
  1032. let sync = this.ctx.fenceSync(condition, flags);
  1033. let id = this.getNewId(this.syncs);
  1034. sync.name = id;
  1035. this.syncs[id] = sync;
  1036. return id;
  1037. },
  1038. IsSync: (sync) => {
  1039. this.assertWebGL2();
  1040. return this.ctx.isSync(this.syncs[sync]);
  1041. },
  1042. DeleteSync: (id) => {
  1043. this.assertWebGL2();
  1044. let obj = this.syncs[id];
  1045. if (obj && id != 0) {
  1046. this.ctx.deleteSampler(obj);
  1047. this.syncs[id] = null;
  1048. }
  1049. },
  1050. ClientWaitSync: (sync, flags, timeout) => {
  1051. this.assertWebGL2();
  1052. return this.ctx.clientWaitSync(this.syncs[sync], flags, timeout);
  1053. },
  1054. WaitSync: (sync, flags, timeout) => {
  1055. this.assertWebGL2();
  1056. this.ctx.waitSync(this.syncs[sync], flags, timeout) ;
  1057. },
  1058. /* Transform Feedback */
  1059. CreateTransformFeedback: () => {
  1060. this.assertWebGL2();
  1061. let transformFeedback = this.ctx.createTransformFeedback();
  1062. let id = this.getNewId(this.transformFeedbacks);
  1063. transformFeedback.name = id;
  1064. this.transformFeedbacks[id] = transformFeedback;
  1065. return id;
  1066. },
  1067. DeleteTransformFeedback: (id) => {
  1068. this.assertWebGL2();
  1069. let obj = this.transformFeedbacks[id];
  1070. if (obj && id != 0) {
  1071. this.ctx.deleteTransformFeedback(obj);
  1072. this.transformFeedbacks[id] = null;
  1073. }
  1074. },
  1075. IsTransformFeedback: (tf) => {
  1076. this.assertWebGL2();
  1077. return this.ctx.isTransformFeedback(this.transformFeedbacks[tf]);
  1078. },
  1079. BindTransformFeedback: (target, tf) => {
  1080. this.assertWebGL2();
  1081. this.ctx.bindTransformFeedback(target, this.transformFeedbacks[tf]);
  1082. },
  1083. BeginTransformFeedback: (primitiveMode) => {
  1084. this.assertWebGL2();
  1085. this.ctx.beginTransformFeedback(primitiveMode);
  1086. },
  1087. EndTransformFeedback: () => {
  1088. this.assertWebGL2();
  1089. this.ctx.endTransformFeedback();
  1090. },
  1091. TransformFeedbackVaryings: (program, varyings_ptr, varyings_len, bufferMode) => {
  1092. this.assertWebGL2();
  1093. const stringSize = this.mem.intSize*2;
  1094. let varyings = [];
  1095. for (let i = 0; i < varyings_len; i++) {
  1096. let ptr = this.mem.loadPtr(varyings_ptr + i*stringSize + 0*4);
  1097. let len = this.mem.loadPtr(varyings_ptr + i*stringSize + 1*4);
  1098. varyings.push(this.mem.loadString(ptr, len));
  1099. }
  1100. this.ctx.transformFeedbackVaryings(this.programs[program], varyings, bufferMode);
  1101. },
  1102. PauseTransformFeedback: () => {
  1103. this.assertWebGL2();
  1104. this.ctx.pauseTransformFeedback();
  1105. },
  1106. ResumeTransformFeedback: () => {
  1107. this.assertWebGL2();
  1108. this.ctx.resumeTransformFeedback();
  1109. },
  1110. /* Uniform Buffer Objects and Transform Feedback Buffers */
  1111. BindBufferBase: (target, index, buffer) => {
  1112. this.assertWebGL2();
  1113. this.ctx.bindBufferBase(target, index, this.buffers[buffer]);
  1114. },
  1115. BindBufferRange: (target, index, buffer, offset, size) => {
  1116. this.assertWebGL2();
  1117. this.ctx.bindBufferRange(target, index, this.buffers[buffer], offset, size);
  1118. },
  1119. GetUniformBlockIndex: (program, uniformBlockName_ptr, uniformBlockName_len) => {
  1120. this.assertWebGL2();
  1121. return this.ctx.getUniformBlockIndex(this.programs[program], this.mem.loadString(uniformBlockName_ptr, uniformBlockName_len));
  1122. },
  1123. // any getActiveUniformBlockParameter(WebGLProgram program, GLuint uniformBlockIndex, GLenum pname);
  1124. GetActiveUniformBlockName: (program, uniformBlockIndex, buf_ptr, buf_len, length_ptr) => {
  1125. this.assertWebGL2();
  1126. let name = this.ctx.getActiveUniformBlockName(this.programs[program], uniformBlockIndex);
  1127. let n = Math.min(buf_len, name.length);
  1128. name = name.substring(0, n);
  1129. this.mem.loadBytes(buf_ptr, buf_len).set(new TextEncoder().encode(name))
  1130. this.mem.storeInt(length_ptr, n);
  1131. },
  1132. UniformBlockBinding: (program, uniformBlockIndex, uniformBlockBinding) => {
  1133. this.assertWebGL2();
  1134. this.ctx.uniformBlockBinding(this.programs[program], uniformBlockIndex, uniformBlockBinding);
  1135. },
  1136. /* Vertex Array Objects */
  1137. CreateVertexArray: () => {
  1138. this.assertWebGL2();
  1139. let vao = this.ctx.createVertexArray();
  1140. let id = this.getNewId(this.vaos);
  1141. vao.name = id;
  1142. this.vaos[id] = vao;
  1143. return id;
  1144. },
  1145. DeleteVertexArray: (id) => {
  1146. this.assertWebGL2();
  1147. let obj = this.vaos[id];
  1148. if (obj && id != 0) {
  1149. this.ctx.deleteVertexArray(obj);
  1150. this.vaos[id] = null;
  1151. }
  1152. },
  1153. IsVertexArray: (vertexArray) => {
  1154. this.assertWebGL2();
  1155. return this.ctx.isVertexArray(this.vaos[vertexArray]);
  1156. },
  1157. BindVertexArray: (vertexArray) => {
  1158. this.assertWebGL2();
  1159. this.ctx.bindVertexArray(this.vaos[vertexArray]);
  1160. },
  1161. };
  1162. }
  1163. };
  1164. function odinSetupDefaultImports(wasmMemoryInterface, consoleElement, memory) {
  1165. const MAX_INFO_CONSOLE_LINES = 512;
  1166. let infoConsoleLines = new Array();
  1167. let currentLine = {};
  1168. currentLine[false] = "";
  1169. currentLine[true] = "";
  1170. let prevIsError = false;
  1171. let event_temp = {};
  1172. const onEventReceived = (event_data, data, callback) => {
  1173. event_temp.data = event_data;
  1174. const exports = wasmMemoryInterface.exports;
  1175. const odin_ctx = exports.default_context_ptr();
  1176. exports.odin_dom_do_event_callback(data, callback, odin_ctx);
  1177. event_temp.data = null;
  1178. };
  1179. const writeToConsole = (line, isError) => {
  1180. if (!line) {
  1181. return;
  1182. }
  1183. const println = (text, forceIsError) => {
  1184. let style = [
  1185. "color: #eee",
  1186. "background-color: #d20",
  1187. "padding: 2px 4px",
  1188. "border-radius: 2px",
  1189. ].join(";");
  1190. let doIsError = isError;
  1191. if (forceIsError !== undefined) {
  1192. doIsError = forceIsError;
  1193. }
  1194. if (doIsError) {
  1195. console.log("%c"+text, style);
  1196. } else {
  1197. console.log(text);
  1198. }
  1199. };
  1200. // Print to console
  1201. if (line == "\n") {
  1202. println(currentLine[isError]);
  1203. currentLine[isError] = "";
  1204. } else if (!line.includes("\n")) {
  1205. currentLine[isError] = currentLine[isError].concat(line);
  1206. } else {
  1207. let lines = line.split("\n");
  1208. let printLast = lines.length > 1 && line.endsWith("\n");
  1209. println(currentLine[isError].concat(lines[0]));
  1210. currentLine[isError] = "";
  1211. for (let i = 1; i < lines.length-1; i++) {
  1212. println(lines[i]);
  1213. }
  1214. let last = lines[lines.length-1];
  1215. if (printLast) {
  1216. println(last);
  1217. } else {
  1218. currentLine[isError] = last;
  1219. }
  1220. }
  1221. if (prevIsError != isError) {
  1222. if (prevIsError) {
  1223. println(currentLine[prevIsError], prevIsError);
  1224. currentLine[prevIsError] = "";
  1225. }
  1226. }
  1227. prevIsError = isError;
  1228. // HTML based console
  1229. if (!consoleElement) {
  1230. return;
  1231. }
  1232. const wrap = (x) => {
  1233. if (isError) {
  1234. return '<span style="color:#f21">'+x+'</span>';
  1235. }
  1236. return x;
  1237. };
  1238. if (line == "\n") {
  1239. infoConsoleLines.push(line);
  1240. } else if (!line.includes("\n")) {
  1241. let prevLine = "";
  1242. if (infoConsoleLines.length > 0) {
  1243. prevLine = infoConsoleLines.pop();
  1244. }
  1245. infoConsoleLines.push(prevLine.concat(wrap(line)));
  1246. } else {
  1247. let lines = line.split("\n");
  1248. let lastHasNewline = lines.length > 1 && line.endsWith("\n");
  1249. let prevLine = "";
  1250. if (infoConsoleLines.length > 0) {
  1251. prevLine = infoConsoleLines.pop();
  1252. }
  1253. infoConsoleLines.push(prevLine.concat(wrap(lines[0]).concat("\n")));
  1254. for (let i = 1; i < lines.length-1; i++) {
  1255. infoConsoleLines.push(wrap(lines[i]).concat("\n"));
  1256. }
  1257. let last = lines[lines.length-1];
  1258. if (lastHasNewline) {
  1259. infoConsoleLines.push(last.concat("\n"));
  1260. } else {
  1261. infoConsoleLines.push(last);
  1262. }
  1263. }
  1264. if (infoConsoleLines.length > MAX_INFO_CONSOLE_LINES) {
  1265. infoConsoleLines.shift(MAX_INFO_CONSOLE_LINES);
  1266. }
  1267. let data = "";
  1268. for (let i = 0; i < infoConsoleLines.length; i++) {
  1269. data = data.concat(infoConsoleLines[i]);
  1270. }
  1271. let info = consoleElement;
  1272. info.innerHTML = data;
  1273. info.scrollTop = info.scrollHeight;
  1274. };
  1275. let webglContext = new WebGLInterface(wasmMemoryInterface);
  1276. const env = {};
  1277. if (memory) {
  1278. env.memory = memory;
  1279. }
  1280. return {
  1281. env,
  1282. "odin_env": {
  1283. write: (fd, ptr, len) => {
  1284. const str = wasmMemoryInterface.loadString(ptr, len);
  1285. if (fd == 1) {
  1286. writeToConsole(str, false);
  1287. return;
  1288. } else if (fd == 2) {
  1289. writeToConsole(str, true);
  1290. return;
  1291. } else {
  1292. throw new Error("Invalid fd to 'write'" + stripNewline(str));
  1293. }
  1294. },
  1295. trap: () => { throw new Error() },
  1296. alert: (ptr, len) => { alert(wasmMemoryInterface.loadString(ptr, len)) },
  1297. abort: () => { Module.abort() },
  1298. evaluate: (str_ptr, str_len) => { eval.call(null, wasmMemoryInterface.loadString(str_ptr, str_len)); },
  1299. open: (url_ptr, url_len, name_ptr, name_len, specs_ptr, specs_len) => {
  1300. const url = wasmMemoryInterface.loadString(url_ptr, url_len);
  1301. const name = wasmMemoryInterface.loadString(name_ptr, name_len);
  1302. const specs = wasmMemoryInterface.loadString(specs_ptr, specs_len);
  1303. window.open(url, name, specs);
  1304. },
  1305. // return a bigint to be converted to i64
  1306. time_now: () => BigInt(Date.now()),
  1307. tick_now: () => performance.now(),
  1308. time_sleep: (duration_ms) => {
  1309. if (duration_ms > 0) {
  1310. // TODO(bill): Does this even make any sense?
  1311. }
  1312. },
  1313. sqrt: Math.sqrt,
  1314. sin: Math.sin,
  1315. cos: Math.cos,
  1316. pow: Math.pow,
  1317. fmuladd: (x, y, z) => x*y + z,
  1318. ln: Math.log,
  1319. exp: Math.exp,
  1320. ldexp: (x, exp) => x * Math.pow(2, exp),
  1321. rand_bytes: (ptr, len) => {
  1322. const view = new Uint8Array(wasmMemoryInterface.memory.buffer, ptr, len)
  1323. crypto.getRandomValues(view)
  1324. },
  1325. },
  1326. "odin_dom": {
  1327. init_event_raw: (ep) => {
  1328. const W = wasmMemoryInterface.intSize;
  1329. let offset = ep;
  1330. let off = (amount, alignment) => {
  1331. if (alignment === undefined) {
  1332. alignment = Math.min(amount, W);
  1333. }
  1334. if (offset % alignment != 0) {
  1335. offset += alignment - (offset%alignment);
  1336. }
  1337. let x = offset;
  1338. offset += amount;
  1339. return x;
  1340. };
  1341. let align = (alignment) => {
  1342. const modulo = offset & (alignment-1);
  1343. if (modulo != 0) {
  1344. offset += alignment - modulo
  1345. }
  1346. };
  1347. let wmi = wasmMemoryInterface;
  1348. if (!event_temp.data) {
  1349. return;
  1350. }
  1351. let e = event_temp.data.event;
  1352. wmi.storeU32(off(4), event_temp.data.name_code);
  1353. if (e.target == document) {
  1354. wmi.storeU32(off(4), 1);
  1355. } else if (e.target == window) {
  1356. wmi.storeU32(off(4), 2);
  1357. } else {
  1358. wmi.storeU32(off(4), 0);
  1359. }
  1360. if (e.currentTarget == document) {
  1361. wmi.storeU32(off(4), 1);
  1362. } else if (e.currentTarget == window) {
  1363. wmi.storeU32(off(4), 2);
  1364. } else {
  1365. wmi.storeU32(off(4), 0);
  1366. }
  1367. align(W);
  1368. wmi.storeI32(off(W), event_temp.data.id_ptr);
  1369. wmi.storeUint(off(W), event_temp.data.id_len);
  1370. align(8);
  1371. wmi.storeF64(off(8), e.timeStamp*1e-3);
  1372. wmi.storeU8(off(1), e.eventPhase);
  1373. let options = 0;
  1374. if (!!e.bubbles) { options |= 1<<0; }
  1375. if (!!e.cancelable) { options |= 1<<1; }
  1376. if (!!e.composed) { options |= 1<<2; }
  1377. wmi.storeU8(off(1), options);
  1378. wmi.storeU8(off(1), !!e.isComposing);
  1379. wmi.storeU8(off(1), !!e.isTrusted);
  1380. align(8);
  1381. if (e instanceof WheelEvent) {
  1382. wmi.storeF64(off(8), e.deltaX);
  1383. wmi.storeF64(off(8), e.deltaY);
  1384. wmi.storeF64(off(8), e.deltaZ);
  1385. wmi.storeU32(off(4), e.deltaMode);
  1386. } else if (e instanceof MouseEvent) {
  1387. wmi.storeI64(off(8), e.screenX);
  1388. wmi.storeI64(off(8), e.screenY);
  1389. wmi.storeI64(off(8), e.clientX);
  1390. wmi.storeI64(off(8), e.clientY);
  1391. wmi.storeI64(off(8), e.offsetX);
  1392. wmi.storeI64(off(8), e.offsetY);
  1393. wmi.storeI64(off(8), e.pageX);
  1394. wmi.storeI64(off(8), e.pageY);
  1395. wmi.storeI64(off(8), e.movementX);
  1396. wmi.storeI64(off(8), e.movementY);
  1397. wmi.storeU8(off(1), !!e.ctrlKey);
  1398. wmi.storeU8(off(1), !!e.shiftKey);
  1399. wmi.storeU8(off(1), !!e.altKey);
  1400. wmi.storeU8(off(1), !!e.metaKey);
  1401. wmi.storeI16(off(2), e.button);
  1402. wmi.storeU16(off(2), e.buttons);
  1403. if (e instanceof PointerEvent) {
  1404. wmi.storeF64(off(8), e.altitudeAngle);
  1405. wmi.storeF64(off(8), e.azimuthAngle);
  1406. wmi.storeInt(off(W), e.persistentDeviceId);
  1407. wmi.storeInt(off(W), e.pointerId);
  1408. wmi.storeInt(off(W), e.width);
  1409. wmi.storeInt(off(W), e.height);
  1410. wmi.storeF64(off(8), e.pressure);
  1411. wmi.storeF64(off(8), e.tangentialPressure);
  1412. wmi.storeF64(off(8), e.tiltX);
  1413. wmi.storeF64(off(8), e.tiltY);
  1414. wmi.storeF64(off(8), e.twist);
  1415. if (e.pointerType == "pen") {
  1416. wmi.storeU8(off(1), 1);
  1417. } else if (e.pointerType == "touch") {
  1418. wmi.storeU8(off(1), 2);
  1419. } else {
  1420. wmi.storeU8(off(1), 0);
  1421. }
  1422. wmi.storeU8(off(1), !!e.isPrimary);
  1423. }
  1424. } else if (e instanceof KeyboardEvent) {
  1425. // Note: those strings are constructed
  1426. // on the native side from buffers that
  1427. // are filled later, so skip them
  1428. const keyPtr = off(W*2, W);
  1429. const codePtr = off(W*2, W);
  1430. wmi.storeU8(off(1), e.location);
  1431. wmi.storeU8(off(1), !!e.ctrlKey);
  1432. wmi.storeU8(off(1), !!e.shiftKey);
  1433. wmi.storeU8(off(1), !!e.altKey);
  1434. wmi.storeU8(off(1), !!e.metaKey);
  1435. wmi.storeU8(off(1), !!e.repeat);
  1436. wmi.storeI32(off(4), e.charCode);
  1437. wmi.storeInt(off(W, W), e.key.length)
  1438. wmi.storeInt(off(W, W), e.code.length)
  1439. wmi.storeString(off(32, 1), e.key);
  1440. wmi.storeString(off(32, 1), e.code);
  1441. } else if (e.type === 'scroll') {
  1442. wmi.storeF64(off(8, 8), window.scrollX);
  1443. wmi.storeF64(off(8, 8), window.scrollY);
  1444. } else if (e.type === 'visibilitychange') {
  1445. wmi.storeU8(off(1), !document.hidden);
  1446. } else if (e instanceof GamepadEvent) {
  1447. const idPtr = off(W*2, W);
  1448. const mappingPtr = off(W*2, W);
  1449. wmi.storeI32(off(W, W), e.gamepad.index);
  1450. wmi.storeU8(off(1), !!e.gamepad.connected);
  1451. wmi.storeF64(off(8, 8), e.gamepad.timestamp);
  1452. wmi.storeInt(off(W, W), e.gamepad.buttons.length);
  1453. wmi.storeInt(off(W, W), e.gamepad.axes.length);
  1454. for (let i = 0; i < 64; i++) {
  1455. if (i < e.gamepad.buttons.length) {
  1456. let b = e.gamepad.buttons[i];
  1457. wmi.storeF64(off(8, 8), b.value);
  1458. wmi.storeU8(off(1), !!b.pressed);
  1459. wmi.storeU8(off(1), !!b.touched);
  1460. } else {
  1461. off(16, 8);
  1462. }
  1463. }
  1464. for (let i = 0; i < 16; i++) {
  1465. if (i < e.gamepad.axes.length) {
  1466. let a = e.gamepad.axes[i];
  1467. wmi.storeF64(off(8, 8), a);
  1468. } else {
  1469. off(8, 8);
  1470. }
  1471. }
  1472. let idLength = e.gamepad.id.length;
  1473. let id = e.gamepad.id;
  1474. if (idLength > 96) {
  1475. idLength = 96;
  1476. id = id.slice(0, 93) + '...';
  1477. }
  1478. let mappingLength = e.gamepad.mapping.length;
  1479. let mapping = e.gamepad.mapping;
  1480. if (mappingLength > 64) {
  1481. mappingLength = 61;
  1482. mapping = mapping.slice(0, 61) + '...';
  1483. }
  1484. wmi.storeInt(off(W, W), idLength);
  1485. wmi.storeInt(off(W, W), mappingLength);
  1486. wmi.storeString(off(96, 1), id);
  1487. wmi.storeString(off(64, 1), mapping);
  1488. }
  1489. },
  1490. add_event_listener: (id_ptr, id_len, name_ptr, name_len, name_code, data, callback, use_capture) => {
  1491. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1492. let name = wasmMemoryInterface.loadString(name_ptr, name_len);
  1493. let element = getElement(id);
  1494. if (element == undefined) {
  1495. return false;
  1496. }
  1497. let listener = (e) => {
  1498. let event_data = {};
  1499. event_data.id_ptr = id_ptr;
  1500. event_data.id_len = id_len;
  1501. event_data.event = e;
  1502. event_data.name_code = name_code;
  1503. onEventReceived(event_data, data, callback);
  1504. };
  1505. wasmMemoryInterface.listenerMap[{data: data, callback: callback}] = listener;
  1506. element.addEventListener(name, listener, !!use_capture);
  1507. return true;
  1508. },
  1509. add_window_event_listener: (name_ptr, name_len, name_code, data, callback, use_capture) => {
  1510. let name = wasmMemoryInterface.loadString(name_ptr, name_len);
  1511. let element = window;
  1512. let listener = (e) => {
  1513. let event_data = {};
  1514. event_data.id_ptr = 0;
  1515. event_data.id_len = 0;
  1516. event_data.event = e;
  1517. event_data.name_code = name_code;
  1518. onEventReceived(event_data, data, callback);
  1519. };
  1520. wasmMemoryInterface.listenerMap[{data: data, callback: callback}] = listener;
  1521. element.addEventListener(name, listener, !!use_capture);
  1522. return true;
  1523. },
  1524. remove_event_listener: (id_ptr, id_len, name_ptr, name_len, data, callback) => {
  1525. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1526. let name = wasmMemoryInterface.loadString(name_ptr, name_len);
  1527. let element = getElement(id);
  1528. if (element == undefined) {
  1529. return false;
  1530. }
  1531. let listener = wasmMemoryInterface.listenerMap[{data: data, callback: callback}];
  1532. if (listener == undefined) {
  1533. return false;
  1534. }
  1535. element.removeEventListener(name, listener);
  1536. return true;
  1537. },
  1538. remove_window_event_listener: (name_ptr, name_len, data, callback) => {
  1539. let name = wasmMemoryInterface.loadString(name_ptr, name_len);
  1540. let element = window;
  1541. let key = {data: data, callback: callback};
  1542. let listener = wasmMemoryInterface.listenerMap[key];
  1543. if (!listener) {
  1544. return false;
  1545. }
  1546. wasmMemoryInterface.listenerMap[key] = undefined;
  1547. element.removeEventListener(name, listener);
  1548. return true;
  1549. },
  1550. event_stop_propagation: () => {
  1551. if (event_temp.data && event_temp.data.event) {
  1552. event_temp.data.event.stopPropagation();
  1553. }
  1554. },
  1555. event_stop_immediate_propagation: () => {
  1556. if (event_temp.data && event_temp.data.event) {
  1557. event_temp.data.event.stopImmediatePropagation();
  1558. }
  1559. },
  1560. event_prevent_default: () => {
  1561. if (event_temp.data && event_temp.data.event) {
  1562. event_temp.data.event.preventDefault();
  1563. }
  1564. },
  1565. dispatch_custom_event: (id_ptr, id_len, name_ptr, name_len, options_bits) => {
  1566. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1567. let name = wasmMemoryInterface.loadString(name_ptr, name_len);
  1568. let options = {
  1569. bubbles: (options_bits & (1<<0)) !== 0,
  1570. cancelable: (options_bits & (1<<1)) !== 0,
  1571. composed: (options_bits & (1<<2)) !== 0,
  1572. };
  1573. let element = getElement(id);
  1574. if (element) {
  1575. element.dispatchEvent(new Event(name, options));
  1576. return true;
  1577. }
  1578. return false;
  1579. },
  1580. get_gamepad_state: (gamepad_id, ep) => {
  1581. let index = gamepad_id;
  1582. let gps = navigator.getGamepads();
  1583. if (0 <= index && index < gps.length) {
  1584. let gamepad = gps[index];
  1585. if (!gamepad) {
  1586. return false;
  1587. }
  1588. const W = wasmMemoryInterface.intSize;
  1589. let offset = ep;
  1590. let off = (amount, alignment) => {
  1591. if (alignment === undefined) {
  1592. alignment = Math.min(amount, W);
  1593. }
  1594. if (offset % alignment != 0) {
  1595. offset += alignment - (offset%alignment);
  1596. }
  1597. let x = offset;
  1598. offset += amount;
  1599. return x;
  1600. };
  1601. let align = (alignment) => {
  1602. const modulo = offset & (alignment-1);
  1603. if (modulo != 0) {
  1604. offset += alignment - modulo
  1605. }
  1606. };
  1607. let wmi = wasmMemoryInterface;
  1608. const idPtr = off(W*2, W);
  1609. const mappingPtr = off(W*2, W);
  1610. wmi.storeI32(off(W), gamepad.index);
  1611. wmi.storeU8(off(1), !!gamepad.connected);
  1612. wmi.storeF64(off(8), gamepad.timestamp);
  1613. wmi.storeInt(off(W), gamepad.buttons.length);
  1614. wmi.storeInt(off(W), gamepad.axes.length);
  1615. for (let i = 0; i < 64; i++) {
  1616. if (i < gamepad.buttons.length) {
  1617. let b = gamepad.buttons[i];
  1618. wmi.storeF64(off(8, 8), b.value);
  1619. wmi.storeU8(off(1), !!b.pressed);
  1620. wmi.storeU8(off(1), !!b.touched);
  1621. } else {
  1622. off(16, 8);
  1623. }
  1624. }
  1625. for (let i = 0; i < 16; i++) {
  1626. if (i < gamepad.axes.length) {
  1627. wmi.storeF64(off(8, 8), gamepad.axes[i]);
  1628. } else {
  1629. off(8, 8);
  1630. }
  1631. }
  1632. let idLength = gamepad.id.length;
  1633. let id = gamepad.id;
  1634. if (idLength > 96) {
  1635. idLength = 96;
  1636. id = id.slice(0, 93) + '...';
  1637. }
  1638. let mappingLength = gamepad.mapping.length;
  1639. let mapping = gamepad.mapping;
  1640. if (mappingLength > 64) {
  1641. mappingLength = 61;
  1642. mapping = mapping.slice(0, 61) + '...';
  1643. }
  1644. wmi.storeInt(off(W, W), idLength);
  1645. wmi.storeInt(off(W, W), mappingLength);
  1646. wmi.storeString(off(96, 1), id);
  1647. wmi.storeString(off(64, 1), mapping);
  1648. return true;
  1649. }
  1650. return false;
  1651. },
  1652. get_element_value_f64: (id_ptr, id_len) => {
  1653. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1654. let element = getElement(id);
  1655. return element ? element.value : 0;
  1656. },
  1657. get_element_value_string: (id_ptr, id_len, buf_ptr, buf_len) => {
  1658. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1659. let element = getElement(id);
  1660. if (element) {
  1661. let str = element.value;
  1662. if (buf_len > 0 && buf_ptr) {
  1663. let n = Math.min(buf_len, str.length);
  1664. str = str.substring(0, n);
  1665. this.mem.loadBytes(buf_ptr, buf_len).set(new TextEncoder().encode(str))
  1666. return n;
  1667. }
  1668. }
  1669. return 0;
  1670. },
  1671. get_element_value_string_length: (id_ptr, id_len) => {
  1672. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1673. let element = getElement(id);
  1674. if (element) {
  1675. return element.value.length;
  1676. }
  1677. return 0;
  1678. },
  1679. get_element_min_max: (ptr_array2_f64, id_ptr, id_len) => {
  1680. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1681. let element = getElement(id);
  1682. if (element) {
  1683. let values = wasmMemoryInterface.loadF64Array(ptr_array2_f64, 2);
  1684. values[0] = element.min;
  1685. values[1] = element.max;
  1686. }
  1687. },
  1688. set_element_value_f64: (id_ptr, id_len, value) => {
  1689. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1690. let element = getElement(id);
  1691. if (element) {
  1692. element.value = value;
  1693. }
  1694. },
  1695. set_element_value_string: (id_ptr, id_len, value_ptr, value_len) => {
  1696. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1697. let value = wasmMemoryInterface.loadString(value_ptr, value_len);
  1698. let element = getElement(id);
  1699. if (element) {
  1700. element.value = value;
  1701. }
  1702. },
  1703. set_element_style: (id_ptr, id_len, key_ptr, key_len, value_ptr, value_len) => {
  1704. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1705. let key = wasmMemoryInterface.loadString(key_ptr, key_len);
  1706. let value = wasmMemoryInterface.loadString(value_ptr, value_len);
  1707. let element = getElement(id);
  1708. if (element) {
  1709. element.style[key] = value;
  1710. }
  1711. },
  1712. get_element_key_f64: (id_ptr, id_len, key_ptr, key_len) => {
  1713. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1714. let key = wasmMemoryInterface.loadString(key_ptr, key_len);
  1715. let element = getElement(id);
  1716. return element ? element[key] : 0;
  1717. },
  1718. get_element_key_string: (id_ptr, id_len, key_ptr, key_len, buf_ptr, buf_len) => {
  1719. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1720. let key = wasmMemoryInterface.loadString(key_ptr, key_len);
  1721. let element = getElement(id);
  1722. if (element) {
  1723. let str = element[key];
  1724. if (buf_len > 0 && buf_ptr) {
  1725. let n = Math.min(buf_len, str.length);
  1726. str = str.substring(0, n);
  1727. this.mem.loadBytes(buf_ptr, buf_len).set(new TextEncoder().encode(str))
  1728. return n;
  1729. }
  1730. }
  1731. return 0;
  1732. },
  1733. get_element_key_string_length: (id_ptr, id_len, key_ptr, key_len) => {
  1734. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1735. let key = wasmMemoryInterface.loadString(key_ptr, key_len);
  1736. let element = getElement(id);
  1737. if (element && element[key]) {
  1738. return element[key].length;
  1739. }
  1740. return 0;
  1741. },
  1742. set_element_key_f64: (id_ptr, id_len, key_ptr, key_len, value) => {
  1743. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1744. let key = wasmMemoryInterface.loadString(key_ptr, key_len);
  1745. let element = getElement(id);
  1746. if (element) {
  1747. element[key] = value;
  1748. }
  1749. },
  1750. set_element_key_string: (id_ptr, id_len, key_ptr, key_len, value_ptr, value_len) => {
  1751. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1752. let key = wasmMemoryInterface.loadString(key_ptr, key_len);
  1753. let value = wasmMemoryInterface.loadString(value_ptr, value_len);
  1754. let element = getElement(id);
  1755. if (element) {
  1756. element[key] = value;
  1757. }
  1758. },
  1759. get_bounding_client_rect: (rect_ptr, id_ptr, id_len) => {
  1760. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1761. let element = getElement(id);
  1762. if (element) {
  1763. let values = wasmMemoryInterface.loadF64Array(rect_ptr, 4);
  1764. let rect = element.getBoundingClientRect();
  1765. values[0] = rect.left;
  1766. values[1] = rect.top;
  1767. values[2] = rect.right - rect.left;
  1768. values[3] = rect.bottom - rect.top;
  1769. }
  1770. },
  1771. window_get_rect: (rect_ptr) => {
  1772. let values = wasmMemoryInterface.loadF64Array(rect_ptr, 4);
  1773. values[0] = window.screenX;
  1774. values[1] = window.screenY;
  1775. values[2] = window.screen.width;
  1776. values[3] = window.screen.height;
  1777. },
  1778. window_get_scroll: (pos_ptr) => {
  1779. let values = wasmMemoryInterface.loadF64Array(pos_ptr, 2);
  1780. values[0] = window.scrollX;
  1781. values[1] = window.scrollY;
  1782. },
  1783. window_set_scroll: (x, y) => {
  1784. window.scroll(x, y);
  1785. },
  1786. device_pixel_ratio: () => {
  1787. return window.devicePixelRatio;
  1788. },
  1789. },
  1790. "webgl": webglContext.getWebGL1Interface(),
  1791. "webgl2": webglContext.getWebGL2Interface(),
  1792. };
  1793. };
  1794. /**
  1795. * @param {string} wasmPath - Path to the WASM module to run
  1796. * @param {?HTMLPreElement} consoleElement - Optional console/pre element to append output to, in addition to the console
  1797. * @param {any} extraForeignImports - Imports, in addition to the default runtime to provide the module
  1798. * @param {?WasmMemoryInterface} wasmMemoryInterface - Optional memory to use instead of the defaults
  1799. * @param {?int} intSize - Size (in bytes) of the integer type, should be 4 on `js_wasm32` and 8 on `js_wasm64p32`
  1800. */
  1801. async function runWasm(wasmPath, consoleElement, extraForeignImports, wasmMemoryInterface, intSize = 4) {
  1802. if (!wasmMemoryInterface) {
  1803. wasmMemoryInterface = new WasmMemoryInterface();
  1804. }
  1805. wasmMemoryInterface.setIntSize(intSize);
  1806. let imports = odinSetupDefaultImports(wasmMemoryInterface, consoleElement, wasmMemoryInterface.memory);
  1807. let exports = {};
  1808. if (extraForeignImports !== undefined) {
  1809. imports = {
  1810. ...imports,
  1811. ...extraForeignImports,
  1812. };
  1813. }
  1814. const response = await fetch(wasmPath);
  1815. const file = await response.arrayBuffer();
  1816. const wasm = await WebAssembly.instantiate(file, imports);
  1817. exports = wasm.instance.exports;
  1818. wasmMemoryInterface.setExports(exports);
  1819. if (exports.memory) {
  1820. if (wasmMemoryInterface.memory) {
  1821. console.warn("WASM module exports memory, but `runWasm` was given an interface with existing memory too");
  1822. }
  1823. wasmMemoryInterface.setMemory(exports.memory);
  1824. }
  1825. exports._start();
  1826. // Define a `@export step :: proc(delta_time: f64) -> (keep_going: bool) {`
  1827. // in your app and it will get called every frame.
  1828. // return `false` to stop the execution of the module.
  1829. if (exports.step) {
  1830. const odin_ctx = exports.default_context_ptr();
  1831. let prevTimeStamp = undefined;
  1832. function step(currTimeStamp) {
  1833. if (prevTimeStamp == undefined) {
  1834. prevTimeStamp = currTimeStamp;
  1835. }
  1836. const dt = (currTimeStamp - prevTimeStamp)*0.001;
  1837. prevTimeStamp = currTimeStamp;
  1838. if (!exports.step(dt, odin_ctx)) {
  1839. exports._end();
  1840. return;
  1841. }
  1842. window.requestAnimationFrame(step);
  1843. }
  1844. window.requestAnimationFrame(step);
  1845. } else {
  1846. exports._end();
  1847. }
  1848. return;
  1849. };
  1850. window.odin = {
  1851. // Interface Types
  1852. WasmMemoryInterface: WasmMemoryInterface,
  1853. WebGLInterface: WebGLInterface,
  1854. // Functions
  1855. setupDefaultImports: odinSetupDefaultImports,
  1856. runWasm: runWasm,
  1857. };
  1858. })();