UNPKG

@omnimedia/omnitool

Version:

open source video processing tools

43 lines (35 loc) 38.1 kB
import{a as be,b as ye,d as Ge,f as Se,h as Ce,j as ve,k as Ue,l as we,m as Me}from"./chunk-Y2VKPF3Q.js";import{b as G,c as ge,n as Te,o as Be,p as Ee}from"./chunk-GT46VDWY.js";import{u as le,v as q}from"./chunk-TT2DOKKC.js";import{a as ne}from"./chunk-ASDTIIJ2.js";import{a as $}from"./chunk-2B6UHEI4.js";import{b as X,d as _e,f as xe,h as Z,j as Pe,k as B,o as J}from"./chunk-LFJVYUTB.js";import{D as oe,E as b,F as ae,K as N,L as fe,M as j,N as K,O as Y,P as me,d,e as T,k as V,l as pe,p as y,z as he}from"./chunk-ERLCDDYH.js";var S=class{constructor(){this._maxTextures=0}contextChange(e){let t=new j({uTransformMatrix:{value:new V,type:"mat3x3<f32>"},uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uRound:{value:0,type:"f32"}});this._maxTextures=e.limits.maxBatchableTextures;let r=X({name:"graphics",bits:[_e,xe(this._maxTextures),ye,Z]});this.shader=new K({gpuProgram:r,resources:{localUniforms:t}})}execute(e,t){let r=t.context,s=r.customShader||this.shader,i=e.renderer,o=i.graphicsContext,{batcher:n,instructions:u}=o.getContextRenderData(r),c=i.encoder;c.setGeometry(n.geometry,s.gpuProgram);let m=i.globalUniforms.bindGroup;c.setBindGroup(0,m,s.gpuProgram);let h=i.renderPipes.uniformBatch.getUniformBindGroup(s.resources.localUniforms,!0);c.setBindGroup(2,h,s.gpuProgram);let l=u.instructions,p=null;for(let f=0;f<u.instructionSize;f++){let g=l[f];if(g.topology!==p&&(p=g.topology,c.setPipelineFromGeometryProgramAndState(n.geometry,s.gpuProgram,e.state,g.topology)),s.groups[1]=g.bindGroup,!g.gpuBindGroup){let H=g.textures;g.bindGroup=$(H.textures,H.count,this._maxTextures),g.gpuBindGroup=i.bindGroup.getBindGroup(g.bindGroup,s.gpuProgram,1)}c.setBindGroup(1,g.bindGroup,s.gpuProgram),c.renderPassEncoder.drawIndexed(g.size,1,g.start)}}destroy(){this.shader.destroy(!0),this.shader=null}};S.extension={type:[d.WebGPUPipesAdaptor],name:"graphics"};var C=class{init(){let e=X({name:"mesh",bits:[be,Ge,Z]});this._shader=new K({gpuProgram:e,resources:{uTexture:oe.EMPTY._source,uSampler:oe.EMPTY._source.style,textureUniforms:{uTextureMatrix:{type:"mat3x3<f32>",value:new V}}}})}execute(e,t){let r=e.renderer,s=t._shader;if(!s)s=this._shader,s.groups[2]=r.texture.getTextureBindGroup(t.texture);else if(!s.gpuProgram){y("Mesh shader has no gpuProgram",t.shader);return}let i=s.gpuProgram;if(i.autoAssignGlobalUniforms&&(s.groups[0]=r.globalUniforms.bindGroup),i.autoAssignLocalUniforms){let o=e.localUniforms;s.groups[1]=r.renderPipes.uniformBatch.getUniformBindGroup(o,!0)}r.encoder.draw({geometry:t._geometry,shader:s,state:t.state})}destroy(){this._shader.destroy(!0),this._shader=null}};C.extension={type:[d.WebGPUPipesAdaptor],name:"mesh"};var Q=q.for2d(),v=class{start(e,t,r){let s=e.renderer,i=s.encoder,o=r.gpuProgram;this._shader=r,this._geometry=t,i.setGeometry(t,o),Q.blendMode="normal",s.pipeline.getPipeline(t,o,Q);let n=s.globalUniforms.bindGroup;i.resetBindGroup(1),i.setBindGroup(0,n,o)}execute(e,t){let r=this._shader.gpuProgram,s=e.renderer,i=s.encoder;if(!t.bindGroup){let u=t.textures;t.bindGroup=$(u.textures,u.count,s.limits.maxBatchableTextures)}Q.blendMode=t.blendMode;let o=s.bindGroup.getBindGroup(t.bindGroup,r,1),n=s.pipeline.getPipeline(this._geometry,r,Q,t.topology);t.bindGroup._touch(s.gc.now,s.tick),i.setPipeline(n),i.renderPassEncoder.setBindGroup(1,o),i.renderPassEncoder.drawIndexed(t.size,1,t.start)}};v.extension={type:[d.WebGPUPipesAdaptor],name:"batch"};var U=class{constructor(e){this._hash=Object.create(null),this._renderer=e}contextChange(e){this._gpu=e}getBindGroup(e,t,r){return e._updateKey(),this._hash[e._key]||this._createBindGroup(e,t,r)}_createBindGroup(e,t,r){let s=this._gpu.device,i=t.layout[r],o=[],n=this._renderer;for(let m in i){let h=e.resources[m]??e.resources[i[m]],l;if(h._resourceType==="uniformGroup"){let p=h;n.ubo.updateUniformGroup(p);let f=p.buffer;l={buffer:n.buffer.getGPUBuffer(f),offset:0,size:f.descriptor.size}}else if(h._resourceType==="buffer"){let p=h;l={buffer:n.buffer.getGPUBuffer(p),offset:0,size:p.descriptor.size}}else if(h._resourceType==="bufferResource"){let p=h;l={buffer:n.buffer.getGPUBuffer(p.buffer),offset:p.offset,size:p.size}}else if(h._resourceType==="textureSampler"){let p=h;l=n.texture.getGpuSampler(p)}else if(h._resourceType==="textureSource"){let p=h;l=n.texture.getTextureView(p)}o.push({binding:i[m],resource:l})}let u=n.shader.getProgramData(t).bindGroups[r],c=s.createBindGroup({layout:u,entries:o});return this._hash[e._key]=c,c}destroy(){this._hash=null,this._renderer=null}};U.extension={type:[d.WebGPUSystem],name:"bindGroup"};var ue=class{constructor(e){this.gpuBuffer=e}destroy(){this.gpuBuffer.destroy(),this.gpuBuffer=null}},w=class{constructor(e){this._renderer=e,this._managedBuffers=new J({renderer:e,type:"resource",onUnload:this.onBufferUnload.bind(this),name:"gpuBuffer"})}contextChange(e){this._gpu=e}getGPUBuffer(e){return e._gcLastUsed=this._renderer.gc.now,e._gpuData[this._renderer.uid]?.gpuBuffer||this.createGPUBuffer(e)}updateBuffer(e){let t=this.getGPUBuffer(e),r=e.data;return e._updateID&&r&&(e._updateID=0,this._gpu.device.queue.writeBuffer(t,0,r.buffer,0,(e._updateSize||r.byteLength)+3&-4)),t}destroyAll(){this._managedBuffers.removeAll()}onBufferUnload(e){e.off("update",this.updateBuffer,this),e.off("change",this.onBufferChange,this)}createGPUBuffer(e){let t=this._gpu.device.createBuffer(e.descriptor);return e._updateID=0,e._resourceId=pe("resource"),e.data&&(Pe(e.data.buffer,t.getMappedRange(),e.data.byteOffset,e.data.byteLength),t.unmap()),e._gpuData[this._renderer.uid]=new ue(t),this._managedBuffers.add(e)&&(e.on("update",this.updateBuffer,this),e.on("change",this.onBufferChange,this)),t}onBufferChange(e){this._managedBuffers.remove(e),e._updateID=0,this.createGPUBuffer(e)}destroy(){this._managedBuffers.destroy(),this._renderer=null,this._gpu=null}};w.extension={type:[d.WebGPUSystem],name:"buffer"};var M=class{constructor(e){this._colorMaskCache=15,this._renderer=e}setMask(e){this._colorMaskCache!==e&&(this._colorMaskCache=e,this._renderer.pipeline.setColorMask(e))}destroy(){this._renderer=null,this._colorMaskCache=null}};M.extension={type:[d.WebGPUSystem],name:"colorMask"};var P=class{constructor(e){this._renderer=e}async init(e){return this._initPromise?this._initPromise:(this._initPromise=(e.gpu?Promise.resolve(e.gpu):this._createDeviceAndAdaptor(e)).then(t=>{this.gpu=t,this._renderer.runners.contextChange.emit(this.gpu)}),this._initPromise)}contextChange(e){this._renderer.gpu=e}async _createDeviceAndAdaptor(e){let t=await b.get().getNavigator().gpu.requestAdapter({powerPreference:e.powerPreference,forceFallbackAdapter:e.forceFallbackAdapter}),r=["texture-compression-bc","texture-compression-astc","texture-compression-etc2"].filter(i=>t.features.has(i)),s=await t.requestDevice({requiredFeatures:r});return{adapter:t,device:s}}destroy(){this.gpu=null,this._renderer=null}};P.extension={type:[d.WebGPUSystem],name:"device"};P.defaultOptions={powerPreference:void 0,forceFallbackAdapter:!1};var E=class{constructor(e){this._boundBindGroup=Object.create(null),this._boundVertexBuffer=Object.create(null),this._renderer=e}renderStart(){this.commandFinished=new Promise(e=>{this._resolveCommandFinished=e}),this.commandEncoder=this._renderer.gpu.device.createCommandEncoder()}beginRenderPass(e){this.endRenderPass(),this._clearCache(),this.renderPassEncoder=this.commandEncoder.beginRenderPass(e.descriptor)}endRenderPass(){this.renderPassEncoder&&this.renderPassEncoder.end(),this.renderPassEncoder=null}setViewport(e){this.renderPassEncoder.setViewport(e.x,e.y,e.width,e.height,0,1)}setPipelineFromGeometryProgramAndState(e,t,r,s){let i=this._renderer.pipeline.getPipeline(e,t,r,s);this.setPipeline(i)}setPipeline(e){this._boundPipeline!==e&&(this._boundPipeline=e,this.renderPassEncoder.setPipeline(e))}_setVertexBuffer(e,t){this._boundVertexBuffer[e]!==t&&(this._boundVertexBuffer[e]=t,this.renderPassEncoder.setVertexBuffer(e,this._renderer.buffer.updateBuffer(t)))}_setIndexBuffer(e){if(this._boundIndexBuffer===e)return;this._boundIndexBuffer=e;let t=e.data.BYTES_PER_ELEMENT===2?"uint16":"uint32";this.renderPassEncoder.setIndexBuffer(this._renderer.buffer.updateBuffer(e),t)}resetBindGroup(e){this._boundBindGroup[e]=null}setBindGroup(e,t,r){if(this._boundBindGroup[e]===t)return;this._boundBindGroup[e]=t,t._touch(this._renderer.gc.now,this._renderer.tick);let s=this._renderer.bindGroup.getBindGroup(t,r,e);this.renderPassEncoder.setBindGroup(e,s)}setGeometry(e,t){let r=this._renderer.pipeline.getBufferNamesToBind(e,t);for(let s in r)this._setVertexBuffer(parseInt(s,10),e.attributes[r[s]].buffer);e.indexBuffer&&this._setIndexBuffer(e.indexBuffer)}_setShaderBindGroups(e,t){for(let r in e.groups){let s=e.groups[r];t||this._syncBindGroup(s),this.setBindGroup(r,s,e.gpuProgram)}}_syncBindGroup(e){for(let t in e.resources){let r=e.resources[t];r.isUniformGroup&&this._renderer.ubo.updateUniformGroup(r)}}draw(e){let{geometry:t,shader:r,state:s,topology:i,size:o,start:n,instanceCount:u,skipSync:c}=e;this.setPipelineFromGeometryProgramAndState(t,r.gpuProgram,s,i),this.setGeometry(t,r.gpuProgram),this._setShaderBindGroups(r,c),t.indexBuffer?this.renderPassEncoder.drawIndexed(o||t.indexBuffer.data.length,u??t.instanceCount,n||0):this.renderPassEncoder.draw(o||t.getSize(),u??t.instanceCount,n||0)}finishRenderPass(){this.renderPassEncoder&&(this.renderPassEncoder.end(),this.renderPassEncoder=null)}postrender(){this.finishRenderPass(),this._gpu.device.queue.submit([this.commandEncoder.finish()]),this._resolveCommandFinished(),this.commandEncoder=null}restoreRenderPass(){let e=this._renderer.renderTarget.adaptor.getDescriptor(this._renderer.renderTarget.renderTarget,!1,[0,0,0,1],this._renderer.renderTarget.mipLevel,this._renderer.renderTarget.layer);this.renderPassEncoder=this.commandEncoder.beginRenderPass(e);let t=this._boundPipeline,r={...this._boundVertexBuffer},s=this._boundIndexBuffer,i={...this._boundBindGroup};this._clearCache();let o=this._renderer.renderTarget.viewport;this.renderPassEncoder.setViewport(o.x,o.y,o.width,o.height,0,1),this.setPipeline(t);for(let n in r)this._setVertexBuffer(n,r[n]);for(let n in i)this.setBindGroup(n,i[n],null);this._setIndexBuffer(s)}_clearCache(){for(let e=0;e<16;e++)this._boundBindGroup[e]=null,this._boundVertexBuffer[e]=null;this._boundIndexBuffer=null,this._boundPipeline=null}destroy(){this._renderer=null,this._gpu=null,this._boundBindGroup=null,this._boundVertexBuffer=null,this._boundIndexBuffer=null,this._boundPipeline=null}contextChange(e){this._gpu=e}};E.extension={type:[d.WebGPUSystem],name:"encoder",priority:1};var R=class{constructor(e){this._renderer=e}contextChange(){this.maxTextures=this._renderer.device.gpu.device.limits.maxSampledTexturesPerShaderStage,this.maxBatchableTextures=this.maxTextures}destroy(){}};R.extension={type:[d.WebGPUSystem],name:"limits"};var L=class{constructor(e){this._renderTargetStencilState=Object.create(null),this._renderer=e,e.renderTarget.onRenderTargetChange.add(this)}onRenderTargetChange(e){let t=this._renderTargetStencilState[e.uid];t||(t=this._renderTargetStencilState[e.uid]={stencilMode:B.DISABLED,stencilReference:0}),this._activeRenderTarget=e,this.setStencilMode(t.stencilMode,t.stencilReference)}setStencilMode(e,t){let r=this._renderTargetStencilState[this._activeRenderTarget.uid];r.stencilMode=e,r.stencilReference=t;let s=this._renderer;s.pipeline.setStencilMode(e),s.encoder.renderPassEncoder.setStencilReference(t)}destroy(){this._renderer.renderTarget.onRenderTargetChange.remove(this),this._renderer=null,this._activeRenderTarget=null,this._renderTargetStencilState=null}};L.extension={type:[d.WebGPUSystem],name:"stencil"};var A={i32:{align:4,size:4},u32:{align:4,size:4},f32:{align:4,size:4},f16:{align:2,size:2},"vec2<i32>":{align:8,size:8},"vec2<u32>":{align:8,size:8},"vec2<f32>":{align:8,size:8},"vec2<f16>":{align:4,size:4},"vec3<i32>":{align:16,size:12},"vec3<u32>":{align:16,size:12},"vec3<f32>":{align:16,size:12},"vec3<f16>":{align:8,size:6},"vec4<i32>":{align:16,size:16},"vec4<u32>":{align:16,size:16},"vec4<f32>":{align:16,size:16},"vec4<f16>":{align:8,size:8},"mat2x2<f32>":{align:8,size:16},"mat2x2<f16>":{align:4,size:8},"mat3x2<f32>":{align:8,size:24},"mat3x2<f16>":{align:4,size:12},"mat4x2<f32>":{align:8,size:32},"mat4x2<f16>":{align:4,size:16},"mat2x3<f32>":{align:16,size:32},"mat2x3<f16>":{align:8,size:16},"mat3x3<f32>":{align:16,size:48},"mat3x3<f16>":{align:8,size:24},"mat4x3<f32>":{align:16,size:64},"mat4x3<f16>":{align:8,size:32},"mat2x4<f32>":{align:16,size:32},"mat2x4<f16>":{align:8,size:16},"mat3x4<f32>":{align:16,size:48},"mat3x4<f16>":{align:8,size:24},"mat4x4<f32>":{align:16,size:64},"mat4x4<f16>":{align:8,size:32}};function Re(a){let e=a.map(r=>({data:r,offset:0,size:0})),t=0;for(let r=0;r<e.length;r++){let s=e[r],i=A[s.data.type].size,o=A[s.data.type].align;if(!A[s.data.type])throw new Error(`[Pixi.js] WebGPU UniformBuffer: Unknown type ${s.data.type}`);s.data.size>1&&(i=Math.max(i,o)*s.data.size),t=Math.ceil(t/o)*o,s.size=i,s.offset=t,t+=i}return t=Math.ceil(t/16)*16,{uboElements:e,size:t}}function Le(a,e){let{size:t,align:r}=A[a.data.type],s=(r-t)/4,i=a.data.type.indexOf("i32")>=0?"dataInt32":"data";return` v = uv.${a.data.name}; ${e!==0?`offset += ${e};`:""} arrayOffset = offset; t = 0; for(var i=0; i < ${a.data.size*(t/4)}; i++) { for(var j = 0; j < ${t/4}; j++) { ${i}[arrayOffset++] = v[t++]; } ${s!==0?`arrayOffset += ${s};`:""} } `}function Ae(a){return Ce(a,"uboWgsl",Le,ve)}var D=class extends Se{constructor(){super({createUboElements:Re,generateUboSync:Ae})}};D.extension={type:[d.WebGPUSystem],name:"ubo"};var ee=class{constructor({minUniformOffsetAlignment:e}){this._minUniformOffsetAlignment=256,this.byteIndex=0,this._minUniformOffsetAlignment=e,this.data=new Float32Array(65535)}clear(){this.byteIndex=0}addEmptyGroup(e){if(e>this._minUniformOffsetAlignment/4)throw new Error(`UniformBufferBatch: array is too large: ${e*4}`);let t=this.byteIndex,r=t+e*4;if(r=Math.ceil(r/this._minUniformOffsetAlignment)*this._minUniformOffsetAlignment,r>this.data.length*4)throw new Error("UniformBufferBatch: ubo batch got too big");return this.byteIndex=r,t}addGroup(e){let t=this.addEmptyGroup(e.length);for(let r=0;r<e.length;r++)this.data[t/4+r]=e[r];return t}destroy(){this.data=null}};var x=128,k=class{constructor(e){this._bindGroupHash=Object.create(null),this._buffers=[],this._bindGroups=[],this._bufferResources=[],this._renderer=e,this._batchBuffer=new ee({minUniformOffsetAlignment:x});let t=256/x;for(let r=0;r<t;r++){let s=Y.UNIFORM|Y.COPY_DST;r===0&&(s|=Y.COPY_SRC),this._buffers.push(new me({data:this._batchBuffer.data,usage:s}))}}renderEnd(){this._uploadBindGroups(),this._resetBindGroups()}_resetBindGroups(){this._bindGroupHash=Object.create(null),this._batchBuffer.clear()}getUniformBindGroup(e,t){if(!t&&this._bindGroupHash[e.uid])return this._bindGroupHash[e.uid];this._renderer.ubo.ensureUniformGroup(e);let r=e.buffer.data,s=this._batchBuffer.addEmptyGroup(r.length);return this._renderer.ubo.syncUniformGroup(e,this._batchBuffer.data,s/4),this._bindGroupHash[e.uid]=this._getBindGroup(s/x),this._bindGroupHash[e.uid]}getUboResource(e){this._renderer.ubo.updateUniformGroup(e);let t=e.buffer.data,r=this._batchBuffer.addGroup(t);return this._getBufferResource(r/x)}getArrayBindGroup(e){let t=this._batchBuffer.addGroup(e);return this._getBindGroup(t/x)}getArrayBufferResource(e){let r=this._batchBuffer.addGroup(e)/x;return this._getBufferResource(r)}_getBufferResource(e){if(!this._bufferResources[e]){let t=this._buffers[e%2];this._bufferResources[e]=new Ue({buffer:t,offset:(e/2|0)*256,size:x})}return this._bufferResources[e]}_getBindGroup(e){if(!this._bindGroups[e]){let t=new N({0:this._getBufferResource(e)});this._bindGroups[e]=t}return this._bindGroups[e]}_uploadBindGroups(){let e=this._renderer.buffer,t=this._buffers[0];t.update(this._batchBuffer.byteIndex),e.updateBuffer(t);let r=this._renderer.gpu.device.createCommandEncoder();for(let s=1;s<this._buffers.length;s++){let i=this._buffers[s];r.copyBufferToBuffer(e.getGPUBuffer(t),x,e.getGPUBuffer(i),0,this._batchBuffer.byteIndex)}this._renderer.gpu.device.queue.submit([r.finish()])}destroy(){for(let e=0;e<this._bindGroups.length;e++)this._bindGroups[e]?.destroy();this._bindGroups=null,this._bindGroupHash=null;for(let e=0;e<this._buffers.length;e++)this._buffers[e].destroy();this._buffers=null;for(let e=0;e<this._bufferResources.length;e++)this._bufferResources[e].destroy();this._bufferResources=null,this._batchBuffer.destroy(),this._renderer=null}};k.extension={type:[d.WebGPUPipes],name:"uniformBatch"};var Ne={"point-list":0,"line-list":1,"line-strip":2,"triangle-list":3,"triangle-strip":4};function je(a,e,t,r,s){return a<<24|e<<16|t<<10|r<<5|s}function Ke(a,e,t,r,s){return t<<8|a<<5|r<<3|s<<1|e}var z=class{constructor(e){this._moduleCache=Object.create(null),this._bufferLayoutsCache=Object.create(null),this._bindingNamesCache=Object.create(null),this._pipeCache=Object.create(null),this._pipeStateCaches=Object.create(null),this._colorMask=15,this._multisampleCount=1,this._colorTargetCount=1,this._renderer=e}contextChange(e){this._gpu=e,this.setStencilMode(B.DISABLED),this._updatePipeHash()}setMultisampleCount(e){this._multisampleCount!==e&&(this._multisampleCount=e,this._updatePipeHash())}setRenderTarget(e){this._multisampleCount=e.msaaSamples,this._depthStencilAttachment=e.descriptor.depthStencilAttachment?1:0,this._colorTargetCount=e.colorTargetCount,this._updatePipeHash()}setColorMask(e){this._colorMask!==e&&(this._colorMask=e,this._updatePipeHash())}setStencilMode(e){this._stencilMode!==e&&(this._stencilMode=e,this._stencilState=Me[e],this._updatePipeHash())}setPipeline(e,t,r,s){let i=this.getPipeline(e,t,r);s.setPipeline(i)}getPipeline(e,t,r,s){e._layoutKey||(we(e,t.attributeData),this._generateBufferKey(e)),s||(s=e.topology);let i=je(e._layoutKey,t._layoutKey,r.data,r._blendModeId,Ne[s]);return this._pipeCache[i]?this._pipeCache[i]:(this._pipeCache[i]=this._createPipeline(e,t,r,s),this._pipeCache[i])}_createPipeline(e,t,r,s){let i=this._gpu.device,o=this._createVertexBufferLayouts(e,t),n=this._renderer.state.getColorTargets(r,this._colorTargetCount),u=this._stencilMode===B.RENDERING_MASK_ADD?0:this._colorMask;for(let l=0;l<n.length;l++)n[l].writeMask=u;let c=this._renderer.shader.getProgramData(t).pipeline,m={vertex:{module:this._getModule(t.vertex.source),entryPoint:t.vertex.entryPoint,buffers:o},fragment:{module:this._getModule(t.fragment.source),entryPoint:t.fragment.entryPoint,targets:n},primitive:{topology:s,cullMode:r.cullMode},layout:c,multisample:{count:this._multisampleCount},label:"PIXI Pipeline"};return this._depthStencilAttachment&&(m.depthStencil={...this._stencilState,format:"depth24plus-stencil8",depthWriteEnabled:r.depthTest,depthCompare:r.depthTest?"less":"always"}),i.createRenderPipeline(m)}_getModule(e){return this._moduleCache[e]||this._createModule(e)}_createModule(e){let t=this._gpu.device;return this._moduleCache[e]=t.createShaderModule({code:e}),this._moduleCache[e]}_generateBufferKey(e){let t=[],r=0,s=Object.keys(e.attributes).sort();for(let o=0;o<s.length;o++){let n=e.attributes[s[o]];t[r++]=n.offset,t[r++]=n.format,t[r++]=n.stride,t[r++]=n.instance}let i=t.join("|");return e._layoutKey=ae(i,"geometry"),e._layoutKey}_generateAttributeLocationsKey(e){let t=[],r=0,s=Object.keys(e.attributeData).sort();for(let o=0;o<s.length;o++){let n=e.attributeData[s[o]];t[r++]=n.location}let i=t.join("|");return e._attributeLocationsKey=ae(i,"programAttributes"),e._attributeLocationsKey}getBufferNamesToBind(e,t){let r=e._layoutKey<<16|t._attributeLocationsKey;if(this._bindingNamesCache[r])return this._bindingNamesCache[r];let s=this._createVertexBufferLayouts(e,t),i=Object.create(null),o=t.attributeData;for(let n=0;n<s.length;n++){let c=Object.values(s[n].attributes)[0].shaderLocation;for(let m in o)if(o[m].location===c){i[n]=m;break}}return this._bindingNamesCache[r]=i,i}_createVertexBufferLayouts(e,t){t._attributeLocationsKey||this._generateAttributeLocationsKey(t);let r=e._layoutKey<<16|t._attributeLocationsKey;if(this._bufferLayoutsCache[r])return this._bufferLayoutsCache[r];let s=[];return e.buffers.forEach(i=>{let o={arrayStride:0,stepMode:"vertex",attributes:[]},n=o.attributes;for(let u in t.attributeData){let c=e.attributes[u];(c.divisor??1)!==1&&y(`Attribute ${u} has an invalid divisor value of '${c.divisor}'. WebGPU only supports a divisor value of 1`),c.buffer===i&&(o.arrayStride=c.stride,o.stepMode=c.instance?"instance":"vertex",n.push({shaderLocation:t.attributeData[u].location,offset:c.offset,format:c.format}))}n.length&&s.push(o)}),this._bufferLayoutsCache[r]=s,s}_updatePipeHash(){let e=Ke(this._stencilMode,this._multisampleCount,this._colorMask,this._depthStencilAttachment,this._colorTargetCount);this._pipeStateCaches[e]||(this._pipeStateCaches[e]=Object.create(null)),this._pipeCache=this._pipeStateCaches[e]}destroy(){this._renderer=null,this._bufferLayoutsCache=null}};z.extension={type:[d.WebGPUSystem],name:"pipeline"};var te=class{constructor(){this.contexts=[],this.msaaTextures=[],this.msaaSamples=1}};var re=class{init(e,t){this._renderer=e,this._renderTargetSystem=t}copyToTexture(e,t,r,s,i){let o=this._renderer,n=this._getGpuColorTexture(e),u=o.texture.getGpuSource(t.source);return o.encoder.commandEncoder.copyTextureToTexture({texture:n,origin:r},{texture:u,origin:i},s),t}startRenderPass(e,t=!0,r,s,i=0,o=0){let u=this._renderTargetSystem.getGpuRenderTarget(e);if(o!==0&&u.msaaTextures?.length)throw new Error("[RenderTargetSystem] Rendering to array layers is not supported with MSAA render targets.");if(i>0&&u.msaaTextures?.length)throw new Error("[RenderTargetSystem] Rendering to mip levels is not supported with MSAA render targets.");let c=this.getDescriptor(e,t,r,i,o);u.descriptor=c,this._renderer.pipeline.setRenderTarget(u),this._renderer.encoder.beginRenderPass(u),this._renderer.encoder.setViewport(s)}finishRenderPass(){this._renderer.encoder.endRenderPass()}_getGpuColorTexture(e){let t=this._renderTargetSystem.getGpuRenderTarget(e);return t.contexts[0]?t.contexts[0].getCurrentTexture():this._renderer.texture.getGpuSource(e.colorTextures[0].source)}getDescriptor(e,t,r,s=0,i=0){typeof t=="boolean"&&(t=t?G.ALL:G.NONE);let o=this._renderTargetSystem,n=o.getGpuRenderTarget(e),u=e.colorTextures.map((h,l)=>{let p=n.contexts[l],f,g;if(p){if(i!==0)throw new Error("[RenderTargetSystem] Rendering to array layers is not supported for canvas targets.");f=p.getCurrentTexture().createView()}else f=this._renderer.texture.getGpuSource(h).createView({dimension:"2d",baseMipLevel:s,mipLevelCount:1,baseArrayLayer:i,arrayLayerCount:1});n.msaaTextures[l]&&(g=f,f=this._renderer.texture.getTextureView(n.msaaTextures[l]));let H=t&G.COLOR?"clear":"load";return r??(r=o.defaultClearColor),{view:f,resolveTarget:g,clearValue:r,storeOp:"store",loadOp:H}}),c;if((e.stencil||e.depth)&&!e.depthStencilTexture&&(e.ensureDepthStencilTexture(),e.depthStencilTexture.source.sampleCount=n.msaa?4:1),e.depthStencilTexture){let h=t&G.STENCIL?"clear":"load",l=t&G.DEPTH?"clear":"load";c={view:this._renderer.texture.getGpuSource(e.depthStencilTexture.source).createView({dimension:"2d",baseMipLevel:s,mipLevelCount:1,baseArrayLayer:i,arrayLayerCount:1}),stencilStoreOp:"store",stencilLoadOp:h,depthClearValue:1,depthLoadOp:l,depthStoreOp:"store"}}return{colorAttachments:u,depthStencilAttachment:c}}clear(e,t=!0,r,s,i=0,o=0){if(!t)return;let{gpu:n,encoder:u}=this._renderer,c=n.device;if(u.commandEncoder===null){let h=c.createCommandEncoder(),l=this.getDescriptor(e,t,r,i,o),p=h.beginRenderPass(l);p.setViewport(s.x,s.y,s.width,s.height,0,1),p.end();let f=h.finish();c.queue.submit([f])}else this.startRenderPass(e,t,r,s,i,o)}initGpuRenderTarget(e){e.isRoot=!0;let t=new te;return t.colorTargetCount=e.colorTextures.length,e.colorTextures.forEach((r,s)=>{if(r instanceof le){let i=r.resource.getContext("webgpu"),o=r.transparent?"premultiplied":"opaque";try{i.configure({device:this._renderer.gpu.device,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,format:"bgra8unorm",alphaMode:o})}catch(n){console.error(n)}t.contexts[s]=i}if(t.msaa=r.source.antialias,r.source.antialias){let i=new he({width:0,height:0,sampleCount:4,arrayLayerCount:r.source.arrayLayerCount});t.msaaTextures[s]=i}}),t.msaa&&(t.msaaSamples=4,e.depthStencilTexture&&(e.depthStencilTexture.source.sampleCount=4)),t}destroyGpuRenderTarget(e){e.contexts.forEach(t=>{t.unconfigure()}),e.msaaTextures.forEach(t=>{t.destroy()}),e.msaaTextures.length=0,e.contexts.length=0}ensureDepthStencilTexture(e){let t=this._renderTargetSystem.getGpuRenderTarget(e);e.depthStencilTexture&&t.msaa&&(e.depthStencilTexture.source.sampleCount=4)}resizeGpuRenderTarget(e){let t=this._renderTargetSystem.getGpuRenderTarget(e);t.width=e.width,t.height=e.height,t.msaa&&e.colorTextures.forEach((r,s)=>{t.msaaTextures[s]?.resize(r.source.width,r.source.height,r.source._resolution)})}};var I=class extends Ee{constructor(e){super(e),this.adaptor=new re,this.adaptor.init(e,this)}};I.extension={type:[d.WebGPUSystem],name:"renderTarget"};var F=class{constructor(){this._gpuProgramData=Object.create(null)}contextChange(e){this._gpu=e}getProgramData(e){return this._gpuProgramData[e._layoutKey]||this._createGPUProgramData(e)}_createGPUProgramData(e){let t=this._gpu.device,r=e.gpuLayout.map(i=>t.createBindGroupLayout({entries:i})),s={bindGroupLayouts:r};return this._gpuProgramData[e._layoutKey]={bindGroups:r,pipeline:t.createPipelineLayout(s)},this._gpuProgramData[e._layoutKey]}destroy(){this._gpu=null,this._gpuProgramData=null}};F.extension={type:[d.WebGPUSystem],name:"shader"};var _={};_.normal={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}};_.add={alpha:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one",operation:"add"}};_.multiply={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"dst",dstFactor:"one-minus-src-alpha",operation:"add"}};_.screen={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src",operation:"add"}};_.overlay={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src",operation:"add"}};_.none={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"zero",dstFactor:"zero",operation:"add"}};_["normal-npm"]={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"}};_["add-npm"]={alpha:{srcFactor:"one",dstFactor:"one",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one",operation:"add"}};_["screen-npm"]={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one-minus-src",operation:"add"}};_.erase={alpha:{srcFactor:"zero",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"zero",dstFactor:"one-minus-src",operation:"add"}};_.min={alpha:{srcFactor:"one",dstFactor:"one",operation:"min"},color:{srcFactor:"one",dstFactor:"one",operation:"min"}};_.max={alpha:{srcFactor:"one",dstFactor:"one",operation:"max"},color:{srcFactor:"one",dstFactor:"one",operation:"max"}};var O=class{constructor(){this.defaultState=new q,this.defaultState.blend=!0}contextChange(e){this.gpu=e}getColorTargets(e,t){let r=_[e.blendMode]||_.normal,s=[],i={format:"bgra8unorm",writeMask:0,blend:r};for(let o=0;o<t;o++)s[o]=i;return s}destroy(){this.gpu=null}};O.extension={type:[d.WebGPUSystem],name:"state"};var De={type:"image",upload(a,e,t,r=0){let s=a.resource,i=(a.pixelWidth|0)*(a.pixelHeight|0),o=s.byteLength/i;t.device.queue.writeTexture({texture:e,origin:{x:0,y:0,z:r}},s,{offset:0,rowsPerImage:a.pixelHeight,bytesPerRow:a.pixelWidth*o},{width:a.pixelWidth,height:a.pixelHeight,depthOrArrayLayers:1})}};var ce={"bc1-rgba-unorm":{blockBytes:8,blockWidth:4,blockHeight:4},"bc2-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"bc3-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"bc7-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"etc1-rgb-unorm":{blockBytes:8,blockWidth:4,blockHeight:4},"etc2-rgba8unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"astc-4x4-unorm":{blockBytes:16,blockWidth:4,blockHeight:4}},qe={blockBytes:4,blockWidth:1,blockHeight:1},ke={type:"compressed",upload(a,e,t,r=0){let s=a.pixelWidth,i=a.pixelHeight,o=ce[a.format]||qe;for(let n=0;n<a.resource.length;n++){let u=a.resource[n],c=Math.ceil(s/o.blockWidth)*o.blockBytes;t.device.queue.writeTexture({texture:e,mipLevel:n,origin:{x:0,y:0,z:r}},u,{offset:0,bytesPerRow:c},{width:Math.ceil(s/o.blockWidth)*o.blockWidth,height:Math.ceil(i/o.blockHeight)*o.blockHeight,depthOrArrayLayers:1}),s=Math.max(s>>1,1),i=Math.max(i>>1,1)}}};var ze=["right","left","top","bottom","front","back"];function Ie(a){return{type:"cube",upload(e,t,r){let s=e.faces;for(let i=0;i<ze.length;i++){let o=ze[i],n=s[o];(a[n.uploadMethodId]||a.image).upload(n,t,r,i)}}}}var se={type:"image",upload(a,e,t,r=0){let s=a.resource;if(!s)return;if(globalThis.HTMLImageElement&&s instanceof HTMLImageElement){let u=b.get().createCanvas(s.width,s.height);u.getContext("2d").drawImage(s,0,0,s.width,s.height),a.resource=u,y("ImageSource: Image element passed, converting to canvas and replacing resource.")}let i=Math.min(e.width,a.resourceWidth||a.pixelWidth),o=Math.min(e.height,a.resourceHeight||a.pixelHeight),n=a.alphaMode==="premultiply-alpha-on-upload";t.device.queue.copyExternalImageToTexture({source:s},{texture:e,origin:{x:0,y:0,z:r},premultipliedAlpha:n},{width:i,height:o})}};var Fe={type:"video",upload(a,e,t,r){se.upload(a,e,t,r)}};var ie=class{constructor(e){this.device=e,this.sampler=e.createSampler({minFilter:"linear"}),this.pipelines={}}_getMipmapPipeline(e){let t=this.pipelines[e];return t||(this.mipmapShaderModule||(this.mipmapShaderModule=this.device.createShaderModule({code:` var<private> pos : array<vec2<f32>, 3> = array<vec2<f32>, 3>( vec2<f32>(-1.0, -1.0), vec2<f32>(-1.0, 3.0), vec2<f32>(3.0, -1.0)); struct VertexOutput { @builtin(position) position : vec4<f32>, @location(0) texCoord : vec2<f32>, }; @vertex fn vertexMain(@builtin(vertex_index) vertexIndex : u32) -> VertexOutput { var output : VertexOutput; output.texCoord = pos[vertexIndex] * vec2<f32>(0.5, -0.5) + vec2<f32>(0.5); output.position = vec4<f32>(pos[vertexIndex], 0.0, 1.0); return output; } @group(0) @binding(0) var imgSampler : sampler; @group(0) @binding(1) var img : texture_2d<f32>; @fragment fn fragmentMain(@location(0) texCoord : vec2<f32>) -> @location(0) vec4<f32> { return textureSample(img, imgSampler, texCoord); } `})),t=this.device.createRenderPipeline({layout:"auto",vertex:{module:this.mipmapShaderModule,entryPoint:"vertexMain"},fragment:{module:this.mipmapShaderModule,entryPoint:"fragmentMain",targets:[{format:e}]}}),this.pipelines[e]=t),t}generateMipmap(e){let t=this._getMipmapPipeline(e.format);if(e.dimension==="3d"||e.dimension==="1d")throw new Error("Generating mipmaps for non-2d textures is currently unsupported!");let r=e,s=e.depthOrArrayLayers||1,i=e.usage&GPUTextureUsage.RENDER_ATTACHMENT;if(!i){let u={size:{width:Math.ceil(e.width/2),height:Math.ceil(e.height/2),depthOrArrayLayers:s},format:e.format,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC|GPUTextureUsage.RENDER_ATTACHMENT,mipLevelCount:e.mipLevelCount-1};r=this.device.createTexture(u)}let o=this.device.createCommandEncoder({}),n=t.getBindGroupLayout(0);for(let u=0;u<s;++u){let c=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:"2d",baseArrayLayer:u,arrayLayerCount:1}),m=i?1:0;for(let h=1;h<e.mipLevelCount;++h){let l=r.createView({baseMipLevel:m++,mipLevelCount:1,dimension:"2d",baseArrayLayer:u,arrayLayerCount:1}),p=o.beginRenderPass({colorAttachments:[{view:l,storeOp:"store",loadOp:"clear",clearValue:{r:0,g:0,b:0,a:0}}]}),f=this.device.createBindGroup({layout:n,entries:[{binding:0,resource:this.sampler},{binding:1,resource:c}]});p.setPipeline(t),p.setBindGroup(0,f),p.draw(3,1,0,0),p.end(),c=l}}if(!i){let u={width:Math.ceil(e.width/2),height:Math.ceil(e.height/2),depthOrArrayLayers:s};for(let c=1;c<e.mipLevelCount;++c)o.copyTextureToTexture({texture:r,mipLevel:c-1},{texture:e,mipLevel:c},u),u.width=Math.ceil(u.width/2),u.height=Math.ceil(u.height/2)}return this.device.queue.submit([o.finish()]),i||r.destroy(),e}};var de=class{constructor(e){this.textureView=null,this.gpuTexture=e}destroy(){this.gpuTexture.destroy(),this.textureView=null,this.gpuTexture=null}},W=class{constructor(e){this._gpuSamplers=Object.create(null),this._bindGroupHash=Object.create(null),this._renderer=e,e.gc.addCollection(this,"_bindGroupHash","hash"),this._managedTextures=new J({renderer:e,type:"resource",onUnload:this.onSourceUnload.bind(this),name:"gpuTextureSource"});let t={image:se,buffer:De,video:Fe,compressed:ke};this._uploads={...t,cube:Ie(t)}}get managedTextures(){return Object.values(this._managedTextures.items)}contextChange(e){this._gpu=e}initSource(e){return e._gpuData[this._renderer.uid]?.gpuTexture||this._initSource(e)}_initSource(e){if(e.autoGenerateMipmaps){let c=Math.max(e.pixelWidth,e.pixelHeight);e.mipLevelCount=Math.floor(Math.log2(c))+1}let t=GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST;e.uploadMethodId!=="compressed"&&(t|=GPUTextureUsage.RENDER_ATTACHMENT,t|=GPUTextureUsage.COPY_SRC);let r=ce[e.format]||{blockBytes:4,blockWidth:1,blockHeight:1},s=Math.ceil(e.pixelWidth/r.blockWidth)*r.blockWidth,i=Math.ceil(e.pixelHeight/r.blockHeight)*r.blockHeight,o={label:e.label,size:{width:s,height:i,depthOrArrayLayers:e.arrayLayerCount},format:e.format,sampleCount:e.sampleCount,mipLevelCount:e.mipLevelCount,dimension:e.dimension,usage:t},n=this._gpu.device.createTexture(o);return e._gpuData[this._renderer.uid]=new de(n),this._managedTextures.add(e)&&(e.on("update",this.onSourceUpdate,this),e.on("resize",this.onSourceResize,this),e.on("updateMipmaps",this.onUpdateMipmaps,this)),this.onSourceUpdate(e),n}onSourceUpdate(e){let t=this.getGpuSource(e);t&&(this._uploads[e.uploadMethodId]&&this._uploads[e.uploadMethodId].upload(e,t,this._gpu),e.autoGenerateMipmaps&&e.mipLevelCount>1&&this.onUpdateMipmaps(e))}onUpdateMipmaps(e){this._mipmapGenerator||(this._mipmapGenerator=new ie(this._gpu.device));let t=this.getGpuSource(e);this._mipmapGenerator.generateMipmap(t)}onSourceUnload(e){e.off("update",this.onSourceUpdate,this),e.off("resize",this.onSourceResize,this),e.off("updateMipmaps",this.onUpdateMipmaps,this)}onSourceResize(e){e._gcLastUsed=this._renderer.gc.now;let t=e._gpuData[this._renderer.uid],r=t?.gpuTexture;r?(r.width!==e.pixelWidth||r.height!==e.pixelHeight)&&(t.destroy(),this._bindGroupHash[e.uid]=null,e._gpuData[this._renderer.uid]=null,this.initSource(e)):this.initSource(e)}_initSampler(e){return this._gpuSamplers[e._resourceId]=this._gpu.device.createSampler(e),this._gpuSamplers[e._resourceId]}getGpuSampler(e){return this._gpuSamplers[e._resourceId]||this._initSampler(e)}getGpuSource(e){return e._gcLastUsed=this._renderer.gc.now,e._gpuData[this._renderer.uid]?.gpuTexture||this.initSource(e)}getTextureBindGroup(e){return this._bindGroupHash[e.uid]||this._createTextureBindGroup(e)}_createTextureBindGroup(e){let t=e.source;return this._bindGroupHash[e.uid]=new N({0:t,1:t.style,2:new j({uTextureMatrix:{type:"mat3x3<f32>",value:e.textureMatrix.mapCoord}})}),this._bindGroupHash[e.uid]}getTextureView(e){let t=e.source;t._gcLastUsed=this._renderer.gc.now;let r=t._gpuData[this._renderer.uid];return r||(this.initSource(t),r=t._gpuData[this._renderer.uid]),r.textureView||(r.textureView=r.gpuTexture.createView({dimension:t.viewDimension})),r.textureView}generateCanvas(e){let t=this._renderer,r=t.gpu.device.createCommandEncoder(),s=b.get().createCanvas();s.width=e.source.pixelWidth,s.height=e.source.pixelHeight;let i=s.getContext("webgpu");return i.configure({device:t.gpu.device,usage:GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC,format:b.get().getNavigator().gpu.getPreferredCanvasFormat(),alphaMode:"premultiplied"}),r.copyTextureToTexture({texture:t.texture.getGpuSource(e.source),origin:{x:0,y:0}},{texture:i.getCurrentTexture()},{width:s.width,height:s.height}),t.gpu.device.queue.submit([r.finish()]),s}getPixels(e){let t=this.generateCanvas(e),r=ne.getOptimalCanvasAndContext(t.width,t.height),s=r.context;s.drawImage(t,0,0);let{width:i,height:o}=t,n=s.getImageData(0,0,i,o),u=new Uint8ClampedArray(n.data.buffer);return ne.returnCanvasAndContext(r),{pixels:u,width:i,height:o}}destroy(){this._managedTextures.destroy();for(let e of Object.keys(this._bindGroupHash)){let t=Number(e);this._bindGroupHash[t]?.destroy()}this._renderer=null,this._gpu=null,this._mipmapGenerator=null,this._gpuSamplers=null,this._bindGroupHash=null}};W.extension={type:[d.WebGPUSystem],name:"texture"};var Ye=[...Te,D,E,P,R,w,W,I,F,O,z,M,L,U],$e=[...Be,k],Xe=[v,C,S],We=[],He=[],Ve=[];T.handleByNamedList(d.WebGPUSystem,We);T.handleByNamedList(d.WebGPUPipes,He);T.handleByNamedList(d.WebGPUPipesAdaptor,Ve);T.add(...Ye,...$e,...Xe);var Oe=class extends ge{constructor(){let e={name:"webgpu",type:fe.WEBGPU,systems:We,renderPipes:He,renderPipeAdaptors:Ve};super(e)}};export{Oe as a}; //# sourceMappingURL=chunk-7Z2UP4WF.js.map