odin.js 60 KB

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