runtime.js 52 KB

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