odin.js 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088
  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 = new Map();
  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.trimEnd().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. if (lines.length > 1) {
  1215. let last = lines[lines.length-1];
  1216. if (printLast) {
  1217. println(last);
  1218. } else {
  1219. currentLine[isError] = last;
  1220. }
  1221. }
  1222. }
  1223. if (prevIsError != isError) {
  1224. if (prevIsError) {
  1225. println(currentLine[prevIsError], prevIsError);
  1226. currentLine[prevIsError] = "";
  1227. }
  1228. }
  1229. prevIsError = isError;
  1230. // HTML based console
  1231. if (!consoleElement) {
  1232. return;
  1233. }
  1234. const wrap = (x) => {
  1235. if (isError) {
  1236. return '<span style="color:#f21">'+x+'</span>';
  1237. }
  1238. return x;
  1239. };
  1240. if (line == "\n") {
  1241. infoConsoleLines.push(line);
  1242. } else if (!line.includes("\n")) {
  1243. let prevLine = "";
  1244. if (infoConsoleLines.length > 0) {
  1245. prevLine = infoConsoleLines.pop();
  1246. }
  1247. infoConsoleLines.push(prevLine.concat(wrap(line)));
  1248. } else {
  1249. let lines = line.split("\n");
  1250. let lastHasNewline = lines.length > 1 && line.endsWith("\n");
  1251. let prevLine = "";
  1252. if (infoConsoleLines.length > 0) {
  1253. prevLine = infoConsoleLines.pop();
  1254. }
  1255. infoConsoleLines.push(prevLine.concat(wrap(lines[0]).concat("\n")));
  1256. for (let i = 1; i < lines.length-1; i++) {
  1257. infoConsoleLines.push(wrap(lines[i]).concat("\n"));
  1258. }
  1259. let last = lines[lines.length-1];
  1260. if (lastHasNewline) {
  1261. infoConsoleLines.push(last.concat("\n"));
  1262. } else {
  1263. infoConsoleLines.push(last);
  1264. }
  1265. }
  1266. if (infoConsoleLines.length > MAX_INFO_CONSOLE_LINES) {
  1267. infoConsoleLines.shift(MAX_INFO_CONSOLE_LINES);
  1268. }
  1269. let data = "";
  1270. for (let i = 0; i < infoConsoleLines.length; i++) {
  1271. data = data.concat(infoConsoleLines[i]);
  1272. }
  1273. let info = consoleElement;
  1274. info.innerHTML = data;
  1275. info.scrollTop = info.scrollHeight;
  1276. };
  1277. const listener_key = (id, name, data, callback, useCapture) => {
  1278. return `${id}-${name}-data:${data}-callback:${callback}-useCapture:${useCapture}`;
  1279. };
  1280. let webglContext = new WebGLInterface(wasmMemoryInterface);
  1281. const env = {};
  1282. if (memory) {
  1283. env.memory = memory;
  1284. }
  1285. return {
  1286. env,
  1287. "odin_env": {
  1288. write: (fd, ptr, len) => {
  1289. const str = wasmMemoryInterface.loadString(ptr, len);
  1290. if (fd == 1) {
  1291. writeToConsole(str, false);
  1292. return;
  1293. } else if (fd == 2) {
  1294. writeToConsole(str, true);
  1295. return;
  1296. } else {
  1297. throw new Error("Invalid fd to 'write'" + stripNewline(str));
  1298. }
  1299. },
  1300. trap: () => { throw new Error() },
  1301. alert: (ptr, len) => { alert(wasmMemoryInterface.loadString(ptr, len)) },
  1302. abort: () => { Module.abort() },
  1303. evaluate: (str_ptr, str_len) => { eval.call(null, wasmMemoryInterface.loadString(str_ptr, str_len)); },
  1304. open: (url_ptr, url_len, name_ptr, name_len, specs_ptr, specs_len) => {
  1305. const url = wasmMemoryInterface.loadString(url_ptr, url_len);
  1306. const name = wasmMemoryInterface.loadString(name_ptr, name_len);
  1307. const specs = wasmMemoryInterface.loadString(specs_ptr, specs_len);
  1308. window.open(url, name, specs);
  1309. },
  1310. // return a bigint to be converted to i64
  1311. time_now: () => BigInt(Date.now()),
  1312. tick_now: () => performance.now(),
  1313. time_sleep: (duration_ms) => {
  1314. if (duration_ms > 0) {
  1315. // TODO(bill): Does this even make any sense?
  1316. }
  1317. },
  1318. sqrt: Math.sqrt,
  1319. sin: Math.sin,
  1320. cos: Math.cos,
  1321. pow: Math.pow,
  1322. fmuladd: (x, y, z) => x*y + z,
  1323. ln: Math.log,
  1324. exp: Math.exp,
  1325. ldexp: (x, exp) => x * Math.pow(2, exp),
  1326. rand_bytes: (ptr, len) => {
  1327. const view = new Uint8Array(wasmMemoryInterface.memory.buffer, ptr, len)
  1328. crypto.getRandomValues(view)
  1329. },
  1330. },
  1331. "odin_dom": {
  1332. init_event_raw: (ep) => {
  1333. const W = wasmMemoryInterface.intSize;
  1334. let offset = ep;
  1335. let off = (amount, alignment) => {
  1336. if (alignment === undefined) {
  1337. alignment = Math.min(amount, W);
  1338. }
  1339. if (offset % alignment != 0) {
  1340. offset += alignment - (offset%alignment);
  1341. }
  1342. let x = offset;
  1343. offset += amount;
  1344. return x;
  1345. };
  1346. let align = (alignment) => {
  1347. const modulo = offset & (alignment-1);
  1348. if (modulo != 0) {
  1349. offset += alignment - modulo
  1350. }
  1351. };
  1352. let wmi = wasmMemoryInterface;
  1353. if (!event_temp.data) {
  1354. return;
  1355. }
  1356. let e = event_temp.data.event;
  1357. wmi.storeU32(off(4), event_temp.data.name_code);
  1358. if (e.target == document) {
  1359. wmi.storeU32(off(4), 1);
  1360. } else if (e.target == window) {
  1361. wmi.storeU32(off(4), 2);
  1362. } else {
  1363. wmi.storeU32(off(4), 0);
  1364. }
  1365. if (e.currentTarget == document) {
  1366. wmi.storeU32(off(4), 1);
  1367. } else if (e.currentTarget == window) {
  1368. wmi.storeU32(off(4), 2);
  1369. } else {
  1370. wmi.storeU32(off(4), 0);
  1371. }
  1372. align(W);
  1373. wmi.storeI32(off(W), event_temp.data.id_ptr);
  1374. wmi.storeUint(off(W), event_temp.data.id_len);
  1375. align(8);
  1376. wmi.storeF64(off(8), e.timeStamp*1e-3);
  1377. wmi.storeU8(off(1), e.eventPhase);
  1378. let options = 0;
  1379. if (!!e.bubbles) { options |= 1<<0; }
  1380. if (!!e.cancelable) { options |= 1<<1; }
  1381. if (!!e.composed) { options |= 1<<2; }
  1382. wmi.storeU8(off(1), options);
  1383. wmi.storeU8(off(1), !!e.isComposing);
  1384. wmi.storeU8(off(1), !!e.isTrusted);
  1385. align(8);
  1386. if (e instanceof WheelEvent) {
  1387. wmi.storeF64(off(8), e.deltaX);
  1388. wmi.storeF64(off(8), e.deltaY);
  1389. wmi.storeF64(off(8), e.deltaZ);
  1390. wmi.storeU32(off(4), e.deltaMode);
  1391. } else if (e instanceof MouseEvent) {
  1392. wmi.storeI64(off(8), e.screenX);
  1393. wmi.storeI64(off(8), e.screenY);
  1394. wmi.storeI64(off(8), e.clientX);
  1395. wmi.storeI64(off(8), e.clientY);
  1396. wmi.storeI64(off(8), e.offsetX);
  1397. wmi.storeI64(off(8), e.offsetY);
  1398. wmi.storeI64(off(8), e.pageX);
  1399. wmi.storeI64(off(8), e.pageY);
  1400. wmi.storeI64(off(8), e.movementX);
  1401. wmi.storeI64(off(8), e.movementY);
  1402. wmi.storeU8(off(1), !!e.ctrlKey);
  1403. wmi.storeU8(off(1), !!e.shiftKey);
  1404. wmi.storeU8(off(1), !!e.altKey);
  1405. wmi.storeU8(off(1), !!e.metaKey);
  1406. wmi.storeI16(off(2), e.button);
  1407. wmi.storeU16(off(2), e.buttons);
  1408. if (e instanceof PointerEvent) {
  1409. wmi.storeF64(off(8), e.altitudeAngle);
  1410. wmi.storeF64(off(8), e.azimuthAngle);
  1411. wmi.storeInt(off(W), e.persistentDeviceId);
  1412. wmi.storeInt(off(W), e.pointerId);
  1413. wmi.storeInt(off(W), e.width);
  1414. wmi.storeInt(off(W), e.height);
  1415. wmi.storeF64(off(8), e.pressure);
  1416. wmi.storeF64(off(8), e.tangentialPressure);
  1417. wmi.storeF64(off(8), e.tiltX);
  1418. wmi.storeF64(off(8), e.tiltY);
  1419. wmi.storeF64(off(8), e.twist);
  1420. if (e.pointerType == "pen") {
  1421. wmi.storeU8(off(1), 1);
  1422. } else if (e.pointerType == "touch") {
  1423. wmi.storeU8(off(1), 2);
  1424. } else {
  1425. wmi.storeU8(off(1), 0);
  1426. }
  1427. wmi.storeU8(off(1), !!e.isPrimary);
  1428. }
  1429. } else if (e instanceof KeyboardEvent) {
  1430. // Note: those strings are constructed
  1431. // on the native side from buffers that
  1432. // are filled later, so skip them
  1433. const keyPtr = off(W*2, W);
  1434. const codePtr = off(W*2, W);
  1435. wmi.storeU8(off(1), e.location);
  1436. wmi.storeU8(off(1), !!e.ctrlKey);
  1437. wmi.storeU8(off(1), !!e.shiftKey);
  1438. wmi.storeU8(off(1), !!e.altKey);
  1439. wmi.storeU8(off(1), !!e.metaKey);
  1440. wmi.storeU8(off(1), !!e.repeat);
  1441. wmi.storeI32(off(4), e.charCode);
  1442. wmi.storeInt(off(W, W), e.key.length)
  1443. wmi.storeInt(off(W, W), e.code.length)
  1444. wmi.storeString(off(32, 1), e.key);
  1445. wmi.storeString(off(32, 1), e.code);
  1446. } else if (e.type === 'scroll') {
  1447. wmi.storeF64(off(8, 8), window.scrollX);
  1448. wmi.storeF64(off(8, 8), window.scrollY);
  1449. } else if (e.type === 'visibilitychange') {
  1450. wmi.storeU8(off(1), !document.hidden);
  1451. } else if (e instanceof GamepadEvent) {
  1452. const idPtr = off(W*2, W);
  1453. const mappingPtr = off(W*2, W);
  1454. wmi.storeI32(off(W, W), e.gamepad.index);
  1455. wmi.storeU8(off(1), !!e.gamepad.connected);
  1456. wmi.storeF64(off(8, 8), e.gamepad.timestamp);
  1457. wmi.storeInt(off(W, W), e.gamepad.buttons.length);
  1458. wmi.storeInt(off(W, W), e.gamepad.axes.length);
  1459. for (let i = 0; i < 64; i++) {
  1460. if (i < e.gamepad.buttons.length) {
  1461. let b = e.gamepad.buttons[i];
  1462. wmi.storeF64(off(8, 8), b.value);
  1463. wmi.storeU8(off(1), !!b.pressed);
  1464. wmi.storeU8(off(1), !!b.touched);
  1465. } else {
  1466. off(16, 8);
  1467. }
  1468. }
  1469. for (let i = 0; i < 16; i++) {
  1470. if (i < e.gamepad.axes.length) {
  1471. let a = e.gamepad.axes[i];
  1472. wmi.storeF64(off(8, 8), a);
  1473. } else {
  1474. off(8, 8);
  1475. }
  1476. }
  1477. let idLength = e.gamepad.id.length;
  1478. let id = e.gamepad.id;
  1479. if (idLength > 96) {
  1480. idLength = 96;
  1481. id = id.slice(0, 93) + '...';
  1482. }
  1483. let mappingLength = e.gamepad.mapping.length;
  1484. let mapping = e.gamepad.mapping;
  1485. if (mappingLength > 64) {
  1486. mappingLength = 61;
  1487. mapping = mapping.slice(0, 61) + '...';
  1488. }
  1489. wmi.storeInt(off(W, W), idLength);
  1490. wmi.storeInt(off(W, W), mappingLength);
  1491. wmi.storeString(off(96, 1), id);
  1492. wmi.storeString(off(64, 1), mapping);
  1493. }
  1494. },
  1495. add_event_listener: (id_ptr, id_len, name_ptr, name_len, name_code, data, callback, use_capture) => {
  1496. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1497. let name = wasmMemoryInterface.loadString(name_ptr, name_len);
  1498. let element = getElement(id);
  1499. if (element == undefined) {
  1500. return false;
  1501. }
  1502. let key = listener_key(id, name, data, callback, !!use_capture);
  1503. if (wasmMemoryInterface.listenerMap.has(key)) {
  1504. return false;
  1505. }
  1506. let listener = (e) => {
  1507. let event_data = {};
  1508. event_data.id_ptr = id_ptr;
  1509. event_data.id_len = id_len;
  1510. event_data.event = e;
  1511. event_data.name_code = name_code;
  1512. onEventReceived(event_data, data, callback);
  1513. };
  1514. wasmMemoryInterface.listenerMap.set(key, listener);
  1515. element.addEventListener(name, listener, !!use_capture);
  1516. return true;
  1517. },
  1518. add_window_event_listener: (name_ptr, name_len, name_code, data, callback, use_capture) => {
  1519. let name = wasmMemoryInterface.loadString(name_ptr, name_len);
  1520. let element = window;
  1521. let key = listener_key('window', name, data, callback, !!use_capture);
  1522. if (wasmMemoryInterface.listenerMap.has(key)) {
  1523. return false;
  1524. }
  1525. let listener = (e) => {
  1526. let event_data = {};
  1527. event_data.id_ptr = 0;
  1528. event_data.id_len = 0;
  1529. event_data.event = e;
  1530. event_data.name_code = name_code;
  1531. onEventReceived(event_data, data, callback);
  1532. };
  1533. wasmMemoryInterface.listenerMap.set(key, listener);
  1534. element.addEventListener(name, listener, !!use_capture);
  1535. return true;
  1536. },
  1537. remove_event_listener: (id_ptr, id_len, name_ptr, name_len, data, callback, use_capture) => {
  1538. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1539. let name = wasmMemoryInterface.loadString(name_ptr, name_len);
  1540. let element = getElement(id);
  1541. if (element == undefined) {
  1542. return false;
  1543. }
  1544. let key = listener_key(id, name, data, callback, !!use_capture);
  1545. let listener = wasmMemoryInterface.listenerMap.get(key);
  1546. if (listener === undefined) {
  1547. return false;
  1548. }
  1549. wasmMemoryInterface.listenerMap.delete(key);
  1550. element.removeEventListener(name, listener, !!use_capture);
  1551. return true;
  1552. },
  1553. remove_window_event_listener: (name_ptr, name_len, data, callback, use_capture) => {
  1554. let name = wasmMemoryInterface.loadString(name_ptr, name_len);
  1555. let element = window;
  1556. let key = listener_key('window', name, data, callback, !!use_capture);
  1557. let listener = wasmMemoryInterface.listenerMap.get(key);
  1558. if (listener === undefined) {
  1559. return false;
  1560. }
  1561. wasmMemoryInterface.listenerMap.delete(key);
  1562. element.removeEventListener(name, listener, !!use_capture);
  1563. return true;
  1564. },
  1565. event_stop_propagation: () => {
  1566. if (event_temp.data && event_temp.data.event) {
  1567. event_temp.data.event.stopPropagation();
  1568. }
  1569. },
  1570. event_stop_immediate_propagation: () => {
  1571. if (event_temp.data && event_temp.data.event) {
  1572. event_temp.data.event.stopImmediatePropagation();
  1573. }
  1574. },
  1575. event_prevent_default: () => {
  1576. if (event_temp.data && event_temp.data.event) {
  1577. event_temp.data.event.preventDefault();
  1578. }
  1579. },
  1580. dispatch_custom_event: (id_ptr, id_len, name_ptr, name_len, options_bits) => {
  1581. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1582. let name = wasmMemoryInterface.loadString(name_ptr, name_len);
  1583. let options = {
  1584. bubbles: (options_bits & (1<<0)) !== 0,
  1585. cancelable: (options_bits & (1<<1)) !== 0,
  1586. composed: (options_bits & (1<<2)) !== 0,
  1587. };
  1588. let element = getElement(id);
  1589. if (element) {
  1590. element.dispatchEvent(new Event(name, options));
  1591. return true;
  1592. }
  1593. return false;
  1594. },
  1595. get_gamepad_state: (gamepad_id, ep) => {
  1596. let index = gamepad_id;
  1597. let gps = navigator.getGamepads();
  1598. if (0 <= index && index < gps.length) {
  1599. let gamepad = gps[index];
  1600. if (!gamepad) {
  1601. return false;
  1602. }
  1603. const W = wasmMemoryInterface.intSize;
  1604. let offset = ep;
  1605. let off = (amount, alignment) => {
  1606. if (alignment === undefined) {
  1607. alignment = Math.min(amount, W);
  1608. }
  1609. if (offset % alignment != 0) {
  1610. offset += alignment - (offset%alignment);
  1611. }
  1612. let x = offset;
  1613. offset += amount;
  1614. return x;
  1615. };
  1616. let align = (alignment) => {
  1617. const modulo = offset & (alignment-1);
  1618. if (modulo != 0) {
  1619. offset += alignment - modulo
  1620. }
  1621. };
  1622. let wmi = wasmMemoryInterface;
  1623. const idPtr = off(W*2, W);
  1624. const mappingPtr = off(W*2, W);
  1625. wmi.storeI32(off(W), gamepad.index);
  1626. wmi.storeU8(off(1), !!gamepad.connected);
  1627. wmi.storeF64(off(8), gamepad.timestamp);
  1628. wmi.storeInt(off(W), gamepad.buttons.length);
  1629. wmi.storeInt(off(W), gamepad.axes.length);
  1630. for (let i = 0; i < 64; i++) {
  1631. if (i < gamepad.buttons.length) {
  1632. let b = gamepad.buttons[i];
  1633. wmi.storeF64(off(8, 8), b.value);
  1634. wmi.storeU8(off(1), !!b.pressed);
  1635. wmi.storeU8(off(1), !!b.touched);
  1636. } else {
  1637. off(16, 8);
  1638. }
  1639. }
  1640. for (let i = 0; i < 16; i++) {
  1641. if (i < gamepad.axes.length) {
  1642. wmi.storeF64(off(8, 8), gamepad.axes[i]);
  1643. } else {
  1644. off(8, 8);
  1645. }
  1646. }
  1647. let idLength = gamepad.id.length;
  1648. let id = gamepad.id;
  1649. if (idLength > 96) {
  1650. idLength = 96;
  1651. id = id.slice(0, 93) + '...';
  1652. }
  1653. let mappingLength = gamepad.mapping.length;
  1654. let mapping = gamepad.mapping;
  1655. if (mappingLength > 64) {
  1656. mappingLength = 61;
  1657. mapping = mapping.slice(0, 61) + '...';
  1658. }
  1659. wmi.storeInt(off(W, W), idLength);
  1660. wmi.storeInt(off(W, W), mappingLength);
  1661. wmi.storeString(off(96, 1), id);
  1662. wmi.storeString(off(64, 1), mapping);
  1663. return true;
  1664. }
  1665. return false;
  1666. },
  1667. get_element_value_f64: (id_ptr, id_len) => {
  1668. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1669. let element = getElement(id);
  1670. return element ? element.value : 0;
  1671. },
  1672. get_element_value_string: (id_ptr, id_len, buf_ptr, buf_len) => {
  1673. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1674. let element = getElement(id);
  1675. if (element) {
  1676. let str = element.value;
  1677. if (buf_len > 0 && buf_ptr) {
  1678. let n = Math.min(buf_len, str.length);
  1679. str = str.substring(0, n);
  1680. this.mem.loadBytes(buf_ptr, buf_len).set(new TextEncoder().encode(str))
  1681. return n;
  1682. }
  1683. }
  1684. return 0;
  1685. },
  1686. get_element_value_string_length: (id_ptr, id_len) => {
  1687. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1688. let element = getElement(id);
  1689. if (element) {
  1690. return element.value.length;
  1691. }
  1692. return 0;
  1693. },
  1694. get_element_min_max: (ptr_array2_f64, id_ptr, id_len) => {
  1695. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1696. let element = getElement(id);
  1697. if (element) {
  1698. let values = wasmMemoryInterface.loadF64Array(ptr_array2_f64, 2);
  1699. values[0] = element.min;
  1700. values[1] = element.max;
  1701. }
  1702. },
  1703. set_element_value_f64: (id_ptr, id_len, value) => {
  1704. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1705. let element = getElement(id);
  1706. if (element) {
  1707. element.value = value;
  1708. }
  1709. },
  1710. set_element_value_string: (id_ptr, id_len, value_ptr, value_len) => {
  1711. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1712. let value = wasmMemoryInterface.loadString(value_ptr, value_len);
  1713. let element = getElement(id);
  1714. if (element) {
  1715. element.value = value;
  1716. }
  1717. },
  1718. set_element_style: (id_ptr, id_len, key_ptr, key_len, value_ptr, value_len) => {
  1719. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1720. let key = wasmMemoryInterface.loadString(key_ptr, key_len);
  1721. let value = wasmMemoryInterface.loadString(value_ptr, value_len);
  1722. let element = getElement(id);
  1723. if (element) {
  1724. element.style[key] = value;
  1725. }
  1726. },
  1727. get_element_key_f64: (id_ptr, id_len, key_ptr, key_len) => {
  1728. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1729. let key = wasmMemoryInterface.loadString(key_ptr, key_len);
  1730. let element = getElement(id);
  1731. return element ? element[key] : 0;
  1732. },
  1733. get_element_key_string: (id_ptr, id_len, key_ptr, key_len, buf_ptr, buf_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) {
  1738. let str = element[key];
  1739. if (buf_len > 0 && buf_ptr) {
  1740. let n = Math.min(buf_len, str.length);
  1741. str = str.substring(0, n);
  1742. this.mem.loadBytes(buf_ptr, buf_len).set(new TextEncoder().encode(str))
  1743. return n;
  1744. }
  1745. }
  1746. return 0;
  1747. },
  1748. get_element_key_string_length: (id_ptr, id_len, key_ptr, key_len) => {
  1749. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1750. let key = wasmMemoryInterface.loadString(key_ptr, key_len);
  1751. let element = getElement(id);
  1752. if (element && element[key]) {
  1753. return element[key].length;
  1754. }
  1755. return 0;
  1756. },
  1757. set_element_key_f64: (id_ptr, id_len, key_ptr, key_len, value) => {
  1758. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1759. let key = wasmMemoryInterface.loadString(key_ptr, key_len);
  1760. let element = getElement(id);
  1761. if (element) {
  1762. element[key] = value;
  1763. }
  1764. },
  1765. set_element_key_string: (id_ptr, id_len, key_ptr, key_len, value_ptr, value_len) => {
  1766. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1767. let key = wasmMemoryInterface.loadString(key_ptr, key_len);
  1768. let value = wasmMemoryInterface.loadString(value_ptr, value_len);
  1769. let element = getElement(id);
  1770. if (element) {
  1771. element[key] = value;
  1772. }
  1773. },
  1774. get_bounding_client_rect: (rect_ptr, id_ptr, id_len) => {
  1775. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1776. let element = getElement(id);
  1777. if (element) {
  1778. let values = wasmMemoryInterface.loadF64Array(rect_ptr, 4);
  1779. let rect = element.getBoundingClientRect();
  1780. values[0] = rect.left;
  1781. values[1] = rect.top;
  1782. values[2] = rect.right - rect.left;
  1783. values[3] = rect.bottom - rect.top;
  1784. }
  1785. },
  1786. window_get_rect: (rect_ptr) => {
  1787. let values = wasmMemoryInterface.loadF64Array(rect_ptr, 4);
  1788. values[0] = window.screenX;
  1789. values[1] = window.screenY;
  1790. values[2] = window.screen.width;
  1791. values[3] = window.screen.height;
  1792. },
  1793. window_get_scroll: (pos_ptr) => {
  1794. let values = wasmMemoryInterface.loadF64Array(pos_ptr, 2);
  1795. values[0] = window.scrollX;
  1796. values[1] = window.scrollY;
  1797. },
  1798. window_set_scroll: (x, y) => {
  1799. window.scroll(x, y);
  1800. },
  1801. device_pixel_ratio: () => {
  1802. return window.devicePixelRatio;
  1803. },
  1804. },
  1805. "webgl": webglContext.getWebGL1Interface(),
  1806. "webgl2": webglContext.getWebGL2Interface(),
  1807. };
  1808. };
  1809. /**
  1810. * @param {string} wasmPath - Path to the WASM module to run
  1811. * @param {?HTMLPreElement} consoleElement - Optional console/pre element to append output to, in addition to the console
  1812. * @param {any} extraForeignImports - Imports, in addition to the default runtime to provide the module
  1813. * @param {?WasmMemoryInterface} wasmMemoryInterface - Optional memory to use instead of the defaults
  1814. * @param {?int} intSize - Size (in bytes) of the integer type, should be 4 on `js_wasm32` and 8 on `js_wasm64p32`
  1815. */
  1816. async function runWasm(wasmPath, consoleElement, extraForeignImports, wasmMemoryInterface, intSize = 4) {
  1817. if (!wasmMemoryInterface) {
  1818. wasmMemoryInterface = new WasmMemoryInterface();
  1819. }
  1820. wasmMemoryInterface.setIntSize(intSize);
  1821. let imports = odinSetupDefaultImports(wasmMemoryInterface, consoleElement, wasmMemoryInterface.memory);
  1822. let exports = {};
  1823. if (extraForeignImports !== undefined) {
  1824. imports = {
  1825. ...imports,
  1826. ...extraForeignImports,
  1827. };
  1828. }
  1829. const response = await fetch(wasmPath);
  1830. const file = await response.arrayBuffer();
  1831. const wasm = await WebAssembly.instantiate(file, imports);
  1832. exports = wasm.instance.exports;
  1833. wasmMemoryInterface.setExports(exports);
  1834. if (exports.memory) {
  1835. if (wasmMemoryInterface.memory) {
  1836. console.warn("WASM module exports memory, but `runWasm` was given an interface with existing memory too");
  1837. }
  1838. wasmMemoryInterface.setMemory(exports.memory);
  1839. }
  1840. exports._start();
  1841. // Define a `@export step :: proc(delta_time: f64) -> (keep_going: bool) {`
  1842. // in your app and it will get called every frame.
  1843. // return `false` to stop the execution of the module.
  1844. if (exports.step) {
  1845. const odin_ctx = exports.default_context_ptr();
  1846. let prevTimeStamp = undefined;
  1847. function step(currTimeStamp) {
  1848. if (prevTimeStamp == undefined) {
  1849. prevTimeStamp = currTimeStamp;
  1850. }
  1851. const dt = (currTimeStamp - prevTimeStamp)*0.001;
  1852. prevTimeStamp = currTimeStamp;
  1853. if (!exports.step(dt, odin_ctx)) {
  1854. exports._end();
  1855. return;
  1856. }
  1857. window.requestAnimationFrame(step);
  1858. }
  1859. window.requestAnimationFrame(step);
  1860. } else {
  1861. exports._end();
  1862. }
  1863. return;
  1864. };
  1865. window.odin = {
  1866. // Interface Types
  1867. WasmMemoryInterface: WasmMemoryInterface,
  1868. WebGLInterface: WebGLInterface,
  1869. // Functions
  1870. setupDefaultImports: odinSetupDefaultImports,
  1871. runWasm: runWasm,
  1872. };
  1873. })();