odin.js 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157
  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. if (ptr == 0) {
  97. return null;
  98. }
  99. let len = 0;
  100. for (; this.mem.getUint8(ptr+len) != 0; len += 1) {}
  101. return this.loadString(ptr, len);
  102. }
  103. storeU8(addr, value) { this.mem.setUint8 (addr, value); }
  104. storeI8(addr, value) { this.mem.setInt8 (addr, value); }
  105. storeU16(addr, value) { this.mem.setUint16 (addr, value, true); }
  106. storeI16(addr, value) { this.mem.setInt16 (addr, value, true); }
  107. storeU32(addr, value) { this.mem.setUint32 (addr, value, true); }
  108. storeI32(addr, value) { this.mem.setInt32 (addr, value, true); }
  109. storeU64(addr, value) {
  110. this.mem.setUint32(addr + 0, Number(value), true);
  111. let div = 4294967296;
  112. if (typeof value == 'bigint') {
  113. div = BigInt(div);
  114. }
  115. this.mem.setUint32(addr + 4, Math.floor(Number(value / div)), true);
  116. }
  117. storeI64(addr, value) {
  118. this.mem.setUint32(addr + 0, Number(value), true);
  119. let div = 4294967296;
  120. if (typeof value == 'bigint') {
  121. div = BigInt(div);
  122. }
  123. this.mem.setInt32(addr + 4, Math.floor(Number(value / div)), true);
  124. }
  125. storeF32(addr, value) { this.mem.setFloat32(addr, value, true); }
  126. storeF64(addr, value) { this.mem.setFloat64(addr, value, true); }
  127. storeInt(addr, value) {
  128. if (this.intSize == 8) {
  129. this.storeI64(addr, value);
  130. } else if (this.intSize == 4) {
  131. this.storeI32(addr, value);
  132. } else {
  133. throw new Error('Unhandled `intSize`, expected `4` or `8`');
  134. }
  135. }
  136. storeUint(addr, value) {
  137. if (this.intSize == 8) {
  138. this.storeU64(addr, value);
  139. } else if (this.intSize == 4) {
  140. this.storeU32(addr, value);
  141. } else {
  142. throw new Error('Unhandled `intSize`, expected `4` or `8`');
  143. }
  144. }
  145. // Returned length might not be the same as `value.length` if non-ascii strings are given.
  146. storeString(addr, value) {
  147. const src = new TextEncoder().encode(value);
  148. const dst = new Uint8Array(this.memory.buffer, addr, src.length);
  149. dst.set(src);
  150. return src.length;
  151. }
  152. };
  153. class WebGLInterface {
  154. constructor(wasmMemoryInterface) {
  155. this.wasmMemoryInterface = wasmMemoryInterface;
  156. this.ctxElement = null;
  157. this.ctx = null;
  158. this.ctxVersion = 1.0;
  159. this.counter = 1;
  160. this.lastError = 0;
  161. this.buffers = [];
  162. this.mappedBuffers = {};
  163. this.programs = [];
  164. this.framebuffers = [];
  165. this.renderbuffers = [];
  166. this.textures = [];
  167. this.uniforms = [];
  168. this.shaders = [];
  169. this.vaos = [];
  170. this.contexts = [];
  171. this.currentContext = null;
  172. this.offscreenCanvases = {};
  173. this.timerQueriesEXT = [];
  174. this.queries = [];
  175. this.samplers = [];
  176. this.transformFeedbacks = [];
  177. this.syncs = [];
  178. this.programInfos = {};
  179. }
  180. get mem() {
  181. return this.wasmMemoryInterface
  182. }
  183. setCurrentContext(element, contextSettings) {
  184. if (!element) {
  185. return false;
  186. }
  187. if (this.ctxElement == element) {
  188. return true;
  189. }
  190. contextSettings = contextSettings ?? {};
  191. this.ctx = element.getContext("webgl2", contextSettings) || element.getContext("webgl", contextSettings);
  192. if (!this.ctx) {
  193. return false;
  194. }
  195. this.ctxElement = element;
  196. if (this.ctx.getParameter(0x1F02).indexOf("WebGL 2.0") !== -1) {
  197. this.ctxVersion = 2.0;
  198. } else {
  199. this.ctxVersion = 1.0;
  200. }
  201. return true;
  202. }
  203. assertWebGL2() {
  204. if (this.ctxVersion < 2) {
  205. throw new Error("WebGL2 procedure called in a canvas without a WebGL2 context");
  206. }
  207. }
  208. getNewId(table) {
  209. for (var ret = this.counter++, i = table.length; i < ret; i++) {
  210. table[i] = null;
  211. }
  212. return ret;
  213. }
  214. recordError(errorCode) {
  215. this.lastError || (this.lastError = errorCode);
  216. }
  217. populateUniformTable(program) {
  218. let p = this.programs[program];
  219. this.programInfos[program] = {
  220. uniforms: {},
  221. maxUniformLength: 0,
  222. maxAttributeLength: -1,
  223. maxUniformBlockNameLength: -1,
  224. };
  225. for (let ptable = this.programInfos[program], utable = ptable.uniforms, numUniforms = this.ctx.getProgramParameter(p, this.ctx.ACTIVE_UNIFORMS), i = 0; i < numUniforms; ++i) {
  226. let u = this.ctx.getActiveUniform(p, i);
  227. let name = u.name;
  228. if (ptable.maxUniformLength = Math.max(ptable.maxUniformLength, name.length + 1), name.indexOf("]", name.length - 1) !== -1) {
  229. name = name.slice(0, name.lastIndexOf("["));
  230. }
  231. let loc = this.ctx.getUniformLocation(p, name);
  232. if (loc !== null) {
  233. let id = this.getNewId(this.uniforms);
  234. utable[name] = [u.size, id], this.uniforms[id] = loc;
  235. for (let j = 1; j < u.size; ++j) {
  236. let n = name + "[" + j + "]";
  237. let loc = this.ctx.getUniformLocation(p, n);
  238. let id = this.getNewId(this.uniforms);
  239. this.uniforms[id] = loc;
  240. }
  241. }
  242. }
  243. }
  244. getSource(shader, strings_ptr, strings_length) {
  245. const stringSize = this.mem.intSize*2;
  246. let source = "";
  247. for (let i = 0; i < strings_length; i++) {
  248. let ptr = this.mem.loadPtr(strings_ptr + i*stringSize);
  249. let len = this.mem.loadPtr(strings_ptr + i*stringSize + 4);
  250. let str = this.mem.loadString(ptr, len);
  251. source += str;
  252. }
  253. return source;
  254. }
  255. getWebGL1Interface() {
  256. return {
  257. SetCurrentContextById: (name_ptr, name_len) => {
  258. let name = this.mem.loadString(name_ptr, name_len);
  259. let element = getElement(name);
  260. return this.setCurrentContext(element, {alpha: true, antialias: true, depth: true, premultipliedAlpha: true});
  261. },
  262. CreateCurrentContextById: (name_ptr, name_len, attributes) => {
  263. let name = this.mem.loadString(name_ptr, name_len);
  264. let element = getElement(name);
  265. let contextSettings = {
  266. alpha: !(attributes & (1<<0)),
  267. antialias: !(attributes & (1<<1)),
  268. depth: !(attributes & (1<<2)),
  269. failIfMajorPerformanceCaveat: !!(attributes & (1<<3)),
  270. premultipliedAlpha: !(attributes & (1<<4)),
  271. preserveDrawingBuffer: !!(attributes & (1<<5)),
  272. stencil: !!(attributes & (1<<6)),
  273. desynchronized: !!(attributes & (1<<7)),
  274. };
  275. return this.setCurrentContext(element, contextSettings);
  276. },
  277. GetCurrentContextAttributes: () => {
  278. if (!this.ctx) {
  279. return 0;
  280. }
  281. let attrs = this.ctx.getContextAttributes();
  282. let res = 0;
  283. if (!attrs.alpha) res |= 1<<0;
  284. if (!attrs.antialias) res |= 1<<1;
  285. if (!attrs.depth) res |= 1<<2;
  286. if (attrs.failIfMajorPerformanceCaveat) res |= 1<<3;
  287. if (!attrs.premultipliedAlpha) res |= 1<<4;
  288. if (attrs.preserveDrawingBuffer) res |= 1<<5;
  289. if (attrs.stencil) res |= 1<<6;
  290. if (attrs.desynchronized) res |= 1<<7;
  291. return res;
  292. },
  293. DrawingBufferWidth: () => this.ctx.drawingBufferWidth,
  294. DrawingBufferHeight: () => this.ctx.drawingBufferHeight,
  295. IsExtensionSupported: (name_ptr, name_len) => {
  296. let name = this.mem.loadString(name_ptr, name_len);
  297. let extensions = this.ctx.getSupportedExtensions();
  298. return extensions.indexOf(name) !== -1
  299. },
  300. GetError: () => {
  301. let err = this.lastError;
  302. this.recordError(0);
  303. if (err) {
  304. return err;
  305. }
  306. return this.ctx.getError();
  307. },
  308. GetWebGLVersion: (major_ptr, minor_ptr) => {
  309. let version = this.ctx.getParameter(0x1F02);
  310. if (version.indexOf("WebGL 2.0") !== -1) {
  311. this.mem.storeI32(major_ptr, 2);
  312. this.mem.storeI32(minor_ptr, 0);
  313. return;
  314. }
  315. this.mem.storeI32(major_ptr, 1);
  316. this.mem.storeI32(minor_ptr, 0);
  317. },
  318. GetESVersion: (major_ptr, minor_ptr) => {
  319. let version = this.ctx.getParameter(0x1F02);
  320. if (version.indexOf("OpenGL ES 3.0") !== -1) {
  321. this.mem.storeI32(major_ptr, 3);
  322. this.mem.storeI32(minor_ptr, 0);
  323. return;
  324. }
  325. this.mem.storeI32(major_ptr, 2);
  326. this.mem.storeI32(minor_ptr, 0);
  327. },
  328. ActiveTexture: (x) => {
  329. this.ctx.activeTexture(x);
  330. },
  331. AttachShader: (program, shader) => {
  332. this.ctx.attachShader(this.programs[program], this.shaders[shader]);
  333. },
  334. BindAttribLocation: (program, index, name_ptr, name_len) => {
  335. let name = this.mem.loadString(name_ptr, name_len);
  336. this.ctx.bindAttribLocation(this.programs[program], index, name)
  337. },
  338. BindBuffer: (target, buffer) => {
  339. let bufferObj = buffer ? this.buffers[buffer] : null;
  340. if (target == 35051) {
  341. this.ctx.currentPixelPackBufferBinding = buffer;
  342. } else {
  343. if (target == 35052) {
  344. this.ctx.currentPixelUnpackBufferBinding = buffer;
  345. }
  346. this.ctx.bindBuffer(target, bufferObj)
  347. }
  348. },
  349. BindFramebuffer: (target, framebuffer) => {
  350. this.ctx.bindFramebuffer(target, framebuffer ? this.framebuffers[framebuffer] : null)
  351. },
  352. BindTexture: (target, texture) => {
  353. this.ctx.bindTexture(target, texture ? this.textures[texture] : null)
  354. },
  355. BindRenderbuffer: (target, renderbuffer) => {
  356. this.ctx.bindRenderbuffer(target, renderbuffer ? this.renderbuffers[renderbuffer] : 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. Uniform1fv: (location, count, addr) => {
  733. let array = this.mem.loadF32Array(addr, 1*count);
  734. this.ctx.uniform1fv(this.uniforms[location], array);
  735. },
  736. Uniform2fv: (location, count, addr) => {
  737. let array = this.mem.loadF32Array(addr, 2*count);
  738. this.ctx.uniform2fv(this.uniforms[location], array);
  739. },
  740. Uniform3fv: (location, count, addr) => {
  741. let array = this.mem.loadF32Array(addr, 3*count);
  742. this.ctx.uniform3fv(this.uniforms[location], array);
  743. },
  744. Uniform4fv: (location, count, addr) => {
  745. let array = this.mem.loadF32Array(addr, 4*count);
  746. this.ctx.uniform4fv(this.uniforms[location], array);
  747. },
  748. Uniform1iv: (location, count, addr) => {
  749. let array = this.mem.loadI32Array(addr, 1*count);
  750. this.ctx.uniform1iv(this.uniforms[location], array);
  751. },
  752. Uniform2iv: (location, count, addr) => {
  753. let array = this.mem.loadI32Array(addr, 2*count);
  754. this.ctx.uniform2iv(this.uniforms[location], array);
  755. },
  756. Uniform3iv: (location, count, addr) => {
  757. let array = this.mem.loadI32Array(addr, 3*count);
  758. this.ctx.uniform3iv(this.uniforms[location], array);
  759. },
  760. Uniform4iv: (location, count, addr) => {
  761. let array = this.mem.loadI32Array(addr, 4*count);
  762. this.ctx.uniform4iv(this.uniforms[location], array);
  763. },
  764. UniformMatrix2fv: (location, addr) => {
  765. let array = this.mem.loadF32Array(addr, 2*2);
  766. this.ctx.uniformMatrix2fv(this.uniforms[location], false, array);
  767. },
  768. UniformMatrix3fv: (location, addr) => {
  769. let array = this.mem.loadF32Array(addr, 3*3);
  770. this.ctx.uniformMatrix3fv(this.uniforms[location], false, array);
  771. },
  772. UniformMatrix4fv: (location, addr) => {
  773. let array = this.mem.loadF32Array(addr, 4*4);
  774. this.ctx.uniformMatrix4fv(this.uniforms[location], false, array);
  775. },
  776. UseProgram: (program) => {
  777. if (program) this.ctx.useProgram(this.programs[program]);
  778. },
  779. ValidateProgram: (program) => {
  780. if (program) this.ctx.validateProgram(this.programs[program]);
  781. },
  782. VertexAttrib1f: (index, x) => {
  783. this.ctx.vertexAttrib1f(index, x);
  784. },
  785. VertexAttrib2f: (index, x, y) => {
  786. this.ctx.vertexAttrib2f(index, x, y);
  787. },
  788. VertexAttrib3f: (index, x, y, z) => {
  789. this.ctx.vertexAttrib3f(index, x, y, z);
  790. },
  791. VertexAttrib4f: (index, x, y, z, w) => {
  792. this.ctx.vertexAttrib4f(index, x, y, z, w);
  793. },
  794. VertexAttribPointer: (index, size, type, normalized, stride, ptr) => {
  795. this.ctx.vertexAttribPointer(index, size, type, !!normalized, stride, ptr);
  796. },
  797. Viewport: (x, y, w, h) => {
  798. this.ctx.viewport(x, y, w, h);
  799. },
  800. };
  801. }
  802. getWebGL2Interface() {
  803. return {
  804. /* Buffer objects */
  805. CopyBufferSubData: (readTarget, writeTarget, readOffset, writeOffset, size) => {
  806. this.assertWebGL2();
  807. this.ctx.copyBufferSubData(readTarget, writeTarget, readOffset, writeOffset, size);
  808. },
  809. GetBufferSubData: (target, srcByteOffset, dst_buffer_ptr, dst_buffer_len, dstOffset, length) => {
  810. this.assertWebGL2();
  811. this.ctx.getBufferSubData(target, srcByteOffset, this.mem.loadBytes(dst_buffer_ptr, dst_buffer_len), dstOffset, length);
  812. },
  813. /* Framebuffer objects */
  814. BlitFramebuffer: (srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter) => {
  815. this.assertWebGL2();
  816. this.ctx.blitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter);
  817. },
  818. FramebufferTextureLayer: (target, attachment, texture, level, layer) => {
  819. this.assertWebGL2();
  820. this.ctx.framebufferTextureLayer(target, attachment, this.textures[texture], level, layer);
  821. },
  822. InvalidateFramebuffer: (target, attachments_ptr, attachments_len) => {
  823. this.assertWebGL2();
  824. let attachments = this.mem.loadU32Array(attachments_ptr, attachments_len);
  825. this.ctx.invalidateFramebuffer(target, attachments);
  826. },
  827. InvalidateSubFramebuffer: (target, attachments_ptr, attachments_len, x, y, width, height) => {
  828. this.assertWebGL2();
  829. let attachments = this.mem.loadU32Array(attachments_ptr, attachments_len);
  830. this.ctx.invalidateSubFramebuffer(target, attachments, x, y, width, height);
  831. },
  832. ReadBuffer: (src) => {
  833. this.assertWebGL2();
  834. this.ctx.readBuffer(src);
  835. },
  836. /* Renderbuffer objects */
  837. RenderbufferStorageMultisample: (target, samples, internalformat, width, height) => {
  838. this.assertWebGL2();
  839. this.ctx.renderbufferStorageMultisample(target, samples, internalformat, width, height);
  840. },
  841. /* Texture objects */
  842. TexStorage3D: (target, levels, internalformat, width, height, depth) => {
  843. this.assertWebGL2();
  844. this.ctx.texStorage3D(target, levels, internalformat, width, height, depth);
  845. },
  846. TexImage3D: (target, level, internalformat, width, height, depth, border, format, type, size, data) => {
  847. this.assertWebGL2();
  848. if (data) {
  849. this.ctx.texImage3D(target, level, internalformat, width, height, depth, border, format, type, this.mem.loadBytes(data, size));
  850. } else {
  851. this.ctx.texImage3D(target, level, internalformat, width, height, depth, border, format, type, null);
  852. }
  853. },
  854. TexSubImage3D: (target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, size, data) => {
  855. this.assertWebGL2();
  856. this.ctx.texSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, this.mem.loadBytes(data, size));
  857. },
  858. CompressedTexImage3D: (target, level, internalformat, width, height, depth, border, imageSize, data) => {
  859. this.assertWebGL2();
  860. if (data) {
  861. this.ctx.compressedTexImage3D(target, level, internalformat, width, height, depth, border, this.mem.loadBytes(data, imageSize));
  862. } else {
  863. this.ctx.compressedTexImage3D(target, level, internalformat, width, height, depth, border, null);
  864. }
  865. },
  866. CompressedTexSubImage3D: (target, level, xoffset, yoffset, zoffset, width, height, depth, format, imageSize, data) => {
  867. this.assertWebGL2();
  868. if (data) {
  869. this.ctx.compressedTexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, this.mem.loadBytes(data, imageSize));
  870. } else {
  871. this.ctx.compressedTexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, null);
  872. }
  873. },
  874. CopyTexSubImage3D: (target, level, xoffset, yoffset, zoffset, x, y, width, height) => {
  875. this.assertWebGL2();
  876. this.ctx.copyTexSubImage3D(target, level, xoffset, yoffset, zoffset, x, y, width, height);
  877. },
  878. /* Programs and shaders */
  879. GetFragDataLocation: (program, name_ptr, name_len) => {
  880. this.assertWebGL2();
  881. return this.ctx.getFragDataLocation(this.programs[program], this.mem.loadString(name_ptr, name_len));
  882. },
  883. /* Uniforms */
  884. Uniform1ui: (location, v0) => {
  885. this.assertWebGL2();
  886. this.ctx.uniform1ui(this.uniforms[location], v0);
  887. },
  888. Uniform2ui: (location, v0, v1) => {
  889. this.assertWebGL2();
  890. this.ctx.uniform2ui(this.uniforms[location], v0, v1);
  891. },
  892. Uniform3ui: (location, v0, v1, v2) => {
  893. this.assertWebGL2();
  894. this.ctx.uniform3ui(this.uniforms[location], v0, v1, v2);
  895. },
  896. Uniform4ui: (location, v0, v1, v2, v3) => {
  897. this.assertWebGL2();
  898. this.ctx.uniform4ui(this.uniforms[location], v0, v1, v2, v3);
  899. },
  900. UniformMatrix3x2fv: (location, addr) => {
  901. this.assertWebGL2();
  902. let array = this.mem.loadF32Array(addr, 3*2);
  903. this.ctx.uniformMatrix3x2fv(this.uniforms[location], false, array);
  904. },
  905. UniformMatrix4x2fv: (location, addr) => {
  906. this.assertWebGL2();
  907. let array = this.mem.loadF32Array(addr, 4*2);
  908. this.ctx.uniformMatrix4x2fv(this.uniforms[location], false, array);
  909. },
  910. UniformMatrix2x3fv: (location, addr) => {
  911. this.assertWebGL2();
  912. let array = this.mem.loadF32Array(addr, 2*3);
  913. this.ctx.uniformMatrix2x3fv(this.uniforms[location], false, array);
  914. },
  915. UniformMatrix4x3fv: (location, addr) => {
  916. this.assertWebGL2();
  917. let array = this.mem.loadF32Array(addr, 4*3);
  918. this.ctx.uniformMatrix4x3fv(this.uniforms[location], false, array);
  919. },
  920. UniformMatrix2x4fv: (location, addr) => {
  921. this.assertWebGL2();
  922. let array = this.mem.loadF32Array(addr, 2*4);
  923. this.ctx.uniformMatrix2x4fv(this.uniforms[location], false, array);
  924. },
  925. UniformMatrix3x4fv: (location, addr) => {
  926. this.assertWebGL2();
  927. let array = this.mem.loadF32Array(addr, 3*4);
  928. this.ctx.uniformMatrix3x4fv(this.uniforms[location], false, array);
  929. },
  930. /* Vertex attribs */
  931. VertexAttribI4i: (index, x, y, z, w) => {
  932. this.assertWebGL2();
  933. this.ctx.vertexAttribI4i(index, x, y, z, w);
  934. },
  935. VertexAttribI4ui: (index, x, y, z, w) => {
  936. this.assertWebGL2();
  937. this.ctx.vertexAttribI4ui(index, x, y, z, w);
  938. },
  939. VertexAttribIPointer: (index, size, type, stride, offset) => {
  940. this.assertWebGL2();
  941. this.ctx.vertexAttribIPointer(index, size, type, stride, offset);
  942. },
  943. /* Writing to the drawing buffer */
  944. VertexAttribDivisor: (index, divisor) => {
  945. this.assertWebGL2();
  946. this.ctx.vertexAttribDivisor(index, divisor);
  947. },
  948. DrawArraysInstanced: (mode, first, count, instanceCount) => {
  949. this.assertWebGL2();
  950. this.ctx.drawArraysInstanced(mode, first, count, instanceCount);
  951. },
  952. DrawElementsInstanced: (mode, count, type, offset, instanceCount) => {
  953. this.assertWebGL2();
  954. this.ctx.drawElementsInstanced(mode, count, type, offset, instanceCount);
  955. },
  956. DrawRangeElements: (mode, start, end, count, type, offset) => {
  957. this.assertWebGL2();
  958. this.ctx.drawRangeElements(mode, start, end, count, type, offset);
  959. },
  960. /* Multiple Render Targets */
  961. DrawBuffers: (buffers_ptr, buffers_len) => {
  962. this.assertWebGL2();
  963. let array = this.mem.loadU32Array(buffers_ptr, buffers_len);
  964. this.ctx.drawBuffers(array);
  965. },
  966. ClearBufferfv: (buffer, drawbuffer, values_ptr, values_len) => {
  967. this.assertWebGL2();
  968. let array = this.mem.loadF32Array(values_ptr, values_len);
  969. this.ctx.clearBufferfv(buffer, drawbuffer, array);
  970. },
  971. ClearBufferiv: (buffer, drawbuffer, values_ptr, values_len) => {
  972. this.assertWebGL2();
  973. let array = this.mem.loadI32Array(values_ptr, values_len);
  974. this.ctx.clearBufferiv(buffer, drawbuffer, array);
  975. },
  976. ClearBufferuiv: (buffer, drawbuffer, values_ptr, values_len) => {
  977. this.assertWebGL2();
  978. let array = this.mem.loadU32Array(values_ptr, values_len);
  979. this.ctx.clearBufferuiv(buffer, drawbuffer, array);
  980. },
  981. ClearBufferfi: (buffer, drawbuffer, depth, stencil) => {
  982. this.assertWebGL2();
  983. this.ctx.clearBufferfi(buffer, drawbuffer, depth, stencil);
  984. },
  985. /* Query Objects */
  986. CreateQuery: () => {
  987. this.assertWebGL2();
  988. let query = this.ctx.createQuery();
  989. let id = this.getNewId(this.queries);
  990. query.name = id;
  991. this.queries[id] = query;
  992. return id;
  993. },
  994. DeleteQuery: (id) => {
  995. this.assertWebGL2();
  996. let obj = this.queries[id];
  997. if (obj && id != 0) {
  998. this.ctx.deleteQuery(obj);
  999. this.queries[id] = null;
  1000. }
  1001. },
  1002. IsQuery: (query) => {
  1003. this.assertWebGL2();
  1004. return this.ctx.isQuery(this.queries[query]);
  1005. },
  1006. BeginQuery: (target, query) => {
  1007. this.assertWebGL2();
  1008. this.ctx.beginQuery(target, this.queries[query])
  1009. },
  1010. EndQuery: (target) => {
  1011. this.assertWebGL2();
  1012. this.ctx.endQuery(target);
  1013. },
  1014. GetQuery: (target, pname) => {
  1015. this.assertWebGL2();
  1016. let query = this.ctx.getQuery(target, pname);
  1017. if (!query) {
  1018. return 0;
  1019. }
  1020. if (this.queries.indexOf(query) !== -1) {
  1021. return query.name;
  1022. }
  1023. let id = this.getNewId(this.queries);
  1024. query.name = id;
  1025. this.queries[id] = query;
  1026. return id;
  1027. },
  1028. /* Sampler Objects */
  1029. CreateSampler: () => {
  1030. this.assertWebGL2();
  1031. let sampler = this.ctx.createSampler();
  1032. let id = this.getNewId(this.samplers);
  1033. sampler.name = id;
  1034. this.samplers[id] = sampler;
  1035. return id;
  1036. },
  1037. DeleteSampler: (id) => {
  1038. this.assertWebGL2();
  1039. let obj = this.samplers[id];
  1040. if (obj && id != 0) {
  1041. this.ctx.deleteSampler(obj);
  1042. this.samplers[id] = null;
  1043. }
  1044. },
  1045. IsSampler: (sampler) => {
  1046. this.assertWebGL2();
  1047. return this.ctx.isSampler(this.samplers[sampler]);
  1048. },
  1049. BindSampler: (unit, sampler) => {
  1050. this.assertWebGL2();
  1051. this.ctx.bindSampler(unit, this.samplers[sampler]);
  1052. },
  1053. SamplerParameteri: (sampler, pname, param) => {
  1054. this.assertWebGL2();
  1055. this.ctx.samplerParameteri(this.samplers[sampler], pname, param);
  1056. },
  1057. SamplerParameterf: (sampler, pname, param) => {
  1058. this.assertWebGL2();
  1059. this.ctx.samplerParameterf(this.samplers[sampler], pname, param);
  1060. },
  1061. /* Sync objects */
  1062. FenceSync: (condition, flags) => {
  1063. this.assertWebGL2();
  1064. let sync = this.ctx.fenceSync(condition, flags);
  1065. let id = this.getNewId(this.syncs);
  1066. sync.name = id;
  1067. this.syncs[id] = sync;
  1068. return id;
  1069. },
  1070. IsSync: (sync) => {
  1071. this.assertWebGL2();
  1072. return this.ctx.isSync(this.syncs[sync]);
  1073. },
  1074. DeleteSync: (id) => {
  1075. this.assertWebGL2();
  1076. let obj = this.syncs[id];
  1077. if (obj && id != 0) {
  1078. this.ctx.deleteSampler(obj);
  1079. this.syncs[id] = null;
  1080. }
  1081. },
  1082. ClientWaitSync: (sync, flags, timeout) => {
  1083. this.assertWebGL2();
  1084. return this.ctx.clientWaitSync(this.syncs[sync], flags, timeout);
  1085. },
  1086. WaitSync: (sync, flags, timeout) => {
  1087. this.assertWebGL2();
  1088. this.ctx.waitSync(this.syncs[sync], flags, timeout) ;
  1089. },
  1090. /* Transform Feedback */
  1091. CreateTransformFeedback: () => {
  1092. this.assertWebGL2();
  1093. let transformFeedback = this.ctx.createTransformFeedback();
  1094. let id = this.getNewId(this.transformFeedbacks);
  1095. transformFeedback.name = id;
  1096. this.transformFeedbacks[id] = transformFeedback;
  1097. return id;
  1098. },
  1099. DeleteTransformFeedback: (id) => {
  1100. this.assertWebGL2();
  1101. let obj = this.transformFeedbacks[id];
  1102. if (obj && id != 0) {
  1103. this.ctx.deleteTransformFeedback(obj);
  1104. this.transformFeedbacks[id] = null;
  1105. }
  1106. },
  1107. IsTransformFeedback: (tf) => {
  1108. this.assertWebGL2();
  1109. return this.ctx.isTransformFeedback(this.transformFeedbacks[tf]);
  1110. },
  1111. BindTransformFeedback: (target, tf) => {
  1112. this.assertWebGL2();
  1113. this.ctx.bindTransformFeedback(target, this.transformFeedbacks[tf]);
  1114. },
  1115. BeginTransformFeedback: (primitiveMode) => {
  1116. this.assertWebGL2();
  1117. this.ctx.beginTransformFeedback(primitiveMode);
  1118. },
  1119. EndTransformFeedback: () => {
  1120. this.assertWebGL2();
  1121. this.ctx.endTransformFeedback();
  1122. },
  1123. TransformFeedbackVaryings: (program, varyings_ptr, varyings_len, bufferMode) => {
  1124. this.assertWebGL2();
  1125. const stringSize = this.mem.intSize*2;
  1126. let varyings = [];
  1127. for (let i = 0; i < varyings_len; i++) {
  1128. let ptr = this.mem.loadPtr(varyings_ptr + i*stringSize + 0*4);
  1129. let len = this.mem.loadPtr(varyings_ptr + i*stringSize + 1*4);
  1130. varyings.push(this.mem.loadString(ptr, len));
  1131. }
  1132. this.ctx.transformFeedbackVaryings(this.programs[program], varyings, bufferMode);
  1133. },
  1134. PauseTransformFeedback: () => {
  1135. this.assertWebGL2();
  1136. this.ctx.pauseTransformFeedback();
  1137. },
  1138. ResumeTransformFeedback: () => {
  1139. this.assertWebGL2();
  1140. this.ctx.resumeTransformFeedback();
  1141. },
  1142. /* Uniform Buffer Objects and Transform Feedback Buffers */
  1143. BindBufferBase: (target, index, buffer) => {
  1144. this.assertWebGL2();
  1145. this.ctx.bindBufferBase(target, index, this.buffers[buffer]);
  1146. },
  1147. BindBufferRange: (target, index, buffer, offset, size) => {
  1148. this.assertWebGL2();
  1149. this.ctx.bindBufferRange(target, index, this.buffers[buffer], offset, size);
  1150. },
  1151. GetUniformBlockIndex: (program, uniformBlockName_ptr, uniformBlockName_len) => {
  1152. this.assertWebGL2();
  1153. return this.ctx.getUniformBlockIndex(this.programs[program], this.mem.loadString(uniformBlockName_ptr, uniformBlockName_len));
  1154. },
  1155. // any getActiveUniformBlockParameter(WebGLProgram program, GLuint uniformBlockIndex, GLenum pname);
  1156. GetActiveUniformBlockName: (program, uniformBlockIndex, buf_ptr, buf_len, length_ptr) => {
  1157. this.assertWebGL2();
  1158. let name = this.ctx.getActiveUniformBlockName(this.programs[program], uniformBlockIndex);
  1159. let n = Math.min(buf_len, name.length);
  1160. name = name.substring(0, n);
  1161. this.mem.loadBytes(buf_ptr, buf_len).set(new TextEncoder().encode(name))
  1162. this.mem.storeInt(length_ptr, n);
  1163. },
  1164. UniformBlockBinding: (program, uniformBlockIndex, uniformBlockBinding) => {
  1165. this.assertWebGL2();
  1166. this.ctx.uniformBlockBinding(this.programs[program], uniformBlockIndex, uniformBlockBinding);
  1167. },
  1168. /* Vertex Array Objects */
  1169. CreateVertexArray: () => {
  1170. this.assertWebGL2();
  1171. let vao = this.ctx.createVertexArray();
  1172. let id = this.getNewId(this.vaos);
  1173. vao.name = id;
  1174. this.vaos[id] = vao;
  1175. return id;
  1176. },
  1177. DeleteVertexArray: (id) => {
  1178. this.assertWebGL2();
  1179. let obj = this.vaos[id];
  1180. if (obj && id != 0) {
  1181. this.ctx.deleteVertexArray(obj);
  1182. this.vaos[id] = null;
  1183. }
  1184. },
  1185. IsVertexArray: (vertexArray) => {
  1186. this.assertWebGL2();
  1187. return this.ctx.isVertexArray(this.vaos[vertexArray]);
  1188. },
  1189. BindVertexArray: (vertexArray) => {
  1190. this.assertWebGL2();
  1191. this.ctx.bindVertexArray(this.vaos[vertexArray]);
  1192. },
  1193. };
  1194. }
  1195. };
  1196. function odinSetupDefaultImports(wasmMemoryInterface, consoleElement, memory) {
  1197. const MAX_INFO_CONSOLE_LINES = 512;
  1198. let infoConsoleLines = new Array();
  1199. let currentLine = {};
  1200. currentLine[false] = "";
  1201. currentLine[true] = "";
  1202. let prevIsError = false;
  1203. let event_temp = {};
  1204. const onEventReceived = (event_data, data, callback) => {
  1205. event_temp.data = event_data;
  1206. const exports = wasmMemoryInterface.exports;
  1207. const odin_ctx = exports.default_context_ptr();
  1208. exports.odin_dom_do_event_callback(data, callback, odin_ctx);
  1209. event_temp.data = null;
  1210. };
  1211. const writeToConsole = (line, isError) => {
  1212. if (!line) {
  1213. return;
  1214. }
  1215. const println = (text, forceIsError) => {
  1216. let style = [
  1217. "color: #eee",
  1218. "background-color: #d20",
  1219. "padding: 2px 4px",
  1220. "border-radius: 2px",
  1221. ].join(";");
  1222. let doIsError = isError;
  1223. if (forceIsError !== undefined) {
  1224. doIsError = forceIsError;
  1225. }
  1226. if (doIsError) {
  1227. console.log("%c"+text, style);
  1228. } else {
  1229. console.log(text);
  1230. }
  1231. };
  1232. // Print to console
  1233. if (line == "\n") {
  1234. println(currentLine[isError]);
  1235. currentLine[isError] = "";
  1236. } else if (!line.includes("\n")) {
  1237. currentLine[isError] = currentLine[isError].concat(line);
  1238. } else {
  1239. let lines = line.trimEnd().split("\n");
  1240. let printLast = lines.length > 1 && line.endsWith("\n");
  1241. println(currentLine[isError].concat(lines[0]));
  1242. currentLine[isError] = "";
  1243. for (let i = 1; i < lines.length-1; i++) {
  1244. println(lines[i]);
  1245. }
  1246. if (lines.length > 1) {
  1247. let last = lines[lines.length-1];
  1248. if (printLast) {
  1249. println(last);
  1250. } else {
  1251. currentLine[isError] = last;
  1252. }
  1253. }
  1254. }
  1255. if (prevIsError != isError) {
  1256. if (prevIsError) {
  1257. println(currentLine[prevIsError], prevIsError);
  1258. currentLine[prevIsError] = "";
  1259. }
  1260. }
  1261. prevIsError = isError;
  1262. // HTML based console
  1263. if (!consoleElement) {
  1264. return;
  1265. }
  1266. const wrap = (x) => {
  1267. if (isError) {
  1268. return '<span style="color:#f21">'+x+'</span>';
  1269. }
  1270. return x;
  1271. };
  1272. if (line == "\n") {
  1273. infoConsoleLines.push(line);
  1274. } else if (!line.includes("\n")) {
  1275. let prevLine = "";
  1276. if (infoConsoleLines.length > 0) {
  1277. prevLine = infoConsoleLines.pop();
  1278. }
  1279. infoConsoleLines.push(prevLine.concat(wrap(line)));
  1280. } else {
  1281. let lines = line.split("\n");
  1282. let lastHasNewline = lines.length > 1 && line.endsWith("\n");
  1283. let prevLine = "";
  1284. if (infoConsoleLines.length > 0) {
  1285. prevLine = infoConsoleLines.pop();
  1286. }
  1287. infoConsoleLines.push(prevLine.concat(wrap(lines[0]).concat("\n")));
  1288. for (let i = 1; i < lines.length-1; i++) {
  1289. infoConsoleLines.push(wrap(lines[i]).concat("\n"));
  1290. }
  1291. let last = lines[lines.length-1];
  1292. if (lastHasNewline) {
  1293. infoConsoleLines.push(last.concat("\n"));
  1294. } else {
  1295. infoConsoleLines.push(last);
  1296. }
  1297. }
  1298. if (infoConsoleLines.length > MAX_INFO_CONSOLE_LINES) {
  1299. infoConsoleLines.shift(MAX_INFO_CONSOLE_LINES);
  1300. }
  1301. let data = "";
  1302. for (let i = 0; i < infoConsoleLines.length; i++) {
  1303. data = data.concat(infoConsoleLines[i]);
  1304. }
  1305. let info = consoleElement;
  1306. info.innerHTML = data;
  1307. info.scrollTop = info.scrollHeight;
  1308. };
  1309. const listener_key = (id, name, data, callback, useCapture) => {
  1310. return `${id}-${name}-data:${data}-callback:${callback}-useCapture:${useCapture}`;
  1311. };
  1312. let webglContext = new WebGLInterface(wasmMemoryInterface);
  1313. const env = {};
  1314. if (memory) {
  1315. env.memory = memory;
  1316. }
  1317. return {
  1318. env,
  1319. "odin_env": {
  1320. write: (fd, ptr, len) => {
  1321. const str = wasmMemoryInterface.loadString(ptr, len);
  1322. if (fd == 1) {
  1323. writeToConsole(str, false);
  1324. return;
  1325. } else if (fd == 2) {
  1326. writeToConsole(str, true);
  1327. return;
  1328. } else {
  1329. throw new Error("Invalid fd to 'write'" + stripNewline(str));
  1330. }
  1331. },
  1332. trap: () => { throw new Error() },
  1333. alert: (ptr, len) => { alert(wasmMemoryInterface.loadString(ptr, len)) },
  1334. abort: () => { Module.abort() },
  1335. evaluate: (str_ptr, str_len) => { eval.call(null, wasmMemoryInterface.loadString(str_ptr, str_len)); },
  1336. open: (url_ptr, url_len, name_ptr, name_len, specs_ptr, specs_len) => {
  1337. const url = wasmMemoryInterface.loadString(url_ptr, url_len);
  1338. const name = wasmMemoryInterface.loadString(name_ptr, name_len);
  1339. const specs = wasmMemoryInterface.loadString(specs_ptr, specs_len);
  1340. window.open(url, name, specs);
  1341. },
  1342. // return a bigint to be converted to i64
  1343. time_now: () => BigInt(Date.now()),
  1344. tick_now: () => performance.now(),
  1345. time_sleep: (duration_ms) => {
  1346. if (duration_ms > 0) {
  1347. // TODO(bill): Does this even make any sense?
  1348. }
  1349. },
  1350. sqrt: Math.sqrt,
  1351. sin: Math.sin,
  1352. cos: Math.cos,
  1353. pow: Math.pow,
  1354. fmuladd: (x, y, z) => x*y + z,
  1355. ln: Math.log,
  1356. exp: Math.exp,
  1357. ldexp: (x, exp) => x * Math.pow(2, exp),
  1358. rand_bytes: (ptr, len) => {
  1359. const view = new Uint8Array(wasmMemoryInterface.memory.buffer, ptr, len)
  1360. crypto.getRandomValues(view)
  1361. },
  1362. },
  1363. "odin_dom": {
  1364. init_event_raw: (ep) => {
  1365. const W = wasmMemoryInterface.intSize;
  1366. let offset = ep;
  1367. let off = (amount, alignment) => {
  1368. if (alignment === undefined) {
  1369. alignment = Math.min(amount, W);
  1370. }
  1371. if (offset % alignment != 0) {
  1372. offset += alignment - (offset%alignment);
  1373. }
  1374. let x = offset;
  1375. offset += amount;
  1376. return x;
  1377. };
  1378. let align = (alignment) => {
  1379. const modulo = offset & (alignment-1);
  1380. if (modulo != 0) {
  1381. offset += alignment - modulo
  1382. }
  1383. };
  1384. let wmi = wasmMemoryInterface;
  1385. if (!event_temp.data) {
  1386. return;
  1387. }
  1388. let e = event_temp.data.event;
  1389. wmi.storeU32(off(4), event_temp.data.name_code);
  1390. if (e.target == document) {
  1391. wmi.storeU32(off(4), 1);
  1392. } else if (e.target == window) {
  1393. wmi.storeU32(off(4), 2);
  1394. } else {
  1395. wmi.storeU32(off(4), 0);
  1396. }
  1397. if (e.currentTarget == document) {
  1398. wmi.storeU32(off(4), 1);
  1399. } else if (e.currentTarget == window) {
  1400. wmi.storeU32(off(4), 2);
  1401. } else {
  1402. wmi.storeU32(off(4), 0);
  1403. }
  1404. align(W);
  1405. wmi.storeI32(off(W), event_temp.data.id_ptr);
  1406. wmi.storeUint(off(W), event_temp.data.id_len);
  1407. align(8);
  1408. wmi.storeF64(off(8), e.timeStamp*1e-3);
  1409. wmi.storeU8(off(1), e.eventPhase);
  1410. let options = 0;
  1411. if (!!e.bubbles) { options |= 1<<0; }
  1412. if (!!e.cancelable) { options |= 1<<1; }
  1413. if (!!e.composed) { options |= 1<<2; }
  1414. wmi.storeU8(off(1), options);
  1415. wmi.storeU8(off(1), !!e.isComposing);
  1416. wmi.storeU8(off(1), !!e.isTrusted);
  1417. align(8);
  1418. if (e instanceof WheelEvent) {
  1419. wmi.storeF64(off(8), e.deltaX);
  1420. wmi.storeF64(off(8), e.deltaY);
  1421. wmi.storeF64(off(8), e.deltaZ);
  1422. wmi.storeU32(off(4), e.deltaMode);
  1423. } else if (e instanceof MouseEvent) {
  1424. wmi.storeI64(off(8), e.screenX);
  1425. wmi.storeI64(off(8), e.screenY);
  1426. wmi.storeI64(off(8), e.clientX);
  1427. wmi.storeI64(off(8), e.clientY);
  1428. wmi.storeI64(off(8), e.offsetX);
  1429. wmi.storeI64(off(8), e.offsetY);
  1430. wmi.storeI64(off(8), e.pageX);
  1431. wmi.storeI64(off(8), e.pageY);
  1432. wmi.storeI64(off(8), e.movementX);
  1433. wmi.storeI64(off(8), e.movementY);
  1434. wmi.storeU8(off(1), !!e.ctrlKey);
  1435. wmi.storeU8(off(1), !!e.shiftKey);
  1436. wmi.storeU8(off(1), !!e.altKey);
  1437. wmi.storeU8(off(1), !!e.metaKey);
  1438. wmi.storeI16(off(2), e.button);
  1439. wmi.storeU16(off(2), e.buttons);
  1440. if (e instanceof PointerEvent) {
  1441. wmi.storeF64(off(8), e.altitudeAngle);
  1442. wmi.storeF64(off(8), e.azimuthAngle);
  1443. wmi.storeInt(off(W), e.persistentDeviceId);
  1444. wmi.storeInt(off(W), e.pointerId);
  1445. wmi.storeInt(off(W), e.width);
  1446. wmi.storeInt(off(W), e.height);
  1447. wmi.storeF64(off(8), e.pressure);
  1448. wmi.storeF64(off(8), e.tangentialPressure);
  1449. wmi.storeF64(off(8), e.tiltX);
  1450. wmi.storeF64(off(8), e.tiltY);
  1451. wmi.storeF64(off(8), e.twist);
  1452. if (e.pointerType == "pen") {
  1453. wmi.storeU8(off(1), 1);
  1454. } else if (e.pointerType == "touch") {
  1455. wmi.storeU8(off(1), 2);
  1456. } else {
  1457. wmi.storeU8(off(1), 0);
  1458. }
  1459. wmi.storeU8(off(1), !!e.isPrimary);
  1460. }
  1461. } else if (e instanceof KeyboardEvent) {
  1462. // Note: those strings are constructed
  1463. // on the native side from buffers that
  1464. // are filled later, so skip them
  1465. const keyPtr = off(W*2, W);
  1466. const codePtr = off(W*2, W);
  1467. wmi.storeU8(off(1), e.location);
  1468. wmi.storeU8(off(1), !!e.ctrlKey);
  1469. wmi.storeU8(off(1), !!e.shiftKey);
  1470. wmi.storeU8(off(1), !!e.altKey);
  1471. wmi.storeU8(off(1), !!e.metaKey);
  1472. wmi.storeU8(off(1), !!e.repeat);
  1473. wmi.storeI32(off(4), e.charCode);
  1474. wmi.storeInt(off(W, W), e.key.length)
  1475. wmi.storeInt(off(W, W), e.code.length)
  1476. wmi.storeString(off(32, 1), e.key);
  1477. wmi.storeString(off(32, 1), e.code);
  1478. } else if (e.type === 'scroll') {
  1479. wmi.storeF64(off(8, 8), window.scrollX);
  1480. wmi.storeF64(off(8, 8), window.scrollY);
  1481. } else if (e.type === 'visibilitychange') {
  1482. wmi.storeU8(off(1), !document.hidden);
  1483. } else if (e instanceof GamepadEvent) {
  1484. const idPtr = off(W*2, W);
  1485. const mappingPtr = off(W*2, W);
  1486. wmi.storeI32(off(W, W), e.gamepad.index);
  1487. wmi.storeU8(off(1), !!e.gamepad.connected);
  1488. wmi.storeF64(off(8, 8), e.gamepad.timestamp);
  1489. wmi.storeInt(off(W, W), e.gamepad.buttons.length);
  1490. wmi.storeInt(off(W, W), e.gamepad.axes.length);
  1491. for (let i = 0; i < 64; i++) {
  1492. if (i < e.gamepad.buttons.length) {
  1493. let b = e.gamepad.buttons[i];
  1494. wmi.storeF64(off(8, 8), b.value);
  1495. wmi.storeU8(off(1), !!b.pressed);
  1496. wmi.storeU8(off(1), !!b.touched);
  1497. } else {
  1498. off(16, 8);
  1499. }
  1500. }
  1501. for (let i = 0; i < 16; i++) {
  1502. if (i < e.gamepad.axes.length) {
  1503. let a = e.gamepad.axes[i];
  1504. wmi.storeF64(off(8, 8), a);
  1505. } else {
  1506. off(8, 8);
  1507. }
  1508. }
  1509. let idLength = e.gamepad.id.length;
  1510. let id = e.gamepad.id;
  1511. if (idLength > 96) {
  1512. idLength = 96;
  1513. id = id.slice(0, 93) + '...';
  1514. }
  1515. let mappingLength = e.gamepad.mapping.length;
  1516. let mapping = e.gamepad.mapping;
  1517. if (mappingLength > 64) {
  1518. mappingLength = 61;
  1519. mapping = mapping.slice(0, 61) + '...';
  1520. }
  1521. wmi.storeInt(off(W, W), idLength);
  1522. wmi.storeInt(off(W, W), mappingLength);
  1523. wmi.storeString(off(96, 1), id);
  1524. wmi.storeString(off(64, 1), mapping);
  1525. }
  1526. },
  1527. add_event_listener: (id_ptr, id_len, name_ptr, name_len, name_code, data, callback, use_capture) => {
  1528. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1529. let name = wasmMemoryInterface.loadString(name_ptr, name_len);
  1530. let element = getElement(id);
  1531. if (element == undefined) {
  1532. return false;
  1533. }
  1534. let key = listener_key(id, name, data, callback, !!use_capture);
  1535. if (wasmMemoryInterface.listenerMap.has(key)) {
  1536. return false;
  1537. }
  1538. let listener = (e) => {
  1539. let event_data = {};
  1540. event_data.id_ptr = id_ptr;
  1541. event_data.id_len = id_len;
  1542. event_data.event = e;
  1543. event_data.name_code = name_code;
  1544. onEventReceived(event_data, data, callback);
  1545. };
  1546. wasmMemoryInterface.listenerMap.set(key, listener);
  1547. element.addEventListener(name, listener, !!use_capture);
  1548. return true;
  1549. },
  1550. add_window_event_listener: (name_ptr, name_len, name_code, data, callback, use_capture) => {
  1551. let name = wasmMemoryInterface.loadString(name_ptr, name_len);
  1552. let element = window;
  1553. let key = listener_key('window', name, data, callback, !!use_capture);
  1554. if (wasmMemoryInterface.listenerMap.has(key)) {
  1555. return false;
  1556. }
  1557. let listener = (e) => {
  1558. let event_data = {};
  1559. event_data.id_ptr = 0;
  1560. event_data.id_len = 0;
  1561. event_data.event = e;
  1562. event_data.name_code = name_code;
  1563. onEventReceived(event_data, data, callback);
  1564. };
  1565. wasmMemoryInterface.listenerMap.set(key, listener);
  1566. element.addEventListener(name, listener, !!use_capture);
  1567. return true;
  1568. },
  1569. add_document_event_listener: (name_ptr, name_len, name_code, data, callback, use_capture) => {
  1570. let name = wasmMemoryInterface.loadString(name_ptr, name_len);
  1571. let element = document;
  1572. let key = listener_key('document', name, data, callback, !!use_capture);
  1573. if (wasmMemoryInterface.listenerMap.has(key)) {
  1574. return false;
  1575. }
  1576. let listener = (e) => {
  1577. let event_data = {};
  1578. event_data.id_ptr = 0;
  1579. event_data.id_len = 0;
  1580. event_data.event = e;
  1581. event_data.name_code = name_code;
  1582. onEventReceived(event_data, data, callback);
  1583. };
  1584. wasmMemoryInterface.listenerMap.set(key, listener);
  1585. element.addEventListener(name, listener, !!use_capture);
  1586. return true;
  1587. },
  1588. remove_event_listener: (id_ptr, id_len, name_ptr, name_len, data, callback, use_capture) => {
  1589. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1590. let name = wasmMemoryInterface.loadString(name_ptr, name_len);
  1591. let element = getElement(id);
  1592. if (element == undefined) {
  1593. return false;
  1594. }
  1595. let key = listener_key(id, name, data, callback, !!use_capture);
  1596. let listener = wasmMemoryInterface.listenerMap.get(key);
  1597. if (listener === undefined) {
  1598. return false;
  1599. }
  1600. wasmMemoryInterface.listenerMap.delete(key);
  1601. element.removeEventListener(name, listener, !!use_capture);
  1602. return true;
  1603. },
  1604. remove_window_event_listener: (name_ptr, name_len, data, callback, use_capture) => {
  1605. let name = wasmMemoryInterface.loadString(name_ptr, name_len);
  1606. let element = window;
  1607. let key = listener_key('window', name, data, callback, !!use_capture);
  1608. let listener = wasmMemoryInterface.listenerMap.get(key);
  1609. if (listener === undefined) {
  1610. return false;
  1611. }
  1612. wasmMemoryInterface.listenerMap.delete(key);
  1613. element.removeEventListener(name, listener, !!use_capture);
  1614. return true;
  1615. },
  1616. remove_document_event_listener: (name_ptr, name_len, data, callback, use_capture) => {
  1617. let name = wasmMemoryInterface.loadString(name_ptr, name_len);
  1618. let element = document;
  1619. let key = listener_key('document', name, data, callback, !!use_capture);
  1620. let listener = wasmMemoryInterface.listenerMap.get(key);
  1621. if (listener === undefined) {
  1622. return false;
  1623. }
  1624. wasmMemoryInterface.listenerMap.delete(key);
  1625. element.removeEventListener(name, listener, !!use_capture);
  1626. return true;
  1627. },
  1628. event_stop_propagation: () => {
  1629. if (event_temp.data && event_temp.data.event) {
  1630. event_temp.data.event.stopPropagation();
  1631. }
  1632. },
  1633. event_stop_immediate_propagation: () => {
  1634. if (event_temp.data && event_temp.data.event) {
  1635. event_temp.data.event.stopImmediatePropagation();
  1636. }
  1637. },
  1638. event_prevent_default: () => {
  1639. if (event_temp.data && event_temp.data.event) {
  1640. event_temp.data.event.preventDefault();
  1641. }
  1642. },
  1643. dispatch_custom_event: (id_ptr, id_len, name_ptr, name_len, options_bits) => {
  1644. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1645. let name = wasmMemoryInterface.loadString(name_ptr, name_len);
  1646. let options = {
  1647. bubbles: (options_bits & (1<<0)) !== 0,
  1648. cancelable: (options_bits & (1<<1)) !== 0,
  1649. composed: (options_bits & (1<<2)) !== 0,
  1650. };
  1651. let element = getElement(id);
  1652. if (element) {
  1653. element.dispatchEvent(new Event(name, options));
  1654. return true;
  1655. }
  1656. return false;
  1657. },
  1658. get_gamepad_state: (gamepad_id, ep) => {
  1659. let index = gamepad_id;
  1660. let gps = navigator.getGamepads();
  1661. if (0 <= index && index < gps.length) {
  1662. let gamepad = gps[index];
  1663. if (!gamepad) {
  1664. return false;
  1665. }
  1666. const W = wasmMemoryInterface.intSize;
  1667. let offset = ep;
  1668. let off = (amount, alignment) => {
  1669. if (alignment === undefined) {
  1670. alignment = Math.min(amount, W);
  1671. }
  1672. if (offset % alignment != 0) {
  1673. offset += alignment - (offset%alignment);
  1674. }
  1675. let x = offset;
  1676. offset += amount;
  1677. return x;
  1678. };
  1679. let align = (alignment) => {
  1680. const modulo = offset & (alignment-1);
  1681. if (modulo != 0) {
  1682. offset += alignment - modulo
  1683. }
  1684. };
  1685. let wmi = wasmMemoryInterface;
  1686. const idPtr = off(W*2, W);
  1687. const mappingPtr = off(W*2, W);
  1688. wmi.storeI32(off(W), gamepad.index);
  1689. wmi.storeU8(off(1), !!gamepad.connected);
  1690. wmi.storeF64(off(8), gamepad.timestamp);
  1691. wmi.storeInt(off(W), gamepad.buttons.length);
  1692. wmi.storeInt(off(W), gamepad.axes.length);
  1693. for (let i = 0; i < 64; i++) {
  1694. if (i < gamepad.buttons.length) {
  1695. let b = gamepad.buttons[i];
  1696. wmi.storeF64(off(8, 8), b.value);
  1697. wmi.storeU8(off(1), !!b.pressed);
  1698. wmi.storeU8(off(1), !!b.touched);
  1699. } else {
  1700. off(16, 8);
  1701. }
  1702. }
  1703. for (let i = 0; i < 16; i++) {
  1704. if (i < gamepad.axes.length) {
  1705. wmi.storeF64(off(8, 8), gamepad.axes[i]);
  1706. } else {
  1707. off(8, 8);
  1708. }
  1709. }
  1710. let idLength = gamepad.id.length;
  1711. let id = gamepad.id;
  1712. if (idLength > 96) {
  1713. idLength = 96;
  1714. id = id.slice(0, 93) + '...';
  1715. }
  1716. let mappingLength = gamepad.mapping.length;
  1717. let mapping = gamepad.mapping;
  1718. if (mappingLength > 64) {
  1719. mappingLength = 61;
  1720. mapping = mapping.slice(0, 61) + '...';
  1721. }
  1722. wmi.storeInt(off(W, W), idLength);
  1723. wmi.storeInt(off(W, W), mappingLength);
  1724. wmi.storeString(off(96, 1), id);
  1725. wmi.storeString(off(64, 1), mapping);
  1726. return true;
  1727. }
  1728. return false;
  1729. },
  1730. get_element_value_f64: (id_ptr, id_len) => {
  1731. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1732. let element = getElement(id);
  1733. return element ? element.value : 0;
  1734. },
  1735. get_element_value_string: (id_ptr, id_len, buf_ptr, buf_len) => {
  1736. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1737. let element = getElement(id);
  1738. if (element) {
  1739. let str = element.value;
  1740. if (buf_len > 0 && buf_ptr) {
  1741. let n = Math.min(buf_len, str.length);
  1742. str = str.substring(0, n);
  1743. wasmMemoryInterface.loadBytes(buf_ptr, buf_len).set(new TextEncoder().encode(str))
  1744. return n;
  1745. }
  1746. }
  1747. return 0;
  1748. },
  1749. get_element_value_string_length: (id_ptr, id_len) => {
  1750. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1751. let element = getElement(id);
  1752. if (element) {
  1753. return element.value.length;
  1754. }
  1755. return 0;
  1756. },
  1757. get_element_min_max: (ptr_array2_f64, id_ptr, id_len) => {
  1758. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1759. let element = getElement(id);
  1760. if (element) {
  1761. let values = wasmMemoryInterface.loadF64Array(ptr_array2_f64, 2);
  1762. values[0] = element.min;
  1763. values[1] = element.max;
  1764. }
  1765. },
  1766. set_element_value_f64: (id_ptr, id_len, value) => {
  1767. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1768. let element = getElement(id);
  1769. if (element) {
  1770. element.value = value;
  1771. }
  1772. },
  1773. set_element_value_string: (id_ptr, id_len, value_ptr, value_len) => {
  1774. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1775. let value = wasmMemoryInterface.loadString(value_ptr, value_len);
  1776. let element = getElement(id);
  1777. if (element) {
  1778. element.value = value;
  1779. }
  1780. },
  1781. set_element_style: (id_ptr, id_len, key_ptr, key_len, value_ptr, value_len) => {
  1782. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1783. let key = wasmMemoryInterface.loadString(key_ptr, key_len);
  1784. let value = wasmMemoryInterface.loadString(value_ptr, value_len);
  1785. let element = getElement(id);
  1786. if (element) {
  1787. element.style[key] = value;
  1788. }
  1789. },
  1790. get_element_key_f64: (id_ptr, id_len, key_ptr, key_len) => {
  1791. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1792. let key = wasmMemoryInterface.loadString(key_ptr, key_len);
  1793. let element = getElement(id);
  1794. return element ? element[key] : 0;
  1795. },
  1796. get_element_key_string: (id_ptr, id_len, key_ptr, key_len, buf_ptr, buf_len) => {
  1797. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1798. let key = wasmMemoryInterface.loadString(key_ptr, key_len);
  1799. let element = getElement(id);
  1800. if (element) {
  1801. let str = element[key];
  1802. if (buf_len > 0 && buf_ptr) {
  1803. let n = Math.min(buf_len, str.length);
  1804. str = str.substring(0, n);
  1805. wasmMemoryInterface.loadBytes(buf_ptr, buf_len).set(new TextEncoder().encode(str))
  1806. return n;
  1807. }
  1808. }
  1809. return 0;
  1810. },
  1811. get_element_key_string_length: (id_ptr, id_len, key_ptr, key_len) => {
  1812. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1813. let key = wasmMemoryInterface.loadString(key_ptr, key_len);
  1814. let element = getElement(id);
  1815. if (element && element[key]) {
  1816. return element[key].length;
  1817. }
  1818. return 0;
  1819. },
  1820. set_element_key_f64: (id_ptr, id_len, key_ptr, key_len, value) => {
  1821. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1822. let key = wasmMemoryInterface.loadString(key_ptr, key_len);
  1823. let element = getElement(id);
  1824. if (element) {
  1825. element[key] = value;
  1826. }
  1827. },
  1828. set_element_key_string: (id_ptr, id_len, key_ptr, key_len, value_ptr, value_len) => {
  1829. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1830. let key = wasmMemoryInterface.loadString(key_ptr, key_len);
  1831. let value = wasmMemoryInterface.loadString(value_ptr, value_len);
  1832. let element = getElement(id);
  1833. if (element) {
  1834. element[key] = value;
  1835. }
  1836. },
  1837. get_bounding_client_rect: (rect_ptr, id_ptr, id_len) => {
  1838. let id = wasmMemoryInterface.loadString(id_ptr, id_len);
  1839. let element = getElement(id);
  1840. if (element) {
  1841. let values = wasmMemoryInterface.loadF64Array(rect_ptr, 4);
  1842. let rect = element.getBoundingClientRect();
  1843. values[0] = rect.left;
  1844. values[1] = rect.top;
  1845. values[2] = rect.right - rect.left;
  1846. values[3] = rect.bottom - rect.top;
  1847. }
  1848. },
  1849. window_get_rect: (rect_ptr) => {
  1850. let values = wasmMemoryInterface.loadF64Array(rect_ptr, 4);
  1851. values[0] = window.screenX;
  1852. values[1] = window.screenY;
  1853. values[2] = window.screen.width;
  1854. values[3] = window.screen.height;
  1855. },
  1856. window_get_scroll: (pos_ptr) => {
  1857. let values = wasmMemoryInterface.loadF64Array(pos_ptr, 2);
  1858. values[0] = window.scrollX;
  1859. values[1] = window.scrollY;
  1860. },
  1861. window_set_scroll: (x, y) => {
  1862. window.scroll(x, y);
  1863. },
  1864. device_pixel_ratio: () => {
  1865. return window.devicePixelRatio;
  1866. },
  1867. },
  1868. "webgl": webglContext.getWebGL1Interface(),
  1869. "webgl2": webglContext.getWebGL2Interface(),
  1870. };
  1871. };
  1872. /**
  1873. * @param {string} wasmPath - Path to the WASM module to run
  1874. * @param {?HTMLPreElement} consoleElement - Optional console/pre element to append output to, in addition to the console
  1875. * @param {any} extraForeignImports - Imports, in addition to the default runtime to provide the module
  1876. * @param {?WasmMemoryInterface} wasmMemoryInterface - Optional memory to use instead of the defaults
  1877. * @param {?int} intSize - Size (in bytes) of the integer type, should be 4 on `js_wasm32` and 8 on `js_wasm64p32`
  1878. */
  1879. async function runWasm(wasmPath, consoleElement, extraForeignImports, wasmMemoryInterface, intSize = 4) {
  1880. if (!wasmMemoryInterface) {
  1881. wasmMemoryInterface = new WasmMemoryInterface();
  1882. }
  1883. wasmMemoryInterface.setIntSize(intSize);
  1884. let imports = odinSetupDefaultImports(wasmMemoryInterface, consoleElement, wasmMemoryInterface.memory);
  1885. let exports = {};
  1886. if (extraForeignImports !== undefined) {
  1887. imports = {
  1888. ...imports,
  1889. ...extraForeignImports,
  1890. };
  1891. }
  1892. const response = await fetch(wasmPath);
  1893. const file = await response.arrayBuffer();
  1894. const wasm = await WebAssembly.instantiate(file, imports);
  1895. exports = wasm.instance.exports;
  1896. wasmMemoryInterface.setExports(exports);
  1897. if (exports.memory) {
  1898. if (wasmMemoryInterface.memory) {
  1899. console.warn("WASM module exports memory, but `runWasm` was given an interface with existing memory too");
  1900. }
  1901. wasmMemoryInterface.setMemory(exports.memory);
  1902. }
  1903. exports._start();
  1904. // Define a `@export step :: proc(delta_time: f64) -> (keep_going: bool) {`
  1905. // in your app and it will get called every frame.
  1906. // return `false` to stop the execution of the module.
  1907. if (exports.step) {
  1908. const odin_ctx = exports.default_context_ptr();
  1909. let prevTimeStamp = undefined;
  1910. function step(currTimeStamp) {
  1911. if (prevTimeStamp == undefined) {
  1912. prevTimeStamp = currTimeStamp;
  1913. }
  1914. const dt = (currTimeStamp - prevTimeStamp)*0.001;
  1915. prevTimeStamp = currTimeStamp;
  1916. if (!exports.step(dt, odin_ctx)) {
  1917. exports._end();
  1918. return;
  1919. }
  1920. window.requestAnimationFrame(step);
  1921. }
  1922. window.requestAnimationFrame(step);
  1923. } else {
  1924. exports._end();
  1925. }
  1926. return;
  1927. };
  1928. window.odin = {
  1929. // Interface Types
  1930. WasmMemoryInterface: WasmMemoryInterface,
  1931. WebGLInterface: WebGLInterface,
  1932. // Functions
  1933. setupDefaultImports: odinSetupDefaultImports,
  1934. runWasm: runWasm,
  1935. };
  1936. })();