wgpu.js 93 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911
  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} bufferIdx
  2148. * @param {number} formatInt
  2149. * @param {BigInt} offset
  2150. * @param {BigInt} size
  2151. */
  2152. wgpuRenderPassEncoderSetIndexBuffer: (renderPassEncoderIdx, bufferIdx, formatInt, offset, size) => {
  2153. const renderPassEncoder = this.renderPassEncoders.get(renderPassEncoderIdx);
  2154. const buffer = this.buffers.get(bufferIdx);
  2155. const format = this.enums.IndexFormat[formatInt];
  2156. offset = this.unwrapBigInt(offset);
  2157. size = this.unwrapBigInt(size);
  2158. renderPassEncoder.setIndexBuffer(buffer.buffer, format, offset, size);
  2159. },
  2160. /**
  2161. * @param {number} renderPassEncoderIdx
  2162. * @param {number} pipelineIdx
  2163. */
  2164. wgpuRenderPassEncoderSetPipeline: (renderPassEncoderIdx, pipelineIdx) => {
  2165. const renderPassEncoder = this.renderPassEncoders.get(renderPassEncoderIdx);
  2166. const pipeline = this.renderPipelines.get(pipelineIdx);
  2167. renderPassEncoder.setPipeline(pipeline);
  2168. },
  2169. /**
  2170. * @param {number} renderPassEncoderIdx
  2171. * @param {number} x
  2172. * @param {number} y
  2173. * @param {number} width
  2174. * @param {number} height
  2175. */
  2176. wgpuRenderPassEncoderSetScissorRect: (renderPassEncoderIdx, x, y, width, height) => {
  2177. const renderPassEncoder = this.renderPassEncoders.get(renderPassEncoderIdx);
  2178. renderPassEncoder.setScissorRect(x, y, width, height);
  2179. },
  2180. /**
  2181. * @param {number} renderPassEncoderIdx
  2182. * @param {number} reference
  2183. */
  2184. wgpuRenderPassEncoderSetStencilReference: (renderPassEncoderIdx, reference) => {
  2185. const renderPassEncoder = this.renderPassEncoders.get(renderPassEncoderIdx);
  2186. renderPassEncoder.setStencilReference(reference);
  2187. },
  2188. /**
  2189. * @param {number} renderPassEncoderIdx
  2190. * @param {number} slot
  2191. * @param {0|number} bufferIdx
  2192. * @param {BigInt} offset
  2193. * @param {BigInt} size
  2194. */
  2195. wgpuRenderPassEncoderSetVertexBuffer: (renderPassEncoderIdx, slot, bufferIdx, offset, size) => {
  2196. const renderPassEncoder = this.renderPassEncoders.get(renderPassEncoderIdx);
  2197. let buffer;
  2198. if (bufferIdx > 0) {
  2199. buffer = this.buffers.get(bufferIdx).buffer;
  2200. }
  2201. offset = this.unwrapBigInt(offset);
  2202. size = this.unwrapBigInt(size);
  2203. renderPassEncoder.setVertexBuffer(slot, buffer, offset, size);
  2204. },
  2205. /**
  2206. * @param {number} renderPassEncoderIdx
  2207. * @param {number} x
  2208. * @param {number} y
  2209. * @param {number} width
  2210. * @param {number} height
  2211. * @param {number} minDepth
  2212. * @param {number} maxDepth
  2213. */
  2214. wgpuRenderPassEncoderSetViewport: (renderPassEncoderIdx, x, y, width, height, minDepth, maxDepth) => {
  2215. const renderPassEncoder = this.renderPassEncoders.get(renderPassEncoderIdx);
  2216. renderPassEncoder.setViewport(x, y, width, height, minDepth, maxDepth);
  2217. },
  2218. ...this.renderPassEncoders.interface(true),
  2219. /* ---------------------- RenderPipeline ---------------------- */
  2220. /**
  2221. * @param {number} renderPipelineIdx
  2222. * @param {number} groupIndex
  2223. * @returns {number}
  2224. */
  2225. wgpuRenderPipelineGetBindGroupLayout: (renderPipelineIdx, groupIndex) => {
  2226. const renderPipeline = this.renderPipelines.get(renderPipelineIdx);
  2227. const bindGroupLayout = renderPipeline.getBindGroupLayout(groupIndex);
  2228. return this.bindGroupLayouts.create(bindGroupLayout);
  2229. },
  2230. ...this.renderPipelines.interface(true),
  2231. /* ---------------------- Sampler ---------------------- */
  2232. ...this.samplers.interface(true),
  2233. /* ---------------------- ShaderModule ---------------------- */
  2234. /**
  2235. * @param {number} shaderModuleIdx
  2236. * @param {number} callbackPtr
  2237. * @param {number} userdata
  2238. */
  2239. wgpuShaderModuleGetCompilationInfo: async (shaderModuleIdx, callbackPtr, userdata) => {
  2240. const shaderModule = this.shaderModules.get(shaderModuleIdx);
  2241. const callback = this.mem.exports.__indirect_function_table.get(callbackPtr);
  2242. let status = 0;
  2243. let retAddr = 0;
  2244. const ptrsToFree = [];
  2245. try {
  2246. const compilationInfo = await shaderModule.getCompilationInfo();
  2247. const size = compilationInfo.messages.length * 72;
  2248. const addr = this.mem.exports.wgpu_alloc(size);
  2249. ptrsToFree.push(addr);
  2250. compilationInfo.messages.forEach((message, i) => {
  2251. const messageLength = new TextEncoder().encode(message.message).length;
  2252. const messageAddr = this.mem.exports.wgpu_alloc(messageLength);
  2253. ptrsToFree.push(messageAddr);
  2254. this.mem.storeString(messageAddr, message.message);
  2255. this.mem.storeI32(addr + (i * size) + 4);
  2256. this.mem.storeI32(addr + (i * size) + 8, this.enums.CompilationMessageType.indexOf(message.type));
  2257. this.mem.storeU64(addr + (i * size) + 16, message.lineNum);
  2258. this.mem.storeU64(addr + (i * size) + 24, message.linePos);
  2259. this.mem.storeU64(addr + (i * size) + 32, message.offset);
  2260. this.mem.storeU64(addr + (i * size) + 40, message.length);
  2261. // TODO: UTF16 units.
  2262. this.mem.storeU64(addr + (i * size) + 48, message.linePos);
  2263. this.mem.storeU64(addr + (i * size) + 56, message.offset);
  2264. this.mem.storeU64(addr + (i * size) + 64, message.length);
  2265. });
  2266. retAddr = this.mem.exports.wgpu_alloc(3*this.mem.intSize);
  2267. ptrsToFree.push(retAddr);
  2268. this.mem.storeUint(retAddr + this.mem.intSize, compilationInfo.messages.length);
  2269. this.mem.storeI32(retAddr + this.mem.intSize*2, addr);
  2270. } catch (e) {
  2271. console.warn(e);
  2272. status = 1;
  2273. }
  2274. callback(status, retAddr, userdata);
  2275. ptrsToFree.forEach(ptr => this.mem.exports.wgpu_free(ptr));
  2276. },
  2277. ...this.shaderModules.interface(true),
  2278. /* ---------------------- Surface ---------------------- */
  2279. /**
  2280. * @param {number} surfaceIdx
  2281. * @param {number} configPtr
  2282. */
  2283. wgpuSurfaceConfigure: (surfaceIdx, configPtr) => {
  2284. const surface = this.surfaces.get(surfaceIdx);
  2285. const context = surface.getContext('webgpu');
  2286. const widthOff = 16 + this.mem.intSize + 8;
  2287. surface.width = this.mem.loadU32(configPtr + widthOff);
  2288. surface.height = this.mem.loadU32(configPtr + widthOff + 4);
  2289. /** @type {GPUCanvasConfiguration} */
  2290. const config = {
  2291. device: this.devices.get(this.mem.loadPtr(configPtr + 4)),
  2292. format: this.enumeration("TextureFormat", configPtr + 8),
  2293. usage: this.mem.loadU32(configPtr + 12),
  2294. viewFormats: this.array(
  2295. this.mem.loadUint(configPtr + 16),
  2296. this.mem.loadPtr(configPtr + 16 + this.mem.intSize),
  2297. (ptr) => this.enumeration("TextureFormat", ptr),
  2298. 4,
  2299. ),
  2300. alphaMode: this.enumeration("CompositeAlphaMode", configPtr + widthOff - 4),
  2301. // // NOTE: present mode seems unused.
  2302. presentMode: this.enumeration("PresentMode", configPtr + widthOff + 4),
  2303. };
  2304. context.configure(config);
  2305. },
  2306. /**
  2307. * @param {number} surfaceIdx
  2308. * @param {number} adapterIdx
  2309. * @param {number} capabilitiesPtr
  2310. */
  2311. wgpuSurfaceGetCapabilities: (surfaceIdx, adapterIdx, capabilitiesPtr) => {
  2312. const formatStr = navigator.gpu.getPreferredCanvasFormat();
  2313. const format = this.enums.TextureFormat.indexOf(formatStr);
  2314. this.mem.storeUint(capabilitiesPtr + 8, 1);
  2315. const formatAddr = this.mem.exports.wgpu_alloc(4);
  2316. this.mem.storeI32(formatAddr, format);
  2317. this.mem.storeI32(capabilitiesPtr + 8 + this.mem.intSize, formatAddr);
  2318. // NOTE: present modes don't seem to actually do anything in JS, we can just give back a default FIFO though.
  2319. this.mem.storeUint(capabilitiesPtr + 8 + this.mem.intSize*2, 1);
  2320. const presentModesAddr = this.mem.exports.wgpu_alloc(4);
  2321. this.mem.storeI32(presentModesAddr, 0);
  2322. this.mem.storeI32(capabilitiesPtr + 8 + this.mem.intSize*3, presentModesAddr);
  2323. // Browser seems to support opaque (1) and premultiplied (2).
  2324. this.mem.storeUint(capabilitiesPtr + 8 + this.mem.intSize*4, 2);
  2325. const alphaModesAddr = this.mem.exports.wgpu_alloc(8);
  2326. this.mem.storeI32(alphaModesAddr + 0, 1); // Opaque.
  2327. this.mem.storeI32(alphaModesAddr + 4, 2); // premultiplied.
  2328. this.mem.storeI32(capabilitiesPtr + 8 + this.mem.intSize*5, alphaModesAddr);
  2329. },
  2330. /**
  2331. * @param {number} surfaceIdx
  2332. * @param {number} texturePtr
  2333. */
  2334. wgpuSurfaceGetCurrentTexture: (surfaceIdx, texturePtr) => {
  2335. const surface = this.surfaces.get(surfaceIdx);
  2336. const context = surface.getContext('webgpu');
  2337. const texture = context.getCurrentTexture();
  2338. const textureIdx = this.textures.create(texture);
  2339. this.mem.storeI32(texturePtr, textureIdx);
  2340. // TODO: determine suboptimal and/or status.
  2341. },
  2342. /**
  2343. * @param {number} surfaceIdx
  2344. */
  2345. wgpuSurfacePresent: (surfaceIdx) => {
  2346. // NOTE: Not really anything to do here.
  2347. },
  2348. /**
  2349. * @param {number} surfaceIdx
  2350. */
  2351. wgpuSurfaceUnconfigure: (surfaceIdx) => {
  2352. const surface = this.surfaces.get(surfaceIdx);
  2353. surface.getContext('webgpu').unconfigure();
  2354. },
  2355. ...this.surfaces.interface(true),
  2356. /* ---------------------- SurfaceCapabilities ---------------------- */
  2357. /**
  2358. * @param {number} surfaceCapabilitiesPtr
  2359. */
  2360. wgpuSurfaceCapabilitiesFreeMembers: (surfaceCapabilitiesPtr) => {
  2361. const formatsAddr = this.mem.loadI32(surfaceCapabilitiesPtr + this.mem.intSize*2);
  2362. this.mem.exports.wgpu_free(formatsAddr);
  2363. const presentModesAddr = this.mem.loadI32(surfaceCapabilitiesPtr + this.mem.intSize*4);
  2364. this.mem.exports.wgpu_free(presentModesAddr);
  2365. const alphaModesAddr = this.mem.loadI32(surfaceCapabilitiesPtr + this.mem.intSize*6);
  2366. this.mem.exports.wgpu_free(alphaModesAddr);
  2367. },
  2368. /* ---------------------- Texture ---------------------- */
  2369. /**
  2370. * @param {number} textureIdx
  2371. * @param {0|number} descriptorPtr
  2372. * @returns {number}
  2373. */
  2374. wgpuTextureCreateView: (textureIdx, descriptorPtr) => {
  2375. const texture = this.textures.get(textureIdx);
  2376. /** @type {?GPUTextureViewDescriptor} */
  2377. let descriptor;
  2378. if (descriptorPtr != 0) {
  2379. descriptor = {
  2380. label: this.mem.loadCstring(descriptorPtr + 4),
  2381. format: this.enumeration("TextureFormat", descriptorPtr + 8),
  2382. dimension: this.enumeration("TextureViewDimension", descriptorPtr + 12),
  2383. baseMipLevel: this.mem.loadU32(descriptorPtr + 16),
  2384. mipLevelCount: this.mem.loadU32(descriptorPtr + 20),
  2385. baseArrayLayer: this.mem.loadU32(descriptorPtr + 24),
  2386. arrayLayerCount: this.mem.loadU32(descriptorPtr + 28),
  2387. aspect: this.enumeration("TextureAspect", descriptorPtr + 32),
  2388. };
  2389. if (descriptor.arrayLayerCount == 0xFFFFFFFF) {
  2390. descriptor.arrayLayerCount = undefined;
  2391. }
  2392. if (descriptor.mipLevelCount == 0xFFFFFFFF) {
  2393. descriptor.mipLevelCount = undefined;
  2394. }
  2395. }
  2396. const textureView = texture.createView(descriptor);
  2397. return this.textureViews.create(textureView);
  2398. },
  2399. /**
  2400. * @param {number} textureIdx
  2401. */
  2402. wgpuTextureDestroy: (textureIdx) => {
  2403. const texture = this.textures.get(textureIdx);
  2404. texture.destroy();
  2405. },
  2406. /**
  2407. * @param {number} textureIdx
  2408. * @returns {number}
  2409. */
  2410. wgpuTextureDepthOrArrayLayers: (textureIdx) => {
  2411. const texture = this.textures.get(textureIdx);
  2412. return texture.depthOrArrayLayers;
  2413. },
  2414. /**
  2415. * @param {number} textureIdx
  2416. * @returns {number}
  2417. */
  2418. wgpuTextureGetDimension: (textureIdx) => {
  2419. const texture = this.textures.get(textureIdx);
  2420. return this.enums.TextureDimension.indexOf(texture.dimension);
  2421. },
  2422. /**
  2423. * @param {number} textureIdx
  2424. * @returns {number}
  2425. */
  2426. wgpuTextureGetFormat: (textureIdx) => {
  2427. const texture = this.textures.get(textureIdx);
  2428. return this.enums.TextureFormat.indexOf(texture.format);
  2429. },
  2430. /**
  2431. * @param {number} textureIdx
  2432. * @returns {number}
  2433. */
  2434. wgpuTextureGetHeight: (textureIdx) => {
  2435. const texture = this.textures.get(textureIdx);
  2436. return texture.height;
  2437. },
  2438. /**
  2439. * @param {number} textureIdx
  2440. * @returns {number}
  2441. */
  2442. wgpuTextureGetMipLevelCount: (textureIdx) => {
  2443. const texture = this.textures.get(textureIdx);
  2444. return texture.mipLevelCount;
  2445. },
  2446. /**
  2447. * @param {number} textureIdx
  2448. * @returns {number}
  2449. */
  2450. wgpuTextureGetSampleCount: (textureIdx) => {
  2451. const texture = this.textures.get(textureIdx);
  2452. return texture.sampleCount;
  2453. },
  2454. /**
  2455. * @param {number} textureIdx
  2456. * @returns {number}
  2457. */
  2458. wgpuTextureGetUsage: (textureIdx) => {
  2459. const texture = this.textures.get(textureIdx);
  2460. return texture.usage;
  2461. },
  2462. /**
  2463. * @param {number} textureIdx
  2464. * @returns {number}
  2465. */
  2466. wgpuTextureGetWidth: (textureIdx) => {
  2467. const texture = this.textures.get(textureIdx);
  2468. return texture.width;
  2469. },
  2470. ...this.textures.interface(true),
  2471. /* ---------------------- TextureView ---------------------- */
  2472. ...this.textureViews.interface(true),
  2473. };
  2474. }
  2475. }
  2476. /** @template T */
  2477. class WebGPUObjectManager {
  2478. /**
  2479. * @param {string} name
  2480. * @param {WasmMemoryInterface} mem
  2481. */
  2482. constructor(name, mem) {
  2483. this.name = name;
  2484. this.mem = mem;
  2485. this.idx = 0;
  2486. /** @type {Record<number, { references: number, object: T }>} */
  2487. this.objects = {};
  2488. }
  2489. /**
  2490. * @param {T} object
  2491. * @returns {number}
  2492. */
  2493. create(object) {
  2494. this.objects[this.idx] = { references: 1, object };
  2495. this.idx += 1;
  2496. return this.idx;
  2497. }
  2498. /**
  2499. * @param {number} idx
  2500. * @returns {T}
  2501. */
  2502. get(idx) {
  2503. return this.objects[idx-1].object;
  2504. }
  2505. /** @param {number} idx */
  2506. release(idx) {
  2507. this.objects[idx-1].references -= 1;
  2508. if (this.objects[idx-1].references == 0) {
  2509. delete this.objects[idx-1];
  2510. }
  2511. }
  2512. /** @param {number} idx */
  2513. reference(idx) {
  2514. this.objects[idx-1].references += 1;
  2515. }
  2516. interface(withLabelSetter = false) {
  2517. const inter = {};
  2518. inter[`wgpu${this.name}Reference`] = this.reference.bind(this);
  2519. inter[`wgpu${this.name}Release`] = this.release.bind(this);
  2520. if (withLabelSetter) {
  2521. inter[`wgpu${this.name}SetLabel`] = (idx, labelPtr) => {
  2522. const obj = this.get(idx);
  2523. obj.label = this.mem.loadCstring(labelPtr);
  2524. };
  2525. }
  2526. return inter;
  2527. }
  2528. }
  2529. window.odin = window.odin || {};
  2530. window.odin.WebGPUInterface = WebGPUInterface;
  2531. })();