runtime.js 52 KB

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