wgpu.js 93 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921
  1. (function() {
  2. /**
  3. * Assumptions:
  4. * - Ability to allocate memory, set the context to allocate with using the global `wgpu.g_context`
  5. * - Exports a function table (for callbacks), added with `-extra-linker-flags:"--export-table"`
  6. */
  7. class WebGPUInterface {
  8. /**
  9. * @param {WasmMemoryInterface} mem
  10. */
  11. constructor(mem) {
  12. this.mem = mem;
  13. this.enums = {
  14. FeatureName: [undefined, "depth-clip-control", "depth32float-stencil8", "timestamp-query", "texture-compression-bc", "texture-compression-etc2", "texture-compression-astc", "indirect-first-instance", "shader-f16", "rg11b10ufloat-renderable", "bgra8unorm-storage", "float32-filterable", ],
  15. StoreOp: [undefined, "store", "discard", ],
  16. LoadOp: [undefined, "clear", "load", ],
  17. BufferBindingType: [undefined, "uniform", "storage", "read-only-storage", ],
  18. SamplerBindingType: [undefined, "filtering", "non-filtering", "comparison", ],
  19. TextureSampleType: [undefined, "float", "unfilterable-float", "depth", "sint", "uint", ],
  20. TextureViewDimension: [undefined, "1d", "2d", "2d-array", "cube", "cube-array", "3d", ],
  21. StorageTextureAccess: [undefined, "write-only", "read-only", "read-write", ],
  22. TextureFormat: [undefined, "r8unorm", "r8snorm", "r8uint", "r8sint", "r16uint", "r16sint", "r16float", "rg8unorm", "rg8snorm", "rg8uint", "rg8sint", "r32float", "r32uint", "r32sint", "rg16uint", "rg16sint", "rg16float", "rgba8unorm", "rgba8unorm-srgb", "rgba8snorm", "rgba8uint", "rgba8sint", "bgra8unorm", "bgra8unorm-srgb", "rgb10a2uint", "rgb10a2unorm", "rg11b10ufloat", "rgb9e5ufloat", "rg32float", "rg32uint", "rg32sint", "rgba16uint", "rgba16sint", "rgba16float", "rgba32float", "rgba32uint", "rgba32sint", "stencil8", "depth16unorm", "depth24plus", "depth24plus-stencil8", "depth32float", "depth32float-stencil8", "bc1-rgba-unorm", "bc1-rgba-unorm-srgb", "bc2-rgba-unorm", "bc2-rgba-unorm-srgb", "bc3-rgba-unorm", "bc3-rgba-unorm-srgb", "bc4-r-unorm", "bc4-r-snorm", "bc5-rg-unorm", "bc5-rg-snorm", "bc6h-rgb-ufloat", "bc6h-rgb-float", "bc7-rgba-unorm", "bc7-rgba-unorm-srgb", "etc2-rgb8unorm", "etc2-rgb8unorm-srgb", "etc2-rgb8a1unorm", "etc2-rgb8a1unorm-srgb", "etc2-rgba8unorm", "etc2-rgba8unorm-srgb", "eac-r11unorm", "eac-r11snorm", "eac-rg11unorm", "eac-rg11snorm", "astc-4x4-unorm", "astc-4x4-unorm-srgb", "astc-5x4-unorm", "astc-5x4-unorm-srgb", "astc-5x5-unorm", "astc-5x5-unorm-srgb", "astc-6x5-unorm", "astc-6x5-unorm-srgb", "astc-6x6-unorm", "astc-6x6-unorm-srgb", "astc-8x5-unorm", "astc-8x5-unorm-srgb", "astc-8x6-unorm", "astc-8x6-unorm-srgb", "astc-8x8-unorm", "astc-8x8-unorm-srgb", "astc-10x5-unorm", "astc-10x5-unorm-srgb", "astc-10x6-unorm", "astc-10x6-unorm-srgb", "astc-10x8-unorm", "astc-10x8-unorm-srgb", "astc-10x10-unorm", "astc-10x10-unorm-srgb", "astc-12x10-unorm", "astc-12x10-unorm-srgb", "astc-12x12-unorm", "astc-12x12-unorm-srgb", ],
  23. QueryType: ["occlusion", "timestamp", ],
  24. VertexStepMode: ["vertex", "instance", "vertex-buffer-not-used", ],
  25. VertexFormat: [undefined, "uint8x2", "uint8x4", "sint8x2", "sint8x4", "unorm8x2", "unorm8x4", "snorm8x2", "snorm8x4", "uint16x2", "uint16x4", "sint16x2", "sint16x4", "unorm16x2", "unorm16x4", "snorm16x2", "snorm16x4", "float16x2", "float16x4", "float32", "float32x2", "float32x3", "float32x4", "uint32", "uint32x2", "uint32x3", "uint32x4", "sint32", "sint32x2", "sint32x3", "sint32x4", ],
  26. PrimitiveTopology: ["point-list", "line-list", "line-strip", "triangle-list", "triangle-strip", ],
  27. IndexFormat: [undefined, "uint16", "uint32", ],
  28. FrontFace: ["ccw", "cw", ],
  29. CullMode: ["none", "front", "back", ],
  30. AddressMode: ["repeat", "mirror-repeat", "clamp-to-edge", ],
  31. FilterMode: ["nearest", "linear", ],
  32. MipmapFilterMode: ["nearest", "linear", ],
  33. CompareFunction: [undefined, "never", "less", "less-equal", "greater", "greater-equal", "equal", "not-equal", "always", ],
  34. TextureDimension: ["1d", "2d", "3d", ],
  35. ErrorType: ["no-error", "validation", "out-of-memory", "internal", "unknown", "device-lost", ],
  36. WGSLFeatureName: [undefined, "readonly_and_readwrite_storage_textures", "packed_4x8_integer_dot_product", "unrestricted_pointer_parameters", "pointer_composite_access", ],
  37. PowerPreference: [undefined, "low-power", "high-performance", ],
  38. CompositeAlphaMode: ["auto", "opaque", "premultiplied", "unpremultiplied", "inherit", ],
  39. StencilOperation: ["keep", "zero", "replace", "invert", "increment-clamp", "decrement-clamp", "increment-wrap", "decrement-wrap", ],
  40. BlendOperation: ["add", "subtract", "reverse-subtract", "min", "max", ],
  41. BlendFactor: ["zero", "one", "src", "one-minus-src", "src-alpha", "one-minus-src-alpha", "dst", "one-minus-dst", "dst-alpha", "one-minus-dst-alpha", "src-alpha-saturated", "constant", "one-minus-constant", ],
  42. PresentMode: ["fifo", "fifo-relaxed", "immediate", "mailbox", ],
  43. TextureAspect: ["all", "stencil-only", "depth-only"],
  44. DeviceLostReason: [undefined, "unknown", "destroyed"],
  45. };
  46. /** @type {WebGPUObjectManager<{}>} */
  47. this.instances = new WebGPUObjectManager("Instance", this.mem);
  48. /** @type {WebGPUObjectManager<GPUAdapter>} */
  49. this.adapters = new WebGPUObjectManager("Adapter", this.mem);
  50. /** @type {WebGPUObjectManager<GPUBindGroup>} */
  51. this.bindGroups = new WebGPUObjectManager("BindGroup", this.mem);
  52. /** @type {WebGPUObjectManager<GPUBindGroupLayout>} */
  53. this.bindGroupLayouts = new WebGPUObjectManager("BindGroupLayout", this.mem);
  54. /** @type {WebGPUObjectManager<{ buffer: GPUBuffer, mapping: ?{ range: ArrayBuffer, ptr: number, size: number } }>} */
  55. this.buffers = new WebGPUObjectManager("Buffer", this.mem);
  56. /** @type {WebGPUObjectManager<GPUDevice>} */
  57. this.devices = new WebGPUObjectManager("Device", this.mem);
  58. /** @type {WebGPUObjectManager<GPUCommandBuffer>} */
  59. this.commandBuffers = new WebGPUObjectManager("CommandBuffer", this.mem);
  60. /** @type {WebGPUObjectManager<GPUCommandEncoder>} */
  61. this.commandEncoders = new WebGPUObjectManager("CommandEncoder", this.mem);
  62. /** @type {WebGPUObjectManager<GPUComputePassEncoder>} */
  63. this.computePassEncoders = new WebGPUObjectManager("ComputePassEncoder", this.mem);
  64. /** @type {WebGPUObjectManager<GPURenderPassEncoder>} */
  65. this.renderPassEncoders = new WebGPUObjectManager("RenderPassEncoder", this.mem);
  66. /** @type {WebGPUObjectManager<GPUQuerySet>} */
  67. this.querySets = new WebGPUObjectManager("QuerySet", this.mem);
  68. /** @type {WebGPUObjectManager<GPUComputePipeline>} */
  69. this.computePipelines = new WebGPUObjectManager("ComputePipeline", this.mem);
  70. /** @type {WebGPUObjectManager<GPUPipelineLayout>} */
  71. this.pipelineLayouts = new WebGPUObjectManager("PipelineLayout", this.mem);
  72. /** @type {WebGPUObjectManager<GPUQueue>} */
  73. this.queues = new WebGPUObjectManager("Queue", this.mem);
  74. /** @type {WebGPUObjectManager<GPURenderBundle>} */
  75. this.renderBundles = new WebGPUObjectManager("RenderBundle", this.mem);
  76. /** @type {WebGPUObjectManager<GPURenderBundleEncoder>} */
  77. this.renderBundleEncoders = new WebGPUObjectManager("RenderBundleEncoder", this.mem);
  78. /** @type {WebGPUObjectManager<GPURenderPipeline>} */
  79. this.renderPipelines = new WebGPUObjectManager("RenderPipeline", this.mem);
  80. /** @type {WebGPUObjectManager<GPUSampler>} */
  81. this.samplers = new WebGPUObjectManager("Sampler", this.mem);
  82. /** @type {WebGPUObjectManager<GPUShaderModule>} */
  83. this.shaderModules = new WebGPUObjectManager("ShaderModule", this.mem);
  84. /** @type {WebGPUObjectManager<HTMLCanvasElement>} */
  85. this.surfaces = new WebGPUObjectManager("Surface", this.mem);
  86. /** @type {WebGPUObjectManager<GPUTexture>} */
  87. this.textures = new WebGPUObjectManager("Texture", this.mem);
  88. /** @type {WebGPUObjectManager<GPUTextureView>} */
  89. this.textureViews = new WebGPUObjectManager("TextureView", this.mem);
  90. }
  91. /**
  92. * @param {number|BigInt} src
  93. * @returns {number|BigInt}
  94. */
  95. uint(src) {
  96. if (this.mem.intSize == 8) {
  97. return BigInt(src);
  98. } else if (this.mem.intSize == 4) {
  99. return src;
  100. } else {
  101. throw new Error("unreachable");
  102. }
  103. }
  104. /**
  105. * @param {number|BigInt} src
  106. * @returns {number}
  107. */
  108. unwrapBigInt(src) {
  109. if (typeof src == "number") {
  110. return src;
  111. }
  112. const MAX_SAFE_INTEGER = 9007199254740991n;
  113. if (typeof src != "bigint") {
  114. throw new TypeError(`unwrapBigInt got invalid param of type ${typeof src}`);
  115. }
  116. if (src > MAX_SAFE_INTEGER) {
  117. throw new Error(`unwrapBigInt precision would be lost converting ${src}`);
  118. }
  119. return Number(src);
  120. }
  121. /**
  122. * @param {boolean} condition
  123. * @param {string} message
  124. */
  125. assert(condition, message = "assertion failure") {
  126. if (!condition) {
  127. throw new Error(message);
  128. }
  129. }
  130. /**
  131. * @template T
  132. *
  133. * @param {number} count
  134. * @param {number} start
  135. * @param {function(number): T} decoder
  136. * @param {number} stride
  137. * @returns {Array<T>}
  138. */
  139. array(count, start, decoder, stride) {
  140. if (count == 0) {
  141. return [];
  142. }
  143. this.assert(start != 0);
  144. const out = [];
  145. for (let i = 0; i < count; i += 1) {
  146. out.push(decoder.call(this, start));
  147. start += stride;
  148. }
  149. return out;
  150. }
  151. /**
  152. * @param {string} name
  153. * @param {number} ptr
  154. * @returns {`GPU${name}`}
  155. */
  156. enumeration(name, ptr) {
  157. const int = this.mem.loadI32(ptr);
  158. this.assert(this.enums[name], `Unknown enumeration "${name}"`);
  159. return this.enums[name][int];
  160. }
  161. /**
  162. * @param {GPUSupportedFeatures} features
  163. * @param {number} ptr
  164. * @returns {BigInt|number}
  165. */
  166. genericEnumerateFeatures(features, ptr) {
  167. const availableFeatures = [];
  168. this.enums.FeatureName.forEach((feature, value) => {
  169. if (!feature) {
  170. return;
  171. }
  172. if (features.has(feature)) {
  173. availableFeatures.push(value);
  174. }
  175. });
  176. if (ptr != 0) {
  177. for (let i = 0; i < availableFeatures.length; i += 1) {
  178. this.mem.storeI32(ptr + (i * 4), availableFeatures[i]);
  179. }
  180. }
  181. return this.uint(availableFeatures.length);
  182. }
  183. /**
  184. * @param {GPUSupportedLimits} limits
  185. * @param {number} ptr
  186. */
  187. genericGetLimits(limits, supportedLimitsPtr) {
  188. this.assert(supportedLimitsPtr != 0);
  189. const limitsPtr = supportedLimitsPtr + 8;
  190. this.mem.storeU32(limitsPtr + 0, limits.maxTextureDimension1D);
  191. this.mem.storeU32(limitsPtr + 4, limits.maxTextureDimension2D);
  192. this.mem.storeU32(limitsPtr + 8, limits.maxTextureDimension3D);
  193. this.mem.storeU32(limitsPtr + 12, limits.maxTextureArrayLayers);
  194. this.mem.storeU32(limitsPtr + 16, limits.maxBindGroups);
  195. this.mem.storeU32(limitsPtr + 20, limits.maxBindGroupsPlusVertexBuffers);
  196. this.mem.storeU32(limitsPtr + 24, limits.maxBindingsPerBindGroup);
  197. this.mem.storeU32(limitsPtr + 28, limits.maxDynamicUniformBuffersPerPipelineLayout);
  198. this.mem.storeU32(limitsPtr + 32, limits.maxDynamicStorageBuffersPerPipelineLayout);
  199. this.mem.storeU32(limitsPtr + 36, limits.maxSampledTexturesPerShaderStage);
  200. this.mem.storeU32(limitsPtr + 40, limits.maxSamplersPerShaderStage);
  201. this.mem.storeU32(limitsPtr + 44, limits.maxStorageBuffersPerShaderStage);
  202. this.mem.storeU32(limitsPtr + 48, limits.maxStorageTexturesPerShaderStage);
  203. this.mem.storeU32(limitsPtr + 52, limits.maxUniformBuffersPerShaderStage);
  204. this.mem.storeU64(limitsPtr + 56, limits.maxUniformBufferBindingSize);
  205. this.mem.storeU64(limitsPtr + 64, limits.maxStorageBufferBindingSize);
  206. this.mem.storeU32(limitsPtr + 72, limits.minUniformBufferOffsetAlignment);
  207. this.mem.storeU32(limitsPtr + 76, limits.minStorageBufferOffsetAlignment);
  208. this.mem.storeU32(limitsPtr + 80, limits.maxVertexBuffers);
  209. this.mem.storeU64(limitsPtr + 88, limits.maxBufferSize);
  210. this.mem.storeU32(limitsPtr + 96, limits.maxVertexAttributes);
  211. this.mem.storeU32(limitsPtr + 100, limits.maxVertexBufferArrayStride);
  212. this.mem.storeU32(limitsPtr + 104, limits.maxInterStageShaderComponents);
  213. this.mem.storeU32(limitsPtr + 108, limits.maxInterStageShaderVariables);
  214. this.mem.storeU32(limitsPtr + 112, limits.maxColorAttachments);
  215. this.mem.storeU32(limitsPtr + 116, limits.maxColorAttachmentBytesPerSample);
  216. this.mem.storeU32(limitsPtr + 120, limits.maxComputeWorkgroupStorageSize);
  217. this.mem.storeU32(limitsPtr + 124, limits.maxComputeInvocationsPerWorkgroup);
  218. this.mem.storeU32(limitsPtr + 128, limits.maxComputeWorkgroupSizeX);
  219. this.mem.storeU32(limitsPtr + 132, limits.maxComputeWorkgroupSizeY);
  220. this.mem.storeU32(limitsPtr + 136, limits.maxComputeWorkgroupSizeZ);
  221. this.mem.storeU32(limitsPtr + 140, limits.maxComputeWorkgroupsPerDimension);
  222. return true;
  223. }
  224. /**
  225. * @param {number} ptr
  226. * @returns {GPUFeatureName}
  227. */
  228. FeatureNamePtr(ptr) {
  229. return this.FeatureName(this.mem.loadI32(ptr));
  230. }
  231. /**
  232. * @param {number} featureInt
  233. * @returns {GPUFeatureName}
  234. */
  235. FeatureName(featureInt) {
  236. return this.enums.FeatureName[featureInt];
  237. }
  238. /**
  239. * @param {number} ptr
  240. * @returns {GPUSupportedLimits}
  241. */
  242. RequiredLimitsPtr(ptr) {
  243. const start = this.mem.loadPtr(ptr);
  244. if (start == 0) {
  245. return undefined;
  246. }
  247. return this.Limits(start + 8);
  248. }
  249. /**
  250. * @param {number} start
  251. * @return {GPUSupportedLimits}
  252. */
  253. Limits(start) {
  254. const limitU32 = (ptr) => {
  255. const value = this.mem.loadU32(ptr);
  256. if (value == 0xFFFFFFFF) { // LIMIT_32_UNDEFINED.
  257. return undefined;
  258. }
  259. return value;
  260. };
  261. const limitU64 = (ptr) => {
  262. const part1 = this.mem.loadU32(ptr);
  263. const part2 = this.mem.loadU32(ptr + 4);
  264. if (part1 != 0xFFFFFFFF || part2 != 0xFFFFFFFF) { // LIMIT_64_UNDEFINED.
  265. return this.mem.loadU64(ptr);
  266. }
  267. return undefined;
  268. };
  269. return {
  270. maxTextureDimension1D: limitU32(start + 0),
  271. maxTextureDimension2D: limitU32(start + 4),
  272. maxTextureDimension3D: limitU32(start + 8),
  273. maxTextureArrayLayers: limitU32(start + 12),
  274. maxBindGroups: limitU32(start + 16),
  275. maxBindGroupsPlusVertexBuffers: limitU32(start + 20),
  276. maxBindingsPerBindGroup: limitU32(start + 24),
  277. maxDynamicUniformBuffersPerPipelineLayout: limitU32(start + 28),
  278. maxDynamicStorageBuffersPerPipelineLayout: limitU32(start + 32),
  279. maxSampledTexturesPerShaderStage: limitU32(start + 36),
  280. maxSamplersPerShaderStage: limitU32(start + 40),
  281. maxStorageBuffersPerShaderStage: limitU32(start + 44),
  282. maxStorageTexturesPerShaderStage: limitU32(start + 48),
  283. maxUniformBuffersPerShaderStage: limitU32(start + 52),
  284. maxUniformBufferBindingSize: limitU64(start + 56),
  285. maxStorageBufferBindingSize: limitU64(start + 64),
  286. minUniformBufferOffsetAlignment: limitU32(start + 72),
  287. minStorageBufferOffsetAlignment: limitU32(start + 76),
  288. maxVertexBuffers: limitU32(start + 80),
  289. maxBufferSize: limitU64(start + 88),
  290. maxVertexAttributes: limitU32(start + 96),
  291. maxVertexBufferArrayStride: limitU32(start + 100),
  292. maxInterStageShaderComponents: limitU32(start + 104),
  293. maxInterStageShaderVariables: limitU32(start + 108),
  294. maxColorAttachments: limitU32(start + 112),
  295. maxColorAttachmentBytesPerSample: limitU32(start + 116),
  296. maxComputeWorkgroupStorageSize: limitU32(start + 120),
  297. maxComputeInvocationsPerWorkgroup: limitU32(start + 124),
  298. maxComputeWorkgroupSizeX: limitU32(start + 128),
  299. maxComputeWorkgroupSizeY: limitU32(start + 132),
  300. maxComputeWorkgroupSizeZ: limitU32(start + 136),
  301. maxComputeWorkgroupsPerDimension: limitU32(start + 140),
  302. };
  303. }
  304. /**
  305. * @param {number} start
  306. * @returns {GPUQueueDescriptor}
  307. */
  308. QueueDescriptor(start) {
  309. return {
  310. label: this.mem.loadCstring(start + 4),
  311. };
  312. }
  313. /**
  314. * @param {number} ptr
  315. * @returns {GPUComputePassTimestampWrites}
  316. */
  317. ComputePassTimestampWritesPtr(ptr) {
  318. const start = this.mem.loadPtr(ptr);
  319. if (start == 0) {
  320. return undefined;
  321. }
  322. return {
  323. querySet: this.querySets.get(this.mem.loadPtr(start + 0)),
  324. beginningOfPassWriteIndex: this.mem.loadU32(start + 4),
  325. endOfPassWriteIndex: this.mem.loadU32(start + 8),
  326. };
  327. }
  328. /**
  329. * @param {number} start
  330. * @returns {GPURenderPassColorAttachment}
  331. */
  332. RenderPassColorAttachment(start) {
  333. const viewIdx = this.mem.loadPtr(start + 4);
  334. const resolveTargetIdx = this.mem.loadPtr(start + 12);
  335. let depthSlice = this.mem.loadU32(start + 8);
  336. if (depthSlice == 0xFFFFFFFF) { // DEPTH_SLICE_UNDEFINED.
  337. depthSlice = undefined;
  338. }
  339. return {
  340. view: viewIdx > 0 ? this.textureViews.get(viewIdx) : undefined,
  341. resolveTarget: resolveTargetIdx > 0 ? this.textureViews.get(resolveTargetIdx) : undefined,
  342. depthSlice: depthSlice,
  343. loadOp: this.enumeration("LoadOp", start + 16),
  344. storeOp: this.enumeration("StoreOp", start + 20),
  345. clearValue: this.Color(start + 24),
  346. };
  347. }
  348. /**
  349. * @param {number} start
  350. * @returns {GPUColor}
  351. */
  352. Color(start) {
  353. return {
  354. r: this.mem.loadF64(start + 0),
  355. g: this.mem.loadF64(start + 8),
  356. b: this.mem.loadF64(start + 16),
  357. a: this.mem.loadF64(start + 24),
  358. };
  359. }
  360. /**
  361. * @param {number} ptr
  362. * @returns {GPURenderPassDepthStencilAttachment}
  363. */
  364. RenderPassDepthStencilAttachmentPtr(ptr) {
  365. const start = this.mem.loadPtr(ptr);
  366. if (start == 0) {
  367. return undefined;
  368. }
  369. return {
  370. view: this.textureViews.get(this.mem.loadPtr(start + 0)),
  371. depthLoadOp: this.enumeration("LoadOp", start + 4),
  372. depthStoreOp: this.enumeration("StoreOp", start + 8),
  373. depthClearValue: this.mem.loadF32(start + 12),
  374. depthReadOnly: this.mem.loadB32(start + 16),
  375. stencilLoadOp: this.enumeration("LoadOp", start + 20),
  376. stencilStoreOp: this.enumeration("StoreOp", start + 24),
  377. stencilClearValue: this.mem.loadF32(start + 28),
  378. stencilReadOnly: this.mem.loadB32(start + 32),
  379. };
  380. }
  381. /**
  382. * @param {number} ptr
  383. * @returns {undefined|GPUQuerySet}
  384. */
  385. QuerySet(ptr) {
  386. ptr = this.mem.loadPtr(ptr);
  387. if (ptr == 0) {
  388. return undefined;
  389. }
  390. return this.querySets.get(ptr);
  391. }
  392. /**
  393. * @param {number} ptr
  394. * @returns {GPURenderPassTimestampWrites}
  395. */
  396. RenderPassTimestampWritesPtr(ptr) {
  397. return this.ComputePassTimestampWritesPtr(ptr);
  398. }
  399. /**
  400. * @param {number} start
  401. * @returns {GPUImageDataLayout}
  402. */
  403. TextureDataLayout(start) {
  404. return {
  405. offset: this.mem.loadU64(start + 8),
  406. bytesPerRow: this.mem.loadU32(start + 16),
  407. rowsPerImage: this.mem.loadU32(start + 20),
  408. };
  409. }
  410. /**
  411. * @param {number} start
  412. * @returns {GPUImageCopyBuffer}
  413. */
  414. ImageCopyBuffer(start) {
  415. return {
  416. ...this.TextureDataLayout(start + 8),
  417. buffer: this.buffers.get(this.mem.loadPtr(start + 32)).buffer,
  418. };
  419. }
  420. /**
  421. * @param {number} start
  422. * @returns {GPUImageCopyTexture}
  423. */
  424. ImageCopyTexture(start) {
  425. return {
  426. texture: this.textures.get(this.mem.loadPtr(start + 4)),
  427. mipLevel: this.mem.loadU32(start + 8),
  428. origin: this.Origin3D(start + 12),
  429. aspect: this.enumeration("TextureAspect", start + 24),
  430. };
  431. }
  432. /**
  433. * @param {number} start
  434. * @returns {GPUOrigin3D}
  435. */
  436. Origin3D(start) {
  437. return {
  438. x: this.mem.loadU32(start + 0),
  439. y: this.mem.loadU32(start + 4),
  440. z: this.mem.loadU32(start + 8),
  441. };
  442. }
  443. /**
  444. * @param {number} start
  445. * @returns {GPUExtent3D}
  446. */
  447. Extent3D(start) {
  448. return {
  449. width: this.mem.loadU32(start + 0),
  450. height: this.mem.loadU32(start + 4),
  451. depthOrArrayLayers: this.mem.loadU32(start + 8),
  452. };
  453. }
  454. /**
  455. * @param {number} start
  456. * @returns {GPUBindGroupEntry}
  457. */
  458. BindGroupEntry(start) {
  459. const buffer = this.mem.loadPtr(start + 8);
  460. const sampler = this.mem.loadPtr(start + 32);
  461. const textureView = this.mem.loadPtr(start + 36);
  462. /** @type {GPUBindingResource} */
  463. let resource;
  464. if (buffer > 0) {
  465. resource = {
  466. buffer: this.buffers.get(buffer).buffer,
  467. offset: this.mem.loadU64(start + 16),
  468. size: this.mem.loadU64(start + 24),
  469. }
  470. } else if (sampler > 0) {
  471. resource = this.samplers.get(sampler);
  472. } else if (textureView > 0) {
  473. resource = this.textureViews.get(textureView);
  474. }
  475. return {
  476. binding: this.mem.loadU32(start + 4),
  477. resource: resource,
  478. };
  479. }
  480. /**
  481. * @param {number} start
  482. * @returns {GPUBindGroupLayoutEntry}
  483. */
  484. BindGroupLayoutEntry(start) {
  485. const entry = {
  486. binding: this.mem.loadU32(start + 4),
  487. visibility: this.mem.loadU32(start + 8),
  488. buffer: this.BufferBindingLayout(start + 16),
  489. sampler: this.SamplerBindingLayout(start + 40),
  490. texture: this.TextureBindingLayout(start + 48),
  491. storageTexture: this.StorageTextureBindingLayout(start + 64),
  492. };
  493. if (!entry.buffer.type) {
  494. entry.buffer = undefined;
  495. }
  496. if (!entry.sampler.type) {
  497. entry.sampler = undefined;
  498. }
  499. if (!entry.texture.sampleType) {
  500. entry.texture = undefined;
  501. }
  502. if (!entry.storageTexture.access) {
  503. entry.storageTexture = undefined;
  504. }
  505. return entry;
  506. }
  507. /**
  508. * @param {number} start
  509. * @returns {GPUBufferBindingLayout}
  510. */
  511. BufferBindingLayout(start) {
  512. return {
  513. type: this.enumeration("BufferBindingType", start + 4),
  514. hasDynamicOffset: this.mem.loadB32(start + 8),
  515. minBindingSize: this.mem.loadU64(start + 16),
  516. };
  517. }
  518. /**
  519. * @param {number} start
  520. * @returns {GPUSamplerBindingLayout}
  521. */
  522. SamplerBindingLayout(start) {
  523. return {
  524. type: this.enumeration("SamplerBindingType", start + 4),
  525. };
  526. }
  527. /**
  528. * @param {number} start
  529. * @returns {GPUTextureBindingLayout}
  530. */
  531. TextureBindingLayout(start) {
  532. return {
  533. sampleType: this.enumeration("TextureSampleType", start + 4),
  534. viewDimension: this.enumeration("TextureViewDimension", start + 8),
  535. multisampled: this.mem.loadB32(start + 12),
  536. };
  537. }
  538. /**
  539. * @param {number} start
  540. * @returns {GPUStorageTextureBindingLayout}
  541. */
  542. StorageTextureBindingLayout(start) {
  543. return {
  544. access: this.enumeration("StorageTextureAccess", start + 4),
  545. format: this.enumeration("TextureFormat", start + 8),
  546. viewDimension: this.enumeration("TextureViewDimension", start + 12),
  547. };
  548. }
  549. /**
  550. * @param {number} start
  551. * @returns {GPUProgrammableStage}
  552. */
  553. ProgrammableStageDescriptor(start) {
  554. const constantsArray = this.array(
  555. this.mem.loadUint(start + 8 + this.mem.intSize),
  556. this.mem.loadPtr(start + 8 + this.mem.intSize*2),
  557. this.ConstantEntry,
  558. 16,
  559. );
  560. return {
  561. module: this.shaderModules.get(this.mem.loadPtr(start + 4)),
  562. entryPoint: this.mem.loadCstring(start + 8),
  563. constants: constantsArray.reduce((prev, curr) => {
  564. prev[curr.key] = curr.value;
  565. return prev;
  566. }, {}),
  567. };
  568. }
  569. /**
  570. * @param {number} start
  571. * @returns {{ key: string, value: number }}
  572. */
  573. ConstantEntry(start) {
  574. return {
  575. key: this.mem.loadCstring(start + 4),
  576. value: this.mem.loadF64(start + 8),
  577. };
  578. }
  579. /**
  580. * @param {number} start
  581. * @returns {GPUComputePipelineDescriptor}
  582. */
  583. ComputePipelineDescriptor(start) {
  584. const layoutIdx = this.mem.loadPtr(start + 8)
  585. return {
  586. label: this.mem.loadCstring(start + 4),
  587. layout: layoutIdx > 0 ? this.pipelineLayouts.get(layoutIdx) : undefined,
  588. compute: this.ProgrammableStageDescriptor(start + 8 + this.mem.intSize),
  589. };
  590. }
  591. /**
  592. * @param {number} start
  593. * @returns {GPUVertexState}
  594. */
  595. VertexState(start) {
  596. let off = 8 + this.mem.intSize;
  597. const constantsArray = this.array(
  598. this.mem.loadUint(start + off),
  599. this.mem.loadPtr(start + off + this.mem.intSize),
  600. this.ConstantEntry,
  601. 16,
  602. );
  603. off += this.mem.intSize * 2;
  604. return {
  605. module: this.shaderModules.get(this.mem.loadPtr(start + 4)),
  606. entryPoint: this.mem.loadCstring(start + 8),
  607. constants: constantsArray.reduce((prev, curr) => {
  608. prev[curr.key] = curr.value;
  609. return prev;
  610. }, {}),
  611. buffers: this.array(
  612. this.mem.loadUint(start + off),
  613. this.mem.loadPtr(start + off + this.mem.intSize),
  614. this.VertexBufferLayout,
  615. this.mem.intSize == 8 ? 32 : 24,
  616. ),
  617. };
  618. }
  619. /**
  620. * @param {number} start
  621. * @returns {?GPUVertexBufferLayout}
  622. */
  623. VertexBufferLayout(start) {
  624. const stepMode = this.enumeration("VertexStepMode", start + 8);
  625. if (stepMode == "vertex-buffer-not-used") {
  626. return null;
  627. }
  628. return {
  629. arrayStride: this.mem.loadU64(start + 0),
  630. stepMode: stepMode,
  631. attributes: this.array(
  632. this.mem.loadUint(start + 8 + this.mem.intSize),
  633. this.mem.loadPtr(start + 8 + this.mem.intSize*2),
  634. this.VertexAttribute,
  635. 24,
  636. ),
  637. };
  638. }
  639. /**
  640. * @param {number} start
  641. * @returns {GPUVertexAttribute}
  642. */
  643. VertexAttribute(start) {
  644. return {
  645. format: this.enumeration("VertexFormat", start + 0),
  646. offset: this.mem.loadU64(start + 8),
  647. shaderLocation: this.mem.loadU32(start + 16),
  648. };
  649. }
  650. /**
  651. * @param {number} start
  652. * @returns {GPUPrimitiveState}
  653. */
  654. PrimitiveState(start) {
  655. let unclippedDepth = undefined;
  656. const nextInChain = this.mem.loadPtr(start);
  657. if (nextInChain != 0) {
  658. const nextInChainType = this.mem.loadI32(nextInChain + 4);
  659. // PrimitiveDepthClipControl = 0x00000007,
  660. if (nextInChainType == 7) {
  661. unclippedDepth = this.mem.loadB32(nextInChain + 8);
  662. }
  663. }
  664. return {
  665. topology: this.enumeration("PrimitiveTopology", start + 4),
  666. stripIndexFormat: this.enumeration("IndexFormat", start + 8),
  667. frontFace: this.enumeration("FrontFace", start + 12),
  668. cullMode: this.enumeration("CullMode", start + 16),
  669. unclippedDepth: unclippedDepth,
  670. };
  671. }
  672. /**
  673. * @param {number} start
  674. * @returns {GPURenderPipelineDescriptor}
  675. */
  676. RenderPipelineDescriptor(start) {
  677. const layoutIdx = this.mem.loadPtr(start + 8);
  678. const offs = this.mem.intSize == 8 ? [64, 84, 88, 104] : [40, 60, 64, 80];
  679. return {
  680. label: this.mem.loadCstring(start + 4),
  681. layout: layoutIdx > 0 ? this.pipelineLayouts.get(layoutIdx) : undefined,
  682. vertex: this.VertexState(start + 8 + this.mem.intSize),
  683. primitive: this.PrimitiveState(start + offs[0]),
  684. depthStencil: this.DepthStencilStatePtr(start + offs[1]),
  685. multisample: this.MultisampleState(start + offs[2]),
  686. fragment: this.FragmentStatePtr(start + offs[3]),
  687. };
  688. }
  689. /**
  690. * @param {number} start
  691. * @returns {GPUShaderModuleCompilationHint}
  692. */
  693. ShaderModuleCompilationHint(start) {
  694. return {
  695. entryPoint: this.mem.loadCstring(start + 4),
  696. layout: this.pipelineLayouts.get(this.mem.loadPtr(start + 8)),
  697. };
  698. }
  699. /**
  700. * @param {number} ptr
  701. * @returns {?GPUDepthStencilState}
  702. */
  703. DepthStencilStatePtr(ptr) {
  704. const start = this.mem.loadPtr(ptr);
  705. if (start == 0) {
  706. return undefined;
  707. }
  708. return {
  709. format: this.enumeration("TextureFormat", start + 4),
  710. depthWriteEnabled: this.mem.loadB32(start + 8),
  711. depthCompare: this.enumeration("CompareFunction", start + 12),
  712. stencilFront: this.StencilFaceState(start + 16),
  713. stencilBack: this.StencilFaceState(start + 32),
  714. stencilReadMask: this.mem.loadU32(start + 48),
  715. stencilWriteMask: this.mem.loadU32(start + 52),
  716. depthBias: this.mem.loadI32(start + 56),
  717. depthBiasSlopeScale: this.mem.loadF32(start + 60),
  718. depthBiasClamp: this.mem.loadF32(start + 64),
  719. };
  720. }
  721. /**
  722. * @param {number} start
  723. * @returns {GPUStencilFaceState}
  724. */
  725. StencilFaceState(start) {
  726. return {
  727. compare: this.enumeration("CompareFunction", start + 0),
  728. failOp: this.enumeration("StencilOperation", start + 4),
  729. depthFailOp: this.enumeration("StencilOperation", start + 8),
  730. passOp: this.enumeration("StencilOperation", start + 12),
  731. };
  732. }
  733. /**
  734. * @param {number} start
  735. * @returns {GPUMultisampleState}
  736. */
  737. MultisampleState(start) {
  738. return {
  739. count: this.mem.loadU32(start + 4),
  740. mask: this.mem.loadU32(start + 8),
  741. alphaToCoverageEnabled: this.mem.loadB32(start + 12),
  742. };
  743. }
  744. /**
  745. * @param {number} ptr
  746. * @returns {?GPUFragmentState}
  747. */
  748. FragmentStatePtr(ptr) {
  749. const start = this.mem.loadPtr(ptr);
  750. if (start == 0) {
  751. return undefined;
  752. }
  753. let off = 8 + this.mem.intSize;
  754. const constantsArray = this.array(
  755. this.mem.loadUint(start + off),
  756. this.mem.loadPtr(start + off + this.mem.intSize),
  757. this.ConstantEntry,
  758. 16,
  759. );
  760. off += this.mem.intSize * 2;
  761. return {
  762. module: this.shaderModules.get(this.mem.loadPtr(start + 4)),
  763. entryPoint: this.mem.loadCstring(start + 8),
  764. constants: constantsArray.reduce((prev, curr) => {
  765. prev[curr.key] = curr.value;
  766. return prev;
  767. }, {}),
  768. targets: this.array(
  769. this.mem.loadUint(start + off),
  770. this.mem.loadPtr(start + off + this.mem.intSize),
  771. this.ColorTargetState,
  772. 16,
  773. ),
  774. };
  775. }
  776. /**
  777. * @param {number} start
  778. * @returns {GPUColorTargetState}
  779. */
  780. ColorTargetState(start) {
  781. return {
  782. format: this.enumeration("TextureFormat", start + 4),
  783. blend: this.BlendStatePtr(start + 8),
  784. writeMask: this.mem.loadU32(start + 12),
  785. };
  786. }
  787. /**
  788. * @param {number} ptr
  789. * @returns {?GPUBlendState}
  790. */
  791. BlendStatePtr(ptr) {
  792. const start = this.mem.loadPtr(ptr);
  793. if (start == 0) {
  794. return undefined;
  795. }
  796. return {
  797. color: this.BlendComponent(start + 0),
  798. alpha: this.BlendComponent(start + 12),
  799. };
  800. }
  801. /**
  802. * @param {number} start
  803. * @returns {?GPUBlendComponent}
  804. */
  805. BlendComponent(start) {
  806. return {
  807. operation: this.enumeration("BlendOperation", start + 0),
  808. srcFactor: this.enumeration("BlendFactor", start + 4),
  809. dstFactor: this.enumeration("BlendFactor", start + 8),
  810. };
  811. }
  812. getInterface() {
  813. return {
  814. /**
  815. * @param {0|number} descriptorPtr
  816. * @returns {number}
  817. */
  818. wgpuCreateInstance: (descriptorPtr) => {
  819. if (!navigator.gpu) {
  820. console.error("WebGPU is not supported by this browser");
  821. return 0;
  822. }
  823. return this.instances.create({});
  824. },
  825. /**
  826. * @param {number} deviceIdx
  827. * @param {number} procNamePtr
  828. * @returns {number}
  829. */
  830. wgpuGetProcAddress: (deviceIdx, procNamePtr) => {
  831. console.error(`unimplemented: wgpuGetProcAddress`);
  832. return 0;
  833. },
  834. /* ---------------------- Adapter ---------------------- */
  835. /**
  836. * @param {number} adapterIdx
  837. * @param {number} featuresPtr
  838. * @returns {number|BigInt}
  839. */
  840. wgpuAdapterEnumerateFeatures: (adapterIdx, featuresPtr) => {
  841. const adapter = this.adapters.get(adapterIdx);
  842. return this.genericEnumerateFeatures(adapter.features, featuresPtr);
  843. },
  844. /**
  845. * @param {number} adapterIdx
  846. * @param {number} supportedLimitsPtr
  847. * @returns {boolean}
  848. */
  849. wgpuAdapterGetLimits: (adapterIdx, supportedLimitsPtr) => {
  850. const adapter = this.adapters.get(adapterIdx);
  851. return this.genericGetLimits(adapter.limits, supportedLimitsPtr);
  852. },
  853. /**
  854. * @param {number} adapterIdx
  855. * @param {number} infoPtr
  856. */
  857. wgpuAdapterGetInfo: (adapterIdx, infoPtr) => {
  858. this.assert(infoPtr != 0);
  859. // WebGPU backend.
  860. this.mem.storeI32(infoPtr + 20, 2);
  861. // Unknown adapter.
  862. this.mem.storeI32(infoPtr + 24, 3);
  863. // NOTE: I don't think getting the other fields in this struct is possible.
  864. // `adapter.requestAdapterInfo` is deprecated.
  865. },
  866. /**
  867. * @param {number} infoPtr
  868. */
  869. wgpuAdapterInfoFreeMembers: (infoPtr) => {
  870. // NOTE: nothing to free.
  871. },
  872. /**
  873. * @param {number} adapterIdx
  874. * @param {number} featureInt
  875. * @returns {boolean}
  876. */
  877. wgpuAdapterHasFeature: (adapterIdx, featureInt) => {
  878. const adapter = this.adapters.get(adapterIdx);
  879. return adapter.features.has(this.enums.FeatureName[featureInt]);
  880. },
  881. /**
  882. * @param {number} adapterIdx
  883. * @param {0|number} descriptorPtr
  884. * @param {number} callbackPtr
  885. * @param {0|number} userdata
  886. */
  887. wgpuAdapterRequestDevice: async (adapterIdx, descriptorPtr, callbackPtr, userdata) => {
  888. const adapter = this.adapters.get(adapterIdx);
  889. const callback = this.mem.exports.__indirect_function_table.get(callbackPtr);
  890. /** @type {GPUDeviceDescriptor} */
  891. let descriptor;
  892. if (descriptorPtr != 0) {
  893. descriptor = {
  894. label: this.mem.loadCstring(descriptorPtr + 4),
  895. requiredFeatures: this.array(
  896. this.mem.loadUint(descriptorPtr + 8),
  897. this.mem.loadPtr(descriptorPtr + 8 + this.mem.intSize),
  898. this.FeatureNamePtr,
  899. 4,
  900. ),
  901. requiredLimits: this.RequiredLimitsPtr(descriptorPtr + 8 + this.mem.intSize + 4),
  902. defaultQueue: this.QueueDescriptor( descriptorPtr + 8 + this.mem.intSize + 4 + 4),
  903. };
  904. }
  905. let device;
  906. let deviceIdx;
  907. try {
  908. device = await adapter.requestDevice(descriptor);
  909. deviceIdx = this.devices.create(device);
  910. // NOTE: don't callback here, any errors that happen later will then be caught by the catch here.
  911. } catch (e) {
  912. const messageLength = new TextEncoder().encode(e.message).length;
  913. const messageAddr = this.mem.exports.wgpu_alloc(messageLength + 1);
  914. this.mem.storeString(messageAddr, e.message);
  915. callback(1, null, messageAddr, userdata);
  916. this.mem.exports.wgpu_free(messageAddr);
  917. }
  918. let callbacksPtr = descriptorPtr + 24 + this.mem.intSize;
  919. const deviceLostCallbackPtr = this.mem.loadPtr(callbacksPtr);
  920. if (deviceLostCallbackPtr != 0) {
  921. const deviceLostUserData = this.mem.loadPtr(callbacksPtr) + 4;
  922. const deviceLostCallback = this.mem.exports.__indirect_function_table.get(deviceLostCallbackPtr);
  923. device.lost.then((info) => {
  924. const reason = this.enums.DeviceLostReason.indexOf(info.reason);
  925. const messageLength = new TextEncoder().encode(info.message).length;
  926. const messageAddr = this.mem.exports.wgpu_alloc(messageLength + 1);
  927. this.mem.storeString(messageAddr, info.message);
  928. deviceLostCallback(reason, messageAddr, deviceLostUserData);
  929. this.mem.exports.wgpu_free(messageAddr);
  930. });
  931. }
  932. callbacksPtr += 8;
  933. // Skip over `nextInChain`.
  934. callbacksPtr += 4;
  935. const uncapturedErrorCallbackPtr = this.mem.loadPtr(callbacksPtr);
  936. if (uncapturedErrorCallbackPtr != 0) {
  937. const uncapturedErrorUserData = this.mem.loadPtr(callbacksPtr + 4);
  938. const uncapturedErrorCallback = this.mem.exports.__indirect_function_table.get(uncapturedErrorCallbackPtr);
  939. device.onuncapturederror = (ev) => {
  940. let status = 4; // Unknown
  941. if (ev.error instanceof GPUValidationError) {
  942. status = 1; // Validation
  943. } else if (ev.error instanceof GPUOutOfMemoryError) {
  944. status = 2; // OutOfMemory
  945. } else if (ev.error instanceof GPUInternalError) {
  946. status = 3; // Internal
  947. }
  948. const messageLength = new TextEncoder().encode(ev.error.message).length;
  949. const messageAddr = this.mem.exports.wgpu_alloc(messageLength + 1);
  950. this.mem.storeString(messageAddr, ev.error.message);
  951. uncapturedErrorCallback(status, messageAddr, uncapturedErrorUserData);
  952. this.mem.exports.wgpu_free(messageAddr);
  953. };
  954. }
  955. callback(0, deviceIdx, null, userdata);
  956. },
  957. ...this.adapters.interface(),
  958. /* ---------------------- BindGroup ---------------------- */
  959. ...this.bindGroups.interface(true),
  960. /* ---------------------- BindGroupLayout ---------------------- */
  961. ...this.bindGroupLayouts.interface(true),
  962. /* ---------------------- Buffer ---------------------- */
  963. /** @param {number} bufferIdx */
  964. wgpuBufferDestroy: (bufferIdx) => {
  965. const buffer = this.buffers.get(bufferIdx);
  966. buffer.buffer.destroy();
  967. },
  968. /**
  969. * @param {number} bufferIdx
  970. * @param {number|BigInt} offset
  971. * @param {number|BigInt} size
  972. * @returns {number}
  973. */
  974. wgpuBufferGetMappedRange: (bufferIdx, offset, size) => {
  975. const buffer = this.buffers.get(bufferIdx);
  976. offset = this.unwrapBigInt(offset);
  977. size = this.unwrapBigInt(size);
  978. this.assert(!buffer.mapping, "buffer already mapped");
  979. const range = buffer.buffer.getMappedRange(offset, size);
  980. const ptr = this.mem.exports.wgpu_alloc(range.byteLength);
  981. buffer.mapping = { range: range, ptr: ptr, size: range.byteLength };
  982. return ptr;
  983. },
  984. /**
  985. * @param {number} bufferIdx
  986. * @returns {BigInt}
  987. */
  988. wgpuBufferGetSize: (bufferIdx) => {
  989. const buffer = this.buffers.get(bufferIdx);
  990. return BigInt(buffer.buffer.size);
  991. },
  992. /**
  993. * @param {number} bufferIdx
  994. * @returns {number}
  995. */
  996. wgpuBufferGetUsage: (bufferIdx) => {
  997. const buffer = this.buffers.get(bufferIdx);
  998. return buffer.buffer.usage;
  999. },
  1000. /**
  1001. * @param {number} bufferIdx
  1002. * @param {number} mode
  1003. * @param {number|BigInt} offset
  1004. * @param {number|BigInt} size
  1005. * @param {number} callbackPtr
  1006. * @param {0|number} userdata
  1007. */
  1008. wgpuBufferMapAsync: async (bufferIdx, mode, offset, size, callbackPtr, userdata) => {
  1009. const buffer = this.buffers.get(bufferIdx);
  1010. const callback = this.mem.exports.__indirect_function_table.get(callbackPtr);
  1011. offset = this.unwrapBigInt(offset);
  1012. size = this.unwrapBigInt(size);
  1013. if (buffer.buffer.mapState == "pending") {
  1014. callback(this.enums.BufferMapAsyncStatus.MappingAlreadyPending, userdata);
  1015. } else {
  1016. let result;
  1017. try {
  1018. await buffer.buffer.mapAsync(mode, offset, size);
  1019. result = 0; // Success.
  1020. } catch(e) {
  1021. console.warn(e);
  1022. result = 2; // Unknown error.
  1023. if (e instanceof DomException) {
  1024. if (e.name == "OperationError") {
  1025. result = 1; // Validation error.
  1026. }
  1027. }
  1028. }
  1029. callback(result, userdata);
  1030. }
  1031. },
  1032. /**
  1033. * @param {number} bufferIdx
  1034. * @param {number} labelPtr
  1035. */
  1036. wgpuBufferSetLabel: (bufferIdx, labelPtr) => {
  1037. const buffer = this.buffers.get(bufferIdx);
  1038. buffer.buffer.label = this.mem.loadCstring(labelPtr);
  1039. },
  1040. /**
  1041. * @param {number} bufferIdx
  1042. */
  1043. wgpuBufferUnmap: (bufferIdx) => {
  1044. const buffer = this.buffers.get(bufferIdx);
  1045. this.assert(buffer.mapping, "buffer not mapped");
  1046. const mapping = new Uint8Array(this.mem.memory.buffer, buffer.mapping.ptr, buffer.mapping.size);
  1047. (new Uint8Array(buffer.mapping.range)).set(mapping);
  1048. buffer.buffer.unmap();
  1049. this.mem.exports.wgpu_free(buffer.mapping.ptr);
  1050. buffer.mapping = null;
  1051. },
  1052. ...this.buffers.interface(),
  1053. /* ---------------------- CommandBuffer ---------------------- */
  1054. ...this.commandBuffers.interface(true),
  1055. /* ---------------------- CommandEncoder ---------------------- */
  1056. /**
  1057. * @param {number} commandEncoderIdx
  1058. * @param {0|number} descriptorPtr
  1059. * @return {number} The compute pass encoder
  1060. */
  1061. wgpuCommandEncoderBeginComputePass: (commandEncoderIdx, descriptorPtr) => {
  1062. const commandEncoder = this.commandEncoders.get(commandEncoderIdx);
  1063. /** @type {?GPUComputePassDescriptor} */
  1064. let descriptor;
  1065. if (descriptorPtr != 0) {
  1066. descriptor = {
  1067. label: this.mem.loadCstring(descriptorPtr + 4),
  1068. timestampWrites: this.ComputePassTimestampWritesPtr(descriptorPtr + 8),
  1069. };
  1070. }
  1071. const computePassEncoder = commandEncoder.beginComputePass(descriptor);
  1072. return this.computePassEncoders.create(computePassEncoder);
  1073. },
  1074. /**
  1075. * @param {number} commandEncoderIdx
  1076. * @param {number} descriptorPtr
  1077. * @return {number} The render pass encoder
  1078. */
  1079. wgpuCommandEncoderBeginRenderPass: (commandEncoderIdx, descriptorPtr) => {
  1080. const commandEncoder = this.commandEncoders.get(commandEncoderIdx);
  1081. this.assert(descriptorPtr != 0);
  1082. let maxDrawCount = undefined;
  1083. const nextInChain = this.mem.loadPtr(descriptorPtr);
  1084. if (nextInChain != 0) {
  1085. const nextInChainType = this.mem.loadI32(nextInChain + 4);
  1086. // RenderPassDescriptorMaxDrawCount = 0x0000000F,
  1087. if (nextInChainType == 0x0000000F) {
  1088. maxDrawCount = this.mem.loadU64(nextInChain + 8);
  1089. }
  1090. }
  1091. /** @type {GPURenderPassDescriptor} */
  1092. const descriptor = {
  1093. label: this.mem.loadCstring(descriptorPtr + 4),
  1094. colorAttachments: this.array(
  1095. this.mem.loadUint(descriptorPtr + 8),
  1096. this.mem.loadPtr(descriptorPtr + 8 + this.mem.intSize),
  1097. this.RenderPassColorAttachment,
  1098. 56,
  1099. ),
  1100. depthStencilAttachment: this.RenderPassDepthStencilAttachmentPtr(descriptorPtr + 8 + this.mem.intSize + 4),
  1101. occlusionQuerySet: this.QuerySet(descriptorPtr + 8 + this.mem.intSize + 4 + 4),
  1102. timestampWrites: this.RenderPassTimestampWritesPtr(descriptorPtr + 8 + this.mem.intSize + 4 + 4),
  1103. maxDrawCount: maxDrawCount,
  1104. };
  1105. const renderPassEncoder = commandEncoder.beginRenderPass(descriptor);
  1106. return this.renderPassEncoders.create(renderPassEncoder);
  1107. },
  1108. /**
  1109. * @param {number} commandEncoderIdx
  1110. * @param {number} bufferIdx
  1111. * @param {BigInt} offset
  1112. * @param {BigInt} size
  1113. */
  1114. wgpuCommandEncoderClearBuffer: (commandEncoderIdx, bufferIdx, offset, size) => {
  1115. const commandEncoder = this.commandEncoders.get(commandEncoderIdx);
  1116. const buffer = this.buffers.get(bufferIdx);
  1117. offset = this.unwrapBigInt(offset);
  1118. size = this.unwrapBigInt(size);
  1119. commandEncoder.clearBuffer(buffer.buffer, offset, size);
  1120. },
  1121. /**
  1122. * @param {number} commandEncoderIdx
  1123. * @param {number} sourceIdx
  1124. * @param {BigInt} sourceOffset
  1125. * @param {number} destinationIdx
  1126. * @param {BigInt} destinationOffset
  1127. * @param {BigInt} size
  1128. */
  1129. wgpuCommandEncoderCopyBufferToBuffer: (commandEncoderIdx, sourceIdx, sourceOffset, destinationIdx, destinationOffset, size) => {
  1130. const commandEncoder = this.commandEncoders.get(commandEncoderIdx);
  1131. const source = this.buffers.get(sourceIdx);
  1132. const destination = this.buffers.get(destinationIdx);
  1133. sourceOffset = this.unwrapBigInt(sourceOffset);
  1134. destinationOffset = this.unwrapBigInt(destinationOffset);
  1135. size = this.unwrapBigInt(size);
  1136. commandEncoder.copyBufferToBuffer(source.buffer, sourceOffset, destination.buffer, destinationOffset, size);
  1137. },
  1138. /**
  1139. * @param {number} commandEncoderIdx
  1140. * @param {number} sourcePtr
  1141. * @param {number} destinationPtr
  1142. * @param {number} copySizePtr
  1143. */
  1144. wgpuCommandEncoderCopyBufferToTexture: (commandEncoderIdx, sourcePtr, destinationPtr, copySizePtr) => {
  1145. const commandEncoder = this.commandEncoders.get(commandEncoderIdx);
  1146. commandEncoder.copyBufferToTexture(
  1147. this.ImageCopyBuffer(sourcePtr),
  1148. this.ImageCopyTexture(destinationPtr),
  1149. this.Extent3D(copySizePtr),
  1150. );
  1151. },
  1152. /**
  1153. * @param {number} commandEncoderIdx
  1154. * @param {number} sourcePtr
  1155. * @param {number} destinationPtr
  1156. * @param {number} copySizePtr
  1157. */
  1158. wgpuCommandEncoderCopyTextureToBuffer: (commandEncoderIdx, sourcePtr, destinationPtr, copySizePtr) => {
  1159. const commandEncoder = this.commandEncoders.get(commandEncoderIdx);
  1160. commandEncoder.copyTextureToBuffer(
  1161. this.ImageCopyTexture(sourcePtr),
  1162. this.ImageCopyBuffer(destinationPtr),
  1163. this.Extent3D(copySizePtr),
  1164. );
  1165. },
  1166. /**
  1167. * @param {number} commandEncoderIdx
  1168. * @param {number} sourcePtr
  1169. * @param {number} destinationPtr
  1170. * @param {number} copySizePtr
  1171. */
  1172. wgpuCommandEncoderCopyTextureToTexture: (commandEncoderIdx, sourcePtr, destinationPtr, copySizePtr) => {
  1173. const commandEncoder = this.commandEncoders.get(commandEncoderIdx);
  1174. commandEncoder.copyTextureToTexture(
  1175. this.ImageCopyTexture(sourcePtr),
  1176. this.ImageCopyTexture(destinationPtr),
  1177. this.Extent3D(copySizePtr),
  1178. );
  1179. },
  1180. /**
  1181. * @param {number} commandEncoderIdx
  1182. * @param {0|number} descriptorPtr
  1183. * @returns {number} The command buffer.
  1184. */
  1185. wgpuCommandEncoderFinish: (commandEncoderIdx, descriptorPtr) => {
  1186. const commandEncoder = this.commandEncoders.get(commandEncoderIdx);
  1187. /** @type {undefined|GPUCommandBufferDescriptor} */
  1188. let descriptor;
  1189. if (descriptorPtr != 0) {
  1190. descriptor = {
  1191. label: this.mem.loadCstring(descriptorPtr + 4),
  1192. };
  1193. }
  1194. const commandBuffer = commandEncoder.finish(descriptor);
  1195. return this.commandBuffers.create(commandBuffer);
  1196. },
  1197. /**
  1198. * @param {number} commandEncoderIdx
  1199. * @param {number} markerLabelPtr
  1200. */
  1201. wgpuCommandEncoderInsertDebugMarker: (commandEncoderIdx, markerLabelPtr) => {
  1202. const commandEncoder = this.commandEncoders.get(commandEncoderIdx);
  1203. commandEncoder.insertDebugMarker(this.mem.loadCstring(markerLabelPtr));
  1204. },
  1205. /**
  1206. * @param {number} commandEncoderIdx
  1207. */
  1208. wgpuCommandEncoderPopDebugGroup: (commandEncoderIdx) => {
  1209. const commandEncoder = this.commandEncoders.get(commandEncoderIdx);
  1210. commandEncoder.popDebugGroup();
  1211. },
  1212. /**
  1213. * @param {number} commandEncoderIdx
  1214. * @param {number} markerLabelPtr
  1215. */
  1216. wgpuCommandEncoderPushDebugGroup: (commandEncoderIdx, groupLabelPtr) => {
  1217. const commandEncoder = this.commandEncoders.get(commandEncoderIdx);
  1218. commandEncoder.pushDebugGroup(this.mem.loadCstring(groupLabelPtr));
  1219. },
  1220. /**
  1221. * @param {number} commandEncoderIdx
  1222. * @param {number} querySetIdx
  1223. * @param {number} firstQuery
  1224. * @param {number} queryCount
  1225. * @param {number} destinationIdx
  1226. * @param {BigInt} destinationOffset
  1227. */
  1228. wgpuCommandEncoderResolveQuerySet: (commandEncoderIdx, querySetIdx, firstQuery, queryCount, destinationIdx, destinationOffset) => {
  1229. const commandEncoder = this.commandEncoders.get(commandEncoderIdx);
  1230. const querySet = this.querySets.get(querySetIdx);
  1231. const destination = this.buffers.get(destinationIdx);
  1232. destinationOffset = this.unwrapBigInt(destinationOffset);
  1233. commandEncoder.resolveQuerySet(querySet, firstQuery, queryCount, destination.buffer, destinationOffset);
  1234. },
  1235. /**
  1236. * @param {number} commandEncoderIdx
  1237. * @param {number} querySetIdx
  1238. * @param {number} queryIndex
  1239. */
  1240. wgpuCommandEncoderWriteTimestamp: (commandEncoderIdx, querySetIdx, queryIndex) => {
  1241. const commandEncoder = this.commandEncoders.get(commandEncoderIdx);
  1242. const querySet = this.querySets.get(querySetIdx);
  1243. commandEncoder.writeTimestamp(querySet, queryIndex);
  1244. },
  1245. ...this.commandEncoders.interface(true),
  1246. /* ---------------------- ComputePassEncoder ---------------------- */
  1247. /**
  1248. * @param {number} computePassEncoderIdx
  1249. * @param {number} workgroupCountX
  1250. * @param {number} workgroupCountY
  1251. * @param {number} workgroupCountZ
  1252. */
  1253. wgpuComputePassEncoderDispachWorkgroups: (computePassEncoderIdx, workgroupCountX, workgroupCountY, workgroupCountZ) => {
  1254. const computePassEncoder = this.computePassEncoders.get(computePassEncoderIdx);
  1255. computePassEncoder.dispatchWorkgroups(workgroupCountX, workgroupCountY, workgroupCountZ);
  1256. },
  1257. /**
  1258. * @param {number} computePassEncoderIdx
  1259. * @param {number} indirectBufferIdx
  1260. * @param {BigInt} indirectOffset
  1261. */
  1262. wgpuComputePassEncoderDispachWorkgroupsIndirect: (computePassEncoderIdx, indirectBufferIdx, indirectOffset) => {
  1263. const computePassEncoder = this.computePassEncoders.get(computePassEncoderIdx);
  1264. const indirectBuffer = this.buffers.get(indirectBufferIdx);
  1265. indirectOffset = this.unwrapBigInt(indirectOffset);
  1266. computePassEncoder.dispatchWorkgroupsIndirect(indirectBuffer.buffer, indirectOffset);
  1267. },
  1268. /**
  1269. * @param {number} computePassEncoderIdx
  1270. */
  1271. wgpuComputePassEncoderEnd: (computePassEncoderIdx) => {
  1272. const computePassEncoder = this.computePassEncoders.get(computePassEncoderIdx);
  1273. computePassEncoder.end();
  1274. },
  1275. /**
  1276. * @param {number} computePassEncoderIdx
  1277. * @param {number} markerLabelPtr
  1278. */
  1279. wgpuComputePassEncoderInsertDebugMarker: (computePassEncoderIdx, markerLabelPtr) => {
  1280. const computePassEncoder = this.computePassEncoders.get(computePassEncoderIdx);
  1281. computePassEncoder.insertDebugMarker(this.mem.loadCstring(markerLabelPtr));
  1282. },
  1283. /**
  1284. * @param {number} computePassEncoderIdx
  1285. */
  1286. wgpuComputePassEncoderPopDebugGroup: (computePassEncoderIdx) => {
  1287. const computePassEncoder = this.computePassEncoders.get(computePassEncoderIdx);
  1288. computePassEncoder.popDebugGroup();
  1289. },
  1290. /**
  1291. * @param {number} computePassEncoderIdx
  1292. * @param {number} markerLabelPtr
  1293. */
  1294. wgpuComputePassEncoderPushDebugGroup: (computePassEncoderIdx, groupLabelPtr) => {
  1295. const computePassEncoder = this.computePassEncoders.get(computePassEncoderIdx);
  1296. computePassEncoder.pushDebugGroup(this.mem.loadCstring(groupLabelPtr));
  1297. },
  1298. /**
  1299. * @param {number} computePassEncoderIdx
  1300. * @param {number} groupIndex
  1301. * @param {0|number} groupIdx
  1302. * @param {number|BigInt} dynamicOffsetCount
  1303. * @param {number} dynamicOffsetsPtr
  1304. */
  1305. wgpuComputePassEncoderSetBindGroup: (computePassEncoderIdx, groupIndex, groupIdx, dynamicOffsetCount, dynamicOffsetsPtr) => {
  1306. const computePassEncoder = this.computePassEncoders.get(computePassEncoderIdx);
  1307. dynamicOffsetCount = this.unwrapBigInt(dynamicOffsetCount);
  1308. let bindGroup;
  1309. if (groupIdx != 0) {
  1310. bindGroup = this.bindGroups.get(groupIdx);
  1311. }
  1312. const dynamicOffsets = [];
  1313. for (let i = 0; i < dynamicOffsetCount; i += 1) {
  1314. dynamicOffsets.push(this.mem.loadU32(dynamicOffsetsPtr));
  1315. dynamicOffsetsPtr += 4;
  1316. }
  1317. computePassEncoder.setBindGroup(groupIndex, bindGroup, dynamicOffsets);
  1318. },
  1319. /**
  1320. * @param {number} computePassEncoderIdx
  1321. * @param {number} pipelineIdx
  1322. */
  1323. wgpuComputePassEncoderSetPipeline: (computePassEncoderIdx, pipelineIdx) => {
  1324. const computePassEncoder = this.computePassEncoders.get(computePassEncoderIdx);
  1325. const pipeline = this.computePipelines.get(pipelineIdx);
  1326. computePassEncoder.setPipeline(pipeline);
  1327. },
  1328. ...this.computePassEncoders.interface(true),
  1329. /* ---------------------- ComputePipeline ---------------------- */
  1330. /**
  1331. * @param {number} computePipelineIdx
  1332. * @param {number} groupIndex
  1333. * @returns {number}
  1334. */
  1335. wgpuComputePipelineGetBindGroupLayout: (computePipelineIdx, groupIndex) => {
  1336. const computePipeline = this.computePipelines.get(computePipelineIdx);
  1337. const bindGroupLayout = computePipeline.getBindGroupLayout(groupIndex);
  1338. return this.bindGroupLayouts.create(bindGroupLayout);
  1339. },
  1340. ...this.computePipelines.interface(true),
  1341. /* ---------------------- Device ---------------------- */
  1342. /**
  1343. * @param {number} deviceIdx
  1344. * @param {number} descriptorPtr
  1345. * @returns {number} The bind group.
  1346. */
  1347. wgpuDeviceCreateBindGroup: (deviceIdx, descriptorPtr) => {
  1348. const device = this.devices.get(deviceIdx);
  1349. this.assert(descriptorPtr != 0);
  1350. /** @type {GPUBindGroupDescriptor} */
  1351. const descriptor = {
  1352. label: this.mem.loadCstring(descriptorPtr + 4),
  1353. layout: this.bindGroupLayouts.get(this.mem.loadPtr(descriptorPtr + 8)),
  1354. entries: this.array(
  1355. this.mem.loadUint(descriptorPtr + 8 + this.mem.intSize),
  1356. this.mem.loadPtr(descriptorPtr + 8 + this.mem.intSize * 2),
  1357. this.BindGroupEntry,
  1358. 40,
  1359. ),
  1360. };
  1361. const bindGroup = device.createBindGroup(descriptor);
  1362. return this.bindGroups.create(bindGroup);
  1363. },
  1364. /**
  1365. * @param {number} deviceIdx
  1366. * @param {number} descriptorPtr
  1367. * @returns {number} The bind group layout.
  1368. */
  1369. wgpuDeviceCreateBindGroupLayout: (deviceIdx, descriptorPtr) => {
  1370. const device = this.devices.get(deviceIdx);
  1371. this.assert(descriptorPtr != 0);
  1372. /** @type {GPUBindGroupLayoutDescriptor} */
  1373. const descriptor = {
  1374. label: this.mem.loadCstring(descriptorPtr + 4),
  1375. entries: this.array(
  1376. this.mem.loadUint(descriptorPtr + 8),
  1377. this.mem.loadPtr(descriptorPtr + 8 + this.mem.intSize),
  1378. this.BindGroupLayoutEntry,
  1379. 80,
  1380. ),
  1381. };
  1382. const bindGroupLayout = device.createBindGroupLayout(descriptor);
  1383. return this.bindGroupLayouts.create(bindGroupLayout);
  1384. },
  1385. /**
  1386. * @param {number} deviceIdx
  1387. * @param {number} descriptorPtr
  1388. * @returns {number} The buffer.
  1389. */
  1390. wgpuDeviceCreateBuffer: (deviceIdx, descriptorPtr) => {
  1391. const device = this.devices.get(deviceIdx);
  1392. this.assert(descriptorPtr != 0);
  1393. /** @type {GPUBufferDescriptor} */
  1394. const descriptor = {
  1395. label: this.mem.loadCstring(descriptorPtr + 4),
  1396. usage: this.mem.loadU32(descriptorPtr + 8),
  1397. size: this.mem.loadU64(descriptorPtr + 16),
  1398. mappedAtCreation: this.mem.loadB32(descriptorPtr + 24),
  1399. };
  1400. const buffer = device.createBuffer(descriptor);
  1401. return this.buffers.create({buffer: buffer, mapping: null});
  1402. },
  1403. /**
  1404. * @param {number} deviceIdx
  1405. * @param {0|number} descriptorPtr
  1406. * @returns {number} The command encoder.
  1407. */
  1408. wgpuDeviceCreateCommandEncoder: (deviceIdx, descriptorPtr) => {
  1409. const device = this.devices.get(deviceIdx);
  1410. /** @type {GPUCommandEncoderDescriptor} */
  1411. let descriptor;
  1412. if (descriptor != 0) {
  1413. descriptor = {
  1414. label: this.mem.loadCstring(descriptorPtr + 4),
  1415. };
  1416. }
  1417. const commandEncoder = device.createCommandEncoder(descriptor);
  1418. return this.commandEncoders.create(commandEncoder);
  1419. },
  1420. /**
  1421. * @param {number} deviceIdx
  1422. * @param {number} descriptorPtr
  1423. * @returns {number} The compute pipeline.
  1424. */
  1425. wgpuDeviceCreateComputePipeline: (deviceIdx, descriptorPtr) => {
  1426. const device = this.devices.get(deviceIdx);
  1427. this.assert(descriptorPtr != 0);
  1428. const computePipeline = device.createComputePipeline(this.ComputePipelineDescriptor(descriptorPtr));
  1429. return this.computePipelines.create(computePipeline);
  1430. },
  1431. /**
  1432. * @param {number} deviceIdx
  1433. * @param {number} descriptorPtr
  1434. * @param {number} callbackPtr
  1435. * @param {number} userdata
  1436. */
  1437. wgpuDeviceCreateComputePipelineAsync: async (deviceIdx, descriptorPtr, callbackPtr, userdata) => {
  1438. const device = this.devices.get(deviceIdx);
  1439. const callback = this.mem.exports.__indirect_function_table.get(callbackPtr);
  1440. this.assert(descriptorPtr != 0);
  1441. let result;
  1442. let resultIdx;
  1443. try {
  1444. const computePipeline = await device.createComputePipelineAsync(this.ComputePipelineDescriptor(descriptorPtr));
  1445. resultIdx = this.computePipelines.create(computePipeline);
  1446. result = 0; /* Success */
  1447. // NOTE: don't callback here, any errors that happen later will then be caught by the catch here.
  1448. } catch (e) {
  1449. console.warn(e);
  1450. result = 5; /* Unknown error */
  1451. }
  1452. callback(result, resultIdx, null, userdata);
  1453. },
  1454. /**
  1455. * @param {number} deviceIdx
  1456. * @param {number} descriptorPtr
  1457. * @returns {number} The pipeline layout.
  1458. */
  1459. wgpuDeviceCreatePipelineLayout: (deviceIdx, descriptorPtr) => {
  1460. const device = this.devices.get(deviceIdx);
  1461. this.assert(descriptorPtr != 0);
  1462. /** @type {GPUPipelineLayoutDescriptor} */
  1463. const descriptor = {
  1464. label: this.mem.loadCstring(descriptorPtr + 4),
  1465. bindGroupLayouts: this.array(
  1466. this.mem.loadUint(descriptorPtr + 8),
  1467. this.mem.loadPtr(descriptorPtr + 8 + this.mem.intSize),
  1468. (ptr) => this.bindGroupLayouts.get(this.mem.loadPtr(ptr)),
  1469. 4,
  1470. ),
  1471. };
  1472. const pipelineLayout = device.createPipelineLayout(descriptor);
  1473. return this.pipelineLayouts.create(pipelineLayout);
  1474. },
  1475. /**
  1476. * @param {number} deviceIdx
  1477. * @param {number} descriptorPtr
  1478. * @returns {number} The query set.
  1479. */
  1480. wgpuDeviceCreateQuerySet: (deviceIdx, descriptorPtr) => {
  1481. const device = this.devices.get(deviceIdx);
  1482. this.assert(descriptorPtr != 0);
  1483. /** @type {GPUQuerySetDescriptor} */
  1484. const descriptor = {
  1485. label: this.mem.loadCstring(descriptorPtr + 4),
  1486. type: this.QueryType(descriptorPtr + 8),
  1487. count: this.mem.loadU32(descriptorPtr + 12),
  1488. };
  1489. const querySet = device.createQuerySet(descriptor);
  1490. return this.querySets.create(querySet);
  1491. },
  1492. /**
  1493. * @param {number} deviceIdx
  1494. * @param {number} descriptorPtr
  1495. * @returns {number} The query set.
  1496. */
  1497. wgpuDeviceCreateRenderBundleEncoder: (deviceIdx, descriptorPtr) => {
  1498. const device = this.devices.get(deviceIdx);
  1499. this.assert(descriptorPtr != 0);
  1500. /** @type {GPURenderBundleEncoderDescriptor} */
  1501. const descriptor = {
  1502. label: this.mem.loadCstring(descriptorPtr + 4),
  1503. colorFormats: this.array(
  1504. this.mem.loadUint(descriptorPtr + 8),
  1505. this.mem.loadPtr(descriptorPtr + 8 + this.mem.intSize),
  1506. this.TextureFormat,
  1507. 4,
  1508. ),
  1509. depthStencilFormat: this.enumeration("TextureFormat", descriptorPtr + 8 + this.mem.intSize + 4),
  1510. sampleCount: this.mem.loadU32(descriptorPtr + 8 + this.mem.intSize + 8),
  1511. depthReadOnly: this.mem.loadB32(descriptorPtr + 8 + this.mem.intSize + 12),
  1512. stencilReadOnly: this.mem.loadB32(descriptorPtr + 8 + this.mem.intSize + 16),
  1513. };
  1514. const renderBundleEncoder = device.createRenderBundleEncoder(descriptor);
  1515. return this.renderBundleEncoders.create(renderBundleEncoder);
  1516. },
  1517. /**
  1518. * @param {number} deviceIdx
  1519. * @param {number} descriptorPtr
  1520. * @returns {number} The render pipeline.
  1521. */
  1522. wgpuDeviceCreateRenderPipeline: (deviceIdx, descriptorPtr) => {
  1523. const device = this.devices.get(deviceIdx);
  1524. this.assert(descriptorPtr != 0);
  1525. const descriptor = this.RenderPipelineDescriptor(descriptorPtr);
  1526. const renderPipeline = device.createRenderPipeline(descriptor);
  1527. return this.renderPipelines.create(renderPipeline);
  1528. },
  1529. /**
  1530. * @param {number} deviceIdx
  1531. * @param {number} descriptorPtr
  1532. * @param {number} callbackPtr
  1533. * @param {number} userdata
  1534. */
  1535. wgpuDeviceCreateRenderPipelineAsync: async (deviceIdx, descriptorPtr, callbackPtr, userdata) => {
  1536. const device = this.devices.get(deviceIdx);
  1537. const callback = this.mem.exports.__indirect_function_table.get(callbackPtr);
  1538. this.assert(descriptorPtr != 0);
  1539. let result;
  1540. let resultIdx;
  1541. try {
  1542. const renderPipeline = await device.createRenderPipelineAsync(this.RenderPipelineDescriptor(descriptorPtr));
  1543. resultIdx = this.renderPipelines.create(renderPipeline);
  1544. result = 0; /* Success */
  1545. // NOTE: don't callback here, any errors that happen later will then be caught by the catch here.
  1546. } catch (e) {
  1547. console.warn(e);
  1548. result = 5; /* Unknown error */
  1549. }
  1550. callback(result, resultIdx, null, userdata);
  1551. },
  1552. /**
  1553. * @param {number} deviceIdx
  1554. * @param {0|number} descriptorPtr
  1555. * @returns {number} The sampler.
  1556. */
  1557. wgpuDeviceCreateSampler: (deviceIdx, descriptorPtr) => {
  1558. const device = this.devices.get(deviceIdx);
  1559. /** @type {?GPUSamplerDescriptor} */
  1560. let descriptor;
  1561. if (descriptorPtr != 0) {
  1562. descriptor = {
  1563. label: this.mem.loadCstring(descriptorPtr + 4),
  1564. addressModeU: this.enumeration("AddressMode", descriptorPtr + 8),
  1565. addressModeV: this.enumeration("AddressMode", descriptorPtr + 12),
  1566. addressModeW: this.enumeration("AddressMode", descriptorPtr + 16),
  1567. magFilter: this.enumeration("FilterMode", descriptorPtr + 20),
  1568. minFilter: this.enumeration("FilterMode", descriptorPtr + 24),
  1569. mipMapFilter: this.enumeration("MipmapFilterMode", descriptorPtr + 28),
  1570. lodMinClamp: this.mem.loadF32(descriptorPtr + 32),
  1571. lodMaxClamp: this.mem.loadF32(descriptorPtr + 36),
  1572. compare: this.enumeration("CompareFunction", descriptorPtr + 40),
  1573. maxAnisotropy: this.mem.loadU16(descriptorPtr + 44),
  1574. };
  1575. }
  1576. const sampler = device.createSampler(descriptor);
  1577. return this.samplers.create(sampler);
  1578. },
  1579. /**
  1580. * @param {number} deviceIdx
  1581. * @param {number} descriptorPtr
  1582. * @returns {number} The shader module.
  1583. */
  1584. wgpuDeviceCreateShaderModule: (deviceIdx, descriptorPtr) => {
  1585. const device = this.devices.get(deviceIdx);
  1586. this.assert(descriptorPtr != 0);
  1587. const nextInChain = this.mem.loadPtr(descriptorPtr);
  1588. const nextInChainType = this.mem.loadI32(nextInChain + 4);
  1589. // ShaderModuleWGSLDescriptor = 0x00000006,
  1590. if (nextInChainType != 6) {
  1591. throw new TypeError(`Descriptor type should be 'ShaderModuleWGSLDescriptor', got ${nextInChainType}`);
  1592. }
  1593. /** @type {GPUShaderModuleDescriptor} */
  1594. const descriptor = {
  1595. label: this.mem.loadCstring(descriptorPtr + 4),
  1596. code: this.mem.loadCstring(nextInChain + 8),
  1597. compilationHints: this.array(
  1598. this.mem.loadUint(descriptorPtr + 8),
  1599. this.mem.loadPtr(descriptorPtr + 8 + this.mem.intSize),
  1600. this.ShaderModuleCompilationHint,
  1601. 12,
  1602. ),
  1603. };
  1604. const shaderModule = device.createShaderModule(descriptor);
  1605. return this.shaderModules.create(shaderModule);
  1606. },
  1607. /**
  1608. * @param {number} deviceIdx
  1609. * @param {number} descriptorPtr
  1610. * @returns {number} The texture.
  1611. */
  1612. wgpuDeviceCreateTexture: (deviceIdx, descriptorPtr) => {
  1613. const device = this.devices.get(deviceIdx);
  1614. this.assert(descriptorPtr != 0);
  1615. /** @type {GPUTextureDescriptor} */
  1616. const descriptor = {
  1617. label: this.mem.loadCstring(descriptorPtr + 4),
  1618. usage: this.mem.loadU32(descriptorPtr + 8),
  1619. dimension: this.enumeration("TextureDimension", descriptorPtr + 12),
  1620. size: this.Extent3D(descriptorPtr + 16),
  1621. format: this.enumeration("TextureFormat", descriptorPtr + 28),
  1622. mipLevelCount: this.mem.loadU32(descriptorPtr + 32),
  1623. sampleCount: this.mem.loadU32(descriptorPtr + 36),
  1624. viewFormats: this.array(
  1625. this.mem.loadUint(descriptorPtr + 40),
  1626. this.mem.loadPtr(descriptorPtr + 40 + this.mem.intSize),
  1627. (ptr) => this.enumeration("TextureFormat", ptr),
  1628. 4,
  1629. ),
  1630. };
  1631. const texture = device.createTexture(descriptor);
  1632. return this.textures.create(texture);
  1633. },
  1634. /**
  1635. * @param {number} deviceIdx
  1636. */
  1637. wgpuDeviceDestroy: (deviceIdx) => {
  1638. const device = this.devices.get(deviceIdx);
  1639. device.destroy();
  1640. },
  1641. /**
  1642. * @param {number} deviceIdx
  1643. * @param {number} featuresPtr
  1644. * @returns {number|BigInt}
  1645. */
  1646. wgpuDeviceEnumerateFeatures: (deviceIdx, featuresPtr) => {
  1647. const device = this.devices.get(deviceIdx);
  1648. return this.genericEnumerateFeatures(device.features, featuresPtr);
  1649. },
  1650. /**
  1651. * @param {number} deviceIdx
  1652. * @param {number} limitsPtr
  1653. * @returns {boolean}
  1654. */
  1655. wgpuDeviceGetLimits: (deviceIdx, limitsPtr) => {
  1656. const device = this.devices.get(deviceIdx);
  1657. return this.genericGetLimits(device.limits, limitsPtr);
  1658. },
  1659. /**
  1660. * @param {number} deviceIdx
  1661. * @returns {number}
  1662. */
  1663. wgpuDeviceGetQueue: (deviceIdx) => {
  1664. const device = this.devices.get(deviceIdx);
  1665. return this.queues.create(device.queue);
  1666. },
  1667. /**
  1668. * @param {number} deviceIdx
  1669. * @param {number} featureInt
  1670. * @returns {boolean}
  1671. */
  1672. wgpuDeviceHasFeature: (deviceIdx, featureInt) => {
  1673. const device = this.devices.get(deviceIdx);
  1674. return device.features.has(this.enums.FeatureName[featureInt]);
  1675. },
  1676. /**
  1677. * @param {number} deviceIdx
  1678. * @param {number} callbackPtr
  1679. * @param {number} userdata
  1680. */
  1681. wgpuDevicePopErrorScope: async (deviceIdx, callbackPtr, userdata) => {
  1682. const device = this.devices.get(deviceIdx);
  1683. const callback = this.mem.exports.__indirect_function_table.get(callbackPtr);
  1684. const error = await device.popErrorScope();
  1685. if (!error) {
  1686. callback(0, null, userdata);
  1687. return;
  1688. }
  1689. console.warn(error);
  1690. let status = 4;
  1691. if (error instanceof GPUValidationError) {
  1692. status = 1;
  1693. } else if (error instanceof GPUOutOfMemoryError) {
  1694. status = 2;
  1695. } else if (error instanceof GPUInternalError) {
  1696. status = 3;
  1697. }
  1698. callback(status, null, userdata);
  1699. },
  1700. /**
  1701. * @param {number} deviceIdx
  1702. * @param {number} filterInt
  1703. */
  1704. wgpuDevicePushErrorScope: (deviceIdx, filterInt) => {
  1705. const device = this.devices.get(deviceIdx);
  1706. device.pushErrorScope(this.enums.ErrorFilter[filterInt]);
  1707. },
  1708. ...this.devices.interface(true),
  1709. /* ---------------------- Instance ---------------------- */
  1710. /**
  1711. * @param {number} instanceIdx
  1712. * @param {number} descriptorPtr
  1713. */
  1714. wgpuInstanceCreateSurface: (instanceIdx, descriptorPtr) => {
  1715. this.assert(instanceIdx > 0);
  1716. this.assert(descriptorPtr != 0);
  1717. const nextInChain = this.mem.loadPtr(descriptorPtr);
  1718. const nextInChainType = this.mem.loadI32(nextInChain + 4);
  1719. // SurfaceDescriptorFromCanvasHTMLSelector = 0x00000004,
  1720. if (nextInChainType != 4) {
  1721. throw new TypeError(`Descriptor type should be 'SurfaceDescriptorFromCanvasHTMLSelector', got ${nextInChainType}`);
  1722. }
  1723. const selector = this.mem.loadCstring(nextInChain + 8);
  1724. const surface = document.querySelector(selector);
  1725. if (!surface) {
  1726. throw new Error(`Selector '${selector}' did not match any element`);
  1727. }
  1728. if (!(surface instanceof HTMLCanvasElement)) {
  1729. throw new Error('Selector matches an element that is not a canvas');
  1730. }
  1731. return this.surfaces.create(surface);
  1732. },
  1733. /**
  1734. * @param {number} instanceIdx
  1735. * @param {number} featureInt
  1736. * @returns {boolean}
  1737. */
  1738. wgpuInstanceHasWGSLLanguageFeature: (instanceIdx, featureInt) => {
  1739. return navigator.gpu.wgslLanguageFeatures.has(this.enums.WGSLFeatureName[featureInt]);
  1740. },
  1741. /**
  1742. * @param {number} instanceIdx
  1743. */
  1744. wgpuInstanceProcessEvents: (instanceIdx) => {
  1745. console.warn("unimplemented: wgpuInstanceProcessEvents");
  1746. },
  1747. /**
  1748. * @param {number} instanceIdx
  1749. * @param {0|number} optionsPtr
  1750. * @param {number} callbackPtr
  1751. * @param {number} userdata
  1752. */
  1753. wgpuInstanceRequestAdapter: async (instanceIdx, optionsPtr, callbackPtr, userdata) => {
  1754. this.assert(instanceIdx > 0);
  1755. const callback = this.mem.exports.__indirect_function_table.get(callbackPtr);
  1756. /** @type {GPURequestAdapterOptions} */
  1757. let options;
  1758. if (optionsPtr != 0) {
  1759. options = {
  1760. powerPreference: this.enumeration("PowerPreference", optionsPtr + 8),
  1761. forceFallbackAdapter: this.mem.loadB32(optionsPtr + 16),
  1762. };
  1763. }
  1764. let adapterIdx;
  1765. try {
  1766. const adapter = await navigator.gpu.requestAdapter(options);
  1767. adapterIdx = this.adapters.create(adapter);
  1768. // NOTE: don't callback here, any errors that happen later will then be caught by the catch here.
  1769. } catch(e) {
  1770. console.warn(e);
  1771. callback(2, null, null, userdata);
  1772. }
  1773. callback(0, adapterIdx, null, userdata);
  1774. },
  1775. ...this.instances.interface(false),
  1776. /* ---------------------- PipelineLayout ---------------------- */
  1777. ...this.pipelineLayouts.interface(true),
  1778. /* ---------------------- QuerySet ---------------------- */
  1779. /**
  1780. * @param {number} querySetIdx
  1781. */
  1782. wgpuQuerySetDestroy: (querySetIdx) => {
  1783. const querySet = this.querySets.get(querySetIdx);
  1784. querySet.destroy();
  1785. },
  1786. /**
  1787. * @param {number} querySetIdx
  1788. * @returns {number}
  1789. */
  1790. wgpuQuerySetGetCount: (querySetIdx) => {
  1791. const querySet = this.querySets.get(querySetIdx);
  1792. return querySet.count;
  1793. },
  1794. /**
  1795. * @param {number} querySetIdx
  1796. * @returns {number}
  1797. */
  1798. wgpuQuerySetGetType: (querySetIdx) => {
  1799. const querySet = this.querySets.get(querySetIdx);
  1800. return this.enums.QueryType.indexOf(querySet.type);
  1801. },
  1802. ...this.querySets.interface(true),
  1803. /* ---------------------- Queue ---------------------- */
  1804. /**
  1805. * @param {number} queueIdx
  1806. * @param {number} callbackPtr
  1807. * @param {number} userdata
  1808. */
  1809. wgpuQueueOnSubmittedWorkDone: async (queueIdx, callbackPtr, userdata) => {
  1810. const queue = this.queues.get(queueIdx);
  1811. const callback = this.mem.exports.__indirect_function_table.get(callbackPtr);
  1812. let result;
  1813. try {
  1814. await queue.onSubmittedWorkDone();
  1815. result = 0;
  1816. } catch(e) {
  1817. console.warn(e);
  1818. result = 1;
  1819. }
  1820. callback(result, userdata);
  1821. },
  1822. /**
  1823. * @param {number} queueIdx
  1824. * @param {BigInt|number} commandCount
  1825. * @param {number} commandsPtr
  1826. */
  1827. wgpuQueueSubmit: (queueIdx, commandCount, commandsPtr) => {
  1828. const queue = this.queues.get(queueIdx);
  1829. const commands = this.array(
  1830. this.unwrapBigInt(commandCount),
  1831. commandsPtr,
  1832. (ptr) => this.commandBuffers.get(this.mem.loadPtr(ptr)),
  1833. 4,
  1834. );
  1835. queue.submit(commands);
  1836. },
  1837. /**
  1838. * @param {number} queueIdx
  1839. * @param {number} bufferIdx
  1840. * @param {BigInt} bufferOffset
  1841. * @param {number} dataPtr
  1842. * @param {number|BigInt} size
  1843. */
  1844. wgpuQueueWriteBuffer: (queueIdx, bufferIdx, bufferOffset, dataPtr, size) => {
  1845. const queue = this.queues.get(queueIdx);
  1846. const buffer = this.buffers.get(bufferIdx);
  1847. bufferOffset = this.unwrapBigInt(bufferOffset);
  1848. size = this.unwrapBigInt(size);
  1849. queue.writeBuffer(buffer.buffer, bufferOffset, this.mem.loadBytes(dataPtr, size), 0, size);
  1850. },
  1851. /**
  1852. * @param {number} queueIdx
  1853. * @param {number} destinationPtr
  1854. * @param {number} dataPtr
  1855. * @param {number|BigInt} dataSize
  1856. * @param {number} dataLayoutPtr
  1857. * @param {number} writeSizePtr
  1858. */
  1859. wgpuQueueWriteTexture: (queueIdx, destinationPtr, dataPtr, dataSize, dataLayoutPtr, writeSizePtr) => {
  1860. const queue = this.queues.get(queueIdx);
  1861. const destination = this.ImageCopyTexture(destinationPtr);
  1862. dataSize = this.unwrapBigInt(dataSize);
  1863. const dataLayout = this.TextureDataLayout(dataLayoutPtr);
  1864. const writeSize = this.Extent3D(writeSizePtr);
  1865. queue.writeTexture(destination, this.mem.loadBytes(dataPtr, dataSize), dataLayout, writeSize);
  1866. },
  1867. ...this.queues.interface(true),
  1868. /* ---------------------- RenderBundle ---------------------- */
  1869. ...this.renderBundles.interface(true),
  1870. /* ---------------------- RenderBundleEncoder ---------------------- */
  1871. /**
  1872. * @param {number} renderBundleEncoderIdx
  1873. * @param {number} vertexCount
  1874. * @param {number} instanceCount
  1875. * @param {number} firstVertex
  1876. * @param {number} firstInstance
  1877. */
  1878. wgpuRenderBundleEncoderDraw: (renderBundleEncoderIdx, vertexCount, instanceCount, firstVertex, firstInstance) => {
  1879. const renderBundleEncoder = this.renderBundleEncoders.get(renderBundleEncoderIdx);
  1880. renderBundleEncoder.draw(vertexCount, instanceCount, firstVertex, firstInstance);
  1881. },
  1882. /**
  1883. * @param {number} renderBundleEncoderIdx
  1884. * @param {number} indexCount
  1885. * @param {number} instanceCount
  1886. * @param {number} firstIndex
  1887. * @param {number} baseVertex
  1888. * @param {number} firstInstance
  1889. */
  1890. wgpuRenderBundleEncoderDrawIndexed: (renderBundleEncoderIdx, indexCount, instanceCount, firstIndex, baseVertex, firstInstance) => {
  1891. const renderBundleEncoder = this.renderBundleEncoders.get(renderBundleEncoderIdx);
  1892. renderBundleEncoder.drawIndexed(indexCount, instanceCount, firstIndex, baseVertex, firstInstance);
  1893. },
  1894. /**
  1895. * @param {number} renderBundleEncoderIdx
  1896. * @param {number} indirectBufferIdx
  1897. * @param {BigInt} indirectOffset
  1898. */
  1899. wgpuRenderBundleEncoderDrawIndexedIndirect: (renderBundleEncoderIdx, indirectBufferIdx, indirectOffset) => {
  1900. const renderBundleEncoder = this.renderBundleEncoders.get(renderBundleEncoderIdx);
  1901. indirectOffset = this.unwrapBigInt(indirectOffset);
  1902. const buffer = this.buffers.get(indirectBufferIdx);
  1903. renderBundleEncoder.drawIndexedIndirect(buffer.buffer, indirectOffset);
  1904. },
  1905. /**
  1906. * @param {number} renderBundleEncoderIdx
  1907. * @param {number} indirectBufferIdx
  1908. * @param {BigInt} indirectOffset
  1909. */
  1910. wgpuRenderBundleEncoderDrawIndirect: (renderBundleEncoderIdx, indirectBufferIdx, indirectOffset) => {
  1911. const renderBundleEncoder = this.renderBundleEncoders.get(renderBundleEncoderIdx);
  1912. indirectOffset = this.unwrapBigInt(indirectOffset);
  1913. const buffer = this.buffers.get(indirectBufferIdx);
  1914. renderBundleEncoder.drawIndirect(buffer.buffer, indirectOffset);
  1915. },
  1916. /**
  1917. * @param {number} renderBundleEncoderIdx
  1918. * @param {0|number} descriptorPtr
  1919. * @returns {number}
  1920. */
  1921. wgpuRenderBundleEncoderFinish: (renderBundleEncoderIdx, descriptorPtr) => {
  1922. const renderBundleEncoder = this.renderBundleEncoders.get(renderBundleEncoderIdx);
  1923. /** @type {?GPURenderBundleDescriptor} */
  1924. let descriptor;
  1925. if (descriptorPtr != 0) {
  1926. descriptor = {
  1927. label: this.mem.loadCstring(descriptorPtr + 4),
  1928. };
  1929. }
  1930. const renderBundle = renderBundleEncoder.finish(descriptor);
  1931. return this.renderBundles.create(renderBundle);
  1932. },
  1933. /**
  1934. * @param {number} renderBundleEncoderIdx
  1935. * @param {number} markerLabelPtr
  1936. */
  1937. wgpuRenderBundleEncoderInsertDebugMarker: (renderBundleEncoderIdx, markerLabelPtr) => {
  1938. const renderBundleEncoder = this.renderBundleEncoders.get(renderBundleEncoderIdx);
  1939. this.assert(markerLabelPtr != 0);
  1940. const markerLabel = this.mem.loadCstring(markerLabelPtr);
  1941. renderBundleEncoder.insertDebugMarker(markerLabel);
  1942. },
  1943. /**
  1944. * @param {number} renderBundleEncoderIdx
  1945. */
  1946. wgpuRenderBundleEncoderPopDebugGroup: (renderBundleEncoderIdx) => {
  1947. const renderBundleEncoder = this.renderBundleEncoders.get(renderBundleEncoderIdx);
  1948. renderBundleEncoder.popDebugGroup();
  1949. },
  1950. /**
  1951. * @param {number} renderBundleEncoderIdx
  1952. * @param {number} groupLabelPtr
  1953. */
  1954. wgpuRenderBundleEncoderPushDebugGroup: (renderBundleEncoderIdx, groupLabelPtr) => {
  1955. const renderBundleEncoder = this.renderBundleEncoders.get(renderBundleEncoderIdx);
  1956. this.assert(groupLabelPtr!= 0);
  1957. const groupLabel = this.mem.loadCstring(groupLabelPtr);
  1958. renderBundleEncoder.pushDebugGroup(groupLabel);
  1959. },
  1960. /**
  1961. * @param {number} renderBundleEncoderIdx
  1962. * @param {number} groupIndex
  1963. * @param {0|number} groupIdx
  1964. * @param {number|BigInt} dynamicOffsetCount
  1965. * @param {number} dynamicOffsetsPtr
  1966. */
  1967. wgpuRenderBundleEncoderSetBindGroup: (renderBundleEncoderIdx, groupIndex, groupIdx, dynamicOffsetCount, dynamicOffsetsPtr) => {
  1968. const renderBundleEncoder = this.renderBundleEncoders.get(renderBundleEncoderIdx);
  1969. let group;
  1970. if (groupIdx > 0) {
  1971. group = this.bindGroups.get(groupIdx);
  1972. }
  1973. dynamicOffsetCount = this.unwrapBigInt(dynamicOffsetCount);
  1974. const dynamicOffsets = this.array(dynamicOffsetCount, dynamicOffsetsPtr, this.mem.loadU32, 4);
  1975. renderBundleEncoder.setBindGroup(groupIndex, group, dynamicOffsets);
  1976. },
  1977. /**
  1978. * @param {number} renderBundleEncoderIdx
  1979. * @param {number} bufferIdx
  1980. * @param {number} formatInt
  1981. * @param {BigInt} offset
  1982. * @param {BigInt} size
  1983. */
  1984. wgpuRenderBundleEncoderSetIndexBuffer: (renderBundleEncoderIdx, bufferIdx, formatInt, offset, size) => {
  1985. const renderBundleEncoder = this.renderBundleEncoders.get(renderBundleEncoderIdx);
  1986. const buffer = this.buffers.get(bufferIdx);
  1987. const format = this.enums.IndexFormat[formatInt];
  1988. offset = this.unwrapBigInt(offset);
  1989. size = this.unwrapBigInt(size);
  1990. renderBundleEncoder.setIndexBuffer(buffer.buffer, format, offset, size);
  1991. },
  1992. /**
  1993. * @param {number} renderBundleEncoderIdx
  1994. * @param {number} pipelineIdx
  1995. */
  1996. wgpuRenderBundleEncoderSetPipeline: (renderBundleEncoderIdx, pipelineIdx) => {
  1997. const renderBundleEncoder = this.renderBundleEncoders.get(renderBundleEncoderIdx);
  1998. const pipeline = this.renderPipelines.get(pipelineIdx);
  1999. renderBundleEncoder.setPipeline(pipeline);
  2000. },
  2001. /**
  2002. * @param {number} renderBundleEncoderIdx
  2003. * @param {number} slot
  2004. * @param {0|number} bufferIdx
  2005. * @param {BigInt} offset
  2006. * @param {BigInt} size
  2007. */
  2008. wgpuRenderBundleEncoderSetVertexBuffer: (renderBundleEncoderIdx, slot, bufferIdx, offset, size) => {
  2009. const renderBundleEncoder = this.renderBundleEncoders.get(renderBundleEncoderIdx);
  2010. let buffer;
  2011. if (bufferIdx > 0) {
  2012. buffer = this.buffers.get(bufferIdx).buffer;
  2013. }
  2014. offset = this.unwrapBigInt(offset);
  2015. size = this.unwrapBigInt(size);
  2016. renderBundleEncoder.setVertexBuffer(slot, buffer, offset, size);
  2017. },
  2018. ...this.renderBundleEncoders.interface(true),
  2019. /* ---------------------- RenderPassEncoder ---------------------- */
  2020. /**
  2021. * @param {number} renderPassEncoderIdx
  2022. * @param {number} queryIndex
  2023. */
  2024. wgpuRenderPassEncoderBeginOcclusionQuery: (renderPassEncoderIdx, queryIndex) => {
  2025. const renderPassEncoder = this.renderPassEncoders.get(renderPassEncoderIdx);
  2026. renderPassEncoder.beginOcclusionQuery(queryIndex);
  2027. },
  2028. /**
  2029. * @param {number} renderPassEncoderIdx
  2030. * @param {number} vertexCount
  2031. * @param {number} instanceCount
  2032. * @param {number} firstVertex
  2033. * @param {number} firstInstance
  2034. */
  2035. wgpuRenderPassEncoderDraw: (renderPassEncoderIdx, vertexCount, instanceCount, firstVertex, firstInstance) => {
  2036. const renderPassEncoder = this.renderPassEncoders.get(renderPassEncoderIdx);
  2037. renderPassEncoder.draw(vertexCount, instanceCount, firstVertex, firstInstance);
  2038. },
  2039. /**
  2040. * @param {number} renderPassEncoderIdx
  2041. * @param {number} indexCount
  2042. * @param {number} instanceCount
  2043. * @param {number} firstIndex
  2044. * @param {number} baseVertex
  2045. * @param {number} firstInstance
  2046. */
  2047. wgpuRenderPassEncoderDrawIndexed: (renderPassEncoderIdx, indexCount, instanceCount, firstIndex, baseVertex, firstInstance) => {
  2048. const renderPassEncoder = this.renderPassEncoders.get(renderPassEncoderIdx);
  2049. renderPassEncoder.drawIndexed(indexCount, instanceCount, firstIndex, baseVertex, firstInstance);
  2050. },
  2051. /**
  2052. * @param {number} renderPassEncoderIdx
  2053. * @param {number} indirectBufferIdx
  2054. * @param {BigInt} indirectOffset
  2055. */
  2056. wgpuRenderPassEncoderDrawIndexedIndirect: (renderPassEncoderIdx, indirectBufferIdx, indirectOffset) => {
  2057. const renderPassEncoder = this.renderPassEncoders.get(renderPassEncoderIdx);
  2058. const buffer = this.buffers.get(indirectBufferIdx);
  2059. indirectOffset = this.unwrapBigInt(indirectOffset);
  2060. renderPassEncoder.drawIndexedIndirect(buffer.buffer, indirectOffset);
  2061. },
  2062. /**
  2063. * @param {number} renderPassEncoderIdx
  2064. * @param {number} indirectBufferIdx
  2065. * @param {BigInt} indirectOffset
  2066. */
  2067. wgpuRenderPassEncoderDrawIndirect: (renderPassEncoderIdx, indirectBufferIdx, indirectOffset) => {
  2068. const renderPassEncoder = this.renderPassEncoders.get(renderPassEncoderIdx);
  2069. const buffer = this.buffers.get(indirectBufferIdx);
  2070. indirectOffset = this.unwrapBigInt(indirectOffset);
  2071. renderPassEncoder.drawIndirect(buffer.buffer, indirectOffset);
  2072. },
  2073. /**
  2074. * @param {number} renderPassEncoderIdx
  2075. */
  2076. wgpuRenderPassEncoderEnd: (renderPassEncoderIdx) => {
  2077. const renderPassEncoder = this.renderPassEncoders.get(renderPassEncoderIdx);
  2078. renderPassEncoder.end();
  2079. },
  2080. /**
  2081. * @param {number} renderPassEncoderIdx
  2082. */
  2083. wgpuRenderPassEncoderEndOcclusionQuery: (renderPassEncoderIdx) => {
  2084. const renderPassEncoder = this.renderPassEncoders.get(renderPassEncoderIdx);
  2085. renderPassEncoder.endOcclusionQuery();
  2086. },
  2087. /**
  2088. * @param {number} renderPassEncoderIdx
  2089. * @param {number|BigInt} bundleCount
  2090. * @param {number} bundlesPtr
  2091. */
  2092. wgpuRenderPassEncoderExecuteBundles: (renderPassEncoderIdx, bundleCount, bundlesPtr) => {
  2093. const renderPassEncoder = this.renderPassEncoders.get(renderPassEncoderIdx);
  2094. bundleCount = this.unwrapBigInt(bundleCount);
  2095. const bundles = this.array(
  2096. bundleCount,
  2097. bundlesPtr,
  2098. (ptr) => this.renderBundles.get(this.mem.loadPtr(ptr)),
  2099. 4,
  2100. );
  2101. renderPassEncoder.executeBundles(bundles);
  2102. },
  2103. /**
  2104. * @param {number} renderPassEncoderIdx
  2105. * @param {number} markerLabelPtr
  2106. */
  2107. wgpuRenderPassEncoderInsertDebugMarker: (renderPassEncoderIdx, markerLabelPtr) => {
  2108. const renderPassEncoder = this.renderPassEncoders.get(renderPassEncoderIdx);
  2109. const markerLabel = this.mem.loadCstring(markerLabelPtr);
  2110. renderPassEncoder.insertDebugMarker(markerLabel);
  2111. },
  2112. /**
  2113. * @param {number} renderPassEncoderIdx
  2114. */
  2115. wgpuRenderPassEncoderPopDebugGroup: (renderPassEncoderIdx) => {
  2116. const renderPassEncoder = this.renderPassEncoders.get(renderPassEncoderIdx);
  2117. renderPassEncoder.popDebugGroup();
  2118. },
  2119. /**
  2120. * @param {number} renderPassEncoderIdx
  2121. * @param {number} groupLabelPtr
  2122. */
  2123. wgpuRenderPassEncoderPushDebugGroup: (renderPassEncoderIdx, groupLabelPtr) => {
  2124. const renderPassEncoder = this.renderPassEncoders.get(renderPassEncoderIdx);
  2125. const groupLabel = this.mem.loadCstring(groupLabelPtr);
  2126. renderPassEncoder.pushDebugGroup(groupLabel);
  2127. },
  2128. /**
  2129. * @param {number} renderPassEncoderIdx
  2130. * @param {number} groupIndex
  2131. * @param {0|number} groupIdx
  2132. * @param {number|BigInt} dynamicOffsetCount
  2133. * @param {number} dynamicOffsetsPtr
  2134. */
  2135. wgpuRenderPassEncoderSetBindGroup: (renderPassEncoderIdx, groupIndex, groupIdx, dynamicOffsetCount, dynamicOffsetsPtr) => {
  2136. const renderPassEncoder = this.renderPassEncoders.get(renderPassEncoderIdx);
  2137. let group;
  2138. if (groupIdx > 0) {
  2139. group = this.bindGroups.get(groupIdx);
  2140. }
  2141. dynamicOffsetCount = this.unwrapBigInt(dynamicOffsetCount);
  2142. const dynamicOffsets = this.array(dynamicOffsetCount, dynamicOffsetsPtr, this.mem.loadU32, 4);
  2143. renderPassEncoder.setBindGroup(groupIndex, group, dynamicOffsets);
  2144. },
  2145. /**
  2146. * @param {number} renderPassEncoderIdx
  2147. * @param {number} colorPtr
  2148. */
  2149. wgpuRenderPassEncoderSetBlendConstant: (renderPassEncoderIdx, colorPtr) => {
  2150. const renderPassEncoder = this.renderPassEncoders.get(renderPassEncoderIdx);
  2151. this.assert(colorPtr != 0);
  2152. renderPassEncoder.setBlendConstant(this.Color(colorPtr));
  2153. },
  2154. /**
  2155. * @param {number} renderPassEncoderIdx
  2156. * @param {number} bufferIdx
  2157. * @param {number} formatInt
  2158. * @param {BigInt} offset
  2159. * @param {BigInt} size
  2160. */
  2161. wgpuRenderPassEncoderSetIndexBuffer: (renderPassEncoderIdx, bufferIdx, formatInt, offset, size) => {
  2162. const renderPassEncoder = this.renderPassEncoders.get(renderPassEncoderIdx);
  2163. const buffer = this.buffers.get(bufferIdx);
  2164. const format = this.enums.IndexFormat[formatInt];
  2165. offset = this.unwrapBigInt(offset);
  2166. size = this.unwrapBigInt(size);
  2167. renderPassEncoder.setIndexBuffer(buffer.buffer, format, offset, size);
  2168. },
  2169. /**
  2170. * @param {number} renderPassEncoderIdx
  2171. * @param {number} pipelineIdx
  2172. */
  2173. wgpuRenderPassEncoderSetPipeline: (renderPassEncoderIdx, pipelineIdx) => {
  2174. const renderPassEncoder = this.renderPassEncoders.get(renderPassEncoderIdx);
  2175. const pipeline = this.renderPipelines.get(pipelineIdx);
  2176. renderPassEncoder.setPipeline(pipeline);
  2177. },
  2178. /**
  2179. * @param {number} renderPassEncoderIdx
  2180. * @param {number} x
  2181. * @param {number} y
  2182. * @param {number} width
  2183. * @param {number} height
  2184. */
  2185. wgpuRenderPassEncoderSetScissorRect: (renderPassEncoderIdx, x, y, width, height) => {
  2186. const renderPassEncoder = this.renderPassEncoders.get(renderPassEncoderIdx);
  2187. renderPassEncoder.setScissorRect(x, y, width, height);
  2188. },
  2189. /**
  2190. * @param {number} renderPassEncoderIdx
  2191. * @param {number} reference
  2192. */
  2193. wgpuRenderPassEncoderSetStencilReference: (renderPassEncoderIdx, reference) => {
  2194. const renderPassEncoder = this.renderPassEncoders.get(renderPassEncoderIdx);
  2195. renderPassEncoder.setStencilReference(reference);
  2196. },
  2197. /**
  2198. * @param {number} renderPassEncoderIdx
  2199. * @param {number} slot
  2200. * @param {0|number} bufferIdx
  2201. * @param {BigInt} offset
  2202. * @param {BigInt} size
  2203. */
  2204. wgpuRenderPassEncoderSetVertexBuffer: (renderPassEncoderIdx, slot, bufferIdx, offset, size) => {
  2205. const renderPassEncoder = this.renderPassEncoders.get(renderPassEncoderIdx);
  2206. let buffer;
  2207. if (bufferIdx > 0) {
  2208. buffer = this.buffers.get(bufferIdx).buffer;
  2209. }
  2210. offset = this.unwrapBigInt(offset);
  2211. size = this.unwrapBigInt(size);
  2212. renderPassEncoder.setVertexBuffer(slot, buffer, offset, size);
  2213. },
  2214. /**
  2215. * @param {number} renderPassEncoderIdx
  2216. * @param {number} x
  2217. * @param {number} y
  2218. * @param {number} width
  2219. * @param {number} height
  2220. * @param {number} minDepth
  2221. * @param {number} maxDepth
  2222. */
  2223. wgpuRenderPassEncoderSetViewport: (renderPassEncoderIdx, x, y, width, height, minDepth, maxDepth) => {
  2224. const renderPassEncoder = this.renderPassEncoders.get(renderPassEncoderIdx);
  2225. renderPassEncoder.setViewport(x, y, width, height, minDepth, maxDepth);
  2226. },
  2227. ...this.renderPassEncoders.interface(true),
  2228. /* ---------------------- RenderPipeline ---------------------- */
  2229. /**
  2230. * @param {number} renderPipelineIdx
  2231. * @param {number} groupIndex
  2232. * @returns {number}
  2233. */
  2234. wgpuRenderPipelineGetBindGroupLayout: (renderPipelineIdx, groupIndex) => {
  2235. const renderPipeline = this.renderPipelines.get(renderPipelineIdx);
  2236. const bindGroupLayout = renderPipeline.getBindGroupLayout(groupIndex);
  2237. return this.bindGroupLayouts.create(bindGroupLayout);
  2238. },
  2239. ...this.renderPipelines.interface(true),
  2240. /* ---------------------- Sampler ---------------------- */
  2241. ...this.samplers.interface(true),
  2242. /* ---------------------- ShaderModule ---------------------- */
  2243. /**
  2244. * @param {number} shaderModuleIdx
  2245. * @param {number} callbackPtr
  2246. * @param {number} userdata
  2247. */
  2248. wgpuShaderModuleGetCompilationInfo: async (shaderModuleIdx, callbackPtr, userdata) => {
  2249. const shaderModule = this.shaderModules.get(shaderModuleIdx);
  2250. const callback = this.mem.exports.__indirect_function_table.get(callbackPtr);
  2251. let status = 0;
  2252. let retAddr = 0;
  2253. const ptrsToFree = [];
  2254. try {
  2255. const compilationInfo = await shaderModule.getCompilationInfo();
  2256. const size = compilationInfo.messages.length * 72;
  2257. const addr = this.mem.exports.wgpu_alloc(size);
  2258. ptrsToFree.push(addr);
  2259. compilationInfo.messages.forEach((message, i) => {
  2260. const messageLength = new TextEncoder().encode(message.message).length;
  2261. const messageAddr = this.mem.exports.wgpu_alloc(messageLength);
  2262. ptrsToFree.push(messageAddr);
  2263. this.mem.storeString(messageAddr, message.message);
  2264. this.mem.storeI32(addr + (i * size) + 4);
  2265. this.mem.storeI32(addr + (i * size) + 8, this.enums.CompilationMessageType.indexOf(message.type));
  2266. this.mem.storeU64(addr + (i * size) + 16, message.lineNum);
  2267. this.mem.storeU64(addr + (i * size) + 24, message.linePos);
  2268. this.mem.storeU64(addr + (i * size) + 32, message.offset);
  2269. this.mem.storeU64(addr + (i * size) + 40, message.length);
  2270. // TODO: UTF16 units.
  2271. this.mem.storeU64(addr + (i * size) + 48, message.linePos);
  2272. this.mem.storeU64(addr + (i * size) + 56, message.offset);
  2273. this.mem.storeU64(addr + (i * size) + 64, message.length);
  2274. });
  2275. retAddr = this.mem.exports.wgpu_alloc(3*this.mem.intSize);
  2276. ptrsToFree.push(retAddr);
  2277. this.mem.storeUint(retAddr + this.mem.intSize, compilationInfo.messages.length);
  2278. this.mem.storeI32(retAddr + this.mem.intSize*2, addr);
  2279. } catch (e) {
  2280. console.warn(e);
  2281. status = 1;
  2282. }
  2283. callback(status, retAddr, userdata);
  2284. ptrsToFree.forEach(ptr => this.mem.exports.wgpu_free(ptr));
  2285. },
  2286. ...this.shaderModules.interface(true),
  2287. /* ---------------------- Surface ---------------------- */
  2288. /**
  2289. * @param {number} surfaceIdx
  2290. * @param {number} configPtr
  2291. */
  2292. wgpuSurfaceConfigure: (surfaceIdx, configPtr) => {
  2293. const surface = this.surfaces.get(surfaceIdx);
  2294. const context = surface.getContext('webgpu');
  2295. const widthOff = 16 + this.mem.intSize + 8;
  2296. surface.width = this.mem.loadU32(configPtr + widthOff);
  2297. surface.height = this.mem.loadU32(configPtr + widthOff + 4);
  2298. /** @type {GPUCanvasConfiguration} */
  2299. const config = {
  2300. device: this.devices.get(this.mem.loadPtr(configPtr + 4)),
  2301. format: this.enumeration("TextureFormat", configPtr + 8),
  2302. usage: this.mem.loadU32(configPtr + 12),
  2303. viewFormats: this.array(
  2304. this.mem.loadUint(configPtr + 16),
  2305. this.mem.loadPtr(configPtr + 16 + this.mem.intSize),
  2306. (ptr) => this.enumeration("TextureFormat", ptr),
  2307. 4,
  2308. ),
  2309. alphaMode: this.enumeration("CompositeAlphaMode", configPtr + widthOff - 4),
  2310. // // NOTE: present mode seems unused.
  2311. presentMode: this.enumeration("PresentMode", configPtr + widthOff + 4),
  2312. };
  2313. context.configure(config);
  2314. },
  2315. /**
  2316. * @param {number} surfaceIdx
  2317. * @param {number} adapterIdx
  2318. * @param {number} capabilitiesPtr
  2319. */
  2320. wgpuSurfaceGetCapabilities: (surfaceIdx, adapterIdx, capabilitiesPtr) => {
  2321. const formatStr = navigator.gpu.getPreferredCanvasFormat();
  2322. const format = this.enums.TextureFormat.indexOf(formatStr);
  2323. this.mem.storeUint(capabilitiesPtr + 8, 1);
  2324. const formatAddr = this.mem.exports.wgpu_alloc(4);
  2325. this.mem.storeI32(formatAddr, format);
  2326. this.mem.storeI32(capabilitiesPtr + 8 + this.mem.intSize, formatAddr);
  2327. // NOTE: present modes don't seem to actually do anything in JS, we can just give back a default FIFO though.
  2328. this.mem.storeUint(capabilitiesPtr + 8 + this.mem.intSize*2, 1);
  2329. const presentModesAddr = this.mem.exports.wgpu_alloc(4);
  2330. this.mem.storeI32(presentModesAddr, 0);
  2331. this.mem.storeI32(capabilitiesPtr + 8 + this.mem.intSize*3, presentModesAddr);
  2332. // Browser seems to support opaque (1) and premultiplied (2).
  2333. this.mem.storeUint(capabilitiesPtr + 8 + this.mem.intSize*4, 2);
  2334. const alphaModesAddr = this.mem.exports.wgpu_alloc(8);
  2335. this.mem.storeI32(alphaModesAddr + 0, 1); // Opaque.
  2336. this.mem.storeI32(alphaModesAddr + 4, 2); // premultiplied.
  2337. this.mem.storeI32(capabilitiesPtr + 8 + this.mem.intSize*5, alphaModesAddr);
  2338. },
  2339. /**
  2340. * @param {number} surfaceIdx
  2341. * @param {number} texturePtr
  2342. */
  2343. wgpuSurfaceGetCurrentTexture: (surfaceIdx, texturePtr) => {
  2344. const surface = this.surfaces.get(surfaceIdx);
  2345. const context = surface.getContext('webgpu');
  2346. const texture = context.getCurrentTexture();
  2347. const textureIdx = this.textures.create(texture);
  2348. this.mem.storeI32(texturePtr, textureIdx);
  2349. // TODO: determine suboptimal and/or status.
  2350. },
  2351. /**
  2352. * @param {number} surfaceIdx
  2353. */
  2354. wgpuSurfacePresent: (surfaceIdx) => {
  2355. // NOTE: Not really anything to do here.
  2356. },
  2357. /**
  2358. * @param {number} surfaceIdx
  2359. */
  2360. wgpuSurfaceUnconfigure: (surfaceIdx) => {
  2361. const surface = this.surfaces.get(surfaceIdx);
  2362. surface.getContext('webgpu').unconfigure();
  2363. },
  2364. ...this.surfaces.interface(true),
  2365. /* ---------------------- SurfaceCapabilities ---------------------- */
  2366. /**
  2367. * @param {number} surfaceCapabilitiesPtr
  2368. */
  2369. wgpuSurfaceCapabilitiesFreeMembers: (surfaceCapabilitiesPtr) => {
  2370. const formatsAddr = this.mem.loadI32(surfaceCapabilitiesPtr + this.mem.intSize*2);
  2371. this.mem.exports.wgpu_free(formatsAddr);
  2372. const presentModesAddr = this.mem.loadI32(surfaceCapabilitiesPtr + this.mem.intSize*4);
  2373. this.mem.exports.wgpu_free(presentModesAddr);
  2374. const alphaModesAddr = this.mem.loadI32(surfaceCapabilitiesPtr + this.mem.intSize*6);
  2375. this.mem.exports.wgpu_free(alphaModesAddr);
  2376. },
  2377. /* ---------------------- Texture ---------------------- */
  2378. /**
  2379. * @param {number} textureIdx
  2380. * @param {0|number} descriptorPtr
  2381. * @returns {number}
  2382. */
  2383. wgpuTextureCreateView: (textureIdx, descriptorPtr) => {
  2384. const texture = this.textures.get(textureIdx);
  2385. /** @type {?GPUTextureViewDescriptor} */
  2386. let descriptor;
  2387. if (descriptorPtr != 0) {
  2388. descriptor = {
  2389. label: this.mem.loadCstring(descriptorPtr + 4),
  2390. format: this.enumeration("TextureFormat", descriptorPtr + 8),
  2391. dimension: this.enumeration("TextureViewDimension", descriptorPtr + 12),
  2392. baseMipLevel: this.mem.loadU32(descriptorPtr + 16),
  2393. mipLevelCount: this.mem.loadU32(descriptorPtr + 20),
  2394. baseArrayLayer: this.mem.loadU32(descriptorPtr + 24),
  2395. arrayLayerCount: this.mem.loadU32(descriptorPtr + 28),
  2396. aspect: this.enumeration("TextureAspect", descriptorPtr + 32),
  2397. };
  2398. if (descriptor.arrayLayerCount == 0xFFFFFFFF) {
  2399. descriptor.arrayLayerCount = undefined;
  2400. }
  2401. if (descriptor.mipLevelCount == 0xFFFFFFFF) {
  2402. descriptor.mipLevelCount = undefined;
  2403. }
  2404. }
  2405. const textureView = texture.createView(descriptor);
  2406. return this.textureViews.create(textureView);
  2407. },
  2408. /**
  2409. * @param {number} textureIdx
  2410. */
  2411. wgpuTextureDestroy: (textureIdx) => {
  2412. const texture = this.textures.get(textureIdx);
  2413. texture.destroy();
  2414. },
  2415. /**
  2416. * @param {number} textureIdx
  2417. * @returns {number}
  2418. */
  2419. wgpuTextureDepthOrArrayLayers: (textureIdx) => {
  2420. const texture = this.textures.get(textureIdx);
  2421. return texture.depthOrArrayLayers;
  2422. },
  2423. /**
  2424. * @param {number} textureIdx
  2425. * @returns {number}
  2426. */
  2427. wgpuTextureGetDimension: (textureIdx) => {
  2428. const texture = this.textures.get(textureIdx);
  2429. return this.enums.TextureDimension.indexOf(texture.dimension);
  2430. },
  2431. /**
  2432. * @param {number} textureIdx
  2433. * @returns {number}
  2434. */
  2435. wgpuTextureGetFormat: (textureIdx) => {
  2436. const texture = this.textures.get(textureIdx);
  2437. return this.enums.TextureFormat.indexOf(texture.format);
  2438. },
  2439. /**
  2440. * @param {number} textureIdx
  2441. * @returns {number}
  2442. */
  2443. wgpuTextureGetHeight: (textureIdx) => {
  2444. const texture = this.textures.get(textureIdx);
  2445. return texture.height;
  2446. },
  2447. /**
  2448. * @param {number} textureIdx
  2449. * @returns {number}
  2450. */
  2451. wgpuTextureGetMipLevelCount: (textureIdx) => {
  2452. const texture = this.textures.get(textureIdx);
  2453. return texture.mipLevelCount;
  2454. },
  2455. /**
  2456. * @param {number} textureIdx
  2457. * @returns {number}
  2458. */
  2459. wgpuTextureGetSampleCount: (textureIdx) => {
  2460. const texture = this.textures.get(textureIdx);
  2461. return texture.sampleCount;
  2462. },
  2463. /**
  2464. * @param {number} textureIdx
  2465. * @returns {number}
  2466. */
  2467. wgpuTextureGetUsage: (textureIdx) => {
  2468. const texture = this.textures.get(textureIdx);
  2469. return texture.usage;
  2470. },
  2471. /**
  2472. * @param {number} textureIdx
  2473. * @returns {number}
  2474. */
  2475. wgpuTextureGetWidth: (textureIdx) => {
  2476. const texture = this.textures.get(textureIdx);
  2477. return texture.width;
  2478. },
  2479. ...this.textures.interface(true),
  2480. /* ---------------------- TextureView ---------------------- */
  2481. ...this.textureViews.interface(true),
  2482. };
  2483. }
  2484. }
  2485. /** @template T */
  2486. class WebGPUObjectManager {
  2487. /**
  2488. * @param {string} name
  2489. * @param {WasmMemoryInterface} mem
  2490. */
  2491. constructor(name, mem) {
  2492. this.name = name;
  2493. this.mem = mem;
  2494. this.idx = 0;
  2495. /** @type {Record<number, { references: number, object: T }>} */
  2496. this.objects = {};
  2497. }
  2498. /**
  2499. * @param {T} object
  2500. * @returns {number}
  2501. */
  2502. create(object) {
  2503. this.objects[this.idx] = { references: 1, object };
  2504. this.idx += 1;
  2505. return this.idx;
  2506. }
  2507. /**
  2508. * @param {number} idx
  2509. * @returns {T}
  2510. */
  2511. get(idx) {
  2512. return this.objects[idx-1].object;
  2513. }
  2514. /** @param {number} idx */
  2515. release(idx) {
  2516. this.objects[idx-1].references -= 1;
  2517. if (this.objects[idx-1].references == 0) {
  2518. delete this.objects[idx-1];
  2519. }
  2520. }
  2521. /** @param {number} idx */
  2522. reference(idx) {
  2523. this.objects[idx-1].references += 1;
  2524. }
  2525. interface(withLabelSetter = false) {
  2526. const inter = {};
  2527. inter[`wgpu${this.name}Reference`] = this.reference.bind(this);
  2528. inter[`wgpu${this.name}Release`] = this.release.bind(this);
  2529. if (withLabelSetter) {
  2530. inter[`wgpu${this.name}SetLabel`] = (idx, labelPtr) => {
  2531. const obj = this.get(idx);
  2532. obj.label = this.mem.loadCstring(labelPtr);
  2533. };
  2534. }
  2535. return inter;
  2536. }
  2537. }
  2538. window.odin = window.odin || {};
  2539. window.odin.WebGPUInterface = WebGPUInterface;
  2540. })();