diff --git a/dist/index.js b/dist/index.js index 135a5024d0..e09b59ea52 100644 --- a/dist/index.js +++ b/dist/index.js @@ -1 +1 @@ -const consoleAndThrowError=(...i)=>{const g=Array.prototype.slice.call(i).join(" ");throw new Error(g)},validatePositiveNumberRange=(i,g=0,x=Number.MAX_VALUE)=>(("number"!=typeof i||Number.isNaN(i))&&consoleAndThrowError("Only numbers allowed."),("number"!=typeof g||Number.isNaN(g))&&consoleAndThrowError("Only numbers allowed."),("number"!=typeof x||Number.isNaN(x))&&consoleAndThrowError("Only numbers allowed."),(g<0||i<0||ix)&&consoleAndThrowError(`Only numbers within the range of [${g}, ${x}] are allowed.`),!0),isUint=i=>Number.isInteger(i)&&i>=0,validateUintRange=(i,g=0,x=4503599627370496)=>{const v=isUint(i),_=isUint(g),y=isUint(x),b="is not Uint! / value : ",S=`(check range : ${g}u ~ ${x}u)`;return v||consoleAndThrowError(`value ${b}${i} / ${S}`),_||consoleAndThrowError(`min ${b}${g} / ${S}`),y||consoleAndThrowError(`max ${b}${x} / ${S}`),g>=x&&consoleAndThrowError(`maximum value is bigger than minimum value. / ${S}`),g>i&&consoleAndThrowError(`value is smaller than minimum value. / value : ${i} / ${S}`),x{if("number"==typeof i)return!Number.isNaN(i)&&Number.isInteger(i)&&i>=0&&i<=16777215;if("string"!=typeof i)return!1;const g=/^([A-Fa-f0-9]{3}){1,2}$/;return!!i.startsWith("#")&&g.test(i.substring(1))};function convertHexToRgb(i,g=!1){if(Number.isNaN(i))throw Error(`from convertHexToRgb: input value - ${i} / NaN is not allowed`);let x;if("number"==typeof i)x=i;else{if(!isHexColor(i))throw Error(`from convertHexToRgb: input value - ${i} / Only '#' prefixed hex strings or numbers allowed`);{let g=i.substring(1);3===g.length&&(g=g.charAt(0)+g.charAt(0)+g.charAt(1)+g.charAt(1)+g.charAt(2)+g.charAt(2)),x=parseInt(g,16)}}const v=x>>16&255,_=x>>8&255,y=255&x;return g?[v,_,y]:{r:v,g:_,b:y}}const convertRgbToHex=(i,g,x)=>{validateUintRange(i,0,255),validateUintRange(g,0,255),validateUintRange(x,0,255);return`#${i.toString(16).padStart(2,"0").toUpperCase()}${g.toString(16).padStart(2,"0").toUpperCase()}${x.toString(16).padStart(2,"0").toUpperCase()}`};class ColorRGB{#e;#t;#r;#i;constructor(i=255,g=255,x=255,v=void 0){this.#n(i,g,x),this.#a(i,g,x),v&&(this.#i=v)}get r(){return this.#e}set r(i){validateUintRange(i,0,255),this.#e=i,this.#i?.()}get g(){return this.#t}set g(i){validateUintRange(i,0,255),this.#t=i,this.#i?.()}get b(){return this.#r}set b(i){validateUintRange(i,0,255),this.#r=i,this.#i?.()}get rgb(){return[this.#e,this.#t,this.#r]}get rgbNormal(){return[this.#e/255,this.#t/255,this.#r/255]}get rgbNormalLinear(){return[Math.pow(this.#e/255,2.2),Math.pow(this.#t/255,2.2),Math.pow(this.#r/255,2.2)]}get hex(){return convertRgbToHex(this.#e,this.#t,this.#r)}setColorByRGB(i,g,x){this.#n(i,g,x),this.#a(i,g,x)}setColorByHEX(i){const{r:g,g:x,b:v}=convertHexToRgb(i);this.#a(g,x,v)}setColorByRGBString(i){const g=/rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/.exec(i);g||consoleAndThrowError(`유효하지 않은 rgb 색상 값입니다: ${i}`);const[,x,v,_]=g.map(Number);this.#n(x,v,_),this.#a(x,v,_)}#a(i,g,x){this.#e=i,this.#t=g,this.#r=x,this.#i?.()}#n(i,g,x){validateUintRange(i,0,255),validateUintRange(g,0,255),validateUintRange(x,0,255)}}Object.freeze(ColorRGB);class ColorRGBA extends ColorRGB{#s;#i;constructor(i=255,g=255,x=255,v=1,_=void 0){super(i,g,x,_),validatePositiveNumberRange(v,0,1),this.#s=v,_&&(this.#i=_)}get a(){return this.#s}set a(i){validatePositiveNumberRange(i,0,1),this.#s=i,this.#i?.()}get rgba(){return[this.r,this.g,this.b,this.#s]}get rgbaNormal(){return[this.r/255,this.g/255,this.b/255,this.#s]}get rgbaNormalLinear(){return[Math.pow(this.r/255,2.2),Math.pow(this.g/255,2.2),Math.pow(this.b/255,2.2),this.#s]}setColorByRGBA(i,g,x,v){this.#o(i,g,x,v),this.r=i,this.g=g,this.b=x,this.#s=v,this.#i?.()}setColorByRGBAString(i){const g=/rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d*(?:\.\d+)?)\s*\)/.exec(i);if(!g)throw new Error(`유효하지 않은 rgba 색상 값입니다: ${i}`);const[,x,v,_,y]=g.map(Number);this.#o(x,v,_,y),this.r=x,this.g=v,this.b=_,this.#s=y,this.#i?.()}#o(i,g,x,v){validateUintRange(i,0,255),validateUintRange(g,0,255),validateUintRange(x,0,255),validatePositiveNumberRange(v,0,1)}}Object.freeze(ColorRGBA);const i={MOVE:"move",DOWN:"down",UP:"up",OVER:"over",OUT:"out",CLICK:"click"};Object.freeze(i);const copyGPUBuffer=(i,g,x)=>{const v=Math.min(g.size,x.size);if(v%4!=0)throw new Error(`[RedGPU] copyGPUBuffer: Copy size (${v}) must be a multiple of 4 bytes.`);i.copyBufferToBuffer(g,0,x,0,v)},formatBytes=(i,g=2)=>{if(("number"!=typeof i||i<0||Number.isNaN(i)||!Number.isInteger(i))&&consoleAndThrowError("Invalid input: 'bytes' must be a positive integer."),0===i)return"0 Bytes";const x=g<0?0:g,v=Math.floor(Math.log(i)/Math.log(1024));return parseFloat((i/Math.pow(1024,v)).toFixed(x))+" "+["Bytes","KB","MB","GB"][v]};function getAbsoluteURL(i,g){if("string"!=typeof g||!g)throw new Error("relative must be a non-empty string");if("string"!=typeof i&&!(i instanceof URL))throw new Error("base must be a string or URL instance");if("string"==typeof i&&!i)throw new Error("base must be a non-empty string");return new URL(g,i).href}const getFileExtension=i=>{if(!i||0===i.trim().length)throw new Error("URL must not be empty or undefined");const g=i.split("/"),x=g[g.length-1],v=x.lastIndexOf(".");return-1===v?"":x.substring(v+1).toLowerCase()},getFileName=(i,g=!0)=>{const x=i.substring(i.lastIndexOf("/")+1);return g?x:x.split(".").slice(0,-1).join(".")},getFilePath=i=>{if(!i||0===i.trim().length)throw new Error("URL must not be empty or undefined");return i.substring(0,i.lastIndexOf("/")+1)};function calculateTextureByteSize(i){return function(i){switch(i){case"r8unorm":case"r8snorm":case"r8uint":case"r8sint":return 1;case"r16uint":case"r16sint":case"r16float":case"rg8unorm":case"rg8snorm":case"rg8uint":case"rg8sint":case"depth16unorm":return 2;case"r32uint":case"r32sint":case"r32float":case"rg16uint":case"rg16sint":case"rg16float":case"rgba8unorm":case"rgba8unorm-srgb":case"rgba8snorm":case"rgba8uint":case"rgba8sint":case"bgra8unorm":case"bgra8unorm-srgb":case"depth24plus":case"depth32float":return 4;case"rg32uint":case"rg32sint":case"rg32float":case"rgba16uint":case"rgba16sint":case"rgba16float":return 8;case"rgba32uint":case"rgba32sint":case"rgba32float":return 16;default:throw new Error(`Unrecognized texture format: ${i}`)}}(i.format)*(i.width*i.height*(i.depthOrArrayLayers||1))*(i.sampleCount||1)}const getMipLevelCount=(i,g)=>(validateUintRange(i),validateUintRange(g),Math.floor(Math.log2(Math.max(i,g)))+1),imageBitmapToGPUTexture=(i,g,x,v=!0)=>{x.usage|=GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT;const _=i.createTexture(x);for(let y=0;y{const i="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split("");let g,x=0,v=new Array(36);for(v[8]=v[13]=v[18]=v[23]="-",v[14]="4";x<36;)v[x]||(g=16*Math.random()|0,v[x]=i[19===x?3&g|8:15&g]),x++;return v.join("")};class InstanceIdGenerator{static idMaps=new Map;static getNextId(i){let g=this.idMaps.get(i)||0;return this.idMaps.set(i,g+1),g}}Object.freeze(InstanceIdGenerator);const uuidToUint=i=>{const g=i.replace(/-/g,"").substring(0,8);return parseInt(g,16)},g=console.log.bind(console);var x=Object.freeze({__proto__:null,InstanceIdGenerator:InstanceIdGenerator,calculateTextureByteSize:calculateTextureByteSize,copyGPUBuffer:copyGPUBuffer,copyToTextureArray:function(i,g,x,v){i.copyTextureToTexture({texture:g},{texture:x,origin:[0,0,v]},[g.width,g.height,1])},createUUID:createUUID,formatBytes:formatBytes,getAbsoluteURL:getAbsoluteURL,getFileExtension:getFileExtension,getFileName:getFileName,getFilePath:getFilePath,getMipLevelCount:getMipLevelCount,imageBitmapToGPUTexture:imageBitmapToGPUTexture,keepLog:g,loadAndCreateBitmapImage:loadAndCreateBitmapImage,uuidToUint:uuidToUint});const v={CLAMP_TO_EDGE:"clamp-to-edge",REPEAT:"repeat",MIRRORED_REPEAT:"mirror-repeat"};Object.freeze(v);const _={NEAREST:"nearest",LINEAR:"linear"};Object.freeze(_);const y={NEAREST:"nearest",LINEAR:"linear"};Object.freeze(y);const validateRedGPUContext=i=>{if("RedGPUContext"!==i?.constructor?.name){return consoleAndThrowError(`from ${i?.constructor?.name} : requires a RedGPUContext instance, but received : ${i}`),!1}return!0};class BaseObject{#u=createUUID();#l="";#c;constructor(){}get uuid(){return this.#u}get name(){return this.#c||(this.#c=InstanceIdGenerator.getNextId(this.constructor)),this.#l||`${this.constructor.name} Instance ${this.#c}`}set name(i){this.#l=i}}Object.freeze(BaseObject);class RedGPUObject extends BaseObject{#h;constructor(i){super(),validateRedGPUContext(i),this.#h=i}get redGPUContext(){return this.#h}get gpuDevice(){return this.#h.gpuDevice}get resourceManager(){return this.#h.resourceManager}get antialiasingManager(){return this.#h.antialiasingManager}get commandEncoderManager(){return this.#h.commandEncoderManager}}Object.freeze(RedGPUObject);class ResourceBase extends RedGPUObject{#f;#d;#m=[];#p;#g=0;constructor(i,g){super(i),this.#p=g,this.#f=i.gpuDevice}get revision(){return this.#g}get cacheKey(){return this.#d}set cacheKey(i){this.#d=i}get resourceManagerKey(){return this.#p}get gpuDevice(){return this.#f}__addDirtyPipelineListener(i){this.#x(!0),this.#m.push(i)}__removeDirtyPipelineListener(i){const g=this.#m.indexOf(i);g>-1&&(this.#m.splice(g,1),this.#x(!1))}notifyUpdate(i=!1){this.#g++;for(const i of this.#m)i(this);i&&(this.#m.length=0)}#x(i){const{resourceManager:g}=this;if("Sampler"!==this.constructor.name&&g){const x=g[this.#p];x||consoleAndThrowError("need managedStateKey",this.constructor.name);const v=x?.table.get(this.cacheKey);v&&(i?v.useNum++:v.useNum--)}}}const b=new Map,S=Object.values(_),w=Object.values(v),L=Object.values(y);class Sampler extends ResourceBase{#v;#_=_.LINEAR;#y=_.LINEAR;#b=y.LINEAR;#S=v.CLAMP_TO_EDGE;#T=v.CLAMP_TO_EDGE;#w=v.REPEAT;#M;#P;#R;#C=1;constructor(i,g){super(i),this.#B(g)}get addressModeU(){return this.#S}set addressModeU(i){this.#D(i,"addressModeU")}get addressModeV(){return this.#T}set addressModeV(i){this.#D(i,"addressModeV")}get addressModeW(){return this.#w}set addressModeW(i){this.#D(i,"addressModeW")}get mipmapFilter(){return this.#b}set mipmapFilter(i){this.#E(i,L,"mipmapFilter")}get gpuSampler(){return this.#v}get magFilter(){return this.#_}set magFilter(i){this.#E(i,S,"magFilter")}get minFilter(){return this.#y}set minFilter(i){this.#E(i,S,"minFilter")}get maxAnisotropy(){return this.#C}set maxAnisotropy(i){validateUintRange(i,1,16),this.#C=i,this.#B()}get isAnisotropyValid(){return!this.#C||"linear"===this.#_&&"linear"===this.#y&&"linear"===this.#b}#I(){this.notifyUpdate()}#D(i,g){if(w.includes(i)){switch(g){case"addressModeU":this.#S=i;break;case"addressModeV":this.#T=i;break;case"addressModeW":this.#w=i}this.#B()}else consoleAndThrowError(`Invalid ${g} value. Must be one of ${w.join(", ")}, but received: ${i}.`)}#E(i,g,x){if(g.includes(i)||null===i){switch(x){case"mipmapFilter":this.#b=i;break;case"magFilter":this.#_=i;break;case"minFilter":this.#y=i}this.#B()}else consoleAndThrowError(`Invalid ${x} value. Must be one of ${g.join(", ")}, but received: ${i}.`)}#A(){return`${this.#_}:${this.#y}:${this.#b}:${this.#S}:${this.#T}:${this.#w}:${this.#M}:${this.#P}:${this.#R}:${this.#C}`}#B(i){i&&(i.magFilter&&(this.#_=i.magFilter),i.minFilter&&(this.#y=i.minFilter),i.mipmapFilter&&(this.#b=i.mipmapFilter),i.addressModeU&&(this.#S=i.addressModeU),i.addressModeV&&(this.#T=i.addressModeV),i.addressModeW&&(this.#w=i.addressModeW),void 0!==i.lodMinClamp&&(this.#M=i.lodMinClamp),void 0!==i.lodMaxClamp&&(this.#P=i.lodMaxClamp),i.compare&&(this.#R=i.compare),i.maxAnisotropy&&(this.#C=i.maxAnisotropy)),this.isAnisotropyValid||1===this.#C||(console.warn(`Invalid maxAnisotropy setting (${this.#C}) detected: magFilter(${this.#_}), minFilter(${this.#y}), mipmapFilter(${this.#b}) must all be set to 'linear' for anisotropic filtering to work. Falling back to default (1).`),this.#C=1);const g=this.#A();if(!b.has(g)){let i={};this.#_&&(i.magFilter=this.#_),this.#y&&(i.minFilter=this.#y),this.#b&&(i.mipmapFilter=this.#b),this.#S&&(i.addressModeU=this.#S),this.#T&&(i.addressModeV=this.#T),this.#w&&(i.addressModeW=this.#w),void 0!==this.#M&&(i.lodMinClamp=this.#M),void 0!==this.#P&&(i.lodMaxClamp=this.#P),this.#R&&(i.compare=this.#R),this.#C&&(i.maxAnisotropy=this.#C),b.set(g,this.redGPUContext.gpuDevice.createSampler(i))}this.#v=b.get(g),this.#I()}}Object.freeze(Sampler);class BRDFGenerator extends RedGPUObject{#L;#U;#k;constructor(i){super(i)}get brdfLUTTexture(){return this.#k||this.#G(),this.#k}#G(){const{gpuDevice:i,resourceManager:g,commandEncoderManager:x}=this,v="rg16float";this.#k=g.createManagedTexture({size:[128,128],format:v,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT,label:"BRDF_LUT_Texture"}),this.#L||(this.#L=g.createGPUShaderModule("BRDF_GENERATOR_SHADER_MODULE",{code:"#redgpu_include math.PI #redgpu_include math.PI2 #redgpu_include math.tnb.getTBN #redgpu_include math.hash.getHammersley fn importanceSampleGGX(Xi:vec2,N:vec3,roughness:f32)->vec3{let a=roughness*roughness;let phi=PI2*Xi.x;let cosTheta=sqrt((1.0-Xi.y)/(1.0+(a*a-1.0)*Xi.y));let sinTheta=sqrt(1.0-cosTheta*cosTheta);let H_local=vec3(cos(phi)*sinTheta,sin(phi)*sinTheta,cosTheta);let up=select(vec3(1.0,.0,.0),vec3(.0,.0,1.0),abs(N.z)<0.999);let tbn=getTBN(N,up);return normalize(tbn*H_local);}fn geometrySchlickGGX(NdotV:f32,roughness:f32)->f32{let a=roughness;let k=(a*a)/2.0;let nom=NdotV;let denom=NdotV*(1.0-k)+k;return nom/denom;}fn geometrySmith(N:vec3,V:vec3,L:vec3,roughness:f32)->f32{let NdotV=max(dot(N,V),.0);let NdotL=max(dot(N,L),.0);let ggx2=geometrySchlickGGX(NdotV,roughness);let ggx1=geometrySchlickGGX(NdotL,roughness);return ggx1*ggx2;}fn integrateBRDF(in_NdotV:f32,roughness:f32)->vec2{let NdotV=max(in_NdotV,.0);var V:vec3;V.x=sqrt(max(.0,1.0-NdotV*NdotV));V.y=.0;V.z=NdotV;var A=.0;var B=.0;let N=vec3(.0,.0,1.0);let sampleCount=2048u;for(var i=0u;i.0){let G=geometrySmith(N,V,L,roughness);let G_Vis=(G*VdotH)/(max(NdotH*NdotV,1e-8));let Fc=pow(1.0-VdotH,5.0);A=A+(1.0-Fc)*G_Vis;B=B+Fc*G_Vis;}}return vec2(A,B)/f32(sampleCount);}struct VertexOutput{@builtin(position)position:vec4,@location(0)uv:vec2,};@vertex fn vs_main(@builtin(vertex_index)vertexIndex:u32)->VertexOutput{var pos=array,3>(vec2(-1.0,-1.0),vec2(3.0,-1.0),vec2(-1.0,3.0));var output:VertexOutput;output.position=vec4(pos[vertexIndex],.0,1.0);output.uv=pos[vertexIndex]*0.5+0.5;return output;}@fragment fn fs_main(@location(0)uv:vec2)->@location(0)vec4{let integratedBRDF=integrateBRDF(uv.x,1.0-uv.y);return vec4(integratedBRDF,.0,1.0);}"})),this.#U||(this.#U=i.createRenderPipeline({label:"BRDF_GENERATOR_PIPELINE",layout:"auto",vertex:{module:this.#L,entryPoint:"vs_main"},fragment:{module:this.#L,entryPoint:"fs_main",targets:[{format:v}]},primitive:{topology:"triangle-list"}})),x.addResourceRenderPass({label:"BRDF_GENERATOR_RENDER_PASS",colorAttachments:[{view:this.#k.createView(),loadOp:"clear",clearValue:{r:0,g:0,b:0,a:1},storeOp:"store"}]},i=>{i.setPipeline(this.#U),i.draw(3)})}}Object.freeze(BRDFGenerator);class ManagementResourceBase extends ResourceBase{#O;constructor(i,g){super(i,g),g||consoleAndThrowError("need managedStateKey",this.constructor.name),this.#O=i.resourceManager[g],this.#O||consoleAndThrowError(g,"is not exist in RedGPUContext.resourceManager",this.constructor.name)}get targetResourceManagedState(){return this.#O}}class BRDFLUTTexture extends ManagementResourceBase{#V;constructor(i){super(i,"managedBitmapTextureState"),this.#N()}get gpuTexture(){return this.#V}get videoMemorySize(){return 65536}#N(){this.#V=this.redGPUContext.resourceManager.brdfGenerator.brdfLUTTexture,this.notifyUpdate()}}Object.freeze(BRDFLUTTexture);class ResourceStateCubeTexture{texture;srcList;cacheKey;useNum=0;uuid;constructor(i){this.texture=i,this.srcList="CubeTexture"===i.constructor.name?i.srcList:void 0,this.cacheKey=i.cacheKey,this.useNum=0,this.uuid=i.uuid}}class ADirectTexture extends ManagementResourceBase{#V;#F;#H=0;#z;#$=1;constructor(i,g,x){super(i,g),this.cacheKey=x}get gpuTexture(){return this.#V}set gpuTexture(i){this.setGpuTexture(i)}get gpuTextureView(){return this.#F}get videoMemorySize(){return this.#H}get format(){return this.#z}get mipLevelCount(){return this.#$}destroy(){const i=this.#V;this.setGpuTexture(null),this.notifyUpdate(!0),this.unregisterResource(),this.cacheKey=null,i&&this.redGPUContext.commandEncoderManager.addDeferredDestroy(i)}setGpuTexture(i){this.targetResourceManagedState.videoMemory-=this.#H,this.#V=i,i?(this.#z=i.format,this.#$=i.mipLevelCount,this.#H=calculateTextureByteSize(i),this.#F=i.createView(this.viewDescriptor)):(this.#F=null,this.#z=null,this.#$=0,this.#H=0),this.targetResourceManagedState.videoMemory+=this.#H,this.notifyUpdate()}}class CubeTexture extends ManagementResourceBase{static defaultViewDescriptor={dimension:"cube",aspect:"all",baseMipLevel:0,mipLevelCount:1,baseArrayLayer:0,arrayLayerCount:6};#V;#j;#$;#K;#X;#H=0;#z;#q;#Y;constructor(i,g,x=!0,v,_,y){super(i,"managedCubeTextureState"),this.#q=v,this.#Y=_,this.#K=x,this.#z=y||`${navigator.gpu.getPreferredCanvasFormat()}-srgb`,this.#j=this.#W(g),this.cacheKey=this.#Z(g);const{table:b}=this.targetResourceManagedState;if(g){let i=b.get(this.cacheKey);if(i){const g=i.texture;return this.#q?.(g),g}this.srcList=g,this.#J()}}get viewDescriptor(){return{...CubeTexture.defaultViewDescriptor,mipLevelCount:this.#$}}get videoMemorySize(){return this.#H}get gpuTexture(){return this.#V}get mipLevelCount(){return this.#$}get srcList(){return this.#j}set srcList(i){this.#j=this.#W(i),this.cacheKey=this.#Z(i),this.#j?.length&&this.#Q(this.#j)}get useMipmap(){return this.#K}set useMipmap(i){this.#K=i,this.#ee()}destroy(){const i=this.#V;this.#te(null),this.notifyUpdate(!0),this.#re(),this.#j=null,this.cacheKey=null,i&&this.redGPUContext.commandEncoderManager.addDeferredDestroy(i)}setGPUTextureDirectly(i,g,x=!0){this.#V&&(this.redGPUContext.commandEncoderManager.addDeferredDestroy(this.#V),this.targetResourceManagedState.videoMemory-=this.#H),this.#V=i,this.#K=x,this.#$=i.mipLevelCount,this.cacheKey=g||`direct_${this.uuid}`,this.#H=calculateTextureByteSize(i),this.targetResourceManagedState.videoMemory+=this.#H,this.notifyUpdate()}#Z(i){return i?i instanceof Array?i.length?i.toString():this.uuid:i.cacheKey||i.srcList.toString():this.uuid}#W(i){return i instanceof Array?i:i?.srcList}#te(i){this.#V=i,i||(this.#X=null),this.notifyUpdate()}#J(){this.redGPUContext.resourceManager.registerManagementResource(this,new ResourceStateCubeTexture(this))}#re(){this.redGPUContext.resourceManager.unregisterManagementResource(this)}#ee(){const{gpuDevice:i,resourceManager:g}=this.redGPUContext,{mipmapGenerator:x}=g;this.#V&&(this.redGPUContext.commandEncoderManager.addDeferredDestroy(this.#V),this.#V=null),this.#$=1;{const g=this.#X,v=g[0],{width:_,height:y}=v,b={size:[_,y,6],format:this.#z,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC,label:`cubeTexture_${this.#j?.toString()||this.uuid}`};this.#K&&(this.#$=getMipLevelCount(_,y),b.mipLevelCount=this.#$,b.usage|=GPUTextureUsage.RENDER_ATTACHMENT);const S=imageBitmapToGPUTexture(i,g,b);this.targetResourceManagedState.videoMemory-=this.#H,this.#H=calculateTextureByteSize(S),this.targetResourceManagedState.videoMemory+=this.#H,this.#K&&x.generateMipmap(S,b),this.#te(S)}}async#Q(i){this.#X=await async function(i){const g=i.map(i=>loadAndCreateBitmapImage(i));return await Promise.all(g)}(i);try{this.#ee(),this.#q?.(this)}catch(i){console.error(i),this.#Y?.(i)}}}Object.freeze(CubeTexture);class DirectCubeTexture extends ADirectTexture{#ie="2d";constructor(i,g,x){super(i,"managedCubeTextureState",g);const{table:v}=this.targetResourceManagedState;if(g){const i=v.get(g);if(i)return i.texture}x&&this.setGpuTexture(x),this.registerResource()}get viewDescriptor(){const i="3d"===this.#ie;return{...CubeTexture.defaultViewDescriptor,dimension:i?"3d":"cube",arrayLayerCount:i?1:6,mipLevelCount:this.mipLevelCount}}setGpuTexture(i){i&&(this.#ie=i.dimension),super.setGpuTexture(i)}registerResource(){this.redGPUContext.resourceManager.registerManagementResource(this,new ResourceStateCubeTexture(this))}unregisterResource(){this.redGPUContext.resourceManager.unregisterManagementResource(this)}}Object.freeze(DirectCubeTexture);const k={RESOURCE:"RESOURCE",PRE_PROCESS:"PRE_PROCESS",MAIN:"MAIN",POST_PROCESS:"POST_PROCESS"};class IrradianceGenerator extends RedGPUObject{#ne;#U;#ae;#se;constructor(i){super(i),this.#ne=new Sampler(i,{magFilter:_.LINEAR,minFilter:_.LINEAR,mipmapFilter:y.LINEAR,addressModeU:v.CLAMP_TO_EDGE,addressModeV:v.CLAMP_TO_EDGE,addressModeW:v.CLAMP_TO_EDGE})}async generate(i,g=32,x=k.RESOURCE){const{resourceManager:v,redGPUContext:_}=this,y=v.createManagedTexture({size:[g,g,6],format:"rgba16float",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.COPY_SRC|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT,dimension:"2d",mipLevelCount:1,label:`Irradiance_Map_Texture_${createUUID()}`});return await this.render(i,y,x),new DirectCubeTexture(_,`Irradiance_Map_${createUUID()}`,y)}async render(i,g,x=k.RESOURCE){const{gpuDevice:v,resourceManager:_,commandEncoderManager:y}=this,b=g.width;this.#ae||(this.#ae=_.createGPUShaderModule("IRRADIANCE_GENERATOR_SHADER_MODULE",{code:"@group(0)@binding(0)var environmentTexture:texture_cube;@group(0)@binding(1)var environmentSampler:sampler;@group(0)@binding(2)var outTexture:texture_storage_2d_array;@group(0)@binding(3)varfaceMatrices:array,6>;#redgpu_include math.PI #redgpu_include math.PI2 #redgpu_include math.INV_PI #redgpu_include math.tnb.getTBN #redgpu_include math.hash.getHammersley @compute @workgroup_size(8,8,1)fn cs_main(@builtin(global_invocation_id)global_id:vec3){let size_u=textureDimensions(outTexture);let size=vec2(size_u);if(global_id.x>=size_u.x||global_id.y>=size_u.y||global_id.z>=6u){return;}let face=global_id.z;let uv=(vec2(global_id.xy)+0.5)/size;let x=uv.x*2.0-1.0;let y=uv.y*2.0-1.0;let localPos=vec4(x,y,1.0,1.0);let normal=normalize((faceMatrices[face]*localPos).xyz);let up=select(vec3(1.0,.0,.0),vec3(.0,.0,1.0),abs(normal.z)<0.999);let tbn=getTBN(normal,up);var irradiance=vec3(.0);var totalWeight=.0;let totalSamples=1024u;let envSize=f32(textureDimensions(environmentTexture).x);let saTexel=4.0*PI/(6.0*envSize*envSize);for(var i=0u;i(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);let worldSample=normalize(tbn*sampleVec);let pdf=max(cosTheta,.001)*INV_PI;let saSample=1.0/(f32(totalSamples)*pdf+.0001);let mipLevel=max(0.5*log2(saSample/saTexel),.0);let sampleColor=textureSampleLevel(environmentTexture,environmentSampler,worldSample,mipLevel);irradiance+=sampleColor.rgb;totalWeight+=1.0;}irradiance=(irradiance/totalWeight)*PI;textureStore(outTexture,global_id.xy,face,vec4(irradiance,1.0));}"})),this.#U||(this.#U=v.createComputePipeline({label:"IRRADIANCE_GENERATOR_PIPELINE",layout:"auto",compute:{module:this.#ae,entryPoint:"cs_main"}}));const S=this.#oe();this.#se||(this.#se=v.createBuffer({size:384,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,label:"Irradiance_face_matrices_uniform"}));const w=new Float32Array(96);S.forEach((i,g)=>w.set(i,16*g)),v.queue.writeBuffer(this.#se,0,w);const L=v.createBindGroup({layout:this.#U.getBindGroupLayout(0),entries:[{binding:0,resource:i.createView({dimension:"cube"})},{binding:1,resource:this.#ne.gpuSampler},{binding:2,resource:g.createView({dimension:"2d-array"})},{binding:3,resource:{buffer:this.#se}}]}),H="Irradiance_Generator_Compute_Pass",computePassExecutor=i=>{i.setPipeline(this.#U),i.setBindGroup(0,L),i.dispatchWorkgroups(Math.ceil(b/8),Math.ceil(b/8),6)};x===k.RESOURCE?y.addResourceComputePass(H,computePassExecutor):x===k.PRE_PROCESS?y.addPreProcessComputePass(H,computePassExecutor):x===k.MAIN?y.addMainComputePass(H,computePassExecutor):y.addPostProcessComputePass(H,computePassExecutor)}#oe(){return[new Float32Array([0,0,-1,0,0,-1,0,0,1,0,0,0,0,0,0,1]),new Float32Array([0,0,1,0,0,-1,0,0,-1,0,0,0,0,0,0,1]),new Float32Array([1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1]),new Float32Array([1,0,0,0,0,0,-1,0,0,-1,0,0,0,0,0,1]),new Float32Array([1,0,0,0,0,-1,0,0,0,0,1,0,0,0,0,1]),new Float32Array([-1,0,0,0,0,-1,0,0,0,0,-1,0,0,0,0,1])]}}Object.freeze(IrradianceGenerator);class PrefilterGenerator extends RedGPUObject{#ne;#U;#ae;#ue=[];constructor(i){super(i),this.#ne=new Sampler(i,{magFilter:_.LINEAR,minFilter:_.LINEAR,addressModeU:v.CLAMP_TO_EDGE,addressModeV:v.CLAMP_TO_EDGE,addressModeW:v.CLAMP_TO_EDGE})}async generate(i,g=512,x,v=k.RESOURCE){const{gpuDevice:_,resourceManager:y,commandEncoderManager:b,redGPUContext:S}=this,w="rgba16float",L=getMipLevelCount(g,g);let H;x?(H=x instanceof GPUTexture?x:x.gpuTexture,H||(H=y.createManagedTexture({size:[g,g,6],format:w,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.COPY_SRC|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT,dimension:"2d",mipLevelCount:L,label:`Prefilter_Map_Texture_${createUUID()}`}),x instanceof DirectCubeTexture&&(x.gpuTexture=H))):H=y.createManagedTexture({size:[g,g,6],format:w,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.COPY_SRC|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT,dimension:"2d",mipLevelCount:L,label:`Prefilter_Map_Texture_${createUUID()}`}),this.#ae||(this.#ae=y.createGPUShaderModule("PREFILTER_GENERATOR_SHADER_MODULE",{code:"@group(0)@binding(0)var environmentTexture:texture_cube;@group(0)@binding(1)var textureSampler:sampler;@group(0)@binding(2)var outTexture:texture_storage_2d_array;struct PrefilterUniforms{faceMatrices:array,6>,roughness:f32,}@group(0)@binding(3)varuniforms:PrefilterUniforms;#redgpu_include math.PI #redgpu_include math.PI2 #redgpu_include math.tnb.getTBN #redgpu_include math.hash.getHammersley fn distribution_ggx(NdotH:f32,roughness:f32)->f32{let a=roughness*roughness;let a2=a*a;let NdotH2=NdotH*NdotH;let denom=(NdotH2*(a2-1.0)+1.0);return a2/(PI*denom*denom);}fn importanceSampleGGX(xi:vec2,N:vec3,roughness:f32)->vec3{let a=roughness*roughness;let phi=PI2*xi.x;let cosTheta=sqrt((1.0-xi.y)/(1.0+(a*a-1.0)*xi.y));let sinTheta=sqrt(max(.0,1.0-cosTheta*cosTheta));let H_local=vec3(cos(phi)*sinTheta,sin(phi)*sinTheta,cosTheta);let up=select(vec3(1.0,.0,.0),vec3(.0,.0,1.0),abs(N.z)<0.999);let tbn=getTBN(N,up);return normalize(tbn*H_local);}@compute @workgroup_size(8,8,1)fn cs_main(@builtin(global_invocation_id)global_id:vec3){let size_u=textureDimensions(outTexture);let size=vec2(size_u);if(global_id.x>=size_u.x||global_id.y>=size_u.y||global_id.z>=6u){return;}let face=global_id.z;let roughness=uniforms.roughness;let uv=(vec2(global_id.xy)+0.5)/size;let x=uv.x*2.0-1.0;let y=uv.y*2.0-1.0;let localPos=vec4(x,y,1.0,1.0);let N=normalize((uniforms.faceMatrices[face]*localPos).xyz);if(roughness<=.0){textureStore(outTexture,global_id.xy,face,textureSampleLevel(environmentTexture,textureSampler,N,.0));return;}let R=N;let V=R;var prefilteredColor=vec3(.0);var totalWeight=.0;let numSamples=1024u;let envSize=f32(textureDimensions(environmentTexture).x);let saTexel=4.0*PI/(6.0*envSize*envSize);for(var i=0u;i.0){let NdotH=max(dot(N,H),.001);let VdotH=max(dot(V,H),.001);let D=distribution_ggx(NdotH,roughness);let pdf=(D*NdotH/(4.0*VdotH))+.0001;let saSample=1.0/(f32(numSamples)*pdf+.0001);let mipLevel=max(0.5*log2(saSample/saTexel),.0);prefilteredColor+=textureSampleLevel(environmentTexture,textureSampler,L,mipLevel).rgb*NdotL;totalWeight+=NdotL;}}if(totalWeight>.0){textureStore(outTexture,global_id.xy,face,vec4(prefilteredColor/totalWeight,1.0));}else{textureStore(outTexture,global_id.xy,face,textureSampleLevel(environmentTexture,textureSampler,N,.0));}}"})),this.#U||(this.#U=_.createComputePipeline({label:"PREFILTER_GENERATOR_PIPELINE",layout:"auto",compute:{module:this.#ae,entryPoint:"cs_main"}}));const z=this.#oe();for(let x=0;x>x),S=x/(L-1),w=new Float32Array(100);z.forEach((i,g)=>w.set(i,16*g)),w[96]=S,this.#ue[x]||(this.#ue[x]=_.createBuffer({size:w.byteLength,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,label:`Prefilter_UniformBuffer_Mip${x}`})),_.queue.writeBuffer(this.#ue[x],0,w);const q=_.createBindGroup({layout:this.#U.getBindGroupLayout(0),entries:[{binding:0,resource:i.createView({dimension:"cube"})},{binding:1,resource:this.#ne.gpuSampler},{binding:2,resource:H.createView({dimension:"2d-array",baseMipLevel:x,mipLevelCount:1})},{binding:3,resource:{buffer:this.#ue[x]}}]}),W=`Prefilter_mip_${x}_compute_pass`,computePassExecutor=i=>{i.setPipeline(this.#U),i.setBindGroup(0,q),i.dispatchWorkgroups(Math.ceil(y/8),Math.ceil(y/8),6)};v===k.RESOURCE?b.addResourceComputePass(W,computePassExecutor):v===k.PRE_PROCESS?b.addPreProcessComputePass(W,computePassExecutor):v===k.MAIN?b.addMainComputePass(W,computePassExecutor):b.addPostProcessComputePass(W,computePassExecutor)}return x instanceof DirectCubeTexture?(x.notifyUpdate(),x):new DirectCubeTexture(S,`Prefilter_Map_${createUUID()}`,H)}#oe(){return[new Float32Array([0,0,-1,0,0,-1,0,0,1,0,0,0,0,0,0,1]),new Float32Array([0,0,1,0,0,-1,0,0,-1,0,0,0,0,0,0,1]),new Float32Array([1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1]),new Float32Array([1,0,0,0,0,0,-1,0,0,-1,0,0,0,0,0,1]),new Float32Array([1,0,0,0,0,-1,0,0,0,0,1,0,0,0,0,1]),new Float32Array([-1,0,0,0,0,-1,0,0,0,0,-1,0,0,0,0,1])]}}Object.freeze(PrefilterGenerator);class EquirectangularToCubeGenerator extends RedGPUObject{#ae;#U;#ne;#se;constructor(i){super(i),this.#ne=new Sampler(i,{magFilter:_.LINEAR,minFilter:_.LINEAR,addressModeU:v.CLAMP_TO_EDGE,addressModeV:v.CLAMP_TO_EDGE})}async generate(i,g=512){const{gpuDevice:x,resourceManager:v,commandEncoderManager:_,redGPUContext:y}=this,b=getMipLevelCount(g,g),S={size:[g,g,6],format:"rgba16float",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.COPY_SRC|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT,dimension:"2d",mipLevelCount:b,label:`EquirectangularToCube_Texture_${createUUID()}`},w=v.createManagedTexture(S);this.#ae||(this.#ae=v.createGPUShaderModule("EQUIRECTANGULAR_TO_CUBE_GENERATOR_SHADER_MODULE",{code:"@group(0)@binding(0)var equirectangularTexture:texture_2d;@group(0)@binding(1)var textureSampler:sampler;@group(0)@binding(2)var outTexture:texture_storage_2d_array;@group(0)@binding(3)varfaceMatrices:array,6>;#redgpu_include math.PI #redgpu_include math.PI2 #redgpu_include math.INV_PI fn directionToSphericalUV(dir:vec3)->vec2{let normalizedDir=normalize(dir);let theta=atan2(normalizedDir.x,normalizedDir.z);let phi=acos(clamp(normalizedDir.y,-1.0,1.0));return vec2(0.5-theta/PI2,phi*INV_PI);}@compute @workgroup_size(8,8,1)fn cs_main(@builtin(global_invocation_id)global_id:vec3){let size=textureDimensions(outTexture);if(global_id.x>=size.x||global_id.y>=size.y||global_id.z>=6u){return;}let face=global_id.z;let uv=(vec2(global_id.xy)+0.5)/vec2(size);let x=uv.x*2.0-1.0;let y=uv.y*2.0-1.0;let localPos=vec4(x,y,1.0,1.0);let direction=(faceMatrices[face]*localPos).xyz;let sphericalUV=directionToSphericalUV(direction);let color=textureSampleLevel(equirectangularTexture,textureSampler,sphericalUV,.0);textureStore(outTexture,global_id.xy,face,color);}"})),this.#U||(this.#U=x.createComputePipeline({label:"EQUIRECTANGULAR_TO_CUBE_GENERATOR_PIPELINE",layout:"auto",compute:{module:this.#ae,entryPoint:"cs_main"}}));const L=this.#oe();this.#se||(this.#se=x.createBuffer({size:384,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,label:"EquirectangularToCube_face_matrices_uniform"}));const k=new Float32Array(96);L.forEach((i,g)=>k.set(i,16*g)),x.queue.writeBuffer(this.#se,0,k);const H=x.createBindGroup({layout:this.#U.getBindGroupLayout(0),entries:[{binding:0,resource:i.createView()},{binding:1,resource:this.#ne.gpuSampler},{binding:2,resource:w.createView({dimension:"2d-array",baseMipLevel:0,mipLevelCount:1})},{binding:3,resource:{buffer:this.#se}}]});return _.addResourceComputePass({label:"EquirectangularToCube_Generator_Compute_Pass"},i=>{i.setPipeline(this.#U),i.setBindGroup(0,H),i.dispatchWorkgroups(Math.ceil(g/8),Math.ceil(g/8),6)}),v.mipmapGenerator.generateMipmap(w,S,!0),new DirectCubeTexture(y,`CubeMap_From_Equirect_${createUUID()}`,w)}#oe(){return[new Float32Array([0,0,-1,0,0,-1,0,0,1,0,0,0,0,0,0,1]),new Float32Array([0,0,1,0,0,-1,0,0,-1,0,0,0,0,0,0,1]),new Float32Array([1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1]),new Float32Array([1,0,0,0,0,0,-1,0,0,-1,0,0,0,0,0,1]),new Float32Array([1,0,0,0,0,-1,0,0,0,0,1,0,0,0,0,1]),new Float32Array([-1,0,0,0,0,-1,0,0,0,0,-1,0,0,0,0,1])]}}Object.freeze(EquirectangularToCubeGenerator);var H=Object.freeze({__proto__:null,BRDFGenerator:BRDFGenerator,BRDFLUTTexture:BRDFLUTTexture,EquirectangularToCubeGenerator:EquirectangularToCubeGenerator,IrradianceGenerator:IrradianceGenerator,PrefilterGenerator:PrefilterGenerator});class DownSampleCubeMapGenerator extends RedGPUObject{#le=new Map;#ce=new Map;#he=null;#fe=null;#de=new Map;#me=new Map;#pe=[];constructor(i){super(i)}createSourceTextureView(i,g){const x=`DOWN_SAMPLE_CUBE_GENERATOR_SOURCE_VIEW_${i.label}_${g}`;if(!this.#de.has(x)){const v=i.createView({label:x,dimension:"cube",baseMipLevel:g,mipLevelCount:1});this.#de.set(x,v)}return this.#de.get(x)}createTargetTextureView(i,g){const x=`DOWN_SAMPLE_CUBE_GENERATOR_TARGET_VIEW_${i.label}_${g}`;if(!this.#de.has(x)){const v=i.createView({label:x,dimension:"2d-array",baseMipLevel:g,mipLevelCount:1,arrayLayerCount:6});this.#de.set(x,v)}return this.#de.get(x)}createBindGroup(i,g,x,v){const _=`DOWN_SAMPLE_CUBE_GENERATOR_BIND_GROUP_${g.label}_${x.label}`;if(!this.#me.has(_)){const{gpuDevice:y}=this,b=y.createBindGroup({label:_,layout:i,entries:[{binding:0,resource:g},{binding:1,resource:x},{binding:2,resource:this.#fe},{binding:3,resource:{buffer:v}}]});this.#me.set(_,b)}return this.#me.get(_)}async downsampleCubemap(i,g=256,x="rgba16float"){try{this.#ge(),this.#xe();const{resourceManager:v}=this;if(!i)throw new Error("Invalid source cubemap texture");if(g<=0||!Number.isInteger(g))throw new Error("Target size must be a positive integer");const _=i.mipLevelCount,y=getMipLevelCount(g,g),b=v.createManagedTexture({size:[g,g,6],format:x,usage:GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.RENDER_ATTACHMENT,dimension:"2d",mipLevelCount:y,label:`DOWN_SAMPLE_CUBE_GENERATOR_TEXTURE_${g}_${Date.now()}`});for(let v=0;v>v),S=this.#ve(i.width,g,v,_);this.#_e(i,b,S,v,y,x)}return this.#ge(),b}catch(i){throw console.error("큐브맵 다운샘플링 실패:",i),this.#ge(),i}}destroy(){this.#ge(),this.#pe.forEach(i=>i.destroy()),this.#pe=[],this.#le.clear(),this.#ce.clear(),this.#he=null,this.#fe=null}#ve(i,g,x,v){const _=i/Math.max(1,g>>x),y=Math.max(0,Math.floor(Math.log2(_)));return Math.min(y,v-1)}#_e(i,g,x,v,_,y){const{gpuDevice:b,commandEncoderManager:S}=this,w=this.#ye(y),L=this.#ce.get(y);this.#pe[v]||(this.#pe[v]=b.createBuffer({size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,label:`DOWN_SAMPLE_CUBE_GENERATOR_UNIFORM_BUFFER_MIP${v}`}));const k=this.#pe[v],H=this.createSourceTextureView(i,x),z=this.createTargetTextureView(g,v),q=this.createBindGroup(L,H,z,k);this.#be(k,x,v,_),S.addResourceComputePass({label:`DOWN_SAMPLE_CUBE_GENERATOR_PASS_MIP${v}`},i=>{i.setPipeline(w),i.setBindGroup(0,q);const g=Math.ceil(_/8);i.dispatchWorkgroups(g,g,6)})}#be(i,g,x,v){const _=new Float32Array([v,g,x,0]);this.gpuDevice.queue.writeBuffer(i,0,_)}#xe(){if(this.#he)return;const{resourceManager:i,redGPUContext:g}=this;this.#fe=new Sampler(g,{minFilter:"linear",magFilter:"linear",mipmapFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge",addressModeW:"clamp-to-edge"}).gpuSampler,this.#he=i.createGPUShaderModule("DOWN_SAMPLE_CUBE_GENERATOR_COMPUTE_SHADER",{code:"struct Uniforms{targetSize:f32,sourceMipLevel:f32,targetMipLevel:f32,padding:f32,};@group(0)@binding(0)var sourceCubemap:texture_cube;@group(0)@binding(1)var targetCubemap:texture_storage_2d_array;@group(0)@binding(2)var cubemapSampler:sampler;@group(0)@binding(3)varuniforms:Uniforms;fn cubemapUVToDirection(uv:vec2,face:u32)->vec3{let u=uv.x*2.0-1.0;let v=uv.y*2.0-1.0;switch face{case 0u:{return vec3(1.0,-v,-u);}case 1u:{return vec3(-1.0,-v,u);}case 2u:{return vec3(u,1.0,v);}case 3u:{return vec3(u,-1.0,-v);}case 4u:{return vec3(u,-v,1.0);}case 5u:{return vec3(-u,-v,-1.0);}default:{return vec3(.0,.0,1.0);}}}fn gaussianWeight(x:f32,y:f32,sigma:f32)->f32{let sigmaSq=sigma*sigma;return exp(-(x*x+y*y)/(2.0*sigmaSq))/(2.0*PI*sigmaSq);}fn clampCubemapUV(uv:vec2)->vec2{return clamp(uv,vec2(.0),vec2(1.0));}#redgpu_include color.getLuminance #redgpu_include math.PI @compute @workgroup_size(8,8,1)fn main(@builtin(global_invocation_id)global_id:vec3){let face=global_id.z;let coord=vec2(global_id.xy);let targetSize=u32(uniforms.targetSize);if(coord.x>=targetSize||coord.y>=targetSize||face>=6u){return;}let uv=(vec2(coord)+0.5)/f32(targetSize);let direction=normalize(cubemapUVToDirection(uv,face));let sourceMipLevel=uniforms.sourceMipLevel;let targetMipLevel=uniforms.targetMipLevel;var color=vec4(.0);if(sourceMipLevel==.0&&targetSize>64u){let sampleCount=16u;let sampleRadius=1.0/f32(targetSize);var totalWeight=.0;for(var i=0u;i(cos(angle)*radius,sin(angle)*radius));let sampleDir=normalize(cubemapUVToDirection(offsetUV,face));let sampleColor=textureSampleLevel(sourceCubemap,cubemapSampler,sampleDir,sourceMipLevel);let weight=gaussianWeight(cos(angle)*radius*f32(targetSize),sin(angle)*radius*f32(targetSize),0.8);color+=sampleColor*weight;totalWeight+=weight;}if(totalWeight>.0){color=color/totalWeight;}}else if(sourceMipLevel==.0&&targetSize>16u){let sampleCount=4u;let invSampleCount=1.0/f32(sampleCount*sampleCount);let sampleOffset=0.5/f32(targetSize);for(var x=0u;x((f32(x)-1.5)*sampleOffset,(f32(y)-1.5)*sampleOffset);let offsetUV=clampCubemapUV(uv+offset);let sampleDir=normalize(cubemapUVToDirection(offsetUV,face));color+=textureSampleLevel(sourceCubemap,cubemapSampler,sampleDir,sourceMipLevel);}}color*=invSampleCount;}else if(targetSize>4u){let sampleCount=2u;let invSampleCount=1.0/f32(sampleCount*sampleCount);let sampleOffset=0.25/f32(targetSize);for(var x=0u;x((f32(x)-0.5)*sampleOffset,(f32(y)-0.5)*sampleOffset);let offsetUV=clampCubemapUV(uv+offset);let sampleDir=normalize(cubemapUVToDirection(offsetUV,face));color+=textureSampleLevel(sourceCubemap,cubemapSampler,sampleDir,sourceMipLevel);}}color*=invSampleCount;}else{color=textureSampleLevel(sourceCubemap,cubemapSampler,direction,sourceMipLevel);}if(targetMipLevel>.0){let luminance=getLuminance(color.rgb);let saturation=0.9+0.1/(1.0+targetMipLevel*0.1);color=vec4(mix(vec3(luminance),color.rgb,saturation),color.a);}textureStore(targetCubemap,vec2(coord),i32(face),color);}"})}#ye(i){if(!this.#le.has(i)){const{gpuDevice:g,resourceManager:x}=this,v=x.createBindGroupLayout(`DOWN_SAMPLE_CUBE_GENERATOR_BGL_${i}`,{entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,texture:{viewDimension:"cube"}},{binding:1,visibility:GPUShaderStage.COMPUTE,storageTexture:{format:i,viewDimension:"2d-array"}},{binding:2,visibility:GPUShaderStage.COMPUTE,sampler:{type:"filtering"}},{binding:3,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}}]}),_=g.createComputePipeline({label:`DOWN_SAMPLE_CUBE_GENERATOR_PIPELINE_${i}`,layout:g.createPipelineLayout({bindGroupLayouts:[v]}),compute:{module:this.#he,entryPoint:"main"}});this.#ce.set(i,v),this.#le.set(i,_)}return this.#le.get(i)}#ge(){this.#de.clear(),this.#me.clear()}}Object.freeze(DownSampleCubeMapGenerator);const z={LOAD:"load",CLEAR:"clear"};Object.freeze(z);const q={STORE:"store",DISCARD:"discard"};Object.freeze(q);class MipmapGenerator extends RedGPUObject{#ne;#Se;#Te;#we;#Me;#de=new Map;#me=new Map;#Pe=new WeakMap;#Re=new WeakMap;constructor(i){super(i),this.#ne=new Sampler(i,{minFilter:"linear"}).gpuSampler,this.#Te={}}createTextureView(i,g,x,v=!1){const _=`${g}_${x}`;if(v){let v=this.#Re.get(i);if(v||(v=new Map,this.#Re.set(i,v)),v.has(_))return v.get(_);const y=i.createView({baseMipLevel:g,mipLevelCount:1,dimension:"2d",baseArrayLayer:x,arrayLayerCount:1,label:`MIPMAP_GENERATOR_CACHED_${i.label}_${_}`});return v.set(_,y),y}{const v=`MIPMAP_GENERATOR_${i.label}_${g}_${x}`;if(!this.#de.has(v)){const _=i.createView({baseMipLevel:g,mipLevelCount:1,dimension:"2d",baseArrayLayer:x,arrayLayerCount:1,label:v});this.#de.set(v,_)}return this.#de.get(v)}}createBindGroup(i,g,x=!1){const{gpuDevice:v}=this;if(x){let x=this.#Pe.get(i);x||(x=new Map,this.#Pe.set(i,x));const _=g.label||"unlabeled";if(x.has(_))return x.get(_);const y=v.createBindGroup({label:`MIPMAP_GENERATOR_BIND_GROUP_CACHED_${i.label}_${_}`,layout:this.#we,entries:[{binding:0,resource:this.#ne},{binding:1,resource:g}]});return x.set(_,y),y}{const x=`${i.label}_${g.label}`;if(this.#me.has(x))return this.#me.get(x);const _=v.createBindGroup({label:`MIPMAP_GENERATOR_BIND_GROUP_TEMP_${x}`,layout:this.#we,entries:[{binding:0,resource:this.#ne},{binding:1,resource:g}]});return this.#me.set(x,_),_}}getMipmapPipeline(i){const{gpuDevice:g,resourceManager:x}=this;let v=this.#Te[i];return v||(this.#Me||(this.#Me=x.createGPUShaderModule("MIPMAP_GENERATOR_SHADER_MODULE",{code:"varpos:array,3>=array,3>(vec2(-1.0,-1.0),vec2(-1.0,3.0),vec2(3.0,-1.0));struct VertexOutput{@builtin(position)position:vec4,@location(0)texCoord:vec2,};@vertex fn vertexMain(@builtin(vertex_index)vertexIndex:u32)->VertexOutput{var output:VertexOutput;output.texCoord=pos[vertexIndex]*vec2(0.5,-0.5)+vec2(0.5);output.position=vec4(pos[vertexIndex],.0,1.0);return output;}@group(0)@binding(0)var imgSampler:sampler;@group(0)@binding(1)var img:texture_2d;@fragment fn fragmentMain(@location(0)texCoord:vec2)->@location(0)vec4{return textureSample(img,imgSampler,texCoord);}"}),this.#we=x.createBindGroupLayout("MIPMAP_GENERATOR_FRAGMENT_BIND_GROUP_LAYOUT",{entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,sampler:{}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{}}]}),this.#Se=x.createGPUPipelineLayout("MIPMAP_GENERATOR_PIPELINE_LAYOUT",{bindGroupLayouts:[this.#we]})),v=g.createRenderPipeline({label:`MIPMAP_GENERATOR_PIPELINE_${i}`,layout:this.#Se,vertex:{module:this.#Me,entryPoint:"vertexMain"},fragment:{module:this.#Me,entryPoint:"fragmentMain",targets:[{format:i}]}}),this.#Te[i]=v),v}generateMipmap(i,g,x=!1,v=k.RESOURCE){x||this.#ge();const{resourceManager:_,commandEncoderManager:y}=this,b=this.getMipmapPipeline(g.format);if("3d"==g.dimension||"1d"==g.dimension)throw new Error("Generating mipmaps for non-2d textures is currently unsupported!");let S=i;const w=g.size[0],L=g.size[1],H=g.size[2]||1,W=g.usage&GPUTextureUsage.RENDER_ATTACHMENT;if(!W){const i={size:{width:Math.max(1,w>>>1),height:Math.max(1,L>>>1),depthOrArrayLayers:H},format:g.format,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC|GPUTextureUsage.RENDER_ATTACHMENT,mipLevelCount:g.mipLevelCount-1};S=_.createManagedTexture(i)}for(let _=0;_{i.setPipeline(b),i.setBindGroup(0,W),i.draw(3,1,0,0)}):v===k.PRE_PROCESS?y.addPreProcessRenderPass(be,i=>{i.setPipeline(b),i.setBindGroup(0,W),i.draw(3,1,0,0)}):v===k.MAIN?y.addMainRenderPass(be,i=>{i.setPipeline(b),i.setBindGroup(0,W),i.draw(3,1,0,0)}):v===k.POST_PROCESS&&y.addPostProcessRenderPass(be,i=>{i.setPipeline(b),i.setBindGroup(0,W),i.draw(3,1,0,0)}),w=g}}return W||y.useEncoder(v,x=>{const v={width:Math.max(1,w>>>1),height:Math.max(1,L>>>1),depthOrArrayLayers:H};for(let _=1;_>>1),v.height=Math.max(1,v.height>>>1)}),W||y.addDeferredDestroy(S),x||this.#ge(),i}destroy(){this.#ge()}#ge(){this.#de.clear(),this.#me.clear()}}Object.freeze(MipmapGenerator);const W={TILE_COUNT_X:32,TILE_COUNT_Y:32,TILE_COUNT_Z:48,WORKGROUP_SIZE_X:8,WORKGROUP_SIZE_Y:4,WORKGROUP_SIZE_Z:8,MAX_LIGHTS_PER_CLUSTER:100,MAX_CLUSTER_LIGHTS:1024,getTotalTileSize:()=>W.TILE_COUNT_X*W.TILE_COUNT_Y*W.TILE_COUNT_Z,getClusterLightsBufferSize:()=>{const i=W.getTotalTileSize();return 8*i+8*W.MAX_LIGHTS_PER_CLUSTER*i+4},getDispatchSize:()=>[Math.ceil(W.TILE_COUNT_X/W.WORKGROUP_SIZE_X),Math.ceil(W.TILE_COUNT_Y/W.WORKGROUP_SIZE_Y),Math.ceil(W.TILE_COUNT_Z/W.WORKGROUP_SIZE_Z)]};Object.freeze(W);var be,je,Ke,Xe,Ye,Ze,Je,Qe,et,tt,it="#redgpu_include skyAtmosphere.skyAtmosphereFn @group(0)@binding(0)var transmittanceLUT:texture_storage_2d;@group(0)@binding(1)varparams:SkyAtmosphere;@compute @workgroup_size(16,16)fn main(@builtin(global_invocation_id)global_id:vec3){let size=textureDimensions(transmittanceLUT);if(global_id.x>=size.x||global_id.y>=size.y){return;}let uv=(vec2(global_id.xy)+0.5)/vec2(size);let x=uv.x*2.0-1.0;let cosTheta=sign(x)*x*x;let viewHeight=clamp((1.0-uv.y)*params.atmosphereHeight,.0,params.atmosphereHeight);let T=exp(-min(getOpticalDepth(viewHeight,cosTheta),vec3(100.0)));textureStore(transmittanceLUT,global_id.xy,vec4(T,1.0));}fn getOpticalDepth(viewHeight:f32,cosTheta:f32)->vec3{let groundRadius=params.groundRadius;let rayOrigin=vec3(.0,viewHeight+groundRadius,.0);let sinTheta=sqrt(max(.0,1.0-cosTheta*cosTheta));let rayDir=vec3(sinTheta,cosTheta,.0);let tMax=getRaySphereIntersection(rayOrigin,rayDir,groundRadius+params.atmosphereHeight);if(tMax<=.0){return vec3(.0);}let tEarth=getRaySphereIntersection(rayOrigin,rayDir,groundRadius);if(groundRadius>.0&&tEarth>.0){return vec3(MAX_TAU);}return integrateOpticalDepth(rayOrigin,rayDir,.0,tMax,TRANSMITTANCE_STEPS,params);}";!function(i){var g,x,v,_,y;(g=i.hash||(i.hash={})).getHash1D="fn getHash1D(seed:f32)->f32{var x=u32(abs(seed));x=((x>>16u)^ x)*0x45d9f3bu;x=((x>>16u)^ x)*0x45d9f3bu;x=(x>>16u)^ x;return f32(x)/4294967296.0;}",g.getHash1D_vec2="fn getHash1D_vec2(coord:vec2)->f32{let q=vec2(abs(coord));var x=(q.x*73856093u)^(q.y*19349663u);x=((x>>16u)^ x)*0x45d9f3bu;x=((x>>16u)^ x)*0x45d9f3bu;x=(x>>16u)^ x;return f32(x)/4294967296.0;}",g.getHash1D_vec3="fn getHash1D_vec3(v:vec3)->f32{let q=vec3(abs(v));var x=(q.x*73856093u)^(q.y*19349663u)^(q.z*83492791u);x=((x>>16u)^ x)*0x45d9f3bu;x=((x>>16u)^ x)*0x45d9f3bu;x=(x>>16u)^ x;return f32(x)/4294967296.0;}",g.getHash1D_vec4="fn getHash1D_vec4(v:vec4)->f32{let q=vec4(abs(v));var x=(q.x*73856093u)^(q.y*19349663u)^(q.z*83492791u)^(q.w*4000000007u);x=((x>>16u)^ x)*0x45d9f3bu;x=((x>>16u)^ x)*0x45d9f3bu;x=(x>>16u)^ x;return f32(x)/4294967296.0;}",g.getHash2D_vec2="fn getHash2D_vec2(coord:vec2)->vec2{var q=vec2(abs(coord));var x=(q.x*1597334677u)^(q.y*3812015801u);x=((x>>16u)^ x)*0x45d9f3bu;x=((x>>16u)^ x)*0x45d9f3bu;x=(x>>16u)^ x;let r=f32(x)/4294967296.0;x=(x*1103515245u+12345u);let g=f32(x)/4294967296.0;return vec2(r,g);}",g.getHash3D_vec3="fn getHash3D_vec3(position:vec3)->vec3{var q=vec3(abs(position));var x=(q.x*73856093u)^(q.y*19349663u)^(q.z*83492791u);x=((x>>16u)^ x)*0x45d9f3bu;x=((x>>16u)^ x)*0x45d9f3bu;x=(x>>16u)^ x;let r=f32(x)/4294967296.0;x=(x*1103515245u+12345u);let g=f32(x)/4294967296.0;x=(x*1103515245u+12345u);let b=f32(x)/4294967296.0;return vec3(r,g,b);}",g.getBitHash1D="fn getBitHash1D(seed:f32)->f32{var x=bitcast(seed);x=((x>>16u)^ x)*0x45d9f3bu;x=((x>>16u)^ x)*0x45d9f3bu;x=(x>>16u)^ x;return f32(x)/4294967296.0;}",g.getBitHash1D_vec2="fn getBitHash1D_vec2(coord:vec2)->f32{let q=bitcast>(coord);var x=(q.x*73856093u)^(q.y*19349663u);x=((x>>16u)^ x)*0x45d9f3bu;x=((x>>16u)^ x)*0x45d9f3bu;x=(x>>16u)^ x;return f32(x)/4294967296.0;}",g.getBitHash1D_vec3="fn getBitHash1D_vec3(v:vec3)->f32{var q=bitcast>(v);var x=(q.x*73856093u)^(q.y*19349663u)^(q.z*83492791u);x=((x>>16u)^ x)*0x45d9f3bu;x=((x>>16u)^ x)*0x45d9f3bu;x=(x>>16u)^ x;return f32(x)/4294967296.0;}",g.getBitHash1D_vec4="fn getBitHash1D_vec4(v:vec4)->f32{var q=bitcast>(v);var x=(q.x*73856093u)^(q.y*19349663u)^(q.z*83492791u)^(q.w*4000000007u);x=((x>>16u)^ x)*0x45d9f3bu;x=((x>>16u)^ x)*0x45d9f3bu;x=(x>>16u)^ x;return f32(x)/4294967296.0;}",g.getBitHash2D_vec2="fn getBitHash2D_vec2(coord:vec2)->vec2{var q=bitcast>(coord);var x=(q.x*1597334677u)^(q.y*3812015801u);x=((x>>16u)^ x)*0x45d9f3bu;x=((x>>16u)^ x)*0x45d9f3bu;x=(x>>16u)^ x;let r=f32(x)/4294967296.0;x=(x*1103515245u+12345u);let g=f32(x)/4294967296.0;return vec2(r,g);}",g.getBitHash3D_vec3="fn getBitHash3D_vec3(position:vec3)->vec3{var q=bitcast>(position);var x=(q.x*73856093u)^(q.y*19349663u)^(q.z*83492791u);x=((x>>16u)^ x)*0x45d9f3bu;x=((x>>16u)^ x)*0x45d9f3bu;x=(x>>16u)^ x;let r=f32(x)/4294967296.0;x=(x*1103515245u+12345u);let g=f32(x)/4294967296.0;x=(x*1103515245u+12345u);let b=f32(x)/4294967296.0;return vec3(r,g,b);}",g.getRadicalInverseVanDerCorput="fn getRadicalInverseVanDerCorput(bits_in:u32)->f32{var bits=bits_in;bits=(bits<<16u)|(bits>>16u);bits=((bits & 0x55555555u)<<1u)|((bits & 0xAAAAAAAAu)>>1u);bits=((bits & 0x33333333u)<<2u)|((bits & 0xCCCCCCCCu)>>2u);bits=((bits & 0x0F0F0F0Fu)<<4u)|((bits & 0xF0F0F0F0u)>>4u);bits=((bits & 0x00FF00FFu)<<8u)|((bits & 0xFF00FF00u)>>8u);return f32(bits)*2.3283064365386963e-10;}",g.getHammersley="#redgpu_include math.hash.getRadicalInverseVanDerCorput fn getHammersley(i:u32,N:u32)->vec2{return vec2(f32(i)/f32(N),getRadicalInverseVanDerCorput(i));}",i.getInterleavedGradientNoise="fn getInterleavedGradientNoise(screenCoord:vec2)->f32{let magic=vec3(.06711056,.00583715,52.9829189);return fract(magic.z*fract(dot(screenCoord,magic.xy)));}",i.getMotionVector="#redgpu_include math.EPSILON fn getMotionVector(currentClipPos:vec4,prevClipPos:vec4,)->vec2{let currentNDC=currentClipPos.xy/max(currentClipPos.w,EPSILON);let prevNDC=prevClipPos.xy/max(prevClipPos.w,EPSILON);var motionVector=currentNDC-prevNDC;motionVector.y=-motionVector.y;let uvMotionVector=motionVector*0.5;return uvMotionVector;}",i.getIsFinite="fn getIsFiniteScalar(x:f32)->bool{return x==x&&abs(x)<1e30;}fn getIsFiniteVec3(v:vec3)->vec3{return vec3(v.x==v.x&&abs(v.x)<1e30,v.y==v.y&&abs(v.y)<1e30,v.z==v.z&&abs(v.z)<1e30);}",(x=i.billboard||(i.billboard={})).getBillboardMatrix="fn getBillboardMatrix(viewMatrix:mat4x4,modelMatrix:mat4x4,useStandardScale:u32)->mat4x4{var resultMatrix=viewMatrix*modelMatrix;if(useStandardScale==1u){let scaleX=length(modelMatrix[0].xyz);let scaleY=length(modelMatrix[1].xyz);let scaleZ=length(modelMatrix[2].xyz);resultMatrix[0]=vec4(scaleX,.0,.0,resultMatrix[0].w);resultMatrix[1]=vec4(.0,scaleY,.0,resultMatrix[1].w);resultMatrix[2]=vec4(.0,.0,scaleZ,resultMatrix[2].w);}else{resultMatrix[0]=vec4(modelMatrix[0][0],.0,.0,resultMatrix[0].w);resultMatrix[1]=vec4(.0,modelMatrix[1][1],.0,resultMatrix[1].w);resultMatrix[2]=vec4(.0,.0,modelMatrix[2][2],resultMatrix[2].w);}return resultMatrix;}",x.getBillboardResult="struct BillboardResult{position:vec4,vertexPosition:vec3,vertexNormal:vec3,}fn getBillboardResult(input_position:vec3,input_normal:vec3,modelMatrix:mat4x4,viewMatrix:mat4x4,projectionMatrix:mat4x4,resolution:vec2,useBillboard:u32,usePixelSize:u32,pixelSize:f32,renderRatioX:f32,renderRatioY:f32)->BillboardResult{var result:BillboardResult;let ratioScaleMatrix=mat4x4(renderRatioX,0,0,0,0,renderRatioY,0,0,0,0,1,0,0,0,0,1);var viewPos:vec4;var viewNormal:vec4;if(useBillboard==1u){let billboardMatrix=getBillboardMatrix(viewMatrix,modelMatrix,1u);if(usePixelSize==1u){let viewCenter=billboardMatrix*vec4(.0,.0,.0,1.0);let clipCenter=projectionMatrix*viewCenter;let scaleX=(pixelSize/resolution.x)*2.0*renderRatioX;let scaleY=(pixelSize/resolution.y)*2.0*renderRatioY;result.position=vec4(clipCenter.xy+input_position.xy*vec2(scaleX,scaleY)*clipCenter.w,clipCenter.zw);viewPos=viewCenter;viewNormal=vec4(.0,.0,1.0,.0);}else{viewPos=billboardMatrix*ratioScaleMatrix*vec4(input_position,1.0);viewNormal=vec4(.0,.0,1.0,.0);result.position=projectionMatrix*viewPos;}}else{viewPos=viewMatrix*modelMatrix*ratioScaleMatrix*vec4(input_position,1.0);viewNormal=viewMatrix*modelMatrix*ratioScaleMatrix*vec4(input_normal,.0);result.position=projectionMatrix*viewPos;}result.vertexPosition=viewPos.xyz;result.vertexNormal=normalize(viewNormal.xyz);return result;}",(v=i.direction||(i.direction={})).getViewDirection="fn getViewDirection(worldPosition:vec3,cameraPosition:vec3)->vec3{return normalize(cameraPosition-worldPosition);}",v.getRayDirection="fn getRayDirection(worldPosition:vec3,cameraPosition:vec3)->vec3{return normalize(worldPosition-cameraPosition);}",v.getReflectionVectorFromViewDirection="fn getReflectionVectorFromViewDirection(viewDirection:vec3,normal:vec3)->vec3{return reflect(-viewDirection,normal);}",(_=i.reconstruct||(i.reconstruct={})).getNDCFromDepth="fn getNDCFromDepth(uv:vec2,depth:f32)->vec3{return vec3(uv.x*2.0-1.0,(1.0-uv.y)*2.0-1.0,depth);}",_.getWorldPositionFromDepth="#redgpu_include math.reconstruct.getNDCFromDepth fn getWorldPositionFromDepth(uv:vec2,depth:f32,inverseProjectionViewMatrix:mat4x4)->vec3{let ndc=getNDCFromDepth(uv,depth);let worldPos4=inverseProjectionViewMatrix*vec4(ndc,1.0);return worldPos4.xyz/worldPos4.w;}",_.getViewPositionFromDepth="#redgpu_include math.reconstruct.getNDCFromDepth fn getViewPositionFromDepth(uv:vec2,depth:f32,inverseProjectionMatrix:mat4x4)->vec3{let ndc=getNDCFromDepth(uv,depth);let viewPos4=inverseProjectionMatrix*vec4(ndc,1.0);return viewPos4.xyz/viewPos4.w;}",_.getWorldNormalFromGNormalBuffer="fn getWorldNormalFromGNormalBuffer(gBufferNormal:vec3)->vec3{return normalize(gBufferNormal*2.0-1.0);}",_.getViewNormalFromGNormalBuffer="#redgpu_include math.reconstruct.getWorldNormalFromGNormalBuffer fn getViewNormalFromGNormalBuffer(gBufferNormal:vec3,viewMatrix:mat4x4)->vec3{let worldNormal=getWorldNormalFromGNormalBuffer(gBufferNormal);return normalize((viewMatrix*vec4(worldNormal,.0)).xyz);}",(y=i.tnb||(i.tnb={})).getTBNFromVertexTangent="fn getTBNFromVertexTangent(inputNormal:vec3,inputVertexTangent:vec4)->mat3x3{let tangent=normalize(inputVertexTangent.xyz-inputNormal*dot(inputVertexTangent.xyz,inputNormal));let bitangent=cross(inputNormal,tangent)*inputVertexTangent.w;return mat3x3(tangent,bitangent,inputNormal);}",y.getTBN="fn getTBN(inputNormal:vec3,inputTangent:vec3)->mat3x3{let tangent=normalize(inputTangent-inputNormal*dot(inputTangent,inputNormal));let bitangent=cross(inputNormal,tangent);return mat3x3(tangent,bitangent,inputNormal);}",y.getTBNFromCotangent="fn getTBNFromCotangent(inputNormal:vec3,inputWorldPos:vec3,inputUV:vec2)->mat3x3{let dp1=dpdx(inputWorldPos);let dp2=dpdy(inputWorldPos);let duv1=dpdx(inputUV);let duv2=dpdy(inputUV);let dp2perp=cross(dp2,inputNormal);let dp1perp=cross(inputNormal,dp1);let tangent=dp2perp*duv1.x+dp1perp*duv2.x;let bitangent=dp2perp*duv1.y+dp1perp*duv2.y;let invmax=inverseSqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));return mat3x3(tangent*invmax,-bitangent*invmax,inputNormal);}",y.getNormalFromNormalMap="fn getNormalFromNormalMap(sampledNormalColor:vec3,tbn:mat3x3,strength:f32)->vec3{var n:vec2=sampledNormalColor.xy*2.0-1.0;n.y=-n.y;n*=strength;let z:f32=sqrt(max(.0,1.0-dot(n,n)));return normalize(tbn*vec3(n,z));}",i.PI="const PI: f32 = 3.141592653589793;",i.PI2="const PI2: f32 = 6.283185307179586;",i.HPI="const HPI: f32 = 1.5707963267948966;",i.INV_PI="const INV_PI: f32 = 0.31830988618379067;",i.DEG_TO_RAD="const DEG_TO_RAD: f32 = 0.017453292519943295;",i.RAD_TO_DEG="const RAD_TO_DEG: f32 = 57.29577951308232;",i.EPSILON="const EPSILON: f32 = 1e-6;",i.FLT_MAX="const FLT_MAX: f32 = 3.402823466e+38;"}(be||(be={})),function(i){i.getShadowCoord="fn getShadowCoord(worldPosition:vec3,lightViewProjectionMatrix:mat4x4)->vec3{let posFromLight=lightViewProjectionMatrix*vec4(worldPosition,1.0);let shadowCoordNDC=posFromLight.xyz/posFromLight.w;return vec3(shadowCoordNDC.xy*vec2(0.5,-0.5)+vec2(0.5,0.5),shadowCoordNDC.z);}",i.getShadowClipPosition="fn getShadowClipPosition(worldPosition:vec3,lightViewProjectionMatrix:mat4x4)->vec4{return lightViewProjectionMatrix*vec4(worldPosition,1.0);}",i.getDirectionalShadowVisibility="fn getDirectionalShadowVisibility(directionalShadowMap:texture_depth_2d,directionalShadowMapSampler:sampler_comparison,shadowDepthTextureSize:u32,bias:f32,shadowCoord:vec3)->f32{let oneOverShadowDepthTextureSize=1.0/f32(shadowDepthTextureSize);let shadowDepth=clamp(shadowCoord.z,.0,1.0);var visibility:f32=.0;for(var y=-1;y<=1;y++){for(var x=-1;x<=1;x++){let offset=vec2f(vec2(x,y))*oneOverShadowDepthTextureSize;let tUV=shadowCoord.xy+offset;let sampleVisibility=textureSampleCompare(directionalShadowMap,directionalShadowMapSampler,tUV,shadowDepth-bias);if(tUV.x<.0||tUV.x>1.0||tUV.y<.0||tUV.y>1.0){visibility+=1.0;}else{visibility+=sampleVisibility;}}}visibility/=9.0;return visibility;}"}(je||(je={})),function(i){i.rgbToYCoCg="fn rgbToYCoCg(rgb:vec3)->vec3{let y=dot(rgb,vec3(0.25,0.5,0.25));let co=dot(rgb,vec3(0.5,.0,-0.5));let cg=dot(rgb,vec3(-0.25,0.5,-0.25));return vec3(y,co,cg);}",i.YCoCgToRgb="fn YCoCgToRgb(ycocg:vec3)->vec3{let y=ycocg.x;let co=ycocg.y;let cg=ycocg.z;return vec3(y+co-cg,y+cg,y-co-cg);}",i.linearToSrgbVec3="fn linearToSrgbVec3(linearColor:vec3)->vec3{return select(12.92*linearColor,1.055*pow(linearColor,vec3(1.0/2.4))-.055,linearColor>vec3(.0031308));}",i.linearToSrgbVec4="#redgpu_include color.linearToSrgbVec3 fn linearToSrgbVec4(linearColor:vec4)->vec4{return vec4(linearToSrgbVec3(linearColor.rgb),linearColor.a);}",i.srgbToLinearVec3="fn srgbToLinearVec3(srgbColor:vec3)->vec3{return select(srgbColor/12.92,pow((srgbColor+.055)/1.055,vec3(2.4)),srgbColor>vec3(.04045));}",i.srgbToLinearVec4="#redgpu_include color.srgbToLinearVec3 fn srgbToLinearVec4(srgbColor:vec4)->vec4{return vec4(srgbToLinearVec3(srgbColor.rgb),srgbColor.a);}",i.getLuminance="fn getLuminance(rgb:vec3)->f32{return dot(rgb,vec3(0.2126,0.7152,.0722));}",i.getTintBlendMode="#redgpu_include math.EPSILON fn rgbToHsl(rgb:vec3)->vec3{let maxVal:f32=max(max(rgb.r,rgb.g),rgb.b);let minVal:f32=min(min(rgb.r,rgb.g),rgb.b);let delta:f32=maxVal-minVal;let lightness:f32=(maxVal+minVal)*0.5;if(delta(.0,.0,lightness);}var saturation:f32;if(lightness<0.5){saturation=delta/(maxVal+minVal+EPSILON);}else{saturation=delta/(2.0-maxVal-minVal+EPSILON);}var hue:f32=.0;if(abs(rgb.r-maxVal)(hue,saturation,lightness);}fn hslToRgb(hsl:vec3)->vec3{let h=hsl.x;let s=hsl.y;let l=hsl.z;if(s==.0){return vec3(l,l,l);}var q:f32;if(l<0.5){q=l*(1.0+s);}else{q=l+s-l*s;}let p=2.0*l-q;var r:f32;var g:f32;var b:f32;for(var i:i32=0;i<3;i=i+1){var t:f32;if(i==0){t=h+1.0/3.0;}else if(i==1){t=h;}else{t=h-1.0/3.0;}if(t<.0){t=t+1.0;}if(t>1.0){t=t-1.0;}var color:f32;if(t<1.0/6.0){color=p+(q-p)*6.0*t;}else if(t<1.0/2.0){color=q;}else if(t<2.0/3.0){color=p+(q-p)*(2.0/3.0-t)*6.0;}else{color=p;}if(i==0){r=color;}else if(i==1){g=color;}else{b=color;}}return vec3(r,g,b);}fn getTintBlendMode(baseColor:vec4,tintBlendMode:u32,tint:vec4)->vec4{var tintedColor:vec3;switch(tintBlendMode){case 0u:{tintedColor=mix(baseColor.rgb,tint.rgb,tint.a);}case 1u:{tintedColor=baseColor.rgb*tint.rgb;}case 2u:{tintedColor=max(baseColor.rgb,tint.rgb);}case 3u:{tintedColor=1.0-(1.0-baseColor.rgb)*(1.0-tint.rgb);}case 4u:{tintedColor=clamp(baseColor.rgb+tint.rgb,vec3(.0),vec3(1.0));}case 5u:{tintedColor=clamp(baseColor.rgb-tint.rgb,vec3(.0),vec3(1.0));}case 6u:{tintedColor=min(baseColor.rgb,tint.rgb);}case 7u:{tintedColor=mix(2.0*baseColor.rgb*tint.rgb,1.0-2.0*(1.0-baseColor.rgb)*(1.0-tint.rgb),step(vec3(0.5),baseColor.rgb));}case 8u:{tintedColor=clamp(baseColor.rgb/(1.0-tint.rgb+EPSILON),vec3(.0),vec3(1.0));}case 9u:{tintedColor=1.0-clamp((1.0-baseColor.rgb)/(tint.rgb+EPSILON),vec3(.0),vec3(1.0));}case 10u:{tintedColor=mix(2.0*baseColor.rgb*tint.rgb,1.0-2.0*(1.0-baseColor.rgb)*(1.0-tint.rgb),step(vec3(0.5),tint.rgb));}case 11u:{tintedColor=mix(baseColor.rgb*(tint.rgb+tint.rgb-vec3(1.0)),baseColor.rgb+tint.rgb-baseColor.rgb*tint.rgb,step(vec3(0.5),tint.rgb));}case 12u:{tintedColor=abs(baseColor.rgb-tint.rgb);}case 13u:{tintedColor=baseColor.rgb+tint.rgb-2.0*baseColor.rgb*tint.rgb;}case 14u:{tintedColor=clamp(baseColor.rgb/(tint.rgb+EPSILON),vec3(.0),vec3(1.0));}case 15u:{tintedColor=mix(clamp(baseColor.rgb/(1.0-(tint.rgb-vec3(0.5))*2.0+EPSILON),vec3(.0),vec3(1.0)),1.0-clamp((1.0-baseColor.rgb)/(tint.rgb*2.0+EPSILON),vec3(.0),vec3(1.0)),step(vec3(0.5),tint.rgb));}case 16u:{tintedColor=clamp(baseColor.rgb+tint.rgb-vec3(1.0),vec3(.0),vec3(1.0));}case 17u:{tintedColor=mix(min(baseColor.rgb,2.0*tint.rgb),max(baseColor.rgb,2.0*tint.rgb-vec3(1.0)),step(vec3(0.5),tint.rgb));}case 18u:{let baseHsl=rgbToHsl(baseColor.rgb);let tintHsl=rgbToHsl(tint.rgb);tintedColor=hslToRgb(vec3(baseHsl.x,tintHsl.y,baseHsl.z));}case 19u:{let baseHsl=rgbToHsl(baseColor.rgb);let tintHsl=rgbToHsl(tint.rgb);tintedColor=hslToRgb(vec3(tintHsl.x,baseHsl.y,baseHsl.z));}case 20u:{let baseHsl=rgbToHsl(baseColor.rgb);let tintHsl=rgbToHsl(tint.rgb);tintedColor=hslToRgb(vec3(baseHsl.x,baseHsl.y,tintHsl.z));}case 21u:{let baseHsl=rgbToHsl(baseColor.rgb);let tintHsl=rgbToHsl(tint.rgb);tintedColor=hslToRgb(vec3(tintHsl.x,tintHsl.y,baseHsl.z));}case 22u:{tintedColor=1.0-abs(1.0-baseColor.rgb-tint.rgb);}default:{tintedColor=baseColor.rgb;}}return vec4(tintedColor,baseColor.a*tint.a);}"}(Ke||(Ke={})),function(i){i.getLinearizeDepth="#redgpu_include math.EPSILON fn getLinearizeDepth(depthSample:f32,near:f32,far:f32)->f32{let d=clamp(depthSample,.0,1.0);return(near*far)/max(EPSILON,far-d*(far-near));}"}(Xe||(Xe={})),function(i){i.getLightDistanceAttenuation="#redgpu_include math.EPSILON fn getLightDistanceAttenuation(distance:f32,radius:f32)->f32{let d2=distance*distance;let factor=distance/radius;let factor2=factor*factor;let factor4=factor2*factor2;let windowing=clamp(1.0-factor4,.0,1.0);return(windowing*windowing)/max(d2,.0001);}",i.getLightAngleAttenuation="#redgpu_include math.EPSILON fn getLightAngleAttenuation(lightToVertexDirection:vec3,lightDirection:vec3,innerCutoff:f32,outerCutoff:f32)->f32{let cosTheta=dot(lightToVertexDirection,lightDirection);let cosOuter=cos(radians(outerCutoff));let cosInner=cos(radians(innerCutoff));let epsilon=max(EPSILON,cosInner-cosOuter);let factor=clamp((cosTheta-cosOuter)/epsilon,.0,1.0);return factor*factor;}"}(Ye||(Ye={})),function(i){i.skyAtmosphereFn="#redgpu_include math.PI #redgpu_include math.PI2 #redgpu_include math.HPI #redgpu_include math.INV_PI #redgpu_include math.DEG_TO_RAD #redgpu_include math.EPSILON #redgpu_include systemStruct.SkyAtmosphere #redgpu_include color.getLuminance const MAX_TAU:f32=100.0;const SUN_ANGULAR_RADIUS_RAD:f32=.00465;const SUN_SOLID_ANGLE_BASE:f32=6.794e-5;const TRANSMITTANCE_STEPS:u32=40u;const MULTI_SCAT_STEPS:u32=40u;const SKY_VIEW_STEPS:u32=128u;const AP_STEPS:u32=64u;const MULTI_SCAT_SAMPLES:u32=128u;const IRRADIANCE_SAMPLES:u32=256u;const SUN_RADIANCE_BOOST:f32=1.0;const MIE_GLOW_SUPPRESS:f32=0.40;const NEAR_FIELD_CORRECTION_DIST:f32=0.2;struct AtmosphereDensities{rhoR:f32,rhoM:f32,rhoO:f32};struct AtmosphereCoefficients{scatTotal:vec3,extinction:vec3};fn getRaySphereIntersection(rayOrigin:vec3,rayDir:vec3,sphereRadius:f32)->f32{let b=dot(rayOrigin,rayDir);let c=dot(rayOrigin,rayOrigin)-sphereRadius*sphereRadius;let delta=b*b-c;if(delta<.0){return-1.0;}let s=sqrt(delta);let t0=-b-s;let t1=-b+s;if(t0>EPSILON){return t0;}if(t1>EPSILON){return t1;}return-1.0;}fn getPlanetIntersection(origin:vec3,dir:vec3,r:f32)->vec2{let b=dot(origin,dir);let c=dot(origin,origin)-r*r;let delta=b*b-c;if(delta<.0){return vec2(-1.0);}let s=sqrt(delta);return vec2(-b-s,-b+s);}fn getTransmittanceUV(viewHeight:f32,cosTheta:f32,atmosphereHeight:f32)->vec2{let mu=clamp(cosTheta,-1.0,1.0);let u=clamp(0.5+0.5*sign(mu)*sqrt(abs(mu)),.001,0.999);let v=clamp(1.0-viewHeight/atmosphereHeight,.001,0.999);return vec2(u,v);}fn getSkyViewUV(viewDir:vec3,viewHeight:f32,groundRadius:f32,atmosphereHeight:f32)->vec2{var azimuth:f32;if(abs(viewDir.z)<1e-6&&abs(viewDir.x)<1e-6){azimuth=.0;}else{azimuth=atan2(viewDir.z,viewDir.x);}let u=clamp((azimuth/PI2)+0.5,.001,0.999);let r=groundRadius;let h=max(.0001,viewHeight);let horizonCos=-sqrt(max(.0,h*(2.0*r+h)))/(r+h);let horizonElevation=asin(clamp(horizonCos,-1.0,1.0));let viewElevation=asin(clamp(viewDir.y,-1.0,1.0));var v:f32;if(viewElevation>=horizonElevation){let ratio=(viewElevation-horizonElevation)/(HPI-horizonElevation);v=0.5*(1.0-sqrt(max(.0,ratio)));}else{let ratio=(horizonElevation-viewElevation)/(horizonElevation+HPI);v=0.5*(1.0+sqrt(max(.0,ratio)));}return vec2(u,clamp(v,.001,0.999));}fn getTransmittance(transmittanceLUT:texture_2d,skyAtmosphereSampler:sampler,viewHeight:f32,cosTheta:f32,atmosphereHeight:f32)->vec3{let uv=getTransmittanceUV(viewHeight,cosTheta,atmosphereHeight);var transmittance=textureSampleLevel(transmittanceLUT,skyAtmosphereSampler,uv,.0).rgb;let mu=clamp(cosTheta,-1.0,1.0);if(mu<.0){let groundMask=smoothstep(-.015,.0,mu);transmittance*=groundMask;}return transmittance;}fn getPlanetShadowMask(p:vec3,sunDir:vec3,r:f32,params:SkyAtmosphere)->f32{if(r>.0&&getRaySphereIntersection(p,sunDir,r)>.0){return .0;}return 1.0;}fn getAtmosphereDensities(viewHeight:f32,params:SkyAtmosphere)->AtmosphereDensities{var d:AtmosphereDensities;if(viewHeight<.0){d.rhoR=.0;d.rhoM=.0;d.rhoO=.0;}else{d.rhoR=exp(-viewHeight/params.rayleighExponentialDistribution);d.rhoM=exp(-viewHeight/params.mieExponentialDistribution);let ozoneDist=abs(viewHeight-params.absorptionTipAltitude);d.rhoO=max(.0,1.0-ozoneDist/params.absorptionTentWidth);}return d;}fn getSunTransmittanceManual(p:vec3,sunDir:vec3,params:SkyAtmosphere)->vec3{let r=params.groundRadius;let tMax=getRaySphereIntersection(p,sunDir,r+params.atmosphereHeight);if(tMax<=.0){return vec3(1.0);}let intersect=getPlanetIntersection(p,sunDir,r);if(r>.0&&intersect.x>EPSILON){return vec3(.0);}var optExt=vec3(.0);let halfSteps=TRANSMITTANCE_STEPS/2u;if(intersect.x>EPSILON&&intersect.x.0&&tMax>intersect.y){optExt+=integrateOpticalDepth(p,sunDir,intersect.y,tMax,halfSteps,params);}}else{optExt=integrateOpticalDepth(p,sunDir,.0,tMax,TRANSMITTANCE_STEPS,params);}return exp(-min(optExt,vec3(MAX_TAU)));}fn getPhysicalTransmittance(p:vec3,sunDir:vec3,r:f32,atmosphereHeight:f32,params:SkyAtmosphere)->vec3{let minElevationRad=params.transmittanceMinLightElevationAngle*DEG_TO_RAD;var adjustedSunDir=sunDir;if(sunDir.y(sunDir.x,.0,sunDir.z));adjustedSunDir=vec3(horizontalDir.x*cosEl,sinEl,horizontalDir.z*cosEl);}let intersect=getPlanetIntersection(p,adjustedSunDir,r);if(r>.0&&intersect.x>EPSILON){return vec3(.0);}return getSunTransmittanceManual(p,adjustedSunDir,params);}fn integrateOpticalDepth(origin:vec3,dir:vec3,tMin:f32,tMax:f32,steps:u32,params:SkyAtmosphere)->vec3{if(tMax<=tMin){return vec3(.0);}let stepSize=(tMax-tMin)/f32(steps);var optExt=vec3(.0);for(var i=0u;if32{return 3.0/(16.0*PI)*(1.0+cosTheta*cosTheta);}fn phaseMie(cosTheta:f32,g:f32)->f32{let g2=g*g;return 1.0/(4.0*PI)*((1.0-g2)/pow(max(EPSILON,1.0+g2-2.0*g*cosTheta),1.5));}fn phaseMieStable(cosTheta:f32,g:f32)->f32{return phaseMie(cosTheta,min(g,0.80));}fn getSquashedViewSunCos(viewDir:vec3,sunDir:vec3)->f32{let sunElevationParam=saturate(sunDir.y);let squashFactor=mix(0.85,1.0,sunElevationParam);let verticalDist=viewDir.y-sunDir.y;let correctionGuard=saturate(dot(viewDir,sunDir)*10.0)*(1.0-sunElevationParam*sunElevationParam);let squashCorrection=(1.0/(squashFactor*squashFactor)-1.0)*(verticalDist*verticalDist)*correctionGuard;return dot(viewDir,sunDir)-squashCorrection;}fn getSunDiskRadianceUnit(viewSunCos:f32,sunSize:f32,sunLimbDarkening:f32,skyTrans:vec3,edgeSoftness:f32,params:SkyAtmosphere)->vec3{let sunRad=(sunSize*0.5)*DEG_TO_RAD;let cosSunRad=cos(sunRad);let solidAngle=PI2*(1.0-cosSunRad);let radianceScale=SUN_RADIANCE_BOOST/max(6.7e-5,solidAngle);let dist=(1.0-viewSunCos)/max(1e-7,1.0-cosSunRad);let sunMask=1.0-smoothstep(1.0-edgeSoftness,1.0,dist);if(sunMask<=.0){return vec3(.0);}let limbDarkening=pow(max(1e-7,1.0-saturate(dist)),sunLimbDarkening);let energyNormalization=sunLimbDarkening+1.0;return(radianceScale*limbDarkening*energyNormalization*sunMask)*skyTrans;}fn getSunDiskRadianceIBL(viewSunCos:f32,sunLimbDarkening:f32,skyTrans:vec3,params:SkyAtmosphere)->vec3{let sunRad=(params.sunSize*0.5)*DEG_TO_RAD;let iblAlpha=max(sunRad*2.0,0.175);let cosAlpha=cos(iblAlpha);let radScale=1.0/(PI2*(1.0-cosAlpha));let diff=saturate(1.0-viewSunCos);let sigma_sq=1.0-cosAlpha;let falloff=exp(-diff/max(1e-7,sigma_sq));if(falloff<.001){return vec3(.0);}return(radScale*falloff)*skyTrans;}fn getMieGlowAmountUnit(viewSunCos:f32,viewHeight:f32,params:SkyAtmosphere,transmittanceLUT:texture_2d,skyAtmosphereSampler:sampler,transToEdge:vec3,overrideHalo:f32)->vec3{let actualAnisotropy=params.mieAnisotropy;let halo=select(actualAnisotropy,overrideHalo,overrideHalo>.0);let sharpG=min(max(halo,0.88),0.94);let stableG=min(actualAnisotropy,0.80);let sharpPhase=phaseMie(viewSunCos,sharpG);let stablePhase=phaseMie(viewSunCos,stableG);let diffPhase=max(.0,sharpPhase-stablePhase);let sunDirY=params.sunDirection.y;let sunCosTheta=clamp(sunDirY,-1.0,1.0);let sunTransForGlow=getTransmittance(transmittanceLUT,skyAtmosphereSampler,viewHeight,sunCosTheta,params.atmosphereHeight);return sunTransForGlow*(params.mieScattering/max(vec3(.0001),params.mieScattering+params.mieAbsorption))*(diffPhase)*(1.0-transToEdge)*MIE_GLOW_SUPPRESS*params.skyLuminanceFactor;}fn integrateScatSegment(origin:vec3,dir:vec3,tMin:f32,tMax:f32,steps:u32,params:SkyAtmosphere,transmittanceLUT:texture_2d,skyAtmosphereSampler:sampler,multiScatLUT:texture_2d,useLUT:bool,radiance:ptr>,transmittance:ptr>){if(tMax<=tMin){return;}let r=params.groundRadius;let stepSize=(tMax-tMin)/f32(steps);let sunDir=params.sunDirection;let viewSunCos=dot(dir,sunDir);let phaseR=phaseRayleigh(viewSunCos);let phaseM=select(phaseMie(viewSunCos,params.mieAnisotropy),phaseMieStable(viewSunCos,params.mieAnisotropy),useLUT);for(var i=0u;i.0&&viewHeight<.0){continue;}let up=p/pLen;let cosSun=dot(up,sunDir);var sunTrans:vec3;if(useLUT){sunTrans=getTransmittance(transmittanceLUT,skyAtmosphereSampler,viewHeight,cosSun,params.atmosphereHeight);}else{sunTrans=getSunTransmittanceManual(p,sunDir,params);}let shadowMask=select(1.0,.0,r>.0&&getRaySphereIntersection(p,sunDir,r)>.0);let d=getAtmosphereDensities(viewHeight,params);let scatR_phys=params.rayleighScattering*d.rhoR;let scatM_phys=params.mieScattering*d.rhoM;let mieAbs_phys=params.mieAbsorption*d.rhoM;let ozoneAbs_phys=params.absorptionCoefficient*d.rhoO;let scatR_luminous=scatR_phys*params.skyLuminanceFactor;let scatM_luminous=scatM_phys*params.skyLuminanceFactor;let stepScat=(scatR_luminous*phaseR+scatM_luminous*phaseM)*sunTrans*shadowMask;let scatTotal_luminous=scatR_luminous+scatM_luminous;let msUV=vec2(clamp(cosSun*0.5+0.5,.001,0.999),clamp(1.0-viewHeight/params.atmosphereHeight,.001,0.999));let msScat=textureSampleLevel(multiScatLUT,skyAtmosphereSampler,msUV,.0).rgb*scatTotal_luminous*shadowMask*params.multiScatteringFactor;*radiance+=*transmittance*(stepScat+msScat)*stepSize;let extinction_phys=scatR_phys+scatM_phys+mieAbs_phys+ozoneAbs_phys;*transmittance*=exp(-extinction_phys*stepSize);}}fn getCubeMapDirection(uv:vec2,face:u32)->vec3{let tex=uv*2.0-1.0;var dir:vec3;switch(face){case 0u:{dir=vec3(1.0,-tex.y,-tex.x);}case 1u:{dir=vec3(-1.0,-tex.y,tex.x);}case 2u:{dir=vec3(tex.x,1.0,tex.y);}case 3u:{dir=vec3(tex.x,-1.0,-tex.y);}case 4u:{dir=vec3(tex.x,-tex.y,1.0);}case 5u:{dir=vec3(-tex.x,-tex.y,-1.0);}default:{dir=vec3(.0);}}return dir;}fn evaluateGroundRadiance(cosSun:f32,sunTrans:vec3,msEnergy:vec3,groundAlbedo:vec3)->vec3{let sunShadow=smoothstep(-.01,.01,cosSun);var groundRadiance=vec3(.0);if(sunShadow>.0){groundRadiance=(sunTrans*max(.0,cosSun)*INV_PI+msEnergy)*groundAlbedo*sunShadow;}else{groundRadiance=msEnergy*groundAlbedo;}return groundRadiance;}fn evaluateIBLRadiance(viewDir:vec3,params:SkyAtmosphere,transmittanceLUT:texture_2d,multiScatLUT:texture_2d,skyViewLUT:texture_2d,skyAtmosphereSampler:sampler)->vec3{let r=params.groundRadius;let viewHeight=max(.0,params.cameraHeight);let atmosphereHeight=params.atmosphereHeight;let sunDir=normalize(params.sunDirection);let skyUV=getSkyViewUV(viewDir,viewHeight,r,atmosphereHeight);let skySample=textureSampleLevel(skyViewLUT,skyAtmosphereSampler,skyUV,.0);var radiance=skySample.rgb;let viewSunCos=getSquashedViewSunCos(viewDir,sunDir);let camPos=vec3(.0,r+viewHeight,.0);let tEarth=getRaySphereIntersection(camPos,viewDir,r);let isGround=r>.0&&tEarth>.0&&viewDir.y<-.0001;let transToEdge=select(getTransmittance(transmittanceLUT,skyAtmosphereSampler,viewHeight,viewDir.y,atmosphereHeight),vec3(skySample.a),isGround);let sunShadow=getPlanetShadowMask(camPos,sunDir,r,params);if(!isGround&&sunShadow>.0){let mieGlow=getMieGlowAmountUnit(viewSunCos,viewHeight,params,transmittanceLUT,skyAtmosphereSampler,transToEdge,.0);radiance+=mieGlow*sunShadow;}return radiance;}fn getSpecularSunLobe(viewSun:f32,lobeHalfAngle:f32)->f32{let cosHalf=cos(lobeHalfAngle);let sunLobePower=clamp(log(0.5)/log(max(1e-4,cosHalf)),2.0,128.0);let sunLobeNorm=(sunLobePower+1.0)*(0.5*INV_PI);return sunLobeNorm*pow(max(.0,viewSun),sunLobePower);}fn evaluateIBLRadianceCompensated(viewDir:vec3,params:SkyAtmosphere,transmittanceLUT:texture_2d,multiScatLUT:texture_2d,skyViewLUT:texture_2d,skyAtmosphereSampler:sampler)->vec3{let r=params.groundRadius;let viewHeight=max(.0,params.cameraHeight);let atmosphereHeight=params.atmosphereHeight;let sunDir=normalize(params.sunDirection);let skyUV=getSkyViewUV(viewDir,viewHeight,r,atmosphereHeight);let skySample=textureSampleLevel(skyViewLUT,skyAtmosphereSampler,skyUV,.0);var radiance=skySample.rgb;let viewSunCos=getSquashedViewSunCos(viewDir,sunDir);let camPos=vec3(.0,r+viewHeight,.0);let tEarth=getRaySphereIntersection(camPos,viewDir,r);let isGround=r>.0&&tEarth>.0&&viewDir.y<-.0001;let transToEdge=select(getTransmittance(transmittanceLUT,skyAtmosphereSampler,viewHeight,viewDir.y,atmosphereHeight),vec3(skySample.a),isGround);let sunShadow=getPlanetShadowMask(camPos,sunDir,r,params);if(!isGround&&sunShadow>.0){let mieGlow=getMieGlowAmountUnit(viewSunCos,viewHeight,params,transmittanceLUT,skyAtmosphereSampler,transToEdge,.0);radiance+=mieGlow*sunShadow;radiance+=getSunDiskRadianceIBL(viewSunCos,params.sunLimbDarkening,transToEdge,params)*sunShadow;}return radiance;}fn getFrustumRayDirection(uv:vec2,invP:mat4x4,invV:mat4x4)->vec3{let ndc=vec2(uv.x*2.0-1.0,(1.0-uv.y)*2.0-1.0);let viewSpaceDir=normalize(vec3(ndc.x*invP[0][0],ndc.y*invP[1][1],-1.0));let worldRotation=mat3x3(invV[0].xyz,invV[1].xyz,invV[2].xyz);return normalize(worldRotation*viewSpaceDir);}fn cloud_hash(p:vec2)->f32{return fract(sin(dot(p,vec2(127.1,311.7)))*43758.5453123);}fn cloud_noise(p:vec2)->f32{let i=floor(p);let f=fract(p);let u=f*f*(3.0-2.0*f);return mix(mix(cloud_hash(i+vec2(.0,.0)),cloud_hash(i+vec2(1.0,.0)),u.x),mix(cloud_hash(i+vec2(.0,1.0)),cloud_hash(i+vec2(1.0,1.0)),u.x),u.y);}fn cloud_fbm(p:vec2)->f32{var v=.0;var a=0.5;var shift=vec2(100.0);var p_mut=p;for(var i=0;i<5;i=i+1){v+=a*cloud_noise(p_mut);p_mut=p_mut*2.0+shift;a*=0.5;}return v;}fn getCloudWarpedUV(hitP:vec3,params:SkyAtmosphere)->vec2{let baseUV=hitP.xz*.05+vec2(params.cloudTime*.02);let warp=vec2(cloud_noise(baseUV*1.2+vec2(params.cloudTime*.01)),cloud_noise(baseUV*1.2+vec2(5.7,1.3)+vec2(params.cloudTime*.012)));return baseUV+warp*0.2;}fn getCloudDensity(hitP:vec3,params:SkyAtmosphere)->f32{let warpedUV=getCloudWarpedUV(hitP,params);let density=cloud_fbm(warpedUV);let coverage=params.cloudCoverage;let softness=(1.0-params.cloudDensity)*0.5+.01;return smoothstep(1.0-coverage,1.0-coverage+softness,density);}fn getCloudNormal(hitP:vec3,params:SkyAtmosphere)->vec3{let warpedUV=getCloudWarpedUV(hitP,params);let density=cloud_fbm(warpedUV);let eps=0.2;let dIdx=(cloud_fbm(warpedUV+vec2(eps,.0))-density)/eps;let dIdy=(cloud_fbm(warpedUV+vec2(.0,eps))-density)/eps;return normalize(vec3(-dIdx,2.0,-dIdy));}",i.transmittanceLUT=it}(Ze||(Ze={})),function(i){var g,x;(g=i.mesh||(i.mesh={})).entryPointPickingVertex="@vertex fn entryPointPickingVertex(inputData:InputData)->VertexOutput{var output:VertexOutput;let input_position=inputData.position;let u_modelMatrix=vertexUniforms.matrixList.modelMatrix;let u_projectionMatrix=systemUniforms.projection.projectionMatrix;let u_projectionViewMatrix=systemUniforms.projection.projectionViewMatrix;let u_camera=systemUniforms.camera;let u_viewMatrix=u_camera.viewMatrix;var position:vec4=u_modelMatrix*vec4(input_position,1.0);output.position=u_projectionViewMatrix*position;output.pickingId=unpack4x8unorm(vertexUniforms.pickingId);return output;}",g.entryPointPickingFragment="@fragment fn entryPointPickingFragment(inputData:InputData)->@location(0)vec4{var finalColor:vec4=inputData.pickingId;return finalColor;}",g.entryPointShadowVertex="#redgpu_include shadow.getShadowClipPosition #redgpu_include systemStruct.OutputShadowData;@vertex fn entryPointShadowVertex(inputData:InputData)->OutputShadowData{var output:OutputShadowData;let u_directionalLightProjectionViewMatrix=systemUniforms.directionalLightProjectionViewMatrix;let u_camera=systemUniforms.camera;let u_viewMatrix=u_camera.viewMatrix;let u_cameraPosition=u_camera.cameraPosition;let u_modelMatrix=vertexUniforms.matrixList.modelMatrix;let input_position=inputData.position;let input_vertexNormal=inputData.vertexNormal;let input_uv=inputData.uv;var position:vec4;position=u_modelMatrix*vec4(input_position,1.0);#redgpu_if useDisplacementTexture{let distance=distance(position.xyz,u_cameraPosition);let maxMip=f32(textureNumLevels(displacementTexture))-1.0;let mipLevel=clamp((distance/maxDistance)*maxMip,.0,maxMip);let displacedPosition=getDisplacementPosition(input_position,input_vertexNormal,displacementTexture,displacementTextureSampler,vertexUniforms.displacementScale,input_uv,mipLevel);position=u_modelMatrix*vec4(displacedPosition,1.0);}#redgpu_endIf output.position=getShadowClipPosition(position.xyz,u_directionalLightProjectionViewMatrix);return output;}",(i.billboard||(i.billboard={})).entryPointPickingVertex="@vertex fn entryPointPickingVertex(inputData:InputData)->VertexOutput{var output:VertexOutput;let u_resolution=systemUniforms.resolution;#redgpu_if disableJitter let u_projectionMatrix=systemUniforms.projection.noneJitterProjectionMatrix;#redgpu_else let u_projectionMatrix=systemUniforms.projection.projectionMatrix;#redgpu_endIf let u_viewMatrix=systemUniforms.camera.viewMatrix;let u_modelMatrix=vertexUniforms.matrixList.modelMatrix;let u_useBillboard=vertexUniforms.useBillboard;let u_usePixelSize=vertexUniforms.usePixelSize;let u_pixelSize=vertexUniforms.pixelSize;let u_renderRatioX=vertexUniforms._renderRatioX;let u_renderRatioY=vertexUniforms._renderRatioY;var ratioScaleMatrix:mat4x4=mat4x4(u_renderRatioX,0,0,0,0,u_renderRatioY,0,0,0,0,1,0,0,0,0,1);if(u_useBillboard==1){let billboardMatrix=getBillboardMatrix(u_viewMatrix,u_modelMatrix,1u);if(u_usePixelSize==1){let viewPositionCenter=billboardMatrix*vec4(.0,.0,.0,1.0);let clipCenter=u_projectionMatrix*viewPositionCenter;let scaleX=(u_pixelSize/u_resolution.x)*2.0*u_renderRatioX;let scaleY=(u_pixelSize/u_resolution.y)*2.0*u_renderRatioY;output.position=vec4(clipCenter.xy+inputData.position.xy*vec2(scaleX,scaleY)*clipCenter.w,clipCenter.zw);}else{output.position=u_projectionMatrix*billboardMatrix*ratioScaleMatrix*vec4(inputData.position,1.0);}}else{output.position=u_projectionMatrix*u_viewMatrix*u_modelMatrix*ratioScaleMatrix*vec4(inputData.position,1.0);}output.pickingId=unpack4x8unorm(vertexUniforms.pickingId);return output;}",(x=i.empty||(i.empty={})).entryPointPickingVertex="@vertex fn entryPointPickingVertex(inputData:InputData)->VertexOutput{var output:VertexOutput;return output;}",x.entryPointShadowVertex="#redgpu_include systemStruct.OutputShadowData;@vertex fn entryPointShadowVertex(inputData:InputData)->OutputShadowData{var output:OutputShadowData;return output;}"}(Je||(Je={})),function(i){i.OutputFragment="struct OutputFragment{@location(0)color:vec4,@location(1)gBufferNormal:vec4,@location(2)gBufferMotionVector:vec4,}",i.OutputShadowData="struct OutputShadowData{@builtin(position)position:vec4,};",i.Camera="struct Camera{viewMatrix:mat4x4,inverseViewMatrix:mat4x4,cameraPosition:vec3,nearClipping:f32,farClipping:f32,fieldOfView:f32,ev100:f32,_pad_exposure:f32,aperture:f32,shutterSpeed:f32,iso:f32,_pad:f32};",i.Projection="struct Projection{projectionMatrix:mat4x4,projectionViewMatrix:mat4x4,noneJitterProjectionMatrix:mat4x4,noneJitterProjectionViewMatrix:mat4x4,inverseProjectionMatrix:mat4x4,inverseProjectionViewMatrix:mat4x4,prevNoneJitterProjectionViewMatrix:mat4x4};",i.Time="struct Time{time:f32,deltaTime:f32,frameIndex:u32,sinTime:f32};",i.DirectionalLight="struct DirectionalLight{direction:vec3,color:vec3,intensity:f32,};",i.AmbientLight="struct AmbientLight{color:vec3,intensity:f32};",i.Shadow="struct Shadow{directionalShadowDepthTextureSize:u32,directionalShadowBias:f32,padding:vec2};",i.SkyAtmosphere="struct SkyAtmosphere{rayleighScattering:vec3,rayleighExponentialDistribution:f32,mieScattering:vec3,mieAnisotropy:f32,mieAbsorption:vec3,mieExponentialDistribution:f32,absorptionCoefficient:vec3,absorptionTipAltitude:f32,groundAlbedo:vec3,absorptionTentWidth:f32,skyLuminanceFactor:vec3,multiScatteringFactor:f32,sunDirection:vec3,transmittanceMinLightElevationAngle:f32,groundRadius:f32,atmosphereHeight:f32,aerialPerspectiveDistanceScale:f32,aerialPerspectiveStartDepth:f32,sunIntensity:f32,sunSize:f32,sunLimbDarkening:f32,cameraHeight:f32,cloudTime:f32,cloudTimeMultiplier:f32,cloudCoverage:f32,cloudDensity:f32,cloudHeight:f32};",i.meshVertexBasicUniform="struct MatrixList{localMatrix:mat4x4,modelMatrix:mat4x4,prevModelMatrix:mat4x4,normalModelMatrix:mat4x4,}struct VertexUniforms{matrixList:MatrixList,pickingId:u32,receiveShadow:f32,combinedOpacity:f32,useDisplacementTexture:u32,displacementScale:f32,disableJitter:u32,uvTransform:vec4,};"}(Qe||(Qe={})),function(i){i.getDisplacementPosition="fn getDisplacementPosition(input_position:vec3,input_vertexNormal:vec3,displacementTexture:texture_2d,displacementTextureSampler:sampler,displacementScale:f32,input_uv:vec2,mipLevel:f32)->vec3{let textureDimensions=vec2(textureDimensions(displacementTexture,0));let invTexSize=1.0/textureDimensions;let uv=input_uv*textureDimensions;let iuv=floor(uv-0.5);let fuv=fract(uv-0.5);let w0=(1.0-fuv)*(1.0-fuv)*(1.0-fuv)/6.0;let w1=(4.0-6.0*fuv*fuv+3.0*fuv*fuv*fuv)/6.0;let w2=(1.0+3.0*fuv+3.0*fuv*fuv-3.0*fuv*fuv*fuv)/6.0;let w3=fuv*fuv*fuv/6.0;let g0=w0+w1;let g1=w2+w3;let h0=(w1/g0)-1.0+iuv;let h1=(w3/g1)+1.0+iuv;let res0=textureSampleLevel(displacementTexture,displacementTextureSampler,(vec2(h0.x,h0.y)+0.5)*invTexSize,mipLevel).r*g0.x*g0.y;let res1=textureSampleLevel(displacementTexture,displacementTextureSampler,(vec2(h1.x,h0.y)+0.5)*invTexSize,mipLevel).r*g1.x*g0.y;let res2=textureSampleLevel(displacementTexture,displacementTextureSampler,(vec2(h0.x,h1.y)+0.5)*invTexSize,mipLevel).r*g0.x*g1.y;let res3=textureSampleLevel(displacementTexture,displacementTextureSampler,(vec2(h1.x,h1.y)+0.5)*invTexSize,mipLevel).r*g1.x*g1.y;let h_bicubic=res0+res1+res2+res3;let scaledDisplacement=(h_bicubic-0.5)*displacementScale;let displacedPosition=input_position+normalize(input_vertexNormal)*scaledDisplacement;return displacedPosition;}",i.getDisplacementNormal="fn sampleBicubic(uv:vec2,tex:texture_2d,smp:sampler,dims:vec2,invSize:vec2,mip:f32)->f32{let res_uv=uv*dims;let i=floor(res_uv-0.5);let f=fract(res_uv-0.5);let w0=(1.0-f)*(1.0-f)*(1.0-f)/6.0;let w1=(4.0-6.0*f*f+3.0*f*f*f)/6.0;let w2=(1.0+3.0*f+3.0*f*f-3.0*f*f*f)/6.0;let w3=f*f*f/6.0;let g0=w0+w1;let g1=w2+w3;let h0=(w1/g0)-1.0+i;let h1=(w3/g1)+1.0+i;let r0=textureSampleLevel(tex,smp,(vec2(h0.x,h0.y)+0.5)*invSize,mip).r*g0.x*g0.y;let r1=textureSampleLevel(tex,smp,(vec2(h1.x,h0.y)+0.5)*invSize,mip).r*g1.x*g0.y;let r2=textureSampleLevel(tex,smp,(vec2(h0.x,h1.y)+0.5)*invSize,mip).r*g0.x*g1.y;let r3=textureSampleLevel(tex,smp,(vec2(h1.x,h1.y)+0.5)*invSize,mip).r*g1.x*g1.y;return r0+r1+r2+r3;}fn getDisplacementNormal(displacementTexture:texture_2d,displacementTextureSampler:sampler,displacementScale:f32,input_uv:vec2,mipLevel:f32)->vec3{let textureDimensions=vec2(textureDimensions(displacementTexture,0));let invTexSize=1.0/textureDimensions;let step=invTexSize*exp2(mipLevel);let h_u0=sampleBicubic(input_uv+vec2(-step.x,.0),displacementTexture,displacementTextureSampler,textureDimensions,invTexSize,mipLevel);let h_u1=sampleBicubic(input_uv+vec2(step.x,.0),displacementTexture,displacementTextureSampler,textureDimensions,invTexSize,mipLevel);let h_v0=sampleBicubic(input_uv+vec2(.0,-step.y),displacementTexture,displacementTextureSampler,textureDimensions,invTexSize,mipLevel);let h_v1=sampleBicubic(input_uv+vec2(.0,step.y),displacementTexture,displacementTextureSampler,textureDimensions,invTexSize,mipLevel);let ddu=(h_u1-h_u0)*displacementScale/(step.x*2.0);let ddv=(h_v1-h_v0)*displacementScale/(step.y*2.0);return normalize(vec3(-ddu,-ddv,1.0));}"}(et||(et={})),function(i){i.SYSTEM_UNIFORM="#redgpu_include systemStruct.DirectionalLight #redgpu_include systemStruct.AmbientLight #redgpu_include systemStruct.Camera #redgpu_include systemStruct.Projection #redgpu_include systemStruct.Time #redgpu_include systemStruct.Shadow #redgpu_include systemStruct.SkyAtmosphere struct SystemUniform{projection:Projection,time:Time,resolution:vec2,camera:Camera,usePrefilterTexture:u32,isView3D:u32,useSkyAtmosphere:u32,preExposure:f32,iblIntensity:f32,skyAtmosphere:SkyAtmosphere,shadow:Shadow,directionalLightCount:u32,directionalLightProjectionViewMatrix:mat4x4,directionalLightProjectionMatrix:mat4x4,directionalLightViewMatrix:mat4x4,directionalLights:array,ambientLight:AmbientLight,};@group(0)@binding(0)varsystemUniforms:SystemUniform;@group(0)@binding(1)var directionalShadowMapSampler:sampler_comparison;@group(0)@binding(2)var directionalShadowMap:texture_depth_2d;@group(0)@binding(3)var prefilterTextureSampler:sampler;@group(0)@binding(7)var renderPath1ResultTextureSampler:sampler;@group(0)@binding(8)var renderPath1ResultTexture:texture_2d;@group(0)@binding(9)var packedTextureSampler:sampler;@group(0)@binding(10)var ibl_prefilterTexture:texture_cube;@group(0)@binding(11)var ibl_irradianceTexture:texture_cube;@group(0)@binding(12)var ibl_brdfLUTTexture:texture_2d;@group(0)@binding(13)var atmosphereSampler:sampler;@group(0)@binding(14)var transmittanceTexture:texture_2d;@group(0)@binding(15)var atmosphereIrradianceLUT:texture_cube;@group(0)@binding(16)var skyAtmosphere_prefilteredTexture:texture_cube;#redgpu_include depth.getLinearizeDepth const clusterLight_indicesLength:u32=u32(REDGPU_DEFINE_MAX_LIGHTS_PER_CLUSTERu*REDGPU_DEFINE_TOTAL_TILESu);const clusterLight_tileCount=vec3(REDGPU_DEFINE_TILE_COUNT_Xu,REDGPU_DEFINE_TILE_COUNT_Yu,REDGPU_DEFINE_TILE_COUNT_Zu);struct ClusterLightCell{offset:u32,count:u32};struct ClusterLightGrid{offset:atomic,cells:array,indices:array};struct ClusterLight{position:vec3,radius:f32,color:vec3,intensity:f32,isSpotLight:f32,directionX:f32,directionY:f32,directionZ:f32,outerCutoff:f32,innerCutoff:f32,};struct ClusterLightList{count:vec4,lights:array};@group(0)@binding(5)varclusterLightList:ClusterLightList;@group(0)@binding(6)varclusterLightGrid:ClusterLightGrid;fn getClusterLightClusterIndex(fragCoord:vec4)->u32{let tile=getClusterLightTile(fragCoord);return tile.x+tile.y*clusterLight_tileCount.x+tile.z*clusterLight_tileCount.x*clusterLight_tileCount.y;}fn getClusterLightTile(fragCoord:vec4)->vec3{let near=systemUniforms.camera.nearClipping;let far=systemUniforms.camera.farClipping;let sliceScale=f32(clusterLight_tileCount.z)/log2(far/near);let sliceBias=-(f32(clusterLight_tileCount.z)*log2(near)/log2(far/near));let zTile=u32(max(log2(getLinearizeDepth(fragCoord.z,near,far))*sliceScale+sliceBias,.0));return vec3(u32(fragCoord.x/(systemUniforms.resolution.x/f32(clusterLight_tileCount.x))),u32(fragCoord.y/(systemUniforms.resolution.y/f32(clusterLight_tileCount.y))),zTile);}",i.POST_EFFECT_SYSTEM_UNIFORM="#redgpu_include systemStruct.Camera #redgpu_include systemStruct.Projection #redgpu_include systemStruct.Time #redgpu_include systemStruct.SkyAtmosphere struct SystemUniform{projection:Projection,time:Time,camera:Camera,useSkyAtmosphere:u32,preExposure:f32,devicePixelRatio:f32,skyAtmosphere:SkyAtmosphere,};@group(2)@binding(4)varsystemUniforms:SystemUniform;",i.math=be,i.shadow=je,i.color=Ke,i.depth=Xe,i.lighting=Ye,i.skyAtmosphere=Ze,i.entryPoint=Je,i.systemStruct=Qe,i.displacement=et}(tt||(tt={}));var ft=tt;class ShaderVariantGenerator{#Ce=new Map;#Be;#De;#Ee=[];#Ie=[];#Ae=new Map;#Le=new Map;constructor(i,g){this.#Be=i,this.#De=g}setBaseInfo(i,g){this.#Ee=i,this.#Ie=g}addConditionalInfo(i,g,x){this.#Ae.set(i,g),this.#Le.set(i,x)}getVariantTextures(i){const g="none"===i?[]:i.split("+"),x=[...this.#Ee];return g.forEach(i=>{const g=this.#Ae.get(i);g&&g.forEach(i=>{x.find(g=>g.name===i.name)||x.push(i)})}),x}getVariantSamplers(i){const g="none"===i?[]:i.split("+"),x=[...this.#Ie];return g.forEach(i=>{const g=this.#Le.get(i);g&&g.forEach(i=>{x.find(g=>g.name===i.name)||x.push(i)})}),x}getUnionTextures(){const i=[...this.#Ee];return this.#Ae.forEach(g=>{g.forEach(g=>{i.find(i=>i.name===g.name)||i.push(g)})}),i}getUnionSamplers(){const i=[...this.#Ie];return this.#Le.forEach(g=>{g.forEach(g=>{i.find(i=>i.name===g.name)||i.push(g)})}),i}getVariant(i){if(this.#Ce.has(i))return this.#Ce.get(i);const g="none"===i?[]:i.split("+"),x=this.#Ue(g);return this.#Ce.set(i,x),x}getCachedVariants(){return Array.from(this.#Ce.keys())}#Ue(i){let g=this.#Be;for(let x=this.#De.length-1;x>=0;x--){const v=this.#De[x];g=i.includes(v.uniformName)?g.replace(v.fullMatch,v.ifBlock):g.replace(v.fullMatch,v.elseBlock||"")}return g}}const pt=/#redgpu_include\s+([\w.]+)/g,xt=/REDGPU_DEFINE_(?:TILE_COUNT_[XYZ]|TOTAL_TILES|WORKGROUP_SIZE_[XYZ]|MAX_LIGHTS_PER_CLUSTER)/g,vt={REDGPU_DEFINE_TILE_COUNT_X:W.TILE_COUNT_X.toString(),REDGPU_DEFINE_TILE_COUNT_Y:W.TILE_COUNT_Y.toString(),REDGPU_DEFINE_TILE_COUNT_Z:W.TILE_COUNT_Z.toString(),REDGPU_DEFINE_TOTAL_TILES:W.getTotalTileSize().toString(),REDGPU_DEFINE_WORKGROUP_SIZE_X:W.WORKGROUP_SIZE_X.toString(),REDGPU_DEFINE_WORKGROUP_SIZE_Y:W.WORKGROUP_SIZE_Y.toString(),REDGPU_DEFINE_WORKGROUP_SIZE_Z:W.WORKGROUP_SIZE_Z.toString(),REDGPU_DEFINE_MAX_LIGHTS_PER_CLUSTER:W.MAX_LIGHTS_PER_CLUSTER.toString()},yt=new Map,bt=new Map,preprocessWGSL=(i,g,x)=>{if(!i)throw new Error(`[preprocessWGSL] sourceName is required. (provided: ${i})`);const v=(i=>{let g=0;for(let x=0;x{let v=i,_=0;const y=new Set,resolvePath=(i,v,_)=>{if(y.has(i))return"";if(x&&i in x)return y.add(i),x[i];const b=i.split(".");let S=ft;for(const x of b){if(!S||"object"!=typeof S||!(x in S)){const x=_.substring(0,v).split("\n").length;throw new Error(`[preprocessWGSL] Invalid include path in [${g}] at line ${x}: #redgpu_include ${i}. Path not found in injected library or ShaderLibrary.`)}S=S[x]}if("string"==typeof S)return y.add(i),S;{const x=_.substring(0,v).split("\n").length;throw new Error(`[preprocessWGSL] Invalid include target in [${g}] at line ${x}: #redgpu_include ${i}. Target is not a WGSL string.`)}};for(;_<10;){const i=v;if(v=v.replace(pt,(i,g,x)=>{const _=resolvePath(g,x,v);return null!==_?_:i}),v===i)break;_++}return v})(g,i,x),w=(i=>i.replace(xt,i=>vt[i]||i))(S),L=(i=>{const g=[],x=/#redgpu_if\s+(\w+)\b|#redgpu_else|#redgpu_endIf/g,v=[];let _,y=0;for(;null!==(_=x.exec(i));){const x=_[0];if(x.startsWith("#redgpu_if"))v.push({uniformName:_[1],startIndex:_.index,headerLength:x.length});else if("#redgpu_else"===x){const i=v[v.length-1];if(!i)throw new Error(`[preprocessWGSL] Mismatched #redgpu_else at index ${_.index}`);void 0===i.elseIndex&&(i.elseIndex=_.index)}else if("#redgpu_endIf"===x){const b=v.pop();if(!b)throw new Error(`[preprocessWGSL] Mismatched #redgpu_endIf at index ${_.index}`);{const v=i.substring(b.startIndex,_.index+x.length);let S,w;void 0!==b.elseIndex?(S=i.substring(b.startIndex+b.headerLength,b.elseIndex),w=i.substring(b.elseIndex+12,_.index)):S=i.substring(b.startIndex+b.headerLength,_.index),g.push({uniformName:b.uniformName,ifBlock:S.trim(),elseBlock:w?.trim(),fullMatch:v,blockIndex:y++})}}}if(v.length>0)throw new Error(`[preprocessWGSL] Unclosed #redgpu_if for: ${v.map(i=>i.uniformName).join(", ")}`);return g})(w);(i=>{if(!i.length)return;const g=new Map;i.forEach(i=>{g.set(i.uniformName,(g.get(i.uniformName)||0)+1)}),Array.from(g.entries()).filter(([i,g])=>g>1).length})(L);const k=[...new Set(L.map(i=>i.uniformName))],H=new ShaderVariantGenerator(w,L),z={cacheKey:y,defaultSource:H.getVariant("none"),shaderSourceVariant:H,conditionalBlocks:k,conditionalBlockInfos:L};return Math.pow(2,k.length),yt.set(y,z),z};class ResourceStatusInfo{table=new Map;videoMemory=0;constructor(){}}var St;Object.freeze(ResourceStatusInfo),function(i){i.GPUShaderModule="GPUShaderModule",i.GPUBindGroupLayout="GPUBindGroupLayout",i.GPUPipelineLayout="GPUPipelineLayout",i.GPUBuffer="GPUBuffer"}(St||(St={}));class ResourceManager extends RedGPUObject{static PRESET_GPUBindGroupLayout_System="PRESET_GPUBindGroupLayout_System";static PRESET_VERTEX_GPUBindGroupLayout_Instancing="PRESET_VERTEX_GPUBindGroupLayout_Instancing";static PRESET_VERTEX_GPUBindGroupLayout="PRESET_VERTEX_GPUBindGroupLayout";static PRESET_VERTEX_GPUBindGroupLayout_SKIN="PRESET_VERTEX_GPUBindGroupLayout_SKIN";#ke=new ImmutableKeyMap([[St.GPUShaderModule,new Map],[St.GPUBindGroupLayout,new Map],[St.GPUPipelineLayout,new Map],[St.GPUBuffer,new MemoryTrackingMap]]);#Ge=new ResourceStatusInfo;#Oe=new ResourceStatusInfo;#Ve=new ResourceStatusInfo;#Ne=new ResourceStatusInfo;#Fe=new ResourceStatusInfo;#He=new ResourceStatusInfo;#ze=new ResourceStatusInfo;#$e={};#je;#Ke;#Xe;#qe;#Ye;#We;#Ze;#Je;#Qe;#et;#tt;#rt;#it=new WeakMap;#nt=new WeakMap;constructor(i){super(i),this.#Ye=new MipmapGenerator(i),this.#We=new DownSampleCubeMapGenerator(i),this.#Ze=new BRDFGenerator(i),this.#Je=new IrradianceGenerator(i),this.#Qe=new PrefilterGenerator(i),this.#et=new EquirectangularToCubeGenerator(i),this.#at()}get basicSampler(){return this.#tt}get basicDisplacementSampler(){return this.#rt}get brdfGenerator(){return this.#Ze}get irradianceGenerator(){return this.#Je}get prefilterGenerator(){return this.#Qe}get equirectangularToCubeGenerator(){return this.#et}get mipmapGenerator(){return this.#Ye}get downSampleCubeMapGenerator(){return this.#We}get cachedBufferState(){return this.#$e}get emptyBitmapTextureView(){return this.#je}get emptyCubeTextureView(){return this.#Ke}get emptyTexture3DView(){return this.#Xe}get emptyDepthTextureView(){return this.#qe}get managedBitmapTextureState(){return this.#Ge}get managedCubeTextureState(){return this.#Oe}get managedHDRTextureState(){return this.#Ve}get managedUniformBufferState(){return this.#Ne}get managedVertexBufferState(){return this.#Fe}get managedIndexBufferState(){return this.#He}get managedStorageBufferState(){return this.#ze}get resources(){return this.#ke}registerManagementResource(i,x){const{cacheKey:v,targetResourceManagedState:_}=i,{table:y}=_;y.get(v)?g(`Resource with cacheKey ${v} is already registered.`):(y.set(v,x),_.videoMemory+=i.videoMemorySize)}unregisterManagementResource(i){const{cacheKey:g,targetResourceManagedState:x}=i,{table:v}=x;v.get(g)&&(x.videoMemory-=i.videoMemorySize,v.delete(g))}createManagedTexture(i){const g=this.gpuDevice.createTexture(i),x=g.destroy.bind(g);return g.destroy=()=>{this.#st(g,i),x()},g}getGPUResourceBitmapTextureView(i,g){const x=i instanceof GPUTexture?i:i?.gpuTexture;if(!x)return this.#je;let v=this.#it.get(x);v||(v=new Map,this.#it.set(x,v));const _=this.#ot(g);let y=v.get(_);if(!y){const i=g?{...g,label:g.label||x.label}:{label:x.label};y=x.createView(i),v.set(_,y)}return y}getGPUResourceCubeTextureView(i,g){const x=i instanceof GPUTexture?i:i?.gpuTexture;if(!x)return this.#Ke;let v=this.#nt.get(x);v||(v=new Map,this.#nt.set(x,v));const _=g||(i instanceof GPUTexture?CubeTexture.defaultViewDescriptor:i.viewDescriptor),y=this.#ot(_);let b=v.get(y);if(!b){const i={..._,label:x.label};b=x.createView(i),v.set(y,b)}return b}createGPUShaderModule(i,g){return this.#ut(i,g,g=>this.#lt(i,g),St.GPUShaderModule)}getGPUShaderModule(i){return this.#ct(i,St.GPUShaderModule)}deleteGPUShaderModule(i){this.#ht(i,St.GPUShaderModule)}createBindGroupLayout(i,g){return this.#ut(i,g,g=>(g.label||(g.label=i),this.redGPUContext.gpuDevice.createBindGroupLayout(g)),St.GPUBindGroupLayout)}getGPUBindGroupLayout(i){return this.#ct(i,St.GPUBindGroupLayout)}deleteGPUBindGroupLayout(i){this.#ht(i,St.GPUBindGroupLayout)}createGPUPipelineLayout(i,g){return this.#ut(i,g,g=>(g.label||(g.label=i),this.redGPUContext.gpuDevice.createPipelineLayout(g)),St.GPUPipelineLayout)}createGPUBuffer(i,g){return this.#ut(i,g,g=>(g.label||(g.label=i),this.gpuDevice.createBuffer(g)),St.GPUBuffer)}#st(i,g){const x="3d"===g.dimension?this.#nt:this.#it;x.get(i)?.clear(),x.delete(i)}#ot(i){return i?JSON.stringify(i):"default"}#at(){const{gpuDevice:i}=this.redGPUContext;{const g=i.createTexture({size:{width:1,height:1,depthOrArrayLayers:1},format:"rgba8unorm",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.STORAGE_BINDING,label:"EMPTY_BITMAP_TEXTURE"});this.#je=g.createView({label:g.label});const x=new Uint8Array([0,0,0,0]);i.queue.writeTexture({texture:g},x,{bytesPerRow:4,rowsPerImage:1},{width:1,height:1,depthOrArrayLayers:1});const v=i.createTexture({size:{width:1,height:1,depthOrArrayLayers:6},format:"rgba8unorm",usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST,label:"EMPTY_CUBE_TEXTURE"});this.#Ke=v.createView(CubeTexture.defaultViewDescriptor);const _=new Uint8Array([0,0,0,0]);for(let g=0;g<6;g++)i.queue.writeTexture({texture:v,origin:{x:0,y:0,z:g}},_,{bytesPerRow:4,rowsPerImage:1},{width:1,height:1,depthOrArrayLayers:1});const y=i.createTexture({size:{width:1,height:1,depthOrArrayLayers:1},dimension:"3d",format:"rgba8unorm",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST,label:"EMPTY_TEXTURE_3D"});this.#Xe=y.createView({label:y.label,dimension:"3d"});const b=i.createTexture({size:{width:1,height:1,depthOrArrayLayers:1},format:"depth24plus",usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING,label:"EMPTY_DEPTH_TEXTURE"});this.#qe=b.createView({label:b.label}),this.#tt=new Sampler(this.redGPUContext),this.#rt=new Sampler(this.redGPUContext,{magFilter:"linear",minFilter:"linear",mipmapFilter:"linear",addressModeU:"repeat",addressModeV:"repeat",addressModeW:"repeat"})}this.createBindGroupLayout(ResourceManager.PRESET_GPUBindGroupLayout_System,{entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT|GPUShaderStage.COMPUTE,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,sampler:{type:"comparison"}},{binding:2,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"depth"}},{binding:3,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}},{binding:5,visibility:GPUShaderStage.FRAGMENT|GPUShaderStage.COMPUTE,buffer:{type:"read-only-storage"}},{binding:6,visibility:GPUShaderStage.FRAGMENT|GPUShaderStage.COMPUTE,buffer:{type:"storage"}},{binding:7,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}},{binding:8,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:9,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}},{binding:10,visibility:GPUShaderStage.FRAGMENT,texture:{viewDimension:"cube"}},{binding:11,visibility:GPUShaderStage.FRAGMENT,texture:{viewDimension:"cube"}},{binding:12,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:13,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}},{binding:14,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:15,visibility:GPUShaderStage.FRAGMENT,texture:{viewDimension:"cube"}},{binding:16,visibility:GPUShaderStage.FRAGMENT,texture:{viewDimension:"cube"}}]}),this.createBindGroupLayout(ResourceManager.PRESET_VERTEX_GPUBindGroupLayout,{entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.VERTEX,sampler:{type:"filtering"}},{binding:2,visibility:GPUShaderStage.VERTEX,texture:{}}]}),this.createBindGroupLayout(ResourceManager.PRESET_VERTEX_GPUBindGroupLayout_SKIN,{entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.VERTEX,sampler:{type:"filtering"}},{binding:2,visibility:GPUShaderStage.VERTEX,texture:{}},{binding:3,visibility:GPUShaderStage.VERTEX,buffer:{type:"read-only-storage"}},{binding:4,visibility:GPUShaderStage.VERTEX,buffer:{type:"read-only-storage"}}]}),this.createBindGroupLayout(ResourceManager.PRESET_VERTEX_GPUBindGroupLayout_Instancing,{entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"read-only-storage"}},{binding:1,visibility:GPUShaderStage.VERTEX,sampler:{type:"filtering"}},{binding:2,visibility:GPUShaderStage.VERTEX,texture:{}},{binding:3,visibility:GPUShaderStage.VERTEX,buffer:{type:"read-only-storage"}}]})}#ft(i){return this.#ke.get(i)}#lt(i,g){const{code:x}=g,v=preprocessWGSL(i,x).defaultSource,_=this.redGPUContext.gpuDevice.createShaderModule({...g,code:v});return this.#ft(St.GPUShaderModule).set(i,_),_}#dt(i,g){if(!i)throw new Error("Name is required");return this.#ft(g)}#ut(i,g,x,v){const _=this.#dt(i,v);if(_.has(i))return _.get(i);g.label||(g.label=i);const y=x(g);return _.set(i,y),y}#ct(i,g){return this.#dt(i,g).get(i)}#ht(i,g){const x=this.#dt(i,g);if(!x.has(i))throw new Error(`${g} with name ${i} doesn't exist.`);x.delete(i)}}Object.freeze(ResourceManager);class ImmutableKeyMap extends Map{constructor(i=[]){super(),i?.forEach(([i,g])=>super.set(i,g))}set(i,g){if(this.has(i))throw new Error("Cannot change the value of an existing key");return super.set(i,g)}}class MemoryTrackingMap extends Map{#mt=0;constructor(){super()}get videoMemory(){return this.#mt}set(i,g){const x=g&&"videoMemorySize"in g?"videoMemorySize":g&&"size"in g?"size":void 0;if(this.has(i)){const g=this.get(i);g&&g[x]&&(this.#mt-=g[x])}if(g&&g){const i=g[x];"number"==typeof i&&(this.#mt+=i)}return super.set(i,g)}delete(i){if(this.has(i)){const g=this.get(i),x=g&&"videoMemorySize"in g?"videoMemorySize":g&&"size"in g?"size":void 0;g&&"number"==typeof g[x]&&(this.#mt-=g[x])}return super.delete(i)}clear(){this.#mt=0,super.clear()}}class AntialiasingManager{#pt=createUUID();#gt=!0;#xt=!1;#vt=!1;constructor(){window.devicePixelRatio>1?this.useTAA=!0:this.useMSAA=!0}get useTAA(){return this.#vt}set useTAA(i){this.#vt!==i&&(this.#_t(),this.#vt=i)}get useMSAA(){return this.#gt}set useMSAA(i){this.#gt!==i&&(this.#_t(),this.#pt=createUUID(),this.#gt=i)}get useFXAA(){return this.#xt}set useFXAA(i){this.#xt!==i&&(this.#_t(),this.#xt=i)}get msaaID(){return this.#pt}#_t(){this.#gt=!1,this.#xt=!1,this.#vt=!1}}Object.freeze(AntialiasingManager);class RedGPUContextDetector{#yt;#bt;#St;#Tt;#wt={};#Mt={};#Pt;#Rt;#Ct;#Bt;#Dt;#Et;#It;#At;#Lt;#Ut;constructor(i){const g=navigator.userAgent;this.#Rt=g,this.#Ct=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|Windows Phone|Kindle|Silk|PlayBook/i.test(g),this.#Bt=/iPhone|iPad|iPod/i.test(g),this.#Dt=/Android/i.test(g),this.#Et=/Chrome|Chromium|Edg|Opr/i.test(g)&&!/Edge/i.test(g),this.#It=/Safari/i.test(g)&&!/Chrome|Chromium|Edg|Opr/i.test(g),this.#At=/Firefox/i.test(g),this.#Lt=navigator.hardwareConcurrency||4,this.#Ut=navigator.deviceMemory||4;const{gpuAdapter:x,gpuDevice:v}=i;this.#yt=x;const _=["core-features-and-limits","depth-clip-control","depth32float-stencil8","texture-compression-bc","texture-compression-bc-sliced-3d","texture-compression-etc2","texture-compression-astc","texture-compression-astc-sliced-3d","timestamp-query","indirect-first-instance","shader-f16","rg11b10ufloat-renderable","bgra8unorm-storage","float32-filterable","float32-blendable","clip-distances","dual-source-blending","subgroups","texture-formats-tier1","texture-formats-tier2","primitive-index","texture-component-swizzle"];if(x){this.#bt=x.info,this.#Pt=x.info.isFallbackAdapter,this.#St=x.limits;const i=Array.from(x.features),g=Array.from(new Set([..._,...i])).sort();this.#wt={};for(const i of g)this.#wt[i]=x.features.has(i)}if(v){this.#Tt=v.limits,this.#Mt={};for(const i in this.#wt)this.#Mt[i]=v.features.has(i)}}get supportedFeatures(){return this.#wt}get activeFeatures(){return this.#Mt}get supportedLimits(){return this.#St}get activeLimits(){return this.#Tt}get gpuAdapter(){return this.#yt}get adapterInfo(){return this.#bt}get isFallbackAdapter(){return this.#Pt}get userAgent(){return this.#Rt}get isMobile(){return this.#Ct}get isIOS(){return this.#Bt}get isAndroid(){return this.#Dt}get isChromium(){return this.#Et}get isSafari(){return this.#It}get isFirefox(){return this.#At}get hardwareConcurrency(){return this.#Lt}get deviceMemory(){return this.#Ut}toReport(){return{platform:{isMobile:this.#Ct,isIOS:this.#Bt,isAndroid:this.#Dt,userAgent:this.#Rt},browser:{isChromium:this.#Et,isSafari:this.#It,isFirefox:this.#At},hardware:{hardwareConcurrency:this.#Lt,deviceMemory:this.#Ut},gpu:{vendor:this.#bt?.vendor,architecture:this.#bt?.architecture,device:this.#bt?.device,description:this.#bt?.description,isFallback:this.#Pt,supportedFeatures:{...this.#wt},activeFeatures:{...this.#Mt},supportedLimits:this.#St?this.#kt(this.#St):null,activeLimits:this.#Tt?this.#kt(this.#Tt):null}}}#kt(i){const g={},x=Object.getPrototypeOf(i);return Object.getOwnPropertyNames(x).forEach(x=>{const v=i[x];"number"==typeof v&&(g[x]=v)}),g}}const validateNumber=i=>"number"==typeof i&&!Number.isNaN(i)||(consoleAndThrowError("Only numbers allowed."),!1);class RedGPUContextSizeManager extends RedGPUObject{#Gt;#Ot;#Vt=[0,0,0,0];#Nt;#Ft=1;constructor(i,g="100%",x="100%"){super(i),this.#Nt=i.htmlCanvas,this.#Nt.style.boxSizing="border-box",this.#Nt.style.verticalAlign="top",this.#Gt=g,this.#Ot=x}get renderScale(){return this.#Ft}set renderScale(i){validateNumber(i),i<=0&&(i=.01),this.#Ft=i,this.setSize()}get width(){return this.#Gt}set width(i){this.setSize(i,this.#Ot)}get height(){return this.#Ot}set height(i){this.setSize(this.#Gt,i)}get pixelRectArray(){return this.#Vt}get pixelRectObject(){return{x:this.#Vt[0],y:this.#Vt[1],width:this.#Vt[2],height:this.#Vt[3]}}get parentDomRect(){const i=this.#Nt.parentElement;if(!i||i===document.body||i===document.documentElement)return{x:0,y:0,width:window.innerWidth,height:window.innerHeight};const g=i.getBoundingClientRect();return{x:g.x,y:g.y,width:i.clientWidth||g.width,height:i.clientHeight||g.height}}get screenRectObject(){return{x:this.#Vt[0]/devicePixelRatio,y:this.#Vt[1]/devicePixelRatio,width:this.#Vt[2]/devicePixelRatio,height:this.#Vt[3]/devicePixelRatio}}static validateSizeValue=i=>{switch(typeof i){case"number":validatePositiveNumberRange(i);break;case"string":new RegExp(/^[+]?^[.]?(\d+)(\.\d+)?(?:px|%|$)/gm).test(i)||consoleAndThrowError(`allow positive number, %, px model / input : ${i}`);break;default:consoleAndThrowError(`positive number, %, px model / input : ${i}`)}};static validatePositionValue=i=>{switch(typeof i){case"number":validateNumber(i);break;case"string":new RegExp(/^-?\d+(\.\d+)?(px|%)?$/).test(i)||consoleAndThrowError(`allow number, %, px model / input : ${i}`);break;default:consoleAndThrowError(`number, %, px model / input : ${i}`)}};static getPixelDimension(i,g,x){return"number"==typeof x?x:RedGPUContextSizeManager.calculateSizeFromString(i,g,x)}static calculateSizeFromString(i,g,x){return x.includes("%")?Math.round(i[g]*+x.replace("%","")/100):+x.replace("px","")}setSize(i=this.#Gt,g=this.#Ot){RedGPUContextSizeManager.validateSizeValue(i),RedGPUContextSizeManager.validateSizeValue(g),this.#Gt=i,this.#Ot=g;const x=this.parentDomRect,v=RedGPUContextSizeManager.getPixelDimension(x,"width",i),_=RedGPUContextSizeManager.getPixelDimension(x,"height",g),y=window.devicePixelRatio,b=Math.max(1,Math.floor(v*this.#Ft*y)),S=Math.max(1,Math.floor(_*this.#Ft*y));this.#Vt[2]===b&&this.#Vt[3]===S&&Math.abs(parseFloat(this.#Nt.style.width)-v)<.1&&Math.abs(parseFloat(this.#Nt.style.height)-_)<.1||(this.#Ht(v,_),this.#zt(v,_),this.#$t())}#zt(i,g){this.#Vt[2]=Math.max(1,Math.floor(i*this.#Ft*window.devicePixelRatio)),this.#Vt[3]=Math.max(1,Math.floor(g*this.#Ft*window.devicePixelRatio))}#$t(){const{redGPUContext:i}=this;i.onResize&&i.onResize({target:i,screenRectObject:this.screenRectObject,pixelRectObject:this.pixelRectObject}),i.viewList.forEach(i=>{i.setSize(),i.setPosition()})}#Ht(i,g){const x=this.#Nt,{style:v}=x;x.width=Math.max(1,i*this.#Ft*window.devicePixelRatio),x.height=Math.max(1,g*this.#Ft*window.devicePixelRatio),v.width=`${i}px`,v.height=`${g}px`}}var Tt=1e-6,wt="undefined"!=typeof Float32Array?Float32Array:Array,Mt=Math.random;function round$3(i){return i>=0?Math.round(i):i%.5==0?Math.floor(i):Math.round(i)}function create$5(){var i=new wt(9);return wt!=Float32Array&&(i[1]=0,i[2]=0,i[3]=0,i[5]=0,i[6]=0,i[7]=0),i[0]=1,i[4]=1,i[8]=1,i}function multiply$5(i,g,x){var v=g[0],_=g[1],y=g[2],b=g[3],S=g[4],w=g[5],L=g[6],k=g[7],H=g[8],z=x[0],q=x[1],W=x[2],be=x[3],je=x[4],Ke=x[5],Xe=x[6],Ye=x[7],Ze=x[8];return i[0]=z*v+q*b+W*L,i[1]=z*_+q*S+W*k,i[2]=z*y+q*w+W*H,i[3]=be*v+je*b+Ke*L,i[4]=be*_+je*S+Ke*k,i[5]=be*y+je*w+Ke*H,i[6]=Xe*v+Ye*b+Ze*L,i[7]=Xe*_+Ye*S+Ze*k,i[8]=Xe*y+Ye*w+Ze*H,i}function subtract$4(i,g,x){return i[0]=g[0]-x[0],i[1]=g[1]-x[1],i[2]=g[2]-x[2],i[3]=g[3]-x[3],i[4]=g[4]-x[4],i[5]=g[5]-x[5],i[6]=g[6]-x[6],i[7]=g[7]-x[7],i[8]=g[8]-x[8],i}var Pt=multiply$5,Rt=subtract$4,Ct=Object.freeze({__proto__:null,add:function(i,g,x){return i[0]=g[0]+x[0],i[1]=g[1]+x[1],i[2]=g[2]+x[2],i[3]=g[3]+x[3],i[4]=g[4]+x[4],i[5]=g[5]+x[5],i[6]=g[6]+x[6],i[7]=g[7]+x[7],i[8]=g[8]+x[8],i},adjoint:function(i,g){var x=g[0],v=g[1],_=g[2],y=g[3],b=g[4],S=g[5],w=g[6],L=g[7],k=g[8];return i[0]=b*k-S*L,i[1]=_*L-v*k,i[2]=v*S-_*b,i[3]=S*w-y*k,i[4]=x*k-_*w,i[5]=_*y-x*S,i[6]=y*L-b*w,i[7]=v*w-x*L,i[8]=x*b-v*y,i},clone:function(i){var g=new wt(9);return g[0]=i[0],g[1]=i[1],g[2]=i[2],g[3]=i[3],g[4]=i[4],g[5]=i[5],g[6]=i[6],g[7]=i[7],g[8]=i[8],g},copy:function(i,g){return i[0]=g[0],i[1]=g[1],i[2]=g[2],i[3]=g[3],i[4]=g[4],i[5]=g[5],i[6]=g[6],i[7]=g[7],i[8]=g[8],i},create:create$5,determinant:function(i){var g=i[0],x=i[1],v=i[2],_=i[3],y=i[4],b=i[5],S=i[6],w=i[7],L=i[8];return g*(L*y-b*w)+x*(-L*_+b*S)+v*(w*_-y*S)},equals:function(i,g){var x=i[0],v=i[1],_=i[2],y=i[3],b=i[4],S=i[5],w=i[6],L=i[7],k=i[8],H=g[0],z=g[1],q=g[2],W=g[3],be=g[4],je=g[5],Ke=g[6],Xe=g[7],Ye=g[8];return Math.abs(x-H)<=Tt*Math.max(1,Math.abs(x),Math.abs(H))&&Math.abs(v-z)<=Tt*Math.max(1,Math.abs(v),Math.abs(z))&&Math.abs(_-q)<=Tt*Math.max(1,Math.abs(_),Math.abs(q))&&Math.abs(y-W)<=Tt*Math.max(1,Math.abs(y),Math.abs(W))&&Math.abs(b-be)<=Tt*Math.max(1,Math.abs(b),Math.abs(be))&&Math.abs(S-je)<=Tt*Math.max(1,Math.abs(S),Math.abs(je))&&Math.abs(w-Ke)<=Tt*Math.max(1,Math.abs(w),Math.abs(Ke))&&Math.abs(L-Xe)<=Tt*Math.max(1,Math.abs(L),Math.abs(Xe))&&Math.abs(k-Ye)<=Tt*Math.max(1,Math.abs(k),Math.abs(Ye))},exactEquals:function(i,g){return i[0]===g[0]&&i[1]===g[1]&&i[2]===g[2]&&i[3]===g[3]&&i[4]===g[4]&&i[5]===g[5]&&i[6]===g[6]&&i[7]===g[7]&&i[8]===g[8]},frob:function(i){return Math.sqrt(i[0]*i[0]+i[1]*i[1]+i[2]*i[2]+i[3]*i[3]+i[4]*i[4]+i[5]*i[5]+i[6]*i[6]+i[7]*i[7]+i[8]*i[8])},fromMat2d:function(i,g){return i[0]=g[0],i[1]=g[1],i[2]=0,i[3]=g[2],i[4]=g[3],i[5]=0,i[6]=g[4],i[7]=g[5],i[8]=1,i},fromMat4:function(i,g){return i[0]=g[0],i[1]=g[1],i[2]=g[2],i[3]=g[4],i[4]=g[5],i[5]=g[6],i[6]=g[8],i[7]=g[9],i[8]=g[10],i},fromQuat:function(i,g){var x=g[0],v=g[1],_=g[2],y=g[3],b=x+x,S=v+v,w=_+_,L=x*b,k=v*b,H=v*S,z=_*b,q=_*S,W=_*w,be=y*b,je=y*S,Ke=y*w;return i[0]=1-H-W,i[3]=k-Ke,i[6]=z+je,i[1]=k+Ke,i[4]=1-L-W,i[7]=q-be,i[2]=z-je,i[5]=q+be,i[8]=1-L-H,i},fromRotation:function(i,g){var x=Math.sin(g),v=Math.cos(g);return i[0]=v,i[1]=x,i[2]=0,i[3]=-x,i[4]=v,i[5]=0,i[6]=0,i[7]=0,i[8]=1,i},fromScaling:function(i,g){return i[0]=g[0],i[1]=0,i[2]=0,i[3]=0,i[4]=g[1],i[5]=0,i[6]=0,i[7]=0,i[8]=1,i},fromTranslation:function(i,g){return i[0]=1,i[1]=0,i[2]=0,i[3]=0,i[4]=1,i[5]=0,i[6]=g[0],i[7]=g[1],i[8]=1,i},fromValues:function(i,g,x,v,_,y,b,S,w){var L=new wt(9);return L[0]=i,L[1]=g,L[2]=x,L[3]=v,L[4]=_,L[5]=y,L[6]=b,L[7]=S,L[8]=w,L},identity:function(i){return i[0]=1,i[1]=0,i[2]=0,i[3]=0,i[4]=1,i[5]=0,i[6]=0,i[7]=0,i[8]=1,i},invert:function(i,g){var x=g[0],v=g[1],_=g[2],y=g[3],b=g[4],S=g[5],w=g[6],L=g[7],k=g[8],H=k*b-S*L,z=-k*y+S*w,q=L*y-b*w,W=x*H+v*z+_*q;return W?(W=1/W,i[0]=H*W,i[1]=(-k*v+_*L)*W,i[2]=(S*v-_*b)*W,i[3]=z*W,i[4]=(k*x-_*w)*W,i[5]=(-S*x+_*y)*W,i[6]=q*W,i[7]=(-L*x+v*w)*W,i[8]=(b*x-v*y)*W,i):null},mul:Pt,multiply:multiply$5,multiplyScalar:function(i,g,x){return i[0]=g[0]*x,i[1]=g[1]*x,i[2]=g[2]*x,i[3]=g[3]*x,i[4]=g[4]*x,i[5]=g[5]*x,i[6]=g[6]*x,i[7]=g[7]*x,i[8]=g[8]*x,i},multiplyScalarAndAdd:function(i,g,x,v){return i[0]=g[0]+x[0]*v,i[1]=g[1]+x[1]*v,i[2]=g[2]+x[2]*v,i[3]=g[3]+x[3]*v,i[4]=g[4]+x[4]*v,i[5]=g[5]+x[5]*v,i[6]=g[6]+x[6]*v,i[7]=g[7]+x[7]*v,i[8]=g[8]+x[8]*v,i},normalFromMat4:function(i,g){var x=g[0],v=g[1],_=g[2],y=g[3],b=g[4],S=g[5],w=g[6],L=g[7],k=g[8],H=g[9],z=g[10],q=g[11],W=g[12],be=g[13],je=g[14],Ke=g[15],Xe=x*S-v*b,Ye=x*w-_*b,Ze=x*L-y*b,Je=v*w-_*S,Qe=v*L-y*S,et=_*L-y*w,tt=k*be-H*W,it=k*je-z*W,ft=k*Ke-q*W,pt=H*je-z*be,xt=H*Ke-q*be,vt=z*Ke-q*je,yt=Xe*vt-Ye*xt+Ze*pt+Je*ft-Qe*it+et*tt;return yt?(yt=1/yt,i[0]=(S*vt-w*xt+L*pt)*yt,i[1]=(w*ft-b*vt-L*it)*yt,i[2]=(b*xt-S*ft+L*tt)*yt,i[3]=(_*xt-v*vt-y*pt)*yt,i[4]=(x*vt-_*ft+y*it)*yt,i[5]=(v*ft-x*xt-y*tt)*yt,i[6]=(be*et-je*Qe+Ke*Je)*yt,i[7]=(je*Ze-W*et-Ke*Ye)*yt,i[8]=(W*Qe-be*Ze+Ke*Xe)*yt,i):null},projection:function(i,g,x){return i[0]=2/g,i[1]=0,i[2]=0,i[3]=0,i[4]=-2/x,i[5]=0,i[6]=-1,i[7]=1,i[8]=1,i},rotate:function(i,g,x){var v=g[0],_=g[1],y=g[2],b=g[3],S=g[4],w=g[5],L=g[6],k=g[7],H=g[8],z=Math.sin(x),q=Math.cos(x);return i[0]=q*v+z*b,i[1]=q*_+z*S,i[2]=q*y+z*w,i[3]=q*b-z*v,i[4]=q*S-z*_,i[5]=q*w-z*y,i[6]=L,i[7]=k,i[8]=H,i},scale:function(i,g,x){var v=x[0],_=x[1];return i[0]=v*g[0],i[1]=v*g[1],i[2]=v*g[2],i[3]=_*g[3],i[4]=_*g[4],i[5]=_*g[5],i[6]=g[6],i[7]=g[7],i[8]=g[8],i},set:function(i,g,x,v,_,y,b,S,w,L){return i[0]=g,i[1]=x,i[2]=v,i[3]=_,i[4]=y,i[5]=b,i[6]=S,i[7]=w,i[8]=L,i},str:function(i){return"mat3("+i[0]+", "+i[1]+", "+i[2]+", "+i[3]+", "+i[4]+", "+i[5]+", "+i[6]+", "+i[7]+", "+i[8]+")"},sub:Rt,subtract:subtract$4,translate:function(i,g,x){var v=g[0],_=g[1],y=g[2],b=g[3],S=g[4],w=g[5],L=g[6],k=g[7],H=g[8],z=x[0],q=x[1];return i[0]=v,i[1]=_,i[2]=y,i[3]=b,i[4]=S,i[5]=w,i[6]=z*v+q*b+L,i[7]=z*_+q*S+k,i[8]=z*y+q*w+H,i},transpose:function(i,g){if(i===g){var x=g[1],v=g[2],_=g[5];i[1]=g[3],i[2]=g[6],i[3]=x,i[5]=g[7],i[6]=v,i[7]=_}else i[0]=g[0],i[1]=g[3],i[2]=g[6],i[3]=g[1],i[4]=g[4],i[5]=g[7],i[6]=g[2],i[7]=g[5],i[8]=g[8];return i}});function create$4(){var i=new wt(16);return wt!=Float32Array&&(i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[11]=0,i[12]=0,i[13]=0,i[14]=0),i[0]=1,i[5]=1,i[10]=1,i[15]=1,i}function clone$4(i){var g=new wt(16);return g[0]=i[0],g[1]=i[1],g[2]=i[2],g[3]=i[3],g[4]=i[4],g[5]=i[5],g[6]=i[6],g[7]=i[7],g[8]=i[8],g[9]=i[9],g[10]=i[10],g[11]=i[11],g[12]=i[12],g[13]=i[13],g[14]=i[14],g[15]=i[15],g}function copy$4(i,g){return i[0]=g[0],i[1]=g[1],i[2]=g[2],i[3]=g[3],i[4]=g[4],i[5]=g[5],i[6]=g[6],i[7]=g[7],i[8]=g[8],i[9]=g[9],i[10]=g[10],i[11]=g[11],i[12]=g[12],i[13]=g[13],i[14]=g[14],i[15]=g[15],i}function fromValues$4(i,g,x,v,_,y,b,S,w,L,k,H,z,q,W,be){var je=new wt(16);return je[0]=i,je[1]=g,je[2]=x,je[3]=v,je[4]=_,je[5]=y,je[6]=b,je[7]=S,je[8]=w,je[9]=L,je[10]=k,je[11]=H,je[12]=z,je[13]=q,je[14]=W,je[15]=be,je}function identity$1(i){return i[0]=1,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=1,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[10]=1,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,i}function transpose(i,g){if(i===g){var x=g[1],v=g[2],_=g[3],y=g[6],b=g[7],S=g[11];i[1]=g[4],i[2]=g[8],i[3]=g[12],i[4]=x,i[6]=g[9],i[7]=g[13],i[8]=v,i[9]=y,i[11]=g[14],i[12]=_,i[13]=b,i[14]=S}else i[0]=g[0],i[1]=g[4],i[2]=g[8],i[3]=g[12],i[4]=g[1],i[5]=g[5],i[6]=g[9],i[7]=g[13],i[8]=g[2],i[9]=g[6],i[10]=g[10],i[11]=g[14],i[12]=g[3],i[13]=g[7],i[14]=g[11],i[15]=g[15];return i}function invert$1(i,g){var x=g[0],v=g[1],_=g[2],y=g[3],b=g[4],S=g[5],w=g[6],L=g[7],k=g[8],H=g[9],z=g[10],q=g[11],W=g[12],be=g[13],je=g[14],Ke=g[15],Xe=x*S-v*b,Ye=x*w-_*b,Ze=x*L-y*b,Je=v*w-_*S,Qe=v*L-y*S,et=_*L-y*w,tt=k*be-H*W,it=k*je-z*W,ft=k*Ke-q*W,pt=H*je-z*be,xt=H*Ke-q*be,vt=z*Ke-q*je,yt=Xe*vt-Ye*xt+Ze*pt+Je*ft-Qe*it+et*tt;return yt?(yt=1/yt,i[0]=(S*vt-w*xt+L*pt)*yt,i[1]=(_*xt-v*vt-y*pt)*yt,i[2]=(be*et-je*Qe+Ke*Je)*yt,i[3]=(z*Qe-H*et-q*Je)*yt,i[4]=(w*ft-b*vt-L*it)*yt,i[5]=(x*vt-_*ft+y*it)*yt,i[6]=(je*Ze-W*et-Ke*Ye)*yt,i[7]=(k*et-z*Ze+q*Ye)*yt,i[8]=(b*xt-S*ft+L*tt)*yt,i[9]=(v*ft-x*xt-y*tt)*yt,i[10]=(W*Qe-be*Ze+Ke*Xe)*yt,i[11]=(H*Ze-k*Qe-q*Xe)*yt,i[12]=(S*it-b*pt-w*tt)*yt,i[13]=(x*pt-v*it+_*tt)*yt,i[14]=(be*Ye-W*Je-je*Xe)*yt,i[15]=(k*Je-H*Ye+z*Xe)*yt,i):null}function multiply$4(i,g,x){var v=g[0],_=g[1],y=g[2],b=g[3],S=g[4],w=g[5],L=g[6],k=g[7],H=g[8],z=g[9],q=g[10],W=g[11],be=g[12],je=g[13],Ke=g[14],Xe=g[15],Ye=x[0],Ze=x[1],Je=x[2],Qe=x[3];return i[0]=Ye*v+Ze*S+Je*H+Qe*be,i[1]=Ye*_+Ze*w+Je*z+Qe*je,i[2]=Ye*y+Ze*L+Je*q+Qe*Ke,i[3]=Ye*b+Ze*k+Je*W+Qe*Xe,Ye=x[4],Ze=x[5],Je=x[6],Qe=x[7],i[4]=Ye*v+Ze*S+Je*H+Qe*be,i[5]=Ye*_+Ze*w+Je*z+Qe*je,i[6]=Ye*y+Ze*L+Je*q+Qe*Ke,i[7]=Ye*b+Ze*k+Je*W+Qe*Xe,Ye=x[8],Ze=x[9],Je=x[10],Qe=x[11],i[8]=Ye*v+Ze*S+Je*H+Qe*be,i[9]=Ye*_+Ze*w+Je*z+Qe*je,i[10]=Ye*y+Ze*L+Je*q+Qe*Ke,i[11]=Ye*b+Ze*k+Je*W+Qe*Xe,Ye=x[12],Ze=x[13],Je=x[14],Qe=x[15],i[12]=Ye*v+Ze*S+Je*H+Qe*be,i[13]=Ye*_+Ze*w+Je*z+Qe*je,i[14]=Ye*y+Ze*L+Je*q+Qe*Ke,i[15]=Ye*b+Ze*k+Je*W+Qe*Xe,i}function translate(i,g,x){var v,_,y,b,S,w,L,k,H,z,q,W,be=x[0],je=x[1],Ke=x[2];return g===i?(i[12]=g[0]*be+g[4]*je+g[8]*Ke+g[12],i[13]=g[1]*be+g[5]*je+g[9]*Ke+g[13],i[14]=g[2]*be+g[6]*je+g[10]*Ke+g[14],i[15]=g[3]*be+g[7]*je+g[11]*Ke+g[15]):(v=g[0],_=g[1],y=g[2],b=g[3],S=g[4],w=g[5],L=g[6],k=g[7],H=g[8],z=g[9],q=g[10],W=g[11],i[0]=v,i[1]=_,i[2]=y,i[3]=b,i[4]=S,i[5]=w,i[6]=L,i[7]=k,i[8]=H,i[9]=z,i[10]=q,i[11]=W,i[12]=v*be+S*je+H*Ke+g[12],i[13]=_*be+w*je+z*Ke+g[13],i[14]=y*be+L*je+q*Ke+g[14],i[15]=b*be+k*je+W*Ke+g[15]),i}function scale$4(i,g,x){var v=x[0],_=x[1],y=x[2];return i[0]=g[0]*v,i[1]=g[1]*v,i[2]=g[2]*v,i[3]=g[3]*v,i[4]=g[4]*_,i[5]=g[5]*_,i[6]=g[6]*_,i[7]=g[7]*_,i[8]=g[8]*y,i[9]=g[9]*y,i[10]=g[10]*y,i[11]=g[11]*y,i[12]=g[12],i[13]=g[13],i[14]=g[14],i[15]=g[15],i}function rotateX$2(i,g,x){var v=Math.sin(x),_=Math.cos(x),y=g[4],b=g[5],S=g[6],w=g[7],L=g[8],k=g[9],H=g[10],z=g[11];return g!==i&&(i[0]=g[0],i[1]=g[1],i[2]=g[2],i[3]=g[3],i[12]=g[12],i[13]=g[13],i[14]=g[14],i[15]=g[15]),i[4]=y*_+L*v,i[5]=b*_+k*v,i[6]=S*_+H*v,i[7]=w*_+z*v,i[8]=L*_-y*v,i[9]=k*_-b*v,i[10]=H*_-S*v,i[11]=z*_-w*v,i}function rotateY$2(i,g,x){var v=Math.sin(x),_=Math.cos(x),y=g[0],b=g[1],S=g[2],w=g[3],L=g[8],k=g[9],H=g[10],z=g[11];return g!==i&&(i[4]=g[4],i[5]=g[5],i[6]=g[6],i[7]=g[7],i[12]=g[12],i[13]=g[13],i[14]=g[14],i[15]=g[15]),i[0]=y*_-L*v,i[1]=b*_-k*v,i[2]=S*_-H*v,i[3]=w*_-z*v,i[8]=y*v+L*_,i[9]=b*v+k*_,i[10]=S*v+H*_,i[11]=w*v+z*_,i}function rotateZ$2(i,g,x){var v=Math.sin(x),_=Math.cos(x),y=g[0],b=g[1],S=g[2],w=g[3],L=g[4],k=g[5],H=g[6],z=g[7];return g!==i&&(i[8]=g[8],i[9]=g[9],i[10]=g[10],i[11]=g[11],i[12]=g[12],i[13]=g[13],i[14]=g[14],i[15]=g[15]),i[0]=y*_+L*v,i[1]=b*_+k*v,i[2]=S*_+H*v,i[3]=w*_+z*v,i[4]=L*_-y*v,i[5]=k*_-b*v,i[6]=H*_-S*v,i[7]=z*_-w*v,i}function fromRotationTranslation(i,g,x){var v=g[0],_=g[1],y=g[2],b=g[3],S=v+v,w=_+_,L=y+y,k=v*S,H=v*w,z=v*L,q=_*w,W=_*L,be=y*L,je=b*S,Ke=b*w,Xe=b*L;return i[0]=1-(q+be),i[1]=H+Xe,i[2]=z-Ke,i[3]=0,i[4]=H-Xe,i[5]=1-(k+be),i[6]=W+je,i[7]=0,i[8]=z+Ke,i[9]=W-je,i[10]=1-(k+q),i[11]=0,i[12]=x[0],i[13]=x[1],i[14]=x[2],i[15]=1,i}function getScaling(i,g){var x=g[0],v=g[1],_=g[2],y=g[4],b=g[5],S=g[6],w=g[8],L=g[9],k=g[10];return i[0]=Math.sqrt(x*x+v*v+_*_),i[1]=Math.sqrt(y*y+b*b+S*S),i[2]=Math.sqrt(w*w+L*L+k*k),i}function perspectiveNO(i,g,x,v,_){var y=1/Math.tan(g/2);if(i[0]=y/x,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=y,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[11]=-1,i[12]=0,i[13]=0,i[15]=0,null!=_&&_!==1/0){var b=1/(v-_);i[10]=(_+v)*b,i[14]=2*_*v*b}else i[10]=-1,i[14]=-2*v;return i}var Bt=perspectiveNO;function orthoNO(i,g,x,v,_,y,b){var S=1/(g-x),w=1/(v-_),L=1/(y-b);return i[0]=-2*S,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=-2*w,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[10]=2*L,i[11]=0,i[12]=(g+x)*S,i[13]=(_+v)*w,i[14]=(b+y)*L,i[15]=1,i}var Dt=orthoNO;function orthoZO(i,g,x,v,_,y,b){var S=1/(g-x),w=1/(v-_),L=1/(y-b);return i[0]=-2*S,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=-2*w,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[10]=L,i[11]=0,i[12]=(g+x)*S,i[13]=(_+v)*w,i[14]=y*L,i[15]=1,i}function lookAt(i,g,x,v){var _,y,b,S,w,L,k,H,z,q,W=g[0],be=g[1],je=g[2],Ke=v[0],Xe=v[1],Ye=v[2],Ze=x[0],Je=x[1],Qe=x[2];return Math.abs(W-Ze)0&&(k*=q=1/Math.sqrt(q),H*=q,z*=q);var W=w*z-L*H,be=L*k-S*z,je=S*H-w*k;return(q=W*W+be*be+je*je)>0&&(W*=q=1/Math.sqrt(q),be*=q,je*=q),i[0]=W,i[1]=be,i[2]=je,i[3]=0,i[4]=H*je-z*be,i[5]=z*W-k*je,i[6]=k*be-H*W,i[7]=0,i[8]=k,i[9]=H,i[10]=z,i[11]=0,i[12]=_,i[13]=y,i[14]=b,i[15]=1,i}function subtract$3(i,g,x){return i[0]=g[0]-x[0],i[1]=g[1]-x[1],i[2]=g[2]-x[2],i[3]=g[3]-x[3],i[4]=g[4]-x[4],i[5]=g[5]-x[5],i[6]=g[6]-x[6],i[7]=g[7]-x[7],i[8]=g[8]-x[8],i[9]=g[9]-x[9],i[10]=g[10]-x[10],i[11]=g[11]-x[11],i[12]=g[12]-x[12],i[13]=g[13]-x[13],i[14]=g[14]-x[14],i[15]=g[15]-x[15],i}var Et=multiply$4,It=subtract$3,At=Object.freeze({__proto__:null,add:function(i,g,x){return i[0]=g[0]+x[0],i[1]=g[1]+x[1],i[2]=g[2]+x[2],i[3]=g[3]+x[3],i[4]=g[4]+x[4],i[5]=g[5]+x[5],i[6]=g[6]+x[6],i[7]=g[7]+x[7],i[8]=g[8]+x[8],i[9]=g[9]+x[9],i[10]=g[10]+x[10],i[11]=g[11]+x[11],i[12]=g[12]+x[12],i[13]=g[13]+x[13],i[14]=g[14]+x[14],i[15]=g[15]+x[15],i},adjoint:function(i,g){var x=g[0],v=g[1],_=g[2],y=g[3],b=g[4],S=g[5],w=g[6],L=g[7],k=g[8],H=g[9],z=g[10],q=g[11],W=g[12],be=g[13],je=g[14],Ke=g[15],Xe=x*S-v*b,Ye=x*w-_*b,Ze=x*L-y*b,Je=v*w-_*S,Qe=v*L-y*S,et=_*L-y*w,tt=k*be-H*W,it=k*je-z*W,ft=k*Ke-q*W,pt=H*je-z*be,xt=H*Ke-q*be,vt=z*Ke-q*je;return i[0]=S*vt-w*xt+L*pt,i[1]=_*xt-v*vt-y*pt,i[2]=be*et-je*Qe+Ke*Je,i[3]=z*Qe-H*et-q*Je,i[4]=w*ft-b*vt-L*it,i[5]=x*vt-_*ft+y*it,i[6]=je*Ze-W*et-Ke*Ye,i[7]=k*et-z*Ze+q*Ye,i[8]=b*xt-S*ft+L*tt,i[9]=v*ft-x*xt-y*tt,i[10]=W*Qe-be*Ze+Ke*Xe,i[11]=H*Ze-k*Qe-q*Xe,i[12]=S*it-b*pt-w*tt,i[13]=x*pt-v*it+_*tt,i[14]=be*Ye-W*Je-je*Xe,i[15]=k*Je-H*Ye+z*Xe,i},clone:clone$4,copy:copy$4,create:create$4,decompose:function(i,g,x,v){g[0]=v[12],g[1]=v[13],g[2]=v[14];var _=v[0],y=v[1],b=v[2],S=v[4],w=v[5],L=v[6],k=v[8],H=v[9],z=v[10];x[0]=Math.sqrt(_*_+y*y+b*b),x[1]=Math.sqrt(S*S+w*w+L*L),x[2]=Math.sqrt(k*k+H*H+z*z);var q=1/x[0],W=1/x[1],be=1/x[2],je=_*q,Ke=y*W,Xe=b*be,Ye=S*q,Ze=w*W,Je=L*be,Qe=k*q,et=H*W,tt=z*be,it=je+Ze+tt,ft=0;return it>0?(ft=2*Math.sqrt(it+1),i[3]=.25*ft,i[0]=(Je-et)/ft,i[1]=(Qe-Xe)/ft,i[2]=(Ke-Ye)/ft):je>Ze&&je>tt?(ft=2*Math.sqrt(1+je-Ze-tt),i[3]=(Je-et)/ft,i[0]=.25*ft,i[1]=(Ke+Ye)/ft,i[2]=(Qe+Xe)/ft):Ze>tt?(ft=2*Math.sqrt(1+Ze-je-tt),i[3]=(Qe-Xe)/ft,i[0]=(Ke+Ye)/ft,i[1]=.25*ft,i[2]=(Je+et)/ft):(ft=2*Math.sqrt(1+tt-je-Ze),i[3]=(Ke-Ye)/ft,i[0]=(Qe+Xe)/ft,i[1]=(Je+et)/ft,i[2]=.25*ft),i},determinant:function(i){var g=i[0],x=i[1],v=i[2],_=i[3],y=i[4],b=i[5],S=i[6],w=i[7],L=i[8],k=i[9],H=i[10],z=i[11],q=i[12],W=i[13],be=i[14],je=g*b-x*y,Ke=g*S-v*y,Xe=x*S-v*b,Ye=L*W-k*q,Ze=L*be-H*q,Je=k*be-H*W;return w*(g*Je-x*Ze+v*Ye)-_*(y*Je-b*Ze+S*Ye)+i[15]*(L*Xe-k*Ke+H*je)-z*(q*Xe-W*Ke+be*je)},equals:function(i,g){var x=i[0],v=i[1],_=i[2],y=i[3],b=i[4],S=i[5],w=i[6],L=i[7],k=i[8],H=i[9],z=i[10],q=i[11],W=i[12],be=i[13],je=i[14],Ke=i[15],Xe=g[0],Ye=g[1],Ze=g[2],Je=g[3],Qe=g[4],et=g[5],tt=g[6],it=g[7],ft=g[8],pt=g[9],xt=g[10],vt=g[11],yt=g[12],bt=g[13],St=g[14],wt=g[15];return Math.abs(x-Xe)<=Tt*Math.max(1,Math.abs(x),Math.abs(Xe))&&Math.abs(v-Ye)<=Tt*Math.max(1,Math.abs(v),Math.abs(Ye))&&Math.abs(_-Ze)<=Tt*Math.max(1,Math.abs(_),Math.abs(Ze))&&Math.abs(y-Je)<=Tt*Math.max(1,Math.abs(y),Math.abs(Je))&&Math.abs(b-Qe)<=Tt*Math.max(1,Math.abs(b),Math.abs(Qe))&&Math.abs(S-et)<=Tt*Math.max(1,Math.abs(S),Math.abs(et))&&Math.abs(w-tt)<=Tt*Math.max(1,Math.abs(w),Math.abs(tt))&&Math.abs(L-it)<=Tt*Math.max(1,Math.abs(L),Math.abs(it))&&Math.abs(k-ft)<=Tt*Math.max(1,Math.abs(k),Math.abs(ft))&&Math.abs(H-pt)<=Tt*Math.max(1,Math.abs(H),Math.abs(pt))&&Math.abs(z-xt)<=Tt*Math.max(1,Math.abs(z),Math.abs(xt))&&Math.abs(q-vt)<=Tt*Math.max(1,Math.abs(q),Math.abs(vt))&&Math.abs(W-yt)<=Tt*Math.max(1,Math.abs(W),Math.abs(yt))&&Math.abs(be-bt)<=Tt*Math.max(1,Math.abs(be),Math.abs(bt))&&Math.abs(je-St)<=Tt*Math.max(1,Math.abs(je),Math.abs(St))&&Math.abs(Ke-wt)<=Tt*Math.max(1,Math.abs(Ke),Math.abs(wt))},exactEquals:function(i,g){return i[0]===g[0]&&i[1]===g[1]&&i[2]===g[2]&&i[3]===g[3]&&i[4]===g[4]&&i[5]===g[5]&&i[6]===g[6]&&i[7]===g[7]&&i[8]===g[8]&&i[9]===g[9]&&i[10]===g[10]&&i[11]===g[11]&&i[12]===g[12]&&i[13]===g[13]&&i[14]===g[14]&&i[15]===g[15]},frob:function(i){return Math.sqrt(i[0]*i[0]+i[1]*i[1]+i[2]*i[2]+i[3]*i[3]+i[4]*i[4]+i[5]*i[5]+i[6]*i[6]+i[7]*i[7]+i[8]*i[8]+i[9]*i[9]+i[10]*i[10]+i[11]*i[11]+i[12]*i[12]+i[13]*i[13]+i[14]*i[14]+i[15]*i[15])},fromQuat:function(i,g){var x=g[0],v=g[1],_=g[2],y=g[3],b=x+x,S=v+v,w=_+_,L=x*b,k=v*b,H=v*S,z=_*b,q=_*S,W=_*w,be=y*b,je=y*S,Ke=y*w;return i[0]=1-H-W,i[1]=k+Ke,i[2]=z-je,i[3]=0,i[4]=k-Ke,i[5]=1-L-W,i[6]=q+be,i[7]=0,i[8]=z+je,i[9]=q-be,i[10]=1-L-H,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,i},fromQuat2:function(i,g){var x=new wt(3),v=-g[0],_=-g[1],y=-g[2],b=g[3],S=g[4],w=g[5],L=g[6],k=g[7],H=v*v+_*_+y*y+b*b;return H>0?(x[0]=2*(S*b+k*v+w*y-L*_)/H,x[1]=2*(w*b+k*_+L*v-S*y)/H,x[2]=2*(L*b+k*y+S*_-w*v)/H):(x[0]=2*(S*b+k*v+w*y-L*_),x[1]=2*(w*b+k*_+L*v-S*y),x[2]=2*(L*b+k*y+S*_-w*v)),fromRotationTranslation(i,g,x),i},fromRotation:function(i,g,x){var v,_,y,b=x[0],S=x[1],w=x[2],L=Math.sqrt(b*b+S*S+w*w);return L0?(je=2*Math.sqrt(be+1),i[3]=.25*je,i[0]=(H-q)/je,i[1]=(z-w)/je,i[2]=(S-L)/je):b>k&&b>W?(je=2*Math.sqrt(1+b-k-W),i[3]=(H-q)/je,i[0]=.25*je,i[1]=(S+L)/je,i[2]=(z+w)/je):k>W?(je=2*Math.sqrt(1+k-b-W),i[3]=(z-w)/je,i[0]=(S+L)/je,i[1]=.25*je,i[2]=(H+q)/je):(je=2*Math.sqrt(1+W-b-k),i[3]=(S-L)/je,i[0]=(z+w)/je,i[1]=(H+q)/je,i[2]=.25*je),i},getScaling:getScaling,getTranslation:function(i,g){return i[0]=g[12],i[1]=g[13],i[2]=g[14],i},identity:identity$1,invert:invert$1,lookAt:lookAt,mul:Et,multiply:multiply$4,multiplyScalar:function(i,g,x){return i[0]=g[0]*x,i[1]=g[1]*x,i[2]=g[2]*x,i[3]=g[3]*x,i[4]=g[4]*x,i[5]=g[5]*x,i[6]=g[6]*x,i[7]=g[7]*x,i[8]=g[8]*x,i[9]=g[9]*x,i[10]=g[10]*x,i[11]=g[11]*x,i[12]=g[12]*x,i[13]=g[13]*x,i[14]=g[14]*x,i[15]=g[15]*x,i},multiplyScalarAndAdd:function(i,g,x,v){return i[0]=g[0]+x[0]*v,i[1]=g[1]+x[1]*v,i[2]=g[2]+x[2]*v,i[3]=g[3]+x[3]*v,i[4]=g[4]+x[4]*v,i[5]=g[5]+x[5]*v,i[6]=g[6]+x[6]*v,i[7]=g[7]+x[7]*v,i[8]=g[8]+x[8]*v,i[9]=g[9]+x[9]*v,i[10]=g[10]+x[10]*v,i[11]=g[11]+x[11]*v,i[12]=g[12]+x[12]*v,i[13]=g[13]+x[13]*v,i[14]=g[14]+x[14]*v,i[15]=g[15]+x[15]*v,i},ortho:Dt,orthoNO:orthoNO,orthoZO:orthoZO,perspective:Bt,perspectiveFromFieldOfView:function(i,g,x,v){var _=Math.tan(g.upDegrees*Math.PI/180),y=Math.tan(g.downDegrees*Math.PI/180),b=Math.tan(g.leftDegrees*Math.PI/180),S=Math.tan(g.rightDegrees*Math.PI/180),w=2/(b+S),L=2/(_+y);return i[0]=w,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=L,i[6]=0,i[7]=0,i[8]=-(b-S)*w*.5,i[9]=(_-y)*L*.5,i[10]=v/(x-v),i[11]=-1,i[12]=0,i[13]=0,i[14]=v*x/(x-v),i[15]=0,i},perspectiveNO:perspectiveNO,perspectiveZO:function(i,g,x,v,_){var y=1/Math.tan(g/2);if(i[0]=y/x,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=y,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[11]=-1,i[12]=0,i[13]=0,i[15]=0,null!=_&&_!==1/0){var b=1/(v-_);i[10]=_*b,i[14]=_*v*b}else i[10]=-1,i[14]=-v;return i},rotate:function(i,g,x,v){var _,y,b,S,w,L,k,H,z,q,W,be,je,Ke,Xe,Ye,Ze,Je,Qe,et,tt,it,ft,pt,xt=v[0],vt=v[1],yt=v[2],bt=Math.sqrt(xt*xt+vt*vt+yt*yt);return bt0&&(y=1/Math.sqrt(y)),i[0]=g[0]*y,i[1]=g[1]*y,i[2]=g[2]*y,i}function dot$3(i,g){return i[0]*g[0]+i[1]*g[1]+i[2]*g[2]}function cross$2(i,g,x){var v=g[0],_=g[1],y=g[2],b=x[0],S=x[1],w=x[2];return i[0]=_*w-y*S,i[1]=y*b-v*w,i[2]=v*S-_*b,i}function lerp$3(i,g,x,v){var _=g[0],y=g[1],b=g[2];return i[0]=_+v*(x[0]-_),i[1]=y+v*(x[1]-y),i[2]=b+v*(x[2]-b),i}function transformMat4$2(i,g,x){var v=g[0],_=g[1],y=g[2],b=x[3]*v+x[7]*_+x[11]*y+x[15];return b=b||1,i[0]=(x[0]*v+x[4]*_+x[8]*y+x[12])/b,i[1]=(x[1]*v+x[5]*_+x[9]*y+x[13])/b,i[2]=(x[2]*v+x[6]*_+x[10]*y+x[14])/b,i}var Lt,Ut=subtract$2,kt=multiply$3,Gt=divide$2,Ot=distance$2,Vt=squaredDistance$2,Nt=length$3,Ft=squaredLength$3,Ht=(Lt=create$3(),function(i,g,x,v,_,y){var b,S;for(g||(g=3),x||(x=0),S=v?Math.min(v*g+x,i.length):i.length,b=x;b0&&(b=1/Math.sqrt(b)),i[0]=x*b,i[1]=v*b,i[2]=_*b,i[3]=y*b,i}function dot$2(i,g){return i[0]*g[0]+i[1]*g[1]+i[2]*g[2]+i[3]*g[3]}function lerp$2(i,g,x,v){var _=g[0],y=g[1],b=g[2],S=g[3];return i[0]=_+v*(x[0]-_),i[1]=y+v*(x[1]-y),i[2]=b+v*(x[2]-b),i[3]=S+v*(x[3]-S),i}function transformMat4$1(i,g,x){var v=g[0],_=g[1],y=g[2],b=g[3];return i[0]=x[0]*v+x[4]*_+x[8]*y+x[12]*b,i[1]=x[1]*v+x[5]*_+x[9]*y+x[13]*b,i[2]=x[2]*v+x[6]*_+x[10]*y+x[14]*b,i[3]=x[3]*v+x[7]*_+x[11]*y+x[15]*b,i}function exactEquals$2(i,g){return i[0]===g[0]&&i[1]===g[1]&&i[2]===g[2]&&i[3]===g[3]}var $t=subtract$1,jt=multiply$2,Kt=divide$1,Xt=distance$1,qt=squaredDistance$1,Yt=length$2,Wt=squaredLength$2,Zt=function(){var i=create$2();return function(g,x,v,_,y,b){var S,w;for(x||(x=4),v||(v=0),w=_?Math.min(_*x+v,g.length):g.length,S=v;S0?S*Math.sin(b)/b:0;return i[0]=x*w,i[1]=v*w,i[2]=_*w,i[3]=S*Math.cos(b),i}function ln(i,g){var x=g[0],v=g[1],_=g[2],y=g[3],b=Math.sqrt(x*x+v*v+_*_),S=b>0?Math.atan2(b,y)/b:0;return i[0]=x*S,i[1]=v*S,i[2]=_*S,i[3]=.5*Math.log(x*x+v*v+_*_+y*y),i}function slerp(i,g,x,v){var _,y,b,S,w,L=g[0],k=g[1],H=g[2],z=g[3],q=x[0],W=x[1],be=x[2],je=x[3];return(y=L*q+k*W+H*be+z*je)<0&&(y=-y,q=-q,W=-W,be=-be,je=-je),1-y>Tt?(_=Math.acos(y),b=Math.sin(_),S=Math.sin((1-v)*_)/b,w=Math.sin(v*_)/b):(S=1-v,w=v),i[0]=S*L+w*q,i[1]=S*k+w*W,i[2]=S*H+w*be,i[3]=S*z+w*je,i}function fromMat3(i,g){var x,v=g[0]+g[4]+g[8];if(v>0)x=Math.sqrt(v+1),i[3]=.5*x,x=.5/x,i[0]=(g[5]-g[7])*x,i[1]=(g[6]-g[2])*x,i[2]=(g[1]-g[3])*x;else{var _=0;g[4]>g[0]&&(_=1),g[8]>g[3*_+_]&&(_=2);var y=(_+1)%3,b=(_+2)%3;x=Math.sqrt(g[3*_+_]-g[3*y+y]-g[3*b+b]+1),i[_]=.5*x,x=.5/x,i[3]=(g[3*y+b]-g[3*b+y])*x,i[y]=(g[3*y+_]+g[3*_+y])*x,i[b]=(g[3*b+_]+g[3*_+b])*x}return i}var Qt=clone$2,er=fromValues$2,tr=copy$2,rr=set$2,ir=add$2,nr=multiply$1,ar=scale$2,sr=dot$2,or=lerp$2,ur=length$2,lr=ur,cr=squaredLength$2,hr=cr,fr=normalize$2,dr=exactEquals$2;var mr,pr,gr,xr,vr=(mr=create$3(),pr=fromValues$3(1,0,0),gr=fromValues$3(0,1,0),function(i,g,x){var v=dot$3(g,x);return v<-.999999?(cross$2(mr,pr,g),Nt(mr)<1e-6&&cross$2(mr,gr,g),normalize$3(mr,mr),setAxisAngle(i,mr,Math.PI),i):v>.999999?(i[0]=0,i[1]=0,i[2]=0,i[3]=1,i):(cross$2(mr,g,x),i[0]=mr[0],i[1]=mr[1],i[2]=mr[2],i[3]=1+v,fr(i,i))}),_r=function(){var i=create$1(),g=create$1();return function(x,v,_,y,b,S){return slerp(i,v,b,S),slerp(g,_,y,S),slerp(x,i,g,2*S*(1-S)),x}}(),yr=(xr=create$5(),function(i,g,x,v){return xr[0]=x[0],xr[3]=x[1],xr[6]=x[2],xr[1]=v[0],xr[4]=v[1],xr[7]=v[2],xr[2]=-g[0],xr[5]=-g[1],xr[8]=-g[2],fr(i,fromMat3(i,xr))}),br=Object.freeze({__proto__:null,add:ir,calculateW:function(i,g){var x=g[0],v=g[1],_=g[2];return i[0]=x,i[1]=v,i[2]=_,i[3]=Math.sqrt(Math.abs(1-x*x-v*v-_*_)),i},clone:Qt,conjugate:function(i,g){return i[0]=-g[0],i[1]=-g[1],i[2]=-g[2],i[3]=g[3],i},copy:tr,create:create$1,dot:sr,equals:function(i,g){return Math.abs(dot$2(i,g))>=.999999},exactEquals:dr,exp:exp,fromEuler:function(i,g,x,v){var _=arguments.length>4&&void 0!==arguments[4]?arguments[4]:"zyx",y=Math.PI/360;g*=y,v*=y,x*=y;var b=Math.sin(g),S=Math.cos(g),w=Math.sin(x),L=Math.cos(x),k=Math.sin(v),H=Math.cos(v);switch(_){case"xyz":i[0]=b*L*H+S*w*k,i[1]=S*w*H-b*L*k,i[2]=S*L*k+b*w*H,i[3]=S*L*H-b*w*k;break;case"xzy":i[0]=b*L*H-S*w*k,i[1]=S*w*H-b*L*k,i[2]=S*L*k+b*w*H,i[3]=S*L*H+b*w*k;break;case"yxz":i[0]=b*L*H+S*w*k,i[1]=S*w*H-b*L*k,i[2]=S*L*k-b*w*H,i[3]=S*L*H+b*w*k;break;case"yzx":i[0]=b*L*H+S*w*k,i[1]=S*w*H+b*L*k,i[2]=S*L*k-b*w*H,i[3]=S*L*H-b*w*k;break;case"zxy":i[0]=b*L*H-S*w*k,i[1]=S*w*H+b*L*k,i[2]=S*L*k+b*w*H,i[3]=S*L*H-b*w*k;break;case"zyx":i[0]=b*L*H-S*w*k,i[1]=S*w*H+b*L*k,i[2]=S*L*k-b*w*H,i[3]=S*L*H+b*w*k;break;default:throw new Error("Unknown angle order "+_)}return i},fromMat3:fromMat3,fromValues:er,getAngle:function(i,g){var x=sr(i,g);return Math.acos(2*x*x-1)},getAxisAngle:function(i,g){var x=2*Math.acos(g[3]),v=Math.sin(x/2);return v>Tt?(i[0]=g[0]/v,i[1]=g[1]/v,i[2]=g[2]/v):(i[0]=1,i[1]=0,i[2]=0),x},identity:function(i){return i[0]=0,i[1]=0,i[2]=0,i[3]=1,i},invert:function(i,g){var x=g[0],v=g[1],_=g[2],y=g[3],b=x*x+v*v+_*_+y*y,S=b?1/b:0;return i[0]=-x*S,i[1]=-v*S,i[2]=-_*S,i[3]=y*S,i},len:lr,length:ur,lerp:or,ln:ln,mul:nr,multiply:multiply$1,normalize:fr,pow:function(i,g,x){return ln(i,g),ar(i,i,x),exp(i,i),i},random:function(i){var g=Mt(),x=Mt(),v=Mt(),_=Math.sqrt(1-g),y=Math.sqrt(g);return i[0]=_*Math.sin(2*Math.PI*x),i[1]=_*Math.cos(2*Math.PI*x),i[2]=y*Math.sin(2*Math.PI*v),i[3]=y*Math.cos(2*Math.PI*v),i},rotateX:function(i,g,x){x*=.5;var v=g[0],_=g[1],y=g[2],b=g[3],S=Math.sin(x),w=Math.cos(x);return i[0]=v*w+b*S,i[1]=_*w+y*S,i[2]=y*w-_*S,i[3]=b*w-v*S,i},rotateY:function(i,g,x){x*=.5;var v=g[0],_=g[1],y=g[2],b=g[3],S=Math.sin(x),w=Math.cos(x);return i[0]=v*w-y*S,i[1]=_*w+b*S,i[2]=y*w+v*S,i[3]=b*w-_*S,i},rotateZ:function(i,g,x){x*=.5;var v=g[0],_=g[1],y=g[2],b=g[3],S=Math.sin(x),w=Math.cos(x);return i[0]=v*w+_*S,i[1]=_*w-v*S,i[2]=y*w+b*S,i[3]=b*w-y*S,i},rotationTo:vr,scale:ar,set:rr,setAxes:yr,setAxisAngle:setAxisAngle,slerp:slerp,sqlerp:_r,sqrLen:hr,squaredLength:cr,str:function(i){return"quat("+i[0]+", "+i[1]+", "+i[2]+", "+i[3]+")"}});function create(){var i=new wt(2);return wt!=Float32Array&&(i[0]=0,i[1]=0),i}function fromValues(i,g){var x=new wt(2);return x[0]=i,x[1]=g,x}function set(i,g,x){return i[0]=g,i[1]=x,i}function subtract(i,g,x){return i[0]=g[0]-x[0],i[1]=g[1]-x[1],i}function multiply(i,g,x){return i[0]=g[0]*x[0],i[1]=g[1]*x[1],i}function divide(i,g,x){return i[0]=g[0]/x[0],i[1]=g[1]/x[1],i}function scaleAndAdd(i,g,x,v){return i[0]=g[0]+x[0]*v,i[1]=g[1]+x[1]*v,i}function distance(i,g){var x=g[0]-i[0],v=g[1]-i[1];return Math.sqrt(x*x+v*v)}function squaredDistance(i,g){var x=g[0]-i[0],v=g[1]-i[1];return x*x+v*v}function length(i){var g=i[0],x=i[1];return Math.sqrt(g*g+x*x)}function squaredLength(i){var g=i[0],x=i[1];return g*g+x*x}function lerp(i,g,x,v){var _=g[0],y=g[1];return i[0]=_+v*(x[0]-_),i[1]=y+v*(x[1]-y),i}var Sr=length,Tr=subtract,wr=multiply,Mr=divide,Pr=distance,Rr=squaredDistance,Cr=squaredLength,Br=function(){var i=create();return function(g,x,v,_,y,b){var S,w;for(x||(x=2),v||(v=0),w=_?Math.min(_*x+v,g.length):g.length,S=v;S0&&(_=1/Math.sqrt(_)),i[0]=g[0]*_,i[1]=g[1]*_,i},random:function(i,g){g=void 0===g?1:g;var x=2*Mt()*Math.PI;return i[0]=Math.cos(x)*g,i[1]=Math.sin(x)*g,i},rotate:function(i,g,x,v){var _=g[0]-x[0],y=g[1]-x[1],b=Math.sin(v),S=Math.cos(v);return i[0]=_*S-y*b+x[0],i[1]=_*b+y*S+x[1],i},round:function(i,g){return i[0]=round$3(g[0]),i[1]=round$3(g[1]),i},scale:function(i,g,x){return i[0]=g[0]*x,i[1]=g[1]*x,i},scaleAndAdd:scaleAndAdd,set:set,signedAngle:function(i,g){var x=i[0],v=i[1],_=g[0],y=g[1];return Math.atan2(x*y-v*_,x*_+v*y)},sqrDist:Rr,sqrLen:Cr,squaredDistance:squaredDistance,squaredLength:squaredLength,str:function(i){return"vec2("+i[0]+", "+i[1]+")"},sub:Tr,subtract:subtract,transformMat2:function(i,g,x){var v=g[0],_=g[1];return i[0]=x[0]*v+x[2]*_,i[1]=x[1]*v+x[3]*_,i},transformMat2d:function(i,g,x){var v=g[0],_=g[1];return i[0]=x[0]*v+x[2]*_+x[4],i[1]=x[1]*v+x[3]*_+x[5],i},transformMat3:function(i,g,x){var v=g[0],_=g[1];return i[0]=x[0]*v+x[3]*_+x[6],i[1]=x[1]*v+x[4]*_+x[7],i},transformMat4:function(i,g,x){var v=g[0],_=g[1];return i[0]=x[0]*v+x[4]*_+x[12],i[1]=x[1]*v+x[5]*_+x[13],i},zero:function(i){return i[0]=0,i[1]=0,i}});const Er={NEVER:"never",LESS:"less",EQUAL:"equal",LESS_EQUAL:"less-equal",GREATER:"greater",NOT_EQUAL:"not-equal",GREATER_EQUAL:"greater-equal",ALWAYS:"always"};Object.freeze(Er);class ResourceStateUniformBuffer{static dirtyList=[];buffer;uuid;#jt=0;constructor(i){this.buffer=i,this.uuid=i.uuid}get useNum(){return this.#jt}set useNum(i){this.#jt=i,ResourceStateUniformBuffer.dirtyList.push(this)}}const Ir=Symbol("gpuBuffer"),Ar=Symbol("gpuBufferData"),Lr=Symbol("gpuBufferDataViewF32"),Ur=Symbol("gpuBufferDataViewU32"),kr=Symbol("gpuBufferCacheKey");class ABaseBuffer extends ManagementResourceBase{[Ir];[kr];#Kt;constructor(i,g,x){super(i,g),this.#Kt=x}get cacheKey(){return this[kr]||this.uuid}get gpuBuffer(){return this[Ir]}get usage(){return this.#Kt}get size(){return this[Ar]?.byteLength||0}get videoMemorySize(){return this.size}destroy(){const i=this[Ir];i&&(this[Ir]=null,this.notifyUpdate(!0),this.redGPUContext.resourceManager.unregisterManagementResource(this),this.redGPUContext.commandEncoderManager.addDeferredDestroy(i))}}class AUniformBaseBuffer extends ABaseBuffer{[Ar];#Xt;#qt;constructor(i,g,x,v,_=""){super(i,g,x),this.#qt=v.byteLength,this.#Xt={size:this.#qt,usage:this.usage,label:_};try{this[Ir]=i.gpuDevice.createBuffer(this.#Xt)}catch(i){console.error("GPU 버퍼 생성에 실패했습니다:",i)}i.gpuDevice.queue.writeBuffer(this[Ir],0,v),this[Ar]=v,this[Lr]=new Float32Array(v),this[Ur]=new Uint32Array(v)}get label(){return this.#Xt.label}get data(){return this[Ar]}get dataViewF32(){return this[Lr]}get dataViewU32(){return this[Ur]}get size(){return this.#qt}get uniformBufferDescriptor(){return this.#Xt}writeOnlyBuffer(i,g){"boolean"==typeof g&&(g=g?1:0),this.redGPUContext.gpuDevice.queue.writeBuffer(this.gpuBuffer,i.uniformOffset,new i.View("number"==typeof g?[g]:g))}}class UniformBuffer extends AUniformBaseBuffer{constructor(i,g,x="",v=""){super(i,"managedUniformBufferState",GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC,g,x);const{table:_}=this.targetResourceManagedState,y=_.get(v);if(y)return y.buffer;v&&(this.name=v,this[kr]=v),this.redGPUContext.resourceManager.registerManagementResource(this,new ResourceStateUniformBuffer(this))}}Object.freeze(UniformBuffer);class e{constructor(i,g){this.name=i,this.attributes=g,this.size=0}get isArray(){return!1}get isStruct(){return!1}get isTemplate(){return!1}get isPointer(){return!1}getTypeName(){return this.name}}class t{constructor(i,g,x){this.name=i,this.type=g,this.attributes=x,this.offset=0,this.size=0}get isArray(){return this.type.isArray}get isStruct(){return this.type.isStruct}get isTemplate(){return this.type.isTemplate}get align(){return this.type.isStruct?this.type.align:0}get members(){return this.type.isStruct?this.type.members:null}get format(){return this.type.isArray||this.type.isTemplate?this.type.format:null}get count(){return this.type.isArray?this.type.count:0}get stride(){return this.type.isArray?this.type.stride:this.size}}class n extends e{constructor(i,g){super(i,g),this.members=[],this.align=0,this.startLine=-1,this.endLine=-1,this.inUse=!1}get isStruct(){return!0}}class s extends e{constructor(i,g){super(i,g),this.count=0,this.stride=0}get isArray(){return!0}getTypeName(){return`array<${this.format.getTypeName()}, ${this.count}>`}}class r extends e{constructor(i,g,x){super(i,x),this.format=g}get isPointer(){return!0}getTypeName(){return`&${this.format.getTypeName()}`}}class a extends e{constructor(i,g,x,v){super(i,x),this.format=g,this.access=v}get isTemplate(){return!0}getTypeName(){let i=this.name;if(null!==this.format){if("vec2"===i||"vec3"===i||"vec4"===i||"mat2x2"===i||"mat2x3"===i||"mat2x4"===i||"mat3x2"===i||"mat3x3"===i||"mat3x4"===i||"mat4x2"===i||"mat4x3"===i||"mat4x4"===i){if("f32"===this.format.name)return i+="f",i;if("i32"===this.format.name)return i+="i",i;if("u32"===this.format.name)return i+="u",i;if("bool"===this.format.name)return i+="b",i;if("f16"===this.format.name)return i+="h",i}i+=`<${this.format.name}>`}else if("vec2"===i||"vec3"===i||"vec4"===i)return i;return i}}var Gr;(i=>{i[i.Uniform=0]="Uniform",i[i.Storage=1]="Storage",i[i.Texture=2]="Texture",i[i.Sampler=3]="Sampler",i[i.StorageTexture=4]="StorageTexture"})(Gr||(Gr={}));class o{constructor(i,g,x,v,_,y,b){this.name=i,this.type=g,this.group=x,this.binding=v,this.attributes=_,this.resourceType=y,this.access=b}get isArray(){return this.type.isArray}get isStruct(){return this.type.isStruct}get isTemplate(){return this.type.isTemplate}get size(){return this.type.size}get align(){return this.type.isStruct?this.type.align:0}get members(){return this.type.isStruct?this.type.members:null}get format(){return this.type.isArray||this.type.isTemplate?this.type.format:null}get count(){return this.type.isArray?this.type.count:0}get stride(){return this.type.isArray?this.type.stride:this.size}}class c{constructor(i,g){this.name=i,this.type=g}}class l{constructor(i,g,x,v){this.name=i,this.type=g,this.locationType=x,this.location=v,this.interpolation=null}}class u{constructor(i,g,x,v){this.name=i,this.type=g,this.locationType=x,this.location=v}}class h{constructor(i,g,x,v){this.name=i,this.type=g,this.attributes=x,this.id=v}}class f{constructor(i,g,x){this.name=i,this.type=g,this.attributes=x}}class p{constructor(i,g=null,x){this.stage=null,this.inputs=[],this.outputs=[],this.arguments=[],this.returnType=null,this.resources=[],this.overrides=[],this.startLine=-1,this.endLine=-1,this.inUse=!1,this.calls=new Set,this.name=i,this.stage=g,this.attributes=x}}class d{constructor(){this.vertex=[],this.fragment=[],this.compute=[]}}function m(i){var g=(32768&i)>>15,x=(31744&i)>>10,v=1023&i;return 0==x?(g?-1:1)*Math.pow(2,-14)*(v/Math.pow(2,10)):31==x?v?NaN:1/0*(g?-1:1):(g?-1:1)*Math.pow(2,x-15)*(1+v/Math.pow(2,10))}const Or=new Float32Array(1),Vr=new Int32Array(Or.buffer),Nr=new Uint16Array(1);function y$1(i){Or[0]=i;const g=Vr[0],x=g>>31&1;let v=g>>23&255,_=8388607&g;if(255===v)return Nr[0]=x<<15|31744|(0!==_?512:0),Nr[0];if(0===v){if(0===_)return Nr[0]=x<<15,Nr[0];_|=8388608;let i=113;for(;!(8388608&_);)_<<=1,i--;return v=127-i,_&=8388607,v>0?(_=(_>>126-v)+(_>>127-v&1),Nr[0]=x<<15|v<<10|_>>13,Nr[0]):(Nr[0]=x<<15,Nr[0])}return v=v-127+15,v>=31?(Nr[0]=x<<15|31744,Nr[0]):v<=0?v<-10?(Nr[0]=x<<15,Nr[0]):(_=(8388608|_)>>1-v,Nr[0]=x<<15|_>>13,Nr[0]):(_>>=13,Nr[0]=x<<15|v<<10|_,Nr[0])}const Fr=new Uint32Array(1),Hr=new Float32Array(Fr.buffer,0,1);function w$1(i){const g=112+(i>>6&31)<<23|(63&i)<<17;return Fr[0]=g,Hr[0]}function I(i,g,x,v){const _=[0,0,0,0];for(let y=0;y{i.increment="++",i.decrement="--"})(jr||(jr={})),(i=>{i.parse=function(g){const x=g;if("parse"==x)throw new Error("Invalid value for IncrementOperator");return i[x]}})(jr||(jr={}));class R extends C{constructor(i,g){super(),this.operator=i,this.variable=g}get astNodeType(){return"increment"}search(i){this.variable.search(i)}}(i=>{i.assign="=",i.addAssign="+=",i.subtractAssin="-=",i.multiplyAssign="*=",i.divideAssign="/=",i.moduloAssign="%=",i.andAssign="&=",i.orAssign="|=",i.xorAssign="^=",i.shiftLeftAssign="<<=",i.shiftRightAssign=">>="})(Kr||(Kr={})),(Kr||(Kr={})).parse=function(i){const g=i;if("parse"==g)throw new Error("Invalid value for AssignOperator");return g};class G extends C{constructor(i,g,x){super(),this.operator=i,this.variable=g,this.value=x}get astNodeType(){return"assign"}search(i){this.variable.search(i),this.value.search(i)}}class X extends C{constructor(i,g){super(),this.name=i,this.args=g}get astNodeType(){return"call"}isBuiltin(){return $r.has(this.name)}search(i){for(const g of this.args)g.search(i);i(this)}}class j extends C{constructor(i,g){super(),this.body=i,this.continuing=g}get astNodeType(){return"loop"}search(i){var g;this.searchBlock(this.body,i),null===(g=this.continuing)||void 0===g||g.search(i)}}class Z extends C{constructor(i,g){super(),this.condition=i,this.cases=g}get astNodeType(){return"switch"}search(i){i(this);for(const g of this.cases)g.search(i)}}class Q extends C{constructor(i,g,x,v){super(),this.condition=i,this.body=g,this.elseif=x,this.else=v}get astNodeType(){return"if"}search(i){this.condition.search(i),this.searchBlock(this.body,i),this.searchBlock(this.elseif,i),this.searchBlock(this.else,i)}}class Y extends C{constructor(i){super(),this.value=i}get astNodeType(){return"return"}search(i){var g;null===(g=this.value)||void 0===g||g.search(i)}}class K extends C{constructor(i){super(),this.name=i}get astNodeType(){return"enable"}}class J extends C{constructor(i){super(),this.extensions=i}get astNodeType(){return"requires"}}class ee extends C{constructor(i,g){super(),this.severity=i,this.rule=g}get astNodeType(){return"diagnostic"}}class te extends C{constructor(i,g){super(),this.name=i,this.type=g}get astNodeType(){return"alias"}}class ne extends C{constructor(){super()}get astNodeType(){return"discard"}}class se extends C{constructor(){super(),this.condition=null,this.loopId=-1}get astNodeType(){return"break"}}class re extends C{constructor(){super(),this.loopId=-1}get astNodeType(){return"continue"}}class ae extends C{constructor(i){super(),this.attributes=null,this.name=i}get astNodeType(){return"type"}get isStruct(){return!1}get isArray(){return!1}static maxFormatType(i){let g=i[0];if("f32"===g.name)return g;for(let x=1;x`}else if("vec2"===i||"vec3"===i||"vec4"===i)return i;return i}}ce.vec2f=new ce("vec2",ae.f32,null),ce.vec3f=new ce("vec3",ae.f32,null),ce.vec4f=new ce("vec4",ae.f32,null),ce.vec2i=new ce("vec2",ae.i32,null),ce.vec3i=new ce("vec3",ae.i32,null),ce.vec4i=new ce("vec4",ae.i32,null),ce.vec2u=new ce("vec2",ae.u32,null),ce.vec3u=new ce("vec3",ae.u32,null),ce.vec4u=new ce("vec4",ae.u32,null),ce.vec2h=new ce("vec2",ae.f16,null),ce.vec3h=new ce("vec3",ae.f16,null),ce.vec4h=new ce("vec4",ae.f16,null),ce.vec2b=new ce("vec2",ae.bool,null),ce.vec3b=new ce("vec3",ae.bool,null),ce.vec4b=new ce("vec4",ae.bool,null),ce.mat2x2f=new ce("mat2x2",ae.f32,null),ce.mat2x3f=new ce("mat2x3",ae.f32,null),ce.mat2x4f=new ce("mat2x4",ae.f32,null),ce.mat3x2f=new ce("mat3x2",ae.f32,null),ce.mat3x3f=new ce("mat3x3",ae.f32,null),ce.mat3x4f=new ce("mat3x4",ae.f32,null),ce.mat4x2f=new ce("mat4x2",ae.f32,null),ce.mat4x3f=new ce("mat4x3",ae.f32,null),ce.mat4x4f=new ce("mat4x4",ae.f32,null),ce.mat2x2h=new ce("mat2x2",ae.f16,null),ce.mat2x3h=new ce("mat2x3",ae.f16,null),ce.mat2x4h=new ce("mat2x4",ae.f16,null),ce.mat3x2h=new ce("mat3x2",ae.f16,null),ce.mat3x3h=new ce("mat3x3",ae.f16,null),ce.mat3x4h=new ce("mat3x4",ae.f16,null),ce.mat4x2h=new ce("mat4x2",ae.f16,null),ce.mat4x3h=new ce("mat4x3",ae.f16,null),ce.mat4x4h=new ce("mat4x4",ae.f16,null),ce.mat2x2i=new ce("mat2x2",ae.i32,null),ce.mat2x3i=new ce("mat2x3",ae.i32,null),ce.mat2x4i=new ce("mat2x4",ae.i32,null),ce.mat3x2i=new ce("mat3x2",ae.i32,null),ce.mat3x3i=new ce("mat3x3",ae.i32,null),ce.mat3x4i=new ce("mat3x4",ae.i32,null),ce.mat4x2i=new ce("mat4x2",ae.i32,null),ce.mat4x3i=new ce("mat4x3",ae.i32,null),ce.mat4x4i=new ce("mat4x4",ae.i32,null),ce.mat2x2u=new ce("mat2x2",ae.u32,null),ce.mat2x3u=new ce("mat2x3",ae.u32,null),ce.mat2x4u=new ce("mat2x4",ae.u32,null),ce.mat3x2u=new ce("mat3x2",ae.u32,null),ce.mat3x3u=new ce("mat3x3",ae.u32,null),ce.mat3x4u=new ce("mat3x4",ae.u32,null),ce.mat4x2u=new ce("mat4x2",ae.u32,null),ce.mat4x3u=new ce("mat4x3",ae.u32,null),ce.mat4x4u=new ce("mat4x4",ae.u32,null);class le extends ae{constructor(i,g,x,v){super(i),this.storage=g,this.type=x,this.access=v}get astNodeType(){return"pointer"}}class ue extends ae{constructor(i,g,x,v){super(i),this.attributes=g,this.format=x,this.count=v}get astNodeType(){return"array"}get isArray(){return!0}}class he extends ae{constructor(i,g,x){super(i),this.format=g,this.access=x}get astNodeType(){return"sampler"}}class fe extends A{constructor(){super(),this.postfix=null}}class pe extends fe{constructor(i){super(),this.value=i}get astNodeType(){return"stringExpr"}toString(){return this.value}constEvaluateString(){return this.value}}class de extends fe{constructor(i,g){super(),this.type=i,this.args=g}get astNodeType(){return"createExpr"}search(i){if(i(this),this.args)for(const g of this.args)g.search(i)}constEvaluate(i,g){return g&&(g[0]=this.type),i.evalExpression(this,i.context)}}class me extends fe{constructor(i,g){super(),this.cachedReturnValue=null,this.name=i,this.args=g}get astNodeType(){return"callExpr"}setCachedReturnValue(i){this.cachedReturnValue=i}get isBuiltin(){return $r.has(this.name)}constEvaluate(i,g){return i.evalExpression(this,i.context)}search(i){for(const g of this.args)g.search(i);i(this)}}class ge extends fe{constructor(i){super(),this.name=i}get astNodeType(){return"varExpr"}search(i){i(this),this.postfix&&this.postfix.search(i)}constEvaluate(i,g){return i.evalExpression(this,i.context)}}class _e extends fe{constructor(i,g){super(),this.name=i,this.initializer=g}get astNodeType(){return"constExpr"}constEvaluate(i,g){if(this.initializer){const g=i.evalExpression(this.initializer,i.context);return null!==g&&this.postfix?g.getSubData(i,this.postfix,i.context):g}return null}search(i){this.initializer.search(i)}}class xe extends fe{constructor(i,g){super(),this.value=i,this.type=g}get astNodeType(){return"literalExpr"}constEvaluate(i,g){return void 0!==g&&(g[0]=this.type),this.value}get isScalar(){return this.value instanceof Be}get isVector(){return this.value instanceof Me||this.value instanceof Ue}get scalarValue(){return this.value instanceof Be?this.value.value:(console.error("Value is not scalar."),0)}get vectorValue(){return this.value instanceof Me||this.value instanceof Ue?this.value.data:(console.error("Value is not a vector or matrix."),new Float32Array(0))}}class ye extends fe{constructor(i,g){super(),this.type=i,this.value=g}get astNodeType(){return"bitcastExpr"}search(i){this.value.search(i)}}class ve extends fe{constructor(i){super(),this.index=i}search(i){this.index.search(i)}}class we extends fe{constructor(){super()}}class ke extends we{constructor(i,g){super(),this.operator=i,this.right=g}get astNodeType(){return"unaryOp"}constEvaluate(i,g){return i.evalExpression(this,i.context)}search(i){this.right.search(i)}}class Ie extends we{constructor(i,g,x){super(),this.operator=i,this.left=g,this.right=x}get astNodeType(){return"binaryOp"}_getPromotedType(i,g){return i.name===g.name?i:"f32"===i.name||"f32"===g.name?ae.f32:"u32"===i.name||"u32"===g.name?ae.u32:ae.i32}constEvaluate(i,g){return i.evalExpression(this,i.context)}search(i){this.left.search(i),this.right.search(i)}}class Te extends A{constructor(i){super(),this.body=i}search(i){i(this),this.searchBlock(this.body,i)}}class Se extends fe{constructor(){super()}get astNodeType(){return"default"}}class Ae extends Te{constructor(i,g){super(g),this.selectors=i}get astNodeType(){return"case"}search(i){this.searchBlock(this.body,i)}}class Ee extends Te{constructor(i){super(i)}get astNodeType(){return"default"}search(i){this.searchBlock(this.body,i)}}class $e extends A{constructor(i,g,x){super(),this.name=i,this.type=g,this.attributes=x}get astNodeType(){return"argument"}}class Le extends A{constructor(i,g){super(),this.condition=i,this.body=g}get astNodeType(){return"elseif"}search(i){this.condition.search(i),this.searchBlock(this.body,i)}}class Ce extends A{constructor(i,g,x){super(),this.name=i,this.type=g,this.attributes=x}get astNodeType(){return"member"}}class De extends A{constructor(i,g){super(),this.name=i,this.value=g}get astNodeType(){return"attribute"}}class Ne{constructor(i,g){this.parent=null,this.typeInfo=i,this.parent=g,this.id=Ne._id++}clone(){throw`Clone: Not implemented for ${this.constructor.name}`}setDataValue(i,g,x,v){console.error(`SetDataValue: Not implemented for ${this.constructor.name}`)}getSubData(i,g,x){return console.error(`GetDataValue: Not implemented for ${this.constructor.name}`),null}toString(){return`<${this.typeInfo.getTypeName()}>`}}Ne._id=0;class Ve extends Ne{constructor(){super(new e("void",null),null)}toString(){return"void"}}Ve.void=new Ve;class Oe extends Ne{constructor(i){super(new r("pointer",i.typeInfo,null),null),this.reference=i}clone(){return this}setDataValue(i,g,x,v){this.reference.setDataValue(i,g,x,v)}getSubData(i,g,x){return g?this.reference.getSubData(i,g,x):this}toString(){return`&${this.reference.toString()}`}}class Be extends Ne{constructor(i,g,x=null){super(g,x),i instanceof Int32Array||i instanceof Uint32Array||i instanceof Float32Array?this.data=i:"x32"===this.typeInfo.name?i-Math.floor(i)!==0?this.data=new Float32Array([i]):this.data=i>=0?new Uint32Array([i]):new Int32Array([i]):"i32"===this.typeInfo.name||"bool"===this.typeInfo.name?this.data=new Int32Array([i]):"u32"===this.typeInfo.name?this.data=new Uint32Array([i]):"f32"===this.typeInfo.name||"f16"===this.typeInfo.name?this.data=new Float32Array([i]):console.error("ScalarData2: Invalid type",g)}clone(){if(this.data instanceof Float32Array)return new Be(new Float32Array(this.data),this.typeInfo,null);if(this.data instanceof Int32Array)return new Be(new Int32Array(this.data),this.typeInfo,null);if(this.data instanceof Uint32Array)return new Be(new Uint32Array(this.data),this.typeInfo,null);throw"ScalarData: Invalid data type"}get value(){return this.data[0]}set value(i){this.data[0]=i}setDataValue(i,g,x,v){if(x)return void console.error("SetDataValue: Scalar data does not support postfix",x);if(!(g instanceof Be))return void console.error("SetDataValue: Invalid value",g);let _=g.data[0];"i32"===this.typeInfo.name||"u32"===this.typeInfo.name?_=Math.floor(_):"bool"===this.typeInfo.name&&(_=_?1:0),this.data[0]=_}getSubData(i,g,x){return g?(console.error("getSubData: Scalar data does not support postfix",g),null):this}toString(){return`${this.value}`}}function Fe(i,g,x){const v=g.length;return 2===v?"f32"===x?new Me(new Float32Array(g),i.getTypeInfo("vec2f")):"i32"===x||"bool"===x?new Me(new Int32Array(g),i.getTypeInfo("vec2i")):"u32"===x?new Me(new Uint32Array(g),i.getTypeInfo("vec2u")):"f16"===x?new Me(new Float32Array(g),i.getTypeInfo("vec2h")):(console.error(`getSubData: Unknown format ${x}`),null):3===v?"f32"===x?new Me(new Float32Array(g),i.getTypeInfo("vec3f")):"i32"===x||"bool"===x?new Me(new Int32Array(g),i.getTypeInfo("vec3i")):"u32"===x?new Me(new Uint32Array(g),i.getTypeInfo("vec3u")):"f16"===x?new Me(new Float32Array(g),i.getTypeInfo("vec3h")):(console.error(`getSubData: Unknown format ${x}`),null):4===v?"f32"===x?new Me(new Float32Array(g),i.getTypeInfo("vec4f")):"i32"===x||"bool"===x?new Me(new Int32Array(g),i.getTypeInfo("vec4i")):"u32"===x?new Me(new Uint32Array(g),i.getTypeInfo("vec4u")):"f16"===x?new Me(new Float32Array(g),i.getTypeInfo("vec4h")):(console.error(`getSubData: Unknown format ${x}`),null):(console.error(`getSubData: Invalid vector size ${g.length}`),null)}class Me extends Ne{constructor(i,g,x=null){if(super(g,x),i instanceof Float32Array||i instanceof Uint32Array||i instanceof Int32Array)this.data=i;else{const g=this.typeInfo.name;"vec2f"===g||"vec3f"===g||"vec4f"===g?this.data=new Float32Array(i):"vec2i"===g||"vec3i"===g||"vec4i"===g?this.data=new Int32Array(i):"vec2u"===g||"vec3u"===g||"vec4u"===g?this.data=new Uint32Array(i):"vec2h"===g||"vec3h"===g||"vec4h"===g?this.data=new Float32Array(i):"vec2b"===g||"vec3b"===g||"vec4b"===g?this.data=new Int32Array(i):"vec2"===g||"vec3"===g||"vec4"===g?this.data=new Float32Array(i):console.error(`VectorData: Invalid type ${g}`)}}clone(){if(this.data instanceof Float32Array)return new Me(new Float32Array(this.data),this.typeInfo,null);if(this.data instanceof Int32Array)return new Me(new Int32Array(this.data),this.typeInfo,null);if(this.data instanceof Uint32Array)return new Me(new Uint32Array(this.data),this.typeInfo,null);throw"VectorData: Invalid data type"}setDataValue(i,g,x,v){x instanceof pe?console.error("TODO: Set vector postfix"):g instanceof Me?this.data=g.data:console.error("SetDataValue: Invalid value",g)}getSubData(i,g,x){if(null===g)return this;let v=i.getTypeInfo("f32");if(this.typeInfo instanceof a)v=this.typeInfo.format||v;else{const g=this.typeInfo.name;"vec2f"===g||"vec3f"===g||"vec4f"===g?v=i.getTypeInfo("f32"):"vec2i"===g||"vec3i"===g||"vec4i"===g?v=i.getTypeInfo("i32"):"vec2b"===g||"vec3b"===g||"vec4b"===g?v=i.getTypeInfo("bool"):"vec2u"===g||"vec3u"===g||"vec4u"===g?v=i.getTypeInfo("u32"):"vec2h"===g||"vec3h"===g||"vec4h"===g?v=i.getTypeInfo("f16"):console.error(`GetSubData: Unknown type ${g}`)}let _=this;for(;null!==g&&null!==_;){if(g instanceof ve){const y=g.index;let b=-1;if(y instanceof xe){if(!(y.value instanceof Be))return console.error(`GetSubData: Invalid array index ${y.value}`),null;b=y.value.value}else{const g=i.evalExpression(y,x);if(!(g instanceof Be))return console.error("GetSubData: Unknown index type",y),null;b=g.value}if(b<0||b>=_.data.length)return console.error("GetSubData: Index out of range",b),null;if(_.data instanceof Float32Array){const i=new Float32Array(_.data.buffer,_.data.byteOffset+4*b,1);return new Be(i,v)}if(_.data instanceof Int32Array){const i=new Int32Array(_.data.buffer,_.data.byteOffset+4*b,1);return new Be(i,v)}if(_.data instanceof Uint32Array){const i=new Uint32Array(_.data.buffer,_.data.byteOffset+4*b,1);return new Be(i,v)}throw"GetSubData: Invalid data type"}if(!(g instanceof pe))return console.error("GetSubData: Unknown postfix",g),null;{const x=g.value.toLowerCase();if(1===x.length){let i=0;if("x"===x||"r"===x)i=0;else if("y"===x||"g"===x)i=1;else if("z"===x||"b"===x)i=2;else{if("w"!==x&&"a"!==x)return console.error(`GetSubData: Unknown member ${x}`),null;i=3}if(this.data instanceof Float32Array){let g=new Float32Array(this.data.buffer,this.data.byteOffset+4*i,1);return new Be(g,v,this)}if(this.data instanceof Int32Array){let g=new Int32Array(this.data.buffer,this.data.byteOffset+4*i,1);return new Be(g,v,this)}if(this.data instanceof Uint32Array){let g=new Uint32Array(this.data.buffer,this.data.byteOffset+4*i,1);return new Be(g,v,this)}}const y=[];for(const i of x)"x"===i||"r"===i?y.push(this.data[0]):"y"===i||"g"===i?y.push(this.data[1]):"z"===i||"b"===i?y.push(this.data[2]):"w"===i||"a"===i?y.push(this.data[3]):console.error(`GetDataValue: Unknown member ${i}`);_=Fe(i,y,v.name)}g=g.postfix}return _}toString(){let i=`${this.data[0]}`;for(let g=1;g=this.data.length)return console.error("GetDataValue: Index out of range",y),null;const b=v.endsWith("h")?"h":"f";let S;if("mat2x2"===v||"mat2x2f"===v||"mat2x2h"===v||"mat3x2"===v||"mat3x2f"===v||"mat3x2h"===v||"mat4x2"===v||"mat4x2f"===v||"mat4x2h"===v)S=new Me(new Float32Array(this.data.buffer,this.data.byteOffset+2*y*4,2),i.getTypeInfo(`vec2${b}`));else if("mat2x3"===v||"mat2x3f"===v||"mat2x3h"===v||"mat3x3"===v||"mat3x3f"===v||"mat3x3h"===v||"mat4x3"===v||"mat4x3f"===v||"mat4x3h"===v)S=new Me(new Float32Array(this.data.buffer,this.data.byteOffset+3*y*4,3),i.getTypeInfo(`vec3${b}`));else{if("mat2x4"!==v&&"mat2x4f"!==v&&"mat2x4h"!==v&&"mat3x4"!==v&&"mat3x4f"!==v&&"mat3x4h"!==v&&"mat4x4"!==v&&"mat4x4f"!==v&&"mat4x4h"!==v)return console.error(`GetDataValue: Unknown type ${v}`),null;S=new Me(new Float32Array(this.data.buffer,this.data.byteOffset+4*y*4,4),i.getTypeInfo(`vec4${b}`))}return g.postfix?S.getSubData(i,g.postfix,x):S}return console.error("GetDataValue: Invalid postfix",g),null}toString(){let i=`${this.data[0]}`;for(let g=1;g"!==y&&"x32"!==y)if("u32"!==y&&"atomic"!==y)if("bool"!==y){if("vec2f"===y||"vec2h"===y){const i=new Float32Array(this.buffer,v,2);return void(g instanceof Me?(i[0]=g.data[0],i[1]=g.data[1]):(i[0]=g[0],i[1]=g[1]))}if("vec3f"===y||"vec3h"===y){const i=new Float32Array(this.buffer,v,3);return void(g instanceof Me?(i[0]=g.data[0],i[1]=g.data[1],i[2]=g.data[2]):(i[0]=g[0],i[1]=g[1],i[2]=g[2]))}if("vec4f"===y||"vec4h"===y){const i=new Float32Array(this.buffer,v,4);return void(g instanceof Me?(i[0]=g.data[0],i[1]=g.data[1],i[2]=g.data[2],i[3]=g.data[3]):(i[0]=g[0],i[1]=g[1],i[2]=g[2],i[3]=g[3]))}if("vec2i"===y){const i=new Int32Array(this.buffer,v,2);return void(g instanceof Me?(i[0]=g.data[0],i[1]=g.data[1]):(i[0]=g[0],i[1]=g[1]))}if("vec3i"===y){const i=new Int32Array(this.buffer,v,3);return void(g instanceof Me?(i[0]=g.data[0],i[1]=g.data[1],i[2]=g.data[2]):(i[0]=g[0],i[1]=g[1],i[2]=g[2]))}if("vec4i"===y){const i=new Int32Array(this.buffer,v,4);return void(g instanceof Me?(i[0]=g.data[0],i[1]=g.data[1],i[2]=g.data[2],i[3]=g.data[3]):(i[0]=g[0],i[1]=g[1],i[2]=g[2],i[3]=g[3]))}if("vec2u"===y){const i=new Uint32Array(this.buffer,v,2);return void(g instanceof Me?(i[0]=g.data[0],i[1]=g.data[1]):(i[0]=g[0],i[1]=g[1]))}if("vec3u"===y){const i=new Uint32Array(this.buffer,v,3);return void(g instanceof Me?(i[0]=g.data[0],i[1]=g.data[1],i[2]=g.data[2]):(i[0]=g[0],i[1]=g[1],i[2]=g[2]))}if("vec4u"===y){const i=new Uint32Array(this.buffer,v,4);return void(g instanceof Me?(i[0]=g.data[0],i[1]=g.data[1],i[2]=g.data[2],i[3]=g.data[3]):(i[0]=g[0],i[1]=g[1],i[2]=g[2],i[3]=g[3]))}if("vec2b"===y){const i=new Uint32Array(this.buffer,v,2);return void(g instanceof Me?(i[0]=g.data[0],i[1]=g.data[1]):(i[0]=g[0],i[1]=g[1]))}if("vec3b"===y){const i=new Uint32Array(this.buffer,v,3);return void(g instanceof Me?(i[0]=g.data[0],i[1]=g.data[1],i[2]=g.data[2]):(i[0]=g[0],i[1]=g[1],i[2]=g[2]))}if("vec4b"===y){const i=new Uint32Array(this.buffer,v,4);return void(g instanceof Me?(i[0]=g.data[0],i[1]=g.data[1],i[2]=g.data[2],i[3]=g.data[3]):(i[0]=g[0],i[1]=g[1],i[2]=g[2],i[3]=g[3]))}if("mat2x2f"===y||"mat2x2h"===y){const i=new Float32Array(this.buffer,v,4);return void(g instanceof Ue?(i[0]=g.data[0],i[1]=g.data[1],i[2]=g.data[2],i[3]=g.data[3]):(i[0]=g[0],i[1]=g[1],i[2]=g[2],i[3]=g[3]))}if("mat2x3f"===y||"mat2x3h"===y){const i=new Float32Array(this.buffer,v,6);return void(g instanceof Ue?(i[0]=g.data[0],i[1]=g.data[1],i[2]=g.data[2],i[3]=g.data[3],i[4]=g.data[4],i[5]=g.data[5]):(i[0]=g[0],i[1]=g[1],i[2]=g[2],i[3]=g[3],i[4]=g[4],i[5]=g[5]))}if("mat2x4f"===y||"mat2x4h"===y){const i=new Float32Array(this.buffer,v,8);return void(g instanceof Ue?(i[0]=g.data[0],i[1]=g.data[1],i[2]=g.data[2],i[3]=g.data[3],i[4]=g.data[4],i[5]=g.data[5],i[6]=g.data[6],i[7]=g.data[7]):(i[0]=g[0],i[1]=g[1],i[2]=g[2],i[3]=g[3],i[4]=g[4],i[5]=g[5],i[6]=g[6],i[7]=g[7]))}if("mat3x2f"===y||"mat3x2h"===y){const i=new Float32Array(this.buffer,v,6);return void(g instanceof Ue?(i[0]=g.data[0],i[1]=g.data[1],i[2]=g.data[2],i[3]=g.data[3],i[4]=g.data[4],i[5]=g.data[5]):(i[0]=g[0],i[1]=g[1],i[2]=g[2],i[3]=g[3],i[4]=g[4],i[5]=g[5]))}if("mat3x3f"===y||"mat3x3h"===y){const i=new Float32Array(this.buffer,v,9);return void(g instanceof Ue?(i[0]=g.data[0],i[1]=g.data[1],i[2]=g.data[2],i[3]=g.data[3],i[4]=g.data[4],i[5]=g.data[5],i[6]=g.data[6],i[7]=g.data[7],i[8]=g.data[8]):(i[0]=g[0],i[1]=g[1],i[2]=g[2],i[3]=g[3],i[4]=g[4],i[5]=g[5],i[6]=g[6],i[7]=g[7],i[8]=g[8]))}if("mat3x4f"===y||"mat3x4h"===y){const i=new Float32Array(this.buffer,v,12);return void(g instanceof Ue?(i[0]=g.data[0],i[1]=g.data[1],i[2]=g.data[2],i[3]=g.data[3],i[4]=g.data[4],i[5]=g.data[5],i[6]=g.data[6],i[7]=g.data[7],i[8]=g.data[8],i[9]=g.data[9],i[10]=g.data[10],i[11]=g.data[11]):(i[0]=g[0],i[1]=g[1],i[2]=g[2],i[3]=g[3],i[4]=g[4],i[5]=g[5],i[6]=g[6],i[7]=g[7],i[8]=g[8],i[9]=g[9],i[10]=g[10],i[11]=g[11]))}if("mat4x2f"===y||"mat4x2h"===y){const i=new Float32Array(this.buffer,v,8);return void(g instanceof Ue?(i[0]=g.data[0],i[1]=g.data[1],i[2]=g.data[2],i[3]=g.data[3],i[4]=g.data[4],i[5]=g.data[5],i[6]=g.data[6],i[7]=g.data[7]):(i[0]=g[0],i[1]=g[1],i[2]=g[2],i[3]=g[3],i[4]=g[4],i[5]=g[5],i[6]=g[6],i[7]=g[7]))}if("mat4x3f"===y||"mat4x3h"===y){const i=new Float32Array(this.buffer,v,12);return void(g instanceof Ue?(i[0]=g.data[0],i[1]=g.data[1],i[2]=g.data[2],i[3]=g.data[3],i[4]=g.data[4],i[5]=g.data[5],i[6]=g.data[6],i[7]=g.data[7],i[8]=g.data[8],i[9]=g.data[9],i[10]=g.data[10],i[11]=g.data[11]):(i[0]=g[0],i[1]=g[1],i[2]=g[2],i[3]=g[3],i[4]=g[4],i[5]=g[5],i[6]=g[6],i[7]=g[7],i[8]=g[8],i[9]=g[9],i[10]=g[10],i[11]=g[11]))}if("mat4x4f"===y||"mat4x4h"===y){const i=new Float32Array(this.buffer,v,16);return void(g instanceof Ue?(i[0]=g.data[0],i[1]=g.data[1],i[2]=g.data[2],i[3]=g.data[3],i[4]=g.data[4],i[5]=g.data[5],i[6]=g.data[6],i[7]=g.data[7],i[8]=g.data[8],i[9]=g.data[9],i[10]=g.data[10],i[11]=g.data[11],i[12]=g.data[12],i[13]=g.data[13],i[14]=g.data[14],i[15]=g.data[15]):(i[0]=g[0],i[1]=g[1],i[2]=g[2],i[3]=g[3],i[4]=g[4],i[5]=g[5],i[6]=g[6],i[7]=g[7],i[8]=g[8],i[9]=g[9],i[10]=g[10],i[11]=g[11],i[12]=g[12],i[13]=g[13],i[14]=g[14],i[15]=g[15]))}if(g instanceof Pe){if(x===g.typeInfo)return void new Uint8Array(this.buffer,v,g.buffer.byteLength).set(new Uint8Array(g.buffer));console.error("SetDataValue: Type mismatch",y,g.typeInfo.getTypeName())}else console.error(`SetData: Unknown type ${y}`)}else g instanceof Be&&(new Int32Array(this.buffer,v,1)[0]=g.value);else g instanceof Be&&(new Uint32Array(this.buffer,v,1)[0]=g.value);else g instanceof Be&&(new Int32Array(this.buffer,v,1)[0]=g.value);else g instanceof Be&&(new Float32Array(this.buffer,v,1)[0]=g.value)}getSubData(i,g,x){var v,_,y;if(null===g)return this;let b=this.offset,S=this.typeInfo;for(;g;){if(g instanceof ve){const v=g.index,_=v instanceof fe?i.evalExpression(v,x):v;let y=0;if(_ instanceof Be?y=_.value:"number"==typeof _?y=_:console.error("GetDataValue: Invalid index type",v),S instanceof s)b+=y*S.stride,S=S.format;else{const g=S.getTypeName();"mat4x4"===g||"mat4x4f"===g||"mat4x4h"===g?(b+=16*y,S=i.getTypeInfo("vec4f")):console.error(`getDataValue: Type ${S.getTypeName()} is not an array`)}}else{if(!(g instanceof pe))return console.error("GetDataValue: Unknown postfix type",g),null;{const x=g.value;if(S instanceof n){let i=!1;for(const g of S.members)if(g.name===x){b+=g.offset,S=g.type,i=!0;break}if(!i)return console.error(`GetDataValue: Member ${x} not found`),null}else if(S instanceof e){const g=S.getTypeName();if("vec2f"===g||"vec3f"===g||"vec4f"===g||"vec2i"===g||"vec3i"===g||"vec4i"===g||"vec2u"===g||"vec3u"===g||"vec4u"===g||"vec2b"===g||"vec3b"===g||"vec4b"===g||"vec2h"===g||"vec3h"===g||"vec4h"===g||"vec2"===g||"vec3"===g||"vec4"===g){if(x.length>0&&x.length<5){let v="f";const _=[];for(let y=0;y=this.buffer.byteLength)return console.log("Insufficient buffer data"),null;const i=new Float32Array(this.buffer,b,3);_.push(i[w])}else if("vec4f"===g)_.push(new Float32Array(this.buffer,b,4)[w]);else if("vec2i"===g)v="i",_.push(new Int32Array(this.buffer,b,2)[w]);else if("vec3i"===g)v="i",_.push(new Int32Array(this.buffer,b,3)[w]);else if("vec4i"===g)v="i",_.push(new Int32Array(this.buffer,b,4)[w]);else if("vec2u"===g){v="u";const i=new Uint32Array(this.buffer,b,2);_.push(i[w])}else"vec3u"===g?(v="u",_.push(new Uint32Array(this.buffer,b,3)[w])):"vec4u"===g&&(v="u",_.push(new Uint32Array(this.buffer,b,4)[w]))}return 2===_.length?S=i.getTypeInfo(`vec2${v}`):3===_.length?S=i.getTypeInfo(`vec3${v}`):4===_.length?S=i.getTypeInfo(`vec4${v}`):console.error(`GetDataValue: Invalid vector length ${_.length}`),new Me(_,S,null)}return console.error(`GetDataValue: Unknown member ${x}`),null}return console.error(`GetDataValue: Type ${g} is not a struct`),null}}}g=g.postfix}const w=S.getTypeName();return"f32"===w?new Be(new Float32Array(this.buffer,b,1),S,this):"i32"===w?new Be(new Int32Array(this.buffer,b,1),S,this):"u32"===w?new Be(new Uint32Array(this.buffer,b,1),S,this):"vec2f"===w?new Me(new Float32Array(this.buffer,b,2),S,this):"vec3f"===w?new Me(new Float32Array(this.buffer,b,3),S,this):"vec4f"===w?new Me(new Float32Array(this.buffer,b,4),S,this):"vec2i"===w?new Me(new Int32Array(this.buffer,b,2),S,this):"vec3i"===w?new Me(new Int32Array(this.buffer,b,3),S,this):"vec4i"===w?new Me(new Int32Array(this.buffer,b,4),S,this):"vec2u"===w?new Me(new Uint32Array(this.buffer,b,2),S,this):"vec3u"===w?new Me(new Uint32Array(this.buffer,b,3),S,this):"vec4u"===w?new Me(new Uint32Array(this.buffer,b,4),S,this):S instanceof a&&"atomic"===S.name?"u32"===(null===(v=S.format)||void 0===v?void 0:v.name)?new Be(new Uint32Array(this.buffer,b,1)[0],S.format,this):"i32"===(null===(_=S.format)||void 0===_?void 0:_.name)?new Be(new Int32Array(this.buffer,b,1)[0],S.format,this):(console.error(`GetDataValue: Invalid atomic format ${null===(y=S.format)||void 0===y?void 0:y.name}`),null):new Pe(this.buffer,S,b,this)}toString(){let i="";if(this.typeInfo instanceof s)if("f32"===this.typeInfo.format.name){const g=new Float32Array(this.buffer,this.offset);i=`[${g[0]}`;for(let x=1;x0?null!==(i=x[0])&&void 0!==i?i:0:x instanceof Object&&null!==(g=x.width)&&void 0!==g?g:0}get height(){var i,g;const x=this.descriptor.size;return x instanceof Array&&x.length>1?null!==(i=x[1])&&void 0!==i?i:0:x instanceof Object&&null!==(g=x.height)&&void 0!==g?g:0}get depthOrArrayLayers(){var i,g;const x=this.descriptor.size;return x instanceof Array&&x.length>2?null!==(i=x[2])&&void 0!==i?i:0:x instanceof Object&&null!==(g=x.depthOrArrayLayers)&&void 0!==g?g:0}get format(){var i;return this.descriptor&&null!==(i=this.descriptor.format)&&void 0!==i?i:"rgba8unorm"}get sampleCount(){var i;return this.descriptor&&null!==(i=this.descriptor.sampleCount)&&void 0!==i?i:1}get mipLevelCount(){var i;return this.descriptor&&null!==(i=this.descriptor.mipLevelCount)&&void 0!==i?i:1}get dimension(){var i;return this.descriptor&&null!==(i=this.descriptor.dimension)&&void 0!==i?i:"2d"}getMipLevelSize(i){if(i>=this.mipLevelCount)return[0,0,0];const g=[this.width,this.height,this.depthOrArrayLayers];for(let x=0;x>i);return g}get texelByteSize(){const i=this.format,g=zr[i];return g?g.isDepthStencil?4:g.bytesPerBlock:0}get bytesPerRow(){return this.width*this.texelByteSize}get isDepthStencil(){const i=this.format,g=zr[i];return!!g&&g.isDepthStencil}getGpuSize(){const i=this.format,g=zr[i],x=this.width;if(!i||x<=0||!g)return-1;const v=this.height,_=this.depthOrArrayLayers,y=this.dimension;return x/g.blockWidth*("1d"===y?1:v/g.blockHeight)*g.bytesPerBlock*_}getPixel(i,g,x=0,v=0){const _=this.texelByteSize,y=this.bytesPerRow,b=this.height,S=this.data[v];return function(i,g,x,v,_,y,b,S,w){const L=v*(b>>=_)*(y>>=_)+x*b+g*S;switch(w){case"r8unorm":return[I(i,L,"8unorm",1)[0]];case"r8snorm":return[I(i,L,"8snorm",1)[0]];case"r8uint":return[I(i,L,"8uint",1)[0]];case"r8sint":return[I(i,L,"8sint",1)[0]];case"rg8unorm":{const g=I(i,L,"8unorm",2);return[g[0],g[1]]}case"rg8snorm":{const g=I(i,L,"8snorm",2);return[g[0],g[1]]}case"rg8uint":{const g=I(i,L,"8uint",2);return[g[0],g[1]]}case"rg8sint":{const g=I(i,L,"8sint",2);return[g[0],g[1]]}case"rgba8unorm-srgb":case"rgba8unorm":{const g=I(i,L,"8unorm",4);return[g[0],g[1],g[2],g[3]]}case"rgba8snorm":{const g=I(i,L,"8snorm",4);return[g[0],g[1],g[2],g[3]]}case"rgba8uint":{const g=I(i,L,"8uint",4);return[g[0],g[1],g[2],g[3]]}case"rgba8sint":{const g=I(i,L,"8sint",4);return[g[0],g[1],g[2],g[3]]}case"bgra8unorm-srgb":case"bgra8unorm":{const g=I(i,L,"8unorm",4);return[g[2],g[1],g[0],g[3]]}case"r16uint":return[I(i,L,"16uint",1)[0]];case"r16sint":return[I(i,L,"16sint",1)[0]];case"r16float":return[I(i,L,"16float",1)[0]];case"rg16uint":{const g=I(i,L,"16uint",2);return[g[0],g[1]]}case"rg16sint":{const g=I(i,L,"16sint",2);return[g[0],g[1]]}case"rg16float":{const g=I(i,L,"16float",2);return[g[0],g[1]]}case"rgba16uint":{const g=I(i,L,"16uint",4);return[g[0],g[1],g[2],g[3]]}case"rgba16sint":{const g=I(i,L,"16sint",4);return[g[0],g[1],g[2],g[3]]}case"rgba16float":{const g=I(i,L,"16float",4);return[g[0],g[1],g[2],g[3]]}case"r32uint":return[I(i,L,"32uint",1)[0]];case"r32sint":return[I(i,L,"32sint",1)[0]];case"depth16unorm":case"depth24plus":case"depth24plus-stencil8":case"depth32float":case"depth32float-stencil8":case"r32float":return[I(i,L,"32float",1)[0]];case"rg32uint":{const g=I(i,L,"32uint",2);return[g[0],g[1]]}case"rg32sint":{const g=I(i,L,"32sint",2);return[g[0],g[1]]}case"rg32float":{const g=I(i,L,"32float",2);return[g[0],g[1]]}case"rgba32uint":{const g=I(i,L,"32uint",4);return[g[0],g[1],g[2],g[3]]}case"rgba32sint":{const g=I(i,L,"32sint",4);return[g[0],g[1],g[2],g[3]]}case"rgba32float":{const g=I(i,L,"32float",4);return[g[0],g[1],g[2],g[3]]}case"rg11b10ufloat":{const g=new Uint32Array(i.buffer,L,1)[0],x=(4192256&g)>>11,v=(4290772992&g)>>22;return[w$1(2047&g),w$1(x),function(i){const g=112+(i>>5&31)<<23|(31&i)<<18;return Fr[0]=g,Hr[0]}(v),1]}}return null}(new Uint8Array(S),i,g,x,v,b,y,_,this.format)}setPixel(i,g,x,v,_){const y=this.texelByteSize,b=this.bytesPerRow,S=this.height,w=this.data[v];!function(i,g,x,v,_,y,b,S,w,L){const k=v*(b>>=_)*(y>>=_)+x*b+g*S;switch(w){case"r8unorm":return void T(i,k,"8unorm",1,L);case"r8snorm":return void T(i,k,"8snorm",1,L);case"r8uint":return void T(i,k,"8uint",1,L);case"r8sint":return void T(i,k,"8sint",1,L);case"rg8unorm":return void T(i,k,"8unorm",2,L);case"rg8snorm":return void T(i,k,"8snorm",2,L);case"rg8uint":return void T(i,k,"8uint",2,L);case"rg8sint":return void T(i,k,"8sint",2,L);case"rgba8unorm-srgb":case"rgba8unorm":case"bgra8unorm-srgb":case"bgra8unorm":return void T(i,k,"8unorm",4,L);case"rgba8snorm":return void T(i,k,"8snorm",4,L);case"rgba8uint":return void T(i,k,"8uint",4,L);case"rgba8sint":return void T(i,k,"8sint",4,L);case"r16uint":return void T(i,k,"16uint",1,L);case"r16sint":return void T(i,k,"16sint",1,L);case"r16float":return void T(i,k,"16float",1,L);case"rg16uint":return void T(i,k,"16uint",2,L);case"rg16sint":return void T(i,k,"16sint",2,L);case"rg16float":return void T(i,k,"16float",2,L);case"rgba16uint":return void T(i,k,"16uint",4,L);case"rgba16sint":return void T(i,k,"16sint",4,L);case"rgba16float":return void T(i,k,"16float",4,L);case"r32uint":return void T(i,k,"32uint",1,L);case"r32sint":return void T(i,k,"32sint",1,L);case"depth16unorm":case"depth24plus":case"depth24plus-stencil8":case"depth32float":case"depth32float-stencil8":case"r32float":return void T(i,k,"32float",1,L);case"rg32uint":return void T(i,k,"32uint",2,L);case"rg32sint":return void T(i,k,"32sint",2,L);case"rg32float":return void T(i,k,"32float",2,L);case"rgba32uint":return void T(i,k,"32uint",4,L);case"rgba32sint":return void T(i,k,"32sint",4,L);case"rgba32float":return void T(i,k,"32float",4,L);case"rg11b10ufloat":console.error("TODO: rg11b10ufloat not supported for writing")}}(new Uint8Array(w),i,g,x,v,S,b,y,this.format,_)}}(i=>{i[i.token=0]="token",i[i.keyword=1]="keyword",i[i.reserved=2]="reserved"})(qr||(qr={}));class qe{constructor(i,g,x){this.name=i,this.type=g,this.rule=x}toString(){return this.name}}class He{}Xr=He,He.none=new qe("",qr.reserved,""),He.eof=new qe("EOF",qr.token,""),He.reserved={asm:new qe("asm",qr.reserved,"asm"),bf16:new qe("bf16",qr.reserved,"bf16"),do:new qe("do",qr.reserved,"do"),enum:new qe("enum",qr.reserved,"enum"),f16:new qe("f16",qr.reserved,"f16"),f64:new qe("f64",qr.reserved,"f64"),handle:new qe("handle",qr.reserved,"handle"),i8:new qe("i8",qr.reserved,"i8"),i16:new qe("i16",qr.reserved,"i16"),i64:new qe("i64",qr.reserved,"i64"),mat:new qe("mat",qr.reserved,"mat"),premerge:new qe("premerge",qr.reserved,"premerge"),regardless:new qe("regardless",qr.reserved,"regardless"),typedef:new qe("typedef",qr.reserved,"typedef"),u8:new qe("u8",qr.reserved,"u8"),u16:new qe("u16",qr.reserved,"u16"),u64:new qe("u64",qr.reserved,"u64"),unless:new qe("unless",qr.reserved,"unless"),using:new qe("using",qr.reserved,"using"),vec:new qe("vec",qr.reserved,"vec"),void:new qe("void",qr.reserved,"void")},He.keywords={array:new qe("array",qr.keyword,"array"),atomic:new qe("atomic",qr.keyword,"atomic"),bool:new qe("bool",qr.keyword,"bool"),f32:new qe("f32",qr.keyword,"f32"),i32:new qe("i32",qr.keyword,"i32"),mat2x2:new qe("mat2x2",qr.keyword,"mat2x2"),mat2x3:new qe("mat2x3",qr.keyword,"mat2x3"),mat2x4:new qe("mat2x4",qr.keyword,"mat2x4"),mat3x2:new qe("mat3x2",qr.keyword,"mat3x2"),mat3x3:new qe("mat3x3",qr.keyword,"mat3x3"),mat3x4:new qe("mat3x4",qr.keyword,"mat3x4"),mat4x2:new qe("mat4x2",qr.keyword,"mat4x2"),mat4x3:new qe("mat4x3",qr.keyword,"mat4x3"),mat4x4:new qe("mat4x4",qr.keyword,"mat4x4"),ptr:new qe("ptr",qr.keyword,"ptr"),sampler:new qe("sampler",qr.keyword,"sampler"),sampler_comparison:new qe("sampler_comparison",qr.keyword,"sampler_comparison"),struct:new qe("struct",qr.keyword,"struct"),texture_1d:new qe("texture_1d",qr.keyword,"texture_1d"),texture_2d:new qe("texture_2d",qr.keyword,"texture_2d"),texture_2d_array:new qe("texture_2d_array",qr.keyword,"texture_2d_array"),texture_3d:new qe("texture_3d",qr.keyword,"texture_3d"),texture_cube:new qe("texture_cube",qr.keyword,"texture_cube"),texture_cube_array:new qe("texture_cube_array",qr.keyword,"texture_cube_array"),texture_multisampled_2d:new qe("texture_multisampled_2d",qr.keyword,"texture_multisampled_2d"),texture_storage_1d:new qe("texture_storage_1d",qr.keyword,"texture_storage_1d"),texture_storage_2d:new qe("texture_storage_2d",qr.keyword,"texture_storage_2d"),texture_storage_2d_array:new qe("texture_storage_2d_array",qr.keyword,"texture_storage_2d_array"),texture_storage_3d:new qe("texture_storage_3d",qr.keyword,"texture_storage_3d"),texture_depth_2d:new qe("texture_depth_2d",qr.keyword,"texture_depth_2d"),texture_depth_2d_array:new qe("texture_depth_2d_array",qr.keyword,"texture_depth_2d_array"),texture_depth_cube:new qe("texture_depth_cube",qr.keyword,"texture_depth_cube"),texture_depth_cube_array:new qe("texture_depth_cube_array",qr.keyword,"texture_depth_cube_array"),texture_depth_multisampled_2d:new qe("texture_depth_multisampled_2d",qr.keyword,"texture_depth_multisampled_2d"),texture_external:new qe("texture_external",qr.keyword,"texture_external"),u32:new qe("u32",qr.keyword,"u32"),vec2:new qe("vec2",qr.keyword,"vec2"),vec3:new qe("vec3",qr.keyword,"vec3"),vec4:new qe("vec4",qr.keyword,"vec4"),bitcast:new qe("bitcast",qr.keyword,"bitcast"),block:new qe("block",qr.keyword,"block"),break:new qe("break",qr.keyword,"break"),case:new qe("case",qr.keyword,"case"),continue:new qe("continue",qr.keyword,"continue"),continuing:new qe("continuing",qr.keyword,"continuing"),default:new qe("default",qr.keyword,"default"),diagnostic:new qe("diagnostic",qr.keyword,"diagnostic"),discard:new qe("discard",qr.keyword,"discard"),else:new qe("else",qr.keyword,"else"),enable:new qe("enable",qr.keyword,"enable"),fallthrough:new qe("fallthrough",qr.keyword,"fallthrough"),false:new qe("false",qr.keyword,"false"),fn:new qe("fn",qr.keyword,"fn"),for:new qe("for",qr.keyword,"for"),function:new qe("function",qr.keyword,"function"),if:new qe("if",qr.keyword,"if"),let:new qe("let",qr.keyword,"let"),const:new qe("const",qr.keyword,"const"),loop:new qe("loop",qr.keyword,"loop"),while:new qe("while",qr.keyword,"while"),private:new qe("private",qr.keyword,"private"),read:new qe("read",qr.keyword,"read"),read_write:new qe("read_write",qr.keyword,"read_write"),return:new qe("return",qr.keyword,"return"),requires:new qe("requires",qr.keyword,"requires"),storage:new qe("storage",qr.keyword,"storage"),switch:new qe("switch",qr.keyword,"switch"),true:new qe("true",qr.keyword,"true"),alias:new qe("alias",qr.keyword,"alias"),type:new qe("type",qr.keyword,"type"),uniform:new qe("uniform",qr.keyword,"uniform"),var:new qe("var",qr.keyword,"var"),override:new qe("override",qr.keyword,"override"),workgroup:new qe("workgroup",qr.keyword,"workgroup"),write:new qe("write",qr.keyword,"write"),r8unorm:new qe("r8unorm",qr.keyword,"r8unorm"),r8snorm:new qe("r8snorm",qr.keyword,"r8snorm"),r8uint:new qe("r8uint",qr.keyword,"r8uint"),r8sint:new qe("r8sint",qr.keyword,"r8sint"),r16uint:new qe("r16uint",qr.keyword,"r16uint"),r16sint:new qe("r16sint",qr.keyword,"r16sint"),r16float:new qe("r16float",qr.keyword,"r16float"),rg8unorm:new qe("rg8unorm",qr.keyword,"rg8unorm"),rg8snorm:new qe("rg8snorm",qr.keyword,"rg8snorm"),rg8uint:new qe("rg8uint",qr.keyword,"rg8uint"),rg8sint:new qe("rg8sint",qr.keyword,"rg8sint"),r32uint:new qe("r32uint",qr.keyword,"r32uint"),r32sint:new qe("r32sint",qr.keyword,"r32sint"),r32float:new qe("r32float",qr.keyword,"r32float"),rg16uint:new qe("rg16uint",qr.keyword,"rg16uint"),rg16sint:new qe("rg16sint",qr.keyword,"rg16sint"),rg16float:new qe("rg16float",qr.keyword,"rg16float"),rgba8unorm:new qe("rgba8unorm",qr.keyword,"rgba8unorm"),rgba8unorm_srgb:new qe("rgba8unorm_srgb",qr.keyword,"rgba8unorm_srgb"),rgba8snorm:new qe("rgba8snorm",qr.keyword,"rgba8snorm"),rgba8uint:new qe("rgba8uint",qr.keyword,"rgba8uint"),rgba8sint:new qe("rgba8sint",qr.keyword,"rgba8sint"),bgra8unorm:new qe("bgra8unorm",qr.keyword,"bgra8unorm"),bgra8unorm_srgb:new qe("bgra8unorm_srgb",qr.keyword,"bgra8unorm_srgb"),rgb10a2unorm:new qe("rgb10a2unorm",qr.keyword,"rgb10a2unorm"),rg11b10float:new qe("rg11b10float",qr.keyword,"rg11b10float"),rg32uint:new qe("rg32uint",qr.keyword,"rg32uint"),rg32sint:new qe("rg32sint",qr.keyword,"rg32sint"),rg32float:new qe("rg32float",qr.keyword,"rg32float"),rgba16uint:new qe("rgba16uint",qr.keyword,"rgba16uint"),rgba16sint:new qe("rgba16sint",qr.keyword,"rgba16sint"),rgba16float:new qe("rgba16float",qr.keyword,"rgba16float"),rgba32uint:new qe("rgba32uint",qr.keyword,"rgba32uint"),rgba32sint:new qe("rgba32sint",qr.keyword,"rgba32sint"),rgba32float:new qe("rgba32float",qr.keyword,"rgba32float"),static_assert:new qe("static_assert",qr.keyword,"static_assert")},He.tokens={decimal_float_literal:new qe("decimal_float_literal",qr.token,/((-?[0-9]*\.[0-9]+|-?[0-9]+\.[0-9]*)((e|E)(\+|-)?[0-9]+)?[fh]?)|(-?[0-9]+(e|E)(\+|-)?[0-9]+[fh]?)|(-?[0-9]+[fh])/),hex_float_literal:new qe("hex_float_literal",qr.token,/-?0x((([0-9a-fA-F]*\.[0-9a-fA-F]+|[0-9a-fA-F]+\.[0-9a-fA-F]*)((p|P)(\+|-)?[0-9]+[fh]?)?)|([0-9a-fA-F]+(p|P)(\+|-)?[0-9]+[fh]?))/),int_literal:new qe("int_literal",qr.token,/-?0x[0-9a-fA-F]+|0i?|-?[1-9][0-9]*i?/),uint_literal:new qe("uint_literal",qr.token,/0x[0-9a-fA-F]+u|0u|[1-9][0-9]*u/),name:new qe("name",qr.token,/([_\p{XID_Start}][\p{XID_Continue}]+)|([\p{XID_Start}])/u),ident:new qe("ident",qr.token,/[_a-zA-Z][0-9a-zA-Z_]*/),and:new qe("and",qr.token,"&"),and_and:new qe("and_and",qr.token,"&&"),arrow:new qe("arrow ",qr.token,"->"),attr:new qe("attr",qr.token,"@"),forward_slash:new qe("forward_slash",qr.token,"/"),bang:new qe("bang",qr.token,"!"),bracket_left:new qe("bracket_left",qr.token,"["),bracket_right:new qe("bracket_right",qr.token,"]"),brace_left:new qe("brace_left",qr.token,"{"),brace_right:new qe("brace_right",qr.token,"}"),colon:new qe("colon",qr.token,":"),comma:new qe("comma",qr.token,","),equal:new qe("equal",qr.token,"="),equal_equal:new qe("equal_equal",qr.token,"=="),not_equal:new qe("not_equal",qr.token,"!="),greater_than:new qe("greater_than",qr.token,">"),greater_than_equal:new qe("greater_than_equal",qr.token,">="),shift_right:new qe("shift_right",qr.token,">>"),less_than:new qe("less_than",qr.token,"<"),less_than_equal:new qe("less_than_equal",qr.token,"<="),shift_left:new qe("shift_left",qr.token,"<<"),modulo:new qe("modulo",qr.token,"%"),minus:new qe("minus",qr.token,"-"),minus_minus:new qe("minus_minus",qr.token,"--"),period:new qe("period",qr.token,"."),plus:new qe("plus",qr.token,"+"),plus_plus:new qe("plus_plus",qr.token,"++"),or:new qe("or",qr.token,"|"),or_or:new qe("or_or",qr.token,"||"),paren_left:new qe("paren_left",qr.token,"("),paren_right:new qe("paren_right",qr.token,")"),semicolon:new qe("semicolon",qr.token,";"),star:new qe("star",qr.token,"*"),tilde:new qe("tilde",qr.token,"~"),underscore:new qe("underscore",qr.token,"_"),xor:new qe("xor",qr.token,"^"),plus_equal:new qe("plus_equal",qr.token,"+="),minus_equal:new qe("minus_equal",qr.token,"-="),times_equal:new qe("times_equal",qr.token,"*="),division_equal:new qe("division_equal",qr.token,"/="),modulo_equal:new qe("modulo_equal",qr.token,"%="),and_equal:new qe("and_equal",qr.token,"&="),or_equal:new qe("or_equal",qr.token,"|="),xor_equal:new qe("xor_equal",qr.token,"^="),shift_right_equal:new qe("shift_right_equal",qr.token,">>="),shift_left_equal:new qe("shift_left_equal",qr.token,"<<=")},He.simpleTokens={"@":Xr.tokens.attr,"{":Xr.tokens.brace_left,"}":Xr.tokens.brace_right,":":Xr.tokens.colon,",":Xr.tokens.comma,"(":Xr.tokens.paren_left,")":Xr.tokens.paren_right,";":Xr.tokens.semicolon},He.literalTokens={"&":Xr.tokens.and,"&&":Xr.tokens.and_and,"->":Xr.tokens.arrow,"/":Xr.tokens.forward_slash,"!":Xr.tokens.bang,"[":Xr.tokens.bracket_left,"]":Xr.tokens.bracket_right,"=":Xr.tokens.equal,"==":Xr.tokens.equal_equal,"!=":Xr.tokens.not_equal,">":Xr.tokens.greater_than,">=":Xr.tokens.greater_than_equal,">>":Xr.tokens.shift_right,"<":Xr.tokens.less_than,"<=":Xr.tokens.less_than_equal,"<<":Xr.tokens.shift_left,"%":Xr.tokens.modulo,"-":Xr.tokens.minus,"--":Xr.tokens.minus_minus,".":Xr.tokens.period,"+":Xr.tokens.plus,"++":Xr.tokens.plus_plus,"|":Xr.tokens.or,"||":Xr.tokens.or_or,"*":Xr.tokens.star,"~":Xr.tokens.tilde,_:Xr.tokens.underscore,"^":Xr.tokens.xor,"+=":Xr.tokens.plus_equal,"-=":Xr.tokens.minus_equal,"*=":Xr.tokens.times_equal,"/=":Xr.tokens.division_equal,"%=":Xr.tokens.modulo_equal,"&=":Xr.tokens.and_equal,"|=":Xr.tokens.or_equal,"^=":Xr.tokens.xor_equal,">>=":Xr.tokens.shift_right_equal,"<<=":Xr.tokens.shift_left_equal},He.regexTokens={decimal_float_literal:Xr.tokens.decimal_float_literal,hex_float_literal:Xr.tokens.hex_float_literal,int_literal:Xr.tokens.int_literal,uint_literal:Xr.tokens.uint_literal,ident:Xr.tokens.ident},He.storage_class=[Xr.keywords.function,Xr.keywords.private,Xr.keywords.workgroup,Xr.keywords.uniform,Xr.keywords.storage],He.access_mode=[Xr.keywords.read,Xr.keywords.write,Xr.keywords.read_write],He.sampler_type=[Xr.keywords.sampler,Xr.keywords.sampler_comparison],He.sampled_texture_type=[Xr.keywords.texture_1d,Xr.keywords.texture_2d,Xr.keywords.texture_2d_array,Xr.keywords.texture_3d,Xr.keywords.texture_cube,Xr.keywords.texture_cube_array],He.multisampled_texture_type=[Xr.keywords.texture_multisampled_2d],He.storage_texture_type=[Xr.keywords.texture_storage_1d,Xr.keywords.texture_storage_2d,Xr.keywords.texture_storage_2d_array,Xr.keywords.texture_storage_3d],He.depth_texture_type=[Xr.keywords.texture_depth_2d,Xr.keywords.texture_depth_2d_array,Xr.keywords.texture_depth_cube,Xr.keywords.texture_depth_cube_array,Xr.keywords.texture_depth_multisampled_2d],He.texture_external_type=[Xr.keywords.texture_external],He.any_texture_type=[...Xr.sampled_texture_type,...Xr.multisampled_texture_type,...Xr.storage_texture_type,...Xr.depth_texture_type,...Xr.texture_external_type],He.texel_format=[Xr.keywords.r8unorm,Xr.keywords.r8snorm,Xr.keywords.r8uint,Xr.keywords.r8sint,Xr.keywords.r16uint,Xr.keywords.r16sint,Xr.keywords.r16float,Xr.keywords.rg8unorm,Xr.keywords.rg8snorm,Xr.keywords.rg8uint,Xr.keywords.rg8sint,Xr.keywords.r32uint,Xr.keywords.r32sint,Xr.keywords.r32float,Xr.keywords.rg16uint,Xr.keywords.rg16sint,Xr.keywords.rg16float,Xr.keywords.rgba8unorm,Xr.keywords.rgba8unorm_srgb,Xr.keywords.rgba8snorm,Xr.keywords.rgba8uint,Xr.keywords.rgba8sint,Xr.keywords.bgra8unorm,Xr.keywords.bgra8unorm_srgb,Xr.keywords.rgb10a2unorm,Xr.keywords.rg11b10float,Xr.keywords.rg32uint,Xr.keywords.rg32sint,Xr.keywords.rg32float,Xr.keywords.rgba16uint,Xr.keywords.rgba16sint,Xr.keywords.rgba16float,Xr.keywords.rgba32uint,Xr.keywords.rgba32sint,Xr.keywords.rgba32float],He.const_literal=[Xr.tokens.int_literal,Xr.tokens.uint_literal,Xr.tokens.decimal_float_literal,Xr.tokens.hex_float_literal,Xr.keywords.true,Xr.keywords.false],He.literal_or_ident=[Xr.tokens.ident,Xr.tokens.int_literal,Xr.tokens.uint_literal,Xr.tokens.decimal_float_literal,Xr.tokens.hex_float_literal,Xr.tokens.name],He.element_count_expression=[Xr.tokens.int_literal,Xr.tokens.uint_literal,Xr.tokens.ident],He.template_types=[Xr.keywords.vec2,Xr.keywords.vec3,Xr.keywords.vec4,Xr.keywords.mat2x2,Xr.keywords.mat2x3,Xr.keywords.mat2x4,Xr.keywords.mat3x2,Xr.keywords.mat3x3,Xr.keywords.mat3x4,Xr.keywords.mat4x2,Xr.keywords.mat4x3,Xr.keywords.mat4x4,Xr.keywords.atomic,Xr.keywords.bitcast,...Xr.any_texture_type],He.attribute_name=[Xr.tokens.ident,Xr.keywords.block,Xr.keywords.diagnostic],He.assignment_operators=[Xr.tokens.equal,Xr.tokens.plus_equal,Xr.tokens.minus_equal,Xr.tokens.times_equal,Xr.tokens.division_equal,Xr.tokens.modulo_equal,Xr.tokens.and_equal,Xr.tokens.or_equal,Xr.tokens.xor_equal,Xr.tokens.shift_right_equal,Xr.tokens.shift_left_equal],He.increment_operators=[Xr.tokens.plus_plus,Xr.tokens.minus_minus];class ze{constructor(i,g,x,v,_){this.type=i,this.lexeme=g,this.line=x,this.start=v,this.end=_}toString(){return this.lexeme}isTemplateType(){return-1!=He.template_types.indexOf(this.type)}isArrayType(){return this.type==He.keywords.array}isArrayOrTemplateType(){return this.isArrayType()||this.isTemplateType()}}class Re{constructor(i){this._tokens=[],this._start=0,this._current=0,this._line=1,this._source=null!=i?i:""}scanTokens(){for(;!this._isAtEnd();)if(this._start=this._current,!this.scanToken())throw`Invalid syntax at line ${this._line}`;return this._tokens.push(new ze(He.eof,"",this._line,this._current,this._current)),this._tokens}scanToken(){let i=this._advance();if("\n"==i)return this._line++,!0;if(this._isWhitespace(i))return!0;if("/"==i){if("/"==this._peekAhead()){for(;"\n"!=i;){if(this._isAtEnd())return!0;i=this._advance()}return this._line++,!0}if("*"==this._peekAhead()){this._advance();let g=1;for(;g>0;){if(this._isAtEnd())return!0;if(i=this._advance(),"\n"==i)this._line++;else if("*"==i){if("/"==this._peekAhead()&&(this._advance(),g--,0==g))return!0}else"/"==i&&"*"==this._peekAhead()&&(this._advance(),g++)}return!0}}const g=He.simpleTokens[i];if(g)return this._addToken(g),!0;let x=He.none;const v=this._isAlpha(i),_="_"===i;if(this._isAlphaNumeric(i)){let g=this._peekAhead();for(;this._isAlphaNumeric(g);)i+=this._advance(),g=this._peekAhead()}if(v){const g=He.keywords[i];if(g)return this._addToken(g),!0}if(v||_)return this._addToken(He.tokens.ident),!0;for(;;){let g=this._findType(i);const v=this._peekAhead();if("-"==i&&this._tokens.length>0){if("="==v)return this._current++,i+=v,this._addToken(He.tokens.minus_equal),!0;if("-"==v)return this._current++,i+=v,this._addToken(He.tokens.minus_minus),!0;const x=this._tokens.length-1;if((-1!=He.literal_or_ident.indexOf(this._tokens[x].type)||this._tokens[x].type==He.tokens.paren_right)&&">"!=v)return this._addToken(g),!0}if(">"==i&&(">"==v||"="==v)){let i=!1,x=this._tokens.length-1;for(let g=0;g<5&&x>=0&&-1===He.assignment_operators.indexOf(this._tokens[x].type);++g,--x)if(this._tokens[x].type===He.tokens.less_than){x>0&&this._tokens[x-1].isArrayOrTemplateType()&&(i=!0);break}if(i)return this._addToken(g),!0}if(g===He.none){let v=i,_=0;const y=2;for(let i=0;i=this._source.length}_isAlpha(i){return!this._isNumeric(i)&&!this._isWhitespace(i)&&"_"!==i&&"."!==i&&"("!==i&&")"!==i&&"["!==i&&"]"!==i&&"{"!==i&&"}"!==i&&","!==i&&";"!==i&&":"!==i&&"="!==i&&"!"!==i&&"<"!==i&&">"!==i&&"+"!==i&&"-"!==i&&"*"!==i&&"/"!==i&&"%"!==i&&"&"!==i&&"|"!==i&&"^"!==i&&"~"!==i&&"@"!==i&&"#"!==i&&"?"!==i&&"'"!==i&&"`"!==i&&'"'!==i&&"\\"!==i&&"\n"!==i&&"\r"!==i&&"\t"!==i&&"\0"!==i}_isNumeric(i){return i>="0"&&i<="9"}_isAlphaNumeric(i){return this._isAlpha(i)||this._isNumeric(i)||"_"===i}_isWhitespace(i){return" "==i||"\t"==i||"\r"==i}_advance(i=0){let g=this._source[this._current];return i=i||0,i++,this._current+=i,g}_peekAhead(i=0){return i=i||0,this._current+i>=this._source.length?"\0":this._source[this._current+i]}_addToken(i){const g=this._source.substring(this._start,this._current);this._tokens.push(new ze(i,g,this._line,this._start,this._current))}}function Ge(i){return Array.isArray(i)||(null==i?void 0:i.buffer)instanceof ArrayBuffer}const Yr=new Float32Array(1),Wr=new Uint32Array(Yr.buffer),Zr=new Uint32Array(Yr.buffer),Jr=new Int32Array(1),Qr=new Float32Array(Jr.buffer),ei=new Uint32Array(Jr.buffer),ti=new Uint32Array(1),ri=new Float32Array(ti.buffer),ii=new Int32Array(ti.buffer);function nt(i,g,x){if(g===x)return i;if("f32"===g){if("i32"===x||"x32"===x)return Yr[0]=i,Wr[0];if("u32"===x)return Yr[0]=i,Zr[0]}else if("i32"===g||"x32"===g){if("f32"===x)return Jr[0]=i,Qr[0];if("u32"===x)return Jr[0]=i,ei[0]}else if("u32"===g){if("f32"===x)return ti[0]=i,ri[0];if("i32"===x||"x32"===x)return ti[0]=i,ii[0]}return console.error(`Unsupported cast from ${g} to ${x}`),i}class st{constructor(i){this.resources=null,this.inUse=!1,this.info=null,this.node=i}}class rt{constructor(i,g){this.align=i,this.size=g}}class at{constructor(){this.uniforms=[],this.storage=[],this.textures=[],this.samplers=[],this.aliases=[],this.overrides=[],this.structs=[],this.entry=new d,this.functions=[],this._types=new Map,this._functions=new Map}_isStorageTexture(i){return"texture_storage_1d"==i.name||"texture_storage_2d"==i.name||"texture_storage_2d_array"==i.name||"texture_storage_3d"==i.name}updateAST(i){for(const g of i)g instanceof D&&this._functions.set(g.name,new st(g));for(const g of i)if(g instanceof oe){const i=this.getTypeInfo(g,null);i instanceof n&&this.structs.push(i)}for(const g of i)if(g instanceof te)this.aliases.push(this._getAliasInfo(g));else{if(g instanceof M){const i=g,x=this._getAttributeNum(i.attributes,"id",0),v=null!=i.type?this.getTypeInfo(i.type,i.attributes):null;this.overrides.push(new h(i.name,v,i.attributes,x));continue}if(this._isUniformVar(g)){const i=g,x=this._getAttributeNum(i.attributes,"group",0),v=this._getAttributeNum(i.attributes,"binding",0),_=this.getTypeInfo(i.type,i.attributes),y=new o(i.name,_,x,v,i.attributes,Gr.Uniform,i.access);y.access||(y.access="read"),this.uniforms.push(y);continue}if(this._isStorageVar(g)){const i=g,x=this._getAttributeNum(i.attributes,"group",0),v=this._getAttributeNum(i.attributes,"binding",0),_=this.getTypeInfo(i.type,i.attributes),y=this._isStorageTexture(_),b=new o(i.name,_,x,v,i.attributes,y?Gr.StorageTexture:Gr.Storage,i.access);b.access||(b.access="read"),this.storage.push(b);continue}if(this._isTextureVar(g)){const i=g,x=this._getAttributeNum(i.attributes,"group",0),v=this._getAttributeNum(i.attributes,"binding",0),_=this.getTypeInfo(i.type,i.attributes),y=this._isStorageTexture(_),b=new o(i.name,_,x,v,i.attributes,y?Gr.StorageTexture:Gr.Texture,i.access);b.access||(b.access="read"),y?this.storage.push(b):this.textures.push(b);continue}if(this._isSamplerVar(g)){const i=g,x=this._getAttributeNum(i.attributes,"group",0),v=this._getAttributeNum(i.attributes,"binding",0),_=this.getTypeInfo(i.type,i.attributes),y=new o(i.name,_,x,v,i.attributes,Gr.Sampler,i.access);this.samplers.push(y);continue}}for(const g of i)if(g instanceof D){const i=this._getAttribute(g,"vertex"),x=this._getAttribute(g,"fragment"),v=this._getAttribute(g,"compute"),_=i||x||v,y=new p(g.name,null==_?void 0:_.name,g.attributes);y.attributes=g.attributes,y.startLine=g.startLine,y.endLine=g.endLine,this.functions.push(y),this._functions.get(g.name).info=y,_&&(this._functions.get(g.name).inUse=!0,y.inUse=!0,y.resources=this._findResources(g,!!_),y.inputs=this._getInputs(g.args),y.outputs=this._getOutputs(g.returnType),this.entry[_.name].push(y)),y.arguments=g.args.map(i=>new f(i.name,this.getTypeInfo(i.type,i.attributes),i.attributes)),y.returnType=g.returnType?this.getTypeInfo(g.returnType,g.attributes):null;continue}for(const i of this._functions.values())i.info&&(i.info.inUse=i.inUse,this._addCalls(i.node,i.info.calls));for(const i of this._functions.values())i.node.search(g=>{var x,v,_;if(g instanceof De){if(g.value)if(Ge(g.value))for(const v of g.value)for(const g of this.overrides)v===g.name&&(null===(x=i.info)||void 0===x||x.overrides.push(g));else for(const x of this.overrides)g.value===x.name&&(null===(v=i.info)||void 0===v||v.overrides.push(x))}else if(g instanceof ge)for(const x of this.overrides)g.name===x.name&&(null===(_=i.info)||void 0===_||_.overrides.push(x))});for(const i of this.uniforms)this._markStructsInUse(i.type);for(const i of this.storage)this._markStructsInUse(i.type)}getFunctionInfo(i){for(const g of this.functions)if(g.name==i)return g;return null}getStructInfo(i){for(const g of this.structs)if(g.name==i)return g;return null}getOverrideInfo(i){for(const g of this.overrides)if(g.name==i)return g;return null}_markStructsInUse(i){if(i)if(i.isStruct){if(i.inUse=!0,i.members)for(const g of i.members)this._markStructsInUse(g.type)}else if(i.isArray)this._markStructsInUse(i.format);else if(i.isTemplate)i.format&&this._markStructsInUse(i.format);else{const g=this._getAlias(i.name);g&&this._markStructsInUse(g)}}_addCalls(i,g){var x;for(const v of i.calls){const i=null===(x=this._functions.get(v.name))||void 0===x?void 0:x.info;i&&g.add(i)}}findResource(i,g,x){if(x){for(const v of this.entry.compute)if(v.name===x)for(const x of v.resources)if(x.group==i&&x.binding==g)return x;for(const v of this.entry.vertex)if(v.name===x)for(const x of v.resources)if(x.group==i&&x.binding==g)return x;for(const v of this.entry.fragment)if(v.name===x)for(const x of v.resources)if(x.group==i&&x.binding==g)return x}for(const x of this.uniforms)if(x.group==i&&x.binding==g)return x;for(const x of this.storage)if(x.group==i&&x.binding==g)return x;for(const x of this.textures)if(x.group==i&&x.binding==g)return x;for(const x of this.samplers)if(x.group==i&&x.binding==g)return x;return null}_findResource(i){for(const g of this.uniforms)if(g.name==i)return g;for(const g of this.storage)if(g.name==i)return g;for(const g of this.textures)if(g.name==i)return g;for(const g of this.samplers)if(g.name==i)return g;return null}_markStructsFromAST(i){const g=this.getTypeInfo(i,null);this._markStructsInUse(g)}_findResources(i,g){const x=[],v=this,_=[];return i.search(y=>{if(y instanceof E)_.push({});else if(y instanceof $)_.pop();else if(y instanceof F){const i=y;g&&null!==i.type&&this._markStructsFromAST(i.type),_.length>0&&(_[_.length-1][i.name]=i)}else if(y instanceof de){const i=y;g&&null!==i.type&&this._markStructsFromAST(i.type)}else if(y instanceof U){const i=y;g&&null!==i.type&&this._markStructsFromAST(i.type),_.length>0&&(_[_.length-1][i.name]=i)}else if(y instanceof ge){const i=y;if(_.length>0&&_[_.length-1][i.name])return;const g=v._findResource(i.name);g&&x.push(g)}else if(y instanceof me){const _=y,b=v._functions.get(_.name);b&&(g&&(b.inUse=!0),i.calls.add(b.node),null===b.resources&&(b.resources=v._findResources(b.node,g)),x.push(...b.resources))}else if(y instanceof X){const _=y,b=v._functions.get(_.name);b&&(g&&(b.inUse=!0),i.calls.add(b.node),null===b.resources&&(b.resources=v._findResources(b.node,g)),x.push(...b.resources))}}),[...new Map(x.map(i=>[i.name,i])).values()]}getBindGroups(){const i=[];function t(g,x){g>=i.length&&(i.length=g+1),void 0===i[g]&&(i[g]=[]),x>=i[g].length&&(i[g].length=x+1)}for(const g of this.uniforms)t(g.group,g.binding),i[g.group][g.binding]=g;for(const g of this.storage)t(g.group,g.binding),i[g.group][g.binding]=g;for(const g of this.textures)t(g.group,g.binding),i[g.group][g.binding]=g;for(const g of this.samplers)t(g.group,g.binding),i[g.group][g.binding]=g;return i}_getOutputs(i,g=void 0){if(void 0===g&&(g=[]),i instanceof oe)this._getStructOutputs(i,g);else{const x=this._getOutputInfo(i);null!==x&&g.push(x)}return g}_getStructOutputs(i,g){for(const x of i.members)if(x.type instanceof oe)this._getStructOutputs(x.type,g);else{const i=this._getAttribute(x,"location")||this._getAttribute(x,"builtin");if(null!==i){const v=this.getTypeInfo(x.type,x.type.attributes),_=this._parseInt(i.value),y=new u(x.name,v,i.name,_);g.push(y)}}}_getOutputInfo(i){const g=this._getAttribute(i,"location")||this._getAttribute(i,"builtin");if(null!==g){const x=this.getTypeInfo(i,i.attributes),v=this._parseInt(g.value);return new u("",x,g.name,v)}return null}_getInputs(i,g=void 0){void 0===g&&(g=[]);for(const x of i)if(x.type instanceof oe)this._getStructInputs(x.type,g);else{const i=this._getInputInfo(x);null!==i&&g.push(i)}return g}_getStructInputs(i,g){for(const x of i.members)if(x.type instanceof oe)this._getStructInputs(x.type,g);else{const i=this._getInputInfo(x);null!==i&&g.push(i)}}_getInputInfo(i){const g=this._getAttribute(i,"location")||this._getAttribute(i,"builtin");if(null!==g){const x=this._getAttribute(i,"interpolation"),v=this.getTypeInfo(i.type,i.attributes),_=this._parseInt(g.value),y=new l(i.name,v,g.name,_);return null!==x&&(y.interpolation=this._parseString(x.value)),y}return null}_parseString(i){return i instanceof Array&&(i=i[0]),i}_parseInt(i){i instanceof Array&&(i=i[0]);const g=parseInt(i);return isNaN(g)?i:g}_getAlias(i){for(const g of this.aliases)if(g.name==i)return g.type;return null}_getAliasInfo(i){return new c(i.name,this.getTypeInfo(i.type,null))}getTypeInfoByName(i){for(const g of this.structs)if(g.name==i)return g;for(const g of this.aliases)if(g.name==i)return g.type;return null}getTypeInfo(i,g=null){if(this._types.has(i))return this._types.get(i);if(i instanceof le){const x=i.type?this.getTypeInfo(i.type,i.attributes):null,v=new r(i.name,x,g);return this._types.set(i,v),this._updateTypeInfo(v),v}if(i instanceof ue){const x=i,v=x.format?this.getTypeInfo(x.format,x.attributes):null,_=new s(x.name,g);return _.format=v,_.count=x.count,this._types.set(i,_),this._updateTypeInfo(_),_}if(i instanceof oe){const x=i,v=new n(x.name,g);v.startLine=x.startLine,v.endLine=x.endLine;for(const i of x.members){const g=this.getTypeInfo(i.type,i.attributes);v.members.push(new t(i.name,g,i.attributes))}return this._types.set(i,v),this._updateTypeInfo(v),v}if(i instanceof he){const x=i,v=x.format instanceof ae,_=x.format?v?this.getTypeInfo(x.format,null):new e(x.format,null):null,y=new a(x.name,_,g,x.access);return this._types.set(i,y),this._updateTypeInfo(y),y}if(i instanceof ce){const x=i,v=x.format?this.getTypeInfo(x.format,null):null,_=new a(x.name,v,g,x.access);return this._types.set(i,_),this._updateTypeInfo(_),_}const x=new e(i.name,g);return this._types.set(i,x),this._updateTypeInfo(x),x}_updateTypeInfo(i){var g,x,v;const _=this._getTypeSize(i);if(i.size=null!==(g=null==_?void 0:_.size)&&void 0!==g?g:0,i instanceof s&&i.format){const g=this._getTypeSize(i.format);i.stride=Math.max(null!==(x=null==g?void 0:g.size)&&void 0!==x?x:0,null!==(v=null==g?void 0:g.align)&&void 0!==v?v:0),this._updateTypeInfo(i.format)}i instanceof r&&this._updateTypeInfo(i.format),i instanceof n&&this._updateStructInfo(i)}_updateStructInfo(i){var g;let x=0,v=0,_=0,y=0;for(let b=0,S=i.members.length;bi.name),at._samplerTypes=He.sampler_type.map(i=>i.name);let ni=0;class ot{constructor(i,g,x){this.id=ni++,this.name=i,this.value=g,this.node=x}clone(){return new ot(this.name,this.value,this.node)}}class ct{constructor(i){this.id=ni++,this.name=i.name,this.node=i}clone(){return new ct(this.node)}}class lt{constructor(i){this.parent=null,this.variables=new Map,this.functions=new Map,this.currentFunctionName="",this.id=ni++,i&&(this.parent=i,this.currentFunctionName=i.currentFunctionName)}getVariable(i){var g;return this.variables.has(i)?null!==(g=this.variables.get(i))&&void 0!==g?g:null:this.parent?this.parent.getVariable(i):null}getFunction(i){var g;return this.functions.has(i)?null!==(g=this.functions.get(i))&&void 0!==g?g:null:this.parent?this.parent.getFunction(i):null}createVariable(i,g,x){this.variables.set(i,new ot(i,g,null!=x?x:null))}setVariable(i,g,x){const v=this.getVariable(i);null!==v?v.value=g:this.createVariable(i,g,x)}getVariableValue(i){var g;const x=this.getVariable(i);return null!==(g=null==x?void 0:x.value)&&void 0!==g?g:null}clone(){return new lt(this)}}class ut{evalExpression(i,g){return null}getTypeInfo(i){return null}getVariableName(i,g){return""}}class ht{constructor(i){this.exec=i}getTypeInfo(i){return this.exec.getTypeInfo(i)}All(i,g){const x=this.exec.evalExpression(i.args[0],g);let v=!0;if(x instanceof Me)return x.data.forEach(i=>{i||(v=!1)}),new Be(v?1:0,this.getTypeInfo("bool"));throw new Error(`All() expects a vector argument. Line ${i.line}`)}Any(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me){const i=x.data.some(i=>i);return new Be(i?1:0,this.getTypeInfo("bool"))}throw new Error(`Any() expects a vector argument. Line ${i.line}`)}Select(i,g){const x=this.exec.evalExpression(i.args[2],g);if(!(x instanceof Be))throw new Error(`Select() expects a bool condition. Line ${i.line}`);return x.value?this.exec.evalExpression(i.args[1],g):this.exec.evalExpression(i.args[0],g)}ArrayLength(i,g){let x=i.args[0];x instanceof ke&&(x=x.right);const v=this.exec.evalExpression(x,g);if(v instanceof Pe&&0===v.typeInfo.size){const i=v.typeInfo,g=v.buffer.byteLength/i.stride;return new Be(g,this.getTypeInfo("u32"))}return new Be(v.typeInfo.size,this.getTypeInfo("u32"))}Abs(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.abs(i)),x.typeInfo);const v=x;return new Be(Math.abs(v.value),v.typeInfo)}Acos(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.acos(i)),x.typeInfo);const v=x;return new Be(Math.acos(v.value),x.typeInfo)}Acosh(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.acosh(i)),x.typeInfo);const v=x;return new Be(Math.acosh(v.value),x.typeInfo)}Asin(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.asin(i)),x.typeInfo);const v=x;return new Be(Math.asin(v.value),x.typeInfo)}Asinh(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.asinh(i)),x.typeInfo);const v=x;return new Be(Math.asinh(v.value),x.typeInfo)}Atan(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.atan(i)),x.typeInfo);const v=x;return new Be(Math.atan(v.value),x.typeInfo)}Atanh(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.atanh(i)),x.typeInfo);const v=x;return new Be(Math.atanh(v.value),x.typeInfo)}Atan2(i,g){const x=this.exec.evalExpression(i.args[0],g),v=this.exec.evalExpression(i.args[1],g);if(x instanceof Me&&v instanceof Me)return new Me(x.data.map((i,g)=>Math.atan2(i,v.data[g])),x.typeInfo);const _=x,y=v;return new Be(Math.atan2(_.value,y.value),x.typeInfo)}Ceil(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.ceil(i)),x.typeInfo);const v=x;return new Be(Math.ceil(v.value),x.typeInfo)}_clamp(i,g,x){return Math.min(Math.max(i,g),x)}Clamp(i,g){const x=this.exec.evalExpression(i.args[0],g),v=this.exec.evalExpression(i.args[1],g),_=this.exec.evalExpression(i.args[2],g);if(x instanceof Me&&v instanceof Me&&_ instanceof Me)return new Me(x.data.map((i,g)=>this._clamp(i,v.data[g],_.data[g])),x.typeInfo);const y=x,b=v,S=_;return new Be(this._clamp(y.value,b.value,S.value),x.typeInfo)}Cos(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.cos(i)),x.typeInfo);const v=x;return new Be(Math.cos(v.value),x.typeInfo)}Cosh(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.cosh(i)),x.typeInfo);const v=x;return new Be(Math.cos(v.value),x.typeInfo)}CountLeadingZeros(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.clz32(i)),x.typeInfo);const v=x;return new Be(Math.clz32(v.value),x.typeInfo)}_countOneBits(i){let g=0;for(;0!==i;)1&i&&g++,i>>=1;return g}CountOneBits(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>this._countOneBits(i)),x.typeInfo);const v=x;return new Be(this._countOneBits(v.value),x.typeInfo)}_countTrailingZeros(i){if(0===i)return 32;let g=0;for(;!(1&i);)i>>=1,g++;return g}CountTrailingZeros(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>this._countTrailingZeros(i)),x.typeInfo);const v=x;return new Be(this._countTrailingZeros(v.value),x.typeInfo)}Cross(i,g){const x=this.exec.evalExpression(i.args[0],g),v=this.exec.evalExpression(i.args[1],g);if(x instanceof Me&&v instanceof Me){if(3!==x.data.length||3!==v.data.length)return console.error(`Cross() expects 3D vectors. Line ${i.line}`),null;const g=x.data,_=v.data;return new Me([g[1]*_[2]-_[1]*g[2],g[2]*_[0]-_[2]*g[0],g[0]*_[1]-_[0]*g[1]],x.typeInfo)}return console.error(`Cross() expects vector arguments. Line ${i.line}`),null}Degrees(i,g){const x=this.exec.evalExpression(i.args[0],g),v=180/Math.PI;return x instanceof Me?new Me(x.data.map(i=>i*v),x.typeInfo):new Be(x.value*v,this.getTypeInfo("f32"))}Determinant(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Ue){const i=x.data,g=x.typeInfo.getTypeName(),v=g.endsWith("h")?this.getTypeInfo("f16"):this.getTypeInfo("f32");if("mat2x2"===g||"mat2x2f"===g||"mat2x2h"===g)return new Be(i[0]*i[3]-i[1]*i[2],v);if("mat2x3"===g||"mat2x3f"===g||"mat2x3h"===g)return new Be(i[0]*(i[4]*i[8]-i[5]*i[7])-i[1]*(i[3]*i[8]-i[5]*i[6])+i[2]*(i[3]*i[7]-i[4]*i[6]),v);if("mat2x4"===g||"mat2x4f"===g||"mat2x4h"===g)console.error(`TODO: Determinant for ${g}`);else if("mat3x2"===g||"mat3x2f"===g||"mat3x2h"===g)console.error(`TODO: Determinant for ${g}`);else{if("mat3x3"===g||"mat3x3f"===g||"mat3x3h"===g)return new Be(i[0]*(i[4]*i[8]-i[5]*i[7])-i[1]*(i[3]*i[8]-i[5]*i[6])+i[2]*(i[3]*i[7]-i[4]*i[6]),v);"mat3x4"===g||"mat3x4f"===g||"mat3x4h"===g||"mat4x2"===g||"mat4x2f"===g||"mat4x2h"===g||"mat4x3"===g||"mat4x3f"===g||"mat4x3h"===g?console.error(`TODO: Determinant for ${g}`):"mat4x4"!==g&&"mat4x4f"!==g&&"mat4x4h"!==g||console.error(`TODO: Determinant for ${g}`)}}return console.error(`Determinant expects a matrix argument. Line ${i.line}`),null}Distance(i,g){const x=this.exec.evalExpression(i.args[0],g),v=this.exec.evalExpression(i.args[1],g);if(x instanceof Me&&v instanceof Me){let i=0;for(let g=0;gMath.exp(i)),x.typeInfo);const v=x;return new Be(Math.exp(v.value),x.typeInfo)}Exp2(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.pow(2,i)),x.typeInfo);const v=x;return new Be(Math.pow(2,v.value),x.typeInfo)}ExtractBits(i,g){const x=this.exec.evalExpression(i.args[0],g),v=this.exec.evalExpression(i.args[1],g),_=this.exec.evalExpression(i.args[2],g);if("u32"!==v.typeInfo.name&&"x32"!==v.typeInfo.name)return console.error(`ExtractBits() expects an i32 offset argument. Line ${i.line}`),null;if("u32"!==_.typeInfo.name&&"x32"!==_.typeInfo.name)return console.error(`ExtractBits() expects an i32 count argument. Line ${i.line}`),null;const y=v.value,b=_.value;if(x instanceof Me)return new Me(x.data.map(i=>i>>y&(1<>y&(1<-i),x.typeInfo)}return console.error(`FaceForward() expects vector arguments. Line ${i.line}`),null}_firstLeadingBit(i){return 0===i?-1:31-Math.clz32(i)}FirstLeadingBit(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>this._firstLeadingBit(i)),x.typeInfo);const v=x;return new Be(this._firstLeadingBit(v.value),x.typeInfo)}_firstTrailingBit(i){return 0===i?-1:Math.log2(i&-i)}FirstTrailingBit(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>this._firstTrailingBit(i)),x.typeInfo);const v=x;return new Be(this._firstTrailingBit(v.value),x.typeInfo)}Floor(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.floor(i)),x.typeInfo);const v=x;return new Be(Math.floor(v.value),x.typeInfo)}Fma(i,g){const x=this.exec.evalExpression(i.args[0],g),v=this.exec.evalExpression(i.args[1],g),_=this.exec.evalExpression(i.args[2],g);if(x instanceof Me&&v instanceof Me&&_ instanceof Me)return x.data.length!==v.data.length||x.data.length!==_.data.length?(console.error(`Fma() expects vectors of the same length. Line ${i.line}`),null):new Me(x.data.map((i,g)=>i*v.data[g]+_.data[g]),x.typeInfo);const y=x,b=v,S=_;return new Be(y.value*b.value+S.value,y.typeInfo)}Fract(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>i-Math.floor(i)),x.typeInfo);const v=x;return new Be(v.value-Math.floor(v.value),x.typeInfo)}Frexp(i,g){return console.error(`TODO: frexp. Line ${i.line}`),null}InsertBits(i,g){const x=this.exec.evalExpression(i.args[0],g),v=this.exec.evalExpression(i.args[1],g),_=this.exec.evalExpression(i.args[2],g),y=this.exec.evalExpression(i.args[3],g);if("u32"!==_.typeInfo.name&&"x32"!==_.typeInfo.name)return console.error(`InsertBits() expects an i32 offset argument. Line ${i.line}`),null;const b=_.value,S=(1<i&w|v.data[g]<1/Math.sqrt(i)),x.typeInfo);const v=x;return new Be(1/Math.sqrt(v.value),x.typeInfo)}Ldexp(i,g){return console.error(`TODO: ldexp. Line ${i.line}`),null}Length(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me){let i=0;return x.data.forEach(g=>{i+=g*g}),new Be(Math.sqrt(i),this.getTypeInfo("f32"))}const v=x;return new Be(Math.abs(v.value),x.typeInfo)}Log(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.log(i)),x.typeInfo);const v=x;return new Be(Math.log(v.value),x.typeInfo)}Log2(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.log2(i)),x.typeInfo);const v=x;return new Be(Math.log2(v.value),x.typeInfo)}Max(i,g){const x=this.exec.evalExpression(i.args[0],g),v=this.exec.evalExpression(i.args[1],g);if(x instanceof Me&&v instanceof Me)return new Me(x.data.map((i,g)=>Math.max(i,v.data[g])),x.typeInfo);const _=x,y=v;return new Be(Math.max(_.value,y.value),x.typeInfo)}Min(i,g){const x=this.exec.evalExpression(i.args[0],g),v=this.exec.evalExpression(i.args[1],g);if(x instanceof Me&&v instanceof Me)return new Me(x.data.map((i,g)=>Math.min(i,v.data[g])),x.typeInfo);const _=x,y=v;return new Be(Math.min(_.value,y.value),x.typeInfo)}Mix(i,g){const x=this.exec.evalExpression(i.args[0],g),v=this.exec.evalExpression(i.args[1],g),_=this.exec.evalExpression(i.args[2],g);if(x instanceof Me&&v instanceof Me&&_ instanceof Me)return new Me(x.data.map((i,g)=>x.data[g]*(1-_.data[g])+v.data[g]*_.data[g]),x.typeInfo);const y=v,b=_;return new Be(x.value*(1-b.value)+y.value*b.value,x.typeInfo)}Modf(i,g){const x=this.exec.evalExpression(i.args[0],g),v=this.exec.evalExpression(i.args[1],g);if(x instanceof Me&&v instanceof Me)return new Me(x.data.map((i,g)=>i%v.data[g]),x.typeInfo);const _=v;return new Be(x.value%_.value,x.typeInfo)}Normalize(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me){const v=this.Length(i,g).value;return new Me(x.data.map(i=>i/v),x.typeInfo)}return console.error(`Normalize() expects a vector argument. Line ${i.line}`),null}Pow(i,g){const x=this.exec.evalExpression(i.args[0],g),v=this.exec.evalExpression(i.args[1],g);if(x instanceof Me&&v instanceof Me)return new Me(x.data.map((i,g)=>Math.pow(i,v.data[g])),x.typeInfo);const _=x,y=v;return new Be(Math.pow(_.value,y.value),x.typeInfo)}QuantizeToF16(i,g){const x=this.exec.evalExpression(i.args[0],g);return x instanceof Me?new Me(x.data.map(i=>i),x.typeInfo):new Be(x.value,x.typeInfo)}Radians(i,g){const x=this.exec.evalExpression(i.args[0],g);return x instanceof Me?new Me(x.data.map(i=>i*Math.PI/180),x.typeInfo):new Be(x.value*Math.PI/180,this.getTypeInfo("f32"))}Reflect(i,g){let x=this.exec.evalExpression(i.args[0],g),v=this.exec.evalExpression(i.args[1],g);if(x instanceof Me&&v instanceof Me){const i=this._dot(x.data,v.data);return new Me(x.data.map((g,x)=>g-2*i*v.data[x]),x.typeInfo)}return console.error(`Reflect() expects vector arguments. Line ${i.line}`),null}Refract(i,g){let x=this.exec.evalExpression(i.args[0],g),v=this.exec.evalExpression(i.args[1],g),_=this.exec.evalExpression(i.args[2],g);if(x instanceof Me&&v instanceof Me&&_ instanceof Be){const i=this._dot(v.data,x.data);return new Me(x.data.map((g,x)=>{const y=1-_.value*_.value*(1-i*i);if(y<0)return 0;const b=Math.sqrt(y);return _.value*g-(_.value*i+b)*v.data[x]}),x.typeInfo)}return console.error(`Refract() expects vector arguments and a scalar argument. Line ${i.line}`),null}ReverseBits(i,g){return console.error(`TODO: reverseBits. Line ${i.line}`),null}Round(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.round(i)),x.typeInfo);const v=x;return new Be(Math.round(v.value),x.typeInfo)}Saturate(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.min(Math.max(i,0),1)),x.typeInfo);const v=x;return new Be(Math.min(Math.max(v.value,0),1),x.typeInfo)}Sign(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.sign(i)),x.typeInfo);const v=x;return new Be(Math.sign(v.value),x.typeInfo)}Sin(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.sin(i)),x.typeInfo);const v=x;return new Be(Math.sin(v.value),x.typeInfo)}Sinh(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.sinh(i)),x.typeInfo);const v=x;return new Be(Math.sinh(v.value),x.typeInfo)}_smoothstep(i,g,x){const v=Math.min(Math.max((x-i)/(g-i),0),1);return v*v*(3-2*v)}SmoothStep(i,g){const x=this.exec.evalExpression(i.args[0],g),v=this.exec.evalExpression(i.args[1],g),_=this.exec.evalExpression(i.args[2],g);if(_ instanceof Me&&x instanceof Me&&v instanceof Me)return new Me(_.data.map((i,g)=>this._smoothstep(x.data[g],v.data[g],i)),_.typeInfo);const y=x,b=v,S=_;return new Be(this._smoothstep(y.value,b.value,S.value),_.typeInfo)}Sqrt(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.sqrt(i)),x.typeInfo);const v=x;return new Be(Math.sqrt(v.value),x.typeInfo)}Step(i,g){const x=this.exec.evalExpression(i.args[0],g),v=this.exec.evalExpression(i.args[1],g);if(v instanceof Me&&x instanceof Me)return new Me(v.data.map((i,g)=>iMath.tan(i)),x.typeInfo);const v=x;return new Be(Math.tan(v.value),x.typeInfo)}Tanh(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.tanh(i)),x.typeInfo);const v=x;return new Be(Math.tanh(v.value),x.typeInfo)}_getTransposeType(i){const g=i.getTypeName();return"mat2x2f"===g||"mat2x2h"===g?i:"mat2x3f"===g?this.getTypeInfo("mat3x2f"):"mat2x3h"===g?this.getTypeInfo("mat3x2h"):"mat2x4f"===g?this.getTypeInfo("mat4x2f"):"mat2x4h"===g?this.getTypeInfo("mat4x2h"):"mat3x2f"===g?this.getTypeInfo("mat2x3f"):"mat3x2h"===g?this.getTypeInfo("mat2x3h"):"mat3x3f"===g||"mat3x3h"===g?i:"mat3x4f"===g?this.getTypeInfo("mat4x3f"):"mat3x4h"===g?this.getTypeInfo("mat4x3h"):"mat4x2f"===g?this.getTypeInfo("mat2x4f"):"mat4x2h"===g?this.getTypeInfo("mat2x4h"):"mat4x3f"===g?this.getTypeInfo("mat3x4f"):"mat4x3h"===g?this.getTypeInfo("mat3x4h"):("mat4x4f"===g||"mat4x4h"===g||console.error(`Invalid matrix type ${g}`),i)}Transpose(i,g){const x=this.exec.evalExpression(i.args[0],g);if(!(x instanceof Ue))return console.error(`Transpose() expects a matrix argument. Line ${i.line}`),null;const v=this._getTransposeType(x.typeInfo);if("mat2x2"===x.typeInfo.name||"mat2x2f"===x.typeInfo.name||"mat2x2h"===x.typeInfo.name){const i=x.data;return new Ue([i[0],i[2],i[1],i[3]],v)}if("mat2x3"===x.typeInfo.name||"mat2x3f"===x.typeInfo.name||"mat2x3h"===x.typeInfo.name){const i=x.data;return new Ue([i[0],i[3],i[6],i[1],i[4],i[7]],v)}if("mat2x4"===x.typeInfo.name||"mat2x4f"===x.typeInfo.name||"mat2x4h"===x.typeInfo.name){const i=x.data;return new Ue([i[0],i[4],i[8],i[12],i[1],i[5],i[9],i[13]],v)}if("mat3x2"===x.typeInfo.name||"mat3x2f"===x.typeInfo.name||"mat3x2h"===x.typeInfo.name){const i=x.data;return new Ue([i[0],i[3],i[1],i[4],i[2],i[5]],v)}if("mat3x3"===x.typeInfo.name||"mat3x3f"===x.typeInfo.name||"mat3x3h"===x.typeInfo.name){const i=x.data;return new Ue([i[0],i[3],i[6],i[1],i[4],i[7],i[2],i[5],i[8]],v)}if("mat3x4"===x.typeInfo.name||"mat3x4f"===x.typeInfo.name||"mat3x4h"===x.typeInfo.name){const i=x.data;return new Ue([i[0],i[4],i[8],i[12],i[1],i[5],i[9],i[13],i[2],i[6],i[10],i[14]],v)}if("mat4x2"===x.typeInfo.name||"mat4x2f"===x.typeInfo.name||"mat4x2h"===x.typeInfo.name){const i=x.data;return new Ue([i[0],i[4],i[1],i[5],i[2],i[6]],v)}if("mat4x3"===x.typeInfo.name||"mat4x3f"===x.typeInfo.name||"mat4x3h"===x.typeInfo.name){const i=x.data;return new Ue([i[0],i[4],i[8],i[1],i[5],i[9],i[2],i[6],i[10]],v)}if("mat4x4"===x.typeInfo.name||"mat4x4f"===x.typeInfo.name||"mat4x4h"===x.typeInfo.name){const i=x.data;return new Ue([i[0],i[4],i[8],i[12],i[1],i[5],i[9],i[13],i[2],i[6],i[10],i[14],i[3],i[7],i[11],i[15]],v)}return console.error(`Invalid matrix type ${x.typeInfo.name}`),null}Trunc(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.trunc(i)),x.typeInfo);const v=x;return new Be(Math.trunc(v.value),x.typeInfo)}Dpdx(i,g){return console.error(`TODO: dpdx. Line ${i.line}`),null}DpdxCoarse(i,g){return console.error(`TODO: dpdxCoarse. Line ${i.line}`),null}DpdxFine(i,g){return console.error("TODO: dpdxFine"),null}Dpdy(i,g){return console.error("TODO: dpdy"),null}DpdyCoarse(i,g){return console.error("TODO: dpdyCoarse"),null}DpdyFine(i,g){return console.error("TODO: dpdyFine"),null}Fwidth(i,g){return console.error("TODO: fwidth"),null}FwidthCoarse(i,g){return console.error("TODO: fwidthCoarse"),null}FwidthFine(i,g){return console.error("TODO: fwidthFine"),null}TextureDimensions(i,g){const x=i.args[0],v=i.args.length>1?this.exec.evalExpression(i.args[1],g).value:0;if(x instanceof ge){const _=x.name,y=g.getVariableValue(_);if(y instanceof We){if(v<0||v>=y.mipLevelCount)return console.error(`Invalid mip level for textureDimensions. Line ${i.line}`),null;const g=y.getMipLevelSize(v),x=y.dimension;return"1d"===x?new Be(g[0],this.getTypeInfo("u32")):"3d"===x?new Me(g,this.getTypeInfo("vec3u")):"2d"===x?new Me(g.slice(0,2),this.getTypeInfo("vec2u")):(console.error(`Invalid texture dimension ${x} not found. Line ${i.line}`),null)}return console.error(`Texture ${_} not found. Line ${i.line}`),null}return console.error(`Invalid texture argument for textureDimensions. Line ${i.line}`),null}TextureGather(i,g){return console.error("TODO: textureGather"),null}TextureGatherCompare(i,g){return console.error("TODO: textureGatherCompare"),null}TextureLoad(i,g){const x=i.args[0],v=this.exec.evalExpression(i.args[1],g),_=i.args.length>2?this.exec.evalExpression(i.args[2],g).value:0;if(!(v instanceof Me)||2!==v.data.length)return console.error(`Invalid UV argument for textureLoad. Line ${i.line}`),null;if(x instanceof ge){const y=x.name,b=g.getVariableValue(y);if(b instanceof We){const g=Math.floor(v.data[0]),x=Math.floor(v.data[1]);if(g<0||g>=b.width||x<0||x>=b.height)return console.error(`Texture ${y} out of bounds. Line ${i.line}`),null;const S=b.getPixel(g,x,0,_);return null===S?(console.error(`Invalid texture format for textureLoad. Line ${i.line}`),null):new Me(S,this.getTypeInfo("vec4f"))}return console.error(`Texture ${y} not found. Line ${i.line}`),null}return console.error(`Invalid texture argument for textureLoad. Line ${i.line}`),null}TextureNumLayers(i,g){const x=i.args[0];if(x instanceof ge){const v=x.name,_=g.getVariableValue(v);return _ instanceof We?new Be(_.depthOrArrayLayers,this.getTypeInfo("u32")):(console.error(`Texture ${v} not found. Line ${i.line}`),null)}return console.error(`Invalid texture argument for textureNumLayers. Line ${i.line}`),null}TextureNumLevels(i,g){const x=i.args[0];if(x instanceof ge){const v=x.name,_=g.getVariableValue(v);return _ instanceof We?new Be(_.mipLevelCount,this.getTypeInfo("u32")):(console.error(`Texture ${v} not found. Line ${i.line}`),null)}return console.error(`Invalid texture argument for textureNumLevels. Line ${i.line}`),null}TextureNumSamples(i,g){const x=i.args[0];if(x instanceof ge){const v=x.name,_=g.getVariableValue(v);return _ instanceof We?new Be(_.sampleCount,this.getTypeInfo("u32")):(console.error(`Texture ${v} not found. Line ${i.line}`),null)}return console.error(`Invalid texture argument for textureNumSamples. Line ${i.line}`),null}TextureSample(i,g){return console.error("TODO: textureSample"),null}TextureSampleBias(i,g){return console.error("TODO: textureSampleBias"),null}TextureSampleCompare(i,g){return console.error("TODO: textureSampleCompare"),null}TextureSampleCompareLevel(i,g){return console.error("TODO: textureSampleCompareLevel"),null}TextureSampleGrad(i,g){return console.error("TODO: textureSampleGrad"),null}TextureSampleLevel(i,g){return console.error("TODO: textureSampleLevel"),null}TextureSampleBaseClampToEdge(i,g){return console.error("TODO: textureSampleBaseClampToEdge"),null}TextureStore(i,g){const x=i.args[0],v=this.exec.evalExpression(i.args[1],g),_=4===i.args.length?this.exec.evalExpression(i.args[2],g).value:0,y=4===i.args.length?this.exec.evalExpression(i.args[3],g).data:this.exec.evalExpression(i.args[2],g).data;if(4!==y.length)return console.error(`Invalid value argument for textureStore. Line ${i.line}`),null;if(!(v instanceof Me)||2!==v.data.length)return console.error(`Invalid UV argument for textureStore. Line ${i.line}`),null;if(x instanceof ge){const b=x.name,S=g.getVariableValue(b);if(S instanceof We){const g=S.getMipLevelSize(0),x=Math.floor(v.data[0]),w=Math.floor(v.data[1]);return x<0||x>=g[0]||w<0||w>=g[1]?(console.error(`Texture ${b} out of bounds. Line ${i.line}`),null):(S.setPixel(x,w,0,_,Array.from(y)),null)}return console.error(`Texture ${b} not found. Line ${i.line}`),null}return console.error(`Invalid texture argument for textureStore. Line ${i.line}`),null}AtomicLoad(i,g){let x=i.args[0];x instanceof ke&&(x=x.right);const v=this.exec.getVariableName(x,g);return g.getVariable(v).value.getSubData(this.exec,x.postfix,g)}AtomicStore(i,g){let x=i.args[0];x instanceof ke&&(x=x.right);const v=this.exec.getVariableName(x,g),_=g.getVariable(v);let y=i.args[1];const b=this.exec.evalExpression(y,g),S=_.value.getSubData(this.exec,x.postfix,g);return S instanceof Be&&b instanceof Be&&(S.value=b.value),_.value instanceof Pe&&_.value.setDataValue(this.exec,S,x.postfix,g),null}AtomicAdd(i,g){let x=i.args[0];x instanceof ke&&(x=x.right);const v=this.exec.getVariableName(x,g),_=g.getVariable(v);let y=i.args[1];const b=this.exec.evalExpression(y,g),S=_.value.getSubData(this.exec,x.postfix,g),w=new Be(S.value,S.typeInfo);return S instanceof Be&&b instanceof Be&&(S.value+=b.value),_.value instanceof Pe&&_.value.setDataValue(this.exec,S,x.postfix,g),w}AtomicSub(i,g){let x=i.args[0];x instanceof ke&&(x=x.right);const v=this.exec.getVariableName(x,g),_=g.getVariable(v);let y=i.args[1];const b=this.exec.evalExpression(y,g),S=_.value.getSubData(this.exec,x.postfix,g),w=new Be(S.value,S.typeInfo);return S instanceof Be&&b instanceof Be&&(S.value-=b.value),_.value instanceof Pe&&_.value.setDataValue(this.exec,S,x.postfix,g),w}AtomicMax(i,g){let x=i.args[0];x instanceof ke&&(x=x.right);const v=this.exec.getVariableName(x,g),_=g.getVariable(v);let y=i.args[1];const b=this.exec.evalExpression(y,g),S=_.value.getSubData(this.exec,x.postfix,g),w=new Be(S.value,S.typeInfo);return S instanceof Be&&b instanceof Be&&(S.value=Math.max(S.value,b.value)),_.value instanceof Pe&&_.value.setDataValue(this.exec,S,x.postfix,g),w}AtomicMin(i,g){let x=i.args[0];x instanceof ke&&(x=x.right);const v=this.exec.getVariableName(x,g),_=g.getVariable(v);let y=i.args[1];const b=this.exec.evalExpression(y,g),S=_.value.getSubData(this.exec,x.postfix,g),w=new Be(S.value,S.typeInfo);return S instanceof Be&&b instanceof Be&&(S.value=Math.min(S.value,b.value)),_.value instanceof Pe&&_.value.setDataValue(this.exec,S,x.postfix,g),w}AtomicAnd(i,g){let x=i.args[0];x instanceof ke&&(x=x.right);const v=this.exec.getVariableName(x,g),_=g.getVariable(v);let y=i.args[1];const b=this.exec.evalExpression(y,g),S=_.value.getSubData(this.exec,x.postfix,g),w=new Be(S.value,S.typeInfo);return S instanceof Be&&b instanceof Be&&(S.value=S.value&b.value),_.value instanceof Pe&&_.value.setDataValue(this.exec,S,x.postfix,g),w}AtomicOr(i,g){let x=i.args[0];x instanceof ke&&(x=x.right);const v=this.exec.getVariableName(x,g),_=g.getVariable(v);let y=i.args[1];const b=this.exec.evalExpression(y,g),S=_.value.getSubData(this.exec,x.postfix,g),w=new Be(S.value,S.typeInfo);return S instanceof Be&&b instanceof Be&&(S.value=S.value|b.value),_.value instanceof Pe&&_.value.setDataValue(this.exec,S,x.postfix,g),w}AtomicXor(i,g){let x=i.args[0];x instanceof ke&&(x=x.right);const v=this.exec.getVariableName(x,g),_=g.getVariable(v);let y=i.args[1];const b=this.exec.evalExpression(y,g),S=_.value.getSubData(this.exec,x.postfix,g),w=new Be(S.value,S.typeInfo);return S instanceof Be&&b instanceof Be&&(S.value=S.value^b.value),_.value instanceof Pe&&_.value.setDataValue(this.exec,S,x.postfix,g),w}AtomicExchange(i,g){let x=i.args[0];x instanceof ke&&(x=x.right);const v=this.exec.getVariableName(x,g),_=g.getVariable(v);let y=i.args[1];const b=this.exec.evalExpression(y,g),S=_.value.getSubData(this.exec,x.postfix,g),w=new Be(S.value,S.typeInfo);return S instanceof Be&&b instanceof Be&&(S.value=b.value),_.value instanceof Pe&&_.value.setDataValue(this.exec,S,x.postfix,g),w}AtomicCompareExchangeWeak(i,g){return console.error("TODO: atomicCompareExchangeWeak"),null}Pack4x8snorm(i,g){return console.error("TODO: pack4x8snorm"),null}Pack4x8unorm(i,g){return console.error("TODO: pack4x8unorm"),null}Pack4xI8(i,g){return console.error("TODO: pack4xI8"),null}Pack4xU8(i,g){return console.error("TODO: pack4xU8"),null}Pack4x8Clamp(i,g){return console.error("TODO: pack4x8Clamp"),null}Pack4xU8Clamp(i,g){return console.error("TODO: pack4xU8Clamp"),null}Pack2x16snorm(i,g){return console.error("TODO: pack2x16snorm"),null}Pack2x16unorm(i,g){return console.error("TODO: pack2x16unorm"),null}Pack2x16float(i,g){return console.error("TODO: pack2x16float"),null}Unpack4x8snorm(i,g){return console.error("TODO: unpack4x8snorm"),null}Unpack4x8unorm(i,g){return console.error("TODO: unpack4x8unorm"),null}Unpack4xI8(i,g){return console.error("TODO: unpack4xI8"),null}Unpack4xU8(i,g){return console.error("TODO: unpack4xU8"),null}Unpack2x16snorm(i,g){return console.error("TODO: unpack2x16snorm"),null}Unpack2x16unorm(i,g){return console.error("TODO: unpack2x16unorm"),null}Unpack2x16float(i,g){return console.error("TODO: unpack2x16float"),null}StorageBarrier(i,g){return null}TextureBarrier(i,g){return null}WorkgroupBarrier(i,g){return null}WorkgroupUniformLoad(i,g){return null}SubgroupAdd(i,g){return console.error("TODO: subgroupAdd"),null}SubgroupExclusiveAdd(i,g){return console.error("TODO: subgroupExclusiveAdd"),null}SubgroupInclusiveAdd(i,g){return console.error("TODO: subgroupInclusiveAdd"),null}SubgroupAll(i,g){return console.error("TODO: subgroupAll"),null}SubgroupAnd(i,g){return console.error("TODO: subgroupAnd"),null}SubgroupAny(i,g){return console.error("TODO: subgroupAny"),null}SubgroupBallot(i,g){return console.error("TODO: subgroupBallot"),null}SubgroupBroadcast(i,g){return console.error("TODO: subgroupBroadcast"),null}SubgroupBroadcastFirst(i,g){return console.error("TODO: subgroupBroadcastFirst"),null}SubgroupElect(i,g){return console.error("TODO: subgroupElect"),null}SubgroupMax(i,g){return console.error("TODO: subgroupMax"),null}SubgroupMin(i,g){return console.error("TODO: subgroupMin"),null}SubgroupMul(i,g){return console.error("TODO: subgroupMul"),null}SubgroupExclusiveMul(i,g){return console.error("TODO: subgroupExclusiveMul"),null}SubgroupInclusiveMul(i,g){return console.error("TODO: subgroupInclusiveMul"),null}SubgroupOr(i,g){return console.error("TODO: subgroupOr"),null}SubgroupShuffle(i,g){return console.error("TODO: subgroupShuffle"),null}SubgroupShuffleDown(i,g){return console.error("TODO: subgroupShuffleDown"),null}SubgroupShuffleUp(i,g){return console.error("TODO: subgroupShuffleUp"),null}SubgroupShuffleXor(i,g){return console.error("TODO: subgroupShuffleXor"),null}SubgroupXor(i,g){return console.error("TODO: subgroupXor"),null}QuadBroadcast(i,g){return console.error("TODO: quadBroadcast"),null}QuadSwapDiagonal(i,g){return console.error("TODO: quadSwapDiagonal"),null}QuadSwapX(i,g){return console.error("TODO: quadSwapX"),null}QuadSwapY(i,g){return console.error("TODO: quadSwapY"),null}}const ai={vec2:2,vec2f:2,vec2i:2,vec2u:2,vec2b:2,vec2h:2,vec3:3,vec3f:3,vec3i:3,vec3u:3,vec3b:3,vec3h:3,vec4:4,vec4f:4,vec4i:4,vec4u:4,vec4b:4,vec4h:4},si={mat2x2:[2,2,4],mat2x2f:[2,2,4],mat2x2h:[2,2,4],mat2x3:[2,3,6],mat2x3f:[2,3,6],mat2x3h:[2,3,6],mat2x4:[2,4,8],mat2x4f:[2,4,8],mat2x4h:[2,4,8],mat3x2:[3,2,6],mat3x2f:[3,2,6],mat3x2h:[3,2,6],mat3x3:[3,3,9],mat3x3f:[3,3,9],mat3x3h:[3,3,9],mat3x4:[3,4,12],mat3x4f:[3,4,12],mat3x4h:[3,4,12],mat4x2:[4,2,8],mat4x2f:[4,2,8],mat4x2h:[4,2,8],mat4x3:[4,3,12],mat4x3f:[4,3,12],mat4x3h:[4,3,12],mat4x4:[4,4,16],mat4x4f:[4,4,16],mat4x4h:[4,4,16]};class dt extends ut{constructor(i,g){var x;super(),this.ast=null!=i?i:[],this.reflection=new at,this.reflection.updateAST(this.ast),this.context=null!==(x=null==g?void 0:g.clone())&&void 0!==x?x:new lt,this.builtins=new ht(this),this.typeInfo={bool:this.getTypeInfo(ae.bool),i32:this.getTypeInfo(ae.i32),u32:this.getTypeInfo(ae.u32),f32:this.getTypeInfo(ae.f32),f16:this.getTypeInfo(ae.f16),vec2f:this.getTypeInfo(ce.vec2f),vec2u:this.getTypeInfo(ce.vec2u),vec2i:this.getTypeInfo(ce.vec2i),vec2h:this.getTypeInfo(ce.vec2h),vec3f:this.getTypeInfo(ce.vec3f),vec3u:this.getTypeInfo(ce.vec3u),vec3i:this.getTypeInfo(ce.vec3i),vec3h:this.getTypeInfo(ce.vec3h),vec4f:this.getTypeInfo(ce.vec4f),vec4u:this.getTypeInfo(ce.vec4u),vec4i:this.getTypeInfo(ce.vec4i),vec4h:this.getTypeInfo(ce.vec4h),mat2x2f:this.getTypeInfo(ce.mat2x2f),mat2x3f:this.getTypeInfo(ce.mat2x3f),mat2x4f:this.getTypeInfo(ce.mat2x4f),mat3x2f:this.getTypeInfo(ce.mat3x2f),mat3x3f:this.getTypeInfo(ce.mat3x3f),mat3x4f:this.getTypeInfo(ce.mat3x4f),mat4x2f:this.getTypeInfo(ce.mat4x2f),mat4x3f:this.getTypeInfo(ce.mat4x3f),mat4x4f:this.getTypeInfo(ce.mat4x4f)}}getVariableValue(i){var g,x;const v=null!==(x=null===(g=this.context.getVariable(i))||void 0===g?void 0:g.value)&&void 0!==x?x:null;if(null===v)return null;if(v instanceof Be)return v.value;if(v instanceof Me)return Array.from(v.data);if(v instanceof Ue)return Array.from(v.data);if(v instanceof Pe&&v.typeInfo instanceof s){if("u32"===v.typeInfo.format.name)return Array.from(new Uint32Array(v.buffer,v.offset,v.typeInfo.count));if("i32"===v.typeInfo.format.name)return Array.from(new Int32Array(v.buffer,v.offset,v.typeInfo.count));if("f32"===v.typeInfo.format.name)return Array.from(new Float32Array(v.buffer,v.offset,v.typeInfo.count))}return console.error(`Unsupported return variable type ${v.typeInfo.name}`),null}execute(i){(i=null!=i?i:{}).constants&&this._setOverrides(i.constants,this.context),this._execStatements(this.ast,this.context)}dispatchWorkgroups(i,g,x,v){const _=this.context.clone();(v=null!=v?v:{}).constants&&this._setOverrides(v.constants,_),this._execStatements(this.ast,_);const y=_.getFunction(i);if(!y)return void console.error(`Function ${i} not found`);if("number"==typeof g)g=[g,1,1];else{if(0===g.length)return void console.error("Invalid dispatch count");1===g.length?g=[g[0],1,1]:2===g.length?g=[g[0],g[1],1]:g.length>3&&(g=[g[0],g[1],g[2]])}const b=g[0],S=g[1],w=g[2],L=this.getTypeInfo("vec3u");_.setVariable("@num_workgroups",new Me(g,L));const k=this.reflection.getFunctionInfo(i);null===k&&console.error(`Function ${i} not found in reflection data`);for(const i in x)for(const g in x[i]){const v=x[i][g];_.variables.forEach(x=>{var _;const y=x.node;if(null==y?void 0:y.attributes){let b=null,S=null;for(const i of y.attributes)"binding"===i.name?b=i.value:"group"===i.name&&(S=i.value);if(g==b&&i==S){let b=!1;for(const v of k.resources)if(v.name===x.name&&v.group===parseInt(i)&&v.binding===parseInt(g)){b=!0;break}if(b)if(void 0!==v.texture&&void 0!==v.descriptor){const i=new We(v.texture,this.getTypeInfo(y.type),v.descriptor,null!==(_=v.texture.view)&&void 0!==_?_:null);x.value=i}else void 0!==v.uniform?x.value=new Pe(v.uniform,this.getTypeInfo(y.type)):x.value=new Pe(v,this.getTypeInfo(y.type))}}})}for(let i=0;i0){const i=x.getVariableValue(g.value[0]);v[0]=i instanceof Be?i.value:parseInt(g.value[0])}if(g.value.length>1){const i=x.getVariableValue(g.value[1]);v[1]=i instanceof Be?i.value:parseInt(g.value[1])}if(g.value.length>2){const i=x.getVariableValue(g.value[2]);v[2]=i instanceof Be?i.value:parseInt(g.value[2])}}const _=this.getTypeInfo("vec3u"),y=this.getTypeInfo("u32");x.setVariable("@workgroup_size",new Me(v,_));const b=v[0],S=v[1],w=v[2];for(let L=0,k=0;L",_=null;if(i.variable instanceof ke){const x=this._getVariableData(i.variable,g),v=this.evalExpression(i.value,g),_=i.operator;if("="===_){if(x instanceof Be||x instanceof Me||x instanceof Ue){if(v instanceof Be||v instanceof Me||v instanceof Ue&&x.data.length===v.data.length)return void x.data.set(v.data);console.error(`Invalid assignment. Line ${i.line}`)}else if(x instanceof Pe&&v instanceof Pe&&x.buffer.byteLength-x.offset>=v.buffer.byteLength-v.offset)return void(x.buffer.byteLength%4==0?new Uint32Array(x.buffer,x.offset,x.typeInfo.size/4).set(new Uint32Array(v.buffer,v.offset,v.typeInfo.size/4)):new Uint8Array(x.buffer,x.offset,x.typeInfo.size).set(new Uint8Array(v.buffer,v.offset,v.typeInfo.size)));return console.error(`Invalid assignment. Line ${i.line}`),null}if("+="===_)return x instanceof Be||x instanceof Me||x instanceof Ue?v instanceof Be||v instanceof Me||v instanceof Ue?void x.data.set(v.data.map((i,g)=>x.data[g]+i)):void console.error(`Invalid assignment . Line ${i.line}`):void console.error(`Invalid assignment. Line ${i.line}`);if("-="===_)return(x instanceof Be||x instanceof Me||x instanceof Ue)&&(v instanceof Be||v instanceof Me||v instanceof Ue)?void x.data.set(v.data.map((i,g)=>x.data[g]-i)):void console.error(`Invalid assignment. Line ${i.line}`)}if(i.variable instanceof ke){if("*"===i.variable.operator){v=this.getVariableName(i.variable.right,g);const _=g.getVariable(v);if(!(_&&_.value instanceof Oe))return void console.error(`Variable ${v} is not a pointer. Line ${i.line}`);x=_.value.reference;let y=i.variable.postfix;if(!y){let g=i.variable.right;for(;g instanceof ke;){if(g.postfix){y=g.postfix;break}g=g.right}}y&&(x=x.getSubData(this,y,g))}}else{_=i.variable.postfix,v=this.getVariableName(i.variable,g);const y=g.getVariable(v);if(null===y)return void console.error(`Variable ${v} not found. Line ${i.line}`);x=y.value}if(x instanceof Oe&&(x=x.reference),null===x)return void console.error(`Variable ${v} not found. Line ${i.line}`);const y=this.evalExpression(i.value,g),b=i.operator;if("="!==b){const v=x.getSubData(this,_,g);if(v instanceof Me&&y instanceof Be){const g=v.data,x=y.value;if("+="===b)for(let i=0;i>="===b)for(let i=0;i>=x;else console.error(`Invalid operator ${b}. Line ${i.line}`)}else if(v instanceof Me&&y instanceof Me){const g=v.data,x=y.data;if(g.length!==x.length)return void console.error(`Vector length mismatch. Line ${i.line}`);if("+="===b)for(let i=0;i>="===b)for(let i=0;i>=x[i];else console.error(`Invalid operator ${b}. Line ${i.line}`)}else{if(!(v instanceof Be&&y instanceof Be))return void console.error(`Invalid type for ${i.operator} operator. Line ${i.line}`);"+="===b?v.value+=y.value:"-="===b?v.value-=y.value:"*="===b?v.value*=y.value:"/="===b?v.value/=y.value:"%="===b?v.value%=y.value:"&="===b?v.value&=y.value:"|="===b?v.value|=y.value:"^="===b?v.value^=y.value:"<<="===b?v.value<<=y.value:">>="===b?v.value>>=y.value:console.error(`Invalid operator ${b}. Line ${i.line}`)}return void(x instanceof Pe&&x.setDataValue(this,v,_,g))}if(x instanceof Pe)x.setDataValue(this,y,_,g);else if(_){if(!(x instanceof Me||x instanceof Ue))return void console.error(`Variable ${v} is not a vector or matrix. Line ${i.line}`);if(_ instanceof ve){const b=this.evalExpression(_.index,g).value;if(x instanceof Me){if(!(y instanceof Be))return void console.error(`Invalid assignment to ${v}. Line ${i.line}`);x.data[b]=y.value}else{if(!(x instanceof Ue))return void console.error(`Invalid assignment to ${v}. Line ${i.line}`);{const b=this.evalExpression(_.index,g).value;if(b<0)return void console.error(`Invalid assignment to ${v}. Line ${i.line}`);if(!(y instanceof Me))return void console.error(`Invalid assignment to ${v}. Line ${i.line}`);{const g=x.typeInfo.getTypeName();if("mat2x2"===g||"mat2x2f"===g||"mat2x2h"===g){if(!(b<2&&2===y.data.length))return void console.error(`Invalid assignment to ${v}. Line ${i.line}`);x.data[2*b]=y.data[0],x.data[2*b+1]=y.data[1]}else if("mat2x3"===g||"mat2x3f"===g||"mat2x3h"===g){if(!(b<2&&3===y.data.length))return void console.error(`Invalid assignment to ${v}. Line ${i.line}`);x.data[3*b]=y.data[0],x.data[3*b+1]=y.data[1],x.data[3*b+2]=y.data[2]}else if("mat2x4"===g||"mat2x4f"===g||"mat2x4h"===g){if(!(b<2&&4===y.data.length))return void console.error(`Invalid assignment to ${v}. Line ${i.line}`);x.data[4*b]=y.data[0],x.data[4*b+1]=y.data[1],x.data[4*b+2]=y.data[2],x.data[4*b+3]=y.data[3]}else if("mat3x2"===g||"mat3x2f"===g||"mat3x2h"===g){if(!(b<3&&2===y.data.length))return void console.error(`Invalid assignment to ${v}. Line ${i.line}`);x.data[2*b]=y.data[0],x.data[2*b+1]=y.data[1]}else if("mat3x3"===g||"mat3x3f"===g||"mat3x3h"===g){if(!(b<3&&3===y.data.length))return void console.error(`Invalid assignment to ${v}. Line ${i.line}`);x.data[3*b]=y.data[0],x.data[3*b+1]=y.data[1],x.data[3*b+2]=y.data[2]}else if("mat3x4"===g||"mat3x4f"===g||"mat3x4h"===g){if(!(b<3&&4===y.data.length))return void console.error(`Invalid assignment to ${v}. Line ${i.line}`);x.data[4*b]=y.data[0],x.data[4*b+1]=y.data[1],x.data[4*b+2]=y.data[2],x.data[4*b+3]=y.data[3]}else if("mat4x2"===g||"mat4x2f"===g||"mat4x2h"===g){if(!(b<4&&2===y.data.length))return void console.error(`Invalid assignment to ${v}. Line ${i.line}`);x.data[2*b]=y.data[0],x.data[2*b+1]=y.data[1]}else if("mat4x3"===g||"mat4x3f"===g||"mat4x3h"===g){if(!(b<4&&3===y.data.length))return void console.error(`Invalid assignment to ${v}. Line ${i.line}`);x.data[3*b]=y.data[0],x.data[3*b+1]=y.data[1],x.data[3*b+2]=y.data[2]}else{if("mat4x4"!==g&&"mat4x4f"!==g&&"mat4x4h"!==g)return void console.error(`Invalid assignment to ${v}. Line ${i.line}`);if(!(b<4&&4===y.data.length))return void console.error(`Invalid assignment to ${v}. Line ${i.line}`);x.data[4*b]=y.data[0],x.data[4*b+1]=y.data[1],x.data[4*b+2]=y.data[2],x.data[4*b+3]=y.data[3]}}}}}else if(_ instanceof pe){const g=_.value;if(!(x instanceof Me))return void console.error(`Invalid assignment to ${g}. Variable ${v} is not a vector. Line ${i.line}`);if(y instanceof Be){if(g.length>1)return void console.error(`Invalid assignment to ${g} for variable ${v}. Line ${i.line}`);if("x"===g)x.data[0]=y.value;else if("y"===g){if(x.data.length<2)return void console.error(`Invalid assignment to ${g} for variable ${v}. Line ${i.line}`);x.data[1]=y.value}else if("z"===g){if(x.data.length<3)return void console.error(`Invalid assignment to ${g} for variable ${v}. Line ${i.line}`);x.data[2]=y.value}else if("w"===g){if(x.data.length<4)return void console.error(`Invalid assignment to ${g} for variable ${v}. Line ${i.line}`);x.data[3]=y.value}}else{if(!(y instanceof Me))return void console.error(`Invalid assignment to ${v}. Line ${i.line}`);if(g.length!==y.data.length)return void console.error(`Invalid assignment to ${g} for variable ${v}. Line ${i.line}`);for(let _=0;_+i);return new Me(i,x.typeInfo)}const i=v,g=this._maxFormatTypeInfo([x.typeInfo,x.typeInfo]);return new Be(+i,g)}case"-":{if(Ge(v)){const i=v.map((i,g)=>-i);return new Me(i,x.typeInfo)}const i=v,g=this._maxFormatTypeInfo([x.typeInfo,x.typeInfo]);return new Be(-i,g)}case"!":{if(Ge(v)){const i=v.map((i,g)=>i?0:1);return new Me(i,x.typeInfo)}const i=v,g=this._maxFormatTypeInfo([x.typeInfo,x.typeInfo]);return new Be(i?0:1,g)}case"~":{if(Ge(v)){const i=v.map((i,g)=>~i);return new Me(i,x.typeInfo)}const i=v,g=this._maxFormatTypeInfo([x.typeInfo,x.typeInfo]);return new Be(~i,g)}}return console.error(`Invalid unary operator ${i.operator}. Line ${i.line}`),null}_evalBinaryOp(i,g){const x=this.evalExpression(i.left,g),v=this.evalExpression(i.right,g),_=x instanceof Be?x.value:x instanceof Me||x instanceof Ue?Array.from(x.data):null,y=v instanceof Be?v.value:v instanceof Me||v instanceof Ue?Array.from(v.data):null;switch(i.operator){case"+":{if(Ge(_)&&Ge(y)){const g=_,v=y;if(g.length!==v.length)return console.error(`Vector length mismatch. Line ${i.line}.`),null;const b=g.map((i,g)=>i+v[g]);return new Me(b,x.typeInfo)}if(Ge(_)){const i=y,g=_.map((g,x)=>g+i);return new Me(g,x.typeInfo)}if(Ge(y)){const i=_,g=y.map((g,x)=>i+g);return new Me(g,v.typeInfo)}const g=_,b=y,S=this._maxFormatTypeInfo([x.typeInfo,v.typeInfo]);return new Be(g+b,S)}case"-":{if(Ge(_)&&Ge(y)){const g=_,v=y;if(g.length!==v.length)return console.error(`Vector length mismatch. Line ${i.line}.`),null;const b=g.map((i,g)=>i-v[g]);return new Me(b,x.typeInfo)}if(Ge(_)){const i=y,g=_.map((g,x)=>g-i);return new Me(g,x.typeInfo)}if(Ge(y)){const i=_,g=y.map((g,x)=>i-g);return new Me(g,v.typeInfo)}const g=_,b=y,S=this._maxFormatTypeInfo([x.typeInfo,v.typeInfo]);return new Be(g-b,S)}case"*":{if(Ge(_)&&Ge(y)){const g=_,b=y;if(x instanceof Ue&&v instanceof Ue){const _=function(i,g,x,v){if(void 0===si[g.name]||void 0===si[v.name])return null;const _=si[g.name][0],y=si[g.name][1],b=si[v.name][0];if(_!==si[v.name][1])return null;const S=new Array(b*y);for(let g=0;gi*b[g]);return new Me(v,x.typeInfo)}}if(Ge(_)){const i=y,g=_.map((g,x)=>g*i);return x instanceof Ue?new Ue(g,x.typeInfo):new Me(g,x.typeInfo)}if(Ge(y)){const i=_,g=y.map((g,x)=>i*g);return v instanceof Ue?new Ue(g,v.typeInfo):new Me(g,v.typeInfo)}const g=_,b=y,S=this._maxFormatTypeInfo([x.typeInfo,v.typeInfo]);return new Be(g*b,S)}case"%":{if(Ge(_)&&Ge(y)){const g=_,v=y;if(g.length!==v.length)return console.error(`Vector length mismatch. Line ${i.line}.`),null;const b=g.map((i,g)=>i%v[g]);return new Me(b,x.typeInfo)}if(Ge(_)){const i=y,g=_.map((g,x)=>g%i);return new Me(g,x.typeInfo)}if(Ge(y)){const i=_,g=y.map((g,x)=>i%g);return new Me(g,v.typeInfo)}const g=_,b=y,S=this._maxFormatTypeInfo([x.typeInfo,v.typeInfo]);return new Be(g%b,S)}case"/":{if(Ge(_)&&Ge(y)){const g=_,v=y;if(g.length!==v.length)return console.error(`Vector length mismatch. Line ${i.line}.`),null;const b=g.map((i,g)=>i/v[g]);return new Me(b,x.typeInfo)}if(Ge(_)){const i=y,g=_.map((g,x)=>g/i);return new Me(g,x.typeInfo)}if(Ge(y)){const i=_,g=y.map((g,x)=>i/g);return new Me(g,v.typeInfo)}const g=_,b=y,S=this._maxFormatTypeInfo([x.typeInfo,v.typeInfo]);return new Be(g/b,S)}case"&":{if(Ge(_)&&Ge(y)){const g=_,v=y;if(g.length!==v.length)return console.error(`Vector length mismatch. Line ${i.line}.`),null;const b=g.map((i,g)=>i&v[g]);return new Me(b,x.typeInfo)}if(Ge(_)){const i=y,g=_.map((g,x)=>g&i);return new Me(g,x.typeInfo)}if(Ge(y)){const i=_,g=y.map((g,x)=>i&g);return new Me(g,v.typeInfo)}const g=_,b=y,S=this._maxFormatTypeInfo([x.typeInfo,v.typeInfo]);return new Be(g&b,S)}case"|":{if(Ge(_)&&Ge(y)){const g=_,v=y;if(g.length!==v.length)return console.error(`Vector length mismatch. Line ${i.line}.`),null;const b=g.map((i,g)=>i|v[g]);return new Me(b,x.typeInfo)}if(Ge(_)){const i=y,g=_.map((g,x)=>g|i);return new Me(g,x.typeInfo)}if(Ge(y)){const i=_,g=y.map((g,x)=>i|g);return new Me(g,v.typeInfo)}const g=_,b=y,S=this._maxFormatTypeInfo([x.typeInfo,v.typeInfo]);return new Be(g|b,S)}case"^":{if(Ge(_)&&Ge(y)){const g=_,v=y;if(g.length!==v.length)return console.error(`Vector length mismatch. Line ${i.line}.`),null;const b=g.map((i,g)=>i^v[g]);return new Me(b,x.typeInfo)}if(Ge(_)){const i=y,g=_.map((g,x)=>g^i);return new Me(g,x.typeInfo)}if(Ge(y)){const i=_,g=y.map((g,x)=>i^g);return new Me(g,v.typeInfo)}const g=_,b=y,S=this._maxFormatTypeInfo([x.typeInfo,v.typeInfo]);return new Be(g^b,S)}case"<<":{if(Ge(_)&&Ge(y)){const g=_,v=y;if(g.length!==v.length)return console.error(`Vector length mismatch. Line ${i.line}.`),null;const b=g.map((i,g)=>i<g<i<>":{if(Ge(_)&&Ge(y)){const g=_,v=y;if(g.length!==v.length)return console.error(`Vector length mismatch. Line ${i.line}.`),null;const b=g.map((i,g)=>i>>v[g]);return new Me(b,x.typeInfo)}if(Ge(_)){const i=y,g=_.map((g,x)=>g>>i);return new Me(g,x.typeInfo)}if(Ge(y)){const i=_,g=y.map((g,x)=>i>>g);return new Me(g,v.typeInfo)}const g=_,b=y,S=this._maxFormatTypeInfo([x.typeInfo,v.typeInfo]);return new Be(g>>b,S)}case">":if(Ge(_)&&Ge(y)){const g=_,v=y;if(g.length!==v.length)return console.error(`Vector length mismatch. Line ${i.line}.`),null;const b=g.map((i,g)=>i>v[g]?1:0);return new Me(b,x.typeInfo)}if(Ge(_)){const i=y,g=_.map((g,x)=>g>i?1:0);return new Me(g,x.typeInfo)}if(Ge(y)){const i=_,g=y.map((g,x)=>i>g?1:0);return new Me(g,v.typeInfo)}return new Be(_>y?1:0,this.getTypeInfo("bool"));case"<":if(Ge(_)&&Ge(y)){const g=_,v=y;if(g.length!==v.length)return console.error(`Vector length mismatch. Line ${i.line}.`),null;const b=g.map((i,g)=>igii===v[g]?1:0);return new Me(b,x.typeInfo)}if(Ge(_)){const i=y,g=_.map((g,x)=>g==i?1:0);return new Me(g,x.typeInfo)}if(Ge(y)){const i=_,g=y.map((g,x)=>i==g?1:0);return new Me(g,v.typeInfo)}return new Be(_===y?1:0,this.getTypeInfo("bool"));case"!=":if(Ge(_)&&Ge(y)){const g=_,v=y;if(g.length!==v.length)return console.error(`Vector length mismatch. Line ${i.line}.`),null;const b=g.map((i,g)=>i!==v[g]?1:0);return new Me(b,x.typeInfo)}if(Ge(_)){const i=y,g=_.map((g,x)=>g!==i?1:0);return new Me(g,x.typeInfo)}if(Ge(y)){const i=_,g=y.map((g,x)=>i!==g?1:0);return new Me(g,v.typeInfo)}return new Be(_!==y?1:0,this.getTypeInfo("bool"));case">=":if(Ge(_)&&Ge(y)){const g=_,v=y;if(g.length!==v.length)return console.error(`Vector length mismatch. Line ${i.line}.`),null;const b=g.map((i,g)=>i>=v[g]?1:0);return new Me(b,x.typeInfo)}if(Ge(_)){const i=y,g=_.map((g,x)=>g>=i?1:0);return new Me(g,x.typeInfo)}if(Ge(y)){const i=_,g=y.map((g,x)=>i>=g?1:0);return new Me(g,v.typeInfo)}return new Be(_>=y?1:0,this.getTypeInfo("bool"));case"<=":if(Ge(_)&&Ge(y)){const g=_,v=y;if(g.length!==v.length)return console.error(`Vector length mismatch. Line ${i.line}.`),null;const b=g.map((i,g)=>i<=v[g]?1:0);return new Me(b,x.typeInfo)}if(Ge(_)){const i=y,g=_.map((g,x)=>g<=i?1:0);return new Me(g,x.typeInfo)}if(Ge(y)){const i=_,g=y.map((g,x)=>i<=g?1:0);return new Me(g,v.typeInfo)}return new Be(_<=y?1:0,this.getTypeInfo("bool"));case"&&":if(Ge(_)&&Ge(y)){const g=_,v=y;if(g.length!==v.length)return console.error(`Vector length mismatch. Line ${i.line}.`),null;const b=g.map((i,g)=>i&&v[g]?1:0);return new Me(b,x.typeInfo)}if(Ge(_)){const i=y,g=_.map((g,x)=>g&&i?1:0);return new Me(g,x.typeInfo)}if(Ge(y)){const i=_,g=y.map((g,x)=>i&&g?1:0);return new Me(g,v.typeInfo)}return new Be(_&&y?1:0,this.getTypeInfo("bool"));case"||":if(Ge(_)&&Ge(y)){const g=_,v=y;if(g.length!==v.length)return console.error(`Vector length mismatch. Line ${i.line}.`),null;const b=g.map((i,g)=>i||v[g]?1:0);return new Me(b,x.typeInfo)}if(Ge(_)){const i=y,g=_.map((g,x)=>g||i?1:0);return new Me(g,x.typeInfo)}if(Ge(y)){const i=_,g=y.map((g,x)=>i||g?1:0);return new Me(g,v.typeInfo)}return new Be(_||y?1:0,this.getTypeInfo("bool"))}return console.error(`Unknown operator ${i.operator}. Line ${i.line}`),null}_evalCall(i,g){if(null!==i.cachedReturnValue)return i.cachedReturnValue;const x=g.clone();x.currentFunctionName=i.name;const v=g.getFunction(i.name);if(!v)return i.isBuiltin?this._callBuiltinFunction(i,x):this.getTypeInfo(i.name)?this._evalCreate(i,g):(console.error(`Unknown function "${i.name}". Line ${i.line}`),null);for(let g=0;g_?y.slice(0,_):y,x).getSubData(this,i.postfix,g)}_callConstructorMatrix(i,g){const x=this.getTypeInfo(i.type),v=i.type.getTypeName(),_=si[v];if(void 0===_)return console.error(`Invalid matrix constructor ${v}. Line ${i.line}`),null;const y=[];if(i instanceof xe)if(i.isVector){const g=i.vectorValue;for(const i of g)y.push(i)}else y.push(i.scalarValue);else if(i.args)for(const x of i.args){const i=this.evalExpression(x,g);i instanceof Me?y.push(...i.data):i instanceof Be?y.push(i.value):i instanceof Ue&&y.push(...i.data)}if(x instanceof a&&null===x.format&&(x.format=this.getTypeInfo("f32")),0===y.length){const v=new Array(_[2]).fill(0);return new Ue(v,x).getSubData(this,i.postfix,g)}return y.length!==_[2]?(console.error(`Invalid matrix constructor. Line ${i.line}`),null):new Ue(y,x).getSubData(this,i.postfix,g)}}dt._breakObj=new Ne(new e("BREAK",null),null),dt._continueObj=new Ne(new e("CONTINUE",null),null),dt._priority=new Map([["f32",0],["f16",1],["u32",2],["i32",3],["x32",3]]);class mt{constructor(){this.constants=new Map,this.aliases=new Map,this.structs=new Map}}class gt{constructor(){this._tokens=[],this._current=0,this._currentLine=1,this._deferArrayCountEval=[],this._currentLoop=[],this._context=new mt,this._exec=new dt,this._forwardTypeCount=0}parse(i){this._initialize(i),this._deferArrayCountEval.length=0;const g=[];for(;!this._isAtEnd();){const i=this._global_decl_or_directive();if(!i)break;g.push(i)}if(this._deferArrayCountEval.length>0){for(const g of this._deferArrayCountEval){const x=g.arrayType,v=g.countNode;if(v instanceof ge){const g=v.name,_=this._context.constants.get(g);if(_)try{const i=_.constEvaluate(this._exec);x.count=i}catch(i){}}}this._deferArrayCountEval.length=0}if(this._forwardTypeCount>0)for(const i of g)i.search(i=>{i instanceof Ce||i instanceof le?i.type=this._forwardType(i.type):i instanceof ue?i.format=this._forwardType(i.format):i instanceof F||i instanceof U||i instanceof P?i.type=this._forwardType(i.type):i instanceof D?i.returnType=this._forwardType(i.returnType):i instanceof $e&&(i.type=this._forwardType(i.type))});return g}_forwardType(i){if(i instanceof ie){const g=this._getType(i.name);if(g)return g}else i instanceof le?i.type=this._forwardType(i.type):i instanceof ue&&(i.format=this._forwardType(i.format));return i}_initialize(i){if(i)if("string"==typeof i){const g=new Re(i);this._tokens=g.scanTokens()}else this._tokens=i;else this._tokens=[];this._current=0}_updateNode(i,g){return i.line=null!=g?g:this._currentLine,i}_error(i,g){return{token:i,message:g,toString:()=>`${g}`}}_isAtEnd(){return this._current>=this._tokens.length||this._peek().type==He.eof}_match(i){if(i instanceof qe)return!!this._check(i)&&(this._advance(),!0);for(let g=0,x=i.length;g0){const i=this._currentLoop[this._currentLoop.length-1];g.loopId=i.id}i=g,this._check(He.keywords.if)&&(this._advance(),g.condition=this._optional_paren_expression())}else if(this._match(He.keywords.continue)){const g=this._updateNode(new re);if(!(this._currentLoop.length>0))throw this._error(this._peek(),`Continue statement must be inside a loop. Line: ${g.line}`);{const i=this._currentLoop[this._currentLoop.length-1];g.loopId=i.id}i=g}else i=this._increment_decrement_statement()||this._func_call_statement()||this._assignment_statement();return null!=i&&this._consume(He.tokens.semicolon,"Expected ';' after statement."),i}_static_assert_statement(){if(!this._match(He.keywords.static_assert))return null;const i=this._currentLine,g=this._optional_paren_expression();return this._updateNode(new N(g),i)}_while_statement(){if(!this._match(He.keywords.while))return null;const i=this._updateNode(new V(null,null));return this._currentLoop.push(i),i.condition=this._optional_paren_expression(),this._check(He.tokens.attr)&&this._attribute(),i.body=this._compound_statement(),this._currentLoop.pop(),i}_continuing_statement(){const i=this._currentLoop.length>0?this._currentLoop[this._currentLoop.length-1].id:-1;if(!this._match(He.keywords.continuing))return null;const g=this._currentLine,x=this._compound_statement();return this._updateNode(new O(x,i),g)}_for_statement(){if(!this._match(He.keywords.for))return null;this._consume(He.tokens.paren_left,"Expected '('.");const i=this._updateNode(new B(null,null,null,null));return this._currentLoop.push(i),i.init=this._check(He.tokens.semicolon)?null:this._for_init(),this._consume(He.tokens.semicolon,"Expected ';'."),i.condition=this._check(He.tokens.semicolon)?null:this._short_circuit_or_expression(),this._consume(He.tokens.semicolon,"Expected ';'."),i.increment=this._check(He.tokens.paren_right)?null:this._for_increment(),this._consume(He.tokens.paren_right,"Expected ')'."),this._check(He.tokens.attr)&&this._attribute(),i.body=this._compound_statement(),this._currentLoop.pop(),i}_for_init(){return this._variable_statement()||this._func_call_statement()||this._assignment_statement()}_for_increment(){return this._func_call_statement()||this._increment_decrement_statement()||this._assignment_statement()}_variable_statement(){if(this._check(He.keywords.var)){const i=this._variable_decl();if(null===i)throw this._error(this._peek(),"Variable declaration expected.");let g=null;return this._match(He.tokens.equal)&&(g=this._short_circuit_or_expression()),this._updateNode(new F(i.name,i.type,i.storage,i.access,g),i.line)}if(this._match(He.keywords.let)){const i=this._currentLine,g=this._consume(He.tokens.name,"Expected name for let.").toString();let x=null;if(this._match(He.tokens.colon)){const i=this._attribute();x=this._type_decl(),null!=x&&(x.attributes=i)}this._consume(He.tokens.equal,"Expected '=' for let.");const v=this._short_circuit_or_expression();return this._updateNode(new U(g,x,null,null,v),i)}if(this._match(He.keywords.const)){const i=this._currentLine,g=this._consume(He.tokens.name,"Expected name for const.").toString();let x=null;if(this._match(He.tokens.colon)){const i=this._attribute();x=this._type_decl(),null!=x&&(x.attributes=i)}this._consume(He.tokens.equal,"Expected '=' for const.");const v=this._short_circuit_or_expression();return null===x&&v instanceof xe&&(x=v.type),this._updateNode(new P(g,x,null,null,v),i)}return null}_increment_decrement_statement(){const i=this._current,g=this._unary_expression();if(null==g)return null;if(!this._check(He.increment_operators))return this._current=i,null;const x=this._consume(He.increment_operators,"Expected increment operator");return this._updateNode(new R(x.type===He.tokens.plus_plus?jr.increment:jr.decrement,g))}_assignment_statement(){let i=null;const g=this._currentLine;if(this._check(He.tokens.brace_right))return null;let x=this._match(He.tokens.underscore);if(x||(i=this._unary_expression()),!x&&null==i)return null;const v=this._consume(He.assignment_operators,"Expected assignment operator."),_=this._short_circuit_or_expression();return this._updateNode(new G(Kr.parse(v.lexeme),i,_),g)}_func_call_statement(){if(!this._check(He.tokens.ident))return null;const i=this._currentLine,g=this._current,x=this._consume(He.tokens.ident,"Expected function name."),v=this._argument_expression_list();return null===v?(this._current=g,null):this._updateNode(new X(x.lexeme,v),i)}_loop_statement(){if(!this._match(He.keywords.loop))return null;this._check(He.tokens.attr)&&this._attribute(),this._consume(He.tokens.brace_left,"Expected '{' for loop.");const i=this._updateNode(new j([],null));this._currentLoop.push(i);let g=this._statement();for(;null!==g;){if(Array.isArray(g))for(let x of g)i.body.push(x);else i.body.push(g);if(g instanceof O){i.continuing=g;break}g=this._statement()}return this._currentLoop.pop(),this._consume(He.tokens.brace_right,"Expected '}' for loop."),i}_switch_statement(){if(!this._match(He.keywords.switch))return null;const i=this._updateNode(new Z(null,[]));if(this._currentLoop.push(i),i.condition=this._optional_paren_expression(),this._check(He.tokens.attr)&&this._attribute(),this._consume(He.tokens.brace_left,"Expected '{' for switch."),i.cases=this._switch_body(),null==i.cases||0==i.cases.length)throw this._error(this._previous(),"Expected 'case' or 'default'.");return this._consume(He.tokens.brace_right,"Expected '}' for switch."),this._currentLoop.pop(),i}_switch_body(){const i=[];let g=!1;for(;this._check([He.keywords.default,He.keywords.case]);){if(this._match(He.keywords.case)){const x=this._case_selectors();for(const i of x)if(i instanceof Se){if(g)throw this._error(this._previous(),"Multiple default cases in switch statement.");g=!0;break}this._match(He.tokens.colon),this._check(He.tokens.attr)&&this._attribute(),this._consume(He.tokens.brace_left,"Exected '{' for switch case.");const v=this._case_body();this._consume(He.tokens.brace_right,"Exected '}' for switch case."),i.push(this._updateNode(new Ae(x,v)))}if(this._match(He.keywords.default)){if(g)throw this._error(this._previous(),"Multiple default cases in switch statement.");this._match(He.tokens.colon),this._check(He.tokens.attr)&&this._attribute(),this._consume(He.tokens.brace_left,"Exected '{' for switch default.");const x=this._case_body();this._consume(He.tokens.brace_right,"Exected '}' for switch default."),i.push(this._updateNode(new Ee(x)))}}return i}_case_selectors(){const i=[];for(this._match(He.keywords.default)?i.push(this._updateNode(new Se)):i.push(this._shift_expression());this._match(He.tokens.comma);)this._match(He.keywords.default)?i.push(this._updateNode(new Se)):i.push(this._shift_expression());return i}_case_body(){if(this._match(He.keywords.fallthrough))return this._consume(He.tokens.semicolon,"Expected ';'"),[];let i=this._statement();if(null==i)return[];i instanceof Array||(i=[i]);const g=this._case_body();return 0==g.length?i:[...i,g[0]]}_if_statement(){if(!this._match(He.keywords.if))return null;const i=this._currentLine,g=this._optional_paren_expression();this._check(He.tokens.attr)&&this._attribute();const x=this._compound_statement();let v=[];this._match_elseif()&&(this._check(He.tokens.attr)&&this._attribute(),v=this._elseif_statement(v));let _=null;return this._match(He.keywords.else)&&(this._check(He.tokens.attr)&&this._attribute(),_=this._compound_statement()),this._updateNode(new Q(g,x,v,_),i)}_match_elseif(){return this._tokens[this._current].type===He.keywords.else&&this._tokens[this._current+1].type===He.keywords.if&&(this._advance(),this._advance(),!0)}_elseif_statement(i=[]){const g=this._optional_paren_expression(),x=this._compound_statement();return i.push(this._updateNode(new Le(g,x))),this._match_elseif()&&(this._check(He.tokens.attr)&&this._attribute(),this._elseif_statement(i)),i}_return_statement(){if(!this._match(He.keywords.return))return null;const i=this._short_circuit_or_expression();return this._updateNode(new Y(i))}_short_circuit_or_expression(){let i=this._short_circuit_and_expr();for(;this._match(He.tokens.or_or);)i=this._updateNode(new Ie(this._previous().toString(),i,this._short_circuit_and_expr()));return i}_short_circuit_and_expr(){let i=this._inclusive_or_expression();for(;this._match(He.tokens.and_and);)i=this._updateNode(new Ie(this._previous().toString(),i,this._inclusive_or_expression()));return i}_inclusive_or_expression(){let i=this._exclusive_or_expression();for(;this._match(He.tokens.or);)i=this._updateNode(new Ie(this._previous().toString(),i,this._exclusive_or_expression()));return i}_exclusive_or_expression(){let i=this._and_expression();for(;this._match(He.tokens.xor);)i=this._updateNode(new Ie(this._previous().toString(),i,this._and_expression()));return i}_and_expression(){let i=this._equality_expression();for(;this._match(He.tokens.and);)i=this._updateNode(new Ie(this._previous().toString(),i,this._equality_expression()));return i}_equality_expression(){const i=this._relational_expression();return this._match([He.tokens.equal_equal,He.tokens.not_equal])?this._updateNode(new Ie(this._previous().toString(),i,this._relational_expression())):i}_relational_expression(){let i=this._shift_expression();for(;this._match([He.tokens.less_than,He.tokens.greater_than,He.tokens.less_than_equal,He.tokens.greater_than_equal]);)i=this._updateNode(new Ie(this._previous().toString(),i,this._shift_expression()));return i}_shift_expression(){let i=this._additive_expression();for(;this._match([He.tokens.shift_left,He.tokens.shift_right]);)i=this._updateNode(new Ie(this._previous().toString(),i,this._additive_expression()));return i}_additive_expression(){let i=this._multiplicative_expression();for(;this._match([He.tokens.plus,He.tokens.minus]);)i=this._updateNode(new Ie(this._previous().toString(),i,this._multiplicative_expression()));return i}_multiplicative_expression(){let i=this._unary_expression();for(;this._match([He.tokens.star,He.tokens.forward_slash,He.tokens.modulo]);)i=this._updateNode(new Ie(this._previous().toString(),i,this._unary_expression()));return i}_unary_expression(){return this._match([He.tokens.minus,He.tokens.bang,He.tokens.tilde,He.tokens.star,He.tokens.and])?this._updateNode(new ke(this._previous().toString(),this._unary_expression())):this._singular_expression()}_singular_expression(){const i=this._primary_expression(),g=this._postfix_expression();return g&&(i.postfix=g),i}_postfix_expression(){if(this._match(He.tokens.bracket_left)){const i=this._short_circuit_or_expression();this._consume(He.tokens.bracket_right,"Expected ']'.");const g=this._updateNode(new ve(i)),x=this._postfix_expression();return x&&(g.postfix=x),g}if(this._match(He.tokens.period)){const i=this._consume(He.tokens.name,"Expected member name."),g=this._postfix_expression(),x=this._updateNode(new pe(i.lexeme));return g&&(x.postfix=g),x}return null}_getStruct(i){return this._context.aliases.has(i)?this._context.aliases.get(i).type:this._context.structs.has(i)?this._context.structs.get(i):null}_getType(i){const g=this._getStruct(i);if(null!==g)return g;switch(i){case"void":return ae.void;case"bool":return ae.bool;case"i32":return ae.i32;case"u32":return ae.u32;case"f32":return ae.f32;case"f16":return ae.f16;case"vec2f":return ce.vec2f;case"vec3f":return ce.vec3f;case"vec4f":return ce.vec4f;case"vec2i":return ce.vec2i;case"vec3i":return ce.vec3i;case"vec4i":return ce.vec4i;case"vec2u":return ce.vec2u;case"vec3u":return ce.vec3u;case"vec4u":return ce.vec4u;case"vec2h":return ce.vec2h;case"vec3h":return ce.vec3h;case"vec4h":return ce.vec4h;case"mat2x2f":return ce.mat2x2f;case"mat2x3f":return ce.mat2x3f;case"mat2x4f":return ce.mat2x4f;case"mat3x2f":return ce.mat3x2f;case"mat3x3f":return ce.mat3x3f;case"mat3x4f":return ce.mat3x4f;case"mat4x2f":return ce.mat4x2f;case"mat4x3f":return ce.mat4x3f;case"mat4x4f":return ce.mat4x4f;case"mat2x2h":return ce.mat2x2h;case"mat2x3h":return ce.mat2x3h;case"mat2x4h":return ce.mat2x4h;case"mat3x2h":return ce.mat3x2h;case"mat3x3h":return ce.mat3x3h;case"mat3x4h":return ce.mat3x4h;case"mat4x2h":return ce.mat4x2h;case"mat4x3h":return ce.mat4x3h;case"mat4x4h":return ce.mat4x4h;case"mat2x2i":return ce.mat2x2i;case"mat2x3i":return ce.mat2x3i;case"mat2x4i":return ce.mat2x4i;case"mat3x2i":return ce.mat3x2i;case"mat3x3i":return ce.mat3x3i;case"mat3x4i":return ce.mat3x4i;case"mat4x2i":return ce.mat4x2i;case"mat4x3i":return ce.mat4x3i;case"mat4x4i":return ce.mat4x4i;case"mat2x2u":return ce.mat2x2u;case"mat2x3u":return ce.mat2x3u;case"mat2x4u":return ce.mat2x4u;case"mat3x2u":return ce.mat3x2u;case"mat3x3u":return ce.mat3x3u;case"mat3x4u":return ce.mat3x4u;case"mat4x2u":return ce.mat4x2u;case"mat4x3u":return ce.mat4x3u;case"mat4x4u":return ce.mat4x4u}return null}_validateTypeRange(i,g){if("i32"===g.name){if(i<-2147483648||i>2147483647)throw this._error(this._previous(),`Value out of range for i32: ${i}. Line: ${this._currentLine}.`)}else if("u32"===g.name&&(i<0||i>4294967295))throw this._error(this._previous(),`Value out of range for u32: ${i}. Line: ${this._currentLine}.`)}_primary_expression(){if(this._match(He.tokens.ident)){const i=this._previous().toString();if(this._check(He.tokens.paren_left)){const g=this._argument_expression_list(),x=this._getType(i);return null!==x?this._updateNode(new de(x,g)):this._updateNode(new me(i,g))}if(this._context.constants.has(i)){const g=this._context.constants.get(i);return this._updateNode(new _e(i,g.value))}return this._updateNode(new ge(i))}if(this._match(He.tokens.int_literal)){const i=this._previous().toString();let g=i.endsWith("i")||i.endsWith("i")?ae.i32:i.endsWith("u")||i.endsWith("U")?ae.u32:ae.x32;const x=parseInt(i);return this._validateTypeRange(x,g),this._updateNode(new xe(new Be(x,this._exec.getTypeInfo(g)),g))}if(this._match(He.tokens.uint_literal)){const i=parseInt(this._previous().toString());return this._validateTypeRange(i,ae.u32),this._updateNode(new xe(new Be(i,this._exec.getTypeInfo(ae.u32)),ae.u32))}if(this._match([He.tokens.decimal_float_literal,He.tokens.hex_float_literal])){let i=this._previous().toString(),g=i.endsWith("h");g&&(i=i.substring(0,i.length-1));const x=parseFloat(i);this._validateTypeRange(x,g?ae.f16:ae.f32);const v=g?ae.f16:ae.f32;return this._updateNode(new xe(new Be(x,this._exec.getTypeInfo(v)),v))}if(this._match([He.keywords.true,He.keywords.false])){let i=this._previous().toString()===He.keywords.true.rule;return this._updateNode(new xe(new Be(i?1:0,this._exec.getTypeInfo(ae.bool)),ae.bool))}if(this._check(He.tokens.paren_left))return this._paren_expression();if(this._match(He.keywords.bitcast)){this._consume(He.tokens.less_than,"Expected '<'.");const i=this._type_decl();this._consume(He.tokens.greater_than,"Expected '>'.");const g=this._paren_expression();return this._updateNode(new ye(i,g))}const i=this._type_decl(),g=this._argument_expression_list();return this._updateNode(new de(i,g))}_argument_expression_list(){if(!this._match(He.tokens.paren_left))return null;const i=[];do{if(this._check(He.tokens.paren_right))break;const g=this._short_circuit_or_expression();i.push(g)}while(this._match(He.tokens.comma));return this._consume(He.tokens.paren_right,"Expected ')' for agument list"),i}_optional_paren_expression(){this._match(He.tokens.paren_left);const i=this._short_circuit_or_expression();return this._match(He.tokens.paren_right),i}_paren_expression(){this._consume(He.tokens.paren_left,"Expected '('.");const i=this._short_circuit_or_expression();return this._consume(He.tokens.paren_right,"Expected ')'."),i}_struct_decl(){if(!this._match(He.keywords.struct))return null;const i=this._currentLine,g=this._consume(He.tokens.ident,"Expected name for struct.").toString();this._consume(He.tokens.brace_left,"Expected '{' for struct body.");const x=[];for(;!this._check(He.tokens.brace_right);){const i=this._attribute(),g=this._consume(He.tokens.name,"Expected variable name.").toString();this._consume(He.tokens.colon,"Expected ':' for struct member type.");const v=this._attribute(),_=this._type_decl();null!=_&&(_.attributes=v),this._check(He.tokens.brace_right)?this._match(He.tokens.comma):this._consume(He.tokens.comma,"Expected ',' for struct member."),x.push(this._updateNode(new Ce(g,_,i)))}this._consume(He.tokens.brace_right,"Expected '}' after struct body.");const v=this._currentLine,_=this._updateNode(new oe(g,x,i,v),i);return this._context.structs.set(g,_),_}_global_variable_decl(){const i=this._variable_decl();if(!i)return null;if(this._match(He.tokens.equal)){const g=this._const_expression();i.value=g}if(null!==i.type&&i.value instanceof xe){if("x32"!==i.value.type.name&&i.type.getTypeName()!==i.value.type.getTypeName())throw this._error(this._peek(),`Invalid cast from ${i.value.type.name} to ${i.type.name}. Line:${this._currentLine}`);i.value.isScalar&&this._validateTypeRange(i.value.scalarValue,i.type),i.value.type=i.type}else null===i.type&&i.value instanceof xe&&(i.type="x32"===i.value.type.name?ae.i32:i.value.type,i.value.isScalar&&this._validateTypeRange(i.value.scalarValue,i.type));return i}_override_variable_decl(){const i=this._override_decl();return i&&this._match(He.tokens.equal)&&(i.value=this._const_expression()),i}_global_const_decl(){var i;if(!this._match(He.keywords.const))return null;const g=this._consume(He.tokens.name,"Expected variable name"),x=this._currentLine;let v=null;if(this._match(He.tokens.colon)){const i=this._attribute();v=this._type_decl(),null!=v&&(v.attributes=i)}let _=null;this._consume(He.tokens.equal,"const declarations require an assignment");const y=this._short_circuit_or_expression();try{let i=[ae.f32],x=y.constEvaluate(this._exec,i);x instanceof Be&&this._validateTypeRange(x.value,i[0]),i[0]instanceof ce&&null===i[0].format&&x.typeInfo instanceof a&&null!==x.typeInfo.format&&("f16"===x.typeInfo.format.name?i[0].format=ae.f16:"f32"===x.typeInfo.format.name?i[0].format=ae.f32:"i32"===x.typeInfo.format.name?i[0].format=ae.i32:"u32"===x.typeInfo.format.name?i[0].format=ae.u32:"bool"===x.typeInfo.format.name?i[0].format=ae.bool:console.error(`TODO: impelement template format type ${x.typeInfo.format.name}`)),_=this._updateNode(new xe(x,i[0])),this._exec.context.setVariable(g.toString(),x)}catch(i){_=y}if(null!==v&&_ instanceof xe){if("x32"!==_.type.name&&v.getTypeName()!==_.type.getTypeName())throw this._error(this._peek(),`Invalid cast from ${_.type.name} to ${v.name}. Line:${this._currentLine}`);_.type=v,_.isScalar&&this._validateTypeRange(_.scalarValue,_.type)}else null===v&&_ instanceof xe&&(v=null!==(i=null==_?void 0:_.type)&&void 0!==i?i:ae.f32,v===ae.x32&&(v=ae.i32));const b=this._updateNode(new P(g.toString(),v,"","",_),x);return this._context.constants.set(b.name,b),b}_global_let_decl(){if(!this._match(He.keywords.let))return null;const i=this._currentLine,g=this._consume(He.tokens.name,"Expected variable name");let x=null;if(this._match(He.tokens.colon)){const i=this._attribute();x=this._type_decl(),null!=x&&(x.attributes=i)}let v=null;if(this._match(He.tokens.equal)&&(v=this._const_expression()),null!==x&&v instanceof xe){if("x32"!==v.type.name&&x.getTypeName()!==v.type.getTypeName())throw this._error(this._peek(),`Invalid cast from ${v.type.name} to ${x.name}. Line:${this._currentLine}`);v.type=x}else null===x&&v instanceof xe&&(x="x32"===v.type.name?ae.i32:v.type);return v instanceof xe&&v.isScalar&&this._validateTypeRange(v.scalarValue,x),this._updateNode(new U(g.toString(),x,"","",v),i)}_const_expression(){return this._short_circuit_or_expression()}_variable_decl(){if(!this._match(He.keywords.var))return null;const i=this._currentLine;let g="",x="";this._match(He.tokens.less_than)&&(g=this._consume(He.storage_class,"Expected storage_class.").toString(),this._match(He.tokens.comma)&&(x=this._consume(He.access_mode,"Expected access_mode.").toString()),this._consume(He.tokens.greater_than,"Expected '>'."));const v=this._consume(He.tokens.name,"Expected variable name");let _=null;if(this._match(He.tokens.colon)){const i=this._attribute();_=this._type_decl(),null!=_&&(_.attributes=i)}return this._updateNode(new F(v.toString(),_,g,x,null),i)}_override_decl(){if(!this._match(He.keywords.override))return null;const i=this._consume(He.tokens.name,"Expected variable name");let g=null;if(this._match(He.tokens.colon)){const i=this._attribute();g=this._type_decl(),null!=g&&(g.attributes=i)}return this._updateNode(new M(i.toString(),g,null))}_diagnostic(){this._consume(He.tokens.paren_left,"Expected '('");const i=this._consume(He.tokens.ident,"Expected severity control name.");this._consume(He.tokens.comma,"Expected ','");let g=this._consume(He.tokens.ident,"Expected diagnostic rule name.").toString();return this._match(He.tokens.period)&&(g+=`.${this._consume(He.tokens.ident,"Expected diagnostic message.").toString()}`),this._consume(He.tokens.paren_right,"Expected ')'"),this._updateNode(new ee(i.toString(),g))}_enable_directive(){const i=this._consume(He.tokens.ident,"identity expected.");return this._updateNode(new K(i.toString()))}_requires_directive(){const i=[this._consume(He.tokens.ident,"identity expected.").toString()];for(;this._match(He.tokens.comma);){const g=this._consume(He.tokens.ident,"identity expected.");i.push(g.toString())}return this._updateNode(new J(i))}_type_alias(){const i=this._consume(He.tokens.ident,"identity expected.");this._consume(He.tokens.equal,"Expected '=' for type alias.");let g=this._type_decl();if(null===g)throw this._error(this._peek(),"Expected Type for Alias.");this._context.aliases.has(g.name)&&(g=this._context.aliases.get(g.name).type);const x=this._updateNode(new te(i.toString(),g));return this._context.aliases.set(x.name,x),x}_type_decl(){if(this._check([He.tokens.ident,...He.texel_format,He.keywords.bool,He.keywords.f32,He.keywords.i32,He.keywords.u32])){const i=this._advance().toString();if(this._context.structs.has(i))return this._context.structs.get(i);if(this._context.aliases.has(i))return this._context.aliases.get(i).type;if(!this._getType(i)){const g=this._updateNode(new ie(i));return this._forwardTypeCount++,g}return this._updateNode(new ae(i))}let i=this._texture_sampler_types();if(i)return i;if(this._check(He.template_types)){let i=this._advance().toString(),g=null,x=null;return this._match(He.tokens.less_than)&&(g=this._type_decl(),x=null,this._match(He.tokens.comma)&&(x=this._consume(He.access_mode,"Expected access_mode for pointer").toString()),this._consume(He.tokens.greater_than,"Expected '>' for type.")),this._updateNode(new ce(i,g,x))}if(this._match(He.keywords.ptr)){let i=this._previous().toString();this._consume(He.tokens.less_than,"Expected '<' for pointer.");const g=this._consume(He.storage_class,"Expected storage_class for pointer");this._consume(He.tokens.comma,"Expected ',' for pointer.");const x=this._type_decl();let v=null;return this._match(He.tokens.comma)&&(v=this._consume(He.access_mode,"Expected access_mode for pointer").toString()),this._consume(He.tokens.greater_than,"Expected '>' for pointer."),this._updateNode(new le(i,g.toString(),x,v))}const g=this._attribute();if(this._match(He.keywords.array)){let x=null,v=-1;const _=this._previous();let y=null;if(this._match(He.tokens.less_than)){x=this._type_decl(),this._context.aliases.has(x.name)&&(x=this._context.aliases.get(x.name).type);let g="";if(this._match(He.tokens.comma)){y=this._shift_expression();try{g=y.constEvaluate(this._exec).toString(),y=null}catch(i){g="1"}}this._consume(He.tokens.greater_than,"Expected '>' for array."),v=g?parseInt(g):0}const b=this._updateNode(new ue(_.toString(),g,x,v));return y&&this._deferArrayCountEval.push({arrayType:b,countNode:y}),b}return null}_texture_sampler_types(){if(this._match(He.sampler_type))return this._updateNode(new he(this._previous().toString(),null,null));if(this._match(He.depth_texture_type))return this._updateNode(new he(this._previous().toString(),null,null));if(this._match(He.sampled_texture_type)||this._match(He.multisampled_texture_type)){const i=this._previous();this._consume(He.tokens.less_than,"Expected '<' for sampler type.");const g=this._type_decl();return this._consume(He.tokens.greater_than,"Expected '>' for sampler type."),this._updateNode(new he(i.toString(),g,null))}if(this._match(He.storage_texture_type)){const i=this._previous();this._consume(He.tokens.less_than,"Expected '<' for sampler type.");const g=this._consume(He.texel_format,"Invalid texel format.").toString();this._consume(He.tokens.comma,"Expected ',' after texel format.");const x=this._consume(He.access_mode,"Expected access mode for storage texture type.").toString();return this._consume(He.tokens.greater_than,"Expected '>' for sampler type."),this._updateNode(new he(i.toString(),g,x))}return null}_attribute(){let i=[];for(;this._match(He.tokens.attr);){const g=this._consume(He.attribute_name,"Expected attribute name"),x=this._updateNode(new De(g.toString(),null));if(this._match(He.tokens.paren_left)){if(x.value=this._consume(He.literal_or_ident,"Expected attribute value").toString(),this._check(He.tokens.comma)){this._advance();do{const i=this._consume(He.literal_or_ident,"Expected attribute value").toString();x.value instanceof Array||(x.value=[x.value]),x.value.push(i)}while(this._match(He.tokens.comma))}this._consume(He.tokens.paren_right,"Expected ')'")}i.push(x)}return 0==i.length?null:i}}class _t extends at{constructor(i){super(),i&&this.update(i)}update(i){const g=(new gt).parse(i);this.updateAST(g)}}function ensureVertexIndexBuiltin(i){if(/@builtin\s*\(\s*vertex_index\s*\)/.test(i))return i;return i.replace(/(@vertex\s+fn\s+)([a-zA-Z_][a-zA-Z0-9_]*)\s*\(([^)]*)(\))/,(i,g,x,v,_)=>{const y=v.trim(),b="@builtin(vertex_index) redgpu_auto_builtin_vertex_index: u32";return`${g}${x}(${0===y.length?b:`${y}, ${b}`}${_}`})}class WGSLUniformTypes{static get i32(){return{numElements:1,align:4,size:4,type:"i32",wgslType:"i32",View:Int32Array}}static get u32(){return{numElements:1,align:4,size:4,type:"u32",wgslType:"u32",View:Uint32Array}}static get f32(){return{numElements:1,align:4,size:4,type:"f32",wgslType:"f32",View:Float32Array}}static get f16(){return{numElements:1,align:2,size:2,type:"f16",wgslType:"f16",View:Uint16Array}}static get vec2f32(){return{numElements:2,align:8,size:8,type:"f32",wgslType:"vec2",View:Float32Array}}static get vec2i32(){return{numElements:2,align:8,size:8,type:"i32",wgslType:"vec2",View:Int32Array}}static get vec2u32(){return{numElements:2,align:8,size:8,type:"u32",wgslType:"vec2",View:Uint32Array}}static get vec2u16(){return{numElements:2,align:4,size:4,type:"u16",wgslType:"vec2",View:Uint16Array}}static get vec3i32(){return{numElements:3,align:16,size:12,type:"i32",wgslType:"vec3",View:Int32Array}}static get vec3u32(){return{numElements:3,align:16,size:12,type:"u32",wgslType:"vec3",View:Uint32Array}}static get vec3f32(){return{numElements:3,align:16,size:12,type:"f32",wgslType:"vec3",View:Float32Array}}static get vec3u16(){return{numElements:3,align:8,size:6,type:"u16",wgslType:"vec3",View:Uint16Array}}static get vec4i32(){return{numElements:4,align:16,size:16,type:"i32",wgslType:"vec4",View:Int32Array}}static get vec4u32(){return{numElements:4,align:16,size:16,type:"u32",wgslType:"vec4",View:Uint32Array}}static get vec4f32(){return{numElements:4,align:16,size:16,type:"f32",wgslType:"vec4",View:Float32Array}}static get vec4u16(){return{numElements:4,align:8,size:8,type:"u16",wgslType:"vec4",View:Uint16Array}}static get mat2x2f32(){return{numElements:4,align:8,size:16,type:"f32",wgslType:"mat2x2",View:Float32Array}}static get mat2x2u16(){return{numElements:4,align:4,size:8,type:"u16",wgslType:"mat2x2",View:Uint16Array}}static get mat3x2f32(){return{numElements:6,align:8,size:24,type:"f32",wgslType:"mat3x2",View:Float32Array}}static get mat3x2u16(){return{numElements:6,align:4,size:12,type:"u16",wgslType:"mat3x2",View:Uint16Array}}static get mat3x3f32(){return{numElements:16,align:16,size:64,type:"f32",wgslType:"mat3x3",View:Float32Array}}static get mat4x2f32(){return{numElements:8,align:8,size:32,type:"f32",wgslType:"mat4x2",View:Float32Array}}static get mat4x2u16(){return{numElements:8,align:4,size:16,type:"u16",wgslType:"mat4x2",View:Uint16Array}}static get mat2x3f32(){return{numElements:8,align:16,size:32,type:"f32",wgslType:"mat2x3",View:Float32Array}}static get mat2x3u16(){return{numElements:8,align:8,size:16,type:"u16",wgslType:"mat2x3",View:Uint16Array}}static get mat4x4f32(){return{numElements:16,align:16,size:64,type:"f32",wgslType:"mat4x4",View:Float32Array}}static get mat4x4u16(){return{numElements:16,align:8,size:32,type:"u16",wgslType:"mat4x4",View:Uint16Array}}}Object.freeze(WGSLUniformTypes);const processMembers=(i,g=0,x=0)=>{let v=0,_=x;const y=i?.reduce((i,x,y)=>{const{type:b,offset:S,size:w,stride:L,count:k,isArray:H}=x,{format:z}=b,q="array"===b.name?`${z.name}${z.format?`${z.format.name}`:""}`:`${b.name}${z?`${z.name}`:""}`;if(v=g,_=S+w,i[x.name]=((i,g,x)=>{const v=WGSLUniformTypes[x];return{uniformOffset:i.offset+g,uniformOffsetForData:i.offset,stride:i.stride,isArray:i.isArray,typeInfo:v,View:v?.View}})(x,g,q),H&&z.members){const g=processMembers(z.members).members;i[x.name].memberList=Array.from({length:k},(i,x)=>{const v={};for(const i in g){const _=v[i]={...g[i]};_.uniformOffset=_.uniformOffset+S+L*x}return v})}else b.members&&(i[x.name]=processMembers(b.members,S+g,_));return i},{});return{members:y,startOffset:v,endOffset:_}},oi=new Map,parseWGSL=(i,g,x)=>{if(!i)throw new Error(`[parseWGSL] sourceName is required. (provided: ${i})`);g=ensureVertexIndexBuiltin(g);const{defaultSource:v,shaderSourceVariant:_,conditionalBlocks:y,cacheKey:b}=preprocessWGSL(i,g,x),S=oi.get(b);let w;if(S)w=S;else{const i=new _t(v);w={uniforms:{...(k=i.uniforms,k.reduce((i,g)=>(i[g.name]={name:g.name,...processMembers(g.members),arrayBufferByteLength:g.size,stride:g.stride},g.attributes?.forEach(x=>i[g.name][x.name]=+x.value),i),{}))},storage:{...(L=i.storage,L.reduce((i,g)=>(i[g.name]={name:g.name,...processMembers(g.members),arrayBufferByteLength:g.size,stride:g.stride,acccess:g.access,type:g.type},g.attributes?.forEach(x=>i[g.name][x.name]=+x.value),i),{}))},samplers:i.samplers,textures:i.textures,vertexEntries:i.entry.vertex.map(i=>i.name),fragmentEntries:i.entry.fragment.map(i=>i.name),computeEntries:i.entry.compute.map(i=>i.name)},_.setBaseInfo(w.textures,w.samplers),y.forEach(i=>{const g=_.getVariant(i),x=new _t(g),v=x.textures.filter(i=>!w.textures.find(g=>g.name===i.name)),y=x.samplers.filter(i=>!w.samplers.find(g=>g.name===i.name));_.addConditionalInfo(i,v,y)}),w.textures=_.getUnionTextures(),w.samplers=_.getUnionSamplers(),oi.set(b,w)}var L,k;return{...w,defaultSource:v,shaderSourceVariant:_,conditionalBlocks:y}},ui={ZERO:"zero",ONE:"one",SRC:"src",ONE_MINUS_SRC:"one-minus-src",SRC_ALPHA:"src-alpha",ONE_MINUS_SRC_ALPHA:"one-minus-src-alpha",DST:"dst",ONE_MINUS_DST:"one-minus-dst",DST_ALPHA:"dst-alpha",ONE_MINUS_DST_ALPHA:"one-minus-dst-alpha",SRC_ALPHA_SATURATED:"src-alpha-saturated",CONSTANT:"constant",ONE_MINUS_CONSTANT:"one-minus-constant",SRC1:"src1",ONE_MINUS_SRC1:"one-minus-src1",SRC1_ALPHA:"src1-alpha",ONE_MINUS_SRC1_ALPHA:"one-minus-src1-alpha"};Object.freeze(ui);const li={ADD:"add",SUBTRACT:"subtract",REVERSE_SUBTRACT:"reverse-subtract",MIN:"min",MAX:"max"};Object.freeze(li);const ci=Object.values(ui),hi=Object.values(li);class BlendState{state;#Yt;#Wt;#Zt;#Jt;constructor(i,g=ui.SRC_ALPHA,x=ui.ONE_MINUS_SRC_ALPHA,v=li.ADD){this.#Jt=i,this.srcFactor=g,this.dstFactor=x,this.operation=v}get operation(){return this.#Zt}set operation(i){hi.includes(i)||consoleAndThrowError(`Invalid GPUBlendOperation: ${i}. Valid operations are ${hi.join(", ")}`),this.#Zt=i,this.#Qt()}get srcFactor(){return this.#Yt}set srcFactor(i){ci.includes(i)||consoleAndThrowError(`Invalid GPUBlendFactor: ${i}. Valid srcFactor factors are ${ci.join(", ")}`),this.#Yt=i,this.#Qt()}get dstFactor(){return this.#Wt}set dstFactor(i){ci.includes(i)||consoleAndThrowError(`Invalid GPUBlendFactor: ${i}. Valid dstFactor factors are ${ci.join(", ")}`),this.#Wt=i,this.#Qt()}#Qt(){const i=this.#Zt?{operation:this.#Zt}:{},g=this.#Yt?{srcFactor:this.#Yt}:{},x=this.#Wt?{dstFactor:this.#Wt}:{};this.state={...i,...g,...x},this.#Jt.dirtyPipeline=!0}}const fi=new Map,di=new WeakMap;let mi,pi,gi;class PackedTexture extends RedGPUObject{#ne;#V;#er;#me=new Map;constructor(i){super(i),this.#tr(),this.#ne=this.#rr()}get gpuTexture(){return this.#V}static getCacheMap(){return fi}async packing(i,g,x,v,_,y){const b={r:"r",g:"g",b:"b",a:"a",..._},S=`${i.r?.label||""}_${i.g?.label||""}_${i.b?.label||""}_${i.a?.label||""}`,w=`${JSON.stringify(b)}_${S}`;if(!(i.r||i.g||i.b||i.a))return;this.#ir(w);fi.get(w)||await this.#nr(i,g,x,v,b,w,y)}destroy(){const i=di.get(this);if(i){const g=fi.get(i);g&&(g.useNum--,0===g.useNum&&(g.gpuTexture?.destroy(),fi.delete(i))),di.delete(this)}}#tr(){const{resourceManager:i}=this;gi=i.createGPUBuffer("PACK_TEXTURE_MAPPING_BUFFER",{size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),pi||(pi=i.createBindGroupLayout("PACK_TEXTURE_BIND_GROUP_LAYOUT",{entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:2,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:3,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:4,visibility:GPUShaderStage.FRAGMENT,sampler:{}},{binding:5,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]})),mi||(mi=this.#ar())}#sr(i){const g=`${i.r?.label||"empty"}_${i.g?.label||"empty"}_${i.b?.label||"empty"}_${i.a?.label||"empty"}`,{resourceManager:x,gpuDevice:v}=this;if(!this.#me.has(g)){const _=[{binding:0,resource:x.getGPUResourceBitmapTextureView(i.r)},{binding:1,resource:x.getGPUResourceBitmapTextureView(i.g)},{binding:2,resource:x.getGPUResourceBitmapTextureView(i.b)},{binding:3,resource:x.getGPUResourceBitmapTextureView(i.a)},{binding:4,resource:this.#ne},{binding:5,resource:{buffer:gi}}],y=v.createBindGroup({label:`PACK_TEXTURE_BIND_GROUP_${g}`,layout:pi,entries:_});this.#me.set(g,y)}this.#er=this.#me.get(g)}#ir(i){const g=di.get(this);if(g&&g!==i){const i=fi.get(g);i&&(i.useNum--,0===i.useNum&&(i.gpuTexture?.destroy(),fi.delete(g)))}const x=fi.get(i);x&&(this.#V=x.gpuTexture,x.useNum++),di.set(this,i)}async#nr(i,g,x,v,_,y,b){const S={size:[g,x,1],format:"rgba8unorm",usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC,label:v||`PACK_TEXTURE_${createUUID()}`,mipLevelCount:getMipLevelCount(g,x)};this.#V&&(this.#V=null);const{resourceManager:w,gpuDevice:L,uuid:k}=this,H=w.createManagedTexture(S),z=new Uint32Array([["r","g","b","a"].indexOf(_.r),["r","g","b","a"].indexOf(_.g),["r","g","b","a"].indexOf(_.b),["r","g","b","a"].indexOf(_.a)]);L.queue.writeBuffer(gi,0,z),this.#sr(i),this.#or(H,b),this.#V=S.mipLevelCount>1?w.mipmapGenerator.generateMipmap(H,S,!0):H,fi.set(y,{gpuTexture:this.#V,useNum:1,mappingKey:y,uuid:k}),this.#er=null}#or(i,g){const{resourceManager:x,gpuDevice:v}=this,_=g||v.createCommandEncoder({label:"PackedTexture_CommandEncoder"}),y=_.beginRenderPass({colorAttachments:[{view:x.getGPUResourceBitmapTextureView(i,{baseMipLevel:0,mipLevelCount:1,dimension:"2d",label:`${i.label}_RENDER_TARGET`}),loadOp:"clear",storeOp:"store",clearValue:[0,0,0,0]}]});y.setPipeline(mi),y.setBindGroup(0,this.#er),y.draw(6,1,0,0),y.end(),g||v.queue.submit([_.finish()])}#ar(){const i="struct VertexOutput{@builtin(position)position:vec4,@location(0)uv:vec2,};@vertex fn vertexMain(@builtin(vertex_index)VertexIndex:u32)->VertexOutput{var pos=array,6>(vec2(-1.0,-1.0),vec2(1.0,-1.0),vec2(-1.0,1.0),vec2(-1.0,1.0),vec2(1.0,-1.0),vec2(1.0,1.0));var uv=array,6>(vec2(.0,1.0),vec2(1.0,1.0),vec2(.0,.0),vec2(.0,.0),vec2(1.0,1.0),vec2(1.0,.0));var output:VertexOutput;output.position=vec4(pos[VertexIndex],.0,1.0);output.uv=uv[VertexIndex];return output;}struct ComponentMapping{r_component:u32,g_component:u32,b_component:u32,a_component:u32,};@group(0)@binding(0)var textureR:texture_2d;@group(0)@binding(1)var textureG:texture_2d;@group(0)@binding(2)var textureB:texture_2d;@group(0)@binding(3)var textureA:texture_2d;@group(0)@binding(4)var sampler0:sampler;@group(0)@binding(5)varmapping:ComponentMapping;fn getComponent(color:vec4,componentIndex:u32)->f32{switch componentIndex{case 0u:{return color.r;}case 1u:{return color.g;}case 2u:{return color.b;}case 3u:{return color.a;}default:{return .0;}}}@fragment fn fragmentMain(input:VertexOutput)->@location(0)vec4{let colorR=textureSample(textureR,sampler0,input.uv);let colorG=textureSample(textureG,sampler0,input.uv);let colorB=textureSample(textureB,sampler0,input.uv);let colorA=textureSample(textureA,sampler0,input.uv);let r=getComponent(colorR,mapping.r_component);let g=getComponent(colorG,mapping.g_component);let b=getComponent(colorB,mapping.b_component);let a=getComponent(colorA,mapping.a_component);return vec4(r,g,b,a);}",{resourceManager:g,gpuDevice:x}=this,v=x.createPipelineLayout({label:"PACK_TEXTURE_PIPELINE_LAYOUT",bindGroupLayouts:[pi]});return x.createRenderPipeline({label:"PACK_TEXTURE_PIPELINE",layout:v,vertex:{module:g.createGPUShaderModule("PACK_TEXTURE_SHADER_MODULE",{code:i}),entryPoint:"vertexMain"},fragment:{module:g.createGPUShaderModule("PACK_TEXTURE_SHADER_MODULE",{code:i}),entryPoint:"fragmentMain",targets:[{format:"rgba8unorm"}]},primitive:{topology:"triangle-list"}})}#rr(){return new Sampler(this.redGPUContext).gpuSampler}}const xi={NORMAL:0,MULTIPLY:1,LIGHTEN:2,SCREEN:3,LINEAR_DODGE:4,SUBTRACT:5,DARKEN:6,OVERLAY:7,COLOR_DODGE:8,COLOR_BURN:9,HARD_LIGHT:10,SOFT_LIGHT:11,DIFFERENCE:12,EXCLUSION:13,DIVIDE:14,VIVID_LIGHT:15,LINEAR_BURN:16,PIN_LIGHT:17,SATURATION:18,HUE:19,LUMINOSITY:20,COLOR:21,NEGATION:22};class FragmentGPURenderInfo{fragmentShaderModule;fragmentShaderSourceVariant;fragmentShaderVariantConditionalBlocks;fragmentUniformInfo;fragmentBindGroupLayout;fragmentUniformBuffer;fragmentUniformBindGroup;fragmentState;constructor(i,g,x,v,_,y,b,S){this.fragmentShaderModule=i,this.fragmentShaderSourceVariant=g,this.fragmentShaderVariantConditionalBlocks=x,this.fragmentUniformInfo=v,this.fragmentBindGroupLayout=_,this.fragmentUniformBuffer=y,this.fragmentUniformBindGroup=b,this.fragmentState=S}}Object.freeze(FragmentGPURenderInfo);const getBindGroupLayoutDescriptorFromShaderInfo=(i,g,x,v=!0)=>{const{textures:_,samplers:y,uniforms:b,storage:S}=i,w=[];for(const i in S){const v=S[i],{binding:_,name:y,group:b,type:L}=v;if(v.access){const i={write:"write-only-storage",read:"read-only-storage",read_write:"read-write-storage"}[v.access];g===b&&w.push({binding:_,visibility:x,buffer:{type:i}})}else if(g===b){const{access:i,format:g}=L,v={write:"write-only",read:"read-only",read_write:"read-write"}[i],y=g.name;w.push({binding:_,visibility:x,storageTexture:{access:v,format:y}})}}for(const i in _){const v=_[i],{binding:y,name:b,group:S,type:L}=v,{name:k}=L;g===S&&w.push({binding:y,visibility:x,texture:"texture_depth_2d"===k||"texture_depth_multisampled_2d"===k?{viewDimension:"2d",sampleType:"depth",multisampled:"texture_depth_multisampled_2d"===k}:"texture_cube"===k?{viewDimension:"cube"}:"texture_3d"===k?{viewDimension:"3d"}:"texture_2d_array"===k?{viewDimension:"2d-array",sampleType:"float",multisampled:!1}:{}})}for(const i in y){const v=y[i],{binding:_,name:b,group:S}=v;g===S&&w.push({binding:_,visibility:x,sampler:{type:"filtering"}})}for(const i in b){const v=b[i],{binding:_,name:y,group:S}=v;g===S&&w.push({binding:_,visibility:x,buffer:{type:"uniform"}})}return{entries:w}},getFragmentBindGroupLayoutDescriptorFromShaderInfo=(i,g)=>getBindGroupLayoutDescriptorFromShaderInfo(i,g,GPUShaderStage.FRAGMENT),getVertexBindGroupLayoutDescriptorFromShaderInfo=(i,g)=>getBindGroupLayoutDescriptorFromShaderInfo(i,g,GPUShaderStage.VERTEX),getComputeBindGroupLayoutDescriptorFromShaderInfo=(i,g,x)=>getBindGroupLayoutDescriptorFromShaderInfo(i,g,GPUShaderStage.COMPUTE,x),applyProperties=(i,g,x)=>{(Array.isArray(g)?g:[g]).forEach(g=>{if(Array.isArray(g)){const[v,..._]=g;Object.defineProperty(i.prototype,v,x(v,..._))}else"object"==typeof g&&null!==g&&"key"in g?Object.defineProperty(i.prototype,g.key,x(g)):Object.defineProperty(i.prototype,g,x(g))})},updateTargetUniform=(i,g,x)=>{let v,_;const{gpuRenderInfo:y}=i;i.isInstanceofMaterial?(v=y.fragmentUniformInfo,_=y.fragmentUniformBuffer):i.isInstanceofPostEffect?(v=i.uniformsInfo,_=i.uniformBuffer):y?.vertexUniformInfo&&(v=y.vertexUniformInfo,_=y.vertexUniformBuffer),_&&v.members[g]&&_.writeOnlyBuffer(v.members[g],x)},vi={enumerable:!0,configurable:!1};function createSetter$6(i,g,x=0,v){return function(_){validatePositiveNumberRange(_),void 0!==x&&_v&&(console.warn(`Value for ${i} exceeds the maximum (${v}). Adjusted to ${v}.`),_=v),this[g]=_,updateTargetUniform(this,i,_)}}function definePositiveNumberRange_func(i){const{key:g,value:x=0,min:v=0,max:_}=i,y=Symbol(g);return{get:function(){return void 0===this[y]&&(this[y]=x),this[y]},set:createSetter$6(g,y,v,_),...vi}}Object.freeze(vi);const definePositiveNumber=(i,g)=>applyProperties(i,g,definePositiveNumberRange_func);function createSetter$5(i,g){return function(x){"boolean"!=typeof x&&console.warn(`Value for ${i} should be a boolean. Received: ${typeof x}.`),this[g]=x,updateTargetUniform(this,i,x?1:0),this.dirtyPipeline=!0}}function defineBoolean_func(i){const{key:g,value:x=!1}=i,v=Symbol(g);return{get:function(){return void 0===this[v]&&(this[v]=x),this[v]},set:createSetter$5(g,v),...vi}}Object.freeze(definePositiveNumber);const defineBoolean=(i,g)=>applyProperties(i,g,defineBoolean_func);function createColorRGBA(i,g,x,v){let _=255,y=255,b=255;if(isHexColor(v)){const i=convertHexToRgb(v);_=i.r,y=i.g,b=i.b}return new ColorRGBA(_,y,b,1,()=>{updateTargetUniform(i,g,i[x].rgbaNormalLinear)})}function defineColorRGBA_func(i){const g=i.key,x=i.value??"#fff",v=Symbol(g);return{get:function(){return void 0===this[v]&&(this[v]=createColorRGBA(this,g,v,x)),this[v]},set:function(i){if("string"==typeof i&&isHexColor(i)){const{r:x,g:_,b:y}=convertHexToRgb(i);this[v]?(this[v].r=x,this[v].g=_,this[v].b=y):this[v]=createColorRGBA(this,g,v,i)}else i instanceof ColorRGBA&&(this[v]=i,updateTargetUniform(this,g,i.rgbaNormalLinear))},...vi}}Object.freeze(defineBoolean);const defineColorRGBA=(i,g)=>applyProperties(i,g,defineColorRGBA_func);Object.freeze(defineColorRGBA);class ABaseMaterial extends ResourceBase{use2PathRender;gpuRenderInfo;dirtyPipeline=!1;transparent=!1;#ur;#lr;#cr=GPUColorWrite.ALL;#hr;#fr;#Ke;#dr;#mr;#pr;#gr;#xr;#vr;#_r;#yr;#br;#we;#Sr;#Tr=xi.MULTIPLY;constructor(i,g,x,v){super(i);const{resourceManager:_}=i;this.#br=g,this.#dr=`FRAGMENT_MODULE_${this.#br}`,this.#mr=`FRAGMENT_BIND_GROUP_DESCRIPTOR_${g}`,this.#pr=`FRAGMENT_BIND_GROUP_LAYOUT_${g}`,this.#gr=x,this.#xr=x?.storage,this.#vr=x?.uniforms.uniforms,this.#Sr=v,this.#_r=x.shaderSourceVariant.getUnionTextures(),this.#yr=x.shaderSourceVariant.getUnionSamplers(),this.#we=_.getGPUBindGroupLayout(this.#pr)||_.createBindGroupLayout(this.#pr,getFragmentBindGroupLayoutDescriptorFromShaderInfo(x,v)),this.#ur=new BlendState(this),this.#lr=new BlendState(this),this.#hr=_.basicSampler.gpuSampler,this.#fr=_.emptyBitmapTextureView,this.#Ke=_.emptyCubeTextureView}get tintBlendMode(){const i=Object.entries(xi).find(([,i])=>i===this.#Tr);if(!i)throw new Error(`Invalid tint mode value: ${this.#Tr}`);return i[0]}set tintBlendMode(i){const{fragmentUniformInfo:g,fragmentUniformBuffer:x}=this.gpuRenderInfo;let v;if("string"==typeof i){if(!(i in xi))throw new Error(`Invalid tint mode key: ${i}`);v=xi[i]}else{if("number"!=typeof i||!Object.values(xi).includes(i))throw new Error(`Invalid tint mode: ${i}`);v=i}x.writeOnlyBuffer(g.members.tintBlendMode,v),this.#Tr=v}get MODULE_NAME(){return this.#br}get FRAGMENT_SHADER_MODULE_NAME(){return this.#dr}get FRAGMENT_BIND_GROUP_DESCRIPTOR_NAME(){return this.#mr}get STORAGE_STRUCT(){return this.#xr}get UNIFORM_STRUCT(){return this.#vr}get blendColorState(){return this.#ur}get blendAlphaState(){return this.#lr}get writeMaskState(){return this.#cr}set writeMaskState(i){this.#cr=i}initGPURenderInfos(){const{redGPUContext:i}=this,{resourceManager:g}=i,x=g.createGPUShaderModule(this.#dr,{code:this.#gr.defaultSource}),v=new ArrayBuffer(Math.max(this.#vr.arrayBufferByteLength,16)),_=new UniformBuffer(i,v,`UniformBuffer_${this.#br}_${this.uuid}`);this.gpuRenderInfo=new FragmentGPURenderInfo(x,this.#gr.shaderSourceVariant,this.#gr.conditionalBlocks,this.#vr,this.#we,_,null,null),this._updateBaseProperty(),this._updateFragmentState()}_updateFragmentState(){const{gpuDevice:i,resourceManager:g}=this.redGPUContext;this.#wr();const x=[];for(const i in this.#_r){const v=this.#_r[i],{binding:_,name:y,group:b,type:S}=v,{name:w}=S;let L;L="texture_cube"===w?g.getGPUResourceCubeTextureView(this[y]):this[y]instanceof PackedTexture?g.getGPUResourceBitmapTextureView(this[y]):g.getGPUResourceBitmapTextureView(this[y])||this.#fr,2===b&&x.push({binding:_,resource:L})}for(const i in this.#yr){const g=this.#yr[i],{binding:v,name:_,group:y}=g;2===y&&x.push({binding:v,resource:this.getGPUResourceSampler(this[_])})}this.#vr&&x.push({binding:this.#vr.binding,resource:{buffer:this.gpuRenderInfo.fragmentUniformBuffer.gpuBuffer,offset:0,size:this.gpuRenderInfo.fragmentUniformBuffer.size}});const v={layout:this.gpuRenderInfo.fragmentBindGroupLayout,label:this.#mr,entries:x},_=i.createBindGroup(v);this.gpuRenderInfo.fragmentState=this.getFragmentRenderState(),this.gpuRenderInfo.fragmentUniformBindGroup=_}getFragmentRenderState(i="main"){return{module:this.gpuRenderInfo.fragmentShaderModule,entryPoint:i,targets:[{format:"rgba16float",blend:{color:this.blendColorState.state,alpha:this.blendAlphaState.state},writeMask:this.writeMaskState},{format:navigator.gpu.getPreferredCanvasFormat(),blend:void 0,writeMask:this.writeMaskState},{format:"rgba16float",blend:void 0,writeMask:this.writeMaskState}]}}_updateBaseProperty(){const{fragmentUniformInfo:i,fragmentUniformBuffer:g}=this.gpuRenderInfo,{members:x}=i;for(const v in x){const x=this[v];x instanceof ColorRGBA?g.writeOnlyBuffer(i.members[v],x.rgbaNormalLinear):x instanceof ColorRGB?g.writeOnlyBuffer(i.members[v],x.rgbNormalLinear):_i.test(v)||(this[v]=x)}}getGPUResourceSampler(i){return i?.gpuSampler||this.#hr}#wr(){const{resourceManager:i}=this.redGPUContext,g=this.#Mr(),x=`${this.#dr}_${g}`;let v=i.getGPUShaderModule(x);if(!v){const _=this.gpuRenderInfo.fragmentShaderSourceVariant.getVariant(g);v=_?i.createGPUShaderModule(x,{code:_}):this.gpuRenderInfo.fragmentShaderModule}this.gpuRenderInfo.fragmentShaderModule=v,this.#_r=this.gpuRenderInfo.fragmentShaderSourceVariant.getVariantTextures(g),this.#yr=this.gpuRenderInfo.fragmentShaderSourceVariant.getVariantSamplers(g);const _=`${this.#pr}_${g}`;let y=i.getGPUBindGroupLayout(_);if(!y){const g={...this.#gr,textures:this.#_r,samplers:this.#yr};y=i.createBindGroupLayout(_,getFragmentBindGroupLayoutDescriptorFromShaderInfo(g,this.#Sr))}this.gpuRenderInfo.fragmentBindGroupLayout=y}#Mr(){const{fragmentShaderVariantConditionalBlocks:i}=this.gpuRenderInfo,g=new Set;for(const x of i)this[x]&&g.add(x);const x=g.size>0?Array.from(g).sort().join("+"):"none";return g.size,x}}const _i=/^use\w+Texture$/;Object.defineProperty(ABaseMaterial.prototype,"isInstanceofMaterial",{value:!0,writable:!1}),definePositiveNumber(ABaseMaterial,[{key:"opacity",value:1,max:1}]),defineBoolean(ABaseMaterial,[{key:"useTint",value:!1}]),defineColorRGBA(ABaseMaterial,[{key:"tint",value:"#ffffff"}]),Object.freeze(ABaseMaterial);class ABitmapBaseMaterial extends ABaseMaterial{__packingList;constructor(i,g,x,v){super(i,g,x,v)}updateTexture(i,g){i&&i.__removeDirtyPipelineListener(this.#Pr),g&&g.__addDirtyPipelineListener(this.#Pr),this.#Pr()}updateSampler(i,g){i&&i.__removeDirtyPipelineListener(this.#Pr),g&&g.__addDirtyPipelineListener(this.#Pr),this.#Pr()}#Pr=()=>{this.dirtyPipeline=!0;{let i=(this.__packingList||[]).length;for(;i--;)this.__packingList[i]()}this.gpuRenderInfo?.fragmentShaderModule?this._updateFragmentState():this.initGPURenderInfos()}}Object.freeze(ABitmapBaseMaterial);class AUVTransformBaseMaterial extends ABitmapBaseMaterial{dirtyTextureTransform=!1;#Rr=[0,0];#Cr=[1,1];constructor(i,g,x,v){super(i,g,x,v)}get textureOffset(){return this.#Rr}set textureOffset(i){this.dirtyTextureTransform=!0,this.#Rr=i}get textureScale(){return this.#Cr}set textureScale(i){this.dirtyTextureTransform=!0,this.#Cr=i}}Object.freeze(AUVTransformBaseMaterial);var yi=Object.freeze({__proto__:null,ABaseMaterial:ABaseMaterial,ABitmapBaseMaterial:ABitmapBaseMaterial,AUVTransformBaseMaterial:AUVTransformBaseMaterial,FragmentGPURenderInfo:FragmentGPURenderInfo,getComputeBindGroupLayoutDescriptorFromShaderInfo:getComputeBindGroupLayoutDescriptorFromShaderInfo,getFragmentBindGroupLayoutDescriptorFromShaderInfo:getFragmentBindGroupLayoutDescriptorFromShaderInfo,getVertexBindGroupLayoutDescriptorFromShaderInfo:getVertexBindGroupLayoutDescriptorFromShaderInfo});const bi=new WeakMap;let Si=0;class ASinglePassPostEffect extends RedGPUObject{isLdr=!1;#Br;#Dr;#Er;#Ir;#Ar;#Lr;#Ur;#kr;#Gr;#Or;#Vr;#Nr;#Fr;#Hr;#zr;#$r;#se;#jr;#Kr;#Xr;#l;#qr;#Yr;#Wr;#Zr;#Jr;#Qr=16;#ei=16;#ti=1;#H=0;#ri;#ii;#ni=new Map;#ai;#si=new Map;constructor(i,g){super(i),g&&(void 0!==g.x&&(this.#Qr=g.x),void 0!==g.y&&(this.#ei=g.y),void 0!==g.z&&(this.#ti=g.z))}get videoMemorySize(){return this.#H}get storageInfo(){return this.#Xr}get shaderInfo(){return this.antialiasingManager.useMSAA?this.#qr:this.#Yr}get uniformBuffer(){return this.#se}get uniformsInfo(){return this.#jr}get systemUniformsInfo(){return this.#Kr}get WORK_SIZE_X(){return this.#Qr}get WORK_SIZE_Y(){return this.#ei}get WORK_SIZE_Z(){return this.#ti}get outputTextureView(){return this.#Jr}clear(){this.#Zr=null,this.#Jr=null,this.#ni.clear(),this.#ai=null,this.#si.clear()}init(i,g,x){this.#l=g;const{resourceManager:v}=i;this.#Br=v.createGPUShaderModule(`${g}_MSAA`,{code:x.msaa}),this.#Dr=v.createGPUShaderModule(`${g}_NonMSAA`,{code:x.nonMsaa}),this.#qr=parseWGSL(`${g}_MSAA`,x.msaa),this.#Yr=parseWGSL(`${g}_NonMSAA`,x.nonMsaa);const{storage:_,uniforms:y}=this.#qr;if(this.#Xr=_,this.#jr=y.uniforms,this.#Kr=y.systemUniforms,this.#jr){const g=new ArrayBuffer(this.#jr.arrayBufferByteLength);this.#se=new UniformBuffer(i,g,`${this.constructor.name}_UniformBuffer`)}{const{members:i}=this.#jr||{};if(i)for(const g in i)this.uniformBuffer.writeOnlyBuffer(i[g],this[g])}}render(i,g,x,...v){const{gpuDevice:_,antialiasingManager:y}=this,{useMSAA:b,msaaID:S}=y,w=i.postEffectManager.texturePool.allocResult(g,x,"rgba16float");this.#Zr=w.texture,this.#Jr=w.textureView;const L=this.#Wr?.width!==g||this.#Wr?.height!==x,k=this.#ri!==b||this.#ii!==S;return(L||k)&&(this.#ni.clear(),this.#ai=null,this.#si.clear()),this.#oi(i,b,_),this.#ui(v,this.#Jr,b,_),this.#li(i,g,x,i.postEffectManager.gbufferBindGroup),this.#ri=b,this.#ii=S,this.#Wr={width:g,height:x},this.#ci(),{texture:this.#Zr,textureView:this.#Jr}}updateUniform(i,g){const x=this.uniformsInfo?.members[i];x&&this.uniformBuffer.writeOnlyBuffer(x,g)}#hi(i){if(!i)return 0;let g=bi.get(i);return void 0===g&&(g=Si++,bi.set(i,g)),g}#li(i,g,x,v){const{commandEncoderManager:_}=this,{renderViewStateData:y}=i;_.addPostProcessComputePass(`ASinglePassPostEffect_${this.#l}_ComputePass`,i=>{i.setPipeline(this.#Hr);const _=y.swapBufferIndex?this.#Ur:this.#Lr;_&&i.setBindGroup(0,_),this.#kr&&i.setBindGroup(1,this.#kr),v&&i.setBindGroup(2,v),this.#Gr&&i.setBindGroup(3,this.#Gr),i.dispatchWorkgroups(Math.ceil(g/this.WORK_SIZE_X),Math.ceil(x/this.WORK_SIZE_Y))})}#oi(i,g,x){const v=g?this.#zr:this.#$r;if(v)return void(this.#Hr=v);const{resourceManager:_}=this,y=g?this.#qr:this.#Yr,b=g?this.#Br:this.#Dr,S=`${this.#l}_BIND_GROUP_LAYOUT_0_USE_MSAA_${g}`,w=`${this.#l}_BIND_GROUP_LAYOUT_1_USE_MSAA_${g}`,L=`${this.#l}_BIND_GROUP_LAYOUT_3_USE_MSAA_${g}`;this.#Er=_.getGPUBindGroupLayout(S)||_.createBindGroupLayout(S,getComputeBindGroupLayoutDescriptorFromShaderInfo(y,0,g)),this.#Ir=_.getGPUBindGroupLayout(w)||_.createBindGroupLayout(w,getComputeBindGroupLayoutDescriptorFromShaderInfo(y,1,g)),this.#Ar=_.getGPUBindGroupLayout(L)||_.createBindGroupLayout(L,getComputeBindGroupLayoutDescriptorFromShaderInfo(y,3,g));const k=x.createComputePipeline({label:`${this.#l}_COMPUTE_PIPELINE_USE_MSAA_${g}`,layout:x.createPipelineLayout({bindGroupLayouts:[this.#Er,this.#Ir,i.postEffectManager.gbufferBindGroupLayout,this.#Ar]}),compute:{module:b,entryPoint:"main"}});g?this.#zr=k:this.#$r=k,this.#Hr=k}#ui(i,g,x,v){const{storage:_,textures:y}=this.shaderInfo,b=i.map(i=>this.#hi(i.texture)).join("_"),S=this.#ni.get(`${b}_swap0`),w=this.#ni.get(`${b}_swap1`);if(S&&w)this.#Lr=S,this.#Ur=w;else{this.#Or=[],this.#Vr=[];for(const g in _){const{binding:x,name:v,group:y}=_[g];if(0===y&&"outputTexture"!==v){const g=i[x]?.textureView;g&&(this.#Or.push({binding:x,resource:g}),this.#Vr.push({binding:x,resource:g}))}}y.forEach(({binding:g,group:x})=>{if(0===x){const x=i[g]?.textureView;x&&(this.#Or.push({binding:g,resource:x}),this.#Vr.push({binding:g,resource:x}))}}),this.#Lr=v.createBindGroup({label:`${this.#l}_BIND_GROUP_0_USE_MSAA_${x}_SWAP0`,layout:this.#Er,entries:this.#Or}),this.#Ur=v.createBindGroup({label:`${this.#l}_BIND_GROUP_0_USE_MSAA_${x}_SWAP1`,layout:this.#Er,entries:this.#Vr}),this.#ni.set(`${b}_swap0`,this.#Lr),this.#ni.set(`${b}_swap1`,this.#Ur)}this.#ai?this.#kr=this.#ai:this.#se&&this.uniformsInfo&&(this.#Nr=[{binding:0,resource:{buffer:this.#se.gpuBuffer,offset:0,size:this.#se.size}}],this.#kr=v.createBindGroup({label:`${this.#l}_BIND_GROUP_1_USE_MSAA_${x}`,layout:this.#Ir,entries:this.#Nr}),this.#ai=this.#kr);const L=this.#hi(this.#Zr);this.#si.has(L)?this.#Gr=this.#si.get(L):(this.#Fr=[{binding:0,resource:g}],this.#Gr=v.createBindGroup({label:`${this.#l}_BIND_GROUP_3_USE_MSAA_${x}`,layout:this.#Ar,entries:this.#Fr}),this.#si.set(L,this.#Gr))}#ci(){this.#H=this.#se?this.#se.size:0}}Object.defineProperty(ASinglePassPostEffect.prototype,"isInstanceofPostEffect",{value:!0,writable:!1}),Object.freeze(ASinglePassPostEffect);class AMultiPassPostEffect extends ASinglePassPostEffect{#fi=[];#H=0;constructor(i,g){super(i),this.#fi.push(...g)}get videoMemorySize(){return this.#ci(),this.#H}get passList(){return this.#fi}clear(){this.#fi.forEach(i=>i.clear())}render(i,g,x,v){let _;const y=i.postEffectManager.texturePool;return this.#fi.forEach((b,S)=>{const w=_;S&&(v=_),_=b.render(i,g,x,v),w&&y.release(w.texture)}),_}#ci(){this.#H=0,this.#fi.forEach(i=>{this.#H+=i.videoMemorySize})}}Object.freeze(AMultiPassPostEffect);const createCode=(i,g,x="",v=!1,_={name:"sourceTexture"})=>{const{WORK_SIZE_X:y,WORK_SIZE_Y:b,WORK_SIZE_Z:S}=i,w=v?"texture_depth_multisampled_2d":"texture_depth_2d";let L="";return(Array.isArray(_)?_:[_]).forEach((i,g)=>{let x,v=!0;x=i.name,void 0!==i.isSampled&&(v=i.isSampled),L+=v?`@group(0) @binding(${g}) var ${x} : texture_2d;\n`:`@group(0) @binding(${g}) var ${x} : texture_storage_2d;\n`}),`\n ${x}\n \n ${L}\n \n ${x?"@group(1) @binding(0) var uniforms: Uniforms;":""}\n \n ${ft.POST_EFFECT_SYSTEM_UNIFORM}\n @group(2) @binding(5) var basicSampler : sampler;\n \n @group(2) @binding(0) var depthTexture : ${w};\n @group(2) @binding(1) var gBufferNormalTexture : texture_2d;\n @group(2) @binding(2) var gBufferMotionVector : texture_2d;\n @group(2) @binding(3) var prevDepthTexture : ${w};\n \n @group(3) @binding(0) var outputTexture : texture_storage_2d;\n \n @compute @workgroup_size(${y}, ${b}, ${S})\n fn main(\n @builtin(global_invocation_id) global_id : vec3,\n ) {\n ${g}\n }\n `},createBasicPostEffectCode=(i,g,x="",v={name:"sourceTexture"})=>({msaa:createCode(i,g,x,!0,v),nonMsaa:createCode(i,g,x,!1,v)});Object.freeze(createBasicPostEffectCode);function createSetter$4(i,g,x=0,v){return function(_){validateUintRange(_),void 0!==x&&_v&&(console.warn(`Value for ${i} exceeds the maximum (${v}). Adjusted to ${v}.`),_=v),this[g]=_,updateTargetUniform(this,i,_)}}function defineUintRange_func(i){const{key:g,value:x=0,min:v=0,max:_}=i,y=Symbol(g);return{get:function(){return void 0===this[y]&&(this[y]=x),this[y]},set:createSetter$4(g,y,v,_),...vi}}const defineUint=(i,g)=>applyProperties(i,g,defineUintRange_func);Object.freeze(defineUint);class BlurX extends ASinglePassPostEffect{constructor(i){super(i),this.init(i,"POST_EFFECT_BLUR_X",createBasicPostEffectCode(this,"let index=global_id.xy;let dimensions=vec2(textureDimensions(sourceTexture));if(f32(index.x)>=dimensions.x||f32(index.y)>=dimensions.y){return;}let invSize=1.0/dimensions;let centerUV=(vec2(index)+0.5)*invSize;let blurSize=uniforms.size*systemUniforms.devicePixelRatio;var sum:vec4=vec4(.0);var totalWeight:f32=.0;let steps=uniforms.sampleCount;for(var i=-steps;i<=steps;i+=1.0){let offsetPixels=(i/steps)*blurSize;let weight=exp(-0.5*pow(i/(steps*0.6),2.0));let sampleUV=centerUV+vec2(offsetPixels*invSize.x,.0);sum+=textureSampleLevel(sourceTexture,basicSampler,sampleUV,.0)*weight;totalWeight+=weight;}textureStore(outputTexture,index,sum/totalWeight);","struct Uniforms{size:f32,sampleCount:f32,};"))}}definePositiveNumber(BlurX,[{key:"size",value:32,min:0,max:512}]),defineUint(BlurX,[{key:"sampleCount",value:10,min:1,max:100}]),Object.freeze(BlurX);class BlurY extends ASinglePassPostEffect{constructor(i){super(i),this.init(i,"POST_EFFECT_BLUR_Y",createBasicPostEffectCode(this,"let index=global_id.xy;let dimensions=vec2(textureDimensions(sourceTexture));if(f32(index.x)>=dimensions.x||f32(index.y)>=dimensions.y){return;}let invSize=1.0/dimensions;let centerUV=(vec2(index)+0.5)*invSize;let blurSize=uniforms.size*systemUniforms.devicePixelRatio;var sum:vec4=vec4(.0);var totalWeight:f32=.0;let steps=uniforms.sampleCount;for(var i=-steps;i<=steps;i+=1.0){let offsetPixels=(i/steps)*blurSize;let weight=exp(-0.5*pow(i/(steps*0.6),2.0));let sampleUV=centerUV+vec2(.0,offsetPixels*invSize.y);sum+=textureSampleLevel(sourceTexture,basicSampler,sampleUV,.0)*weight;totalWeight+=weight;}textureStore(outputTexture,index,sum/totalWeight);","struct Uniforms{size:f32,sampleCount:f32,};"))}}definePositiveNumber(BlurY,[{key:"size",value:32,min:0,max:512}]),defineUint(BlurY,[{key:"sampleCount",value:10,min:1,max:100}]),Object.freeze(BlurY);class GaussianBlur extends AMultiPassPostEffect{#qt=32;#di=10;constructor(i){super(i,[new BlurX(i),new BlurY(i)]),this.size=this.size,this.sampleCount=this.#di}get size(){return this.#qt}set size(i){this.#qt=i,this.passList.forEach(g=>g.size=i)}get sampleCount(){return this.#di}set sampleCount(i){this.#di=i,this.passList.forEach(g=>g.sampleCount=i)}}Object.freeze(GaussianBlur);class SSAO_AO extends ASinglePassPostEffect{constructor(i){super(i),this.init(i,"POST_EFFECT_SSAO",createBasicPostEffectCode(this,"{let screenCoord=vec2(global_id.xy);let texSize=vec2(textureDimensions(sourceTexture));if(screenCoord.x>=texSize.x||screenCoord.y>=texSize.y){return;}let originalColor=textureLoad(sourceTexture,screenCoord,0);let depth=textureLoad(depthTexture,screenCoord,0);var failColor=vec4(select(originalColor.rgb,vec3(1.0),uniforms.useBlur==1u),originalColor.a);if(depth<.001){textureStore(outputTexture,screenCoord,failColor);return;}let normalData=textureLoad(gBufferNormalTexture,screenCoord,0);if(length(normalData.rgb)<.001){textureStore(outputTexture,screenCoord,failColor);return;}let viewPos=getViewPositionFromDepth((vec2(screenCoord)+0.5)/vec2(texSize),depth,systemUniforms.projection.inverseProjectionMatrix);let viewNormal=getViewNormalFromGNormalBuffer(normalData.rgb,systemUniforms.camera.viewMatrix);let distToCamera=-viewPos.z;let depthScale=distToCamera*0.1;let adaptiveRadius=uniforms.radius*(1.0+depthScale);let noiseVec=getNoiseVec(vec2(screenCoord));let tbn=getTBN(viewNormal,noiseVec);let samples=array,8>(vec3(.04,.03,.08),vec3(-.04,.04,.08),vec3(0.10,-.08,0.18),vec3(-.09,-0.10,0.18),vec3(0.18,0.15,0.30),vec3(-0.17,0.18,0.30),vec3(0.28,-0.25,0.45),vec3(-0.27,-0.28,0.45));var totalOcclusion=.0;for(var i=0u;i<8u;i++){let sampleOffset=tbn*samples[i];let sampleDir=normalize(sampleOffset);let sampleViewPos=viewPos+sampleOffset*adaptiveRadius;let clipPos=systemUniforms.projection.projectionMatrix*vec4(sampleViewPos,1.0);let sampleUV=(clipPos.xy/clipPos.w)*vec2(0.5,-0.5)+0.5;if(sampleUV.x<.0||sampleUV.x>1.0||sampleUV.y<.0||sampleUV.y>1.0){continue;}let sampleCoord=vec2(sampleUV*vec2(texSize));let realDepth=textureLoad(depthTexture,sampleCoord,0);if(realDepth<.001){continue;}let realViewPos=getViewPositionFromDepth(sampleUV,realDepth,systemUniforms.projection.inverseProjectionMatrix);let adaptiveBias=uniforms.bias*(1.0+distToCamera*uniforms.biasDistanceScale);let deltaZ=realViewPos.z-sampleViewPos.z;if(deltaZ>adaptiveBias&&deltaZ(select(originalColor.rgb*vec3(finalAO),vec3(finalAO),uniforms.useBlur==1u),originalColor.a);textureStore(outputTexture,screenCoord,finalColor);}","#redgpu_include math.getInterleavedGradientNoise #redgpu_include math.PI2 #redgpu_include depth.getLinearizeDepth #redgpu_include math.reconstruct.getViewPositionFromDepth #redgpu_include math.reconstruct.getViewNormalFromGNormalBuffer #redgpu_include math.tnb.getTBN struct Uniforms{radius:f32,intensity:f32,bias:f32,biasDistanceScale:f32,fadeDistanceStart:f32,fadeDistanceRange:f32,contrast:f32,useBlur:u32,}fn getTextureSize()->vec2{return vec2(textureDimensions(sourceTexture));}fn getNoiseVec(p:vec2)->vec3{let noise=getInterleavedGradientNoise(p);let angle=noise*PI2;return vec3(cos(angle),sin(angle),.0);}"))}}defineBoolean(SSAO_AO,[{key:"useBlur",value:!0}]),definePositiveNumber(SSAO_AO,[{key:"contrast",value:1.5,min:.5,max:4},{key:"radius",value:.253,min:.01,max:5},{key:"intensity",value:1,min:0,max:10},{key:"bias",value:.02,min:0,max:.1},{key:"biasDistanceScale",value:.02,min:0,max:.5},{key:"fadeDistanceStart",value:30,min:1,max:200},{key:"fadeDistanceRange",value:20,min:1,max:100}]),Object.freeze(SSAO_AO);class SSAOBlend extends ASinglePassPostEffect{constructor(i){super(i),this.init(i,"POST_EFFECT_SSAO_BLEND",createBasicPostEffectCode(this,"let index=global_id.xy;var diffuse:vec4=textureLoad(sourceTexture0,index,0);var blur:vec4=textureLoad(sourceTexture1,index,0);let finalColor=vec4(diffuse.rgb*blur.rgb,diffuse.a);textureStore(outputTexture,index,finalColor);","",[{name:"sourceTexture0"},{name:"sourceTexture1"}]))}}Object.freeze(SSAOBlend);class SSAO extends AMultiPassPostEffect{#mi;#pi;#gi;constructor(i){super(i,[new SSAO_AO(i),new GaussianBlur(i),new SSAOBlend(i)]),this.#mi=this.passList[0],this.#pi=this.passList[1],this.#pi.size=3,this.#gi=this.passList[2]}get useBlur(){return this.#mi.useBlur}set useBlur(i){this.#mi.useBlur=i}get radius(){return this.#mi.radius}set radius(i){this.#mi.radius=i}get intensity(){return this.#mi.intensity}set intensity(i){this.#mi.intensity=i}get bias(){return this.#mi.bias}set bias(i){this.#mi.bias=i}get biasDistanceScale(){return this.#mi.biasDistanceScale}set biasDistanceScale(i){this.#mi.biasDistanceScale=i}get fadeDistanceStart(){return this.#mi.fadeDistanceStart}set fadeDistanceStart(i){this.#mi.fadeDistanceStart=i}get fadeDistanceRange(){return this.#mi.fadeDistanceRange}set fadeDistanceRange(i){this.#mi.fadeDistanceRange=i}get contrast(){return this.#mi.contrast}set contrast(i){this.#mi.contrast=i}render(i,g,x,v){const _=i.postEffectManager.texturePool,y=this.#mi.render(i,g,x,v);if(this.useBlur){const b=this.#pi.render(i,g,x,y);_.release(y.texture);const S=this.#gi.render(i,g,x,v,b);return _.release(b.texture),S}return y}}Object.freeze(SSAO);class SSR extends ASinglePassPostEffect{constructor(i){super(i,{x:8,y:8,z:1}),this.init(i,"POST_EFFECT_SSR",createBasicPostEffectCode(this,"let screenCoord=vec2(global_id.xy);let texDims=textureDimensions(sourceTexture);let texSize=vec2(texDims);if(screenCoord.x>=texSize.x||screenCoord.y>=texSize.y){return;}let originalColor=textureLoad(sourceTexture,screenCoord,0);let depth=textureLoad(depthTexture,screenCoord,0);if(depth>=0.999){textureStore(outputTexture,screenCoord,originalColor);return;}let gBufferNormalData=textureLoad(gBufferNormalTexture,screenCoord,0);let precomputedReflectionStrength=gBufferNormalData.a;if(precomputedReflectionStrength<.05){textureStore(outputTexture,screenCoord,originalColor);return;}let uv=(vec2(screenCoord)+0.5)/vec2(texDims);let worldPos=reconstructWorldPosition(uv,depth);let worldNormal=getWorldNormalFromGNormalBuffer(gBufferNormalData.rgb);if(length(worldNormal)<.01){textureStore(outputTexture,screenCoord,originalColor);return;}let normal=normalize(worldNormal);let cameraWorldPos=systemUniforms.camera.inverseViewMatrix[3].xyz;let reflectionDir=calculateWorldReflectionRay(worldPos,normal,cameraWorldPos);let reflection=performWorldRayMarching(worldPos,reflectionDir,screenCoord);if(reflection.a>.001){let finalReflectionStrength=reflection.a*uniforms.reflectionIntensity*precomputedReflectionStrength;let reflectionColor=reflection.rgb*finalReflectionStrength;let diffuseColor=originalColor.rgb*(1.0-finalReflectionStrength);let finalColor=diffuseColor+reflectionColor;textureStore(outputTexture,screenCoord,vec4(finalColor,originalColor.a));}else{textureStore(outputTexture,screenCoord,originalColor);}","#redgpu_include math.getInterleavedGradientNoise #redgpu_include depth.getLinearizeDepth #redgpu_include math.EPSILON #redgpu_include math.reconstruct.getViewPositionFromDepth #redgpu_include math.reconstruct.getWorldNormalFromGNormalBuffer #redgpu_include math.direction.getViewDirection #redgpu_include math.direction.getReflectionVectorFromViewDirection struct Uniforms{maxSteps:u32,maxDistance:f32,stepSize:f32,reflectionIntensity:f32,fadeDistance:f32,edgeFade:f32,_padding:f32,_padding2:f32,}fn getTextureDimensions()->vec2{return textureDimensions(depthTexture);}fn reconstructWorldPosition(uv:vec2,depth:f32)->vec3{let viewPos=getViewPositionFromDepth(uv,depth,systemUniforms.projection.inverseProjectionMatrix);let worldPos4=systemUniforms.camera.inverseViewMatrix*vec4(viewPos,1.0);return worldPos4.xyz;}fn worldToScreen(worldPos:vec3)->vec2{let clipPos4=systemUniforms.projection.projectionViewMatrix*vec4(worldPos,1.0);if(abs(clipPos4.w)(-1.0);}let ndc=clipPos4.xyz/clipPos4.w;return vec2(ndc.x*0.5+0.5,-ndc.y*0.5+0.5);}fn calculateEdgeFade(screenUV:vec2)->f32{let edge=min(screenUV,1.0-screenUV);let edgeDist=min(edge.x,edge.y);return smoothstep(.0,uniforms.edgeFade,edgeDist);}fn calculateWorldReflectionRay(worldPos:vec3,worldNormal:vec3,cameraWorldPos:vec3)->vec3{let viewDir=getViewDirection(worldPos,cameraWorldPos);return getReflectionVectorFromViewDirection(viewDir,worldNormal);}fn performWorldRayMarching(startWorldPos:vec3,rayDir:vec3,screenCoord:vec2)->vec4{let cameraWorldPos=systemUniforms.camera.inverseViewMatrix[3].xyz;let cameraDistance=length(startWorldPos-cameraWorldPos);let distanceScale=1.0+cameraDistance*0.1;let adaptiveStepSize=uniforms.stepSize*min(distanceScale,4.0);let stepScale=1.0+cameraDistance*.067;let adaptiveMaxSteps=u32(f32(uniforms.maxSteps)*min(stepScale,2.0));let maxDistanceSq=uniforms.maxDistance*uniforms.maxDistance;let texDims=getTextureDimensions();let texSizeF=vec2(texDims);let maxRefinementLevels=4u;let invMaxSteps=1.0/f32(adaptiveMaxSteps);let jitter=getInterleavedGradientNoise(vec2(screenCoord));var currentWorldPos=startWorldPos+rayDir*(adaptiveStepSize*jitter);var currentStepSize=adaptiveStepSize;var refinementLevel=0u;for(var i=0u;imaxDistanceSq){break;}let currentScreenUV=worldToScreen(currentWorldPos);if(any(currentScreenUV(.0))||any(currentScreenUV>vec2(1.0))){break;}let coord=vec2(currentScreenUV*texSizeF);let sampledDepth=textureLoad(depthTexture,coord,0);if(sampledDepth>=0.999){continue;}let sampledWorldPos=reconstructWorldPosition(currentScreenUV,sampledDepth);let rayDistanceFromCamera=length(currentWorldPos-cameraWorldPos);let surfaceDistanceFromCamera=length(sampledWorldPos-cameraWorldPos);let distanceDiff=rayDistanceFromCamera-surfaceDistanceFromCamera;let intersectionThreshold=currentStepSize*(4.0+cameraDistance*.033);if(distanceDiff>.0&&distanceDiff(reflectionColor.rgb,totalFade);}}return vec4(.0);}"))}}definePositiveNumber(SSR,[{key:"maxSteps",value:64,min:1,max:512},{key:"maxDistance",value:15,min:1,max:200},{key:"stepSize",value:.02,min:.001,max:5},{key:"reflectionIntensity",value:1,min:0,max:10},{key:"fadeDistance",value:12,min:1,max:100},{key:"edgeFade",value:.15,min:0,max:.5}]),Object.freeze(SSR);class TAASharpen extends ASinglePassPostEffect{constructor(i){super(i),this.isLdr=!0,this.init(i,"POST_EFFECT_TAA_SHARPEN",createBasicPostEffectCode(this,"let index=global_id.xy;let dimensions=textureDimensions(sourceTexture);if(index.x>=dimensions.x||index.y>=dimensions.y){return;}let centerRGBA=textureLoad(sourceTexture,index,0);let leftRGBA=textureLoad(sourceTexture,index-vec2(select(0u,1u,index.x>0u),0u),0);let rightRGBA=textureLoad(sourceTexture,min(index+vec2(1u,0u),dimensions-1u),0);let upRGBA=textureLoad(sourceTexture,index-vec2(0u,select(0u,1u,index.y>0u)),0);let downRGBA=textureLoad(sourceTexture,min(index+vec2(0u,1u),dimensions-1u),0);let lCenter=getLuminance(centerRGBA.rgb);let lLeft=getLuminance(leftRGBA.rgb);let lRight=getLuminance(rightRGBA.rgb);let lUp=getLuminance(upRGBA.rgb);let lDown=getLuminance(downRGBA.rgb);let minL=min(lCenter,min(min(lLeft,lRight),min(lUp,lDown)));let maxL=max(lCenter,max(max(lLeft,lRight),max(lUp,lDown)));let contrast=maxL-minL;var finalRGBA:vec4;let k=uniforms.sharpness*0.2;if(contrast>.001){let edgeRGB=4.0*centerRGBA.rgb-(leftRGBA.rgb+rightRGBA.rgb+upRGBA.rgb+downRGBA.rgb);let sharpRGB=centerRGBA.rgb+edgeRGB*k;let edgeAlpha=4.0*centerRGBA.a-(leftRGBA.a+rightRGBA.a+upRGBA.a+downRGBA.a);let sharpAlpha=centerRGBA.a+edgeAlpha*k;finalRGBA=vec4(sharpRGB,sharpAlpha);}else{finalRGBA=centerRGBA;}textureStore(outputTexture,index,saturate(finalRGBA));","#redgpu_include color.getLuminance struct Uniforms{sharpness:f32};"))}}definePositiveNumber(TAASharpen,[{key:"sharpness",value:.5,min:0,max:1}]),Object.freeze(TAASharpen);class ACamera extends BaseObject{static CALIBRATION_CONSTANT=12.5;#xi=16;#vi=1/3200;#_i=100;#yi=0;#bi=!0;#Si=!0;get useAutoExposure(){return this.#bi}set useAutoExposure(i){if(this.#bi!==i){if(this.#bi&&!i){this.#_i=100;let i=this.#xi*this.#xi/Math.pow(2,this.#yi);const g=[1,1/1.3,.625,.5,.4,1/3.2,1/4,.2,1/6,1/8,.1,1/13,1/15,.05,.04,1/30,1/40,.02,1/60,1/80,.01,.008,1/160,.005,.004,1/320,1/400,.002,1/640,1/800,.001,8e-4,1/1600,5e-4,4e-4,1/3200,1/4e3,2e-4,1/6400,1/8e3];this.#vi=g.reduce((g,x)=>Math.abs(x-i){v.forEach(({key:v,value:_})=>{const y=i[v];if(!y)return;const b=y.View===Float32Array?g:x;y.View&&b.set("number"==typeof _?[_]:_,y.uniformOffset/y.View.BYTES_PER_ELEMENT)})};let Ti=create$4();class SystemUniformUpdater{static updateCamera(i,g,x,v){const{viewMatrix:_,position:y}=i,b=i instanceof Camera2D;updateSystemUniformData(g,x,v,[{key:"viewMatrix",value:_},{key:"inverseViewMatrix",value:invert$1(Ti,_)},{key:"cameraPosition",value:y},{key:"nearClipping",value:b?0:i.nearClipping},{key:"farClipping",value:b?0:i.farClipping},{key:"fieldOfView",value:i.fieldOfView*Math.PI/180},{key:"ev100",value:i.ev100},{key:"aperture",value:i.aperture},{key:"shutterSpeed",value:i.shutterSpeed},{key:"iso",value:i.iso}])}static updateShadow(i,g,x,v){updateSystemUniformData(g,x,v,[{key:"directionalShadowDepthTextureSize",value:i.directionalShadowManager.shadowDepthTextureSize},{key:"directionalShadowBias",value:i.directionalShadowManager.bias}])}static updateSkyAtmosphere(i,g,x,v){const _=i?.params,y=g.skyAtmosphere.members;updateSystemUniformData(g,x,v,[{key:"useSkyAtmosphere",value:i?1:0}]),updateSystemUniformData(y,x,v,[{key:"rayleighScattering",value:_?.rayleighScattering||[0,0,0]},{key:"rayleighExponentialDistribution",value:_?.rayleighExponentialDistribution||0},{key:"mieScattering",value:_?.mieScattering||[0,0,0]},{key:"mieAnisotropy",value:_?.mieAnisotropy||0},{key:"mieAbsorption",value:_?.mieAbsorption||[0,0,0]},{key:"mieExponentialDistribution",value:_?.mieExponentialDistribution||0},{key:"absorptionCoefficient",value:_?.absorptionCoefficient||[0,0,0]},{key:"absorptionTipAltitude",value:_?.absorptionTipAltitude||0},{key:"groundAlbedo",value:_?.groundAlbedo||[0,0,0]},{key:"absorptionTentWidth",value:_?.absorptionTentWidth||0},{key:"skyLuminanceFactor",value:_?.skyLuminanceFactor||[1,1,1]},{key:"multiScatteringFactor",value:_?.multiScatteringFactor||0},{key:"sunDirection",value:_?.sunDirection||[0,0,0]},{key:"transmittanceMinLightElevationAngle",value:_?.transmittanceMinLightElevationAngle||0},{key:"groundRadius",value:_?.groundRadius||0},{key:"atmosphereHeight",value:_?.atmosphereHeight||0},{key:"aerialPerspectiveDistanceScale",value:_?.aerialPerspectiveDistanceScale||100},{key:"aerialPerspectiveStartDepth",value:_?.aerialPerspectiveStartDepth||0},{key:"sunIntensity",value:_?.sunIntensity||0},{key:"sunSize",value:_?.sunSize||0},{key:"sunLimbDarkening",value:_?.sunLimbDarkening||0},{key:"cameraHeight",value:_?.cameraHeight||0},{key:"cloudTime",value:_?.cloudTime||0},{key:"cloudTimeMultiplier",value:_?.cloudTimeMultiplier||0},{key:"cloudCoverage",value:_?.cloudCoverage||0},{key:"cloudDensity",value:_?.cloudDensity||0},{key:"cloudHeight",value:_?.cloudHeight||0}])}static updateTime(i,g,x,v){updateSystemUniformData(g,x,v,[{key:"time",value:i.time},{key:"deltaTime",value:i.deltaTime},{key:"frameIndex",value:i.frameIndex},{key:"sinTime",value:i.sinTime}])}static updateProjection(i,g,x,v){updateSystemUniformData(g,x,v,[{key:"projectionMatrix",value:i.projectionMatrix},{key:"projectionViewMatrix",value:i.projectionViewMatrix},{key:"noneJitterProjectionMatrix",value:i.noneJitterProjectionMatrix},{key:"noneJitterProjectionViewMatrix",value:i.noneJitterProjectionViewMatrix},{key:"inverseProjectionMatrix",value:i.inverseProjectionMatrix},{key:"inverseProjectionViewMatrix",value:i.inverseProjectionViewMatrix||create$4()},{key:"prevNoneJitterProjectionViewMatrix",value:i.prevNoneJitterProjectionViewMatrix}])}static updateDirectionalLights(i,g,x,v){i.forEach((i,_)=>{const y=g[_];updateSystemUniformData(y,x,v,[{key:"direction",value:i.direction},{key:"color",value:i.color.rgbNormalLinear},{key:"intensity",value:i.intensityMultiplier*i.lux}])})}static updateAmbientLight(i,g,x,v){updateSystemUniformData(g,x,v,[{key:"color",value:i?i.color.rgbNormalLinear:[0,0,0]},{key:"intensity",value:i?i.intensityMultiplier*i.lux:0}])}}Object.freeze(SystemUniformUpdater);class ResourceStateStorageBuffer{static dirtyList=[];buffer;uuid;#jt=0;constructor(i){this.buffer=i,this.uuid=i.uuid}get useNum(){return this.#jt}set useNum(i){this.#jt=i,ResourceStateStorageBuffer.dirtyList.push(this)}}class StorageBuffer extends AUniformBaseBuffer{constructor(i,g,x="",v=""){super(i,"managedStorageBufferState",GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC,g,x);const{table:_}=this.targetResourceManagedState,y=_.get(v);if(y)return y.buffer;v&&(this.name=v,this[kr]=v),this.redGPUContext.resourceManager.registerManagementResource(this,new ResourceStateStorageBuffer(this))}}Object.freeze(StorageBuffer);var wi,Mi="#redgpu_include color.getLuminance @group(0)@binding(0)var sourceTexture:texture_2d;@group(0)@binding(1)var depthTexture:texture_depth_2d;@group(1)@binding(0)varhistogram:array,256>;struct AutoExposureUniforms{deltaTime:f32,targetLuminance:f32,adjustmentSpeedUp:f32,adjustmentSpeedDown:f32,exposureCompensation:f32,minEV100:f32,maxEV100:f32,calibrationConstant:f32,ev100Range:f32,lowPercentile:f32,highPercentile:f32,invEv100Range:f32,width:f32,height:f32,currentPreExposure:f32,maxExposureMultiplier:f32,meteringMode:f32};@group(1)@binding(1)varuniforms:AutoExposureUniforms;varlocalHistogram:array,256>;@compute @workgroup_size(16,16,1)fn main(@builtin(global_invocation_id)global_id:vec3,@builtin(local_invocation_index)local_index:u32){if(local_index<256u){atomicStore(&localHistogram[local_index],0u);}workgroupBarrier();if(f32(global_id.x)(i32(global_id.x),i32(global_id.y)),0).rgb;let brightness=max(color.r,max(color.g,color.b));let lum=brightness/max(uniforms.currentPreExposure,.0001);let texel=textureLoad(sourceTexture,vec2(i32(global_id.x),i32(global_id.y)),0);let depth=textureLoad(depthTexture,vec2(i32(global_id.x),i32(global_id.y)),0);if(lum>.0001&&texel.a>.0&&depth<1.0){let ev100=log2(lum*100.0/uniforms.calibrationConstant);let normalizedEV100=clamp((ev100-uniforms.minEV100)*uniforms.invEv100Range,.0,1.0);let binIndex=u32(normalizedEV100*255.0);var weight=1.0;let uv=vec2(f32(global_id.x)/uniforms.width,f32(global_id.y)/uniforms.height);let dist=distance(uv,vec2(0.5,0.5));if(uniforms.meteringMode==1.0){weight=clamp(1.0-dist*1.0,.0,1.0);weight=weight*weight;}else if(uniforms.meteringMode==2.0){weight=clamp(1.0-dist*4.0,.0,1.0);weight=weight*weight*weight*weight;}atomicAdd(&localHistogram[binIndex],u32(weight*100.0));}}}workgroupBarrier();if(local_index<256u){let localCount=atomicLoad(&localHistogram[local_index]);if(localCount>0u){atomicAdd(&histogram[local_index],localCount);}}}";!function(i){i[i.AVERAGE=0]="AVERAGE",i[i.CENTER_WEIGHTED=1]="CENTER_WEIGHTED",i[i.SPOT=2]="SPOT"}(wi||(wi={})),Object.freeze(wi);var Pi=wi;const Ri={COLOR:"gBufferColor",NORMAL:"gBufferNormal",MOTION_VECTOR:"gBufferMotionVector",RENDER_PATH1_RESULT:"renderPath1ResultTexture"};Object.freeze(Ri);class AutoExposure extends RedGPUObject{#Ri;#Ci;#Bi;#Di;#Ei=new Map;#Ii=new Map;#Ai;#Li;#se;#Ui=1;#ki;#Gi=!1;#Oi=0;#Vi=15;#Ni=3;#Fi=1;#Hi=.8;#zi=.983;#$i=16;#ji=Pi.AVERAGE;#Ki=.18;#Xi=0;#ii;#qi;#Yi;#Wi=new WeakMap;#Zi;#Ji;constructor(i){super(i.redGPUContext),this.#Ri=i,this.#Qi(),this.#en()}get exposureCompensation(){return this.#Xi}set exposureCompensation(i){this.#Xi=i}get targetLuminance(){return this.#Ki}set targetLuminance(i){this.#Ki=i}get minEV100(){return this.#Oi}set minEV100(i){this.#Oi=i}get maxEV100(){return this.#Vi}set maxEV100(i){this.#Vi=i}get adaptationSpeedUp(){return this.#Ni}set adaptationSpeedUp(i){this.#Ni=i}get adaptationSpeedDown(){return this.#Fi}set adaptationSpeedDown(i){this.#Fi=i}get lowPercentile(){return this.#Hi}set lowPercentile(i){this.#Hi=i}get highPercentile(){return this.#zi}set highPercentile(i){this.#zi=i}get maxExposureMultiplier(){return this.#$i}set maxExposureMultiplier(i){this.#$i=i}get meteringMode(){return this.#ji}set meteringMode(i){this.#ji=i}get preExposure(){const{rawCamera:i}=this.#Ri;return this.#tn(i.ev100,this.#Xi)}get currentAdaptedEV100(){return this.#Ui}set currentAdaptedEV100(i){this.#Ui=i;const g=new Float32Array([i]);this.gpuDevice.queue.writeBuffer(this.#Ci.gpuBuffer,0,g.buffer)}get adaptedLuminanceBuffer(){return this.#Ci}render(i){const{gpuDevice:g,antialiasingManager:x,commandEncoderManager:v}=this,{useMSAA:_,msaaID:y}=x,{width:b,height:S}=this.#Ri.viewRenderTextureManager.getGBufferTexture(Ri.COLOR),{rawCamera:w,renderViewStateData:L,viewRenderTextureManager:H}=this.#Ri,{deltaTime:z,swapBufferIndex:q}=L,W=this.#Vi-this.#Oi,be=this.#tn(w.ev100,this.#Xi);g.queue.writeBuffer(this.#se.gpuBuffer,0,new Float32Array([z,this.#Ki,this.#Ni,this.#Fi,this.#Xi,this.#Oi,this.#Vi,ACamera.CALIBRATION_CONSTANT,W,this.#Hi,this.#zi,1/W,b,S,be,this.#$i,this.#ji]));const je=this.#ii!==y,Ke=this.#qi!==b||this.#Yi!==S;(je||Ke)&&(this.#Wi=new WeakMap,this.#ii=y,this.#qi=b,this.#Yi=S);let Xe=this.#Wi.get(i.texture);if(!Xe){const x=H.depthTextureView,v=H.prevDepthTextureView,y=this.#rn(_);Xe={swap0:g.createBindGroup({label:"AutoExposure_Downsample_BG0_Swap0",layout:y,entries:[{binding:0,resource:i.textureView},{binding:1,resource:x}]}),swap1:g.createBindGroup({label:"AutoExposure_Downsample_BG0_Swap1",layout:y,entries:[{binding:0,resource:i.textureView},{binding:1,resource:v}]})},this.#Wi.set(i.texture,Xe)}v.useEncoder(k.POST_PROCESS,i=>{i.clearBuffer(this.#Bi.gpuBuffer)});const Ye=this.#in(_);v.addPostProcessComputePass("AutoExposure_GenerateHistogram_Pass",i=>{i.setPipeline(Ye),i.setBindGroup(0,q?Xe.swap1:Xe.swap0),i.setBindGroup(1,this.#Zi),i.dispatchWorkgroups(Math.ceil(b/16),Math.ceil(S/16),1)}),v.addPostProcessComputePass("AutoExposure_Adaptation_Pass",i=>{i.setPipeline(this.#Di),i.setBindGroup(0,this.#Ji),i.dispatchWorkgroups(1,1,1)}),this.#Gi||v.useEncoder(k.POST_PROCESS,i=>{copyGPUBuffer(i,this.#Ci.gpuBuffer,this.#ki)})}resolveReadback(){this.#Gi||(this.#Gi=!0,this.#ki.mapAsync(GPUMapMode.READ).then(()=>{const i=new Float32Array(this.#ki.getMappedRange());this.#Ui=i[0],this.#ki.unmap(),this.#Gi=!1}).catch(()=>{this.#Gi=!1}))}#tn(i,g){return Math.pow(2,g)/(1.2*Math.pow(2,i))}#Qi(){const{gpuDevice:i,redGPUContext:g}=this;this.#Ri.rawCamera.updateExposure();const x=Math.max(this.#Oi,Math.min(this.#Vi,this.#Ri.rawCamera.ev100));this.#Ui=x;const v=new Float32Array([x]);this.#Ci=new StorageBuffer(g,v.buffer,"AutoExposure_AdaptedEV100"),this.#Bi=new StorageBuffer(g,new Uint32Array(256).buffer,"AutoExposure_HistogramBuffer"),this.#ki=i.createBuffer({size:4,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,label:"AutoExposure_ReadBuffer"});const _=new Float32Array(18);this.#se=new UniformBuffer(g,_.buffer,"AutoExposure_UniformBuffer")}#en(){const{gpuDevice:i,resourceManager:g}=this,x=g.createGPUShaderModule("AutoExposure_Adaptation",{code:"struct AutoExposureUniforms{deltaTime:f32,targetLuminance:f32,adjustmentSpeedUp:f32,adjustmentSpeedDown:f32,exposureCompensation:f32,minEV100:f32,maxEV100:f32,calibrationConstant:f32,ev100Range:f32,lowPercentile:f32,highPercentile:f32,invEv100Range:f32,width:f32,height:f32,currentPreExposure:f32,maxExposureMultiplier:f32,meteringMode:f32};@group(0)@binding(0)varhistogram:array,256>;@group(0)@binding(1)varadaptedEV100:f32;@group(0)@binding(2)varuniforms:AutoExposureUniforms;@compute @workgroup_size(1,1,1)fn main(){var countBuffer:array;var totalPixels:u32=0u;for(var i=0u;i<256u;i=i+1u){let val=atomicExchange(&histogram[i],0u);countBuffer[i]=val;totalPixels+=val;}if(totalPixels==0u){return;}let minPixel=u32(f32(totalPixels)*uniforms.lowPercentile);let maxPixel=u32(f32(totalPixels)*uniforms.highPercentile);var pixelCounter:u32=0u;var weightedEV100Sum:f32=.0;var totalValidPixels:f32=.0;for(var i=0u;i<256u;i=i+1u){let nextCounter=pixelCounter+countBuffer[i];let validPixels=max(.0,f32(min(nextCounter,maxPixel))-f32(max(pixelCounter,minPixel)));if(validPixels>.0){let ev100=uniforms.minEV100+(f32(i)/255.0)*uniforms.ev100Range;weightedEV100Sum+=ev100*validPixels;totalValidPixels+=validPixels;}pixelCounter=nextCounter;}let avgEV100=weightedEV100Sum/max(totalValidPixels,1.0);var targetEV100=avgEV100-log2((120.0*uniforms.targetLuminance)/uniforms.calibrationConstant)-uniforms.exposureCompensation;let minPossibleEV100=uniforms.exposureCompensation-log2(1.2*uniforms.maxExposureMultiplier);targetEV100=max(targetEV100,minPossibleEV100);let prevEV100=adaptedEV100;let diff=targetEV100-prevEV100;let speed=select(uniforms.adjustmentSpeedDown,uniforms.adjustmentSpeedUp,diff>.0);let adaptationFactor=1.0-exp(-speed*uniforms.deltaTime);var nextEV100=prevEV100+diff*adaptationFactor;adaptedEV100=clamp(nextEV100,uniforms.minEV100,uniforms.maxEV100);}"});this.#Ai=g.createBindGroupLayout("AutoExposure_Downsample_BGL1",{entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}},{binding:1,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}}]}),this.#Li=g.createBindGroupLayout("AutoExposure_Adaptation_BGL0",{entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}},{binding:1,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}},{binding:2,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}}]}),this.#Di=i.createComputePipeline({label:"AutoExposure_Adaptation_Pipeline",layout:i.createPipelineLayout({bindGroupLayouts:[this.#Li]}),compute:{module:x,entryPoint:"main"}}),this.#Zi=i.createBindGroup({label:"AutoExposure_Downsample_BG1",layout:this.#Ai,entries:[{binding:0,resource:{buffer:this.#Bi.gpuBuffer}},{binding:1,resource:{buffer:this.#se.gpuBuffer}}]}),this.#Ji=i.createBindGroup({label:"AutoExposure_Adaptation_BG0",layout:this.#Li,entries:[{binding:0,resource:{buffer:this.#Bi.gpuBuffer}},{binding:1,resource:{buffer:this.#Ci.gpuBuffer}},{binding:2,resource:{buffer:this.#se.gpuBuffer}}]})}#in(i){if(this.#Ii.has(i))return this.#Ii.get(i);const{gpuDevice:g,resourceManager:x}=this,v=i?Mi.replace("texture_depth_2d","texture_depth_multisampled_2d"):Mi,_=x.createGPUShaderModule("AutoExposure_Downsample_"+(i?"MSAA":"NonMSAA"),{code:v}),y=this.#rn(i),b=g.createComputePipeline({label:"AutoExposure_Downsample_Pipeline_"+(i?"MSAA":"NonMSAA"),layout:g.createPipelineLayout({bindGroupLayouts:[y,this.#Ai]}),compute:{module:_,entryPoint:"main"}});return this.#Ii.set(i,b),b}#rn(i){if(this.#Ei.has(i))return this.#Ei.get(i);const{gpuDevice:g}=this,x=g.createBindGroupLayout({label:"AutoExposure_Downsample_BGL0_"+(i?"MSAA":"NonMSAA"),entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,texture:{}},{binding:1,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:"depth",multisampled:i}}]});return this.#Ei.set(i,x),x}}Object.freeze(AutoExposure);class PostEffectTexturePool extends RedGPUObject{#nn=new Map;#an=new Set;#sn=new WeakMap;#on=new WeakMap;#H=0;#un=0;#ln=0;#cn=0;constructor(i){super(i)}get videoMemorySize(){return this.#H}get totalCount(){return this.activeCount+this.idleCount}get activeCount(){return this.#an.size}get idleCount(){let i=0;return this.#nn.forEach(g=>i+=g.length),i}get peakActiveCount(){return this.#un}get allocationCount(){return this.#ln}get hitRate(){return 0===this.#cn?0:(this.#cn-this.#ln)/this.#cn}getDetails(){const i=[];return this.#nn.forEach((g,x)=>{const v=[...this.#an].filter(i=>this.#sn.get(i)===x).length;i.push({key:x,total:g.length+v,active:v,idle:g.length})}),i}allocResult(i,g,x="rgba16float"){const v=this.#hn(i,g,x);return{texture:v,textureView:this.#on.get(v)}}release(i){if(this.#an.has(i)){this.#an.delete(i);const g=this.#sn.get(i);g&&this.#nn.get(g).push(i)}}releaseAll(){this.#an.forEach(i=>{const g=this.#sn.get(i);g&&this.#nn.get(g).push(i)}),this.#an.clear()}clear(){this.releaseAll(),this.#nn.forEach(i=>{i.forEach(i=>i.destroy())}),this.#nn.clear(),this.#H=0,this.#un=0,this.#ln=0,this.#cn=0}#hn(i,g,x="rgba16float"){const{resourceManager:v}=this;this.#cn++;const _=`${i}x${g}_${x}`;let y,b=this.#nn.get(_);return b||(b=[],this.#nn.set(_,b)),b.length>0?y=b.shift():(this.#ln++,y=v.createManagedTexture({size:{width:i,height:g},format:x,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.COPY_SRC|GPUTextureUsage.COPY_DST,label:`PostEffectTexturePool_${_}`}),this.#H+=calculateTextureByteSize(y),this.#sn.set(y,_),this.#on.set(y,v.getGPUResourceBitmapTextureView(y))),this.#an.add(y),this.#an.size>this.#un&&(this.#un=this.#an.size),y}}Object.freeze(PostEffectTexturePool);class PostEffectManager{#Ri;#fn=[];#dn;#mn;#pn;#gn;#H=0;#xn;#vn;#_n;#yn;#bn;#Sn=!1;#Tn;#wn=!1;#Mn;#Pn;#Rn;#Cn;#Bn;#Dn;constructor(i){this.#Ri=i,this.#dn=new PostEffectTexturePool(this.#Ri.redGPUContext),this.#N(),this.#En()}get gbufferBindGroupLayout(){return this.#Ri.redGPUContext.antialiasingManager.useMSAA?this.#Pn:this.#Rn}get gbufferBindGroup(){return this.#Ri.renderViewStateData.swapBufferIndex?this.#Bn:this.#Cn}get texturePool(){return this.#dn}get autoExposure(){return this.#Mn||(this.#Mn=new AutoExposure(this.#Ri)),this.#Mn}get useSSAO(){return this.#Sn}set useSSAO(i){this.#Sn=i,this.#In()}get ssao(){return this.#bn||(this.#bn=new SSAO(this.#Ri.redGPUContext)),this.#bn}get useSSR(){return this.#wn}set useSSR(i){this.#wn=i,this.#An()}get ssr(){return this.#Tn||(this.#Tn=new SSR(this.#Ri.redGPUContext)),this.#Tn}get postEffectSystemUniformBuffer(){return this.#pn}get view(){return this.#Ri}get effectList(){return this.#fn}get videoMemorySize(){return this.#ci(),this.#H}addEffect(i){this.#fn.push(i)}getEffectAt(i){return this.#fn[i]}removeEffect(i){const g=this.#fn.indexOf(i);g>-1&&(i.clear(),this.#fn.splice(g,1))}removeEffectAt(i){this.#fn[i]&&(this.#fn[i].clear(),this.#fn.splice(i,1))}removeAllEffect(){this.#fn.forEach(i=>{i.clear()}),this.#fn.length=0}render(){const{viewRenderTextureManager:i,redGPUContext:g,taa:x,fxaa:v}=this.#Ri,{antialiasingManager:_}=g,{useMSAA:y,useFXAA:b,useTAA:S,msaaID:w}=_,L=i.getGBufferTexture(Ri.COLOR),{width:k,height:H}=L;this.#Dn!==w&&this.#dn.clear(),y?i.getGBufferResolveTexture(Ri.COLOR):i.getGBufferTexture(Ri.COLOR),this.#Ln(),this.#Un();const{useAutoExposure:z}=this.#Ri.rawCamera;let q=this.#kn(this.#Ri);this.#Ri.skyAtmosphere&&(q=this.#Gn(q,()=>this.#Ri.skyAtmosphere.render(this.#Ri,k,H,q))),this.#Sn&&(q=this.#Gn(q,()=>this.ssao.render(this.#Ri,k,H,q))),this.#wn&&(q=this.#Gn(q,()=>this.ssr.render(this.#Ri,k,H,q))),z&&this.autoExposure.render(q);let W=!1;return this.#fn.forEach(i=>{i.isLdr&&!W&&(q=this.#Gn(q,()=>this.#Ri.toneMappingManager.render(this.#Ri,k,H,q)),W=!0),q=this.#Gn(q,()=>i.render(this.#Ri,k,H,q))}),W||(q=this.#Gn(q,()=>this.#Ri.toneMappingManager.render(this.#Ri,k,H,q))),b&&(q=this.#Gn(q,()=>v.render(this.#Ri,k,H,q))),S&&("View3D"===this.#Ri.constructor.name?(q=this.#Gn(q,()=>x.render(this.#Ri,k,H,q)),this.#yn||(this.#yn=new TAASharpen(g)),q=this.#Gn(q,()=>this.#yn.render(this.#Ri,k,H,q))):q=this.#Gn(q,()=>v.render(this.#Ri,k,H,q))),this.#dn.releaseAll(),q}clear(){this.#fn.forEach(i=>{i.clear()}),this.#dn&&this.#dn.clear()}#Gn(i,g){const x=g();return i&&i.texture&&this.#dn.release(i.texture),x}#En(){const{gpuDevice:i}=this.#Ri.redGPUContext,getEntries=i=>[{binding:0,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:"depth",multisampled:i}},{binding:1,visibility:GPUShaderStage.COMPUTE,texture:{}},{binding:2,visibility:GPUShaderStage.COMPUTE,texture:{}},{binding:3,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:"depth",multisampled:i}},{binding:4,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}},{binding:5,visibility:GPUShaderStage.COMPUTE,sampler:{}}];this.#Pn=i.createBindGroupLayout({label:"PostEffect_Shared_GBuffer_BGL_MSAA",entries:getEntries(!0)}),this.#Rn=i.createBindGroupLayout({label:"PostEffect_Shared_GBuffer_BGL_NonMSAA",entries:getEntries(!1)})}#Un(){const{viewRenderTextureManager:i,redGPUContext:g}=this.#Ri,{gpuDevice:x,antialiasingManager:v,resourceManager:_}=g,{useMSAA:y,msaaID:b}=v,S=i.getGBufferTexture(Ri.COLOR),{width:w,height:L}=S,k=this.#Dn!==b,H=this.#mn?.width!==w||this.#mn?.height!==L;if(k||H){const g=i.depthTextureView,v=i.prevDepthTextureView,S=y?i.getGBufferResolveTextureView(Ri.NORMAL):i.getGBufferTextureView(Ri.NORMAL),w=y?i.getGBufferResolveTextureView(Ri.MOTION_VECTOR):i.getGBufferTextureView(Ri.MOTION_VECTOR),L=_.basicSampler.gpuSampler,k={buffer:this.#pn.gpuBuffer,offset:0,size:this.#pn.size},getEntries=(i,g)=>[{binding:0,resource:i},{binding:1,resource:S},{binding:2,resource:w},{binding:3,resource:g},{binding:4,resource:k},{binding:5,resource:L}],H=y?this.#Pn:this.#Rn;this.#Cn=x.createBindGroup({label:"PostEffect_Shared_GBuffer_BG_Swap0",layout:H,entries:getEntries(g,v)}),this.#Bn=x.createBindGroup({label:"PostEffect_Shared_GBuffer_BG_Swap1",layout:H,entries:getEntries(v,g)}),this.#Dn=b}}#In(){!this.#bn&&this.#Sn&&(this.#bn=new SSAO(this.#Ri.redGPUContext))}#An(){!this.#Tn&&this.#wn&&(this.#Tn=new SSR(this.#Ri.redGPUContext))}#Ln(){const{inverseProjectionMatrix:i,projectionMatrix:g,noneJitterProjectionMatrix:x,rawCamera:v,redGPUContext:_,taa:y,renderViewStateData:b,skyAtmosphere:S}=this.#Ri,{gpuDevice:w,antialiasingManager:L}=_,{viewMatrix:k}=v,{gpuBuffer:H}=this.#pn,{members:z}=this.#gn,{camera:q,time:W,projection:be}=z;v.updateExposure(this.#Ri);const je=multiply$4(Ci,g,k),Ke=multiply$4(Bi,x,k);SystemUniformUpdater.updateCamera(v,q.members,this.#vn,this.#_n),SystemUniformUpdater.updateTime(b,W.members,this.#vn,this.#_n),SystemUniformUpdater.updateProjection({projectionMatrix:g,projectionViewMatrix:je,noneJitterProjectionMatrix:x,noneJitterProjectionViewMatrix:Ke,inverseProjectionMatrix:i,inverseProjectionViewMatrix:invert$1(Di,je),prevNoneJitterProjectionViewMatrix:L.useTAA?y.prevNoneJitterProjectionViewMatrix:Ke},be.members,this.#vn,this.#_n),SystemUniformUpdater.updateSkyAtmosphere(S,z,this.#vn,this.#_n),updateSystemUniformData(z,this.#vn,this.#_n,[{key:"preExposure",value:this.autoExposure.preExposure},{key:"devicePixelRatio",value:devicePixelRatio}]),w.queue.writeBuffer(H,0,this.#xn)}#N(){const{redGPUContext:i}=this.#Ri,g=parseWGSL("POST_EFFECT_SYSTEM_UNIFORM",ft.POST_EFFECT_SYSTEM_UNIFORM).uniforms.systemUniforms,x=new ArrayBuffer(g.arrayBufferByteLength);this.#gn=g,this.#pn=new UniformBuffer(i,x,`${this.#Ri.name}_POST_EFFECT_SYSTEM_UNIFORM_BUFFER`),this.#xn=new ArrayBuffer(this.#gn.endOffset),this.#vn=new Float32Array(this.#xn),this.#_n=new Uint32Array(this.#xn)}#ci(){this.#H=0,this.#dn&&(this.#H+=this.#dn.videoMemorySize),this.#fn.forEach(i=>{this.#H+=i.videoMemorySize})}#kn(i){const{redGPUContext:g,viewRenderTextureManager:x}=i,v=x.getGBufferTexture(Ri.COLOR),{antialiasingManager:_}=g,{width:y,height:b}=v;(y!==this.#mn?.width||b!==this.#mn?.height)&&(this.#dn.clear(),this.#mn={width:y,height:b});return{texture:_.useMSAA?x.getGBufferResolveTexture(Ri.COLOR):x.getGBufferTexture(Ri.COLOR),textureView:_.useMSAA?x.getGBufferResolveTextureView(Ri.COLOR):x.getGBufferTextureView(Ri.COLOR)}}}let Ci=create$4(),Bi=create$4(),Di=create$4();Object.freeze(PostEffectManager);class GeometryGPURenderInfo{buffers;constructor(i){this.buffers=i}}Object.freeze(GeometryGPURenderInfo);class AABB{minX;maxX;minY;maxY;minZ;maxZ;centerX;centerY;centerZ;xSize;ySize;zSize;geometryRadius;constructor(i,g,x,v,_,y){this.minX=i,this.maxX=g,this.minY=x,this.maxY=v,this.minZ=_,this.maxZ=y,this.centerX=(g+i)/2,this.centerY=(v+x)/2,this.centerZ=(y+_)/2,this.xSize=g-i,this.ySize=v-x,this.zSize=y-_,this.geometryRadius=Math.sqrt((this.xSize/2)**2+(this.ySize/2)**2+(this.zSize/2)**2)}intersects(i){return i instanceof AABB||consoleAndThrowError("allow only AABB instance"),this.minX<=i.maxX&&this.maxX>=i.minX&&this.minY<=i.maxY&&this.maxY>=i.minY&&this.minZ<=i.maxZ&&this.maxZ>=i.minZ}contains(i,g,x){if(Array.isArray(i)){const[g,x,v]=i;return g>=this.minX&&g<=this.maxX&&x>=this.minY&&x<=this.maxY&&v>=this.minZ&&v<=this.maxZ}return i>=this.minX&&i<=this.maxX&&g>=this.minY&&g<=this.maxY&&x>=this.minZ&&x<=this.maxZ}clone(){return new AABB(this.minX,this.maxX,this.minY,this.maxY,this.minZ,this.maxZ)}}Object.freeze(AABB);const calculateGeometryAABB=i=>{if(!i||!i.data||0===i.vertexCount)return new AABB(0,0,0,0,0,0);const g=i.stride,x=i.data,v=i.vertexCount;let _=1/0,y=1/0,b=1/0,S=-1/0,w=-1/0,L=-1/0,k=0;for(;k<=v-4;k+=4){let i=k*g;const v=x[i],H=x[i+1],z=x[i+2];i=(k+1)*g;const q=x[i],W=x[i+1],be=x[i+2];i=(k+2)*g;const je=x[i],Ke=x[i+1],Xe=x[i+2];i=(k+3)*g;const Ye=x[i],Ze=x[i+1],Je=x[i+2];v<_&&(_=v),q<_&&(_=q),je<_&&(_=je),Ye<_&&(_=Ye),v>S&&(S=v),q>S&&(S=q),je>S&&(S=je),Ye>S&&(S=Ye),Hw&&(w=H),W>w&&(w=W),Ke>w&&(w=Ke),Ze>w&&(w=Ze),zL&&(L=z),be>L&&(L=be),Xe>L&&(L=Xe),Je>L&&(L=Je)}for(;kS&&(S=v),H>w&&(w=H),z>L&&(L=z)}return new AABB(_,S,y,w,b,L)};class Geometry extends ResourceBase{gpuRenderInfo;#On;#Vn;#Nn;constructor(i,g,x){super(i),this.#Fn(g),this.#Hn(x);const{interleavedStruct:v}=this.#On;this.gpuRenderInfo=new GeometryGPURenderInfo([{arrayStride:v.arrayStride,attributes:v.attributes}])}get vertexBuffer(){return this.#On}get indexBuffer(){return this.#Vn}get volume(){return this.#Nn||(this.#Nn=calculateGeometryAABB(this.#On)),this.#Nn}#Fn(i){const g=this.#On;this.#On=i,g&&g.__removeDirtyPipelineListener(this.#zn),i&&i.__addDirtyPipelineListener(this.#zn),this.#Nn=null}#Hn(i){const g=this.#Vn;this.#Vn=i,g&&g.__removeDirtyPipelineListener(this.#$n),i&&i.__addDirtyPipelineListener(this.#$n)}#zn(){this.notifyUpdate()}#$n(){this.notifyUpdate()}}Object.freeze(Geometry);const Ei={POINT_LIST:"point-list",LINE_LIST:"line-list",LINE_STRIP:"line-strip",TRIANGLE_LIST:"triangle-list",TRIANGLE_STRIP:"triangle-strip"};Object.freeze(Ei);function createColorRGB(i,g,x,v){let _=255,y=255,b=255;if(isHexColor(v)){const i=convertHexToRgb(v);_=i.r,y=i.g,b=i.b}return new ColorRGB(_,y,b,()=>{updateTargetUniform(i,g,i[x].rgbNormalLinear)})}function defineColorRGB_func(i){const g=i.key,x=i.value??"#fff",v=Symbol(g);return{get:function(){return void 0===this[v]&&(this[v]=createColorRGB(this,g,v,x)),this[v]},set:function(i){if("string"==typeof i&&isHexColor(i)){const{r:x,g:_,b:y}=convertHexToRgb(i);this[v]?(this[v].r=x,this[v].g=_,this[v].b=y):this[v]=createColorRGB(this,g,v,i)}else i instanceof ColorRGB&&(this[v]=i,updateTargetUniform(this,g,i.rgbNormalLinear))},...vi}}const defineColorRGB=(i,g)=>applyProperties(i,g,defineColorRGB_func);Object.freeze(defineColorRGB);const Ii=parseWGSL("COLOR_MATERIAL","#redgpu_include SYSTEM_UNIFORM #redgpu_include entryPoint.mesh.entryPointPickingFragment #redgpu_include color.getTintBlendMode #redgpu_include systemStruct.OutputFragment #redgpu_include math.getMotionVector struct Uniforms{color:vec3,opacity:f32,useTint:u32,tint:vec4,tintBlendMode:u32,};struct InputData{@builtin(position)position:vec4,@location(0)vertexPosition:vec3,@location(7)currentClipPos:vec4,@location(8)prevClipPos:vec4,@location(11)combinedOpacity:f32,@location(12)motionVector:vec3,@location(15)@interpolate(flat)pickingId:vec4,}@group(2)@binding(0)varuniforms:Uniforms;@fragment fn main(inputData:InputData)->OutputFragment{var output:OutputFragment;var finalColor=vec4(uniforms.color.r,uniforms.color.g,uniforms.color.b,uniforms.opacity*inputData.combinedOpacity);#redgpu_if useTint finalColor=getTintBlendMode(finalColor,uniforms.tintBlendMode,uniforms.tint);#redgpu_endIf if(finalColor.a==.0){discard;}output.color=vec4(finalColor.rgb,finalColor.a);output.gBufferMotionVector=vec4(getMotionVector(inputData.currentClipPos,inputData.prevClipPos),.0,1.0);return output;}");class ColorMaterial extends ABaseMaterial{constructor(i,g="#fff"){super(i,"COLOR_MATERIAL",Ii,2),this.initGPURenderInfos(),this.color.setColorByHEX(g)}}defineColorRGB(ColorMaterial,[{key:"color"}]),Object.freeze(ColorMaterial);class ResourceStateVertexBuffer{static dirtyList=[];buffer;label;uuid;#jt=0;constructor(i){this.buffer=i,this.label=i.name,this.uuid=i.uuid}get useNum(){return this.#jt}set useNum(i){this.#jt=i,ResourceStateVertexBuffer.dirtyList.push(this)}}class VertexBuffer extends ABaseBuffer{[Ar];#jn=0;#Kn=0;#Xn;#qn=0;constructor(i,g,x,v=GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST|GPUBufferUsage.STORAGE,_=""){super(i,"managedVertexBufferState",v);const{table:y}=this.targetResourceManagedState,b=y.get(_);if(b)return b.buffer;this.#Xn=x,_&&(this.name=_,this[kr]=_),this.changeData(g,this.#Xn),this.redGPUContext.resourceManager.registerManagementResource(this,new ResourceStateVertexBuffer(this))}get data(){return this[Ar]}get stride(){return this.#Kn}get interleavedStruct(){return this.#Xn}get vertexCount(){return this.#jn}get triangleCount(){return this.#qn}changeData(i,g){const{gpuDevice:x}=this;if(Array.isArray(i)&&(i=new Float32Array(i)),this[Ar]=i,g&&this.#Yn(g),this[Ir]){this.targetResourceManagedState.videoMemory-=this[Ar].byteLength||0;let i=this[Ir];requestAnimationFrame(()=>{i.destroy()}),this[Ir]=null}const v={size:this[Ar].byteLength,usage:this.usage,label:this.name};this[Ir]=x.createBuffer(v),this.targetResourceManagedState.videoMemory+=this[Ar].byteLength||0,this.#qn=this[Ar].length/this.#Kn/3,x.queue.writeBuffer(this[Ir],0,this[Ar])}updateData(i,g=0){i instanceof Array&&(i=new Float32Array(i));const{gpuDevice:x}=this;x.queue.writeBuffer(this[Ir],g,i)}updateAllData(i){const{gpuDevice:g}=this;g.queue.writeBuffer(this[Ir],0,this[Ar])}#Yn(i){this.#Xn=i,this.#jn=0,this.#Kn=0;for(const i in this.#Xn.define){const g=this.#Xn.define[i].attributeStride/Float32Array.BYTES_PER_ELEMENT;this.#jn+=g,this.#Kn+=g}this.#jn=this[Ar].length/this.#jn}}Object.freeze(VertexBuffer);class VertexInterleavedStructElement{attributeName;attributeStride;interleaveType;constructor(i,g,x){this.attributeName=i,this.attributeStride=g,this.interleaveType=x}}class VertexInterleavedStruct{#Wn;#l="";#Zn=[];#Jn=0;constructor(i,g=""){this.#l=g,this.#Qn(i),this.#ea()}get label(){return this.#l}get attributes(){return this.#Zn}get arrayStride(){return this.#Jn}get define(){return{...this.#Wn}}getAttributeOffset(i){const g=this.#Zn.find(g=>g.attributeName===i);return g||consoleAndThrowError(`Attribute not found: ${i}`),g.offset/4}#Qn(i){let g={};for(const x in i){const v=i[x],_=v.stride;g[x]=new VertexInterleavedStructElement(x,_,v),_%4!=0&&consoleAndThrowError(`Invalid attribute stride: ${_}`)}this.#Wn=g}#ea(){this.#Jn=0,this.#Zn=[];for(const[i,{attributeStride:g,interleaveType:x}]of Object.entries(this.#Wn))this.#Zn.push({attributeName:i,shaderLocation:this.#Zn.length,offset:this.#Jn,format:x.gpuVertexFormat}),this.#Jn+=g}}class VertexInterleaveType{static get float32(){return{numElements:1,stride:Float32Array.BYTES_PER_ELEMENT,gpuVertexFormat:"float32",offset:0}}static get float32x2(){return{numElements:2,stride:2*Float32Array.BYTES_PER_ELEMENT,gpuVertexFormat:"float32x2",offset:0}}static get float32x3(){return{numElements:3,stride:3*Float32Array.BYTES_PER_ELEMENT,gpuVertexFormat:"float32x3",offset:0}}static get float32x4(){return{numElements:4,stride:4*Float32Array.BYTES_PER_ELEMENT,gpuVertexFormat:"float32x4",offset:0}}}Object.freeze(VertexInterleaveType);class DrawBufferManager extends RedGPUObject{static#ta;static#ra=5;#ia=[];#na=[];#aa;#sa=0;#oa=0;#ua;#la=new Set;constructor(i){super(i),this.#ca()}static getInstance(i){return DrawBufferManager.#ta||(DrawBufferManager.#ta=new DrawBufferManager(i)),DrawBufferManager.#ta}allocateDrawCommand(i){this.#oa>=this.#aa&&(this.#sa=this.#ha(),this.#oa=0),this.#la.add(this.#sa);const g={bufferIndex:this.#sa,commandOffset:this.#oa*DrawBufferManager.#ra,buffer:this.#ia[this.#sa],dataArray:this.#na[this.#sa]};return this.#oa++,g}setIndexedIndirectCommand(i,g,x=1,v=0,_=0,y=0){const b=i.commandOffset,S=i.dataArray;S[b]=g,S[b+1]=x,S[b+2]=v,S[b+3]=_,S[b+4]=y}setInstanceNum(i,g=0){const x=i.commandOffset;i.dataArray[x+1]=g}setIndirectCommand(i,g,x=1,v=0,_=0){const y=i.commandOffset,b=i.dataArray;b[y]=g,b[y+1]=x,b[y+2]=v,b[y+3]=_}updateSingleCommand(i){const g=this.#ia[i.bufferIndex],x=this.#na[i.bufferIndex],v=DrawBufferManager.#ra,_=4*i.commandOffset,y=v;this.gpuDevice.queue.writeBuffer(g,_,x,i.commandOffset,y)}getTotalCommandCount(){let i=0;for(const g of this.#la)g===this.#sa?i+=this.#oa:i+=this.#aa;return i}getMemoryUsage(){const i=this.#ia.length,g=this.#la.size,x=i*this.#ua,v=g*this.#ua;return{totalBuffers:i,usedBuffers:g,maxCommandsPerBuffer:this.#aa,totalMemory:formatBytes(x),usedMemory:formatBytes(v),totalCommands:this.getTotalCommandCount()}}flushAllCommands(i){for(const i of this.#la){const g=this.#ia[i],x=this.#na[i],v=(i===this.#sa?this.#oa:this.#aa)*DrawBufferManager.#ra*4;this.gpuDevice.queue.writeBuffer(g,0,x,0,v/4)}performance.now()}#ca(){this.#fa(),this.#da()}#fa(){const i=this.redGPUContext.detector.activeLimits;this.#ua=Math.floor(.9*Math.min(i.maxBufferSize,134217728)),this.#aa=Math.floor(this.#ua/(4*DrawBufferManager.#ra))}#da(){this.#ha()}#ha(){const i=this.#aa*DrawBufferManager.#ra*4,g=this.gpuDevice.createBuffer({size:i,usage:GPUBufferUsage.INDIRECT|GPUBufferUsage.COPY_DST,label:`DrawBuffer_${this.#ia.length}`}),x=new Uint32Array(this.#aa*DrawBufferManager.#ra);return this.#ia.push(g),this.#na.push(x),this.#ia.length-1}}const calculateMeshAABB=i=>{if(!i||!i._geometry)return i.modelMatrix,new AABB(0,0,0,0,0,0);const g=i._geometry.volume,{minX:x,maxX:v,minY:_,maxY:y,minZ:b,maxZ:S}=g;let w=1/0,L=1/0,k=1/0,H=-1/0,z=-1/0,q=-1/0;const W=i.modelMatrix;for(let i=0;i<8;i++){const g=1&i?v:x,be=2&i?y:_,je=4&i?S:b,Ke=W[0]*g+W[4]*be+W[8]*je+W[12],Xe=W[1]*g+W[5]*be+W[9]*je+W[13],Ye=W[2]*g+W[6]*be+W[10]*je+W[14];KeH&&(H=Ke),Xe>z&&(z=Xe),Ye>q&&(q=Ye)}return new AABB(w,H,L,z,k,q)},calculateMeshCombinedAABB=i=>{const g=[];return collectRecursive(i,g),0===g.length?new AABB(0,0,0,0,0,0):calculateCombinedAABBFromAABBs(g)},collectRecursive=(i,g)=>{if(i._geometry){const x=i.boundingAABB;g.push(x)}if(i.children)for(let x=0;x{if(0===i.length)return new AABB(0,0,0,0,0,0);if(1===i.length)return i[0];let g=1/0,x=1/0,v=1/0,_=-1/0,y=-1/0,b=-1/0;for(let S=0;S_&&(_=w.maxX),w.maxY>y&&(y=w.maxY),w.maxZ>b&&(b=w.maxZ)}return new AABB(g,_,x,y,v,b)};class OBB{centerX;centerY;centerZ;halfExtentX;halfExtentY;halfExtentZ;orientation;center;halfExtents;geometryRadius;constructor(i,g,x){this.centerX=i[0],this.centerY=i[1],this.centerZ=i[2],this.halfExtentX=g[0],this.halfExtentY=g[1],this.halfExtentZ=g[2],this.center=[this.centerX,this.centerY,this.centerZ],this.halfExtents=[this.halfExtentX,this.halfExtentY,this.halfExtentZ],this.orientation=clone$4(x),this.geometryRadius=Math.sqrt(this.halfExtentX**2+this.halfExtentY**2+this.halfExtentZ**2)}intersects(i){i instanceof OBB||consoleAndThrowError("allow only OBB instance");const g=subtract$2(create$3(),this.center,i.center);if(length$3(g)>this.geometryRadius+i.geometryRadius)return!1;const x=[...this.#ma(),...i.#ma()];for(const v of x){const x=this.#pa(v),_=i.#pa(v);if(Math.abs(dot$3(g,v))>x+_)return!1}return!0}contains(i,g,x){let v;v=Array.isArray(i)?fromValues$3(i[0],i[1],i[2]):fromValues$3(i,g,x);const _=subtract$2(create$3(),v,this.center),y=this.#ma();for(let i=0;i<3;i++){const g=dot$3(_,y[i]);if(Math.abs(g)>this.halfExtents[i])return!1}return!0}clone(){return new OBB([this.centerX,this.centerY,this.centerZ],[this.halfExtentX,this.halfExtentY,this.halfExtentZ],this.orientation)}#ma(){return[fromValues$3(this.orientation[0],this.orientation[1],this.orientation[2]),fromValues$3(this.orientation[4],this.orientation[5],this.orientation[6]),fromValues$3(this.orientation[8],this.orientation[9],this.orientation[10])]}#pa(i){const g=this.#ma();return Math.abs(dot$3(g[0],i))*this.halfExtentX+Math.abs(dot$3(g[1],i))*this.halfExtentY+Math.abs(dot$3(g[2],i))*this.halfExtentZ}}const calculateMeshOBB=i=>{if(!i||!i._geometry){const i=create$4();return new OBB([0,0,0],[0,0,0],i)}const g=i._geometry.volume;if(0===g.minX&&0===g.maxX&&0===g.minY&&0===g.maxY&&0===g.minZ&&0===g.maxZ){const i=create$4();return new OBB([0,0,0],[0,0,0],i)}const x=[g.centerX,g.centerY,g.centerZ],v=[(g.maxX-g.minX)/2,(g.maxY-g.minY)/2,(g.maxZ-g.minZ)/2],_=create$3();transformMat4$2(_,x,i.modelMatrix);const y=create$4();copy$4(y,i.modelMatrix),y[12]=0,y[13]=0,y[14]=0;const b=[create$3(),create$3(),create$3()],S=[0,0,0];for(let i=0;i<3;i++){const g=[0,0,0];g[i]=v[i],transformMat4$2(b[i],g,y),S[i]=length$3(b[i]),normalize$3(b[i],b[i])}const w=create$4();return w[0]=b[0][0],w[1]=b[0][1],w[2]=b[0][2],w[3]=0,w[4]=b[1][0],w[5]=b[1][1],w[6]=b[1][2],w[7]=0,w[8]=b[2][0],w[9]=b[2][1],w[10]=b[2][2],w[11]=0,w[12]=0,w[13]=0,w[14]=0,w[15]=1,new OBB([_[0],_[1],_[2]],S,w)},mat4ToEuler=(i,g,x)=>{g=g||[0,0,0],x=x||"XYZ";let v=i[0],_=i[4],y=i[8],b=i[1],S=i[5],w=i[9],L=i[2],k=i[6],H=i[10];return"XYZ"===x?(g[1]=Math.asin(clamp(y,-1,1)),Math.abs(y)<.99999?(g[0]=Math.atan2(-w,H),g[2]=Math.atan2(-_,v)):(g[0]=Math.atan2(k,S),g[2]=0)):"YXZ"===x?(g[0]=Math.asin(-clamp(w,-1,1)),Math.abs(w)<.99999?(g[1]=Math.atan2(y,H),g[2]=Math.atan2(b,S)):(g[1]=Math.atan2(-L,v),g[2]=0)):"ZXY"===x?(g[0]=Math.asin(clamp(k,-1,1)),Math.abs(k)<.99999?(g[1]=Math.atan2(-L,H),g[2]=Math.atan2(-_,S)):(g[1]=0,g[2]=Math.atan2(b,v))):"ZYX"===x?(g[1]=Math.asin(-clamp(L,-1,1)),Math.abs(L)<.99999?(g[0]=Math.atan2(k,H),g[2]=Math.atan2(b,v)):(g[0]=0,g[2]=Math.atan2(-_,S))):"YZX"===x?(g[2]=Math.asin(clamp(b,-1,1)),Math.abs(b)<.99999?(g[0]=Math.atan2(-w,S),g[1]=Math.atan2(-L,v)):(g[0]=0,g[1]=Math.atan2(y,H))):"XZY"===x&&(g[2]=Math.asin(-clamp(_,-1,1)),Math.abs(_)<.99999?(g[0]=Math.atan2(k,S),g[1]=Math.atan2(y,v)):(g[0]=Math.atan2(-w,H),g[1]=0)),g};let clamp=function(i,g,x){return Math.max(g,Math.min(x,i))};const Ai=[[-1,-1,-1],[1,-1,-1],[1,1,-1],[-1,1,-1],[-1,-1,1],[1,-1,1],[1,1,1],[-1,1,1]],Li=[[0,1],[1,2],[2,3],[3,0],[4,5],[5,6],[6,7],[7,4],[0,4],[1,5],[2,6],[3,7]];class DrawDebuggerMesh{#ga;#On;#xa;#va;#_a="AABB";#ya;#ba;#Sa=null;#Ta=null;constructor(i,g){this.#ga=g;const x=this.#wa(i);this.#On=x.vertexBuffer,this.#xa=new ColorMaterial(i),this.#xa.color.setColorByRGB(255,0,0),this.#va=new Mesh(i,x,this.#xa),this.#va.primitiveState.cullMode="none",this.#va.primitiveState.topology=Ei.LINE_LIST;const v=this.#wa(i);this.#ya=new ColorMaterial(i),this.#ya.color.setColorByRGB(0,255,0),this.#ba=new Mesh(i,v,this.#ya),this.#ba.primitiveState.cullMode="none",this.#ba.primitiveState.topology=Ei.LINE_LIST}get debugMode(){return this.#_a}set debugMode(i){this.#_a=i,"OBB"===i?this.#xa.color.setColorByRGB(255,0,0):"AABB"===i||"COMBINED_AABB"===i?this.#xa.color.setColorByRGB(0,255,0):"BOTH"===i&&(this.#xa.color.setColorByRGB(255,0,0),this.#ya.color.setColorByRGB(0,255,0)),this.#Sa=null,this.#Ta=null}render(i){if(!this.#ga.enableDebugger)return;if("OBB"===this.#_a){const i=this.#ga.boundingOBB;this.#Ma(i)&&(this.#Pa(i,this.#On),this.#Ra(i))}else if("AABB"===this.#_a||"COMBINED_AABB"===this.#_a){const i="COMBINED_AABB"===this.#_a?this.#ga.combinedBoundingAABB:this.#ga.boundingAABB;this.#Ca(i)&&(this.#Ba(i,this.#On),this.#Da(i))}else if("BOTH"===this.#_a){const i=this.#ga.boundingOBB,g=this.#ga.boundingAABB;this.#Ma(i)&&(this.#Pa(i,this.#On),this.#Ra(i)),this.#Ca(g)&&(this.#Ba(g,this.#ba.geometry.vertexBuffer),this.#Da(g))}let g=!0,x=!0;{const{frustumPlanes:v}=i,_=v[0],y=v[1],b=v[2],S=v[3],w=v[4],L=v[5];{const i=this.#ga.boundingAABB,x=i.centerX,v=i.centerY,k=i.centerZ,H=i.geometryRadius;(_[0]*x+_[1]*v+_[2]*k+_[3]<=-H||y[0]*x+y[1]*v+y[2]*k+y[3]<=-H||b[0]*x+b[1]*v+b[2]*k+b[3]<=-H||S[0]*x+S[1]*v+S[2]*k+S[3]<=-H||w[0]*x+w[1]*v+w[2]*k+w[3]<=-H||L[0]*x+L[1]*v+L[2]*k+L[3]<=-H)&&(g=!1)}{const i=this.#ga.boundingOBB,g=i.centerX,v=i.centerY,k=i.centerZ,H=i.geometryRadius;(_[0]*g+_[1]*v+_[2]*k+_[3]<=-H||y[0]*g+y[1]*v+y[2]*k+y[3]<=-H||b[0]*g+b[1]*v+b[2]*k+b[3]<=-H||S[0]*g+S[1]*v+S[2]*k+S[3]<=-H||w[0]*g+w[1]*v+w[2]*k+w[3]<=-H||L[0]*g+L[1]*v+L[2]*k+L[3]<=-H)&&(x=!1)}}"OBB"===this.#_a?x&&this.#va.render(i):"AABB"===this.#_a||"COMBINED_AABB"===this.#_a?g&&this.#va.render(i):"BOTH"===this.#_a&&(x&&this.#va.render(i),g&&this.#ba.render(i))}#wa(i){const g=new Float32Array(288),x=new VertexInterleavedStruct({vertexPosition:VertexInterleaveType.float32x3,vertexNormal:VertexInterleaveType.float32x3,texcoord:VertexInterleaveType.float32x2,vertexTangent:VertexInterleaveType.float32x4},`wireframeBoxStruct_${Math.random()}`),v=new VertexBuffer(i,g,x);return new Geometry(i,v)}#Ma(i){if(!this.#Sa)return!0;const g=this.#Sa;return g.center[0]!==i.center[0]||g.center[1]!==i.center[1]||g.center[2]!==i.center[2]||g.halfExtents[0]!==i.halfExtents[0]||g.halfExtents[1]!==i.halfExtents[1]||g.halfExtents[2]!==i.halfExtents[2]||!this.#Ea(g.orientation,i.orientation)}#Ca(i){if(!this.#Ta)return!0;const g=this.#Ta;return g.minX!==i.minX||g.maxX!==i.maxX||g.minY!==i.minY||g.maxY!==i.maxY||g.minZ!==i.minZ||g.maxZ!==i.maxZ}#Ea(i,g){if(i.length!==g.length)return!1;for(let x=0;x1e-4)return!1;return!0}#Ra(i){this.#Sa=new OBB(i.center,i.halfExtents,i.orientation)}#Da(i){this.#Ta=i.clone()}#Pa(i,g){const{center:x,halfExtents:v,orientation:_}=i,y=[];for(let i=0;i<8;i++){const g=Ai[i],b=g[0]*v[0],S=g[1]*v[1],w=g[2]*v[2],L=_[0]*b+_[4]*S+_[8]*w,k=_[1]*b+_[5]*S+_[9]*w,H=_[2]*b+_[6]*S+_[10]*w;y.push([L+x[0],k+x[1],H+x[2]])}this.#Fn(y,g)}#Ba(i,g){const{minX:x,maxX:v,minY:_,maxY:y,minZ:b,maxZ:S}=i,w=[[x,_,b],[v,_,b],[v,y,b],[x,y,b],[x,_,S],[v,_,S],[v,y,S],[x,y,S]];this.#Fn(w,g)}#Fn(i,g){const x=g.data;let v=0;for(let g=0;g<12;g++){const _=Li[g],y=_[0],b=_[1],S=i[y],w=i[b];x[v++]=S[0],x[v++]=S[1],x[v++]=S[2],x[v++]=0,x[v++]=0,x[v++]=1,x[v++]=0,x[v++]=0,x[v++]=1,x[v++]=0,x[v++]=0,x[v++]=1,x[v++]=w[0],x[v++]=w[1],x[v++]=w[2],x[v++]=0,x[v++]=0,x[v++]=1,x[v++]=0,x[v++]=0,x[v++]=1,x[v++]=0,x[v++]=0,x[v++]=1}g.updateAllData(x)}}Object.freeze(DrawDebuggerMesh);const createMeshVertexUniformBuffers=(i,g=!1)=>{const{gpuRenderInfo:x,redGPUContext:v}=i,{resourceManager:_}=v,y=_.getGPUBindGroupLayout(g?ResourceManager.PRESET_VERTEX_GPUBindGroupLayout_SKIN:ResourceManager.PRESET_VERTEX_GPUBindGroupLayout),b=new ArrayBuffer(x.vertexUniformInfo.arrayBufferByteLength),S=new UniformBuffer(v,b,i.name);x.vertexBindGroupLayout=y,x.vertexUniformBuffer=S};function createSetter$3(i,g){return function(x){this[g]=x,updateTargetUniform(this,i,x)}}function defineVector(i,g){const x=Symbol(i);return{get:function(){return void 0===this[x]&&(this[x]=g),this[x]},set:createSetter$3(i,x),...vi}}function defineVector3_func(i){return defineVector(i.key,i.value??[0,0,0])}Object.freeze(defineVector);const defineVector3=(i,g)=>applyProperties(i,g,defineVector3_func);function defineVector4_func(i){return defineVector(i.key,i.value??[0,0,0,0])}Object.freeze(defineVector3);const defineVector4=(i,g)=>applyProperties(i,g,defineVector4_func);function defineVector2_func(i){return defineVector(i.key,i.value??[0,0])}Object.freeze(defineVector4);const defineVector2=(i,g)=>applyProperties(i,g,defineVector2_func);function defineSampler_func(i){const{key:g}=i,x=Symbol(g);return{get:function(){return this[x]},set:function(i){const g=this[x];this[x]=i,this.updateSampler(g,i)},...vi}}Object.freeze(defineVector2);const defineSampler=(i,g)=>applyProperties(i,g,defineSampler_func);function createSetter$2(i,g){const x=`use${i.charAt(0).toUpperCase()}${i.substring(1)}`;return function(i){const v=this[g];this[g]=i,this.updateTexture(v,i),x in this&&(this[x]=!!i),updateTargetUniform(this,x,i?1:0)}}function defineTexture_func(i){const{key:g}=i,x=Symbol(g);return{get:function(){return this[x]},set:createSetter$2(g,x),...vi}}Object.freeze(defineSampler);const defineTexture=(i,g)=>applyProperties(i,g,defineTexture_func);Object.freeze(defineTexture);const Ui=[{textureList:["baseColorTexture"],vec4List:[{key:"baseColorFactor",value:[1,1,1,1]}]},{textureList:["normalTexture"]},{textureList:["metallicRoughnessTexture"],positiveNumberList:[{key:"metallicFactor",value:1},{key:"roughnessFactor",value:1}]},{textureList:["emissiveTexture"],vec3List:[{key:"emissiveFactor",value:[0,0,0]}]},{textureList:["occlusionTexture"],positiveNumberList:[{key:"occlusionStrength",value:1}]},{extensionName:"KHR_materials_clearcoat",textureList:["KHR_clearcoatTexture","KHR_clearcoatNormalTexture","KHR_clearcoatRoughnessTexture"],positiveNumberList:[{key:"KHR_clearcoatFactor",value:0},{key:"KHR_clearcoatRoughnessFactor",value:0},{key:"KHR_clearcoatNormalScale",value:1}]},{extensionName:"KHR_materials_sheen",textureList:["KHR_sheenColorTexture","KHR_sheenRoughnessTexture"],positiveNumberList:[{key:"KHR_sheenRoughnessFactor",value:0}],vec3List:[{key:"KHR_sheenColorFactor",value:[0,0,0]}]},{extensionName:"KHR_materials_specular",textureList:["KHR_specularTexture","KHR_specularColorTexture"],positiveNumberList:[{key:"KHR_specularFactor",value:1}],vec3List:[{key:"KHR_specularColorFactor",value:[1,1,1]}]},{extensionName:"KHR_materials_transmission",textureList:["KHR_transmissionTexture"],positiveNumberList:[{key:"KHR_transmissionFactor",value:0}]},{extensionName:"KHR_materials_volume",textureList:["KHR_thicknessTexture"],positiveNumberList:[{key:"KHR_thicknessFactor",value:0},{key:"KHR_attenuationDistance",value:1}],vec3List:[{key:"KHR_attenuationColor",value:[1,1,1]}]},{extensionName:"KHR_materials_diffuse_transmission",textureList:["KHR_diffuseTransmissionTexture","KHR_diffuseTransmissionColorTexture"],positiveNumberList:[{key:"KHR_diffuseTransmissionFactor",value:0}],vec3List:[{key:"KHR_diffuseTransmissionColorFactor",value:[1,1,1]}]},{extensionName:"KHR_materials_anisotropy",textureList:["KHR_anisotropyTexture"],positiveNumberList:[{key:"KHR_anisotropyStrength",value:0},{key:"KHR_anisotropyRotation",value:0}]},{extensionName:"KHR_materials_iridescence",textureList:["KHR_iridescenceTexture","KHR_iridescenceThicknessTexture"],positiveNumberList:[{key:"KHR_iridescenceFactor",value:0},{key:"KHR_iridescenceIor",value:1.3},{key:"KHR_iridescenceThicknessMinimum",value:100},{key:"KHR_iridescenceThicknessMaximum",value:400}]}],ki=parseWGSL("PBR_MATERIAL",(i=>{const g=Ui.map(i=>{const{textureList:g}=i,x=g?.map(i=>`\n\t\t\t\tuse${i.charAt(0).toUpperCase()}${i.substring(1)}: u32,\n \t\t${i}_texCoord_index: u32,\n\t\t\t\tuse_${i}_KHR_texture_transform: u32,\n\t\t\t\t${i}_KHR_texture_transform_offset: vec2,\n\t\t\t\t${i}_KHR_texture_transform_scale: vec2,\n\t\t\t\t${i}_KHR_texture_transform_rotation: f32,`).join("");return[x].join("\n")}).join("");return i.replace(/#redgpu_include KHR_texture_transform/g,g)})("#redgpu_include SYSTEM_UNIFORM;#redgpu_include shadow.getDirectionalShadowVisibility;#redgpu_include color.getTintBlendMode;#redgpu_include entryPoint.mesh.entryPointPickingFragment;#redgpu_include systemStruct.OutputFragment;#redgpu_include math.getMotionVector;#redgpu_include math.getIsFinite;#redgpu_include lighting.getLightDistanceAttenuation;#redgpu_include lighting.getLightAngleAttenuation;#redgpu_include math.PI #redgpu_include math.PI2 #redgpu_include math.INV_PI #redgpu_include math.EPSILON #redgpu_include math.direction.getViewDirection #redgpu_include math.direction.getReflectionVectorFromViewDirection #redgpu_include math.tnb.getTBNFromVertexTangent #redgpu_include math.tnb.getTBN #redgpu_include math.tnb.getNormalFromNormalMap #redgpu_include skyAtmosphere.skyAtmosphereFn struct Uniforms{useVertexColor:u32,useCutOff:u32,cutOff:f32,alphaBlend:u32,doubleSided:u32,useVertexTangent:u32,opacity:f32,useTint:u32,tint:vec4,tintBlendMode:u32,baseColorFactor:vec4,emissiveFactor:vec3,emissiveStrength:f32,occlusionStrength:f32,metallicFactor:f32,roughnessFactor:f32,normalScale:f32,useKHR_materials_unlit:u32,KHR_materials_ior:f32,useKHR_materials_transmission:u32,KHR_transmissionFactor:f32,useKHR_materials_diffuse_transmission:u32,KHR_diffuseTransmissionFactor:f32,KHR_diffuseTransmissionColorFactor:vec3,KHR_dispersion:f32,useKHR_materials_volume:u32,KHR_thicknessFactor:f32,KHR_attenuationDistance:f32,KHR_attenuationColor:vec3,useKHR_materials_specular:u32,KHR_specularFactor:f32,KHR_specularColorFactor:vec3,useKHR_materials_anisotropy:u32,KHR_anisotropyStrength:f32,KHR_anisotropyRotation:f32,useKHR_materials_iridescence:u32,KHR_iridescenceFactor:f32,KHR_iridescenceIor:f32,KHR_iridescenceThicknessMinimum:f32,KHR_iridescenceThicknessMaximum:f32,useKHR_materials_sheen:u32,KHR_sheenColorFactor:vec3,KHR_sheenRoughnessFactor:f32,useKHR_materials_clearcoat:u32,KHR_clearcoatFactor:f32,KHR_clearcoatRoughnessFactor:f32,KHR_clearcoatNormalScale:f32,#redgpu_include KHR_texture_transform};@group(2)@binding(0)varuniforms:Uniforms;@group(2)@binding(1)var baseColorTextureSampler:sampler;#redgpu_if baseColorTexture @group(2)@binding(2)var baseColorTexture:texture_2d;#redgpu_endIf #redgpu_if emissiveTexture @group(2)@binding(3)var emissiveTextureSampler:sampler;@group(2)@binding(4)var emissiveTexture:texture_2d;#redgpu_endIf #redgpu_if normalTexture @group(2)@binding(5)var normalTextureSampler:sampler;@group(2)@binding(6)var normalTexture:texture_2d;#redgpu_endIf #redgpu_if packedORMTexture @group(2)@binding(7)var packedORMTexture:texture_2d;#redgpu_endIf #redgpu_if useKHR_materials_specular @group(2)@binding(8)var KHR_specularTextureSampler:sampler;@group(2)@binding(9)var KHR_specularTexture:texture_2d;@group(2)@binding(10)var KHR_specularColorTextureSampler:sampler;@group(2)@binding(11)var KHR_specularColorTexture:texture_2d;#redgpu_endIf @group(2)@binding(12)var KHR_clearcoatNormalTexture:texture_2d;@group(2)@binding(13)var packedKHR_clearcoatTexture_transmission:texture_2d;#redgpu_if useKHR_materials_diffuse_transmission @group(2)@binding(14)var packedKHR_diffuse_transmission:texture_2d;#redgpu_endIf #redgpu_if useKHR_materials_sheen @group(2)@binding(15)var packedKHR_sheen:texture_2d;#redgpu_endIf #redgpu_if useKHR_materials_anisotropy @group(2)@binding(16)var KHR_anisotropyTexture:texture_2d;#redgpu_endIf #redgpu_if useKHR_materials_iridescence @group(2)@binding(17)var packedKHR_iridescence:texture_2d;#redgpu_endIf struct InputData{@builtin(position)position:vec4,@location(0)vertexPosition:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,@location(3)uv1:vec2,@location(4)vertexColor_0:vec4,@location(5)vertexTangent:vec4,@location(7)currentClipPos:vec4,@location(8)prevClipPos:vec4,@location(10)localNodeScale_volumeScale:vec2,@location(11)combinedOpacity:f32,@location(12)motionVector:vec3,@location(13)shadowCoord:vec3,@location(14)@interpolate(flat)receiveShadow:f32,@location(15)@interpolate(flat)pickingId:vec4,}fn getTransmissionRefraction(u_useKHR_materials_volume:bool,thicknessParameter:f32,u_KHR_dispersion:f32,u_KHR_attenuationDistance:f32,u_KHR_attenuationColor:vec3,ior:f32,roughnessParameter:f32,albedo:vec3,projectionViewMatrix:mat4x4,input_vertexPosition:vec3,input_ndcPosition:vec3,V:vec3,N:vec3,renderPath1ResultTexture:texture_2d,renderPath1ResultTextureSampler:sampler)->vec3{var transmissionRefraction=vec3(.0);let maxMipLevel=f32(textureNumLevels(renderPath1ResultTexture)-1);let transmissionMipLevel=clamp(roughnessParameter*maxMipLevel,.0,maxMipLevel);if(u_useKHR_materials_volume){var iorR:f32=ior;var iorG:f32=ior;var iorB:f32=ior;if(u_KHR_dispersion>.0){let halfSpread:f32=(ior-1.0)*.025*u_KHR_dispersion;iorR=ior+halfSpread;iorG=ior;iorB=ior-halfSpread;}iorR=max(iorR,1.0+EPSILON);iorG=max(iorG,1.0+EPSILON);iorB=max(iorB,1.0+EPSILON);let refractedVecR:vec3=refract(-V,N,1.0/iorR);let refractedVecG:vec3=refract(-V,N,1.0/iorG);let refractedVecB:vec3=refract(-V,N,1.0/iorB);let validR=dot(refractedVecR,refractedVecR)>.0;let validG=dot(refractedVecG,refractedVecG)>.0;let validB=dot(refractedVecB,refractedVecB)>.0;let R=getReflectionVectorFromViewDirection(V,N);let finalRefractR=select(R,refractedVecR,validR);let finalRefractG=select(R,refractedVecG,validG);let finalRefractB=select(R,refractedVecB,validB);let safeThickness=clamp(thicknessParameter,.0,100.0);let worldPosR:vec3=input_vertexPosition+finalRefractR*safeThickness;let worldPosG:vec3=input_vertexPosition+finalRefractG*safeThickness;let worldPosB:vec3=input_vertexPosition+finalRefractB*safeThickness;let clipPosR:vec4=projectionViewMatrix*vec4(worldPosR,1.0);let clipPosG:vec4=projectionViewMatrix*vec4(worldPosG,1.0);let clipPosB:vec4=projectionViewMatrix*vec4(worldPosB,1.0);let wR=max(abs(clipPosR.w),EPSILON);let wG=max(abs(clipPosG.w),EPSILON);let wB=max(abs(clipPosB.w),EPSILON);let ndcR:vec2=clipPosR.xy/wR*0.5+0.5;let ndcG:vec2=clipPosG.xy/wG*0.5+0.5;let ndcB:vec2=clipPosB.xy/wB*0.5+0.5;let finalUV_R:vec2=clamp(vec2(ndcR.x,1.0-ndcR.y),vec2(.0),vec2(1.0));let finalUV_G:vec2=clamp(vec2(ndcG.x,1.0-ndcG.y),vec2(.0),vec2(1.0));let finalUV_B:vec2=clamp(vec2(ndcB.x,1.0-ndcB.y),vec2(.0),vec2(1.0));let sampledR=textureSampleLevel(renderPath1ResultTexture,renderPath1ResultTextureSampler,finalUV_R,transmissionMipLevel).r;let sampledG=textureSampleLevel(renderPath1ResultTexture,renderPath1ResultTextureSampler,finalUV_G,transmissionMipLevel).g;let sampledB=textureSampleLevel(renderPath1ResultTexture,renderPath1ResultTextureSampler,finalUV_B,transmissionMipLevel).b;transmissionRefraction.r=select(.0,sampledR,getIsFiniteScalar(sampledR));transmissionRefraction.g=select(.0,sampledG,getIsFiniteScalar(sampledG));transmissionRefraction.b=select(.0,sampledB,getIsFiniteScalar(sampledB));}else{let safeIor=max(ior,1.0+EPSILON);let refractedVec:vec3=refract(-V,N,1.0/safeIor);let valid=dot(refractedVec,refractedVec)>.0;let R=getReflectionVectorFromViewDirection(V,N);let finalRefract=select(R,refractedVec,valid);let safeThickness=clamp(thicknessParameter,.0,100.0);let worldPos:vec3=input_vertexPosition+finalRefract*safeThickness;let clipPos:vec4=projectionViewMatrix*vec4(worldPos,1.0);let w=max(abs(clipPos.w),EPSILON);let ndc:vec2=clipPos.xy/w*0.5+0.5;let finalUV:vec2=clamp(vec2(ndc.x,1.0-ndc.y),vec2(.0),vec2(1.0));let sampled=textureSampleLevel(renderPath1ResultTexture,renderPath1ResultTextureSampler,finalUV,transmissionMipLevel).rgb;transmissionRefraction=select(vec3(.0),sampled,all(getIsFiniteVec3(sampled)));}let safeAlbedo=clamp(albedo,vec3(.0),vec3(1.0));transmissionRefraction*=safeAlbedo;transmissionRefraction=select(vec3(.0),transmissionRefraction,all(getIsFiniteVec3(transmissionRefraction)));return transmissionRefraction;}@fragment fn main(inputData:InputData)->OutputFragment{var output:OutputFragment;let input_vertexNormal=(inputData.vertexNormal.xyz);let input_vertexPosition=inputData.vertexPosition.xyz;let input_vertexColor_0=inputData.vertexColor_0;let input_vertexTangent=inputData.vertexTangent;let input_ndcPosition=inputData.position.xyz/inputData.position.w;let input_uv=inputData.uv;let input_uv1=inputData.uv1;let u_camera=systemUniforms.camera;let u_cameraPosition=u_camera.cameraPosition;let preExposure=systemUniforms.preExposure;let u_usePrefilterTexture=systemUniforms.usePrefilterTexture==1u;let u_useSkyAtmosphere=systemUniforms.useSkyAtmosphere==1u;let u_opacity=uniforms.opacity;let u_cutOff=uniforms.cutOff;let u_useVertexColor=uniforms.useVertexColor==1u;let u_useVertexTangent=uniforms.useVertexTangent==1u;let u_baseColorFactor=uniforms.baseColorFactor;let u_metallicFactor=uniforms.metallicFactor;let u_roughnessFactor=uniforms.roughnessFactor;let u_normalScale=uniforms.normalScale;let u_occlusionStrength=uniforms.occlusionStrength;let u_emissiveFactor=uniforms.emissiveFactor;let u_emissiveStrength=uniforms.emissiveStrength;let u_useKHR_materials_unlit=uniforms.useKHR_materials_unlit==1u;let u_KHR_materials_ior=uniforms.KHR_materials_ior;let u_KHR_dispersion=uniforms.KHR_dispersion;let u_KHR_transmissionFactor=uniforms.KHR_transmissionFactor;let u_useKHR_materials_volume=uniforms.useKHR_materials_volume==1u;let u_KHR_thicknessFactor=uniforms.KHR_thicknessFactor;let u_KHR_attenuationColor=uniforms.KHR_attenuationColor;let u_KHR_attenuationDistance=uniforms.KHR_attenuationDistance;let u_useKHR_materials_diffuse_transmission=uniforms.useKHR_materials_diffuse_transmission==1u;let u_KHR_diffuseTransmissionFactor=uniforms.KHR_diffuseTransmissionFactor;let u_KHR_diffuseTransmissionColorFactor=uniforms.KHR_diffuseTransmissionColorFactor;let u_KHR_specularFactor=uniforms.KHR_specularFactor;let u_KHR_specularColorFactor=uniforms.KHR_specularColorFactor;let u_KHR_anisotropyStrength=uniforms.KHR_anisotropyStrength;let u_KHR_anisotropyRotation=uniforms.KHR_anisotropyRotation;let u_useKHR_anisotropyTexture=uniforms.useKHR_anisotropyTexture==1u;let u_KHR_sheenColorFactor=uniforms.KHR_sheenColorFactor;let u_KHR_sheenRoughnessFactor=uniforms.KHR_sheenRoughnessFactor;let u_useKHR_materials_iridescence=uniforms.useKHR_materials_iridescence==1u;let u_KHR_iridescenceFactor=uniforms.KHR_iridescenceFactor;let u_KHR_iridescenceIor=uniforms.KHR_iridescenceIor;let u_KHR_iridescenceThicknessMinimum=uniforms.KHR_iridescenceThicknessMinimum;let u_KHR_iridescenceThicknessMaximum=uniforms.KHR_iridescenceThicknessMaximum;let u_KHR_clearcoatFactor=uniforms.KHR_clearcoatFactor;let u_KHR_clearcoatRoughnessFactor=uniforms.KHR_clearcoatRoughnessFactor;let u_KHR_clearcoatNormalScale=uniforms.KHR_clearcoatNormalScale;let diffuseUV=getTextureTransformUV(input_uv,input_uv1,uniforms.baseColorTexture_texCoord_index,uniforms.use_baseColorTexture_KHR_texture_transform,uniforms.baseColorTexture_KHR_texture_transform_offset,uniforms.baseColorTexture_KHR_texture_transform_rotation,uniforms.baseColorTexture_KHR_texture_transform_scale);let emissiveUV=getTextureTransformUV(input_uv,input_uv1,uniforms.emissiveTexture_texCoord_index,uniforms.use_emissiveTexture_KHR_texture_transform,uniforms.emissiveTexture_KHR_texture_transform_offset,uniforms.emissiveTexture_KHR_texture_transform_rotation,uniforms.emissiveTexture_KHR_texture_transform_scale);let occlusionUV=getTextureTransformUV(input_uv,input_uv1,uniforms.occlusionTexture_texCoord_index,uniforms.use_occlusionTexture_KHR_texture_transform,uniforms.occlusionTexture_KHR_texture_transform_offset,uniforms.occlusionTexture_KHR_texture_transform_rotation,uniforms.occlusionTexture_KHR_texture_transform_scale);let metallicRoughnessUV=getTextureTransformUV(input_uv,input_uv1,uniforms.metallicRoughnessTexture_texCoord_index,uniforms.use_metallicRoughnessTexture_KHR_texture_transform,uniforms.metallicRoughnessTexture_KHR_texture_transform_offset,uniforms.metallicRoughnessTexture_KHR_texture_transform_rotation,uniforms.metallicRoughnessTexture_KHR_texture_transform_scale);let normalUV=getTextureTransformUV(input_uv,input_uv1,uniforms.normalTexture_texCoord_index,uniforms.use_normalTexture_KHR_texture_transform,uniforms.normalTexture_KHR_texture_transform_offset,uniforms.normalTexture_KHR_texture_transform_rotation,uniforms.normalTexture_KHR_texture_transform_scale);let KHR_clearcoatUV=getTextureTransformUV(input_uv,input_uv1,uniforms.KHR_clearcoatTexture_texCoord_index,uniforms.use_KHR_clearcoatTexture_KHR_texture_transform,uniforms.KHR_clearcoatTexture_KHR_texture_transform_offset,uniforms.KHR_clearcoatTexture_KHR_texture_transform_rotation,uniforms.KHR_clearcoatTexture_KHR_texture_transform_scale);#redgpu_if useKHR_materials_clearcoat let KHR_clearcoatNormalUV=getTextureTransformUV(input_uv,input_uv1,uniforms.KHR_clearcoatNormalTexture_texCoord_index,uniforms.use_KHR_clearcoatNormalTexture_KHR_texture_transform,uniforms.KHR_clearcoatNormalTexture_KHR_texture_transform_offset,uniforms.KHR_clearcoatNormalTexture_KHR_texture_transform_rotation,uniforms.KHR_clearcoatNormalTexture_KHR_texture_transform_scale);#redgpu_endIf let KHR_clearcoatRoughnessUV=getTextureTransformUV(input_uv,input_uv1,uniforms.KHR_clearcoatRoughnessTexture_texCoord_index,uniforms.use_KHR_clearcoatRoughnessTexture_KHR_texture_transform,uniforms.KHR_clearcoatRoughnessTexture_KHR_texture_transform_offset,uniforms.KHR_clearcoatRoughnessTexture_KHR_texture_transform_rotation,uniforms.KHR_clearcoatRoughnessTexture_KHR_texture_transform_scale);let KHR_sheenColorUV=getTextureTransformUV(input_uv,input_uv1,uniforms.KHR_sheenColorTexture_texCoord_index,uniforms.use_KHR_sheenColorTexture_KHR_texture_transform,uniforms.KHR_sheenColorTexture_KHR_texture_transform_offset,uniforms.KHR_sheenColorTexture_KHR_texture_transform_rotation,uniforms.KHR_sheenColorTexture_KHR_texture_transform_scale);let KHR_sheenRoughnessUV=getTextureTransformUV(input_uv,input_uv1,uniforms.KHR_sheenRoughnessTexture_texCoord_index,uniforms.use_KHR_sheenRoughnessTexture_KHR_texture_transform,uniforms.KHR_sheenRoughnessTexture_KHR_texture_transform_offset,uniforms.KHR_sheenRoughnessTexture_KHR_texture_transform_rotation,uniforms.KHR_sheenRoughnessTexture_KHR_texture_transform_scale);let KHR_specularTextureUV=getTextureTransformUV(input_uv,input_uv1,uniforms.KHR_specularTexture_texCoord_index,uniforms.use_KHR_specularTexture_KHR_texture_transform,uniforms.KHR_specularTexture_KHR_texture_transform_offset,uniforms.KHR_specularTexture_KHR_texture_transform_rotation,uniforms.KHR_specularTexture_KHR_texture_transform_scale);let KHR_specularColorTextureUV=getTextureTransformUV(input_uv,input_uv1,uniforms.KHR_specularColorTexture_texCoord_index,uniforms.use_KHR_specularColorTexture_KHR_texture_transform,uniforms.KHR_specularColorTexture_KHR_texture_transform_offset,uniforms.KHR_specularColorTexture_KHR_texture_transform_rotation,uniforms.KHR_specularColorTexture_KHR_texture_transform_scale);let KHR_iridescenceTextureUV=getTextureTransformUV(input_uv,input_uv1,uniforms.KHR_iridescenceTexture_texCoord_index,uniforms.use_KHR_iridescenceTexture_KHR_texture_transform,uniforms.KHR_iridescenceTexture_KHR_texture_transform_offset,uniforms.KHR_iridescenceTexture_KHR_texture_transform_rotation,uniforms.KHR_iridescenceTexture_KHR_texture_transform_scale);let KHR_iridescenceThicknessTextureUV=getTextureTransformUV(input_uv,input_uv1,uniforms.KHR_iridescenceThicknessTexture_texCoord_index,uniforms.use_KHR_iridescenceThicknessTexture_KHR_texture_transform,uniforms.KHR_iridescenceThicknessTexture_KHR_texture_transform_offset,uniforms.KHR_iridescenceThicknessTexture_KHR_texture_transform_rotation,uniforms.KHR_iridescenceThicknessTexture_KHR_texture_transform_scale);let KHR_transmissionUV=getTextureTransformUV(input_uv,input_uv1,uniforms.KHR_transmissionTexture_texCoord_index,uniforms.use_KHR_transmissionTexture_KHR_texture_transform,uniforms.KHR_transmissionTexture_KHR_texture_transform_offset,uniforms.KHR_transmissionTexture_KHR_texture_transform_rotation,uniforms.KHR_transmissionTexture_KHR_texture_transform_scale);let KHR_diffuseTransmissionUV=getTextureTransformUV(input_uv,input_uv1,uniforms.KHR_diffuseTransmissionTexture_texCoord_index,uniforms.use_KHR_diffuseTransmissionTexture_KHR_texture_transform,uniforms.KHR_diffuseTransmissionTexture_KHR_texture_transform_offset,uniforms.KHR_diffuseTransmissionTexture_KHR_texture_transform_rotation,uniforms.KHR_diffuseTransmissionTexture_KHR_texture_transform_scale);let KHR_diffuseTransmissionColorUV=getTextureTransformUV(input_uv,input_uv1,uniforms.KHR_diffuseTransmissionColorTexture_texCoord_index,uniforms.use_KHR_diffuseTransmissionColorTexture_KHR_texture_transform,uniforms.KHR_diffuseTransmissionColorTexture_KHR_texture_transform_offset,uniforms.KHR_diffuseTransmissionColorTexture_KHR_texture_transform_rotation,uniforms.KHR_diffuseTransmissionColorTexture_KHR_texture_transform_scale);let KHR_anisotropyUV=getTextureTransformUV(input_uv,input_uv1,uniforms.KHR_anisotropyTexture_texCoord_index,uniforms.use_KHR_anisotropyTexture_KHR_texture_transform,uniforms.KHR_anisotropyTexture_KHR_texture_transform_offset,uniforms.KHR_anisotropyTexture_KHR_texture_transform_rotation,uniforms.KHR_anisotropyTexture_KHR_texture_transform_scale);let V:vec3=getViewDirection(input_vertexPosition,u_cameraPosition);let baseNormal:vec3=normalize(input_vertexNormal.xyz);var N:vec3=baseNormal;var backFaceYn:bool=false;#redgpu_if doubleSided{if(dot(baseNormal,V)<.0){backFaceYn=true;}}#redgpu_endIf let tbnNeeded=#redgpu_if normalTexture true||#redgpu_endIf #redgpu_if useKHR_materials_clearcoat true||#redgpu_endIf #redgpu_if useKHR_materials_anisotropy true||#redgpu_endIf false;var tbn:mat3x3;if(tbnNeeded){tbn=getTBNFromVertexTangent(baseNormal,input_vertexTangent);}#redgpu_if normalTexture{var normalSamplerColor=textureSample(normalTexture,normalTextureSampler,normalUV).rgb;N=getNormalFromNormalMap(vec3(normalSamplerColor.r,1.0-normalSamplerColor.g,normalSamplerColor.b),tbn,u_normalScale);}#redgpu_endIf if(backFaceYn){N=-N;}N=normalize(N);let NdotV=max(abs(dot(N,V)),.04);let receiveShadowYn=inputData.receiveShadow !=.0;var visibility:f32=1.0;visibility=getDirectionalShadowVisibility(directionalShadowMap,directionalShadowMapSampler,systemUniforms.shadow.directionalShadowDepthTextureSize,systemUniforms.shadow.directionalShadowBias,inputData.shadowCoord);if(!receiveShadowYn){visibility=1.0;}var baseColor=u_baseColorFactor;var resultAlpha:f32=u_opacity*baseColor.a;baseColor*=select(vec4(1.0),input_vertexColor_0,u_useVertexColor);#redgpu_if baseColorTexture let diffuseSampleColor=(textureSample(baseColorTexture,baseColorTextureSampler,diffuseUV));baseColor*=diffuseSampleColor;resultAlpha*=diffuseSampleColor.a;#redgpu_endIf #redgpu_if useKHR_materials_unlit if(u_useKHR_materials_unlit){output.color=vec4(baseColor.rgb,baseColor.a);return output;}#redgpu_endIf let albedo:vec3=baseColor.rgb;var ior:f32=u_KHR_materials_ior;var occlusionParameter:f32=1.0;#redgpu_if useOcclusionTexture occlusionParameter=textureSample(packedORMTexture,packedTextureSampler,occlusionUV).r*u_occlusionStrength;#redgpu_endIf var metallicParameter:f32=u_metallicFactor;var roughnessParameter:f32=u_roughnessFactor;#redgpu_if useMetallicRoughnessTexture let metallicRoughnessSample=(textureSample(packedORMTexture,packedTextureSampler,metallicRoughnessUV));metallicParameter*=metallicRoughnessSample.b;roughnessParameter*=metallicRoughnessSample.g;#redgpu_endIf roughnessParameter=max(roughnessParameter,.04);if(abs(ior-1.0)=select(baseNormal,-baseNormal,backFaceYn);#redgpu_if useKHR_materials_clearcoat{if(clearcoatParameter>.0){#redgpu_if useKHR_clearcoatTexture let clearcoatSample=textureSample(packedKHR_clearcoatTexture_transmission,packedTextureSampler,KHR_clearcoatUV);clearcoatParameter*=clearcoatSample.r;#redgpu_endIf #redgpu_if useKHR_clearcoatRoughnessTexture let clearcoatRoughnesstSample=textureSample(packedKHR_clearcoatTexture_transmission,packedTextureSampler,KHR_clearcoatRoughnessUV);clearcoatRoughnessParameter*=clearcoatRoughnesstSample.g;#redgpu_endIf #redgpu_if useKHR_clearcoatNormalTexture{let clearcoatNormalSamplerColor=textureSample(KHR_clearcoatNormalTexture,baseColorTextureSampler,KHR_clearcoatNormalUV).rgb;let texturedNormal=getNormalFromNormalMap(clearcoatNormalSamplerColor,tbn,u_KHR_clearcoatNormalScale);clearcoatNormal=select(texturedNormal,-texturedNormal,backFaceYn);}#redgpu_endIf clearcoatNormal=normalize(clearcoatNormal);}}#redgpu_endIf var specularParameter=u_KHR_specularFactor;var specularColor=u_KHR_specularColorFactor;#redgpu_if useKHR_materials_specular #redgpu_if KHR_specularColorTexture specularColor*=textureSample(KHR_specularColorTexture,KHR_specularColorTextureSampler,KHR_specularColorTextureUV).rgb;#redgpu_endIf #redgpu_if KHR_specularTexture specularParameter*=textureSample(KHR_specularTexture,KHR_specularTextureSampler,KHR_specularTextureUV).a;#redgpu_endIf #redgpu_endIf var transmissionParameter:f32=u_KHR_transmissionFactor;var thicknessParameter:f32=u_KHR_thicknessFactor;#redgpu_if useKHR_materials_transmission #redgpu_if useKHR_transmissionTexture transmissionParameter*=textureSample(packedKHR_clearcoatTexture_transmission,packedTextureSampler,KHR_transmissionUV).b;#redgpu_endIf #redgpu_if useKHR_thicknessTexture thicknessParameter*=textureSample(packedKHR_clearcoatTexture_transmission,packedTextureSampler,KHR_transmissionUV).a;#redgpu_endIf #redgpu_endIf var diffuseTransmissionColor:vec3=u_KHR_diffuseTransmissionColorFactor;var diffuseTransmissionParameter:f32=u_KHR_diffuseTransmissionFactor;#redgpu_if useKHR_materials_diffuse_transmission #redgpu_if useKHR_diffuseTransmissionTexture diffuseTransmissionParameter*=textureSample(packedKHR_diffuse_transmission,packedTextureSampler,KHR_diffuseTransmissionUV).a;#redgpu_endIf #redgpu_if useKHR_diffuseTransmissionColorTexture diffuseTransmissionColor*=textureSample(packedKHR_diffuse_transmission,packedTextureSampler,KHR_diffuseTransmissionColorUV).rgb;#redgpu_endIf #redgpu_endIf var sheenColor=u_KHR_sheenColorFactor;var sheenRoughnessParameter=u_KHR_sheenRoughnessFactor;#redgpu_if useKHR_materials_sheen #redgpu_if useKHR_sheenColorTexture sheenColor*=textureSample(packedKHR_sheen,packedTextureSampler,KHR_sheenColorUV).rgb;#redgpu_endIf #redgpu_if useKHR_sheenRoughnessTexture sheenRoughnessParameter*=textureSample(packedKHR_sheen,packedTextureSampler,KHR_sheenRoughnessUV).a;#redgpu_endIf #redgpu_endIf var iridescenceParameter=u_KHR_iridescenceFactor;var iridescenceThickness=u_KHR_iridescenceThicknessMaximum;#redgpu_if useKHR_materials_iridescence #redgpu_if useKHR_iridescenceTexture iridescenceParameter*=textureSample(packedKHR_iridescence,packedTextureSampler,KHR_iridescenceTextureUV).r;#redgpu_endIf #redgpu_if useKHR_iridescenceThicknessTexture iridescenceThickness=mix(u_KHR_iridescenceThicknessMinimum,u_KHR_iridescenceThicknessMaximum,textureSample(packedKHR_iridescence,packedTextureSampler,KHR_iridescenceThicknessTextureUV).g);#redgpu_endIf #redgpu_endIf var anisotropy:f32=u_KHR_anisotropyStrength;var anisotropicT:vec3=vec3(1.0);var anisotropicB:vec3=vec3(1.0);#redgpu_if useKHR_materials_anisotropy{let T=tbn[0];let B=tbn[1];var anisotropicDirection:vec2=vec2(1.0,.0);if(u_useKHR_anisotropyTexture){let anisotropyTex=textureSample(KHR_anisotropyTexture,baseColorTextureSampler,KHR_anisotropyUV).rgb;anisotropicDirection=anisotropyTex.rg*2.0-1.0;anisotropy*=anisotropyTex.b;}let cosR=cos(u_KHR_anisotropyRotation);let sinR=sin(u_KHR_anisotropyRotation);anisotropicDirection=mat2x2(cosR,sinR,-sinR,cosR)*anisotropicDirection;let anisotropicTBN=getTBN(N,T*anisotropicDirection.x+B*anisotropicDirection.y);anisotropicT=anisotropicTBN[0];anisotropicB=anisotropicTBN[1];}#redgpu_endIf var transmissionRefraction=vec3(.0);#redgpu_if useKHR_materials_transmission{transmissionRefraction=getTransmissionRefraction(u_useKHR_materials_volume,thicknessParameter*inputData.localNodeScale_volumeScale[1],u_KHR_dispersion,u_KHR_attenuationDistance,u_KHR_attenuationColor,ior,roughnessParameter,albedo,systemUniforms.projection.projectionViewMatrix,input_vertexPosition,input_ndcPosition,V,N,renderPath1ResultTexture,renderPath1ResultTextureSampler);#redgpu_if useKHR_materials_volume if(u_useKHR_materials_volume){let localNodeScale=inputData.localNodeScale_volumeScale[0];let scaledThickness=thicknessParameter*localNodeScale;let safeAttenuationColor=clamp(u_KHR_attenuationColor,vec3(EPSILON),vec3(1.0));let safeAttenuationDistance=max(u_KHR_attenuationDistance,EPSILON);let attenuationCoefficient=-log(safeAttenuationColor)/safeAttenuationDistance;let pathLength=scaledThickness/max(NdotV,.04);transmissionRefraction*=exp(-attenuationCoefficient*pathLength);}#redgpu_endIf}#redgpu_endIf let F0_dielectric_base=getDielectricF0(ior);var F0_dielectric=F0_dielectric_base*specularColor;var F0_metal=albedo;#redgpu_if useKHR_materials_iridescence if(iridescenceParameter>.0){F0_dielectric=getIridescentFresnel(1.0,u_KHR_iridescenceIor,F0_dielectric,iridescenceThickness,iridescenceParameter,NdotV);F0_metal=getIridescentFresnel(1.0,u_KHR_iridescenceIor,albedo,iridescenceThickness,iridescenceParameter,NdotV);}#redgpu_endIf let F0=mix(F0_dielectric,F0_metal,metallicParameter);let totalDirectLighting=getDirectPbrLighting(input_vertexPosition,inputData.position,visibility,N,V,NdotV,roughnessParameter,metallicParameter,albedo,F0_dielectric_base,ior,specularColor,specularParameter,u_useKHR_materials_diffuse_transmission,diffuseTransmissionParameter,diffuseTransmissionColor,transmissionParameter,sheenColor,sheenRoughnessParameter,anisotropy,anisotropicT,anisotropicB,clearcoatParameter,clearcoatRoughnessParameter,clearcoatNormal,u_useKHR_materials_iridescence,iridescenceParameter,u_KHR_iridescenceIor,iridescenceThickness);let indirectLighting=getIndirectPbrLighting(N,V,NdotV,albedo,&roughnessParameter,metallicParameter,F0,F0_dielectric,F0_metal,specularParameter,occlusionParameter,transmissionParameter,transmissionRefraction,u_useKHR_materials_diffuse_transmission,diffuseTransmissionParameter,diffuseTransmissionColor,sheenColor,sheenRoughnessParameter,anisotropy,anisotropicT,anisotropicB,clearcoatParameter,clearcoatRoughnessParameter,clearcoatNormal);var emissiveColor=u_emissiveFactor*u_emissiveStrength;#redgpu_if emissiveTexture emissiveColor*=textureSample(emissiveTexture,emissiveTextureSampler,emissiveUV).rgb;#redgpu_endIf let finalColor=vec4(totalDirectLighting+indirectLighting+emissiveColor,resultAlpha);#redgpu_if useCutOff if(resultAlpha<=u_cutOff){discard;}#redgpu_endIf #redgpu_if useTint output.color=getTintBlendMode(finalColor,uniforms.tintBlendMode,uniforms.tint);#redgpu_else output.color=finalColor;#redgpu_endIf{let smoothness=1.0-roughnessParameter;let smoothnessCurved=smoothness*smoothness*(3.0-2.0*smoothness);let baseReflectionStrength=smoothnessCurved*(.04+0.96*metallicParameter*metallicParameter);output.gBufferNormal=vec4(N*0.5+0.5,baseReflectionStrength);}output.gBufferMotionVector=vec4(getMotionVector(inputData.currentClipPos,inputData.prevClipPos),.0,1.0);return output;}fn getTextureTransformUV(input_uv:vec2,input_uv1:vec2,texCoord_index:u32,use_transform:u32,transform_offset:vec2,transform_rotation:f32,transform_scale:vec2)->vec2{var result_uv=select(input_uv,input_uv1,texCoord_index==1u);if(use_transform==1u){let translation=mat3x3(1.0,.0,.0,.0,1.0,.0,transform_offset.x,transform_offset.y,1.0);let cos_rot=cos(transform_rotation);let sin_rot=sin(transform_rotation);let rotation_matrix=mat3x3(cos_rot,-sin_rot,.0,sin_rot,cos_rot,.0,.0,.0,1.0);let scale_matrix=mat3x3(transform_scale.x,.0,.0,.0,transform_scale.y,.0,.0,.0,1.0);let result_matrix=translation*rotation_matrix*scale_matrix;result_uv=(result_matrix*vec3(result_uv,1.0)).xy;}return result_uv;}fn getDielectricF0(ior:f32)->vec3{let f0_factor=(ior-1.0)/(ior+1.0);return vec3(f0_factor*f0_factor);}fn getSpecularNDF(NdotH:f32,roughness:f32)->f32{let alpha=roughness*roughness;let alpha2=alpha*alpha;let NdotH2=NdotH*NdotH;let nom=alpha2;let denom=(NdotH2*(alpha2-1.0)+1.0);let denomSquared=denom*denom;return nom/max(EPSILON,denomSquared*PI);}fn getSpecularVisibility(NdotV:f32,NdotL:f32,roughness:f32)->f32{let alpha=roughness*roughness;let alpha2=alpha*alpha;let safeNdotV=max(NdotV,1e-4);let safeNdotL=max(NdotL,1e-4);let GGXV=safeNdotL*sqrt(safeNdotV*safeNdotV*(1.0-alpha2)+alpha2);let GGXL=safeNdotV*sqrt(safeNdotL*safeNdotL*(1.0-alpha2)+alpha2);return 0.5/max(GGXV+GGXL,EPSILON);}fn getFresnel(cosTheta:f32,F0:vec3)->vec3{return F0+(vec3(1.0)-F0)*pow(clamp(1.0-cosTheta,.0,1.0),5.0);}fn getIndirectFresnel(cosTheta:f32,F0:vec3,roughness:f32,fresnelTerm:f32)->vec3{let F90=max(vec3(1.0-roughness*0.8),F0);return F0+(F90-F0)*fresnelTerm;}fn getDirectSpecularBRDF(F:vec3,roughness:f32,NdotH:f32,NdotV:f32,NdotL:f32)->vec3{let D=getSpecularNDF(NdotH,roughness);let V=getSpecularVisibility(NdotV,NdotL,roughness);return D*V*F;}fn getDirectDiffuseBRDF(NdotL:f32,NdotV:f32,LdotH:f32,roughness:f32,albedo:vec3)->vec3{if(NdotL<=.0){return vec3(.0);}let energyBias=mix(.0,0.5,roughness);let energyFactor=mix(1.0,1.0/1.51,roughness);let fd90=energyBias+2.0*LdotH*LdotH*roughness;let f0=1.0;let lightScatter=f0+(fd90-f0)*pow(1.0-NdotL,5.0);let viewScatter=f0+(fd90-f0)*pow(1.0-NdotV,5.0);return albedo*NdotL*lightScatter*viewScatter*energyFactor*INV_PI;}fn getDirectSpecularBTDF(NdotV:f32,NdotL:f32,NdotH:f32,VdotH:f32,LdotH:f32,roughness:f32,F:vec3,ior:f32)->vec3{let eta:f32=1.0/ior;let D_rough:f32=getSpecularNDF(NdotH,roughness);let t:f32=clamp((ior-1.0)*100.0,.0,1.0);let D:f32=mix(1.0,D_rough,t);let G:f32=min(1.0,min((2.0*NdotH*NdotV)/VdotH,(2.0*NdotH*abs(NdotL))/VdotH));let denom=(eta*VdotH+LdotH)*(eta*VdotH+LdotH);let btdf:vec3=(vec3(1.0)-F)*abs(VdotH*LdotH)*(eta*eta)*D*G/(max(NdotV,EPSILON)*max(abs(NdotL),EPSILON)*max(denom,EPSILON));return btdf;}fn getDirectDiffuseBTDF(N:vec3,L:vec3,albedo:vec3)->vec3{let cosTheta=max(-dot(N,L),.0);return albedo*cosTheta*INV_PI;}struct SheenIBLResult{sheenIBLContribution:vec3,sheenAlbedoScaling:f32}fn getSheenAlbedoScaling(maxSheenColor:f32,sheenE:f32)->f32{return 1.0-maxSheenColor*sheenE;}fn getIndirectSheenDFG(NdotV:f32,roughness:f32)->f32{if(roughness<.01){return .0;}let r=clamp(roughness,.01,1.0);let grazingFactor=1.0-NdotV;let roughnessExp=1.0/max(r,EPSILON);let distribution=pow(grazingFactor,roughnessExp);let intensity=pow(roughnessExp,0.5);return distribution*intensity*0.5;}fn getSheenCharlieE(NdotV:f32,roughness:f32)->f32{if(roughness<.01){return .0;}let r=clamp(roughness,.01,1.0);let grazingFactor=1.0-NdotV;let roughnessExp=1.0/max(r,EPSILON);return pow(grazingFactor,roughnessExp)*pow(r,0.5);}fn getIndirectSheenBRDF(N:vec3,V:vec3,R:vec3,sheenColor:vec3,maxSheenColor:f32,sheenRoughness:f32,iblMipmapCount:f32,irradianceTexture:texture_cube,textureSampler:sampler)->SheenIBLResult{let NdotV=clamp(dot(N,V),EPSILON,1.0);let mipLevel=sheenRoughness*iblMipmapCount;let sheenRadiance=textureSampleLevel(irradianceTexture,textureSampler,R,mipLevel).rgb*systemUniforms.preExposure*systemUniforms.iblIntensity;let r=clamp(sheenRoughness,.01,1.0);let grazingFactor=1.0-NdotV;let roughnessExp=1.0/r;let sharedPow=pow(grazingFactor,roughnessExp);let sheenDFG=sharedPow*pow(roughnessExp,0.5)*0.5;let E=sharedPow*pow(r,0.5);let contribution=sheenRadiance*sheenColor*sheenDFG;let albedoScaling=getSheenAlbedoScaling(maxSheenColor,E);return SheenIBLResult(contribution,albedoScaling);}fn getDirectSheenBRDF(NdotL:f32,NdotV:f32,NdotH:f32,sheenColor:vec3,sheenRoughness:f32)->vec3{let invAlpha=1.0/max(sheenRoughness,.000001);let cos2h=NdotH*NdotH;let sin2h=max(1.0-cos2h,.0078125);let sheenDistribution=(2.0+invAlpha)*pow(sin2h,invAlpha*0.5)/(2.0*PI);let sheenVisibility=1.0/(4.0*(NdotL+NdotV-NdotL*NdotV));return sheenColor*sheenDistribution*sheenVisibility;}fn getDirectAnisotropicVisibility(NdotL:f32,NdotV:f32,BdotV:f32,TdotV:f32,TdotL:f32,BdotL:f32,at:f32,ab:f32)->f32{let GGXV=NdotL*length(vec3(at*TdotV,ab*BdotV,NdotV));let GGXL=NdotV*length(vec3(at*TdotL,ab*BdotL,NdotL));let v=0.5/max(GGXV+GGXL,EPSILON);return v;}fn getDirectAnisotropicNDF(NdotH:f32,TdotH:f32,BdotH:f32,at:f32,ab:f32)->f32{let a2:f32=at*ab;let f:vec3=vec3(ab*TdotH,at*BdotH,a2*NdotH);let denominator:f32=dot(f,f);let w2:f32=a2/max(denominator,EPSILON);return a2*w2*w2*INV_PI;}fn getDirectAnisotropicBRDF(F:vec3,alphaRoughness:f32,VdotH:f32,NdotL:f32,NdotV:f32,NdotH:f32,BdotV:f32,TdotV:f32,TdotL:f32,BdotL:f32,TdotH:f32,BdotH:f32,anisotropy:f32)->vec3{var at=mix(alphaRoughness,1.0,anisotropy*anisotropy);var ab=alphaRoughness;var V:f32=getDirectAnisotropicVisibility(NdotL,NdotV,BdotV,TdotV,TdotL,BdotL,at,ab);var D:f32=getDirectAnisotropicNDF(NdotH,TdotH,BdotH,at,ab);return F*(V*D);}fn getIndirectAnisotropicBRDF(V:vec3,N:vec3,roughness:f32,anisotropy:f32,anisotropicT:vec3,anisotropicB:vec3)->vec4{let grainDir=select(anisotropicT,anisotropicB,anisotropy>=.0);let stretch=abs(anisotropy)*(1.0-roughness);var T_perp_V=cross(grainDir,V);if(dot(T_perp_V,T_perp_V)(R,max(effectiveRoughness,.04));}fn getDirectClearcoatBRDF(L:vec3,V:vec3,H:vec3,clearcoatNormal:vec3,clearcoatRoughness:f32,LdotH:f32)->vec3{let clearcoatNdotL=max(dot(clearcoatNormal,L),.0);let clearcoatNdotV=max(dot(clearcoatNormal,V),.04);let clearcoatNdotH=max(dot(clearcoatNormal,H),.0);let clearcoatF=getFresnel(LdotH,vec3(.04));let CLEARCOAT_BRDF=getDirectSpecularBRDF(clearcoatF,clearcoatRoughness,clearcoatNdotH,clearcoatNdotV,clearcoatNdotL);return CLEARCOAT_BRDF*clearcoatNdotL;}fn getIndirectClearcoatBRDF(V:vec3,clearcoatNormal:vec3,clearcoatRoughness:f32,iblMipmapCount:f32,ibl_prefilterTexture:texture_cube,prefilterTextureSampler:sampler,ibl_brdfLUTTexture:texture_2d,useSkyAtmosphere:bool,sunIntensity:f32,skyAtmosphere_prefilteredTexture:texture_cube,atmosphereSampler:sampler,cameraHeight:f32,atmosphereHeight:f32,transmittanceTexture:texture_2d,mainR:vec3,isMainNormal:bool)->vec4{let clearcoatR=select(getReflectionVectorFromViewDirection(V,clearcoatNormal),mainR,isMainNormal);let clearcoatNdotV=max(abs(dot(clearcoatNormal,V)),.04);let clearcoatMipLevel=clearcoatRoughness*iblMipmapCount;var clearcoatRadiance=textureSampleLevel(ibl_prefilterTexture,prefilterTextureSampler,clearcoatR,clearcoatMipLevel).rgb*systemUniforms.preExposure*systemUniforms.iblIntensity;if(useSkyAtmosphere){let u_atmo=systemUniforms.skyAtmosphere;let skyIntensity=u_atmo.sunIntensity;let ccTrans=getTransmittance(transmittanceTexture,atmosphereSampler,cameraHeight,clearcoatR.y,atmosphereHeight);let atmoMipCount=f32(textureNumLevels(skyAtmosphere_prefilteredTexture)-1);let atmoMipLevel=clearcoatRoughness*atmoMipCount;let ccSkyScat=textureSampleLevel(skyAtmosphere_prefilteredTexture,atmosphereSampler,clearcoatR,atmoMipLevel).rgb*skyIntensity*systemUniforms.preExposure;clearcoatRadiance=(clearcoatRadiance*ccTrans)+ccSkyScat;}let clearcoatEnvBRDF=textureSampleLevel(ibl_brdfLUTTexture,prefilterTextureSampler,clamp(vec2(clearcoatNdotV,clearcoatRoughness),vec2(.005),vec2(0.995)),.0).rg;let coatF=getIndirectFresnel(clearcoatNdotV,vec3(.04),clearcoatRoughness,pow(1.0-clearcoatNdotV,5.0-2.0*clearcoatRoughness)).x;let clearcoatIBL_Weight=(.04*clearcoatEnvBRDF.x+clearcoatEnvBRDF.y);return vec4(clearcoatRadiance*clearcoatIBL_Weight,coatF);}fn getIridescentFresnel(outsideIOR:f32,iridescenceIOR:f32,baseF0:vec3,iridescenceThickness:f32,iridescenceFactor:f32,cosTheta1:f32)->vec3{if(iridescenceThickness<=.0||iridescenceFactor<=.0){return baseF0;}let cosTheta1Abs=abs(cosTheta1);let safeIridescenceIOR=max(iridescenceIOR,1.01);let sinTheta1=sqrt(max(.0,1.0-cosTheta1Abs*cosTheta1Abs));let sinTheta2=(outsideIOR/safeIridescenceIOR)*sinTheta1;if(sinTheta2>=1.0){return baseF0+iridescenceFactor*(1.0-baseF0);}let cosTheta2=sqrt(1.0-sinTheta2*sinTheta2);let opticalThickness=2.0*iridescenceThickness*safeIridescenceIOR*cosTheta2;let phase=(PI2*opticalThickness)*vec3(1.0/650.0,1.0/510.0,1.0/475.0);let cosPhase=cos(phase);let sinPhase=sin(phase);let outsideCos1=outsideIOR*cosTheta1Abs;let iridescenceCos2=safeIridescenceIOR*cosTheta2;let iridescenceCos1=safeIridescenceIOR*cosTheta1Abs;let outsideCos2=outsideIOR*cosTheta2;let r12_s=(outsideCos1-iridescenceCos2)/max(outsideCos1+iridescenceCos2,EPSILON);let r12_p=(iridescenceCos1-outsideCos2)/max(iridescenceCos1+outsideCos2,EPSILON);let sqrtF0=sqrt(clamp(baseF0,vec3(.01),vec3(0.99)));let safeN3=(1.0+sqrtF0)/max(1.0-sqrtF0,vec3(EPSILON));let r23_s=(iridescenceCos2-safeN3*cosTheta1Abs)/max(iridescenceCos2+safeN3*cosTheta1Abs,vec3(EPSILON));let r23_p=(safeN3*cosTheta2-iridescenceCos1)/max(safeN3*cosTheta2+iridescenceCos1,vec3(EPSILON));let r12_s_vec=vec3(r12_s);let r12_p_vec=vec3(r12_p);let denSReal=1.0+r12_s_vec*r23_s*cosPhase;let denSImag=-r12_s_vec*r23_s*sinPhase;let denSSquared=denSReal*denSReal+denSImag*denSImag;let numSReal=r12_s_vec+r23_s*cosPhase;let numSImag=-r23_s*sinPhase;let Rs=(numSReal*numSReal+numSImag*numSImag)/max(denSSquared,vec3(EPSILON));let denPReal=1.0+r12_p_vec*r23_p*cosPhase;let denPImag=-r12_p_vec*r23_p*sinPhase;let denPSquared=denPReal*denPReal+denPImag*denPImag;let numPReal=r12_p_vec+r23_p*cosPhase;let numPImag=-r23_p*sinPhase;let Rp=(numPReal*numPReal+numPImag*numPImag)/max(denPSquared,vec3(EPSILON));let reflectance=clamp(0.5*(Rs+Rp),vec3(.0),vec3(1.0));return mix(baseF0,reflectance,iridescenceFactor);}fn getDirectPbrLighting(input_vertexPosition:vec3,inputData_position:vec4,visibility:f32,N:vec3,V:vec3,NdotV:f32,roughnessParameter:f32,metallicParameter:f32,albedo:vec3,F0_dielectric_base:vec3,ior:f32,specularColor:vec3,specularParameter:f32,u_useKHR_materials_diffuse_transmission:bool,diffuseTransmissionParameter:f32,diffuseTransmissionColor:vec3,transmissionParameter:f32,sheenColor:vec3,sheenRoughnessParameter:f32,anisotropy:f32,anisotropicT:vec3,anisotropicB:vec3,clearcoatParameter:f32,clearcoatRoughnessParameter:f32,clearcoatNormal:vec3,useIridescence:bool,iridescenceFactor:f32,iridescenceIor:f32,iridescenceThickness:f32)->vec3{var totalDirectLighting=vec3(.0);let u_directionalLightCount=systemUniforms.directionalLightCount;let u_directionalLights=systemUniforms.directionalLights;for(var i=0u;iu_clusterLightRadius){continue;}let L=normalize(lightDir);let attenuation=getLightDistanceAttenuation(lightDistance,u_clusterLightRadius);var finalAttenuation=attenuation;if(u_isSpotLight>.0){let u_clusterLightDirection=normalize(vec3(targetLight.directionX,targetLight.directionY,targetLight.directionZ));let lightToVertex=normalize(-L);finalAttenuation*=getLightAngleAttenuation(lightToVertex,u_clusterLightDirection,targetLight.innerCutoff,targetLight.outerCutoff);}var finalLightColor=targetLight.color*targetLight.intensity*finalAttenuation*systemUniforms.preExposure;totalDirectLighting+=getDirectPbrLight(finalLightColor,N,V,L,NdotV,roughnessParameter,metallicParameter,albedo,F0_dielectric_base,ior,specularColor,specularParameter,u_useKHR_materials_diffuse_transmission,diffuseTransmissionParameter,diffuseTransmissionColor,transmissionParameter,sheenColor,sheenRoughnessParameter,anisotropy,anisotropicT,anisotropicB,clearcoatParameter,clearcoatRoughnessParameter,clearcoatNormal,useIridescence,iridescenceFactor,iridescenceIor,iridescenceThickness);}}return totalDirectLighting;}fn getIndirectPbrLighting(N:vec3,V:vec3,NdotV:f32,albedo:vec3,roughnessParameter:ptr,metallicParameter:f32,F0:vec3,F0_dielectric:vec3,F0_metal:vec3,specularParameter:f32,occlusionParameter:f32,transmissionParameter:f32,transmissionRefraction:vec3,u_useKHR_materials_diffuse_transmission:bool,diffuseTransmissionParameter:f32,diffuseTransmissionColor:vec3,sheenColor:vec3,sheenRoughnessParameter:f32,anisotropy:f32,anisotropicT:vec3,anisotropicB:vec3,clearcoatParameter:f32,clearcoatRoughnessParameter:f32,clearcoatNormal:vec3)->vec3{let u_usePrefilterTexture=systemUniforms.usePrefilterTexture==1u;let u_useSkyAtmosphere=systemUniforms.useSkyAtmosphere==1u;let preExposure=systemUniforms.preExposure;if(u_usePrefilterTexture||u_useSkyAtmosphere){var R=getReflectionVectorFromViewDirection(V,N);let NdotV_IBL=max(abs(dot(N,V)),.04);var iblRoughness=*roughnessParameter;#redgpu_if useKHR_materials_anisotropy if(anisotropy>.0){let anisotropicResult=getIndirectAnisotropicBRDF(V,N,iblRoughness,anisotropy,anisotropicT,anisotropicB);R=anisotropicResult.xyz;iblRoughness=anisotropicResult.w;}#redgpu_endIf var reflectedColor=vec3(.0);var iblDiffuseColor=vec3(.0);var iblMipmapCount:f32=.0;if(u_usePrefilterTexture){iblMipmapCount=f32(textureNumLevels(ibl_prefilterTexture)-1);var mipLevel=iblRoughness*iblMipmapCount;reflectedColor=textureSampleLevel(ibl_prefilterTexture,prefilterTextureSampler,R,mipLevel).rgb*preExposure*systemUniforms.iblIntensity;iblDiffuseColor=textureSampleLevel(ibl_irradianceTexture,prefilterTextureSampler,N,0).rgb*preExposure*systemUniforms.iblIntensity;}if(u_useSkyAtmosphere){let u_atmo=systemUniforms.skyAtmosphere;let camH=u_atmo.cameraHeight;let atmH=u_atmo.atmosphereHeight;let skyIntensity=u_atmo.sunIntensity;let specTrans=getTransmittance(transmittanceTexture,atmosphereSampler,camH,R.y,atmH);let atmoMipCount=f32(textureNumLevels(skyAtmosphere_prefilteredTexture)-1);let atmoMipLevel=iblRoughness*atmoMipCount;let specSkyScat=textureSampleLevel(skyAtmosphere_prefilteredTexture,atmosphereSampler,R,atmoMipLevel).rgb*skyIntensity*preExposure;reflectedColor=(reflectedColor*specTrans)+specSkyScat;let diffTrans=getTransmittance(transmittanceTexture,atmosphereSampler,camH,N.y,atmH);let skyIrradiance=textureSampleLevel(atmosphereIrradianceLUT,atmosphereSampler,N,.0).rgb*skyIntensity*preExposure;iblDiffuseColor=(iblDiffuseColor*diffTrans)+skyIrradiance;}let envBRDF=textureSampleLevel(ibl_brdfLUTTexture,prefilterTextureSampler,clamp(vec2(NdotV_IBL,*roughnessParameter),vec2(.005),vec2(0.995)),.0).rg;let energyCompensation=1.0+F0*(1.0/max(envBRDF.x+envBRDF.y,1e-4)-1.0);reflectedColor*=energyCompensation;let fresnelPower=5.0-2.0*(*roughnessParameter);let fresnelTerm=pow(saturate(1.0-NdotV_IBL),fresnelPower);let FR_dielectric=getIndirectFresnel(NdotV_IBL,F0_dielectric,*roughnessParameter,fresnelTerm);let FR_metal=getIndirectFresnel(NdotV_IBL,F0_metal,*roughnessParameter,fresnelTerm);let horizonOcclusion=saturate(1.0+1.1*dot(R,N));reflectedColor*=horizonOcclusion*horizonOcclusion;let F_IBL_dielectric=FR_dielectric*envBRDF.x+envBRDF.y;let F_IBL_metal=FR_metal*envBRDF.x+envBRDF.y;let F_IBL_dielectric_weight=F_IBL_dielectric*specularParameter;let specularOcclusion=saturate(pow(NdotV_IBL+occlusionParameter,exp2(-16.0*(*roughnessParameter)-1.0))-1.0+occlusionParameter);let specularAlbedo_IBL=saturate(F0_dielectric*envBRDF.x+envBRDF.y);let diffuseWeight_IBL=(vec3(1.0)-specularAlbedo_IBL*specularParameter);var envIBL_DIFFUSE:vec3=albedo*iblDiffuseColor*diffuseWeight_IBL*INV_PI*occlusionParameter;#redgpu_if useKHR_materials_diffuse_transmission{var backScatteringColor=vec3(.0);if(u_usePrefilterTexture){let mipLevel=iblRoughness*iblMipmapCount;backScatteringColor=textureSampleLevel(ibl_prefilterTexture,prefilterTextureSampler,-N,mipLevel).rgb*preExposure*systemUniforms.iblIntensity;}if(u_useSkyAtmosphere){let u_atmo=systemUniforms.skyAtmosphere;let skyIntensity=u_atmo.sunIntensity;let backTrans=getTransmittance(transmittanceTexture,atmosphereSampler,u_atmo.cameraHeight,-N.y,u_atmo.atmosphereHeight);let backSkyScat=textureSampleLevel(skyAtmosphere_prefilteredTexture,prefilterTextureSampler,-N,.0).rgb*skyIntensity*preExposure;backScatteringColor=(backScatteringColor*backTrans)+backSkyScat;}let transmittedIBL=backScatteringColor*diffuseTransmissionColor*(vec3(1.0)-F_IBL_dielectric_weight);envIBL_DIFFUSE=mix(envIBL_DIFFUSE,transmittedIBL,diffuseTransmissionParameter);}#redgpu_endIf var envIBL_SPECULAR_BTDF=vec3(.0);#redgpu_if useKHR_materials_transmission if(transmissionParameter>.0){envIBL_SPECULAR_BTDF=transmissionRefraction*(vec3(1.0)-F_IBL_dielectric_weight)*specularOcclusion;}#redgpu_endIf var sheenIBLContribution=vec3(.0);var sheenAlbedoScaling:f32=1.0;#redgpu_if useKHR_materials_sheen{let maxSheenColor=max(sheenColor.x,max(sheenColor.y,sheenColor.z));let sheenResult=getIndirectSheenBRDF(N,V,R,sheenColor,maxSheenColor,sheenRoughnessParameter,iblMipmapCount,ibl_prefilterTexture,prefilterTextureSampler);sheenIBLContribution=sheenResult.sheenIBLContribution;sheenAlbedoScaling=sheenResult.sheenAlbedoScaling;}#redgpu_endIf let ibl_specular_dielectric=reflectedColor*F_IBL_dielectric_weight*specularOcclusion;let ibl_diffuse_dielectric=mix(envIBL_DIFFUSE,envIBL_SPECULAR_BTDF,transmissionParameter);let dielectricPart_IBL=ibl_specular_dielectric+ibl_diffuse_dielectric;let metallicPart_IBL=reflectedColor*F_IBL_metal*specularOcclusion;let baseIndirect=mix(dielectricPart_IBL,metallicPart_IBL,metallicParameter);var indirectLighting=(baseIndirect*sheenAlbedoScaling+sheenIBLContribution);#redgpu_if useKHR_materials_clearcoat if(clearcoatParameter>.0){let u_atmo=systemUniforms.skyAtmosphere;let clearcoatResult=getIndirectClearcoatBRDF(V,clearcoatNormal,clearcoatRoughnessParameter,iblMipmapCount,ibl_prefilterTexture,prefilterTextureSampler,ibl_brdfLUTTexture,u_useSkyAtmosphere,u_atmo.sunIntensity,skyAtmosphere_prefilteredTexture,atmosphereSampler,u_atmo.cameraHeight,u_atmo.atmosphereHeight,transmittanceTexture,R,all(clearcoatNormal==N));let clearcoatSpecularIBL=clearcoatResult.rgb*clearcoatParameter;let coatF=clearcoatResult.a*clearcoatParameter;indirectLighting=clearcoatSpecularIBL+(vec3(1.0)-coatF)*indirectLighting;}#redgpu_endIf return indirectLighting;}else{let ambientContribution=albedo*systemUniforms.ambientLight.color*systemUniforms.ambientLight.intensity*occlusionParameter*preExposure*INV_PI;var indirectLighting=ambientContribution;#redgpu_if useKHR_materials_transmission if(transmissionParameter>.0){let transmissionFresnel=getFresnel(NdotV,F0);let transmissionWeight=transmissionParameter*(vec3(1.0)-transmissionFresnel);indirectLighting=mix(ambientContribution,transmissionRefraction,transmissionWeight);}#redgpu_endIf return indirectLighting;}}fn getDirectPbrLight(lightColor:vec3,N:vec3,V:vec3,L:vec3,VdotN:f32,roughnessParameter:f32,metallicParameter:f32,albedo:vec3,F0_base:vec3,ior:f32,specularColor:vec3,specularParameter:f32,u_useKHR_materials_diffuse_transmission:bool,diffuseTransmissionParameter:f32,diffuseTransmissionColor:vec3,transmissionParameter:f32,sheenColor:vec3,sheenRoughnessParameter:f32,anisotropy:f32,anisotropicT:vec3,anisotropicB:vec3,clearcoatParameter:f32,clearcoatRoughnessParameter:f32,clearcoatNormal:vec3,useIridescence:bool,iridescenceFactor:f32,iridescenceIor:f32,iridescenceThickness:f32)->vec3{let dLight=lightColor;let NdotL_origin=dot(N,L);let NdotL=max(NdotL_origin,.0);let H=normalize(L+V);let NdotH=max(dot(N,H),.0);let LdotH=max(dot(L,H),.0);let VdotH=max(dot(V,H),.0);var F:vec3;let dielectric_f0=F0_base*specularColor;let metal_f0=albedo;let combined_f0=mix(dielectric_f0,metal_f0,metallicParameter);if(useIridescence&&iridescenceFactor>.0){let F_irid_dielectric=getIridescentFresnel(1.0,iridescenceIor,dielectric_f0,iridescenceThickness,iridescenceFactor,VdotH);let F_irid_metal=getIridescentFresnel(1.0,iridescenceIor,metal_f0,iridescenceThickness,iridescenceFactor,VdotH);F=mix(F_irid_dielectric,F_irid_metal,metallicParameter);}else{F=getFresnel(VdotH,combined_f0);}if(abs(ior-1.0)(.0);}var SPEC_BRDF=getDirectSpecularBRDF(F,roughnessParameter,NdotH,VdotN,NdotL);if(anisotropy>.0){#redgpu_if useKHR_materials_anisotropy var TdotL=dot(anisotropicT,L);var TdotV=dot(anisotropicT,V);var BdotL=dot(anisotropicB,L);var TdotH=dot(anisotropicT,H);var BdotH=dot(anisotropicB,H);var BdotV=dot(anisotropicB,V);SPEC_BRDF=getDirectAnisotropicBRDF(F,roughnessParameter*roughnessParameter,VdotH,NdotL,VdotN,NdotH,BdotV,TdotV,TdotL,BdotL,TdotH,BdotH,anisotropy);#redgpu_endIf}if(abs(ior-1.0)(.0);}let diffuse_reflection=getDirectDiffuseBRDF(NdotL,VdotN,LdotH,roughnessParameter,albedo);var diffuse_transmission=vec3(.0);#redgpu_if useKHR_materials_diffuse_transmission if(u_useKHR_materials_diffuse_transmission){diffuse_transmission=getDirectDiffuseBTDF(N,L,diffuseTransmissionColor);}#redgpu_endIf var specular_transmission=vec3(.0);#redgpu_if useKHR_materials_transmission if(transmissionParameter>.0){specular_transmission=getDirectSpecularBTDF(VdotN,NdotL_origin,NdotH,VdotH,LdotH,roughnessParameter,F,ior)*max(-NdotL_origin,.0);if(abs(ior-1.0)(.0);}}#redgpu_endIf let specular_weight=F*specularParameter;let total_diffuse=mix(diffuse_reflection,diffuse_transmission,diffuseTransmissionParameter);let dielectricPart=(SPEC_BRDF*specularParameter*NdotL)+mix((vec3(1.0)-specular_weight)*total_diffuse,specular_transmission,transmissionParameter);let metallicPart=SPEC_BRDF*NdotL;var result=mix(dielectricPart,metallicPart,metallicParameter);#redgpu_if useKHR_materials_sheen{let maxSheenColor=max(sheenColor.x,max(sheenColor.y,sheenColor.z));if(sheenRoughnessParameter>.0&&maxSheenColor>.001){let sheen_brdf=getDirectSheenBRDF(NdotL,VdotN,NdotH,sheenColor,sheenRoughnessParameter);let sheen_albedo_scaling=getSheenAlbedoScaling(maxSheenColor,getSheenCharlieE(VdotN,sheenRoughnessParameter));result=result*sheen_albedo_scaling+(sheen_brdf*NdotL);}}#redgpu_endIf #redgpu_if useKHR_materials_clearcoat if(clearcoatParameter>.0){let CLEARCOAT_BRDF=getDirectClearcoatBRDF(L,V,H,clearcoatNormal,clearcoatRoughnessParameter,LdotH);let coatF=getFresnel(max(dot(clearcoatNormal,V),.04),vec3(.04)).x*clearcoatParameter;result=CLEARCOAT_BRDF+(vec3(1.0)-coatF)*result;}#redgpu_endIf return result*dLight;}"));class PBRMaterial extends AUVTransformBaseMaterial{#Ia;#Aa;#La;#Ua;#ka;constructor(i){super(i,"PBR_MATERIAL",ki,2),this.initGPURenderInfos(),this.__packingList=[()=>{this.setupPackORMTexture(),this.setupPackedKHR_clearcoatTexture_transmission(),this.setupPackedKHR_diffuse_transmission(),this.setupPackedKHR_sheen(),this.setupPackedKHR_iridescence()}]}get packedKHR_clearcoatTexture_transmission(){return this.#ka}get packedKHR_iridescence(){return this.#Ua}get packedORMTexture(){return this.#Ia}get packedKHR_sheen(){return this.#La}get packedKHR_diffuse_transmission(){return this.#Aa}async setupPackORMTexture(){if(!this.occlusionTexture&&!this.metallicRoughnessTexture)return;this.#Ia||(this.#Ia=new PackedTexture(this.redGPUContext));const i=Math.max(this.occlusionTexture?.gpuTexture?.width||1,this.metallicRoughnessTexture?.gpuTexture?.width||1),g=Math.max(this.occlusionTexture?.gpuTexture?.height||1,this.metallicRoughnessTexture?.gpuTexture?.height||1);await this.#Ia.packing({r:this.occlusionTexture?.gpuTexture,g:this.metallicRoughnessTexture?.gpuTexture,b:this.metallicRoughnessTexture?.gpuTexture},i,g,"packedORMTexture")}async setupPackedKHR_clearcoatTexture_transmission(){this.#ka||(this.#ka=new PackedTexture(this.redGPUContext));const i=Math.max(this.KHR_clearcoatTexture?.gpuTexture?.width||1,this.KHR_clearcoatRoughnessTexture?.gpuTexture?.width||1),g=Math.max(this.KHR_clearcoatTexture?.gpuTexture?.height||1,this.KHR_clearcoatRoughnessTexture?.gpuTexture?.height||1),x=Math.max(this.KHR_transmissionTexture?.gpuTexture?.width||1,this.KHR_thicknessTexture?.gpuTexture?.width||1),v=Math.max(this.KHR_transmissionTexture?.gpuTexture?.height||1,this.KHR_thicknessTexture?.gpuTexture?.height||1),_=Math.max(i,x),y=Math.max(g,v);await this.#ka.packing({r:this.KHR_clearcoatTexture?.gpuTexture,g:this.KHR_clearcoatRoughnessTexture?.gpuTexture,b:this.KHR_transmissionTexture?.gpuTexture,a:this.KHR_thicknessTexture?.gpuTexture},_,y,"packedKHR_clearcoatTexture_transmission",{b:"r",a:"g"})}async setupPackedKHR_diffuse_transmission(){if(!this.KHR_diffuseTransmissionColorTexture&&!this.KHR_diffuseTransmissionTexture)return;this.#Aa||(this.#Aa=new PackedTexture(this.redGPUContext));const i=Math.max(this.KHR_diffuseTransmissionColorTexture?.gpuTexture?.width||1,this.KHR_diffuseTransmissionTexture?.gpuTexture?.width||1),g=Math.max(this.KHR_diffuseTransmissionColorTexture?.gpuTexture?.height||1,this.KHR_diffuseTransmissionTexture?.gpuTexture?.height||1);await this.#Aa.packing({r:this.KHR_diffuseTransmissionColorTexture?.gpuTexture,g:this.KHR_diffuseTransmissionColorTexture?.gpuTexture,b:this.KHR_diffuseTransmissionColorTexture?.gpuTexture,a:this.KHR_diffuseTransmissionTexture?.gpuTexture},i,g,"packedKHR_diffuse_transmission")}async setupPackedKHR_sheen(){if(!this.KHR_sheenColorTexture&&!this.KHR_sheenRoughnessTexture)return;this.#La||(this.#La=new PackedTexture(this.redGPUContext));const i=Math.max(this.KHR_sheenColorTexture?.gpuTexture?.width||1,this.KHR_sheenRoughnessTexture?.gpuTexture?.width||1),g=Math.max(this.KHR_sheenColorTexture?.gpuTexture?.height||1,this.KHR_sheenRoughnessTexture?.gpuTexture?.height||1);await this.#La.packing({r:this.KHR_sheenColorTexture?.gpuTexture,g:this.KHR_sheenColorTexture?.gpuTexture,b:this.KHR_sheenColorTexture?.gpuTexture,a:this.KHR_sheenRoughnessTexture?.gpuTexture},i,g,"packedKHR_sheen")}async setupPackedKHR_iridescence(){if(!this.KHR_iridescenceTexture&&!this.KHR_iridescenceThicknessTexture)return;this.#Ua||(this.#Ua=new PackedTexture(this.redGPUContext));const i=Math.max(this.KHR_iridescenceTexture?.gpuTexture?.width||1,this.KHR_iridescenceThicknessTexture?.gpuTexture?.width||1),g=Math.max(this.KHR_iridescenceTexture?.gpuTexture?.height||1,this.KHR_iridescenceThicknessTexture?.gpuTexture?.height||1);await this.#Ua.packing({r:this.KHR_iridescenceTexture?.gpuTexture,g:this.KHR_iridescenceThicknessTexture?.gpuTexture},i,g,"packedKHR_iridescence")}}definePositiveNumber(PBRMaterial,[{key:"emissiveStrength",value:1},{key:"normalScale",value:1}]);Ui.forEach(i=>{const{extensionName:g,textureList:x,useSampler:v}=i,{positiveNumberList:_,vec3List:y,vec4List:b}=i;g&&defineBoolean(PBRMaterial,[{key:`use${g}`,value:!1}]),((i,g)=>{i?.forEach(i=>{defineBoolean(PBRMaterial,[{key:`use${i.charAt(0).toUpperCase()}${i.substring(1)}`,value:!1}]),definePositiveNumber(PBRMaterial,[{key:`${i}_KHR_texture_transform_rotation`,value:0}]),defineBoolean(PBRMaterial,[{key:`use_${i}_KHR_texture_transform`,value:!1}]),defineVector2(PBRMaterial,[{key:`${i}_KHR_texture_transform_offset`},{key:`${i}_KHR_texture_transform_scale`,value:[1,1]}]),defineUint(PBRMaterial,[{key:`${i}_texCoord_index`,value:0}]),defineTexture(PBRMaterial,[{key:i}]),g&&defineSampler(PBRMaterial,[{key:`${i}Sampler`}])})})(x,!v),_?.forEach(i=>{definePositiveNumber(PBRMaterial,[i])}),y?.forEach(i=>{defineVector3(PBRMaterial,[i])}),b?.forEach(i=>{defineVector4(PBRMaterial,[i])})}),definePositiveNumber(PBRMaterial,[{key:"cutOff",value:0},{key:"KHR_materials_ior",value:1.5},{key:"KHR_dispersion",value:0}]),defineUint(PBRMaterial,[{key:"alphaBlend",value:0}]),defineBoolean(PBRMaterial,[{key:"doubleSided",value:!1},{key:"useCutOff",value:!1},{key:"useVertexColor",value:!1},{key:"useVertexTangent",value:!1},{key:"useKHR_materials_unlit",value:!1},{key:"useSSR",value:!0}]),Object.freeze(PBRMaterial);var Gi="struct InputData{@location(0)position:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,@location(3)uv1:vec2,@location(4)vertexColor_0:vec4,@location(5)vertexTangent:vec4,};",Oi="struct VertexOutput{@builtin(position)position:vec4,@location(0)vertexPosition:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,@location(3)uv1:vec2,@location(4)vertexColor_0:vec4,@location(5)vertexTangent:vec4,@location(7)currentClipPos:vec4,@location(8)prevClipPos:vec4,@location(10)localNodeScale_volumeScale:vec2,@location(11)combinedOpacity:f32,@location(12)motionVector:vec3,@location(13)shadowCoord:vec3,@location(14)@interpolate(flat)receiveShadow:f32,@location(15)@interpolate(flat)pickingId:vec4,};",Vi="struct InputData{@location(0)position:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,@location(3)vertexTangent:vec4,};",Ni="struct VertexOutput{@builtin(position)position:vec4,@location(0)vertexPosition:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,@location(3)vertexTangent:vec4,@location(7)currentClipPos:vec4,@location(8)prevClipPos:vec4,@location(11)combinedOpacity:f32,@location(12)motionVector:vec3,@location(13)shadowCoord:vec3,@location(14)@interpolate(flat)receiveShadow:f32,@location(15)@interpolate(flat)pickingId:vec4,};",Fi="#redgpu_include SYSTEM_UNIFORM;#redgpu_include shadow.getShadowCoord;#redgpu_include entryPoint.mesh.entryPointShadowVertex;#redgpu_include entryPoint.mesh.entryPointPickingVertex;#redgpu_include displacement.getDisplacementPosition;#redgpu_include systemStruct.meshVertexBasicUniform;const maxDistance:f32=1000.0;@group(1)@binding(0)varvertexUniforms:VertexUniforms;@group(1)@binding(1)var displacementTextureSampler:sampler;@group(1)@binding(2)var displacementTexture:texture_2d;@vertex fn main(inputData:InputData)->VertexOutput{var output:VertexOutput;#redgpu_if disableJitter{let u_projectionMatrix=systemUniforms.projection.noneJitterProjectionViewMatrix;}#redgpu_else{let u_projectionMatrix=systemUniforms.projection.projectionMatrix;}#redgpu_endIf let u_projectionViewMatrix=systemUniforms.projection.projectionViewMatrix;let u_noneJitterProjectionViewMatrix=systemUniforms.projection.noneJitterProjectionViewMatrix;let u_prevNoneJitterProjectionViewMatrix=systemUniforms.projection.prevNoneJitterProjectionViewMatrix;let u_resolution=systemUniforms.resolution;let u_camera=systemUniforms.camera;let u_viewMatrix=u_camera.viewMatrix;let u_cameraPosition=u_camera.cameraPosition;let u_matrixList=vertexUniforms.matrixList;let u_modelMatrix=u_matrixList.modelMatrix;let u_prevModelMatrix=u_matrixList.prevModelMatrix;let u_normalModelMatrix=u_matrixList.normalModelMatrix;let u_displacementScale=vertexUniforms.displacementScale;let u_useDisplacementTexture=vertexUniforms.useDisplacementTexture==1u;let u_receiveShadow=vertexUniforms.receiveShadow;let u_directionalLightCount=systemUniforms.directionalLightCount;let u_directionalLights=systemUniforms.directionalLights;let u_directionalLightProjectionViewMatrix=systemUniforms.directionalLightProjectionViewMatrix;let input_position=inputData.position;let input_position_vec4=vec4(input_position,1.0);let input_vertexNormal=inputData.vertexNormal;let input_uv=inputData.uv;let transformedUV=input_uv*vertexUniforms.uvTransform.zw+vertexUniforms.uvTransform.xy;var position:vec4;#redgpu_if useDisplacementTexture let tempPosition=u_modelMatrix*input_position_vec4;let distance=distance(tempPosition.xyz,u_cameraPosition);let maxMipLevel=f32(textureNumLevels(displacementTexture))-1.0;let targetMipLevel=clamp((distance/maxDistance)*maxMipLevel,.0,maxMipLevel);let displacedPosition=getDisplacementPosition(input_position,input_vertexNormal,displacementTexture,displacementTextureSampler,u_displacementScale,transformedUV,targetMipLevel);position=u_modelMatrix*vec4(displacedPosition,1.0);#redgpu_else position=u_modelMatrix*input_position_vec4;#redgpu_endIf let worldNormal=normalize((u_normalModelMatrix*vec4(input_vertexNormal,.0)).xyz);let normalPosition=vec4(worldNormal,.0);output.position=u_projectionViewMatrix*position;output.vertexPosition=position.xyz;output.vertexNormal=normalPosition.xyz;output.uv=transformedUV;let transformedTangentXYZ=(u_normalModelMatrix*vec4(inputData.vertexTangent.xyz,.0)).xyz;output.vertexTangent=vec4(normalize(transformedTangentXYZ),inputData.vertexTangent.w);output.combinedOpacity=vertexUniforms.combinedOpacity;#redgpu_if receiveShadow{output.shadowCoord=getShadowCoord(position.xyz,u_directionalLightProjectionViewMatrix);output.receiveShadow=vertexUniforms.receiveShadow;}#redgpu_endIf{output.currentClipPos=u_noneJitterProjectionViewMatrix*position;output.prevClipPos=u_prevNoneJitterProjectionViewMatrix*u_prevModelMatrix*input_position_vec4;}return output;}";const Hi={SHADER_INFO_PBR:parseWGSL("MESH_PBR",[Gi,Oi,"#redgpu_include SYSTEM_UNIFORM;#redgpu_include shadow.getShadowCoord;#redgpu_include entryPoint.mesh.entryPointShadowVertex;#redgpu_include entryPoint.mesh.entryPointPickingVertex;#redgpu_include systemStruct.meshVertexBasicUniform;@group(1)@binding(0)varvertexUniforms:VertexUniforms;@group(1)@binding(1)var displacementTextureSampler:sampler;@group(1)@binding(2)var displacementTexture:texture_2d;@vertex fn main(inputData:InputData)->VertexOutput{var output:VertexOutput;let input_position=inputData.position;let input_position_vec4=vec4(input_position,1.0);let input_vertexNormal=inputData.vertexNormal;let u_projectionMatrix=systemUniforms.projection.projectionMatrix;let u_projectionViewMatrix=systemUniforms.projection.projectionViewMatrix;let u_noneJitterProjectionViewMatrix=systemUniforms.projection.noneJitterProjectionViewMatrix;let u_prevNoneJitterProjectionViewMatrix=systemUniforms.projection.prevNoneJitterProjectionViewMatrix;let u_resolution=systemUniforms.resolution;let u_camera=systemUniforms.camera;let u_viewMatrix=u_camera.viewMatrix;let u_cameraPosition=u_camera.cameraPosition;let u_matrixList=vertexUniforms.matrixList;let u_localMatrix=u_matrixList.localMatrix;let u_modelMatrix=u_matrixList.modelMatrix;let u_normalModelMatrix=u_matrixList.normalModelMatrix;let u_prevModelMatrix=u_matrixList.prevModelMatrix;let u_receiveShadow=vertexUniforms.receiveShadow;let u_directionalLightCount=systemUniforms.directionalLightCount;let u_directionalLights=systemUniforms.directionalLights;let u_directionalLightProjectionViewMatrix=systemUniforms.directionalLightProjectionViewMatrix;var position:vec4;var normalPosition:vec4;position=u_modelMatrix*input_position_vec4;normalPosition=u_normalModelMatrix*vec4(input_vertexNormal,.0);output.position=u_projectionViewMatrix*position;output.vertexPosition=position.xyz;output.vertexNormal=normalize(normalPosition.xyz);output.uv=inputData.uv;output.uv1=inputData.uv1;output.vertexColor_0=inputData.vertexColor_0;let transformedTangentXYZ=(u_normalModelMatrix*vec4(inputData.vertexTangent.xyz,.0)).xyz;output.vertexTangent=vec4(normalize(transformedTangentXYZ),inputData.vertexTangent.w);#redgpu_if receiveShadow{output.shadowCoord=getShadowCoord(position.xyz,u_directionalLightProjectionViewMatrix);output.receiveShadow=vertexUniforms.receiveShadow;}#redgpu_endIf{output.currentClipPos=u_noneJitterProjectionViewMatrix*position;output.prevClipPos=u_prevNoneJitterProjectionViewMatrix*u_prevModelMatrix*input_position_vec4;}let nodeScaleX=length(u_localMatrix[0].xyz);let nodeScaleY=length(u_localMatrix[1].xyz);let nodeScaleZ=length(u_localMatrix[2].xyz);let volumeScaleX=length(u_modelMatrix[0].xyz);let volumeScaleY=length(u_modelMatrix[1].xyz);let volumeScaleZ=length(u_modelMatrix[2].xyz);output.localNodeScale_volumeScale=vec2(pow(nodeScaleX*nodeScaleY*nodeScaleZ,1.0/3.0),pow(volumeScaleX*volumeScaleY*volumeScaleZ,1.0/3.0));return output;}"].join("\n")),SHADER_INFO_BASIC:parseWGSL("MESH_BASIC",[Vi,Ni,Fi].join("\n")),SHADER_INFO_ONLY_FRAGMENT_PBR:parseWGSL("MESH_ONLY_FRAGMENT_PBR",[Vi,Oi,Fi].join("\n")),SHADER_INFO_ONLY_VERTEX_PBR:parseWGSL("MESH_ONLY_VERTEX_PBR",[Gi,Ni,Fi].join("\n"))};Object.freeze(Hi);const{SHADER_INFO_PBR:zi,SHADER_INFO_BASIC:$i,SHADER_INFO_ONLY_FRAGMENT_PBR:ji,SHADER_INFO_ONLY_VERTEX_PBR:Ki}=Hi,Xi=zi.shaderSourceVariant.getVariant("none"),qi=$i.shaderSourceVariant.getVariant("none"),Yi=ji.shaderSourceVariant.getVariant("none"),Wi=Ki.shaderSourceVariant.getVariant("none");class LODManager{#Ga=[];#Oa;#Va=!1;constructor(i,g){"InstancingMesh"===i.constructor.name&&(this.#Va=!0),this.#Oa=g}get LODList(){return[...this.#Ga]}addLOD(i,g,x){if(validatePositiveNumberRange(i,1),this.#Ga.length>=8)throw new Error("Maximum of 8 LOD levels allowed.");if(this.#Ga.some(g=>g.distance===i))throw new Error(`LOD with distance ${i} already exists.`);const v="PBR"===g.vertexBuffer.interleavedStruct.label,_=x instanceof PBRMaterial,y={distance:i,distanceSquared:i*i,geometry:g,material:x,geometryIsPBR:v,materialIsPBR:_};this.#Ga.push({...y,...this.#Va?{}:{label:`vertex_${v?"pbr":"noPbr"}_fragment_${_?"pbr":"noPbr"}`,source:this.#Na(g,x)}}),this.#Ga.sort((i,g)=>i.distance-g.distance),this.#Oa?.()}getLOD(i){for(const g of this.#Ga)if(ig.distance!==i),this.#Oa?.()}clearLOD(){this.#Ga.length=0,this.#Oa?.()}#Na(i,g){const x="PBR"===i.vertexBuffer.interleavedStruct.label,v=g instanceof PBRMaterial;return x&&v?Xi:!x&&v?Yi:x&&!v?Wi:qi}}const Zi=Object.values(Er);class DepthStencilState{#Fa;#z="depth32float";#Ha=["r8unorm","r8snorm","r8uint","r8sint","r16uint","r16sint","r16float","rg8unorm","rg8snorm","rg8uint","rg8sint","r32uint","r32sint","r32float","rg16uint","rg16sint","rg16float","rgba8unorm","rgba8unorm-srgb","rgba8snorm","rgba8uint","rgba8sint","bgra8unorm","bgra8unorm-srgb","rgb9e5ufloat","rgb10a2uint","rgb10a2unorm","rg11b10ufloat","rg32uint","rg32sint","rg32float","rgba16uint","rgba16sint","rgba16float","rgba32uint","rgba32sint","rgba32float","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"];#za=!0;#$a=Er.LESS_EQUAL;#ja;#Ka;#Xa;#qa;#Ya=1;#Wa=1;#Za=1;constructor(i){this.#Fa=i}get format(){return this.#z}set format(i){this.#Ha.includes(i)?(this.#z=i,this.#Fa.dirtyPipeline=!0):consoleAndThrowError(`Invalid value for format. Received ${i}. Expected one of: ${this.#Ha.join(", ")}`)}get depthWriteEnabled(){return this.#za}set depthWriteEnabled(i){this.#za=i,this.#Fa.dirtyPipeline=!0}get depthCompare(){return this.#$a}set depthCompare(i){Zi.includes(i)?(this.#$a=i,this.#Fa.dirtyPipeline=!0):consoleAndThrowError(`Invalid value for depthCompare. Received ${i}. Expected one of: ${Zi.join(", ")}`)}get stencilFront(){return this.#ja}set stencilFront(i){this.#ja=i,this.#Fa.dirtyPipeline=!0}get stencilBack(){return this.#Ka}set stencilBack(i){this.#Ka=i,this.#Fa.dirtyPipeline=!0}get stencilReadMask(){return this.#Xa}set stencilReadMask(i){this.#Xa=i,this.#Fa.dirtyPipeline=!0}get stencilWriteMask(){return this.#qa}set stencilWriteMask(i){this.#qa=i,this.#Fa.dirtyPipeline=!0}get depthBias(){return this.#Ya}set depthBias(i){this.#Ya=i,this.#Fa.dirtyPipeline=!0}get depthBiasSlopeScale(){return this.#Wa}set depthBiasSlopeScale(i){this.#Wa=i,this.#Fa.dirtyPipeline=!0}get depthBiasClamp(){return this.#Za}set depthBiasClamp(i){this.#Za=i,this.#Fa.dirtyPipeline=!0}get state(){let i=!1;if(this.#Fa?.primitiveState){const{topology:g}=this.#Fa.primitiveState;i=g===Ei.TRIANGLE_LIST||g===Ei.TRIANGLE_STRIP}return{format:this.#z,depthWriteEnabled:this.#za,depthCompare:this.#$a,stencilFront:this.#ja,stencilBack:this.#Ka,stencilReadMask:this.#Xa,stencilWriteMask:this.#qa,depthBias:i?this.#Ya:null,depthBiasSlopeScale:i?this.#Wa:null,depthBiasClamp:i?this.#Za:null}}}const Ji={NONE:"none",FRONT:"front",BACK:"back"};Object.freeze(Ji);const Qi={CW:"cw",CCW:"ccw"};Object.freeze(Qi);const en={UINT16:"uint16",UINT32:"uint32"};Object.freeze(en);const tn=Object.values(en),rn=Object.values(Qi),nn=Object.values(Ji),an=["point-list","line-list","line-strip","triangle-list","triangle-strip"];class PrimitiveState{dirtyPipeline=!1;state;#Fa;#Ja=Ei.TRIANGLE_LIST;#Qa;#es=Qi.CCW;#ts=Ji.BACK;#rs=!1;constructor(i){this.#Fa=i,this.#Qt()}get topology(){return this.#Ja}set topology(i){an.includes(i)?(this.#Ja=i,this.#Qt()):consoleAndThrowError(`Invalid value for topology. Received ${i}. Expected one of: ${an.join(", ")}`)}get stripIndexFormat(){return this.#Qa}set stripIndexFormat(i){tn.includes(i)?(this.#Qa=i,this.#Qt()):consoleAndThrowError(`Invalid value for stripIndexFormat. Received ${i}. Expected one of: ${tn.join(", ")}`)}get frontFace(){return this.#es}set frontFace(i){rn.includes(i)?(this.#es=i,this.#Qt()):consoleAndThrowError(`Invalid value for frontFace. Received ${i}. Expected one of: ${rn.join(", ")}`)}get cullMode(){return this.#ts}set cullMode(i){nn.includes(i)?(this.#ts=i,this.#Qt()):consoleAndThrowError(`Invalid value for cullMode. Received ${i}. Expected one of: ${nn.join(", ")}`)}get unclippedDepth(){return this.#rs}set unclippedDepth(i){"boolean"==typeof i?(this.#rs=i,this.#Qt()):consoleAndThrowError(`Invalid type for unclippedDepth. Received ${typeof i}. Expected type: boolean.`)}#Qt(){this.state={topology:this.#Ja,stripIndexFormat:this.#Qa,frontFace:this.#es,cullMode:this.#ts,unclippedDepth:this.#rs},this.#Fa.dirtyPipeline=!0}}const sn=create$4(),on={x:0,y:0,z:0,w:0},getScreenPoint=(i,g)=>{"View3D"!==i?.constructor?.name&&consoleAndThrowError("allow only View3D instance"),identity$1(sn);const{noneJitterProjectionMatrix:x,rawCamera:v,pixelRectArray:_}=i;return multiply$4(sn,x,v.viewMatrix),multiply$4(sn,sn,g),on.z=sn[14],on.w=sn[15],on.x=.5*sn[12]/on.w+.5,on.y=.5*sn[13]/on.w+.5,[(_[0]+on.x*_[2])/window.devicePixelRatio,(_[1]+(1-on.y)*_[3])/window.devicePixelRatio]},un=create$4(),localToWorld=(i,g,x,v)=>(validateNumber(g),validateNumber(x),validateNumber(v),identity$1(un),translate(un,un,[g,x,v]),multiply$4(un,i,un),[un[12],un[13],un[14]]),cn=create$4(),hn=create$3(),worldToLocal=(i,g,x,v)=>(validateNumber(g),validateNumber(x),validateNumber(v),invert$1(cn,i),set$3(hn,g,x,v),transformMat4$2(hn,hn,cn),[hn[0],hn[1],hn[2]]);class Object3DContainer extends BaseObject{modelMatrix=create$4();#is=[];constructor(){super()}get children(){return this.#is}get numChildren(){return this.#is.length}contains(i){return this.#ns(i),this.#is.includes(i)}addChild(i){return this.#ns(i),this.#as(i)?(this.#is.push(i),i.dirtyTransform=!0,i):null}addChildAt(i,g){if(validateUintRange(g),this.#is.lengththis.#is.length)&&this.#as(i))return this.#is.splice(g,0,i),i.dirtyTransform=!0,this}getChildAt(i){if(validateUintRange(i),!(i>=this.#is.length||i<0))return this.#is[i]}getChildIndex(i){this.#ns(i);const g=this.#is.indexOf(i);return-1===g?-1:g}setChildIndex(i,g){this.#ns(i),validateUintRange(g);const x=this.#is.length,v=g>=x,_=this.#is.indexOf(i);-1!==_?v?consoleAndThrowError(`Invalid index. Index ${g} is out of bounds. Index should be between 0 and ${x-1}.`):(this.#is.splice(_,1),this.#is.splice(g,0,i)):consoleAndThrowError(`The provided is not a child of the Object3DContainer.: ${i}`)}swapChildren(i,g){if(this.#ns(i),this.#ns(g),i===g)return void consoleAndThrowError("Error: child1 and child2 are the same. Cannot swap a child with itself.");const x=this.#is.indexOf(i),v=this.#is.indexOf(g);-1!==x&&-1!==v||consoleAndThrowError(`Error: ${-1===x?"child1":"child2"} is not a child of this Object3DContainer.`),this.swapChildrenAt(x,v)}swapChildrenAt(i,g){validateUintRange(i),validateUintRange(g),i===g&&consoleAndThrowError("Error: index1 and index2 are identical. Cannot swap a child with itself.");const x=this.#is.length;(i>=x||g>=x)&&consoleAndThrowError(`Error: Both index1 and index2 should be less than the number of children. Provided index1: ${i}, index2: ${g}, number of children: ${x}`);let v=this.#is[i];this.#is[i]=this.#is[g],this.#is[g]=v}removeChild(i){this.#ns(i);const g=this.#is.indexOf(i);if(g>-1)return i.parent=null,this.#is.splice(g,1)[0];consoleAndThrowError("Error: Child not found within parent.")}removeChildAt(i){validateUintRange(i);const g=this.#is[i];if(g)return g.parent=null,this.#is.splice(i,1)[0];throw new Error(`Error: No child found at provided index: ${i}.`)}removeAllChildren(){let i=this.#is.length;for(;i--;)this.#is[i].parent=null;return this.#is.length=0,this}#ns(i){i instanceof Object3DContainer||consoleAndThrowError("allow only Object3DContainer instance.")}#as=i=>(this.#ns(i),i.parent?!!i.parent?.removeChild(i)&&(i.parent=this,!0):(i.parent=this,!0))}class MeshBase extends Object3DContainer{gpuRenderInfo;animationInfo={skinInfo:null,morphInfo:null,weightBuffer:null,jointBuffer:null,animationsList:null};gltfLoaderInfo;dirtyPipeline=!0;dirtyTransform=!0;dirtyOpacity=!0;modelMatrix=create$4();localMatrix=create$4();normalModelMatrix=create$4();#h;#f;#ss;#os;#us;constructor(i){super(),validateRedGPUContext(i),this.#h=i,this.#f=i.gpuDevice,this.#ss=new PrimitiveState(this),this.#os=new DepthStencilState(this)}get currentShaderModuleName(){return this.#us}set currentShaderModuleName(i){this.#us=i}get primitiveState(){return this.#ss}get depthStencilState(){return this.#os}get gpuDevice(){return this.#f}get redGPUContext(){return this.#h}worldToLocal(i,g,x){return worldToLocal(this.modelMatrix,i,g,x)}localToWorld(i,g,x){return localToWorld(this.modelMatrix,i,g,x)}getScreenPoint(i){return getScreenPoint(i,this.modelMatrix)}}const fn="shadow",dn="picking",createBasePipeline=(i,g,x,v)=>{const{redGPUContext:_}=i,{gpuDevice:y,resourceManager:b}=_,S=i.material.gpuRenderInfo;let w,L;switch(v){case fn:w="entryPointShadowVertex",L=`${g.label}_shadow_pipeline`;break;case dn:w="entryPointPickingVertex",L=`${g.label}_picking_pipeline`;break;default:w="main",L=`${g.label}_pipeline`}const k={module:g,entryPoint:w,buffers:i.vertexStateBuffers},H=[b.getGPUBindGroupLayout(ResourceManager.PRESET_GPUBindGroupLayout_System),x];v!==fn&&H.push(S.fragmentBindGroupLayout);const z={bindGroupLayouts:H,label:`${L}_${S.fragmentBindGroupLayout.label}`},q={label:L,layout:b.createGPUPipelineLayout(`${z.label}`,z),vertex:k,primitive:i.primitiveState.state};switch(v){case fn:q.depthStencil={depthWriteEnabled:!0,depthCompare:Er.LESS_EQUAL,format:"depth32float"};break;case dn:i.material&&(q.fragment={module:i.material.gpuRenderInfo.fragmentShaderModule,entryPoint:"entryPointPickingFragment",targets:[{format:navigator.gpu.getPreferredCanvasFormat()}]},q.depthStencil=i.depthStencilState.state);break;default:q.fragment=S.fragmentState,q.depthStencil=i.depthStencilState.state,q.multisample={count:_.antialiasingManager.useMSAA?4:1}}return y.createRenderPipeline(q)};const getBasicMeshVertexBindGroupDescriptor=(i,g=!1)=>{const{redGPUContext:x,gpuRenderInfo:v,material:_}=i,{resourceManager:y}=x,{vertexUniformBuffer:b,vertexBindGroupLayout:S}=v,{basicSampler:w,emptyBitmapTextureView:L,basicDisplacementSampler:k}=y,{gpuSampler:H}=w;return{layout:S,label:g?"VERTEX_BIND_GROUP_DESCRIPTOR_MESH_SKIN":"VERTEX_BIND_GROUP_DESCRIPTOR_MESH",entries:g?[{binding:0,resource:{buffer:b.gpuBuffer,offset:0,size:b.size}},{binding:1,resource:k.gpuSampler},{binding:2,resource:y.getGPUResourceBitmapTextureView(_?.displacementTexture)||L},{binding:3,resource:{buffer:i.animationInfo.skinInfo.vertexStorageBuffer,offset:0,size:i.animationInfo.skinInfo.vertexStorageBuffer.size}},{binding:4,resource:{buffer:i.animationInfo.skinInfo.prevVertexStorageBuffer,offset:0,size:i.animationInfo.skinInfo.prevVertexStorageBuffer.size}}]:[{binding:0,resource:{buffer:b.gpuBuffer,offset:0,size:b.size}},{binding:1,resource:k.gpuSampler},{binding:2,resource:y.getGPUResourceBitmapTextureView(_?.displacementTexture)||L}]}},{SHADER_INFO_PBR:mn,SHADER_INFO_BASIC:pn,SHADER_INFO_ONLY_FRAGMENT_PBR:gn,SHADER_INFO_ONLY_VERTEX_PBR:xn}=Hi,vn=mn.uniforms.vertexUniforms,_n=pn.uniforms.vertexUniforms,createMeshVertexShaderModule=i=>{const{material:g}=i;let x,v="basic";switch(g instanceof PBRMaterial&&i.animationInfo?.skinInfo?v="skin":i.createCustomMeshVertexShaderModule&&(v="custom"),v){case"basic":{const g=(i=>{const{geometry:g,material:x}=i,v="PBR"===g.vertexBuffer.interleavedStruct.label,_=x instanceof PBRMaterial,y=v&&!_,b=!v&&_;return v&&_?{name:"VERTEX_MODULE_MESH_PBR",shaderInfo:mn,source:mn.defaultSource,uniformStruct:vn}:b?{name:"VERTEX_MODULE_MESH_ONLY_FRAGMENT_PBR",shaderInfo:gn,source:gn.defaultSource,uniformStruct:_n}:y?{name:"VERTEX_MODULE_MESH_ONLY_VERTEX_PBR",shaderInfo:xn,source:xn.defaultSource,uniformStruct:_n}:{name:"VERTEX_MODULE_MESH",shaderInfo:pn,source:pn.defaultSource,uniformStruct:_n}})(i);x=i.createMeshVertexShaderModuleBASIC(g.name,g.shaderInfo,g.uniformStruct,g.source);break}case"skin":x=((i,g)=>{const{redGPUContext:x,currentShaderModuleName:v}=g,{resourceManager:_,gpuDevice:y}=x,{gpuRenderInfo:b}=g,S=`${g.animationInfo.skinInfo.joints.length}`,w=`${i}_${S}`,L="#redgpu_include SYSTEM_UNIFORM;#redgpu_include shadow.getShadowCoord;#redgpu_include shadow.getShadowClipPosition;#redgpu_include systemStruct.meshVertexBasicUniform;@group(1)@binding(0)varvertexUniforms:VertexUniforms;@group(1)@binding(1)var displacementTextureSampler:sampler;@group(1)@binding(2)var displacementTexture:texture_2d;@group(1)@binding(3)varvertexStorages:array>;@group(1)@binding(4)varprevVertexStorages:array>;struct InputDataSkin{@builtin(vertex_index)idx:u32,@location(0)position:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,@location(3)uv1:vec2,@location(4)vertexColor_0:vec4,@location(5)vertexTangent:vec4,};struct VertexOutput{@builtin(position)position:vec4,@location(0)vertexPosition:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,@location(3)uv1:vec2,@location(4)vertexColor_0:vec4,@location(5)vertexTangent:vec4,@location(7)currentClipPos:vec4,@location(8)prevClipPos:vec4,@location(10)localNodeScale_volumeScale:vec2,@location(11)combinedOpacity:f32,@location(12)motionVector:vec3,@location(13)shadowCoord:vec3,@location(14)@interpolate(flat)receiveShadow:f32,@location(15)@interpolate(flat)pickingId:vec4,};#redgpu_include systemStruct.OutputShadowData;@vertex fn main(inputData:InputDataSkin)->VertexOutput{var output:VertexOutput;let input_position=inputData.position;let input_position_vec4=vec4(input_position,1.0);let input_vertexNormal=inputData.vertexNormal;let u_projectionMatrix=systemUniforms.projection.projectionMatrix;let u_projectionViewMatrix=systemUniforms.projection.projectionViewMatrix;let u_noneJitterProjectionViewMatrix=systemUniforms.projection.noneJitterProjectionViewMatrix;let u_prevNoneJitterProjectionViewMatrix=systemUniforms.projection.prevNoneJitterProjectionViewMatrix;let u_resolution=systemUniforms.resolution;let u_camera=systemUniforms.camera;let u_viewMatrix=u_camera.viewMatrix;let u_cameraPosition=u_camera.cameraPosition;let u_matrixList=vertexUniforms.matrixList;let u_localMatrix=u_matrixList.localMatrix;let u_modelMatrix=u_matrixList.modelMatrix;let u_prevModelMatrix=u_matrixList.prevModelMatrix;let u_normalModelMatrix=u_matrixList.normalModelMatrix;let u_receiveShadow=vertexUniforms.receiveShadow;let u_directionalLightCount=systemUniforms.directionalLightCount;let u_directionalLights=systemUniforms.directionalLights;let u_directionalLightProjectionViewMatrix=systemUniforms.directionalLightProjectionViewMatrix;let skinMat=vertexStorages[inputData.idx];let prevSkinMat=prevVertexStorages[inputData.idx];let skinnedPosition=(skinMat*vec4(inputData.position,1.0));let position=u_modelMatrix*skinnedPosition;let skinnedNormal=(skinMat*vec4(input_vertexNormal,.0)).xyz;let transformedNormal=normalize((u_normalModelMatrix*vec4(skinnedNormal,.0)).xyz);output.vertexNormal=transformedNormal;let skinnedTangent=(skinMat*vec4(inputData.vertexTangent.xyz,.0)).xyz;let transformedTangentXYZ=(u_normalModelMatrix*vec4(skinnedTangent,.0)).xyz;output.vertexTangent=vec4(normalize(transformedTangentXYZ),inputData.vertexTangent.w);output.position=u_projectionViewMatrix*position;output.vertexPosition=position.xyz;output.uv=inputData.uv;output.uv1=inputData.uv1;output.vertexColor_0=inputData.vertexColor_0;#redgpu_if receiveShadow{output.shadowCoord=getShadowCoord(position.xyz,u_directionalLightProjectionViewMatrix);output.receiveShadow=vertexUniforms.receiveShadow;}#redgpu_endIf{output.currentClipPos=u_noneJitterProjectionViewMatrix*position;output.prevClipPos=u_prevNoneJitterProjectionViewMatrix*u_prevModelMatrix*(prevSkinMat*input_position_vec4);}let nodeScaleX=length(u_localMatrix[0].xyz);let nodeScaleY=length(u_localMatrix[1].xyz);let nodeScaleZ=length(u_localMatrix[2].xyz);let volumeScaleX=length(u_modelMatrix[0].xyz);let volumeScaleY=length(u_modelMatrix[1].xyz);let volumeScaleZ=length(u_modelMatrix[2].xyz);output.localNodeScale_volumeScale=vec2(pow(nodeScaleX*nodeScaleY*nodeScaleZ,1.0/3.0),pow(volumeScaleX*volumeScaleY*volumeScaleZ,1.0/3.0));return output;}@vertex fn entryPointShadowVertex(inputData:InputDataSkin)->OutputShadowData{var output:OutputShadowData;let u_directionalLightProjectionViewMatrix=systemUniforms.directionalLightProjectionViewMatrix;let u_modelMatrix=vertexUniforms.matrixList.modelMatrix;let input_position=inputData.position;let skinMat=vertexStorages[inputData.idx];let position=u_modelMatrix*skinMat*vec4(input_position,1.0);output.position=getShadowClipPosition(position.xyz,u_directionalLightProjectionViewMatrix);return output;}@vertex fn entryPointPickingVertex(inputData:InputDataSkin)->VertexOutput{var output:VertexOutput;let u_projectionViewMatrix=systemUniforms.projection.projectionViewMatrix;let u_modelMatrix=vertexUniforms.matrixList.modelMatrix;let skinMat=vertexStorages[inputData.idx];let position=u_modelMatrix*skinMat*vec4(inputData.position,1.0);output.position=u_projectionViewMatrix*position;output.pickingId=unpack4x8unorm(vertexUniforms.pickingId);return output;}",k={code:L};return v===w?_.getGPUShaderModule(w):(k.code=L.replaceAll("#JOINT_NUM",S),b.vertexUniformInfo=parseWGSL("MESH_VERTEX_PBR_SKIN",k.code).uniforms.vertexUniforms,g.animationInfo.skinInfo?(createMeshVertexUniformBuffers(g,!0),g.animationInfo.skinInfo.vertexStorageInfo=parseWGSL("MESH_VERTEX_PBR_SKIN",k.code).storage.vertexStorages,g.animationInfo.skinInfo.vertexStorageBuffer=y.createBuffer({size:16*g.geometry.vertexBuffer.vertexCount*4,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST}),g.animationInfo.skinInfo.prevVertexStorageBuffer=y.createBuffer({size:16*g.geometry.vertexBuffer.vertexCount*4,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST}),b.vertexUniformBindGroup=x.gpuDevice.createBindGroup(getBasicMeshVertexBindGroupDescriptor(g,!0))):(createMeshVertexUniformBuffers(g),b.vertexUniformBindGroup=x.gpuDevice.createBindGroup(getBasicMeshVertexBindGroupDescriptor(g))),g.gpuRenderInfo.vertexShaderModule=_.createGPUShaderModule(w,k),g.gpuRenderInfo.vertexShaderModule)})("VERTEX_MODULE_MESH_PBR_SKIN",i);break;case"custom":x=i.createCustomMeshVertexShaderModule()}return i.currentShaderModuleName=x.label,x},updateMeshDirtyPipeline=(i,g)=>{const{material:x,gpuRenderInfo:v,redGPUContext:_}=i,{resourceManager:y}=_;i.dirtyTransform=!0,x.dirtyPipeline&&x._updateFragmentState();const b=createMeshVertexShaderModule(i),S=y.getGPUBindGroupLayout(i.animationInfo.skinInfo?ResourceManager.PRESET_VERTEX_GPUBindGroupLayout_SKIN:ResourceManager.PRESET_VERTEX_GPUBindGroupLayout);v.vertexShaderModule=b,v.pipeline=createBasePipeline(i,b,S),v.shadowPipeline=null,v.pickingPipeline=null;const{vertexUniformInfo:w}=i.gpuRenderInfo,{members:L}=w;for(const g in L)"pickingId"!==g&&"pixelSize"!==g&&(i[g]=i[g]);i.gpuRenderInfo.vertexUniformInfo.members.pickingId&&i.gpuRenderInfo.vertexUniformBuffer.writeOnlyBuffer(i.gpuRenderInfo.vertexUniformInfo.members.pickingId,i.pickingId),x.dirtyPipeline=!1,i.dirtyPipeline=!1,g&&g.renderResults.numDirtyPipelines++};class VertexGPURenderInfo{vertexShaderModule;vertexShaderSourceVariant;vertexShaderVariantConditionalBlocks;vertexStructInfo;vertexUniformInfo;vertexBindGroupLayout;vertexUniformBindGroup;vertexUniformBuffer;pipeline;shadowPipeline;pickingPipeline;constructor(i,g,x,v,_,y,b,S,w,L){this.vertexShaderModule=i,this.vertexShaderSourceVariant=g,this.vertexShaderVariantConditionalBlocks=x,this.vertexUniformInfo=v,this.vertexBindGroupLayout=_,this.vertexUniformBindGroup=b,this.vertexUniformBuffer=y,this.pipeline=S,this.shadowPipeline=w,this.pickingPipeline=L}}Object.freeze(VertexGPURenderInfo);const yn="VERTEX_MODULE_MESH_PBR_SKIN",bn=Math.PI/180,Sn=3.141592653589793,Tn=6.283185307179586,wn=.225,Mn=1.27323954,Pn=.405284735,Rn=1.5707963267948966,Cn=new Float32Array(1),Bn=new Float32Array(4),Dn=new Float32Array([0,1,0]);class Mesh extends MeshBase{castShadow=!1;dirtyLOD=!1;passFrustumCulling=!0;createCustomMeshVertexShaderModule;#ls;#cs;#wi=0;#Mi=0;#Pi=0;#hs=new Float32Array([0,0,0]);#fs=0;#ds=0;#ms=0;#ps;#gs=1;#xs=1;#vs=1;#_s=new Float32Array([1,1,1]);#ys=0;#bs=0;#Ss=0;#Ts=new Float32Array([0,0,0]);#ws={};#Ms=0;#Ps=!1;#Rs=1;#Cs;#Bs=!1;#Ds;#Es;#Is;#As;#Ls;#Us=[];#ks=[];#Gs;#Os=null;#Vs=[];#Ns=null;#Fs=!0;#Hs=!0;#zs;#$s;#js;#Ks=[];#Xs=-1;constructor(i,g,x,v){super(i),v&&(this.name=v),this._geometry=g,this._material=x,this.#ps=uuidToUint(this.uuid),this.#Ns=DrawBufferManager.getInstance(i),this.#qs(),this.#js=new LODManager(this,()=>{this.dirtyLOD=!0})}get LODManager(){return this.#js}get enableDebugger(){return this.#Bs}set enableDebugger(i){this.#Bs=i,i&&!this.#Cs&&(this.#Cs=new DrawDebuggerMesh(this.redGPUContext,this))}get drawDebugger(){return this.#Cs}_material;get material(){return this._material}set material(i){this._material=i,this.dirtyPipeline=!0,"blendMode"in this&&(this.blendMode=this.blendMode)}_geometry;get geometry(){return this._geometry}set geometry(i){this._geometry=i,this.dirtyPipeline=!0,this.dirtyTransform=!0}get opacity(){return this.#Rs}set opacity(i){validatePositiveNumberRange(i,0,1),this.#Rs=i,this.dirtyOpacity=!0}get ignoreFrustumCulling(){return this.#Ps}set ignoreFrustumCulling(i){this.#Ps=i}get pickingId(){return this.#ps}get events(){return this.#ws}get vertexStateBuffers(){return this._geometry.gpuRenderInfo.buffers}get parent(){return this.#cs}set parent(i){this.#cs=i}get pivotX(){return this.#fs}set pivotX(i){this.#fs=i,this.dirtyTransform=!0}get pivotY(){return this.#ds}set pivotY(i){this.#ds=i,this.dirtyTransform=!0}get pivotZ(){return this.#ms}set pivotZ(i){this.#ms=i,this.dirtyTransform=!0}get x(){return this.#wi}set x(i){this.#wi=this.#hs[0]=i,this.dirtyTransform=!0}get y(){return this.#Mi}set y(i){this.#Mi=this.#hs[1]=i,this.dirtyTransform=!0}get z(){return this.#Pi}set z(i){this.#Pi=this.#hs[2]=i,this.dirtyTransform=!0}get position(){return this.#hs}get scaleX(){return this.#gs}set scaleX(i){this.#gs=this.#_s[0]=i,this.dirtyTransform=!0}get scaleY(){return this.#xs}set scaleY(i){this.#xs=this.#_s[1]=i,this.dirtyTransform=!0}get scaleZ(){return this.#vs}set scaleZ(i){this.#vs=this.#_s[2]=i,this.dirtyTransform=!0}get scale(){return this.#_s}get rotationX(){return this.#ys}set rotationX(i){this.#ys=this.#Ts[0]=i%360,this.dirtyTransform=!0}get rotationY(){return this.#bs}set rotationY(i){this.#bs=this.#Ts[1]=i%360,this.dirtyTransform=!0}get rotationZ(){return this.#Ss}set rotationZ(i){this.#Ss=this.#Ts[2]=i%360,this.dirtyTransform=!0}get rotation(){return this.#Ts}get boundingOBB(){return this.#Es&&!this.dirtyTransform||(this.#Es=null,this.#Ds=null,this.#Es=calculateMeshOBB(this)),this.#Es}get boundingAABB(){return this.#Ds&&!this.dirtyTransform||(this.#Es=null,this.#Ds=null,this.#Ds=calculateMeshAABB(this)),this.#Ds}get combinedBoundingAABB(){return calculateMeshCombinedAABB(this)}setEnableDebuggerRecursively(i=!1){"enableDebugger"in this&&(this.enableDebugger=i),this.children&&this.children.forEach(g=>{g.setEnableDebuggerRecursively(i)})}setCastShadowRecursively(i=!1){"castShadow"in this&&(this.castShadow=i),this.children&&this.children.forEach(g=>{g.setCastShadowRecursively(i)})}setReceiveShadowRecursively(i=!1){"receiveShadow"in this&&(this.receiveShadow=i),this.children&&this.children.forEach(g=>{g.setReceiveShadowRecursively(i)})}setIgnoreFrustumCullingRecursively(i=!1){"ignoreFrustumCulling"in this&&(this.ignoreFrustumCulling=i),this.children&&this.children.forEach(g=>{g.setIgnoreFrustumCullingRecursively(i)})}getCombinedOpacity(){if(this.is2DMeshType){const i=this.parent;return this.#Rs*(i?.getCombinedOpacity?i.getCombinedOpacity():1)}return 1}addListener(i,g){this.#ws[i]=g,this.#Ms=Object.keys(this.#ws).length}lookAt(i,g,x){let v=[],_=[];v[0]=i,v[1]=g,v[2]=x,identity$1(this.localMatrix),targetTo(this.localMatrix,[this.#wi,this.#Mi,this.#Pi],v,Dn),_=mat4ToEuler(this.localMatrix,[]),this.rotationX=180*_[0]/Math.PI,this.rotationY=180*_[1]/Math.PI,this.rotationZ=180*_[2]/Math.PI}setScale(i,g,x){g=g??i,x=x??i;const v=this.#_s;this.#gs=v[0]=i,this.#xs=v[1]=g,this.#vs=v[2]=x,this.dirtyTransform=!0}setPosition(i,g,x){g=g??i,x=x??i;const v=this.#hs;this.#wi=v[0]=i,this.#Mi=v[1]=g,this.#Pi=v[2]=x,this.dirtyTransform=!0}setRotation(i,g,x){g=g??i,x=x??i;const v=this.#Ts;this.#ys=v[0]=i,this.#bs=v[1]=g,this.#Ss=v[2]=x,this.dirtyTransform=!0}clone(){const i=new Mesh(this.redGPUContext,this._geometry,this._material);i.setPosition(this.#wi,this.#Mi,this.#Pi),i.setRotation(this.#ys,this.#bs,this.#Ss),i.setScale(this.#gs,this.#xs,this.#vs);let g=this.children.length;for(;g--;)i.addChild(this.children[g].clone());return i}render(i){const{redGPUContext:g}=this,{view:x,isScene2DMode:v,frustumPlanes:_,dirtyVertexUniformFromMaterial:y,useDistanceCulling:b,cullingDistanceSquared:S}=i,{antialiasingManager:w,gpuDevice:L}=g,{scene:k}=x,{shadowManager:H}=k,{directionalShadowManager:z}=H,{pickingManager:q}=x,{castingList:W}=z,be=this._geometry,je=this._material,{uuid:Ke}=je||{};let Xe,Ye,Ze=this.dirtyPipeline;const{skinInfo:Je}=this.animationInfo;if(v&&(this.#Pi=0,this.#ms=0,this.depthStencilState.depthWriteEnabled&&(this.depthStencilState.depthWriteEnabled=!1)),this.dirtyTransform){Xe=!0,this.#Fs=!0,this.#Hs=!0;{const i=this.parent,g=this.localMatrix;let x,_,y,b,S,w,L,k,H,z,q,W,be,je,Ke,Xe,Ye,Ze,Je,Qe,et,tt,it,ft,pt,xt,vt,yt,bt,St,Tt,wt,Mt,Pt,Rt,Ct,Bt,Dt,Et;g[12]=this.#wi,g[13]=this.#Mi,g[14]=this.#Pi,g[15]=1,x=this.#ys*bn,_=this.#bs*bn,y=this.#Ss*bn,it=1,ft=0,pt=0,vt=0,yt=1,bt=0,Tt=0,wt=0,Mt=1,Et=x%Tn,Et<-Sn?Et+=Tn:Et>Sn&&(Et-=Tn),Et=Et<0?Mn*Et+Pn*Et*Et:Mn*Et-Pn*Et*Et,b=Et<0?wn*(Et*-Et-Et)+Et:wn*(Et*Et-Et)+Et,Et=(x+Rn)%Tn,Et<-Sn?Et+=Tn:Et>Sn&&(Et-=Tn),Et=Et<0?Mn*Et+Pn*Et*Et:Mn*Et-Pn*Et*Et,L=Et<0?wn*(Et*-Et-Et)+Et:wn*(Et*Et-Et)+Et,Et=_%Tn,Et<-Sn?Et+=Tn:Et>Sn&&(Et-=Tn),Et=Et<0?Mn*Et+Pn*Et*Et:Mn*Et-Pn*Et*Et,S=Et<0?wn*(Et*-Et-Et)+Et:wn*(Et*Et-Et)+Et,Et=(_+Rn)%Tn,Et<-Sn?Et+=Tn:Et>Sn&&(Et-=Tn),Et=Et<0?Mn*Et+Pn*Et*Et:Mn*Et-Pn*Et*Et,k=Et<0?wn*(Et*-Et-Et)+Et:wn*(Et*Et-Et)+Et,Et=y%Tn,Et<-Sn?Et+=Tn:Et>Sn&&(Et-=Tn),Et=Et<0?Mn*Et+Pn*Et*Et:Mn*Et-Pn*Et*Et,w=Et<0?wn*(Et*-Et-Et)+Et:wn*(Et*Et-Et)+Et,Et=(y+Rn)%Tn,Et<-Sn?Et+=Tn:Et>Sn&&(Et-=Tn),Et=Et<0?Mn*Et+Pn*Et*Et:Mn*Et-Pn*Et*Et,H=Et<0?wn*(Et*-Et-Et)+Et:wn*(Et*Et-Et)+Et,je=k*H,Ke=L*w+b*S*H,Xe=b*w-L*S*H,Ye=-k*w,Ze=L*H-b*S*w,Je=b*H+L*S*w,Qe=S,et=-b*k,tt=L*k;let It=this.#gs,At=this.#xs,Lt=this.#vs;if(this.renderTextureWidth&&(It*=this.renderTextureWidth,At*=this.renderTextureHeight),g[0]=je*It,g[1]=Ke*It,g[2]=Xe*It,g[3]=0,g[4]=Ye*At,g[5]=Ze*At,g[6]=Je*At,g[7]=0,g[8]=Qe*Lt,g[9]=et*Lt,g[10]=tt*Lt,g[11]=0,(this.#fs||this.#ds||this.#ms)&&(it=g[0],ft=g[1],pt=g[2],xt=g[3],vt=g[4],yt=g[5],bt=g[6],St=g[7],Tt=g[8],wt=g[9],Mt=g[10],Pt=g[11],Rt=g[12],Ct=g[13],Bt=g[14],Dt=g[15],z=1,q=0,W=0,be=0,g[0]=z*it+q*vt+W*Tt+be*Rt,g[1]=z*ft+q*yt+W*wt+be*Ct,g[2]=z*pt+q*bt+W*Mt+be*Bt,g[3]=z*xt+q*St+W*Pt+be*Dt,z=0,q=1,W=0,be=0,g[4]=z*it+q*vt+W*Tt+be*Rt,g[5]=z*ft+q*yt+W*wt+be*Ct,g[6]=z*pt+q*bt+W*Mt+be*Bt,g[7]=z*xt+q*St+W*Pt+be*Dt,z=0,q=0,W=1,be=0,g[8]=z*it+q*vt+W*Tt+be*Rt,g[9]=z*ft+q*yt+W*wt+be*Ct,g[10]=z*pt+q*bt+W*Mt+be*Bt,g[11]=z*xt+q*St+W*Pt+be*Dt,v?i?.modelMatrix?(z=-this.#fs,q=-this.#ds,W=-this.#ms,be=1):(z=-this.#fs/x,q=-this.#ds/_,W=-this.#ms,be=1):(z=-this.#fs,q=-this.#ds,W=-this.#ms,be=1),g[12]=z*it+q*vt+W*Tt+be*Rt,g[13]=z*ft+q*yt+W*wt+be*Ct,g[14]=z*pt+q*bt+W*Mt+be*Bt,g[15]=z*xt+q*St+W*Pt+be*Dt),i?.modelMatrix){const g=i.modelMatrix,x=this.localMatrix,v=this.modelMatrix,_=g[0],y=g[1],b=g[2],S=g[3],w=g[4],L=g[5],k=g[6],H=g[7],z=g[8],q=g[9],W=g[10],be=g[11],je=g[12],Ke=g[13],Xe=g[14],Ye=g[15];let Ze=x[0],Je=x[1],Qe=x[2],et=x[3];v[0]=Ze*_+Je*w+Qe*z+et*je,v[1]=Ze*y+Je*L+Qe*q+et*Ke,v[2]=Ze*b+Je*k+Qe*W+et*Xe,v[3]=Ze*S+Je*H+Qe*be+et*Ye,Ze=x[4],Je=x[5],Qe=x[6],et=x[7],v[4]=Ze*_+Je*w+Qe*z+et*je,v[5]=Ze*y+Je*L+Qe*q+et*Ke,v[6]=Ze*b+Je*k+Qe*W+et*Xe,v[7]=Ze*S+Je*H+Qe*be+et*Ye,Ze=x[8],Je=x[9],Qe=x[10],et=x[11],v[8]=Ze*_+Je*w+Qe*z+et*je,v[9]=Ze*y+Je*L+Qe*q+et*Ke,v[10]=Ze*b+Je*k+Qe*W+et*Xe,v[11]=Ze*S+Je*H+Qe*be+et*Ye,Ze=x[12],Je=x[13],Qe=x[14],et=x[15],v[12]=Ze*_+Je*w+Qe*z+et*je,v[13]=Ze*y+Je*L+Qe*q+et*Ke,v[14]=Ze*b+Je*k+Qe*W+et*Xe,v[15]=Ze*S+Je*H+Qe*be+et*Ye}else{const{modelMatrix:i,localMatrix:g}=this;i[0]=g[0],i[1]=g[1],i[2]=g[2],i[3]=g[3],i[4]=g[4],i[5]=g[5],i[6]=g[6],i[7]=g[7],i[8]=g[8],i[9]=g[9],i[10]=g[10],i[11]=g[11],i[12]=g[12],i[13]=g[13],i[14]=g[14],i[15]=g[15]}}be||(this.#Hs=!1),this.dirtyTransform=!1,this.#Ds=null,this.#Es=null}if(w.useTAA&&this.#zs){const{gpuRenderInfo:i}=this,{vertexUniformBuffer:x,vertexUniformInfo:v}=i,{members:_}=v,{members:y}=_.matrixList;this.#Is&&y.prevModelMatrix&&(this.#zs.set(this.#Is,y.prevModelMatrix.uniformOffsetForData/Float32Array.BYTES_PER_ELEMENT),this.#Hs||g.gpuDevice.queue.writeBuffer(x.gpuBuffer,y.prevModelMatrix.uniformOffset,this.#Is));{this.#Is||(this.#Is=new Float32Array(16));const i=this.#Is,g=this.modelMatrix;i[0]=g[0],i[1]=g[1],i[2]=g[2],i[3]=g[3],i[4]=g[4],i[5]=g[5],i[6]=g[6],i[7]=g[7],i[8]=g[8],i[9]=g[9],i[10]=g[10],i[11]=g[11],i[12]=g[12],i[13]=g[13],i[14]=g[14],i[15]=g[15]}}else this.#Is=null;let Qe=this.passFrustumCulling=!0,et=0;const tt=this.#js.LODList,it=tt.length;if(b&&be||this.#js.LODList.length){const{rawCamera:i}=x,g=this.boundingAABB,v=i.x-g.centerX,_=i.y-g.centerY,y=i.z-g.centerZ;et=v*v+_*_+y*y}if(b&&be){const i=this.boundingAABB.geometryRadius;et>S+i*i&&(Qe=!1)}if(_&&Qe&&!this.#Ps){const{rawCamera:i}=x,g=this.boundingAABB;if("IsometricController"===i.constructor.name){const{centerX:x,centerY:v,centerZ:_,geometryRadius:y}=g,b=i,{left:S,right:w,top:L,bottom:k,nearClipping:H,farClipping:z}=b,{x:q,y:W,z:be}=b;{const i=x-q,g=v-W,b=_-be,je=45*(Math.PI/180),Ke=Math.cos(je),Xe=Math.sin(je),Ye=i*Ke+b*Xe,Ze=-i*Xe+b*Ke;(Ye+yw||g+yL||Ze+yz)&&(Qe=!1)}}else{const i=_[0],x=_[1],v=_[2],y=_[3],b=_[4],S=_[5],w=g.centerX,L=g.centerY,k=g.centerZ,H=g.geometryRadius,z=1;(i[0]*w+i[1]*L+i[2]*k+i[3]<=-H-z||x[0]*w+x[1]*L+x[2]*k+x[3]<=-H-z||v[0]*w+v[1]*L+v[2]*k+v[3]<=-H-z||y[0]*w+y[1]*L+y[2]*k+y[3]<=-H-z||b[0]*w+b[1]*L+b[2]*k+b[3]<=-H-z||S[0]*w+S[1]*L+S[2]*k+S[3]<=-H-z)&&(Qe=!1)}}Qe&&(this.gltfLoaderInfo?.activeAnimations?.length&&(i.animationList[i.animationList.length]=this.gltfLoaderInfo?.activeAnimations),Je&&(this.currentShaderModuleName.includes(yn)||(Ze=!0),this.currentShaderModuleName===`${yn}_${Je.joints?.length}`&&(i.skinList[i.skinList.length]=this,Xe=!1))),this.passFrustumCulling=Qe;const{displacementTexture:ft,displacementScale:pt}=je||{};if((Ze||je?.dirtyPipeline||y[Ke])&&(y[Ke]=!0),be){i.renderResults.num3DObjects++,this.#ls!==w.msaaID&&(Ze=!0,this.dirtyLOD=!0,this.#ls=w.msaaID),this.gpuRenderInfo||this.initGPURenderInfos();const g=!!ft;this.useDisplacementTexture!==g&&(this.useDisplacementTexture=g,Ze=!0),(Ze||y[Ke])&&(updateMeshDirtyPipeline(this,i),this.#As=null,this.#Ls=null);{const{gpuRenderInfo:i}=this,{vertexUniformBuffer:g,vertexUniformInfo:x}=i,{members:v}=x,{gpuBuffer:_}=g;if(this.#zs||(this.#zs=new Float32Array(v.matrixList.endOffset/Float32Array.BYTES_PER_ELEMENT)),v.uvTransform&&(je.dirtyTextureTransform||y[Ke])){const i=je,g=i.textureOffset||[0,0],x=i.textureScale||[1,1];g&&(y[Ke]=!0,Bn[0]=g[0],Bn[1]=g[1],Bn[2]=x[0],Bn[3]=x[1],L.queue.writeBuffer(_,v.uvTransform.uniformOffset,Bn),je.dirtyTextureTransform=!1)}}}else i.renderResults.num3DGroups++;if(be&&Qe){const{gpuRenderInfo:g}=this,{vertexUniformBuffer:v,vertexUniformInfo:_}=g,{members:y}=_,{members:b}=y.matrixList,{gpuBuffer:S}=v;if(this.#zs||(this.#zs=new Float32Array(y.matrixList.endOffset/Float32Array.BYTES_PER_ELEMENT)),void 0!==y.displacementScale&&this.#$s!==pt&&(this.#$s=pt,Cn[0]=pt,L.queue.writeBuffer(S,y.displacementScale.uniformOffset,Cn)),this.#Hs){{const i=this.is2DMeshType?multiply$4(create$4(),this.modelMatrix,fromValues$4(this.width,0,0,0,0,this.height,0,0,0,0,1,0,0,0,0,1)):this.modelMatrix;this.#zs.set(i,b.modelMatrix.uniformOffsetForData/Float32Array.BYTES_PER_ELEMENT)}if(this.#Fs&&b.normalModelMatrix){this.#Fs=!1;const i=this.modelMatrix,g=this.normalModelMatrix,x=i[0],v=i[1],_=i[2],y=i[4],b=i[5],S=i[6],w=i[8],L=i[9],k=i[10],H=x*(b*k-S*L)-v*(y*k-S*w)+_*(y*L-b*w);if(0===H)g[0]=1,g[1]=0,g[2]=0,g[3]=0,g[4]=0,g[5]=1,g[6]=0,g[7]=0,g[8]=0,g[9]=0,g[10]=1,g[11]=0,g[12]=0,g[13]=0,g[14]=0,g[15]=1;else{const i=1/H;g[0]=(b*k-S*L)*i,g[1]=(S*w-y*k)*i,g[2]=(y*L-b*w)*i,g[3]=0,g[4]=(_*L-v*k)*i,g[5]=(x*k-_*w)*i,g[6]=(v*w-x*L)*i,g[7]=0,g[8]=(v*S-_*b)*i,g[9]=(_*y-x*S)*i,g[10]=(x*b-v*y)*i,g[11]=0,g[12]=0,g[13]=0,g[14]=0,g[15]=1}}this.#zs.set(this.normalModelMatrix,b.normalModelMatrix.uniformOffsetForData/Float32Array.BYTES_PER_ELEMENT),b.localMatrix&&this.#zs.set(this.localMatrix,b.localMatrix.uniformOffsetForData/Float32Array.BYTES_PER_ELEMENT),Xe=!0,this.#Hs=!1,L.queue.writeBuffer(S,y.matrixList.startOffset,this.#zs)}this.dirtyOpacity&&(Ye=!0,y.combinedOpacity&&(Cn[0]=this.getCombinedOpacity(),L.queue.writeBuffer(S,y.combinedOpacity.uniformOffset,Cn)),this.dirtyOpacity=!1);const{bundleListRender2PathLayer:w,bundleListParticleLayer:k,bundleListTransparentLayer:H,bundleListAlphaLayer:z,bundleListBasicList:W}=i.renderBundleResults;{const{fragmentUniformBindGroup:g}=je.gpuRenderInfo;if((!this.#As||Ze||this.#Gs!==g||this.#ks[i.viewIndex]!==x.systemUniform_Vertex_UniformBindGroup||this.dirtyLOD)&&this.#Ys(i),i.renderResults.numDrawCalls++,be.indexBuffer){const{indexBuffer:g}=be,{indexCount:x,triangleCount:v}=g;i.renderResults.numTriangles+=v,i.renderResults.numPoints+=x}else{const{vertexBuffer:g}=be,{vertexCount:x,triangleCount:v}=g;i.renderResults.numTriangles+=v,i.renderResults.numPoints+=x}let v=this.#Ls;if(it){let i=this.#Xs;(i<0||i>=it)&&(i=-1);let g=!1;if(-1===i)et>=tt[0].distanceSquared&&(g=!0);else if(i===it-1)et=v)&&(g=!0)}if(g){let g=-1;for(let i=0;i=tt[i].distanceSquared;i++)g=i;g!==i&&(this.#Xs=g,g>=0&&g=0&&i{const{redGPUContext:_}=this,{gpuRenderInfo:y}=this;return y.vertexUniformInfo!==x&&(y.vertexUniformInfo=x,y.vertexStructInfo=g,createMeshVertexUniformBuffers(this)),y.vertexShaderSourceVariant=g.shaderSourceVariant,y.vertexShaderVariantConditionalBlocks=g.conditionalBlocks,y.vertexUniformBindGroup=_.gpuDevice.createBindGroup(getBasicMeshVertexBindGroupDescriptor(this)),this.#wr(i),this.gpuRenderInfo.vertexShaderModule};#Ws=()=>{const{redGPUContext:i}=this,{resourceManager:g}=i;this.#Ks.length=0;const x=g.getGPUBindGroupLayout(ResourceManager.PRESET_VERTEX_GPUBindGroupLayout);this.LODManager.LODList.forEach((v,_)=>{const y={code:v.source},b=g.createGPUShaderModule(v.label,y);this.#Ks[_]={pipeline:createBasePipeline({vertexStateBuffers:v.geometry.gpuRenderInfo.buffers,primitiveState:this.primitiveState,depthStencilState:this.depthStencilState,geometry:v.geometry,material:v.material||this.material,redGPUContext:i,gpuRenderInfo:this.gpuRenderInfo},b,x),vertexUniformBindGroup:i.gpuDevice.createBindGroup(getBasicMeshVertexBindGroupDescriptor({redGPUContext:i,material:v.material||this.material,gpuRenderInfo:{vertexBindGroupLayout:x,vertexUniformBuffer:this.gpuRenderInfo.vertexUniformBuffer}}))}}),this.#Xs=-1};#Ys(i){const{view:g}=i;this.#Ls=this.#Zs(g,this._geometry,this._material),this.dirtyLOD&&(this.#Ws(),this.dirtyLOD=!1),this.#Us.length=0,this.LODManager.LODList.forEach((i,x)=>{this.#Us[x]=this.#Zs(g,i.geometry,i.material||this._material,x)})}#Zs(i,g,x,v=null){const{gpuDevice:_}=this.redGPUContext,{renderViewStateData:y}=i,{vertexBuffer:b,indexBuffer:S}=g,{fragmentUniformBindGroup:w}=x.gpuRenderInfo;this.#Js(g,v);const L=null!==v,k=_.createRenderBundleEncoder({...i.basicRenderBundleEncoderDescriptor,label:this.uuid});L||(this.#As=k,this.#ks[y.viewIndex]=i.systemUniform_Vertex_UniformBindGroup,this.#Gs=w);const{gpuBuffer:H}=b,z=L?this.#Ks[v].pipeline:this.gpuRenderInfo.pipeline,q=L?this.#Ks[v].vertexUniformBindGroup:this.gpuRenderInfo.vertexUniformBindGroup;k.setPipeline(z),k.setVertexBuffer(0,H),this.particleBuffers?.length&&this.particleBuffers.forEach((i,g)=>{k.setVertexBuffer(g+1,i)}),k.setBindGroup(0,i.systemUniform_Vertex_UniformBindGroup),k.setBindGroup(1,q),k.setBindGroup(2,w);let W=this.#Os;if(null!==v&&(W=this.#Vs[v]),S){const{gpuBuffer:i,format:g}=S;k.setIndexBuffer(i,g),k.drawIndexedIndirect(W.buffer,4*W.commandOffset)}else k.drawIndirect(W.buffer,4*W.commandOffset);const be=k.finish({label:`${this.name}_LOD${v||0}`});return be.mesh=null,be}#qs(){this.#Os||(this.#Os=this.#Ns.allocateDrawCommand(this.name))}#Js(i,g=null){const{vertexBuffer:x,indexBuffer:v}=i,_=this.#Ns;let y=this.#Os;if(null!==g&&(this.#Vs[g]||(this.#Vs[g]=this.#Ns.allocateDrawCommand(`${this.name}_LOD${g}`)),y=this.#Vs[g]),this.#qs(),v){const{indexCount:i}=v;this.particleBuffers?_.setIndexedIndirectCommand(y,i,this.particleNum,0,0,0):_.setIndexedIndirectCommand(y,i,1,0,0,0)}else{const{vertexCount:i}=x;_.setIndirectCommand(y,i,1,0,0)}}#wr(i){const{resourceManager:g}=this.redGPUContext,x=this.#Mr(),v=`${i}_${x}`;let _=g.getGPUShaderModule(v);if(!_){let i=this.gpuRenderInfo.vertexShaderSourceVariant.getVariant(x);if(i)if(this.animationInfo?.skinInfo){const y=`${this.animationInfo.skinInfo.joints.length}`;i=i.replaceAll("#JOINT_NUM",y),this.gpuRenderInfo.vertexShaderSourceVariant.getVariant(x),_=g.createGPUShaderModule(`${v}_${y}`,{code:i})}else _=g.createGPUShaderModule(v,{code:i});else console.warn("⚠️ 버텍스 바리안트 소스를 찾을 수 없음:",x),_=this.gpuRenderInfo.vertexShaderModule}this.gpuRenderInfo.vertexShaderModule=_}#Mr(){const{vertexShaderVariantConditionalBlocks:i}=this.gpuRenderInfo,g=new Set;for(const x of i)this[x]&&g.add(x);const x=g.size>0?Array.from(g).sort().join("+"):"none";return g.size,x}}Object.defineProperty(Mesh.prototype,"isInstanceofMesh",{value:!0,writable:!1}),defineBoolean(Mesh,[{key:"receiveShadow",value:!1},{key:"useDisplacementTexture",value:!1},{key:"disableJitter",value:!1}]),Object.freeze(Mesh);class Primitive{static#Qs=new VertexInterleavedStruct({vertexPosition:VertexInterleaveType.float32x3,vertexNormal:VertexInterleaveType.float32x3,texcoord:VertexInterleaveType.float32x2,vertexTangent:VertexInterleaveType.float32x4},"primitiveInterleaveStruct");#eo;#On;#Vn;#Nn;constructor(i,g,x){validateRedGPUContext(i);const v=i.resourceManager.cachedBufferState;let _=v[g];_||(_=v[g]=x()),this.#to(_)}static get primitiveInterleaveStruct(){return this.#Qs}get gpuRenderInfo(){return this.#eo}get vertexBuffer(){return this.#On}get indexBuffer(){return this.#Vn}get volume(){return this.#Nn||(this.#Nn=calculateGeometryAABB(this.#On)),this.#Nn}static generateUniqueKey(i,g){let x="PRIMITIVE_"+i.toUpperCase();for(const i in g){const v=g[i];void 0!==v&&(x+="_"+i.toUpperCase()+v)}return x}#to(i){if(this.#On=i.vertexBuffer,this.#Vn=i.indexBuffer,this.#On){const{interleavedStruct:i}=this.#On;this.#eo=new GeometryGPURenderInfo([{arrayStride:i.arrayStride,attributes:i.attributes}])}}}Object.freeze(Primitive);const calculateTangentsInterleaved=(i,g,x,v,_,y,b)=>{const S=1e-6,w=i.length/x,L=g.length>0,k=L?g.length/3:w/3,H=new Float32Array(3*w),z=new Float32Array(3*w);for(let _=0;_{const _=i.length/3,y=new Float32Array(12*_);for(let v=0;v<_;v++){const _=12*v;y[_]=i[3*v],y[_+1]=i[3*v+1],y[_+2]=i[3*v+2],y[_+3]=g[3*v],y[_+4]=g[3*v+1],y[_+5]=g[3*v+2],y[_+6]=x[2*v],y[_+7]=x[2*v+1]}calculateTangentsInterleaved(y,v,12,0,3,6,8);const b=new Float32Array(4*_);for(let i=0;i<_;i++){const g=12*i,x=4*i;b[x]=y[g+8],b[x+1]=y[g+9],b[x+2]=y[g+10],b[x+3]=y[g+11]}return b};class ResourceStateIndexBuffer{static dirtyList=[];buffer;label;uuid;#jt=0;constructor(i){this.buffer=i,this.label=i.name,this.uuid=i.uuid}get useNum(){return this.#jt}set useNum(i){this.#jt=i,ResourceStateIndexBuffer.dirtyList.push(this)}}class IndexBuffer extends ABaseBuffer{[Ar];#ro=0;#qn=0;#z=en.UINT32;constructor(i,g,x=GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST,v=""){super(i,"managedIndexBufferState",x);const{table:_}=this.targetResourceManagedState,y=_.get(v);if(y)return y.buffer;v&&(this.name=v,this[kr]=v),this.changeData(g),this.redGPUContext.resourceManager.registerManagementResource(this,new ResourceStateIndexBuffer(this))}get format(){return this.#z}get triangleCount(){return this.#qn}get indexCount(){return this.#ro}get data(){return this[Ar]}changeData(i){const{gpuDevice:g}=this;Array.isArray(i)&&(i=new Uint32Array(i)),this[Ir]&&(this.targetResourceManagedState.videoMemory-=this[Ar].byteLength||0,this.redGPUContext.commandEncoderManager.addDeferredDestroy(this[Ir]),this[Ir]=null),this[Ar]=i,this.#ro=i.length;const x={size:this[Ar].byteLength,usage:this.usage,label:this.name};this[Ir]=g.createBuffer(x),this.targetResourceManagedState.videoMemory+=this[Ar].byteLength||0,this.#qn=this.#ro/3,g.queue.writeBuffer(this[Ir],0,this[Ar])}}Object.freeze(IndexBuffer);const createPrimitiveGeometry=(i,g,x,v)=>new Geometry(i,new VertexBuffer(i,new Float32Array(g),Primitive.primitiveInterleaveStruct,void 0,`VertexBuffer_${v}`),new IndexBuffer(i,new Uint32Array(x),void 0,`IndexBuffer_${v}`));class PrimitiveUtils{static#io={x:1,y:0,z:0};static#no={x:0,y:0,z:-1};static#ao={x:0,y:0,z:0};static#so={x:0,y:1,z:0};static#oo={x:0,y:-1,z:0};static#uo={x:0,y:0,z:0};static#lo={x:0,y:0,z:0};static#co={x:0,y:0,z:0};static#ho={x:0,y:0,z:0};static#fo={x:0,y:0,z:0};static#do={x:0,y:0,z:0};static#mo={x:0,y:0,z:0};static#po={x:0,y:0,z:0};static#go={x:0,y:0,z:0};static#xo={x:0,y:0,z:0};static get#vo(){return Primitive.primitiveInterleaveStruct.arrayStride/4}static finalize(i,g,x,v){return this.calculateTangents(g,x),createPrimitiveGeometry(i,g,x,v)}static generateGrid(i,g,x,v,_,y=!1,b=!1){const S=i.length/this.#vo;for(let i=0;i<=v;i++){const g=i/v;for(let v=0;v<=x;v++)_(v/x,g,v,i)}!y&&g&&this.generateGridIndices(g,S,x,v,x+1,b)}static getEmptyGeometry(i,g){const x=[];return this.interleavePacker(x,0,0,0,0,1,0,0,0),createPrimitiveGeometry(i,x,[],g)}static generateBoxData(i,g,x,v,_,y,b,S){return this.generateRoundedBoxData(i,g,x,v,_,y,b,0,0,S)}static generateRoundedBoxData(i,g,x,v,_,y,b,S,w,L){const k=[],H=[],z=g/2,q=x/2,W=v/2,be=Math.min(S,z,q,W),je=be>0?{w:g,h:x,d:v,r:be}:null;return this.generatePlaneData(k,H,v,x,b,y,{x:z,y:0,z:0},{x:0,y:0,z:-1},{x:0,y:-1,z:0},{x:1,y:0,z:0},be,w,je),this.generatePlaneData(k,H,v,x,b,y,{x:-z,y:0,z:0},{x:0,y:0,z:1},{x:0,y:-1,z:0},{x:-1,y:0,z:0},be,w,je),this.generatePlaneData(k,H,g,v,_,b,{x:0,y:q,z:0},{x:1,y:0,z:0},{x:0,y:0,z:1},{x:0,y:1,z:0},be,w,je),this.generatePlaneData(k,H,g,v,_,b,{x:0,y:-q,z:0},{x:1,y:0,z:0},{x:0,y:0,z:-1},{x:0,y:-1,z:0},be,w,je),this.generatePlaneData(k,H,g,x,_,y,{x:0,y:0,z:W},{x:1,y:0,z:0},{x:0,y:-1,z:0},{x:0,y:0,z:1},be,w,je),this.generatePlaneData(k,H,g,x,_,y,{x:0,y:0,z:-W},{x:-1,y:0,z:0},{x:0,y:-1,z:0},{x:0,y:0,z:-1},be,w,je),this.finalize(i,k,H,L)}static generatePlaneData(i,g,x,v,_,y,b,S,w,L,k=0,H=0,z=null,q=!1){const W=i.length/this.#vo,be=_+2*H,je=y+2*H,getCoordInfo=(i,g,x,v,_)=>{if(x<=0||v<=0){const x=i/_;return{pos:(x-.5)*g,norm:0,uv:x}}const y=g/2-x,b=Math.PI/2*x,S=2*b+2*y;if(i<=v){const g=i/v,_=(1-g)*Math.PI/2;return{pos:-y-Math.sin(_)*x,norm:-Math.sin(_),uv:g*b/S}}if(i<=v+_){const g=(i-v)/_;return{pos:g*(2*y)-y,norm:0,uv:(b+g*(2*y))/S}}{const g=(i-v-_)/v,w=g*Math.PI/2;return{pos:y+Math.sin(w)*x,norm:Math.sin(w),uv:(b+2*y+g*b)/S}}};for(let g=0;g<=je;g++){const W=getCoordInfo(g,v,k,H,y),je=q?1-W.uv:W.uv;for(let g=0;g<=be;g++){const v=getCoordInfo(g,x,k,H,_);let y=b.x+v.pos*S.x+W.pos*w.x,q=b.y+v.pos*S.y+W.pos*w.y,be=b.z+v.pos*S.z+W.pos*w.z,Ke=L.x,Xe=L.y,Ye=L.z;if(z){const{w:i,h:g,d:x,r:v}=z,_=i/2-v,b=g/2-v,S=x/2-v,w=Math.max(-_,Math.min(y,_)),L=Math.max(-b,Math.min(q,b)),k=Math.max(-S,Math.min(be,S)),H=y-w,W=q-L,je=be-k,Ze=Math.sqrt(H*H+W*W+je*je)||1e-6;Ke=H/Ze,Xe=W/Ze,Ye=je/Ze,y=w+Ke*v,q=L+Xe*v,be=k+Ye*v}this.interleavePacker(i,y,q,be,Ke,Xe,Ye,v.uv,je)}}this.generateGridIndices(g,W,be,je,be+1)}static generateSphereData(i,g,x,v,_,y,b,S,w){const L=[],k=[];return g<=0||Math.abs(y)<1e-6||Math.abs(S)<1e-6?this.getEmptyGeometry(i,w):(this.generateSphericalData(L,k,g,x,v,_,y,b,S),this.finalize(i,L,k,w))}static generateCylinderData(i,g,x,v,_,y,b,S,w,L,k,H,z){const q=[],W=[],be=v/2;return g<=0&&x<=0||v<=0||Math.abs(L)<1e-6?this.getEmptyGeometry(i,z):(this.generateCylinderTorsoData(q,W,g,x,v,_,y,w,L,this.#ao,this.#io,this.#no),b&&g>0&&this.generateRingData(q,W,0,g,_,1,w,L,{x:0,y:be,z:0},this.#io,this.#no,this.#so,!0,k),S&&x>0&&this.generateRingData(q,W,0,x,_,1,w,L,{x:0,y:-be,z:0},this.#io,this.#no,this.#oo,!1,H),this.finalize(i,q,W,z))}static generateConeData(i,g,x,v,_,y,b,S,w){return this.generateCylinderData(i,0,g,x,v,_,!1,y,b,S,!1,!1,w)}static generatePlaneEntryData(i,g,x,v,_,y,b){const S=[],w=[];return g<=0||x<=0?this.getEmptyGeometry(i,b):(this.generatePlaneData(S,w,g,x,v,_,this.#ao,this.#io,{x:0,y:-1,z:0},{x:0,y:0,z:1},0,0,null,y),this.finalize(i,S,w,b))}static generateGroundData(i,g,x,v,_,y,b){const S=[],w=[];return g<=0||x<=0?this.getEmptyGeometry(i,b):(this.generatePlaneData(S,w,g,x,v,_,this.#ao,this.#io,{x:0,y:0,z:1},this.#so,0,0,null,y),this.finalize(i,S,w,b))}static generateCircleEntryData(i,g,x,v,_,y,b){const S=[],w=[];return g<=0||Math.abs(_)<1e-6?this.getEmptyGeometry(i,b):(this.generateRingData(S,w,0,g,x,1,v,_,this.#ao,this.#io,this.#no,this.#so,!0,y),this.finalize(i,S,w,b))}static generateRingEntryData(i,g,x,v,_,y,b,S,w){const L=[],k=[];return x<=0||Math.abs(b)<1e-6?this.getEmptyGeometry(i,w):(this.generateRingData(L,k,g,x,v,_,y,b,this.#ao,this.#io,this.#no,this.#so,!0,S),this.finalize(i,L,k,w))}static generateTorusData(i,g,x,v,_,y,b,S,w,L,k,H){const z=[],q=[],W=Math.abs(b)<2*Math.PI;if(this.generateGrid(z,q,v,_,(i,v)=>{const _=y+i*b,S=v*Math.PI*2,w=this.#uo,L=this.#lo,k=this.#co,H=this.#ho,q=this.#fo;this.#_o(this.#ao,1,_,this.#io,this.#no,w),this.#yo(L,w.x*g,0,w.z*g),this.#yo(k,-w.x,0,-w.z),this.#_o(L,x,S,k,this.#so,H),this.#_o(this.#ao,1,S,k,this.#so,q),this.interleavePacker(z,H.x,H.y,H.z,q.x,q.y,q.z,i,v)}),W){const i=this.#io,v=this.#no,H=this.#so,W=this.#uo,be=this.#lo,je=this.#co;if(S&&(this.#_o(this.#ao,g,y,i,v,W),this.#_o(this.#ao,1,y,i,v,be),this.#yo(je,Math.cos(y),0,-Math.sin(y)),this.generateRingData(z,q,0,x,_,1,0,2*Math.PI,W,be,H,je,!0,L)),w){const S=y+b;this.#_o(this.#ao,g,S,i,v,W),this.#_o(this.#ao,1,S,i,v,be),this.#yo(je,-Math.cos(S),0,Math.sin(S)),this.generateRingData(z,q,0,x,_,1,0,2*Math.PI,W,be,H,je,!1,k)}}return this.finalize(i,z,q,H)}static generateTorusKnotData(i,g,x,v,_,y,b,S){const w=[],L=[];return this.generateGrid(w,L,_,v,(i,v)=>{const _=v*y*Math.PI*2,S=this.#uo,L=this.#lo,k=this.#co,H=this.#ho,z=this.#fo,q=this.#do,W=this.#mo,be=this.#po,je=this.#go;this.#bo(_,y,b,g,S),this.#bo(_+.01,y,b,g,L),this.#yo(k,L.x-S.x,L.y-S.y,L.z-S.z),this.#yo(H,L.x+S.x,L.y+S.y,L.z+S.z),this.#So(k,H,z),this.#To(z),this.#So(z,k,H),this.#To(H);const Ke=i*Math.PI*2;this.#yo(be,-z.x,-z.y,-z.z),this.#yo(je,-H.x,-H.y,-H.z),this.#_o(S,x,Ke,be,je,q),this.#_o(this.#ao,1,Ke,be,je,W),this.interleavePacker(w,q.x,q.y,q.z,W.x,W.y,W.z,v,i)}),this.finalize(i,w,L,S)}static generateRingData(i,g,x,v,_,y,b,S,w,L,k,H,z=!0,q=!1,W=0,be=1){if(v<=1e-6||Math.abs(S)<1e-6)return void this.interleavePacker(i,w.x,w.y,w.z,H.x,H.y,H.z,.5,.5);const je=this.#xo;this.generateGrid(i,g,_,y,(g,_)=>{const y=x+_*(v-x),z=b+g*S,Ke=W+_*(be-W);this.#_o(w,y,z,L,k,je);const Xe=q?g:.5-y/v*Math.sin(z)*.5,Ye=q?Ke:.5-y/v*Math.cos(z)*.5;this.interleavePacker(i,je.x,je.y,je.z,H.x,H.y,H.z,Xe,Ye)},!1,!z)}static generateSphericalData(i,g,x,v,_,y,b,S,w,L=0,k=0,H=1){this.generateGrid(i,g,v,_,(g,v)=>{const _=S+v*w,z=y+g*b,q=Math.sin(_),W=Math.cos(_),be=Math.sin(z),je=Math.cos(z),Ke=k+v*(H-k),Xe=-be*q,Ye=W,Ze=-je*q;this.interleavePacker(i,x*Xe,x*Ye+L,x*Ze,Xe,Ye,Ze,g,Ke)},null===g)}static generateCylinderTorsoData(i,g,x,v,_,y,b,S,w,L,k,H,z={x:0,y:1,z:0},q=!1,W=0,be=1){const je=_/2,Ke=(v-x)/_;if(0===w||x<=0&&v<=0)return void this.interleavePacker(i,L.x,L.y,L.z,0,1,0,0,0);const Xe=this.#uo,Ye=this.#lo,Ze=this.#co;this.generateGrid(i,g,y,b,(g,y)=>{const b=y*(v-x)+x,q=g*w+S,Je=je-y*_,Qe=W+y*(be-W);this.#_o({x:0,y:0,z:0},b,q,k,H,Xe),this.#_o({x:0,y:0,z:0},1,q,k,H,Ye);const et=L.x+Xe.x+Je*z.x,tt=L.y+Xe.y+Je*z.y,it=L.z+Xe.z+Je*z.z;this.#yo(Ze,Ye.x+Ke*z.x,Ye.y+Ke*z.y,Ye.z+Ke*z.z),this.#To(Ze),this.interleavePacker(i,et,tt,it,Ze.x,Ze.y,Ze.z,g,Qe)},q)}static generateCapsuleData(i,g,x,v,_,y,b){const S=[],w=[],L=v+1,k=x/2,H=Math.PI/2*g,z=2*H+x,q=H/z,W=(H+x)/z;return this.generateSphericalData(S,null,g,v,y,0,2*Math.PI,0,Math.PI/2,k,0,q),this.generateCylinderTorsoData(S,null,g,g,x,v,_,0,2*Math.PI,this.#ao,this.#io,this.#no,this.#so,!0,q,W),this.generateSphericalData(S,null,g,v,y,0,2*Math.PI,Math.PI/2,Math.PI/2,-k,W,1),this.generateGridIndices(w,0,v,2*y+_,L),this.finalize(i,S,w,b)}static generateGridIndices(i,g,x,v,_,y=!1){for(let b=0;bPrimitiveUtils.generatePlaneEntryData(i,g,x,v,_,y,b))}}class ResourceStateBitmapTexture{texture;src;cacheKey;useNum=0;uuid;constructor(i){this.texture=i,this.src=i.src,this.cacheKey=i.cacheKey,this.useNum=0,this.uuid=i.uuid}}class BitmapTexture extends ManagementResourceBase{#V;#wo;#$;#K;#Mo;#H=0;#Po=!0;#z;#q;#Y;constructor(i,g,x=!0,v,_,y,b=!1){if(super(i,"managedBitmapTextureState"),this.#q=v,this.#Y=_,this.#Po=b,this.#K=x,this.#z=y||`${navigator.gpu.getPreferredCanvasFormat()}-srgb`,g){this.#wo=this.#W(g),this.cacheKey=this.#Z(g);const{table:i}=this.targetResourceManagedState;let x=i.get(this.cacheKey);if(x){const i=x.texture;return this.#q?.(i),i}this.src=g,this.#J()}}get width(){return this.#Mo?.width||0}get height(){return this.#Mo?.height||0}get usePremultiplyAlpha(){return this.#Po}get videoMemorySize(){return this.#H}get gpuTexture(){return this.#V}get mipLevelCount(){return this.#$}get src(){return this.#wo}set src(i){this.#wo=this.#W(i),this.cacheKey=this.#Z(i),this.#wo&&this.#Q(this.#wo)}get useMipmap(){return this.#K}set useMipmap(i){this.#K=i,this.#ee()}destroy(){const i=this.#V;this.#te(null),this.notifyUpdate(!0),this.#re(),this.cacheKey=null,this.#wo=null,i&&this.redGPUContext.commandEncoderManager.addDeferredDestroy(i)}#Z(i){return i?"string"==typeof i?getAbsoluteURL(window.location.href,i):i.cacheKey||getAbsoluteURL(window.location.href,i.src):this.uuid}#W(i){return"string"==typeof i?i:i.src}#te(i){this.#V=i,i||(this.#Mo=null),this.notifyUpdate()}#J(){this.redGPUContext.resourceManager.registerManagementResource(this,new ResourceStateBitmapTexture(this))}#re(){this.redGPUContext.resourceManager.unregisterManagementResource(this)}#ee(){const{gpuDevice:i,resourceManager:g}=this.redGPUContext,{mipmapGenerator:x}=g;this.#V&&(this.redGPUContext.commandEncoderManager.addDeferredDestroy(this.#V),this.#V=null),this.targetResourceManagedState.videoMemory-=this.#H,this.#H=0;const{width:v,height:_}=this.#Mo;this.#$=1;const y={size:[v,_],format:this.#z,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC,label:this.#wo};this.#K&&(this.#$=getMipLevelCount(v,_),y.mipLevelCount=this.#$,y.usage|=GPUTextureUsage.RENDER_ATTACHMENT);const b=imageBitmapToGPUTexture(i,[this.#Mo],y,this.#Po);this.#H=calculateTextureByteSize(b),this.targetResourceManagedState.videoMemory+=this.#H,this.#K&&x.generateMipmap(b,y),this.#te(b)}async#Ro(i){return new Promise((g,x)=>{const v=new Image;v.src=i,v.onload=()=>{const i=document.createElement("canvas");i.width=v.width||512,i.height=v.height||512;const _=i.getContext("2d");_?(_.fillStyle="rgba(0, 0, 0, 0)",_.fillRect(0,0,i.width,i.height),_.drawImage(v,0,0,i.width,i.height),createImageBitmap(i,{colorSpaceConversion:"none",premultiplyAlpha:this.#Po?"premultiply":"none"}).then(g).catch(x)):x(new Error("Canvas context could not be created."))},v.onerror=i=>{x(new Error(`Failed to load SVG: ${i}`))}})}async#Q(i){try{i.endsWith(".svg")?this.#Mo=await this.#Ro(i):this.#Mo=await loadAndCreateBitmapImage(i,"none",this.#Po?"premultiply":"none"),this.#ee(),this.#q?.(this)}catch(i){console.error(i),this.#Y?.(i)}}}Object.freeze(BitmapTexture);const En=parseWGSL("TEXTFIELD_MATERIAL","#redgpu_include SYSTEM_UNIFORM;#redgpu_include color.getTintBlendMode;#redgpu_include entryPoint.mesh.entryPointPickingFragment;#redgpu_include systemStruct.OutputFragment;struct Uniforms{useDiffuseTexture:u32,opacity:f32,useTint:u32,tint:vec4,tintBlendMode:u32,};@group(2)@binding(0)varuniforms:Uniforms;@group(2)@binding(1)var diffuseTextureSampler:sampler;@group(2)@binding(2)var diffuseTexture:texture_2d;struct InputData{@builtin(position)position:vec4,@location(0)vertexPosition:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,@location(11)combinedOpacity:f32,@location(13)shadowCoord:vec3,@location(15)@interpolate(flat)pickingId:vec4,};@fragment fn main(inputData:InputData)->OutputFragment{var output:OutputFragment;var finalColor:vec4=textureSample(diffuseTexture,diffuseTextureSampler,inputData.uv);finalColor=vec4(finalColor.rgb/finalColor.a,finalColor.a*uniforms.opacity*inputData.combinedOpacity);#redgpu_if useTint finalColor=getTintBlendMode(finalColor,uniforms.tintBlendMode,uniforms.tint);#redgpu_endIf if(finalColor.a==.0){discard;}output.color=vec4(finalColor.rgb,finalColor.a);output.gBufferMotionVector=vec4(.0,.0,1.0,1.0);return output;};");class TextFieldMaterial extends ABitmapBaseMaterial{constructor(i,g,x){super(i,"TEXT_FIELD_MATERIAL",En,2),x&&(this.name=x),this.diffuseTexture=g,this.diffuseTextureSampler=new Sampler(this.redGPUContext),this.initGPURenderInfos()}}defineSampler(TextFieldMaterial,[{key:"diffuseTextureSampler"}]),defineTexture(TextFieldMaterial,[{key:"diffuseTexture"}]),Object.freeze(TextFieldMaterial);const In=";box-sizing:content-box;white-space:nowrap;",An={padding:0,background:"transparent",color:"#fff",fontFamily:"Arial",fontSize:24,fontWeight:"normal",fontStyle:"normal",letterSpacing:0,wordBreak:"keep-all",verticalAlign:"middle",textAlign:"center",borderRadius:0,lineHeight:1.4,border:"",boxShadow:"none",boxSizing:"border-box",filter:""};class ATextField extends Mesh{#Co;#Bo;#Do;#Eo;#Io;#Ao;#Lo;#Uo=!0;#h;#ko;#Go=!1;#Oo=1;#Vo=1;constructor(i,g,x=!0){super(i),this.#h=i,this.#Uo=x,this.#Lo=g,this._material=new TextFieldMaterial(i),this._material.transparent=!0,this._material.diffuseTextureSampler=new Sampler(i,x?{minFilter:_.LINEAR,magFilter:_.LINEAR,mipmapFilter:y.LINEAR}:{minFilter:_.NEAREST,magFilter:_.NEAREST,mipmapFilter:null}),this.depthStencilState.depthWriteEnabled=!1,this.#No(),this.#Fo(),this.#Ho(),this.#zo(),this.#$o()}get text(){return this.#Ao}set text(i){if(this.#Ao===i)return;this.#Ao=i;const g=this.#Do.querySelector("foreignObject div"),x=this.#jo(i);this.#Eo.innerHTML=x,g.innerHTML=x,this.#Go=!0}render(i){this.#Lo(this.#Oo,this.#Vo),this.#Ko(),super.render(i)}#jo(i){return i.toString().replace(/\/gi,"
")}#No(){"undefined"!=typeof OffscreenCanvas?this.#Co=new OffscreenCanvas(100,100):this.#Co=document.createElement("canvas"),this.#Bo=this.#Co.getContext("2d")}#Xo(){const i=this.#Eo.getBoundingClientRect();const g=i.width+3+3,x=i.height+3+3;return{width:-2&Math.ceil(g),height:-2&Math.ceil(x),extraTop:3,extraRight:3,extraBottom:3,extraLeft:3}}#qo(){const i=this.#Do,g=i.querySelector("foreignObject"),{width:x,height:v,extraTop:_,extraRight:y,extraBottom:b,extraLeft:S}=this.#Xo();g.setAttribute("width",x.toString()),g.setAttribute("height",v.toString()),g.style.padding=`${_}px ${y}px ${b}px ${S}px`,i.setAttribute("width",x.toString()),i.setAttribute("height",v.toString()),this.#Io.src="data:image/svg+xml;charset=utf-8,"+encodeURIComponent(i.outerHTML)}#zo(){this.#Io=new Image,this.#Io.style.cssText="position:absolute;bottom:0px;left:0;",this.#Io.onload=i=>{let g,x;const{width:v,height:_}=this.#Xo(),y=1===window.devicePixelRatio?2:window.devicePixelRatio;g=v*y,x=_*y,this.#Io.width=v,this.#Io.height=_,this.#Co.width=g,this.#Co.height=x,this.#Co instanceof OffscreenCanvas||(this.#Co.style.width=`${v}px`,this.#Co.style.height=`${_}px`),this.#Bo.imageSmoothingEnabled=!0,this.#Bo.imageSmoothingQuality="high",this.#Bo.clearRect(0,0,g,x),this.#Bo.fillStyle="rgba(0, 0, 0, 0)",this.#Bo.fillRect(0,0,g,x),this.#Bo.drawImage(this.#Io,0,0,g,x),this.dirtyTransform=!0;const callback=i=>{if(this.material.diffuseTexture){const i=this.material.diffuseTexture.src,g="string"==typeof i&&i?.startsWith?.("blob:");this.material.diffuseTexture.destroy(),this.material.diffuseTexture=null,g&&URL.revokeObjectURL(i)}this.material.diffuseTexture=new BitmapTexture(this.#h,URL.createObjectURL(i),!0,()=>{this.#Oo=v,this.#Vo=_},null,null,!0)};this.#Co instanceof OffscreenCanvas?this.#Co.convertToBlob({type:"image/png"}).then(callback):this.#Co.toBlob(callback,"image/png")}}#Ko(){this.#Go&&(this.#ko&&cancelAnimationFrame(this.#ko),this.#ko=requestAnimationFrame(()=>{this.#qo()})),this.#Go=!1}#Yo=(i,g)=>{const x=this.#Do.querySelector("foreignObject > div").style,v=this.#Eo.style,_=`_${i}`;this[_]=g,Object.defineProperty(this,i,{get:()=>this[_],set:g=>{const y=this[_];this[_]=g;const b=(i=>"number"==typeof i)(g)&&(i=>!["lineHeight","fontWeight"].includes(i))(i)?`${g}px`:g;x[i]=b,v[i]=b,y!==g&&(this.#Go=!0)},configurable:!0}),this[i]=g};#Fo(){this.#Eo=document.createElement("div"),this.#Eo.style.cssText=In+";position:absolute;top:200px;left:0;visibility:hidden;text-rendering:optimizeLegibility",document.body.appendChild(this.#Eo)}#Ho(){const i=this.#Do=document.createElementNS("http://www.w3.org/2000/svg","svg");i.setAttribute("xmlns","http://www.w3.org/2000/svg"),i.setAttribute("text-rendering","optimizeLegibility"),i.style.cssText="position:absolute;top:0px;left:0px;z-index:1;margin:0;padding:0;overflow:visible;background:transparent",i.innerHTML=`\n \n \n\t\t\t
\n\t\t\t
`}#$o(){for(const[i,g]of Object.entries(An))this.#Yo(i,g);this.#Go=!0}}Object.freeze(ATextField);var Ln="#redgpu_include SYSTEM_UNIFORM;#redgpu_include math.billboard.getBillboardMatrix;#redgpu_include math.billboard.getBillboardResult;#redgpu_include entryPoint.billboard.entryPointPickingVertex;#redgpu_include entryPoint.empty.entryPointShadowVertex;struct MatrixList{modelMatrix:mat4x4,normalModelMatrix:mat4x4,}struct VertexUniforms{pickingId:u32,matrixList:MatrixList,normalModelMatrix:mat4x4,useSizeAttenuation:u32,useBillboard:u32,usePixelSize:u32,pixelSize:f32,_renderRatioX:f32,_renderRatioY:f32,combinedOpacity:f32,};@group(1)@binding(0)varvertexUniforms:VertexUniforms;struct InputData{@location(0)position:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,};struct VertexOutput{@builtin(position)position:vec4,@location(0)vertexPosition:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,@location(11)combinedOpacity:f32,@location(13)shadowCoord:vec3,@location(15)@interpolate(flat)pickingId:vec4,};@vertex fn main(inputData:InputData)->VertexOutput{var output:VertexOutput;let billboardResult=getBillboardResult(inputData.position,inputData.vertexNormal,vertexUniforms.matrixList.modelMatrix,systemUniforms.camera.viewMatrix,systemUniforms.projection.noneJitterProjectionMatrix,systemUniforms.resolution,vertexUniforms.useBillboard,vertexUniforms.usePixelSize,vertexUniforms.pixelSize,vertexUniforms._renderRatioX,vertexUniforms._renderRatioY);output.position=billboardResult.position;output.vertexPosition=billboardResult.vertexPosition;output.vertexNormal=billboardResult.vertexNormal;output.uv=inputData.uv;output.combinedOpacity=vertexUniforms.combinedOpacity;return output;}";const Un=parseWGSL("TEXTFIELD3D_VERTEX",Ln),kn=Un.uniforms.vertexUniforms;class TextField3D extends ATextField{#Wo=1;#Zo=1;#Jo=1;#Qo=!1;constructor(i,g){super(i,(i,g)=>{i&&g&&(i===this.#Wo&&g===this.#Zo||(this.#Wo=i,this.#Zo=g,this.gpuRenderInfo&&this.redGPUContext.gpuDevice.queue.writeBuffer(this.gpuRenderInfo.vertexUniformBuffer.gpuBuffer,this.gpuRenderInfo.vertexUniformInfo.members.pixelSize.uniformOffset,new Float32Array([g*window.devicePixelRatio])),this.#eu()))}),this._geometry=new Plane(i),this.disableJitter=!0,g&&(this.text=g)}get worldSize(){return this.#Jo}set worldSize(i){this.#Jo!==i&&(this.#Jo=i,this.#eu())}get usePixelSize(){return this.#Qo}set usePixelSize(i){if(this.gpuRenderInfo){const{vertexUniformBuffer:g,vertexUniformInfo:x}=this.gpuRenderInfo;this.redGPUContext.gpuDevice.queue.writeBuffer(g.gpuBuffer,x.members.usePixelSize.uniformOffset,new Uint32Array([i?1:0])),this.redGPUContext.gpuDevice.queue.writeBuffer(g.gpuBuffer,x.members.pixelSize.uniformOffset,new Float32Array([this.#Zo*window.devicePixelRatio]))}this.#Qo!==i&&(this.#Qo=i,this.#eu())}get pixelSize(){return this.#Zo}get geometry(){return this._geometry}set geometry(i){console.error("TextField3D can not change geometry")}get material(){return this._material}set material(i){console.error("TextField3D can not change material")}render(i){super.render(i)}createCustomMeshVertexShaderModule=()=>this.createMeshVertexShaderModuleBASIC("VERTEX_MODULE_TEXT_FIELD_3D",Un,kn,Ln);#eu(){if(this.#Zo){const i=this._renderRatioX,g=this._renderRatioY;this.usePixelSize?(this._renderRatioY=1,this._renderRatioX=this.#Wo/this.#Zo):(this._renderRatioY=this.#Jo,this._renderRatioX=this.#Wo/this.#Zo*this.#Jo),i===this._renderRatioX&&g===this._renderRatioY||(this.dirtyTransform=!0)}}}definePositiveNumber(TextField3D,[{key:"_renderRatioX",value:1},{key:"_renderRatioY",value:1}]),defineBoolean(TextField3D,[{key:"useBillboard",value:!0}]),Object.freeze(TextField3D);class ADrawDebuggerLight{#tu;#ru;#ga;#iu;constructor(i,g,x,v,_=32){this.#ga=g;const y=this.#nu(i,_);this.#tu=new ColorMaterial(i,convertRgbToHex(v[0],v[1],v[2])),this.#ru=new Mesh(i,y,this.#tu);const{primitiveState:b}=this.#ru;b.cullMode="none",b.topology=Ei.LINE_LIST,this.#iu=new TextField3D(i),this.#iu.usePixelSize=!0,this.#iu.fontSize=40,this.#iu.text=x,this.#ru.addChild(this.#iu)}get target(){return this.#ga}get label(){return this.#iu}get lightDebugMesh(){return this.#ru}updateVertexBuffer(i,g){const x=g.data;let v=0;const _=Math.min(i.length,Math.floor(x.length/24));for(let g=0;g<_;g++){const[_,y]=i[g];x[v++]=_[0],x[v++]=_[1],x[v++]=_[2],x[v++]=0,x[v++]=0,x[v++]=1,x[v++]=0,x[v++]=0,x[v++]=1,x[v++]=0,x[v++]=0,x[v++]=1,x[v++]=y[0],x[v++]=y[1],x[v++]=y[2],x[v++]=0,x[v++]=0,x[v++]=1,x[v++]=0,x[v++]=0,x[v++]=1,x[v++]=0,x[v++]=0,x[v++]=1}g.updateAllData(x)}#nu(i,g){const x=new Float32Array(2*g*12),v=new VertexInterleavedStruct({vertexPosition:VertexInterleaveType.float32x3,vertexNormal:VertexInterleaveType.float32x3,texcoord:VertexInterleaveType.float32x2,vertexTangent:VertexInterleaveType.float32x4},`lightDebugStruct_${Math.random()}`),_=new VertexBuffer(i,x,v);return new Geometry(i,_)}}Object.freeze(ADrawDebuggerLight);class DrawDebuggerDirectionalLight extends ADrawDebuggerLight{#au=[0,10,0];constructor(i,g){super(i,g,"☀️",[255,255,0],8)}render(i){const{lightDebugMesh:g,label:x,target:v}=this;if(!i.view.systemUniform_Vertex_UniformBindGroup)return;if(!v.enableDebugger)return;this.#su(v,g.geometry.vertexBuffer),g.render(i);const{direction:_}=v,y=this.#au,b=Math.sqrt(_[0]*_[0]+_[1]*_[1]+_[2]*_[2]),S=[_[0]/b,_[1]/b,_[2]/b];x.setPosition(y[0]-0*S[0],y[1]-0*S[1],y[2]-0*S[2])}#su(i,g){const x=this.#au,v=i.direction||[0,-1,0],_=Math.sqrt(v[0]*v[0]+v[1]*v[1]+v[2]*v[2]),y=[v[0]/_,v[1]/_,v[2]/_],b=[x[0]+3*y[0],x[1]+3*y[1],x[2]+3*y[2]],S=.3;let w=[0,1,0];Math.abs(y[1])>.99&&(w=[1,0,0]);const L=[y[1]*w[2]-y[2]*w[1],y[2]*w[0]-y[0]*w[2],y[0]*w[1]-y[1]*w[0]],k=Math.sqrt(L[0]*L[0]+L[1]*L[1]+L[2]*L[2]),H=[L[0]/k,L[1]/k,L[2]/k],z=[H[1]*y[2]-H[2]*y[1],H[2]*y[0]-H[0]*y[2],H[0]*y[1]-H[1]*y[0]],q=[[x,b],[b,[b[0]+-.5*y[0]+H[0]*S,b[1]+-.5*y[1]+H[1]*S,b[2]+-.5*y[2]+H[2]*S]],[b,[b[0]+-.5*y[0]-H[0]*S,b[1]+-.5*y[1]-H[1]*S,b[2]+-.5*y[2]-H[2]*S]],[b,[b[0]+-.5*y[0]+z[0]*S,b[1]+-.5*y[1]+z[1]*S,b[2]+-.5*y[2]+z[2]*S]],[b,[b[0]+-.5*y[0]-z[0]*S,b[1]+-.5*y[1]-z[1]*S,b[2]+-.5*y[2]-z[2]*S]],[[x[0]-.3,x[1],x[2]],[x[0]+.3,x[1],x[2]]],[[x[0],x[1]-.3,x[2]],[x[0],x[1]+.3,x[2]]],[[x[0],x[1],x[2]-.3],[x[0],x[1],x[2]+.3]]];this.updateVertexBuffer(q,g)}}Object.freeze(DrawDebuggerDirectionalLight);class PickingEvent{pickingId;mouseX;mouseY;target;time;type;movementX=0;movementY=0;point=create$3();distance=0;localPoint=create$3();localX=0;localY=0;localZ=0;uv=create();ray;faceIndex=-1;altKey=!1;ctrlKey=!1;shiftKey=!1;constructor(i,g,x,v,_,y,b,S){this.pickingId=i,this.mouseX=g,this.mouseY=x,this.target=v,this.time=_,this.type=y,this.altKey=b.altKey,this.ctrlKey=b.ctrlKey,this.shiftKey=b.shiftKey,S&&(this.point=S.point,this.localPoint=S.localPoint,this.localX=S.localPoint[0],this.localY=S.localPoint[1],this.localZ=S.localPoint[2],this.distance=S.distance,this.faceIndex=S.faceIndex,this.uv=S.uv,this.ray=S.ray)}}Object.freeze(PickingEvent);class Ray{origin;direction;constructor(i=create$3(),g=fromValues$3(0,0,-1)){this.origin=clone$3(i),this.direction=clone$3(g)}clone(){return new Ray(this.origin,this.direction)}applyMatrix4(i){transformMat4$2(this.origin,this.origin,i);const g=create$3();copy$3(g,this.direction);const x=clone$4(i);return x[12]=x[13]=x[14]=0,transformMat4$2(this.direction,g,x),normalize$3(this.direction,this.direction),this}intersectBox(i){let g=-1/0,x=1/0;for(let v=0;v<3;v++){const _=1/this.direction[v],y=0===v?i.minX:1===v?i.minY:i.minZ,b=0===v?i.maxX:1===v?i.maxY:i.maxZ;let S=(y-this.origin[v])*_,w=(b-this.origin[v])*_;if(S>w){const i=S;S=w,w=i}g=Math.max(g,S),x=Math.min(x,w)}return x>=g&&x>=0}intersectTriangle(i,g,x,v=!0){const _=create$3(),y=create$3(),b=create$3(),S=create$3(),w=create$3();subtract$2(_,g,i),subtract$2(y,x,i),cross$2(b,this.direction,y);const L=dot$3(_,b);if(v){if(L<1e-5)return null}else if(L>-1e-5&&L<1e-5)return null;const k=1/L;subtract$2(S,this.origin,i);const H=k*dot$3(S,b);if(H<0||H>1)return null;cross$2(w,S,_);const z=k*dot$3(this.direction,w);if(z<0||H+z>1)return null;const q=k*dot$3(y,w);if(q>1e-5){const i=create$3();return scaleAndAdd$2(i,this.origin,this.direction,q),i}return null}intersectTriangleBarycentric(i,g,x,v=!0){const _=create$3(),y=create$3(),b=create$3(),S=create$3(),w=create$3();subtract$2(_,g,i),subtract$2(y,x,i),cross$2(b,this.direction,y);const L=dot$3(_,b);if(v){if(L<1e-5)return null}else if(L>-1e-5&&L<1e-5)return null;const k=1/L;subtract$2(S,this.origin,i);const H=k*dot$3(S,b);if(H<0||H>1)return null;cross$2(w,S,_);const z=k*dot$3(this.direction,w);if(z<0||H+z>1)return null;const q=k*dot$3(y,w);if(q>1e-5){const i=create$3();return scaleAndAdd$2(i,this.origin,this.direction,q),{point:i,t:q,u:H,v:z}}return null}}Object.freeze(Ray);class Raycaster3D{ray;near=0;far=1/0;#ou=create$4();#uu=create$4();#lu=create$4();#cu=create$3();#Ri;#hu=create();constructor(){this.ray=new Ray}setFromCamera(i,g,x){const{rawCamera:v,redGPUContext:_}=x,y=fromValues$3(v.x,v.y,v.z),b=x.screenToWorld(i,g),S=create$3();subtract$2(S,b,y),normalize$3(S,S),copy$3(this.ray.origin,y),copy$3(this.ray.direction,S),this.#Ri=x;const{pixelRectObject:w}=x,L=window.devicePixelRatio,k=_.renderScale,H=g*L*k,z=i*L*k/w.width*2-1,q=-H/w.height*2+1;set(this.#hu,z,q),"nearClipping"in v&&(this.near=v.nearClipping),"farClipping"in v&&(this.far=v.farClipping)}intersectObject(i,g=!0){const x=[];return this.#fu(i,g,x),x.sort((i,g)=>i.distance-g.distance)}intersectObjects(i,g=!0){const x=[];for(const v of i)this.#fu(v,g,x);return x.sort((i,g)=>i.distance-g.distance)}#fu(i,g,x){const v=i.useBillboard,_=i._renderRatioX||1,y=i._renderRatioY||1;if(v&&this.#Ri){i.usePixelSize?this.#du(i,x):this.#mu(i,x)}else if(i.geometry){const g=this.#uu;if(copy$4(g,i.modelMatrix),1!==_||1!==y)scale$4(g,g,[_,y,1]),this.#pu(i,g,x,!0);else{const g=i.boundingAABB;this.ray.intersectBox(g)&&this.#pu(i,i.modelMatrix,x,!0)}}if(g&&i.children)for(const v of i.children)this.#fu(v,g,x)}#du(i,x){const v=this.#Ri,_=i.modelMatrix,y=i.pixelSize;g(i.fontSize);const b=i._renderRatioX||1,S=i._renderRatioY||1,{rawCamera:w,projectionMatrix:L,pixelRectObject:k}=v,H=fromValues$3(_[12],_[13],_[14]),z=transformMat4$2(this.#cu,H,w.viewMatrix),q=transformMat4$1(this.#ou,fromValues$2(z[0],z[1],z[2],1),L);if(q[3]<=0)return;const W=q[0]/q[3],be=q[1]/q[3],je=this.#hu[0],Ke=this.#hu[1],Xe=y*window.devicePixelRatio,Ye=Xe/k.width*2*(b/S),Ze=Xe/k.height*2;if(Math.abs(je-W)<=.5*Ye&&Math.abs(Ke-be)<=.5*Ze){const g=distance$2(this.ray.origin,H);if(g>=this.near&&g<=this.far){const v=(je-W)/Ye+.5,_=(Ke-be)/Ze+.5;x.push({distance:g,point:H,localPoint:fromValues$3(0,0,0),object:i,faceIndex:0,uv:fromValues(v,1-_),ray:this.ray.clone()})}}}#mu(i,g){const x=this.#Ri,v=i.modelMatrix,_=i._renderRatioX||1,y=i._renderRatioY||1,b=invert$1(this.#uu,x.rawCamera.viewMatrix),S=this.#lu;copy$4(S,b),S[12]=v[12],S[13]=v[13],S[14]=v[14];scale$4(S,S,[Math.hypot(v[0],v[1],v[2])*_,Math.hypot(v[4],v[5],v[6])*y,Math.hypot(v[8],v[9],v[10])]),this.#pu(i,S,g,!1)}#pu(i,g,x,v){const _=new Ray;copy$3(_.origin,this.ray.origin),copy$3(_.direction,this.ray.direction);const y=invert$1(this.#ou,g);if(y){_.applyMatrix4(y);const b=i.geometry,S=b.vertexBuffer,w=b.indexBuffer,L=S.data,k=S.interleavedStruct.arrayStride/4;if(w){const y=w.data;for(let b=0;b=this.near&&z<=this.far){const x=fromValues(v[y*_+6],v[y*_+7]),q=fromValues(v[b*_+6],v[b*_+7]),W=fromValues(v[S*_+6],v[S*_+7]),be=create();scaleAndAdd(be,be,x,1-L-k),scaleAndAdd(be,be,q,L),scaleAndAdd(be,be,W,k),w.push({distance:z,point:H,localPoint:i,object:g,faceIndex:Math.floor(y/3),uv:be,ray:this.ray.clone()})}}}}Object.freeze(Raycaster3D);class Raycaster2D{ray;#Ri;#xu=create$3();#ou=create$4();#uu=create$4();#cu=create$3();constructor(){this.ray=new Ray}setFromCamera(i,g,x){this.#Ri=x;const{pixelRectObject:v}=x,_=i*devicePixelRatio/v.width*2-1,y=1-g*devicePixelRatio/v.height*2;set$3(this.#xu,_,y,0);const b=x.screenToWorld(i,g);set$3(this.ray.origin,b[0],b[1],b[2]),set$3(this.ray.direction,0,0,-1)}intersectObject(i,g=!0){const x=[];return this.#fu(i,g,x),x.sort((i,g)=>i.distance-g.distance)}intersectObjects(i,g=!0){const x=[];for(const v of i)this.#fu(v,g,x);return x.sort((i,g)=>i.distance-g.distance)}#fu(i,g,x){if(i.geometry){const g=this.#Ri,v=g.projectionMatrix,_=g.rawCamera.viewMatrix,y=multiply$4(this.#ou,v,_);multiply$4(y,y,i.modelMatrix);const b=invert$1(this.#uu,y);if(b){const g=transformMat4$2(this.#cu,this.#xu,b);let y=!1,S=1,w=1;if(i.is2DMeshType?(S=i.width,w=i.height,g[0]>=-S/2&&g[0]<=S/2&&g[1]>=-w/2&&g[1]<=w/2&&(y=!0)):g[0]>=-.5&&g[0]<=.5&&g[1]>=-.5&&g[1]<=.5&&(y=!0),y){const y=invert$1(create$4(),multiply$4(create$4(),v,_)),b=transformMat4$2(create$3(),this.#xu,y),L=g[0]/S>g[1]/w?1:0;x.push({distance:0,point:b,localPoint:clone$3(g),object:i,uv:fromValues(g[0]/S+.5,g[1]/w+.5),ray:this.ray.clone(),faceIndex:L})}}}if(g&&i.children)for(const v of i.children)this.#fu(v,g,x)}}Object.freeze(Raycaster2D);const updateViewportAndScissor=(i,g,x="DEFAULT")=>{const{scene:v,pixelRectObject:_,pickingManager:y,redGPUContext:b}=i,{width:S,height:w}=_;if("SHADOW"===x){const{shadowManager:i}=v,{directionalShadowManager:x}=i,_=x.shadowDepthTextureSize;g.setViewport(0,0,_,_,0,1),g.setScissorRect(0,0,_,_)}else if("PICKING"===x){const i=window.devicePixelRatio*b.renderScale,x=Math.floor(y.mouseX*i),v=Math.floor(y.mouseY*i);g.setViewport(0,0,S,w,0,1),g.setScissorRect(Math.max(0,Math.min(S-1,x)),Math.max(0,Math.min(w-1,v)),1,1)}else g.setViewport(0,0,S,w,0,1),g.setScissorRect(0,0,S,w)},renderListForLayer=(i,g,x="pipeline")=>{let v=0;const _=i.length,{currentRenderPassEncoder:y,renderResults:b}=g;for(y.setBindGroup(0,g.view.systemUniform_Vertex_UniformBindGroup);v<_;v++){const g=i[v];if(g.passFrustumCulling&&g.gpuRenderInfo){const i=g._geometry,v=g._material;i?b.num3DObjects++:b.num3DGroups++;const{gpuRenderInfo:_}=g,{vertexUniformBindGroup:S}=_;if(i&&_[x]){y.setPipeline(_[x]);const{gpuBuffer:g}=i.vertexBuffer,{fragmentUniformBindGroup:w}=v.gpuRenderInfo;if(y.setVertexBuffer(0,g),y.setBindGroup(1,S),y.setBindGroup(2,w),b.numDrawCalls++,i.indexBuffer){const{indexBuffer:g}=i,{indexCount:x,triangleCount:v,gpuBuffer:_,format:S}=g;y.setIndexBuffer(_,S),y.drawIndexed(x,1,0,0,0),b.numTriangles+=v,b.numPoints+=x}else{const{vertexBuffer:g}=i,{vertexCount:x,triangleCount:v}=g;y.draw(x,1,0,0),b.numTriangles+=v,b.numPoints+=x}}}}};class PickingManager extends RedGPUObject{lastMouseEvent;lastMouseClickEvent;#vu;#_u;#yu;#bu;#Ri;#Su=[];#Tu=0;#wu=0;#Mu;#Pu;#H=0;#Ru=new Raycaster3D;#Cu=new Raycaster2D;#Bu;#Gi=!1;#Du;constructor(i){super(i.redGPUContext),this.#Ri=i}get videoMemorySize(){return this.#H}get mouseX(){return this.#Tu}set mouseX(i){this.#Tu=i}get mouseY(){return this.#wu}set mouseY(i){this.#wu=i}get castingList(){return this.#Su}get pickingGPUTexture(){return this.#yu}get pickingGPUTextureView(){return this.#bu}get pickingDepthGPUTextureView(){return this.#_u}get pickingPassDescriptor(){return this.#Du}render(i){if(this.castingList.length){const{redGPUContext:g}=i;this.#Eu(i);const x=this.#Su;let v=0;const _=x.length;for(;v<_;v++){const i=x[v],{gpuRenderInfo:g}=i;g&&!g.pickingPipeline&&(g.pickingPipeline=g.vertexStructInfo.vertexEntries.includes("entryPointPickingVertex")?createBasePipeline(i,g.vertexShaderModule,g.vertexBindGroupLayout,dn):null)}this.#Du={label:`${i.name} Picking Render Pass`,colorAttachments:[{view:this.pickingGPUTextureView,clearValue:{r:0,g:0,b:0,a:0},loadOp:z.CLEAR,storeOp:q.STORE}],depthStencilAttachment:{view:this.pickingDepthGPUTextureView,depthClearValue:1,depthLoadOp:z.CLEAR,depthStoreOp:q.STORE}},g.commandEncoderManager.addMainRenderPass(this.pickingPassDescriptor,g=>{updateViewportAndScissor(i,g,"PICKING"),((i,g)=>{const{renderViewStateData:x,pickingManager:v}=i;x.currentRenderPassEncoder=g;const{castingList:_}=v;renderListForLayer(_,x,"pickingPipeline")})(i,g)})}this.#Iu(i)}resetCastingList(){this.#Su.length=0}destroy(){this.#yu&&(this.#yu.destroy(),this.#vu.destroy(),this.#yu=null,this.#bu=null,this.#vu=null,this.#_u=null)}async checkEvents(i,g){if(this.castingList.length&&!this.#Gi){const{pixelRectArray:x,redGPUContext:v}=i,_=window.devicePixelRatio*v.renderScale,y=this.#Tu,b=this.#wu,S=y*_,w=b*_;if(S>=0&&S=0&&w=L[2]||z<0||z>=L[3]||(this.#Bu||(this.#Bu=g.createBuffer({size:4,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,label:"PickingManager_ReadPixelBuffer"})),x.useEncoder(k.MAIN,i=>{const g={texture:this.#yu,origin:{x:H,y:z,z:0}},x={buffer:this.#Bu,bytesPerRow:256,rowsPerImage:1};i.copyTextureToBuffer(g,x,{width:1,height:1,depthOrArrayLayers:1})}))}#ci(){const i=this.#yu;if(!i)return 0;this.#H=calculateTextureByteSize(i)+calculateTextureByteSize(this.#vu)}#Ou(i,g){const{resourceManager:x}=this;return x.createManagedTexture({size:[this.#Ri.pixelRectObject.width,this.#Ri.pixelRectObject.height,1],usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC,format:g,sampleCount:1,label:`${this.#Ri.name}_${i}_${this.#Ri.pixelRectObject.width}x${this.#Ri.pixelRectObject.height}`})}#Au=()=>this.#Su.reduce((i,g)=>(i[g.pickingId]=g,i),{});#Vu(i,g,x,v,_,y,b){const S="Camera2D"===this.#Ri.rawCamera.constructor.name?this.#Cu:this.#Ru;let w;if(S.setFromCamera(this.#Tu,this.#wu,this.#Ri),v){w=S.intersectObject(v)[0]}const L=new PickingEvent(i,g,x,v,_,y,b,w);return L.ray||(L.ray=S.ray.clone()),L}#Uu=(g,x,v,_,y)=>{const b=y[g],S=this.lastMouseClickEvent?.type;if(S===i.CLICK){const i=this.#Vu(g,x,v,b,_,S,this.lastMouseClickEvent);this.#Nu(S,i)}};#ku=(g,x,v,_,y)=>{const b=y[g],S=this.lastMouseEvent?.type;if(S){const y=this.#Vu(g,x,v,b,_,S,this.lastMouseEvent);switch(this.#Mu&&(y.movementX=x-this.#Mu.mouseX,y.movementY=v-this.#Mu.mouseY),S){case i.DOWN:case i.UP:this.#Nu(S,y);break;case i.MOVE:this.#Fu(g,b,y)}this.#Mu=y}};#Fu=(g,x,v)=>{const _=this.#Mu?.pickingId;_!==g?(this.#Mu&&_&&_!==g&&this.#Gu(),this.#Pu!==x&&(this.#Nu(i.OVER,v),document.body.style.cursor="pointer"),this.#Pu=x):this.#Nu(i.MOVE,v)};#Gu=()=>{this.#Mu&&this.#Nu(i.OUT,this.#Mu),this.#Mu=null,this.#Pu=null,document.body.style.cursor="default"};async#Lu(i){await i.mapAsync(GPUMapMode.READ);const g=new DataView(i.getMappedRange()),x="rgba8unorm"==this.#yu.format?[0,1,2,3]:[2,1,0,3],v=g.getUint8(x[0]),_=g.getUint8(x[1]),y=g.getUint8(x[2]),b=g.getUint8(x[3]);return i.unmap(),(b<<24|y<<16|_<<8|v)>>>0}#Nu(i,g){g.target&&g.target.events[i]&&g.target.events[i](g)}}Object.freeze(PickingManager);class FXAA extends ASinglePassPostEffect{constructor(i){super(i),this.isLdr=!0,this.init(i,"POST_EFFECT_FXAA",createBasicPostEffectCode(this,"let index=global_id.xy;let dims=textureDimensions(sourceTexture);let i_index=vec2(index);let colorM4=textureLoad(sourceTexture,index,0);let lumaM=getLuminance(colorM4.rgb);let colorN4=fetchColor4(i_index+vec2(0,-1),dims);let colorS4=fetchColor4(i_index+vec2(0,1),dims);let colorW4=fetchColor4(i_index+vec2(-1,0),dims);let colorE4=fetchColor4(i_index+vec2(1,0),dims);let lumaN=getLuminance(colorN4.rgb);let lumaS=getLuminance(colorS4.rgb);let lumaW=getLuminance(colorW4.rgb);let lumaE=getLuminance(colorE4.rgb);let lumaMin=min(lumaM,min(min(lumaN,lumaS),min(lumaW,lumaE)));let lumaMax=max(lumaM,max(max(lumaN,lumaS),max(lumaW,lumaE)));let range=lumaMax-lumaMin;if(range(-1,-1),dims).rgb);let lumaNE=getLuminance(fetchColor4(i_index+vec2(1,-1),dims).rgb);let lumaSW=getLuminance(fetchColor4(i_index+vec2(-1,1),dims).rgb);let lumaSE=getLuminance(fetchColor4(i_index+vec2(1,1),dims).rgb);let edgeVer=abs(lumaNW+lumaSW-2.0*lumaW)+abs(lumaN+lumaS-2.0*lumaM)*2.0+abs(lumaNE+lumaSE-2.0*lumaE);let edgeHor=abs(lumaNW+lumaNE-2.0*lumaN)+abs(lumaW+lumaE-2.0*lumaM)*2.0+abs(lumaSW+lumaSE-2.0*lumaS);let isHorizontal=edgeHor>=edgeVer;let luma1=select(lumaW,lumaN,isHorizontal);let luma2=select(lumaE,lumaS,isHorizontal);let gradient1=luma1-lumaM;let gradient2=luma2-lumaM;let is1Steeper=abs(gradient1)>=abs(gradient2);let gradientScaled=0.25*max(abs(gradient1),abs(gradient2));var lumaLocalAverage=.0;var edgeStep=vec2(0,0);if(is1Steeper){edgeStep=select(vec2(-1,0),vec2(0,-1),isHorizontal);lumaLocalAverage=0.5*(luma1+lumaM);}else{edgeStep=select(vec2(1,0),vec2(0,1),isHorizontal);lumaLocalAverage=0.5*(luma2+lumaM);}var posP=i_index+edgeStep;var posN=i_index+edgeStep;let searchStep=select(vec2(1,0),vec2(0,1),isHorizontal);var doneP=false;var doneN=false;for(var i=0;i<10;i++){if(!doneP){if(abs(getLuminance(fetchColor4(posP,dims).rgb)-lumaLocalAverage)>=gradientScaled){doneP=true;}else{posP+=searchStep;}}if(!doneN){if(abs(getLuminance(fetchColor4(posN,dims).rgb)-lumaLocalAverage)>=gradientScaled){doneN=true;}else{posN-=searchStep;}}if(doneP&&doneN){break;}}let distP=select(f32(posP.x-i_index.x),f32(posP.y-i_index.y),isHorizontal);let distN=select(f32(i_index.x-posN.x),f32(i_index.y-posN.y),isHorizontal);let distMin=min(abs(distP),abs(distN));let edgeBlend=saturate(0.5-distMin/(abs(distP)+abs(distN)));let lumaL=(lumaN+lumaS+lumaW+lumaE)*2.0;let lumaCorners=lumaNW+lumaNE+lumaSW+lumaSE;let subpixFilter=saturate(abs((lumaL+lumaCorners)/12.0-lumaM)/range);let subpixBlend=smoothstep(.0,1.0,subpixFilter)*uniforms.subpix;let finalBlend=max(edgeBlend,subpixBlend);let colorTarget4=fetchColor4(i_index+edgeStep,dims);let finalColor4=mix(colorM4,colorTarget4,finalBlend);textureStore(outputTexture,index,finalColor4);","struct Uniforms{subpix:f32,edgeThreshold:f32,edgeThresholdMin:f32,padding:f32};#redgpu_include color.getLuminance fn fetchColor4(pos:vec2,dims:vec2)->vec4{let p=vec2(clamp(vec2(pos),vec2(0),dims-1));return textureLoad(sourceTexture,p,0);}"))}}definePositiveNumber(FXAA,[{key:"edgeThresholdMin",value:.0625,min:1e-5,max:.1},{key:"edgeThreshold",value:.125,min:1e-4,max:.25},{key:"subpix",value:.75,min:0,max:1}]),Object.freeze(FXAA);class TAA extends ASinglePassPostEffect{#Hu;#zu;#$u=0;#ju=.5;#Ku=[0,0];#Xu=create$4();#H=0;#Wr;constructor(i){super(i,{x:8,y:8,z:1}),this.isLdr=!0,this.init(i,"POST_EFFECT_TAA",createBasicPostEffectCode(this,"{let pixelCoord=vec2(global_id.xy);let screenSizeU=textureDimensions(sourceTexture);let screenSize=vec2(screenSizeU);let yFlipVec2=vec2(1.0,-1.0);if(any(pixelCoord>=vec2(screenSizeU))){return;}let currentUV=(vec2(pixelCoord)+0.5-uniforms.currJitterOffset*yFlipVec2)/screenSize;let stats=calculate_neighborhood_stats_ycocg(pixelCoord,screenSizeU);let currentRGBA=textureSampleLevel(sourceTexture,basicSampler,currentUV,.0);let currentRGB=currentRGBA.rgb;let currentAlpha=currentRGBA.a;let currentYCoCg=rgbToYCoCg(currentRGB);let currentDepth=textureLoad(depthTexture,pixelCoord,0);var closestDepth=1.0;var closestCoord=pixelCoord;for(var y:i32=-1;y<=1;y++){for(var x:i32=-1;x<=1;x++){let sc=clamp(pixelCoord+vec2(x,y),vec2(0),vec2(screenSizeU)-1);let d=textureLoad(depthTexture,sc,0);if(d0.5;if(jitterDisabled){textureStore(outputTexture,pixelCoord,vec4(currentRGB,currentAlpha));return;}let historyUV=(vec2(pixelCoord)+0.5-uniforms.currJitterOffset*yFlipVec2+uniforms.prevJitterOffset*yFlipVec2)/screenSize-velocity;var finalRGB:vec3;var finalAlpha:f32;if(any(historyUV(.0))||any(historyUV>vec2(1.0))){finalRGB=currentRGB;finalAlpha=currentAlpha;}else{let prevDepth=fetch_depth_bilinear(historyUV,screenSize);let historyData=sample_texture_catmull_rom_antiflicker(historyTexture,basicSampler,historyUV,screenSize);let motionLen=length(velocity*screenSize);let motionSoft=smoothstep(.0,1.0,motionLen);let clippedYCoCg=clip_history_ycocg(historyData.ycocg,stats,motionSoft);let clippedAlpha=clamp(historyData.alpha,stats.minAlpha,stats.maxAlpha);let clippedHistoryRGB=YCoCgToRgb(clippedYCoCg);let lumaWeight=get_color_discrepancy_weight(stats,clippedHistoryRGB);var blendFactor=mix(.08,0.4,motionSoft);let depthConfidence=get_depth_confidence(currentDepth,prevDepth);blendFactor=max(blendFactor,1.0-depthConfidence*depthConfidence);blendFactor=max(blendFactor,lumaWeight*0.5);let currentRGBA_final=vec4(currentRGB,currentAlpha);let clippedHistoryRGBA=vec4(clippedHistoryRGB,clippedAlpha);let finalRGBA=mix(clippedHistoryRGBA,currentRGBA_final,blendFactor);finalRGB=finalRGBA.rgb;finalAlpha=finalRGBA.a;}textureStore(outputTexture,pixelCoord,vec4(finalRGB,finalAlpha));}","#redgpu_include color.getLuminance #redgpu_include color.rgbToYCoCg #redgpu_include color.YCoCgToRgb #redgpu_include depth.getLinearizeDepth #redgpu_include math.EPSILON struct Uniforms{frameIndex:f32,currJitterOffset:vec2,prevJitterOffset:vec2,};struct NeighborhoodStats{minColor:vec3,maxColor:vec3,mean:vec3,stdDev:vec3,minAlpha:f32,maxAlpha:f32,meanAlpha:f32,meanLuminance:f32,stdDevLuminance:f32,};struct SampledColor{rgb:vec3,ycocg:vec3,alpha:f32,};fn get_depth_confidence(currDepth:f32,prevDepth:f32)->f32{let currLinear=getLinearizeDepth(currDepth,systemUniforms.camera.nearClipping,systemUniforms.camera.farClipping);let prevLinear=getLinearizeDepth(prevDepth,systemUniforms.camera.nearClipping,systemUniforms.camera.farClipping);let depthDiff=abs(currLinear-prevLinear);return 1.0-clamp((depthDiff-0.1)/0.4,.0,1.0);}fn fetch_depth_bilinear(uv:vec2,screenSize:vec2)->f32{let samplePos=uv*screenSize-0.5;let f=fract(samplePos);let base=vec2(floor(samplePos));let size=vec2(textureDimensions(prevDepthTexture));let d00=textureLoad(prevDepthTexture,clamp(base+vec2(0,0),vec2(0),size-1),0);let d10=textureLoad(prevDepthTexture,clamp(base+vec2(1,0),vec2(0),size-1),0);let d01=textureLoad(prevDepthTexture,clamp(base+vec2(0,1),vec2(0),size-1),0);let d11=textureLoad(prevDepthTexture,clamp(base+vec2(1,1),vec2(0),size-1),0);return mix(mix(d00,d10,f.x),mix(d01,d11,f.x),f.y);}fn calculate_neighborhood_stats_ycocg(pixelCoord:vec2,screenSizeU:vec2)->NeighborhoodStats{let screenSize=vec2(screenSizeU);var m1=vec3(.0);var m2=vec3(.0);var m1L=.0;var m2L=.0;var m1A=.0;var minC=vec3(1e5);var maxC=vec3(-1e5);var minA=1e5;var maxA=-1e5;for(var y:i32=-1;y<=1;y++){for(var x:i32=-1;x<=1;x++){let sampleCoord=clamp(pixelCoord+vec2(x,y),vec2(0),vec2(screenSizeU)-1);let colorRGBA=textureLoad(sourceTexture,sampleCoord,0);let colorRGB=colorRGBA.rgb;let colorYCoCg=rgbToYCoCg(colorRGB);let lum=getLuminance(colorRGB);let alpha=colorRGBA.a;m1+=colorYCoCg;m2+=colorYCoCg*colorYCoCg;m1L+=lum;m2L+=lum*lum;m1A+=alpha;minC=min(minC,colorYCoCg);maxC=max(maxC,colorYCoCg);minA=min(minA,alpha);maxA=max(maxA,alpha);}}let sampleCount=9.0;var stats:NeighborhoodStats;stats.mean=m1/sampleCount;stats.stdDev=sqrt(max((m2/sampleCount)-(stats.mean*stats.mean),vec3(.0)));stats.meanLuminance=m1L/sampleCount;stats.stdDevLuminance=sqrt(max((m2L/sampleCount)-(stats.meanLuminance*stats.meanLuminance),.0));stats.minColor=minC;stats.maxColor=maxC;stats.minAlpha=minA;stats.maxAlpha=maxA;stats.meanAlpha=m1A/sampleCount;return stats;}fn get_color_discrepancy_weight(stats:NeighborhoodStats,histRGB:vec3)->f32{let histLuminance=getLuminance(histRGB);let diff=abs(stats.meanLuminance-histLuminance);let threshold=max(stats.stdDevLuminance*0.45,.01);return smoothstep(threshold,threshold*2.0,diff);}fn sample_texture_catmull_rom_antiflicker(tex:texture_2d,smp:sampler,uv:vec2,texSize:vec2)->SampledColor{let samplePos=uv*texSize;let texPos1=floor(samplePos-0.5)+0.5;let f=samplePos-texPos1;let w0=f*(-0.5+f*(1.0-0.5*f));let w1=1.0+f*f*(-2.5+1.5*f);let w2=f*(0.5+f*(2.0-1.5*f));let w3=f*f*(-0.5+0.5*f);let w12=w1+w2;let offset12=w2/w12;let invTexSize=1.0/texSize;let coords=array,5>((texPos1+vec2(offset12.x,-1.0))*invTexSize,(texPos1+vec2(-1.0,offset12.y))*invTexSize,(texPos1+offset12)*invTexSize,(texPos1+vec2(2.0,offset12.y))*invTexSize,(texPos1+vec2(offset12.x,2.0))*invTexSize);let weights=array(w12.x*w0.y,w0.x*w12.y,w12.x*w12.y,w3.x*w12.y,w12.x*w3.y);var sumRGB=vec3(.0);var sumYCoCg=vec3(.0);var sumAlpha=.0;var sumW=.0;for(var i=0;i<5;i++){let sampleRGBA=textureSampleLevel(tex,smp,coords[i],.0);let sampleRGB=max(sampleRGBA.rgb,vec3(.0));let sampleYCoCg=rgbToYCoCg(sampleRGB);let sampleLum=getLuminance(sampleRGB);let w=weights[i]*(1.0/(1.0+sampleLum));sumRGB+=sampleRGB*w;sumYCoCg+=sampleYCoCg*w;sumAlpha+=sampleRGBA.a*w;sumW+=w;}var result:SampledColor;let invSumW=1.0/max(sumW,EPSILON);result.rgb=sumRGB*invSumW;result.ycocg=sumYCoCg*invSumW;result.alpha=sumAlpha*invSumW;return result;}fn clip_history_ycocg(historyYCoCg:vec3,stats:NeighborhoodStats,motion:f32)->vec3{let gamma=mix(0.2,0.7,motion);let v_min=min(stats.minColor,stats.mean-stats.stdDev*gamma);let v_max=max(stats.maxColor,stats.mean+stats.stdDev*gamma);return clamp(historyYCoCg,v_min,v_max);}",[{name:"sourceTexture"},{name:"historyTexture"}])),this.jitterStrength=this.#ju}get prevNoneJitterProjectionViewMatrix(){return this.#Xu}get frameIndex(){return this.#$u}get videoMemorySize(){return this.#H}get jitterStrength(){return this.#ju}set jitterStrength(i){this.#ju=i}render(i,g,x,v){const{redGPUContext:_}=this,{commandEncoderManager:y}=_;this.#$u++,this.updateUniform("frameIndex",this.#$u),this.updateUniform("currJitterOffset",i.jitterOffset),this.updateUniform("prevJitterOffset",this.#Ku),copy$4(this.#Xu,i.noneJitterProjectionViewMatrix),this.#Ku=[...i.jitterOffset],this.#qu(g,x);const b={texture:this.#Hu,textureView:this.#zu},S=super.render(i,g,x,v,b);return y.useEncoder(k.POST_PROCESS,i=>{i.copyTextureToTexture({texture:S.texture},{texture:this.#Hu},[g,x,1])}),this.#$u<=20||this.#$u,S}clear(){super.clear(),this.#Hu&&(this.#Hu.destroy(),this.#Hu=null,this.#zu=null),this.#Wr=null}#qu(i,g){if(this.#Wr?.width!==i||this.#Wr?.height!==g||!this.#Hu){this.#Hu&&this.#Hu.destroy();const{resourceManager:x}=this.redGPUContext;this.#Hu=x.createManagedTexture({size:{width:i,height:g},format:"rgba16float",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST,label:`TAA_HistoryTexture_${i}x${g}`}),this.#zu=x.getGPUResourceBitmapTextureView(this.#Hu,{dimension:"2d",format:"rgba16float",label:"TAA_HistoryTextureView"}),this.#Wr={width:i,height:g},this.#Yu()}}#Yu(){this.#H=this.uniformBuffer?this.uniformBuffer.size:0,this.#Hu&&(this.#H+=calculateTextureByteSize(this.#Hu))}}let Gn,On,Vn,Nn,Fn;Object.freeze(TAA);let Hn,zn=create$3(),$n=create$4(),jn=create$4();const screenToWorld=(i,g,x)=>{const{rawCamera:v,pixelRectArray:_}=x;return Gn=2*(i*window.devicePixelRatio+_[0])/_[2]-1,On=-2*(g*window.devicePixelRatio+_[1])/_[3]+1,Vn=1,multiply$4(jn,x.noneJitterProjectionMatrix,v.viewMatrix),Hn=clone$4(jn),invert$1(Hn,Hn),zn=fromValues$3(Gn,On,1),identity$1($n),translate($n,$n,zn),multiply$4(Hn,Hn,$n),zn[0]=Hn[12],zn[1]=Hn[13],zn[2]=Hn[14],Nn=jn[12]*Gn+jn[13]*On+jn[15],0!==Nn&&(Fn=1/Nn,zn[0]/=Fn,zn[1]/=Fn,zn[2]/=Fn,zn[0]=zn[0]+v.x,zn[1]=zn[1]+v.y,zn[2]=zn[2]+v.z),[zn[0],zn[1],zn[2]]};class Box extends Primitive{constructor(i,g=1,x=1,v=1,_=1,y=1,b=1){const S=Primitive.generateUniqueKey("BOX",{width:g,height:x,depth:v,widthSegments:_,heightSegments:y,depthSegments:b});super(i,S,()=>PrimitiveUtils.generateBoxData(i,g,x,v,_,y,b,S))}}class Cylinder extends Primitive{constructor(i,g=1,x=1,v=1,_=8,y=1,b=!0,S=!0,w=0,L=2*Math.PI,k=!1,H=!1){const z=Primitive.generateUniqueKey("CYLINDER",{radiusTop:g,radiusBottom:x,height:v,radialSegments:_,heightSegments:y,capTop:b,capBottom:S,thetaStart:w,thetaLength:L,isRadialTop:k,isRadialBottom:H});super(i,z,()=>PrimitiveUtils.generateCylinderData(i,g,x,v,_,y,b,S,w,L,k,H,z))}}class Sphere extends Primitive{constructor(i,g=1,x=16,v=16,_=0,y=2*Math.PI,b=0,S=Math.PI){const w=Primitive.generateUniqueKey("SPHERE",{radius:g,widthSegments:x,heightSegments:v,phiStart:_,phiLength:y,thetaStart:b,thetaLength:S});super(i,w,()=>PrimitiveUtils.generateSphereData(i,g,x,v,_,y,b,S,w))}}class DrawDebuggerAxis extends Mesh{constructor(i){super(i,null,null);const g=new Mesh(i,new Sphere(i,.5),new ColorMaterial(i));this.addChild(g);const x=new Box(i);this.addChild(this.#Wu(x,"#ff0000",[5,.1,.1],[2.5,0,0])),this.addChild(this.#Zu(i,"#ff0000",[.5,1.25],[5.5,0,0],[0,0,90])),this.addChild(this.#Wu(x,"#00ff00",[.1,5,.1],[0,2.5,0])),this.addChild(this.#Zu(i,"#00ff00",[.5,1.25],[0,5.5,0],[180,0,0])),this.addChild(this.#Wu(x,"#0000ff",[.1,.1,5],[0,0,2.5])),this.addChild(this.#Zu(i,"#0000ff",[.5,1.25],[0,0,5.5],[-90,0,0]))}#Wu(i,g,x,v){const{redGPUContext:_}=this,y=new Mesh(_,i,new ColorMaterial(_,g));return y.setScale(...x),y.setPosition(...v),y}#Zu(i,g,x,v,_){const y=new Mesh(i,new Cylinder(i,x[0],.001,x[1],32,1),new ColorMaterial(i,g));return y.setScale(x[0],x[1],x[0]),y.setPosition(...v),y.setRotation(..._),y}}Object.freeze(DrawDebuggerAxis);var Kn="#redgpu_include SYSTEM_UNIFORM;#redgpu_include systemStruct.OutputFragment;#redgpu_include math.getMotionVector;struct InputData{@location(0)position:vec4,@location(1)color:vec4,}struct VertexOutput{@builtin(position)position:vec4,@location(0)color:vec4,@location(1)worldPos:vec3,@location(2)currentClipPos:vec4,@location(3)prevClipPos:vec4,}struct GridArgs{lineColor:vec4,}@group(1)@binding(0)vargridArgs:GridArgs;const FADE_START:f32=20.0;const FADE_END:f32=80.0;const AXIS_THRESHOLD:f32=0.8;const AXIS_ALPHA:f32=0.8;@vertex fn vertexMain(inputData:InputData)->VertexOutput{var output:VertexOutput;let modelPos=inputData.position;let viewProj=systemUniforms.projection.noneJitterProjectionViewMatrix;let prevViewProj=systemUniforms.projection.prevNoneJitterProjectionViewMatrix;output.position=viewProj*modelPos;output.worldPos=modelPos.xyz;output.color=inputData.color;output.currentClipPos=output.position;output.prevClipPos=prevViewProj*modelPos;return output;}@fragment fn fragmentMain(inputData:VertexOutput)->OutputFragment{var output:OutputFragment;let distanceToCamera=length(inputData.worldPos-systemUniforms.camera.cameraPosition);let distanceFade=clamp(1.0-saturate((distanceToCamera-FADE_START)/(FADE_END-FADE_START)),0.5,1.0);var finalColor:vec3;var baseAlpha:f32;let isXAxis=inputData.color.r>AXIS_THRESHOLD;let isZAxis=inputData.color.b>AXIS_THRESHOLD;if(isXAxis){finalColor=vec3(1.0,.0,.0);baseAlpha=AXIS_ALPHA;}else if(isZAxis){finalColor=vec3(.0,.0,1.0);baseAlpha=AXIS_ALPHA;}else{finalColor=gridArgs.lineColor.rgb;baseAlpha=gridArgs.lineColor.a;}output.color=vec4(finalColor,baseAlpha*distanceFade);let motion=getMotionVector(inputData.currentClipPos,inputData.prevClipPos);output.gBufferMotionVector=vec4(motion,.0,1.0);return output;}";const Xn=parseWGSL("DRAW_DEBUGGER_GRID",Kn),qn=Xn.uniforms.gridArgs;class DrawDebuggerGrid extends BaseObject{#On;#Vn;#se;#Ju;#U;#Qu;#ur;#lr;#el;#qt=100;#Ns;#Os;#As;#Ls;#tl;#ls;constructor(i){super(),validateRedGPUContext(i),this.#Ns=DrawBufferManager.getInstance(i);const{resourceManager:g,gpuDevice:x}=i,v={code:Kn},_=g.createGPUShaderModule("VERTEX_MODULE_GRID",v);this.#ur=new BlendState(this),this.#lr=new BlendState(this),this.#el=new ColorRGBA(128,128,128,.25);const y=g.getGPUBindGroupLayout(ResourceManager.PRESET_GPUBindGroupLayout_System),b="GRID_MATERIAL_BIND_GROUP_LAYOUT",S=g.getGPUBindGroupLayout(b)||g.createBindGroupLayout(b,getFragmentBindGroupLayoutDescriptorFromShaderInfo(Xn,1));this.#rl(i),this.#Ju=x.createBindGroup({label:"FRAGMENT_BIND_GROUP_DESCRIPTOR_GRID",layout:S,entries:[{binding:0,resource:{buffer:this.#se.gpuBuffer,offset:0,size:this.#se.size}}]});const w={label:"PIPELINE_DESCRIPTOR_GRID",layout:x.createPipelineLayout({label:"DRAW_DEBUGGER_GRID_PIPELINE_LAYOUT",bindGroupLayouts:[y,S]}),vertex:{module:_,entryPoint:"vertexMain",buffers:[{arrayStride:this.#On.interleavedStruct.arrayStride,attributes:this.#On.interleavedStruct.attributes}]},primitive:{topology:"line-list"},fragment:{module:_,entryPoint:"fragmentMain",targets:[{format:"rgba16float",blend:{color:this.#ur.state,alpha:this.#lr.state}},{format:navigator.gpu.getPreferredCanvasFormat(),blend:void 0},{format:"rgba16float",blend:void 0}]},depthStencil:{format:"depth32float",depthWriteEnabled:!0,depthCompare:Er.LESS_EQUAL}};this.#U=x.createRenderPipeline(w),this.#Qu=x.createRenderPipeline({...w,multisample:{count:4}});const L=this.#Ns;this.#Os||(this.#Os=L.allocateDrawCommand(this.name),L.setIndexedIndirectCommand(this.#Os,this.#Vn.indexCount,1,0,0,0))}get size(){return this.#qt}set size(i){this.#qt=i}get lineColor(){return this.#el}render(i){const{view:g,currentRenderPassEncoder:x,renderResults:v}=i,{redGPUContext:_}=g,{gpuDevice:y,antialiasingManager:b}=_,{msaaID:S}=b;set$3(create$3(),g.rawCamera.x,g.rawCamera.y,g.rawCamera.z),v.num3DObjects++,v.numDrawCalls++;const w=this.#ls!==S,L=g.systemUniform_Vertex_UniformBindGroup!==this.#tl;if(this.#U){const i=2*(2*(this.#qt+1));(!this.#As||w||L)&&(this.#ls=S,this.#As=y.createRenderBundleEncoder({...g.basicRenderBundleEncoderDescriptor,label:this.name}),this.#As.setPipeline(g.redGPUContext.antialiasingManager.useMSAA?this.#Qu:this.#U),this.#As.setBindGroup(0,g.systemUniform_Vertex_UniformBindGroup),this.#As.setBindGroup(1,this.#Ju),this.#As.setVertexBuffer(0,this.#On.gpuBuffer),this.#As.setIndexBuffer(this.#Vn.gpuBuffer,this.#Vn.format),this.#As.drawIndexedIndirect(this.#Os.buffer,4*this.#Os.commandOffset),this.#Ls=this.#As.finish()),v.numTriangles+=0,v.numPoints+=i,x.executeBundles([this.#Ls])}this.#tl=g.systemUniform_Vertex_UniformBindGroup}#il(i){const g=[],x=[],v=i/2;let _=0;for(let i=-v;i<=v;i+=1){const y=0===i?[0,0,1,1]:[.5,.5,.5,1];g.push(i,0,-v,...y,i,0,v,...y),x.push(_,_+1),_+=2}for(let i=-v;i<=v;i+=1){const y=0===i?[1,0,0,1]:[.5,.5,.5,1];g.push(-v,0,i,...y,v,0,i,...y),x.push(_,_+1),_+=2}return{interleaveData:g,indexData:x}}#rl(i){const g=this.#qt,{resourceManager:x}=i,{cachedBufferState:v}=x;{const x=`VertexBuffer_Grid_${g}`;let _=v[x];if(!_){const{interleaveData:y}=this.#il(g);_=new VertexBuffer(i,y,new VertexInterleavedStruct({position:VertexInterleaveType.float32x3,color:VertexInterleaveType.float32x4}),void 0,x),v[x]=_}this.#On=_}{const x=`IndexBuffer_Grid_${g}`;let _=v[x];if(!_){const{indexData:y}=this.#il(g);_=new IndexBuffer(i,y,void 0,x),v[x]=_}this.#Vn=_}{const g="UniformBuffer_Grid";let x=v[g];if(!x){const _=new ArrayBuffer(qn.arrayBufferByteLength);x=new UniformBuffer(i,_,g,g),v[g]=x}this.#se=x}this.#se.writeOnlyBuffer(qn.members.lineColor,this.#el.rgbaNormalLinear)}}Object.freeze(DrawDebuggerGrid);class ABaseLight{drawDebugger;#nl;#al;#Bs=!1;constructor(i,g=1){this.#nl=i,this.#al=g}get enableDebugger(){return this.#Bs}set enableDebugger(i){this.#Bs=i}get color(){return this.#nl}set color(i){i instanceof ColorRGB||consoleAndThrowError("Only ColorRGB instances are allowed."),this.#nl=i}get intensityMultiplier(){return this.#al}set intensityMultiplier(i){validatePositiveNumberRange(i,0),this.#al=i}}Object.freeze(ABaseLight);class AmbientLight extends ABaseLight{#sl=0;constructor(i="#ADD8E6",g=50){super(new ColorRGB(...convertHexToRgb(i,!0))),this.#sl=g}get lux(){return this.#sl}set lux(i){this.#sl=i}}Object.freeze(AmbientLight);class DirectionalLight extends ABaseLight{#ol=-1;#ul=-1;#ll=-1;#cl=35.264389682754654;#hl=45;#sl=1e5;constructor(i=[-1,-1,-1],g="#fff",x=1e5){super(new ColorRGB(...convertHexToRgb(g,!0))),this.direction=i,this.#sl=x}get lux(){return this.#sl}set lux(i){this.#sl=i}get elevation(){return this.#cl}set elevation(i){this.#cl=i,this.#fl()}get azimuth(){return this.#hl}set azimuth(i){this.#hl=i,this.#fl()}get directionX(){return this.#ol}set directionX(i){this.#ol=i,this.#dl()}get directionY(){return this.#ul}set directionY(i){this.#ul=i,this.#dl()}get directionZ(){return this.#ll}set directionZ(i){this.#ll=i,this.#dl()}get direction(){return[this.#ol,this.#ul,this.#ll]}set direction(i){this.#ol=i[0],this.#ul=i[1],this.#ll=i[2],this.#dl()}#fl(){const i=this.#cl*Math.PI/180,g=this.#hl*Math.PI/180,x=Math.cos(i),v=x*Math.cos(g),_=Math.sin(i),y=x*Math.sin(g);this.#ol=-v,this.#ul=-_,this.#ll=-y}#dl(){const i=-this.#ol,g=-this.#ul,x=-this.#ll,v=Math.sqrt(i*i+g*g+x*x),_=i/v,y=g/v,b=x/v;this.#cl=180*Math.asin(y)/Math.PI,this.#hl=180*Math.atan2(b,_)/Math.PI}}Object.freeze(DirectionalLight);class PointLight extends ABaseLight{#ml=10;#wi=0;#Mi=0;#Pi=0;#pl=1e3;constructor(i="#fff",g=1e3){super(new ColorRGB(...convertHexToRgb(i,!0))),this.#pl=g}get lumen(){return this.#pl}set lumen(i){this.#pl=i}get x(){return this.#wi}set x(i){this.#wi=i}get y(){return this.#Mi}set y(i){this.#Mi=i}get z(){return this.#Pi}set z(i){this.#Pi=i}get position(){return[this.#wi,this.#Mi,this.#Pi]}get radius(){return this.#ml}set radius(i){this.#ml=i}setPosition(i,g,x){Array.isArray(i)?[this.#wi,this.#Mi,this.#Pi]=i:(this.#wi=i,this.#Mi=g,this.#Pi=x)}}Object.freeze(PointLight);class SpotLight extends ABaseLight{#ml=10;#wi=0;#Mi=2;#Pi=0;#ol=0;#ul=-1;#ll=0;#gl=0;#xl=44;#pl=1e3;constructor(i="#fff",g=1e3){super(new ColorRGB(...convertHexToRgb(i,!0))),this.#pl=g}get lumen(){return this.#pl}set lumen(i){this.#pl=i}get x(){return this.#wi}set x(i){this.#wi=i}get y(){return this.#Mi}set y(i){this.#Mi=i}get z(){return this.#Pi}set z(i){this.#Pi=i}get position(){return[this.#wi,this.#Mi,this.#Pi]}get radius(){return this.#ml}set radius(i){this.#ml=i}get directionX(){return this.#ol}set directionX(i){this.#ol=i}get directionY(){return this.#ul}set directionY(i){this.#ul=i}get directionZ(){return this.#ll}set directionZ(i){this.#ll=i}get direction(){return[this.#ol,this.#ul,this.#ll]}set direction(i){this.#ol=i[0],this.#ul=i[1],this.#ll=i[2]}get innerCutoff(){return this.#gl}set innerCutoff(i){this.#gl=i}get outerCutoff(){return this.#xl}set outerCutoff(i){this.#xl=i}get innerCutoffCos(){return Math.cos(this.#gl*Math.PI/180)}get outerCutoffCos(){return Math.cos(this.#xl*Math.PI/180)}setPosition(i,g,x){Array.isArray(i)?[this.#wi,this.#Mi,this.#Pi]=i:(this.#wi=i,this.#Mi=g,this.#Pi=x)}lookAt(i,g,x){let v,_,y;Array.isArray(i)?[v,_,y]=i:(v=i,_=g,y=x);const b=v-this.#wi,S=_-this.#Mi,w=y-this.#Pi,L=Math.sqrt(b*b+S*S+w*w);L>0&&(this.#ol=b/L,this.#ul=S/L,this.#ll=w/L)}}Object.freeze(SpotLight);class LightManager{#vl=3;#_l=W.MAX_CLUSTER_LIGHTS;#yl=[];#bl=[];#Sl=[];#Tl;#wl=create$4();get spotLights(){return this.#Sl}get spotLightCount(){return this.#Sl.length}get limitClusterLightCount(){return this.#_l}get pointLights(){return this.#bl}get pointLightCount(){return this.#bl.length}get limitDirectionalLightCount(){return this.#vl}get directionalLightCount(){return this.#yl.length}get directionalLights(){return this.#yl}get ambientLight(){return this.#Tl}set ambientLight(i){i instanceof AmbientLight||consoleAndThrowError("allow only AmbientLight instance"),this.#Tl=i}addSpotLight(i){i instanceof SpotLight||consoleAndThrowError("allow only SpotLight instance");this.#Sl.length+this.#bl.length>=this.#_l&&consoleAndThrowError("Cannot add more cluster lights. The limit has been reached."),this.#Sl.push(i)}addPointLight(i){i instanceof PointLight||consoleAndThrowError("allow only PointLight instance");this.#Sl.length+this.#bl.length>=this.#_l&&consoleAndThrowError("Cannot add more cluster lights. The limit has been reached."),this.#bl.push(i)}addDirectionalLight(i){i instanceof DirectionalLight||consoleAndThrowError("allow only DirectionalLight instance");this.#yl.length>=this.#vl&&consoleAndThrowError("Cannot add more directional lights. The limit has been reached."),this.#yl.push(i)}removeSpotLight(i){const g=this.#Sl.indexOf(i);-1!==g&&this.#Sl.splice(g,1)}removePointLight(i){const g=this.#bl.indexOf(i);-1!==g&&this.#bl.splice(g,1)}removeDirectionalLight(i){const g=this.#yl.indexOf(i);-1!==g&&this.#yl.splice(g,1)}removeAllSpotLight(){this.#Sl=[]}removeAllPointLight(){this.#bl=[]}removeAllDirectionalLight(){this.#yl=[]}removeAllLight(){this.removeAllPointLight(),this.removeAllSpotLight(),this.removeAllDirectionalLight(),this.#Tl=null}getDirectionalLightProjectionViewMatrix(i){return multiply$4(create$4(),this.getDirectionalLightProjectionMatrix(i),this.getDirectionalLightViewMatrix(i))}getDirectionalLightProjectionMatrix(i){const g=create$4(),x=i.rawCamera instanceof Camera2D?fromValues$3(0,0,0):fromValues$3(i.rawCamera.x,i.rawCamera.y,i.rawCamera.z),v=Math.max(distance$2(x,create$3()),1);return Dt(g,-v,v,-v,v,3*-v,3*v),g}getDirectionalLightViewMatrix(i){identity$1(this.#wl);const g=i.rawCamera instanceof Camera2D?fromValues$3(0,0,0):fromValues$3(i.rawCamera.x,i.rawCamera.y,i.rawCamera.z),x=Math.max(distance$2(g,create$3()),1),v=fromValues$3(0,1,0),_=fromValues$3(0,0,0),{directionalLights:y}=i.scene.lightManager,b=y.length?fromValues$3(-y[0].direction[0]*x,-y[0].direction[1]*x,-y[0].direction[2]*x):create$3(),S=create$4();return lookAt(S,b,_,v),S}}Object.freeze(LightManager);class DirectionalShadowManager{#Ml=2048;#Pl=.005;#Rl;#Cl;#Bl;#Dl;#h;#Su=[];#H=0;get videoMemorySize(){return this.#H}get castingList(){return this.#Su}get shadowDepthTextureView(){return this.#Cl}get shadowDepthTextureViewEmpty(){return this.#Dl}get bias(){return this.#Pl}set bias(i){validatePositiveNumberRange(i,0,1),this.#Pl=i}get shadowDepthTextureSize(){return this.#Ml}set shadowDepthTextureSize(i){validateUintRange(i,1),this.#Ml=i}reset(){this.destroy()}resetCastingList(){this.#Su.length=0}update(i){this.#h=i,this.#El()}destroy(){const{commandEncoderManager:i}=this.#h;this.#Rl&&(i.addDeferredDestroy(this.#Rl),this.#Rl=null,this.#Cl=null),this.#Bl&&(i.addDeferredDestroy(this.#Bl),this.#Bl=null,this.#Dl=null)}#ci(){const i=this.#Rl;if(!i)return 0;this.#H=calculateTextureByteSize(i)}#El(){this.#Rl?.width!==this.#Ml&&(this.destroy(),this.#Il(),this.#ci())}#Al(i){this.#Bl=i.createTexture({size:[1,1,1],usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING,format:"depth32float",label:`DirectionalShadowManager_EmptyDepthTexture_1x1_${Date.now()}`}),this.#Dl=this.#Bl.createView({label:this.#Bl.label})}#Il(){const{gpuDevice:i,resourceManager:g}=this.#h;this.#Rl=g.createManagedTexture({size:[this.#Ml,this.#Ml,1],usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING,format:"depth32float",label:`DirectionalShadowManager_shadowDepthTextureSize_${this.#Ml}x${this.#Ml}_${Date.now()}`}),this.#Cl=this.#Rl.createView({label:this.#Rl.label}),this.#Dl||this.#Al(i)}}Object.freeze(DirectionalShadowManager);class ShadowManager{#Ll=new DirectionalShadowManager;#Ul;constructor(){}get directionalShadowManager(){return this.#Ll}get shadowPassDescriptor(){return this.#Ul}render(i){if(0===this.#Ll.castingList.length)return;const{redGPUContext:g}=i,x=this.#Ll.castingList;let v=0;const _=x.length;for(;v<_;v++){const i=x[v],{gpuRenderInfo:g}=i;g&&!g.shadowPipeline&&(g.shadowPipeline=g.vertexStructInfo.vertexEntries.includes("entryPointShadowVertex")?createBasePipeline(i,g.vertexShaderModule,g.vertexBindGroupLayout,fn):null)}this.#Ul={label:`${i.name} Shadow Render Pass`,colorAttachments:[],depthStencilAttachment:{view:this.#Ll.shadowDepthTextureView,depthClearValue:1,depthLoadOp:z.CLEAR,depthStoreOp:q.STORE}},g.commandEncoderManager.addMainRenderPass(this.shadowPassDescriptor,g=>{updateViewportAndScissor(i,g,"SHADOW"),this.#Ll.castingList.length&&((i,g)=>{const{renderViewStateData:x,scene:v}=i;x.currentRenderPassEncoder=g;const{shadowManager:_}=v,{directionalShadowManager:y}=_,{castingList:b}=y;renderListForLayer(b,x,"shadowPipeline")})(i,g)}),this.#Ll.resetCastingList()}update(i){this.#Ll.update(i)}}Object.freeze(ShadowManager);class Scene extends Object3DContainer{#kl=new ColorRGBA;#Gl=!1;#Ol=new LightManager;#Vl=new ShadowManager;#Nl;constructor(i){super(),i&&(this.name=i)}get lightManager(){return this.#Ol}get shadowManager(){return this.#Vl}get physicsEngine(){return this.#Nl}set physicsEngine(i){this.#Nl=i}get backgroundColor(){return this.#kl}set backgroundColor(i){i instanceof ColorRGBA||consoleAndThrowError("allow only ColorRGBA instance"),this.#kl=i}get useBackgroundColor(){return this.#Gl}set useBackgroundColor(i){this.#Gl=i}}const validateNumberRange=(i,g=-Number.MAX_VALUE,x=Number.MAX_VALUE)=>(("number"!=typeof i||Number.isNaN(i))&&consoleAndThrowError("Only numbers allowed."),("number"!=typeof g||Number.isNaN(g))&&consoleAndThrowError("Only numbers allowed."),("number"!=typeof x||Number.isNaN(x))&&consoleAndThrowError("Only numbers allowed."),(ix)&&consoleAndThrowError(`Only numbers within the range of [${g}, ${x}] are allowed. input : ${i}`),!0);class PerspectiveCamera extends ACamera{#Fl=new Float32Array([0,1,0]);#Ti=create$4();#wi=0;#Pi=0;#Mi=0;#ys=0;#bs=0;#Ss=0;#Hl=60;#zl=.1;#$l=5e4;constructor(){super()}get rotationX(){return this.#ys}set rotationX(i){this.#ys=i}get rotationY(){return this.#bs}set rotationY(i){this.#bs=i}get rotationZ(){return this.#Ss}set rotationZ(i){this.#Ss=i}get fieldOfView(){return this.#Hl}set fieldOfView(i){validateNumber(i),this.#Hl=i}get nearClipping(){return this.#zl}set nearClipping(i){validateNumber(i),this.#zl=i}get farClipping(){return this.#$l}set farClipping(i){validateNumber(i),this.#$l=i}get viewMatrix(){return this.#Ti}get x(){return this.#wi}set x(i){this.#wi=i,this.#Ti[12]=i}get y(){return this.#Mi}set y(i){this.#Mi=i,this.#Ti[13]=i}get z(){return this.#Pi}set z(i){this.#Pi=i,this.#Ti[14]=i}get position(){return[this.#wi,this.#Mi,this.#Pi]}setPosition(i,g,x){Array.isArray(i)?[this.#wi,this.#Mi,this.#Pi]=i:(this.#wi=i,this.#Mi=g,this.#Pi=x),[this.#Ti[12],this.#Ti[13],this.#Ti[14]]=[this.#wi,this.#Mi,this.#Pi]}lookAt(i,g,x){const v=[this.#wi,this.#Mi,this.#Pi],_=[i,g,x],y=[this.#Fl[0],this.#Fl[1],this.#Fl[2]],b=[_[0]-v[0],_[1]-v[1],_[2]-v[2]],S=Math.sqrt(b[0]*b[0]+b[1]*b[1]+b[2]*b[2]);b[0]/=S,b[1]/=S,b[2]/=S;const w=[b[1]*y[2]-b[2]*y[1],b[2]*y[0]-b[0]*y[2],b[0]*y[1]-b[1]*y[0]];Math.sqrt(w[0]*w[0]+w[1]*w[1]+w[2]*w[2])<1e-4&&(y[2]=b[1]>0?1:-1,y[0]=0,y[1]=0),lookAt(this.#Ti,v,_,y)}}class OrthographicCamera extends PerspectiveCamera{#jl=1;#Kl=-1;#Xl=-1;#ql=1;#Yl=1;#Wl=.1;#Zl=10;constructor(){super(),this.nearClipping=.01,this.farClipping=1e4}get top(){return this.#jl}set top(i){validateNumber(i),this.#jl=i}get bottom(){return this.#Kl}set bottom(i){validateNumber(i),this.#Kl=i}get left(){return this.#Xl}set left(i){validateNumber(i),this.#Xl=i}get right(){return this.#ql}set right(i){validateNumber(i),this.#ql=i}get zoom(){return this.#Yl}set zoom(i){validateNumberRange(i,this.#Wl,this.#Zl),this.#Yl=i}get minZoom(){return this.#Wl}set minZoom(i){validateNumberRange(i,.01),this.#Wl=i}get maxZoom(){return this.#Zl}set maxZoom(i){validateNumberRange(i,.01),this.#Zl=i}setZoom(i){this.zoom=i}}class AController extends RedGPUObject{static#Jl=null;static#Ql=null;#ec;#tc;#rc=-1;#ic=0;#nc=new Set;#ac=!1;#sc=null;#oc=!1;#uc;#lc=0;#cc=0;#hc=0;#fc=!1;constructor(i,g){super(i),this.#tc=g||{},this.#ec=g.camera||new PerspectiveCamera;const x=this.redGPUContext.detector.isMobile;this.#uc={moveKey:x?"touchmove":"mousemove",upKey:x?"touchend":"mouseup",downKey:x?"touchstart":"mousedown"},this.#dc()}get camera(){return this.#ec}get x(){return this.camera.x}get y(){return this.camera.y}get z(){return this.camera.z}get hoveredView(){return this.#sc}get keyboardActiveView(){return AController.#Jl}set keyboardActiveView(i){AController.#Jl=i,AController.#Ql=null===i?null:this}get isKeyboardActiveController(){return AController.#Ql===this}get keyboardProcessedThisFrame(){return this.#ac}set keyboardProcessedThisFrame(i){this.#ac=i}destroy(){const{moveKey:i,upKey:g,downKey:x}=this.#uc,{htmlCanvas:v}=this.redGPUContext;v.removeEventListener(x,this.#mc),v.removeEventListener(i,this.#pc),v.removeEventListener(i,this.#gc),window.removeEventListener(g,this.#xc),this.#tc.HD_Wheel&&v.removeEventListener("wheel",this.#vc)}update(i,g,x){this.#rc!==g&&(this.#ic=-1===this.#rc?0:(g-this.#rc)/1e3,this.#rc=g,this.#nc.clear(),this.#ac=!1),this.#nc.has(i)||(this.#nc.add(i),this.#tc.useKeyboard&&this.keyboardActiveView&&this.keyboardActiveView!==i||x?.(this.#ic))}checkKeyboardInput(i,g){if(this.keyboardProcessedThisFrame)return!1;const{keyboardKeyBuffer:x}=i.redGPUContext;let v=!1;for(const i in g)if(x[g[i]]){v=!0;break}if(!v)return this.keyboardActiveView=null,!1;if(!this.keyboardActiveView){if(this.hoveredView!==i)return!1;this.keyboardActiveView=i}return this.keyboardActiveView===i&&(this.keyboardProcessedThisFrame=!0,!0)}getCanvasEventPoint=(i,g)=>{const x=g.detector.isMobile,v=g.boundingClientRect,_="clientX",y="clientY";let b,S;if(x){const g=i instanceof WheelEvent?i:i.changedTouches[0];b=g[_],S=g[y]}else{const g=i;b=g[_],S=g[y]}return{x:b-v.left,y:S-v.top}};findTargetViewByInputEvent=i=>{const{redGPUContext:g}=this,{renderScale:x,viewList:v}=g,{x:_,y:y}=this.getCanvasEventPoint(i,g),b=window.devicePixelRatio*x,S=_*b,w=y*b;let L=null;for(const i of v){const g=i.pixelRectObject;g.x{if(i.length<2)return 0;const g=i[0].clientX-i[1].clientX,x=i[0].clientY-i[1].clientY;return Math.sqrt(g*g+x*x)};#dc(){const{redGPUContext:i}=this,{htmlCanvas:g}=i,{downKey:x,moveKey:v}=this.#uc;g.addEventListener(x,this.#mc),g.addEventListener(v,this.#pc),this.#tc.HD_Wheel&&g.addEventListener("wheel",this.#vc,{passive:!1}),this.#tc.HD_TouchPinch&&g.addEventListener("touchmove",this.#yc,{passive:!1})}#pc=i=>{AController.#Jl||this.#oc||(this.#sc=this.findTargetViewByInputEvent(i))};#mc=i=>{const g=this.findTargetViewByInputEvent(i);if(!g)return;AController.#Jl||this.#oc||(this.#sc=g);const{redGPUContext:x}=this,{moveKey:v,upKey:_}=this.#uc,{x:y,y:b}=this.getCanvasEventPoint(i,x);this.#lc=y,this.#cc=b,i instanceof TouchEvent&&(i.touches.length>=2?(this.#fc=!0,this.#hc=this.#_c(i.touches)):(this.#fc=!1,this.#hc=0)),this.#nc.has(g)&&(this.#oc=!0,AController.#Jl=g,x.htmlCanvas.addEventListener(v,this.#gc),window.addEventListener(_,this.#xc))};#gc=i=>{if(i instanceof TouchEvent&&i.touches.length>=2)return void(this.#fc=!0);this.#fc=!1;const{x:g,y:x}=this.getCanvasEventPoint(i,this.redGPUContext),v=g-this.#lc,_=x-this.#cc;this.#lc=g,this.#cc=x,this.#tc.HD_Move?.(v,_)};#yc=i=>{if(i.touches.length<2||!this.#tc.HD_TouchPinch)return;if(!this.#fc)return;i.preventDefault();const g=this.#_c(i.touches);if(0===this.#hc)return void(this.#hc=g);if(this.findTargetViewByInputEvent(i).rawCamera!==this.#ec)return;const x=g/this.#hc;this.#tc.HD_TouchPinch?.(x),this.#hc=g};#xc=()=>{const{htmlCanvas:i}=this.redGPUContext,{moveKey:g,upKey:x}=this.#uc;this.#fc=!1,this.#hc=0,this.#oc=!1,i.removeEventListener(g,this.#gc),window.removeEventListener(x,this.#xc)};#vc=i=>{const g=this.findTargetViewByInputEvent(i);g&&g.rawCamera===this.#ec&&(i.stopPropagation(),i.preventDefault(),this.#tc.HD_Wheel?.(i))}}const Yn=create$4(),computeViewFrustumPlanes=(i,g)=>{multiply$4(Yn,i,g);const x=[[Yn[3]-Yn[0],Yn[7]-Yn[4],Yn[11]-Yn[8],Yn[15]-Yn[12]],[Yn[3]+Yn[0],Yn[7]+Yn[4],Yn[11]+Yn[8],Yn[15]+Yn[12]],[Yn[3]+Yn[1],Yn[7]+Yn[5],Yn[11]+Yn[9],Yn[15]+Yn[13]],[Yn[3]-Yn[1],Yn[7]-Yn[5],Yn[11]-Yn[9],Yn[15]-Yn[13]],[Yn[3]-Yn[2],Yn[7]-Yn[6],Yn[11]-Yn[10],Yn[15]-Yn[14]],[Yn[3]+Yn[2],Yn[7]+Yn[6],Yn[11]+Yn[10],Yn[15]+Yn[14]]];for(let i=0;i<6;i++){const g=x[i],v=Math.sqrt(g[0]*g[0]+g[1]*g[1]+g[2]*g[2]);g[0]/=v,g[1]/=v,g[2]/=v,g[3]/=v}return x};class ViewTransform extends RedGPUObject{onResize=null;#bc=create$4();#Sc=create$4();#ec;#wi=0;#Mi=0;#Gt;#Ot;#Vt=[0,0,0,0];#Tc=0;#wc=0;constructor(i){super(i),this.setSize("100%","100%")}get camera(){return this.#ec}set camera(i){i instanceof PerspectiveCamera||i instanceof Camera2D||i instanceof OrthographicCamera||i instanceof AController||consoleAndThrowError("allow PerspectiveCamera or OrthographicCamera or AController instance"),this.#ec=i}get x(){return this.#wi}set x(i){this.setPosition(i,this.y)}get y(){return this.#Mi}set y(i){this.setPosition(this.x,i)}get width(){return this.#Gt}set width(i){this.setSize(i,this.#Ot)}get height(){return this.#Ot}set height(i){this.setSize(this.#Gt,i)}get pixelRectArray(){return this.#Vt}get pixelRectObject(){return{x:this.#Vt[0],y:this.#Vt[1],width:this.#Vt[2],height:this.#Vt[3]}}get screenRectObject(){return{x:this.#Vt[0]/devicePixelRatio,y:this.#Vt[1]/devicePixelRatio,width:this.#Vt[2]/devicePixelRatio,height:this.#Vt[3]/devicePixelRatio}}get aspect(){return this.#Vt[2]/this.#Vt[3]}get frustumPlanes(){return this.#ec instanceof AController?computeViewFrustumPlanes(this.projectionMatrix,this.#ec.camera.viewMatrix):computeViewFrustumPlanes(this.projectionMatrix,this.#ec.viewMatrix)}get rawCamera(){return this.#ec instanceof AController?this.#ec.camera:this.#ec}get noneJitterProjectionMatrix(){const{pixelRectObject:i,redGPUContext:g}=this;if(this.rawCamera instanceof OrthographicCamera){const{nearClipping:i,farClipping:g}=this.rawCamera;orthoZO(this.#Sc,this.rawCamera.left,this.rawCamera.right,this.rawCamera.bottom,this.rawCamera.top,i,g)}else if(this.rawCamera instanceof Camera2D)Dt(this.#Sc,-.5,.5,-.5,.5,-1e5,1e5),scale$4(this.#Sc,this.#Sc,[g.renderScale,g.renderScale,1]),translate(this.#Sc,this.#Sc,[-.5,.5,0]),scale$4(this.#Sc,this.#Sc,[1/i.width*window.devicePixelRatio,-1/i.height*window.devicePixelRatio,1]);else{const{fieldOfView:i,nearClipping:g,farClipping:x}=this.rawCamera;Bt(this.#Sc,Math.PI/180*i,this.aspect,g,x)}return this.#Sc}get projectionMatrix(){const{redGPUContext:i}=this,{antialiasingManager:g}=i;this.#bc=clone$4(this.noneJitterProjectionMatrix);if("View3D"===this.constructor.name&&"IsometricController"!==this.camera.constructor.name&&g.useTAA&&this.rawCamera instanceof PerspectiveCamera&&(0!==this.#Tc||0!==this.#wc)){const i=this.#Tc/this.pixelRectObject.width*2,g=this.#wc/this.pixelRectObject.height*2;this.#bc[8]+=i,this.#bc[9]+=g}return this.#bc}get inverseProjectionMatrix(){return invert$1(create$4(),this.#bc)}get jitterOffset(){return[this.#Tc,this.#wc]}setJitterOffset(i,g){this.#Tc=i,this.#wc=g}clearJitterOffset(){this.#Tc=0,this.#wc=0}setPosition(i=this.#wi,g=this.#Mi){const{sizeManager:x}=this.redGPUContext;RedGPUContextSizeManager.validatePositionValue(i),RedGPUContextSizeManager.validatePositionValue(g),this.#wi=i,this.#Mi=g;const v=x.pixelRectObject,_=RedGPUContextSizeManager.getPixelDimension(v,"width",i),y=RedGPUContextSizeManager.getPixelDimension(v,"height",g);this.#Vt[0]=Math.round(_*(this.#wi.toString().includes("%")?1:x.renderScale*window.devicePixelRatio)),this.#Vt[1]=Math.round(y*(this.#Mi.toString().includes("%")?1:x.renderScale*window.devicePixelRatio))}setSize(i=this.#Gt,g=this.#Ot){const{sizeManager:x}=this.redGPUContext;RedGPUContextSizeManager.validateSizeValue(i),RedGPUContextSizeManager.validateSizeValue(g),this.#Gt=i,this.#Ot=g;const v=x.pixelRectObject,_=RedGPUContextSizeManager.getPixelDimension(v,"width",i),y=RedGPUContextSizeManager.getPixelDimension(v,"height",g);this.#Vt[2]=Math.max(1,Math.round(_*(this.#Gt.toString().includes("%")?1:x.renderScale*window.devicePixelRatio))),this.#Vt[3]=Math.max(1,Math.round(y*(this.#Ot.toString().includes("%")?1:x.renderScale*window.devicePixelRatio))),this.onResize&&this.onResize({target:this,screenRectObject:this.screenRectObject,pixelRectObject:this.pixelRectObject})}}Object.freeze(ViewTransform);class AView extends ViewTransform{#Mc;#Pc;#Rc=!0;#Cc=!1;#Bc=50;#Dc;#Ec;#Ic;#Ac;constructor(i,g,x,v){super(i),this.scene=g,this.camera=x,this.#Pc=new PickingManager(this),v&&(this.name=v)}get scene(){return this.#Mc}set scene(i){i instanceof Scene||consoleAndThrowError("allow only Scene instance"),this.#Mc=i}get pickingManager(){return this.#Pc}get useFrustumCulling(){return this.#Rc}set useFrustumCulling(i){this.#Rc=i}get useDistanceCulling(){return this.#Cc}set useDistanceCulling(i){this.#Cc=i}get distanceCulling(){return this.#Bc}set distanceCulling(i){this.#Bc=i}get grid(){return this.#Dc}set grid(i){if("boolean"==typeof i)i=!0===i?new DrawDebuggerGrid(this.redGPUContext):null;else if(!(i instanceof DrawDebuggerGrid)&&null!==i)throw new TypeError("grid must be of type 'DrawDebuggerGrid', 'boolean', or 'null'.");this.#Dc=i}get axis(){return this.#Ec}set axis(i){if("boolean"==typeof i)i=!0===i?new DrawDebuggerAxis(this.redGPUContext):null;else if(!(i instanceof DrawDebuggerAxis)&&null!==i)throw new TypeError("axis must be of type 'DrawDebuggerAxis', 'boolean', or 'null'.");this.#Ec=i}get fxaa(){return this.#Ac||(this.#Ac=new FXAA(this.redGPUContext)),this.#Ac}get taa(){return this.#Ic||(this.#Ic=new TAA(this.redGPUContext)),this.#Ic}screenToWorld(i,g){return screenToWorld(i,g,this)}checkMouseInViewBounds(){const{pixelRectObject:i,pickingManager:g}=this,{mouseX:x,mouseY:v}=g;return 00&&(this.prevTimestamp+=this.numFixedSteps*x),this.elapsed=i-this.timestamp,this.time=i/1e3,this.deltaTime=this.elapsed/1e3,this.sinTime=Math.sin(this.time),this.timestamp=i,this.viewRenderStartTime=i}}const Wn="depthTexture0",Zn="depthTexture1",Jn=GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC,Qn={[Ri.COLOR]:{format:"rgba16float",usage:Jn|GPUTextureUsage.STORAGE_BINDING,withResolve:!0,useMipmap:!1},[Ri.MOTION_VECTOR]:{format:"rgba16float",usage:Jn,withResolve:!0,useMipmap:!1},[Ri.NORMAL]:{usage:Jn,withResolve:!0,useMipmap:!1},[Ri.RENDER_PATH1_RESULT]:{format:"rgba16float",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,withResolve:!1,useMipmap:!0}};class ViewRenderTextureManager extends RedGPUObject{#H=0;#Ri;#Uc=new Map;#ls;#kc;#Gc;constructor(i){super(i.redGPUContext),this.#Ri=i}get gBuffers(){return this.#Uc}get videoMemorySize(){return this.#H}get renderPath1ResultTextureDescriptor(){return this.#Uc.get(Ri.RENDER_PATH1_RESULT)?.textureDescriptor}get depthTexture(){return this.#Qt(),this.#Ri.renderViewStateData.swapBufferIndex?this.#Uc.get(Zn)?.texture:this.#Uc.get(Wn)?.texture}get depthTextureView(){return this.#Qt(),this.#Ri.renderViewStateData.swapBufferIndex?this.#Uc.get(Zn)?.textureView:this.#Uc.get(Wn)?.textureView}get prevDepthTextureView(){return this.#Qt(),this.#Ri.renderViewStateData.swapBufferIndex?this.#Uc.get(Wn)?.textureView:this.#Uc.get(Zn)?.textureView}get depthTexture0View(){return this.#Qt(),this.#Uc.get(Wn)?.textureView}get depthTexture1View(){return this.#Qt(),this.#Uc.get(Zn)?.textureView}get renderPath1ResultTextureView(){return this.getGBufferTextureView(Ri.RENDER_PATH1_RESULT)}get renderPath1ResultTexture(){return this.getGBufferTexture(Ri.RENDER_PATH1_RESULT)}getGBufferTexture(i){return this.#Qt(),this.#Uc.get(i)?.texture}getGBufferResolveTexture(i){return this.#Qt(),this.#Uc.get(i)?.resolveTexture}getGBufferTextureView(i){return this.#Qt(),this.#Uc.get(i)?.textureView}getGBufferResolveTextureView(i){return this.#Qt(),this.#Uc.get(i)?.resolveTextureView}#Qt(){const{antialiasingManager:i}=this,{msaaID:g}=i,{pixelRectObject:x,renderViewStateData:v}=this.#Ri;this.#kc={width:Math.max(x.width,1),height:Math.max(x.height,1),depthOrArrayLayers:1},this.#Gc=`${this.#kc.width}x${this.#kc.height}`;const _=this.#Uc.get(Ri.RENDER_PATH1_RESULT)?.texture,y=_?.width!==this.#kc.width||_?.height!==this.#kc.height,b=this.#ls!==g;if(y||b||!_){this.#ls=g,v.swapBufferIndex=0,this.#Il(Wn),this.#Il(Zn);for(const i in Ri)this.#Oc(Ri[i]);this.#Vc()}}#Vc(){const i=[];this.#Uc.forEach(g=>{g.texture&&i.push(g.texture),g.resolveTexture&&i.push(g.resolveTexture)}),this.#H=i.reduce((i,g)=>i+calculateTextureByteSize(g),0)}#Nc(i){const g=this.#Uc.get(i);if(g){const{texture:x,resolveTexture:v}=g;g.texture=null,g.textureView=null,g.resolveTexture=null,g.resolveTextureView=null,this.#Uc.delete(i);const{commandEncoderManager:_}=this;x&&_.addDeferredDestroy(x),v&&_.addDeferredDestroy(v)}}#Fc(i,g,x,v=!1,_=1){const{antialiasingManager:y,resourceManager:b}=this,{useMSAA:S}=y,w={texture:null,textureView:null,textureDescriptor:null},{name:L}=this.#Ri,k=S&&1===_?4:1,H={size:this.#kc,sampleCount:k,label:`${L}_${i}_texture_${this.#Gc}`,format:g,usage:k>1?x&~GPUTextureUsage.STORAGE_BINDING:x,mipLevelCount:_},z=b.createManagedTexture(H);if(w.textureDescriptor=H,w.texture=z,w.textureView=b.getGPUResourceBitmapTextureView(z),v&&S){const v={size:this.#kc,sampleCount:1,label:`${L}_${i}_resolveTexture_${this.#Gc}`,format:g,usage:x},_=b.createManagedTexture(v);w.resolveTextureDescriptor=v,w.resolveTexture=_,w.resolveTextureView=b.getGPUResourceBitmapTextureView(_)}return w}#Oc(i){g(`새 텍스처 생성 중: ${i}`);let x=Qn[i]?.format||navigator.gpu.getPreferredCanvasFormat(),{usage:v,withResolve:_,useMipmap:y}=Qn[i],b=y?getMipLevelCount(this.#kc.width,this.#kc.height):1;this.#Nc(i),this.#Uc.set(i,this.#Fc(i,x,v,_,b))}#Il(i){this.#Nc(i),g(`새 텍스처 생성 중: ${i}`);const x=GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC;this.#Uc.set(i,this.#Fc(i,"depth32float",x,!1))}}Object.freeze(ViewRenderTextureManager);const ea={LINEAR:"linear",KHRONOS_PBR_NEUTRAL:"khronosPBRNeutral",ACES_FILMIC_HILL:"ACESFilmicHill",ACES_FILMIC_NARKOWICZ:"ACESFilmicNarkowicz"};Object.freeze(ea);var ta="#redgpu_include color.linearToSrgbVec3 struct Uniforms{contrast:f32,brightness:f32,_pad:f32,_pad2:f32,};fn linearToneMapping(color:vec3)->vec3{return color;}fn khronosPBRNeutralToneMapping(color:vec3)->vec3{let startCompression:f32=0.8-.04;let desaturation:f32=0.15;var col=color;let x=min(col.r,min(col.g,col.b));var offset:f32;if(x<.08){offset=x-6.25*x*x;}else{offset=.04;}col=col-vec3(offset);let peak=max(col.r,max(col.g,col.b));if(peak(.0),vec3(1.0));}let d=1.0-startCompression;let newPeak=1.0-d*d/(peak+d-startCompression);col=col*(newPeak/peak);let g=1.0-1.0/(desaturation*(peak-newPeak)+1.0);return clamp(mix(col,vec3(newPeak),g),vec3(.0),vec3(1.0));}fn acesFilmicNarkowiczToneMapping(color:vec3)->vec3{let x=color;let a=2.51;let b=.03;let c=2.43;let d=0.59;let e=0.14;return clamp((x*(a*x+b))/(x*(c*x+d)+e),vec3(.0),vec3(1.0));}fn acesFilmicHillToneMapping(color:vec3)->vec3{let v=color;let a1=v.r*0.59719+v.g*0.35458+v.b*.04823;let a2=v.r*.07600+v.g*0.90834+v.b*.01566;let a3=v.r*.02840+v.g*0.13383+v.b*0.83777;let a=vec3(a1,a2,a3);let b=(a*(a+.0245786)-.000090537)/(a*(0.983729*a+0.4329510)+0.238081);let r=b.r*1.60475-b.g*0.53108-b.b*.07367;let g=b.r*-0.10208+b.g*1.10813-b.b*.00605;let bl=b.r*-.00327-b.g*.07276+b.b*1.07602;return clamp(vec3(r,g,bl),vec3(.0),vec3(1.0));}fn getFinalSRGB(toneMappedColor:vec3,contrast:f32,brightness:f32)->vec3{let contrastRGB=applyContrast(toneMappedColor,contrast);let finalLinearRGB=applyBrightness(contrastRGB,brightness);let finalSRGB=clamp(linearToSrgbVec3(finalLinearRGB),vec3(.0),vec3(1.0));return finalSRGB;}fn applyContrast(color:vec3,contrast:f32)->vec3{return 0.5+contrast*(color-0.5);}fn applyBrightness(color:vec3,brightness:f32)->vec3{return color+brightness;}";function createSetter$1(i,g,x,v){return function(_){validateNumber(_),void 0!==x&&_v&&(console.warn(`Value for ${i} exceeds the maximum (${v}). Received: ${_}. Adjusted to ${v}.`),_=v),this[g]=_,updateTargetUniform(this,i,_)}}function defineNumber_func(i){const{key:g,value:x=0,min:v,max:_}=i,y=Symbol(g);return{get:function(){return void 0===this[y]&&(this[y]=x),this[y]},set:createSetter$1(g,y,v,_),...vi}}const defineNumber=(i,g)=>applyProperties(i,g,defineNumber_func);Object.freeze(defineNumber);class AToneMappingEffect extends ASinglePassPostEffect{constructor(i){super(i)}}defineNumber(AToneMappingEffect,[{key:"contrast",value:5,min:.5,max:20},{key:"brightness",value:0,min:-1,max:1}]),Object.freeze(AToneMappingEffect);class ToneLinear extends AToneMappingEffect{constructor(i){super(i),this.init(i,"POST_EFFECT_TONE_MAPPING_LINEAR",createBasicPostEffectCode(this,"{let index=vec2(global_id.xy);let inputColor=textureLoad(sourceTexture,index,0);let toneMappedColor=linearToneMapping(inputColor.rgb);let finalSRGB=getFinalSRGB(toneMappedColor,uniforms.contrast,uniforms.brightness);textureStore(outputTexture,index,vec4(finalSRGB,inputColor.a));}",ta))}}Object.freeze(ToneLinear);class ToneKhronosPBRNeutral extends AToneMappingEffect{constructor(i){super(i),this.init(i,"POST_EFFECT_TONE_MAPPING_KHRONOS_PBR_NEUTRAL",createBasicPostEffectCode(this,"{let index=vec2(global_id.xy);let inputColor=textureLoad(sourceTexture,index,0);let toneMappedColor=khronosPBRNeutralToneMapping(inputColor.rgb);let finalSRGB=getFinalSRGB(toneMappedColor,uniforms.contrast,uniforms.brightness);textureStore(outputTexture,index,vec4(finalSRGB,inputColor.a));}",ta))}}Object.freeze(ToneKhronosPBRNeutral);class ToneACESFilmicNarkowicz extends AToneMappingEffect{constructor(i){super(i),this.init(i,"POST_EFFECT_TONE_MAPPING_ACES_FILMIC_NARKOWICZ",createBasicPostEffectCode(this,"{let index=vec2(global_id.xy);let inputColor=textureLoad(sourceTexture,index,0);let toneMappedColor=acesFilmicNarkowiczToneMapping(inputColor.rgb);let finalSRGB=getFinalSRGB(toneMappedColor,uniforms.contrast,uniforms.brightness);textureStore(outputTexture,index,vec4(finalSRGB,inputColor.a));}",ta))}}Object.freeze(ToneACESFilmicNarkowicz);class ToneACESFilmicHill extends AToneMappingEffect{constructor(i){super(i),this.init(i,"POST_EFFECT_TONE_MAPPING_ACES_FILMIC_HILL",createBasicPostEffectCode(this,"{let index=vec2(global_id.xy);let inputColor=textureLoad(sourceTexture,index,0);let toneMappedColor=acesFilmicHillToneMapping(inputColor.rgb);let finalSRGB=getFinalSRGB(toneMappedColor,uniforms.contrast,uniforms.brightness);textureStore(outputTexture,index,vec4(finalSRGB,inputColor.a));}",ta))}}Object.freeze(ToneACESFilmicHill);class ToneMappingManager{#h;#Hc;#zc=ea.KHRONOS_PBR_NEUTRAL;#$c=1;#jc=0;constructor(i){this.#h=i}get redGPUContext(){return this.#h}get toneMapping(){return this.#Kc(),this.#Hc}get mode(){return this.#zc}set mode(i){this.#zc!==i&&(this.#zc=i,this.clear())}get contrast(){return this.#$c}set contrast(i){this.#$c=i,this.#Hc&&(this.#Hc.contrast=i)}get brightness(){return this.#jc}set brightness(i){this.#jc=i,this.#Hc&&(this.#Hc.brightness=i)}clear(){this.#Hc&&(this.#Hc.clear(),this.#Hc=void 0)}render(i,g,x,v){const _=this.toneMapping;return _?_.render(i,g,x,v):v}#Kc(){if(this.#Hc)return;const{redGPUContext:i}=this;switch(this.#zc){case ea.LINEAR:this.#Hc=new ToneLinear(i);break;case ea.KHRONOS_PBR_NEUTRAL:this.#Hc=new ToneKhronosPBRNeutral(i);break;case ea.ACES_FILMIC_NARKOWICZ:this.#Hc=new ToneACESFilmicNarkowicz(i);break;case ea.ACES_FILMIC_HILL:this.#Hc=new ToneACESFilmicHill(i);break;default:this.#Hc=new ToneKhronosPBRNeutral(i)}this.#Hc&&(this.#Hc.contrast=this.#$c,this.#Hc.brightness=this.#jc)}}Object.freeze(ToneMappingManager);class DrawDebuggerPointLight extends ADrawDebuggerLight{constructor(i,g){super(i,g,"💡",[0,255,255],51)}render(i){const{lightDebugMesh:g,label:x,target:v}=this;i.view.systemUniform_Vertex_UniformBindGroup&&v.enableDebugger&&(this.#su(v,g.geometry.vertexBuffer),g.render(i),x.setPosition(...v.position))}#su(i,g){const x=i.position||[0,0,0],v=i.radius||1,_=16,y=[];for(let i=0;i<_;i++){const g=i/_*Math.PI*2,b=(i+1)/_*Math.PI*2,S=x[0]+Math.cos(g)*v,w=x[1]+Math.sin(g)*v,L=x[2],k=x[0]+Math.cos(b)*v,H=x[1]+Math.sin(b)*v,z=x[2];y.push([[S,w,L],[k,H,z]])}for(let i=0;i<_;i++){const g=i/_*Math.PI*2,b=(i+1)/_*Math.PI*2,S=x[0]+Math.cos(g)*v,w=x[1],L=x[2]+Math.sin(g)*v,k=x[0]+Math.cos(b)*v,H=x[1],z=x[2]+Math.sin(b)*v;y.push([[S,w,L],[k,H,z]])}for(let i=0;i<_;i++){const g=i/_*Math.PI*2,b=(i+1)/_*Math.PI*2,S=x[0],w=x[1]+Math.cos(g)*v,L=x[2]+Math.sin(g)*v,k=x[0],H=x[1]+Math.cos(b)*v,z=x[2]+Math.sin(b)*v;y.push([[S,w,L],[k,H,z]])}const b=.2*v;y.push([[x[0]-b,x[1],x[2]],[x[0]+b,x[1],x[2]]]),y.push([[x[0],x[1]-b,x[2]],[x[0],x[1]+b,x[2]]]),y.push([[x[0],x[1],x[2]-b],[x[0],x[1],x[2]+b]]),this.updateVertexBuffer(y,g)}}Object.freeze(DrawDebuggerPointLight);class DrawDebuggerSpotLight extends ADrawDebuggerLight{constructor(i,g){super(i,g,"🔦",[255,255,0],80)}render(i){const{lightDebugMesh:g,label:x,target:v}=this;i.view.systemUniform_Vertex_UniformBindGroup&&v.enableDebugger&&(this.#su(v,g.geometry.vertexBuffer),g.render(i),x.setPosition(...v.position))}#su(i,g){const x=i.position||[0,0,0],v=i.direction||[0,-1,0],_=i.radius||5,y=i.outerCutoff||22.5,b=i.innerCutoff||15,S=[],w=Math.sqrt(v[0]*v[0]+v[1]*v[1]+v[2]*v[2]),L=[v[0]/w,v[1]/w,v[2]/w],k=[x[0]+L[0]*_,x[1]+L[1]*_,x[2]+L[2]*_],H=_*Math.tan(y*Math.PI/180),z=_*Math.tan(b*Math.PI/180);let q=[0,1,0];Math.abs(L[1])>.99&&(q=[1,0,0]);const W=[L[1]*q[2]-L[2]*q[1],L[2]*q[0]-L[0]*q[2],L[0]*q[1]-L[1]*q[0]],be=Math.sqrt(W[0]*W[0]+W[1]*W[1]+W[2]*W[2]),je=[W[0]/be,W[1]/be,W[2]/be],Ke=[je[1]*L[2]-je[2]*L[1],je[2]*L[0]-je[0]*L[2],je[0]*L[1]-je[1]*L[0]],Xe=16;for(let i=0;i{const x=W.getDispatchSize();g.setPipeline(this.#Wc),g.setBindGroup(0,i),g.setBindGroup(1,this.#Yc),g.dispatchWorkgroups(x[0],x[1],x[2])})}}#Zc(){const{gpuDevice:i,resourceManager:g}=this,x=parseWGSL("PASS_CLUSTER_LIGHT_BOUND",ra+"#redgpu_include SYSTEM_UNIFORM;@group(1)@binding(0)varclusterBoundsGrid:ClusterBoundsGrid;fn lineIntersectionToZPlane(a:vec3,b:vec3,zDistance:f32)->vec3{let normal=vec3(.0,.0,0.5);let ab=b-a;let t=(zDistance-dot(normal,a))/dot(normal,ab);return a+t*ab;}fn clipToView(clip:vec4)->vec4{let view=systemUniforms.projection.inverseProjectionMatrix*clip;return view/vec4(view.w,view.w,view.w,view.w);}fn screen2View(screen:vec4)->vec4{let texCoord=screen.xy/systemUniforms.resolution.xy;let clip=vec4(vec2(texCoord.x,1.0-texCoord.y)*2.0-vec2(1.0,1.0),screen.z,screen.w);return clipToView(clip);}const eyePos=vec3(.0);@compute @workgroup_size(REDGPU_DEFINE_WORKGROUP_SIZE_X,REDGPU_DEFINE_WORKGROUP_SIZE_Y,REDGPU_DEFINE_WORKGROUP_SIZE_Z)fn main(@builtin(global_invocation_id)global_id:vec3){let tileIndex=global_id.x+global_id.y*clusterLight_tileCount.x+global_id.z*clusterLight_tileCount.x*clusterLight_tileCount.y;let tileSize=vec2(systemUniforms.resolution.x/f32(clusterLight_tileCount.x),systemUniforms.resolution.y/f32(clusterLight_tileCount.y));let global_id_x_pos_one=vec2(f32(global_id.x+1u),f32(global_id.y+1u))*tileSize;let global_id_x_y=vec2(f32(global_id.x),f32(global_id.y))*tileSize;let maxPoint_sS=vec4(global_id_x_pos_one,.0,1.0);let minPoint_sS=vec4(global_id_x_y,.0,1.0);let maxPoint_vS=screen2View(maxPoint_sS).xyz;let minPoint_vS=screen2View(minPoint_sS).xyz;let nearFarX=systemUniforms.camera.nearClipping;let nearFarY=systemUniforms.camera.farClipping;let tileZ=f32(global_id.z)/f32(clusterLight_tileCount.z);let tileZ_plus_one=f32(global_id.z+1u)/f32(clusterLight_tileCount.z);let tileNear=-nearFarX*pow(nearFarY/nearFarX,tileZ);let tileFar=-nearFarX*pow(nearFarY/nearFarX,tileZ_plus_one);let minPointNear=lineIntersectionToZPlane(eyePos,minPoint_vS,tileNear);let minPointFar=lineIntersectionToZPlane(eyePos,minPoint_vS,tileFar);let maxPointNear=lineIntersectionToZPlane(eyePos,maxPoint_vS,tileNear);let maxPointFar=lineIntersectionToZPlane(eyePos,maxPoint_vS,tileFar);let minAABB=min(min(minPointNear,minPointFar),min(maxPointNear,maxPointFar));let maxAABB=max(max(minPointNear,minPointFar),max(maxPointNear,maxPointFar));clusterBoundsGrid.cubeList[tileIndex].minAABB=vec4(minAABB,.0);clusterBoundsGrid.cubeList[tileIndex].maxAABB=vec4(maxAABB,.0);}").defaultSource;this.#Xc=g.createGPUBuffer("PASS_CLUSTER_BOUND_BUFFER",{size:32*W.getTotalTileSize(),usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),this.#qc=i.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}}]}),this.#Yc=i.createBindGroup({label:"CLUSTER_BOUND_BIND_GROUP",layout:this.#qc,entries:[{binding:0,resource:{buffer:this.#Xc}}]}),this.#Wc=i.createComputePipeline({label:"CLUSTER_BOUND_PIPELINE",layout:i.createPipelineLayout({bindGroupLayouts:[g.getGPUBindGroupLayout(ResourceManager.PRESET_GPUBindGroupLayout_System),this.#qc]}),compute:{module:g.createGPUShaderModule("CLUSTER_BOUND_SHADER",{code:x}),entryPoint:"main"}})}}Object.freeze(PassClusterLightBound);const ia=new Uint32Array([0,0,0,0]);class PassClustersLight extends RedGPUObject{#Ri;#Jc;#Qc;#eh;constructor(i,g){super(i),this.#Ri=g,this.#Zc()}get clusterLightsBuffer(){return this.#eh}render(){const i=this.#Ri.systemUniform_Vertex_UniformBindGroup;if(i){const{commandEncoderManager:g,gpuDevice:x}=this;g.addPreProcessComputePass("PassClustersLight_ComputePass",g=>{const v=W.getDispatchSize();x.queue.writeBuffer(this.clusterLightsBuffer,0,ia),g.setPipeline(this.#Qc),g.setBindGroup(0,i),g.setBindGroup(1,this.#Jc),g.dispatchWorkgroups(v[0],v[1],v[2])})}}#Zc(){const{gpuDevice:i,resourceManager:g}=this,x=parseWGSL("PASS_CLUSTERS_LIGHT",ra+"#redgpu_include SYSTEM_UNIFORM;@group(1)@binding(0)varclusterBoundsGrid:ClusterBoundsGrid;fn pointLight_testSphereAABB(light:u32,tile:u32)->bool{let targetLight=clusterLightList.lights[light];let targetTile=clusterBoundsGrid.cubeList[tile];let radius:f32=targetLight.radius;let position:vec3=targetLight.position;let center:vec3=(systemUniforms.camera.viewMatrix*vec4(position,1.0)).xyz;let squaredDistance:f32=pointLight_sqDistPointAABB(center,tile,targetTile.minAABB.xyz,targetTile.maxAABB.xyz);return squaredDistance<=(radius*radius);}fn pointLight_sqDistPointAABB(targetPoint:vec3,tile:u32,minAABB:vec3,maxAABB:vec3)->f32{var sqDist=.0;for(var i=0u;i<3u;i=i+1u){let v=targetPoint[i];let _minAABB=minAABB[i];let _maxAABB=maxAABB[i];if(v<_minAABB){sqDist+=(_minAABB-v)*(_minAABB-v);}if(v>_maxAABB){sqDist+=(v-_maxAABB)*(v-_maxAABB);}}return sqDist;}fn spotLight_testSphereAABB(light:u32,tile:u32)->bool{let targetLight=clusterLightList.lights[light];let targetTile=clusterBoundsGrid.cubeList[tile];let radius:f32=targetLight.radius;let position:vec3=targetLight.position;let center:vec3=(systemUniforms.camera.viewMatrix*vec4(position,1.0)).xyz;let squaredDistance:f32=pointLight_sqDistPointAABB(center,tile,targetTile.minAABB.xyz,targetTile.maxAABB.xyz);return squaredDistance<=(radius*radius);}@compute @workgroup_size(REDGPU_DEFINE_WORKGROUP_SIZE_X,REDGPU_DEFINE_WORKGROUP_SIZE_Y,REDGPU_DEFINE_WORKGROUP_SIZE_Z)fn main(@builtin(global_invocation_id)global_id:vec3){let tileIndex=global_id.x+global_id.y*clusterLight_tileCount.x+global_id.z*clusterLight_tileCount.x*clusterLight_tileCount.y;var clusterLightCount=0u;var clusterLightIndices:array;for(var i=0u;i-1){let i=!0,g=this.#mh[q];const v=b?.skyAtmosphereReflectionLUT,_=b?.skyAtmosphereIrradianceLUT;g&&(i=g.ibl!==y||g.skyAtmosphere!==b||g.skyAtmosphereReflectionLUT!==v||g.skyAtmosphereReflectionLUTRevision!==v?.revision||g.skyAtmosphereIrradianceLUT!==_||g.skyAtmosphereIrradianceLUTRevision!==_?.revision||g.ibl_prefilterTexture!==L||g.ibl_irradianceTexture!==k||g.renderPath1ResultTextureView!==x||g.shadowDepthTextureView!==H||!this.#yh.passClustersLight),i?this.#Sh(q,H,this.ibl,x):this.#ah=this.#mh[q].vertexUniformBindGroup,this.#mh[q]={ibl:y,skyAtmosphere:b,skyAtmosphereReflectionLUT:v,skyAtmosphereReflectionLUTRevision:v?.revision,skyAtmosphereIrradianceLUT:_,skyAtmosphereIrradianceLUTRevision:_?.revision,ibl_prefilterTexture:L,ibl_irradianceTexture:k,renderPath1ResultTextureView:x,shadowDepthTextureView:H,vertexUniformBindGroup:this.#ah}}this.#Th()}#Th(){const{inverseProjectionMatrix:i,noneJitterProjectionMatrix:g,projectionMatrix:x,rawCamera:v}=this;v.updateExposure(this);const{redGPUContext:_,systemUniform_Vertex_UniformBuffer:y}=this,{gpuDevice:b}=_,{lightManager:S,shadowManager:w}=this.scene,{viewMatrix:L}=v,k=this.systemUniform_Vertex_StructInfo,{members:H}=k;{this.#_h=multiply$4(sa,g,L);const y=multiply$4(aa,x,L);SystemUniformUpdater.updateCamera(v,H.camera.members,this.#vn,this.#_n),SystemUniformUpdater.updateShadow(w,H.shadow.members,this.#vn,this.#_n),SystemUniformUpdater.updateSkyAtmosphere(this.skyAtmosphere,H,this.#vn,this.#_n),SystemUniformUpdater.updateDirectionalLights(S.directionalLights,H.directionalLights.memberList,this.#vn,this.#_n),SystemUniformUpdater.updateAmbientLight(S.ambientLight,H.ambientLight.members,this.#vn,this.#_n),SystemUniformUpdater.updateTime(this.renderViewStateData,H.time.members,this.#vn,this.#_n),SystemUniformUpdater.updateProjection({projectionMatrix:x,projectionViewMatrix:y,noneJitterProjectionMatrix:g,noneJitterProjectionViewMatrix:this.#_h,inverseProjectionMatrix:i,inverseProjectionViewMatrix:invert$1(oa,y),prevNoneJitterProjectionViewMatrix:_.antialiasingManager.useTAA?this.taa.prevNoneJitterProjectionViewMatrix:this.#_h},H.projection.members,this.#vn,this.#_n),updateSystemUniformData(H,this.#vn,this.#_n,[{key:"resolution",value:[this.pixelRectObject.width,this.pixelRectObject.height]},{key:"usePrefilterTexture",value:this.ibl?.prefilterTexture?.gpuTexture?1:0},{key:"isView3D",value:this.constructor===View3D?1:0},{key:"directionalLightCount",value:S.directionalLightCount},{key:"iblIntensity",value:this.ibl?this.ibl.luminance*this.ibl.intensityMultiplier:1},{key:"directionalLightProjectionViewMatrix",value:S.getDirectionalLightProjectionViewMatrix(this)},{key:"directionalLightProjectionMatrix",value:S.getDirectionalLightProjectionMatrix(this)},{key:"directionalLightViewMatrix",value:S.getDirectionalLightViewMatrix(this)},{key:"preExposure",value:this.postEffectManager.autoExposure.preExposure}])}S.directionalLights.forEach(i=>{i.enableDebugger&&(i.drawDebugger||(i.drawDebugger=new DrawDebuggerDirectionalLight(_,i)),i.drawDebugger.render(this.renderViewStateData))}),b.queue.writeBuffer(y.gpuBuffer,0,this.#xn)}#Sh(i,g,x,v){this.#yh.updateClusterLights();const _=x?.prefilterTexture,y=x?.irradianceTexture,{redGPUContext:b}=this,{gpuDevice:S,resourceManager:w}=b,L={layout:w.getGPUBindGroupLayout(ResourceManager.PRESET_GPUBindGroupLayout_System),label:`SYSTEM_UNIFORM_bindGroup_${i}`,entries:[{binding:0,resource:{buffer:this.#sh.gpuBuffer,offset:0,size:this.#sh.size}},{binding:1,resource:this.#ph},{binding:2,resource:g},{binding:3,resource:this.#tt},{binding:5,resource:{buffer:this.#yh.clusterLightsBuffer,offset:0,size:this.#yh.clusterLightsBuffer.size}},{binding:6,resource:{buffer:this.#yh.passClustersLight.clusterLightsBuffer,offset:0,size:this.#yh.passClustersLight.clusterLightsBuffer.size}},{binding:7,resource:this.#tt},{binding:8,resource:v||w.emptyBitmapTextureView},{binding:9,resource:this.#gh},{binding:10,resource:w.getGPUResourceCubeTextureView(_,_?.viewDescriptor||CubeTexture.defaultViewDescriptor)},{binding:11,resource:w.getGPUResourceCubeTextureView(y,y?.viewDescriptor||CubeTexture.defaultViewDescriptor)},{binding:12,resource:w.brdfGenerator.brdfLUTTexture?.createView()||w.emptyBitmapTextureView},{binding:13,resource:this.skyAtmosphere?this.skyAtmosphere.atmosphereSampler.gpuSampler:this.#tt},{binding:14,resource:this.skyAtmosphere?this.skyAtmosphere.transmittanceLUT.gpuTextureView:w.emptyBitmapTextureView},{binding:15,resource:w.getGPUResourceCubeTextureView(this.skyAtmosphere?.skyAtmosphereIrradianceLUT,this.skyAtmosphere?.skyAtmosphereIrradianceLUT?.viewDescriptor||CubeTexture.defaultViewDescriptor)},{binding:16,resource:w.getGPUResourceCubeTextureView(this.skyAtmosphere?.skyAtmosphereReflectionLUT,this.skyAtmosphere?.skyAtmosphereReflectionLUT?.viewDescriptor||CubeTexture.defaultViewDescriptor)}]};this.#ah=S.createBindGroup(L),this.#wh(w,_,y)}#wh(i,g,x){[[this.#xh,g],[this.#vh,x]].forEach(([g,x])=>{g&&g!==x&&this.#bh(i,g.cacheKey,!1),x&&g!==x&&this.#bh(i,x.cacheKey,!0)}),this.#xh=g,this.#vh=x}#bh(i,g,x){const v=i.managedCubeTextureState,_=v?.table.get(g);_&&(x?_.useNum++:_.useNum--)}#N(){const i=new ArrayBuffer(na.arrayBufferByteLength);this.#sh=new UniformBuffer(this.redGPUContext,i,"SYSTEM_UNIFORM_BUFFER_VERTEX","SYSTEM_UNIFORM_BUFFER_VERTEX"),this.#ph=new Sampler(this.redGPUContext,{addressModeU:v.CLAMP_TO_EDGE,addressModeV:v.CLAMP_TO_EDGE,addressModeW:v.CLAMP_TO_EDGE,compare:Er.LESS_EQUAL}).gpuSampler,this.#tt=new Sampler(this.redGPUContext).gpuSampler,this.#gh=new Sampler(this.redGPUContext,{addressModeU:v.REPEAT,addressModeV:v.REPEAT}).gpuSampler}}Object.freeze(View3D);class RedGPUContextViewContainer{#Mh=[];constructor(){}get viewList(){return this.#Mh}get numViews(){return this.#Mh.length}contains(i){return this.#Mh.includes(i)}addView(i){this.#Ph(i),this.#Mh.push(i)}addViewAt(i,g){this.#Ph(i),validateUintRange(g);const x=this.#Mh.length;x=x,_=this.#Mh.indexOf(i);-1===_&&consoleAndThrowError("입력하신 View 는 RedGPUContext instance 에 등록되지 않은 View 입니다."),v&&consoleAndThrowError(`index must be smaller than the viewList length. / index : ${g} / this.#viewList.length : ${x}`),this.#Mh.splice(_,1),this.#Mh.splice(g,0,i)}swapViews(i,g){this.#Ph(i),this.#Ph(g);const x=this.#Mh.indexOf(i),v=this.#Mh.indexOf(g);-1!==x&&-1!==v||consoleAndThrowError((-1===x?"view1":"view2")+" is not child of this RedGPUContext instance."),this.swapViewsAt(x,v)}swapViewsAt(i,g){i===g&&consoleAndThrowError("The indices to swap cannot be the same."),validateUintRange(i),validateUintRange(g);const x=this.#Mh.length;(i>=x||g>=x)&&consoleAndThrowError(`index1, index2 must be smaller than the viewList length. / index1 : ${i} / index2 : ${g} / this.#viewList.length : ${x}`);const v=this.#Mh[i];this.#Mh[i]=this.#Mh[g],this.#Mh[g]=v}removeView(i){this.#Ph(i);const g=this.#Mh.indexOf(i);g>-1?this.#Mh.splice(g,1):consoleAndThrowError("View3D is not found in the view list.")}removeViewAt(i){validateUintRange(i);const g=this.#Mh.length;i{const _=v.beginRenderPass(i);g(_),_.end(),x&&x(v)},"Immediate Submitted Render Pass")}async immediateComputePass(i,g,x){const v=this.#kh(i),_=v.label||"RedGPU_Immediate_Compute_Encoder";await this.#Uh(_,i=>{const _=i.beginComputePass(v);g(_),_.end(),x&&x(i)},"Immediate Submitted Compute Pass")}async immediateSubmit(i,g){await this.#Uh(i,g,"Immediate Submitted Commands")}submit(i){if(this.#Ch[i])throw new Error(`[RedGPU] Cannot submit ${i} phase while a pass is still active.`);const g=this.#Gh(i);if(g.length>0){this.gpuDevice.queue.submit(g);const x=this.#Oh(i,g.length);return this.#Vh(i),this.#Nh(),x}return this.#Nh(),null}submitAll(){const i=[],g={};if([k.RESOURCE,k.PRE_PROCESS,k.MAIN,k.POST_PROCESS].forEach(x=>{if(this.#Ch[x])throw new Error(`[RedGPU] Cannot submit ${x} phase while a pass is still active.`);const v=this.#Gh(x);i.push(...v),g[x]=this.#Oh(x,v.length),this.#Vh(x)}),i.length>0){this.gpuDevice.queue.submit(i);const x=this.#Nh();return{phases:g,deferredDestroyCount:x}}const x=this.#Nh();return x>0?{phases:g,deferredDestroyCount:x}:null}resetAll(){this.#Rh.clear(),this.#Bh.clear(),this.#Nh(),Object.keys(this.#Ch).forEach(i=>{delete this.#Ch[i]})}#Nh(){const i=this.#Dh.length;if(i>0){let g=0;for(;g"string"==typeof i?{label:i}:i;#Oh(i,g){const x=this.#Bh.get(i)||{renderPasses:[],computePasses:[],rawUsages:0};return{Phase:i,"Command Buffers":g,"Render Passes":{count:x.renderPasses.length,list:x.renderPasses},"Compute Passes":{count:x.computePasses.length,list:x.computePasses},"Raw Usages":x.rawUsages}}#Lh(i,g,x){this.#Bh.has(i)||this.#Bh.set(i,{renderPasses:[],computePasses:[],rawUsages:0});const v=this.#Bh.get(i);"rawUsages"===g?v.rawUsages++:v[g].push(x||"unlabeled")}#Vh(i){this.#Bh.set(i,{renderPasses:[],computePasses:[],rawUsages:0})}#Gh(i){const g=this.#Rh.get(i);if(g&&g.length>0){const x=g.map(i=>i.finish());return this.#Rh.set(i,[]),delete this.#Ch[i],x}return[]}}class RedGPUContextObserver extends RedGPUObject{#Nt;#Fh;#Hh=null;#zh=null;#$h=null;#jh=null;constructor(i,g){super(i),this.#Nt=i.htmlCanvas,this.#Fh=g,this.#N()}stop(){this.#$h?.disconnect(),this.#zh?.disconnect(),this.#jh?.disconnect()}#N(){this.#$h=new MutationObserver(i=>{for(const g of i)"childList"===g.type&&this.#Hh!==this.#Nt.parentElement&&this.#Kh()}),"undefined"!=typeof document&&this.#$h.observe(document.body,{childList:!0,subtree:!0}),this.#jh=new IntersectionObserver(()=>{this.#Xh()},{threshold:[0,1]}),this.#jh.observe(this.#Nt),window.addEventListener("resize",()=>this.#Xh()),this.#Kh()}#Kh(){const i=this.#Nt.parentElement;this.#Hh!==i&&(this.#zh&&(this.#zh.disconnect(),this.#zh=null),this.#Hh=i,this.#Hh&&(this.#zh=new ResizeObserver(()=>{this.#Xh()}),this.#zh.observe(this.#Hh))),this.#Xh()}#Xh(){this.#Fh(),this.redGPUContext.sizeManager.setSize()}}class RedGPUContext extends RedGPUContextViewContainer{currentRequestAnimationFrame;onResize=null;currentTime;#qh;#yt;#Yh;#Wh;#f;#Nt;#Zh;#Jh;#Qh;#ef;#tf;#kl=new ColorRGBA(0,0,0,1);#rf={};#if;#nf;constructor(i,g,x,v,_){super(),this.#yt=g,this.#f=x,this.#Wh=v,this.#Yh=_,this.#Nt=i,this.#Zh=new RedGPUContextSizeManager(this),this.#Jh=new RedGPUContextDetector(this),this.#Qh=new ResourceManager(this),this.#ef=new CommandEncoderManager(this),this.#tf=new AntialiasingManager,this.#af()}get commandEncoderManager(){return this.#ef}get boundingClientRect(){return this.#if}get antialiasingManager(){return this.#tf}get backgroundColor(){return this.#kl}set backgroundColor(i){i instanceof ColorRGBA||consoleAndThrowError("allow only ColorRGBA instance"),this.#kl=i}get detector(){return this.#Jh}get configurationDescription(){return this.#qh}get gpuAdapter(){return this.#yt}get alphaMode(){return this.#Yh}set alphaMode(i){this.#Yh=i,this.#sf()}get gpuContext(){return this.#Wh}get gpuDevice(){return this.#f}get htmlCanvas(){return this.#Nt}get keyboardKeyBuffer(){return this.#rf}set keyboardKeyBuffer(i){this.#rf=i}get resourceManager(){return this.#Qh}get sizeManager(){return this.#Zh}get width(){return this.#Zh.width}set width(i){this.#Zh.width=i}get height(){return this.#Zh.height}set height(i){this.#Zh.height=i}get screenRectObject(){return this.#Zh.screenRectObject}get pixelRectObject(){return this.#Zh.pixelRectObject}get renderScale(){return this.#Zh.renderScale}set renderScale(i){this.#Zh.renderScale=i,this.viewList.forEach(i=>{i.setPosition(),i.setSize()})}destroy(){this.#nf?.stop(),this.#f.destroy()}setSize(i=this.width,g=this.height){this.sizeManager.setSize(i,g)}#of(){this.#if=this.#Nt.getBoundingClientRect()}#af(){this.#sf(),this.#of(),this.sizeManager.setSize("100%","100%"),this.#nf=new RedGPUContextObserver(this,()=>this.#of());(this.detector.isMobile?["click","touchmove","touchstart","touchend"]:["click","mousemove","mousedown","mouseup"]).forEach(g=>{const x=this.detector.isMobile?{click:i.CLICK,touchmove:i.MOVE,touchstart:i.DOWN,touchend:i.UP}:{click:i.CLICK,mousemove:i.MOVE,mousedown:i.DOWN,mouseup:i.UP};this.#Nt.addEventListener(g,g=>{const v=x[g.type];this.viewList.forEach(x=>{this.detector.isMobile&&g instanceof TouchEvent&&g.touches.length>0?(x.pickingManager.mouseX=g.touches[0].clientX-x.pixelRectObject.x,x.pickingManager.mouseY=g.touches[0].clientY-x.pixelRectObject.y):g instanceof MouseEvent&&(x.pickingManager.mouseX=g.offsetX-x.pixelRectObject.x,x.pickingManager.mouseY=g.offsetY-x.pixelRectObject.y),v===i.CLICK?x.pickingManager.lastMouseClickEvent={...g,type:v}:x.pickingManager.lastMouseEvent={...g,type:v}})})});{const HD_keyDown=i=>{this.#rf[i.key]=!0},HD_keyUp=i=>{this.#rf[i.key]=!1};window?.addEventListener("keyup",HD_keyUp),window?.addEventListener("keydown",HD_keyDown)}}#sf(){const i=navigator.gpu.getPreferredCanvasFormat();this.#qh={device:this.#f,format:i,alphaMode:this.#Yh},this.#Wh.configure(this.#qh)}}Object.freeze(RedGPUContext);const init=async(i,x,v,_,y="premultiplied",b={powerPreference:"high-performance",forceFallbackAdapter:!1})=>{if(isSearchEngineBot())return void g("🤖 Search engine bot detected - skipping WebGPU initialization");const{gpu:S}=navigator;if(!S){const i="WebGPU is not supported in this browser. Please use a modern browser with WebGPU enabled.";return void v?.(i)}const errorHandler=(i,g)=>{const x=generateErrorMessage(i,g);console.error("\n============\n",x,"\n============\n"),v?.(x)},validateAndRequestDevice=async g=>{const x=[];[].forEach(i=>{g?.features.has(i)&&x.push(i)});const v={};["maxBufferSize","maxStorageBufferBindingSize","maxSampledTexturesPerShaderStage","maxSamplersPerShaderStage","maxStorageBuffersPerShaderStage","maxStorageTexturesPerShaderStage","maxUniformBuffersPerShaderStage","maxUniformBufferBindingSize","maxBindGroups","maxVertexAttributes","maxVertexBuffers","maxInterStageShaderComponents","maxComputeWorkgroupStorageSize","maxComputeInvocationsPerWorkgroup","maxComputeWorkgroupSizeX","maxComputeWorkgroupSizeY","maxComputeWorkgroupSizeZ","maxComputeWorkgroupsPerDimension"].forEach(i=>{g.limits[i]&&(v[i]=g.limits[i])});const _={requiredFeatures:x,requiredLimits:v};try{const x=await g.requestDevice(_);validateAndInitializeContext(i,g,x)}catch(i){errorHandler(null,`Failed to request device. Adapter was ${g}, error message is ${i.message}`)}},validateAndInitializeContext=(i,v,b)=>{const S=i.getContext("webgpu");if(S)try{{const i=b.createShaderModule.bind(b);b.createShaderModule=function(g){return g.code=ensureVertexIndexBuiltin(g.code),i(g)}}const w=new RedGPUContext(i,v,b,S,y);x(w),b.addEventListener("uncapturederror",i=>{console.warn("TODO A WebGPU error was not captured:",i),console.warn(i.error?.message),window.cancelAnimationFrame(w.currentRequestAnimationFrame)}),b.lost.then(i=>{console.warn(i),console.warn(`Device lost occurred: ${i.message}`),"destroyed"===i.reason&&_?.(i)});const clearDevice=()=>{if(w.gpuContext)try{w.gpuContext.unconfigure(),g("🧹 Canvas Context unconfigure 완료")}catch(i){g("⚠️ Canvas Context unconfigure 실패:",i)}window?.cancelAnimationFrame(w.currentRequestAnimationFrame),w.gpuDevice.destroy()};window?.addEventListener("beforeunload",()=>{w&&w.gpuDevice&&(g("🧹 페이지 종료 시 GPU 디바이스 정리"),clearDevice())}),window?.addEventListener("pageshow",i=>{i.persisted&&(g("🔄 bfcache에서 복원됨 (뒤로가기 또는 앞으로가기) - 페이지 재로드"),window.location.reload())}),window?.addEventListener("pagehide",i=>{i.persisted&&(g("💾 bfcache에 저장됨"),w&&w.gpuDevice&&clearDevice())})}catch(i){errorHandler(i,"")}else errorHandler(new Error(`Failed to get context from canvas: ${i.id||i}`),"Failed to get webgpu initialize from canvas")},initializeWebGPU=async()=>{x instanceof Function?i instanceof HTMLCanvasElement?await(async i=>{i||errorHandler(null,"Cannot find navigator.gpu");try{const g=await i.requestAdapter(b);await validateAndRequestDevice(g)}catch(g){errorHandler(g,`Failed to request adapter or validate device with target GPU: ${i}, error message is ${g.message}`)}})(S):errorHandler(null,`Expected HTMLCanvasElement, but received : ${i}`):errorHandler(null,`Expected onWebGPUInitialized, but received : ${x}`)};try{await initializeWebGPU()}catch(i){errorHandler(i,`Unexpected error occurred during WebGPU initialization: ${i.message}`)}},generateErrorMessage=(i,g)=>{let x=g;return i instanceof Error?(x=i.message??g,"string"==typeof i.stack&&(x+=`\nStack Trace: ${i.stack}`)):console.warn("generateErrorMessage function expected an Error instance, but got: ",i),x},isSearchEngineBot=()=>{if("undefined"==typeof navigator||"undefined"==typeof window)return!0;const i=navigator.userAgent.toLowerCase();return["googlebot","bingbot","slurp","duckduckbot","baiduspider","yandexbot","facebookexternalhit","twitterbot","rogerbot","linkedinbot","embedly","quora link preview","showyoubot","outbrain","pinterest/0.","developers.google.com/+/web/snippet","www.google.com/webmasters/tools/richsnippets","slackbot","vkshare","w3c_validator","redditbot","applebot","whatsapp","flipboard","tumblr","bitlybot","skypeuripreview","nuzzel","line","discordbot","telegrambot","crawler","spider","bot"].some(g=>i.includes(g))};class TextureLoaderData{src;texture;loadEnd;loadSuccess;srcInfo;idx;constructor(i,g,x){this.src=i,this.texture=null,this.loadEnd=!1,this.loadSuccess=!1,this.srcInfo=g,this.idx=x}}class TextureLoader extends RedGPUObject{textures=[];#uf=0;#lf;#Oa;#cf;constructor(i,g=[],x,v){super(i),this.#lf=g,this.#Oa=x,this.#cf=v,this.#lf.length?this.#lf.forEach((i,g)=>this.#hf(i,g)):this.#ff()}getTextureByIndex(i){if(this.textures[i])return this.textures[i].texture}#hf(i,g){const{redGPUContext:x}=this;let v,_,y=BitmapTexture;_=i.hasOwnProperty("src")?i.src:i,_ instanceof Array&&(y=CubeTexture),v=new TextureLoaderData(_,i,g);const onLoadHandler=()=>{v.loadSuccess=!0,v.loadEnd=!0,this.#df()},onErrorHandler=()=>{v.loadSuccess=!1,v.loadEnd=!0,this.#df()};v.texture=y===BitmapTexture?new y(x,{src:i.src,cacheKey:i.cacheKey},i.useMipmap,onLoadHandler,onErrorHandler,i.format,!1):new y(x,{src:i.src,cacheKey:i.cacheKey},i.useMipmap,onLoadHandler,onErrorHandler,i.format),this.textures.push(v),this.#mf()}#mf(){const i=this.#lf.length,g=this.#uf;this.#cf&&this.#cf.call(this,{total:i,loaded:g,percent:Math.min(100,parseFloat((g/i*100).toFixed(2)))})}#df(){this.#uf++,this.#mf(),this.#uf===this.#lf.length&&this.#ff()}#ff(){requestAnimationFrame(()=>{this.#Oa&&this.#Oa.call(this,this)})}}const checkProgress=(i,g,x)=>{const v=g.buffers.length;i.loadingProgressInfo.buffers={loaded:x,total:v,percent:Math.min(100,parseFloat((x/v*100).toFixed(2)))}},ua=new Map,la=new Map,arrayBufferLoader=(i,g,x)=>{if(i=getAbsoluteURL(window.location.href,i),ua.has(i))return void g?.(ua.get(i));if(la.has(i))return void la.get(i).then(i=>g?.(i)).catch(i=>x?.(i));const v=fetch(i).then(i=>{if(!i.ok)throw new Error(`Network response was not ok: ${i.statusText}`);return i.arrayBuffer()}).then(g=>(ua.set(i,g),g)).finally(()=>{la.delete(i)});la.set(i,v),v.then(i=>g?.(i)).catch(i=>x?.(i))},ca={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array};Object.freeze(ca);class AccessorInfo_GLTF{accessor;bufferView;bufferGlTfId;buffer;bufferURIDataView;componentType;componentType_BYTES_PER_ELEMENT;getMethod;accessorBufferOffset;bufferViewOffset;bufferViewByteStride;startIndex;constructor(i,g,x){switch(this.accessor=g.accessors[x],this.bufferView=g.bufferViews[this.accessor.bufferView],this.bufferGlTfId=this.bufferView.buffer,this.buffer=g.buffers[this.bufferGlTfId],this.bufferURIDataView=null,this.buffer.uri&&(this.bufferURIDataView=i.parsingResult.uris.buffers[this.bufferGlTfId]),this.componentType=ca[this.accessor.componentType],this.componentType_BYTES_PER_ELEMENT=this.componentType.BYTES_PER_ELEMENT,this.componentType){case Float32Array:this.getMethod="getFloat32";break;case Uint32Array:this.getMethod="getUint32";break;case Uint16Array:this.getMethod="getUint16";break;case Int16Array:this.getMethod="getInt16";break;case Uint8Array:this.getMethod="getUint8";break;case Int8Array:this.getMethod="getInt8";break;default:consoleAndThrowError("파싱할수없는 타입",this.componentType)}this.accessorBufferOffset=this.accessor.byteOffset||0,this.bufferViewOffset=this.bufferView.byteOffset||0,this.bufferViewByteStride=this.bufferView.byteStride||0,this.startIndex=(this.bufferViewOffset+this.accessorBufferOffset)/this.componentType_BYTES_PER_ELEMENT}}class AnimationData_GLTF{gltfLoader;scenesData;accessorGlTfId;dataList;constructor(i,g,x){this.gltfLoader=i,this.scenesData=g,this.accessorGlTfId=x;const v=new AccessorInfo_GLTF(this.gltfLoader,this.scenesData,this.accessorGlTfId),{accessor:_,startIndex:y,componentType_BYTES_PER_ELEMENT:b,bufferURIDataView:S,getMethod:w}=v,{type:L,count:k}=_;let H=y,z=1;switch(L){case"SCALAR":z=1;break;case"VEC4":z=4;break;case"VEC3":z=3}const q=[];let W=0;for(;Wanimation_data_list:array;@group(0)@binding(1)varuniforms:Uniforms;@group(0)@binding(2)varvertices:array;@group(0)@binding(3)varorigin_data:array;@group(0)@binding(4)varmorph_interleave_data:array;@compute @workgroup_size(64)fn main(@builtin(global_invocation_id)global_id:vec3){let vertex_index=global_id.x;let vertex_count=u32(uniforms.vertex_count);let stride=u32(uniforms.vertex_stride);let morph_length=u32(uniforms.morph_length);if(vertex_index>=vertex_count){return;}let base_vertex_index=vertex_index*stride;let base_vertex_index2=vertex_index*3u;let prev_time_offset=u32(uniforms.prev_time_data_index)*morph_length;let next_time_offset=u32(uniforms.next_time_data_index)*morph_length;var prev_weight=origin_data[base_vertex_index];var next_weight=origin_data[base_vertex_index];var prev_weight1=origin_data[base_vertex_index+1u];var next_weight1=origin_data[base_vertex_index+1u];var prev_weight2=origin_data[base_vertex_index+2u];var next_weight2=origin_data[base_vertex_index+2u];for(var morph_index=0u;morph_indexArray.from(i.interleaveData)),S=x.createBuffer({size:4*b.length,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST});x.queue.writeBuffer(y,0,v.origin),x.queue.writeBuffer(S,0,new Float32Array(b));const w=x.createBindGroup({layout:this.#Hr.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:this.#gf}},{binding:1,resource:{buffer:this.#se}},{binding:2,resource:{buffer:_.gpuBuffer}},{binding:3,resource:{buffer:y}},{binding:4,resource:{buffer:S}}]});this.#xf.set(g,{bindGroup:w,originBuffer:y,morphInterleavedBuffer:S})}}const parseAnimations=(i,g)=>new Promise(async x=>{g.animations||(g.animations=[]);const{parsingResult:v}=i,{animations:_}=v,{animations:y}=g;if(y.length){const x=y.map(async x=>{const{samplers:v,channels:y}=x,b=[];b.minTime=1e7,b.maxTime=-1,b.name=x.name,_.push(b),await Promise.all(y.map(async x=>((i,g,x,v,_)=>{let y,b;const{nodes:S,meshes:w}=_,L=[],{sampler:k,target:H}=x,z=v[k],{node:q,path:W}=H,be=S[q];if("mesh"in be){y=be.Mesh;const{primitives:i}=w[be.mesh];let g=i.length;for(;g--;)L.push(i[g].Mesh)}else{let g;if(!i.parsingResult.groups[q])return;g=i.parsingResult.groups[q],y=g}if("scale"!=W&&"rotation"!=W&&"translation"!=W&&"weights"!=W||(b=new AniTrack_GLTF(W,new AnimationData_GLTF(i,_,z.input),new AnimationData_GLTF(i,_,z.output),z.interpolation,y,L),g.push(b)),b){const{timeAnimationInfo:i}=b,{dataList:x}=i;g.minTime>x[0]&&(g.minTime=x[0]),g.maxTimei.playAnimation(g))}x()});class ParsedSkinInfo_GLTF{joints;inverseBindMatrices;skeletonMesh;vertexStorageInfo;vertexStorageBuffer;prevVertexStorageBuffer;invertNodeGlobalTransform;usedJoints=null;WORK_SIZE=64;jointData;uniformBuffer;computeShader;computePipeline;bindGroup;constructor(){this.joints=[],this.inverseBindMatrices=null,this.skeletonMesh=null}getUsedJointIndices(i){const g=new Set,{jointBuffer:x}=i.animationInfo;if(!x.data.length)return[];const v=x.data,_=v.length;for(let i=0;i<_;i++){const x=i;for(let i=0;i<4;i++){const _=Math.floor(v[x+i]);_>=0&&_,\n\t\t\t jointModelMatrices: array, ${this.usedJoints.length}>,\n\t\t\t inverseBindMatrices: array, ${this.joints.length}>,\n\t\t\t searchJointIndexTable: array, ${this.joints.length}>,\n\t\t\t};\n\t\t\t\n\t\t\t@group(0) @binding(0) var vertexWeight: array>;\n\t\t\t@group(0) @binding(1) var vertexJoint: array>;\n\t\t\t@group(0) @binding(2) var skinMatrixBuffer: array>;\n\t\t\t@group(0) @binding(3) var prevSkinMatrixBuffer: array>;\n\t\t\t@group(0) @binding(4) var uniforms: Uniforms;\n\t\t\t\n\t\t\t@compute @workgroup_size(${this.WORK_SIZE},1,1)\n\t\t\tfn main(@builtin(global_invocation_id) global_id: vec3) { \n\t\t\t let idx = global_id.x;\n\t\t\t if (idx >= arrayLength(&vertexWeight)) {\n\t\t\t return;\n\t\t\t }\n\t\t\t\n\t\t\t let weights = vertexWeight[idx];\n\t\t\t let joints = vertexJoint[idx];\n\t\t\t prevSkinMatrixBuffer[idx] = skinMatrixBuffer[idx];\n\t\t\t skinMatrixBuffer[idx] = uniforms.invertNodeGlobalTransform * (\n\t\t\t\t weights.x * (\n\t\t\t\t \tuniforms.jointModelMatrices[uniforms.searchJointIndexTable[joints.x].x] * uniforms.inverseBindMatrices[joints.x]\n\t\t\t\t ) +\n\t\t\t\t weights.y * (\n\t\t\t\t \tuniforms.jointModelMatrices[uniforms.searchJointIndexTable[joints.y].x] * uniforms.inverseBindMatrices[joints.y]\n\t\t\t\t ) +\n\t\t\t\t weights.z * (\n\t\t\t\t \tuniforms.jointModelMatrices[uniforms.searchJointIndexTable[joints.z].x] * uniforms.inverseBindMatrices[joints.z]\n\t\t\t\t ) +\n\t\t\t\t weights.w * (\n\t\t\t\t \tuniforms.jointModelMatrices[uniforms.searchJointIndexTable[joints.w].x] * uniforms.inverseBindMatrices[joints.w]\n\t\t\t\t )\n\t\t\t\t);\n\t\t\t}\n `;this.jointData=new Float32Array(16*(1+this.usedJoints.length)),this.computeShader=i.resourceManager.createGPUShaderModule(`calcSkinMatrix_${this.usedJoints.length}`,{code:y}),this.computePipeline=g.createComputePipeline({label:"calcSkinMatrix",layout:"auto",compute:{module:this.computeShader,entryPoint:"main"}}),this.uniformBuffer=g.createBuffer({size:this.jointData.byteLength+16*this.joints.length*4+4*this.joints.length*4,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),g.queue.writeBuffer(this.uniformBuffer,this.jointData.byteLength,new Float32Array(this.inverseBindMatrices.map(i=>Array.from(i)).flat()));const b=new Uint32Array(4*this.joints.length);b.fill(0),this.usedJoints.forEach((i,g)=>{b[4*i]=g}),g.queue.writeBuffer(this.uniformBuffer,this.jointData.byteLength+16*this.joints.length*4,b),this.bindGroup=g.createBindGroup({layout:this.computePipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:v.gpuBuffer}},{binding:1,resource:{buffer:_.gpuBuffer}},{binding:2,resource:{buffer:this.vertexStorageBuffer}},{binding:3,resource:{buffer:this.prevVertexStorageBuffer}},{binding:4,resource:{buffer:this.uniformBuffer}}]})}}const parseJoint_GLTF=(i,g,x,v)=>{const _=x[v].Mesh;_?g.joints.push(_):requestAnimationFrame(function(){parseJoint_GLTF(i,g,x,v)})},calculateNormals=(i,g)=>{let x,v,_=[],y=g;const b=i.length/3;if(!g||0===g.length){g=[];for(let i=0;i{const y=x.sparse;if(!y)return;const{values:b,indices:S,count:w}=y,L=v.bufferViews,k=L[b.bufferView],H=k.buffer,z=v.buffers,q=z[H],W=[],be=[],je=L[S.bufferView],Ke=je.buffer,Xe=z[Ke];let Ye;q.uri&&(Ye=i.parsingResult.uris.buffers[H]);const Ze=ca[x.componentType],{BYTES_PER_ELEMENT:Je}=Ze;let Qe;switch(Ze){case Float32Array:Qe="getFloat32";break;case Uint32Array:Qe="getUint32";break;case Uint16Array:Qe="getUint16";break;case Int16Array:Qe="getInt16";break;case Uint8Array:Qe="getUint8";break;case Int8Array:Qe="getInt8"}const et=x.byteOffset||0;let tt,it,ft=((k.byteOffset||0)+et)/Je;switch(x.type){case"VEC3":for(tt=ft+Je*w/Je*3;ft{const _=new MorphInfoData_GLTF;for(let v in x){const{vertices:y,verticesColor_0:b,normals:S,uvs:w,uvs1:L,uvs2:k,jointWeights:H,joints:z,tangents:q}=_,W=x[v],be=new AccessorInfo_GLTF(i,g,W),{accessor:je}=be;parseAttributeInfo_GLTF(v,be,y,w,L,0,S,H,z,b,q),je.sparse&&parseSparse_GLTF(i,v,je,g,y)}return v.length&&(_.interleaveData=new Float32Array(_.vertices)),_})),this.weights=v||[],this.origin=null}}const parseMaterialTexture=(i,g,x,v,_,y=!0)=>{const{redGPUContext:b,gltfData:S}=i,{textureRawList:w}=i.parsingResult,L=x.index,k=S.textures[L],H=k.extensions?.EXT_texture_webp?.source||k.source,z=getURL(i,S,H);if(z){const L=k.sampler,q=getSamplerInfo(i,S,L),{parsedURI:W,cacheKey:be}=z,je=`${v}SourceGlTfId_${H}`;if(w[je]?(w[je].materialList.push(g),w[je].samplerList.push(new Sampler(b,q))):w[je]={src:W,cacheKey:be,targetTextureKey:v,targetSamplerKey:`${v}Sampler`,materialList:[g],samplerList:[new Sampler(b,q)],format:_||navigator.gpu.getPreferredCanvasFormat(),useMipmap:y},g[`${v}_texCoord_index`]=x.texCoord||0,"extensions"in x){const{extensions:i}=x,{KHR_texture_transform:_}=i;_&&((i,g,x)=>{i[`${g}_KHR_texture_transform_offset`]=x.offset||[0,0],i[`${g}_KHR_texture_transform_scale`]=x.scale||[1,1],i[`${g}_KHR_texture_transform_rotation`]=x.rotation||0,i[`use_${g}_KHR_texture_transform`]=!0})(g,v,_)}}},getURL=function(i,g,x){if(!g.images[x])return null;const{uri:v}=g.images[x];let _;const y=`${i.url}_${x}`;return _=v.indexOf("blob:http")>-1?v:(v.indexOf(";base64,")>-1?"":i.filePath)+v,{parsedURI:_,cacheKey:y}},getSamplerInfo=function(i,g,x){const _={magFilter:y.LINEAR,minFilter:y.LINEAR,mipmapFilter:y.LINEAR,addressModeU:v.REPEAT,addressModeV:v.REPEAT,addressModeW:v.REPEAT},b={33071:v.CLAMP_TO_EDGE,33648:v.MIRRORED_REPEAT,10497:v.REPEAT},S={9728:y.NEAREST,9729:y.LINEAR},w={9728:y.NEAREST,9729:y.LINEAR};if(g.samplers){let i=g.samplers[x];i&&("magFilter"in i&&(_.magFilter=S[i.magFilter]||y.LINEAR),"minFilter"in i&&(_.minFilter=w[i.minFilter]||y.LINEAR),"wrapS"in i&&(_.addressModeU=b[i.wrapS]),"wrapT"in i&&(_.addressModeV=b[i.wrapT]))}return _.string=JSON.stringify(_),_},parseMaterialInfo_GLTF=(i,g,x)=>{const{redGPUContext:v}=i;let _,y=!1,b="OPAQUE",S=.5;if("material"in x){_=new PBRMaterial(v);const w=x.material,L=g.materials[w];y=!!L.doubleSided,b=L.alphaMode??b,S=L.alphaCutoff??S;const{pbrMetallicRoughness:k,normalTexture:H,emissiveTexture:z,occlusionTexture:q}=L;if(_.emissiveFactor=L.emissiveFactor||[0,0,0],k){const{metallicRoughnessTexture:g,baseColorTexture:x}=k;let v,y;_.baseColorFactor=k.baseColorFactor||[1,1,1,1],"metallicFactor"in k&&(v=k.metallicFactor),"roughnessFactor"in k&&(y=k.roughnessFactor),_.metallicFactor=null!=v?v:1,_.roughnessFactor=null!=y?y:1,x&&parseMaterialTexture(i,_,x,"baseColorTexture",`${navigator.gpu.getPreferredCanvasFormat()}-srgb`),g&&parseMaterialTexture(i,_,g,"metallicRoughnessTexture",null,!1)}if(H){parseMaterialTexture(i,_,H,"normalTexture");const{scale:g}=H;_.normalScale=null!=g?g:1}if(z&&parseMaterialTexture(i,_,z,"emissiveTexture",`${navigator.gpu.getPreferredCanvasFormat()}-srgb`),q&&(parseMaterialTexture(i,_,q,"occlusionTexture",null,!1),_.occlusionStrength=L.occlusionTexture.strength||1),"extensions"in L){const{extensions:g}=L,{KHR_materials_clearcoat:x,KHR_materials_emissive_strength:v,KHR_materials_transmission:y,KHR_materials_diffuse_transmission:S,KHR_materials_volume:w,KHR_materials_unlit:k,KHR_materials_ior:H,KHR_materials_sheen:z,KHR_materials_specular:q,KHR_materials_dispersion:W,KHR_materials_anisotropy:be,KHR_materials_iridescence:je}=g;if(je&&((i,g,x)=>{i.useKHR_materials_iridescence=!0,i.KHR_iridescenceFactor=g.iridescenceFactor||0,i.KHR_iridescenceIor=g.iridescenceIor||1.3,i.KHR_iridescenceThicknessMinimum=g.iridescenceThicknessMinimum||100,i.KHR_iridescenceThicknessMaximum=g.iridescenceThicknessMaximum||400,i.transparent=!0;{const{iridescenceTexture:v,iridescenceThicknessTexture:_}=g;v&&parseMaterialTexture(x,i,v,"KHR_iridescenceTexture",null,!1),_&&parseMaterialTexture(x,i,_,"KHR_iridescenceThicknessTexture",null,!1)}})(_,je,i),be&&((i,g,x)=>{i.useKHR_materials_anisotropy=!0,i.KHR_anisotropyStrength=g.anisotropyStrength||0,i.KHR_anisotropyRotation=g.anisotropyRotation||0;const{anisotropyTexture:v}=g;v&&parseMaterialTexture(x,i,v,"KHR_anisotropyTexture")})(_,be,i),x&&((i,g,x)=>{i.KHR_clearcoatFactor=g.clearcoatFactor||0,i.KHR_clearcoatRoughnessFactor=g.clearcoatRoughnessFactor||0,i.useKHR_materials_clearcoat=!0;const{clearcoatTexture:v,clearcoatNormalTexture:_,clearcoatRoughnessTexture:y}=g;v&&parseMaterialTexture(x,i,v,"KHR_clearcoatTexture",null,!1),_&&parseMaterialTexture(x,i,_,"KHR_clearcoatNormalTexture"),y&&parseMaterialTexture(x,i,y,"KHR_clearcoatRoughnessTexture",null,!1)})(_,x,i),v){const{emissiveStrength:i}=v;_.emissiveStrength=null!=i?i:1}if(y&&(((i,g,x)=>{i.useKHR_materials_transmission=!0,i.KHR_transmissionFactor=g.transmissionFactor||0,i.use2PathRender=!0;{const v=g.transmissionTexture;v&&parseMaterialTexture(x,i,v,"KHR_transmissionTexture",null,!1)}})(_,y,i),_.transparent="BLEND"===b),S&&((i,g,x)=>{i.useKHR_materials_diffuse_transmission=!0,i.KHR_diffuseTransmissionFactor=g.diffuseTransmissionFactor||0,i.KHR_diffuseTransmissionColorFactor=g.diffuseTransmissionColorFactor||[1,1,1],i.transparent=!0;{const v=g.diffuseTransmissionTexture;v&&parseMaterialTexture(x,i,v,"KHR_diffuseTransmissionTexture",null,!1);const _=g.diffuseTransmissionColorTexture;_&&parseMaterialTexture(x,i,_,"KHR_diffuseTransmissionColorTexture",`${navigator.gpu.getPreferredCanvasFormat()}-srgb`,!1)}})(_,S,i),w&&(((i,g,x)=>{i.useKHR_materials_volume=!0,i.KHR_thicknessFactor=g.thicknessFactor||1,i.KHR_attenuationDistance=g.attenuationDistance||1,i.KHR_attenuationColor=g.attenuationColor||[1,1,1],i.use2PathRender=!0,i.transparent=!0;{const v=g.thicknessTexture;v&&parseMaterialTexture(x,i,v,"KHR_thicknessTexture",null,!1)}})(_,w,i),b="BLEND"),k&&(_.useKHR_materials_unlit=!0),H){const{ior:i}=H;_.KHR_materials_ior=null!=i?i:1.5,_.use2PathRender=!0,_.transparent=!0}if(W){const{dispersion:i}=W;_.KHR_dispersion=i||0,_.use2PathRender=!0,_.transparent=!0}z&&((i,g,x)=>{i.KHR_sheenColorFactor=g.sheenColorFactor||[0,0,0],i.KHR_sheenRoughnessFactor=g.sheenRoughnessFactor||0,i.useKHR_materials_sheen=!0;const{sheenColorTexture:v,sheenRoughnessTexture:_}=g;v&&parseMaterialTexture(x,i,v,"KHR_sheenColorTexture",`${navigator.gpu.getPreferredCanvasFormat()}-srgb`,!1),_&&parseMaterialTexture(x,i,_,"KHR_sheenRoughnessTexture",null,!1)})(_,z,i),q&&((i,g,x)=>{i.useKHR_materials_specular=!0,i.KHR_specularFactor=g.specularFactor??1,i.KHR_specularColorFactor=g.specularColorFactor||[1,1,1];const{specularTexture:v,specularColorTexture:_}=g;v&&parseMaterialTexture(x,i,v,"KHR_specularTexture"),_&&parseMaterialTexture(x,i,_,"KHR_specularColorTexture",`${navigator.gpu.getPreferredCanvasFormat()}-srgb`)})(_,q,i)}}else _=new PBRMaterial(v);Object.hasOwn(x.attributes,"COLOR_0")&&(_.useVertexColor=!0),_.doubleSided=y,_.cutOff=S;const{blendColorState:w,blendAlphaState:L}=_;switch(b){case"BLEND":_.alphaBlend=2,w.srcFactor=ui.SRC_ALPHA,w.dstFactor=ui.ONE_MINUS_SRC_ALPHA,L.srcFactor=ui.SRC_ALPHA,L.dstFactor=ui.ONE_MINUS_SRC_ALPHA,_.transparent=!0;break;case"MASK":_.alphaBlend=1,_.useCutOff=!0,w.srcFactor=ui.ONE,w.dstFactor=ui.ZERO,L.srcFactor=ui.ONE,L.dstFactor=ui.ZERO;break;default:w.srcFactor=ui.ONE,w.dstFactor=ui.ZERO,L.srcFactor=ui.ONE,L.dstFactor=ui.ZERO,_.alphaBlend=0}return _},parseIndicesInfo_GLTF=(i,g)=>{const{accessor:x,startIndex:v,getMethod:_,bufferURIDataView:y,componentType_BYTES_PER_ELEMENT:b}=i,{type:S,count:w}=x;let L,k=v;if("SCALAR"===S)for(L=k+w;k{let z,q,W,be,je,Ke,Xe,Ye,Ze,Je=0,Qe=g.length/3,et=0;const tt=g.length,it=v.length,ft=y.length,pt=x.length,xt=S.length,vt=w.length,yt=L.length;if(z=W=Ke=0,q=be=Xe=1,je=Ye=2,Ze=3,k)for(;Je{let x=i[0],v=i[1],_=i[2],y=i[3],b=x+x,S=v+v,w=_+_,L=x*b,k=x*S,H=x*w,z=v*S,q=v*w,W=_*w,be=y*b,je=y*S,Ke=y*w;return g[0]=1-(z+W),g[4]=k-Ke,g[8]=H+je,g[1]=k+Ke,g[5]=1-(L+W),g[9]=q-be,g[2]=H-je,g[6]=q+be,g[10]=1-(L+z),g[3]=0,g[7]=0,g[11]=0,g[12]=0,g[13]=0,g[14]=0,g[15]=1,g},ha=180/Math.PI,setMeshRotation=(i,g)=>{g.setRotation(i[0]*ha,i[1]*ha,i[2]*ha)},parseTRSAndMATRIX_GLTF=(i,g)=>{const{matrix:x,rotation:v,translation:_,scale:y}=g;let b,S;if(b=create$4(),"matrix"in g){S=create$3(),mat4ToEuler(x,S),setMeshRotation(S,i),i.setPosition(x[12],x[13],x[14]);const g=fromValues$3(1,1,1);getScaling(g,x),i.setScale(g[0],g[1],g[2])}else"rotation"in g&&(S=create$3(),quaternionToRotationMat4(v,b),mat4ToEuler(b,S),setMeshRotation(S,i)),"translation"in g&&i.setPosition(_[0],_[1],_[2]),"scale"in g&&(i.setScale(y[0],y[1],y[2]),(y[0]<0||y[1]<0||y[2]<0)&&(i.primitiveState.frontFace=Qi.CW))},parseChildrenAndSkin=(i,g,x,v,_)=>{if("children"in v){const _=v.children,y=_.length;for(let v=0;v{const _=new ParsedSkinInfo_GLTF,y=[],{nodes:b}=g,{joints:S,skeleton:w}=x;{let g=0;const x=S.length;for(;g{const{redGPUContext:_,parsingResult:y}=i,{nodes:b,meshes:S,skins:w}=g,{groups:L,cameras:k}=y,H=b[x];if("mesh"in H){const _=function(i,g,x,v){const{redGPUContext:_}=i;let y;x.name&&(y=x.name);const b=[],{primitives:S}=x;let w=0;const L=S.length;for(;w-1;if(y){const i=`TEXCOORD_${tt.size}`;tt.set(x,i)}parseAttributeInfo_GLTF(y?tt.get(x):x,_,W,je,Ke,0,Ye,Ze,Je,be,Qe),_.accessor.sparse&&parseSparse_GLTF(i,x,_.accessor,g,W)}if("indices"in L){let x=L.indices,v=new AccessorInfo_GLTF(i,g,x);parseIndicesInfo_GLTF(v,q)}H=parseMaterialInfo_GLTF(i,g,L),H instanceof PBRMaterial&&i.parsingResult.materials.push(H);let it,ft=!1;if("mode"in L)switch(L.mode){case 0:z=Ei.POINT_LIST;break;case 1:case 2:z=Ei.LINE_LIST;break;case 3:z=Ei.LINE_STRIP,ft=!0;break;case 4:case 6:z=Ei.TRIANGLE_LIST;break;case 5:z=Ei.TRIANGLE_STRIP,ft=!0}be.length&&(H.useVertexColor_0=!0),it=Ye.length?Ye:calculateNormals(W,q),Qe.length>0||(Qe=Array.from(calculateTangents(W,it,je,q))),Qe.length&&(H.useVertexTangent=!0);let pt,xt=[];parseInterleaveData_GLTF(xt,W,be,it,je,Ke,0,Ze,Je,Qe);let vt={};W.length&&(vt.aVertexPosition=VertexInterleaveType.float32x3),it.length&&(vt.aVertexNormal=VertexInterleaveType.float32x3),je.length&&(vt.aTexcoord=VertexInterleaveType.float32x2),(Xe.length||Ke.length||je.length)&&(vt.aTexcoord1=VertexInterleaveType.float32x2),vt.aVertexColor_0=VertexInterleaveType.float32x4,vt.aVertexTangent=VertexInterleaveType.float32x4;const yt=[],bt=[];parseInterleaveData_GLTF(yt,W,be,it,je,Ke,0,Ze,Je,Qe,!0),parseInterleaveData_GLTF(bt,W,be,it,je,Ke,0,Ze,Je,Qe,!1,!0);const St=new VertexBuffer(_,yt,new VertexInterleavedStruct({aVertexWeight:VertexInterleaveType.float32x4}),void 0,`Weight_${i.url}_${v}_${w}`),Tt=new IndexBuffer(_,bt,GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST,`Joint_${i.url}_${v}_${w}`);let wt=new MorphInfo_GLTF(i,g,L,x.weights);const Mt=`Vertex_${i.url}_${v}_${w}_${wt.weights.length?createUUID():""}`,Pt=_.resourceManager.managedVertexBufferState.table.get(Mt)?.buffer;if(pt=new Geometry(_,Pt||new VertexBuffer(_,xt,new VertexInterleavedStruct(vt,"PBR"),void 0,Mt),!ft&&q.length?new IndexBuffer(_,new Uint32Array(q),void 0,`Index_${i.url}_${v}_${w}`):null),H||consoleAndThrowError("재질을 파싱할수없는경우 ",L),k=new Mesh(_,pt,H),k.animationInfo.weightBuffer=St,k.animationInfo.jointBuffer=Tt,y&&(k.name=y,i.parsingOption))for(let g in i.parsingOption)y.toLowerCase().indexOf(g)>-1&&i.parsingOption[g](k);k.primitiveState.topology=z||Ei.TRIANGLE_LIST,k.material.doubleSided&&(k.primitiveState.cullMode=Ji.NONE),k.material.use2PathRender&&(k.primitiveState.cullMode=Ji.NONE,k.depthStencilState.depthCompare=Er.LESS_EQUAL),2===k.material.alphaBlend&&(k.depthStencilState.depthCompare=Er.LESS_EQUAL),k.animationInfo.morphInfo=wt,k.animationInfo.morphInfo.origin=new Float32Array(xt);let Rt=k.geometry.vertexBuffer.data;k.gpuRenderInfo||k.initGPURenderInfos();let Ct=0;for(const i in vt)Ct+=vt[i].numElements;if(!Pt){const i=k.animationInfo.morphInfo.morphInfoDataList;let g=0;const x=i.length,v=Rt.length;for(;g{x.extensionsUsed?.includes("KHR_draco_mesh_compression")&&alert("RedGPU GLTFLoader does not support the KHR_draco_mesh_compression extension. Models using this extension may not load properly."),requestAnimationFrame(()=>{(i=>{const g=i?.asset;g||consoleAndThrowError("GLTFLoader - asset must be defined"),g.version||consoleAndThrowError("GLTFLoader - asset version must be defined");const x=parseFloat(g.version);isNaN(x)&&consoleAndThrowError("GLTFLoader - asset version must be a numerical value"),x<2&&consoleAndThrowError("GLTFLoader - asset version must be 2.0 or higher")})(x),requestAnimationFrame(()=>{((i,g,x,v)=>{const{parsingResult:_}=i,{uris:y}=_,b="buffers",S=y[b],w=g.buffers,L=w.length;let k=0;checkProgress(i,g,k),w.forEach((_,y)=>{var w;function checkLoadingStatus(){checkProgress(i,g,k),v?.(i.loadingProgressInfo),k===L&&x&&x()}_._redURIkey=b,_._redURIIndex=y,_.uri instanceof ArrayBuffer?(w=new DataView(_.uri),k++,S[y]=w,checkLoadingStatus()):function(g){const x=g.startsWith("data:")?g:i.filePath+g;arrayBufferLoader(x,function(i){k++,S[y]=new DataView(i),checkLoadingStatus()},function(i,g){})}(_.uri)})})(i,x,()=>{requestAnimationFrame(()=>{((i,g,x)=>{const{scenes:v}=g;v[0].nodes.forEach(x=>{parseNode_GLTF(i,g,x,i.resultMesh)}),x?.()})(i,x,()=>{requestAnimationFrame(()=>{((i,x)=>{const{cameras:v}=x;v&&v.forEach(function(x){let v=new PerspectiveCamera;if("orthographic"==x.type);else{g(x);const i=x.perspective.yfov??x.perspective.yfieldOfView;void 0!==i&&(v.fieldOfView=180*i/Math.PI),v.farClipping=x.perspective.zfar,v.nearClipping=x.perspective.znear}i.parsingResult.cameras.push(v)})})(i,x),new TextureLoader(i.redGPUContext,Object.values(i.parsingResult.textureRawList),g=>{g.textures.forEach(i=>{const{targetTextureKey:g,targetSamplerKey:x,samplerList:v}=i.srcInfo;i.srcInfo.materialList.forEach((_,y)=>{_[g]=i.texture,v[y]&&(_[x]=v[y])})}),parseAnimations(i,x).then(i=>{v&&v()})},g=>{i.loadingProgressInfo.textures=g,_?.(i.loadingProgressInfo)})})})})},_)})})},fa=new Map,da=new Map,parseFileGLB=async(i,x,v)=>{const _=getAbsoluteURL(window.location.href,i.filePath+i.fileName),progress=()=>{if(v){const g=fa.get(_);i.loadingProgressInfo.model={loaded:g.byteLength,total:g.byteLength,lengthComputable:!0,percent:100,transferred:"Cached",totalSize:"Cached"},v(i.loadingProgressInfo)}};if(fa.has(_))return g("GLB Model parsing has cache",_),progress(),void await parseArrayBuffer(i,fa.get(_),x,v);if(da.has(_))return await da.get(_),progress(),void await parseArrayBuffer(i,fa.get(_),x,v);const y=new Promise((x,y)=>{(async(i,g,x=()=>{},v=()=>{})=>{try{const x=await fetch(i);if(!x.ok)throw new Error(`HTTP error! status: ${x.status}`);const _=x.headers.get("content-length"),y=_?parseInt(_,10):0,b=y>0,S=b?formatBytes(y):"Unknown";if(!x.body)return void g(new ArrayBuffer(0));const w=x.body.getReader();let L=0;const k=[];for(;;){const{done:i,value:g}=await w.read();if(i)break;g&&(k.push(g),L+=g.length,v({loaded:L,total:y,lengthComputable:b,percent:b?Math.min(100,parseFloat((L/y*100).toFixed(2))):0,transferred:formatBytes(L),totalSize:S}))}if(0===L)return void g(new ArrayBuffer(0));const H=new Blob(k);g(await H.arrayBuffer())}catch(i){x?x(i):console.error("getArrayBufferFromSrc 로딩 중 오류 발생:",i)}})(_,i=>{fa.set(_,i),g("GLB Model parsing set cache",_),da.delete(_),x(i)},i=>{g("GLB Model parsing error",i),da.delete(_),y(i)},g=>{i.loadingProgressInfo.model=g,v?.(i.loadingProgressInfo)})});da.set(_,y);try{const g=await y;await parseArrayBuffer(i,g,x,v)}catch(i){}},parseArrayBuffer=async(i,g,x,v)=>{const{content:_,binaryChunk:y}=parseBuffer(g);if(null===_)throw new Error("JSON content not found");const b=JSON.parse(_);processImagesIfExist(b,y),b.buffers[0].uri=y,i.gltfData=b,parseGLTF(i,b,x,v)},parseBuffer=i=>{let g=null,x=null;const v=new DataView(i,12),_=v.byteLength;for(let y=0;y<_;){const _=v.getUint32(y,!0);y+=4;const b=v.getUint32(y,!0);switch(y+=4,b){case 1313821514:const v=new Uint8Array(i,12+y,_);g=convertUint8ArrayToString(v);break;case 5130562:const b=12+y;x=i.slice(b,b+_)}y+=_}return{content:g,binaryChunk:x}},processImagesIfExist=(i,g)=>{const{images:x,bufferViews:v}=i,_=["image/png","image/jpeg","image/gif","image/webp"],y=new Map;if(x)for(let i=0;i{let g="";for(let x of i)g+=String.fromCharCode(x);return g},ma=new Map,pa=new Map,getData=i=>({...i,meshes:JSON.parse(JSON.stringify(i.meshes))});class GLTFLoader extends RedGPUObject{parsingResult;resultMesh;parsingOption;activeAnimations=[];#yf;#bf;#Sf;#Tf;#wf;#q;#Y;#Mf;#Pf={url:"",model:{loaded:0,total:0,lengthComputable:!0,percent:0,transferred:"0",totalSize:"0"}};constructor(i,g,x,v,_){super(i),this.#Sf=g,this.#yf=getFilePath(g),this.#bf=getFileName(g),this.#Tf=getFileExtension(g),this.#q=x,this.#Mf=v,this.#Y=_,this.parsingResult={groups:[],materials:[],uris:{buffers:[]},textures:{},textureRawList:[],cameras:[],animations:[]},this.resultMesh=new Mesh(i),this.resultMesh.gltfLoaderInfo=this,this.resultMesh.animationInfo.animationsList=this.parsingResult.animations,this.#Pf.url=getFileName(g),this.#Rf()}get loadingProgressInfo(){return this.#Pf}get filePath(){return this.#yf}get gltfData(){return this.#wf}set gltfData(i){this.#wf=i}get fileName(){return this.#bf}get url(){return this.#Sf}stopAnimation(){this.activeAnimations.length=0}playAnimation(i){const{activeAnimations:g}=this;g.push(new PlayAnimationInfo(performance.now(),i))}async#Rf(){try{"glb"===this.#Tf?parseFileGLB(this,()=>this.#q(this),this.#Mf):"gltf"===this.#Tf?(async(i,x,v)=>{const _=getAbsoluteURL(window.location.href,i.filePath+i.fileName),cachedProgress=()=>{if(v){const g=ma.get(_);i.loadingProgressInfo.model={loaded:g.byteLength,total:g.byteLength,lengthComputable:!0,percent:100,transferred:"Cached",totalSize:"Cached"},v(i.loadingProgressInfo)}};if(ma.has(_))return i.gltfData=getData(ma.get(_)),cachedProgress(),void requestAnimationFrame(()=>{parseGLTF(i,i.gltfData,x,v)});if(pa.has(_))return await pa.get(_),cachedProgress(),i.gltfData=getData(ma.get(_)),void requestAnimationFrame(()=>{parseGLTF(i,i.gltfData,x,v)});const y=new Promise(async(x,y)=>{try{const y=await fetch(i.url);if(!y.ok)throw new Error("GLTF 네트워크 오류: "+y.status);const b=y.headers.get("content-length"),S=b?parseInt(b,10):0;g(`전체 사이즈: ${S} bytes`);const w=await y.json();ma.set(_,w),i.loadingProgressInfo.model={loaded:S,total:S,lengthComputable:!0,percent:100,transferred:formatBytes(S),totalSize:formatBytes(S)};{g(w);const x=w.buffers.length;if(x){let g=0;i.loadingProgressInfo.buffers={loaded:g,total:x,percent:Math.min(100,parseFloat((g/x*100).toFixed(2)))}}}v?.(i.loadingProgressInfo),x(w)}catch(i){y(i)}finally{pa.delete(_)}});pa.set(_,y);const b=await y;i.gltfData=getData(b),requestAnimationFrame(()=>{parseGLTF(i,i.gltfData,x,v)})})(this,()=>this.#q(this),this.#Mf):consoleAndThrowError("Unknown file extension: "+this.#Tf)}catch(i){this.#Y?.(i)}}}Object.freeze(GLTFLoader);class PlayAnimationInfo{startTime;targetGLTFParsedSingleClip;constructor(i,g){this.startTime=i,this.targetGLTFParsedSingleClip=g}}var ga=Object.freeze({__proto__:null,AABB:AABB,OBB:OBB,calculateGeometryAABB:calculateGeometryAABB,calculateMeshAABB:calculateMeshAABB,calculateMeshCombinedAABB:calculateMeshCombinedAABB,calculateMeshOBB:calculateMeshOBB}),xa=Object.freeze({__proto__:null,BaseObject:BaseObject,RedGPUObject:RedGPUObject}),va=Object.freeze({__proto__:null,ACamera:ACamera,AController:AController,AutoExposure:AutoExposure,METERING_MODE:Pi});const _a=Math.PI/180,updateObject3DMatrix=(i,g)=>{const{pixelRectObject:x}=g,v=i.parent,_=i.localMatrix;identity$1(_),translate(_,_,[i.x,i.y,i.z]),rotateY$2(_,_,i.rotationY*_a),rotateX$2(_,_,i.rotationX*_a),rotateZ$2(_,_,i.rotationZ*_a);let y=[i.scaleX,i.scaleY,i.scaleZ];if(i.renderTextureWidth&&(y[0]*=i.renderTextureWidth/x.height,y[1]*=i.renderTextureHeight/x.height),scale$4(_,_,y),i.pivotX||i.pivotY||i.pivotZ){translate(_,_,[-i.pivotX,-i.pivotY,-i.pivotZ])}v?.modelMatrix?multiply$4(i.modelMatrix,v.modelMatrix,i.localMatrix):copy$4(i.modelMatrix,i.localMatrix)},ya=Math.PI/180;const ba=Math.PI/180,Sa=create$4(),Ta=create$3();class FollowController extends AController{#Cf=10;#Bf=10;#Df=.02;#Ef=5;#If=5;#Af=.02;#Lf=.02;#Uf=0;#kf=0;#Gf=.02;#Of=20;#Vf=20;#Nf=.02;#Ff=!0;#Hf=0;#zf=0;#$f=0;#jf;#Kf=create$3();constructor(i,g){super(i,{HD_Wheel:i=>{this.#Bf+=i.deltaY/100},HD_TouchPinch:i=>{const g=i-1;this.#Bf-=g*this.#Bf}}),this.targetMesh=g,this.#jf.setIgnoreFrustumCullingRecursively(!0)}get distance(){return this.#Bf}set distance(i){validateNumberRange(i,.1),this.#Bf=i}get distanceInterpolation(){return this.#Df}set distanceInterpolation(i){validateNumberRange(i,.01,1),this.#Df=i}get height(){return this.#If}set height(i){validateNumber(i),this.#If=i}get heightInterpolation(){return this.#Af}set heightInterpolation(i){validateNumberRange(i,.01,1),this.#Af=i}get pan(){return this.#kf}set pan(i){validateNumber(i),this.#kf=i}get panInterpolation(){return this.#Gf}set panInterpolation(i){validateNumberRange(i,.01,1),this.#Gf=i}get tilt(){return this.#Vf}set tilt(i){validateNumber(i),this.#Vf=Math.max(-89,Math.min(89,i))}get tiltInterpolation(){return this.#Nf}set tiltInterpolation(i){validateNumberRange(i,.01,1),this.#Nf=i}get interpolation(){return this.#Lf}set interpolation(i){validateNumberRange(i,.01,1),this.#Lf=i}get followTargetRotation(){return this.#Ff}set followTargetRotation(i){this.#Ff=i}get targetOffsetX(){return this.#Hf}set targetOffsetX(i){validateNumber(i),this.#Hf=i}get targetOffsetY(){return this.#zf}set targetOffsetY(i){validateNumber(i),this.#zf=i}get targetOffsetZ(){return this.#$f}set targetOffsetZ(i){validateNumber(i),this.#$f=i}get targetMesh(){return this.#jf}set targetMesh(i){if(!i)throw new Error("FollowController: targetMesh cannot be null or undefined");this.#jf=i,this.#jf.setIgnoreFrustumCullingRecursively(!0),this.#Xf()}setTargetOffset(i,g=0,x=0){validateNumber(i),validateNumber(g),validateNumber(x),this.#Hf=i,this.#zf=g,this.#$f=x}update(i,g){super.update(i,g,g=>{const{targetMesh:x}=this;x&&updateObject3DMatrix(x,i),this.#Cf=this.#Bf+(this.#Cf-this.#Bf)*Math.pow(this.#Df,g),this.#Ef=this.#If+(this.#Ef-this.#If)*Math.pow(this.#Af,g);let v=(this.#kf-this.#Uf)%360;v>180&&(v-=360),v<-180&&(v+=360),this.#Uf+=v*(1-Math.pow(this.#Gf,g)),this.#Of=this.#Vf+(this.#Of-this.#Vf)*Math.pow(this.#Nf,g);const _=this.#qf(),y=Math.pow(this.#Lf,g);this.#Kf[0]=_[0]+(this.#Kf[0]-_[0])*y,this.#Kf[1]=_[1]+(this.#Kf[1]-_[1])*y,this.#Kf[2]=_[2]+(this.#Kf[2]-_[2])*y,this.camera.setPosition(this.#Kf[0],this.#Kf[1],this.#Kf[2]);const b=this.#Yf();this.camera.lookAt(b[0],b[1],b[2])})}#qf(){const i=this.#Uf*ba,g=this.#Of*ba,x=Math.cos(g),v=Math.sin(g),_=Math.cos(i),y=Math.sin(i),b=this.#jf.modelMatrix,S=b[12],w=b[13],L=b[14];return this.#Ff?(set$3(Ta,y*this.#Cf*x,v*this.#Cf+this.#Ef,_*this.#Cf*x),copy$4(Sa,b),Sa[12]=Sa[13]=Sa[14]=0,transformMat4$2(Ta,Ta,Sa),fromValues$3(S+Ta[0],w+Ta[1],L+Ta[2])):fromValues$3(S+this.#Cf*x*y,w+this.#Ef+this.#Cf*v,L+this.#Cf*x*_)}#Yf(){set$3(Ta,this.#Hf,this.#zf,this.#$f);const i=this.#jf.modelMatrix,g=i[12],x=i[13],v=i[14];return!this.#Ff||0===this.#Hf&&0===this.#zf&&0===this.#$f||(copy$4(Sa,i),Sa[12]=Sa[13]=Sa[14]=0,transformMat4$2(Ta,Ta,Sa)),fromValues$3(g+Ta[0],x+Ta[1],v+Ta[2])}#Xf(){updateObject3DMatrix(this.#jf,{pixelRectObject:{height:1}}),this.#Cf=this.#Bf,this.#Ef=this.#If,this.#Uf=this.#kf,this.#Of=this.#Vf;const i=this.#qf();copy$3(this.#Kf,i),this.camera.setPosition(this.#Kf[0],this.#Kf[1],this.#Kf[2]);const g=this.#Yf();this.camera.lookAt(g[0],g[1],g[2])}}Object.freeze(FollowController);const wa=Math.PI/180,Ma=1e-4,Pa=create$4();class OrbitController extends AController{#Wf=0;#Zf=0;#Jf=0;#Qf=15;#ed=1.5;#Df=.02;#td=.1;#rd=1/0;#id=0;#nd=-35;#ad=3;#sd=.02;#od=-90;#ud=90;#Uf=0;#Of=0;#Cf=0;constructor(i){super(i,{HD_Move:(i,g)=>{this.#id-=i*this.#ad*.1,this.#nd-=g*this.#ad*.1},HD_Wheel:i=>{this.#Qf+=i.deltaY/100*this.#ed,this.#Qfthis.#rd&&(this.#Qf=this.#rd)},HD_TouchPinch:i=>{const g=(i-1)*this.#ed;this.#Qf-=g*this.#Qf,this.#Qfthis.#rd&&(this.#Qf=this.#rd)}}),this.#Uf=this.#id,this.#Of=this.#nd,this.#Cf=this.#Qf}get centerX(){return this.#Wf}set centerX(i){this.#Wf=i}get centerY(){return this.#Zf}set centerY(i){this.#Zf=i}get centerZ(){return this.#Jf}set centerZ(i){this.#Jf=i}get distance(){return this.#Qf}set distance(i){validateNumberRange(i,0),this.#Qf=i}get speedDistance(){return this.#ed}set speedDistance(i){validateNumberRange(i,.01),this.#ed=i}get distanceInterpolation(){return this.#Df}set distanceInterpolation(i){validateNumberRange(i,.01,1),this.#Df=i}get minDistance(){return this.#td}set minDistance(i){validateNumberRange(i,.1),this.#td=i}get maxDistance(){return this.#rd}set maxDistance(i){validateNumberRange(i,.1),this.#rd=i}get speedRotation(){return this.#ad}set speedRotation(i){validateNumberRange(i,.01),this.#ad=i}get rotationInterpolation(){return this.#sd}set rotationInterpolation(i){validateNumberRange(i,.01,1),this.#sd=i}get pan(){return this.#id}set pan(i){this.#id=i}get tilt(){return this.#nd}set tilt(i){validateNumberRange(i,-90,90),this.#nd=i}get minTilt(){return this.#od}set minTilt(i){validateNumberRange(i,-90,90),this.#od=i}get maxTilt(){return this.#ud}set maxTilt(i){validateNumberRange(i,-90,90),this.#ud=i}update(i,g){super.update(i,g,i=>{this.#ld(i)})}#ld(i){this.#ndthis.#ud&&(this.#nd=this.#ud);const{camera:g}=this,x=this.#id-this.#Uf;Math.abs(x)>Ma?this.#Uf+=x*(1-Math.pow(this.#sd,i)):this.#Uf=this.#id;const v=this.#nd-this.#Of;Math.abs(v)>Ma?this.#Of+=v*(1-Math.pow(this.#sd,i)):this.#Of=this.#nd,this.#Qfthis.#rd&&(this.#Qf=this.#rd);const _=this.#Qf-this.#Cf;Math.abs(_)>1e-4?this.#Cf+=_*(1-Math.pow(this.#Df,i)):this.#Cf=this.#Qf,this.#Cf{this.#fd-=i.deltaY/100*this.#md,this.#fd=Math.max(this.#Wl,Math.min(this.#Zl,this.#fd))},HD_Move:(g,x)=>{if(!this.#jf)return;const v=this.#cd*Ra,_=Math.cos(v),y=Math.sin(v),b=this.#pd/this.#hd/i.boundingClientRect.height,S=g*b,w=x*b,L=-S*_-w*y,k=-S*-y-w*_;this.#vd+=L,this.#_d+=k},HD_TouchPinch:i=>{this.#fd/=i,this.#fd=Math.max(this.#Wl,Math.min(this.#Zl,this.#fd))},useKeyboard:!0}),this.#jf=new Mesh(i),this.#jf.setIgnoreFrustumCullingRecursively(!0)}get zoom(){return this.#fd}set zoom(i){validateNumberRange(i),this.#fd=Math.max(this.#Wl,Math.min(this.#Zl,i))}get zoomInterpolation(){return this.#dd}set zoomInterpolation(i){validateNumberRange(i,1e-4,1),this.#dd=i}get speedZoom(){return this.#md}set speedZoom(i){validateNumberRange(i,.01),this.#md=i}get minZoom(){return this.#Wl}set minZoom(i){validateNumberRange(i,.01),this.#Wl=i,this.zoom=this.#fd}get maxZoom(){return this.#Zl}set maxZoom(i){validateNumberRange(i,.01),this.#Zl=i,this.zoom=this.#fd}get viewHeight(){return this.#gd}set viewHeight(i){validateNumberRange(i,.1),this.#gd=i}get viewHeightInterpolation(){return this.#xd}set viewHeightInterpolation(i){validateNumberRange(i,1e-4,1),this.#xd=i}get moveSpeed(){return this.#yd}set moveSpeed(i){validateNumberRange(i,.01),this.#yd=i}get moveSpeedInterpolation(){return this.#bd}set moveSpeedInterpolation(i){validateNumberRange(i,1e-4,1),this.#bd=i}get mouseMoveSpeed(){return this.#Td}set mouseMoveSpeed(i){validateNumberRange(i,.01),this.#Td=i}get mouseMoveSpeedInterpolation(){return this.#wd}set mouseMoveSpeedInterpolation(i){validateNumberRange(i,1e-4,1),this.#wd=i}get keyNameMapper(){return{...this.#Sd}}get targetX(){return this.#jf.x}get targetY(){return this.#jf.y}get targetZ(){return this.#jf.z}setMoveUpKey(i){this.#Sd.moveUp=i}setMoveDownKey(i){this.#Sd.moveDown=i}setMoveLeftKey(i){this.#Sd.moveLeft=i}setMoveRightKey(i){this.#Sd.moveRight=i}update(i,g){super.update(i,g,g=>{this.#ld(i,g)})}#ld(i,g){if(this.#Md(i,g),this.#hd=this.#fd+(this.#hd-this.#fd)*Math.pow(this.#dd,g),this.#pd=this.#gd+(this.#pd-this.#gd)*Math.pow(this.#xd,g),!this.#jf)return;const x=Math.pow(this.#bd,g);this.#jf.x=this.#vd+(this.#jf.x-this.#vd)*x,this.#jf.z=this.#_d+(this.#jf.z-this.#_d)*x;const v=this.#jf.position,_=this.#cd*Ra,{width:y,height:b}=i.pixelRectObject,S=y/b,w=this.#pd/this.#hd,L=w*S,k=this.#pd/15,H=15*k/this.#hd,z=12*k/this.#hd,q=v[0]+Math.cos(_)*H,W=v[1]+z,be=v[2]+Math.sin(_)*H;this.camera.setPosition(q,W,be),this.camera.lookAt(v[0],v[1],v[2]);const je=this.camera;je.left=-L/2,je.right=L/2,je.top=w/2,je.bottom=-w/2}#Md(i,g){if(!this.checkKeyboardInput(i,this.#Sd))return!1;if(!this.#jf)return!1;const{keyboardKeyBuffer:x}=i.redGPUContext,v=this.#Sd,_=this.#yd*g;let y=0,b=0,S=0,w=0;x[v.moveUp]&&(y=_),x[v.moveDown]&&(b=_),x[v.moveLeft]&&(S=_),x[v.moveRight]&&(w=_);const L=this.#cd*Ra,k=Math.cos(L),H=Math.sin(L),z=(b-y)*k+(w-S)*k,q=(b-y)*H+(w-S)*-H;return this.#vd+=z,this.#_d+=q,!0}}Object.freeze(IsometricController);var Ca=Object.freeze({__proto__:null,Camera2D:Camera2D,Core:va,FollowController:FollowController,FreeController:class extends AController{#Sd={moveForward:"w",moveBack:"s",moveLeft:"a",moveRight:"d",moveUp:"e",moveDown:"q",turnLeft:"z",turnRight:"c",turnUp:"r",turnDown:"f"};#yd=600;#Pd=.001;#Rd=1;#Cd=0;#Bd=360;#sd=.001;#Dd=.15;#Ed=[0,0,0];#id=0;#nd=0;#jf;#Id=create$4();#Ad=create$4();#Ld=create$3();constructor(i){super(i,{HD_Move:(i,g)=>{this.#id-=i*this.#Dd,this.#nd-=g*this.#Dd},useKeyboard:!0}),this.#dc()}get x(){return this.#jf.x}set x(i){validateNumber(i),this.#jf.x=i,this.#Ed[0]=i}get y(){return this.#jf.y}set y(i){validateNumber(i),this.#jf.y=i,this.#Ed[1]=i}get z(){return this.#jf.z}set z(i){validateNumber(i),this.#jf.z=i,this.#Ed[2]=i}get pan(){return this.#id}set pan(i){validateNumber(i),this.#id=i}get tilt(){return this.#nd}set tilt(i){validateNumber(i),this.#nd=Math.max(-89.9,Math.min(89.9,i))}get mouseSensitivity(){return this.#Dd}set mouseSensitivity(i){validateNumberRange(i,.01),this.#Dd=i}get moveSpeed(){return this.#yd}set moveSpeed(i){validateNumberRange(i,.01),this.#yd=i}get moveSpeedInterpolation(){return this.#Pd}set moveSpeedInterpolation(i){validateNumberRange(i,1e-4,1),this.#Pd=i}get rotationSpeed(){return this.#Bd}set rotationSpeed(i){validateNumberRange(i,.01),this.#Bd=i}get rotationSpeedInterpolation(){return this.#sd}set rotationSpeedInterpolation(i){validateNumberRange(i,1e-4,1),this.#sd=i}get maxAcceleration(){return this.#Rd}set maxAcceleration(i){this.#Rd=i}get keyNameMapper(){return{...this.#Sd}}setMoveForwardKey(i){this.#Sd.moveForward=i}setMoveBackKey(i){this.#Sd.moveBack=i}setMoveLeftKey(i){this.#Sd.moveLeft=i}setMoveRightKey(i){this.#Sd.moveRight=i}setMoveUpKey(i){this.#Sd.moveUp=i}setMoveDownKey(i){this.#Sd.moveDown=i}setTurnLeftKey(i){this.#Sd.turnLeft=i}setTurnRightKey(i){this.#Sd.turnRight=i}setTurnUpKey(i){this.#Sd.turnUp=i}setTurnDownKey(i){this.#Sd.turnDown=i}update(i,g){super.update(i,g,g=>{this.#ld(i,g)})}#dc(){this.#jf=new Mesh(this.redGPUContext)}#ld(i,g){const x=this.#jf,v=Math.pow(this.#Pd,g),_=Math.pow(this.#sd,g);let y=(this.#id-x.rotationY)%360;y>180&&(y-=360),y<-180&&(y+=360),x.rotationY+=y*(1-_);const b=this.#nd-x.rotationX;x.rotationX+=b*(1-_),this.#Ud(i,g)&&(updateObject3DMatrix(x,i),identity$1(this.#Ad),rotateY$2(this.#Ad,this.#Ad,x.rotationY*ya),rotateX$2(this.#Ad,this.#Ad,x.rotationX*ya),translate(this.#Ad,this.#Ad,this.#Ld),identity$1(this.#Id),translate(this.#Id,this.#Id,x.position),multiply$4(this.#Id,this.#Id,this.#Ad),this.#Ed[0]=this.#Id[12],this.#Ed[1]=this.#Id[13],this.#Ed[2]=this.#Id[14]),x.x+=(this.#Ed[0]-x.x)*(1-v),x.y+=(this.#Ed[1]-x.y)*(1-v),x.z+=(this.#Ed[2]-x.z)*(1-v),identity$1(this.#Id),translate(this.#Id,this.#Id,x.position),rotateY$2(this.#Id,this.#Id,x.rotationY*ya),rotateX$2(this.#Id,this.#Id,x.rotationX*ya),this.camera.setPosition(x.x,x.y,x.z);const S=fromValues$3(0,0,-10);transformMat4$2(S,S,this.#Id),this.camera.lookAt(S[0],S[1],S[2])}#Ud(i,g){if(!this.checkKeyboardInput(i,this.#Sd))return!1;const{keyboardKeyBuffer:x}=i.redGPUContext,v=this.#yd*g,_=this.#Bd*g,y=this.#Sd;let b=!1,S=!1,w=0,L=0;this.#Ld[0]=0,this.#Ld[1]=0,this.#Ld[2]=0;const k=this.#Cd*v;x[y.turnLeft]&&(S=!0,w=_),x[y.turnRight]&&(S=!0,w=-_),x[y.turnUp]&&(S=!0,L=_),x[y.turnDown]&&(S=!0,L=-_),x[y.moveForward]&&(b=!0,this.#Ld[2]=-k),x[y.moveBack]&&(b=!0,this.#Ld[2]=k),x[y.moveLeft]&&(b=!0,this.#Ld[0]=-k),x[y.moveRight]&&(b=!0,this.#Ld[0]=k),x[y.moveUp]&&(b=!0,this.#Ld[1]=k),x[y.moveDown]&&(b=!0,this.#Ld[1]=-k);const H=3*g;return this.#Cd=S||b?Math.min(this.#Rd,this.#Cd+H):Math.max(0,this.#Cd-H),S&&(this.#id+=w,this.#nd=Math.max(-89.9,Math.min(89.9,this.#nd+L))),b||S}},IsometricController:IsometricController,OrbitController:OrbitController,OrthographicCamera:OrthographicCamera,PerspectiveCamera:PerspectiveCamera}),Ba=Object.freeze({__proto__:null,RedGPUContextDetector:RedGPUContextDetector,RedGPUContextObserver:RedGPUContextObserver,RedGPUContextSizeManager:RedGPUContextSizeManager,RedGPUContextViewContainer:RedGPUContextViewContainer}),Da=Object.freeze({__proto__:null,Core:Ba,RedGPUContext:RedGPUContext}),Ea=Object.freeze({__proto__:null,ColorRGB:ColorRGB,ColorRGBA:ColorRGBA,convertHexToRgb:convertHexToRgb,convertRgbToHex:convertRgbToHex}),Ia=Object.freeze({__proto__:null,COMMAND_ENCODER_TYPE:k,CommandEncoderManager:CommandEncoderManager});function createSetter(i,g){const x=`use${i.charAt(0).toUpperCase()}${i.substring(1)}`;return function(i){const v=this[g];this[g]=i,this.updateTexture(v,i),x in this&&(this[x]=!!i),updateTargetUniform(this,x,i?1:0)}}function defineCubeTexture_func(i){const{key:g}=i,x=Symbol(g);return{get:function(){return this[x]},set:createSetter(g,x),...vi}}const defineCubeTexture=(i,g)=>applyProperties(i,g,defineCubeTexture_func);Object.freeze(defineCubeTexture);const Aa=parseWGSL("SKYBOX_MATERIAL","#redgpu_include SYSTEM_UNIFORM #redgpu_include systemStruct.OutputFragment #redgpu_include color.getLuminance #redgpu_include math.PI #redgpu_include math.PI2 #redgpu_include math.INV_PI #redgpu_include skyAtmosphere.skyAtmosphereFn struct Uniforms{blur:f32,intensityMultiplier:f32,luminance:f32,averageLuminance:f32,opacity:f32,transitionProgress:f32,};@group(2)@binding(0)varuniforms:Uniforms;@group(2)@binding(1)var sampler0:sampler;@group(2)@binding(2)var texture0:texture_cube;@group(2)@binding(3)var transitionTexture:texture_cube;@group(2)@binding(4)var transitionMask:texture_2d;struct InputData{@location(0)vertexPosition:vec4,};fn sphericalToUV(dir:vec3)->vec2{let normalizedDir=normalize(dir);let phi=atan2(normalizedDir.z,normalizedDir.x);let theta=acos(clamp(normalizedDir.y,-1.0,1.0));return vec2((phi+PI)/PI2,theta*INV_PI);}@fragment fn main(inputData:InputData)->OutputFragment{var cubemapVec=inputData.vertexPosition.xyz;let viewDir=normalize(cubemapVec);let mipmapCount=f32(textureNumLevels(texture0)-1);let blurCurve=uniforms.blur*uniforms.blur;let skyboxColor=textureSampleLevel(texture0,sampler0,cubemapVec,mipmapCount*blurCurve);var sampleColor=skyboxColor;let u_transitionProgress=uniforms.transitionProgress;if(u_transitionProgress>.0){let transitionSample=textureSampleLevel(transitionTexture,sampler0,cubemapVec,mipmapCount*blurCurve);#redgpu_if transitionMask let uv=sphericalToUV(viewDir);let maskSample=textureSampleLevel(transitionMask,sampler0,uv,.0);let maskValue=getLuminance(maskSample.rgb);let threshold=u_transitionProgress;let mask=smoothstep(threshold-0.1,threshold+0.1,maskValue+(u_transitionProgress-0.5)*0.3);sampleColor=mix(transitionSample,skyboxColor,mask*(1.0-u_transitionProgress));#redgpu_else sampleColor=mix(skyboxColor,transitionSample,u_transitionProgress);#redgpu_endIf}let finalIntensity=systemUniforms.preExposure*(uniforms.intensityMultiplier*uniforms.luminance);var finalAlpha=sampleColor.a*uniforms.opacity;if(systemUniforms.useSkyAtmosphere==1u){let u_atmo=systemUniforms.skyAtmosphere;let transmittance=getTransmittance(transmittanceTexture,atmosphereSampler,u_atmo.cameraHeight,viewDir.y,u_atmo.atmosphereHeight);finalAlpha*=(transmittance.r+transmittance.g+transmittance.b)/3.0;}var outColor=vec4(sampleColor.rgb*finalIntensity,finalAlpha);if(outColor.a==.0){discard;}var output:OutputFragment;output.color=outColor;output.gBufferNormal=vec4(.0);output.gBufferMotionVector=vec4(.0);return output;}");class SkyBoxMaterial extends ABitmapBaseMaterial{constructor(i,g){super(i,"SKYBOX_MATERIAL",Aa,2),this.texture0=g,this.sampler0=new Sampler(this.redGPUContext,{addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge",addressModeW:"clamp-to-edge"}),this.initGPURenderInfos()}}definePositiveNumber(SkyBoxMaterial,[{key:"blur",value:0},{key:"intensityMultiplier",value:1},{key:"luminance",value:1e4},{key:"transitionProgress",value:0}]),defineCubeTexture(SkyBoxMaterial,[{key:"texture0"},{key:"transitionTexture"}]),defineTexture(SkyBoxMaterial,[{key:"transitionMask"}]),defineSampler(SkyBoxMaterial,[{key:"sampler0"}]),Object.freeze(SkyBoxMaterial);var La="#redgpu_include SYSTEM_UNIFORM;struct InputData{@location(0)position:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,};struct VertexOutput{@builtin(position)position:vec4,@location(0)vertexPosition:vec4,};struct VertexUniforms{modelMatrix:mat4x4,};@group(1)@binding(0)varvertexUniforms:VertexUniforms;@vertex fn main(inputData:InputData)->VertexOutput{var output:VertexOutput;let u_camera=systemUniforms.camera;let u_viewMatrix=u_camera.viewMatrix;let u_projectionMatrix=systemUniforms.projection.projectionMatrix;var viewRotation=u_viewMatrix;viewRotation[3]=vec4(.0,.0,.0,1.0);let clipPos=u_projectionMatrix*viewRotation*vertexUniforms.modelMatrix*vec4(inputData.position,1.0);output.position=clipPos.xyww;output.vertexPosition=vec4(inputData.position,1.0);return output;}";const Ua=parseWGSL("SKYBOX_VERTEX",La),ka=Ua.uniforms.vertexUniforms;class SkyBox extends RedGPUObject{modelMatrix=create$4();gpuRenderInfo;#kd=!0;#Ls;#Gd;#xa;#ss;#os;#Od;#Vd;#Nd=0;#Fd=0;#Hd=0;#tl;#zd=25e3;#ls;constructor(i,g,x=25e3){super(i),this.#Gd=new Box(i),this.#Od=g,this.#xa=new SkyBoxMaterial(i,this.#Od),this.luminance=this.#zd=x,this.#ss=new PrimitiveState(this),this.#ss.cullMode=Ji.NONE,this.#os=new DepthStencilState(this)}get texture(){return this.#Od}set texture(i){i||consoleAndThrowError("SkyBox requires a valid CubeTexture | DirectCubeTexture"),this.#Od=i,this.#xa.texture0=i}get luminance(){return this.#zd}set luminance(i){this.#zd=i,this.#xa.luminance=i}get intensityMultiplier(){return this.#xa.intensityMultiplier}set intensityMultiplier(i){this.#xa.intensityMultiplier=i}get blur(){return this.#xa.blur}set blur(i){validatePositiveNumberRange(i,0,1),this.#xa.blur=i}get opacity(){return this.#xa.opacity}set opacity(i){validatePositiveNumberRange(i,0,1),this.#xa.opacity=i}get transitionTexture(){return this.#Vd}transition(i,g=300,x){this.#Vd=i,this.#xa.transitionTexture=i,this.#Fd=g,this.#Nd=performance.now(),this.#xa.transitionMask=x}render(i){const{currentRenderPassEncoder:g,viewRenderStartTime:x,view:v}=i,{indexBuffer:_}=this.#Gd,{triangleCount:y,indexCount:b,format:S}=_,{gpuDevice:w,redGPUContext:L}=this;if(this.#$d(),this.gpuRenderInfo||this.#jd(),this.#Nd)if(this.#Hd=Math.max(x-this.#Nd,0),this.#Hd>this.#Fd)this.#Nd=0,this.#xa.transitionProgress=0,this.texture=this.#Vd,this.#xa.transitionTexture=null,this.#kd=!0;else{const i=this.#Hd/this.#Fd;this.#xa.transitionProgress=i<0?0:i>1?1:i}if(this.#kd||this.#xa.dirtyPipeline||this.#tl!==v.systemUniform_Vertex_UniformBindGroup){this.gpuRenderInfo.pipeline=this.#Kd(),this.#kd=!1,i.renderResults.numDirtyPipelines++,this.#tl=v.systemUniform_Vertex_UniformBindGroup;{this.#xa.dirtyPipeline=!1;const i=w.createRenderBundleEncoder({...v.basicRenderBundleEncoderDescriptor,label:"skybox"}),{gpuRenderInfo:g}=this,{vertexUniformBindGroup:x,pipeline:y}=g;i.setPipeline(y),i.setBindGroup(0,v.systemUniform_Vertex_UniformBindGroup),i.setVertexBuffer(0,this.#Gd.vertexBuffer.gpuBuffer),i.setBindGroup(1,x),i.setBindGroup(2,this.#xa.gpuRenderInfo.fragmentUniformBindGroup),i.setIndexBuffer(_.gpuBuffer,S),i.drawIndexed(_.indexCount,1,0,0,0),this.#Ls=i.finish({label:"renderBundle skybox"})}}g.executeBundles([this.#Ls]);const{renderResults:k}=i;k.num3DObjects++,k.numDrawCalls++,k.numTriangles+=y,k.numPoints+=b}#$d(){const{msaaID:i}=this.antialiasingManager;this.#ls!==i&&(this.#kd=!0,this.#ls=i)}#jd(){const{resourceManager:i,redGPUContext:g}=this,x=i.getGPUBindGroupLayout("SKYBOX_VERTEX_BIND_GROUP_LAYOUT")||i.createBindGroupLayout("SKYBOX_VERTEX_BIND_GROUP_LAYOUT",getVertexBindGroupLayoutDescriptorFromShaderInfo(Ua,1)),v=new ArrayBuffer(ka.arrayBufferByteLength),_=new UniformBuffer(g,v,"SKYBOX_VERTEX_UNIFORM_BUFFER","SKYBOX_VERTEX_UNIFORM_BUFFER");identity$1(this.modelMatrix),_.writeOnlyBuffer(ka.members.modelMatrix,this.modelMatrix);const y={layout:x,label:"VERTEX_BIND_GROUP_DESCRIPTOR_SKYBOX",entries:[{binding:0,resource:{buffer:_.gpuBuffer,offset:0,size:_.size}}]},b=g.gpuDevice.createBindGroup(y);this.gpuRenderInfo=new VertexGPURenderInfo(null,Ua.shaderSourceVariant,Ua.conditionalBlocks,ka,x,_,b,this.#Kd())}#Kd(){const{resourceManager:i,gpuDevice:g,antialiasingManager:x}=this,v={module:i.createGPUShaderModule("VERTEX_MODULE_SKYBOX",{code:La}),entryPoint:"main",buffers:this.#Gd.gpuRenderInfo.buffers},_=i.getGPUBindGroupLayout("SKYBOX_VERTEX_BIND_GROUP_LAYOUT")||i.createBindGroupLayout("SKYBOX_VERTEX_BIND_GROUP_LAYOUT",getVertexBindGroupLayoutDescriptorFromShaderInfo(Ua,1)),y=[i.getGPUBindGroupLayout(ResourceManager.PRESET_GPUBindGroupLayout_System),_,this.#xa.gpuRenderInfo.fragmentBindGroupLayout],b={label:"PIPELINE_DESCRIPTOR_SKYBOX",layout:i.createGPUPipelineLayout("SKYBOX_PIPELINE_LAYOUT",{bindGroupLayouts:y}),vertex:v,fragment:this.#xa.gpuRenderInfo.fragmentState,primitive:this.#ss.state,depthStencil:this.#os.state,multisample:{count:x.useMSAA?4:1}};return g.createRenderPipeline(b)}}Object.freeze(SkyBox);var Ga=Object.freeze({__proto__:null,SkyBoxMaterial:SkyBoxMaterial});class DirectTexture extends ADirectTexture{constructor(i,g,x){super(i,"managedBitmapTextureState",g);const{table:v}=this.targetResourceManagedState;if(g){const i=v.get(g);if(i)return i.texture}x&&this.setGpuTexture(x),this.registerResource()}get viewDescriptor(){return{dimension:"2d",format:this.format,mipLevelCount:this.mipLevelCount,baseMipLevel:0,arrayLayerCount:1,baseArrayLayer:0,aspect:"all"}}registerResource(){this.redGPUContext.resourceManager.registerManagementResource(this,new ResourceStateBitmapTexture(this))}unregisterResource(){this.redGPUContext.resourceManager.unregisterManagementResource(this)}}Object.freeze(DirectTexture);class ASkyAtmosphereLUTGenerator extends RedGPUObject{#Xd;#ne;#iu;#Gt;#Ot;#qd;constructor(i,g,x,v,_,y,b=1){super(i),this.#Xd=g,this.#ne=x,this.#iu=v,this.#Gt=_,this.#Ot=y,this.#qd=b}get sharedUniformBuffer(){return this.#Xd}get sampler(){return this.#ne}get label(){return this.#iu}get width(){return this.#Gt}get height(){return this.#Ot}get depth(){return this.#qd}executeComputePass(i,g,x=[16,16,1]){const{commandEncoderManager:v}=this;v.addResourceComputePass(`SkyAtmosphere_${this.#iu}_ComputePass`,v=>{v.setPipeline(i),v.setBindGroup(0,g),v.dispatchWorkgroups(Math.ceil(this.#Gt/x[0]),Math.ceil(this.#Ot/x[1]),Math.ceil(this.#qd/x[2]))}),this.lutTexture.notifyUpdate()}createLUTTexture(i=!1,g="rgba16float"){const{resourceManager:x}=this;return x.createManagedTexture({label:`SkyAtmosphere_${this.#iu}_Texture`,size:[this.#Gt,this.#Ot,this.#qd],dimension:i?"3d":"2d",format:g,usage:GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC})}createComputePipeline(i,g){const{gpuDevice:x}=this;return x.createComputePipeline({label:i,layout:"auto",compute:{module:x.createShaderModule({code:g}),entryPoint:"main"}})}createBindGroup(i,g,x){return this.gpuDevice.createBindGroup({label:i,layout:g.getBindGroupLayout(0),entries:x})}}Object.freeze(ASkyAtmosphereLUTGenerator);const Oa=parseWGSL("SkyAtmosphere_Transmittance_Generator",it);class TransmittanceGenerator extends ASkyAtmosphereLUTGenerator{#Yd;#er;#U;constructor(i,g,x){super(i,g,x,"Transmittance_Gen",256,64),this.#N()}get lutTexture(){return this.#Yd}render(){this.#er||(this.#er=this.createBindGroup("SkyAtmosphere_Transmittance_BindGroup",this.#U,[{binding:0,resource:this.#Yd.gpuTextureView},{binding:1,resource:{buffer:this.sharedUniformBuffer.gpuBuffer}}])),this.executeComputePass(this.#U,this.#er,[16,16,1])}#N(){this.#Yd=new DirectTexture(this.redGPUContext,`SkyAtmosphere_Transmittance_LUTTexture_${createUUID()}`,this.createLUTTexture()),this.#U=this.createComputePipeline("SkyAtmosphere_Transmittance_Pipeline",Oa.defaultSource)}}Object.freeze(TransmittanceGenerator);const Va=parseWGSL("SkyAtmosphere_MultiScattering_Generator","#redgpu_include skyAtmosphere.skyAtmosphereFn #redgpu_include math.INV_PI @group(0)@binding(0)var multiScatLUT:texture_storage_2d;@group(0)@binding(1)var transmittanceLUT:texture_2d;@group(0)@binding(2)var skyAtmosphereSampler:sampler;@group(0)@binding(3)varparams:SkyAtmosphere;@compute @workgroup_size(8,8)fn main(@builtin(global_invocation_id)global_id:vec3){let size=textureDimensions(multiScatLUT);if(global_id.x>=size.x||global_id.y>=size.y){return;}let uv=(vec2(global_id.xy)+0.5)/vec2(size);let cosSunTheta=uv.x*2.0-1.0;let viewHeight=clamp((1.0-uv.y)*params.atmosphereHeight,.0,params.atmosphereHeight);let groundRadius=params.groundRadius;let rayOrigin=vec3(.0,viewHeight+groundRadius,.0);let sunDir=vec3(sqrt(max(.0,1.0-cosSunTheta*cosSunTheta)),cosSunTheta,.0);var lumTotal=vec3(.0);var fmsTotal=vec3(.0);for(var i=0u;i(sin(theta)*cos(phi),cos(theta),sin(theta)*sin(phi));let tMax=getRaySphereIntersection(rayOrigin,rayDir,groundRadius+params.atmosphereHeight);let tEarth=getRaySphereIntersection(rayOrigin,rayDir,groundRadius);var L1=vec3(.0);var f1=vec3(.0);var TPath=vec3(1.0);if(groundRadius>.0&&tEarth>.0){integrateMultiScatSegment(rayOrigin,rayDir,.0,tEarth,MULTI_SCAT_STEPS,sunDir,&L1,&f1,&TPath);let hitP=rayOrigin+rayDir*tEarth;let up=normalize(hitP);let localCosSun=dot(up,sunDir);let sunT=getTransmittance(transmittanceLUT,skyAtmosphereSampler,.0,localCosSun,params.atmosphereHeight);L1+=TPath*sunT*max(.0,localCosSun)*params.groundAlbedo*INV_PI;f1+=TPath*params.groundAlbedo;}else if(tMax>.0){integrateMultiScatSegment(rayOrigin,rayDir,.0,tMax,MULTI_SCAT_STEPS,sunDir,&L1,&f1,&TPath);}lumTotal+=L1;fmsTotal+=f1/f32(MULTI_SCAT_SAMPLES);}let output=(lumTotal/f32(MULTI_SCAT_SAMPLES))/(1.0-min(fmsTotal,vec3(0.999)));textureStore(multiScatLUT,global_id.xy,vec4(output,1.0));}fn integrateMultiScatSegment(origin:vec3,dir:vec3,tMin:f32,tMax:f32,steps:u32,sunDir:vec3,L1:ptr>,f1:ptr>,TPath:ptr>){if(tMax<=tMin){return;}let groundRadius=params.groundRadius;let stepSize=(tMax-tMin)/f32(steps);let phaseIsotropic=1.0/(4.0*PI);for(var j=0u;j;@group(0)@binding(1)var transmittanceLUT:texture_2d;@group(0)@binding(2)var multiScatLUT:texture_2d;@group(0)@binding(3)var skyAtmosphereSampler:sampler;@group(0)@binding(4)varparams:SkyAtmosphere;@compute @workgroup_size(16,16)fn main(@builtin(global_invocation_id)global_id:vec3){let size=textureDimensions(skyViewLUT);if(global_id.x>=size.x||global_id.y>=size.y){return;}let uv=(vec2(global_id.xy)+0.5)/vec2(size);let azimuth=(uv.x-0.5)*PI2;let groundRadius=params.groundRadius;let viewHeight=max(.0001,params.cameraHeight);let horizonCos=-sqrt(max(.0,viewHeight*(2.0*groundRadius+viewHeight)))/(groundRadius+viewHeight);let horizonElevation=asin(clamp(horizonCos,-1.0,1.0));var viewElevation:f32;if(uv.y<0.5){let ratio=1.0-(uv.y*2.0);viewElevation=horizonElevation+ratio*ratio*(HPI-horizonElevation);}else{let ratio=(uv.y-0.5)*2.0;viewElevation=horizonElevation-ratio*ratio*(horizonElevation+HPI);}let viewDir=vec3(cos(viewElevation)*cos(azimuth),sin(viewElevation),cos(viewElevation)*sin(azimuth));let rayOrigin=vec3(.0,viewHeight+groundRadius,.0);var radiance=vec3(.0);var transmittance=vec3(1.0);let tEarth=getRaySphereIntersection(rayOrigin,viewDir,groundRadius);let atmosphereHeight=params.atmosphereHeight;let tMax=getRaySphereIntersection(rayOrigin,viewDir,groundRadius+atmosphereHeight);if(groundRadius>.0&&tEarth>.0){integrateScatSegment(rayOrigin,viewDir,.0,tEarth,SKY_VIEW_STEPS/2u,params,transmittanceLUT,skyAtmosphereSampler,multiScatLUT,true,&radiance,&transmittance);let hitPoint=rayOrigin+viewDir*tEarth;let up=normalize(hitPoint);let localCosSun=dot(up,normalize(params.sunDirection));let sunT=getTransmittance(transmittanceLUT,skyAtmosphereSampler,.0,localCosSun,atmosphereHeight);let msUV=vec2(clamp(localCosSun*0.5+0.5,.001,0.999),1.0);let msEnergy=textureSampleLevel(multiScatLUT,skyAtmosphereSampler,msUV,.0).rgb;let groundRadiance=evaluateGroundRadiance(localCosSun,sunT,msEnergy,params.groundAlbedo);radiance+=transmittance*groundRadiance;}else if(tMax>.0){integrateScatSegment(rayOrigin,viewDir,.0,tMax,SKY_VIEW_STEPS,params,transmittanceLUT,skyAtmosphereSampler,multiScatLUT,true,&radiance,&transmittance);}textureStore(skyViewLUT,global_id.xy,vec4(radiance,(transmittance.r+transmittance.g+transmittance.b)/3.0));}");class SkyViewGenerator extends ASkyAtmosphereLUTGenerator{#Yd;#er;#U;constructor(i,g,x){super(i,g,x,"SkyView_Gen",512,256),this.#N()}get lutTexture(){return this.#Yd}render(i,g){this.#er||(this.#er=this.createBindGroup("SkyAtmosphere_SkyView_BindGroup",this.#U,[{binding:0,resource:this.#Yd.gpuTextureView},{binding:1,resource:i.gpuTextureView},{binding:2,resource:g.gpuTextureView},{binding:3,resource:this.sampler.gpuSampler},{binding:4,resource:{buffer:this.sharedUniformBuffer.gpuBuffer}}])),this.executeComputePass(this.#U,this.#er,[16,16,1])}#N(){this.#Yd=new DirectTexture(this.redGPUContext,`SkyAtmosphere_SkyView_LUTTexture_${createUUID()}`,this.createLUTTexture(!1)),this.#U=this.createComputePipeline("SkyAtmosphere_SkyView_Pipeline",Na.defaultSource)}}Object.freeze(SkyViewGenerator);const Fa=parseWGSL("SkyAtmosphere_AerialPerspective_Generator","#redgpu_include SYSTEM_UNIFORM;#redgpu_include skyAtmosphere.skyAtmosphereFn @group(0)@binding(1)var aerialPerspectiveLUT:texture_storage_3d;@group(0)@binding(2)var multiScatLUT:texture_2d;@group(0)@binding(3)varparams:SkyAtmosphere;@group(0)@binding(4)var transmittanceLUT:texture_2d;@group(0)@binding(13)var skyAtmosphereSampler:sampler;@compute @workgroup_size(8,8,4)fn main(@builtin(global_invocation_id)global_id:vec3){let size=textureDimensions(aerialPerspectiveLUT);if(global_id.x>=size.x||global_id.y>=size.y||global_id.z>=size.z){return;}let uvw=(vec3(global_id)+0.5)/vec3(size);let invP=systemUniforms.projection.inverseProjectionMatrix;let invV=systemUniforms.camera.inverseViewMatrix;let ndc=vec2(uvw.x*2.0-1.0,(1.0-uvw.y)*2.0-1.0);let viewSpaceDir=normalize(vec3(ndc.x*invP[0][0],ndc.y*invP[1][1],-1.0));let worldRotation=mat3x3(invV[0].xyz,invV[1].xyz,invV[2].xyz);let viewDir=normalize(worldRotation*viewSpaceDir);let sliceDist=uvw.z*uvw.z*params.aerialPerspectiveDistanceScale;let groundRadius=params.groundRadius;let viewHeight=max(.0,params.cameraHeight);let rayOrigin=vec3(.0,viewHeight+groundRadius,.0);var radiance=vec3(.0);var transmittance=vec3(1.0);let tEarth=getRaySphereIntersection(rayOrigin,viewDir,groundRadius);let tMax=select(sliceDist,min(sliceDist,tEarth),groundRadius>.0&&tEarth>.0);if(tMax>.0){integrateScatSegment(rayOrigin,viewDir,.0,tMax,AP_STEPS,params,transmittanceLUT,skyAtmosphereSampler,multiScatLUT,true,&radiance,&transmittance);let sunDir=normalize(params.sunDirection);let viewSunCos=dot(viewDir,sunDir);let mieGlow=getMieGlowAmountUnit(viewSunCos,viewHeight,params,transmittanceLUT,skyAtmosphereSampler,transmittance,.0);radiance+=mieGlow;}let avgTrans=(transmittance.r+transmittance.g+transmittance.b)/3.0;textureStore(aerialPerspectiveLUT,global_id,vec4(radiance,avgTrans));}");class AerialPerspectiveGenerator extends ASkyAtmosphereLUTGenerator{#Yd;#er;#U;#Wd;constructor(i,g,x){super(i,g,x,"AerialPerspective_Gen",32,32,32),this.#N()}get lutTexture(){return this.#Yd}render(i,g,x){const v=i.systemUniform_Vertex_UniformBuffer?.gpuBuffer;v?(this.#er&&this.#Wd===v||(this.#Wd=v,this.#er=this.createBindGroup("SkyAtmosphere_AerialPerspective_BindGroup",this.#U,[{binding:0,resource:{buffer:v}},{binding:1,resource:this.#Yd.gpuTextureView},{binding:2,resource:x.gpuTextureView},{binding:3,resource:{buffer:this.sharedUniformBuffer.gpuBuffer}},{binding:4,resource:g.gpuTextureView},{binding:13,resource:this.sampler.gpuSampler}])),this.executeComputePass(this.#U,this.#er,[8,8,4])):console.warn("AerialPerspectiveGenerator: systemUniform_Vertex_UniformBuffer is not ready yet.")}#N(){const i=this.createLUTTexture(!0);this.#Yd=new DirectCubeTexture(this.redGPUContext,`SkyAtmosphere_AerialPerspective_LUTTexture_${createUUID()}`,i),this.#U=this.createComputePipeline("SkyAtmosphere_AerialPerspective_Pipeline",Fa.defaultSource)}}Object.freeze(AerialPerspectiveGenerator);const Ha=parseWGSL("SkyLight_Reflection_Generator","#redgpu_include skyAtmosphere.skyAtmosphereFn @group(0)@binding(0)var outputTexture:texture_storage_2d_array;@group(0)@binding(1)var multiScatTexture:texture_2d;@group(0)@binding(2)var atmosphereSampler:sampler;@group(0)@binding(3)varparams:SkyAtmosphere;@group(0)@binding(4)var transmittanceTexture:texture_2d;@group(0)@binding(5)var skyViewTexture:texture_2d;#redgpu_include math.PI #redgpu_include math.PI2 #redgpu_include math.DEG_TO_RAD #redgpu_include math.INV_PI #redgpu_include math.hash.getHammersley #redgpu_include color.getLuminance fn getIBLAtmosphereRadiance(viewDir:vec3)->vec3{var radiance=evaluateIBLRadiance(viewDir,params,transmittanceTexture,multiScatTexture,skyViewTexture,atmosphereSampler);let maxIBLLuminance:f32=10000.0;let lum=getLuminance(radiance);if(lum>maxIBLLuminance){radiance*=(maxIBLLuminance/lum);}return radiance;}@compute @workgroup_size(8,8,1)fn main(@builtin(global_invocation_id)global_id:vec3){let size_u=textureDimensions(outputTexture).xy;if(global_id.x>=size_u.x||global_id.y>=size_u.y||global_id.z>=6u){return;}let size=vec2(size_u);let face=global_id.z;var totalRadiance=vec3(.0);const SAMPLE_COUNT:u32=8u;for(var i=0u;i(global_id.xy)+0.5+offset)/size;var viewDir=getCubeMapDirection(uv,face);viewDir=normalize(viewDir);if(abs(viewDir.y)>0.9999){viewDir=vec3(.0,sign(viewDir.y),.0);}totalRadiance+=getIBLAtmosphereRadiance(viewDir);}let radiance=totalRadiance/f32(SAMPLE_COUNT);textureStore(outputTexture,global_id.xy,global_id.z,vec4(radiance,1.0));}");class SkyLightReflectionGenerator extends ASkyAtmosphereLUTGenerator{#Zd;#Jd;#Qd;#U;#er;constructor(i,g,x){super(i,g,x,"SkyLight_Reflection_Gen",256,256,6),this.#N()}get sourceCubeTexture(){return this.#Zd}get prefilteredTexture(){return this.#Qd}get lutTexture(){return this.#Qd}async render(i,g,x){this.#er||(this.#er=this.#em(i,g,x)),await this.#tm(this.#U,this.#er,this.#Qd)}#em(i,g,x){return this.createBindGroup(`SkyLight_Reflection_BindGroup_${createUUID()}`,this.#U,[{binding:0,resource:this.#Jd},{binding:1,resource:g.gpuTextureView},{binding:2,resource:this.sampler.gpuSampler},{binding:3,resource:{buffer:this.sharedUniformBuffer.gpuBuffer}},{binding:4,resource:i.gpuTextureView},{binding:5,resource:x.gpuTextureView}])}async#tm(i,g,x){const{resourceManager:v}=this.redGPUContext;this.#rm(i,g,[8,8,1]),v.mipmapGenerator.generateMipmap(this.#Zd,{size:[this.width,this.height,6],format:"rgba16float",usage:this.#Zd.usage,mipLevelCount:getMipLevelCount(this.width,this.height),dimension:"2d"},!0,k.RESOURCE),await v.prefilterGenerator.generate(this.#Zd,this.width,x,k.RESOURCE)}#N(){const{gpuDevice:i}=this.redGPUContext,g=getMipLevelCount(this.width,this.height);this.#Zd=i.createTexture({label:"SkyLight_Reflection_Source_CubeTexture",size:[this.width,this.height,6],format:"rgba16float",usage:GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT,mipLevelCount:g}),this.#Jd=this.#Zd.createView({dimension:"2d-array",baseMipLevel:0,mipLevelCount:1}),this.#Qd=new DirectCubeTexture(this.redGPUContext,`SkyLight_Reflection_LUTTexture_${createUUID()}`),this.#U=this.createComputePipeline("Base",Ha.defaultSource)}#rm(i,g,x=[16,16,1],v=this.width,_=this.height,y=this.depth){const{commandEncoderManager:b}=this.redGPUContext;b.addResourceComputePass(`SkyLight_${this.label}_ComputePass`,b=>{b.setPipeline(i),b.setBindGroup(0,g),b.dispatchWorkgroups(Math.ceil(v/x[0]),Math.ceil(_/x[1]),Math.ceil(y/x[2]))})}}Object.freeze(SkyLightReflectionGenerator);const za=parseWGSL("SkyLight_Irradiance_Generator","#redgpu_include skyAtmosphere.skyAtmosphereFn @group(0)@binding(0)var outputTexture:texture_storage_2d_array;@group(0)@binding(1)var multiScatTexture:texture_2d;@group(0)@binding(2)var atmosphereSampler:sampler;@group(0)@binding(3)varparams:SkyAtmosphere;@group(0)@binding(4)var transmittanceTexture:texture_2d;@group(0)@binding(5)var skyViewTexture:texture_2d;#redgpu_include math.PI #redgpu_include math.PI2 #redgpu_include math.DEG_TO_RAD #redgpu_include math.INV_PI #redgpu_include math.hash.getHammersley @compute @workgroup_size(8,8,1)fn main(@builtin(global_invocation_id)global_id:vec3){let size_u=textureDimensions(outputTexture).xy;if(global_id.x>=size_u.x||global_id.y>=size_u.y||global_id.z>=6u){return;}let size=vec2(size_u);let face=global_id.z;var totalRadiance=vec3(.0);const SAMPLE_COUNT:u32=4u;for(var i=0u;i(global_id.xy)+0.5+offset*0.8)/size;var viewDir=getCubeMapDirection(uv,face);viewDir=normalize(viewDir);if(abs(viewDir.y)>0.9999){viewDir=vec3(.0,sign(viewDir.y),.0);}totalRadiance+=evaluateIBLRadianceCompensated(viewDir,params,transmittanceTexture,multiScatTexture,skyViewTexture,atmosphereSampler);}let radiance=totalRadiance/f32(SAMPLE_COUNT);textureStore(outputTexture,global_id.xy,global_id.z,vec4(radiance,1.0));}");class SkyLightIrradianceGenerator extends ASkyAtmosphereLUTGenerator{#Zd;#Jd;#Qd;#U;#er;constructor(i,g,x){super(i,g,x,"SkyLight_Irradiance_Gen",256,256,6),this.#N()}get sourceCubeTexture(){return this.#Zd}get prefilteredTexture(){return this.#Qd}get lutTexture(){return this.#Qd}async render(i,g,x){this.#er||(this.#er=this.#em(i,g,x)),await this.#tm(this.#U,this.#er,this.#Qd)}#em(i,g,x){return this.createBindGroup(`SkyLight_Irradiance_BindGroup_${createUUID()}`,this.#U,[{binding:0,resource:this.#Jd},{binding:1,resource:g.gpuTextureView},{binding:2,resource:this.sampler.gpuSampler},{binding:3,resource:{buffer:this.sharedUniformBuffer.gpuBuffer}},{binding:4,resource:i.gpuTextureView},{binding:5,resource:x.gpuTextureView}])}async#tm(i,g,x){const{resourceManager:v}=this.redGPUContext;this.#rm(i,g,[8,8,1]),v.mipmapGenerator.generateMipmap(this.#Zd,{size:[this.width,this.height,6],format:"rgba16float",usage:this.#Zd.usage,mipLevelCount:getMipLevelCount(this.width,this.height),dimension:"2d"},!0,k.RESOURCE),await v.prefilterGenerator.generate(this.#Zd,this.width,x,k.RESOURCE)}#N(){const{gpuDevice:i}=this.redGPUContext,g=getMipLevelCount(this.width,this.height);this.#Zd=i.createTexture({label:"SkyLight_Irradiance_Source_CubeTexture",size:[this.width,this.height,6],format:"rgba16float",usage:GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT,mipLevelCount:g}),this.#Jd=this.#Zd.createView({dimension:"2d-array",baseMipLevel:0,mipLevelCount:1}),this.#Qd=new DirectCubeTexture(this.redGPUContext,`SkyLight_Irradiance_LUTTexture_${createUUID()}`),this.#U=this.createComputePipeline("Base",za.defaultSource)}#rm(i,g,x=[16,16,1],v=this.width,_=this.height,y=this.depth){const{commandEncoderManager:b}=this.redGPUContext;b.addResourceComputePass(`SkyLight_${this.label}_ComputePass`,b=>{b.setPipeline(i),b.setBindGroup(0,g),b.dispatchWorkgroups(Math.ceil(v/x[0]),Math.ceil(_/x[1]),Math.ceil(y/x[2]))})}}Object.freeze(SkyLightIrradianceGenerator);class SkyLight extends RedGPUObject{dirty=!0;#im;#Je;#nm;#ne;#Xd;#am=!1;constructor(i,g,x){super(i),this.#Xd=g,this.#ne=x,this.#nm=new DirectCubeTexture(i,`SkyAtmosphere_Irradiance_LUTTexture_${createUUID()}`,this.resourceManager.createManagedTexture({size:[32,32,6],format:"rgba16float",usage:GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT,dimension:"2d",mipLevelCount:1,label:"SkyAtmosphere_Irradiance_LUT"})),this.#im=new SkyLightReflectionGenerator(i,this.#Xd,this.#ne),this.#Je=new SkyLightIrradianceGenerator(i,this.#Xd,this.#ne)}get irradianceLUT(){return this.#nm}get reflectionLUT(){return this.#im.prefilteredTexture}async update(i){this.dirty&&!this.#am&&(this.#am=!0,this.#im.render(i.transmittanceLUT,i.multiScatLUT,i.skyViewLUT),this.#Je.render(i.transmittanceLUT,i.multiScatLUT,i.skyViewLUT),this.resourceManager.irradianceGenerator.render(this.#Je.sourceCubeTexture,this.#nm.gpuTexture),this.#nm.notifyUpdate(),this.#am=!1,this.dirty=!1)}}Object.freeze(SkyLight);class SkyAtmosphereBackground extends RedGPUObject{#sm;#om;#um;#lm;#cm=!0;#hm;#ls;constructor(i){super(i),this.#sm=this.gpuDevice.createBindGroupLayout({label:"SKY_ATMOSPHERE_BACKGROUND_BGL_2",entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:2,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:3,visibility:GPUShaderStage.FRAGMENT,sampler:{}}]})}render(i,g,x,v,_){const{currentRenderPassEncoder:y,view:b}=i,{gpuDevice:S,antialiasingManager:w}=this,{useMSAA:L,msaaID:k}=w,H=this.#ls!==k;if(this.#cm||H||this.#hm!==b.systemUniform_Vertex_UniformBindGroup){this.#ls=k,this.#fm(L),this.#cm=!1,this.#hm=b.systemUniform_Vertex_UniformBindGroup,this.#om=S.createBindGroup({label:"SKY_ATMOSPHERE_BACKGROUND_BG_2",layout:this.#sm,entries:[{binding:0,resource:g.gpuTextureView},{binding:1,resource:x.gpuTextureView},{binding:2,resource:v.gpuTextureView},{binding:3,resource:_.gpuSampler}]});const i=S.createRenderBundleEncoder({...b.basicRenderBundleEncoderDescriptor,label:"SKY_ATMOSPHERE_BACKGROUND_BUNDLE_ENCODER"});i.setPipeline(this.#um),i.setBindGroup(0,b.systemUniform_Vertex_UniformBindGroup),i.setBindGroup(1,this.#om),i.draw(3,1,0,0),this.#lm=i.finish({label:"SKY_ATMOSPHERE_BACKGROUND_BUNDLE"})}y.executeBundles([this.#lm])}#fm(i){const{gpuDevice:g,resourceManager:x}=this,v=x.createGPUShaderModule("SkyAtmosphere_Background_Vertex_ShaderModule",{code:"#redgpu_include SYSTEM_UNIFORM;struct VertexOutput{@builtin(position)position:vec4,@location(0)vertexPosition:vec4,};@vertex fn main(@builtin(vertex_index)vertexIndex:u32)->VertexOutput{var output:VertexOutput;let x=f32((i32(vertexIndex)<<1u)& 2i)*2.0-1.0;let y=f32(i32(vertexIndex)& 2i)*2.0-1.0;let ndcPos=vec4(x,y,1.0,1.0);output.position=ndcPos.xyww;let u_camera=systemUniforms.camera;let invProj=systemUniforms.projection.inverseProjectionMatrix;var viewRotation=u_camera.viewMatrix;viewRotation[3]=vec4(.0,.0,.0,1.0);let invViewRotation=transpose(viewRotation);var viewDir=invProj*ndcPos;viewDir=vec4(viewDir.xyz/viewDir.w,.0);let worldDir=invViewRotation*viewDir;output.vertexPosition=vec4(worldDir.xyz,1.0);return output;}"}),_=x.createGPUShaderModule("SkyAtmosphere_Background_Fragment_ShaderModule",{code:"#redgpu_include math.PI #redgpu_include math.DEG_TO_RAD #redgpu_include SYSTEM_UNIFORM;#redgpu_include skyAtmosphere.skyAtmosphereFn;struct VertexOutput{@builtin(position)position:vec4,@location(0)vertexPosition:vec4,};struct FragmentOutput{@location(0)color:vec4,@location(1)normal:vec4,@location(2)motionVector:vec4,};@group(1)@binding(0)var bg_transmittanceLUT:texture_2d;@group(1)@binding(1)var bg_multiScatLUT:texture_2d;@group(1)@binding(2)var bg_skyViewLUT:texture_2d;@group(1)@binding(3)var bg_skyAtmosphereSampler:sampler;@fragment fn main(input:VertexOutput)->FragmentOutput{let uniforms=systemUniforms.skyAtmosphere;let groundRadius=uniforms.groundRadius;let atmosphereHeight=uniforms.atmosphereHeight;let viewDir=normalize(input.vertexPosition.xyz);let viewHeight=max(.0,uniforms.cameraHeight);let camPos=vec3(.0,groundRadius+viewHeight,.0);let tEarth=getRaySphereIntersection(camPos,viewDir,groundRadius);let isGroundHit=groundRadius>.0&&tEarth>.0;var baseRadiance:vec3;var skyTransmittance:f32=1.0;if(isGroundHit){let hitPoint=camPos+viewDir*tEarth;let up=normalize(hitPoint);let sunDir=normalize(uniforms.sunDirection);let localCosSun=dot(up,sunDir);let sunT=getTransmittance(bg_transmittanceLUT,bg_skyAtmosphereSampler,.0,localCosSun,atmosphereHeight);let msUV=vec2(clamp(localCosSun*0.5+0.5,.001,0.999),1.0);let msEnergy=textureSampleLevel(bg_multiScatLUT,bg_skyAtmosphereSampler,msUV,.0).rgb;baseRadiance=evaluateGroundRadiance(localCosSun,sunT,msEnergy,uniforms.groundAlbedo);skyTransmittance=.0;}else{let skyUV=getSkyViewUV(viewDir,viewHeight,groundRadius,atmosphereHeight);let skySample=textureSampleLevel(bg_skyViewLUT,bg_skyAtmosphereSampler,skyUV,.0);baseRadiance=skySample.rgb;skyTransmittance=skySample.a;}var finalRadiance=baseRadiance*uniforms.sunIntensity*systemUniforms.preExposure;if(!isGroundHit&&viewDir.y>.0){let cloudR=groundRadius+uniforms.cloudHeight;let tCloud=getRaySphereIntersection(camPos,viewDir,cloudR);if(tCloud>.0){let hitP=camPos+viewDir*tCloud;let cloudMask=getCloudDensity(hitP,uniforms);if(cloudMask>.0){let sunDir=normalize(uniforms.sunDirection);let sunT=getTransmittance(bg_transmittanceLUT,bg_skyAtmosphereSampler,uniforms.cloudHeight,sunDir.y,atmosphereHeight);let cloudNormal=getCloudNormal(hitP,uniforms);let cloudShadow=saturate(dot(cloudNormal,sunDir)*0.5+0.5);let cloudColor=(sunT*uniforms.sunIntensity*0.5+baseRadiance*0.5)*cloudShadow*systemUniforms.preExposure;finalRadiance=mix(finalRadiance,cloudColor,cloudMask*skyTransmittance);}}}var output:FragmentOutput;output.color=vec4(finalRadiance,1.0);output.normal=vec4(.0,.0,.0,.0);output.motionVector=vec4(.0,.0,.0,.0);return output;}"});this.#um=g.createRenderPipeline({label:"SkyAtmosphere_Background_Pipeline",layout:g.createPipelineLayout({bindGroupLayouts:[x.getGPUBindGroupLayout(ResourceManager.PRESET_GPUBindGroupLayout_System),this.#sm]}),vertex:{module:v,entryPoint:"main",buffers:[]},fragment:{module:_,entryPoint:"main",targets:[{format:"rgba16float"},{format:navigator.gpu.getPreferredCanvasFormat()},{format:"rgba16float"}]},primitive:{topology:"triangle-list",cullMode:"none"},depthStencil:{format:"depth32float",depthWriteEnabled:!1,depthCompare:"less-equal"},multisample:{count:i?4:1}})}}Object.freeze(SkyAtmosphereBackground);var $a="let id=global_id.xy;let size=textureDimensions(outputTexture);if(id.x>=size.x||id.y>=size.y){return;}let uv=(vec2(id)+0.5)/vec2(size);let sceneSample=textureLoad(sourceTexture,id);var sceneColor=sceneSample.rgb;let rawDepth=fetchDepth(id);let invP=systemUniforms.projection.inverseProjectionMatrix;let viewSpacePos=vec3((uv.x*2.0-1.0)*invP[0][0],((1.0-uv.y)*2.0-1.0)*invP[1][1],-1.0);let rayLengthRatio=length(viewSpacePos);let worldRotation=mat3x3(systemUniforms.camera.inverseViewMatrix[0].xyz,systemUniforms.camera.inverseViewMatrix[1].xyz,systemUniforms.camera.inverseViewMatrix[2].xyz);let viewDir=normalize(worldRotation*viewSpacePos);let sunDir=normalize(uniforms.sunDirection);let viewSunCos=dot(viewDir,sunDir);let mappingH=max(.0,uniforms.cameraHeight);let groundRadius=uniforms.groundRadius;let atmosphereHeight=uniforms.atmosphereHeight;var baseScattering:vec3=vec3(.0);var atmosphereTrans:f32=1.0;var sceneBlendingTrans:f32=1.0;if(rawDepth>=1.0){let skyUV=getSkyViewUV(viewDir,mappingH,groundRadius,atmosphereHeight);atmosphereTrans=textureSampleLevel(skyViewLUT,basicSampler,skyUV,.0).a;sceneBlendingTrans=1.0;}else{let depthKm=getLinearizeDepth(rawDepth,systemUniforms.camera.nearClipping,systemUniforms.camera.farClipping)/1000.0;let actualDist=depthKm*rayLengthRatio;let maxApDist=uniforms.aerialPerspectiveDistanceScale;let apDist=clamp(actualDist-uniforms.aerialPerspectiveStartDepth,.0,maxApDist);let apW=clamp(sqrt(apDist/maxApDist),.0,1.0);var apSample=textureSampleLevel(aerialPerspectiveLUT,basicSampler,vec3(uv.x,uv.y,apW),.0);if(actualDist(scatM*phaseM))*sunT;let localExt=scatR+vec3((uniforms.mieScattering+uniforms.mieAbsorption)*d.rhoM*uniforms.skyLuminanceFactor)+uniforms.absorptionCoefficient*d.rhoO;let analyticalScat=localScat*actualDist;let analyticalTrans=exp(-localExt*actualDist);let analyticalA=(analyticalTrans.r+analyticalTrans.g+analyticalTrans.b)/3.0;apSample=mix(vec4(analyticalScat,analyticalA),apSample,smoothstep(.0,NEAR_FIELD_CORRECTION_DIST,actualDist));}baseScattering=apSample.rgb;atmosphereTrans=apSample.a;sceneBlendingTrans=apSample.a;}let camPos=vec3(.0,mappingH+groundRadius,.0);let sunShadow=getPlanetShadowMask(camPos,sunDir,groundRadius,uniforms);let mieGlow=getMieGlowAmountUnit(viewSunCos,mappingH,uniforms,transmittanceLUT,basicSampler,vec3(atmosphereTrans),.0);let hitsVirtualGround=groundRadius>.0&&getRaySphereIntersection(camPos,viewDir,groundRadius)>.0;let drawSunDisk=(rawDepth>=1.0)&&!hitsVirtualGround;let sunDisk=select(vec3(.0),getSunDiskRadianceUnit(viewSunCos,uniforms.sunSize,uniforms.sunLimbDarkening,vec3(atmosphereTrans),.01,uniforms),drawSunDisk);var finalCloudMask:f32=.0;if(drawSunDisk){let cloudR=groundRadius+uniforms.cloudHeight;let tCloud=getRaySphereIntersection(camPos,viewDir,cloudR);if(tCloud>.0){let hitP=camPos+viewDir*tCloud;finalCloudMask=getCloudDensity(hitP,uniforms);}}let addedRadiance=(mieGlow+sunDisk)*sunShadow*(1.0-finalCloudMask);let totalScattering=(baseScattering*uniforms.sunIntensity+addedRadiance*uniforms.sunIntensity)*systemUniforms.preExposure;let finalColor=sceneColor*saturate(sceneBlendingTrans)+totalScattering;textureStore(outputTexture,id,vec4(finalColor,1.0));";class SkyAtmospherePostEffect extends ASinglePassPostEffect{#uh;constructor(i,g){super(i),this.#uh=g;const createCode=i=>["#redgpu_include depth.getLinearizeDepth","#redgpu_include skyAtmosphere.skyAtmosphereFn","@group(0) @binding(0) var sourceTexture : texture_storage_2d;","@group(0) @binding(1) var transmittanceLUT : texture_2d;","@group(0) @binding(2) var multiScatLUT : texture_2d;","@group(0) @binding(3) var skyViewLUT : texture_2d;","@group(0) @binding(4) var aerialPerspectiveLUT : texture_3d;","@group(0) @binding(5) var skyAtmosphereIrradianceLUT : texture_cube;","",ft.POST_EFFECT_SYSTEM_UNIFORM,"@group(2) @binding(5) var basicSampler : sampler;","",`@group(2) @binding(0) var depthTexture : ${i?"texture_depth_multisampled_2d":"texture_depth_2d"};`,"@group(2) @binding(1) var gBufferNormalTexture : texture_2d;","@group(2) @binding(2) var gBufferMotionVector : texture_2d;",`@group(2) @binding(3) var prevDepthTexture : ${i?"texture_depth_multisampled_2d":"texture_depth_2d"};`,"","@group(3) @binding(0) var outputTexture : texture_storage_2d;","","fn fetchDepth(pos: vec2) -> f32 {"," let dSize = textureDimensions(depthTexture);"," let clampedPos = min(pos, dSize - 1u);"," return textureLoad(depthTexture, clampedPos, 0);","}","","@compute @workgroup_size(16, 16)","fn main(@builtin(global_invocation_id) global_id : vec3) {"," let uniforms = systemUniforms.skyAtmosphere;"," let viewHeight = uniforms.cameraHeight;",$a,"}"].join("\n");this.init(i,"POST_EFFECT_SKY_ATMOSPHERE",{msaa:createCode(!0),nonMsaa:createCode(!1)})}render(i,g,x,v){const _=this.#uh;return super.render(i,g,x,v,{texture:_.transmittanceLUT.gpuTexture,textureView:_.transmittanceLUT.gpuTextureView},{texture:_.multiScatLUT.gpuTexture,textureView:_.multiScatLUT.gpuTextureView},{texture:_.skyViewLUT.gpuTexture,textureView:_.skyViewLUT.gpuTextureView},{texture:_.aerialPerspectiveLUT.gpuTexture,textureView:_.aerialPerspectiveLUT.gpuTextureView},{texture:_.skyAtmosphereIrradianceLUT.gpuTexture,textureView:_.skyAtmosphereIrradianceLUT.gpuTextureView})}}Object.freeze(SkyAtmospherePostEffect);const ja=parseWGSL("SkyAtmosphere_Core",it).uniforms.params;class SkyAtmosphere extends RedGPUObject{#dm;#mm;#pm;#gm;#ne;#Xd;#xm;#vm;#_m;#ym={rayleighScattering:[.005802,.013558,.0331],rayleighExponentialDistribution:8,mieScattering:[.003996,.003996,.003996],mieAnisotropy:.8,mieAbsorption:[444e-6,444e-6,444e-6],mieExponentialDistribution:1.2,absorptionCoefficient:[65e-5,.001881,85e-6],absorptionTipAltitude:25,groundAlbedo:[.4,.4,.4],absorptionTentWidth:15,skyLuminanceFactor:[1,1,1],multiScatteringFactor:1,sunDirection:new Float32Array([0,1,0]),transmittanceMinLightElevationAngle:-90,groundRadius:6360,atmosphereHeight:60,aerialPerspectiveDistanceScale:100,aerialPerspectiveStartDepth:0,sunIntensity:1e5,sunSize:.533,sunLimbDarkening:.5,cameraHeight:.001,cloudTime:0,cloudTimeMultiplier:0,cloudCoverage:.4,cloudDensity:.7,cloudHeight:5};#bm=null;#Sm=null;#Tm=!0;#wm=!0;#Mm=!0;#Pm=-1;#Rm=create$4();constructor(i){super(i),this.#Xd=new UniformBuffer(this.redGPUContext,new ArrayBuffer(ja.arrayBufferByteLength),"SkyAtmosphere_Shared_UniformBuffer"),this.#ne=new Sampler(i,{magFilter:"linear",minFilter:"linear",mipmapFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"}),this.#dm=new TransmittanceGenerator(i,this.#Xd,this.#ne),this.#mm=new MultiScatteringGenerator(i,this.#Xd,this.#ne),this.#pm=new SkyViewGenerator(i,this.#Xd,this.#ne),this.#gm=new AerialPerspectiveGenerator(i,this.#Xd,this.#ne),this.#xm=new SkyLight(i,this.#Xd,this.#ne),this.#vm=new SkyAtmosphereBackground(i),this.#_m=new SkyAtmospherePostEffect(i,this)}get postEffect(){return this.#_m}get params(){return this.#ym}get cloudTimeMultiplier(){return this.#ym.cloudTimeMultiplier}set cloudTimeMultiplier(i){this.#Cm("cloudTimeMultiplier",i,!1,!1,!1,i=>validateNumberRange(i))}get cloudCoverage(){return this.#ym.cloudCoverage}set cloudCoverage(i){this.#Cm("cloudCoverage",i,!1,!1,!1,i=>validateNumberRange(i,0,1))}get cloudDensity(){return this.#ym.cloudDensity}set cloudDensity(i){this.#Cm("cloudDensity",i,!1,!1,!1,i=>validateNumberRange(i,0,1))}get cloudHeight(){return this.#ym.cloudHeight}set cloudHeight(i){this.#Cm("cloudHeight",i,!1,!1,!1,i=>validatePositiveNumberRange(i,.1,20))}get aerialPerspectiveDistanceScale(){return this.#ym.aerialPerspectiveDistanceScale}set aerialPerspectiveDistanceScale(i){this.#Cm("aerialPerspectiveDistanceScale",i,!1,!0,!0,i=>validatePositiveNumberRange(i,1,1e3))}get aerialPerspectiveStartDepth(){return this.#ym.aerialPerspectiveStartDepth}set aerialPerspectiveStartDepth(i){this.#Cm("aerialPerspectiveStartDepth",i,!1,!0,!0,i=>validatePositiveNumberRange(i,0,100))}get transmittanceMinLightElevationAngle(){return this.#ym.transmittanceMinLightElevationAngle}set transmittanceMinLightElevationAngle(i){this.#Cm("transmittanceMinLightElevationAngle",i,!0,!0,!0,i=>validateNumberRange(i,-90,90))}get groundRadius(){return this.#ym.groundRadius}set groundRadius(i){this.#Cm("groundRadius",i,!0,!1,!0,i=>validatePositiveNumberRange(i,1))}get atmosphereHeight(){return this.#ym.atmosphereHeight}set atmosphereHeight(i){this.#Cm("atmosphereHeight",i,!0,!1,!0,i=>validatePositiveNumberRange(i,1))}get mieScattering(){return[this.#ym.mieScattering[0],this.#ym.mieScattering[1],this.#ym.mieScattering[2]]}set mieScattering(i){this.#Cm("mieScattering",[...i],!0,!1,!0)}get mieAbsorption(){return[this.#ym.mieAbsorption[0],this.#ym.mieAbsorption[1],this.#ym.mieAbsorption[2]]}set mieAbsorption(i){this.#Cm("mieAbsorption",[...i],!0,!1,!0)}get rayleighScattering(){return[this.#ym.rayleighScattering[0],this.#ym.rayleighScattering[1],this.#ym.rayleighScattering[2]]}set rayleighScattering(i){this.#Cm("rayleighScattering",[...i],!0,!1,!0)}get rayleighExponentialDistribution(){return this.#ym.rayleighExponentialDistribution}set rayleighExponentialDistribution(i){this.#Cm("rayleighExponentialDistribution",i,!0,!1,!0,i=>validatePositiveNumberRange(i,.1,100))}get mieExponentialDistribution(){return this.#ym.mieExponentialDistribution}set mieExponentialDistribution(i){this.#Cm("mieExponentialDistribution",i,!0,!1,!0,i=>validatePositiveNumberRange(i,.1,100))}get mieAnisotropy(){return this.#ym.mieAnisotropy}set mieAnisotropy(i){this.#Cm("mieAnisotropy",i,!0,!1,!0,i=>validateNumberRange(i,0,.999))}get groundAlbedo(){return[this.#ym.groundAlbedo[0],this.#ym.groundAlbedo[1],this.#ym.groundAlbedo[2]]}set groundAlbedo(i){this.#Cm("groundAlbedo",[...i],!0,!1,!0)}get absorptionCoefficient(){return[this.#ym.absorptionCoefficient[0],this.#ym.absorptionCoefficient[1],this.#ym.absorptionCoefficient[2]]}set absorptionCoefficient(i){this.#Cm("absorptionCoefficient",[...i],!0,!1,!0)}get absorptionTipAltitude(){return this.#ym.absorptionTipAltitude}set absorptionTipAltitude(i){this.#Cm("absorptionTipAltitude",i,!0,!1,!0,i=>validatePositiveNumberRange(0,100))}get absorptionTentWidth(){return this.#ym.absorptionTentWidth}set absorptionTentWidth(i){this.#Cm("absorptionTentWidth",i,!0,!1,!0,i=>validatePositiveNumberRange(i,1,50))}get multiScatteringFactor(){return this.#ym.multiScatteringFactor}set multiScatteringFactor(i){this.#Cm("multiScatteringFactor",i,!0,!1,!0,i=>validatePositiveNumberRange(i,0,10))}get sunSize(){return this.#ym.sunSize}set sunSize(i){this.#Cm("sunSize",i,!1,!0,!0,i=>validatePositiveNumberRange(i,.01,10))}get sunLimbDarkening(){return this.#ym.sunLimbDarkening}set sunLimbDarkening(i){this.#Cm("sunLimbDarkening",i,!1,!1,!0,i=>validateNumberRange(i,0,10))}get skyLuminanceFactor(){return[this.#ym.skyLuminanceFactor[0],this.#ym.skyLuminanceFactor[1],this.#ym.skyLuminanceFactor[2]]}set skyLuminanceFactor(i){this.#Cm("skyLuminanceFactor",[...i],!0,!1,!0)}get transmittanceLUT(){return this.#dm.lutTexture}get multiScatLUT(){return this.#mm.lutTexture}get skyViewLUT(){return this.#pm.lutTexture}get aerialPerspectiveLUT(){return this.#gm.lutTexture}get skyAtmosphereIrradianceLUT(){return this.#xm.irradianceLUT}get skyAtmosphereReflectionLUT(){return this.#xm.reflectionLUT}get skyLight(){return this.#xm}get atmosphereSampler(){return this.#ne}renderBackground(i){this.#vm.render(i,this.#dm.lutTexture,this.#mm.lutTexture,this.skyViewLUT,this.#ne)}render(i,g,x,v){return this.update(i),this.#_m.render(i,g,x,v)}update(i){const g=i.renderViewStateData.frameIndex;this.#Pm!==g&&(this.#Pm=g,this.#ym.cloudTime=.001*i.renderViewStateData.time*this.#ym.cloudTimeMultiplier,this.#Mm=!0,this.#Bm(i),this.#Dm(i))}#Em(i,g,x){this.#Mm=!0,i&&(this.#Tm=!0),g&&(this.#wm=!0),x&&(this.#xm.dirty=!0)}#Bm(i){const g=i.scene.lightManager.directionalLights[0]||null,x=this.#Sm!==g;if(x&&(this.#Sm=g,this.#bm=g),g){const i=g.direction,v=this.#ym.sunDirection,_=1e-4,y=Math.sqrt(i[0]*i[0]+i[1]*i[1]+i[2]*i[2]),b=-(y>_?i[0]/y:i[0]),S=-(y>_?i[1]/y:i[1]),w=-(y>_?i[2]/y:i[2]),L=Math.abs(b-v[0])>_||Math.abs(S-v[1])>_||Math.abs(w-v[2])>_;(x||L)&&(v[0]=b,v[1]=S,v[2]=w,this.#Em(!1,!0,!0));const k=g.lux*g.intensityMultiplier;Math.abs(this.#ym.sunIntensity-k)>_&&(this.#ym.sunIntensity=k,this.#Em(!1,!1,!0))}}#Dm(i){const{rawCamera:g}=i,x=[g.x,g.y,g.z],v=Math.max(.001,x[1]/1e3);Math.abs(this.#ym.cameraHeight-v)>1e-4&&(this.#ym.cameraHeight=v,this.#Mm=!0);const _=g.viewMatrix;let y=!1;for(let i=0;i<16;i++)if(Math.abs(_[i]-this.#Rm[i])>1e-4){y=!0;break}y&&(copy$4(this.#Rm,_),this.#wm=!0),this.#Mm&&(this.#Im(),this.#Mm=!1),this.#Tm&&(this.#dm.render(),this.#mm.render(this.#dm.lutTexture),this.#Tm=!1,this.#wm=!0,this.#xm.dirty=!0),this.#wm&&(this.#pm.render(this.#dm.lutTexture,this.#mm.lutTexture),this.#gm.render(i,this.#dm.lutTexture,this.#mm.lutTexture),this.#wm=!1),this.#xm.update(this)}#Cm(i,g,x,v,_,y){y&&y(g),this.#ym[i]=g,this.#Em(x,v,_)}#Im(){const{members:i}=ja,g=this.#Xd.dataViewF32,x=this.#Xd.dataViewU32;for(const[v,_]of Object.entries(i)){const i=this.#ym[v];if(void 0!==i){const v=_,y=v.uniformOffset/4;if("number"==typeof i)v.View===Float32Array?g[y]=i:x[y]=i;else if(i instanceof Float32Array||Array.isArray(i))for(let x=0;xi===this.#Lm);if(!i)throw new Error(`Invalid blendMode value: ${this.#Lm}`);return i[0]}set blendMode(i){let g;if("string"==typeof i){if(!(i in Xa))throw new Error(`Invalid blendMode key: ${i}`);g=Xa[i]}else{if("number"!=typeof i||!Object.values(Xa).includes(i))throw new Error(`Invalid blendMode: ${i}`);g=i}this.#Lm=g,this.#Um(g)}get rotation(){return this.#Am}set rotation(i){this.#Am=i,super.rotationZ=i}setScale(i,g){g=g??i,super.setScale(i,g,1)}setPosition(i,g){g=g??i,super.setPosition(i,g,0)}setRotation(i){this.rotation=i}#Um(i){const{blendColorState:g,blendAlphaState:x}=this._material;switch(i){case Xa.NORMAL:g.operation=li.ADD,g.srcFactor=ui.SRC_ALPHA,g.dstFactor=ui.ONE_MINUS_SRC_ALPHA,x.operation=li.ADD,x.srcFactor=ui.SRC_ALPHA,x.dstFactor=ui.ONE_MINUS_SRC_ALPHA;break;case Xa.MULTIPLY:g.operation=li.ADD,g.srcFactor=ui.ONE_MINUS_DST_ALPHA,g.dstFactor=ui.ONE_MINUS_SRC_ALPHA,x.operation=li.ADD,x.srcFactor=ui.SRC_ALPHA,x.dstFactor=ui.ONE_MINUS_SRC_ALPHA;break;case Xa.LIGHTEN:g.operation=li.MAX,g.srcFactor=ui.ONE,g.dstFactor=ui.ONE,x.operation=li.ADD,x.srcFactor=ui.SRC_ALPHA,x.dstFactor=ui.ONE_MINUS_SRC_ALPHA;break;case Xa.SCREEN:g.operation=li.ADD,g.srcFactor=ui.ONE,g.dstFactor=ui.ONE_MINUS_SRC,x.operation=li.ADD,x.srcFactor=ui.SRC_ALPHA,x.dstFactor=ui.ONE_MINUS_SRC_ALPHA;break;case Xa.LINEAR_DODGE:g.operation=li.ADD,g.srcFactor=ui.ONE,g.dstFactor=ui.ONE,x.operation=li.ADD,x.srcFactor=ui.SRC_ALPHA,x.dstFactor=ui.ONE;break;case Xa.SUBTRACT:g.operation=li.REVERSE_SUBTRACT,g.srcFactor=ui.SRC_ALPHA,g.dstFactor=ui.ONE_MINUS_SRC_ALPHA,x.operation=li.REVERSE_SUBTRACT,x.srcFactor=ui.ONE,x.dstFactor=ui.ONE;break;case Xa.DIFFERENCE:g.operation=li.SUBTRACT,g.srcFactor=ui.ONE,g.dstFactor=ui.ONE,x.operation=li.SUBTRACT,x.srcFactor=ui.ONE,x.dstFactor=ui.ONE;break;case Xa.EXCLUSION:g.operation=li.ADD,g.srcFactor=ui.ONE_MINUS_DST_ALPHA,g.dstFactor=ui.ONE_MINUS_SRC_ALPHA,x.operation=li.ADD,x.srcFactor=ui.ONE,x.dstFactor=ui.ONE;break;default:console.warn(`Unsupported blend mode: ${i}`)}}};return Object.defineProperty(g.prototype,"is2DMeshType",{value:!0,writable:!1}),g}var qa=Object.freeze({__proto__:null,LODManager:LODManager,MeshBase:MeshBase,Object3DContainer:Object3DContainer,VertexGPURenderInfo:VertexGPURenderInfo,createMeshVertexUniformBuffers:createMeshVertexUniformBuffers,mixInMesh2D:mixInMesh2D}),Ya=Object.freeze({__proto__:null,AView:AView,RenderViewStateData:RenderViewStateData,ViewRenderTextureManager:ViewRenderTextureManager,ViewTransform:ViewTransform});class View2D extends View3D{constructor(i,g,x){super(i,g,new Camera2D,x)}}Object.freeze(View2D);class Group3D extends Object3DContainer{modelMatrix=create$4();localMatrix=create$4();#cs;#wi=0;#Pi=0;#Mi=0;#hs=[0,0,0];#fs=0;#ds=0;#ms=0;#gs=1;#xs=1;#vs=1;#_s=[1,1,1];#ys=0;#bs=0;#Ss=0;#Ts=[0,0,0];#km=!0;constructor(i){super(),i&&(this.name=i)}get dirtyTransform(){return this.#km}set dirtyTransform(i){this.#km=i}get parent(){return this.#cs}set parent(i){this.#cs=i}get pivotX(){return this.#fs}set pivotX(i){this.#fs=i,this.dirtyTransform=!0}get pivotY(){return this.#ds}set pivotY(i){this.#ds=i,this.dirtyTransform=!0}get pivotZ(){return this.#ms}set pivotZ(i){this.#ms=i,this.dirtyTransform=!0}get x(){return this.#wi}set x(i){this.#wi=this.#hs[0]=i,this.dirtyTransform=!0}get y(){return this.#Mi}set y(i){this.#Mi=this.#hs[1]=i,this.dirtyTransform=!0}get z(){return this.#Pi}set z(i){this.#Pi=this.#hs[2]=i,this.dirtyTransform=!0}get position(){return this.#hs}get scaleX(){return this.#gs}set scaleX(i){this.#gs=this.#_s[0]=i,this.dirtyTransform=!0}get scaleY(){return this.#xs}set scaleY(i){this.#xs=this.#_s[1]=i,this.dirtyTransform=!0}get scaleZ(){return this.#vs}set scaleZ(i){this.#vs=this.#_s[2]=i,this.dirtyTransform=!0}get scale(){return this.#_s}get rotationX(){return this.#ys}set rotationX(i){this.#ys=this.#Ts[0]=i,this.dirtyTransform=!0}get rotationY(){return this.#bs}set rotationY(i){this.#bs=this.#Ts[1]=i,this.dirtyTransform=!0}get rotationZ(){return this.#Ss}set rotationZ(i){this.#Ss=this.#Ts[2]=i,this.dirtyTransform=!0}get rotation(){return this.#Ts}setScale(i,g,x){g=g??i,x=x??i;const v=this.#_s;this.#gs=v[0]=i,this.#xs=v[1]=g,this.#vs=v[2]=x,this.dirtyTransform=!0}setPosition(i,g,x){g=g??i,x=x??i;const v=this.#hs;this.#wi=v[0]=i,this.#Mi=v[1]=g,this.#Pi=v[2]=x,this.dirtyTransform=!0}setRotation(i,g,x){g=g??i,x=x??i;const v=this.#Ts;this.#ys=v[0]=i,this.#bs=v[1]=g,this.#Ss=v[2]=x,this.dirtyTransform=!0}render(i){const{view:g,isScene2DMode:x}=i;let v;x&&(this.#Pi=0,this.#ms=0),this.dirtyTransform&&(v=!0,updateObject3DMatrix(this,g)),this.dirtyTransform&&(v=!0,this.dirtyTransform=!1),i.renderResults.num3DGroups++;const{children:_}=this;let y=0;const b=_.length;for(;y,tintBlendMode:u32,};@group(2)@binding(0)varuniforms:Uniforms;@group(2)@binding(1)var diffuseTextureSampler:sampler;@group(2)@binding(2)var diffuseTexture:texture_2d;struct InputData{@builtin(position)position:vec4,@location(0)vertexPosition:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,@location(7)currentClipPos:vec4,@location(8)prevClipPos:vec4,@location(11)combinedOpacity:f32,@location(12)motionVector:vec3,@location(13)shadowCoord:vec3,@location(15)@interpolate(flat)pickingId:vec4,};@fragment fn main(inputData:InputData)->OutputFragment{var output:OutputFragment;var finalColor:vec4=vec4(.0);#redgpu_if diffuseTexture finalColor=textureSample(diffuseTexture,diffuseTextureSampler,inputData.uv);#redgpu_endIf let alpha2D=select(finalColor.a,1.0,systemUniforms.isView3D==1u);finalColor=vec4(finalColor.rgb*alpha2D,finalColor.a*uniforms.opacity*inputData.combinedOpacity);#redgpu_if useTint finalColor=getTintBlendMode(finalColor,uniforms.tintBlendMode,uniforms.tint);#redgpu_endIf if(systemUniforms.isView3D==1&&finalColor.a==.0){discard;}output.color=vec4(finalColor.rgb,finalColor.a);output.gBufferMotionVector=vec4(getMotionVector(inputData.currentClipPos,inputData.prevClipPos),.0,1.0);return output;};");class BitmapMaterial extends AUVTransformBaseMaterial{constructor(i,g,x){super(i,"BITMAP_MATERIAL",Za,2),x&&(this.name=x),this.diffuseTexture=g,this.diffuseTextureSampler=new Sampler(this.redGPUContext),this.initGPURenderInfos()}}defineSampler(BitmapMaterial,[{key:"diffuseTextureSampler"}]),defineTexture(BitmapMaterial,[{key:"diffuseTexture"}]),Object.freeze(BitmapMaterial);var Ja="#redgpu_include SYSTEM_UNIFORM;#redgpu_include math.billboard.getBillboardMatrix;struct MatrixList{modelMatrix:mat4x4,normalModelMatrix:mat4x4,}struct VertexUniforms{matrixList:MatrixList,pickingId:u32,useBillboardPerspective:u32,useBillboard:u32,combinedOpacity:f32,};@group(1)@binding(0)varvertexUniforms:VertexUniforms;struct InputData{@location(0)a_position:vec3,@location(1)a_normal:vec3,@location(2)a_uv:vec2,@location(3)a_tangent:vec4,@location(4)position:vec3,@location(5)alpha:f32,@location(6)rotation:vec3,@location(7)scale:f32,};struct VertexOutput{@builtin(position)position:vec4,@location(0)vertexPosition:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,@location(7)currentClipPos:vec4,@location(8)prevClipPos:vec4,@location(11)combinedOpacity:f32,@location(12)motionVector:vec3,@location(13)shadowCoord:vec3,@location(14)@interpolate(flat)receiveShadow:f32,@location(15)@interpolate(flat)pickingId:vec4,};fn mat4_inverse(a:mat4x4)->mat4x4{var a00:f32=a[0][0];var a01:f32=a[0][1];var a02:f32=a[0][2];var a03:f32=a[0][3];var a10:f32=a[1][0];var a11:f32=a[1][1];var a12:f32=a[1][2];var a13:f32=a[1][3];var a20:f32=a[2][0];var a21:f32=a[2][1];var a22:f32=a[2][2];var a23:f32=a[2][3];var a30:f32=a[3][0];var a31:f32=a[3][1];var a32:f32=a[3][2];var a33:f32=a[3][3];var b00:f32=a00*a11-a01*a10;var b01:f32=a00*a12-a02*a10;var b02:f32=a00*a13-a03*a10;var b03:f32=a01*a12-a02*a11;var b04:f32=a01*a13-a03*a11;var b05:f32=a02*a13-a03*a12;var b06:f32=a20*a31-a21*a30;var b07:f32=a20*a32-a22*a30;var b08:f32=a20*a33-a23*a30;var b09:f32=a21*a32-a22*a31;var b10:f32=a21*a33-a23*a31;var b11:f32=a22*a33-a23*a32;var det:f32=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;if(det !=.0){det=1.0/det;return mat4x4((a11*b11-a12*b10+a13*b09)*det,(a02*b10-a01*b11-a03*b09)*det,(a31*b05-a32*b04+a33*b03)*det,(a22*b04-a21*b05-a23*b03)*det,(a12*b08-a10*b11-a13*b07)*det,(a00*b11-a02*b08+a03*b07)*det,(a32*b02-a30*b05-a33*b01)*det,(a20*b05-a22*b02+a23*b01)*det,(a10*b10-a11*b08+a13*b06)*det,(a01*b08-a00*b10-a03*b06)*det,(a30*b04-a31*b02+a33*b00)*det,(a21*b02-a20*b04-a23*b00)*det,(a11*b07-a10*b09-a12*b06)*det,(a00*b09-a01*b07+a02*b06)*det,(a31*b01-a30*b03-a32*b00)*det,(a20*b03-a21*b01+a22*b00)*det);}return mat4x4(.0,.0,.0,.0,.0,.0,.0,.0,.0,.0,.0,.0,.0,.0,.0,.0);}fn rotationMTX(t:vec3)->mat4x4{var s:f32=sin(t.x);var c:f32=cos(t.x);var m1=mat4x4(1,0,0,0,0,c,-s,0,0,s,c,0,0,0,0,1);s=sin(t[1]);c=cos(t[1]);var m2=mat4x4(c,0,s,0,0,1,0,0,-s,0,c,0,0,0,0,1);s=sin(t[2]);c=cos(t[2]);var m3=mat4x4(c,-s,0,0,s,c,0,0,0,0,1,0,0,0,0,1);return m1*m2*m3;}@vertex fn main(inputData:InputData)->VertexOutput{var output:VertexOutput;let u_projectionMatrix=systemUniforms.projection.projectionMatrix;let u_projectionViewMatrix=systemUniforms.projection.projectionViewMatrix;let u_resolution=systemUniforms.resolution;let u_camera=systemUniforms.camera;let u_viewMatrix=u_camera.viewMatrix;let u_cameraPosition=u_camera.cameraPosition;let u_modelMatrix=vertexUniforms.matrixList.modelMatrix;let u_normalModelMatrix=vertexUniforms.matrixList.normalModelMatrix;let u_useBillboardPerspective=vertexUniforms.useBillboardPerspective==1u;let u_useBillboard=vertexUniforms.useBillboard==1u;let input_position=inputData.position;var position:vec4;var normalPosition:vec4;var scaleMTX=mat4x4(inputData.scale,0,0,0,0,inputData.scale,0,0,0,0,inputData.scale,0,0,0,0,1);var translateTX=mat4x4(1,0,0,0,0,1,0,0,0,0,1,0,inputData.position.x,inputData.position.y,inputData.position.z,1);var temp:mat4x4;if(u_useBillboard){var rotateMTX2=rotationMTX(vec3(0,0,inputData.rotation.z));temp=translateTX*rotateMTX2;position=rotateMTX2*vec4(inputData.a_position,1);output.position=u_projectionMatrix*getBillboardMatrix(u_viewMatrix,temp,0u)*scaleMTX*position;}else{var rotateMTX=rotationMTX(inputData.rotation);temp=translateTX*rotateMTX*scaleMTX;position=temp*vec4(inputData.a_position,1);output.position=u_projectionViewMatrix*position;}output.vertexPosition=position.xyz;output.vertexNormal=(transpose(mat4_inverse(temp))*vec4(inputData.a_normal,1.0)).xyz;output.uv=inputData.a_uv;output.combinedOpacity=inputData.alpha;return output;}";const Qa=parseWGSL("PARTICLE_EMITTER_VERTEX",Ja),es=Qa.uniforms.vertexUniforms;class ParticleEmitter extends Mesh{#Gm=1e3;#Om=5e3;#Vm=0;#Nm=0;#Fm=0;#Hm=0;#zm=0;#$m=0;#jm=-5;#Km=-5;#Xm=-5;#qm=5;#Ym=5;#Wm=5;#Zm=1;#Jm=1;#Qm=1;#ep=1;#tp=0;#rp=1;#ip=0;#np=0;#ap=-360;#sp=-360;#op=-360;#up=360;#lp=360;#cp=360;#hp=-360;#fp=-360;#dp=-360;#mp=360;#pp=360;#gp=360;#xp=Wa.CubicOut;#vp=Wa.CubicOut;#_p=Wa.CubicOut;#yp=Wa.Linear;#bp=Wa.Linear;#Sp=Wa.CubicOut;#Tp=Wa.CubicOut;#wp=Wa.CubicOut;#Mp;#Pp;#Rp;#Hr;#Cp;#Bp=2e3;constructor(i){super(i),this.geometry=new Plane(i),this.material=new BitmapMaterial(i),this.ignoreFrustumCulling=!0}get vertexStateBuffers(){const i=this.geometry.gpuRenderInfo.buffers[0],g=Array.from(i.attributes).length;return[i,{arrayStride:48,stepMode:"instance",attributes:[{shaderLocation:g,offset:16,format:"float32x3"},{shaderLocation:g+1,offset:28,format:"float32"},{shaderLocation:g+2,offset:32,format:"float32x3"},{shaderLocation:g+3,offset:44,format:"float32"}]}]}get particleNum(){return this.#Bp}set particleNum(i){this.#Bp=Math.max(Math.min(i,5e5),1),this.#Mp||this.#N(),this.#Dp()}get minLife(){return this.#Gm}set minLife(i){this.#Gm=i}get maxLife(){return this.#Om}set maxLife(i){this.#Om=i}get minStartX(){return this.#Vm}set minStartX(i){this.#Vm=i}get minStartY(){return this.#Nm}set minStartY(i){this.#Nm=i}get minStartZ(){return this.#Fm}set minStartZ(i){this.#Fm=i}get maxStartX(){return this.#Hm}set maxStartX(i){this.#Hm=i}get maxStartY(){return this.#zm}set maxStartY(i){this.#zm=i}get maxStartZ(){return this.#$m}set maxStartZ(i){this.#$m=i}get minEndX(){return this.#jm}set minEndX(i){this.#jm=i}get minEndY(){return this.#Km}set minEndY(i){this.#Km=i}get minEndZ(){return this.#Xm}set minEndZ(i){this.#Xm=i}get maxEndX(){return this.#qm}set maxEndX(i){this.#qm=i}get maxEndY(){return this.#Ym}set maxEndY(i){this.#Ym=i}get maxEndZ(){return this.#Wm}set maxEndZ(i){this.#Wm=i}get minStartAlpha(){return this.#Zm}set minStartAlpha(i){this.#Zm=i}get maxStartAlpha(){return this.#Jm}set maxStartAlpha(i){this.#Jm=i}get minEndAlpha(){return this.#Qm}set minEndAlpha(i){this.#Qm=i}get maxEndAlpha(){return this.#ep}set maxEndAlpha(i){this.#ep=i}get minStartScale(){return this.#tp}set minStartScale(i){this.#tp=i}get maxStartScale(){return this.#rp}set maxStartScale(i){this.#rp=i}get minEndScale(){return this.#ip}set minEndScale(i){this.#ip=i}get maxEndScale(){return this.#np}set maxEndScale(i){this.#np=i}get minStartRotationX(){return this.#ap}set minStartRotationX(i){this.#ap=i}get minStartRotationY(){return this.#sp}set minStartRotationY(i){this.#sp=i}get minStartRotationZ(){return this.#op}set minStartRotationZ(i){this.#op=i}get maxStartRotationX(){return this.#up}set maxStartRotationX(i){this.#up=i}get maxStartRotationY(){return this.#lp}set maxStartRotationY(i){this.#lp=i}get maxStartRotationZ(){return this.#cp}set maxStartRotationZ(i){this.#cp=i}get minEndRotationX(){return this.#hp}set minEndRotationX(i){this.#hp=i}get minEndRotationY(){return this.#fp}set minEndRotationY(i){this.#fp=i}get minEndRotationZ(){return this.#dp}set minEndRotationZ(i){this.#dp=i}get maxEndRotationX(){return this.#mp}set maxEndRotationX(i){this.#mp=i}get maxEndRotationY(){return this.#pp}set maxEndRotationY(i){this.#pp=i}get maxEndRotationZ(){return this.#gp}set maxEndRotationZ(i){this.#gp=i}get easeX(){return this.#xp}set easeX(i){this.#xp=i}get easeY(){return this.#vp}set easeY(i){this.#vp=i}get easeZ(){return this.#_p}set easeZ(i){this.#_p=i}get easeAlpha(){return this.#yp}set easeAlpha(i){this.#yp=i}get easeScale(){return this.#bp}set easeScale(i){this.#bp=i}get easeRotationX(){return this.#Sp}set easeRotationX(i){this.#Sp=i}get easeRotationY(){return this.#Tp}set easeRotationY(i){this.#Tp=i}get easeRotationZ(){return this.#wp}set easeRotationZ(i){this.#wp=i}get particleBuffers(){return this.#Pp}render(i){this.#Mp||this.#N(),this.#Ep(i.timestamp),super.render(i)}createCustomMeshVertexShaderModule=()=>this.createMeshVertexShaderModuleBASIC("VERTEX_MODULE_PARTICLE_EMITTER",Qa,es,Ja);#N(){this.#Rp=new Float32Array(46);let i={size:this.#Rp.byteLength,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST};const{gpuDevice:g}=this.redGPUContext;this.#Mp=g.createBuffer(i),g.queue.writeBuffer(this.#Mp,0,this.#Rp),this.#Dp(),this.depthStencilState.depthWriteEnabled=!1}#Dp(){this.dirtyPipeline=!0;let i=this.redGPUContext;const g=new Float32Array(12*this.#Bp),x=new Float32Array(12*this.#Bp),v=new Float32Array(12*this.#Bp),_=new Float32Array(4*this.#Bp),y=new Float32Array(4*this.#Bp),b=performance.now(),S=this.localToWorld(this.x,this.y,this.z);for(let i=0;i{L.forEach((g,x)=>{const v=z.createBuffer({size:g.byteLength,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC|GPUBufferUsage.VERTEX|GPUBufferUsage.STORAGE});z.queue.writeBuffer(v,0,g),this.#Pp.push(v),w?.length&©GPUBuffer(i,w[x],v)})}),w&&w.forEach(i=>H.addDeferredDestroy(i));let q={code:"#redgpu_include math.hash.getHash1D struct Info{startValue:f32,endValue:f32,easeType:f32,birthCenterValue:f32};struct InfoGroup{infoX:Info,infoY:Info,infoZ:Info,};struct Particle{startTime:f32,life:f32,valuePosition:vec3,valueAlpha:f32,valueRotation:vec3,valueScale:f32,};struct SimParams{time:f32,currentPositionX:f32,currentPositionY:f32,currentPositionZ:f32,minLife:f32,maxLife:f32,minStartX:f32,maxStartX:f32,minEndX:f32,maxEndX:f32,easeX:f32,minStartY:f32,maxStartY:f32,minEndY:f32,maxEndY:f32,easeY:f32,minStartZ:f32,maxStartZ:f32,minEndZ:f32,maxEndZ:f32,easeZ:f32,minStartAlpha:f32,maxStartAlpha:f32,minEndAlpha:f32,maxEndAlpha:f32,easeAlpha:f32,minStartScale:f32,maxStartScale:f32,minEndScale:f32,maxEndScale:f32,easeScale:f32,minStartRotationX:f32,maxStartRotationX:f32,minEndRotationX:f32,maxEndRotationX:f32,easeRotationX:f32,minStartRotationY:f32,maxStartRotationY:f32,minEndRotationY:f32,maxEndRotationY:f32,easeRotationY:f32,minStartRotationZ:f32,maxStartRotationZ:f32,minEndRotationZ:f32,maxEndRotationZ:f32,easeRotationZ:f32,};@group(0)@binding(0)varparams:SimParams;@group(0)@binding(1)varparticles:array;@group(0)@binding(2)varinfoPosition:array;@group(0)@binding(3)varinfoRotation:array;@group(0)@binding(4)varinfoScale:array;@group(0)@binding(5)varinfoAlpha:array;#redgpu_include math.PI #redgpu_include math.HPI #redgpu_include math.PI2 #redgpu_include math.DEG_TO_RAD fn calEasing(n:f32,easingType:f32)->f32{var m:f32=n;let easingInt:i32=i32(easingType);switch(easingInt){case 0:{m=m;}case 1:{m=m*m*m*m*m;}case 2:{m-=1.0;m=(m*m*m*m*m)+1.0;}case 3:{if(m*2.0<1.0){m*=2.0;m=m*m*m*m*m*0.5;}else{m=m*2.0-2.0;m=0.5*(m*m*m*m*m+2.0);}}case 4:{m=m*m*(m*1.70158+m-1.70158);}case 5:{m-=1.0;m=m*m*(m*1.70158+m+1.70158)+1.0;}case 6:{if(m*2.0<1.0){m*=2.0;m=0.5*m*m*(m*1.70158+m-1.70158);}else{m=m*2.0-2.0;m=0.5*m*m*(m*1.70158+m+1.70158)+1.0;}}case 7:{m=-1.0*(sqrt(1.0-m*m)-1.0);}case 8:{m-=1.0;m=sqrt(1.0-m*m);}case 9:{if(m*2.0<1.0){m*=2.0;m=-0.5*(sqrt(1.0-m*m)-1.0);}else{m=m*2.0-2.0;m=0.5*sqrt(1.0-m*m)+0.5;}}case 10:{m=m*m*m;}case 11:{m-=1.0;m=m*m*m+1.0;}case 12:{if(m*2.0<1.0){m*=2.0;m=m*m*m*0.5;}else{m=m*2.0-2.0;m=0.5*(m*m*m+2.0);}}case 13:{if(m==.0){m=.0;}else{m=pow(2.0,10.0*(m-1.0));}}case 14:{if(m==1.0){m=1.0;}else{m=-pow(2.0,-10.0*m)+1.0;}}case 15:{if(m*2.0<1.0){if(m==.0){m=.0;}else{m*=2.0;m=0.5*pow(2.0,10.0*(m-1.0));}}else{if(m==2.0){m=1.0;}else{m=m*2.0-1.0;m=-0.5*pow(2.0,-10.0*m)+1.0;}}}case 16:{m=m*m;}case 17:{m=(2.0-m)*m;}case 18:{if(m*2.0<1.0){m*=2.0;m=m*m*0.5;}else{m=2.0-m;m=0.5*(m*m+1.0);}}case 19:{m=m*m*m*m;}case 20:{m-=1.0;m=1.0-(m*m*m*m);}case 21:{if(m*2.0<1.0){m*=2.0;m=m*m*m*m*0.5;}else{m=m*2.0-2.0;m=1.0-(m*m*m*m*0.5);}}case 22:{m=-cos(m*HPI)+1.0;}case 23:{m=sin(m*HPI);}case 24:{m=(-cos(m*PI)+1.0)*0.5;}case 25:{if(m==.0){m=.0;}else if(m==1.0){m=1.0;}else{m-=1.0;m=-1.0*pow(2.0,10.0*m)*sin((m-.075)*PI2/0.3);}}case 26:{if(m==.0){m=.0;}else if(m==1.0){m=1.0;}else{m-=1.0;m=-pow(2.0,10.0*m)*sin((m-.075)*PI2/0.3);}}case 27:{if(m==.0){m=.0;}else if(m==1.0){m=1.0;}else{m=pow(2.0,-10.0*m)*sin((m-.075)*PI2/0.3)+1.0;}}default:{m=m;}}return m;}fn randomRange(min:f32,max:f32,v:f32)->f32{var newValue:f32=getHash1D(v);return(newValue*(max-min))+min;}fn compute_value(tInfo:Info,lifeRatio:f32)->f32{return tInfo.startValue+((tInfo.endValue-tInfo.startValue)*calEasing(lifeRatio,tInfo.easeType));}@compute @workgroup_size(256,1,1)fn main(@builtin(global_invocation_id)global_id:vec3){let index:u32=(global_id.x);let age:f32=(params.time-particles[index].startTime);var lifeRatio:f32=(age/particles[index].life);if(lifeRatio>=1.0){let uuid:f32=(params.time+f32(index));particles[index].startTime=params.time;particles[index].life=randomRange(params.minLife,params.maxLife,uuid);infoPosition[index].infoX.startValue=randomRange(params.minStartX+params.currentPositionX,params.maxStartX+params.currentPositionX,(uuid+1.0));infoPosition[index].infoX.endValue=randomRange(params.minEndX+params.currentPositionX,params.maxEndX+params.currentPositionX,(uuid+2.0));infoPosition[index].infoX.easeType=params.easeX;infoPosition[index].infoX.birthCenterValue=params.currentPositionX;infoPosition[index].infoY.startValue=randomRange(params.minStartY+params.currentPositionY,params.maxStartY+params.currentPositionY,(uuid+3.0));infoPosition[index].infoY.endValue=randomRange(params.minEndY+params.currentPositionY,params.maxEndY+params.currentPositionY,(uuid+4.0));infoPosition[index].infoY.easeType=params.easeY;infoPosition[index].infoY.birthCenterValue=params.currentPositionY;infoPosition[index].infoZ.startValue=randomRange(params.minStartZ+params.currentPositionZ,params.maxStartZ+params.currentPositionZ,(uuid+5.0));infoPosition[index].infoZ.endValue=randomRange(params.minEndZ+params.currentPositionZ,params.maxEndZ+params.currentPositionZ,(uuid+6.0));infoPosition[index].infoZ.easeType=params.easeZ;infoPosition[index].infoZ.birthCenterValue=params.currentPositionZ;infoAlpha[index].startValue=randomRange(params.minStartAlpha,params.maxStartAlpha,(uuid+7.0));infoAlpha[index].endValue=randomRange(params.minEndAlpha,params.maxEndAlpha,(uuid+8.0));infoAlpha[index].easeType=params.easeAlpha;infoScale[index].startValue=randomRange(params.minStartScale,params.maxStartScale,(uuid+9.0));infoScale[index].endValue=randomRange(params.minEndScale,params.maxEndScale,(uuid+10.0));infoScale[index].easeType=params.easeScale;infoRotation[index].infoX.startValue=randomRange(params.minStartRotationX,params.maxStartRotationX,(uuid+11.0));infoRotation[index].infoX.endValue=randomRange(params.minEndRotationX,params.maxEndRotationX,(uuid+12.0));infoRotation[index].infoX.easeType=params.easeRotationX;infoRotation[index].infoY.startValue=randomRange(params.minStartRotationY,params.maxStartRotationY,(uuid+13.0));infoRotation[index].infoY.endValue=randomRange(params.minEndRotationY,params.maxEndRotationY,(uuid+14.0));infoRotation[index].infoY.easeType=params.easeRotationY;infoRotation[index].infoZ.startValue=randomRange(params.minStartRotationZ,params.maxStartRotationZ,(uuid+15.0));infoRotation[index].infoZ.endValue=randomRange(params.minEndRotationZ,params.maxEndRotationZ,(uuid+16.0));infoRotation[index].infoZ.easeType=params.easeRotationZ;lifeRatio=.0;}var targetInfo:Info;let targetParticle=particles[index];targetInfo=infoPosition[index].infoX;particles[index].valuePosition.x=compute_value(targetInfo,lifeRatio);targetInfo=infoPosition[index].infoY;particles[index].valuePosition.y=compute_value(targetInfo,lifeRatio);targetInfo=infoPosition[index].infoZ;particles[index].valuePosition.z=compute_value(targetInfo,lifeRatio);targetInfo=infoAlpha[index];particles[index].valueAlpha=compute_value(targetInfo,lifeRatio);targetInfo=infoScale[index];particles[index].valueScale=compute_value(targetInfo,lifeRatio);targetInfo=infoRotation[index].infoX;particles[index].valueRotation.x=compute_value(targetInfo,lifeRatio)*DEG_TO_RAD;targetInfo=infoRotation[index].infoY;particles[index].valueRotation.y=compute_value(targetInfo,lifeRatio)*DEG_TO_RAD;targetInfo=infoRotation[index].infoZ;particles[index].valueRotation.z=compute_value(targetInfo,lifeRatio)*DEG_TO_RAD;}"},W=i.resourceManager.createGPUShaderModule("PARTICLE_EMITTER_MODULE",q);const be=[{binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}}],je=[{binding:0,resource:{buffer:this.#Mp,offset:0,size:this.#Rp.byteLength}}];L.forEach((i,g)=>{be.push({binding:g+1,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}}),je.push({binding:g+1,resource:{buffer:this.#Pp[g],offset:0,size:i.byteLength}})});const Ke=i.gpuDevice.createBindGroupLayout({entries:be}),Xe=i.gpuDevice.createPipelineLayout({bindGroupLayouts:[Ke]});this.#Cp=i.gpuDevice.createBindGroup({label:"PARTICLE_EMITTER_BIND_GROUP",layout:Ke,entries:je}),this.#Hr=i.gpuDevice.createComputePipeline({label:"PARTICLE_EMITTER_PIPELINE",layout:Xe,compute:{module:W,entryPoint:"main"}})}#Ep(i){const g=this.localToWorld(this.x,this.y,this.z);this.#Rp.set([i,...g,this.#Gm,this.#Om,this.#Vm,this.#Hm,this.#jm,this.#qm,this.#xp,this.#Nm,this.#zm,this.#Km,this.#Ym,this.#vp,this.#Fm,this.#$m,this.#Xm,this.#Wm,this.#_p,this.#Zm,this.#Jm,this.#Qm,this.#ep,this.#yp,this.#tp,this.#rp,this.#ip,this.#np,this.#bp,this.#ap,this.#up,this.#hp,this.#mp,this.#Sp,this.#sp,this.#lp,this.#fp,this.#pp,this.#Tp,this.#op,this.#cp,this.#dp,this.#gp,this.#wp],0);const{commandEncoderManager:x}=this.redGPUContext;this.redGPUContext.gpuDevice.queue.writeBuffer(this.#Mp,0,this.#Rp),x.addPreProcessComputePass("PARTICLE_EMITTER_COMPUTE_PASS",i=>{i.setPipeline(this.#Hr),i.setBindGroup(0,this.#Cp),i.dispatchWorkgroups(Math.ceil(this.#Bp/256))})}}Object.defineProperty(ParticleEmitter.prototype,"isInstanceofParticle",{value:!0,writable:!1}),defineBoolean(ParticleEmitter,[{key:"useBillboard",value:!0}]),Object.freeze(ParticleEmitter);const ts=mixInMesh2D(Mesh);class Sprite2D extends ts{#Gt=1;#Ot=1;constructor(i,g){super(i,new Plane(i,1,1,1,1,!0),g),this.primitiveState.cullMode=Ji.FRONT}get width(){return this.#Gt}set width(i){validatePositiveNumberRange(i),this.#Gt=i,this.dirtyTransform=!0}get height(){return this.#Ot}set height(i){validatePositiveNumberRange(i),this.#Ot=i,this.dirtyTransform=!0}setSize(i,g){this.width=i,this.height=void 0!==g?g:i}}Object.freeze(Sprite2D);var rs="#redgpu_include SYSTEM_UNIFORM;#redgpu_include math.billboard.getBillboardMatrix;#redgpu_include math.billboard.getBillboardResult;#redgpu_include entryPoint.billboard.entryPointPickingVertex;#redgpu_include entryPoint.empty.entryPointShadowVertex;struct MatrixList{modelMatrix:mat4x4,normalModelMatrix:mat4x4,}struct VertexUniforms{matrixList:MatrixList,pickingId:u32,useBillboard:u32,usePixelSize:u32,pixelSize:f32,_renderRatioX:f32,_renderRatioY:f32,combinedOpacity:f32,};@group(1)@binding(0)varvertexUniforms:VertexUniforms;struct InputData{@location(0)position:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,};struct VertexOutput{@builtin(position)position:vec4,@location(0)vertexPosition:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,@location(7)currentClipPos:vec4,@location(8)prevClipPos:vec4,@location(11)combinedOpacity:f32,@location(12)motionVector:vec3,@location(13)shadowCoord:vec3,@location(15)@interpolate(flat)pickingId:vec4,};@vertex fn main(inputData:InputData)->VertexOutput{var output:VertexOutput;let billboardResult=getBillboardResult(inputData.position,inputData.vertexNormal,vertexUniforms.matrixList.modelMatrix,systemUniforms.camera.viewMatrix,systemUniforms.projection.projectionMatrix,systemUniforms.resolution,vertexUniforms.useBillboard,vertexUniforms.usePixelSize,vertexUniforms.pixelSize,vertexUniforms._renderRatioX,vertexUniforms._renderRatioY);output.position=billboardResult.position;output.vertexPosition=billboardResult.vertexPosition;output.vertexNormal=billboardResult.vertexNormal;output.uv=inputData.uv;output.combinedOpacity=vertexUniforms.combinedOpacity;return output;}";const is=parseWGSL("SPRITE3D_VERTEX",rs),ns=is.uniforms.vertexUniforms;class Sprite3D extends Mesh{#Wo=1;#Zo=1;#Jo=1;#Ip=0;#Qo=!1;constructor(i,g,x){super(i),this._geometry=x||new Plane(i),this._material=g,this._material&&(this._material.transparent=!0),this.dirtyPipeline=!0,this.dirtyTransform=!0,this.primitiveState.cullMode=Ji.NONE}get worldSize(){return this.#Jo}set worldSize(i){this.#Jo!==i&&(this.#Jo=i,this.#eu())}get usePixelSize(){return this.#Qo}set usePixelSize(i){if(this.gpuRenderInfo){const{vertexUniformBuffer:g,vertexUniformInfo:x}=this.gpuRenderInfo;this.redGPUContext.gpuDevice.queue.writeBuffer(g.gpuBuffer,x.members.usePixelSize.uniformOffset,new Uint32Array([i?1:0]))}this.#Qo!==i&&(this.#Qo=i,this.#eu())}get pixelSize(){return this.#Ip}set pixelSize(i){if(this.gpuRenderInfo){const{vertexUniformBuffer:g,vertexUniformInfo:x}=this.gpuRenderInfo;this.redGPUContext.gpuDevice.queue.writeBuffer(g.gpuBuffer,x.members.pixelSize.uniformOffset,new Float32Array([i*window.devicePixelRatio]))}this.#Ip=i}render(i){if(this._material instanceof BitmapMaterial&&this._material.diffuseTexture){const{gpuTexture:i}=this._material.diffuseTexture;if(i){const g=i.width,x=i.height;if(g!==this.#Wo||x!==this.#Zo){this.#Wo=g,this.#Zo=x;const i=this.pixelSize;this.pixelSize=this.pixelSize||x,this.#eu(),i!==this.pixelSize&&(this.dirtyTransform=!0)}}}super.render(i)}createCustomMeshVertexShaderModule=()=>this.createMeshVertexShaderModuleBASIC("VERTEX_MODULE_SPRITE_3D",is,ns,rs);#eu(){if(this.#Zo){const i=this._renderRatioX,g=this._renderRatioY;this.usePixelSize?(this._renderRatioY=1,this._renderRatioX=this.#Wo/this.#Zo):(this._renderRatioY=this.#Jo,this._renderRatioX=this.#Wo/this.#Zo*this.#Jo),i===this._renderRatioX&&g===this._renderRatioY||(this.dirtyTransform=!0)}}}definePositiveNumber(Sprite3D,[{key:"_renderRatioX",value:1},{key:"_renderRatioY",value:1}]),defineBoolean(Sprite3D,[{key:"useBillboard",value:!0}]),Object.freeze(Sprite3D);class ASpriteSheet extends Mesh{#Ap=0;#Lp=0;#Up=0;#kp=!0;#Gp=!0;#Op;#Vp;#Np="play";constructor(i,g,x){super(i),this.#Vp=x,this._material=new BitmapMaterial(i),this._material.transparent=!0,this.dirtyPipeline=!0,this.dirtyTransform=!0,this.spriteSheetInfo=g,this._material.diffuseTextureSampler=new Sampler(i),this._material.diffuseTextureSampler.addressModeU=v.REPEAT,this._material.diffuseTextureSampler.addressModeV=v.REPEAT}get state(){return this.#Np}get loop(){return this.#Gp}set loop(i){this.#Gp=i}get frameRate(){return this.#Ap}set frameRate(i){i<0&&(i=0),0===this.#Ap&&i&&(this.#Lp=0),this.#Ap=i,this.#Up=1e3/this.#Ap}get geometry(){return this._geometry}set geometry(i){consoleAndThrowError("ASpriteSheet can not change geometry")}get material(){return this._material}set material(i){consoleAndThrowError("ASpriteSheet can not change material")}get spriteSheetInfo(){return this.#Op}set spriteSheetInfo(i){this.#Op=i,this.frameRate=i.frameRate,this.segmentW=i.segmentW,this.segmentH=i.segmentH,this.totalFrame=i.totalFrame,this.currentIndex=i.startIndex,this.#Gp=!0,this.#Lp=0,this._material.diffuseTexture=i.texture}play(){this.#kp=!0,this.#Np="play",this.#Lp=0}pause(){this.#kp=!1,this.#Np="pause"}stop(){this.#kp=!1,this.currentIndex=0,this.#Np="stop"}render(i){const{diffuseTexture:g}=this._material;this.#Vp(g,this.segmentW,this.segmentH);const{timestamp:x}=i;if(this.#Lp||(this.#Lp=this.#Up+x),this.#kp&&this.#Lp=this.totalFrame&&(this.loop?(this.#kp=!0,this.currentIndex=0):(this.#kp=!1,this.currentIndex=this.totalFrame-1))}super.render(i)}}definePositiveNumber(ASpriteSheet,[{key:"segmentW",value:5},{key:"segmentH",value:3},{key:"totalFrame",value:15},{key:"currentIndex",value:0}]),Object.freeze(ASpriteSheet);var as=Object.freeze({__proto__:null,ASpriteSheet:ASpriteSheet}),ss="#redgpu_include SYSTEM_UNIFORM;struct MatrixList{modelMatrix:mat4x4,normalModelMatrix:mat4x4,}struct VertexUniforms{matrixList:MatrixList,pickingId:u32,segmentW:f32,segmentH:f32,totalFrame:f32,currentIndex:f32,combinedOpacity:f32,};@group(1)@binding(0)varvertexUniforms:VertexUniforms;struct InputData{@location(0)position:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,};struct VertexOutput{@builtin(position)position:vec4,@location(0)vertexPosition:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,@location(7)currentClipPos:vec4,@location(8)prevClipPos:vec4,@location(11)combinedOpacity:f32,@location(12)motionVector:vec3,@location(13)shadowCoord:vec3,@location(15)@interpolate(flat)pickingId:vec4,};@vertex fn main(inputData:InputData)->VertexOutput{var output:VertexOutput;let u_projectionMatrix=systemUniforms.projection.projectionMatrix;let u_camera=systemUniforms.camera;let u_viewMatrix=u_camera.viewMatrix;let u_modelMatrix=vertexUniforms.matrixList.modelMatrix;let u_normalModelMatrix=vertexUniforms.matrixList.normalModelMatrix;let input_position=inputData.position;let input_vertexNormal=inputData.vertexNormal;let input_uv=inputData.uv;let viewPos=u_viewMatrix*u_modelMatrix*vec4(input_position,1.0);let viewNormal=u_viewMatrix*u_normalModelMatrix*vec4(input_vertexNormal,.0);output.position=u_projectionMatrix*viewPos;output.vertexPosition=viewPos.xyz;output.vertexNormal=viewNormal.xyz;output.combinedOpacity=vertexUniforms.combinedOpacity;let uv=vec2(input_uv.x*(1.0/vertexUniforms.segmentW)+((vertexUniforms.currentIndex % vertexUniforms.segmentW)/vertexUniforms.segmentW),input_uv.y*(1.0/vertexUniforms.segmentH)-(floor(vertexUniforms.currentIndex/vertexUniforms.segmentH)/vertexUniforms.segmentH));output.uv=uv;return output;}@vertex fn entryPointPickingVertex(inputData:InputData)->VertexOutput{var output:VertexOutput;let u_projectionMatrix=systemUniforms.projection.projectionMatrix;let u_viewMatrix=systemUniforms.camera.viewMatrix;let u_modelMatrix=vertexUniforms.matrixList.modelMatrix;let viewPos=u_viewMatrix*u_modelMatrix*vec4(inputData.position,1.0);output.position=u_projectionMatrix*viewPos;output.pickingId=unpack4x8unorm(vertexUniforms.pickingId);return output;}";const os=parseWGSL("SPRITE_SHEET_2D_VERTEX",ss),us=os.uniforms.vertexUniforms,ls=mixInMesh2D(ASpriteSheet);class SpriteSheet2D extends ls{#Gt=1;#Ot=1;constructor(i,g){super(i,g,(i,g,x)=>{if(i){const{gpuTexture:v}=i,_=v?.width/g,y=v?.height/x;_===this.#Gt&&y===this.#Ot||(this.#Gt=v?.width/g,this.#Ot=v?.height/x,this.dirtyTransform=!0)}else this.#Gt=1,this.#Ot=1}),this._geometry=new Plane(i,1,1,1,1,!0),this.primitiveState.cullMode=Ji.FRONT}get width(){return this.#Gt}get height(){return this.#Ot}get geometry(){return this._geometry}set geometry(i){consoleAndThrowError("SpriteSheet2D can not change geometry")}get material(){return this._material}set material(i){consoleAndThrowError("SpriteSheet2D can not change material")}createCustomMeshVertexShaderModule=()=>this.createMeshVertexShaderModuleBASIC("VERTEX_MODULE_SPRITE_SHEET_2D",os,us,ss)}Object.freeze(SpriteSheet2D);var cs="#redgpu_include SYSTEM_UNIFORM;#redgpu_include math.billboard.getBillboardMatrix;#redgpu_include math.billboard.getBillboardResult;#redgpu_include entryPoint.billboard.entryPointPickingVertex;#redgpu_include entryPoint.empty.entryPointShadowVertex;struct MatrixList{modelMatrix:mat4x4,normalModelMatrix:mat4x4,}struct VertexUniforms{matrixList:MatrixList,pickingId:u32,useSizeAttenuation:u32,useBillboard:u32,segmentW:f32,segmentH:f32,totalFrame:f32,currentIndex:f32,usePixelSize:u32,pixelSize:f32,_renderRatioX:f32,_renderRatioY:f32,combinedOpacity:f32,};@group(1)@binding(0)varvertexUniforms:VertexUniforms;struct InputData{@location(0)position:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,};struct VertexOutput{@builtin(position)position:vec4,@location(0)vertexPosition:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,@location(7)currentClipPos:vec4,@location(8)prevClipPos:vec4,@location(11)combinedOpacity:f32,@location(12)motionVector:vec3,@location(13)shadowCoord:vec3,@location(15)@interpolate(flat)pickingId:vec4,};@vertex fn main(inputData:InputData)->VertexOutput{var output:VertexOutput;let billboardResult=getBillboardResult(inputData.position,inputData.vertexNormal,vertexUniforms.matrixList.modelMatrix,systemUniforms.camera.viewMatrix,systemUniforms.projection.projectionMatrix,systemUniforms.resolution,vertexUniforms.useBillboard,vertexUniforms.usePixelSize,vertexUniforms.pixelSize,vertexUniforms._renderRatioX,vertexUniforms._renderRatioY);output.position=billboardResult.position;output.vertexPosition=billboardResult.vertexPosition;output.vertexNormal=billboardResult.vertexNormal;output.uv=vec2(inputData.uv.x/vertexUniforms.segmentW+((vertexUniforms.currentIndex % vertexUniforms.segmentW)/vertexUniforms.segmentW),inputData.uv.y/vertexUniforms.segmentH-(floor(vertexUniforms.currentIndex/vertexUniforms.segmentH)/vertexUniforms.segmentH));output.combinedOpacity=vertexUniforms.combinedOpacity;return output;}";const hs=parseWGSL("SPRITE_SHEET_3D_VERTEX",cs),fs=hs.uniforms.vertexUniforms;class SpriteSheet3D extends ASpriteSheet{#Wo=1;#Zo=1;#Jo=1;#Ip=0;#Qo=!1;constructor(i,g){super(i,g,(i,g,x)=>{if(i){const{gpuTexture:v}=i;if(v){const i=v.width/g,_=v.height/x;i===this.#Wo&&_===this.#Zo||(this.#Wo=i,this.#Zo=_,this.pixelSize=this.#Ip?this.#Ip:_,this.#eu(),this.dirtyTransform=!0)}}else this.#Wo=1,this.#Zo=1}),this._geometry=new Plane(i)}get worldSize(){return this.#Jo}set worldSize(i){this.#Jo!==i&&(this.#Jo=i,this.#eu())}get pixelSize(){return this.#Ip}set pixelSize(i){if(this.gpuRenderInfo){const{vertexUniformBuffer:g,vertexUniformInfo:x}=this.gpuRenderInfo;this.redGPUContext.gpuDevice.queue.writeBuffer(g.gpuBuffer,x.members.pixelSize.uniformOffset,new Float32Array([i*window.devicePixelRatio]))}this.#Ip=i}get usePixelSize(){return this.#Qo}set usePixelSize(i){if(this.gpuRenderInfo){const{vertexUniformBuffer:g,vertexUniformInfo:x}=this.gpuRenderInfo;this.redGPUContext.gpuDevice.queue.writeBuffer(g.gpuBuffer,x.members.usePixelSize.uniformOffset,new Uint32Array([i?1:0]))}this.#Qo!==i&&(this.#Qo=i,this.#eu())}get geometry(){return this._geometry}set geometry(i){consoleAndThrowError("SpriteSheet3D can not change geometry")}get material(){return this._material}set material(i){consoleAndThrowError("SpriteSheet3D can not change material")}render(i){super.render(i)}createCustomMeshVertexShaderModule=()=>this.createMeshVertexShaderModuleBASIC("VERTEX_MODULE_SPRITE_SHEET_3D",hs,fs,cs);#eu(){if(this.#Zo){const i=this._renderRatioX,g=this._renderRatioY;this.usePixelSize?(this._renderRatioY=1,this._renderRatioX=this.#Wo/this.#Zo):(this._renderRatioY=this.#Jo,this._renderRatioX=this.#Wo/this.#Zo*this.#Jo),i===this._renderRatioX&&g===this._renderRatioY||(this.dirtyTransform=!0)}}}definePositiveNumber(SpriteSheet3D,[{key:"_renderRatioX",value:1},{key:"_renderRatioY",value:1}]),defineBoolean(SpriteSheet3D,[{key:"useBillboard",value:!0}]),Object.freeze(SpriteSheet3D);class SpriteSheetInfo{#Fp=0;#Hp=0;#zp=0;#$p=0;#Ap=0;#Gp=!0;#Od;constructor(i,g,x,v,_,y,b=!0,S=60){validateRedGPUContext(i),validateUintRange(x),validateUintRange(v),validateUintRange(_),validateUintRange(y),validateUintRange(S),this.#Fp=x,this.#Hp=v,this.#zp=_,this.#$p=y,this.#Od=new BitmapTexture(i,g),this.#Gp=b,this.#Ap=S}get segmentW(){return this.#Fp}get segmentH(){return this.#Hp}get totalFrame(){return this.#zp}get startIndex(){return this.#$p}get texture(){return this.#Od}get frameRate(){return this.#Ap}get loop(){return this.#Gp}}Object.freeze(SpriteSheetInfo);const ds=parseWGSL("LINE_MATERIAL","#redgpu_include SYSTEM_UNIFORM;#redgpu_include entryPoint.mesh.entryPointPickingFragment;#redgpu_include systemStruct.OutputFragment;#redgpu_include math.getMotionVector;struct Uniforms{opacity:f32,};struct InputData{@builtin(position)position:vec4,@location(0)vertexPosition:vec3,@location(1)vertexColor:vec4,@location(7)currentClipPos:vec4,@location(8)prevClipPos:vec4,@location(15)@interpolate(flat)pickingId:vec4,}@group(2)@binding(0)varuniforms:Uniforms;@fragment fn main(inputData:InputData)->OutputFragment{var output:OutputFragment;var finalColor=inputData.vertexColor;finalColor.a=finalColor.a*uniforms.opacity;output.color=vec4(finalColor.rgb,finalColor.a);output.gBufferNormal=vec4(.0,.0,.0,.0);output.gBufferMotionVector=vec4(getMotionVector(inputData.currentClipPos,inputData.prevClipPos),.0,1.0);return output;}");class LineMaterial extends ABaseMaterial{constructor(i,g){super(i,"LINE_MATERIAL",ds,2),g&&(this.name=g),this.initGPURenderInfos()}}Object.freeze(LineMaterial);class LinePoint{position;colorRGBA;constructor(i=0,g=0,x=0,v){this.position=[i,g,x],this.colorRGBA=v}}const getPointsOnBezierCurveWithSplitting=(i,g,x,v)=>{let _=v||[];if(((i,g)=>{let x=i[g].position,v=i[g+1].position,_=i[g+2].position,y=i[g+3].position,b=3*v[0]-2*x[0]-y[0],S=3*v[1]-2*x[1]-y[1],w=3*_[0]-2*y[0]-x[0],L=3*_[1]-2*y[1]-x[1];return b*=b,S*=S,w*=w,L*=L,b{let y=_||[],b=i[g],S=i[x-1],w=0,L=1,k=g+1;for(;kw&&(w=g,L=k)}return Math.sqrt(w)>v?(lineSimplifyPoints(i,g,L+1,v,y),lineSimplifyPoints(i,L,x,v,y)):y.push(b,S),y},ms={LINEAR:"linear",CATMULL_ROM:"catmullRom",BEZIER:"bezier"};Object.freeze(ms);var ps="#redgpu_include SYSTEM_UNIFORM;struct MatrixList{modelMatrix:mat4x4,prevModelMatrix:mat4x4,normalModelMatrix:mat4x4,}struct VertexUniforms{matrixList:MatrixList,pickingId:u32,};@group(1)@binding(0)varvertexUniforms:VertexUniforms;struct InputData{@location(0)position:vec3,@location(1)vertexColor:vec4,};struct VertexOutput{@builtin(position)position:vec4,@location(0)vertexPosition:vec3,@location(1)vertexColor:vec4,@location(7)currentClipPos:vec4,@location(8)prevClipPos:vec4,@location(15)@interpolate(flat)pickingId:vec4,};@vertex fn main(inputData:InputData)->VertexOutput{var output:VertexOutput;let u_projectionViewMatrix=systemUniforms.projection.projectionViewMatrix;let u_noneJitterProjectionViewMatrix=systemUniforms.projection.noneJitterProjectionViewMatrix;let u_prevNoneJitterProjectionViewMatrix=systemUniforms.projection.prevNoneJitterProjectionViewMatrix;let u_matrixList=vertexUniforms.matrixList;let u_modelMatrix=u_matrixList.modelMatrix;let u_prevModelMatrix=u_matrixList.prevModelMatrix;let input_position=inputData.position;let input_vertexColor=inputData.vertexColor;let input_position_vec4=vec4(input_position,1.0);var position:vec4;position=u_modelMatrix*input_position_vec4;output.position=u_projectionViewMatrix*position;output.vertexPosition=position.xyz;output.vertexColor=input_vertexColor;{output.currentClipPos=u_noneJitterProjectionViewMatrix*position;output.prevClipPos=u_prevNoneJitterProjectionViewMatrix*u_prevModelMatrix*input_position_vec4;}return output;}#redgpu_include entryPoint.empty.entryPointPickingVertex;#redgpu_include entryPoint.empty.entryPointShadowVertex;";const gs=parseWGSL("LINE3D_VERTEX",ps),xs=gs.uniforms.vertexUniforms;class Line3D extends Mesh{baseColor;#jp;#Kp=1;#Xp=.01;#Qf=.01;#qp=[];#Yp=[];#Wp;constructor(i,g=ms.LINEAR,x="#fff"){super(i),this.primitiveState.topology=Ei.LINE_STRIP,this.baseColor=x,this.#jp=g,this._geometry=new Geometry(i,new VertexBuffer(i,this.#qp,new VertexInterleavedStruct({vertexPosition:VertexInterleaveType.float32x3,vertexColor:VertexInterleaveType.float32x4}))),this._material=new LineMaterial(i)}get originalPoints(){return this.#Yp}get type(){return this.#jp}set type(i){this.#jp=i,this.#Zp()}get interleaveData(){return this.#qp}get tension(){return this.#Kp}set tension(i){validatePositiveNumberRange(i),this.#Kp=i,this.#Zp()}get tolerance(){return this.#Xp}set tolerance(i){validatePositiveNumberRange(i),this.#Xp=i,this.#Zp()}get distance(){return this.#Qf}set distance(i){validatePositiveNumberRange(i),this.#Qf=i,this.#Zp()}get numPoints(){return this.#Yp.length}get geometry(){return this._geometry}set geometry(i){consoleAndThrowError("Line3D can not change geometry")}get material(){return this._material}set material(i){consoleAndThrowError("Line3D can not change material")}createCustomMeshVertexShaderModule=()=>this.createMeshVertexShaderModuleBASIC("VERTEX_MODULE_LINE_3D",gs,xs,ps);addPoint(i=0,g=0,x=0,v=this.baseColor,_=1,y=0,b=0,S=0,w=0,L=0,k=0){this.#Yp.push(new LinePointWithInOut(i,g,x,y,b,S,w,L,k,v,_)),this.#Zp()}addPointAt(i,g=0,x=0,v=0,_=this.baseColor,y=1,b=0,S=0,w=0,L=0,k=0,H=0){this.#Yp.length1)for(this.#Wp=(i=>{let g,x=[],v=0,_=0;const y=i.length;for(;v{const x=i.length,v=x-2;for(let _=0;_{let x=[],v=(i.length-1)/3;v=Math.floor(v);let _,y=0;for(;y,normalModelMatrix:mat4x4,}struct VertexUniforms{pickingId:u32,matrixList:MatrixList,combinedOpacity:f32,};@group(1)@binding(0)varvertexUniforms:VertexUniforms;struct InputData{@location(0)position:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,};struct VertexOutput{@builtin(position)position:vec4,@location(0)vertexPosition:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,@location(11)combinedOpacity:f32,@location(13)shadowCoord:vec3,@location(15)@interpolate(flat)pickingId:vec4,};#redgpu_include systemStruct.OutputShadowData;@vertex fn main(inputData:InputData)->VertexOutput{var output:VertexOutput;let u_projectionMatrix=systemUniforms.projection.projectionMatrix;let u_viewMatrix=systemUniforms.camera.viewMatrix;let u_modelMatrix=vertexUniforms.matrixList.modelMatrix;let u_normalModelMatrix=vertexUniforms.matrixList.normalModelMatrix;let input_position=inputData.position;let input_vertexNormal=inputData.vertexNormal;let input_uv=inputData.uv;let viewPos=u_viewMatrix*u_modelMatrix*vec4(input_position,1.0);let viewNormal=u_viewMatrix*u_normalModelMatrix*vec4(input_vertexNormal,.0);output.position=u_projectionMatrix*viewPos;output.vertexPosition=viewPos.xyz;output.vertexNormal=viewNormal.xyz;output.uv=input_uv;output.combinedOpacity=vertexUniforms.combinedOpacity;return output;}@vertex fn entryPointPickingVertex(inputData:InputData)->VertexOutput{var output:VertexOutput;let u_projectionMatrix=systemUniforms.projection.projectionMatrix;let u_viewMatrix=systemUniforms.camera.viewMatrix;let u_modelMatrix=vertexUniforms.matrixList.modelMatrix;let viewPos=u_viewMatrix*u_modelMatrix*vec4(inputData.position,1.0);output.position=u_projectionMatrix*viewPos;output.pickingId=unpack4x8unorm(vertexUniforms.pickingId);return output;}";const Ss=parseWGSL("TEXTFIELD2D_VERTEX",bs),Ts=Ss.uniforms.vertexUniforms,ws=mixInMesh2D(ATextField);class TextField2D extends ws{#Gt=1;#Ot=1;#Jp=!0;constructor(i,g=!0){super(i,(i,g)=>{this.#Gt===i&&this.#Ot===g||(this.dirtyTransform=!0),this.#Gt=i,this.#Ot=g},!1),this._geometry=new Plane(i,1,1,1,1,!0),this.useSmoothing=g,this.primitiveState.cullMode=Ji.FRONT}get useSmoothing(){return this.#Jp}set useSmoothing(i){this.#Jp=i;const{diffuseTextureSampler:g}=this._material;this.useSmoothing?(g.minFilter=_.LINEAR,g.magFilter=_.LINEAR,g.mipmapFilter=y.LINEAR):(g.minFilter=_.NEAREST,g.magFilter=_.NEAREST,g.mipmapFilter=null)}get width(){return this.#Gt}get height(){return this.#Ot}get geometry(){return this._geometry}set geometry(i){console.error("TextField2D can not change geometry")}get material(){return this._material}set material(i){console.error("TextField2D can not change material")}createCustomMeshVertexShaderModule=()=>this.createMeshVertexShaderModuleBASIC("VERTEX_MODULE_TEXT_FIELD_2D",Ss,Ts,bs)}Object.freeze(TextField2D);const Ms=3.141592653589793,Ps=6.283185307179586,Rs=.225,Cs=1.27323954,Bs=.405284735,Ds=1.5707963267948966,Es=Math.PI/180;class InstancingMeshObject3D{modelMatrix=create$4();localMatrix=create$4();normalModelMatrix=create$4();#wi=0;#Pi=0;#Mi=0;#hs=[0,0,0];#gs=1;#xs=1;#vs=1;#_s=[1,1,1];#ys=0;#bs=0;#Ss=0;#Ts=[0,0,0];#Qp=0;#eg;#h;#Rs=1;constructor(i,g,x){validateRedGPUContext(i),this.#h=i,this.#eg=x,this.#Qp=g,this.#tg()}get opacity(){return this.#Rs}set opacity(i){validatePositiveNumberRange(i,0,1),this.#Rs=i,this.#tg()}get x(){return this.#wi}set x(i){this.#wi=this.#hs[0]=i,this.#tg()}get y(){return this.#Mi}set y(i){this.#Mi=this.#hs[1]=i,this.#tg()}get z(){return this.#Pi}set z(i){this.#Pi=this.#hs[2]=i,this.#tg()}get position(){return this.#hs}set position(i){this.#wi=this.#hs[0]=i,this.#Mi=this.#hs[1]=i,this.#Pi=this.#hs[2]=i,this.#tg()}get scaleX(){return this.#gs}set scaleX(i){this.#gs=this.#_s[0]=i,this.#tg()}get scaleY(){return this.#xs}set scaleY(i){this.#xs=this.#_s[1]=i,this.#tg()}get scaleZ(){return this.#vs}set scaleZ(i){this.#vs=this.#_s[2]=i,this.#tg()}get scale(){return this.#_s}set scale(i){this.#gs=this.#_s[0]=i,this.#xs=this.#_s[1]=i,this.#vs=this.#_s[2]=i,this.#tg()}get rotationX(){return this.#ys}set rotationX(i){this.#ys=this.#Ts[0]=i,this.#tg()}get rotationY(){return this.#bs}set rotationY(i){this.#bs=this.#Ts[1]=i,this.#tg()}get rotationZ(){return this.#Ss}set rotationZ(i){this.#Ss=this.#Ts[2]=i,this.#tg()}get rotation(){return this.#Ts}set rotation(i){this.#ys=this.#Ts[0]=i,this.#bs=this.#Ts[1]=i,this.#Ss=this.#Ts[2]=i,this.#tg()}setScale(i,g,x){g=g??i,x=x??i;const v=this.#_s;this.#gs=v[0]=i,this.#xs=v[1]=g,this.#vs=v[2]=x,this.#tg()}setPosition(i,g,x){g=g??i,x=x??i;const v=this.#hs;this.#wi=v[0]=i,this.#Mi=v[1]=g,this.#Pi=v[2]=x,this.#tg()}setRotation(i,g,x){g=g??i,x=x??i;const v=this.#Ts;this.#ys=v[0]=i,this.#bs=v[1]=g,this.#Ss=v[2]=x,this.#tg()}#tg(){let i,g,x,v,_,y,b,S,w,L,k,H,z,q,W,be,je,Ke,Xe,Ye,Ze,Je,Qe,et,tt,it,ft,pt,xt,vt,yt,bt,St,Tt,wt,Mt,Pt,Rt;{const z=this.localMatrix;let je;L=1,k=0,H=0,q=0,W=1,be=0,Ke=0,Xe=0,Ye=1,z[12]=this.#wi,z[13]=this.#Mi,z[14]=this.#Pi,z[15]=1,b=this.#ys*Es,S=this.#bs*Es,w=this.#Ss*Es,je=b%Ps,je<-Ms?je+=Ps:je>Ms&&(je-=Ps),je=je<0?Cs*je+Bs*je*je:Cs*je-Bs*je*je,i=je<0?Rs*(je*-je-je)+je:Rs*(je*je-je)+je,je=(b+Ds)%Ps,je<-Ms?je+=Ps:je>Ms&&(je-=Ps),je=je<0?Cs*je+Bs*je*je:Cs*je-Bs*je*je,v=je<0?Rs*(je*-je-je)+je:Rs*(je*je-je)+je,je=S%Ps,je<-Ms?je+=Ps:je>Ms&&(je-=Ps),je=je<0?Cs*je+Bs*je*je:Cs*je-Bs*je*je,g=je<0?Rs*(je*-je-je)+je:Rs*(je*je-je)+je,je=(S+Ds)%Ps,je<-Ms?je+=Ps:je>Ms&&(je-=Ps),je=je<0?Cs*je+Bs*je*je:Cs*je-Bs*je*je,_=je<0?Rs*(je*-je-je)+je:Rs*(je*je-je)+je,je=w%Ps,je<-Ms?je+=Ps:je>Ms&&(je-=Ps),je=je<0?Cs*je+Bs*je*je:Cs*je-Bs*je*je,x=je<0?Rs*(je*-je-je)+je:Rs*(je*je-je)+je,je=(w+Ds)%Ps,je<-Ms?je+=Ps:je>Ms&&(je-=Ps),je=je<0?Cs*je+Bs*je*je:Cs*je-Bs*je*je,y=je<0?Rs*(je*-je-je)+je:Rs*(je*je-je)+je,vt=_*y,yt=v*x+i*g*y,bt=i*x-v*g*y,St=-_*x,Tt=v*y-i*g*x,wt=i*y+v*g*x,Mt=g,Pt=-i*_,Rt=v*_;let Ze=this.#gs,Je=this.#xs,Qe=this.#vs;z[0]=vt*Ze,z[1]=yt*Ze,z[2]=bt*Ze,z[3]=0,z[4]=St*Je,z[5]=Tt*Je,z[6]=wt*Je,z[7]=0,z[8]=Mt*Qe,z[9]=Pt*Qe,z[10]=Rt*Qe,z[11]=0}this.modelMatrix=this.localMatrix;{let i=this.normalModelMatrix,g=this.modelMatrix;L=g[0],k=g[1],H=g[2],z=g[3],q=g[4],W=g[5],be=g[6],je=g[7],Ke=g[8],Xe=g[9],Ye=g[10],Ze=g[11],Qe=g[12],et=g[13],tt=g[14],it=g[15],Je=L*W-k*q,ft=L*be-H*q,pt=L*je-z*q,xt=k*be-H*W,vt=k*je-z*W,yt=H*je-z*be,bt=Ke*et-Xe*Qe,St=Ke*tt-Ye*Qe,Tt=Ke*it-Ze*Qe,Mt=Xe*it-Ze*et,wt=Ye*it-Ze*tt,Rt=Je*wt-ft*Mt+pt*wt+xt*Tt-vt*St+yt*bt,Rt=1/Rt,i[0]=(W*wt-be*Mt+je*wt)*Rt,i[4]=(-k*wt+H*Mt-z*wt)*Rt,i[8]=(et*yt-tt*vt+it*xt)*Rt,i[12]=(-Xe*yt+Ye*vt-Ze*xt)*Rt,i[1]=(-q*wt+be*Tt-je*St)*Rt,i[5]=(L*wt-H*Tt+z*St)*Rt,i[9]=(-Qe*yt+tt*pt-it*ft)*Rt,i[13]=(Ke*yt-Ye*pt+Ze*ft)*Rt,i[2]=(q*Mt-W*Tt+je*bt)*Rt,i[6]=(-L*Mt+k*Tt-z*bt)*Rt,i[10]=(Qe*vt-et*pt+it*Je)*Rt,i[14]=(-Ke*vt+Xe*pt-Ze*Je)*Rt,i[3]=(-q*wt+W*St-be*bt)*Rt,i[7]=(L*wt-k*St+H*bt)*Rt,i[11]=(-Qe*xt+et*ft-tt*Je)*Rt,i[15]=(Ke*xt-Xe*ft+Ye*Je)*Rt}if(this.#eg.gpuRenderInfo){const{vertexUniformBuffer:i,vertexUniformInfo:g}=this.#eg.gpuRenderInfo,{dataViewF32:x}=i,{members:v}=g,_=v.instanceModelMatrixs,y=v.instanceNormalModelMatrix,b=v.instanceOpacity;x.set(this.modelMatrix,(_.uniformOffset+_.stride*this.#Qp)/4),x.set(this.normalModelMatrix,(y.uniformOffset+y.stride*this.#Qp)/4),x.set([this.opacity],(b.uniformOffset+b.stride*this.#Qp)/4),this.#eg.dirtyInstanceMeshObject3D=!0}}}Object.freeze(InstancingMeshObject3D);var Is=Object.freeze({__proto__:null,instancingMeshObject3D:InstancingMeshObject3D}),As="struct VertexOutput{@builtin(position)position:vec4,@location(0)vertexPosition:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,@location(3)uv1:vec2,@location(4)vertexColor_0:vec4,@location(5)vertexTangent:vec4,@location(7)currentClipPos:vec4,@location(8)prevClipPos:vec4,@location(10)localNodeScale_volumeScale:vec2,@location(11)instanceOpacity:f32,@location(12)motionVector:vec3,@location(13)shadowCoord:vec3,@location(14)@interpolate(flat)receiveShadow:f32,@location(15)@interpolate(flat)pickingId:vec4,};";const Ls="VERTEX_MODULE_INSTANCING";class InstancingMesh extends Mesh{dirtyInstanceMeshObject3D=!0;dirtyInstanceNum=!0;#ls;#h;#rg=1;#ig=1;#ng=[];#$s;#ag;#sg;#og;#ug;#lg;#cg=0;#hg=0;#fg;#Ks=[];constructor(i,g,x,v,_){super(i,v,_),this.#h=i;const y=InstancingMesh.getLimitSize(this.#h);this.#ig=Math.min(g,y),this.#rg=Math.min(x,this.#ig),this.#N(),this.gpuRenderInfo.vertexUniformInfo=parseWGSL(`INSTANCING_MESH_VERTEX_${this.#ig}`,this.#dg(this.geometry,this.material)).storage.instanceUniforms,this.#mg(),this.#pg(),this.#jd(this.#h),this.instanceCount=this.#rg}get instanceCount(){return this.#rg}set instanceCount(i){validateUintRange(i),this.#rg=Math.min(i,this.#ig),this.#ng.length>this.#rg&&(this.#ng.length=this.#rg);let g=this.#rg;for(;g--;)this.#ng[g]||(this.#ng[g]=new InstancingMeshObject3D(this.#h,g,this));this.dirtyInstanceNum=!0}get maxInstanceCount(){return this.#ig}get instanceChildren(){return this.#ng}static getLimitSize(i){const g=Math.min(i.detector.activeLimits.maxStorageBufferBindingSize,536870912);return Math.floor((g-144)/132)}render(i,g=!1){if(this.dirtyLOD)return this.#pg(),this.#jd(this.#h),this.dirtyInstanceNum=!0,void(this.dirtyLOD=!1);const{view:x,currentRenderPassEncoder:v,renderResults:_}=i,{scene:y}=x,{shadowManager:b}=y,{directionalShadowManager:S}=b,{castingList:w}=S;this.dirtyTransform&&this.#gg(),this.geometry?_.num3DObjects++:_.num3DGroups++;const L=this.#h;if(this.geometry){const{antialiasingManager:x}=L;this.#ls!==x.msaaID&&(this.dirtyPipeline=!0,this.#ls=x.msaaID),this.gpuRenderInfo||this.#jd(L);(this.dirtyPipeline||this.material.dirtyPipeline)&&this.#xg(i),g||this.#vg(i),this.#_g(i,g,v)}this.castShadow&&(w[w.length]=this);const{children:k}=this;let H=k.length;for(;H--;)k[H].dirtyTransform=this.dirtyTransform,k[H].render(i);this.dirtyTransform=!1}#gg(){identity$1(this.localMatrix),translate(this.localMatrix,this.localMatrix,[this.x,this.y,this.z]),rotateX$2(this.localMatrix,this.localMatrix,this.rotationX),rotateY$2(this.localMatrix,this.localMatrix,this.rotationY),rotateZ$2(this.localMatrix,this.localMatrix,this.rotationZ),scale$4(this.localMatrix,this.localMatrix,[this.scaleX,this.scaleY,this.scaleZ]);const i=this.parent;i?.modelMatrix?multiply$4(this.modelMatrix,i.modelMatrix,this.localMatrix):this.modelMatrix=clone$4(this.localMatrix)}#xg(i){this.dirtyTransform=!0,this.material.dirtyPipeline&&this.material._updateFragmentState(),this.#yg(),this.material.dirtyPipeline=!1,this.dirtyPipeline=!1,i.renderResults.numDirtyPipelines++}#_g(i,g,x){const{gpuRenderInfo:v}=this,{pipeline:_,shadowPipeline:y}=v,{view:b,renderResults:S}=i;this.#bg(),this.#Sg();const{fragmentUniformBindGroup:w}=this.material.gpuRenderInfo;x.setBindGroup(0,b.systemUniform_Vertex_UniformBindGroup),x.setBindGroup(2,w),x.setPipeline(g?y:_);this.#Tg(x,this.geometry,this.gpuRenderInfo.vertexUniformBindGroup,this.material.gpuRenderInfo.fragmentUniformBindGroup,0,20),this.LODManager.LODList.forEach((i,g)=>{const v=this.#Ks[g];x.setPipeline(v.pipeline),this.#Tg(x,i.geometry,v.vertexUniformBindGroup,i.material?i.material.gpuRenderInfo.fragmentUniformBindGroup:this.material.gpuRenderInfo.fragmentUniformBindGroup,g+1,20)}),S.numDrawCalls++,S.numInstances++}#Tg(i,g,x,v,_,y){const{vertexBuffer:b,indexBuffer:S}=g,w=y*_;if(i.setBindGroup(1,x),i.setBindGroup(2,v),i.setVertexBuffer(0,b.gpuBuffer),S){const{gpuBuffer:g,format:x}=S;i.setIndexBuffer(g,x),i.drawIndexedIndirect(this.#fg,w)}else i.drawIndirect(this.#fg,w)}#bg(){const{vertexUniformBuffer:i,vertexUniformInfo:g}=this.gpuRenderInfo,{displacementTexture:x,displacementScale:v}=this.material||{},{members:_}=g;void 0!==_.displacementScale&&this.#$s!==v&&(this.#$s=v,i.dataViewF32.set(new _.displacementScale.View([v]),_.displacementScale.uniformOffset/4)),void 0!==_.useDisplacementTexture&&this.#ag!==!!x&&(this.#ag=!!x,i.dataViewF32.set(new _.useDisplacementTexture.View([x?1:0]),_.useDisplacementTexture.uniformOffset/4))}#Sg(){const{vertexUniformBuffer:i,vertexUniformInfo:g}=this.gpuRenderInfo,{gpuDevice:x}=this.#h,{members:v}=g;if(this.dirtyTransform){i.dataViewF32.set(this.modelMatrix,v.instanceGroupModelMatrix.uniformOffset/4);const g=create$4();invert$1(g,this.modelMatrix),transpose(g,g),i.dataViewF32.set(g,v.instanceGroupNormalModelMatrix.uniformOffset/4),x.queue.writeBuffer(i.gpuBuffer,v.instanceGroupModelMatrix.uniformOffset,new v.instanceGroupModelMatrix.View(this.modelMatrix)),x.queue.writeBuffer(i.gpuBuffer,v.instanceGroupNormalModelMatrix.uniformOffset,new v.instanceGroupNormalModelMatrix.View(g))}(this.dirtyInstanceMeshObject3D||this.dirtyInstanceNum)&&(x.queue.writeBuffer(i.gpuBuffer,0,i.data),this.dirtyInstanceMeshObject3D=!1,this.dirtyInstanceNum=!1)}#N(){const{gpuDevice:i}=this.#h;this.gpuRenderInfo=new VertexGPURenderInfo(null,null,null,null,null,null,null,null);this.#fg=i.createBuffer({size:160,usage:GPUBufferUsage.INDIRECT|GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST,label:`IndirectDrawBuffer_${this.uuid}`});const g=new Float32Array(40);this.#ug=new StorageBuffer(this.#h,g.buffer,`CullingUniformBuffer_${this.uuid}`)}#jd(i){this.dirtyPipeline=!0;const g=new ArrayBuffer(this.#cg*(this.LODManager.LODList.length+1));this.#lg?.destroy(),this.#lg=new StorageBuffer(i,g,`VisibilityBuffer_${this.uuid}`),this.#yg(),this.#wg(this.#h)}#wg(i){const{gpuDevice:g,resourceManager:x}=i,v={code:this.#Mg()},_=x.createGPUShaderModule(`CULLING_COMPUTE_MODULE_INSTANCING_${this.#ig}_${this.uuid}`,v),y=g.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"read-only-storage"}},{binding:1,visibility:GPUShaderStage.COMPUTE,buffer:{type:"read-only-storage"}},{binding:2,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}},{binding:3,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}}]});this.#sg=g.createComputePipeline({layout:g.createPipelineLayout({bindGroupLayouts:[y]}),compute:{module:_,entryPoint:"main"}}),this.#og=g.createBindGroup({layout:y,entries:[{binding:0,resource:{buffer:this.gpuRenderInfo.vertexUniformBuffer.gpuBuffer}},{binding:1,resource:{buffer:this.#ug.gpuBuffer}},{binding:2,resource:{buffer:this.#lg.gpuBuffer}},{binding:3,resource:{buffer:this.#fg}}]})}#Pg(i){const{view:g}=i,{gpuDevice:x}=this.#h,{data:v,dataViewU32:_,dataViewF32:y}=this.#ug;_.set([this.#rg],0),_.set([this.#hg],1),_.set([this.LODManager.LODList.length],2),y.set(g.rawCamera.position,4),y.set(g.frustumPlanes.flat(),8),y.set([...this.LODManager.LODList.map(i=>i.distance)],32),x.queue.writeBuffer(this.#ug.gpuBuffer,0,v)}#vg(i){const{gpuDevice:g,commandEncoderManager:x}=this.#h,{indexBuffer:v,vertexBuffer:_}=this.geometry;this.#Pg(i);const y=v?v.indexCount:_.vertexCount,b=new Uint32Array([y,0,0,0,0]);g.queue.writeBuffer(this.#fg,0,b),this.LODManager.LODList.forEach((i,x)=>{const v=i.geometry.indexBuffer.indexCount,_=new Uint32Array([v,0,0,0,0]),y=20*(x+1);g.queue.writeBuffer(this.#fg,y,_)}),x.addPreProcessComputePass("InstancingMesh_GPUCulling_ComputePass",i=>{i.setPipeline(this.#sg),i.setBindGroup(0,this.#og);const g=Math.ceil(this.#rg/64);i.dispatchWorkgroups(g)})}#yg(){const{resourceManager:i,gpuDevice:g}=this.#h,x={code:this.#dg(this.geometry,this.material)},v=i.createGPUShaderModule(`${Ls}_${this.#ig}_${this.uuid}`,x),_=i.getGPUBindGroupLayout(ResourceManager.PRESET_VERTEX_GPUBindGroupLayout_Instancing);this.gpuRenderInfo.vertexShaderModule=v,this.gpuRenderInfo.pipeline=createBasePipeline(this,v,_),this.gpuRenderInfo.shadowPipeline=createBasePipeline(this,v,_,fn),this.gpuRenderInfo.vertexUniformBindGroup=g.createBindGroup(this.#Rg()),this.#Ks.length=0,this.LODManager.LODList.forEach((x,v)=>{const y={code:this.#dg(x.geometry,x.material)},b=i.createGPUShaderModule(`${Ls}_${this.#ig}_LOD${v}_${this.uuid}`,y);this.#Ks[v]={pipeline:createBasePipeline({vertexStateBuffers:x.geometry.gpuRenderInfo.buffers,primitiveState:this.primitiveState,depthStencilState:this.depthStencilState,geometry:x.geometry,material:x.material||this.material,redGPUContext:this.#h,gpuRenderInfo:this.gpuRenderInfo},b,_),vertexUniformBindGroup:g.createBindGroup(this.#Rg(v+1))}})}#Rg(i=0){const{resourceManager:g}=this.#h,{vertexUniformBuffer:x}=this.gpuRenderInfo,{material:v}=this,{basicSampler:_,basicDisplacementSampler:y,emptyBitmapTextureView:b}=g,{gpuSampler:S}=_,w=g.getGPUBindGroupLayout(ResourceManager.PRESET_VERTEX_GPUBindGroupLayout_Instancing),L=this.#cg,k=L*i,H=L;if(k+H>this.#lg.size)throw new Error("Binding range exceeds visibility buffer size.");return{layout:w,label:"VERTEX_BIND_GROUP_DESCRIPTOR_INSTANCING",entries:[{binding:0,resource:{buffer:x.gpuBuffer,offset:0,size:x.size}},{binding:1,resource:y.gpuSampler},{binding:2,resource:g.getGPUResourceBitmapTextureView(v?.displacementTexture)||b},{binding:3,resource:{buffer:this.#lg.gpuBuffer,offset:k,size:H}}]}}#pg(){const i=4*this.#ig;this.#cg=256*Math.ceil(i/256),this.#hg=this.#cg/4}#mg(){const i=this.gpuRenderInfo.vertexUniformInfo,g=new ArrayBuffer(i.arrayBufferByteLength),x=new StorageBuffer(this.#h,g,`InstanceBuffer_${this.uuid}`),v=this.gpuRenderInfo.vertexUniformBuffer;v?.gpuBuffer&&(v.dataViewF32.length>x.dataViewF32.length?x.dataViewF32.set(v.dataViewF32.subarray(0,x.dataViewF32.length),0):x.dataViewF32.set(v.dataViewF32,0),v.destroy()),this.gpuRenderInfo.vertexUniformBuffer=x}#Cg(i,g="",x="",v="",_=""){return[g,x,v,i.replaceAll(/__INSTANCE_COUNT__/g,this.#ig.toString()),_].join("\n")}#dg(i,g){const x=i.vertexBuffer.interleavedStruct.label,v=g instanceof PBRMaterial,_="PBR"===x&&v,y=_?"struct InputData{@builtin(instance_index)instanceIdx:u32,@location(0)position:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,@location(3)uv1:vec2,@location(4)vertexColor_0:vec4,@location(5)vertexTangent:vec4,};":"struct InputData{@builtin(instance_index)instanceIdx:u32,@location(0)position:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,@location(3)vertexTangent:vec4,};",b="PBR"!==x&&v||_?As:"struct VertexOutput{@builtin(position)position:vec4,@location(0)vertexPosition:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,@location(3)vertexTangent:vec4,@location(7)currentClipPos:vec4,@location(8)prevClipPos:vec4,@location(11)instanceOpacity:f32,@location(12)motionVector:vec3,@location(13)shadowCoord:vec3,@location(14)@interpolate(flat)receiveShadow:f32,@location(15)@interpolate(flat)pickingId:vec4,};";return this.#Cg("#redgpu_include SYSTEM_UNIFORM;#redgpu_include displacement.getDisplacementPosition;#redgpu_include displacement.getDisplacementNormal;struct InstanceUniforms{instanceGroupModelMatrix:mat4x4,instanceGroupNormalModelMatrix:mat4x4,useDisplacementTexture:u32,displacementScale:f32,padding:vec2,instanceModelMatrixs:array,__INSTANCE_COUNT__>,instanceNormalModelMatrix:array,__INSTANCE_COUNT__>,instanceOpacity:array,};@group(1)@binding(0)varinstanceUniforms:InstanceUniforms;@group(1)@binding(1)var displacementTextureSampler:sampler;@group(1)@binding(2)var displacementTexture:texture_2d;@group(1)@binding(3)varvisibilityBuffer:array;const maxDistance:f32=1000.0;",_?"@vertex fn main(inputData:InputData)->VertexOutput{var output:VertexOutput;let input_instanceIdx:u32=visibilityBuffer[inputData.instanceIdx];let u_modelMatrix=instanceUniforms.instanceModelMatrixs[input_instanceIdx];let u_normalModelMatrix=instanceUniforms.instanceNormalModelMatrix[input_instanceIdx];let u_instanceGroupModelMatrix=instanceUniforms.instanceGroupModelMatrix;let u_useDisplacementTexture=instanceUniforms.useDisplacementTexture==1u;let u_displacementScale=instanceUniforms.displacementScale;let u_projectionMatrix=systemUniforms.projection.projectionMatrix;let u_projectionViewMatrix=systemUniforms.projection.projectionViewMatrix;let u_camera=systemUniforms.camera;let u_viewMatrix=u_camera.viewMatrix;let u_cameraPosition=u_camera.cameraPosition;let input_position=inputData.position;let input_vertexNormal=inputData.vertexNormal;let input_uv=inputData.uv;var position:vec4=u_modelMatrix*vec4(input_position,1.0);let worldPosition=position.xyz;if(u_useDisplacementTexture){let worldPosForDisplacement=(u_instanceGroupModelMatrix*position).xyz;let distance=distance(worldPosForDisplacement,u_cameraPosition);let maxMipLevel=f32(textureNumLevels(displacementTexture))-1.0;let targetMipLevel=clamp((distance/maxDistance)*maxMipLevel,.0,maxMipLevel);let displacedPosition=getDisplacementPosition(input_position,input_vertexNormal,displacementTexture,displacementTextureSampler,u_displacementScale,input_uv,targetMipLevel);position=u_modelMatrix*vec4(displacedPosition,1.0);}let worldPositionVec4=u_instanceGroupModelMatrix*position;output.position=u_projectionViewMatrix*worldPositionVec4;output.vertexPosition=worldPositionVec4.xyz;let u_instanceGroupNormalModelMatrix=instanceUniforms.instanceGroupNormalModelMatrix;var normalPosition:vec3=(u_instanceGroupNormalModelMatrix*u_normalModelMatrix*vec4(input_vertexNormal,.0)).xyz;output.vertexNormal=normalize(normalPosition);output.instanceOpacity=instanceUniforms.instanceOpacity[input_instanceIdx];output.uv=inputData.uv;output.uv1=inputData.uv1;output.vertexColor_0=inputData.vertexColor_0;output.vertexTangent=vec4((u_instanceGroupNormalModelMatrix*u_normalModelMatrix*vec4(inputData.vertexTangent.xyz,.0)).xyz,inputData.vertexTangent.w);return output;}":"@vertex fn main(inputData:InputData)->VertexOutput{var output:VertexOutput;let input_instanceIdx:u32=visibilityBuffer[inputData.instanceIdx];let u_modelMatrix=instanceUniforms.instanceModelMatrixs[input_instanceIdx];let u_normalModelMatrix=instanceUniforms.instanceNormalModelMatrix[input_instanceIdx];let u_instanceGroupModelMatrix=instanceUniforms.instanceGroupModelMatrix;let u_useDisplacementTexture=instanceUniforms.useDisplacementTexture==1u;let u_displacementScale=instanceUniforms.displacementScale;let u_projectionMatrix=systemUniforms.projection.projectionMatrix;let u_projectionViewMatrix=systemUniforms.projection.projectionViewMatrix;let u_camera=systemUniforms.camera;let u_viewMatrix=u_camera.viewMatrix;let u_cameraPosition=u_camera.cameraPosition;let input_position=inputData.position;let input_vertexNormal=inputData.vertexNormal;let input_uv=inputData.uv;var position:vec4=u_modelMatrix*vec4(input_position,1.0);let worldPosition=position.xyz;if(u_useDisplacementTexture){let worldPosForDisplacement=(u_instanceGroupModelMatrix*position).xyz;let distance=distance(worldPosForDisplacement,u_cameraPosition);let maxMip=f32(textureNumLevels(displacementTexture))-1.0;let mipLevel=clamp((distance/maxDistance)*maxMip,.0,maxMip);let displacedPosition=getDisplacementPosition(input_position,input_vertexNormal,displacementTexture,displacementTextureSampler,u_displacementScale,input_uv,mipLevel);position=u_modelMatrix*vec4(displacedPosition,1.0);}let worldPositionVec4=u_instanceGroupModelMatrix*position;output.position=u_projectionViewMatrix*worldPositionVec4;output.vertexPosition=worldPositionVec4.xyz;let u_instanceGroupNormalModelMatrix=instanceUniforms.instanceGroupNormalModelMatrix;var normalPosition:vec3=(u_instanceGroupNormalModelMatrix*u_normalModelMatrix*vec4(input_vertexNormal,.0)).xyz;output.vertexNormal=normalize(normalPosition);output.uv=input_uv;output.instanceOpacity=instanceUniforms.instanceOpacity[input_instanceIdx];return output;}",y,b,"#redgpu_include shadow.getShadowClipPosition #redgpu_include systemStruct.OutputShadowData;@vertex fn entryPointShadowVertex(inputData:InputData)->OutputShadowData{var output:OutputShadowData;let input_instanceIdx:u32=visibilityBuffer[inputData.instanceIdx];let u_directionalLightProjectionViewMatrix=systemUniforms.directionalLightProjectionViewMatrix;let u_modelMatrix=instanceUniforms.instanceModelMatrixs[input_instanceIdx];let u_instanceGroupModelMatrix=instanceUniforms.instanceGroupModelMatrix;let u_useDisplacementTexture=instanceUniforms.useDisplacementTexture==1u;let u_displacementScale=instanceUniforms.displacementScale;let input_position=inputData.position;let input_vertexNormal=inputData.vertexNormal;let input_uv=inputData.uv;var position:vec4=u_modelMatrix*vec4(input_position,1.0);if(u_useDisplacementTexture){let worldPos=(u_instanceGroupModelMatrix*position).xyz;let distance=distance(worldPos,u_directionalLightProjectionViewMatrix[3].xyz);let maxMipLevel=f32(textureNumLevels(displacementTexture))-1.0;let targetMipLevel=clamp((distance/maxDistance)*maxMipLevel,.0,maxMipLevel);let displacedPosition=getDisplacementPosition(input_position,input_vertexNormal,displacementTexture,displacementTextureSampler,u_displacementScale,input_uv,targetMipLevel);position=u_modelMatrix*vec4(displacedPosition,1.0);}output.position=getShadowClipPosition((u_instanceGroupModelMatrix*position).xyz,u_directionalLightProjectionViewMatrix);return output;}")}#Mg(){return this.#Cg("struct InstanceUniforms{instanceGroupModelMatrix:mat4x4,instanceGroupNormalModelMatrix:mat4x4,useDisplacementTexture:u32,displacementScale:f32,padding:vec2,instanceModelMatrixs:array,__INSTANCE_COUNT__>,instanceNormalModelMatrix:array,__INSTANCE_COUNT__>,instanceOpacity:array,};struct CullingUniforms{instanceCount:u32,stride:u32,lodNum:u32,padding:f32,cameraPosition:vec3,frustumPlanes:array,6>,lodDistanceList:array,};struct IndirectDrawArgs{vertexCount:u32,instanceCount:atomic,firstVertex:u32,baseVertex:u32,firstInstance:u32,};@group(0)@binding(0)varinstanceUniforms:InstanceUniforms;@group(0)@binding(1)varcullingUniforms:CullingUniforms;@group(0)@binding(2)varvisibilityBuffer:array;@group(0)@binding(3)varindirectDrawBuffer:array;const BOUNDING_RADIUS:f32=1.0;fn distanceToPlane(position:vec3,plane:vec4)->f32{return dot(vec4(position,1.0),plane);}fn isInsideFrustum(position:vec3,radius:f32)->bool{for(var i:u32=0u;i<6u;i=i+1u){let plane=cullingUniforms.frustumPlanes[i];let distance=distanceToPlane(position,plane);if(distance<-radius){return false;}}return true;}fn calculateLODLevel(distanceToCamera:f32)->u32{if(cullingUniforms.lodNum==0u){return 0u;}for(var i:u32=0u;i){let instanceIdx=globalId.x;if(instanceIdx>=(cullingUniforms.instanceCount)){return;}let u_instanceGroupModelMatrix=instanceUniforms.instanceGroupModelMatrix;let modelMatrix=u_instanceGroupModelMatrix*instanceUniforms.instanceModelMatrixs[instanceIdx];let worldPosition=vec3(modelMatrix[3][0],modelMatrix[3][1],modelMatrix[3][2]);let scaleX=length(vec3(modelMatrix[0][0],modelMatrix[0][1],modelMatrix[0][2]));let scaleY=length(vec3(modelMatrix[1][0],modelMatrix[1][1],modelMatrix[1][2]));let scaleZ=length(vec3(modelMatrix[2][0],modelMatrix[2][1],modelMatrix[2][2]));let maxScale=max(max(scaleX,scaleY),scaleZ);let scaledRadius=BOUNDING_RADIUS*maxScale;let isVisible=isInsideFrustum(worldPosition,scaledRadius);if(isVisible){let distanceToCamera=distance(worldPosition,cullingUniforms.cameraPosition);let lodLevel=calculateLODLevel(distanceToCamera);let visibilityStride=cullingUniforms.stride;let aliveIndex=atomicAdd(&indirectDrawBuffer[lodLevel].instanceCount,1u);visibilityBuffer[visibilityStride*lodLevel+aliveIndex]=instanceIdx;}}")}}var Us=Object.freeze({__proto__:null,ADrawDebuggerLight:ADrawDebuggerLight,DrawDebuggerAxis:DrawDebuggerAxis,DrawDebuggerDirectionalLight:DrawDebuggerDirectionalLight,DrawDebuggerGrid:DrawDebuggerGrid,DrawDebuggerMesh:DrawDebuggerMesh,DrawDebuggerPointLight:DrawDebuggerPointLight,DrawDebuggerSpotLight:DrawDebuggerSpotLight}),ks=Object.freeze({__proto__:null,CoreInstancingMesh:Is,CoreMesh:qa,CoreSkyAtmosphere:Ka,CoreSkyBox:Ga,CoreSpriteSheet:as,CoreTextField:ys,CoreView:Ya,DrawDebugger:Us,Group2D:Group2D,Group3D:Group3D,InstancingMesh:InstancingMesh,LINE_TYPE:ms,Line2D:class extends Line3D{constructor(i,g=ms.LINEAR,x="#fff"){super(i,g,x),this._material=new LineMaterial(i)}get geometry(){return this._geometry}set geometry(i){consoleAndThrowError("Line2D can not change geometry")}get material(){return this._material}set material(i){consoleAndThrowError("Line2D can not change material")}createCustomMeshVertexShaderModule=()=>this.createMeshVertexShaderModuleBASIC("VERTEX_MODULE_LINE_2D",vs,_s,ps);addPoint(i=0,g=0,x=this.baseColor,v=1,_=0,y=0,b=0,S=0){super.addPoint(i,g,0,x,v,_,y,0,b,S,0)}addPointAt(i,g=0,x=0,v=this.baseColor,_=1,y=0,b=0,S=0,w=0){super.addPointAt(i,g,x,0,v,_,y,b,0,S,w,0)}},Line3D:Line3D,Mesh:Mesh,PARTICLE_EASE:Wa,ParticleEmitter:ParticleEmitter,Scene:Scene,SkyAtmosphere:SkyAtmosphere,SkyBox:SkyBox,Sprite2D:Sprite2D,Sprite3D:Sprite3D,SpriteSheet2D:SpriteSheet2D,SpriteSheet3D:SpriteSheet3D,SpriteSheetInfo:SpriteSheetInfo,TextField2D:TextField2D,TextField3D:TextField3D,View2D:View2D,View3D:View3D}),Gs=Object.freeze({__proto__:null,ABaseLight:ABaseLight,LightManager:LightManager}),Os=Object.freeze({__proto__:null,AmbientLight:AmbientLight,Core:Gs,DirectionalLight:DirectionalLight,PointLight:PointLight,SpotLight:SpotLight});function sortTransparentObjects(i,g){const x={},{x:v,y:_,z:y}=i;return g.sort((i,g)=>{if(i=i.mesh,g=g.mesh,!x[i.uuid]){const g=i.x-v,b=i.y-_,S=i.z-y;x[i.uuid]=g*g+b*b+S*S}if(!x[g.uuid]){const i=g.x-v,b=g.y-_,S=g.z-y;x[g.uuid]=i*i+b*b+S*S}return x[g.uuid]-x[i.uuid]})}var Vs=Object.freeze({__proto__:null,Ray:Ray,calculateNormals:calculateNormals,calculateTangents:calculateTangents,computeViewFrustumPlanes:computeViewFrustumPlanes,getScreenPoint:getScreenPoint,localToWorld:localToWorld,mat3:Ct,mat4:At,matToEuler:mat4ToEuler,quat:br,quaternionToRotationMat4:quaternionToRotationMat4,screenToWorld:screenToWorld,sortTransparentObjects:sortTransparentObjects,updateObject3DMatrix:updateObject3DMatrix,vec2:Dr,vec3:zt,vec4:Jt,worldToLocal:worldToLocal}),Ns=Object.freeze({__proto__:null,GeometryGPURenderInfo:GeometryGPURenderInfo,Primitive:Primitive,PrimitiveUtils:PrimitiveUtils,createPrimitiveGeometry:createPrimitiveGeometry});var Fs=Object.freeze({__proto__:null,Box:Box,Capsule:class extends Primitive{constructor(i,g=.5,x=1,v=32,_=1,y=12){const b=Primitive.generateUniqueKey("CAPSULE",{radius:g,height:x,radialSegments:v,heightSegments:_,capSegments:y});super(i,b,()=>PrimitiveUtils.generateCapsuleData(i,g,x,v,_,y,b))}},Circle:class extends Primitive{constructor(i,g=1,x=8,v=0,_=2*Math.PI,y=!1){const b=Primitive.generateUniqueKey("CIRCLE",{radius:g,radialSegments:x,thetaStart:v,thetaLength:_,isRadial:y});super(i,b,()=>PrimitiveUtils.generateCircleEntryData(i,g,x,v,_,y,b))}},Cone:class extends Primitive{constructor(i,g=1,x=1,v=32,_=1,y=!0,b=0,S=2*Math.PI){const w=Primitive.generateUniqueKey("CONE",{radius:g,height:x,radialSegments:v,heightSegments:_,capBottom:y,thetaStart:b,thetaLength:S});super(i,w,()=>PrimitiveUtils.generateConeData(i,g,x,v,_,y,b,S,w))}},Core:Ns,Cylinder:Cylinder,Ground:class extends Primitive{constructor(i,g=1,x=1,v=1,_=1,y=!1){const b=Primitive.generateUniqueKey("GROUND",{width:g,height:x,widthSegments:v,heightSegments:_,flipY:y});super(i,b,()=>PrimitiveUtils.generateGroundData(i,g,x,v,_,y,b))}},Plane:Plane,Ring:class extends Primitive{constructor(i,g=.5,x=1,v=8,_=1,y=0,b=2*Math.PI,S=!1){const w=Primitive.generateUniqueKey("RING",{innerRadius:g,outerRadius:x,thetaSegments:v,phiSegments:_,thetaStart:y,thetaLength:b,isRadial:S});super(i,w,()=>PrimitiveUtils.generateRingEntryData(i,g,x,v,_,y,b,S,w))}},RoundedBox:class extends Primitive{constructor(i,g=1,x=1,v=1,_=1,y=1,b=1,S=.1,w=4){const L=`RoundedBox_${g}_${x}_${v}_${_}_${y}_${b}_${S}_${w}`;super(i,L,()=>PrimitiveUtils.generateRoundedBoxData(i,g,x,v,_,y,b,S,w,L))}},Sphere:Sphere,Torus:class extends Primitive{constructor(i,g=1,x=.5,v=16,_=16,y=0,b=2*Math.PI,S=!1,w=!1,L=!1,k=!1){if(v<3)throw new Error("radialSegments must be 3 or greater");if(_<3)throw new Error("tubularSegments must be 3 or greater");const H=Primitive.generateUniqueKey("TORUS",{radius:g,thickness:x,radialSegments:v,tubularSegments:_,thetaStart:y,thetaLength:b,capStart:S,capEnd:w,isRadialCapStart:L,isRadialCapEnd:k});super(i,H,()=>PrimitiveUtils.generateTorusData(i,g,x,v,_,y,b,S,w,L,k,H))}},TorusKnot:class extends Primitive{constructor(i,g=1,x=.4,v=64,_=8,y=2,b=3){const S=Primitive.generateUniqueKey("TORUS_KNOT",{radius:g,tubeRadius:x,tubularSegments:v,radialSegments:_,windingsAroundAxis:y,windingsAroundCircle:b});super(i,S,()=>PrimitiveUtils.generateTorusKnotData(i,g,x,v,_,y,b,S))}}});const Hs=parseWGSL("PHONG_MATERIAL","#redgpu_include SYSTEM_UNIFORM;#redgpu_include color.getTintBlendMode;#redgpu_include shadow.getDirectionalShadowVisibility;#redgpu_include math.tnb.getTBNFromVertexTangent #redgpu_include math.tnb.getNormalFromNormalMap #redgpu_include displacement.getDisplacementNormal;#redgpu_include entryPoint.mesh.entryPointPickingFragment;#redgpu_include systemStruct.OutputFragment;#redgpu_include math.getMotionVector;#redgpu_include lighting.getLightDistanceAttenuation;#redgpu_include lighting.getLightAngleAttenuation;#redgpu_include skyAtmosphere.skyAtmosphereFn const maxDistance:f32=1000.0;struct Uniforms{color:vec3,emissiveColor:vec3,emissiveStrength:f32,specularColor:vec3,specularStrength:f32,shininess:f32,aoStrength:f32,normalScale:f32,displacementScale:f32,opacity:f32,useTint:u32,tint:vec4,tintBlendMode:u32,useSSR:u32,metallic:f32,roughness:f32,};struct InputData{@builtin(position)position:vec4,@location(0)vertexPosition:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,@location(3)vertexTangent:vec4,@location(7)currentClipPos:vec4,@location(8)prevClipPos:vec4,@location(11)combinedOpacity:f32,@location(12)motionVector:vec3,@location(13)shadowCoord:vec3,@location(14)@interpolate(flat)receiveShadow:f32,@location(15)@interpolate(flat)pickingId:vec4,}@group(2)@binding(0)varuniforms:Uniforms;@group(2)@binding(1)var diffuseTextureSampler:sampler;@group(2)@binding(2)var diffuseTexture:texture_2d;@group(2)@binding(3)var alphaTextureSampler:sampler;@group(2)@binding(4)var alphaTexture:texture_2d;@group(2)@binding(5)var specularTextureSampler:sampler;@group(2)@binding(6)var specularTexture:texture_2d;@group(2)@binding(7)var emissiveTextureSampler:sampler;@group(2)@binding(8)var emissiveTexture:texture_2d;@group(2)@binding(9)var aoTextureSampler:sampler;@group(2)@binding(10)var aoTexture:texture_2d;@group(2)@binding(11)var normalTextureSampler:sampler;@group(2)@binding(12)var normalTexture:texture_2d;@group(2)@binding(13)var displacementTextureSampler:sampler;@group(2)@binding(14)var displacementTexture:texture_2d;#redgpu_include math.PI #redgpu_include math.INV_PI #redgpu_include math.EPSILON #redgpu_include math.direction.getViewDirection fn getDiffuseBRDFDisney(NdotL:f32,NdotV:f32,LdotH:f32,roughness:f32,albedo:vec3)->vec3{if(NdotL<=.0){return vec3(.0);}let energyBias=mix(.0,0.5,roughness);let energyFactor=mix(1.0,1.0/1.51,roughness);let fd90=energyBias+2.0*LdotH*LdotH*roughness;let f0=1.0;let lightScatter=f0+(fd90-f0)*pow(1.0-NdotL,5.0);let viewScatter=f0+(fd90-f0)*pow(1.0-NdotV,5.0);return albedo*NdotL*lightScatter*viewScatter*energyFactor*INV_PI;}fn getFresnelSchlick(cosTheta:f32,F0:vec3)->vec3{return F0+(vec3(1.0)-F0)*pow(clamp(1.0-cosTheta,.0,1.0),5.0);}fn getDistributionGGX(NdotH:f32,roughness:f32)->f32{let alpha=roughness*roughness;let alpha2=alpha*alpha;let NdotH2=NdotH*NdotH;let nom=alpha2;let denom=(NdotH2*(alpha2-1.0)+1.0);let denomSquared=denom*denom;return nom/max(EPSILON,denomSquared*PI);}fn getSpecularVisibility(NdotV:f32,NdotL:f32,roughness:f32)->f32{let alpha=roughness*roughness;let alpha2=alpha*alpha;let safeNdotV=max(NdotV,1e-4);let safeNdotL=max(NdotL,1e-4);let GGXV=safeNdotL*sqrt(safeNdotV*safeNdotV*(1.0-alpha2)+alpha2);let GGXL=safeNdotV*sqrt(safeNdotL*safeNdotL*(1.0-alpha2)+alpha2);return 0.5/max(GGXV+GGXL,EPSILON);}fn getSpecularBRDF(F0:vec3,roughness:f32,NdotH:f32,NdotV:f32,NdotL:f32,LdotH:f32)->vec3{let D=getDistributionGGX(NdotH,roughness);let V=getSpecularVisibility(NdotV,NdotL,roughness);let F=getFresnelSchlick(LdotH,F0);return D*V*F;}@fragment fn main(inputData:InputData)->OutputFragment{var output:OutputFragment;let input_vertexNormal=inputData.vertexNormal.xyz;let input_vertexPosition=inputData.vertexPosition.xyz;let u_ambientLight=systemUniforms.ambientLight;let u_directionalLightCount=systemUniforms.directionalLightCount;let u_directionalLights=systemUniforms.directionalLights;let u_directionalShadowDepthTextureSize=systemUniforms.shadow.directionalShadowDepthTextureSize;let u_directionalShadowBias=systemUniforms.shadow.directionalShadowBias;let u_camera=systemUniforms.camera;let u_cameraPosition=u_camera.cameraPosition;let u_color=uniforms.color;let u_aoStrength=uniforms.aoStrength;let u_emissiveColor=uniforms.emissiveColor;let u_emissiveStrength=uniforms.emissiveStrength;let u_normalScale=uniforms.normalScale;let u_specularColor=uniforms.specularColor;let u_specularStrength=uniforms.specularStrength;let u_shininess=uniforms.shininess;let u_opacity=uniforms.opacity;let V=getViewDirection(input_vertexPosition,u_cameraPosition);let receiveShadowYn=inputData.receiveShadow !=.0;var N=normalize(input_vertexNormal);#redgpu_if displacementTexture{let dist=distance(input_vertexPosition,u_cameraPosition);let maxMip=f32(textureNumLevels(displacementTexture))-1.0;let targetMipLevel=clamp((dist/maxDistance)*maxMip,.0,maxMip);let tangentDisplacedNormal=getDisplacementNormal(displacementTexture,displacementTextureSampler,uniforms.displacementScale,inputData.uv,targetMipLevel);let tbn=getTBNFromVertexTangent(N,inputData.vertexTangent);N=normalize(tbn*tangentDisplacedNormal);}#redgpu_endIf #redgpu_if normalTexture let normalSamplerColor=textureSample(normalTexture,normalTextureSampler,inputData.uv).rgb;let tbn=getTBNFromVertexTangent(N,inputData.vertexTangent);N=getNormalFromNormalMap(normalSamplerColor,tbn,u_normalScale);#redgpu_endIf N=normalize(N);let NdotV=max(dot(N,V),1e-6);var resultAlpha:f32=u_opacity*inputData.combinedOpacity;#redgpu_if alphaTexture let alphaMapValue:f32=textureSample(alphaTexture,alphaTextureSampler,inputData.uv).r;resultAlpha=alphaMapValue*resultAlpha;if(resultAlpha==.0){discard;}#redgpu_endIf var baseColor:vec3=u_color;#redgpu_if diffuseTexture let diffuseSampleColor=textureSample(diffuseTexture,diffuseTextureSampler,inputData.uv);baseColor=diffuseSampleColor.rgb;resultAlpha=resultAlpha*diffuseSampleColor.a;#redgpu_endIf let metallicParameter=uniforms.metallic;var roughnessParameter=select(sqrt(2.0/(u_shininess+2.0)),uniforms.roughness,uniforms.roughness>.0);roughnessParameter=clamp(roughnessParameter,.045,1.0);var specularSamplerValue:f32=1.0;#redgpu_if specularTexture specularSamplerValue=textureSample(specularTexture,specularTextureSampler,inputData.uv).r;#redgpu_endIf let F0_dielectric=vec3(.04)*u_specularColor*u_specularStrength*specularSamplerValue;let F0=mix(F0_dielectric,baseColor,metallicParameter);let albedo=baseColor*(1.0-metallicParameter);var visibility:f32=1.0;visibility=getDirectionalShadowVisibility(directionalShadowMap,directionalShadowMapSampler,u_directionalShadowDepthTextureSize,u_directionalShadowBias,inputData.shadowCoord);if(!receiveShadowYn){visibility=1.0;}var totalDirectLighting=vec3(.0);for(var i=0u;itLight.radius){continue;}let L=normalize(lightDir);var attenuation=getLightDistanceAttenuation(lightDistance,tLight.radius);if(tLight.isSpotLight>.0){let spotDir=normalize(vec3(tLight.directionX,tLight.directionY,tLight.directionZ));attenuation*=getLightAngleAttenuation(normalize(-L),spotDir,tLight.innerCutoff,tLight.outerCutoff);}if(attenuation<=.0){continue;}let finalLightColor=tLight.color*tLight.intensity*attenuation;totalDirectLighting+=calcPbrLight(finalLightColor,N,V,L,NdotV,roughnessParameter,metallicParameter,albedo,F0);}var ambientContribution=albedo*u_ambientLight.color*u_ambientLight.intensity*INV_PI;if(systemUniforms.useSkyAtmosphere==1u){let u_atmo=systemUniforms.skyAtmosphere;let skyIntensity=u_atmo.sunIntensity;let diffTrans=getTransmittance(transmittanceTexture,atmosphereSampler,u_atmo.cameraHeight,N.y,u_atmo.atmosphereHeight);let skyIrradiance=textureSampleLevel(atmosphereIrradianceLUT,atmosphereSampler,N,.0).rgb*skyIntensity;ambientContribution=(ambientContribution*diffTrans)+(albedo*skyIrradiance*INV_PI);}var mixColor=totalDirectLighting+ambientContribution;#redgpu_if aoTexture mixColor*=textureSample(aoTexture,aoTextureSampler,inputData.uv).rgb*u_aoStrength;#redgpu_endIf var emissiveColor=u_emissiveColor*u_emissiveStrength;#redgpu_if emissiveTexture emissiveColor=textureSample(emissiveTexture,emissiveTextureSampler,inputData.uv).rgb*u_emissiveStrength;#redgpu_endIf let finalColor=vec4((mixColor*systemUniforms.preExposure)+emissiveColor,resultAlpha);#redgpu_if useTint output.color=getTintBlendMode(finalColor,uniforms.tintBlendMode,uniforms.tint);#redgpu_else output.color=finalColor;#redgpu_endIf if(systemUniforms.isView3D==1&&output.color.a==.0){discard;}let smoothness=1.0-roughnessParameter;let smoothnessCurved=smoothness*smoothness*(3.0-2.0*smoothness);output.gBufferNormal=vec4(N*0.5+0.5,smoothnessCurved*(.04+0.96*metallicParameter*metallicParameter));output.gBufferMotionVector=vec4(getMotionVector(inputData.currentClipPos,inputData.prevClipPos),.0,1.0);return output;}fn calcPbrLight(lightColor:vec3,N:vec3,V:vec3,L:vec3,NdotV:f32,roughness:f32,metallic:f32,albedo:vec3,F0:vec3)->vec3{let NdotL=max(dot(N,L),.0);if(NdotL<=.0){return vec3(.0);}let H=normalize(L+V);let NdotH=max(dot(N,H),.0);let LdotH=max(dot(L,H),.0);let VdotH=max(dot(V,H),.0);let F=getFresnelSchlick(VdotH,F0);let D=getDistributionGGX(NdotH,roughness);let Vis=getSpecularVisibility(NdotV,NdotL,roughness);let spec=D*Vis*F;let diff=getDiffuseBRDFDisney(NdotL,NdotV,LdotH,roughness,albedo);let kS=F;let kD=(vec3(1.0)-kS)*(1.0-metallic);return(kD*diff+spec)*lightColor*NdotL;}");class PhongMaterial extends AUVTransformBaseMaterial{constructor(i,g="#fff",x){super(i,"PHONG_MATERIAL",Hs,2),x&&(this.name=x),this.initGPURenderInfos(),this.color.setColorByHEX(g),this.emissiveColor.setColorByHEX(this.emissiveColor.hex),this.specularColor.setColorByHEX(this.specularColor.hex),this.diffuseTextureSampler=new Sampler(this.redGPUContext,{magFilter:"linear",minFilter:"linear",mipmapFilter:"linear",addressModeU:"repeat",addressModeV:"repeat",addressModeW:"repeat"})}}defineSampler(PhongMaterial,[{key:"alphaTextureSampler"},{key:"aoTextureSampler"},{key:"diffuseTextureSampler"},{key:"emissiveTextureSampler"},{key:"environmentTextureSampler"},{key:"normalTextureSampler"},{key:"specularTextureSampler"},{key:"displacementTextureSampler"}]),definePositiveNumber(PhongMaterial,[{key:"aoStrength",value:1},{key:"specularStrength",value:1},{key:"emissiveStrength",value:1},{key:"shininess",value:32},{key:"normalScale",value:1},{key:"displacementScale",value:1}]),defineColorRGB(PhongMaterial,[{key:"color"},{key:"emissiveColor",value:"#000000"},{key:"specularColor",value:"#ffffff"}]),defineTexture(PhongMaterial,[{key:"alphaTexture"},{key:"aoTexture"},{key:"diffuseTexture"},{key:"emissiveTexture"},{key:"environmentTexture"},{key:"normalTexture"},{key:"specularTexture"},{key:"displacementTexture"}]),defineBoolean(PhongMaterial,[{key:"useSSR",value:!1}]),definePositiveNumber(PhongMaterial,[{key:"metallic",value:0,min:0,max:1},{key:"roughness",value:0,min:0,max:1}]),Object.freeze(PhongMaterial);var zs=Object.freeze({__proto__:null,BLEND_MODE:Xa,BitmapMaterial:BitmapMaterial,ColorMaterial:ColorMaterial,Core:yi,PBRMaterial:PBRMaterial,PhongMaterial:PhongMaterial,TINT_BLEND_MODE:xi}),$s=Object.freeze({__proto__:null,ImmutableKeyMap:ImmutableKeyMap,ManagementResourceBase:ManagementResourceBase,ResourceBase:ResourceBase,ResourceManager:ResourceManager,ResourceStatusInfo:ResourceStatusInfo}),js=Object.freeze({__proto__:null,ABaseBuffer:ABaseBuffer,AUniformBaseBuffer:AUniformBaseBuffer}),Ks=Object.freeze({__proto__:null,VertexInterleavedStructElement:VertexInterleavedStructElement});class ResourceStateHDRTexture{texture;src;cacheKey;useNum=0;uuid;constructor(i){this.texture=i,this.src=i.src,this.cacheKey=i.cacheKey,this.useNum=0,this.uuid=i.uuid}}class HDRLoader{#Bg=!0;constructor(i=!0){this.#Bg=i}get enableDebugLogs(){return this.#Bg}set enableDebugLogs(i){this.#Bg=i}async loadHDRFile(i){this.#Bg&&g(`HDR 파일 로딩 시작: ${i}`);const x=await fetch(i);if(!x.ok)throw new Error(`HTTP ${x.status}: ${x.statusText}`);const v=await x.arrayBuffer(),_=new Uint8Array(v),y=this.#Dg(_,i);return g({...y}),{...y}}#Dg(i,x){const v=this.#Eg(i);if(this.#Bg&&g(`파일 형식: ${v.format}`),!v.isValid)throw new Error(v.error||"지원되지 않는 파일 형식입니다");if(x.split("?")[0].toLowerCase().endsWith(".hdr")){this.#Bg&&this.#Ig(i.slice(0,200));const g=this.#Ag(i);return this.#Bg&&this.#Lg(g),g}throw x.split("?")[0].toLowerCase().endsWith(".exr")?new Error("EXR format not supported yet"):new Error(`Unsupported HDR format: ${x}`)}#Ag(i){let x=0,v="";const _={};for(;x0){_[v.substring(0,g).trim()]=v.substring(g+1).trim()}}for(v="";x>8&255)&&i[g+3]===(255&x)){g+=4;for(let _=0;_<4;_++){let y=_;for(;y<4*x;){const _=i[g++];if(_>128){const b=_-128,S=i[g++];for(let i=0;ii.toString(16).padStart(2,"0")).join(" "),Array.from(i.slice(g,g+16)).map(i=>i>=32&&i<=126?String.fromCharCode(i):".").join("")}}async function float32ToFloat16Linear(i,g,x){const v=performance.now(),{gpuDevice:_}=i,{width:y,height:b,targetTexture:S}=x,w=g.length/4;try{const x=_.createShaderModule({code:"struct Constants{width:u32,height:u32,}@group(0)@binding(0)varinputData:array;@group(0)@binding(1)varoutputData:array;@group(0)@binding(2)varconstants:Constants;fn floatToHalf(value:f32)->u32{let bits=bitcast(value);let sign=(bits>>16u)& 0x8000u;var exp=(bits>>23u)& 0xFFu;var mantissa=bits & 0x7FFFFFu;if(exp==0u){return sign;}if(exp==255u){return sign | 0x7C00u | select(0u,1u,mantissa !=0u);}let newExp=i32(exp)-127+15;if(newExp<=0){return sign;}if(newExp>=31){return sign | 0x7C00u;}return sign |(u32(newExp)<<10u)|(mantissa>>13u);}@compute @workgroup_size(8,8)fn main(@builtin(global_invocation_id)global_id:vec3){let x=global_id.x;let y=global_id.y;if(x>=constants.width||y>=constants.height){return;}let pixelIndex=y*constants.width+x;let baseIndex=pixelIndex*4u;let r=inputData[baseIndex];let g=inputData[baseIndex+1u];let b=inputData[baseIndex+2u];let a=inputData[baseIndex+3u];let r16=floatToHalf(r);let g16=floatToHalf(g);let b16=floatToHalf(b);let a16=floatToHalf(a);let outputIndex=pixelIndex*2u;outputData[outputIndex]=(g16<<16u)| r16;outputData[outputIndex+1u]=(a16<<16u)| b16;}",label:"float16_linear_conversion_shader"}),L=function(i,g,x){const v=i.createBuffer({size:g.byteLength,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST,label:"float16_input_buffer"}),_=i.createBuffer({size:8*x,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC,label:"float16_output_buffer"}),y=i.createBuffer({size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,label:"float16_constants_buffer"});return i.queue.writeBuffer(v,0,g),{inputBuffer:v,outputBuffer:_,constantsBuffer:y}}(_,g,w);_.queue.writeBuffer(L.constantsBuffer,0,new Uint32Array([y,b]));const{computePipeline:k,bindGroup:H}=function(i,g,x){const v=i.createComputePipeline({layout:"auto",compute:{module:g,entryPoint:"main"},label:"float16_conversion_pipeline"}),_=i.createBindGroup({layout:v.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:x.inputBuffer}},{binding:1,resource:{buffer:x.outputBuffer}},{binding:2,resource:{buffer:x.constantsBuffer}}],label:"float16_conversion_bindgroup"});return{computePipeline:v,bindGroup:_}}(_,x,L);await async function(i,g,x,v,_,y,b){const S=Math.ceil(y/8),w=Math.ceil(b/8);if(S>65535||w>65535)throw new Error(`이미지 크기 초과: ${S} × ${w}`);await i.commandEncoderManager.immediateComputePass("float16_conversion_command_encoder",i=>{i.setPipeline(g),i.setBindGroup(0,x),i.dispatchWorkgroups(S,w)},i=>{i.copyBufferToTexture({buffer:v,bytesPerRow:8*y,rowsPerImage:b},{texture:_},{width:y,height:b,depthOrArrayLayers:1})}),await i.gpuDevice.queue.onSubmittedWorkDone()}(i,k,H,L.outputBuffer,S,y,b),function(i){i.inputBuffer.destroy(),i.outputBuffer.destroy(),i.constantsBuffer.destroy()}(L);return{processedPixels:w,executionTime:performance.now()-v}}catch(i){throw console.error("Float16 변환 실패:",i),i}}class HDRTexture extends ManagementResourceBase{#V;#wo;#H=0;#kg=new HDRLoader;#z="rgba16float";#q;#Y;#Gt=0;#Ot=0;constructor(i,g,x,v){if(super(i,"managedHDRTextureState"),this.#q=x,this.#Y=v,g){const i=this.#W(g);this.#Gg(i),this.#wo=i,this.cacheKey=this.#Z(g);const{table:x}=this.targetResourceManagedState;let v=x.get(this.cacheKey);if(v){const i=v.texture;return this.#q?.(i),i}this.src=g,this.#J()}}get width(){return this.#Gt}get height(){return this.#Ot}get videoMemorySize(){return this.#H}get gpuTexture(){return this.#V}get src(){return this.#wo}set src(i){const g=this.#W(i);this.#Gg(g),this.#wo=g,this.cacheKey=this.#Z(i),this.#wo&&this.#Og(this.#wo)}destroy(){const i=this.#V;this.#te(null),this.notifyUpdate(!0),this.#re(),this.#wo=null,this.cacheKey=null,i&&this.redGPUContext.commandEncoderManager.addDeferredDestroy(i)}#Z(i){let g;return i||(g=this.uuid),g="string"==typeof i?getAbsoluteURL(window.location.href,i):i.cacheKey||getAbsoluteURL(window.location.href,i.src),`HDRTexture_${g}`}#W(i){return"string"==typeof i?i:i.src}#Gg(i){if(!i||"string"!=typeof i)throw new Error("HDR 파일 경로가 필요합니다");if(!i.split("?")[0].split("#")[0].toLowerCase().endsWith(".hdr"))throw new Error(`지원되지 않는 형식입니다. .hdr 형식만 지원됩니다. 입력된 파일: ${i}`)}async#Og(i){try{const g=await this.#kg.loadHDRFile(i);this.#Gt=g.width,this.#Ot=g.height,await this.#ee(g),this.#q?.(this),this.notifyUpdate()}catch(i){console.error("HDR loading error:",i),this.#Y?.(i)}}async#ee(i){const{gpuDevice:g}=this.redGPUContext,x=this.#V,v={size:[this.#Gt,this.#Ot,1],format:this.#z,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC,label:`HDRTexture_2D_${this.#wo}`},_=g.createTexture(v);await float32ToFloat16Linear(this.redGPUContext,i.data,{width:this.#Gt,height:this.#Ot,targetTexture:_}),this.#te(_),x&&this.redGPUContext.commandEncoderManager.addDeferredDestroy(x)}#te(i){this.targetResourceManagedState.videoMemory-=this.#H,this.#V=i,this.#H=i?calculateTextureByteSize(i):0,this.targetResourceManagedState.videoMemory+=this.#H,this.notifyUpdate()}#J(){this.redGPUContext.resourceManager.registerManagementResource(this,new ResourceStateHDRTexture(this))}#re(){this.redGPUContext.resourceManager.unregisterManagementResource(this)}}Object.freeze(HDRTexture);const Xs={MODE_1D:1,MODE_2D:2,MODE_3D:3};Object.freeze(Xs);const qs="managedBitmapTextureState",Ys={animationSpeed:1,animationX:.1,animationY:.1};class ANoiseTexture extends ManagementResourceBase{mipLevelCount=1;useMipmap=!0;src;#V;#Vg=8;#Ng=8;#Fg=1;#Hg;#zg;#$g;#jg;#Kg;#se;#Xg;#Gt;#Ot;#qg;#Yg=0;#Wg=1;#Zg=Ys.animationX;#Jg=Ys.animationY;#H=0;constructor(i,g=1024,x=1024,v,_=!0){super(i,qs),validateUintRange(g,2,2048),validateUintRange(x,2,2048),this.#Gt=g,this.#Ot=x,this.#qg=v,this.useMipmap=_,this.#N(i),this.cacheKey=`NoiseTexture_${g}x${x}_${Date.now()}`,this.#V=this.#Qg(i,g,x),this.#H=calculateTextureByteSize(this.#V),this.#ex(),this.#J()}get videoMemorySize(){return this.#H}get resourceManagerKey(){return qs}get animationSpeed(){return this.#Wg}set animationSpeed(i){validatePositiveNumberRange(i),this.#Wg=i,this.updateUniform("animationSpeed",i)}get animationX(){return this.#Zg}set animationX(i){validateNumber(i),this.#Zg=i,this.updateUniform("animationX",i)}get animationY(){return this.#Jg}set animationY(i){validateNumber(i),this.#Jg=i,this.updateUniform("animationY",i)}get uniformInfo(){return this.#Xg}get gpuTexture(){return this.#V}get time(){return this.#Yg}set time(i){validatePositiveNumberRange(i),this.#Yg=i,this.updateUniform("time",i/1e3)}updateUniform(i,g){this.#Xg.members[i]&&(this.#se.writeOnlyBuffer(this.#Xg.members[i],g),this.#qg[i]=g),this.#ex()}updateUniforms(i){Object.entries(i).forEach(([i,g])=>{this.#Xg.members[i]&&(this.#se.writeOnlyBuffer(this.#Xg.members[i],g),this.#qg[i]=g)}),this.#ex()}render(i){this.updateUniform("time",i)}destroy(){const i=this.#V;this.notifyUpdate(!0),this.#re(),i&&i.destroy(),this.src=null,this.cacheKey=null,this.#V=null}#N(i){const{gpuDevice:g}=i,x=this.#tx();this.cacheKey=this.uuid,this.#Hg=g.createShaderModule({code:x}),this.#$g=this.#rx(i),this.#jg=this.#ix(g,this.#Hg,this.#$g);const v=parseWGSL("ANoiseTexture",x);this.#Xg=v.uniforms.uniforms;const _=new ArrayBuffer(this.#Xg.arrayBufferByteLength);this.#se=new UniformBuffer(i,_,`${this.constructor.name}_UniformBuffer`),this.#qg.uniformDefaults&&this.updateUniforms({...Ys,...this.#qg.uniformDefaults})}#tx(){return`\n ${`\n struct Uniforms {\n time: f32,\n\t\t\t\t\t\t\t\tanimationSpeed: f32,\n\t\t\t\t\t\t\t\tanimationX: f32,\n\t\t\t\t\t\t\t\tanimationY: f32,\n ${this.#qg.uniformStruct||""}\n };\n `}\n @group(0) @binding(0) var uniforms : Uniforms;\n @group(0) @binding(1) var outputTexture : texture_storage_2d;\n \n ${this.#qg.helperFunctions||""}\n @compute @workgroup_size(${this.#Vg},${this.#Ng},${this.#Fg})\n fn main (\n @builtin(global_invocation_id) global_id : vec3,\n ){\n let index = vec2(global_id.xy);\n let dimensions: vec2 = textureDimensions(outputTexture);\n \n if (index.x >= dimensions.x || index.y >= dimensions.y) {\n return;\n }\n \n let dimW = f32(dimensions.x);\n let dimH = f32(dimensions.y);\n let base_uv = vec2((f32(index.x) + 0.5) / dimW, (f32(index.y) + 0.5) / dimH);\n ${this.#qg.mainLogic}\n \n textureStore(outputTexture, index, finalColor);\n }\n `}#ex(){if(!this.#zg)return;const{redGPUContext:i}=this,{commandEncoderManager:g,resourceManager:x}=i,v={label:`NoiseTexture_${this.uuid}_ComputePass`};g.addResourceComputePass(v,i=>{i.setPipeline(this.#jg),i.setBindGroup(0,this.#zg),i.dispatchWorkgroups(Math.ceil(this.#Gt/this.#Vg),Math.ceil(this.#Ot/this.#Ng))}),this.useMipmap&&x.mipmapGenerator.generateMipmap(this.#V,this.#Kg)}#rx(i){return i.resourceManager.createBindGroupLayout("NoiseTextureBindGroupLayout",{entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.COMPUTE,storageTexture:{format:"rgba16float"}}]})}#Qg(i,g,x){this.mipLevelCount=this.useMipmap?getMipLevelCount(g,x):1,this.#Kg={size:{width:g,height:x},format:"rgba16float",mipLevelCount:this.mipLevelCount,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_DST,label:this.cacheKey};const v=i.gpuDevice.createTexture(this.#Kg),_=v.createView({baseMipLevel:0,mipLevelCount:1});return this.#zg=this.#nx(i,this.#$g,_),v}#nx(i,g,x){return i.gpuDevice.createBindGroup({layout:g,entries:[{binding:0,resource:{buffer:this.#se.gpuBuffer,offset:0,size:this.#se.gpuBuffer.size}},{binding:1,resource:x}]})}#ix(i,g,x){return i.createComputePipeline({layout:i.createPipelineLayout({bindGroupLayouts:[x]}),compute:{module:g,entryPoint:"main"}})}#J(){this.redGPUContext.resourceManager.registerManagementResource(this,new ResourceStateBitmapTexture(this))}#re(){this.redGPUContext.resourceManager.unregisterManagementResource(this)}}const mergerNoiseUniformStruct=(i,g)=>[i,g].filter(Boolean).join("\n"),mergerNoiseUniformDefault=(i,g)=>({...i,...g||{}}),mergerNoiseHelperFunctions=(i,g)=>[i,g].filter(Boolean).join("\n");const Ws=Object.values(Xs),Zs={frequency:8,amplitude:1,octaves:1,persistence:.5,lacunarity:2,seed:0,noiseDimension:Xs.MODE_2D};const Js={EUCLIDEAN:0,MANHATTAN:1,CHEBYSHEV:2};Object.freeze(Js);const Qs={F1:0,F2:1,F2_MINUS_F1:2,F1_PLUS_F2:3,CELL_ID:4,CELL_ID_COLOR:5};Object.freeze(Qs);const eo=Object.values(Js),to=Object.values(Qs),ro={frequency:8,distanceScale:1,octaves:1,persistence:.5,lacunarity:2,seed:0,distanceType:Js.EUCLIDEAN,outputType:Qs.F1,jitter:1,cellIdColorIntensity:1};var io=Object.freeze({__proto__:null,ANoiseTexture:ANoiseTexture,mergerNoiseHelperFunctions:mergerNoiseHelperFunctions,mergerNoiseUniformDefault:mergerNoiseUniformDefault,mergerNoiseUniformStruct:mergerNoiseUniformStruct});class IBL extends RedGPUObject{#Zd;#ax;#sx;#ox;#ux;#lx;#cx;#hx;#fx=!1;#al=1;#zd=2e4;constructor(i,g,x=25e3,v=1024,_=512,y=64){super(i);const b=`${g}?key=${v}_${_}_${y}`;this.#cx=_,this.#lx=v,this.#hx=y,this.#zd=x,this.#ax=new DirectCubeTexture(i,`IBL_ENV_${b}`),this.#ox=new DirectCubeTexture(i,`IBL_SPECULAR_${b}`),this.#sx=new DirectCubeTexture(i,`IBL_IRRADIANCE_${b}`);const onLoad=async i=>{i.__addDirtyPipelineListener(this.#dx),i.gpuTexture&&await this.#dx(i)};this.#ux="string"==typeof g?new HDRTexture(i,g,onLoad):new CubeTexture(i,g,!0,onLoad)}get environmentSize(){return this.#lx}get prefilterSize(){return this.#cx}get irradianceSize(){return this.#hx}get irradianceTexture(){return this.#sx}get environmentTexture(){return this.#ax}get prefilterTexture(){return this.#ox}get intensityMultiplier(){return this.#al}set intensityMultiplier(i){this.#al=i}get luminance(){return this.#zd}set luminance(i){this.#zd=i}#dx=async i=>{if(!(i=i||this.#ux)||!i.gpuTexture||this.#fx)return;const{resourceManager:g}=this;this.#fx=!0;try{if(i instanceof HDRTexture){const{equirectangularToCubeGenerator:x}=g,v=await x.generate(i.gpuTexture,this.#lx);this.#Zd=v.gpuTexture}else this.#Zd=i.gpuTexture;await this.#mx()}finally{this.#fx=!1}};async#mx(){const{resourceManager:i}=this,{prefilterGenerator:g,irradianceGenerator:x}=i;if(this.#Zd){this.#ax.gpuTexture=this.#Zd;const i=await g.generate(this.#Zd,this.#cx);this.#ox.gpuTexture=i.gpuTexture;const v=await x.generate(this.#Zd,this.#hx);this.#sx.gpuTexture=v.gpuTexture}}}Object.freeze(IBL);var no=Object.freeze({__proto__:null,ShaderVariantGenerator:ShaderVariantGenerator,WGSLUniformTypes:WGSLUniformTypes,ensureVertexIndexBuiltin:ensureVertexIndexBuiltin,preprocessWGSL:preprocessWGSL}),ao=Object.freeze({__proto__:null,BitmapTexture:BitmapTexture,Core:$s,CoreBuffer:js,CoreIBL:H,CoreNoiseTexture:io,CoreVertexBuffer:Ks,CoreWGSLParser:no,CubeTexture:CubeTexture,DirectCubeTexture:DirectCubeTexture,DirectTexture:DirectTexture,DownSampleCubeMapGenerator:DownSampleCubeMapGenerator,HDRTexture:HDRTexture,IBL:IBL,IndexBuffer:IndexBuffer,MipmapGenerator:MipmapGenerator,NOISE_DIMENSION:Xs,PackedTexture:PackedTexture,Sampler:Sampler,SimplexTexture:class extends ANoiseTexture{#px=Zs.frequency;#gx=Zs.amplitude;#xx=Zs.octaves;#vx=Zs.persistence;#_x=Zs.lacunarity;#yx=Zs.seed;#bx=Zs.noiseDimension;constructor(i,g=1024,x=1024,v,_=!0){super(i,g,x,{...v,mainLogic:v?.mainLogic||"\n\t\t\t\t\t\tlet uv = vec2(\n\t\t\t\t\t\t\t(base_uv.x + uniforms.time * ( uniforms.animationX * uniforms.animationSpeed )) , \n\t\t\t\t\t\t\t(base_uv.y + uniforms.time * ( uniforms.animationY * uniforms.animationSpeed )) \n\t\t\t\t\t\t);\n\t\t\t\t\t\tlet noise = getSimplexNoiseByDimension( uv,uniforms );\n \n let finalColor = vec4(noise, noise, noise, 1.0);\n\t\t\t",uniformStruct:mergerNoiseUniformStruct("\n\t\t\t\t\tnoiseDimension : f32,\n\t\t\t\t\tfrequency: f32,\n\t\t\t\t\tamplitude: f32,\n\t\t\t\t\toctaves: i32,\n\t\t\t\t\tpersistence: f32,\n\t\t\t\t\tlacunarity: f32,\n\t\t\t\t\tseed: f32,\n\t\t\t\t",v?.uniformStruct),uniformDefaults:mergerNoiseUniformDefault(Zs,v?.uniformDefaults),helperFunctions:mergerNoiseHelperFunctions("fn mod289_vec3(x:vec3)->vec3{return x-floor(x*(1.0/289.0))*289.0;}fn mod289_vec2(x:vec2)->vec2{return x-floor(x*(1.0/289.0))*289.0;}fn mod289_vec4(x:vec4)->vec4{return x-floor(x*(1.0/289.0))*289.0;}fn mod289_f32(x:f32)->f32{return x-floor(x*(1.0/289.0))*289.0;}fn permute(x:vec3)->vec3{return mod289_vec3(((x*34.0)+1.0)*x);}fn permute4(x:vec4)->vec4{return mod289_vec4(((x*34.0)+1.0)*x);}fn permute_f32(x:f32)->f32{return mod289_f32(((x*34.0)+1.0)*x);}fn taylorInvSqrt4(r:vec4)->vec4{return 1.79284291400159-0.85373472095314*r;}fn simplex1D(x:f32)->f32{var i=floor(x);let f=fract(x);let g0=select(-1.0,1.0,(permute_f32(i)*.024390243902439)>=0.5);let g1=select(-1.0,1.0,(permute_f32(i+1.0)*.024390243902439)>=0.5);let d0=f;let d1=f-1.0;let t=f*f*f*(f*(f*6.0-15.0)+10.0);let n0=g0*d0;let n1=g1*d1;return mix(n0,n1,t)*0.395;}fn simplex2D(v:vec2)->f32{let C=vec4(0.211324865405187,0.366025403784439,-0.577350269189626,.024390243902439);var i=floor(v+dot(v,C.yy));let x0=v-i+dot(i,C.xx);let i1=select(vec2(.0,1.0),vec2(1.0,.0),x0.x>x0.y);var x12=x0.xyxy+C.xxzz;x12.x=x12.x-i1.x;x12.y=x12.y-i1.y;i=mod289_vec2(i);let p=permute(permute(i.y+vec3(.0,i1.y,1.0))+i.x+vec3(.0,i1.x,1.0));var m=max(0.5-vec3(dot(x0,x0),dot(x12.xy,x12.xy),dot(x12.zw,x12.zw)),vec3(.0));m=m*m;m=m*m;let x=2.0*fract(p*C.www)-1.0;let h=abs(x)-0.5;let ox=floor(x+0.5);let a0=x-ox;m=m*(1.79284291400159-0.85373472095314*(a0*a0+h*h));let g=vec3(a0.x*x0.x+h.x*x0.y,a0.y*x12.x+h.y*x12.y,a0.z*x12.z+h.z*x12.w);return 130.0*dot(m,g);}fn simplex3D(v:vec3)->f32{let C=vec2(1.0/6.0,1.0/3.0);let D=vec4(.0,0.5,1.0,2.0);var i=floor(v+dot(v,C.yyy));let x0=v-i+dot(i,C.xxx);let g=step(x0.yzx,x0.xyz);let l=1.0-g;let i1=min(g.xyz,l.zxy);let i2=max(g.xyz,l.zxy);let x1=x0-i1+C.xxx;let x2=x0-i2+C.yyy;let x3=x0-D.yyy;i=mod289_vec3(i);let p=permute4(permute4(permute4(i.z+vec4(.0,i1.z,i2.z,1.0))+i.y+vec4(.0,i1.y,i2.y,1.0))+i.x+vec4(.0,i1.x,i2.x,1.0));let n_=0.142857142857;let ns=n_*D.wyz-D.xzx;let j=p-49.0*floor(p*ns.z*ns.z);let x_=floor(j*ns.z);let y_=floor(j-7.0*x_);let x=x_*ns.x+ns.yyyy;let y=y_*ns.x+ns.yyyy;let h=1.0-abs(x)-abs(y);let b0=vec4(x.xy,y.xy);let b1=vec4(x.zw,y.zw);let s0=floor(b0)*2.0+1.0;let s1=floor(b1)*2.0+1.0;let sh=-step(h,vec4(.0));let a0=b0.xzyw+s0.xzyw*sh.xxyy;let a1=b1.xzyw+s1.xzyw*sh.zzww;var p0=vec3(a0.xy,h.x);var p1=vec3(a0.zw,h.y);var p2=vec3(a1.xy,h.z);var p3=vec3(a1.zw,h.w);let norm=taylorInvSqrt4(vec4(dot(p0,p0),dot(p1,p1),dot(p2,p2),dot(p3,p3)));p0*=norm.x;p1*=norm.y;p2*=norm.z;p3*=norm.w;var m=max(0.6-vec4(dot(x0,x0),dot(x1,x1),dot(x2,x2),dot(x3,x3)),vec4(.0));m=m*m;return 42.0*dot(m*m,vec4(dot(p0,x0),dot(p1,x1),dot(p2,x2),dot(p3,x3)));}fn fbm1D(pos:f32,octaves:i32)->f32{var value=.0;var amplitude=0.5;var frequency=1.0;var max_value=.0;for(var i=0;i=octaves){break;}value+=simplex1D(pos*frequency)*amplitude;max_value+=amplitude;amplitude*=0.5;frequency*=2.0;}return value/max_value;}fn fbm(pos:vec2,octaves:i32)->f32{var value=.0;var amplitude=0.5;var frequency=1.0;var max_value=.0;for(var i=0;i=octaves){break;}value+=simplex2D(pos*frequency)*amplitude;max_value+=amplitude;amplitude*=0.5;frequency*=2.0;}return value/max_value;}fn fbm3D(pos:vec3,octaves:i32)->f32{var value=.0;var amplitude=0.5;var frequency=1.0;var max_value=.0;for(var i=0;i=octaves){break;}value+=simplex3D(pos*frequency)*amplitude;max_value+=amplitude;amplitude*=0.5;frequency*=2.0;}return value/max_value;}fn getSimplexNoise1D(pos:f32,uniforms:Uniforms)->f32{var total_amplitude:f32=.0;var noise_value:f32=.0;var current_amplitude:f32=1.0;var current_frequency:f32=uniforms.frequency;for(var i:i32=0;i,uniforms:Uniforms)->f32{var total_amplitude:f32=.0;var noise_value:f32=.0;var current_amplitude:f32=1.0;var current_frequency:f32=uniforms.frequency;for(var i:i32=0;i,uniforms:Uniforms)->f32{var total_amplitude:f32=.0;var noise_value:f32=.0;var current_amplitude:f32=1.0;var current_frequency:f32=uniforms.frequency;for(var i:i32=0;i(uniforms.seed))*current_frequency;let octave_noise=simplex3D(noise_pos);noise_value+=octave_noise*current_amplitude;total_amplitude+=current_amplitude;current_amplitude*=uniforms.persistence;current_frequency*=uniforms.lacunarity;}noise_value/=total_amplitude;noise_value*=uniforms.amplitude;let normalized_noise=(noise_value+1.0)*0.5;return normalized_noise;}fn getSimplexNoiseByDimension(uv:vec2,uniforms:Uniforms)->f32{if(uniforms.noiseDimension<1.1){return getSimplexNoise1D(uv.x,uniforms);}else if(uniforms.noiseDimension<2.1){return getSimplexNoise2D(uv,uniforms);}else if(uniforms.noiseDimension<3.1){return getSimplexNoise3D(vec3(uv.x,uv.y,uniforms.seed*0.1),uniforms);}else{return getSimplexNoise2D(uv,uniforms);}}",v?.helperFunctions)},_)}get noiseDimension(){return this.#bx}set noiseDimension(i){Ws.includes(i)?(this.#bx=i,this.updateUniform("noiseDimension",i)):consoleAndThrowError(`Invalid value for noiseDimension. Received ${i}. Expected one of: ${Ws.join(", ")}`)}get frequency(){return this.#px}set frequency(i){validatePositiveNumberRange(i),this.#px=i,this.updateUniform("frequency",i)}get amplitude(){return this.#gx}set amplitude(i){validatePositiveNumberRange(i),this.#gx=i,this.updateUniform("amplitude",i)}get octaves(){return this.#xx}set octaves(i){validateUintRange(i,1,8),this.#xx=i,this.updateUniform("octaves",i)}get persistence(){return this.#vx}set persistence(i){validatePositiveNumberRange(i,0,1),this.#vx=i,this.updateUniform("persistence",i)}get lacunarity(){return this.#_x}set lacunarity(i){validatePositiveNumberRange(i),this.#_x=i,this.updateUniform("lacunarity",i)}get seed(){return this.#yx}set seed(i){this.#yx=i,this.updateUniform("seed",i)}randomizeSeed(){this.seed=1e3*Math.random()}getSettings(){return{frequency:this.#px,amplitude:this.#gx,octaves:this.#xx,persistence:this.#vx,lacunarity:this.#_x,seed:this.#yx}}applySettings(i){void 0!==i.frequency&&(this.frequency=i.frequency),void 0!==i.amplitude&&(this.amplitude=i.amplitude),void 0!==i.octaves&&(this.octaves=i.octaves),void 0!==i.persistence&&(this.persistence=i.persistence),void 0!==i.lacunarity&&(this.lacunarity=i.lacunarity),void 0!==i.seed&&(this.seed=i.seed)}},StorageBuffer:StorageBuffer,UniformBuffer:UniformBuffer,VORONOI_DISTANCE_TYPE:Js,VORONOI_OUTPUT_TYPE:Qs,VertexBuffer:VertexBuffer,VertexInterleaveType:VertexInterleaveType,VertexInterleavedStruct:VertexInterleavedStruct,VoronoiTexture:class extends ANoiseTexture{#px=ro.frequency;#Sx=ro.distanceScale;#xx=ro.octaves;#vx=ro.persistence;#_x=ro.lacunarity;#yx=ro.seed;#Tx=ro.distanceType;#wx=ro.outputType;#Mx=ro.jitter;#Px=ro.cellIdColorIntensity;constructor(i,g=1024,x=1024,v,_=!0){super(i,g,x,{...v,mainLogic:v?.mainLogic||"\n let uv = vec2(\n (base_uv.x + uniforms.time * (uniforms.animationX * uniforms.animationSpeed)),\n (base_uv.y + uniforms.time * (uniforms.animationY * uniforms.animationSpeed))\n );\n var finalColor: vec4;\n if (uniforms.outputType == 5) {\n let colorNoise = getVoronoiColorNoise(uv, uniforms);\n finalColor = vec4(colorNoise, 1.0);\n } else {\n let noise = getVoronoiNoise(uv, uniforms);\n finalColor = vec4(noise, noise, noise, 1.0);\n }\n ",uniformStruct:mergerNoiseUniformStruct("\n frequency: f32,\n distanceScale: f32,\n octaves: i32,\n persistence: f32,\n lacunarity: f32,\n seed: f32,\n distanceType: i32,\n outputType: i32,\n jitter: f32,\n cellIdColorIntensity: f32,\n ",v?.uniformStruct),uniformDefaults:mergerNoiseUniformDefault(ro,v?.uniformDefaults),helperFunctions:mergerNoiseHelperFunctions("fn hash22(p:vec2)->vec2{var p3=fract(vec3(p.xyx)*vec3(0.1031,0.1030,.0973));p3+=dot(p3,p3.yzx+33.33);return fract((p3.xx+p3.yz)*p3.zy);}fn hash12(p:vec2)->f32{var p3=fract(vec3(p.xyx)*0.1031);p3+=dot(p3,p3.yzx+33.33);return fract((p3.x+p3.y)*p3.z);}fn euclideanDistance(a:vec2,b:vec2)->f32{let d=a-b;return sqrt(d.x*d.x+d.y*d.y);}fn manhattanDistance(a:vec2,b:vec2)->f32{let d=abs(a-b);return d.x+d.y;}fn chebyshevDistance(a:vec2,b:vec2)->f32{let d=abs(a-b);return max(d.x,d.y);}fn calculateDistance(a:vec2,b:vec2,distanceType:i32)->f32{switch(distanceType){case 0:{return euclideanDistance(a,b);}case 1:{return manhattanDistance(a,b);}case 2:{return chebyshevDistance(a,b);}default:{return euclideanDistance(a,b);}}}fn cellIdToColor(cellId:f32,intensity:f32)->vec3{let h=cellId*6.28318;let s=0.7+0.3*fract(cellId*7.0);let v=0.6+0.4*fract(cellId*13.0);let c=v*s;let x=c*(1.0-abs(((h/1.047198)% 2.0)-1.0));let m=v-c;var rgb:vec3;let sector=i32(h/1.047198)% 6;switch(sector){case 0:{rgb=vec3(c,x,.0);}case 1:{rgb=vec3(x,c,.0);}case 2:{rgb=vec3(.0,c,x);}case 3:{rgb=vec3(.0,x,c);}case 4:{rgb=vec3(x,.0,c);}default:{rgb=vec3(c,.0,x);}}return(rgb+m)*intensity;}struct VoronoiResult{f1:f32,f2:f32,cellId:f32,}fn voronoiSingle(pos:vec2,frequency:f32,seed:f32,jitter:f32,distanceType:i32)->VoronoiResult{let scaledPos=pos*frequency;let gridPos=floor(scaledPos);let localPos=fract(scaledPos);var minDist1=999.0;var minDist2=999.0;var closestCellId=.0;for(var y=-1;y<=1;y++){for(var x=-1;x<=1;x++){let neighborGrid=gridPos+vec2(f32(x),f32(y));let randomOffset=hash22(neighborGrid+seed);let jitteredOffset=mix(vec2(0.5),randomOffset,jitter);let cellPoint=vec2(f32(x),f32(y))+jitteredOffset;let dist=calculateDistance(localPos,cellPoint,distanceType);if(dist,uniforms:Uniforms)->f32{var total=.0;var frequency=uniforms.frequency;var amplitude=1.0;var maxValue=.0;for(var i=0;i,uniforms:Uniforms)->vec3{if(uniforms.outputType==5){let voronoiResult=voronoiSingle(uv,uniforms.frequency,uniforms.seed,uniforms.jitter,uniforms.distanceType);return cellIdToColor(voronoiResult.cellId,uniforms.cellIdColorIntensity);}else{let grayValue=getVoronoiNoise(uv,uniforms);return vec3(grayValue,grayValue,grayValue);}}",v?.helperFunctions)},_)}get frequency(){return this.#px}set frequency(i){validatePositiveNumberRange(i),this.#px=i,this.updateUniform("frequency",i)}get distanceScale(){return this.#Sx}set distanceScale(i){validatePositiveNumberRange(i),this.#Sx=i,this.updateUniform("distanceScale",i)}get octaves(){return this.#xx}set octaves(i){validateUintRange(i,1,8),this.#xx=i,this.updateUniform("octaves",i)}get persistence(){return this.#vx}set persistence(i){validatePositiveNumberRange(i,0,1),this.#vx=i,this.updateUniform("persistence",i)}get lacunarity(){return this.#_x}set lacunarity(i){validatePositiveNumberRange(i),this.#_x=i,this.updateUniform("lacunarity",i)}get seed(){return this.#yx}set seed(i){this.#yx=i,this.updateUniform("seed",i)}get distanceType(){return this.#Tx}set distanceType(i){eo.includes(i)?(this.#Tx=i,this.updateUniform("distanceType",i)):consoleAndThrowError(`Invalid value for distanceType. Received ${i}. Expected one of: ${eo.join(", ")}`)}get outputType(){return this.#wx}set outputType(i){to.includes(i)?(this.#wx=i,this.updateUniform("outputType",i)):consoleAndThrowError(`Invalid value for outputType. Received ${i}. Expected one of: ${to.join(", ")}`)}get jitter(){return this.#Mx}set jitter(i){validatePositiveNumberRange(i,0,1),this.#Mx=i,this.updateUniform("jitter",i)}get cellIdColorIntensity(){return this.#Px}set cellIdColorIntensity(i){validatePositiveNumberRange(i),this.#Px=i,this.updateUniform("cellIdColorIntensity",i)}randomizeSeed(){this.seed=1e3*Math.random()}setEuclideanDistance(){this.distanceType=Js.EUCLIDEAN}setManhattanDistance(){this.distanceType=Js.MANHATTAN}setChebyshevDistance(){this.distanceType=Js.CHEBYSHEV}setF1Output(){this.outputType=Qs.F1}setF2Output(){this.outputType=Qs.F2}setCrackPattern(){this.outputType=Qs.F2_MINUS_F1}setSmoothBlend(){this.outputType=Qs.F1_PLUS_F2}setCellIdOutput(){this.outputType=Qs.CELL_ID}setCellIdColorOutput(){this.outputType=Qs.CELL_ID_COLOR}setCellularPattern(){this.outputType=Qs.F1,this.distanceType=Js.EUCLIDEAN,this.jitter=1}setStonePattern(){this.outputType=Qs.F2_MINUS_F1,this.distanceType=Js.EUCLIDEAN,this.jitter=.8}setOrganicPattern(){this.distanceType=Js.MANHATTAN,this.jitter=.6}setGridPattern(){this.jitter=0,this.distanceType=Js.EUCLIDEAN}setCrystalPattern(){this.outputType=Qs.F2_MINUS_F1,this.distanceType=Js.CHEBYSHEV,this.jitter=.9}setStainedGlassPattern(){this.outputType=Qs.CELL_ID_COLOR,this.distanceType=Js.EUCLIDEAN,this.jitter=.7,this.cellIdColorIntensity=.8}setMosaicPattern(){this.outputType=Qs.CELL_ID_COLOR,this.distanceType=Js.MANHATTAN,this.jitter=.3,this.cellIdColorIntensity=1}setBiomeMapPattern(){this.outputType=Qs.CELL_ID,this.distanceType=Js.EUCLIDEAN,this.jitter=.8,this.frequency=4}getSettings(){return{frequency:this.#px,distanceScale:this.#Sx,octaves:this.#xx,persistence:this.#vx,lacunarity:this.#_x,seed:this.#yx,distanceType:this.#Tx,outputType:this.#wx,jitter:this.#Mx,cellIdColorIntensity:this.#Px}}applySettings(i){void 0!==i.frequency&&(this.frequency=i.frequency),void 0!==i.distanceScale&&(this.distanceScale=i.distanceScale),void 0!==i.octaves&&(this.octaves=i.octaves),void 0!==i.persistence&&(this.persistence=i.persistence),void 0!==i.lacunarity&&(this.lacunarity=i.lacunarity),void 0!==i.seed&&(this.seed=i.seed),void 0!==i.distanceType&&(this.distanceType=i.distanceType),void 0!==i.outputType&&(this.outputType=i.outputType),void 0!==i.jitter&&(this.jitter=i.jitter),void 0!==i.cellIdColorIntensity&&(this.cellIdColorIntensity=i.cellIdColorIntensity)}getDistanceTypeName(){return{[Js.EUCLIDEAN]:"Euclidean",[Js.MANHATTAN]:"Manhattan",[Js.CHEBYSHEV]:"Chebyshev"}[this.#Tx]||"Unknown"}getOutputTypeName(){return{[Qs.F1]:"F1",[Qs.F2]:"F2",[Qs.F2_MINUS_F1]:"F2-F1 (Crack)",[Qs.F1_PLUS_F2]:"F1+F2 (Blend)",[Qs.CELL_ID]:"Cell ID",[Qs.CELL_ID_COLOR]:"Cell ID Color"}[this.#wx]||"Unknown"}},parseWGSL:parseWGSL});class GltfAnimationLooperManager{#Rx=60;#Cx=1e3/this.#Rx;#rc=0;#Bx=0;render=(i,g,x,v)=>{const _=g;this.#rc;this.#Cx,this.#rc=_,this.#Bx++;const y=Tt,b=180/Math.PI;let S,w,L,k,H,z,q,W,be,je,Ke,Xe,Ye,Ze,Je,Qe,et,tt,it,ft,pt,xt,vt,yt,bt,St,wt,Mt,Pt,Rt,Ct,Bt,Dt,Et,It,At,Lt,Ut,kt,Gt,Ot,Vt,Nt,Ft,Ht,zt,$t,jt,Kt,Xt,qt,Yt,Wt,Zt,Jt,Qt,er,tr,rr,ir,nr,ar,sr,or,ur,lr,cr,hr,fr=v.length;for(;fr--;){nr=v[fr],ir=nr.targetGLTFParsedSingleClip,rr=ir.length;const _=ir.maxTime;for(;rr--;){ar=ir[rr],sr=ar.cacheTable;const{animationTargetMesh:v,timeAnimationInfo:Tt,aniDataAnimationInfo:fr,weightMeshes:dr}=ar;v.dirtyTransform=!0,Jt=(g-nr.startTime)%(1e3*_)/1e3,lr=Tt.dataList,cr=fr.dataList,hr=lr.length;const mr=ar.lastPrevIdx||0;if(mr=lr[hr-1])ur=hr-1,or=0;else{let i=0,g=hr-1;for(;i>1;lr[x]<=Jt?i=x:g=x}ur=i,or=g}else if(Jt<=lr[0])ur=hr-1,or=0;else if(Jt>=lr[hr-1])ur=hr-1,or=0;else{let i=0,g=hr-1;for(;i>1;lr[x]<=Jt?i=x:g=x}ur=i,or=g}let pr,gr,xr,vr,_r,yr,br;ar.lastPrevIdx=ur,Qt=lr[ur],er=lr[or];const Sr=ar.interpolation;if("CUBICSPLINE"==Sr){const i=er-Qt;tr=i==i?i:0;const g=(Jt-Qt)/tr;pr=g==g?g:0,gr=pr*pr,xr=gr*pr,yr=-2*xr+3*gr,br=xr-gr,vr=1-yr,_r=br-gr+pr}else if("STEP"==Sr)tr=0;else{const i=(Jt-Qt)/(er-Qt);tr=i==i?i:0}switch(ar.key){case"rotation":if(ur!==hr-1){if("CUBICSPLINE"===Sr){let i,g,x,v,_,y,b,Je;kt=12*ur,Gt=12*or,S=cr[kt+4],w=cr[kt+5],L=cr[kt+6],k=cr[kt+7],H=S*S+w*w+L*L+k*k,H>0?(z=1/Math.sqrt(H),q=S*z,W=w*z,be=L*z,je=k*z):(q=W=be=0,je=1),S=cr[kt+8],w=cr[kt+9],L=cr[kt+10],k=cr[kt+11],H=S*S+w*w+L*L+k*k,H>0?(z=1/Math.sqrt(H),i=S*z,g=w*z,x=L*z,v=k*z):(i=g=x=0,v=1),S=cr[Gt],w=cr[Gt+1],L=cr[Gt+2],k=cr[Gt+3],H=S*S+w*w+L*L+k*k,H>0?(z=1/Math.sqrt(H),_=S*z,y=w*z,b=L*z,Je=k*z):(_=y=b=0,Je=1),S=cr[Gt+4],w=cr[Gt+5],L=cr[Gt+6],k=cr[Gt+7],H=S*S+w*w+L*L+k*k,H>0?(z=1/Math.sqrt(H),Ke=S*z,Xe=w*z,Ye=L*z,Ze=k*z):(Ke=Xe=Ye=0,Ze=1),S=vr*q+_r*i*tr+yr*Ke+br*_*tr,w=vr*W+_r*g*tr+yr*Xe+br*y*tr,L=vr*be+_r*x*tr+yr*Ye+br*b*tr,k=vr*je+_r*v*tr+yr*Ze+br*Je*tr}else{kt=ur<<2,Gt=or<<2;const i=kt<<16|Gt;let g=sr[i];g?(Je=g[0],q=g[1],W=g[2],be=g[3],je=g[4],Ke=g[5],Xe=g[6],Ye=g[7],Ze=g[8]):(S=cr[kt],w=cr[kt+1],L=cr[kt+2],k=cr[kt+3],H=S*S+w*w+L*L+k*k,H>0?(z=1/Math.sqrt(H),q=S*z,W=w*z,be=L*z,je=k*z):(q=W=be=0,je=1),S=cr[Gt],w=cr[Gt+1],L=cr[Gt+2],k=cr[Gt+3],H=S*S+w*w+L*L+k*k,H>0?(z=1/Math.sqrt(H),Ke=S*z,Xe=w*z,Ye=L*z,Ze=k*z):(Ke=Xe=Ye=0,Ze=1),Je=q*Ke+W*Xe+be*Ye+je*Ze,Je<0&&(Je=-Je,Ke=-Ke,Xe=-Xe,Ye=-Ye,Ze=-Ze),g=new Float32Array(9),g[0]=Je,g[1]=q,g[2]=W,g[3]=be,g[4]=je,g[5]=Ke,g[6]=Xe,g[7]=Ye,g[8]=Ze,sr[i]=g),1-Je>y?(Qe=Math.acos(Je),et=Math.sin(Qe),tt=Math.sin((1-tr)*Qe)/et,it=Math.sin(tr*Qe)/et):(tt=1-tr,it=tr),S=tt*q+it*Ke,w=tt*W+it*Xe,L=tt*be+it*Ye,k=tt*je+it*Ze}ft=S+S,pt=w+w,xt=L+L,vt=S*ft,yt=S*pt,bt=S*xt,St=w*pt,wt=w*xt,Mt=L*xt,Pt=k*ft,Rt=k*pt,Ct=k*xt,Et=bt+Rt,Bt=1-(St+Mt),Dt=yt-Ct,At=wt-Pt,Ut=1-(vt+St),Lt=wt+Pt,It=1-(vt+Mt),w=Math.asin(Math.max(-1,Math.min(1,Et))),Math.abs(Et)<.99999?(S=Math.atan2(-At,Ut),L=Math.atan2(-Dt,Bt)):(S=Math.atan2(Lt,It),L=0),v.rotationX=S*b,v.rotationY=w*b,v.rotationZ=L*b}break;case"translation":"CUBICSPLINE"===Sr?ur!==hr-1&&(kt=9*ur,Ot=cr[kt+3],Vt=cr[kt+4],Nt=cr[kt+5],Xt=cr[kt+6],qt=cr[kt+7],Yt=cr[kt+8],Gt=9*or,$t=cr[Gt],jt=cr[Gt+1],Kt=cr[Gt+2],Ft=cr[Gt+3],Ht=cr[Gt+4],zt=cr[Gt+5],Wt=Xt*tr,Zt=$t*tr,v.x=vr*Ft+_r*Wt+yr*Ot+br*Zt,Wt=qt*tr,Zt=jt*tr,v.y=vr*Ht+_r*Wt+yr*Vt+br*Zt,Wt=Yt*tr,Zt=Kt*tr,v.z=vr*zt+_r*Wt+yr*Nt+br*Zt):(kt=3*or,Ot=cr[kt],Vt=cr[kt+1],Nt=cr[kt+2],Gt=3*ur,Ft=cr[Gt],Ht=cr[Gt+1],zt=cr[Gt+2],v.x=Ft+tr*(Ot-Ft),v.y=Ht+tr*(Vt-Ht),v.z=zt+tr*(Nt-zt));break;case"scale":"CUBICSPLINE"===Sr?ur!==hr-1&&(kt=9*ur,Ot=cr[kt+3],Vt=cr[kt+4],Nt=cr[kt+5],Xt=cr[kt+6],qt=cr[kt+7],Yt=cr[kt+8],Gt=9*or,$t=cr[Gt],jt=cr[Gt+1],Kt=cr[Gt+2],Ft=cr[Gt+3],Ht=cr[Gt+4],zt=cr[Gt+5],Wt=Xt*tr,Zt=$t*tr,v.scaleX=vr*Ft+_r*Wt+yr*Ot+br*Zt,Wt=qt*tr,Zt=jt*tr,v.scaleY=vr*Ht+_r*Wt+yr*Vt+br*Zt,Wt=Yt*tr,Zt=Kt*tr,v.scaleZ=vr*zt+_r*Wt+yr*Nt+br*Zt):(kt=3*or,Ot=cr[kt],Vt=cr[kt+1],Nt=cr[kt+2],Gt=3*ur,Ft=cr[Gt],Ht=cr[Gt+1],zt=cr[Gt+2],v.scaleX=Ft+tr*(Ot-Ft),v.scaleY=Ht+tr*(Vt-Ht),v.scaleZ=zt+tr*(Nt-zt));break;case"weights":{let g=dr.length;for(;g--;)ar.renderWeight(i,x,dr[g],tr,ur,or);break}}}}}}var so="struct Uniforms{backgroundColor:vec4}@group(1)@binding(0)var _sampler:sampler;@group(1)@binding(1)var _texture:texture_2d;@group(1)@binding(2)varuniforms:Uniforms;@fragment fn main(@location(0)fragUV:vec2)->@location(0)vec4{var viewColor:vec4=textureSample(_texture,_sampler,fragUV);let backgroundColor=uniforms.backgroundColor;let blendedColor=vec4(viewColor.rgb+backgroundColor.rgb*(1.0-viewColor.a),viewColor.a+backgroundColor.a*(1.0-viewColor.a));return blendedColor;}",oo="struct VertexUniforms{modelMatrix:mat4x4,};@group(0)@binding(0)varvertexUniforms:VertexUniforms;struct VertexOutput{@builtin(position)Position:vec4,@location(0)fragUV:vec2,};@vertex fn main(@builtin(vertex_index)VertexIndex:u32)->VertexOutput{var pos=array,6>(vec2(1.0,1.0),vec2(1.0,-1.0),vec2(-1.0,-1.0),vec2(1.0,1.0),vec2(-1.0,-1.0),vec2(-1.0,1.0),);var uv=array,6>(vec2(1.0,.0),vec2(1.0,1.0),vec2(.0,1.0),vec2(1.0,.0),vec2(.0,1.0),vec2(.0,.0),);var output:VertexOutput;output.Position=vertexUniforms.modelMatrix*vec4(pos[VertexIndex],.0,1.0);output.fragUV=uv[VertexIndex];return output;}";const uo=parseWGSL("FINAL_RENDER_VERTEX",oo),lo=parseWGSL("FINAL_RENDER_FRAGMENT",so),co=uo.uniforms.vertexUniforms;class FinalRender{#Dx=[];#Ex=[];#Ix;#Ax;#Lx;#Ux;#kx;#Gx=[];#U;#ne;#Ox=[];#Vx=[];#ls;constructor(){}render(i,g){const{sizeManager:x,antialiasingManager:v,commandEncoderManager:_}=i,{msaaID:y}=v,{pixelRectObject:b}=x,{width:S,height:w}=b;if(0===S||0===w)return;const L=this.#ls!==y,k=this.#Nx(i);_.addMainRenderPass(k,x=>{x.setViewport(0,0,S,w,0,1),x.setScissorRect(0,0,S,w),this.#Ix&&!L||(this.#Fx(i),this.#Gx=[]),this.#Hx(i,x,g.map(i=>{const g=i.colorAttachments[0];return g.postEffectView||g.pickingView||g.resolveTarget||g.view}),S,w,L)}),this.#ls=y}#zx(i,g){{const{scene:x,redGPUContext:v}=i,{gpuDevice:_}=v,{backgroundColor:y,useBackgroundColor:b}=x,S=b?y.rgbaNormal:[0,0,0,0],w=v.backgroundColor.rgbaNormal;let L;const k=[S[0]*S[3],S[1]*S[3],S[2]*S[3],S[3]],H=[w[0]*w[3],w[1]*w[3],w[2]*w[3],w[3]];L=[k[0]+H[0]*(1-S[3]),k[1]+H[1]*(1-S[3]),k[2]+H[2]*(1-S[3]),S[3]+w[3]*(1-S[3])],this.#Vx[g][0]=L[0],this.#Vx[g][1]=L[1],this.#Vx[g][2]=L[2],this.#Vx[g][3]=L[3],_.queue.writeBuffer(this.#Ox[g],0,this.#Vx[g])}}#Hx(i,g,x,v,_,y){const{gpuDevice:b}=i;x.forEach((x,S)=>{const w=i.viewList[S],{x:L,y:k,width:H,height:z}=w.pixelRectObject,q=create$4();Dt(q,0,1,0,1,-1e3,1e3),scale$4(q,q,[1/v,1/_,1]),translate(q,q,[H/2+L,_-z/2-k,0]),scale$4(q,q,[H/2,z/2,1]),this.#$x(i,S);const W=this.#Dx[S],be=this.#Ex[S];b.queue.writeBuffer(W.gpuBuffer,co.members.modelMatrix.uniformOffset,q),this.#Gx[S]&&!y||(this.#Gx[S]=null,this.#Gx[S]=new WeakMap);let je=this.#Gx[S].get(x);if(!je){const i={layout:this.#Ux,label:"FRAGMENT_BIND_GROUP_DESCRIPTOR_FINAL_RENDER",entries:[{binding:0,resource:this.#ne.gpuSampler},{binding:1,resource:x},{binding:2,resource:{buffer:this.#Ox[S],offset:0,size:this.#Ox[S].size}}]};je=b.createBindGroup(i),this.#Gx[S].set(x,je)}this.#zx(w,S),g.setPipeline(this.#jx(i,y)),g.setBindGroup(0,be),g.setBindGroup(1,je),g.draw(6,1,0,0)})}#Fx(i){const{resourceManager:g}=i;this.#Ix=g.createBindGroupLayout("FINAL_RENDER_VERTEX_BIND_GROUP_LAYOUT",getVertexBindGroupLayoutDescriptorFromShaderInfo(uo,0)),this.#Ax=g.createGPUShaderModule("VERTEX_MODULE_FINAL_RENDER",{code:oo}),this.#Lx={module:this.#Ax,entryPoint:"main"},this.#kx=g.createGPUShaderModule("FRAGMENT_MODULE_FINAL_RENDER",{code:so}),this.#Ux=g.createBindGroupLayout("FINAL_RENDER_BIND_GROUP_LAYOUT",getFragmentBindGroupLayoutDescriptorFromShaderInfo(lo,1)),this.#ne=new Sampler(i,{minFilter:"linear"})}#$x(i,g){const{gpuDevice:x}=i;if(!this.#Dx[g]){const v=new ArrayBuffer(co.arrayBufferByteLength),_=this.#Dx[g]=new UniformBuffer(i,v,`FinalRender_View(${g})_VertexUniform`),y={layout:this.#Ix,label:"VERTEX_BIND_GROUP_DESCRIPTOR_FINAL_RENDER",entries:[{binding:0,resource:{buffer:_.gpuBuffer,offset:0,size:_.size}}]};this.#Ex[g]=x.createBindGroup(y)}this.#Ox[g]||(this.#Ox[g]=i.gpuDevice.createBuffer({label:`FINAL_RENDER_FRAGMENT_BUFFER_${g}`,size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.#Vx[g]=new Float32Array([1,0,0,1]))}#Nx(i){const{gpuContext:g}=i;return{colorAttachments:[{view:g.getCurrentTexture().createView({label:"FINAL_RENDER"}),clearValue:{r:0,g:0,b:0,a:0},loadOp:z.CLEAR,storeOp:q.STORE}]}}#jx(i,g){if(!this.#U||g){const{gpuDevice:g}=i,x={label:"PIPELINE_DESCRIPTOR_FINAL_RENDER",layout:g.createPipelineLayout({label:"FINAL_RENDER_PIPELINE_LAYOUT",bindGroupLayouts:[this.#Ix,this.#Ux]}),vertex:this.#Lx,fragment:{module:this.#kx,entryPoint:"main",targets:[{format:navigator.gpu.getPreferredCanvasFormat(),blend:{color:{srcFactor:ui.SRC_ALPHA,dstFactor:ui.ONE_MINUS_SRC_ALPHA,operation:li.ADD},alpha:{srcFactor:ui.SRC_ALPHA,dstFactor:ui.ONE_MINUS_SRC_ALPHA,operation:li.ADD}}}]}};this.#U=g.createRenderPipeline(x)}return this.#U}}const haltonSequence=(i,g)=>{let x=0,v=1,_=i;for(;_>0;)v/=g,x+=v*(_%g),_=Math.floor(_/g);return x};class Renderer{#Kx;#Xx=new GltfAnimationLooperManager;constructor(){}start(i,g){cancelAnimationFrame(i.currentRequestAnimationFrame);const HD_render=x=>{g?.(x),i.currentTime=x,this.renderFrame(i,x),i.currentRequestAnimationFrame=requestAnimationFrame(HD_render)};i.currentRequestAnimationFrame=requestAnimationFrame(HD_render)}stop(i){cancelAnimationFrame(i.currentRequestAnimationFrame),i.currentRequestAnimationFrame=null}renderFrame(i,g){this.#Kx||(this.#Kx=new FinalRender);const x=[];{let g=0;const v=i.viewList.length;for(;g{const _=i.viewList[v];_.pickingManager?.checkEvents(_,g),_.postEffectManager.autoExposure.resolveReadback()})}renderView(i){const{redGPUContext:g,camera:x,pickingManager:v,pixelRectObject:_,renderViewStateData:y}=i,{colorAttachment:b,depthStencilAttachment:S,gBufferNormalTextureAttachment:w,gBufferMotionVectorTextureAttachment:L}=this.#qx(i),k={label:`${i.name} Basic Render Pass`,colorAttachments:[b,w,L],depthStencilAttachment:S};if(i.renderViewStateData.reset(),_.width&&_.height){const{scene:_}=i,{lightManager:b,shadowManager:w}=_;(b.pointLightCount||b.spotLightCount)&&i.clusterLightManager.updateClusterLights();DrawBufferManager.getInstance(g).flushAllCommands(y);if(y.numFixedSteps>0){const{scene:g}=i;if(g.physicsEngine){let i=y.numFixedSteps;for(;i--;)g.physicsEngine.step(y.fixedStepDeltaTime)}}x.update?.(i,g.currentTime),(i=>{const{taa:g}=i,x=g.frameIndex||0,v=g.jitterStrength,_=x%16,y=(haltonSequence(_+1,2)-.5)/1*v,b=(haltonSequence(_+1,3)-.5)/1*v;i.setJitterOffset(y,b)})(i),i.update(!0,!1,null),w.render(i);const L=i.viewRenderTextureManager.getGBufferTextureView(Ri.RENDER_PATH1_RESULT);i.update(!1,!0,L),this.#Yx(i,k),this.#Wx(i,k,S),v.render(i)}return k.colorAttachments[0].postEffectView=i.postEffectManager.render().textureView,((i,g,x)=>{const{animationList:v,skinList:_}=g,y=_.length,b=v.length;if(!y&&!b)return;const{gpuDevice:S,commandEncoderManager:w}=i;w.addPreProcessComputePass("ProcessAnimationsAndSkinning_ComputePass",w=>{b&&x.render(i,g.timestamp,w,v.flat());for(let g=0;g{updateViewportAndScissor(i,g,"DEFAULT"),x.currentRenderPassEncoder=g,v&&v.render(x),_&&_.renderBackground(x),b&&b.render(x),((i,g)=>{const{renderViewStateData:x,scene:v}=i;x.currentRenderPassEncoder=g;const{children:_}=v;let y=0;const b=_.length;for(;y{const{renderViewStateData:x,rawCamera:v}=i;x.currentRenderPassEncoder=g;const{bundleListAlphaLayer:_,bundleListTransparentLayer:y,bundleListParticleLayer:b}=x.renderBundleResults;_.length&&g.executeBundles(_);const{x:S,y:w,z:L}=v;y.length&&g.executeBundles(sortTransparentObjects({x:S,y:w,z:L},y)),b.length&&g.executeBundles(b)})(i,g)})}#Wx(i,g,x){const{redGPUContext:v,renderViewStateData:_}=i,{antialiasingManager:y,commandEncoderManager:b}=v,{useMSAA:S}=y;if(i.renderViewStateData.renderBundleResults.bundleListRender2PathLayer.length){const{mipmapGenerator:y}=v.resourceManager;let w=i.viewRenderTextureManager.getGBufferTexture(Ri.RENDER_PATH1_RESULT),L=S?i.viewRenderTextureManager.getGBufferResolveTexture(Ri.COLOR):i.viewRenderTextureManager.getGBufferTexture(Ri.COLOR);L||(S?console.error("MSAA가 활성화되어 있지만 G-Buffer Color Resolve 텍스처가 정의되지 않았습니다"):console.error("G-Buffer Color 텍스처가 정의되지 않았습니다")),b.useEncoder(k.MAIN,g=>{g.copyTextureToTexture({texture:L},{texture:w},{width:i.pixelRectObject.width,height:i.pixelRectObject.height,depthOrArrayLayers:1})}),y.generateMipmap(w,i.viewRenderTextureManager.renderPath1ResultTextureDescriptor,!0,k.MAIN),b.addMainRenderPass({label:`${i.name} 2Path Render Pass`,colorAttachments:[...g.colorAttachments].map(i=>({...i,loadOp:z.LOAD})),depthStencilAttachment:{...x,depthLoadOp:z.LOAD}},g=>{updateViewportAndScissor(i,g),g.executeBundles(_.renderBundleResults.bundleListRender2PathLayer)})}}#qx(i){const{redGPUContext:g,viewRenderTextureManager:x}=i,{antialiasingManager:v}=g,{useMSAA:_}=v,y=x.depthTextureView,b=x.getGBufferTextureView(Ri.COLOR),S=x.getGBufferTextureView(Ri.NORMAL),w=x.getGBufferTextureView(Ri.MOTION_VECTOR),L={view:b,clearValue:{r:0,g:0,b:0,a:0},loadOp:z.CLEAR,storeOp:q.STORE},k={view:y,depthClearValue:1,depthLoadOp:z.CLEAR,depthStoreOp:q.STORE},H={view:S,clearValue:{r:0,g:0,b:0,a:0},loadOp:z.CLEAR,storeOp:q.STORE},W={view:w,clearValue:{r:0,g:0,b:0,a:0},loadOp:z.CLEAR,storeOp:q.STORE};return _&&(L.resolveTarget=x.getGBufferResolveTextureView(Ri.COLOR),H.resolveTarget=x.getGBufferResolveTextureView(Ri.NORMAL),W.resolveTarget=x.getGBufferResolveTextureView(Ri.MOTION_VECTOR)),{colorAttachment:L,depthStencilAttachment:k,gBufferNormalTextureAttachment:H,gBufferMotionVectorTextureAttachment:W}}}var ho=Object.freeze({__proto__:null,isHexColor:isHexColor,isUint:isUint,validateNumber:validateNumber,validateNumberRange:validateNumberRange,validatePositiveNumberRange:validatePositiveNumberRange,validateRedGPUContext:validateRedGPUContext,validateUintRange:validateUintRange});class BrightnessContrast extends ASinglePassPostEffect{constructor(i){super(i),this.isLdr=!0,this.init(i,"POST_EFFECT_BRIGHTNESS_CONTRAST",createBasicPostEffectCode(this,"let index=global_id.xy;var color:vec4=textureLoad(sourceTexture,index,0);let brightness_value:f32=uniforms.brightness/255.0;let contrast_value:f32=uniforms.contrast/255.0;var tempColor:vec3;if(contrast_value>.0){tempColor=(color.rgb-0.5)/(1.0-contrast_value)+0.5;}else{tempColor=(color.rgb-0.5)*(1.0+contrast_value)+0.5;}color=vec4(tempColor+brightness_value,color.a);textureStore(outputTexture,index,color);","struct Uniforms{brightness:f32,contrast:f32};"))}}defineNumber(BrightnessContrast,[{key:"brightness",value:0,min:-150,max:150},{key:"contrast",value:0,min:-50,max:100}]),Object.freeze(BrightnessContrast);class ColorBalance extends ASinglePassPostEffect{constructor(i){super(i),this.isLdr=!0,this.init(i,"POST_EFFECT_COLOR_BALANCE",createBasicPostEffectCode(this,"let index=global_id.xy;var color:vec4=textureLoad(sourceTexture,index,0);let original_luminance=getLuminance(color.rgb);let shadow_weight=1.0-smoothstep(.0,0.5,original_luminance);let highlight_weight=smoothstep(0.5,1.0,original_luminance);let midtone_weight=1.0-shadow_weight-highlight_weight;let cyan_red=shadow_weight*uniforms.shadowCyanRed+midtone_weight*uniforms.midtoneCyanRed+highlight_weight*uniforms.highlightCyanRed;let magenta_green=shadow_weight*uniforms.shadowMagentaGreen+midtone_weight*uniforms.midtoneMagentaGreen+highlight_weight*uniforms.highlightMagentaGreen;let yellow_blue=shadow_weight*uniforms.shadowYellowBlue+midtone_weight*uniforms.midtoneYellowBlue+highlight_weight*uniforms.highlightYellowBlue;color.r+=cyan_red*.01;color.g+=magenta_green*.01;color.b+=yellow_blue*.01;let adjusted_luminance=getLuminance(color.rgb);if(uniforms.preserveLuminosity==1u&&adjusted_luminance>.0){let ratio=original_luminance/adjusted_luminance;color=vec4(color.rgb*ratio,color.a);}textureStore(outputTexture,index,color);","#redgpu_include color.getLuminance struct Uniforms{shadowCyanRed:f32,shadowMagentaGreen:f32,shadowYellowBlue:f32,midtoneCyanRed:f32,midtoneMagentaGreen:f32,midtoneYellowBlue:f32,highlightCyanRed:f32,highlightMagentaGreen:f32,highlightYellowBlue:f32,preserveLuminosity:u32};"))}}defineBoolean(ColorBalance,[{key:"preserveLuminosity",value:!0}]),defineNumber(ColorBalance,[{key:"highlightYellowBlue",value:0,min:-100,max:100},{key:"highlightMagentaGreen",value:0,min:-100,max:100},{key:"highlightCyanRed",value:0,min:-100,max:100},{key:"midtoneYellowBlue",value:0,min:-100,max:100},{key:"midtoneMagentaGreen",value:0,min:-100,max:100},{key:"midtoneCyanRed",value:0,min:-100,max:100},{key:"shadowYellowBlue",value:0,min:-100,max:100},{key:"shadowMagentaGreen",value:0,min:-100,max:100},{key:"shadowCyanRed",value:0,min:-100,max:100}]),Object.freeze(ColorBalance);class ColorTemperatureTint extends ASinglePassPostEffect{constructor(i){super(i),this.isLdr=!0,this.init(i,"POST_EFFECT_COLOR_TEMPERATURE_TINT",createBasicPostEffectCode(this,"let index=global_id.xy;var color:vec4=textureLoad(sourceTexture,index,0);let temp=uniforms.temperature;var tempRGB:vec3;if(temp<=6600.0){tempRGB.r=1.0;}else{let t=temp-6600.0;tempRGB.r=clamp(1.292936*pow(t,-0.1332047),.0,1.0);}if(temp<=6600.0){let t=temp;tempRGB.g=clamp(0.39008157*log(t)-0.63184144,.0,1.0);}else{let t=temp-6600.0;tempRGB.g=clamp(1.292936*pow(t,-0.1332047),.0,1.0);}if(temp>=6600.0){tempRGB.b=1.0;}else if(temp<=1900.0){tempRGB.b=.0;}else{let t=temp-1000.0;tempRGB.b=clamp(0.543206789*log(t)-1.19625408,.0,1.0);}let neutralTemp:vec3=vec3(1.0,1.0,1.0);let tempAdjust:vec3=tempRGB/neutralTemp;let tintValue=uniforms.tint*.01;var tintRGB:vec3;if(tintValue>=.0){tintRGB=vec3(1.0-tintValue*0.2,1.0,1.0-tintValue*0.2);}else{let mag=-tintValue;tintRGB=vec3(1.0,1.0-mag*0.2,1.0);}let colorAdjust=tempAdjust*tintRGB;let finalAdjust=mix(vec3(1.0),colorAdjust,uniforms.amount);color=vec4(color.rgb*finalAdjust,color.a);color=vec4(clamp(color.rgb,vec3(.0),vec3(1.0)),color.a);textureStore(outputTexture,index,color);","struct Uniforms{temperature:f32,tint:f32,amount:f32};")),this.temperature=6500,this.amount=1,this.tint=0}setWarmTone(){this.temperature=3200,this.tint=-10}setCoolTone(){this.temperature=8e3,this.tint=10}setNeutral(){this.temperature=6500,this.tint=0}setCandleLight(){this.temperature=1900,this.tint=-5}setDaylight(){this.temperature=5600,this.tint=0}setCloudyDay(){this.temperature=7500,this.tint=5}setNeonLight(){this.temperature=9e3,this.tint=15}}definePositiveNumber(ColorTemperatureTint,[{key:"temperature",value:6500,min:1e3,max:2e4},{key:"amount",value:1,min:0,max:1}]),defineNumber(ColorTemperatureTint,[{key:"tint",value:0,min:-100,max:100}]),Object.freeze(ColorTemperatureTint);class Grayscale extends ASinglePassPostEffect{constructor(i){super(i),this.isLdr=!0,this.init(i,"POST_EFFECT_GRAYSCALE",createBasicPostEffectCode(this,"let index=vec2(global_id.xy);var color:vec4=textureLoad(sourceTexture,index,0);let gray=getLuminance(color.rgb);let finalColor=mix(color,vec4(gray,gray,gray,color.a),uniforms.amount);textureStore(outputTexture,index,finalColor);","#redgpu_include color.getLuminance struct Uniforms{amount:f32};"))}}definePositiveNumber(Grayscale,[{key:"amount",value:1,min:0,max:1}]),Object.freeze(Grayscale);class HueSaturation extends ASinglePassPostEffect{constructor(i){super(i),this.isLdr=!0,this.init(i,"POST_EFFECT_HUE_SATURATION",createBasicPostEffectCode(this,"let index=global_id.xy;var color:vec4=textureLoad(sourceTexture,index,0);let hue_value:f32=uniforms.hue/180.0;let angle:f32=hue_value*PI;let s:f32=sin(angle);let c:f32=cos(angle);var weights:vec3=(vec3(2.0*c,-sqrt(3.0)*s-c,sqrt(3.0)*s-c)+1.0)/3.0;color=vec4(vec3(dot(color.rgb,weights.xyz),dot(color.rgb,weights.zxy),dot(color.rgb,weights.yzx)),color.a);let saturation_value:f32=uniforms.saturation/100.0;let luminance=getLuminance(color.rgb);if(saturation_value>.0){color=vec4(color.rgb+(luminance-color.rgb)*(1.0-1.0/(1.001-saturation_value)),color.a);}else{color=vec4(color.rgb+(luminance-color.rgb)*(-saturation_value),color.a);}textureStore(outputTexture,index,color);","#redgpu_include math.PI #redgpu_include color.getLuminance struct Uniforms{hue:f32,saturation:f32};"))}}defineNumber(HueSaturation,[{key:"hue",value:0,min:-180,max:180},{key:"saturation",value:0,min:-100,max:100}]),Object.freeze(HueSaturation);class Invert extends ASinglePassPostEffect{constructor(i){super(i),this.isLdr=!0,this.init(i,"POST_EFFECT_INVERT",createBasicPostEffectCode(this,"let index=vec2(global_id.xy);var color:vec4=textureLoad(sourceTexture,index,0);let invertedRGB=1.0-color.rgb;let finalColor=vec4(mix(color.rgb,invertedRGB,uniforms.amount),color.a);textureStore(outputTexture,index,finalColor);","struct Uniforms{amount:f32};"))}}definePositiveNumber(Invert,[{key:"amount",value:1,min:0,max:1}]),Object.freeze(Invert);class Threshold extends ASinglePassPostEffect{constructor(i){super(i),this.isLdr=!0,this.init(i,"POST_EFFECT_THRESHOLD",createBasicPostEffectCode(this,"let index=global_id.xy;var color:vec4=textureLoad(sourceTexture,index,0);let threshold_value:f32=uniforms.threshold/255.0;var v=.0;if(getLuminance(color.rgb)>=threshold_value){v=1.0;}color=vec4(v,v,v,color.a);textureStore(outputTexture,index,color);","#redgpu_include color.getLuminance struct Uniforms{threshold:f32};"))}}definePositiveNumber(Threshold,[{key:"threshold",value:128,min:1,max:255}]),Object.freeze(Threshold);class Vibrance extends ASinglePassPostEffect{constructor(i){super(i),this.isLdr=!0,this.init(i,"POST_EFFECT_VIBRANCE",createBasicPostEffectCode(this,"let index=global_id.xy;var color:vec4=textureLoad(sourceTexture,index,0);let originalColor=color;let luminance=getLuminance(color.rgb);if(uniforms.saturation !=.0){let saturationFactor=1.0+uniforms.saturation*.01;color=vec4(mix(luminance,color.r,saturationFactor),mix(luminance,color.g,saturationFactor),mix(luminance,color.b,saturationFactor),color.a);}if(uniforms.vibrance !=.0){let maxComponent=max(max(color.r,color.g),color.b);let minComponent=min(min(color.r,color.g),color.b);let currentSaturation=maxComponent-minComponent;let protectionFactor=1.0/(1.0+exp(6.0*(currentSaturation-0.6)));var skinToneProtection=1.0;if(color.r>color.g&&color.g>color.b){let skinToneAmount=(color.r-color.b)/max(color.r,.001);skinToneProtection=1.0-smoothstep(0.3,0.8,skinToneAmount)*0.7;}let finalProtection=protectionFactor*skinToneProtection;let vibranceStrength=uniforms.vibrance*.01*finalProtection;let vibranceFactor=1.0+vibranceStrength;color=vec4(mix(luminance,color.r,vibranceFactor),mix(luminance,color.g,vibranceFactor),mix(luminance,color.b,vibranceFactor),color.a);}color=clamp(color,vec4(.0),vec4(1.0));textureStore(outputTexture,index,color);","#redgpu_include color.getLuminance struct Uniforms{vibrance:f32,saturation:f32};"))}}defineNumber(Vibrance,[{key:"vibrance",value:0,min:-100,max:100},{key:"saturation",value:0,min:-100,max:100}]),Object.freeze(Vibrance);const fo=[0,0,0,0,0,1,0,0,0,0,0,0],mo=[0,-1,0,0,-1,5,-1,0,0,-1,0,0],po=[1,1,1,0,1,1,1,0,1,1,1,0],go=[0,1,0,0,1,-4,1,0,0,1,0,0],xo=[-2,-1,0,0,-1,1,1,0,0,1,2,0];class Convolution extends ASinglePassPostEffect{static NORMAL=fo;static SHARPEN=mo;static BLUR=po;static EDGE=go;static EMBOSS=xo;#Zx=go;constructor(i){super(i),this.isLdr=!0,this.init(i,"POST_EFFECT_CONVOLUTION",createBasicPostEffectCode(this,"let index=vec2(global_id.xy);var color:vec4=vec4(.0);let kernelWeight_value:f32=uniforms.kernelWeight;let kernel_value:mat3x3=uniforms.kernel;color+=textureLoad(sourceTexture,index+vec2(-1,-1),0)*kernel_value[0][0];color+=textureLoad(sourceTexture,index+vec2(0,-1),0)*kernel_value[0][1];color+=textureLoad(sourceTexture,index+vec2(1,-1),0)*kernel_value[0][2];color+=textureLoad(sourceTexture,index+vec2(-1,0),0)*kernel_value[1][0];color+=textureLoad(sourceTexture,index+vec2(0,0),0)*kernel_value[1][1];color+=textureLoad(sourceTexture,index+vec2(1,0),0)*kernel_value[1][2];color+=textureLoad(sourceTexture,index+vec2(-1,1),0)*kernel_value[2][0];color+=textureLoad(sourceTexture,index+vec2(0,1),0)*kernel_value[2][1];color+=textureLoad(sourceTexture,index+vec2(1,1),0)*kernel_value[2][2];textureStore(outputTexture,index,color/kernelWeight_value);","struct Uniforms{kernelWeight:f32,kernel:mat3x3};"))}get kernel(){return this.#Zx}set kernel(i){this.#Zx=i;let g=0;this.#Zx.forEach(i=>g+=i),this.updateUniform("kernelWeight",g||1),this.updateUniform("kernel",i)}}Object.freeze(Convolution);class Blur extends AMultiPassPostEffect{#Jx;constructor(i){super(i,[new Convolution(i)]),this.#Jx=this.passList[0],this.#Jx.kernel=Convolution.BLUR}render(i,g,x,v){return this.#Jx.render(i,g,x,v)}}Object.freeze(Blur);class DirectionalBlur extends ASinglePassPostEffect{#Qx=0;constructor(i){super(i),this.init(i,"POST_EFFECT_DIRECTIONAL_BLUR",createBasicPostEffectCode(this,"let index=vec2(global_id.xy);let dimensions=vec2(textureDimensions(sourceTexture));if(f32(index.x)>=dimensions.x||f32(index.y)>=dimensions.y){return;}let invSize=1.0/dimensions;let centerUV=(vec2(index)+0.5)*invSize;let direction=vec2(uniforms.directionX,uniforms.directionY);let dirLength=length(direction);let normalizedDir=select(vec2(.0),direction/dirLength,dirLength>.0);let dir=normalizedDir*(uniforms.amount*systemUniforms.devicePixelRatio)*invSize;var sum=vec4(.0);var totalWeight=.0;let steps=uniforms.sampleCount;for(var i=-steps;i<=steps;i+=1.0){let t=i/steps;let weight=exp(-0.5*pow(t*2.0,2.0));let sampleUV=centerUV+dir*t;sum+=textureSampleLevel(sourceTexture,basicSampler,sampleUV,.0)*weight;totalWeight+=weight;}textureStore(outputTexture,index,sum/totalWeight);","struct Uniforms{amount:f32,directionX:f32,directionY:f32,sampleCount:f32,};"))}get angle(){return this.#Qx}set angle(i){validateNumber(i),this.#Qx=i%360,this.#ev()}#ev(){const i=this.#Qx*Math.PI/180,g=Math.cos(i),x=Math.sin(i);this.updateUniform("directionX",g),this.updateUniform("directionY",x)}}definePositiveNumber(DirectionalBlur,[{key:"amount",value:15}]),defineUint(DirectionalBlur,[{key:"sampleCount",value:30,min:1,max:100}]),Object.freeze(DirectionalBlur);class RadialBlur extends ASinglePassPostEffect{constructor(i){super(i),this.init(i,"POST_EFFECT_RADIAL_BLUR",createBasicPostEffectCode(this,"let index=global_id.xy;let dimensions=vec2(textureDimensions(sourceTexture));if(f32(index.x)>=dimensions.x||f32(index.y)>=dimensions.y){return;}let invSize=1.0/dimensions;let centerUV=(vec2(index)+0.5)*invSize;let center=vec2(0.5)+vec2(uniforms.centerX,uniforms.centerY)*systemUniforms.devicePixelRatio*invSize;let toPixel=centerUV-center;let distance=length(toPixel);let angle=atan2(toPixel.y,toPixel.x);let rotationAngle=uniforms.amount*distance*.005;let sampleCount=i32(uniforms.sampleCount);var sum=vec4(.0);var totalWeight=.0;for(var i=0;i(cos(sampleAngle)*distance,sin(sampleAngle)*distance);let weight=1.0-abs(t-0.5)*1.5;sum+=textureSampleLevel(sourceTexture,basicSampler,sampleUV,.0)*max(weight,0.1);totalWeight+=weight;}let centerFalloff=smoothstep(.0,0.1,distance);let originalColor=textureSampleLevel(sourceTexture,basicSampler,centerUV,.0);let blurredColor=sum/totalWeight;textureStore(outputTexture,index,mix(originalColor,blurredColor,centerFalloff));","struct Uniforms{amount:f32,centerX:f32,centerY:f32,sampleCount:f32,};"))}}definePositiveNumber(RadialBlur,[{key:"amount",value:50}]),defineNumber(RadialBlur,[{key:"centerX",value:0},{key:"centerY",value:0}]),defineUint(RadialBlur,[{key:"sampleCount",value:16,min:2,max:100}]),Object.freeze(RadialBlur);class ZoomBlur extends ASinglePassPostEffect{constructor(i){super(i),this.init(i,"POST_EFFECT_ZOOM_BLUR",createBasicPostEffectCode(this,"let index=global_id.xy;let dimensions=vec2(textureDimensions(sourceTexture));if(f32(index.x)>=dimensions.x||f32(index.y)>=dimensions.y){return;}let invSize=1.0/dimensions;let centerUV=(vec2(index)+0.5)*invSize;let center=vec2(0.5)+vec2(uniforms.centerX,uniforms.centerY)*systemUniforms.devicePixelRatio*invSize;let dir=(center-centerUV)*(uniforms.amount*.01);var sum=vec4(.0);var totalWeight=.0;let steps=uniforms.sampleCount;for(var i=-steps;i<=steps;i+=1.0){let t=i/steps;let weight=1.0-abs(t);let sampleUV=centerUV+dir*t;sum+=textureSampleLevel(sourceTexture,basicSampler,sampleUV,.0)*weight;totalWeight+=weight;}textureStore(outputTexture,index,sum/totalWeight);","struct Uniforms{amount:f32,centerX:f32,centerY:f32,sampleCount:f32,};"))}}definePositiveNumber(ZoomBlur,[{key:"amount",value:10}]),defineNumber(ZoomBlur,[{key:"centerX",value:0},{key:"centerY",value:0}]),defineUint(ZoomBlur,[{key:"sampleCount",value:30,min:1,max:100}]),Object.freeze(ZoomBlur);const vo={filmGrainIntensity:.008,filmGrainResponse:1.5,filmGrainScale:1.2,coloredGrain:.05,grainSaturation:.1},_o={filmGrainIntensity:.015,filmGrainResponse:1.2,filmGrainScale:1.8,coloredGrain:.15,grainSaturation:.3},yo={filmGrainIntensity:.03,filmGrainResponse:1,filmGrainScale:2.5,coloredGrain:.25,grainSaturation:.5},bo={filmGrainIntensity:.06,filmGrainResponse:.7,filmGrainScale:4,coloredGrain:.6,grainSaturation:.8};class FilmGrain extends ASinglePassPostEffect{static SUBTLE=vo;static MEDIUM=_o;static HEAVY=yo;static VINTAGE=bo;constructor(i){super(i),this.isLdr=!0,this.init(i,"POST_EFFECT_FILM_GRAIN",createBasicPostEffectCode(this,"let index=vec2(global_id.xy);let dimensions:vec2=textureDimensions(sourceTexture);let originalColor=textureLoad(sourceTexture,index,0);let filmGrainIntensity_value:f32=uniforms.filmGrainIntensity;let filmGrainResponse_value:f32=uniforms.filmGrainResponse;let filmGrainScale_value:f32=uniforms.filmGrainScale;let coloredGrain_value:f32=uniforms.coloredGrain;let grainSaturation_value:f32=uniforms.grainSaturation;let frameIndex_value:u32=systemUniforms.time.frameIndex;if(filmGrainIntensity_value<=.0){textureStore(outputTexture,index,originalColor);return;}let baseScale=max(filmGrainScale_value,0.1)*systemUniforms.devicePixelRatio;let grainCoord=floor(vec2(global_id.xy)/baseScale);var grain=getFilmicGrain(grainCoord,frameIndex_value,coloredGrain_value);let grainLum=getLuminance(grain);grain=mix(vec3(grainLum),grain,grainSaturation_value);let sceneLuminance=getLuminance(originalColor.rgb);let responseMask=pow(1.0-sceneLuminance,filmGrainResponse_value);let finalMask=responseMask*smoothstep(.0,0.1,sceneLuminance);let intensity=filmGrainIntensity_value*max(.05,finalMask);let finalColor=originalColor.rgb+grain*intensity;let outputColor=vec4(saturate(finalColor),originalColor.a);textureStore(outputTexture,index,outputColor);","#redgpu_include color.getLuminance #redgpu_include math.hash.getHash1D_vec3 #redgpu_include math.getInterleavedGradientNoise struct Uniforms{filmGrainIntensity:f32,filmGrainResponse:f32,filmGrainScale:f32,coloredGrain:f32,grainSaturation:f32,};fn getFilmicGrain(coord:vec2,frameIndex:u32,coloredGrain:f32)->vec3{let fIndex=f32(frameIndex % 4096u);let frameSeed=fIndex*1.61803398875;let scrambledX=coord.x*12.9898+frameSeed;let scrambledY=coord.y*78.233+frameSeed;let n1=getHash1D_vec3(vec3(scrambledX,scrambledY,frameSeed));let n2=getHash1D_vec3(vec3(scrambledY,frameSeed,scrambledX));let n3=getHash1D_vec3(vec3(frameSeed,scrambledX,scrambledY));var noise=mix(vec3(n1),vec3(n1,n2,n3),coloredGrain);let ign=getInterleavedGradientNoise(coord+frameSeed);let finalNoise=mix(noise,vec3(ign),.02);return(finalNoise-0.5)*2.0;}"))}applyPreset(i){this.filmGrainIntensity=i.filmGrainIntensity,this.filmGrainResponse=i.filmGrainResponse,this.filmGrainScale=i.filmGrainScale,this.coloredGrain=i.coloredGrain,this.grainSaturation=i.grainSaturation}}definePositiveNumber(FilmGrain,[{key:"filmGrainIntensity",value:bo.filmGrainIntensity},{key:"filmGrainResponse",value:bo.filmGrainResponse},{key:"filmGrainScale",value:bo.filmGrainScale},{key:"coloredGrain",value:bo.coloredGrain},{key:"grainSaturation",value:bo.grainSaturation}]),Object.freeze(FilmGrain);class Fog extends ASinglePassPostEffect{static EXPONENTIAL=0;static EXPONENTIAL_SQUARED=1;constructor(i){super(i),this.init(i,"POST_EFFECT_FOG",createBasicPostEffectCode(this,"let id=global_id.xy;let coord=vec2(id);var sceneColor=textureLoad(sourceTexture,coord,0);let depth=textureLoad(depthTexture,coord,0);let linDepth=getLinearizeDepth(depth,systemUniforms.camera.nearClipping,systemUniforms.camera.farClipping);let u_density=uniforms.density;let u_near=uniforms.nearDistance;let u_far=uniforms.farDistance;let cameraFar=systemUniforms.camera.farClipping;var fogFactor:f32;if(linDepth>=(cameraFar*0.99)){fogFactor=1.0-u_density;}else{let dist=max(.0,linDepth-u_near);let maxDist=u_far-u_near;let normalizedDist=clamp(dist/max(0.1,maxDist),.0,1.0);if(uniforms.fogType==0u){fogFactor=exp(-u_density*normalizedDist*10.0);}else{let expVal=u_density*normalizedDist*5.0;fogFactor=exp(-(expVal*expVal));}}let finalColor=mix(uniforms.fogColor.rgb,sceneColor.rgb,saturate(fogFactor));textureStore(outputTexture,coord,vec4(finalColor,sceneColor.a));","#redgpu_include depth.getLinearizeDepth struct Uniforms{fogType:u32,density:f32,nearDistance:f32,farDistance:f32,fogColor:vec3,padding1:f32,};"))}}definePositiveNumber(Fog,[{key:"density",value:.5,min:0,max:1}]),defineNumber(Fog,[{key:"nearDistance",value:4.5,min:0},{key:"farDistance",value:50,min:.1}]),defineUint(Fog,[{key:"fogType",value:Fog.EXPONENTIAL,max:1}]),defineColorRGB(Fog,[{key:"fogColor",value:"#1b2866"}]),Object.freeze(Fog);class HeightFog extends ASinglePassPostEffect{static EXPONENTIAL=0;static EXPONENTIAL_SQUARED=1;constructor(i){super(i),this.init(i,"POST_EFFECT_HEIGHT_FOG",createBasicPostEffectCode(this,"let dimensions=textureDimensions(sourceTexture);let dimW=f32(dimensions.x);let dimH=f32(dimensions.y);let global_id_vec=vec2(global_id.xy);let screenCoord=(global_id_vec+0.5)/vec2(dimW,dimH);var depth:f32=1.0;if(dimensions.x>u32(global_id.x)&&dimensions.y>u32(global_id.y)){depth=textureLoad(depthTexture,vec2(global_id.xy),0);}let fogFactor=calculateHeightFogFactor(screenCoord,depth);let originalColor=textureLoad(sourceTexture,vec2(global_id.xy),0).rgb;let foggedColor=mix(uniforms.fogColor,originalColor,fogFactor);textureStore(outputTexture,vec2(global_id.xy),vec4(foggedColor,1.0));","#redgpu_include math.EPSILON #redgpu_include math.reconstruct.getWorldPositionFromDepth #redgpu_include math.direction.getRayDirection struct Uniforms{fogType:u32,density:f32,baseHeight:f32,thickness:f32,falloff:f32,fogColor:vec3,padding1:f32,padding2:f32,};fn isFiniteValue(value:f32)->bool{return value==value;}fn isFiniteVec3(v:vec3)->bool{return isFiniteValue(v.x)&&isFiniteValue(v.y)&&isFiniteValue(v.z);}fn reconstructWorldPositionUltraPrecise(screenCoord:vec2,depth:f32)->vec3{let worldPos=getWorldPositionFromDepth(screenCoord,depth,systemUniforms.projection.inverseProjectionViewMatrix);return select(vec3(.0),worldPos,isFiniteVec3(worldPos));}fn calculateHeightFogFactor(screenCoord:vec2,depth:f32)->f32{let backgroundThreshold=1.0-1e-5;let isBackground=depth>=backgroundThreshold;var pixelWorldHeight:f32;if(isBackground){let rayDirection=getRayDirectionMaxPrecision(screenCoord);pixelWorldHeight=getSkyboxHeightMaxPrecision(rayDirection);}else{let worldPos=reconstructWorldPositionUltraPrecise(screenCoord,depth);pixelWorldHeight=worldPos.y;}return calculateAbsoluteHeightFogMaxPrecision(pixelWorldHeight);}fn getSkyboxHeightMaxPrecision(rayDirection:vec3)->f32{let u_baseHeight=uniforms.baseHeight;let u_maxHeight=u_baseHeight+uniforms.thickness;let rayY=clamp(rayDirection.y,-0.999,0.999);let upThreshold=.08;let downThreshold=-.015;let transitionRange=upThreshold-downThreshold;let safeTransitionRange=max(transitionRange,EPSILON);if(rayY>upThreshold){return u_maxHeight+25.0;}else if(rayYf32{let u_baseHeight=uniforms.baseHeight;let u_maxHeight=u_baseHeight+uniforms.thickness;let u_density=uniforms.density;let u_falloff=uniforms.falloff;let u_fogType=uniforms.fogType;if(!isFiniteValue(worldHeight)){return 1.0;}let heightRange=u_maxHeight-u_baseHeight;let safeHeightRange=max(heightRange,1e-3);let margin=fma(safeHeightRange,0.18,1.2);let extendedBaseHeight=u_baseHeight-margin;let extendedMaxHeight=u_maxHeight+margin;let extendedRange=extendedMaxHeight-extendedBaseHeight;if(worldHeight<=extendedBaseHeight||worldHeight>=extendedMaxHeight){return 1.0;}let safeExtendedRange=max(extendedRange,1e-3);if(safeExtendedRange<=0.3){return 1.0;}let normalizedHeight=clamp((worldHeight-extendedBaseHeight)/safeExtendedRange,.0,1.0);let centerOffset=normalizedHeight-0.5;let edgeFactor=fma(-abs(centerOffset),0.25,1.0);let heightFactor=1.0-normalizedHeight;let safeHeightFactor=max(heightFactor,1e-4);let safeFalloff=clamp(u_falloff,.05,1.8);let expPower=fma(safeFalloff,0.73,1.05);var fogDensity:f32;if(u_fogType==0u){fogDensity=pow(safeHeightFactor,expPower);fogDensity=smoothstep(.0,1.0,fogDensity);}else{let expResult=pow(safeHeightFactor,expPower);fogDensity=expResult*expResult;fogDensity=smoothstep(.0,1.0,fogDensity);}let densityWithEdge=fogDensity*edgeFactor;let safeDensity=clamp(u_density,.0,4.0);let finalFogAmount=fma(densityWithEdge,safeDensity,.0)*0.42;let result=clamp(1.0-finalFogAmount,.0,1.0);return select(1.0,result,isFiniteValue(result));}fn getRayDirectionMaxPrecision(screenCoord:vec2)->vec3{let worldPos=getWorldPositionFromDepth(screenCoord,1.0,systemUniforms.projection.inverseProjectionViewMatrix);let rayDir=getRayDirection(worldPos,systemUniforms.camera.cameraPosition);return select(vec3(.0,.0,1.0),rayDir,isFiniteVec3(rayDir));}"))}}definePositiveNumber(HeightFog,[{key:"density",value:1,min:0,max:5},{key:"falloff",value:.1,min:.001,max:2},{key:"thickness",value:100,min:.1}]),defineNumber(HeightFog,[{key:"baseHeight",value:0}]),defineUint(HeightFog,[{key:"fogType",value:HeightFog.EXPONENTIAL,max:1}]),defineColorRGB(HeightFog,[{key:"fogColor",value:"#1b2866"}]),Object.freeze(HeightFog);class ChromaticAberration extends ASinglePassPostEffect{constructor(i){super(i),this.isLdr=!0,this.init(i,"POST_EFFECT_CHROMATIC_ABERRATION",createBasicPostEffectCode(this,"let index=global_id.xy;let dimensions=textureDimensions(sourceTexture);let dimW=f32(dimensions.x);let dimH=f32(dimensions.y);let uv=vec2(index)/vec2(dimW,dimH);let invSize=1.0/vec2(dimensions);let center=vec2(0.5)+vec2(uniforms.centerX,uniforms.centerY)*systemUniforms.devicePixelRatio*invSize;let offset=uv-center;let distance=length(offset);let distortion=uniforms.strength*pow(distance,uniforms.falloff);let redOffset=uv+offset*distortion*vec2(-1.0,-1.0);let greenOffset=uv;let blueOffset=uv+offset*distortion*vec2(1.0,1.0);var finalColor:vec3;finalColor.r=textureSampleLevel(sourceTexture,basicSampler,redOffset,.0).r;finalColor.g=textureSampleLevel(sourceTexture,basicSampler,greenOffset,.0).g;finalColor.b=textureSampleLevel(sourceTexture,basicSampler,blueOffset,.0).b;let originalAlpha=textureLoad(sourceTexture,index,0).a;textureStore(outputTexture,index,vec4(finalColor,originalAlpha));","struct Uniforms{strength:f32,centerX:f32,centerY:f32,falloff:f32};"))}}defineNumber(ChromaticAberration,[{key:"strength",value:.015,min:0},{key:"centerX",value:0},{key:"centerY",value:0},{key:"falloff",value:.5,min:0,max:5}]),Object.freeze(ChromaticAberration);class DOFCoC extends ASinglePassPostEffect{constructor(i){super(i),this.init(i,"POST_EFFECT_DOF_COC",createBasicPostEffectCode(this,"let index=vec2(global_id.xy);let coord=vec2(global_id.xy);let originalColor=textureLoad(sourceTexture,coord,0).xyzw;let depth=textureLoad(depthTexture,coord,0);let linearDepth=getLinearizeDepth(depth,uniforms.nearPlane,uniforms.farPlane);let coc=calculateCoC(linearDepth);let encodedCoC=encodeCoC(coc);textureStore(outputTexture,coord,vec4(originalColor.rgb,encodedCoC));","#redgpu_include depth.getLinearizeDepth struct Uniforms{focusDistance:f32,aperture:f32,maxCoC:f32,nearPlane:f32,farPlane:f32,};fn encodeCoC(coc:f32)->f32{return(coc+1.0)*0.5;}fn calculateCoC(linearDepth:f32)->f32{let subjectDistance=linearDepth;let focalLength=50.0;let focusRange=uniforms.focusDistance*0.15;let transitionRange=uniforms.focusDistance*0.35;let distanceFromFocus=abs(subjectDistance-uniforms.focusDistance);if(distanceFromFocus.05){signedCoC=-min(1.0,absCoC*smoothstep(.05,0.3,absCoC)*1.5);}if(distanceFromFocus0.1){signedCoC=min(1.0,absCoC*smoothstep(0.1,0.5,absCoC)*1.2);}if(distanceFromFocus=dimensions.x||index.y>=dimensions.y){return;}let centerUV=(vec2(index)+0.5)/vec2(dimensions);let originalSample=textureLoad(sourceTexture,index,0);let originalColor=originalSample.rgb;let originalAlpha=originalSample.a;let encodedCoC=textureLoad(cocTexture,index,0).a;let cocValue=decodeCoC(encodedCoC);if(abs(cocValue)<.005){textureStore(outputTexture,index,vec4(originalColor,originalAlpha));return;}var finalColor=originalColor;var finalAlpha=originalAlpha;if(cocValue<.0){let blurResult=calculateBlur(centerUV,abs(cocValue),uniforms.nearBlurSize,true);let nearBlur=blurResult.rgb;let nearBlurAlpha=blurResult.a;let nearBlend=saturate(pow(abs(cocValue)*uniforms.nearStrength,0.7));finalColor=mix(originalColor,nearBlur,nearBlend);finalAlpha=mix(originalAlpha,nearBlurAlpha,nearBlend);}else if(cocValue>.0){let blurResult=calculateBlur(centerUV,cocValue,uniforms.farBlurSize,false);let farBlur=blurResult.rgb;let farBlurAlpha=blurResult.a;let rawBlend=cocValue*uniforms.farStrength;let farBlend=saturate(smoothstep(.0,0.8,rawBlend));finalColor=mix(originalColor,farBlur,farBlend);finalAlpha=mix(originalAlpha,farBlurAlpha,farBlend);}textureStore(outputTexture,index,vec4(finalColor,finalAlpha));","#redgpu_include math.PI2 struct Uniforms{nearBlurSize:f32,farBlurSize:f32,nearStrength:f32,farStrength:f32,};fn decodeCoC(encoded:f32)->f32{return encoded*2.0-1.0;}fn calculateBlur(centerUV:vec2,intensity:f32,maxBlurSize:f32,isNear:bool)->vec4{let blurRadius=intensity*maxBlurSize*systemUniforms.devicePixelRatio;let dimensions=vec2(textureDimensions(sourceTexture));let invSize=1.0/vec2(dimensions);if(blurRadius<0.3){return textureSampleLevel(sourceTexture,basicSampler,centerUV,.0);}var sum:vec3=vec3(.0);var sumAlpha:f32=.0;var totalWeight=.0;let maxRadius=min(blurRadius,maxBlurSize*systemUniforms.devicePixelRatio);let samples=select(8,16,isNear);let angleStep=PI2/f32(samples);let originalColor=textureSampleLevel(sourceTexture,basicSampler,centerUV,.0);let centerWeight=select(0.4,0.2,isNear);sum+=originalColor.rgb*centerWeight;sumAlpha+=originalColor.a*centerWeight;totalWeight+=centerWeight;for(var i=0;i(cos(angle),sin(angle))*r*invSize;let sampleUV=centerUV+offsetUV;let sampleData=textureSampleLevel(sourceTexture,basicSampler,sampleUV,.0);let sampleEncodedCoC=textureSampleLevel(cocTexture,basicSampler,sampleUV,.0).a;let sampleCoC=decodeCoC(sampleEncodedCoC);var weight=exp(-r*r/(maxRadius*maxRadius*0.5));if(isNear){if(sampleCoC<.0&&abs(sampleCoC)>=intensity*0.5){weight*=1.5;}}else{if(sampleCoC>.0&&sampleCoC>=intensity*0.7){weight*=1.2;}}sum+=sampleData.rgb*weight;sumAlpha+=sampleData.a*weight;totalWeight+=weight;}}return vec4(sum/totalWeight,sumAlpha/totalWeight);}",[{name:"sourceTexture"},{name:"cocTexture"}]))}}definePositiveNumber(DOFUnified,[{key:"nearBlurSize",value:16},{key:"farBlurSize",value:24},{key:"nearStrength",value:1},{key:"farStrength",value:1}]),Object.freeze(DOFUnified);class DOF extends AMultiPassPostEffect{#tv;#rv;#iv=15;#xi=2.8;#nv=25;#av=.1;#sv=1e3;#ov=15;#uv=15;#lv=1;#cv=1;constructor(i){super(i,[new DOFCoC(i),new DOFUnified(i)]),this.#tv=this.passList[0],this.#rv=this.passList[1],this.#tv.focusDistance=this.#iv,this.#tv.aperture=this.#xi,this.#tv.maxCoC=this.#nv,this.#tv.nearPlane=this.#av,this.#tv.farPlane=this.#sv,this.#rv.nearBlurSize=this.#ov,this.#rv.farBlurSize=this.#uv,this.#rv.nearStrength=this.#lv,this.#rv.farStrength=this.#cv}get focusDistance(){return this.#iv}set focusDistance(i){this.#iv=i,this.#tv.focusDistance=i}get aperture(){return this.#xi}set aperture(i){this.#xi=i,this.#tv.aperture=i}get maxCoC(){return this.#nv}set maxCoC(i){this.#nv=i,this.#tv.maxCoC=i}get nearPlane(){return this.#av}set nearPlane(i){this.#av=i,this.#tv.nearPlane=i}get farPlane(){return this.#sv}set farPlane(i){this.#sv=i,this.#tv.farPlane=i}get nearBlurSize(){return this.#ov}set nearBlurSize(i){this.#ov=i,this.#rv.nearBlurSize=i}get farBlurSize(){return this.#uv}set farBlurSize(i){this.#uv=i,this.#rv.farBlurSize=i}get nearStrength(){return this.#lv}set nearStrength(i){this.#lv=i,this.#rv.nearStrength=i}get farStrength(){return this.#cv}set farStrength(i){this.#cv=i,this.#rv.farStrength=i}setGameDefault(){this.focusDistance=15,this.aperture=2.8,this.maxCoC=25,this.nearBlurSize=15,this.farBlurSize=15,this.nearStrength=1,this.farStrength=1}setCinematic(){this.focusDistance=20,this.aperture=1.4,this.maxCoC=40,this.nearBlurSize=25,this.farBlurSize=30,this.nearStrength=1.2,this.farStrength=1.3}setPortrait(){this.focusDistance=8,this.aperture=1.8,this.maxCoC=35,this.nearBlurSize=12,this.farBlurSize=25,this.nearStrength=.8,this.farStrength=1.4}setLandscape(){this.focusDistance=50,this.aperture=8,this.maxCoC=20,this.nearBlurSize=20,this.farBlurSize=10,this.nearStrength=1.1,this.farStrength=.6}setMacro(){this.focusDistance=2,this.aperture=1,this.maxCoC=50,this.nearBlurSize=30,this.farBlurSize=35,this.nearStrength=1.5,this.farStrength=1.6}setSports(){this.focusDistance=25,this.aperture=4,this.maxCoC=18,this.nearBlurSize=10,this.farBlurSize=12,this.nearStrength=.8,this.farStrength=.9}setNightMode(){this.focusDistance=12,this.aperture=2,this.maxCoC=30,this.nearBlurSize=18,this.farBlurSize=20,this.nearStrength=1.1,this.farStrength=1.2}render(i,g,x,v){const _=i.postEffectManager.texturePool,y=this.#tv.render(i,g,x,v),b=this.#rv.render(i,g,x,v,y);return _.release(y.texture),b}}Object.freeze(DOF);class LensDistortion extends ASinglePassPostEffect{constructor(i){super(i),this.isLdr=!0,this.init(i,"POST_EFFECT_LENS_DISTORTION",createBasicPostEffectCode(this,"let index=global_id.xy;let dimensions=textureDimensions(sourceTexture);let dimF=vec2(dimensions);let invSize=1.0/dimF;let uv=vec2(index)/dimF;let uvCenter=vec2(0.5)+vec2(uniforms.centerX,uniforms.centerY)*systemUniforms.devicePixelRatio*invSize;let offset=uv-uvCenter;let distance=length(offset);let distortionFactor=1.0+uniforms.distortion*distance*distance;let distortedUV=uvCenter+offset*distortionFactor;if(distortedUV.x<.0||distortedUV.x>1.0||distortedUV.y<.0||distortedUV.y>1.0){textureStore(outputTexture,index,vec4(.0,.0,.0,1.0));}else{let sampledColor=textureSampleLevel(sourceTexture,basicSampler,distortedUV,.0);textureStore(outputTexture,index,sampledColor);}","struct Uniforms{distortion:f32,centerX:f32,centerY:f32};"))}}defineNumber(LensDistortion,[{key:"distortion",value:.1},{key:"centerX",value:0},{key:"centerY",value:0}]),Object.freeze(LensDistortion);class Vignetting extends ASinglePassPostEffect{constructor(i){super(i),this.isLdr=!0,this.init(i,"POST_EFFECT_VIGNETTING",createBasicPostEffectCode(this,"let dimensions=textureDimensions(sourceTexture);let dimF=vec2(dimensions);let invSize=1.0/dimF;let index=global_id.xy;let uv=vec2(index)/dimF;let uvCenter=vec2(0.5)+vec2(uniforms.centerX,uniforms.centerY)*systemUniforms.devicePixelRatio*invSize;let smoothness=uniforms.smoothness;let size=uniforms.size;var color:vec4=textureLoad(sourceTexture,index,0);var diff=size-distance(uv,uvCenter);let vignette=smoothstep(-smoothness,smoothness,diff);color=vec4(color.rgb*vignette,color.a);textureStore(outputTexture,index,color);","struct Uniforms{smoothness:f32,size:f32,centerX:f32,centerY:f32,};"))}}definePositiveNumber(Vignetting,[{key:"size",value:.5,max:1},{key:"smoothness",value:.2,max:1}]),defineNumber(Vignetting,[{key:"centerX",value:0},{key:"centerY",value:0}]),Object.freeze(Vignetting);class OldBloomBlend extends ASinglePassPostEffect{constructor(i){super(i),this.init(i,"POST_EFFECT_OLD_BLOOM_BLEND",createBasicPostEffectCode(this,"let index=vec2(global_id.xy);let dimensions:vec2=textureDimensions(sourceTexture0);if(index.x>=dimensions.x||index.y>=dimensions.y){return;}let diffuseSample=textureLoad(sourceTexture0,index,0);let blurSample=textureLoad(sourceTexture1,index,0);let diffuseRGB=diffuseSample.rgb;let blurRGB=blurSample.rgb*uniforms.bloomStrength;let diffuseYCoCg=rgbToYCoCg(diffuseRGB);let blurYCoCg=rgbToYCoCg(blurRGB);var finalYCoCg:vec3;finalYCoCg.x=diffuseYCoCg.x+blurYCoCg.x;finalYCoCg.y=diffuseYCoCg.y+blurYCoCg.y*0.5;finalYCoCg.z=diffuseYCoCg.z+blurYCoCg.z*0.5;let finalRGB=YCoCgToRgb(finalYCoCg)*uniforms.exposure;textureStore(outputTexture,index,vec4(finalRGB,diffuseSample.a));","#redgpu_include color.getLuminance #redgpu_include color.rgbToYCoCg #redgpu_include color.YCoCgToRgb struct Uniforms{bloomStrength:f32,exposure:f32,};",[{name:"sourceTexture0"},{name:"sourceTexture1"}]))}render(i,g,x,v,_){return super.render(i,g,x,v,_)}}definePositiveNumber(OldBloomBlend,[{key:"bloomStrength",value:1},{key:"exposure",value:1}]),Object.freeze(OldBloomBlend);class OldBloom extends AMultiPassPostEffect{#hv;#fv;#dv;#mv=156;#pv=32;#gv=1;#xv=1.2;constructor(i){super(i,[new Threshold(i),new GaussianBlur(i),new OldBloomBlend(i)]),this.#hv=this.passList[0],this.#fv=this.passList[1],this.#dv=this.passList[2],this.#hv.threshold=this.#mv,this.#fv.size=this.#pv,this.#dv.exposure=this.#gv,this.#dv.bloomStrength=this.#xv}get threshold(){return this.#mv}set threshold(i){this.#mv=i,this.#hv.threshold=i}get gaussianBlurSize(){return this.#pv}set gaussianBlurSize(i){this.#pv=i,this.#fv.size=i}get exposure(){return this.#gv}set exposure(i){this.#gv=i,this.#dv.exposure=i}get bloomStrength(){return this.#xv}set bloomStrength(i){this.#xv=i,this.#dv.bloomStrength=i}render(i,g,x,v){const _=i.postEffectManager.texturePool,y=this.#hv.render(i,g,x,v),b=this.#fv.render(i,g,x,y);_.release(y.texture);const S=this.#dv.render(i,g,x,v,b);return _.release(b.texture),S}}Object.freeze(OldBloom);class Sharpen extends AMultiPassPostEffect{#Jx;constructor(i){super(i,[new Convolution(i)]),this.isLdr=!0,this.#Jx=this.passList[0],this.#Jx.kernel=Convolution.SHARPEN}render(i,g,x,v){return this.#Jx.render(i,g,x,v)}}Object.freeze(Sharpen);var So=Object.freeze({__proto__:null,AMultiPassPostEffect:AMultiPassPostEffect,ASinglePassPostEffect:ASinglePassPostEffect,PostEffectTexturePool:PostEffectTexturePool,createBasicPostEffectCode:createBasicPostEffectCode}),To=Object.freeze({__proto__:null,Blur:Blur,BlurX:BlurX,BlurY:BlurY,BrightnessContrast:BrightnessContrast,ChromaticAberration:ChromaticAberration,ColorBalance:ColorBalance,ColorTemperatureTint:ColorTemperatureTint,Convolution:Convolution,Core:So,DOF:DOF,DirectionalBlur:DirectionalBlur,FilmGrain:FilmGrain,Fog:Fog,GaussianBlur:GaussianBlur,Grayscale:Grayscale,HeightFog:HeightFog,HueSaturation:HueSaturation,Invert:Invert,LensDistortion:LensDistortion,OldBloom:OldBloom,PostEffectManager:PostEffectManager,RadialBlur:RadialBlur,Sharpen:Sharpen,Threshold:Threshold,Vibrance:Vibrance,Vignetting:Vignetting,ZoomBlur:ZoomBlur}),wo=Object.freeze({__proto__:null,PICKING_EVENT_TYPE:i,PickingEvent:PickingEvent,PickingManager:PickingManager,Raycaster2D:Raycaster2D,Raycaster3D:Raycaster3D}),Mo=Object.freeze({__proto__:null,BlendState:BlendState,DepthStencilState:DepthStencilState,PrimitiveState:PrimitiveState}),Po=Object.freeze({__proto__:null,TONE_MAPPING_MODE:ea,ToneMappingManager:ToneMappingManager}),Ro=Object.freeze({__proto__:null,DirectionalShadowManager:DirectionalShadowManager,ShadowManager:ShadowManager}),Co=Object.freeze({__proto__:null,defineBoolean:defineBoolean,defineColorRGB:defineColorRGB,defineColorRGBA:defineColorRGBA,defineCubeTexture:defineCubeTexture,defineNumber:defineNumber,definePositiveNumber:definePositiveNumber,defineSampler:defineSampler,defineTexture:defineTexture,defineUint:defineUint,defineVector2:defineVector2,defineVector3:defineVector3,defineVector4:defineVector4}),Bo=Object.freeze({__proto__:null,AntialiasingManager:AntialiasingManager,FXAA:FXAA,TAA:TAA,TAASharpen:TAASharpen});var Do=Object.freeze({__proto__:null,PHYSICS_BODY_TYPE:{DYNAMIC:"dynamic",STATIC:"static",KINEMATIC:"kinematic",KINEMATIC_POSITION:"kinematicPosition",KINEMATIC_VELOCITY:"kinematicVelocity"},PHYSICS_SHAPE:{BOX:"box",SPHERE:"sphere",CAPSULE:"capsule",CYLINDER:"cylinder",HEIGHTFIELD:"heightfield",MESH:"mesh"}});export{Bo as Antialiasing,xa as BaseObject,ga as Bound,Ca as Camera,Ea as Color,Ia as CommandEncoderManager,Da as Context,Co as DefineGPUProperty,ks as Display,GLTFLoader,v as GPU_ADDRESS_MODE,ui as GPU_BLEND_FACTOR,li as GPU_BLEND_OPERATION,Er as GPU_COMPARE_FUNCTION,Ji as GPU_CULL_MODE,_ as GPU_FILTER_MODE,Qi as GPU_FRONT_FACE,en as GPU_INDEX_FORMAT,z as GPU_LOAD_OP,y as GPU_MIPMAP_FILTER_MODE,Ei as GPU_PRIMITIVE_TOPOLOGY,q as GPU_STORE_OP,Geometry,Os as Light,zs as Material,Vs as Math,Do as Physics,wo as Picking,To as PostEffect,Fs as Primitive,Mo as RenderState,Renderer,ao as Resource,ho as RuntimeChecker,ft as ShaderLibrary,Ro as Shadow,SystemUniformUpdater,Po as ToneMapping,x as Util,init}; +const consoleAndThrowError=(...i)=>{const g=Array.prototype.slice.call(i).join(" ");throw new Error(g)},validatePositiveNumberRange=(i,g=0,x=Number.MAX_VALUE)=>(("number"!=typeof i||Number.isNaN(i))&&consoleAndThrowError("Only numbers allowed."),("number"!=typeof g||Number.isNaN(g))&&consoleAndThrowError("Only numbers allowed."),("number"!=typeof x||Number.isNaN(x))&&consoleAndThrowError("Only numbers allowed."),(g<0||i<0||ix)&&consoleAndThrowError(`Only numbers within the range of [${g}, ${x}] are allowed.`),!0),isUint=i=>Number.isInteger(i)&&i>=0,validateUintRange=(i,g=0,x=4503599627370496)=>{const v=isUint(i),_=isUint(g),y=isUint(x),b="is not Uint! / value : ",S=`(check range : ${g}u ~ ${x}u)`;return v||consoleAndThrowError(`value ${b}${i} / ${S}`),_||consoleAndThrowError(`min ${b}${g} / ${S}`),y||consoleAndThrowError(`max ${b}${x} / ${S}`),g>=x&&consoleAndThrowError(`maximum value is bigger than minimum value. / ${S}`),g>i&&consoleAndThrowError(`value is smaller than minimum value. / value : ${i} / ${S}`),x{if("number"==typeof i)return!Number.isNaN(i)&&Number.isInteger(i)&&i>=0&&i<=16777215;if("string"!=typeof i)return!1;const g=/^([A-Fa-f0-9]{3}){1,2}$/;return!!i.startsWith("#")&&g.test(i.substring(1))};function convertHexToRgb(i,g=!1){if(Number.isNaN(i))throw Error(`from convertHexToRgb: input value - ${i} / NaN is not allowed`);let x;if("number"==typeof i)x=i;else{if(!isHexColor(i))throw Error(`from convertHexToRgb: input value - ${i} / Only '#' prefixed hex strings or numbers allowed`);{let g=i.substring(1);3===g.length&&(g=g.charAt(0)+g.charAt(0)+g.charAt(1)+g.charAt(1)+g.charAt(2)+g.charAt(2)),x=parseInt(g,16)}}const v=x>>16&255,_=x>>8&255,y=255&x;return g?[v,_,y]:{r:v,g:_,b:y}}const convertRgbToHex=(i,g,x)=>{validateUintRange(i,0,255),validateUintRange(g,0,255),validateUintRange(x,0,255);return`#${i.toString(16).padStart(2,"0").toUpperCase()}${g.toString(16).padStart(2,"0").toUpperCase()}${x.toString(16).padStart(2,"0").toUpperCase()}`};class ColorRGB{#e;#t;#r;#i;constructor(i=255,g=255,x=255,v=void 0){this.#n(i,g,x),this.#a(i,g,x),v&&(this.#i=v)}get r(){return this.#e}set r(i){validateUintRange(i,0,255),this.#e=i,this.#i?.()}get g(){return this.#t}set g(i){validateUintRange(i,0,255),this.#t=i,this.#i?.()}get b(){return this.#r}set b(i){validateUintRange(i,0,255),this.#r=i,this.#i?.()}get rgb(){return[this.#e,this.#t,this.#r]}get rgbNormal(){return[this.#e/255,this.#t/255,this.#r/255]}get rgbNormalLinear(){return[Math.pow(this.#e/255,2.2),Math.pow(this.#t/255,2.2),Math.pow(this.#r/255,2.2)]}get hex(){return convertRgbToHex(this.#e,this.#t,this.#r)}setColorByRGB(i,g,x){this.#n(i,g,x),this.#a(i,g,x)}setColorByHEX(i){const{r:g,g:x,b:v}=convertHexToRgb(i);this.#a(g,x,v)}setColorByRGBString(i){const g=/rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/.exec(i);g||consoleAndThrowError(`유효하지 않은 rgb 색상 값입니다: ${i}`);const[,x,v,_]=g.map(Number);this.#n(x,v,_),this.#a(x,v,_)}#a(i,g,x){this.#e=i,this.#t=g,this.#r=x,this.#i?.()}#n(i,g,x){validateUintRange(i,0,255),validateUintRange(g,0,255),validateUintRange(x,0,255)}}Object.freeze(ColorRGB);class ColorRGBA extends ColorRGB{#s;#i;constructor(i=255,g=255,x=255,v=1,_=void 0){super(i,g,x,_),validatePositiveNumberRange(v,0,1),this.#s=v,_&&(this.#i=_)}get a(){return this.#s}set a(i){validatePositiveNumberRange(i,0,1),this.#s=i,this.#i?.()}get rgba(){return[this.r,this.g,this.b,this.#s]}get rgbaNormal(){return[this.r/255,this.g/255,this.b/255,this.#s]}get rgbaNormalLinear(){return[Math.pow(this.r/255,2.2),Math.pow(this.g/255,2.2),Math.pow(this.b/255,2.2),this.#s]}setColorByRGBA(i,g,x,v){this.#o(i,g,x,v),this.r=i,this.g=g,this.b=x,this.#s=v,this.#i?.()}setColorByRGBAString(i){const g=/rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d*(?:\.\d+)?)\s*\)/.exec(i);if(!g)throw new Error(`유효하지 않은 rgba 색상 값입니다: ${i}`);const[,x,v,_,y]=g.map(Number);this.#o(x,v,_,y),this.r=x,this.g=v,this.b=_,this.#s=y,this.#i?.()}#o(i,g,x,v){validateUintRange(i,0,255),validateUintRange(g,0,255),validateUintRange(x,0,255),validatePositiveNumberRange(v,0,1)}}Object.freeze(ColorRGBA);const i={MOVE:"move",DOWN:"down",UP:"up",OVER:"over",OUT:"out",CLICK:"click"};Object.freeze(i);const copyGPUBuffer=(i,g,x)=>{const v=Math.min(g.size,x.size);if(v%4!=0)throw new Error(`[RedGPU] copyGPUBuffer: Copy size (${v}) must be a multiple of 4 bytes.`);i.copyBufferToBuffer(g,0,x,0,v)},formatBytes=(i,g=2)=>{if(("number"!=typeof i||i<0||Number.isNaN(i)||!Number.isInteger(i))&&consoleAndThrowError("Invalid input: 'bytes' must be a positive integer."),0===i)return"0 Bytes";const x=g<0?0:g,v=Math.floor(Math.log(i)/Math.log(1024));return parseFloat((i/Math.pow(1024,v)).toFixed(x))+" "+["Bytes","KB","MB","GB"][v]};function getAbsoluteURL(i,g){if("string"!=typeof g||!g)throw new Error("relative must be a non-empty string");if("string"!=typeof i&&!(i instanceof URL))throw new Error("base must be a string or URL instance");if("string"==typeof i&&!i)throw new Error("base must be a non-empty string");return new URL(g,i).href}const getFileExtension=i=>{if(!i||0===i.trim().length)throw new Error("URL must not be empty or undefined");const g=i.split("/"),x=g[g.length-1],v=x.lastIndexOf(".");return-1===v?"":x.substring(v+1).toLowerCase()},getFileName=(i,g=!0)=>{const x=i.substring(i.lastIndexOf("/")+1);return g?x:x.split(".").slice(0,-1).join(".")},getFilePath=i=>{if(!i||0===i.trim().length)throw new Error("URL must not be empty or undefined");return i.substring(0,i.lastIndexOf("/")+1)};function calculateTextureByteSize(i){return function(i){switch(i){case"r8unorm":case"r8snorm":case"r8uint":case"r8sint":return 1;case"r16uint":case"r16sint":case"r16float":case"rg8unorm":case"rg8snorm":case"rg8uint":case"rg8sint":case"depth16unorm":return 2;case"r32uint":case"r32sint":case"r32float":case"rg16uint":case"rg16sint":case"rg16float":case"rgba8unorm":case"rgba8unorm-srgb":case"rgba8snorm":case"rgba8uint":case"rgba8sint":case"bgra8unorm":case"bgra8unorm-srgb":case"depth24plus":case"depth32float":return 4;case"rg32uint":case"rg32sint":case"rg32float":case"rgba16uint":case"rgba16sint":case"rgba16float":return 8;case"rgba32uint":case"rgba32sint":case"rgba32float":return 16;default:throw new Error(`Unrecognized texture format: ${i}`)}}(i.format)*(i.width*i.height*(i.depthOrArrayLayers||1))*(i.sampleCount||1)}const getMipLevelCount=(i,g)=>(validateUintRange(i),validateUintRange(g),Math.floor(Math.log2(Math.max(i,g)))+1),imageBitmapToGPUTexture=(i,g,x,v=!0)=>{x.usage|=GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT;const _=i.createTexture(x);for(let y=0;y{const i="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split("");let g,x=0,v=new Array(36);for(v[8]=v[13]=v[18]=v[23]="-",v[14]="4";x<36;)v[x]||(g=16*Math.random()|0,v[x]=i[19===x?3&g|8:15&g]),x++;return v.join("")};class InstanceIdGenerator{static idMaps=new Map;static getNextId(i){let g=this.idMaps.get(i)||0;return this.idMaps.set(i,g+1),g}}Object.freeze(InstanceIdGenerator);const uuidToUint=i=>{const g=i.replace(/-/g,"").substring(0,8);return parseInt(g,16)},g=console.log.bind(console);var x=Object.freeze({__proto__:null,InstanceIdGenerator:InstanceIdGenerator,calculateTextureByteSize:calculateTextureByteSize,copyGPUBuffer:copyGPUBuffer,copyToTextureArray:function(i,g,x,v){i.copyTextureToTexture({texture:g},{texture:x,origin:[0,0,v]},[g.width,g.height,1])},createUUID:createUUID,formatBytes:formatBytes,getAbsoluteURL:getAbsoluteURL,getFileExtension:getFileExtension,getFileName:getFileName,getFilePath:getFilePath,getMipLevelCount:getMipLevelCount,imageBitmapToGPUTexture:imageBitmapToGPUTexture,keepLog:g,loadAndCreateBitmapImage:loadAndCreateBitmapImage,uuidToUint:uuidToUint});const v={CLAMP_TO_EDGE:"clamp-to-edge",REPEAT:"repeat",MIRRORED_REPEAT:"mirror-repeat"};Object.freeze(v);const _={NEAREST:"nearest",LINEAR:"linear"};Object.freeze(_);const y={NEAREST:"nearest",LINEAR:"linear"};Object.freeze(y);const validateRedGPUContext=i=>{if("RedGPUContext"!==i?.constructor?.name){return consoleAndThrowError(`from ${i?.constructor?.name} : requires a RedGPUContext instance, but received : ${i}`),!1}return!0};class BaseObject{#u=createUUID();#l="";#c;constructor(){}get uuid(){return this.#u}get name(){return this.#c||(this.#c=InstanceIdGenerator.getNextId(this.constructor)),this.#l||`${this.constructor.name} Instance ${this.#c}`}set name(i){this.#l=i}}Object.freeze(BaseObject);class RedGPUObject extends BaseObject{#h;constructor(i){super(),validateRedGPUContext(i),this.#h=i}get redGPUContext(){return this.#h}get gpuDevice(){return this.#h.gpuDevice}get resourceManager(){return this.#h.resourceManager}get antialiasingManager(){return this.#h.antialiasingManager}get commandEncoderManager(){return this.#h.commandEncoderManager}}Object.freeze(RedGPUObject);class ResourceBase extends RedGPUObject{#f;#d;#m=[];#p;#g=0;constructor(i,g){super(i),this.#p=g,this.#f=i.gpuDevice}get revision(){return this.#g}get cacheKey(){return this.#d}set cacheKey(i){this.#d=i}get resourceManagerKey(){return this.#p}get gpuDevice(){return this.#f}__addDirtyPipelineListener(i){this.#x(!0),this.#m.push(i)}__removeDirtyPipelineListener(i){const g=this.#m.indexOf(i);g>-1&&(this.#m.splice(g,1),this.#x(!1))}notifyUpdate(i=!1){this.#g++;for(const i of this.#m)i(this);i&&(this.#m.length=0)}#x(i){const{resourceManager:g}=this;if("Sampler"!==this.constructor.name&&g){const x=g[this.#p];x||consoleAndThrowError("need managedStateKey",this.constructor.name);const v=x?.table.get(this.cacheKey);v&&(i?v.useNum++:v.useNum--)}}}const b=new Map,S=Object.values(_),w=Object.values(v),L=Object.values(y);class Sampler extends ResourceBase{#v;#_=_.LINEAR;#y=_.LINEAR;#b=y.LINEAR;#S=v.CLAMP_TO_EDGE;#T=v.CLAMP_TO_EDGE;#w=v.REPEAT;#M;#P;#R;#C=1;constructor(i,g){super(i),this.#B(g)}get addressModeU(){return this.#S}set addressModeU(i){this.#D(i,"addressModeU")}get addressModeV(){return this.#T}set addressModeV(i){this.#D(i,"addressModeV")}get addressModeW(){return this.#w}set addressModeW(i){this.#D(i,"addressModeW")}get mipmapFilter(){return this.#b}set mipmapFilter(i){this.#E(i,L,"mipmapFilter")}get gpuSampler(){return this.#v}get magFilter(){return this.#_}set magFilter(i){this.#E(i,S,"magFilter")}get minFilter(){return this.#y}set minFilter(i){this.#E(i,S,"minFilter")}get maxAnisotropy(){return this.#C}set maxAnisotropy(i){validateUintRange(i,1,16),this.#C=i,this.#B()}get isAnisotropyValid(){return!this.#C||"linear"===this.#_&&"linear"===this.#y&&"linear"===this.#b}#I(){this.notifyUpdate()}#D(i,g){if(w.includes(i)){switch(g){case"addressModeU":this.#S=i;break;case"addressModeV":this.#T=i;break;case"addressModeW":this.#w=i}this.#B()}else consoleAndThrowError(`Invalid ${g} value. Must be one of ${w.join(", ")}, but received: ${i}.`)}#E(i,g,x){if(g.includes(i)||null===i){switch(x){case"mipmapFilter":this.#b=i;break;case"magFilter":this.#_=i;break;case"minFilter":this.#y=i}this.#B()}else consoleAndThrowError(`Invalid ${x} value. Must be one of ${g.join(", ")}, but received: ${i}.`)}#A(){return`${this.#_}:${this.#y}:${this.#b}:${this.#S}:${this.#T}:${this.#w}:${this.#M}:${this.#P}:${this.#R}:${this.#C}`}#B(i){i&&(i.magFilter&&(this.#_=i.magFilter),i.minFilter&&(this.#y=i.minFilter),i.mipmapFilter&&(this.#b=i.mipmapFilter),i.addressModeU&&(this.#S=i.addressModeU),i.addressModeV&&(this.#T=i.addressModeV),i.addressModeW&&(this.#w=i.addressModeW),void 0!==i.lodMinClamp&&(this.#M=i.lodMinClamp),void 0!==i.lodMaxClamp&&(this.#P=i.lodMaxClamp),i.compare&&(this.#R=i.compare),i.maxAnisotropy&&(this.#C=i.maxAnisotropy)),this.isAnisotropyValid||1===this.#C||(console.warn(`Invalid maxAnisotropy setting (${this.#C}) detected: magFilter(${this.#_}), minFilter(${this.#y}), mipmapFilter(${this.#b}) must all be set to 'linear' for anisotropic filtering to work. Falling back to default (1).`),this.#C=1);const g=this.#A();if(!b.has(g)){let i={};this.#_&&(i.magFilter=this.#_),this.#y&&(i.minFilter=this.#y),this.#b&&(i.mipmapFilter=this.#b),this.#S&&(i.addressModeU=this.#S),this.#T&&(i.addressModeV=this.#T),this.#w&&(i.addressModeW=this.#w),void 0!==this.#M&&(i.lodMinClamp=this.#M),void 0!==this.#P&&(i.lodMaxClamp=this.#P),this.#R&&(i.compare=this.#R),this.#C&&(i.maxAnisotropy=this.#C),b.set(g,this.redGPUContext.gpuDevice.createSampler(i))}this.#v=b.get(g),this.#I()}}Object.freeze(Sampler);class BRDFGenerator extends RedGPUObject{#L;#U;#k;constructor(i){super(i)}get brdfLUTTexture(){return this.#k||this.#G(),this.#k}#G(){const{gpuDevice:i,resourceManager:g,commandEncoderManager:x}=this,v="rg16float";this.#k=g.createManagedTexture({size:[128,128],format:v,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT,label:"BRDF_LUT_Texture"}),this.#L||(this.#L=g.createGPUShaderModule("BRDF_GENERATOR_SHADER_MODULE",{code:"#redgpu_include math.PI #redgpu_include math.PI2 #redgpu_include math.tnb.getTBN #redgpu_include math.hash.getHammersley fn importanceSampleGGX(Xi:vec2,N:vec3,roughness:f32)->vec3{let a=roughness*roughness;let phi=PI2*Xi.x;let cosTheta=sqrt((1.0-Xi.y)/(1.0+(a*a-1.0)*Xi.y));let sinTheta=sqrt(1.0-cosTheta*cosTheta);let H_local=vec3(cos(phi)*sinTheta,sin(phi)*sinTheta,cosTheta);let up=select(vec3(1.0,.0,.0),vec3(.0,.0,1.0),abs(N.z)<0.999);let tbn=getTBN(N,up);return normalize(tbn*H_local);}fn geometrySchlickGGX(NdotV:f32,roughness:f32)->f32{let a=roughness;let k=(a*a)/2.0;let nom=NdotV;let denom=NdotV*(1.0-k)+k;return nom/denom;}fn geometrySmith(N:vec3,V:vec3,L:vec3,roughness:f32)->f32{let NdotV=max(dot(N,V),.0);let NdotL=max(dot(N,L),.0);let ggx2=geometrySchlickGGX(NdotV,roughness);let ggx1=geometrySchlickGGX(NdotL,roughness);return ggx1*ggx2;}fn integrateBRDF(in_NdotV:f32,roughness:f32)->vec2{let NdotV=max(in_NdotV,.0);var V:vec3;V.x=sqrt(max(.0,1.0-NdotV*NdotV));V.y=.0;V.z=NdotV;var A=.0;var B=.0;let N=vec3(.0,.0,1.0);let sampleCount=2048u;for(var i=0u;i.0){let G=geometrySmith(N,V,L,roughness);let G_Vis=(G*VdotH)/(max(NdotH*NdotV,1e-8));let Fc=pow(1.0-VdotH,5.0);A=A+(1.0-Fc)*G_Vis;B=B+Fc*G_Vis;}}return vec2(A,B)/f32(sampleCount);}struct VertexOutput{@builtin(position)position:vec4,@location(0)uv:vec2,};@vertex fn vs_main(@builtin(vertex_index)vertexIndex:u32)->VertexOutput{var pos=array,3>(vec2(-1.0,-1.0),vec2(3.0,-1.0),vec2(-1.0,3.0));var output:VertexOutput;output.position=vec4(pos[vertexIndex],.0,1.0);output.uv=pos[vertexIndex]*0.5+0.5;return output;}@fragment fn fs_main(@location(0)uv:vec2)->@location(0)vec4{let integratedBRDF=integrateBRDF(uv.x,1.0-uv.y);return vec4(integratedBRDF,.0,1.0);}"})),this.#U||(this.#U=i.createRenderPipeline({label:"BRDF_GENERATOR_PIPELINE",layout:"auto",vertex:{module:this.#L,entryPoint:"vs_main"},fragment:{module:this.#L,entryPoint:"fs_main",targets:[{format:v}]},primitive:{topology:"triangle-list"}})),x.addResourceRenderPass({label:"BRDF_GENERATOR_RENDER_PASS",colorAttachments:[{view:this.#k.createView(),loadOp:"clear",clearValue:{r:0,g:0,b:0,a:1},storeOp:"store"}]},i=>{i.setPipeline(this.#U),i.draw(3)})}}Object.freeze(BRDFGenerator);class ManagementResourceBase extends ResourceBase{#O;constructor(i,g){super(i,g),g||consoleAndThrowError("need managedStateKey",this.constructor.name),this.#O=i.resourceManager[g],this.#O||consoleAndThrowError(g,"is not exist in RedGPUContext.resourceManager",this.constructor.name)}get targetResourceManagedState(){return this.#O}}class BRDFLUTTexture extends ManagementResourceBase{#V;constructor(i){super(i,"managedBitmapTextureState"),this.#N()}get gpuTexture(){return this.#V}get videoMemorySize(){return 65536}#N(){this.#V=this.redGPUContext.resourceManager.brdfGenerator.brdfLUTTexture,this.notifyUpdate()}}Object.freeze(BRDFLUTTexture);class ResourceStateCubeTexture{texture;srcList;cacheKey;useNum=0;uuid;constructor(i){this.texture=i,this.srcList="CubeTexture"===i.constructor.name?i.srcList:void 0,this.cacheKey=i.cacheKey,this.useNum=0,this.uuid=i.uuid}}class ADirectTexture extends ManagementResourceBase{#V;#F;#H=0;#z;#$=1;constructor(i,g,x){super(i,g),this.cacheKey=x}get gpuTexture(){return this.#V}set gpuTexture(i){this.setGpuTexture(i)}get gpuTextureView(){return this.#F}get videoMemorySize(){return this.#H}get format(){return this.#z}get mipLevelCount(){return this.#$}destroy(){const i=this.#V;this.setGpuTexture(null),this.notifyUpdate(!0),this.unregisterResource(),this.cacheKey=null,i&&this.redGPUContext.commandEncoderManager.addDeferredDestroy(i)}setGpuTexture(i){this.targetResourceManagedState.videoMemory-=this.#H,this.#V=i,i?(this.#z=i.format,this.#$=i.mipLevelCount,this.#H=calculateTextureByteSize(i),this.#F=i.createView(this.viewDescriptor)):(this.#F=null,this.#z=null,this.#$=0,this.#H=0),this.targetResourceManagedState.videoMemory+=this.#H,this.notifyUpdate()}}class CubeTexture extends ManagementResourceBase{static defaultViewDescriptor={dimension:"cube",aspect:"all",baseMipLevel:0,mipLevelCount:1,baseArrayLayer:0,arrayLayerCount:6};#V;#j;#$;#K;#X;#H=0;#z;#q;#Y;constructor(i,g,x=!0,v,_,y){super(i,"managedCubeTextureState"),this.#q=v,this.#Y=_,this.#K=x,this.#z=y||`${navigator.gpu.getPreferredCanvasFormat()}-srgb`,this.#j=this.#W(g),this.cacheKey=this.#Z(g);const{table:b}=this.targetResourceManagedState;if(g){let i=b.get(this.cacheKey);if(i){const g=i.texture;return this.#q?.(g),g}this.srcList=g,this.#J()}}get viewDescriptor(){return{...CubeTexture.defaultViewDescriptor,mipLevelCount:this.#$}}get videoMemorySize(){return this.#H}get gpuTexture(){return this.#V}get mipLevelCount(){return this.#$}get srcList(){return this.#j}set srcList(i){this.#j=this.#W(i),this.cacheKey=this.#Z(i),this.#j?.length&&this.#Q(this.#j)}get useMipmap(){return this.#K}set useMipmap(i){this.#K=i,this.#ee()}destroy(){const i=this.#V;this.#te(null),this.notifyUpdate(!0),this.#re(),this.#j=null,this.cacheKey=null,i&&this.redGPUContext.commandEncoderManager.addDeferredDestroy(i)}setGPUTextureDirectly(i,g,x=!0){this.#V&&(this.redGPUContext.commandEncoderManager.addDeferredDestroy(this.#V),this.targetResourceManagedState.videoMemory-=this.#H),this.#V=i,this.#K=x,this.#$=i.mipLevelCount,this.cacheKey=g||`direct_${this.uuid}`,this.#H=calculateTextureByteSize(i),this.targetResourceManagedState.videoMemory+=this.#H,this.notifyUpdate()}#Z(i){return i?i instanceof Array?i.length?i.toString():this.uuid:i.cacheKey||i.srcList.toString():this.uuid}#W(i){return i instanceof Array?i:i?.srcList}#te(i){this.#V=i,i||(this.#X=null),this.notifyUpdate()}#J(){this.redGPUContext.resourceManager.registerManagementResource(this,new ResourceStateCubeTexture(this))}#re(){this.redGPUContext.resourceManager.unregisterManagementResource(this)}#ee(){const{gpuDevice:i,resourceManager:g}=this.redGPUContext,{mipmapGenerator:x}=g;this.#V&&(this.redGPUContext.commandEncoderManager.addDeferredDestroy(this.#V),this.#V=null),this.#$=1;{const g=this.#X,v=g[0],{width:_,height:y}=v,b={size:[_,y,6],format:this.#z,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC,label:`cubeTexture_${this.#j?.toString()||this.uuid}`};this.#K&&(this.#$=getMipLevelCount(_,y),b.mipLevelCount=this.#$,b.usage|=GPUTextureUsage.RENDER_ATTACHMENT);const S=imageBitmapToGPUTexture(i,g,b);this.targetResourceManagedState.videoMemory-=this.#H,this.#H=calculateTextureByteSize(S),this.targetResourceManagedState.videoMemory+=this.#H,this.#K&&x.generateMipmap(S,b),this.#te(S)}}async#Q(i){this.#X=await async function(i){const g=i.map(i=>loadAndCreateBitmapImage(i));return await Promise.all(g)}(i);try{this.#ee(),this.#q?.(this)}catch(i){console.error(i),this.#Y?.(i)}}}Object.freeze(CubeTexture);class DirectCubeTexture extends ADirectTexture{#ie="2d";constructor(i,g,x){super(i,"managedCubeTextureState",g);const{table:v}=this.targetResourceManagedState;if(g){const i=v.get(g);if(i)return i.texture}x&&this.setGpuTexture(x),this.registerResource()}get viewDescriptor(){const i="3d"===this.#ie;return{...CubeTexture.defaultViewDescriptor,dimension:i?"3d":"cube",arrayLayerCount:i?1:6,mipLevelCount:this.mipLevelCount}}setGpuTexture(i){i&&(this.#ie=i.dimension),super.setGpuTexture(i)}registerResource(){this.redGPUContext.resourceManager.registerManagementResource(this,new ResourceStateCubeTexture(this))}unregisterResource(){this.redGPUContext.resourceManager.unregisterManagementResource(this)}}Object.freeze(DirectCubeTexture);const k={RESOURCE:"RESOURCE",PRE_PROCESS:"PRE_PROCESS",MAIN:"MAIN",POST_PROCESS:"POST_PROCESS"};class IrradianceGenerator extends RedGPUObject{#ne;#U;#ae;#se;constructor(i){super(i),this.#ne=new Sampler(i,{magFilter:_.LINEAR,minFilter:_.LINEAR,mipmapFilter:y.LINEAR,addressModeU:v.CLAMP_TO_EDGE,addressModeV:v.CLAMP_TO_EDGE,addressModeW:v.CLAMP_TO_EDGE})}async generate(i,g=32,x=k.RESOURCE){const{resourceManager:v,redGPUContext:_}=this,y=v.createManagedTexture({size:[g,g,6],format:"rgba16float",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.COPY_SRC|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT,dimension:"2d",mipLevelCount:1,label:`Irradiance_Map_Texture_${createUUID()}`});return await this.render(i,y,x),new DirectCubeTexture(_,`Irradiance_Map_${createUUID()}`,y)}async render(i,g,x=k.RESOURCE){const{gpuDevice:v,resourceManager:_,commandEncoderManager:y}=this,b=g.width;this.#ae||(this.#ae=_.createGPUShaderModule("IRRADIANCE_GENERATOR_SHADER_MODULE",{code:"@group(0)@binding(0)var environmentTexture:texture_cube;@group(0)@binding(1)var environmentSampler:sampler;@group(0)@binding(2)var outTexture:texture_storage_2d_array;@group(0)@binding(3)varfaceMatrices:array,6>;#redgpu_include math.PI #redgpu_include math.PI2 #redgpu_include math.INV_PI #redgpu_include math.tnb.getTBN #redgpu_include math.hash.getHammersley @compute @workgroup_size(8,8,1)fn cs_main(@builtin(global_invocation_id)global_id:vec3){let size_u=textureDimensions(outTexture);let size=vec2(size_u);if(global_id.x>=size_u.x||global_id.y>=size_u.y||global_id.z>=6u){return;}let face=global_id.z;let uv=(vec2(global_id.xy)+0.5)/size;let x=uv.x*2.0-1.0;let y=uv.y*2.0-1.0;let localPos=vec4(x,y,1.0,1.0);let normal=normalize((faceMatrices[face]*localPos).xyz);let up=select(vec3(1.0,.0,.0),vec3(.0,.0,1.0),abs(normal.z)<0.999);let tbn=getTBN(normal,up);var irradiance=vec3(.0);var totalWeight=.0;let totalSamples=1024u;let envSize=f32(textureDimensions(environmentTexture).x);let saTexel=4.0*PI/(6.0*envSize*envSize);for(var i=0u;i(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);let worldSample=normalize(tbn*sampleVec);let pdf=max(cosTheta,.001)*INV_PI;let saSample=1.0/(f32(totalSamples)*pdf+.0001);let mipLevel=max(0.5*log2(saSample/saTexel),.0);let sampleColor=textureSampleLevel(environmentTexture,environmentSampler,worldSample,mipLevel);irradiance+=sampleColor.rgb;totalWeight+=1.0;}irradiance=(irradiance/totalWeight)*PI;textureStore(outTexture,global_id.xy,face,vec4(irradiance,1.0));}"})),this.#U||(this.#U=v.createComputePipeline({label:"IRRADIANCE_GENERATOR_PIPELINE",layout:"auto",compute:{module:this.#ae,entryPoint:"cs_main"}}));const S=this.#oe();this.#se||(this.#se=v.createBuffer({size:384,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,label:"Irradiance_face_matrices_uniform"}));const w=new Float32Array(96);S.forEach((i,g)=>w.set(i,16*g)),v.queue.writeBuffer(this.#se,0,w);const L=v.createBindGroup({layout:this.#U.getBindGroupLayout(0),entries:[{binding:0,resource:i.createView({dimension:"cube"})},{binding:1,resource:this.#ne.gpuSampler},{binding:2,resource:g.createView({dimension:"2d-array"})},{binding:3,resource:{buffer:this.#se}}]}),H="Irradiance_Generator_Compute_Pass",computePassExecutor=i=>{i.setPipeline(this.#U),i.setBindGroup(0,L),i.dispatchWorkgroups(Math.ceil(b/8),Math.ceil(b/8),6)};x===k.RESOURCE?y.addResourceComputePass(H,computePassExecutor):x===k.PRE_PROCESS?y.addPreProcessComputePass(H,computePassExecutor):x===k.MAIN?y.addMainComputePass(H,computePassExecutor):y.addPostProcessComputePass(H,computePassExecutor)}#oe(){return[new Float32Array([0,0,-1,0,0,-1,0,0,1,0,0,0,0,0,0,1]),new Float32Array([0,0,1,0,0,-1,0,0,-1,0,0,0,0,0,0,1]),new Float32Array([1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1]),new Float32Array([1,0,0,0,0,0,-1,0,0,-1,0,0,0,0,0,1]),new Float32Array([1,0,0,0,0,-1,0,0,0,0,1,0,0,0,0,1]),new Float32Array([-1,0,0,0,0,-1,0,0,0,0,-1,0,0,0,0,1])]}}Object.freeze(IrradianceGenerator);class PrefilterGenerator extends RedGPUObject{#ne;#U;#ae;#ue=[];constructor(i){super(i),this.#ne=new Sampler(i,{magFilter:_.LINEAR,minFilter:_.LINEAR,addressModeU:v.CLAMP_TO_EDGE,addressModeV:v.CLAMP_TO_EDGE,addressModeW:v.CLAMP_TO_EDGE})}async generate(i,g=512,x,v=k.RESOURCE){const{gpuDevice:_,resourceManager:y,commandEncoderManager:b,redGPUContext:S}=this,w="rgba16float",L=getMipLevelCount(g,g);let H;x?(H=x instanceof GPUTexture?x:x.gpuTexture,H||(H=y.createManagedTexture({size:[g,g,6],format:w,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.COPY_SRC|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT,dimension:"2d",mipLevelCount:L,label:`Prefilter_Map_Texture_${createUUID()}`}),x instanceof DirectCubeTexture&&(x.gpuTexture=H))):H=y.createManagedTexture({size:[g,g,6],format:w,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.COPY_SRC|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT,dimension:"2d",mipLevelCount:L,label:`Prefilter_Map_Texture_${createUUID()}`}),this.#ae||(this.#ae=y.createGPUShaderModule("PREFILTER_GENERATOR_SHADER_MODULE",{code:"@group(0)@binding(0)var environmentTexture:texture_cube;@group(0)@binding(1)var textureSampler:sampler;@group(0)@binding(2)var outTexture:texture_storage_2d_array;struct PrefilterUniforms{faceMatrices:array,6>,roughness:f32,}@group(0)@binding(3)varuniforms:PrefilterUniforms;#redgpu_include math.PI #redgpu_include math.PI2 #redgpu_include math.tnb.getTBN #redgpu_include math.hash.getHammersley fn distribution_ggx(NdotH:f32,roughness:f32)->f32{let a=roughness*roughness;let a2=a*a;let NdotH2=NdotH*NdotH;let denom=(NdotH2*(a2-1.0)+1.0);return a2/(PI*denom*denom);}fn importanceSampleGGX(xi:vec2,N:vec3,roughness:f32)->vec3{let a=roughness*roughness;let phi=PI2*xi.x;let cosTheta=sqrt((1.0-xi.y)/(1.0+(a*a-1.0)*xi.y));let sinTheta=sqrt(max(.0,1.0-cosTheta*cosTheta));let H_local=vec3(cos(phi)*sinTheta,sin(phi)*sinTheta,cosTheta);let up=select(vec3(1.0,.0,.0),vec3(.0,.0,1.0),abs(N.z)<0.999);let tbn=getTBN(N,up);return normalize(tbn*H_local);}@compute @workgroup_size(8,8,1)fn cs_main(@builtin(global_invocation_id)global_id:vec3){let size_u=textureDimensions(outTexture);let size=vec2(size_u);if(global_id.x>=size_u.x||global_id.y>=size_u.y||global_id.z>=6u){return;}let face=global_id.z;let roughness=uniforms.roughness;let uv=(vec2(global_id.xy)+0.5)/size;let x=uv.x*2.0-1.0;let y=uv.y*2.0-1.0;let localPos=vec4(x,y,1.0,1.0);let N=normalize((uniforms.faceMatrices[face]*localPos).xyz);if(roughness<=.0){textureStore(outTexture,global_id.xy,face,textureSampleLevel(environmentTexture,textureSampler,N,.0));return;}let R=N;let V=R;var prefilteredColor=vec3(.0);var totalWeight=.0;let numSamples=1024u;let envSize=f32(textureDimensions(environmentTexture).x);let saTexel=4.0*PI/(6.0*envSize*envSize);for(var i=0u;i.0){let NdotH=max(dot(N,H),.001);let VdotH=max(dot(V,H),.001);let D=distribution_ggx(NdotH,roughness);let pdf=(D*NdotH/(4.0*VdotH))+.0001;let saSample=1.0/(f32(numSamples)*pdf+.0001);let mipLevel=max(0.5*log2(saSample/saTexel),.0);prefilteredColor+=textureSampleLevel(environmentTexture,textureSampler,L,mipLevel).rgb*NdotL;totalWeight+=NdotL;}}if(totalWeight>.0){textureStore(outTexture,global_id.xy,face,vec4(prefilteredColor/totalWeight,1.0));}else{textureStore(outTexture,global_id.xy,face,textureSampleLevel(environmentTexture,textureSampler,N,.0));}}"})),this.#U||(this.#U=_.createComputePipeline({label:"PREFILTER_GENERATOR_PIPELINE",layout:"auto",compute:{module:this.#ae,entryPoint:"cs_main"}}));const z=this.#oe();for(let x=0;x>x),S=x/(L-1),w=new Float32Array(100);z.forEach((i,g)=>w.set(i,16*g)),w[96]=S,this.#ue[x]||(this.#ue[x]=_.createBuffer({size:w.byteLength,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,label:`Prefilter_UniformBuffer_Mip${x}`})),_.queue.writeBuffer(this.#ue[x],0,w);const q=_.createBindGroup({layout:this.#U.getBindGroupLayout(0),entries:[{binding:0,resource:i.createView({dimension:"cube"})},{binding:1,resource:this.#ne.gpuSampler},{binding:2,resource:H.createView({dimension:"2d-array",baseMipLevel:x,mipLevelCount:1})},{binding:3,resource:{buffer:this.#ue[x]}}]}),W=`Prefilter_mip_${x}_compute_pass`,computePassExecutor=i=>{i.setPipeline(this.#U),i.setBindGroup(0,q),i.dispatchWorkgroups(Math.ceil(y/8),Math.ceil(y/8),6)};v===k.RESOURCE?b.addResourceComputePass(W,computePassExecutor):v===k.PRE_PROCESS?b.addPreProcessComputePass(W,computePassExecutor):v===k.MAIN?b.addMainComputePass(W,computePassExecutor):b.addPostProcessComputePass(W,computePassExecutor)}return x instanceof DirectCubeTexture?(x.notifyUpdate(),x):new DirectCubeTexture(S,`Prefilter_Map_${createUUID()}`,H)}#oe(){return[new Float32Array([0,0,-1,0,0,-1,0,0,1,0,0,0,0,0,0,1]),new Float32Array([0,0,1,0,0,-1,0,0,-1,0,0,0,0,0,0,1]),new Float32Array([1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1]),new Float32Array([1,0,0,0,0,0,-1,0,0,-1,0,0,0,0,0,1]),new Float32Array([1,0,0,0,0,-1,0,0,0,0,1,0,0,0,0,1]),new Float32Array([-1,0,0,0,0,-1,0,0,0,0,-1,0,0,0,0,1])]}}Object.freeze(PrefilterGenerator);class EquirectangularToCubeGenerator extends RedGPUObject{#ae;#U;#ne;#se;constructor(i){super(i),this.#ne=new Sampler(i,{magFilter:_.LINEAR,minFilter:_.LINEAR,addressModeU:v.CLAMP_TO_EDGE,addressModeV:v.CLAMP_TO_EDGE})}async generate(i,g=512){const{gpuDevice:x,resourceManager:v,commandEncoderManager:_,redGPUContext:y}=this,b=getMipLevelCount(g,g),S={size:[g,g,6],format:"rgba16float",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.COPY_SRC|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT,dimension:"2d",mipLevelCount:b,label:`EquirectangularToCube_Texture_${createUUID()}`},w=v.createManagedTexture(S);this.#ae||(this.#ae=v.createGPUShaderModule("EQUIRECTANGULAR_TO_CUBE_GENERATOR_SHADER_MODULE",{code:"@group(0)@binding(0)var equirectangularTexture:texture_2d;@group(0)@binding(1)var textureSampler:sampler;@group(0)@binding(2)var outTexture:texture_storage_2d_array;@group(0)@binding(3)varfaceMatrices:array,6>;#redgpu_include math.PI #redgpu_include math.PI2 #redgpu_include math.INV_PI fn directionToSphericalUV(dir:vec3)->vec2{let normalizedDir=normalize(dir);let theta=atan2(normalizedDir.x,normalizedDir.z);let phi=acos(clamp(normalizedDir.y,-1.0,1.0));return vec2(0.5-theta/PI2,phi*INV_PI);}@compute @workgroup_size(8,8,1)fn cs_main(@builtin(global_invocation_id)global_id:vec3){let size=textureDimensions(outTexture);if(global_id.x>=size.x||global_id.y>=size.y||global_id.z>=6u){return;}let face=global_id.z;let uv=(vec2(global_id.xy)+0.5)/vec2(size);let x=uv.x*2.0-1.0;let y=uv.y*2.0-1.0;let localPos=vec4(x,y,1.0,1.0);let direction=(faceMatrices[face]*localPos).xyz;let sphericalUV=directionToSphericalUV(direction);let color=textureSampleLevel(equirectangularTexture,textureSampler,sphericalUV,.0);textureStore(outTexture,global_id.xy,face,color);}"})),this.#U||(this.#U=x.createComputePipeline({label:"EQUIRECTANGULAR_TO_CUBE_GENERATOR_PIPELINE",layout:"auto",compute:{module:this.#ae,entryPoint:"cs_main"}}));const L=this.#oe();this.#se||(this.#se=x.createBuffer({size:384,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,label:"EquirectangularToCube_face_matrices_uniform"}));const k=new Float32Array(96);L.forEach((i,g)=>k.set(i,16*g)),x.queue.writeBuffer(this.#se,0,k);const H=x.createBindGroup({layout:this.#U.getBindGroupLayout(0),entries:[{binding:0,resource:i.createView()},{binding:1,resource:this.#ne.gpuSampler},{binding:2,resource:w.createView({dimension:"2d-array",baseMipLevel:0,mipLevelCount:1})},{binding:3,resource:{buffer:this.#se}}]});return _.addResourceComputePass({label:"EquirectangularToCube_Generator_Compute_Pass"},i=>{i.setPipeline(this.#U),i.setBindGroup(0,H),i.dispatchWorkgroups(Math.ceil(g/8),Math.ceil(g/8),6)}),v.mipmapGenerator.generateMipmap(w,S,!0),new DirectCubeTexture(y,`CubeMap_From_Equirect_${createUUID()}`,w)}#oe(){return[new Float32Array([0,0,-1,0,0,-1,0,0,1,0,0,0,0,0,0,1]),new Float32Array([0,0,1,0,0,-1,0,0,-1,0,0,0,0,0,0,1]),new Float32Array([1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1]),new Float32Array([1,0,0,0,0,0,-1,0,0,-1,0,0,0,0,0,1]),new Float32Array([1,0,0,0,0,-1,0,0,0,0,1,0,0,0,0,1]),new Float32Array([-1,0,0,0,0,-1,0,0,0,0,-1,0,0,0,0,1])]}}Object.freeze(EquirectangularToCubeGenerator);var H=Object.freeze({__proto__:null,BRDFGenerator:BRDFGenerator,BRDFLUTTexture:BRDFLUTTexture,EquirectangularToCubeGenerator:EquirectangularToCubeGenerator,IrradianceGenerator:IrradianceGenerator,PrefilterGenerator:PrefilterGenerator});class DownSampleCubeMapGenerator extends RedGPUObject{#le=new Map;#ce=new Map;#he=null;#fe=null;#de=new Map;#me=new Map;#pe=[];constructor(i){super(i)}createSourceTextureView(i,g){const x=`DOWN_SAMPLE_CUBE_GENERATOR_SOURCE_VIEW_${i.label}_${g}`;if(!this.#de.has(x)){const v=i.createView({label:x,dimension:"cube",baseMipLevel:g,mipLevelCount:1});this.#de.set(x,v)}return this.#de.get(x)}createTargetTextureView(i,g){const x=`DOWN_SAMPLE_CUBE_GENERATOR_TARGET_VIEW_${i.label}_${g}`;if(!this.#de.has(x)){const v=i.createView({label:x,dimension:"2d-array",baseMipLevel:g,mipLevelCount:1,arrayLayerCount:6});this.#de.set(x,v)}return this.#de.get(x)}createBindGroup(i,g,x,v){const _=`DOWN_SAMPLE_CUBE_GENERATOR_BIND_GROUP_${g.label}_${x.label}`;if(!this.#me.has(_)){const{gpuDevice:y}=this,b=y.createBindGroup({label:_,layout:i,entries:[{binding:0,resource:g},{binding:1,resource:x},{binding:2,resource:this.#fe},{binding:3,resource:{buffer:v}}]});this.#me.set(_,b)}return this.#me.get(_)}async downsampleCubemap(i,g=256,x="rgba16float"){try{this.#ge(),this.#xe();const{resourceManager:v}=this;if(!i)throw new Error("Invalid source cubemap texture");if(g<=0||!Number.isInteger(g))throw new Error("Target size must be a positive integer");const _=i.mipLevelCount,y=getMipLevelCount(g,g),b=v.createManagedTexture({size:[g,g,6],format:x,usage:GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.RENDER_ATTACHMENT,dimension:"2d",mipLevelCount:y,label:`DOWN_SAMPLE_CUBE_GENERATOR_TEXTURE_${g}_${Date.now()}`});for(let v=0;v>v),S=this.#ve(i.width,g,v,_);this.#_e(i,b,S,v,y,x)}return this.#ge(),b}catch(i){throw console.error("큐브맵 다운샘플링 실패:",i),this.#ge(),i}}destroy(){this.#ge(),this.#pe.forEach(i=>i.destroy()),this.#pe=[],this.#le.clear(),this.#ce.clear(),this.#he=null,this.#fe=null}#ve(i,g,x,v){const _=i/Math.max(1,g>>x),y=Math.max(0,Math.floor(Math.log2(_)));return Math.min(y,v-1)}#_e(i,g,x,v,_,y){const{gpuDevice:b,commandEncoderManager:S}=this,w=this.#ye(y),L=this.#ce.get(y);this.#pe[v]||(this.#pe[v]=b.createBuffer({size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,label:`DOWN_SAMPLE_CUBE_GENERATOR_UNIFORM_BUFFER_MIP${v}`}));const k=this.#pe[v],H=this.createSourceTextureView(i,x),z=this.createTargetTextureView(g,v),q=this.createBindGroup(L,H,z,k);this.#be(k,x,v,_),S.addResourceComputePass({label:`DOWN_SAMPLE_CUBE_GENERATOR_PASS_MIP${v}`},i=>{i.setPipeline(w),i.setBindGroup(0,q);const g=Math.ceil(_/8);i.dispatchWorkgroups(g,g,6)})}#be(i,g,x,v){const _=new Float32Array([v,g,x,0]);this.gpuDevice.queue.writeBuffer(i,0,_)}#xe(){if(this.#he)return;const{resourceManager:i,redGPUContext:g}=this;this.#fe=new Sampler(g,{minFilter:"linear",magFilter:"linear",mipmapFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge",addressModeW:"clamp-to-edge"}).gpuSampler,this.#he=i.createGPUShaderModule("DOWN_SAMPLE_CUBE_GENERATOR_COMPUTE_SHADER",{code:"struct Uniforms{targetSize:f32,sourceMipLevel:f32,targetMipLevel:f32,padding:f32,};@group(0)@binding(0)var sourceCubemap:texture_cube;@group(0)@binding(1)var targetCubemap:texture_storage_2d_array;@group(0)@binding(2)var cubemapSampler:sampler;@group(0)@binding(3)varuniforms:Uniforms;fn cubemapUVToDirection(uv:vec2,face:u32)->vec3{let u=uv.x*2.0-1.0;let v=uv.y*2.0-1.0;switch face{case 0u:{return vec3(1.0,-v,-u);}case 1u:{return vec3(-1.0,-v,u);}case 2u:{return vec3(u,1.0,v);}case 3u:{return vec3(u,-1.0,-v);}case 4u:{return vec3(u,-v,1.0);}case 5u:{return vec3(-u,-v,-1.0);}default:{return vec3(.0,.0,1.0);}}}fn gaussianWeight(x:f32,y:f32,sigma:f32)->f32{let sigmaSq=sigma*sigma;return exp(-(x*x+y*y)/(2.0*sigmaSq))/(2.0*PI*sigmaSq);}fn clampCubemapUV(uv:vec2)->vec2{return clamp(uv,vec2(.0),vec2(1.0));}#redgpu_include color.getLuminance #redgpu_include math.PI @compute @workgroup_size(8,8,1)fn main(@builtin(global_invocation_id)global_id:vec3){let face=global_id.z;let coord=vec2(global_id.xy);let targetSize=u32(uniforms.targetSize);if(coord.x>=targetSize||coord.y>=targetSize||face>=6u){return;}let uv=(vec2(coord)+0.5)/f32(targetSize);let direction=normalize(cubemapUVToDirection(uv,face));let sourceMipLevel=uniforms.sourceMipLevel;let targetMipLevel=uniforms.targetMipLevel;var color=vec4(.0);if(sourceMipLevel==.0&&targetSize>64u){let sampleCount=16u;let sampleRadius=1.0/f32(targetSize);var totalWeight=.0;for(var i=0u;i(cos(angle)*radius,sin(angle)*radius));let sampleDir=normalize(cubemapUVToDirection(offsetUV,face));let sampleColor=textureSampleLevel(sourceCubemap,cubemapSampler,sampleDir,sourceMipLevel);let weight=gaussianWeight(cos(angle)*radius*f32(targetSize),sin(angle)*radius*f32(targetSize),0.8);color+=sampleColor*weight;totalWeight+=weight;}if(totalWeight>.0){color=color/totalWeight;}}else if(sourceMipLevel==.0&&targetSize>16u){let sampleCount=4u;let invSampleCount=1.0/f32(sampleCount*sampleCount);let sampleOffset=0.5/f32(targetSize);for(var x=0u;x((f32(x)-1.5)*sampleOffset,(f32(y)-1.5)*sampleOffset);let offsetUV=clampCubemapUV(uv+offset);let sampleDir=normalize(cubemapUVToDirection(offsetUV,face));color+=textureSampleLevel(sourceCubemap,cubemapSampler,sampleDir,sourceMipLevel);}}color*=invSampleCount;}else if(targetSize>4u){let sampleCount=2u;let invSampleCount=1.0/f32(sampleCount*sampleCount);let sampleOffset=0.25/f32(targetSize);for(var x=0u;x((f32(x)-0.5)*sampleOffset,(f32(y)-0.5)*sampleOffset);let offsetUV=clampCubemapUV(uv+offset);let sampleDir=normalize(cubemapUVToDirection(offsetUV,face));color+=textureSampleLevel(sourceCubemap,cubemapSampler,sampleDir,sourceMipLevel);}}color*=invSampleCount;}else{color=textureSampleLevel(sourceCubemap,cubemapSampler,direction,sourceMipLevel);}if(targetMipLevel>.0){let luminance=getLuminance(color.rgb);let saturation=0.9+0.1/(1.0+targetMipLevel*0.1);color=vec4(mix(vec3(luminance),color.rgb,saturation),color.a);}textureStore(targetCubemap,vec2(coord),i32(face),color);}"})}#ye(i){if(!this.#le.has(i)){const{gpuDevice:g,resourceManager:x}=this,v=x.createBindGroupLayout(`DOWN_SAMPLE_CUBE_GENERATOR_BGL_${i}`,{entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,texture:{viewDimension:"cube"}},{binding:1,visibility:GPUShaderStage.COMPUTE,storageTexture:{format:i,viewDimension:"2d-array"}},{binding:2,visibility:GPUShaderStage.COMPUTE,sampler:{type:"filtering"}},{binding:3,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}}]}),_=g.createComputePipeline({label:`DOWN_SAMPLE_CUBE_GENERATOR_PIPELINE_${i}`,layout:g.createPipelineLayout({bindGroupLayouts:[v]}),compute:{module:this.#he,entryPoint:"main"}});this.#ce.set(i,v),this.#le.set(i,_)}return this.#le.get(i)}#ge(){this.#de.clear(),this.#me.clear()}}Object.freeze(DownSampleCubeMapGenerator);const z={LOAD:"load",CLEAR:"clear"};Object.freeze(z);const q={STORE:"store",DISCARD:"discard"};Object.freeze(q);class MipmapGenerator extends RedGPUObject{#ne;#Se;#Te;#we;#Me;#de=new Map;#me=new Map;#Pe=new WeakMap;#Re=new WeakMap;constructor(i){super(i),this.#ne=new Sampler(i,{minFilter:"linear"}).gpuSampler,this.#Te={}}createTextureView(i,g,x,v=!1){const _=`${g}_${x}`;if(v){let v=this.#Re.get(i);if(v||(v=new Map,this.#Re.set(i,v)),v.has(_))return v.get(_);const y=i.createView({baseMipLevel:g,mipLevelCount:1,dimension:"2d",baseArrayLayer:x,arrayLayerCount:1,label:`MIPMAP_GENERATOR_CACHED_${i.label}_${_}`});return v.set(_,y),y}{const v=`MIPMAP_GENERATOR_${i.label}_${g}_${x}`;if(!this.#de.has(v)){const _=i.createView({baseMipLevel:g,mipLevelCount:1,dimension:"2d",baseArrayLayer:x,arrayLayerCount:1,label:v});this.#de.set(v,_)}return this.#de.get(v)}}createBindGroup(i,g,x=!1){const{gpuDevice:v}=this;if(x){let x=this.#Pe.get(i);x||(x=new Map,this.#Pe.set(i,x));const _=g.label||"unlabeled";if(x.has(_))return x.get(_);const y=v.createBindGroup({label:`MIPMAP_GENERATOR_BIND_GROUP_CACHED_${i.label}_${_}`,layout:this.#we,entries:[{binding:0,resource:this.#ne},{binding:1,resource:g}]});return x.set(_,y),y}{const x=`${i.label}_${g.label}`;if(this.#me.has(x))return this.#me.get(x);const _=v.createBindGroup({label:`MIPMAP_GENERATOR_BIND_GROUP_TEMP_${x}`,layout:this.#we,entries:[{binding:0,resource:this.#ne},{binding:1,resource:g}]});return this.#me.set(x,_),_}}getMipmapPipeline(i){const{gpuDevice:g,resourceManager:x}=this;let v=this.#Te[i];return v||(this.#Me||(this.#Me=x.createGPUShaderModule("MIPMAP_GENERATOR_SHADER_MODULE",{code:"varpos:array,3>=array,3>(vec2(-1.0,-1.0),vec2(-1.0,3.0),vec2(3.0,-1.0));struct VertexOutput{@builtin(position)position:vec4,@location(0)texCoord:vec2,};@vertex fn vertexMain(@builtin(vertex_index)vertexIndex:u32)->VertexOutput{var output:VertexOutput;output.texCoord=pos[vertexIndex]*vec2(0.5,-0.5)+vec2(0.5);output.position=vec4(pos[vertexIndex],.0,1.0);return output;}@group(0)@binding(0)var imgSampler:sampler;@group(0)@binding(1)var img:texture_2d;@fragment fn fragmentMain(@location(0)texCoord:vec2)->@location(0)vec4{return textureSample(img,imgSampler,texCoord);}"}),this.#we=x.createBindGroupLayout("MIPMAP_GENERATOR_FRAGMENT_BIND_GROUP_LAYOUT",{entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,sampler:{}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{}}]}),this.#Se=x.createGPUPipelineLayout("MIPMAP_GENERATOR_PIPELINE_LAYOUT",{bindGroupLayouts:[this.#we]})),v=g.createRenderPipeline({label:`MIPMAP_GENERATOR_PIPELINE_${i}`,layout:this.#Se,vertex:{module:this.#Me,entryPoint:"vertexMain"},fragment:{module:this.#Me,entryPoint:"fragmentMain",targets:[{format:i}]}}),this.#Te[i]=v),v}generateMipmap(i,g,x=!1,v=k.RESOURCE){x||this.#ge();const{resourceManager:_,commandEncoderManager:y}=this,b=this.getMipmapPipeline(g.format);if("3d"==g.dimension||"1d"==g.dimension)throw new Error("Generating mipmaps for non-2d textures is currently unsupported!");let S=i;const w=g.size[0],L=g.size[1],H=g.size[2]||1,W=g.usage&GPUTextureUsage.RENDER_ATTACHMENT;if(!W){const i={size:{width:Math.max(1,w>>>1),height:Math.max(1,L>>>1),depthOrArrayLayers:H},format:g.format,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC|GPUTextureUsage.RENDER_ATTACHMENT,mipLevelCount:g.mipLevelCount-1};S=_.createManagedTexture(i)}for(let _=0;_{i.setPipeline(b),i.setBindGroup(0,W),i.draw(3,1,0,0)}):v===k.PRE_PROCESS?y.addPreProcessRenderPass(be,i=>{i.setPipeline(b),i.setBindGroup(0,W),i.draw(3,1,0,0)}):v===k.MAIN?y.addMainRenderPass(be,i=>{i.setPipeline(b),i.setBindGroup(0,W),i.draw(3,1,0,0)}):v===k.POST_PROCESS&&y.addPostProcessRenderPass(be,i=>{i.setPipeline(b),i.setBindGroup(0,W),i.draw(3,1,0,0)}),w=g}}return W||y.useEncoder(v,x=>{const v={width:Math.max(1,w>>>1),height:Math.max(1,L>>>1),depthOrArrayLayers:H};for(let _=1;_>>1),v.height=Math.max(1,v.height>>>1)}),W||y.addDeferredDestroy(S),x||this.#ge(),i}destroy(){this.#ge()}#ge(){this.#de.clear(),this.#me.clear()}}Object.freeze(MipmapGenerator);const W={TILE_COUNT_X:32,TILE_COUNT_Y:32,TILE_COUNT_Z:48,WORKGROUP_SIZE_X:8,WORKGROUP_SIZE_Y:4,WORKGROUP_SIZE_Z:8,MAX_LIGHTS_PER_CLUSTER:100,MAX_CLUSTER_LIGHTS:1024,getTotalTileSize:()=>W.TILE_COUNT_X*W.TILE_COUNT_Y*W.TILE_COUNT_Z,getClusterLightsBufferSize:()=>{const i=W.getTotalTileSize();return 8*i+8*W.MAX_LIGHTS_PER_CLUSTER*i+4},getDispatchSize:()=>[Math.ceil(W.TILE_COUNT_X/W.WORKGROUP_SIZE_X),Math.ceil(W.TILE_COUNT_Y/W.WORKGROUP_SIZE_Y),Math.ceil(W.TILE_COUNT_Z/W.WORKGROUP_SIZE_Z)]};Object.freeze(W);var be,je,Ke,Xe,Ye,Ze,Je,Qe,et,tt,it="#redgpu_include skyAtmosphere.skyAtmosphereFn @group(0)@binding(0)var transmittanceLUT:texture_storage_2d;@group(0)@binding(1)varparams:SkyAtmosphere;@compute @workgroup_size(16,16)fn main(@builtin(global_invocation_id)global_id:vec3){let size=textureDimensions(transmittanceLUT);if(global_id.x>=size.x||global_id.y>=size.y){return;}let uv=(vec2(global_id.xy)+0.5)/vec2(size);let x=uv.x*2.0-1.0;let cosTheta=sign(x)*x*x;let viewHeight=clamp((1.0-uv.y)*params.atmosphereHeight,.0,params.atmosphereHeight);let T=exp(-min(getOpticalDepth(viewHeight,cosTheta),vec3(100.0)));textureStore(transmittanceLUT,global_id.xy,vec4(T,1.0));}fn getOpticalDepth(viewHeight:f32,cosTheta:f32)->vec3{let groundRadius=params.groundRadius;let rayOrigin=vec3(.0,viewHeight+groundRadius,.0);let sinTheta=sqrt(max(.0,1.0-cosTheta*cosTheta));let rayDir=vec3(sinTheta,cosTheta,.0);let tMax=getRaySphereIntersection(rayOrigin,rayDir,groundRadius+params.atmosphereHeight);if(tMax<=.0){return vec3(.0);}let tEarth=getRaySphereIntersection(rayOrigin,rayDir,groundRadius);if(groundRadius>.0&&tEarth>.0){return vec3(MAX_TAU);}return integrateOpticalDepth(rayOrigin,rayDir,.0,tMax,TRANSMITTANCE_STEPS,params);}";!function(i){var g,x,v,_,y;(g=i.hash||(i.hash={})).getHash1D="fn getHash1D(seed:f32)->f32{var x=u32(abs(seed));x=((x>>16u)^ x)*0x45d9f3bu;x=((x>>16u)^ x)*0x45d9f3bu;x=(x>>16u)^ x;return f32(x)/4294967296.0;}",g.getHash1D_vec2="fn getHash1D_vec2(coord:vec2)->f32{let q=vec2(abs(coord));var x=(q.x*73856093u)^(q.y*19349663u);x=((x>>16u)^ x)*0x45d9f3bu;x=((x>>16u)^ x)*0x45d9f3bu;x=(x>>16u)^ x;return f32(x)/4294967296.0;}",g.getHash1D_vec3="fn getHash1D_vec3(v:vec3)->f32{let q=vec3(abs(v));var x=(q.x*73856093u)^(q.y*19349663u)^(q.z*83492791u);x=((x>>16u)^ x)*0x45d9f3bu;x=((x>>16u)^ x)*0x45d9f3bu;x=(x>>16u)^ x;return f32(x)/4294967296.0;}",g.getHash1D_vec4="fn getHash1D_vec4(v:vec4)->f32{let q=vec4(abs(v));var x=(q.x*73856093u)^(q.y*19349663u)^(q.z*83492791u)^(q.w*4000000007u);x=((x>>16u)^ x)*0x45d9f3bu;x=((x>>16u)^ x)*0x45d9f3bu;x=(x>>16u)^ x;return f32(x)/4294967296.0;}",g.getHash2D_vec2="fn getHash2D_vec2(coord:vec2)->vec2{var q=vec2(abs(coord));var x=(q.x*1597334677u)^(q.y*3812015801u);x=((x>>16u)^ x)*0x45d9f3bu;x=((x>>16u)^ x)*0x45d9f3bu;x=(x>>16u)^ x;let r=f32(x)/4294967296.0;x=(x*1103515245u+12345u);let g=f32(x)/4294967296.0;return vec2(r,g);}",g.getHash3D_vec3="fn getHash3D_vec3(position:vec3)->vec3{var q=vec3(abs(position));var x=(q.x*73856093u)^(q.y*19349663u)^(q.z*83492791u);x=((x>>16u)^ x)*0x45d9f3bu;x=((x>>16u)^ x)*0x45d9f3bu;x=(x>>16u)^ x;let r=f32(x)/4294967296.0;x=(x*1103515245u+12345u);let g=f32(x)/4294967296.0;x=(x*1103515245u+12345u);let b=f32(x)/4294967296.0;return vec3(r,g,b);}",g.getBitHash1D="fn getBitHash1D(seed:f32)->f32{var x=bitcast(seed);x=((x>>16u)^ x)*0x45d9f3bu;x=((x>>16u)^ x)*0x45d9f3bu;x=(x>>16u)^ x;return f32(x)/4294967296.0;}",g.getBitHash1D_vec2="fn getBitHash1D_vec2(coord:vec2)->f32{let q=bitcast>(coord);var x=(q.x*73856093u)^(q.y*19349663u);x=((x>>16u)^ x)*0x45d9f3bu;x=((x>>16u)^ x)*0x45d9f3bu;x=(x>>16u)^ x;return f32(x)/4294967296.0;}",g.getBitHash1D_vec3="fn getBitHash1D_vec3(v:vec3)->f32{var q=bitcast>(v);var x=(q.x*73856093u)^(q.y*19349663u)^(q.z*83492791u);x=((x>>16u)^ x)*0x45d9f3bu;x=((x>>16u)^ x)*0x45d9f3bu;x=(x>>16u)^ x;return f32(x)/4294967296.0;}",g.getBitHash1D_vec4="fn getBitHash1D_vec4(v:vec4)->f32{var q=bitcast>(v);var x=(q.x*73856093u)^(q.y*19349663u)^(q.z*83492791u)^(q.w*4000000007u);x=((x>>16u)^ x)*0x45d9f3bu;x=((x>>16u)^ x)*0x45d9f3bu;x=(x>>16u)^ x;return f32(x)/4294967296.0;}",g.getBitHash2D_vec2="fn getBitHash2D_vec2(coord:vec2)->vec2{var q=bitcast>(coord);var x=(q.x*1597334677u)^(q.y*3812015801u);x=((x>>16u)^ x)*0x45d9f3bu;x=((x>>16u)^ x)*0x45d9f3bu;x=(x>>16u)^ x;let r=f32(x)/4294967296.0;x=(x*1103515245u+12345u);let g=f32(x)/4294967296.0;return vec2(r,g);}",g.getBitHash3D_vec3="fn getBitHash3D_vec3(position:vec3)->vec3{var q=bitcast>(position);var x=(q.x*73856093u)^(q.y*19349663u)^(q.z*83492791u);x=((x>>16u)^ x)*0x45d9f3bu;x=((x>>16u)^ x)*0x45d9f3bu;x=(x>>16u)^ x;let r=f32(x)/4294967296.0;x=(x*1103515245u+12345u);let g=f32(x)/4294967296.0;x=(x*1103515245u+12345u);let b=f32(x)/4294967296.0;return vec3(r,g,b);}",g.getRadicalInverseVanDerCorput="fn getRadicalInverseVanDerCorput(bits_in:u32)->f32{var bits=bits_in;bits=(bits<<16u)|(bits>>16u);bits=((bits & 0x55555555u)<<1u)|((bits & 0xAAAAAAAAu)>>1u);bits=((bits & 0x33333333u)<<2u)|((bits & 0xCCCCCCCCu)>>2u);bits=((bits & 0x0F0F0F0Fu)<<4u)|((bits & 0xF0F0F0F0u)>>4u);bits=((bits & 0x00FF00FFu)<<8u)|((bits & 0xFF00FF00u)>>8u);return f32(bits)*2.3283064365386963e-10;}",g.getHammersley="#redgpu_include math.hash.getRadicalInverseVanDerCorput fn getHammersley(i:u32,N:u32)->vec2{return vec2(f32(i)/f32(N),getRadicalInverseVanDerCorput(i));}",i.getInterleavedGradientNoise="fn getInterleavedGradientNoise(screenCoord:vec2)->f32{let magic=vec3(.06711056,.00583715,52.9829189);return fract(magic.z*fract(dot(screenCoord,magic.xy)));}",i.getMotionVector="#redgpu_include math.EPSILON fn getMotionVector(currentClipPos:vec4,prevClipPos:vec4,)->vec2{let currentNDC=currentClipPos.xy/max(currentClipPos.w,EPSILON);let prevNDC=prevClipPos.xy/max(prevClipPos.w,EPSILON);var motionVector=currentNDC-prevNDC;motionVector.y=-motionVector.y;let uvMotionVector=motionVector*0.5;return uvMotionVector;}",i.getIsFinite="fn getIsFiniteScalar(x:f32)->bool{return x==x&&abs(x)<1e30;}fn getIsFiniteVec3(v:vec3)->vec3{return vec3(v.x==v.x&&abs(v.x)<1e30,v.y==v.y&&abs(v.y)<1e30,v.z==v.z&&abs(v.z)<1e30);}",(x=i.billboard||(i.billboard={})).getBillboardMatrix="fn getBillboardMatrix(viewMatrix:mat4x4,modelMatrix:mat4x4,useStandardScale:u32)->mat4x4{var resultMatrix=viewMatrix*modelMatrix;if(useStandardScale==1u){let scaleX=length(modelMatrix[0].xyz);let scaleY=length(modelMatrix[1].xyz);let scaleZ=length(modelMatrix[2].xyz);resultMatrix[0]=vec4(scaleX,.0,.0,resultMatrix[0].w);resultMatrix[1]=vec4(.0,scaleY,.0,resultMatrix[1].w);resultMatrix[2]=vec4(.0,.0,scaleZ,resultMatrix[2].w);}else{resultMatrix[0]=vec4(modelMatrix[0][0],.0,.0,resultMatrix[0].w);resultMatrix[1]=vec4(.0,modelMatrix[1][1],.0,resultMatrix[1].w);resultMatrix[2]=vec4(.0,.0,modelMatrix[2][2],resultMatrix[2].w);}return resultMatrix;}",x.getBillboardResult="struct BillboardResult{position:vec4,vertexPosition:vec3,vertexNormal:vec3,}fn getBillboardResult(input_position:vec3,input_normal:vec3,modelMatrix:mat4x4,viewMatrix:mat4x4,projectionMatrix:mat4x4,resolution:vec2,useBillboard:u32,usePixelSize:u32,pixelSize:f32,renderRatioX:f32,renderRatioY:f32)->BillboardResult{var result:BillboardResult;let ratioScaleMatrix=mat4x4(renderRatioX,0,0,0,0,renderRatioY,0,0,0,0,1,0,0,0,0,1);var viewPos:vec4;var viewNormal:vec4;if(useBillboard==1u){let billboardMatrix=getBillboardMatrix(viewMatrix,modelMatrix,1u);if(usePixelSize==1u){let viewCenter=billboardMatrix*vec4(.0,.0,.0,1.0);let clipCenter=projectionMatrix*viewCenter;let scaleX=(pixelSize/resolution.x)*2.0*renderRatioX;let scaleY=(pixelSize/resolution.y)*2.0*renderRatioY;result.position=vec4(clipCenter.xy+input_position.xy*vec2(scaleX,scaleY)*clipCenter.w,clipCenter.zw);viewPos=viewCenter;viewNormal=vec4(.0,.0,1.0,.0);}else{viewPos=billboardMatrix*ratioScaleMatrix*vec4(input_position,1.0);viewNormal=vec4(.0,.0,1.0,.0);result.position=projectionMatrix*viewPos;}}else{viewPos=viewMatrix*modelMatrix*ratioScaleMatrix*vec4(input_position,1.0);viewNormal=viewMatrix*modelMatrix*ratioScaleMatrix*vec4(input_normal,.0);result.position=projectionMatrix*viewPos;}result.vertexPosition=viewPos.xyz;result.vertexNormal=normalize(viewNormal.xyz);return result;}",(v=i.direction||(i.direction={})).getViewDirection="fn getViewDirection(worldPosition:vec3,cameraPosition:vec3)->vec3{return normalize(cameraPosition-worldPosition);}",v.getRayDirection="fn getRayDirection(worldPosition:vec3,cameraPosition:vec3)->vec3{return normalize(worldPosition-cameraPosition);}",v.getReflectionVectorFromViewDirection="fn getReflectionVectorFromViewDirection(viewDirection:vec3,normal:vec3)->vec3{return reflect(-viewDirection,normal);}",(_=i.reconstruct||(i.reconstruct={})).getNDCFromDepth="fn getNDCFromDepth(uv:vec2,depth:f32)->vec3{return vec3(uv.x*2.0-1.0,(1.0-uv.y)*2.0-1.0,depth);}",_.getWorldPositionFromDepth="#redgpu_include math.reconstruct.getNDCFromDepth fn getWorldPositionFromDepth(uv:vec2,depth:f32,inverseProjectionViewMatrix:mat4x4)->vec3{let ndc=getNDCFromDepth(uv,depth);let worldPos4=inverseProjectionViewMatrix*vec4(ndc,1.0);return worldPos4.xyz/worldPos4.w;}",_.getViewPositionFromDepth="#redgpu_include math.reconstruct.getNDCFromDepth fn getViewPositionFromDepth(uv:vec2,depth:f32,inverseProjectionMatrix:mat4x4)->vec3{let ndc=getNDCFromDepth(uv,depth);let viewPos4=inverseProjectionMatrix*vec4(ndc,1.0);return viewPos4.xyz/viewPos4.w;}",_.getWorldNormalFromGNormalBuffer="fn getWorldNormalFromGNormalBuffer(gBufferNormal:vec3)->vec3{return normalize(gBufferNormal*2.0-1.0);}",_.getViewNormalFromGNormalBuffer="#redgpu_include math.reconstruct.getWorldNormalFromGNormalBuffer fn getViewNormalFromGNormalBuffer(gBufferNormal:vec3,viewMatrix:mat4x4)->vec3{let worldNormal=getWorldNormalFromGNormalBuffer(gBufferNormal);return normalize((viewMatrix*vec4(worldNormal,.0)).xyz);}",(y=i.tnb||(i.tnb={})).getTBNFromVertexTangent="fn getTBNFromVertexTangent(inputNormal:vec3,inputVertexTangent:vec4)->mat3x3{let tangent=normalize(inputVertexTangent.xyz-inputNormal*dot(inputVertexTangent.xyz,inputNormal));let bitangent=cross(inputNormal,tangent)*inputVertexTangent.w;return mat3x3(tangent,bitangent,inputNormal);}",y.getTBN="fn getTBN(inputNormal:vec3,inputTangent:vec3)->mat3x3{let tangent=normalize(inputTangent-inputNormal*dot(inputTangent,inputNormal));let bitangent=cross(inputNormal,tangent);return mat3x3(tangent,bitangent,inputNormal);}",y.getTBNFromCotangent="fn getTBNFromCotangent(inputNormal:vec3,inputWorldPos:vec3,inputUV:vec2)->mat3x3{let dp1=dpdx(inputWorldPos);let dp2=dpdy(inputWorldPos);let duv1=dpdx(inputUV);let duv2=dpdy(inputUV);let dp2perp=cross(dp2,inputNormal);let dp1perp=cross(inputNormal,dp1);let tangent=dp2perp*duv1.x+dp1perp*duv2.x;let bitangent=dp2perp*duv1.y+dp1perp*duv2.y;let invmax=inverseSqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));return mat3x3(tangent*invmax,-bitangent*invmax,inputNormal);}",y.getNormalFromNormalMap="fn getNormalFromNormalMap(sampledNormalColor:vec3,tbn:mat3x3,strength:f32)->vec3{var n:vec2=sampledNormalColor.xy*2.0-1.0;n.y=-n.y;n*=strength;let z:f32=sqrt(max(.0,1.0-dot(n,n)));return normalize(tbn*vec3(n,z));}",i.PI="const PI: f32 = 3.141592653589793;",i.PI2="const PI2: f32 = 6.283185307179586;",i.HPI="const HPI: f32 = 1.5707963267948966;",i.INV_PI="const INV_PI: f32 = 0.31830988618379067;",i.DEG_TO_RAD="const DEG_TO_RAD: f32 = 0.017453292519943295;",i.RAD_TO_DEG="const RAD_TO_DEG: f32 = 57.29577951308232;",i.EPSILON="const EPSILON: f32 = 1e-6;",i.FLT_MAX="const FLT_MAX: f32 = 3.402823466e+38;"}(be||(be={})),function(i){i.getShadowCoord="fn getShadowCoord(worldPosition:vec3,lightViewProjectionMatrix:mat4x4)->vec3{let posFromLight=lightViewProjectionMatrix*vec4(worldPosition,1.0);let shadowCoordNDC=posFromLight.xyz/posFromLight.w;return vec3(shadowCoordNDC.xy*vec2(0.5,-0.5)+vec2(0.5,0.5),shadowCoordNDC.z);}",i.getShadowClipPosition="fn getShadowClipPosition(worldPosition:vec3,lightViewProjectionMatrix:mat4x4)->vec4{return lightViewProjectionMatrix*vec4(worldPosition,1.0);}",i.getDirectionalShadowVisibility="fn getDirectionalShadowVisibility(directionalShadowMap:texture_depth_2d,directionalShadowMapSampler:sampler_comparison,shadowDepthTextureSize:u32,bias:f32,shadowCoord:vec3)->f32{let oneOverShadowDepthTextureSize=1.0/f32(shadowDepthTextureSize);let shadowDepth=clamp(shadowCoord.z,.0,1.0);var visibility:f32=.0;for(var y=-1;y<=1;y++){for(var x=-1;x<=1;x++){let offset=vec2f(vec2(x,y))*oneOverShadowDepthTextureSize;let tUV=shadowCoord.xy+offset;let sampleVisibility=textureSampleCompare(directionalShadowMap,directionalShadowMapSampler,tUV,shadowDepth-bias);if(tUV.x<.0||tUV.x>1.0||tUV.y<.0||tUV.y>1.0){visibility+=1.0;}else{visibility+=sampleVisibility;}}}visibility/=9.0;return visibility;}"}(je||(je={})),function(i){i.rgbToYCoCg="fn rgbToYCoCg(rgb:vec3)->vec3{let y=dot(rgb,vec3(0.25,0.5,0.25));let co=dot(rgb,vec3(0.5,.0,-0.5));let cg=dot(rgb,vec3(-0.25,0.5,-0.25));return vec3(y,co,cg);}",i.YCoCgToRgb="fn YCoCgToRgb(ycocg:vec3)->vec3{let y=ycocg.x;let co=ycocg.y;let cg=ycocg.z;return vec3(y+co-cg,y+cg,y-co-cg);}",i.linearToSrgbVec3="fn linearToSrgbVec3(linearColor:vec3)->vec3{return select(12.92*linearColor,1.055*pow(linearColor,vec3(1.0/2.4))-.055,linearColor>vec3(.0031308));}",i.linearToSrgbVec4="#redgpu_include color.linearToSrgbVec3 fn linearToSrgbVec4(linearColor:vec4)->vec4{return vec4(linearToSrgbVec3(linearColor.rgb),linearColor.a);}",i.srgbToLinearVec3="fn srgbToLinearVec3(srgbColor:vec3)->vec3{return select(srgbColor/12.92,pow((srgbColor+.055)/1.055,vec3(2.4)),srgbColor>vec3(.04045));}",i.srgbToLinearVec4="#redgpu_include color.srgbToLinearVec3 fn srgbToLinearVec4(srgbColor:vec4)->vec4{return vec4(srgbToLinearVec3(srgbColor.rgb),srgbColor.a);}",i.getLuminance="fn getLuminance(rgb:vec3)->f32{return dot(rgb,vec3(0.2126,0.7152,.0722));}",i.getTintBlendMode="#redgpu_include math.EPSILON fn rgbToHsl(rgb:vec3)->vec3{let maxVal:f32=max(max(rgb.r,rgb.g),rgb.b);let minVal:f32=min(min(rgb.r,rgb.g),rgb.b);let delta:f32=maxVal-minVal;let lightness:f32=(maxVal+minVal)*0.5;if(delta(.0,.0,lightness);}var saturation:f32;if(lightness<0.5){saturation=delta/(maxVal+minVal+EPSILON);}else{saturation=delta/(2.0-maxVal-minVal+EPSILON);}var hue:f32=.0;if(abs(rgb.r-maxVal)(hue,saturation,lightness);}fn hslToRgb(hsl:vec3)->vec3{let h=hsl.x;let s=hsl.y;let l=hsl.z;if(s==.0){return vec3(l,l,l);}var q:f32;if(l<0.5){q=l*(1.0+s);}else{q=l+s-l*s;}let p=2.0*l-q;var r:f32;var g:f32;var b:f32;for(var i:i32=0;i<3;i=i+1){var t:f32;if(i==0){t=h+1.0/3.0;}else if(i==1){t=h;}else{t=h-1.0/3.0;}if(t<.0){t=t+1.0;}if(t>1.0){t=t-1.0;}var color:f32;if(t<1.0/6.0){color=p+(q-p)*6.0*t;}else if(t<1.0/2.0){color=q;}else if(t<2.0/3.0){color=p+(q-p)*(2.0/3.0-t)*6.0;}else{color=p;}if(i==0){r=color;}else if(i==1){g=color;}else{b=color;}}return vec3(r,g,b);}fn getTintBlendMode(baseColor:vec4,tintBlendMode:u32,tint:vec4)->vec4{var tintedColor:vec3;switch(tintBlendMode){case 0u:{tintedColor=mix(baseColor.rgb,tint.rgb,tint.a);}case 1u:{tintedColor=baseColor.rgb*tint.rgb;}case 2u:{tintedColor=max(baseColor.rgb,tint.rgb);}case 3u:{tintedColor=1.0-(1.0-baseColor.rgb)*(1.0-tint.rgb);}case 4u:{tintedColor=clamp(baseColor.rgb+tint.rgb,vec3(.0),vec3(1.0));}case 5u:{tintedColor=clamp(baseColor.rgb-tint.rgb,vec3(.0),vec3(1.0));}case 6u:{tintedColor=min(baseColor.rgb,tint.rgb);}case 7u:{tintedColor=mix(2.0*baseColor.rgb*tint.rgb,1.0-2.0*(1.0-baseColor.rgb)*(1.0-tint.rgb),step(vec3(0.5),baseColor.rgb));}case 8u:{tintedColor=clamp(baseColor.rgb/(1.0-tint.rgb+EPSILON),vec3(.0),vec3(1.0));}case 9u:{tintedColor=1.0-clamp((1.0-baseColor.rgb)/(tint.rgb+EPSILON),vec3(.0),vec3(1.0));}case 10u:{tintedColor=mix(2.0*baseColor.rgb*tint.rgb,1.0-2.0*(1.0-baseColor.rgb)*(1.0-tint.rgb),step(vec3(0.5),tint.rgb));}case 11u:{tintedColor=mix(baseColor.rgb*(tint.rgb+tint.rgb-vec3(1.0)),baseColor.rgb+tint.rgb-baseColor.rgb*tint.rgb,step(vec3(0.5),tint.rgb));}case 12u:{tintedColor=abs(baseColor.rgb-tint.rgb);}case 13u:{tintedColor=baseColor.rgb+tint.rgb-2.0*baseColor.rgb*tint.rgb;}case 14u:{tintedColor=clamp(baseColor.rgb/(tint.rgb+EPSILON),vec3(.0),vec3(1.0));}case 15u:{tintedColor=mix(clamp(baseColor.rgb/(1.0-(tint.rgb-vec3(0.5))*2.0+EPSILON),vec3(.0),vec3(1.0)),1.0-clamp((1.0-baseColor.rgb)/(tint.rgb*2.0+EPSILON),vec3(.0),vec3(1.0)),step(vec3(0.5),tint.rgb));}case 16u:{tintedColor=clamp(baseColor.rgb+tint.rgb-vec3(1.0),vec3(.0),vec3(1.0));}case 17u:{tintedColor=mix(min(baseColor.rgb,2.0*tint.rgb),max(baseColor.rgb,2.0*tint.rgb-vec3(1.0)),step(vec3(0.5),tint.rgb));}case 18u:{let baseHsl=rgbToHsl(baseColor.rgb);let tintHsl=rgbToHsl(tint.rgb);tintedColor=hslToRgb(vec3(baseHsl.x,tintHsl.y,baseHsl.z));}case 19u:{let baseHsl=rgbToHsl(baseColor.rgb);let tintHsl=rgbToHsl(tint.rgb);tintedColor=hslToRgb(vec3(tintHsl.x,baseHsl.y,baseHsl.z));}case 20u:{let baseHsl=rgbToHsl(baseColor.rgb);let tintHsl=rgbToHsl(tint.rgb);tintedColor=hslToRgb(vec3(baseHsl.x,baseHsl.y,tintHsl.z));}case 21u:{let baseHsl=rgbToHsl(baseColor.rgb);let tintHsl=rgbToHsl(tint.rgb);tintedColor=hslToRgb(vec3(tintHsl.x,tintHsl.y,baseHsl.z));}case 22u:{tintedColor=1.0-abs(1.0-baseColor.rgb-tint.rgb);}default:{tintedColor=baseColor.rgb;}}return vec4(tintedColor,baseColor.a*tint.a);}"}(Ke||(Ke={})),function(i){i.getLinearizeDepth="#redgpu_include math.EPSILON fn getLinearizeDepth(depthSample:f32,near:f32,far:f32)->f32{let d=clamp(depthSample,.0,1.0);return(near*far)/max(EPSILON,far-d*(far-near));}"}(Xe||(Xe={})),function(i){i.getLightDistanceAttenuation="#redgpu_include math.EPSILON fn getLightDistanceAttenuation(distance:f32,radius:f32)->f32{let d2=distance*distance;let factor=distance/radius;let factor2=factor*factor;let factor4=factor2*factor2;let windowing=clamp(1.0-factor4,.0,1.0);return(windowing*windowing)/max(d2,.0001);}",i.getLightAngleAttenuation="#redgpu_include math.EPSILON fn getLightAngleAttenuation(lightToVertexDirection:vec3,lightDirection:vec3,innerCutoff:f32,outerCutoff:f32)->f32{let cosTheta=dot(lightToVertexDirection,lightDirection);let cosOuter=cos(radians(outerCutoff));let cosInner=cos(radians(innerCutoff));let epsilon=max(EPSILON,cosInner-cosOuter);let factor=clamp((cosTheta-cosOuter)/epsilon,.0,1.0);return factor*factor;}"}(Ye||(Ye={})),function(i){i.skyAtmosphereFn="#redgpu_include math.PI #redgpu_include math.PI2 #redgpu_include math.HPI #redgpu_include math.INV_PI #redgpu_include math.DEG_TO_RAD #redgpu_include math.EPSILON #redgpu_include systemStruct.SkyAtmosphere #redgpu_include color.getLuminance const MAX_TAU:f32=100.0;const SUN_ANGULAR_RADIUS_RAD:f32=.00465;const SUN_SOLID_ANGLE_BASE:f32=6.794e-5;const TRANSMITTANCE_STEPS:u32=40u;const MULTI_SCAT_STEPS:u32=40u;const SKY_VIEW_STEPS:u32=128u;const AP_STEPS:u32=64u;const MULTI_SCAT_SAMPLES:u32=128u;const IRRADIANCE_SAMPLES:u32=256u;const SUN_RADIANCE_BOOST:f32=1.0;const MIE_GLOW_SUPPRESS:f32=0.40;const NEAR_FIELD_CORRECTION_DIST:f32=0.2;struct AtmosphereDensities{rhoR:f32,rhoM:f32,rhoO:f32};struct AtmosphereCoefficients{scatTotal:vec3,extinction:vec3};fn getRaySphereIntersection(rayOrigin:vec3,rayDir:vec3,sphereRadius:f32)->f32{let b=dot(rayOrigin,rayDir);let c=dot(rayOrigin,rayOrigin)-sphereRadius*sphereRadius;let delta=b*b-c;if(delta<.0){return-1.0;}let s=sqrt(delta);let t0=-b-s;let t1=-b+s;if(t0>EPSILON){return t0;}if(t1>EPSILON){return t1;}return-1.0;}fn getPlanetIntersection(origin:vec3,dir:vec3,r:f32)->vec2{let b=dot(origin,dir);let c=dot(origin,origin)-r*r;let delta=b*b-c;if(delta<.0){return vec2(-1.0);}let s=sqrt(delta);return vec2(-b-s,-b+s);}fn getTransmittanceUV(viewHeight:f32,cosTheta:f32,atmosphereHeight:f32)->vec2{let mu=clamp(cosTheta,-1.0,1.0);let u=clamp(0.5+0.5*sign(mu)*sqrt(abs(mu)),.001,0.999);let v=clamp(1.0-viewHeight/atmosphereHeight,.001,0.999);return vec2(u,v);}fn getSkyViewUV(viewDir:vec3,viewHeight:f32,groundRadius:f32,atmosphereHeight:f32)->vec2{var azimuth:f32;if(abs(viewDir.z)<1e-6&&abs(viewDir.x)<1e-6){azimuth=.0;}else{azimuth=atan2(viewDir.z,viewDir.x);}let u=clamp((azimuth/PI2)+0.5,.001,0.999);let r=groundRadius;let h=max(.0001,viewHeight);let horizonCos=-sqrt(max(.0,h*(2.0*r+h)))/(r+h);let horizonElevation=asin(clamp(horizonCos,-1.0,1.0));let viewElevation=asin(clamp(viewDir.y,-1.0,1.0));var v:f32;if(viewElevation>=horizonElevation){let ratio=(viewElevation-horizonElevation)/(HPI-horizonElevation);v=0.5*(1.0-sqrt(max(.0,ratio)));}else{let ratio=(horizonElevation-viewElevation)/(horizonElevation+HPI);v=0.5*(1.0+sqrt(max(.0,ratio)));}return vec2(u,clamp(v,.001,0.999));}fn getTransmittance(transmittanceLUT:texture_2d,skyAtmosphereSampler:sampler,viewHeight:f32,cosTheta:f32,atmosphereHeight:f32)->vec3{let uv=getTransmittanceUV(viewHeight,cosTheta,atmosphereHeight);var transmittance=textureSampleLevel(transmittanceLUT,skyAtmosphereSampler,uv,.0).rgb;let mu=clamp(cosTheta,-1.0,1.0);if(mu<.0){let groundMask=smoothstep(-.015,.0,mu);transmittance*=groundMask;}return transmittance;}fn getPlanetShadowMask(p:vec3,sunDir:vec3,r:f32,params:SkyAtmosphere)->f32{if(r>.0&&getRaySphereIntersection(p,sunDir,r)>.0){return .0;}return 1.0;}fn getAtmosphereDensities(viewHeight:f32,params:SkyAtmosphere)->AtmosphereDensities{var d:AtmosphereDensities;if(viewHeight<.0){d.rhoR=.0;d.rhoM=.0;d.rhoO=.0;}else{d.rhoR=exp(-viewHeight/params.rayleighExponentialDistribution);d.rhoM=exp(-viewHeight/params.mieExponentialDistribution);let ozoneDist=abs(viewHeight-params.absorptionTipAltitude);d.rhoO=max(.0,1.0-ozoneDist/params.absorptionTentWidth);}return d;}fn getSunTransmittanceManual(p:vec3,sunDir:vec3,params:SkyAtmosphere)->vec3{let r=params.groundRadius;let tMax=getRaySphereIntersection(p,sunDir,r+params.atmosphereHeight);if(tMax<=.0){return vec3(1.0);}let intersect=getPlanetIntersection(p,sunDir,r);if(r>.0&&intersect.x>EPSILON){return vec3(.0);}var optExt=vec3(.0);let halfSteps=TRANSMITTANCE_STEPS/2u;if(intersect.x>EPSILON&&intersect.x.0&&tMax>intersect.y){optExt+=integrateOpticalDepth(p,sunDir,intersect.y,tMax,halfSteps,params);}}else{optExt=integrateOpticalDepth(p,sunDir,.0,tMax,TRANSMITTANCE_STEPS,params);}return exp(-min(optExt,vec3(MAX_TAU)));}fn getPhysicalTransmittance(p:vec3,sunDir:vec3,r:f32,atmosphereHeight:f32,params:SkyAtmosphere)->vec3{let minElevationRad=params.transmittanceMinLightElevationAngle*DEG_TO_RAD;var adjustedSunDir=sunDir;if(sunDir.y(sunDir.x,.0,sunDir.z));adjustedSunDir=vec3(horizontalDir.x*cosEl,sinEl,horizontalDir.z*cosEl);}let intersect=getPlanetIntersection(p,adjustedSunDir,r);if(r>.0&&intersect.x>EPSILON){return vec3(.0);}return getSunTransmittanceManual(p,adjustedSunDir,params);}fn integrateOpticalDepth(origin:vec3,dir:vec3,tMin:f32,tMax:f32,steps:u32,params:SkyAtmosphere)->vec3{if(tMax<=tMin){return vec3(.0);}let stepSize=(tMax-tMin)/f32(steps);var optExt=vec3(.0);for(var i=0u;if32{return 3.0/(16.0*PI)*(1.0+cosTheta*cosTheta);}fn phaseMie(cosTheta:f32,g:f32)->f32{let g2=g*g;return 1.0/(4.0*PI)*((1.0-g2)/pow(max(EPSILON,1.0+g2-2.0*g*cosTheta),1.5));}fn phaseMieStable(cosTheta:f32,g:f32)->f32{return phaseMie(cosTheta,min(g,0.80));}fn getSquashedViewSunCos(viewDir:vec3,sunDir:vec3)->f32{let sunElevationParam=saturate(sunDir.y);let squashFactor=mix(0.85,1.0,sunElevationParam);let verticalDist=viewDir.y-sunDir.y;let correctionGuard=saturate(dot(viewDir,sunDir)*10.0)*(1.0-sunElevationParam*sunElevationParam);let squashCorrection=(1.0/(squashFactor*squashFactor)-1.0)*(verticalDist*verticalDist)*correctionGuard;return dot(viewDir,sunDir)-squashCorrection;}fn getSunDiskRadianceUnit(viewSunCos:f32,sunSize:f32,sunLimbDarkening:f32,skyTrans:vec3,edgeSoftness:f32,params:SkyAtmosphere)->vec3{let sunRad=(sunSize*0.5)*DEG_TO_RAD;let cosSunRad=cos(sunRad);let solidAngle=PI2*(1.0-cosSunRad);let radianceScale=SUN_RADIANCE_BOOST/max(6.7e-5,solidAngle);let dist=(1.0-viewSunCos)/max(1e-7,1.0-cosSunRad);let sunMask=1.0-smoothstep(1.0-edgeSoftness,1.0,dist);if(sunMask<=.0){return vec3(.0);}let limbDarkening=pow(max(1e-7,1.0-saturate(dist)),sunLimbDarkening);let energyNormalization=sunLimbDarkening+1.0;return(radianceScale*limbDarkening*energyNormalization*sunMask)*skyTrans;}fn getSunDiskRadianceIBL(viewSunCos:f32,sunLimbDarkening:f32,skyTrans:vec3,params:SkyAtmosphere)->vec3{let sunRad=(params.sunSize*0.5)*DEG_TO_RAD;let iblAlpha=max(sunRad*2.0,0.175);let cosAlpha=cos(iblAlpha);let radScale=1.0/(PI2*(1.0-cosAlpha));let diff=saturate(1.0-viewSunCos);let sigma_sq=1.0-cosAlpha;let falloff=exp(-diff/max(1e-7,sigma_sq));if(falloff<.001){return vec3(.0);}return(radScale*falloff)*skyTrans;}fn getMieGlowAmountUnit(viewSunCos:f32,viewHeight:f32,params:SkyAtmosphere,transmittanceLUT:texture_2d,skyAtmosphereSampler:sampler,transToEdge:vec3,overrideHalo:f32)->vec3{let actualAnisotropy=params.mieAnisotropy;let halo=select(actualAnisotropy,overrideHalo,overrideHalo>.0);let sharpG=min(max(halo,0.88),0.94);let stableG=min(actualAnisotropy,0.80);let sharpPhase=phaseMie(viewSunCos,sharpG);let stablePhase=phaseMie(viewSunCos,stableG);let diffPhase=max(.0,sharpPhase-stablePhase);let sunDirY=params.sunDirection.y;let sunCosTheta=clamp(sunDirY,-1.0,1.0);let sunTransForGlow=getTransmittance(transmittanceLUT,skyAtmosphereSampler,viewHeight,sunCosTheta,params.atmosphereHeight);return sunTransForGlow*(params.mieScattering/max(vec3(.0001),params.mieScattering+params.mieAbsorption))*(diffPhase)*(1.0-transToEdge)*MIE_GLOW_SUPPRESS*params.skyLuminanceFactor;}fn integrateScatSegment(origin:vec3,dir:vec3,tMin:f32,tMax:f32,steps:u32,params:SkyAtmosphere,transmittanceLUT:texture_2d,skyAtmosphereSampler:sampler,multiScatLUT:texture_2d,useLUT:bool,radiance:ptr>,transmittance:ptr>){if(tMax<=tMin){return;}let r=params.groundRadius;let stepSize=(tMax-tMin)/f32(steps);let sunDir=params.sunDirection;let viewSunCos=dot(dir,sunDir);let phaseR=phaseRayleigh(viewSunCos);let phaseM=select(phaseMie(viewSunCos,params.mieAnisotropy),phaseMieStable(viewSunCos,params.mieAnisotropy),useLUT);for(var i=0u;i.0&&viewHeight<.0){continue;}let up=p/pLen;let cosSun=dot(up,sunDir);var sunTrans:vec3;if(useLUT){sunTrans=getTransmittance(transmittanceLUT,skyAtmosphereSampler,viewHeight,cosSun,params.atmosphereHeight);}else{sunTrans=getSunTransmittanceManual(p,sunDir,params);}let shadowMask=select(1.0,.0,r>.0&&getRaySphereIntersection(p,sunDir,r)>.0);let d=getAtmosphereDensities(viewHeight,params);let scatR_phys=params.rayleighScattering*d.rhoR;let scatM_phys=params.mieScattering*d.rhoM;let mieAbs_phys=params.mieAbsorption*d.rhoM;let ozoneAbs_phys=params.absorptionCoefficient*d.rhoO;let scatR_luminous=scatR_phys*params.skyLuminanceFactor;let scatM_luminous=scatM_phys*params.skyLuminanceFactor;let stepScat=(scatR_luminous*phaseR+scatM_luminous*phaseM)*sunTrans*shadowMask;let scatTotal_luminous=scatR_luminous+scatM_luminous;let msUV=vec2(clamp(cosSun*0.5+0.5,.001,0.999),clamp(1.0-viewHeight/params.atmosphereHeight,.001,0.999));let msScat=textureSampleLevel(multiScatLUT,skyAtmosphereSampler,msUV,.0).rgb*scatTotal_luminous*shadowMask*params.multiScatteringFactor;*radiance+=*transmittance*(stepScat+msScat)*stepSize;let extinction_phys=scatR_phys+scatM_phys+mieAbs_phys+ozoneAbs_phys;*transmittance*=exp(-extinction_phys*stepSize);}}fn getCubeMapDirection(uv:vec2,face:u32)->vec3{let tex=uv*2.0-1.0;var dir:vec3;switch(face){case 0u:{dir=vec3(1.0,-tex.y,-tex.x);}case 1u:{dir=vec3(-1.0,-tex.y,tex.x);}case 2u:{dir=vec3(tex.x,1.0,tex.y);}case 3u:{dir=vec3(tex.x,-1.0,-tex.y);}case 4u:{dir=vec3(tex.x,-tex.y,1.0);}case 5u:{dir=vec3(-tex.x,-tex.y,-1.0);}default:{dir=vec3(.0);}}return dir;}fn evaluateGroundRadiance(cosSun:f32,sunTrans:vec3,msEnergy:vec3,groundAlbedo:vec3)->vec3{let sunShadow=smoothstep(-.01,.01,cosSun);var groundRadiance=vec3(.0);if(sunShadow>.0){groundRadiance=(sunTrans*max(.0,cosSun)*INV_PI+msEnergy)*groundAlbedo*sunShadow;}else{groundRadiance=msEnergy*groundAlbedo;}return groundRadiance;}fn evaluateIBLRadiance(viewDir:vec3,params:SkyAtmosphere,transmittanceLUT:texture_2d,multiScatLUT:texture_2d,skyViewLUT:texture_2d,skyAtmosphereSampler:sampler)->vec3{let r=params.groundRadius;let viewHeight=max(.0,params.cameraHeight);let atmosphereHeight=params.atmosphereHeight;let sunDir=normalize(params.sunDirection);let skyUV=getSkyViewUV(viewDir,viewHeight,r,atmosphereHeight);let skySample=textureSampleLevel(skyViewLUT,skyAtmosphereSampler,skyUV,.0);var radiance=skySample.rgb;let viewSunCos=getSquashedViewSunCos(viewDir,sunDir);let camPos=vec3(.0,r+viewHeight,.0);let tEarth=getRaySphereIntersection(camPos,viewDir,r);let isGround=r>.0&&tEarth>.0&&viewDir.y<-.0001;let transToEdge=select(getTransmittance(transmittanceLUT,skyAtmosphereSampler,viewHeight,viewDir.y,atmosphereHeight),vec3(skySample.a),isGround);let sunShadow=getPlanetShadowMask(camPos,sunDir,r,params);if(!isGround&&sunShadow>.0){let mieGlow=getMieGlowAmountUnit(viewSunCos,viewHeight,params,transmittanceLUT,skyAtmosphereSampler,transToEdge,.0);radiance+=mieGlow*sunShadow;}return radiance;}fn getSpecularSunLobe(viewSun:f32,lobeHalfAngle:f32)->f32{let cosHalf=cos(lobeHalfAngle);let sunLobePower=clamp(log(0.5)/log(max(1e-4,cosHalf)),2.0,128.0);let sunLobeNorm=(sunLobePower+1.0)*(0.5*INV_PI);return sunLobeNorm*pow(max(.0,viewSun),sunLobePower);}fn evaluateIBLRadianceCompensated(viewDir:vec3,params:SkyAtmosphere,transmittanceLUT:texture_2d,multiScatLUT:texture_2d,skyViewLUT:texture_2d,skyAtmosphereSampler:sampler)->vec3{let r=params.groundRadius;let viewHeight=max(.0,params.cameraHeight);let atmosphereHeight=params.atmosphereHeight;let sunDir=normalize(params.sunDirection);let skyUV=getSkyViewUV(viewDir,viewHeight,r,atmosphereHeight);let skySample=textureSampleLevel(skyViewLUT,skyAtmosphereSampler,skyUV,.0);var radiance=skySample.rgb;let viewSunCos=getSquashedViewSunCos(viewDir,sunDir);let camPos=vec3(.0,r+viewHeight,.0);let tEarth=getRaySphereIntersection(camPos,viewDir,r);let isGround=r>.0&&tEarth>.0&&viewDir.y<-.0001;let transToEdge=select(getTransmittance(transmittanceLUT,skyAtmosphereSampler,viewHeight,viewDir.y,atmosphereHeight),vec3(skySample.a),isGround);let sunShadow=getPlanetShadowMask(camPos,sunDir,r,params);if(!isGround&&sunShadow>.0){let mieGlow=getMieGlowAmountUnit(viewSunCos,viewHeight,params,transmittanceLUT,skyAtmosphereSampler,transToEdge,.0);radiance+=mieGlow*sunShadow;radiance+=getSunDiskRadianceIBL(viewSunCos,params.sunLimbDarkening,transToEdge,params)*sunShadow;}return radiance;}fn getFrustumRayDirection(uv:vec2,invP:mat4x4,invV:mat4x4)->vec3{let ndc=vec2(uv.x*2.0-1.0,(1.0-uv.y)*2.0-1.0);let viewSpaceDir=normalize(vec3(ndc.x*invP[0][0],ndc.y*invP[1][1],-1.0));let worldRotation=mat3x3(invV[0].xyz,invV[1].xyz,invV[2].xyz);return normalize(worldRotation*viewSpaceDir);}fn cloud_hash(p:vec2)->f32{return fract(sin(dot(p,vec2(127.1,311.7)))*43758.5453123);}fn cloud_noise(p:vec2)->f32{let i=floor(p);let f=fract(p);let u=f*f*(3.0-2.0*f);return mix(mix(cloud_hash(i+vec2(.0,.0)),cloud_hash(i+vec2(1.0,.0)),u.x),mix(cloud_hash(i+vec2(.0,1.0)),cloud_hash(i+vec2(1.0,1.0)),u.x),u.y);}fn cloud_fbm(p:vec2)->f32{var v=.0;var a=0.5;var shift=vec2(100.0);var p_mut=p;for(var i=0;i<5;i=i+1){v+=a*cloud_noise(p_mut);p_mut=p_mut*2.0+shift;a*=0.5;}return v;}fn getCloudWarpedUV(hitP:vec3,params:SkyAtmosphere)->vec2{let baseUV=hitP.xz*.05+vec2(params.cloudTime*.02);let warp=vec2(cloud_noise(baseUV*1.2+vec2(params.cloudTime*.01)),cloud_noise(baseUV*1.2+vec2(5.7,1.3)+vec2(params.cloudTime*.012)));return baseUV+warp*0.2;}fn getCloudDensity(hitP:vec3,params:SkyAtmosphere)->f32{let warpedUV=getCloudWarpedUV(hitP,params);let density=cloud_fbm(warpedUV);let coverage=params.cloudCoverage;let softness=(1.0-params.cloudDensity)*0.5+.01;return smoothstep(1.0-coverage,1.0-coverage+softness,density);}fn getCloudNormal(hitP:vec3,params:SkyAtmosphere)->vec3{let warpedUV=getCloudWarpedUV(hitP,params);let density=cloud_fbm(warpedUV);let eps=0.2;let dIdx=(cloud_fbm(warpedUV+vec2(eps,.0))-density)/eps;let dIdy=(cloud_fbm(warpedUV+vec2(.0,eps))-density)/eps;return normalize(vec3(-dIdx,2.0,-dIdy));}",i.transmittanceLUT=it}(Ze||(Ze={})),function(i){var g,x;(g=i.mesh||(i.mesh={})).entryPointPickingVertex="@vertex fn entryPointPickingVertex(inputData:InputData)->VertexOutput{var output:VertexOutput;let input_position=inputData.position;let u_modelMatrix=vertexUniforms.matrixList.modelMatrix;let u_projectionMatrix=systemUniforms.projection.projectionMatrix;let u_projectionViewMatrix=systemUniforms.projection.projectionViewMatrix;let u_camera=systemUniforms.camera;let u_viewMatrix=u_camera.viewMatrix;var position:vec4=u_modelMatrix*vec4(input_position,1.0);output.position=u_projectionViewMatrix*position;output.pickingId=unpack4x8unorm(vertexUniforms.pickingId);return output;}",g.entryPointPickingFragment="@fragment fn entryPointPickingFragment(inputData:InputData)->@location(0)vec4{var finalColor:vec4=inputData.pickingId;return finalColor;}",g.entryPointShadowVertex="#redgpu_include shadow.getShadowClipPosition #redgpu_include systemStruct.OutputShadowData;@vertex fn entryPointShadowVertex(inputData:InputData)->OutputShadowData{var output:OutputShadowData;let u_directionalLightProjectionViewMatrix=systemUniforms.directionalLightProjectionViewMatrix;let u_camera=systemUniforms.camera;let u_viewMatrix=u_camera.viewMatrix;let u_cameraPosition=u_camera.cameraPosition;let u_modelMatrix=vertexUniforms.matrixList.modelMatrix;let input_position=inputData.position;let input_vertexNormal=inputData.vertexNormal;let input_uv=inputData.uv;var position:vec4;position=u_modelMatrix*vec4(input_position,1.0);#redgpu_if useDisplacementTexture{let distance=distance(position.xyz,u_cameraPosition);let maxMip=f32(textureNumLevels(displacementTexture))-1.0;let mipLevel=clamp((distance/maxDistance)*maxMip,.0,maxMip);let displacedPosition=getDisplacementPosition(input_position,input_vertexNormal,displacementTexture,displacementTextureSampler,vertexUniforms.displacementScale,input_uv,mipLevel);position=u_modelMatrix*vec4(displacedPosition,1.0);}#redgpu_endIf output.position=getShadowClipPosition(position.xyz,u_directionalLightProjectionViewMatrix);return output;}",(i.billboard||(i.billboard={})).entryPointPickingVertex="@vertex fn entryPointPickingVertex(inputData:InputData)->VertexOutput{var output:VertexOutput;let u_resolution=systemUniforms.resolution;#redgpu_if disableJitter let u_projectionMatrix=systemUniforms.projection.noneJitterProjectionMatrix;#redgpu_else let u_projectionMatrix=systemUniforms.projection.projectionMatrix;#redgpu_endIf let u_viewMatrix=systemUniforms.camera.viewMatrix;let u_modelMatrix=vertexUniforms.matrixList.modelMatrix;let u_useBillboard=vertexUniforms.useBillboard;let u_usePixelSize=vertexUniforms.usePixelSize;let u_pixelSize=vertexUniforms.pixelSize;let u_renderRatioX=vertexUniforms._renderRatioX;let u_renderRatioY=vertexUniforms._renderRatioY;var ratioScaleMatrix:mat4x4=mat4x4(u_renderRatioX,0,0,0,0,u_renderRatioY,0,0,0,0,1,0,0,0,0,1);if(u_useBillboard==1){let billboardMatrix=getBillboardMatrix(u_viewMatrix,u_modelMatrix,1u);if(u_usePixelSize==1){let viewPositionCenter=billboardMatrix*vec4(.0,.0,.0,1.0);let clipCenter=u_projectionMatrix*viewPositionCenter;let scaleX=(u_pixelSize/u_resolution.x)*2.0*u_renderRatioX;let scaleY=(u_pixelSize/u_resolution.y)*2.0*u_renderRatioY;output.position=vec4(clipCenter.xy+inputData.position.xy*vec2(scaleX,scaleY)*clipCenter.w,clipCenter.zw);}else{output.position=u_projectionMatrix*billboardMatrix*ratioScaleMatrix*vec4(inputData.position,1.0);}}else{output.position=u_projectionMatrix*u_viewMatrix*u_modelMatrix*ratioScaleMatrix*vec4(inputData.position,1.0);}output.pickingId=unpack4x8unorm(vertexUniforms.pickingId);return output;}",(x=i.empty||(i.empty={})).entryPointPickingVertex="@vertex fn entryPointPickingVertex(inputData:InputData)->VertexOutput{var output:VertexOutput;return output;}",x.entryPointShadowVertex="#redgpu_include systemStruct.OutputShadowData;@vertex fn entryPointShadowVertex(inputData:InputData)->OutputShadowData{var output:OutputShadowData;return output;}"}(Je||(Je={})),function(i){i.OutputFragment="struct OutputFragment{@location(0)color:vec4,@location(1)gBufferNormal:vec4,@location(2)gBufferMotionVector:vec4,}",i.OutputShadowData="struct OutputShadowData{@builtin(position)position:vec4,};",i.Camera="struct Camera{viewMatrix:mat4x4,inverseViewMatrix:mat4x4,cameraPosition:vec3,nearClipping:f32,farClipping:f32,fieldOfView:f32,ev100:f32,_pad_exposure:f32,aperture:f32,shutterSpeed:f32,iso:f32,_pad:f32};",i.Projection="struct Projection{projectionMatrix:mat4x4,projectionViewMatrix:mat4x4,noneJitterProjectionMatrix:mat4x4,noneJitterProjectionViewMatrix:mat4x4,inverseProjectionMatrix:mat4x4,inverseProjectionViewMatrix:mat4x4,prevNoneJitterProjectionViewMatrix:mat4x4};",i.Time="struct Time{time:f32,deltaTime:f32,frameIndex:u32,sinTime:f32};",i.DirectionalLight="struct DirectionalLight{direction:vec3,color:vec3,intensity:f32,};",i.AmbientLight="struct AmbientLight{color:vec3,intensity:f32};",i.Shadow="struct Shadow{directionalShadowDepthTextureSize:u32,directionalShadowBias:f32,padding:vec2};",i.SkyAtmosphere="struct SkyAtmosphere{rayleighScattering:vec3,rayleighExponentialDistribution:f32,mieScattering:vec3,mieAnisotropy:f32,mieAbsorption:vec3,mieExponentialDistribution:f32,absorptionCoefficient:vec3,absorptionTipAltitude:f32,groundAlbedo:vec3,absorptionTentWidth:f32,skyLuminanceFactor:vec3,multiScatteringFactor:f32,sunDirection:vec3,transmittanceMinLightElevationAngle:f32,groundRadius:f32,atmosphereHeight:f32,aerialPerspectiveDistanceScale:f32,aerialPerspectiveStartDepth:f32,sunIntensity:f32,sunSize:f32,sunLimbDarkening:f32,cameraHeight:f32,cloudTime:f32,cloudTimeMultiplier:f32,cloudCoverage:f32,cloudDensity:f32,cloudHeight:f32};",i.meshVertexBasicUniform="struct MatrixList{localMatrix:mat4x4,modelMatrix:mat4x4,prevModelMatrix:mat4x4,normalModelMatrix:mat4x4,}struct VertexUniforms{matrixList:MatrixList,pickingId:u32,receiveShadow:f32,combinedOpacity:f32,useDisplacementTexture:u32,displacementScale:f32,disableJitter:u32,uvTransform:vec4,};"}(Qe||(Qe={})),function(i){i.getDisplacementPosition="fn getDisplacementPosition(input_position:vec3,input_vertexNormal:vec3,displacementTexture:texture_2d,displacementTextureSampler:sampler,displacementScale:f32,input_uv:vec2,mipLevel:f32)->vec3{let textureDimensions=vec2(textureDimensions(displacementTexture,0));let invTexSize=1.0/textureDimensions;let uv=input_uv*textureDimensions;let iuv=floor(uv-0.5);let fuv=fract(uv-0.5);let w0=(1.0-fuv)*(1.0-fuv)*(1.0-fuv)/6.0;let w1=(4.0-6.0*fuv*fuv+3.0*fuv*fuv*fuv)/6.0;let w2=(1.0+3.0*fuv+3.0*fuv*fuv-3.0*fuv*fuv*fuv)/6.0;let w3=fuv*fuv*fuv/6.0;let g0=w0+w1;let g1=w2+w3;let h0=(w1/g0)-1.0+iuv;let h1=(w3/g1)+1.0+iuv;let res0=textureSampleLevel(displacementTexture,displacementTextureSampler,(vec2(h0.x,h0.y)+0.5)*invTexSize,mipLevel).r*g0.x*g0.y;let res1=textureSampleLevel(displacementTexture,displacementTextureSampler,(vec2(h1.x,h0.y)+0.5)*invTexSize,mipLevel).r*g1.x*g0.y;let res2=textureSampleLevel(displacementTexture,displacementTextureSampler,(vec2(h0.x,h1.y)+0.5)*invTexSize,mipLevel).r*g0.x*g1.y;let res3=textureSampleLevel(displacementTexture,displacementTextureSampler,(vec2(h1.x,h1.y)+0.5)*invTexSize,mipLevel).r*g1.x*g1.y;let h_bicubic=res0+res1+res2+res3;let scaledDisplacement=(h_bicubic-0.5)*displacementScale;let displacedPosition=input_position+normalize(input_vertexNormal)*scaledDisplacement;return displacedPosition;}",i.getDisplacementNormal="fn sampleBicubic(uv:vec2,tex:texture_2d,smp:sampler,dims:vec2,invSize:vec2,mip:f32)->f32{let res_uv=uv*dims;let i=floor(res_uv-0.5);let f=fract(res_uv-0.5);let w0=(1.0-f)*(1.0-f)*(1.0-f)/6.0;let w1=(4.0-6.0*f*f+3.0*f*f*f)/6.0;let w2=(1.0+3.0*f+3.0*f*f-3.0*f*f*f)/6.0;let w3=f*f*f/6.0;let g0=w0+w1;let g1=w2+w3;let h0=(w1/g0)-1.0+i;let h1=(w3/g1)+1.0+i;let r0=textureSampleLevel(tex,smp,(vec2(h0.x,h0.y)+0.5)*invSize,mip).r*g0.x*g0.y;let r1=textureSampleLevel(tex,smp,(vec2(h1.x,h0.y)+0.5)*invSize,mip).r*g1.x*g0.y;let r2=textureSampleLevel(tex,smp,(vec2(h0.x,h1.y)+0.5)*invSize,mip).r*g0.x*g1.y;let r3=textureSampleLevel(tex,smp,(vec2(h1.x,h1.y)+0.5)*invSize,mip).r*g1.x*g1.y;return r0+r1+r2+r3;}fn getDisplacementNormal(displacementTexture:texture_2d,displacementTextureSampler:sampler,displacementScale:f32,input_uv:vec2,mipLevel:f32)->vec3{let textureDimensions=vec2(textureDimensions(displacementTexture,0));let invTexSize=1.0/textureDimensions;let step=invTexSize*exp2(mipLevel);let h_u0=sampleBicubic(input_uv+vec2(-step.x,.0),displacementTexture,displacementTextureSampler,textureDimensions,invTexSize,mipLevel);let h_u1=sampleBicubic(input_uv+vec2(step.x,.0),displacementTexture,displacementTextureSampler,textureDimensions,invTexSize,mipLevel);let h_v0=sampleBicubic(input_uv+vec2(.0,-step.y),displacementTexture,displacementTextureSampler,textureDimensions,invTexSize,mipLevel);let h_v1=sampleBicubic(input_uv+vec2(.0,step.y),displacementTexture,displacementTextureSampler,textureDimensions,invTexSize,mipLevel);let ddu=(h_u1-h_u0)*displacementScale/(step.x*2.0);let ddv=(h_v1-h_v0)*displacementScale/(step.y*2.0);return normalize(vec3(-ddu,-ddv,1.0));}"}(et||(et={})),function(i){i.SYSTEM_UNIFORM="#redgpu_include systemStruct.DirectionalLight #redgpu_include systemStruct.AmbientLight #redgpu_include systemStruct.Camera #redgpu_include systemStruct.Projection #redgpu_include systemStruct.Time #redgpu_include systemStruct.Shadow #redgpu_include systemStruct.SkyAtmosphere struct SystemUniform{projection:Projection,time:Time,resolution:vec2,camera:Camera,usePrefilterTexture:u32,isView3D:u32,useSkyAtmosphere:u32,preExposure:f32,iblIntensity:f32,skyAtmosphere:SkyAtmosphere,shadow:Shadow,directionalLightCount:u32,directionalLightProjectionViewMatrix:mat4x4,directionalLightProjectionMatrix:mat4x4,directionalLightViewMatrix:mat4x4,directionalLights:array,ambientLight:AmbientLight,};@group(0)@binding(0)varsystemUniforms:SystemUniform;@group(0)@binding(1)var directionalShadowMapSampler:sampler_comparison;@group(0)@binding(2)var directionalShadowMap:texture_depth_2d;@group(0)@binding(3)var prefilterTextureSampler:sampler;@group(0)@binding(7)var renderPath1ResultTextureSampler:sampler;@group(0)@binding(8)var renderPath1ResultTexture:texture_2d;@group(0)@binding(9)var packedTextureSampler:sampler;@group(0)@binding(10)var ibl_prefilterTexture:texture_cube;@group(0)@binding(11)var ibl_irradianceTexture:texture_cube;@group(0)@binding(12)var ibl_brdfLUTTexture:texture_2d;@group(0)@binding(13)var atmosphereSampler:sampler;@group(0)@binding(14)var transmittanceTexture:texture_2d;@group(0)@binding(15)var atmosphereIrradianceLUT:texture_cube;@group(0)@binding(16)var skyAtmosphere_prefilteredTexture:texture_cube;#redgpu_include depth.getLinearizeDepth const clusterLight_indicesLength:u32=u32(REDGPU_DEFINE_MAX_LIGHTS_PER_CLUSTERu*REDGPU_DEFINE_TOTAL_TILESu);const clusterLight_tileCount=vec3(REDGPU_DEFINE_TILE_COUNT_Xu,REDGPU_DEFINE_TILE_COUNT_Yu,REDGPU_DEFINE_TILE_COUNT_Zu);struct ClusterLightCell{offset:u32,count:u32};struct ClusterLightGrid{offset:atomic,cells:array,indices:array};struct ClusterLight{position:vec3,radius:f32,color:vec3,intensity:f32,isSpotLight:f32,directionX:f32,directionY:f32,directionZ:f32,outerCutoff:f32,innerCutoff:f32,};struct ClusterLightList{count:vec4,lights:array};@group(0)@binding(5)varclusterLightList:ClusterLightList;@group(0)@binding(6)varclusterLightGrid:ClusterLightGrid;fn getClusterLightClusterIndex(fragCoord:vec4)->u32{let tile=getClusterLightTile(fragCoord);return tile.x+tile.y*clusterLight_tileCount.x+tile.z*clusterLight_tileCount.x*clusterLight_tileCount.y;}fn getClusterLightTile(fragCoord:vec4)->vec3{let near=systemUniforms.camera.nearClipping;let far=systemUniforms.camera.farClipping;let sliceScale=f32(clusterLight_tileCount.z)/log2(far/near);let sliceBias=-(f32(clusterLight_tileCount.z)*log2(near)/log2(far/near));let zTile=u32(max(log2(getLinearizeDepth(fragCoord.z,near,far))*sliceScale+sliceBias,.0));return vec3(u32(fragCoord.x/(systemUniforms.resolution.x/f32(clusterLight_tileCount.x))),u32(fragCoord.y/(systemUniforms.resolution.y/f32(clusterLight_tileCount.y))),zTile);}",i.POST_EFFECT_SYSTEM_UNIFORM="#redgpu_include systemStruct.Camera #redgpu_include systemStruct.Projection #redgpu_include systemStruct.Time #redgpu_include systemStruct.SkyAtmosphere struct SystemUniform{projection:Projection,time:Time,camera:Camera,useSkyAtmosphere:u32,preExposure:f32,devicePixelRatio:f32,skyAtmosphere:SkyAtmosphere,};@group(2)@binding(4)varsystemUniforms:SystemUniform;",i.math=be,i.shadow=je,i.color=Ke,i.depth=Xe,i.lighting=Ye,i.skyAtmosphere=Ze,i.entryPoint=Je,i.systemStruct=Qe,i.displacement=et}(tt||(tt={}));var ft=tt;class ShaderVariantGenerator{#Ce=new Map;#Be;#De;#Ee=[];#Ie=[];#Ae=new Map;#Le=new Map;constructor(i,g){this.#Be=i,this.#De=g}setBaseInfo(i,g){this.#Ee=i,this.#Ie=g}addConditionalInfo(i,g,x){this.#Ae.set(i,g),this.#Le.set(i,x)}getVariantTextures(i){const g="none"===i?[]:i.split("+"),x=[...this.#Ee];return g.forEach(i=>{const g=this.#Ae.get(i);g&&g.forEach(i=>{x.find(g=>g.name===i.name)||x.push(i)})}),x}getVariantSamplers(i){const g="none"===i?[]:i.split("+"),x=[...this.#Ie];return g.forEach(i=>{const g=this.#Le.get(i);g&&g.forEach(i=>{x.find(g=>g.name===i.name)||x.push(i)})}),x}getUnionTextures(){const i=[...this.#Ee];return this.#Ae.forEach(g=>{g.forEach(g=>{i.find(i=>i.name===g.name)||i.push(g)})}),i}getUnionSamplers(){const i=[...this.#Ie];return this.#Le.forEach(g=>{g.forEach(g=>{i.find(i=>i.name===g.name)||i.push(g)})}),i}getVariant(i){if(this.#Ce.has(i))return this.#Ce.get(i);const g="none"===i?[]:i.split("+"),x=this.#Ue(g);return this.#Ce.set(i,x),x}getCachedVariants(){return Array.from(this.#Ce.keys())}#Ue(i){let g=this.#Be;for(let x=this.#De.length-1;x>=0;x--){const v=this.#De[x];g=i.includes(v.uniformName)?g.replace(v.fullMatch,v.ifBlock):g.replace(v.fullMatch,v.elseBlock||"")}return g}}const pt=/#redgpu_include\s+([\w.]+)/g,xt=/REDGPU_DEFINE_(?:TILE_COUNT_[XYZ]|TOTAL_TILES|WORKGROUP_SIZE_[XYZ]|MAX_LIGHTS_PER_CLUSTER)/g,vt={REDGPU_DEFINE_TILE_COUNT_X:W.TILE_COUNT_X.toString(),REDGPU_DEFINE_TILE_COUNT_Y:W.TILE_COUNT_Y.toString(),REDGPU_DEFINE_TILE_COUNT_Z:W.TILE_COUNT_Z.toString(),REDGPU_DEFINE_TOTAL_TILES:W.getTotalTileSize().toString(),REDGPU_DEFINE_WORKGROUP_SIZE_X:W.WORKGROUP_SIZE_X.toString(),REDGPU_DEFINE_WORKGROUP_SIZE_Y:W.WORKGROUP_SIZE_Y.toString(),REDGPU_DEFINE_WORKGROUP_SIZE_Z:W.WORKGROUP_SIZE_Z.toString(),REDGPU_DEFINE_MAX_LIGHTS_PER_CLUSTER:W.MAX_LIGHTS_PER_CLUSTER.toString()},yt=new Map,bt=new Map,preprocessWGSL=(i,g,x)=>{if(!i)throw new Error(`[preprocessWGSL] sourceName is required. (provided: ${i})`);const v=(i=>{let g=0;for(let x=0;x{let v=i,_=0;const y=new Set,resolvePath=(i,v,_)=>{if(y.has(i))return"";if(x&&i in x)return y.add(i),x[i];const b=i.split(".");let S=ft;for(const x of b){if(!S||"object"!=typeof S||!(x in S)){const x=_.substring(0,v).split("\n").length;throw new Error(`[preprocessWGSL] Invalid include path in [${g}] at line ${x}: #redgpu_include ${i}. Path not found in injected library or ShaderLibrary.`)}S=S[x]}if("string"==typeof S)return y.add(i),S;{const x=_.substring(0,v).split("\n").length;throw new Error(`[preprocessWGSL] Invalid include target in [${g}] at line ${x}: #redgpu_include ${i}. Target is not a WGSL string.`)}};for(;_<10;){const i=v;if(v=v.replace(pt,(i,g,x)=>{const _=resolvePath(g,x,v);return null!==_?_:i}),v===i)break;_++}return v})(g,i,x),w=(i=>i.replace(xt,i=>vt[i]||i))(S),L=(i=>{const g=[],x=/#redgpu_if\s+(\w+)\b|#redgpu_else|#redgpu_endIf/g,v=[];let _,y=0;for(;null!==(_=x.exec(i));){const x=_[0];if(x.startsWith("#redgpu_if"))v.push({uniformName:_[1],startIndex:_.index,headerLength:x.length});else if("#redgpu_else"===x){const i=v[v.length-1];if(!i)throw new Error(`[preprocessWGSL] Mismatched #redgpu_else at index ${_.index}`);void 0===i.elseIndex&&(i.elseIndex=_.index)}else if("#redgpu_endIf"===x){const b=v.pop();if(!b)throw new Error(`[preprocessWGSL] Mismatched #redgpu_endIf at index ${_.index}`);{const v=i.substring(b.startIndex,_.index+x.length);let S,w;void 0!==b.elseIndex?(S=i.substring(b.startIndex+b.headerLength,b.elseIndex),w=i.substring(b.elseIndex+12,_.index)):S=i.substring(b.startIndex+b.headerLength,_.index),g.push({uniformName:b.uniformName,ifBlock:S.trim(),elseBlock:w?.trim(),fullMatch:v,blockIndex:y++})}}}if(v.length>0)throw new Error(`[preprocessWGSL] Unclosed #redgpu_if for: ${v.map(i=>i.uniformName).join(", ")}`);return g})(w);(i=>{if(!i.length)return;const g=new Map;i.forEach(i=>{g.set(i.uniformName,(g.get(i.uniformName)||0)+1)}),Array.from(g.entries()).filter(([i,g])=>g>1).length})(L);const k=[...new Set(L.map(i=>i.uniformName))],H=new ShaderVariantGenerator(w,L),z={cacheKey:y,defaultSource:H.getVariant("none"),shaderSourceVariant:H,conditionalBlocks:k,conditionalBlockInfos:L};return Math.pow(2,k.length),yt.set(y,z),z};class ResourceStatusInfo{table=new Map;videoMemory=0;constructor(){}}var St;Object.freeze(ResourceStatusInfo),function(i){i.GPUShaderModule="GPUShaderModule",i.GPUBindGroupLayout="GPUBindGroupLayout",i.GPUPipelineLayout="GPUPipelineLayout",i.GPUBuffer="GPUBuffer"}(St||(St={}));class ResourceManager extends RedGPUObject{static PRESET_GPUBindGroupLayout_System="PRESET_GPUBindGroupLayout_System";static PRESET_VERTEX_GPUBindGroupLayout_Instancing="PRESET_VERTEX_GPUBindGroupLayout_Instancing";static PRESET_VERTEX_GPUBindGroupLayout="PRESET_VERTEX_GPUBindGroupLayout";static PRESET_VERTEX_GPUBindGroupLayout_SKIN="PRESET_VERTEX_GPUBindGroupLayout_SKIN";#ke=new ImmutableKeyMap([[St.GPUShaderModule,new Map],[St.GPUBindGroupLayout,new Map],[St.GPUPipelineLayout,new Map],[St.GPUBuffer,new MemoryTrackingMap]]);#Ge=new ResourceStatusInfo;#Oe=new ResourceStatusInfo;#Ve=new ResourceStatusInfo;#Ne=new ResourceStatusInfo;#Fe=new ResourceStatusInfo;#He=new ResourceStatusInfo;#ze=new ResourceStatusInfo;#$e={};#je;#Ke;#Xe;#qe;#Ye;#We;#Ze;#Je;#Qe;#et;#tt;#rt;#it=new WeakMap;#nt=new WeakMap;constructor(i){super(i),this.#Ye=new MipmapGenerator(i),this.#We=new DownSampleCubeMapGenerator(i),this.#Ze=new BRDFGenerator(i),this.#Je=new IrradianceGenerator(i),this.#Qe=new PrefilterGenerator(i),this.#et=new EquirectangularToCubeGenerator(i),this.#at()}get basicSampler(){return this.#tt}get basicDisplacementSampler(){return this.#rt}get brdfGenerator(){return this.#Ze}get irradianceGenerator(){return this.#Je}get prefilterGenerator(){return this.#Qe}get equirectangularToCubeGenerator(){return this.#et}get mipmapGenerator(){return this.#Ye}get downSampleCubeMapGenerator(){return this.#We}get cachedBufferState(){return this.#$e}get emptyBitmapTextureView(){return this.#je}get emptyCubeTextureView(){return this.#Ke}get emptyTexture3DView(){return this.#Xe}get emptyDepthTextureView(){return this.#qe}get managedBitmapTextureState(){return this.#Ge}get managedCubeTextureState(){return this.#Oe}get managedHDRTextureState(){return this.#Ve}get managedUniformBufferState(){return this.#Ne}get managedVertexBufferState(){return this.#Fe}get managedIndexBufferState(){return this.#He}get managedStorageBufferState(){return this.#ze}get resources(){return this.#ke}registerManagementResource(i,x){const{cacheKey:v,targetResourceManagedState:_}=i,{table:y}=_;y.get(v)?g(`Resource with cacheKey ${v} is already registered.`):(y.set(v,x),_.videoMemory+=i.videoMemorySize)}unregisterManagementResource(i){const{cacheKey:g,targetResourceManagedState:x}=i,{table:v}=x;v.get(g)&&(x.videoMemory-=i.videoMemorySize,v.delete(g))}createManagedTexture(i){const g=this.gpuDevice.createTexture(i),x=g.destroy.bind(g);return g.destroy=()=>{this.#st(g,i),x()},g}getGPUResourceBitmapTextureView(i,g){const x=i instanceof GPUTexture?i:i?.gpuTexture;if(!x)return this.#je;let v=this.#it.get(x);v||(v=new Map,this.#it.set(x,v));const _=this.#ot(g);let y=v.get(_);if(!y){const i=g?{...g,label:g.label||x.label}:{label:x.label};y=x.createView(i),v.set(_,y)}return y}getGPUResourceCubeTextureView(i,g){const x=i instanceof GPUTexture?i:i?.gpuTexture;if(!x)return this.#Ke;let v=this.#nt.get(x);v||(v=new Map,this.#nt.set(x,v));const _=g||(i instanceof GPUTexture?CubeTexture.defaultViewDescriptor:i.viewDescriptor),y=this.#ot(_);let b=v.get(y);if(!b){const i={..._,label:x.label};b=x.createView(i),v.set(y,b)}return b}createGPUShaderModule(i,g){return this.#ut(i,g,g=>this.#lt(i,g),St.GPUShaderModule)}getGPUShaderModule(i){return this.#ct(i,St.GPUShaderModule)}deleteGPUShaderModule(i){this.#ht(i,St.GPUShaderModule)}createBindGroupLayout(i,g){return this.#ut(i,g,g=>(g.label||(g.label=i),this.redGPUContext.gpuDevice.createBindGroupLayout(g)),St.GPUBindGroupLayout)}getGPUBindGroupLayout(i){return this.#ct(i,St.GPUBindGroupLayout)}deleteGPUBindGroupLayout(i){this.#ht(i,St.GPUBindGroupLayout)}createGPUPipelineLayout(i,g){return this.#ut(i,g,g=>(g.label||(g.label=i),this.redGPUContext.gpuDevice.createPipelineLayout(g)),St.GPUPipelineLayout)}createGPUBuffer(i,g){return this.#ut(i,g,g=>(g.label||(g.label=i),this.gpuDevice.createBuffer(g)),St.GPUBuffer)}#st(i,g){const x="3d"===g.dimension?this.#nt:this.#it;x.get(i)?.clear(),x.delete(i)}#ot(i){return i?JSON.stringify(i):"default"}#at(){const{gpuDevice:i}=this.redGPUContext;{const g=i.createTexture({size:{width:1,height:1,depthOrArrayLayers:1},format:"rgba8unorm",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.STORAGE_BINDING,label:"EMPTY_BITMAP_TEXTURE"});this.#je=g.createView({label:g.label});const x=new Uint8Array([0,0,0,0]);i.queue.writeTexture({texture:g},x,{bytesPerRow:4,rowsPerImage:1},{width:1,height:1,depthOrArrayLayers:1});const v=i.createTexture({size:{width:1,height:1,depthOrArrayLayers:6},format:"rgba8unorm",usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST,label:"EMPTY_CUBE_TEXTURE"});this.#Ke=v.createView(CubeTexture.defaultViewDescriptor);const _=new Uint8Array([0,0,0,0]);for(let g=0;g<6;g++)i.queue.writeTexture({texture:v,origin:{x:0,y:0,z:g}},_,{bytesPerRow:4,rowsPerImage:1},{width:1,height:1,depthOrArrayLayers:1});const y=i.createTexture({size:{width:1,height:1,depthOrArrayLayers:1},dimension:"3d",format:"rgba8unorm",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST,label:"EMPTY_TEXTURE_3D"});this.#Xe=y.createView({label:y.label,dimension:"3d"});const b=i.createTexture({size:{width:1,height:1,depthOrArrayLayers:1},format:"depth24plus",usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING,label:"EMPTY_DEPTH_TEXTURE"});this.#qe=b.createView({label:b.label}),this.#tt=new Sampler(this.redGPUContext),this.#rt=new Sampler(this.redGPUContext,{magFilter:"linear",minFilter:"linear",mipmapFilter:"linear",addressModeU:"repeat",addressModeV:"repeat",addressModeW:"repeat"})}this.createBindGroupLayout(ResourceManager.PRESET_GPUBindGroupLayout_System,{entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT|GPUShaderStage.COMPUTE,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,sampler:{type:"comparison"}},{binding:2,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"depth"}},{binding:3,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}},{binding:5,visibility:GPUShaderStage.FRAGMENT|GPUShaderStage.COMPUTE,buffer:{type:"read-only-storage"}},{binding:6,visibility:GPUShaderStage.FRAGMENT|GPUShaderStage.COMPUTE,buffer:{type:"storage"}},{binding:7,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}},{binding:8,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:9,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}},{binding:10,visibility:GPUShaderStage.FRAGMENT,texture:{viewDimension:"cube"}},{binding:11,visibility:GPUShaderStage.FRAGMENT,texture:{viewDimension:"cube"}},{binding:12,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:13,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}},{binding:14,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:15,visibility:GPUShaderStage.FRAGMENT,texture:{viewDimension:"cube"}},{binding:16,visibility:GPUShaderStage.FRAGMENT,texture:{viewDimension:"cube"}}]}),this.createBindGroupLayout(ResourceManager.PRESET_VERTEX_GPUBindGroupLayout,{entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.VERTEX,sampler:{type:"filtering"}},{binding:2,visibility:GPUShaderStage.VERTEX,texture:{}}]}),this.createBindGroupLayout(ResourceManager.PRESET_VERTEX_GPUBindGroupLayout_SKIN,{entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.VERTEX,sampler:{type:"filtering"}},{binding:2,visibility:GPUShaderStage.VERTEX,texture:{}},{binding:3,visibility:GPUShaderStage.VERTEX,buffer:{type:"read-only-storage"}},{binding:4,visibility:GPUShaderStage.VERTEX,buffer:{type:"read-only-storage"}}]}),this.createBindGroupLayout(ResourceManager.PRESET_VERTEX_GPUBindGroupLayout_Instancing,{entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"read-only-storage"}},{binding:1,visibility:GPUShaderStage.VERTEX,sampler:{type:"filtering"}},{binding:2,visibility:GPUShaderStage.VERTEX,texture:{}},{binding:3,visibility:GPUShaderStage.VERTEX,buffer:{type:"read-only-storage"}}]})}#ft(i){return this.#ke.get(i)}#lt(i,g){const{code:x}=g,v=preprocessWGSL(i,x).defaultSource,_=this.redGPUContext.gpuDevice.createShaderModule({...g,code:v});return this.#ft(St.GPUShaderModule).set(i,_),_}#dt(i,g){if(!i)throw new Error("Name is required");return this.#ft(g)}#ut(i,g,x,v){const _=this.#dt(i,v);if(_.has(i))return _.get(i);g.label||(g.label=i);const y=x(g);return _.set(i,y),y}#ct(i,g){return this.#dt(i,g).get(i)}#ht(i,g){const x=this.#dt(i,g);if(!x.has(i))throw new Error(`${g} with name ${i} doesn't exist.`);x.delete(i)}}Object.freeze(ResourceManager);class ImmutableKeyMap extends Map{constructor(i=[]){super(),i?.forEach(([i,g])=>super.set(i,g))}set(i,g){if(this.has(i))throw new Error("Cannot change the value of an existing key");return super.set(i,g)}}class MemoryTrackingMap extends Map{#mt=0;constructor(){super()}get videoMemory(){return this.#mt}set(i,g){const x=g&&"videoMemorySize"in g?"videoMemorySize":g&&"size"in g?"size":void 0;if(this.has(i)){const g=this.get(i);g&&g[x]&&(this.#mt-=g[x])}if(g&&g){const i=g[x];"number"==typeof i&&(this.#mt+=i)}return super.set(i,g)}delete(i){if(this.has(i)){const g=this.get(i),x=g&&"videoMemorySize"in g?"videoMemorySize":g&&"size"in g?"size":void 0;g&&"number"==typeof g[x]&&(this.#mt-=g[x])}return super.delete(i)}clear(){this.#mt=0,super.clear()}}class AntialiasingManager{#pt=createUUID();#gt=!0;#xt=!1;#vt=!1;constructor(){window.devicePixelRatio>1?this.useTAA=!0:this.useMSAA=!0}get useTAA(){return this.#vt}set useTAA(i){this.#vt!==i&&(this.#_t(),this.#vt=i)}get useMSAA(){return this.#gt}set useMSAA(i){this.#gt!==i&&(this.#_t(),this.#pt=createUUID(),this.#gt=i)}get useFXAA(){return this.#xt}set useFXAA(i){this.#xt!==i&&(this.#_t(),this.#xt=i)}get msaaID(){return this.#pt}#_t(){this.#gt=!1,this.#xt=!1,this.#vt=!1}}Object.freeze(AntialiasingManager);class RedGPUContextDetector{#yt;#bt;#St;#Tt;#wt={};#Mt={};#Pt;#Rt;#Ct;#Bt;#Dt;#Et;#It;#At;#Lt;#Ut;constructor(i){const g=navigator.userAgent;this.#Rt=g,this.#Ct=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|Windows Phone|Kindle|Silk|PlayBook/i.test(g),this.#Bt=/iPhone|iPad|iPod/i.test(g),this.#Dt=/Android/i.test(g),this.#Et=/Chrome|Chromium|Edg|Opr/i.test(g)&&!/Edge/i.test(g),this.#It=/Safari/i.test(g)&&!/Chrome|Chromium|Edg|Opr/i.test(g),this.#At=/Firefox/i.test(g),this.#Lt=navigator.hardwareConcurrency||4,this.#Ut=navigator.deviceMemory||4;const{gpuAdapter:x,gpuDevice:v}=i;this.#yt=x;const _=["core-features-and-limits","depth-clip-control","depth32float-stencil8","texture-compression-bc","texture-compression-bc-sliced-3d","texture-compression-etc2","texture-compression-astc","texture-compression-astc-sliced-3d","timestamp-query","indirect-first-instance","shader-f16","rg11b10ufloat-renderable","bgra8unorm-storage","float32-filterable","float32-blendable","clip-distances","dual-source-blending","subgroups","texture-formats-tier1","texture-formats-tier2","primitive-index","texture-component-swizzle"];if(x){this.#bt=x.info,this.#Pt=x.info.isFallbackAdapter,this.#St=x.limits;const i=Array.from(x.features),g=Array.from(new Set([..._,...i])).sort();this.#wt={};for(const i of g)this.#wt[i]=x.features.has(i)}if(v){this.#Tt=v.limits,this.#Mt={};for(const i in this.#wt)this.#Mt[i]=v.features.has(i)}}get supportedFeatures(){return this.#wt}get activeFeatures(){return this.#Mt}get supportedLimits(){return this.#St}get activeLimits(){return this.#Tt}get gpuAdapter(){return this.#yt}get adapterInfo(){return this.#bt}get isFallbackAdapter(){return this.#Pt}get userAgent(){return this.#Rt}get isMobile(){return this.#Ct}get isIOS(){return this.#Bt}get isAndroid(){return this.#Dt}get isChromium(){return this.#Et}get isSafari(){return this.#It}get isFirefox(){return this.#At}get hardwareConcurrency(){return this.#Lt}get deviceMemory(){return this.#Ut}toReport(){return{platform:{isMobile:this.#Ct,isIOS:this.#Bt,isAndroid:this.#Dt,userAgent:this.#Rt},browser:{isChromium:this.#Et,isSafari:this.#It,isFirefox:this.#At},hardware:{hardwareConcurrency:this.#Lt,deviceMemory:this.#Ut},gpu:{vendor:this.#bt?.vendor,architecture:this.#bt?.architecture,device:this.#bt?.device,description:this.#bt?.description,isFallback:this.#Pt,supportedFeatures:{...this.#wt},activeFeatures:{...this.#Mt},supportedLimits:this.#St?this.#kt(this.#St):null,activeLimits:this.#Tt?this.#kt(this.#Tt):null}}}#kt(i){const g={},x=Object.getPrototypeOf(i);return Object.getOwnPropertyNames(x).forEach(x=>{const v=i[x];"number"==typeof v&&(g[x]=v)}),g}}const validateNumber=i=>"number"==typeof i&&!Number.isNaN(i)||(consoleAndThrowError("Only numbers allowed."),!1);class RedGPUContextSizeManager extends RedGPUObject{#Gt;#Ot;#Vt=[0,0,0,0];#Nt;#Ft=1;constructor(i,g="100%",x="100%"){super(i),this.#Nt=i.htmlCanvas,this.#Nt.style.boxSizing="border-box",this.#Nt.style.verticalAlign="top",this.#Gt=g,this.#Ot=x}get renderScale(){return this.#Ft}set renderScale(i){validateNumber(i),i<=0&&(i=.01),this.#Ft=i,this.setSize()}get width(){return this.#Gt}set width(i){this.setSize(i,this.#Ot)}get height(){return this.#Ot}set height(i){this.setSize(this.#Gt,i)}get pixelRectArray(){return this.#Vt}get pixelRectObject(){return{x:this.#Vt[0],y:this.#Vt[1],width:this.#Vt[2],height:this.#Vt[3]}}get parentDomRect(){const i=this.#Nt.parentElement;if(!i||i===document.body||i===document.documentElement)return{x:0,y:0,width:window.innerWidth,height:window.innerHeight};const g=i.getBoundingClientRect();return{x:g.x,y:g.y,width:i.clientWidth||g.width,height:i.clientHeight||g.height}}get screenRectObject(){return{x:this.#Vt[0]/devicePixelRatio,y:this.#Vt[1]/devicePixelRatio,width:this.#Vt[2]/devicePixelRatio,height:this.#Vt[3]/devicePixelRatio}}static validateSizeValue=i=>{switch(typeof i){case"number":validatePositiveNumberRange(i);break;case"string":new RegExp(/^[+]?^[.]?(\d+)(\.\d+)?(?:px|%|$)/gm).test(i)||consoleAndThrowError(`allow positive number, %, px model / input : ${i}`);break;default:consoleAndThrowError(`positive number, %, px model / input : ${i}`)}};static validatePositionValue=i=>{switch(typeof i){case"number":validateNumber(i);break;case"string":new RegExp(/^-?\d+(\.\d+)?(px|%)?$/).test(i)||consoleAndThrowError(`allow number, %, px model / input : ${i}`);break;default:consoleAndThrowError(`number, %, px model / input : ${i}`)}};static getPixelDimension(i,g,x){return"number"==typeof x?x:RedGPUContextSizeManager.calculateSizeFromString(i,g,x)}static calculateSizeFromString(i,g,x){return x.includes("%")?Math.round(i[g]*+x.replace("%","")/100):+x.replace("px","")}setSize(i=this.#Gt,g=this.#Ot){RedGPUContextSizeManager.validateSizeValue(i),RedGPUContextSizeManager.validateSizeValue(g),this.#Gt=i,this.#Ot=g;const x=this.parentDomRect,v=RedGPUContextSizeManager.getPixelDimension(x,"width",i),_=RedGPUContextSizeManager.getPixelDimension(x,"height",g),y=window.devicePixelRatio,b=Math.max(1,Math.floor(v*this.#Ft*y)),S=Math.max(1,Math.floor(_*this.#Ft*y));this.#Vt[2]===b&&this.#Vt[3]===S&&Math.abs(parseFloat(this.#Nt.style.width)-v)<.1&&Math.abs(parseFloat(this.#Nt.style.height)-_)<.1||(this.#Ht(v,_),this.#zt(v,_),this.#$t())}#zt(i,g){this.#Vt[2]=Math.max(1,Math.floor(i*this.#Ft*window.devicePixelRatio)),this.#Vt[3]=Math.max(1,Math.floor(g*this.#Ft*window.devicePixelRatio))}#$t(){const{redGPUContext:i}=this;i.onResize&&i.onResize({target:i,screenRectObject:this.screenRectObject,pixelRectObject:this.pixelRectObject}),i.viewList.forEach(i=>{i.setSize(),i.setPosition()})}#Ht(i,g){const x=this.#Nt,{style:v}=x;x.width=Math.max(1,i*this.#Ft*window.devicePixelRatio),x.height=Math.max(1,g*this.#Ft*window.devicePixelRatio),v.width=`${i}px`,v.height=`${g}px`}}var Tt=1e-6,wt="undefined"!=typeof Float32Array?Float32Array:Array,Mt=Math.random;function round$3(i){return i>=0?Math.round(i):i%.5==0?Math.floor(i):Math.round(i)}function create$5(){var i=new wt(9);return wt!=Float32Array&&(i[1]=0,i[2]=0,i[3]=0,i[5]=0,i[6]=0,i[7]=0),i[0]=1,i[4]=1,i[8]=1,i}function multiply$5(i,g,x){var v=g[0],_=g[1],y=g[2],b=g[3],S=g[4],w=g[5],L=g[6],k=g[7],H=g[8],z=x[0],q=x[1],W=x[2],be=x[3],je=x[4],Ke=x[5],Xe=x[6],Ye=x[7],Ze=x[8];return i[0]=z*v+q*b+W*L,i[1]=z*_+q*S+W*k,i[2]=z*y+q*w+W*H,i[3]=be*v+je*b+Ke*L,i[4]=be*_+je*S+Ke*k,i[5]=be*y+je*w+Ke*H,i[6]=Xe*v+Ye*b+Ze*L,i[7]=Xe*_+Ye*S+Ze*k,i[8]=Xe*y+Ye*w+Ze*H,i}function subtract$4(i,g,x){return i[0]=g[0]-x[0],i[1]=g[1]-x[1],i[2]=g[2]-x[2],i[3]=g[3]-x[3],i[4]=g[4]-x[4],i[5]=g[5]-x[5],i[6]=g[6]-x[6],i[7]=g[7]-x[7],i[8]=g[8]-x[8],i}var Pt=multiply$5,Rt=subtract$4,Ct=Object.freeze({__proto__:null,add:function(i,g,x){return i[0]=g[0]+x[0],i[1]=g[1]+x[1],i[2]=g[2]+x[2],i[3]=g[3]+x[3],i[4]=g[4]+x[4],i[5]=g[5]+x[5],i[6]=g[6]+x[6],i[7]=g[7]+x[7],i[8]=g[8]+x[8],i},adjoint:function(i,g){var x=g[0],v=g[1],_=g[2],y=g[3],b=g[4],S=g[5],w=g[6],L=g[7],k=g[8];return i[0]=b*k-S*L,i[1]=_*L-v*k,i[2]=v*S-_*b,i[3]=S*w-y*k,i[4]=x*k-_*w,i[5]=_*y-x*S,i[6]=y*L-b*w,i[7]=v*w-x*L,i[8]=x*b-v*y,i},clone:function(i){var g=new wt(9);return g[0]=i[0],g[1]=i[1],g[2]=i[2],g[3]=i[3],g[4]=i[4],g[5]=i[5],g[6]=i[6],g[7]=i[7],g[8]=i[8],g},copy:function(i,g){return i[0]=g[0],i[1]=g[1],i[2]=g[2],i[3]=g[3],i[4]=g[4],i[5]=g[5],i[6]=g[6],i[7]=g[7],i[8]=g[8],i},create:create$5,determinant:function(i){var g=i[0],x=i[1],v=i[2],_=i[3],y=i[4],b=i[5],S=i[6],w=i[7],L=i[8];return g*(L*y-b*w)+x*(-L*_+b*S)+v*(w*_-y*S)},equals:function(i,g){var x=i[0],v=i[1],_=i[2],y=i[3],b=i[4],S=i[5],w=i[6],L=i[7],k=i[8],H=g[0],z=g[1],q=g[2],W=g[3],be=g[4],je=g[5],Ke=g[6],Xe=g[7],Ye=g[8];return Math.abs(x-H)<=Tt*Math.max(1,Math.abs(x),Math.abs(H))&&Math.abs(v-z)<=Tt*Math.max(1,Math.abs(v),Math.abs(z))&&Math.abs(_-q)<=Tt*Math.max(1,Math.abs(_),Math.abs(q))&&Math.abs(y-W)<=Tt*Math.max(1,Math.abs(y),Math.abs(W))&&Math.abs(b-be)<=Tt*Math.max(1,Math.abs(b),Math.abs(be))&&Math.abs(S-je)<=Tt*Math.max(1,Math.abs(S),Math.abs(je))&&Math.abs(w-Ke)<=Tt*Math.max(1,Math.abs(w),Math.abs(Ke))&&Math.abs(L-Xe)<=Tt*Math.max(1,Math.abs(L),Math.abs(Xe))&&Math.abs(k-Ye)<=Tt*Math.max(1,Math.abs(k),Math.abs(Ye))},exactEquals:function(i,g){return i[0]===g[0]&&i[1]===g[1]&&i[2]===g[2]&&i[3]===g[3]&&i[4]===g[4]&&i[5]===g[5]&&i[6]===g[6]&&i[7]===g[7]&&i[8]===g[8]},frob:function(i){return Math.sqrt(i[0]*i[0]+i[1]*i[1]+i[2]*i[2]+i[3]*i[3]+i[4]*i[4]+i[5]*i[5]+i[6]*i[6]+i[7]*i[7]+i[8]*i[8])},fromMat2d:function(i,g){return i[0]=g[0],i[1]=g[1],i[2]=0,i[3]=g[2],i[4]=g[3],i[5]=0,i[6]=g[4],i[7]=g[5],i[8]=1,i},fromMat4:function(i,g){return i[0]=g[0],i[1]=g[1],i[2]=g[2],i[3]=g[4],i[4]=g[5],i[5]=g[6],i[6]=g[8],i[7]=g[9],i[8]=g[10],i},fromQuat:function(i,g){var x=g[0],v=g[1],_=g[2],y=g[3],b=x+x,S=v+v,w=_+_,L=x*b,k=v*b,H=v*S,z=_*b,q=_*S,W=_*w,be=y*b,je=y*S,Ke=y*w;return i[0]=1-H-W,i[3]=k-Ke,i[6]=z+je,i[1]=k+Ke,i[4]=1-L-W,i[7]=q-be,i[2]=z-je,i[5]=q+be,i[8]=1-L-H,i},fromRotation:function(i,g){var x=Math.sin(g),v=Math.cos(g);return i[0]=v,i[1]=x,i[2]=0,i[3]=-x,i[4]=v,i[5]=0,i[6]=0,i[7]=0,i[8]=1,i},fromScaling:function(i,g){return i[0]=g[0],i[1]=0,i[2]=0,i[3]=0,i[4]=g[1],i[5]=0,i[6]=0,i[7]=0,i[8]=1,i},fromTranslation:function(i,g){return i[0]=1,i[1]=0,i[2]=0,i[3]=0,i[4]=1,i[5]=0,i[6]=g[0],i[7]=g[1],i[8]=1,i},fromValues:function(i,g,x,v,_,y,b,S,w){var L=new wt(9);return L[0]=i,L[1]=g,L[2]=x,L[3]=v,L[4]=_,L[5]=y,L[6]=b,L[7]=S,L[8]=w,L},identity:function(i){return i[0]=1,i[1]=0,i[2]=0,i[3]=0,i[4]=1,i[5]=0,i[6]=0,i[7]=0,i[8]=1,i},invert:function(i,g){var x=g[0],v=g[1],_=g[2],y=g[3],b=g[4],S=g[5],w=g[6],L=g[7],k=g[8],H=k*b-S*L,z=-k*y+S*w,q=L*y-b*w,W=x*H+v*z+_*q;return W?(W=1/W,i[0]=H*W,i[1]=(-k*v+_*L)*W,i[2]=(S*v-_*b)*W,i[3]=z*W,i[4]=(k*x-_*w)*W,i[5]=(-S*x+_*y)*W,i[6]=q*W,i[7]=(-L*x+v*w)*W,i[8]=(b*x-v*y)*W,i):null},mul:Pt,multiply:multiply$5,multiplyScalar:function(i,g,x){return i[0]=g[0]*x,i[1]=g[1]*x,i[2]=g[2]*x,i[3]=g[3]*x,i[4]=g[4]*x,i[5]=g[5]*x,i[6]=g[6]*x,i[7]=g[7]*x,i[8]=g[8]*x,i},multiplyScalarAndAdd:function(i,g,x,v){return i[0]=g[0]+x[0]*v,i[1]=g[1]+x[1]*v,i[2]=g[2]+x[2]*v,i[3]=g[3]+x[3]*v,i[4]=g[4]+x[4]*v,i[5]=g[5]+x[5]*v,i[6]=g[6]+x[6]*v,i[7]=g[7]+x[7]*v,i[8]=g[8]+x[8]*v,i},normalFromMat4:function(i,g){var x=g[0],v=g[1],_=g[2],y=g[3],b=g[4],S=g[5],w=g[6],L=g[7],k=g[8],H=g[9],z=g[10],q=g[11],W=g[12],be=g[13],je=g[14],Ke=g[15],Xe=x*S-v*b,Ye=x*w-_*b,Ze=x*L-y*b,Je=v*w-_*S,Qe=v*L-y*S,et=_*L-y*w,tt=k*be-H*W,it=k*je-z*W,ft=k*Ke-q*W,pt=H*je-z*be,xt=H*Ke-q*be,vt=z*Ke-q*je,yt=Xe*vt-Ye*xt+Ze*pt+Je*ft-Qe*it+et*tt;return yt?(yt=1/yt,i[0]=(S*vt-w*xt+L*pt)*yt,i[1]=(w*ft-b*vt-L*it)*yt,i[2]=(b*xt-S*ft+L*tt)*yt,i[3]=(_*xt-v*vt-y*pt)*yt,i[4]=(x*vt-_*ft+y*it)*yt,i[5]=(v*ft-x*xt-y*tt)*yt,i[6]=(be*et-je*Qe+Ke*Je)*yt,i[7]=(je*Ze-W*et-Ke*Ye)*yt,i[8]=(W*Qe-be*Ze+Ke*Xe)*yt,i):null},projection:function(i,g,x){return i[0]=2/g,i[1]=0,i[2]=0,i[3]=0,i[4]=-2/x,i[5]=0,i[6]=-1,i[7]=1,i[8]=1,i},rotate:function(i,g,x){var v=g[0],_=g[1],y=g[2],b=g[3],S=g[4],w=g[5],L=g[6],k=g[7],H=g[8],z=Math.sin(x),q=Math.cos(x);return i[0]=q*v+z*b,i[1]=q*_+z*S,i[2]=q*y+z*w,i[3]=q*b-z*v,i[4]=q*S-z*_,i[5]=q*w-z*y,i[6]=L,i[7]=k,i[8]=H,i},scale:function(i,g,x){var v=x[0],_=x[1];return i[0]=v*g[0],i[1]=v*g[1],i[2]=v*g[2],i[3]=_*g[3],i[4]=_*g[4],i[5]=_*g[5],i[6]=g[6],i[7]=g[7],i[8]=g[8],i},set:function(i,g,x,v,_,y,b,S,w,L){return i[0]=g,i[1]=x,i[2]=v,i[3]=_,i[4]=y,i[5]=b,i[6]=S,i[7]=w,i[8]=L,i},str:function(i){return"mat3("+i[0]+", "+i[1]+", "+i[2]+", "+i[3]+", "+i[4]+", "+i[5]+", "+i[6]+", "+i[7]+", "+i[8]+")"},sub:Rt,subtract:subtract$4,translate:function(i,g,x){var v=g[0],_=g[1],y=g[2],b=g[3],S=g[4],w=g[5],L=g[6],k=g[7],H=g[8],z=x[0],q=x[1];return i[0]=v,i[1]=_,i[2]=y,i[3]=b,i[4]=S,i[5]=w,i[6]=z*v+q*b+L,i[7]=z*_+q*S+k,i[8]=z*y+q*w+H,i},transpose:function(i,g){if(i===g){var x=g[1],v=g[2],_=g[5];i[1]=g[3],i[2]=g[6],i[3]=x,i[5]=g[7],i[6]=v,i[7]=_}else i[0]=g[0],i[1]=g[3],i[2]=g[6],i[3]=g[1],i[4]=g[4],i[5]=g[7],i[6]=g[2],i[7]=g[5],i[8]=g[8];return i}});function create$4(){var i=new wt(16);return wt!=Float32Array&&(i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[11]=0,i[12]=0,i[13]=0,i[14]=0),i[0]=1,i[5]=1,i[10]=1,i[15]=1,i}function clone$4(i){var g=new wt(16);return g[0]=i[0],g[1]=i[1],g[2]=i[2],g[3]=i[3],g[4]=i[4],g[5]=i[5],g[6]=i[6],g[7]=i[7],g[8]=i[8],g[9]=i[9],g[10]=i[10],g[11]=i[11],g[12]=i[12],g[13]=i[13],g[14]=i[14],g[15]=i[15],g}function copy$4(i,g){return i[0]=g[0],i[1]=g[1],i[2]=g[2],i[3]=g[3],i[4]=g[4],i[5]=g[5],i[6]=g[6],i[7]=g[7],i[8]=g[8],i[9]=g[9],i[10]=g[10],i[11]=g[11],i[12]=g[12],i[13]=g[13],i[14]=g[14],i[15]=g[15],i}function fromValues$4(i,g,x,v,_,y,b,S,w,L,k,H,z,q,W,be){var je=new wt(16);return je[0]=i,je[1]=g,je[2]=x,je[3]=v,je[4]=_,je[5]=y,je[6]=b,je[7]=S,je[8]=w,je[9]=L,je[10]=k,je[11]=H,je[12]=z,je[13]=q,je[14]=W,je[15]=be,je}function identity$1(i){return i[0]=1,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=1,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[10]=1,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,i}function transpose(i,g){if(i===g){var x=g[1],v=g[2],_=g[3],y=g[6],b=g[7],S=g[11];i[1]=g[4],i[2]=g[8],i[3]=g[12],i[4]=x,i[6]=g[9],i[7]=g[13],i[8]=v,i[9]=y,i[11]=g[14],i[12]=_,i[13]=b,i[14]=S}else i[0]=g[0],i[1]=g[4],i[2]=g[8],i[3]=g[12],i[4]=g[1],i[5]=g[5],i[6]=g[9],i[7]=g[13],i[8]=g[2],i[9]=g[6],i[10]=g[10],i[11]=g[14],i[12]=g[3],i[13]=g[7],i[14]=g[11],i[15]=g[15];return i}function invert$1(i,g){var x=g[0],v=g[1],_=g[2],y=g[3],b=g[4],S=g[5],w=g[6],L=g[7],k=g[8],H=g[9],z=g[10],q=g[11],W=g[12],be=g[13],je=g[14],Ke=g[15],Xe=x*S-v*b,Ye=x*w-_*b,Ze=x*L-y*b,Je=v*w-_*S,Qe=v*L-y*S,et=_*L-y*w,tt=k*be-H*W,it=k*je-z*W,ft=k*Ke-q*W,pt=H*je-z*be,xt=H*Ke-q*be,vt=z*Ke-q*je,yt=Xe*vt-Ye*xt+Ze*pt+Je*ft-Qe*it+et*tt;return yt?(yt=1/yt,i[0]=(S*vt-w*xt+L*pt)*yt,i[1]=(_*xt-v*vt-y*pt)*yt,i[2]=(be*et-je*Qe+Ke*Je)*yt,i[3]=(z*Qe-H*et-q*Je)*yt,i[4]=(w*ft-b*vt-L*it)*yt,i[5]=(x*vt-_*ft+y*it)*yt,i[6]=(je*Ze-W*et-Ke*Ye)*yt,i[7]=(k*et-z*Ze+q*Ye)*yt,i[8]=(b*xt-S*ft+L*tt)*yt,i[9]=(v*ft-x*xt-y*tt)*yt,i[10]=(W*Qe-be*Ze+Ke*Xe)*yt,i[11]=(H*Ze-k*Qe-q*Xe)*yt,i[12]=(S*it-b*pt-w*tt)*yt,i[13]=(x*pt-v*it+_*tt)*yt,i[14]=(be*Ye-W*Je-je*Xe)*yt,i[15]=(k*Je-H*Ye+z*Xe)*yt,i):null}function multiply$4(i,g,x){var v=g[0],_=g[1],y=g[2],b=g[3],S=g[4],w=g[5],L=g[6],k=g[7],H=g[8],z=g[9],q=g[10],W=g[11],be=g[12],je=g[13],Ke=g[14],Xe=g[15],Ye=x[0],Ze=x[1],Je=x[2],Qe=x[3];return i[0]=Ye*v+Ze*S+Je*H+Qe*be,i[1]=Ye*_+Ze*w+Je*z+Qe*je,i[2]=Ye*y+Ze*L+Je*q+Qe*Ke,i[3]=Ye*b+Ze*k+Je*W+Qe*Xe,Ye=x[4],Ze=x[5],Je=x[6],Qe=x[7],i[4]=Ye*v+Ze*S+Je*H+Qe*be,i[5]=Ye*_+Ze*w+Je*z+Qe*je,i[6]=Ye*y+Ze*L+Je*q+Qe*Ke,i[7]=Ye*b+Ze*k+Je*W+Qe*Xe,Ye=x[8],Ze=x[9],Je=x[10],Qe=x[11],i[8]=Ye*v+Ze*S+Je*H+Qe*be,i[9]=Ye*_+Ze*w+Je*z+Qe*je,i[10]=Ye*y+Ze*L+Je*q+Qe*Ke,i[11]=Ye*b+Ze*k+Je*W+Qe*Xe,Ye=x[12],Ze=x[13],Je=x[14],Qe=x[15],i[12]=Ye*v+Ze*S+Je*H+Qe*be,i[13]=Ye*_+Ze*w+Je*z+Qe*je,i[14]=Ye*y+Ze*L+Je*q+Qe*Ke,i[15]=Ye*b+Ze*k+Je*W+Qe*Xe,i}function translate(i,g,x){var v,_,y,b,S,w,L,k,H,z,q,W,be=x[0],je=x[1],Ke=x[2];return g===i?(i[12]=g[0]*be+g[4]*je+g[8]*Ke+g[12],i[13]=g[1]*be+g[5]*je+g[9]*Ke+g[13],i[14]=g[2]*be+g[6]*je+g[10]*Ke+g[14],i[15]=g[3]*be+g[7]*je+g[11]*Ke+g[15]):(v=g[0],_=g[1],y=g[2],b=g[3],S=g[4],w=g[5],L=g[6],k=g[7],H=g[8],z=g[9],q=g[10],W=g[11],i[0]=v,i[1]=_,i[2]=y,i[3]=b,i[4]=S,i[5]=w,i[6]=L,i[7]=k,i[8]=H,i[9]=z,i[10]=q,i[11]=W,i[12]=v*be+S*je+H*Ke+g[12],i[13]=_*be+w*je+z*Ke+g[13],i[14]=y*be+L*je+q*Ke+g[14],i[15]=b*be+k*je+W*Ke+g[15]),i}function scale$4(i,g,x){var v=x[0],_=x[1],y=x[2];return i[0]=g[0]*v,i[1]=g[1]*v,i[2]=g[2]*v,i[3]=g[3]*v,i[4]=g[4]*_,i[5]=g[5]*_,i[6]=g[6]*_,i[7]=g[7]*_,i[8]=g[8]*y,i[9]=g[9]*y,i[10]=g[10]*y,i[11]=g[11]*y,i[12]=g[12],i[13]=g[13],i[14]=g[14],i[15]=g[15],i}function rotateX$2(i,g,x){var v=Math.sin(x),_=Math.cos(x),y=g[4],b=g[5],S=g[6],w=g[7],L=g[8],k=g[9],H=g[10],z=g[11];return g!==i&&(i[0]=g[0],i[1]=g[1],i[2]=g[2],i[3]=g[3],i[12]=g[12],i[13]=g[13],i[14]=g[14],i[15]=g[15]),i[4]=y*_+L*v,i[5]=b*_+k*v,i[6]=S*_+H*v,i[7]=w*_+z*v,i[8]=L*_-y*v,i[9]=k*_-b*v,i[10]=H*_-S*v,i[11]=z*_-w*v,i}function rotateY$2(i,g,x){var v=Math.sin(x),_=Math.cos(x),y=g[0],b=g[1],S=g[2],w=g[3],L=g[8],k=g[9],H=g[10],z=g[11];return g!==i&&(i[4]=g[4],i[5]=g[5],i[6]=g[6],i[7]=g[7],i[12]=g[12],i[13]=g[13],i[14]=g[14],i[15]=g[15]),i[0]=y*_-L*v,i[1]=b*_-k*v,i[2]=S*_-H*v,i[3]=w*_-z*v,i[8]=y*v+L*_,i[9]=b*v+k*_,i[10]=S*v+H*_,i[11]=w*v+z*_,i}function rotateZ$2(i,g,x){var v=Math.sin(x),_=Math.cos(x),y=g[0],b=g[1],S=g[2],w=g[3],L=g[4],k=g[5],H=g[6],z=g[7];return g!==i&&(i[8]=g[8],i[9]=g[9],i[10]=g[10],i[11]=g[11],i[12]=g[12],i[13]=g[13],i[14]=g[14],i[15]=g[15]),i[0]=y*_+L*v,i[1]=b*_+k*v,i[2]=S*_+H*v,i[3]=w*_+z*v,i[4]=L*_-y*v,i[5]=k*_-b*v,i[6]=H*_-S*v,i[7]=z*_-w*v,i}function fromRotationTranslation(i,g,x){var v=g[0],_=g[1],y=g[2],b=g[3],S=v+v,w=_+_,L=y+y,k=v*S,H=v*w,z=v*L,q=_*w,W=_*L,be=y*L,je=b*S,Ke=b*w,Xe=b*L;return i[0]=1-(q+be),i[1]=H+Xe,i[2]=z-Ke,i[3]=0,i[4]=H-Xe,i[5]=1-(k+be),i[6]=W+je,i[7]=0,i[8]=z+Ke,i[9]=W-je,i[10]=1-(k+q),i[11]=0,i[12]=x[0],i[13]=x[1],i[14]=x[2],i[15]=1,i}function getScaling(i,g){var x=g[0],v=g[1],_=g[2],y=g[4],b=g[5],S=g[6],w=g[8],L=g[9],k=g[10];return i[0]=Math.sqrt(x*x+v*v+_*_),i[1]=Math.sqrt(y*y+b*b+S*S),i[2]=Math.sqrt(w*w+L*L+k*k),i}function perspectiveNO(i,g,x,v,_){var y=1/Math.tan(g/2);if(i[0]=y/x,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=y,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[11]=-1,i[12]=0,i[13]=0,i[15]=0,null!=_&&_!==1/0){var b=1/(v-_);i[10]=(_+v)*b,i[14]=2*_*v*b}else i[10]=-1,i[14]=-2*v;return i}var Bt=perspectiveNO;function orthoNO(i,g,x,v,_,y,b){var S=1/(g-x),w=1/(v-_),L=1/(y-b);return i[0]=-2*S,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=-2*w,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[10]=2*L,i[11]=0,i[12]=(g+x)*S,i[13]=(_+v)*w,i[14]=(b+y)*L,i[15]=1,i}var Dt=orthoNO;function orthoZO(i,g,x,v,_,y,b){var S=1/(g-x),w=1/(v-_),L=1/(y-b);return i[0]=-2*S,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=-2*w,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[10]=L,i[11]=0,i[12]=(g+x)*S,i[13]=(_+v)*w,i[14]=y*L,i[15]=1,i}function lookAt(i,g,x,v){var _,y,b,S,w,L,k,H,z,q,W=g[0],be=g[1],je=g[2],Ke=v[0],Xe=v[1],Ye=v[2],Ze=x[0],Je=x[1],Qe=x[2];return Math.abs(W-Ze)0&&(k*=q=1/Math.sqrt(q),H*=q,z*=q);var W=w*z-L*H,be=L*k-S*z,je=S*H-w*k;return(q=W*W+be*be+je*je)>0&&(W*=q=1/Math.sqrt(q),be*=q,je*=q),i[0]=W,i[1]=be,i[2]=je,i[3]=0,i[4]=H*je-z*be,i[5]=z*W-k*je,i[6]=k*be-H*W,i[7]=0,i[8]=k,i[9]=H,i[10]=z,i[11]=0,i[12]=_,i[13]=y,i[14]=b,i[15]=1,i}function subtract$3(i,g,x){return i[0]=g[0]-x[0],i[1]=g[1]-x[1],i[2]=g[2]-x[2],i[3]=g[3]-x[3],i[4]=g[4]-x[4],i[5]=g[5]-x[5],i[6]=g[6]-x[6],i[7]=g[7]-x[7],i[8]=g[8]-x[8],i[9]=g[9]-x[9],i[10]=g[10]-x[10],i[11]=g[11]-x[11],i[12]=g[12]-x[12],i[13]=g[13]-x[13],i[14]=g[14]-x[14],i[15]=g[15]-x[15],i}var Et=multiply$4,It=subtract$3,At=Object.freeze({__proto__:null,add:function(i,g,x){return i[0]=g[0]+x[0],i[1]=g[1]+x[1],i[2]=g[2]+x[2],i[3]=g[3]+x[3],i[4]=g[4]+x[4],i[5]=g[5]+x[5],i[6]=g[6]+x[6],i[7]=g[7]+x[7],i[8]=g[8]+x[8],i[9]=g[9]+x[9],i[10]=g[10]+x[10],i[11]=g[11]+x[11],i[12]=g[12]+x[12],i[13]=g[13]+x[13],i[14]=g[14]+x[14],i[15]=g[15]+x[15],i},adjoint:function(i,g){var x=g[0],v=g[1],_=g[2],y=g[3],b=g[4],S=g[5],w=g[6],L=g[7],k=g[8],H=g[9],z=g[10],q=g[11],W=g[12],be=g[13],je=g[14],Ke=g[15],Xe=x*S-v*b,Ye=x*w-_*b,Ze=x*L-y*b,Je=v*w-_*S,Qe=v*L-y*S,et=_*L-y*w,tt=k*be-H*W,it=k*je-z*W,ft=k*Ke-q*W,pt=H*je-z*be,xt=H*Ke-q*be,vt=z*Ke-q*je;return i[0]=S*vt-w*xt+L*pt,i[1]=_*xt-v*vt-y*pt,i[2]=be*et-je*Qe+Ke*Je,i[3]=z*Qe-H*et-q*Je,i[4]=w*ft-b*vt-L*it,i[5]=x*vt-_*ft+y*it,i[6]=je*Ze-W*et-Ke*Ye,i[7]=k*et-z*Ze+q*Ye,i[8]=b*xt-S*ft+L*tt,i[9]=v*ft-x*xt-y*tt,i[10]=W*Qe-be*Ze+Ke*Xe,i[11]=H*Ze-k*Qe-q*Xe,i[12]=S*it-b*pt-w*tt,i[13]=x*pt-v*it+_*tt,i[14]=be*Ye-W*Je-je*Xe,i[15]=k*Je-H*Ye+z*Xe,i},clone:clone$4,copy:copy$4,create:create$4,decompose:function(i,g,x,v){g[0]=v[12],g[1]=v[13],g[2]=v[14];var _=v[0],y=v[1],b=v[2],S=v[4],w=v[5],L=v[6],k=v[8],H=v[9],z=v[10];x[0]=Math.sqrt(_*_+y*y+b*b),x[1]=Math.sqrt(S*S+w*w+L*L),x[2]=Math.sqrt(k*k+H*H+z*z);var q=1/x[0],W=1/x[1],be=1/x[2],je=_*q,Ke=y*W,Xe=b*be,Ye=S*q,Ze=w*W,Je=L*be,Qe=k*q,et=H*W,tt=z*be,it=je+Ze+tt,ft=0;return it>0?(ft=2*Math.sqrt(it+1),i[3]=.25*ft,i[0]=(Je-et)/ft,i[1]=(Qe-Xe)/ft,i[2]=(Ke-Ye)/ft):je>Ze&&je>tt?(ft=2*Math.sqrt(1+je-Ze-tt),i[3]=(Je-et)/ft,i[0]=.25*ft,i[1]=(Ke+Ye)/ft,i[2]=(Qe+Xe)/ft):Ze>tt?(ft=2*Math.sqrt(1+Ze-je-tt),i[3]=(Qe-Xe)/ft,i[0]=(Ke+Ye)/ft,i[1]=.25*ft,i[2]=(Je+et)/ft):(ft=2*Math.sqrt(1+tt-je-Ze),i[3]=(Ke-Ye)/ft,i[0]=(Qe+Xe)/ft,i[1]=(Je+et)/ft,i[2]=.25*ft),i},determinant:function(i){var g=i[0],x=i[1],v=i[2],_=i[3],y=i[4],b=i[5],S=i[6],w=i[7],L=i[8],k=i[9],H=i[10],z=i[11],q=i[12],W=i[13],be=i[14],je=g*b-x*y,Ke=g*S-v*y,Xe=x*S-v*b,Ye=L*W-k*q,Ze=L*be-H*q,Je=k*be-H*W;return w*(g*Je-x*Ze+v*Ye)-_*(y*Je-b*Ze+S*Ye)+i[15]*(L*Xe-k*Ke+H*je)-z*(q*Xe-W*Ke+be*je)},equals:function(i,g){var x=i[0],v=i[1],_=i[2],y=i[3],b=i[4],S=i[5],w=i[6],L=i[7],k=i[8],H=i[9],z=i[10],q=i[11],W=i[12],be=i[13],je=i[14],Ke=i[15],Xe=g[0],Ye=g[1],Ze=g[2],Je=g[3],Qe=g[4],et=g[5],tt=g[6],it=g[7],ft=g[8],pt=g[9],xt=g[10],vt=g[11],yt=g[12],bt=g[13],St=g[14],wt=g[15];return Math.abs(x-Xe)<=Tt*Math.max(1,Math.abs(x),Math.abs(Xe))&&Math.abs(v-Ye)<=Tt*Math.max(1,Math.abs(v),Math.abs(Ye))&&Math.abs(_-Ze)<=Tt*Math.max(1,Math.abs(_),Math.abs(Ze))&&Math.abs(y-Je)<=Tt*Math.max(1,Math.abs(y),Math.abs(Je))&&Math.abs(b-Qe)<=Tt*Math.max(1,Math.abs(b),Math.abs(Qe))&&Math.abs(S-et)<=Tt*Math.max(1,Math.abs(S),Math.abs(et))&&Math.abs(w-tt)<=Tt*Math.max(1,Math.abs(w),Math.abs(tt))&&Math.abs(L-it)<=Tt*Math.max(1,Math.abs(L),Math.abs(it))&&Math.abs(k-ft)<=Tt*Math.max(1,Math.abs(k),Math.abs(ft))&&Math.abs(H-pt)<=Tt*Math.max(1,Math.abs(H),Math.abs(pt))&&Math.abs(z-xt)<=Tt*Math.max(1,Math.abs(z),Math.abs(xt))&&Math.abs(q-vt)<=Tt*Math.max(1,Math.abs(q),Math.abs(vt))&&Math.abs(W-yt)<=Tt*Math.max(1,Math.abs(W),Math.abs(yt))&&Math.abs(be-bt)<=Tt*Math.max(1,Math.abs(be),Math.abs(bt))&&Math.abs(je-St)<=Tt*Math.max(1,Math.abs(je),Math.abs(St))&&Math.abs(Ke-wt)<=Tt*Math.max(1,Math.abs(Ke),Math.abs(wt))},exactEquals:function(i,g){return i[0]===g[0]&&i[1]===g[1]&&i[2]===g[2]&&i[3]===g[3]&&i[4]===g[4]&&i[5]===g[5]&&i[6]===g[6]&&i[7]===g[7]&&i[8]===g[8]&&i[9]===g[9]&&i[10]===g[10]&&i[11]===g[11]&&i[12]===g[12]&&i[13]===g[13]&&i[14]===g[14]&&i[15]===g[15]},frob:function(i){return Math.sqrt(i[0]*i[0]+i[1]*i[1]+i[2]*i[2]+i[3]*i[3]+i[4]*i[4]+i[5]*i[5]+i[6]*i[6]+i[7]*i[7]+i[8]*i[8]+i[9]*i[9]+i[10]*i[10]+i[11]*i[11]+i[12]*i[12]+i[13]*i[13]+i[14]*i[14]+i[15]*i[15])},fromQuat:function(i,g){var x=g[0],v=g[1],_=g[2],y=g[3],b=x+x,S=v+v,w=_+_,L=x*b,k=v*b,H=v*S,z=_*b,q=_*S,W=_*w,be=y*b,je=y*S,Ke=y*w;return i[0]=1-H-W,i[1]=k+Ke,i[2]=z-je,i[3]=0,i[4]=k-Ke,i[5]=1-L-W,i[6]=q+be,i[7]=0,i[8]=z+je,i[9]=q-be,i[10]=1-L-H,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,i},fromQuat2:function(i,g){var x=new wt(3),v=-g[0],_=-g[1],y=-g[2],b=g[3],S=g[4],w=g[5],L=g[6],k=g[7],H=v*v+_*_+y*y+b*b;return H>0?(x[0]=2*(S*b+k*v+w*y-L*_)/H,x[1]=2*(w*b+k*_+L*v-S*y)/H,x[2]=2*(L*b+k*y+S*_-w*v)/H):(x[0]=2*(S*b+k*v+w*y-L*_),x[1]=2*(w*b+k*_+L*v-S*y),x[2]=2*(L*b+k*y+S*_-w*v)),fromRotationTranslation(i,g,x),i},fromRotation:function(i,g,x){var v,_,y,b=x[0],S=x[1],w=x[2],L=Math.sqrt(b*b+S*S+w*w);return L0?(je=2*Math.sqrt(be+1),i[3]=.25*je,i[0]=(H-q)/je,i[1]=(z-w)/je,i[2]=(S-L)/je):b>k&&b>W?(je=2*Math.sqrt(1+b-k-W),i[3]=(H-q)/je,i[0]=.25*je,i[1]=(S+L)/je,i[2]=(z+w)/je):k>W?(je=2*Math.sqrt(1+k-b-W),i[3]=(z-w)/je,i[0]=(S+L)/je,i[1]=.25*je,i[2]=(H+q)/je):(je=2*Math.sqrt(1+W-b-k),i[3]=(S-L)/je,i[0]=(z+w)/je,i[1]=(H+q)/je,i[2]=.25*je),i},getScaling:getScaling,getTranslation:function(i,g){return i[0]=g[12],i[1]=g[13],i[2]=g[14],i},identity:identity$1,invert:invert$1,lookAt:lookAt,mul:Et,multiply:multiply$4,multiplyScalar:function(i,g,x){return i[0]=g[0]*x,i[1]=g[1]*x,i[2]=g[2]*x,i[3]=g[3]*x,i[4]=g[4]*x,i[5]=g[5]*x,i[6]=g[6]*x,i[7]=g[7]*x,i[8]=g[8]*x,i[9]=g[9]*x,i[10]=g[10]*x,i[11]=g[11]*x,i[12]=g[12]*x,i[13]=g[13]*x,i[14]=g[14]*x,i[15]=g[15]*x,i},multiplyScalarAndAdd:function(i,g,x,v){return i[0]=g[0]+x[0]*v,i[1]=g[1]+x[1]*v,i[2]=g[2]+x[2]*v,i[3]=g[3]+x[3]*v,i[4]=g[4]+x[4]*v,i[5]=g[5]+x[5]*v,i[6]=g[6]+x[6]*v,i[7]=g[7]+x[7]*v,i[8]=g[8]+x[8]*v,i[9]=g[9]+x[9]*v,i[10]=g[10]+x[10]*v,i[11]=g[11]+x[11]*v,i[12]=g[12]+x[12]*v,i[13]=g[13]+x[13]*v,i[14]=g[14]+x[14]*v,i[15]=g[15]+x[15]*v,i},ortho:Dt,orthoNO:orthoNO,orthoZO:orthoZO,perspective:Bt,perspectiveFromFieldOfView:function(i,g,x,v){var _=Math.tan(g.upDegrees*Math.PI/180),y=Math.tan(g.downDegrees*Math.PI/180),b=Math.tan(g.leftDegrees*Math.PI/180),S=Math.tan(g.rightDegrees*Math.PI/180),w=2/(b+S),L=2/(_+y);return i[0]=w,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=L,i[6]=0,i[7]=0,i[8]=-(b-S)*w*.5,i[9]=(_-y)*L*.5,i[10]=v/(x-v),i[11]=-1,i[12]=0,i[13]=0,i[14]=v*x/(x-v),i[15]=0,i},perspectiveNO:perspectiveNO,perspectiveZO:function(i,g,x,v,_){var y=1/Math.tan(g/2);if(i[0]=y/x,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=y,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[11]=-1,i[12]=0,i[13]=0,i[15]=0,null!=_&&_!==1/0){var b=1/(v-_);i[10]=_*b,i[14]=_*v*b}else i[10]=-1,i[14]=-v;return i},rotate:function(i,g,x,v){var _,y,b,S,w,L,k,H,z,q,W,be,je,Ke,Xe,Ye,Ze,Je,Qe,et,tt,it,ft,pt,xt=v[0],vt=v[1],yt=v[2],bt=Math.sqrt(xt*xt+vt*vt+yt*yt);return bt0&&(y=1/Math.sqrt(y)),i[0]=g[0]*y,i[1]=g[1]*y,i[2]=g[2]*y,i}function dot$3(i,g){return i[0]*g[0]+i[1]*g[1]+i[2]*g[2]}function cross$2(i,g,x){var v=g[0],_=g[1],y=g[2],b=x[0],S=x[1],w=x[2];return i[0]=_*w-y*S,i[1]=y*b-v*w,i[2]=v*S-_*b,i}function lerp$3(i,g,x,v){var _=g[0],y=g[1],b=g[2];return i[0]=_+v*(x[0]-_),i[1]=y+v*(x[1]-y),i[2]=b+v*(x[2]-b),i}function transformMat4$2(i,g,x){var v=g[0],_=g[1],y=g[2],b=x[3]*v+x[7]*_+x[11]*y+x[15];return b=b||1,i[0]=(x[0]*v+x[4]*_+x[8]*y+x[12])/b,i[1]=(x[1]*v+x[5]*_+x[9]*y+x[13])/b,i[2]=(x[2]*v+x[6]*_+x[10]*y+x[14])/b,i}var Lt,Ut=subtract$2,kt=multiply$3,Gt=divide$2,Ot=distance$2,Vt=squaredDistance$2,Nt=length$3,Ft=squaredLength$3,Ht=(Lt=create$3(),function(i,g,x,v,_,y){var b,S;for(g||(g=3),x||(x=0),S=v?Math.min(v*g+x,i.length):i.length,b=x;b0&&(b=1/Math.sqrt(b)),i[0]=x*b,i[1]=v*b,i[2]=_*b,i[3]=y*b,i}function dot$2(i,g){return i[0]*g[0]+i[1]*g[1]+i[2]*g[2]+i[3]*g[3]}function lerp$2(i,g,x,v){var _=g[0],y=g[1],b=g[2],S=g[3];return i[0]=_+v*(x[0]-_),i[1]=y+v*(x[1]-y),i[2]=b+v*(x[2]-b),i[3]=S+v*(x[3]-S),i}function transformMat4$1(i,g,x){var v=g[0],_=g[1],y=g[2],b=g[3];return i[0]=x[0]*v+x[4]*_+x[8]*y+x[12]*b,i[1]=x[1]*v+x[5]*_+x[9]*y+x[13]*b,i[2]=x[2]*v+x[6]*_+x[10]*y+x[14]*b,i[3]=x[3]*v+x[7]*_+x[11]*y+x[15]*b,i}function exactEquals$2(i,g){return i[0]===g[0]&&i[1]===g[1]&&i[2]===g[2]&&i[3]===g[3]}var $t=subtract$1,jt=multiply$2,Kt=divide$1,Xt=distance$1,qt=squaredDistance$1,Yt=length$2,Wt=squaredLength$2,Zt=function(){var i=create$2();return function(g,x,v,_,y,b){var S,w;for(x||(x=4),v||(v=0),w=_?Math.min(_*x+v,g.length):g.length,S=v;S0?S*Math.sin(b)/b:0;return i[0]=x*w,i[1]=v*w,i[2]=_*w,i[3]=S*Math.cos(b),i}function ln(i,g){var x=g[0],v=g[1],_=g[2],y=g[3],b=Math.sqrt(x*x+v*v+_*_),S=b>0?Math.atan2(b,y)/b:0;return i[0]=x*S,i[1]=v*S,i[2]=_*S,i[3]=.5*Math.log(x*x+v*v+_*_+y*y),i}function slerp(i,g,x,v){var _,y,b,S,w,L=g[0],k=g[1],H=g[2],z=g[3],q=x[0],W=x[1],be=x[2],je=x[3];return(y=L*q+k*W+H*be+z*je)<0&&(y=-y,q=-q,W=-W,be=-be,je=-je),1-y>Tt?(_=Math.acos(y),b=Math.sin(_),S=Math.sin((1-v)*_)/b,w=Math.sin(v*_)/b):(S=1-v,w=v),i[0]=S*L+w*q,i[1]=S*k+w*W,i[2]=S*H+w*be,i[3]=S*z+w*je,i}function fromMat3(i,g){var x,v=g[0]+g[4]+g[8];if(v>0)x=Math.sqrt(v+1),i[3]=.5*x,x=.5/x,i[0]=(g[5]-g[7])*x,i[1]=(g[6]-g[2])*x,i[2]=(g[1]-g[3])*x;else{var _=0;g[4]>g[0]&&(_=1),g[8]>g[3*_+_]&&(_=2);var y=(_+1)%3,b=(_+2)%3;x=Math.sqrt(g[3*_+_]-g[3*y+y]-g[3*b+b]+1),i[_]=.5*x,x=.5/x,i[3]=(g[3*y+b]-g[3*b+y])*x,i[y]=(g[3*y+_]+g[3*_+y])*x,i[b]=(g[3*b+_]+g[3*_+b])*x}return i}var Qt=clone$2,er=fromValues$2,tr=copy$2,rr=set$2,ir=add$2,nr=multiply$1,ar=scale$2,sr=dot$2,or=lerp$2,ur=length$2,lr=ur,cr=squaredLength$2,hr=cr,fr=normalize$2,dr=exactEquals$2;var mr,pr,gr,xr,vr=(mr=create$3(),pr=fromValues$3(1,0,0),gr=fromValues$3(0,1,0),function(i,g,x){var v=dot$3(g,x);return v<-.999999?(cross$2(mr,pr,g),Nt(mr)<1e-6&&cross$2(mr,gr,g),normalize$3(mr,mr),setAxisAngle(i,mr,Math.PI),i):v>.999999?(i[0]=0,i[1]=0,i[2]=0,i[3]=1,i):(cross$2(mr,g,x),i[0]=mr[0],i[1]=mr[1],i[2]=mr[2],i[3]=1+v,fr(i,i))}),_r=function(){var i=create$1(),g=create$1();return function(x,v,_,y,b,S){return slerp(i,v,b,S),slerp(g,_,y,S),slerp(x,i,g,2*S*(1-S)),x}}(),yr=(xr=create$5(),function(i,g,x,v){return xr[0]=x[0],xr[3]=x[1],xr[6]=x[2],xr[1]=v[0],xr[4]=v[1],xr[7]=v[2],xr[2]=-g[0],xr[5]=-g[1],xr[8]=-g[2],fr(i,fromMat3(i,xr))}),br=Object.freeze({__proto__:null,add:ir,calculateW:function(i,g){var x=g[0],v=g[1],_=g[2];return i[0]=x,i[1]=v,i[2]=_,i[3]=Math.sqrt(Math.abs(1-x*x-v*v-_*_)),i},clone:Qt,conjugate:function(i,g){return i[0]=-g[0],i[1]=-g[1],i[2]=-g[2],i[3]=g[3],i},copy:tr,create:create$1,dot:sr,equals:function(i,g){return Math.abs(dot$2(i,g))>=.999999},exactEquals:dr,exp:exp,fromEuler:function(i,g,x,v){var _=arguments.length>4&&void 0!==arguments[4]?arguments[4]:"zyx",y=Math.PI/360;g*=y,v*=y,x*=y;var b=Math.sin(g),S=Math.cos(g),w=Math.sin(x),L=Math.cos(x),k=Math.sin(v),H=Math.cos(v);switch(_){case"xyz":i[0]=b*L*H+S*w*k,i[1]=S*w*H-b*L*k,i[2]=S*L*k+b*w*H,i[3]=S*L*H-b*w*k;break;case"xzy":i[0]=b*L*H-S*w*k,i[1]=S*w*H-b*L*k,i[2]=S*L*k+b*w*H,i[3]=S*L*H+b*w*k;break;case"yxz":i[0]=b*L*H+S*w*k,i[1]=S*w*H-b*L*k,i[2]=S*L*k-b*w*H,i[3]=S*L*H+b*w*k;break;case"yzx":i[0]=b*L*H+S*w*k,i[1]=S*w*H+b*L*k,i[2]=S*L*k-b*w*H,i[3]=S*L*H-b*w*k;break;case"zxy":i[0]=b*L*H-S*w*k,i[1]=S*w*H+b*L*k,i[2]=S*L*k+b*w*H,i[3]=S*L*H-b*w*k;break;case"zyx":i[0]=b*L*H-S*w*k,i[1]=S*w*H+b*L*k,i[2]=S*L*k-b*w*H,i[3]=S*L*H+b*w*k;break;default:throw new Error("Unknown angle order "+_)}return i},fromMat3:fromMat3,fromValues:er,getAngle:function(i,g){var x=sr(i,g);return Math.acos(2*x*x-1)},getAxisAngle:function(i,g){var x=2*Math.acos(g[3]),v=Math.sin(x/2);return v>Tt?(i[0]=g[0]/v,i[1]=g[1]/v,i[2]=g[2]/v):(i[0]=1,i[1]=0,i[2]=0),x},identity:function(i){return i[0]=0,i[1]=0,i[2]=0,i[3]=1,i},invert:function(i,g){var x=g[0],v=g[1],_=g[2],y=g[3],b=x*x+v*v+_*_+y*y,S=b?1/b:0;return i[0]=-x*S,i[1]=-v*S,i[2]=-_*S,i[3]=y*S,i},len:lr,length:ur,lerp:or,ln:ln,mul:nr,multiply:multiply$1,normalize:fr,pow:function(i,g,x){return ln(i,g),ar(i,i,x),exp(i,i),i},random:function(i){var g=Mt(),x=Mt(),v=Mt(),_=Math.sqrt(1-g),y=Math.sqrt(g);return i[0]=_*Math.sin(2*Math.PI*x),i[1]=_*Math.cos(2*Math.PI*x),i[2]=y*Math.sin(2*Math.PI*v),i[3]=y*Math.cos(2*Math.PI*v),i},rotateX:function(i,g,x){x*=.5;var v=g[0],_=g[1],y=g[2],b=g[3],S=Math.sin(x),w=Math.cos(x);return i[0]=v*w+b*S,i[1]=_*w+y*S,i[2]=y*w-_*S,i[3]=b*w-v*S,i},rotateY:function(i,g,x){x*=.5;var v=g[0],_=g[1],y=g[2],b=g[3],S=Math.sin(x),w=Math.cos(x);return i[0]=v*w-y*S,i[1]=_*w+b*S,i[2]=y*w+v*S,i[3]=b*w-_*S,i},rotateZ:function(i,g,x){x*=.5;var v=g[0],_=g[1],y=g[2],b=g[3],S=Math.sin(x),w=Math.cos(x);return i[0]=v*w+_*S,i[1]=_*w-v*S,i[2]=y*w+b*S,i[3]=b*w-y*S,i},rotationTo:vr,scale:ar,set:rr,setAxes:yr,setAxisAngle:setAxisAngle,slerp:slerp,sqlerp:_r,sqrLen:hr,squaredLength:cr,str:function(i){return"quat("+i[0]+", "+i[1]+", "+i[2]+", "+i[3]+")"}});function create(){var i=new wt(2);return wt!=Float32Array&&(i[0]=0,i[1]=0),i}function fromValues(i,g){var x=new wt(2);return x[0]=i,x[1]=g,x}function set(i,g,x){return i[0]=g,i[1]=x,i}function subtract(i,g,x){return i[0]=g[0]-x[0],i[1]=g[1]-x[1],i}function multiply(i,g,x){return i[0]=g[0]*x[0],i[1]=g[1]*x[1],i}function divide(i,g,x){return i[0]=g[0]/x[0],i[1]=g[1]/x[1],i}function scaleAndAdd(i,g,x,v){return i[0]=g[0]+x[0]*v,i[1]=g[1]+x[1]*v,i}function distance(i,g){var x=g[0]-i[0],v=g[1]-i[1];return Math.sqrt(x*x+v*v)}function squaredDistance(i,g){var x=g[0]-i[0],v=g[1]-i[1];return x*x+v*v}function length(i){var g=i[0],x=i[1];return Math.sqrt(g*g+x*x)}function squaredLength(i){var g=i[0],x=i[1];return g*g+x*x}function lerp(i,g,x,v){var _=g[0],y=g[1];return i[0]=_+v*(x[0]-_),i[1]=y+v*(x[1]-y),i}var Sr=length,Tr=subtract,wr=multiply,Mr=divide,Pr=distance,Rr=squaredDistance,Cr=squaredLength,Br=function(){var i=create();return function(g,x,v,_,y,b){var S,w;for(x||(x=2),v||(v=0),w=_?Math.min(_*x+v,g.length):g.length,S=v;S0&&(_=1/Math.sqrt(_)),i[0]=g[0]*_,i[1]=g[1]*_,i},random:function(i,g){g=void 0===g?1:g;var x=2*Mt()*Math.PI;return i[0]=Math.cos(x)*g,i[1]=Math.sin(x)*g,i},rotate:function(i,g,x,v){var _=g[0]-x[0],y=g[1]-x[1],b=Math.sin(v),S=Math.cos(v);return i[0]=_*S-y*b+x[0],i[1]=_*b+y*S+x[1],i},round:function(i,g){return i[0]=round$3(g[0]),i[1]=round$3(g[1]),i},scale:function(i,g,x){return i[0]=g[0]*x,i[1]=g[1]*x,i},scaleAndAdd:scaleAndAdd,set:set,signedAngle:function(i,g){var x=i[0],v=i[1],_=g[0],y=g[1];return Math.atan2(x*y-v*_,x*_+v*y)},sqrDist:Rr,sqrLen:Cr,squaredDistance:squaredDistance,squaredLength:squaredLength,str:function(i){return"vec2("+i[0]+", "+i[1]+")"},sub:Tr,subtract:subtract,transformMat2:function(i,g,x){var v=g[0],_=g[1];return i[0]=x[0]*v+x[2]*_,i[1]=x[1]*v+x[3]*_,i},transformMat2d:function(i,g,x){var v=g[0],_=g[1];return i[0]=x[0]*v+x[2]*_+x[4],i[1]=x[1]*v+x[3]*_+x[5],i},transformMat3:function(i,g,x){var v=g[0],_=g[1];return i[0]=x[0]*v+x[3]*_+x[6],i[1]=x[1]*v+x[4]*_+x[7],i},transformMat4:function(i,g,x){var v=g[0],_=g[1];return i[0]=x[0]*v+x[4]*_+x[12],i[1]=x[1]*v+x[5]*_+x[13],i},zero:function(i){return i[0]=0,i[1]=0,i}});const Er={NEVER:"never",LESS:"less",EQUAL:"equal",LESS_EQUAL:"less-equal",GREATER:"greater",NOT_EQUAL:"not-equal",GREATER_EQUAL:"greater-equal",ALWAYS:"always"};Object.freeze(Er);class ResourceStateUniformBuffer{static dirtyList=[];buffer;uuid;#jt=0;constructor(i){this.buffer=i,this.uuid=i.uuid}get useNum(){return this.#jt}set useNum(i){this.#jt=i,ResourceStateUniformBuffer.dirtyList.push(this)}}const Ir=Symbol("gpuBuffer"),Ar=Symbol("gpuBufferData"),Lr=Symbol("gpuBufferDataViewF32"),Ur=Symbol("gpuBufferDataViewU32"),kr=Symbol("gpuBufferCacheKey");class ABaseBuffer extends ManagementResourceBase{[Ir];[kr];#Kt;constructor(i,g,x){super(i,g),this.#Kt=x}get cacheKey(){return this[kr]||this.uuid}get gpuBuffer(){return this[Ir]}get usage(){return this.#Kt}get size(){return this[Ar]?.byteLength||0}get videoMemorySize(){return this.size}destroy(){const i=this[Ir];i&&(this[Ir]=null,this.notifyUpdate(!0),this.redGPUContext.resourceManager.unregisterManagementResource(this),this.redGPUContext.commandEncoderManager.addDeferredDestroy(i))}}class AUniformBaseBuffer extends ABaseBuffer{[Ar];#Xt;#qt;constructor(i,g,x,v,_=""){super(i,g,x),this.#qt=v.byteLength,this.#Xt={size:this.#qt,usage:this.usage,label:_};try{this[Ir]=i.gpuDevice.createBuffer(this.#Xt)}catch(i){console.error("GPU 버퍼 생성에 실패했습니다:",i)}i.gpuDevice.queue.writeBuffer(this[Ir],0,v),this[Ar]=v,this[Lr]=new Float32Array(v),this[Ur]=new Uint32Array(v)}get label(){return this.#Xt.label}get data(){return this[Ar]}get dataViewF32(){return this[Lr]}get dataViewU32(){return this[Ur]}get size(){return this.#qt}get uniformBufferDescriptor(){return this.#Xt}writeOnlyBuffer(i,g){"boolean"==typeof g&&(g=g?1:0),this.redGPUContext.gpuDevice.queue.writeBuffer(this.gpuBuffer,i.uniformOffset,new i.View("number"==typeof g?[g]:g))}}class UniformBuffer extends AUniformBaseBuffer{constructor(i,g,x="",v=""){super(i,"managedUniformBufferState",GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC,g,x);const{table:_}=this.targetResourceManagedState,y=_.get(v);if(y)return y.buffer;v&&(this.name=v,this[kr]=v),this.redGPUContext.resourceManager.registerManagementResource(this,new ResourceStateUniformBuffer(this))}}Object.freeze(UniformBuffer);class e{constructor(i,g){this.name=i,this.attributes=g,this.size=0}get isArray(){return!1}get isStruct(){return!1}get isTemplate(){return!1}get isPointer(){return!1}getTypeName(){return this.name}}class t{constructor(i,g,x){this.name=i,this.type=g,this.attributes=x,this.offset=0,this.size=0}get isArray(){return this.type.isArray}get isStruct(){return this.type.isStruct}get isTemplate(){return this.type.isTemplate}get align(){return this.type.isStruct?this.type.align:0}get members(){return this.type.isStruct?this.type.members:null}get format(){return this.type.isArray||this.type.isTemplate?this.type.format:null}get count(){return this.type.isArray?this.type.count:0}get stride(){return this.type.isArray?this.type.stride:this.size}}class n extends e{constructor(i,g){super(i,g),this.members=[],this.align=0,this.startLine=-1,this.endLine=-1,this.inUse=!1}get isStruct(){return!0}}class s extends e{constructor(i,g){super(i,g),this.count=0,this.stride=0}get isArray(){return!0}getTypeName(){return`array<${this.format.getTypeName()}, ${this.count}>`}}class r extends e{constructor(i,g,x){super(i,x),this.format=g}get isPointer(){return!0}getTypeName(){return`&${this.format.getTypeName()}`}}class a extends e{constructor(i,g,x,v){super(i,x),this.format=g,this.access=v}get isTemplate(){return!0}getTypeName(){let i=this.name;if(null!==this.format){if("vec2"===i||"vec3"===i||"vec4"===i||"mat2x2"===i||"mat2x3"===i||"mat2x4"===i||"mat3x2"===i||"mat3x3"===i||"mat3x4"===i||"mat4x2"===i||"mat4x3"===i||"mat4x4"===i){if("f32"===this.format.name)return i+="f",i;if("i32"===this.format.name)return i+="i",i;if("u32"===this.format.name)return i+="u",i;if("bool"===this.format.name)return i+="b",i;if("f16"===this.format.name)return i+="h",i}i+=`<${this.format.name}>`}else if("vec2"===i||"vec3"===i||"vec4"===i)return i;return i}}var Gr;(i=>{i[i.Uniform=0]="Uniform",i[i.Storage=1]="Storage",i[i.Texture=2]="Texture",i[i.Sampler=3]="Sampler",i[i.StorageTexture=4]="StorageTexture"})(Gr||(Gr={}));class o{constructor(i,g,x,v,_,y,b){this.name=i,this.type=g,this.group=x,this.binding=v,this.attributes=_,this.resourceType=y,this.access=b}get isArray(){return this.type.isArray}get isStruct(){return this.type.isStruct}get isTemplate(){return this.type.isTemplate}get size(){return this.type.size}get align(){return this.type.isStruct?this.type.align:0}get members(){return this.type.isStruct?this.type.members:null}get format(){return this.type.isArray||this.type.isTemplate?this.type.format:null}get count(){return this.type.isArray?this.type.count:0}get stride(){return this.type.isArray?this.type.stride:this.size}}class c{constructor(i,g){this.name=i,this.type=g}}class l{constructor(i,g,x,v){this.name=i,this.type=g,this.locationType=x,this.location=v,this.interpolation=null}}class u{constructor(i,g,x,v){this.name=i,this.type=g,this.locationType=x,this.location=v}}class h{constructor(i,g,x,v){this.name=i,this.type=g,this.attributes=x,this.id=v}}class f{constructor(i,g,x){this.name=i,this.type=g,this.attributes=x}}class p{constructor(i,g=null,x){this.stage=null,this.inputs=[],this.outputs=[],this.arguments=[],this.returnType=null,this.resources=[],this.overrides=[],this.startLine=-1,this.endLine=-1,this.inUse=!1,this.calls=new Set,this.name=i,this.stage=g,this.attributes=x}}class d{constructor(){this.vertex=[],this.fragment=[],this.compute=[]}}function m(i){var g=(32768&i)>>15,x=(31744&i)>>10,v=1023&i;return 0==x?(g?-1:1)*Math.pow(2,-14)*(v/Math.pow(2,10)):31==x?v?NaN:1/0*(g?-1:1):(g?-1:1)*Math.pow(2,x-15)*(1+v/Math.pow(2,10))}const Or=new Float32Array(1),Vr=new Int32Array(Or.buffer),Nr=new Uint16Array(1);function y$1(i){Or[0]=i;const g=Vr[0],x=g>>31&1;let v=g>>23&255,_=8388607&g;if(255===v)return Nr[0]=x<<15|31744|(0!==_?512:0),Nr[0];if(0===v){if(0===_)return Nr[0]=x<<15,Nr[0];_|=8388608;let i=113;for(;!(8388608&_);)_<<=1,i--;return v=127-i,_&=8388607,v>0?(_=(_>>126-v)+(_>>127-v&1),Nr[0]=x<<15|v<<10|_>>13,Nr[0]):(Nr[0]=x<<15,Nr[0])}return v=v-127+15,v>=31?(Nr[0]=x<<15|31744,Nr[0]):v<=0?v<-10?(Nr[0]=x<<15,Nr[0]):(_=(8388608|_)>>1-v,Nr[0]=x<<15|_>>13,Nr[0]):(_>>=13,Nr[0]=x<<15|v<<10|_,Nr[0])}const Fr=new Uint32Array(1),Hr=new Float32Array(Fr.buffer,0,1);function w$1(i){const g=112+(i>>6&31)<<23|(63&i)<<17;return Fr[0]=g,Hr[0]}function I(i,g,x,v){const _=[0,0,0,0];for(let y=0;y{i.increment="++",i.decrement="--"})(jr||(jr={})),(i=>{i.parse=function(g){const x=g;if("parse"==x)throw new Error("Invalid value for IncrementOperator");return i[x]}})(jr||(jr={}));class R extends C{constructor(i,g){super(),this.operator=i,this.variable=g}get astNodeType(){return"increment"}search(i){this.variable.search(i)}}(i=>{i.assign="=",i.addAssign="+=",i.subtractAssin="-=",i.multiplyAssign="*=",i.divideAssign="/=",i.moduloAssign="%=",i.andAssign="&=",i.orAssign="|=",i.xorAssign="^=",i.shiftLeftAssign="<<=",i.shiftRightAssign=">>="})(Kr||(Kr={})),(Kr||(Kr={})).parse=function(i){const g=i;if("parse"==g)throw new Error("Invalid value for AssignOperator");return g};class G extends C{constructor(i,g,x){super(),this.operator=i,this.variable=g,this.value=x}get astNodeType(){return"assign"}search(i){this.variable.search(i),this.value.search(i)}}class X extends C{constructor(i,g){super(),this.name=i,this.args=g}get astNodeType(){return"call"}isBuiltin(){return $r.has(this.name)}search(i){for(const g of this.args)g.search(i);i(this)}}class j extends C{constructor(i,g){super(),this.body=i,this.continuing=g}get astNodeType(){return"loop"}search(i){var g;this.searchBlock(this.body,i),null===(g=this.continuing)||void 0===g||g.search(i)}}class Z extends C{constructor(i,g){super(),this.condition=i,this.cases=g}get astNodeType(){return"switch"}search(i){i(this);for(const g of this.cases)g.search(i)}}class Q extends C{constructor(i,g,x,v){super(),this.condition=i,this.body=g,this.elseif=x,this.else=v}get astNodeType(){return"if"}search(i){this.condition.search(i),this.searchBlock(this.body,i),this.searchBlock(this.elseif,i),this.searchBlock(this.else,i)}}class Y extends C{constructor(i){super(),this.value=i}get astNodeType(){return"return"}search(i){var g;null===(g=this.value)||void 0===g||g.search(i)}}class K extends C{constructor(i){super(),this.name=i}get astNodeType(){return"enable"}}class J extends C{constructor(i){super(),this.extensions=i}get astNodeType(){return"requires"}}class ee extends C{constructor(i,g){super(),this.severity=i,this.rule=g}get astNodeType(){return"diagnostic"}}class te extends C{constructor(i,g){super(),this.name=i,this.type=g}get astNodeType(){return"alias"}}class ne extends C{constructor(){super()}get astNodeType(){return"discard"}}class se extends C{constructor(){super(),this.condition=null,this.loopId=-1}get astNodeType(){return"break"}}class re extends C{constructor(){super(),this.loopId=-1}get astNodeType(){return"continue"}}class ae extends C{constructor(i){super(),this.attributes=null,this.name=i}get astNodeType(){return"type"}get isStruct(){return!1}get isArray(){return!1}static maxFormatType(i){let g=i[0];if("f32"===g.name)return g;for(let x=1;x`}else if("vec2"===i||"vec3"===i||"vec4"===i)return i;return i}}ce.vec2f=new ce("vec2",ae.f32,null),ce.vec3f=new ce("vec3",ae.f32,null),ce.vec4f=new ce("vec4",ae.f32,null),ce.vec2i=new ce("vec2",ae.i32,null),ce.vec3i=new ce("vec3",ae.i32,null),ce.vec4i=new ce("vec4",ae.i32,null),ce.vec2u=new ce("vec2",ae.u32,null),ce.vec3u=new ce("vec3",ae.u32,null),ce.vec4u=new ce("vec4",ae.u32,null),ce.vec2h=new ce("vec2",ae.f16,null),ce.vec3h=new ce("vec3",ae.f16,null),ce.vec4h=new ce("vec4",ae.f16,null),ce.vec2b=new ce("vec2",ae.bool,null),ce.vec3b=new ce("vec3",ae.bool,null),ce.vec4b=new ce("vec4",ae.bool,null),ce.mat2x2f=new ce("mat2x2",ae.f32,null),ce.mat2x3f=new ce("mat2x3",ae.f32,null),ce.mat2x4f=new ce("mat2x4",ae.f32,null),ce.mat3x2f=new ce("mat3x2",ae.f32,null),ce.mat3x3f=new ce("mat3x3",ae.f32,null),ce.mat3x4f=new ce("mat3x4",ae.f32,null),ce.mat4x2f=new ce("mat4x2",ae.f32,null),ce.mat4x3f=new ce("mat4x3",ae.f32,null),ce.mat4x4f=new ce("mat4x4",ae.f32,null),ce.mat2x2h=new ce("mat2x2",ae.f16,null),ce.mat2x3h=new ce("mat2x3",ae.f16,null),ce.mat2x4h=new ce("mat2x4",ae.f16,null),ce.mat3x2h=new ce("mat3x2",ae.f16,null),ce.mat3x3h=new ce("mat3x3",ae.f16,null),ce.mat3x4h=new ce("mat3x4",ae.f16,null),ce.mat4x2h=new ce("mat4x2",ae.f16,null),ce.mat4x3h=new ce("mat4x3",ae.f16,null),ce.mat4x4h=new ce("mat4x4",ae.f16,null),ce.mat2x2i=new ce("mat2x2",ae.i32,null),ce.mat2x3i=new ce("mat2x3",ae.i32,null),ce.mat2x4i=new ce("mat2x4",ae.i32,null),ce.mat3x2i=new ce("mat3x2",ae.i32,null),ce.mat3x3i=new ce("mat3x3",ae.i32,null),ce.mat3x4i=new ce("mat3x4",ae.i32,null),ce.mat4x2i=new ce("mat4x2",ae.i32,null),ce.mat4x3i=new ce("mat4x3",ae.i32,null),ce.mat4x4i=new ce("mat4x4",ae.i32,null),ce.mat2x2u=new ce("mat2x2",ae.u32,null),ce.mat2x3u=new ce("mat2x3",ae.u32,null),ce.mat2x4u=new ce("mat2x4",ae.u32,null),ce.mat3x2u=new ce("mat3x2",ae.u32,null),ce.mat3x3u=new ce("mat3x3",ae.u32,null),ce.mat3x4u=new ce("mat3x4",ae.u32,null),ce.mat4x2u=new ce("mat4x2",ae.u32,null),ce.mat4x3u=new ce("mat4x3",ae.u32,null),ce.mat4x4u=new ce("mat4x4",ae.u32,null);class le extends ae{constructor(i,g,x,v){super(i),this.storage=g,this.type=x,this.access=v}get astNodeType(){return"pointer"}}class ue extends ae{constructor(i,g,x,v){super(i),this.attributes=g,this.format=x,this.count=v}get astNodeType(){return"array"}get isArray(){return!0}}class he extends ae{constructor(i,g,x){super(i),this.format=g,this.access=x}get astNodeType(){return"sampler"}}class fe extends A{constructor(){super(),this.postfix=null}}class pe extends fe{constructor(i){super(),this.value=i}get astNodeType(){return"stringExpr"}toString(){return this.value}constEvaluateString(){return this.value}}class de extends fe{constructor(i,g){super(),this.type=i,this.args=g}get astNodeType(){return"createExpr"}search(i){if(i(this),this.args)for(const g of this.args)g.search(i)}constEvaluate(i,g){return g&&(g[0]=this.type),i.evalExpression(this,i.context)}}class me extends fe{constructor(i,g){super(),this.cachedReturnValue=null,this.name=i,this.args=g}get astNodeType(){return"callExpr"}setCachedReturnValue(i){this.cachedReturnValue=i}get isBuiltin(){return $r.has(this.name)}constEvaluate(i,g){return i.evalExpression(this,i.context)}search(i){for(const g of this.args)g.search(i);i(this)}}class ge extends fe{constructor(i){super(),this.name=i}get astNodeType(){return"varExpr"}search(i){i(this),this.postfix&&this.postfix.search(i)}constEvaluate(i,g){return i.evalExpression(this,i.context)}}class _e extends fe{constructor(i,g){super(),this.name=i,this.initializer=g}get astNodeType(){return"constExpr"}constEvaluate(i,g){if(this.initializer){const g=i.evalExpression(this.initializer,i.context);return null!==g&&this.postfix?g.getSubData(i,this.postfix,i.context):g}return null}search(i){this.initializer.search(i)}}class xe extends fe{constructor(i,g){super(),this.value=i,this.type=g}get astNodeType(){return"literalExpr"}constEvaluate(i,g){return void 0!==g&&(g[0]=this.type),this.value}get isScalar(){return this.value instanceof Be}get isVector(){return this.value instanceof Me||this.value instanceof Ue}get scalarValue(){return this.value instanceof Be?this.value.value:(console.error("Value is not scalar."),0)}get vectorValue(){return this.value instanceof Me||this.value instanceof Ue?this.value.data:(console.error("Value is not a vector or matrix."),new Float32Array(0))}}class ye extends fe{constructor(i,g){super(),this.type=i,this.value=g}get astNodeType(){return"bitcastExpr"}search(i){this.value.search(i)}}class ve extends fe{constructor(i){super(),this.index=i}search(i){this.index.search(i)}}class we extends fe{constructor(){super()}}class ke extends we{constructor(i,g){super(),this.operator=i,this.right=g}get astNodeType(){return"unaryOp"}constEvaluate(i,g){return i.evalExpression(this,i.context)}search(i){this.right.search(i)}}class Ie extends we{constructor(i,g,x){super(),this.operator=i,this.left=g,this.right=x}get astNodeType(){return"binaryOp"}_getPromotedType(i,g){return i.name===g.name?i:"f32"===i.name||"f32"===g.name?ae.f32:"u32"===i.name||"u32"===g.name?ae.u32:ae.i32}constEvaluate(i,g){return i.evalExpression(this,i.context)}search(i){this.left.search(i),this.right.search(i)}}class Te extends A{constructor(i){super(),this.body=i}search(i){i(this),this.searchBlock(this.body,i)}}class Se extends fe{constructor(){super()}get astNodeType(){return"default"}}class Ae extends Te{constructor(i,g){super(g),this.selectors=i}get astNodeType(){return"case"}search(i){this.searchBlock(this.body,i)}}class Ee extends Te{constructor(i){super(i)}get astNodeType(){return"default"}search(i){this.searchBlock(this.body,i)}}class $e extends A{constructor(i,g,x){super(),this.name=i,this.type=g,this.attributes=x}get astNodeType(){return"argument"}}class Le extends A{constructor(i,g){super(),this.condition=i,this.body=g}get astNodeType(){return"elseif"}search(i){this.condition.search(i),this.searchBlock(this.body,i)}}class Ce extends A{constructor(i,g,x){super(),this.name=i,this.type=g,this.attributes=x}get astNodeType(){return"member"}}class De extends A{constructor(i,g){super(),this.name=i,this.value=g}get astNodeType(){return"attribute"}}class Ne{constructor(i,g){this.parent=null,this.typeInfo=i,this.parent=g,this.id=Ne._id++}clone(){throw`Clone: Not implemented for ${this.constructor.name}`}setDataValue(i,g,x,v){console.error(`SetDataValue: Not implemented for ${this.constructor.name}`)}getSubData(i,g,x){return console.error(`GetDataValue: Not implemented for ${this.constructor.name}`),null}toString(){return`<${this.typeInfo.getTypeName()}>`}}Ne._id=0;class Ve extends Ne{constructor(){super(new e("void",null),null)}toString(){return"void"}}Ve.void=new Ve;class Oe extends Ne{constructor(i){super(new r("pointer",i.typeInfo,null),null),this.reference=i}clone(){return this}setDataValue(i,g,x,v){this.reference.setDataValue(i,g,x,v)}getSubData(i,g,x){return g?this.reference.getSubData(i,g,x):this}toString(){return`&${this.reference.toString()}`}}class Be extends Ne{constructor(i,g,x=null){super(g,x),i instanceof Int32Array||i instanceof Uint32Array||i instanceof Float32Array?this.data=i:"x32"===this.typeInfo.name?i-Math.floor(i)!==0?this.data=new Float32Array([i]):this.data=i>=0?new Uint32Array([i]):new Int32Array([i]):"i32"===this.typeInfo.name||"bool"===this.typeInfo.name?this.data=new Int32Array([i]):"u32"===this.typeInfo.name?this.data=new Uint32Array([i]):"f32"===this.typeInfo.name||"f16"===this.typeInfo.name?this.data=new Float32Array([i]):console.error("ScalarData2: Invalid type",g)}clone(){if(this.data instanceof Float32Array)return new Be(new Float32Array(this.data),this.typeInfo,null);if(this.data instanceof Int32Array)return new Be(new Int32Array(this.data),this.typeInfo,null);if(this.data instanceof Uint32Array)return new Be(new Uint32Array(this.data),this.typeInfo,null);throw"ScalarData: Invalid data type"}get value(){return this.data[0]}set value(i){this.data[0]=i}setDataValue(i,g,x,v){if(x)return void console.error("SetDataValue: Scalar data does not support postfix",x);if(!(g instanceof Be))return void console.error("SetDataValue: Invalid value",g);let _=g.data[0];"i32"===this.typeInfo.name||"u32"===this.typeInfo.name?_=Math.floor(_):"bool"===this.typeInfo.name&&(_=_?1:0),this.data[0]=_}getSubData(i,g,x){return g?(console.error("getSubData: Scalar data does not support postfix",g),null):this}toString(){return`${this.value}`}}function Fe(i,g,x){const v=g.length;return 2===v?"f32"===x?new Me(new Float32Array(g),i.getTypeInfo("vec2f")):"i32"===x||"bool"===x?new Me(new Int32Array(g),i.getTypeInfo("vec2i")):"u32"===x?new Me(new Uint32Array(g),i.getTypeInfo("vec2u")):"f16"===x?new Me(new Float32Array(g),i.getTypeInfo("vec2h")):(console.error(`getSubData: Unknown format ${x}`),null):3===v?"f32"===x?new Me(new Float32Array(g),i.getTypeInfo("vec3f")):"i32"===x||"bool"===x?new Me(new Int32Array(g),i.getTypeInfo("vec3i")):"u32"===x?new Me(new Uint32Array(g),i.getTypeInfo("vec3u")):"f16"===x?new Me(new Float32Array(g),i.getTypeInfo("vec3h")):(console.error(`getSubData: Unknown format ${x}`),null):4===v?"f32"===x?new Me(new Float32Array(g),i.getTypeInfo("vec4f")):"i32"===x||"bool"===x?new Me(new Int32Array(g),i.getTypeInfo("vec4i")):"u32"===x?new Me(new Uint32Array(g),i.getTypeInfo("vec4u")):"f16"===x?new Me(new Float32Array(g),i.getTypeInfo("vec4h")):(console.error(`getSubData: Unknown format ${x}`),null):(console.error(`getSubData: Invalid vector size ${g.length}`),null)}class Me extends Ne{constructor(i,g,x=null){if(super(g,x),i instanceof Float32Array||i instanceof Uint32Array||i instanceof Int32Array)this.data=i;else{const g=this.typeInfo.name;"vec2f"===g||"vec3f"===g||"vec4f"===g?this.data=new Float32Array(i):"vec2i"===g||"vec3i"===g||"vec4i"===g?this.data=new Int32Array(i):"vec2u"===g||"vec3u"===g||"vec4u"===g?this.data=new Uint32Array(i):"vec2h"===g||"vec3h"===g||"vec4h"===g?this.data=new Float32Array(i):"vec2b"===g||"vec3b"===g||"vec4b"===g?this.data=new Int32Array(i):"vec2"===g||"vec3"===g||"vec4"===g?this.data=new Float32Array(i):console.error(`VectorData: Invalid type ${g}`)}}clone(){if(this.data instanceof Float32Array)return new Me(new Float32Array(this.data),this.typeInfo,null);if(this.data instanceof Int32Array)return new Me(new Int32Array(this.data),this.typeInfo,null);if(this.data instanceof Uint32Array)return new Me(new Uint32Array(this.data),this.typeInfo,null);throw"VectorData: Invalid data type"}setDataValue(i,g,x,v){x instanceof pe?console.error("TODO: Set vector postfix"):g instanceof Me?this.data=g.data:console.error("SetDataValue: Invalid value",g)}getSubData(i,g,x){if(null===g)return this;let v=i.getTypeInfo("f32");if(this.typeInfo instanceof a)v=this.typeInfo.format||v;else{const g=this.typeInfo.name;"vec2f"===g||"vec3f"===g||"vec4f"===g?v=i.getTypeInfo("f32"):"vec2i"===g||"vec3i"===g||"vec4i"===g?v=i.getTypeInfo("i32"):"vec2b"===g||"vec3b"===g||"vec4b"===g?v=i.getTypeInfo("bool"):"vec2u"===g||"vec3u"===g||"vec4u"===g?v=i.getTypeInfo("u32"):"vec2h"===g||"vec3h"===g||"vec4h"===g?v=i.getTypeInfo("f16"):console.error(`GetSubData: Unknown type ${g}`)}let _=this;for(;null!==g&&null!==_;){if(g instanceof ve){const y=g.index;let b=-1;if(y instanceof xe){if(!(y.value instanceof Be))return console.error(`GetSubData: Invalid array index ${y.value}`),null;b=y.value.value}else{const g=i.evalExpression(y,x);if(!(g instanceof Be))return console.error("GetSubData: Unknown index type",y),null;b=g.value}if(b<0||b>=_.data.length)return console.error("GetSubData: Index out of range",b),null;if(_.data instanceof Float32Array){const i=new Float32Array(_.data.buffer,_.data.byteOffset+4*b,1);return new Be(i,v)}if(_.data instanceof Int32Array){const i=new Int32Array(_.data.buffer,_.data.byteOffset+4*b,1);return new Be(i,v)}if(_.data instanceof Uint32Array){const i=new Uint32Array(_.data.buffer,_.data.byteOffset+4*b,1);return new Be(i,v)}throw"GetSubData: Invalid data type"}if(!(g instanceof pe))return console.error("GetSubData: Unknown postfix",g),null;{const x=g.value.toLowerCase();if(1===x.length){let i=0;if("x"===x||"r"===x)i=0;else if("y"===x||"g"===x)i=1;else if("z"===x||"b"===x)i=2;else{if("w"!==x&&"a"!==x)return console.error(`GetSubData: Unknown member ${x}`),null;i=3}if(this.data instanceof Float32Array){let g=new Float32Array(this.data.buffer,this.data.byteOffset+4*i,1);return new Be(g,v,this)}if(this.data instanceof Int32Array){let g=new Int32Array(this.data.buffer,this.data.byteOffset+4*i,1);return new Be(g,v,this)}if(this.data instanceof Uint32Array){let g=new Uint32Array(this.data.buffer,this.data.byteOffset+4*i,1);return new Be(g,v,this)}}const y=[];for(const i of x)"x"===i||"r"===i?y.push(this.data[0]):"y"===i||"g"===i?y.push(this.data[1]):"z"===i||"b"===i?y.push(this.data[2]):"w"===i||"a"===i?y.push(this.data[3]):console.error(`GetDataValue: Unknown member ${i}`);_=Fe(i,y,v.name)}g=g.postfix}return _}toString(){let i=`${this.data[0]}`;for(let g=1;g=this.data.length)return console.error("GetDataValue: Index out of range",y),null;const b=v.endsWith("h")?"h":"f";let S;if("mat2x2"===v||"mat2x2f"===v||"mat2x2h"===v||"mat3x2"===v||"mat3x2f"===v||"mat3x2h"===v||"mat4x2"===v||"mat4x2f"===v||"mat4x2h"===v)S=new Me(new Float32Array(this.data.buffer,this.data.byteOffset+2*y*4,2),i.getTypeInfo(`vec2${b}`));else if("mat2x3"===v||"mat2x3f"===v||"mat2x3h"===v||"mat3x3"===v||"mat3x3f"===v||"mat3x3h"===v||"mat4x3"===v||"mat4x3f"===v||"mat4x3h"===v)S=new Me(new Float32Array(this.data.buffer,this.data.byteOffset+3*y*4,3),i.getTypeInfo(`vec3${b}`));else{if("mat2x4"!==v&&"mat2x4f"!==v&&"mat2x4h"!==v&&"mat3x4"!==v&&"mat3x4f"!==v&&"mat3x4h"!==v&&"mat4x4"!==v&&"mat4x4f"!==v&&"mat4x4h"!==v)return console.error(`GetDataValue: Unknown type ${v}`),null;S=new Me(new Float32Array(this.data.buffer,this.data.byteOffset+4*y*4,4),i.getTypeInfo(`vec4${b}`))}return g.postfix?S.getSubData(i,g.postfix,x):S}return console.error("GetDataValue: Invalid postfix",g),null}toString(){let i=`${this.data[0]}`;for(let g=1;g"!==y&&"x32"!==y)if("u32"!==y&&"atomic"!==y)if("bool"!==y){if("vec2f"===y||"vec2h"===y){const i=new Float32Array(this.buffer,v,2);return void(g instanceof Me?(i[0]=g.data[0],i[1]=g.data[1]):(i[0]=g[0],i[1]=g[1]))}if("vec3f"===y||"vec3h"===y){const i=new Float32Array(this.buffer,v,3);return void(g instanceof Me?(i[0]=g.data[0],i[1]=g.data[1],i[2]=g.data[2]):(i[0]=g[0],i[1]=g[1],i[2]=g[2]))}if("vec4f"===y||"vec4h"===y){const i=new Float32Array(this.buffer,v,4);return void(g instanceof Me?(i[0]=g.data[0],i[1]=g.data[1],i[2]=g.data[2],i[3]=g.data[3]):(i[0]=g[0],i[1]=g[1],i[2]=g[2],i[3]=g[3]))}if("vec2i"===y){const i=new Int32Array(this.buffer,v,2);return void(g instanceof Me?(i[0]=g.data[0],i[1]=g.data[1]):(i[0]=g[0],i[1]=g[1]))}if("vec3i"===y){const i=new Int32Array(this.buffer,v,3);return void(g instanceof Me?(i[0]=g.data[0],i[1]=g.data[1],i[2]=g.data[2]):(i[0]=g[0],i[1]=g[1],i[2]=g[2]))}if("vec4i"===y){const i=new Int32Array(this.buffer,v,4);return void(g instanceof Me?(i[0]=g.data[0],i[1]=g.data[1],i[2]=g.data[2],i[3]=g.data[3]):(i[0]=g[0],i[1]=g[1],i[2]=g[2],i[3]=g[3]))}if("vec2u"===y){const i=new Uint32Array(this.buffer,v,2);return void(g instanceof Me?(i[0]=g.data[0],i[1]=g.data[1]):(i[0]=g[0],i[1]=g[1]))}if("vec3u"===y){const i=new Uint32Array(this.buffer,v,3);return void(g instanceof Me?(i[0]=g.data[0],i[1]=g.data[1],i[2]=g.data[2]):(i[0]=g[0],i[1]=g[1],i[2]=g[2]))}if("vec4u"===y){const i=new Uint32Array(this.buffer,v,4);return void(g instanceof Me?(i[0]=g.data[0],i[1]=g.data[1],i[2]=g.data[2],i[3]=g.data[3]):(i[0]=g[0],i[1]=g[1],i[2]=g[2],i[3]=g[3]))}if("vec2b"===y){const i=new Uint32Array(this.buffer,v,2);return void(g instanceof Me?(i[0]=g.data[0],i[1]=g.data[1]):(i[0]=g[0],i[1]=g[1]))}if("vec3b"===y){const i=new Uint32Array(this.buffer,v,3);return void(g instanceof Me?(i[0]=g.data[0],i[1]=g.data[1],i[2]=g.data[2]):(i[0]=g[0],i[1]=g[1],i[2]=g[2]))}if("vec4b"===y){const i=new Uint32Array(this.buffer,v,4);return void(g instanceof Me?(i[0]=g.data[0],i[1]=g.data[1],i[2]=g.data[2],i[3]=g.data[3]):(i[0]=g[0],i[1]=g[1],i[2]=g[2],i[3]=g[3]))}if("mat2x2f"===y||"mat2x2h"===y){const i=new Float32Array(this.buffer,v,4);return void(g instanceof Ue?(i[0]=g.data[0],i[1]=g.data[1],i[2]=g.data[2],i[3]=g.data[3]):(i[0]=g[0],i[1]=g[1],i[2]=g[2],i[3]=g[3]))}if("mat2x3f"===y||"mat2x3h"===y){const i=new Float32Array(this.buffer,v,6);return void(g instanceof Ue?(i[0]=g.data[0],i[1]=g.data[1],i[2]=g.data[2],i[3]=g.data[3],i[4]=g.data[4],i[5]=g.data[5]):(i[0]=g[0],i[1]=g[1],i[2]=g[2],i[3]=g[3],i[4]=g[4],i[5]=g[5]))}if("mat2x4f"===y||"mat2x4h"===y){const i=new Float32Array(this.buffer,v,8);return void(g instanceof Ue?(i[0]=g.data[0],i[1]=g.data[1],i[2]=g.data[2],i[3]=g.data[3],i[4]=g.data[4],i[5]=g.data[5],i[6]=g.data[6],i[7]=g.data[7]):(i[0]=g[0],i[1]=g[1],i[2]=g[2],i[3]=g[3],i[4]=g[4],i[5]=g[5],i[6]=g[6],i[7]=g[7]))}if("mat3x2f"===y||"mat3x2h"===y){const i=new Float32Array(this.buffer,v,6);return void(g instanceof Ue?(i[0]=g.data[0],i[1]=g.data[1],i[2]=g.data[2],i[3]=g.data[3],i[4]=g.data[4],i[5]=g.data[5]):(i[0]=g[0],i[1]=g[1],i[2]=g[2],i[3]=g[3],i[4]=g[4],i[5]=g[5]))}if("mat3x3f"===y||"mat3x3h"===y){const i=new Float32Array(this.buffer,v,9);return void(g instanceof Ue?(i[0]=g.data[0],i[1]=g.data[1],i[2]=g.data[2],i[3]=g.data[3],i[4]=g.data[4],i[5]=g.data[5],i[6]=g.data[6],i[7]=g.data[7],i[8]=g.data[8]):(i[0]=g[0],i[1]=g[1],i[2]=g[2],i[3]=g[3],i[4]=g[4],i[5]=g[5],i[6]=g[6],i[7]=g[7],i[8]=g[8]))}if("mat3x4f"===y||"mat3x4h"===y){const i=new Float32Array(this.buffer,v,12);return void(g instanceof Ue?(i[0]=g.data[0],i[1]=g.data[1],i[2]=g.data[2],i[3]=g.data[3],i[4]=g.data[4],i[5]=g.data[5],i[6]=g.data[6],i[7]=g.data[7],i[8]=g.data[8],i[9]=g.data[9],i[10]=g.data[10],i[11]=g.data[11]):(i[0]=g[0],i[1]=g[1],i[2]=g[2],i[3]=g[3],i[4]=g[4],i[5]=g[5],i[6]=g[6],i[7]=g[7],i[8]=g[8],i[9]=g[9],i[10]=g[10],i[11]=g[11]))}if("mat4x2f"===y||"mat4x2h"===y){const i=new Float32Array(this.buffer,v,8);return void(g instanceof Ue?(i[0]=g.data[0],i[1]=g.data[1],i[2]=g.data[2],i[3]=g.data[3],i[4]=g.data[4],i[5]=g.data[5],i[6]=g.data[6],i[7]=g.data[7]):(i[0]=g[0],i[1]=g[1],i[2]=g[2],i[3]=g[3],i[4]=g[4],i[5]=g[5],i[6]=g[6],i[7]=g[7]))}if("mat4x3f"===y||"mat4x3h"===y){const i=new Float32Array(this.buffer,v,12);return void(g instanceof Ue?(i[0]=g.data[0],i[1]=g.data[1],i[2]=g.data[2],i[3]=g.data[3],i[4]=g.data[4],i[5]=g.data[5],i[6]=g.data[6],i[7]=g.data[7],i[8]=g.data[8],i[9]=g.data[9],i[10]=g.data[10],i[11]=g.data[11]):(i[0]=g[0],i[1]=g[1],i[2]=g[2],i[3]=g[3],i[4]=g[4],i[5]=g[5],i[6]=g[6],i[7]=g[7],i[8]=g[8],i[9]=g[9],i[10]=g[10],i[11]=g[11]))}if("mat4x4f"===y||"mat4x4h"===y){const i=new Float32Array(this.buffer,v,16);return void(g instanceof Ue?(i[0]=g.data[0],i[1]=g.data[1],i[2]=g.data[2],i[3]=g.data[3],i[4]=g.data[4],i[5]=g.data[5],i[6]=g.data[6],i[7]=g.data[7],i[8]=g.data[8],i[9]=g.data[9],i[10]=g.data[10],i[11]=g.data[11],i[12]=g.data[12],i[13]=g.data[13],i[14]=g.data[14],i[15]=g.data[15]):(i[0]=g[0],i[1]=g[1],i[2]=g[2],i[3]=g[3],i[4]=g[4],i[5]=g[5],i[6]=g[6],i[7]=g[7],i[8]=g[8],i[9]=g[9],i[10]=g[10],i[11]=g[11],i[12]=g[12],i[13]=g[13],i[14]=g[14],i[15]=g[15]))}if(g instanceof Pe){if(x===g.typeInfo)return void new Uint8Array(this.buffer,v,g.buffer.byteLength).set(new Uint8Array(g.buffer));console.error("SetDataValue: Type mismatch",y,g.typeInfo.getTypeName())}else console.error(`SetData: Unknown type ${y}`)}else g instanceof Be&&(new Int32Array(this.buffer,v,1)[0]=g.value);else g instanceof Be&&(new Uint32Array(this.buffer,v,1)[0]=g.value);else g instanceof Be&&(new Int32Array(this.buffer,v,1)[0]=g.value);else g instanceof Be&&(new Float32Array(this.buffer,v,1)[0]=g.value)}getSubData(i,g,x){var v,_,y;if(null===g)return this;let b=this.offset,S=this.typeInfo;for(;g;){if(g instanceof ve){const v=g.index,_=v instanceof fe?i.evalExpression(v,x):v;let y=0;if(_ instanceof Be?y=_.value:"number"==typeof _?y=_:console.error("GetDataValue: Invalid index type",v),S instanceof s)b+=y*S.stride,S=S.format;else{const g=S.getTypeName();"mat4x4"===g||"mat4x4f"===g||"mat4x4h"===g?(b+=16*y,S=i.getTypeInfo("vec4f")):console.error(`getDataValue: Type ${S.getTypeName()} is not an array`)}}else{if(!(g instanceof pe))return console.error("GetDataValue: Unknown postfix type",g),null;{const x=g.value;if(S instanceof n){let i=!1;for(const g of S.members)if(g.name===x){b+=g.offset,S=g.type,i=!0;break}if(!i)return console.error(`GetDataValue: Member ${x} not found`),null}else if(S instanceof e){const g=S.getTypeName();if("vec2f"===g||"vec3f"===g||"vec4f"===g||"vec2i"===g||"vec3i"===g||"vec4i"===g||"vec2u"===g||"vec3u"===g||"vec4u"===g||"vec2b"===g||"vec3b"===g||"vec4b"===g||"vec2h"===g||"vec3h"===g||"vec4h"===g||"vec2"===g||"vec3"===g||"vec4"===g){if(x.length>0&&x.length<5){let v="f";const _=[];for(let y=0;y=this.buffer.byteLength)return console.log("Insufficient buffer data"),null;const i=new Float32Array(this.buffer,b,3);_.push(i[w])}else if("vec4f"===g)_.push(new Float32Array(this.buffer,b,4)[w]);else if("vec2i"===g)v="i",_.push(new Int32Array(this.buffer,b,2)[w]);else if("vec3i"===g)v="i",_.push(new Int32Array(this.buffer,b,3)[w]);else if("vec4i"===g)v="i",_.push(new Int32Array(this.buffer,b,4)[w]);else if("vec2u"===g){v="u";const i=new Uint32Array(this.buffer,b,2);_.push(i[w])}else"vec3u"===g?(v="u",_.push(new Uint32Array(this.buffer,b,3)[w])):"vec4u"===g&&(v="u",_.push(new Uint32Array(this.buffer,b,4)[w]))}return 2===_.length?S=i.getTypeInfo(`vec2${v}`):3===_.length?S=i.getTypeInfo(`vec3${v}`):4===_.length?S=i.getTypeInfo(`vec4${v}`):console.error(`GetDataValue: Invalid vector length ${_.length}`),new Me(_,S,null)}return console.error(`GetDataValue: Unknown member ${x}`),null}return console.error(`GetDataValue: Type ${g} is not a struct`),null}}}g=g.postfix}const w=S.getTypeName();return"f32"===w?new Be(new Float32Array(this.buffer,b,1),S,this):"i32"===w?new Be(new Int32Array(this.buffer,b,1),S,this):"u32"===w?new Be(new Uint32Array(this.buffer,b,1),S,this):"vec2f"===w?new Me(new Float32Array(this.buffer,b,2),S,this):"vec3f"===w?new Me(new Float32Array(this.buffer,b,3),S,this):"vec4f"===w?new Me(new Float32Array(this.buffer,b,4),S,this):"vec2i"===w?new Me(new Int32Array(this.buffer,b,2),S,this):"vec3i"===w?new Me(new Int32Array(this.buffer,b,3),S,this):"vec4i"===w?new Me(new Int32Array(this.buffer,b,4),S,this):"vec2u"===w?new Me(new Uint32Array(this.buffer,b,2),S,this):"vec3u"===w?new Me(new Uint32Array(this.buffer,b,3),S,this):"vec4u"===w?new Me(new Uint32Array(this.buffer,b,4),S,this):S instanceof a&&"atomic"===S.name?"u32"===(null===(v=S.format)||void 0===v?void 0:v.name)?new Be(new Uint32Array(this.buffer,b,1)[0],S.format,this):"i32"===(null===(_=S.format)||void 0===_?void 0:_.name)?new Be(new Int32Array(this.buffer,b,1)[0],S.format,this):(console.error(`GetDataValue: Invalid atomic format ${null===(y=S.format)||void 0===y?void 0:y.name}`),null):new Pe(this.buffer,S,b,this)}toString(){let i="";if(this.typeInfo instanceof s)if("f32"===this.typeInfo.format.name){const g=new Float32Array(this.buffer,this.offset);i=`[${g[0]}`;for(let x=1;x0?null!==(i=x[0])&&void 0!==i?i:0:x instanceof Object&&null!==(g=x.width)&&void 0!==g?g:0}get height(){var i,g;const x=this.descriptor.size;return x instanceof Array&&x.length>1?null!==(i=x[1])&&void 0!==i?i:0:x instanceof Object&&null!==(g=x.height)&&void 0!==g?g:0}get depthOrArrayLayers(){var i,g;const x=this.descriptor.size;return x instanceof Array&&x.length>2?null!==(i=x[2])&&void 0!==i?i:0:x instanceof Object&&null!==(g=x.depthOrArrayLayers)&&void 0!==g?g:0}get format(){var i;return this.descriptor&&null!==(i=this.descriptor.format)&&void 0!==i?i:"rgba8unorm"}get sampleCount(){var i;return this.descriptor&&null!==(i=this.descriptor.sampleCount)&&void 0!==i?i:1}get mipLevelCount(){var i;return this.descriptor&&null!==(i=this.descriptor.mipLevelCount)&&void 0!==i?i:1}get dimension(){var i;return this.descriptor&&null!==(i=this.descriptor.dimension)&&void 0!==i?i:"2d"}getMipLevelSize(i){if(i>=this.mipLevelCount)return[0,0,0];const g=[this.width,this.height,this.depthOrArrayLayers];for(let x=0;x>i);return g}get texelByteSize(){const i=this.format,g=zr[i];return g?g.isDepthStencil?4:g.bytesPerBlock:0}get bytesPerRow(){return this.width*this.texelByteSize}get isDepthStencil(){const i=this.format,g=zr[i];return!!g&&g.isDepthStencil}getGpuSize(){const i=this.format,g=zr[i],x=this.width;if(!i||x<=0||!g)return-1;const v=this.height,_=this.depthOrArrayLayers,y=this.dimension;return x/g.blockWidth*("1d"===y?1:v/g.blockHeight)*g.bytesPerBlock*_}getPixel(i,g,x=0,v=0){const _=this.texelByteSize,y=this.bytesPerRow,b=this.height,S=this.data[v];return function(i,g,x,v,_,y,b,S,w){const L=v*(b>>=_)*(y>>=_)+x*b+g*S;switch(w){case"r8unorm":return[I(i,L,"8unorm",1)[0]];case"r8snorm":return[I(i,L,"8snorm",1)[0]];case"r8uint":return[I(i,L,"8uint",1)[0]];case"r8sint":return[I(i,L,"8sint",1)[0]];case"rg8unorm":{const g=I(i,L,"8unorm",2);return[g[0],g[1]]}case"rg8snorm":{const g=I(i,L,"8snorm",2);return[g[0],g[1]]}case"rg8uint":{const g=I(i,L,"8uint",2);return[g[0],g[1]]}case"rg8sint":{const g=I(i,L,"8sint",2);return[g[0],g[1]]}case"rgba8unorm-srgb":case"rgba8unorm":{const g=I(i,L,"8unorm",4);return[g[0],g[1],g[2],g[3]]}case"rgba8snorm":{const g=I(i,L,"8snorm",4);return[g[0],g[1],g[2],g[3]]}case"rgba8uint":{const g=I(i,L,"8uint",4);return[g[0],g[1],g[2],g[3]]}case"rgba8sint":{const g=I(i,L,"8sint",4);return[g[0],g[1],g[2],g[3]]}case"bgra8unorm-srgb":case"bgra8unorm":{const g=I(i,L,"8unorm",4);return[g[2],g[1],g[0],g[3]]}case"r16uint":return[I(i,L,"16uint",1)[0]];case"r16sint":return[I(i,L,"16sint",1)[0]];case"r16float":return[I(i,L,"16float",1)[0]];case"rg16uint":{const g=I(i,L,"16uint",2);return[g[0],g[1]]}case"rg16sint":{const g=I(i,L,"16sint",2);return[g[0],g[1]]}case"rg16float":{const g=I(i,L,"16float",2);return[g[0],g[1]]}case"rgba16uint":{const g=I(i,L,"16uint",4);return[g[0],g[1],g[2],g[3]]}case"rgba16sint":{const g=I(i,L,"16sint",4);return[g[0],g[1],g[2],g[3]]}case"rgba16float":{const g=I(i,L,"16float",4);return[g[0],g[1],g[2],g[3]]}case"r32uint":return[I(i,L,"32uint",1)[0]];case"r32sint":return[I(i,L,"32sint",1)[0]];case"depth16unorm":case"depth24plus":case"depth24plus-stencil8":case"depth32float":case"depth32float-stencil8":case"r32float":return[I(i,L,"32float",1)[0]];case"rg32uint":{const g=I(i,L,"32uint",2);return[g[0],g[1]]}case"rg32sint":{const g=I(i,L,"32sint",2);return[g[0],g[1]]}case"rg32float":{const g=I(i,L,"32float",2);return[g[0],g[1]]}case"rgba32uint":{const g=I(i,L,"32uint",4);return[g[0],g[1],g[2],g[3]]}case"rgba32sint":{const g=I(i,L,"32sint",4);return[g[0],g[1],g[2],g[3]]}case"rgba32float":{const g=I(i,L,"32float",4);return[g[0],g[1],g[2],g[3]]}case"rg11b10ufloat":{const g=new Uint32Array(i.buffer,L,1)[0],x=(4192256&g)>>11,v=(4290772992&g)>>22;return[w$1(2047&g),w$1(x),function(i){const g=112+(i>>5&31)<<23|(31&i)<<18;return Fr[0]=g,Hr[0]}(v),1]}}return null}(new Uint8Array(S),i,g,x,v,b,y,_,this.format)}setPixel(i,g,x,v,_){const y=this.texelByteSize,b=this.bytesPerRow,S=this.height,w=this.data[v];!function(i,g,x,v,_,y,b,S,w,L){const k=v*(b>>=_)*(y>>=_)+x*b+g*S;switch(w){case"r8unorm":return void T(i,k,"8unorm",1,L);case"r8snorm":return void T(i,k,"8snorm",1,L);case"r8uint":return void T(i,k,"8uint",1,L);case"r8sint":return void T(i,k,"8sint",1,L);case"rg8unorm":return void T(i,k,"8unorm",2,L);case"rg8snorm":return void T(i,k,"8snorm",2,L);case"rg8uint":return void T(i,k,"8uint",2,L);case"rg8sint":return void T(i,k,"8sint",2,L);case"rgba8unorm-srgb":case"rgba8unorm":case"bgra8unorm-srgb":case"bgra8unorm":return void T(i,k,"8unorm",4,L);case"rgba8snorm":return void T(i,k,"8snorm",4,L);case"rgba8uint":return void T(i,k,"8uint",4,L);case"rgba8sint":return void T(i,k,"8sint",4,L);case"r16uint":return void T(i,k,"16uint",1,L);case"r16sint":return void T(i,k,"16sint",1,L);case"r16float":return void T(i,k,"16float",1,L);case"rg16uint":return void T(i,k,"16uint",2,L);case"rg16sint":return void T(i,k,"16sint",2,L);case"rg16float":return void T(i,k,"16float",2,L);case"rgba16uint":return void T(i,k,"16uint",4,L);case"rgba16sint":return void T(i,k,"16sint",4,L);case"rgba16float":return void T(i,k,"16float",4,L);case"r32uint":return void T(i,k,"32uint",1,L);case"r32sint":return void T(i,k,"32sint",1,L);case"depth16unorm":case"depth24plus":case"depth24plus-stencil8":case"depth32float":case"depth32float-stencil8":case"r32float":return void T(i,k,"32float",1,L);case"rg32uint":return void T(i,k,"32uint",2,L);case"rg32sint":return void T(i,k,"32sint",2,L);case"rg32float":return void T(i,k,"32float",2,L);case"rgba32uint":return void T(i,k,"32uint",4,L);case"rgba32sint":return void T(i,k,"32sint",4,L);case"rgba32float":return void T(i,k,"32float",4,L);case"rg11b10ufloat":console.error("TODO: rg11b10ufloat not supported for writing")}}(new Uint8Array(w),i,g,x,v,S,b,y,this.format,_)}}(i=>{i[i.token=0]="token",i[i.keyword=1]="keyword",i[i.reserved=2]="reserved"})(qr||(qr={}));class qe{constructor(i,g,x){this.name=i,this.type=g,this.rule=x}toString(){return this.name}}class He{}Xr=He,He.none=new qe("",qr.reserved,""),He.eof=new qe("EOF",qr.token,""),He.reserved={asm:new qe("asm",qr.reserved,"asm"),bf16:new qe("bf16",qr.reserved,"bf16"),do:new qe("do",qr.reserved,"do"),enum:new qe("enum",qr.reserved,"enum"),f16:new qe("f16",qr.reserved,"f16"),f64:new qe("f64",qr.reserved,"f64"),handle:new qe("handle",qr.reserved,"handle"),i8:new qe("i8",qr.reserved,"i8"),i16:new qe("i16",qr.reserved,"i16"),i64:new qe("i64",qr.reserved,"i64"),mat:new qe("mat",qr.reserved,"mat"),premerge:new qe("premerge",qr.reserved,"premerge"),regardless:new qe("regardless",qr.reserved,"regardless"),typedef:new qe("typedef",qr.reserved,"typedef"),u8:new qe("u8",qr.reserved,"u8"),u16:new qe("u16",qr.reserved,"u16"),u64:new qe("u64",qr.reserved,"u64"),unless:new qe("unless",qr.reserved,"unless"),using:new qe("using",qr.reserved,"using"),vec:new qe("vec",qr.reserved,"vec"),void:new qe("void",qr.reserved,"void")},He.keywords={array:new qe("array",qr.keyword,"array"),atomic:new qe("atomic",qr.keyword,"atomic"),bool:new qe("bool",qr.keyword,"bool"),f32:new qe("f32",qr.keyword,"f32"),i32:new qe("i32",qr.keyword,"i32"),mat2x2:new qe("mat2x2",qr.keyword,"mat2x2"),mat2x3:new qe("mat2x3",qr.keyword,"mat2x3"),mat2x4:new qe("mat2x4",qr.keyword,"mat2x4"),mat3x2:new qe("mat3x2",qr.keyword,"mat3x2"),mat3x3:new qe("mat3x3",qr.keyword,"mat3x3"),mat3x4:new qe("mat3x4",qr.keyword,"mat3x4"),mat4x2:new qe("mat4x2",qr.keyword,"mat4x2"),mat4x3:new qe("mat4x3",qr.keyword,"mat4x3"),mat4x4:new qe("mat4x4",qr.keyword,"mat4x4"),ptr:new qe("ptr",qr.keyword,"ptr"),sampler:new qe("sampler",qr.keyword,"sampler"),sampler_comparison:new qe("sampler_comparison",qr.keyword,"sampler_comparison"),struct:new qe("struct",qr.keyword,"struct"),texture_1d:new qe("texture_1d",qr.keyword,"texture_1d"),texture_2d:new qe("texture_2d",qr.keyword,"texture_2d"),texture_2d_array:new qe("texture_2d_array",qr.keyword,"texture_2d_array"),texture_3d:new qe("texture_3d",qr.keyword,"texture_3d"),texture_cube:new qe("texture_cube",qr.keyword,"texture_cube"),texture_cube_array:new qe("texture_cube_array",qr.keyword,"texture_cube_array"),texture_multisampled_2d:new qe("texture_multisampled_2d",qr.keyword,"texture_multisampled_2d"),texture_storage_1d:new qe("texture_storage_1d",qr.keyword,"texture_storage_1d"),texture_storage_2d:new qe("texture_storage_2d",qr.keyword,"texture_storage_2d"),texture_storage_2d_array:new qe("texture_storage_2d_array",qr.keyword,"texture_storage_2d_array"),texture_storage_3d:new qe("texture_storage_3d",qr.keyword,"texture_storage_3d"),texture_depth_2d:new qe("texture_depth_2d",qr.keyword,"texture_depth_2d"),texture_depth_2d_array:new qe("texture_depth_2d_array",qr.keyword,"texture_depth_2d_array"),texture_depth_cube:new qe("texture_depth_cube",qr.keyword,"texture_depth_cube"),texture_depth_cube_array:new qe("texture_depth_cube_array",qr.keyword,"texture_depth_cube_array"),texture_depth_multisampled_2d:new qe("texture_depth_multisampled_2d",qr.keyword,"texture_depth_multisampled_2d"),texture_external:new qe("texture_external",qr.keyword,"texture_external"),u32:new qe("u32",qr.keyword,"u32"),vec2:new qe("vec2",qr.keyword,"vec2"),vec3:new qe("vec3",qr.keyword,"vec3"),vec4:new qe("vec4",qr.keyword,"vec4"),bitcast:new qe("bitcast",qr.keyword,"bitcast"),block:new qe("block",qr.keyword,"block"),break:new qe("break",qr.keyword,"break"),case:new qe("case",qr.keyword,"case"),continue:new qe("continue",qr.keyword,"continue"),continuing:new qe("continuing",qr.keyword,"continuing"),default:new qe("default",qr.keyword,"default"),diagnostic:new qe("diagnostic",qr.keyword,"diagnostic"),discard:new qe("discard",qr.keyword,"discard"),else:new qe("else",qr.keyword,"else"),enable:new qe("enable",qr.keyword,"enable"),fallthrough:new qe("fallthrough",qr.keyword,"fallthrough"),false:new qe("false",qr.keyword,"false"),fn:new qe("fn",qr.keyword,"fn"),for:new qe("for",qr.keyword,"for"),function:new qe("function",qr.keyword,"function"),if:new qe("if",qr.keyword,"if"),let:new qe("let",qr.keyword,"let"),const:new qe("const",qr.keyword,"const"),loop:new qe("loop",qr.keyword,"loop"),while:new qe("while",qr.keyword,"while"),private:new qe("private",qr.keyword,"private"),read:new qe("read",qr.keyword,"read"),read_write:new qe("read_write",qr.keyword,"read_write"),return:new qe("return",qr.keyword,"return"),requires:new qe("requires",qr.keyword,"requires"),storage:new qe("storage",qr.keyword,"storage"),switch:new qe("switch",qr.keyword,"switch"),true:new qe("true",qr.keyword,"true"),alias:new qe("alias",qr.keyword,"alias"),type:new qe("type",qr.keyword,"type"),uniform:new qe("uniform",qr.keyword,"uniform"),var:new qe("var",qr.keyword,"var"),override:new qe("override",qr.keyword,"override"),workgroup:new qe("workgroup",qr.keyword,"workgroup"),write:new qe("write",qr.keyword,"write"),r8unorm:new qe("r8unorm",qr.keyword,"r8unorm"),r8snorm:new qe("r8snorm",qr.keyword,"r8snorm"),r8uint:new qe("r8uint",qr.keyword,"r8uint"),r8sint:new qe("r8sint",qr.keyword,"r8sint"),r16uint:new qe("r16uint",qr.keyword,"r16uint"),r16sint:new qe("r16sint",qr.keyword,"r16sint"),r16float:new qe("r16float",qr.keyword,"r16float"),rg8unorm:new qe("rg8unorm",qr.keyword,"rg8unorm"),rg8snorm:new qe("rg8snorm",qr.keyword,"rg8snorm"),rg8uint:new qe("rg8uint",qr.keyword,"rg8uint"),rg8sint:new qe("rg8sint",qr.keyword,"rg8sint"),r32uint:new qe("r32uint",qr.keyword,"r32uint"),r32sint:new qe("r32sint",qr.keyword,"r32sint"),r32float:new qe("r32float",qr.keyword,"r32float"),rg16uint:new qe("rg16uint",qr.keyword,"rg16uint"),rg16sint:new qe("rg16sint",qr.keyword,"rg16sint"),rg16float:new qe("rg16float",qr.keyword,"rg16float"),rgba8unorm:new qe("rgba8unorm",qr.keyword,"rgba8unorm"),rgba8unorm_srgb:new qe("rgba8unorm_srgb",qr.keyword,"rgba8unorm_srgb"),rgba8snorm:new qe("rgba8snorm",qr.keyword,"rgba8snorm"),rgba8uint:new qe("rgba8uint",qr.keyword,"rgba8uint"),rgba8sint:new qe("rgba8sint",qr.keyword,"rgba8sint"),bgra8unorm:new qe("bgra8unorm",qr.keyword,"bgra8unorm"),bgra8unorm_srgb:new qe("bgra8unorm_srgb",qr.keyword,"bgra8unorm_srgb"),rgb10a2unorm:new qe("rgb10a2unorm",qr.keyword,"rgb10a2unorm"),rg11b10float:new qe("rg11b10float",qr.keyword,"rg11b10float"),rg32uint:new qe("rg32uint",qr.keyword,"rg32uint"),rg32sint:new qe("rg32sint",qr.keyword,"rg32sint"),rg32float:new qe("rg32float",qr.keyword,"rg32float"),rgba16uint:new qe("rgba16uint",qr.keyword,"rgba16uint"),rgba16sint:new qe("rgba16sint",qr.keyword,"rgba16sint"),rgba16float:new qe("rgba16float",qr.keyword,"rgba16float"),rgba32uint:new qe("rgba32uint",qr.keyword,"rgba32uint"),rgba32sint:new qe("rgba32sint",qr.keyword,"rgba32sint"),rgba32float:new qe("rgba32float",qr.keyword,"rgba32float"),static_assert:new qe("static_assert",qr.keyword,"static_assert")},He.tokens={decimal_float_literal:new qe("decimal_float_literal",qr.token,/((-?[0-9]*\.[0-9]+|-?[0-9]+\.[0-9]*)((e|E)(\+|-)?[0-9]+)?[fh]?)|(-?[0-9]+(e|E)(\+|-)?[0-9]+[fh]?)|(-?[0-9]+[fh])/),hex_float_literal:new qe("hex_float_literal",qr.token,/-?0x((([0-9a-fA-F]*\.[0-9a-fA-F]+|[0-9a-fA-F]+\.[0-9a-fA-F]*)((p|P)(\+|-)?[0-9]+[fh]?)?)|([0-9a-fA-F]+(p|P)(\+|-)?[0-9]+[fh]?))/),int_literal:new qe("int_literal",qr.token,/-?0x[0-9a-fA-F]+|0i?|-?[1-9][0-9]*i?/),uint_literal:new qe("uint_literal",qr.token,/0x[0-9a-fA-F]+u|0u|[1-9][0-9]*u/),name:new qe("name",qr.token,/([_\p{XID_Start}][\p{XID_Continue}]+)|([\p{XID_Start}])/u),ident:new qe("ident",qr.token,/[_a-zA-Z][0-9a-zA-Z_]*/),and:new qe("and",qr.token,"&"),and_and:new qe("and_and",qr.token,"&&"),arrow:new qe("arrow ",qr.token,"->"),attr:new qe("attr",qr.token,"@"),forward_slash:new qe("forward_slash",qr.token,"/"),bang:new qe("bang",qr.token,"!"),bracket_left:new qe("bracket_left",qr.token,"["),bracket_right:new qe("bracket_right",qr.token,"]"),brace_left:new qe("brace_left",qr.token,"{"),brace_right:new qe("brace_right",qr.token,"}"),colon:new qe("colon",qr.token,":"),comma:new qe("comma",qr.token,","),equal:new qe("equal",qr.token,"="),equal_equal:new qe("equal_equal",qr.token,"=="),not_equal:new qe("not_equal",qr.token,"!="),greater_than:new qe("greater_than",qr.token,">"),greater_than_equal:new qe("greater_than_equal",qr.token,">="),shift_right:new qe("shift_right",qr.token,">>"),less_than:new qe("less_than",qr.token,"<"),less_than_equal:new qe("less_than_equal",qr.token,"<="),shift_left:new qe("shift_left",qr.token,"<<"),modulo:new qe("modulo",qr.token,"%"),minus:new qe("minus",qr.token,"-"),minus_minus:new qe("minus_minus",qr.token,"--"),period:new qe("period",qr.token,"."),plus:new qe("plus",qr.token,"+"),plus_plus:new qe("plus_plus",qr.token,"++"),or:new qe("or",qr.token,"|"),or_or:new qe("or_or",qr.token,"||"),paren_left:new qe("paren_left",qr.token,"("),paren_right:new qe("paren_right",qr.token,")"),semicolon:new qe("semicolon",qr.token,";"),star:new qe("star",qr.token,"*"),tilde:new qe("tilde",qr.token,"~"),underscore:new qe("underscore",qr.token,"_"),xor:new qe("xor",qr.token,"^"),plus_equal:new qe("plus_equal",qr.token,"+="),minus_equal:new qe("minus_equal",qr.token,"-="),times_equal:new qe("times_equal",qr.token,"*="),division_equal:new qe("division_equal",qr.token,"/="),modulo_equal:new qe("modulo_equal",qr.token,"%="),and_equal:new qe("and_equal",qr.token,"&="),or_equal:new qe("or_equal",qr.token,"|="),xor_equal:new qe("xor_equal",qr.token,"^="),shift_right_equal:new qe("shift_right_equal",qr.token,">>="),shift_left_equal:new qe("shift_left_equal",qr.token,"<<=")},He.simpleTokens={"@":Xr.tokens.attr,"{":Xr.tokens.brace_left,"}":Xr.tokens.brace_right,":":Xr.tokens.colon,",":Xr.tokens.comma,"(":Xr.tokens.paren_left,")":Xr.tokens.paren_right,";":Xr.tokens.semicolon},He.literalTokens={"&":Xr.tokens.and,"&&":Xr.tokens.and_and,"->":Xr.tokens.arrow,"/":Xr.tokens.forward_slash,"!":Xr.tokens.bang,"[":Xr.tokens.bracket_left,"]":Xr.tokens.bracket_right,"=":Xr.tokens.equal,"==":Xr.tokens.equal_equal,"!=":Xr.tokens.not_equal,">":Xr.tokens.greater_than,">=":Xr.tokens.greater_than_equal,">>":Xr.tokens.shift_right,"<":Xr.tokens.less_than,"<=":Xr.tokens.less_than_equal,"<<":Xr.tokens.shift_left,"%":Xr.tokens.modulo,"-":Xr.tokens.minus,"--":Xr.tokens.minus_minus,".":Xr.tokens.period,"+":Xr.tokens.plus,"++":Xr.tokens.plus_plus,"|":Xr.tokens.or,"||":Xr.tokens.or_or,"*":Xr.tokens.star,"~":Xr.tokens.tilde,_:Xr.tokens.underscore,"^":Xr.tokens.xor,"+=":Xr.tokens.plus_equal,"-=":Xr.tokens.minus_equal,"*=":Xr.tokens.times_equal,"/=":Xr.tokens.division_equal,"%=":Xr.tokens.modulo_equal,"&=":Xr.tokens.and_equal,"|=":Xr.tokens.or_equal,"^=":Xr.tokens.xor_equal,">>=":Xr.tokens.shift_right_equal,"<<=":Xr.tokens.shift_left_equal},He.regexTokens={decimal_float_literal:Xr.tokens.decimal_float_literal,hex_float_literal:Xr.tokens.hex_float_literal,int_literal:Xr.tokens.int_literal,uint_literal:Xr.tokens.uint_literal,ident:Xr.tokens.ident},He.storage_class=[Xr.keywords.function,Xr.keywords.private,Xr.keywords.workgroup,Xr.keywords.uniform,Xr.keywords.storage],He.access_mode=[Xr.keywords.read,Xr.keywords.write,Xr.keywords.read_write],He.sampler_type=[Xr.keywords.sampler,Xr.keywords.sampler_comparison],He.sampled_texture_type=[Xr.keywords.texture_1d,Xr.keywords.texture_2d,Xr.keywords.texture_2d_array,Xr.keywords.texture_3d,Xr.keywords.texture_cube,Xr.keywords.texture_cube_array],He.multisampled_texture_type=[Xr.keywords.texture_multisampled_2d],He.storage_texture_type=[Xr.keywords.texture_storage_1d,Xr.keywords.texture_storage_2d,Xr.keywords.texture_storage_2d_array,Xr.keywords.texture_storage_3d],He.depth_texture_type=[Xr.keywords.texture_depth_2d,Xr.keywords.texture_depth_2d_array,Xr.keywords.texture_depth_cube,Xr.keywords.texture_depth_cube_array,Xr.keywords.texture_depth_multisampled_2d],He.texture_external_type=[Xr.keywords.texture_external],He.any_texture_type=[...Xr.sampled_texture_type,...Xr.multisampled_texture_type,...Xr.storage_texture_type,...Xr.depth_texture_type,...Xr.texture_external_type],He.texel_format=[Xr.keywords.r8unorm,Xr.keywords.r8snorm,Xr.keywords.r8uint,Xr.keywords.r8sint,Xr.keywords.r16uint,Xr.keywords.r16sint,Xr.keywords.r16float,Xr.keywords.rg8unorm,Xr.keywords.rg8snorm,Xr.keywords.rg8uint,Xr.keywords.rg8sint,Xr.keywords.r32uint,Xr.keywords.r32sint,Xr.keywords.r32float,Xr.keywords.rg16uint,Xr.keywords.rg16sint,Xr.keywords.rg16float,Xr.keywords.rgba8unorm,Xr.keywords.rgba8unorm_srgb,Xr.keywords.rgba8snorm,Xr.keywords.rgba8uint,Xr.keywords.rgba8sint,Xr.keywords.bgra8unorm,Xr.keywords.bgra8unorm_srgb,Xr.keywords.rgb10a2unorm,Xr.keywords.rg11b10float,Xr.keywords.rg32uint,Xr.keywords.rg32sint,Xr.keywords.rg32float,Xr.keywords.rgba16uint,Xr.keywords.rgba16sint,Xr.keywords.rgba16float,Xr.keywords.rgba32uint,Xr.keywords.rgba32sint,Xr.keywords.rgba32float],He.const_literal=[Xr.tokens.int_literal,Xr.tokens.uint_literal,Xr.tokens.decimal_float_literal,Xr.tokens.hex_float_literal,Xr.keywords.true,Xr.keywords.false],He.literal_or_ident=[Xr.tokens.ident,Xr.tokens.int_literal,Xr.tokens.uint_literal,Xr.tokens.decimal_float_literal,Xr.tokens.hex_float_literal,Xr.tokens.name],He.element_count_expression=[Xr.tokens.int_literal,Xr.tokens.uint_literal,Xr.tokens.ident],He.template_types=[Xr.keywords.vec2,Xr.keywords.vec3,Xr.keywords.vec4,Xr.keywords.mat2x2,Xr.keywords.mat2x3,Xr.keywords.mat2x4,Xr.keywords.mat3x2,Xr.keywords.mat3x3,Xr.keywords.mat3x4,Xr.keywords.mat4x2,Xr.keywords.mat4x3,Xr.keywords.mat4x4,Xr.keywords.atomic,Xr.keywords.bitcast,...Xr.any_texture_type],He.attribute_name=[Xr.tokens.ident,Xr.keywords.block,Xr.keywords.diagnostic],He.assignment_operators=[Xr.tokens.equal,Xr.tokens.plus_equal,Xr.tokens.minus_equal,Xr.tokens.times_equal,Xr.tokens.division_equal,Xr.tokens.modulo_equal,Xr.tokens.and_equal,Xr.tokens.or_equal,Xr.tokens.xor_equal,Xr.tokens.shift_right_equal,Xr.tokens.shift_left_equal],He.increment_operators=[Xr.tokens.plus_plus,Xr.tokens.minus_minus];class ze{constructor(i,g,x,v,_){this.type=i,this.lexeme=g,this.line=x,this.start=v,this.end=_}toString(){return this.lexeme}isTemplateType(){return-1!=He.template_types.indexOf(this.type)}isArrayType(){return this.type==He.keywords.array}isArrayOrTemplateType(){return this.isArrayType()||this.isTemplateType()}}class Re{constructor(i){this._tokens=[],this._start=0,this._current=0,this._line=1,this._source=null!=i?i:""}scanTokens(){for(;!this._isAtEnd();)if(this._start=this._current,!this.scanToken())throw`Invalid syntax at line ${this._line}`;return this._tokens.push(new ze(He.eof,"",this._line,this._current,this._current)),this._tokens}scanToken(){let i=this._advance();if("\n"==i)return this._line++,!0;if(this._isWhitespace(i))return!0;if("/"==i){if("/"==this._peekAhead()){for(;"\n"!=i;){if(this._isAtEnd())return!0;i=this._advance()}return this._line++,!0}if("*"==this._peekAhead()){this._advance();let g=1;for(;g>0;){if(this._isAtEnd())return!0;if(i=this._advance(),"\n"==i)this._line++;else if("*"==i){if("/"==this._peekAhead()&&(this._advance(),g--,0==g))return!0}else"/"==i&&"*"==this._peekAhead()&&(this._advance(),g++)}return!0}}const g=He.simpleTokens[i];if(g)return this._addToken(g),!0;let x=He.none;const v=this._isAlpha(i),_="_"===i;if(this._isAlphaNumeric(i)){let g=this._peekAhead();for(;this._isAlphaNumeric(g);)i+=this._advance(),g=this._peekAhead()}if(v){const g=He.keywords[i];if(g)return this._addToken(g),!0}if(v||_)return this._addToken(He.tokens.ident),!0;for(;;){let g=this._findType(i);const v=this._peekAhead();if("-"==i&&this._tokens.length>0){if("="==v)return this._current++,i+=v,this._addToken(He.tokens.minus_equal),!0;if("-"==v)return this._current++,i+=v,this._addToken(He.tokens.minus_minus),!0;const x=this._tokens.length-1;if((-1!=He.literal_or_ident.indexOf(this._tokens[x].type)||this._tokens[x].type==He.tokens.paren_right)&&">"!=v)return this._addToken(g),!0}if(">"==i&&(">"==v||"="==v)){let i=!1,x=this._tokens.length-1;for(let g=0;g<5&&x>=0&&-1===He.assignment_operators.indexOf(this._tokens[x].type);++g,--x)if(this._tokens[x].type===He.tokens.less_than){x>0&&this._tokens[x-1].isArrayOrTemplateType()&&(i=!0);break}if(i)return this._addToken(g),!0}if(g===He.none){let v=i,_=0;const y=2;for(let i=0;i=this._source.length}_isAlpha(i){return!this._isNumeric(i)&&!this._isWhitespace(i)&&"_"!==i&&"."!==i&&"("!==i&&")"!==i&&"["!==i&&"]"!==i&&"{"!==i&&"}"!==i&&","!==i&&";"!==i&&":"!==i&&"="!==i&&"!"!==i&&"<"!==i&&">"!==i&&"+"!==i&&"-"!==i&&"*"!==i&&"/"!==i&&"%"!==i&&"&"!==i&&"|"!==i&&"^"!==i&&"~"!==i&&"@"!==i&&"#"!==i&&"?"!==i&&"'"!==i&&"`"!==i&&'"'!==i&&"\\"!==i&&"\n"!==i&&"\r"!==i&&"\t"!==i&&"\0"!==i}_isNumeric(i){return i>="0"&&i<="9"}_isAlphaNumeric(i){return this._isAlpha(i)||this._isNumeric(i)||"_"===i}_isWhitespace(i){return" "==i||"\t"==i||"\r"==i}_advance(i=0){let g=this._source[this._current];return i=i||0,i++,this._current+=i,g}_peekAhead(i=0){return i=i||0,this._current+i>=this._source.length?"\0":this._source[this._current+i]}_addToken(i){const g=this._source.substring(this._start,this._current);this._tokens.push(new ze(i,g,this._line,this._start,this._current))}}function Ge(i){return Array.isArray(i)||(null==i?void 0:i.buffer)instanceof ArrayBuffer}const Yr=new Float32Array(1),Wr=new Uint32Array(Yr.buffer),Zr=new Uint32Array(Yr.buffer),Jr=new Int32Array(1),Qr=new Float32Array(Jr.buffer),ei=new Uint32Array(Jr.buffer),ti=new Uint32Array(1),ri=new Float32Array(ti.buffer),ii=new Int32Array(ti.buffer);function nt(i,g,x){if(g===x)return i;if("f32"===g){if("i32"===x||"x32"===x)return Yr[0]=i,Wr[0];if("u32"===x)return Yr[0]=i,Zr[0]}else if("i32"===g||"x32"===g){if("f32"===x)return Jr[0]=i,Qr[0];if("u32"===x)return Jr[0]=i,ei[0]}else if("u32"===g){if("f32"===x)return ti[0]=i,ri[0];if("i32"===x||"x32"===x)return ti[0]=i,ii[0]}return console.error(`Unsupported cast from ${g} to ${x}`),i}class st{constructor(i){this.resources=null,this.inUse=!1,this.info=null,this.node=i}}class rt{constructor(i,g){this.align=i,this.size=g}}class at{constructor(){this.uniforms=[],this.storage=[],this.textures=[],this.samplers=[],this.aliases=[],this.overrides=[],this.structs=[],this.entry=new d,this.functions=[],this._types=new Map,this._functions=new Map}_isStorageTexture(i){return"texture_storage_1d"==i.name||"texture_storage_2d"==i.name||"texture_storage_2d_array"==i.name||"texture_storage_3d"==i.name}updateAST(i){for(const g of i)g instanceof D&&this._functions.set(g.name,new st(g));for(const g of i)if(g instanceof oe){const i=this.getTypeInfo(g,null);i instanceof n&&this.structs.push(i)}for(const g of i)if(g instanceof te)this.aliases.push(this._getAliasInfo(g));else{if(g instanceof M){const i=g,x=this._getAttributeNum(i.attributes,"id",0),v=null!=i.type?this.getTypeInfo(i.type,i.attributes):null;this.overrides.push(new h(i.name,v,i.attributes,x));continue}if(this._isUniformVar(g)){const i=g,x=this._getAttributeNum(i.attributes,"group",0),v=this._getAttributeNum(i.attributes,"binding",0),_=this.getTypeInfo(i.type,i.attributes),y=new o(i.name,_,x,v,i.attributes,Gr.Uniform,i.access);y.access||(y.access="read"),this.uniforms.push(y);continue}if(this._isStorageVar(g)){const i=g,x=this._getAttributeNum(i.attributes,"group",0),v=this._getAttributeNum(i.attributes,"binding",0),_=this.getTypeInfo(i.type,i.attributes),y=this._isStorageTexture(_),b=new o(i.name,_,x,v,i.attributes,y?Gr.StorageTexture:Gr.Storage,i.access);b.access||(b.access="read"),this.storage.push(b);continue}if(this._isTextureVar(g)){const i=g,x=this._getAttributeNum(i.attributes,"group",0),v=this._getAttributeNum(i.attributes,"binding",0),_=this.getTypeInfo(i.type,i.attributes),y=this._isStorageTexture(_),b=new o(i.name,_,x,v,i.attributes,y?Gr.StorageTexture:Gr.Texture,i.access);b.access||(b.access="read"),y?this.storage.push(b):this.textures.push(b);continue}if(this._isSamplerVar(g)){const i=g,x=this._getAttributeNum(i.attributes,"group",0),v=this._getAttributeNum(i.attributes,"binding",0),_=this.getTypeInfo(i.type,i.attributes),y=new o(i.name,_,x,v,i.attributes,Gr.Sampler,i.access);this.samplers.push(y);continue}}for(const g of i)if(g instanceof D){const i=this._getAttribute(g,"vertex"),x=this._getAttribute(g,"fragment"),v=this._getAttribute(g,"compute"),_=i||x||v,y=new p(g.name,null==_?void 0:_.name,g.attributes);y.attributes=g.attributes,y.startLine=g.startLine,y.endLine=g.endLine,this.functions.push(y),this._functions.get(g.name).info=y,_&&(this._functions.get(g.name).inUse=!0,y.inUse=!0,y.resources=this._findResources(g,!!_),y.inputs=this._getInputs(g.args),y.outputs=this._getOutputs(g.returnType),this.entry[_.name].push(y)),y.arguments=g.args.map(i=>new f(i.name,this.getTypeInfo(i.type,i.attributes),i.attributes)),y.returnType=g.returnType?this.getTypeInfo(g.returnType,g.attributes):null;continue}for(const i of this._functions.values())i.info&&(i.info.inUse=i.inUse,this._addCalls(i.node,i.info.calls));for(const i of this._functions.values())i.node.search(g=>{var x,v,_;if(g instanceof De){if(g.value)if(Ge(g.value))for(const v of g.value)for(const g of this.overrides)v===g.name&&(null===(x=i.info)||void 0===x||x.overrides.push(g));else for(const x of this.overrides)g.value===x.name&&(null===(v=i.info)||void 0===v||v.overrides.push(x))}else if(g instanceof ge)for(const x of this.overrides)g.name===x.name&&(null===(_=i.info)||void 0===_||_.overrides.push(x))});for(const i of this.uniforms)this._markStructsInUse(i.type);for(const i of this.storage)this._markStructsInUse(i.type)}getFunctionInfo(i){for(const g of this.functions)if(g.name==i)return g;return null}getStructInfo(i){for(const g of this.structs)if(g.name==i)return g;return null}getOverrideInfo(i){for(const g of this.overrides)if(g.name==i)return g;return null}_markStructsInUse(i){if(i)if(i.isStruct){if(i.inUse=!0,i.members)for(const g of i.members)this._markStructsInUse(g.type)}else if(i.isArray)this._markStructsInUse(i.format);else if(i.isTemplate)i.format&&this._markStructsInUse(i.format);else{const g=this._getAlias(i.name);g&&this._markStructsInUse(g)}}_addCalls(i,g){var x;for(const v of i.calls){const i=null===(x=this._functions.get(v.name))||void 0===x?void 0:x.info;i&&g.add(i)}}findResource(i,g,x){if(x){for(const v of this.entry.compute)if(v.name===x)for(const x of v.resources)if(x.group==i&&x.binding==g)return x;for(const v of this.entry.vertex)if(v.name===x)for(const x of v.resources)if(x.group==i&&x.binding==g)return x;for(const v of this.entry.fragment)if(v.name===x)for(const x of v.resources)if(x.group==i&&x.binding==g)return x}for(const x of this.uniforms)if(x.group==i&&x.binding==g)return x;for(const x of this.storage)if(x.group==i&&x.binding==g)return x;for(const x of this.textures)if(x.group==i&&x.binding==g)return x;for(const x of this.samplers)if(x.group==i&&x.binding==g)return x;return null}_findResource(i){for(const g of this.uniforms)if(g.name==i)return g;for(const g of this.storage)if(g.name==i)return g;for(const g of this.textures)if(g.name==i)return g;for(const g of this.samplers)if(g.name==i)return g;return null}_markStructsFromAST(i){const g=this.getTypeInfo(i,null);this._markStructsInUse(g)}_findResources(i,g){const x=[],v=this,_=[];return i.search(y=>{if(y instanceof E)_.push({});else if(y instanceof $)_.pop();else if(y instanceof F){const i=y;g&&null!==i.type&&this._markStructsFromAST(i.type),_.length>0&&(_[_.length-1][i.name]=i)}else if(y instanceof de){const i=y;g&&null!==i.type&&this._markStructsFromAST(i.type)}else if(y instanceof U){const i=y;g&&null!==i.type&&this._markStructsFromAST(i.type),_.length>0&&(_[_.length-1][i.name]=i)}else if(y instanceof ge){const i=y;if(_.length>0&&_[_.length-1][i.name])return;const g=v._findResource(i.name);g&&x.push(g)}else if(y instanceof me){const _=y,b=v._functions.get(_.name);b&&(g&&(b.inUse=!0),i.calls.add(b.node),null===b.resources&&(b.resources=v._findResources(b.node,g)),x.push(...b.resources))}else if(y instanceof X){const _=y,b=v._functions.get(_.name);b&&(g&&(b.inUse=!0),i.calls.add(b.node),null===b.resources&&(b.resources=v._findResources(b.node,g)),x.push(...b.resources))}}),[...new Map(x.map(i=>[i.name,i])).values()]}getBindGroups(){const i=[];function t(g,x){g>=i.length&&(i.length=g+1),void 0===i[g]&&(i[g]=[]),x>=i[g].length&&(i[g].length=x+1)}for(const g of this.uniforms)t(g.group,g.binding),i[g.group][g.binding]=g;for(const g of this.storage)t(g.group,g.binding),i[g.group][g.binding]=g;for(const g of this.textures)t(g.group,g.binding),i[g.group][g.binding]=g;for(const g of this.samplers)t(g.group,g.binding),i[g.group][g.binding]=g;return i}_getOutputs(i,g=void 0){if(void 0===g&&(g=[]),i instanceof oe)this._getStructOutputs(i,g);else{const x=this._getOutputInfo(i);null!==x&&g.push(x)}return g}_getStructOutputs(i,g){for(const x of i.members)if(x.type instanceof oe)this._getStructOutputs(x.type,g);else{const i=this._getAttribute(x,"location")||this._getAttribute(x,"builtin");if(null!==i){const v=this.getTypeInfo(x.type,x.type.attributes),_=this._parseInt(i.value),y=new u(x.name,v,i.name,_);g.push(y)}}}_getOutputInfo(i){const g=this._getAttribute(i,"location")||this._getAttribute(i,"builtin");if(null!==g){const x=this.getTypeInfo(i,i.attributes),v=this._parseInt(g.value);return new u("",x,g.name,v)}return null}_getInputs(i,g=void 0){void 0===g&&(g=[]);for(const x of i)if(x.type instanceof oe)this._getStructInputs(x.type,g);else{const i=this._getInputInfo(x);null!==i&&g.push(i)}return g}_getStructInputs(i,g){for(const x of i.members)if(x.type instanceof oe)this._getStructInputs(x.type,g);else{const i=this._getInputInfo(x);null!==i&&g.push(i)}}_getInputInfo(i){const g=this._getAttribute(i,"location")||this._getAttribute(i,"builtin");if(null!==g){const x=this._getAttribute(i,"interpolation"),v=this.getTypeInfo(i.type,i.attributes),_=this._parseInt(g.value),y=new l(i.name,v,g.name,_);return null!==x&&(y.interpolation=this._parseString(x.value)),y}return null}_parseString(i){return i instanceof Array&&(i=i[0]),i}_parseInt(i){i instanceof Array&&(i=i[0]);const g=parseInt(i);return isNaN(g)?i:g}_getAlias(i){for(const g of this.aliases)if(g.name==i)return g.type;return null}_getAliasInfo(i){return new c(i.name,this.getTypeInfo(i.type,null))}getTypeInfoByName(i){for(const g of this.structs)if(g.name==i)return g;for(const g of this.aliases)if(g.name==i)return g.type;return null}getTypeInfo(i,g=null){if(this._types.has(i))return this._types.get(i);if(i instanceof le){const x=i.type?this.getTypeInfo(i.type,i.attributes):null,v=new r(i.name,x,g);return this._types.set(i,v),this._updateTypeInfo(v),v}if(i instanceof ue){const x=i,v=x.format?this.getTypeInfo(x.format,x.attributes):null,_=new s(x.name,g);return _.format=v,_.count=x.count,this._types.set(i,_),this._updateTypeInfo(_),_}if(i instanceof oe){const x=i,v=new n(x.name,g);v.startLine=x.startLine,v.endLine=x.endLine;for(const i of x.members){const g=this.getTypeInfo(i.type,i.attributes);v.members.push(new t(i.name,g,i.attributes))}return this._types.set(i,v),this._updateTypeInfo(v),v}if(i instanceof he){const x=i,v=x.format instanceof ae,_=x.format?v?this.getTypeInfo(x.format,null):new e(x.format,null):null,y=new a(x.name,_,g,x.access);return this._types.set(i,y),this._updateTypeInfo(y),y}if(i instanceof ce){const x=i,v=x.format?this.getTypeInfo(x.format,null):null,_=new a(x.name,v,g,x.access);return this._types.set(i,_),this._updateTypeInfo(_),_}const x=new e(i.name,g);return this._types.set(i,x),this._updateTypeInfo(x),x}_updateTypeInfo(i){var g,x,v;const _=this._getTypeSize(i);if(i.size=null!==(g=null==_?void 0:_.size)&&void 0!==g?g:0,i instanceof s&&i.format){const g=this._getTypeSize(i.format);i.stride=Math.max(null!==(x=null==g?void 0:g.size)&&void 0!==x?x:0,null!==(v=null==g?void 0:g.align)&&void 0!==v?v:0),this._updateTypeInfo(i.format)}i instanceof r&&this._updateTypeInfo(i.format),i instanceof n&&this._updateStructInfo(i)}_updateStructInfo(i){var g;let x=0,v=0,_=0,y=0;for(let b=0,S=i.members.length;bi.name),at._samplerTypes=He.sampler_type.map(i=>i.name);let ni=0;class ot{constructor(i,g,x){this.id=ni++,this.name=i,this.value=g,this.node=x}clone(){return new ot(this.name,this.value,this.node)}}class ct{constructor(i){this.id=ni++,this.name=i.name,this.node=i}clone(){return new ct(this.node)}}class lt{constructor(i){this.parent=null,this.variables=new Map,this.functions=new Map,this.currentFunctionName="",this.id=ni++,i&&(this.parent=i,this.currentFunctionName=i.currentFunctionName)}getVariable(i){var g;return this.variables.has(i)?null!==(g=this.variables.get(i))&&void 0!==g?g:null:this.parent?this.parent.getVariable(i):null}getFunction(i){var g;return this.functions.has(i)?null!==(g=this.functions.get(i))&&void 0!==g?g:null:this.parent?this.parent.getFunction(i):null}createVariable(i,g,x){this.variables.set(i,new ot(i,g,null!=x?x:null))}setVariable(i,g,x){const v=this.getVariable(i);null!==v?v.value=g:this.createVariable(i,g,x)}getVariableValue(i){var g;const x=this.getVariable(i);return null!==(g=null==x?void 0:x.value)&&void 0!==g?g:null}clone(){return new lt(this)}}class ut{evalExpression(i,g){return null}getTypeInfo(i){return null}getVariableName(i,g){return""}}class ht{constructor(i){this.exec=i}getTypeInfo(i){return this.exec.getTypeInfo(i)}All(i,g){const x=this.exec.evalExpression(i.args[0],g);let v=!0;if(x instanceof Me)return x.data.forEach(i=>{i||(v=!1)}),new Be(v?1:0,this.getTypeInfo("bool"));throw new Error(`All() expects a vector argument. Line ${i.line}`)}Any(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me){const i=x.data.some(i=>i);return new Be(i?1:0,this.getTypeInfo("bool"))}throw new Error(`Any() expects a vector argument. Line ${i.line}`)}Select(i,g){const x=this.exec.evalExpression(i.args[2],g);if(!(x instanceof Be))throw new Error(`Select() expects a bool condition. Line ${i.line}`);return x.value?this.exec.evalExpression(i.args[1],g):this.exec.evalExpression(i.args[0],g)}ArrayLength(i,g){let x=i.args[0];x instanceof ke&&(x=x.right);const v=this.exec.evalExpression(x,g);if(v instanceof Pe&&0===v.typeInfo.size){const i=v.typeInfo,g=v.buffer.byteLength/i.stride;return new Be(g,this.getTypeInfo("u32"))}return new Be(v.typeInfo.size,this.getTypeInfo("u32"))}Abs(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.abs(i)),x.typeInfo);const v=x;return new Be(Math.abs(v.value),v.typeInfo)}Acos(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.acos(i)),x.typeInfo);const v=x;return new Be(Math.acos(v.value),x.typeInfo)}Acosh(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.acosh(i)),x.typeInfo);const v=x;return new Be(Math.acosh(v.value),x.typeInfo)}Asin(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.asin(i)),x.typeInfo);const v=x;return new Be(Math.asin(v.value),x.typeInfo)}Asinh(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.asinh(i)),x.typeInfo);const v=x;return new Be(Math.asinh(v.value),x.typeInfo)}Atan(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.atan(i)),x.typeInfo);const v=x;return new Be(Math.atan(v.value),x.typeInfo)}Atanh(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.atanh(i)),x.typeInfo);const v=x;return new Be(Math.atanh(v.value),x.typeInfo)}Atan2(i,g){const x=this.exec.evalExpression(i.args[0],g),v=this.exec.evalExpression(i.args[1],g);if(x instanceof Me&&v instanceof Me)return new Me(x.data.map((i,g)=>Math.atan2(i,v.data[g])),x.typeInfo);const _=x,y=v;return new Be(Math.atan2(_.value,y.value),x.typeInfo)}Ceil(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.ceil(i)),x.typeInfo);const v=x;return new Be(Math.ceil(v.value),x.typeInfo)}_clamp(i,g,x){return Math.min(Math.max(i,g),x)}Clamp(i,g){const x=this.exec.evalExpression(i.args[0],g),v=this.exec.evalExpression(i.args[1],g),_=this.exec.evalExpression(i.args[2],g);if(x instanceof Me&&v instanceof Me&&_ instanceof Me)return new Me(x.data.map((i,g)=>this._clamp(i,v.data[g],_.data[g])),x.typeInfo);const y=x,b=v,S=_;return new Be(this._clamp(y.value,b.value,S.value),x.typeInfo)}Cos(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.cos(i)),x.typeInfo);const v=x;return new Be(Math.cos(v.value),x.typeInfo)}Cosh(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.cosh(i)),x.typeInfo);const v=x;return new Be(Math.cos(v.value),x.typeInfo)}CountLeadingZeros(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.clz32(i)),x.typeInfo);const v=x;return new Be(Math.clz32(v.value),x.typeInfo)}_countOneBits(i){let g=0;for(;0!==i;)1&i&&g++,i>>=1;return g}CountOneBits(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>this._countOneBits(i)),x.typeInfo);const v=x;return new Be(this._countOneBits(v.value),x.typeInfo)}_countTrailingZeros(i){if(0===i)return 32;let g=0;for(;!(1&i);)i>>=1,g++;return g}CountTrailingZeros(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>this._countTrailingZeros(i)),x.typeInfo);const v=x;return new Be(this._countTrailingZeros(v.value),x.typeInfo)}Cross(i,g){const x=this.exec.evalExpression(i.args[0],g),v=this.exec.evalExpression(i.args[1],g);if(x instanceof Me&&v instanceof Me){if(3!==x.data.length||3!==v.data.length)return console.error(`Cross() expects 3D vectors. Line ${i.line}`),null;const g=x.data,_=v.data;return new Me([g[1]*_[2]-_[1]*g[2],g[2]*_[0]-_[2]*g[0],g[0]*_[1]-_[0]*g[1]],x.typeInfo)}return console.error(`Cross() expects vector arguments. Line ${i.line}`),null}Degrees(i,g){const x=this.exec.evalExpression(i.args[0],g),v=180/Math.PI;return x instanceof Me?new Me(x.data.map(i=>i*v),x.typeInfo):new Be(x.value*v,this.getTypeInfo("f32"))}Determinant(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Ue){const i=x.data,g=x.typeInfo.getTypeName(),v=g.endsWith("h")?this.getTypeInfo("f16"):this.getTypeInfo("f32");if("mat2x2"===g||"mat2x2f"===g||"mat2x2h"===g)return new Be(i[0]*i[3]-i[1]*i[2],v);if("mat2x3"===g||"mat2x3f"===g||"mat2x3h"===g)return new Be(i[0]*(i[4]*i[8]-i[5]*i[7])-i[1]*(i[3]*i[8]-i[5]*i[6])+i[2]*(i[3]*i[7]-i[4]*i[6]),v);if("mat2x4"===g||"mat2x4f"===g||"mat2x4h"===g)console.error(`TODO: Determinant for ${g}`);else if("mat3x2"===g||"mat3x2f"===g||"mat3x2h"===g)console.error(`TODO: Determinant for ${g}`);else{if("mat3x3"===g||"mat3x3f"===g||"mat3x3h"===g)return new Be(i[0]*(i[4]*i[8]-i[5]*i[7])-i[1]*(i[3]*i[8]-i[5]*i[6])+i[2]*(i[3]*i[7]-i[4]*i[6]),v);"mat3x4"===g||"mat3x4f"===g||"mat3x4h"===g||"mat4x2"===g||"mat4x2f"===g||"mat4x2h"===g||"mat4x3"===g||"mat4x3f"===g||"mat4x3h"===g?console.error(`TODO: Determinant for ${g}`):"mat4x4"!==g&&"mat4x4f"!==g&&"mat4x4h"!==g||console.error(`TODO: Determinant for ${g}`)}}return console.error(`Determinant expects a matrix argument. Line ${i.line}`),null}Distance(i,g){const x=this.exec.evalExpression(i.args[0],g),v=this.exec.evalExpression(i.args[1],g);if(x instanceof Me&&v instanceof Me){let i=0;for(let g=0;gMath.exp(i)),x.typeInfo);const v=x;return new Be(Math.exp(v.value),x.typeInfo)}Exp2(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.pow(2,i)),x.typeInfo);const v=x;return new Be(Math.pow(2,v.value),x.typeInfo)}ExtractBits(i,g){const x=this.exec.evalExpression(i.args[0],g),v=this.exec.evalExpression(i.args[1],g),_=this.exec.evalExpression(i.args[2],g);if("u32"!==v.typeInfo.name&&"x32"!==v.typeInfo.name)return console.error(`ExtractBits() expects an i32 offset argument. Line ${i.line}`),null;if("u32"!==_.typeInfo.name&&"x32"!==_.typeInfo.name)return console.error(`ExtractBits() expects an i32 count argument. Line ${i.line}`),null;const y=v.value,b=_.value;if(x instanceof Me)return new Me(x.data.map(i=>i>>y&(1<>y&(1<-i),x.typeInfo)}return console.error(`FaceForward() expects vector arguments. Line ${i.line}`),null}_firstLeadingBit(i){return 0===i?-1:31-Math.clz32(i)}FirstLeadingBit(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>this._firstLeadingBit(i)),x.typeInfo);const v=x;return new Be(this._firstLeadingBit(v.value),x.typeInfo)}_firstTrailingBit(i){return 0===i?-1:Math.log2(i&-i)}FirstTrailingBit(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>this._firstTrailingBit(i)),x.typeInfo);const v=x;return new Be(this._firstTrailingBit(v.value),x.typeInfo)}Floor(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.floor(i)),x.typeInfo);const v=x;return new Be(Math.floor(v.value),x.typeInfo)}Fma(i,g){const x=this.exec.evalExpression(i.args[0],g),v=this.exec.evalExpression(i.args[1],g),_=this.exec.evalExpression(i.args[2],g);if(x instanceof Me&&v instanceof Me&&_ instanceof Me)return x.data.length!==v.data.length||x.data.length!==_.data.length?(console.error(`Fma() expects vectors of the same length. Line ${i.line}`),null):new Me(x.data.map((i,g)=>i*v.data[g]+_.data[g]),x.typeInfo);const y=x,b=v,S=_;return new Be(y.value*b.value+S.value,y.typeInfo)}Fract(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>i-Math.floor(i)),x.typeInfo);const v=x;return new Be(v.value-Math.floor(v.value),x.typeInfo)}Frexp(i,g){return console.error(`TODO: frexp. Line ${i.line}`),null}InsertBits(i,g){const x=this.exec.evalExpression(i.args[0],g),v=this.exec.evalExpression(i.args[1],g),_=this.exec.evalExpression(i.args[2],g),y=this.exec.evalExpression(i.args[3],g);if("u32"!==_.typeInfo.name&&"x32"!==_.typeInfo.name)return console.error(`InsertBits() expects an i32 offset argument. Line ${i.line}`),null;const b=_.value,S=(1<i&w|v.data[g]<1/Math.sqrt(i)),x.typeInfo);const v=x;return new Be(1/Math.sqrt(v.value),x.typeInfo)}Ldexp(i,g){return console.error(`TODO: ldexp. Line ${i.line}`),null}Length(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me){let i=0;return x.data.forEach(g=>{i+=g*g}),new Be(Math.sqrt(i),this.getTypeInfo("f32"))}const v=x;return new Be(Math.abs(v.value),x.typeInfo)}Log(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.log(i)),x.typeInfo);const v=x;return new Be(Math.log(v.value),x.typeInfo)}Log2(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.log2(i)),x.typeInfo);const v=x;return new Be(Math.log2(v.value),x.typeInfo)}Max(i,g){const x=this.exec.evalExpression(i.args[0],g),v=this.exec.evalExpression(i.args[1],g);if(x instanceof Me&&v instanceof Me)return new Me(x.data.map((i,g)=>Math.max(i,v.data[g])),x.typeInfo);const _=x,y=v;return new Be(Math.max(_.value,y.value),x.typeInfo)}Min(i,g){const x=this.exec.evalExpression(i.args[0],g),v=this.exec.evalExpression(i.args[1],g);if(x instanceof Me&&v instanceof Me)return new Me(x.data.map((i,g)=>Math.min(i,v.data[g])),x.typeInfo);const _=x,y=v;return new Be(Math.min(_.value,y.value),x.typeInfo)}Mix(i,g){const x=this.exec.evalExpression(i.args[0],g),v=this.exec.evalExpression(i.args[1],g),_=this.exec.evalExpression(i.args[2],g);if(x instanceof Me&&v instanceof Me&&_ instanceof Me)return new Me(x.data.map((i,g)=>x.data[g]*(1-_.data[g])+v.data[g]*_.data[g]),x.typeInfo);const y=v,b=_;return new Be(x.value*(1-b.value)+y.value*b.value,x.typeInfo)}Modf(i,g){const x=this.exec.evalExpression(i.args[0],g),v=this.exec.evalExpression(i.args[1],g);if(x instanceof Me&&v instanceof Me)return new Me(x.data.map((i,g)=>i%v.data[g]),x.typeInfo);const _=v;return new Be(x.value%_.value,x.typeInfo)}Normalize(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me){const v=this.Length(i,g).value;return new Me(x.data.map(i=>i/v),x.typeInfo)}return console.error(`Normalize() expects a vector argument. Line ${i.line}`),null}Pow(i,g){const x=this.exec.evalExpression(i.args[0],g),v=this.exec.evalExpression(i.args[1],g);if(x instanceof Me&&v instanceof Me)return new Me(x.data.map((i,g)=>Math.pow(i,v.data[g])),x.typeInfo);const _=x,y=v;return new Be(Math.pow(_.value,y.value),x.typeInfo)}QuantizeToF16(i,g){const x=this.exec.evalExpression(i.args[0],g);return x instanceof Me?new Me(x.data.map(i=>i),x.typeInfo):new Be(x.value,x.typeInfo)}Radians(i,g){const x=this.exec.evalExpression(i.args[0],g);return x instanceof Me?new Me(x.data.map(i=>i*Math.PI/180),x.typeInfo):new Be(x.value*Math.PI/180,this.getTypeInfo("f32"))}Reflect(i,g){let x=this.exec.evalExpression(i.args[0],g),v=this.exec.evalExpression(i.args[1],g);if(x instanceof Me&&v instanceof Me){const i=this._dot(x.data,v.data);return new Me(x.data.map((g,x)=>g-2*i*v.data[x]),x.typeInfo)}return console.error(`Reflect() expects vector arguments. Line ${i.line}`),null}Refract(i,g){let x=this.exec.evalExpression(i.args[0],g),v=this.exec.evalExpression(i.args[1],g),_=this.exec.evalExpression(i.args[2],g);if(x instanceof Me&&v instanceof Me&&_ instanceof Be){const i=this._dot(v.data,x.data);return new Me(x.data.map((g,x)=>{const y=1-_.value*_.value*(1-i*i);if(y<0)return 0;const b=Math.sqrt(y);return _.value*g-(_.value*i+b)*v.data[x]}),x.typeInfo)}return console.error(`Refract() expects vector arguments and a scalar argument. Line ${i.line}`),null}ReverseBits(i,g){return console.error(`TODO: reverseBits. Line ${i.line}`),null}Round(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.round(i)),x.typeInfo);const v=x;return new Be(Math.round(v.value),x.typeInfo)}Saturate(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.min(Math.max(i,0),1)),x.typeInfo);const v=x;return new Be(Math.min(Math.max(v.value,0),1),x.typeInfo)}Sign(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.sign(i)),x.typeInfo);const v=x;return new Be(Math.sign(v.value),x.typeInfo)}Sin(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.sin(i)),x.typeInfo);const v=x;return new Be(Math.sin(v.value),x.typeInfo)}Sinh(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.sinh(i)),x.typeInfo);const v=x;return new Be(Math.sinh(v.value),x.typeInfo)}_smoothstep(i,g,x){const v=Math.min(Math.max((x-i)/(g-i),0),1);return v*v*(3-2*v)}SmoothStep(i,g){const x=this.exec.evalExpression(i.args[0],g),v=this.exec.evalExpression(i.args[1],g),_=this.exec.evalExpression(i.args[2],g);if(_ instanceof Me&&x instanceof Me&&v instanceof Me)return new Me(_.data.map((i,g)=>this._smoothstep(x.data[g],v.data[g],i)),_.typeInfo);const y=x,b=v,S=_;return new Be(this._smoothstep(y.value,b.value,S.value),_.typeInfo)}Sqrt(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.sqrt(i)),x.typeInfo);const v=x;return new Be(Math.sqrt(v.value),x.typeInfo)}Step(i,g){const x=this.exec.evalExpression(i.args[0],g),v=this.exec.evalExpression(i.args[1],g);if(v instanceof Me&&x instanceof Me)return new Me(v.data.map((i,g)=>iMath.tan(i)),x.typeInfo);const v=x;return new Be(Math.tan(v.value),x.typeInfo)}Tanh(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.tanh(i)),x.typeInfo);const v=x;return new Be(Math.tanh(v.value),x.typeInfo)}_getTransposeType(i){const g=i.getTypeName();return"mat2x2f"===g||"mat2x2h"===g?i:"mat2x3f"===g?this.getTypeInfo("mat3x2f"):"mat2x3h"===g?this.getTypeInfo("mat3x2h"):"mat2x4f"===g?this.getTypeInfo("mat4x2f"):"mat2x4h"===g?this.getTypeInfo("mat4x2h"):"mat3x2f"===g?this.getTypeInfo("mat2x3f"):"mat3x2h"===g?this.getTypeInfo("mat2x3h"):"mat3x3f"===g||"mat3x3h"===g?i:"mat3x4f"===g?this.getTypeInfo("mat4x3f"):"mat3x4h"===g?this.getTypeInfo("mat4x3h"):"mat4x2f"===g?this.getTypeInfo("mat2x4f"):"mat4x2h"===g?this.getTypeInfo("mat2x4h"):"mat4x3f"===g?this.getTypeInfo("mat3x4f"):"mat4x3h"===g?this.getTypeInfo("mat3x4h"):("mat4x4f"===g||"mat4x4h"===g||console.error(`Invalid matrix type ${g}`),i)}Transpose(i,g){const x=this.exec.evalExpression(i.args[0],g);if(!(x instanceof Ue))return console.error(`Transpose() expects a matrix argument. Line ${i.line}`),null;const v=this._getTransposeType(x.typeInfo);if("mat2x2"===x.typeInfo.name||"mat2x2f"===x.typeInfo.name||"mat2x2h"===x.typeInfo.name){const i=x.data;return new Ue([i[0],i[2],i[1],i[3]],v)}if("mat2x3"===x.typeInfo.name||"mat2x3f"===x.typeInfo.name||"mat2x3h"===x.typeInfo.name){const i=x.data;return new Ue([i[0],i[3],i[6],i[1],i[4],i[7]],v)}if("mat2x4"===x.typeInfo.name||"mat2x4f"===x.typeInfo.name||"mat2x4h"===x.typeInfo.name){const i=x.data;return new Ue([i[0],i[4],i[8],i[12],i[1],i[5],i[9],i[13]],v)}if("mat3x2"===x.typeInfo.name||"mat3x2f"===x.typeInfo.name||"mat3x2h"===x.typeInfo.name){const i=x.data;return new Ue([i[0],i[3],i[1],i[4],i[2],i[5]],v)}if("mat3x3"===x.typeInfo.name||"mat3x3f"===x.typeInfo.name||"mat3x3h"===x.typeInfo.name){const i=x.data;return new Ue([i[0],i[3],i[6],i[1],i[4],i[7],i[2],i[5],i[8]],v)}if("mat3x4"===x.typeInfo.name||"mat3x4f"===x.typeInfo.name||"mat3x4h"===x.typeInfo.name){const i=x.data;return new Ue([i[0],i[4],i[8],i[12],i[1],i[5],i[9],i[13],i[2],i[6],i[10],i[14]],v)}if("mat4x2"===x.typeInfo.name||"mat4x2f"===x.typeInfo.name||"mat4x2h"===x.typeInfo.name){const i=x.data;return new Ue([i[0],i[4],i[1],i[5],i[2],i[6]],v)}if("mat4x3"===x.typeInfo.name||"mat4x3f"===x.typeInfo.name||"mat4x3h"===x.typeInfo.name){const i=x.data;return new Ue([i[0],i[4],i[8],i[1],i[5],i[9],i[2],i[6],i[10]],v)}if("mat4x4"===x.typeInfo.name||"mat4x4f"===x.typeInfo.name||"mat4x4h"===x.typeInfo.name){const i=x.data;return new Ue([i[0],i[4],i[8],i[12],i[1],i[5],i[9],i[13],i[2],i[6],i[10],i[14],i[3],i[7],i[11],i[15]],v)}return console.error(`Invalid matrix type ${x.typeInfo.name}`),null}Trunc(i,g){const x=this.exec.evalExpression(i.args[0],g);if(x instanceof Me)return new Me(x.data.map(i=>Math.trunc(i)),x.typeInfo);const v=x;return new Be(Math.trunc(v.value),x.typeInfo)}Dpdx(i,g){return console.error(`TODO: dpdx. Line ${i.line}`),null}DpdxCoarse(i,g){return console.error(`TODO: dpdxCoarse. Line ${i.line}`),null}DpdxFine(i,g){return console.error("TODO: dpdxFine"),null}Dpdy(i,g){return console.error("TODO: dpdy"),null}DpdyCoarse(i,g){return console.error("TODO: dpdyCoarse"),null}DpdyFine(i,g){return console.error("TODO: dpdyFine"),null}Fwidth(i,g){return console.error("TODO: fwidth"),null}FwidthCoarse(i,g){return console.error("TODO: fwidthCoarse"),null}FwidthFine(i,g){return console.error("TODO: fwidthFine"),null}TextureDimensions(i,g){const x=i.args[0],v=i.args.length>1?this.exec.evalExpression(i.args[1],g).value:0;if(x instanceof ge){const _=x.name,y=g.getVariableValue(_);if(y instanceof We){if(v<0||v>=y.mipLevelCount)return console.error(`Invalid mip level for textureDimensions. Line ${i.line}`),null;const g=y.getMipLevelSize(v),x=y.dimension;return"1d"===x?new Be(g[0],this.getTypeInfo("u32")):"3d"===x?new Me(g,this.getTypeInfo("vec3u")):"2d"===x?new Me(g.slice(0,2),this.getTypeInfo("vec2u")):(console.error(`Invalid texture dimension ${x} not found. Line ${i.line}`),null)}return console.error(`Texture ${_} not found. Line ${i.line}`),null}return console.error(`Invalid texture argument for textureDimensions. Line ${i.line}`),null}TextureGather(i,g){return console.error("TODO: textureGather"),null}TextureGatherCompare(i,g){return console.error("TODO: textureGatherCompare"),null}TextureLoad(i,g){const x=i.args[0],v=this.exec.evalExpression(i.args[1],g),_=i.args.length>2?this.exec.evalExpression(i.args[2],g).value:0;if(!(v instanceof Me)||2!==v.data.length)return console.error(`Invalid UV argument for textureLoad. Line ${i.line}`),null;if(x instanceof ge){const y=x.name,b=g.getVariableValue(y);if(b instanceof We){const g=Math.floor(v.data[0]),x=Math.floor(v.data[1]);if(g<0||g>=b.width||x<0||x>=b.height)return console.error(`Texture ${y} out of bounds. Line ${i.line}`),null;const S=b.getPixel(g,x,0,_);return null===S?(console.error(`Invalid texture format for textureLoad. Line ${i.line}`),null):new Me(S,this.getTypeInfo("vec4f"))}return console.error(`Texture ${y} not found. Line ${i.line}`),null}return console.error(`Invalid texture argument for textureLoad. Line ${i.line}`),null}TextureNumLayers(i,g){const x=i.args[0];if(x instanceof ge){const v=x.name,_=g.getVariableValue(v);return _ instanceof We?new Be(_.depthOrArrayLayers,this.getTypeInfo("u32")):(console.error(`Texture ${v} not found. Line ${i.line}`),null)}return console.error(`Invalid texture argument for textureNumLayers. Line ${i.line}`),null}TextureNumLevels(i,g){const x=i.args[0];if(x instanceof ge){const v=x.name,_=g.getVariableValue(v);return _ instanceof We?new Be(_.mipLevelCount,this.getTypeInfo("u32")):(console.error(`Texture ${v} not found. Line ${i.line}`),null)}return console.error(`Invalid texture argument for textureNumLevels. Line ${i.line}`),null}TextureNumSamples(i,g){const x=i.args[0];if(x instanceof ge){const v=x.name,_=g.getVariableValue(v);return _ instanceof We?new Be(_.sampleCount,this.getTypeInfo("u32")):(console.error(`Texture ${v} not found. Line ${i.line}`),null)}return console.error(`Invalid texture argument for textureNumSamples. Line ${i.line}`),null}TextureSample(i,g){return console.error("TODO: textureSample"),null}TextureSampleBias(i,g){return console.error("TODO: textureSampleBias"),null}TextureSampleCompare(i,g){return console.error("TODO: textureSampleCompare"),null}TextureSampleCompareLevel(i,g){return console.error("TODO: textureSampleCompareLevel"),null}TextureSampleGrad(i,g){return console.error("TODO: textureSampleGrad"),null}TextureSampleLevel(i,g){return console.error("TODO: textureSampleLevel"),null}TextureSampleBaseClampToEdge(i,g){return console.error("TODO: textureSampleBaseClampToEdge"),null}TextureStore(i,g){const x=i.args[0],v=this.exec.evalExpression(i.args[1],g),_=4===i.args.length?this.exec.evalExpression(i.args[2],g).value:0,y=4===i.args.length?this.exec.evalExpression(i.args[3],g).data:this.exec.evalExpression(i.args[2],g).data;if(4!==y.length)return console.error(`Invalid value argument for textureStore. Line ${i.line}`),null;if(!(v instanceof Me)||2!==v.data.length)return console.error(`Invalid UV argument for textureStore. Line ${i.line}`),null;if(x instanceof ge){const b=x.name,S=g.getVariableValue(b);if(S instanceof We){const g=S.getMipLevelSize(0),x=Math.floor(v.data[0]),w=Math.floor(v.data[1]);return x<0||x>=g[0]||w<0||w>=g[1]?(console.error(`Texture ${b} out of bounds. Line ${i.line}`),null):(S.setPixel(x,w,0,_,Array.from(y)),null)}return console.error(`Texture ${b} not found. Line ${i.line}`),null}return console.error(`Invalid texture argument for textureStore. Line ${i.line}`),null}AtomicLoad(i,g){let x=i.args[0];x instanceof ke&&(x=x.right);const v=this.exec.getVariableName(x,g);return g.getVariable(v).value.getSubData(this.exec,x.postfix,g)}AtomicStore(i,g){let x=i.args[0];x instanceof ke&&(x=x.right);const v=this.exec.getVariableName(x,g),_=g.getVariable(v);let y=i.args[1];const b=this.exec.evalExpression(y,g),S=_.value.getSubData(this.exec,x.postfix,g);return S instanceof Be&&b instanceof Be&&(S.value=b.value),_.value instanceof Pe&&_.value.setDataValue(this.exec,S,x.postfix,g),null}AtomicAdd(i,g){let x=i.args[0];x instanceof ke&&(x=x.right);const v=this.exec.getVariableName(x,g),_=g.getVariable(v);let y=i.args[1];const b=this.exec.evalExpression(y,g),S=_.value.getSubData(this.exec,x.postfix,g),w=new Be(S.value,S.typeInfo);return S instanceof Be&&b instanceof Be&&(S.value+=b.value),_.value instanceof Pe&&_.value.setDataValue(this.exec,S,x.postfix,g),w}AtomicSub(i,g){let x=i.args[0];x instanceof ke&&(x=x.right);const v=this.exec.getVariableName(x,g),_=g.getVariable(v);let y=i.args[1];const b=this.exec.evalExpression(y,g),S=_.value.getSubData(this.exec,x.postfix,g),w=new Be(S.value,S.typeInfo);return S instanceof Be&&b instanceof Be&&(S.value-=b.value),_.value instanceof Pe&&_.value.setDataValue(this.exec,S,x.postfix,g),w}AtomicMax(i,g){let x=i.args[0];x instanceof ke&&(x=x.right);const v=this.exec.getVariableName(x,g),_=g.getVariable(v);let y=i.args[1];const b=this.exec.evalExpression(y,g),S=_.value.getSubData(this.exec,x.postfix,g),w=new Be(S.value,S.typeInfo);return S instanceof Be&&b instanceof Be&&(S.value=Math.max(S.value,b.value)),_.value instanceof Pe&&_.value.setDataValue(this.exec,S,x.postfix,g),w}AtomicMin(i,g){let x=i.args[0];x instanceof ke&&(x=x.right);const v=this.exec.getVariableName(x,g),_=g.getVariable(v);let y=i.args[1];const b=this.exec.evalExpression(y,g),S=_.value.getSubData(this.exec,x.postfix,g),w=new Be(S.value,S.typeInfo);return S instanceof Be&&b instanceof Be&&(S.value=Math.min(S.value,b.value)),_.value instanceof Pe&&_.value.setDataValue(this.exec,S,x.postfix,g),w}AtomicAnd(i,g){let x=i.args[0];x instanceof ke&&(x=x.right);const v=this.exec.getVariableName(x,g),_=g.getVariable(v);let y=i.args[1];const b=this.exec.evalExpression(y,g),S=_.value.getSubData(this.exec,x.postfix,g),w=new Be(S.value,S.typeInfo);return S instanceof Be&&b instanceof Be&&(S.value=S.value&b.value),_.value instanceof Pe&&_.value.setDataValue(this.exec,S,x.postfix,g),w}AtomicOr(i,g){let x=i.args[0];x instanceof ke&&(x=x.right);const v=this.exec.getVariableName(x,g),_=g.getVariable(v);let y=i.args[1];const b=this.exec.evalExpression(y,g),S=_.value.getSubData(this.exec,x.postfix,g),w=new Be(S.value,S.typeInfo);return S instanceof Be&&b instanceof Be&&(S.value=S.value|b.value),_.value instanceof Pe&&_.value.setDataValue(this.exec,S,x.postfix,g),w}AtomicXor(i,g){let x=i.args[0];x instanceof ke&&(x=x.right);const v=this.exec.getVariableName(x,g),_=g.getVariable(v);let y=i.args[1];const b=this.exec.evalExpression(y,g),S=_.value.getSubData(this.exec,x.postfix,g),w=new Be(S.value,S.typeInfo);return S instanceof Be&&b instanceof Be&&(S.value=S.value^b.value),_.value instanceof Pe&&_.value.setDataValue(this.exec,S,x.postfix,g),w}AtomicExchange(i,g){let x=i.args[0];x instanceof ke&&(x=x.right);const v=this.exec.getVariableName(x,g),_=g.getVariable(v);let y=i.args[1];const b=this.exec.evalExpression(y,g),S=_.value.getSubData(this.exec,x.postfix,g),w=new Be(S.value,S.typeInfo);return S instanceof Be&&b instanceof Be&&(S.value=b.value),_.value instanceof Pe&&_.value.setDataValue(this.exec,S,x.postfix,g),w}AtomicCompareExchangeWeak(i,g){return console.error("TODO: atomicCompareExchangeWeak"),null}Pack4x8snorm(i,g){return console.error("TODO: pack4x8snorm"),null}Pack4x8unorm(i,g){return console.error("TODO: pack4x8unorm"),null}Pack4xI8(i,g){return console.error("TODO: pack4xI8"),null}Pack4xU8(i,g){return console.error("TODO: pack4xU8"),null}Pack4x8Clamp(i,g){return console.error("TODO: pack4x8Clamp"),null}Pack4xU8Clamp(i,g){return console.error("TODO: pack4xU8Clamp"),null}Pack2x16snorm(i,g){return console.error("TODO: pack2x16snorm"),null}Pack2x16unorm(i,g){return console.error("TODO: pack2x16unorm"),null}Pack2x16float(i,g){return console.error("TODO: pack2x16float"),null}Unpack4x8snorm(i,g){return console.error("TODO: unpack4x8snorm"),null}Unpack4x8unorm(i,g){return console.error("TODO: unpack4x8unorm"),null}Unpack4xI8(i,g){return console.error("TODO: unpack4xI8"),null}Unpack4xU8(i,g){return console.error("TODO: unpack4xU8"),null}Unpack2x16snorm(i,g){return console.error("TODO: unpack2x16snorm"),null}Unpack2x16unorm(i,g){return console.error("TODO: unpack2x16unorm"),null}Unpack2x16float(i,g){return console.error("TODO: unpack2x16float"),null}StorageBarrier(i,g){return null}TextureBarrier(i,g){return null}WorkgroupBarrier(i,g){return null}WorkgroupUniformLoad(i,g){return null}SubgroupAdd(i,g){return console.error("TODO: subgroupAdd"),null}SubgroupExclusiveAdd(i,g){return console.error("TODO: subgroupExclusiveAdd"),null}SubgroupInclusiveAdd(i,g){return console.error("TODO: subgroupInclusiveAdd"),null}SubgroupAll(i,g){return console.error("TODO: subgroupAll"),null}SubgroupAnd(i,g){return console.error("TODO: subgroupAnd"),null}SubgroupAny(i,g){return console.error("TODO: subgroupAny"),null}SubgroupBallot(i,g){return console.error("TODO: subgroupBallot"),null}SubgroupBroadcast(i,g){return console.error("TODO: subgroupBroadcast"),null}SubgroupBroadcastFirst(i,g){return console.error("TODO: subgroupBroadcastFirst"),null}SubgroupElect(i,g){return console.error("TODO: subgroupElect"),null}SubgroupMax(i,g){return console.error("TODO: subgroupMax"),null}SubgroupMin(i,g){return console.error("TODO: subgroupMin"),null}SubgroupMul(i,g){return console.error("TODO: subgroupMul"),null}SubgroupExclusiveMul(i,g){return console.error("TODO: subgroupExclusiveMul"),null}SubgroupInclusiveMul(i,g){return console.error("TODO: subgroupInclusiveMul"),null}SubgroupOr(i,g){return console.error("TODO: subgroupOr"),null}SubgroupShuffle(i,g){return console.error("TODO: subgroupShuffle"),null}SubgroupShuffleDown(i,g){return console.error("TODO: subgroupShuffleDown"),null}SubgroupShuffleUp(i,g){return console.error("TODO: subgroupShuffleUp"),null}SubgroupShuffleXor(i,g){return console.error("TODO: subgroupShuffleXor"),null}SubgroupXor(i,g){return console.error("TODO: subgroupXor"),null}QuadBroadcast(i,g){return console.error("TODO: quadBroadcast"),null}QuadSwapDiagonal(i,g){return console.error("TODO: quadSwapDiagonal"),null}QuadSwapX(i,g){return console.error("TODO: quadSwapX"),null}QuadSwapY(i,g){return console.error("TODO: quadSwapY"),null}}const ai={vec2:2,vec2f:2,vec2i:2,vec2u:2,vec2b:2,vec2h:2,vec3:3,vec3f:3,vec3i:3,vec3u:3,vec3b:3,vec3h:3,vec4:4,vec4f:4,vec4i:4,vec4u:4,vec4b:4,vec4h:4},si={mat2x2:[2,2,4],mat2x2f:[2,2,4],mat2x2h:[2,2,4],mat2x3:[2,3,6],mat2x3f:[2,3,6],mat2x3h:[2,3,6],mat2x4:[2,4,8],mat2x4f:[2,4,8],mat2x4h:[2,4,8],mat3x2:[3,2,6],mat3x2f:[3,2,6],mat3x2h:[3,2,6],mat3x3:[3,3,9],mat3x3f:[3,3,9],mat3x3h:[3,3,9],mat3x4:[3,4,12],mat3x4f:[3,4,12],mat3x4h:[3,4,12],mat4x2:[4,2,8],mat4x2f:[4,2,8],mat4x2h:[4,2,8],mat4x3:[4,3,12],mat4x3f:[4,3,12],mat4x3h:[4,3,12],mat4x4:[4,4,16],mat4x4f:[4,4,16],mat4x4h:[4,4,16]};class dt extends ut{constructor(i,g){var x;super(),this.ast=null!=i?i:[],this.reflection=new at,this.reflection.updateAST(this.ast),this.context=null!==(x=null==g?void 0:g.clone())&&void 0!==x?x:new lt,this.builtins=new ht(this),this.typeInfo={bool:this.getTypeInfo(ae.bool),i32:this.getTypeInfo(ae.i32),u32:this.getTypeInfo(ae.u32),f32:this.getTypeInfo(ae.f32),f16:this.getTypeInfo(ae.f16),vec2f:this.getTypeInfo(ce.vec2f),vec2u:this.getTypeInfo(ce.vec2u),vec2i:this.getTypeInfo(ce.vec2i),vec2h:this.getTypeInfo(ce.vec2h),vec3f:this.getTypeInfo(ce.vec3f),vec3u:this.getTypeInfo(ce.vec3u),vec3i:this.getTypeInfo(ce.vec3i),vec3h:this.getTypeInfo(ce.vec3h),vec4f:this.getTypeInfo(ce.vec4f),vec4u:this.getTypeInfo(ce.vec4u),vec4i:this.getTypeInfo(ce.vec4i),vec4h:this.getTypeInfo(ce.vec4h),mat2x2f:this.getTypeInfo(ce.mat2x2f),mat2x3f:this.getTypeInfo(ce.mat2x3f),mat2x4f:this.getTypeInfo(ce.mat2x4f),mat3x2f:this.getTypeInfo(ce.mat3x2f),mat3x3f:this.getTypeInfo(ce.mat3x3f),mat3x4f:this.getTypeInfo(ce.mat3x4f),mat4x2f:this.getTypeInfo(ce.mat4x2f),mat4x3f:this.getTypeInfo(ce.mat4x3f),mat4x4f:this.getTypeInfo(ce.mat4x4f)}}getVariableValue(i){var g,x;const v=null!==(x=null===(g=this.context.getVariable(i))||void 0===g?void 0:g.value)&&void 0!==x?x:null;if(null===v)return null;if(v instanceof Be)return v.value;if(v instanceof Me)return Array.from(v.data);if(v instanceof Ue)return Array.from(v.data);if(v instanceof Pe&&v.typeInfo instanceof s){if("u32"===v.typeInfo.format.name)return Array.from(new Uint32Array(v.buffer,v.offset,v.typeInfo.count));if("i32"===v.typeInfo.format.name)return Array.from(new Int32Array(v.buffer,v.offset,v.typeInfo.count));if("f32"===v.typeInfo.format.name)return Array.from(new Float32Array(v.buffer,v.offset,v.typeInfo.count))}return console.error(`Unsupported return variable type ${v.typeInfo.name}`),null}execute(i){(i=null!=i?i:{}).constants&&this._setOverrides(i.constants,this.context),this._execStatements(this.ast,this.context)}dispatchWorkgroups(i,g,x,v){const _=this.context.clone();(v=null!=v?v:{}).constants&&this._setOverrides(v.constants,_),this._execStatements(this.ast,_);const y=_.getFunction(i);if(!y)return void console.error(`Function ${i} not found`);if("number"==typeof g)g=[g,1,1];else{if(0===g.length)return void console.error("Invalid dispatch count");1===g.length?g=[g[0],1,1]:2===g.length?g=[g[0],g[1],1]:g.length>3&&(g=[g[0],g[1],g[2]])}const b=g[0],S=g[1],w=g[2],L=this.getTypeInfo("vec3u");_.setVariable("@num_workgroups",new Me(g,L));const k=this.reflection.getFunctionInfo(i);null===k&&console.error(`Function ${i} not found in reflection data`);for(const i in x)for(const g in x[i]){const v=x[i][g];_.variables.forEach(x=>{var _;const y=x.node;if(null==y?void 0:y.attributes){let b=null,S=null;for(const i of y.attributes)"binding"===i.name?b=i.value:"group"===i.name&&(S=i.value);if(g==b&&i==S){let b=!1;for(const v of k.resources)if(v.name===x.name&&v.group===parseInt(i)&&v.binding===parseInt(g)){b=!0;break}if(b)if(void 0!==v.texture&&void 0!==v.descriptor){const i=new We(v.texture,this.getTypeInfo(y.type),v.descriptor,null!==(_=v.texture.view)&&void 0!==_?_:null);x.value=i}else void 0!==v.uniform?x.value=new Pe(v.uniform,this.getTypeInfo(y.type)):x.value=new Pe(v,this.getTypeInfo(y.type))}}})}for(let i=0;i0){const i=x.getVariableValue(g.value[0]);v[0]=i instanceof Be?i.value:parseInt(g.value[0])}if(g.value.length>1){const i=x.getVariableValue(g.value[1]);v[1]=i instanceof Be?i.value:parseInt(g.value[1])}if(g.value.length>2){const i=x.getVariableValue(g.value[2]);v[2]=i instanceof Be?i.value:parseInt(g.value[2])}}const _=this.getTypeInfo("vec3u"),y=this.getTypeInfo("u32");x.setVariable("@workgroup_size",new Me(v,_));const b=v[0],S=v[1],w=v[2];for(let L=0,k=0;L",_=null;if(i.variable instanceof ke){const x=this._getVariableData(i.variable,g),v=this.evalExpression(i.value,g),_=i.operator;if("="===_){if(x instanceof Be||x instanceof Me||x instanceof Ue){if(v instanceof Be||v instanceof Me||v instanceof Ue&&x.data.length===v.data.length)return void x.data.set(v.data);console.error(`Invalid assignment. Line ${i.line}`)}else if(x instanceof Pe&&v instanceof Pe&&x.buffer.byteLength-x.offset>=v.buffer.byteLength-v.offset)return void(x.buffer.byteLength%4==0?new Uint32Array(x.buffer,x.offset,x.typeInfo.size/4).set(new Uint32Array(v.buffer,v.offset,v.typeInfo.size/4)):new Uint8Array(x.buffer,x.offset,x.typeInfo.size).set(new Uint8Array(v.buffer,v.offset,v.typeInfo.size)));return console.error(`Invalid assignment. Line ${i.line}`),null}if("+="===_)return x instanceof Be||x instanceof Me||x instanceof Ue?v instanceof Be||v instanceof Me||v instanceof Ue?void x.data.set(v.data.map((i,g)=>x.data[g]+i)):void console.error(`Invalid assignment . Line ${i.line}`):void console.error(`Invalid assignment. Line ${i.line}`);if("-="===_)return(x instanceof Be||x instanceof Me||x instanceof Ue)&&(v instanceof Be||v instanceof Me||v instanceof Ue)?void x.data.set(v.data.map((i,g)=>x.data[g]-i)):void console.error(`Invalid assignment. Line ${i.line}`)}if(i.variable instanceof ke){if("*"===i.variable.operator){v=this.getVariableName(i.variable.right,g);const _=g.getVariable(v);if(!(_&&_.value instanceof Oe))return void console.error(`Variable ${v} is not a pointer. Line ${i.line}`);x=_.value.reference;let y=i.variable.postfix;if(!y){let g=i.variable.right;for(;g instanceof ke;){if(g.postfix){y=g.postfix;break}g=g.right}}y&&(x=x.getSubData(this,y,g))}}else{_=i.variable.postfix,v=this.getVariableName(i.variable,g);const y=g.getVariable(v);if(null===y)return void console.error(`Variable ${v} not found. Line ${i.line}`);x=y.value}if(x instanceof Oe&&(x=x.reference),null===x)return void console.error(`Variable ${v} not found. Line ${i.line}`);const y=this.evalExpression(i.value,g),b=i.operator;if("="!==b){const v=x.getSubData(this,_,g);if(v instanceof Me&&y instanceof Be){const g=v.data,x=y.value;if("+="===b)for(let i=0;i>="===b)for(let i=0;i>=x;else console.error(`Invalid operator ${b}. Line ${i.line}`)}else if(v instanceof Me&&y instanceof Me){const g=v.data,x=y.data;if(g.length!==x.length)return void console.error(`Vector length mismatch. Line ${i.line}`);if("+="===b)for(let i=0;i>="===b)for(let i=0;i>=x[i];else console.error(`Invalid operator ${b}. Line ${i.line}`)}else{if(!(v instanceof Be&&y instanceof Be))return void console.error(`Invalid type for ${i.operator} operator. Line ${i.line}`);"+="===b?v.value+=y.value:"-="===b?v.value-=y.value:"*="===b?v.value*=y.value:"/="===b?v.value/=y.value:"%="===b?v.value%=y.value:"&="===b?v.value&=y.value:"|="===b?v.value|=y.value:"^="===b?v.value^=y.value:"<<="===b?v.value<<=y.value:">>="===b?v.value>>=y.value:console.error(`Invalid operator ${b}. Line ${i.line}`)}return void(x instanceof Pe&&x.setDataValue(this,v,_,g))}if(x instanceof Pe)x.setDataValue(this,y,_,g);else if(_){if(!(x instanceof Me||x instanceof Ue))return void console.error(`Variable ${v} is not a vector or matrix. Line ${i.line}`);if(_ instanceof ve){const b=this.evalExpression(_.index,g).value;if(x instanceof Me){if(!(y instanceof Be))return void console.error(`Invalid assignment to ${v}. Line ${i.line}`);x.data[b]=y.value}else{if(!(x instanceof Ue))return void console.error(`Invalid assignment to ${v}. Line ${i.line}`);{const b=this.evalExpression(_.index,g).value;if(b<0)return void console.error(`Invalid assignment to ${v}. Line ${i.line}`);if(!(y instanceof Me))return void console.error(`Invalid assignment to ${v}. Line ${i.line}`);{const g=x.typeInfo.getTypeName();if("mat2x2"===g||"mat2x2f"===g||"mat2x2h"===g){if(!(b<2&&2===y.data.length))return void console.error(`Invalid assignment to ${v}. Line ${i.line}`);x.data[2*b]=y.data[0],x.data[2*b+1]=y.data[1]}else if("mat2x3"===g||"mat2x3f"===g||"mat2x3h"===g){if(!(b<2&&3===y.data.length))return void console.error(`Invalid assignment to ${v}. Line ${i.line}`);x.data[3*b]=y.data[0],x.data[3*b+1]=y.data[1],x.data[3*b+2]=y.data[2]}else if("mat2x4"===g||"mat2x4f"===g||"mat2x4h"===g){if(!(b<2&&4===y.data.length))return void console.error(`Invalid assignment to ${v}. Line ${i.line}`);x.data[4*b]=y.data[0],x.data[4*b+1]=y.data[1],x.data[4*b+2]=y.data[2],x.data[4*b+3]=y.data[3]}else if("mat3x2"===g||"mat3x2f"===g||"mat3x2h"===g){if(!(b<3&&2===y.data.length))return void console.error(`Invalid assignment to ${v}. Line ${i.line}`);x.data[2*b]=y.data[0],x.data[2*b+1]=y.data[1]}else if("mat3x3"===g||"mat3x3f"===g||"mat3x3h"===g){if(!(b<3&&3===y.data.length))return void console.error(`Invalid assignment to ${v}. Line ${i.line}`);x.data[3*b]=y.data[0],x.data[3*b+1]=y.data[1],x.data[3*b+2]=y.data[2]}else if("mat3x4"===g||"mat3x4f"===g||"mat3x4h"===g){if(!(b<3&&4===y.data.length))return void console.error(`Invalid assignment to ${v}. Line ${i.line}`);x.data[4*b]=y.data[0],x.data[4*b+1]=y.data[1],x.data[4*b+2]=y.data[2],x.data[4*b+3]=y.data[3]}else if("mat4x2"===g||"mat4x2f"===g||"mat4x2h"===g){if(!(b<4&&2===y.data.length))return void console.error(`Invalid assignment to ${v}. Line ${i.line}`);x.data[2*b]=y.data[0],x.data[2*b+1]=y.data[1]}else if("mat4x3"===g||"mat4x3f"===g||"mat4x3h"===g){if(!(b<4&&3===y.data.length))return void console.error(`Invalid assignment to ${v}. Line ${i.line}`);x.data[3*b]=y.data[0],x.data[3*b+1]=y.data[1],x.data[3*b+2]=y.data[2]}else{if("mat4x4"!==g&&"mat4x4f"!==g&&"mat4x4h"!==g)return void console.error(`Invalid assignment to ${v}. Line ${i.line}`);if(!(b<4&&4===y.data.length))return void console.error(`Invalid assignment to ${v}. Line ${i.line}`);x.data[4*b]=y.data[0],x.data[4*b+1]=y.data[1],x.data[4*b+2]=y.data[2],x.data[4*b+3]=y.data[3]}}}}}else if(_ instanceof pe){const g=_.value;if(!(x instanceof Me))return void console.error(`Invalid assignment to ${g}. Variable ${v} is not a vector. Line ${i.line}`);if(y instanceof Be){if(g.length>1)return void console.error(`Invalid assignment to ${g} for variable ${v}. Line ${i.line}`);if("x"===g)x.data[0]=y.value;else if("y"===g){if(x.data.length<2)return void console.error(`Invalid assignment to ${g} for variable ${v}. Line ${i.line}`);x.data[1]=y.value}else if("z"===g){if(x.data.length<3)return void console.error(`Invalid assignment to ${g} for variable ${v}. Line ${i.line}`);x.data[2]=y.value}else if("w"===g){if(x.data.length<4)return void console.error(`Invalid assignment to ${g} for variable ${v}. Line ${i.line}`);x.data[3]=y.value}}else{if(!(y instanceof Me))return void console.error(`Invalid assignment to ${v}. Line ${i.line}`);if(g.length!==y.data.length)return void console.error(`Invalid assignment to ${g} for variable ${v}. Line ${i.line}`);for(let _=0;_+i);return new Me(i,x.typeInfo)}const i=v,g=this._maxFormatTypeInfo([x.typeInfo,x.typeInfo]);return new Be(+i,g)}case"-":{if(Ge(v)){const i=v.map((i,g)=>-i);return new Me(i,x.typeInfo)}const i=v,g=this._maxFormatTypeInfo([x.typeInfo,x.typeInfo]);return new Be(-i,g)}case"!":{if(Ge(v)){const i=v.map((i,g)=>i?0:1);return new Me(i,x.typeInfo)}const i=v,g=this._maxFormatTypeInfo([x.typeInfo,x.typeInfo]);return new Be(i?0:1,g)}case"~":{if(Ge(v)){const i=v.map((i,g)=>~i);return new Me(i,x.typeInfo)}const i=v,g=this._maxFormatTypeInfo([x.typeInfo,x.typeInfo]);return new Be(~i,g)}}return console.error(`Invalid unary operator ${i.operator}. Line ${i.line}`),null}_evalBinaryOp(i,g){const x=this.evalExpression(i.left,g),v=this.evalExpression(i.right,g),_=x instanceof Be?x.value:x instanceof Me||x instanceof Ue?Array.from(x.data):null,y=v instanceof Be?v.value:v instanceof Me||v instanceof Ue?Array.from(v.data):null;switch(i.operator){case"+":{if(Ge(_)&&Ge(y)){const g=_,v=y;if(g.length!==v.length)return console.error(`Vector length mismatch. Line ${i.line}.`),null;const b=g.map((i,g)=>i+v[g]);return new Me(b,x.typeInfo)}if(Ge(_)){const i=y,g=_.map((g,x)=>g+i);return new Me(g,x.typeInfo)}if(Ge(y)){const i=_,g=y.map((g,x)=>i+g);return new Me(g,v.typeInfo)}const g=_,b=y,S=this._maxFormatTypeInfo([x.typeInfo,v.typeInfo]);return new Be(g+b,S)}case"-":{if(Ge(_)&&Ge(y)){const g=_,v=y;if(g.length!==v.length)return console.error(`Vector length mismatch. Line ${i.line}.`),null;const b=g.map((i,g)=>i-v[g]);return new Me(b,x.typeInfo)}if(Ge(_)){const i=y,g=_.map((g,x)=>g-i);return new Me(g,x.typeInfo)}if(Ge(y)){const i=_,g=y.map((g,x)=>i-g);return new Me(g,v.typeInfo)}const g=_,b=y,S=this._maxFormatTypeInfo([x.typeInfo,v.typeInfo]);return new Be(g-b,S)}case"*":{if(Ge(_)&&Ge(y)){const g=_,b=y;if(x instanceof Ue&&v instanceof Ue){const _=function(i,g,x,v){if(void 0===si[g.name]||void 0===si[v.name])return null;const _=si[g.name][0],y=si[g.name][1],b=si[v.name][0];if(_!==si[v.name][1])return null;const S=new Array(b*y);for(let g=0;gi*b[g]);return new Me(v,x.typeInfo)}}if(Ge(_)){const i=y,g=_.map((g,x)=>g*i);return x instanceof Ue?new Ue(g,x.typeInfo):new Me(g,x.typeInfo)}if(Ge(y)){const i=_,g=y.map((g,x)=>i*g);return v instanceof Ue?new Ue(g,v.typeInfo):new Me(g,v.typeInfo)}const g=_,b=y,S=this._maxFormatTypeInfo([x.typeInfo,v.typeInfo]);return new Be(g*b,S)}case"%":{if(Ge(_)&&Ge(y)){const g=_,v=y;if(g.length!==v.length)return console.error(`Vector length mismatch. Line ${i.line}.`),null;const b=g.map((i,g)=>i%v[g]);return new Me(b,x.typeInfo)}if(Ge(_)){const i=y,g=_.map((g,x)=>g%i);return new Me(g,x.typeInfo)}if(Ge(y)){const i=_,g=y.map((g,x)=>i%g);return new Me(g,v.typeInfo)}const g=_,b=y,S=this._maxFormatTypeInfo([x.typeInfo,v.typeInfo]);return new Be(g%b,S)}case"/":{if(Ge(_)&&Ge(y)){const g=_,v=y;if(g.length!==v.length)return console.error(`Vector length mismatch. Line ${i.line}.`),null;const b=g.map((i,g)=>i/v[g]);return new Me(b,x.typeInfo)}if(Ge(_)){const i=y,g=_.map((g,x)=>g/i);return new Me(g,x.typeInfo)}if(Ge(y)){const i=_,g=y.map((g,x)=>i/g);return new Me(g,v.typeInfo)}const g=_,b=y,S=this._maxFormatTypeInfo([x.typeInfo,v.typeInfo]);return new Be(g/b,S)}case"&":{if(Ge(_)&&Ge(y)){const g=_,v=y;if(g.length!==v.length)return console.error(`Vector length mismatch. Line ${i.line}.`),null;const b=g.map((i,g)=>i&v[g]);return new Me(b,x.typeInfo)}if(Ge(_)){const i=y,g=_.map((g,x)=>g&i);return new Me(g,x.typeInfo)}if(Ge(y)){const i=_,g=y.map((g,x)=>i&g);return new Me(g,v.typeInfo)}const g=_,b=y,S=this._maxFormatTypeInfo([x.typeInfo,v.typeInfo]);return new Be(g&b,S)}case"|":{if(Ge(_)&&Ge(y)){const g=_,v=y;if(g.length!==v.length)return console.error(`Vector length mismatch. Line ${i.line}.`),null;const b=g.map((i,g)=>i|v[g]);return new Me(b,x.typeInfo)}if(Ge(_)){const i=y,g=_.map((g,x)=>g|i);return new Me(g,x.typeInfo)}if(Ge(y)){const i=_,g=y.map((g,x)=>i|g);return new Me(g,v.typeInfo)}const g=_,b=y,S=this._maxFormatTypeInfo([x.typeInfo,v.typeInfo]);return new Be(g|b,S)}case"^":{if(Ge(_)&&Ge(y)){const g=_,v=y;if(g.length!==v.length)return console.error(`Vector length mismatch. Line ${i.line}.`),null;const b=g.map((i,g)=>i^v[g]);return new Me(b,x.typeInfo)}if(Ge(_)){const i=y,g=_.map((g,x)=>g^i);return new Me(g,x.typeInfo)}if(Ge(y)){const i=_,g=y.map((g,x)=>i^g);return new Me(g,v.typeInfo)}const g=_,b=y,S=this._maxFormatTypeInfo([x.typeInfo,v.typeInfo]);return new Be(g^b,S)}case"<<":{if(Ge(_)&&Ge(y)){const g=_,v=y;if(g.length!==v.length)return console.error(`Vector length mismatch. Line ${i.line}.`),null;const b=g.map((i,g)=>i<g<i<>":{if(Ge(_)&&Ge(y)){const g=_,v=y;if(g.length!==v.length)return console.error(`Vector length mismatch. Line ${i.line}.`),null;const b=g.map((i,g)=>i>>v[g]);return new Me(b,x.typeInfo)}if(Ge(_)){const i=y,g=_.map((g,x)=>g>>i);return new Me(g,x.typeInfo)}if(Ge(y)){const i=_,g=y.map((g,x)=>i>>g);return new Me(g,v.typeInfo)}const g=_,b=y,S=this._maxFormatTypeInfo([x.typeInfo,v.typeInfo]);return new Be(g>>b,S)}case">":if(Ge(_)&&Ge(y)){const g=_,v=y;if(g.length!==v.length)return console.error(`Vector length mismatch. Line ${i.line}.`),null;const b=g.map((i,g)=>i>v[g]?1:0);return new Me(b,x.typeInfo)}if(Ge(_)){const i=y,g=_.map((g,x)=>g>i?1:0);return new Me(g,x.typeInfo)}if(Ge(y)){const i=_,g=y.map((g,x)=>i>g?1:0);return new Me(g,v.typeInfo)}return new Be(_>y?1:0,this.getTypeInfo("bool"));case"<":if(Ge(_)&&Ge(y)){const g=_,v=y;if(g.length!==v.length)return console.error(`Vector length mismatch. Line ${i.line}.`),null;const b=g.map((i,g)=>igii===v[g]?1:0);return new Me(b,x.typeInfo)}if(Ge(_)){const i=y,g=_.map((g,x)=>g==i?1:0);return new Me(g,x.typeInfo)}if(Ge(y)){const i=_,g=y.map((g,x)=>i==g?1:0);return new Me(g,v.typeInfo)}return new Be(_===y?1:0,this.getTypeInfo("bool"));case"!=":if(Ge(_)&&Ge(y)){const g=_,v=y;if(g.length!==v.length)return console.error(`Vector length mismatch. Line ${i.line}.`),null;const b=g.map((i,g)=>i!==v[g]?1:0);return new Me(b,x.typeInfo)}if(Ge(_)){const i=y,g=_.map((g,x)=>g!==i?1:0);return new Me(g,x.typeInfo)}if(Ge(y)){const i=_,g=y.map((g,x)=>i!==g?1:0);return new Me(g,v.typeInfo)}return new Be(_!==y?1:0,this.getTypeInfo("bool"));case">=":if(Ge(_)&&Ge(y)){const g=_,v=y;if(g.length!==v.length)return console.error(`Vector length mismatch. Line ${i.line}.`),null;const b=g.map((i,g)=>i>=v[g]?1:0);return new Me(b,x.typeInfo)}if(Ge(_)){const i=y,g=_.map((g,x)=>g>=i?1:0);return new Me(g,x.typeInfo)}if(Ge(y)){const i=_,g=y.map((g,x)=>i>=g?1:0);return new Me(g,v.typeInfo)}return new Be(_>=y?1:0,this.getTypeInfo("bool"));case"<=":if(Ge(_)&&Ge(y)){const g=_,v=y;if(g.length!==v.length)return console.error(`Vector length mismatch. Line ${i.line}.`),null;const b=g.map((i,g)=>i<=v[g]?1:0);return new Me(b,x.typeInfo)}if(Ge(_)){const i=y,g=_.map((g,x)=>g<=i?1:0);return new Me(g,x.typeInfo)}if(Ge(y)){const i=_,g=y.map((g,x)=>i<=g?1:0);return new Me(g,v.typeInfo)}return new Be(_<=y?1:0,this.getTypeInfo("bool"));case"&&":if(Ge(_)&&Ge(y)){const g=_,v=y;if(g.length!==v.length)return console.error(`Vector length mismatch. Line ${i.line}.`),null;const b=g.map((i,g)=>i&&v[g]?1:0);return new Me(b,x.typeInfo)}if(Ge(_)){const i=y,g=_.map((g,x)=>g&&i?1:0);return new Me(g,x.typeInfo)}if(Ge(y)){const i=_,g=y.map((g,x)=>i&&g?1:0);return new Me(g,v.typeInfo)}return new Be(_&&y?1:0,this.getTypeInfo("bool"));case"||":if(Ge(_)&&Ge(y)){const g=_,v=y;if(g.length!==v.length)return console.error(`Vector length mismatch. Line ${i.line}.`),null;const b=g.map((i,g)=>i||v[g]?1:0);return new Me(b,x.typeInfo)}if(Ge(_)){const i=y,g=_.map((g,x)=>g||i?1:0);return new Me(g,x.typeInfo)}if(Ge(y)){const i=_,g=y.map((g,x)=>i||g?1:0);return new Me(g,v.typeInfo)}return new Be(_||y?1:0,this.getTypeInfo("bool"))}return console.error(`Unknown operator ${i.operator}. Line ${i.line}`),null}_evalCall(i,g){if(null!==i.cachedReturnValue)return i.cachedReturnValue;const x=g.clone();x.currentFunctionName=i.name;const v=g.getFunction(i.name);if(!v)return i.isBuiltin?this._callBuiltinFunction(i,x):this.getTypeInfo(i.name)?this._evalCreate(i,g):(console.error(`Unknown function "${i.name}". Line ${i.line}`),null);for(let g=0;g_?y.slice(0,_):y,x).getSubData(this,i.postfix,g)}_callConstructorMatrix(i,g){const x=this.getTypeInfo(i.type),v=i.type.getTypeName(),_=si[v];if(void 0===_)return console.error(`Invalid matrix constructor ${v}. Line ${i.line}`),null;const y=[];if(i instanceof xe)if(i.isVector){const g=i.vectorValue;for(const i of g)y.push(i)}else y.push(i.scalarValue);else if(i.args)for(const x of i.args){const i=this.evalExpression(x,g);i instanceof Me?y.push(...i.data):i instanceof Be?y.push(i.value):i instanceof Ue&&y.push(...i.data)}if(x instanceof a&&null===x.format&&(x.format=this.getTypeInfo("f32")),0===y.length){const v=new Array(_[2]).fill(0);return new Ue(v,x).getSubData(this,i.postfix,g)}return y.length!==_[2]?(console.error(`Invalid matrix constructor. Line ${i.line}`),null):new Ue(y,x).getSubData(this,i.postfix,g)}}dt._breakObj=new Ne(new e("BREAK",null),null),dt._continueObj=new Ne(new e("CONTINUE",null),null),dt._priority=new Map([["f32",0],["f16",1],["u32",2],["i32",3],["x32",3]]);class mt{constructor(){this.constants=new Map,this.aliases=new Map,this.structs=new Map}}class gt{constructor(){this._tokens=[],this._current=0,this._currentLine=1,this._deferArrayCountEval=[],this._currentLoop=[],this._context=new mt,this._exec=new dt,this._forwardTypeCount=0}parse(i){this._initialize(i),this._deferArrayCountEval.length=0;const g=[];for(;!this._isAtEnd();){const i=this._global_decl_or_directive();if(!i)break;g.push(i)}if(this._deferArrayCountEval.length>0){for(const g of this._deferArrayCountEval){const x=g.arrayType,v=g.countNode;if(v instanceof ge){const g=v.name,_=this._context.constants.get(g);if(_)try{const i=_.constEvaluate(this._exec);x.count=i}catch(i){}}}this._deferArrayCountEval.length=0}if(this._forwardTypeCount>0)for(const i of g)i.search(i=>{i instanceof Ce||i instanceof le?i.type=this._forwardType(i.type):i instanceof ue?i.format=this._forwardType(i.format):i instanceof F||i instanceof U||i instanceof P?i.type=this._forwardType(i.type):i instanceof D?i.returnType=this._forwardType(i.returnType):i instanceof $e&&(i.type=this._forwardType(i.type))});return g}_forwardType(i){if(i instanceof ie){const g=this._getType(i.name);if(g)return g}else i instanceof le?i.type=this._forwardType(i.type):i instanceof ue&&(i.format=this._forwardType(i.format));return i}_initialize(i){if(i)if("string"==typeof i){const g=new Re(i);this._tokens=g.scanTokens()}else this._tokens=i;else this._tokens=[];this._current=0}_updateNode(i,g){return i.line=null!=g?g:this._currentLine,i}_error(i,g){return{token:i,message:g,toString:()=>`${g}`}}_isAtEnd(){return this._current>=this._tokens.length||this._peek().type==He.eof}_match(i){if(i instanceof qe)return!!this._check(i)&&(this._advance(),!0);for(let g=0,x=i.length;g0){const i=this._currentLoop[this._currentLoop.length-1];g.loopId=i.id}i=g,this._check(He.keywords.if)&&(this._advance(),g.condition=this._optional_paren_expression())}else if(this._match(He.keywords.continue)){const g=this._updateNode(new re);if(!(this._currentLoop.length>0))throw this._error(this._peek(),`Continue statement must be inside a loop. Line: ${g.line}`);{const i=this._currentLoop[this._currentLoop.length-1];g.loopId=i.id}i=g}else i=this._increment_decrement_statement()||this._func_call_statement()||this._assignment_statement();return null!=i&&this._consume(He.tokens.semicolon,"Expected ';' after statement."),i}_static_assert_statement(){if(!this._match(He.keywords.static_assert))return null;const i=this._currentLine,g=this._optional_paren_expression();return this._updateNode(new N(g),i)}_while_statement(){if(!this._match(He.keywords.while))return null;const i=this._updateNode(new V(null,null));return this._currentLoop.push(i),i.condition=this._optional_paren_expression(),this._check(He.tokens.attr)&&this._attribute(),i.body=this._compound_statement(),this._currentLoop.pop(),i}_continuing_statement(){const i=this._currentLoop.length>0?this._currentLoop[this._currentLoop.length-1].id:-1;if(!this._match(He.keywords.continuing))return null;const g=this._currentLine,x=this._compound_statement();return this._updateNode(new O(x,i),g)}_for_statement(){if(!this._match(He.keywords.for))return null;this._consume(He.tokens.paren_left,"Expected '('.");const i=this._updateNode(new B(null,null,null,null));return this._currentLoop.push(i),i.init=this._check(He.tokens.semicolon)?null:this._for_init(),this._consume(He.tokens.semicolon,"Expected ';'."),i.condition=this._check(He.tokens.semicolon)?null:this._short_circuit_or_expression(),this._consume(He.tokens.semicolon,"Expected ';'."),i.increment=this._check(He.tokens.paren_right)?null:this._for_increment(),this._consume(He.tokens.paren_right,"Expected ')'."),this._check(He.tokens.attr)&&this._attribute(),i.body=this._compound_statement(),this._currentLoop.pop(),i}_for_init(){return this._variable_statement()||this._func_call_statement()||this._assignment_statement()}_for_increment(){return this._func_call_statement()||this._increment_decrement_statement()||this._assignment_statement()}_variable_statement(){if(this._check(He.keywords.var)){const i=this._variable_decl();if(null===i)throw this._error(this._peek(),"Variable declaration expected.");let g=null;return this._match(He.tokens.equal)&&(g=this._short_circuit_or_expression()),this._updateNode(new F(i.name,i.type,i.storage,i.access,g),i.line)}if(this._match(He.keywords.let)){const i=this._currentLine,g=this._consume(He.tokens.name,"Expected name for let.").toString();let x=null;if(this._match(He.tokens.colon)){const i=this._attribute();x=this._type_decl(),null!=x&&(x.attributes=i)}this._consume(He.tokens.equal,"Expected '=' for let.");const v=this._short_circuit_or_expression();return this._updateNode(new U(g,x,null,null,v),i)}if(this._match(He.keywords.const)){const i=this._currentLine,g=this._consume(He.tokens.name,"Expected name for const.").toString();let x=null;if(this._match(He.tokens.colon)){const i=this._attribute();x=this._type_decl(),null!=x&&(x.attributes=i)}this._consume(He.tokens.equal,"Expected '=' for const.");const v=this._short_circuit_or_expression();return null===x&&v instanceof xe&&(x=v.type),this._updateNode(new P(g,x,null,null,v),i)}return null}_increment_decrement_statement(){const i=this._current,g=this._unary_expression();if(null==g)return null;if(!this._check(He.increment_operators))return this._current=i,null;const x=this._consume(He.increment_operators,"Expected increment operator");return this._updateNode(new R(x.type===He.tokens.plus_plus?jr.increment:jr.decrement,g))}_assignment_statement(){let i=null;const g=this._currentLine;if(this._check(He.tokens.brace_right))return null;let x=this._match(He.tokens.underscore);if(x||(i=this._unary_expression()),!x&&null==i)return null;const v=this._consume(He.assignment_operators,"Expected assignment operator."),_=this._short_circuit_or_expression();return this._updateNode(new G(Kr.parse(v.lexeme),i,_),g)}_func_call_statement(){if(!this._check(He.tokens.ident))return null;const i=this._currentLine,g=this._current,x=this._consume(He.tokens.ident,"Expected function name."),v=this._argument_expression_list();return null===v?(this._current=g,null):this._updateNode(new X(x.lexeme,v),i)}_loop_statement(){if(!this._match(He.keywords.loop))return null;this._check(He.tokens.attr)&&this._attribute(),this._consume(He.tokens.brace_left,"Expected '{' for loop.");const i=this._updateNode(new j([],null));this._currentLoop.push(i);let g=this._statement();for(;null!==g;){if(Array.isArray(g))for(let x of g)i.body.push(x);else i.body.push(g);if(g instanceof O){i.continuing=g;break}g=this._statement()}return this._currentLoop.pop(),this._consume(He.tokens.brace_right,"Expected '}' for loop."),i}_switch_statement(){if(!this._match(He.keywords.switch))return null;const i=this._updateNode(new Z(null,[]));if(this._currentLoop.push(i),i.condition=this._optional_paren_expression(),this._check(He.tokens.attr)&&this._attribute(),this._consume(He.tokens.brace_left,"Expected '{' for switch."),i.cases=this._switch_body(),null==i.cases||0==i.cases.length)throw this._error(this._previous(),"Expected 'case' or 'default'.");return this._consume(He.tokens.brace_right,"Expected '}' for switch."),this._currentLoop.pop(),i}_switch_body(){const i=[];let g=!1;for(;this._check([He.keywords.default,He.keywords.case]);){if(this._match(He.keywords.case)){const x=this._case_selectors();for(const i of x)if(i instanceof Se){if(g)throw this._error(this._previous(),"Multiple default cases in switch statement.");g=!0;break}this._match(He.tokens.colon),this._check(He.tokens.attr)&&this._attribute(),this._consume(He.tokens.brace_left,"Exected '{' for switch case.");const v=this._case_body();this._consume(He.tokens.brace_right,"Exected '}' for switch case."),i.push(this._updateNode(new Ae(x,v)))}if(this._match(He.keywords.default)){if(g)throw this._error(this._previous(),"Multiple default cases in switch statement.");this._match(He.tokens.colon),this._check(He.tokens.attr)&&this._attribute(),this._consume(He.tokens.brace_left,"Exected '{' for switch default.");const x=this._case_body();this._consume(He.tokens.brace_right,"Exected '}' for switch default."),i.push(this._updateNode(new Ee(x)))}}return i}_case_selectors(){const i=[];for(this._match(He.keywords.default)?i.push(this._updateNode(new Se)):i.push(this._shift_expression());this._match(He.tokens.comma);)this._match(He.keywords.default)?i.push(this._updateNode(new Se)):i.push(this._shift_expression());return i}_case_body(){if(this._match(He.keywords.fallthrough))return this._consume(He.tokens.semicolon,"Expected ';'"),[];let i=this._statement();if(null==i)return[];i instanceof Array||(i=[i]);const g=this._case_body();return 0==g.length?i:[...i,g[0]]}_if_statement(){if(!this._match(He.keywords.if))return null;const i=this._currentLine,g=this._optional_paren_expression();this._check(He.tokens.attr)&&this._attribute();const x=this._compound_statement();let v=[];this._match_elseif()&&(this._check(He.tokens.attr)&&this._attribute(),v=this._elseif_statement(v));let _=null;return this._match(He.keywords.else)&&(this._check(He.tokens.attr)&&this._attribute(),_=this._compound_statement()),this._updateNode(new Q(g,x,v,_),i)}_match_elseif(){return this._tokens[this._current].type===He.keywords.else&&this._tokens[this._current+1].type===He.keywords.if&&(this._advance(),this._advance(),!0)}_elseif_statement(i=[]){const g=this._optional_paren_expression(),x=this._compound_statement();return i.push(this._updateNode(new Le(g,x))),this._match_elseif()&&(this._check(He.tokens.attr)&&this._attribute(),this._elseif_statement(i)),i}_return_statement(){if(!this._match(He.keywords.return))return null;const i=this._short_circuit_or_expression();return this._updateNode(new Y(i))}_short_circuit_or_expression(){let i=this._short_circuit_and_expr();for(;this._match(He.tokens.or_or);)i=this._updateNode(new Ie(this._previous().toString(),i,this._short_circuit_and_expr()));return i}_short_circuit_and_expr(){let i=this._inclusive_or_expression();for(;this._match(He.tokens.and_and);)i=this._updateNode(new Ie(this._previous().toString(),i,this._inclusive_or_expression()));return i}_inclusive_or_expression(){let i=this._exclusive_or_expression();for(;this._match(He.tokens.or);)i=this._updateNode(new Ie(this._previous().toString(),i,this._exclusive_or_expression()));return i}_exclusive_or_expression(){let i=this._and_expression();for(;this._match(He.tokens.xor);)i=this._updateNode(new Ie(this._previous().toString(),i,this._and_expression()));return i}_and_expression(){let i=this._equality_expression();for(;this._match(He.tokens.and);)i=this._updateNode(new Ie(this._previous().toString(),i,this._equality_expression()));return i}_equality_expression(){const i=this._relational_expression();return this._match([He.tokens.equal_equal,He.tokens.not_equal])?this._updateNode(new Ie(this._previous().toString(),i,this._relational_expression())):i}_relational_expression(){let i=this._shift_expression();for(;this._match([He.tokens.less_than,He.tokens.greater_than,He.tokens.less_than_equal,He.tokens.greater_than_equal]);)i=this._updateNode(new Ie(this._previous().toString(),i,this._shift_expression()));return i}_shift_expression(){let i=this._additive_expression();for(;this._match([He.tokens.shift_left,He.tokens.shift_right]);)i=this._updateNode(new Ie(this._previous().toString(),i,this._additive_expression()));return i}_additive_expression(){let i=this._multiplicative_expression();for(;this._match([He.tokens.plus,He.tokens.minus]);)i=this._updateNode(new Ie(this._previous().toString(),i,this._multiplicative_expression()));return i}_multiplicative_expression(){let i=this._unary_expression();for(;this._match([He.tokens.star,He.tokens.forward_slash,He.tokens.modulo]);)i=this._updateNode(new Ie(this._previous().toString(),i,this._unary_expression()));return i}_unary_expression(){return this._match([He.tokens.minus,He.tokens.bang,He.tokens.tilde,He.tokens.star,He.tokens.and])?this._updateNode(new ke(this._previous().toString(),this._unary_expression())):this._singular_expression()}_singular_expression(){const i=this._primary_expression(),g=this._postfix_expression();return g&&(i.postfix=g),i}_postfix_expression(){if(this._match(He.tokens.bracket_left)){const i=this._short_circuit_or_expression();this._consume(He.tokens.bracket_right,"Expected ']'.");const g=this._updateNode(new ve(i)),x=this._postfix_expression();return x&&(g.postfix=x),g}if(this._match(He.tokens.period)){const i=this._consume(He.tokens.name,"Expected member name."),g=this._postfix_expression(),x=this._updateNode(new pe(i.lexeme));return g&&(x.postfix=g),x}return null}_getStruct(i){return this._context.aliases.has(i)?this._context.aliases.get(i).type:this._context.structs.has(i)?this._context.structs.get(i):null}_getType(i){const g=this._getStruct(i);if(null!==g)return g;switch(i){case"void":return ae.void;case"bool":return ae.bool;case"i32":return ae.i32;case"u32":return ae.u32;case"f32":return ae.f32;case"f16":return ae.f16;case"vec2f":return ce.vec2f;case"vec3f":return ce.vec3f;case"vec4f":return ce.vec4f;case"vec2i":return ce.vec2i;case"vec3i":return ce.vec3i;case"vec4i":return ce.vec4i;case"vec2u":return ce.vec2u;case"vec3u":return ce.vec3u;case"vec4u":return ce.vec4u;case"vec2h":return ce.vec2h;case"vec3h":return ce.vec3h;case"vec4h":return ce.vec4h;case"mat2x2f":return ce.mat2x2f;case"mat2x3f":return ce.mat2x3f;case"mat2x4f":return ce.mat2x4f;case"mat3x2f":return ce.mat3x2f;case"mat3x3f":return ce.mat3x3f;case"mat3x4f":return ce.mat3x4f;case"mat4x2f":return ce.mat4x2f;case"mat4x3f":return ce.mat4x3f;case"mat4x4f":return ce.mat4x4f;case"mat2x2h":return ce.mat2x2h;case"mat2x3h":return ce.mat2x3h;case"mat2x4h":return ce.mat2x4h;case"mat3x2h":return ce.mat3x2h;case"mat3x3h":return ce.mat3x3h;case"mat3x4h":return ce.mat3x4h;case"mat4x2h":return ce.mat4x2h;case"mat4x3h":return ce.mat4x3h;case"mat4x4h":return ce.mat4x4h;case"mat2x2i":return ce.mat2x2i;case"mat2x3i":return ce.mat2x3i;case"mat2x4i":return ce.mat2x4i;case"mat3x2i":return ce.mat3x2i;case"mat3x3i":return ce.mat3x3i;case"mat3x4i":return ce.mat3x4i;case"mat4x2i":return ce.mat4x2i;case"mat4x3i":return ce.mat4x3i;case"mat4x4i":return ce.mat4x4i;case"mat2x2u":return ce.mat2x2u;case"mat2x3u":return ce.mat2x3u;case"mat2x4u":return ce.mat2x4u;case"mat3x2u":return ce.mat3x2u;case"mat3x3u":return ce.mat3x3u;case"mat3x4u":return ce.mat3x4u;case"mat4x2u":return ce.mat4x2u;case"mat4x3u":return ce.mat4x3u;case"mat4x4u":return ce.mat4x4u}return null}_validateTypeRange(i,g){if("i32"===g.name){if(i<-2147483648||i>2147483647)throw this._error(this._previous(),`Value out of range for i32: ${i}. Line: ${this._currentLine}.`)}else if("u32"===g.name&&(i<0||i>4294967295))throw this._error(this._previous(),`Value out of range for u32: ${i}. Line: ${this._currentLine}.`)}_primary_expression(){if(this._match(He.tokens.ident)){const i=this._previous().toString();if(this._check(He.tokens.paren_left)){const g=this._argument_expression_list(),x=this._getType(i);return null!==x?this._updateNode(new de(x,g)):this._updateNode(new me(i,g))}if(this._context.constants.has(i)){const g=this._context.constants.get(i);return this._updateNode(new _e(i,g.value))}return this._updateNode(new ge(i))}if(this._match(He.tokens.int_literal)){const i=this._previous().toString();let g=i.endsWith("i")||i.endsWith("i")?ae.i32:i.endsWith("u")||i.endsWith("U")?ae.u32:ae.x32;const x=parseInt(i);return this._validateTypeRange(x,g),this._updateNode(new xe(new Be(x,this._exec.getTypeInfo(g)),g))}if(this._match(He.tokens.uint_literal)){const i=parseInt(this._previous().toString());return this._validateTypeRange(i,ae.u32),this._updateNode(new xe(new Be(i,this._exec.getTypeInfo(ae.u32)),ae.u32))}if(this._match([He.tokens.decimal_float_literal,He.tokens.hex_float_literal])){let i=this._previous().toString(),g=i.endsWith("h");g&&(i=i.substring(0,i.length-1));const x=parseFloat(i);this._validateTypeRange(x,g?ae.f16:ae.f32);const v=g?ae.f16:ae.f32;return this._updateNode(new xe(new Be(x,this._exec.getTypeInfo(v)),v))}if(this._match([He.keywords.true,He.keywords.false])){let i=this._previous().toString()===He.keywords.true.rule;return this._updateNode(new xe(new Be(i?1:0,this._exec.getTypeInfo(ae.bool)),ae.bool))}if(this._check(He.tokens.paren_left))return this._paren_expression();if(this._match(He.keywords.bitcast)){this._consume(He.tokens.less_than,"Expected '<'.");const i=this._type_decl();this._consume(He.tokens.greater_than,"Expected '>'.");const g=this._paren_expression();return this._updateNode(new ye(i,g))}const i=this._type_decl(),g=this._argument_expression_list();return this._updateNode(new de(i,g))}_argument_expression_list(){if(!this._match(He.tokens.paren_left))return null;const i=[];do{if(this._check(He.tokens.paren_right))break;const g=this._short_circuit_or_expression();i.push(g)}while(this._match(He.tokens.comma));return this._consume(He.tokens.paren_right,"Expected ')' for agument list"),i}_optional_paren_expression(){this._match(He.tokens.paren_left);const i=this._short_circuit_or_expression();return this._match(He.tokens.paren_right),i}_paren_expression(){this._consume(He.tokens.paren_left,"Expected '('.");const i=this._short_circuit_or_expression();return this._consume(He.tokens.paren_right,"Expected ')'."),i}_struct_decl(){if(!this._match(He.keywords.struct))return null;const i=this._currentLine,g=this._consume(He.tokens.ident,"Expected name for struct.").toString();this._consume(He.tokens.brace_left,"Expected '{' for struct body.");const x=[];for(;!this._check(He.tokens.brace_right);){const i=this._attribute(),g=this._consume(He.tokens.name,"Expected variable name.").toString();this._consume(He.tokens.colon,"Expected ':' for struct member type.");const v=this._attribute(),_=this._type_decl();null!=_&&(_.attributes=v),this._check(He.tokens.brace_right)?this._match(He.tokens.comma):this._consume(He.tokens.comma,"Expected ',' for struct member."),x.push(this._updateNode(new Ce(g,_,i)))}this._consume(He.tokens.brace_right,"Expected '}' after struct body.");const v=this._currentLine,_=this._updateNode(new oe(g,x,i,v),i);return this._context.structs.set(g,_),_}_global_variable_decl(){const i=this._variable_decl();if(!i)return null;if(this._match(He.tokens.equal)){const g=this._const_expression();i.value=g}if(null!==i.type&&i.value instanceof xe){if("x32"!==i.value.type.name&&i.type.getTypeName()!==i.value.type.getTypeName())throw this._error(this._peek(),`Invalid cast from ${i.value.type.name} to ${i.type.name}. Line:${this._currentLine}`);i.value.isScalar&&this._validateTypeRange(i.value.scalarValue,i.type),i.value.type=i.type}else null===i.type&&i.value instanceof xe&&(i.type="x32"===i.value.type.name?ae.i32:i.value.type,i.value.isScalar&&this._validateTypeRange(i.value.scalarValue,i.type));return i}_override_variable_decl(){const i=this._override_decl();return i&&this._match(He.tokens.equal)&&(i.value=this._const_expression()),i}_global_const_decl(){var i;if(!this._match(He.keywords.const))return null;const g=this._consume(He.tokens.name,"Expected variable name"),x=this._currentLine;let v=null;if(this._match(He.tokens.colon)){const i=this._attribute();v=this._type_decl(),null!=v&&(v.attributes=i)}let _=null;this._consume(He.tokens.equal,"const declarations require an assignment");const y=this._short_circuit_or_expression();try{let i=[ae.f32],x=y.constEvaluate(this._exec,i);x instanceof Be&&this._validateTypeRange(x.value,i[0]),i[0]instanceof ce&&null===i[0].format&&x.typeInfo instanceof a&&null!==x.typeInfo.format&&("f16"===x.typeInfo.format.name?i[0].format=ae.f16:"f32"===x.typeInfo.format.name?i[0].format=ae.f32:"i32"===x.typeInfo.format.name?i[0].format=ae.i32:"u32"===x.typeInfo.format.name?i[0].format=ae.u32:"bool"===x.typeInfo.format.name?i[0].format=ae.bool:console.error(`TODO: impelement template format type ${x.typeInfo.format.name}`)),_=this._updateNode(new xe(x,i[0])),this._exec.context.setVariable(g.toString(),x)}catch(i){_=y}if(null!==v&&_ instanceof xe){if("x32"!==_.type.name&&v.getTypeName()!==_.type.getTypeName())throw this._error(this._peek(),`Invalid cast from ${_.type.name} to ${v.name}. Line:${this._currentLine}`);_.type=v,_.isScalar&&this._validateTypeRange(_.scalarValue,_.type)}else null===v&&_ instanceof xe&&(v=null!==(i=null==_?void 0:_.type)&&void 0!==i?i:ae.f32,v===ae.x32&&(v=ae.i32));const b=this._updateNode(new P(g.toString(),v,"","",_),x);return this._context.constants.set(b.name,b),b}_global_let_decl(){if(!this._match(He.keywords.let))return null;const i=this._currentLine,g=this._consume(He.tokens.name,"Expected variable name");let x=null;if(this._match(He.tokens.colon)){const i=this._attribute();x=this._type_decl(),null!=x&&(x.attributes=i)}let v=null;if(this._match(He.tokens.equal)&&(v=this._const_expression()),null!==x&&v instanceof xe){if("x32"!==v.type.name&&x.getTypeName()!==v.type.getTypeName())throw this._error(this._peek(),`Invalid cast from ${v.type.name} to ${x.name}. Line:${this._currentLine}`);v.type=x}else null===x&&v instanceof xe&&(x="x32"===v.type.name?ae.i32:v.type);return v instanceof xe&&v.isScalar&&this._validateTypeRange(v.scalarValue,x),this._updateNode(new U(g.toString(),x,"","",v),i)}_const_expression(){return this._short_circuit_or_expression()}_variable_decl(){if(!this._match(He.keywords.var))return null;const i=this._currentLine;let g="",x="";this._match(He.tokens.less_than)&&(g=this._consume(He.storage_class,"Expected storage_class.").toString(),this._match(He.tokens.comma)&&(x=this._consume(He.access_mode,"Expected access_mode.").toString()),this._consume(He.tokens.greater_than,"Expected '>'."));const v=this._consume(He.tokens.name,"Expected variable name");let _=null;if(this._match(He.tokens.colon)){const i=this._attribute();_=this._type_decl(),null!=_&&(_.attributes=i)}return this._updateNode(new F(v.toString(),_,g,x,null),i)}_override_decl(){if(!this._match(He.keywords.override))return null;const i=this._consume(He.tokens.name,"Expected variable name");let g=null;if(this._match(He.tokens.colon)){const i=this._attribute();g=this._type_decl(),null!=g&&(g.attributes=i)}return this._updateNode(new M(i.toString(),g,null))}_diagnostic(){this._consume(He.tokens.paren_left,"Expected '('");const i=this._consume(He.tokens.ident,"Expected severity control name.");this._consume(He.tokens.comma,"Expected ','");let g=this._consume(He.tokens.ident,"Expected diagnostic rule name.").toString();return this._match(He.tokens.period)&&(g+=`.${this._consume(He.tokens.ident,"Expected diagnostic message.").toString()}`),this._consume(He.tokens.paren_right,"Expected ')'"),this._updateNode(new ee(i.toString(),g))}_enable_directive(){const i=this._consume(He.tokens.ident,"identity expected.");return this._updateNode(new K(i.toString()))}_requires_directive(){const i=[this._consume(He.tokens.ident,"identity expected.").toString()];for(;this._match(He.tokens.comma);){const g=this._consume(He.tokens.ident,"identity expected.");i.push(g.toString())}return this._updateNode(new J(i))}_type_alias(){const i=this._consume(He.tokens.ident,"identity expected.");this._consume(He.tokens.equal,"Expected '=' for type alias.");let g=this._type_decl();if(null===g)throw this._error(this._peek(),"Expected Type for Alias.");this._context.aliases.has(g.name)&&(g=this._context.aliases.get(g.name).type);const x=this._updateNode(new te(i.toString(),g));return this._context.aliases.set(x.name,x),x}_type_decl(){if(this._check([He.tokens.ident,...He.texel_format,He.keywords.bool,He.keywords.f32,He.keywords.i32,He.keywords.u32])){const i=this._advance().toString();if(this._context.structs.has(i))return this._context.structs.get(i);if(this._context.aliases.has(i))return this._context.aliases.get(i).type;if(!this._getType(i)){const g=this._updateNode(new ie(i));return this._forwardTypeCount++,g}return this._updateNode(new ae(i))}let i=this._texture_sampler_types();if(i)return i;if(this._check(He.template_types)){let i=this._advance().toString(),g=null,x=null;return this._match(He.tokens.less_than)&&(g=this._type_decl(),x=null,this._match(He.tokens.comma)&&(x=this._consume(He.access_mode,"Expected access_mode for pointer").toString()),this._consume(He.tokens.greater_than,"Expected '>' for type.")),this._updateNode(new ce(i,g,x))}if(this._match(He.keywords.ptr)){let i=this._previous().toString();this._consume(He.tokens.less_than,"Expected '<' for pointer.");const g=this._consume(He.storage_class,"Expected storage_class for pointer");this._consume(He.tokens.comma,"Expected ',' for pointer.");const x=this._type_decl();let v=null;return this._match(He.tokens.comma)&&(v=this._consume(He.access_mode,"Expected access_mode for pointer").toString()),this._consume(He.tokens.greater_than,"Expected '>' for pointer."),this._updateNode(new le(i,g.toString(),x,v))}const g=this._attribute();if(this._match(He.keywords.array)){let x=null,v=-1;const _=this._previous();let y=null;if(this._match(He.tokens.less_than)){x=this._type_decl(),this._context.aliases.has(x.name)&&(x=this._context.aliases.get(x.name).type);let g="";if(this._match(He.tokens.comma)){y=this._shift_expression();try{g=y.constEvaluate(this._exec).toString(),y=null}catch(i){g="1"}}this._consume(He.tokens.greater_than,"Expected '>' for array."),v=g?parseInt(g):0}const b=this._updateNode(new ue(_.toString(),g,x,v));return y&&this._deferArrayCountEval.push({arrayType:b,countNode:y}),b}return null}_texture_sampler_types(){if(this._match(He.sampler_type))return this._updateNode(new he(this._previous().toString(),null,null));if(this._match(He.depth_texture_type))return this._updateNode(new he(this._previous().toString(),null,null));if(this._match(He.sampled_texture_type)||this._match(He.multisampled_texture_type)){const i=this._previous();this._consume(He.tokens.less_than,"Expected '<' for sampler type.");const g=this._type_decl();return this._consume(He.tokens.greater_than,"Expected '>' for sampler type."),this._updateNode(new he(i.toString(),g,null))}if(this._match(He.storage_texture_type)){const i=this._previous();this._consume(He.tokens.less_than,"Expected '<' for sampler type.");const g=this._consume(He.texel_format,"Invalid texel format.").toString();this._consume(He.tokens.comma,"Expected ',' after texel format.");const x=this._consume(He.access_mode,"Expected access mode for storage texture type.").toString();return this._consume(He.tokens.greater_than,"Expected '>' for sampler type."),this._updateNode(new he(i.toString(),g,x))}return null}_attribute(){let i=[];for(;this._match(He.tokens.attr);){const g=this._consume(He.attribute_name,"Expected attribute name"),x=this._updateNode(new De(g.toString(),null));if(this._match(He.tokens.paren_left)){if(x.value=this._consume(He.literal_or_ident,"Expected attribute value").toString(),this._check(He.tokens.comma)){this._advance();do{const i=this._consume(He.literal_or_ident,"Expected attribute value").toString();x.value instanceof Array||(x.value=[x.value]),x.value.push(i)}while(this._match(He.tokens.comma))}this._consume(He.tokens.paren_right,"Expected ')'")}i.push(x)}return 0==i.length?null:i}}class _t extends at{constructor(i){super(),i&&this.update(i)}update(i){const g=(new gt).parse(i);this.updateAST(g)}}function ensureVertexIndexBuiltin(i){if(/@builtin\s*\(\s*vertex_index\s*\)/.test(i))return i;return i.replace(/(@vertex\s+fn\s+)([a-zA-Z_][a-zA-Z0-9_]*)\s*\(([^)]*)(\))/,(i,g,x,v,_)=>{const y=v.trim(),b="@builtin(vertex_index) redgpu_auto_builtin_vertex_index: u32";return`${g}${x}(${0===y.length?b:`${y}, ${b}`}${_}`})}class WGSLUniformTypes{static get i32(){return{numElements:1,align:4,size:4,type:"i32",wgslType:"i32",View:Int32Array}}static get u32(){return{numElements:1,align:4,size:4,type:"u32",wgslType:"u32",View:Uint32Array}}static get f32(){return{numElements:1,align:4,size:4,type:"f32",wgslType:"f32",View:Float32Array}}static get f16(){return{numElements:1,align:2,size:2,type:"f16",wgslType:"f16",View:Uint16Array}}static get vec2f32(){return{numElements:2,align:8,size:8,type:"f32",wgslType:"vec2",View:Float32Array}}static get vec2i32(){return{numElements:2,align:8,size:8,type:"i32",wgslType:"vec2",View:Int32Array}}static get vec2u32(){return{numElements:2,align:8,size:8,type:"u32",wgslType:"vec2",View:Uint32Array}}static get vec2u16(){return{numElements:2,align:4,size:4,type:"u16",wgslType:"vec2",View:Uint16Array}}static get vec3i32(){return{numElements:3,align:16,size:12,type:"i32",wgslType:"vec3",View:Int32Array}}static get vec3u32(){return{numElements:3,align:16,size:12,type:"u32",wgslType:"vec3",View:Uint32Array}}static get vec3f32(){return{numElements:3,align:16,size:12,type:"f32",wgslType:"vec3",View:Float32Array}}static get vec3u16(){return{numElements:3,align:8,size:6,type:"u16",wgslType:"vec3",View:Uint16Array}}static get vec4i32(){return{numElements:4,align:16,size:16,type:"i32",wgslType:"vec4",View:Int32Array}}static get vec4u32(){return{numElements:4,align:16,size:16,type:"u32",wgslType:"vec4",View:Uint32Array}}static get vec4f32(){return{numElements:4,align:16,size:16,type:"f32",wgslType:"vec4",View:Float32Array}}static get vec4u16(){return{numElements:4,align:8,size:8,type:"u16",wgslType:"vec4",View:Uint16Array}}static get mat2x2f32(){return{numElements:4,align:8,size:16,type:"f32",wgslType:"mat2x2",View:Float32Array}}static get mat2x2u16(){return{numElements:4,align:4,size:8,type:"u16",wgslType:"mat2x2",View:Uint16Array}}static get mat3x2f32(){return{numElements:6,align:8,size:24,type:"f32",wgslType:"mat3x2",View:Float32Array}}static get mat3x2u16(){return{numElements:6,align:4,size:12,type:"u16",wgslType:"mat3x2",View:Uint16Array}}static get mat3x3f32(){return{numElements:16,align:16,size:64,type:"f32",wgslType:"mat3x3",View:Float32Array}}static get mat4x2f32(){return{numElements:8,align:8,size:32,type:"f32",wgslType:"mat4x2",View:Float32Array}}static get mat4x2u16(){return{numElements:8,align:4,size:16,type:"u16",wgslType:"mat4x2",View:Uint16Array}}static get mat2x3f32(){return{numElements:8,align:16,size:32,type:"f32",wgslType:"mat2x3",View:Float32Array}}static get mat2x3u16(){return{numElements:8,align:8,size:16,type:"u16",wgslType:"mat2x3",View:Uint16Array}}static get mat4x4f32(){return{numElements:16,align:16,size:64,type:"f32",wgslType:"mat4x4",View:Float32Array}}static get mat4x4u16(){return{numElements:16,align:8,size:32,type:"u16",wgslType:"mat4x4",View:Uint16Array}}}Object.freeze(WGSLUniformTypes);const processMembers=(i,g=0,x=0)=>{let v=0,_=x;const y=i?.reduce((i,x,y)=>{const{type:b,offset:S,size:w,stride:L,count:k,isArray:H}=x,{format:z}=b,q="array"===b.name?`${z.name}${z.format?`${z.format.name}`:""}`:`${b.name}${z?`${z.name}`:""}`;if(v=g,_=S+w,i[x.name]=((i,g,x)=>{const v=WGSLUniformTypes[x];return{uniformOffset:i.offset+g,uniformOffsetForData:i.offset,stride:i.stride,isArray:i.isArray,typeInfo:v,View:v?.View}})(x,g,q),H&&z.members){const g=processMembers(z.members).members;i[x.name].memberList=Array.from({length:k},(i,x)=>{const v={};for(const i in g){const _=v[i]={...g[i]};_.uniformOffset=_.uniformOffset+S+L*x}return v})}else b.members&&(i[x.name]=processMembers(b.members,S+g,_));return i},{});return{members:y,startOffset:v,endOffset:_}},oi=new Map,parseWGSL=(i,g,x)=>{if(!i)throw new Error(`[parseWGSL] sourceName is required. (provided: ${i})`);g=ensureVertexIndexBuiltin(g);const{defaultSource:v,shaderSourceVariant:_,conditionalBlocks:y,cacheKey:b}=preprocessWGSL(i,g,x),S=oi.get(b);let w;if(S)w=S;else{const i=new _t(v);w={uniforms:{...(k=i.uniforms,k.reduce((i,g)=>(i[g.name]={name:g.name,...processMembers(g.members),arrayBufferByteLength:g.size,stride:g.stride},g.attributes?.forEach(x=>i[g.name][x.name]=+x.value),i),{}))},storage:{...(L=i.storage,L.reduce((i,g)=>(i[g.name]={name:g.name,...processMembers(g.members),arrayBufferByteLength:g.size,stride:g.stride,acccess:g.access,type:g.type},g.attributes?.forEach(x=>i[g.name][x.name]=+x.value),i),{}))},samplers:i.samplers,textures:i.textures,vertexEntries:i.entry.vertex.map(i=>i.name),fragmentEntries:i.entry.fragment.map(i=>i.name),computeEntries:i.entry.compute.map(i=>i.name)},_.setBaseInfo(w.textures,w.samplers),y.forEach(i=>{const g=_.getVariant(i),x=new _t(g),v=x.textures.filter(i=>!w.textures.find(g=>g.name===i.name)),y=x.samplers.filter(i=>!w.samplers.find(g=>g.name===i.name));_.addConditionalInfo(i,v,y)}),w.textures=_.getUnionTextures(),w.samplers=_.getUnionSamplers(),oi.set(b,w)}var L,k;return{...w,defaultSource:v,shaderSourceVariant:_,conditionalBlocks:y}},ui={ZERO:"zero",ONE:"one",SRC:"src",ONE_MINUS_SRC:"one-minus-src",SRC_ALPHA:"src-alpha",ONE_MINUS_SRC_ALPHA:"one-minus-src-alpha",DST:"dst",ONE_MINUS_DST:"one-minus-dst",DST_ALPHA:"dst-alpha",ONE_MINUS_DST_ALPHA:"one-minus-dst-alpha",SRC_ALPHA_SATURATED:"src-alpha-saturated",CONSTANT:"constant",ONE_MINUS_CONSTANT:"one-minus-constant",SRC1:"src1",ONE_MINUS_SRC1:"one-minus-src1",SRC1_ALPHA:"src1-alpha",ONE_MINUS_SRC1_ALPHA:"one-minus-src1-alpha"};Object.freeze(ui);const li={ADD:"add",SUBTRACT:"subtract",REVERSE_SUBTRACT:"reverse-subtract",MIN:"min",MAX:"max"};Object.freeze(li);const ci=Object.values(ui),hi=Object.values(li);class BlendState{state;#Yt;#Wt;#Zt;#Jt;constructor(i,g=ui.SRC_ALPHA,x=ui.ONE_MINUS_SRC_ALPHA,v=li.ADD){this.#Jt=i,this.srcFactor=g,this.dstFactor=x,this.operation=v}get operation(){return this.#Zt}set operation(i){hi.includes(i)||consoleAndThrowError(`Invalid GPUBlendOperation: ${i}. Valid operations are ${hi.join(", ")}`),this.#Zt=i,this.#Qt()}get srcFactor(){return this.#Yt}set srcFactor(i){ci.includes(i)||consoleAndThrowError(`Invalid GPUBlendFactor: ${i}. Valid srcFactor factors are ${ci.join(", ")}`),this.#Yt=i,this.#Qt()}get dstFactor(){return this.#Wt}set dstFactor(i){ci.includes(i)||consoleAndThrowError(`Invalid GPUBlendFactor: ${i}. Valid dstFactor factors are ${ci.join(", ")}`),this.#Wt=i,this.#Qt()}#Qt(){const i=this.#Zt?{operation:this.#Zt}:{},g=this.#Yt?{srcFactor:this.#Yt}:{},x=this.#Wt?{dstFactor:this.#Wt}:{};this.state={...i,...g,...x},this.#Jt.dirtyPipeline=!0}}const fi=new Map,di=new WeakMap;let mi,pi,gi;class PackedTexture extends RedGPUObject{#ne;#V;#er;#me=new Map;constructor(i){super(i),this.#tr(),this.#ne=this.#rr()}get gpuTexture(){return this.#V}static getCacheMap(){return fi}async packing(i,g,x,v,_,y){const b={r:"r",g:"g",b:"b",a:"a",..._},S=`${i.r?.label||""}_${i.g?.label||""}_${i.b?.label||""}_${i.a?.label||""}`,w=`${JSON.stringify(b)}_${S}`;if(!(i.r||i.g||i.b||i.a))return;this.#ir(w);fi.get(w)||await this.#nr(i,g,x,v,b,w,y)}destroy(){const i=di.get(this);if(i){const g=fi.get(i);g&&(g.useNum--,0===g.useNum&&(g.gpuTexture?.destroy(),fi.delete(i))),di.delete(this)}}#tr(){const{resourceManager:i}=this;gi=i.createGPUBuffer("PACK_TEXTURE_MAPPING_BUFFER",{size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),pi||(pi=i.createBindGroupLayout("PACK_TEXTURE_BIND_GROUP_LAYOUT",{entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:2,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:3,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:4,visibility:GPUShaderStage.FRAGMENT,sampler:{}},{binding:5,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]})),mi||(mi=this.#ar())}#sr(i){const g=`${i.r?.label||"empty"}_${i.g?.label||"empty"}_${i.b?.label||"empty"}_${i.a?.label||"empty"}`,{resourceManager:x,gpuDevice:v}=this;if(!this.#me.has(g)){const _=[{binding:0,resource:x.getGPUResourceBitmapTextureView(i.r)},{binding:1,resource:x.getGPUResourceBitmapTextureView(i.g)},{binding:2,resource:x.getGPUResourceBitmapTextureView(i.b)},{binding:3,resource:x.getGPUResourceBitmapTextureView(i.a)},{binding:4,resource:this.#ne},{binding:5,resource:{buffer:gi}}],y=v.createBindGroup({label:`PACK_TEXTURE_BIND_GROUP_${g}`,layout:pi,entries:_});this.#me.set(g,y)}this.#er=this.#me.get(g)}#ir(i){const g=di.get(this);if(g&&g!==i){const i=fi.get(g);i&&(i.useNum--,0===i.useNum&&(i.gpuTexture?.destroy(),fi.delete(g)))}const x=fi.get(i);x&&(this.#V=x.gpuTexture,x.useNum++),di.set(this,i)}async#nr(i,g,x,v,_,y,b){const S={size:[g,x,1],format:"rgba8unorm",usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC,label:v||`PACK_TEXTURE_${createUUID()}`,mipLevelCount:getMipLevelCount(g,x)};this.#V&&(this.#V=null);const{resourceManager:w,gpuDevice:L,uuid:k}=this,H=w.createManagedTexture(S),z=new Uint32Array([["r","g","b","a"].indexOf(_.r),["r","g","b","a"].indexOf(_.g),["r","g","b","a"].indexOf(_.b),["r","g","b","a"].indexOf(_.a)]);L.queue.writeBuffer(gi,0,z),this.#sr(i),this.#or(H,b),this.#V=S.mipLevelCount>1?w.mipmapGenerator.generateMipmap(H,S,!0):H,fi.set(y,{gpuTexture:this.#V,useNum:1,mappingKey:y,uuid:k}),this.#er=null}#or(i,g){const{resourceManager:x,gpuDevice:v}=this,_=g||v.createCommandEncoder({label:"PackedTexture_CommandEncoder"}),y=_.beginRenderPass({colorAttachments:[{view:x.getGPUResourceBitmapTextureView(i,{baseMipLevel:0,mipLevelCount:1,dimension:"2d",label:`${i.label}_RENDER_TARGET`}),loadOp:"clear",storeOp:"store",clearValue:[0,0,0,0]}]});y.setPipeline(mi),y.setBindGroup(0,this.#er),y.draw(6,1,0,0),y.end(),g||v.queue.submit([_.finish()])}#ar(){const i="struct VertexOutput{@builtin(position)position:vec4,@location(0)uv:vec2,};@vertex fn vertexMain(@builtin(vertex_index)VertexIndex:u32)->VertexOutput{var pos=array,6>(vec2(-1.0,-1.0),vec2(1.0,-1.0),vec2(-1.0,1.0),vec2(-1.0,1.0),vec2(1.0,-1.0),vec2(1.0,1.0));var uv=array,6>(vec2(.0,1.0),vec2(1.0,1.0),vec2(.0,.0),vec2(.0,.0),vec2(1.0,1.0),vec2(1.0,.0));var output:VertexOutput;output.position=vec4(pos[VertexIndex],.0,1.0);output.uv=uv[VertexIndex];return output;}struct ComponentMapping{r_component:u32,g_component:u32,b_component:u32,a_component:u32,};@group(0)@binding(0)var textureR:texture_2d;@group(0)@binding(1)var textureG:texture_2d;@group(0)@binding(2)var textureB:texture_2d;@group(0)@binding(3)var textureA:texture_2d;@group(0)@binding(4)var sampler0:sampler;@group(0)@binding(5)varmapping:ComponentMapping;fn getComponent(color:vec4,componentIndex:u32)->f32{switch componentIndex{case 0u:{return color.r;}case 1u:{return color.g;}case 2u:{return color.b;}case 3u:{return color.a;}default:{return .0;}}}@fragment fn fragmentMain(input:VertexOutput)->@location(0)vec4{let colorR=textureSample(textureR,sampler0,input.uv);let colorG=textureSample(textureG,sampler0,input.uv);let colorB=textureSample(textureB,sampler0,input.uv);let colorA=textureSample(textureA,sampler0,input.uv);let r=getComponent(colorR,mapping.r_component);let g=getComponent(colorG,mapping.g_component);let b=getComponent(colorB,mapping.b_component);let a=getComponent(colorA,mapping.a_component);return vec4(r,g,b,a);}",{resourceManager:g,gpuDevice:x}=this,v=x.createPipelineLayout({label:"PACK_TEXTURE_PIPELINE_LAYOUT",bindGroupLayouts:[pi]});return x.createRenderPipeline({label:"PACK_TEXTURE_PIPELINE",layout:v,vertex:{module:g.createGPUShaderModule("PACK_TEXTURE_SHADER_MODULE",{code:i}),entryPoint:"vertexMain"},fragment:{module:g.createGPUShaderModule("PACK_TEXTURE_SHADER_MODULE",{code:i}),entryPoint:"fragmentMain",targets:[{format:"rgba8unorm"}]},primitive:{topology:"triangle-list"}})}#rr(){return new Sampler(this.redGPUContext).gpuSampler}}const xi={NORMAL:0,MULTIPLY:1,LIGHTEN:2,SCREEN:3,LINEAR_DODGE:4,SUBTRACT:5,DARKEN:6,OVERLAY:7,COLOR_DODGE:8,COLOR_BURN:9,HARD_LIGHT:10,SOFT_LIGHT:11,DIFFERENCE:12,EXCLUSION:13,DIVIDE:14,VIVID_LIGHT:15,LINEAR_BURN:16,PIN_LIGHT:17,SATURATION:18,HUE:19,LUMINOSITY:20,COLOR:21,NEGATION:22};class FragmentGPURenderInfo{fragmentShaderModule;fragmentShaderSourceVariant;fragmentShaderVariantConditionalBlocks;fragmentUniformInfo;fragmentBindGroupLayout;fragmentUniformBuffer;fragmentUniformBindGroup;fragmentState;constructor(i,g,x,v,_,y,b,S){this.fragmentShaderModule=i,this.fragmentShaderSourceVariant=g,this.fragmentShaderVariantConditionalBlocks=x,this.fragmentUniformInfo=v,this.fragmentBindGroupLayout=_,this.fragmentUniformBuffer=y,this.fragmentUniformBindGroup=b,this.fragmentState=S}}Object.freeze(FragmentGPURenderInfo);const getBindGroupLayoutDescriptorFromShaderInfo=(i,g,x,v=!0)=>{const{textures:_,samplers:y,uniforms:b,storage:S}=i,w=[];for(const i in S){const v=S[i],{binding:_,name:y,group:b,type:L}=v;if(v.access){const i={write:"write-only-storage",read:"read-only-storage",read_write:"read-write-storage"}[v.access];g===b&&w.push({binding:_,visibility:x,buffer:{type:i}})}else if(g===b){const{access:i,format:g}=L,v={write:"write-only",read:"read-only",read_write:"read-write"}[i],y=g.name;w.push({binding:_,visibility:x,storageTexture:{access:v,format:y}})}}for(const i in _){const v=_[i],{binding:y,name:b,group:S,type:L}=v,{name:k}=L;g===S&&w.push({binding:y,visibility:x,texture:"texture_depth_2d"===k||"texture_depth_multisampled_2d"===k?{viewDimension:"2d",sampleType:"depth",multisampled:"texture_depth_multisampled_2d"===k}:"texture_cube"===k?{viewDimension:"cube"}:"texture_3d"===k?{viewDimension:"3d"}:"texture_2d_array"===k?{viewDimension:"2d-array",sampleType:"float",multisampled:!1}:{}})}for(const i in y){const v=y[i],{binding:_,name:b,group:S}=v;g===S&&w.push({binding:_,visibility:x,sampler:{type:"filtering"}})}for(const i in b){const v=b[i],{binding:_,name:y,group:S}=v;g===S&&w.push({binding:_,visibility:x,buffer:{type:"uniform"}})}return{entries:w}},getFragmentBindGroupLayoutDescriptorFromShaderInfo=(i,g)=>getBindGroupLayoutDescriptorFromShaderInfo(i,g,GPUShaderStage.FRAGMENT),getVertexBindGroupLayoutDescriptorFromShaderInfo=(i,g)=>getBindGroupLayoutDescriptorFromShaderInfo(i,g,GPUShaderStage.VERTEX),getComputeBindGroupLayoutDescriptorFromShaderInfo=(i,g,x)=>getBindGroupLayoutDescriptorFromShaderInfo(i,g,GPUShaderStage.COMPUTE,x),applyProperties=(i,g,x)=>{(Array.isArray(g)?g:[g]).forEach(g=>{if(Array.isArray(g)){const[v,..._]=g;Object.defineProperty(i.prototype,v,x(v,..._))}else"object"==typeof g&&null!==g&&"key"in g?Object.defineProperty(i.prototype,g.key,x(g)):Object.defineProperty(i.prototype,g,x(g))})},updateTargetUniform=(i,g,x)=>{let v,_;const{gpuRenderInfo:y}=i;i.isInstanceofMaterial?(v=y.fragmentUniformInfo,_=y.fragmentUniformBuffer):i.isInstanceofPostEffect?(v=i.uniformsInfo,_=i.uniformBuffer):y?.vertexUniformInfo&&(v=y.vertexUniformInfo,_=y.vertexUniformBuffer),_&&v.members[g]&&_.writeOnlyBuffer(v.members[g],x)},vi={enumerable:!0,configurable:!1};function createSetter$6(i,g,x=0,v){return function(_){validatePositiveNumberRange(_),void 0!==x&&_v&&(console.warn(`Value for ${i} exceeds the maximum (${v}). Adjusted to ${v}.`),_=v),this[g]=_,updateTargetUniform(this,i,_)}}function definePositiveNumberRange_func(i){const{key:g,value:x=0,min:v=0,max:_}=i,y=Symbol(g);return{get:function(){return void 0===this[y]&&(this[y]=x),this[y]},set:createSetter$6(g,y,v,_),...vi}}Object.freeze(vi);const definePositiveNumber=(i,g)=>applyProperties(i,g,definePositiveNumberRange_func);function createSetter$5(i,g){return function(x){"boolean"!=typeof x&&console.warn(`Value for ${i} should be a boolean. Received: ${typeof x}.`),this[g]=x,updateTargetUniform(this,i,x?1:0),this.dirtyPipeline=!0}}function defineBoolean_func(i){const{key:g,value:x=!1}=i,v=Symbol(g);return{get:function(){return void 0===this[v]&&(this[v]=x),this[v]},set:createSetter$5(g,v),...vi}}Object.freeze(definePositiveNumber);const defineBoolean=(i,g)=>applyProperties(i,g,defineBoolean_func);function createColorRGBA(i,g,x,v){let _=255,y=255,b=255;if(isHexColor(v)){const i=convertHexToRgb(v);_=i.r,y=i.g,b=i.b}return new ColorRGBA(_,y,b,1,()=>{updateTargetUniform(i,g,i[x].rgbaNormalLinear)})}function defineColorRGBA_func(i){const g=i.key,x=i.value??"#fff",v=Symbol(g);return{get:function(){return void 0===this[v]&&(this[v]=createColorRGBA(this,g,v,x)),this[v]},set:function(i){if("string"==typeof i&&isHexColor(i)){const{r:x,g:_,b:y}=convertHexToRgb(i);this[v]?(this[v].r=x,this[v].g=_,this[v].b=y):this[v]=createColorRGBA(this,g,v,i)}else i instanceof ColorRGBA&&(this[v]=i,updateTargetUniform(this,g,i.rgbaNormalLinear))},...vi}}Object.freeze(defineBoolean);const defineColorRGBA=(i,g)=>applyProperties(i,g,defineColorRGBA_func);Object.freeze(defineColorRGBA);class ABaseMaterial extends ResourceBase{use2PathRender;gpuRenderInfo;dirtyPipeline=!1;transparent=!1;#ur;#lr;#cr=GPUColorWrite.ALL;#hr;#fr;#Ke;#dr;#mr;#pr;#gr;#xr;#vr;#_r;#yr;#br;#we;#Sr;#Tr=xi.MULTIPLY;constructor(i,g,x,v){super(i);const{resourceManager:_}=i;this.#br=g,this.#dr=`FRAGMENT_MODULE_${this.#br}`,this.#mr=`FRAGMENT_BIND_GROUP_DESCRIPTOR_${g}`,this.#pr=`FRAGMENT_BIND_GROUP_LAYOUT_${g}`,this.#gr=x,this.#xr=x?.storage,this.#vr=x?.uniforms.uniforms,this.#Sr=v,this.#_r=x.shaderSourceVariant.getUnionTextures(),this.#yr=x.shaderSourceVariant.getUnionSamplers(),this.#we=_.getGPUBindGroupLayout(this.#pr)||_.createBindGroupLayout(this.#pr,getFragmentBindGroupLayoutDescriptorFromShaderInfo(x,v)),this.#ur=new BlendState(this),this.#lr=new BlendState(this),this.#hr=_.basicSampler.gpuSampler,this.#fr=_.emptyBitmapTextureView,this.#Ke=_.emptyCubeTextureView}get tintBlendMode(){const i=Object.entries(xi).find(([,i])=>i===this.#Tr);if(!i)throw new Error(`Invalid tint mode value: ${this.#Tr}`);return i[0]}set tintBlendMode(i){const{fragmentUniformInfo:g,fragmentUniformBuffer:x}=this.gpuRenderInfo;let v;if("string"==typeof i){if(!(i in xi))throw new Error(`Invalid tint mode key: ${i}`);v=xi[i]}else{if("number"!=typeof i||!Object.values(xi).includes(i))throw new Error(`Invalid tint mode: ${i}`);v=i}x.writeOnlyBuffer(g.members.tintBlendMode,v),this.#Tr=v}get MODULE_NAME(){return this.#br}get FRAGMENT_SHADER_MODULE_NAME(){return this.#dr}get FRAGMENT_BIND_GROUP_DESCRIPTOR_NAME(){return this.#mr}get STORAGE_STRUCT(){return this.#xr}get UNIFORM_STRUCT(){return this.#vr}get blendColorState(){return this.#ur}get blendAlphaState(){return this.#lr}get writeMaskState(){return this.#cr}set writeMaskState(i){this.#cr=i}initGPURenderInfos(){const{redGPUContext:i}=this,{resourceManager:g}=i,x=g.createGPUShaderModule(this.#dr,{code:this.#gr.defaultSource}),v=new ArrayBuffer(Math.max(this.#vr.arrayBufferByteLength,16)),_=new UniformBuffer(i,v,`UniformBuffer_${this.#br}_${this.uuid}`);this.gpuRenderInfo=new FragmentGPURenderInfo(x,this.#gr.shaderSourceVariant,this.#gr.conditionalBlocks,this.#vr,this.#we,_,null,null),this._updateBaseProperty(),this._updateFragmentState()}_updateFragmentState(){const{gpuDevice:i,resourceManager:g}=this.redGPUContext;this.#wr();const x=[];for(const i in this.#_r){const v=this.#_r[i],{binding:_,name:y,group:b,type:S}=v,{name:w}=S;let L;L="texture_cube"===w?g.getGPUResourceCubeTextureView(this[y]):this[y]instanceof PackedTexture?g.getGPUResourceBitmapTextureView(this[y]):g.getGPUResourceBitmapTextureView(this[y])||this.#fr,2===b&&x.push({binding:_,resource:L})}for(const i in this.#yr){const g=this.#yr[i],{binding:v,name:_,group:y}=g;2===y&&x.push({binding:v,resource:this.getGPUResourceSampler(this[_])})}this.#vr&&x.push({binding:this.#vr.binding,resource:{buffer:this.gpuRenderInfo.fragmentUniformBuffer.gpuBuffer,offset:0,size:this.gpuRenderInfo.fragmentUniformBuffer.size}});const v={layout:this.gpuRenderInfo.fragmentBindGroupLayout,label:this.#mr,entries:x},_=i.createBindGroup(v);this.gpuRenderInfo.fragmentState=this.getFragmentRenderState(),this.gpuRenderInfo.fragmentUniformBindGroup=_}getFragmentRenderState(i="main"){return{module:this.gpuRenderInfo.fragmentShaderModule,entryPoint:i,targets:[{format:"rgba16float",blend:{color:this.blendColorState.state,alpha:this.blendAlphaState.state},writeMask:this.writeMaskState},{format:navigator.gpu.getPreferredCanvasFormat(),blend:void 0,writeMask:this.writeMaskState},{format:"rgba16float",blend:void 0,writeMask:this.writeMaskState}]}}_updateBaseProperty(){const{fragmentUniformInfo:i,fragmentUniformBuffer:g}=this.gpuRenderInfo,{members:x}=i;for(const v in x){const x=this[v];x instanceof ColorRGBA?g.writeOnlyBuffer(i.members[v],x.rgbaNormalLinear):x instanceof ColorRGB?g.writeOnlyBuffer(i.members[v],x.rgbNormalLinear):_i.test(v)||(this[v]=x)}}getGPUResourceSampler(i){return i?.gpuSampler||this.#hr}#wr(){const{resourceManager:i}=this.redGPUContext,g=this.#Mr(),x=`${this.#dr}_${g}`;let v=i.getGPUShaderModule(x);if(!v){const _=this.gpuRenderInfo.fragmentShaderSourceVariant.getVariant(g);v=_?i.createGPUShaderModule(x,{code:_}):this.gpuRenderInfo.fragmentShaderModule}this.gpuRenderInfo.fragmentShaderModule=v,this.#_r=this.gpuRenderInfo.fragmentShaderSourceVariant.getVariantTextures(g),this.#yr=this.gpuRenderInfo.fragmentShaderSourceVariant.getVariantSamplers(g);const _=`${this.#pr}_${g}`;let y=i.getGPUBindGroupLayout(_);if(!y){const g={...this.#gr,textures:this.#_r,samplers:this.#yr};y=i.createBindGroupLayout(_,getFragmentBindGroupLayoutDescriptorFromShaderInfo(g,this.#Sr))}this.gpuRenderInfo.fragmentBindGroupLayout=y}#Mr(){const{fragmentShaderVariantConditionalBlocks:i}=this.gpuRenderInfo,g=new Set;for(const x of i)this[x]&&g.add(x);const x=g.size>0?Array.from(g).sort().join("+"):"none";return g.size,x}}const _i=/^use\w+Texture$/;Object.defineProperty(ABaseMaterial.prototype,"isInstanceofMaterial",{value:!0,writable:!1}),definePositiveNumber(ABaseMaterial,[{key:"opacity",value:1,max:1}]),defineBoolean(ABaseMaterial,[{key:"useTint",value:!1}]),defineColorRGBA(ABaseMaterial,[{key:"tint",value:"#ffffff"}]),Object.freeze(ABaseMaterial);class ABitmapBaseMaterial extends ABaseMaterial{__packingList;constructor(i,g,x,v){super(i,g,x,v)}updateTexture(i,g){i&&i.__removeDirtyPipelineListener(this.#Pr),g&&g.__addDirtyPipelineListener(this.#Pr),this.#Pr()}updateSampler(i,g){i&&i.__removeDirtyPipelineListener(this.#Pr),g&&g.__addDirtyPipelineListener(this.#Pr),this.#Pr()}#Pr=()=>{this.dirtyPipeline=!0;{let i=(this.__packingList||[]).length;for(;i--;)this.__packingList[i]()}this.gpuRenderInfo?.fragmentShaderModule?this._updateFragmentState():this.initGPURenderInfos()}}Object.freeze(ABitmapBaseMaterial);class AUVTransformBaseMaterial extends ABitmapBaseMaterial{dirtyTextureTransform=!1;#Rr=[0,0];#Cr=[1,1];constructor(i,g,x,v){super(i,g,x,v)}get textureOffset(){return this.#Rr}set textureOffset(i){this.dirtyTextureTransform=!0,this.#Rr=i}get textureScale(){return this.#Cr}set textureScale(i){this.dirtyTextureTransform=!0,this.#Cr=i}}Object.freeze(AUVTransformBaseMaterial);var yi=Object.freeze({__proto__:null,ABaseMaterial:ABaseMaterial,ABitmapBaseMaterial:ABitmapBaseMaterial,AUVTransformBaseMaterial:AUVTransformBaseMaterial,FragmentGPURenderInfo:FragmentGPURenderInfo,getComputeBindGroupLayoutDescriptorFromShaderInfo:getComputeBindGroupLayoutDescriptorFromShaderInfo,getFragmentBindGroupLayoutDescriptorFromShaderInfo:getFragmentBindGroupLayoutDescriptorFromShaderInfo,getVertexBindGroupLayoutDescriptorFromShaderInfo:getVertexBindGroupLayoutDescriptorFromShaderInfo});const bi=new WeakMap;let Si=0;class ASinglePassPostEffect extends RedGPUObject{isLdr=!1;#Br;#Dr;#Er;#Ir;#Ar;#Lr;#Ur;#kr;#Gr;#Or;#Vr;#Nr;#Fr;#Hr;#zr;#$r;#se;#jr;#Kr;#Xr;#l;#qr;#Yr;#Wr;#Zr;#Jr;#Qr=16;#ei=16;#ti=1;#H=0;#ri;#ii;#ni=new Map;#ai;#si=new Map;constructor(i,g){super(i),g&&(void 0!==g.x&&(this.#Qr=g.x),void 0!==g.y&&(this.#ei=g.y),void 0!==g.z&&(this.#ti=g.z))}get videoMemorySize(){return this.#H}get storageInfo(){return this.#Xr}get shaderInfo(){return this.antialiasingManager.useMSAA?this.#qr:this.#Yr}get uniformBuffer(){return this.#se}get uniformsInfo(){return this.#jr}get systemUniformsInfo(){return this.#Kr}get WORK_SIZE_X(){return this.#Qr}get WORK_SIZE_Y(){return this.#ei}get WORK_SIZE_Z(){return this.#ti}get outputTextureView(){return this.#Jr}clear(){this.#Zr=null,this.#Jr=null,this.#ni.clear(),this.#ai=null,this.#si.clear()}init(i,g,x){this.#l=g;const{resourceManager:v}=i;this.#Br=v.createGPUShaderModule(`${g}_MSAA`,{code:x.msaa}),this.#Dr=v.createGPUShaderModule(`${g}_NonMSAA`,{code:x.nonMsaa}),this.#qr=parseWGSL(`${g}_MSAA`,x.msaa),this.#Yr=parseWGSL(`${g}_NonMSAA`,x.nonMsaa);const{storage:_,uniforms:y}=this.#qr;if(this.#Xr=_,this.#jr=y.uniforms,this.#Kr=y.systemUniforms,this.#jr){const g=new ArrayBuffer(this.#jr.arrayBufferByteLength);this.#se=new UniformBuffer(i,g,`${this.constructor.name}_UniformBuffer`)}{const{members:i}=this.#jr||{};if(i)for(const g in i)this.uniformBuffer.writeOnlyBuffer(i[g],this[g])}}render(i,g,x,...v){const{gpuDevice:_,antialiasingManager:y}=this,{useMSAA:b,msaaID:S}=y,w=i.postEffectManager.texturePool.allocResult(g,x,"rgba16float");this.#Zr=w.texture,this.#Jr=w.textureView;const L=this.#Wr?.width!==g||this.#Wr?.height!==x,k=this.#ri!==b||this.#ii!==S;return(L||k)&&(this.#ni.clear(),this.#ai=null,this.#si.clear()),this.#oi(i,b,_),this.#ui(v,this.#Jr,b,_),this.#li(i,g,x,i.postEffectManager.gbufferBindGroup),this.#ri=b,this.#ii=S,this.#Wr={width:g,height:x},this.#ci(),{texture:this.#Zr,textureView:this.#Jr}}updateUniform(i,g){const x=this.uniformsInfo?.members[i];x&&this.uniformBuffer.writeOnlyBuffer(x,g)}#hi(i){if(!i)return 0;let g=bi.get(i);return void 0===g&&(g=Si++,bi.set(i,g)),g}#li(i,g,x,v){const{commandEncoderManager:_}=this,{renderViewStateData:y}=i;_.addPostProcessComputePass(`ASinglePassPostEffect_${this.#l}_ComputePass`,i=>{i.setPipeline(this.#Hr);const _=y.swapBufferIndex?this.#Ur:this.#Lr;_&&i.setBindGroup(0,_),this.#kr&&i.setBindGroup(1,this.#kr),v&&i.setBindGroup(2,v),this.#Gr&&i.setBindGroup(3,this.#Gr),i.dispatchWorkgroups(Math.ceil(g/this.WORK_SIZE_X),Math.ceil(x/this.WORK_SIZE_Y))})}#oi(i,g,x){const v=g?this.#zr:this.#$r;if(v)return void(this.#Hr=v);const{resourceManager:_}=this,y=g?this.#qr:this.#Yr,b=g?this.#Br:this.#Dr,S=`${this.#l}_BIND_GROUP_LAYOUT_0_USE_MSAA_${g}`,w=`${this.#l}_BIND_GROUP_LAYOUT_1_USE_MSAA_${g}`,L=`${this.#l}_BIND_GROUP_LAYOUT_3_USE_MSAA_${g}`;this.#Er=_.getGPUBindGroupLayout(S)||_.createBindGroupLayout(S,getComputeBindGroupLayoutDescriptorFromShaderInfo(y,0,g)),this.#Ir=_.getGPUBindGroupLayout(w)||_.createBindGroupLayout(w,getComputeBindGroupLayoutDescriptorFromShaderInfo(y,1,g)),this.#Ar=_.getGPUBindGroupLayout(L)||_.createBindGroupLayout(L,getComputeBindGroupLayoutDescriptorFromShaderInfo(y,3,g));const k=x.createComputePipeline({label:`${this.#l}_COMPUTE_PIPELINE_USE_MSAA_${g}`,layout:x.createPipelineLayout({bindGroupLayouts:[this.#Er,this.#Ir,i.postEffectManager.gbufferBindGroupLayout,this.#Ar]}),compute:{module:b,entryPoint:"main"}});g?this.#zr=k:this.#$r=k,this.#Hr=k}#ui(i,g,x,v){const{storage:_,textures:y}=this.shaderInfo,b=i.map(i=>this.#hi(i.texture)).join("_"),S=this.#ni.get(`${b}_swap0`),w=this.#ni.get(`${b}_swap1`);if(S&&w)this.#Lr=S,this.#Ur=w;else{this.#Or=[],this.#Vr=[];for(const g in _){const{binding:x,name:v,group:y}=_[g];if(0===y&&"outputTexture"!==v){const g=i[x]?.textureView;g&&(this.#Or.push({binding:x,resource:g}),this.#Vr.push({binding:x,resource:g}))}}y.forEach(({binding:g,group:x})=>{if(0===x){const x=i[g]?.textureView;x&&(this.#Or.push({binding:g,resource:x}),this.#Vr.push({binding:g,resource:x}))}}),this.#Lr=v.createBindGroup({label:`${this.#l}_BIND_GROUP_0_USE_MSAA_${x}_SWAP0`,layout:this.#Er,entries:this.#Or}),this.#Ur=v.createBindGroup({label:`${this.#l}_BIND_GROUP_0_USE_MSAA_${x}_SWAP1`,layout:this.#Er,entries:this.#Vr}),this.#ni.set(`${b}_swap0`,this.#Lr),this.#ni.set(`${b}_swap1`,this.#Ur)}this.#ai?this.#kr=this.#ai:this.#se&&this.uniformsInfo&&(this.#Nr=[{binding:0,resource:{buffer:this.#se.gpuBuffer,offset:0,size:this.#se.size}}],this.#kr=v.createBindGroup({label:`${this.#l}_BIND_GROUP_1_USE_MSAA_${x}`,layout:this.#Ir,entries:this.#Nr}),this.#ai=this.#kr);const L=this.#hi(this.#Zr);this.#si.has(L)?this.#Gr=this.#si.get(L):(this.#Fr=[{binding:0,resource:g}],this.#Gr=v.createBindGroup({label:`${this.#l}_BIND_GROUP_3_USE_MSAA_${x}`,layout:this.#Ar,entries:this.#Fr}),this.#si.set(L,this.#Gr))}#ci(){this.#H=this.#se?this.#se.size:0}}Object.defineProperty(ASinglePassPostEffect.prototype,"isInstanceofPostEffect",{value:!0,writable:!1}),Object.freeze(ASinglePassPostEffect);class AMultiPassPostEffect extends ASinglePassPostEffect{#fi=[];#H=0;constructor(i,g){super(i),this.#fi.push(...g)}get videoMemorySize(){return this.#ci(),this.#H}get passList(){return this.#fi}clear(){this.#fi.forEach(i=>i.clear())}render(i,g,x,v){let _;const y=i.postEffectManager.texturePool;return this.#fi.forEach((b,S)=>{const w=_;S&&(v=_),_=b.render(i,g,x,v),w&&y.release(w.texture)}),_}#ci(){this.#H=0,this.#fi.forEach(i=>{this.#H+=i.videoMemorySize})}}Object.freeze(AMultiPassPostEffect);const createCode=(i,g,x="",v=!1,_={name:"sourceTexture"})=>{const{WORK_SIZE_X:y,WORK_SIZE_Y:b,WORK_SIZE_Z:S}=i,w=v?"texture_depth_multisampled_2d":"texture_depth_2d";let L="";return(Array.isArray(_)?_:[_]).forEach((i,g)=>{let x,v=!0;x=i.name,void 0!==i.isSampled&&(v=i.isSampled),L+=v?`@group(0) @binding(${g}) var ${x} : texture_2d;\n`:`@group(0) @binding(${g}) var ${x} : texture_storage_2d;\n`}),`\n ${x}\n \n ${L}\n \n ${x?"@group(1) @binding(0) var uniforms: Uniforms;":""}\n \n ${ft.POST_EFFECT_SYSTEM_UNIFORM}\n @group(2) @binding(5) var basicSampler : sampler;\n \n @group(2) @binding(0) var depthTexture : ${w};\n @group(2) @binding(1) var gBufferNormalTexture : texture_2d;\n @group(2) @binding(2) var gBufferMotionVector : texture_2d;\n @group(2) @binding(3) var prevDepthTexture : ${w};\n \n @group(3) @binding(0) var outputTexture : texture_storage_2d;\n \n @compute @workgroup_size(${y}, ${b}, ${S})\n fn main(\n @builtin(global_invocation_id) global_id : vec3,\n ) {\n ${g}\n }\n `},createBasicPostEffectCode=(i,g,x="",v={name:"sourceTexture"})=>({msaa:createCode(i,g,x,!0,v),nonMsaa:createCode(i,g,x,!1,v)});Object.freeze(createBasicPostEffectCode);function createSetter$4(i,g,x=0,v){return function(_){validateUintRange(_),void 0!==x&&_v&&(console.warn(`Value for ${i} exceeds the maximum (${v}). Adjusted to ${v}.`),_=v),this[g]=_,updateTargetUniform(this,i,_)}}function defineUintRange_func(i){const{key:g,value:x=0,min:v=0,max:_}=i,y=Symbol(g);return{get:function(){return void 0===this[y]&&(this[y]=x),this[y]},set:createSetter$4(g,y,v,_),...vi}}const defineUint=(i,g)=>applyProperties(i,g,defineUintRange_func);Object.freeze(defineUint);class BlurX extends ASinglePassPostEffect{constructor(i){super(i),this.init(i,"POST_EFFECT_BLUR_X",createBasicPostEffectCode(this,"let index=global_id.xy;let dimensions=vec2(textureDimensions(sourceTexture));if(f32(index.x)>=dimensions.x||f32(index.y)>=dimensions.y){return;}let invSize=1.0/dimensions;let centerUV=(vec2(index)+0.5)*invSize;let blurSize=uniforms.size*systemUniforms.devicePixelRatio;var sum:vec4=vec4(.0);var totalWeight:f32=.0;let steps=uniforms.sampleCount;for(var i=-steps;i<=steps;i+=1.0){let offsetPixels=(i/steps)*blurSize;let weight=exp(-0.5*pow(i/(steps*0.6),2.0));let sampleUV=centerUV+vec2(offsetPixels*invSize.x,.0);sum+=textureSampleLevel(sourceTexture,basicSampler,sampleUV,.0)*weight;totalWeight+=weight;}textureStore(outputTexture,index,sum/totalWeight);","struct Uniforms{size:f32,sampleCount:f32,};"))}}definePositiveNumber(BlurX,[{key:"size",value:32,min:0,max:512}]),defineUint(BlurX,[{key:"sampleCount",value:10,min:1,max:100}]),Object.freeze(BlurX);class BlurY extends ASinglePassPostEffect{constructor(i){super(i),this.init(i,"POST_EFFECT_BLUR_Y",createBasicPostEffectCode(this,"let index=global_id.xy;let dimensions=vec2(textureDimensions(sourceTexture));if(f32(index.x)>=dimensions.x||f32(index.y)>=dimensions.y){return;}let invSize=1.0/dimensions;let centerUV=(vec2(index)+0.5)*invSize;let blurSize=uniforms.size*systemUniforms.devicePixelRatio;var sum:vec4=vec4(.0);var totalWeight:f32=.0;let steps=uniforms.sampleCount;for(var i=-steps;i<=steps;i+=1.0){let offsetPixels=(i/steps)*blurSize;let weight=exp(-0.5*pow(i/(steps*0.6),2.0));let sampleUV=centerUV+vec2(.0,offsetPixels*invSize.y);sum+=textureSampleLevel(sourceTexture,basicSampler,sampleUV,.0)*weight;totalWeight+=weight;}textureStore(outputTexture,index,sum/totalWeight);","struct Uniforms{size:f32,sampleCount:f32,};"))}}definePositiveNumber(BlurY,[{key:"size",value:32,min:0,max:512}]),defineUint(BlurY,[{key:"sampleCount",value:10,min:1,max:100}]),Object.freeze(BlurY);class GaussianBlur extends AMultiPassPostEffect{#qt=32;#di=10;constructor(i){super(i,[new BlurX(i),new BlurY(i)]),this.size=this.size,this.sampleCount=this.#di}get size(){return this.#qt}set size(i){this.#qt=i,this.passList.forEach(g=>g.size=i)}get sampleCount(){return this.#di}set sampleCount(i){this.#di=i,this.passList.forEach(g=>g.sampleCount=i)}}Object.freeze(GaussianBlur);class SSAO_AO extends ASinglePassPostEffect{constructor(i){super(i),this.init(i,"POST_EFFECT_SSAO",createBasicPostEffectCode(this,"{let screenCoord=vec2(global_id.xy);let texSize=vec2(textureDimensions(sourceTexture));if(screenCoord.x>=texSize.x||screenCoord.y>=texSize.y){return;}let originalColor=textureLoad(sourceTexture,screenCoord,0);let depth=textureLoad(depthTexture,screenCoord,0);var failColor=vec4(select(originalColor.rgb,vec3(1.0),uniforms.useBlur==1u),originalColor.a);if(depth<.001){textureStore(outputTexture,screenCoord,failColor);return;}let normalData=textureLoad(gBufferNormalTexture,screenCoord,0);if(length(normalData.rgb)<.001){textureStore(outputTexture,screenCoord,failColor);return;}let viewPos=getViewPositionFromDepth((vec2(screenCoord)+0.5)/vec2(texSize),depth,systemUniforms.projection.inverseProjectionMatrix);let viewNormal=getViewNormalFromGNormalBuffer(normalData.rgb,systemUniforms.camera.viewMatrix);let distToCamera=-viewPos.z;let depthScale=distToCamera*0.1;let adaptiveRadius=uniforms.radius*(1.0+depthScale);let noiseVec=getNoiseVec(vec2(screenCoord));let tbn=getTBN(viewNormal,noiseVec);let samples=array,8>(vec3(.04,.03,.08),vec3(-.04,.04,.08),vec3(0.10,-.08,0.18),vec3(-.09,-0.10,0.18),vec3(0.18,0.15,0.30),vec3(-0.17,0.18,0.30),vec3(0.28,-0.25,0.45),vec3(-0.27,-0.28,0.45));var totalOcclusion=.0;for(var i=0u;i<8u;i++){let sampleOffset=tbn*samples[i];let sampleDir=normalize(sampleOffset);let sampleViewPos=viewPos+sampleOffset*adaptiveRadius;let clipPos=systemUniforms.projection.projectionMatrix*vec4(sampleViewPos,1.0);let sampleUV=(clipPos.xy/clipPos.w)*vec2(0.5,-0.5)+0.5;if(sampleUV.x<.0||sampleUV.x>1.0||sampleUV.y<.0||sampleUV.y>1.0){continue;}let sampleCoord=vec2(sampleUV*vec2(texSize));let realDepth=textureLoad(depthTexture,sampleCoord,0);if(realDepth<.001){continue;}let realViewPos=getViewPositionFromDepth(sampleUV,realDepth,systemUniforms.projection.inverseProjectionMatrix);let adaptiveBias=uniforms.bias*(1.0+distToCamera*uniforms.biasDistanceScale);let deltaZ=realViewPos.z-sampleViewPos.z;if(deltaZ>adaptiveBias&&deltaZ(select(originalColor.rgb*vec3(finalAO),vec3(finalAO),uniforms.useBlur==1u),originalColor.a);textureStore(outputTexture,screenCoord,finalColor);}","#redgpu_include math.getInterleavedGradientNoise #redgpu_include math.PI2 #redgpu_include depth.getLinearizeDepth #redgpu_include math.reconstruct.getViewPositionFromDepth #redgpu_include math.reconstruct.getViewNormalFromGNormalBuffer #redgpu_include math.tnb.getTBN struct Uniforms{radius:f32,intensity:f32,bias:f32,biasDistanceScale:f32,fadeDistanceStart:f32,fadeDistanceRange:f32,contrast:f32,useBlur:u32,}fn getTextureSize()->vec2{return vec2(textureDimensions(sourceTexture));}fn getNoiseVec(p:vec2)->vec3{let noise=getInterleavedGradientNoise(p);let angle=noise*PI2;return vec3(cos(angle),sin(angle),.0);}"))}}defineBoolean(SSAO_AO,[{key:"useBlur",value:!0}]),definePositiveNumber(SSAO_AO,[{key:"contrast",value:1.5,min:.5,max:4},{key:"radius",value:.253,min:.01,max:5},{key:"intensity",value:1,min:0,max:10},{key:"bias",value:.02,min:0,max:.1},{key:"biasDistanceScale",value:.02,min:0,max:.5},{key:"fadeDistanceStart",value:30,min:1,max:200},{key:"fadeDistanceRange",value:20,min:1,max:100}]),Object.freeze(SSAO_AO);class SSAOBlend extends ASinglePassPostEffect{constructor(i){super(i),this.init(i,"POST_EFFECT_SSAO_BLEND",createBasicPostEffectCode(this,"let index=global_id.xy;var diffuse:vec4=textureLoad(sourceTexture0,index,0);var blur:vec4=textureLoad(sourceTexture1,index,0);let finalColor=vec4(diffuse.rgb*blur.rgb,diffuse.a);textureStore(outputTexture,index,finalColor);","",[{name:"sourceTexture0"},{name:"sourceTexture1"}]))}}Object.freeze(SSAOBlend);class SSAO extends AMultiPassPostEffect{#mi;#pi;#gi;constructor(i){super(i,[new SSAO_AO(i),new GaussianBlur(i),new SSAOBlend(i)]),this.#mi=this.passList[0],this.#pi=this.passList[1],this.#pi.size=3,this.#gi=this.passList[2]}get useBlur(){return this.#mi.useBlur}set useBlur(i){this.#mi.useBlur=i}get radius(){return this.#mi.radius}set radius(i){this.#mi.radius=i}get intensity(){return this.#mi.intensity}set intensity(i){this.#mi.intensity=i}get bias(){return this.#mi.bias}set bias(i){this.#mi.bias=i}get biasDistanceScale(){return this.#mi.biasDistanceScale}set biasDistanceScale(i){this.#mi.biasDistanceScale=i}get fadeDistanceStart(){return this.#mi.fadeDistanceStart}set fadeDistanceStart(i){this.#mi.fadeDistanceStart=i}get fadeDistanceRange(){return this.#mi.fadeDistanceRange}set fadeDistanceRange(i){this.#mi.fadeDistanceRange=i}get contrast(){return this.#mi.contrast}set contrast(i){this.#mi.contrast=i}render(i,g,x,v){const _=i.postEffectManager.texturePool,y=this.#mi.render(i,g,x,v);if(this.useBlur){const b=this.#pi.render(i,g,x,y);_.release(y.texture);const S=this.#gi.render(i,g,x,v,b);return _.release(b.texture),S}return y}}Object.freeze(SSAO);class SSR extends ASinglePassPostEffect{constructor(i){super(i,{x:8,y:8,z:1}),this.init(i,"POST_EFFECT_SSR",createBasicPostEffectCode(this,"let screenCoord=vec2(global_id.xy);let texDims=textureDimensions(sourceTexture);let texSize=vec2(texDims);if(screenCoord.x>=texSize.x||screenCoord.y>=texSize.y){return;}let originalColor=textureLoad(sourceTexture,screenCoord,0);let depth=textureLoad(depthTexture,screenCoord,0);if(depth>=0.999){textureStore(outputTexture,screenCoord,originalColor);return;}let gBufferNormalData=textureLoad(gBufferNormalTexture,screenCoord,0);let precomputedReflectionStrength=gBufferNormalData.a;if(precomputedReflectionStrength<.05){textureStore(outputTexture,screenCoord,originalColor);return;}let uv=(vec2(screenCoord)+0.5)/vec2(texDims);let worldPos=reconstructWorldPosition(uv,depth);let worldNormal=getWorldNormalFromGNormalBuffer(gBufferNormalData.rgb);if(length(worldNormal)<.01){textureStore(outputTexture,screenCoord,originalColor);return;}let normal=normalize(worldNormal);let cameraWorldPos=systemUniforms.camera.inverseViewMatrix[3].xyz;let reflectionDir=calculateWorldReflectionRay(worldPos,normal,cameraWorldPos);let reflection=performWorldRayMarching(worldPos,reflectionDir,screenCoord);if(reflection.a>.001){let finalReflectionStrength=reflection.a*uniforms.reflectionIntensity*precomputedReflectionStrength;let reflectionColor=reflection.rgb*finalReflectionStrength;let diffuseColor=originalColor.rgb*(1.0-finalReflectionStrength);let finalColor=diffuseColor+reflectionColor;textureStore(outputTexture,screenCoord,vec4(finalColor,originalColor.a));}else{textureStore(outputTexture,screenCoord,originalColor);}","#redgpu_include math.getInterleavedGradientNoise #redgpu_include depth.getLinearizeDepth #redgpu_include math.EPSILON #redgpu_include math.reconstruct.getViewPositionFromDepth #redgpu_include math.reconstruct.getWorldNormalFromGNormalBuffer #redgpu_include math.direction.getViewDirection #redgpu_include math.direction.getReflectionVectorFromViewDirection struct Uniforms{maxSteps:u32,maxDistance:f32,stepSize:f32,reflectionIntensity:f32,fadeDistance:f32,edgeFade:f32,_padding:f32,_padding2:f32,}fn getTextureDimensions()->vec2{return textureDimensions(depthTexture);}fn reconstructWorldPosition(uv:vec2,depth:f32)->vec3{let viewPos=getViewPositionFromDepth(uv,depth,systemUniforms.projection.inverseProjectionMatrix);let worldPos4=systemUniforms.camera.inverseViewMatrix*vec4(viewPos,1.0);return worldPos4.xyz;}fn worldToScreen(worldPos:vec3)->vec2{let clipPos4=systemUniforms.projection.projectionViewMatrix*vec4(worldPos,1.0);if(abs(clipPos4.w)(-1.0);}let ndc=clipPos4.xyz/clipPos4.w;return vec2(ndc.x*0.5+0.5,-ndc.y*0.5+0.5);}fn calculateEdgeFade(screenUV:vec2)->f32{let edge=min(screenUV,1.0-screenUV);let edgeDist=min(edge.x,edge.y);return smoothstep(.0,uniforms.edgeFade,edgeDist);}fn calculateWorldReflectionRay(worldPos:vec3,worldNormal:vec3,cameraWorldPos:vec3)->vec3{let viewDir=getViewDirection(worldPos,cameraWorldPos);return getReflectionVectorFromViewDirection(viewDir,worldNormal);}fn performWorldRayMarching(startWorldPos:vec3,rayDir:vec3,screenCoord:vec2)->vec4{let cameraWorldPos=systemUniforms.camera.inverseViewMatrix[3].xyz;let cameraDistance=length(startWorldPos-cameraWorldPos);let distanceScale=1.0+cameraDistance*0.1;let adaptiveStepSize=uniforms.stepSize*min(distanceScale,4.0);let stepScale=1.0+cameraDistance*.067;let adaptiveMaxSteps=u32(f32(uniforms.maxSteps)*min(stepScale,2.0));let maxDistanceSq=uniforms.maxDistance*uniforms.maxDistance;let texDims=getTextureDimensions();let texSizeF=vec2(texDims);let maxRefinementLevels=4u;let invMaxSteps=1.0/f32(adaptiveMaxSteps);let jitter=getInterleavedGradientNoise(vec2(screenCoord));var currentWorldPos=startWorldPos+rayDir*(adaptiveStepSize*jitter);var currentStepSize=adaptiveStepSize;var refinementLevel=0u;for(var i=0u;imaxDistanceSq){break;}let currentScreenUV=worldToScreen(currentWorldPos);if(any(currentScreenUV(.0))||any(currentScreenUV>vec2(1.0))){break;}let coord=vec2(currentScreenUV*texSizeF);let sampledDepth=textureLoad(depthTexture,coord,0);if(sampledDepth>=0.999){continue;}let sampledWorldPos=reconstructWorldPosition(currentScreenUV,sampledDepth);let rayDistanceFromCamera=length(currentWorldPos-cameraWorldPos);let surfaceDistanceFromCamera=length(sampledWorldPos-cameraWorldPos);let distanceDiff=rayDistanceFromCamera-surfaceDistanceFromCamera;let intersectionThreshold=currentStepSize*(4.0+cameraDistance*.033);if(distanceDiff>.0&&distanceDiff(reflectionColor.rgb,totalFade);}}return vec4(.0);}"))}}definePositiveNumber(SSR,[{key:"maxSteps",value:64,min:1,max:512},{key:"maxDistance",value:15,min:1,max:200},{key:"stepSize",value:.02,min:.001,max:5},{key:"reflectionIntensity",value:1,min:0,max:10},{key:"fadeDistance",value:12,min:1,max:100},{key:"edgeFade",value:.15,min:0,max:.5}]),Object.freeze(SSR);class TAASharpen extends ASinglePassPostEffect{constructor(i){super(i),this.isLdr=!0,this.init(i,"POST_EFFECT_TAA_SHARPEN",createBasicPostEffectCode(this,"let index=global_id.xy;let dimensions=textureDimensions(sourceTexture);if(index.x>=dimensions.x||index.y>=dimensions.y){return;}let centerRGBA=textureLoad(sourceTexture,index,0);let leftRGBA=textureLoad(sourceTexture,index-vec2(select(0u,1u,index.x>0u),0u),0);let rightRGBA=textureLoad(sourceTexture,min(index+vec2(1u,0u),dimensions-1u),0);let upRGBA=textureLoad(sourceTexture,index-vec2(0u,select(0u,1u,index.y>0u)),0);let downRGBA=textureLoad(sourceTexture,min(index+vec2(0u,1u),dimensions-1u),0);let lCenter=getLuminance(centerRGBA.rgb);let lLeft=getLuminance(leftRGBA.rgb);let lRight=getLuminance(rightRGBA.rgb);let lUp=getLuminance(upRGBA.rgb);let lDown=getLuminance(downRGBA.rgb);let minL=min(lCenter,min(min(lLeft,lRight),min(lUp,lDown)));let maxL=max(lCenter,max(max(lLeft,lRight),max(lUp,lDown)));let contrast=maxL-minL;var finalRGBA:vec4;let k=uniforms.sharpness*0.2;if(contrast>.001){let edgeRGB=4.0*centerRGBA.rgb-(leftRGBA.rgb+rightRGBA.rgb+upRGBA.rgb+downRGBA.rgb);let sharpRGB=centerRGBA.rgb+edgeRGB*k;let edgeAlpha=4.0*centerRGBA.a-(leftRGBA.a+rightRGBA.a+upRGBA.a+downRGBA.a);let sharpAlpha=centerRGBA.a+edgeAlpha*k;finalRGBA=vec4(sharpRGB,sharpAlpha);}else{finalRGBA=centerRGBA;}textureStore(outputTexture,index,saturate(finalRGBA));","#redgpu_include color.getLuminance struct Uniforms{sharpness:f32};"))}}definePositiveNumber(TAASharpen,[{key:"sharpness",value:.5,min:0,max:1}]),Object.freeze(TAASharpen);class ACamera extends BaseObject{static CALIBRATION_CONSTANT=12.5;#xi=16;#vi=1/3200;#_i=100;#yi=0;#bi=!0;#Si=!0;get useAutoExposure(){return this.#bi}set useAutoExposure(i){if(this.#bi!==i){if(this.#bi&&!i){this.#_i=100;let i=this.#xi*this.#xi/Math.pow(2,this.#yi);const g=[1,1/1.3,.625,.5,.4,1/3.2,1/4,.2,1/6,1/8,.1,1/13,1/15,.05,.04,1/30,1/40,.02,1/60,1/80,.01,.008,1/160,.005,.004,1/320,1/400,.002,1/640,1/800,.001,8e-4,1/1600,5e-4,4e-4,1/3200,1/4e3,2e-4,1/6400,1/8e3];this.#vi=g.reduce((g,x)=>Math.abs(x-i){v.forEach(({key:v,value:_})=>{const y=i[v];if(!y)return;const b=y.View===Float32Array?g:x;y.View&&b.set("number"==typeof _?[_]:_,y.uniformOffset/y.View.BYTES_PER_ELEMENT)})};let Ti=create$4();class SystemUniformUpdater{static updateCamera(i,g,x,v){const{viewMatrix:_,position:y}=i,b=i instanceof Camera2D;updateSystemUniformData(g,x,v,[{key:"viewMatrix",value:_},{key:"inverseViewMatrix",value:invert$1(Ti,_)},{key:"cameraPosition",value:y},{key:"nearClipping",value:b?0:i.nearClipping},{key:"farClipping",value:b?0:i.farClipping},{key:"fieldOfView",value:i.fieldOfView*Math.PI/180},{key:"ev100",value:i.ev100},{key:"aperture",value:i.aperture},{key:"shutterSpeed",value:i.shutterSpeed},{key:"iso",value:i.iso}])}static updateShadow(i,g,x,v){updateSystemUniformData(g,x,v,[{key:"directionalShadowDepthTextureSize",value:i.directionalShadowManager.shadowDepthTextureSize},{key:"directionalShadowBias",value:i.directionalShadowManager.bias}])}static updateSkyAtmosphere(i,g,x,v){const _=i?.params,y=g.skyAtmosphere.members;updateSystemUniformData(g,x,v,[{key:"useSkyAtmosphere",value:i?1:0}]),updateSystemUniformData(y,x,v,[{key:"rayleighScattering",value:_?.rayleighScattering||[0,0,0]},{key:"rayleighExponentialDistribution",value:_?.rayleighExponentialDistribution||0},{key:"mieScattering",value:_?.mieScattering||[0,0,0]},{key:"mieAnisotropy",value:_?.mieAnisotropy||0},{key:"mieAbsorption",value:_?.mieAbsorption||[0,0,0]},{key:"mieExponentialDistribution",value:_?.mieExponentialDistribution||0},{key:"absorptionCoefficient",value:_?.absorptionCoefficient||[0,0,0]},{key:"absorptionTipAltitude",value:_?.absorptionTipAltitude||0},{key:"groundAlbedo",value:_?.groundAlbedo||[0,0,0]},{key:"absorptionTentWidth",value:_?.absorptionTentWidth||0},{key:"skyLuminanceFactor",value:_?.skyLuminanceFactor||[1,1,1]},{key:"multiScatteringFactor",value:_?.multiScatteringFactor||0},{key:"sunDirection",value:_?.sunDirection||[0,0,0]},{key:"transmittanceMinLightElevationAngle",value:_?.transmittanceMinLightElevationAngle||0},{key:"groundRadius",value:_?.groundRadius||0},{key:"atmosphereHeight",value:_?.atmosphereHeight||0},{key:"aerialPerspectiveDistanceScale",value:_?.aerialPerspectiveDistanceScale||100},{key:"aerialPerspectiveStartDepth",value:_?.aerialPerspectiveStartDepth||0},{key:"sunIntensity",value:_?.sunIntensity||0},{key:"sunSize",value:_?.sunSize||0},{key:"sunLimbDarkening",value:_?.sunLimbDarkening||0},{key:"cameraHeight",value:_?.cameraHeight||0},{key:"cloudTime",value:_?.cloudTime||0},{key:"cloudTimeMultiplier",value:_?.cloudTimeMultiplier||0},{key:"cloudCoverage",value:_?.cloudCoverage||0},{key:"cloudDensity",value:_?.cloudDensity||0},{key:"cloudHeight",value:_?.cloudHeight||0}])}static updateTime(i,g,x,v){updateSystemUniformData(g,x,v,[{key:"time",value:i.time},{key:"deltaTime",value:i.deltaTime},{key:"frameIndex",value:i.frameIndex},{key:"sinTime",value:i.sinTime}])}static updateProjection(i,g,x,v){updateSystemUniformData(g,x,v,[{key:"projectionMatrix",value:i.projectionMatrix},{key:"projectionViewMatrix",value:i.projectionViewMatrix},{key:"noneJitterProjectionMatrix",value:i.noneJitterProjectionMatrix},{key:"noneJitterProjectionViewMatrix",value:i.noneJitterProjectionViewMatrix},{key:"inverseProjectionMatrix",value:i.inverseProjectionMatrix},{key:"inverseProjectionViewMatrix",value:i.inverseProjectionViewMatrix||create$4()},{key:"prevNoneJitterProjectionViewMatrix",value:i.prevNoneJitterProjectionViewMatrix}])}static updateDirectionalLights(i,g,x,v){i.forEach((i,_)=>{const y=g[_];updateSystemUniformData(y,x,v,[{key:"direction",value:i.direction},{key:"color",value:i.color.rgbNormalLinear},{key:"intensity",value:i.intensityMultiplier*i.lux}])})}static updateAmbientLight(i,g,x,v){updateSystemUniformData(g,x,v,[{key:"color",value:i?i.color.rgbNormalLinear:[0,0,0]},{key:"intensity",value:i?i.intensityMultiplier*i.lux:0}])}}Object.freeze(SystemUniformUpdater);class ResourceStateStorageBuffer{static dirtyList=[];buffer;uuid;#jt=0;constructor(i){this.buffer=i,this.uuid=i.uuid}get useNum(){return this.#jt}set useNum(i){this.#jt=i,ResourceStateStorageBuffer.dirtyList.push(this)}}class StorageBuffer extends AUniformBaseBuffer{constructor(i,g,x="",v=""){super(i,"managedStorageBufferState",GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC,g,x);const{table:_}=this.targetResourceManagedState,y=_.get(v);if(y)return y.buffer;v&&(this.name=v,this[kr]=v),this.redGPUContext.resourceManager.registerManagementResource(this,new ResourceStateStorageBuffer(this))}}Object.freeze(StorageBuffer);var wi,Mi="#redgpu_include color.getLuminance @group(0)@binding(0)var sourceTexture:texture_2d;@group(0)@binding(1)var depthTexture:texture_depth_2d;@group(1)@binding(0)varhistogram:array,256>;struct AutoExposureUniforms{deltaTime:f32,targetLuminance:f32,adjustmentSpeedUp:f32,adjustmentSpeedDown:f32,exposureCompensation:f32,minEV100:f32,maxEV100:f32,calibrationConstant:f32,ev100Range:f32,lowPercentile:f32,highPercentile:f32,invEv100Range:f32,width:f32,height:f32,currentPreExposure:f32,maxExposureMultiplier:f32,meteringMode:f32};@group(1)@binding(1)varuniforms:AutoExposureUniforms;varlocalHistogram:array,256>;@compute @workgroup_size(16,16,1)fn main(@builtin(global_invocation_id)global_id:vec3,@builtin(local_invocation_index)local_index:u32){if(local_index<256u){atomicStore(&localHistogram[local_index],0u);}workgroupBarrier();if(f32(global_id.x)(i32(global_id.x),i32(global_id.y)),0).rgb;let brightness=max(color.r,max(color.g,color.b));let lum=brightness/max(uniforms.currentPreExposure,.0001);let texel=textureLoad(sourceTexture,vec2(i32(global_id.x),i32(global_id.y)),0);let depth=textureLoad(depthTexture,vec2(i32(global_id.x),i32(global_id.y)),0);if(lum>.0001&&texel.a>.0&&depth<1.0){let ev100=log2(lum*100.0/uniforms.calibrationConstant);let normalizedEV100=clamp((ev100-uniforms.minEV100)*uniforms.invEv100Range,.0,1.0);let binIndex=u32(normalizedEV100*255.0);var weight=1.0;let uv=vec2(f32(global_id.x)/uniforms.width,f32(global_id.y)/uniforms.height);let dist=distance(uv,vec2(0.5,0.5));if(uniforms.meteringMode==1.0){weight=clamp(1.0-dist*1.0,.0,1.0);weight=weight*weight;}else if(uniforms.meteringMode==2.0){weight=clamp(1.0-dist*4.0,.0,1.0);weight=weight*weight*weight*weight;}atomicAdd(&localHistogram[binIndex],u32(weight*100.0));}}}workgroupBarrier();if(local_index<256u){let localCount=atomicLoad(&localHistogram[local_index]);if(localCount>0u){atomicAdd(&histogram[local_index],localCount);}}}";!function(i){i[i.AVERAGE=0]="AVERAGE",i[i.CENTER_WEIGHTED=1]="CENTER_WEIGHTED",i[i.SPOT=2]="SPOT"}(wi||(wi={})),Object.freeze(wi);var Pi=wi;const Ri={COLOR:"gBufferColor",NORMAL:"gBufferNormal",MOTION_VECTOR:"gBufferMotionVector",RENDER_PATH1_RESULT:"renderPath1ResultTexture"};Object.freeze(Ri);class AutoExposure extends RedGPUObject{#Ri;#Ci;#Bi;#Di;#Ei=new Map;#Ii=new Map;#Ai;#Li;#se;#Ui=1;#ki;#Gi=!1;#Oi=0;#Vi=15;#Ni=3;#Fi=1;#Hi=.8;#zi=.983;#$i=16;#ji=Pi.AVERAGE;#Ki=.18;#Xi=0;#ii;#qi;#Yi;#Wi=new WeakMap;#Zi;#Ji;constructor(i){super(i.redGPUContext),this.#Ri=i,this.#Qi(),this.#en()}get exposureCompensation(){return this.#Xi}set exposureCompensation(i){this.#Xi=i}get targetLuminance(){return this.#Ki}set targetLuminance(i){this.#Ki=i}get minEV100(){return this.#Oi}set minEV100(i){this.#Oi=i}get maxEV100(){return this.#Vi}set maxEV100(i){this.#Vi=i}get adaptationSpeedUp(){return this.#Ni}set adaptationSpeedUp(i){this.#Ni=i}get adaptationSpeedDown(){return this.#Fi}set adaptationSpeedDown(i){this.#Fi=i}get lowPercentile(){return this.#Hi}set lowPercentile(i){this.#Hi=i}get highPercentile(){return this.#zi}set highPercentile(i){this.#zi=i}get maxExposureMultiplier(){return this.#$i}set maxExposureMultiplier(i){this.#$i=i}get meteringMode(){return this.#ji}set meteringMode(i){this.#ji=i}get preExposure(){const{rawCamera:i}=this.#Ri;return this.#tn(i.ev100,this.#Xi)}get currentAdaptedEV100(){return this.#Ui}set currentAdaptedEV100(i){this.#Ui=i;const g=new Float32Array([i]);this.gpuDevice.queue.writeBuffer(this.#Ci.gpuBuffer,0,g.buffer)}get adaptedLuminanceBuffer(){return this.#Ci}render(i){const{gpuDevice:g,antialiasingManager:x,commandEncoderManager:v}=this,{useMSAA:_,msaaID:y}=x,{width:b,height:S}=this.#Ri.viewRenderTextureManager.getGBufferTexture(Ri.COLOR),{rawCamera:w,renderViewStateData:L,viewRenderTextureManager:H}=this.#Ri,{deltaTime:z,swapBufferIndex:q}=L,W=this.#Vi-this.#Oi,be=this.#tn(w.ev100,this.#Xi);g.queue.writeBuffer(this.#se.gpuBuffer,0,new Float32Array([z,this.#Ki,this.#Ni,this.#Fi,this.#Xi,this.#Oi,this.#Vi,ACamera.CALIBRATION_CONSTANT,W,this.#Hi,this.#zi,1/W,b,S,be,this.#$i,this.#ji]));const je=this.#ii!==y,Ke=this.#qi!==b||this.#Yi!==S;(je||Ke)&&(this.#Wi=new WeakMap,this.#ii=y,this.#qi=b,this.#Yi=S);let Xe=this.#Wi.get(i.texture);if(!Xe){const x=H.depthTextureView,v=H.prevDepthTextureView,y=this.#rn(_);Xe={swap0:g.createBindGroup({label:"AutoExposure_Downsample_BG0_Swap0",layout:y,entries:[{binding:0,resource:i.textureView},{binding:1,resource:x}]}),swap1:g.createBindGroup({label:"AutoExposure_Downsample_BG0_Swap1",layout:y,entries:[{binding:0,resource:i.textureView},{binding:1,resource:v}]})},this.#Wi.set(i.texture,Xe)}v.useEncoder(k.POST_PROCESS,i=>{i.clearBuffer(this.#Bi.gpuBuffer)});const Ye=this.#in(_);v.addPostProcessComputePass("AutoExposure_GenerateHistogram_Pass",i=>{i.setPipeline(Ye),i.setBindGroup(0,q?Xe.swap1:Xe.swap0),i.setBindGroup(1,this.#Zi),i.dispatchWorkgroups(Math.ceil(b/16),Math.ceil(S/16),1)}),v.addPostProcessComputePass("AutoExposure_Adaptation_Pass",i=>{i.setPipeline(this.#Di),i.setBindGroup(0,this.#Ji),i.dispatchWorkgroups(1,1,1)}),this.#Gi||v.useEncoder(k.POST_PROCESS,i=>{copyGPUBuffer(i,this.#Ci.gpuBuffer,this.#ki)})}resolveReadback(){this.#Gi||(this.#Gi=!0,this.#ki.mapAsync(GPUMapMode.READ).then(()=>{const i=new Float32Array(this.#ki.getMappedRange());this.#Ui=i[0],this.#ki.unmap(),this.#Gi=!1}).catch(()=>{this.#Gi=!1}))}#tn(i,g){return Math.pow(2,g)/(1.2*Math.pow(2,i))}#Qi(){const{gpuDevice:i,redGPUContext:g}=this;this.#Ri.rawCamera.updateExposure();const x=Math.max(this.#Oi,Math.min(this.#Vi,this.#Ri.rawCamera.ev100));this.#Ui=x;const v=new Float32Array([x]);this.#Ci=new StorageBuffer(g,v.buffer,"AutoExposure_AdaptedEV100"),this.#Bi=new StorageBuffer(g,new Uint32Array(256).buffer,"AutoExposure_HistogramBuffer"),this.#ki=i.createBuffer({size:4,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,label:"AutoExposure_ReadBuffer"});const _=new Float32Array(18);this.#se=new UniformBuffer(g,_.buffer,"AutoExposure_UniformBuffer")}#en(){const{gpuDevice:i,resourceManager:g}=this,x=g.createGPUShaderModule("AutoExposure_Adaptation",{code:"struct AutoExposureUniforms{deltaTime:f32,targetLuminance:f32,adjustmentSpeedUp:f32,adjustmentSpeedDown:f32,exposureCompensation:f32,minEV100:f32,maxEV100:f32,calibrationConstant:f32,ev100Range:f32,lowPercentile:f32,highPercentile:f32,invEv100Range:f32,width:f32,height:f32,currentPreExposure:f32,maxExposureMultiplier:f32,meteringMode:f32};@group(0)@binding(0)varhistogram:array,256>;@group(0)@binding(1)varadaptedEV100:f32;@group(0)@binding(2)varuniforms:AutoExposureUniforms;@compute @workgroup_size(1,1,1)fn main(){var countBuffer:array;var totalPixels:u32=0u;for(var i=0u;i<256u;i=i+1u){let val=atomicExchange(&histogram[i],0u);countBuffer[i]=val;totalPixels+=val;}if(totalPixels==0u){return;}let minPixel=u32(f32(totalPixels)*uniforms.lowPercentile);let maxPixel=u32(f32(totalPixels)*uniforms.highPercentile);var pixelCounter:u32=0u;var weightedEV100Sum:f32=.0;var totalValidPixels:f32=.0;for(var i=0u;i<256u;i=i+1u){let nextCounter=pixelCounter+countBuffer[i];let validPixels=max(.0,f32(min(nextCounter,maxPixel))-f32(max(pixelCounter,minPixel)));if(validPixels>.0){let ev100=uniforms.minEV100+(f32(i)/255.0)*uniforms.ev100Range;weightedEV100Sum+=ev100*validPixels;totalValidPixels+=validPixels;}pixelCounter=nextCounter;}let avgEV100=weightedEV100Sum/max(totalValidPixels,1.0);var targetEV100=avgEV100-log2((120.0*uniforms.targetLuminance)/uniforms.calibrationConstant)-uniforms.exposureCompensation;let minPossibleEV100=uniforms.exposureCompensation-log2(1.2*uniforms.maxExposureMultiplier);targetEV100=max(targetEV100,minPossibleEV100);let prevEV100=adaptedEV100;let diff=targetEV100-prevEV100;let speed=select(uniforms.adjustmentSpeedDown,uniforms.adjustmentSpeedUp,diff>.0);let adaptationFactor=1.0-exp(-speed*uniforms.deltaTime);var nextEV100=prevEV100+diff*adaptationFactor;adaptedEV100=clamp(nextEV100,uniforms.minEV100,uniforms.maxEV100);}"});this.#Ai=g.createBindGroupLayout("AutoExposure_Downsample_BGL1",{entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}},{binding:1,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}}]}),this.#Li=g.createBindGroupLayout("AutoExposure_Adaptation_BGL0",{entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}},{binding:1,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}},{binding:2,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}}]}),this.#Di=i.createComputePipeline({label:"AutoExposure_Adaptation_Pipeline",layout:i.createPipelineLayout({bindGroupLayouts:[this.#Li]}),compute:{module:x,entryPoint:"main"}}),this.#Zi=i.createBindGroup({label:"AutoExposure_Downsample_BG1",layout:this.#Ai,entries:[{binding:0,resource:{buffer:this.#Bi.gpuBuffer}},{binding:1,resource:{buffer:this.#se.gpuBuffer}}]}),this.#Ji=i.createBindGroup({label:"AutoExposure_Adaptation_BG0",layout:this.#Li,entries:[{binding:0,resource:{buffer:this.#Bi.gpuBuffer}},{binding:1,resource:{buffer:this.#Ci.gpuBuffer}},{binding:2,resource:{buffer:this.#se.gpuBuffer}}]})}#in(i){if(this.#Ii.has(i))return this.#Ii.get(i);const{gpuDevice:g,resourceManager:x}=this,v=i?Mi.replace("texture_depth_2d","texture_depth_multisampled_2d"):Mi,_=x.createGPUShaderModule("AutoExposure_Downsample_"+(i?"MSAA":"NonMSAA"),{code:v}),y=this.#rn(i),b=g.createComputePipeline({label:"AutoExposure_Downsample_Pipeline_"+(i?"MSAA":"NonMSAA"),layout:g.createPipelineLayout({bindGroupLayouts:[y,this.#Ai]}),compute:{module:_,entryPoint:"main"}});return this.#Ii.set(i,b),b}#rn(i){if(this.#Ei.has(i))return this.#Ei.get(i);const{gpuDevice:g}=this,x=g.createBindGroupLayout({label:"AutoExposure_Downsample_BGL0_"+(i?"MSAA":"NonMSAA"),entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,texture:{}},{binding:1,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:"depth",multisampled:i}}]});return this.#Ei.set(i,x),x}}Object.freeze(AutoExposure);class PostEffectTexturePool extends RedGPUObject{#nn=new Map;#an=new Set;#sn=new WeakMap;#on=new WeakMap;#H=0;#un=0;#ln=0;#cn=0;constructor(i){super(i)}get videoMemorySize(){return this.#H}get totalCount(){return this.activeCount+this.idleCount}get activeCount(){return this.#an.size}get idleCount(){let i=0;return this.#nn.forEach(g=>i+=g.length),i}get peakActiveCount(){return this.#un}get allocationCount(){return this.#ln}get hitRate(){return 0===this.#cn?0:(this.#cn-this.#ln)/this.#cn}getDetails(){const i=[];return this.#nn.forEach((g,x)=>{const v=[...this.#an].filter(i=>this.#sn.get(i)===x).length;i.push({key:x,total:g.length+v,active:v,idle:g.length})}),i}allocResult(i,g,x="rgba16float"){const v=this.#hn(i,g,x);return{texture:v,textureView:this.#on.get(v)}}release(i){if(this.#an.has(i)){this.#an.delete(i);const g=this.#sn.get(i);g&&this.#nn.get(g).push(i)}}releaseAll(){this.#an.forEach(i=>{const g=this.#sn.get(i);g&&this.#nn.get(g).push(i)}),this.#an.clear()}clear(){this.releaseAll(),this.#nn.forEach(i=>{i.forEach(i=>i.destroy())}),this.#nn.clear(),this.#H=0,this.#un=0,this.#ln=0,this.#cn=0}#hn(i,g,x="rgba16float"){const{resourceManager:v}=this;this.#cn++;const _=`${i}x${g}_${x}`;let y,b=this.#nn.get(_);return b||(b=[],this.#nn.set(_,b)),b.length>0?y=b.shift():(this.#ln++,y=v.createManagedTexture({size:{width:i,height:g},format:x,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.COPY_SRC|GPUTextureUsage.COPY_DST,label:`PostEffectTexturePool_${_}`}),this.#H+=calculateTextureByteSize(y),this.#sn.set(y,_),this.#on.set(y,v.getGPUResourceBitmapTextureView(y))),this.#an.add(y),this.#an.size>this.#un&&(this.#un=this.#an.size),y}}Object.freeze(PostEffectTexturePool);class PostEffectManager{#Ri;#fn=[];#dn;#mn;#pn;#gn;#H=0;#xn;#vn;#_n;#yn;#bn;#Sn=!1;#Tn;#wn=!1;#Mn;#Pn;#Rn;#Cn;#Bn;#Dn;constructor(i){this.#Ri=i,this.#dn=new PostEffectTexturePool(this.#Ri.redGPUContext),this.#N(),this.#En()}get gbufferBindGroupLayout(){return this.#Ri.redGPUContext.antialiasingManager.useMSAA?this.#Pn:this.#Rn}get gbufferBindGroup(){return this.#Ri.renderViewStateData.swapBufferIndex?this.#Bn:this.#Cn}get texturePool(){return this.#dn}get autoExposure(){return this.#Mn||(this.#Mn=new AutoExposure(this.#Ri)),this.#Mn}get useSSAO(){return this.#Sn}set useSSAO(i){this.#Sn=i,this.#In()}get ssao(){return this.#bn||(this.#bn=new SSAO(this.#Ri.redGPUContext)),this.#bn}get useSSR(){return this.#wn}set useSSR(i){this.#wn=i,this.#An()}get ssr(){return this.#Tn||(this.#Tn=new SSR(this.#Ri.redGPUContext)),this.#Tn}get postEffectSystemUniformBuffer(){return this.#pn}get view(){return this.#Ri}get effectList(){return this.#fn}get videoMemorySize(){return this.#ci(),this.#H}addEffect(i){this.#fn.push(i)}getEffectAt(i){return this.#fn[i]}removeEffect(i){const g=this.#fn.indexOf(i);g>-1&&(i.clear(),this.#fn.splice(g,1))}removeEffectAt(i){this.#fn[i]&&(this.#fn[i].clear(),this.#fn.splice(i,1))}removeAllEffect(){this.#fn.forEach(i=>{i.clear()}),this.#fn.length=0}render(){const{viewRenderTextureManager:i,redGPUContext:g,taa:x,fxaa:v}=this.#Ri,{antialiasingManager:_}=g,{useMSAA:y,useFXAA:b,useTAA:S,msaaID:w}=_,L=i.getGBufferTexture(Ri.COLOR),{width:k,height:H}=L;this.#Dn!==w&&this.#dn.clear(),y?i.getGBufferResolveTexture(Ri.COLOR):i.getGBufferTexture(Ri.COLOR),this.#Ln(),this.#Un();const{useAutoExposure:z}=this.#Ri.rawCamera;let q=this.#kn(this.#Ri);this.#Ri.skyAtmosphere&&(q=this.#Gn(q,()=>this.#Ri.skyAtmosphere.render(this.#Ri,k,H,q))),this.#Sn&&(q=this.#Gn(q,()=>this.ssao.render(this.#Ri,k,H,q))),this.#wn&&(q=this.#Gn(q,()=>this.ssr.render(this.#Ri,k,H,q))),z&&this.autoExposure.render(q);let W=!1;return this.#fn.forEach(i=>{i.isLdr&&!W&&(q=this.#Gn(q,()=>this.#Ri.toneMappingManager.render(this.#Ri,k,H,q)),W=!0),q=this.#Gn(q,()=>i.render(this.#Ri,k,H,q))}),W||(q=this.#Gn(q,()=>this.#Ri.toneMappingManager.render(this.#Ri,k,H,q))),b&&(q=this.#Gn(q,()=>v.render(this.#Ri,k,H,q))),S&&("View3D"===this.#Ri.constructor.name?(q=this.#Gn(q,()=>x.render(this.#Ri,k,H,q)),this.#yn||(this.#yn=new TAASharpen(g)),q=this.#Gn(q,()=>this.#yn.render(this.#Ri,k,H,q))):q=this.#Gn(q,()=>v.render(this.#Ri,k,H,q))),this.#dn.releaseAll(),q}clear(){this.#fn.forEach(i=>{i.clear()}),this.#dn&&this.#dn.clear()}#Gn(i,g){const x=g();return i&&i.texture&&this.#dn.release(i.texture),x}#En(){const{gpuDevice:i}=this.#Ri.redGPUContext,getEntries=i=>[{binding:0,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:"depth",multisampled:i}},{binding:1,visibility:GPUShaderStage.COMPUTE,texture:{}},{binding:2,visibility:GPUShaderStage.COMPUTE,texture:{}},{binding:3,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:"depth",multisampled:i}},{binding:4,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}},{binding:5,visibility:GPUShaderStage.COMPUTE,sampler:{}}];this.#Pn=i.createBindGroupLayout({label:"PostEffect_Shared_GBuffer_BGL_MSAA",entries:getEntries(!0)}),this.#Rn=i.createBindGroupLayout({label:"PostEffect_Shared_GBuffer_BGL_NonMSAA",entries:getEntries(!1)})}#Un(){const{viewRenderTextureManager:i,redGPUContext:g}=this.#Ri,{gpuDevice:x,antialiasingManager:v,resourceManager:_}=g,{useMSAA:y,msaaID:b}=v,S=i.getGBufferTexture(Ri.COLOR),{width:w,height:L}=S,k=this.#Dn!==b,H=this.#mn?.width!==w||this.#mn?.height!==L;if(k||H){const g=i.depthTextureView,v=i.prevDepthTextureView,S=y?i.getGBufferResolveTextureView(Ri.NORMAL):i.getGBufferTextureView(Ri.NORMAL),w=y?i.getGBufferResolveTextureView(Ri.MOTION_VECTOR):i.getGBufferTextureView(Ri.MOTION_VECTOR),L=_.basicSampler.gpuSampler,k={buffer:this.#pn.gpuBuffer,offset:0,size:this.#pn.size},getEntries=(i,g)=>[{binding:0,resource:i},{binding:1,resource:S},{binding:2,resource:w},{binding:3,resource:g},{binding:4,resource:k},{binding:5,resource:L}],H=y?this.#Pn:this.#Rn;this.#Cn=x.createBindGroup({label:"PostEffect_Shared_GBuffer_BG_Swap0",layout:H,entries:getEntries(g,v)}),this.#Bn=x.createBindGroup({label:"PostEffect_Shared_GBuffer_BG_Swap1",layout:H,entries:getEntries(v,g)}),this.#Dn=b}}#In(){!this.#bn&&this.#Sn&&(this.#bn=new SSAO(this.#Ri.redGPUContext))}#An(){!this.#Tn&&this.#wn&&(this.#Tn=new SSR(this.#Ri.redGPUContext))}#Ln(){const{inverseProjectionMatrix:i,projectionMatrix:g,noneJitterProjectionMatrix:x,rawCamera:v,redGPUContext:_,taa:y,renderViewStateData:b,skyAtmosphere:S}=this.#Ri,{gpuDevice:w,antialiasingManager:L}=_,{viewMatrix:k}=v,{gpuBuffer:H}=this.#pn,{members:z}=this.#gn,{camera:q,time:W,projection:be}=z;v.updateExposure(this.#Ri);const je=multiply$4(Ci,g,k),Ke=multiply$4(Bi,x,k);SystemUniformUpdater.updateCamera(v,q.members,this.#vn,this.#_n),SystemUniformUpdater.updateTime(b,W.members,this.#vn,this.#_n),SystemUniformUpdater.updateProjection({projectionMatrix:g,projectionViewMatrix:je,noneJitterProjectionMatrix:x,noneJitterProjectionViewMatrix:Ke,inverseProjectionMatrix:i,inverseProjectionViewMatrix:invert$1(Di,je),prevNoneJitterProjectionViewMatrix:L.useTAA?y.prevNoneJitterProjectionViewMatrix:Ke},be.members,this.#vn,this.#_n),SystemUniformUpdater.updateSkyAtmosphere(S,z,this.#vn,this.#_n),updateSystemUniformData(z,this.#vn,this.#_n,[{key:"preExposure",value:this.autoExposure.preExposure},{key:"devicePixelRatio",value:devicePixelRatio}]),w.queue.writeBuffer(H,0,this.#xn)}#N(){const{redGPUContext:i}=this.#Ri,g=parseWGSL("POST_EFFECT_SYSTEM_UNIFORM",ft.POST_EFFECT_SYSTEM_UNIFORM).uniforms.systemUniforms,x=new ArrayBuffer(g.arrayBufferByteLength);this.#gn=g,this.#pn=new UniformBuffer(i,x,`${this.#Ri.name}_POST_EFFECT_SYSTEM_UNIFORM_BUFFER`),this.#xn=new ArrayBuffer(this.#gn.endOffset),this.#vn=new Float32Array(this.#xn),this.#_n=new Uint32Array(this.#xn)}#ci(){this.#H=0,this.#dn&&(this.#H+=this.#dn.videoMemorySize),this.#fn.forEach(i=>{this.#H+=i.videoMemorySize})}#kn(i){const{redGPUContext:g,viewRenderTextureManager:x}=i,v=x.getGBufferTexture(Ri.COLOR),{antialiasingManager:_}=g,{width:y,height:b}=v;(y!==this.#mn?.width||b!==this.#mn?.height)&&(this.#dn.clear(),this.#mn={width:y,height:b});return{texture:_.useMSAA?x.getGBufferResolveTexture(Ri.COLOR):x.getGBufferTexture(Ri.COLOR),textureView:_.useMSAA?x.getGBufferResolveTextureView(Ri.COLOR):x.getGBufferTextureView(Ri.COLOR)}}}let Ci=create$4(),Bi=create$4(),Di=create$4();Object.freeze(PostEffectManager);class GeometryGPURenderInfo{buffers;constructor(i){this.buffers=i}}Object.freeze(GeometryGPURenderInfo);class AABB{minX;maxX;minY;maxY;minZ;maxZ;centerX;centerY;centerZ;xSize;ySize;zSize;geometryRadius;constructor(i,g,x,v,_,y){this.minX=i,this.maxX=g,this.minY=x,this.maxY=v,this.minZ=_,this.maxZ=y,this.centerX=(g+i)/2,this.centerY=(v+x)/2,this.centerZ=(y+_)/2,this.xSize=g-i,this.ySize=v-x,this.zSize=y-_,this.geometryRadius=Math.sqrt((this.xSize/2)**2+(this.ySize/2)**2+(this.zSize/2)**2)}intersects(i){return i instanceof AABB||consoleAndThrowError("allow only AABB instance"),this.minX<=i.maxX&&this.maxX>=i.minX&&this.minY<=i.maxY&&this.maxY>=i.minY&&this.minZ<=i.maxZ&&this.maxZ>=i.minZ}contains(i,g,x){if(Array.isArray(i)){const[g,x,v]=i;return g>=this.minX&&g<=this.maxX&&x>=this.minY&&x<=this.maxY&&v>=this.minZ&&v<=this.maxZ}return i>=this.minX&&i<=this.maxX&&g>=this.minY&&g<=this.maxY&&x>=this.minZ&&x<=this.maxZ}clone(){return new AABB(this.minX,this.maxX,this.minY,this.maxY,this.minZ,this.maxZ)}}Object.freeze(AABB);const calculateGeometryAABB=i=>{if(!i||!i.data||0===i.vertexCount)return new AABB(0,0,0,0,0,0);const g=i.stride,x=i.data,v=i.vertexCount;let _=1/0,y=1/0,b=1/0,S=-1/0,w=-1/0,L=-1/0,k=0;for(;k<=v-4;k+=4){let i=k*g;const v=x[i],H=x[i+1],z=x[i+2];i=(k+1)*g;const q=x[i],W=x[i+1],be=x[i+2];i=(k+2)*g;const je=x[i],Ke=x[i+1],Xe=x[i+2];i=(k+3)*g;const Ye=x[i],Ze=x[i+1],Je=x[i+2];v<_&&(_=v),q<_&&(_=q),je<_&&(_=je),Ye<_&&(_=Ye),v>S&&(S=v),q>S&&(S=q),je>S&&(S=je),Ye>S&&(S=Ye),Hw&&(w=H),W>w&&(w=W),Ke>w&&(w=Ke),Ze>w&&(w=Ze),zL&&(L=z),be>L&&(L=be),Xe>L&&(L=Xe),Je>L&&(L=Je)}for(;kS&&(S=v),H>w&&(w=H),z>L&&(L=z)}return new AABB(_,S,y,w,b,L)};class Geometry extends ResourceBase{gpuRenderInfo;#On;#Vn;#Nn;constructor(i,g,x){super(i),this.#Fn(g),this.#Hn(x);const{interleavedStruct:v}=this.#On;this.gpuRenderInfo=new GeometryGPURenderInfo([{arrayStride:v.arrayStride,attributes:v.attributes}])}get vertexBuffer(){return this.#On}get indexBuffer(){return this.#Vn}get volume(){return this.#Nn||(this.#Nn=calculateGeometryAABB(this.#On)),this.#Nn}#Fn(i){const g=this.#On;this.#On=i,g&&g.__removeDirtyPipelineListener(this.#zn),i&&i.__addDirtyPipelineListener(this.#zn),this.#Nn=null}#Hn(i){const g=this.#Vn;this.#Vn=i,g&&g.__removeDirtyPipelineListener(this.#$n),i&&i.__addDirtyPipelineListener(this.#$n)}#zn(){this.notifyUpdate()}#$n(){this.notifyUpdate()}}Object.freeze(Geometry);const Ei={POINT_LIST:"point-list",LINE_LIST:"line-list",LINE_STRIP:"line-strip",TRIANGLE_LIST:"triangle-list",TRIANGLE_STRIP:"triangle-strip"};Object.freeze(Ei);function createColorRGB(i,g,x,v){let _=255,y=255,b=255;if(isHexColor(v)){const i=convertHexToRgb(v);_=i.r,y=i.g,b=i.b}return new ColorRGB(_,y,b,()=>{updateTargetUniform(i,g,i[x].rgbNormalLinear)})}function defineColorRGB_func(i){const g=i.key,x=i.value??"#fff",v=Symbol(g);return{get:function(){return void 0===this[v]&&(this[v]=createColorRGB(this,g,v,x)),this[v]},set:function(i){if("string"==typeof i&&isHexColor(i)){const{r:x,g:_,b:y}=convertHexToRgb(i);this[v]?(this[v].r=x,this[v].g=_,this[v].b=y):this[v]=createColorRGB(this,g,v,i)}else i instanceof ColorRGB&&(this[v]=i,updateTargetUniform(this,g,i.rgbNormalLinear))},...vi}}const defineColorRGB=(i,g)=>applyProperties(i,g,defineColorRGB_func);Object.freeze(defineColorRGB);const Ii=parseWGSL("COLOR_MATERIAL","#redgpu_include SYSTEM_UNIFORM #redgpu_include entryPoint.mesh.entryPointPickingFragment #redgpu_include color.getTintBlendMode #redgpu_include systemStruct.OutputFragment #redgpu_include math.getMotionVector struct Uniforms{color:vec3,opacity:f32,useTint:u32,tint:vec4,tintBlendMode:u32,};struct InputData{@builtin(position)position:vec4,@location(0)vertexPosition:vec3,@location(7)currentClipPos:vec4,@location(8)prevClipPos:vec4,@location(11)combinedOpacity:f32,@location(12)motionVector:vec3,@location(15)@interpolate(flat)pickingId:vec4,}@group(2)@binding(0)varuniforms:Uniforms;@fragment fn main(inputData:InputData)->OutputFragment{var output:OutputFragment;var finalColor=vec4(uniforms.color.r,uniforms.color.g,uniforms.color.b,uniforms.opacity*inputData.combinedOpacity);#redgpu_if useTint finalColor=getTintBlendMode(finalColor,uniforms.tintBlendMode,uniforms.tint);#redgpu_endIf if(finalColor.a==.0){discard;}output.color=vec4(finalColor.rgb,finalColor.a);output.gBufferMotionVector=vec4(getMotionVector(inputData.currentClipPos,inputData.prevClipPos),.0,1.0);return output;}");class ColorMaterial extends ABaseMaterial{constructor(i,g="#fff"){super(i,"COLOR_MATERIAL",Ii,2),this.initGPURenderInfos(),this.color.setColorByHEX(g)}}defineColorRGB(ColorMaterial,[{key:"color"}]),Object.freeze(ColorMaterial);class ResourceStateVertexBuffer{static dirtyList=[];buffer;label;uuid;#jt=0;constructor(i){this.buffer=i,this.label=i.name,this.uuid=i.uuid}get useNum(){return this.#jt}set useNum(i){this.#jt=i,ResourceStateVertexBuffer.dirtyList.push(this)}}class VertexBuffer extends ABaseBuffer{[Ar];#jn=0;#Kn=0;#Xn;#qn=0;constructor(i,g,x,v=GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST|GPUBufferUsage.STORAGE,_=""){super(i,"managedVertexBufferState",v);const{table:y}=this.targetResourceManagedState,b=y.get(_);if(b)return b.buffer;this.#Xn=x,_&&(this.name=_,this[kr]=_),this.changeData(g,this.#Xn),this.redGPUContext.resourceManager.registerManagementResource(this,new ResourceStateVertexBuffer(this))}get data(){return this[Ar]}get stride(){return this.#Kn}get interleavedStruct(){return this.#Xn}get vertexCount(){return this.#jn}get triangleCount(){return this.#qn}changeData(i,g){const{gpuDevice:x}=this;if(Array.isArray(i)&&(i=new Float32Array(i)),this[Ar]=i,g&&this.#Yn(g),this[Ir]){this.targetResourceManagedState.videoMemory-=this[Ar].byteLength||0;let i=this[Ir];requestAnimationFrame(()=>{i.destroy()}),this[Ir]=null}const v={size:this[Ar].byteLength,usage:this.usage,label:this.name};this[Ir]=x.createBuffer(v),this.targetResourceManagedState.videoMemory+=this[Ar].byteLength||0,this.#qn=this[Ar].length/this.#Kn/3,x.queue.writeBuffer(this[Ir],0,this[Ar])}updateData(i,g=0){i instanceof Array&&(i=new Float32Array(i));const{gpuDevice:x}=this;x.queue.writeBuffer(this[Ir],g,i)}updateAllData(i){const{gpuDevice:g}=this;g.queue.writeBuffer(this[Ir],0,this[Ar])}#Yn(i){this.#Xn=i,this.#jn=0,this.#Kn=0;for(const i in this.#Xn.define){const g=this.#Xn.define[i].attributeStride/Float32Array.BYTES_PER_ELEMENT;this.#jn+=g,this.#Kn+=g}this.#jn=this[Ar].length/this.#jn}}Object.freeze(VertexBuffer);class VertexInterleavedStructElement{attributeName;attributeStride;interleaveType;constructor(i,g,x){this.attributeName=i,this.attributeStride=g,this.interleaveType=x}}class VertexInterleavedStruct{#Wn;#l="";#Zn=[];#Jn=0;constructor(i,g=""){this.#l=g,this.#Qn(i),this.#ea()}get label(){return this.#l}get attributes(){return this.#Zn}get arrayStride(){return this.#Jn}get define(){return{...this.#Wn}}getAttributeOffset(i){const g=this.#Zn.find(g=>g.attributeName===i);return g||consoleAndThrowError(`Attribute not found: ${i}`),g.offset/4}#Qn(i){let g={};for(const x in i){const v=i[x],_=v.stride;g[x]=new VertexInterleavedStructElement(x,_,v),_%4!=0&&consoleAndThrowError(`Invalid attribute stride: ${_}`)}this.#Wn=g}#ea(){this.#Jn=0,this.#Zn=[];for(const[i,{attributeStride:g,interleaveType:x}]of Object.entries(this.#Wn))this.#Zn.push({attributeName:i,shaderLocation:this.#Zn.length,offset:this.#Jn,format:x.gpuVertexFormat}),this.#Jn+=g}}class VertexInterleaveType{static get float32(){return{numElements:1,stride:Float32Array.BYTES_PER_ELEMENT,gpuVertexFormat:"float32",offset:0}}static get float32x2(){return{numElements:2,stride:2*Float32Array.BYTES_PER_ELEMENT,gpuVertexFormat:"float32x2",offset:0}}static get float32x3(){return{numElements:3,stride:3*Float32Array.BYTES_PER_ELEMENT,gpuVertexFormat:"float32x3",offset:0}}static get float32x4(){return{numElements:4,stride:4*Float32Array.BYTES_PER_ELEMENT,gpuVertexFormat:"float32x4",offset:0}}}Object.freeze(VertexInterleaveType);class DrawBufferManager extends RedGPUObject{static#ta;static#ra=5;#ia=[];#na=[];#aa;#sa=0;#oa=0;#ua;#la=new Set;constructor(i){super(i),this.#ca()}static getInstance(i){return DrawBufferManager.#ta||(DrawBufferManager.#ta=new DrawBufferManager(i)),DrawBufferManager.#ta}allocateDrawCommand(i){this.#oa>=this.#aa&&(this.#sa=this.#ha(),this.#oa=0),this.#la.add(this.#sa);const g={bufferIndex:this.#sa,commandOffset:this.#oa*DrawBufferManager.#ra,buffer:this.#ia[this.#sa],dataArray:this.#na[this.#sa]};return this.#oa++,g}setIndexedIndirectCommand(i,g,x=1,v=0,_=0,y=0){const b=i.commandOffset,S=i.dataArray;S[b]=g,S[b+1]=x,S[b+2]=v,S[b+3]=_,S[b+4]=y}setInstanceNum(i,g=0){const x=i.commandOffset;i.dataArray[x+1]=g}setIndirectCommand(i,g,x=1,v=0,_=0){const y=i.commandOffset,b=i.dataArray;b[y]=g,b[y+1]=x,b[y+2]=v,b[y+3]=_}updateSingleCommand(i){const g=this.#ia[i.bufferIndex],x=this.#na[i.bufferIndex],v=DrawBufferManager.#ra,_=4*i.commandOffset,y=v;this.gpuDevice.queue.writeBuffer(g,_,x,i.commandOffset,y)}getTotalCommandCount(){let i=0;for(const g of this.#la)g===this.#sa?i+=this.#oa:i+=this.#aa;return i}getMemoryUsage(){const i=this.#ia.length,g=this.#la.size,x=i*this.#ua,v=g*this.#ua;return{totalBuffers:i,usedBuffers:g,maxCommandsPerBuffer:this.#aa,totalMemory:formatBytes(x),usedMemory:formatBytes(v),totalCommands:this.getTotalCommandCount()}}flushAllCommands(i){for(const i of this.#la){const g=this.#ia[i],x=this.#na[i],v=(i===this.#sa?this.#oa:this.#aa)*DrawBufferManager.#ra*4;this.gpuDevice.queue.writeBuffer(g,0,x,0,v/4)}performance.now()}#ca(){this.#fa(),this.#da()}#fa(){const i=this.redGPUContext.detector.activeLimits;this.#ua=Math.floor(.9*Math.min(i.maxBufferSize,134217728)),this.#aa=Math.floor(this.#ua/(4*DrawBufferManager.#ra))}#da(){this.#ha()}#ha(){const i=this.#aa*DrawBufferManager.#ra*4,g=this.gpuDevice.createBuffer({size:i,usage:GPUBufferUsage.INDIRECT|GPUBufferUsage.COPY_DST,label:`DrawBuffer_${this.#ia.length}`}),x=new Uint32Array(this.#aa*DrawBufferManager.#ra);return this.#ia.push(g),this.#na.push(x),this.#ia.length-1}}const calculateMeshAABB=i=>{if(!i||!i._geometry)return i.modelMatrix,new AABB(0,0,0,0,0,0);const g=i._geometry.volume,{minX:x,maxX:v,minY:_,maxY:y,minZ:b,maxZ:S}=g;let w=1/0,L=1/0,k=1/0,H=-1/0,z=-1/0,q=-1/0;const W=i.modelMatrix;for(let i=0;i<8;i++){const g=1&i?v:x,be=2&i?y:_,je=4&i?S:b,Ke=W[0]*g+W[4]*be+W[8]*je+W[12],Xe=W[1]*g+W[5]*be+W[9]*je+W[13],Ye=W[2]*g+W[6]*be+W[10]*je+W[14];KeH&&(H=Ke),Xe>z&&(z=Xe),Ye>q&&(q=Ye)}return new AABB(w,H,L,z,k,q)},calculateMeshCombinedAABB=i=>{const g=[];return collectRecursive(i,g),0===g.length?new AABB(0,0,0,0,0,0):calculateCombinedAABBFromAABBs(g)},collectRecursive=(i,g)=>{if(i._geometry){const x=i.boundingAABB;g.push(x)}if(i.children)for(let x=0;x{if(0===i.length)return new AABB(0,0,0,0,0,0);if(1===i.length)return i[0];let g=1/0,x=1/0,v=1/0,_=-1/0,y=-1/0,b=-1/0;for(let S=0;S_&&(_=w.maxX),w.maxY>y&&(y=w.maxY),w.maxZ>b&&(b=w.maxZ)}return new AABB(g,_,x,y,v,b)};class OBB{centerX;centerY;centerZ;halfExtentX;halfExtentY;halfExtentZ;orientation;center;halfExtents;geometryRadius;constructor(i,g,x){this.centerX=i[0],this.centerY=i[1],this.centerZ=i[2],this.halfExtentX=g[0],this.halfExtentY=g[1],this.halfExtentZ=g[2],this.center=[this.centerX,this.centerY,this.centerZ],this.halfExtents=[this.halfExtentX,this.halfExtentY,this.halfExtentZ],this.orientation=clone$4(x),this.geometryRadius=Math.sqrt(this.halfExtentX**2+this.halfExtentY**2+this.halfExtentZ**2)}intersects(i){i instanceof OBB||consoleAndThrowError("allow only OBB instance");const g=subtract$2(create$3(),this.center,i.center);if(length$3(g)>this.geometryRadius+i.geometryRadius)return!1;const x=[...this.#ma(),...i.#ma()];for(const v of x){const x=this.#pa(v),_=i.#pa(v);if(Math.abs(dot$3(g,v))>x+_)return!1}return!0}contains(i,g,x){let v;v=Array.isArray(i)?fromValues$3(i[0],i[1],i[2]):fromValues$3(i,g,x);const _=subtract$2(create$3(),v,this.center),y=this.#ma();for(let i=0;i<3;i++){const g=dot$3(_,y[i]);if(Math.abs(g)>this.halfExtents[i])return!1}return!0}clone(){return new OBB([this.centerX,this.centerY,this.centerZ],[this.halfExtentX,this.halfExtentY,this.halfExtentZ],this.orientation)}#ma(){return[fromValues$3(this.orientation[0],this.orientation[1],this.orientation[2]),fromValues$3(this.orientation[4],this.orientation[5],this.orientation[6]),fromValues$3(this.orientation[8],this.orientation[9],this.orientation[10])]}#pa(i){const g=this.#ma();return Math.abs(dot$3(g[0],i))*this.halfExtentX+Math.abs(dot$3(g[1],i))*this.halfExtentY+Math.abs(dot$3(g[2],i))*this.halfExtentZ}}const calculateMeshOBB=i=>{if(!i||!i._geometry){const i=create$4();return new OBB([0,0,0],[0,0,0],i)}const g=i._geometry.volume;if(0===g.minX&&0===g.maxX&&0===g.minY&&0===g.maxY&&0===g.minZ&&0===g.maxZ){const i=create$4();return new OBB([0,0,0],[0,0,0],i)}const x=[g.centerX,g.centerY,g.centerZ],v=[(g.maxX-g.minX)/2,(g.maxY-g.minY)/2,(g.maxZ-g.minZ)/2],_=create$3();transformMat4$2(_,x,i.modelMatrix);const y=create$4();copy$4(y,i.modelMatrix),y[12]=0,y[13]=0,y[14]=0;const b=[create$3(),create$3(),create$3()],S=[0,0,0];for(let i=0;i<3;i++){const g=[0,0,0];g[i]=v[i],transformMat4$2(b[i],g,y),S[i]=length$3(b[i]),normalize$3(b[i],b[i])}const w=create$4();return w[0]=b[0][0],w[1]=b[0][1],w[2]=b[0][2],w[3]=0,w[4]=b[1][0],w[5]=b[1][1],w[6]=b[1][2],w[7]=0,w[8]=b[2][0],w[9]=b[2][1],w[10]=b[2][2],w[11]=0,w[12]=0,w[13]=0,w[14]=0,w[15]=1,new OBB([_[0],_[1],_[2]],S,w)},mat4ToEuler=(i,g,x)=>{g=g||[0,0,0],x=x||"XYZ";let v=i[0],_=i[4],y=i[8],b=i[1],S=i[5],w=i[9],L=i[2],k=i[6],H=i[10];return"XYZ"===x?(g[1]=Math.asin(clamp(y,-1,1)),Math.abs(y)<.99999?(g[0]=Math.atan2(-w,H),g[2]=Math.atan2(-_,v)):(g[0]=Math.atan2(k,S),g[2]=0)):"YXZ"===x?(g[0]=Math.asin(-clamp(w,-1,1)),Math.abs(w)<.99999?(g[1]=Math.atan2(y,H),g[2]=Math.atan2(b,S)):(g[1]=Math.atan2(-L,v),g[2]=0)):"ZXY"===x?(g[0]=Math.asin(clamp(k,-1,1)),Math.abs(k)<.99999?(g[1]=Math.atan2(-L,H),g[2]=Math.atan2(-_,S)):(g[1]=0,g[2]=Math.atan2(b,v))):"ZYX"===x?(g[1]=Math.asin(-clamp(L,-1,1)),Math.abs(L)<.99999?(g[0]=Math.atan2(k,H),g[2]=Math.atan2(b,v)):(g[0]=0,g[2]=Math.atan2(-_,S))):"YZX"===x?(g[2]=Math.asin(clamp(b,-1,1)),Math.abs(b)<.99999?(g[0]=Math.atan2(-w,S),g[1]=Math.atan2(-L,v)):(g[0]=0,g[1]=Math.atan2(y,H))):"XZY"===x&&(g[2]=Math.asin(-clamp(_,-1,1)),Math.abs(_)<.99999?(g[0]=Math.atan2(k,S),g[1]=Math.atan2(y,v)):(g[0]=Math.atan2(-w,H),g[1]=0)),g};let clamp=function(i,g,x){return Math.max(g,Math.min(x,i))};const Ai=[[-1,-1,-1],[1,-1,-1],[1,1,-1],[-1,1,-1],[-1,-1,1],[1,-1,1],[1,1,1],[-1,1,1]],Li=[[0,1],[1,2],[2,3],[3,0],[4,5],[5,6],[6,7],[7,4],[0,4],[1,5],[2,6],[3,7]];class DrawDebuggerMesh{#ga;#On;#xa;#va;#_a="AABB";#ya;#ba;#Sa=null;#Ta=null;constructor(i,g){this.#ga=g;const x=this.#wa(i);this.#On=x.vertexBuffer,this.#xa=new ColorMaterial(i),this.#xa.color.setColorByRGB(255,0,0),this.#va=new Mesh(i,x,this.#xa),this.#va.primitiveState.cullMode="none",this.#va.primitiveState.topology=Ei.LINE_LIST;const v=this.#wa(i);this.#ya=new ColorMaterial(i),this.#ya.color.setColorByRGB(0,255,0),this.#ba=new Mesh(i,v,this.#ya),this.#ba.primitiveState.cullMode="none",this.#ba.primitiveState.topology=Ei.LINE_LIST}get debugMode(){return this.#_a}set debugMode(i){this.#_a=i,"OBB"===i?this.#xa.color.setColorByRGB(255,0,0):"AABB"===i||"COMBINED_AABB"===i?this.#xa.color.setColorByRGB(0,255,0):"BOTH"===i&&(this.#xa.color.setColorByRGB(255,0,0),this.#ya.color.setColorByRGB(0,255,0)),this.#Sa=null,this.#Ta=null}render(i){if(!this.#ga.enableDebugger)return;if("OBB"===this.#_a){const i=this.#ga.boundingOBB;this.#Ma(i)&&(this.#Pa(i,this.#On),this.#Ra(i))}else if("AABB"===this.#_a||"COMBINED_AABB"===this.#_a){const i="COMBINED_AABB"===this.#_a?this.#ga.combinedBoundingAABB:this.#ga.boundingAABB;this.#Ca(i)&&(this.#Ba(i,this.#On),this.#Da(i))}else if("BOTH"===this.#_a){const i=this.#ga.boundingOBB,g=this.#ga.boundingAABB;this.#Ma(i)&&(this.#Pa(i,this.#On),this.#Ra(i)),this.#Ca(g)&&(this.#Ba(g,this.#ba.geometry.vertexBuffer),this.#Da(g))}let g=!0,x=!0;{const{frustumPlanes:v}=i,_=v[0],y=v[1],b=v[2],S=v[3],w=v[4],L=v[5];{const i=this.#ga.boundingAABB,x=i.centerX,v=i.centerY,k=i.centerZ,H=i.geometryRadius;(_[0]*x+_[1]*v+_[2]*k+_[3]<=-H||y[0]*x+y[1]*v+y[2]*k+y[3]<=-H||b[0]*x+b[1]*v+b[2]*k+b[3]<=-H||S[0]*x+S[1]*v+S[2]*k+S[3]<=-H||w[0]*x+w[1]*v+w[2]*k+w[3]<=-H||L[0]*x+L[1]*v+L[2]*k+L[3]<=-H)&&(g=!1)}{const i=this.#ga.boundingOBB,g=i.centerX,v=i.centerY,k=i.centerZ,H=i.geometryRadius;(_[0]*g+_[1]*v+_[2]*k+_[3]<=-H||y[0]*g+y[1]*v+y[2]*k+y[3]<=-H||b[0]*g+b[1]*v+b[2]*k+b[3]<=-H||S[0]*g+S[1]*v+S[2]*k+S[3]<=-H||w[0]*g+w[1]*v+w[2]*k+w[3]<=-H||L[0]*g+L[1]*v+L[2]*k+L[3]<=-H)&&(x=!1)}}"OBB"===this.#_a?x&&this.#va.render(i):"AABB"===this.#_a||"COMBINED_AABB"===this.#_a?g&&this.#va.render(i):"BOTH"===this.#_a&&(x&&this.#va.render(i),g&&this.#ba.render(i))}#wa(i){const g=new Float32Array(288),x=new VertexInterleavedStruct({vertexPosition:VertexInterleaveType.float32x3,vertexNormal:VertexInterleaveType.float32x3,texcoord:VertexInterleaveType.float32x2,vertexTangent:VertexInterleaveType.float32x4},`wireframeBoxStruct_${Math.random()}`),v=new VertexBuffer(i,g,x);return new Geometry(i,v)}#Ma(i){if(!this.#Sa)return!0;const g=this.#Sa;return g.center[0]!==i.center[0]||g.center[1]!==i.center[1]||g.center[2]!==i.center[2]||g.halfExtents[0]!==i.halfExtents[0]||g.halfExtents[1]!==i.halfExtents[1]||g.halfExtents[2]!==i.halfExtents[2]||!this.#Ea(g.orientation,i.orientation)}#Ca(i){if(!this.#Ta)return!0;const g=this.#Ta;return g.minX!==i.minX||g.maxX!==i.maxX||g.minY!==i.minY||g.maxY!==i.maxY||g.minZ!==i.minZ||g.maxZ!==i.maxZ}#Ea(i,g){if(i.length!==g.length)return!1;for(let x=0;x1e-4)return!1;return!0}#Ra(i){this.#Sa=new OBB(i.center,i.halfExtents,i.orientation)}#Da(i){this.#Ta=i.clone()}#Pa(i,g){const{center:x,halfExtents:v,orientation:_}=i,y=[];for(let i=0;i<8;i++){const g=Ai[i],b=g[0]*v[0],S=g[1]*v[1],w=g[2]*v[2],L=_[0]*b+_[4]*S+_[8]*w,k=_[1]*b+_[5]*S+_[9]*w,H=_[2]*b+_[6]*S+_[10]*w;y.push([L+x[0],k+x[1],H+x[2]])}this.#Fn(y,g)}#Ba(i,g){const{minX:x,maxX:v,minY:_,maxY:y,minZ:b,maxZ:S}=i,w=[[x,_,b],[v,_,b],[v,y,b],[x,y,b],[x,_,S],[v,_,S],[v,y,S],[x,y,S]];this.#Fn(w,g)}#Fn(i,g){const x=g.data;let v=0;for(let g=0;g<12;g++){const _=Li[g],y=_[0],b=_[1],S=i[y],w=i[b];x[v++]=S[0],x[v++]=S[1],x[v++]=S[2],x[v++]=0,x[v++]=0,x[v++]=1,x[v++]=0,x[v++]=0,x[v++]=1,x[v++]=0,x[v++]=0,x[v++]=1,x[v++]=w[0],x[v++]=w[1],x[v++]=w[2],x[v++]=0,x[v++]=0,x[v++]=1,x[v++]=0,x[v++]=0,x[v++]=1,x[v++]=0,x[v++]=0,x[v++]=1}g.updateAllData(x)}}Object.freeze(DrawDebuggerMesh);const createMeshVertexUniformBuffers=(i,g=!1)=>{const{gpuRenderInfo:x,redGPUContext:v}=i,{resourceManager:_}=v,y=_.getGPUBindGroupLayout(g?ResourceManager.PRESET_VERTEX_GPUBindGroupLayout_SKIN:ResourceManager.PRESET_VERTEX_GPUBindGroupLayout),b=new ArrayBuffer(x.vertexUniformInfo.arrayBufferByteLength),S=new UniformBuffer(v,b,i.name);x.vertexBindGroupLayout=y,x.vertexUniformBuffer=S};function createSetter$3(i,g){return function(x){this[g]=x,updateTargetUniform(this,i,x)}}function defineVector(i,g){const x=Symbol(i);return{get:function(){return void 0===this[x]&&(this[x]=g),this[x]},set:createSetter$3(i,x),...vi}}function defineVector3_func(i){return defineVector(i.key,i.value??[0,0,0])}Object.freeze(defineVector);const defineVector3=(i,g)=>applyProperties(i,g,defineVector3_func);function defineVector4_func(i){return defineVector(i.key,i.value??[0,0,0,0])}Object.freeze(defineVector3);const defineVector4=(i,g)=>applyProperties(i,g,defineVector4_func);function defineVector2_func(i){return defineVector(i.key,i.value??[0,0])}Object.freeze(defineVector4);const defineVector2=(i,g)=>applyProperties(i,g,defineVector2_func);function defineSampler_func(i){const{key:g}=i,x=Symbol(g);return{get:function(){return this[x]},set:function(i){const g=this[x];this[x]=i,this.updateSampler(g,i)},...vi}}Object.freeze(defineVector2);const defineSampler=(i,g)=>applyProperties(i,g,defineSampler_func);function createSetter$2(i,g){const x=`use${i.charAt(0).toUpperCase()}${i.substring(1)}`;return function(i){const v=this[g];this[g]=i,this.updateTexture(v,i),x in this&&(this[x]=!!i),updateTargetUniform(this,x,i?1:0)}}function defineTexture_func(i){const{key:g}=i,x=Symbol(g);return{get:function(){return this[x]},set:createSetter$2(g,x),...vi}}Object.freeze(defineSampler);const defineTexture=(i,g)=>applyProperties(i,g,defineTexture_func);Object.freeze(defineTexture);const Ui=[{textureList:["baseColorTexture"],vec4List:[{key:"baseColorFactor",value:[1,1,1,1]}]},{textureList:["normalTexture"]},{textureList:["metallicRoughnessTexture"],positiveNumberList:[{key:"metallicFactor",value:1},{key:"roughnessFactor",value:1}]},{textureList:["emissiveTexture"],vec3List:[{key:"emissiveFactor",value:[0,0,0]}]},{textureList:["occlusionTexture"],positiveNumberList:[{key:"occlusionStrength",value:1}]},{extensionName:"KHR_materials_clearcoat",textureList:["KHR_clearcoatTexture","KHR_clearcoatNormalTexture","KHR_clearcoatRoughnessTexture"],positiveNumberList:[{key:"KHR_clearcoatFactor",value:0},{key:"KHR_clearcoatRoughnessFactor",value:0},{key:"KHR_clearcoatNormalScale",value:1}]},{extensionName:"KHR_materials_sheen",textureList:["KHR_sheenColorTexture","KHR_sheenRoughnessTexture"],positiveNumberList:[{key:"KHR_sheenRoughnessFactor",value:0}],vec3List:[{key:"KHR_sheenColorFactor",value:[0,0,0]}]},{extensionName:"KHR_materials_specular",textureList:["KHR_specularTexture","KHR_specularColorTexture"],positiveNumberList:[{key:"KHR_specularFactor",value:1}],vec3List:[{key:"KHR_specularColorFactor",value:[1,1,1]}]},{extensionName:"KHR_materials_transmission",textureList:["KHR_transmissionTexture"],positiveNumberList:[{key:"KHR_transmissionFactor",value:0}]},{extensionName:"KHR_materials_volume",textureList:["KHR_thicknessTexture"],positiveNumberList:[{key:"KHR_thicknessFactor",value:0},{key:"KHR_attenuationDistance",value:1}],vec3List:[{key:"KHR_attenuationColor",value:[1,1,1]}]},{extensionName:"KHR_materials_diffuse_transmission",textureList:["KHR_diffuseTransmissionTexture","KHR_diffuseTransmissionColorTexture"],positiveNumberList:[{key:"KHR_diffuseTransmissionFactor",value:0}],vec3List:[{key:"KHR_diffuseTransmissionColorFactor",value:[1,1,1]}]},{extensionName:"KHR_materials_anisotropy",textureList:["KHR_anisotropyTexture"],positiveNumberList:[{key:"KHR_anisotropyStrength",value:0},{key:"KHR_anisotropyRotation",value:0}]},{extensionName:"KHR_materials_iridescence",textureList:["KHR_iridescenceTexture","KHR_iridescenceThicknessTexture"],positiveNumberList:[{key:"KHR_iridescenceFactor",value:0},{key:"KHR_iridescenceIor",value:1.3},{key:"KHR_iridescenceThicknessMinimum",value:100},{key:"KHR_iridescenceThicknessMaximum",value:400}]}],ki=parseWGSL("PBR_MATERIAL",(i=>{const g=Ui.map(i=>{const{textureList:g}=i,x=g?.map(i=>`\n\t\t\t\tuse${i.charAt(0).toUpperCase()}${i.substring(1)}: u32,\n \t\t${i}_texCoord_index: u32,\n\t\t\t\tuse_${i}_KHR_texture_transform: u32,\n\t\t\t\t${i}_KHR_texture_transform_offset: vec2,\n\t\t\t\t${i}_KHR_texture_transform_scale: vec2,\n\t\t\t\t${i}_KHR_texture_transform_rotation: f32,`).join("");return[x].join("\n")}).join("");return i.replace(/#redgpu_include KHR_texture_transform/g,g)})("#redgpu_include SYSTEM_UNIFORM;#redgpu_include shadow.getDirectionalShadowVisibility;#redgpu_include color.getTintBlendMode;#redgpu_include entryPoint.mesh.entryPointPickingFragment;#redgpu_include systemStruct.OutputFragment;#redgpu_include math.getMotionVector;#redgpu_include math.getIsFinite;#redgpu_include lighting.getLightDistanceAttenuation;#redgpu_include lighting.getLightAngleAttenuation;#redgpu_include math.PI #redgpu_include math.PI2 #redgpu_include math.INV_PI #redgpu_include math.EPSILON #redgpu_include math.direction.getViewDirection #redgpu_include math.direction.getReflectionVectorFromViewDirection #redgpu_include math.tnb.getTBNFromVertexTangent #redgpu_include math.tnb.getTBN #redgpu_include math.tnb.getNormalFromNormalMap #redgpu_include skyAtmosphere.skyAtmosphereFn struct Uniforms{useVertexColor:u32,useCutOff:u32,cutOff:f32,alphaBlend:u32,doubleSided:u32,useVertexTangent:u32,opacity:f32,useTint:u32,tint:vec4,tintBlendMode:u32,baseColorFactor:vec4,emissiveFactor:vec3,emissiveStrength:f32,occlusionStrength:f32,metallicFactor:f32,roughnessFactor:f32,normalScale:f32,useKHR_materials_unlit:u32,KHR_materials_ior:f32,useKHR_materials_transmission:u32,KHR_transmissionFactor:f32,useKHR_materials_diffuse_transmission:u32,KHR_diffuseTransmissionFactor:f32,KHR_diffuseTransmissionColorFactor:vec3,KHR_dispersion:f32,useKHR_materials_volume:u32,KHR_thicknessFactor:f32,KHR_attenuationDistance:f32,KHR_attenuationColor:vec3,useKHR_materials_specular:u32,KHR_specularFactor:f32,KHR_specularColorFactor:vec3,useKHR_materials_anisotropy:u32,KHR_anisotropyStrength:f32,KHR_anisotropyRotation:f32,useKHR_materials_iridescence:u32,KHR_iridescenceFactor:f32,KHR_iridescenceIor:f32,KHR_iridescenceThicknessMinimum:f32,KHR_iridescenceThicknessMaximum:f32,useKHR_materials_sheen:u32,KHR_sheenColorFactor:vec3,KHR_sheenRoughnessFactor:f32,useKHR_materials_clearcoat:u32,KHR_clearcoatFactor:f32,KHR_clearcoatRoughnessFactor:f32,KHR_clearcoatNormalScale:f32,#redgpu_include KHR_texture_transform};@group(2)@binding(0)varuniforms:Uniforms;@group(2)@binding(1)var baseColorTextureSampler:sampler;#redgpu_if baseColorTexture @group(2)@binding(2)var baseColorTexture:texture_2d;#redgpu_endIf #redgpu_if emissiveTexture @group(2)@binding(3)var emissiveTextureSampler:sampler;@group(2)@binding(4)var emissiveTexture:texture_2d;#redgpu_endIf #redgpu_if normalTexture @group(2)@binding(5)var normalTextureSampler:sampler;@group(2)@binding(6)var normalTexture:texture_2d;#redgpu_endIf #redgpu_if packedORMTexture @group(2)@binding(7)var packedORMTexture:texture_2d;#redgpu_endIf #redgpu_if useKHR_materials_specular @group(2)@binding(8)var KHR_specularTextureSampler:sampler;@group(2)@binding(9)var KHR_specularTexture:texture_2d;@group(2)@binding(10)var KHR_specularColorTextureSampler:sampler;@group(2)@binding(11)var KHR_specularColorTexture:texture_2d;#redgpu_endIf @group(2)@binding(12)var KHR_clearcoatNormalTexture:texture_2d;@group(2)@binding(13)var packedKHR_clearcoatTexture_transmission:texture_2d;#redgpu_if useKHR_materials_diffuse_transmission @group(2)@binding(14)var packedKHR_diffuse_transmission:texture_2d;#redgpu_endIf #redgpu_if useKHR_materials_sheen @group(2)@binding(15)var packedKHR_sheen:texture_2d;#redgpu_endIf #redgpu_if useKHR_materials_anisotropy @group(2)@binding(16)var KHR_anisotropyTexture:texture_2d;#redgpu_endIf #redgpu_if useKHR_materials_iridescence @group(2)@binding(17)var packedKHR_iridescence:texture_2d;#redgpu_endIf struct InputData{@builtin(position)position:vec4,@location(0)vertexPosition:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,@location(3)uv1:vec2,@location(4)vertexColor_0:vec4,@location(5)vertexTangent:vec4,@location(7)currentClipPos:vec4,@location(8)prevClipPos:vec4,@location(10)localNodeScale_volumeScale:vec2,@location(11)combinedOpacity:f32,@location(12)motionVector:vec3,@location(13)shadowCoord:vec3,@location(14)@interpolate(flat)receiveShadow:f32,@location(15)@interpolate(flat)pickingId:vec4,}fn getTransmissionRefraction(u_useKHR_materials_volume:bool,thicknessParameter:f32,u_KHR_dispersion:f32,u_KHR_attenuationDistance:f32,u_KHR_attenuationColor:vec3,ior:f32,roughnessParameter:f32,albedo:vec3,projectionViewMatrix:mat4x4,input_vertexPosition:vec3,input_ndcPosition:vec3,V:vec3,N:vec3,renderPath1ResultTexture:texture_2d,renderPath1ResultTextureSampler:sampler)->vec3{var transmissionRefraction=vec3(.0);let maxMipLevel=f32(textureNumLevels(renderPath1ResultTexture)-1);let transmissionMipLevel=clamp(roughnessParameter*maxMipLevel,.0,maxMipLevel);if(u_useKHR_materials_volume){var iorR:f32=ior;var iorG:f32=ior;var iorB:f32=ior;if(u_KHR_dispersion>.0){let halfSpread:f32=(ior-1.0)*.025*u_KHR_dispersion;iorR=ior+halfSpread;iorG=ior;iorB=ior-halfSpread;}iorR=max(iorR,1.0+EPSILON);iorG=max(iorG,1.0+EPSILON);iorB=max(iorB,1.0+EPSILON);let refractedVecR:vec3=refract(-V,N,1.0/iorR);let refractedVecG:vec3=refract(-V,N,1.0/iorG);let refractedVecB:vec3=refract(-V,N,1.0/iorB);let validR=dot(refractedVecR,refractedVecR)>.0;let validG=dot(refractedVecG,refractedVecG)>.0;let validB=dot(refractedVecB,refractedVecB)>.0;let R=getReflectionVectorFromViewDirection(V,N);let finalRefractR=select(R,refractedVecR,validR);let finalRefractG=select(R,refractedVecG,validG);let finalRefractB=select(R,refractedVecB,validB);let safeThickness=clamp(thicknessParameter,.0,100.0);let worldPosR:vec3=input_vertexPosition+finalRefractR*safeThickness;let worldPosG:vec3=input_vertexPosition+finalRefractG*safeThickness;let worldPosB:vec3=input_vertexPosition+finalRefractB*safeThickness;let clipPosR:vec4=projectionViewMatrix*vec4(worldPosR,1.0);let clipPosG:vec4=projectionViewMatrix*vec4(worldPosG,1.0);let clipPosB:vec4=projectionViewMatrix*vec4(worldPosB,1.0);let wR=max(abs(clipPosR.w),EPSILON);let wG=max(abs(clipPosG.w),EPSILON);let wB=max(abs(clipPosB.w),EPSILON);let ndcR:vec2=clipPosR.xy/wR*0.5+0.5;let ndcG:vec2=clipPosG.xy/wG*0.5+0.5;let ndcB:vec2=clipPosB.xy/wB*0.5+0.5;let finalUV_R:vec2=clamp(vec2(ndcR.x,1.0-ndcR.y),vec2(.0),vec2(1.0));let finalUV_G:vec2=clamp(vec2(ndcG.x,1.0-ndcG.y),vec2(.0),vec2(1.0));let finalUV_B:vec2=clamp(vec2(ndcB.x,1.0-ndcB.y),vec2(.0),vec2(1.0));let sampledR=textureSampleLevel(renderPath1ResultTexture,renderPath1ResultTextureSampler,finalUV_R,transmissionMipLevel).r;let sampledG=textureSampleLevel(renderPath1ResultTexture,renderPath1ResultTextureSampler,finalUV_G,transmissionMipLevel).g;let sampledB=textureSampleLevel(renderPath1ResultTexture,renderPath1ResultTextureSampler,finalUV_B,transmissionMipLevel).b;transmissionRefraction.r=select(.0,sampledR,getIsFiniteScalar(sampledR));transmissionRefraction.g=select(.0,sampledG,getIsFiniteScalar(sampledG));transmissionRefraction.b=select(.0,sampledB,getIsFiniteScalar(sampledB));}else{let safeIor=max(ior,1.0+EPSILON);let refractedVec:vec3=refract(-V,N,1.0/safeIor);let valid=dot(refractedVec,refractedVec)>.0;let R=getReflectionVectorFromViewDirection(V,N);let finalRefract=select(R,refractedVec,valid);let safeThickness=clamp(thicknessParameter,.0,100.0);let worldPos:vec3=input_vertexPosition+finalRefract*safeThickness;let clipPos:vec4=projectionViewMatrix*vec4(worldPos,1.0);let w=max(abs(clipPos.w),EPSILON);let ndc:vec2=clipPos.xy/w*0.5+0.5;let finalUV:vec2=clamp(vec2(ndc.x,1.0-ndc.y),vec2(.0),vec2(1.0));let sampled=textureSampleLevel(renderPath1ResultTexture,renderPath1ResultTextureSampler,finalUV,transmissionMipLevel).rgb;transmissionRefraction=select(vec3(.0),sampled,all(getIsFiniteVec3(sampled)));}let safeAlbedo=clamp(albedo,vec3(.0),vec3(1.0));transmissionRefraction*=safeAlbedo;transmissionRefraction=select(vec3(.0),transmissionRefraction,all(getIsFiniteVec3(transmissionRefraction)));return transmissionRefraction;}@fragment fn main(inputData:InputData)->OutputFragment{var output:OutputFragment;let input_vertexNormal=(inputData.vertexNormal.xyz);let input_vertexPosition=inputData.vertexPosition.xyz;let input_vertexColor_0=inputData.vertexColor_0;let input_vertexTangent=inputData.vertexTangent;let input_ndcPosition=inputData.position.xyz/inputData.position.w;let input_uv=inputData.uv;let input_uv1=inputData.uv1;let u_camera=systemUniforms.camera;let u_cameraPosition=u_camera.cameraPosition;let preExposure=systemUniforms.preExposure;let u_usePrefilterTexture=systemUniforms.usePrefilterTexture==1u;let u_useSkyAtmosphere=systemUniforms.useSkyAtmosphere==1u;let u_opacity=uniforms.opacity;let u_cutOff=uniforms.cutOff;let u_useVertexColor=uniforms.useVertexColor==1u;let u_useVertexTangent=uniforms.useVertexTangent==1u;let u_baseColorFactor=uniforms.baseColorFactor;let u_metallicFactor=uniforms.metallicFactor;let u_roughnessFactor=uniforms.roughnessFactor;let u_normalScale=uniforms.normalScale;let u_occlusionStrength=uniforms.occlusionStrength;let u_emissiveFactor=uniforms.emissiveFactor;let u_emissiveStrength=uniforms.emissiveStrength;let u_useKHR_materials_unlit=uniforms.useKHR_materials_unlit==1u;let u_KHR_materials_ior=uniforms.KHR_materials_ior;let u_KHR_dispersion=uniforms.KHR_dispersion;let u_KHR_transmissionFactor=uniforms.KHR_transmissionFactor;let u_useKHR_materials_volume=uniforms.useKHR_materials_volume==1u;let u_KHR_thicknessFactor=uniforms.KHR_thicknessFactor;let u_KHR_attenuationColor=uniforms.KHR_attenuationColor;let u_KHR_attenuationDistance=uniforms.KHR_attenuationDistance;let u_useKHR_materials_diffuse_transmission=uniforms.useKHR_materials_diffuse_transmission==1u;let u_KHR_diffuseTransmissionFactor=uniforms.KHR_diffuseTransmissionFactor;let u_KHR_diffuseTransmissionColorFactor=uniforms.KHR_diffuseTransmissionColorFactor;let u_KHR_specularFactor=uniforms.KHR_specularFactor;let u_KHR_specularColorFactor=uniforms.KHR_specularColorFactor;let u_KHR_anisotropyStrength=uniforms.KHR_anisotropyStrength;let u_KHR_anisotropyRotation=uniforms.KHR_anisotropyRotation;let u_useKHR_anisotropyTexture=uniforms.useKHR_anisotropyTexture==1u;let u_KHR_sheenColorFactor=uniforms.KHR_sheenColorFactor;let u_KHR_sheenRoughnessFactor=uniforms.KHR_sheenRoughnessFactor;let u_useKHR_materials_iridescence=uniforms.useKHR_materials_iridescence==1u;let u_KHR_iridescenceFactor=uniforms.KHR_iridescenceFactor;let u_KHR_iridescenceIor=uniforms.KHR_iridescenceIor;let u_KHR_iridescenceThicknessMinimum=uniforms.KHR_iridescenceThicknessMinimum;let u_KHR_iridescenceThicknessMaximum=uniforms.KHR_iridescenceThicknessMaximum;let u_KHR_clearcoatFactor=uniforms.KHR_clearcoatFactor;let u_KHR_clearcoatRoughnessFactor=uniforms.KHR_clearcoatRoughnessFactor;let u_KHR_clearcoatNormalScale=uniforms.KHR_clearcoatNormalScale;let diffuseUV=getTextureTransformUV(input_uv,input_uv1,uniforms.baseColorTexture_texCoord_index,uniforms.use_baseColorTexture_KHR_texture_transform,uniforms.baseColorTexture_KHR_texture_transform_offset,uniforms.baseColorTexture_KHR_texture_transform_rotation,uniforms.baseColorTexture_KHR_texture_transform_scale);let emissiveUV=getTextureTransformUV(input_uv,input_uv1,uniforms.emissiveTexture_texCoord_index,uniforms.use_emissiveTexture_KHR_texture_transform,uniforms.emissiveTexture_KHR_texture_transform_offset,uniforms.emissiveTexture_KHR_texture_transform_rotation,uniforms.emissiveTexture_KHR_texture_transform_scale);let occlusionUV=getTextureTransformUV(input_uv,input_uv1,uniforms.occlusionTexture_texCoord_index,uniforms.use_occlusionTexture_KHR_texture_transform,uniforms.occlusionTexture_KHR_texture_transform_offset,uniforms.occlusionTexture_KHR_texture_transform_rotation,uniforms.occlusionTexture_KHR_texture_transform_scale);let metallicRoughnessUV=getTextureTransformUV(input_uv,input_uv1,uniforms.metallicRoughnessTexture_texCoord_index,uniforms.use_metallicRoughnessTexture_KHR_texture_transform,uniforms.metallicRoughnessTexture_KHR_texture_transform_offset,uniforms.metallicRoughnessTexture_KHR_texture_transform_rotation,uniforms.metallicRoughnessTexture_KHR_texture_transform_scale);let normalUV=getTextureTransformUV(input_uv,input_uv1,uniforms.normalTexture_texCoord_index,uniforms.use_normalTexture_KHR_texture_transform,uniforms.normalTexture_KHR_texture_transform_offset,uniforms.normalTexture_KHR_texture_transform_rotation,uniforms.normalTexture_KHR_texture_transform_scale);let KHR_clearcoatUV=getTextureTransformUV(input_uv,input_uv1,uniforms.KHR_clearcoatTexture_texCoord_index,uniforms.use_KHR_clearcoatTexture_KHR_texture_transform,uniforms.KHR_clearcoatTexture_KHR_texture_transform_offset,uniforms.KHR_clearcoatTexture_KHR_texture_transform_rotation,uniforms.KHR_clearcoatTexture_KHR_texture_transform_scale);#redgpu_if useKHR_materials_clearcoat let KHR_clearcoatNormalUV=getTextureTransformUV(input_uv,input_uv1,uniforms.KHR_clearcoatNormalTexture_texCoord_index,uniforms.use_KHR_clearcoatNormalTexture_KHR_texture_transform,uniforms.KHR_clearcoatNormalTexture_KHR_texture_transform_offset,uniforms.KHR_clearcoatNormalTexture_KHR_texture_transform_rotation,uniforms.KHR_clearcoatNormalTexture_KHR_texture_transform_scale);#redgpu_endIf let KHR_clearcoatRoughnessUV=getTextureTransformUV(input_uv,input_uv1,uniforms.KHR_clearcoatRoughnessTexture_texCoord_index,uniforms.use_KHR_clearcoatRoughnessTexture_KHR_texture_transform,uniforms.KHR_clearcoatRoughnessTexture_KHR_texture_transform_offset,uniforms.KHR_clearcoatRoughnessTexture_KHR_texture_transform_rotation,uniforms.KHR_clearcoatRoughnessTexture_KHR_texture_transform_scale);let KHR_sheenColorUV=getTextureTransformUV(input_uv,input_uv1,uniforms.KHR_sheenColorTexture_texCoord_index,uniforms.use_KHR_sheenColorTexture_KHR_texture_transform,uniforms.KHR_sheenColorTexture_KHR_texture_transform_offset,uniforms.KHR_sheenColorTexture_KHR_texture_transform_rotation,uniforms.KHR_sheenColorTexture_KHR_texture_transform_scale);let KHR_sheenRoughnessUV=getTextureTransformUV(input_uv,input_uv1,uniforms.KHR_sheenRoughnessTexture_texCoord_index,uniforms.use_KHR_sheenRoughnessTexture_KHR_texture_transform,uniforms.KHR_sheenRoughnessTexture_KHR_texture_transform_offset,uniforms.KHR_sheenRoughnessTexture_KHR_texture_transform_rotation,uniforms.KHR_sheenRoughnessTexture_KHR_texture_transform_scale);let KHR_specularTextureUV=getTextureTransformUV(input_uv,input_uv1,uniforms.KHR_specularTexture_texCoord_index,uniforms.use_KHR_specularTexture_KHR_texture_transform,uniforms.KHR_specularTexture_KHR_texture_transform_offset,uniforms.KHR_specularTexture_KHR_texture_transform_rotation,uniforms.KHR_specularTexture_KHR_texture_transform_scale);let KHR_specularColorTextureUV=getTextureTransformUV(input_uv,input_uv1,uniforms.KHR_specularColorTexture_texCoord_index,uniforms.use_KHR_specularColorTexture_KHR_texture_transform,uniforms.KHR_specularColorTexture_KHR_texture_transform_offset,uniforms.KHR_specularColorTexture_KHR_texture_transform_rotation,uniforms.KHR_specularColorTexture_KHR_texture_transform_scale);let KHR_iridescenceTextureUV=getTextureTransformUV(input_uv,input_uv1,uniforms.KHR_iridescenceTexture_texCoord_index,uniforms.use_KHR_iridescenceTexture_KHR_texture_transform,uniforms.KHR_iridescenceTexture_KHR_texture_transform_offset,uniforms.KHR_iridescenceTexture_KHR_texture_transform_rotation,uniforms.KHR_iridescenceTexture_KHR_texture_transform_scale);let KHR_iridescenceThicknessTextureUV=getTextureTransformUV(input_uv,input_uv1,uniforms.KHR_iridescenceThicknessTexture_texCoord_index,uniforms.use_KHR_iridescenceThicknessTexture_KHR_texture_transform,uniforms.KHR_iridescenceThicknessTexture_KHR_texture_transform_offset,uniforms.KHR_iridescenceThicknessTexture_KHR_texture_transform_rotation,uniforms.KHR_iridescenceThicknessTexture_KHR_texture_transform_scale);let KHR_transmissionUV=getTextureTransformUV(input_uv,input_uv1,uniforms.KHR_transmissionTexture_texCoord_index,uniforms.use_KHR_transmissionTexture_KHR_texture_transform,uniforms.KHR_transmissionTexture_KHR_texture_transform_offset,uniforms.KHR_transmissionTexture_KHR_texture_transform_rotation,uniforms.KHR_transmissionTexture_KHR_texture_transform_scale);let KHR_diffuseTransmissionUV=getTextureTransformUV(input_uv,input_uv1,uniforms.KHR_diffuseTransmissionTexture_texCoord_index,uniforms.use_KHR_diffuseTransmissionTexture_KHR_texture_transform,uniforms.KHR_diffuseTransmissionTexture_KHR_texture_transform_offset,uniforms.KHR_diffuseTransmissionTexture_KHR_texture_transform_rotation,uniforms.KHR_diffuseTransmissionTexture_KHR_texture_transform_scale);let KHR_diffuseTransmissionColorUV=getTextureTransformUV(input_uv,input_uv1,uniforms.KHR_diffuseTransmissionColorTexture_texCoord_index,uniforms.use_KHR_diffuseTransmissionColorTexture_KHR_texture_transform,uniforms.KHR_diffuseTransmissionColorTexture_KHR_texture_transform_offset,uniforms.KHR_diffuseTransmissionColorTexture_KHR_texture_transform_rotation,uniforms.KHR_diffuseTransmissionColorTexture_KHR_texture_transform_scale);let KHR_anisotropyUV=getTextureTransformUV(input_uv,input_uv1,uniforms.KHR_anisotropyTexture_texCoord_index,uniforms.use_KHR_anisotropyTexture_KHR_texture_transform,uniforms.KHR_anisotropyTexture_KHR_texture_transform_offset,uniforms.KHR_anisotropyTexture_KHR_texture_transform_rotation,uniforms.KHR_anisotropyTexture_KHR_texture_transform_scale);let V:vec3=getViewDirection(input_vertexPosition,u_cameraPosition);let baseNormal:vec3=normalize(input_vertexNormal.xyz);var N:vec3=baseNormal;var backFaceYn:bool=false;#redgpu_if doubleSided{if(dot(baseNormal,V)<.0){backFaceYn=true;}}#redgpu_endIf let tbnNeeded=#redgpu_if normalTexture true||#redgpu_endIf #redgpu_if useKHR_materials_clearcoat true||#redgpu_endIf #redgpu_if useKHR_materials_anisotropy true||#redgpu_endIf false;var tbn:mat3x3;if(tbnNeeded){tbn=getTBNFromVertexTangent(baseNormal,input_vertexTangent);}#redgpu_if normalTexture{var normalSamplerColor=textureSample(normalTexture,normalTextureSampler,normalUV).rgb;N=getNormalFromNormalMap(vec3(normalSamplerColor.r,1.0-normalSamplerColor.g,normalSamplerColor.b),tbn,u_normalScale);}#redgpu_endIf if(backFaceYn){N=-N;}N=normalize(N);let NdotV=max(abs(dot(N,V)),.04);let receiveShadowYn=inputData.receiveShadow !=.0;var visibility:f32=1.0;visibility=getDirectionalShadowVisibility(directionalShadowMap,directionalShadowMapSampler,systemUniforms.shadow.directionalShadowDepthTextureSize,systemUniforms.shadow.directionalShadowBias,inputData.shadowCoord);if(!receiveShadowYn){visibility=1.0;}var baseColor=u_baseColorFactor;var resultAlpha:f32=u_opacity*baseColor.a;baseColor*=select(vec4(1.0),input_vertexColor_0,u_useVertexColor);#redgpu_if baseColorTexture let diffuseSampleColor=(textureSample(baseColorTexture,baseColorTextureSampler,diffuseUV));baseColor*=diffuseSampleColor;resultAlpha*=diffuseSampleColor.a;#redgpu_endIf #redgpu_if useKHR_materials_unlit if(u_useKHR_materials_unlit){output.color=vec4(baseColor.rgb,baseColor.a);return output;}#redgpu_endIf let albedo:vec3=baseColor.rgb;var ior:f32=u_KHR_materials_ior;var occlusionParameter:f32=1.0;#redgpu_if useOcclusionTexture occlusionParameter=textureSample(packedORMTexture,packedTextureSampler,occlusionUV).r*u_occlusionStrength;#redgpu_endIf var metallicParameter:f32=u_metallicFactor;var roughnessParameter:f32=u_roughnessFactor;#redgpu_if useMetallicRoughnessTexture let metallicRoughnessSample=(textureSample(packedORMTexture,packedTextureSampler,metallicRoughnessUV));metallicParameter*=metallicRoughnessSample.b;roughnessParameter*=metallicRoughnessSample.g;#redgpu_endIf roughnessParameter=max(roughnessParameter,.04);if(abs(ior-1.0)=select(baseNormal,-baseNormal,backFaceYn);#redgpu_if useKHR_materials_clearcoat{if(clearcoatParameter>.0){#redgpu_if useKHR_clearcoatTexture let clearcoatSample=textureSample(packedKHR_clearcoatTexture_transmission,packedTextureSampler,KHR_clearcoatUV);clearcoatParameter*=clearcoatSample.r;#redgpu_endIf #redgpu_if useKHR_clearcoatRoughnessTexture let clearcoatRoughnesstSample=textureSample(packedKHR_clearcoatTexture_transmission,packedTextureSampler,KHR_clearcoatRoughnessUV);clearcoatRoughnessParameter*=clearcoatRoughnesstSample.g;#redgpu_endIf #redgpu_if useKHR_clearcoatNormalTexture{let clearcoatNormalSamplerColor=textureSample(KHR_clearcoatNormalTexture,baseColorTextureSampler,KHR_clearcoatNormalUV).rgb;let texturedNormal=getNormalFromNormalMap(clearcoatNormalSamplerColor,tbn,u_KHR_clearcoatNormalScale);clearcoatNormal=select(texturedNormal,-texturedNormal,backFaceYn);}#redgpu_endIf clearcoatNormal=normalize(clearcoatNormal);}}#redgpu_endIf var specularParameter=u_KHR_specularFactor;var specularColor=u_KHR_specularColorFactor;#redgpu_if useKHR_materials_specular #redgpu_if KHR_specularColorTexture specularColor*=textureSample(KHR_specularColorTexture,KHR_specularColorTextureSampler,KHR_specularColorTextureUV).rgb;#redgpu_endIf #redgpu_if KHR_specularTexture specularParameter*=textureSample(KHR_specularTexture,KHR_specularTextureSampler,KHR_specularTextureUV).a;#redgpu_endIf #redgpu_endIf var transmissionParameter:f32=u_KHR_transmissionFactor;var thicknessParameter:f32=u_KHR_thicknessFactor;#redgpu_if useKHR_materials_transmission #redgpu_if useKHR_transmissionTexture transmissionParameter*=textureSample(packedKHR_clearcoatTexture_transmission,packedTextureSampler,KHR_transmissionUV).b;#redgpu_endIf #redgpu_if useKHR_thicknessTexture thicknessParameter*=textureSample(packedKHR_clearcoatTexture_transmission,packedTextureSampler,KHR_transmissionUV).a;#redgpu_endIf #redgpu_endIf var diffuseTransmissionColor:vec3=u_KHR_diffuseTransmissionColorFactor;var diffuseTransmissionParameter:f32=u_KHR_diffuseTransmissionFactor;#redgpu_if useKHR_materials_diffuse_transmission #redgpu_if useKHR_diffuseTransmissionTexture diffuseTransmissionParameter*=textureSample(packedKHR_diffuse_transmission,packedTextureSampler,KHR_diffuseTransmissionUV).a;#redgpu_endIf #redgpu_if useKHR_diffuseTransmissionColorTexture diffuseTransmissionColor*=textureSample(packedKHR_diffuse_transmission,packedTextureSampler,KHR_diffuseTransmissionColorUV).rgb;#redgpu_endIf #redgpu_endIf var sheenColor=u_KHR_sheenColorFactor;var sheenRoughnessParameter=u_KHR_sheenRoughnessFactor;#redgpu_if useKHR_materials_sheen #redgpu_if useKHR_sheenColorTexture sheenColor*=textureSample(packedKHR_sheen,packedTextureSampler,KHR_sheenColorUV).rgb;#redgpu_endIf #redgpu_if useKHR_sheenRoughnessTexture sheenRoughnessParameter*=textureSample(packedKHR_sheen,packedTextureSampler,KHR_sheenRoughnessUV).a;#redgpu_endIf #redgpu_endIf var iridescenceParameter=u_KHR_iridescenceFactor;var iridescenceThickness=u_KHR_iridescenceThicknessMaximum;#redgpu_if useKHR_materials_iridescence #redgpu_if useKHR_iridescenceTexture iridescenceParameter*=textureSample(packedKHR_iridescence,packedTextureSampler,KHR_iridescenceTextureUV).r;#redgpu_endIf #redgpu_if useKHR_iridescenceThicknessTexture iridescenceThickness=mix(u_KHR_iridescenceThicknessMinimum,u_KHR_iridescenceThicknessMaximum,textureSample(packedKHR_iridescence,packedTextureSampler,KHR_iridescenceThicknessTextureUV).g);#redgpu_endIf #redgpu_endIf var anisotropy:f32=u_KHR_anisotropyStrength;var anisotropicT:vec3=vec3(1.0);var anisotropicB:vec3=vec3(1.0);#redgpu_if useKHR_materials_anisotropy{let T=tbn[0];let B=tbn[1];var anisotropicDirection:vec2=vec2(1.0,.0);if(u_useKHR_anisotropyTexture){let anisotropyTex=textureSample(KHR_anisotropyTexture,baseColorTextureSampler,KHR_anisotropyUV).rgb;anisotropicDirection=anisotropyTex.rg*2.0-1.0;anisotropy*=anisotropyTex.b;}let cosR=cos(u_KHR_anisotropyRotation);let sinR=sin(u_KHR_anisotropyRotation);anisotropicDirection=mat2x2(cosR,sinR,-sinR,cosR)*anisotropicDirection;let anisotropicTBN=getTBN(N,T*anisotropicDirection.x+B*anisotropicDirection.y);anisotropicT=anisotropicTBN[0];anisotropicB=anisotropicTBN[1];}#redgpu_endIf var transmissionRefraction=vec3(.0);#redgpu_if useKHR_materials_transmission{transmissionRefraction=getTransmissionRefraction(u_useKHR_materials_volume,thicknessParameter*inputData.localNodeScale_volumeScale[1],u_KHR_dispersion,u_KHR_attenuationDistance,u_KHR_attenuationColor,ior,roughnessParameter,albedo,systemUniforms.projection.projectionViewMatrix,input_vertexPosition,input_ndcPosition,V,N,renderPath1ResultTexture,renderPath1ResultTextureSampler);#redgpu_if useKHR_materials_volume if(u_useKHR_materials_volume){let localNodeScale=inputData.localNodeScale_volumeScale[0];let scaledThickness=thicknessParameter*localNodeScale;let safeAttenuationColor=clamp(u_KHR_attenuationColor,vec3(EPSILON),vec3(1.0));let safeAttenuationDistance=max(u_KHR_attenuationDistance,EPSILON);let attenuationCoefficient=-log(safeAttenuationColor)/safeAttenuationDistance;let pathLength=scaledThickness/max(NdotV,.04);transmissionRefraction*=exp(-attenuationCoefficient*pathLength);}#redgpu_endIf}#redgpu_endIf let F0_dielectric_base=getDielectricF0(ior);var F0_dielectric=F0_dielectric_base*specularColor;var F0_metal=albedo;#redgpu_if useKHR_materials_iridescence if(iridescenceParameter>.0){F0_dielectric=getIridescentFresnel(1.0,u_KHR_iridescenceIor,F0_dielectric,iridescenceThickness,iridescenceParameter,NdotV);F0_metal=getIridescentFresnel(1.0,u_KHR_iridescenceIor,albedo,iridescenceThickness,iridescenceParameter,NdotV);}#redgpu_endIf let F0=mix(F0_dielectric,F0_metal,metallicParameter);let totalDirectLighting=getDirectPbrLighting(input_vertexPosition,inputData.position,visibility,N,V,NdotV,roughnessParameter,metallicParameter,albedo,F0_dielectric_base,ior,specularColor,specularParameter,u_useKHR_materials_diffuse_transmission,diffuseTransmissionParameter,diffuseTransmissionColor,transmissionParameter,sheenColor,sheenRoughnessParameter,anisotropy,anisotropicT,anisotropicB,clearcoatParameter,clearcoatRoughnessParameter,clearcoatNormal,u_useKHR_materials_iridescence,iridescenceParameter,u_KHR_iridescenceIor,iridescenceThickness);let indirectLighting=getIndirectPbrLighting(N,V,NdotV,albedo,&roughnessParameter,metallicParameter,F0,F0_dielectric,F0_metal,specularParameter,occlusionParameter,transmissionParameter,transmissionRefraction,u_useKHR_materials_diffuse_transmission,diffuseTransmissionParameter,diffuseTransmissionColor,sheenColor,sheenRoughnessParameter,anisotropy,anisotropicT,anisotropicB,clearcoatParameter,clearcoatRoughnessParameter,clearcoatNormal);var emissiveColor=u_emissiveFactor*u_emissiveStrength;#redgpu_if emissiveTexture emissiveColor*=textureSample(emissiveTexture,emissiveTextureSampler,emissiveUV).rgb;#redgpu_endIf let finalColor=vec4(totalDirectLighting+indirectLighting+emissiveColor,resultAlpha);#redgpu_if useCutOff if(resultAlpha<=u_cutOff){discard;}#redgpu_endIf #redgpu_if useTint output.color=getTintBlendMode(finalColor,uniforms.tintBlendMode,uniforms.tint);#redgpu_else output.color=finalColor;#redgpu_endIf{let smoothness=1.0-roughnessParameter;let smoothnessCurved=smoothness*smoothness*(3.0-2.0*smoothness);let baseReflectionStrength=smoothnessCurved*(.04+0.96*metallicParameter*metallicParameter);output.gBufferNormal=vec4(N*0.5+0.5,baseReflectionStrength);}output.gBufferMotionVector=vec4(getMotionVector(inputData.currentClipPos,inputData.prevClipPos),.0,1.0);return output;}fn getTextureTransformUV(input_uv:vec2,input_uv1:vec2,texCoord_index:u32,use_transform:u32,transform_offset:vec2,transform_rotation:f32,transform_scale:vec2)->vec2{var result_uv=select(input_uv,input_uv1,texCoord_index==1u);if(use_transform==1u){let translation=mat3x3(1.0,.0,.0,.0,1.0,.0,transform_offset.x,transform_offset.y,1.0);let cos_rot=cos(transform_rotation);let sin_rot=sin(transform_rotation);let rotation_matrix=mat3x3(cos_rot,-sin_rot,.0,sin_rot,cos_rot,.0,.0,.0,1.0);let scale_matrix=mat3x3(transform_scale.x,.0,.0,.0,transform_scale.y,.0,.0,.0,1.0);let result_matrix=translation*rotation_matrix*scale_matrix;result_uv=(result_matrix*vec3(result_uv,1.0)).xy;}return result_uv;}fn getDielectricF0(ior:f32)->vec3{let f0_factor=(ior-1.0)/(ior+1.0);return vec3(f0_factor*f0_factor);}fn getSpecularNDF(NdotH:f32,roughness:f32)->f32{let alpha=roughness*roughness;let alpha2=alpha*alpha;let NdotH2=NdotH*NdotH;let nom=alpha2;let denom=(NdotH2*(alpha2-1.0)+1.0);let denomSquared=denom*denom;return nom/max(EPSILON,denomSquared*PI);}fn getSpecularVisibility(NdotV:f32,NdotL:f32,roughness:f32)->f32{let alpha=roughness*roughness;let alpha2=alpha*alpha;let safeNdotV=max(NdotV,1e-4);let safeNdotL=max(NdotL,1e-4);let GGXV=safeNdotL*sqrt(safeNdotV*safeNdotV*(1.0-alpha2)+alpha2);let GGXL=safeNdotV*sqrt(safeNdotL*safeNdotL*(1.0-alpha2)+alpha2);return 0.5/max(GGXV+GGXL,EPSILON);}fn getFresnel(cosTheta:f32,F0:vec3)->vec3{return F0+(vec3(1.0)-F0)*pow(clamp(1.0-cosTheta,.0,1.0),5.0);}fn getIndirectFresnel(cosTheta:f32,F0:vec3,roughness:f32,fresnelTerm:f32)->vec3{let F90=max(vec3(1.0-roughness*0.8),F0);return F0+(F90-F0)*fresnelTerm;}fn getDirectSpecularBRDF(F:vec3,roughness:f32,NdotH:f32,NdotV:f32,NdotL:f32)->vec3{let D=getSpecularNDF(NdotH,roughness);let V=getSpecularVisibility(NdotV,NdotL,roughness);return D*V*F;}fn getDirectDiffuseBRDF(NdotL:f32,NdotV:f32,LdotH:f32,roughness:f32,albedo:vec3)->vec3{if(NdotL<=.0){return vec3(.0);}let energyBias=mix(.0,0.5,roughness);let energyFactor=mix(1.0,1.0/1.51,roughness);let fd90=energyBias+2.0*LdotH*LdotH*roughness;let f0=1.0;let lightScatter=f0+(fd90-f0)*pow(1.0-NdotL,5.0);let viewScatter=f0+(fd90-f0)*pow(1.0-NdotV,5.0);return albedo*NdotL*lightScatter*viewScatter*energyFactor*INV_PI;}fn getDirectSpecularBTDF(NdotV:f32,NdotL:f32,NdotH:f32,VdotH:f32,LdotH:f32,roughness:f32,F:vec3,ior:f32)->vec3{let eta:f32=1.0/ior;let D_rough:f32=getSpecularNDF(NdotH,roughness);let t:f32=clamp((ior-1.0)*100.0,.0,1.0);let D:f32=mix(1.0,D_rough,t);let G:f32=min(1.0,min((2.0*NdotH*NdotV)/VdotH,(2.0*NdotH*abs(NdotL))/VdotH));let denom=(eta*VdotH+LdotH)*(eta*VdotH+LdotH);let btdf:vec3=(vec3(1.0)-F)*abs(VdotH*LdotH)*(eta*eta)*D*G/(max(NdotV,EPSILON)*max(abs(NdotL),EPSILON)*max(denom,EPSILON));return btdf;}fn getDirectDiffuseBTDF(N:vec3,L:vec3,albedo:vec3)->vec3{let cosTheta=max(-dot(N,L),.0);return albedo*cosTheta*INV_PI;}struct SheenIBLResult{sheenIBLContribution:vec3,sheenAlbedoScaling:f32}fn getSheenAlbedoScaling(maxSheenColor:f32,sheenE:f32)->f32{return 1.0-maxSheenColor*sheenE;}fn getIndirectSheenDFG(NdotV:f32,roughness:f32)->f32{if(roughness<.01){return .0;}let r=clamp(roughness,.01,1.0);let grazingFactor=1.0-NdotV;let roughnessExp=1.0/max(r,EPSILON);let distribution=pow(grazingFactor,roughnessExp);let intensity=pow(roughnessExp,0.5);return distribution*intensity*0.5;}fn getSheenCharlieE(NdotV:f32,roughness:f32)->f32{if(roughness<.01){return .0;}let r=clamp(roughness,.01,1.0);let grazingFactor=1.0-NdotV;let roughnessExp=1.0/max(r,EPSILON);return pow(grazingFactor,roughnessExp)*pow(r,0.5);}fn getIndirectSheenBRDF(N:vec3,V:vec3,R:vec3,sheenColor:vec3,maxSheenColor:f32,sheenRoughness:f32,iblMipmapCount:f32,irradianceTexture:texture_cube,textureSampler:sampler)->SheenIBLResult{let NdotV=clamp(dot(N,V),EPSILON,1.0);let mipLevel=sheenRoughness*iblMipmapCount;let sheenRadiance=textureSampleLevel(irradianceTexture,textureSampler,R,mipLevel).rgb*systemUniforms.preExposure*systemUniforms.iblIntensity;let r=clamp(sheenRoughness,.01,1.0);let grazingFactor=1.0-NdotV;let roughnessExp=1.0/r;let sharedPow=pow(grazingFactor,roughnessExp);let sheenDFG=sharedPow*pow(roughnessExp,0.5)*0.5;let E=sharedPow*pow(r,0.5);let contribution=sheenRadiance*sheenColor*sheenDFG;let albedoScaling=getSheenAlbedoScaling(maxSheenColor,E);return SheenIBLResult(contribution,albedoScaling);}fn getDirectSheenBRDF(NdotL:f32,NdotV:f32,NdotH:f32,sheenColor:vec3,sheenRoughness:f32)->vec3{let invAlpha=1.0/max(sheenRoughness,.000001);let cos2h=NdotH*NdotH;let sin2h=max(1.0-cos2h,.0078125);let sheenDistribution=(2.0+invAlpha)*pow(sin2h,invAlpha*0.5)/(2.0*PI);let sheenVisibility=1.0/(4.0*(NdotL+NdotV-NdotL*NdotV));return sheenColor*sheenDistribution*sheenVisibility;}fn getDirectAnisotropicVisibility(NdotL:f32,NdotV:f32,BdotV:f32,TdotV:f32,TdotL:f32,BdotL:f32,at:f32,ab:f32)->f32{let GGXV=NdotL*length(vec3(at*TdotV,ab*BdotV,NdotV));let GGXL=NdotV*length(vec3(at*TdotL,ab*BdotL,NdotL));let v=0.5/max(GGXV+GGXL,EPSILON);return v;}fn getDirectAnisotropicNDF(NdotH:f32,TdotH:f32,BdotH:f32,at:f32,ab:f32)->f32{let a2:f32=at*ab;let f:vec3=vec3(ab*TdotH,at*BdotH,a2*NdotH);let denominator:f32=dot(f,f);let w2:f32=a2/max(denominator,EPSILON);return a2*w2*w2*INV_PI;}fn getDirectAnisotropicBRDF(F:vec3,alphaRoughness:f32,VdotH:f32,NdotL:f32,NdotV:f32,NdotH:f32,BdotV:f32,TdotV:f32,TdotL:f32,BdotL:f32,TdotH:f32,BdotH:f32,anisotropy:f32)->vec3{var at=mix(alphaRoughness,1.0,anisotropy*anisotropy);var ab=alphaRoughness;var V:f32=getDirectAnisotropicVisibility(NdotL,NdotV,BdotV,TdotV,TdotL,BdotL,at,ab);var D:f32=getDirectAnisotropicNDF(NdotH,TdotH,BdotH,at,ab);return F*(V*D);}fn getIndirectAnisotropicBRDF(V:vec3,N:vec3,roughness:f32,anisotropy:f32,anisotropicT:vec3,anisotropicB:vec3)->vec4{let grainDir=select(anisotropicT,anisotropicB,anisotropy>=.0);let stretch=abs(anisotropy)*(1.0-roughness);var T_perp_V=cross(grainDir,V);if(dot(T_perp_V,T_perp_V)(R,max(effectiveRoughness,.04));}fn getDirectClearcoatBRDF(L:vec3,V:vec3,H:vec3,clearcoatNormal:vec3,clearcoatRoughness:f32,LdotH:f32)->vec3{let clearcoatNdotL=max(dot(clearcoatNormal,L),.0);let clearcoatNdotV=max(dot(clearcoatNormal,V),.04);let clearcoatNdotH=max(dot(clearcoatNormal,H),.0);let clearcoatF=getFresnel(LdotH,vec3(.04));let CLEARCOAT_BRDF=getDirectSpecularBRDF(clearcoatF,clearcoatRoughness,clearcoatNdotH,clearcoatNdotV,clearcoatNdotL);return CLEARCOAT_BRDF*clearcoatNdotL;}fn getIndirectClearcoatBRDF(V:vec3,clearcoatNormal:vec3,clearcoatRoughness:f32,iblMipmapCount:f32,ibl_prefilterTexture:texture_cube,prefilterTextureSampler:sampler,ibl_brdfLUTTexture:texture_2d,useSkyAtmosphere:bool,sunIntensity:f32,skyAtmosphere_prefilteredTexture:texture_cube,atmosphereSampler:sampler,cameraHeight:f32,atmosphereHeight:f32,transmittanceTexture:texture_2d,mainR:vec3,isMainNormal:bool)->vec4{let clearcoatR=select(getReflectionVectorFromViewDirection(V,clearcoatNormal),mainR,isMainNormal);let clearcoatNdotV=max(abs(dot(clearcoatNormal,V)),.04);let clearcoatMipLevel=clearcoatRoughness*iblMipmapCount;var clearcoatRadiance=textureSampleLevel(ibl_prefilterTexture,prefilterTextureSampler,clearcoatR,clearcoatMipLevel).rgb*systemUniforms.preExposure*systemUniforms.iblIntensity;if(useSkyAtmosphere){let u_atmo=systemUniforms.skyAtmosphere;let skyIntensity=u_atmo.sunIntensity;let ccTrans=getTransmittance(transmittanceTexture,atmosphereSampler,cameraHeight,clearcoatR.y,atmosphereHeight);let atmoMipCount=f32(textureNumLevels(skyAtmosphere_prefilteredTexture)-1);let atmoMipLevel=clearcoatRoughness*atmoMipCount;let ccSkyScat=textureSampleLevel(skyAtmosphere_prefilteredTexture,atmosphereSampler,clearcoatR,atmoMipLevel).rgb*skyIntensity*systemUniforms.preExposure;clearcoatRadiance=(clearcoatRadiance*ccTrans)+ccSkyScat;}let clearcoatEnvBRDF=textureSampleLevel(ibl_brdfLUTTexture,prefilterTextureSampler,clamp(vec2(clearcoatNdotV,clearcoatRoughness),vec2(.005),vec2(0.995)),.0).rg;let coatF=getIndirectFresnel(clearcoatNdotV,vec3(.04),clearcoatRoughness,pow(1.0-clearcoatNdotV,5.0-2.0*clearcoatRoughness)).x;let clearcoatIBL_Weight=(.04*clearcoatEnvBRDF.x+clearcoatEnvBRDF.y);return vec4(clearcoatRadiance*clearcoatIBL_Weight,coatF);}fn getIridescentFresnel(outsideIOR:f32,iridescenceIOR:f32,baseF0:vec3,iridescenceThickness:f32,iridescenceFactor:f32,cosTheta1:f32)->vec3{if(iridescenceThickness<=.0||iridescenceFactor<=.0){return baseF0;}let cosTheta1Abs=abs(cosTheta1);let safeIridescenceIOR=max(iridescenceIOR,1.01);let sinTheta1=sqrt(max(.0,1.0-cosTheta1Abs*cosTheta1Abs));let sinTheta2=(outsideIOR/safeIridescenceIOR)*sinTheta1;if(sinTheta2>=1.0){return baseF0+iridescenceFactor*(1.0-baseF0);}let cosTheta2=sqrt(1.0-sinTheta2*sinTheta2);let opticalThickness=2.0*iridescenceThickness*safeIridescenceIOR*cosTheta2;let phase=(PI2*opticalThickness)*vec3(1.0/650.0,1.0/510.0,1.0/475.0);let cosPhase=cos(phase);let sinPhase=sin(phase);let outsideCos1=outsideIOR*cosTheta1Abs;let iridescenceCos2=safeIridescenceIOR*cosTheta2;let iridescenceCos1=safeIridescenceIOR*cosTheta1Abs;let outsideCos2=outsideIOR*cosTheta2;let r12_s=(outsideCos1-iridescenceCos2)/max(outsideCos1+iridescenceCos2,EPSILON);let r12_p=(iridescenceCos1-outsideCos2)/max(iridescenceCos1+outsideCos2,EPSILON);let sqrtF0=sqrt(clamp(baseF0,vec3(.01),vec3(0.99)));let safeN3=(1.0+sqrtF0)/max(1.0-sqrtF0,vec3(EPSILON));let r23_s=(iridescenceCos2-safeN3*cosTheta1Abs)/max(iridescenceCos2+safeN3*cosTheta1Abs,vec3(EPSILON));let r23_p=(safeN3*cosTheta2-iridescenceCos1)/max(safeN3*cosTheta2+iridescenceCos1,vec3(EPSILON));let r12_s_vec=vec3(r12_s);let r12_p_vec=vec3(r12_p);let denSReal=1.0+r12_s_vec*r23_s*cosPhase;let denSImag=-r12_s_vec*r23_s*sinPhase;let denSSquared=denSReal*denSReal+denSImag*denSImag;let numSReal=r12_s_vec+r23_s*cosPhase;let numSImag=-r23_s*sinPhase;let Rs=(numSReal*numSReal+numSImag*numSImag)/max(denSSquared,vec3(EPSILON));let denPReal=1.0+r12_p_vec*r23_p*cosPhase;let denPImag=-r12_p_vec*r23_p*sinPhase;let denPSquared=denPReal*denPReal+denPImag*denPImag;let numPReal=r12_p_vec+r23_p*cosPhase;let numPImag=-r23_p*sinPhase;let Rp=(numPReal*numPReal+numPImag*numPImag)/max(denPSquared,vec3(EPSILON));let reflectance=clamp(0.5*(Rs+Rp),vec3(.0),vec3(1.0));return mix(baseF0,reflectance,iridescenceFactor);}fn getDirectPbrLighting(input_vertexPosition:vec3,inputData_position:vec4,visibility:f32,N:vec3,V:vec3,NdotV:f32,roughnessParameter:f32,metallicParameter:f32,albedo:vec3,F0_dielectric_base:vec3,ior:f32,specularColor:vec3,specularParameter:f32,u_useKHR_materials_diffuse_transmission:bool,diffuseTransmissionParameter:f32,diffuseTransmissionColor:vec3,transmissionParameter:f32,sheenColor:vec3,sheenRoughnessParameter:f32,anisotropy:f32,anisotropicT:vec3,anisotropicB:vec3,clearcoatParameter:f32,clearcoatRoughnessParameter:f32,clearcoatNormal:vec3,useIridescence:bool,iridescenceFactor:f32,iridescenceIor:f32,iridescenceThickness:f32)->vec3{var totalDirectLighting=vec3(.0);let u_directionalLightCount=systemUniforms.directionalLightCount;let u_directionalLights=systemUniforms.directionalLights;for(var i=0u;iu_clusterLightRadius){continue;}let L=normalize(lightDir);let attenuation=getLightDistanceAttenuation(lightDistance,u_clusterLightRadius);var finalAttenuation=attenuation;if(u_isSpotLight>.0){let u_clusterLightDirection=normalize(vec3(targetLight.directionX,targetLight.directionY,targetLight.directionZ));let lightToVertex=normalize(-L);finalAttenuation*=getLightAngleAttenuation(lightToVertex,u_clusterLightDirection,targetLight.innerCutoff,targetLight.outerCutoff);}var finalLightColor=targetLight.color*targetLight.intensity*finalAttenuation*systemUniforms.preExposure;totalDirectLighting+=getDirectPbrLight(finalLightColor,N,V,L,NdotV,roughnessParameter,metallicParameter,albedo,F0_dielectric_base,ior,specularColor,specularParameter,u_useKHR_materials_diffuse_transmission,diffuseTransmissionParameter,diffuseTransmissionColor,transmissionParameter,sheenColor,sheenRoughnessParameter,anisotropy,anisotropicT,anisotropicB,clearcoatParameter,clearcoatRoughnessParameter,clearcoatNormal,useIridescence,iridescenceFactor,iridescenceIor,iridescenceThickness);}}return totalDirectLighting;}fn getIndirectPbrLighting(N:vec3,V:vec3,NdotV:f32,albedo:vec3,roughnessParameter:ptr,metallicParameter:f32,F0:vec3,F0_dielectric:vec3,F0_metal:vec3,specularParameter:f32,occlusionParameter:f32,transmissionParameter:f32,transmissionRefraction:vec3,u_useKHR_materials_diffuse_transmission:bool,diffuseTransmissionParameter:f32,diffuseTransmissionColor:vec3,sheenColor:vec3,sheenRoughnessParameter:f32,anisotropy:f32,anisotropicT:vec3,anisotropicB:vec3,clearcoatParameter:f32,clearcoatRoughnessParameter:f32,clearcoatNormal:vec3)->vec3{let u_usePrefilterTexture=systemUniforms.usePrefilterTexture==1u;let u_useSkyAtmosphere=systemUniforms.useSkyAtmosphere==1u;let preExposure=systemUniforms.preExposure;if(u_usePrefilterTexture||u_useSkyAtmosphere){var R=getReflectionVectorFromViewDirection(V,N);let NdotV_IBL=max(abs(dot(N,V)),.04);var iblRoughness=*roughnessParameter;#redgpu_if useKHR_materials_anisotropy if(anisotropy>.0){let anisotropicResult=getIndirectAnisotropicBRDF(V,N,iblRoughness,anisotropy,anisotropicT,anisotropicB);R=anisotropicResult.xyz;iblRoughness=anisotropicResult.w;}#redgpu_endIf var reflectedColor=vec3(.0);var iblDiffuseColor=vec3(.0);var iblMipmapCount:f32=.0;if(u_usePrefilterTexture){iblMipmapCount=f32(textureNumLevels(ibl_prefilterTexture)-1);var mipLevel=iblRoughness*iblMipmapCount;reflectedColor=textureSampleLevel(ibl_prefilterTexture,prefilterTextureSampler,R,mipLevel).rgb*preExposure*systemUniforms.iblIntensity;iblDiffuseColor=textureSampleLevel(ibl_irradianceTexture,prefilterTextureSampler,N,0).rgb*preExposure*systemUniforms.iblIntensity;}if(u_useSkyAtmosphere){let u_atmo=systemUniforms.skyAtmosphere;let camH=u_atmo.cameraHeight;let atmH=u_atmo.atmosphereHeight;let skyIntensity=u_atmo.sunIntensity;let specTrans=getTransmittance(transmittanceTexture,atmosphereSampler,camH,R.y,atmH);let atmoMipCount=f32(textureNumLevels(skyAtmosphere_prefilteredTexture)-1);let atmoMipLevel=iblRoughness*atmoMipCount;let specSkyScat=textureSampleLevel(skyAtmosphere_prefilteredTexture,atmosphereSampler,R,atmoMipLevel).rgb*skyIntensity*preExposure;reflectedColor=(reflectedColor*specTrans)+specSkyScat;let diffTrans=getTransmittance(transmittanceTexture,atmosphereSampler,camH,N.y,atmH);let skyIrradiance=textureSampleLevel(atmosphereIrradianceLUT,atmosphereSampler,N,.0).rgb*skyIntensity*preExposure;iblDiffuseColor=(iblDiffuseColor*diffTrans)+skyIrradiance;}let envBRDF=textureSampleLevel(ibl_brdfLUTTexture,prefilterTextureSampler,clamp(vec2(NdotV_IBL,*roughnessParameter),vec2(.005),vec2(0.995)),.0).rg;let energyCompensation=1.0+F0*(1.0/max(envBRDF.x+envBRDF.y,1e-4)-1.0);reflectedColor*=energyCompensation;let fresnelPower=5.0-2.0*(*roughnessParameter);let fresnelTerm=pow(saturate(1.0-NdotV_IBL),fresnelPower);let FR_dielectric=getIndirectFresnel(NdotV_IBL,F0_dielectric,*roughnessParameter,fresnelTerm);let FR_metal=getIndirectFresnel(NdotV_IBL,F0_metal,*roughnessParameter,fresnelTerm);let horizonOcclusion=saturate(1.0+1.1*dot(R,N));reflectedColor*=horizonOcclusion*horizonOcclusion;let F_IBL_dielectric=FR_dielectric*envBRDF.x+envBRDF.y;let F_IBL_metal=FR_metal*envBRDF.x+envBRDF.y;let F_IBL_dielectric_weight=F_IBL_dielectric*specularParameter;let specularOcclusion=saturate(pow(NdotV_IBL+occlusionParameter,exp2(-16.0*(*roughnessParameter)-1.0))-1.0+occlusionParameter);let specularAlbedo_IBL=saturate(F0_dielectric*envBRDF.x+envBRDF.y);let diffuseWeight_IBL=(vec3(1.0)-specularAlbedo_IBL*specularParameter);var envIBL_DIFFUSE:vec3=albedo*iblDiffuseColor*diffuseWeight_IBL*INV_PI*occlusionParameter;#redgpu_if useKHR_materials_diffuse_transmission{var backScatteringColor=vec3(.0);if(u_usePrefilterTexture){let mipLevel=iblRoughness*iblMipmapCount;backScatteringColor=textureSampleLevel(ibl_prefilterTexture,prefilterTextureSampler,-N,mipLevel).rgb*preExposure*systemUniforms.iblIntensity;}if(u_useSkyAtmosphere){let u_atmo=systemUniforms.skyAtmosphere;let skyIntensity=u_atmo.sunIntensity;let backTrans=getTransmittance(transmittanceTexture,atmosphereSampler,u_atmo.cameraHeight,-N.y,u_atmo.atmosphereHeight);let backSkyScat=textureSampleLevel(skyAtmosphere_prefilteredTexture,prefilterTextureSampler,-N,.0).rgb*skyIntensity*preExposure;backScatteringColor=(backScatteringColor*backTrans)+backSkyScat;}let transmittedIBL=backScatteringColor*diffuseTransmissionColor*(vec3(1.0)-F_IBL_dielectric_weight);envIBL_DIFFUSE=mix(envIBL_DIFFUSE,transmittedIBL,diffuseTransmissionParameter);}#redgpu_endIf var envIBL_SPECULAR_BTDF=vec3(.0);#redgpu_if useKHR_materials_transmission if(transmissionParameter>.0){envIBL_SPECULAR_BTDF=transmissionRefraction*(vec3(1.0)-F_IBL_dielectric_weight)*specularOcclusion;}#redgpu_endIf var sheenIBLContribution=vec3(.0);var sheenAlbedoScaling:f32=1.0;#redgpu_if useKHR_materials_sheen{let maxSheenColor=max(sheenColor.x,max(sheenColor.y,sheenColor.z));let sheenResult=getIndirectSheenBRDF(N,V,R,sheenColor,maxSheenColor,sheenRoughnessParameter,iblMipmapCount,ibl_prefilterTexture,prefilterTextureSampler);sheenIBLContribution=sheenResult.sheenIBLContribution;sheenAlbedoScaling=sheenResult.sheenAlbedoScaling;}#redgpu_endIf let ibl_specular_dielectric=reflectedColor*F_IBL_dielectric_weight*specularOcclusion;let ibl_diffuse_dielectric=mix(envIBL_DIFFUSE,envIBL_SPECULAR_BTDF,transmissionParameter);let dielectricPart_IBL=ibl_specular_dielectric+ibl_diffuse_dielectric;let metallicPart_IBL=reflectedColor*F_IBL_metal*specularOcclusion;let baseIndirect=mix(dielectricPart_IBL,metallicPart_IBL,metallicParameter);var indirectLighting=(baseIndirect*sheenAlbedoScaling+sheenIBLContribution);#redgpu_if useKHR_materials_clearcoat if(clearcoatParameter>.0){let u_atmo=systemUniforms.skyAtmosphere;let clearcoatResult=getIndirectClearcoatBRDF(V,clearcoatNormal,clearcoatRoughnessParameter,iblMipmapCount,ibl_prefilterTexture,prefilterTextureSampler,ibl_brdfLUTTexture,u_useSkyAtmosphere,u_atmo.sunIntensity,skyAtmosphere_prefilteredTexture,atmosphereSampler,u_atmo.cameraHeight,u_atmo.atmosphereHeight,transmittanceTexture,R,all(clearcoatNormal==N));let clearcoatSpecularIBL=clearcoatResult.rgb*clearcoatParameter;let coatF=clearcoatResult.a*clearcoatParameter;indirectLighting=clearcoatSpecularIBL+(vec3(1.0)-coatF)*indirectLighting;}#redgpu_endIf return indirectLighting;}else{let ambientContribution=albedo*systemUniforms.ambientLight.color*systemUniforms.ambientLight.intensity*occlusionParameter*preExposure*INV_PI;var indirectLighting=ambientContribution;#redgpu_if useKHR_materials_transmission if(transmissionParameter>.0){let transmissionFresnel=getFresnel(NdotV,F0);let transmissionWeight=transmissionParameter*(vec3(1.0)-transmissionFresnel);indirectLighting=mix(ambientContribution,transmissionRefraction,transmissionWeight);}#redgpu_endIf return indirectLighting;}}fn getDirectPbrLight(lightColor:vec3,N:vec3,V:vec3,L:vec3,VdotN:f32,roughnessParameter:f32,metallicParameter:f32,albedo:vec3,F0_base:vec3,ior:f32,specularColor:vec3,specularParameter:f32,u_useKHR_materials_diffuse_transmission:bool,diffuseTransmissionParameter:f32,diffuseTransmissionColor:vec3,transmissionParameter:f32,sheenColor:vec3,sheenRoughnessParameter:f32,anisotropy:f32,anisotropicT:vec3,anisotropicB:vec3,clearcoatParameter:f32,clearcoatRoughnessParameter:f32,clearcoatNormal:vec3,useIridescence:bool,iridescenceFactor:f32,iridescenceIor:f32,iridescenceThickness:f32)->vec3{let dLight=lightColor;let NdotL_origin=dot(N,L);let NdotL=max(NdotL_origin,.0);let H=normalize(L+V);let NdotH=max(dot(N,H),.0);let LdotH=max(dot(L,H),.0);let VdotH=max(dot(V,H),.0);var F:vec3;let dielectric_f0=F0_base*specularColor;let metal_f0=albedo;let combined_f0=mix(dielectric_f0,metal_f0,metallicParameter);if(useIridescence&&iridescenceFactor>.0){let F_irid_dielectric=getIridescentFresnel(1.0,iridescenceIor,dielectric_f0,iridescenceThickness,iridescenceFactor,VdotH);let F_irid_metal=getIridescentFresnel(1.0,iridescenceIor,metal_f0,iridescenceThickness,iridescenceFactor,VdotH);F=mix(F_irid_dielectric,F_irid_metal,metallicParameter);}else{F=getFresnel(VdotH,combined_f0);}if(abs(ior-1.0)(.0);}var SPEC_BRDF=getDirectSpecularBRDF(F,roughnessParameter,NdotH,VdotN,NdotL);if(anisotropy>.0){#redgpu_if useKHR_materials_anisotropy var TdotL=dot(anisotropicT,L);var TdotV=dot(anisotropicT,V);var BdotL=dot(anisotropicB,L);var TdotH=dot(anisotropicT,H);var BdotH=dot(anisotropicB,H);var BdotV=dot(anisotropicB,V);SPEC_BRDF=getDirectAnisotropicBRDF(F,roughnessParameter*roughnessParameter,VdotH,NdotL,VdotN,NdotH,BdotV,TdotV,TdotL,BdotL,TdotH,BdotH,anisotropy);#redgpu_endIf}if(abs(ior-1.0)(.0);}let diffuse_reflection=getDirectDiffuseBRDF(NdotL,VdotN,LdotH,roughnessParameter,albedo);var diffuse_transmission=vec3(.0);#redgpu_if useKHR_materials_diffuse_transmission if(u_useKHR_materials_diffuse_transmission){diffuse_transmission=getDirectDiffuseBTDF(N,L,diffuseTransmissionColor);}#redgpu_endIf var specular_transmission=vec3(.0);#redgpu_if useKHR_materials_transmission if(transmissionParameter>.0){specular_transmission=getDirectSpecularBTDF(VdotN,NdotL_origin,NdotH,VdotH,LdotH,roughnessParameter,F,ior)*max(-NdotL_origin,.0);if(abs(ior-1.0)(.0);}}#redgpu_endIf let specular_weight=F*specularParameter;let total_diffuse=mix(diffuse_reflection,diffuse_transmission,diffuseTransmissionParameter);let dielectricPart=(SPEC_BRDF*specularParameter*NdotL)+mix((vec3(1.0)-specular_weight)*total_diffuse,specular_transmission,transmissionParameter);let metallicPart=SPEC_BRDF*NdotL;var result=mix(dielectricPart,metallicPart,metallicParameter);#redgpu_if useKHR_materials_sheen{let maxSheenColor=max(sheenColor.x,max(sheenColor.y,sheenColor.z));if(sheenRoughnessParameter>.0&&maxSheenColor>.001){let sheen_brdf=getDirectSheenBRDF(NdotL,VdotN,NdotH,sheenColor,sheenRoughnessParameter);let sheen_albedo_scaling=getSheenAlbedoScaling(maxSheenColor,getSheenCharlieE(VdotN,sheenRoughnessParameter));result=result*sheen_albedo_scaling+(sheen_brdf*NdotL);}}#redgpu_endIf #redgpu_if useKHR_materials_clearcoat if(clearcoatParameter>.0){let CLEARCOAT_BRDF=getDirectClearcoatBRDF(L,V,H,clearcoatNormal,clearcoatRoughnessParameter,LdotH);let coatF=getFresnel(max(dot(clearcoatNormal,V),.04),vec3(.04)).x*clearcoatParameter;result=CLEARCOAT_BRDF+(vec3(1.0)-coatF)*result;}#redgpu_endIf return result*dLight;}"));class PBRMaterial extends AUVTransformBaseMaterial{#Ia;#Aa;#La;#Ua;#ka;constructor(i){super(i,"PBR_MATERIAL",ki,2),this.initGPURenderInfos(),this.__packingList=[()=>{this.setupPackORMTexture(),this.setupPackedKHR_clearcoatTexture_transmission(),this.setupPackedKHR_diffuse_transmission(),this.setupPackedKHR_sheen(),this.setupPackedKHR_iridescence()}]}get packedKHR_clearcoatTexture_transmission(){return this.#ka}get packedKHR_iridescence(){return this.#Ua}get packedORMTexture(){return this.#Ia}get packedKHR_sheen(){return this.#La}get packedKHR_diffuse_transmission(){return this.#Aa}async setupPackORMTexture(){if(!this.occlusionTexture&&!this.metallicRoughnessTexture)return;this.#Ia||(this.#Ia=new PackedTexture(this.redGPUContext));const i=Math.max(this.occlusionTexture?.gpuTexture?.width||1,this.metallicRoughnessTexture?.gpuTexture?.width||1),g=Math.max(this.occlusionTexture?.gpuTexture?.height||1,this.metallicRoughnessTexture?.gpuTexture?.height||1);await this.#Ia.packing({r:this.occlusionTexture?.gpuTexture,g:this.metallicRoughnessTexture?.gpuTexture,b:this.metallicRoughnessTexture?.gpuTexture},i,g,"packedORMTexture")}async setupPackedKHR_clearcoatTexture_transmission(){this.#ka||(this.#ka=new PackedTexture(this.redGPUContext));const i=Math.max(this.KHR_clearcoatTexture?.gpuTexture?.width||1,this.KHR_clearcoatRoughnessTexture?.gpuTexture?.width||1),g=Math.max(this.KHR_clearcoatTexture?.gpuTexture?.height||1,this.KHR_clearcoatRoughnessTexture?.gpuTexture?.height||1),x=Math.max(this.KHR_transmissionTexture?.gpuTexture?.width||1,this.KHR_thicknessTexture?.gpuTexture?.width||1),v=Math.max(this.KHR_transmissionTexture?.gpuTexture?.height||1,this.KHR_thicknessTexture?.gpuTexture?.height||1),_=Math.max(i,x),y=Math.max(g,v);await this.#ka.packing({r:this.KHR_clearcoatTexture?.gpuTexture,g:this.KHR_clearcoatRoughnessTexture?.gpuTexture,b:this.KHR_transmissionTexture?.gpuTexture,a:this.KHR_thicknessTexture?.gpuTexture},_,y,"packedKHR_clearcoatTexture_transmission",{b:"r",a:"g"})}async setupPackedKHR_diffuse_transmission(){if(!this.KHR_diffuseTransmissionColorTexture&&!this.KHR_diffuseTransmissionTexture)return;this.#Aa||(this.#Aa=new PackedTexture(this.redGPUContext));const i=Math.max(this.KHR_diffuseTransmissionColorTexture?.gpuTexture?.width||1,this.KHR_diffuseTransmissionTexture?.gpuTexture?.width||1),g=Math.max(this.KHR_diffuseTransmissionColorTexture?.gpuTexture?.height||1,this.KHR_diffuseTransmissionTexture?.gpuTexture?.height||1);await this.#Aa.packing({r:this.KHR_diffuseTransmissionColorTexture?.gpuTexture,g:this.KHR_diffuseTransmissionColorTexture?.gpuTexture,b:this.KHR_diffuseTransmissionColorTexture?.gpuTexture,a:this.KHR_diffuseTransmissionTexture?.gpuTexture},i,g,"packedKHR_diffuse_transmission")}async setupPackedKHR_sheen(){if(!this.KHR_sheenColorTexture&&!this.KHR_sheenRoughnessTexture)return;this.#La||(this.#La=new PackedTexture(this.redGPUContext));const i=Math.max(this.KHR_sheenColorTexture?.gpuTexture?.width||1,this.KHR_sheenRoughnessTexture?.gpuTexture?.width||1),g=Math.max(this.KHR_sheenColorTexture?.gpuTexture?.height||1,this.KHR_sheenRoughnessTexture?.gpuTexture?.height||1);await this.#La.packing({r:this.KHR_sheenColorTexture?.gpuTexture,g:this.KHR_sheenColorTexture?.gpuTexture,b:this.KHR_sheenColorTexture?.gpuTexture,a:this.KHR_sheenRoughnessTexture?.gpuTexture},i,g,"packedKHR_sheen")}async setupPackedKHR_iridescence(){if(!this.KHR_iridescenceTexture&&!this.KHR_iridescenceThicknessTexture)return;this.#Ua||(this.#Ua=new PackedTexture(this.redGPUContext));const i=Math.max(this.KHR_iridescenceTexture?.gpuTexture?.width||1,this.KHR_iridescenceThicknessTexture?.gpuTexture?.width||1),g=Math.max(this.KHR_iridescenceTexture?.gpuTexture?.height||1,this.KHR_iridescenceThicknessTexture?.gpuTexture?.height||1);await this.#Ua.packing({r:this.KHR_iridescenceTexture?.gpuTexture,g:this.KHR_iridescenceThicknessTexture?.gpuTexture},i,g,"packedKHR_iridescence")}}definePositiveNumber(PBRMaterial,[{key:"emissiveStrength",value:1},{key:"normalScale",value:1}]);Ui.forEach(i=>{const{extensionName:g,textureList:x,useSampler:v}=i,{positiveNumberList:_,vec3List:y,vec4List:b}=i;g&&defineBoolean(PBRMaterial,[{key:`use${g}`,value:!1}]),((i,g)=>{i?.forEach(i=>{defineBoolean(PBRMaterial,[{key:`use${i.charAt(0).toUpperCase()}${i.substring(1)}`,value:!1}]),definePositiveNumber(PBRMaterial,[{key:`${i}_KHR_texture_transform_rotation`,value:0}]),defineBoolean(PBRMaterial,[{key:`use_${i}_KHR_texture_transform`,value:!1}]),defineVector2(PBRMaterial,[{key:`${i}_KHR_texture_transform_offset`},{key:`${i}_KHR_texture_transform_scale`,value:[1,1]}]),defineUint(PBRMaterial,[{key:`${i}_texCoord_index`,value:0}]),defineTexture(PBRMaterial,[{key:i}]),g&&defineSampler(PBRMaterial,[{key:`${i}Sampler`}])})})(x,!v),_?.forEach(i=>{definePositiveNumber(PBRMaterial,[i])}),y?.forEach(i=>{defineVector3(PBRMaterial,[i])}),b?.forEach(i=>{defineVector4(PBRMaterial,[i])})}),definePositiveNumber(PBRMaterial,[{key:"cutOff",value:0},{key:"KHR_materials_ior",value:1.5},{key:"KHR_dispersion",value:0}]),defineUint(PBRMaterial,[{key:"alphaBlend",value:0}]),defineBoolean(PBRMaterial,[{key:"doubleSided",value:!1},{key:"useCutOff",value:!1},{key:"useVertexColor",value:!1},{key:"useVertexTangent",value:!1},{key:"useKHR_materials_unlit",value:!1},{key:"useSSR",value:!0}]),Object.freeze(PBRMaterial);var Gi="struct InputData{@location(0)position:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,@location(3)uv1:vec2,@location(4)vertexColor_0:vec4,@location(5)vertexTangent:vec4,};",Oi="struct VertexOutput{@builtin(position)position:vec4,@location(0)vertexPosition:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,@location(3)uv1:vec2,@location(4)vertexColor_0:vec4,@location(5)vertexTangent:vec4,@location(7)currentClipPos:vec4,@location(8)prevClipPos:vec4,@location(10)localNodeScale_volumeScale:vec2,@location(11)combinedOpacity:f32,@location(12)motionVector:vec3,@location(13)shadowCoord:vec3,@location(14)@interpolate(flat)receiveShadow:f32,@location(15)@interpolate(flat)pickingId:vec4,};",Vi="struct InputData{@location(0)position:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,@location(3)vertexTangent:vec4,};",Ni="struct VertexOutput{@builtin(position)position:vec4,@location(0)vertexPosition:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,@location(3)vertexTangent:vec4,@location(7)currentClipPos:vec4,@location(8)prevClipPos:vec4,@location(11)combinedOpacity:f32,@location(12)motionVector:vec3,@location(13)shadowCoord:vec3,@location(14)@interpolate(flat)receiveShadow:f32,@location(15)@interpolate(flat)pickingId:vec4,};",Fi="#redgpu_include SYSTEM_UNIFORM;#redgpu_include shadow.getShadowCoord;#redgpu_include entryPoint.mesh.entryPointShadowVertex;#redgpu_include entryPoint.mesh.entryPointPickingVertex;#redgpu_include displacement.getDisplacementPosition;#redgpu_include systemStruct.meshVertexBasicUniform;const maxDistance:f32=1000.0;@group(1)@binding(0)varvertexUniforms:VertexUniforms;@group(1)@binding(1)var displacementTextureSampler:sampler;@group(1)@binding(2)var displacementTexture:texture_2d;@vertex fn main(inputData:InputData)->VertexOutput{var output:VertexOutput;#redgpu_if disableJitter{let u_projectionMatrix=systemUniforms.projection.noneJitterProjectionViewMatrix;}#redgpu_else{let u_projectionMatrix=systemUniforms.projection.projectionMatrix;}#redgpu_endIf let u_projectionViewMatrix=systemUniforms.projection.projectionViewMatrix;let u_noneJitterProjectionViewMatrix=systemUniforms.projection.noneJitterProjectionViewMatrix;let u_prevNoneJitterProjectionViewMatrix=systemUniforms.projection.prevNoneJitterProjectionViewMatrix;let u_resolution=systemUniforms.resolution;let u_camera=systemUniforms.camera;let u_viewMatrix=u_camera.viewMatrix;let u_cameraPosition=u_camera.cameraPosition;let u_matrixList=vertexUniforms.matrixList;let u_modelMatrix=u_matrixList.modelMatrix;let u_prevModelMatrix=u_matrixList.prevModelMatrix;let u_normalModelMatrix=u_matrixList.normalModelMatrix;let u_displacementScale=vertexUniforms.displacementScale;let u_useDisplacementTexture=vertexUniforms.useDisplacementTexture==1u;let u_receiveShadow=vertexUniforms.receiveShadow;let u_directionalLightCount=systemUniforms.directionalLightCount;let u_directionalLights=systemUniforms.directionalLights;let u_directionalLightProjectionViewMatrix=systemUniforms.directionalLightProjectionViewMatrix;let input_position=inputData.position;let input_position_vec4=vec4(input_position,1.0);let input_vertexNormal=inputData.vertexNormal;let input_uv=inputData.uv;let transformedUV=input_uv*vertexUniforms.uvTransform.zw+vertexUniforms.uvTransform.xy;var position:vec4;#redgpu_if useDisplacementTexture let tempPosition=u_modelMatrix*input_position_vec4;let distance=distance(tempPosition.xyz,u_cameraPosition);let maxMipLevel=f32(textureNumLevels(displacementTexture))-1.0;let targetMipLevel=clamp((distance/maxDistance)*maxMipLevel,.0,maxMipLevel);let displacedPosition=getDisplacementPosition(input_position,input_vertexNormal,displacementTexture,displacementTextureSampler,u_displacementScale,transformedUV,targetMipLevel);position=u_modelMatrix*vec4(displacedPosition,1.0);#redgpu_else position=u_modelMatrix*input_position_vec4;#redgpu_endIf let worldNormal=normalize((u_normalModelMatrix*vec4(input_vertexNormal,.0)).xyz);let normalPosition=vec4(worldNormal,.0);output.position=u_projectionViewMatrix*position;output.vertexPosition=position.xyz;output.vertexNormal=normalPosition.xyz;output.uv=transformedUV;let transformedTangentXYZ=(u_normalModelMatrix*vec4(inputData.vertexTangent.xyz,.0)).xyz;output.vertexTangent=vec4(normalize(transformedTangentXYZ),inputData.vertexTangent.w);output.combinedOpacity=vertexUniforms.combinedOpacity;#redgpu_if receiveShadow{output.shadowCoord=getShadowCoord(position.xyz,u_directionalLightProjectionViewMatrix);output.receiveShadow=vertexUniforms.receiveShadow;}#redgpu_endIf{output.currentClipPos=u_noneJitterProjectionViewMatrix*position;output.prevClipPos=u_prevNoneJitterProjectionViewMatrix*u_prevModelMatrix*input_position_vec4;}return output;}";const Hi={SHADER_INFO_PBR:parseWGSL("MESH_PBR",[Gi,Oi,"#redgpu_include SYSTEM_UNIFORM;#redgpu_include shadow.getShadowCoord;#redgpu_include entryPoint.mesh.entryPointShadowVertex;#redgpu_include entryPoint.mesh.entryPointPickingVertex;#redgpu_include systemStruct.meshVertexBasicUniform;@group(1)@binding(0)varvertexUniforms:VertexUniforms;@group(1)@binding(1)var displacementTextureSampler:sampler;@group(1)@binding(2)var displacementTexture:texture_2d;@vertex fn main(inputData:InputData)->VertexOutput{var output:VertexOutput;let input_position=inputData.position;let input_position_vec4=vec4(input_position,1.0);let input_vertexNormal=inputData.vertexNormal;let u_projectionMatrix=systemUniforms.projection.projectionMatrix;let u_projectionViewMatrix=systemUniforms.projection.projectionViewMatrix;let u_noneJitterProjectionViewMatrix=systemUniforms.projection.noneJitterProjectionViewMatrix;let u_prevNoneJitterProjectionViewMatrix=systemUniforms.projection.prevNoneJitterProjectionViewMatrix;let u_resolution=systemUniforms.resolution;let u_camera=systemUniforms.camera;let u_viewMatrix=u_camera.viewMatrix;let u_cameraPosition=u_camera.cameraPosition;let u_matrixList=vertexUniforms.matrixList;let u_localMatrix=u_matrixList.localMatrix;let u_modelMatrix=u_matrixList.modelMatrix;let u_normalModelMatrix=u_matrixList.normalModelMatrix;let u_prevModelMatrix=u_matrixList.prevModelMatrix;let u_receiveShadow=vertexUniforms.receiveShadow;let u_directionalLightCount=systemUniforms.directionalLightCount;let u_directionalLights=systemUniforms.directionalLights;let u_directionalLightProjectionViewMatrix=systemUniforms.directionalLightProjectionViewMatrix;var position:vec4;var normalPosition:vec4;position=u_modelMatrix*input_position_vec4;normalPosition=u_normalModelMatrix*vec4(input_vertexNormal,.0);output.position=u_projectionViewMatrix*position;output.vertexPosition=position.xyz;output.vertexNormal=normalize(normalPosition.xyz);output.uv=inputData.uv;output.uv1=inputData.uv1;output.vertexColor_0=inputData.vertexColor_0;let transformedTangentXYZ=(u_normalModelMatrix*vec4(inputData.vertexTangent.xyz,.0)).xyz;output.vertexTangent=vec4(normalize(transformedTangentXYZ),inputData.vertexTangent.w);#redgpu_if receiveShadow{output.shadowCoord=getShadowCoord(position.xyz,u_directionalLightProjectionViewMatrix);output.receiveShadow=vertexUniforms.receiveShadow;}#redgpu_endIf{output.currentClipPos=u_noneJitterProjectionViewMatrix*position;output.prevClipPos=u_prevNoneJitterProjectionViewMatrix*u_prevModelMatrix*input_position_vec4;}let nodeScaleX=length(u_localMatrix[0].xyz);let nodeScaleY=length(u_localMatrix[1].xyz);let nodeScaleZ=length(u_localMatrix[2].xyz);let volumeScaleX=length(u_modelMatrix[0].xyz);let volumeScaleY=length(u_modelMatrix[1].xyz);let volumeScaleZ=length(u_modelMatrix[2].xyz);output.localNodeScale_volumeScale=vec2(pow(nodeScaleX*nodeScaleY*nodeScaleZ,1.0/3.0),pow(volumeScaleX*volumeScaleY*volumeScaleZ,1.0/3.0));return output;}"].join("\n")),SHADER_INFO_BASIC:parseWGSL("MESH_BASIC",[Vi,Ni,Fi].join("\n")),SHADER_INFO_ONLY_FRAGMENT_PBR:parseWGSL("MESH_ONLY_FRAGMENT_PBR",[Vi,Oi,Fi].join("\n")),SHADER_INFO_ONLY_VERTEX_PBR:parseWGSL("MESH_ONLY_VERTEX_PBR",[Gi,Ni,Fi].join("\n"))};Object.freeze(Hi);const{SHADER_INFO_PBR:zi,SHADER_INFO_BASIC:$i,SHADER_INFO_ONLY_FRAGMENT_PBR:ji,SHADER_INFO_ONLY_VERTEX_PBR:Ki}=Hi,Xi=zi.shaderSourceVariant.getVariant("none"),qi=$i.shaderSourceVariant.getVariant("none"),Yi=ji.shaderSourceVariant.getVariant("none"),Wi=Ki.shaderSourceVariant.getVariant("none");class LODManager{#Ga=[];#Oa;#Va=!1;constructor(i,g){"InstancingMesh"===i.constructor.name&&(this.#Va=!0),this.#Oa=g}get LODList(){return[...this.#Ga]}addLOD(i,g,x){if(validatePositiveNumberRange(i,1),this.#Ga.length>=8)throw new Error("Maximum of 8 LOD levels allowed.");if(this.#Ga.some(g=>g.distance===i))throw new Error(`LOD with distance ${i} already exists.`);const v="PBR"===g.vertexBuffer.interleavedStruct.label,_=x instanceof PBRMaterial,y={distance:i,distanceSquared:i*i,geometry:g,material:x,geometryIsPBR:v,materialIsPBR:_};this.#Ga.push({...y,...this.#Va?{}:{label:`vertex_${v?"pbr":"noPbr"}_fragment_${_?"pbr":"noPbr"}`,source:this.#Na(g,x)}}),this.#Ga.sort((i,g)=>i.distance-g.distance),this.#Oa?.()}getLOD(i){for(const g of this.#Ga)if(ig.distance!==i),this.#Oa?.()}clearLOD(){this.#Ga.length=0,this.#Oa?.()}#Na(i,g){const x="PBR"===i.vertexBuffer.interleavedStruct.label,v=g instanceof PBRMaterial;return x&&v?Xi:!x&&v?Yi:x&&!v?Wi:qi}}const Zi=Object.values(Er);class DepthStencilState{#Fa;#z="depth32float";#Ha=["r8unorm","r8snorm","r8uint","r8sint","r16uint","r16sint","r16float","rg8unorm","rg8snorm","rg8uint","rg8sint","r32uint","r32sint","r32float","rg16uint","rg16sint","rg16float","rgba8unorm","rgba8unorm-srgb","rgba8snorm","rgba8uint","rgba8sint","bgra8unorm","bgra8unorm-srgb","rgb9e5ufloat","rgb10a2uint","rgb10a2unorm","rg11b10ufloat","rg32uint","rg32sint","rg32float","rgba16uint","rgba16sint","rgba16float","rgba32uint","rgba32sint","rgba32float","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"];#za=!0;#$a=Er.LESS_EQUAL;#ja;#Ka;#Xa;#qa;#Ya=1;#Wa=1;#Za=1;constructor(i){this.#Fa=i}get format(){return this.#z}set format(i){this.#Ha.includes(i)?(this.#z=i,this.#Fa.dirtyPipeline=!0):consoleAndThrowError(`Invalid value for format. Received ${i}. Expected one of: ${this.#Ha.join(", ")}`)}get depthWriteEnabled(){return this.#za}set depthWriteEnabled(i){this.#za=i,this.#Fa.dirtyPipeline=!0}get depthCompare(){return this.#$a}set depthCompare(i){Zi.includes(i)?(this.#$a=i,this.#Fa.dirtyPipeline=!0):consoleAndThrowError(`Invalid value for depthCompare. Received ${i}. Expected one of: ${Zi.join(", ")}`)}get stencilFront(){return this.#ja}set stencilFront(i){this.#ja=i,this.#Fa.dirtyPipeline=!0}get stencilBack(){return this.#Ka}set stencilBack(i){this.#Ka=i,this.#Fa.dirtyPipeline=!0}get stencilReadMask(){return this.#Xa}set stencilReadMask(i){this.#Xa=i,this.#Fa.dirtyPipeline=!0}get stencilWriteMask(){return this.#qa}set stencilWriteMask(i){this.#qa=i,this.#Fa.dirtyPipeline=!0}get depthBias(){return this.#Ya}set depthBias(i){this.#Ya=i,this.#Fa.dirtyPipeline=!0}get depthBiasSlopeScale(){return this.#Wa}set depthBiasSlopeScale(i){this.#Wa=i,this.#Fa.dirtyPipeline=!0}get depthBiasClamp(){return this.#Za}set depthBiasClamp(i){this.#Za=i,this.#Fa.dirtyPipeline=!0}get state(){let i=!1;if(this.#Fa?.primitiveState){const{topology:g}=this.#Fa.primitiveState;i=g===Ei.TRIANGLE_LIST||g===Ei.TRIANGLE_STRIP}return{format:this.#z,depthWriteEnabled:this.#za,depthCompare:this.#$a,stencilFront:this.#ja,stencilBack:this.#Ka,stencilReadMask:this.#Xa,stencilWriteMask:this.#qa,depthBias:i?this.#Ya:null,depthBiasSlopeScale:i?this.#Wa:null,depthBiasClamp:i?this.#Za:null}}}const Ji={NONE:"none",FRONT:"front",BACK:"back"};Object.freeze(Ji);const Qi={CW:"cw",CCW:"ccw"};Object.freeze(Qi);const en={UINT16:"uint16",UINT32:"uint32"};Object.freeze(en);const tn=Object.values(en),rn=Object.values(Qi),nn=Object.values(Ji),an=["point-list","line-list","line-strip","triangle-list","triangle-strip"];class PrimitiveState{dirtyPipeline=!1;state;#Fa;#Ja=Ei.TRIANGLE_LIST;#Qa;#es=Qi.CCW;#ts=Ji.BACK;#rs=!1;constructor(i){this.#Fa=i,this.#Qt()}get topology(){return this.#Ja}set topology(i){an.includes(i)?(this.#Ja=i,this.#Qt()):consoleAndThrowError(`Invalid value for topology. Received ${i}. Expected one of: ${an.join(", ")}`)}get stripIndexFormat(){return this.#Qa}set stripIndexFormat(i){tn.includes(i)?(this.#Qa=i,this.#Qt()):consoleAndThrowError(`Invalid value for stripIndexFormat. Received ${i}. Expected one of: ${tn.join(", ")}`)}get frontFace(){return this.#es}set frontFace(i){rn.includes(i)?(this.#es=i,this.#Qt()):consoleAndThrowError(`Invalid value for frontFace. Received ${i}. Expected one of: ${rn.join(", ")}`)}get cullMode(){return this.#ts}set cullMode(i){nn.includes(i)?(this.#ts=i,this.#Qt()):consoleAndThrowError(`Invalid value for cullMode. Received ${i}. Expected one of: ${nn.join(", ")}`)}get unclippedDepth(){return this.#rs}set unclippedDepth(i){"boolean"==typeof i?(this.#rs=i,this.#Qt()):consoleAndThrowError(`Invalid type for unclippedDepth. Received ${typeof i}. Expected type: boolean.`)}#Qt(){this.state={topology:this.#Ja,stripIndexFormat:this.#Qa,frontFace:this.#es,cullMode:this.#ts,unclippedDepth:this.#rs},this.#Fa.dirtyPipeline=!0}}const sn=create$4(),on={x:0,y:0,z:0,w:0},getScreenPoint=(i,g)=>{"View3D"!==i?.constructor?.name&&consoleAndThrowError("allow only View3D instance"),identity$1(sn);const{noneJitterProjectionMatrix:x,rawCamera:v,pixelRectArray:_}=i;return multiply$4(sn,x,v.viewMatrix),multiply$4(sn,sn,g),on.z=sn[14],on.w=sn[15],on.x=.5*sn[12]/on.w+.5,on.y=.5*sn[13]/on.w+.5,[(_[0]+on.x*_[2])/window.devicePixelRatio,(_[1]+(1-on.y)*_[3])/window.devicePixelRatio]},un=create$4(),localToWorld=(i,g,x,v)=>(validateNumber(g),validateNumber(x),validateNumber(v),identity$1(un),translate(un,un,[g,x,v]),multiply$4(un,i,un),[un[12],un[13],un[14]]),cn=create$4(),hn=create$3(),worldToLocal=(i,g,x,v)=>(validateNumber(g),validateNumber(x),validateNumber(v),invert$1(cn,i),set$3(hn,g,x,v),transformMat4$2(hn,hn,cn),[hn[0],hn[1],hn[2]]);class Object3DContainer extends BaseObject{modelMatrix=create$4();#is=[];constructor(){super()}get children(){return this.#is}get numChildren(){return this.#is.length}contains(i){return this.#ns(i),this.#is.includes(i)}addChild(i){return this.#ns(i),this.#as(i)?(this.#is.push(i),i.dirtyTransform=!0,i):null}addChildAt(i,g){if(validateUintRange(g),this.#is.lengththis.#is.length)&&this.#as(i))return this.#is.splice(g,0,i),i.dirtyTransform=!0,this}getChildAt(i){if(validateUintRange(i),!(i>=this.#is.length||i<0))return this.#is[i]}getChildIndex(i){this.#ns(i);const g=this.#is.indexOf(i);return-1===g?-1:g}setChildIndex(i,g){this.#ns(i),validateUintRange(g);const x=this.#is.length,v=g>=x,_=this.#is.indexOf(i);-1!==_?v?consoleAndThrowError(`Invalid index. Index ${g} is out of bounds. Index should be between 0 and ${x-1}.`):(this.#is.splice(_,1),this.#is.splice(g,0,i)):consoleAndThrowError(`The provided is not a child of the Object3DContainer.: ${i}`)}swapChildren(i,g){if(this.#ns(i),this.#ns(g),i===g)return void consoleAndThrowError("Error: child1 and child2 are the same. Cannot swap a child with itself.");const x=this.#is.indexOf(i),v=this.#is.indexOf(g);-1!==x&&-1!==v||consoleAndThrowError(`Error: ${-1===x?"child1":"child2"} is not a child of this Object3DContainer.`),this.swapChildrenAt(x,v)}swapChildrenAt(i,g){validateUintRange(i),validateUintRange(g),i===g&&consoleAndThrowError("Error: index1 and index2 are identical. Cannot swap a child with itself.");const x=this.#is.length;(i>=x||g>=x)&&consoleAndThrowError(`Error: Both index1 and index2 should be less than the number of children. Provided index1: ${i}, index2: ${g}, number of children: ${x}`);let v=this.#is[i];this.#is[i]=this.#is[g],this.#is[g]=v}removeChild(i){this.#ns(i);const g=this.#is.indexOf(i);if(g>-1)return i.parent=null,this.#is.splice(g,1)[0];consoleAndThrowError("Error: Child not found within parent.")}removeChildAt(i){validateUintRange(i);const g=this.#is[i];if(g)return g.parent=null,this.#is.splice(i,1)[0];throw new Error(`Error: No child found at provided index: ${i}.`)}removeAllChildren(){let i=this.#is.length;for(;i--;)this.#is[i].parent=null;return this.#is.length=0,this}#ns(i){i instanceof Object3DContainer||consoleAndThrowError("allow only Object3DContainer instance.")}#as=i=>(this.#ns(i),i.parent?!!i.parent?.removeChild(i)&&(i.parent=this,!0):(i.parent=this,!0))}class MeshBase extends Object3DContainer{gpuRenderInfo;animationInfo={skinInfo:null,morphInfo:null,weightBuffer:null,jointBuffer:null,animationsList:null};gltfLoaderInfo;dirtyPipeline=!0;dirtyTransform=!0;dirtyOpacity=!0;modelMatrix=create$4();localMatrix=create$4();normalModelMatrix=create$4();#h;#f;#ss;#os;#us;constructor(i){super(),validateRedGPUContext(i),this.#h=i,this.#f=i.gpuDevice,this.#ss=new PrimitiveState(this),this.#os=new DepthStencilState(this)}get currentShaderModuleName(){return this.#us}set currentShaderModuleName(i){this.#us=i}get primitiveState(){return this.#ss}get depthStencilState(){return this.#os}get gpuDevice(){return this.#f}get redGPUContext(){return this.#h}worldToLocal(i,g,x){return worldToLocal(this.modelMatrix,i,g,x)}localToWorld(i,g,x){return localToWorld(this.modelMatrix,i,g,x)}getScreenPoint(i){return getScreenPoint(i,this.modelMatrix)}}const fn="shadow",dn="picking",createBasePipeline=(i,g,x,v)=>{const{redGPUContext:_}=i,{gpuDevice:y,resourceManager:b}=_,S=i.material.gpuRenderInfo;let w,L;switch(v){case fn:w="entryPointShadowVertex",L=`${g.label}_shadow_pipeline`;break;case dn:w="entryPointPickingVertex",L=`${g.label}_picking_pipeline`;break;default:w="main",L=`${g.label}_pipeline`}const k={module:g,entryPoint:w,buffers:i.vertexStateBuffers},H=[b.getGPUBindGroupLayout(ResourceManager.PRESET_GPUBindGroupLayout_System),x];v!==fn&&H.push(S.fragmentBindGroupLayout);const z={bindGroupLayouts:H,label:`${L}_${S.fragmentBindGroupLayout.label}`},q={label:L,layout:b.createGPUPipelineLayout(`${z.label}`,z),vertex:k,primitive:i.primitiveState.state};switch(v){case fn:q.depthStencil={depthWriteEnabled:!0,depthCompare:Er.LESS_EQUAL,format:"depth32float"};break;case dn:i.material&&(q.fragment={module:i.material.gpuRenderInfo.fragmentShaderModule,entryPoint:"entryPointPickingFragment",targets:[{format:navigator.gpu.getPreferredCanvasFormat()}]},q.depthStencil=i.depthStencilState.state);break;default:q.fragment=S.fragmentState,q.depthStencil=i.depthStencilState.state,q.multisample={count:_.antialiasingManager.useMSAA?4:1}}return y.createRenderPipeline(q)};const getBasicMeshVertexBindGroupDescriptor=(i,g=!1)=>{const{redGPUContext:x,gpuRenderInfo:v,material:_}=i,{resourceManager:y}=x,{vertexUniformBuffer:b,vertexBindGroupLayout:S}=v,{basicSampler:w,emptyBitmapTextureView:L,basicDisplacementSampler:k}=y,{gpuSampler:H}=w;return{layout:S,label:g?"VERTEX_BIND_GROUP_DESCRIPTOR_MESH_SKIN":"VERTEX_BIND_GROUP_DESCRIPTOR_MESH",entries:g?[{binding:0,resource:{buffer:b.gpuBuffer,offset:0,size:b.size}},{binding:1,resource:k.gpuSampler},{binding:2,resource:y.getGPUResourceBitmapTextureView(_?.displacementTexture)||L},{binding:3,resource:{buffer:i.animationInfo.skinInfo.vertexStorageBuffer,offset:0,size:i.animationInfo.skinInfo.vertexStorageBuffer.size}},{binding:4,resource:{buffer:i.animationInfo.skinInfo.prevVertexStorageBuffer,offset:0,size:i.animationInfo.skinInfo.prevVertexStorageBuffer.size}}]:[{binding:0,resource:{buffer:b.gpuBuffer,offset:0,size:b.size}},{binding:1,resource:k.gpuSampler},{binding:2,resource:y.getGPUResourceBitmapTextureView(_?.displacementTexture)||L}]}},{SHADER_INFO_PBR:mn,SHADER_INFO_BASIC:pn,SHADER_INFO_ONLY_FRAGMENT_PBR:gn,SHADER_INFO_ONLY_VERTEX_PBR:xn}=Hi,vn=mn.uniforms.vertexUniforms,_n=pn.uniforms.vertexUniforms,createMeshVertexShaderModule=i=>{const{material:g}=i;let x,v="basic";switch(g instanceof PBRMaterial&&i.animationInfo?.skinInfo?v="skin":i.createCustomMeshVertexShaderModule&&(v="custom"),v){case"basic":{const g=(i=>{const{geometry:g,material:x}=i,v="PBR"===g.vertexBuffer.interleavedStruct.label,_=x instanceof PBRMaterial,y=v&&!_,b=!v&&_;return v&&_?{name:"VERTEX_MODULE_MESH_PBR",shaderInfo:mn,source:mn.defaultSource,uniformStruct:vn}:b?{name:"VERTEX_MODULE_MESH_ONLY_FRAGMENT_PBR",shaderInfo:gn,source:gn.defaultSource,uniformStruct:_n}:y?{name:"VERTEX_MODULE_MESH_ONLY_VERTEX_PBR",shaderInfo:xn,source:xn.defaultSource,uniformStruct:_n}:{name:"VERTEX_MODULE_MESH",shaderInfo:pn,source:pn.defaultSource,uniformStruct:_n}})(i);x=i.createMeshVertexShaderModuleBASIC(g.name,g.shaderInfo,g.uniformStruct,g.source);break}case"skin":x=((i,g)=>{const{redGPUContext:x,currentShaderModuleName:v}=g,{resourceManager:_,gpuDevice:y}=x,{gpuRenderInfo:b}=g,S=`${g.animationInfo.skinInfo.joints.length}`,w=`${i}_${S}`,L="#redgpu_include SYSTEM_UNIFORM;#redgpu_include shadow.getShadowCoord;#redgpu_include shadow.getShadowClipPosition;#redgpu_include systemStruct.meshVertexBasicUniform;@group(1)@binding(0)varvertexUniforms:VertexUniforms;@group(1)@binding(1)var displacementTextureSampler:sampler;@group(1)@binding(2)var displacementTexture:texture_2d;@group(1)@binding(3)varvertexStorages:array>;@group(1)@binding(4)varprevVertexStorages:array>;struct InputDataSkin{@builtin(vertex_index)idx:u32,@location(0)position:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,@location(3)uv1:vec2,@location(4)vertexColor_0:vec4,@location(5)vertexTangent:vec4,};struct VertexOutput{@builtin(position)position:vec4,@location(0)vertexPosition:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,@location(3)uv1:vec2,@location(4)vertexColor_0:vec4,@location(5)vertexTangent:vec4,@location(7)currentClipPos:vec4,@location(8)prevClipPos:vec4,@location(10)localNodeScale_volumeScale:vec2,@location(11)combinedOpacity:f32,@location(12)motionVector:vec3,@location(13)shadowCoord:vec3,@location(14)@interpolate(flat)receiveShadow:f32,@location(15)@interpolate(flat)pickingId:vec4,};#redgpu_include systemStruct.OutputShadowData;@vertex fn main(inputData:InputDataSkin)->VertexOutput{var output:VertexOutput;let input_position=inputData.position;let input_position_vec4=vec4(input_position,1.0);let input_vertexNormal=inputData.vertexNormal;let u_projectionMatrix=systemUniforms.projection.projectionMatrix;let u_projectionViewMatrix=systemUniforms.projection.projectionViewMatrix;let u_noneJitterProjectionViewMatrix=systemUniforms.projection.noneJitterProjectionViewMatrix;let u_prevNoneJitterProjectionViewMatrix=systemUniforms.projection.prevNoneJitterProjectionViewMatrix;let u_resolution=systemUniforms.resolution;let u_camera=systemUniforms.camera;let u_viewMatrix=u_camera.viewMatrix;let u_cameraPosition=u_camera.cameraPosition;let u_matrixList=vertexUniforms.matrixList;let u_localMatrix=u_matrixList.localMatrix;let u_modelMatrix=u_matrixList.modelMatrix;let u_prevModelMatrix=u_matrixList.prevModelMatrix;let u_normalModelMatrix=u_matrixList.normalModelMatrix;let u_receiveShadow=vertexUniforms.receiveShadow;let u_directionalLightCount=systemUniforms.directionalLightCount;let u_directionalLights=systemUniforms.directionalLights;let u_directionalLightProjectionViewMatrix=systemUniforms.directionalLightProjectionViewMatrix;let skinMat=vertexStorages[inputData.idx];let prevSkinMat=prevVertexStorages[inputData.idx];let skinnedPosition=(skinMat*vec4(inputData.position,1.0));let position=u_modelMatrix*skinnedPosition;let skinnedNormal=(skinMat*vec4(input_vertexNormal,.0)).xyz;let transformedNormal=normalize((u_normalModelMatrix*vec4(skinnedNormal,.0)).xyz);output.vertexNormal=transformedNormal;let skinnedTangent=(skinMat*vec4(inputData.vertexTangent.xyz,.0)).xyz;let transformedTangentXYZ=(u_normalModelMatrix*vec4(skinnedTangent,.0)).xyz;output.vertexTangent=vec4(normalize(transformedTangentXYZ),inputData.vertexTangent.w);output.position=u_projectionViewMatrix*position;output.vertexPosition=position.xyz;output.uv=inputData.uv;output.uv1=inputData.uv1;output.vertexColor_0=inputData.vertexColor_0;#redgpu_if receiveShadow{output.shadowCoord=getShadowCoord(position.xyz,u_directionalLightProjectionViewMatrix);output.receiveShadow=vertexUniforms.receiveShadow;}#redgpu_endIf{output.currentClipPos=u_noneJitterProjectionViewMatrix*position;output.prevClipPos=u_prevNoneJitterProjectionViewMatrix*u_prevModelMatrix*(prevSkinMat*input_position_vec4);}let nodeScaleX=length(u_localMatrix[0].xyz);let nodeScaleY=length(u_localMatrix[1].xyz);let nodeScaleZ=length(u_localMatrix[2].xyz);let volumeScaleX=length(u_modelMatrix[0].xyz);let volumeScaleY=length(u_modelMatrix[1].xyz);let volumeScaleZ=length(u_modelMatrix[2].xyz);output.localNodeScale_volumeScale=vec2(pow(nodeScaleX*nodeScaleY*nodeScaleZ,1.0/3.0),pow(volumeScaleX*volumeScaleY*volumeScaleZ,1.0/3.0));return output;}@vertex fn entryPointShadowVertex(inputData:InputDataSkin)->OutputShadowData{var output:OutputShadowData;let u_directionalLightProjectionViewMatrix=systemUniforms.directionalLightProjectionViewMatrix;let u_modelMatrix=vertexUniforms.matrixList.modelMatrix;let input_position=inputData.position;let skinMat=vertexStorages[inputData.idx];let position=u_modelMatrix*skinMat*vec4(input_position,1.0);output.position=getShadowClipPosition(position.xyz,u_directionalLightProjectionViewMatrix);return output;}@vertex fn entryPointPickingVertex(inputData:InputDataSkin)->VertexOutput{var output:VertexOutput;let u_projectionViewMatrix=systemUniforms.projection.projectionViewMatrix;let u_modelMatrix=vertexUniforms.matrixList.modelMatrix;let skinMat=vertexStorages[inputData.idx];let position=u_modelMatrix*skinMat*vec4(inputData.position,1.0);output.position=u_projectionViewMatrix*position;output.pickingId=unpack4x8unorm(vertexUniforms.pickingId);return output;}",k={code:L};return v===w?_.getGPUShaderModule(w):(k.code=L.replaceAll("#JOINT_NUM",S),b.vertexUniformInfo=parseWGSL("MESH_VERTEX_PBR_SKIN",k.code).uniforms.vertexUniforms,g.animationInfo.skinInfo?(createMeshVertexUniformBuffers(g,!0),g.animationInfo.skinInfo.vertexStorageInfo=parseWGSL("MESH_VERTEX_PBR_SKIN",k.code).storage.vertexStorages,g.animationInfo.skinInfo.vertexStorageBuffer=y.createBuffer({size:16*g.geometry.vertexBuffer.vertexCount*4,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST}),g.animationInfo.skinInfo.prevVertexStorageBuffer=y.createBuffer({size:16*g.geometry.vertexBuffer.vertexCount*4,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST}),b.vertexUniformBindGroup=x.gpuDevice.createBindGroup(getBasicMeshVertexBindGroupDescriptor(g,!0))):(createMeshVertexUniformBuffers(g),b.vertexUniformBindGroup=x.gpuDevice.createBindGroup(getBasicMeshVertexBindGroupDescriptor(g))),g.gpuRenderInfo.vertexShaderModule=_.createGPUShaderModule(w,k),g.gpuRenderInfo.vertexShaderModule)})("VERTEX_MODULE_MESH_PBR_SKIN",i);break;case"custom":x=i.createCustomMeshVertexShaderModule()}return i.currentShaderModuleName=x.label,x},updateMeshDirtyPipeline=(i,g)=>{const{material:x,gpuRenderInfo:v,redGPUContext:_}=i,{resourceManager:y}=_;i.dirtyTransform=!0,x.dirtyPipeline&&x._updateFragmentState();const b=createMeshVertexShaderModule(i),S=y.getGPUBindGroupLayout(i.animationInfo.skinInfo?ResourceManager.PRESET_VERTEX_GPUBindGroupLayout_SKIN:ResourceManager.PRESET_VERTEX_GPUBindGroupLayout);v.vertexShaderModule=b,v.pipeline=createBasePipeline(i,b,S),v.shadowPipeline=null,v.pickingPipeline=null;const{vertexUniformInfo:w}=i.gpuRenderInfo,{members:L}=w;for(const g in L)"pickingId"!==g&&"pixelSize"!==g&&(i[g]=i[g]);i.gpuRenderInfo.vertexUniformInfo.members.pickingId&&i.gpuRenderInfo.vertexUniformBuffer.writeOnlyBuffer(i.gpuRenderInfo.vertexUniformInfo.members.pickingId,i.pickingId),x.dirtyPipeline=!1,i.dirtyPipeline=!1,g&&g.renderResults.numDirtyPipelines++};class VertexGPURenderInfo{vertexShaderModule;vertexShaderSourceVariant;vertexShaderVariantConditionalBlocks;vertexStructInfo;vertexUniformInfo;vertexBindGroupLayout;vertexUniformBindGroup;vertexUniformBuffer;pipeline;shadowPipeline;pickingPipeline;constructor(i,g,x,v,_,y,b,S,w,L){this.vertexShaderModule=i,this.vertexShaderSourceVariant=g,this.vertexShaderVariantConditionalBlocks=x,this.vertexUniformInfo=v,this.vertexBindGroupLayout=_,this.vertexUniformBindGroup=b,this.vertexUniformBuffer=y,this.pipeline=S,this.shadowPipeline=w,this.pickingPipeline=L}}Object.freeze(VertexGPURenderInfo);const yn="VERTEX_MODULE_MESH_PBR_SKIN",bn=Math.PI/180,Sn=3.141592653589793,Tn=6.283185307179586,wn=.225,Mn=1.27323954,Pn=.405284735,Rn=1.5707963267948966,Cn=new Float32Array(1),Bn=new Float32Array(4),Dn=new Float32Array([0,1,0]);class Mesh extends MeshBase{castShadow=!1;dirtyLOD=!1;passFrustumCulling=!0;createCustomMeshVertexShaderModule;#ls;#cs;#wi=0;#Mi=0;#Pi=0;#hs=new Float32Array([0,0,0]);#fs=0;#ds=0;#ms=0;#ps;#gs=1;#xs=1;#vs=1;#_s=new Float32Array([1,1,1]);#ys=0;#bs=0;#Ss=0;#Ts=new Float32Array([0,0,0]);#ws={};#Ms=0;#Ps=!1;#Rs=1;#Cs;#Bs=!1;#Ds;#Es;#Is;#As;#Ls;#Us=[];#ks=[];#Gs;#Os=null;#Vs=[];#Ns=null;#Fs=!0;#Hs=!0;#zs;#$s;#js;#Ks=[];#Xs=-1;constructor(i,g,x,v){super(i),v&&(this.name=v),this._geometry=g,this._material=x,this.#ps=uuidToUint(this.uuid),this.#Ns=DrawBufferManager.getInstance(i),this.#qs(),this.#js=new LODManager(this,()=>{this.dirtyLOD=!0})}get LODManager(){return this.#js}get enableDebugger(){return this.#Bs}set enableDebugger(i){this.#Bs=i,i&&!this.#Cs&&(this.#Cs=new DrawDebuggerMesh(this.redGPUContext,this))}get drawDebugger(){return this.#Cs}_material;get material(){return this._material}set material(i){this._material=i,this.dirtyPipeline=!0,"blendMode"in this&&(this.blendMode=this.blendMode)}_geometry;get geometry(){return this._geometry}set geometry(i){this._geometry=i,this.dirtyPipeline=!0,this.dirtyTransform=!0}get opacity(){return this.#Rs}set opacity(i){validatePositiveNumberRange(i,0,1),this.#Rs=i,this.dirtyOpacity=!0}get ignoreFrustumCulling(){return this.#Ps}set ignoreFrustumCulling(i){this.#Ps=i}get pickingId(){return this.#ps}get events(){return this.#ws}get vertexStateBuffers(){return this._geometry.gpuRenderInfo.buffers}get parent(){return this.#cs}set parent(i){this.#cs=i}get pivotX(){return this.#fs}set pivotX(i){this.#fs=i,this.dirtyTransform=!0}get pivotY(){return this.#ds}set pivotY(i){this.#ds=i,this.dirtyTransform=!0}get pivotZ(){return this.#ms}set pivotZ(i){this.#ms=i,this.dirtyTransform=!0}get x(){return this.#wi}set x(i){this.#wi=this.#hs[0]=i,this.dirtyTransform=!0}get y(){return this.#Mi}set y(i){this.#Mi=this.#hs[1]=i,this.dirtyTransform=!0}get z(){return this.#Pi}set z(i){this.#Pi=this.#hs[2]=i,this.dirtyTransform=!0}get position(){return this.#hs}get scaleX(){return this.#gs}set scaleX(i){this.#gs=this.#_s[0]=i,this.dirtyTransform=!0}get scaleY(){return this.#xs}set scaleY(i){this.#xs=this.#_s[1]=i,this.dirtyTransform=!0}get scaleZ(){return this.#vs}set scaleZ(i){this.#vs=this.#_s[2]=i,this.dirtyTransform=!0}get scale(){return this.#_s}get rotationX(){return this.#ys}set rotationX(i){this.#ys=this.#Ts[0]=i%360,this.dirtyTransform=!0}get rotationY(){return this.#bs}set rotationY(i){this.#bs=this.#Ts[1]=i%360,this.dirtyTransform=!0}get rotationZ(){return this.#Ss}set rotationZ(i){this.#Ss=this.#Ts[2]=i%360,this.dirtyTransform=!0}get rotation(){return this.#Ts}get boundingOBB(){return this.#Es&&!this.dirtyTransform||(this.#Es=null,this.#Ds=null,this.#Es=calculateMeshOBB(this)),this.#Es}get boundingAABB(){return this.#Ds&&!this.dirtyTransform||(this.#Es=null,this.#Ds=null,this.#Ds=calculateMeshAABB(this)),this.#Ds}get combinedBoundingAABB(){return calculateMeshCombinedAABB(this)}setEnableDebuggerRecursively(i=!1){"enableDebugger"in this&&(this.enableDebugger=i),this.children&&this.children.forEach(g=>{g.setEnableDebuggerRecursively(i)})}setCastShadowRecursively(i=!1){"castShadow"in this&&(this.castShadow=i),this.children&&this.children.forEach(g=>{g.setCastShadowRecursively(i)})}setReceiveShadowRecursively(i=!1){"receiveShadow"in this&&(this.receiveShadow=i),this.children&&this.children.forEach(g=>{g.setReceiveShadowRecursively(i)})}setIgnoreFrustumCullingRecursively(i=!1){"ignoreFrustumCulling"in this&&(this.ignoreFrustumCulling=i),this.children&&this.children.forEach(g=>{g.setIgnoreFrustumCullingRecursively(i)})}getCombinedOpacity(){if(this.is2DMeshType){const i=this.parent;return this.#Rs*(i?.getCombinedOpacity?i.getCombinedOpacity():1)}return 1}addListener(i,g){this.#ws[i]=g,this.#Ms=Object.keys(this.#ws).length}lookAt(i,g,x){let v=[],_=[];v[0]=i,v[1]=g,v[2]=x,identity$1(this.localMatrix),targetTo(this.localMatrix,[this.#wi,this.#Mi,this.#Pi],v,Dn),_=mat4ToEuler(this.localMatrix,[]),this.rotationX=180*_[0]/Math.PI,this.rotationY=180*_[1]/Math.PI,this.rotationZ=180*_[2]/Math.PI}setScale(i,g,x){g=g??i,x=x??i;const v=this.#_s;this.#gs=v[0]=i,this.#xs=v[1]=g,this.#vs=v[2]=x,this.dirtyTransform=!0}setPosition(i,g,x){g=g??i,x=x??i;const v=this.#hs;this.#wi=v[0]=i,this.#Mi=v[1]=g,this.#Pi=v[2]=x,this.dirtyTransform=!0}setRotation(i,g,x){g=g??i,x=x??i;const v=this.#Ts;this.#ys=v[0]=i,this.#bs=v[1]=g,this.#Ss=v[2]=x,this.dirtyTransform=!0}clone(){const i=new Mesh(this.redGPUContext,this._geometry,this._material);i.setPosition(this.#wi,this.#Mi,this.#Pi),i.setRotation(this.#ys,this.#bs,this.#Ss),i.setScale(this.#gs,this.#xs,this.#vs);let g=this.children.length;for(;g--;)i.addChild(this.children[g].clone());return i}render(i){const{redGPUContext:g}=this,{view:x,isScene2DMode:v,frustumPlanes:_,dirtyVertexUniformFromMaterial:y,useDistanceCulling:b,cullingDistanceSquared:S}=i,{antialiasingManager:w,gpuDevice:L}=g,{scene:k}=x,{shadowManager:H}=k,{directionalShadowManager:z}=H,{pickingManager:q}=x,{castingList:W}=z,be=this._geometry,je=this._material,{uuid:Ke}=je||{};let Xe,Ye,Ze=this.dirtyPipeline;const{skinInfo:Je}=this.animationInfo;if(v&&(this.#Pi=0,this.#ms=0,this.depthStencilState.depthWriteEnabled&&(this.depthStencilState.depthWriteEnabled=!1)),this.dirtyTransform){Xe=!0,this.#Fs=!0,this.#Hs=!0;{const i=this.parent,g=this.localMatrix;let x,_,y,b,S,w,L,k,H,z,q,W,be,je,Ke,Xe,Ye,Ze,Je,Qe,et,tt,it,ft,pt,xt,vt,yt,bt,St,Tt,wt,Mt,Pt,Rt,Ct,Bt,Dt,Et;g[12]=this.#wi,g[13]=this.#Mi,g[14]=this.#Pi,g[15]=1,x=this.#ys*bn,_=this.#bs*bn,y=this.#Ss*bn,it=1,ft=0,pt=0,vt=0,yt=1,bt=0,Tt=0,wt=0,Mt=1,Et=x%Tn,Et<-Sn?Et+=Tn:Et>Sn&&(Et-=Tn),Et=Et<0?Mn*Et+Pn*Et*Et:Mn*Et-Pn*Et*Et,b=Et<0?wn*(Et*-Et-Et)+Et:wn*(Et*Et-Et)+Et,Et=(x+Rn)%Tn,Et<-Sn?Et+=Tn:Et>Sn&&(Et-=Tn),Et=Et<0?Mn*Et+Pn*Et*Et:Mn*Et-Pn*Et*Et,L=Et<0?wn*(Et*-Et-Et)+Et:wn*(Et*Et-Et)+Et,Et=_%Tn,Et<-Sn?Et+=Tn:Et>Sn&&(Et-=Tn),Et=Et<0?Mn*Et+Pn*Et*Et:Mn*Et-Pn*Et*Et,S=Et<0?wn*(Et*-Et-Et)+Et:wn*(Et*Et-Et)+Et,Et=(_+Rn)%Tn,Et<-Sn?Et+=Tn:Et>Sn&&(Et-=Tn),Et=Et<0?Mn*Et+Pn*Et*Et:Mn*Et-Pn*Et*Et,k=Et<0?wn*(Et*-Et-Et)+Et:wn*(Et*Et-Et)+Et,Et=y%Tn,Et<-Sn?Et+=Tn:Et>Sn&&(Et-=Tn),Et=Et<0?Mn*Et+Pn*Et*Et:Mn*Et-Pn*Et*Et,w=Et<0?wn*(Et*-Et-Et)+Et:wn*(Et*Et-Et)+Et,Et=(y+Rn)%Tn,Et<-Sn?Et+=Tn:Et>Sn&&(Et-=Tn),Et=Et<0?Mn*Et+Pn*Et*Et:Mn*Et-Pn*Et*Et,H=Et<0?wn*(Et*-Et-Et)+Et:wn*(Et*Et-Et)+Et,je=k*H,Ke=L*w+b*S*H,Xe=b*w-L*S*H,Ye=-k*w,Ze=L*H-b*S*w,Je=b*H+L*S*w,Qe=S,et=-b*k,tt=L*k;let It=this.#gs,At=this.#xs,Lt=this.#vs;if(this.renderTextureWidth&&(It*=this.renderTextureWidth,At*=this.renderTextureHeight),g[0]=je*It,g[1]=Ke*It,g[2]=Xe*It,g[3]=0,g[4]=Ye*At,g[5]=Ze*At,g[6]=Je*At,g[7]=0,g[8]=Qe*Lt,g[9]=et*Lt,g[10]=tt*Lt,g[11]=0,(this.#fs||this.#ds||this.#ms)&&(it=g[0],ft=g[1],pt=g[2],xt=g[3],vt=g[4],yt=g[5],bt=g[6],St=g[7],Tt=g[8],wt=g[9],Mt=g[10],Pt=g[11],Rt=g[12],Ct=g[13],Bt=g[14],Dt=g[15],z=1,q=0,W=0,be=0,g[0]=z*it+q*vt+W*Tt+be*Rt,g[1]=z*ft+q*yt+W*wt+be*Ct,g[2]=z*pt+q*bt+W*Mt+be*Bt,g[3]=z*xt+q*St+W*Pt+be*Dt,z=0,q=1,W=0,be=0,g[4]=z*it+q*vt+W*Tt+be*Rt,g[5]=z*ft+q*yt+W*wt+be*Ct,g[6]=z*pt+q*bt+W*Mt+be*Bt,g[7]=z*xt+q*St+W*Pt+be*Dt,z=0,q=0,W=1,be=0,g[8]=z*it+q*vt+W*Tt+be*Rt,g[9]=z*ft+q*yt+W*wt+be*Ct,g[10]=z*pt+q*bt+W*Mt+be*Bt,g[11]=z*xt+q*St+W*Pt+be*Dt,v?i?.modelMatrix?(z=-this.#fs,q=-this.#ds,W=-this.#ms,be=1):(z=-this.#fs/x,q=-this.#ds/_,W=-this.#ms,be=1):(z=-this.#fs,q=-this.#ds,W=-this.#ms,be=1),g[12]=z*it+q*vt+W*Tt+be*Rt,g[13]=z*ft+q*yt+W*wt+be*Ct,g[14]=z*pt+q*bt+W*Mt+be*Bt,g[15]=z*xt+q*St+W*Pt+be*Dt),i?.modelMatrix){const g=i.modelMatrix,x=this.localMatrix,v=this.modelMatrix,_=g[0],y=g[1],b=g[2],S=g[3],w=g[4],L=g[5],k=g[6],H=g[7],z=g[8],q=g[9],W=g[10],be=g[11],je=g[12],Ke=g[13],Xe=g[14],Ye=g[15];let Ze=x[0],Je=x[1],Qe=x[2],et=x[3];v[0]=Ze*_+Je*w+Qe*z+et*je,v[1]=Ze*y+Je*L+Qe*q+et*Ke,v[2]=Ze*b+Je*k+Qe*W+et*Xe,v[3]=Ze*S+Je*H+Qe*be+et*Ye,Ze=x[4],Je=x[5],Qe=x[6],et=x[7],v[4]=Ze*_+Je*w+Qe*z+et*je,v[5]=Ze*y+Je*L+Qe*q+et*Ke,v[6]=Ze*b+Je*k+Qe*W+et*Xe,v[7]=Ze*S+Je*H+Qe*be+et*Ye,Ze=x[8],Je=x[9],Qe=x[10],et=x[11],v[8]=Ze*_+Je*w+Qe*z+et*je,v[9]=Ze*y+Je*L+Qe*q+et*Ke,v[10]=Ze*b+Je*k+Qe*W+et*Xe,v[11]=Ze*S+Je*H+Qe*be+et*Ye,Ze=x[12],Je=x[13],Qe=x[14],et=x[15],v[12]=Ze*_+Je*w+Qe*z+et*je,v[13]=Ze*y+Je*L+Qe*q+et*Ke,v[14]=Ze*b+Je*k+Qe*W+et*Xe,v[15]=Ze*S+Je*H+Qe*be+et*Ye}else{const{modelMatrix:i,localMatrix:g}=this;i[0]=g[0],i[1]=g[1],i[2]=g[2],i[3]=g[3],i[4]=g[4],i[5]=g[5],i[6]=g[6],i[7]=g[7],i[8]=g[8],i[9]=g[9],i[10]=g[10],i[11]=g[11],i[12]=g[12],i[13]=g[13],i[14]=g[14],i[15]=g[15]}}be||(this.#Hs=!1),this.dirtyTransform=!1,this.#Ds=null,this.#Es=null}if(w.useTAA&&this.#zs){const{gpuRenderInfo:i}=this,{vertexUniformBuffer:x,vertexUniformInfo:v}=i,{members:_}=v,{members:y}=_.matrixList;this.#Is&&y.prevModelMatrix&&(this.#zs.set(this.#Is,y.prevModelMatrix.uniformOffsetForData/Float32Array.BYTES_PER_ELEMENT),this.#Hs||g.gpuDevice.queue.writeBuffer(x.gpuBuffer,y.prevModelMatrix.uniformOffset,this.#Is));{this.#Is||(this.#Is=new Float32Array(16));const i=this.#Is,g=this.modelMatrix;i[0]=g[0],i[1]=g[1],i[2]=g[2],i[3]=g[3],i[4]=g[4],i[5]=g[5],i[6]=g[6],i[7]=g[7],i[8]=g[8],i[9]=g[9],i[10]=g[10],i[11]=g[11],i[12]=g[12],i[13]=g[13],i[14]=g[14],i[15]=g[15]}}else this.#Is=null;let Qe=this.passFrustumCulling=!0,et=0;const tt=this.#js.LODList,it=tt.length;if(b&&be||this.#js.LODList.length){const{rawCamera:i}=x,g=this.boundingAABB,v=i.x-g.centerX,_=i.y-g.centerY,y=i.z-g.centerZ;et=v*v+_*_+y*y}if(b&&be){const i=this.boundingAABB.geometryRadius;et>S+i*i&&(Qe=!1)}if(_&&Qe&&!this.#Ps){const{rawCamera:i}=x,g=this.boundingAABB;if("IsometricController"===i.constructor.name){const{centerX:x,centerY:v,centerZ:_,geometryRadius:y}=g,b=i,{left:S,right:w,top:L,bottom:k,nearClipping:H,farClipping:z}=b,{x:q,y:W,z:be}=b;{const i=x-q,g=v-W,b=_-be,je=45*(Math.PI/180),Ke=Math.cos(je),Xe=Math.sin(je),Ye=i*Ke+b*Xe,Ze=-i*Xe+b*Ke;(Ye+yw||g+yL||Ze+yz)&&(Qe=!1)}}else{const i=_[0],x=_[1],v=_[2],y=_[3],b=_[4],S=_[5],w=g.centerX,L=g.centerY,k=g.centerZ,H=g.geometryRadius,z=1;(i[0]*w+i[1]*L+i[2]*k+i[3]<=-H-z||x[0]*w+x[1]*L+x[2]*k+x[3]<=-H-z||v[0]*w+v[1]*L+v[2]*k+v[3]<=-H-z||y[0]*w+y[1]*L+y[2]*k+y[3]<=-H-z||b[0]*w+b[1]*L+b[2]*k+b[3]<=-H-z||S[0]*w+S[1]*L+S[2]*k+S[3]<=-H-z)&&(Qe=!1)}}Qe&&(this.gltfLoaderInfo?.activeAnimations?.length&&(i.animationList[i.animationList.length]=this.gltfLoaderInfo?.activeAnimations),Je&&(this.currentShaderModuleName.includes(yn)||(Ze=!0),this.currentShaderModuleName===`${yn}_${Je.joints?.length}`&&(i.skinList[i.skinList.length]=this,Xe=!1))),this.passFrustumCulling=Qe;const{displacementTexture:ft,displacementScale:pt}=je||{};if((Ze||je?.dirtyPipeline||y[Ke])&&(y[Ke]=!0),be){i.renderResults.num3DObjects++,this.#ls!==w.msaaID&&(Ze=!0,this.dirtyLOD=!0,this.#ls=w.msaaID),this.gpuRenderInfo||this.initGPURenderInfos();const g=!!ft;this.useDisplacementTexture!==g&&(this.useDisplacementTexture=g,Ze=!0),(Ze||y[Ke])&&(updateMeshDirtyPipeline(this,i),this.#As=null,this.#Ls=null);{const{gpuRenderInfo:i}=this,{vertexUniformBuffer:g,vertexUniformInfo:x}=i,{members:v}=x,{gpuBuffer:_}=g;if(this.#zs||(this.#zs=new Float32Array(v.matrixList.endOffset/Float32Array.BYTES_PER_ELEMENT)),v.uvTransform&&(je.dirtyTextureTransform||y[Ke])){const i=je,g=i.textureOffset||[0,0],x=i.textureScale||[1,1];g&&(y[Ke]=!0,Bn[0]=g[0],Bn[1]=g[1],Bn[2]=x[0],Bn[3]=x[1],L.queue.writeBuffer(_,v.uvTransform.uniformOffset,Bn),je.dirtyTextureTransform=!1)}}}else i.renderResults.num3DGroups++;if(be&&Qe){const{gpuRenderInfo:g}=this,{vertexUniformBuffer:v,vertexUniformInfo:_}=g,{members:y}=_,{members:b}=y.matrixList,{gpuBuffer:S}=v;if(this.#zs||(this.#zs=new Float32Array(y.matrixList.endOffset/Float32Array.BYTES_PER_ELEMENT)),void 0!==y.displacementScale&&this.#$s!==pt&&(this.#$s=pt,Cn[0]=pt,L.queue.writeBuffer(S,y.displacementScale.uniformOffset,Cn)),this.#Hs){{const i=this.is2DMeshType?multiply$4(create$4(),this.modelMatrix,fromValues$4(this.width,0,0,0,0,this.height,0,0,0,0,1,0,0,0,0,1)):this.modelMatrix;this.#zs.set(i,b.modelMatrix.uniformOffsetForData/Float32Array.BYTES_PER_ELEMENT)}if(this.#Fs&&b.normalModelMatrix){this.#Fs=!1;const i=this.modelMatrix,g=this.normalModelMatrix,x=i[0],v=i[1],_=i[2],y=i[4],b=i[5],S=i[6],w=i[8],L=i[9],k=i[10],H=x*(b*k-S*L)-v*(y*k-S*w)+_*(y*L-b*w);if(0===H)g[0]=1,g[1]=0,g[2]=0,g[3]=0,g[4]=0,g[5]=1,g[6]=0,g[7]=0,g[8]=0,g[9]=0,g[10]=1,g[11]=0,g[12]=0,g[13]=0,g[14]=0,g[15]=1;else{const i=1/H;g[0]=(b*k-S*L)*i,g[1]=(S*w-y*k)*i,g[2]=(y*L-b*w)*i,g[3]=0,g[4]=(_*L-v*k)*i,g[5]=(x*k-_*w)*i,g[6]=(v*w-x*L)*i,g[7]=0,g[8]=(v*S-_*b)*i,g[9]=(_*y-x*S)*i,g[10]=(x*b-v*y)*i,g[11]=0,g[12]=0,g[13]=0,g[14]=0,g[15]=1}}this.#zs.set(this.normalModelMatrix,b.normalModelMatrix.uniformOffsetForData/Float32Array.BYTES_PER_ELEMENT),b.localMatrix&&this.#zs.set(this.localMatrix,b.localMatrix.uniformOffsetForData/Float32Array.BYTES_PER_ELEMENT),Xe=!0,this.#Hs=!1,L.queue.writeBuffer(S,y.matrixList.startOffset,this.#zs)}this.dirtyOpacity&&(Ye=!0,y.combinedOpacity&&(Cn[0]=this.getCombinedOpacity(),L.queue.writeBuffer(S,y.combinedOpacity.uniformOffset,Cn)),this.dirtyOpacity=!1);const{bundleListRender2PathLayer:w,bundleListParticleLayer:k,bundleListTransparentLayer:H,bundleListAlphaLayer:z,bundleListBasicList:W}=i.renderBundleResults;{const{fragmentUniformBindGroup:g}=je.gpuRenderInfo;if((!this.#As||Ze||this.#Gs!==g||this.#ks[i.viewIndex]!==x.systemUniform_Vertex_UniformBindGroup||this.dirtyLOD)&&this.#Ys(i),i.renderResults.numDrawCalls++,be.indexBuffer){const{indexBuffer:g}=be,{indexCount:x,triangleCount:v}=g;i.renderResults.numTriangles+=v,i.renderResults.numPoints+=x}else{const{vertexBuffer:g}=be,{vertexCount:x,triangleCount:v}=g;i.renderResults.numTriangles+=v,i.renderResults.numPoints+=x}let v=this.#Ls;if(it){let i=this.#Xs;(i<0||i>=it)&&(i=-1);let g=!1;if(-1===i)et>=tt[0].distanceSquared&&(g=!0);else if(i===it-1)et=v)&&(g=!0)}if(g){let g=-1;for(let i=0;i=tt[i].distanceSquared;i++)g=i;g!==i&&(this.#Xs=g,g>=0&&g=0&&i{const{redGPUContext:_}=this,{gpuRenderInfo:y}=this;return y.vertexUniformInfo!==x&&(y.vertexUniformInfo=x,y.vertexStructInfo=g,createMeshVertexUniformBuffers(this)),y.vertexShaderSourceVariant=g.shaderSourceVariant,y.vertexShaderVariantConditionalBlocks=g.conditionalBlocks,y.vertexUniformBindGroup=_.gpuDevice.createBindGroup(getBasicMeshVertexBindGroupDescriptor(this)),this.#wr(i),this.gpuRenderInfo.vertexShaderModule};#Ws=()=>{const{redGPUContext:i}=this,{resourceManager:g}=i;this.#Ks.length=0;const x=g.getGPUBindGroupLayout(ResourceManager.PRESET_VERTEX_GPUBindGroupLayout);this.LODManager.LODList.forEach((v,_)=>{const y={code:v.source},b=g.createGPUShaderModule(v.label,y);this.#Ks[_]={pipeline:createBasePipeline({vertexStateBuffers:v.geometry.gpuRenderInfo.buffers,primitiveState:this.primitiveState,depthStencilState:this.depthStencilState,geometry:v.geometry,material:v.material||this.material,redGPUContext:i,gpuRenderInfo:this.gpuRenderInfo},b,x),vertexUniformBindGroup:i.gpuDevice.createBindGroup(getBasicMeshVertexBindGroupDescriptor({redGPUContext:i,material:v.material||this.material,gpuRenderInfo:{vertexBindGroupLayout:x,vertexUniformBuffer:this.gpuRenderInfo.vertexUniformBuffer}}))}}),this.#Xs=-1};#Ys(i){const{view:g}=i;this.#Ls=this.#Zs(g,this._geometry,this._material),this.dirtyLOD&&(this.#Ws(),this.dirtyLOD=!1),this.#Us.length=0,this.LODManager.LODList.forEach((i,x)=>{this.#Us[x]=this.#Zs(g,i.geometry,i.material||this._material,x)})}#Zs(i,g,x,v=null){const{gpuDevice:_}=this.redGPUContext,{renderViewStateData:y}=i,{vertexBuffer:b,indexBuffer:S}=g,{fragmentUniformBindGroup:w}=x.gpuRenderInfo;this.#Js(g,v);const L=null!==v,k=_.createRenderBundleEncoder({...i.basicRenderBundleEncoderDescriptor,label:this.uuid});L||(this.#As=k,this.#ks[y.viewIndex]=i.systemUniform_Vertex_UniformBindGroup,this.#Gs=w);const{gpuBuffer:H}=b,z=L?this.#Ks[v].pipeline:this.gpuRenderInfo.pipeline,q=L?this.#Ks[v].vertexUniformBindGroup:this.gpuRenderInfo.vertexUniformBindGroup;k.setPipeline(z),k.setVertexBuffer(0,H),this.particleBuffers?.length&&this.particleBuffers.forEach((i,g)=>{k.setVertexBuffer(g+1,i)}),k.setBindGroup(0,i.systemUniform_Vertex_UniformBindGroup),k.setBindGroup(1,q),k.setBindGroup(2,w);let W=this.#Os;if(null!==v&&(W=this.#Vs[v]),S){const{gpuBuffer:i,format:g}=S;k.setIndexBuffer(i,g),k.drawIndexedIndirect(W.buffer,4*W.commandOffset)}else k.drawIndirect(W.buffer,4*W.commandOffset);const be=k.finish({label:`${this.name}_LOD${v||0}`});return be.mesh=null,be}#qs(){this.#Os||(this.#Os=this.#Ns.allocateDrawCommand(this.name))}#Js(i,g=null){const{vertexBuffer:x,indexBuffer:v}=i,_=this.#Ns;let y=this.#Os;if(null!==g&&(this.#Vs[g]||(this.#Vs[g]=this.#Ns.allocateDrawCommand(`${this.name}_LOD${g}`)),y=this.#Vs[g]),this.#qs(),v){const{indexCount:i}=v;this.particleBuffers?_.setIndexedIndirectCommand(y,i,this.particleNum,0,0,0):_.setIndexedIndirectCommand(y,i,1,0,0,0)}else{const{vertexCount:i}=x;_.setIndirectCommand(y,i,1,0,0)}}#wr(i){const{resourceManager:g}=this.redGPUContext,x=this.#Mr(),v=`${i}_${x}`;let _=g.getGPUShaderModule(v);if(!_){let i=this.gpuRenderInfo.vertexShaderSourceVariant.getVariant(x);if(i)if(this.animationInfo?.skinInfo){const y=`${this.animationInfo.skinInfo.joints.length}`;i=i.replaceAll("#JOINT_NUM",y),this.gpuRenderInfo.vertexShaderSourceVariant.getVariant(x),_=g.createGPUShaderModule(`${v}_${y}`,{code:i})}else _=g.createGPUShaderModule(v,{code:i});else console.warn("⚠️ 버텍스 바리안트 소스를 찾을 수 없음:",x),_=this.gpuRenderInfo.vertexShaderModule}this.gpuRenderInfo.vertexShaderModule=_}#Mr(){const{vertexShaderVariantConditionalBlocks:i}=this.gpuRenderInfo,g=new Set;for(const x of i)this[x]&&g.add(x);const x=g.size>0?Array.from(g).sort().join("+"):"none";return g.size,x}}Object.defineProperty(Mesh.prototype,"isInstanceofMesh",{value:!0,writable:!1}),defineBoolean(Mesh,[{key:"receiveShadow",value:!1},{key:"useDisplacementTexture",value:!1},{key:"disableJitter",value:!1}]),Object.freeze(Mesh);class Primitive{static#Qs=new VertexInterleavedStruct({vertexPosition:VertexInterleaveType.float32x3,vertexNormal:VertexInterleaveType.float32x3,texcoord:VertexInterleaveType.float32x2,vertexTangent:VertexInterleaveType.float32x4},"primitiveInterleaveStruct");#eo;#On;#Vn;#Nn;constructor(i,g,x){validateRedGPUContext(i);const v=i.resourceManager.cachedBufferState;let _=v[g];_||(_=v[g]=x()),this.#to(_)}static get primitiveInterleaveStruct(){return this.#Qs}get gpuRenderInfo(){return this.#eo}get vertexBuffer(){return this.#On}get indexBuffer(){return this.#Vn}get volume(){return this.#Nn||(this.#Nn=calculateGeometryAABB(this.#On)),this.#Nn}static generateUniqueKey(i,g){let x="PRIMITIVE_"+i.toUpperCase();for(const i in g){const v=g[i];void 0!==v&&(x+="_"+i.toUpperCase()+v)}return x}#to(i){if(this.#On=i.vertexBuffer,this.#Vn=i.indexBuffer,this.#On){const{interleavedStruct:i}=this.#On;this.#eo=new GeometryGPURenderInfo([{arrayStride:i.arrayStride,attributes:i.attributes}])}}}Object.freeze(Primitive);const calculateTangentsInterleaved=(i,g,x,v,_,y,b)=>{const S=1e-6,w=i.length/x,L=g.length>0,k=L?g.length/3:w/3,H=new Float32Array(3*w),z=new Float32Array(3*w);for(let _=0;_{const _=i.length/3,y=new Float32Array(12*_);for(let v=0;v<_;v++){const _=12*v;y[_]=i[3*v],y[_+1]=i[3*v+1],y[_+2]=i[3*v+2],y[_+3]=g[3*v],y[_+4]=g[3*v+1],y[_+5]=g[3*v+2],y[_+6]=x[2*v],y[_+7]=x[2*v+1]}calculateTangentsInterleaved(y,v,12,0,3,6,8);const b=new Float32Array(4*_);for(let i=0;i<_;i++){const g=12*i,x=4*i;b[x]=y[g+8],b[x+1]=y[g+9],b[x+2]=y[g+10],b[x+3]=y[g+11]}return b};class ResourceStateIndexBuffer{static dirtyList=[];buffer;label;uuid;#jt=0;constructor(i){this.buffer=i,this.label=i.name,this.uuid=i.uuid}get useNum(){return this.#jt}set useNum(i){this.#jt=i,ResourceStateIndexBuffer.dirtyList.push(this)}}class IndexBuffer extends ABaseBuffer{[Ar];#ro=0;#qn=0;#z=en.UINT32;constructor(i,g,x=GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST,v=""){super(i,"managedIndexBufferState",x);const{table:_}=this.targetResourceManagedState,y=_.get(v);if(y)return y.buffer;v&&(this.name=v,this[kr]=v),this.changeData(g),this.redGPUContext.resourceManager.registerManagementResource(this,new ResourceStateIndexBuffer(this))}get format(){return this.#z}get triangleCount(){return this.#qn}get indexCount(){return this.#ro}get data(){return this[Ar]}changeData(i){const{gpuDevice:g}=this;Array.isArray(i)&&(i=new Uint32Array(i)),this[Ir]&&(this.targetResourceManagedState.videoMemory-=this[Ar].byteLength||0,this.redGPUContext.commandEncoderManager.addDeferredDestroy(this[Ir]),this[Ir]=null),this[Ar]=i,this.#ro=i.length;const x={size:this[Ar].byteLength,usage:this.usage,label:this.name};this[Ir]=g.createBuffer(x),this.targetResourceManagedState.videoMemory+=this[Ar].byteLength||0,this.#qn=this.#ro/3,g.queue.writeBuffer(this[Ir],0,this[Ar])}}Object.freeze(IndexBuffer);const createPrimitiveGeometry=(i,g,x,v)=>new Geometry(i,new VertexBuffer(i,new Float32Array(g),Primitive.primitiveInterleaveStruct,void 0,`VertexBuffer_${v}`),new IndexBuffer(i,new Uint32Array(x),void 0,`IndexBuffer_${v}`));class PrimitiveUtils{static#io={x:1,y:0,z:0};static#no={x:0,y:0,z:-1};static#ao={x:0,y:0,z:0};static#so={x:0,y:1,z:0};static#oo={x:0,y:-1,z:0};static#uo={x:0,y:0,z:0};static#lo={x:0,y:0,z:0};static#co={x:0,y:0,z:0};static#ho={x:0,y:0,z:0};static#fo={x:0,y:0,z:0};static#do={x:0,y:0,z:0};static#mo={x:0,y:0,z:0};static#po={x:0,y:0,z:0};static#go={x:0,y:0,z:0};static#xo={x:0,y:0,z:0};static get#vo(){return Primitive.primitiveInterleaveStruct.arrayStride/4}static finalize(i,g,x,v){return this.calculateTangents(g,x),createPrimitiveGeometry(i,g,x,v)}static generateGrid(i,g,x,v,_,y=!1,b=!1){const S=i.length/this.#vo;for(let i=0;i<=v;i++){const g=i/v;for(let v=0;v<=x;v++)_(v/x,g,v,i)}!y&&g&&this.generateGridIndices(g,S,x,v,x+1,b)}static getEmptyGeometry(i,g){const x=[];return this.interleavePacker(x,0,0,0,0,1,0,0,0),createPrimitiveGeometry(i,x,[],g)}static generateBoxData(i,g,x,v,_,y,b,S){return this.generateRoundedBoxData(i,g,x,v,_,y,b,0,0,S)}static generateRoundedBoxData(i,g,x,v,_,y,b,S,w,L){const k=[],H=[],z=g/2,q=x/2,W=v/2,be=Math.min(S,z,q,W),je=be>0?{w:g,h:x,d:v,r:be}:null;return this.generatePlaneData(k,H,v,x,b,y,{x:z,y:0,z:0},{x:0,y:0,z:-1},{x:0,y:-1,z:0},{x:1,y:0,z:0},be,w,je),this.generatePlaneData(k,H,v,x,b,y,{x:-z,y:0,z:0},{x:0,y:0,z:1},{x:0,y:-1,z:0},{x:-1,y:0,z:0},be,w,je),this.generatePlaneData(k,H,g,v,_,b,{x:0,y:q,z:0},{x:1,y:0,z:0},{x:0,y:0,z:1},{x:0,y:1,z:0},be,w,je),this.generatePlaneData(k,H,g,v,_,b,{x:0,y:-q,z:0},{x:1,y:0,z:0},{x:0,y:0,z:-1},{x:0,y:-1,z:0},be,w,je),this.generatePlaneData(k,H,g,x,_,y,{x:0,y:0,z:W},{x:1,y:0,z:0},{x:0,y:-1,z:0},{x:0,y:0,z:1},be,w,je),this.generatePlaneData(k,H,g,x,_,y,{x:0,y:0,z:-W},{x:-1,y:0,z:0},{x:0,y:-1,z:0},{x:0,y:0,z:-1},be,w,je),this.finalize(i,k,H,L)}static generatePlaneData(i,g,x,v,_,y,b,S,w,L,k=0,H=0,z=null,q=!1){const W=i.length/this.#vo,be=_+2*H,je=y+2*H,getCoordInfo=(i,g,x,v,_)=>{if(x<=0||v<=0){const x=i/_;return{pos:(x-.5)*g,norm:0,uv:x}}const y=g/2-x,b=Math.PI/2*x,S=2*b+2*y;if(i<=v){const g=i/v,_=(1-g)*Math.PI/2;return{pos:-y-Math.sin(_)*x,norm:-Math.sin(_),uv:g*b/S}}if(i<=v+_){const g=(i-v)/_;return{pos:g*(2*y)-y,norm:0,uv:(b+g*(2*y))/S}}{const g=(i-v-_)/v,w=g*Math.PI/2;return{pos:y+Math.sin(w)*x,norm:Math.sin(w),uv:(b+2*y+g*b)/S}}};for(let g=0;g<=je;g++){const W=getCoordInfo(g,v,k,H,y),je=q?1-W.uv:W.uv;for(let g=0;g<=be;g++){const v=getCoordInfo(g,x,k,H,_);let y=b.x+v.pos*S.x+W.pos*w.x,q=b.y+v.pos*S.y+W.pos*w.y,be=b.z+v.pos*S.z+W.pos*w.z,Ke=L.x,Xe=L.y,Ye=L.z;if(z){const{w:i,h:g,d:x,r:v}=z,_=i/2-v,b=g/2-v,S=x/2-v,w=Math.max(-_,Math.min(y,_)),L=Math.max(-b,Math.min(q,b)),k=Math.max(-S,Math.min(be,S)),H=y-w,W=q-L,je=be-k,Ze=Math.sqrt(H*H+W*W+je*je)||1e-6;Ke=H/Ze,Xe=W/Ze,Ye=je/Ze,y=w+Ke*v,q=L+Xe*v,be=k+Ye*v}this.interleavePacker(i,y,q,be,Ke,Xe,Ye,v.uv,je)}}this.generateGridIndices(g,W,be,je,be+1)}static generateSphereData(i,g,x,v,_,y,b,S,w){const L=[],k=[];return g<=0||Math.abs(y)<1e-6||Math.abs(S)<1e-6?this.getEmptyGeometry(i,w):(this.generateSphericalData(L,k,g,x,v,_,y,b,S),this.finalize(i,L,k,w))}static generateCylinderData(i,g,x,v,_,y,b,S,w,L,k,H,z){const q=[],W=[],be=v/2;return g<=0&&x<=0||v<=0||Math.abs(L)<1e-6?this.getEmptyGeometry(i,z):(this.generateCylinderTorsoData(q,W,g,x,v,_,y,w,L,this.#ao,this.#io,this.#no),b&&g>0&&this.generateRingData(q,W,0,g,_,1,w,L,{x:0,y:be,z:0},this.#io,this.#no,this.#so,!0,k),S&&x>0&&this.generateRingData(q,W,0,x,_,1,w,L,{x:0,y:-be,z:0},this.#io,this.#no,this.#oo,!1,H),this.finalize(i,q,W,z))}static generateConeData(i,g,x,v,_,y,b,S,w){return this.generateCylinderData(i,0,g,x,v,_,!1,y,b,S,!1,!1,w)}static generatePlaneEntryData(i,g,x,v,_,y,b){const S=[],w=[];return g<=0||x<=0?this.getEmptyGeometry(i,b):(this.generatePlaneData(S,w,g,x,v,_,this.#ao,this.#io,{x:0,y:-1,z:0},{x:0,y:0,z:1},0,0,null,y),this.finalize(i,S,w,b))}static generateGroundData(i,g,x,v,_,y,b){const S=[],w=[];return g<=0||x<=0?this.getEmptyGeometry(i,b):(this.generatePlaneData(S,w,g,x,v,_,this.#ao,this.#io,{x:0,y:0,z:1},this.#so,0,0,null,y),this.finalize(i,S,w,b))}static generateCircleEntryData(i,g,x,v,_,y,b){const S=[],w=[];return g<=0||Math.abs(_)<1e-6?this.getEmptyGeometry(i,b):(this.generateRingData(S,w,0,g,x,1,v,_,this.#ao,this.#io,this.#no,this.#so,!0,y),this.finalize(i,S,w,b))}static generateRingEntryData(i,g,x,v,_,y,b,S,w){const L=[],k=[];return x<=0||Math.abs(b)<1e-6?this.getEmptyGeometry(i,w):(this.generateRingData(L,k,g,x,v,_,y,b,this.#ao,this.#io,this.#no,this.#so,!0,S),this.finalize(i,L,k,w))}static generateTorusData(i,g,x,v,_,y,b,S,w,L,k,H){const z=[],q=[],W=Math.abs(b)<2*Math.PI;if(this.generateGrid(z,q,v,_,(i,v)=>{const _=y+i*b,S=v*Math.PI*2,w=this.#uo,L=this.#lo,k=this.#co,H=this.#ho,q=this.#fo;this.#_o(this.#ao,1,_,this.#io,this.#no,w),this.#yo(L,w.x*g,0,w.z*g),this.#yo(k,-w.x,0,-w.z),this.#_o(L,x,S,k,this.#so,H),this.#_o(this.#ao,1,S,k,this.#so,q),this.interleavePacker(z,H.x,H.y,H.z,q.x,q.y,q.z,i,v)}),W){const i=this.#io,v=this.#no,H=this.#so,W=this.#uo,be=this.#lo,je=this.#co;if(S&&(this.#_o(this.#ao,g,y,i,v,W),this.#_o(this.#ao,1,y,i,v,be),this.#yo(je,Math.cos(y),0,-Math.sin(y)),this.generateRingData(z,q,0,x,_,1,0,2*Math.PI,W,be,H,je,!0,L)),w){const S=y+b;this.#_o(this.#ao,g,S,i,v,W),this.#_o(this.#ao,1,S,i,v,be),this.#yo(je,-Math.cos(S),0,Math.sin(S)),this.generateRingData(z,q,0,x,_,1,0,2*Math.PI,W,be,H,je,!1,k)}}return this.finalize(i,z,q,H)}static generateTorusKnotData(i,g,x,v,_,y,b,S){const w=[],L=[];return this.generateGrid(w,L,_,v,(i,v)=>{const _=v*y*Math.PI*2,S=this.#uo,L=this.#lo,k=this.#co,H=this.#ho,z=this.#fo,q=this.#do,W=this.#mo,be=this.#po,je=this.#go;this.#bo(_,y,b,g,S),this.#bo(_+.01,y,b,g,L),this.#yo(k,L.x-S.x,L.y-S.y,L.z-S.z),this.#yo(H,L.x+S.x,L.y+S.y,L.z+S.z),this.#So(k,H,z),this.#To(z),this.#So(z,k,H),this.#To(H);const Ke=i*Math.PI*2;this.#yo(be,-z.x,-z.y,-z.z),this.#yo(je,-H.x,-H.y,-H.z),this.#_o(S,x,Ke,be,je,q),this.#_o(this.#ao,1,Ke,be,je,W),this.interleavePacker(w,q.x,q.y,q.z,W.x,W.y,W.z,v,i)}),this.finalize(i,w,L,S)}static generateRingData(i,g,x,v,_,y,b,S,w,L,k,H,z=!0,q=!1,W=0,be=1){if(v<=1e-6||Math.abs(S)<1e-6)return void this.interleavePacker(i,w.x,w.y,w.z,H.x,H.y,H.z,.5,.5);const je=this.#xo;this.generateGrid(i,g,_,y,(g,_)=>{const y=x+_*(v-x),z=b+g*S,Ke=W+_*(be-W);this.#_o(w,y,z,L,k,je);const Xe=q?g:.5-y/v*Math.sin(z)*.5,Ye=q?Ke:.5-y/v*Math.cos(z)*.5;this.interleavePacker(i,je.x,je.y,je.z,H.x,H.y,H.z,Xe,Ye)},!1,!z)}static generateSphericalData(i,g,x,v,_,y,b,S,w,L=0,k=0,H=1){this.generateGrid(i,g,v,_,(g,v)=>{const _=S+v*w,z=y+g*b,q=Math.sin(_),W=Math.cos(_),be=Math.sin(z),je=Math.cos(z),Ke=k+v*(H-k),Xe=-be*q,Ye=W,Ze=-je*q;this.interleavePacker(i,x*Xe,x*Ye+L,x*Ze,Xe,Ye,Ze,g,Ke)},null===g)}static generateCylinderTorsoData(i,g,x,v,_,y,b,S,w,L,k,H,z={x:0,y:1,z:0},q=!1,W=0,be=1){const je=_/2,Ke=(v-x)/_;if(0===w||x<=0&&v<=0)return void this.interleavePacker(i,L.x,L.y,L.z,0,1,0,0,0);const Xe=this.#uo,Ye=this.#lo,Ze=this.#co;this.generateGrid(i,g,y,b,(g,y)=>{const b=y*(v-x)+x,q=g*w+S,Je=je-y*_,Qe=W+y*(be-W);this.#_o({x:0,y:0,z:0},b,q,k,H,Xe),this.#_o({x:0,y:0,z:0},1,q,k,H,Ye);const et=L.x+Xe.x+Je*z.x,tt=L.y+Xe.y+Je*z.y,it=L.z+Xe.z+Je*z.z;this.#yo(Ze,Ye.x+Ke*z.x,Ye.y+Ke*z.y,Ye.z+Ke*z.z),this.#To(Ze),this.interleavePacker(i,et,tt,it,Ze.x,Ze.y,Ze.z,g,Qe)},q)}static generateCapsuleData(i,g,x,v,_,y,b){const S=[],w=[],L=v+1,k=x/2,H=Math.PI/2*g,z=2*H+x,q=H/z,W=(H+x)/z;return this.generateSphericalData(S,null,g,v,y,0,2*Math.PI,0,Math.PI/2,k,0,q),this.generateCylinderTorsoData(S,null,g,g,x,v,_,0,2*Math.PI,this.#ao,this.#io,this.#no,this.#so,!0,q,W),this.generateSphericalData(S,null,g,v,y,0,2*Math.PI,Math.PI/2,Math.PI/2,-k,W,1),this.generateGridIndices(w,0,v,2*y+_,L),this.finalize(i,S,w,b)}static generateGridIndices(i,g,x,v,_,y=!1){for(let b=0;bPrimitiveUtils.generatePlaneEntryData(i,g,x,v,_,y,b))}}class ResourceStateBitmapTexture{texture;src;cacheKey;useNum=0;uuid;constructor(i){this.texture=i,this.src=i.src,this.cacheKey=i.cacheKey,this.useNum=0,this.uuid=i.uuid}}class BitmapTexture extends ManagementResourceBase{#V;#wo;#$;#K;#Mo;#H=0;#Po=!0;#z;#q;#Y;constructor(i,g,x=!0,v,_,y,b=!1){if(super(i,"managedBitmapTextureState"),this.#q=v,this.#Y=_,this.#Po=b,this.#K=x,this.#z=y||`${navigator.gpu.getPreferredCanvasFormat()}-srgb`,g){this.#wo=this.#W(g),this.cacheKey=this.#Z(g);const{table:i}=this.targetResourceManagedState;let x=i.get(this.cacheKey);if(x){const i=x.texture;return this.#q?.(i),i}this.src=g,this.#J()}}get width(){return this.#Mo?.width||0}get height(){return this.#Mo?.height||0}get usePremultiplyAlpha(){return this.#Po}get videoMemorySize(){return this.#H}get gpuTexture(){return this.#V}get mipLevelCount(){return this.#$}get src(){return this.#wo}set src(i){this.#wo=this.#W(i),this.cacheKey=this.#Z(i),this.#wo&&this.#Q(this.#wo)}get useMipmap(){return this.#K}set useMipmap(i){this.#K=i,this.#ee()}destroy(){const i=this.#V;this.#te(null),this.notifyUpdate(!0),this.#re(),this.cacheKey=null,this.#wo=null,i&&this.redGPUContext.commandEncoderManager.addDeferredDestroy(i)}#Z(i){return i?"string"==typeof i?getAbsoluteURL(window.location.href,i):i.cacheKey||getAbsoluteURL(window.location.href,i.src):this.uuid}#W(i){return"string"==typeof i?i:i.src}#te(i){this.#V=i,i||(this.#Mo=null),this.notifyUpdate()}#J(){this.redGPUContext.resourceManager.registerManagementResource(this,new ResourceStateBitmapTexture(this))}#re(){this.redGPUContext.resourceManager.unregisterManagementResource(this)}#ee(){const{gpuDevice:i,resourceManager:g}=this.redGPUContext,{mipmapGenerator:x}=g;this.#V&&(this.redGPUContext.commandEncoderManager.addDeferredDestroy(this.#V),this.#V=null),this.targetResourceManagedState.videoMemory-=this.#H,this.#H=0;const{width:v,height:_}=this.#Mo;this.#$=1;const y={size:[v,_],format:this.#z,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC,label:this.#wo};this.#K&&(this.#$=getMipLevelCount(v,_),y.mipLevelCount=this.#$,y.usage|=GPUTextureUsage.RENDER_ATTACHMENT);const b=imageBitmapToGPUTexture(i,[this.#Mo],y,this.#Po);this.#H=calculateTextureByteSize(b),this.targetResourceManagedState.videoMemory+=this.#H,this.#K&&x.generateMipmap(b,y),this.#te(b)}async#Ro(i){return new Promise((g,x)=>{const v=new Image;v.src=i,v.onload=()=>{const i=document.createElement("canvas");i.width=v.width||512,i.height=v.height||512;const _=i.getContext("2d");_?(_.fillStyle="rgba(0, 0, 0, 0)",_.fillRect(0,0,i.width,i.height),_.drawImage(v,0,0,i.width,i.height),createImageBitmap(i,{colorSpaceConversion:"none",premultiplyAlpha:this.#Po?"premultiply":"none"}).then(g).catch(x)):x(new Error("Canvas context could not be created."))},v.onerror=i=>{x(new Error(`Failed to load SVG: ${i}`))}})}async#Q(i){try{i.endsWith(".svg")?this.#Mo=await this.#Ro(i):this.#Mo=await loadAndCreateBitmapImage(i,"none",this.#Po?"premultiply":"none"),this.#ee(),this.#q?.(this)}catch(i){console.error(i),this.#Y?.(i)}}}Object.freeze(BitmapTexture);const En=parseWGSL("TEXTFIELD_MATERIAL","#redgpu_include SYSTEM_UNIFORM;#redgpu_include color.getTintBlendMode;#redgpu_include entryPoint.mesh.entryPointPickingFragment;#redgpu_include systemStruct.OutputFragment;struct Uniforms{useDiffuseTexture:u32,opacity:f32,useTint:u32,tint:vec4,tintBlendMode:u32,};@group(2)@binding(0)varuniforms:Uniforms;@group(2)@binding(1)var diffuseTextureSampler:sampler;@group(2)@binding(2)var diffuseTexture:texture_2d;struct InputData{@builtin(position)position:vec4,@location(0)vertexPosition:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,@location(11)combinedOpacity:f32,@location(13)shadowCoord:vec3,@location(15)@interpolate(flat)pickingId:vec4,};@fragment fn main(inputData:InputData)->OutputFragment{var output:OutputFragment;var finalColor:vec4=textureSample(diffuseTexture,diffuseTextureSampler,inputData.uv);finalColor=vec4(finalColor.rgb/finalColor.a,finalColor.a*uniforms.opacity*inputData.combinedOpacity);#redgpu_if useTint finalColor=getTintBlendMode(finalColor,uniforms.tintBlendMode,uniforms.tint);#redgpu_endIf if(finalColor.a==.0){discard;}output.color=vec4(finalColor.rgb,finalColor.a);output.gBufferMotionVector=vec4(.0,.0,1.0,1.0);return output;};");class TextFieldMaterial extends ABitmapBaseMaterial{constructor(i,g,x){super(i,"TEXT_FIELD_MATERIAL",En,2),x&&(this.name=x),this.diffuseTexture=g,this.diffuseTextureSampler=new Sampler(this.redGPUContext),this.initGPURenderInfos()}}defineSampler(TextFieldMaterial,[{key:"diffuseTextureSampler"}]),defineTexture(TextFieldMaterial,[{key:"diffuseTexture"}]),Object.freeze(TextFieldMaterial);const In=";box-sizing:content-box;white-space:nowrap;",An={padding:0,background:"transparent",color:"#fff",fontFamily:"Arial",fontSize:24,fontWeight:"normal",fontStyle:"normal",letterSpacing:0,wordBreak:"keep-all",verticalAlign:"middle",textAlign:"center",borderRadius:0,lineHeight:1.4,border:"",boxShadow:"none",boxSizing:"border-box",filter:""};class ATextField extends Mesh{#Co;#Bo;#Do;#Eo;#Io;#Ao;#Lo;#Uo=!0;#h;#ko;#Go=!1;#Oo=1;#Vo=1;constructor(i,g,x=!0){super(i),this.#h=i,this.#Uo=x,this.#Lo=g,this._material=new TextFieldMaterial(i),this._material.transparent=!0,this._material.diffuseTextureSampler=new Sampler(i,x?{minFilter:_.LINEAR,magFilter:_.LINEAR,mipmapFilter:y.LINEAR}:{minFilter:_.NEAREST,magFilter:_.NEAREST,mipmapFilter:null}),this.depthStencilState.depthWriteEnabled=!1,this.#No(),this.#Fo(),this.#Ho(),this.#zo(),this.#$o()}get text(){return this.#Ao}set text(i){if(this.#Ao===i)return;this.#Ao=i;const g=this.#Do.querySelector("foreignObject div"),x=this.#jo(i);this.#Eo.innerHTML=x,g.innerHTML=x,this.#Go=!0}render(i){this.#Lo(this.#Oo,this.#Vo),this.#Ko(),super.render(i)}#jo(i){return i.toString().replace(/\/gi,"
")}#No(){"undefined"!=typeof OffscreenCanvas?this.#Co=new OffscreenCanvas(100,100):this.#Co=document.createElement("canvas"),this.#Bo=this.#Co.getContext("2d")}#Xo(){const i=this.#Eo.getBoundingClientRect();const g=i.width+3+3,x=i.height+3+3;return{width:-2&Math.ceil(g),height:-2&Math.ceil(x),extraTop:3,extraRight:3,extraBottom:3,extraLeft:3}}#qo(){const i=this.#Do,g=i.querySelector("foreignObject"),{width:x,height:v,extraTop:_,extraRight:y,extraBottom:b,extraLeft:S}=this.#Xo();g.setAttribute("width",x.toString()),g.setAttribute("height",v.toString()),g.style.padding=`${_}px ${y}px ${b}px ${S}px`,i.setAttribute("width",x.toString()),i.setAttribute("height",v.toString()),this.#Io.src="data:image/svg+xml;charset=utf-8,"+encodeURIComponent(i.outerHTML)}#zo(){this.#Io=new Image,this.#Io.style.cssText="position:absolute;bottom:0px;left:0;",this.#Io.onload=i=>{let g,x;const{width:v,height:_}=this.#Xo(),y=1===window.devicePixelRatio?2:window.devicePixelRatio;g=v*y,x=_*y,this.#Io.width=v,this.#Io.height=_,this.#Co.width=g,this.#Co.height=x,this.#Co instanceof OffscreenCanvas||(this.#Co.style.width=`${v}px`,this.#Co.style.height=`${_}px`),this.#Bo.imageSmoothingEnabled=!0,this.#Bo.imageSmoothingQuality="high",this.#Bo.clearRect(0,0,g,x),this.#Bo.fillStyle="rgba(0, 0, 0, 0)",this.#Bo.fillRect(0,0,g,x),this.#Bo.drawImage(this.#Io,0,0,g,x),this.dirtyTransform=!0;const callback=i=>{if(this.material.diffuseTexture){const i=this.material.diffuseTexture.src,g="string"==typeof i&&i?.startsWith?.("blob:");this.material.diffuseTexture.destroy(),this.material.diffuseTexture=null,g&&URL.revokeObjectURL(i)}this.material.diffuseTexture=new BitmapTexture(this.#h,URL.createObjectURL(i),!0,()=>{this.#Oo=v,this.#Vo=_},null,null,!0)};this.#Co instanceof OffscreenCanvas?this.#Co.convertToBlob({type:"image/png"}).then(callback):this.#Co.toBlob(callback,"image/png")}}#Ko(){this.#Go&&(this.#ko&&cancelAnimationFrame(this.#ko),this.#ko=requestAnimationFrame(()=>{this.#qo()})),this.#Go=!1}#Yo=(i,g)=>{const x=this.#Do.querySelector("foreignObject > div").style,v=this.#Eo.style,_=`_${i}`;this[_]=g,Object.defineProperty(this,i,{get:()=>this[_],set:g=>{const y=this[_];this[_]=g;const b=(i=>"number"==typeof i)(g)&&(i=>!["lineHeight","fontWeight"].includes(i))(i)?`${g}px`:g;x[i]=b,v[i]=b,y!==g&&(this.#Go=!0)},configurable:!0}),this[i]=g};#Fo(){this.#Eo=document.createElement("div"),this.#Eo.style.cssText=In+";position:absolute;top:200px;left:0;visibility:hidden;text-rendering:optimizeLegibility",document.body.appendChild(this.#Eo)}#Ho(){const i=this.#Do=document.createElementNS("http://www.w3.org/2000/svg","svg");i.setAttribute("xmlns","http://www.w3.org/2000/svg"),i.setAttribute("text-rendering","optimizeLegibility"),i.style.cssText="position:absolute;top:0px;left:0px;z-index:1;margin:0;padding:0;overflow:visible;background:transparent",i.innerHTML=`\n \n \n\t\t\t
\n\t\t\t
`}#$o(){for(const[i,g]of Object.entries(An))this.#Yo(i,g);this.#Go=!0}}Object.freeze(ATextField);var Ln="#redgpu_include SYSTEM_UNIFORM;#redgpu_include math.billboard.getBillboardMatrix;#redgpu_include math.billboard.getBillboardResult;#redgpu_include entryPoint.billboard.entryPointPickingVertex;#redgpu_include entryPoint.empty.entryPointShadowVertex;struct MatrixList{modelMatrix:mat4x4,normalModelMatrix:mat4x4,}struct VertexUniforms{pickingId:u32,matrixList:MatrixList,normalModelMatrix:mat4x4,useSizeAttenuation:u32,useBillboard:u32,usePixelSize:u32,pixelSize:f32,_renderRatioX:f32,_renderRatioY:f32,combinedOpacity:f32,};@group(1)@binding(0)varvertexUniforms:VertexUniforms;struct InputData{@location(0)position:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,};struct VertexOutput{@builtin(position)position:vec4,@location(0)vertexPosition:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,@location(11)combinedOpacity:f32,@location(13)shadowCoord:vec3,@location(15)@interpolate(flat)pickingId:vec4,};@vertex fn main(inputData:InputData)->VertexOutput{var output:VertexOutput;let billboardResult=getBillboardResult(inputData.position,inputData.vertexNormal,vertexUniforms.matrixList.modelMatrix,systemUniforms.camera.viewMatrix,systemUniforms.projection.noneJitterProjectionMatrix,systemUniforms.resolution,vertexUniforms.useBillboard,vertexUniforms.usePixelSize,vertexUniforms.pixelSize,vertexUniforms._renderRatioX,vertexUniforms._renderRatioY);output.position=billboardResult.position;output.vertexPosition=billboardResult.vertexPosition;output.vertexNormal=billboardResult.vertexNormal;output.uv=inputData.uv;output.combinedOpacity=vertexUniforms.combinedOpacity;return output;}";const Un=parseWGSL("TEXTFIELD3D_VERTEX",Ln),kn=Un.uniforms.vertexUniforms;class TextField3D extends ATextField{#Wo=1;#Zo=1;#Jo=1;#Qo=!1;constructor(i,g){super(i,(i,g)=>{i&&g&&(i===this.#Wo&&g===this.#Zo||(this.#Wo=i,this.#Zo=g,this.gpuRenderInfo&&this.redGPUContext.gpuDevice.queue.writeBuffer(this.gpuRenderInfo.vertexUniformBuffer.gpuBuffer,this.gpuRenderInfo.vertexUniformInfo.members.pixelSize.uniformOffset,new Float32Array([g*window.devicePixelRatio])),this.#eu()))}),this._geometry=new Plane(i),this.disableJitter=!0,g&&(this.text=g)}get worldSize(){return this.#Jo}set worldSize(i){this.#Jo!==i&&(this.#Jo=i,this.#eu())}get usePixelSize(){return this.#Qo}set usePixelSize(i){if(this.gpuRenderInfo){const{vertexUniformBuffer:g,vertexUniformInfo:x}=this.gpuRenderInfo;this.redGPUContext.gpuDevice.queue.writeBuffer(g.gpuBuffer,x.members.usePixelSize.uniformOffset,new Uint32Array([i?1:0])),this.redGPUContext.gpuDevice.queue.writeBuffer(g.gpuBuffer,x.members.pixelSize.uniformOffset,new Float32Array([this.#Zo*window.devicePixelRatio]))}this.#Qo!==i&&(this.#Qo=i,this.#eu())}get pixelSize(){return this.#Zo}get geometry(){return this._geometry}set geometry(i){console.error("TextField3D can not change geometry")}get material(){return this._material}set material(i){console.error("TextField3D can not change material")}render(i){super.render(i)}createCustomMeshVertexShaderModule=()=>this.createMeshVertexShaderModuleBASIC("VERTEX_MODULE_TEXT_FIELD_3D",Un,kn,Ln);#eu(){if(this.#Zo){const i=this._renderRatioX,g=this._renderRatioY;this.usePixelSize?(this._renderRatioY=1,this._renderRatioX=this.#Wo/this.#Zo):(this._renderRatioY=this.#Jo,this._renderRatioX=this.#Wo/this.#Zo*this.#Jo),i===this._renderRatioX&&g===this._renderRatioY||(this.dirtyTransform=!0)}}}definePositiveNumber(TextField3D,[{key:"_renderRatioX",value:1},{key:"_renderRatioY",value:1}]),defineBoolean(TextField3D,[{key:"useBillboard",value:!0}]),Object.freeze(TextField3D);class ADrawDebuggerLight{#tu;#ru;#ga;#iu;constructor(i,g,x,v,_=32){this.#ga=g;const y=this.#nu(i,_);this.#tu=new ColorMaterial(i,convertRgbToHex(v[0],v[1],v[2])),this.#ru=new Mesh(i,y,this.#tu);const{primitiveState:b}=this.#ru;b.cullMode="none",b.topology=Ei.LINE_LIST,this.#iu=new TextField3D(i),this.#iu.usePixelSize=!0,this.#iu.fontSize=40,this.#iu.text=x,this.#ru.addChild(this.#iu)}get target(){return this.#ga}get label(){return this.#iu}get lightDebugMesh(){return this.#ru}updateVertexBuffer(i,g){const x=g.data;let v=0;const _=Math.min(i.length,Math.floor(x.length/24));for(let g=0;g<_;g++){const[_,y]=i[g];x[v++]=_[0],x[v++]=_[1],x[v++]=_[2],x[v++]=0,x[v++]=0,x[v++]=1,x[v++]=0,x[v++]=0,x[v++]=1,x[v++]=0,x[v++]=0,x[v++]=1,x[v++]=y[0],x[v++]=y[1],x[v++]=y[2],x[v++]=0,x[v++]=0,x[v++]=1,x[v++]=0,x[v++]=0,x[v++]=1,x[v++]=0,x[v++]=0,x[v++]=1}g.updateAllData(x)}#nu(i,g){const x=new Float32Array(2*g*12),v=new VertexInterleavedStruct({vertexPosition:VertexInterleaveType.float32x3,vertexNormal:VertexInterleaveType.float32x3,texcoord:VertexInterleaveType.float32x2,vertexTangent:VertexInterleaveType.float32x4},`lightDebugStruct_${Math.random()}`),_=new VertexBuffer(i,x,v);return new Geometry(i,_)}}Object.freeze(ADrawDebuggerLight);class DrawDebuggerDirectionalLight extends ADrawDebuggerLight{#au=[0,10,0];constructor(i,g){super(i,g,"☀️",[255,255,0],8)}render(i){const{lightDebugMesh:g,label:x,target:v}=this;if(!i.view.systemUniform_Vertex_UniformBindGroup)return;if(!v.enableDebugger)return;this.#su(v,g.geometry.vertexBuffer),g.render(i);const{direction:_}=v,y=this.#au,b=Math.sqrt(_[0]*_[0]+_[1]*_[1]+_[2]*_[2]),S=[_[0]/b,_[1]/b,_[2]/b];x.setPosition(y[0]-0*S[0],y[1]-0*S[1],y[2]-0*S[2])}#su(i,g){const x=this.#au,v=i.direction||[0,-1,0],_=Math.sqrt(v[0]*v[0]+v[1]*v[1]+v[2]*v[2]),y=[v[0]/_,v[1]/_,v[2]/_],b=[x[0]+3*y[0],x[1]+3*y[1],x[2]+3*y[2]],S=.3;let w=[0,1,0];Math.abs(y[1])>.99&&(w=[1,0,0]);const L=[y[1]*w[2]-y[2]*w[1],y[2]*w[0]-y[0]*w[2],y[0]*w[1]-y[1]*w[0]],k=Math.sqrt(L[0]*L[0]+L[1]*L[1]+L[2]*L[2]),H=[L[0]/k,L[1]/k,L[2]/k],z=[H[1]*y[2]-H[2]*y[1],H[2]*y[0]-H[0]*y[2],H[0]*y[1]-H[1]*y[0]],q=[[x,b],[b,[b[0]+-.5*y[0]+H[0]*S,b[1]+-.5*y[1]+H[1]*S,b[2]+-.5*y[2]+H[2]*S]],[b,[b[0]+-.5*y[0]-H[0]*S,b[1]+-.5*y[1]-H[1]*S,b[2]+-.5*y[2]-H[2]*S]],[b,[b[0]+-.5*y[0]+z[0]*S,b[1]+-.5*y[1]+z[1]*S,b[2]+-.5*y[2]+z[2]*S]],[b,[b[0]+-.5*y[0]-z[0]*S,b[1]+-.5*y[1]-z[1]*S,b[2]+-.5*y[2]-z[2]*S]],[[x[0]-.3,x[1],x[2]],[x[0]+.3,x[1],x[2]]],[[x[0],x[1]-.3,x[2]],[x[0],x[1]+.3,x[2]]],[[x[0],x[1],x[2]-.3],[x[0],x[1],x[2]+.3]]];this.updateVertexBuffer(q,g)}}Object.freeze(DrawDebuggerDirectionalLight);class PickingEvent{pickingId;mouseX;mouseY;target;time;type;movementX=0;movementY=0;point=create$3();distance=0;localPoint=create$3();localX=0;localY=0;localZ=0;uv=create();ray;faceIndex=-1;altKey=!1;ctrlKey=!1;shiftKey=!1;constructor(i,g,x,v,_,y,b,S){this.pickingId=i,this.mouseX=g,this.mouseY=x,this.target=v,this.time=_,this.type=y,this.altKey=b.altKey,this.ctrlKey=b.ctrlKey,this.shiftKey=b.shiftKey,S&&(this.point=S.point,this.localPoint=S.localPoint,this.localX=S.localPoint[0],this.localY=S.localPoint[1],this.localZ=S.localPoint[2],this.distance=S.distance,this.faceIndex=S.faceIndex,this.uv=S.uv,this.ray=S.ray)}}Object.freeze(PickingEvent);class Ray{origin;direction;constructor(i=create$3(),g=fromValues$3(0,0,-1)){this.origin=clone$3(i),this.direction=clone$3(g)}clone(){return new Ray(this.origin,this.direction)}applyMatrix4(i){transformMat4$2(this.origin,this.origin,i);const g=create$3();copy$3(g,this.direction);const x=clone$4(i);return x[12]=x[13]=x[14]=0,transformMat4$2(this.direction,g,x),normalize$3(this.direction,this.direction),this}intersectBox(i){let g=-1/0,x=1/0;for(let v=0;v<3;v++){const _=1/this.direction[v],y=0===v?i.minX:1===v?i.minY:i.minZ,b=0===v?i.maxX:1===v?i.maxY:i.maxZ;let S=(y-this.origin[v])*_,w=(b-this.origin[v])*_;if(S>w){const i=S;S=w,w=i}g=Math.max(g,S),x=Math.min(x,w)}return x>=g&&x>=0}intersectTriangle(i,g,x,v=!0){const _=create$3(),y=create$3(),b=create$3(),S=create$3(),w=create$3();subtract$2(_,g,i),subtract$2(y,x,i),cross$2(b,this.direction,y);const L=dot$3(_,b);if(v){if(L<1e-5)return null}else if(L>-1e-5&&L<1e-5)return null;const k=1/L;subtract$2(S,this.origin,i);const H=k*dot$3(S,b);if(H<0||H>1)return null;cross$2(w,S,_);const z=k*dot$3(this.direction,w);if(z<0||H+z>1)return null;const q=k*dot$3(y,w);if(q>1e-5){const i=create$3();return scaleAndAdd$2(i,this.origin,this.direction,q),i}return null}intersectTriangleBarycentric(i,g,x,v=!0){const _=create$3(),y=create$3(),b=create$3(),S=create$3(),w=create$3();subtract$2(_,g,i),subtract$2(y,x,i),cross$2(b,this.direction,y);const L=dot$3(_,b);if(v){if(L<1e-5)return null}else if(L>-1e-5&&L<1e-5)return null;const k=1/L;subtract$2(S,this.origin,i);const H=k*dot$3(S,b);if(H<0||H>1)return null;cross$2(w,S,_);const z=k*dot$3(this.direction,w);if(z<0||H+z>1)return null;const q=k*dot$3(y,w);if(q>1e-5){const i=create$3();return scaleAndAdd$2(i,this.origin,this.direction,q),{point:i,t:q,u:H,v:z}}return null}}Object.freeze(Ray);class Raycaster3D{ray;near=0;far=1/0;#ou=create$4();#uu=create$4();#lu=create$4();#cu=create$3();#Ri;#hu=create();constructor(){this.ray=new Ray}setFromCamera(i,g,x){const{rawCamera:v,redGPUContext:_}=x,y=fromValues$3(v.x,v.y,v.z),b=x.screenToWorld(i,g),S=create$3();subtract$2(S,b,y),normalize$3(S,S),copy$3(this.ray.origin,y),copy$3(this.ray.direction,S),this.#Ri=x;const{pixelRectObject:w}=x,L=window.devicePixelRatio,k=_.renderScale,H=g*L*k,z=i*L*k/w.width*2-1,q=-H/w.height*2+1;set(this.#hu,z,q),"nearClipping"in v&&(this.near=v.nearClipping),"farClipping"in v&&(this.far=v.farClipping)}intersectObject(i,g=!0){const x=[];return this.#fu(i,g,x),x.sort((i,g)=>i.distance-g.distance)}intersectObjects(i,g=!0){const x=[];for(const v of i)this.#fu(v,g,x);return x.sort((i,g)=>i.distance-g.distance)}#fu(i,g,x){const v=i.useBillboard,_=i._renderRatioX||1,y=i._renderRatioY||1;if(v&&this.#Ri){i.usePixelSize?this.#du(i,x):this.#mu(i,x)}else if(i.geometry){const g=this.#uu;if(copy$4(g,i.modelMatrix),1!==_||1!==y)scale$4(g,g,[_,y,1]),this.#pu(i,g,x,!0);else{const g=i.boundingAABB;this.ray.intersectBox(g)&&this.#pu(i,i.modelMatrix,x,!0)}}if(g&&i.children)for(const v of i.children)this.#fu(v,g,x)}#du(i,x){const v=this.#Ri,_=i.modelMatrix,y=i.pixelSize;g(i.fontSize);const b=i._renderRatioX||1,S=i._renderRatioY||1,{rawCamera:w,projectionMatrix:L,pixelRectObject:k}=v,H=fromValues$3(_[12],_[13],_[14]),z=transformMat4$2(this.#cu,H,w.viewMatrix),q=transformMat4$1(this.#ou,fromValues$2(z[0],z[1],z[2],1),L);if(q[3]<=0)return;const W=q[0]/q[3],be=q[1]/q[3],je=this.#hu[0],Ke=this.#hu[1],Xe=y*window.devicePixelRatio,Ye=Xe/k.width*2*(b/S),Ze=Xe/k.height*2;if(Math.abs(je-W)<=.5*Ye&&Math.abs(Ke-be)<=.5*Ze){const g=distance$2(this.ray.origin,H);if(g>=this.near&&g<=this.far){const v=(je-W)/Ye+.5,_=(Ke-be)/Ze+.5;x.push({distance:g,point:H,localPoint:fromValues$3(0,0,0),object:i,faceIndex:0,uv:fromValues(v,1-_),ray:this.ray.clone()})}}}#mu(i,g){const x=this.#Ri,v=i.modelMatrix,_=i._renderRatioX||1,y=i._renderRatioY||1,b=invert$1(this.#uu,x.rawCamera.viewMatrix),S=this.#lu;copy$4(S,b),S[12]=v[12],S[13]=v[13],S[14]=v[14];scale$4(S,S,[Math.hypot(v[0],v[1],v[2])*_,Math.hypot(v[4],v[5],v[6])*y,Math.hypot(v[8],v[9],v[10])]),this.#pu(i,S,g,!1)}#pu(i,g,x,v){const _=new Ray;copy$3(_.origin,this.ray.origin),copy$3(_.direction,this.ray.direction);const y=invert$1(this.#ou,g);if(y){_.applyMatrix4(y);const b=i.geometry,S=b.vertexBuffer,w=b.indexBuffer,L=S.data,k=S.interleavedStruct.arrayStride/4;if(w){const y=w.data;for(let b=0;b=this.near&&z<=this.far){const x=fromValues(v[y*_+6],v[y*_+7]),q=fromValues(v[b*_+6],v[b*_+7]),W=fromValues(v[S*_+6],v[S*_+7]),be=create();scaleAndAdd(be,be,x,1-L-k),scaleAndAdd(be,be,q,L),scaleAndAdd(be,be,W,k),w.push({distance:z,point:H,localPoint:i,object:g,faceIndex:Math.floor(y/3),uv:be,ray:this.ray.clone()})}}}}Object.freeze(Raycaster3D);class Raycaster2D{ray;#Ri;#xu=create$3();#ou=create$4();#uu=create$4();#cu=create$3();constructor(){this.ray=new Ray}setFromCamera(i,g,x){this.#Ri=x;const{pixelRectObject:v}=x,_=i*devicePixelRatio/v.width*2-1,y=1-g*devicePixelRatio/v.height*2;set$3(this.#xu,_,y,0);const b=x.screenToWorld(i,g);set$3(this.ray.origin,b[0],b[1],b[2]),set$3(this.ray.direction,0,0,-1)}intersectObject(i,g=!0){const x=[];return this.#fu(i,g,x),x.sort((i,g)=>i.distance-g.distance)}intersectObjects(i,g=!0){const x=[];for(const v of i)this.#fu(v,g,x);return x.sort((i,g)=>i.distance-g.distance)}#fu(i,g,x){if(i.geometry){const g=this.#Ri,v=g.projectionMatrix,_=g.rawCamera.viewMatrix,y=multiply$4(this.#ou,v,_);multiply$4(y,y,i.modelMatrix);const b=invert$1(this.#uu,y);if(b){const g=transformMat4$2(this.#cu,this.#xu,b);let y=!1,S=1,w=1;if(i.is2DMeshType?(S=i.width,w=i.height,g[0]>=-S/2&&g[0]<=S/2&&g[1]>=-w/2&&g[1]<=w/2&&(y=!0)):g[0]>=-.5&&g[0]<=.5&&g[1]>=-.5&&g[1]<=.5&&(y=!0),y){const y=invert$1(create$4(),multiply$4(create$4(),v,_)),b=transformMat4$2(create$3(),this.#xu,y),L=g[0]/S>g[1]/w?1:0;x.push({distance:0,point:b,localPoint:clone$3(g),object:i,uv:fromValues(g[0]/S+.5,g[1]/w+.5),ray:this.ray.clone(),faceIndex:L})}}}if(g&&i.children)for(const v of i.children)this.#fu(v,g,x)}}Object.freeze(Raycaster2D);const updateViewportAndScissor=(i,g,x="DEFAULT")=>{const{scene:v,pixelRectObject:_,pickingManager:y,redGPUContext:b}=i,{width:S,height:w}=_;if("SHADOW"===x){const{shadowManager:i}=v,{directionalShadowManager:x}=i,_=x.shadowDepthTextureSize;g.setViewport(0,0,_,_,0,1),g.setScissorRect(0,0,_,_)}else if("PICKING"===x){const i=window.devicePixelRatio*b.renderScale,x=Math.floor(y.mouseX*i),v=Math.floor(y.mouseY*i);g.setViewport(0,0,S,w,0,1),g.setScissorRect(Math.max(0,Math.min(S-1,x)),Math.max(0,Math.min(w-1,v)),1,1)}else g.setViewport(0,0,S,w,0,1),g.setScissorRect(0,0,S,w)},renderListForLayer=(i,g,x="pipeline")=>{let v=0;const _=i.length,{currentRenderPassEncoder:y,renderResults:b}=g;for(y.setBindGroup(0,g.view.systemUniform_Vertex_UniformBindGroup);v<_;v++){const g=i[v];if(g.passFrustumCulling&&g.gpuRenderInfo){const i=g._geometry,v=g._material;i?b.num3DObjects++:b.num3DGroups++;const{gpuRenderInfo:_}=g,{vertexUniformBindGroup:S}=_;if(i&&_[x]){y.setPipeline(_[x]);const{gpuBuffer:g}=i.vertexBuffer,{fragmentUniformBindGroup:w}=v.gpuRenderInfo;if(y.setVertexBuffer(0,g),y.setBindGroup(1,S),y.setBindGroup(2,w),b.numDrawCalls++,i.indexBuffer){const{indexBuffer:g}=i,{indexCount:x,triangleCount:v,gpuBuffer:_,format:S}=g;y.setIndexBuffer(_,S),y.drawIndexed(x,1,0,0,0),b.numTriangles+=v,b.numPoints+=x}else{const{vertexBuffer:g}=i,{vertexCount:x,triangleCount:v}=g;y.draw(x,1,0,0),b.numTriangles+=v,b.numPoints+=x}}}}};class PickingManager extends RedGPUObject{lastMouseEvent;lastMouseClickEvent;#vu;#_u;#yu;#bu;#Ri;#Su=[];#Tu=0;#wu=0;#Mu;#Pu;#H=0;#Ru=new Raycaster3D;#Cu=new Raycaster2D;#Bu;#Gi=!1;#Du;constructor(i){super(i.redGPUContext),this.#Ri=i}get videoMemorySize(){return this.#H}get mouseX(){return this.#Tu}set mouseX(i){this.#Tu=i}get mouseY(){return this.#wu}set mouseY(i){this.#wu=i}get castingList(){return this.#Su}get pickingGPUTexture(){return this.#yu}get pickingGPUTextureView(){return this.#bu}get pickingDepthGPUTextureView(){return this.#_u}get pickingPassDescriptor(){return this.#Du}render(i){if(this.castingList.length){const{redGPUContext:g}=i;this.#Eu(i);const x=this.#Su;let v=0;const _=x.length;for(;v<_;v++){const i=x[v],{gpuRenderInfo:g}=i;g&&!g.pickingPipeline&&(g.pickingPipeline=g.vertexStructInfo.vertexEntries.includes("entryPointPickingVertex")?createBasePipeline(i,g.vertexShaderModule,g.vertexBindGroupLayout,dn):null)}this.#Du={label:`${i.name} Picking Render Pass`,colorAttachments:[{view:this.pickingGPUTextureView,clearValue:{r:0,g:0,b:0,a:0},loadOp:z.CLEAR,storeOp:q.STORE}],depthStencilAttachment:{view:this.pickingDepthGPUTextureView,depthClearValue:1,depthLoadOp:z.CLEAR,depthStoreOp:q.STORE}},g.commandEncoderManager.addMainRenderPass(this.pickingPassDescriptor,g=>{updateViewportAndScissor(i,g,"PICKING"),((i,g)=>{const{renderViewStateData:x,pickingManager:v}=i;x.currentRenderPassEncoder=g;const{castingList:_}=v;renderListForLayer(_,x,"pickingPipeline")})(i,g)})}this.#Iu(i)}resetCastingList(){this.#Su.length=0}destroy(){this.#yu&&(this.#yu.destroy(),this.#vu.destroy(),this.#yu=null,this.#bu=null,this.#vu=null,this.#_u=null)}async checkEvents(i,g){if(this.castingList.length&&!this.#Gi){const{pixelRectArray:x,redGPUContext:v}=i,_=window.devicePixelRatio*v.renderScale,y=this.#Tu,b=this.#wu,S=y*_,w=b*_;if(S>=0&&S=0&&w=L[2]||z<0||z>=L[3]||(this.#Bu||(this.#Bu=g.createBuffer({size:4,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,label:"PickingManager_ReadPixelBuffer"})),x.useEncoder(k.MAIN,i=>{const g={texture:this.#yu,origin:{x:H,y:z,z:0}},x={buffer:this.#Bu,bytesPerRow:256,rowsPerImage:1};i.copyTextureToBuffer(g,x,{width:1,height:1,depthOrArrayLayers:1})}))}#ci(){const i=this.#yu;if(!i)return 0;this.#H=calculateTextureByteSize(i)+calculateTextureByteSize(this.#vu)}#Ou(i,g){const{resourceManager:x}=this;return x.createManagedTexture({size:[this.#Ri.pixelRectObject.width,this.#Ri.pixelRectObject.height,1],usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC,format:g,sampleCount:1,label:`${this.#Ri.name}_${i}_${this.#Ri.pixelRectObject.width}x${this.#Ri.pixelRectObject.height}`})}#Au=()=>this.#Su.reduce((i,g)=>(i[g.pickingId]=g,i),{});#Vu(i,g,x,v,_,y,b){const S="Camera2D"===this.#Ri.rawCamera.constructor.name?this.#Cu:this.#Ru;let w;if(S.setFromCamera(this.#Tu,this.#wu,this.#Ri),v){w=S.intersectObject(v)[0]}const L=new PickingEvent(i,g,x,v,_,y,b,w);return L.ray||(L.ray=S.ray.clone()),L}#Uu=(g,x,v,_,y)=>{const b=y[g],S=this.lastMouseClickEvent?.type;if(S===i.CLICK){const i=this.#Vu(g,x,v,b,_,S,this.lastMouseClickEvent);this.#Nu(S,i)}};#ku=(g,x,v,_,y)=>{const b=y[g],S=this.lastMouseEvent?.type;if(S){const y=this.#Vu(g,x,v,b,_,S,this.lastMouseEvent);switch(this.#Mu&&(y.movementX=x-this.#Mu.mouseX,y.movementY=v-this.#Mu.mouseY),S){case i.DOWN:case i.UP:this.#Nu(S,y);break;case i.MOVE:this.#Fu(g,b,y)}this.#Mu=y}};#Fu=(g,x,v)=>{const _=this.#Mu?.pickingId;_!==g?(this.#Mu&&_&&_!==g&&this.#Gu(),this.#Pu!==x&&(this.#Nu(i.OVER,v),document.body.style.cursor="pointer"),this.#Pu=x):this.#Nu(i.MOVE,v)};#Gu=()=>{this.#Mu&&this.#Nu(i.OUT,this.#Mu),this.#Mu=null,this.#Pu=null,document.body.style.cursor="default"};async#Lu(i){await i.mapAsync(GPUMapMode.READ);const g=new DataView(i.getMappedRange()),x="rgba8unorm"==this.#yu.format?[0,1,2,3]:[2,1,0,3],v=g.getUint8(x[0]),_=g.getUint8(x[1]),y=g.getUint8(x[2]),b=g.getUint8(x[3]);return i.unmap(),(b<<24|y<<16|_<<8|v)>>>0}#Nu(i,g){g.target&&g.target.events[i]&&g.target.events[i](g)}}Object.freeze(PickingManager);class FXAA extends ASinglePassPostEffect{constructor(i){super(i),this.isLdr=!0,this.init(i,"POST_EFFECT_FXAA",createBasicPostEffectCode(this,"let index=global_id.xy;let dims=textureDimensions(sourceTexture);let i_index=vec2(index);let colorM4=textureLoad(sourceTexture,index,0);let lumaM=getLuminance(colorM4.rgb);let colorN4=fetchColor4(i_index+vec2(0,-1),dims);let colorS4=fetchColor4(i_index+vec2(0,1),dims);let colorW4=fetchColor4(i_index+vec2(-1,0),dims);let colorE4=fetchColor4(i_index+vec2(1,0),dims);let lumaN=getLuminance(colorN4.rgb);let lumaS=getLuminance(colorS4.rgb);let lumaW=getLuminance(colorW4.rgb);let lumaE=getLuminance(colorE4.rgb);let lumaMin=min(lumaM,min(min(lumaN,lumaS),min(lumaW,lumaE)));let lumaMax=max(lumaM,max(max(lumaN,lumaS),max(lumaW,lumaE)));let range=lumaMax-lumaMin;if(range(-1,-1),dims).rgb);let lumaNE=getLuminance(fetchColor4(i_index+vec2(1,-1),dims).rgb);let lumaSW=getLuminance(fetchColor4(i_index+vec2(-1,1),dims).rgb);let lumaSE=getLuminance(fetchColor4(i_index+vec2(1,1),dims).rgb);let edgeVer=abs(lumaNW+lumaSW-2.0*lumaW)+abs(lumaN+lumaS-2.0*lumaM)*2.0+abs(lumaNE+lumaSE-2.0*lumaE);let edgeHor=abs(lumaNW+lumaNE-2.0*lumaN)+abs(lumaW+lumaE-2.0*lumaM)*2.0+abs(lumaSW+lumaSE-2.0*lumaS);let isHorizontal=edgeHor>=edgeVer;let luma1=select(lumaW,lumaN,isHorizontal);let luma2=select(lumaE,lumaS,isHorizontal);let gradient1=luma1-lumaM;let gradient2=luma2-lumaM;let is1Steeper=abs(gradient1)>=abs(gradient2);let gradientScaled=0.25*max(abs(gradient1),abs(gradient2));var lumaLocalAverage=.0;var edgeStep=vec2(0,0);if(is1Steeper){edgeStep=select(vec2(-1,0),vec2(0,-1),isHorizontal);lumaLocalAverage=0.5*(luma1+lumaM);}else{edgeStep=select(vec2(1,0),vec2(0,1),isHorizontal);lumaLocalAverage=0.5*(luma2+lumaM);}var posP=i_index+edgeStep;var posN=i_index+edgeStep;let searchStep=select(vec2(1,0),vec2(0,1),isHorizontal);var doneP=false;var doneN=false;for(var i=0;i<10;i++){if(!doneP){if(abs(getLuminance(fetchColor4(posP,dims).rgb)-lumaLocalAverage)>=gradientScaled){doneP=true;}else{posP+=searchStep;}}if(!doneN){if(abs(getLuminance(fetchColor4(posN,dims).rgb)-lumaLocalAverage)>=gradientScaled){doneN=true;}else{posN-=searchStep;}}if(doneP&&doneN){break;}}let distP=select(f32(posP.x-i_index.x),f32(posP.y-i_index.y),isHorizontal);let distN=select(f32(i_index.x-posN.x),f32(i_index.y-posN.y),isHorizontal);let distMin=min(abs(distP),abs(distN));let edgeBlend=saturate(0.5-distMin/(abs(distP)+abs(distN)));let lumaL=(lumaN+lumaS+lumaW+lumaE)*2.0;let lumaCorners=lumaNW+lumaNE+lumaSW+lumaSE;let subpixFilter=saturate(abs((lumaL+lumaCorners)/12.0-lumaM)/range);let subpixBlend=smoothstep(.0,1.0,subpixFilter)*uniforms.subpix;let finalBlend=max(edgeBlend,subpixBlend);let colorTarget4=fetchColor4(i_index+edgeStep,dims);let finalColor4=mix(colorM4,colorTarget4,finalBlend);textureStore(outputTexture,index,finalColor4);","struct Uniforms{subpix:f32,edgeThreshold:f32,edgeThresholdMin:f32,padding:f32};#redgpu_include color.getLuminance fn fetchColor4(pos:vec2,dims:vec2)->vec4{let p=vec2(clamp(vec2(pos),vec2(0),dims-1));return textureLoad(sourceTexture,p,0);}"))}}definePositiveNumber(FXAA,[{key:"edgeThresholdMin",value:.0625,min:1e-5,max:.1},{key:"edgeThreshold",value:.125,min:1e-4,max:.25},{key:"subpix",value:.75,min:0,max:1}]),Object.freeze(FXAA);class TAA extends ASinglePassPostEffect{#Hu;#zu;#$u=0;#ju=.5;#Ku=[0,0];#Xu=create$4();#H=0;#Wr;constructor(i){super(i,{x:8,y:8,z:1}),this.isLdr=!0,this.init(i,"POST_EFFECT_TAA",createBasicPostEffectCode(this,"{let pixelCoord=vec2(global_id.xy);let screenSizeU=textureDimensions(sourceTexture);let screenSize=vec2(screenSizeU);let yFlipVec2=vec2(1.0,-1.0);if(any(pixelCoord>=vec2(screenSizeU))){return;}let currentUV=(vec2(pixelCoord)+0.5-uniforms.currJitterOffset*yFlipVec2)/screenSize;let stats=calculate_neighborhood_stats_ycocg(pixelCoord,screenSizeU);let currentRGBA=textureSampleLevel(sourceTexture,basicSampler,currentUV,.0);let currentRGB=currentRGBA.rgb;let currentAlpha=currentRGBA.a;let currentYCoCg=rgbToYCoCg(currentRGB);let currentDepth=textureLoad(depthTexture,pixelCoord,0);var closestDepth=1.0;var closestCoord=pixelCoord;for(var y:i32=-1;y<=1;y++){for(var x:i32=-1;x<=1;x++){let sc=clamp(pixelCoord+vec2(x,y),vec2(0),vec2(screenSizeU)-1);let d=textureLoad(depthTexture,sc,0);if(d0.5;if(jitterDisabled){textureStore(outputTexture,pixelCoord,vec4(currentRGB,currentAlpha));return;}let historyUV=(vec2(pixelCoord)+0.5-uniforms.currJitterOffset*yFlipVec2+uniforms.prevJitterOffset*yFlipVec2)/screenSize-velocity;var finalRGB:vec3;var finalAlpha:f32;if(any(historyUV(.0))||any(historyUV>vec2(1.0))){finalRGB=currentRGB;finalAlpha=currentAlpha;}else{let prevDepth=fetch_depth_bilinear(historyUV,screenSize);let historyData=sample_texture_catmull_rom_antiflicker(historyTexture,basicSampler,historyUV,screenSize);let motionLen=length(velocity*screenSize);let motionSoft=smoothstep(.0,1.0,motionLen);let clippedYCoCg=clip_history_ycocg(historyData.ycocg,stats,motionSoft);let clippedAlpha=clamp(historyData.alpha,stats.minAlpha,stats.maxAlpha);let clippedHistoryRGB=YCoCgToRgb(clippedYCoCg);let lumaWeight=get_color_discrepancy_weight(stats,clippedHistoryRGB);var blendFactor=mix(.08,0.4,motionSoft);let depthConfidence=get_depth_confidence(currentDepth,prevDepth);blendFactor=max(blendFactor,1.0-depthConfidence*depthConfidence);blendFactor=max(blendFactor,lumaWeight*0.5);let currentRGBA_final=vec4(currentRGB,currentAlpha);let clippedHistoryRGBA=vec4(clippedHistoryRGB,clippedAlpha);let finalRGBA=mix(clippedHistoryRGBA,currentRGBA_final,blendFactor);finalRGB=finalRGBA.rgb;finalAlpha=finalRGBA.a;}textureStore(outputTexture,pixelCoord,vec4(finalRGB,finalAlpha));}","#redgpu_include color.getLuminance #redgpu_include color.rgbToYCoCg #redgpu_include color.YCoCgToRgb #redgpu_include depth.getLinearizeDepth #redgpu_include math.EPSILON struct Uniforms{frameIndex:f32,currJitterOffset:vec2,prevJitterOffset:vec2,};struct NeighborhoodStats{minColor:vec3,maxColor:vec3,mean:vec3,stdDev:vec3,minAlpha:f32,maxAlpha:f32,meanAlpha:f32,meanLuminance:f32,stdDevLuminance:f32,};struct SampledColor{rgb:vec3,ycocg:vec3,alpha:f32,};fn get_depth_confidence(currDepth:f32,prevDepth:f32)->f32{let currLinear=getLinearizeDepth(currDepth,systemUniforms.camera.nearClipping,systemUniforms.camera.farClipping);let prevLinear=getLinearizeDepth(prevDepth,systemUniforms.camera.nearClipping,systemUniforms.camera.farClipping);let depthDiff=abs(currLinear-prevLinear);return 1.0-clamp((depthDiff-0.1)/0.4,.0,1.0);}fn fetch_depth_bilinear(uv:vec2,screenSize:vec2)->f32{let samplePos=uv*screenSize-0.5;let f=fract(samplePos);let base=vec2(floor(samplePos));let size=vec2(textureDimensions(prevDepthTexture));let d00=textureLoad(prevDepthTexture,clamp(base+vec2(0,0),vec2(0),size-1),0);let d10=textureLoad(prevDepthTexture,clamp(base+vec2(1,0),vec2(0),size-1),0);let d01=textureLoad(prevDepthTexture,clamp(base+vec2(0,1),vec2(0),size-1),0);let d11=textureLoad(prevDepthTexture,clamp(base+vec2(1,1),vec2(0),size-1),0);return mix(mix(d00,d10,f.x),mix(d01,d11,f.x),f.y);}fn calculate_neighborhood_stats_ycocg(pixelCoord:vec2,screenSizeU:vec2)->NeighborhoodStats{let screenSize=vec2(screenSizeU);var m1=vec3(.0);var m2=vec3(.0);var m1L=.0;var m2L=.0;var m1A=.0;var minC=vec3(1e5);var maxC=vec3(-1e5);var minA=1e5;var maxA=-1e5;for(var y:i32=-1;y<=1;y++){for(var x:i32=-1;x<=1;x++){let sampleCoord=clamp(pixelCoord+vec2(x,y),vec2(0),vec2(screenSizeU)-1);let colorRGBA=textureLoad(sourceTexture,sampleCoord,0);let colorRGB=colorRGBA.rgb;let colorYCoCg=rgbToYCoCg(colorRGB);let lum=getLuminance(colorRGB);let alpha=colorRGBA.a;m1+=colorYCoCg;m2+=colorYCoCg*colorYCoCg;m1L+=lum;m2L+=lum*lum;m1A+=alpha;minC=min(minC,colorYCoCg);maxC=max(maxC,colorYCoCg);minA=min(minA,alpha);maxA=max(maxA,alpha);}}let sampleCount=9.0;var stats:NeighborhoodStats;stats.mean=m1/sampleCount;stats.stdDev=sqrt(max((m2/sampleCount)-(stats.mean*stats.mean),vec3(.0)));stats.meanLuminance=m1L/sampleCount;stats.stdDevLuminance=sqrt(max((m2L/sampleCount)-(stats.meanLuminance*stats.meanLuminance),.0));stats.minColor=minC;stats.maxColor=maxC;stats.minAlpha=minA;stats.maxAlpha=maxA;stats.meanAlpha=m1A/sampleCount;return stats;}fn get_color_discrepancy_weight(stats:NeighborhoodStats,histRGB:vec3)->f32{let histLuminance=getLuminance(histRGB);let diff=abs(stats.meanLuminance-histLuminance);let threshold=max(stats.stdDevLuminance*0.45,.01);return smoothstep(threshold,threshold*2.0,diff);}fn sample_texture_catmull_rom_antiflicker(tex:texture_2d,smp:sampler,uv:vec2,texSize:vec2)->SampledColor{let samplePos=uv*texSize;let texPos1=floor(samplePos-0.5)+0.5;let f=samplePos-texPos1;let w0=f*(-0.5+f*(1.0-0.5*f));let w1=1.0+f*f*(-2.5+1.5*f);let w2=f*(0.5+f*(2.0-1.5*f));let w3=f*f*(-0.5+0.5*f);let w12=w1+w2;let offset12=w2/w12;let invTexSize=1.0/texSize;let coords=array,5>((texPos1+vec2(offset12.x,-1.0))*invTexSize,(texPos1+vec2(-1.0,offset12.y))*invTexSize,(texPos1+offset12)*invTexSize,(texPos1+vec2(2.0,offset12.y))*invTexSize,(texPos1+vec2(offset12.x,2.0))*invTexSize);let weights=array(w12.x*w0.y,w0.x*w12.y,w12.x*w12.y,w3.x*w12.y,w12.x*w3.y);var sumRGB=vec3(.0);var sumYCoCg=vec3(.0);var sumAlpha=.0;var sumW=.0;for(var i=0;i<5;i++){let sampleRGBA=textureSampleLevel(tex,smp,coords[i],.0);let sampleRGB=max(sampleRGBA.rgb,vec3(.0));let sampleYCoCg=rgbToYCoCg(sampleRGB);let sampleLum=getLuminance(sampleRGB);let w=weights[i]*(1.0/(1.0+sampleLum));sumRGB+=sampleRGB*w;sumYCoCg+=sampleYCoCg*w;sumAlpha+=sampleRGBA.a*w;sumW+=w;}var result:SampledColor;let invSumW=1.0/max(sumW,EPSILON);result.rgb=sumRGB*invSumW;result.ycocg=sumYCoCg*invSumW;result.alpha=sumAlpha*invSumW;return result;}fn clip_history_ycocg(historyYCoCg:vec3,stats:NeighborhoodStats,motion:f32)->vec3{let gamma=mix(0.2,0.7,motion);let v_min=min(stats.minColor,stats.mean-stats.stdDev*gamma);let v_max=max(stats.maxColor,stats.mean+stats.stdDev*gamma);return clamp(historyYCoCg,v_min,v_max);}",[{name:"sourceTexture"},{name:"historyTexture"}])),this.jitterStrength=this.#ju}get prevNoneJitterProjectionViewMatrix(){return this.#Xu}get frameIndex(){return this.#$u}get videoMemorySize(){return this.#H}get jitterStrength(){return this.#ju}set jitterStrength(i){this.#ju=i}render(i,g,x,v){const{redGPUContext:_}=this,{commandEncoderManager:y}=_;this.#$u++,this.updateUniform("frameIndex",this.#$u),this.updateUniform("currJitterOffset",i.jitterOffset),this.updateUniform("prevJitterOffset",this.#Ku),copy$4(this.#Xu,i.noneJitterProjectionViewMatrix),this.#Ku=[...i.jitterOffset],this.#qu(g,x);const b={texture:this.#Hu,textureView:this.#zu},S=super.render(i,g,x,v,b);return y.useEncoder(k.POST_PROCESS,i=>{i.copyTextureToTexture({texture:S.texture},{texture:this.#Hu},[g,x,1])}),this.#$u<=20||this.#$u,S}clear(){super.clear(),this.#Hu&&(this.#Hu.destroy(),this.#Hu=null,this.#zu=null),this.#Wr=null}#qu(i,g){if(this.#Wr?.width!==i||this.#Wr?.height!==g||!this.#Hu){this.#Hu&&this.#Hu.destroy();const{resourceManager:x}=this.redGPUContext;this.#Hu=x.createManagedTexture({size:{width:i,height:g},format:"rgba16float",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST,label:`TAA_HistoryTexture_${i}x${g}`}),this.#zu=x.getGPUResourceBitmapTextureView(this.#Hu,{dimension:"2d",format:"rgba16float",label:"TAA_HistoryTextureView"}),this.#Wr={width:i,height:g},this.#Yu()}}#Yu(){this.#H=this.uniformBuffer?this.uniformBuffer.size:0,this.#Hu&&(this.#H+=calculateTextureByteSize(this.#Hu))}}let Gn,On,Vn,Nn,Fn;Object.freeze(TAA);let Hn,zn=create$3(),$n=create$4(),jn=create$4();const screenToWorld=(i,g,x)=>{const{rawCamera:v,pixelRectArray:_}=x;return Gn=2*(i*window.devicePixelRatio+_[0])/_[2]-1,On=-2*(g*window.devicePixelRatio+_[1])/_[3]+1,Vn=1,multiply$4(jn,x.noneJitterProjectionMatrix,v.viewMatrix),Hn=clone$4(jn),invert$1(Hn,Hn),zn=fromValues$3(Gn,On,1),identity$1($n),translate($n,$n,zn),multiply$4(Hn,Hn,$n),zn[0]=Hn[12],zn[1]=Hn[13],zn[2]=Hn[14],Nn=jn[12]*Gn+jn[13]*On+jn[15],0!==Nn&&(Fn=1/Nn,zn[0]/=Fn,zn[1]/=Fn,zn[2]/=Fn,zn[0]=zn[0]+v.x,zn[1]=zn[1]+v.y,zn[2]=zn[2]+v.z),[zn[0],zn[1],zn[2]]};class Box extends Primitive{constructor(i,g=1,x=1,v=1,_=1,y=1,b=1){const S=Primitive.generateUniqueKey("BOX",{width:g,height:x,depth:v,widthSegments:_,heightSegments:y,depthSegments:b});super(i,S,()=>PrimitiveUtils.generateBoxData(i,g,x,v,_,y,b,S))}}class Cylinder extends Primitive{constructor(i,g=1,x=1,v=1,_=8,y=1,b=!0,S=!0,w=0,L=2*Math.PI,k=!1,H=!1){const z=Primitive.generateUniqueKey("CYLINDER",{radiusTop:g,radiusBottom:x,height:v,radialSegments:_,heightSegments:y,capTop:b,capBottom:S,thetaStart:w,thetaLength:L,isRadialTop:k,isRadialBottom:H});super(i,z,()=>PrimitiveUtils.generateCylinderData(i,g,x,v,_,y,b,S,w,L,k,H,z))}}class Sphere extends Primitive{constructor(i,g=1,x=16,v=16,_=0,y=2*Math.PI,b=0,S=Math.PI){const w=Primitive.generateUniqueKey("SPHERE",{radius:g,widthSegments:x,heightSegments:v,phiStart:_,phiLength:y,thetaStart:b,thetaLength:S});super(i,w,()=>PrimitiveUtils.generateSphereData(i,g,x,v,_,y,b,S,w))}}class DrawDebuggerAxis extends Mesh{constructor(i){super(i,null,null);const g=new Mesh(i,new Sphere(i,.5),new ColorMaterial(i));this.addChild(g);const x=new Box(i);this.addChild(this.#Wu(x,"#ff0000",[5,.1,.1],[2.5,0,0])),this.addChild(this.#Zu(i,"#ff0000",[.5,1.25],[5.5,0,0],[0,0,90])),this.addChild(this.#Wu(x,"#00ff00",[.1,5,.1],[0,2.5,0])),this.addChild(this.#Zu(i,"#00ff00",[.5,1.25],[0,5.5,0],[180,0,0])),this.addChild(this.#Wu(x,"#0000ff",[.1,.1,5],[0,0,2.5])),this.addChild(this.#Zu(i,"#0000ff",[.5,1.25],[0,0,5.5],[-90,0,0]))}#Wu(i,g,x,v){const{redGPUContext:_}=this,y=new Mesh(_,i,new ColorMaterial(_,g));return y.setScale(...x),y.setPosition(...v),y}#Zu(i,g,x,v,_){const y=new Mesh(i,new Cylinder(i,x[0],.001,x[1],32,1),new ColorMaterial(i,g));return y.setScale(x[0],x[1],x[0]),y.setPosition(...v),y.setRotation(..._),y}}Object.freeze(DrawDebuggerAxis);var Kn="#redgpu_include SYSTEM_UNIFORM;#redgpu_include systemStruct.OutputFragment;#redgpu_include math.getMotionVector;struct InputData{@location(0)position:vec4,@location(1)color:vec4,}struct VertexOutput{@builtin(position)position:vec4,@location(0)color:vec4,@location(1)worldPos:vec3,@location(2)currentClipPos:vec4,@location(3)prevClipPos:vec4,}struct GridArgs{lineColor:vec4,}@group(1)@binding(0)vargridArgs:GridArgs;const FADE_START:f32=20.0;const FADE_END:f32=80.0;const AXIS_THRESHOLD:f32=0.8;const AXIS_ALPHA:f32=0.8;@vertex fn vertexMain(inputData:InputData)->VertexOutput{var output:VertexOutput;let modelPos=inputData.position;let viewProj=systemUniforms.projection.noneJitterProjectionViewMatrix;let prevViewProj=systemUniforms.projection.prevNoneJitterProjectionViewMatrix;output.position=viewProj*modelPos;output.worldPos=modelPos.xyz;output.color=inputData.color;output.currentClipPos=output.position;output.prevClipPos=prevViewProj*modelPos;return output;}@fragment fn fragmentMain(inputData:VertexOutput)->OutputFragment{var output:OutputFragment;let distanceToCamera=length(inputData.worldPos-systemUniforms.camera.cameraPosition);let distanceFade=clamp(1.0-saturate((distanceToCamera-FADE_START)/(FADE_END-FADE_START)),0.5,1.0);var finalColor:vec3;var baseAlpha:f32;let isXAxis=inputData.color.r>AXIS_THRESHOLD;let isZAxis=inputData.color.b>AXIS_THRESHOLD;if(isXAxis){finalColor=vec3(1.0,.0,.0);baseAlpha=AXIS_ALPHA;}else if(isZAxis){finalColor=vec3(.0,.0,1.0);baseAlpha=AXIS_ALPHA;}else{finalColor=gridArgs.lineColor.rgb;baseAlpha=gridArgs.lineColor.a;}output.color=vec4(finalColor,baseAlpha*distanceFade);let motion=getMotionVector(inputData.currentClipPos,inputData.prevClipPos);output.gBufferMotionVector=vec4(motion,.0,1.0);return output;}";const Xn=parseWGSL("DRAW_DEBUGGER_GRID",Kn),qn=Xn.uniforms.gridArgs;class DrawDebuggerGrid extends BaseObject{#On;#Vn;#se;#Ju;#U;#Qu;#ur;#lr;#el;#qt=100;#Ns;#Os;#As;#Ls;#tl;#ls;constructor(i){super(),validateRedGPUContext(i),this.#Ns=DrawBufferManager.getInstance(i);const{resourceManager:g,gpuDevice:x}=i,v={code:Kn},_=g.createGPUShaderModule("VERTEX_MODULE_GRID",v);this.#ur=new BlendState(this),this.#lr=new BlendState(this),this.#el=new ColorRGBA(128,128,128,.25);const y=g.getGPUBindGroupLayout(ResourceManager.PRESET_GPUBindGroupLayout_System),b="GRID_MATERIAL_BIND_GROUP_LAYOUT",S=g.getGPUBindGroupLayout(b)||g.createBindGroupLayout(b,getFragmentBindGroupLayoutDescriptorFromShaderInfo(Xn,1));this.#rl(i),this.#Ju=x.createBindGroup({label:"FRAGMENT_BIND_GROUP_DESCRIPTOR_GRID",layout:S,entries:[{binding:0,resource:{buffer:this.#se.gpuBuffer,offset:0,size:this.#se.size}}]});const w={label:"PIPELINE_DESCRIPTOR_GRID",layout:x.createPipelineLayout({label:"DRAW_DEBUGGER_GRID_PIPELINE_LAYOUT",bindGroupLayouts:[y,S]}),vertex:{module:_,entryPoint:"vertexMain",buffers:[{arrayStride:this.#On.interleavedStruct.arrayStride,attributes:this.#On.interleavedStruct.attributes}]},primitive:{topology:"line-list"},fragment:{module:_,entryPoint:"fragmentMain",targets:[{format:"rgba16float",blend:{color:this.#ur.state,alpha:this.#lr.state}},{format:navigator.gpu.getPreferredCanvasFormat(),blend:void 0},{format:"rgba16float",blend:void 0}]},depthStencil:{format:"depth32float",depthWriteEnabled:!0,depthCompare:Er.LESS_EQUAL}};this.#U=x.createRenderPipeline(w),this.#Qu=x.createRenderPipeline({...w,multisample:{count:4}});const L=this.#Ns;this.#Os||(this.#Os=L.allocateDrawCommand(this.name),L.setIndexedIndirectCommand(this.#Os,this.#Vn.indexCount,1,0,0,0))}get size(){return this.#qt}set size(i){this.#qt=i}get lineColor(){return this.#el}render(i){const{view:g,currentRenderPassEncoder:x,renderResults:v}=i,{redGPUContext:_}=g,{gpuDevice:y,antialiasingManager:b}=_,{msaaID:S}=b;set$3(create$3(),g.rawCamera.x,g.rawCamera.y,g.rawCamera.z),v.num3DObjects++,v.numDrawCalls++;const w=this.#ls!==S,L=g.systemUniform_Vertex_UniformBindGroup!==this.#tl;if(this.#U){const i=2*(2*(this.#qt+1));(!this.#As||w||L)&&(this.#ls=S,this.#As=y.createRenderBundleEncoder({...g.basicRenderBundleEncoderDescriptor,label:this.name}),this.#As.setPipeline(g.redGPUContext.antialiasingManager.useMSAA?this.#Qu:this.#U),this.#As.setBindGroup(0,g.systemUniform_Vertex_UniformBindGroup),this.#As.setBindGroup(1,this.#Ju),this.#As.setVertexBuffer(0,this.#On.gpuBuffer),this.#As.setIndexBuffer(this.#Vn.gpuBuffer,this.#Vn.format),this.#As.drawIndexedIndirect(this.#Os.buffer,4*this.#Os.commandOffset),this.#Ls=this.#As.finish()),v.numTriangles+=0,v.numPoints+=i,x.executeBundles([this.#Ls])}this.#tl=g.systemUniform_Vertex_UniformBindGroup}#il(i){const g=[],x=[],v=i/2;let _=0;for(let i=-v;i<=v;i+=1){const y=0===i?[0,0,1,1]:[.5,.5,.5,1];g.push(i,0,-v,...y,i,0,v,...y),x.push(_,_+1),_+=2}for(let i=-v;i<=v;i+=1){const y=0===i?[1,0,0,1]:[.5,.5,.5,1];g.push(-v,0,i,...y,v,0,i,...y),x.push(_,_+1),_+=2}return{interleaveData:g,indexData:x}}#rl(i){const g=this.#qt,{resourceManager:x}=i,{cachedBufferState:v}=x;{const x=`VertexBuffer_Grid_${g}`;let _=v[x];if(!_){const{interleaveData:y}=this.#il(g);_=new VertexBuffer(i,y,new VertexInterleavedStruct({position:VertexInterleaveType.float32x3,color:VertexInterleaveType.float32x4}),void 0,x),v[x]=_}this.#On=_}{const x=`IndexBuffer_Grid_${g}`;let _=v[x];if(!_){const{indexData:y}=this.#il(g);_=new IndexBuffer(i,y,void 0,x),v[x]=_}this.#Vn=_}{const g="UniformBuffer_Grid";let x=v[g];if(!x){const _=new ArrayBuffer(qn.arrayBufferByteLength);x=new UniformBuffer(i,_,g,g),v[g]=x}this.#se=x}this.#se.writeOnlyBuffer(qn.members.lineColor,this.#el.rgbaNormalLinear)}}Object.freeze(DrawDebuggerGrid);class ABaseLight{drawDebugger;#nl;#al;#Bs=!1;constructor(i,g=1){this.#nl=i,this.#al=g}get enableDebugger(){return this.#Bs}set enableDebugger(i){this.#Bs=i}get color(){return this.#nl}set color(i){i instanceof ColorRGB||consoleAndThrowError("Only ColorRGB instances are allowed."),this.#nl=i}get intensityMultiplier(){return this.#al}set intensityMultiplier(i){validatePositiveNumberRange(i,0),this.#al=i}}Object.freeze(ABaseLight);class AmbientLight extends ABaseLight{#sl=0;constructor(i="#ADD8E6",g=50){super(new ColorRGB(...convertHexToRgb(i,!0))),this.#sl=g}get lux(){return this.#sl}set lux(i){this.#sl=i}}Object.freeze(AmbientLight);class DirectionalLight extends ABaseLight{#ol=-1;#ul=-1;#ll=-1;#cl=35.264389682754654;#hl=45;#sl=1e5;constructor(i=[-1,-1,-1],g="#fff",x=1e5){super(new ColorRGB(...convertHexToRgb(g,!0))),this.direction=i,this.#sl=x}get lux(){return this.#sl}set lux(i){this.#sl=i}get elevation(){return this.#cl}set elevation(i){this.#cl=i,this.#fl()}get azimuth(){return this.#hl}set azimuth(i){this.#hl=i,this.#fl()}get directionX(){return this.#ol}set directionX(i){this.#ol=i,this.#dl()}get directionY(){return this.#ul}set directionY(i){this.#ul=i,this.#dl()}get directionZ(){return this.#ll}set directionZ(i){this.#ll=i,this.#dl()}get direction(){return[this.#ol,this.#ul,this.#ll]}set direction(i){this.#ol=i[0],this.#ul=i[1],this.#ll=i[2],this.#dl()}#fl(){const i=this.#cl*Math.PI/180,g=this.#hl*Math.PI/180,x=Math.cos(i),v=x*Math.cos(g),_=Math.sin(i),y=x*Math.sin(g);this.#ol=-v,this.#ul=-_,this.#ll=-y}#dl(){const i=-this.#ol,g=-this.#ul,x=-this.#ll,v=Math.sqrt(i*i+g*g+x*x),_=i/v,y=g/v,b=x/v;this.#cl=180*Math.asin(y)/Math.PI,this.#hl=180*Math.atan2(b,_)/Math.PI}}Object.freeze(DirectionalLight);class PointLight extends ABaseLight{#ml=10;#wi=0;#Mi=0;#Pi=0;#pl=1e3;constructor(i="#fff",g=1e3){super(new ColorRGB(...convertHexToRgb(i,!0))),this.#pl=g}get lumen(){return this.#pl}set lumen(i){this.#pl=i}get x(){return this.#wi}set x(i){this.#wi=i}get y(){return this.#Mi}set y(i){this.#Mi=i}get z(){return this.#Pi}set z(i){this.#Pi=i}get position(){return[this.#wi,this.#Mi,this.#Pi]}get radius(){return this.#ml}set radius(i){this.#ml=i}setPosition(i,g,x){Array.isArray(i)?[this.#wi,this.#Mi,this.#Pi]=i:(this.#wi=i,this.#Mi=g,this.#Pi=x)}}Object.freeze(PointLight);class SpotLight extends ABaseLight{#ml=10;#wi=0;#Mi=2;#Pi=0;#ol=0;#ul=-1;#ll=0;#gl=0;#xl=44;#pl=1e3;constructor(i="#fff",g=1e3){super(new ColorRGB(...convertHexToRgb(i,!0))),this.#pl=g}get lumen(){return this.#pl}set lumen(i){this.#pl=i}get x(){return this.#wi}set x(i){this.#wi=i}get y(){return this.#Mi}set y(i){this.#Mi=i}get z(){return this.#Pi}set z(i){this.#Pi=i}get position(){return[this.#wi,this.#Mi,this.#Pi]}get radius(){return this.#ml}set radius(i){this.#ml=i}get directionX(){return this.#ol}set directionX(i){this.#ol=i}get directionY(){return this.#ul}set directionY(i){this.#ul=i}get directionZ(){return this.#ll}set directionZ(i){this.#ll=i}get direction(){return[this.#ol,this.#ul,this.#ll]}set direction(i){this.#ol=i[0],this.#ul=i[1],this.#ll=i[2]}get innerCutoff(){return this.#gl}set innerCutoff(i){this.#gl=i}get outerCutoff(){return this.#xl}set outerCutoff(i){this.#xl=i}get innerCutoffCos(){return Math.cos(this.#gl*Math.PI/180)}get outerCutoffCos(){return Math.cos(this.#xl*Math.PI/180)}setPosition(i,g,x){Array.isArray(i)?[this.#wi,this.#Mi,this.#Pi]=i:(this.#wi=i,this.#Mi=g,this.#Pi=x)}lookAt(i,g,x){let v,_,y;Array.isArray(i)?[v,_,y]=i:(v=i,_=g,y=x);const b=v-this.#wi,S=_-this.#Mi,w=y-this.#Pi,L=Math.sqrt(b*b+S*S+w*w);L>0&&(this.#ol=b/L,this.#ul=S/L,this.#ll=w/L)}}Object.freeze(SpotLight);class LightManager{#vl=3;#_l=W.MAX_CLUSTER_LIGHTS;#yl=[];#bl=[];#Sl=[];#Tl;#wl=create$4();get spotLights(){return this.#Sl}get spotLightCount(){return this.#Sl.length}get limitClusterLightCount(){return this.#_l}get pointLights(){return this.#bl}get pointLightCount(){return this.#bl.length}get limitDirectionalLightCount(){return this.#vl}get directionalLightCount(){return this.#yl.length}get directionalLights(){return this.#yl}get ambientLight(){return this.#Tl}set ambientLight(i){i instanceof AmbientLight||consoleAndThrowError("allow only AmbientLight instance"),this.#Tl=i}addSpotLight(i){i instanceof SpotLight||consoleAndThrowError("allow only SpotLight instance");this.#Sl.length+this.#bl.length>=this.#_l&&consoleAndThrowError("Cannot add more cluster lights. The limit has been reached."),this.#Sl.push(i)}addPointLight(i){i instanceof PointLight||consoleAndThrowError("allow only PointLight instance");this.#Sl.length+this.#bl.length>=this.#_l&&consoleAndThrowError("Cannot add more cluster lights. The limit has been reached."),this.#bl.push(i)}addDirectionalLight(i){i instanceof DirectionalLight||consoleAndThrowError("allow only DirectionalLight instance");this.#yl.length>=this.#vl&&consoleAndThrowError("Cannot add more directional lights. The limit has been reached."),this.#yl.push(i)}removeSpotLight(i){const g=this.#Sl.indexOf(i);-1!==g&&this.#Sl.splice(g,1)}removePointLight(i){const g=this.#bl.indexOf(i);-1!==g&&this.#bl.splice(g,1)}removeDirectionalLight(i){const g=this.#yl.indexOf(i);-1!==g&&this.#yl.splice(g,1)}removeAllSpotLight(){this.#Sl=[]}removeAllPointLight(){this.#bl=[]}removeAllDirectionalLight(){this.#yl=[]}removeAllLight(){this.removeAllPointLight(),this.removeAllSpotLight(),this.removeAllDirectionalLight(),this.#Tl=null}getDirectionalLightProjectionViewMatrix(i){return multiply$4(create$4(),this.getDirectionalLightProjectionMatrix(i),this.getDirectionalLightViewMatrix(i))}getDirectionalLightProjectionMatrix(i){const g=create$4(),x=i.rawCamera instanceof Camera2D?fromValues$3(0,0,0):fromValues$3(i.rawCamera.x,i.rawCamera.y,i.rawCamera.z),v=Math.max(distance$2(x,create$3()),1);return Dt(g,-v,v,-v,v,3*-v,3*v),g}getDirectionalLightViewMatrix(i){identity$1(this.#wl);const g=i.rawCamera instanceof Camera2D?fromValues$3(0,0,0):fromValues$3(i.rawCamera.x,i.rawCamera.y,i.rawCamera.z),x=Math.max(distance$2(g,create$3()),1),v=fromValues$3(0,1,0),_=fromValues$3(0,0,0),{directionalLights:y}=i.scene.lightManager,b=y.length?fromValues$3(-y[0].direction[0]*x,-y[0].direction[1]*x,-y[0].direction[2]*x):create$3(),S=create$4();return lookAt(S,b,_,v),S}}Object.freeze(LightManager);class DirectionalShadowManager{#Ml=2048;#Pl=.005;#Rl;#Cl;#Bl;#Dl;#h;#Su=[];#H=0;get videoMemorySize(){return this.#H}get castingList(){return this.#Su}get shadowDepthTextureView(){return this.#Cl}get shadowDepthTextureViewEmpty(){return this.#Dl}get bias(){return this.#Pl}set bias(i){validatePositiveNumberRange(i,0,1),this.#Pl=i}get shadowDepthTextureSize(){return this.#Ml}set shadowDepthTextureSize(i){validateUintRange(i,1),this.#Ml=i}reset(){this.destroy()}resetCastingList(){this.#Su.length=0}update(i){this.#h=i,this.#El()}destroy(){const{commandEncoderManager:i}=this.#h;this.#Rl&&(i.addDeferredDestroy(this.#Rl),this.#Rl=null,this.#Cl=null),this.#Bl&&(i.addDeferredDestroy(this.#Bl),this.#Bl=null,this.#Dl=null)}#ci(){const i=this.#Rl;if(!i)return 0;this.#H=calculateTextureByteSize(i)}#El(){this.#Rl?.width!==this.#Ml&&(this.destroy(),this.#Il(),this.#ci())}#Al(i){this.#Bl=i.createTexture({size:[1,1,1],usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING,format:"depth32float",label:`DirectionalShadowManager_EmptyDepthTexture_1x1_${Date.now()}`}),this.#Dl=this.#Bl.createView({label:this.#Bl.label})}#Il(){const{gpuDevice:i,resourceManager:g}=this.#h;this.#Rl=g.createManagedTexture({size:[this.#Ml,this.#Ml,1],usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING,format:"depth32float",label:`DirectionalShadowManager_shadowDepthTextureSize_${this.#Ml}x${this.#Ml}_${Date.now()}`}),this.#Cl=this.#Rl.createView({label:this.#Rl.label}),this.#Dl||this.#Al(i)}}Object.freeze(DirectionalShadowManager);class ShadowManager{#Ll=new DirectionalShadowManager;#Ul;constructor(){}get directionalShadowManager(){return this.#Ll}get shadowPassDescriptor(){return this.#Ul}render(i){if(0===this.#Ll.castingList.length)return;const{redGPUContext:g}=i,x=this.#Ll.castingList;let v=0;const _=x.length;for(;v<_;v++){const i=x[v],{gpuRenderInfo:g}=i;g&&!g.shadowPipeline&&(g.shadowPipeline=g.vertexStructInfo.vertexEntries.includes("entryPointShadowVertex")?createBasePipeline(i,g.vertexShaderModule,g.vertexBindGroupLayout,fn):null)}this.#Ul={label:`${i.name} Shadow Render Pass`,colorAttachments:[],depthStencilAttachment:{view:this.#Ll.shadowDepthTextureView,depthClearValue:1,depthLoadOp:z.CLEAR,depthStoreOp:q.STORE}},g.commandEncoderManager.addMainRenderPass(this.shadowPassDescriptor,g=>{updateViewportAndScissor(i,g,"SHADOW"),this.#Ll.castingList.length&&((i,g)=>{const{renderViewStateData:x,scene:v}=i;x.currentRenderPassEncoder=g;const{shadowManager:_}=v,{directionalShadowManager:y}=_,{castingList:b}=y;renderListForLayer(b,x,"shadowPipeline")})(i,g)}),this.#Ll.resetCastingList()}update(i){this.#Ll.update(i)}}Object.freeze(ShadowManager);class Scene extends Object3DContainer{#kl=new ColorRGBA;#Gl=!1;#Ol=new LightManager;#Vl=new ShadowManager;#Nl;constructor(i){super(),i&&(this.name=i)}get lightManager(){return this.#Ol}get shadowManager(){return this.#Vl}get physicsEngine(){return this.#Nl}set physicsEngine(i){this.#Nl=i}get backgroundColor(){return this.#kl}set backgroundColor(i){i instanceof ColorRGBA||consoleAndThrowError("allow only ColorRGBA instance"),this.#kl=i}get useBackgroundColor(){return this.#Gl}set useBackgroundColor(i){this.#Gl=i}}const validateNumberRange=(i,g=-Number.MAX_VALUE,x=Number.MAX_VALUE)=>(("number"!=typeof i||Number.isNaN(i))&&consoleAndThrowError("Only numbers allowed."),("number"!=typeof g||Number.isNaN(g))&&consoleAndThrowError("Only numbers allowed."),("number"!=typeof x||Number.isNaN(x))&&consoleAndThrowError("Only numbers allowed."),(ix)&&consoleAndThrowError(`Only numbers within the range of [${g}, ${x}] are allowed. input : ${i}`),!0);class PerspectiveCamera extends ACamera{#Fl=new Float32Array([0,1,0]);#Ti=create$4();#wi=0;#Pi=0;#Mi=0;#ys=0;#bs=0;#Ss=0;#Hl=60;#zl=.1;#$l=5e4;constructor(){super()}get rotationX(){return this.#ys}set rotationX(i){this.#ys=i}get rotationY(){return this.#bs}set rotationY(i){this.#bs=i}get rotationZ(){return this.#Ss}set rotationZ(i){this.#Ss=i}get fieldOfView(){return this.#Hl}set fieldOfView(i){validateNumber(i),this.#Hl=i}get nearClipping(){return this.#zl}set nearClipping(i){validateNumber(i),this.#zl=i}get farClipping(){return this.#$l}set farClipping(i){validateNumber(i),this.#$l=i}get viewMatrix(){return this.#Ti}get x(){return this.#wi}set x(i){this.#wi=i,this.#Ti[12]=i}get y(){return this.#Mi}set y(i){this.#Mi=i,this.#Ti[13]=i}get z(){return this.#Pi}set z(i){this.#Pi=i,this.#Ti[14]=i}get position(){return[this.#wi,this.#Mi,this.#Pi]}setPosition(i,g,x){Array.isArray(i)?[this.#wi,this.#Mi,this.#Pi]=i:(this.#wi=i,this.#Mi=g,this.#Pi=x),[this.#Ti[12],this.#Ti[13],this.#Ti[14]]=[this.#wi,this.#Mi,this.#Pi]}lookAt(i,g,x){const v=[this.#wi,this.#Mi,this.#Pi],_=[i,g,x],y=[this.#Fl[0],this.#Fl[1],this.#Fl[2]],b=[_[0]-v[0],_[1]-v[1],_[2]-v[2]],S=Math.sqrt(b[0]*b[0]+b[1]*b[1]+b[2]*b[2]);b[0]/=S,b[1]/=S,b[2]/=S;const w=[b[1]*y[2]-b[2]*y[1],b[2]*y[0]-b[0]*y[2],b[0]*y[1]-b[1]*y[0]];Math.sqrt(w[0]*w[0]+w[1]*w[1]+w[2]*w[2])<1e-4&&(y[2]=b[1]>0?1:-1,y[0]=0,y[1]=0),lookAt(this.#Ti,v,_,y)}}class OrthographicCamera extends PerspectiveCamera{#jl=1;#Kl=-1;#Xl=-1;#ql=1;#Yl=1;#Wl=.1;#Zl=10;constructor(){super(),this.nearClipping=.01,this.farClipping=1e4}get top(){return this.#jl}set top(i){validateNumber(i),this.#jl=i}get bottom(){return this.#Kl}set bottom(i){validateNumber(i),this.#Kl=i}get left(){return this.#Xl}set left(i){validateNumber(i),this.#Xl=i}get right(){return this.#ql}set right(i){validateNumber(i),this.#ql=i}get zoom(){return this.#Yl}set zoom(i){validateNumberRange(i,this.#Wl,this.#Zl),this.#Yl=i}get minZoom(){return this.#Wl}set minZoom(i){validateNumberRange(i,.01),this.#Wl=i}get maxZoom(){return this.#Zl}set maxZoom(i){validateNumberRange(i,.01),this.#Zl=i}setZoom(i){this.zoom=i}}class AController extends RedGPUObject{static#Jl=null;static#Ql=null;#ec;#tc;#rc=-1;#ic=0;#nc=new Set;#ac=!1;#sc=null;#oc=!1;#uc;#lc=0;#cc=0;#hc=0;#fc=!1;constructor(i,g){super(i),this.#tc=g||{},this.#ec=g.camera||new PerspectiveCamera;const x=this.redGPUContext.detector.isMobile;this.#uc={moveKey:x?"touchmove":"mousemove",upKey:x?"touchend":"mouseup",downKey:x?"touchstart":"mousedown"},this.#dc()}get camera(){return this.#ec}get x(){return this.camera.x}get y(){return this.camera.y}get z(){return this.camera.z}get hoveredView(){return this.#sc}get keyboardActiveView(){return AController.#Jl}set keyboardActiveView(i){AController.#Jl=i,AController.#Ql=null===i?null:this}get isKeyboardActiveController(){return AController.#Ql===this}get keyboardProcessedThisFrame(){return this.#ac}set keyboardProcessedThisFrame(i){this.#ac=i}destroy(){const{moveKey:i,upKey:g,downKey:x}=this.#uc,{htmlCanvas:v}=this.redGPUContext;v.removeEventListener(x,this.#mc),v.removeEventListener(i,this.#pc),v.removeEventListener(i,this.#gc),window.removeEventListener(g,this.#xc),this.#tc.HD_Wheel&&v.removeEventListener("wheel",this.#vc)}update(i,g,x){this.#rc!==g&&(this.#ic=-1===this.#rc?0:(g-this.#rc)/1e3,this.#rc=g,this.#nc.clear(),this.#ac=!1),this.#nc.has(i)||(this.#nc.add(i),this.#tc.useKeyboard&&this.keyboardActiveView&&this.keyboardActiveView!==i||x?.(this.#ic))}checkKeyboardInput(i,g){if(this.keyboardProcessedThisFrame)return!1;const{keyboardKeyBuffer:x}=i.redGPUContext;let v=!1;for(const i in g)if(x[g[i]]){v=!0;break}if(!v)return this.keyboardActiveView=null,!1;if(!this.keyboardActiveView){if(this.hoveredView!==i)return!1;this.keyboardActiveView=i}return this.keyboardActiveView===i&&(this.keyboardProcessedThisFrame=!0,!0)}getCanvasEventPoint=(i,g)=>{const x=g.detector.isMobile,v=g.boundingClientRect,_="clientX",y="clientY";let b,S;if(x){const g=i instanceof WheelEvent?i:i.changedTouches[0];b=g[_],S=g[y]}else{const g=i;b=g[_],S=g[y]}return{x:b-v.left,y:S-v.top}};findTargetViewByInputEvent=i=>{const{redGPUContext:g}=this,{renderScale:x,viewList:v}=g,{x:_,y:y}=this.getCanvasEventPoint(i,g),b=window.devicePixelRatio*x,S=_*b,w=y*b;let L=null;for(const i of v){const g=i.pixelRectObject;g.x{if(i.length<2)return 0;const g=i[0].clientX-i[1].clientX,x=i[0].clientY-i[1].clientY;return Math.sqrt(g*g+x*x)};#dc(){const{redGPUContext:i}=this,{htmlCanvas:g}=i,{downKey:x,moveKey:v}=this.#uc;g.addEventListener(x,this.#mc),g.addEventListener(v,this.#pc),this.#tc.HD_Wheel&&g.addEventListener("wheel",this.#vc,{passive:!1}),this.#tc.HD_TouchPinch&&g.addEventListener("touchmove",this.#yc,{passive:!1})}#pc=i=>{AController.#Jl||this.#oc||(this.#sc=this.findTargetViewByInputEvent(i))};#mc=i=>{const g=this.findTargetViewByInputEvent(i);if(!g)return;AController.#Jl||this.#oc||(this.#sc=g);const{redGPUContext:x}=this,{moveKey:v,upKey:_}=this.#uc,{x:y,y:b}=this.getCanvasEventPoint(i,x);this.#lc=y,this.#cc=b,i instanceof TouchEvent&&(i.touches.length>=2?(this.#fc=!0,this.#hc=this.#_c(i.touches)):(this.#fc=!1,this.#hc=0)),this.#nc.has(g)&&(this.#oc=!0,AController.#Jl=g,x.htmlCanvas.addEventListener(v,this.#gc),window.addEventListener(_,this.#xc))};#gc=i=>{if(i instanceof TouchEvent&&i.touches.length>=2)return void(this.#fc=!0);this.#fc=!1;const{x:g,y:x}=this.getCanvasEventPoint(i,this.redGPUContext),v=g-this.#lc,_=x-this.#cc;this.#lc=g,this.#cc=x,this.#tc.HD_Move?.(v,_)};#yc=i=>{if(i.touches.length<2||!this.#tc.HD_TouchPinch)return;if(!this.#fc)return;i.preventDefault();const g=this.#_c(i.touches);if(0===this.#hc)return void(this.#hc=g);if(this.findTargetViewByInputEvent(i).rawCamera!==this.#ec)return;const x=g/this.#hc;this.#tc.HD_TouchPinch?.(x),this.#hc=g};#xc=()=>{const{htmlCanvas:i}=this.redGPUContext,{moveKey:g,upKey:x}=this.#uc;this.#fc=!1,this.#hc=0,this.#oc=!1,i.removeEventListener(g,this.#gc),window.removeEventListener(x,this.#xc)};#vc=i=>{const g=this.findTargetViewByInputEvent(i);g&&g.rawCamera===this.#ec&&(i.stopPropagation(),i.preventDefault(),this.#tc.HD_Wheel?.(i))}}const Yn=create$4(),computeViewFrustumPlanes=(i,g)=>{multiply$4(Yn,i,g);const x=[[Yn[3]-Yn[0],Yn[7]-Yn[4],Yn[11]-Yn[8],Yn[15]-Yn[12]],[Yn[3]+Yn[0],Yn[7]+Yn[4],Yn[11]+Yn[8],Yn[15]+Yn[12]],[Yn[3]+Yn[1],Yn[7]+Yn[5],Yn[11]+Yn[9],Yn[15]+Yn[13]],[Yn[3]-Yn[1],Yn[7]-Yn[5],Yn[11]-Yn[9],Yn[15]-Yn[13]],[Yn[3]-Yn[2],Yn[7]-Yn[6],Yn[11]-Yn[10],Yn[15]-Yn[14]],[Yn[3]+Yn[2],Yn[7]+Yn[6],Yn[11]+Yn[10],Yn[15]+Yn[14]]];for(let i=0;i<6;i++){const g=x[i],v=Math.sqrt(g[0]*g[0]+g[1]*g[1]+g[2]*g[2]);g[0]/=v,g[1]/=v,g[2]/=v,g[3]/=v}return x};class ViewTransform extends RedGPUObject{onResize=null;#bc=create$4();#Sc=create$4();#ec;#wi=0;#Mi=0;#Gt;#Ot;#Vt=[0,0,0,0];#Tc=0;#wc=0;constructor(i){super(i),this.setSize("100%","100%")}get camera(){return this.#ec}set camera(i){i instanceof PerspectiveCamera||i instanceof Camera2D||i instanceof OrthographicCamera||i instanceof AController||consoleAndThrowError("allow PerspectiveCamera or OrthographicCamera or AController instance"),this.#ec=i}get x(){return this.#wi}set x(i){this.setPosition(i,this.y)}get y(){return this.#Mi}set y(i){this.setPosition(this.x,i)}get width(){return this.#Gt}set width(i){this.setSize(i,this.#Ot)}get height(){return this.#Ot}set height(i){this.setSize(this.#Gt,i)}get pixelRectArray(){return this.#Vt}get pixelRectObject(){return{x:this.#Vt[0],y:this.#Vt[1],width:this.#Vt[2],height:this.#Vt[3]}}get screenRectObject(){return{x:this.#Vt[0]/devicePixelRatio,y:this.#Vt[1]/devicePixelRatio,width:this.#Vt[2]/devicePixelRatio,height:this.#Vt[3]/devicePixelRatio}}get aspect(){return this.#Vt[2]/this.#Vt[3]}get frustumPlanes(){return this.#ec instanceof AController?computeViewFrustumPlanes(this.projectionMatrix,this.#ec.camera.viewMatrix):computeViewFrustumPlanes(this.projectionMatrix,this.#ec.viewMatrix)}get rawCamera(){return this.#ec instanceof AController?this.#ec.camera:this.#ec}get noneJitterProjectionMatrix(){const{pixelRectObject:i,redGPUContext:g}=this;if(this.rawCamera instanceof OrthographicCamera){const{nearClipping:i,farClipping:g}=this.rawCamera;orthoZO(this.#Sc,this.rawCamera.left,this.rawCamera.right,this.rawCamera.bottom,this.rawCamera.top,i,g)}else if(this.rawCamera instanceof Camera2D)Dt(this.#Sc,-.5,.5,-.5,.5,-1e5,1e5),scale$4(this.#Sc,this.#Sc,[g.renderScale,g.renderScale,1]),translate(this.#Sc,this.#Sc,[-.5,.5,0]),scale$4(this.#Sc,this.#Sc,[1/i.width*window.devicePixelRatio,-1/i.height*window.devicePixelRatio,1]);else{const{fieldOfView:i,nearClipping:g,farClipping:x}=this.rawCamera;Bt(this.#Sc,Math.PI/180*i,this.aspect,g,x)}return this.#Sc}get projectionMatrix(){const{redGPUContext:i}=this,{antialiasingManager:g}=i;this.#bc=clone$4(this.noneJitterProjectionMatrix);if("View3D"===this.constructor.name&&"IsometricController"!==this.camera.constructor.name&&g.useTAA&&this.rawCamera instanceof PerspectiveCamera&&(0!==this.#Tc||0!==this.#wc)){const i=this.#Tc/this.pixelRectObject.width*2,g=this.#wc/this.pixelRectObject.height*2;this.#bc[8]+=i,this.#bc[9]+=g}return this.#bc}get inverseProjectionMatrix(){return invert$1(create$4(),this.#bc)}get jitterOffset(){return[this.#Tc,this.#wc]}setJitterOffset(i,g){this.#Tc=i,this.#wc=g}clearJitterOffset(){this.#Tc=0,this.#wc=0}setPosition(i=this.#wi,g=this.#Mi){const{sizeManager:x}=this.redGPUContext;RedGPUContextSizeManager.validatePositionValue(i),RedGPUContextSizeManager.validatePositionValue(g),this.#wi=i,this.#Mi=g;const v=x.pixelRectObject,_=RedGPUContextSizeManager.getPixelDimension(v,"width",i),y=RedGPUContextSizeManager.getPixelDimension(v,"height",g);this.#Vt[0]=Math.round(_*(this.#wi.toString().includes("%")?1:x.renderScale*window.devicePixelRatio)),this.#Vt[1]=Math.round(y*(this.#Mi.toString().includes("%")?1:x.renderScale*window.devicePixelRatio))}setSize(i=this.#Gt,g=this.#Ot){const{sizeManager:x}=this.redGPUContext;RedGPUContextSizeManager.validateSizeValue(i),RedGPUContextSizeManager.validateSizeValue(g),this.#Gt=i,this.#Ot=g;const v=x.pixelRectObject,_=RedGPUContextSizeManager.getPixelDimension(v,"width",i),y=RedGPUContextSizeManager.getPixelDimension(v,"height",g);this.#Vt[2]=Math.max(1,Math.round(_*(this.#Gt.toString().includes("%")?1:x.renderScale*window.devicePixelRatio))),this.#Vt[3]=Math.max(1,Math.round(y*(this.#Ot.toString().includes("%")?1:x.renderScale*window.devicePixelRatio))),this.onResize&&this.onResize({target:this,screenRectObject:this.screenRectObject,pixelRectObject:this.pixelRectObject})}}Object.freeze(ViewTransform);class AView extends ViewTransform{#Mc;#Pc;#Rc=!0;#Cc=!1;#Bc=50;#Dc;#Ec;#Ic;#Ac;constructor(i,g,x,v){super(i),this.scene=g,this.camera=x,this.#Pc=new PickingManager(this),v&&(this.name=v)}get scene(){return this.#Mc}set scene(i){i instanceof Scene||consoleAndThrowError("allow only Scene instance"),this.#Mc=i}get pickingManager(){return this.#Pc}get useFrustumCulling(){return this.#Rc}set useFrustumCulling(i){this.#Rc=i}get useDistanceCulling(){return this.#Cc}set useDistanceCulling(i){this.#Cc=i}get distanceCulling(){return this.#Bc}set distanceCulling(i){this.#Bc=i}get grid(){return this.#Dc}set grid(i){if("boolean"==typeof i)i=!0===i?new DrawDebuggerGrid(this.redGPUContext):null;else if(!(i instanceof DrawDebuggerGrid)&&null!==i)throw new TypeError("grid must be of type 'DrawDebuggerGrid', 'boolean', or 'null'.");this.#Dc=i}get axis(){return this.#Ec}set axis(i){if("boolean"==typeof i)i=!0===i?new DrawDebuggerAxis(this.redGPUContext):null;else if(!(i instanceof DrawDebuggerAxis)&&null!==i)throw new TypeError("axis must be of type 'DrawDebuggerAxis', 'boolean', or 'null'.");this.#Ec=i}get fxaa(){return this.#Ac||(this.#Ac=new FXAA(this.redGPUContext)),this.#Ac}get taa(){return this.#Ic||(this.#Ic=new TAA(this.redGPUContext)),this.#Ic}screenToWorld(i,g){return screenToWorld(i,g,this)}checkMouseInViewBounds(){const{pixelRectObject:i,pickingManager:g}=this,{mouseX:x,mouseY:v}=g;return 00&&(this.prevTimestamp+=this.numFixedSteps*x),this.elapsed=i-this.timestamp,this.time=i/1e3,this.deltaTime=this.elapsed/1e3,this.sinTime=Math.sin(this.time),this.timestamp=i,this.viewRenderStartTime=i}}const Wn="depthTexture0",Zn="depthTexture1",Jn=GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC,Qn={[Ri.COLOR]:{format:"rgba16float",usage:Jn|GPUTextureUsage.STORAGE_BINDING,withResolve:!0,useMipmap:!1},[Ri.MOTION_VECTOR]:{format:"rgba16float",usage:Jn,withResolve:!0,useMipmap:!1},[Ri.NORMAL]:{usage:Jn,withResolve:!0,useMipmap:!1},[Ri.RENDER_PATH1_RESULT]:{format:"rgba16float",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,withResolve:!1,useMipmap:!0}};class ViewRenderTextureManager extends RedGPUObject{#H=0;#Ri;#Uc=new Map;#ls;#kc;#Gc;constructor(i){super(i.redGPUContext),this.#Ri=i}get gBuffers(){return this.#Uc}get videoMemorySize(){return this.#H}get renderPath1ResultTextureDescriptor(){return this.#Uc.get(Ri.RENDER_PATH1_RESULT)?.textureDescriptor}get depthTexture(){return this.#Qt(),this.#Ri.renderViewStateData.swapBufferIndex?this.#Uc.get(Zn)?.texture:this.#Uc.get(Wn)?.texture}get depthTextureView(){return this.#Qt(),this.#Ri.renderViewStateData.swapBufferIndex?this.#Uc.get(Zn)?.textureView:this.#Uc.get(Wn)?.textureView}get prevDepthTextureView(){return this.#Qt(),this.#Ri.renderViewStateData.swapBufferIndex?this.#Uc.get(Wn)?.textureView:this.#Uc.get(Zn)?.textureView}get depthTexture0View(){return this.#Qt(),this.#Uc.get(Wn)?.textureView}get depthTexture1View(){return this.#Qt(),this.#Uc.get(Zn)?.textureView}get renderPath1ResultTextureView(){return this.getGBufferTextureView(Ri.RENDER_PATH1_RESULT)}get renderPath1ResultTexture(){return this.getGBufferTexture(Ri.RENDER_PATH1_RESULT)}getGBufferTexture(i){return this.#Qt(),this.#Uc.get(i)?.texture}getGBufferResolveTexture(i){return this.#Qt(),this.#Uc.get(i)?.resolveTexture}getGBufferTextureView(i){return this.#Qt(),this.#Uc.get(i)?.textureView}getGBufferResolveTextureView(i){return this.#Qt(),this.#Uc.get(i)?.resolveTextureView}#Qt(){const{antialiasingManager:i}=this,{msaaID:g}=i,{pixelRectObject:x,renderViewStateData:v}=this.#Ri;this.#kc={width:Math.max(x.width,1),height:Math.max(x.height,1),depthOrArrayLayers:1},this.#Gc=`${this.#kc.width}x${this.#kc.height}`;const _=this.#Uc.get(Ri.RENDER_PATH1_RESULT)?.texture,y=_?.width!==this.#kc.width||_?.height!==this.#kc.height,b=this.#ls!==g;if(y||b||!_){this.#ls=g,v.swapBufferIndex=0,this.#Il(Wn),this.#Il(Zn);for(const i in Ri)this.#Oc(Ri[i]);this.#Vc()}}#Vc(){const i=[];this.#Uc.forEach(g=>{g.texture&&i.push(g.texture),g.resolveTexture&&i.push(g.resolveTexture)}),this.#H=i.reduce((i,g)=>i+calculateTextureByteSize(g),0)}#Nc(i){const g=this.#Uc.get(i);if(g){const{texture:x,resolveTexture:v}=g;g.texture=null,g.textureView=null,g.resolveTexture=null,g.resolveTextureView=null,this.#Uc.delete(i);const{commandEncoderManager:_}=this;x&&_.addDeferredDestroy(x),v&&_.addDeferredDestroy(v)}}#Fc(i,g,x,v=!1,_=1){const{antialiasingManager:y,resourceManager:b}=this,{useMSAA:S}=y,w={texture:null,textureView:null,textureDescriptor:null},{name:L}=this.#Ri,k=S&&1===_?4:1,H={size:this.#kc,sampleCount:k,label:`${L}_${i}_texture_${this.#Gc}`,format:g,usage:k>1?x&~GPUTextureUsage.STORAGE_BINDING:x,mipLevelCount:_},z=b.createManagedTexture(H);if(w.textureDescriptor=H,w.texture=z,w.textureView=b.getGPUResourceBitmapTextureView(z),v&&S){const v={size:this.#kc,sampleCount:1,label:`${L}_${i}_resolveTexture_${this.#Gc}`,format:g,usage:x},_=b.createManagedTexture(v);w.resolveTextureDescriptor=v,w.resolveTexture=_,w.resolveTextureView=b.getGPUResourceBitmapTextureView(_)}return w}#Oc(i){g(`새 텍스처 생성 중: ${i}`);let x=Qn[i]?.format||navigator.gpu.getPreferredCanvasFormat(),{usage:v,withResolve:_,useMipmap:y}=Qn[i],b=y?getMipLevelCount(this.#kc.width,this.#kc.height):1;this.#Nc(i),this.#Uc.set(i,this.#Fc(i,x,v,_,b))}#Il(i){this.#Nc(i),g(`새 텍스처 생성 중: ${i}`);const x=GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC;this.#Uc.set(i,this.#Fc(i,"depth32float",x,!1))}}Object.freeze(ViewRenderTextureManager);const ea={LINEAR:"linear",KHRONOS_PBR_NEUTRAL:"khronosPBRNeutral",ACES_FILMIC_HILL:"ACESFilmicHill",ACES_FILMIC_NARKOWICZ:"ACESFilmicNarkowicz"};Object.freeze(ea);var ta="#redgpu_include color.linearToSrgbVec3 struct Uniforms{contrast:f32,brightness:f32,_pad:f32,_pad2:f32,};fn linearToneMapping(color:vec3)->vec3{return color;}fn khronosPBRNeutralToneMapping(color:vec3)->vec3{let startCompression:f32=0.8-.04;let desaturation:f32=0.15;var col=color;let x=min(col.r,min(col.g,col.b));var offset:f32;if(x<.08){offset=x-6.25*x*x;}else{offset=.04;}col=col-vec3(offset);let peak=max(col.r,max(col.g,col.b));if(peak(.0),vec3(1.0));}let d=1.0-startCompression;let newPeak=1.0-d*d/(peak+d-startCompression);col=col*(newPeak/peak);let g=1.0-1.0/(desaturation*(peak-newPeak)+1.0);return clamp(mix(col,vec3(newPeak),g),vec3(.0),vec3(1.0));}fn acesFilmicNarkowiczToneMapping(color:vec3)->vec3{let x=color;let a=2.51;let b=.03;let c=2.43;let d=0.59;let e=0.14;return clamp((x*(a*x+b))/(x*(c*x+d)+e),vec3(.0),vec3(1.0));}fn acesFilmicHillToneMapping(color:vec3)->vec3{let v=color;let a1=v.r*0.59719+v.g*0.35458+v.b*.04823;let a2=v.r*.07600+v.g*0.90834+v.b*.01566;let a3=v.r*.02840+v.g*0.13383+v.b*0.83777;let a=vec3(a1,a2,a3);let b=(a*(a+.0245786)-.000090537)/(a*(0.983729*a+0.4329510)+0.238081);let r=b.r*1.60475-b.g*0.53108-b.b*.07367;let g=b.r*-0.10208+b.g*1.10813-b.b*.00605;let bl=b.r*-.00327-b.g*.07276+b.b*1.07602;return clamp(vec3(r,g,bl),vec3(.0),vec3(1.0));}fn getFinalSRGB(toneMappedColor:vec3,contrast:f32,brightness:f32)->vec3{let contrastRGB=applyContrast(toneMappedColor,contrast);let finalLinearRGB=applyBrightness(contrastRGB,brightness);let finalSRGB=clamp(linearToSrgbVec3(finalLinearRGB),vec3(.0),vec3(1.0));return finalSRGB;}fn applyContrast(color:vec3,contrast:f32)->vec3{return 0.5+contrast*(color-0.5);}fn applyBrightness(color:vec3,brightness:f32)->vec3{return color+brightness;}";function createSetter$1(i,g,x,v){return function(_){validateNumber(_),void 0!==x&&_v&&(console.warn(`Value for ${i} exceeds the maximum (${v}). Received: ${_}. Adjusted to ${v}.`),_=v),this[g]=_,updateTargetUniform(this,i,_)}}function defineNumber_func(i){const{key:g,value:x=0,min:v,max:_}=i,y=Symbol(g);return{get:function(){return void 0===this[y]&&(this[y]=x),this[y]},set:createSetter$1(g,y,v,_),...vi}}const defineNumber=(i,g)=>applyProperties(i,g,defineNumber_func);Object.freeze(defineNumber);class AToneMappingEffect extends ASinglePassPostEffect{constructor(i){super(i)}}defineNumber(AToneMappingEffect,[{key:"contrast",value:5,min:.5,max:20},{key:"brightness",value:0,min:-1,max:1}]),Object.freeze(AToneMappingEffect);class ToneLinear extends AToneMappingEffect{constructor(i){super(i),this.init(i,"POST_EFFECT_TONE_MAPPING_LINEAR",createBasicPostEffectCode(this,"{let index=vec2(global_id.xy);let inputColor=textureLoad(sourceTexture,index,0);let toneMappedColor=linearToneMapping(inputColor.rgb);let finalSRGB=getFinalSRGB(toneMappedColor,uniforms.contrast,uniforms.brightness);textureStore(outputTexture,index,vec4(finalSRGB,inputColor.a));}",ta))}}Object.freeze(ToneLinear);class ToneKhronosPBRNeutral extends AToneMappingEffect{constructor(i){super(i),this.init(i,"POST_EFFECT_TONE_MAPPING_KHRONOS_PBR_NEUTRAL",createBasicPostEffectCode(this,"{let index=vec2(global_id.xy);let inputColor=textureLoad(sourceTexture,index,0);let toneMappedColor=khronosPBRNeutralToneMapping(inputColor.rgb);let finalSRGB=getFinalSRGB(toneMappedColor,uniforms.contrast,uniforms.brightness);textureStore(outputTexture,index,vec4(finalSRGB,inputColor.a));}",ta))}}Object.freeze(ToneKhronosPBRNeutral);class ToneACESFilmicNarkowicz extends AToneMappingEffect{constructor(i){super(i),this.init(i,"POST_EFFECT_TONE_MAPPING_ACES_FILMIC_NARKOWICZ",createBasicPostEffectCode(this,"{let index=vec2(global_id.xy);let inputColor=textureLoad(sourceTexture,index,0);let toneMappedColor=acesFilmicNarkowiczToneMapping(inputColor.rgb);let finalSRGB=getFinalSRGB(toneMappedColor,uniforms.contrast,uniforms.brightness);textureStore(outputTexture,index,vec4(finalSRGB,inputColor.a));}",ta))}}Object.freeze(ToneACESFilmicNarkowicz);class ToneACESFilmicHill extends AToneMappingEffect{constructor(i){super(i),this.init(i,"POST_EFFECT_TONE_MAPPING_ACES_FILMIC_HILL",createBasicPostEffectCode(this,"{let index=vec2(global_id.xy);let inputColor=textureLoad(sourceTexture,index,0);let toneMappedColor=acesFilmicHillToneMapping(inputColor.rgb);let finalSRGB=getFinalSRGB(toneMappedColor,uniforms.contrast,uniforms.brightness);textureStore(outputTexture,index,vec4(finalSRGB,inputColor.a));}",ta))}}Object.freeze(ToneACESFilmicHill);class ToneMappingManager{#h;#Hc;#zc=ea.KHRONOS_PBR_NEUTRAL;#$c=1;#jc=0;constructor(i){this.#h=i}get redGPUContext(){return this.#h}get toneMapping(){return this.#Kc(),this.#Hc}get mode(){return this.#zc}set mode(i){this.#zc!==i&&(this.#zc=i,this.clear())}get contrast(){return this.#$c}set contrast(i){this.#$c=i,this.#Hc&&(this.#Hc.contrast=i)}get brightness(){return this.#jc}set brightness(i){this.#jc=i,this.#Hc&&(this.#Hc.brightness=i)}clear(){this.#Hc&&(this.#Hc.clear(),this.#Hc=void 0)}render(i,g,x,v){const _=this.toneMapping;return _?_.render(i,g,x,v):v}#Kc(){if(this.#Hc)return;const{redGPUContext:i}=this;switch(this.#zc){case ea.LINEAR:this.#Hc=new ToneLinear(i);break;case ea.KHRONOS_PBR_NEUTRAL:this.#Hc=new ToneKhronosPBRNeutral(i);break;case ea.ACES_FILMIC_NARKOWICZ:this.#Hc=new ToneACESFilmicNarkowicz(i);break;case ea.ACES_FILMIC_HILL:this.#Hc=new ToneACESFilmicHill(i);break;default:this.#Hc=new ToneKhronosPBRNeutral(i)}this.#Hc&&(this.#Hc.contrast=this.#$c,this.#Hc.brightness=this.#jc)}}Object.freeze(ToneMappingManager);class DrawDebuggerPointLight extends ADrawDebuggerLight{constructor(i,g){super(i,g,"💡",[0,255,255],51)}render(i){const{lightDebugMesh:g,label:x,target:v}=this;i.view.systemUniform_Vertex_UniformBindGroup&&v.enableDebugger&&(this.#su(v,g.geometry.vertexBuffer),g.render(i),x.setPosition(...v.position))}#su(i,g){const x=i.position||[0,0,0],v=i.radius||1,_=16,y=[];for(let i=0;i<_;i++){const g=i/_*Math.PI*2,b=(i+1)/_*Math.PI*2,S=x[0]+Math.cos(g)*v,w=x[1]+Math.sin(g)*v,L=x[2],k=x[0]+Math.cos(b)*v,H=x[1]+Math.sin(b)*v,z=x[2];y.push([[S,w,L],[k,H,z]])}for(let i=0;i<_;i++){const g=i/_*Math.PI*2,b=(i+1)/_*Math.PI*2,S=x[0]+Math.cos(g)*v,w=x[1],L=x[2]+Math.sin(g)*v,k=x[0]+Math.cos(b)*v,H=x[1],z=x[2]+Math.sin(b)*v;y.push([[S,w,L],[k,H,z]])}for(let i=0;i<_;i++){const g=i/_*Math.PI*2,b=(i+1)/_*Math.PI*2,S=x[0],w=x[1]+Math.cos(g)*v,L=x[2]+Math.sin(g)*v,k=x[0],H=x[1]+Math.cos(b)*v,z=x[2]+Math.sin(b)*v;y.push([[S,w,L],[k,H,z]])}const b=.2*v;y.push([[x[0]-b,x[1],x[2]],[x[0]+b,x[1],x[2]]]),y.push([[x[0],x[1]-b,x[2]],[x[0],x[1]+b,x[2]]]),y.push([[x[0],x[1],x[2]-b],[x[0],x[1],x[2]+b]]),this.updateVertexBuffer(y,g)}}Object.freeze(DrawDebuggerPointLight);class DrawDebuggerSpotLight extends ADrawDebuggerLight{constructor(i,g){super(i,g,"🔦",[255,255,0],80)}render(i){const{lightDebugMesh:g,label:x,target:v}=this;i.view.systemUniform_Vertex_UniformBindGroup&&v.enableDebugger&&(this.#su(v,g.geometry.vertexBuffer),g.render(i),x.setPosition(...v.position))}#su(i,g){const x=i.position||[0,0,0],v=i.direction||[0,-1,0],_=i.radius||5,y=i.outerCutoff||22.5,b=i.innerCutoff||15,S=[],w=Math.sqrt(v[0]*v[0]+v[1]*v[1]+v[2]*v[2]),L=[v[0]/w,v[1]/w,v[2]/w],k=[x[0]+L[0]*_,x[1]+L[1]*_,x[2]+L[2]*_],H=_*Math.tan(y*Math.PI/180),z=_*Math.tan(b*Math.PI/180);let q=[0,1,0];Math.abs(L[1])>.99&&(q=[1,0,0]);const W=[L[1]*q[2]-L[2]*q[1],L[2]*q[0]-L[0]*q[2],L[0]*q[1]-L[1]*q[0]],be=Math.sqrt(W[0]*W[0]+W[1]*W[1]+W[2]*W[2]),je=[W[0]/be,W[1]/be,W[2]/be],Ke=[je[1]*L[2]-je[2]*L[1],je[2]*L[0]-je[0]*L[2],je[0]*L[1]-je[1]*L[0]],Xe=16;for(let i=0;i{const x=W.getDispatchSize();g.setPipeline(this.#Wc),g.setBindGroup(0,i),g.setBindGroup(1,this.#Yc),g.dispatchWorkgroups(x[0],x[1],x[2])})}}#Zc(){const{gpuDevice:i,resourceManager:g}=this,x=parseWGSL("PASS_CLUSTER_LIGHT_BOUND",ra+"#redgpu_include SYSTEM_UNIFORM;@group(1)@binding(0)varclusterBoundsGrid:ClusterBoundsGrid;fn lineIntersectionToZPlane(a:vec3,b:vec3,zDistance:f32)->vec3{let normal=vec3(.0,.0,0.5);let ab=b-a;let t=(zDistance-dot(normal,a))/dot(normal,ab);return a+t*ab;}fn clipToView(clip:vec4)->vec4{let view=systemUniforms.projection.inverseProjectionMatrix*clip;return view/vec4(view.w,view.w,view.w,view.w);}fn screen2View(screen:vec4)->vec4{let texCoord=screen.xy/systemUniforms.resolution.xy;let clip=vec4(vec2(texCoord.x,1.0-texCoord.y)*2.0-vec2(1.0,1.0),screen.z,screen.w);return clipToView(clip);}const eyePos=vec3(.0);@compute @workgroup_size(REDGPU_DEFINE_WORKGROUP_SIZE_X,REDGPU_DEFINE_WORKGROUP_SIZE_Y,REDGPU_DEFINE_WORKGROUP_SIZE_Z)fn main(@builtin(global_invocation_id)global_id:vec3){let tileIndex=global_id.x+global_id.y*clusterLight_tileCount.x+global_id.z*clusterLight_tileCount.x*clusterLight_tileCount.y;let tileSize=vec2(systemUniforms.resolution.x/f32(clusterLight_tileCount.x),systemUniforms.resolution.y/f32(clusterLight_tileCount.y));let global_id_x_pos_one=vec2(f32(global_id.x+1u),f32(global_id.y+1u))*tileSize;let global_id_x_y=vec2(f32(global_id.x),f32(global_id.y))*tileSize;let maxPoint_sS=vec4(global_id_x_pos_one,.0,1.0);let minPoint_sS=vec4(global_id_x_y,.0,1.0);let maxPoint_vS=screen2View(maxPoint_sS).xyz;let minPoint_vS=screen2View(minPoint_sS).xyz;let nearFarX=systemUniforms.camera.nearClipping;let nearFarY=systemUniforms.camera.farClipping;let tileZ=f32(global_id.z)/f32(clusterLight_tileCount.z);let tileZ_plus_one=f32(global_id.z+1u)/f32(clusterLight_tileCount.z);let tileNear=-nearFarX*pow(nearFarY/nearFarX,tileZ);let tileFar=-nearFarX*pow(nearFarY/nearFarX,tileZ_plus_one);let minPointNear=lineIntersectionToZPlane(eyePos,minPoint_vS,tileNear);let minPointFar=lineIntersectionToZPlane(eyePos,minPoint_vS,tileFar);let maxPointNear=lineIntersectionToZPlane(eyePos,maxPoint_vS,tileNear);let maxPointFar=lineIntersectionToZPlane(eyePos,maxPoint_vS,tileFar);let minAABB=min(min(minPointNear,minPointFar),min(maxPointNear,maxPointFar));let maxAABB=max(max(minPointNear,minPointFar),max(maxPointNear,maxPointFar));clusterBoundsGrid.cubeList[tileIndex].minAABB=vec4(minAABB,.0);clusterBoundsGrid.cubeList[tileIndex].maxAABB=vec4(maxAABB,.0);}").defaultSource;this.#Xc=g.createGPUBuffer("PASS_CLUSTER_BOUND_BUFFER",{size:32*W.getTotalTileSize(),usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),this.#qc=i.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}}]}),this.#Yc=i.createBindGroup({label:"CLUSTER_BOUND_BIND_GROUP",layout:this.#qc,entries:[{binding:0,resource:{buffer:this.#Xc}}]}),this.#Wc=i.createComputePipeline({label:"CLUSTER_BOUND_PIPELINE",layout:i.createPipelineLayout({bindGroupLayouts:[g.getGPUBindGroupLayout(ResourceManager.PRESET_GPUBindGroupLayout_System),this.#qc]}),compute:{module:g.createGPUShaderModule("CLUSTER_BOUND_SHADER",{code:x}),entryPoint:"main"}})}}Object.freeze(PassClusterLightBound);const ia=new Uint32Array([0,0,0,0]);class PassClustersLight extends RedGPUObject{#Ri;#Jc;#Qc;#eh;constructor(i,g){super(i),this.#Ri=g,this.#Zc()}get clusterLightsBuffer(){return this.#eh}render(){const i=this.#Ri.systemUniform_Vertex_UniformBindGroup;if(i){const{commandEncoderManager:g,gpuDevice:x}=this;g.addPreProcessComputePass("PassClustersLight_ComputePass",g=>{const v=W.getDispatchSize();x.queue.writeBuffer(this.clusterLightsBuffer,0,ia),g.setPipeline(this.#Qc),g.setBindGroup(0,i),g.setBindGroup(1,this.#Jc),g.dispatchWorkgroups(v[0],v[1],v[2])})}}#Zc(){const{gpuDevice:i,resourceManager:g}=this,x=parseWGSL("PASS_CLUSTERS_LIGHT",ra+"#redgpu_include SYSTEM_UNIFORM;@group(1)@binding(0)varclusterBoundsGrid:ClusterBoundsGrid;fn pointLight_testSphereAABB(light:u32,tile:u32)->bool{let targetLight=clusterLightList.lights[light];let targetTile=clusterBoundsGrid.cubeList[tile];let radius:f32=targetLight.radius;let position:vec3=targetLight.position;let center:vec3=(systemUniforms.camera.viewMatrix*vec4(position,1.0)).xyz;let squaredDistance:f32=pointLight_sqDistPointAABB(center,tile,targetTile.minAABB.xyz,targetTile.maxAABB.xyz);return squaredDistance<=(radius*radius);}fn pointLight_sqDistPointAABB(targetPoint:vec3,tile:u32,minAABB:vec3,maxAABB:vec3)->f32{var sqDist=.0;for(var i=0u;i<3u;i=i+1u){let v=targetPoint[i];let _minAABB=minAABB[i];let _maxAABB=maxAABB[i];if(v<_minAABB){sqDist+=(_minAABB-v)*(_minAABB-v);}if(v>_maxAABB){sqDist+=(v-_maxAABB)*(v-_maxAABB);}}return sqDist;}fn spotLight_testSphereAABB(light:u32,tile:u32)->bool{let targetLight=clusterLightList.lights[light];let targetTile=clusterBoundsGrid.cubeList[tile];let radius:f32=targetLight.radius;let position:vec3=targetLight.position;let center:vec3=(systemUniforms.camera.viewMatrix*vec4(position,1.0)).xyz;let squaredDistance:f32=pointLight_sqDistPointAABB(center,tile,targetTile.minAABB.xyz,targetTile.maxAABB.xyz);return squaredDistance<=(radius*radius);}@compute @workgroup_size(REDGPU_DEFINE_WORKGROUP_SIZE_X,REDGPU_DEFINE_WORKGROUP_SIZE_Y,REDGPU_DEFINE_WORKGROUP_SIZE_Z)fn main(@builtin(global_invocation_id)global_id:vec3){let tileIndex=global_id.x+global_id.y*clusterLight_tileCount.x+global_id.z*clusterLight_tileCount.x*clusterLight_tileCount.y;var clusterLightCount=0u;var clusterLightIndices:array;for(var i=0u;i-1){let i=!0,g=this.#mh[q];const v=b?.skyAtmosphereReflectionLUT,_=b?.skyAtmosphereIrradianceLUT;g&&(i=g.ibl!==y||g.skyAtmosphere!==b||g.skyAtmosphereReflectionLUT!==v||g.skyAtmosphereReflectionLUTRevision!==v?.revision||g.skyAtmosphereIrradianceLUT!==_||g.skyAtmosphereIrradianceLUTRevision!==_?.revision||g.ibl_prefilterTexture!==L||g.ibl_irradianceTexture!==k||g.renderPath1ResultTextureView!==x||g.shadowDepthTextureView!==H||!this.#yh.passClustersLight),i?this.#Sh(q,H,this.ibl,x):this.#ah=this.#mh[q].vertexUniformBindGroup,this.#mh[q]={ibl:y,skyAtmosphere:b,skyAtmosphereReflectionLUT:v,skyAtmosphereReflectionLUTRevision:v?.revision,skyAtmosphereIrradianceLUT:_,skyAtmosphereIrradianceLUTRevision:_?.revision,ibl_prefilterTexture:L,ibl_irradianceTexture:k,renderPath1ResultTextureView:x,shadowDepthTextureView:H,vertexUniformBindGroup:this.#ah}}this.#Th()}#Th(){const{inverseProjectionMatrix:i,noneJitterProjectionMatrix:g,projectionMatrix:x,rawCamera:v}=this;v.updateExposure(this);const{redGPUContext:_,systemUniform_Vertex_UniformBuffer:y}=this,{gpuDevice:b}=_,{lightManager:S,shadowManager:w}=this.scene,{viewMatrix:L}=v,k=this.systemUniform_Vertex_StructInfo,{members:H}=k;{this.#_h=multiply$4(sa,g,L);const y=multiply$4(aa,x,L);SystemUniformUpdater.updateCamera(v,H.camera.members,this.#vn,this.#_n),SystemUniformUpdater.updateShadow(w,H.shadow.members,this.#vn,this.#_n),SystemUniformUpdater.updateSkyAtmosphere(this.skyAtmosphere,H,this.#vn,this.#_n),SystemUniformUpdater.updateDirectionalLights(S.directionalLights,H.directionalLights.memberList,this.#vn,this.#_n),SystemUniformUpdater.updateAmbientLight(S.ambientLight,H.ambientLight.members,this.#vn,this.#_n),SystemUniformUpdater.updateTime(this.renderViewStateData,H.time.members,this.#vn,this.#_n),SystemUniformUpdater.updateProjection({projectionMatrix:x,projectionViewMatrix:y,noneJitterProjectionMatrix:g,noneJitterProjectionViewMatrix:this.#_h,inverseProjectionMatrix:i,inverseProjectionViewMatrix:invert$1(oa,y),prevNoneJitterProjectionViewMatrix:_.antialiasingManager.useTAA?this.taa.prevNoneJitterProjectionViewMatrix:this.#_h},H.projection.members,this.#vn,this.#_n),updateSystemUniformData(H,this.#vn,this.#_n,[{key:"resolution",value:[this.pixelRectObject.width,this.pixelRectObject.height]},{key:"usePrefilterTexture",value:this.ibl?.prefilterTexture?.gpuTexture?1:0},{key:"isView3D",value:this.constructor===View3D?1:0},{key:"directionalLightCount",value:S.directionalLightCount},{key:"iblIntensity",value:this.ibl?this.ibl.luminance*this.ibl.intensityMultiplier:1},{key:"directionalLightProjectionViewMatrix",value:S.getDirectionalLightProjectionViewMatrix(this)},{key:"directionalLightProjectionMatrix",value:S.getDirectionalLightProjectionMatrix(this)},{key:"directionalLightViewMatrix",value:S.getDirectionalLightViewMatrix(this)},{key:"preExposure",value:this.postEffectManager.autoExposure.preExposure}])}S.directionalLights.forEach(i=>{i.enableDebugger&&(i.drawDebugger||(i.drawDebugger=new DrawDebuggerDirectionalLight(_,i)),i.drawDebugger.render(this.renderViewStateData))}),b.queue.writeBuffer(y.gpuBuffer,0,this.#xn)}#Sh(i,g,x,v){this.#yh.updateClusterLights();const _=x?.prefilterTexture,y=x?.irradianceTexture,{redGPUContext:b}=this,{gpuDevice:S,resourceManager:w}=b,L={layout:w.getGPUBindGroupLayout(ResourceManager.PRESET_GPUBindGroupLayout_System),label:`SYSTEM_UNIFORM_bindGroup_${i}`,entries:[{binding:0,resource:{buffer:this.#sh.gpuBuffer,offset:0,size:this.#sh.size}},{binding:1,resource:this.#ph},{binding:2,resource:g},{binding:3,resource:this.#tt},{binding:5,resource:{buffer:this.#yh.clusterLightsBuffer,offset:0,size:this.#yh.clusterLightsBuffer.size}},{binding:6,resource:{buffer:this.#yh.passClustersLight.clusterLightsBuffer,offset:0,size:this.#yh.passClustersLight.clusterLightsBuffer.size}},{binding:7,resource:this.#tt},{binding:8,resource:v||w.emptyBitmapTextureView},{binding:9,resource:this.#gh},{binding:10,resource:w.getGPUResourceCubeTextureView(_,_?.viewDescriptor||CubeTexture.defaultViewDescriptor)},{binding:11,resource:w.getGPUResourceCubeTextureView(y,y?.viewDescriptor||CubeTexture.defaultViewDescriptor)},{binding:12,resource:w.brdfGenerator.brdfLUTTexture?.createView()||w.emptyBitmapTextureView},{binding:13,resource:this.skyAtmosphere?this.skyAtmosphere.atmosphereSampler.gpuSampler:this.#tt},{binding:14,resource:this.skyAtmosphere?this.skyAtmosphere.transmittanceLUT.gpuTextureView:w.emptyBitmapTextureView},{binding:15,resource:w.getGPUResourceCubeTextureView(this.skyAtmosphere?.skyAtmosphereIrradianceLUT,this.skyAtmosphere?.skyAtmosphereIrradianceLUT?.viewDescriptor||CubeTexture.defaultViewDescriptor)},{binding:16,resource:w.getGPUResourceCubeTextureView(this.skyAtmosphere?.skyAtmosphereReflectionLUT,this.skyAtmosphere?.skyAtmosphereReflectionLUT?.viewDescriptor||CubeTexture.defaultViewDescriptor)}]};this.#ah=S.createBindGroup(L),this.#wh(w,_,y)}#wh(i,g,x){[[this.#xh,g],[this.#vh,x]].forEach(([g,x])=>{g&&g!==x&&this.#bh(i,g.cacheKey,!1),x&&g!==x&&this.#bh(i,x.cacheKey,!0)}),this.#xh=g,this.#vh=x}#bh(i,g,x){const v=i.managedCubeTextureState,_=v?.table.get(g);_&&(x?_.useNum++:_.useNum--)}#N(){const i=new ArrayBuffer(na.arrayBufferByteLength);this.#sh=new UniformBuffer(this.redGPUContext,i,"SYSTEM_UNIFORM_BUFFER_VERTEX","SYSTEM_UNIFORM_BUFFER_VERTEX"),this.#ph=new Sampler(this.redGPUContext,{addressModeU:v.CLAMP_TO_EDGE,addressModeV:v.CLAMP_TO_EDGE,addressModeW:v.CLAMP_TO_EDGE,compare:Er.LESS_EQUAL}).gpuSampler,this.#tt=new Sampler(this.redGPUContext).gpuSampler,this.#gh=new Sampler(this.redGPUContext,{addressModeU:v.REPEAT,addressModeV:v.REPEAT}).gpuSampler}}Object.freeze(View3D);class RedGPUContextViewContainer{#Mh=[];constructor(){}get viewList(){return this.#Mh}get numViews(){return this.#Mh.length}contains(i){return this.#Mh.includes(i)}addView(i){this.#Ph(i),this.#Mh.push(i)}addViewAt(i,g){this.#Ph(i),validateUintRange(g);const x=this.#Mh.length;x=x,_=this.#Mh.indexOf(i);-1===_&&consoleAndThrowError("입력하신 View 는 RedGPUContext instance 에 등록되지 않은 View 입니다."),v&&consoleAndThrowError(`index must be smaller than the viewList length. / index : ${g} / this.#viewList.length : ${x}`),this.#Mh.splice(_,1),this.#Mh.splice(g,0,i)}swapViews(i,g){this.#Ph(i),this.#Ph(g);const x=this.#Mh.indexOf(i),v=this.#Mh.indexOf(g);-1!==x&&-1!==v||consoleAndThrowError((-1===x?"view1":"view2")+" is not child of this RedGPUContext instance."),this.swapViewsAt(x,v)}swapViewsAt(i,g){i===g&&consoleAndThrowError("The indices to swap cannot be the same."),validateUintRange(i),validateUintRange(g);const x=this.#Mh.length;(i>=x||g>=x)&&consoleAndThrowError(`index1, index2 must be smaller than the viewList length. / index1 : ${i} / index2 : ${g} / this.#viewList.length : ${x}`);const v=this.#Mh[i];this.#Mh[i]=this.#Mh[g],this.#Mh[g]=v}removeView(i){this.#Ph(i);const g=this.#Mh.indexOf(i);g>-1?this.#Mh.splice(g,1):consoleAndThrowError("View3D is not found in the view list.")}removeViewAt(i){validateUintRange(i);const g=this.#Mh.length;i{const _=v.beginRenderPass(i);g(_),_.end(),x&&x(v)},"Immediate Submitted Render Pass")}async immediateComputePass(i,g,x){const v=this.#kh(i),_=v.label||"RedGPU_Immediate_Compute_Encoder";await this.#Uh(_,i=>{const _=i.beginComputePass(v);g(_),_.end(),x&&x(i)},"Immediate Submitted Compute Pass")}async immediateSubmit(i,g){await this.#Uh(i,g,"Immediate Submitted Commands")}submit(i){if(this.#Ch[i])throw new Error(`[RedGPU] Cannot submit ${i} phase while a pass is still active.`);const g=this.#Gh(i);if(g.length>0){this.gpuDevice.queue.submit(g);const x=this.#Oh(i,g.length);return this.#Vh(i),this.#Nh(),x}return this.#Nh(),null}submitAll(){const i=[],g={};if([k.RESOURCE,k.PRE_PROCESS,k.MAIN,k.POST_PROCESS].forEach(x=>{if(this.#Ch[x])throw new Error(`[RedGPU] Cannot submit ${x} phase while a pass is still active.`);const v=this.#Gh(x);i.push(...v),g[x]=this.#Oh(x,v.length),this.#Vh(x)}),i.length>0){this.gpuDevice.queue.submit(i);const x=this.#Nh();return{phases:g,deferredDestroyCount:x}}const x=this.#Nh();return x>0?{phases:g,deferredDestroyCount:x}:null}resetAll(){this.#Rh.clear(),this.#Bh.clear(),this.#Nh(),Object.keys(this.#Ch).forEach(i=>{delete this.#Ch[i]})}#Nh(){const i=this.#Dh.length;if(i>0){let g=0;for(;g"string"==typeof i?{label:i}:i;#Oh(i,g){const x=this.#Bh.get(i)||{renderPasses:[],computePasses:[],rawUsages:0};return{Phase:i,"Command Buffers":g,"Render Passes":{count:x.renderPasses.length,list:x.renderPasses},"Compute Passes":{count:x.computePasses.length,list:x.computePasses},"Raw Usages":x.rawUsages}}#Lh(i,g,x){this.#Bh.has(i)||this.#Bh.set(i,{renderPasses:[],computePasses:[],rawUsages:0});const v=this.#Bh.get(i);"rawUsages"===g?v.rawUsages++:v[g].push(x||"unlabeled")}#Vh(i){this.#Bh.set(i,{renderPasses:[],computePasses:[],rawUsages:0})}#Gh(i){const g=this.#Rh.get(i);if(g&&g.length>0){const x=g.map(i=>i.finish());return this.#Rh.set(i,[]),delete this.#Ch[i],x}return[]}}class RedGPUContextObserver extends RedGPUObject{#Nt;#Fh;#Hh=null;#zh=null;#$h=null;#jh=null;constructor(i,g){super(i),this.#Nt=i.htmlCanvas,this.#Fh=g,this.#N()}stop(){this.#$h?.disconnect(),this.#zh?.disconnect(),this.#jh?.disconnect()}#N(){this.#$h=new MutationObserver(i=>{for(const g of i)"childList"===g.type&&this.#Hh!==this.#Nt.parentElement&&this.#Kh()}),"undefined"!=typeof document&&this.#$h.observe(document.body,{childList:!0,subtree:!0}),this.#jh=new IntersectionObserver(()=>{this.#Xh()},{threshold:[0,1]}),this.#jh.observe(this.#Nt),window.addEventListener("resize",()=>this.#Xh()),this.#Kh()}#Kh(){const i=this.#Nt.parentElement;this.#Hh!==i&&(this.#zh&&(this.#zh.disconnect(),this.#zh=null),this.#Hh=i,this.#Hh&&(this.#zh=new ResizeObserver(()=>{this.#Xh()}),this.#zh.observe(this.#Hh))),this.#Xh()}#Xh(){this.#Fh(),this.redGPUContext.sizeManager.setSize()}}class RedGPUContext extends RedGPUContextViewContainer{currentRequestAnimationFrame;onResize=null;currentTime;#qh;#yt;#Yh;#Wh;#f;#Nt;#Zh;#Jh;#Qh;#ef;#tf;#kl=new ColorRGBA(0,0,0,1);#rf={};#if;#nf;constructor(i,g,x,v,_){super(),this.#yt=g,this.#f=x,this.#Wh=v,this.#Yh=_,this.#Nt=i,this.#Zh=new RedGPUContextSizeManager(this),this.#Jh=new RedGPUContextDetector(this),this.#Qh=new ResourceManager(this),this.#ef=new CommandEncoderManager(this),this.#tf=new AntialiasingManager,this.#af()}get commandEncoderManager(){return this.#ef}get boundingClientRect(){return this.#if}get antialiasingManager(){return this.#tf}get backgroundColor(){return this.#kl}set backgroundColor(i){i instanceof ColorRGBA||consoleAndThrowError("allow only ColorRGBA instance"),this.#kl=i}get detector(){return this.#Jh}get configurationDescription(){return this.#qh}get gpuAdapter(){return this.#yt}get alphaMode(){return this.#Yh}set alphaMode(i){this.#Yh=i,this.#sf()}get gpuContext(){return this.#Wh}get gpuDevice(){return this.#f}get htmlCanvas(){return this.#Nt}get keyboardKeyBuffer(){return this.#rf}set keyboardKeyBuffer(i){this.#rf=i}get resourceManager(){return this.#Qh}get sizeManager(){return this.#Zh}get width(){return this.#Zh.width}set width(i){this.#Zh.width=i}get height(){return this.#Zh.height}set height(i){this.#Zh.height=i}get screenRectObject(){return this.#Zh.screenRectObject}get pixelRectObject(){return this.#Zh.pixelRectObject}get renderScale(){return this.#Zh.renderScale}set renderScale(i){this.#Zh.renderScale=i,this.viewList.forEach(i=>{i.setPosition(),i.setSize()})}destroy(){this.#nf?.stop(),this.#f.destroy()}setSize(i=this.width,g=this.height){this.sizeManager.setSize(i,g)}#of(){this.#if=this.#Nt.getBoundingClientRect()}#af(){this.#sf(),this.#of(),this.sizeManager.setSize("100%","100%"),this.#nf=new RedGPUContextObserver(this,()=>this.#of());(this.detector.isMobile?["click","touchmove","touchstart","touchend"]:["click","mousemove","mousedown","mouseup"]).forEach(g=>{const x=this.detector.isMobile?{click:i.CLICK,touchmove:i.MOVE,touchstart:i.DOWN,touchend:i.UP}:{click:i.CLICK,mousemove:i.MOVE,mousedown:i.DOWN,mouseup:i.UP};this.#Nt.addEventListener(g,g=>{const v=x[g.type];this.viewList.forEach(x=>{this.detector.isMobile&&g instanceof TouchEvent&&g.touches.length>0?(x.pickingManager.mouseX=g.touches[0].clientX-x.pixelRectObject.x,x.pickingManager.mouseY=g.touches[0].clientY-x.pixelRectObject.y):g instanceof MouseEvent&&(x.pickingManager.mouseX=g.offsetX-x.pixelRectObject.x,x.pickingManager.mouseY=g.offsetY-x.pixelRectObject.y),v===i.CLICK?x.pickingManager.lastMouseClickEvent={...g,type:v}:x.pickingManager.lastMouseEvent={...g,type:v}})})});{const HD_keyDown=i=>{this.#rf[i.key]=!0},HD_keyUp=i=>{this.#rf[i.key]=!1};window?.addEventListener("keyup",HD_keyUp),window?.addEventListener("keydown",HD_keyDown)}}#sf(){const i=navigator.gpu.getPreferredCanvasFormat();this.#qh={device:this.#f,format:i,alphaMode:this.#Yh},this.#Wh.configure(this.#qh)}}Object.freeze(RedGPUContext);const init=async(i,x,v,_,y="premultiplied",b={powerPreference:"high-performance",forceFallbackAdapter:!1})=>{if(isSearchEngineBot())return void g("🤖 Search engine bot detected - skipping WebGPU initialization");const{gpu:S}=navigator;if(!S){const i="WebGPU is not supported in this browser. Please use a modern browser with WebGPU enabled.";return void v?.(i)}const errorHandler=(i,g)=>{const x=generateErrorMessage(i,g);console.error("\n============\n",x,"\n============\n"),v?.(x)},validateAndRequestDevice=async g=>{const x=[];[].forEach(i=>{g?.features.has(i)&&x.push(i)});const v={};["maxBufferSize","maxStorageBufferBindingSize","maxSampledTexturesPerShaderStage","maxSamplersPerShaderStage","maxStorageBuffersPerShaderStage","maxStorageTexturesPerShaderStage","maxUniformBuffersPerShaderStage","maxUniformBufferBindingSize","maxBindGroups","maxVertexAttributes","maxVertexBuffers","maxInterStageShaderComponents","maxComputeWorkgroupStorageSize","maxComputeInvocationsPerWorkgroup","maxComputeWorkgroupSizeX","maxComputeWorkgroupSizeY","maxComputeWorkgroupSizeZ","maxComputeWorkgroupsPerDimension"].forEach(i=>{g.limits[i]&&(v[i]=g.limits[i])});const _={requiredFeatures:x,requiredLimits:v};try{const x=await g.requestDevice(_);validateAndInitializeContext(i,g,x)}catch(i){errorHandler(null,`Failed to request device. Adapter was ${g}, error message is ${i.message}`)}},validateAndInitializeContext=(i,v,b)=>{const S=i.getContext("webgpu");if(S)try{{const i=b.createShaderModule.bind(b);b.createShaderModule=function(g){return g.code=ensureVertexIndexBuiltin(g.code),i(g)}}const w=new RedGPUContext(i,v,b,S,y);x(w),b.addEventListener("uncapturederror",i=>{console.warn("TODO A WebGPU error was not captured:",i),console.warn(i.error?.message),window.cancelAnimationFrame(w.currentRequestAnimationFrame)}),b.lost.then(i=>{console.warn(i),console.warn(`Device lost occurred: ${i.message}`),"destroyed"===i.reason&&_?.(i)});const clearDevice=()=>{if(w.gpuContext)try{w.gpuContext.unconfigure(),g("🧹 Canvas Context unconfigure 완료")}catch(i){g("⚠️ Canvas Context unconfigure 실패:",i)}window?.cancelAnimationFrame(w.currentRequestAnimationFrame),w.gpuDevice.destroy()};window?.addEventListener("beforeunload",()=>{w&&w.gpuDevice&&(g("🧹 페이지 종료 시 GPU 디바이스 정리"),clearDevice())}),window?.addEventListener("pageshow",i=>{i.persisted&&(g("🔄 bfcache에서 복원됨 (뒤로가기 또는 앞으로가기) - 페이지 재로드"),window.location.reload())}),window?.addEventListener("pagehide",i=>{i.persisted&&(g("💾 bfcache에 저장됨"),w&&w.gpuDevice&&clearDevice())})}catch(i){errorHandler(i,"")}else errorHandler(new Error(`Failed to get context from canvas: ${i.id||i}`),"Failed to get webgpu initialize from canvas")},initializeWebGPU=async()=>{x instanceof Function?i instanceof HTMLCanvasElement?await(async i=>{i||errorHandler(null,"Cannot find navigator.gpu");try{const g=await i.requestAdapter(b);await validateAndRequestDevice(g)}catch(g){errorHandler(g,`Failed to request adapter or validate device with target GPU: ${i}, error message is ${g.message}`)}})(S):errorHandler(null,`Expected HTMLCanvasElement, but received : ${i}`):errorHandler(null,`Expected onWebGPUInitialized, but received : ${x}`)};try{await initializeWebGPU()}catch(i){errorHandler(i,`Unexpected error occurred during WebGPU initialization: ${i.message}`)}},generateErrorMessage=(i,g)=>{let x=g;return i instanceof Error?(x=i.message??g,"string"==typeof i.stack&&(x+=`\nStack Trace: ${i.stack}`)):console.warn("generateErrorMessage function expected an Error instance, but got: ",i),x},isSearchEngineBot=()=>{if("undefined"==typeof navigator||"undefined"==typeof window)return!0;const i=navigator.userAgent.toLowerCase();return["googlebot","bingbot","slurp","duckduckbot","baiduspider","yandexbot","facebookexternalhit","twitterbot","rogerbot","linkedinbot","embedly","quora link preview","showyoubot","outbrain","pinterest/0.","developers.google.com/+/web/snippet","www.google.com/webmasters/tools/richsnippets","slackbot","vkshare","w3c_validator","redditbot","applebot","whatsapp","flipboard","tumblr","bitlybot","skypeuripreview","nuzzel","line","discordbot","telegrambot","crawler","spider","bot"].some(g=>i.includes(g))};class TextureLoaderData{src;texture;loadEnd;loadSuccess;srcInfo;idx;constructor(i,g,x){this.src=i,this.texture=null,this.loadEnd=!1,this.loadSuccess=!1,this.srcInfo=g,this.idx=x}}class TextureLoader extends RedGPUObject{textures=[];#uf=0;#lf;#Oa;#cf;constructor(i,g=[],x,v){super(i),this.#lf=g,this.#Oa=x,this.#cf=v,this.#lf.length?this.#lf.forEach((i,g)=>this.#hf(i,g)):this.#ff()}getTextureByIndex(i){if(this.textures[i])return this.textures[i].texture}#hf(i,g){const{redGPUContext:x}=this;let v,_,y=BitmapTexture;_=i.hasOwnProperty("src")?i.src:i,_ instanceof Array&&(y=CubeTexture),v=new TextureLoaderData(_,i,g);const onLoadHandler=()=>{v.loadSuccess=!0,v.loadEnd=!0,this.#df()},onErrorHandler=()=>{v.loadSuccess=!1,v.loadEnd=!0,this.#df()};v.texture=y===BitmapTexture?new y(x,{src:i.src,cacheKey:i.cacheKey},i.useMipmap,onLoadHandler,onErrorHandler,i.format,!1):new y(x,{src:i.src,cacheKey:i.cacheKey},i.useMipmap,onLoadHandler,onErrorHandler,i.format),this.textures.push(v),this.#mf()}#mf(){const i=this.#lf.length,g=this.#uf;this.#cf&&this.#cf.call(this,{total:i,loaded:g,percent:Math.min(100,parseFloat((g/i*100).toFixed(2)))})}#df(){this.#uf++,this.#mf(),this.#uf===this.#lf.length&&this.#ff()}#ff(){requestAnimationFrame(()=>{this.#Oa&&this.#Oa.call(this,this)})}}const checkProgress=(i,g,x)=>{const v=g.buffers.length;i.loadingProgressInfo.buffers={loaded:x,total:v,percent:Math.min(100,parseFloat((x/v*100).toFixed(2)))}},ua=new Map,la=new Map,arrayBufferLoader=(i,g,x)=>{if(i=getAbsoluteURL(window.location.href,i),ua.has(i))return void g?.(ua.get(i));if(la.has(i))return void la.get(i).then(i=>g?.(i)).catch(i=>x?.(i));const v=fetch(i).then(i=>{if(!i.ok)throw new Error(`Network response was not ok: ${i.statusText}`);return i.arrayBuffer()}).then(g=>(ua.set(i,g),g)).finally(()=>{la.delete(i)});la.set(i,v),v.then(i=>g?.(i)).catch(i=>x?.(i))},ca={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array};Object.freeze(ca);class AccessorInfo_GLTF{accessor;bufferView;bufferGlTfId;buffer;bufferURIDataView;componentType;componentType_BYTES_PER_ELEMENT;getMethod;accessorBufferOffset;bufferViewOffset;bufferViewByteStride;startIndex;constructor(i,g,x){switch(this.accessor=g.accessors[x],this.bufferView=g.bufferViews[this.accessor.bufferView],this.bufferGlTfId=this.bufferView.buffer,this.buffer=g.buffers[this.bufferGlTfId],this.bufferURIDataView=null,this.buffer.uri&&(this.bufferURIDataView=i.parsingResult.uris.buffers[this.bufferGlTfId]),this.componentType=ca[this.accessor.componentType],this.componentType_BYTES_PER_ELEMENT=this.componentType.BYTES_PER_ELEMENT,this.componentType){case Float32Array:this.getMethod="getFloat32";break;case Uint32Array:this.getMethod="getUint32";break;case Uint16Array:this.getMethod="getUint16";break;case Int16Array:this.getMethod="getInt16";break;case Uint8Array:this.getMethod="getUint8";break;case Int8Array:this.getMethod="getInt8";break;default:consoleAndThrowError("파싱할수없는 타입",this.componentType)}this.accessorBufferOffset=this.accessor.byteOffset||0,this.bufferViewOffset=this.bufferView.byteOffset||0,this.bufferViewByteStride=this.bufferView.byteStride||0,this.startIndex=(this.bufferViewOffset+this.accessorBufferOffset)/this.componentType_BYTES_PER_ELEMENT}}class AnimationData_GLTF{gltfLoader;scenesData;accessorGlTfId;dataList;constructor(i,g,x){this.gltfLoader=i,this.scenesData=g,this.accessorGlTfId=x;const v=new AccessorInfo_GLTF(this.gltfLoader,this.scenesData,this.accessorGlTfId),{accessor:_,startIndex:y,componentType_BYTES_PER_ELEMENT:b,bufferURIDataView:S,getMethod:w}=v,{type:L,count:k}=_;let H=y,z=1;switch(L){case"SCALAR":z=1;break;case"VEC4":z=4;break;case"VEC3":z=3}const q=[];let W=0;for(;Wanimation_data_list:array;@group(0)@binding(1)varuniforms:Uniforms;@group(0)@binding(2)varvertices:array;@group(0)@binding(3)varorigin_data:array;@group(0)@binding(4)varmorph_interleave_data:array;@compute @workgroup_size(64)fn main(@builtin(global_invocation_id)global_id:vec3){let vertex_index=global_id.x;let vertex_count=u32(uniforms.vertex_count);let stride=u32(uniforms.vertex_stride);let morph_length=u32(uniforms.morph_length);if(vertex_index>=vertex_count){return;}let base_vertex_index=vertex_index*stride;let base_vertex_index2=vertex_index*3u;let prev_time_offset=u32(uniforms.prev_time_data_index)*morph_length;let next_time_offset=u32(uniforms.next_time_data_index)*morph_length;var prev_weight=origin_data[base_vertex_index];var next_weight=origin_data[base_vertex_index];var prev_weight1=origin_data[base_vertex_index+1u];var next_weight1=origin_data[base_vertex_index+1u];var prev_weight2=origin_data[base_vertex_index+2u];var next_weight2=origin_data[base_vertex_index+2u];for(var morph_index=0u;morph_indexArray.from(i.interleaveData)),S=x.createBuffer({size:4*b.length,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST});x.queue.writeBuffer(y,0,v.origin),x.queue.writeBuffer(S,0,new Float32Array(b));const w=x.createBindGroup({layout:this.#Hr.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:this.#gf}},{binding:1,resource:{buffer:this.#se}},{binding:2,resource:{buffer:_.gpuBuffer}},{binding:3,resource:{buffer:y}},{binding:4,resource:{buffer:S}}]});this.#xf.set(g,{bindGroup:w,originBuffer:y,morphInterleavedBuffer:S})}}const parseAnimations=(i,g)=>new Promise(async x=>{g.animations||(g.animations=[]);const{parsingResult:v}=i,{animations:_}=v,{animations:y}=g;if(y.length){const x=y.map(async x=>{const{samplers:v,channels:y}=x,b=[];b.minTime=1e7,b.maxTime=-1,b.name=x.name,_.push(b),await Promise.all(y.map(async x=>((i,g,x,v,_)=>{let y,b;const{nodes:S,meshes:w}=_,L=[],{sampler:k,target:H}=x,z=v[k],{node:q,path:W}=H,be=S[q];if("mesh"in be){y=be.Mesh;const{primitives:i}=w[be.mesh];let g=i.length;for(;g--;)L.push(i[g].Mesh)}else{let g;if(!i.parsingResult.groups[q])return;g=i.parsingResult.groups[q],y=g}if("scale"!=W&&"rotation"!=W&&"translation"!=W&&"weights"!=W||(b=new AniTrack_GLTF(W,new AnimationData_GLTF(i,_,z.input),new AnimationData_GLTF(i,_,z.output),z.interpolation,y,L),g.push(b)),b){const{timeAnimationInfo:i}=b,{dataList:x}=i;g.minTime>x[0]&&(g.minTime=x[0]),g.maxTimei.playAnimation(g))}x()});class ParsedSkinInfo_GLTF{joints;inverseBindMatrices;skeletonMesh;vertexStorageInfo;vertexStorageBuffer;prevVertexStorageBuffer;invertNodeGlobalTransform;usedJoints=null;WORK_SIZE=64;jointData;uniformBuffer;computeShader;computePipeline;bindGroup;constructor(){this.joints=[],this.inverseBindMatrices=null,this.skeletonMesh=null}getUsedJointIndices(i){const g=new Set,{jointBuffer:x}=i.animationInfo;if(!x.data.length)return[];const v=x.data,_=v.length;for(let i=0;i<_;i++){const x=i;for(let i=0;i<4;i++){const _=Math.floor(v[x+i]);_>=0&&_,\n\t\t\t jointModelMatrices: array, ${this.usedJoints.length}>,\n\t\t\t inverseBindMatrices: array, ${this.joints.length}>,\n\t\t\t searchJointIndexTable: array, ${this.joints.length}>,\n\t\t\t};\n\t\t\t\n\t\t\t@group(0) @binding(0) var vertexWeight: array>;\n\t\t\t@group(0) @binding(1) var vertexJoint: array>;\n\t\t\t@group(0) @binding(2) var skinMatrixBuffer: array>;\n\t\t\t@group(0) @binding(3) var prevSkinMatrixBuffer: array>;\n\t\t\t@group(0) @binding(4) var uniforms: Uniforms;\n\t\t\t\n\t\t\t@compute @workgroup_size(${this.WORK_SIZE},1,1)\n\t\t\tfn main(@builtin(global_invocation_id) global_id: vec3) { \n\t\t\t let idx = global_id.x;\n\t\t\t if (idx >= arrayLength(&vertexWeight)) {\n\t\t\t return;\n\t\t\t }\n\t\t\t\n\t\t\t let weights = vertexWeight[idx];\n\t\t\t let joints = vertexJoint[idx];\n\t\t\t prevSkinMatrixBuffer[idx] = skinMatrixBuffer[idx];\n\t\t\t skinMatrixBuffer[idx] = uniforms.invertNodeGlobalTransform * (\n\t\t\t\t weights.x * (\n\t\t\t\t \tuniforms.jointModelMatrices[uniforms.searchJointIndexTable[joints.x].x] * uniforms.inverseBindMatrices[joints.x]\n\t\t\t\t ) +\n\t\t\t\t weights.y * (\n\t\t\t\t \tuniforms.jointModelMatrices[uniforms.searchJointIndexTable[joints.y].x] * uniforms.inverseBindMatrices[joints.y]\n\t\t\t\t ) +\n\t\t\t\t weights.z * (\n\t\t\t\t \tuniforms.jointModelMatrices[uniforms.searchJointIndexTable[joints.z].x] * uniforms.inverseBindMatrices[joints.z]\n\t\t\t\t ) +\n\t\t\t\t weights.w * (\n\t\t\t\t \tuniforms.jointModelMatrices[uniforms.searchJointIndexTable[joints.w].x] * uniforms.inverseBindMatrices[joints.w]\n\t\t\t\t )\n\t\t\t\t);\n\t\t\t}\n `;this.jointData=new Float32Array(16*(1+this.usedJoints.length)),this.computeShader=i.resourceManager.createGPUShaderModule(`calcSkinMatrix_${this.usedJoints.length}`,{code:y}),this.computePipeline=g.createComputePipeline({label:"calcSkinMatrix",layout:"auto",compute:{module:this.computeShader,entryPoint:"main"}}),this.uniformBuffer=g.createBuffer({size:this.jointData.byteLength+16*this.joints.length*4+4*this.joints.length*4,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),g.queue.writeBuffer(this.uniformBuffer,this.jointData.byteLength,new Float32Array(this.inverseBindMatrices.map(i=>Array.from(i)).flat()));const b=new Uint32Array(4*this.joints.length);b.fill(0),this.usedJoints.forEach((i,g)=>{b[4*i]=g}),g.queue.writeBuffer(this.uniformBuffer,this.jointData.byteLength+16*this.joints.length*4,b),this.bindGroup=g.createBindGroup({layout:this.computePipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:v.gpuBuffer}},{binding:1,resource:{buffer:_.gpuBuffer}},{binding:2,resource:{buffer:this.vertexStorageBuffer}},{binding:3,resource:{buffer:this.prevVertexStorageBuffer}},{binding:4,resource:{buffer:this.uniformBuffer}}]})}}const parseJoint_GLTF=(i,g,x,v)=>{const _=x[v].Mesh;_?g.joints.push(_):requestAnimationFrame(function(){parseJoint_GLTF(i,g,x,v)})},calculateNormals=(i,g)=>{let x,v,_=[],y=g;const b=i.length/3;if(!g||0===g.length){g=[];for(let i=0;i{const y=x.sparse;if(!y)return;const{values:b,indices:S,count:w}=y,L=v.bufferViews,k=L[b.bufferView],H=k.buffer,z=v.buffers,q=z[H],W=[],be=[],je=L[S.bufferView],Ke=je.buffer,Xe=z[Ke];let Ye;q.uri&&(Ye=i.parsingResult.uris.buffers[H]);const Ze=ca[x.componentType],{BYTES_PER_ELEMENT:Je}=Ze;let Qe;switch(Ze){case Float32Array:Qe="getFloat32";break;case Uint32Array:Qe="getUint32";break;case Uint16Array:Qe="getUint16";break;case Int16Array:Qe="getInt16";break;case Uint8Array:Qe="getUint8";break;case Int8Array:Qe="getInt8"}const et=x.byteOffset||0;let tt,it,ft=((k.byteOffset||0)+et)/Je;switch(x.type){case"VEC3":for(tt=ft+Je*w/Je*3;ft{const _=new MorphInfoData_GLTF;for(let v in x){const{vertices:y,verticesColor_0:b,normals:S,uvs:w,uvs1:L,uvs2:k,jointWeights:H,joints:z,tangents:q}=_,W=x[v],be=new AccessorInfo_GLTF(i,g,W),{accessor:je}=be;parseAttributeInfo_GLTF(v,be,y,w,L,0,S,H,z,b,q),je.sparse&&parseSparse_GLTF(i,v,je,g,y)}return v.length&&(_.interleaveData=new Float32Array(_.vertices)),_})),this.weights=v||[],this.origin=null}}const parseMaterialTexture=(i,g,x,v,_,y=!0)=>{const{redGPUContext:b,gltfData:S}=i,{textureRawList:w}=i.parsingResult,L=x.index,k=S.textures[L],H=k.extensions?.EXT_texture_webp?.source||k.source,z=getURL(i,S,H);if(z){const L=k.sampler,q=getSamplerInfo(i,S,L),{parsedURI:W,cacheKey:be}=z,je=`${v}SourceGlTfId_${H}`;if(w[je]?(w[je].materialList.push(g),w[je].samplerList.push(new Sampler(b,q))):w[je]={src:W,cacheKey:be,targetTextureKey:v,targetSamplerKey:`${v}Sampler`,materialList:[g],samplerList:[new Sampler(b,q)],format:_||navigator.gpu.getPreferredCanvasFormat(),useMipmap:y},g[`${v}_texCoord_index`]=x.texCoord||0,"extensions"in x){const{extensions:i}=x,{KHR_texture_transform:_}=i;_&&((i,g,x)=>{i[`${g}_KHR_texture_transform_offset`]=x.offset||[0,0],i[`${g}_KHR_texture_transform_scale`]=x.scale||[1,1],i[`${g}_KHR_texture_transform_rotation`]=x.rotation||0,i[`use_${g}_KHR_texture_transform`]=!0})(g,v,_)}}},getURL=function(i,g,x){if(!g.images[x])return null;const{uri:v}=g.images[x];let _;const y=`${i.url}_${x}`;return _=v.indexOf("blob:http")>-1?v:(v.indexOf(";base64,")>-1?"":i.filePath)+v,{parsedURI:_,cacheKey:y}},getSamplerInfo=function(i,g,x){const _={magFilter:y.LINEAR,minFilter:y.LINEAR,mipmapFilter:y.LINEAR,addressModeU:v.REPEAT,addressModeV:v.REPEAT,addressModeW:v.REPEAT},b={33071:v.CLAMP_TO_EDGE,33648:v.MIRRORED_REPEAT,10497:v.REPEAT},S={9728:y.NEAREST,9729:y.LINEAR},w={9728:y.NEAREST,9729:y.LINEAR};if(g.samplers){let i=g.samplers[x];i&&("magFilter"in i&&(_.magFilter=S[i.magFilter]||y.LINEAR),"minFilter"in i&&(_.minFilter=w[i.minFilter]||y.LINEAR),"wrapS"in i&&(_.addressModeU=b[i.wrapS]),"wrapT"in i&&(_.addressModeV=b[i.wrapT]))}return _.string=JSON.stringify(_),_},parseMaterialInfo_GLTF=(i,g,x)=>{const{redGPUContext:v}=i;let _,y=!1,b="OPAQUE",S=.5;if("material"in x){_=new PBRMaterial(v);const w=x.material,L=g.materials[w];y=!!L.doubleSided,b=L.alphaMode??b,S=L.alphaCutoff??S;const{pbrMetallicRoughness:k,normalTexture:H,emissiveTexture:z,occlusionTexture:q}=L;if(_.emissiveFactor=L.emissiveFactor||[0,0,0],k){const{metallicRoughnessTexture:g,baseColorTexture:x}=k;let v,y;_.baseColorFactor=k.baseColorFactor||[1,1,1,1],"metallicFactor"in k&&(v=k.metallicFactor),"roughnessFactor"in k&&(y=k.roughnessFactor),_.metallicFactor=null!=v?v:1,_.roughnessFactor=null!=y?y:1,x&&parseMaterialTexture(i,_,x,"baseColorTexture",`${navigator.gpu.getPreferredCanvasFormat()}-srgb`),g&&parseMaterialTexture(i,_,g,"metallicRoughnessTexture",null,!1)}if(H){parseMaterialTexture(i,_,H,"normalTexture");const{scale:g}=H;_.normalScale=null!=g?g:1}if(z&&parseMaterialTexture(i,_,z,"emissiveTexture",`${navigator.gpu.getPreferredCanvasFormat()}-srgb`),q&&(parseMaterialTexture(i,_,q,"occlusionTexture",null,!1),_.occlusionStrength=L.occlusionTexture.strength||1),"extensions"in L){const{extensions:g}=L,{KHR_materials_clearcoat:x,KHR_materials_emissive_strength:v,KHR_materials_transmission:y,KHR_materials_diffuse_transmission:S,KHR_materials_volume:w,KHR_materials_unlit:k,KHR_materials_ior:H,KHR_materials_sheen:z,KHR_materials_specular:q,KHR_materials_dispersion:W,KHR_materials_anisotropy:be,KHR_materials_iridescence:je}=g;if(je&&((i,g,x)=>{i.useKHR_materials_iridescence=!0,i.KHR_iridescenceFactor=g.iridescenceFactor||0,i.KHR_iridescenceIor=g.iridescenceIor||1.3,i.KHR_iridescenceThicknessMinimum=g.iridescenceThicknessMinimum||100,i.KHR_iridescenceThicknessMaximum=g.iridescenceThicknessMaximum||400,i.transparent=!0;{const{iridescenceTexture:v,iridescenceThicknessTexture:_}=g;v&&parseMaterialTexture(x,i,v,"KHR_iridescenceTexture",null,!1),_&&parseMaterialTexture(x,i,_,"KHR_iridescenceThicknessTexture",null,!1)}})(_,je,i),be&&((i,g,x)=>{i.useKHR_materials_anisotropy=!0,i.KHR_anisotropyStrength=g.anisotropyStrength||0,i.KHR_anisotropyRotation=g.anisotropyRotation||0;const{anisotropyTexture:v}=g;v&&parseMaterialTexture(x,i,v,"KHR_anisotropyTexture")})(_,be,i),x&&((i,g,x)=>{i.KHR_clearcoatFactor=g.clearcoatFactor||0,i.KHR_clearcoatRoughnessFactor=g.clearcoatRoughnessFactor||0,i.useKHR_materials_clearcoat=!0;const{clearcoatTexture:v,clearcoatNormalTexture:_,clearcoatRoughnessTexture:y}=g;v&&parseMaterialTexture(x,i,v,"KHR_clearcoatTexture",null,!1),_&&parseMaterialTexture(x,i,_,"KHR_clearcoatNormalTexture"),y&&parseMaterialTexture(x,i,y,"KHR_clearcoatRoughnessTexture",null,!1)})(_,x,i),v){const{emissiveStrength:i}=v;_.emissiveStrength=null!=i?i:1}if(y&&(((i,g,x)=>{i.useKHR_materials_transmission=!0,i.KHR_transmissionFactor=g.transmissionFactor||0,i.use2PathRender=!0;{const v=g.transmissionTexture;v&&parseMaterialTexture(x,i,v,"KHR_transmissionTexture",null,!1)}})(_,y,i),_.transparent="BLEND"===b),S&&((i,g,x)=>{i.useKHR_materials_diffuse_transmission=!0,i.KHR_diffuseTransmissionFactor=g.diffuseTransmissionFactor||0,i.KHR_diffuseTransmissionColorFactor=g.diffuseTransmissionColorFactor||[1,1,1],i.transparent=!0;{const v=g.diffuseTransmissionTexture;v&&parseMaterialTexture(x,i,v,"KHR_diffuseTransmissionTexture",null,!1);const _=g.diffuseTransmissionColorTexture;_&&parseMaterialTexture(x,i,_,"KHR_diffuseTransmissionColorTexture",`${navigator.gpu.getPreferredCanvasFormat()}-srgb`,!1)}})(_,S,i),w&&(((i,g,x)=>{i.useKHR_materials_volume=!0,i.KHR_thicknessFactor=g.thicknessFactor||1,i.KHR_attenuationDistance=g.attenuationDistance||1,i.KHR_attenuationColor=g.attenuationColor||[1,1,1],i.use2PathRender=!0,i.transparent=!0;{const v=g.thicknessTexture;v&&parseMaterialTexture(x,i,v,"KHR_thicknessTexture",null,!1)}})(_,w,i),b="BLEND"),k&&(_.useKHR_materials_unlit=!0),H){const{ior:i}=H;_.KHR_materials_ior=null!=i?i:1.5,_.use2PathRender=!0,_.transparent=!0}if(W){const{dispersion:i}=W;_.KHR_dispersion=i||0,_.use2PathRender=!0,_.transparent=!0}z&&((i,g,x)=>{i.KHR_sheenColorFactor=g.sheenColorFactor||[0,0,0],i.KHR_sheenRoughnessFactor=g.sheenRoughnessFactor||0,i.useKHR_materials_sheen=!0;const{sheenColorTexture:v,sheenRoughnessTexture:_}=g;v&&parseMaterialTexture(x,i,v,"KHR_sheenColorTexture",`${navigator.gpu.getPreferredCanvasFormat()}-srgb`,!1),_&&parseMaterialTexture(x,i,_,"KHR_sheenRoughnessTexture",null,!1)})(_,z,i),q&&((i,g,x)=>{i.useKHR_materials_specular=!0,i.KHR_specularFactor=g.specularFactor??1,i.KHR_specularColorFactor=g.specularColorFactor||[1,1,1];const{specularTexture:v,specularColorTexture:_}=g;v&&parseMaterialTexture(x,i,v,"KHR_specularTexture"),_&&parseMaterialTexture(x,i,_,"KHR_specularColorTexture",`${navigator.gpu.getPreferredCanvasFormat()}-srgb`)})(_,q,i)}}else _=new PBRMaterial(v);Object.hasOwn(x.attributes,"COLOR_0")&&(_.useVertexColor=!0),_.doubleSided=y,_.cutOff=S;const{blendColorState:w,blendAlphaState:L}=_;switch(b){case"BLEND":_.alphaBlend=2,w.srcFactor=ui.SRC_ALPHA,w.dstFactor=ui.ONE_MINUS_SRC_ALPHA,L.srcFactor=ui.SRC_ALPHA,L.dstFactor=ui.ONE_MINUS_SRC_ALPHA,_.transparent=!0;break;case"MASK":_.alphaBlend=1,_.useCutOff=!0,w.srcFactor=ui.ONE,w.dstFactor=ui.ZERO,L.srcFactor=ui.ONE,L.dstFactor=ui.ZERO;break;default:w.srcFactor=ui.ONE,w.dstFactor=ui.ZERO,L.srcFactor=ui.ONE,L.dstFactor=ui.ZERO,_.alphaBlend=0}return _},parseIndicesInfo_GLTF=(i,g)=>{const{accessor:x,startIndex:v,getMethod:_,bufferURIDataView:y,componentType_BYTES_PER_ELEMENT:b}=i,{type:S,count:w}=x;let L,k=v;if("SCALAR"===S)for(L=k+w;k{let z,q,W,be,je,Ke,Xe,Ye,Ze,Je=0,Qe=g.length/3,et=0;const tt=g.length,it=v.length,ft=y.length,pt=x.length,xt=S.length,vt=w.length,yt=L.length;if(z=W=Ke=0,q=be=Xe=1,je=Ye=2,Ze=3,k)for(;Je{let x=i[0],v=i[1],_=i[2],y=i[3],b=x+x,S=v+v,w=_+_,L=x*b,k=x*S,H=x*w,z=v*S,q=v*w,W=_*w,be=y*b,je=y*S,Ke=y*w;return g[0]=1-(z+W),g[4]=k-Ke,g[8]=H+je,g[1]=k+Ke,g[5]=1-(L+W),g[9]=q-be,g[2]=H-je,g[6]=q+be,g[10]=1-(L+z),g[3]=0,g[7]=0,g[11]=0,g[12]=0,g[13]=0,g[14]=0,g[15]=1,g},ha=180/Math.PI,setMeshRotation=(i,g)=>{g.setRotation(i[0]*ha,i[1]*ha,i[2]*ha)},parseTRSAndMATRIX_GLTF=(i,g)=>{const{matrix:x,rotation:v,translation:_,scale:y}=g;let b,S;if(b=create$4(),"matrix"in g){S=create$3(),mat4ToEuler(x,S),setMeshRotation(S,i),i.setPosition(x[12],x[13],x[14]);const g=fromValues$3(1,1,1);getScaling(g,x),i.setScale(g[0],g[1],g[2])}else"rotation"in g&&(S=create$3(),quaternionToRotationMat4(v,b),mat4ToEuler(b,S),setMeshRotation(S,i)),"translation"in g&&i.setPosition(_[0],_[1],_[2]),"scale"in g&&(i.setScale(y[0],y[1],y[2]),(y[0]<0||y[1]<0||y[2]<0)&&(i.primitiveState.frontFace=Qi.CW))},parseChildrenAndSkin=(i,g,x,v,_)=>{if("children"in v){const _=v.children,y=_.length;for(let v=0;v{const _=new ParsedSkinInfo_GLTF,y=[],{nodes:b}=g,{joints:S,skeleton:w}=x;{let g=0;const x=S.length;for(;g{const{redGPUContext:_,parsingResult:y}=i,{nodes:b,meshes:S,skins:w}=g,{groups:L,cameras:k}=y,H=b[x];if("mesh"in H){const _=function(i,g,x,v){const{redGPUContext:_}=i;let y;x.name&&(y=x.name);const b=[],{primitives:S}=x;let w=0;const L=S.length;for(;w-1;if(y){const i=`TEXCOORD_${tt.size}`;tt.set(x,i)}parseAttributeInfo_GLTF(y?tt.get(x):x,_,W,je,Ke,0,Ye,Ze,Je,be,Qe),_.accessor.sparse&&parseSparse_GLTF(i,x,_.accessor,g,W)}if("indices"in L){let x=L.indices,v=new AccessorInfo_GLTF(i,g,x);parseIndicesInfo_GLTF(v,q)}H=parseMaterialInfo_GLTF(i,g,L),H instanceof PBRMaterial&&i.parsingResult.materials.push(H);let it,ft=!1;if("mode"in L)switch(L.mode){case 0:z=Ei.POINT_LIST;break;case 1:case 2:z=Ei.LINE_LIST;break;case 3:z=Ei.LINE_STRIP,ft=!0;break;case 4:case 6:z=Ei.TRIANGLE_LIST;break;case 5:z=Ei.TRIANGLE_STRIP,ft=!0}be.length&&(H.useVertexColor_0=!0),it=Ye.length?Ye:calculateNormals(W,q),Qe.length>0||(Qe=Array.from(calculateTangents(W,it,je,q))),Qe.length&&(H.useVertexTangent=!0);let pt,xt=[];parseInterleaveData_GLTF(xt,W,be,it,je,Ke,0,Ze,Je,Qe);let vt={};W.length&&(vt.aVertexPosition=VertexInterleaveType.float32x3),it.length&&(vt.aVertexNormal=VertexInterleaveType.float32x3),je.length&&(vt.aTexcoord=VertexInterleaveType.float32x2),(Xe.length||Ke.length||je.length)&&(vt.aTexcoord1=VertexInterleaveType.float32x2),vt.aVertexColor_0=VertexInterleaveType.float32x4,vt.aVertexTangent=VertexInterleaveType.float32x4;const yt=[],bt=[];parseInterleaveData_GLTF(yt,W,be,it,je,Ke,0,Ze,Je,Qe,!0),parseInterleaveData_GLTF(bt,W,be,it,je,Ke,0,Ze,Je,Qe,!1,!0);const St=new VertexBuffer(_,yt,new VertexInterleavedStruct({aVertexWeight:VertexInterleaveType.float32x4}),void 0,`Weight_${i.url}_${v}_${w}`),Tt=new IndexBuffer(_,bt,GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST,`Joint_${i.url}_${v}_${w}`);let wt=new MorphInfo_GLTF(i,g,L,x.weights);const Mt=`Vertex_${i.url}_${v}_${w}_${wt.weights.length?createUUID():""}`,Pt=_.resourceManager.managedVertexBufferState.table.get(Mt)?.buffer;if(pt=new Geometry(_,Pt||new VertexBuffer(_,xt,new VertexInterleavedStruct(vt,"PBR"),void 0,Mt),!ft&&q.length?new IndexBuffer(_,new Uint32Array(q),void 0,`Index_${i.url}_${v}_${w}`):null),H||consoleAndThrowError("재질을 파싱할수없는경우 ",L),k=new Mesh(_,pt,H),k.animationInfo.weightBuffer=St,k.animationInfo.jointBuffer=Tt,y&&(k.name=y,i.parsingOption))for(let g in i.parsingOption)y.toLowerCase().indexOf(g)>-1&&i.parsingOption[g](k);k.primitiveState.topology=z||Ei.TRIANGLE_LIST,k.material.doubleSided&&(k.primitiveState.cullMode=Ji.NONE),k.material.use2PathRender&&(k.primitiveState.cullMode=Ji.NONE,k.depthStencilState.depthCompare=Er.LESS_EQUAL),2===k.material.alphaBlend&&(k.depthStencilState.depthCompare=Er.LESS_EQUAL),k.animationInfo.morphInfo=wt,k.animationInfo.morphInfo.origin=new Float32Array(xt);let Rt=k.geometry.vertexBuffer.data;k.gpuRenderInfo||k.initGPURenderInfos();let Ct=0;for(const i in vt)Ct+=vt[i].numElements;if(!Pt){const i=k.animationInfo.morphInfo.morphInfoDataList;let g=0;const x=i.length,v=Rt.length;for(;g{x.extensionsUsed?.includes("KHR_draco_mesh_compression")&&alert("RedGPU GLTFLoader does not support the KHR_draco_mesh_compression extension. Models using this extension may not load properly."),requestAnimationFrame(()=>{(i=>{const g=i?.asset;g||consoleAndThrowError("GLTFLoader - asset must be defined"),g.version||consoleAndThrowError("GLTFLoader - asset version must be defined");const x=parseFloat(g.version);isNaN(x)&&consoleAndThrowError("GLTFLoader - asset version must be a numerical value"),x<2&&consoleAndThrowError("GLTFLoader - asset version must be 2.0 or higher")})(x),requestAnimationFrame(()=>{((i,g,x,v)=>{const{parsingResult:_}=i,{uris:y}=_,b="buffers",S=y[b],w=g.buffers,L=w.length;let k=0;checkProgress(i,g,k),w.forEach((_,y)=>{var w;function checkLoadingStatus(){checkProgress(i,g,k),v?.(i.loadingProgressInfo),k===L&&x&&x()}_._redURIkey=b,_._redURIIndex=y,_.uri instanceof ArrayBuffer?(w=new DataView(_.uri),k++,S[y]=w,checkLoadingStatus()):function(g){const x=g.startsWith("data:")?g:i.filePath+g;arrayBufferLoader(x,function(i){k++,S[y]=new DataView(i),checkLoadingStatus()},function(i,g){})}(_.uri)})})(i,x,()=>{requestAnimationFrame(()=>{((i,g,x)=>{const{scenes:v}=g;v[0].nodes.forEach(x=>{parseNode_GLTF(i,g,x,i.resultMesh)}),x?.()})(i,x,()=>{requestAnimationFrame(()=>{((i,x)=>{const{cameras:v}=x;v&&v.forEach(function(x){let v=new PerspectiveCamera;if("orthographic"==x.type);else{g(x);const i=x.perspective.yfov??x.perspective.yfieldOfView;void 0!==i&&(v.fieldOfView=180*i/Math.PI),v.farClipping=x.perspective.zfar,v.nearClipping=x.perspective.znear}i.parsingResult.cameras.push(v)})})(i,x),new TextureLoader(i.redGPUContext,Object.values(i.parsingResult.textureRawList),g=>{g.textures.forEach(i=>{const{targetTextureKey:g,targetSamplerKey:x,samplerList:v}=i.srcInfo;i.srcInfo.materialList.forEach((_,y)=>{_[g]=i.texture,v[y]&&(_[x]=v[y])})}),parseAnimations(i,x).then(i=>{v&&v()})},g=>{i.loadingProgressInfo.textures=g,_?.(i.loadingProgressInfo)})})})})},_)})})},fa=new Map,da=new Map,parseFileGLB=async(i,x,v)=>{const _=getAbsoluteURL(window.location.href,i.filePath+i.fileName),progress=()=>{if(v){const g=fa.get(_);i.loadingProgressInfo.model={loaded:g.byteLength,total:g.byteLength,lengthComputable:!0,percent:100,transferred:"Cached",totalSize:"Cached"},v(i.loadingProgressInfo)}};if(fa.has(_))return g("GLB Model parsing has cache",_),progress(),void await parseArrayBuffer(i,fa.get(_),x,v);if(da.has(_))return await da.get(_),progress(),void await parseArrayBuffer(i,fa.get(_),x,v);const y=new Promise((x,y)=>{(async(i,g,x=()=>{},v=()=>{})=>{try{const x=await fetch(i);if(!x.ok)throw new Error(`HTTP error! status: ${x.status}`);const _=x.headers.get("content-length"),y=_?parseInt(_,10):0,b=y>0,S=b?formatBytes(y):"Unknown";if(!x.body)return void g(new ArrayBuffer(0));const w=x.body.getReader();let L=0;const k=[];for(;;){const{done:i,value:g}=await w.read();if(i)break;g&&(k.push(g),L+=g.length,v({loaded:L,total:y,lengthComputable:b,percent:b?Math.min(100,parseFloat((L/y*100).toFixed(2))):0,transferred:formatBytes(L),totalSize:S}))}if(0===L)return void g(new ArrayBuffer(0));const H=new Blob(k);g(await H.arrayBuffer())}catch(i){x?x(i):console.error("getArrayBufferFromSrc 로딩 중 오류 발생:",i)}})(_,i=>{fa.set(_,i),g("GLB Model parsing set cache",_),da.delete(_),x(i)},i=>{g("GLB Model parsing error",i),da.delete(_),y(i)},g=>{i.loadingProgressInfo.model=g,v?.(i.loadingProgressInfo)})});da.set(_,y);try{const g=await y;await parseArrayBuffer(i,g,x,v)}catch(i){}},parseArrayBuffer=async(i,g,x,v)=>{const{content:_,binaryChunk:y}=parseBuffer(g);if(null===_)throw new Error("JSON content not found");const b=JSON.parse(_);processImagesIfExist(b,y),b.buffers[0].uri=y,i.gltfData=b,parseGLTF(i,b,x,v)},parseBuffer=i=>{let g=null,x=null;const v=new DataView(i,12),_=v.byteLength;for(let y=0;y<_;){const _=v.getUint32(y,!0);y+=4;const b=v.getUint32(y,!0);switch(y+=4,b){case 1313821514:const v=new Uint8Array(i,12+y,_);g=convertUint8ArrayToString(v);break;case 5130562:const b=12+y;x=i.slice(b,b+_)}y+=_}return{content:g,binaryChunk:x}},processImagesIfExist=(i,g)=>{const{images:x,bufferViews:v}=i,_=["image/png","image/jpeg","image/gif","image/webp"],y=new Map;if(x)for(let i=0;i{let g="";for(let x of i)g+=String.fromCharCode(x);return g},ma=new Map,pa=new Map,getData=i=>({...i,meshes:JSON.parse(JSON.stringify(i.meshes))});class GLTFLoader extends RedGPUObject{parsingResult;resultMesh;parsingOption;activeAnimations=[];#yf;#bf;#Sf;#Tf;#wf;#q;#Y;#Mf;#Pf={url:"",model:{loaded:0,total:0,lengthComputable:!0,percent:0,transferred:"0",totalSize:"0"}};constructor(i,g,x,v,_){super(i),this.#Sf=g,this.#yf=getFilePath(g),this.#bf=getFileName(g),this.#Tf=getFileExtension(g),this.#q=x,this.#Mf=v,this.#Y=_,this.parsingResult={groups:[],materials:[],uris:{buffers:[]},textures:{},textureRawList:[],cameras:[],animations:[]},this.resultMesh=new Mesh(i),this.resultMesh.gltfLoaderInfo=this,this.resultMesh.animationInfo.animationsList=this.parsingResult.animations,this.#Pf.url=getFileName(g),this.#Rf()}get loadingProgressInfo(){return this.#Pf}get filePath(){return this.#yf}get gltfData(){return this.#wf}set gltfData(i){this.#wf=i}get fileName(){return this.#bf}get url(){return this.#Sf}stopAnimation(){this.activeAnimations.length=0}playAnimation(i){const{activeAnimations:g}=this;g.push(new PlayAnimationInfo(performance.now(),i))}async#Rf(){try{"glb"===this.#Tf?parseFileGLB(this,()=>this.#q(this),this.#Mf):"gltf"===this.#Tf?(async(i,x,v)=>{const _=getAbsoluteURL(window.location.href,i.filePath+i.fileName),cachedProgress=()=>{if(v){const g=ma.get(_);i.loadingProgressInfo.model={loaded:g.byteLength,total:g.byteLength,lengthComputable:!0,percent:100,transferred:"Cached",totalSize:"Cached"},v(i.loadingProgressInfo)}};if(ma.has(_))return i.gltfData=getData(ma.get(_)),cachedProgress(),void requestAnimationFrame(()=>{parseGLTF(i,i.gltfData,x,v)});if(pa.has(_))return await pa.get(_),cachedProgress(),i.gltfData=getData(ma.get(_)),void requestAnimationFrame(()=>{parseGLTF(i,i.gltfData,x,v)});const y=new Promise(async(x,y)=>{try{const y=await fetch(i.url);if(!y.ok)throw new Error("GLTF 네트워크 오류: "+y.status);const b=y.headers.get("content-length"),S=b?parseInt(b,10):0;g(`전체 사이즈: ${S} bytes`);const w=await y.json();ma.set(_,w),i.loadingProgressInfo.model={loaded:S,total:S,lengthComputable:!0,percent:100,transferred:formatBytes(S),totalSize:formatBytes(S)};{g(w);const x=w.buffers.length;if(x){let g=0;i.loadingProgressInfo.buffers={loaded:g,total:x,percent:Math.min(100,parseFloat((g/x*100).toFixed(2)))}}}v?.(i.loadingProgressInfo),x(w)}catch(i){y(i)}finally{pa.delete(_)}});pa.set(_,y);const b=await y;i.gltfData=getData(b),requestAnimationFrame(()=>{parseGLTF(i,i.gltfData,x,v)})})(this,()=>this.#q(this),this.#Mf):consoleAndThrowError("Unknown file extension: "+this.#Tf)}catch(i){this.#Y?.(i)}}}Object.freeze(GLTFLoader);class PlayAnimationInfo{startTime;targetGLTFParsedSingleClip;constructor(i,g){this.startTime=i,this.targetGLTFParsedSingleClip=g}}var ga=Object.freeze({__proto__:null,AABB:AABB,OBB:OBB,calculateGeometryAABB:calculateGeometryAABB,calculateMeshAABB:calculateMeshAABB,calculateMeshCombinedAABB:calculateMeshCombinedAABB,calculateMeshOBB:calculateMeshOBB}),xa=Object.freeze({__proto__:null,BaseObject:BaseObject,RedGPUObject:RedGPUObject}),va=Object.freeze({__proto__:null,ACamera:ACamera,AController:AController,AutoExposure:AutoExposure,METERING_MODE:Pi});const _a=Math.PI/180,updateObject3DMatrix=(i,g)=>{const{pixelRectObject:x}=g,v=i.parent,_=i.localMatrix;identity$1(_),translate(_,_,[i.x,i.y,i.z]),rotateY$2(_,_,i.rotationY*_a),rotateX$2(_,_,i.rotationX*_a),rotateZ$2(_,_,i.rotationZ*_a);let y=[i.scaleX,i.scaleY,i.scaleZ];if(i.renderTextureWidth&&(y[0]*=i.renderTextureWidth/x.height,y[1]*=i.renderTextureHeight/x.height),scale$4(_,_,y),i.pivotX||i.pivotY||i.pivotZ){translate(_,_,[-i.pivotX,-i.pivotY,-i.pivotZ])}v?.modelMatrix?multiply$4(i.modelMatrix,v.modelMatrix,i.localMatrix):copy$4(i.modelMatrix,i.localMatrix)},ya=Math.PI/180;const ba=Math.PI/180,Sa=create$4(),Ta=create$3();class FollowController extends AController{#Cf=10;#Bf=10;#Df=.02;#Ef=5;#If=5;#Af=.02;#Lf=.02;#Uf=0;#kf=0;#Gf=.02;#Of=20;#Vf=20;#Nf=.02;#Ff=!0;#Hf=0;#zf=0;#$f=0;#jf;#Kf=create$3();constructor(i,g){super(i,{HD_Wheel:i=>{this.#Bf+=i.deltaY/100},HD_TouchPinch:i=>{const g=i-1;this.#Bf-=g*this.#Bf}}),this.targetMesh=g,this.#jf.setIgnoreFrustumCullingRecursively(!0)}get distance(){return this.#Bf}set distance(i){validateNumberRange(i,.1),this.#Bf=i}get distanceInterpolation(){return this.#Df}set distanceInterpolation(i){validateNumberRange(i,.01,1),this.#Df=i}get height(){return this.#If}set height(i){validateNumber(i),this.#If=i}get heightInterpolation(){return this.#Af}set heightInterpolation(i){validateNumberRange(i,.01,1),this.#Af=i}get pan(){return this.#kf}set pan(i){validateNumber(i),this.#kf=i}get panInterpolation(){return this.#Gf}set panInterpolation(i){validateNumberRange(i,.01,1),this.#Gf=i}get tilt(){return this.#Vf}set tilt(i){validateNumber(i),this.#Vf=Math.max(-89,Math.min(89,i))}get tiltInterpolation(){return this.#Nf}set tiltInterpolation(i){validateNumberRange(i,.01,1),this.#Nf=i}get interpolation(){return this.#Lf}set interpolation(i){validateNumberRange(i,.01,1),this.#Lf=i}get followTargetRotation(){return this.#Ff}set followTargetRotation(i){this.#Ff=i}get targetOffsetX(){return this.#Hf}set targetOffsetX(i){validateNumber(i),this.#Hf=i}get targetOffsetY(){return this.#zf}set targetOffsetY(i){validateNumber(i),this.#zf=i}get targetOffsetZ(){return this.#$f}set targetOffsetZ(i){validateNumber(i),this.#$f=i}get targetMesh(){return this.#jf}set targetMesh(i){if(!i)throw new Error("FollowController: targetMesh cannot be null or undefined");this.#jf=i,this.#jf.setIgnoreFrustumCullingRecursively(!0),this.#Xf()}setTargetOffset(i,g=0,x=0){validateNumber(i),validateNumber(g),validateNumber(x),this.#Hf=i,this.#zf=g,this.#$f=x}update(i,g){super.update(i,g,g=>{const{targetMesh:x}=this;x&&updateObject3DMatrix(x,i),this.#Cf=this.#Bf+(this.#Cf-this.#Bf)*Math.pow(this.#Df,g),this.#Ef=this.#If+(this.#Ef-this.#If)*Math.pow(this.#Af,g);let v=(this.#kf-this.#Uf)%360;v>180&&(v-=360),v<-180&&(v+=360),this.#Uf+=v*(1-Math.pow(this.#Gf,g)),this.#Of=this.#Vf+(this.#Of-this.#Vf)*Math.pow(this.#Nf,g);const _=this.#qf(),y=Math.pow(this.#Lf,g);this.#Kf[0]=_[0]+(this.#Kf[0]-_[0])*y,this.#Kf[1]=_[1]+(this.#Kf[1]-_[1])*y,this.#Kf[2]=_[2]+(this.#Kf[2]-_[2])*y,this.camera.setPosition(this.#Kf[0],this.#Kf[1],this.#Kf[2]);const b=this.#Yf();this.camera.lookAt(b[0],b[1],b[2])})}#qf(){const i=this.#Uf*ba,g=this.#Of*ba,x=Math.cos(g),v=Math.sin(g),_=Math.cos(i),y=Math.sin(i),b=this.#jf.modelMatrix,S=b[12],w=b[13],L=b[14];return this.#Ff?(set$3(Ta,y*this.#Cf*x,v*this.#Cf+this.#Ef,_*this.#Cf*x),copy$4(Sa,b),Sa[12]=Sa[13]=Sa[14]=0,transformMat4$2(Ta,Ta,Sa),fromValues$3(S+Ta[0],w+Ta[1],L+Ta[2])):fromValues$3(S+this.#Cf*x*y,w+this.#Ef+this.#Cf*v,L+this.#Cf*x*_)}#Yf(){set$3(Ta,this.#Hf,this.#zf,this.#$f);const i=this.#jf.modelMatrix,g=i[12],x=i[13],v=i[14];return!this.#Ff||0===this.#Hf&&0===this.#zf&&0===this.#$f||(copy$4(Sa,i),Sa[12]=Sa[13]=Sa[14]=0,transformMat4$2(Ta,Ta,Sa)),fromValues$3(g+Ta[0],x+Ta[1],v+Ta[2])}#Xf(){updateObject3DMatrix(this.#jf,{pixelRectObject:{height:1}}),this.#Cf=this.#Bf,this.#Ef=this.#If,this.#Uf=this.#kf,this.#Of=this.#Vf;const i=this.#qf();copy$3(this.#Kf,i),this.camera.setPosition(this.#Kf[0],this.#Kf[1],this.#Kf[2]);const g=this.#Yf();this.camera.lookAt(g[0],g[1],g[2])}}Object.freeze(FollowController);const wa=Math.PI/180,Ma=1e-4,Pa=create$4();class OrbitController extends AController{#Wf=0;#Zf=0;#Jf=0;#Qf=15;#ed=1.5;#Df=.02;#td=.1;#rd=1/0;#id=0;#nd=-35;#ad=3;#sd=.02;#od=-90;#ud=90;#Uf=0;#Of=0;#Cf=0;constructor(i){super(i,{HD_Move:(i,g)=>{this.#id-=i*this.#ad*.1,this.#nd-=g*this.#ad*.1},HD_Wheel:i=>{this.#Qf+=i.deltaY/100*this.#ed,this.#Qfthis.#rd&&(this.#Qf=this.#rd)},HD_TouchPinch:i=>{const g=(i-1)*this.#ed;this.#Qf-=g*this.#Qf,this.#Qfthis.#rd&&(this.#Qf=this.#rd)}}),this.#Uf=this.#id,this.#Of=this.#nd,this.#Cf=this.#Qf}get centerX(){return this.#Wf}set centerX(i){this.#Wf=i}get centerY(){return this.#Zf}set centerY(i){this.#Zf=i}get centerZ(){return this.#Jf}set centerZ(i){this.#Jf=i}get distance(){return this.#Qf}set distance(i){validateNumberRange(i,0),this.#Qf=i}get speedDistance(){return this.#ed}set speedDistance(i){validateNumberRange(i,.01),this.#ed=i}get distanceInterpolation(){return this.#Df}set distanceInterpolation(i){validateNumberRange(i,.01,1),this.#Df=i}get minDistance(){return this.#td}set minDistance(i){validateNumberRange(i,.1),this.#td=i}get maxDistance(){return this.#rd}set maxDistance(i){validateNumberRange(i,.1),this.#rd=i}get speedRotation(){return this.#ad}set speedRotation(i){validateNumberRange(i,.01),this.#ad=i}get rotationInterpolation(){return this.#sd}set rotationInterpolation(i){validateNumberRange(i,.01,1),this.#sd=i}get pan(){return this.#id}set pan(i){this.#id=i}get tilt(){return this.#nd}set tilt(i){validateNumberRange(i,-90,90),this.#nd=i}get minTilt(){return this.#od}set minTilt(i){validateNumberRange(i,-90,90),this.#od=i}get maxTilt(){return this.#ud}set maxTilt(i){validateNumberRange(i,-90,90),this.#ud=i}update(i,g){super.update(i,g,i=>{this.#ld(i)})}#ld(i){this.#ndthis.#ud&&(this.#nd=this.#ud);const{camera:g}=this,x=this.#id-this.#Uf;Math.abs(x)>Ma?this.#Uf+=x*(1-Math.pow(this.#sd,i)):this.#Uf=this.#id;const v=this.#nd-this.#Of;Math.abs(v)>Ma?this.#Of+=v*(1-Math.pow(this.#sd,i)):this.#Of=this.#nd,this.#Qfthis.#rd&&(this.#Qf=this.#rd);const _=this.#Qf-this.#Cf;Math.abs(_)>1e-4?this.#Cf+=_*(1-Math.pow(this.#Df,i)):this.#Cf=this.#Qf,this.#Cf{this.#fd-=i.deltaY/100*this.#md,this.#fd=Math.max(this.#Wl,Math.min(this.#Zl,this.#fd))},HD_Move:(g,x)=>{if(!this.#jf)return;const v=this.#cd*Ra,_=Math.cos(v),y=Math.sin(v),b=this.#pd/this.#hd/i.boundingClientRect.height,S=g*b,w=x*b,L=-S*_-w*y,k=-S*-y-w*_;this.#vd+=L,this.#_d+=k},HD_TouchPinch:i=>{this.#fd/=i,this.#fd=Math.max(this.#Wl,Math.min(this.#Zl,this.#fd))},useKeyboard:!0}),this.#jf=new Mesh(i),this.#jf.setIgnoreFrustumCullingRecursively(!0)}get zoom(){return this.#fd}set zoom(i){validateNumberRange(i),this.#fd=Math.max(this.#Wl,Math.min(this.#Zl,i))}get zoomInterpolation(){return this.#dd}set zoomInterpolation(i){validateNumberRange(i,1e-4,1),this.#dd=i}get speedZoom(){return this.#md}set speedZoom(i){validateNumberRange(i,.01),this.#md=i}get minZoom(){return this.#Wl}set minZoom(i){validateNumberRange(i,.01),this.#Wl=i,this.zoom=this.#fd}get maxZoom(){return this.#Zl}set maxZoom(i){validateNumberRange(i,.01),this.#Zl=i,this.zoom=this.#fd}get viewHeight(){return this.#gd}set viewHeight(i){validateNumberRange(i,.1),this.#gd=i}get viewHeightInterpolation(){return this.#xd}set viewHeightInterpolation(i){validateNumberRange(i,1e-4,1),this.#xd=i}get moveSpeed(){return this.#yd}set moveSpeed(i){validateNumberRange(i,.01),this.#yd=i}get moveSpeedInterpolation(){return this.#bd}set moveSpeedInterpolation(i){validateNumberRange(i,1e-4,1),this.#bd=i}get mouseMoveSpeed(){return this.#Td}set mouseMoveSpeed(i){validateNumberRange(i,.01),this.#Td=i}get mouseMoveSpeedInterpolation(){return this.#wd}set mouseMoveSpeedInterpolation(i){validateNumberRange(i,1e-4,1),this.#wd=i}get keyNameMapper(){return{...this.#Sd}}get targetX(){return this.#jf.x}get targetY(){return this.#jf.y}get targetZ(){return this.#jf.z}setMoveUpKey(i){this.#Sd.moveUp=i}setMoveDownKey(i){this.#Sd.moveDown=i}setMoveLeftKey(i){this.#Sd.moveLeft=i}setMoveRightKey(i){this.#Sd.moveRight=i}update(i,g){super.update(i,g,g=>{this.#ld(i,g)})}#ld(i,g){if(this.#Md(i,g),this.#hd=this.#fd+(this.#hd-this.#fd)*Math.pow(this.#dd,g),this.#pd=this.#gd+(this.#pd-this.#gd)*Math.pow(this.#xd,g),!this.#jf)return;const x=Math.pow(this.#bd,g);this.#jf.x=this.#vd+(this.#jf.x-this.#vd)*x,this.#jf.z=this.#_d+(this.#jf.z-this.#_d)*x;const v=this.#jf.position,_=this.#cd*Ra,{width:y,height:b}=i.pixelRectObject,S=y/b,w=this.#pd/this.#hd,L=w*S,k=this.#pd/15,H=15*k/this.#hd,z=12*k/this.#hd,q=v[0]+Math.cos(_)*H,W=v[1]+z,be=v[2]+Math.sin(_)*H;this.camera.setPosition(q,W,be),this.camera.lookAt(v[0],v[1],v[2]);const je=this.camera;je.left=-L/2,je.right=L/2,je.top=w/2,je.bottom=-w/2}#Md(i,g){if(!this.checkKeyboardInput(i,this.#Sd))return!1;if(!this.#jf)return!1;const{keyboardKeyBuffer:x}=i.redGPUContext,v=this.#Sd,_=this.#yd*g;let y=0,b=0,S=0,w=0;x[v.moveUp]&&(y=_),x[v.moveDown]&&(b=_),x[v.moveLeft]&&(S=_),x[v.moveRight]&&(w=_);const L=this.#cd*Ra,k=Math.cos(L),H=Math.sin(L),z=(b-y)*k+(w-S)*k,q=(b-y)*H+(w-S)*-H;return this.#vd+=z,this.#_d+=q,!0}}Object.freeze(IsometricController);var Ca=Object.freeze({__proto__:null,Camera2D:Camera2D,Core:va,FollowController:FollowController,FreeController:class extends AController{#Sd={moveForward:"w",moveBack:"s",moveLeft:"a",moveRight:"d",moveUp:"e",moveDown:"q",turnLeft:"z",turnRight:"c",turnUp:"r",turnDown:"f"};#yd=600;#Pd=.001;#Rd=1;#Cd=0;#Bd=360;#sd=.001;#Dd=.15;#Ed=[0,0,0];#id=0;#nd=0;#jf;#Id=create$4();#Ad=create$4();#Ld=create$3();constructor(i){super(i,{HD_Move:(i,g)=>{this.#id-=i*this.#Dd,this.#nd-=g*this.#Dd},useKeyboard:!0}),this.#dc()}get x(){return this.#jf.x}set x(i){validateNumber(i),this.#jf.x=i,this.#Ed[0]=i}get y(){return this.#jf.y}set y(i){validateNumber(i),this.#jf.y=i,this.#Ed[1]=i}get z(){return this.#jf.z}set z(i){validateNumber(i),this.#jf.z=i,this.#Ed[2]=i}get pan(){return this.#id}set pan(i){validateNumber(i),this.#id=i}get tilt(){return this.#nd}set tilt(i){validateNumber(i),this.#nd=Math.max(-89.9,Math.min(89.9,i))}get mouseSensitivity(){return this.#Dd}set mouseSensitivity(i){validateNumberRange(i,.01),this.#Dd=i}get moveSpeed(){return this.#yd}set moveSpeed(i){validateNumberRange(i,.01),this.#yd=i}get moveSpeedInterpolation(){return this.#Pd}set moveSpeedInterpolation(i){validateNumberRange(i,1e-4,1),this.#Pd=i}get rotationSpeed(){return this.#Bd}set rotationSpeed(i){validateNumberRange(i,.01),this.#Bd=i}get rotationSpeedInterpolation(){return this.#sd}set rotationSpeedInterpolation(i){validateNumberRange(i,1e-4,1),this.#sd=i}get maxAcceleration(){return this.#Rd}set maxAcceleration(i){this.#Rd=i}get keyNameMapper(){return{...this.#Sd}}setMoveForwardKey(i){this.#Sd.moveForward=i}setMoveBackKey(i){this.#Sd.moveBack=i}setMoveLeftKey(i){this.#Sd.moveLeft=i}setMoveRightKey(i){this.#Sd.moveRight=i}setMoveUpKey(i){this.#Sd.moveUp=i}setMoveDownKey(i){this.#Sd.moveDown=i}setTurnLeftKey(i){this.#Sd.turnLeft=i}setTurnRightKey(i){this.#Sd.turnRight=i}setTurnUpKey(i){this.#Sd.turnUp=i}setTurnDownKey(i){this.#Sd.turnDown=i}update(i,g){super.update(i,g,g=>{this.#ld(i,g)})}#dc(){this.#jf=new Mesh(this.redGPUContext)}#ld(i,g){const x=this.#jf,v=Math.pow(this.#Pd,g),_=Math.pow(this.#sd,g);let y=(this.#id-x.rotationY)%360;y>180&&(y-=360),y<-180&&(y+=360),x.rotationY+=y*(1-_);const b=this.#nd-x.rotationX;x.rotationX+=b*(1-_),this.#Ud(i,g)&&(updateObject3DMatrix(x,i),identity$1(this.#Ad),rotateY$2(this.#Ad,this.#Ad,x.rotationY*ya),rotateX$2(this.#Ad,this.#Ad,x.rotationX*ya),translate(this.#Ad,this.#Ad,this.#Ld),identity$1(this.#Id),translate(this.#Id,this.#Id,x.position),multiply$4(this.#Id,this.#Id,this.#Ad),this.#Ed[0]=this.#Id[12],this.#Ed[1]=this.#Id[13],this.#Ed[2]=this.#Id[14]),x.x+=(this.#Ed[0]-x.x)*(1-v),x.y+=(this.#Ed[1]-x.y)*(1-v),x.z+=(this.#Ed[2]-x.z)*(1-v),identity$1(this.#Id),translate(this.#Id,this.#Id,x.position),rotateY$2(this.#Id,this.#Id,x.rotationY*ya),rotateX$2(this.#Id,this.#Id,x.rotationX*ya),this.camera.setPosition(x.x,x.y,x.z);const S=fromValues$3(0,0,-10);transformMat4$2(S,S,this.#Id),this.camera.lookAt(S[0],S[1],S[2])}#Ud(i,g){if(!this.checkKeyboardInput(i,this.#Sd))return!1;const{keyboardKeyBuffer:x}=i.redGPUContext,v=this.#yd*g,_=this.#Bd*g,y=this.#Sd;let b=!1,S=!1,w=0,L=0;this.#Ld[0]=0,this.#Ld[1]=0,this.#Ld[2]=0;const k=this.#Cd*v;x[y.turnLeft]&&(S=!0,w=_),x[y.turnRight]&&(S=!0,w=-_),x[y.turnUp]&&(S=!0,L=_),x[y.turnDown]&&(S=!0,L=-_),x[y.moveForward]&&(b=!0,this.#Ld[2]=-k),x[y.moveBack]&&(b=!0,this.#Ld[2]=k),x[y.moveLeft]&&(b=!0,this.#Ld[0]=-k),x[y.moveRight]&&(b=!0,this.#Ld[0]=k),x[y.moveUp]&&(b=!0,this.#Ld[1]=k),x[y.moveDown]&&(b=!0,this.#Ld[1]=-k);const H=3*g;return this.#Cd=S||b?Math.min(this.#Rd,this.#Cd+H):Math.max(0,this.#Cd-H),S&&(this.#id+=w,this.#nd=Math.max(-89.9,Math.min(89.9,this.#nd+L))),b||S}},IsometricController:IsometricController,OrbitController:OrbitController,OrthographicCamera:OrthographicCamera,PerspectiveCamera:PerspectiveCamera}),Ba=Object.freeze({__proto__:null,RedGPUContextDetector:RedGPUContextDetector,RedGPUContextObserver:RedGPUContextObserver,RedGPUContextSizeManager:RedGPUContextSizeManager,RedGPUContextViewContainer:RedGPUContextViewContainer}),Da=Object.freeze({__proto__:null,Core:Ba,RedGPUContext:RedGPUContext}),Ea=Object.freeze({__proto__:null,ColorRGB:ColorRGB,ColorRGBA:ColorRGBA,convertHexToRgb:convertHexToRgb,convertRgbToHex:convertRgbToHex}),Ia=Object.freeze({__proto__:null,COMMAND_ENCODER_TYPE:k,CommandEncoderManager:CommandEncoderManager});function createSetter(i,g){const x=`use${i.charAt(0).toUpperCase()}${i.substring(1)}`;return function(i){const v=this[g];this[g]=i,this.updateTexture(v,i),x in this&&(this[x]=!!i),updateTargetUniform(this,x,i?1:0)}}function defineCubeTexture_func(i){const{key:g}=i,x=Symbol(g);return{get:function(){return this[x]},set:createSetter(g,x),...vi}}const defineCubeTexture=(i,g)=>applyProperties(i,g,defineCubeTexture_func);Object.freeze(defineCubeTexture);const Aa=parseWGSL("SKYBOX_MATERIAL","#redgpu_include SYSTEM_UNIFORM #redgpu_include systemStruct.OutputFragment #redgpu_include color.getLuminance #redgpu_include math.PI #redgpu_include math.PI2 #redgpu_include math.INV_PI #redgpu_include skyAtmosphere.skyAtmosphereFn struct Uniforms{blur:f32,intensityMultiplier:f32,luminance:f32,averageLuminance:f32,opacity:f32,transitionProgress:f32,};@group(2)@binding(0)varuniforms:Uniforms;@group(2)@binding(1)var sampler0:sampler;@group(2)@binding(2)var texture0:texture_cube;@group(2)@binding(3)var transitionTexture:texture_cube;@group(2)@binding(4)var transitionMask:texture_2d;struct InputData{@location(0)vertexPosition:vec4,};fn sphericalToUV(dir:vec3)->vec2{let normalizedDir=normalize(dir);let phi=atan2(normalizedDir.z,normalizedDir.x);let theta=acos(clamp(normalizedDir.y,-1.0,1.0));return vec2((phi+PI)/PI2,theta*INV_PI);}@fragment fn main(inputData:InputData)->OutputFragment{var cubemapVec=inputData.vertexPosition.xyz;let viewDir=normalize(cubemapVec);let mipmapCount=f32(textureNumLevels(texture0)-1);let blurCurve=uniforms.blur*uniforms.blur;let skyboxColor=textureSampleLevel(texture0,sampler0,viewDir,mipmapCount*blurCurve);var sampleColor=skyboxColor;let u_transitionProgress=uniforms.transitionProgress;if(u_transitionProgress>.0){let transitionSample=textureSampleLevel(transitionTexture,sampler0,viewDir,mipmapCount*blurCurve);#redgpu_if transitionMask let uv=sphericalToUV(viewDir);let maskSample=textureSampleLevel(transitionMask,sampler0,uv,.0);let maskValue=getLuminance(maskSample.rgb);let threshold=u_transitionProgress;let mask=smoothstep(threshold-0.1,threshold+0.1,maskValue+(u_transitionProgress-0.5)*0.3);sampleColor=mix(transitionSample,skyboxColor,mask*(1.0-u_transitionProgress));#redgpu_else sampleColor=mix(skyboxColor,transitionSample,u_transitionProgress);#redgpu_endIf}let finalIntensity=systemUniforms.preExposure*(uniforms.intensityMultiplier*uniforms.luminance);var finalAlpha=sampleColor.a*uniforms.opacity;if(systemUniforms.useSkyAtmosphere==1u){let u_atmo=systemUniforms.skyAtmosphere;let transmittance=getTransmittance(transmittanceTexture,atmosphereSampler,u_atmo.cameraHeight,viewDir.y,u_atmo.atmosphereHeight);finalAlpha*=(transmittance.r+transmittance.g+transmittance.b)/3.0;}var outColor=vec4(sampleColor.rgb*finalIntensity,finalAlpha);if(outColor.a==.0){discard;}var output:OutputFragment;output.color=outColor;output.gBufferNormal=vec4(.0);output.gBufferMotionVector=vec4(.0);return output;}");class SkyBoxMaterial extends ABitmapBaseMaterial{constructor(i,g){super(i,"SKYBOX_MATERIAL",Aa,2),this.texture0=g,this.sampler0=new Sampler(this.redGPUContext,{addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge",addressModeW:"clamp-to-edge"}),this.initGPURenderInfos()}}definePositiveNumber(SkyBoxMaterial,[{key:"blur",value:0},{key:"intensityMultiplier",value:1},{key:"luminance",value:1e4},{key:"transitionProgress",value:0}]),defineCubeTexture(SkyBoxMaterial,[{key:"texture0"},{key:"transitionTexture"}]),defineTexture(SkyBoxMaterial,[{key:"transitionMask"}]),defineSampler(SkyBoxMaterial,[{key:"sampler0"}]),Object.freeze(SkyBoxMaterial);var La="#redgpu_include SYSTEM_UNIFORM;struct InputData{@location(0)position:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,};struct VertexOutput{@builtin(position)position:vec4,@location(0)vertexPosition:vec4,};struct VertexUniforms{modelMatrix:mat4x4,};@group(1)@binding(0)varvertexUniforms:VertexUniforms;@vertex fn main(inputData:InputData)->VertexOutput{var output:VertexOutput;let u_camera=systemUniforms.camera;let u_viewMatrix=u_camera.viewMatrix;let u_projectionMatrix=systemUniforms.projection.projectionMatrix;var viewRotation=u_viewMatrix;viewRotation[3]=vec4(.0,.0,.0,1.0);let clipPos=u_projectionMatrix*viewRotation*vertexUniforms.modelMatrix*vec4(inputData.position,1.0);output.position=clipPos.xyww;output.vertexPosition=vec4(inputData.position,1.0);return output;}";const Ua=parseWGSL("SKYBOX_VERTEX",La),ka=Ua.uniforms.vertexUniforms;class SkyBox extends RedGPUObject{modelMatrix=create$4();gpuRenderInfo;#kd=!0;#Ls;#Gd;#xa;#ss;#os;#Od;#Vd;#Nd=0;#Fd=0;#Hd=0;#tl;#zd=25e3;#ls;constructor(i,g,x=25e3){super(i),this.#Gd=new Box(i),this.#Od=g,this.#xa=new SkyBoxMaterial(i,this.#Od),this.luminance=this.#zd=x,this.#ss=new PrimitiveState(this),this.#ss.cullMode=Ji.NONE,this.#os=new DepthStencilState(this),this.#os.depthWriteEnabled=!1}get texture(){return this.#Od}set texture(i){i||consoleAndThrowError("SkyBox requires a valid CubeTexture | DirectCubeTexture"),this.#Od=i,this.#xa.texture0=i}get luminance(){return this.#zd}set luminance(i){this.#zd=i,this.#xa.luminance=i}get intensityMultiplier(){return this.#xa.intensityMultiplier}set intensityMultiplier(i){this.#xa.intensityMultiplier=i}get blur(){return this.#xa.blur}set blur(i){validatePositiveNumberRange(i,0,1),this.#xa.blur=i}get opacity(){return this.#xa.opacity}set opacity(i){validatePositiveNumberRange(i,0,1),this.#xa.opacity=i}get transitionTexture(){return this.#Vd}transition(i,g=300,x){this.#Vd=i,this.#xa.transitionTexture=i,this.#Fd=g,this.#Nd=performance.now(),this.#xa.transitionMask=x}render(i){const{currentRenderPassEncoder:g,viewRenderStartTime:x,view:v}=i,{indexBuffer:_}=this.#Gd,{triangleCount:y,indexCount:b,format:S}=_,{gpuDevice:w,redGPUContext:L}=this;if(this.#$d(),this.gpuRenderInfo||this.#jd(),this.#Nd)if(this.#Hd=Math.max(x-this.#Nd,0),this.#Hd>this.#Fd)this.#Nd=0,this.#xa.transitionProgress=0,this.texture=this.#Vd,this.#xa.transitionTexture=null,this.#kd=!0;else{const i=this.#Hd/this.#Fd;this.#xa.transitionProgress=i<0?0:i>1?1:i}if(this.#kd||this.#xa.dirtyPipeline||this.#tl!==v.systemUniform_Vertex_UniformBindGroup){this.gpuRenderInfo.pipeline=this.#Kd(),this.#kd=!1,i.renderResults.numDirtyPipelines++,this.#tl=v.systemUniform_Vertex_UniformBindGroup;{this.#xa.dirtyPipeline=!1;const i=w.createRenderBundleEncoder({...v.basicRenderBundleEncoderDescriptor,label:"skybox"}),{gpuRenderInfo:g}=this,{vertexUniformBindGroup:x,pipeline:y}=g;i.setPipeline(y),i.setBindGroup(0,v.systemUniform_Vertex_UniformBindGroup),i.setVertexBuffer(0,this.#Gd.vertexBuffer.gpuBuffer),i.setBindGroup(1,x),i.setBindGroup(2,this.#xa.gpuRenderInfo.fragmentUniformBindGroup),i.setIndexBuffer(_.gpuBuffer,S),i.drawIndexed(_.indexCount,1,0,0,0),this.#Ls=i.finish({label:"renderBundle skybox"})}}g.executeBundles([this.#Ls]);const{renderResults:k}=i;k.num3DObjects++,k.numDrawCalls++,k.numTriangles+=y,k.numPoints+=b}#$d(){const{msaaID:i}=this.antialiasingManager;this.#ls!==i&&(this.#kd=!0,this.#ls=i)}#jd(){const{resourceManager:i,redGPUContext:g}=this,x=i.getGPUBindGroupLayout("SKYBOX_VERTEX_BIND_GROUP_LAYOUT")||i.createBindGroupLayout("SKYBOX_VERTEX_BIND_GROUP_LAYOUT",getVertexBindGroupLayoutDescriptorFromShaderInfo(Ua,1)),v=new ArrayBuffer(ka.arrayBufferByteLength),_=new UniformBuffer(g,v,"SKYBOX_VERTEX_UNIFORM_BUFFER","SKYBOX_VERTEX_UNIFORM_BUFFER");identity$1(this.modelMatrix),_.writeOnlyBuffer(ka.members.modelMatrix,this.modelMatrix);const y={layout:x,label:"VERTEX_BIND_GROUP_DESCRIPTOR_SKYBOX",entries:[{binding:0,resource:{buffer:_.gpuBuffer,offset:0,size:_.size}}]},b=g.gpuDevice.createBindGroup(y);this.gpuRenderInfo=new VertexGPURenderInfo(null,Ua.shaderSourceVariant,Ua.conditionalBlocks,ka,x,_,b,this.#Kd())}#Kd(){const{resourceManager:i,gpuDevice:g,antialiasingManager:x}=this,v={module:i.createGPUShaderModule("VERTEX_MODULE_SKYBOX",{code:La}),entryPoint:"main",buffers:this.#Gd.gpuRenderInfo.buffers},_=i.getGPUBindGroupLayout("SKYBOX_VERTEX_BIND_GROUP_LAYOUT")||i.createBindGroupLayout("SKYBOX_VERTEX_BIND_GROUP_LAYOUT",getVertexBindGroupLayoutDescriptorFromShaderInfo(Ua,1)),y=[i.getGPUBindGroupLayout(ResourceManager.PRESET_GPUBindGroupLayout_System),_,this.#xa.gpuRenderInfo.fragmentBindGroupLayout],b={label:"PIPELINE_DESCRIPTOR_SKYBOX",layout:i.createGPUPipelineLayout("SKYBOX_PIPELINE_LAYOUT",{bindGroupLayouts:y}),vertex:v,fragment:this.#xa.gpuRenderInfo.fragmentState,primitive:this.#ss.state,depthStencil:this.#os.state,multisample:{count:x.useMSAA?4:1}};return g.createRenderPipeline(b)}}Object.freeze(SkyBox);var Ga=Object.freeze({__proto__:null,SkyBoxMaterial:SkyBoxMaterial});class DirectTexture extends ADirectTexture{constructor(i,g,x){super(i,"managedBitmapTextureState",g);const{table:v}=this.targetResourceManagedState;if(g){const i=v.get(g);if(i)return i.texture}x&&this.setGpuTexture(x),this.registerResource()}get viewDescriptor(){return{dimension:"2d",format:this.format,mipLevelCount:this.mipLevelCount,baseMipLevel:0,arrayLayerCount:1,baseArrayLayer:0,aspect:"all"}}registerResource(){this.redGPUContext.resourceManager.registerManagementResource(this,new ResourceStateBitmapTexture(this))}unregisterResource(){this.redGPUContext.resourceManager.unregisterManagementResource(this)}}Object.freeze(DirectTexture);class ASkyAtmosphereLUTGenerator extends RedGPUObject{#Xd;#ne;#iu;#Gt;#Ot;#qd;constructor(i,g,x,v,_,y,b=1){super(i),this.#Xd=g,this.#ne=x,this.#iu=v,this.#Gt=_,this.#Ot=y,this.#qd=b}get sharedUniformBuffer(){return this.#Xd}get sampler(){return this.#ne}get label(){return this.#iu}get width(){return this.#Gt}get height(){return this.#Ot}get depth(){return this.#qd}executeComputePass(i,g,x=[16,16,1]){const{commandEncoderManager:v}=this;v.addResourceComputePass(`SkyAtmosphere_${this.#iu}_ComputePass`,v=>{v.setPipeline(i),v.setBindGroup(0,g),v.dispatchWorkgroups(Math.ceil(this.#Gt/x[0]),Math.ceil(this.#Ot/x[1]),Math.ceil(this.#qd/x[2]))}),this.lutTexture.notifyUpdate()}createLUTTexture(i=!1,g="rgba16float"){const{resourceManager:x}=this;return x.createManagedTexture({label:`SkyAtmosphere_${this.#iu}_Texture`,size:[this.#Gt,this.#Ot,this.#qd],dimension:i?"3d":"2d",format:g,usage:GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC})}createComputePipeline(i,g){const{gpuDevice:x}=this;return x.createComputePipeline({label:i,layout:"auto",compute:{module:x.createShaderModule({code:g}),entryPoint:"main"}})}createBindGroup(i,g,x){return this.gpuDevice.createBindGroup({label:i,layout:g.getBindGroupLayout(0),entries:x})}}Object.freeze(ASkyAtmosphereLUTGenerator);const Oa=parseWGSL("SkyAtmosphere_Transmittance_Generator",it);class TransmittanceGenerator extends ASkyAtmosphereLUTGenerator{#Yd;#er;#U;constructor(i,g,x){super(i,g,x,"Transmittance_Gen",256,64),this.#N()}get lutTexture(){return this.#Yd}render(){this.#er||(this.#er=this.createBindGroup("SkyAtmosphere_Transmittance_BindGroup",this.#U,[{binding:0,resource:this.#Yd.gpuTextureView},{binding:1,resource:{buffer:this.sharedUniformBuffer.gpuBuffer}}])),this.executeComputePass(this.#U,this.#er,[16,16,1])}#N(){this.#Yd=new DirectTexture(this.redGPUContext,`SkyAtmosphere_Transmittance_LUTTexture_${createUUID()}`,this.createLUTTexture()),this.#U=this.createComputePipeline("SkyAtmosphere_Transmittance_Pipeline",Oa.defaultSource)}}Object.freeze(TransmittanceGenerator);const Va=parseWGSL("SkyAtmosphere_MultiScattering_Generator","#redgpu_include skyAtmosphere.skyAtmosphereFn #redgpu_include math.INV_PI @group(0)@binding(0)var multiScatLUT:texture_storage_2d;@group(0)@binding(1)var transmittanceLUT:texture_2d;@group(0)@binding(2)var skyAtmosphereSampler:sampler;@group(0)@binding(3)varparams:SkyAtmosphere;@compute @workgroup_size(8,8)fn main(@builtin(global_invocation_id)global_id:vec3){let size=textureDimensions(multiScatLUT);if(global_id.x>=size.x||global_id.y>=size.y){return;}let uv=(vec2(global_id.xy)+0.5)/vec2(size);let cosSunTheta=uv.x*2.0-1.0;let viewHeight=clamp((1.0-uv.y)*params.atmosphereHeight,.0,params.atmosphereHeight);let groundRadius=params.groundRadius;let rayOrigin=vec3(.0,viewHeight+groundRadius,.0);let sunDir=vec3(sqrt(max(.0,1.0-cosSunTheta*cosSunTheta)),cosSunTheta,.0);var lumTotal=vec3(.0);var fmsTotal=vec3(.0);for(var i=0u;i(sin(theta)*cos(phi),cos(theta),sin(theta)*sin(phi));let tMax=getRaySphereIntersection(rayOrigin,rayDir,groundRadius+params.atmosphereHeight);let tEarth=getRaySphereIntersection(rayOrigin,rayDir,groundRadius);var L1=vec3(.0);var f1=vec3(.0);var TPath=vec3(1.0);if(groundRadius>.0&&tEarth>.0){integrateMultiScatSegment(rayOrigin,rayDir,.0,tEarth,MULTI_SCAT_STEPS,sunDir,&L1,&f1,&TPath);let hitP=rayOrigin+rayDir*tEarth;let up=normalize(hitP);let localCosSun=dot(up,sunDir);let sunT=getTransmittance(transmittanceLUT,skyAtmosphereSampler,.0,localCosSun,params.atmosphereHeight);L1+=TPath*sunT*max(.0,localCosSun)*params.groundAlbedo*INV_PI;f1+=TPath*params.groundAlbedo;}else if(tMax>.0){integrateMultiScatSegment(rayOrigin,rayDir,.0,tMax,MULTI_SCAT_STEPS,sunDir,&L1,&f1,&TPath);}lumTotal+=L1;fmsTotal+=f1/f32(MULTI_SCAT_SAMPLES);}let output=(lumTotal/f32(MULTI_SCAT_SAMPLES))/(1.0-min(fmsTotal,vec3(0.999)));textureStore(multiScatLUT,global_id.xy,vec4(output,1.0));}fn integrateMultiScatSegment(origin:vec3,dir:vec3,tMin:f32,tMax:f32,steps:u32,sunDir:vec3,L1:ptr>,f1:ptr>,TPath:ptr>){if(tMax<=tMin){return;}let groundRadius=params.groundRadius;let stepSize=(tMax-tMin)/f32(steps);let phaseIsotropic=1.0/(4.0*PI);for(var j=0u;j;@group(0)@binding(1)var transmittanceLUT:texture_2d;@group(0)@binding(2)var multiScatLUT:texture_2d;@group(0)@binding(3)var skyAtmosphereSampler:sampler;@group(0)@binding(4)varparams:SkyAtmosphere;@compute @workgroup_size(16,16)fn main(@builtin(global_invocation_id)global_id:vec3){let size=textureDimensions(skyViewLUT);if(global_id.x>=size.x||global_id.y>=size.y){return;}let uv=(vec2(global_id.xy)+0.5)/vec2(size);let azimuth=(uv.x-0.5)*PI2;let groundRadius=params.groundRadius;let viewHeight=max(.0001,params.cameraHeight);let horizonCos=-sqrt(max(.0,viewHeight*(2.0*groundRadius+viewHeight)))/(groundRadius+viewHeight);let horizonElevation=asin(clamp(horizonCos,-1.0,1.0));var viewElevation:f32;if(uv.y<0.5){let ratio=1.0-(uv.y*2.0);viewElevation=horizonElevation+ratio*ratio*(HPI-horizonElevation);}else{let ratio=(uv.y-0.5)*2.0;viewElevation=horizonElevation-ratio*ratio*(horizonElevation+HPI);}let viewDir=vec3(cos(viewElevation)*cos(azimuth),sin(viewElevation),cos(viewElevation)*sin(azimuth));let rayOrigin=vec3(.0,viewHeight+groundRadius,.0);var radiance=vec3(.0);var transmittance=vec3(1.0);let tEarth=getRaySphereIntersection(rayOrigin,viewDir,groundRadius);let atmosphereHeight=params.atmosphereHeight;let tMax=getRaySphereIntersection(rayOrigin,viewDir,groundRadius+atmosphereHeight);if(groundRadius>.0&&tEarth>.0){integrateScatSegment(rayOrigin,viewDir,.0,tEarth,SKY_VIEW_STEPS/2u,params,transmittanceLUT,skyAtmosphereSampler,multiScatLUT,true,&radiance,&transmittance);let hitPoint=rayOrigin+viewDir*tEarth;let up=normalize(hitPoint);let localCosSun=dot(up,normalize(params.sunDirection));let sunT=getTransmittance(transmittanceLUT,skyAtmosphereSampler,.0,localCosSun,atmosphereHeight);let msUV=vec2(clamp(localCosSun*0.5+0.5,.001,0.999),1.0);let msEnergy=textureSampleLevel(multiScatLUT,skyAtmosphereSampler,msUV,.0).rgb;let groundRadiance=evaluateGroundRadiance(localCosSun,sunT,msEnergy,params.groundAlbedo);radiance+=transmittance*groundRadiance;}else if(tMax>.0){integrateScatSegment(rayOrigin,viewDir,.0,tMax,SKY_VIEW_STEPS,params,transmittanceLUT,skyAtmosphereSampler,multiScatLUT,true,&radiance,&transmittance);}textureStore(skyViewLUT,global_id.xy,vec4(radiance,(transmittance.r+transmittance.g+transmittance.b)/3.0));}");class SkyViewGenerator extends ASkyAtmosphereLUTGenerator{#Yd;#er;#U;constructor(i,g,x){super(i,g,x,"SkyView_Gen",512,256),this.#N()}get lutTexture(){return this.#Yd}render(i,g){this.#er||(this.#er=this.createBindGroup("SkyAtmosphere_SkyView_BindGroup",this.#U,[{binding:0,resource:this.#Yd.gpuTextureView},{binding:1,resource:i.gpuTextureView},{binding:2,resource:g.gpuTextureView},{binding:3,resource:this.sampler.gpuSampler},{binding:4,resource:{buffer:this.sharedUniformBuffer.gpuBuffer}}])),this.executeComputePass(this.#U,this.#er,[16,16,1])}#N(){this.#Yd=new DirectTexture(this.redGPUContext,`SkyAtmosphere_SkyView_LUTTexture_${createUUID()}`,this.createLUTTexture(!1)),this.#U=this.createComputePipeline("SkyAtmosphere_SkyView_Pipeline",Na.defaultSource)}}Object.freeze(SkyViewGenerator);const Fa=parseWGSL("SkyAtmosphere_AerialPerspective_Generator","#redgpu_include SYSTEM_UNIFORM;#redgpu_include skyAtmosphere.skyAtmosphereFn @group(0)@binding(1)var aerialPerspectiveLUT:texture_storage_3d;@group(0)@binding(2)var multiScatLUT:texture_2d;@group(0)@binding(3)varparams:SkyAtmosphere;@group(0)@binding(4)var transmittanceLUT:texture_2d;@group(0)@binding(13)var skyAtmosphereSampler:sampler;@compute @workgroup_size(8,8,4)fn main(@builtin(global_invocation_id)global_id:vec3){let size=textureDimensions(aerialPerspectiveLUT);if(global_id.x>=size.x||global_id.y>=size.y||global_id.z>=size.z){return;}let uvw=(vec3(global_id)+0.5)/vec3(size);let invP=systemUniforms.projection.inverseProjectionMatrix;let invV=systemUniforms.camera.inverseViewMatrix;let ndc=vec2(uvw.x*2.0-1.0,(1.0-uvw.y)*2.0-1.0);let viewSpaceDir=normalize(vec3(ndc.x*invP[0][0],ndc.y*invP[1][1],-1.0));let worldRotation=mat3x3(invV[0].xyz,invV[1].xyz,invV[2].xyz);let viewDir=normalize(worldRotation*viewSpaceDir);let sliceDist=uvw.z*uvw.z*params.aerialPerspectiveDistanceScale;let groundRadius=params.groundRadius;let viewHeight=max(.0,params.cameraHeight);let rayOrigin=vec3(.0,viewHeight+groundRadius,.0);var radiance=vec3(.0);var transmittance=vec3(1.0);let tEarth=getRaySphereIntersection(rayOrigin,viewDir,groundRadius);let tMax=select(sliceDist,min(sliceDist,tEarth),groundRadius>.0&&tEarth>.0);if(tMax>.0){integrateScatSegment(rayOrigin,viewDir,.0,tMax,AP_STEPS,params,transmittanceLUT,skyAtmosphereSampler,multiScatLUT,true,&radiance,&transmittance);let sunDir=normalize(params.sunDirection);let viewSunCos=dot(viewDir,sunDir);let mieGlow=getMieGlowAmountUnit(viewSunCos,viewHeight,params,transmittanceLUT,skyAtmosphereSampler,transmittance,.0);radiance+=mieGlow;}let avgTrans=(transmittance.r+transmittance.g+transmittance.b)/3.0;textureStore(aerialPerspectiveLUT,global_id,vec4(radiance,avgTrans));}");class AerialPerspectiveGenerator extends ASkyAtmosphereLUTGenerator{#Yd;#er;#U;#Wd;constructor(i,g,x){super(i,g,x,"AerialPerspective_Gen",32,32,32),this.#N()}get lutTexture(){return this.#Yd}render(i,g,x){const v=i.systemUniform_Vertex_UniformBuffer?.gpuBuffer;v?(this.#er&&this.#Wd===v||(this.#Wd=v,this.#er=this.createBindGroup("SkyAtmosphere_AerialPerspective_BindGroup",this.#U,[{binding:0,resource:{buffer:v}},{binding:1,resource:this.#Yd.gpuTextureView},{binding:2,resource:x.gpuTextureView},{binding:3,resource:{buffer:this.sharedUniformBuffer.gpuBuffer}},{binding:4,resource:g.gpuTextureView},{binding:13,resource:this.sampler.gpuSampler}])),this.executeComputePass(this.#U,this.#er,[8,8,4])):console.warn("AerialPerspectiveGenerator: systemUniform_Vertex_UniformBuffer is not ready yet.")}#N(){const i=this.createLUTTexture(!0);this.#Yd=new DirectCubeTexture(this.redGPUContext,`SkyAtmosphere_AerialPerspective_LUTTexture_${createUUID()}`,i),this.#U=this.createComputePipeline("SkyAtmosphere_AerialPerspective_Pipeline",Fa.defaultSource)}}Object.freeze(AerialPerspectiveGenerator);const Ha=parseWGSL("SkyLight_Reflection_Generator","#redgpu_include skyAtmosphere.skyAtmosphereFn @group(0)@binding(0)var outputTexture:texture_storage_2d_array;@group(0)@binding(1)var multiScatTexture:texture_2d;@group(0)@binding(2)var atmosphereSampler:sampler;@group(0)@binding(3)varparams:SkyAtmosphere;@group(0)@binding(4)var transmittanceTexture:texture_2d;@group(0)@binding(5)var skyViewTexture:texture_2d;#redgpu_include math.PI #redgpu_include math.PI2 #redgpu_include math.DEG_TO_RAD #redgpu_include math.INV_PI #redgpu_include math.hash.getHammersley #redgpu_include color.getLuminance fn getIBLAtmosphereRadiance(viewDir:vec3)->vec3{var radiance=evaluateIBLRadiance(viewDir,params,transmittanceTexture,multiScatTexture,skyViewTexture,atmosphereSampler);let maxIBLLuminance:f32=10000.0;let lum=getLuminance(radiance);if(lum>maxIBLLuminance){radiance*=(maxIBLLuminance/lum);}return radiance;}@compute @workgroup_size(8,8,1)fn main(@builtin(global_invocation_id)global_id:vec3){let size_u=textureDimensions(outputTexture).xy;if(global_id.x>=size_u.x||global_id.y>=size_u.y||global_id.z>=6u){return;}let size=vec2(size_u);let face=global_id.z;var totalRadiance=vec3(.0);const SAMPLE_COUNT:u32=8u;for(var i=0u;i(global_id.xy)+0.5+offset)/size;var viewDir=getCubeMapDirection(uv,face);viewDir=normalize(viewDir);if(abs(viewDir.y)>0.9999){viewDir=vec3(.0,sign(viewDir.y),.0);}totalRadiance+=getIBLAtmosphereRadiance(viewDir);}let radiance=totalRadiance/f32(SAMPLE_COUNT);textureStore(outputTexture,global_id.xy,global_id.z,vec4(radiance,1.0));}");class SkyLightReflectionGenerator extends ASkyAtmosphereLUTGenerator{#Zd;#Jd;#Qd;#U;#er;constructor(i,g,x){super(i,g,x,"SkyLight_Reflection_Gen",256,256,6),this.#N()}get sourceCubeTexture(){return this.#Zd}get prefilteredTexture(){return this.#Qd}get lutTexture(){return this.#Qd}async render(i,g,x){this.#er||(this.#er=this.#em(i,g,x)),await this.#tm(this.#U,this.#er,this.#Qd)}#em(i,g,x){return this.createBindGroup(`SkyLight_Reflection_BindGroup_${createUUID()}`,this.#U,[{binding:0,resource:this.#Jd},{binding:1,resource:g.gpuTextureView},{binding:2,resource:this.sampler.gpuSampler},{binding:3,resource:{buffer:this.sharedUniformBuffer.gpuBuffer}},{binding:4,resource:i.gpuTextureView},{binding:5,resource:x.gpuTextureView}])}async#tm(i,g,x){const{resourceManager:v}=this.redGPUContext;this.#rm(i,g,[8,8,1]),v.mipmapGenerator.generateMipmap(this.#Zd,{size:[this.width,this.height,6],format:"rgba16float",usage:this.#Zd.usage,mipLevelCount:getMipLevelCount(this.width,this.height),dimension:"2d"},!0,k.RESOURCE),await v.prefilterGenerator.generate(this.#Zd,this.width,x,k.RESOURCE)}#N(){const{gpuDevice:i}=this.redGPUContext,g=getMipLevelCount(this.width,this.height);this.#Zd=i.createTexture({label:"SkyLight_Reflection_Source_CubeTexture",size:[this.width,this.height,6],format:"rgba16float",usage:GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT,mipLevelCount:g}),this.#Jd=this.#Zd.createView({dimension:"2d-array",baseMipLevel:0,mipLevelCount:1}),this.#Qd=new DirectCubeTexture(this.redGPUContext,`SkyLight_Reflection_LUTTexture_${createUUID()}`),this.#U=this.createComputePipeline("Base",Ha.defaultSource)}#rm(i,g,x=[16,16,1],v=this.width,_=this.height,y=this.depth){const{commandEncoderManager:b}=this.redGPUContext;b.addResourceComputePass(`SkyLight_${this.label}_ComputePass`,b=>{b.setPipeline(i),b.setBindGroup(0,g),b.dispatchWorkgroups(Math.ceil(v/x[0]),Math.ceil(_/x[1]),Math.ceil(y/x[2]))})}}Object.freeze(SkyLightReflectionGenerator);const za=parseWGSL("SkyLight_Irradiance_Generator","#redgpu_include skyAtmosphere.skyAtmosphereFn @group(0)@binding(0)var outputTexture:texture_storage_2d_array;@group(0)@binding(1)var multiScatTexture:texture_2d;@group(0)@binding(2)var atmosphereSampler:sampler;@group(0)@binding(3)varparams:SkyAtmosphere;@group(0)@binding(4)var transmittanceTexture:texture_2d;@group(0)@binding(5)var skyViewTexture:texture_2d;#redgpu_include math.PI #redgpu_include math.PI2 #redgpu_include math.DEG_TO_RAD #redgpu_include math.INV_PI #redgpu_include math.hash.getHammersley @compute @workgroup_size(8,8,1)fn main(@builtin(global_invocation_id)global_id:vec3){let size_u=textureDimensions(outputTexture).xy;if(global_id.x>=size_u.x||global_id.y>=size_u.y||global_id.z>=6u){return;}let size=vec2(size_u);let face=global_id.z;var totalRadiance=vec3(.0);const SAMPLE_COUNT:u32=4u;for(var i=0u;i(global_id.xy)+0.5+offset*0.8)/size;var viewDir=getCubeMapDirection(uv,face);viewDir=normalize(viewDir);if(abs(viewDir.y)>0.9999){viewDir=vec3(.0,sign(viewDir.y),.0);}totalRadiance+=evaluateIBLRadianceCompensated(viewDir,params,transmittanceTexture,multiScatTexture,skyViewTexture,atmosphereSampler);}let radiance=totalRadiance/f32(SAMPLE_COUNT);textureStore(outputTexture,global_id.xy,global_id.z,vec4(radiance,1.0));}");class SkyLightIrradianceGenerator extends ASkyAtmosphereLUTGenerator{#Zd;#Jd;#Qd;#U;#er;constructor(i,g,x){super(i,g,x,"SkyLight_Irradiance_Gen",256,256,6),this.#N()}get sourceCubeTexture(){return this.#Zd}get prefilteredTexture(){return this.#Qd}get lutTexture(){return this.#Qd}async render(i,g,x){this.#er||(this.#er=this.#em(i,g,x)),await this.#tm(this.#U,this.#er,this.#Qd)}#em(i,g,x){return this.createBindGroup(`SkyLight_Irradiance_BindGroup_${createUUID()}`,this.#U,[{binding:0,resource:this.#Jd},{binding:1,resource:g.gpuTextureView},{binding:2,resource:this.sampler.gpuSampler},{binding:3,resource:{buffer:this.sharedUniformBuffer.gpuBuffer}},{binding:4,resource:i.gpuTextureView},{binding:5,resource:x.gpuTextureView}])}async#tm(i,g,x){const{resourceManager:v}=this.redGPUContext;this.#rm(i,g,[8,8,1]),v.mipmapGenerator.generateMipmap(this.#Zd,{size:[this.width,this.height,6],format:"rgba16float",usage:this.#Zd.usage,mipLevelCount:getMipLevelCount(this.width,this.height),dimension:"2d"},!0,k.RESOURCE),await v.prefilterGenerator.generate(this.#Zd,this.width,x,k.RESOURCE)}#N(){const{gpuDevice:i}=this.redGPUContext,g=getMipLevelCount(this.width,this.height);this.#Zd=i.createTexture({label:"SkyLight_Irradiance_Source_CubeTexture",size:[this.width,this.height,6],format:"rgba16float",usage:GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT,mipLevelCount:g}),this.#Jd=this.#Zd.createView({dimension:"2d-array",baseMipLevel:0,mipLevelCount:1}),this.#Qd=new DirectCubeTexture(this.redGPUContext,`SkyLight_Irradiance_LUTTexture_${createUUID()}`),this.#U=this.createComputePipeline("Base",za.defaultSource)}#rm(i,g,x=[16,16,1],v=this.width,_=this.height,y=this.depth){const{commandEncoderManager:b}=this.redGPUContext;b.addResourceComputePass(`SkyLight_${this.label}_ComputePass`,b=>{b.setPipeline(i),b.setBindGroup(0,g),b.dispatchWorkgroups(Math.ceil(v/x[0]),Math.ceil(_/x[1]),Math.ceil(y/x[2]))})}}Object.freeze(SkyLightIrradianceGenerator);class SkyLight extends RedGPUObject{dirty=!0;#im;#Je;#nm;#ne;#Xd;#am=!1;constructor(i,g,x){super(i),this.#Xd=g,this.#ne=x,this.#nm=new DirectCubeTexture(i,`SkyAtmosphere_Irradiance_LUTTexture_${createUUID()}`,this.resourceManager.createManagedTexture({size:[32,32,6],format:"rgba16float",usage:GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT,dimension:"2d",mipLevelCount:1,label:"SkyAtmosphere_Irradiance_LUT"})),this.#im=new SkyLightReflectionGenerator(i,this.#Xd,this.#ne),this.#Je=new SkyLightIrradianceGenerator(i,this.#Xd,this.#ne)}get irradianceLUT(){return this.#nm}get reflectionLUT(){return this.#im.prefilteredTexture}async update(i){this.dirty&&!this.#am&&(this.#am=!0,this.#im.render(i.transmittanceLUT,i.multiScatLUT,i.skyViewLUT),this.#Je.render(i.transmittanceLUT,i.multiScatLUT,i.skyViewLUT),this.resourceManager.irradianceGenerator.render(this.#Je.sourceCubeTexture,this.#nm.gpuTexture),this.#nm.notifyUpdate(),this.#am=!1,this.dirty=!1)}}Object.freeze(SkyLight);class SkyAtmosphereBackground extends RedGPUObject{#sm;#om;#um;#lm;#cm=!0;#hm;#ls;constructor(i){super(i),this.#sm=this.gpuDevice.createBindGroupLayout({label:"SKY_ATMOSPHERE_BACKGROUND_BGL_2",entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:2,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:3,visibility:GPUShaderStage.FRAGMENT,sampler:{}}]})}render(i,g,x,v,_){const{currentRenderPassEncoder:y,view:b}=i,{gpuDevice:S,antialiasingManager:w}=this,{useMSAA:L,msaaID:k}=w,H=this.#ls!==k;if(this.#cm||H||this.#hm!==b.systemUniform_Vertex_UniformBindGroup){this.#ls=k,this.#fm(L),this.#cm=!1,this.#hm=b.systemUniform_Vertex_UniformBindGroup,this.#om=S.createBindGroup({label:"SKY_ATMOSPHERE_BACKGROUND_BG_2",layout:this.#sm,entries:[{binding:0,resource:g.gpuTextureView},{binding:1,resource:x.gpuTextureView},{binding:2,resource:v.gpuTextureView},{binding:3,resource:_.gpuSampler}]});const i=S.createRenderBundleEncoder({...b.basicRenderBundleEncoderDescriptor,label:"SKY_ATMOSPHERE_BACKGROUND_BUNDLE_ENCODER"});i.setPipeline(this.#um),i.setBindGroup(0,b.systemUniform_Vertex_UniformBindGroup),i.setBindGroup(1,this.#om),i.draw(3,1,0,0),this.#lm=i.finish({label:"SKY_ATMOSPHERE_BACKGROUND_BUNDLE"})}y.executeBundles([this.#lm])}#fm(i){const{gpuDevice:g,resourceManager:x}=this,v=x.createGPUShaderModule("SkyAtmosphere_Background_Vertex_ShaderModule",{code:"#redgpu_include SYSTEM_UNIFORM;struct VertexOutput{@builtin(position)position:vec4,@location(0)vertexPosition:vec4,};@vertex fn main(@builtin(vertex_index)vertexIndex:u32)->VertexOutput{var output:VertexOutput;let x=f32((i32(vertexIndex)<<1u)& 2i)*2.0-1.0;let y=f32(i32(vertexIndex)& 2i)*2.0-1.0;let ndcPos=vec4(x,y,1.0,1.0);output.position=ndcPos.xyww;let u_camera=systemUniforms.camera;let invProj=systemUniforms.projection.inverseProjectionMatrix;var viewRotation=u_camera.viewMatrix;viewRotation[3]=vec4(.0,.0,.0,1.0);let invViewRotation=transpose(viewRotation);var viewDir=invProj*ndcPos;viewDir=vec4(viewDir.xyz/viewDir.w,.0);let worldDir=invViewRotation*viewDir;output.vertexPosition=vec4(worldDir.xyz,1.0);return output;}"}),_=x.createGPUShaderModule("SkyAtmosphere_Background_Fragment_ShaderModule",{code:"#redgpu_include math.PI #redgpu_include math.DEG_TO_RAD #redgpu_include SYSTEM_UNIFORM;#redgpu_include skyAtmosphere.skyAtmosphereFn;struct VertexOutput{@builtin(position)position:vec4,@location(0)vertexPosition:vec4,};struct FragmentOutput{@location(0)color:vec4,@location(1)normal:vec4,@location(2)motionVector:vec4,};@group(1)@binding(0)var bg_transmittanceLUT:texture_2d;@group(1)@binding(1)var bg_multiScatLUT:texture_2d;@group(1)@binding(2)var bg_skyViewLUT:texture_2d;@group(1)@binding(3)var bg_skyAtmosphereSampler:sampler;@fragment fn main(input:VertexOutput)->FragmentOutput{let uniforms=systemUniforms.skyAtmosphere;let groundRadius=uniforms.groundRadius;let atmosphereHeight=uniforms.atmosphereHeight;let viewDir=normalize(input.vertexPosition.xyz);let viewHeight=max(.0,uniforms.cameraHeight);let camPos=vec3(.0,groundRadius+viewHeight,.0);let tEarth=getRaySphereIntersection(camPos,viewDir,groundRadius);let isGroundHit=groundRadius>.0&&tEarth>.0;var baseRadiance:vec3;var skyTransmittance:f32=1.0;if(isGroundHit){let hitPoint=camPos+viewDir*tEarth;let up=normalize(hitPoint);let sunDir=normalize(uniforms.sunDirection);let localCosSun=dot(up,sunDir);let sunT=getTransmittance(bg_transmittanceLUT,bg_skyAtmosphereSampler,.0,localCosSun,atmosphereHeight);let msUV=vec2(clamp(localCosSun*0.5+0.5,.001,0.999),1.0);let msEnergy=textureSampleLevel(bg_multiScatLUT,bg_skyAtmosphereSampler,msUV,.0).rgb;baseRadiance=evaluateGroundRadiance(localCosSun,sunT,msEnergy,uniforms.groundAlbedo);skyTransmittance=.0;}else{let skyUV=getSkyViewUV(viewDir,viewHeight,groundRadius,atmosphereHeight);let skySample=textureSampleLevel(bg_skyViewLUT,bg_skyAtmosphereSampler,skyUV,.0);baseRadiance=skySample.rgb;skyTransmittance=skySample.a;}var finalRadiance=baseRadiance*uniforms.sunIntensity*systemUniforms.preExposure;if(!isGroundHit&&viewDir.y>.0){let cloudR=groundRadius+uniforms.cloudHeight;let tCloud=getRaySphereIntersection(camPos,viewDir,cloudR);if(tCloud>.0){let hitP=camPos+viewDir*tCloud;let cloudMask=getCloudDensity(hitP,uniforms);if(cloudMask>.0){let sunDir=normalize(uniforms.sunDirection);let sunT=getTransmittance(bg_transmittanceLUT,bg_skyAtmosphereSampler,uniforms.cloudHeight,sunDir.y,atmosphereHeight);let cloudNormal=getCloudNormal(hitP,uniforms);let cloudShadow=saturate(dot(cloudNormal,sunDir)*0.5+0.5);let cloudColor=(sunT*uniforms.sunIntensity*0.5+baseRadiance*0.5)*cloudShadow*systemUniforms.preExposure;finalRadiance=mix(finalRadiance,cloudColor,cloudMask*skyTransmittance);}}}var output:FragmentOutput;output.color=vec4(finalRadiance,1.0);output.normal=vec4(.0,.0,.0,.0);output.motionVector=vec4(.0,.0,.0,.0);return output;}"});this.#um=g.createRenderPipeline({label:"SkyAtmosphere_Background_Pipeline",layout:g.createPipelineLayout({bindGroupLayouts:[x.getGPUBindGroupLayout(ResourceManager.PRESET_GPUBindGroupLayout_System),this.#sm]}),vertex:{module:v,entryPoint:"main",buffers:[]},fragment:{module:_,entryPoint:"main",targets:[{format:"rgba16float"},{format:navigator.gpu.getPreferredCanvasFormat()},{format:"rgba16float"}]},primitive:{topology:"triangle-list",cullMode:"none"},depthStencil:{format:"depth32float",depthWriteEnabled:!1,depthCompare:"less-equal"},multisample:{count:i?4:1}})}}Object.freeze(SkyAtmosphereBackground);var $a="let id=global_id.xy;let size=textureDimensions(outputTexture);if(id.x>=size.x||id.y>=size.y){return;}let uv=(vec2(id)+0.5)/vec2(size);let sceneSample=textureLoad(sourceTexture,id);var sceneColor=sceneSample.rgb;let rawDepth=fetchDepth(id);let invP=systemUniforms.projection.inverseProjectionMatrix;let viewSpacePos=vec3((uv.x*2.0-1.0)*invP[0][0],((1.0-uv.y)*2.0-1.0)*invP[1][1],-1.0);let rayLengthRatio=length(viewSpacePos);let worldRotation=mat3x3(systemUniforms.camera.inverseViewMatrix[0].xyz,systemUniforms.camera.inverseViewMatrix[1].xyz,systemUniforms.camera.inverseViewMatrix[2].xyz);let viewDir=normalize(worldRotation*viewSpacePos);let sunDir=normalize(uniforms.sunDirection);let viewSunCos=dot(viewDir,sunDir);let mappingH=max(.0,uniforms.cameraHeight);let groundRadius=uniforms.groundRadius;let atmosphereHeight=uniforms.atmosphereHeight;var baseScattering:vec3=vec3(.0);var atmosphereTrans:f32=1.0;var sceneBlendingTrans:f32=1.0;if(rawDepth>=1.0){let skyUV=getSkyViewUV(viewDir,mappingH,groundRadius,atmosphereHeight);atmosphereTrans=textureSampleLevel(skyViewLUT,basicSampler,skyUV,.0).a;sceneBlendingTrans=1.0;}else{let depthKm=getLinearizeDepth(rawDepth,systemUniforms.camera.nearClipping,systemUniforms.camera.farClipping)/1000.0;let actualDist=depthKm*rayLengthRatio;let maxApDist=uniforms.aerialPerspectiveDistanceScale;let apDist=clamp(actualDist-uniforms.aerialPerspectiveStartDepth,.0,maxApDist);let apW=clamp(sqrt(apDist/maxApDist),.0,1.0);var apSample=textureSampleLevel(aerialPerspectiveLUT,basicSampler,vec3(uv.x,uv.y,apW),.0);if(actualDist(scatM*phaseM))*sunT;let localExt=scatR+vec3((uniforms.mieScattering+uniforms.mieAbsorption)*d.rhoM*uniforms.skyLuminanceFactor)+uniforms.absorptionCoefficient*d.rhoO;let analyticalScat=localScat*actualDist;let analyticalTrans=exp(-localExt*actualDist);let analyticalA=(analyticalTrans.r+analyticalTrans.g+analyticalTrans.b)/3.0;apSample=mix(vec4(analyticalScat,analyticalA),apSample,smoothstep(.0,NEAR_FIELD_CORRECTION_DIST,actualDist));}baseScattering=apSample.rgb;atmosphereTrans=apSample.a;sceneBlendingTrans=apSample.a;}let camPos=vec3(.0,mappingH+groundRadius,.0);let sunShadow=getPlanetShadowMask(camPos,sunDir,groundRadius,uniforms);let mieGlow=getMieGlowAmountUnit(viewSunCos,mappingH,uniforms,transmittanceLUT,basicSampler,vec3(atmosphereTrans),.0);let hitsVirtualGround=groundRadius>.0&&getRaySphereIntersection(camPos,viewDir,groundRadius)>.0;let drawSunDisk=(rawDepth>=1.0)&&!hitsVirtualGround;let sunDisk=select(vec3(.0),getSunDiskRadianceUnit(viewSunCos,uniforms.sunSize,uniforms.sunLimbDarkening,vec3(atmosphereTrans),.01,uniforms),drawSunDisk);var finalCloudMask:f32=.0;if(drawSunDisk){let cloudR=groundRadius+uniforms.cloudHeight;let tCloud=getRaySphereIntersection(camPos,viewDir,cloudR);if(tCloud>.0){let hitP=camPos+viewDir*tCloud;finalCloudMask=getCloudDensity(hitP,uniforms);}}let addedRadiance=(mieGlow+sunDisk)*sunShadow*(1.0-finalCloudMask);let totalScattering=(baseScattering*uniforms.sunIntensity+addedRadiance*uniforms.sunIntensity)*systemUniforms.preExposure;let finalColor=sceneColor*saturate(sceneBlendingTrans)+totalScattering;textureStore(outputTexture,id,vec4(finalColor,1.0));";class SkyAtmospherePostEffect extends ASinglePassPostEffect{#uh;constructor(i,g){super(i),this.#uh=g;const createCode=i=>["#redgpu_include depth.getLinearizeDepth","#redgpu_include skyAtmosphere.skyAtmosphereFn","@group(0) @binding(0) var sourceTexture : texture_storage_2d;","@group(0) @binding(1) var transmittanceLUT : texture_2d;","@group(0) @binding(2) var multiScatLUT : texture_2d;","@group(0) @binding(3) var skyViewLUT : texture_2d;","@group(0) @binding(4) var aerialPerspectiveLUT : texture_3d;","@group(0) @binding(5) var skyAtmosphereIrradianceLUT : texture_cube;","",ft.POST_EFFECT_SYSTEM_UNIFORM,"@group(2) @binding(5) var basicSampler : sampler;","",`@group(2) @binding(0) var depthTexture : ${i?"texture_depth_multisampled_2d":"texture_depth_2d"};`,"@group(2) @binding(1) var gBufferNormalTexture : texture_2d;","@group(2) @binding(2) var gBufferMotionVector : texture_2d;",`@group(2) @binding(3) var prevDepthTexture : ${i?"texture_depth_multisampled_2d":"texture_depth_2d"};`,"","@group(3) @binding(0) var outputTexture : texture_storage_2d;","","fn fetchDepth(pos: vec2) -> f32 {"," let dSize = textureDimensions(depthTexture);"," let clampedPos = min(pos, dSize - 1u);"," return textureLoad(depthTexture, clampedPos, 0);","}","","@compute @workgroup_size(16, 16)","fn main(@builtin(global_invocation_id) global_id : vec3) {"," let uniforms = systemUniforms.skyAtmosphere;"," let viewHeight = uniforms.cameraHeight;",$a,"}"].join("\n");this.init(i,"POST_EFFECT_SKY_ATMOSPHERE",{msaa:createCode(!0),nonMsaa:createCode(!1)})}render(i,g,x,v){const _=this.#uh;return super.render(i,g,x,v,{texture:_.transmittanceLUT.gpuTexture,textureView:_.transmittanceLUT.gpuTextureView},{texture:_.multiScatLUT.gpuTexture,textureView:_.multiScatLUT.gpuTextureView},{texture:_.skyViewLUT.gpuTexture,textureView:_.skyViewLUT.gpuTextureView},{texture:_.aerialPerspectiveLUT.gpuTexture,textureView:_.aerialPerspectiveLUT.gpuTextureView},{texture:_.skyAtmosphereIrradianceLUT.gpuTexture,textureView:_.skyAtmosphereIrradianceLUT.gpuTextureView})}}Object.freeze(SkyAtmospherePostEffect);const ja=parseWGSL("SkyAtmosphere_Core",it).uniforms.params;class SkyAtmosphere extends RedGPUObject{#dm;#mm;#pm;#gm;#ne;#Xd;#xm;#vm;#_m;#ym={rayleighScattering:[.005802,.013558,.0331],rayleighExponentialDistribution:8,mieScattering:[.003996,.003996,.003996],mieAnisotropy:.8,mieAbsorption:[444e-6,444e-6,444e-6],mieExponentialDistribution:1.2,absorptionCoefficient:[65e-5,.001881,85e-6],absorptionTipAltitude:25,groundAlbedo:[.4,.4,.4],absorptionTentWidth:15,skyLuminanceFactor:[1,1,1],multiScatteringFactor:1,sunDirection:new Float32Array([0,1,0]),transmittanceMinLightElevationAngle:-90,groundRadius:6360,atmosphereHeight:60,aerialPerspectiveDistanceScale:100,aerialPerspectiveStartDepth:0,sunIntensity:1e5,sunSize:.533,sunLimbDarkening:.5,cameraHeight:.001,cloudTime:0,cloudTimeMultiplier:0,cloudCoverage:.4,cloudDensity:.7,cloudHeight:5};#bm=null;#Sm=null;#Tm=!0;#wm=!0;#Mm=!0;#Pm=-1;#Rm=create$4();constructor(i){super(i),this.#Xd=new UniformBuffer(this.redGPUContext,new ArrayBuffer(ja.arrayBufferByteLength),"SkyAtmosphere_Shared_UniformBuffer"),this.#ne=new Sampler(i,{magFilter:"linear",minFilter:"linear",mipmapFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"}),this.#dm=new TransmittanceGenerator(i,this.#Xd,this.#ne),this.#mm=new MultiScatteringGenerator(i,this.#Xd,this.#ne),this.#pm=new SkyViewGenerator(i,this.#Xd,this.#ne),this.#gm=new AerialPerspectiveGenerator(i,this.#Xd,this.#ne),this.#xm=new SkyLight(i,this.#Xd,this.#ne),this.#vm=new SkyAtmosphereBackground(i),this.#_m=new SkyAtmospherePostEffect(i,this)}get postEffect(){return this.#_m}get params(){return this.#ym}get cloudTimeMultiplier(){return this.#ym.cloudTimeMultiplier}set cloudTimeMultiplier(i){this.#Cm("cloudTimeMultiplier",i,!1,!1,!1,i=>validateNumberRange(i))}get cloudCoverage(){return this.#ym.cloudCoverage}set cloudCoverage(i){this.#Cm("cloudCoverage",i,!1,!1,!1,i=>validateNumberRange(i,0,1))}get cloudDensity(){return this.#ym.cloudDensity}set cloudDensity(i){this.#Cm("cloudDensity",i,!1,!1,!1,i=>validateNumberRange(i,0,1))}get cloudHeight(){return this.#ym.cloudHeight}set cloudHeight(i){this.#Cm("cloudHeight",i,!1,!1,!1,i=>validatePositiveNumberRange(i,.1,20))}get aerialPerspectiveDistanceScale(){return this.#ym.aerialPerspectiveDistanceScale}set aerialPerspectiveDistanceScale(i){this.#Cm("aerialPerspectiveDistanceScale",i,!1,!0,!0,i=>validatePositiveNumberRange(i,1,1e3))}get aerialPerspectiveStartDepth(){return this.#ym.aerialPerspectiveStartDepth}set aerialPerspectiveStartDepth(i){this.#Cm("aerialPerspectiveStartDepth",i,!1,!0,!0,i=>validatePositiveNumberRange(i,0,100))}get transmittanceMinLightElevationAngle(){return this.#ym.transmittanceMinLightElevationAngle}set transmittanceMinLightElevationAngle(i){this.#Cm("transmittanceMinLightElevationAngle",i,!0,!0,!0,i=>validateNumberRange(i,-90,90))}get groundRadius(){return this.#ym.groundRadius}set groundRadius(i){this.#Cm("groundRadius",i,!0,!1,!0,i=>validatePositiveNumberRange(i,1))}get atmosphereHeight(){return this.#ym.atmosphereHeight}set atmosphereHeight(i){this.#Cm("atmosphereHeight",i,!0,!1,!0,i=>validatePositiveNumberRange(i,1))}get mieScattering(){return[this.#ym.mieScattering[0],this.#ym.mieScattering[1],this.#ym.mieScattering[2]]}set mieScattering(i){this.#Cm("mieScattering",[...i],!0,!1,!0)}get mieAbsorption(){return[this.#ym.mieAbsorption[0],this.#ym.mieAbsorption[1],this.#ym.mieAbsorption[2]]}set mieAbsorption(i){this.#Cm("mieAbsorption",[...i],!0,!1,!0)}get rayleighScattering(){return[this.#ym.rayleighScattering[0],this.#ym.rayleighScattering[1],this.#ym.rayleighScattering[2]]}set rayleighScattering(i){this.#Cm("rayleighScattering",[...i],!0,!1,!0)}get rayleighExponentialDistribution(){return this.#ym.rayleighExponentialDistribution}set rayleighExponentialDistribution(i){this.#Cm("rayleighExponentialDistribution",i,!0,!1,!0,i=>validatePositiveNumberRange(i,.1,100))}get mieExponentialDistribution(){return this.#ym.mieExponentialDistribution}set mieExponentialDistribution(i){this.#Cm("mieExponentialDistribution",i,!0,!1,!0,i=>validatePositiveNumberRange(i,.1,100))}get mieAnisotropy(){return this.#ym.mieAnisotropy}set mieAnisotropy(i){this.#Cm("mieAnisotropy",i,!0,!1,!0,i=>validateNumberRange(i,0,.999))}get groundAlbedo(){return[this.#ym.groundAlbedo[0],this.#ym.groundAlbedo[1],this.#ym.groundAlbedo[2]]}set groundAlbedo(i){this.#Cm("groundAlbedo",[...i],!0,!1,!0)}get absorptionCoefficient(){return[this.#ym.absorptionCoefficient[0],this.#ym.absorptionCoefficient[1],this.#ym.absorptionCoefficient[2]]}set absorptionCoefficient(i){this.#Cm("absorptionCoefficient",[...i],!0,!1,!0)}get absorptionTipAltitude(){return this.#ym.absorptionTipAltitude}set absorptionTipAltitude(i){this.#Cm("absorptionTipAltitude",i,!0,!1,!0,i=>validatePositiveNumberRange(0,100))}get absorptionTentWidth(){return this.#ym.absorptionTentWidth}set absorptionTentWidth(i){this.#Cm("absorptionTentWidth",i,!0,!1,!0,i=>validatePositiveNumberRange(i,1,50))}get multiScatteringFactor(){return this.#ym.multiScatteringFactor}set multiScatteringFactor(i){this.#Cm("multiScatteringFactor",i,!0,!1,!0,i=>validatePositiveNumberRange(i,0,10))}get sunSize(){return this.#ym.sunSize}set sunSize(i){this.#Cm("sunSize",i,!1,!0,!0,i=>validatePositiveNumberRange(i,.01,10))}get sunLimbDarkening(){return this.#ym.sunLimbDarkening}set sunLimbDarkening(i){this.#Cm("sunLimbDarkening",i,!1,!1,!0,i=>validateNumberRange(i,0,10))}get skyLuminanceFactor(){return[this.#ym.skyLuminanceFactor[0],this.#ym.skyLuminanceFactor[1],this.#ym.skyLuminanceFactor[2]]}set skyLuminanceFactor(i){this.#Cm("skyLuminanceFactor",[...i],!0,!1,!0)}get transmittanceLUT(){return this.#dm.lutTexture}get multiScatLUT(){return this.#mm.lutTexture}get skyViewLUT(){return this.#pm.lutTexture}get aerialPerspectiveLUT(){return this.#gm.lutTexture}get skyAtmosphereIrradianceLUT(){return this.#xm.irradianceLUT}get skyAtmosphereReflectionLUT(){return this.#xm.reflectionLUT}get skyLight(){return this.#xm}get atmosphereSampler(){return this.#ne}renderBackground(i){this.#vm.render(i,this.#dm.lutTexture,this.#mm.lutTexture,this.skyViewLUT,this.#ne)}render(i,g,x,v){return this.update(i),this.#_m.render(i,g,x,v)}update(i){const g=i.renderViewStateData.frameIndex;this.#Pm!==g&&(this.#Pm=g,this.#ym.cloudTime=.001*i.renderViewStateData.time*this.#ym.cloudTimeMultiplier,this.#Mm=!0,this.#Bm(i),this.#Dm(i))}#Em(i,g,x){this.#Mm=!0,i&&(this.#Tm=!0),g&&(this.#wm=!0),x&&(this.#xm.dirty=!0)}#Bm(i){const g=i.scene.lightManager.directionalLights[0]||null,x=this.#Sm!==g;if(x&&(this.#Sm=g,this.#bm=g),g){const i=g.direction,v=this.#ym.sunDirection,_=1e-4,y=Math.sqrt(i[0]*i[0]+i[1]*i[1]+i[2]*i[2]),b=-(y>_?i[0]/y:i[0]),S=-(y>_?i[1]/y:i[1]),w=-(y>_?i[2]/y:i[2]),L=Math.abs(b-v[0])>_||Math.abs(S-v[1])>_||Math.abs(w-v[2])>_;(x||L)&&(v[0]=b,v[1]=S,v[2]=w,this.#Em(!1,!0,!0));const k=g.lux*g.intensityMultiplier;Math.abs(this.#ym.sunIntensity-k)>_&&(this.#ym.sunIntensity=k,this.#Em(!1,!1,!0))}}#Dm(i){const{rawCamera:g}=i,x=[g.x,g.y,g.z],v=Math.max(.001,x[1]/1e3);Math.abs(this.#ym.cameraHeight-v)>1e-4&&(this.#ym.cameraHeight=v,this.#Mm=!0);const _=g.viewMatrix;let y=!1;for(let i=0;i<16;i++)if(Math.abs(_[i]-this.#Rm[i])>1e-4){y=!0;break}y&&(copy$4(this.#Rm,_),this.#wm=!0),this.#Mm&&(this.#Im(),this.#Mm=!1),this.#Tm&&(this.#dm.render(),this.#mm.render(this.#dm.lutTexture),this.#Tm=!1,this.#wm=!0,this.#xm.dirty=!0),this.#wm&&(this.#pm.render(this.#dm.lutTexture,this.#mm.lutTexture),this.#gm.render(i,this.#dm.lutTexture,this.#mm.lutTexture),this.#wm=!1),this.#xm.update(this)}#Cm(i,g,x,v,_,y){y&&y(g),this.#ym[i]=g,this.#Em(x,v,_)}#Im(){const{members:i}=ja,g=this.#Xd.dataViewF32,x=this.#Xd.dataViewU32;for(const[v,_]of Object.entries(i)){const i=this.#ym[v];if(void 0!==i){const v=_,y=v.uniformOffset/4;if("number"==typeof i)v.View===Float32Array?g[y]=i:x[y]=i;else if(i instanceof Float32Array||Array.isArray(i))for(let x=0;xi===this.#Lm);if(!i)throw new Error(`Invalid blendMode value: ${this.#Lm}`);return i[0]}set blendMode(i){let g;if("string"==typeof i){if(!(i in Xa))throw new Error(`Invalid blendMode key: ${i}`);g=Xa[i]}else{if("number"!=typeof i||!Object.values(Xa).includes(i))throw new Error(`Invalid blendMode: ${i}`);g=i}this.#Lm=g,this.#Um(g)}get rotation(){return this.#Am}set rotation(i){this.#Am=i,super.rotationZ=i}setScale(i,g){g=g??i,super.setScale(i,g,1)}setPosition(i,g){g=g??i,super.setPosition(i,g,0)}setRotation(i){this.rotation=i}#Um(i){const{blendColorState:g,blendAlphaState:x}=this._material;switch(i){case Xa.NORMAL:g.operation=li.ADD,g.srcFactor=ui.SRC_ALPHA,g.dstFactor=ui.ONE_MINUS_SRC_ALPHA,x.operation=li.ADD,x.srcFactor=ui.SRC_ALPHA,x.dstFactor=ui.ONE_MINUS_SRC_ALPHA;break;case Xa.MULTIPLY:g.operation=li.ADD,g.srcFactor=ui.ONE_MINUS_DST_ALPHA,g.dstFactor=ui.ONE_MINUS_SRC_ALPHA,x.operation=li.ADD,x.srcFactor=ui.SRC_ALPHA,x.dstFactor=ui.ONE_MINUS_SRC_ALPHA;break;case Xa.LIGHTEN:g.operation=li.MAX,g.srcFactor=ui.ONE,g.dstFactor=ui.ONE,x.operation=li.ADD,x.srcFactor=ui.SRC_ALPHA,x.dstFactor=ui.ONE_MINUS_SRC_ALPHA;break;case Xa.SCREEN:g.operation=li.ADD,g.srcFactor=ui.ONE,g.dstFactor=ui.ONE_MINUS_SRC,x.operation=li.ADD,x.srcFactor=ui.SRC_ALPHA,x.dstFactor=ui.ONE_MINUS_SRC_ALPHA;break;case Xa.LINEAR_DODGE:g.operation=li.ADD,g.srcFactor=ui.ONE,g.dstFactor=ui.ONE,x.operation=li.ADD,x.srcFactor=ui.SRC_ALPHA,x.dstFactor=ui.ONE;break;case Xa.SUBTRACT:g.operation=li.REVERSE_SUBTRACT,g.srcFactor=ui.SRC_ALPHA,g.dstFactor=ui.ONE_MINUS_SRC_ALPHA,x.operation=li.REVERSE_SUBTRACT,x.srcFactor=ui.ONE,x.dstFactor=ui.ONE;break;case Xa.DIFFERENCE:g.operation=li.SUBTRACT,g.srcFactor=ui.ONE,g.dstFactor=ui.ONE,x.operation=li.SUBTRACT,x.srcFactor=ui.ONE,x.dstFactor=ui.ONE;break;case Xa.EXCLUSION:g.operation=li.ADD,g.srcFactor=ui.ONE_MINUS_DST_ALPHA,g.dstFactor=ui.ONE_MINUS_SRC_ALPHA,x.operation=li.ADD,x.srcFactor=ui.ONE,x.dstFactor=ui.ONE;break;default:console.warn(`Unsupported blend mode: ${i}`)}}};return Object.defineProperty(g.prototype,"is2DMeshType",{value:!0,writable:!1}),g}var qa=Object.freeze({__proto__:null,LODManager:LODManager,MeshBase:MeshBase,Object3DContainer:Object3DContainer,VertexGPURenderInfo:VertexGPURenderInfo,createMeshVertexUniformBuffers:createMeshVertexUniformBuffers,mixInMesh2D:mixInMesh2D}),Ya=Object.freeze({__proto__:null,AView:AView,RenderViewStateData:RenderViewStateData,ViewRenderTextureManager:ViewRenderTextureManager,ViewTransform:ViewTransform});class View2D extends View3D{constructor(i,g,x){super(i,g,new Camera2D,x)}}Object.freeze(View2D);class Group3D extends Object3DContainer{modelMatrix=create$4();localMatrix=create$4();#cs;#wi=0;#Pi=0;#Mi=0;#hs=[0,0,0];#fs=0;#ds=0;#ms=0;#gs=1;#xs=1;#vs=1;#_s=[1,1,1];#ys=0;#bs=0;#Ss=0;#Ts=[0,0,0];#km=!0;constructor(i){super(),i&&(this.name=i)}get dirtyTransform(){return this.#km}set dirtyTransform(i){this.#km=i}get parent(){return this.#cs}set parent(i){this.#cs=i}get pivotX(){return this.#fs}set pivotX(i){this.#fs=i,this.dirtyTransform=!0}get pivotY(){return this.#ds}set pivotY(i){this.#ds=i,this.dirtyTransform=!0}get pivotZ(){return this.#ms}set pivotZ(i){this.#ms=i,this.dirtyTransform=!0}get x(){return this.#wi}set x(i){this.#wi=this.#hs[0]=i,this.dirtyTransform=!0}get y(){return this.#Mi}set y(i){this.#Mi=this.#hs[1]=i,this.dirtyTransform=!0}get z(){return this.#Pi}set z(i){this.#Pi=this.#hs[2]=i,this.dirtyTransform=!0}get position(){return this.#hs}get scaleX(){return this.#gs}set scaleX(i){this.#gs=this.#_s[0]=i,this.dirtyTransform=!0}get scaleY(){return this.#xs}set scaleY(i){this.#xs=this.#_s[1]=i,this.dirtyTransform=!0}get scaleZ(){return this.#vs}set scaleZ(i){this.#vs=this.#_s[2]=i,this.dirtyTransform=!0}get scale(){return this.#_s}get rotationX(){return this.#ys}set rotationX(i){this.#ys=this.#Ts[0]=i,this.dirtyTransform=!0}get rotationY(){return this.#bs}set rotationY(i){this.#bs=this.#Ts[1]=i,this.dirtyTransform=!0}get rotationZ(){return this.#Ss}set rotationZ(i){this.#Ss=this.#Ts[2]=i,this.dirtyTransform=!0}get rotation(){return this.#Ts}setScale(i,g,x){g=g??i,x=x??i;const v=this.#_s;this.#gs=v[0]=i,this.#xs=v[1]=g,this.#vs=v[2]=x,this.dirtyTransform=!0}setPosition(i,g,x){g=g??i,x=x??i;const v=this.#hs;this.#wi=v[0]=i,this.#Mi=v[1]=g,this.#Pi=v[2]=x,this.dirtyTransform=!0}setRotation(i,g,x){g=g??i,x=x??i;const v=this.#Ts;this.#ys=v[0]=i,this.#bs=v[1]=g,this.#Ss=v[2]=x,this.dirtyTransform=!0}render(i){const{view:g,isScene2DMode:x}=i;let v;x&&(this.#Pi=0,this.#ms=0),this.dirtyTransform&&(v=!0,updateObject3DMatrix(this,g)),this.dirtyTransform&&(v=!0,this.dirtyTransform=!1),i.renderResults.num3DGroups++;const{children:_}=this;let y=0;const b=_.length;for(;y,tintBlendMode:u32,};@group(2)@binding(0)varuniforms:Uniforms;@group(2)@binding(1)var diffuseTextureSampler:sampler;@group(2)@binding(2)var diffuseTexture:texture_2d;struct InputData{@builtin(position)position:vec4,@location(0)vertexPosition:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,@location(7)currentClipPos:vec4,@location(8)prevClipPos:vec4,@location(11)combinedOpacity:f32,@location(12)motionVector:vec3,@location(13)shadowCoord:vec3,@location(15)@interpolate(flat)pickingId:vec4,};@fragment fn main(inputData:InputData)->OutputFragment{var output:OutputFragment;var finalColor:vec4=vec4(.0);#redgpu_if diffuseTexture finalColor=textureSample(diffuseTexture,diffuseTextureSampler,inputData.uv);#redgpu_endIf let alpha2D=select(finalColor.a,1.0,systemUniforms.isView3D==1u);finalColor=vec4(finalColor.rgb*alpha2D,finalColor.a*uniforms.opacity*inputData.combinedOpacity);#redgpu_if useTint finalColor=getTintBlendMode(finalColor,uniforms.tintBlendMode,uniforms.tint);#redgpu_endIf if(systemUniforms.isView3D==1&&finalColor.a==.0){discard;}output.color=vec4(finalColor.rgb,finalColor.a);output.gBufferMotionVector=vec4(getMotionVector(inputData.currentClipPos,inputData.prevClipPos),.0,1.0);return output;};");class BitmapMaterial extends AUVTransformBaseMaterial{constructor(i,g,x){super(i,"BITMAP_MATERIAL",Za,2),x&&(this.name=x),this.diffuseTexture=g,this.diffuseTextureSampler=new Sampler(this.redGPUContext),this.initGPURenderInfos()}}defineSampler(BitmapMaterial,[{key:"diffuseTextureSampler"}]),defineTexture(BitmapMaterial,[{key:"diffuseTexture"}]),Object.freeze(BitmapMaterial);var Ja="#redgpu_include SYSTEM_UNIFORM;#redgpu_include math.billboard.getBillboardMatrix;struct MatrixList{modelMatrix:mat4x4,normalModelMatrix:mat4x4,}struct VertexUniforms{matrixList:MatrixList,pickingId:u32,useBillboardPerspective:u32,useBillboard:u32,combinedOpacity:f32,};@group(1)@binding(0)varvertexUniforms:VertexUniforms;struct InputData{@location(0)a_position:vec3,@location(1)a_normal:vec3,@location(2)a_uv:vec2,@location(3)a_tangent:vec4,@location(4)position:vec3,@location(5)alpha:f32,@location(6)rotation:vec3,@location(7)scale:f32,};struct VertexOutput{@builtin(position)position:vec4,@location(0)vertexPosition:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,@location(7)currentClipPos:vec4,@location(8)prevClipPos:vec4,@location(11)combinedOpacity:f32,@location(12)motionVector:vec3,@location(13)shadowCoord:vec3,@location(14)@interpolate(flat)receiveShadow:f32,@location(15)@interpolate(flat)pickingId:vec4,};fn mat4_inverse(a:mat4x4)->mat4x4{var a00:f32=a[0][0];var a01:f32=a[0][1];var a02:f32=a[0][2];var a03:f32=a[0][3];var a10:f32=a[1][0];var a11:f32=a[1][1];var a12:f32=a[1][2];var a13:f32=a[1][3];var a20:f32=a[2][0];var a21:f32=a[2][1];var a22:f32=a[2][2];var a23:f32=a[2][3];var a30:f32=a[3][0];var a31:f32=a[3][1];var a32:f32=a[3][2];var a33:f32=a[3][3];var b00:f32=a00*a11-a01*a10;var b01:f32=a00*a12-a02*a10;var b02:f32=a00*a13-a03*a10;var b03:f32=a01*a12-a02*a11;var b04:f32=a01*a13-a03*a11;var b05:f32=a02*a13-a03*a12;var b06:f32=a20*a31-a21*a30;var b07:f32=a20*a32-a22*a30;var b08:f32=a20*a33-a23*a30;var b09:f32=a21*a32-a22*a31;var b10:f32=a21*a33-a23*a31;var b11:f32=a22*a33-a23*a32;var det:f32=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;if(det !=.0){det=1.0/det;return mat4x4((a11*b11-a12*b10+a13*b09)*det,(a02*b10-a01*b11-a03*b09)*det,(a31*b05-a32*b04+a33*b03)*det,(a22*b04-a21*b05-a23*b03)*det,(a12*b08-a10*b11-a13*b07)*det,(a00*b11-a02*b08+a03*b07)*det,(a32*b02-a30*b05-a33*b01)*det,(a20*b05-a22*b02+a23*b01)*det,(a10*b10-a11*b08+a13*b06)*det,(a01*b08-a00*b10-a03*b06)*det,(a30*b04-a31*b02+a33*b00)*det,(a21*b02-a20*b04-a23*b00)*det,(a11*b07-a10*b09-a12*b06)*det,(a00*b09-a01*b07+a02*b06)*det,(a31*b01-a30*b03-a32*b00)*det,(a20*b03-a21*b01+a22*b00)*det);}return mat4x4(.0,.0,.0,.0,.0,.0,.0,.0,.0,.0,.0,.0,.0,.0,.0,.0);}fn rotationMTX(t:vec3)->mat4x4{var s:f32=sin(t.x);var c:f32=cos(t.x);var m1=mat4x4(1,0,0,0,0,c,-s,0,0,s,c,0,0,0,0,1);s=sin(t[1]);c=cos(t[1]);var m2=mat4x4(c,0,s,0,0,1,0,0,-s,0,c,0,0,0,0,1);s=sin(t[2]);c=cos(t[2]);var m3=mat4x4(c,-s,0,0,s,c,0,0,0,0,1,0,0,0,0,1);return m1*m2*m3;}@vertex fn main(inputData:InputData)->VertexOutput{var output:VertexOutput;let u_projectionMatrix=systemUniforms.projection.projectionMatrix;let u_projectionViewMatrix=systemUniforms.projection.projectionViewMatrix;let u_resolution=systemUniforms.resolution;let u_camera=systemUniforms.camera;let u_viewMatrix=u_camera.viewMatrix;let u_cameraPosition=u_camera.cameraPosition;let u_modelMatrix=vertexUniforms.matrixList.modelMatrix;let u_normalModelMatrix=vertexUniforms.matrixList.normalModelMatrix;let u_useBillboardPerspective=vertexUniforms.useBillboardPerspective==1u;let u_useBillboard=vertexUniforms.useBillboard==1u;let input_position=inputData.position;var position:vec4;var normalPosition:vec4;var scaleMTX=mat4x4(inputData.scale,0,0,0,0,inputData.scale,0,0,0,0,inputData.scale,0,0,0,0,1);var translateTX=mat4x4(1,0,0,0,0,1,0,0,0,0,1,0,inputData.position.x,inputData.position.y,inputData.position.z,1);var temp:mat4x4;if(u_useBillboard){var rotateMTX2=rotationMTX(vec3(0,0,inputData.rotation.z));temp=translateTX*rotateMTX2;position=rotateMTX2*vec4(inputData.a_position,1);output.position=u_projectionMatrix*getBillboardMatrix(u_viewMatrix,temp,0u)*scaleMTX*position;}else{var rotateMTX=rotationMTX(inputData.rotation);temp=translateTX*rotateMTX*scaleMTX;position=temp*vec4(inputData.a_position,1);output.position=u_projectionViewMatrix*position;}output.vertexPosition=position.xyz;output.vertexNormal=(transpose(mat4_inverse(temp))*vec4(inputData.a_normal,1.0)).xyz;output.uv=inputData.a_uv;output.combinedOpacity=inputData.alpha;return output;}";const Qa=parseWGSL("PARTICLE_EMITTER_VERTEX",Ja),es=Qa.uniforms.vertexUniforms;class ParticleEmitter extends Mesh{#Gm=1e3;#Om=5e3;#Vm=0;#Nm=0;#Fm=0;#Hm=0;#zm=0;#$m=0;#jm=-5;#Km=-5;#Xm=-5;#qm=5;#Ym=5;#Wm=5;#Zm=1;#Jm=1;#Qm=1;#ep=1;#tp=0;#rp=1;#ip=0;#np=0;#ap=-360;#sp=-360;#op=-360;#up=360;#lp=360;#cp=360;#hp=-360;#fp=-360;#dp=-360;#mp=360;#pp=360;#gp=360;#xp=Wa.CubicOut;#vp=Wa.CubicOut;#_p=Wa.CubicOut;#yp=Wa.Linear;#bp=Wa.Linear;#Sp=Wa.CubicOut;#Tp=Wa.CubicOut;#wp=Wa.CubicOut;#Mp;#Pp;#Rp;#Hr;#Cp;#Bp=2e3;constructor(i){super(i),this.geometry=new Plane(i),this.material=new BitmapMaterial(i),this.ignoreFrustumCulling=!0}get vertexStateBuffers(){const i=this.geometry.gpuRenderInfo.buffers[0],g=Array.from(i.attributes).length;return[i,{arrayStride:48,stepMode:"instance",attributes:[{shaderLocation:g,offset:16,format:"float32x3"},{shaderLocation:g+1,offset:28,format:"float32"},{shaderLocation:g+2,offset:32,format:"float32x3"},{shaderLocation:g+3,offset:44,format:"float32"}]}]}get particleNum(){return this.#Bp}set particleNum(i){this.#Bp=Math.max(Math.min(i,5e5),1),this.#Mp||this.#N(),this.#Dp()}get minLife(){return this.#Gm}set minLife(i){this.#Gm=i}get maxLife(){return this.#Om}set maxLife(i){this.#Om=i}get minStartX(){return this.#Vm}set minStartX(i){this.#Vm=i}get minStartY(){return this.#Nm}set minStartY(i){this.#Nm=i}get minStartZ(){return this.#Fm}set minStartZ(i){this.#Fm=i}get maxStartX(){return this.#Hm}set maxStartX(i){this.#Hm=i}get maxStartY(){return this.#zm}set maxStartY(i){this.#zm=i}get maxStartZ(){return this.#$m}set maxStartZ(i){this.#$m=i}get minEndX(){return this.#jm}set minEndX(i){this.#jm=i}get minEndY(){return this.#Km}set minEndY(i){this.#Km=i}get minEndZ(){return this.#Xm}set minEndZ(i){this.#Xm=i}get maxEndX(){return this.#qm}set maxEndX(i){this.#qm=i}get maxEndY(){return this.#Ym}set maxEndY(i){this.#Ym=i}get maxEndZ(){return this.#Wm}set maxEndZ(i){this.#Wm=i}get minStartAlpha(){return this.#Zm}set minStartAlpha(i){this.#Zm=i}get maxStartAlpha(){return this.#Jm}set maxStartAlpha(i){this.#Jm=i}get minEndAlpha(){return this.#Qm}set minEndAlpha(i){this.#Qm=i}get maxEndAlpha(){return this.#ep}set maxEndAlpha(i){this.#ep=i}get minStartScale(){return this.#tp}set minStartScale(i){this.#tp=i}get maxStartScale(){return this.#rp}set maxStartScale(i){this.#rp=i}get minEndScale(){return this.#ip}set minEndScale(i){this.#ip=i}get maxEndScale(){return this.#np}set maxEndScale(i){this.#np=i}get minStartRotationX(){return this.#ap}set minStartRotationX(i){this.#ap=i}get minStartRotationY(){return this.#sp}set minStartRotationY(i){this.#sp=i}get minStartRotationZ(){return this.#op}set minStartRotationZ(i){this.#op=i}get maxStartRotationX(){return this.#up}set maxStartRotationX(i){this.#up=i}get maxStartRotationY(){return this.#lp}set maxStartRotationY(i){this.#lp=i}get maxStartRotationZ(){return this.#cp}set maxStartRotationZ(i){this.#cp=i}get minEndRotationX(){return this.#hp}set minEndRotationX(i){this.#hp=i}get minEndRotationY(){return this.#fp}set minEndRotationY(i){this.#fp=i}get minEndRotationZ(){return this.#dp}set minEndRotationZ(i){this.#dp=i}get maxEndRotationX(){return this.#mp}set maxEndRotationX(i){this.#mp=i}get maxEndRotationY(){return this.#pp}set maxEndRotationY(i){this.#pp=i}get maxEndRotationZ(){return this.#gp}set maxEndRotationZ(i){this.#gp=i}get easeX(){return this.#xp}set easeX(i){this.#xp=i}get easeY(){return this.#vp}set easeY(i){this.#vp=i}get easeZ(){return this.#_p}set easeZ(i){this.#_p=i}get easeAlpha(){return this.#yp}set easeAlpha(i){this.#yp=i}get easeScale(){return this.#bp}set easeScale(i){this.#bp=i}get easeRotationX(){return this.#Sp}set easeRotationX(i){this.#Sp=i}get easeRotationY(){return this.#Tp}set easeRotationY(i){this.#Tp=i}get easeRotationZ(){return this.#wp}set easeRotationZ(i){this.#wp=i}get particleBuffers(){return this.#Pp}render(i){this.#Mp||this.#N(),this.#Ep(i.timestamp),super.render(i)}createCustomMeshVertexShaderModule=()=>this.createMeshVertexShaderModuleBASIC("VERTEX_MODULE_PARTICLE_EMITTER",Qa,es,Ja);#N(){this.#Rp=new Float32Array(46);let i={size:this.#Rp.byteLength,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST};const{gpuDevice:g}=this.redGPUContext;this.#Mp=g.createBuffer(i),g.queue.writeBuffer(this.#Mp,0,this.#Rp),this.#Dp(),this.depthStencilState.depthWriteEnabled=!1}#Dp(){this.dirtyPipeline=!0;let i=this.redGPUContext;const g=new Float32Array(12*this.#Bp),x=new Float32Array(12*this.#Bp),v=new Float32Array(12*this.#Bp),_=new Float32Array(4*this.#Bp),y=new Float32Array(4*this.#Bp),b=performance.now(),S=this.localToWorld(this.x,this.y,this.z);for(let i=0;i{L.forEach((g,x)=>{const v=z.createBuffer({size:g.byteLength,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC|GPUBufferUsage.VERTEX|GPUBufferUsage.STORAGE});z.queue.writeBuffer(v,0,g),this.#Pp.push(v),w?.length&©GPUBuffer(i,w[x],v)})}),w&&w.forEach(i=>H.addDeferredDestroy(i));let q={code:"#redgpu_include math.hash.getHash1D struct Info{startValue:f32,endValue:f32,easeType:f32,birthCenterValue:f32};struct InfoGroup{infoX:Info,infoY:Info,infoZ:Info,};struct Particle{startTime:f32,life:f32,valuePosition:vec3,valueAlpha:f32,valueRotation:vec3,valueScale:f32,};struct SimParams{time:f32,currentPositionX:f32,currentPositionY:f32,currentPositionZ:f32,minLife:f32,maxLife:f32,minStartX:f32,maxStartX:f32,minEndX:f32,maxEndX:f32,easeX:f32,minStartY:f32,maxStartY:f32,minEndY:f32,maxEndY:f32,easeY:f32,minStartZ:f32,maxStartZ:f32,minEndZ:f32,maxEndZ:f32,easeZ:f32,minStartAlpha:f32,maxStartAlpha:f32,minEndAlpha:f32,maxEndAlpha:f32,easeAlpha:f32,minStartScale:f32,maxStartScale:f32,minEndScale:f32,maxEndScale:f32,easeScale:f32,minStartRotationX:f32,maxStartRotationX:f32,minEndRotationX:f32,maxEndRotationX:f32,easeRotationX:f32,minStartRotationY:f32,maxStartRotationY:f32,minEndRotationY:f32,maxEndRotationY:f32,easeRotationY:f32,minStartRotationZ:f32,maxStartRotationZ:f32,minEndRotationZ:f32,maxEndRotationZ:f32,easeRotationZ:f32,};@group(0)@binding(0)varparams:SimParams;@group(0)@binding(1)varparticles:array;@group(0)@binding(2)varinfoPosition:array;@group(0)@binding(3)varinfoRotation:array;@group(0)@binding(4)varinfoScale:array;@group(0)@binding(5)varinfoAlpha:array;#redgpu_include math.PI #redgpu_include math.HPI #redgpu_include math.PI2 #redgpu_include math.DEG_TO_RAD fn calEasing(n:f32,easingType:f32)->f32{var m:f32=n;let easingInt:i32=i32(easingType);switch(easingInt){case 0:{m=m;}case 1:{m=m*m*m*m*m;}case 2:{m-=1.0;m=(m*m*m*m*m)+1.0;}case 3:{if(m*2.0<1.0){m*=2.0;m=m*m*m*m*m*0.5;}else{m=m*2.0-2.0;m=0.5*(m*m*m*m*m+2.0);}}case 4:{m=m*m*(m*1.70158+m-1.70158);}case 5:{m-=1.0;m=m*m*(m*1.70158+m+1.70158)+1.0;}case 6:{if(m*2.0<1.0){m*=2.0;m=0.5*m*m*(m*1.70158+m-1.70158);}else{m=m*2.0-2.0;m=0.5*m*m*(m*1.70158+m+1.70158)+1.0;}}case 7:{m=-1.0*(sqrt(1.0-m*m)-1.0);}case 8:{m-=1.0;m=sqrt(1.0-m*m);}case 9:{if(m*2.0<1.0){m*=2.0;m=-0.5*(sqrt(1.0-m*m)-1.0);}else{m=m*2.0-2.0;m=0.5*sqrt(1.0-m*m)+0.5;}}case 10:{m=m*m*m;}case 11:{m-=1.0;m=m*m*m+1.0;}case 12:{if(m*2.0<1.0){m*=2.0;m=m*m*m*0.5;}else{m=m*2.0-2.0;m=0.5*(m*m*m+2.0);}}case 13:{if(m==.0){m=.0;}else{m=pow(2.0,10.0*(m-1.0));}}case 14:{if(m==1.0){m=1.0;}else{m=-pow(2.0,-10.0*m)+1.0;}}case 15:{if(m*2.0<1.0){if(m==.0){m=.0;}else{m*=2.0;m=0.5*pow(2.0,10.0*(m-1.0));}}else{if(m==2.0){m=1.0;}else{m=m*2.0-1.0;m=-0.5*pow(2.0,-10.0*m)+1.0;}}}case 16:{m=m*m;}case 17:{m=(2.0-m)*m;}case 18:{if(m*2.0<1.0){m*=2.0;m=m*m*0.5;}else{m=2.0-m;m=0.5*(m*m+1.0);}}case 19:{m=m*m*m*m;}case 20:{m-=1.0;m=1.0-(m*m*m*m);}case 21:{if(m*2.0<1.0){m*=2.0;m=m*m*m*m*0.5;}else{m=m*2.0-2.0;m=1.0-(m*m*m*m*0.5);}}case 22:{m=-cos(m*HPI)+1.0;}case 23:{m=sin(m*HPI);}case 24:{m=(-cos(m*PI)+1.0)*0.5;}case 25:{if(m==.0){m=.0;}else if(m==1.0){m=1.0;}else{m-=1.0;m=-1.0*pow(2.0,10.0*m)*sin((m-.075)*PI2/0.3);}}case 26:{if(m==.0){m=.0;}else if(m==1.0){m=1.0;}else{m-=1.0;m=-pow(2.0,10.0*m)*sin((m-.075)*PI2/0.3);}}case 27:{if(m==.0){m=.0;}else if(m==1.0){m=1.0;}else{m=pow(2.0,-10.0*m)*sin((m-.075)*PI2/0.3)+1.0;}}default:{m=m;}}return m;}fn randomRange(min:f32,max:f32,v:f32)->f32{var newValue:f32=getHash1D(v);return(newValue*(max-min))+min;}fn compute_value(tInfo:Info,lifeRatio:f32)->f32{return tInfo.startValue+((tInfo.endValue-tInfo.startValue)*calEasing(lifeRatio,tInfo.easeType));}@compute @workgroup_size(256,1,1)fn main(@builtin(global_invocation_id)global_id:vec3){let index:u32=(global_id.x);let age:f32=(params.time-particles[index].startTime);var lifeRatio:f32=(age/particles[index].life);if(lifeRatio>=1.0){let uuid:f32=(params.time+f32(index));particles[index].startTime=params.time;particles[index].life=randomRange(params.minLife,params.maxLife,uuid);infoPosition[index].infoX.startValue=randomRange(params.minStartX+params.currentPositionX,params.maxStartX+params.currentPositionX,(uuid+1.0));infoPosition[index].infoX.endValue=randomRange(params.minEndX+params.currentPositionX,params.maxEndX+params.currentPositionX,(uuid+2.0));infoPosition[index].infoX.easeType=params.easeX;infoPosition[index].infoX.birthCenterValue=params.currentPositionX;infoPosition[index].infoY.startValue=randomRange(params.minStartY+params.currentPositionY,params.maxStartY+params.currentPositionY,(uuid+3.0));infoPosition[index].infoY.endValue=randomRange(params.minEndY+params.currentPositionY,params.maxEndY+params.currentPositionY,(uuid+4.0));infoPosition[index].infoY.easeType=params.easeY;infoPosition[index].infoY.birthCenterValue=params.currentPositionY;infoPosition[index].infoZ.startValue=randomRange(params.minStartZ+params.currentPositionZ,params.maxStartZ+params.currentPositionZ,(uuid+5.0));infoPosition[index].infoZ.endValue=randomRange(params.minEndZ+params.currentPositionZ,params.maxEndZ+params.currentPositionZ,(uuid+6.0));infoPosition[index].infoZ.easeType=params.easeZ;infoPosition[index].infoZ.birthCenterValue=params.currentPositionZ;infoAlpha[index].startValue=randomRange(params.minStartAlpha,params.maxStartAlpha,(uuid+7.0));infoAlpha[index].endValue=randomRange(params.minEndAlpha,params.maxEndAlpha,(uuid+8.0));infoAlpha[index].easeType=params.easeAlpha;infoScale[index].startValue=randomRange(params.minStartScale,params.maxStartScale,(uuid+9.0));infoScale[index].endValue=randomRange(params.minEndScale,params.maxEndScale,(uuid+10.0));infoScale[index].easeType=params.easeScale;infoRotation[index].infoX.startValue=randomRange(params.minStartRotationX,params.maxStartRotationX,(uuid+11.0));infoRotation[index].infoX.endValue=randomRange(params.minEndRotationX,params.maxEndRotationX,(uuid+12.0));infoRotation[index].infoX.easeType=params.easeRotationX;infoRotation[index].infoY.startValue=randomRange(params.minStartRotationY,params.maxStartRotationY,(uuid+13.0));infoRotation[index].infoY.endValue=randomRange(params.minEndRotationY,params.maxEndRotationY,(uuid+14.0));infoRotation[index].infoY.easeType=params.easeRotationY;infoRotation[index].infoZ.startValue=randomRange(params.minStartRotationZ,params.maxStartRotationZ,(uuid+15.0));infoRotation[index].infoZ.endValue=randomRange(params.minEndRotationZ,params.maxEndRotationZ,(uuid+16.0));infoRotation[index].infoZ.easeType=params.easeRotationZ;lifeRatio=.0;}var targetInfo:Info;let targetParticle=particles[index];targetInfo=infoPosition[index].infoX;particles[index].valuePosition.x=compute_value(targetInfo,lifeRatio);targetInfo=infoPosition[index].infoY;particles[index].valuePosition.y=compute_value(targetInfo,lifeRatio);targetInfo=infoPosition[index].infoZ;particles[index].valuePosition.z=compute_value(targetInfo,lifeRatio);targetInfo=infoAlpha[index];particles[index].valueAlpha=compute_value(targetInfo,lifeRatio);targetInfo=infoScale[index];particles[index].valueScale=compute_value(targetInfo,lifeRatio);targetInfo=infoRotation[index].infoX;particles[index].valueRotation.x=compute_value(targetInfo,lifeRatio)*DEG_TO_RAD;targetInfo=infoRotation[index].infoY;particles[index].valueRotation.y=compute_value(targetInfo,lifeRatio)*DEG_TO_RAD;targetInfo=infoRotation[index].infoZ;particles[index].valueRotation.z=compute_value(targetInfo,lifeRatio)*DEG_TO_RAD;}"},W=i.resourceManager.createGPUShaderModule("PARTICLE_EMITTER_MODULE",q);const be=[{binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}}],je=[{binding:0,resource:{buffer:this.#Mp,offset:0,size:this.#Rp.byteLength}}];L.forEach((i,g)=>{be.push({binding:g+1,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}}),je.push({binding:g+1,resource:{buffer:this.#Pp[g],offset:0,size:i.byteLength}})});const Ke=i.gpuDevice.createBindGroupLayout({entries:be}),Xe=i.gpuDevice.createPipelineLayout({bindGroupLayouts:[Ke]});this.#Cp=i.gpuDevice.createBindGroup({label:"PARTICLE_EMITTER_BIND_GROUP",layout:Ke,entries:je}),this.#Hr=i.gpuDevice.createComputePipeline({label:"PARTICLE_EMITTER_PIPELINE",layout:Xe,compute:{module:W,entryPoint:"main"}})}#Ep(i){const g=this.localToWorld(this.x,this.y,this.z);this.#Rp.set([i,...g,this.#Gm,this.#Om,this.#Vm,this.#Hm,this.#jm,this.#qm,this.#xp,this.#Nm,this.#zm,this.#Km,this.#Ym,this.#vp,this.#Fm,this.#$m,this.#Xm,this.#Wm,this.#_p,this.#Zm,this.#Jm,this.#Qm,this.#ep,this.#yp,this.#tp,this.#rp,this.#ip,this.#np,this.#bp,this.#ap,this.#up,this.#hp,this.#mp,this.#Sp,this.#sp,this.#lp,this.#fp,this.#pp,this.#Tp,this.#op,this.#cp,this.#dp,this.#gp,this.#wp],0);const{commandEncoderManager:x}=this.redGPUContext;this.redGPUContext.gpuDevice.queue.writeBuffer(this.#Mp,0,this.#Rp),x.addPreProcessComputePass("PARTICLE_EMITTER_COMPUTE_PASS",i=>{i.setPipeline(this.#Hr),i.setBindGroup(0,this.#Cp),i.dispatchWorkgroups(Math.ceil(this.#Bp/256))})}}Object.defineProperty(ParticleEmitter.prototype,"isInstanceofParticle",{value:!0,writable:!1}),defineBoolean(ParticleEmitter,[{key:"useBillboard",value:!0}]),Object.freeze(ParticleEmitter);const ts=mixInMesh2D(Mesh);class Sprite2D extends ts{#Gt=1;#Ot=1;constructor(i,g){super(i,new Plane(i,1,1,1,1,!0),g),this.primitiveState.cullMode=Ji.FRONT}get width(){return this.#Gt}set width(i){validatePositiveNumberRange(i),this.#Gt=i,this.dirtyTransform=!0}get height(){return this.#Ot}set height(i){validatePositiveNumberRange(i),this.#Ot=i,this.dirtyTransform=!0}setSize(i,g){this.width=i,this.height=void 0!==g?g:i}}Object.freeze(Sprite2D);var rs="#redgpu_include SYSTEM_UNIFORM;#redgpu_include math.billboard.getBillboardMatrix;#redgpu_include math.billboard.getBillboardResult;#redgpu_include entryPoint.billboard.entryPointPickingVertex;#redgpu_include entryPoint.empty.entryPointShadowVertex;struct MatrixList{modelMatrix:mat4x4,normalModelMatrix:mat4x4,}struct VertexUniforms{matrixList:MatrixList,pickingId:u32,useBillboard:u32,usePixelSize:u32,pixelSize:f32,_renderRatioX:f32,_renderRatioY:f32,combinedOpacity:f32,};@group(1)@binding(0)varvertexUniforms:VertexUniforms;struct InputData{@location(0)position:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,};struct VertexOutput{@builtin(position)position:vec4,@location(0)vertexPosition:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,@location(7)currentClipPos:vec4,@location(8)prevClipPos:vec4,@location(11)combinedOpacity:f32,@location(12)motionVector:vec3,@location(13)shadowCoord:vec3,@location(15)@interpolate(flat)pickingId:vec4,};@vertex fn main(inputData:InputData)->VertexOutput{var output:VertexOutput;let billboardResult=getBillboardResult(inputData.position,inputData.vertexNormal,vertexUniforms.matrixList.modelMatrix,systemUniforms.camera.viewMatrix,systemUniforms.projection.projectionMatrix,systemUniforms.resolution,vertexUniforms.useBillboard,vertexUniforms.usePixelSize,vertexUniforms.pixelSize,vertexUniforms._renderRatioX,vertexUniforms._renderRatioY);output.position=billboardResult.position;output.vertexPosition=billboardResult.vertexPosition;output.vertexNormal=billboardResult.vertexNormal;output.uv=inputData.uv;output.combinedOpacity=vertexUniforms.combinedOpacity;return output;}";const is=parseWGSL("SPRITE3D_VERTEX",rs),ns=is.uniforms.vertexUniforms;class Sprite3D extends Mesh{#Wo=1;#Zo=1;#Jo=1;#Ip=0;#Qo=!1;constructor(i,g,x){super(i),this._geometry=x||new Plane(i),this._material=g,this._material&&(this._material.transparent=!0),this.dirtyPipeline=!0,this.dirtyTransform=!0,this.primitiveState.cullMode=Ji.NONE}get worldSize(){return this.#Jo}set worldSize(i){this.#Jo!==i&&(this.#Jo=i,this.#eu())}get usePixelSize(){return this.#Qo}set usePixelSize(i){if(this.gpuRenderInfo){const{vertexUniformBuffer:g,vertexUniformInfo:x}=this.gpuRenderInfo;this.redGPUContext.gpuDevice.queue.writeBuffer(g.gpuBuffer,x.members.usePixelSize.uniformOffset,new Uint32Array([i?1:0]))}this.#Qo!==i&&(this.#Qo=i,this.#eu())}get pixelSize(){return this.#Ip}set pixelSize(i){if(this.gpuRenderInfo){const{vertexUniformBuffer:g,vertexUniformInfo:x}=this.gpuRenderInfo;this.redGPUContext.gpuDevice.queue.writeBuffer(g.gpuBuffer,x.members.pixelSize.uniformOffset,new Float32Array([i*window.devicePixelRatio]))}this.#Ip=i}render(i){if(this._material instanceof BitmapMaterial&&this._material.diffuseTexture){const{gpuTexture:i}=this._material.diffuseTexture;if(i){const g=i.width,x=i.height;if(g!==this.#Wo||x!==this.#Zo){this.#Wo=g,this.#Zo=x;const i=this.pixelSize;this.pixelSize=this.pixelSize||x,this.#eu(),i!==this.pixelSize&&(this.dirtyTransform=!0)}}}super.render(i)}createCustomMeshVertexShaderModule=()=>this.createMeshVertexShaderModuleBASIC("VERTEX_MODULE_SPRITE_3D",is,ns,rs);#eu(){if(this.#Zo){const i=this._renderRatioX,g=this._renderRatioY;this.usePixelSize?(this._renderRatioY=1,this._renderRatioX=this.#Wo/this.#Zo):(this._renderRatioY=this.#Jo,this._renderRatioX=this.#Wo/this.#Zo*this.#Jo),i===this._renderRatioX&&g===this._renderRatioY||(this.dirtyTransform=!0)}}}definePositiveNumber(Sprite3D,[{key:"_renderRatioX",value:1},{key:"_renderRatioY",value:1}]),defineBoolean(Sprite3D,[{key:"useBillboard",value:!0}]),Object.freeze(Sprite3D);class ASpriteSheet extends Mesh{#Ap=0;#Lp=0;#Up=0;#kp=!0;#Gp=!0;#Op;#Vp;#Np="play";constructor(i,g,x){super(i),this.#Vp=x,this._material=new BitmapMaterial(i),this._material.transparent=!0,this.dirtyPipeline=!0,this.dirtyTransform=!0,this.spriteSheetInfo=g,this._material.diffuseTextureSampler=new Sampler(i),this._material.diffuseTextureSampler.addressModeU=v.REPEAT,this._material.diffuseTextureSampler.addressModeV=v.REPEAT}get state(){return this.#Np}get loop(){return this.#Gp}set loop(i){this.#Gp=i}get frameRate(){return this.#Ap}set frameRate(i){i<0&&(i=0),0===this.#Ap&&i&&(this.#Lp=0),this.#Ap=i,this.#Up=1e3/this.#Ap}get geometry(){return this._geometry}set geometry(i){consoleAndThrowError("ASpriteSheet can not change geometry")}get material(){return this._material}set material(i){consoleAndThrowError("ASpriteSheet can not change material")}get spriteSheetInfo(){return this.#Op}set spriteSheetInfo(i){this.#Op=i,this.frameRate=i.frameRate,this.segmentW=i.segmentW,this.segmentH=i.segmentH,this.totalFrame=i.totalFrame,this.currentIndex=i.startIndex,this.#Gp=!0,this.#Lp=0,this._material.diffuseTexture=i.texture}play(){this.#kp=!0,this.#Np="play",this.#Lp=0}pause(){this.#kp=!1,this.#Np="pause"}stop(){this.#kp=!1,this.currentIndex=0,this.#Np="stop"}render(i){const{diffuseTexture:g}=this._material;this.#Vp(g,this.segmentW,this.segmentH);const{timestamp:x}=i;if(this.#Lp||(this.#Lp=this.#Up+x),this.#kp&&this.#Lp=this.totalFrame&&(this.loop?(this.#kp=!0,this.currentIndex=0):(this.#kp=!1,this.currentIndex=this.totalFrame-1))}super.render(i)}}definePositiveNumber(ASpriteSheet,[{key:"segmentW",value:5},{key:"segmentH",value:3},{key:"totalFrame",value:15},{key:"currentIndex",value:0}]),Object.freeze(ASpriteSheet);var as=Object.freeze({__proto__:null,ASpriteSheet:ASpriteSheet}),ss="#redgpu_include SYSTEM_UNIFORM;struct MatrixList{modelMatrix:mat4x4,normalModelMatrix:mat4x4,}struct VertexUniforms{matrixList:MatrixList,pickingId:u32,segmentW:f32,segmentH:f32,totalFrame:f32,currentIndex:f32,combinedOpacity:f32,};@group(1)@binding(0)varvertexUniforms:VertexUniforms;struct InputData{@location(0)position:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,};struct VertexOutput{@builtin(position)position:vec4,@location(0)vertexPosition:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,@location(7)currentClipPos:vec4,@location(8)prevClipPos:vec4,@location(11)combinedOpacity:f32,@location(12)motionVector:vec3,@location(13)shadowCoord:vec3,@location(15)@interpolate(flat)pickingId:vec4,};@vertex fn main(inputData:InputData)->VertexOutput{var output:VertexOutput;let u_projectionMatrix=systemUniforms.projection.projectionMatrix;let u_camera=systemUniforms.camera;let u_viewMatrix=u_camera.viewMatrix;let u_modelMatrix=vertexUniforms.matrixList.modelMatrix;let u_normalModelMatrix=vertexUniforms.matrixList.normalModelMatrix;let input_position=inputData.position;let input_vertexNormal=inputData.vertexNormal;let input_uv=inputData.uv;let viewPos=u_viewMatrix*u_modelMatrix*vec4(input_position,1.0);let viewNormal=u_viewMatrix*u_normalModelMatrix*vec4(input_vertexNormal,.0);output.position=u_projectionMatrix*viewPos;output.vertexPosition=viewPos.xyz;output.vertexNormal=viewNormal.xyz;output.combinedOpacity=vertexUniforms.combinedOpacity;let uv=vec2(input_uv.x*(1.0/vertexUniforms.segmentW)+((vertexUniforms.currentIndex % vertexUniforms.segmentW)/vertexUniforms.segmentW),input_uv.y*(1.0/vertexUniforms.segmentH)-(floor(vertexUniforms.currentIndex/vertexUniforms.segmentH)/vertexUniforms.segmentH));output.uv=uv;return output;}@vertex fn entryPointPickingVertex(inputData:InputData)->VertexOutput{var output:VertexOutput;let u_projectionMatrix=systemUniforms.projection.projectionMatrix;let u_viewMatrix=systemUniforms.camera.viewMatrix;let u_modelMatrix=vertexUniforms.matrixList.modelMatrix;let viewPos=u_viewMatrix*u_modelMatrix*vec4(inputData.position,1.0);output.position=u_projectionMatrix*viewPos;output.pickingId=unpack4x8unorm(vertexUniforms.pickingId);return output;}";const os=parseWGSL("SPRITE_SHEET_2D_VERTEX",ss),us=os.uniforms.vertexUniforms,ls=mixInMesh2D(ASpriteSheet);class SpriteSheet2D extends ls{#Gt=1;#Ot=1;constructor(i,g){super(i,g,(i,g,x)=>{if(i){const{gpuTexture:v}=i,_=v?.width/g,y=v?.height/x;_===this.#Gt&&y===this.#Ot||(this.#Gt=v?.width/g,this.#Ot=v?.height/x,this.dirtyTransform=!0)}else this.#Gt=1,this.#Ot=1}),this._geometry=new Plane(i,1,1,1,1,!0),this.primitiveState.cullMode=Ji.FRONT}get width(){return this.#Gt}get height(){return this.#Ot}get geometry(){return this._geometry}set geometry(i){consoleAndThrowError("SpriteSheet2D can not change geometry")}get material(){return this._material}set material(i){consoleAndThrowError("SpriteSheet2D can not change material")}createCustomMeshVertexShaderModule=()=>this.createMeshVertexShaderModuleBASIC("VERTEX_MODULE_SPRITE_SHEET_2D",os,us,ss)}Object.freeze(SpriteSheet2D);var cs="#redgpu_include SYSTEM_UNIFORM;#redgpu_include math.billboard.getBillboardMatrix;#redgpu_include math.billboard.getBillboardResult;#redgpu_include entryPoint.billboard.entryPointPickingVertex;#redgpu_include entryPoint.empty.entryPointShadowVertex;struct MatrixList{modelMatrix:mat4x4,normalModelMatrix:mat4x4,}struct VertexUniforms{matrixList:MatrixList,pickingId:u32,useSizeAttenuation:u32,useBillboard:u32,segmentW:f32,segmentH:f32,totalFrame:f32,currentIndex:f32,usePixelSize:u32,pixelSize:f32,_renderRatioX:f32,_renderRatioY:f32,combinedOpacity:f32,};@group(1)@binding(0)varvertexUniforms:VertexUniforms;struct InputData{@location(0)position:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,};struct VertexOutput{@builtin(position)position:vec4,@location(0)vertexPosition:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,@location(7)currentClipPos:vec4,@location(8)prevClipPos:vec4,@location(11)combinedOpacity:f32,@location(12)motionVector:vec3,@location(13)shadowCoord:vec3,@location(15)@interpolate(flat)pickingId:vec4,};@vertex fn main(inputData:InputData)->VertexOutput{var output:VertexOutput;let billboardResult=getBillboardResult(inputData.position,inputData.vertexNormal,vertexUniforms.matrixList.modelMatrix,systemUniforms.camera.viewMatrix,systemUniforms.projection.projectionMatrix,systemUniforms.resolution,vertexUniforms.useBillboard,vertexUniforms.usePixelSize,vertexUniforms.pixelSize,vertexUniforms._renderRatioX,vertexUniforms._renderRatioY);output.position=billboardResult.position;output.vertexPosition=billboardResult.vertexPosition;output.vertexNormal=billboardResult.vertexNormal;output.uv=vec2(inputData.uv.x/vertexUniforms.segmentW+((vertexUniforms.currentIndex % vertexUniforms.segmentW)/vertexUniforms.segmentW),inputData.uv.y/vertexUniforms.segmentH-(floor(vertexUniforms.currentIndex/vertexUniforms.segmentH)/vertexUniforms.segmentH));output.combinedOpacity=vertexUniforms.combinedOpacity;return output;}";const hs=parseWGSL("SPRITE_SHEET_3D_VERTEX",cs),fs=hs.uniforms.vertexUniforms;class SpriteSheet3D extends ASpriteSheet{#Wo=1;#Zo=1;#Jo=1;#Ip=0;#Qo=!1;constructor(i,g){super(i,g,(i,g,x)=>{if(i){const{gpuTexture:v}=i;if(v){const i=v.width/g,_=v.height/x;i===this.#Wo&&_===this.#Zo||(this.#Wo=i,this.#Zo=_,this.pixelSize=this.#Ip?this.#Ip:_,this.#eu(),this.dirtyTransform=!0)}}else this.#Wo=1,this.#Zo=1}),this._geometry=new Plane(i)}get worldSize(){return this.#Jo}set worldSize(i){this.#Jo!==i&&(this.#Jo=i,this.#eu())}get pixelSize(){return this.#Ip}set pixelSize(i){if(this.gpuRenderInfo){const{vertexUniformBuffer:g,vertexUniformInfo:x}=this.gpuRenderInfo;this.redGPUContext.gpuDevice.queue.writeBuffer(g.gpuBuffer,x.members.pixelSize.uniformOffset,new Float32Array([i*window.devicePixelRatio]))}this.#Ip=i}get usePixelSize(){return this.#Qo}set usePixelSize(i){if(this.gpuRenderInfo){const{vertexUniformBuffer:g,vertexUniformInfo:x}=this.gpuRenderInfo;this.redGPUContext.gpuDevice.queue.writeBuffer(g.gpuBuffer,x.members.usePixelSize.uniformOffset,new Uint32Array([i?1:0]))}this.#Qo!==i&&(this.#Qo=i,this.#eu())}get geometry(){return this._geometry}set geometry(i){consoleAndThrowError("SpriteSheet3D can not change geometry")}get material(){return this._material}set material(i){consoleAndThrowError("SpriteSheet3D can not change material")}render(i){super.render(i)}createCustomMeshVertexShaderModule=()=>this.createMeshVertexShaderModuleBASIC("VERTEX_MODULE_SPRITE_SHEET_3D",hs,fs,cs);#eu(){if(this.#Zo){const i=this._renderRatioX,g=this._renderRatioY;this.usePixelSize?(this._renderRatioY=1,this._renderRatioX=this.#Wo/this.#Zo):(this._renderRatioY=this.#Jo,this._renderRatioX=this.#Wo/this.#Zo*this.#Jo),i===this._renderRatioX&&g===this._renderRatioY||(this.dirtyTransform=!0)}}}definePositiveNumber(SpriteSheet3D,[{key:"_renderRatioX",value:1},{key:"_renderRatioY",value:1}]),defineBoolean(SpriteSheet3D,[{key:"useBillboard",value:!0}]),Object.freeze(SpriteSheet3D);class SpriteSheetInfo{#Fp=0;#Hp=0;#zp=0;#$p=0;#Ap=0;#Gp=!0;#Od;constructor(i,g,x,v,_,y,b=!0,S=60){validateRedGPUContext(i),validateUintRange(x),validateUintRange(v),validateUintRange(_),validateUintRange(y),validateUintRange(S),this.#Fp=x,this.#Hp=v,this.#zp=_,this.#$p=y,this.#Od=new BitmapTexture(i,g),this.#Gp=b,this.#Ap=S}get segmentW(){return this.#Fp}get segmentH(){return this.#Hp}get totalFrame(){return this.#zp}get startIndex(){return this.#$p}get texture(){return this.#Od}get frameRate(){return this.#Ap}get loop(){return this.#Gp}}Object.freeze(SpriteSheetInfo);const ds=parseWGSL("LINE_MATERIAL","#redgpu_include SYSTEM_UNIFORM;#redgpu_include entryPoint.mesh.entryPointPickingFragment;#redgpu_include systemStruct.OutputFragment;#redgpu_include math.getMotionVector;struct Uniforms{opacity:f32,};struct InputData{@builtin(position)position:vec4,@location(0)vertexPosition:vec3,@location(1)vertexColor:vec4,@location(7)currentClipPos:vec4,@location(8)prevClipPos:vec4,@location(15)@interpolate(flat)pickingId:vec4,}@group(2)@binding(0)varuniforms:Uniforms;@fragment fn main(inputData:InputData)->OutputFragment{var output:OutputFragment;var finalColor=inputData.vertexColor;finalColor.a=finalColor.a*uniforms.opacity;output.color=vec4(finalColor.rgb,finalColor.a);output.gBufferNormal=vec4(.0,.0,.0,.0);output.gBufferMotionVector=vec4(getMotionVector(inputData.currentClipPos,inputData.prevClipPos),.0,1.0);return output;}");class LineMaterial extends ABaseMaterial{constructor(i,g){super(i,"LINE_MATERIAL",ds,2),g&&(this.name=g),this.initGPURenderInfos()}}Object.freeze(LineMaterial);class LinePoint{position;colorRGBA;constructor(i=0,g=0,x=0,v){this.position=[i,g,x],this.colorRGBA=v}}const getPointsOnBezierCurveWithSplitting=(i,g,x,v)=>{let _=v||[];if(((i,g)=>{let x=i[g].position,v=i[g+1].position,_=i[g+2].position,y=i[g+3].position,b=3*v[0]-2*x[0]-y[0],S=3*v[1]-2*x[1]-y[1],w=3*_[0]-2*y[0]-x[0],L=3*_[1]-2*y[1]-x[1];return b*=b,S*=S,w*=w,L*=L,b{let y=_||[],b=i[g],S=i[x-1],w=0,L=1,k=g+1;for(;kw&&(w=g,L=k)}return Math.sqrt(w)>v?(lineSimplifyPoints(i,g,L+1,v,y),lineSimplifyPoints(i,L,x,v,y)):y.push(b,S),y},ms={LINEAR:"linear",CATMULL_ROM:"catmullRom",BEZIER:"bezier"};Object.freeze(ms);var ps="#redgpu_include SYSTEM_UNIFORM;struct MatrixList{modelMatrix:mat4x4,prevModelMatrix:mat4x4,normalModelMatrix:mat4x4,}struct VertexUniforms{matrixList:MatrixList,pickingId:u32,};@group(1)@binding(0)varvertexUniforms:VertexUniforms;struct InputData{@location(0)position:vec3,@location(1)vertexColor:vec4,};struct VertexOutput{@builtin(position)position:vec4,@location(0)vertexPosition:vec3,@location(1)vertexColor:vec4,@location(7)currentClipPos:vec4,@location(8)prevClipPos:vec4,@location(15)@interpolate(flat)pickingId:vec4,};@vertex fn main(inputData:InputData)->VertexOutput{var output:VertexOutput;let u_projectionViewMatrix=systemUniforms.projection.projectionViewMatrix;let u_noneJitterProjectionViewMatrix=systemUniforms.projection.noneJitterProjectionViewMatrix;let u_prevNoneJitterProjectionViewMatrix=systemUniforms.projection.prevNoneJitterProjectionViewMatrix;let u_matrixList=vertexUniforms.matrixList;let u_modelMatrix=u_matrixList.modelMatrix;let u_prevModelMatrix=u_matrixList.prevModelMatrix;let input_position=inputData.position;let input_vertexColor=inputData.vertexColor;let input_position_vec4=vec4(input_position,1.0);var position:vec4;position=u_modelMatrix*input_position_vec4;output.position=u_projectionViewMatrix*position;output.vertexPosition=position.xyz;output.vertexColor=input_vertexColor;{output.currentClipPos=u_noneJitterProjectionViewMatrix*position;output.prevClipPos=u_prevNoneJitterProjectionViewMatrix*u_prevModelMatrix*input_position_vec4;}return output;}#redgpu_include entryPoint.empty.entryPointPickingVertex;#redgpu_include entryPoint.empty.entryPointShadowVertex;";const gs=parseWGSL("LINE3D_VERTEX",ps),xs=gs.uniforms.vertexUniforms;class Line3D extends Mesh{baseColor;#jp;#Kp=1;#Xp=.01;#Qf=.01;#qp=[];#Yp=[];#Wp;constructor(i,g=ms.LINEAR,x="#fff"){super(i),this.primitiveState.topology=Ei.LINE_STRIP,this.baseColor=x,this.#jp=g,this._geometry=new Geometry(i,new VertexBuffer(i,this.#qp,new VertexInterleavedStruct({vertexPosition:VertexInterleaveType.float32x3,vertexColor:VertexInterleaveType.float32x4}))),this._material=new LineMaterial(i)}get originalPoints(){return this.#Yp}get type(){return this.#jp}set type(i){this.#jp=i,this.#Zp()}get interleaveData(){return this.#qp}get tension(){return this.#Kp}set tension(i){validatePositiveNumberRange(i),this.#Kp=i,this.#Zp()}get tolerance(){return this.#Xp}set tolerance(i){validatePositiveNumberRange(i),this.#Xp=i,this.#Zp()}get distance(){return this.#Qf}set distance(i){validatePositiveNumberRange(i),this.#Qf=i,this.#Zp()}get numPoints(){return this.#Yp.length}get geometry(){return this._geometry}set geometry(i){consoleAndThrowError("Line3D can not change geometry")}get material(){return this._material}set material(i){consoleAndThrowError("Line3D can not change material")}createCustomMeshVertexShaderModule=()=>this.createMeshVertexShaderModuleBASIC("VERTEX_MODULE_LINE_3D",gs,xs,ps);addPoint(i=0,g=0,x=0,v=this.baseColor,_=1,y=0,b=0,S=0,w=0,L=0,k=0){this.#Yp.push(new LinePointWithInOut(i,g,x,y,b,S,w,L,k,v,_)),this.#Zp()}addPointAt(i,g=0,x=0,v=0,_=this.baseColor,y=1,b=0,S=0,w=0,L=0,k=0,H=0){this.#Yp.length1)for(this.#Wp=(i=>{let g,x=[],v=0,_=0;const y=i.length;for(;v{const x=i.length,v=x-2;for(let _=0;_{let x=[],v=(i.length-1)/3;v=Math.floor(v);let _,y=0;for(;y,normalModelMatrix:mat4x4,}struct VertexUniforms{pickingId:u32,matrixList:MatrixList,combinedOpacity:f32,};@group(1)@binding(0)varvertexUniforms:VertexUniforms;struct InputData{@location(0)position:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,};struct VertexOutput{@builtin(position)position:vec4,@location(0)vertexPosition:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,@location(11)combinedOpacity:f32,@location(13)shadowCoord:vec3,@location(15)@interpolate(flat)pickingId:vec4,};#redgpu_include systemStruct.OutputShadowData;@vertex fn main(inputData:InputData)->VertexOutput{var output:VertexOutput;let u_projectionMatrix=systemUniforms.projection.projectionMatrix;let u_viewMatrix=systemUniforms.camera.viewMatrix;let u_modelMatrix=vertexUniforms.matrixList.modelMatrix;let u_normalModelMatrix=vertexUniforms.matrixList.normalModelMatrix;let input_position=inputData.position;let input_vertexNormal=inputData.vertexNormal;let input_uv=inputData.uv;let viewPos=u_viewMatrix*u_modelMatrix*vec4(input_position,1.0);let viewNormal=u_viewMatrix*u_normalModelMatrix*vec4(input_vertexNormal,.0);output.position=u_projectionMatrix*viewPos;output.vertexPosition=viewPos.xyz;output.vertexNormal=viewNormal.xyz;output.uv=input_uv;output.combinedOpacity=vertexUniforms.combinedOpacity;return output;}@vertex fn entryPointPickingVertex(inputData:InputData)->VertexOutput{var output:VertexOutput;let u_projectionMatrix=systemUniforms.projection.projectionMatrix;let u_viewMatrix=systemUniforms.camera.viewMatrix;let u_modelMatrix=vertexUniforms.matrixList.modelMatrix;let viewPos=u_viewMatrix*u_modelMatrix*vec4(inputData.position,1.0);output.position=u_projectionMatrix*viewPos;output.pickingId=unpack4x8unorm(vertexUniforms.pickingId);return output;}";const Ss=parseWGSL("TEXTFIELD2D_VERTEX",bs),Ts=Ss.uniforms.vertexUniforms,ws=mixInMesh2D(ATextField);class TextField2D extends ws{#Gt=1;#Ot=1;#Jp=!0;constructor(i,g=!0){super(i,(i,g)=>{this.#Gt===i&&this.#Ot===g||(this.dirtyTransform=!0),this.#Gt=i,this.#Ot=g},!1),this._geometry=new Plane(i,1,1,1,1,!0),this.useSmoothing=g,this.primitiveState.cullMode=Ji.FRONT}get useSmoothing(){return this.#Jp}set useSmoothing(i){this.#Jp=i;const{diffuseTextureSampler:g}=this._material;this.useSmoothing?(g.minFilter=_.LINEAR,g.magFilter=_.LINEAR,g.mipmapFilter=y.LINEAR):(g.minFilter=_.NEAREST,g.magFilter=_.NEAREST,g.mipmapFilter=null)}get width(){return this.#Gt}get height(){return this.#Ot}get geometry(){return this._geometry}set geometry(i){console.error("TextField2D can not change geometry")}get material(){return this._material}set material(i){console.error("TextField2D can not change material")}createCustomMeshVertexShaderModule=()=>this.createMeshVertexShaderModuleBASIC("VERTEX_MODULE_TEXT_FIELD_2D",Ss,Ts,bs)}Object.freeze(TextField2D);const Ms=3.141592653589793,Ps=6.283185307179586,Rs=.225,Cs=1.27323954,Bs=.405284735,Ds=1.5707963267948966,Es=Math.PI/180;class InstancingMeshObject3D{modelMatrix=create$4();localMatrix=create$4();normalModelMatrix=create$4();#wi=0;#Pi=0;#Mi=0;#hs=[0,0,0];#gs=1;#xs=1;#vs=1;#_s=[1,1,1];#ys=0;#bs=0;#Ss=0;#Ts=[0,0,0];#Qp=0;#eg;#h;#Rs=1;constructor(i,g,x){validateRedGPUContext(i),this.#h=i,this.#eg=x,this.#Qp=g,this.#tg()}get opacity(){return this.#Rs}set opacity(i){validatePositiveNumberRange(i,0,1),this.#Rs=i,this.#tg()}get x(){return this.#wi}set x(i){this.#wi=this.#hs[0]=i,this.#tg()}get y(){return this.#Mi}set y(i){this.#Mi=this.#hs[1]=i,this.#tg()}get z(){return this.#Pi}set z(i){this.#Pi=this.#hs[2]=i,this.#tg()}get position(){return this.#hs}set position(i){this.#wi=this.#hs[0]=i,this.#Mi=this.#hs[1]=i,this.#Pi=this.#hs[2]=i,this.#tg()}get scaleX(){return this.#gs}set scaleX(i){this.#gs=this.#_s[0]=i,this.#tg()}get scaleY(){return this.#xs}set scaleY(i){this.#xs=this.#_s[1]=i,this.#tg()}get scaleZ(){return this.#vs}set scaleZ(i){this.#vs=this.#_s[2]=i,this.#tg()}get scale(){return this.#_s}set scale(i){this.#gs=this.#_s[0]=i,this.#xs=this.#_s[1]=i,this.#vs=this.#_s[2]=i,this.#tg()}get rotationX(){return this.#ys}set rotationX(i){this.#ys=this.#Ts[0]=i,this.#tg()}get rotationY(){return this.#bs}set rotationY(i){this.#bs=this.#Ts[1]=i,this.#tg()}get rotationZ(){return this.#Ss}set rotationZ(i){this.#Ss=this.#Ts[2]=i,this.#tg()}get rotation(){return this.#Ts}set rotation(i){this.#ys=this.#Ts[0]=i,this.#bs=this.#Ts[1]=i,this.#Ss=this.#Ts[2]=i,this.#tg()}setScale(i,g,x){g=g??i,x=x??i;const v=this.#_s;this.#gs=v[0]=i,this.#xs=v[1]=g,this.#vs=v[2]=x,this.#tg()}setPosition(i,g,x){g=g??i,x=x??i;const v=this.#hs;this.#wi=v[0]=i,this.#Mi=v[1]=g,this.#Pi=v[2]=x,this.#tg()}setRotation(i,g,x){g=g??i,x=x??i;const v=this.#Ts;this.#ys=v[0]=i,this.#bs=v[1]=g,this.#Ss=v[2]=x,this.#tg()}#tg(){let i,g,x,v,_,y,b,S,w,L,k,H,z,q,W,be,je,Ke,Xe,Ye,Ze,Je,Qe,et,tt,it,ft,pt,xt,vt,yt,bt,St,Tt,wt,Mt,Pt,Rt;{const z=this.localMatrix;let je;L=1,k=0,H=0,q=0,W=1,be=0,Ke=0,Xe=0,Ye=1,z[12]=this.#wi,z[13]=this.#Mi,z[14]=this.#Pi,z[15]=1,b=this.#ys*Es,S=this.#bs*Es,w=this.#Ss*Es,je=b%Ps,je<-Ms?je+=Ps:je>Ms&&(je-=Ps),je=je<0?Cs*je+Bs*je*je:Cs*je-Bs*je*je,i=je<0?Rs*(je*-je-je)+je:Rs*(je*je-je)+je,je=(b+Ds)%Ps,je<-Ms?je+=Ps:je>Ms&&(je-=Ps),je=je<0?Cs*je+Bs*je*je:Cs*je-Bs*je*je,v=je<0?Rs*(je*-je-je)+je:Rs*(je*je-je)+je,je=S%Ps,je<-Ms?je+=Ps:je>Ms&&(je-=Ps),je=je<0?Cs*je+Bs*je*je:Cs*je-Bs*je*je,g=je<0?Rs*(je*-je-je)+je:Rs*(je*je-je)+je,je=(S+Ds)%Ps,je<-Ms?je+=Ps:je>Ms&&(je-=Ps),je=je<0?Cs*je+Bs*je*je:Cs*je-Bs*je*je,_=je<0?Rs*(je*-je-je)+je:Rs*(je*je-je)+je,je=w%Ps,je<-Ms?je+=Ps:je>Ms&&(je-=Ps),je=je<0?Cs*je+Bs*je*je:Cs*je-Bs*je*je,x=je<0?Rs*(je*-je-je)+je:Rs*(je*je-je)+je,je=(w+Ds)%Ps,je<-Ms?je+=Ps:je>Ms&&(je-=Ps),je=je<0?Cs*je+Bs*je*je:Cs*je-Bs*je*je,y=je<0?Rs*(je*-je-je)+je:Rs*(je*je-je)+je,vt=_*y,yt=v*x+i*g*y,bt=i*x-v*g*y,St=-_*x,Tt=v*y-i*g*x,wt=i*y+v*g*x,Mt=g,Pt=-i*_,Rt=v*_;let Ze=this.#gs,Je=this.#xs,Qe=this.#vs;z[0]=vt*Ze,z[1]=yt*Ze,z[2]=bt*Ze,z[3]=0,z[4]=St*Je,z[5]=Tt*Je,z[6]=wt*Je,z[7]=0,z[8]=Mt*Qe,z[9]=Pt*Qe,z[10]=Rt*Qe,z[11]=0}this.modelMatrix=this.localMatrix;{let i=this.normalModelMatrix,g=this.modelMatrix;L=g[0],k=g[1],H=g[2],z=g[3],q=g[4],W=g[5],be=g[6],je=g[7],Ke=g[8],Xe=g[9],Ye=g[10],Ze=g[11],Qe=g[12],et=g[13],tt=g[14],it=g[15],Je=L*W-k*q,ft=L*be-H*q,pt=L*je-z*q,xt=k*be-H*W,vt=k*je-z*W,yt=H*je-z*be,bt=Ke*et-Xe*Qe,St=Ke*tt-Ye*Qe,Tt=Ke*it-Ze*Qe,Mt=Xe*it-Ze*et,wt=Ye*it-Ze*tt,Rt=Je*wt-ft*Mt+pt*wt+xt*Tt-vt*St+yt*bt,Rt=1/Rt,i[0]=(W*wt-be*Mt+je*wt)*Rt,i[4]=(-k*wt+H*Mt-z*wt)*Rt,i[8]=(et*yt-tt*vt+it*xt)*Rt,i[12]=(-Xe*yt+Ye*vt-Ze*xt)*Rt,i[1]=(-q*wt+be*Tt-je*St)*Rt,i[5]=(L*wt-H*Tt+z*St)*Rt,i[9]=(-Qe*yt+tt*pt-it*ft)*Rt,i[13]=(Ke*yt-Ye*pt+Ze*ft)*Rt,i[2]=(q*Mt-W*Tt+je*bt)*Rt,i[6]=(-L*Mt+k*Tt-z*bt)*Rt,i[10]=(Qe*vt-et*pt+it*Je)*Rt,i[14]=(-Ke*vt+Xe*pt-Ze*Je)*Rt,i[3]=(-q*wt+W*St-be*bt)*Rt,i[7]=(L*wt-k*St+H*bt)*Rt,i[11]=(-Qe*xt+et*ft-tt*Je)*Rt,i[15]=(Ke*xt-Xe*ft+Ye*Je)*Rt}if(this.#eg.gpuRenderInfo){const{vertexUniformBuffer:i,vertexUniformInfo:g}=this.#eg.gpuRenderInfo,{dataViewF32:x}=i,{members:v}=g,_=v.instanceModelMatrixs,y=v.instanceNormalModelMatrix,b=v.instanceOpacity;x.set(this.modelMatrix,(_.uniformOffset+_.stride*this.#Qp)/4),x.set(this.normalModelMatrix,(y.uniformOffset+y.stride*this.#Qp)/4),x.set([this.opacity],(b.uniformOffset+b.stride*this.#Qp)/4),this.#eg.dirtyInstanceMeshObject3D=!0}}}Object.freeze(InstancingMeshObject3D);var Is=Object.freeze({__proto__:null,instancingMeshObject3D:InstancingMeshObject3D}),As="struct VertexOutput{@builtin(position)position:vec4,@location(0)vertexPosition:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,@location(3)uv1:vec2,@location(4)vertexColor_0:vec4,@location(5)vertexTangent:vec4,@location(7)currentClipPos:vec4,@location(8)prevClipPos:vec4,@location(10)localNodeScale_volumeScale:vec2,@location(11)instanceOpacity:f32,@location(12)motionVector:vec3,@location(13)shadowCoord:vec3,@location(14)@interpolate(flat)receiveShadow:f32,@location(15)@interpolate(flat)pickingId:vec4,};";const Ls="VERTEX_MODULE_INSTANCING";class InstancingMesh extends Mesh{dirtyInstanceMeshObject3D=!0;dirtyInstanceNum=!0;#ls;#h;#rg=1;#ig=1;#ng=[];#$s;#ag;#sg;#og;#ug;#lg;#cg=0;#hg=0;#fg;#Ks=[];constructor(i,g,x,v,_){super(i,v,_),this.#h=i;const y=InstancingMesh.getLimitSize(this.#h);this.#ig=Math.min(g,y),this.#rg=Math.min(x,this.#ig),this.#N(),this.gpuRenderInfo.vertexUniformInfo=parseWGSL(`INSTANCING_MESH_VERTEX_${this.#ig}`,this.#dg(this.geometry,this.material)).storage.instanceUniforms,this.#mg(),this.#pg(),this.#jd(this.#h),this.instanceCount=this.#rg}get instanceCount(){return this.#rg}set instanceCount(i){validateUintRange(i),this.#rg=Math.min(i,this.#ig),this.#ng.length>this.#rg&&(this.#ng.length=this.#rg);let g=this.#rg;for(;g--;)this.#ng[g]||(this.#ng[g]=new InstancingMeshObject3D(this.#h,g,this));this.dirtyInstanceNum=!0}get maxInstanceCount(){return this.#ig}get instanceChildren(){return this.#ng}static getLimitSize(i){const g=Math.min(i.detector.activeLimits.maxStorageBufferBindingSize,536870912);return Math.floor((g-144)/132)}render(i,g=!1){if(this.dirtyLOD)return this.#pg(),this.#jd(this.#h),this.dirtyInstanceNum=!0,void(this.dirtyLOD=!1);const{view:x,currentRenderPassEncoder:v,renderResults:_}=i,{scene:y}=x,{shadowManager:b}=y,{directionalShadowManager:S}=b,{castingList:w}=S;this.dirtyTransform&&this.#gg(),this.geometry?_.num3DObjects++:_.num3DGroups++;const L=this.#h;if(this.geometry){const{antialiasingManager:x}=L;this.#ls!==x.msaaID&&(this.dirtyPipeline=!0,this.#ls=x.msaaID),this.gpuRenderInfo||this.#jd(L);(this.dirtyPipeline||this.material.dirtyPipeline)&&this.#xg(i),g||this.#vg(i),this.#_g(i,g,v)}this.castShadow&&(w[w.length]=this);const{children:k}=this;let H=k.length;for(;H--;)k[H].dirtyTransform=this.dirtyTransform,k[H].render(i);this.dirtyTransform=!1}#gg(){identity$1(this.localMatrix),translate(this.localMatrix,this.localMatrix,[this.x,this.y,this.z]),rotateX$2(this.localMatrix,this.localMatrix,this.rotationX),rotateY$2(this.localMatrix,this.localMatrix,this.rotationY),rotateZ$2(this.localMatrix,this.localMatrix,this.rotationZ),scale$4(this.localMatrix,this.localMatrix,[this.scaleX,this.scaleY,this.scaleZ]);const i=this.parent;i?.modelMatrix?multiply$4(this.modelMatrix,i.modelMatrix,this.localMatrix):this.modelMatrix=clone$4(this.localMatrix)}#xg(i){this.dirtyTransform=!0,this.material.dirtyPipeline&&this.material._updateFragmentState(),this.#yg(),this.material.dirtyPipeline=!1,this.dirtyPipeline=!1,i.renderResults.numDirtyPipelines++}#_g(i,g,x){const{gpuRenderInfo:v}=this,{pipeline:_,shadowPipeline:y}=v,{view:b,renderResults:S}=i;this.#bg(),this.#Sg();const{fragmentUniformBindGroup:w}=this.material.gpuRenderInfo;x.setBindGroup(0,b.systemUniform_Vertex_UniformBindGroup),x.setBindGroup(2,w),x.setPipeline(g?y:_);this.#Tg(x,this.geometry,this.gpuRenderInfo.vertexUniformBindGroup,this.material.gpuRenderInfo.fragmentUniformBindGroup,0,20),this.LODManager.LODList.forEach((i,g)=>{const v=this.#Ks[g];x.setPipeline(v.pipeline),this.#Tg(x,i.geometry,v.vertexUniformBindGroup,i.material?i.material.gpuRenderInfo.fragmentUniformBindGroup:this.material.gpuRenderInfo.fragmentUniformBindGroup,g+1,20)}),S.numDrawCalls++,S.numInstances++}#Tg(i,g,x,v,_,y){const{vertexBuffer:b,indexBuffer:S}=g,w=y*_;if(i.setBindGroup(1,x),i.setBindGroup(2,v),i.setVertexBuffer(0,b.gpuBuffer),S){const{gpuBuffer:g,format:x}=S;i.setIndexBuffer(g,x),i.drawIndexedIndirect(this.#fg,w)}else i.drawIndirect(this.#fg,w)}#bg(){const{vertexUniformBuffer:i,vertexUniformInfo:g}=this.gpuRenderInfo,{displacementTexture:x,displacementScale:v}=this.material||{},{members:_}=g;void 0!==_.displacementScale&&this.#$s!==v&&(this.#$s=v,i.dataViewF32.set(new _.displacementScale.View([v]),_.displacementScale.uniformOffset/4)),void 0!==_.useDisplacementTexture&&this.#ag!==!!x&&(this.#ag=!!x,i.dataViewF32.set(new _.useDisplacementTexture.View([x?1:0]),_.useDisplacementTexture.uniformOffset/4))}#Sg(){const{vertexUniformBuffer:i,vertexUniformInfo:g}=this.gpuRenderInfo,{gpuDevice:x}=this.#h,{members:v}=g;if(this.dirtyTransform){i.dataViewF32.set(this.modelMatrix,v.instanceGroupModelMatrix.uniformOffset/4);const g=create$4();invert$1(g,this.modelMatrix),transpose(g,g),i.dataViewF32.set(g,v.instanceGroupNormalModelMatrix.uniformOffset/4),x.queue.writeBuffer(i.gpuBuffer,v.instanceGroupModelMatrix.uniformOffset,new v.instanceGroupModelMatrix.View(this.modelMatrix)),x.queue.writeBuffer(i.gpuBuffer,v.instanceGroupNormalModelMatrix.uniformOffset,new v.instanceGroupNormalModelMatrix.View(g))}(this.dirtyInstanceMeshObject3D||this.dirtyInstanceNum)&&(x.queue.writeBuffer(i.gpuBuffer,0,i.data),this.dirtyInstanceMeshObject3D=!1,this.dirtyInstanceNum=!1)}#N(){const{gpuDevice:i}=this.#h;this.gpuRenderInfo=new VertexGPURenderInfo(null,null,null,null,null,null,null,null);this.#fg=i.createBuffer({size:160,usage:GPUBufferUsage.INDIRECT|GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST,label:`IndirectDrawBuffer_${this.uuid}`});const g=new Float32Array(40);this.#ug=new StorageBuffer(this.#h,g.buffer,`CullingUniformBuffer_${this.uuid}`)}#jd(i){this.dirtyPipeline=!0;const g=new ArrayBuffer(this.#cg*(this.LODManager.LODList.length+1));this.#lg?.destroy(),this.#lg=new StorageBuffer(i,g,`VisibilityBuffer_${this.uuid}`),this.#yg(),this.#wg(this.#h)}#wg(i){const{gpuDevice:g,resourceManager:x}=i,v={code:this.#Mg()},_=x.createGPUShaderModule(`CULLING_COMPUTE_MODULE_INSTANCING_${this.#ig}_${this.uuid}`,v),y=g.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"read-only-storage"}},{binding:1,visibility:GPUShaderStage.COMPUTE,buffer:{type:"read-only-storage"}},{binding:2,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}},{binding:3,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}}]});this.#sg=g.createComputePipeline({layout:g.createPipelineLayout({bindGroupLayouts:[y]}),compute:{module:_,entryPoint:"main"}}),this.#og=g.createBindGroup({layout:y,entries:[{binding:0,resource:{buffer:this.gpuRenderInfo.vertexUniformBuffer.gpuBuffer}},{binding:1,resource:{buffer:this.#ug.gpuBuffer}},{binding:2,resource:{buffer:this.#lg.gpuBuffer}},{binding:3,resource:{buffer:this.#fg}}]})}#Pg(i){const{view:g}=i,{gpuDevice:x}=this.#h,{data:v,dataViewU32:_,dataViewF32:y}=this.#ug;_.set([this.#rg],0),_.set([this.#hg],1),_.set([this.LODManager.LODList.length],2),y.set(g.rawCamera.position,4),y.set(g.frustumPlanes.flat(),8),y.set([...this.LODManager.LODList.map(i=>i.distance)],32),x.queue.writeBuffer(this.#ug.gpuBuffer,0,v)}#vg(i){const{gpuDevice:g,commandEncoderManager:x}=this.#h,{indexBuffer:v,vertexBuffer:_}=this.geometry;this.#Pg(i);const y=v?v.indexCount:_.vertexCount,b=new Uint32Array([y,0,0,0,0]);g.queue.writeBuffer(this.#fg,0,b),this.LODManager.LODList.forEach((i,x)=>{const v=i.geometry.indexBuffer.indexCount,_=new Uint32Array([v,0,0,0,0]),y=20*(x+1);g.queue.writeBuffer(this.#fg,y,_)}),x.addPreProcessComputePass("InstancingMesh_GPUCulling_ComputePass",i=>{i.setPipeline(this.#sg),i.setBindGroup(0,this.#og);const g=Math.ceil(this.#rg/64);i.dispatchWorkgroups(g)})}#yg(){const{resourceManager:i,gpuDevice:g}=this.#h,x={code:this.#dg(this.geometry,this.material)},v=i.createGPUShaderModule(`${Ls}_${this.#ig}_${this.uuid}`,x),_=i.getGPUBindGroupLayout(ResourceManager.PRESET_VERTEX_GPUBindGroupLayout_Instancing);this.gpuRenderInfo.vertexShaderModule=v,this.gpuRenderInfo.pipeline=createBasePipeline(this,v,_),this.gpuRenderInfo.shadowPipeline=createBasePipeline(this,v,_,fn),this.gpuRenderInfo.vertexUniformBindGroup=g.createBindGroup(this.#Rg()),this.#Ks.length=0,this.LODManager.LODList.forEach((x,v)=>{const y={code:this.#dg(x.geometry,x.material)},b=i.createGPUShaderModule(`${Ls}_${this.#ig}_LOD${v}_${this.uuid}`,y);this.#Ks[v]={pipeline:createBasePipeline({vertexStateBuffers:x.geometry.gpuRenderInfo.buffers,primitiveState:this.primitiveState,depthStencilState:this.depthStencilState,geometry:x.geometry,material:x.material||this.material,redGPUContext:this.#h,gpuRenderInfo:this.gpuRenderInfo},b,_),vertexUniformBindGroup:g.createBindGroup(this.#Rg(v+1))}})}#Rg(i=0){const{resourceManager:g}=this.#h,{vertexUniformBuffer:x}=this.gpuRenderInfo,{material:v}=this,{basicSampler:_,basicDisplacementSampler:y,emptyBitmapTextureView:b}=g,{gpuSampler:S}=_,w=g.getGPUBindGroupLayout(ResourceManager.PRESET_VERTEX_GPUBindGroupLayout_Instancing),L=this.#cg,k=L*i,H=L;if(k+H>this.#lg.size)throw new Error("Binding range exceeds visibility buffer size.");return{layout:w,label:"VERTEX_BIND_GROUP_DESCRIPTOR_INSTANCING",entries:[{binding:0,resource:{buffer:x.gpuBuffer,offset:0,size:x.size}},{binding:1,resource:y.gpuSampler},{binding:2,resource:g.getGPUResourceBitmapTextureView(v?.displacementTexture)||b},{binding:3,resource:{buffer:this.#lg.gpuBuffer,offset:k,size:H}}]}}#pg(){const i=4*this.#ig;this.#cg=256*Math.ceil(i/256),this.#hg=this.#cg/4}#mg(){const i=this.gpuRenderInfo.vertexUniformInfo,g=new ArrayBuffer(i.arrayBufferByteLength),x=new StorageBuffer(this.#h,g,`InstanceBuffer_${this.uuid}`),v=this.gpuRenderInfo.vertexUniformBuffer;v?.gpuBuffer&&(v.dataViewF32.length>x.dataViewF32.length?x.dataViewF32.set(v.dataViewF32.subarray(0,x.dataViewF32.length),0):x.dataViewF32.set(v.dataViewF32,0),v.destroy()),this.gpuRenderInfo.vertexUniformBuffer=x}#Cg(i,g="",x="",v="",_=""){return[g,x,v,i.replaceAll(/__INSTANCE_COUNT__/g,this.#ig.toString()),_].join("\n")}#dg(i,g){const x=i.vertexBuffer.interleavedStruct.label,v=g instanceof PBRMaterial,_="PBR"===x&&v,y=_?"struct InputData{@builtin(instance_index)instanceIdx:u32,@location(0)position:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,@location(3)uv1:vec2,@location(4)vertexColor_0:vec4,@location(5)vertexTangent:vec4,};":"struct InputData{@builtin(instance_index)instanceIdx:u32,@location(0)position:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,@location(3)vertexTangent:vec4,};",b="PBR"!==x&&v||_?As:"struct VertexOutput{@builtin(position)position:vec4,@location(0)vertexPosition:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,@location(3)vertexTangent:vec4,@location(7)currentClipPos:vec4,@location(8)prevClipPos:vec4,@location(11)instanceOpacity:f32,@location(12)motionVector:vec3,@location(13)shadowCoord:vec3,@location(14)@interpolate(flat)receiveShadow:f32,@location(15)@interpolate(flat)pickingId:vec4,};";return this.#Cg("#redgpu_include SYSTEM_UNIFORM;#redgpu_include displacement.getDisplacementPosition;#redgpu_include displacement.getDisplacementNormal;struct InstanceUniforms{instanceGroupModelMatrix:mat4x4,instanceGroupNormalModelMatrix:mat4x4,useDisplacementTexture:u32,displacementScale:f32,padding:vec2,instanceModelMatrixs:array,__INSTANCE_COUNT__>,instanceNormalModelMatrix:array,__INSTANCE_COUNT__>,instanceOpacity:array,};@group(1)@binding(0)varinstanceUniforms:InstanceUniforms;@group(1)@binding(1)var displacementTextureSampler:sampler;@group(1)@binding(2)var displacementTexture:texture_2d;@group(1)@binding(3)varvisibilityBuffer:array;const maxDistance:f32=1000.0;",_?"@vertex fn main(inputData:InputData)->VertexOutput{var output:VertexOutput;let input_instanceIdx:u32=visibilityBuffer[inputData.instanceIdx];let u_modelMatrix=instanceUniforms.instanceModelMatrixs[input_instanceIdx];let u_normalModelMatrix=instanceUniforms.instanceNormalModelMatrix[input_instanceIdx];let u_instanceGroupModelMatrix=instanceUniforms.instanceGroupModelMatrix;let u_useDisplacementTexture=instanceUniforms.useDisplacementTexture==1u;let u_displacementScale=instanceUniforms.displacementScale;let u_projectionMatrix=systemUniforms.projection.projectionMatrix;let u_projectionViewMatrix=systemUniforms.projection.projectionViewMatrix;let u_camera=systemUniforms.camera;let u_viewMatrix=u_camera.viewMatrix;let u_cameraPosition=u_camera.cameraPosition;let input_position=inputData.position;let input_vertexNormal=inputData.vertexNormal;let input_uv=inputData.uv;var position:vec4=u_modelMatrix*vec4(input_position,1.0);let worldPosition=position.xyz;if(u_useDisplacementTexture){let worldPosForDisplacement=(u_instanceGroupModelMatrix*position).xyz;let distance=distance(worldPosForDisplacement,u_cameraPosition);let maxMipLevel=f32(textureNumLevels(displacementTexture))-1.0;let targetMipLevel=clamp((distance/maxDistance)*maxMipLevel,.0,maxMipLevel);let displacedPosition=getDisplacementPosition(input_position,input_vertexNormal,displacementTexture,displacementTextureSampler,u_displacementScale,input_uv,targetMipLevel);position=u_modelMatrix*vec4(displacedPosition,1.0);}let worldPositionVec4=u_instanceGroupModelMatrix*position;output.position=u_projectionViewMatrix*worldPositionVec4;output.vertexPosition=worldPositionVec4.xyz;let u_instanceGroupNormalModelMatrix=instanceUniforms.instanceGroupNormalModelMatrix;var normalPosition:vec3=(u_instanceGroupNormalModelMatrix*u_normalModelMatrix*vec4(input_vertexNormal,.0)).xyz;output.vertexNormal=normalize(normalPosition);output.instanceOpacity=instanceUniforms.instanceOpacity[input_instanceIdx];output.uv=inputData.uv;output.uv1=inputData.uv1;output.vertexColor_0=inputData.vertexColor_0;output.vertexTangent=vec4((u_instanceGroupNormalModelMatrix*u_normalModelMatrix*vec4(inputData.vertexTangent.xyz,.0)).xyz,inputData.vertexTangent.w);return output;}":"@vertex fn main(inputData:InputData)->VertexOutput{var output:VertexOutput;let input_instanceIdx:u32=visibilityBuffer[inputData.instanceIdx];let u_modelMatrix=instanceUniforms.instanceModelMatrixs[input_instanceIdx];let u_normalModelMatrix=instanceUniforms.instanceNormalModelMatrix[input_instanceIdx];let u_instanceGroupModelMatrix=instanceUniforms.instanceGroupModelMatrix;let u_useDisplacementTexture=instanceUniforms.useDisplacementTexture==1u;let u_displacementScale=instanceUniforms.displacementScale;let u_projectionMatrix=systemUniforms.projection.projectionMatrix;let u_projectionViewMatrix=systemUniforms.projection.projectionViewMatrix;let u_camera=systemUniforms.camera;let u_viewMatrix=u_camera.viewMatrix;let u_cameraPosition=u_camera.cameraPosition;let input_position=inputData.position;let input_vertexNormal=inputData.vertexNormal;let input_uv=inputData.uv;var position:vec4=u_modelMatrix*vec4(input_position,1.0);let worldPosition=position.xyz;if(u_useDisplacementTexture){let worldPosForDisplacement=(u_instanceGroupModelMatrix*position).xyz;let distance=distance(worldPosForDisplacement,u_cameraPosition);let maxMip=f32(textureNumLevels(displacementTexture))-1.0;let mipLevel=clamp((distance/maxDistance)*maxMip,.0,maxMip);let displacedPosition=getDisplacementPosition(input_position,input_vertexNormal,displacementTexture,displacementTextureSampler,u_displacementScale,input_uv,mipLevel);position=u_modelMatrix*vec4(displacedPosition,1.0);}let worldPositionVec4=u_instanceGroupModelMatrix*position;output.position=u_projectionViewMatrix*worldPositionVec4;output.vertexPosition=worldPositionVec4.xyz;let u_instanceGroupNormalModelMatrix=instanceUniforms.instanceGroupNormalModelMatrix;var normalPosition:vec3=(u_instanceGroupNormalModelMatrix*u_normalModelMatrix*vec4(input_vertexNormal,.0)).xyz;output.vertexNormal=normalize(normalPosition);output.uv=input_uv;output.instanceOpacity=instanceUniforms.instanceOpacity[input_instanceIdx];return output;}",y,b,"#redgpu_include shadow.getShadowClipPosition #redgpu_include systemStruct.OutputShadowData;@vertex fn entryPointShadowVertex(inputData:InputData)->OutputShadowData{var output:OutputShadowData;let input_instanceIdx:u32=visibilityBuffer[inputData.instanceIdx];let u_directionalLightProjectionViewMatrix=systemUniforms.directionalLightProjectionViewMatrix;let u_modelMatrix=instanceUniforms.instanceModelMatrixs[input_instanceIdx];let u_instanceGroupModelMatrix=instanceUniforms.instanceGroupModelMatrix;let u_useDisplacementTexture=instanceUniforms.useDisplacementTexture==1u;let u_displacementScale=instanceUniforms.displacementScale;let input_position=inputData.position;let input_vertexNormal=inputData.vertexNormal;let input_uv=inputData.uv;var position:vec4=u_modelMatrix*vec4(input_position,1.0);if(u_useDisplacementTexture){let worldPos=(u_instanceGroupModelMatrix*position).xyz;let distance=distance(worldPos,u_directionalLightProjectionViewMatrix[3].xyz);let maxMipLevel=f32(textureNumLevels(displacementTexture))-1.0;let targetMipLevel=clamp((distance/maxDistance)*maxMipLevel,.0,maxMipLevel);let displacedPosition=getDisplacementPosition(input_position,input_vertexNormal,displacementTexture,displacementTextureSampler,u_displacementScale,input_uv,targetMipLevel);position=u_modelMatrix*vec4(displacedPosition,1.0);}output.position=getShadowClipPosition((u_instanceGroupModelMatrix*position).xyz,u_directionalLightProjectionViewMatrix);return output;}")}#Mg(){return this.#Cg("struct InstanceUniforms{instanceGroupModelMatrix:mat4x4,instanceGroupNormalModelMatrix:mat4x4,useDisplacementTexture:u32,displacementScale:f32,padding:vec2,instanceModelMatrixs:array,__INSTANCE_COUNT__>,instanceNormalModelMatrix:array,__INSTANCE_COUNT__>,instanceOpacity:array,};struct CullingUniforms{instanceCount:u32,stride:u32,lodNum:u32,padding:f32,cameraPosition:vec3,frustumPlanes:array,6>,lodDistanceList:array,};struct IndirectDrawArgs{vertexCount:u32,instanceCount:atomic,firstVertex:u32,baseVertex:u32,firstInstance:u32,};@group(0)@binding(0)varinstanceUniforms:InstanceUniforms;@group(0)@binding(1)varcullingUniforms:CullingUniforms;@group(0)@binding(2)varvisibilityBuffer:array;@group(0)@binding(3)varindirectDrawBuffer:array;const BOUNDING_RADIUS:f32=1.0;fn distanceToPlane(position:vec3,plane:vec4)->f32{return dot(vec4(position,1.0),plane);}fn isInsideFrustum(position:vec3,radius:f32)->bool{for(var i:u32=0u;i<6u;i=i+1u){let plane=cullingUniforms.frustumPlanes[i];let distance=distanceToPlane(position,plane);if(distance<-radius){return false;}}return true;}fn calculateLODLevel(distanceToCamera:f32)->u32{if(cullingUniforms.lodNum==0u){return 0u;}for(var i:u32=0u;i){let instanceIdx=globalId.x;if(instanceIdx>=(cullingUniforms.instanceCount)){return;}let u_instanceGroupModelMatrix=instanceUniforms.instanceGroupModelMatrix;let modelMatrix=u_instanceGroupModelMatrix*instanceUniforms.instanceModelMatrixs[instanceIdx];let worldPosition=vec3(modelMatrix[3][0],modelMatrix[3][1],modelMatrix[3][2]);let scaleX=length(vec3(modelMatrix[0][0],modelMatrix[0][1],modelMatrix[0][2]));let scaleY=length(vec3(modelMatrix[1][0],modelMatrix[1][1],modelMatrix[1][2]));let scaleZ=length(vec3(modelMatrix[2][0],modelMatrix[2][1],modelMatrix[2][2]));let maxScale=max(max(scaleX,scaleY),scaleZ);let scaledRadius=BOUNDING_RADIUS*maxScale;let isVisible=isInsideFrustum(worldPosition,scaledRadius);if(isVisible){let distanceToCamera=distance(worldPosition,cullingUniforms.cameraPosition);let lodLevel=calculateLODLevel(distanceToCamera);let visibilityStride=cullingUniforms.stride;let aliveIndex=atomicAdd(&indirectDrawBuffer[lodLevel].instanceCount,1u);visibilityBuffer[visibilityStride*lodLevel+aliveIndex]=instanceIdx;}}")}}var Us=Object.freeze({__proto__:null,ADrawDebuggerLight:ADrawDebuggerLight,DrawDebuggerAxis:DrawDebuggerAxis,DrawDebuggerDirectionalLight:DrawDebuggerDirectionalLight,DrawDebuggerGrid:DrawDebuggerGrid,DrawDebuggerMesh:DrawDebuggerMesh,DrawDebuggerPointLight:DrawDebuggerPointLight,DrawDebuggerSpotLight:DrawDebuggerSpotLight}),ks=Object.freeze({__proto__:null,CoreInstancingMesh:Is,CoreMesh:qa,CoreSkyAtmosphere:Ka,CoreSkyBox:Ga,CoreSpriteSheet:as,CoreTextField:ys,CoreView:Ya,DrawDebugger:Us,Group2D:Group2D,Group3D:Group3D,InstancingMesh:InstancingMesh,LINE_TYPE:ms,Line2D:class extends Line3D{constructor(i,g=ms.LINEAR,x="#fff"){super(i,g,x),this._material=new LineMaterial(i)}get geometry(){return this._geometry}set geometry(i){consoleAndThrowError("Line2D can not change geometry")}get material(){return this._material}set material(i){consoleAndThrowError("Line2D can not change material")}createCustomMeshVertexShaderModule=()=>this.createMeshVertexShaderModuleBASIC("VERTEX_MODULE_LINE_2D",vs,_s,ps);addPoint(i=0,g=0,x=this.baseColor,v=1,_=0,y=0,b=0,S=0){super.addPoint(i,g,0,x,v,_,y,0,b,S,0)}addPointAt(i,g=0,x=0,v=this.baseColor,_=1,y=0,b=0,S=0,w=0){super.addPointAt(i,g,x,0,v,_,y,b,0,S,w,0)}},Line3D:Line3D,Mesh:Mesh,PARTICLE_EASE:Wa,ParticleEmitter:ParticleEmitter,Scene:Scene,SkyAtmosphere:SkyAtmosphere,SkyBox:SkyBox,Sprite2D:Sprite2D,Sprite3D:Sprite3D,SpriteSheet2D:SpriteSheet2D,SpriteSheet3D:SpriteSheet3D,SpriteSheetInfo:SpriteSheetInfo,TextField2D:TextField2D,TextField3D:TextField3D,View2D:View2D,View3D:View3D}),Gs=Object.freeze({__proto__:null,ABaseLight:ABaseLight,LightManager:LightManager}),Os=Object.freeze({__proto__:null,AmbientLight:AmbientLight,Core:Gs,DirectionalLight:DirectionalLight,PointLight:PointLight,SpotLight:SpotLight});function sortTransparentObjects(i,g){const x={},{x:v,y:_,z:y}=i;return g.sort((i,g)=>{if(i=i.mesh,g=g.mesh,!x[i.uuid]){const g=i.x-v,b=i.y-_,S=i.z-y;x[i.uuid]=g*g+b*b+S*S}if(!x[g.uuid]){const i=g.x-v,b=g.y-_,S=g.z-y;x[g.uuid]=i*i+b*b+S*S}return x[g.uuid]-x[i.uuid]})}var Vs=Object.freeze({__proto__:null,Ray:Ray,calculateNormals:calculateNormals,calculateTangents:calculateTangents,computeViewFrustumPlanes:computeViewFrustumPlanes,getScreenPoint:getScreenPoint,localToWorld:localToWorld,mat3:Ct,mat4:At,matToEuler:mat4ToEuler,quat:br,quaternionToRotationMat4:quaternionToRotationMat4,screenToWorld:screenToWorld,sortTransparentObjects:sortTransparentObjects,updateObject3DMatrix:updateObject3DMatrix,vec2:Dr,vec3:zt,vec4:Jt,worldToLocal:worldToLocal}),Ns=Object.freeze({__proto__:null,GeometryGPURenderInfo:GeometryGPURenderInfo,Primitive:Primitive,PrimitiveUtils:PrimitiveUtils,createPrimitiveGeometry:createPrimitiveGeometry});var Fs=Object.freeze({__proto__:null,Box:Box,Capsule:class extends Primitive{constructor(i,g=.5,x=1,v=32,_=1,y=12){const b=Primitive.generateUniqueKey("CAPSULE",{radius:g,height:x,radialSegments:v,heightSegments:_,capSegments:y});super(i,b,()=>PrimitiveUtils.generateCapsuleData(i,g,x,v,_,y,b))}},Circle:class extends Primitive{constructor(i,g=1,x=8,v=0,_=2*Math.PI,y=!1){const b=Primitive.generateUniqueKey("CIRCLE",{radius:g,radialSegments:x,thetaStart:v,thetaLength:_,isRadial:y});super(i,b,()=>PrimitiveUtils.generateCircleEntryData(i,g,x,v,_,y,b))}},Cone:class extends Primitive{constructor(i,g=1,x=1,v=32,_=1,y=!0,b=0,S=2*Math.PI){const w=Primitive.generateUniqueKey("CONE",{radius:g,height:x,radialSegments:v,heightSegments:_,capBottom:y,thetaStart:b,thetaLength:S});super(i,w,()=>PrimitiveUtils.generateConeData(i,g,x,v,_,y,b,S,w))}},Core:Ns,Cylinder:Cylinder,Ground:class extends Primitive{constructor(i,g=1,x=1,v=1,_=1,y=!1){const b=Primitive.generateUniqueKey("GROUND",{width:g,height:x,widthSegments:v,heightSegments:_,flipY:y});super(i,b,()=>PrimitiveUtils.generateGroundData(i,g,x,v,_,y,b))}},Plane:Plane,Ring:class extends Primitive{constructor(i,g=.5,x=1,v=8,_=1,y=0,b=2*Math.PI,S=!1){const w=Primitive.generateUniqueKey("RING",{innerRadius:g,outerRadius:x,thetaSegments:v,phiSegments:_,thetaStart:y,thetaLength:b,isRadial:S});super(i,w,()=>PrimitiveUtils.generateRingEntryData(i,g,x,v,_,y,b,S,w))}},RoundedBox:class extends Primitive{constructor(i,g=1,x=1,v=1,_=1,y=1,b=1,S=.1,w=4){const L=`RoundedBox_${g}_${x}_${v}_${_}_${y}_${b}_${S}_${w}`;super(i,L,()=>PrimitiveUtils.generateRoundedBoxData(i,g,x,v,_,y,b,S,w,L))}},Sphere:Sphere,Torus:class extends Primitive{constructor(i,g=1,x=.5,v=16,_=16,y=0,b=2*Math.PI,S=!1,w=!1,L=!1,k=!1){if(v<3)throw new Error("radialSegments must be 3 or greater");if(_<3)throw new Error("tubularSegments must be 3 or greater");const H=Primitive.generateUniqueKey("TORUS",{radius:g,thickness:x,radialSegments:v,tubularSegments:_,thetaStart:y,thetaLength:b,capStart:S,capEnd:w,isRadialCapStart:L,isRadialCapEnd:k});super(i,H,()=>PrimitiveUtils.generateTorusData(i,g,x,v,_,y,b,S,w,L,k,H))}},TorusKnot:class extends Primitive{constructor(i,g=1,x=.4,v=64,_=8,y=2,b=3){const S=Primitive.generateUniqueKey("TORUS_KNOT",{radius:g,tubeRadius:x,tubularSegments:v,radialSegments:_,windingsAroundAxis:y,windingsAroundCircle:b});super(i,S,()=>PrimitiveUtils.generateTorusKnotData(i,g,x,v,_,y,b,S))}}});const Hs=parseWGSL("PHONG_MATERIAL","#redgpu_include SYSTEM_UNIFORM;#redgpu_include color.getTintBlendMode;#redgpu_include shadow.getDirectionalShadowVisibility;#redgpu_include math.tnb.getTBNFromVertexTangent #redgpu_include math.tnb.getNormalFromNormalMap #redgpu_include displacement.getDisplacementNormal;#redgpu_include entryPoint.mesh.entryPointPickingFragment;#redgpu_include systemStruct.OutputFragment;#redgpu_include math.getMotionVector;#redgpu_include lighting.getLightDistanceAttenuation;#redgpu_include lighting.getLightAngleAttenuation;#redgpu_include skyAtmosphere.skyAtmosphereFn const maxDistance:f32=1000.0;struct Uniforms{color:vec3,emissiveColor:vec3,emissiveStrength:f32,specularColor:vec3,specularStrength:f32,shininess:f32,aoStrength:f32,normalScale:f32,displacementScale:f32,opacity:f32,useTint:u32,tint:vec4,tintBlendMode:u32,useSSR:u32,metallic:f32,roughness:f32,};struct InputData{@builtin(position)position:vec4,@location(0)vertexPosition:vec3,@location(1)vertexNormal:vec3,@location(2)uv:vec2,@location(3)vertexTangent:vec4,@location(7)currentClipPos:vec4,@location(8)prevClipPos:vec4,@location(11)combinedOpacity:f32,@location(12)motionVector:vec3,@location(13)shadowCoord:vec3,@location(14)@interpolate(flat)receiveShadow:f32,@location(15)@interpolate(flat)pickingId:vec4,}@group(2)@binding(0)varuniforms:Uniforms;@group(2)@binding(1)var diffuseTextureSampler:sampler;@group(2)@binding(2)var diffuseTexture:texture_2d;@group(2)@binding(3)var alphaTextureSampler:sampler;@group(2)@binding(4)var alphaTexture:texture_2d;@group(2)@binding(5)var specularTextureSampler:sampler;@group(2)@binding(6)var specularTexture:texture_2d;@group(2)@binding(7)var emissiveTextureSampler:sampler;@group(2)@binding(8)var emissiveTexture:texture_2d;@group(2)@binding(9)var aoTextureSampler:sampler;@group(2)@binding(10)var aoTexture:texture_2d;@group(2)@binding(11)var normalTextureSampler:sampler;@group(2)@binding(12)var normalTexture:texture_2d;@group(2)@binding(13)var displacementTextureSampler:sampler;@group(2)@binding(14)var displacementTexture:texture_2d;#redgpu_include math.PI #redgpu_include math.INV_PI #redgpu_include math.EPSILON #redgpu_include math.direction.getViewDirection fn getDiffuseBRDFDisney(NdotL:f32,NdotV:f32,LdotH:f32,roughness:f32,albedo:vec3)->vec3{if(NdotL<=.0){return vec3(.0);}let energyBias=mix(.0,0.5,roughness);let energyFactor=mix(1.0,1.0/1.51,roughness);let fd90=energyBias+2.0*LdotH*LdotH*roughness;let f0=1.0;let lightScatter=f0+(fd90-f0)*pow(1.0-NdotL,5.0);let viewScatter=f0+(fd90-f0)*pow(1.0-NdotV,5.0);return albedo*NdotL*lightScatter*viewScatter*energyFactor*INV_PI;}fn getFresnelSchlick(cosTheta:f32,F0:vec3)->vec3{return F0+(vec3(1.0)-F0)*pow(clamp(1.0-cosTheta,.0,1.0),5.0);}fn getDistributionGGX(NdotH:f32,roughness:f32)->f32{let alpha=roughness*roughness;let alpha2=alpha*alpha;let NdotH2=NdotH*NdotH;let nom=alpha2;let denom=(NdotH2*(alpha2-1.0)+1.0);let denomSquared=denom*denom;return nom/max(EPSILON,denomSquared*PI);}fn getSpecularVisibility(NdotV:f32,NdotL:f32,roughness:f32)->f32{let alpha=roughness*roughness;let alpha2=alpha*alpha;let safeNdotV=max(NdotV,1e-4);let safeNdotL=max(NdotL,1e-4);let GGXV=safeNdotL*sqrt(safeNdotV*safeNdotV*(1.0-alpha2)+alpha2);let GGXL=safeNdotV*sqrt(safeNdotL*safeNdotL*(1.0-alpha2)+alpha2);return 0.5/max(GGXV+GGXL,EPSILON);}fn getSpecularBRDF(F0:vec3,roughness:f32,NdotH:f32,NdotV:f32,NdotL:f32,LdotH:f32)->vec3{let D=getDistributionGGX(NdotH,roughness);let V=getSpecularVisibility(NdotV,NdotL,roughness);let F=getFresnelSchlick(LdotH,F0);return D*V*F;}@fragment fn main(inputData:InputData)->OutputFragment{var output:OutputFragment;let input_vertexNormal=inputData.vertexNormal.xyz;let input_vertexPosition=inputData.vertexPosition.xyz;let u_ambientLight=systemUniforms.ambientLight;let u_directionalLightCount=systemUniforms.directionalLightCount;let u_directionalLights=systemUniforms.directionalLights;let u_directionalShadowDepthTextureSize=systemUniforms.shadow.directionalShadowDepthTextureSize;let u_directionalShadowBias=systemUniforms.shadow.directionalShadowBias;let u_camera=systemUniforms.camera;let u_cameraPosition=u_camera.cameraPosition;let u_color=uniforms.color;let u_aoStrength=uniforms.aoStrength;let u_emissiveColor=uniforms.emissiveColor;let u_emissiveStrength=uniforms.emissiveStrength;let u_normalScale=uniforms.normalScale;let u_specularColor=uniforms.specularColor;let u_specularStrength=uniforms.specularStrength;let u_shininess=uniforms.shininess;let u_opacity=uniforms.opacity;let V=getViewDirection(input_vertexPosition,u_cameraPosition);let receiveShadowYn=inputData.receiveShadow !=.0;var N=normalize(input_vertexNormal);#redgpu_if displacementTexture{let dist=distance(input_vertexPosition,u_cameraPosition);let maxMip=f32(textureNumLevels(displacementTexture))-1.0;let targetMipLevel=clamp((dist/maxDistance)*maxMip,.0,maxMip);let tangentDisplacedNormal=getDisplacementNormal(displacementTexture,displacementTextureSampler,uniforms.displacementScale,inputData.uv,targetMipLevel);let tbn=getTBNFromVertexTangent(N,inputData.vertexTangent);N=normalize(tbn*tangentDisplacedNormal);}#redgpu_endIf #redgpu_if normalTexture let normalSamplerColor=textureSample(normalTexture,normalTextureSampler,inputData.uv).rgb;let tbn=getTBNFromVertexTangent(N,inputData.vertexTangent);N=getNormalFromNormalMap(normalSamplerColor,tbn,u_normalScale);#redgpu_endIf N=normalize(N);let NdotV=max(dot(N,V),1e-6);var resultAlpha:f32=u_opacity*inputData.combinedOpacity;#redgpu_if alphaTexture let alphaMapValue:f32=textureSample(alphaTexture,alphaTextureSampler,inputData.uv).r;resultAlpha=alphaMapValue*resultAlpha;if(resultAlpha==.0){discard;}#redgpu_endIf var baseColor:vec3=u_color;#redgpu_if diffuseTexture let diffuseSampleColor=textureSample(diffuseTexture,diffuseTextureSampler,inputData.uv);baseColor=diffuseSampleColor.rgb;resultAlpha=resultAlpha*diffuseSampleColor.a;#redgpu_endIf let metallicParameter=uniforms.metallic;var roughnessParameter=select(sqrt(2.0/(u_shininess+2.0)),uniforms.roughness,uniforms.roughness>.0);roughnessParameter=clamp(roughnessParameter,.045,1.0);var specularSamplerValue:f32=1.0;#redgpu_if specularTexture specularSamplerValue=textureSample(specularTexture,specularTextureSampler,inputData.uv).r;#redgpu_endIf let F0_dielectric=vec3(.04)*u_specularColor*u_specularStrength*specularSamplerValue;let F0=mix(F0_dielectric,baseColor,metallicParameter);let albedo=baseColor*(1.0-metallicParameter);var visibility:f32=1.0;visibility=getDirectionalShadowVisibility(directionalShadowMap,directionalShadowMapSampler,u_directionalShadowDepthTextureSize,u_directionalShadowBias,inputData.shadowCoord);if(!receiveShadowYn){visibility=1.0;}var totalDirectLighting=vec3(.0);for(var i=0u;itLight.radius){continue;}let L=normalize(lightDir);var attenuation=getLightDistanceAttenuation(lightDistance,tLight.radius);if(tLight.isSpotLight>.0){let spotDir=normalize(vec3(tLight.directionX,tLight.directionY,tLight.directionZ));attenuation*=getLightAngleAttenuation(normalize(-L),spotDir,tLight.innerCutoff,tLight.outerCutoff);}if(attenuation<=.0){continue;}let finalLightColor=tLight.color*tLight.intensity*attenuation;totalDirectLighting+=calcPbrLight(finalLightColor,N,V,L,NdotV,roughnessParameter,metallicParameter,albedo,F0);}var ambientContribution=albedo*u_ambientLight.color*u_ambientLight.intensity*INV_PI;if(systemUniforms.useSkyAtmosphere==1u){let u_atmo=systemUniforms.skyAtmosphere;let skyIntensity=u_atmo.sunIntensity;let diffTrans=getTransmittance(transmittanceTexture,atmosphereSampler,u_atmo.cameraHeight,N.y,u_atmo.atmosphereHeight);let skyIrradiance=textureSampleLevel(atmosphereIrradianceLUT,atmosphereSampler,N,.0).rgb*skyIntensity;ambientContribution=(ambientContribution*diffTrans)+(albedo*skyIrradiance*INV_PI);}var mixColor=totalDirectLighting+ambientContribution;#redgpu_if aoTexture mixColor*=textureSample(aoTexture,aoTextureSampler,inputData.uv).rgb*u_aoStrength;#redgpu_endIf var emissiveColor=u_emissiveColor*u_emissiveStrength;#redgpu_if emissiveTexture emissiveColor=textureSample(emissiveTexture,emissiveTextureSampler,inputData.uv).rgb*u_emissiveStrength;#redgpu_endIf let finalColor=vec4((mixColor*systemUniforms.preExposure)+emissiveColor,resultAlpha);#redgpu_if useTint output.color=getTintBlendMode(finalColor,uniforms.tintBlendMode,uniforms.tint);#redgpu_else output.color=finalColor;#redgpu_endIf if(systemUniforms.isView3D==1&&output.color.a==.0){discard;}let smoothness=1.0-roughnessParameter;let smoothnessCurved=smoothness*smoothness*(3.0-2.0*smoothness);output.gBufferNormal=vec4(N*0.5+0.5,smoothnessCurved*(.04+0.96*metallicParameter*metallicParameter));output.gBufferMotionVector=vec4(getMotionVector(inputData.currentClipPos,inputData.prevClipPos),.0,1.0);return output;}fn calcPbrLight(lightColor:vec3,N:vec3,V:vec3,L:vec3,NdotV:f32,roughness:f32,metallic:f32,albedo:vec3,F0:vec3)->vec3{let NdotL=max(dot(N,L),.0);if(NdotL<=.0){return vec3(.0);}let H=normalize(L+V);let NdotH=max(dot(N,H),.0);let LdotH=max(dot(L,H),.0);let VdotH=max(dot(V,H),.0);let F=getFresnelSchlick(VdotH,F0);let D=getDistributionGGX(NdotH,roughness);let Vis=getSpecularVisibility(NdotV,NdotL,roughness);let spec=D*Vis*F;let diff=getDiffuseBRDFDisney(NdotL,NdotV,LdotH,roughness,albedo);let kS=F;let kD=(vec3(1.0)-kS)*(1.0-metallic);return(kD*diff+spec)*lightColor*NdotL;}");class PhongMaterial extends AUVTransformBaseMaterial{constructor(i,g="#fff",x){super(i,"PHONG_MATERIAL",Hs,2),x&&(this.name=x),this.initGPURenderInfos(),this.color.setColorByHEX(g),this.emissiveColor.setColorByHEX(this.emissiveColor.hex),this.specularColor.setColorByHEX(this.specularColor.hex),this.diffuseTextureSampler=new Sampler(this.redGPUContext,{magFilter:"linear",minFilter:"linear",mipmapFilter:"linear",addressModeU:"repeat",addressModeV:"repeat",addressModeW:"repeat"})}}defineSampler(PhongMaterial,[{key:"alphaTextureSampler"},{key:"aoTextureSampler"},{key:"diffuseTextureSampler"},{key:"emissiveTextureSampler"},{key:"environmentTextureSampler"},{key:"normalTextureSampler"},{key:"specularTextureSampler"},{key:"displacementTextureSampler"}]),definePositiveNumber(PhongMaterial,[{key:"aoStrength",value:1},{key:"specularStrength",value:1},{key:"emissiveStrength",value:1},{key:"shininess",value:32},{key:"normalScale",value:1},{key:"displacementScale",value:1}]),defineColorRGB(PhongMaterial,[{key:"color"},{key:"emissiveColor",value:"#000000"},{key:"specularColor",value:"#ffffff"}]),defineTexture(PhongMaterial,[{key:"alphaTexture"},{key:"aoTexture"},{key:"diffuseTexture"},{key:"emissiveTexture"},{key:"environmentTexture"},{key:"normalTexture"},{key:"specularTexture"},{key:"displacementTexture"}]),defineBoolean(PhongMaterial,[{key:"useSSR",value:!1}]),definePositiveNumber(PhongMaterial,[{key:"metallic",value:0,min:0,max:1},{key:"roughness",value:0,min:0,max:1}]),Object.freeze(PhongMaterial);var zs=Object.freeze({__proto__:null,BLEND_MODE:Xa,BitmapMaterial:BitmapMaterial,ColorMaterial:ColorMaterial,Core:yi,PBRMaterial:PBRMaterial,PhongMaterial:PhongMaterial,TINT_BLEND_MODE:xi}),$s=Object.freeze({__proto__:null,ImmutableKeyMap:ImmutableKeyMap,ManagementResourceBase:ManagementResourceBase,ResourceBase:ResourceBase,ResourceManager:ResourceManager,ResourceStatusInfo:ResourceStatusInfo}),js=Object.freeze({__proto__:null,ABaseBuffer:ABaseBuffer,AUniformBaseBuffer:AUniformBaseBuffer}),Ks=Object.freeze({__proto__:null,VertexInterleavedStructElement:VertexInterleavedStructElement});class ResourceStateHDRTexture{texture;src;cacheKey;useNum=0;uuid;constructor(i){this.texture=i,this.src=i.src,this.cacheKey=i.cacheKey,this.useNum=0,this.uuid=i.uuid}}class HDRLoader{#Bg=!0;constructor(i=!0){this.#Bg=i}get enableDebugLogs(){return this.#Bg}set enableDebugLogs(i){this.#Bg=i}async loadHDRFile(i){this.#Bg&&g(`HDR 파일 로딩 시작: ${i}`);const x=await fetch(i);if(!x.ok)throw new Error(`HTTP ${x.status}: ${x.statusText}`);const v=await x.arrayBuffer(),_=new Uint8Array(v),y=this.#Dg(_,i);return g({...y}),{...y}}#Dg(i,x){const v=this.#Eg(i);if(this.#Bg&&g(`파일 형식: ${v.format}`),!v.isValid)throw new Error(v.error||"지원되지 않는 파일 형식입니다");if(x.split("?")[0].toLowerCase().endsWith(".hdr")){this.#Bg&&this.#Ig(i.slice(0,200));const g=this.#Ag(i);return this.#Bg&&this.#Lg(g),g}throw x.split("?")[0].toLowerCase().endsWith(".exr")?new Error("EXR format not supported yet"):new Error(`Unsupported HDR format: ${x}`)}#Ag(i){let x=0,v="";const _={};for(;x0){_[v.substring(0,g).trim()]=v.substring(g+1).trim()}}for(v="";x>8&255)&&i[g+3]===(255&x)){g+=4;for(let _=0;_<4;_++){let y=_;for(;y<4*x;){const _=i[g++];if(_>128){const b=_-128,S=i[g++];for(let i=0;ii.toString(16).padStart(2,"0")).join(" "),Array.from(i.slice(g,g+16)).map(i=>i>=32&&i<=126?String.fromCharCode(i):".").join("")}}async function float32ToFloat16Linear(i,g,x){const v=performance.now(),{gpuDevice:_}=i,{width:y,height:b,targetTexture:S}=x,w=g.length/4;try{const x=_.createShaderModule({code:"struct Constants{width:u32,height:u32,}@group(0)@binding(0)varinputData:array;@group(0)@binding(1)varoutputData:array;@group(0)@binding(2)varconstants:Constants;fn floatToHalf(value:f32)->u32{let bits=bitcast(value);let sign=(bits>>16u)& 0x8000u;var exp=(bits>>23u)& 0xFFu;var mantissa=bits & 0x7FFFFFu;if(exp==0u){return sign;}if(exp==255u){return sign | 0x7C00u | select(0u,1u,mantissa !=0u);}let newExp=i32(exp)-127+15;if(newExp<=0){return sign;}if(newExp>=31){return sign | 0x7C00u;}return sign |(u32(newExp)<<10u)|(mantissa>>13u);}@compute @workgroup_size(8,8)fn main(@builtin(global_invocation_id)global_id:vec3){let x=global_id.x;let y=global_id.y;if(x>=constants.width||y>=constants.height){return;}let pixelIndex=y*constants.width+x;let baseIndex=pixelIndex*4u;let r=inputData[baseIndex];let g=inputData[baseIndex+1u];let b=inputData[baseIndex+2u];let a=inputData[baseIndex+3u];let r16=floatToHalf(r);let g16=floatToHalf(g);let b16=floatToHalf(b);let a16=floatToHalf(a);let outputIndex=pixelIndex*2u;outputData[outputIndex]=(g16<<16u)| r16;outputData[outputIndex+1u]=(a16<<16u)| b16;}",label:"float16_linear_conversion_shader"}),L=function(i,g,x){const v=i.createBuffer({size:g.byteLength,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST,label:"float16_input_buffer"}),_=i.createBuffer({size:8*x,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC,label:"float16_output_buffer"}),y=i.createBuffer({size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,label:"float16_constants_buffer"});return i.queue.writeBuffer(v,0,g),{inputBuffer:v,outputBuffer:_,constantsBuffer:y}}(_,g,w);_.queue.writeBuffer(L.constantsBuffer,0,new Uint32Array([y,b]));const{computePipeline:k,bindGroup:H}=function(i,g,x){const v=i.createComputePipeline({layout:"auto",compute:{module:g,entryPoint:"main"},label:"float16_conversion_pipeline"}),_=i.createBindGroup({layout:v.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:x.inputBuffer}},{binding:1,resource:{buffer:x.outputBuffer}},{binding:2,resource:{buffer:x.constantsBuffer}}],label:"float16_conversion_bindgroup"});return{computePipeline:v,bindGroup:_}}(_,x,L);await async function(i,g,x,v,_,y,b){const S=Math.ceil(y/8),w=Math.ceil(b/8);if(S>65535||w>65535)throw new Error(`이미지 크기 초과: ${S} × ${w}`);await i.commandEncoderManager.immediateComputePass("float16_conversion_command_encoder",i=>{i.setPipeline(g),i.setBindGroup(0,x),i.dispatchWorkgroups(S,w)},i=>{i.copyBufferToTexture({buffer:v,bytesPerRow:8*y,rowsPerImage:b},{texture:_},{width:y,height:b,depthOrArrayLayers:1})}),await i.gpuDevice.queue.onSubmittedWorkDone()}(i,k,H,L.outputBuffer,S,y,b),function(i){i.inputBuffer.destroy(),i.outputBuffer.destroy(),i.constantsBuffer.destroy()}(L);return{processedPixels:w,executionTime:performance.now()-v}}catch(i){throw console.error("Float16 변환 실패:",i),i}}class HDRTexture extends ManagementResourceBase{#V;#wo;#H=0;#kg=new HDRLoader;#z="rgba16float";#q;#Y;#Gt=0;#Ot=0;constructor(i,g,x,v){if(super(i,"managedHDRTextureState"),this.#q=x,this.#Y=v,g){const i=this.#W(g);this.#Gg(i),this.#wo=i,this.cacheKey=this.#Z(g);const{table:x}=this.targetResourceManagedState;let v=x.get(this.cacheKey);if(v){const i=v.texture;return this.#q?.(i),i}this.src=g,this.#J()}}get width(){return this.#Gt}get height(){return this.#Ot}get videoMemorySize(){return this.#H}get gpuTexture(){return this.#V}get src(){return this.#wo}set src(i){const g=this.#W(i);this.#Gg(g),this.#wo=g,this.cacheKey=this.#Z(i),this.#wo&&this.#Og(this.#wo)}destroy(){const i=this.#V;this.#te(null),this.notifyUpdate(!0),this.#re(),this.#wo=null,this.cacheKey=null,i&&this.redGPUContext.commandEncoderManager.addDeferredDestroy(i)}#Z(i){let g;return i||(g=this.uuid),g="string"==typeof i?getAbsoluteURL(window.location.href,i):i.cacheKey||getAbsoluteURL(window.location.href,i.src),`HDRTexture_${g}`}#W(i){return"string"==typeof i?i:i.src}#Gg(i){if(!i||"string"!=typeof i)throw new Error("HDR 파일 경로가 필요합니다");if(!i.split("?")[0].split("#")[0].toLowerCase().endsWith(".hdr"))throw new Error(`지원되지 않는 형식입니다. .hdr 형식만 지원됩니다. 입력된 파일: ${i}`)}async#Og(i){try{const g=await this.#kg.loadHDRFile(i);this.#Gt=g.width,this.#Ot=g.height,await this.#ee(g),this.#q?.(this),this.notifyUpdate()}catch(i){console.error("HDR loading error:",i),this.#Y?.(i)}}async#ee(i){const{gpuDevice:g}=this.redGPUContext,x=this.#V,v={size:[this.#Gt,this.#Ot,1],format:this.#z,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC,label:`HDRTexture_2D_${this.#wo}`},_=g.createTexture(v);await float32ToFloat16Linear(this.redGPUContext,i.data,{width:this.#Gt,height:this.#Ot,targetTexture:_}),this.#te(_),x&&this.redGPUContext.commandEncoderManager.addDeferredDestroy(x)}#te(i){this.targetResourceManagedState.videoMemory-=this.#H,this.#V=i,this.#H=i?calculateTextureByteSize(i):0,this.targetResourceManagedState.videoMemory+=this.#H,this.notifyUpdate()}#J(){this.redGPUContext.resourceManager.registerManagementResource(this,new ResourceStateHDRTexture(this))}#re(){this.redGPUContext.resourceManager.unregisterManagementResource(this)}}Object.freeze(HDRTexture);const Xs={MODE_1D:1,MODE_2D:2,MODE_3D:3};Object.freeze(Xs);const qs="managedBitmapTextureState",Ys={animationSpeed:1,animationX:.1,animationY:.1};class ANoiseTexture extends ManagementResourceBase{mipLevelCount=1;useMipmap=!0;src;#V;#Vg=8;#Ng=8;#Fg=1;#Hg;#zg;#$g;#jg;#Kg;#se;#Xg;#Gt;#Ot;#qg;#Yg=0;#Wg=1;#Zg=Ys.animationX;#Jg=Ys.animationY;#H=0;constructor(i,g=1024,x=1024,v,_=!0){super(i,qs),validateUintRange(g,2,2048),validateUintRange(x,2,2048),this.#Gt=g,this.#Ot=x,this.#qg=v,this.useMipmap=_,this.#N(i),this.cacheKey=`NoiseTexture_${g}x${x}_${Date.now()}`,this.#V=this.#Qg(i,g,x),this.#H=calculateTextureByteSize(this.#V),this.#ex(),this.#J()}get videoMemorySize(){return this.#H}get resourceManagerKey(){return qs}get animationSpeed(){return this.#Wg}set animationSpeed(i){validatePositiveNumberRange(i),this.#Wg=i,this.updateUniform("animationSpeed",i)}get animationX(){return this.#Zg}set animationX(i){validateNumber(i),this.#Zg=i,this.updateUniform("animationX",i)}get animationY(){return this.#Jg}set animationY(i){validateNumber(i),this.#Jg=i,this.updateUniform("animationY",i)}get uniformInfo(){return this.#Xg}get gpuTexture(){return this.#V}get time(){return this.#Yg}set time(i){validatePositiveNumberRange(i),this.#Yg=i,this.updateUniform("time",i/1e3)}updateUniform(i,g){this.#Xg.members[i]&&(this.#se.writeOnlyBuffer(this.#Xg.members[i],g),this.#qg[i]=g),this.#ex()}updateUniforms(i){Object.entries(i).forEach(([i,g])=>{this.#Xg.members[i]&&(this.#se.writeOnlyBuffer(this.#Xg.members[i],g),this.#qg[i]=g)}),this.#ex()}render(i){this.updateUniform("time",i)}destroy(){const i=this.#V;this.notifyUpdate(!0),this.#re(),i&&i.destroy(),this.src=null,this.cacheKey=null,this.#V=null}#N(i){const{gpuDevice:g}=i,x=this.#tx();this.cacheKey=this.uuid,this.#Hg=g.createShaderModule({code:x}),this.#$g=this.#rx(i),this.#jg=this.#ix(g,this.#Hg,this.#$g);const v=parseWGSL("ANoiseTexture",x);this.#Xg=v.uniforms.uniforms;const _=new ArrayBuffer(this.#Xg.arrayBufferByteLength);this.#se=new UniformBuffer(i,_,`${this.constructor.name}_UniformBuffer`),this.#qg.uniformDefaults&&this.updateUniforms({...Ys,...this.#qg.uniformDefaults})}#tx(){return`\n ${`\n struct Uniforms {\n time: f32,\n\t\t\t\t\t\t\t\tanimationSpeed: f32,\n\t\t\t\t\t\t\t\tanimationX: f32,\n\t\t\t\t\t\t\t\tanimationY: f32,\n ${this.#qg.uniformStruct||""}\n };\n `}\n @group(0) @binding(0) var uniforms : Uniforms;\n @group(0) @binding(1) var outputTexture : texture_storage_2d;\n \n ${this.#qg.helperFunctions||""}\n @compute @workgroup_size(${this.#Vg},${this.#Ng},${this.#Fg})\n fn main (\n @builtin(global_invocation_id) global_id : vec3,\n ){\n let index = vec2(global_id.xy);\n let dimensions: vec2 = textureDimensions(outputTexture);\n \n if (index.x >= dimensions.x || index.y >= dimensions.y) {\n return;\n }\n \n let dimW = f32(dimensions.x);\n let dimH = f32(dimensions.y);\n let base_uv = vec2((f32(index.x) + 0.5) / dimW, (f32(index.y) + 0.5) / dimH);\n ${this.#qg.mainLogic}\n \n textureStore(outputTexture, index, finalColor);\n }\n `}#ex(){if(!this.#zg)return;const{redGPUContext:i}=this,{commandEncoderManager:g,resourceManager:x}=i,v={label:`NoiseTexture_${this.uuid}_ComputePass`};g.addResourceComputePass(v,i=>{i.setPipeline(this.#jg),i.setBindGroup(0,this.#zg),i.dispatchWorkgroups(Math.ceil(this.#Gt/this.#Vg),Math.ceil(this.#Ot/this.#Ng))}),this.useMipmap&&x.mipmapGenerator.generateMipmap(this.#V,this.#Kg)}#rx(i){return i.resourceManager.createBindGroupLayout("NoiseTextureBindGroupLayout",{entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.COMPUTE,storageTexture:{format:"rgba16float"}}]})}#Qg(i,g,x){this.mipLevelCount=this.useMipmap?getMipLevelCount(g,x):1,this.#Kg={size:{width:g,height:x},format:"rgba16float",mipLevelCount:this.mipLevelCount,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_DST,label:this.cacheKey};const v=i.gpuDevice.createTexture(this.#Kg),_=v.createView({baseMipLevel:0,mipLevelCount:1});return this.#zg=this.#nx(i,this.#$g,_),v}#nx(i,g,x){return i.gpuDevice.createBindGroup({layout:g,entries:[{binding:0,resource:{buffer:this.#se.gpuBuffer,offset:0,size:this.#se.gpuBuffer.size}},{binding:1,resource:x}]})}#ix(i,g,x){return i.createComputePipeline({layout:i.createPipelineLayout({bindGroupLayouts:[x]}),compute:{module:g,entryPoint:"main"}})}#J(){this.redGPUContext.resourceManager.registerManagementResource(this,new ResourceStateBitmapTexture(this))}#re(){this.redGPUContext.resourceManager.unregisterManagementResource(this)}}const mergerNoiseUniformStruct=(i,g)=>[i,g].filter(Boolean).join("\n"),mergerNoiseUniformDefault=(i,g)=>({...i,...g||{}}),mergerNoiseHelperFunctions=(i,g)=>[i,g].filter(Boolean).join("\n");const Ws=Object.values(Xs),Zs={frequency:8,amplitude:1,octaves:1,persistence:.5,lacunarity:2,seed:0,noiseDimension:Xs.MODE_2D};const Js={EUCLIDEAN:0,MANHATTAN:1,CHEBYSHEV:2};Object.freeze(Js);const Qs={F1:0,F2:1,F2_MINUS_F1:2,F1_PLUS_F2:3,CELL_ID:4,CELL_ID_COLOR:5};Object.freeze(Qs);const eo=Object.values(Js),to=Object.values(Qs),ro={frequency:8,distanceScale:1,octaves:1,persistence:.5,lacunarity:2,seed:0,distanceType:Js.EUCLIDEAN,outputType:Qs.F1,jitter:1,cellIdColorIntensity:1};var io=Object.freeze({__proto__:null,ANoiseTexture:ANoiseTexture,mergerNoiseHelperFunctions:mergerNoiseHelperFunctions,mergerNoiseUniformDefault:mergerNoiseUniformDefault,mergerNoiseUniformStruct:mergerNoiseUniformStruct});class IBL extends RedGPUObject{#Zd;#ax;#sx;#ox;#ux;#lx;#cx;#hx;#fx=!1;#al=1;#zd=2e4;constructor(i,g,x=25e3,v=1024,_=512,y=64){super(i);const b=`${g}?key=${v}_${_}_${y}`;this.#cx=_,this.#lx=v,this.#hx=y,this.#zd=x,this.#ax=new DirectCubeTexture(i,`IBL_ENV_${b}`),this.#ox=new DirectCubeTexture(i,`IBL_SPECULAR_${b}`),this.#sx=new DirectCubeTexture(i,`IBL_IRRADIANCE_${b}`);const onLoad=async i=>{i.__addDirtyPipelineListener(this.#dx),i.gpuTexture&&await this.#dx(i)};this.#ux="string"==typeof g?new HDRTexture(i,g,onLoad):new CubeTexture(i,g,!0,onLoad)}get environmentSize(){return this.#lx}get prefilterSize(){return this.#cx}get irradianceSize(){return this.#hx}get irradianceTexture(){return this.#sx}get environmentTexture(){return this.#ax}get prefilterTexture(){return this.#ox}get intensityMultiplier(){return this.#al}set intensityMultiplier(i){this.#al=i}get luminance(){return this.#zd}set luminance(i){this.#zd=i}#dx=async i=>{if(!(i=i||this.#ux)||!i.gpuTexture||this.#fx)return;const{resourceManager:g}=this;this.#fx=!0;try{if(i instanceof HDRTexture){const{equirectangularToCubeGenerator:x}=g,v=await x.generate(i.gpuTexture,this.#lx);this.#Zd=v.gpuTexture}else this.#Zd=i.gpuTexture;await this.#mx()}finally{this.#fx=!1}};async#mx(){const{resourceManager:i}=this,{prefilterGenerator:g,irradianceGenerator:x}=i;if(this.#Zd){this.#ax.gpuTexture=this.#Zd;const i=await g.generate(this.#Zd,this.#cx);this.#ox.gpuTexture=i.gpuTexture;const v=await x.generate(this.#Zd,this.#hx);this.#sx.gpuTexture=v.gpuTexture}}}Object.freeze(IBL);var no=Object.freeze({__proto__:null,ShaderVariantGenerator:ShaderVariantGenerator,WGSLUniformTypes:WGSLUniformTypes,ensureVertexIndexBuiltin:ensureVertexIndexBuiltin,preprocessWGSL:preprocessWGSL}),ao=Object.freeze({__proto__:null,BitmapTexture:BitmapTexture,Core:$s,CoreBuffer:js,CoreIBL:H,CoreNoiseTexture:io,CoreVertexBuffer:Ks,CoreWGSLParser:no,CubeTexture:CubeTexture,DirectCubeTexture:DirectCubeTexture,DirectTexture:DirectTexture,DownSampleCubeMapGenerator:DownSampleCubeMapGenerator,HDRTexture:HDRTexture,IBL:IBL,IndexBuffer:IndexBuffer,MipmapGenerator:MipmapGenerator,NOISE_DIMENSION:Xs,PackedTexture:PackedTexture,Sampler:Sampler,SimplexTexture:class extends ANoiseTexture{#px=Zs.frequency;#gx=Zs.amplitude;#xx=Zs.octaves;#vx=Zs.persistence;#_x=Zs.lacunarity;#yx=Zs.seed;#bx=Zs.noiseDimension;constructor(i,g=1024,x=1024,v,_=!0){super(i,g,x,{...v,mainLogic:v?.mainLogic||"\n\t\t\t\t\t\tlet uv = vec2(\n\t\t\t\t\t\t\t(base_uv.x + uniforms.time * ( uniforms.animationX * uniforms.animationSpeed )) , \n\t\t\t\t\t\t\t(base_uv.y + uniforms.time * ( uniforms.animationY * uniforms.animationSpeed )) \n\t\t\t\t\t\t);\n\t\t\t\t\t\tlet noise = getSimplexNoiseByDimension( uv,uniforms );\n \n let finalColor = vec4(noise, noise, noise, 1.0);\n\t\t\t",uniformStruct:mergerNoiseUniformStruct("\n\t\t\t\t\tnoiseDimension : f32,\n\t\t\t\t\tfrequency: f32,\n\t\t\t\t\tamplitude: f32,\n\t\t\t\t\toctaves: i32,\n\t\t\t\t\tpersistence: f32,\n\t\t\t\t\tlacunarity: f32,\n\t\t\t\t\tseed: f32,\n\t\t\t\t",v?.uniformStruct),uniformDefaults:mergerNoiseUniformDefault(Zs,v?.uniformDefaults),helperFunctions:mergerNoiseHelperFunctions("fn mod289_vec3(x:vec3)->vec3{return x-floor(x*(1.0/289.0))*289.0;}fn mod289_vec2(x:vec2)->vec2{return x-floor(x*(1.0/289.0))*289.0;}fn mod289_vec4(x:vec4)->vec4{return x-floor(x*(1.0/289.0))*289.0;}fn mod289_f32(x:f32)->f32{return x-floor(x*(1.0/289.0))*289.0;}fn permute(x:vec3)->vec3{return mod289_vec3(((x*34.0)+1.0)*x);}fn permute4(x:vec4)->vec4{return mod289_vec4(((x*34.0)+1.0)*x);}fn permute_f32(x:f32)->f32{return mod289_f32(((x*34.0)+1.0)*x);}fn taylorInvSqrt4(r:vec4)->vec4{return 1.79284291400159-0.85373472095314*r;}fn simplex1D(x:f32)->f32{var i=floor(x);let f=fract(x);let g0=select(-1.0,1.0,(permute_f32(i)*.024390243902439)>=0.5);let g1=select(-1.0,1.0,(permute_f32(i+1.0)*.024390243902439)>=0.5);let d0=f;let d1=f-1.0;let t=f*f*f*(f*(f*6.0-15.0)+10.0);let n0=g0*d0;let n1=g1*d1;return mix(n0,n1,t)*0.395;}fn simplex2D(v:vec2)->f32{let C=vec4(0.211324865405187,0.366025403784439,-0.577350269189626,.024390243902439);var i=floor(v+dot(v,C.yy));let x0=v-i+dot(i,C.xx);let i1=select(vec2(.0,1.0),vec2(1.0,.0),x0.x>x0.y);var x12=x0.xyxy+C.xxzz;x12.x=x12.x-i1.x;x12.y=x12.y-i1.y;i=mod289_vec2(i);let p=permute(permute(i.y+vec3(.0,i1.y,1.0))+i.x+vec3(.0,i1.x,1.0));var m=max(0.5-vec3(dot(x0,x0),dot(x12.xy,x12.xy),dot(x12.zw,x12.zw)),vec3(.0));m=m*m;m=m*m;let x=2.0*fract(p*C.www)-1.0;let h=abs(x)-0.5;let ox=floor(x+0.5);let a0=x-ox;m=m*(1.79284291400159-0.85373472095314*(a0*a0+h*h));let g=vec3(a0.x*x0.x+h.x*x0.y,a0.y*x12.x+h.y*x12.y,a0.z*x12.z+h.z*x12.w);return 130.0*dot(m,g);}fn simplex3D(v:vec3)->f32{let C=vec2(1.0/6.0,1.0/3.0);let D=vec4(.0,0.5,1.0,2.0);var i=floor(v+dot(v,C.yyy));let x0=v-i+dot(i,C.xxx);let g=step(x0.yzx,x0.xyz);let l=1.0-g;let i1=min(g.xyz,l.zxy);let i2=max(g.xyz,l.zxy);let x1=x0-i1+C.xxx;let x2=x0-i2+C.yyy;let x3=x0-D.yyy;i=mod289_vec3(i);let p=permute4(permute4(permute4(i.z+vec4(.0,i1.z,i2.z,1.0))+i.y+vec4(.0,i1.y,i2.y,1.0))+i.x+vec4(.0,i1.x,i2.x,1.0));let n_=0.142857142857;let ns=n_*D.wyz-D.xzx;let j=p-49.0*floor(p*ns.z*ns.z);let x_=floor(j*ns.z);let y_=floor(j-7.0*x_);let x=x_*ns.x+ns.yyyy;let y=y_*ns.x+ns.yyyy;let h=1.0-abs(x)-abs(y);let b0=vec4(x.xy,y.xy);let b1=vec4(x.zw,y.zw);let s0=floor(b0)*2.0+1.0;let s1=floor(b1)*2.0+1.0;let sh=-step(h,vec4(.0));let a0=b0.xzyw+s0.xzyw*sh.xxyy;let a1=b1.xzyw+s1.xzyw*sh.zzww;var p0=vec3(a0.xy,h.x);var p1=vec3(a0.zw,h.y);var p2=vec3(a1.xy,h.z);var p3=vec3(a1.zw,h.w);let norm=taylorInvSqrt4(vec4(dot(p0,p0),dot(p1,p1),dot(p2,p2),dot(p3,p3)));p0*=norm.x;p1*=norm.y;p2*=norm.z;p3*=norm.w;var m=max(0.6-vec4(dot(x0,x0),dot(x1,x1),dot(x2,x2),dot(x3,x3)),vec4(.0));m=m*m;return 42.0*dot(m*m,vec4(dot(p0,x0),dot(p1,x1),dot(p2,x2),dot(p3,x3)));}fn fbm1D(pos:f32,octaves:i32)->f32{var value=.0;var amplitude=0.5;var frequency=1.0;var max_value=.0;for(var i=0;i=octaves){break;}value+=simplex1D(pos*frequency)*amplitude;max_value+=amplitude;amplitude*=0.5;frequency*=2.0;}return value/max_value;}fn fbm(pos:vec2,octaves:i32)->f32{var value=.0;var amplitude=0.5;var frequency=1.0;var max_value=.0;for(var i=0;i=octaves){break;}value+=simplex2D(pos*frequency)*amplitude;max_value+=amplitude;amplitude*=0.5;frequency*=2.0;}return value/max_value;}fn fbm3D(pos:vec3,octaves:i32)->f32{var value=.0;var amplitude=0.5;var frequency=1.0;var max_value=.0;for(var i=0;i=octaves){break;}value+=simplex3D(pos*frequency)*amplitude;max_value+=amplitude;amplitude*=0.5;frequency*=2.0;}return value/max_value;}fn getSimplexNoise1D(pos:f32,uniforms:Uniforms)->f32{var total_amplitude:f32=.0;var noise_value:f32=.0;var current_amplitude:f32=1.0;var current_frequency:f32=uniforms.frequency;for(var i:i32=0;i,uniforms:Uniforms)->f32{var total_amplitude:f32=.0;var noise_value:f32=.0;var current_amplitude:f32=1.0;var current_frequency:f32=uniforms.frequency;for(var i:i32=0;i,uniforms:Uniforms)->f32{var total_amplitude:f32=.0;var noise_value:f32=.0;var current_amplitude:f32=1.0;var current_frequency:f32=uniforms.frequency;for(var i:i32=0;i(uniforms.seed))*current_frequency;let octave_noise=simplex3D(noise_pos);noise_value+=octave_noise*current_amplitude;total_amplitude+=current_amplitude;current_amplitude*=uniforms.persistence;current_frequency*=uniforms.lacunarity;}noise_value/=total_amplitude;noise_value*=uniforms.amplitude;let normalized_noise=(noise_value+1.0)*0.5;return normalized_noise;}fn getSimplexNoiseByDimension(uv:vec2,uniforms:Uniforms)->f32{if(uniforms.noiseDimension<1.1){return getSimplexNoise1D(uv.x,uniforms);}else if(uniforms.noiseDimension<2.1){return getSimplexNoise2D(uv,uniforms);}else if(uniforms.noiseDimension<3.1){return getSimplexNoise3D(vec3(uv.x,uv.y,uniforms.seed*0.1),uniforms);}else{return getSimplexNoise2D(uv,uniforms);}}",v?.helperFunctions)},_)}get noiseDimension(){return this.#bx}set noiseDimension(i){Ws.includes(i)?(this.#bx=i,this.updateUniform("noiseDimension",i)):consoleAndThrowError(`Invalid value for noiseDimension. Received ${i}. Expected one of: ${Ws.join(", ")}`)}get frequency(){return this.#px}set frequency(i){validatePositiveNumberRange(i),this.#px=i,this.updateUniform("frequency",i)}get amplitude(){return this.#gx}set amplitude(i){validatePositiveNumberRange(i),this.#gx=i,this.updateUniform("amplitude",i)}get octaves(){return this.#xx}set octaves(i){validateUintRange(i,1,8),this.#xx=i,this.updateUniform("octaves",i)}get persistence(){return this.#vx}set persistence(i){validatePositiveNumberRange(i,0,1),this.#vx=i,this.updateUniform("persistence",i)}get lacunarity(){return this.#_x}set lacunarity(i){validatePositiveNumberRange(i),this.#_x=i,this.updateUniform("lacunarity",i)}get seed(){return this.#yx}set seed(i){this.#yx=i,this.updateUniform("seed",i)}randomizeSeed(){this.seed=1e3*Math.random()}getSettings(){return{frequency:this.#px,amplitude:this.#gx,octaves:this.#xx,persistence:this.#vx,lacunarity:this.#_x,seed:this.#yx}}applySettings(i){void 0!==i.frequency&&(this.frequency=i.frequency),void 0!==i.amplitude&&(this.amplitude=i.amplitude),void 0!==i.octaves&&(this.octaves=i.octaves),void 0!==i.persistence&&(this.persistence=i.persistence),void 0!==i.lacunarity&&(this.lacunarity=i.lacunarity),void 0!==i.seed&&(this.seed=i.seed)}},StorageBuffer:StorageBuffer,UniformBuffer:UniformBuffer,VORONOI_DISTANCE_TYPE:Js,VORONOI_OUTPUT_TYPE:Qs,VertexBuffer:VertexBuffer,VertexInterleaveType:VertexInterleaveType,VertexInterleavedStruct:VertexInterleavedStruct,VoronoiTexture:class extends ANoiseTexture{#px=ro.frequency;#Sx=ro.distanceScale;#xx=ro.octaves;#vx=ro.persistence;#_x=ro.lacunarity;#yx=ro.seed;#Tx=ro.distanceType;#wx=ro.outputType;#Mx=ro.jitter;#Px=ro.cellIdColorIntensity;constructor(i,g=1024,x=1024,v,_=!0){super(i,g,x,{...v,mainLogic:v?.mainLogic||"\n let uv = vec2(\n (base_uv.x + uniforms.time * (uniforms.animationX * uniforms.animationSpeed)),\n (base_uv.y + uniforms.time * (uniforms.animationY * uniforms.animationSpeed))\n );\n var finalColor: vec4;\n if (uniforms.outputType == 5) {\n let colorNoise = getVoronoiColorNoise(uv, uniforms);\n finalColor = vec4(colorNoise, 1.0);\n } else {\n let noise = getVoronoiNoise(uv, uniforms);\n finalColor = vec4(noise, noise, noise, 1.0);\n }\n ",uniformStruct:mergerNoiseUniformStruct("\n frequency: f32,\n distanceScale: f32,\n octaves: i32,\n persistence: f32,\n lacunarity: f32,\n seed: f32,\n distanceType: i32,\n outputType: i32,\n jitter: f32,\n cellIdColorIntensity: f32,\n ",v?.uniformStruct),uniformDefaults:mergerNoiseUniformDefault(ro,v?.uniformDefaults),helperFunctions:mergerNoiseHelperFunctions("fn hash22(p:vec2)->vec2{var p3=fract(vec3(p.xyx)*vec3(0.1031,0.1030,.0973));p3+=dot(p3,p3.yzx+33.33);return fract((p3.xx+p3.yz)*p3.zy);}fn hash12(p:vec2)->f32{var p3=fract(vec3(p.xyx)*0.1031);p3+=dot(p3,p3.yzx+33.33);return fract((p3.x+p3.y)*p3.z);}fn euclideanDistance(a:vec2,b:vec2)->f32{let d=a-b;return sqrt(d.x*d.x+d.y*d.y);}fn manhattanDistance(a:vec2,b:vec2)->f32{let d=abs(a-b);return d.x+d.y;}fn chebyshevDistance(a:vec2,b:vec2)->f32{let d=abs(a-b);return max(d.x,d.y);}fn calculateDistance(a:vec2,b:vec2,distanceType:i32)->f32{switch(distanceType){case 0:{return euclideanDistance(a,b);}case 1:{return manhattanDistance(a,b);}case 2:{return chebyshevDistance(a,b);}default:{return euclideanDistance(a,b);}}}fn cellIdToColor(cellId:f32,intensity:f32)->vec3{let h=cellId*6.28318;let s=0.7+0.3*fract(cellId*7.0);let v=0.6+0.4*fract(cellId*13.0);let c=v*s;let x=c*(1.0-abs(((h/1.047198)% 2.0)-1.0));let m=v-c;var rgb:vec3;let sector=i32(h/1.047198)% 6;switch(sector){case 0:{rgb=vec3(c,x,.0);}case 1:{rgb=vec3(x,c,.0);}case 2:{rgb=vec3(.0,c,x);}case 3:{rgb=vec3(.0,x,c);}case 4:{rgb=vec3(x,.0,c);}default:{rgb=vec3(c,.0,x);}}return(rgb+m)*intensity;}struct VoronoiResult{f1:f32,f2:f32,cellId:f32,}fn voronoiSingle(pos:vec2,frequency:f32,seed:f32,jitter:f32,distanceType:i32)->VoronoiResult{let scaledPos=pos*frequency;let gridPos=floor(scaledPos);let localPos=fract(scaledPos);var minDist1=999.0;var minDist2=999.0;var closestCellId=.0;for(var y=-1;y<=1;y++){for(var x=-1;x<=1;x++){let neighborGrid=gridPos+vec2(f32(x),f32(y));let randomOffset=hash22(neighborGrid+seed);let jitteredOffset=mix(vec2(0.5),randomOffset,jitter);let cellPoint=vec2(f32(x),f32(y))+jitteredOffset;let dist=calculateDistance(localPos,cellPoint,distanceType);if(dist,uniforms:Uniforms)->f32{var total=.0;var frequency=uniforms.frequency;var amplitude=1.0;var maxValue=.0;for(var i=0;i,uniforms:Uniforms)->vec3{if(uniforms.outputType==5){let voronoiResult=voronoiSingle(uv,uniforms.frequency,uniforms.seed,uniforms.jitter,uniforms.distanceType);return cellIdToColor(voronoiResult.cellId,uniforms.cellIdColorIntensity);}else{let grayValue=getVoronoiNoise(uv,uniforms);return vec3(grayValue,grayValue,grayValue);}}",v?.helperFunctions)},_)}get frequency(){return this.#px}set frequency(i){validatePositiveNumberRange(i),this.#px=i,this.updateUniform("frequency",i)}get distanceScale(){return this.#Sx}set distanceScale(i){validatePositiveNumberRange(i),this.#Sx=i,this.updateUniform("distanceScale",i)}get octaves(){return this.#xx}set octaves(i){validateUintRange(i,1,8),this.#xx=i,this.updateUniform("octaves",i)}get persistence(){return this.#vx}set persistence(i){validatePositiveNumberRange(i,0,1),this.#vx=i,this.updateUniform("persistence",i)}get lacunarity(){return this.#_x}set lacunarity(i){validatePositiveNumberRange(i),this.#_x=i,this.updateUniform("lacunarity",i)}get seed(){return this.#yx}set seed(i){this.#yx=i,this.updateUniform("seed",i)}get distanceType(){return this.#Tx}set distanceType(i){eo.includes(i)?(this.#Tx=i,this.updateUniform("distanceType",i)):consoleAndThrowError(`Invalid value for distanceType. Received ${i}. Expected one of: ${eo.join(", ")}`)}get outputType(){return this.#wx}set outputType(i){to.includes(i)?(this.#wx=i,this.updateUniform("outputType",i)):consoleAndThrowError(`Invalid value for outputType. Received ${i}. Expected one of: ${to.join(", ")}`)}get jitter(){return this.#Mx}set jitter(i){validatePositiveNumberRange(i,0,1),this.#Mx=i,this.updateUniform("jitter",i)}get cellIdColorIntensity(){return this.#Px}set cellIdColorIntensity(i){validatePositiveNumberRange(i),this.#Px=i,this.updateUniform("cellIdColorIntensity",i)}randomizeSeed(){this.seed=1e3*Math.random()}setEuclideanDistance(){this.distanceType=Js.EUCLIDEAN}setManhattanDistance(){this.distanceType=Js.MANHATTAN}setChebyshevDistance(){this.distanceType=Js.CHEBYSHEV}setF1Output(){this.outputType=Qs.F1}setF2Output(){this.outputType=Qs.F2}setCrackPattern(){this.outputType=Qs.F2_MINUS_F1}setSmoothBlend(){this.outputType=Qs.F1_PLUS_F2}setCellIdOutput(){this.outputType=Qs.CELL_ID}setCellIdColorOutput(){this.outputType=Qs.CELL_ID_COLOR}setCellularPattern(){this.outputType=Qs.F1,this.distanceType=Js.EUCLIDEAN,this.jitter=1}setStonePattern(){this.outputType=Qs.F2_MINUS_F1,this.distanceType=Js.EUCLIDEAN,this.jitter=.8}setOrganicPattern(){this.distanceType=Js.MANHATTAN,this.jitter=.6}setGridPattern(){this.jitter=0,this.distanceType=Js.EUCLIDEAN}setCrystalPattern(){this.outputType=Qs.F2_MINUS_F1,this.distanceType=Js.CHEBYSHEV,this.jitter=.9}setStainedGlassPattern(){this.outputType=Qs.CELL_ID_COLOR,this.distanceType=Js.EUCLIDEAN,this.jitter=.7,this.cellIdColorIntensity=.8}setMosaicPattern(){this.outputType=Qs.CELL_ID_COLOR,this.distanceType=Js.MANHATTAN,this.jitter=.3,this.cellIdColorIntensity=1}setBiomeMapPattern(){this.outputType=Qs.CELL_ID,this.distanceType=Js.EUCLIDEAN,this.jitter=.8,this.frequency=4}getSettings(){return{frequency:this.#px,distanceScale:this.#Sx,octaves:this.#xx,persistence:this.#vx,lacunarity:this.#_x,seed:this.#yx,distanceType:this.#Tx,outputType:this.#wx,jitter:this.#Mx,cellIdColorIntensity:this.#Px}}applySettings(i){void 0!==i.frequency&&(this.frequency=i.frequency),void 0!==i.distanceScale&&(this.distanceScale=i.distanceScale),void 0!==i.octaves&&(this.octaves=i.octaves),void 0!==i.persistence&&(this.persistence=i.persistence),void 0!==i.lacunarity&&(this.lacunarity=i.lacunarity),void 0!==i.seed&&(this.seed=i.seed),void 0!==i.distanceType&&(this.distanceType=i.distanceType),void 0!==i.outputType&&(this.outputType=i.outputType),void 0!==i.jitter&&(this.jitter=i.jitter),void 0!==i.cellIdColorIntensity&&(this.cellIdColorIntensity=i.cellIdColorIntensity)}getDistanceTypeName(){return{[Js.EUCLIDEAN]:"Euclidean",[Js.MANHATTAN]:"Manhattan",[Js.CHEBYSHEV]:"Chebyshev"}[this.#Tx]||"Unknown"}getOutputTypeName(){return{[Qs.F1]:"F1",[Qs.F2]:"F2",[Qs.F2_MINUS_F1]:"F2-F1 (Crack)",[Qs.F1_PLUS_F2]:"F1+F2 (Blend)",[Qs.CELL_ID]:"Cell ID",[Qs.CELL_ID_COLOR]:"Cell ID Color"}[this.#wx]||"Unknown"}},parseWGSL:parseWGSL});class GltfAnimationLooperManager{#Rx=60;#Cx=1e3/this.#Rx;#rc=0;#Bx=0;render=(i,g,x,v)=>{const _=g;this.#rc;this.#Cx,this.#rc=_,this.#Bx++;const y=Tt,b=180/Math.PI;let S,w,L,k,H,z,q,W,be,je,Ke,Xe,Ye,Ze,Je,Qe,et,tt,it,ft,pt,xt,vt,yt,bt,St,wt,Mt,Pt,Rt,Ct,Bt,Dt,Et,It,At,Lt,Ut,kt,Gt,Ot,Vt,Nt,Ft,Ht,zt,$t,jt,Kt,Xt,qt,Yt,Wt,Zt,Jt,Qt,er,tr,rr,ir,nr,ar,sr,or,ur,lr,cr,hr,fr=v.length;for(;fr--;){nr=v[fr],ir=nr.targetGLTFParsedSingleClip,rr=ir.length;const _=ir.maxTime;for(;rr--;){ar=ir[rr],sr=ar.cacheTable;const{animationTargetMesh:v,timeAnimationInfo:Tt,aniDataAnimationInfo:fr,weightMeshes:dr}=ar;v.dirtyTransform=!0,Jt=(g-nr.startTime)%(1e3*_)/1e3,lr=Tt.dataList,cr=fr.dataList,hr=lr.length;const mr=ar.lastPrevIdx||0;if(mr=lr[hr-1])ur=hr-1,or=0;else{let i=0,g=hr-1;for(;i>1;lr[x]<=Jt?i=x:g=x}ur=i,or=g}else if(Jt<=lr[0])ur=hr-1,or=0;else if(Jt>=lr[hr-1])ur=hr-1,or=0;else{let i=0,g=hr-1;for(;i>1;lr[x]<=Jt?i=x:g=x}ur=i,or=g}let pr,gr,xr,vr,_r,yr,br;ar.lastPrevIdx=ur,Qt=lr[ur],er=lr[or];const Sr=ar.interpolation;if("CUBICSPLINE"==Sr){const i=er-Qt;tr=i==i?i:0;const g=(Jt-Qt)/tr;pr=g==g?g:0,gr=pr*pr,xr=gr*pr,yr=-2*xr+3*gr,br=xr-gr,vr=1-yr,_r=br-gr+pr}else if("STEP"==Sr)tr=0;else{const i=(Jt-Qt)/(er-Qt);tr=i==i?i:0}switch(ar.key){case"rotation":if(ur!==hr-1){if("CUBICSPLINE"===Sr){let i,g,x,v,_,y,b,Je;kt=12*ur,Gt=12*or,S=cr[kt+4],w=cr[kt+5],L=cr[kt+6],k=cr[kt+7],H=S*S+w*w+L*L+k*k,H>0?(z=1/Math.sqrt(H),q=S*z,W=w*z,be=L*z,je=k*z):(q=W=be=0,je=1),S=cr[kt+8],w=cr[kt+9],L=cr[kt+10],k=cr[kt+11],H=S*S+w*w+L*L+k*k,H>0?(z=1/Math.sqrt(H),i=S*z,g=w*z,x=L*z,v=k*z):(i=g=x=0,v=1),S=cr[Gt],w=cr[Gt+1],L=cr[Gt+2],k=cr[Gt+3],H=S*S+w*w+L*L+k*k,H>0?(z=1/Math.sqrt(H),_=S*z,y=w*z,b=L*z,Je=k*z):(_=y=b=0,Je=1),S=cr[Gt+4],w=cr[Gt+5],L=cr[Gt+6],k=cr[Gt+7],H=S*S+w*w+L*L+k*k,H>0?(z=1/Math.sqrt(H),Ke=S*z,Xe=w*z,Ye=L*z,Ze=k*z):(Ke=Xe=Ye=0,Ze=1),S=vr*q+_r*i*tr+yr*Ke+br*_*tr,w=vr*W+_r*g*tr+yr*Xe+br*y*tr,L=vr*be+_r*x*tr+yr*Ye+br*b*tr,k=vr*je+_r*v*tr+yr*Ze+br*Je*tr}else{kt=ur<<2,Gt=or<<2;const i=kt<<16|Gt;let g=sr[i];g?(Je=g[0],q=g[1],W=g[2],be=g[3],je=g[4],Ke=g[5],Xe=g[6],Ye=g[7],Ze=g[8]):(S=cr[kt],w=cr[kt+1],L=cr[kt+2],k=cr[kt+3],H=S*S+w*w+L*L+k*k,H>0?(z=1/Math.sqrt(H),q=S*z,W=w*z,be=L*z,je=k*z):(q=W=be=0,je=1),S=cr[Gt],w=cr[Gt+1],L=cr[Gt+2],k=cr[Gt+3],H=S*S+w*w+L*L+k*k,H>0?(z=1/Math.sqrt(H),Ke=S*z,Xe=w*z,Ye=L*z,Ze=k*z):(Ke=Xe=Ye=0,Ze=1),Je=q*Ke+W*Xe+be*Ye+je*Ze,Je<0&&(Je=-Je,Ke=-Ke,Xe=-Xe,Ye=-Ye,Ze=-Ze),g=new Float32Array(9),g[0]=Je,g[1]=q,g[2]=W,g[3]=be,g[4]=je,g[5]=Ke,g[6]=Xe,g[7]=Ye,g[8]=Ze,sr[i]=g),1-Je>y?(Qe=Math.acos(Je),et=Math.sin(Qe),tt=Math.sin((1-tr)*Qe)/et,it=Math.sin(tr*Qe)/et):(tt=1-tr,it=tr),S=tt*q+it*Ke,w=tt*W+it*Xe,L=tt*be+it*Ye,k=tt*je+it*Ze}ft=S+S,pt=w+w,xt=L+L,vt=S*ft,yt=S*pt,bt=S*xt,St=w*pt,wt=w*xt,Mt=L*xt,Pt=k*ft,Rt=k*pt,Ct=k*xt,Et=bt+Rt,Bt=1-(St+Mt),Dt=yt-Ct,At=wt-Pt,Ut=1-(vt+St),Lt=wt+Pt,It=1-(vt+Mt),w=Math.asin(Math.max(-1,Math.min(1,Et))),Math.abs(Et)<.99999?(S=Math.atan2(-At,Ut),L=Math.atan2(-Dt,Bt)):(S=Math.atan2(Lt,It),L=0),v.rotationX=S*b,v.rotationY=w*b,v.rotationZ=L*b}break;case"translation":"CUBICSPLINE"===Sr?ur!==hr-1&&(kt=9*ur,Ot=cr[kt+3],Vt=cr[kt+4],Nt=cr[kt+5],Xt=cr[kt+6],qt=cr[kt+7],Yt=cr[kt+8],Gt=9*or,$t=cr[Gt],jt=cr[Gt+1],Kt=cr[Gt+2],Ft=cr[Gt+3],Ht=cr[Gt+4],zt=cr[Gt+5],Wt=Xt*tr,Zt=$t*tr,v.x=vr*Ft+_r*Wt+yr*Ot+br*Zt,Wt=qt*tr,Zt=jt*tr,v.y=vr*Ht+_r*Wt+yr*Vt+br*Zt,Wt=Yt*tr,Zt=Kt*tr,v.z=vr*zt+_r*Wt+yr*Nt+br*Zt):(kt=3*or,Ot=cr[kt],Vt=cr[kt+1],Nt=cr[kt+2],Gt=3*ur,Ft=cr[Gt],Ht=cr[Gt+1],zt=cr[Gt+2],v.x=Ft+tr*(Ot-Ft),v.y=Ht+tr*(Vt-Ht),v.z=zt+tr*(Nt-zt));break;case"scale":"CUBICSPLINE"===Sr?ur!==hr-1&&(kt=9*ur,Ot=cr[kt+3],Vt=cr[kt+4],Nt=cr[kt+5],Xt=cr[kt+6],qt=cr[kt+7],Yt=cr[kt+8],Gt=9*or,$t=cr[Gt],jt=cr[Gt+1],Kt=cr[Gt+2],Ft=cr[Gt+3],Ht=cr[Gt+4],zt=cr[Gt+5],Wt=Xt*tr,Zt=$t*tr,v.scaleX=vr*Ft+_r*Wt+yr*Ot+br*Zt,Wt=qt*tr,Zt=jt*tr,v.scaleY=vr*Ht+_r*Wt+yr*Vt+br*Zt,Wt=Yt*tr,Zt=Kt*tr,v.scaleZ=vr*zt+_r*Wt+yr*Nt+br*Zt):(kt=3*or,Ot=cr[kt],Vt=cr[kt+1],Nt=cr[kt+2],Gt=3*ur,Ft=cr[Gt],Ht=cr[Gt+1],zt=cr[Gt+2],v.scaleX=Ft+tr*(Ot-Ft),v.scaleY=Ht+tr*(Vt-Ht),v.scaleZ=zt+tr*(Nt-zt));break;case"weights":{let g=dr.length;for(;g--;)ar.renderWeight(i,x,dr[g],tr,ur,or);break}}}}}}var so="struct Uniforms{backgroundColor:vec4}@group(1)@binding(0)var _sampler:sampler;@group(1)@binding(1)var _texture:texture_2d;@group(1)@binding(2)varuniforms:Uniforms;@fragment fn main(@location(0)fragUV:vec2)->@location(0)vec4{var viewColor:vec4=textureSample(_texture,_sampler,fragUV);let backgroundColor=uniforms.backgroundColor;let blendedColor=vec4(viewColor.rgb+backgroundColor.rgb*(1.0-viewColor.a),viewColor.a+backgroundColor.a*(1.0-viewColor.a));return blendedColor;}",oo="struct VertexUniforms{modelMatrix:mat4x4,};@group(0)@binding(0)varvertexUniforms:VertexUniforms;struct VertexOutput{@builtin(position)Position:vec4,@location(0)fragUV:vec2,};@vertex fn main(@builtin(vertex_index)VertexIndex:u32)->VertexOutput{var pos=array,6>(vec2(1.0,1.0),vec2(1.0,-1.0),vec2(-1.0,-1.0),vec2(1.0,1.0),vec2(-1.0,-1.0),vec2(-1.0,1.0),);var uv=array,6>(vec2(1.0,.0),vec2(1.0,1.0),vec2(.0,1.0),vec2(1.0,.0),vec2(.0,1.0),vec2(.0,.0),);var output:VertexOutput;output.Position=vertexUniforms.modelMatrix*vec4(pos[VertexIndex],.0,1.0);output.fragUV=uv[VertexIndex];return output;}";const uo=parseWGSL("FINAL_RENDER_VERTEX",oo),lo=parseWGSL("FINAL_RENDER_FRAGMENT",so),co=uo.uniforms.vertexUniforms;class FinalRender{#Dx=[];#Ex=[];#Ix;#Ax;#Lx;#Ux;#kx;#Gx=[];#U;#ne;#Ox=[];#Vx=[];#ls;constructor(){}render(i,g){const{sizeManager:x,antialiasingManager:v,commandEncoderManager:_}=i,{msaaID:y}=v,{pixelRectObject:b}=x,{width:S,height:w}=b;if(0===S||0===w)return;const L=this.#ls!==y,k=this.#Nx(i);_.addMainRenderPass(k,x=>{x.setViewport(0,0,S,w,0,1),x.setScissorRect(0,0,S,w),this.#Ix&&!L||(this.#Fx(i),this.#Gx=[]),this.#Hx(i,x,g.map(i=>{const g=i.colorAttachments[0];return g.postEffectView||g.pickingView||g.resolveTarget||g.view}),S,w,L)}),this.#ls=y}#zx(i,g){{const{scene:x,redGPUContext:v}=i,{gpuDevice:_}=v,{backgroundColor:y,useBackgroundColor:b}=x,S=b?y.rgbaNormal:[0,0,0,0],w=v.backgroundColor.rgbaNormal;let L;const k=[S[0]*S[3],S[1]*S[3],S[2]*S[3],S[3]],H=[w[0]*w[3],w[1]*w[3],w[2]*w[3],w[3]];L=[k[0]+H[0]*(1-S[3]),k[1]+H[1]*(1-S[3]),k[2]+H[2]*(1-S[3]),S[3]+w[3]*(1-S[3])],this.#Vx[g][0]=L[0],this.#Vx[g][1]=L[1],this.#Vx[g][2]=L[2],this.#Vx[g][3]=L[3],_.queue.writeBuffer(this.#Ox[g],0,this.#Vx[g])}}#Hx(i,g,x,v,_,y){const{gpuDevice:b}=i;x.forEach((x,S)=>{const w=i.viewList[S],{x:L,y:k,width:H,height:z}=w.pixelRectObject,q=create$4();Dt(q,0,1,0,1,-1e3,1e3),scale$4(q,q,[1/v,1/_,1]),translate(q,q,[H/2+L,_-z/2-k,0]),scale$4(q,q,[H/2,z/2,1]),this.#$x(i,S);const W=this.#Dx[S],be=this.#Ex[S];b.queue.writeBuffer(W.gpuBuffer,co.members.modelMatrix.uniformOffset,q),this.#Gx[S]&&!y||(this.#Gx[S]=null,this.#Gx[S]=new WeakMap);let je=this.#Gx[S].get(x);if(!je){const i={layout:this.#Ux,label:"FRAGMENT_BIND_GROUP_DESCRIPTOR_FINAL_RENDER",entries:[{binding:0,resource:this.#ne.gpuSampler},{binding:1,resource:x},{binding:2,resource:{buffer:this.#Ox[S],offset:0,size:this.#Ox[S].size}}]};je=b.createBindGroup(i),this.#Gx[S].set(x,je)}this.#zx(w,S),g.setPipeline(this.#jx(i,y)),g.setBindGroup(0,be),g.setBindGroup(1,je),g.draw(6,1,0,0)})}#Fx(i){const{resourceManager:g}=i;this.#Ix=g.createBindGroupLayout("FINAL_RENDER_VERTEX_BIND_GROUP_LAYOUT",getVertexBindGroupLayoutDescriptorFromShaderInfo(uo,0)),this.#Ax=g.createGPUShaderModule("VERTEX_MODULE_FINAL_RENDER",{code:oo}),this.#Lx={module:this.#Ax,entryPoint:"main"},this.#kx=g.createGPUShaderModule("FRAGMENT_MODULE_FINAL_RENDER",{code:so}),this.#Ux=g.createBindGroupLayout("FINAL_RENDER_BIND_GROUP_LAYOUT",getFragmentBindGroupLayoutDescriptorFromShaderInfo(lo,1)),this.#ne=new Sampler(i,{minFilter:"linear"})}#$x(i,g){const{gpuDevice:x}=i;if(!this.#Dx[g]){const v=new ArrayBuffer(co.arrayBufferByteLength),_=this.#Dx[g]=new UniformBuffer(i,v,`FinalRender_View(${g})_VertexUniform`),y={layout:this.#Ix,label:"VERTEX_BIND_GROUP_DESCRIPTOR_FINAL_RENDER",entries:[{binding:0,resource:{buffer:_.gpuBuffer,offset:0,size:_.size}}]};this.#Ex[g]=x.createBindGroup(y)}this.#Ox[g]||(this.#Ox[g]=i.gpuDevice.createBuffer({label:`FINAL_RENDER_FRAGMENT_BUFFER_${g}`,size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.#Vx[g]=new Float32Array([1,0,0,1]))}#Nx(i){const{gpuContext:g}=i;return{colorAttachments:[{view:g.getCurrentTexture().createView({label:"FINAL_RENDER"}),clearValue:{r:0,g:0,b:0,a:0},loadOp:z.CLEAR,storeOp:q.STORE}]}}#jx(i,g){if(!this.#U||g){const{gpuDevice:g}=i,x={label:"PIPELINE_DESCRIPTOR_FINAL_RENDER",layout:g.createPipelineLayout({label:"FINAL_RENDER_PIPELINE_LAYOUT",bindGroupLayouts:[this.#Ix,this.#Ux]}),vertex:this.#Lx,fragment:{module:this.#kx,entryPoint:"main",targets:[{format:navigator.gpu.getPreferredCanvasFormat(),blend:{color:{srcFactor:ui.SRC_ALPHA,dstFactor:ui.ONE_MINUS_SRC_ALPHA,operation:li.ADD},alpha:{srcFactor:ui.SRC_ALPHA,dstFactor:ui.ONE_MINUS_SRC_ALPHA,operation:li.ADD}}}]}};this.#U=g.createRenderPipeline(x)}return this.#U}}const haltonSequence=(i,g)=>{let x=0,v=1,_=i;for(;_>0;)v/=g,x+=v*(_%g),_=Math.floor(_/g);return x};class Renderer{#Kx;#Xx=new GltfAnimationLooperManager;constructor(){}start(i,g){cancelAnimationFrame(i.currentRequestAnimationFrame);const HD_render=x=>{g?.(x),i.currentTime=x,this.renderFrame(i,x),i.currentRequestAnimationFrame=requestAnimationFrame(HD_render)};i.currentRequestAnimationFrame=requestAnimationFrame(HD_render)}stop(i){cancelAnimationFrame(i.currentRequestAnimationFrame),i.currentRequestAnimationFrame=null}renderFrame(i,g){this.#Kx||(this.#Kx=new FinalRender);const x=[];{let g=0;const v=i.viewList.length;for(;g{const _=i.viewList[v];_.pickingManager?.checkEvents(_,g),_.postEffectManager.autoExposure.resolveReadback()})}renderView(i){const{redGPUContext:g,camera:x,pickingManager:v,pixelRectObject:_,renderViewStateData:y}=i,{colorAttachment:b,depthStencilAttachment:S,gBufferNormalTextureAttachment:w,gBufferMotionVectorTextureAttachment:L}=this.#qx(i),k={label:`${i.name} Basic Render Pass`,colorAttachments:[b,w,L],depthStencilAttachment:S};if(i.renderViewStateData.reset(),_.width&&_.height){const{scene:_}=i,{lightManager:b,shadowManager:w}=_;(b.pointLightCount||b.spotLightCount)&&i.clusterLightManager.updateClusterLights();DrawBufferManager.getInstance(g).flushAllCommands(y);if(y.numFixedSteps>0){const{scene:g}=i;if(g.physicsEngine){let i=y.numFixedSteps;for(;i--;)g.physicsEngine.step(y.fixedStepDeltaTime)}}x.update?.(i,g.currentTime),(i=>{const{taa:g}=i,x=g.frameIndex||0,v=g.jitterStrength,_=x%16,y=(haltonSequence(_+1,2)-.5)/1*v,b=(haltonSequence(_+1,3)-.5)/1*v;i.setJitterOffset(y,b)})(i),i.update(!0,!1,null),w.render(i);const L=i.viewRenderTextureManager.getGBufferTextureView(Ri.RENDER_PATH1_RESULT);i.update(!1,!0,L),this.#Yx(i,k),this.#Wx(i,k,S),v.render(i)}return k.colorAttachments[0].postEffectView=i.postEffectManager.render().textureView,((i,g,x)=>{const{animationList:v,skinList:_}=g,y=_.length,b=v.length;if(!y&&!b)return;const{gpuDevice:S,commandEncoderManager:w}=i;w.addPreProcessComputePass("ProcessAnimationsAndSkinning_ComputePass",w=>{b&&x.render(i,g.timestamp,w,v.flat());for(let g=0;g{updateViewportAndScissor(i,g,"DEFAULT"),x.currentRenderPassEncoder=g,v&&v.render(x),_&&_.renderBackground(x),b&&b.render(x),((i,g)=>{const{renderViewStateData:x,scene:v}=i;x.currentRenderPassEncoder=g;const{children:_}=v;let y=0;const b=_.length;for(;y{const{renderViewStateData:x,rawCamera:v}=i;x.currentRenderPassEncoder=g;const{bundleListAlphaLayer:_,bundleListTransparentLayer:y,bundleListParticleLayer:b}=x.renderBundleResults;_.length&&g.executeBundles(_);const{x:S,y:w,z:L}=v;y.length&&g.executeBundles(sortTransparentObjects({x:S,y:w,z:L},y)),b.length&&g.executeBundles(b)})(i,g)})}#Wx(i,g,x){const{redGPUContext:v,renderViewStateData:_}=i,{antialiasingManager:y,commandEncoderManager:b}=v,{useMSAA:S}=y;if(i.renderViewStateData.renderBundleResults.bundleListRender2PathLayer.length){const{mipmapGenerator:y}=v.resourceManager;let w=i.viewRenderTextureManager.getGBufferTexture(Ri.RENDER_PATH1_RESULT),L=S?i.viewRenderTextureManager.getGBufferResolveTexture(Ri.COLOR):i.viewRenderTextureManager.getGBufferTexture(Ri.COLOR);L||(S?console.error("MSAA가 활성화되어 있지만 G-Buffer Color Resolve 텍스처가 정의되지 않았습니다"):console.error("G-Buffer Color 텍스처가 정의되지 않았습니다")),b.useEncoder(k.MAIN,g=>{g.copyTextureToTexture({texture:L},{texture:w},{width:i.pixelRectObject.width,height:i.pixelRectObject.height,depthOrArrayLayers:1})}),y.generateMipmap(w,i.viewRenderTextureManager.renderPath1ResultTextureDescriptor,!0,k.MAIN),b.addMainRenderPass({label:`${i.name} 2Path Render Pass`,colorAttachments:[...g.colorAttachments].map(i=>({...i,loadOp:z.LOAD})),depthStencilAttachment:{...x,depthLoadOp:z.LOAD}},g=>{updateViewportAndScissor(i,g),g.executeBundles(_.renderBundleResults.bundleListRender2PathLayer)})}}#qx(i){const{redGPUContext:g,viewRenderTextureManager:x}=i,{antialiasingManager:v}=g,{useMSAA:_}=v,y=x.depthTextureView,b=x.getGBufferTextureView(Ri.COLOR),S=x.getGBufferTextureView(Ri.NORMAL),w=x.getGBufferTextureView(Ri.MOTION_VECTOR),L={view:b,clearValue:{r:0,g:0,b:0,a:0},loadOp:z.CLEAR,storeOp:q.STORE},k={view:y,depthClearValue:1,depthLoadOp:z.CLEAR,depthStoreOp:q.STORE},H={view:S,clearValue:{r:0,g:0,b:0,a:0},loadOp:z.CLEAR,storeOp:q.STORE},W={view:w,clearValue:{r:0,g:0,b:0,a:0},loadOp:z.CLEAR,storeOp:q.STORE};return _&&(L.resolveTarget=x.getGBufferResolveTextureView(Ri.COLOR),H.resolveTarget=x.getGBufferResolveTextureView(Ri.NORMAL),W.resolveTarget=x.getGBufferResolveTextureView(Ri.MOTION_VECTOR)),{colorAttachment:L,depthStencilAttachment:k,gBufferNormalTextureAttachment:H,gBufferMotionVectorTextureAttachment:W}}}var ho=Object.freeze({__proto__:null,isHexColor:isHexColor,isUint:isUint,validateNumber:validateNumber,validateNumberRange:validateNumberRange,validatePositiveNumberRange:validatePositiveNumberRange,validateRedGPUContext:validateRedGPUContext,validateUintRange:validateUintRange});class BrightnessContrast extends ASinglePassPostEffect{constructor(i){super(i),this.isLdr=!0,this.init(i,"POST_EFFECT_BRIGHTNESS_CONTRAST",createBasicPostEffectCode(this,"let index=global_id.xy;var color:vec4=textureLoad(sourceTexture,index,0);let brightness_value:f32=uniforms.brightness/255.0;let contrast_value:f32=uniforms.contrast/255.0;var tempColor:vec3;if(contrast_value>.0){tempColor=(color.rgb-0.5)/(1.0-contrast_value)+0.5;}else{tempColor=(color.rgb-0.5)*(1.0+contrast_value)+0.5;}color=vec4(tempColor+brightness_value,color.a);textureStore(outputTexture,index,color);","struct Uniforms{brightness:f32,contrast:f32};"))}}defineNumber(BrightnessContrast,[{key:"brightness",value:0,min:-150,max:150},{key:"contrast",value:0,min:-50,max:100}]),Object.freeze(BrightnessContrast);class ColorBalance extends ASinglePassPostEffect{constructor(i){super(i),this.isLdr=!0,this.init(i,"POST_EFFECT_COLOR_BALANCE",createBasicPostEffectCode(this,"let index=global_id.xy;var color:vec4=textureLoad(sourceTexture,index,0);let original_luminance=getLuminance(color.rgb);let shadow_weight=1.0-smoothstep(.0,0.5,original_luminance);let highlight_weight=smoothstep(0.5,1.0,original_luminance);let midtone_weight=1.0-shadow_weight-highlight_weight;let cyan_red=shadow_weight*uniforms.shadowCyanRed+midtone_weight*uniforms.midtoneCyanRed+highlight_weight*uniforms.highlightCyanRed;let magenta_green=shadow_weight*uniforms.shadowMagentaGreen+midtone_weight*uniforms.midtoneMagentaGreen+highlight_weight*uniforms.highlightMagentaGreen;let yellow_blue=shadow_weight*uniforms.shadowYellowBlue+midtone_weight*uniforms.midtoneYellowBlue+highlight_weight*uniforms.highlightYellowBlue;color.r+=cyan_red*.01;color.g+=magenta_green*.01;color.b+=yellow_blue*.01;let adjusted_luminance=getLuminance(color.rgb);if(uniforms.preserveLuminosity==1u&&adjusted_luminance>.0){let ratio=original_luminance/adjusted_luminance;color=vec4(color.rgb*ratio,color.a);}textureStore(outputTexture,index,color);","#redgpu_include color.getLuminance struct Uniforms{shadowCyanRed:f32,shadowMagentaGreen:f32,shadowYellowBlue:f32,midtoneCyanRed:f32,midtoneMagentaGreen:f32,midtoneYellowBlue:f32,highlightCyanRed:f32,highlightMagentaGreen:f32,highlightYellowBlue:f32,preserveLuminosity:u32};"))}}defineBoolean(ColorBalance,[{key:"preserveLuminosity",value:!0}]),defineNumber(ColorBalance,[{key:"highlightYellowBlue",value:0,min:-100,max:100},{key:"highlightMagentaGreen",value:0,min:-100,max:100},{key:"highlightCyanRed",value:0,min:-100,max:100},{key:"midtoneYellowBlue",value:0,min:-100,max:100},{key:"midtoneMagentaGreen",value:0,min:-100,max:100},{key:"midtoneCyanRed",value:0,min:-100,max:100},{key:"shadowYellowBlue",value:0,min:-100,max:100},{key:"shadowMagentaGreen",value:0,min:-100,max:100},{key:"shadowCyanRed",value:0,min:-100,max:100}]),Object.freeze(ColorBalance);class ColorTemperatureTint extends ASinglePassPostEffect{constructor(i){super(i),this.isLdr=!0,this.init(i,"POST_EFFECT_COLOR_TEMPERATURE_TINT",createBasicPostEffectCode(this,"let index=global_id.xy;var color:vec4=textureLoad(sourceTexture,index,0);let temp=uniforms.temperature;var tempRGB:vec3;if(temp<=6600.0){tempRGB.r=1.0;}else{let t=temp-6600.0;tempRGB.r=clamp(1.292936*pow(t,-0.1332047),.0,1.0);}if(temp<=6600.0){let t=temp;tempRGB.g=clamp(0.39008157*log(t)-0.63184144,.0,1.0);}else{let t=temp-6600.0;tempRGB.g=clamp(1.292936*pow(t,-0.1332047),.0,1.0);}if(temp>=6600.0){tempRGB.b=1.0;}else if(temp<=1900.0){tempRGB.b=.0;}else{let t=temp-1000.0;tempRGB.b=clamp(0.543206789*log(t)-1.19625408,.0,1.0);}let neutralTemp:vec3=vec3(1.0,1.0,1.0);let tempAdjust:vec3=tempRGB/neutralTemp;let tintValue=uniforms.tint*.01;var tintRGB:vec3;if(tintValue>=.0){tintRGB=vec3(1.0-tintValue*0.2,1.0,1.0-tintValue*0.2);}else{let mag=-tintValue;tintRGB=vec3(1.0,1.0-mag*0.2,1.0);}let colorAdjust=tempAdjust*tintRGB;let finalAdjust=mix(vec3(1.0),colorAdjust,uniforms.amount);color=vec4(color.rgb*finalAdjust,color.a);color=vec4(clamp(color.rgb,vec3(.0),vec3(1.0)),color.a);textureStore(outputTexture,index,color);","struct Uniforms{temperature:f32,tint:f32,amount:f32};")),this.temperature=6500,this.amount=1,this.tint=0}setWarmTone(){this.temperature=3200,this.tint=-10}setCoolTone(){this.temperature=8e3,this.tint=10}setNeutral(){this.temperature=6500,this.tint=0}setCandleLight(){this.temperature=1900,this.tint=-5}setDaylight(){this.temperature=5600,this.tint=0}setCloudyDay(){this.temperature=7500,this.tint=5}setNeonLight(){this.temperature=9e3,this.tint=15}}definePositiveNumber(ColorTemperatureTint,[{key:"temperature",value:6500,min:1e3,max:2e4},{key:"amount",value:1,min:0,max:1}]),defineNumber(ColorTemperatureTint,[{key:"tint",value:0,min:-100,max:100}]),Object.freeze(ColorTemperatureTint);class Grayscale extends ASinglePassPostEffect{constructor(i){super(i),this.isLdr=!0,this.init(i,"POST_EFFECT_GRAYSCALE",createBasicPostEffectCode(this,"let index=vec2(global_id.xy);var color:vec4=textureLoad(sourceTexture,index,0);let gray=getLuminance(color.rgb);let finalColor=mix(color,vec4(gray,gray,gray,color.a),uniforms.amount);textureStore(outputTexture,index,finalColor);","#redgpu_include color.getLuminance struct Uniforms{amount:f32};"))}}definePositiveNumber(Grayscale,[{key:"amount",value:1,min:0,max:1}]),Object.freeze(Grayscale);class HueSaturation extends ASinglePassPostEffect{constructor(i){super(i),this.isLdr=!0,this.init(i,"POST_EFFECT_HUE_SATURATION",createBasicPostEffectCode(this,"let index=global_id.xy;var color:vec4=textureLoad(sourceTexture,index,0);let hue_value:f32=uniforms.hue/180.0;let angle:f32=hue_value*PI;let s:f32=sin(angle);let c:f32=cos(angle);var weights:vec3=(vec3(2.0*c,-sqrt(3.0)*s-c,sqrt(3.0)*s-c)+1.0)/3.0;color=vec4(vec3(dot(color.rgb,weights.xyz),dot(color.rgb,weights.zxy),dot(color.rgb,weights.yzx)),color.a);let saturation_value:f32=uniforms.saturation/100.0;let luminance=getLuminance(color.rgb);if(saturation_value>.0){color=vec4(color.rgb+(luminance-color.rgb)*(1.0-1.0/(1.001-saturation_value)),color.a);}else{color=vec4(color.rgb+(luminance-color.rgb)*(-saturation_value),color.a);}textureStore(outputTexture,index,color);","#redgpu_include math.PI #redgpu_include color.getLuminance struct Uniforms{hue:f32,saturation:f32};"))}}defineNumber(HueSaturation,[{key:"hue",value:0,min:-180,max:180},{key:"saturation",value:0,min:-100,max:100}]),Object.freeze(HueSaturation);class Invert extends ASinglePassPostEffect{constructor(i){super(i),this.isLdr=!0,this.init(i,"POST_EFFECT_INVERT",createBasicPostEffectCode(this,"let index=vec2(global_id.xy);var color:vec4=textureLoad(sourceTexture,index,0);let invertedRGB=1.0-color.rgb;let finalColor=vec4(mix(color.rgb,invertedRGB,uniforms.amount),color.a);textureStore(outputTexture,index,finalColor);","struct Uniforms{amount:f32};"))}}definePositiveNumber(Invert,[{key:"amount",value:1,min:0,max:1}]),Object.freeze(Invert);class Threshold extends ASinglePassPostEffect{constructor(i){super(i),this.isLdr=!0,this.init(i,"POST_EFFECT_THRESHOLD",createBasicPostEffectCode(this,"let index=global_id.xy;var color:vec4=textureLoad(sourceTexture,index,0);let threshold_value:f32=uniforms.threshold/255.0;var v=.0;if(getLuminance(color.rgb)>=threshold_value){v=1.0;}color=vec4(v,v,v,color.a);textureStore(outputTexture,index,color);","#redgpu_include color.getLuminance struct Uniforms{threshold:f32};"))}}definePositiveNumber(Threshold,[{key:"threshold",value:128,min:1,max:255}]),Object.freeze(Threshold);class Vibrance extends ASinglePassPostEffect{constructor(i){super(i),this.isLdr=!0,this.init(i,"POST_EFFECT_VIBRANCE",createBasicPostEffectCode(this,"let index=global_id.xy;var color:vec4=textureLoad(sourceTexture,index,0);let originalColor=color;let luminance=getLuminance(color.rgb);if(uniforms.saturation !=.0){let saturationFactor=1.0+uniforms.saturation*.01;color=vec4(mix(luminance,color.r,saturationFactor),mix(luminance,color.g,saturationFactor),mix(luminance,color.b,saturationFactor),color.a);}if(uniforms.vibrance !=.0){let maxComponent=max(max(color.r,color.g),color.b);let minComponent=min(min(color.r,color.g),color.b);let currentSaturation=maxComponent-minComponent;let protectionFactor=1.0/(1.0+exp(6.0*(currentSaturation-0.6)));var skinToneProtection=1.0;if(color.r>color.g&&color.g>color.b){let skinToneAmount=(color.r-color.b)/max(color.r,.001);skinToneProtection=1.0-smoothstep(0.3,0.8,skinToneAmount)*0.7;}let finalProtection=protectionFactor*skinToneProtection;let vibranceStrength=uniforms.vibrance*.01*finalProtection;let vibranceFactor=1.0+vibranceStrength;color=vec4(mix(luminance,color.r,vibranceFactor),mix(luminance,color.g,vibranceFactor),mix(luminance,color.b,vibranceFactor),color.a);}color=clamp(color,vec4(.0),vec4(1.0));textureStore(outputTexture,index,color);","#redgpu_include color.getLuminance struct Uniforms{vibrance:f32,saturation:f32};"))}}defineNumber(Vibrance,[{key:"vibrance",value:0,min:-100,max:100},{key:"saturation",value:0,min:-100,max:100}]),Object.freeze(Vibrance);const fo=[0,0,0,0,0,1,0,0,0,0,0,0],mo=[0,-1,0,0,-1,5,-1,0,0,-1,0,0],po=[1,1,1,0,1,1,1,0,1,1,1,0],go=[0,1,0,0,1,-4,1,0,0,1,0,0],xo=[-2,-1,0,0,-1,1,1,0,0,1,2,0];class Convolution extends ASinglePassPostEffect{static NORMAL=fo;static SHARPEN=mo;static BLUR=po;static EDGE=go;static EMBOSS=xo;#Zx=go;constructor(i){super(i),this.isLdr=!0,this.init(i,"POST_EFFECT_CONVOLUTION",createBasicPostEffectCode(this,"let index=vec2(global_id.xy);var color:vec4=vec4(.0);let kernelWeight_value:f32=uniforms.kernelWeight;let kernel_value:mat3x3=uniforms.kernel;color+=textureLoad(sourceTexture,index+vec2(-1,-1),0)*kernel_value[0][0];color+=textureLoad(sourceTexture,index+vec2(0,-1),0)*kernel_value[0][1];color+=textureLoad(sourceTexture,index+vec2(1,-1),0)*kernel_value[0][2];color+=textureLoad(sourceTexture,index+vec2(-1,0),0)*kernel_value[1][0];color+=textureLoad(sourceTexture,index+vec2(0,0),0)*kernel_value[1][1];color+=textureLoad(sourceTexture,index+vec2(1,0),0)*kernel_value[1][2];color+=textureLoad(sourceTexture,index+vec2(-1,1),0)*kernel_value[2][0];color+=textureLoad(sourceTexture,index+vec2(0,1),0)*kernel_value[2][1];color+=textureLoad(sourceTexture,index+vec2(1,1),0)*kernel_value[2][2];textureStore(outputTexture,index,color/kernelWeight_value);","struct Uniforms{kernelWeight:f32,kernel:mat3x3};"))}get kernel(){return this.#Zx}set kernel(i){this.#Zx=i;let g=0;this.#Zx.forEach(i=>g+=i),this.updateUniform("kernelWeight",g||1),this.updateUniform("kernel",i)}}Object.freeze(Convolution);class Blur extends AMultiPassPostEffect{#Jx;constructor(i){super(i,[new Convolution(i)]),this.#Jx=this.passList[0],this.#Jx.kernel=Convolution.BLUR}render(i,g,x,v){return this.#Jx.render(i,g,x,v)}}Object.freeze(Blur);class DirectionalBlur extends ASinglePassPostEffect{#Qx=0;constructor(i){super(i),this.init(i,"POST_EFFECT_DIRECTIONAL_BLUR",createBasicPostEffectCode(this,"let index=vec2(global_id.xy);let dimensions=vec2(textureDimensions(sourceTexture));if(f32(index.x)>=dimensions.x||f32(index.y)>=dimensions.y){return;}let invSize=1.0/dimensions;let centerUV=(vec2(index)+0.5)*invSize;let direction=vec2(uniforms.directionX,uniforms.directionY);let dirLength=length(direction);let normalizedDir=select(vec2(.0),direction/dirLength,dirLength>.0);let dir=normalizedDir*(uniforms.amount*systemUniforms.devicePixelRatio)*invSize;var sum=vec4(.0);var totalWeight=.0;let steps=uniforms.sampleCount;for(var i=-steps;i<=steps;i+=1.0){let t=i/steps;let weight=exp(-0.5*pow(t*2.0,2.0));let sampleUV=centerUV+dir*t;sum+=textureSampleLevel(sourceTexture,basicSampler,sampleUV,.0)*weight;totalWeight+=weight;}textureStore(outputTexture,index,sum/totalWeight);","struct Uniforms{amount:f32,directionX:f32,directionY:f32,sampleCount:f32,};"))}get angle(){return this.#Qx}set angle(i){validateNumber(i),this.#Qx=i%360,this.#ev()}#ev(){const i=this.#Qx*Math.PI/180,g=Math.cos(i),x=Math.sin(i);this.updateUniform("directionX",g),this.updateUniform("directionY",x)}}definePositiveNumber(DirectionalBlur,[{key:"amount",value:15}]),defineUint(DirectionalBlur,[{key:"sampleCount",value:30,min:1,max:100}]),Object.freeze(DirectionalBlur);class RadialBlur extends ASinglePassPostEffect{constructor(i){super(i),this.init(i,"POST_EFFECT_RADIAL_BLUR",createBasicPostEffectCode(this,"let index=global_id.xy;let dimensions=vec2(textureDimensions(sourceTexture));if(f32(index.x)>=dimensions.x||f32(index.y)>=dimensions.y){return;}let invSize=1.0/dimensions;let centerUV=(vec2(index)+0.5)*invSize;let center=vec2(0.5)+vec2(uniforms.centerX,uniforms.centerY)*systemUniforms.devicePixelRatio*invSize;let toPixel=centerUV-center;let distance=length(toPixel);let angle=atan2(toPixel.y,toPixel.x);let rotationAngle=uniforms.amount*distance*.005;let sampleCount=i32(uniforms.sampleCount);var sum=vec4(.0);var totalWeight=.0;for(var i=0;i(cos(sampleAngle)*distance,sin(sampleAngle)*distance);let weight=1.0-abs(t-0.5)*1.5;sum+=textureSampleLevel(sourceTexture,basicSampler,sampleUV,.0)*max(weight,0.1);totalWeight+=weight;}let centerFalloff=smoothstep(.0,0.1,distance);let originalColor=textureSampleLevel(sourceTexture,basicSampler,centerUV,.0);let blurredColor=sum/totalWeight;textureStore(outputTexture,index,mix(originalColor,blurredColor,centerFalloff));","struct Uniforms{amount:f32,centerX:f32,centerY:f32,sampleCount:f32,};"))}}definePositiveNumber(RadialBlur,[{key:"amount",value:50}]),defineNumber(RadialBlur,[{key:"centerX",value:0},{key:"centerY",value:0}]),defineUint(RadialBlur,[{key:"sampleCount",value:16,min:2,max:100}]),Object.freeze(RadialBlur);class ZoomBlur extends ASinglePassPostEffect{constructor(i){super(i),this.init(i,"POST_EFFECT_ZOOM_BLUR",createBasicPostEffectCode(this,"let index=global_id.xy;let dimensions=vec2(textureDimensions(sourceTexture));if(f32(index.x)>=dimensions.x||f32(index.y)>=dimensions.y){return;}let invSize=1.0/dimensions;let centerUV=(vec2(index)+0.5)*invSize;let center=vec2(0.5)+vec2(uniforms.centerX,uniforms.centerY)*systemUniforms.devicePixelRatio*invSize;let dir=(center-centerUV)*(uniforms.amount*.01);var sum=vec4(.0);var totalWeight=.0;let steps=uniforms.sampleCount;for(var i=-steps;i<=steps;i+=1.0){let t=i/steps;let weight=1.0-abs(t);let sampleUV=centerUV+dir*t;sum+=textureSampleLevel(sourceTexture,basicSampler,sampleUV,.0)*weight;totalWeight+=weight;}textureStore(outputTexture,index,sum/totalWeight);","struct Uniforms{amount:f32,centerX:f32,centerY:f32,sampleCount:f32,};"))}}definePositiveNumber(ZoomBlur,[{key:"amount",value:10}]),defineNumber(ZoomBlur,[{key:"centerX",value:0},{key:"centerY",value:0}]),defineUint(ZoomBlur,[{key:"sampleCount",value:30,min:1,max:100}]),Object.freeze(ZoomBlur);const vo={filmGrainIntensity:.008,filmGrainResponse:1.5,filmGrainScale:1.2,coloredGrain:.05,grainSaturation:.1},_o={filmGrainIntensity:.015,filmGrainResponse:1.2,filmGrainScale:1.8,coloredGrain:.15,grainSaturation:.3},yo={filmGrainIntensity:.03,filmGrainResponse:1,filmGrainScale:2.5,coloredGrain:.25,grainSaturation:.5},bo={filmGrainIntensity:.06,filmGrainResponse:.7,filmGrainScale:4,coloredGrain:.6,grainSaturation:.8};class FilmGrain extends ASinglePassPostEffect{static SUBTLE=vo;static MEDIUM=_o;static HEAVY=yo;static VINTAGE=bo;constructor(i){super(i),this.isLdr=!0,this.init(i,"POST_EFFECT_FILM_GRAIN",createBasicPostEffectCode(this,"let index=vec2(global_id.xy);let dimensions:vec2=textureDimensions(sourceTexture);let originalColor=textureLoad(sourceTexture,index,0);let filmGrainIntensity_value:f32=uniforms.filmGrainIntensity;let filmGrainResponse_value:f32=uniforms.filmGrainResponse;let filmGrainScale_value:f32=uniforms.filmGrainScale;let coloredGrain_value:f32=uniforms.coloredGrain;let grainSaturation_value:f32=uniforms.grainSaturation;let frameIndex_value:u32=systemUniforms.time.frameIndex;if(filmGrainIntensity_value<=.0){textureStore(outputTexture,index,originalColor);return;}let baseScale=max(filmGrainScale_value,0.1)*systemUniforms.devicePixelRatio;let grainCoord=floor(vec2(global_id.xy)/baseScale);var grain=getFilmicGrain(grainCoord,frameIndex_value,coloredGrain_value);let grainLum=getLuminance(grain);grain=mix(vec3(grainLum),grain,grainSaturation_value);let sceneLuminance=getLuminance(originalColor.rgb);let responseMask=pow(1.0-sceneLuminance,filmGrainResponse_value);let finalMask=responseMask*smoothstep(.0,0.1,sceneLuminance);let intensity=filmGrainIntensity_value*max(.05,finalMask);let finalColor=originalColor.rgb+grain*intensity;let outputColor=vec4(saturate(finalColor),originalColor.a);textureStore(outputTexture,index,outputColor);","#redgpu_include color.getLuminance #redgpu_include math.hash.getHash1D_vec3 #redgpu_include math.getInterleavedGradientNoise struct Uniforms{filmGrainIntensity:f32,filmGrainResponse:f32,filmGrainScale:f32,coloredGrain:f32,grainSaturation:f32,};fn getFilmicGrain(coord:vec2,frameIndex:u32,coloredGrain:f32)->vec3{let fIndex=f32(frameIndex % 4096u);let frameSeed=fIndex*1.61803398875;let scrambledX=coord.x*12.9898+frameSeed;let scrambledY=coord.y*78.233+frameSeed;let n1=getHash1D_vec3(vec3(scrambledX,scrambledY,frameSeed));let n2=getHash1D_vec3(vec3(scrambledY,frameSeed,scrambledX));let n3=getHash1D_vec3(vec3(frameSeed,scrambledX,scrambledY));var noise=mix(vec3(n1),vec3(n1,n2,n3),coloredGrain);let ign=getInterleavedGradientNoise(coord+frameSeed);let finalNoise=mix(noise,vec3(ign),.02);return(finalNoise-0.5)*2.0;}"))}applyPreset(i){this.filmGrainIntensity=i.filmGrainIntensity,this.filmGrainResponse=i.filmGrainResponse,this.filmGrainScale=i.filmGrainScale,this.coloredGrain=i.coloredGrain,this.grainSaturation=i.grainSaturation}}definePositiveNumber(FilmGrain,[{key:"filmGrainIntensity",value:bo.filmGrainIntensity},{key:"filmGrainResponse",value:bo.filmGrainResponse},{key:"filmGrainScale",value:bo.filmGrainScale},{key:"coloredGrain",value:bo.coloredGrain},{key:"grainSaturation",value:bo.grainSaturation}]),Object.freeze(FilmGrain);class Fog extends ASinglePassPostEffect{static EXPONENTIAL=0;static EXPONENTIAL_SQUARED=1;constructor(i){super(i),this.init(i,"POST_EFFECT_FOG",createBasicPostEffectCode(this,"let id=global_id.xy;let coord=vec2(id);var sceneColor=textureLoad(sourceTexture,coord,0);let depth=textureLoad(depthTexture,coord,0);let linDepth=getLinearizeDepth(depth,systemUniforms.camera.nearClipping,systemUniforms.camera.farClipping);let u_density=uniforms.density;let u_near=uniforms.nearDistance;let u_far=uniforms.farDistance;let cameraFar=systemUniforms.camera.farClipping;var fogFactor:f32;if(linDepth>=(cameraFar*0.99)){fogFactor=1.0-u_density;}else{let dist=max(.0,linDepth-u_near);let maxDist=u_far-u_near;let normalizedDist=clamp(dist/max(0.1,maxDist),.0,1.0);if(uniforms.fogType==0u){fogFactor=exp(-u_density*normalizedDist*10.0);}else{let expVal=u_density*normalizedDist*5.0;fogFactor=exp(-(expVal*expVal));}}let finalColor=mix(uniforms.fogColor.rgb,sceneColor.rgb,saturate(fogFactor));textureStore(outputTexture,coord,vec4(finalColor,sceneColor.a));","#redgpu_include depth.getLinearizeDepth struct Uniforms{fogType:u32,density:f32,nearDistance:f32,farDistance:f32,fogColor:vec3,padding1:f32,};"))}}definePositiveNumber(Fog,[{key:"density",value:.5,min:0,max:1}]),defineNumber(Fog,[{key:"nearDistance",value:4.5,min:0},{key:"farDistance",value:50,min:.1}]),defineUint(Fog,[{key:"fogType",value:Fog.EXPONENTIAL,max:1}]),defineColorRGB(Fog,[{key:"fogColor",value:"#1b2866"}]),Object.freeze(Fog);class HeightFog extends ASinglePassPostEffect{static EXPONENTIAL=0;static EXPONENTIAL_SQUARED=1;constructor(i){super(i),this.init(i,"POST_EFFECT_HEIGHT_FOG",createBasicPostEffectCode(this,"let dimensions=textureDimensions(sourceTexture);let dimW=f32(dimensions.x);let dimH=f32(dimensions.y);let global_id_vec=vec2(global_id.xy);let screenCoord=(global_id_vec+0.5)/vec2(dimW,dimH);var depth:f32=1.0;if(dimensions.x>u32(global_id.x)&&dimensions.y>u32(global_id.y)){depth=textureLoad(depthTexture,vec2(global_id.xy),0);}let fogFactor=calculateHeightFogFactor(screenCoord,depth);let originalColor=textureLoad(sourceTexture,vec2(global_id.xy),0).rgb;let foggedColor=mix(uniforms.fogColor,originalColor,fogFactor);textureStore(outputTexture,vec2(global_id.xy),vec4(foggedColor,1.0));","#redgpu_include math.EPSILON #redgpu_include math.reconstruct.getWorldPositionFromDepth #redgpu_include math.direction.getRayDirection struct Uniforms{fogType:u32,density:f32,baseHeight:f32,thickness:f32,falloff:f32,fogColor:vec3,padding1:f32,padding2:f32,};fn isFiniteValue(value:f32)->bool{return value==value;}fn isFiniteVec3(v:vec3)->bool{return isFiniteValue(v.x)&&isFiniteValue(v.y)&&isFiniteValue(v.z);}fn reconstructWorldPositionUltraPrecise(screenCoord:vec2,depth:f32)->vec3{let worldPos=getWorldPositionFromDepth(screenCoord,depth,systemUniforms.projection.inverseProjectionViewMatrix);return select(vec3(.0),worldPos,isFiniteVec3(worldPos));}fn calculateHeightFogFactor(screenCoord:vec2,depth:f32)->f32{let backgroundThreshold=1.0-1e-5;let isBackground=depth>=backgroundThreshold;var pixelWorldHeight:f32;if(isBackground){let rayDirection=getRayDirectionMaxPrecision(screenCoord);pixelWorldHeight=getSkyboxHeightMaxPrecision(rayDirection);}else{let worldPos=reconstructWorldPositionUltraPrecise(screenCoord,depth);pixelWorldHeight=worldPos.y;}return calculateAbsoluteHeightFogMaxPrecision(pixelWorldHeight);}fn getSkyboxHeightMaxPrecision(rayDirection:vec3)->f32{let u_baseHeight=uniforms.baseHeight;let u_maxHeight=u_baseHeight+uniforms.thickness;let rayY=clamp(rayDirection.y,-0.999,0.999);let upThreshold=.08;let downThreshold=-.015;let transitionRange=upThreshold-downThreshold;let safeTransitionRange=max(transitionRange,EPSILON);if(rayY>upThreshold){return u_maxHeight+25.0;}else if(rayYf32{let u_baseHeight=uniforms.baseHeight;let u_maxHeight=u_baseHeight+uniforms.thickness;let u_density=uniforms.density;let u_falloff=uniforms.falloff;let u_fogType=uniforms.fogType;if(!isFiniteValue(worldHeight)){return 1.0;}let heightRange=u_maxHeight-u_baseHeight;let safeHeightRange=max(heightRange,1e-3);let margin=fma(safeHeightRange,0.18,1.2);let extendedBaseHeight=u_baseHeight-margin;let extendedMaxHeight=u_maxHeight+margin;let extendedRange=extendedMaxHeight-extendedBaseHeight;if(worldHeight<=extendedBaseHeight||worldHeight>=extendedMaxHeight){return 1.0;}let safeExtendedRange=max(extendedRange,1e-3);if(safeExtendedRange<=0.3){return 1.0;}let normalizedHeight=clamp((worldHeight-extendedBaseHeight)/safeExtendedRange,.0,1.0);let centerOffset=normalizedHeight-0.5;let edgeFactor=fma(-abs(centerOffset),0.25,1.0);let heightFactor=1.0-normalizedHeight;let safeHeightFactor=max(heightFactor,1e-4);let safeFalloff=clamp(u_falloff,.05,1.8);let expPower=fma(safeFalloff,0.73,1.05);var fogDensity:f32;if(u_fogType==0u){fogDensity=pow(safeHeightFactor,expPower);fogDensity=smoothstep(.0,1.0,fogDensity);}else{let expResult=pow(safeHeightFactor,expPower);fogDensity=expResult*expResult;fogDensity=smoothstep(.0,1.0,fogDensity);}let densityWithEdge=fogDensity*edgeFactor;let safeDensity=clamp(u_density,.0,4.0);let finalFogAmount=fma(densityWithEdge,safeDensity,.0)*0.42;let result=clamp(1.0-finalFogAmount,.0,1.0);return select(1.0,result,isFiniteValue(result));}fn getRayDirectionMaxPrecision(screenCoord:vec2)->vec3{let worldPos=getWorldPositionFromDepth(screenCoord,1.0,systemUniforms.projection.inverseProjectionViewMatrix);let rayDir=getRayDirection(worldPos,systemUniforms.camera.cameraPosition);return select(vec3(.0,.0,1.0),rayDir,isFiniteVec3(rayDir));}"))}}definePositiveNumber(HeightFog,[{key:"density",value:1,min:0,max:5},{key:"falloff",value:.1,min:.001,max:2},{key:"thickness",value:100,min:.1}]),defineNumber(HeightFog,[{key:"baseHeight",value:0}]),defineUint(HeightFog,[{key:"fogType",value:HeightFog.EXPONENTIAL,max:1}]),defineColorRGB(HeightFog,[{key:"fogColor",value:"#1b2866"}]),Object.freeze(HeightFog);class ChromaticAberration extends ASinglePassPostEffect{constructor(i){super(i),this.isLdr=!0,this.init(i,"POST_EFFECT_CHROMATIC_ABERRATION",createBasicPostEffectCode(this,"let index=global_id.xy;let dimensions=textureDimensions(sourceTexture);let dimW=f32(dimensions.x);let dimH=f32(dimensions.y);let uv=vec2(index)/vec2(dimW,dimH);let invSize=1.0/vec2(dimensions);let center=vec2(0.5)+vec2(uniforms.centerX,uniforms.centerY)*systemUniforms.devicePixelRatio*invSize;let offset=uv-center;let distance=length(offset);let distortion=uniforms.strength*pow(distance,uniforms.falloff);let redOffset=uv+offset*distortion*vec2(-1.0,-1.0);let greenOffset=uv;let blueOffset=uv+offset*distortion*vec2(1.0,1.0);var finalColor:vec3;finalColor.r=textureSampleLevel(sourceTexture,basicSampler,redOffset,.0).r;finalColor.g=textureSampleLevel(sourceTexture,basicSampler,greenOffset,.0).g;finalColor.b=textureSampleLevel(sourceTexture,basicSampler,blueOffset,.0).b;let originalAlpha=textureLoad(sourceTexture,index,0).a;textureStore(outputTexture,index,vec4(finalColor,originalAlpha));","struct Uniforms{strength:f32,centerX:f32,centerY:f32,falloff:f32};"))}}defineNumber(ChromaticAberration,[{key:"strength",value:.015,min:0},{key:"centerX",value:0},{key:"centerY",value:0},{key:"falloff",value:.5,min:0,max:5}]),Object.freeze(ChromaticAberration);class DOFCoC extends ASinglePassPostEffect{constructor(i){super(i),this.init(i,"POST_EFFECT_DOF_COC",createBasicPostEffectCode(this,"let index=vec2(global_id.xy);let coord=vec2(global_id.xy);let originalColor=textureLoad(sourceTexture,coord,0).xyzw;let depth=textureLoad(depthTexture,coord,0);let linearDepth=getLinearizeDepth(depth,uniforms.nearPlane,uniforms.farPlane);let coc=calculateCoC(linearDepth);let encodedCoC=encodeCoC(coc);textureStore(outputTexture,coord,vec4(originalColor.rgb,encodedCoC));","#redgpu_include depth.getLinearizeDepth struct Uniforms{focusDistance:f32,aperture:f32,maxCoC:f32,nearPlane:f32,farPlane:f32,};fn encodeCoC(coc:f32)->f32{return(coc+1.0)*0.5;}fn calculateCoC(linearDepth:f32)->f32{let subjectDistance=linearDepth;let focalLength=50.0;let focusRange=uniforms.focusDistance*0.15;let transitionRange=uniforms.focusDistance*0.35;let distanceFromFocus=abs(subjectDistance-uniforms.focusDistance);if(distanceFromFocus.05){signedCoC=-min(1.0,absCoC*smoothstep(.05,0.3,absCoC)*1.5);}if(distanceFromFocus0.1){signedCoC=min(1.0,absCoC*smoothstep(0.1,0.5,absCoC)*1.2);}if(distanceFromFocus=dimensions.x||index.y>=dimensions.y){return;}let centerUV=(vec2(index)+0.5)/vec2(dimensions);let originalSample=textureLoad(sourceTexture,index,0);let originalColor=originalSample.rgb;let originalAlpha=originalSample.a;let encodedCoC=textureLoad(cocTexture,index,0).a;let cocValue=decodeCoC(encodedCoC);if(abs(cocValue)<.005){textureStore(outputTexture,index,vec4(originalColor,originalAlpha));return;}var finalColor=originalColor;var finalAlpha=originalAlpha;if(cocValue<.0){let blurResult=calculateBlur(centerUV,abs(cocValue),uniforms.nearBlurSize,true);let nearBlur=blurResult.rgb;let nearBlurAlpha=blurResult.a;let nearBlend=saturate(pow(abs(cocValue)*uniforms.nearStrength,0.7));finalColor=mix(originalColor,nearBlur,nearBlend);finalAlpha=mix(originalAlpha,nearBlurAlpha,nearBlend);}else if(cocValue>.0){let blurResult=calculateBlur(centerUV,cocValue,uniforms.farBlurSize,false);let farBlur=blurResult.rgb;let farBlurAlpha=blurResult.a;let rawBlend=cocValue*uniforms.farStrength;let farBlend=saturate(smoothstep(.0,0.8,rawBlend));finalColor=mix(originalColor,farBlur,farBlend);finalAlpha=mix(originalAlpha,farBlurAlpha,farBlend);}textureStore(outputTexture,index,vec4(finalColor,finalAlpha));","#redgpu_include math.PI2 struct Uniforms{nearBlurSize:f32,farBlurSize:f32,nearStrength:f32,farStrength:f32,};fn decodeCoC(encoded:f32)->f32{return encoded*2.0-1.0;}fn calculateBlur(centerUV:vec2,intensity:f32,maxBlurSize:f32,isNear:bool)->vec4{let blurRadius=intensity*maxBlurSize*systemUniforms.devicePixelRatio;let dimensions=vec2(textureDimensions(sourceTexture));let invSize=1.0/vec2(dimensions);if(blurRadius<0.3){return textureSampleLevel(sourceTexture,basicSampler,centerUV,.0);}var sum:vec3=vec3(.0);var sumAlpha:f32=.0;var totalWeight=.0;let maxRadius=min(blurRadius,maxBlurSize*systemUniforms.devicePixelRatio);let samples=select(8,16,isNear);let angleStep=PI2/f32(samples);let originalColor=textureSampleLevel(sourceTexture,basicSampler,centerUV,.0);let centerWeight=select(0.4,0.2,isNear);sum+=originalColor.rgb*centerWeight;sumAlpha+=originalColor.a*centerWeight;totalWeight+=centerWeight;for(var i=0;i(cos(angle),sin(angle))*r*invSize;let sampleUV=centerUV+offsetUV;let sampleData=textureSampleLevel(sourceTexture,basicSampler,sampleUV,.0);let sampleEncodedCoC=textureSampleLevel(cocTexture,basicSampler,sampleUV,.0).a;let sampleCoC=decodeCoC(sampleEncodedCoC);var weight=exp(-r*r/(maxRadius*maxRadius*0.5));if(isNear){if(sampleCoC<.0&&abs(sampleCoC)>=intensity*0.5){weight*=1.5;}}else{if(sampleCoC>.0&&sampleCoC>=intensity*0.7){weight*=1.2;}}sum+=sampleData.rgb*weight;sumAlpha+=sampleData.a*weight;totalWeight+=weight;}}return vec4(sum/totalWeight,sumAlpha/totalWeight);}",[{name:"sourceTexture"},{name:"cocTexture"}]))}}definePositiveNumber(DOFUnified,[{key:"nearBlurSize",value:16},{key:"farBlurSize",value:24},{key:"nearStrength",value:1},{key:"farStrength",value:1}]),Object.freeze(DOFUnified);class DOF extends AMultiPassPostEffect{#tv;#rv;#iv=15;#xi=2.8;#nv=25;#av=.1;#sv=1e3;#ov=15;#uv=15;#lv=1;#cv=1;constructor(i){super(i,[new DOFCoC(i),new DOFUnified(i)]),this.#tv=this.passList[0],this.#rv=this.passList[1],this.#tv.focusDistance=this.#iv,this.#tv.aperture=this.#xi,this.#tv.maxCoC=this.#nv,this.#tv.nearPlane=this.#av,this.#tv.farPlane=this.#sv,this.#rv.nearBlurSize=this.#ov,this.#rv.farBlurSize=this.#uv,this.#rv.nearStrength=this.#lv,this.#rv.farStrength=this.#cv}get focusDistance(){return this.#iv}set focusDistance(i){this.#iv=i,this.#tv.focusDistance=i}get aperture(){return this.#xi}set aperture(i){this.#xi=i,this.#tv.aperture=i}get maxCoC(){return this.#nv}set maxCoC(i){this.#nv=i,this.#tv.maxCoC=i}get nearPlane(){return this.#av}set nearPlane(i){this.#av=i,this.#tv.nearPlane=i}get farPlane(){return this.#sv}set farPlane(i){this.#sv=i,this.#tv.farPlane=i}get nearBlurSize(){return this.#ov}set nearBlurSize(i){this.#ov=i,this.#rv.nearBlurSize=i}get farBlurSize(){return this.#uv}set farBlurSize(i){this.#uv=i,this.#rv.farBlurSize=i}get nearStrength(){return this.#lv}set nearStrength(i){this.#lv=i,this.#rv.nearStrength=i}get farStrength(){return this.#cv}set farStrength(i){this.#cv=i,this.#rv.farStrength=i}setGameDefault(){this.focusDistance=15,this.aperture=2.8,this.maxCoC=25,this.nearBlurSize=15,this.farBlurSize=15,this.nearStrength=1,this.farStrength=1}setCinematic(){this.focusDistance=20,this.aperture=1.4,this.maxCoC=40,this.nearBlurSize=25,this.farBlurSize=30,this.nearStrength=1.2,this.farStrength=1.3}setPortrait(){this.focusDistance=8,this.aperture=1.8,this.maxCoC=35,this.nearBlurSize=12,this.farBlurSize=25,this.nearStrength=.8,this.farStrength=1.4}setLandscape(){this.focusDistance=50,this.aperture=8,this.maxCoC=20,this.nearBlurSize=20,this.farBlurSize=10,this.nearStrength=1.1,this.farStrength=.6}setMacro(){this.focusDistance=2,this.aperture=1,this.maxCoC=50,this.nearBlurSize=30,this.farBlurSize=35,this.nearStrength=1.5,this.farStrength=1.6}setSports(){this.focusDistance=25,this.aperture=4,this.maxCoC=18,this.nearBlurSize=10,this.farBlurSize=12,this.nearStrength=.8,this.farStrength=.9}setNightMode(){this.focusDistance=12,this.aperture=2,this.maxCoC=30,this.nearBlurSize=18,this.farBlurSize=20,this.nearStrength=1.1,this.farStrength=1.2}render(i,g,x,v){const _=i.postEffectManager.texturePool,y=this.#tv.render(i,g,x,v),b=this.#rv.render(i,g,x,v,y);return _.release(y.texture),b}}Object.freeze(DOF);class LensDistortion extends ASinglePassPostEffect{constructor(i){super(i),this.isLdr=!0,this.init(i,"POST_EFFECT_LENS_DISTORTION",createBasicPostEffectCode(this,"let index=global_id.xy;let dimensions=textureDimensions(sourceTexture);let dimF=vec2(dimensions);let invSize=1.0/dimF;let uv=vec2(index)/dimF;let uvCenter=vec2(0.5)+vec2(uniforms.centerX,uniforms.centerY)*systemUniforms.devicePixelRatio*invSize;let offset=uv-uvCenter;let distance=length(offset);let distortionFactor=1.0+uniforms.distortion*distance*distance;let distortedUV=uvCenter+offset*distortionFactor;if(distortedUV.x<.0||distortedUV.x>1.0||distortedUV.y<.0||distortedUV.y>1.0){textureStore(outputTexture,index,vec4(.0,.0,.0,1.0));}else{let sampledColor=textureSampleLevel(sourceTexture,basicSampler,distortedUV,.0);textureStore(outputTexture,index,sampledColor);}","struct Uniforms{distortion:f32,centerX:f32,centerY:f32};"))}}defineNumber(LensDistortion,[{key:"distortion",value:.1},{key:"centerX",value:0},{key:"centerY",value:0}]),Object.freeze(LensDistortion);class Vignetting extends ASinglePassPostEffect{constructor(i){super(i),this.isLdr=!0,this.init(i,"POST_EFFECT_VIGNETTING",createBasicPostEffectCode(this,"let dimensions=textureDimensions(sourceTexture);let dimF=vec2(dimensions);let invSize=1.0/dimF;let index=global_id.xy;let uv=vec2(index)/dimF;let uvCenter=vec2(0.5)+vec2(uniforms.centerX,uniforms.centerY)*systemUniforms.devicePixelRatio*invSize;let smoothness=uniforms.smoothness;let size=uniforms.size;var color:vec4=textureLoad(sourceTexture,index,0);var diff=size-distance(uv,uvCenter);let vignette=smoothstep(-smoothness,smoothness,diff);color=vec4(color.rgb*vignette,color.a);textureStore(outputTexture,index,color);","struct Uniforms{smoothness:f32,size:f32,centerX:f32,centerY:f32,};"))}}definePositiveNumber(Vignetting,[{key:"size",value:.5,max:1},{key:"smoothness",value:.2,max:1}]),defineNumber(Vignetting,[{key:"centerX",value:0},{key:"centerY",value:0}]),Object.freeze(Vignetting);class OldBloomBlend extends ASinglePassPostEffect{constructor(i){super(i),this.init(i,"POST_EFFECT_OLD_BLOOM_BLEND",createBasicPostEffectCode(this,"let index=vec2(global_id.xy);let dimensions:vec2=textureDimensions(sourceTexture0);if(index.x>=dimensions.x||index.y>=dimensions.y){return;}let diffuseSample=textureLoad(sourceTexture0,index,0);let blurSample=textureLoad(sourceTexture1,index,0);let diffuseRGB=diffuseSample.rgb;let blurRGB=blurSample.rgb*uniforms.bloomStrength;let diffuseYCoCg=rgbToYCoCg(diffuseRGB);let blurYCoCg=rgbToYCoCg(blurRGB);var finalYCoCg:vec3;finalYCoCg.x=diffuseYCoCg.x+blurYCoCg.x;finalYCoCg.y=diffuseYCoCg.y+blurYCoCg.y*0.5;finalYCoCg.z=diffuseYCoCg.z+blurYCoCg.z*0.5;let finalRGB=YCoCgToRgb(finalYCoCg)*uniforms.exposure;textureStore(outputTexture,index,vec4(finalRGB,diffuseSample.a));","#redgpu_include color.getLuminance #redgpu_include color.rgbToYCoCg #redgpu_include color.YCoCgToRgb struct Uniforms{bloomStrength:f32,exposure:f32,};",[{name:"sourceTexture0"},{name:"sourceTexture1"}]))}render(i,g,x,v,_){return super.render(i,g,x,v,_)}}definePositiveNumber(OldBloomBlend,[{key:"bloomStrength",value:1},{key:"exposure",value:1}]),Object.freeze(OldBloomBlend);class OldBloom extends AMultiPassPostEffect{#hv;#fv;#dv;#mv=156;#pv=32;#gv=1;#xv=1.2;constructor(i){super(i,[new Threshold(i),new GaussianBlur(i),new OldBloomBlend(i)]),this.#hv=this.passList[0],this.#fv=this.passList[1],this.#dv=this.passList[2],this.#hv.threshold=this.#mv,this.#fv.size=this.#pv,this.#dv.exposure=this.#gv,this.#dv.bloomStrength=this.#xv}get threshold(){return this.#mv}set threshold(i){this.#mv=i,this.#hv.threshold=i}get gaussianBlurSize(){return this.#pv}set gaussianBlurSize(i){this.#pv=i,this.#fv.size=i}get exposure(){return this.#gv}set exposure(i){this.#gv=i,this.#dv.exposure=i}get bloomStrength(){return this.#xv}set bloomStrength(i){this.#xv=i,this.#dv.bloomStrength=i}render(i,g,x,v){const _=i.postEffectManager.texturePool,y=this.#hv.render(i,g,x,v),b=this.#fv.render(i,g,x,y);_.release(y.texture);const S=this.#dv.render(i,g,x,v,b);return _.release(b.texture),S}}Object.freeze(OldBloom);class Sharpen extends AMultiPassPostEffect{#Jx;constructor(i){super(i,[new Convolution(i)]),this.isLdr=!0,this.#Jx=this.passList[0],this.#Jx.kernel=Convolution.SHARPEN}render(i,g,x,v){return this.#Jx.render(i,g,x,v)}}Object.freeze(Sharpen);var So=Object.freeze({__proto__:null,AMultiPassPostEffect:AMultiPassPostEffect,ASinglePassPostEffect:ASinglePassPostEffect,PostEffectTexturePool:PostEffectTexturePool,createBasicPostEffectCode:createBasicPostEffectCode}),To=Object.freeze({__proto__:null,Blur:Blur,BlurX:BlurX,BlurY:BlurY,BrightnessContrast:BrightnessContrast,ChromaticAberration:ChromaticAberration,ColorBalance:ColorBalance,ColorTemperatureTint:ColorTemperatureTint,Convolution:Convolution,Core:So,DOF:DOF,DirectionalBlur:DirectionalBlur,FilmGrain:FilmGrain,Fog:Fog,GaussianBlur:GaussianBlur,Grayscale:Grayscale,HeightFog:HeightFog,HueSaturation:HueSaturation,Invert:Invert,LensDistortion:LensDistortion,OldBloom:OldBloom,PostEffectManager:PostEffectManager,RadialBlur:RadialBlur,Sharpen:Sharpen,Threshold:Threshold,Vibrance:Vibrance,Vignetting:Vignetting,ZoomBlur:ZoomBlur}),wo=Object.freeze({__proto__:null,PICKING_EVENT_TYPE:i,PickingEvent:PickingEvent,PickingManager:PickingManager,Raycaster2D:Raycaster2D,Raycaster3D:Raycaster3D}),Mo=Object.freeze({__proto__:null,BlendState:BlendState,DepthStencilState:DepthStencilState,PrimitiveState:PrimitiveState}),Po=Object.freeze({__proto__:null,TONE_MAPPING_MODE:ea,ToneMappingManager:ToneMappingManager}),Ro=Object.freeze({__proto__:null,DirectionalShadowManager:DirectionalShadowManager,ShadowManager:ShadowManager}),Co=Object.freeze({__proto__:null,defineBoolean:defineBoolean,defineColorRGB:defineColorRGB,defineColorRGBA:defineColorRGBA,defineCubeTexture:defineCubeTexture,defineNumber:defineNumber,definePositiveNumber:definePositiveNumber,defineSampler:defineSampler,defineTexture:defineTexture,defineUint:defineUint,defineVector2:defineVector2,defineVector3:defineVector3,defineVector4:defineVector4}),Bo=Object.freeze({__proto__:null,AntialiasingManager:AntialiasingManager,FXAA:FXAA,TAA:TAA,TAASharpen:TAASharpen});var Do=Object.freeze({__proto__:null,PHYSICS_BODY_TYPE:{DYNAMIC:"dynamic",STATIC:"static",KINEMATIC:"kinematic",KINEMATIC_POSITION:"kinematicPosition",KINEMATIC_VELOCITY:"kinematicVelocity"},PHYSICS_SHAPE:{BOX:"box",SPHERE:"sphere",CAPSULE:"capsule",CYLINDER:"cylinder",HEIGHTFIELD:"heightfield",MESH:"mesh"}});export{Bo as Antialiasing,xa as BaseObject,ga as Bound,Ca as Camera,Ea as Color,Ia as CommandEncoderManager,Da as Context,Co as DefineGPUProperty,ks as Display,GLTFLoader,v as GPU_ADDRESS_MODE,ui as GPU_BLEND_FACTOR,li as GPU_BLEND_OPERATION,Er as GPU_COMPARE_FUNCTION,Ji as GPU_CULL_MODE,_ as GPU_FILTER_MODE,Qi as GPU_FRONT_FACE,en as GPU_INDEX_FORMAT,z as GPU_LOAD_OP,y as GPU_MIPMAP_FILTER_MODE,Ei as GPU_PRIMITIVE_TOPOLOGY,q as GPU_STORE_OP,Geometry,Os as Light,zs as Material,Vs as Math,Do as Physics,wo as Picking,To as PostEffect,Fs as Primitive,Mo as RenderState,Renderer,ao as Resource,ho as RuntimeChecker,ft as ShaderLibrary,Ro as Shadow,SystemUniformUpdater,Po as ToneMapping,x as Util,init}; diff --git a/examples/2d/blendMode/basic/index.html b/examples/2d/blendMode/basic/index.html index a817797dd6..6e8bf1b602 100644 --- a/examples/2d/blendMode/basic/index.html +++ b/examples/2d/blendMode/basic/index.html @@ -39,12 +39,12 @@ } - - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -53,5 +53,8 @@

- - + + - - + + @@ -53,5 +53,8 @@

- - + + - - + + @@ -53,5 +53,8 @@

- - + + - - + + @@ -53,5 +53,8 @@

- - + + - - + + @@ -53,5 +53,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

{ specularStrength: material.specularStrength, shininess: material.shininess, normalScale: material.normalScale, - displacementScale: material.displacementScale, + // displacementScale: material.displacementScale, textures: { useDiffuse: !!material.diffuseTexture, useAlpha: !!material.alphaTexture, @@ -125,7 +125,7 @@ const renderUI = (redGPUContext, mesh) => { useSpecular: !!material.specularTexture, useNormal: !!material.normalTexture, useEmissive: !!material.emissiveTexture, - useDisplacement: !!material.displacementTexture, + // useDisplacement: !!material.displacementTexture, }, }; @@ -163,7 +163,7 @@ const renderUI = (redGPUContext, mesh) => { {key: "specularStrength", min: 0, max: 20, step: 0.01}, {key: "shininess", min: 0, max: 128, step: 1}, {key: "normalScale", min: 0, max: 2, step: 0.01}, - {key: "displacementScale", min: 0, max: 5, step: 0.01}, + // {key: "displacementScale", min: 0, max: 5, step: 0.01}, ]; properties.forEach(({key, min, max, step}) => @@ -200,7 +200,7 @@ const renderUI = (redGPUContext, mesh) => { // [KO] 초기 텍스처 활성화 // [EN] Initial Texture Activation material.diffuseTexture = textures.diffuse; - material.displacementTexture = textures.displacement; + // material.displacementTexture = textures.displacement; material.normalTexture = textures.normal; params.textures.useDisplacement = true; params.textures.useNormal = true; diff --git a/examples/3d/material/phongMaterialTextures/index.html b/examples/3d/material/phongMaterialTextures/index.html index 1f5a35eb28..c2217c1554 100644 --- a/examples/3d/material/phongMaterialTextures/index.html +++ b/examples/3d/material/phongMaterialTextures/index.html @@ -39,12 +39,12 @@ } - - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

{const s=t[n],r=e[n];return l(s)&&l(r)?Object.assign(Object.assign({},i),{[n]:h(s,r)}):Object.assign(Object.assign({},i),{[n]:n in e?r:s})},{})}function c(t){return!!a(t)&&"target"in t}var d={alreadydisposed:()=>"View has been already disposed",invalidparams:t=>`Invalid parameters for '${t.name}'`,nomatchingcontroller:t=>`No matching controller for '${t.key}'`,nomatchingview:t=>`No matching view for '${JSON.stringify(t.params)}'`,notbindable:()=>"Value is not bindable",notcompatible:t=>`Not compatible with plugin '${t.id}'`,propertynotfound:t=>`Property '${t.name}' not found`,shouldneverhappen:()=>"This error should never happen"},u=class t{static alreadyDisposed(){return new t({type:"alreadydisposed"})}static notBindable(){return new t({type:"notbindable"})}static notCompatible(e,i){return new t({type:"notcompatible",context:{id:`${e}.${i}`}})}static propertyNotFound(e){return new t({type:"propertynotfound",context:{name:e}})}static shouldNeverHappen(){return new t({type:"shouldneverhappen"})}constructor(t){var e;this.message=null!==(e=d[t.type](t.context))&&void 0!==e?e:"Unexpected error",this.name=this.constructor.name,this.stack=new Error(this.message).stack,this.type=t.type}toString(){return this.message}},v=class t{constructor(t,e){this.obj_=t,this.key=e}static isBindable(t){return null!==t&&("object"==typeof t||"function"==typeof t)}read(){return this.obj_[this.key]}write(t){this.obj_[this.key]=t}writeProperty(e,i){const n=this.read();if(!t.isBindable(n))throw u.notBindable();if(!(e in n))throw u.propertyNotFound(e);n[e]=i}},m=class{constructor(){this.observers_={}}on(t,e,i){var n;let s=this.observers_[t];return s||(s=this.observers_[t]=[]),s.push({handler:e,key:null!==(n=null==i?void 0:i.key)&&void 0!==n?n:e}),this}off(t,e){const i=this.observers_[t];return i&&(this.observers_[t]=i.filter(t=>t.key!==e)),this}emit(t,e){const i=this.observers_[t];i&&i.forEach(t=>{t.handler(e)})}},b=class{constructor(t,e){var i;this.constraint_=null==e?void 0:e.constraint,this.equals_=null!==(i=null==e?void 0:e.equals)&&void 0!==i?i:(t,e)=>t===e,this.emitter=new m,this.rawValue_=t}get constraint(){return this.constraint_}get rawValue(){return this.rawValue_}set rawValue(t){this.setRawValue(t,{forceEmit:!1,last:!0})}setRawValue(t,e){const i=null!=e?e:{forceEmit:!1,last:!0},n=this.constraint_?this.constraint_.constrain(t):t,s=this.rawValue_;this.equals_(s,n)&&!i.forceEmit||(this.emitter.emit("beforechange",{sender:this}),this.rawValue_=n,this.emitter.emit("change",{options:i,previousRawValue:s,rawValue:n,sender:this}))}},g=class{constructor(t){this.emitter=new m,this.value_=t}get rawValue(){return this.value_}set rawValue(t){this.setRawValue(t,{forceEmit:!1,last:!0})}setRawValue(t,e){const i=null!=e?e:{forceEmit:!1,last:!0},n=this.value_;(n!==t||i.forceEmit)&&(this.emitter.emit("beforechange",{sender:this}),this.value_=t,this.emitter.emit("change",{options:i,previousRawValue:n,rawValue:this.value_,sender:this}))}},w=class{constructor(t){this.emitter=new m,this.onValueBeforeChange_=this.onValueBeforeChange_.bind(this),this.onValueChange_=this.onValueChange_.bind(this),this.value_=t,this.value_.emitter.on("beforechange",this.onValueBeforeChange_),this.value_.emitter.on("change",this.onValueChange_)}get rawValue(){return this.value_.rawValue}onValueBeforeChange_(t){this.emitter.emit("beforechange",Object.assign(Object.assign({},t),{sender:this}))}onValueChange_(t){this.emitter.emit("change",Object.assign(Object.assign({},t),{sender:this}))}};function _(t,e){const i=null==e?void 0:e.constraint,n=null==e?void 0:e.equals;return i||n?new b(t,e):new g(t)}var f=class t{constructor(t){this.emitter=new m,this.valMap_=t;for(const e in this.valMap_)this.valMap_[e].emitter.on("change",()=>{this.emitter.emit("change",{key:e,sender:this})})}static createCore(t){return Object.keys(t).reduce((e,i)=>Object.assign(e,{[i]:_(t[i])}),{})}static fromObject(e){return new t(this.createCore(e))}get(t){return this.valMap_[t].rawValue}set(t,e){this.valMap_[t].rawValue=e}value(t){return this.valMap_[t]}},x=class{constructor(t){this.values=f.fromObject({max:t.max,min:t.min})}constrain(t){const e=this.values.get("max"),i=this.values.get("min");return Math.min(Math.max(t,i),e)}},C=class{constructor(t){this.values=f.fromObject({max:t.max,min:t.min})}constrain(t){const e=this.values.get("max"),i=this.values.get("min");let n=t;return o(i)||(n=Math.max(n,i)),o(e)||(n=Math.min(n,e)),n}},y=class{constructor(t,e=0){this.step=t,this.origin=e}constrain(t){const e=this.origin%this.step;return e+Math.round((t-e)/this.step)*this.step}},P=class{constructor(t){this.text=t}evaluate(){return Number(this.text)}toString(){return this.text}},E={"**":(t,e)=>Math.pow(t,e),"*":(t,e)=>t*e,"/":(t,e)=>t/e,"%":(t,e)=>t%e,"+":(t,e)=>t+e,"-":(t,e)=>t-e,"<<":(t,e)=>t<>":(t,e)=>t>>e,">>>":(t,e)=>t>>>e,"&":(t,e)=>t&e,"^":(t,e)=>t^e,"|":(t,e)=>t|e},k=class{constructor(t,e,i){this.left=e,this.operator=t,this.right=i}evaluate(){const t=E[this.operator];if(!t)throw new Error(`unexpected binary operator: '${this.operator}`);return t(this.left.evaluate(),this.right.evaluate())}toString(){return["b(",this.left.toString(),this.operator,this.right.toString(),")"].join(" ")}},V={"+":t=>t,"-":t=>-t,"~":t=>~t},L=class{constructor(t,e){this.operator=t,this.expression=e}evaluate(){const t=V[this.operator];if(!t)throw new Error(`unexpected unary operator: '${this.operator}`);return t(this.expression.evaluate())}toString(){return["u(",this.operator,this.expression.toString(),")"].join(" ")}};function M(t){return(e,i)=>{for(let n=0;ne.startsWith(t,i))[0];return n?(i+=n.length,{cursor:i+=S(e,i).length,operator:n}):null}var z=[["**"],["*","/","%"],["+","-"],["<<",">>>",">>"],["&"],["^"],["|"]].reduce((t,e)=>function(t,e){return(i,n)=>{const s=t(i,n);if(!s)return null;n=s.cursor;let r=s.evaluable;for(;;){const s=T(e,i,n);if(!s)break;n=s.cursor;const o=t(i,n);if(!o)return null;n=o.cursor,r=new k(s.operator,r,o.evaluable)}return r?{cursor:n,evaluable:r}:null}}(t,e),function t(e,i){const n=function(t,e){var i;return null!==(i=function(t,e){const i=B(t,e);return e+=i.length,""===i?null:{evaluable:new P(i),cursor:e}}(t,e))&&void 0!==i?i:function(t,e){const i=t.substr(e,1);if(e+=i.length,"("!==i)return null;const n=R(t,e);if(!n)return null;e=n.cursor,e+=S(t,e).length;const s=t.substr(e,1);return e+=s.length,")"!==s?null:{evaluable:n.evaluable,cursor:e}}(t,e)}(e,i);if(n)return n;const s=e.substr(i,1);if(i+=s.length,"+"!==s&&"-"!==s&&"~"!==s)return null;const r=t(e,i);return r?{cursor:i=r.cursor,evaluable:new L(s,r.evaluable)}:null});function R(t,e){return e+=S(t,e).length,z(t,e)}function N(t){var e;const i=function(t){const e=R(t,0);return e?e.cursor+S(t,e.cursor).length!==t.length?null:e.evaluable:null}(t);return null!==(e=null==i?void 0:i.evaluate())&&void 0!==e?e:null}function K(t){if("number"==typeof t)return t;if("string"==typeof t){const e=N(t);if(!o(e))return e}return 0}function I(t){return String(t)}function U(t){return e=>e.toFixed(Math.max(Math.min(t,20),0))}function F(t,e,i,n,s){return n+(t-e)/(i-e)*(s-n)}function $(t){return String(t.toFixed(10)).split(".")[1].replace(/0+$/,"").length}function q(t,e,i){return Math.min(Math.max(t,e),i)}function H(t,e){return(t%e+e)%e}function G(t,e){return o(t.step)?Math.max($(e),2):$(t.step)}function Y(t){var e;return null!==(e=t.step)&&void 0!==e?e:1}function X(t,e){var i;const n=Math.abs(null!==(i=t.step)&&void 0!==i?i:e);return 0===n?.1:Math.pow(10,Math.floor(Math.log10(n))-1)}function W(t,e){return o(t.step)?null:new y(t.step,e)}function Q(t){return o(t.max)||o(t.min)?o(t.max)&&o(t.min)?null:new C({max:t.max,min:t.min}):new x({max:t.max,min:t.min})}function J(t,e){var i,n,s;return{formatter:null!==(i=t.format)&&void 0!==i?i:U(G(t,e)),keyScale:null!==(n=t.keyScale)&&void 0!==n?n:Y(t),pointerScale:null!==(s=t.pointerScale)&&void 0!==s?s:X(t,e)}}function Z(t){return{format:t.optional.function,keyScale:t.optional.number,max:t.optional.number,min:t.optional.number,pointerScale:t.optional.number,step:t.optional.number}}function tt(t){return{constraint:t.constraint,textProps:f.fromObject(J(t.params,t.initialValue))}}var et=class{constructor(t){this.controller=t}get element(){return this.controller.view.element}get disabled(){return this.controller.viewProps.get("disabled")}set disabled(t){this.controller.viewProps.set("disabled",t)}get hidden(){return this.controller.viewProps.get("hidden")}set hidden(t){this.controller.viewProps.set("hidden",t)}dispose(){this.controller.viewProps.set("disposed",!0)}importState(t){return this.controller.importState(t)}exportState(){return this.controller.exportState()}},it=class{constructor(t){this.target=t}},nt=class extends it{constructor(t,e,i){super(t),this.value=e,this.last=null==i||i}},st=class extends it{constructor(t,e){super(t),this.expanded=e}},rt=class extends it{constructor(t,e){super(t),this.index=e}},ot=class extends it{constructor(t,e){super(t),this.native=e}},at=class extends et{constructor(t){super(t),this.onValueChange_=this.onValueChange_.bind(this),this.emitter_=new m,this.controller.value.emitter.on("change",this.onValueChange_)}get label(){return this.controller.labelController.props.get("label")}set label(t){this.controller.labelController.props.set("label",t)}get key(){return this.controller.value.binding.target.key}get tag(){return this.controller.tag}set tag(t){this.controller.tag=t}on(t,e){const i=e.bind(this);return this.emitter_.on(t,t=>{i(t)},{key:e}),this}off(t,e){return this.emitter_.off(t,e),this}refresh(){this.controller.value.fetch()}onValueChange_(t){const e=this.controller.value;this.emitter_.emit("change",new nt(this,e.binding.target.read(),t.options.last))}},lt=class{constructor(t,e){this.onValueBeforeChange_=this.onValueBeforeChange_.bind(this),this.onValueChange_=this.onValueChange_.bind(this),this.binding=e,this.value_=t,this.value_.emitter.on("beforechange",this.onValueBeforeChange_),this.value_.emitter.on("change",this.onValueChange_),this.emitter=new m}get rawValue(){return this.value_.rawValue}set rawValue(t){this.value_.rawValue=t}setRawValue(t,e){this.value_.setRawValue(t,e)}fetch(){this.value_.rawValue=this.binding.read()}push(){this.binding.write(this.value_.rawValue)}onValueBeforeChange_(t){this.emitter.emit("beforechange",Object.assign(Object.assign({},t),{sender:this}))}onValueChange_(t){this.push(),this.emitter.emit("change",Object.assign(Object.assign({},t),{sender:this}))}};function pt(t){return e=>i=>{if(!e&&void 0===i)return{succeeded:!1,value:void 0};if(e&&void 0===i)return{succeeded:!0,value:void 0};const n=t(i);return void 0!==n?{succeeded:!0,value:n}:{succeeded:!1,value:void 0}}}function ht(t){return{custom:e=>pt(e)(t),boolean:pt(t=>"boolean"==typeof t?t:void 0)(t),number:pt(t=>"number"==typeof t?t:void 0)(t),string:pt(t=>"string"==typeof t?t:void 0)(t),function:pt(t=>"function"==typeof t?t:void 0)(t),constant:e=>pt(t=>t===e?e:void 0)(t),raw:pt(t=>t)(t),object:e=>pt(t=>{var i;if(null!==(i=t)&&"object"==typeof i)return function(t,e){return Object.keys(e).reduce((i,n)=>{if(void 0===i)return;const s=(0,e[n])(t[n]);return s.succeeded?Object.assign(Object.assign({},i),{[n]:s.value}):void 0},{})}(t,e)})(t),array:e=>pt(t=>{var i;if(Array.isArray(t))return i=e,t.reduce((t,e)=>{if(void 0===t)return;const n=i(e);return n.succeeded&&void 0!==n.value?[...t,n.value]:void 0},[])})(t)}}var ct={optional:ht(!0),required:ht(!1)};function dt(t,e){const i=e(ct),n=ct.required.object(i)(t);return n.succeeded?n.value:void 0}function ut(t,e,i,n){if(e&&!e(t))return!1;const s=dt(t,i);return!!s&&n(s)}function vt(t,e){var i;return h(null!==(i=null==t?void 0:t())&&void 0!==i?i:{},e)}function mt(t){return"value"in t}function bt(t){return!(!a(t)||!("binding"in t))&&c(t.binding)}var gt="http://www.w3.org/2000/svg";function wt(t){t.offsetHeight}function _t(t){return void 0!==t.ontouchstart}var ft={check:'',dropdown:'',p2dpad:''};function xt(t,e){const i=t.createElementNS(gt,"svg");return i.innerHTML=ft[e],i}function Ct(t,e,i){t.insertBefore(e,t.children[i])}function yt(t){t.parentElement&&t.parentElement.removeChild(t)}function Pt(t){for(;t.children.length>0;)t.removeChild(t.children[0])}function Et(t){return t.relatedTarget?t.relatedTarget:"explicitOriginalTarget"in t?t.explicitOriginalTarget:null}function kt(t,e){t.emitter.on("change",t=>{e(t.rawValue)}),e(t.rawValue)}function Vt(t,e,i){kt(t.value(e),i)}var Lt="tp";function Mt(t){return(e,i)=>[Lt,"-",t,"v",e?`_${e}`:"",i?`-${i}`:""].join("")}var St=Mt("lbl"),jt=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(St()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("div");i.classList.add(St("l")),Vt(e.props,"label",e=>{o(e)?this.element.classList.add(St(void 0,"nol")):(this.element.classList.remove(St(void 0,"nol")),function(t){for(;t.childNodes.length>0;)t.removeChild(t.childNodes[0])}(i),i.appendChild(function(t,e){const i=t.createDocumentFragment();return e.split("\n").map(e=>t.createTextNode(e)).forEach((e,n)=>{n>0&&i.appendChild(t.createElement("br")),i.appendChild(e)}),i}(t,e)))}),this.element.appendChild(i),this.labelElement=i;const n=t.createElement("div");n.classList.add(St("v")),this.element.appendChild(n),this.valueElement=n}},Dt=class{constructor(t,e){this.props=e.props,this.valueController=e.valueController,this.viewProps=e.valueController.viewProps,this.view=new jt(t,{props:e.props,viewProps:this.viewProps}),this.view.valueElement.appendChild(this.valueController.view.element)}importProps(t){return ut(t,null,t=>({label:t.optional.string}),t=>(this.props.set("label",t.label),!0))}exportProps(){return vt(null,{label:this.props.get("label")})}},At=Mt(""),Ot={veryfirst:"vfst",first:"fst",last:"lst",verylast:"vlst"},Bt=class{constructor(t){this.parent_=null,this.blade=t.blade,this.view=t.view,this.viewProps=t.viewProps;const e=this.view.element;this.blade.value("positions").emitter.on("change",()=>{["veryfirst","first","last","verylast"].forEach(t=>{e.classList.remove(At(void 0,Ot[t]))}),this.blade.get("positions").forEach(t=>{e.classList.add(At(void 0,Ot[t]))})}),this.viewProps.handleDispose(()=>{yt(e)})}get parent(){return this.parent_}set parent(t){this.parent_=t,this.viewProps.set("parent",this.parent_?this.parent_.viewProps:null)}importState(t){return ut(t,null,t=>({disabled:t.required.boolean,hidden:t.required.boolean}),t=>(this.viewProps.importState(t),!0))}exportState(){return vt(null,Object.assign({},this.viewProps.exportState()))}},Tt=class extends Bt{constructor(t,e){if(e.value!==e.valueController.value)throw u.shouldNeverHappen();const i=e.valueController.viewProps,n=new Dt(t,{blade:e.blade,props:e.props,valueController:e.valueController});super(Object.assign(Object.assign({},e),{view:new jt(t,{props:e.props,viewProps:i}),viewProps:i})),this.labelController=n,this.value=e.value,this.valueController=e.valueController,this.view.valueElement.appendChild(this.valueController.view.element)}importState(t){return ut(t,e=>{var i,n,s;return super.importState(e)&&this.labelController.importProps(e)&&(null===(s=null===(n=(i=this.valueController).importProps)||void 0===n?void 0:n.call(i,t))||void 0===s||s)},t=>({value:t.optional.raw}),t=>(t.value&&(this.value.rawValue=t.value),!0))}exportState(){var t,e,i;return vt(()=>super.exportState(),Object.assign(Object.assign({value:this.value.rawValue},this.labelController.exportProps()),null!==(i=null===(e=(t=this.valueController).exportProps)||void 0===e?void 0:e.call(t))&&void 0!==i?i:{}))}};function zt(t){const e=Object.assign({},t);return delete e.value,e}var Rt=class extends Tt{constructor(t,e){super(t,e),this.tag=e.tag}importState(t){return ut(t,e=>super.importState(zt(t)),t=>({tag:t.optional.string}),t=>(this.tag=t.tag,!0))}exportState(){return vt(()=>zt(super.exportState()),{binding:{key:this.value.binding.target.key,value:this.value.binding.target.read()},tag:this.tag})}},Nt=class extends Rt{importState(t){return ut(t,t=>super.importState(t),t=>({binding:t.required.object({value:t.required.raw})}),t=>(this.value.binding.inject(t.binding.value),this.value.fetch(),!0))}};function Kt(t,e){for(;t.lengtht.length?i.splice(0,i.length-t.length):Kt(i,t.length),i}(this.value_.rawValue,this.binding.read())}onTick_(){this.fetch()}onValueBeforeChange_(t){this.emitter.emit("beforechange",Object.assign(Object.assign({},t),{sender:this}))}onValueChange_(t){this.emitter.emit("change",Object.assign(Object.assign({},t),{sender:this}))}},Ft=class extends Rt{exportState(){return vt(()=>super.exportState(),{binding:{readonly:!0}})}};var $t=class extends et{get label(){return this.controller.labelController.props.get("label")}set label(t){this.controller.labelController.props.set("label",t)}get title(){var t;return null!==(t=this.controller.buttonController.props.get("title"))&&void 0!==t?t:""}set title(t){this.controller.buttonController.props.set("title",t)}on(t,e){const i=e.bind(this);return this.controller.buttonController.emitter.on(t,t=>{i(new ot(this,t.nativeEvent))}),this}off(t,e){return this.controller.buttonController.emitter.off(t,e),this}};function qt(t,e){return i=>{!function(t,e,i){i?t.classList.add(e):t.classList.remove(e)}(t,e,i)}}function Ht(t,e){kt(t,t=>{e.textContent=null!=t?t:""})}var Gt=Mt("btn"),Yt=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(Gt()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("button");i.classList.add(Gt("b")),e.viewProps.bindDisabled(i),this.element.appendChild(i),this.buttonElement=i;const n=t.createElement("div");n.classList.add(Gt("t")),Ht(e.props.value("title"),n),this.buttonElement.appendChild(n)}},Xt=class{constructor(t,e){this.emitter=new m,this.onClick_=this.onClick_.bind(this),this.props=e.props,this.viewProps=e.viewProps,this.view=new Yt(t,{props:this.props,viewProps:this.viewProps}),this.view.buttonElement.addEventListener("click",this.onClick_)}importProps(t){return ut(t,null,t=>({title:t.optional.string}),t=>(this.props.set("title",t.title),!0))}exportProps(){return vt(null,{title:this.props.get("title")})}onClick_(t){this.emitter.emit("click",{nativeEvent:t,sender:this})}},Wt=class extends Bt{constructor(t,e){const i=new Xt(t,{props:e.buttonProps,viewProps:e.viewProps}),n=new Dt(t,{blade:e.blade,props:e.labelProps,valueController:i});super({blade:e.blade,view:n.view,viewProps:e.viewProps}),this.buttonController=i,this.labelController=n}importState(t){return ut(t,t=>super.importState(t)&&this.buttonController.importProps(t)&&this.labelController.importProps(t),()=>({}),()=>!0)}exportState(){return vt(()=>super.exportState(),Object.assign(Object.assign({},this.buttonController.exportProps()),this.labelController.exportProps()))}},Qt=class{constructor(t){const[e,i]=t.split("-"),n=e.split(".");this.major=parseInt(n[0],10),this.minor=parseInt(n[1],10),this.patch=parseInt(n[2],10),this.prerelease=null!=i?i:null}toString(){const t=[this.major,this.minor,this.patch].join(".");return null!==this.prerelease?[t,this.prerelease].join("-"):t}},Jt=new Qt("2.0.5");function Zt(t){return Object.assign({core:Jt},t)}var te=Zt({id:"button",type:"blade",accept(t){const e=dt(t,t=>({title:t.required.string,view:t.required.constant("button"),label:t.optional.string}));return e?{params:e}:null},controller:t=>new Wt(t.document,{blade:t.blade,buttonProps:f.fromObject({title:t.params.title}),labelProps:f.fromObject({label:t.params.label}),viewProps:t.viewProps}),api:t=>t.controller instanceof Wt?new $t(t.controller):null}),ee=class{constructor(t,e){this.onRackValueChange_=this.onRackValueChange_.bind(this),this.controller_=t,this.emitter_=new m,this.pool_=e,this.controller_.rack.emitter.on("valuechange",this.onRackValueChange_)}get children(){return this.controller_.rack.children.map(t=>this.pool_.createApi(t))}addBinding(t,e,i){const n=null!=i?i:{},s=this.controller_.element.ownerDocument,r=this.pool_.createBinding(s,function(t,e){if(!v.isBindable(t))throw u.notBindable();return new v(t,e)}(t,e),n),o=this.pool_.createBindingApi(r);return this.add(o,n.index)}addFolder(t){return function(t,e){return t.addBlade(Object.assign(Object.assign({},e),{view:"folder"}))}(this,t)}addButton(t){return function(t,e){return t.addBlade(Object.assign(Object.assign({},e),{view:"button"}))}(this,t)}addTab(t){return function(t,e){return t.addBlade(Object.assign(Object.assign({},e),{view:"tab"}))}(this,t)}add(t,e){const i=t.controller;return this.controller_.rack.add(i,e),t}remove(t){this.controller_.rack.remove(t.controller)}addBlade(t){const e=this.controller_.element.ownerDocument,i=this.pool_.createBlade(e,t),n=this.pool_.createApi(i);return this.add(n,t.index)}on(t,e){const i=e.bind(this);return this.emitter_.on(t,t=>{i(t)},{key:e}),this}off(t,e){return this.emitter_.off(t,e),this}refresh(){this.children.forEach(t=>{var e;a(e=t)&&"refresh"in e&&"function"==typeof e.refresh&&t.refresh()})}onRackValueChange_(t){const e=t.bladeController,i=this.pool_.createApi(e),n=bt(e.value)?e.value.binding:null;this.emitter_.emit("change",new nt(i,n?n.target.read():e.value.rawValue,t.options.last))}},ie=class extends et{constructor(t,e){super(t),this.rackApi_=new ee(t.rackController,e)}refresh(){this.rackApi_.refresh()}},ne=class extends Bt{constructor(t){super({blade:t.blade,view:t.view,viewProps:t.rackController.viewProps}),this.rackController=t.rackController}importState(t){return ut(t,t=>super.importState(t),t=>({children:t.required.array(t.required.raw)}),t=>this.rackController.rack.children.every((e,i)=>e.importState(t.children[i])))}exportState(){return vt(()=>super.exportState(),{children:this.rackController.rack.children.map(t=>t.exportState())})}};function se(t){return"rackController"in t}var re=class{constructor(t){this.emitter=new m,this.items_=[],this.cache_=new Set,this.onSubListAdd_=this.onSubListAdd_.bind(this),this.onSubListRemove_=this.onSubListRemove_.bind(this),this.extract_=t}get items(){return this.items_}allItems(){return Array.from(this.cache_)}find(t){for(const e of this.allItems())if(t(e))return e;return null}includes(t){return this.cache_.has(t)}add(t,e){if(this.includes(t))throw u.shouldNeverHappen();const i=void 0!==e?e:this.items_.length;this.items_.splice(i,0,t),this.cache_.add(t);const n=this.extract_(t);n&&(n.emitter.on("add",this.onSubListAdd_),n.emitter.on("remove",this.onSubListRemove_),n.allItems().forEach(t=>{this.cache_.add(t)})),this.emitter.emit("add",{index:i,item:t,root:this,target:this})}remove(t){const e=this.items_.indexOf(t);if(e<0)return;this.items_.splice(e,1),this.cache_.delete(t);const i=this.extract_(t);i&&(i.allItems().forEach(t=>{this.cache_.delete(t)}),i.emitter.off("add",this.onSubListAdd_),i.emitter.off("remove",this.onSubListRemove_)),this.emitter.emit("remove",{index:e,item:t,root:this,target:this})}onSubListAdd_(t){this.cache_.add(t.item),this.emitter.emit("add",{index:t.index,item:t.item,root:this,target:t.target})}onSubListRemove_(t){this.cache_.delete(t.item),this.emitter.emit("remove",{index:t.index,item:t.item,root:this,target:t.target})}};function oe(t){return se(t)?t.rackController.rack.bcSet_:null}var ae=class{constructor(t){var e,i;this.emitter=new m,this.onBladePositionsChange_=this.onBladePositionsChange_.bind(this),this.onSetAdd_=this.onSetAdd_.bind(this),this.onSetRemove_=this.onSetRemove_.bind(this),this.onChildDispose_=this.onChildDispose_.bind(this),this.onChildPositionsChange_=this.onChildPositionsChange_.bind(this),this.onChildValueChange_=this.onChildValueChange_.bind(this),this.onChildViewPropsChange_=this.onChildViewPropsChange_.bind(this),this.onRackLayout_=this.onRackLayout_.bind(this),this.onRackValueChange_=this.onRackValueChange_.bind(this),this.blade_=null!==(e=t.blade)&&void 0!==e?e:null,null===(i=this.blade_)||void 0===i||i.value("positions").emitter.on("change",this.onBladePositionsChange_),this.viewProps=t.viewProps,this.bcSet_=new re(oe),this.bcSet_.emitter.on("add",this.onSetAdd_),this.bcSet_.emitter.on("remove",this.onSetRemove_)}get children(){return this.bcSet_.items}add(t,e){var i;null===(i=t.parent)||void 0===i||i.remove(t),t.parent=this,this.bcSet_.add(t,e)}remove(t){t.parent=null,this.bcSet_.remove(t)}find(t){return this.bcSet_.allItems().filter(t)}onSetAdd_(t){this.updatePositions_();const e=t.target===t.root;if(this.emitter.emit("add",{bladeController:t.item,index:t.index,root:e,sender:this}),!e)return;const i=t.item;if(i.viewProps.emitter.on("change",this.onChildViewPropsChange_),i.blade.value("positions").emitter.on("change",this.onChildPositionsChange_),i.viewProps.handleDispose(this.onChildDispose_),mt(i))i.value.emitter.on("change",this.onChildValueChange_);else if(se(i)){const t=i.rackController.rack;if(t){const e=t.emitter;e.on("layout",this.onRackLayout_),e.on("valuechange",this.onRackValueChange_)}}}onSetRemove_(t){this.updatePositions_();const e=t.target===t.root;if(this.emitter.emit("remove",{bladeController:t.item,root:e,sender:this}),!e)return;const i=t.item;if(mt(i))i.value.emitter.off("change",this.onChildValueChange_);else if(se(i)){const t=i.rackController.rack;if(t){const e=t.emitter;e.off("layout",this.onRackLayout_),e.off("valuechange",this.onRackValueChange_)}}}updatePositions_(){const t=this.bcSet_.items.filter(t=>!t.viewProps.get("hidden")),e=t[0],i=t[t.length-1];this.bcSet_.items.forEach(t=>{const n=[];t===e&&(n.push("first"),this.blade_&&!this.blade_.get("positions").includes("veryfirst")||n.push("veryfirst")),t===i&&(n.push("last"),this.blade_&&!this.blade_.get("positions").includes("verylast")||n.push("verylast")),t.blade.set("positions",n)})}onChildPositionsChange_(){this.updatePositions_(),this.emitter.emit("layout",{sender:this})}onChildViewPropsChange_(t){this.updatePositions_(),this.emitter.emit("layout",{sender:this})}onChildDispose_(){this.bcSet_.items.filter(t=>t.viewProps.get("disposed")).forEach(t=>{this.bcSet_.remove(t)})}onChildValueChange_(t){const e=function(t,e){for(let i=0;i{for(let t=this.rack.children.length-1;t>=0;t--)this.rack.children[t].viewProps.set("disposed",!0)})}onRackAdd_(t){t.root&&Ct(this.element,t.bladeController.view.element,t.index)}onRackRemove_(t){t.root&&yt(t.bladeController.view.element)}};function pe(){return new f({positions:_([],{equals:p})})}var he=class t extends f{constructor(t){super(t)}static create(e){const i={completed:!0,expanded:e,expandedHeight:null,shouldFixHeight:!1,temporaryExpanded:null};return new t(f.createCore(i))}get styleExpanded(){var t;return null!==(t=this.get("temporaryExpanded"))&&void 0!==t?t:this.get("expanded")}get styleHeight(){if(!this.styleExpanded)return"0";const t=this.get("expandedHeight");return this.get("shouldFixHeight")&&!o(t)?`${t}px`:"auto"}bindExpandedClass(t,e){const i=()=>{this.styleExpanded?t.classList.add(e):t.classList.remove(e)};Vt(this,"expanded",i),Vt(this,"temporaryExpanded",i)}cleanUpTransition(){this.set("shouldFixHeight",!1),this.set("expandedHeight",null),this.set("completed",!0)}};function ce(t,e){e.style.height=t.styleHeight}function de(t,e){t.value("expanded").emitter.on("beforechange",()=>{if(t.set("completed",!1),o(t.get("expandedHeight"))){const i=function(t,e){let i=0;return function(n){const s=n.style.transition;n.style.transition="none",t.set("expandedHeight",null),t.set("temporaryExpanded",!0),wt(e),i=e.clientHeight,t.set("temporaryExpanded",null),wt(e),n.style.transition=s}(e),i}(t,e);i>0&&t.set("expandedHeight",i)}t.set("shouldFixHeight",!0),wt(e)}),t.emitter.on("change",()=>{ce(t,e)}),ce(t,e),e.addEventListener("transitionend",e=>{"height"===e.propertyName&&t.cleanUpTransition()})}var ue=class extends ie{constructor(t,e){super(t,e),this.emitter_=new m,this.controller.foldable.value("expanded").emitter.on("change",t=>{this.emitter_.emit("fold",new st(this,t.sender.rawValue))}),this.rackApi_.on("change",t=>{this.emitter_.emit("change",t)})}get expanded(){return this.controller.foldable.get("expanded")}set expanded(t){this.controller.foldable.set("expanded",t)}get title(){return this.controller.props.get("title")}set title(t){this.controller.props.set("title",t)}get children(){return this.rackApi_.children}addBinding(t,e,i){return this.rackApi_.addBinding(t,e,i)}addFolder(t){return this.rackApi_.addFolder(t)}addButton(t){return this.rackApi_.addButton(t)}addTab(t){return this.rackApi_.addTab(t)}add(t,e){return this.rackApi_.add(t,e)}remove(t){this.rackApi_.remove(t)}addBlade(t){return this.rackApi_.addBlade(t)}on(t,e){const i=e.bind(this);return this.emitter_.on(t,t=>{i(t)},{key:e}),this}off(t,e){return this.emitter_.off(t,e),this}},ve=Mt("cnt"),me=class{constructor(t,e){var i;this.className_=Mt(null!==(i=e.viewName)&&void 0!==i?i:"fld"),this.element=t.createElement("div"),this.element.classList.add(this.className_(),ve()),e.viewProps.bindClassModifiers(this.element),this.foldable_=e.foldable,this.foldable_.bindExpandedClass(this.element,this.className_(void 0,"expanded")),Vt(this.foldable_,"completed",qt(this.element,this.className_(void 0,"cpl")));const n=t.createElement("button");n.classList.add(this.className_("b")),Vt(e.props,"title",t=>{o(t)?this.element.classList.add(this.className_(void 0,"not")):this.element.classList.remove(this.className_(void 0,"not"))}),e.viewProps.bindDisabled(n),this.element.appendChild(n),this.buttonElement=n;const s=t.createElement("div");s.classList.add(this.className_("i")),this.element.appendChild(s);const r=t.createElement("div");r.classList.add(this.className_("t")),Ht(e.props.value("title"),r),this.buttonElement.appendChild(r),this.titleElement=r;const a=t.createElement("div");a.classList.add(this.className_("m")),this.buttonElement.appendChild(a);const l=t.createElement("div");l.classList.add(this.className_("c")),this.element.appendChild(l),this.containerElement=l}},be=class extends ne{constructor(t,e){var i;const n=he.create(null===(i=e.expanded)||void 0===i||i),s=new me(t,{foldable:n,props:e.props,viewName:e.root?"rot":void 0,viewProps:e.viewProps});super(Object.assign(Object.assign({},e),{rackController:new le({blade:e.blade,element:s.containerElement,root:e.root,viewProps:e.viewProps}),view:s})),this.onTitleClick_=this.onTitleClick_.bind(this),this.props=e.props,this.foldable=n,de(this.foldable,this.view.containerElement),this.rackController.rack.emitter.on("add",()=>{this.foldable.cleanUpTransition()}),this.rackController.rack.emitter.on("remove",()=>{this.foldable.cleanUpTransition()}),this.view.buttonElement.addEventListener("click",this.onTitleClick_)}get document(){return this.view.element.ownerDocument}importState(t){return ut(t,t=>super.importState(t),t=>({expanded:t.required.boolean,title:t.optional.string}),t=>(this.foldable.set("expanded",t.expanded),this.props.set("title",t.title),!0))}exportState(){return vt(()=>super.exportState(),{expanded:this.foldable.get("expanded"),title:this.props.get("title")})}onTitleClick_(){this.foldable.set("expanded",!this.foldable.get("expanded"))}},ge=Zt({id:"folder",type:"blade",accept(t){const e=dt(t,t=>({title:t.required.string,view:t.required.constant("folder"),expanded:t.optional.boolean}));return e?{params:e}:null},controller:t=>new be(t.document,{blade:t.blade,expanded:t.params.expanded,props:f.fromObject({title:t.params.title}),viewProps:t.viewProps}),api:t=>t.controller instanceof be?new ue(t.controller,t.pool):null}),we=Mt("");function _e(t,e){return qt(t,we(void 0,e))}var fe=class t extends f{constructor(t){var e,i;super(t),this.onDisabledChange_=this.onDisabledChange_.bind(this),this.onParentChange_=this.onParentChange_.bind(this),this.onParentGlobalDisabledChange_=this.onParentGlobalDisabledChange_.bind(this),[this.globalDisabled_,this.setGlobalDisabled_]=(i=_(this.getGlobalDisabled_()),[new w(i),(t,e)=>{i.setRawValue(t,e)}]),this.value("disabled").emitter.on("change",this.onDisabledChange_),this.value("parent").emitter.on("change",this.onParentChange_),null===(e=this.get("parent"))||void 0===e||e.globalDisabled.emitter.on("change",this.onParentGlobalDisabledChange_)}static create(e){var i,n,s;const r=null!=e?e:{};return new t(f.createCore({disabled:null!==(i=r.disabled)&&void 0!==i&&i,disposed:!1,hidden:null!==(n=r.hidden)&&void 0!==n&&n,parent:null!==(s=r.parent)&&void 0!==s?s:null}))}get globalDisabled(){return this.globalDisabled_}bindClassModifiers(t){kt(this.globalDisabled_,_e(t,"disabled")),Vt(this,"hidden",_e(t,"hidden"))}bindDisabled(t){kt(this.globalDisabled_,e=>{t.disabled=e})}bindTabIndex(t){kt(this.globalDisabled_,e=>{t.tabIndex=e?-1:0})}handleDispose(t){this.value("disposed").emitter.on("change",e=>{e&&t()})}importState(t){this.set("disabled",t.disabled),this.set("hidden",t.hidden)}exportState(){return{disabled:this.get("disabled"),hidden:this.get("hidden")}}getGlobalDisabled_(){const t=this.get("parent");return!!t&&t.globalDisabled.rawValue||this.get("disabled")}updateGlobalDisabled_(){this.setGlobalDisabled_(this.getGlobalDisabled_())}onDisabledChange_(){this.updateGlobalDisabled_()}onParentGlobalDisabledChange_(){this.updateGlobalDisabled_()}onParentChange_(t){var e;const i=t.previousRawValue;null==i||i.globalDisabled.emitter.off("change",this.onParentGlobalDisabledChange_),null===(e=this.get("parent"))||void 0===e||e.globalDisabled.emitter.on("change",this.onParentGlobalDisabledChange_),this.updateGlobalDisabled_()}},xe=Mt("tbp"),Ce=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(xe()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("div");i.classList.add(xe("c")),this.element.appendChild(i),this.containerElement=i}},ye=Mt("tbi"),Pe=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(ye()),e.viewProps.bindClassModifiers(this.element),Vt(e.props,"selected",t=>{t?this.element.classList.add(ye(void 0,"sel")):this.element.classList.remove(ye(void 0,"sel"))});const i=t.createElement("button");i.classList.add(ye("b")),e.viewProps.bindDisabled(i),this.element.appendChild(i),this.buttonElement=i;const n=t.createElement("div");n.classList.add(ye("t")),Ht(e.props.value("title"),n),this.buttonElement.appendChild(n),this.titleElement=n}},Ee=class{constructor(t,e){this.emitter=new m,this.onClick_=this.onClick_.bind(this),this.props=e.props,this.viewProps=e.viewProps,this.view=new Pe(t,{props:e.props,viewProps:e.viewProps}),this.view.buttonElement.addEventListener("click",this.onClick_)}onClick_(){this.emitter.emit("click",{sender:this})}},ke=class extends ne{constructor(t,e){const i=new Ce(t,{viewProps:e.viewProps});super(Object.assign(Object.assign({},e),{rackController:new le({blade:e.blade,element:i.containerElement,viewProps:e.viewProps}),view:i})),this.onItemClick_=this.onItemClick_.bind(this),this.ic_=new Ee(t,{props:e.itemProps,viewProps:fe.create()}),this.ic_.emitter.on("click",this.onItemClick_),this.props=e.props,Vt(this.props,"selected",t=>{this.itemController.props.set("selected",t),this.viewProps.set("hidden",!t)})}get itemController(){return this.ic_}importState(t){return ut(t,t=>super.importState(t),t=>({selected:t.required.boolean,title:t.required.string}),t=>(this.ic_.props.set("selected",t.selected),this.ic_.props.set("title",t.title),!0))}exportState(){return vt(()=>super.exportState(),{selected:this.ic_.props.get("selected"),title:this.ic_.props.get("title")})}onItemClick_(){this.props.set("selected",!0)}},Ve=class extends ie{constructor(t,e){super(t,e),this.emitter_=new m,this.onSelect_=this.onSelect_.bind(this),this.pool_=e,this.rackApi_.on("change",t=>{this.emitter_.emit("change",t)}),this.controller.tab.selectedIndex.emitter.on("change",this.onSelect_)}get pages(){return this.rackApi_.children}addPage(t){const e=this.controller.view.element.ownerDocument,i=new ke(e,{blade:pe(),itemProps:f.fromObject({selected:!1,title:t.title}),props:f.fromObject({selected:!1}),viewProps:fe.create()}),n=this.pool_.createApi(i);return this.rackApi_.add(n,t.index)}removePage(t){this.rackApi_.remove(this.rackApi_.children[t])}on(t,e){const i=e.bind(this);return this.emitter_.on(t,t=>{i(t)},{key:e}),this}off(t,e){return this.emitter_.off(t,e),this}onSelect_(t){this.emitter_.emit("select",new rt(this,t.rawValue))}},Le=class extends ie{get title(){var t;return null!==(t=this.controller.itemController.props.get("title"))&&void 0!==t?t:""}set title(t){this.controller.itemController.props.set("title",t)}get selected(){return this.controller.props.get("selected")}set selected(t){this.controller.props.set("selected",t)}get children(){return this.rackApi_.children}addButton(t){return this.rackApi_.addButton(t)}addFolder(t){return this.rackApi_.addFolder(t)}addTab(t){return this.rackApi_.addTab(t)}add(t,e){this.rackApi_.add(t,e)}remove(t){this.rackApi_.remove(t)}addBinding(t,e,i){return this.rackApi_.addBinding(t,e,i)}addBlade(t){return this.rackApi_.addBlade(t)}},Me=class{constructor(){this.onItemSelectedChange_=this.onItemSelectedChange_.bind(this),this.empty=_(!0),this.selectedIndex=_(-1),this.items_=[]}add(t,e){const i=null!=e?e:this.items_.length;this.items_.splice(i,0,t),t.emitter.on("change",this.onItemSelectedChange_),this.keepSelection_()}remove(t){const e=this.items_.indexOf(t);e<0||(this.items_.splice(e,1),t.emitter.off("change",this.onItemSelectedChange_),this.keepSelection_())}keepSelection_(){if(0===this.items_.length)return this.selectedIndex.rawValue=-1,void(this.empty.rawValue=!0);const t=this.items_.findIndex(t=>t.rawValue);t<0?(this.items_.forEach((t,e)=>{t.rawValue=0===e}),this.selectedIndex.rawValue=0):(this.items_.forEach((e,i)=>{e.rawValue=i===t}),this.selectedIndex.rawValue=t),this.empty.rawValue=!1}onItemSelectedChange_(t){if(t.rawValue){const e=this.items_.findIndex(e=>e===t.sender);this.items_.forEach((t,i)=>{t.rawValue=i===e}),this.selectedIndex.rawValue=e}else this.keepSelection_()}},Se=Mt("tab"),je=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(Se(),ve()),e.viewProps.bindClassModifiers(this.element),kt(e.empty,qt(this.element,Se(void 0,"nop")));const i=t.createElement("div");i.classList.add(Se("t")),this.element.appendChild(i),this.itemsElement=i;const n=t.createElement("div");n.classList.add(Se("i")),this.element.appendChild(n);const s=t.createElement("div");s.classList.add(Se("c")),this.element.appendChild(s),this.contentsElement=s}},De=class extends ne{constructor(t,e){const i=new Me,n=new je(t,{empty:i.empty,viewProps:e.viewProps});super({blade:e.blade,rackController:new le({blade:e.blade,element:n.contentsElement,viewProps:e.viewProps}),view:n}),this.onRackAdd_=this.onRackAdd_.bind(this),this.onRackRemove_=this.onRackRemove_.bind(this);const s=this.rackController.rack;s.emitter.on("add",this.onRackAdd_),s.emitter.on("remove",this.onRackRemove_),this.tab=i}add(t,e){this.rackController.rack.add(t,e)}remove(t){this.rackController.rack.remove(this.rackController.rack.children[t])}onRackAdd_(t){if(!t.root)return;const e=t.bladeController;Ct(this.view.itemsElement,e.itemController.view.element,t.index),e.itemController.viewProps.set("parent",this.viewProps),this.tab.add(e.props.value("selected"))}onRackRemove_(t){if(!t.root)return;const e=t.bladeController;yt(e.itemController.view.element),e.itemController.viewProps.set("parent",null),this.tab.remove(e.props.value("selected"))}},Ae=Zt({id:"tab",type:"blade",accept(t){const e=dt(t,t=>({pages:t.required.array(t.required.object({title:t.required.string})),view:t.required.constant("tab")}));return e&&0!==e.pages.length?{params:e}:null},controller(t){const e=new De(t.document,{blade:t.blade,viewProps:t.viewProps});return t.params.pages.forEach(i=>{const n=new ke(t.document,{blade:pe(),itemProps:f.fromObject({selected:!1,title:i.title}),props:f.fromObject({selected:!1}),viewProps:fe.create()});e.add(n)}),e},api:t=>t.controller instanceof De?new Ve(t.controller,t.pool):t.controller instanceof ke?new Le(t.controller,t.pool):null}),Oe=class extends at{get options(){return this.controller.valueController.props.get("options")}set options(t){this.controller.valueController.props.set("options",t)}},Be=class{constructor(){this.disabled=!1,this.emitter=new m}dispose(){}tick(){this.disabled||this.emitter.emit("tick",{sender:this})}},Te=class{constructor(t,e){this.disabled_=!1,this.timerId_=null,this.onTick_=this.onTick_.bind(this),this.doc_=t,this.emitter=new m,this.interval_=e,this.setTimer_()}get disabled(){return this.disabled_}set disabled(t){this.disabled_=t,this.disabled_?this.clearTimer_():this.setTimer_()}dispose(){this.clearTimer_()}clearTimer_(){if(null===this.timerId_)return;const t=this.doc_.defaultView;t&&t.clearInterval(this.timerId_),this.timerId_=null}setTimer_(){if(this.clearTimer_(),this.interval_<=0)return;const t=this.doc_.defaultView;t&&(this.timerId_=t.setInterval(this.onTick_,this.interval_))}onTick_(){this.disabled_||this.emitter.emit("tick",{sender:this})}},ze=class{constructor(t){this.constraints=t}constrain(t){return this.constraints.reduce((t,e)=>e.constrain(t),t)}};function Re(t,e){if(t instanceof e)return t;if(t instanceof ze){const i=t.constraints.reduce((t,i)=>t||(i instanceof e?i:null),null);if(i)return i}return null}var Ne=class{constructor(t){this.values=f.fromObject({options:t})}constrain(t){const e=this.values.get("options");return 0===e.length||e.filter(e=>e.value===t).length>0?t:e[0].value}};function Ke(t){var e;const i=ct;return Array.isArray(t)?null===(e=dt({items:t},t=>({items:t.required.array(t.required.object({text:t.required.string,value:t.required.raw}))})))||void 0===e?void 0:e.items:"object"==typeof t?i.required.raw(t).value:void 0}function Ie(t){if(Array.isArray(t))return t;const e=[];return Object.keys(t).forEach(i=>{e.push({text:i,value:t[i]})}),e}function Ue(t){return o(t)?null:new Ne(Ie(t))}var Fe=Mt("lst"),$e=class{constructor(t,e){this.onValueChange_=this.onValueChange_.bind(this),this.props_=e.props,this.element=t.createElement("div"),this.element.classList.add(Fe()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("select");i.classList.add(Fe("s")),e.viewProps.bindDisabled(i),this.element.appendChild(i),this.selectElement=i;const n=t.createElement("div");n.classList.add(Fe("m")),n.appendChild(xt(t,"dropdown")),this.element.appendChild(n),e.value.emitter.on("change",this.onValueChange_),this.value_=e.value,Vt(this.props_,"options",e=>{Pt(this.selectElement),e.forEach(e=>{const i=t.createElement("option");i.textContent=e.text,this.selectElement.appendChild(i)}),this.update_()})}update_(){const t=this.props_.get("options").map(t=>t.value);this.selectElement.selectedIndex=t.indexOf(this.value_.rawValue)}onValueChange_(){this.update_()}},qe=class{constructor(t,e){this.onSelectChange_=this.onSelectChange_.bind(this),this.props=e.props,this.value=e.value,this.viewProps=e.viewProps,this.view=new $e(t,{props:this.props,value:this.value,viewProps:this.viewProps}),this.view.selectElement.addEventListener("change",this.onSelectChange_)}onSelectChange_(t){const e=t.currentTarget;this.value.rawValue=this.props.get("options")[e.selectedIndex].value}importProps(t){return ut(t,null,t=>({options:t.required.custom(Ke)}),t=>(this.props.set("options",Ie(t.options)),!0))}exportProps(){return vt(null,{options:this.props.get("options")})}},He=Mt("pop"),Ge=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(He()),e.viewProps.bindClassModifiers(this.element),kt(e.shows,qt(this.element,He(void 0,"v")))}},Ye=class{constructor(t,e){this.shows=_(!1),this.viewProps=e.viewProps,this.view=new Ge(t,{shows:this.shows,viewProps:this.viewProps})}},Xe=Mt("txt"),We=class{constructor(t,e){this.onChange_=this.onChange_.bind(this),this.element=t.createElement("div"),this.element.classList.add(Xe()),e.viewProps.bindClassModifiers(this.element),this.props_=e.props,this.props_.emitter.on("change",this.onChange_);const i=t.createElement("input");i.classList.add(Xe("i")),i.type="text",e.viewProps.bindDisabled(i),this.element.appendChild(i),this.inputElement=i,e.value.emitter.on("change",this.onChange_),this.value_=e.value,this.refresh()}refresh(){const t=this.props_.get("formatter");this.inputElement.value=t(this.value_.rawValue)}onChange_(){this.refresh()}},Qe=class{constructor(t,e){this.onInputChange_=this.onInputChange_.bind(this),this.parser_=e.parser,this.props=e.props,this.value=e.value,this.viewProps=e.viewProps,this.view=new We(t,{props:e.props,value:this.value,viewProps:this.viewProps}),this.view.inputElement.addEventListener("change",this.onInputChange_)}onInputChange_(t){const e=t.currentTarget.value,i=this.parser_(e);o(i)||(this.value.rawValue=i),this.view.refresh()}};function Je(t){return"false"!==t&&!!t}function Ze(t){return function(t){return String(t)}(t)}var ti=U(0);function ei(t){return ti(t)+"%"}function ii(t){return String(t)}function ni(t){return t}function si({primary:t,secondary:e,forward:i,backward:n}){let s=!1;function r(t){s||(s=!0,t(),s=!1)}t.emitter.on("change",n=>{r(()=>{e.setRawValue(i(t.rawValue,e.rawValue),n.options)})}),e.emitter.on("change",s=>{r(()=>{t.setRawValue(n(t.rawValue,e.rawValue),s.options)}),r(()=>{e.setRawValue(i(t.rawValue,e.rawValue),s.options)})}),r(()=>{e.setRawValue(i(t.rawValue,e.rawValue),{forceEmit:!1,last:!0})})}function ri(t,e){const i=t*(e.altKey?.1:1)*(e.shiftKey?10:1);return e.upKey?+i:e.downKey?-i:0}function oi(t){return{altKey:t.altKey,downKey:"ArrowDown"===t.key,shiftKey:t.shiftKey,upKey:"ArrowUp"===t.key}}function ai(t){return{altKey:t.altKey,downKey:"ArrowLeft"===t.key,shiftKey:t.shiftKey,upKey:"ArrowRight"===t.key}}function li(t){return function(t){return"ArrowUp"===t||"ArrowDown"===t}(t)||"ArrowLeft"===t||"ArrowRight"===t}function pi(t,e){var i,n;const s=e.ownerDocument.defaultView,r=e.getBoundingClientRect();return{x:t.pageX-((null!==(i=s&&s.scrollX)&&void 0!==i?i:0)+r.left),y:t.pageY-((null!==(n=s&&s.scrollY)&&void 0!==n?n:0)+r.top)}}var hi=class{constructor(t){this.lastTouch_=null,this.onDocumentMouseMove_=this.onDocumentMouseMove_.bind(this),this.onDocumentMouseUp_=this.onDocumentMouseUp_.bind(this),this.onMouseDown_=this.onMouseDown_.bind(this),this.onTouchEnd_=this.onTouchEnd_.bind(this),this.onTouchMove_=this.onTouchMove_.bind(this),this.onTouchStart_=this.onTouchStart_.bind(this),this.elem_=t,this.emitter=new m,t.addEventListener("touchstart",this.onTouchStart_,{passive:!1}),t.addEventListener("touchmove",this.onTouchMove_,{passive:!0}),t.addEventListener("touchend",this.onTouchEnd_),t.addEventListener("mousedown",this.onMouseDown_)}computePosition_(t){const e=this.elem_.getBoundingClientRect();return{bounds:{width:e.width,height:e.height},point:t?{x:t.x,y:t.y}:null}}onMouseDown_(t){var e;t.preventDefault(),null===(e=t.currentTarget)||void 0===e||e.focus();const i=this.elem_.ownerDocument;i.addEventListener("mousemove",this.onDocumentMouseMove_),i.addEventListener("mouseup",this.onDocumentMouseUp_),this.emitter.emit("down",{altKey:t.altKey,data:this.computePosition_(pi(t,this.elem_)),sender:this,shiftKey:t.shiftKey})}onDocumentMouseMove_(t){this.emitter.emit("move",{altKey:t.altKey,data:this.computePosition_(pi(t,this.elem_)),sender:this,shiftKey:t.shiftKey})}onDocumentMouseUp_(t){const e=this.elem_.ownerDocument;e.removeEventListener("mousemove",this.onDocumentMouseMove_),e.removeEventListener("mouseup",this.onDocumentMouseUp_),this.emitter.emit("up",{altKey:t.altKey,data:this.computePosition_(pi(t,this.elem_)),sender:this,shiftKey:t.shiftKey})}onTouchStart_(t){t.preventDefault();const e=t.targetTouches.item(0),i=this.elem_.getBoundingClientRect();this.emitter.emit("down",{altKey:t.altKey,data:this.computePosition_(e?{x:e.clientX-i.left,y:e.clientY-i.top}:void 0),sender:this,shiftKey:t.shiftKey}),this.lastTouch_=e}onTouchMove_(t){const e=t.targetTouches.item(0),i=this.elem_.getBoundingClientRect();this.emitter.emit("move",{altKey:t.altKey,data:this.computePosition_(e?{x:e.clientX-i.left,y:e.clientY-i.top}:void 0),sender:this,shiftKey:t.shiftKey}),this.lastTouch_=e}onTouchEnd_(t){var e;const i=null!==(e=t.targetTouches.item(0))&&void 0!==e?e:this.lastTouch_,n=this.elem_.getBoundingClientRect();this.emitter.emit("up",{altKey:t.altKey,data:this.computePosition_(i?{x:i.clientX-n.left,y:i.clientY-n.top}:void 0),sender:this,shiftKey:t.shiftKey})}},ci=Mt("txt"),di=class{constructor(t,e){this.onChange_=this.onChange_.bind(this),this.props_=e.props,this.props_.emitter.on("change",this.onChange_),this.element=t.createElement("div"),this.element.classList.add(ci(),ci(void 0,"num")),e.arrayPosition&&this.element.classList.add(ci(void 0,e.arrayPosition)),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("input");i.classList.add(ci("i")),i.type="text",e.viewProps.bindDisabled(i),this.element.appendChild(i),this.inputElement=i,this.onDraggingChange_=this.onDraggingChange_.bind(this),this.dragging_=e.dragging,this.dragging_.emitter.on("change",this.onDraggingChange_),this.element.classList.add(ci()),this.inputElement.classList.add(ci("i"));const n=t.createElement("div");n.classList.add(ci("k")),this.element.appendChild(n),this.knobElement=n;const s=t.createElementNS(gt,"svg");s.classList.add(ci("g")),this.knobElement.appendChild(s);const r=t.createElementNS(gt,"path");r.classList.add(ci("gb")),s.appendChild(r),this.guideBodyElem_=r;const o=t.createElementNS(gt,"path");o.classList.add(ci("gh")),s.appendChild(o),this.guideHeadElem_=o;const a=t.createElement("div");a.classList.add(Mt("tt")()),this.knobElement.appendChild(a),this.tooltipElem_=a,e.value.emitter.on("change",this.onChange_),this.value=e.value,this.refresh()}onDraggingChange_(t){if(null===t.rawValue)return void this.element.classList.remove(ci(void 0,"drg"));this.element.classList.add(ci(void 0,"drg"));const e=t.rawValue/this.props_.get("pointerScale"),i=e+(e>0?-1:e<0?1:0),n=q(-i,-4,4);this.guideHeadElem_.setAttributeNS(null,"d",[`M ${i+n},0 L${i},4 L${i+n},8`,`M ${e},-1 L${e},9`].join(" ")),this.guideBodyElem_.setAttributeNS(null,"d",`M 0,4 L${e},4`);const s=this.props_.get("formatter");this.tooltipElem_.textContent=s(this.value.rawValue),this.tooltipElem_.style.left=`${e}px`}refresh(){const t=this.props_.get("formatter");this.inputElement.value=t(this.value.rawValue)}onChange_(){this.refresh()}},ui=class{constructor(t,e){var i;this.originRawValue_=0,this.onInputChange_=this.onInputChange_.bind(this),this.onInputKeyDown_=this.onInputKeyDown_.bind(this),this.onInputKeyUp_=this.onInputKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.parser_=e.parser,this.props=e.props,this.sliderProps_=null!==(i=e.sliderProps)&&void 0!==i?i:null,this.value=e.value,this.viewProps=e.viewProps,this.dragging_=_(null),this.view=new di(t,{arrayPosition:e.arrayPosition,dragging:this.dragging_,props:this.props,value:this.value,viewProps:this.viewProps}),this.view.inputElement.addEventListener("change",this.onInputChange_),this.view.inputElement.addEventListener("keydown",this.onInputKeyDown_),this.view.inputElement.addEventListener("keyup",this.onInputKeyUp_);const n=new hi(this.view.knobElement);n.emitter.on("down",this.onPointerDown_),n.emitter.on("move",this.onPointerMove_),n.emitter.on("up",this.onPointerUp_)}constrainValue_(t){var e,i;const n=null===(e=this.sliderProps_)||void 0===e?void 0:e.get("min"),s=null===(i=this.sliderProps_)||void 0===i?void 0:i.get("max");let r=t;return void 0!==n&&(r=Math.max(r,n)),void 0!==s&&(r=Math.min(r,s)),r}onInputChange_(t){const e=t.currentTarget.value,i=this.parser_(e);o(i)||(this.value.rawValue=this.constrainValue_(i)),this.view.refresh()}onInputKeyDown_(t){const e=ri(this.props.get("keyScale"),oi(t));0!==e&&this.value.setRawValue(this.constrainValue_(this.value.rawValue+e),{forceEmit:!1,last:!1})}onInputKeyUp_(t){0!==ri(this.props.get("keyScale"),oi(t))&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}onPointerDown_(){this.originRawValue_=this.value.rawValue,this.dragging_.rawValue=0}computeDraggingValue_(t){if(!t.point)return null;const e=t.point.x-t.bounds.width/2;return this.constrainValue_(this.originRawValue_+e*this.props.get("pointerScale"))}onPointerMove_(t){const e=this.computeDraggingValue_(t.data);null!==e&&(this.value.setRawValue(e,{forceEmit:!1,last:!1}),this.dragging_.rawValue=this.value.rawValue-this.originRawValue_)}onPointerUp_(t){const e=this.computeDraggingValue_(t.data);null!==e&&(this.value.setRawValue(e,{forceEmit:!0,last:!0}),this.dragging_.rawValue=null)}},vi=Mt("sld"),mi=class{constructor(t,e){this.onChange_=this.onChange_.bind(this),this.props_=e.props,this.props_.emitter.on("change",this.onChange_),this.element=t.createElement("div"),this.element.classList.add(vi()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("div");i.classList.add(vi("t")),e.viewProps.bindTabIndex(i),this.element.appendChild(i),this.trackElement=i;const n=t.createElement("div");n.classList.add(vi("k")),this.trackElement.appendChild(n),this.knobElement=n,e.value.emitter.on("change",this.onChange_),this.value=e.value,this.update_()}update_(){const t=q(F(this.value.rawValue,this.props_.get("min"),this.props_.get("max"),0,100),0,100);this.knobElement.style.width=`${t}%`}onChange_(){this.update_()}},bi=class{constructor(t,e){this.onKeyDown_=this.onKeyDown_.bind(this),this.onKeyUp_=this.onKeyUp_.bind(this),this.onPointerDownOrMove_=this.onPointerDownOrMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.value=e.value,this.viewProps=e.viewProps,this.props=e.props,this.view=new mi(t,{props:this.props,value:this.value,viewProps:this.viewProps}),this.ptHandler_=new hi(this.view.trackElement),this.ptHandler_.emitter.on("down",this.onPointerDownOrMove_),this.ptHandler_.emitter.on("move",this.onPointerDownOrMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.trackElement.addEventListener("keydown",this.onKeyDown_),this.view.trackElement.addEventListener("keyup",this.onKeyUp_)}handlePointerEvent_(t,e){t.point&&this.value.setRawValue(F(q(t.point.x,0,t.bounds.width),0,t.bounds.width,this.props.get("min"),this.props.get("max")),e)}onPointerDownOrMove_(t){this.handlePointerEvent_(t.data,{forceEmit:!1,last:!1})}onPointerUp_(t){this.handlePointerEvent_(t.data,{forceEmit:!0,last:!0})}onKeyDown_(t){const e=ri(this.props.get("keyScale"),ai(t));0!==e&&this.value.setRawValue(this.value.rawValue+e,{forceEmit:!1,last:!1})}onKeyUp_(t){0!==ri(this.props.get("keyScale"),ai(t))&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}},gi=Mt("sldtxt"),wi=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(gi());const i=t.createElement("div");i.classList.add(gi("s")),this.sliderView_=e.sliderView,i.appendChild(this.sliderView_.element),this.element.appendChild(i);const n=t.createElement("div");n.classList.add(gi("t")),this.textView_=e.textView,n.appendChild(this.textView_.element),this.element.appendChild(n)}},_i=class{constructor(t,e){this.value=e.value,this.viewProps=e.viewProps,this.sliderC_=new bi(t,{props:e.sliderProps,value:e.value,viewProps:this.viewProps}),this.textC_=new ui(t,{parser:e.parser,props:e.textProps,sliderProps:e.sliderProps,value:e.value,viewProps:e.viewProps}),this.view=new wi(t,{sliderView:this.sliderC_.view,textView:this.textC_.view})}get sliderController(){return this.sliderC_}get textController(){return this.textC_}importProps(t){return ut(t,null,t=>({max:t.required.number,min:t.required.number}),t=>{const e=this.sliderC_.props;return e.set("max",t.max),e.set("min",t.min),!0})}exportProps(){const t=this.sliderC_.props;return vt(null,{max:t.get("max"),min:t.get("min")})}};function fi(t){return{sliderProps:new f({keyScale:t.keyScale,max:t.max,min:t.min}),textProps:new f({formatter:_(t.formatter),keyScale:t.keyScale,pointerScale:_(t.pointerScale)})}}var xi={containerUnitSize:"cnt-usz"};function Ci(t){return`--${xi[t]}`}function yi(t){return Z(t)}function Pi(t){if(l(t))return dt(t,yi)}function Ei(t,e){if(!t)return;const i=[],n=W(t,e);n&&i.push(n);const s=Q(t);return s&&i.push(s),new ze(i)}function ki(t){if("inline"===t||"popup"===t)return t}function Vi(t,e){t.write(e)}var Li=Mt("ckb"),Mi=class{constructor(t,e){this.onValueChange_=this.onValueChange_.bind(this),this.element=t.createElement("div"),this.element.classList.add(Li()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("label");i.classList.add(Li("l")),this.element.appendChild(i),this.labelElement=i;const n=t.createElement("input");n.classList.add(Li("i")),n.type="checkbox",this.labelElement.appendChild(n),this.inputElement=n,e.viewProps.bindDisabled(this.inputElement);const s=t.createElement("div");s.classList.add(Li("w")),this.labelElement.appendChild(s);const r=xt(t,"check");s.appendChild(r),e.value.emitter.on("change",this.onValueChange_),this.value=e.value,this.update_()}update_(){this.inputElement.checked=this.value.rawValue}onValueChange_(){this.update_()}},Si=class{constructor(t,e){this.onInputChange_=this.onInputChange_.bind(this),this.onLabelMouseDown_=this.onLabelMouseDown_.bind(this),this.value=e.value,this.viewProps=e.viewProps,this.view=new Mi(t,{value:this.value,viewProps:this.viewProps}),this.view.inputElement.addEventListener("change",this.onInputChange_),this.view.labelElement.addEventListener("mousedown",this.onLabelMouseDown_)}onInputChange_(t){const e=t.currentTarget;this.value.rawValue=e.checked,t.preventDefault(),t.stopPropagation()}onLabelMouseDown_(t){t.preventDefault()}},ji=Zt({id:"input-bool",type:"input",accept:(t,e)=>{if("boolean"!=typeof t)return null;const i=dt(e,t=>({options:t.optional.custom(Ke),readonly:t.optional.constant(!1)}));return i?{initialValue:t,params:i}:null},binding:{reader:t=>Je,constraint:t=>function(t){const e=[],i=Ue(t.options);return i&&e.push(i),new ze(e)}(t.params),writer:t=>Vi},controller:t=>{const e=t.document,i=t.value,n=t.constraint,s=n&&Re(n,Ne);return s?new qe(e,{props:new f({options:s.values.value("options")}),value:i,viewProps:t.viewProps}):new Si(e,{value:i,viewProps:t.viewProps})},api:t=>"boolean"!=typeof t.controller.value.rawValue?null:t.controller.valueController instanceof qe?new Oe(t.controller):null}),Di=Mt("col"),Ai=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(Di()),e.foldable.bindExpandedClass(this.element,Di(void 0,"expanded")),Vt(e.foldable,"completed",qt(this.element,Di(void 0,"cpl")));const i=t.createElement("div");i.classList.add(Di("h")),this.element.appendChild(i);const n=t.createElement("div");n.classList.add(Di("s")),i.appendChild(n),this.swatchElement=n;const s=t.createElement("div");if(s.classList.add(Di("t")),i.appendChild(s),this.textElement=s,"inline"===e.pickerLayout){const e=t.createElement("div");e.classList.add(Di("p")),this.element.appendChild(e),this.pickerElement=e}else this.pickerElement=null}};function Oi(t,e,i){const n=H(t,360),s=q(e/100,0,1),r=q(i/100,0,1),o=r*s,a=o*(1-Math.abs(n/60%2-1)),l=r-o;let p,h,c;return[p,h,c]=n>=0&&n<60?[o,a,0]:n>=60&&n<120?[a,o,0]:n>=120&&n<180?[0,o,a]:n>=180&&n<240?[0,a,o]:n>=240&&n<300?[a,0,o]:[o,0,a],[255*(p+l),255*(h+l),255*(c+l)]}function Bi(t){return[t[0],t[1],t[2]]}function Ti(t,e){return[t[0],t[1],t[2],e]}var zi={hsl:{hsl:(t,e,i)=>[t,e,i],hsv:function(t,e,i){const n=i+e*(100-Math.abs(2*i-100))/200;return[t,0!==n?e*(100-Math.abs(2*i-100))/n:0,i+e*(100-Math.abs(2*i-100))/200]},rgb:function(t,e,i){const n=(t%360+360)%360,s=q(e/100,0,1),r=q(i/100,0,1),o=(1-Math.abs(2*r-1))*s,a=o*(1-Math.abs(n/60%2-1)),l=r-o/2;let p,h,c;return[p,h,c]=n>=0&&n<60?[o,a,0]:n>=60&&n<120?[a,o,0]:n>=120&&n<180?[0,o,a]:n>=180&&n<240?[0,a,o]:n>=240&&n<300?[a,0,o]:[o,0,a],[255*(p+l),255*(h+l),255*(c+l)]}},hsv:{hsl:function(t,e,i){const n=100-Math.abs(i*(200-e)/100-100);return[t,0!==n?e*i/n:0,i*(200-e)/200]},hsv:(t,e,i)=>[t,e,i],rgb:Oi},rgb:{hsl:function(t,e,i){const n=q(t/255,0,1),s=q(e/255,0,1),r=q(i/255,0,1),o=Math.max(n,s,r),a=Math.min(n,s,r),l=o-a;let p=0,h=0;const c=(a+o)/2;return 0!==l&&(h=l/(1-Math.abs(o+a-1)),p=n===o?(s-r)/l:s===o?2+(r-n)/l:4+(n-s)/l,p=p/6+(p<0?1:0)),[360*p,100*h,100*c]},hsv:function(t,e,i){const n=q(t/255,0,1),s=q(e/255,0,1),r=q(i/255,0,1),o=Math.max(n,s,r),a=o-Math.min(n,s,r);let l;return l=0===a?0:o===n?((s-r)/a%6+6)%6*60:o===s?60*((r-n)/a+2):60*((n-s)/a+4),[l,100*(0===o?0:a/o),100*o]},rgb:(t,e,i)=>[t,e,i]}};function Ri(t,e){return["float"===e?1:"rgb"===t?255:360,"float"===e?1:"rgb"===t?255:100,"float"===e?1:"rgb"===t?255:100]}function Ni(t,e,i){var n;const s=Ri(e,i);return["rgb"===e?q(t[0],0,s[0]):(r=t[0],o=s[0],r===o?o:H(r,o)),q(t[1],0,s[1]),q(t[2],0,s[2]),q(null!==(n=t[3])&&void 0!==n?n:1,0,1)];var r,o}function Ki(t,e,i,n){const s=Ri(e,i),r=Ri(e,n);return t.map((t,e)=>t/s[e]*r[e])}function Ii(t,e,i){const n=Ki(t,e.mode,e.type,"int");return Ki(zi[e.mode][i.mode](...n),i.mode,"int",i.type)}var Ui=class t{static black(){return new t([0,0,0],"rgb")}constructor(t,e){this.type="int",this.mode=e,this.comps_=Ni(t,e,this.type)}getComponents(t){return Ti(Ii(Bi(this.comps_),{mode:this.mode,type:this.type},{mode:null!=t?t:this.mode,type:this.type}),this.comps_[3])}toRgbaObject(){const t=this.getComponents("rgb");return{r:t[0],g:t[1],b:t[2],a:t[3]}}},Fi=Mt("colp"),$i=class{constructor(t,e){this.alphaViews_=null,this.element=t.createElement("div"),this.element.classList.add(Fi()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("div");i.classList.add(Fi("hsv"));const n=t.createElement("div");n.classList.add(Fi("sv")),this.svPaletteView_=e.svPaletteView,n.appendChild(this.svPaletteView_.element),i.appendChild(n);const s=t.createElement("div");s.classList.add(Fi("h")),this.hPaletteView_=e.hPaletteView,s.appendChild(this.hPaletteView_.element),i.appendChild(s),this.element.appendChild(i);const r=t.createElement("div");if(r.classList.add(Fi("rgb")),this.textsView_=e.textsView,r.appendChild(this.textsView_.element),this.element.appendChild(r),e.alphaViews){this.alphaViews_={palette:e.alphaViews.palette,text:e.alphaViews.text};const i=t.createElement("div");i.classList.add(Fi("a"));const n=t.createElement("div");n.classList.add(Fi("ap")),n.appendChild(this.alphaViews_.palette.element),i.appendChild(n);const s=t.createElement("div");s.classList.add(Fi("at")),s.appendChild(this.alphaViews_.text.element),i.appendChild(s),this.element.appendChild(i)}}get allFocusableElements(){const t=[this.svPaletteView_.element,this.hPaletteView_.element,this.textsView_.modeSelectElement,...this.textsView_.inputViews.map(t=>t.inputElement)];return this.alphaViews_&&t.push(this.alphaViews_.palette.element,this.alphaViews_.text.inputElement),t}};function qi(t){return"int"===t?"int":"float"===t?"float":void 0}function Hi(t){return dt(t,t=>({color:t.optional.object({alpha:t.optional.boolean,type:t.optional.custom(qi)}),expanded:t.optional.boolean,picker:t.optional.custom(ki),readonly:t.optional.constant(!1)}))}function Gi(t){return t?.1:1}function Yi(t){var e;return null===(e=t.color)||void 0===e?void 0:e.type}var Xi=class{constructor(t,e){this.type="float",this.mode=e,this.comps_=Ni(t,e,this.type)}getComponents(t){return Ti(Ii(Bi(this.comps_),{mode:this.mode,type:this.type},{mode:null!=t?t:this.mode,type:this.type}),this.comps_[3])}toRgbaObject(){const t=this.getComponents("rgb");return{r:t[0],g:t[1],b:t[2],a:t[3]}}},Wi={int:(t,e)=>new Ui(t,e),float:(t,e)=>new Xi(t,e)};function Qi(t,e,i){return Wi[i](t,e)}function Ji(t,e){if(t.type===e)return t;if(function(t){return"int"===t.type}(t)&&"float"===e)return function(t){const e=t.getComponents(),i=Ri(t.mode,"int");return new Xi([F(e[0],0,i[0],0,1),F(e[1],0,i[1],0,1),F(e[2],0,i[2],0,1),e[3]],t.mode)}(t);if(function(t){return"float"===t.type}(t)&&"int"===e)return function(t){const e=t.getComponents(),i=Ri(t.mode,"int");return new Ui([Math.round(F(e[0],0,1,0,i[0])),Math.round(F(e[1],0,1,0,i[1])),Math.round(F(e[2],0,1,0,i[2])),e[3]],t.mode)}(t);throw u.shouldNeverHappen()}function Zi(t,e){const i=t.match(/^(.+)%$/);return i?Math.min(.01*parseFloat(i[1])*e,e):Math.min(parseFloat(t),e)}var tn={deg:t=>t,grad:t=>360*t/400,rad:t=>360*t/(2*Math.PI),turn:t=>360*t};function en(t){const e=t.match(/^([0-9.]+?)(deg|grad|rad|turn)$/);if(!e)return parseFloat(t);const i=parseFloat(e[1]);return tn[e[2]](i)}function nn(t){const e=t.match(/^rgb\(\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!e)return null;const i=[Zi(e[1],255),Zi(e[2],255),Zi(e[3],255)];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])?null:i}function sn(t){const e=nn(t);return e?new Ui(e,"rgb"):null}function rn(t){const e=t.match(/^rgba\(\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!e)return null;const i=[Zi(e[1],255),Zi(e[2],255),Zi(e[3],255),Zi(e[4],1)];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])||isNaN(i[3])?null:i}function on(t){const e=rn(t);return e?new Ui(e,"rgb"):null}function an(t){const e=t.match(/^hsl\(\s*([0-9A-Fa-f.]+(?:deg|grad|rad|turn)?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!e)return null;const i=[en(e[1]),Zi(e[2],100),Zi(e[3],100)];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])?null:i}function ln(t){const e=an(t);return e?new Ui(e,"hsl"):null}function pn(t){const e=t.match(/^hsla\(\s*([0-9A-Fa-f.]+(?:deg|grad|rad|turn)?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!e)return null;const i=[en(e[1]),Zi(e[2],100),Zi(e[3],100),Zi(e[4],1)];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])||isNaN(i[3])?null:i}function hn(t){const e=pn(t);return e?new Ui(e,"hsl"):null}function cn(t){const e=t.match(/^#([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])$/);if(e)return[parseInt(e[1]+e[1],16),parseInt(e[2]+e[2],16),parseInt(e[3]+e[3],16)];const i=t.match(/^(?:#|0x)([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})$/);return i?[parseInt(i[1],16),parseInt(i[2],16),parseInt(i[3],16)]:null}function dn(t){const e=cn(t);return e?new Ui(e,"rgb"):null}function un(t){const e=t.match(/^#([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])$/);if(e)return[parseInt(e[1]+e[1],16),parseInt(e[2]+e[2],16),parseInt(e[3]+e[3],16),F(parseInt(e[4]+e[4],16),0,255,0,1)];const i=t.match(/^(?:#|0x)?([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})$/);return i?[parseInt(i[1],16),parseInt(i[2],16),parseInt(i[3],16),F(parseInt(i[4],16),0,255,0,1)]:null}function vn(t){const e=un(t);return e?new Ui(e,"rgb"):null}function mn(t){const e=t.match(/^\{\s*r\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*g\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*b\s*:\s*([0-9A-Fa-f.]+%?)\s*\}$/);if(!e)return null;const i=[parseFloat(e[1]),parseFloat(e[2]),parseFloat(e[3])];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])?null:i}function bn(t){return e=>{const i=mn(e);return i?Qi(i,"rgb",t):null}}function gn(t){const e=t.match(/^\{\s*r\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*g\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*b\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*a\s*:\s*([0-9A-Fa-f.]+%?)\s*\}$/);if(!e)return null;const i=[parseFloat(e[1]),parseFloat(e[2]),parseFloat(e[3]),parseFloat(e[4])];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])||isNaN(i[3])?null:i}function wn(t){return e=>{const i=gn(e);return i?Qi(i,"rgb",t):null}}var _n=[{parser:cn,result:{alpha:!1,mode:"rgb",notation:"hex"}},{parser:un,result:{alpha:!0,mode:"rgb",notation:"hex"}},{parser:nn,result:{alpha:!1,mode:"rgb",notation:"func"}},{parser:rn,result:{alpha:!0,mode:"rgb",notation:"func"}},{parser:an,result:{alpha:!1,mode:"hsl",notation:"func"}},{parser:pn,result:{alpha:!0,mode:"hsl",notation:"func"}},{parser:mn,result:{alpha:!1,mode:"rgb",notation:"object"}},{parser:gn,result:{alpha:!0,mode:"rgb",notation:"object"}}];function fn(t){const e=[dn,vn,sn,on,ln,hn];"int"===t&&e.push(bn("int"),wn("int")),"float"===t&&e.push(bn("float"),wn("float"));const i=function(t){return e=>t.reduce((t,i)=>null!==t?t:i(e),null)}(e);return e=>{const n=i(e);return n?Ji(n,t):null}}function xn(t){const e=fn("int");if("string"!=typeof t)return Ui.black();const i=e(t);return null!=i?i:Ui.black()}function Cn(t){const e=q(Math.floor(t),0,255).toString(16);return 1===e.length?`0${e}`:e}function yn(t,e="#"){return`${e}${Bi(t.getComponents("rgb")).map(Cn).join("")}`}function Pn(t,e="#"){const i=t.getComponents("rgb");return`${e}${[i[0],i[1],i[2],255*i[3]].map(Cn).join("")}`}function En(t){const e=U(0);return`rgb(${Bi(Ji(t,"int").getComponents("rgb")).map(t=>e(t)).join(", ")})`}function kn(t){const e=U(2),i=U(0);return`rgba(${Ji(t,"int").getComponents("rgb").map((t,n)=>(3===n?e:i)(t)).join(", ")})`}function Vn(t,e){const i=U("float"===e?2:0),n=["r","g","b"];return`{${Bi(Ji(t,e).getComponents("rgb")).map((t,e)=>`${n[e]}: ${i(t)}`).join(", ")}}`}function Ln(t){return e=>Vn(e,t)}function Mn(t,e){const i=U(2),n=U("float"===e?2:0),s=["r","g","b","a"];return`{${Ji(t,e).getComponents("rgb").map((t,e)=>`${s[e]}: ${(3===e?i:n)(t)}`).join(", ")}}`}function Sn(t){return e=>Mn(e,t)}var jn=[{format:{alpha:!1,mode:"rgb",notation:"hex",type:"int"},stringifier:yn},{format:{alpha:!0,mode:"rgb",notation:"hex",type:"int"},stringifier:Pn},{format:{alpha:!1,mode:"rgb",notation:"func",type:"int"},stringifier:En},{format:{alpha:!0,mode:"rgb",notation:"func",type:"int"},stringifier:kn},{format:{alpha:!1,mode:"hsl",notation:"func",type:"int"},stringifier:function(t){const e=[U(0),ei,ei];return`hsl(${Bi(Ji(t,"int").getComponents("hsl")).map((t,i)=>e[i](t)).join(", ")})`}},{format:{alpha:!0,mode:"hsl",notation:"func",type:"int"},stringifier:function(t){const e=[U(0),ei,ei,U(2)];return`hsla(${Ji(t,"int").getComponents("hsl").map((t,i)=>e[i](t)).join(", ")})`}},...["int","float"].reduce((t,e)=>[...t,{format:{alpha:!1,mode:"rgb",notation:"object",type:e},stringifier:Ln(e)},{format:{alpha:!0,mode:"rgb",notation:"object",type:e},stringifier:Sn(e)}],[])];function Dn(t){return jn.reduce((e,i)=>{return e||(n=i.format,s=t,n.alpha===s.alpha&&n.mode===s.mode&&n.notation===s.notation&&n.type===s.type?i.stringifier:null);var n,s},null)}var An=Mt("apl"),On=class{constructor(t,e){this.onValueChange_=this.onValueChange_.bind(this),this.value=e.value,this.value.emitter.on("change",this.onValueChange_),this.element=t.createElement("div"),this.element.classList.add(An()),e.viewProps.bindClassModifiers(this.element),e.viewProps.bindTabIndex(this.element);const i=t.createElement("div");i.classList.add(An("b")),this.element.appendChild(i);const n=t.createElement("div");n.classList.add(An("c")),i.appendChild(n),this.colorElem_=n;const s=t.createElement("div");s.classList.add(An("m")),this.element.appendChild(s),this.markerElem_=s;const r=t.createElement("div");r.classList.add(An("p")),this.markerElem_.appendChild(r),this.previewElem_=r,this.update_()}update_(){const t=this.value.rawValue,e=t.getComponents("rgb"),i=new Ui([e[0],e[1],e[2],0],"rgb"),n=new Ui([e[0],e[1],e[2],255],"rgb"),s=["to right",kn(i),kn(n)];this.colorElem_.style.background=`linear-gradient(${s.join(",")})`,this.previewElem_.style.backgroundColor=kn(t);const r=F(e[3],0,1,0,100);this.markerElem_.style.left=`${r}%`}onValueChange_(){this.update_()}},Bn=class{constructor(t,e){this.onKeyDown_=this.onKeyDown_.bind(this),this.onKeyUp_=this.onKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.value=e.value,this.viewProps=e.viewProps,this.view=new On(t,{value:this.value,viewProps:this.viewProps}),this.ptHandler_=new hi(this.view.element),this.ptHandler_.emitter.on("down",this.onPointerDown_),this.ptHandler_.emitter.on("move",this.onPointerMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.element.addEventListener("keydown",this.onKeyDown_),this.view.element.addEventListener("keyup",this.onKeyUp_)}handlePointerEvent_(t,e){if(!t.point)return;const i=t.point.x/t.bounds.width,[n,s,r]=this.value.rawValue.getComponents("hsv");this.value.setRawValue(new Ui([n,s,r,i],"hsv"),e)}onPointerDown_(t){this.handlePointerEvent_(t.data,{forceEmit:!1,last:!1})}onPointerMove_(t){this.handlePointerEvent_(t.data,{forceEmit:!1,last:!1})}onPointerUp_(t){this.handlePointerEvent_(t.data,{forceEmit:!0,last:!0})}onKeyDown_(t){const e=ri(Gi(!0),ai(t));if(0===e)return;const[i,n,s,r]=this.value.rawValue.getComponents("hsv");this.value.setRawValue(new Ui([i,n,s,r+e],"hsv"),{forceEmit:!1,last:!1})}onKeyUp_(t){0!==ri(Gi(!0),ai(t))&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}},Tn=Mt("coltxt"),zn=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(Tn()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("div");i.classList.add(Tn("m")),this.modeElem_=function(t){const e=t.createElement("select");return e.appendChild([{text:"RGB",value:"rgb"},{text:"HSL",value:"hsl"},{text:"HSV",value:"hsv"},{text:"HEX",value:"hex"}].reduce((e,i)=>{const n=t.createElement("option");return n.textContent=i.text,n.value=i.value,e.appendChild(n),e},t.createDocumentFragment())),e}(t),this.modeElem_.classList.add(Tn("ms")),i.appendChild(this.modeSelectElement),e.viewProps.bindDisabled(this.modeElem_);const n=t.createElement("div");n.classList.add(Tn("mm")),n.appendChild(xt(t,"dropdown")),i.appendChild(n),this.element.appendChild(i);const s=t.createElement("div");s.classList.add(Tn("w")),this.element.appendChild(s),this.inputsElem_=s,this.inputViews_=e.inputViews,this.applyInputViews_(),kt(e.mode,t=>{this.modeElem_.value=t})}get modeSelectElement(){return this.modeElem_}get inputViews(){return this.inputViews_}set inputViews(t){this.inputViews_=t,this.applyInputViews_()}applyInputViews_(){Pt(this.inputsElem_);const t=this.element.ownerDocument;this.inputViews_.forEach(e=>{const i=t.createElement("div");i.classList.add(Tn("c")),i.appendChild(e.element),this.inputsElem_.appendChild(i)})}};function Rn(t,e,i){const n=Ri(t,e)[i];return new x({min:0,max:n})}var Nn=class{constructor(t,e){this.onModeSelectChange_=this.onModeSelectChange_.bind(this),this.colorType_=e.colorType,this.value=e.value,this.viewProps=e.viewProps,this.colorMode=_(this.value.rawValue.mode),this.ccs_=this.createComponentControllers_(t),this.view=new zn(t,{mode:this.colorMode,inputViews:[this.ccs_[0].view,this.ccs_[1].view,this.ccs_[2].view],viewProps:this.viewProps}),this.view.modeSelectElement.addEventListener("change",this.onModeSelectChange_)}createComponentControllers_(t){const e=this.colorMode.rawValue;return function(t){return"hex"!==t}(e)?function(t,e){const i={colorMode:e.colorMode,colorType:e.colorType,parser:N,viewProps:e.viewProps};return[0,1,2].map(n=>{const s=function(t,e,i){return new ui(t,{arrayPosition:0===i?"fst":2===i?"lst":"mid",parser:e.parser,props:f.fromObject({formatter:(n=e.colorType,U("float"===n?2:0)),keyScale:Gi(!1),pointerScale:"float"===e.colorType?.01:1}),value:_(0,{constraint:Rn(e.colorMode,e.colorType,i)}),viewProps:e.viewProps});var n}(t,i,n);return si({primary:e.value,secondary:s.value,forward:t=>Ji(t,e.colorType).getComponents(e.colorMode)[n],backward(t,i){const s=e.colorMode,r=Ji(t,e.colorType).getComponents(s);return r[n]=i,Ji(Qi(Ti(Bi(r),r[3]),s,e.colorType),"int")}}),s})}(t,{colorMode:e,colorType:this.colorType_,value:this.value,viewProps:this.viewProps}):function(t,e){const i=new Qe(t,{parser:fn("int"),props:f.fromObject({formatter:yn}),value:_(Ui.black()),viewProps:e.viewProps});return si({primary:e.value,secondary:i.value,forward:t=>new Ui(Bi(t.getComponents()),t.mode),backward:(t,e)=>new Ui(Ti(Bi(e.getComponents(t.mode)),t.getComponents()[3]),t.mode)}),[i]}(t,{value:this.value,viewProps:this.viewProps})}onModeSelectChange_(t){const e=t.currentTarget;this.colorMode.rawValue=e.value,this.ccs_=this.createComponentControllers_(this.view.element.ownerDocument),this.view.inputViews=this.ccs_.map(t=>t.view)}},Kn=Mt("hpl"),In=class{constructor(t,e){this.onValueChange_=this.onValueChange_.bind(this),this.value=e.value,this.value.emitter.on("change",this.onValueChange_),this.element=t.createElement("div"),this.element.classList.add(Kn()),e.viewProps.bindClassModifiers(this.element),e.viewProps.bindTabIndex(this.element);const i=t.createElement("div");i.classList.add(Kn("c")),this.element.appendChild(i);const n=t.createElement("div");n.classList.add(Kn("m")),this.element.appendChild(n),this.markerElem_=n,this.update_()}update_(){const[t]=this.value.rawValue.getComponents("hsv");this.markerElem_.style.backgroundColor=En(new Ui([t,100,100],"hsv"));const e=F(t,0,360,0,100);this.markerElem_.style.left=`${e}%`}onValueChange_(){this.update_()}},Un=class{constructor(t,e){this.onKeyDown_=this.onKeyDown_.bind(this),this.onKeyUp_=this.onKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.value=e.value,this.viewProps=e.viewProps,this.view=new In(t,{value:this.value,viewProps:this.viewProps}),this.ptHandler_=new hi(this.view.element),this.ptHandler_.emitter.on("down",this.onPointerDown_),this.ptHandler_.emitter.on("move",this.onPointerMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.element.addEventListener("keydown",this.onKeyDown_),this.view.element.addEventListener("keyup",this.onKeyUp_)}handlePointerEvent_(t,e){if(!t.point)return;const i=F(q(t.point.x,0,t.bounds.width),0,t.bounds.width,0,360),[,n,s,r]=this.value.rawValue.getComponents("hsv");this.value.setRawValue(new Ui([i,n,s,r],"hsv"),e)}onPointerDown_(t){this.handlePointerEvent_(t.data,{forceEmit:!1,last:!1})}onPointerMove_(t){this.handlePointerEvent_(t.data,{forceEmit:!1,last:!1})}onPointerUp_(t){this.handlePointerEvent_(t.data,{forceEmit:!0,last:!0})}onKeyDown_(t){const e=ri(Gi(!1),ai(t));if(0===e)return;const[i,n,s,r]=this.value.rawValue.getComponents("hsv");this.value.setRawValue(new Ui([i+e,n,s,r],"hsv"),{forceEmit:!1,last:!1})}onKeyUp_(t){0!==ri(Gi(!1),ai(t))&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}},Fn=Mt("svp"),$n=class{constructor(t,e){this.onValueChange_=this.onValueChange_.bind(this),this.value=e.value,this.value.emitter.on("change",this.onValueChange_),this.element=t.createElement("div"),this.element.classList.add(Fn()),e.viewProps.bindClassModifiers(this.element),e.viewProps.bindTabIndex(this.element);const i=t.createElement("canvas");i.height=64,i.width=64,i.classList.add(Fn("c")),this.element.appendChild(i),this.canvasElement=i;const n=t.createElement("div");n.classList.add(Fn("m")),this.element.appendChild(n),this.markerElem_=n,this.update_()}update_(){const t=function(t){const e=t.ownerDocument.defaultView;return e&&"document"in e?t.getContext("2d",{willReadFrequently:!0}):null}(this.canvasElement);if(!t)return;const e=this.value.rawValue.getComponents("hsv"),i=this.canvasElement.width,n=this.canvasElement.height,s=t.getImageData(0,0,i,n),r=s.data;for(let l=0;lt.getComponents()[3],backward:(t,e)=>{const i=t.getComponents();return i[3]=e,new Ui(i,t.mode)}}),this.textsC_=new Nn(t,{colorType:e.colorType,value:this.value,viewProps:this.viewProps}),this.view=new $i(t,{alphaViews:this.alphaIcs_?{palette:this.alphaIcs_.palette.view,text:this.alphaIcs_.text.view}:null,hPaletteView:this.hPaletteC_.view,supportsAlpha:e.supportsAlpha,svPaletteView:this.svPaletteC_.view,textsView:this.textsC_.view,viewProps:this.viewProps})}get textsController(){return this.textsC_}},Gn=Mt("colsw"),Yn=class{constructor(t,e){this.onValueChange_=this.onValueChange_.bind(this),e.value.emitter.on("change",this.onValueChange_),this.value=e.value,this.element=t.createElement("div"),this.element.classList.add(Gn()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("div");i.classList.add(Gn("sw")),this.element.appendChild(i),this.swatchElem_=i;const n=t.createElement("button");n.classList.add(Gn("b")),e.viewProps.bindDisabled(n),this.element.appendChild(n),this.buttonElement=n,this.update_()}update_(){const t=this.value.rawValue;this.swatchElem_.style.backgroundColor=Pn(t)}onValueChange_(){this.update_()}},Xn=class{constructor(t,e){this.value=e.value,this.viewProps=e.viewProps,this.view=new Yn(t,{value:this.value,viewProps:this.viewProps})}},Wn=class{constructor(t,e){this.onButtonBlur_=this.onButtonBlur_.bind(this),this.onButtonClick_=this.onButtonClick_.bind(this),this.onPopupChildBlur_=this.onPopupChildBlur_.bind(this),this.onPopupChildKeydown_=this.onPopupChildKeydown_.bind(this),this.value=e.value,this.viewProps=e.viewProps,this.foldable_=he.create(e.expanded),this.swatchC_=new Xn(t,{value:this.value,viewProps:this.viewProps});const i=this.swatchC_.view.buttonElement;i.addEventListener("blur",this.onButtonBlur_),i.addEventListener("click",this.onButtonClick_),this.textC_=new Qe(t,{parser:e.parser,props:f.fromObject({formatter:e.formatter}),value:this.value,viewProps:this.viewProps}),this.view=new Ai(t,{foldable:this.foldable_,pickerLayout:e.pickerLayout}),this.view.swatchElement.appendChild(this.swatchC_.view.element),this.view.textElement.appendChild(this.textC_.view.element),this.popC_="popup"===e.pickerLayout?new Ye(t,{viewProps:this.viewProps}):null;const n=new Hn(t,{colorType:e.colorType,supportsAlpha:e.supportsAlpha,value:this.value,viewProps:this.viewProps});n.view.allFocusableElements.forEach(t=>{t.addEventListener("blur",this.onPopupChildBlur_),t.addEventListener("keydown",this.onPopupChildKeydown_)}),this.pickerC_=n,this.popC_?(this.view.element.appendChild(this.popC_.view.element),this.popC_.view.element.appendChild(n.view.element),si({primary:this.foldable_.value("expanded"),secondary:this.popC_.shows,forward:t=>t,backward:(t,e)=>e})):this.view.pickerElement&&(this.view.pickerElement.appendChild(this.pickerC_.view.element),de(this.foldable_,this.view.pickerElement))}get textController(){return this.textC_}onButtonBlur_(t){if(!this.popC_)return;const e=this.view.element,i=t.relatedTarget;i&&e.contains(i)||(this.popC_.shows.rawValue=!1)}onButtonClick_(){this.foldable_.set("expanded",!this.foldable_.get("expanded")),this.foldable_.get("expanded")&&this.pickerC_.view.allFocusableElements[0].focus()}onPopupChildBlur_(t){if(!this.popC_)return;const e=this.popC_.view.element,i=Et(t);i&&e.contains(i)||i&&i===this.swatchC_.view.buttonElement&&!_t(e.ownerDocument)||(this.popC_.shows.rawValue=!1)}onPopupChildKeydown_(t){this.popC_?"Escape"===t.key&&(this.popC_.shows.rawValue=!1):this.view.pickerElement&&"Escape"===t.key&&this.swatchC_.view.buttonElement.focus()}};function Qn(t){return Bi(t.getComponents("rgb")).reduce((t,e)=>t<<8|255&Math.floor(e),0)}function Jn(t){return t.getComponents("rgb").reduce((t,e,i)=>t<<8|255&Math.floor(3===i?255*e:e),0)>>>0}function Zn(t){return"number"!=typeof t?Ui.black():new Ui([(e=t)>>16&255,e>>8&255,255&e],"rgb");var e}function ts(t){return"number"!=typeof t?Ui.black():new Ui([(e=t)>>24&255,e>>16&255,e>>8&255,F(255&e,0,255,0,1)],"rgb");var e}function es(t,e){return"object"==typeof t&&!o(t)&&e in t&&"number"==typeof t[e]}function is(t){return es(t,"r")&&es(t,"g")&&es(t,"b")}function ns(t){return is(t)&&es(t,"a")}function ss(t){return is(t)}function rs(t,e){if(t.mode!==e.mode)return!1;if(t.type!==e.type)return!1;const i=t.getComponents(),n=e.getComponents();for(let s=0;s{if("number"!=typeof t)return null;if(!function(t){return"color"in t||"color"===t.view}(e))return null;const i=Hi(e);return i?{initialValue:t,params:Object.assign(Object.assign({},i),{supportsAlpha:(n=e,!!(null===(s=null==n?void 0:n.color)||void 0===s?void 0:s.alpha))})}:null;var n,s},binding:{reader:t=>t.params.supportsAlpha?ts:Zn,equals:rs,writer:t=>function(t){const e=t?Jn:Qn;return(t,i)=>{Vi(t,e(i))}}(t.params.supportsAlpha)},controller:t=>{var e,i,n;return new Wn(t.document,{colorType:"int",expanded:null!==(e=t.params.expanded)&&void 0!==e&&e,formatter:(n=t.params.supportsAlpha,n?t=>Pn(t,"0x"):t=>yn(t,"0x")),parser:fn("int"),pickerLayout:null!==(i=t.params.picker)&&void 0!==i?i:"popup",supportsAlpha:t.params.supportsAlpha,value:t.value,viewProps:t.viewProps})}});function ls(t,e){return i=>t?Mn(i,e):Vn(i,e)}var ps=Zt({id:"input-color-object",type:"input",accept:(t,e)=>{var i;if(!ss(t))return null;const n=Hi(e);return n?{initialValue:t,params:Object.assign(Object.assign({},n),{colorType:null!==(i=Yi(e))&&void 0!==i?i:"int"})}:null},binding:{reader:t=>{return e=t.params.colorType,t=>Ji(function(t,e){return ss(t)?"int"===e?new Ui(os(t),"rgb"):"float"===e?new Xi(os(t),"rgb"):Ji(Ui.black(),"int"):Ji(Ui.black(),e)}(t,e),"int");var e},equals:rs,writer:t=>{return e=ns(t.initialValue),i=t.params.colorType,(t,n)=>{e?function(t,e,i){const n=Ji(e,i).toRgbaObject();t.writeProperty("r",n.r),t.writeProperty("g",n.g),t.writeProperty("b",n.b),t.writeProperty("a",n.a)}(t,n,i):function(t,e,i){const n=Ji(e,i).toRgbaObject();t.writeProperty("r",n.r),t.writeProperty("g",n.g),t.writeProperty("b",n.b)}(t,n,i)};var e,i}},controller:t=>{var e,i;const n=ns(t.initialValue);return new Wn(t.document,{colorType:t.params.colorType,expanded:null!==(e=t.params.expanded)&&void 0!==e&&e,formatter:ls(n,t.params.colorType),parser:fn("int"),pickerLayout:null!==(i=t.params.picker)&&void 0!==i?i:"popup",supportsAlpha:n,value:t.value,viewProps:t.viewProps})}}),hs=Zt({id:"input-color-string",type:"input",accept:(t,e)=>{if("string"!=typeof t)return null;if("text"===e.view)return null;const i=function(t,e="int"){const i=function(t){return _n.reduce((e,{parser:i,result:n})=>e||(i(t)?n:null),null)}(t);return i?"hex"===i.notation&&"float"!==e?Object.assign(Object.assign({},i),{type:"int"}):"func"===i.notation?Object.assign(Object.assign({},i),{type:e}):null:null}(t,Yi(e));if(!i)return null;const n=Dn(i);if(!n)return null;const s=Hi(e);return s?{initialValue:t,params:Object.assign(Object.assign({},s),{format:i,stringifier:n})}:null},binding:{reader:()=>xn,equals:rs,writer:t=>{const e=function(t){const e=Dn(t);return e?(t,i)=>{Vi(t,e(i))}:null}(t.params.format);if(!e)throw u.notBindable();return e}},controller:t=>{var e,i;return new Wn(t.document,{colorType:t.params.format.type,expanded:null!==(e=t.params.expanded)&&void 0!==e&&e,formatter:t.params.stringifier,parser:fn("int"),pickerLayout:null!==(i=t.params.picker)&&void 0!==i?i:"popup",supportsAlpha:t.params.format.alpha,value:t.value,viewProps:t.viewProps})}}),cs=class{constructor(t){this.components=t.components,this.asm_=t.assembly}constrain(t){const e=this.asm_.toComponents(t).map((t,e)=>{var i,n;return null!==(n=null===(i=this.components[e])||void 0===i?void 0:i.constrain(t))&&void 0!==n?n:t});return this.asm_.fromComponents(e)}},ds=Mt("pndtxt"),us=class{constructor(t,e){this.textViews=e.textViews,this.element=t.createElement("div"),this.element.classList.add(ds()),this.textViews.forEach(e=>{const i=t.createElement("div");i.classList.add(ds("a")),i.appendChild(e.element),this.element.appendChild(i)})}},vs=class{constructor(t,e){this.value=e.value,this.viewProps=e.viewProps,this.acs_=e.axes.map((i,n)=>function(t,e,i){return new ui(t,{arrayPosition:0===i?"fst":i===e.axes.length-1?"lst":"mid",parser:e.parser,props:e.axes[i].textProps,value:_(0,{constraint:e.axes[i].constraint}),viewProps:e.viewProps})}(t,e,n)),this.acs_.forEach((t,i)=>{si({primary:this.value,secondary:t.value,forward:t=>e.assembly.toComponents(t)[i],backward:(t,n)=>{const s=e.assembly.toComponents(t);return s[i]=n,e.assembly.fromComponents(s)}})}),this.view=new us(t,{textViews:this.acs_.map(t=>t.view)})}get textControllers(){return this.acs_}},ms=class extends at{get max(){return this.controller.valueController.sliderController.props.get("max")}set max(t){this.controller.valueController.sliderController.props.set("max",t)}get min(){return this.controller.valueController.sliderController.props.get("min")}set min(t){this.controller.valueController.sliderController.props.set("min",t)}},bs=Zt({id:"input-number",type:"input",accept:(t,e)=>{if("number"!=typeof t)return null;const i=dt(e,t=>Object.assign(Object.assign({},Z(t)),{options:t.optional.custom(Ke),readonly:t.optional.constant(!1)}));return i?{initialValue:t,params:i}:null},binding:{reader:t=>K,constraint:t=>function(t,e){const i=[],n=W(t,e);n&&i.push(n);const s=Q(t);s&&i.push(s);const r=Ue(t.options);return r&&i.push(r),new ze(i)}(t.params,t.initialValue),writer:t=>Vi},controller:t=>{const e=t.value,i=t.constraint,n=i&&Re(i,Ne);if(n)return new qe(t.document,{props:new f({options:n.values.value("options")}),value:e,viewProps:t.viewProps});const s=J(t.params,e.rawValue),r=i&&Re(i,x);return r?new _i(t.document,Object.assign(Object.assign({},fi(Object.assign(Object.assign({},s),{keyScale:_(s.keyScale),max:r.values.value("max"),min:r.values.value("min")}))),{parser:N,value:e,viewProps:t.viewProps})):new ui(t.document,{parser:N,props:f.fromObject(s),value:e,viewProps:t.viewProps})},api:t=>"number"!=typeof t.controller.value.rawValue?null:t.controller.valueController instanceof _i?new ms(t.controller):t.controller.valueController instanceof qe?new Oe(t.controller):null}),gs=class{constructor(t=0,e=0){this.x=t,this.y=e}getComponents(){return[this.x,this.y]}static isObject(t){if(o(t))return!1;const e=t.x,i=t.y;return"number"==typeof e&&"number"==typeof i}static equals(t,e){return t.x===e.x&&t.y===e.y}toObject(){return{x:this.x,y:this.y}}},ws={toComponents:t=>t.getComponents(),fromComponents:t=>new gs(...t)},_s=Mt("p2d"),fs=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(_s()),e.viewProps.bindClassModifiers(this.element),kt(e.expanded,qt(this.element,_s(void 0,"expanded")));const i=t.createElement("div");i.classList.add(_s("h")),this.element.appendChild(i);const n=t.createElement("button");n.classList.add(_s("b")),n.appendChild(xt(t,"p2dpad")),e.viewProps.bindDisabled(n),i.appendChild(n),this.buttonElement=n;const s=t.createElement("div");if(s.classList.add(_s("t")),i.appendChild(s),this.textElement=s,"inline"===e.pickerLayout){const e=t.createElement("div");e.classList.add(_s("p")),this.element.appendChild(e),this.pickerElement=e}else this.pickerElement=null}},xs=Mt("p2dp"),Cs=class{constructor(t,e){this.onFoldableChange_=this.onFoldableChange_.bind(this),this.onPropsChange_=this.onPropsChange_.bind(this),this.onValueChange_=this.onValueChange_.bind(this),this.props_=e.props,this.props_.emitter.on("change",this.onPropsChange_),this.element=t.createElement("div"),this.element.classList.add(xs()),"popup"===e.layout&&this.element.classList.add(xs(void 0,"p")),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("div");i.classList.add(xs("p")),e.viewProps.bindTabIndex(i),this.element.appendChild(i),this.padElement=i;const n=t.createElementNS(gt,"svg");n.classList.add(xs("g")),this.padElement.appendChild(n),this.svgElem_=n;const s=t.createElementNS(gt,"line");s.classList.add(xs("ax")),s.setAttributeNS(null,"x1","0"),s.setAttributeNS(null,"y1","50%"),s.setAttributeNS(null,"x2","100%"),s.setAttributeNS(null,"y2","50%"),this.svgElem_.appendChild(s);const r=t.createElementNS(gt,"line");r.classList.add(xs("ax")),r.setAttributeNS(null,"x1","50%"),r.setAttributeNS(null,"y1","0"),r.setAttributeNS(null,"x2","50%"),r.setAttributeNS(null,"y2","100%"),this.svgElem_.appendChild(r);const o=t.createElementNS(gt,"line");o.classList.add(xs("l")),o.setAttributeNS(null,"x1","50%"),o.setAttributeNS(null,"y1","50%"),this.svgElem_.appendChild(o),this.lineElem_=o;const a=t.createElement("div");a.classList.add(xs("m")),this.padElement.appendChild(a),this.markerElem_=a,e.value.emitter.on("change",this.onValueChange_),this.value=e.value,this.update_()}get allFocusableElements(){return[this.padElement]}update_(){const[t,e]=this.value.rawValue.getComponents(),i=this.props_.get("max"),n=F(t,-i,+i,0,100),s=F(e,-i,+i,0,100),r=this.props_.get("invertsY")?100-s:s;this.lineElem_.setAttributeNS(null,"x2",`${n}%`),this.lineElem_.setAttributeNS(null,"y2",`${r}%`),this.markerElem_.style.left=`${n}%`,this.markerElem_.style.top=`${r}%`}onValueChange_(){this.update_()}onPropsChange_(){this.update_()}onFoldableChange_(){this.update_()}};function ys(t,e,i){return[ri(e[0],ai(t)),ri(e[1],oi(t))*(i?1:-1)]}var Ps=class{constructor(t,e){this.onPadKeyDown_=this.onPadKeyDown_.bind(this),this.onPadKeyUp_=this.onPadKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.props=e.props,this.value=e.value,this.viewProps=e.viewProps,this.view=new Cs(t,{layout:e.layout,props:this.props,value:this.value,viewProps:this.viewProps}),this.ptHandler_=new hi(this.view.padElement),this.ptHandler_.emitter.on("down",this.onPointerDown_),this.ptHandler_.emitter.on("move",this.onPointerMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.padElement.addEventListener("keydown",this.onPadKeyDown_),this.view.padElement.addEventListener("keyup",this.onPadKeyUp_)}handlePointerEvent_(t,e){if(!t.point)return;const i=this.props.get("max"),n=F(t.point.x,0,t.bounds.width,-i,+i),s=F(this.props.get("invertsY")?t.bounds.height-t.point.y:t.point.y,0,t.bounds.height,-i,+i);this.value.setRawValue(new gs(n,s),e)}onPointerDown_(t){this.handlePointerEvent_(t.data,{forceEmit:!1,last:!1})}onPointerMove_(t){this.handlePointerEvent_(t.data,{forceEmit:!1,last:!1})}onPointerUp_(t){this.handlePointerEvent_(t.data,{forceEmit:!0,last:!0})}onPadKeyDown_(t){li(t.key)&&t.preventDefault();const[e,i]=ys(t,[this.props.get("xKeyScale"),this.props.get("yKeyScale")],this.props.get("invertsY"));0===e&&0===i||this.value.setRawValue(new gs(this.value.rawValue.x+e,this.value.rawValue.y+i),{forceEmit:!1,last:!1})}onPadKeyUp_(t){const[e,i]=ys(t,[this.props.get("xKeyScale"),this.props.get("yKeyScale")],this.props.get("invertsY"));0===e&&0===i||this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}},Es=class{constructor(t,e){var i,n;this.onPopupChildBlur_=this.onPopupChildBlur_.bind(this),this.onPopupChildKeydown_=this.onPopupChildKeydown_.bind(this),this.onPadButtonBlur_=this.onPadButtonBlur_.bind(this),this.onPadButtonClick_=this.onPadButtonClick_.bind(this),this.value=e.value,this.viewProps=e.viewProps,this.foldable_=he.create(e.expanded),this.popC_="popup"===e.pickerLayout?new Ye(t,{viewProps:this.viewProps}):null;const s=new Ps(t,{layout:e.pickerLayout,props:new f({invertsY:_(e.invertsY),max:_(e.max),xKeyScale:e.axes[0].textProps.value("keyScale"),yKeyScale:e.axes[1].textProps.value("keyScale")}),value:this.value,viewProps:this.viewProps});s.view.allFocusableElements.forEach(t=>{t.addEventListener("blur",this.onPopupChildBlur_),t.addEventListener("keydown",this.onPopupChildKeydown_)}),this.pickerC_=s,this.textC_=new vs(t,{assembly:ws,axes:e.axes,parser:e.parser,value:this.value,viewProps:this.viewProps}),this.view=new fs(t,{expanded:this.foldable_.value("expanded"),pickerLayout:e.pickerLayout,viewProps:this.viewProps}),this.view.textElement.appendChild(this.textC_.view.element),null===(i=this.view.buttonElement)||void 0===i||i.addEventListener("blur",this.onPadButtonBlur_),null===(n=this.view.buttonElement)||void 0===n||n.addEventListener("click",this.onPadButtonClick_),this.popC_?(this.view.element.appendChild(this.popC_.view.element),this.popC_.view.element.appendChild(this.pickerC_.view.element),si({primary:this.foldable_.value("expanded"),secondary:this.popC_.shows,forward:t=>t,backward:(t,e)=>e})):this.view.pickerElement&&(this.view.pickerElement.appendChild(this.pickerC_.view.element),de(this.foldable_,this.view.pickerElement))}get textController(){return this.textC_}onPadButtonBlur_(t){if(!this.popC_)return;const e=this.view.element,i=t.relatedTarget;i&&e.contains(i)||(this.popC_.shows.rawValue=!1)}onPadButtonClick_(){this.foldable_.set("expanded",!this.foldable_.get("expanded")),this.foldable_.get("expanded")&&this.pickerC_.view.allFocusableElements[0].focus()}onPopupChildBlur_(t){if(!this.popC_)return;const e=this.popC_.view.element,i=Et(t);i&&e.contains(i)||i&&i===this.view.buttonElement&&!_t(e.ownerDocument)||(this.popC_.shows.rawValue=!1)}onPopupChildKeydown_(t){this.popC_?"Escape"===t.key&&(this.popC_.shows.rawValue=!1):this.view.pickerElement&&"Escape"===t.key&&this.view.buttonElement.focus()}};function ks(t){return gs.isObject(t)?new gs(t.x,t.y):new gs}function Vs(t,e){t.writeProperty("x",e.x),t.writeProperty("y",e.y)}function Ls(t,e){var i,n;if(!o(t.min)||!o(t.max))return Math.max(Math.abs(null!==(i=t.min)&&void 0!==i?i:0),Math.abs(null!==(n=t.max)&&void 0!==n?n:0));const s=Y(t);return Math.max(10*Math.abs(s),10*Math.abs(e))}function Ms(t,e){var i,n;const s=Ls(h(t,null!==(i=t.x)&&void 0!==i?i:{}),e.x),r=Ls(h(t,null!==(n=t.y)&&void 0!==n?n:{}),e.y);return Math.max(s,r)}function Ss(t){if(!("y"in t))return!1;const e=t.y;return!!e&&"inverted"in e&&!!e.inverted}var js=Zt({id:"input-point2d",type:"input",accept:(t,e)=>{if(!gs.isObject(t))return null;const i=dt(e,t=>Object.assign(Object.assign({},yi(t)),{expanded:t.optional.boolean,picker:t.optional.custom(ki),readonly:t.optional.constant(!1),x:t.optional.custom(Pi),y:t.optional.object(Object.assign(Object.assign({},yi(t)),{inverted:t.optional.boolean}))}));return i?{initialValue:t,params:i}:null},binding:{reader:()=>ks,constraint:t=>{return e=t.params,i=t.initialValue,new cs({assembly:ws,components:[Ei(Object.assign(Object.assign({},e),e.x),i.x),Ei(Object.assign(Object.assign({},e),e.y),i.y)]});var e,i},equals:gs.equals,writer:()=>Vs},controller:t=>{var e,i;const n=t.document,s=t.value,r=t.constraint,o=[t.params.x,t.params.y];return new Es(n,{axes:s.rawValue.getComponents().map((e,i)=>{var n;return tt({constraint:r.components[i],initialValue:e,params:h(t.params,null!==(n=o[i])&&void 0!==n?n:{})})}),expanded:null!==(e=t.params.expanded)&&void 0!==e&&e,invertsY:Ss(t.params),max:Ms(t.params,s.rawValue),parser:N,pickerLayout:null!==(i=t.params.picker)&&void 0!==i?i:"popup",value:s,viewProps:t.viewProps})}}),Ds=class{constructor(t=0,e=0,i=0){this.x=t,this.y=e,this.z=i}getComponents(){return[this.x,this.y,this.z]}static isObject(t){if(o(t))return!1;const e=t.x,i=t.y,n=t.z;return"number"==typeof e&&"number"==typeof i&&"number"==typeof n}static equals(t,e){return t.x===e.x&&t.y===e.y&&t.z===e.z}toObject(){return{x:this.x,y:this.y,z:this.z}}},As={toComponents:t=>t.getComponents(),fromComponents:t=>new Ds(...t)};function Os(t){return Ds.isObject(t)?new Ds(t.x,t.y,t.z):new Ds}function Bs(t,e){t.writeProperty("x",e.x),t.writeProperty("y",e.y),t.writeProperty("z",e.z)}var Ts=Zt({id:"input-point3d",type:"input",accept:(t,e)=>{if(!Ds.isObject(t))return null;const i=dt(e,t=>Object.assign(Object.assign({},yi(t)),{readonly:t.optional.constant(!1),x:t.optional.custom(Pi),y:t.optional.custom(Pi),z:t.optional.custom(Pi)}));return i?{initialValue:t,params:i}:null},binding:{reader:t=>Os,constraint:t=>{return e=t.params,i=t.initialValue,new cs({assembly:As,components:[Ei(Object.assign(Object.assign({},e),e.x),i.x),Ei(Object.assign(Object.assign({},e),e.y),i.y),Ei(Object.assign(Object.assign({},e),e.z),i.z)]});var e,i},equals:Ds.equals,writer:t=>Bs},controller:t=>{const e=t.value,i=t.constraint,n=[t.params.x,t.params.y,t.params.z];return new vs(t.document,{assembly:As,axes:e.rawValue.getComponents().map((e,s)=>{var r;return tt({constraint:i.components[s],initialValue:e,params:h(t.params,null!==(r=n[s])&&void 0!==r?r:{})})}),parser:N,value:e,viewProps:t.viewProps})}}),zs=class{constructor(t=0,e=0,i=0,n=0){this.x=t,this.y=e,this.z=i,this.w=n}getComponents(){return[this.x,this.y,this.z,this.w]}static isObject(t){if(o(t))return!1;const e=t.x,i=t.y,n=t.z,s=t.w;return"number"==typeof e&&"number"==typeof i&&"number"==typeof n&&"number"==typeof s}static equals(t,e){return t.x===e.x&&t.y===e.y&&t.z===e.z&&t.w===e.w}toObject(){return{x:this.x,y:this.y,z:this.z,w:this.w}}},Rs={toComponents:t=>t.getComponents(),fromComponents:t=>new zs(...t)};function Ns(t){return zs.isObject(t)?new zs(t.x,t.y,t.z,t.w):new zs}function Ks(t,e){t.writeProperty("x",e.x),t.writeProperty("y",e.y),t.writeProperty("z",e.z),t.writeProperty("w",e.w)}var Is=Zt({id:"input-point4d",type:"input",accept:(t,e)=>{if(!zs.isObject(t))return null;const i=dt(e,t=>Object.assign(Object.assign({},yi(t)),{readonly:t.optional.constant(!1),w:t.optional.custom(Pi),x:t.optional.custom(Pi),y:t.optional.custom(Pi),z:t.optional.custom(Pi)}));return i?{initialValue:t,params:i}:null},binding:{reader:t=>Ns,constraint:t=>{return e=t.params,i=t.initialValue,new cs({assembly:Rs,components:[Ei(Object.assign(Object.assign({},e),e.x),i.x),Ei(Object.assign(Object.assign({},e),e.y),i.y),Ei(Object.assign(Object.assign({},e),e.z),i.z),Ei(Object.assign(Object.assign({},e),e.w),i.w)]});var e,i},equals:zs.equals,writer:t=>Ks},controller:t=>{const e=t.value,i=t.constraint,n=[t.params.x,t.params.y,t.params.z,t.params.w];return new vs(t.document,{assembly:Rs,axes:e.rawValue.getComponents().map((e,s)=>{var r;return tt({constraint:i.components[s],initialValue:e,params:h(t.params,null!==(r=n[s])&&void 0!==r?r:{})})}),parser:N,value:e,viewProps:t.viewProps})}}),Us=Zt({id:"input-string",type:"input",accept:(t,e)=>{if("string"!=typeof t)return null;const i=dt(e,t=>({readonly:t.optional.constant(!1),options:t.optional.custom(Ke)}));return i?{initialValue:t,params:i}:null},binding:{reader:t=>ii,constraint:t=>function(t){const e=[],i=Ue(t.options);return i&&e.push(i),new ze(e)}(t.params),writer:t=>Vi},controller:t=>{const e=t.document,i=t.value,n=t.constraint,s=n&&Re(n,Ne);return s?new qe(e,{props:new f({options:s.values.value("options")}),value:i,viewProps:t.viewProps}):new Qe(e,{parser:t=>t,props:f.fromObject({formatter:ni}),value:i,viewProps:t.viewProps})},api:t=>"string"!=typeof t.controller.value.rawValue?null:t.controller.valueController instanceof qe?new Oe(t.controller):null}),Fs=200,$s=3,qs=Mt("mll"),Hs=class{constructor(t,e){this.onValueUpdate_=this.onValueUpdate_.bind(this),this.formatter_=e.formatter,this.element=t.createElement("div"),this.element.classList.add(qs()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("textarea");i.classList.add(qs("i")),i.style.height=`calc(var(${Ci("containerUnitSize")}) * ${e.rows})`,i.readOnly=!0,e.viewProps.bindDisabled(i),this.element.appendChild(i),this.textareaElem_=i,e.value.emitter.on("change",this.onValueUpdate_),this.value=e.value,this.update_()}update_(){const t=this.textareaElem_,e=t.scrollTop===t.scrollHeight-t.clientHeight,i=[];this.value.rawValue.forEach(t=>{void 0!==t&&i.push(this.formatter_(t))}),t.textContent=i.join("\n"),e&&(t.scrollTop=t.scrollHeight)}onValueUpdate_(){this.update_()}},Gs=class{constructor(t,e){this.value=e.value,this.viewProps=e.viewProps,this.view=new Hs(t,{formatter:e.formatter,rows:e.rows,value:this.value,viewProps:this.viewProps})}},Ys=Mt("sgl"),Xs=class{constructor(t,e){this.onValueUpdate_=this.onValueUpdate_.bind(this),this.formatter_=e.formatter,this.element=t.createElement("div"),this.element.classList.add(Ys()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("input");i.classList.add(Ys("i")),i.readOnly=!0,i.type="text",e.viewProps.bindDisabled(i),this.element.appendChild(i),this.inputElement=i,e.value.emitter.on("change",this.onValueUpdate_),this.value=e.value,this.update_()}update_(){const t=this.value.rawValue,e=t[t.length-1];this.inputElement.value=void 0!==e?this.formatter_(e):""}onValueUpdate_(){this.update_()}},Ws=class{constructor(t,e){this.value=e.value,this.viewProps=e.viewProps,this.view=new Xs(t,{formatter:e.formatter,value:this.value,viewProps:this.viewProps})}},Qs=Zt({id:"monitor-bool",type:"monitor",accept:(t,e)=>{if("boolean"!=typeof t)return null;const i=dt(e,t=>({readonly:t.required.constant(!0),rows:t.optional.number}));return i?{initialValue:t,params:i}:null},binding:{reader:t=>Je},controller:t=>{var e;return 1===t.value.rawValue.length?new Ws(t.document,{formatter:Ze,value:t.value,viewProps:t.viewProps}):new Gs(t.document,{formatter:Ze,rows:null!==(e=t.params.rows)&&void 0!==e?e:$s,value:t.value,viewProps:t.viewProps})}}),Js=class extends at{get max(){return this.controller.valueController.props.get("max")}set max(t){this.controller.valueController.props.set("max",t)}get min(){return this.controller.valueController.props.get("min")}set min(t){this.controller.valueController.props.set("min",t)}},Zs=Mt("grl"),tr=class{constructor(t,e){this.onCursorChange_=this.onCursorChange_.bind(this),this.onValueUpdate_=this.onValueUpdate_.bind(this),this.element=t.createElement("div"),this.element.classList.add(Zs()),e.viewProps.bindClassModifiers(this.element),this.formatter_=e.formatter,this.props_=e.props,this.cursor_=e.cursor,this.cursor_.emitter.on("change",this.onCursorChange_);const i=t.createElementNS(gt,"svg");i.classList.add(Zs("g")),i.style.height=`calc(var(${Ci("containerUnitSize")}) * ${e.rows})`,this.element.appendChild(i),this.svgElem_=i;const n=t.createElementNS(gt,"polyline");this.svgElem_.appendChild(n),this.lineElem_=n;const s=t.createElement("div");s.classList.add(Zs("t"),Mt("tt")()),this.element.appendChild(s),this.tooltipElem_=s,e.value.emitter.on("change",this.onValueUpdate_),this.value=e.value,this.update_()}get graphElement(){return this.svgElem_}update_(){const{clientWidth:t,clientHeight:e}=this.element,i=this.value.rawValue.length-1,n=this.props_.get("min"),s=this.props_.get("max"),r=[];this.value.rawValue.forEach((o,a)=>{if(void 0===o)return;const l=F(a,0,i,0,t),p=F(o,n,s,e,0);r.push([l,p].join(","))}),this.lineElem_.setAttributeNS(null,"points",r.join(" "));const o=this.tooltipElem_,a=this.value.rawValue[this.cursor_.rawValue];if(void 0===a)return void o.classList.remove(Zs("t","a"));const l=F(this.cursor_.rawValue,0,i,0,t),p=F(a,n,s,e,0);o.style.left=`${l}px`,o.style.top=`${p}px`,o.textContent=`${this.formatter_(a)}`,o.classList.contains(Zs("t","a"))||(o.classList.add(Zs("t","a"),Zs("t","in")),wt(o),o.classList.remove(Zs("t","in")))}onValueUpdate_(){this.update_()}onCursorChange_(){this.update_()}},er=class{constructor(t,e){if(this.onGraphMouseMove_=this.onGraphMouseMove_.bind(this),this.onGraphMouseLeave_=this.onGraphMouseLeave_.bind(this),this.onGraphPointerDown_=this.onGraphPointerDown_.bind(this),this.onGraphPointerMove_=this.onGraphPointerMove_.bind(this),this.onGraphPointerUp_=this.onGraphPointerUp_.bind(this),this.props=e.props,this.value=e.value,this.viewProps=e.viewProps,this.cursor_=_(-1),this.view=new tr(t,{cursor:this.cursor_,formatter:e.formatter,rows:e.rows,props:this.props,value:this.value,viewProps:this.viewProps}),_t(t)){const t=new hi(this.view.element);t.emitter.on("down",this.onGraphPointerDown_),t.emitter.on("move",this.onGraphPointerMove_),t.emitter.on("up",this.onGraphPointerUp_)}else this.view.element.addEventListener("mousemove",this.onGraphMouseMove_),this.view.element.addEventListener("mouseleave",this.onGraphMouseLeave_)}importProps(t){return ut(t,null,t=>({max:t.required.number,min:t.required.number}),t=>(this.props.set("max",t.max),this.props.set("min",t.min),!0))}exportProps(){return vt(null,{max:this.props.get("max"),min:this.props.get("min")})}onGraphMouseLeave_(){this.cursor_.rawValue=-1}onGraphMouseMove_(t){const{clientWidth:e}=this.view.element;this.cursor_.rawValue=Math.floor(F(t.offsetX,0,e,0,this.value.rawValue.length))}onGraphPointerDown_(t){this.onGraphPointerMove_(t)}onGraphPointerMove_(t){t.data.point?this.cursor_.rawValue=Math.floor(F(t.data.point.x,0,t.data.bounds.width,0,this.value.rawValue.length)):this.cursor_.rawValue=-1}onGraphPointerUp_(){this.cursor_.rawValue=-1}};function ir(t){return o(t.format)?U(2):t.format}function nr(t){return"graph"===t.view}var sr=Zt({id:"monitor-number",type:"monitor",accept:(t,e)=>{if("number"!=typeof t)return null;const i=dt(e,t=>({format:t.optional.function,max:t.optional.number,min:t.optional.number,readonly:t.required.constant(!0),rows:t.optional.number,view:t.optional.string}));return i?{initialValue:t,params:i}:null},binding:{defaultBufferSize:t=>nr(t)?64:1,reader:t=>K},controller:t=>nr(t.params)?function(t){var e,i,n;return new er(t.document,{formatter:ir(t.params),rows:null!==(e=t.params.rows)&&void 0!==e?e:$s,props:f.fromObject({max:null!==(i=t.params.max)&&void 0!==i?i:100,min:null!==(n=t.params.min)&&void 0!==n?n:0}),value:t.value,viewProps:t.viewProps})}(t):function(t){var e;return 1===t.value.rawValue.length?new Ws(t.document,{formatter:ir(t.params),value:t.value,viewProps:t.viewProps}):new Gs(t.document,{formatter:ir(t.params),rows:null!==(e=t.params.rows)&&void 0!==e?e:$s,value:t.value,viewProps:t.viewProps})}(t),api:t=>t.controller.valueController instanceof er?new Js(t.controller):null}),rr=Zt({id:"monitor-string",type:"monitor",accept:(t,e)=>{if("string"!=typeof t)return null;const i=dt(e,t=>({multiline:t.optional.boolean,readonly:t.required.constant(!0),rows:t.optional.number}));return i?{initialValue:t,params:i}:null},binding:{reader:t=>ii},controller:t=>{var e;const i=t.value;return i.rawValue.length>1||t.params.multiline?new Gs(t.document,{formatter:ni,rows:null!==(e=t.params.rows)&&void 0!==e?e:$s,value:i,viewProps:t.viewProps}):new Ws(t.document,{formatter:ni,value:i,viewProps:t.viewProps})}}),or=class{constructor(t){this.target=t.target,this.reader_=t.reader,this.writer_=t.writer}read(){return this.reader_(this.target.read())}write(t){this.writer_(this.target,t)}inject(t){this.write(this.reader_(t))}},ar=class{constructor(t){this.target=t.target,this.reader_=t.reader}read(){return this.reader_(this.target.read())}},lr=class{constructor(t){this.pluginsMap_={blades:[],inputs:[],monitors:[]},this.apiCache_=t}getAll(){return[...this.pluginsMap_.blades,...this.pluginsMap_.inputs,...this.pluginsMap_.monitors]}register(t,e){if(!(i=e.core)||i.major!==Jt.major)throw u.notCompatible(t,e.id);var i;"blade"===e.type?this.pluginsMap_.blades.unshift(e):"input"===e.type?this.pluginsMap_.inputs.unshift(e):"monitor"===e.type&&this.pluginsMap_.monitors.unshift(e)}createInput_(t,e,i){return this.pluginsMap_.inputs.reduce((n,s)=>null!=n?n:function(t,e){var i;const n=t.accept(e.target.read(),e.params);if(o(n))return null;const s={target:e.target,initialValue:n.initialValue,params:n.params},r=dt(e.params,t=>({disabled:t.optional.boolean,hidden:t.optional.boolean,label:t.optional.string,tag:t.optional.string})),a=t.binding.reader(s),l=t.binding.constraint?t.binding.constraint(s):void 0,p=new or({reader:a,target:e.target,writer:t.binding.writer(s)}),h=new lt(_(a(n.initialValue),{constraint:l,equals:t.binding.equals}),p),c=t.controller({constraint:l,document:e.document,initialValue:n.initialValue,params:n.params,value:h,viewProps:fe.create({disabled:null==r?void 0:r.disabled,hidden:null==r?void 0:r.hidden})});return new Nt(e.document,{blade:pe(),props:f.fromObject({label:"label"in e.params?null!==(i=null==r?void 0:r.label)&&void 0!==i?i:null:e.target.key}),tag:null==r?void 0:r.tag,value:h,valueController:c})}(s,{document:t,target:e,params:i}),null)}createMonitor_(t,e,i){return this.pluginsMap_.monitors.reduce((n,s)=>null!=n?n:function(t,e){var i,n,s;const r=t.accept(e.target.read(),e.params);if(o(r))return null;const a={target:e.target,initialValue:r.initialValue,params:r.params},l=dt(e.params,t=>({bufferSize:t.optional.number,disabled:t.optional.boolean,hidden:t.optional.boolean,interval:t.optional.number,label:t.optional.string})),p=t.binding.reader(a),h=null!==(n=null!==(i=null==l?void 0:l.bufferSize)&&void 0!==i?i:t.binding.defaultBufferSize&&t.binding.defaultBufferSize(r.params))&&void 0!==n?n:1,c=new Ut({binding:new ar({reader:p,target:e.target}),bufferSize:h,ticker:(d=e.document,u=null==l?void 0:l.interval,0===u?new Be:new Te(d,null!=u?u:Fs))});var d,u;const v=t.controller({document:e.document,params:r.params,value:c,viewProps:fe.create({disabled:null==l?void 0:l.disabled,hidden:null==l?void 0:l.hidden})});return v.viewProps.bindDisabled(c.ticker),v.viewProps.handleDispose(()=>{c.ticker.dispose()}),new Ft(e.document,{blade:pe(),props:f.fromObject({label:"label"in e.params?null!==(s=null==l?void 0:l.label)&&void 0!==s?s:null:e.target.key}),value:c,valueController:v})}(s,{document:t,params:i,target:e}),null)}createBinding(t,e,i){if(o(e.read()))throw new u({context:{key:e.key},type:"nomatchingcontroller"});const n=this.createInput_(t,e,i);if(n)return n;const s=this.createMonitor_(t,e,i);if(s)return s;throw new u({context:{key:e.key},type:"nomatchingcontroller"})}createBlade(t,e){const i=this.pluginsMap_.blades.reduce((i,n)=>null!=i?i:function(t,e){const i=t.accept(e.params);if(!i)return null;const n=dt(e.params,t=>({disabled:t.optional.boolean,hidden:t.optional.boolean}));return t.controller({blade:pe(),document:e.document,params:Object.assign(Object.assign({},i.params),{disabled:null==n?void 0:n.disabled,hidden:null==n?void 0:n.hidden}),viewProps:fe.create({disabled:null==n?void 0:n.disabled,hidden:null==n?void 0:n.hidden})})}(n,{document:t,params:e}),null);if(!i)throw new u({type:"nomatchingview",context:{params:e}});return i}createInputBindingApi_(t){const e=this.pluginsMap_.inputs.reduce((e,i)=>{var n,s;return e||(null!==(s=null===(n=i.api)||void 0===n?void 0:n.call(i,{controller:t}))&&void 0!==s?s:null)},null);return this.apiCache_.add(t,null!=e?e:new at(t))}createMonitorBindingApi_(t){const e=this.pluginsMap_.monitors.reduce((e,i)=>{var n,s;return e||(null!==(s=null===(n=i.api)||void 0===n?void 0:n.call(i,{controller:t}))&&void 0!==s?s:null)},null);return this.apiCache_.add(t,null!=e?e:new at(t))}createBindingApi(t){if(this.apiCache_.has(t))return this.apiCache_.get(t);if(function(t){return mt(t)&&function(t){if(!("binding"in t))return!1;const e=t.binding;return c(e)&&"read"in e&&"write"in e}(t.value)}(t))return this.createInputBindingApi_(t);if(function(t){return mt(t)&&function(t){if(!("binding"in t))return!1;const e=t.binding;return c(e)&&"read"in e&&!("write"in e)}(t.value)}(t))return this.createMonitorBindingApi_(t);throw u.shouldNeverHappen()}createApi(t){if(this.apiCache_.has(t))return this.apiCache_.get(t);if(function(t){return mt(t)&&bt(t.value)}(t))return this.createBindingApi(t);const e=this.pluginsMap_.blades.reduce((e,i)=>null!=e?e:i.api({controller:t,pool:this}),null);if(!e)throw u.shouldNeverHappen();return this.apiCache_.add(t,e)}},pr=new class{constructor(){this.map_=new Map}get(t){var e;return null!==(e=this.map_.get(t))&&void 0!==e?e:null}has(t){return this.map_.has(t)}add(t,e){return this.map_.set(t,e),t.viewProps.handleDispose(()=>{this.map_.delete(t)}),e}},hr=class extends et{constructor(t){super(t),this.emitter_=new m,this.controller.value.emitter.on("change",t=>{this.emitter_.emit("change",new nt(this,t.rawValue))})}get label(){return this.controller.labelController.props.get("label")}set label(t){this.controller.labelController.props.set("label",t)}get options(){return this.controller.valueController.props.get("options")}set options(t){this.controller.valueController.props.set("options",t)}get value(){return this.controller.value.rawValue}set value(t){this.controller.value.rawValue=t}on(t,e){const i=e.bind(this);return this.emitter_.on(t,t=>{i(t)},{key:e}),this}off(t,e){return this.emitter_.off(t,e),this}},cr=class extends et{},dr=class extends et{constructor(t){super(t),this.emitter_=new m,this.controller.value.emitter.on("change",t=>{this.emitter_.emit("change",new nt(this,t.rawValue))})}get label(){return this.controller.labelController.props.get("label")}set label(t){this.controller.labelController.props.set("label",t)}get max(){return this.controller.valueController.sliderController.props.get("max")}set max(t){this.controller.valueController.sliderController.props.set("max",t)}get min(){return this.controller.valueController.sliderController.props.get("min")}set min(t){this.controller.valueController.sliderController.props.set("min",t)}get value(){return this.controller.value.rawValue}set value(t){this.controller.value.rawValue=t}on(t,e){const i=e.bind(this);return this.emitter_.on(t,t=>{i(t)},{key:e}),this}off(t,e){return this.emitter_.off(t,e),this}},ur=class extends et{constructor(t){super(t),this.emitter_=new m,this.controller.value.emitter.on("change",t=>{this.emitter_.emit("change",new nt(this,t.rawValue))})}get label(){return this.controller.labelController.props.get("label")}set label(t){this.controller.labelController.props.set("label",t)}get formatter(){return this.controller.valueController.props.get("formatter")}set formatter(t){this.controller.valueController.props.set("formatter",t)}get value(){return this.controller.value.rawValue}set value(t){this.controller.value.rawValue=t}on(t,e){const i=e.bind(this);return this.emitter_.on(t,t=>{i(t)},{key:e}),this}off(t,e){return this.emitter_.off(t,e),this}},vr={id:"list",type:"blade",core:Jt,accept(t){const e=dt(t,t=>({options:t.required.custom(Ke),value:t.required.raw,view:t.required.constant("list"),label:t.optional.string}));return e?{params:e}:null},controller(t){const e=new Ne(Ie(t.params.options)),i=_(t.params.value,{constraint:e}),n=new qe(t.document,{props:new f({options:e.values.value("options")}),value:i,viewProps:t.viewProps});return new Tt(t.document,{blade:t.blade,props:f.fromObject({label:t.params.label}),value:i,valueController:n})},api:t=>t.controller instanceof Tt&&t.controller.valueController instanceof qe?new hr(t.controller):null},mr=class extends ue{constructor(t,e){super(t,e)}get element(){return this.controller.view.element}},br=class extends be{constructor(t,e){super(t,{expanded:e.expanded,blade:e.blade,props:e.props,root:!0,viewProps:e.viewProps})}},gr=Mt("spr"),wr=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(gr()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("hr");i.classList.add(gr("r")),this.element.appendChild(i)}},_r=class extends Bt{constructor(t,e){super(Object.assign(Object.assign({},e),{view:new wr(t,{viewProps:e.viewProps})}))}},fr={id:"separator",type:"blade",core:Jt,accept(t){const e=dt(t,t=>({view:t.required.constant("separator")}));return e?{params:e}:null},controller:t=>new _r(t.document,{blade:t.blade,viewProps:t.viewProps}),api:t=>t.controller instanceof _r?new cr(t.controller):null},xr={id:"slider",type:"blade",core:Jt,accept(t){const e=dt(t,t=>({max:t.required.number,min:t.required.number,view:t.required.constant("slider"),format:t.optional.function,label:t.optional.string,value:t.optional.number}));return e?{params:e}:null},controller(t){var e,i;const n=null!==(e=t.params.value)&&void 0!==e?e:0,s=new x({max:t.params.max,min:t.params.min}),r=_(n,{constraint:s}),o=new _i(t.document,Object.assign(Object.assign({},fi({formatter:null!==(i=t.params.format)&&void 0!==i?i:I,keyScale:_(1),max:s.values.value("max"),min:s.values.value("min"),pointerScale:X(t.params,n)})),{parser:N,value:r,viewProps:t.viewProps}));return new Tt(t.document,{blade:t.blade,props:f.fromObject({label:t.params.label}),value:r,valueController:o})},api:t=>t.controller instanceof Tt&&t.controller.valueController instanceof _i?new dr(t.controller):null},Cr={id:"text",type:"blade",core:Jt,accept(t){const e=dt(t,t=>({parse:t.required.function,value:t.required.raw,view:t.required.constant("text"),format:t.optional.function,label:t.optional.string}));return e?{params:e}:null},controller(t){var e;const i=_(t.params.value),n=new Qe(t.document,{parser:t.params.parse,props:f.fromObject({formatter:null!==(e=t.params.format)&&void 0!==e?e:t=>String(t)}),value:i,viewProps:t.viewProps});return new Tt(t.document,{blade:t.blade,props:f.fromObject({label:t.params.label}),value:i,valueController:n})},api:t=>t.controller instanceof Tt&&t.controller.valueController instanceof Qe?new ur(t.controller):null},yr=class extends mr{constructor(t){var e,i;const n=null!=t?t:{},s=null!==(e=n.document)&&void 0!==e?e:globalThis.document,r=function(){const t=new lr(pr);return[js,Ts,Is,Us,bs,hs,ps,as,ji,Qs,rr,sr,te,ge,Ae].forEach(e=>{t.register("core",e)}),t}();super(new br(s,{expanded:n.expanded,blade:pe(),props:f.fromObject({title:n.title}),viewProps:fe.create()}),r),this.pool_=r,this.containerElem_=null!==(i=n.container)&&void 0!==i?i:function(t){const e=t.createElement("div");return e.classList.add(Mt("dfw")()),t.body&&t.body.appendChild(e),e}(s),this.containerElem_.appendChild(this.element),this.doc_=s,this.usesDefaultWrapper_=!n.container,this.setUpDefaultPlugins_()}get document(){if(!this.doc_)throw u.alreadyDisposed();return this.doc_}dispose(){const t=this.containerElem_;if(!t)throw u.alreadyDisposed();if(this.usesDefaultWrapper_){const e=t.parentElement;e&&e.removeChild(t)}this.containerElem_=null,this.doc_=null,super.dispose()}registerPlugin(t){t.css&&function(t,e,i){if(t.querySelector(`style[data-tp-style=${e}]`))return;const n=t.createElement("style");n.dataset.tpStyle=e,n.textContent=i,t.head.appendChild(n)}(this.document,`plugin-${t.id}`,t.css),("plugin"in t?[t.plugin]:"plugins"in t?t.plugins:[]).forEach(e=>{this.pool_.register(t.id,e)})}setUpDefaultPlugins_(){this.registerPlugin({id:"default",css:'.tp-tbiv_b,.tp-coltxtv_ms,.tp-colswv_b,.tp-ckbv_i,.tp-sglv_i,.tp-mllv_i,.tp-grlv_g,.tp-txtv_i,.tp-p2dpv_p,.tp-colswv_sw,.tp-rotv_b,.tp-fldv_b,.tp-p2dv_b,.tp-btnv_b,.tp-lstv_s{-webkit-appearance:none;-moz-appearance:none;appearance:none;background-color:rgba(0,0,0,0);border-width:0;font-family:inherit;font-size:inherit;font-weight:inherit;margin:0;outline:none;padding:0}.tp-p2dv_b,.tp-btnv_b,.tp-lstv_s{background-color:var(--btn-bg);border-radius:var(--bld-br);color:var(--btn-fg);cursor:pointer;display:block;font-weight:bold;height:var(--cnt-usz);line-height:var(--cnt-usz);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.tp-p2dv_b:hover,.tp-btnv_b:hover,.tp-lstv_s:hover{background-color:var(--btn-bg-h)}.tp-p2dv_b:focus,.tp-btnv_b:focus,.tp-lstv_s:focus{background-color:var(--btn-bg-f)}.tp-p2dv_b:active,.tp-btnv_b:active,.tp-lstv_s:active{background-color:var(--btn-bg-a)}.tp-p2dv_b:disabled,.tp-btnv_b:disabled,.tp-lstv_s:disabled{opacity:.5}.tp-rotv_c>.tp-cntv.tp-v-lst,.tp-tbpv_c>.tp-cntv.tp-v-lst,.tp-fldv_c>.tp-cntv.tp-v-lst{margin-bottom:calc(-1*var(--cnt-vp))}.tp-rotv_c>.tp-fldv.tp-v-lst .tp-fldv_c,.tp-tbpv_c>.tp-fldv.tp-v-lst .tp-fldv_c,.tp-fldv_c>.tp-fldv.tp-v-lst .tp-fldv_c{border-bottom-left-radius:0}.tp-rotv_c>.tp-fldv.tp-v-lst .tp-fldv_b,.tp-tbpv_c>.tp-fldv.tp-v-lst .tp-fldv_b,.tp-fldv_c>.tp-fldv.tp-v-lst .tp-fldv_b{border-bottom-left-radius:0}.tp-rotv_c>*:not(.tp-v-fst),.tp-tbpv_c>*:not(.tp-v-fst),.tp-fldv_c>*:not(.tp-v-fst){margin-top:var(--cnt-usp)}.tp-rotv_c>.tp-sprv:not(.tp-v-fst),.tp-tbpv_c>.tp-sprv:not(.tp-v-fst),.tp-fldv_c>.tp-sprv:not(.tp-v-fst),.tp-rotv_c>.tp-cntv:not(.tp-v-fst),.tp-tbpv_c>.tp-cntv:not(.tp-v-fst),.tp-fldv_c>.tp-cntv:not(.tp-v-fst){margin-top:var(--cnt-vp)}.tp-rotv_c>.tp-sprv+*:not(.tp-v-hidden),.tp-tbpv_c>.tp-sprv+*:not(.tp-v-hidden),.tp-fldv_c>.tp-sprv+*:not(.tp-v-hidden),.tp-rotv_c>.tp-cntv+*:not(.tp-v-hidden),.tp-tbpv_c>.tp-cntv+*:not(.tp-v-hidden),.tp-fldv_c>.tp-cntv+*:not(.tp-v-hidden){margin-top:var(--cnt-vp)}.tp-rotv_c>.tp-sprv:not(.tp-v-hidden)+.tp-sprv,.tp-tbpv_c>.tp-sprv:not(.tp-v-hidden)+.tp-sprv,.tp-fldv_c>.tp-sprv:not(.tp-v-hidden)+.tp-sprv,.tp-rotv_c>.tp-cntv:not(.tp-v-hidden)+.tp-cntv,.tp-tbpv_c>.tp-cntv:not(.tp-v-hidden)+.tp-cntv,.tp-fldv_c>.tp-cntv:not(.tp-v-hidden)+.tp-cntv{margin-top:0}.tp-tbpv_c>.tp-cntv,.tp-fldv_c>.tp-cntv{margin-left:4px}.tp-tbpv_c>.tp-fldv>.tp-fldv_b,.tp-fldv_c>.tp-fldv>.tp-fldv_b{border-top-left-radius:var(--bld-br);border-bottom-left-radius:var(--bld-br)}.tp-tbpv_c>.tp-fldv.tp-fldv-expanded>.tp-fldv_b,.tp-fldv_c>.tp-fldv.tp-fldv-expanded>.tp-fldv_b{border-bottom-left-radius:0}.tp-tbpv_c .tp-fldv>.tp-fldv_c,.tp-fldv_c .tp-fldv>.tp-fldv_c{border-bottom-left-radius:var(--bld-br)}.tp-tbpv_c>.tp-cntv+.tp-fldv>.tp-fldv_b,.tp-fldv_c>.tp-cntv+.tp-fldv>.tp-fldv_b{border-top-left-radius:0}.tp-tbpv_c>.tp-cntv+.tp-tabv>.tp-tabv_t,.tp-fldv_c>.tp-cntv+.tp-tabv>.tp-tabv_t{border-top-left-radius:0}.tp-tbpv_c>.tp-tabv>.tp-tabv_t,.tp-fldv_c>.tp-tabv>.tp-tabv_t{border-top-left-radius:var(--bld-br)}.tp-tbpv_c .tp-tabv>.tp-tabv_c,.tp-fldv_c .tp-tabv>.tp-tabv_c{border-bottom-left-radius:var(--bld-br)}.tp-rotv_b,.tp-fldv_b{background-color:var(--cnt-bg);color:var(--cnt-fg);cursor:pointer;display:block;height:calc(var(--cnt-usz) + 4px);line-height:calc(var(--cnt-usz) + 4px);overflow:hidden;padding-left:var(--cnt-hp);padding-right:calc(4px + var(--cnt-usz) + var(--cnt-hp));position:relative;text-align:left;text-overflow:ellipsis;white-space:nowrap;width:100%;transition:border-radius .2s ease-in-out .2s}.tp-rotv_b:hover,.tp-fldv_b:hover{background-color:var(--cnt-bg-h)}.tp-rotv_b:focus,.tp-fldv_b:focus{background-color:var(--cnt-bg-f)}.tp-rotv_b:active,.tp-fldv_b:active{background-color:var(--cnt-bg-a)}.tp-rotv_b:disabled,.tp-fldv_b:disabled{opacity:.5}.tp-rotv_m,.tp-fldv_m{background:linear-gradient(to left, var(--cnt-fg), var(--cnt-fg) 2px, transparent 2px, transparent 4px, var(--cnt-fg) 4px);border-radius:2px;bottom:0;content:"";display:block;height:6px;right:calc(var(--cnt-hp) + (var(--cnt-usz) + 4px - 6px)/2 - 2px);margin:auto;opacity:.5;position:absolute;top:0;transform:rotate(90deg);transition:transform .2s ease-in-out;width:6px}.tp-rotv.tp-rotv-expanded .tp-rotv_m,.tp-fldv.tp-fldv-expanded>.tp-fldv_b>.tp-fldv_m{transform:none}.tp-rotv_c,.tp-fldv_c{box-sizing:border-box;height:0;opacity:0;overflow:hidden;padding-bottom:0;padding-top:0;position:relative;transition:height .2s ease-in-out,opacity .2s linear,padding .2s ease-in-out}.tp-rotv.tp-rotv-cpl:not(.tp-rotv-expanded) .tp-rotv_c,.tp-fldv.tp-fldv-cpl:not(.tp-fldv-expanded)>.tp-fldv_c{display:none}.tp-rotv.tp-rotv-expanded .tp-rotv_c,.tp-fldv.tp-fldv-expanded>.tp-fldv_c{opacity:1;padding-bottom:var(--cnt-vp);padding-top:var(--cnt-vp);transform:none;overflow:visible;transition:height .2s ease-in-out,opacity .2s linear .2s,padding .2s ease-in-out}.tp-txtv_i,.tp-p2dpv_p,.tp-colswv_sw{background-color:var(--in-bg);border-radius:var(--bld-br);box-sizing:border-box;color:var(--in-fg);font-family:inherit;height:var(--cnt-usz);line-height:var(--cnt-usz);min-width:0;width:100%}.tp-txtv_i:hover,.tp-p2dpv_p:hover,.tp-colswv_sw:hover{background-color:var(--in-bg-h)}.tp-txtv_i:focus,.tp-p2dpv_p:focus,.tp-colswv_sw:focus{background-color:var(--in-bg-f)}.tp-txtv_i:active,.tp-p2dpv_p:active,.tp-colswv_sw:active{background-color:var(--in-bg-a)}.tp-txtv_i:disabled,.tp-p2dpv_p:disabled,.tp-colswv_sw:disabled{opacity:.5}.tp-lstv,.tp-coltxtv_m{position:relative}.tp-lstv_s{padding:0 20px 0 4px;width:100%}.tp-lstv_m,.tp-coltxtv_mm{bottom:0;margin:auto;pointer-events:none;position:absolute;right:2px;top:0}.tp-lstv_m svg,.tp-coltxtv_mm svg{bottom:0;height:16px;margin:auto;position:absolute;right:0;top:0;width:16px}.tp-lstv_m svg path,.tp-coltxtv_mm svg path{fill:currentColor}.tp-sglv_i,.tp-mllv_i,.tp-grlv_g{background-color:var(--mo-bg);border-radius:var(--bld-br);box-sizing:border-box;color:var(--mo-fg);height:var(--cnt-usz);scrollbar-color:currentColor rgba(0,0,0,0);scrollbar-width:thin;width:100%}.tp-sglv_i::-webkit-scrollbar,.tp-mllv_i::-webkit-scrollbar,.tp-grlv_g::-webkit-scrollbar{height:8px;width:8px}.tp-sglv_i::-webkit-scrollbar-corner,.tp-mllv_i::-webkit-scrollbar-corner,.tp-grlv_g::-webkit-scrollbar-corner{background-color:rgba(0,0,0,0)}.tp-sglv_i::-webkit-scrollbar-thumb,.tp-mllv_i::-webkit-scrollbar-thumb,.tp-grlv_g::-webkit-scrollbar-thumb{background-clip:padding-box;background-color:currentColor;border:rgba(0,0,0,0) solid 2px;border-radius:4px}.tp-pndtxtv,.tp-coltxtv_w{display:flex}.tp-pndtxtv_a,.tp-coltxtv_c{width:100%}.tp-pndtxtv_a+.tp-pndtxtv_a,.tp-coltxtv_c+.tp-pndtxtv_a,.tp-pndtxtv_a+.tp-coltxtv_c,.tp-coltxtv_c+.tp-coltxtv_c{margin-left:2px}.tp-rotv{--bs-bg: var(--tp-base-background-color, hsl(230, 7%, 17%));--bs-br: var(--tp-base-border-radius, 6px);--bs-ff: var(--tp-base-font-family, Roboto Mono, Source Code Pro, Menlo, Courier, monospace);--bs-sh: var(--tp-base-shadow-color, rgba(0, 0, 0, 0.2));--bld-br: var(--tp-blade-border-radius, 2px);--bld-hp: var(--tp-blade-horizontal-padding, 4px);--bld-vw: var(--tp-blade-value-width, 160px);--btn-bg: var(--tp-button-background-color, hsl(230, 7%, 70%));--btn-bg-a: var(--tp-button-background-color-active, #d6d7db);--btn-bg-f: var(--tp-button-background-color-focus, #c8cad0);--btn-bg-h: var(--tp-button-background-color-hover, #bbbcc4);--btn-fg: var(--tp-button-foreground-color, hsl(230, 7%, 17%));--cnt-bg: var(--tp-container-background-color, rgba(187, 188, 196, 0.1));--cnt-bg-a: var(--tp-container-background-color-active, rgba(187, 188, 196, 0.25));--cnt-bg-f: var(--tp-container-background-color-focus, rgba(187, 188, 196, 0.2));--cnt-bg-h: var(--tp-container-background-color-hover, rgba(187, 188, 196, 0.15));--cnt-fg: var(--tp-container-foreground-color, hsl(230, 7%, 75%));--cnt-hp: var(--tp-container-horizontal-padding, 4px);--cnt-vp: var(--tp-container-vertical-padding, 4px);--cnt-usp: var(--tp-container-unit-spacing, 4px);--cnt-usz: var(--tp-container-unit-size, 20px);--in-bg: var(--tp-input-background-color, rgba(187, 188, 196, 0.1));--in-bg-a: var(--tp-input-background-color-active, rgba(187, 188, 196, 0.25));--in-bg-f: var(--tp-input-background-color-focus, rgba(187, 188, 196, 0.2));--in-bg-h: var(--tp-input-background-color-hover, rgba(187, 188, 196, 0.15));--in-fg: var(--tp-input-foreground-color, hsl(230, 7%, 75%));--lbl-fg: var(--tp-label-foreground-color, rgba(187, 188, 196, 0.7));--mo-bg: var(--tp-monitor-background-color, rgba(0, 0, 0, 0.2));--mo-fg: var(--tp-monitor-foreground-color, rgba(187, 188, 196, 0.7));--grv-fg: var(--tp-groove-foreground-color, rgba(187, 188, 196, 0.1))}.tp-btnv_b{width:100%}.tp-btnv_t{text-align:center}.tp-ckbv_l{display:block;position:relative}.tp-ckbv_i{left:0;opacity:0;position:absolute;top:0}.tp-ckbv_w{background-color:var(--in-bg);border-radius:var(--bld-br);cursor:pointer;display:block;height:var(--cnt-usz);position:relative;width:var(--cnt-usz)}.tp-ckbv_w svg{display:block;height:16px;inset:0;margin:auto;opacity:0;position:absolute;width:16px}.tp-ckbv_w svg path{fill:none;stroke:var(--in-fg);stroke-width:2}.tp-ckbv_i:hover+.tp-ckbv_w{background-color:var(--in-bg-h)}.tp-ckbv_i:focus+.tp-ckbv_w{background-color:var(--in-bg-f)}.tp-ckbv_i:active+.tp-ckbv_w{background-color:var(--in-bg-a)}.tp-ckbv_i:checked+.tp-ckbv_w svg{opacity:1}.tp-ckbv.tp-v-disabled .tp-ckbv_w{opacity:.5}.tp-colv{position:relative}.tp-colv_h{display:flex}.tp-colv_s{flex-grow:0;flex-shrink:0;width:var(--cnt-usz)}.tp-colv_t{flex:1;margin-left:4px}.tp-colv_p{height:0;margin-top:0;opacity:0;overflow:hidden;transition:height .2s ease-in-out,opacity .2s linear,margin .2s ease-in-out}.tp-colv.tp-colv-expanded.tp-colv-cpl .tp-colv_p{overflow:visible}.tp-colv.tp-colv-expanded .tp-colv_p{margin-top:var(--cnt-usp);opacity:1}.tp-colv .tp-popv{left:calc(-1*var(--cnt-hp));right:calc(-1*var(--cnt-hp));top:var(--cnt-usz)}.tp-colpv_h,.tp-colpv_ap{margin-left:6px;margin-right:6px}.tp-colpv_h{margin-top:var(--cnt-usp)}.tp-colpv_rgb{display:flex;margin-top:var(--cnt-usp);width:100%}.tp-colpv_a{display:flex;margin-top:var(--cnt-vp);padding-top:calc(var(--cnt-vp) + 2px);position:relative}.tp-colpv_a::before{background-color:var(--grv-fg);content:"";height:2px;left:calc(-1*var(--cnt-hp));position:absolute;right:calc(-1*var(--cnt-hp));top:0}.tp-colpv.tp-v-disabled .tp-colpv_a::before{opacity:.5}.tp-colpv_ap{align-items:center;display:flex;flex:3}.tp-colpv_at{flex:1;margin-left:4px}.tp-svpv{border-radius:var(--bld-br);outline:none;overflow:hidden;position:relative}.tp-svpv.tp-v-disabled{opacity:.5}.tp-svpv_c{cursor:crosshair;display:block;height:calc(var(--cnt-usz)*4);width:100%}.tp-svpv_m{border-radius:100%;border:rgba(255,255,255,.75) solid 2px;box-sizing:border-box;filter:drop-shadow(0 0 1px rgba(0, 0, 0, 0.3));height:12px;margin-left:-6px;margin-top:-6px;pointer-events:none;position:absolute;width:12px}.tp-svpv:focus .tp-svpv_m{border-color:#fff}.tp-hplv{cursor:pointer;height:var(--cnt-usz);outline:none;position:relative}.tp-hplv.tp-v-disabled{opacity:.5}.tp-hplv_c{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAAABCAYAAABubagXAAAAQ0lEQVQoU2P8z8Dwn0GCgQEDi2OK/RBgYHjBgIpfovFh8j8YBIgzFGQxuqEgPhaDOT5gOhPkdCxOZeBg+IDFZZiGAgCaSSMYtcRHLgAAAABJRU5ErkJggg==);background-position:left top;background-repeat:no-repeat;background-size:100% 100%;border-radius:2px;display:block;height:4px;left:0;margin-top:-2px;position:absolute;top:50%;width:100%}.tp-hplv_m{border-radius:var(--bld-br);border:rgba(255,255,255,.75) solid 2px;box-shadow:0 0 2px rgba(0,0,0,.1);box-sizing:border-box;height:12px;left:50%;margin-left:-6px;margin-top:-6px;position:absolute;top:50%;width:12px}.tp-hplv:focus .tp-hplv_m{border-color:#fff}.tp-aplv{cursor:pointer;height:var(--cnt-usz);outline:none;position:relative;width:100%}.tp-aplv.tp-v-disabled{opacity:.5}.tp-aplv_b{background-color:#fff;background-image:linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%),linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%);background-size:4px 4px;background-position:0 0,2px 2px;border-radius:2px;display:block;height:4px;left:0;margin-top:-2px;overflow:hidden;position:absolute;top:50%;width:100%}.tp-aplv_c{inset:0;position:absolute}.tp-aplv_m{background-color:#fff;background-image:linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%),linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%);background-size:12px 12px;background-position:0 0,6px 6px;border-radius:var(--bld-br);box-shadow:0 0 2px rgba(0,0,0,.1);height:12px;left:50%;margin-left:-6px;margin-top:-6px;overflow:hidden;position:absolute;top:50%;width:12px}.tp-aplv_p{border-radius:var(--bld-br);border:rgba(255,255,255,.75) solid 2px;box-sizing:border-box;inset:0;position:absolute}.tp-aplv:focus .tp-aplv_p{border-color:#fff}.tp-colswv{background-color:#fff;background-image:linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%),linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%);background-size:10px 10px;background-position:0 0,5px 5px;border-radius:var(--bld-br);overflow:hidden}.tp-colswv.tp-v-disabled{opacity:.5}.tp-colswv_sw{border-radius:0}.tp-colswv_b{cursor:pointer;display:block;height:var(--cnt-usz);left:0;position:absolute;top:0;width:var(--cnt-usz)}.tp-colswv_b:focus::after{border:rgba(255,255,255,.75) solid 2px;border-radius:var(--bld-br);content:"";display:block;inset:0;position:absolute}.tp-coltxtv{display:flex;width:100%}.tp-coltxtv_m{margin-right:4px}.tp-coltxtv_ms{border-radius:var(--bld-br);color:var(--lbl-fg);cursor:pointer;height:var(--cnt-usz);line-height:var(--cnt-usz);padding:0 18px 0 4px}.tp-coltxtv_ms:hover{background-color:var(--in-bg-h)}.tp-coltxtv_ms:focus{background-color:var(--in-bg-f)}.tp-coltxtv_ms:active{background-color:var(--in-bg-a)}.tp-coltxtv_mm{color:var(--lbl-fg)}.tp-coltxtv.tp-v-disabled .tp-coltxtv_mm{opacity:.5}.tp-coltxtv_w{flex:1}.tp-dfwv{position:absolute;top:8px;right:8px;width:256px}.tp-fldv{position:relative}.tp-fldv_t{padding-left:4px}.tp-fldv_b:disabled .tp-fldv_m{display:none}.tp-fldv_c{padding-left:4px}.tp-fldv_i{bottom:0;color:var(--cnt-bg);left:0;overflow:hidden;position:absolute;top:calc(var(--cnt-usz) + 4px);width:max(var(--bs-br),4px)}.tp-fldv_i::before{background-color:currentColor;bottom:0;content:"";left:0;position:absolute;top:0;width:4px}.tp-fldv_b:hover+.tp-fldv_i{color:var(--cnt-bg-h)}.tp-fldv_b:focus+.tp-fldv_i{color:var(--cnt-bg-f)}.tp-fldv_b:active+.tp-fldv_i{color:var(--cnt-bg-a)}.tp-fldv.tp-v-disabled>.tp-fldv_i{opacity:.5}.tp-grlv{position:relative}.tp-grlv_g{display:block;height:calc(var(--cnt-usz)*3)}.tp-grlv_g polyline{fill:none;stroke:var(--mo-fg);stroke-linejoin:round}.tp-grlv_t{margin-top:-4px;transition:left .05s,top .05s;visibility:hidden}.tp-grlv_t.tp-grlv_t-a{visibility:visible}.tp-grlv_t.tp-grlv_t-in{transition:none}.tp-grlv.tp-v-disabled .tp-grlv_g{opacity:.5}.tp-grlv .tp-ttv{background-color:var(--mo-fg)}.tp-grlv .tp-ttv::before{border-top-color:var(--mo-fg)}.tp-lblv{align-items:center;display:flex;line-height:1.3;padding-left:var(--cnt-hp);padding-right:var(--cnt-hp)}.tp-lblv.tp-lblv-nol{display:block}.tp-lblv_l{color:var(--lbl-fg);flex:1;-webkit-hyphens:auto;hyphens:auto;overflow:hidden;padding-left:4px;padding-right:16px}.tp-lblv.tp-v-disabled .tp-lblv_l{opacity:.5}.tp-lblv.tp-lblv-nol .tp-lblv_l{display:none}.tp-lblv_v{align-self:flex-start;flex-grow:0;flex-shrink:0;width:var(--bld-vw)}.tp-lblv.tp-lblv-nol .tp-lblv_v{width:100%}.tp-lstv_s{padding:0 20px 0 var(--bld-hp);width:100%}.tp-lstv_m{color:var(--btn-fg)}.tp-sglv_i{padding-left:var(--bld-hp);padding-right:var(--bld-hp)}.tp-sglv.tp-v-disabled .tp-sglv_i{opacity:.5}.tp-mllv_i{display:block;height:calc(var(--cnt-usz)*3);line-height:var(--cnt-usz);padding-left:var(--bld-hp);padding-right:var(--bld-hp);resize:none;white-space:pre}.tp-mllv.tp-v-disabled .tp-mllv_i{opacity:.5}.tp-p2dv{position:relative}.tp-p2dv_h{display:flex}.tp-p2dv_b{height:var(--cnt-usz);margin-right:4px;position:relative;width:var(--cnt-usz)}.tp-p2dv_b svg{display:block;height:16px;left:50%;margin-left:-8px;margin-top:-8px;position:absolute;top:50%;width:16px}.tp-p2dv_b svg path{stroke:currentColor;stroke-width:2}.tp-p2dv_b svg circle{fill:currentColor}.tp-p2dv_t{flex:1}.tp-p2dv_p{height:0;margin-top:0;opacity:0;overflow:hidden;transition:height .2s ease-in-out,opacity .2s linear,margin .2s ease-in-out}.tp-p2dv.tp-p2dv-expanded .tp-p2dv_p{margin-top:var(--cnt-usp);opacity:1}.tp-p2dv .tp-popv{left:calc(-1*var(--cnt-hp));right:calc(-1*var(--cnt-hp));top:var(--cnt-usz)}.tp-p2dpv{padding-left:calc(var(--cnt-usz) + 4px)}.tp-p2dpv_p{cursor:crosshair;height:0;overflow:hidden;padding-bottom:100%;position:relative}.tp-p2dpv.tp-v-disabled .tp-p2dpv_p{opacity:.5}.tp-p2dpv_g{display:block;height:100%;left:0;pointer-events:none;position:absolute;top:0;width:100%}.tp-p2dpv_ax{opacity:.1;stroke:var(--in-fg);stroke-dasharray:1}.tp-p2dpv_l{opacity:.5;stroke:var(--in-fg);stroke-dasharray:1}.tp-p2dpv_m{border:var(--in-fg) solid 1px;border-radius:50%;box-sizing:border-box;height:4px;margin-left:-2px;margin-top:-2px;position:absolute;width:4px}.tp-p2dpv_p:focus .tp-p2dpv_m{background-color:var(--in-fg);border-width:0}.tp-popv{background-color:var(--bs-bg);border-radius:var(--bs-br);box-shadow:0 2px 4px var(--bs-sh);display:none;max-width:var(--bld-vw);padding:var(--cnt-vp) var(--cnt-hp);position:absolute;visibility:hidden;z-index:1000}.tp-popv.tp-popv-v{display:block;visibility:visible}.tp-sldv.tp-v-disabled{opacity:.5}.tp-sldv_t{box-sizing:border-box;cursor:pointer;height:var(--cnt-usz);margin:0 6px;outline:none;position:relative}.tp-sldv_t::before{background-color:var(--in-bg);border-radius:1px;content:"";display:block;height:2px;inset:0;margin:auto;position:absolute}.tp-sldv_k{height:100%;left:0;position:absolute;top:0}.tp-sldv_k::before{background-color:var(--in-fg);border-radius:1px;content:"";display:block;height:2px;inset:0;margin-bottom:auto;margin-top:auto;position:absolute}.tp-sldv_k::after{background-color:var(--btn-bg);border-radius:var(--bld-br);bottom:0;content:"";display:block;height:12px;margin-bottom:auto;margin-top:auto;position:absolute;right:-6px;top:0;width:12px}.tp-sldv_t:hover .tp-sldv_k::after{background-color:var(--btn-bg-h)}.tp-sldv_t:focus .tp-sldv_k::after{background-color:var(--btn-bg-f)}.tp-sldv_t:active .tp-sldv_k::after{background-color:var(--btn-bg-a)}.tp-sldtxtv{display:flex}.tp-sldtxtv_s{flex:2}.tp-sldtxtv_t{flex:1;margin-left:4px}.tp-tabv{position:relative}.tp-tabv_t{align-items:flex-end;color:var(--cnt-bg);display:flex;overflow:hidden;position:relative}.tp-tabv_t:hover{color:var(--cnt-bg-h)}.tp-tabv_t:has(*:focus){color:var(--cnt-bg-f)}.tp-tabv_t:has(*:active){color:var(--cnt-bg-a)}.tp-tabv_t::before{background-color:currentColor;bottom:0;content:"";height:2px;left:0;pointer-events:none;position:absolute;right:0}.tp-tabv.tp-v-disabled .tp-tabv_t::before{opacity:.5}.tp-tabv.tp-tabv-nop .tp-tabv_t{height:calc(var(--cnt-usz) + 4px);position:relative}.tp-tabv.tp-tabv-nop .tp-tabv_t::before{background-color:var(--cnt-bg);bottom:0;content:"";height:2px;left:0;position:absolute;right:0}.tp-tabv_i{bottom:0;color:var(--cnt-bg);left:0;overflow:hidden;position:absolute;top:calc(var(--cnt-usz) + 4px);width:max(var(--bs-br),4px)}.tp-tabv_i::before{background-color:currentColor;bottom:0;content:"";left:0;position:absolute;top:0;width:4px}.tp-tabv_t:hover+.tp-tabv_i{color:var(--cnt-bg-h)}.tp-tabv_t:has(*:focus)+.tp-tabv_i{color:var(--cnt-bg-f)}.tp-tabv_t:has(*:active)+.tp-tabv_i{color:var(--cnt-bg-a)}.tp-tabv.tp-v-disabled>.tp-tabv_i{opacity:.5}.tp-tbiv{flex:1;min-width:0;position:relative}.tp-tbiv+.tp-tbiv{margin-left:2px}.tp-tbiv+.tp-tbiv.tp-v-disabled::before{opacity:.5}.tp-tbiv_b{display:block;padding-left:calc(var(--cnt-hp) + 4px);padding-right:calc(var(--cnt-hp) + 4px);position:relative;width:100%}.tp-tbiv_b:disabled{opacity:.5}.tp-tbiv_b::before{background-color:var(--cnt-bg);content:"";inset:0 0 2px;pointer-events:none;position:absolute}.tp-tbiv_b:hover::before{background-color:var(--cnt-bg-h)}.tp-tbiv_b:focus::before{background-color:var(--cnt-bg-f)}.tp-tbiv_b:active::before{background-color:var(--cnt-bg-a)}.tp-tbiv_t{color:var(--cnt-fg);height:calc(var(--cnt-usz) + 4px);line-height:calc(var(--cnt-usz) + 4px);opacity:.5;overflow:hidden;position:relative;text-overflow:ellipsis}.tp-tbiv.tp-tbiv-sel .tp-tbiv_t{opacity:1}.tp-tbpv_c{padding-bottom:var(--cnt-vp);padding-left:4px;padding-top:var(--cnt-vp)}.tp-txtv{position:relative}.tp-txtv_i{padding-left:var(--bld-hp);padding-right:var(--bld-hp)}.tp-txtv.tp-txtv-fst .tp-txtv_i{border-bottom-right-radius:0;border-top-right-radius:0}.tp-txtv.tp-txtv-mid .tp-txtv_i{border-radius:0}.tp-txtv.tp-txtv-lst .tp-txtv_i{border-bottom-left-radius:0;border-top-left-radius:0}.tp-txtv.tp-txtv-num .tp-txtv_i{text-align:right}.tp-txtv.tp-txtv-drg .tp-txtv_i{opacity:.3}.tp-txtv_k{cursor:pointer;height:100%;left:calc(var(--bld-hp) - 5px);position:absolute;top:0;width:12px}.tp-txtv_k::before{background-color:var(--in-fg);border-radius:1px;bottom:0;content:"";height:calc(var(--cnt-usz) - 4px);left:50%;margin-bottom:auto;margin-left:-1px;margin-top:auto;opacity:.1;position:absolute;top:0;transition:border-radius .1s,height .1s,transform .1s,width .1s;width:2px}.tp-txtv_k:hover::before,.tp-txtv.tp-txtv-drg .tp-txtv_k::before{opacity:1}.tp-txtv.tp-txtv-drg .tp-txtv_k::before{border-radius:50%;height:4px;transform:translateX(-1px);width:4px}.tp-txtv_g{bottom:0;display:block;height:8px;left:50%;margin:auto;overflow:visible;pointer-events:none;position:absolute;top:0;visibility:hidden;width:100%}.tp-txtv.tp-txtv-drg .tp-txtv_g{visibility:visible}.tp-txtv_gb{fill:none;stroke:var(--in-fg);stroke-dasharray:1}.tp-txtv_gh{fill:none;stroke:var(--in-fg)}.tp-txtv .tp-ttv{margin-left:6px;visibility:hidden}.tp-txtv.tp-txtv-drg .tp-ttv{visibility:visible}.tp-ttv{background-color:var(--in-fg);border-radius:var(--bld-br);color:var(--bs-bg);padding:2px 4px;pointer-events:none;position:absolute;transform:translate(-50%, -100%)}.tp-ttv::before{border-color:var(--in-fg) rgba(0,0,0,0) rgba(0,0,0,0) rgba(0,0,0,0);border-style:solid;border-width:2px;box-sizing:border-box;content:"";font-size:.9em;height:4px;left:50%;margin-left:-2px;position:absolute;top:100%;width:4px}.tp-rotv{background-color:var(--bs-bg);border-radius:var(--bs-br);box-shadow:0 2px 4px var(--bs-sh);font-family:var(--bs-ff);font-size:11px;font-weight:500;line-height:1;text-align:left}.tp-rotv_b{border-bottom-left-radius:var(--bs-br);border-bottom-right-radius:var(--bs-br);border-top-left-radius:var(--bs-br);border-top-right-radius:var(--bs-br);padding-left:calc(4px + var(--cnt-usz) + var(--cnt-hp));text-align:center}.tp-rotv.tp-rotv-expanded .tp-rotv_b{border-bottom-left-radius:0;border-bottom-right-radius:0;transition-delay:0s;transition-duration:0s}.tp-rotv.tp-rotv-not>.tp-rotv_b{display:none}.tp-rotv_b:disabled .tp-rotv_m{display:none}.tp-rotv_c>.tp-fldv.tp-v-lst>.tp-fldv_c{border-bottom-left-radius:var(--bs-br);border-bottom-right-radius:var(--bs-br)}.tp-rotv_c>.tp-fldv.tp-v-lst>.tp-fldv_i{border-bottom-left-radius:var(--bs-br)}.tp-rotv_c>.tp-fldv.tp-v-lst:not(.tp-fldv-expanded)>.tp-fldv_b{border-bottom-left-radius:var(--bs-br);border-bottom-right-radius:var(--bs-br)}.tp-rotv_c>.tp-fldv.tp-v-lst.tp-fldv-expanded>.tp-fldv_b{transition-delay:0s;transition-duration:0s}.tp-rotv_c .tp-fldv.tp-v-vlst:not(.tp-fldv-expanded)>.tp-fldv_b{border-bottom-right-radius:var(--bs-br)}.tp-rotv.tp-rotv-not .tp-rotv_c>.tp-fldv.tp-v-fst{margin-top:calc(-1*var(--cnt-vp))}.tp-rotv.tp-rotv-not .tp-rotv_c>.tp-fldv.tp-v-fst>.tp-fldv_b{border-top-left-radius:var(--bs-br);border-top-right-radius:var(--bs-br)}.tp-rotv_c>.tp-tabv.tp-v-lst>.tp-tabv_c{border-bottom-left-radius:var(--bs-br);border-bottom-right-radius:var(--bs-br)}.tp-rotv_c>.tp-tabv.tp-v-lst>.tp-tabv_i{border-bottom-left-radius:var(--bs-br)}.tp-rotv.tp-rotv-not .tp-rotv_c>.tp-tabv.tp-v-fst{margin-top:calc(-1*var(--cnt-vp))}.tp-rotv.tp-rotv-not .tp-rotv_c>.tp-tabv.tp-v-fst>.tp-tabv_t{border-top-left-radius:var(--bs-br);border-top-right-radius:var(--bs-br)}.tp-rotv.tp-v-disabled,.tp-rotv .tp-v-disabled{pointer-events:none}.tp-rotv.tp-v-hidden,.tp-rotv .tp-v-hidden{display:none}.tp-sprv_r{background-color:var(--grv-fg);border-width:0;display:block;height:2px;margin:0;width:100%}.tp-sprv.tp-v-disabled .tp-sprv_r{opacity:.5}',plugins:[vr,fr,xr,Ae,Cr]})}},Pr=(new Qt("4.0.5"),t({ButtonCellApi:()=>tc,ButtonGridApi:()=>ic,ButtonGridController:()=>nc,CubicBezier:()=>pc,CubicBezierApi:()=>oc,CubicBezierAssembly:()=>hc,CubicBezierController:()=>kc,CubicBezierGraphController:()=>Pc,CubicBezierGraphView:()=>fc,CubicBezierPickerController:()=>Ec,CubicBezierPickerView:()=>gc,CubicBezierPreviewView:()=>Cc,CubicBezierView:()=>mc,FpsGraphBladeApi:()=>Lc,FpsGraphController:()=>Dc,FpsView:()=>jc,Fpswatch:()=>Mc,Interval:()=>Tc,IntervalAssembly:()=>zc,IntervalConstraint:()=>Rc,RadioCellApi:()=>Yc,RadioController:()=>Zc,RadioGridApi:()=>Wc,RadioGridController:()=>td,RadioView:()=>Jc,RangeSliderController:()=>Fc,RangeSliderTextController:()=>$c,RangeSliderTextView:()=>Kc,RangeSliderView:()=>Uc,TpRadioGridChangeEvent:()=>Xc,css:()=>ad,id:()=>od,plugins:()=>ld}));function Er(t){return null==t}function kr(t){return null!==t&&"object"==typeof t}function Vr(t){return null!==t&&"object"==typeof t}function Lr(t,e){if(t.length!==e.length)return!1;for(let i=0;i{const s=t[n],r=e[n];return Vr(s)&&Vr(r)?Object.assign(Object.assign({},i),{[n]:Mr(s,r)}):Object.assign(Object.assign({},i),{[n]:n in e?r:s})},{})}var Sr={alreadydisposed:()=>"View has been already disposed",invalidparams:t=>`Invalid parameters for '${t.name}'`,nomatchingcontroller:t=>`No matching controller for '${t.key}'`,nomatchingview:t=>`No matching view for '${JSON.stringify(t.params)}'`,notbindable:()=>"Value is not bindable",notcompatible:t=>`Not compatible with plugin '${t.id}'`,propertynotfound:t=>`Property '${t.name}' not found`,shouldneverhappen:()=>"This error should never happen"},jr=class t{static alreadyDisposed(){return new t({type:"alreadydisposed"})}static notBindable(){return new t({type:"notbindable"})}static notCompatible(e,i){return new t({type:"notcompatible",context:{id:`${e}.${i}`}})}static propertyNotFound(e){return new t({type:"propertynotfound",context:{name:e}})}static shouldNeverHappen(){return new t({type:"shouldneverhappen"})}constructor(t){var e;this.message=null!==(e=Sr[t.type](t.context))&&void 0!==e?e:"Unexpected error",this.name=this.constructor.name,this.stack=new Error(this.message).stack,this.type=t.type}toString(){return this.message}},Dr=class t{constructor(t,e){this.obj_=t,this.key=e}static isBindable(t){return null!==t&&("object"==typeof t||"function"==typeof t)}read(){return this.obj_[this.key]}write(t){this.obj_[this.key]=t}writeProperty(e,i){const n=this.read();if(!t.isBindable(n))throw jr.notBindable();if(!(e in n))throw jr.propertyNotFound(e);n[e]=i}},Ar=class{constructor(){this.observers_={}}on(t,e){let i=this.observers_[t];return i||(i=this.observers_[t]=[]),i.push({handler:e}),this}off(t,e){const i=this.observers_[t];return i&&(this.observers_[t]=i.filter(t=>t.handler!==e)),this}emit(t,e){const i=this.observers_[t];i&&i.forEach(t=>{t.handler(e)})}},Or=class{constructor(t,e){var i;this.constraint_=null==e?void 0:e.constraint,this.equals_=null!==(i=null==e?void 0:e.equals)&&void 0!==i?i:(t,e)=>t===e,this.emitter=new Ar,this.rawValue_=t}get constraint(){return this.constraint_}get rawValue(){return this.rawValue_}set rawValue(t){this.setRawValue(t,{forceEmit:!1,last:!0})}setRawValue(t,e){const i=null!=e?e:{forceEmit:!1,last:!0},n=this.constraint_?this.constraint_.constrain(t):t,s=this.rawValue_;this.equals_(s,n)&&!i.forceEmit||(this.emitter.emit("beforechange",{sender:this}),this.rawValue_=n,this.emitter.emit("change",{options:i,previousRawValue:s,rawValue:n,sender:this}))}},Br=class{constructor(t){this.emitter=new Ar,this.value_=t}get rawValue(){return this.value_}set rawValue(t){this.setRawValue(t,{forceEmit:!1,last:!0})}setRawValue(t,e){const i=null!=e?e:{forceEmit:!1,last:!0},n=this.value_;(n!==t||i.forceEmit)&&(this.emitter.emit("beforechange",{sender:this}),this.value_=t,this.emitter.emit("change",{options:i,previousRawValue:n,rawValue:this.value_,sender:this}))}},Tr=class{constructor(t){this.emitter=new Ar,this.onValueBeforeChange_=this.onValueBeforeChange_.bind(this),this.onValueChange_=this.onValueChange_.bind(this),this.value_=t,this.value_.emitter.on("beforechange",this.onValueBeforeChange_),this.value_.emitter.on("change",this.onValueChange_)}get rawValue(){return this.value_.rawValue}onValueBeforeChange_(t){this.emitter.emit("beforechange",Object.assign(Object.assign({},t),{sender:this}))}onValueChange_(t){this.emitter.emit("change",Object.assign(Object.assign({},t),{sender:this}))}};function zr(t,e){const i=null==e?void 0:e.constraint,n=null==e?void 0:e.equals;return i||n?new Or(t,e):new Br(t)}var Rr=class t{constructor(t){this.emitter=new Ar,this.valMap_=t;for(const e in this.valMap_)this.valMap_[e].emitter.on("change",()=>{this.emitter.emit("change",{key:e,sender:this})})}static createCore(t){return Object.keys(t).reduce((e,i)=>Object.assign(e,{[i]:zr(t[i])}),{})}static fromObject(e){return new t(this.createCore(e))}get(t){return this.valMap_[t].rawValue}set(t,e){this.valMap_[t].rawValue=e}value(t){return this.valMap_[t]}},Nr=class{constructor(t){this.values=Rr.fromObject({max:t.max,min:t.min})}constrain(t){const e=this.values.get("max"),i=this.values.get("min");return Math.min(Math.max(t,i),e)}},Kr=class{constructor(t){this.values=Rr.fromObject({max:t.max,min:t.min})}constrain(t){const e=this.values.get("max"),i=this.values.get("min");let n=t;return Er(i)||(n=Math.max(n,i)),Er(e)||(n=Math.min(n,e)),n}},Ir=class{constructor(t,e=0){this.step=t,this.origin=e}constrain(t){const e=this.origin%this.step;return e+Math.round((t-e)/this.step)*this.step}},Ur=class{constructor(t){this.text=t}evaluate(){return Number(this.text)}toString(){return this.text}},Fr={"**":(t,e)=>Math.pow(t,e),"*":(t,e)=>t*e,"/":(t,e)=>t/e,"%":(t,e)=>t%e,"+":(t,e)=>t+e,"-":(t,e)=>t-e,"<<":(t,e)=>t<>":(t,e)=>t>>e,">>>":(t,e)=>t>>>e,"&":(t,e)=>t&e,"^":(t,e)=>t^e,"|":(t,e)=>t|e},$r=class{constructor(t,e,i){this.left=e,this.operator=t,this.right=i}evaluate(){const t=Fr[this.operator];if(!t)throw new Error(`unexpected binary operator: '${this.operator}`);return t(this.left.evaluate(),this.right.evaluate())}toString(){return["b(",this.left.toString(),this.operator,this.right.toString(),")"].join(" ")}},qr={"+":t=>t,"-":t=>-t,"~":t=>~t},Hr=class{constructor(t,e){this.operator=t,this.expression=e}evaluate(){const t=qr[this.operator];if(!t)throw new Error(`unexpected unary operator: '${this.operator}`);return t(this.expression.evaluate())}toString(){return["u(",this.operator,this.expression.toString(),")"].join(" ")}};function Gr(t){return(e,i)=>{for(let n=0;ne.startsWith(t,i))[0];return n?(i+=n.length,{cursor:i+=Yr(e,i).length,operator:n}):null}var eo=[["**"],["*","/","%"],["+","-"],["<<",">>>",">>"],["&"],["^"],["|"]].reduce((t,e)=>function(t,e){return(i,n)=>{const s=t(i,n);if(!s)return null;n=s.cursor;let r=s.evaluable;for(;;){const s=to(e,i,n);if(!s)break;n=s.cursor;const o=t(i,n);if(!o)return null;n=o.cursor,r=new $r(s.operator,r,o.evaluable)}return r?{cursor:n,evaluable:r}:null}}(t,e),function t(e,i){const n=function(t,e){var i;return null!==(i=function(t,e){const i=Zr(t,e);return e+=i.length,""===i?null:{evaluable:new Ur(i),cursor:e}}(t,e))&&void 0!==i?i:function(t,e){const i=t.substr(e,1);if(e+=i.length,"("!==i)return null;const n=io(t,e);if(!n)return null;e=n.cursor,e+=Yr(t,e).length;const s=t.substr(e,1);return e+=s.length,")"!==s?null:{evaluable:n.evaluable,cursor:e}}(t,e)}(e,i);if(n)return n;const s=e.substr(i,1);if(i+=s.length,"+"!==s&&"-"!==s&&"~"!==s)return null;const r=t(e,i);return r?{cursor:i=r.cursor,evaluable:new Hr(s,r.evaluable)}:null});function io(t,e){return e+=Yr(t,e).length,eo(t,e)}function no(t){var e;const i=function(t){const e=io(t,0);return e?e.cursor+Yr(t,e.cursor).length!==t.length?null:e.evaluable:null}(t);return null!==(e=null==i?void 0:i.evaluate())&&void 0!==e?e:null}function so(t){if("number"==typeof t)return t;if("string"==typeof t){const e=no(t);if(!Er(e))return e}return 0}function ro(t){return e=>e.toFixed(Math.max(Math.min(t,20),0))}function oo(t,e,i,n,s){return n+(t-e)/(i-e)*(s-n)}function ao(t){return String(t.toFixed(10)).split(".")[1].replace(/0+$/,"").length}function lo(t,e,i){return Math.min(Math.max(t,e),i)}function po(t,e){return(t%e+e)%e}function ho(t,e){return Er(t.step)?Math.max(ao(e),2):ao(t.step)}function co(t){var e;return null!==(e=t.step)&&void 0!==e?e:1}function uo(t,e){var i;const n=Math.abs(null!==(i=t.step)&&void 0!==i?i:e);return 0===n?.1:Math.pow(10,Math.floor(Math.log10(n))-1)}function vo(t,e){return Er(t.step)?null:new Ir(t.step,e)}function mo(t){return Er(t.max)||Er(t.min)?Er(t.max)&&Er(t.min)?null:new Kr({max:t.max,min:t.min}):new Nr({max:t.max,min:t.min})}function bo(t,e){var i,n,s;return{formatter:null!==(i=t.format)&&void 0!==i?i:ro(ho(t,e)),keyScale:null!==(n=t.keyScale)&&void 0!==n?n:co(t),pointerScale:null!==(s=t.pointerScale)&&void 0!==s?s:uo(t,e)}}function go(t){return{format:t.optional.function,keyScale:t.optional.number,max:t.optional.number,min:t.optional.number,pointerScale:t.optional.number,step:t.optional.number}}function wo(t){return{constraint:t.constraint,textProps:Rr.fromObject(bo(t.params,t.initialValue))}}var _o=class{constructor(t){this.controller=t}get element(){return this.controller.view.element}get disabled(){return this.controller.viewProps.get("disabled")}set disabled(t){this.controller.viewProps.set("disabled",t)}get hidden(){return this.controller.viewProps.get("hidden")}set hidden(t){this.controller.viewProps.set("hidden",t)}dispose(){this.controller.viewProps.set("disposed",!0)}importState(t){return this.controller.importState(t)}exportState(){return this.controller.exportState()}},fo=class{constructor(t){this.target=t}},xo=class extends fo{constructor(t,e,i){super(t),this.value=e,this.last=null==i||i}},Co=class extends fo{constructor(t,e){super(t),this.expanded=e}},yo=class extends fo{constructor(t,e){super(t),this.index=e}},Po=class extends _o{constructor(t){super(t),this.onValueChange_=this.onValueChange_.bind(this),this.emitter_=new Ar,this.controller.value.emitter.on("change",this.onValueChange_)}get label(){return this.controller.labelController.props.get("label")}set label(t){this.controller.labelController.props.set("label",t)}get key(){return this.controller.value.binding.target.key}get tag(){return this.controller.tag}set tag(t){this.controller.tag=t}on(t,e){const i=e.bind(this);return this.emitter_.on(t,t=>{i(t)}),this}refresh(){this.controller.value.fetch()}onValueChange_(t){const e=this.controller.value;this.emitter_.emit("change",new xo(this,e.binding.target.read(),t.options.last))}};function Eo(t){return e=>i=>{if(!e&&void 0===i)return{succeeded:!1,value:void 0};if(e&&void 0===i)return{succeeded:!0,value:void 0};const n=t(i);return void 0!==n?{succeeded:!0,value:n}:{succeeded:!1,value:void 0}}}function ko(t){return{custom:e=>Eo(e)(t),boolean:Eo(t=>"boolean"==typeof t?t:void 0)(t),number:Eo(t=>"number"==typeof t?t:void 0)(t),string:Eo(t=>"string"==typeof t?t:void 0)(t),function:Eo(t=>"function"==typeof t?t:void 0)(t),constant:e=>Eo(t=>t===e?e:void 0)(t),raw:Eo(t=>t)(t),object:e=>Eo(t=>{var i;if(null!==(i=t)&&"object"==typeof i)return function(t,e){return Object.keys(e).reduce((i,n)=>{if(void 0===i)return;const s=(0,e[n])(t[n]);return s.succeeded?Object.assign(Object.assign({},i),{[n]:s.value}):void 0},{})}(t,e)})(t),array:e=>Eo(t=>{var i;if(Array.isArray(t))return i=e,t.reduce((t,e)=>{if(void 0===t)return;const n=i(e);return n.succeeded&&void 0!==n.value?[...t,n.value]:void 0},[])})(t)}}var Vo={optional:ko(!0),required:ko(!1)};function Lo(t,e){const i=e(Vo),n=Vo.required.object(i)(t);return n.succeeded?n.value:void 0}function Mo(t,e,i,n){if(e&&!e(t))return!1;const s=Lo(t,i);return!!s&&n(s)}function So(t,e){var i;return Mr(null!==(i=null==t?void 0:t())&&void 0!==i?i:{},e)}function jo(t){return"value"in t}var Do="http://www.w3.org/2000/svg";function Ao(t){t.offsetHeight}function Oo(t){return void 0!==t.ontouchstart}var Bo={check:'',dropdown:'',p2dpad:''};function To(t,e){const i=t.createElementNS(Do,"svg");return i.innerHTML=Bo[e],i}function zo(t,e,i){t.insertBefore(e,t.children[i])}function Ro(t){t.parentElement&&t.parentElement.removeChild(t)}function No(t){for(;t.children.length>0;)t.removeChild(t.children[0])}function Ko(t){return t.relatedTarget?t.relatedTarget:"explicitOriginalTarget"in t?t.explicitOriginalTarget:null}function Io(t,e){t.emitter.on("change",t=>{e(t.rawValue)}),e(t.rawValue)}function Uo(t,e,i){Io(t.value(e),i)}var Fo="tp";function $o(t){return(e,i)=>[Fo,"-",t,"v",e?`_${e}`:"",i?`-${i}`:""].join("")}var qo=$o("lbl"),Ho=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(qo()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("div");i.classList.add(qo("l")),Uo(e.props,"label",e=>{Er(e)?this.element.classList.add(qo(void 0,"nol")):(this.element.classList.remove(qo(void 0,"nol")),function(t){for(;t.childNodes.length>0;)t.removeChild(t.childNodes[0])}(i),i.appendChild(function(t,e){const i=t.createDocumentFragment();return e.split("\n").map(e=>t.createTextNode(e)).forEach((e,n)=>{n>0&&i.appendChild(t.createElement("br")),i.appendChild(e)}),i}(t,e)))}),this.element.appendChild(i),this.labelElement=i;const n=t.createElement("div");n.classList.add(qo("v")),this.element.appendChild(n),this.valueElement=n}},Go=class{constructor(t,e){this.props=e.props,this.valueController=e.valueController,this.viewProps=e.valueController.viewProps,this.view=new Ho(t,{props:e.props,viewProps:this.viewProps}),this.view.valueElement.appendChild(this.valueController.view.element)}importProps(t){return Mo(t,null,t=>({label:t.optional.string}),t=>(this.props.set("label",t.label),!0))}exportProps(){return So(null,{label:this.props.get("label")})}},Yo=$o(""),Xo={veryfirst:"vfst",first:"fst",last:"lst",verylast:"vlst"},Wo=class{constructor(t){this.parent_=null,this.blade=t.blade,this.view=t.view,this.viewProps=t.viewProps;const e=this.view.element;this.blade.value("positions").emitter.on("change",()=>{["veryfirst","first","last","verylast"].forEach(t=>{e.classList.remove(Yo(void 0,Xo[t]))}),this.blade.get("positions").forEach(t=>{e.classList.add(Yo(void 0,Xo[t]))})}),this.viewProps.handleDispose(()=>{Ro(e)})}get parent(){return this.parent_}set parent(t){this.parent_=t,this.viewProps.set("parent",this.parent_?this.parent_.viewProps:null)}importState(t){return Mo(t,null,t=>({disabled:t.required.boolean,hidden:t.required.boolean}),t=>(this.viewProps.importState(t),!0))}exportState(){return So(null,Object.assign({},this.viewProps.exportState()))}},Qo=class extends Wo{constructor(t,e){if(e.value!==e.valueController.value)throw jr.shouldNeverHappen();const i=e.valueController.viewProps,n=new Go(t,{blade:e.blade,props:e.props,valueController:e.valueController});super(Object.assign(Object.assign({},e),{view:new Ho(t,{props:e.props,viewProps:i}),viewProps:i})),this.labelController=n,this.value=e.value,this.valueController=e.valueController,this.view.valueElement.appendChild(this.valueController.view.element)}importState(t){return Mo(t,e=>{var i,n,s;return super.importState(e)&&this.labelController.importProps(e)&&(null===(s=null===(n=(i=this.valueController).importProps)||void 0===n?void 0:n.call(i,t))||void 0===s||s)},t=>({value:t.optional.raw}),t=>(t.value&&(this.value.rawValue=t.value),!0))}exportState(){var t,e,i;return So(()=>super.exportState(),Object.assign(Object.assign({value:this.value.rawValue},this.labelController.exportProps()),null!==(i=null===(e=(t=this.valueController).exportProps)||void 0===e?void 0:e.call(t))&&void 0!==i?i:{}))}};function Jo(t,e){for(;t.length{i(new fo(this))}),this}};function ia(t,e){return i=>{!function(t,e,i){i?t.classList.add(e):t.classList.remove(e)}(t,e,i)}}function na(t,e){Io(t,t=>{e.textContent=null!=t?t:""})}var sa=$o("btn"),ra=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(sa()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("button");i.classList.add(sa("b")),e.viewProps.bindDisabled(i),this.element.appendChild(i),this.buttonElement=i;const n=t.createElement("div");n.classList.add(sa("t")),na(e.props.value("title"),n),this.buttonElement.appendChild(n)}},oa=class{constructor(t,e){this.emitter=new Ar,this.onClick_=this.onClick_.bind(this),this.props=e.props,this.viewProps=e.viewProps,this.view=new ra(t,{props:this.props,viewProps:this.viewProps}),this.view.buttonElement.addEventListener("click",this.onClick_)}importProps(t){return Mo(t,null,t=>({title:t.optional.string}),t=>(this.props.set("title",t.title),!0))}exportProps(){return So(null,{title:this.props.get("title")})}onClick_(){this.emitter.emit("click",{sender:this})}},aa=class extends Wo{constructor(t,e){const i=new oa(t,{props:e.buttonProps,viewProps:e.viewProps}),n=new Go(t,{blade:e.blade,props:e.labelProps,valueController:i});super({blade:e.blade,view:n.view,viewProps:e.viewProps}),this.buttonController=i,this.labelController=n}importState(t){return Mo(t,t=>super.importState(t)&&this.buttonController.importProps(t)&&this.labelController.importProps(t),()=>({}),()=>!0)}exportState(){return So(()=>super.exportState(),Object.assign(Object.assign({},this.buttonController.exportProps()),this.labelController.exportProps()))}},la=new class{constructor(t){const[e,i]=t.split("-"),n=e.split(".");this.major=parseInt(n[0],10),this.minor=parseInt(n[1],10),this.patch=parseInt(n[2],10),this.prerelease=null!=i?i:null}toString(){const t=[this.major,this.minor,this.patch].join(".");return null!==this.prerelease?[t,this.prerelease].join("-"):t}}("2.0.0-beta.2");function pa(t){return Object.assign({core:la},t)}pa({id:"button",type:"blade",accept(t){const e=Lo(t,t=>({title:t.required.string,view:t.required.constant("button"),label:t.optional.string}));return e?{params:e}:null},controller:t=>new aa(t.document,{blade:t.blade,buttonProps:Rr.fromObject({title:t.params.title}),labelProps:Rr.fromObject({label:t.params.label}),viewProps:t.viewProps}),api:t=>t.controller instanceof aa?new ea(t.controller):null});var ha=class{constructor(t,e){this.onRackValueChange_=this.onRackValueChange_.bind(this),this.controller_=t,this.emitter_=new Ar,this.pool_=e,this.controller_.rack.emitter.on("valuechange",this.onRackValueChange_)}get children(){return this.controller_.rack.children.map(t=>this.pool_.createApi(t))}addBinding(t,e,i){const n=null!=i?i:{},s=this.controller_.element.ownerDocument,r=this.pool_.createBinding(s,function(t,e){if(!Dr.isBindable(t))throw jr.notBindable();return new Dr(t,e)}(t,e),n),o=this.pool_.createBindingApi(r);return this.add(o,n.index)}addFolder(t){return function(t,e){return t.addBlade(Object.assign(Object.assign({},e),{view:"folder"}))}(this,t)}addButton(t){return function(t,e){return t.addBlade(Object.assign(Object.assign({},e),{view:"button"}))}(this,t)}addTab(t){return function(t,e){return t.addBlade(Object.assign(Object.assign({},e),{view:"tab"}))}(this,t)}add(t,e){const i=t.controller;return this.controller_.rack.add(i,e),t}remove(t){this.controller_.rack.remove(t.controller)}addBlade(t){const e=this.controller_.element.ownerDocument,i=this.pool_.createBlade(e,t),n=this.pool_.createApi(i);return this.add(n,t.index)}on(t,e){const i=e.bind(this);return this.emitter_.on(t,t=>{i(t)}),this}refresh(){this.children.forEach(t=>{var e;kr(e=t)&&"refresh"in e&&"function"==typeof e.refresh&&t.refresh()})}onRackValueChange_(t){const e=t.bladeController,i=this.pool_.createApi(e),n=kr(s=e.value)&&"binding"in s&&kr(r=s.binding)&&"target"in r?e.value.binding:null;var s,r;this.emitter_.emit("change",new xo(i,n?n.target.read():e.value.rawValue,t.options.last))}},ca=class extends _o{constructor(t,e){super(t),this.rackApi_=new ha(t.rackController,e)}},da=class extends Wo{constructor(t){super({blade:t.blade,view:t.view,viewProps:t.rackController.viewProps}),this.rackController=t.rackController}importState(t){return Mo(t,t=>super.importState(t),t=>({children:t.required.array(t.required.raw)}),t=>this.rackController.rack.children.every((e,i)=>e.importState(t.children[i])))}exportState(){return So(()=>super.exportState(),{children:this.rackController.rack.children.map(t=>t.exportState())})}};function ua(t){return"rackController"in t}var va=class{constructor(t){this.emitter=new Ar,this.items_=[],this.cache_=new Set,this.onSubListAdd_=this.onSubListAdd_.bind(this),this.onSubListRemove_=this.onSubListRemove_.bind(this),this.extract_=t}get items(){return this.items_}allItems(){return Array.from(this.cache_)}find(t){for(const e of this.allItems())if(t(e))return e;return null}includes(t){return this.cache_.has(t)}add(t,e){if(this.includes(t))throw jr.shouldNeverHappen();const i=void 0!==e?e:this.items_.length;this.items_.splice(i,0,t),this.cache_.add(t);const n=this.extract_(t);n&&(n.emitter.on("add",this.onSubListAdd_),n.emitter.on("remove",this.onSubListRemove_),n.allItems().forEach(t=>{this.cache_.add(t)})),this.emitter.emit("add",{index:i,item:t,root:this,target:this})}remove(t){const e=this.items_.indexOf(t);if(e<0)return;this.items_.splice(e,1),this.cache_.delete(t);const i=this.extract_(t);i&&(i.allItems().forEach(t=>{this.cache_.delete(t)}),i.emitter.off("add",this.onSubListAdd_),i.emitter.off("remove",this.onSubListRemove_)),this.emitter.emit("remove",{index:e,item:t,root:this,target:this})}onSubListAdd_(t){this.cache_.add(t.item),this.emitter.emit("add",{index:t.index,item:t.item,root:this,target:t.target})}onSubListRemove_(t){this.cache_.delete(t.item),this.emitter.emit("remove",{index:t.index,item:t.item,root:this,target:t.target})}};function ma(t){return ua(t)?t.rackController.rack.bcSet_:null}var ba=class{constructor(t){var e,i;this.emitter=new Ar,this.onBladePositionsChange_=this.onBladePositionsChange_.bind(this),this.onSetAdd_=this.onSetAdd_.bind(this),this.onSetRemove_=this.onSetRemove_.bind(this),this.onChildDispose_=this.onChildDispose_.bind(this),this.onChildPositionsChange_=this.onChildPositionsChange_.bind(this),this.onChildValueChange_=this.onChildValueChange_.bind(this),this.onChildViewPropsChange_=this.onChildViewPropsChange_.bind(this),this.onRackLayout_=this.onRackLayout_.bind(this),this.onRackValueChange_=this.onRackValueChange_.bind(this),this.blade_=null!==(e=t.blade)&&void 0!==e?e:null,null===(i=this.blade_)||void 0===i||i.value("positions").emitter.on("change",this.onBladePositionsChange_),this.viewProps=t.viewProps,this.bcSet_=new va(ma),this.bcSet_.emitter.on("add",this.onSetAdd_),this.bcSet_.emitter.on("remove",this.onSetRemove_)}get children(){return this.bcSet_.items}add(t,e){var i;null===(i=t.parent)||void 0===i||i.remove(t),t.parent=this,this.bcSet_.add(t,e)}remove(t){t.parent=null,this.bcSet_.remove(t)}find(t){return this.bcSet_.allItems().filter(t)}onSetAdd_(t){this.updatePositions_();const e=t.target===t.root;if(this.emitter.emit("add",{bladeController:t.item,index:t.index,root:e,sender:this}),!e)return;const i=t.item;if(i.viewProps.emitter.on("change",this.onChildViewPropsChange_),i.blade.value("positions").emitter.on("change",this.onChildPositionsChange_),i.viewProps.handleDispose(this.onChildDispose_),jo(i))i.value.emitter.on("change",this.onChildValueChange_);else if(ua(i)){const t=i.rackController.rack;if(t){const e=t.emitter;e.on("layout",this.onRackLayout_),e.on("valuechange",this.onRackValueChange_)}}}onSetRemove_(t){this.updatePositions_();const e=t.target===t.root;if(this.emitter.emit("remove",{bladeController:t.item,root:e,sender:this}),!e)return;const i=t.item;if(jo(i))i.value.emitter.off("change",this.onChildValueChange_);else if(ua(i)){const t=i.rackController.rack;if(t){const e=t.emitter;e.off("layout",this.onRackLayout_),e.off("valuechange",this.onRackValueChange_)}}}updatePositions_(){const t=this.bcSet_.items.filter(t=>!t.viewProps.get("hidden")),e=t[0],i=t[t.length-1];this.bcSet_.items.forEach(t=>{const n=[];t===e&&(n.push("first"),this.blade_&&!this.blade_.get("positions").includes("veryfirst")||n.push("veryfirst")),t===i&&(n.push("last"),this.blade_&&!this.blade_.get("positions").includes("verylast")||n.push("verylast")),t.blade.set("positions",n)})}onChildPositionsChange_(){this.updatePositions_(),this.emitter.emit("layout",{sender:this})}onChildViewPropsChange_(t){this.updatePositions_(),this.emitter.emit("layout",{sender:this})}onChildDispose_(){this.bcSet_.items.filter(t=>t.viewProps.get("disposed")).forEach(t=>{this.bcSet_.remove(t)})}onChildValueChange_(t){const e=function(t,e){for(let i=0;i{for(let t=this.rack.children.length-1;t>=0;t--)this.rack.children[t].viewProps.set("disposed",!0)})}onRackAdd_(t){t.root&&zo(this.element,t.bladeController.view.element,t.index)}onRackRemove_(t){t.root&&Ro(t.bladeController.view.element)}};function wa(){return new Rr({positions:zr([],{equals:Lr})})}var _a=class t extends Rr{constructor(t){super(t)}static create(e){const i={completed:!0,expanded:e,expandedHeight:null,shouldFixHeight:!1,temporaryExpanded:null};return new t(Rr.createCore(i))}get styleExpanded(){var t;return null!==(t=this.get("temporaryExpanded"))&&void 0!==t?t:this.get("expanded")}get styleHeight(){if(!this.styleExpanded)return"0";const t=this.get("expandedHeight");return this.get("shouldFixHeight")&&!Er(t)?`${t}px`:"auto"}bindExpandedClass(t,e){const i=()=>{this.styleExpanded?t.classList.add(e):t.classList.remove(e)};Uo(this,"expanded",i),Uo(this,"temporaryExpanded",i)}cleanUpTransition(){this.set("shouldFixHeight",!1),this.set("expandedHeight",null),this.set("completed",!0)}};function fa(t,e){e.style.height=t.styleHeight}function xa(t,e){t.value("expanded").emitter.on("beforechange",()=>{if(t.set("completed",!1),Er(t.get("expandedHeight"))){const i=function(t,e){let i=0;return function(n){const s=n.style.transition;n.style.transition="none",t.set("expandedHeight",null),t.set("temporaryExpanded",!0),Ao(e),i=e.clientHeight,t.set("temporaryExpanded",null),Ao(e),n.style.transition=s}(e),i}(t,e);i>0&&t.set("expandedHeight",i)}t.set("shouldFixHeight",!0),Ao(e)}),t.emitter.on("change",()=>{fa(t,e)}),fa(t,e),e.addEventListener("transitionend",e=>{"height"===e.propertyName&&t.cleanUpTransition()})}var Ca=class extends ca{constructor(t,e){super(t,e),this.emitter_=new Ar,this.controller.foldable.value("expanded").emitter.on("change",t=>{this.emitter_.emit("fold",new Co(this,t.sender.rawValue))}),this.rackApi_.on("change",t=>{this.emitter_.emit("change",t)})}get expanded(){return this.controller.foldable.get("expanded")}set expanded(t){this.controller.foldable.set("expanded",t)}get title(){return this.controller.props.get("title")}set title(t){this.controller.props.set("title",t)}get children(){return this.rackApi_.children}addBinding(t,e,i){return this.rackApi_.addBinding(t,e,i)}addFolder(t){return this.rackApi_.addFolder(t)}addButton(t){return this.rackApi_.addButton(t)}addTab(t){return this.rackApi_.addTab(t)}add(t,e){return this.rackApi_.add(t,e)}remove(t){this.rackApi_.remove(t)}addBlade(t){return this.rackApi_.addBlade(t)}on(t,e){const i=e.bind(this);return this.emitter_.on(t,t=>{i(t)}),this}refresh(){this.rackApi_.refresh()}},ya=$o("cnt"),Pa=class{constructor(t,e){var i;this.className_=$o(null!==(i=e.viewName)&&void 0!==i?i:"fld"),this.element=t.createElement("div"),this.element.classList.add(this.className_(),ya()),e.viewProps.bindClassModifiers(this.element),this.foldable_=e.foldable,this.foldable_.bindExpandedClass(this.element,this.className_(void 0,"expanded")),Uo(this.foldable_,"completed",ia(this.element,this.className_(void 0,"cpl")));const n=t.createElement("button");n.classList.add(this.className_("b")),Uo(e.props,"title",t=>{Er(t)?this.element.classList.add(this.className_(void 0,"not")):this.element.classList.remove(this.className_(void 0,"not"))}),e.viewProps.bindDisabled(n),this.element.appendChild(n),this.buttonElement=n;const s=t.createElement("div");s.classList.add(this.className_("i")),this.element.appendChild(s);const r=t.createElement("div");r.classList.add(this.className_("t")),na(e.props.value("title"),r),this.buttonElement.appendChild(r),this.titleElement=r;const o=t.createElement("div");o.classList.add(this.className_("m")),this.buttonElement.appendChild(o);const a=t.createElement("div");a.classList.add(this.className_("c")),this.element.appendChild(a),this.containerElement=a}},Ea=class extends da{constructor(t,e){var i;const n=_a.create(null===(i=e.expanded)||void 0===i||i),s=new Pa(t,{foldable:n,props:e.props,viewName:e.root?"rot":void 0,viewProps:e.viewProps});super(Object.assign(Object.assign({},e),{rackController:new ga({blade:e.blade,element:s.containerElement,root:e.root,viewProps:e.viewProps}),view:s})),this.onTitleClick_=this.onTitleClick_.bind(this),this.props=e.props,this.foldable=n,xa(this.foldable,this.view.containerElement),this.rackController.rack.emitter.on("add",()=>{this.foldable.cleanUpTransition()}),this.rackController.rack.emitter.on("remove",()=>{this.foldable.cleanUpTransition()}),this.view.buttonElement.addEventListener("click",this.onTitleClick_)}get document(){return this.view.element.ownerDocument}importState(t){return Mo(t,t=>super.importState(t),t=>({expanded:t.required.boolean,title:t.optional.string}),t=>(this.foldable.set("expanded",t.expanded),this.props.set("title",t.title),!0))}exportState(){return So(()=>super.exportState(),{expanded:this.foldable.get("expanded"),title:this.props.get("title")})}onTitleClick_(){this.foldable.set("expanded",!this.foldable.get("expanded"))}};pa({id:"folder",type:"blade",accept(t){const e=Lo(t,t=>({title:t.required.string,view:t.required.constant("folder"),expanded:t.optional.boolean}));return e?{params:e}:null},controller:t=>new Ea(t.document,{blade:t.blade,expanded:t.params.expanded,props:Rr.fromObject({title:t.params.title}),viewProps:t.viewProps}),api:t=>t.controller instanceof Ea?new Ca(t.controller,t.pool):null});var ka=$o("");function Va(t,e){return ia(t,ka(void 0,e))}var La=class t extends Rr{constructor(t){var e,i;super(t),this.onDisabledChange_=this.onDisabledChange_.bind(this),this.onParentChange_=this.onParentChange_.bind(this),this.onParentGlobalDisabledChange_=this.onParentGlobalDisabledChange_.bind(this),[this.globalDisabled_,this.setGlobalDisabled_]=(i=zr(this.getGlobalDisabled_()),[new Tr(i),(t,e)=>{i.setRawValue(t,e)}]),this.value("disabled").emitter.on("change",this.onDisabledChange_),this.value("parent").emitter.on("change",this.onParentChange_),null===(e=this.get("parent"))||void 0===e||e.globalDisabled.emitter.on("change",this.onParentGlobalDisabledChange_)}static create(e){var i,n,s;const r=null!=e?e:{};return new t(Rr.createCore({disabled:null!==(i=r.disabled)&&void 0!==i&&i,disposed:!1,hidden:null!==(n=r.hidden)&&void 0!==n&&n,parent:null!==(s=r.parent)&&void 0!==s?s:null}))}get globalDisabled(){return this.globalDisabled_}bindClassModifiers(t){Io(this.globalDisabled_,Va(t,"disabled")),Uo(this,"hidden",Va(t,"hidden"))}bindDisabled(t){Io(this.globalDisabled_,e=>{t.disabled=e})}bindTabIndex(t){Io(this.globalDisabled_,e=>{t.tabIndex=e?-1:0})}handleDispose(t){this.value("disposed").emitter.on("change",e=>{e&&t()})}importState(t){this.set("disabled",t.disabled),this.set("hidden",t.hidden)}exportState(){return{disabled:this.get("disabled"),hidden:this.get("hidden")}}getGlobalDisabled_(){const t=this.get("parent");return!!t&&t.globalDisabled.rawValue||this.get("disabled")}updateGlobalDisabled_(){this.setGlobalDisabled_(this.getGlobalDisabled_())}onDisabledChange_(){this.updateGlobalDisabled_()}onParentGlobalDisabledChange_(){this.updateGlobalDisabled_()}onParentChange_(t){var e;const i=t.previousRawValue;null==i||i.globalDisabled.emitter.off("change",this.onParentGlobalDisabledChange_),null===(e=this.get("parent"))||void 0===e||e.globalDisabled.emitter.on("change",this.onParentGlobalDisabledChange_),this.updateGlobalDisabled_()}},Ma=$o("tbp"),Sa=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(Ma()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("div");i.classList.add(Ma("c")),this.element.appendChild(i),this.containerElement=i}},ja=$o("tbi"),Da=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(ja()),e.viewProps.bindClassModifiers(this.element),Uo(e.props,"selected",t=>{t?this.element.classList.add(ja(void 0,"sel")):this.element.classList.remove(ja(void 0,"sel"))});const i=t.createElement("button");i.classList.add(ja("b")),e.viewProps.bindDisabled(i),this.element.appendChild(i),this.buttonElement=i;const n=t.createElement("div");n.classList.add(ja("t")),na(e.props.value("title"),n),this.buttonElement.appendChild(n),this.titleElement=n}},Aa=class{constructor(t,e){this.emitter=new Ar,this.onClick_=this.onClick_.bind(this),this.props=e.props,this.viewProps=e.viewProps,this.view=new Da(t,{props:e.props,viewProps:e.viewProps}),this.view.buttonElement.addEventListener("click",this.onClick_)}onClick_(){this.emitter.emit("click",{sender:this})}},Oa=class extends da{constructor(t,e){const i=new Sa(t,{viewProps:e.viewProps});super(Object.assign(Object.assign({},e),{rackController:new ga({blade:e.blade,element:i.containerElement,viewProps:e.viewProps}),view:i})),this.onItemClick_=this.onItemClick_.bind(this),this.ic_=new Aa(t,{props:e.itemProps,viewProps:La.create()}),this.ic_.emitter.on("click",this.onItemClick_),this.props=e.props,Uo(this.props,"selected",t=>{this.itemController.props.set("selected",t),this.viewProps.set("hidden",!t)})}get itemController(){return this.ic_}importState(t){return Mo(t,t=>super.importState(t),t=>({selected:t.required.boolean,title:t.required.string}),t=>(this.ic_.props.set("selected",t.selected),this.ic_.props.set("title",t.title),!0))}exportState(){return So(()=>super.exportState(),{selected:this.ic_.props.get("selected"),title:this.ic_.props.get("title")})}onItemClick_(){this.props.set("selected",!0)}},Ba=class extends ca{constructor(t,e){super(t,e),this.emitter_=new Ar,this.onSelect_=this.onSelect_.bind(this),this.pool_=e,this.rackApi_.on("change",t=>{this.emitter_.emit("change",t)}),this.controller.tab.selectedIndex.emitter.on("change",this.onSelect_)}get pages(){return this.rackApi_.children}addPage(t){const e=this.controller.view.element.ownerDocument,i=new Oa(e,{blade:wa(),itemProps:Rr.fromObject({selected:!1,title:t.title}),props:Rr.fromObject({selected:!1}),viewProps:La.create()}),n=this.pool_.createApi(i);return this.rackApi_.add(n,t.index)}removePage(t){this.rackApi_.remove(this.rackApi_.children[t])}on(t,e){const i=e.bind(this);return this.emitter_.on(t,t=>{i(t)}),this}onSelect_(t){this.emitter_.emit("select",new yo(this,t.rawValue))}},Ta=class extends ca{get title(){var t;return null!==(t=this.controller.itemController.props.get("title"))&&void 0!==t?t:""}set title(t){this.controller.itemController.props.set("title",t)}get selected(){return this.controller.props.get("selected")}set selected(t){this.controller.props.set("selected",t)}get children(){return this.rackApi_.children}addButton(t){return this.rackApi_.addButton(t)}addFolder(t){return this.rackApi_.addFolder(t)}addTab(t){return this.rackApi_.addTab(t)}add(t,e){this.rackApi_.add(t,e)}remove(t){this.rackApi_.remove(t)}addBinding(t,e,i){return this.rackApi_.addBinding(t,e,i)}addBlade(t){return this.rackApi_.addBlade(t)}refresh(){this.rackApi_.refresh()}},za=class{constructor(){this.onItemSelectedChange_=this.onItemSelectedChange_.bind(this),this.empty=zr(!0),this.selectedIndex=zr(-1),this.items_=[]}add(t,e){const i=null!=e?e:this.items_.length;this.items_.splice(i,0,t),t.emitter.on("change",this.onItemSelectedChange_),this.keepSelection_()}remove(t){const e=this.items_.indexOf(t);e<0||(this.items_.splice(e,1),t.emitter.off("change",this.onItemSelectedChange_),this.keepSelection_())}keepSelection_(){if(0===this.items_.length)return this.selectedIndex.rawValue=-1,void(this.empty.rawValue=!0);const t=this.items_.findIndex(t=>t.rawValue);t<0?(this.items_.forEach((t,e)=>{t.rawValue=0===e}),this.selectedIndex.rawValue=0):(this.items_.forEach((e,i)=>{e.rawValue=i===t}),this.selectedIndex.rawValue=t),this.empty.rawValue=!1}onItemSelectedChange_(t){if(t.rawValue){const e=this.items_.findIndex(e=>e===t.sender);this.items_.forEach((t,i)=>{t.rawValue=i===e}),this.selectedIndex.rawValue=e}else this.keepSelection_()}},Ra=$o("tab"),Na=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(Ra(),ya()),e.viewProps.bindClassModifiers(this.element),Io(e.empty,ia(this.element,Ra(void 0,"nop")));const i=t.createElement("div");i.classList.add(Ra("t")),this.element.appendChild(i),this.itemsElement=i;const n=t.createElement("div");n.classList.add(Ra("i")),this.element.appendChild(n);const s=t.createElement("div");s.classList.add(Ra("c")),this.element.appendChild(s),this.contentsElement=s}},Ka=class extends da{constructor(t,e){const i=new za,n=new Na(t,{empty:i.empty,viewProps:e.viewProps});super({blade:e.blade,rackController:new ga({blade:e.blade,element:n.contentsElement,viewProps:e.viewProps}),view:n}),this.onRackAdd_=this.onRackAdd_.bind(this),this.onRackRemove_=this.onRackRemove_.bind(this);const s=this.rackController.rack;s.emitter.on("add",this.onRackAdd_),s.emitter.on("remove",this.onRackRemove_),this.tab=i}add(t,e){this.rackController.rack.add(t,e)}remove(t){this.rackController.rack.remove(this.rackController.rack.children[t])}onRackAdd_(t){if(!t.root)return;const e=t.bladeController;zo(this.view.itemsElement,e.itemController.view.element,t.index),e.itemController.viewProps.set("parent",this.viewProps),this.tab.add(e.props.value("selected"))}onRackRemove_(t){if(!t.root)return;const e=t.bladeController;Ro(e.itemController.view.element),e.itemController.viewProps.set("parent",null),this.tab.remove(e.props.value("selected"))}};pa({id:"tab",type:"blade",accept(t){const e=Lo(t,t=>({pages:t.required.array(t.required.object({title:t.required.string})),view:t.required.constant("tab")}));return e&&0!==e.pages.length?{params:e}:null},controller(t){const e=new Ka(t.document,{blade:t.blade,viewProps:t.viewProps});return t.params.pages.forEach(i=>{const n=new Oa(t.document,{blade:wa(),itemProps:Rr.fromObject({selected:!1,title:i.title}),props:Rr.fromObject({selected:!1}),viewProps:La.create()});e.add(n)}),e},api:t=>t.controller instanceof Ka?new Ba(t.controller,t.pool):t.controller instanceof Oa?new Ta(t.controller,t.pool):null});var Ia=class extends Po{get options(){return this.controller.valueController.props.get("options")}set options(t){this.controller.valueController.props.set("options",t)}},Ua=class{constructor(){this.disabled=!1,this.emitter=new Ar}dispose(){}tick(){this.disabled||this.emitter.emit("tick",{sender:this})}},Fa=class{constructor(t,e){this.disabled_=!1,this.timerId_=null,this.onTick_=this.onTick_.bind(this),this.doc_=t,this.emitter=new Ar,this.interval_=e,this.setTimer_()}get disabled(){return this.disabled_}set disabled(t){this.disabled_=t,this.disabled_?this.clearTimer_():this.setTimer_()}dispose(){this.clearTimer_()}clearTimer_(){if(null===this.timerId_)return;const t=this.doc_.defaultView;t&&t.clearInterval(this.timerId_),this.timerId_=null}setTimer_(){if(this.clearTimer_(),this.interval_<=0)return;const t=this.doc_.defaultView;t&&(this.timerId_=t.setInterval(this.onTick_,this.interval_))}onTick_(){this.disabled_||this.emitter.emit("tick",{sender:this})}},$a=class{constructor(t){this.constraints=t}constrain(t){return this.constraints.reduce((t,e)=>e.constrain(t),t)}};function qa(t,e){if(t instanceof e)return t;if(t instanceof $a){const i=t.constraints.reduce((t,i)=>t||(i instanceof e?i:null),null);if(i)return i}return null}var Ha=class{constructor(t){this.values=Rr.fromObject({options:t})}constrain(t){const e=this.values.get("options");return 0===e.length||e.filter(e=>e.value===t).length>0?t:e[0].value}};function Ga(t){var e;const i=Vo;return Array.isArray(t)?null===(e=Lo({items:t},t=>({items:t.required.array(t.required.object({text:t.required.string,value:t.required.raw}))})))||void 0===e?void 0:e.items:"object"==typeof t?i.required.raw(t).value:void 0}function Ya(t){if(Array.isArray(t))return t;const e=[];return Object.keys(t).forEach(i=>{e.push({text:i,value:t[i]})}),e}function Xa(t){return Er(t)?null:new Ha(Ya(t))}var Wa=$o("lst"),Qa=class{constructor(t,e){this.onValueChange_=this.onValueChange_.bind(this),this.props_=e.props,this.element=t.createElement("div"),this.element.classList.add(Wa()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("select");i.classList.add(Wa("s")),e.viewProps.bindDisabled(i),this.element.appendChild(i),this.selectElement=i;const n=t.createElement("div");n.classList.add(Wa("m")),n.appendChild(To(t,"dropdown")),this.element.appendChild(n),e.value.emitter.on("change",this.onValueChange_),this.value_=e.value,Uo(this.props_,"options",e=>{No(this.selectElement),e.forEach(e=>{const i=t.createElement("option");i.textContent=e.text,this.selectElement.appendChild(i)}),this.update_()})}update_(){const t=this.props_.get("options").map(t=>t.value);this.selectElement.selectedIndex=t.indexOf(this.value_.rawValue)}onValueChange_(){this.update_()}},Ja=class{constructor(t,e){this.onSelectChange_=this.onSelectChange_.bind(this),this.props=e.props,this.value=e.value,this.viewProps=e.viewProps,this.view=new Qa(t,{props:this.props,value:this.value,viewProps:this.viewProps}),this.view.selectElement.addEventListener("change",this.onSelectChange_)}onSelectChange_(t){const e=t.currentTarget;this.value.rawValue=this.props.get("options")[e.selectedIndex].value}importProps(t){return Mo(t,null,t=>({options:t.required.custom(Ga)}),t=>(this.props.set("options",Ya(t.options)),!0))}exportProps(){return So(null,{options:this.props.get("options")})}},Za=$o("pop"),tl=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(Za()),e.viewProps.bindClassModifiers(this.element),Io(e.shows,ia(this.element,Za(void 0,"v")))}},el=class{constructor(t,e){this.shows=zr(!1),this.viewProps=e.viewProps,this.view=new tl(t,{shows:this.shows,viewProps:this.viewProps})}},il=$o("txt"),nl=class{constructor(t,e){this.onChange_=this.onChange_.bind(this),this.element=t.createElement("div"),this.element.classList.add(il()),e.viewProps.bindClassModifiers(this.element),this.props_=e.props,this.props_.emitter.on("change",this.onChange_);const i=t.createElement("input");i.classList.add(il("i")),i.type="text",e.viewProps.bindDisabled(i),this.element.appendChild(i),this.inputElement=i,e.value.emitter.on("change",this.onChange_),this.value_=e.value,this.refresh()}refresh(){const t=this.props_.get("formatter");this.inputElement.value=t(this.value_.rawValue)}onChange_(){this.refresh()}},sl=class{constructor(t,e){this.onInputChange_=this.onInputChange_.bind(this),this.parser_=e.parser,this.props=e.props,this.value=e.value,this.viewProps=e.viewProps,this.view=new nl(t,{props:e.props,value:this.value,viewProps:this.viewProps}),this.view.inputElement.addEventListener("change",this.onInputChange_)}onInputChange_(t){const e=t.currentTarget.value,i=this.parser_(e);Er(i)||(this.value.rawValue=i),this.view.refresh()}};function rl(t){return"false"!==t&&!!t}function ol(t){return function(t){return String(t)}(t)}var al=ro(0);function ll(t){return al(t)+"%"}function pl(t){return String(t)}function hl(t){return t}function cl({primary:t,secondary:e,forward:i,backward:n}){let s=!1;function r(t){s||(s=!0,t(),s=!1)}t.emitter.on("change",n=>{r(()=>{e.setRawValue(i(t.rawValue,e.rawValue),n.options)})}),e.emitter.on("change",s=>{r(()=>{t.setRawValue(n(t.rawValue,e.rawValue),s.options)}),r(()=>{e.setRawValue(i(t.rawValue,e.rawValue),s.options)})}),r(()=>{e.setRawValue(i(t.rawValue,e.rawValue),{forceEmit:!1,last:!0})})}function dl(t,e){const i=t*(e.altKey?.1:1)*(e.shiftKey?10:1);return e.upKey?+i:e.downKey?-i:0}function ul(t){return{altKey:t.altKey,downKey:"ArrowDown"===t.key,shiftKey:t.shiftKey,upKey:"ArrowUp"===t.key}}function vl(t){return{altKey:t.altKey,downKey:"ArrowLeft"===t.key,shiftKey:t.shiftKey,upKey:"ArrowRight"===t.key}}function ml(t){return function(t){return"ArrowUp"===t||"ArrowDown"===t}(t)||"ArrowLeft"===t||"ArrowRight"===t}function bl(t,e){var i,n;const s=e.ownerDocument.defaultView,r=e.getBoundingClientRect();return{x:t.pageX-((null!==(i=s&&s.scrollX)&&void 0!==i?i:0)+r.left),y:t.pageY-((null!==(n=s&&s.scrollY)&&void 0!==n?n:0)+r.top)}}var gl=class{constructor(t){this.lastTouch_=null,this.onDocumentMouseMove_=this.onDocumentMouseMove_.bind(this),this.onDocumentMouseUp_=this.onDocumentMouseUp_.bind(this),this.onMouseDown_=this.onMouseDown_.bind(this),this.onTouchEnd_=this.onTouchEnd_.bind(this),this.onTouchMove_=this.onTouchMove_.bind(this),this.onTouchStart_=this.onTouchStart_.bind(this),this.elem_=t,this.emitter=new Ar,t.addEventListener("touchstart",this.onTouchStart_,{passive:!1}),t.addEventListener("touchmove",this.onTouchMove_,{passive:!0}),t.addEventListener("touchend",this.onTouchEnd_),t.addEventListener("mousedown",this.onMouseDown_)}computePosition_(t){const e=this.elem_.getBoundingClientRect();return{bounds:{width:e.width,height:e.height},point:t?{x:t.x,y:t.y}:null}}onMouseDown_(t){var e;t.preventDefault(),null===(e=t.currentTarget)||void 0===e||e.focus();const i=this.elem_.ownerDocument;i.addEventListener("mousemove",this.onDocumentMouseMove_),i.addEventListener("mouseup",this.onDocumentMouseUp_),this.emitter.emit("down",{altKey:t.altKey,data:this.computePosition_(bl(t,this.elem_)),sender:this,shiftKey:t.shiftKey})}onDocumentMouseMove_(t){this.emitter.emit("move",{altKey:t.altKey,data:this.computePosition_(bl(t,this.elem_)),sender:this,shiftKey:t.shiftKey})}onDocumentMouseUp_(t){const e=this.elem_.ownerDocument;e.removeEventListener("mousemove",this.onDocumentMouseMove_),e.removeEventListener("mouseup",this.onDocumentMouseUp_),this.emitter.emit("up",{altKey:t.altKey,data:this.computePosition_(bl(t,this.elem_)),sender:this,shiftKey:t.shiftKey})}onTouchStart_(t){t.preventDefault();const e=t.targetTouches.item(0),i=this.elem_.getBoundingClientRect();this.emitter.emit("down",{altKey:t.altKey,data:this.computePosition_(e?{x:e.clientX-i.left,y:e.clientY-i.top}:void 0),sender:this,shiftKey:t.shiftKey}),this.lastTouch_=e}onTouchMove_(t){const e=t.targetTouches.item(0),i=this.elem_.getBoundingClientRect();this.emitter.emit("move",{altKey:t.altKey,data:this.computePosition_(e?{x:e.clientX-i.left,y:e.clientY-i.top}:void 0),sender:this,shiftKey:t.shiftKey}),this.lastTouch_=e}onTouchEnd_(t){var e;const i=null!==(e=t.targetTouches.item(0))&&void 0!==e?e:this.lastTouch_,n=this.elem_.getBoundingClientRect();this.emitter.emit("up",{altKey:t.altKey,data:this.computePosition_(i?{x:i.clientX-n.left,y:i.clientY-n.top}:void 0),sender:this,shiftKey:t.shiftKey})}},wl=$o("txt"),_l=class{constructor(t,e){this.onChange_=this.onChange_.bind(this),this.props_=e.props,this.props_.emitter.on("change",this.onChange_),this.element=t.createElement("div"),this.element.classList.add(wl(),wl(void 0,"num")),e.arrayPosition&&this.element.classList.add(wl(void 0,e.arrayPosition)),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("input");i.classList.add(wl("i")),i.type="text",e.viewProps.bindDisabled(i),this.element.appendChild(i),this.inputElement=i,this.onDraggingChange_=this.onDraggingChange_.bind(this),this.dragging_=e.dragging,this.dragging_.emitter.on("change",this.onDraggingChange_),this.element.classList.add(wl()),this.inputElement.classList.add(wl("i"));const n=t.createElement("div");n.classList.add(wl("k")),this.element.appendChild(n),this.knobElement=n;const s=t.createElementNS(Do,"svg");s.classList.add(wl("g")),this.knobElement.appendChild(s);const r=t.createElementNS(Do,"path");r.classList.add(wl("gb")),s.appendChild(r),this.guideBodyElem_=r;const o=t.createElementNS(Do,"path");o.classList.add(wl("gh")),s.appendChild(o),this.guideHeadElem_=o;const a=t.createElement("div");a.classList.add($o("tt")()),this.knobElement.appendChild(a),this.tooltipElem_=a,e.value.emitter.on("change",this.onChange_),this.value=e.value,this.refresh()}onDraggingChange_(t){if(null===t.rawValue)return void this.element.classList.remove(wl(void 0,"drg"));this.element.classList.add(wl(void 0,"drg"));const e=t.rawValue/this.props_.get("pointerScale"),i=e+(e>0?-1:e<0?1:0),n=lo(-i,-4,4);this.guideHeadElem_.setAttributeNS(null,"d",[`M ${i+n},0 L${i},4 L${i+n},8`,`M ${e},-1 L${e},9`].join(" ")),this.guideBodyElem_.setAttributeNS(null,"d",`M 0,4 L${e},4`);const s=this.props_.get("formatter");this.tooltipElem_.textContent=s(this.value.rawValue),this.tooltipElem_.style.left=`${e}px`}refresh(){const t=this.props_.get("formatter");this.inputElement.value=t(this.value.rawValue)}onChange_(){this.refresh()}},fl=class{constructor(t,e){var i;this.originRawValue_=0,this.onInputChange_=this.onInputChange_.bind(this),this.onInputKeyDown_=this.onInputKeyDown_.bind(this),this.onInputKeyUp_=this.onInputKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.parser_=e.parser,this.props=e.props,this.sliderProps_=null!==(i=e.sliderProps)&&void 0!==i?i:null,this.value=e.value,this.viewProps=e.viewProps,this.dragging_=zr(null),this.view=new _l(t,{arrayPosition:e.arrayPosition,dragging:this.dragging_,props:this.props,value:this.value,viewProps:this.viewProps}),this.view.inputElement.addEventListener("change",this.onInputChange_),this.view.inputElement.addEventListener("keydown",this.onInputKeyDown_),this.view.inputElement.addEventListener("keyup",this.onInputKeyUp_);const n=new gl(this.view.knobElement);n.emitter.on("down",this.onPointerDown_),n.emitter.on("move",this.onPointerMove_),n.emitter.on("up",this.onPointerUp_)}constrainValue_(t){var e,i;const n=null===(e=this.sliderProps_)||void 0===e?void 0:e.get("min"),s=null===(i=this.sliderProps_)||void 0===i?void 0:i.get("max");let r=t;return void 0!==n&&(r=Math.max(r,n)),void 0!==s&&(r=Math.min(r,s)),r}onInputChange_(t){const e=t.currentTarget.value,i=this.parser_(e);Er(i)||(this.value.rawValue=this.constrainValue_(i)),this.view.refresh()}onInputKeyDown_(t){const e=dl(this.props.get("keyScale"),ul(t));0!==e&&this.value.setRawValue(this.constrainValue_(this.value.rawValue+e),{forceEmit:!1,last:!1})}onInputKeyUp_(t){0!==dl(this.props.get("keyScale"),ul(t))&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}onPointerDown_(){this.originRawValue_=this.value.rawValue,this.dragging_.rawValue=0}computeDraggingValue_(t){if(!t.point)return null;const e=t.point.x-t.bounds.width/2;return this.constrainValue_(this.originRawValue_+e*this.props.get("pointerScale"))}onPointerMove_(t){const e=this.computeDraggingValue_(t.data);null!==e&&(this.value.setRawValue(e,{forceEmit:!1,last:!1}),this.dragging_.rawValue=this.value.rawValue-this.originRawValue_)}onPointerUp_(t){const e=this.computeDraggingValue_(t.data);null!==e&&(this.value.setRawValue(e,{forceEmit:!0,last:!0}),this.dragging_.rawValue=null)}},xl=$o("sld"),Cl=class{constructor(t,e){this.onChange_=this.onChange_.bind(this),this.props_=e.props,this.props_.emitter.on("change",this.onChange_),this.element=t.createElement("div"),this.element.classList.add(xl()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("div");i.classList.add(xl("t")),e.viewProps.bindTabIndex(i),this.element.appendChild(i),this.trackElement=i;const n=t.createElement("div");n.classList.add(xl("k")),this.trackElement.appendChild(n),this.knobElement=n,e.value.emitter.on("change",this.onChange_),this.value=e.value,this.update_()}update_(){const t=lo(oo(this.value.rawValue,this.props_.get("min"),this.props_.get("max"),0,100),0,100);this.knobElement.style.width=`${t}%`}onChange_(){this.update_()}},yl=class{constructor(t,e){this.onKeyDown_=this.onKeyDown_.bind(this),this.onKeyUp_=this.onKeyUp_.bind(this),this.onPointerDownOrMove_=this.onPointerDownOrMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.value=e.value,this.viewProps=e.viewProps,this.props=e.props,this.view=new Cl(t,{props:this.props,value:this.value,viewProps:this.viewProps}),this.ptHandler_=new gl(this.view.trackElement),this.ptHandler_.emitter.on("down",this.onPointerDownOrMove_),this.ptHandler_.emitter.on("move",this.onPointerDownOrMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.trackElement.addEventListener("keydown",this.onKeyDown_),this.view.trackElement.addEventListener("keyup",this.onKeyUp_)}handlePointerEvent_(t,e){t.point&&this.value.setRawValue(oo(lo(t.point.x,0,t.bounds.width),0,t.bounds.width,this.props.get("min"),this.props.get("max")),e)}onPointerDownOrMove_(t){this.handlePointerEvent_(t.data,{forceEmit:!1,last:!1})}onPointerUp_(t){this.handlePointerEvent_(t.data,{forceEmit:!0,last:!0})}onKeyDown_(t){const e=dl(this.props.get("keyScale"),vl(t));0!==e&&this.value.setRawValue(this.value.rawValue+e,{forceEmit:!1,last:!1})}onKeyUp_(t){0!==dl(this.props.get("keyScale"),vl(t))&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}},Pl=$o("sldtxt"),El=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(Pl());const i=t.createElement("div");i.classList.add(Pl("s")),this.sliderView_=e.sliderView,i.appendChild(this.sliderView_.element),this.element.appendChild(i);const n=t.createElement("div");n.classList.add(Pl("t")),this.textView_=e.textView,n.appendChild(this.textView_.element),this.element.appendChild(n)}},kl=class{constructor(t,e){this.value=e.value,this.viewProps=e.viewProps,this.sliderC_=new yl(t,{props:e.sliderProps,value:e.value,viewProps:this.viewProps}),this.textC_=new fl(t,{parser:e.parser,props:e.textProps,sliderProps:e.sliderProps,value:e.value,viewProps:e.viewProps}),this.view=new El(t,{sliderView:this.sliderC_.view,textView:this.textC_.view})}get sliderController(){return this.sliderC_}get textController(){return this.textC_}importProps(t){return Mo(t,null,t=>({max:t.required.number,min:t.required.number}),t=>{const e=this.sliderC_.props;return e.set("max",t.max),e.set("min",t.min),!0})}exportProps(){const t=this.sliderC_.props;return So(null,{max:t.get("max"),min:t.get("min")})}},Vl={containerUnitSize:"cnt-usz"};function Ll(t){return`--${Vl[t]}`}var Ml=class{constructor(t,e){const i=$o(e.viewName);this.element=t.createElement("div"),this.element.classList.add(i()),e.viewProps.bindClassModifiers(this.element)}};function Sl(t){return go(t)}function jl(t){if(Vr(t))return Lo(t,Sl)}function Dl(t,e){if(!t)return;const i=[],n=vo(t,e);n&&i.push(n);const s=mo(t);return s&&i.push(s),new $a(i)}function Al(t){if("inline"===t||"popup"===t)return t}function Ol(t,e){t.write(e)}var Bl=$o("ckb"),Tl=class{constructor(t,e){this.onValueChange_=this.onValueChange_.bind(this),this.element=t.createElement("div"),this.element.classList.add(Bl()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("label");i.classList.add(Bl("l")),this.element.appendChild(i);const n=t.createElement("input");n.classList.add(Bl("i")),n.type="checkbox",i.appendChild(n),this.inputElement=n,e.viewProps.bindDisabled(this.inputElement);const s=t.createElement("div");s.classList.add(Bl("w")),i.appendChild(s);const r=To(t,"check");s.appendChild(r),e.value.emitter.on("change",this.onValueChange_),this.value=e.value,this.update_()}update_(){this.inputElement.checked=this.value.rawValue}onValueChange_(){this.update_()}},zl=class{constructor(t,e){this.onInputChange_=this.onInputChange_.bind(this),this.value=e.value,this.viewProps=e.viewProps,this.view=new Tl(t,{value:this.value,viewProps:this.viewProps}),this.view.inputElement.addEventListener("change",this.onInputChange_)}onInputChange_(t){const e=t.currentTarget;this.value.rawValue=e.checked}};pa({id:"input-bool",type:"input",accept:(t,e)=>{if("boolean"!=typeof t)return null;const i=Lo(e,t=>({options:t.optional.custom(Ga),readonly:t.optional.constant(!1)}));return i?{initialValue:t,params:i}:null},binding:{reader:t=>rl,constraint:t=>function(t){const e=[],i=Xa(t.options);return i&&e.push(i),new $a(e)}(t.params),writer:t=>Ol},controller:t=>{const e=t.document,i=t.value,n=t.constraint,s=n&&qa(n,Ha);return s?new Ja(e,{props:new Rr({options:s.values.value("options")}),value:i,viewProps:t.viewProps}):new zl(e,{value:i,viewProps:t.viewProps})},api:t=>"boolean"!=typeof t.controller.value.rawValue?null:t.controller.valueController instanceof Ja?new Ia(t.controller):null});var Rl=$o("col"),Nl=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(Rl()),e.foldable.bindExpandedClass(this.element,Rl(void 0,"expanded")),Uo(e.foldable,"completed",ia(this.element,Rl(void 0,"cpl")));const i=t.createElement("div");i.classList.add(Rl("h")),this.element.appendChild(i);const n=t.createElement("div");n.classList.add(Rl("s")),i.appendChild(n),this.swatchElement=n;const s=t.createElement("div");if(s.classList.add(Rl("t")),i.appendChild(s),this.textElement=s,"inline"===e.pickerLayout){const e=t.createElement("div");e.classList.add(Rl("p")),this.element.appendChild(e),this.pickerElement=e}else this.pickerElement=null}};function Kl(t,e,i){const n=po(t,360),s=lo(e/100,0,1),r=lo(i/100,0,1),o=r*s,a=o*(1-Math.abs(n/60%2-1)),l=r-o;let p,h,c;return[p,h,c]=n>=0&&n<60?[o,a,0]:n>=60&&n<120?[a,o,0]:n>=120&&n<180?[0,o,a]:n>=180&&n<240?[0,a,o]:n>=240&&n<300?[a,0,o]:[o,0,a],[255*(p+l),255*(h+l),255*(c+l)]}function Il(t){return[t[0],t[1],t[2]]}function Ul(t,e){return[t[0],t[1],t[2],e]}var Fl={hsl:{hsl:(t,e,i)=>[t,e,i],hsv:function(t,e,i){const n=i+e*(100-Math.abs(2*i-100))/200;return[t,0!==n?e*(100-Math.abs(2*i-100))/n:0,i+e*(100-Math.abs(2*i-100))/200]},rgb:function(t,e,i){const n=(t%360+360)%360,s=lo(e/100,0,1),r=lo(i/100,0,1),o=(1-Math.abs(2*r-1))*s,a=o*(1-Math.abs(n/60%2-1)),l=r-o/2;let p,h,c;return[p,h,c]=n>=0&&n<60?[o,a,0]:n>=60&&n<120?[a,o,0]:n>=120&&n<180?[0,o,a]:n>=180&&n<240?[0,a,o]:n>=240&&n<300?[a,0,o]:[o,0,a],[255*(p+l),255*(h+l),255*(c+l)]}},hsv:{hsl:function(t,e,i){const n=100-Math.abs(i*(200-e)/100-100);return[t,0!==n?e*i/n:0,i*(200-e)/200]},hsv:(t,e,i)=>[t,e,i],rgb:Kl},rgb:{hsl:function(t,e,i){const n=lo(t/255,0,1),s=lo(e/255,0,1),r=lo(i/255,0,1),o=Math.max(n,s,r),a=Math.min(n,s,r),l=o-a;let p=0,h=0;const c=(a+o)/2;return 0!==l&&(h=l/(1-Math.abs(o+a-1)),p=n===o?(s-r)/l:s===o?2+(r-n)/l:4+(n-s)/l,p=p/6+(p<0?1:0)),[360*p,100*h,100*c]},hsv:function(t,e,i){const n=lo(t/255,0,1),s=lo(e/255,0,1),r=lo(i/255,0,1),o=Math.max(n,s,r),a=o-Math.min(n,s,r);let l;return l=0===a?0:o===n?((s-r)/a%6+6)%6*60:o===s?60*((r-n)/a+2):60*((n-s)/a+4),[l,100*(0===o?0:a/o),100*o]},rgb:(t,e,i)=>[t,e,i]}};function $l(t,e){return["float"===e?1:"rgb"===t?255:360,"float"===e?1:"rgb"===t?255:100,"float"===e?1:"rgb"===t?255:100]}function ql(t,e,i){var n;const s=$l(e,i);return["rgb"===e?lo(t[0],0,s[0]):(r=t[0],o=s[0],r===o?o:po(r,o)),lo(t[1],0,s[1]),lo(t[2],0,s[2]),lo(null!==(n=t[3])&&void 0!==n?n:1,0,1)];var r,o}function Hl(t,e,i,n){const s=$l(e,i),r=$l(e,n);return t.map((t,e)=>t/s[e]*r[e])}function Gl(t,e,i){const n=Hl(t,e.mode,e.type,"int");return Hl(Fl[e.mode][i.mode](...n),i.mode,"int",i.type)}var Yl=class t{static black(){return new t([0,0,0],"rgb")}constructor(t,e){this.type="int",this.mode=e,this.comps_=ql(t,e,this.type)}getComponents(t){return Ul(Gl(Il(this.comps_),{mode:this.mode,type:this.type},{mode:null!=t?t:this.mode,type:this.type}),this.comps_[3])}toRgbaObject(){const t=this.getComponents("rgb");return{r:t[0],g:t[1],b:t[2],a:t[3]}}},Xl=$o("colp"),Wl=class{constructor(t,e){this.alphaViews_=null,this.element=t.createElement("div"),this.element.classList.add(Xl()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("div");i.classList.add(Xl("hsv"));const n=t.createElement("div");n.classList.add(Xl("sv")),this.svPaletteView_=e.svPaletteView,n.appendChild(this.svPaletteView_.element),i.appendChild(n);const s=t.createElement("div");s.classList.add(Xl("h")),this.hPaletteView_=e.hPaletteView,s.appendChild(this.hPaletteView_.element),i.appendChild(s),this.element.appendChild(i);const r=t.createElement("div");if(r.classList.add(Xl("rgb")),this.textsView_=e.textsView,r.appendChild(this.textsView_.element),this.element.appendChild(r),e.alphaViews){this.alphaViews_={palette:e.alphaViews.palette,text:e.alphaViews.text};const i=t.createElement("div");i.classList.add(Xl("a"));const n=t.createElement("div");n.classList.add(Xl("ap")),n.appendChild(this.alphaViews_.palette.element),i.appendChild(n);const s=t.createElement("div");s.classList.add(Xl("at")),s.appendChild(this.alphaViews_.text.element),i.appendChild(s),this.element.appendChild(i)}}get allFocusableElements(){const t=[this.svPaletteView_.element,this.hPaletteView_.element,this.textsView_.modeSelectElement,...this.textsView_.inputViews.map(t=>t.inputElement)];return this.alphaViews_&&t.push(this.alphaViews_.palette.element,this.alphaViews_.text.inputElement),t}};function Ql(t){return"int"===t?"int":"float"===t?"float":void 0}function Jl(t){return Lo(t,t=>({color:t.optional.object({alpha:t.optional.boolean,type:t.optional.custom(Ql)}),expanded:t.optional.boolean,picker:t.optional.custom(Al),readonly:t.optional.constant(!1)}))}function Zl(t){return t?.1:1}function tp(t){var e;return null===(e=t.color)||void 0===e?void 0:e.type}var ep=class{constructor(t,e){this.type="float",this.mode=e,this.comps_=ql(t,e,this.type)}getComponents(t){return Ul(Gl(Il(this.comps_),{mode:this.mode,type:this.type},{mode:null!=t?t:this.mode,type:this.type}),this.comps_[3])}toRgbaObject(){const t=this.getComponents("rgb");return{r:t[0],g:t[1],b:t[2],a:t[3]}}},ip={int:(t,e)=>new Yl(t,e),float:(t,e)=>new ep(t,e)};function np(t,e,i){return ip[i](t,e)}function sp(t,e){if(t.type===e)return t;if(function(t){return"int"===t.type}(t)&&"float"===e)return function(t){const e=t.getComponents(),i=$l(t.mode,"int");return new ep([oo(e[0],0,i[0],0,1),oo(e[1],0,i[1],0,1),oo(e[2],0,i[2],0,1),e[3]],t.mode)}(t);if(function(t){return"float"===t.type}(t)&&"int"===e)return function(t){const e=t.getComponents(),i=$l(t.mode,"int");return new Yl([Math.round(oo(e[0],0,1,0,i[0])),Math.round(oo(e[1],0,1,0,i[1])),Math.round(oo(e[2],0,1,0,i[2])),e[3]],t.mode)}(t);throw jr.shouldNeverHappen()}function rp(t,e){const i=t.match(/^(.+)%$/);return i?Math.min(.01*parseFloat(i[1])*e,e):Math.min(parseFloat(t),e)}var op={deg:t=>t,grad:t=>360*t/400,rad:t=>360*t/(2*Math.PI),turn:t=>360*t};function ap(t){const e=t.match(/^([0-9.]+?)(deg|grad|rad|turn)$/);if(!e)return parseFloat(t);const i=parseFloat(e[1]);return op[e[2]](i)}function lp(t){const e=t.match(/^rgb\(\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!e)return null;const i=[rp(e[1],255),rp(e[2],255),rp(e[3],255)];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])?null:i}function pp(t){const e=lp(t);return e?new Yl(e,"rgb"):null}function hp(t){const e=t.match(/^rgba\(\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!e)return null;const i=[rp(e[1],255),rp(e[2],255),rp(e[3],255),rp(e[4],1)];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])||isNaN(i[3])?null:i}function cp(t){const e=hp(t);return e?new Yl(e,"rgb"):null}function dp(t){const e=t.match(/^hsl\(\s*([0-9A-Fa-f.]+(?:deg|grad|rad|turn)?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!e)return null;const i=[ap(e[1]),rp(e[2],100),rp(e[3],100)];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])?null:i}function up(t){const e=dp(t);return e?new Yl(e,"hsl"):null}function vp(t){const e=t.match(/^hsla\(\s*([0-9A-Fa-f.]+(?:deg|grad|rad|turn)?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!e)return null;const i=[ap(e[1]),rp(e[2],100),rp(e[3],100),rp(e[4],1)];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])||isNaN(i[3])?null:i}function mp(t){const e=vp(t);return e?new Yl(e,"hsl"):null}function bp(t){const e=t.match(/^#([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])$/);if(e)return[parseInt(e[1]+e[1],16),parseInt(e[2]+e[2],16),parseInt(e[3]+e[3],16)];const i=t.match(/^(?:#|0x)([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})$/);return i?[parseInt(i[1],16),parseInt(i[2],16),parseInt(i[3],16)]:null}function gp(t){const e=bp(t);return e?new Yl(e,"rgb"):null}function wp(t){const e=t.match(/^#?([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])$/);if(e)return[parseInt(e[1]+e[1],16),parseInt(e[2]+e[2],16),parseInt(e[3]+e[3],16),oo(parseInt(e[4]+e[4],16),0,255,0,1)];const i=t.match(/^(?:#|0x)?([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})$/);return i?[parseInt(i[1],16),parseInt(i[2],16),parseInt(i[3],16),oo(parseInt(i[4],16),0,255,0,1)]:null}function _p(t){const e=wp(t);return e?new Yl(e,"rgb"):null}function fp(t){const e=t.match(/^\{\s*r\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*g\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*b\s*:\s*([0-9A-Fa-f.]+%?)\s*\}$/);if(!e)return null;const i=[parseFloat(e[1]),parseFloat(e[2]),parseFloat(e[3])];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])?null:i}function xp(t){return e=>{const i=fp(e);return i?np(i,"rgb",t):null}}function Cp(t){const e=t.match(/^\{\s*r\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*g\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*b\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*a\s*:\s*([0-9A-Fa-f.]+%?)\s*\}$/);if(!e)return null;const i=[parseFloat(e[1]),parseFloat(e[2]),parseFloat(e[3]),parseFloat(e[4])];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])||isNaN(i[3])?null:i}function yp(t){return e=>{const i=Cp(e);return i?np(i,"rgb",t):null}}var Pp=[{parser:bp,result:{alpha:!1,mode:"rgb",notation:"hex"}},{parser:wp,result:{alpha:!0,mode:"rgb",notation:"hex"}},{parser:lp,result:{alpha:!1,mode:"rgb",notation:"func"}},{parser:hp,result:{alpha:!0,mode:"rgb",notation:"func"}},{parser:dp,result:{alpha:!1,mode:"hsl",notation:"func"}},{parser:vp,result:{alpha:!0,mode:"hsl",notation:"func"}},{parser:fp,result:{alpha:!1,mode:"rgb",notation:"object"}},{parser:Cp,result:{alpha:!0,mode:"rgb",notation:"object"}}];function Ep(t){const e=[gp,_p,pp,cp,up,mp];"int"===t&&e.push(xp("int"),yp("int")),"float"===t&&e.push(xp("float"),yp("float"));const i=function(t){return e=>t.reduce((t,i)=>null!==t?t:i(e),null)}(e);return e=>{const n=i(e);return n?sp(n,t):null}}function kp(t){const e=Ep("int");if("string"!=typeof t)return Yl.black();const i=e(t);return null!=i?i:Yl.black()}function Vp(t){const e=lo(Math.floor(t),0,255).toString(16);return 1===e.length?`0${e}`:e}function Lp(t,e="#"){return`${e}${Il(t.getComponents("rgb")).map(Vp).join("")}`}function Mp(t,e="#"){const i=t.getComponents("rgb");return`${e}${[i[0],i[1],i[2],255*i[3]].map(Vp).join("")}`}function Sp(t){const e=ro(0);return`rgb(${Il(sp(t,"int").getComponents("rgb")).map(t=>e(t)).join(", ")})`}function jp(t){const e=ro(2),i=ro(0);return`rgba(${sp(t,"int").getComponents("rgb").map((t,n)=>(3===n?e:i)(t)).join(", ")})`}function Dp(t,e){const i=ro("float"===e?2:0),n=["r","g","b"];return`{${Il(sp(t,e).getComponents("rgb")).map((t,e)=>`${n[e]}: ${i(t)}`).join(", ")}}`}function Ap(t){return e=>Dp(e,t)}function Op(t,e){const i=ro(2),n=ro("float"===e?2:0),s=["r","g","b","a"];return`{${sp(t,e).getComponents("rgb").map((t,e)=>`${s[e]}: ${(3===e?i:n)(t)}`).join(", ")}}`}function Bp(t){return e=>Op(e,t)}var Tp=[{format:{alpha:!1,mode:"rgb",notation:"hex",type:"int"},stringifier:Lp},{format:{alpha:!0,mode:"rgb",notation:"hex",type:"int"},stringifier:Mp},{format:{alpha:!1,mode:"rgb",notation:"func",type:"int"},stringifier:Sp},{format:{alpha:!0,mode:"rgb",notation:"func",type:"int"},stringifier:jp},{format:{alpha:!1,mode:"hsl",notation:"func",type:"int"},stringifier:function(t){const e=[ro(0),ll,ll];return`hsl(${Il(sp(t,"int").getComponents("hsl")).map((t,i)=>e[i](t)).join(", ")})`}},{format:{alpha:!0,mode:"hsl",notation:"func",type:"int"},stringifier:function(t){const e=[ro(0),ll,ll,ro(2)];return`hsla(${sp(t,"int").getComponents("hsl").map((t,i)=>e[i](t)).join(", ")})`}},...["int","float"].reduce((t,e)=>[...t,{format:{alpha:!1,mode:"rgb",notation:"object",type:e},stringifier:Ap(e)},{format:{alpha:!0,mode:"rgb",notation:"object",type:e},stringifier:Bp(e)}],[])];function zp(t){return Tp.reduce((e,i)=>{return e||(n=i.format,s=t,n.alpha===s.alpha&&n.mode===s.mode&&n.notation===s.notation&&n.type===s.type?i.stringifier:null);var n,s},null)}var Rp=$o("apl"),Np=class{constructor(t,e){this.onValueChange_=this.onValueChange_.bind(this),this.value=e.value,this.value.emitter.on("change",this.onValueChange_),this.element=t.createElement("div"),this.element.classList.add(Rp()),e.viewProps.bindClassModifiers(this.element),e.viewProps.bindTabIndex(this.element);const i=t.createElement("div");i.classList.add(Rp("b")),this.element.appendChild(i);const n=t.createElement("div");n.classList.add(Rp("c")),i.appendChild(n),this.colorElem_=n;const s=t.createElement("div");s.classList.add(Rp("m")),this.element.appendChild(s),this.markerElem_=s;const r=t.createElement("div");r.classList.add(Rp("p")),this.markerElem_.appendChild(r),this.previewElem_=r,this.update_()}update_(){const t=this.value.rawValue,e=t.getComponents("rgb"),i=new Yl([e[0],e[1],e[2],0],"rgb"),n=new Yl([e[0],e[1],e[2],255],"rgb"),s=["to right",jp(i),jp(n)];this.colorElem_.style.background=`linear-gradient(${s.join(",")})`,this.previewElem_.style.backgroundColor=jp(t);const r=oo(e[3],0,1,0,100);this.markerElem_.style.left=`${r}%`}onValueChange_(){this.update_()}},Kp=class{constructor(t,e){this.onKeyDown_=this.onKeyDown_.bind(this),this.onKeyUp_=this.onKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.value=e.value,this.viewProps=e.viewProps,this.view=new Np(t,{value:this.value,viewProps:this.viewProps}),this.ptHandler_=new gl(this.view.element),this.ptHandler_.emitter.on("down",this.onPointerDown_),this.ptHandler_.emitter.on("move",this.onPointerMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.element.addEventListener("keydown",this.onKeyDown_),this.view.element.addEventListener("keyup",this.onKeyUp_)}handlePointerEvent_(t,e){if(!t.point)return;const i=t.point.x/t.bounds.width,[n,s,r]=this.value.rawValue.getComponents("hsv");this.value.setRawValue(new Yl([n,s,r,i],"hsv"),e)}onPointerDown_(t){this.handlePointerEvent_(t.data,{forceEmit:!1,last:!1})}onPointerMove_(t){this.handlePointerEvent_(t.data,{forceEmit:!1,last:!1})}onPointerUp_(t){this.handlePointerEvent_(t.data,{forceEmit:!0,last:!0})}onKeyDown_(t){const e=dl(Zl(!0),vl(t));if(0===e)return;const[i,n,s,r]=this.value.rawValue.getComponents("hsv");this.value.setRawValue(new Yl([i,n,s,r+e],"hsv"),{forceEmit:!1,last:!1})}onKeyUp_(t){0!==dl(Zl(!0),vl(t))&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}},Ip=$o("coltxt"),Up=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(Ip()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("div");i.classList.add(Ip("m")),this.modeElem_=function(t){const e=t.createElement("select");return e.appendChild([{text:"RGB",value:"rgb"},{text:"HSL",value:"hsl"},{text:"HSV",value:"hsv"},{text:"HEX",value:"hex"}].reduce((e,i)=>{const n=t.createElement("option");return n.textContent=i.text,n.value=i.value,e.appendChild(n),e},t.createDocumentFragment())),e}(t),this.modeElem_.classList.add(Ip("ms")),i.appendChild(this.modeSelectElement),e.viewProps.bindDisabled(this.modeElem_);const n=t.createElement("div");n.classList.add(Ip("mm")),n.appendChild(To(t,"dropdown")),i.appendChild(n),this.element.appendChild(i);const s=t.createElement("div");s.classList.add(Ip("w")),this.element.appendChild(s),this.inputsElem_=s,this.inputViews_=e.inputViews,this.applyInputViews_(),Io(e.mode,t=>{this.modeElem_.value=t})}get modeSelectElement(){return this.modeElem_}get inputViews(){return this.inputViews_}set inputViews(t){this.inputViews_=t,this.applyInputViews_()}applyInputViews_(){No(this.inputsElem_);const t=this.element.ownerDocument;this.inputViews_.forEach(e=>{const i=t.createElement("div");i.classList.add(Ip("c")),i.appendChild(e.element),this.inputsElem_.appendChild(i)})}};function Fp(t,e,i){const n=$l(t,e)[i];return new Nr({min:0,max:n})}var $p=class{constructor(t,e){this.onModeSelectChange_=this.onModeSelectChange_.bind(this),this.colorType_=e.colorType,this.value=e.value,this.viewProps=e.viewProps,this.colorMode=zr(this.value.rawValue.mode),this.ccs_=this.createComponentControllers_(t),this.view=new Up(t,{mode:this.colorMode,inputViews:[this.ccs_[0].view,this.ccs_[1].view,this.ccs_[2].view],viewProps:this.viewProps}),this.view.modeSelectElement.addEventListener("change",this.onModeSelectChange_)}createComponentControllers_(t){const e=this.colorMode.rawValue;return function(t){return"hex"!==t}(e)?function(t,e){const i={colorMode:e.colorMode,colorType:e.colorType,parser:no,viewProps:e.viewProps};return[0,1,2].map(n=>{const s=function(t,e,i){return new fl(t,{arrayPosition:0===i?"fst":2===i?"lst":"mid",parser:e.parser,props:Rr.fromObject({formatter:(n=e.colorType,ro("float"===n?2:0)),keyScale:Zl(!1),pointerScale:"float"===e.colorType?.01:1}),value:zr(0,{constraint:Fp(e.colorMode,e.colorType,i)}),viewProps:e.viewProps});var n}(t,i,n);return cl({primary:e.value,secondary:s.value,forward:t=>sp(t,e.colorType).getComponents(e.colorMode)[n],backward(t,i){const s=e.colorMode,r=sp(t,e.colorType).getComponents(s);return r[n]=i,sp(np(Ul(Il(r),r[3]),s,e.colorType),"int")}}),s})}(t,{colorMode:e,colorType:this.colorType_,value:this.value,viewProps:this.viewProps}):function(t,e){const i=new sl(t,{parser:Ep("int"),props:Rr.fromObject({formatter:Lp}),value:zr(Yl.black()),viewProps:e.viewProps});return cl({primary:e.value,secondary:i.value,forward:t=>new Yl(Il(t.getComponents()),t.mode),backward:(t,e)=>new Yl(Ul(Il(e.getComponents(t.mode)),t.getComponents()[3]),t.mode)}),[i]}(t,{value:this.value,viewProps:this.viewProps})}onModeSelectChange_(t){const e=t.currentTarget;this.colorMode.rawValue=e.value,this.ccs_=this.createComponentControllers_(this.view.element.ownerDocument),this.view.inputViews=this.ccs_.map(t=>t.view)}},qp=$o("hpl"),Hp=class{constructor(t,e){this.onValueChange_=this.onValueChange_.bind(this),this.value=e.value,this.value.emitter.on("change",this.onValueChange_),this.element=t.createElement("div"),this.element.classList.add(qp()),e.viewProps.bindClassModifiers(this.element),e.viewProps.bindTabIndex(this.element);const i=t.createElement("div");i.classList.add(qp("c")),this.element.appendChild(i);const n=t.createElement("div");n.classList.add(qp("m")),this.element.appendChild(n),this.markerElem_=n,this.update_()}update_(){const[t]=this.value.rawValue.getComponents("hsv");this.markerElem_.style.backgroundColor=Sp(new Yl([t,100,100],"hsv"));const e=oo(t,0,360,0,100);this.markerElem_.style.left=`${e}%`}onValueChange_(){this.update_()}},Gp=class{constructor(t,e){this.onKeyDown_=this.onKeyDown_.bind(this),this.onKeyUp_=this.onKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.value=e.value,this.viewProps=e.viewProps,this.view=new Hp(t,{value:this.value,viewProps:this.viewProps}),this.ptHandler_=new gl(this.view.element),this.ptHandler_.emitter.on("down",this.onPointerDown_),this.ptHandler_.emitter.on("move",this.onPointerMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.element.addEventListener("keydown",this.onKeyDown_),this.view.element.addEventListener("keyup",this.onKeyUp_)}handlePointerEvent_(t,e){if(!t.point)return;const i=oo(lo(t.point.x,0,t.bounds.width),0,t.bounds.width,0,360),[,n,s,r]=this.value.rawValue.getComponents("hsv");this.value.setRawValue(new Yl([i,n,s,r],"hsv"),e)}onPointerDown_(t){this.handlePointerEvent_(t.data,{forceEmit:!1,last:!1})}onPointerMove_(t){this.handlePointerEvent_(t.data,{forceEmit:!1,last:!1})}onPointerUp_(t){this.handlePointerEvent_(t.data,{forceEmit:!0,last:!0})}onKeyDown_(t){const e=dl(Zl(!1),vl(t));if(0===e)return;const[i,n,s,r]=this.value.rawValue.getComponents("hsv");this.value.setRawValue(new Yl([i+e,n,s,r],"hsv"),{forceEmit:!1,last:!1})}onKeyUp_(t){0!==dl(Zl(!1),vl(t))&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}},Yp=$o("svp"),Xp=class{constructor(t,e){this.onValueChange_=this.onValueChange_.bind(this),this.value=e.value,this.value.emitter.on("change",this.onValueChange_),this.element=t.createElement("div"),this.element.classList.add(Yp()),e.viewProps.bindClassModifiers(this.element),e.viewProps.bindTabIndex(this.element);const i=t.createElement("canvas");i.height=64,i.width=64,i.classList.add(Yp("c")),this.element.appendChild(i),this.canvasElement=i;const n=t.createElement("div");n.classList.add(Yp("m")),this.element.appendChild(n),this.markerElem_=n,this.update_()}update_(){const t=function(t){const e=t.ownerDocument.defaultView;return e&&"document"in e?t.getContext("2d",{willReadFrequently:!0}):null}(this.canvasElement);if(!t)return;const e=this.value.rawValue.getComponents("hsv"),i=this.canvasElement.width,n=this.canvasElement.height,s=t.getImageData(0,0,i,n),r=s.data;for(let l=0;lt.getComponents()[3],backward:(t,e)=>{const i=t.getComponents();return i[3]=e,new Yl(i,t.mode)}}),this.textsC_=new $p(t,{colorType:e.colorType,value:this.value,viewProps:this.viewProps}),this.view=new Wl(t,{alphaViews:this.alphaIcs_?{palette:this.alphaIcs_.palette.view,text:this.alphaIcs_.text.view}:null,hPaletteView:this.hPaletteC_.view,supportsAlpha:e.supportsAlpha,svPaletteView:this.svPaletteC_.view,textsView:this.textsC_.view,viewProps:this.viewProps})}get textsController(){return this.textsC_}},Jp=$o("colsw"),Zp=class{constructor(t,e){this.onValueChange_=this.onValueChange_.bind(this),e.value.emitter.on("change",this.onValueChange_),this.value=e.value,this.element=t.createElement("div"),this.element.classList.add(Jp()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("div");i.classList.add(Jp("sw")),this.element.appendChild(i),this.swatchElem_=i;const n=t.createElement("button");n.classList.add(Jp("b")),e.viewProps.bindDisabled(n),this.element.appendChild(n),this.buttonElement=n,this.update_()}update_(){const t=this.value.rawValue;this.swatchElem_.style.backgroundColor=Mp(t)}onValueChange_(){this.update_()}},th=class{constructor(t,e){this.value=e.value,this.viewProps=e.viewProps,this.view=new Zp(t,{value:this.value,viewProps:this.viewProps})}},eh=class{constructor(t,e){this.onButtonBlur_=this.onButtonBlur_.bind(this),this.onButtonClick_=this.onButtonClick_.bind(this),this.onPopupChildBlur_=this.onPopupChildBlur_.bind(this),this.onPopupChildKeydown_=this.onPopupChildKeydown_.bind(this),this.value=e.value,this.viewProps=e.viewProps,this.foldable_=_a.create(e.expanded),this.swatchC_=new th(t,{value:this.value,viewProps:this.viewProps});const i=this.swatchC_.view.buttonElement;i.addEventListener("blur",this.onButtonBlur_),i.addEventListener("click",this.onButtonClick_),this.textC_=new sl(t,{parser:e.parser,props:Rr.fromObject({formatter:e.formatter}),value:this.value,viewProps:this.viewProps}),this.view=new Nl(t,{foldable:this.foldable_,pickerLayout:e.pickerLayout}),this.view.swatchElement.appendChild(this.swatchC_.view.element),this.view.textElement.appendChild(this.textC_.view.element),this.popC_="popup"===e.pickerLayout?new el(t,{viewProps:this.viewProps}):null;const n=new Qp(t,{colorType:e.colorType,supportsAlpha:e.supportsAlpha,value:this.value,viewProps:this.viewProps});n.view.allFocusableElements.forEach(t=>{t.addEventListener("blur",this.onPopupChildBlur_),t.addEventListener("keydown",this.onPopupChildKeydown_)}),this.pickerC_=n,this.popC_?(this.view.element.appendChild(this.popC_.view.element),this.popC_.view.element.appendChild(n.view.element),cl({primary:this.foldable_.value("expanded"),secondary:this.popC_.shows,forward:t=>t,backward:(t,e)=>e})):this.view.pickerElement&&(this.view.pickerElement.appendChild(this.pickerC_.view.element),xa(this.foldable_,this.view.pickerElement))}get textController(){return this.textC_}onButtonBlur_(t){if(!this.popC_)return;const e=this.view.element,i=t.relatedTarget;i&&e.contains(i)||(this.popC_.shows.rawValue=!1)}onButtonClick_(){this.foldable_.set("expanded",!this.foldable_.get("expanded")),this.foldable_.get("expanded")&&this.pickerC_.view.allFocusableElements[0].focus()}onPopupChildBlur_(t){if(!this.popC_)return;const e=this.popC_.view.element,i=Ko(t);i&&e.contains(i)||i&&i===this.swatchC_.view.buttonElement&&!Oo(e.ownerDocument)||(this.popC_.shows.rawValue=!1)}onPopupChildKeydown_(t){this.popC_?"Escape"===t.key&&(this.popC_.shows.rawValue=!1):this.view.pickerElement&&"Escape"===t.key&&this.swatchC_.view.buttonElement.focus()}};function ih(t){return Il(t.getComponents("rgb")).reduce((t,e)=>t<<8|255&Math.floor(e),0)}function nh(t){return t.getComponents("rgb").reduce((t,e,i)=>t<<8|255&Math.floor(3===i?255*e:e),0)>>>0}function sh(t){return"number"!=typeof t?Yl.black():new Yl([(e=t)>>16&255,e>>8&255,255&e],"rgb");var e}function rh(t){return"number"!=typeof t?Yl.black():new Yl([(e=t)>>24&255,e>>16&255,e>>8&255,oo(255&e,0,255,0,1)],"rgb");var e}function oh(t,e){return"object"==typeof t&&!Er(t)&&e in t&&"number"==typeof t[e]}function ah(t){return oh(t,"r")&&oh(t,"g")&&oh(t,"b")}function lh(t){return ah(t)&&oh(t,"a")}function ph(t){return ah(t)}function hh(t,e){if(t.mode!==e.mode)return!1;if(t.type!==e.type)return!1;const i=t.getComponents(),n=e.getComponents();for(let s=0;st?Op(i,e):Dp(i,e)}pa({id:"input-color-number",type:"input",accept:(t,e)=>{if("number"!=typeof t)return null;if(!function(t){return"color"in t||"color"===t.view}(e))return null;const i=Jl(e);return i?{initialValue:t,params:Object.assign(Object.assign({},i),{supportsAlpha:(n=e,!!(null===(s=null==n?void 0:n.color)||void 0===s?void 0:s.alpha))})}:null;var n,s},binding:{reader:t=>t.params.supportsAlpha?rh:sh,equals:hh,writer:t=>function(t){const e=t?nh:ih;return(t,i)=>{Ol(t,e(i))}}(t.params.supportsAlpha)},controller:t=>{var e,i,n;return new eh(t.document,{colorType:"int",expanded:null!==(e=t.params.expanded)&&void 0!==e&&e,formatter:(n=t.params.supportsAlpha,n?t=>Mp(t,"0x"):t=>Lp(t,"0x")),parser:Ep("int"),pickerLayout:null!==(i=t.params.picker)&&void 0!==i?i:"popup",supportsAlpha:t.params.supportsAlpha,value:t.value,viewProps:t.viewProps})}}),pa({id:"input-color-object",type:"input",accept:(t,e)=>{var i;if(!ph(t))return null;const n=Jl(e);return n?{initialValue:t,params:Object.assign(Object.assign({},n),{colorType:null!==(i=tp(e))&&void 0!==i?i:"int"})}:null},binding:{reader:t=>{return e=t.params.colorType,t=>sp(function(t,e){return ph(t)?"int"===e?new Yl(ch(t),"rgb"):"float"===e?new ep(ch(t),"rgb"):sp(Yl.black(),"int"):sp(Yl.black(),e)}(t,e),"int");var e},equals:hh,writer:t=>{return e=lh(t.initialValue),i=t.params.colorType,(t,n)=>{e?function(t,e,i){const n=sp(e,i).toRgbaObject();t.writeProperty("r",n.r),t.writeProperty("g",n.g),t.writeProperty("b",n.b),t.writeProperty("a",n.a)}(t,n,i):function(t,e,i){const n=sp(e,i).toRgbaObject();t.writeProperty("r",n.r),t.writeProperty("g",n.g),t.writeProperty("b",n.b)}(t,n,i)};var e,i}},controller:t=>{var e,i;const n=lh(t.initialValue);return new eh(t.document,{colorType:t.params.colorType,expanded:null!==(e=t.params.expanded)&&void 0!==e&&e,formatter:dh(n,t.params.colorType),parser:Ep("int"),pickerLayout:null!==(i=t.params.picker)&&void 0!==i?i:"popup",supportsAlpha:n,value:t.value,viewProps:t.viewProps})}}),pa({id:"input-color-string",type:"input",accept:(t,e)=>{if("string"!=typeof t)return null;if("text"===e.view)return null;const i=function(t,e="int"){const i=function(t){return Pp.reduce((e,{parser:i,result:n})=>e||(i(t)?n:null),null)}(t);return i?"hex"===i.notation&&"float"!==e?Object.assign(Object.assign({},i),{type:"int"}):"func"===i.notation?Object.assign(Object.assign({},i),{type:e}):null:null}(t,tp(e));if(!i)return null;const n=zp(i);if(!n)return null;const s=Jl(e);return s?{initialValue:t,params:Object.assign(Object.assign({},s),{format:i,stringifier:n})}:null},binding:{reader:()=>kp,equals:hh,writer:t=>{const e=function(t){const e=zp(t);return e?(t,i)=>{Ol(t,e(i))}:null}(t.params.format);if(!e)throw jr.notBindable();return e}},controller:t=>{var e,i;return new eh(t.document,{colorType:t.params.format.type,expanded:null!==(e=t.params.expanded)&&void 0!==e&&e,formatter:t.params.stringifier,parser:Ep("int"),pickerLayout:null!==(i=t.params.picker)&&void 0!==i?i:"popup",supportsAlpha:t.params.format.alpha,value:t.value,viewProps:t.viewProps})}});var uh=class{constructor(t){this.components=t.components,this.asm_=t.assembly}constrain(t){const e=this.asm_.toComponents(t).map((t,e)=>{var i,n;return null!==(n=null===(i=this.components[e])||void 0===i?void 0:i.constrain(t))&&void 0!==n?n:t});return this.asm_.fromComponents(e)}},vh=$o("pndtxt"),mh=class{constructor(t,e){this.textViews=e.textViews,this.element=t.createElement("div"),this.element.classList.add(vh()),this.textViews.forEach(e=>{const i=t.createElement("div");i.classList.add(vh("a")),i.appendChild(e.element),this.element.appendChild(i)})}},bh=class{constructor(t,e){this.value=e.value,this.viewProps=e.viewProps,this.acs_=e.axes.map((i,n)=>function(t,e,i){return new fl(t,{arrayPosition:0===i?"fst":i===e.axes.length-1?"lst":"mid",parser:e.parser,props:e.axes[i].textProps,value:zr(0,{constraint:e.axes[i].constraint}),viewProps:e.viewProps})}(t,e,n)),this.acs_.forEach((t,i)=>{cl({primary:this.value,secondary:t.value,forward:t=>e.assembly.toComponents(t)[i],backward:(t,n)=>{const s=e.assembly.toComponents(t);return s[i]=n,e.assembly.fromComponents(s)}})}),this.view=new mh(t,{textViews:this.acs_.map(t=>t.view)})}get textControllers(){return this.acs_}},gh=class extends Po{get max(){return this.controller.valueController.sliderController.props.get("max")}set max(t){this.controller.valueController.sliderController.props.set("max",t)}get min(){return this.controller.valueController.sliderController.props.get("min")}set min(t){this.controller.valueController.sliderController.props.set("min",t)}};pa({id:"input-number",type:"input",accept:(t,e)=>{if("number"!=typeof t)return null;const i=Lo(e,t=>Object.assign(Object.assign({},go(t)),{options:t.optional.custom(Ga),readonly:t.optional.constant(!1)}));return i?{initialValue:t,params:i}:null},binding:{reader:t=>so,constraint:t=>function(t,e){const i=[],n=vo(t,e);n&&i.push(n);const s=mo(t);s&&i.push(s);const r=Xa(t.options);return r&&i.push(r),new $a(i)}(t.params,t.initialValue),writer:t=>Ol},controller:t=>{const e=t.value,i=t.constraint,n=i&&qa(i,Ha);if(n)return new Ja(t.document,{props:new Rr({options:n.values.value("options")}),value:e,viewProps:t.viewProps});const s=bo(t.params,e.rawValue),r=i&&qa(i,Nr);return r?new kl(t.document,Object.assign(Object.assign({},(o=Object.assign(Object.assign({},s),{keyScale:zr(s.keyScale),max:r.values.value("max"),min:r.values.value("min")}),{sliderProps:new Rr({keyScale:o.keyScale,max:o.max,min:o.min}),textProps:new Rr({formatter:zr(o.formatter),keyScale:o.keyScale,pointerScale:zr(o.pointerScale)})})),{parser:no,value:e,viewProps:t.viewProps})):new fl(t.document,{parser:no,props:Rr.fromObject(s),value:e,viewProps:t.viewProps});var o},api:t=>"number"!=typeof t.controller.value.rawValue?null:t.controller.valueController instanceof kl?new gh(t.controller):t.controller.valueController instanceof Ja?new Ia(t.controller):null});var wh=class{constructor(t=0,e=0){this.x=t,this.y=e}getComponents(){return[this.x,this.y]}static isObject(t){if(Er(t))return!1;const e=t.x,i=t.y;return"number"==typeof e&&"number"==typeof i}static equals(t,e){return t.x===e.x&&t.y===e.y}toObject(){return{x:this.x,y:this.y}}},_h={toComponents:t=>t.getComponents(),fromComponents:t=>new wh(...t)},fh=$o("p2d"),xh=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(fh()),e.viewProps.bindClassModifiers(this.element),Io(e.expanded,ia(this.element,fh(void 0,"expanded")));const i=t.createElement("div");i.classList.add(fh("h")),this.element.appendChild(i);const n=t.createElement("button");n.classList.add(fh("b")),n.appendChild(To(t,"p2dpad")),e.viewProps.bindDisabled(n),i.appendChild(n),this.buttonElement=n;const s=t.createElement("div");if(s.classList.add(fh("t")),i.appendChild(s),this.textElement=s,"inline"===e.pickerLayout){const e=t.createElement("div");e.classList.add(fh("p")),this.element.appendChild(e),this.pickerElement=e}else this.pickerElement=null}},Ch=$o("p2dp"),yh=class{constructor(t,e){this.onFoldableChange_=this.onFoldableChange_.bind(this),this.onPropsChange_=this.onPropsChange_.bind(this),this.onValueChange_=this.onValueChange_.bind(this),this.props_=e.props,this.props_.emitter.on("change",this.onPropsChange_),this.element=t.createElement("div"),this.element.classList.add(Ch()),"popup"===e.layout&&this.element.classList.add(Ch(void 0,"p")),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("div");i.classList.add(Ch("p")),e.viewProps.bindTabIndex(i),this.element.appendChild(i),this.padElement=i;const n=t.createElementNS(Do,"svg");n.classList.add(Ch("g")),this.padElement.appendChild(n),this.svgElem_=n;const s=t.createElementNS(Do,"line");s.classList.add(Ch("ax")),s.setAttributeNS(null,"x1","0"),s.setAttributeNS(null,"y1","50%"),s.setAttributeNS(null,"x2","100%"),s.setAttributeNS(null,"y2","50%"),this.svgElem_.appendChild(s);const r=t.createElementNS(Do,"line");r.classList.add(Ch("ax")),r.setAttributeNS(null,"x1","50%"),r.setAttributeNS(null,"y1","0"),r.setAttributeNS(null,"x2","50%"),r.setAttributeNS(null,"y2","100%"),this.svgElem_.appendChild(r);const o=t.createElementNS(Do,"line");o.classList.add(Ch("l")),o.setAttributeNS(null,"x1","50%"),o.setAttributeNS(null,"y1","50%"),this.svgElem_.appendChild(o),this.lineElem_=o;const a=t.createElement("div");a.classList.add(Ch("m")),this.padElement.appendChild(a),this.markerElem_=a,e.value.emitter.on("change",this.onValueChange_),this.value=e.value,this.update_()}get allFocusableElements(){return[this.padElement]}update_(){const[t,e]=this.value.rawValue.getComponents(),i=this.props_.get("max"),n=oo(t,-i,+i,0,100),s=oo(e,-i,+i,0,100),r=this.props_.get("invertsY")?100-s:s;this.lineElem_.setAttributeNS(null,"x2",`${n}%`),this.lineElem_.setAttributeNS(null,"y2",`${r}%`),this.markerElem_.style.left=`${n}%`,this.markerElem_.style.top=`${r}%`}onValueChange_(){this.update_()}onPropsChange_(){this.update_()}onFoldableChange_(){this.update_()}};function Ph(t,e,i){return[dl(e[0],vl(t)),dl(e[1],ul(t))*(i?1:-1)]}var Eh=class{constructor(t,e){this.onPadKeyDown_=this.onPadKeyDown_.bind(this),this.onPadKeyUp_=this.onPadKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.props=e.props,this.value=e.value,this.viewProps=e.viewProps,this.view=new yh(t,{layout:e.layout,props:this.props,value:this.value,viewProps:this.viewProps}),this.ptHandler_=new gl(this.view.padElement),this.ptHandler_.emitter.on("down",this.onPointerDown_),this.ptHandler_.emitter.on("move",this.onPointerMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.padElement.addEventListener("keydown",this.onPadKeyDown_),this.view.padElement.addEventListener("keyup",this.onPadKeyUp_)}handlePointerEvent_(t,e){if(!t.point)return;const i=this.props.get("max"),n=oo(t.point.x,0,t.bounds.width,-i,+i),s=oo(this.props.get("invertsY")?t.bounds.height-t.point.y:t.point.y,0,t.bounds.height,-i,+i);this.value.setRawValue(new wh(n,s),e)}onPointerDown_(t){this.handlePointerEvent_(t.data,{forceEmit:!1,last:!1})}onPointerMove_(t){this.handlePointerEvent_(t.data,{forceEmit:!1,last:!1})}onPointerUp_(t){this.handlePointerEvent_(t.data,{forceEmit:!0,last:!0})}onPadKeyDown_(t){ml(t.key)&&t.preventDefault();const[e,i]=Ph(t,[this.props.get("xKeyScale"),this.props.get("yKeyScale")],this.props.get("invertsY"));0===e&&0===i||this.value.setRawValue(new wh(this.value.rawValue.x+e,this.value.rawValue.y+i),{forceEmit:!1,last:!1})}onPadKeyUp_(t){const[e,i]=Ph(t,[this.props.get("xKeyScale"),this.props.get("yKeyScale")],this.props.get("invertsY"));0===e&&0===i||this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}},kh=class{constructor(t,e){var i,n;this.onPopupChildBlur_=this.onPopupChildBlur_.bind(this),this.onPopupChildKeydown_=this.onPopupChildKeydown_.bind(this),this.onPadButtonBlur_=this.onPadButtonBlur_.bind(this),this.onPadButtonClick_=this.onPadButtonClick_.bind(this),this.value=e.value,this.viewProps=e.viewProps,this.foldable_=_a.create(e.expanded),this.popC_="popup"===e.pickerLayout?new el(t,{viewProps:this.viewProps}):null;const s=new Eh(t,{layout:e.pickerLayout,props:new Rr({invertsY:zr(e.invertsY),max:zr(e.max),xKeyScale:e.axes[0].textProps.value("keyScale"),yKeyScale:e.axes[1].textProps.value("keyScale")}),value:this.value,viewProps:this.viewProps});s.view.allFocusableElements.forEach(t=>{t.addEventListener("blur",this.onPopupChildBlur_),t.addEventListener("keydown",this.onPopupChildKeydown_)}),this.pickerC_=s,this.textC_=new bh(t,{assembly:_h,axes:e.axes,parser:e.parser,value:this.value,viewProps:this.viewProps}),this.view=new xh(t,{expanded:this.foldable_.value("expanded"),pickerLayout:e.pickerLayout,viewProps:this.viewProps}),this.view.textElement.appendChild(this.textC_.view.element),null===(i=this.view.buttonElement)||void 0===i||i.addEventListener("blur",this.onPadButtonBlur_),null===(n=this.view.buttonElement)||void 0===n||n.addEventListener("click",this.onPadButtonClick_),this.popC_?(this.view.element.appendChild(this.popC_.view.element),this.popC_.view.element.appendChild(this.pickerC_.view.element),cl({primary:this.foldable_.value("expanded"),secondary:this.popC_.shows,forward:t=>t,backward:(t,e)=>e})):this.view.pickerElement&&(this.view.pickerElement.appendChild(this.pickerC_.view.element),xa(this.foldable_,this.view.pickerElement))}get textController(){return this.textC_}onPadButtonBlur_(t){if(!this.popC_)return;const e=this.view.element,i=t.relatedTarget;i&&e.contains(i)||(this.popC_.shows.rawValue=!1)}onPadButtonClick_(){this.foldable_.set("expanded",!this.foldable_.get("expanded")),this.foldable_.get("expanded")&&this.pickerC_.view.allFocusableElements[0].focus()}onPopupChildBlur_(t){if(!this.popC_)return;const e=this.popC_.view.element,i=Ko(t);i&&e.contains(i)||i&&i===this.view.buttonElement&&!Oo(e.ownerDocument)||(this.popC_.shows.rawValue=!1)}onPopupChildKeydown_(t){this.popC_?"Escape"===t.key&&(this.popC_.shows.rawValue=!1):this.view.pickerElement&&"Escape"===t.key&&this.view.buttonElement.focus()}};function Vh(t){return wh.isObject(t)?new wh(t.x,t.y):new wh}function Lh(t,e){t.writeProperty("x",e.x),t.writeProperty("y",e.y)}function Mh(t,e){var i,n;if(!Er(t.min)||!Er(t.max))return Math.max(Math.abs(null!==(i=t.min)&&void 0!==i?i:0),Math.abs(null!==(n=t.max)&&void 0!==n?n:0));const s=co(t);return Math.max(10*Math.abs(s),10*Math.abs(e))}function Sh(t,e){var i,n;const s=Mh(Mr(t,null!==(i=t.x)&&void 0!==i?i:{}),e.x),r=Mh(Mr(t,null!==(n=t.y)&&void 0!==n?n:{}),e.y);return Math.max(s,r)}function jh(t){if(!("y"in t))return!1;const e=t.y;return!!e&&"inverted"in e&&!!e.inverted}pa({id:"input-point2d",type:"input",accept:(t,e)=>{if(!wh.isObject(t))return null;const i=Lo(e,t=>Object.assign(Object.assign({},Sl(t)),{expanded:t.optional.boolean,picker:t.optional.custom(Al),readonly:t.optional.constant(!1),x:t.optional.custom(jl),y:t.optional.object(Object.assign(Object.assign({},Sl(t)),{inverted:t.optional.boolean}))}));return i?{initialValue:t,params:i}:null},binding:{reader:()=>Vh,constraint:t=>{return e=t.params,i=t.initialValue,new uh({assembly:_h,components:[Dl(Object.assign(Object.assign({},e),e.x),i.x),Dl(Object.assign(Object.assign({},e),e.y),i.y)]});var e,i},equals:wh.equals,writer:()=>Lh},controller:t=>{var e,i;const n=t.document,s=t.value,r=t.constraint,o=[t.params.x,t.params.y];return new kh(n,{axes:s.rawValue.getComponents().map((e,i)=>{var n;return wo({constraint:r.components[i],initialValue:e,params:Mr(t.params,null!==(n=o[i])&&void 0!==n?n:{})})}),expanded:null!==(e=t.params.expanded)&&void 0!==e&&e,invertsY:jh(t.params),max:Sh(t.params,s.rawValue),parser:no,pickerLayout:null!==(i=t.params.picker)&&void 0!==i?i:"popup",value:s,viewProps:t.viewProps})}});var Dh=class{constructor(t=0,e=0,i=0){this.x=t,this.y=e,this.z=i}getComponents(){return[this.x,this.y,this.z]}static isObject(t){if(Er(t))return!1;const e=t.x,i=t.y,n=t.z;return"number"==typeof e&&"number"==typeof i&&"number"==typeof n}static equals(t,e){return t.x===e.x&&t.y===e.y&&t.z===e.z}toObject(){return{x:this.x,y:this.y,z:this.z}}},Ah={toComponents:t=>t.getComponents(),fromComponents:t=>new Dh(...t)};function Oh(t){return Dh.isObject(t)?new Dh(t.x,t.y,t.z):new Dh}function Bh(t,e){t.writeProperty("x",e.x),t.writeProperty("y",e.y),t.writeProperty("z",e.z)}pa({id:"input-point3d",type:"input",accept:(t,e)=>{if(!Dh.isObject(t))return null;const i=Lo(e,t=>Object.assign(Object.assign({},Sl(t)),{readonly:t.optional.constant(!1),x:t.optional.custom(jl),y:t.optional.custom(jl),z:t.optional.custom(jl)}));return i?{initialValue:t,params:i}:null},binding:{reader:t=>Oh,constraint:t=>{return e=t.params,i=t.initialValue,new uh({assembly:Ah,components:[Dl(Object.assign(Object.assign({},e),e.x),i.x),Dl(Object.assign(Object.assign({},e),e.y),i.y),Dl(Object.assign(Object.assign({},e),e.z),i.z)]});var e,i},equals:Dh.equals,writer:t=>Bh},controller:t=>{const e=t.value,i=t.constraint,n=[t.params.x,t.params.y,t.params.z];return new bh(t.document,{assembly:Ah,axes:e.rawValue.getComponents().map((e,s)=>{var r;return wo({constraint:i.components[s],initialValue:e,params:Mr(t.params,null!==(r=n[s])&&void 0!==r?r:{})})}),parser:no,value:e,viewProps:t.viewProps})}});var Th=class{constructor(t=0,e=0,i=0,n=0){this.x=t,this.y=e,this.z=i,this.w=n}getComponents(){return[this.x,this.y,this.z,this.w]}static isObject(t){if(Er(t))return!1;const e=t.x,i=t.y,n=t.z,s=t.w;return"number"==typeof e&&"number"==typeof i&&"number"==typeof n&&"number"==typeof s}static equals(t,e){return t.x===e.x&&t.y===e.y&&t.z===e.z&&t.w===e.w}toObject(){return{x:this.x,y:this.y,z:this.z,w:this.w}}},zh={toComponents:t=>t.getComponents(),fromComponents:t=>new Th(...t)};function Rh(t){return Th.isObject(t)?new Th(t.x,t.y,t.z,t.w):new Th}function Nh(t,e){t.writeProperty("x",e.x),t.writeProperty("y",e.y),t.writeProperty("z",e.z),t.writeProperty("w",e.w)}pa({id:"input-point4d",type:"input",accept:(t,e)=>{if(!Th.isObject(t))return null;const i=Lo(e,t=>Object.assign(Object.assign({},Sl(t)),{readonly:t.optional.constant(!1),w:t.optional.custom(jl),x:t.optional.custom(jl),y:t.optional.custom(jl),z:t.optional.custom(jl)}));return i?{initialValue:t,params:i}:null},binding:{reader:t=>Rh,constraint:t=>{return e=t.params,i=t.initialValue,new uh({assembly:zh,components:[Dl(Object.assign(Object.assign({},e),e.x),i.x),Dl(Object.assign(Object.assign({},e),e.y),i.y),Dl(Object.assign(Object.assign({},e),e.z),i.z),Dl(Object.assign(Object.assign({},e),e.w),i.w)]});var e,i},equals:Th.equals,writer:t=>Nh},controller:t=>{const e=t.value,i=t.constraint,n=[t.params.x,t.params.y,t.params.z,t.params.w];return new bh(t.document,{assembly:zh,axes:e.rawValue.getComponents().map((e,s)=>{var r;return wo({constraint:i.components[s],initialValue:e,params:Mr(t.params,null!==(r=n[s])&&void 0!==r?r:{})})}),parser:no,value:e,viewProps:t.viewProps})}}),pa({id:"input-string",type:"input",accept:(t,e)=>{if("string"!=typeof t)return null;const i=Lo(e,t=>({readonly:t.optional.constant(!1),options:t.optional.custom(Ga)}));return i?{initialValue:t,params:i}:null},binding:{reader:t=>pl,constraint:t=>function(t){const e=[],i=Xa(t.options);return i&&e.push(i),new $a(e)}(t.params),writer:t=>Ol},controller:t=>{const e=t.document,i=t.value,n=t.constraint,s=n&&qa(n,Ha);return s?new Ja(e,{props:new Rr({options:s.values.value("options")}),value:i,viewProps:t.viewProps}):new sl(e,{parser:t=>t,props:Rr.fromObject({formatter:hl}),value:i,viewProps:t.viewProps})},api:t=>"string"!=typeof t.controller.value.rawValue?null:t.controller.valueController instanceof Ja?new Ia(t.controller):null});var Kh=200,Ih=3,Uh=$o("mll"),Fh=class{constructor(t,e){this.onValueUpdate_=this.onValueUpdate_.bind(this),this.formatter_=e.formatter,this.element=t.createElement("div"),this.element.classList.add(Uh()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("textarea");i.classList.add(Uh("i")),i.style.height=`calc(var(${Ll("containerUnitSize")}) * ${e.rows})`,i.readOnly=!0,e.viewProps.bindDisabled(i),this.element.appendChild(i),this.textareaElem_=i,e.value.emitter.on("change",this.onValueUpdate_),this.value=e.value,this.update_()}update_(){const t=this.textareaElem_,e=t.scrollTop===t.scrollHeight-t.clientHeight,i=[];this.value.rawValue.forEach(t=>{void 0!==t&&i.push(this.formatter_(t))}),t.textContent=i.join("\n"),e&&(t.scrollTop=t.scrollHeight)}onValueUpdate_(){this.update_()}},$h=class{constructor(t,e){this.value=e.value,this.viewProps=e.viewProps,this.view=new Fh(t,{formatter:e.formatter,rows:e.rows,value:this.value,viewProps:this.viewProps})}},qh=$o("sgl"),Hh=class{constructor(t,e){this.onValueUpdate_=this.onValueUpdate_.bind(this),this.formatter_=e.formatter,this.element=t.createElement("div"),this.element.classList.add(qh()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("input");i.classList.add(qh("i")),i.readOnly=!0,i.type="text",e.viewProps.bindDisabled(i),this.element.appendChild(i),this.inputElement=i,e.value.emitter.on("change",this.onValueUpdate_),this.value=e.value,this.update_()}update_(){const t=this.value.rawValue,e=t[t.length-1];this.inputElement.value=void 0!==e?this.formatter_(e):""}onValueUpdate_(){this.update_()}},Gh=class{constructor(t,e){this.value=e.value,this.viewProps=e.viewProps,this.view=new Hh(t,{formatter:e.formatter,value:this.value,viewProps:this.viewProps})}};pa({id:"monitor-bool",type:"monitor",accept:(t,e)=>{if("boolean"!=typeof t)return null;const i=Lo(e,t=>({readonly:t.required.constant(!0),rows:t.optional.number}));return i?{initialValue:t,params:i}:null},binding:{reader:t=>rl},controller:t=>{var e;return 1===t.value.rawValue.length?new Gh(t.document,{formatter:ol,value:t.value,viewProps:t.viewProps}):new $h(t.document,{formatter:ol,rows:null!==(e=t.params.rows)&&void 0!==e?e:Ih,value:t.value,viewProps:t.viewProps})}});var Yh=class extends Po{get max(){return this.controller.valueController.props.get("max")}set max(t){this.controller.valueController.props.set("max",t)}get min(){return this.controller.valueController.props.get("min")}set min(t){this.controller.valueController.props.set("min",t)}},Xh=$o("grl"),Wh=class{constructor(t,e){this.onCursorChange_=this.onCursorChange_.bind(this),this.onValueUpdate_=this.onValueUpdate_.bind(this),this.element=t.createElement("div"),this.element.classList.add(Xh()),e.viewProps.bindClassModifiers(this.element),this.formatter_=e.formatter,this.props_=e.props,this.cursor_=e.cursor,this.cursor_.emitter.on("change",this.onCursorChange_);const i=t.createElementNS(Do,"svg");i.classList.add(Xh("g")),i.style.height=`calc(var(${Ll("containerUnitSize")}) * ${e.rows})`,this.element.appendChild(i),this.svgElem_=i;const n=t.createElementNS(Do,"polyline");this.svgElem_.appendChild(n),this.lineElem_=n;const s=t.createElement("div");s.classList.add(Xh("t"),$o("tt")()),this.element.appendChild(s),this.tooltipElem_=s,e.value.emitter.on("change",this.onValueUpdate_),this.value=e.value,this.update_()}get graphElement(){return this.svgElem_}update_(){const t=this.svgElem_.getBoundingClientRect(),e=this.value.rawValue.length-1,i=this.props_.get("min"),n=this.props_.get("max"),s=[];this.value.rawValue.forEach((r,o)=>{if(void 0===r)return;const a=oo(o,0,e,0,t.width),l=oo(r,i,n,t.height,0);s.push([a,l].join(","))}),this.lineElem_.setAttributeNS(null,"points",s.join(" "));const r=this.tooltipElem_,o=this.value.rawValue[this.cursor_.rawValue];if(void 0===o)return void r.classList.remove(Xh("t","a"));const a=oo(this.cursor_.rawValue,0,e,0,t.width),l=oo(o,i,n,t.height,0);r.style.left=`${a}px`,r.style.top=`${l}px`,r.textContent=`${this.formatter_(o)}`,r.classList.contains(Xh("t","a"))||(r.classList.add(Xh("t","a"),Xh("t","in")),Ao(r),r.classList.remove(Xh("t","in")))}onValueUpdate_(){this.update_()}onCursorChange_(){this.update_()}},Qh=class{constructor(t,e){if(this.onGraphMouseMove_=this.onGraphMouseMove_.bind(this),this.onGraphMouseLeave_=this.onGraphMouseLeave_.bind(this),this.onGraphPointerDown_=this.onGraphPointerDown_.bind(this),this.onGraphPointerMove_=this.onGraphPointerMove_.bind(this),this.onGraphPointerUp_=this.onGraphPointerUp_.bind(this),this.props=e.props,this.value=e.value,this.viewProps=e.viewProps,this.cursor_=zr(-1),this.view=new Wh(t,{cursor:this.cursor_,formatter:e.formatter,rows:e.rows,props:this.props,value:this.value,viewProps:this.viewProps}),Oo(t)){const t=new gl(this.view.element);t.emitter.on("down",this.onGraphPointerDown_),t.emitter.on("move",this.onGraphPointerMove_),t.emitter.on("up",this.onGraphPointerUp_)}else this.view.element.addEventListener("mousemove",this.onGraphMouseMove_),this.view.element.addEventListener("mouseleave",this.onGraphMouseLeave_)}importProps(t){return Mo(t,null,t=>({max:t.required.number,min:t.required.number}),t=>(this.props.set("max",t.max),this.props.set("min",t.min),!0))}exportProps(){return So(null,{max:this.props.get("max"),min:this.props.get("min")})}onGraphMouseLeave_(){this.cursor_.rawValue=-1}onGraphMouseMove_(t){const e=this.view.element.getBoundingClientRect();this.cursor_.rawValue=Math.floor(oo(t.offsetX,0,e.width,0,this.value.rawValue.length))}onGraphPointerDown_(t){this.onGraphPointerMove_(t)}onGraphPointerMove_(t){t.data.point?this.cursor_.rawValue=Math.floor(oo(t.data.point.x,0,t.data.bounds.width,0,this.value.rawValue.length)):this.cursor_.rawValue=-1}onGraphPointerUp_(){this.cursor_.rawValue=-1}};function Jh(t){return Er(t.format)?ro(2):t.format}function Zh(t){return"graph"===t.view}pa({id:"monitor-number",type:"monitor",accept:(t,e)=>{if("number"!=typeof t)return null;const i=Lo(e,t=>({format:t.optional.function,max:t.optional.number,min:t.optional.number,readonly:t.required.constant(!0),rows:t.optional.number,view:t.optional.string}));return i?{initialValue:t,params:i}:null},binding:{defaultBufferSize:t=>Zh(t)?64:1,reader:t=>so},controller:t=>Zh(t.params)?function(t){var e,i,n;return new Qh(t.document,{formatter:Jh(t.params),rows:null!==(e=t.params.rows)&&void 0!==e?e:Ih,props:Rr.fromObject({max:null!==(i=t.params.max)&&void 0!==i?i:100,min:null!==(n=t.params.min)&&void 0!==n?n:0}),value:t.value,viewProps:t.viewProps})}(t):function(t){var e;return 1===t.value.rawValue.length?new Gh(t.document,{formatter:Jh(t.params),value:t.value,viewProps:t.viewProps}):new $h(t.document,{formatter:Jh(t.params),rows:null!==(e=t.params.rows)&&void 0!==e?e:Ih,value:t.value,viewProps:t.viewProps})}(t),api:t=>t.controller.valueController instanceof Qh?new Yh(t.controller):null}),pa({id:"monitor-string",type:"monitor",accept:(t,e)=>{if("string"!=typeof t)return null;const i=Lo(e,t=>({multiline:t.optional.boolean,readonly:t.required.constant(!0),rows:t.optional.number}));return i?{initialValue:t,params:i}:null},binding:{reader:t=>pl},controller:t=>{var e;const i=t.value;return i.rawValue.length>1||t.params.multiline?new $h(t.document,{formatter:hl,rows:null!==(e=t.params.rows)&&void 0!==e?e:Ih,value:i,viewProps:t.viewProps}):new Gh(t.document,{formatter:hl,value:i,viewProps:t.viewProps})}});var tc=class{constructor(t){this.controller_=t}get disabled(){return this.controller_.viewProps.get("disabled")}set disabled(t){this.controller_.viewProps.set("disabled",t)}get title(){var t;return null!==(t=this.controller_.props.get("title"))&&void 0!==t?t:""}set title(t){this.controller_.props.set("title",t)}on(t,e){const i=e.bind(this);return this.controller_.emitter.on(t,()=>{i(new fo(this))}),this}},ec=class extends fo{constructor(t,e,i){super(t),this.cell=e,this.index=i}},ic=class extends _o{constructor(t){super(t),this.cellToApiMap_=new Map,this.emitter_=new Ar;const e=this.controller.valueController;e.cellControllers.forEach((t,i)=>{const n=new tc(t);this.cellToApiMap_.set(t,n),t.emitter.on("click",()=>{const t=i%e.size[0],s=Math.floor(i/e.size[0]);this.emitter_.emit("click",{event:new ec(this,n,[t,s])})})})}cell(t,e){const i=this.controller.valueController,n=i.cellControllers[e*i.size[0]+t];return this.cellToApiMap_.get(n)}on(t,e){const i=e.bind(this);return this.emitter_.on(t,t=>{i(t.event)}),this}},nc=class{constructor(t,e){this.size=e.size;const[i,n]=this.size,s=[];for(let r=0;r{this.cellCs_.forEach(t=>{t.viewProps.set("disposed",!0)})}),this.view=new Ml(t,{viewProps:this.viewProps,viewName:"btngrid"}),this.view.element.style.gridTemplateColumns=`repeat(${i}, 1fr)`,this.cellCs_.forEach(t=>{this.view.element.appendChild(t.view.element)})}get cellControllers(){return this.cellCs_}},sc=class extends Wo{constructor(t,e){const i=e.valueController,n=new Go(t,{blade:e.blade,props:e.labelProps,valueController:i});super({blade:e.blade,view:n.view,viewProps:i.viewProps}),this.valueController=i,this.labelController=n}},rc=pa({id:"buttongrid",type:"blade",accept(t){const e=Lo(t,t=>({cells:t.required.function,size:t.required.array(t.required.number),view:t.required.constant("buttongrid"),label:t.optional.string}));return e?{params:e}:null},controller:t=>new sc(t.document,{blade:t.blade,labelProps:Rr.fromObject({label:t.params.label}),valueController:new nc(t.document,{cellConfig:t.params.cells,size:t.params.size})}),api:t=>t.controller instanceof sc?new ic(t.controller):null}),oc=class extends _o{get label(){return this.controller.labelController.props.get("label")}set label(t){this.controller.labelController.props.set("label",t)}get value(){return this.controller.valueController.value.rawValue}set value(t){this.controller.valueController.value.rawValue=t}on(t,e){const i=e.bind(this);return this.controller.valueController.value.emitter.on(t,t=>{i(new xo(this,t.rawValue,t.options.last))}),this}};function ac(t,e,i){return t*(1-i)+e*i}function lc(t,e){let i=.25,n=.5,s=-1;for(let r=0;r<20;r++){const[r,o]=t.curve(n);if(n+=i*(rt.toObject(),fromComponents:t=>new pc(...t)};function cc(t){const e=ro(2);return`cubic-bezier(${t.toObject().map(t=>e(t)).join(", ")})`}var dc=[0,.5,.5,1];function uc(t){const e=t.match(/^cubic-bezier\s*\(\s*([0-9.]+)\s*,\s*([0-9.]+)\s*,\s*([0-9.]+)\s*,\s*([0-9.]+)\s*\)$/);if(!e)return new pc(...dc);const i=[e[1],e[2],e[3],e[4]].reduce((t,e)=>{if(!t)return null;const i=Number(e);return isNaN(i)?null:[...t,i]},[]);return new pc(...null!=i?i:dc)}var vc=$o("cbz"),mc=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(vc()),e.viewProps.bindClassModifiers(this.element),e.foldable.bindExpandedClass(this.element,vc(void 0,"expanded")),Uo(e.foldable,"completed",ia(this.element,vc(void 0,"cpl")));const i=t.createElement("div");i.classList.add(vc("h")),this.element.appendChild(i);const n=t.createElement("button");n.classList.add(vc("b")),e.viewProps.bindDisabled(n);const s=t.createElementNS(Do,"svg");s.innerHTML='',n.appendChild(s),i.appendChild(n),this.buttonElement=n;const r=t.createElement("div");if(r.classList.add(vc("t")),i.appendChild(r),this.textElement=r,"inline"===e.pickerLayout){const e=t.createElement("div");e.classList.add(vc("p")),this.element.appendChild(e),this.pickerElement=e}else this.pickerElement=null}},bc=$o("cbzp"),gc=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(bc()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("div");i.classList.add(bc("g")),this.element.appendChild(i),this.graphElement=i;const n=t.createElement("div");n.classList.add(bc("t")),this.element.appendChild(n),this.textElement=n}};function wc(t,e){const i=new MutationObserver(t=>{for(const n of t)"childList"===n.type&&n.addedNodes.forEach(t=>{t.contains(t)&&(e(),i.disconnect())})}),n=t.ownerDocument;i.observe(n.body,{attributes:!0,childList:!0,subtree:!0})}var _c=$o("cbzg"),fc=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(_c()),e.viewProps.bindClassModifiers(this.element),e.viewProps.bindTabIndex(this.element);const i=t.createElement("div");i.classList.add(_c("p")),this.element.appendChild(i),this.previewElement=i;const n=t.createElementNS(Do,"svg");n.classList.add(_c("g")),this.element.appendChild(n),this.svgElem_=n;const s=t.createElementNS(Do,"path");s.classList.add(_c("u")),this.svgElem_.appendChild(s),this.guideElem_=s;const r=t.createElementNS(Do,"polyline");r.classList.add(_c("l")),this.svgElem_.appendChild(r),this.lineElem_=r,this.handleElems_=[t.createElement("div"),t.createElement("div")],this.handleElems_.forEach(t=>{t.classList.add(_c("h")),this.element.appendChild(t)}),this.vectorElems_=[t.createElementNS(Do,"line"),t.createElementNS(Do,"line")],this.vectorElems_.forEach(t=>{t.classList.add(_c("v")),this.svgElem_.appendChild(t)}),this.value_=e.value,this.value_.emitter.on("change",this.onValueChange_.bind(this)),this.sel_=e.selection,this.handleElems_.forEach((t,e)=>{var i,n;Io(this.sel_,(i=t=>t===e,n=ia(t,_c("h","sel")),t=>n(i(t))))}),wc(this.element,()=>{this.refresh()})}getVertMargin_(t){return.25*t}valueToPosition(t,e){const{clientWidth:i,clientHeight:n}=this.element,s=this.getVertMargin_(n);return{x:oo(t,0,1,0,i),y:oo(e,0,1,n-s,s)}}positionToValue(t,e){const i=this.element.getBoundingClientRect(),n=i.width,s=i.height,r=this.getVertMargin_(s);return{x:lo(oo(t,0,n,0,1),0,1),y:oo(e,s-r,r,0,1)}}refresh(){this.guideElem_.setAttributeNS(null,"d",[0,1].map(t=>{const e=this.valueToPosition(0,t),i=this.valueToPosition(1,t);return[`M ${e.x},${e.y}`,`L ${i.x},${i.y}`].join(" ")}).join(" "));const t=this.value_.rawValue,e=[];let i=0;for(;;){const n=this.valueToPosition(...t.curve(i));if(e.push([n.x,n.y].join(",")),i>=1)break;i=Math.min(i+.05,1)}this.lineElem_.setAttributeNS(null,"points",e.join(" "));const n=t.toObject();[0,1].forEach(t=>{const e=this.valueToPosition(t,t),i=this.valueToPosition(n[2*t],n[2*t+1]),s=this.vectorElems_[t];s.setAttributeNS(null,"x1",String(e.x)),s.setAttributeNS(null,"y1",String(e.y)),s.setAttributeNS(null,"x2",String(i.x)),s.setAttributeNS(null,"y2",String(i.y));const r=this.handleElems_[t];r.style.left=`${i.x}px`,r.style.top=`${i.y}px`})}onValueChange_(){this.refresh()}},xc=$o("cbzprv"),Cc=class{constructor(t,e){this.stopped_=!0,this.startTime_=-1,this.onDispose_=this.onDispose_.bind(this),this.onTimer_=this.onTimer_.bind(this),this.onValueChange_=this.onValueChange_.bind(this),this.element=t.createElement("div"),this.element.classList.add(xc()),e.viewProps.bindClassModifiers(this.element);const i=t.createElementNS(Do,"svg");i.classList.add(xc("g")),this.element.appendChild(i),this.svgElem_=i;const n=t.createElementNS(Do,"path");n.classList.add(xc("t")),this.svgElem_.appendChild(n),this.ticksElem_=n;const s=t.createElement("div");s.classList.add(xc("m")),this.element.appendChild(s),this.markerElem_=s,this.value_=e.value,this.value_.emitter.on("change",this.onValueChange_),e.viewProps.handleDispose(this.onDispose_),wc(this.element,()=>{this.refresh()})}play(){this.stop(),this.updateMarker_(0),this.markerElem_.classList.add(xc("m","a")),this.startTime_=(new Date).getTime()+400,this.stopped_=!1,requestAnimationFrame(this.onTimer_)}stop(){this.stopped_=!0,this.markerElem_.classList.remove(xc("m","a"))}onDispose_(){this.stop()}updateMarker_(t){const e=this.value_.rawValue.y(lo(t,0,1));this.markerElem_.style.left=100*e+"%"}refresh(){const{clientWidth:t,clientHeight:e}=this.svgElem_,i=[],n=this.value_.rawValue;for(let s=0;s<24;s++){const r=oo(s,0,23,0,1),o=oo(n.y(r),0,1,0,t);i.push(`M ${o},0 v${e}`)}this.ticksElem_.setAttributeNS(null,"d",i.join(" "))}onTimer_(){if(null===this.startTime_)return;const t=(new Date).getTime()-this.startTime_,e=t/1e3;this.updateMarker_(e),t>1400&&this.stop(),this.stopped_||requestAnimationFrame(this.onTimer_)}onValueChange_(){this.refresh(),this.play()}};function yc(t,e,i,n){const s=i-t,r=n-e;return Math.sqrt(s*s+r*r)}var Pc=class{constructor(t,e){this.onKeyDown_=this.onKeyDown_.bind(this),this.onKeyUp_=this.onKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.keyScale_=e.keyScale,this.value=e.value,this.sel_=zr(0),this.viewProps=e.viewProps,this.view=new fc(t,{selection:this.sel_,value:this.value,viewProps:this.viewProps}),this.view.element.addEventListener("keydown",this.onKeyDown_),this.view.element.addEventListener("keyup",this.onKeyUp_),this.prevView_=new Cc(t,{value:this.value,viewProps:this.viewProps}),this.prevView_.element.addEventListener("mousedown",t=>{t.stopImmediatePropagation(),t.preventDefault(),this.prevView_.play()}),this.view.previewElement.appendChild(this.prevView_.element);const i=new gl(this.view.element);i.emitter.on("down",this.onPointerDown_),i.emitter.on("move",this.onPointerMove_),i.emitter.on("up",this.onPointerUp_)}refresh(){this.view.refresh(),this.prevView_.refresh(),this.prevView_.play()}updateValue_(t,e,i){const n=this.sel_.rawValue,s=this.value.rawValue.toObject(),r=this.view.positionToValue(t.x,t.y),o=e?function(t,e,i,n){const s=yc(t,e,i,n),r=Math.atan2(n-e,i-t),o=Math.round(r/(Math.PI/4))*Math.PI/4;return{x:t+Math.cos(o)*s,y:e+Math.sin(o)*s}}(n,n,r.x,r.y):r;s[2*n]=o.x,s[2*n+1]=o.y,this.value.setRawValue(new pc(...s),i)}onPointerDown_(t){const e=t.data;if(!e.point)return;const i=this.value.rawValue,n=this.view.valueToPosition(i.x1,i.y1),s=yc(e.point.x,e.point.y,n.x,n.y),r=this.view.valueToPosition(i.x2,i.y2),o=yc(e.point.x,e.point.y,r.x,r.y);this.sel_.rawValue=s<=o?0:1,this.updateValue_(e.point,t.shiftKey,{forceEmit:!1,last:!1})}onPointerMove_(t){const e=t.data;e.point&&this.updateValue_(e.point,t.shiftKey,{forceEmit:!1,last:!1})}onPointerUp_(t){const e=t.data;e.point&&this.updateValue_(e.point,t.shiftKey,{forceEmit:!0,last:!0})}onKeyDown_(t){ml(t.key)&&t.preventDefault();const e=this.sel_.rawValue,i=this.value.rawValue.toObject(),n=this.keyScale_.rawValue;i[2*e]+=dl(n,vl(t)),i[2*e+1]+=dl(n,ul(t)),this.value.setRawValue(new pc(...i),{forceEmit:!1,last:!1})}onKeyUp_(t){ml(t.key)&&t.preventDefault();const e=this.keyScale_.rawValue,i=dl(e,vl(t)),n=dl(e,ul(t));0===i&&0===n||this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}},Ec=class{constructor(t,e){this.value=e.value,this.viewProps=e.viewProps,this.view=new gc(t,{viewProps:this.viewProps}),this.gc_=new Pc(t,{keyScale:e.axis.textProps.value("keyScale"),value:this.value,viewProps:this.viewProps}),this.view.graphElement.appendChild(this.gc_.view.element);const i=Object.assign(Object.assign({},e.axis),{constraint:new Kr({max:1,min:0})}),n=Object.assign(Object.assign({},e.axis),{constraint:void 0});this.tc_=new bh(t,{assembly:hc,axes:[i,n,i,n],parser:no,value:this.value,viewProps:this.viewProps}),this.view.textElement.appendChild(this.tc_.view.element)}get allFocusableElements(){return[this.gc_.view.element,...this.tc_.view.textViews.map(t=>t.inputElement)]}refresh(){this.gc_.refresh()}},kc=class{constructor(t,e){this.onButtonBlur_=this.onButtonBlur_.bind(this),this.onButtonClick_=this.onButtonClick_.bind(this),this.onPopupChildBlur_=this.onPopupChildBlur_.bind(this),this.onPopupChildKeydown_=this.onPopupChildKeydown_.bind(this),this.value=e.value,this.viewProps=e.viewProps,this.foldable_=_a.create(e.expanded),this.view=new mc(t,{foldable:this.foldable_,pickerLayout:e.pickerLayout,viewProps:this.viewProps}),this.view.buttonElement.addEventListener("blur",this.onButtonBlur_),this.view.buttonElement.addEventListener("click",this.onButtonClick_),this.tc_=new sl(t,{parser:uc,props:Rr.fromObject({formatter:cc}),value:this.value,viewProps:this.viewProps}),this.view.textElement.appendChild(this.tc_.view.element),this.popC_="popup"===e.pickerLayout?new el(t,{viewProps:this.viewProps}):null;const i=new Ec(t,{axis:e.axis,value:this.value,viewProps:this.viewProps});i.allFocusableElements.forEach(t=>{t.addEventListener("blur",this.onPopupChildBlur_),t.addEventListener("keydown",this.onPopupChildKeydown_)}),this.pickerC_=i,this.popC_?(this.view.element.appendChild(this.popC_.view.element),this.popC_.view.element.appendChild(this.pickerC_.view.element),Io(this.popC_.shows,t=>{t&&i.refresh()}),cl({primary:this.foldable_.value("expanded"),secondary:this.popC_.shows,forward:t=>t,backward:(t,e)=>e})):this.view.pickerElement&&(this.view.pickerElement.appendChild(this.pickerC_.view.element),xa(this.foldable_,this.view.pickerElement))}onButtonBlur_(t){if(!this.popC_)return;const e=t.relatedTarget;e&&this.popC_.view.element.contains(e)||(this.popC_.shows.rawValue=!1)}onButtonClick_(){this.foldable_.set("expanded",!this.foldable_.get("expanded")),this.foldable_.get("expanded")&&this.pickerC_.allFocusableElements[0].focus()}onPopupChildBlur_(t){if(!this.popC_)return;const e=this.popC_.view.element,i=Ko(t);i&&e.contains(i)||i&&i===this.view.buttonElement&&!Oo(e.ownerDocument)||(this.popC_.shows.rawValue=!1)}onPopupChildKeydown_(t){this.popC_&&"Escape"===t.key&&(this.popC_.shows.rawValue=!1)}},Vc=pa({id:"cubicbezier",type:"blade",accept(t){const e=Lo(t,t=>({value:t.required.array(t.required.number),view:t.required.constant("cubicbezier"),expanded:t.optional.boolean,label:t.optional.string,picker:t.optional.custom(t=>"inline"===t||"popup"===t?t:void 0)}));return e?{params:e}:null},controller(t){var e,i;const n=zr(new pc(...t.params.value),{constraint:new uh({assembly:hc,components:[0,1,2,3].map(t=>t%2==0?new Kr({min:0,max:1}):void 0)}),equals:pc.equals}),s=new kc(t.document,{axis:{textProps:Rr.fromObject({keyScale:.1,pointerScale:.01,formatter:ro(2)})},expanded:null!==(e=t.params.expanded)&&void 0!==e&&e,pickerLayout:null!==(i=t.params.picker)&&void 0!==i?i:"popup",value:n,viewProps:t.viewProps});return new Qo(t.document,{blade:t.blade,props:Rr.fromObject({label:t.params.label}),value:n,valueController:s})},api:t=>t.controller instanceof Qo&&t.controller.valueController instanceof kc?new oc(t.controller):null}),Lc=class extends _o{get fps(){return this.controller.valueController.fps}get max(){return this.controller.valueController.props.get("max")}set max(t){this.controller.valueController.props.set("max",t)}get min(){return this.controller.valueController.props.get("min")}set min(t){this.controller.valueController.props.set("min",t)}begin(){this.controller.valueController.begin()}end(){this.controller.valueController.end()}on(t,e){const i=e.bind(this);return this.controller.valueController.ticker.emitter.on(t,()=>{i(new fo(this))}),this}},Mc=class{constructor(){this.start_=null,this.duration_=0,this.fps_=null,this.frameCount_=0,this.timestamps_=[]}get duration(){return this.duration_}get fps(){return this.fps_}begin(t){this.start_=t.getTime()}calculateFps_(t){if(0===this.timestamps_.length)return null;const e=this.timestamps_[0];return 1e3*(this.frameCount_-e.frameCount)/(t-e.time)}compactTimestamps_(){if(this.timestamps_.length<=20)return;const t=this.timestamps_.length-20;this.timestamps_.splice(0,t);const e=this.timestamps_[0].frameCount;this.timestamps_.forEach(t=>{t.frameCount-=e}),this.frameCount_-=e}end(t){if(null===this.start_)return;const e=t.getTime();this.duration_=e-this.start_,this.start_=null,this.fps_=this.calculateFps_(e),this.timestamps_.push({frameCount:this.frameCount_,time:e}),++this.frameCount_,this.compactTimestamps_()}},Sc=$o("fps"),jc=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(Sc()),e.viewProps.bindClassModifiers(this.element),this.graphElement=t.createElement("div"),this.graphElement.classList.add(Sc("g")),this.element.appendChild(this.graphElement);const i=t.createElement("div");i.classList.add(Sc("l")),this.element.appendChild(i);const n=t.createElement("span");n.classList.add(Sc("v")),n.textContent="--",i.appendChild(n),this.valueElement=n;const s=t.createElement("span");s.classList.add(Sc("u")),s.textContent="FPS",i.appendChild(s)}},Dc=class{constructor(t,e){this.stopwatch_=new Mc,this.onTick_=this.onTick_.bind(this),this.ticker=e.ticker,this.ticker.emitter.on("tick",this.onTick_),this.props=e.props,this.value_=e.value,this.viewProps=e.viewProps,this.view=new jc(t,{viewProps:this.viewProps}),this.graphC_=new Qh(t,{formatter:ro(0),props:this.props,rows:e.rows,value:this.value_,viewProps:this.viewProps}),this.view.graphElement.appendChild(this.graphC_.view.element),this.viewProps.handleDispose(()=>{this.graphC_.viewProps.set("disposed",!0),this.ticker.dispose()})}get fps(){return this.stopwatch_.fps}begin(){this.stopwatch_.begin(new Date)}end(){this.stopwatch_.end(new Date)}onTick_(){const t=this.fps;if(null!==t){const e=this.value_.rawValue;this.value_.rawValue=function(t,e){const i=[...ta(t),e];return i.length>t.length?i.splice(0,i.length-t.length):Jo(i,t.length),i}(e,t),this.view.valueElement.textContent=t.toFixed(0)}}},Ac=class extends Wo{constructor(t,e){const i=e.valueController,n=new Go(t,{blade:e.blade,props:e.labelProps,valueController:i});super({blade:e.blade,view:n.view,viewProps:i.viewProps}),this.valueController=i,this.labelController=n}};function Oc(t,e){return 0===e?new Ua:new Fa(t,null!=e?e:Kh)}var Bc=pa({id:"fpsgraph",type:"blade",accept(t){const e=Lo(t,t=>({view:t.required.constant("fpsgraph"),interval:t.optional.number,label:t.optional.string,rows:t.optional.number,max:t.optional.number,min:t.optional.number}));return e?{params:e}:null},controller(t){var e,i,n,s;const r=null!==(e=t.params.interval)&&void 0!==e?e:500;return new Ac(t.document,{blade:t.blade,labelProps:Rr.fromObject({label:t.params.label}),valueController:new Dc(t.document,{props:Rr.fromObject({max:null!==(i=t.params.max)&&void 0!==i?i:90,min:null!==(n=t.params.min)&&void 0!==n?n:0}),rows:null!==(s=t.params.rows)&&void 0!==s?s:2,ticker:Oc(t.document,r),value:zr(Zo(80)),viewProps:t.viewProps})})},api:t=>t.controller instanceof Ac?new Lc(t.controller):null}),Tc=class{constructor(t,e){this.min=t,this.max=e}static isObject(t){if("object"!=typeof t||null===t)return!1;const e=t.min,i=t.max;return"number"==typeof e&&"number"==typeof i}static equals(t,e){return t.min===e.min&&t.max===e.max}get length(){return this.max-this.min}toObject(){return{min:this.min,max:this.max}}},zc={fromComponents:t=>new Tc(t[0],t[1]),toComponents:t=>[t.min,t.max]},Rc=class{constructor(t){this.edge=t}constrain(t){var e,i,n,s,r,o,a,l;if(t.min<=t.max)return new Tc(null!==(i=null===(e=this.edge)||void 0===e?void 0:e.constrain(t.min))&&void 0!==i?i:t.min,null!==(s=null===(n=this.edge)||void 0===n?void 0:n.constrain(t.max))&&void 0!==s?s:t.max);const p=(t.min+t.max)/2;return new Tc(null!==(o=null===(r=this.edge)||void 0===r?void 0:r.constrain(p))&&void 0!==o?o:p,null!==(l=null===(a=this.edge)||void 0===a?void 0:a.constrain(p))&&void 0!==l?l:p)}},Nc=$o("rsltxt"),Kc=class{constructor(t,e){this.sliderView_=e.sliderView,this.textView_=e.textView,this.element=t.createElement("div"),this.element.classList.add(Nc());const i=t.createElement("div");i.classList.add(Nc("s")),i.appendChild(this.sliderView_.element),this.element.appendChild(i);const n=t.createElement("div");n.classList.add(Nc("t")),n.appendChild(this.textView_.element),this.element.appendChild(n)}},Ic=$o("rsl"),Uc=class{constructor(t,e){this.onSliderPropsChange_=this.onSliderPropsChange_.bind(this),this.onValueChange_=this.onValueChange_.bind(this),this.sliderProps_=e.sliderProps,this.sliderProps_.emitter.on("change",this.onSliderPropsChange_),this.element=t.createElement("div"),this.element.classList.add(Ic()),e.viewProps.bindClassModifiers(this.element),this.value_=e.value,this.value_.emitter.on("change",this.onValueChange_);const i=t.createElement("div");i.classList.add(Ic("t")),this.element.appendChild(i),this.trackElement=i;const n=t.createElement("div");n.classList.add(Ic("b")),i.appendChild(n),this.barElement=n;const s=["min","max"].map(e=>{const n=t.createElement("div");return n.classList.add(Ic("k"),Ic("k",e)),i.appendChild(n),n});this.knobElements=[s[0],s[1]],this.update_()}valueToX_(t){return 100*lo(oo(t,this.sliderProps_.get("min"),this.sliderProps_.get("max"),0,1),0,1)}update_(){const t=this.value_.rawValue;0===t.length?this.element.classList.add(Ic(void 0,"zero")):this.element.classList.remove(Ic(void 0,"zero"));const e=[this.valueToX_(t.min),this.valueToX_(t.max)];this.barElement.style.left=`${e[0]}%`,this.barElement.style.right=100-e[1]+"%",this.knobElements.forEach((t,i)=>{t.style.left=`${e[i]}%`})}onSliderPropsChange_(){this.update_()}onValueChange_(){this.update_()}},Fc=class{constructor(t,e){this.grabbing_=null,this.grabOffset_=0,this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.sliderProps=e.sliderProps,this.viewProps=e.viewProps,this.value=e.value,this.view=new Uc(t,{sliderProps:this.sliderProps,value:this.value,viewProps:e.viewProps});const i=new gl(this.view.trackElement);i.emitter.on("down",this.onPointerDown_),i.emitter.on("move",this.onPointerMove_),i.emitter.on("up",this.onPointerUp_)}ofs_(){return"min"===this.grabbing_?this.view.knobElements[0].getBoundingClientRect().width/2:"max"===this.grabbing_?-this.view.knobElements[1].getBoundingClientRect().width/2:0}valueFromData_(t){return t.point?oo((t.point.x+this.ofs_())/t.bounds.width,0,1,this.sliderProps.get("min"),this.sliderProps.get("max")):null}onPointerDown_(t){if(!t.data.point)return;const e=t.data.point.x/t.data.bounds.width,i=this.value.rawValue,n=this.sliderProps.get("min"),s=this.sliderProps.get("max"),r=oo(i.min,n,s,0,1),o=oo(i.max,n,s,0,1);Math.abs(o-e)<=.025?this.grabbing_="max":Math.abs(r-e)<=.025?this.grabbing_="min":e>=r&&e<=o?(this.grabbing_="length",this.grabOffset_=oo(e-r,0,1,0,s-n)):eo&&(this.grabbing_="max",this.onPointerMove_(t))}applyPointToValue_(t,e){const i=this.valueFromData_(t);if(null===i)return;const n=this.sliderProps.get("min"),s=this.sliderProps.get("max");if("min"===this.grabbing_)this.value.setRawValue(new Tc(i,this.value.rawValue.max),e);else if("max"===this.grabbing_)this.value.setRawValue(new Tc(this.value.rawValue.min,i),e);else if("length"===this.grabbing_){const t=this.value.rawValue.length;let r=i-this.grabOffset_,o=r+t;rs&&(r=s-t,o=s),this.value.setRawValue(new Tc(r,o),e)}}onPointerMove_(t){this.applyPointToValue_(t.data,{forceEmit:!1,last:!1})}onPointerUp_(t){this.applyPointToValue_(t.data,{forceEmit:!0,last:!0}),this.grabbing_=null}},$c=class{constructor(t,e){this.value=e.value,this.viewProps=e.viewProps,this.sc_=new Fc(t,e);const i={constraint:e.constraint,textProps:e.textProps};this.tc_=new bh(t,{assembly:zc,axes:[i,i],parser:e.parser,value:this.value,viewProps:e.viewProps}),this.view=new Kc(t,{sliderView:this.sc_.view,textView:this.tc_.view})}get textController(){return this.tc_}};function qc(t){return Tc.isObject(t)?new Tc(t.min,t.max):new Tc(0,0)}function Hc(t,e){t.writeProperty("max",e.max),t.writeProperty("min",e.min)}var Gc=pa({id:"input-interval",type:"input",accept:(t,e)=>{if(!Tc.isObject(t))return null;const i=Lo(e,t=>Object.assign(Object.assign({},go(t)),{readonly:t.optional.constant(!1)}));return i?{initialValue:new Tc(t.min,t.max),params:i}:null},binding:{reader:t=>qc,constraint:t=>function(t){const e=[],i=mo(t);i&&e.push(i);const n=vo(t);return n&&e.push(n),new Rc(new $a(e))}(t.params),equals:Tc.equals,writer:t=>Hc},controller(t){const e=t.value,i=t.constraint;if(!(i instanceof Rc))throw jr.shouldNeverHappen();const n=(e.rawValue.min+e.rawValue.max)/2,s=Rr.fromObject(bo(t.params,n)),r=i.edge&&qa(i.edge,Nr);if(r)return new $c(t.document,{constraint:i.edge,parser:no,sliderProps:new Rr({keyScale:s.value("keyScale"),max:r.values.value("max"),min:r.values.value("min")}),textProps:s,value:e,viewProps:t.viewProps});const o={constraint:i.edge,textProps:s};return new bh(t.document,{assembly:zc,axes:[o,o],parser:no,value:e,viewProps:t.viewProps})}}),Yc=class{constructor(t){this.controller_=t}get disabled(){return this.controller_.viewProps.get("disabled")}set disabled(t){this.controller_.viewProps.set("disabled",t)}get title(){var t;return null!==(t=this.controller_.props.get("title"))&&void 0!==t?t:""}set title(t){this.controller_.props.set("title",t)}},Xc=class extends xo{constructor(t,e,i,n,s){super(t,n,s),this.cell=e,this.index=i}},Wc=class extends _o{constructor(t){super(t),this.cellToApiMap_=new Map,this.controller.valueController.cellControllers.forEach(t=>{const e=new Yc(t);this.cellToApiMap_.set(t,e)})}get value(){return this.controller.value}cell(t,e){const i=this.controller.valueController,n=i.cellControllers[e*i.size[0]+t];return this.cellToApiMap_.get(n)}on(t,e){const i=e.bind(this);this.controller.value.emitter.on(t,t=>{const e=this.controller.valueController,n=e.findCellByValue(t.rawValue);if(!n)return;const s=this.cellToApiMap_.get(n);if(!s)return;const r=e.cellControllers.indexOf(n);i(new Xc(this,s,[r%e.size[0],Math.floor(r/e.size[0])],t.rawValue))})}},Qc=$o("rad"),Jc=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(Qc()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("label");i.classList.add(Qc("l")),this.element.appendChild(i);const n=t.createElement("input");n.classList.add(Qc("i")),n.name=e.name,n.type="radio",e.viewProps.bindDisabled(n),i.appendChild(n),this.inputElement=n;const s=t.createElement("div");s.classList.add(Qc("b")),i.appendChild(s);const r=t.createElement("div");r.classList.add(Qc("t")),s.appendChild(r),Uo(e.props,"title",t=>{r.textContent=t})}},Zc=class{constructor(t,e){this.props=e.props,this.viewProps=e.viewProps,this.view=new Jc(t,{name:e.name,props:this.props,viewProps:this.viewProps})}},td=class{constructor(t,e){this.cellCs_=[],this.cellValues_=[],this.onCellInputChange_=this.onCellInputChange_.bind(this),this.size=e.size;const[i,n]=this.size;for(let s=0;s{const e=this.findCellByValue(t);e&&(e.view.inputElement.checked=!0)}),this.viewProps=La.create(),this.view=new Ml(t,{viewProps:this.viewProps,viewName:"radgrid"}),this.view.element.style.gridTemplateColumns=`repeat(${i}, 1fr)`,this.cellCs_.forEach(t=>{t.view.inputElement.addEventListener("change",this.onCellInputChange_),this.view.element.appendChild(t.view.element)})}get cellControllers(){return this.cellCs_}findCellByValue(t){const e=this.cellValues_.findIndex(e=>e===t);return e<0?null:this.cellCs_[e]}onCellInputChange_(t){const e=t.currentTarget,i=this.cellCs_.findIndex(t=>t.view.inputElement===e);i<0||(this.value.rawValue=this.cellValues_[i])}},ed=pa({id:"radiogrid",type:"blade",accept(t){const e=Lo(t,t=>({cells:t.required.function,groupName:t.required.string,size:t.required.array(t.required.number),value:t.required.raw,view:t.required.constant("radiogrid"),label:t.optional.string}));return e?{params:e}:null},controller(t){const e=zr(t.params.value);return new Qo(t.document,{blade:t.blade,props:Rr.fromObject({label:t.params.label}),value:e,valueController:new td(t.document,{groupName:t.params.groupName,cellConfig:t.params.cells,size:t.params.size,value:e})})},api:t=>t.controller instanceof Qo&&t.controller.valueController instanceof td?new Wc(t.controller):null});function id(t){return pa({id:"input-radiogrid",type:"input",accept(e,i){if(!t.isType(e))return null;const n=Lo(i,t=>({cells:t.required.function,groupName:t.required.string,size:t.required.array(t.required.number),view:t.required.constant("radiogrid")}));return n?{initialValue:e,params:n}:null},binding:t.binding,controller:t=>new td(t.document,{cellConfig:t.params.cells,groupName:t.params.groupName,size:t.params.size,value:t.value})})}var nd=id({isType:t=>"number"==typeof t,binding:{reader:t=>so,writer:t=>Ol}}),sd=id({isType:t=>"string"==typeof t,binding:{reader:t=>pl,writer:t=>Ol}}),rd=id({isType:t=>"boolean"==typeof t,binding:{reader:t=>rl,writer:t=>Ol}}),od="essentials",ad='.tp-cbzgv,.tp-radv_b,.tp-rslv_k,.tp-cbzv_b{-webkit-appearance:none;-moz-appearance:none;appearance:none;background-color:rgba(0,0,0,0);border-width:0;font-family:inherit;font-size:inherit;font-weight:inherit;margin:0;outline:none;padding:0}.tp-radv_b,.tp-rslv_k,.tp-cbzv_b{background-color:var(--btn-bg);border-radius:var(--bld-br);color:var(--btn-fg);cursor:pointer;display:block;font-weight:bold;height:var(--cnt-usz);line-height:var(--cnt-usz);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.tp-radv_b:hover,.tp-rslv_k:hover,.tp-cbzv_b:hover{background-color:var(--btn-bg-h)}.tp-radv_b:focus,.tp-rslv_k:focus,.tp-cbzv_b:focus{background-color:var(--btn-bg-f)}.tp-radv_b:active,.tp-rslv_k:active,.tp-cbzv_b:active{background-color:var(--btn-bg-a)}.tp-radv_b:disabled,.tp-rslv_k:disabled,.tp-cbzv_b:disabled{opacity:.5}.tp-cbzgv{background-color:var(--in-bg);border-radius:var(--bld-br);box-sizing:border-box;color:var(--in-fg);font-family:inherit;height:var(--cnt-usz);line-height:var(--cnt-usz);min-width:0;width:100%}.tp-cbzgv:hover{background-color:var(--in-bg-h)}.tp-cbzgv:focus{background-color:var(--in-bg-f)}.tp-cbzgv:active{background-color:var(--in-bg-a)}.tp-cbzgv:disabled{opacity:.5}.tp-btngridv{border-radius:var(--bld-br);display:grid;overflow:hidden;gap:2px}.tp-btngridv.tp-v-disabled{opacity:.5}.tp-btngridv .tp-btnv_b:disabled{opacity:1}.tp-btngridv .tp-btnv_b:disabled .tp-btnv_t{opacity:.5}.tp-btngridv .tp-btnv_b{border-radius:0}.tp-cbzv{position:relative}.tp-cbzv_h{display:flex}.tp-cbzv_b{margin-right:4px;position:relative;width:var(--cnt-usz)}.tp-cbzv_b svg{display:block;height:16px;left:50%;margin-left:-8px;margin-top:-8px;position:absolute;top:50%;width:16px}.tp-cbzv_b svg path{stroke:var(--bs-bg);stroke-width:2}.tp-cbzv_t{flex:1}.tp-cbzv_p{height:0;margin-top:0;opacity:0;overflow:hidden;transition:height .2s ease-in-out,opacity .2s linear,margin .2s ease-in-out}.tp-cbzv.tp-cbzv-expanded .tp-cbzv_p{margin-top:var(--cnt-usp);opacity:1}.tp-cbzv.tp-cbzv-cpl .tp-cbzv_p{overflow:visible}.tp-cbzv .tp-popv{left:calc(-1 * var(--cnt-hp));position:absolute;right:calc(-1 * var(--cnt-hp));top:var(--cnt-usz)}.tp-cbzpv_t{margin-top:var(--cnt-usp)}.tp-cbzgv{height:auto;overflow:hidden;position:relative}.tp-cbzgv.tp-v-disabled{opacity:.5}.tp-cbzgv_p{left:16px;position:absolute;right:16px;top:0}.tp-cbzgv_g{cursor:pointer;display:block;height:calc(var(--cnt-usz) * 5);width:100%}.tp-cbzgv_u{opacity:.1;stroke:var(--in-fg);stroke-dasharray:1}.tp-cbzgv_l{fill:rgba(0,0,0,0);stroke:var(--in-fg)}.tp-cbzgv_v{opacity:.5;stroke:var(--in-fg);stroke-dasharray:1}.tp-cbzgv_h{border:var(--in-fg) solid 1px;border-radius:50%;box-sizing:border-box;height:4px;margin-left:-2px;margin-top:-2px;pointer-events:none;position:absolute;width:4px}.tp-cbzgv:focus .tp-cbzgv_h-sel{background-color:var(--in-fg);border-width:0}.tp-cbzprvv{cursor:pointer;height:4px;padding:4px 0;position:relative}.tp-cbzprvv_g{display:block;height:100%;overflow:visible;width:100%}.tp-cbzprvv_t{opacity:.5;stroke:var(--mo-fg)}.tp-cbzprvv_m{background-color:var(--mo-fg);border-radius:50%;height:4px;margin-left:-2px;margin-top:-2px;opacity:0;position:absolute;top:50%;transition:opacity .2s ease-out;width:4px}.tp-cbzprvv_m.tp-cbzprvv_m-a{opacity:1}.tp-fpsv{position:relative}.tp-fpsv_l{bottom:4px;color:var(--mo-fg);line-height:1;right:4px;pointer-events:none;position:absolute}.tp-fpsv_u{margin-left:.2em;opacity:.7}.tp-rslv{cursor:pointer;padding-left:8px;padding-right:8px}.tp-rslv.tp-v-disabled{opacity:.5}.tp-rslv_t{height:calc(var(--cnt-usz));position:relative}.tp-rslv_t::before{background-color:var(--in-bg);border-radius:1px;content:"";height:2px;margin-top:-1px;position:absolute;top:50%;left:-4px;right:-4px}.tp-rslv_b{bottom:0;top:0;position:absolute}.tp-rslv_b::before{background-color:var(--in-fg);content:"";height:2px;margin-top:-1px;position:absolute;top:50%;left:0;right:0}.tp-rslv_k{height:calc(var(--cnt-usz) - 8px);margin-top:calc((var(--cnt-usz) - 8px)/-2);position:absolute;top:50%;width:8px}.tp-rslv_k.tp-rslv_k-min{margin-left:-8px}.tp-rslv_k.tp-rslv_k-max{margin-left:0}.tp-rslv.tp-rslv-zero .tp-rslv_k.tp-rslv_k-min{border-bottom-right-radius:0;border-top-right-radius:0}.tp-rslv.tp-rslv-zero .tp-rslv_k.tp-rslv_k-max{border-bottom-left-radius:0;border-top-left-radius:0}.tp-rsltxtv{display:flex}.tp-rsltxtv_s{flex:1}.tp-rsltxtv_t{flex:1;margin-left:4px}.tp-radv_l{display:block;position:relative}.tp-radv_i{left:0;opacity:0;position:absolute;top:0}.tp-radv_b{opacity:.5}.tp-radv_i:hover+.tp-radv_b{background-color:var(--btn-bg-h)}.tp-radv_i:focus+.tp-radv_b{background-color:var(--btn-bg-f)}.tp-radv_i:active+.tp-radv_b{background-color:var(--btn-bg-a)}.tp-radv_i:checked+.tp-radv_b{opacity:1}.tp-radv_t{bottom:0;color:inherit;left:0;overflow:hidden;position:absolute;right:0;text-align:center;text-overflow:ellipsis;top:0}.tp-radv_i:disabled+.tp-radv_b>.tp-radv_t{opacity:.5}.tp-radgridv{border-radius:var(--bld-br);display:grid;overflow:hidden;gap:2px}.tp-radgridv.tp-v-disabled{opacity:.5}.tp-radgridv .tp-radv_b{border-radius:0}',ld=[rc,Vc,Bc,Gc,ed,rd,nd,sd],pd=(t,e,i="BG")=>{const n="a"in e;t.addBinding({get color(){return e.hex},set color(t){e.setColorByHEX(t)}},"color",{label:`${i} Color`,picker:"inline",expanded:!0}),n&&t.addBinding(e,"a",{min:0,max:1,step:.01,label:`${i} Alpha`})},hd=t=>{const e=(()=>{const t=window.location.pathname.split("/"),e=t.indexOf("examples"),i=Math.max(0,t.length-e-2);return"../".repeat(i)})(),i=t=>e+t;return Array.isArray(t)?t.map(i):i(t)},cd=t=>{if("number"==typeof t)return{value:t,unit:"number"};const e=String(t);return e.endsWith("%")?{value:parseFloat(e),unit:"%"}:(e.endsWith("px"),{value:parseFloat(e),unit:"px"})},dd=({gui:t,redGPUContext:e})=>((0,r.useEffect)(()=>{const i=t.addFolder({title:"RedGPUContext"});i.addBinding(e,"renderScale",{min:.01,max:1,step:.01}),i.addBlade({view:"separator"}),e.backgroundColor&&(pd(i,e.backgroundColor),i.addBlade({view:"separator"})),i.addBinding(e,"alphaMode",{options:{opaque:"opaque",premultiplied:"premultiplied"}}),i.addBlade({view:"separator"});const n=cd(e.width),s=cd(e.height),r={width:n.value,widthUnit:n.unit,height:s.value,heightUnit:s.unit},o=i.addFolder({title:"Size"}),a=()=>{e.width="number"===r.widthUnit?r.width:`${r.width}${r.widthUnit}`};o.addBinding(r,"width",{min:0,max:"%"===n.unit?200:4096,step:.01}).on("change",a),o.addBinding(r,"widthUnit",{options:{"%":"%",px:"px",number:"number"}}).on("change",t=>{a()});const l=()=>{e.height="number"===r.heightUnit?r.height:`${r.height}${r.heightUnit}`};o.addBinding(r,"height",{min:0,max:"%"===s.unit?200:4096,step:.01}).on("change",l),o.addBinding(r,"heightUnit",{options:{"%":"%",px:"px",number:"number"}}).on("change",()=>{l()});const p=i.addFolder({title:"setSize method test",expanded:!1});[["300","300"],["600","300"],["50%","300"],["300","50%"],["100%","100%"]].forEach(([t,i])=>{const n=`setSize(${t}, ${i})`;p.addButton({title:n}).on("click",()=>e.setSize(t,i))}),i.addBlade({view:"separator"});const h=i.addFolder({title:"Rect Info",expanded:!0});h.addBinding({get dpr(){return window.devicePixelRatio}},"dpr",{readonly:!0,label:"DPR",interval:500});const c={get screen(){const t=e.screenRectObject;return`x: ${t.x.toFixed(2)}, y: ${t.y.toFixed(2)}\nw: ${t.width.toFixed(2)}, h: ${t.height.toFixed(2)}`},get pixel(){const t=e.pixelRectObject;return`x: ${t.x}, y: ${t.y}\nw: ${t.width}, h: ${t.height}`}};return h.addBinding(c,"screen",{readonly:!0,label:"Screen Rect",multiline:!0,rows:2,interval:32}),h.addBinding(c,"pixel",{readonly:!0,label:"Pixel Rect",multiline:!0,rows:2,interval:32}),()=>{i.dispose()}},[t,e]),null),ud=(t,e)=>{e.addBinding(t,"useBackgroundColor"),t.backgroundColor&&pd(e,t.backgroundColor)},vd=({gui:t,scene:e})=>((0,r.useEffect)(()=>{if(!e)return;const i=e.name||"Scene",n=t.addFolder({title:i});return ud(e,n),()=>{n.dispose()}},[t,e]),null),md=({gui:t,redGPUContext:e})=>((0,r.useEffect)(()=>{const i=e.viewList;if(0===i.length)return;const n=1===i.length?i[0].name?.replace(/Instance/g,"")||"View 0":"ViewList",s=t.addFolder({title:n}),r=(t,e)=>{if("View3D"===t.constructor.name){e.addBinding(t,"useFrustumCulling"),e.addBinding(t,"useDistanceCulling"),e.addBinding(t,"distanceCulling",{min:0,max:1e3,step:1}),e.addBlade({view:"separator"});const i=e.addFolder({title:"Debug Helpers"}),n={get grid(){return!!t.grid},set grid(e){t.grid=e},get axis(){return!!t.axis},set axis(e){t.axis=e}};i.addBinding(n,"grid",{label:"Show Grid"}),i.addBinding(n,"axis",{label:"Show Axis"}),e.addBlade({view:"separator"})}const i={width:cd(t.width).value,widthUnit:cd(t.width).unit,height:cd(t.height).value,heightUnit:cd(t.height).unit,x:cd(t.x).value,xUnit:cd(t.x).unit,y:cd(t.y).value,yUnit:cd(t.y).unit},n=e.addFolder({title:"Size & Position"}),s=e=>{const n=i[e],s=i[`${e}Unit`];t[e]="number"===s?n:`${n}${s}`};if(["width","height","x","y"].forEach(t=>{const e=t,r=`${e}Unit`;n.addBinding(i,e,{min:0,max:"%"===i[r]?200:4096,step:.01}).on("change",()=>s(e)),n.addBinding(i,r,{label:`${e} Unit`,options:{"%":"%",px:"px",number:"number"}}).on("change",()=>s(e))}),t.scene){e.addBlade({view:"separator"});const i=e.addFolder({title:t.scene.name||"Scene",expanded:!0});ud(t.scene,i)}};if(1===i.length)r(i[0],s);else{const t=s.addTab({pages:i.map((t,e)=>({title:t.name?.replace(/Instance/g,"")||`View ${e}`}))});i.forEach((e,i)=>{r(e,t.pages[i])})}return()=>{s.dispose()}},[t,e]),null),bd=[{name:"2K - the sky is on fire",path:"assets/hdr/2k/the_sky_is_on_fire_2k.hdr",nit:3e4},{name:"Cannon_Exterior",path:"assets/hdr/Cannon_Exterior.hdr",nit:25e3},{name:"field",path:"assets/hdr/field.hdr",nit:3e4},{name:"neutral.37290948",path:"assets/hdr/neutral.37290948.hdr",nit:2e4},{name:"pisa",path:"assets/hdr/pisa.hdr",nit:25e3},{name:"6 cube face asset",path:["assets/skybox/px.jpg","assets/skybox/nx.jpg","assets/skybox/py.jpg","assets/skybox/ny.jpg","assets/skybox/pz.jpg","assets/skybox/nz.jpg"],nit:100}],gd=({gui:t,view:e})=>{const i=s(t=>t.RedGPU);return(0,r.useEffect)(()=>{if(!e)return;const n=t.addFolder({title:"Lighting",expanded:!0}),s={texture:bd[0].name,useLight:e.scene.lightManager.directionalLights.length>0,lux:e.scene.lightManager.directionalLights[0]?.lux||1e5,useIBL:!0,intensityMultiplier:e.ibl?.intensityMultiplier||1},r={finalPath:""};let o;const a=n=>{if(!s.useIBL)return;const a=bd.find(t=>t.name===n);if(!a)return;const l=a.path;(t=>{const e=t=>t.split("/").pop()||t;r.finalPath=Array.isArray(t)?t.map(e).join("\n"):e(t),o&&o.refresh()})(l);const p=hd(l),h=a.nit||2e4;if(i){const t=new i.Resource.IBL(e.redGPUContext,p,h);t.intensityMultiplier=s.intensityMultiplier,e.ibl=t}t.refresh()},l=n=>{if(n){if(0===e.scene.lightManager.directionalLights.length&&i){const t=new i.Light.DirectionalLight;t.lux=s.lux,e.scene.lightManager.addDirectionalLight(t)}}else e.scene.lightManager.removeAllLight();t.refresh()};n.addBinding(s,"useLight").on("change",t=>l(t.value)),n.addBinding(s,"lux",{min:0,max:1e5,step:1}).on("change",t=>{const i=e.scene.lightManager.directionalLights;i.length>0&&(i[0].lux=t.value)}),n.addBinding(s,"useIBL").on("change",t=>{t.value?(a(s.texture),p.disabled=!1):(e.ibl=null,p.disabled=!0)});const p=n.addFolder({title:"IBL Settings",expanded:!0});return p.addBinding(s,"texture",{options:bd.reduce((t,e)=>({...t,[e.name]:e.name}),{})}).on("change",t=>a(t.value)),p.addBinding(s,"intensityMultiplier",{min:0,max:5,step:.1}).on("change",t=>{e.ibl&&(e.ibl.intensityMultiplier=t.value)}),p.addBinding({get luminance(){return e.ibl?e.ibl.luminance:0},set luminance(t){e.ibl&&(e.ibl.luminance=t)}},"luminance",{min:0,max:1e5,step:100}),o=p.addBinding(r,"finalPath",{readonly:!0,label:"source",multiline:!0,rows:2}),l(s.useLight),s.useIBL?a(s.texture):p.disabled=!0,()=>{n.dispose()}},[t,e,i]),null},wd=({gui:t,view:e})=>{const i=s(t=>t.RedGPU);return(0,r.useEffect)(()=>{if(!e)return;const n=t.addFolder({title:"SkyBox",expanded:!0}),s={useSkyBox:!0,texture:bd[0].name,blur:e.skybox?.blur||0,intensityMultiplier:e.skybox?.intensityMultiplier||1,opacity:e.skybox?.opacity||1},r={finalPath:""};let o;const a=n=>{if(!s.useSkyBox)return;const a=bd.find(t=>t.name===n);if(!a)return;const l=a.path;(t=>{const e=t=>t.split("/").pop()||t;r.finalPath=Array.isArray(t)?t.map(e).join("\n"):e(t),o&&o.refresh()})(l);const p=hd(l),h=a.nit||2e4;if(i){const t="string"==typeof l&&l.toLowerCase().endsWith(".hdr")?new i.Resource.IBL(e.redGPUContext,p,h).environmentTexture:new i.Resource.CubeTexture(e.redGPUContext,p,!0);e.skybox?(e.skybox.texture=t,e.skybox.luminance=h):e.skybox=new i.Display.SkyBox(e.redGPUContext,t,h),e.skybox.blur=s.blur,e.skybox.intensityMultiplier=s.intensityMultiplier,e.skybox.opacity=s.opacity}t.refresh()};n.addBinding(s,"useSkyBox").on("change",t=>{t.value?(a(s.texture),l.disabled=!1):(e.skybox=null,l.disabled=!0)});const l=n.addFolder({title:"SkyBox Settings",expanded:!0});return l.addBinding(s,"texture",{options:bd.reduce((t,e)=>({...t,[e.name]:e.name}),{})}).on("change",t=>a(t.value)),l.addBinding(s,"blur",{min:0,max:1,step:.01}).on("change",t=>{e.skybox&&(e.skybox.blur=t.value)}),l.addBinding(s,"intensityMultiplier",{min:0,max:5,step:.1}).on("change",t=>{e.skybox&&(e.skybox.intensityMultiplier=t.value)}),l.addBinding(s,"opacity",{min:0,max:1,step:.01}).on("change",t=>{e.skybox&&(e.skybox.opacity=t.value)}),l.addBinding({get luminance(){return e.skybox?e.skybox.luminance:0},set luminance(t){e.skybox&&(e.skybox.luminance=t)}},"luminance",{min:0,max:1e5,step:100}),o=l.addBinding(r,"finalPath",{readonly:!0,label:"source",multiline:!0,rows:2}),s.useSkyBox?a(s.texture):l.disabled=!0,()=>{n.dispose()}},[t,e,i]),null},_d=n(),fd=()=>{const t=s(t=>t.guiConfig),e=s(t=>t.redGPUContext),i=(0,r.useRef)(null),[n,o]=(0,r.useState)(null);return(0,r.useEffect)(()=>{if(i.current&&t){const n=new yr({container:i.current});if(n.registerPlugin(Pr),o(n),t.gui)try{t.gui(n)}catch(e){console.error("Error in custom GUI callback:",e)}return()=>{n.dispose(),o(null)}}},[t]),t? (0,_d.jsxs)(_d.Fragment,{children:[ +import{n as t,r as e}from"./rolldown-runtime-BztV3taV.js?t=1781136546834";import{r as i,t as n}from"./vendor-react-BwJpJ84T.js?t=1781136546834";import{t as s}from"./store-2JcZHIgY.js?t=1781136546834";var r=e(i(),1);function o(t){return null==t}function a(t){return null!==t&&"object"==typeof t}function l(t){return null!==t&&"object"==typeof t}function p(t,e){if(t.length!==e.length)return!1;for(let i=0;i{const s=t[n],r=e[n];return l(s)&&l(r)?Object.assign(Object.assign({},i),{[n]:h(s,r)}):Object.assign(Object.assign({},i),{[n]:n in e?r:s})},{})}function c(t){return!!a(t)&&"target"in t}var d={alreadydisposed:()=>"View has been already disposed",invalidparams:t=>`Invalid parameters for '${t.name}'`,nomatchingcontroller:t=>`No matching controller for '${t.key}'`,nomatchingview:t=>`No matching view for '${JSON.stringify(t.params)}'`,notbindable:()=>"Value is not bindable",notcompatible:t=>`Not compatible with plugin '${t.id}'`,propertynotfound:t=>`Property '${t.name}' not found`,shouldneverhappen:()=>"This error should never happen"},u=class t{static alreadyDisposed(){return new t({type:"alreadydisposed"})}static notBindable(){return new t({type:"notbindable"})}static notCompatible(e,i){return new t({type:"notcompatible",context:{id:`${e}.${i}`}})}static propertyNotFound(e){return new t({type:"propertynotfound",context:{name:e}})}static shouldNeverHappen(){return new t({type:"shouldneverhappen"})}constructor(t){var e;this.message=null!==(e=d[t.type](t.context))&&void 0!==e?e:"Unexpected error",this.name=this.constructor.name,this.stack=new Error(this.message).stack,this.type=t.type}toString(){return this.message}},v=class t{constructor(t,e){this.obj_=t,this.key=e}static isBindable(t){return null!==t&&("object"==typeof t||"function"==typeof t)}read(){return this.obj_[this.key]}write(t){this.obj_[this.key]=t}writeProperty(e,i){const n=this.read();if(!t.isBindable(n))throw u.notBindable();if(!(e in n))throw u.propertyNotFound(e);n[e]=i}},m=class{constructor(){this.observers_={}}on(t,e,i){var n;let s=this.observers_[t];return s||(s=this.observers_[t]=[]),s.push({handler:e,key:null!==(n=null==i?void 0:i.key)&&void 0!==n?n:e}),this}off(t,e){const i=this.observers_[t];return i&&(this.observers_[t]=i.filter(t=>t.key!==e)),this}emit(t,e){const i=this.observers_[t];i&&i.forEach(t=>{t.handler(e)})}},b=class{constructor(t,e){var i;this.constraint_=null==e?void 0:e.constraint,this.equals_=null!==(i=null==e?void 0:e.equals)&&void 0!==i?i:(t,e)=>t===e,this.emitter=new m,this.rawValue_=t}get constraint(){return this.constraint_}get rawValue(){return this.rawValue_}set rawValue(t){this.setRawValue(t,{forceEmit:!1,last:!0})}setRawValue(t,e){const i=null!=e?e:{forceEmit:!1,last:!0},n=this.constraint_?this.constraint_.constrain(t):t,s=this.rawValue_;this.equals_(s,n)&&!i.forceEmit||(this.emitter.emit("beforechange",{sender:this}),this.rawValue_=n,this.emitter.emit("change",{options:i,previousRawValue:s,rawValue:n,sender:this}))}},g=class{constructor(t){this.emitter=new m,this.value_=t}get rawValue(){return this.value_}set rawValue(t){this.setRawValue(t,{forceEmit:!1,last:!0})}setRawValue(t,e){const i=null!=e?e:{forceEmit:!1,last:!0},n=this.value_;(n!==t||i.forceEmit)&&(this.emitter.emit("beforechange",{sender:this}),this.value_=t,this.emitter.emit("change",{options:i,previousRawValue:n,rawValue:this.value_,sender:this}))}},w=class{constructor(t){this.emitter=new m,this.onValueBeforeChange_=this.onValueBeforeChange_.bind(this),this.onValueChange_=this.onValueChange_.bind(this),this.value_=t,this.value_.emitter.on("beforechange",this.onValueBeforeChange_),this.value_.emitter.on("change",this.onValueChange_)}get rawValue(){return this.value_.rawValue}onValueBeforeChange_(t){this.emitter.emit("beforechange",Object.assign(Object.assign({},t),{sender:this}))}onValueChange_(t){this.emitter.emit("change",Object.assign(Object.assign({},t),{sender:this}))}};function _(t,e){const i=null==e?void 0:e.constraint,n=null==e?void 0:e.equals;return i||n?new b(t,e):new g(t)}var f=class t{constructor(t){this.emitter=new m,this.valMap_=t;for(const e in this.valMap_)this.valMap_[e].emitter.on("change",()=>{this.emitter.emit("change",{key:e,sender:this})})}static createCore(t){return Object.keys(t).reduce((e,i)=>Object.assign(e,{[i]:_(t[i])}),{})}static fromObject(e){return new t(this.createCore(e))}get(t){return this.valMap_[t].rawValue}set(t,e){this.valMap_[t].rawValue=e}value(t){return this.valMap_[t]}},x=class{constructor(t){this.values=f.fromObject({max:t.max,min:t.min})}constrain(t){const e=this.values.get("max"),i=this.values.get("min");return Math.min(Math.max(t,i),e)}},C=class{constructor(t){this.values=f.fromObject({max:t.max,min:t.min})}constrain(t){const e=this.values.get("max"),i=this.values.get("min");let n=t;return o(i)||(n=Math.max(n,i)),o(e)||(n=Math.min(n,e)),n}},y=class{constructor(t,e=0){this.step=t,this.origin=e}constrain(t){const e=this.origin%this.step;return e+Math.round((t-e)/this.step)*this.step}},P=class{constructor(t){this.text=t}evaluate(){return Number(this.text)}toString(){return this.text}},E={"**":(t,e)=>Math.pow(t,e),"*":(t,e)=>t*e,"/":(t,e)=>t/e,"%":(t,e)=>t%e,"+":(t,e)=>t+e,"-":(t,e)=>t-e,"<<":(t,e)=>t<>":(t,e)=>t>>e,">>>":(t,e)=>t>>>e,"&":(t,e)=>t&e,"^":(t,e)=>t^e,"|":(t,e)=>t|e},k=class{constructor(t,e,i){this.left=e,this.operator=t,this.right=i}evaluate(){const t=E[this.operator];if(!t)throw new Error(`unexpected binary operator: '${this.operator}`);return t(this.left.evaluate(),this.right.evaluate())}toString(){return["b(",this.left.toString(),this.operator,this.right.toString(),")"].join(" ")}},V={"+":t=>t,"-":t=>-t,"~":t=>~t},L=class{constructor(t,e){this.operator=t,this.expression=e}evaluate(){const t=V[this.operator];if(!t)throw new Error(`unexpected unary operator: '${this.operator}`);return t(this.expression.evaluate())}toString(){return["u(",this.operator,this.expression.toString(),")"].join(" ")}};function M(t){return(e,i)=>{for(let n=0;ne.startsWith(t,i))[0];return n?(i+=n.length,{cursor:i+=S(e,i).length,operator:n}):null}var z=[["**"],["*","/","%"],["+","-"],["<<",">>>",">>"],["&"],["^"],["|"]].reduce((t,e)=>function(t,e){return(i,n)=>{const s=t(i,n);if(!s)return null;n=s.cursor;let r=s.evaluable;for(;;){const s=T(e,i,n);if(!s)break;n=s.cursor;const o=t(i,n);if(!o)return null;n=o.cursor,r=new k(s.operator,r,o.evaluable)}return r?{cursor:n,evaluable:r}:null}}(t,e),function t(e,i){const n=function(t,e){var i;return null!==(i=function(t,e){const i=B(t,e);return e+=i.length,""===i?null:{evaluable:new P(i),cursor:e}}(t,e))&&void 0!==i?i:function(t,e){const i=t.substr(e,1);if(e+=i.length,"("!==i)return null;const n=R(t,e);if(!n)return null;e=n.cursor,e+=S(t,e).length;const s=t.substr(e,1);return e+=s.length,")"!==s?null:{evaluable:n.evaluable,cursor:e}}(t,e)}(e,i);if(n)return n;const s=e.substr(i,1);if(i+=s.length,"+"!==s&&"-"!==s&&"~"!==s)return null;const r=t(e,i);return r?{cursor:i=r.cursor,evaluable:new L(s,r.evaluable)}:null});function R(t,e){return e+=S(t,e).length,z(t,e)}function N(t){var e;const i=function(t){const e=R(t,0);return e?e.cursor+S(t,e.cursor).length!==t.length?null:e.evaluable:null}(t);return null!==(e=null==i?void 0:i.evaluate())&&void 0!==e?e:null}function K(t){if("number"==typeof t)return t;if("string"==typeof t){const e=N(t);if(!o(e))return e}return 0}function I(t){return String(t)}function U(t){return e=>e.toFixed(Math.max(Math.min(t,20),0))}function F(t,e,i,n,s){return n+(t-e)/(i-e)*(s-n)}function $(t){return String(t.toFixed(10)).split(".")[1].replace(/0+$/,"").length}function q(t,e,i){return Math.min(Math.max(t,e),i)}function H(t,e){return(t%e+e)%e}function G(t,e){return o(t.step)?Math.max($(e),2):$(t.step)}function Y(t){var e;return null!==(e=t.step)&&void 0!==e?e:1}function X(t,e){var i;const n=Math.abs(null!==(i=t.step)&&void 0!==i?i:e);return 0===n?.1:Math.pow(10,Math.floor(Math.log10(n))-1)}function W(t,e){return o(t.step)?null:new y(t.step,e)}function Q(t){return o(t.max)||o(t.min)?o(t.max)&&o(t.min)?null:new C({max:t.max,min:t.min}):new x({max:t.max,min:t.min})}function J(t,e){var i,n,s;return{formatter:null!==(i=t.format)&&void 0!==i?i:U(G(t,e)),keyScale:null!==(n=t.keyScale)&&void 0!==n?n:Y(t),pointerScale:null!==(s=t.pointerScale)&&void 0!==s?s:X(t,e)}}function Z(t){return{format:t.optional.function,keyScale:t.optional.number,max:t.optional.number,min:t.optional.number,pointerScale:t.optional.number,step:t.optional.number}}function tt(t){return{constraint:t.constraint,textProps:f.fromObject(J(t.params,t.initialValue))}}var et=class{constructor(t){this.controller=t}get element(){return this.controller.view.element}get disabled(){return this.controller.viewProps.get("disabled")}set disabled(t){this.controller.viewProps.set("disabled",t)}get hidden(){return this.controller.viewProps.get("hidden")}set hidden(t){this.controller.viewProps.set("hidden",t)}dispose(){this.controller.viewProps.set("disposed",!0)}importState(t){return this.controller.importState(t)}exportState(){return this.controller.exportState()}},it=class{constructor(t){this.target=t}},nt=class extends it{constructor(t,e,i){super(t),this.value=e,this.last=null==i||i}},st=class extends it{constructor(t,e){super(t),this.expanded=e}},rt=class extends it{constructor(t,e){super(t),this.index=e}},ot=class extends it{constructor(t,e){super(t),this.native=e}},at=class extends et{constructor(t){super(t),this.onValueChange_=this.onValueChange_.bind(this),this.emitter_=new m,this.controller.value.emitter.on("change",this.onValueChange_)}get label(){return this.controller.labelController.props.get("label")}set label(t){this.controller.labelController.props.set("label",t)}get key(){return this.controller.value.binding.target.key}get tag(){return this.controller.tag}set tag(t){this.controller.tag=t}on(t,e){const i=e.bind(this);return this.emitter_.on(t,t=>{i(t)},{key:e}),this}off(t,e){return this.emitter_.off(t,e),this}refresh(){this.controller.value.fetch()}onValueChange_(t){const e=this.controller.value;this.emitter_.emit("change",new nt(this,e.binding.target.read(),t.options.last))}},lt=class{constructor(t,e){this.onValueBeforeChange_=this.onValueBeforeChange_.bind(this),this.onValueChange_=this.onValueChange_.bind(this),this.binding=e,this.value_=t,this.value_.emitter.on("beforechange",this.onValueBeforeChange_),this.value_.emitter.on("change",this.onValueChange_),this.emitter=new m}get rawValue(){return this.value_.rawValue}set rawValue(t){this.value_.rawValue=t}setRawValue(t,e){this.value_.setRawValue(t,e)}fetch(){this.value_.rawValue=this.binding.read()}push(){this.binding.write(this.value_.rawValue)}onValueBeforeChange_(t){this.emitter.emit("beforechange",Object.assign(Object.assign({},t),{sender:this}))}onValueChange_(t){this.push(),this.emitter.emit("change",Object.assign(Object.assign({},t),{sender:this}))}};function pt(t){return e=>i=>{if(!e&&void 0===i)return{succeeded:!1,value:void 0};if(e&&void 0===i)return{succeeded:!0,value:void 0};const n=t(i);return void 0!==n?{succeeded:!0,value:n}:{succeeded:!1,value:void 0}}}function ht(t){return{custom:e=>pt(e)(t),boolean:pt(t=>"boolean"==typeof t?t:void 0)(t),number:pt(t=>"number"==typeof t?t:void 0)(t),string:pt(t=>"string"==typeof t?t:void 0)(t),function:pt(t=>"function"==typeof t?t:void 0)(t),constant:e=>pt(t=>t===e?e:void 0)(t),raw:pt(t=>t)(t),object:e=>pt(t=>{var i;if(null!==(i=t)&&"object"==typeof i)return function(t,e){return Object.keys(e).reduce((i,n)=>{if(void 0===i)return;const s=(0,e[n])(t[n]);return s.succeeded?Object.assign(Object.assign({},i),{[n]:s.value}):void 0},{})}(t,e)})(t),array:e=>pt(t=>{var i;if(Array.isArray(t))return i=e,t.reduce((t,e)=>{if(void 0===t)return;const n=i(e);return n.succeeded&&void 0!==n.value?[...t,n.value]:void 0},[])})(t)}}var ct={optional:ht(!0),required:ht(!1)};function dt(t,e){const i=e(ct),n=ct.required.object(i)(t);return n.succeeded?n.value:void 0}function ut(t,e,i,n){if(e&&!e(t))return!1;const s=dt(t,i);return!!s&&n(s)}function vt(t,e){var i;return h(null!==(i=null==t?void 0:t())&&void 0!==i?i:{},e)}function mt(t){return"value"in t}function bt(t){return!(!a(t)||!("binding"in t))&&c(t.binding)}var gt="http://www.w3.org/2000/svg";function wt(t){t.offsetHeight}function _t(t){return void 0!==t.ontouchstart}var ft={check:'',dropdown:'',p2dpad:''};function xt(t,e){const i=t.createElementNS(gt,"svg");return i.innerHTML=ft[e],i}function Ct(t,e,i){t.insertBefore(e,t.children[i])}function yt(t){t.parentElement&&t.parentElement.removeChild(t)}function Pt(t){for(;t.children.length>0;)t.removeChild(t.children[0])}function Et(t){return t.relatedTarget?t.relatedTarget:"explicitOriginalTarget"in t?t.explicitOriginalTarget:null}function kt(t,e){t.emitter.on("change",t=>{e(t.rawValue)}),e(t.rawValue)}function Vt(t,e,i){kt(t.value(e),i)}var Lt="tp";function Mt(t){return(e,i)=>[Lt,"-",t,"v",e?`_${e}`:"",i?`-${i}`:""].join("")}var St=Mt("lbl"),jt=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(St()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("div");i.classList.add(St("l")),Vt(e.props,"label",e=>{o(e)?this.element.classList.add(St(void 0,"nol")):(this.element.classList.remove(St(void 0,"nol")),function(t){for(;t.childNodes.length>0;)t.removeChild(t.childNodes[0])}(i),i.appendChild(function(t,e){const i=t.createDocumentFragment();return e.split("\n").map(e=>t.createTextNode(e)).forEach((e,n)=>{n>0&&i.appendChild(t.createElement("br")),i.appendChild(e)}),i}(t,e)))}),this.element.appendChild(i),this.labelElement=i;const n=t.createElement("div");n.classList.add(St("v")),this.element.appendChild(n),this.valueElement=n}},Dt=class{constructor(t,e){this.props=e.props,this.valueController=e.valueController,this.viewProps=e.valueController.viewProps,this.view=new jt(t,{props:e.props,viewProps:this.viewProps}),this.view.valueElement.appendChild(this.valueController.view.element)}importProps(t){return ut(t,null,t=>({label:t.optional.string}),t=>(this.props.set("label",t.label),!0))}exportProps(){return vt(null,{label:this.props.get("label")})}},At=Mt(""),Ot={veryfirst:"vfst",first:"fst",last:"lst",verylast:"vlst"},Bt=class{constructor(t){this.parent_=null,this.blade=t.blade,this.view=t.view,this.viewProps=t.viewProps;const e=this.view.element;this.blade.value("positions").emitter.on("change",()=>{["veryfirst","first","last","verylast"].forEach(t=>{e.classList.remove(At(void 0,Ot[t]))}),this.blade.get("positions").forEach(t=>{e.classList.add(At(void 0,Ot[t]))})}),this.viewProps.handleDispose(()=>{yt(e)})}get parent(){return this.parent_}set parent(t){this.parent_=t,this.viewProps.set("parent",this.parent_?this.parent_.viewProps:null)}importState(t){return ut(t,null,t=>({disabled:t.required.boolean,hidden:t.required.boolean}),t=>(this.viewProps.importState(t),!0))}exportState(){return vt(null,Object.assign({},this.viewProps.exportState()))}},Tt=class extends Bt{constructor(t,e){if(e.value!==e.valueController.value)throw u.shouldNeverHappen();const i=e.valueController.viewProps,n=new Dt(t,{blade:e.blade,props:e.props,valueController:e.valueController});super(Object.assign(Object.assign({},e),{view:new jt(t,{props:e.props,viewProps:i}),viewProps:i})),this.labelController=n,this.value=e.value,this.valueController=e.valueController,this.view.valueElement.appendChild(this.valueController.view.element)}importState(t){return ut(t,e=>{var i,n,s;return super.importState(e)&&this.labelController.importProps(e)&&(null===(s=null===(n=(i=this.valueController).importProps)||void 0===n?void 0:n.call(i,t))||void 0===s||s)},t=>({value:t.optional.raw}),t=>(t.value&&(this.value.rawValue=t.value),!0))}exportState(){var t,e,i;return vt(()=>super.exportState(),Object.assign(Object.assign({value:this.value.rawValue},this.labelController.exportProps()),null!==(i=null===(e=(t=this.valueController).exportProps)||void 0===e?void 0:e.call(t))&&void 0!==i?i:{}))}};function zt(t){const e=Object.assign({},t);return delete e.value,e}var Rt=class extends Tt{constructor(t,e){super(t,e),this.tag=e.tag}importState(t){return ut(t,e=>super.importState(zt(t)),t=>({tag:t.optional.string}),t=>(this.tag=t.tag,!0))}exportState(){return vt(()=>zt(super.exportState()),{binding:{key:this.value.binding.target.key,value:this.value.binding.target.read()},tag:this.tag})}},Nt=class extends Rt{importState(t){return ut(t,t=>super.importState(t),t=>({binding:t.required.object({value:t.required.raw})}),t=>(this.value.binding.inject(t.binding.value),this.value.fetch(),!0))}};function Kt(t,e){for(;t.lengtht.length?i.splice(0,i.length-t.length):Kt(i,t.length),i}(this.value_.rawValue,this.binding.read())}onTick_(){this.fetch()}onValueBeforeChange_(t){this.emitter.emit("beforechange",Object.assign(Object.assign({},t),{sender:this}))}onValueChange_(t){this.emitter.emit("change",Object.assign(Object.assign({},t),{sender:this}))}},Ft=class extends Rt{exportState(){return vt(()=>super.exportState(),{binding:{readonly:!0}})}};var $t=class extends et{get label(){return this.controller.labelController.props.get("label")}set label(t){this.controller.labelController.props.set("label",t)}get title(){var t;return null!==(t=this.controller.buttonController.props.get("title"))&&void 0!==t?t:""}set title(t){this.controller.buttonController.props.set("title",t)}on(t,e){const i=e.bind(this);return this.controller.buttonController.emitter.on(t,t=>{i(new ot(this,t.nativeEvent))}),this}off(t,e){return this.controller.buttonController.emitter.off(t,e),this}};function qt(t,e){return i=>{!function(t,e,i){i?t.classList.add(e):t.classList.remove(e)}(t,e,i)}}function Ht(t,e){kt(t,t=>{e.textContent=null!=t?t:""})}var Gt=Mt("btn"),Yt=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(Gt()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("button");i.classList.add(Gt("b")),e.viewProps.bindDisabled(i),this.element.appendChild(i),this.buttonElement=i;const n=t.createElement("div");n.classList.add(Gt("t")),Ht(e.props.value("title"),n),this.buttonElement.appendChild(n)}},Xt=class{constructor(t,e){this.emitter=new m,this.onClick_=this.onClick_.bind(this),this.props=e.props,this.viewProps=e.viewProps,this.view=new Yt(t,{props:this.props,viewProps:this.viewProps}),this.view.buttonElement.addEventListener("click",this.onClick_)}importProps(t){return ut(t,null,t=>({title:t.optional.string}),t=>(this.props.set("title",t.title),!0))}exportProps(){return vt(null,{title:this.props.get("title")})}onClick_(t){this.emitter.emit("click",{nativeEvent:t,sender:this})}},Wt=class extends Bt{constructor(t,e){const i=new Xt(t,{props:e.buttonProps,viewProps:e.viewProps}),n=new Dt(t,{blade:e.blade,props:e.labelProps,valueController:i});super({blade:e.blade,view:n.view,viewProps:e.viewProps}),this.buttonController=i,this.labelController=n}importState(t){return ut(t,t=>super.importState(t)&&this.buttonController.importProps(t)&&this.labelController.importProps(t),()=>({}),()=>!0)}exportState(){return vt(()=>super.exportState(),Object.assign(Object.assign({},this.buttonController.exportProps()),this.labelController.exportProps()))}},Qt=class{constructor(t){const[e,i]=t.split("-"),n=e.split(".");this.major=parseInt(n[0],10),this.minor=parseInt(n[1],10),this.patch=parseInt(n[2],10),this.prerelease=null!=i?i:null}toString(){const t=[this.major,this.minor,this.patch].join(".");return null!==this.prerelease?[t,this.prerelease].join("-"):t}},Jt=new Qt("2.0.5");function Zt(t){return Object.assign({core:Jt},t)}var te=Zt({id:"button",type:"blade",accept(t){const e=dt(t,t=>({title:t.required.string,view:t.required.constant("button"),label:t.optional.string}));return e?{params:e}:null},controller:t=>new Wt(t.document,{blade:t.blade,buttonProps:f.fromObject({title:t.params.title}),labelProps:f.fromObject({label:t.params.label}),viewProps:t.viewProps}),api:t=>t.controller instanceof Wt?new $t(t.controller):null}),ee=class{constructor(t,e){this.onRackValueChange_=this.onRackValueChange_.bind(this),this.controller_=t,this.emitter_=new m,this.pool_=e,this.controller_.rack.emitter.on("valuechange",this.onRackValueChange_)}get children(){return this.controller_.rack.children.map(t=>this.pool_.createApi(t))}addBinding(t,e,i){const n=null!=i?i:{},s=this.controller_.element.ownerDocument,r=this.pool_.createBinding(s,function(t,e){if(!v.isBindable(t))throw u.notBindable();return new v(t,e)}(t,e),n),o=this.pool_.createBindingApi(r);return this.add(o,n.index)}addFolder(t){return function(t,e){return t.addBlade(Object.assign(Object.assign({},e),{view:"folder"}))}(this,t)}addButton(t){return function(t,e){return t.addBlade(Object.assign(Object.assign({},e),{view:"button"}))}(this,t)}addTab(t){return function(t,e){return t.addBlade(Object.assign(Object.assign({},e),{view:"tab"}))}(this,t)}add(t,e){const i=t.controller;return this.controller_.rack.add(i,e),t}remove(t){this.controller_.rack.remove(t.controller)}addBlade(t){const e=this.controller_.element.ownerDocument,i=this.pool_.createBlade(e,t),n=this.pool_.createApi(i);return this.add(n,t.index)}on(t,e){const i=e.bind(this);return this.emitter_.on(t,t=>{i(t)},{key:e}),this}off(t,e){return this.emitter_.off(t,e),this}refresh(){this.children.forEach(t=>{var e;a(e=t)&&"refresh"in e&&"function"==typeof e.refresh&&t.refresh()})}onRackValueChange_(t){const e=t.bladeController,i=this.pool_.createApi(e),n=bt(e.value)?e.value.binding:null;this.emitter_.emit("change",new nt(i,n?n.target.read():e.value.rawValue,t.options.last))}},ie=class extends et{constructor(t,e){super(t),this.rackApi_=new ee(t.rackController,e)}refresh(){this.rackApi_.refresh()}},ne=class extends Bt{constructor(t){super({blade:t.blade,view:t.view,viewProps:t.rackController.viewProps}),this.rackController=t.rackController}importState(t){return ut(t,t=>super.importState(t),t=>({children:t.required.array(t.required.raw)}),t=>this.rackController.rack.children.every((e,i)=>e.importState(t.children[i])))}exportState(){return vt(()=>super.exportState(),{children:this.rackController.rack.children.map(t=>t.exportState())})}};function se(t){return"rackController"in t}var re=class{constructor(t){this.emitter=new m,this.items_=[],this.cache_=new Set,this.onSubListAdd_=this.onSubListAdd_.bind(this),this.onSubListRemove_=this.onSubListRemove_.bind(this),this.extract_=t}get items(){return this.items_}allItems(){return Array.from(this.cache_)}find(t){for(const e of this.allItems())if(t(e))return e;return null}includes(t){return this.cache_.has(t)}add(t,e){if(this.includes(t))throw u.shouldNeverHappen();const i=void 0!==e?e:this.items_.length;this.items_.splice(i,0,t),this.cache_.add(t);const n=this.extract_(t);n&&(n.emitter.on("add",this.onSubListAdd_),n.emitter.on("remove",this.onSubListRemove_),n.allItems().forEach(t=>{this.cache_.add(t)})),this.emitter.emit("add",{index:i,item:t,root:this,target:this})}remove(t){const e=this.items_.indexOf(t);if(e<0)return;this.items_.splice(e,1),this.cache_.delete(t);const i=this.extract_(t);i&&(i.allItems().forEach(t=>{this.cache_.delete(t)}),i.emitter.off("add",this.onSubListAdd_),i.emitter.off("remove",this.onSubListRemove_)),this.emitter.emit("remove",{index:e,item:t,root:this,target:this})}onSubListAdd_(t){this.cache_.add(t.item),this.emitter.emit("add",{index:t.index,item:t.item,root:this,target:t.target})}onSubListRemove_(t){this.cache_.delete(t.item),this.emitter.emit("remove",{index:t.index,item:t.item,root:this,target:t.target})}};function oe(t){return se(t)?t.rackController.rack.bcSet_:null}var ae=class{constructor(t){var e,i;this.emitter=new m,this.onBladePositionsChange_=this.onBladePositionsChange_.bind(this),this.onSetAdd_=this.onSetAdd_.bind(this),this.onSetRemove_=this.onSetRemove_.bind(this),this.onChildDispose_=this.onChildDispose_.bind(this),this.onChildPositionsChange_=this.onChildPositionsChange_.bind(this),this.onChildValueChange_=this.onChildValueChange_.bind(this),this.onChildViewPropsChange_=this.onChildViewPropsChange_.bind(this),this.onRackLayout_=this.onRackLayout_.bind(this),this.onRackValueChange_=this.onRackValueChange_.bind(this),this.blade_=null!==(e=t.blade)&&void 0!==e?e:null,null===(i=this.blade_)||void 0===i||i.value("positions").emitter.on("change",this.onBladePositionsChange_),this.viewProps=t.viewProps,this.bcSet_=new re(oe),this.bcSet_.emitter.on("add",this.onSetAdd_),this.bcSet_.emitter.on("remove",this.onSetRemove_)}get children(){return this.bcSet_.items}add(t,e){var i;null===(i=t.parent)||void 0===i||i.remove(t),t.parent=this,this.bcSet_.add(t,e)}remove(t){t.parent=null,this.bcSet_.remove(t)}find(t){return this.bcSet_.allItems().filter(t)}onSetAdd_(t){this.updatePositions_();const e=t.target===t.root;if(this.emitter.emit("add",{bladeController:t.item,index:t.index,root:e,sender:this}),!e)return;const i=t.item;if(i.viewProps.emitter.on("change",this.onChildViewPropsChange_),i.blade.value("positions").emitter.on("change",this.onChildPositionsChange_),i.viewProps.handleDispose(this.onChildDispose_),mt(i))i.value.emitter.on("change",this.onChildValueChange_);else if(se(i)){const t=i.rackController.rack;if(t){const e=t.emitter;e.on("layout",this.onRackLayout_),e.on("valuechange",this.onRackValueChange_)}}}onSetRemove_(t){this.updatePositions_();const e=t.target===t.root;if(this.emitter.emit("remove",{bladeController:t.item,root:e,sender:this}),!e)return;const i=t.item;if(mt(i))i.value.emitter.off("change",this.onChildValueChange_);else if(se(i)){const t=i.rackController.rack;if(t){const e=t.emitter;e.off("layout",this.onRackLayout_),e.off("valuechange",this.onRackValueChange_)}}}updatePositions_(){const t=this.bcSet_.items.filter(t=>!t.viewProps.get("hidden")),e=t[0],i=t[t.length-1];this.bcSet_.items.forEach(t=>{const n=[];t===e&&(n.push("first"),this.blade_&&!this.blade_.get("positions").includes("veryfirst")||n.push("veryfirst")),t===i&&(n.push("last"),this.blade_&&!this.blade_.get("positions").includes("verylast")||n.push("verylast")),t.blade.set("positions",n)})}onChildPositionsChange_(){this.updatePositions_(),this.emitter.emit("layout",{sender:this})}onChildViewPropsChange_(t){this.updatePositions_(),this.emitter.emit("layout",{sender:this})}onChildDispose_(){this.bcSet_.items.filter(t=>t.viewProps.get("disposed")).forEach(t=>{this.bcSet_.remove(t)})}onChildValueChange_(t){const e=function(t,e){for(let i=0;i{for(let t=this.rack.children.length-1;t>=0;t--)this.rack.children[t].viewProps.set("disposed",!0)})}onRackAdd_(t){t.root&&Ct(this.element,t.bladeController.view.element,t.index)}onRackRemove_(t){t.root&&yt(t.bladeController.view.element)}};function pe(){return new f({positions:_([],{equals:p})})}var he=class t extends f{constructor(t){super(t)}static create(e){const i={completed:!0,expanded:e,expandedHeight:null,shouldFixHeight:!1,temporaryExpanded:null};return new t(f.createCore(i))}get styleExpanded(){var t;return null!==(t=this.get("temporaryExpanded"))&&void 0!==t?t:this.get("expanded")}get styleHeight(){if(!this.styleExpanded)return"0";const t=this.get("expandedHeight");return this.get("shouldFixHeight")&&!o(t)?`${t}px`:"auto"}bindExpandedClass(t,e){const i=()=>{this.styleExpanded?t.classList.add(e):t.classList.remove(e)};Vt(this,"expanded",i),Vt(this,"temporaryExpanded",i)}cleanUpTransition(){this.set("shouldFixHeight",!1),this.set("expandedHeight",null),this.set("completed",!0)}};function ce(t,e){e.style.height=t.styleHeight}function de(t,e){t.value("expanded").emitter.on("beforechange",()=>{if(t.set("completed",!1),o(t.get("expandedHeight"))){const i=function(t,e){let i=0;return function(n){const s=n.style.transition;n.style.transition="none",t.set("expandedHeight",null),t.set("temporaryExpanded",!0),wt(e),i=e.clientHeight,t.set("temporaryExpanded",null),wt(e),n.style.transition=s}(e),i}(t,e);i>0&&t.set("expandedHeight",i)}t.set("shouldFixHeight",!0),wt(e)}),t.emitter.on("change",()=>{ce(t,e)}),ce(t,e),e.addEventListener("transitionend",e=>{"height"===e.propertyName&&t.cleanUpTransition()})}var ue=class extends ie{constructor(t,e){super(t,e),this.emitter_=new m,this.controller.foldable.value("expanded").emitter.on("change",t=>{this.emitter_.emit("fold",new st(this,t.sender.rawValue))}),this.rackApi_.on("change",t=>{this.emitter_.emit("change",t)})}get expanded(){return this.controller.foldable.get("expanded")}set expanded(t){this.controller.foldable.set("expanded",t)}get title(){return this.controller.props.get("title")}set title(t){this.controller.props.set("title",t)}get children(){return this.rackApi_.children}addBinding(t,e,i){return this.rackApi_.addBinding(t,e,i)}addFolder(t){return this.rackApi_.addFolder(t)}addButton(t){return this.rackApi_.addButton(t)}addTab(t){return this.rackApi_.addTab(t)}add(t,e){return this.rackApi_.add(t,e)}remove(t){this.rackApi_.remove(t)}addBlade(t){return this.rackApi_.addBlade(t)}on(t,e){const i=e.bind(this);return this.emitter_.on(t,t=>{i(t)},{key:e}),this}off(t,e){return this.emitter_.off(t,e),this}},ve=Mt("cnt"),me=class{constructor(t,e){var i;this.className_=Mt(null!==(i=e.viewName)&&void 0!==i?i:"fld"),this.element=t.createElement("div"),this.element.classList.add(this.className_(),ve()),e.viewProps.bindClassModifiers(this.element),this.foldable_=e.foldable,this.foldable_.bindExpandedClass(this.element,this.className_(void 0,"expanded")),Vt(this.foldable_,"completed",qt(this.element,this.className_(void 0,"cpl")));const n=t.createElement("button");n.classList.add(this.className_("b")),Vt(e.props,"title",t=>{o(t)?this.element.classList.add(this.className_(void 0,"not")):this.element.classList.remove(this.className_(void 0,"not"))}),e.viewProps.bindDisabled(n),this.element.appendChild(n),this.buttonElement=n;const s=t.createElement("div");s.classList.add(this.className_("i")),this.element.appendChild(s);const r=t.createElement("div");r.classList.add(this.className_("t")),Ht(e.props.value("title"),r),this.buttonElement.appendChild(r),this.titleElement=r;const a=t.createElement("div");a.classList.add(this.className_("m")),this.buttonElement.appendChild(a);const l=t.createElement("div");l.classList.add(this.className_("c")),this.element.appendChild(l),this.containerElement=l}},be=class extends ne{constructor(t,e){var i;const n=he.create(null===(i=e.expanded)||void 0===i||i),s=new me(t,{foldable:n,props:e.props,viewName:e.root?"rot":void 0,viewProps:e.viewProps});super(Object.assign(Object.assign({},e),{rackController:new le({blade:e.blade,element:s.containerElement,root:e.root,viewProps:e.viewProps}),view:s})),this.onTitleClick_=this.onTitleClick_.bind(this),this.props=e.props,this.foldable=n,de(this.foldable,this.view.containerElement),this.rackController.rack.emitter.on("add",()=>{this.foldable.cleanUpTransition()}),this.rackController.rack.emitter.on("remove",()=>{this.foldable.cleanUpTransition()}),this.view.buttonElement.addEventListener("click",this.onTitleClick_)}get document(){return this.view.element.ownerDocument}importState(t){return ut(t,t=>super.importState(t),t=>({expanded:t.required.boolean,title:t.optional.string}),t=>(this.foldable.set("expanded",t.expanded),this.props.set("title",t.title),!0))}exportState(){return vt(()=>super.exportState(),{expanded:this.foldable.get("expanded"),title:this.props.get("title")})}onTitleClick_(){this.foldable.set("expanded",!this.foldable.get("expanded"))}},ge=Zt({id:"folder",type:"blade",accept(t){const e=dt(t,t=>({title:t.required.string,view:t.required.constant("folder"),expanded:t.optional.boolean}));return e?{params:e}:null},controller:t=>new be(t.document,{blade:t.blade,expanded:t.params.expanded,props:f.fromObject({title:t.params.title}),viewProps:t.viewProps}),api:t=>t.controller instanceof be?new ue(t.controller,t.pool):null}),we=Mt("");function _e(t,e){return qt(t,we(void 0,e))}var fe=class t extends f{constructor(t){var e,i;super(t),this.onDisabledChange_=this.onDisabledChange_.bind(this),this.onParentChange_=this.onParentChange_.bind(this),this.onParentGlobalDisabledChange_=this.onParentGlobalDisabledChange_.bind(this),[this.globalDisabled_,this.setGlobalDisabled_]=(i=_(this.getGlobalDisabled_()),[new w(i),(t,e)=>{i.setRawValue(t,e)}]),this.value("disabled").emitter.on("change",this.onDisabledChange_),this.value("parent").emitter.on("change",this.onParentChange_),null===(e=this.get("parent"))||void 0===e||e.globalDisabled.emitter.on("change",this.onParentGlobalDisabledChange_)}static create(e){var i,n,s;const r=null!=e?e:{};return new t(f.createCore({disabled:null!==(i=r.disabled)&&void 0!==i&&i,disposed:!1,hidden:null!==(n=r.hidden)&&void 0!==n&&n,parent:null!==(s=r.parent)&&void 0!==s?s:null}))}get globalDisabled(){return this.globalDisabled_}bindClassModifiers(t){kt(this.globalDisabled_,_e(t,"disabled")),Vt(this,"hidden",_e(t,"hidden"))}bindDisabled(t){kt(this.globalDisabled_,e=>{t.disabled=e})}bindTabIndex(t){kt(this.globalDisabled_,e=>{t.tabIndex=e?-1:0})}handleDispose(t){this.value("disposed").emitter.on("change",e=>{e&&t()})}importState(t){this.set("disabled",t.disabled),this.set("hidden",t.hidden)}exportState(){return{disabled:this.get("disabled"),hidden:this.get("hidden")}}getGlobalDisabled_(){const t=this.get("parent");return!!t&&t.globalDisabled.rawValue||this.get("disabled")}updateGlobalDisabled_(){this.setGlobalDisabled_(this.getGlobalDisabled_())}onDisabledChange_(){this.updateGlobalDisabled_()}onParentGlobalDisabledChange_(){this.updateGlobalDisabled_()}onParentChange_(t){var e;const i=t.previousRawValue;null==i||i.globalDisabled.emitter.off("change",this.onParentGlobalDisabledChange_),null===(e=this.get("parent"))||void 0===e||e.globalDisabled.emitter.on("change",this.onParentGlobalDisabledChange_),this.updateGlobalDisabled_()}},xe=Mt("tbp"),Ce=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(xe()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("div");i.classList.add(xe("c")),this.element.appendChild(i),this.containerElement=i}},ye=Mt("tbi"),Pe=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(ye()),e.viewProps.bindClassModifiers(this.element),Vt(e.props,"selected",t=>{t?this.element.classList.add(ye(void 0,"sel")):this.element.classList.remove(ye(void 0,"sel"))});const i=t.createElement("button");i.classList.add(ye("b")),e.viewProps.bindDisabled(i),this.element.appendChild(i),this.buttonElement=i;const n=t.createElement("div");n.classList.add(ye("t")),Ht(e.props.value("title"),n),this.buttonElement.appendChild(n),this.titleElement=n}},Ee=class{constructor(t,e){this.emitter=new m,this.onClick_=this.onClick_.bind(this),this.props=e.props,this.viewProps=e.viewProps,this.view=new Pe(t,{props:e.props,viewProps:e.viewProps}),this.view.buttonElement.addEventListener("click",this.onClick_)}onClick_(){this.emitter.emit("click",{sender:this})}},ke=class extends ne{constructor(t,e){const i=new Ce(t,{viewProps:e.viewProps});super(Object.assign(Object.assign({},e),{rackController:new le({blade:e.blade,element:i.containerElement,viewProps:e.viewProps}),view:i})),this.onItemClick_=this.onItemClick_.bind(this),this.ic_=new Ee(t,{props:e.itemProps,viewProps:fe.create()}),this.ic_.emitter.on("click",this.onItemClick_),this.props=e.props,Vt(this.props,"selected",t=>{this.itemController.props.set("selected",t),this.viewProps.set("hidden",!t)})}get itemController(){return this.ic_}importState(t){return ut(t,t=>super.importState(t),t=>({selected:t.required.boolean,title:t.required.string}),t=>(this.ic_.props.set("selected",t.selected),this.ic_.props.set("title",t.title),!0))}exportState(){return vt(()=>super.exportState(),{selected:this.ic_.props.get("selected"),title:this.ic_.props.get("title")})}onItemClick_(){this.props.set("selected",!0)}},Ve=class extends ie{constructor(t,e){super(t,e),this.emitter_=new m,this.onSelect_=this.onSelect_.bind(this),this.pool_=e,this.rackApi_.on("change",t=>{this.emitter_.emit("change",t)}),this.controller.tab.selectedIndex.emitter.on("change",this.onSelect_)}get pages(){return this.rackApi_.children}addPage(t){const e=this.controller.view.element.ownerDocument,i=new ke(e,{blade:pe(),itemProps:f.fromObject({selected:!1,title:t.title}),props:f.fromObject({selected:!1}),viewProps:fe.create()}),n=this.pool_.createApi(i);return this.rackApi_.add(n,t.index)}removePage(t){this.rackApi_.remove(this.rackApi_.children[t])}on(t,e){const i=e.bind(this);return this.emitter_.on(t,t=>{i(t)},{key:e}),this}off(t,e){return this.emitter_.off(t,e),this}onSelect_(t){this.emitter_.emit("select",new rt(this,t.rawValue))}},Le=class extends ie{get title(){var t;return null!==(t=this.controller.itemController.props.get("title"))&&void 0!==t?t:""}set title(t){this.controller.itemController.props.set("title",t)}get selected(){return this.controller.props.get("selected")}set selected(t){this.controller.props.set("selected",t)}get children(){return this.rackApi_.children}addButton(t){return this.rackApi_.addButton(t)}addFolder(t){return this.rackApi_.addFolder(t)}addTab(t){return this.rackApi_.addTab(t)}add(t,e){this.rackApi_.add(t,e)}remove(t){this.rackApi_.remove(t)}addBinding(t,e,i){return this.rackApi_.addBinding(t,e,i)}addBlade(t){return this.rackApi_.addBlade(t)}},Me=class{constructor(){this.onItemSelectedChange_=this.onItemSelectedChange_.bind(this),this.empty=_(!0),this.selectedIndex=_(-1),this.items_=[]}add(t,e){const i=null!=e?e:this.items_.length;this.items_.splice(i,0,t),t.emitter.on("change",this.onItemSelectedChange_),this.keepSelection_()}remove(t){const e=this.items_.indexOf(t);e<0||(this.items_.splice(e,1),t.emitter.off("change",this.onItemSelectedChange_),this.keepSelection_())}keepSelection_(){if(0===this.items_.length)return this.selectedIndex.rawValue=-1,void(this.empty.rawValue=!0);const t=this.items_.findIndex(t=>t.rawValue);t<0?(this.items_.forEach((t,e)=>{t.rawValue=0===e}),this.selectedIndex.rawValue=0):(this.items_.forEach((e,i)=>{e.rawValue=i===t}),this.selectedIndex.rawValue=t),this.empty.rawValue=!1}onItemSelectedChange_(t){if(t.rawValue){const e=this.items_.findIndex(e=>e===t.sender);this.items_.forEach((t,i)=>{t.rawValue=i===e}),this.selectedIndex.rawValue=e}else this.keepSelection_()}},Se=Mt("tab"),je=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(Se(),ve()),e.viewProps.bindClassModifiers(this.element),kt(e.empty,qt(this.element,Se(void 0,"nop")));const i=t.createElement("div");i.classList.add(Se("t")),this.element.appendChild(i),this.itemsElement=i;const n=t.createElement("div");n.classList.add(Se("i")),this.element.appendChild(n);const s=t.createElement("div");s.classList.add(Se("c")),this.element.appendChild(s),this.contentsElement=s}},De=class extends ne{constructor(t,e){const i=new Me,n=new je(t,{empty:i.empty,viewProps:e.viewProps});super({blade:e.blade,rackController:new le({blade:e.blade,element:n.contentsElement,viewProps:e.viewProps}),view:n}),this.onRackAdd_=this.onRackAdd_.bind(this),this.onRackRemove_=this.onRackRemove_.bind(this);const s=this.rackController.rack;s.emitter.on("add",this.onRackAdd_),s.emitter.on("remove",this.onRackRemove_),this.tab=i}add(t,e){this.rackController.rack.add(t,e)}remove(t){this.rackController.rack.remove(this.rackController.rack.children[t])}onRackAdd_(t){if(!t.root)return;const e=t.bladeController;Ct(this.view.itemsElement,e.itemController.view.element,t.index),e.itemController.viewProps.set("parent",this.viewProps),this.tab.add(e.props.value("selected"))}onRackRemove_(t){if(!t.root)return;const e=t.bladeController;yt(e.itemController.view.element),e.itemController.viewProps.set("parent",null),this.tab.remove(e.props.value("selected"))}},Ae=Zt({id:"tab",type:"blade",accept(t){const e=dt(t,t=>({pages:t.required.array(t.required.object({title:t.required.string})),view:t.required.constant("tab")}));return e&&0!==e.pages.length?{params:e}:null},controller(t){const e=new De(t.document,{blade:t.blade,viewProps:t.viewProps});return t.params.pages.forEach(i=>{const n=new ke(t.document,{blade:pe(),itemProps:f.fromObject({selected:!1,title:i.title}),props:f.fromObject({selected:!1}),viewProps:fe.create()});e.add(n)}),e},api:t=>t.controller instanceof De?new Ve(t.controller,t.pool):t.controller instanceof ke?new Le(t.controller,t.pool):null}),Oe=class extends at{get options(){return this.controller.valueController.props.get("options")}set options(t){this.controller.valueController.props.set("options",t)}},Be=class{constructor(){this.disabled=!1,this.emitter=new m}dispose(){}tick(){this.disabled||this.emitter.emit("tick",{sender:this})}},Te=class{constructor(t,e){this.disabled_=!1,this.timerId_=null,this.onTick_=this.onTick_.bind(this),this.doc_=t,this.emitter=new m,this.interval_=e,this.setTimer_()}get disabled(){return this.disabled_}set disabled(t){this.disabled_=t,this.disabled_?this.clearTimer_():this.setTimer_()}dispose(){this.clearTimer_()}clearTimer_(){if(null===this.timerId_)return;const t=this.doc_.defaultView;t&&t.clearInterval(this.timerId_),this.timerId_=null}setTimer_(){if(this.clearTimer_(),this.interval_<=0)return;const t=this.doc_.defaultView;t&&(this.timerId_=t.setInterval(this.onTick_,this.interval_))}onTick_(){this.disabled_||this.emitter.emit("tick",{sender:this})}},ze=class{constructor(t){this.constraints=t}constrain(t){return this.constraints.reduce((t,e)=>e.constrain(t),t)}};function Re(t,e){if(t instanceof e)return t;if(t instanceof ze){const i=t.constraints.reduce((t,i)=>t||(i instanceof e?i:null),null);if(i)return i}return null}var Ne=class{constructor(t){this.values=f.fromObject({options:t})}constrain(t){const e=this.values.get("options");return 0===e.length||e.filter(e=>e.value===t).length>0?t:e[0].value}};function Ke(t){var e;const i=ct;return Array.isArray(t)?null===(e=dt({items:t},t=>({items:t.required.array(t.required.object({text:t.required.string,value:t.required.raw}))})))||void 0===e?void 0:e.items:"object"==typeof t?i.required.raw(t).value:void 0}function Ie(t){if(Array.isArray(t))return t;const e=[];return Object.keys(t).forEach(i=>{e.push({text:i,value:t[i]})}),e}function Ue(t){return o(t)?null:new Ne(Ie(t))}var Fe=Mt("lst"),$e=class{constructor(t,e){this.onValueChange_=this.onValueChange_.bind(this),this.props_=e.props,this.element=t.createElement("div"),this.element.classList.add(Fe()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("select");i.classList.add(Fe("s")),e.viewProps.bindDisabled(i),this.element.appendChild(i),this.selectElement=i;const n=t.createElement("div");n.classList.add(Fe("m")),n.appendChild(xt(t,"dropdown")),this.element.appendChild(n),e.value.emitter.on("change",this.onValueChange_),this.value_=e.value,Vt(this.props_,"options",e=>{Pt(this.selectElement),e.forEach(e=>{const i=t.createElement("option");i.textContent=e.text,this.selectElement.appendChild(i)}),this.update_()})}update_(){const t=this.props_.get("options").map(t=>t.value);this.selectElement.selectedIndex=t.indexOf(this.value_.rawValue)}onValueChange_(){this.update_()}},qe=class{constructor(t,e){this.onSelectChange_=this.onSelectChange_.bind(this),this.props=e.props,this.value=e.value,this.viewProps=e.viewProps,this.view=new $e(t,{props:this.props,value:this.value,viewProps:this.viewProps}),this.view.selectElement.addEventListener("change",this.onSelectChange_)}onSelectChange_(t){const e=t.currentTarget;this.value.rawValue=this.props.get("options")[e.selectedIndex].value}importProps(t){return ut(t,null,t=>({options:t.required.custom(Ke)}),t=>(this.props.set("options",Ie(t.options)),!0))}exportProps(){return vt(null,{options:this.props.get("options")})}},He=Mt("pop"),Ge=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(He()),e.viewProps.bindClassModifiers(this.element),kt(e.shows,qt(this.element,He(void 0,"v")))}},Ye=class{constructor(t,e){this.shows=_(!1),this.viewProps=e.viewProps,this.view=new Ge(t,{shows:this.shows,viewProps:this.viewProps})}},Xe=Mt("txt"),We=class{constructor(t,e){this.onChange_=this.onChange_.bind(this),this.element=t.createElement("div"),this.element.classList.add(Xe()),e.viewProps.bindClassModifiers(this.element),this.props_=e.props,this.props_.emitter.on("change",this.onChange_);const i=t.createElement("input");i.classList.add(Xe("i")),i.type="text",e.viewProps.bindDisabled(i),this.element.appendChild(i),this.inputElement=i,e.value.emitter.on("change",this.onChange_),this.value_=e.value,this.refresh()}refresh(){const t=this.props_.get("formatter");this.inputElement.value=t(this.value_.rawValue)}onChange_(){this.refresh()}},Qe=class{constructor(t,e){this.onInputChange_=this.onInputChange_.bind(this),this.parser_=e.parser,this.props=e.props,this.value=e.value,this.viewProps=e.viewProps,this.view=new We(t,{props:e.props,value:this.value,viewProps:this.viewProps}),this.view.inputElement.addEventListener("change",this.onInputChange_)}onInputChange_(t){const e=t.currentTarget.value,i=this.parser_(e);o(i)||(this.value.rawValue=i),this.view.refresh()}};function Je(t){return"false"!==t&&!!t}function Ze(t){return function(t){return String(t)}(t)}var ti=U(0);function ei(t){return ti(t)+"%"}function ii(t){return String(t)}function ni(t){return t}function si({primary:t,secondary:e,forward:i,backward:n}){let s=!1;function r(t){s||(s=!0,t(),s=!1)}t.emitter.on("change",n=>{r(()=>{e.setRawValue(i(t.rawValue,e.rawValue),n.options)})}),e.emitter.on("change",s=>{r(()=>{t.setRawValue(n(t.rawValue,e.rawValue),s.options)}),r(()=>{e.setRawValue(i(t.rawValue,e.rawValue),s.options)})}),r(()=>{e.setRawValue(i(t.rawValue,e.rawValue),{forceEmit:!1,last:!0})})}function ri(t,e){const i=t*(e.altKey?.1:1)*(e.shiftKey?10:1);return e.upKey?+i:e.downKey?-i:0}function oi(t){return{altKey:t.altKey,downKey:"ArrowDown"===t.key,shiftKey:t.shiftKey,upKey:"ArrowUp"===t.key}}function ai(t){return{altKey:t.altKey,downKey:"ArrowLeft"===t.key,shiftKey:t.shiftKey,upKey:"ArrowRight"===t.key}}function li(t){return function(t){return"ArrowUp"===t||"ArrowDown"===t}(t)||"ArrowLeft"===t||"ArrowRight"===t}function pi(t,e){var i,n;const s=e.ownerDocument.defaultView,r=e.getBoundingClientRect();return{x:t.pageX-((null!==(i=s&&s.scrollX)&&void 0!==i?i:0)+r.left),y:t.pageY-((null!==(n=s&&s.scrollY)&&void 0!==n?n:0)+r.top)}}var hi=class{constructor(t){this.lastTouch_=null,this.onDocumentMouseMove_=this.onDocumentMouseMove_.bind(this),this.onDocumentMouseUp_=this.onDocumentMouseUp_.bind(this),this.onMouseDown_=this.onMouseDown_.bind(this),this.onTouchEnd_=this.onTouchEnd_.bind(this),this.onTouchMove_=this.onTouchMove_.bind(this),this.onTouchStart_=this.onTouchStart_.bind(this),this.elem_=t,this.emitter=new m,t.addEventListener("touchstart",this.onTouchStart_,{passive:!1}),t.addEventListener("touchmove",this.onTouchMove_,{passive:!0}),t.addEventListener("touchend",this.onTouchEnd_),t.addEventListener("mousedown",this.onMouseDown_)}computePosition_(t){const e=this.elem_.getBoundingClientRect();return{bounds:{width:e.width,height:e.height},point:t?{x:t.x,y:t.y}:null}}onMouseDown_(t){var e;t.preventDefault(),null===(e=t.currentTarget)||void 0===e||e.focus();const i=this.elem_.ownerDocument;i.addEventListener("mousemove",this.onDocumentMouseMove_),i.addEventListener("mouseup",this.onDocumentMouseUp_),this.emitter.emit("down",{altKey:t.altKey,data:this.computePosition_(pi(t,this.elem_)),sender:this,shiftKey:t.shiftKey})}onDocumentMouseMove_(t){this.emitter.emit("move",{altKey:t.altKey,data:this.computePosition_(pi(t,this.elem_)),sender:this,shiftKey:t.shiftKey})}onDocumentMouseUp_(t){const e=this.elem_.ownerDocument;e.removeEventListener("mousemove",this.onDocumentMouseMove_),e.removeEventListener("mouseup",this.onDocumentMouseUp_),this.emitter.emit("up",{altKey:t.altKey,data:this.computePosition_(pi(t,this.elem_)),sender:this,shiftKey:t.shiftKey})}onTouchStart_(t){t.preventDefault();const e=t.targetTouches.item(0),i=this.elem_.getBoundingClientRect();this.emitter.emit("down",{altKey:t.altKey,data:this.computePosition_(e?{x:e.clientX-i.left,y:e.clientY-i.top}:void 0),sender:this,shiftKey:t.shiftKey}),this.lastTouch_=e}onTouchMove_(t){const e=t.targetTouches.item(0),i=this.elem_.getBoundingClientRect();this.emitter.emit("move",{altKey:t.altKey,data:this.computePosition_(e?{x:e.clientX-i.left,y:e.clientY-i.top}:void 0),sender:this,shiftKey:t.shiftKey}),this.lastTouch_=e}onTouchEnd_(t){var e;const i=null!==(e=t.targetTouches.item(0))&&void 0!==e?e:this.lastTouch_,n=this.elem_.getBoundingClientRect();this.emitter.emit("up",{altKey:t.altKey,data:this.computePosition_(i?{x:i.clientX-n.left,y:i.clientY-n.top}:void 0),sender:this,shiftKey:t.shiftKey})}},ci=Mt("txt"),di=class{constructor(t,e){this.onChange_=this.onChange_.bind(this),this.props_=e.props,this.props_.emitter.on("change",this.onChange_),this.element=t.createElement("div"),this.element.classList.add(ci(),ci(void 0,"num")),e.arrayPosition&&this.element.classList.add(ci(void 0,e.arrayPosition)),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("input");i.classList.add(ci("i")),i.type="text",e.viewProps.bindDisabled(i),this.element.appendChild(i),this.inputElement=i,this.onDraggingChange_=this.onDraggingChange_.bind(this),this.dragging_=e.dragging,this.dragging_.emitter.on("change",this.onDraggingChange_),this.element.classList.add(ci()),this.inputElement.classList.add(ci("i"));const n=t.createElement("div");n.classList.add(ci("k")),this.element.appendChild(n),this.knobElement=n;const s=t.createElementNS(gt,"svg");s.classList.add(ci("g")),this.knobElement.appendChild(s);const r=t.createElementNS(gt,"path");r.classList.add(ci("gb")),s.appendChild(r),this.guideBodyElem_=r;const o=t.createElementNS(gt,"path");o.classList.add(ci("gh")),s.appendChild(o),this.guideHeadElem_=o;const a=t.createElement("div");a.classList.add(Mt("tt")()),this.knobElement.appendChild(a),this.tooltipElem_=a,e.value.emitter.on("change",this.onChange_),this.value=e.value,this.refresh()}onDraggingChange_(t){if(null===t.rawValue)return void this.element.classList.remove(ci(void 0,"drg"));this.element.classList.add(ci(void 0,"drg"));const e=t.rawValue/this.props_.get("pointerScale"),i=e+(e>0?-1:e<0?1:0),n=q(-i,-4,4);this.guideHeadElem_.setAttributeNS(null,"d",[`M ${i+n},0 L${i},4 L${i+n},8`,`M ${e},-1 L${e},9`].join(" ")),this.guideBodyElem_.setAttributeNS(null,"d",`M 0,4 L${e},4`);const s=this.props_.get("formatter");this.tooltipElem_.textContent=s(this.value.rawValue),this.tooltipElem_.style.left=`${e}px`}refresh(){const t=this.props_.get("formatter");this.inputElement.value=t(this.value.rawValue)}onChange_(){this.refresh()}},ui=class{constructor(t,e){var i;this.originRawValue_=0,this.onInputChange_=this.onInputChange_.bind(this),this.onInputKeyDown_=this.onInputKeyDown_.bind(this),this.onInputKeyUp_=this.onInputKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.parser_=e.parser,this.props=e.props,this.sliderProps_=null!==(i=e.sliderProps)&&void 0!==i?i:null,this.value=e.value,this.viewProps=e.viewProps,this.dragging_=_(null),this.view=new di(t,{arrayPosition:e.arrayPosition,dragging:this.dragging_,props:this.props,value:this.value,viewProps:this.viewProps}),this.view.inputElement.addEventListener("change",this.onInputChange_),this.view.inputElement.addEventListener("keydown",this.onInputKeyDown_),this.view.inputElement.addEventListener("keyup",this.onInputKeyUp_);const n=new hi(this.view.knobElement);n.emitter.on("down",this.onPointerDown_),n.emitter.on("move",this.onPointerMove_),n.emitter.on("up",this.onPointerUp_)}constrainValue_(t){var e,i;const n=null===(e=this.sliderProps_)||void 0===e?void 0:e.get("min"),s=null===(i=this.sliderProps_)||void 0===i?void 0:i.get("max");let r=t;return void 0!==n&&(r=Math.max(r,n)),void 0!==s&&(r=Math.min(r,s)),r}onInputChange_(t){const e=t.currentTarget.value,i=this.parser_(e);o(i)||(this.value.rawValue=this.constrainValue_(i)),this.view.refresh()}onInputKeyDown_(t){const e=ri(this.props.get("keyScale"),oi(t));0!==e&&this.value.setRawValue(this.constrainValue_(this.value.rawValue+e),{forceEmit:!1,last:!1})}onInputKeyUp_(t){0!==ri(this.props.get("keyScale"),oi(t))&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}onPointerDown_(){this.originRawValue_=this.value.rawValue,this.dragging_.rawValue=0}computeDraggingValue_(t){if(!t.point)return null;const e=t.point.x-t.bounds.width/2;return this.constrainValue_(this.originRawValue_+e*this.props.get("pointerScale"))}onPointerMove_(t){const e=this.computeDraggingValue_(t.data);null!==e&&(this.value.setRawValue(e,{forceEmit:!1,last:!1}),this.dragging_.rawValue=this.value.rawValue-this.originRawValue_)}onPointerUp_(t){const e=this.computeDraggingValue_(t.data);null!==e&&(this.value.setRawValue(e,{forceEmit:!0,last:!0}),this.dragging_.rawValue=null)}},vi=Mt("sld"),mi=class{constructor(t,e){this.onChange_=this.onChange_.bind(this),this.props_=e.props,this.props_.emitter.on("change",this.onChange_),this.element=t.createElement("div"),this.element.classList.add(vi()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("div");i.classList.add(vi("t")),e.viewProps.bindTabIndex(i),this.element.appendChild(i),this.trackElement=i;const n=t.createElement("div");n.classList.add(vi("k")),this.trackElement.appendChild(n),this.knobElement=n,e.value.emitter.on("change",this.onChange_),this.value=e.value,this.update_()}update_(){const t=q(F(this.value.rawValue,this.props_.get("min"),this.props_.get("max"),0,100),0,100);this.knobElement.style.width=`${t}%`}onChange_(){this.update_()}},bi=class{constructor(t,e){this.onKeyDown_=this.onKeyDown_.bind(this),this.onKeyUp_=this.onKeyUp_.bind(this),this.onPointerDownOrMove_=this.onPointerDownOrMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.value=e.value,this.viewProps=e.viewProps,this.props=e.props,this.view=new mi(t,{props:this.props,value:this.value,viewProps:this.viewProps}),this.ptHandler_=new hi(this.view.trackElement),this.ptHandler_.emitter.on("down",this.onPointerDownOrMove_),this.ptHandler_.emitter.on("move",this.onPointerDownOrMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.trackElement.addEventListener("keydown",this.onKeyDown_),this.view.trackElement.addEventListener("keyup",this.onKeyUp_)}handlePointerEvent_(t,e){t.point&&this.value.setRawValue(F(q(t.point.x,0,t.bounds.width),0,t.bounds.width,this.props.get("min"),this.props.get("max")),e)}onPointerDownOrMove_(t){this.handlePointerEvent_(t.data,{forceEmit:!1,last:!1})}onPointerUp_(t){this.handlePointerEvent_(t.data,{forceEmit:!0,last:!0})}onKeyDown_(t){const e=ri(this.props.get("keyScale"),ai(t));0!==e&&this.value.setRawValue(this.value.rawValue+e,{forceEmit:!1,last:!1})}onKeyUp_(t){0!==ri(this.props.get("keyScale"),ai(t))&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}},gi=Mt("sldtxt"),wi=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(gi());const i=t.createElement("div");i.classList.add(gi("s")),this.sliderView_=e.sliderView,i.appendChild(this.sliderView_.element),this.element.appendChild(i);const n=t.createElement("div");n.classList.add(gi("t")),this.textView_=e.textView,n.appendChild(this.textView_.element),this.element.appendChild(n)}},_i=class{constructor(t,e){this.value=e.value,this.viewProps=e.viewProps,this.sliderC_=new bi(t,{props:e.sliderProps,value:e.value,viewProps:this.viewProps}),this.textC_=new ui(t,{parser:e.parser,props:e.textProps,sliderProps:e.sliderProps,value:e.value,viewProps:e.viewProps}),this.view=new wi(t,{sliderView:this.sliderC_.view,textView:this.textC_.view})}get sliderController(){return this.sliderC_}get textController(){return this.textC_}importProps(t){return ut(t,null,t=>({max:t.required.number,min:t.required.number}),t=>{const e=this.sliderC_.props;return e.set("max",t.max),e.set("min",t.min),!0})}exportProps(){const t=this.sliderC_.props;return vt(null,{max:t.get("max"),min:t.get("min")})}};function fi(t){return{sliderProps:new f({keyScale:t.keyScale,max:t.max,min:t.min}),textProps:new f({formatter:_(t.formatter),keyScale:t.keyScale,pointerScale:_(t.pointerScale)})}}var xi={containerUnitSize:"cnt-usz"};function Ci(t){return`--${xi[t]}`}function yi(t){return Z(t)}function Pi(t){if(l(t))return dt(t,yi)}function Ei(t,e){if(!t)return;const i=[],n=W(t,e);n&&i.push(n);const s=Q(t);return s&&i.push(s),new ze(i)}function ki(t){if("inline"===t||"popup"===t)return t}function Vi(t,e){t.write(e)}var Li=Mt("ckb"),Mi=class{constructor(t,e){this.onValueChange_=this.onValueChange_.bind(this),this.element=t.createElement("div"),this.element.classList.add(Li()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("label");i.classList.add(Li("l")),this.element.appendChild(i),this.labelElement=i;const n=t.createElement("input");n.classList.add(Li("i")),n.type="checkbox",this.labelElement.appendChild(n),this.inputElement=n,e.viewProps.bindDisabled(this.inputElement);const s=t.createElement("div");s.classList.add(Li("w")),this.labelElement.appendChild(s);const r=xt(t,"check");s.appendChild(r),e.value.emitter.on("change",this.onValueChange_),this.value=e.value,this.update_()}update_(){this.inputElement.checked=this.value.rawValue}onValueChange_(){this.update_()}},Si=class{constructor(t,e){this.onInputChange_=this.onInputChange_.bind(this),this.onLabelMouseDown_=this.onLabelMouseDown_.bind(this),this.value=e.value,this.viewProps=e.viewProps,this.view=new Mi(t,{value:this.value,viewProps:this.viewProps}),this.view.inputElement.addEventListener("change",this.onInputChange_),this.view.labelElement.addEventListener("mousedown",this.onLabelMouseDown_)}onInputChange_(t){const e=t.currentTarget;this.value.rawValue=e.checked,t.preventDefault(),t.stopPropagation()}onLabelMouseDown_(t){t.preventDefault()}},ji=Zt({id:"input-bool",type:"input",accept:(t,e)=>{if("boolean"!=typeof t)return null;const i=dt(e,t=>({options:t.optional.custom(Ke),readonly:t.optional.constant(!1)}));return i?{initialValue:t,params:i}:null},binding:{reader:t=>Je,constraint:t=>function(t){const e=[],i=Ue(t.options);return i&&e.push(i),new ze(e)}(t.params),writer:t=>Vi},controller:t=>{const e=t.document,i=t.value,n=t.constraint,s=n&&Re(n,Ne);return s?new qe(e,{props:new f({options:s.values.value("options")}),value:i,viewProps:t.viewProps}):new Si(e,{value:i,viewProps:t.viewProps})},api:t=>"boolean"!=typeof t.controller.value.rawValue?null:t.controller.valueController instanceof qe?new Oe(t.controller):null}),Di=Mt("col"),Ai=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(Di()),e.foldable.bindExpandedClass(this.element,Di(void 0,"expanded")),Vt(e.foldable,"completed",qt(this.element,Di(void 0,"cpl")));const i=t.createElement("div");i.classList.add(Di("h")),this.element.appendChild(i);const n=t.createElement("div");n.classList.add(Di("s")),i.appendChild(n),this.swatchElement=n;const s=t.createElement("div");if(s.classList.add(Di("t")),i.appendChild(s),this.textElement=s,"inline"===e.pickerLayout){const e=t.createElement("div");e.classList.add(Di("p")),this.element.appendChild(e),this.pickerElement=e}else this.pickerElement=null}};function Oi(t,e,i){const n=H(t,360),s=q(e/100,0,1),r=q(i/100,0,1),o=r*s,a=o*(1-Math.abs(n/60%2-1)),l=r-o;let p,h,c;return[p,h,c]=n>=0&&n<60?[o,a,0]:n>=60&&n<120?[a,o,0]:n>=120&&n<180?[0,o,a]:n>=180&&n<240?[0,a,o]:n>=240&&n<300?[a,0,o]:[o,0,a],[255*(p+l),255*(h+l),255*(c+l)]}function Bi(t){return[t[0],t[1],t[2]]}function Ti(t,e){return[t[0],t[1],t[2],e]}var zi={hsl:{hsl:(t,e,i)=>[t,e,i],hsv:function(t,e,i){const n=i+e*(100-Math.abs(2*i-100))/200;return[t,0!==n?e*(100-Math.abs(2*i-100))/n:0,i+e*(100-Math.abs(2*i-100))/200]},rgb:function(t,e,i){const n=(t%360+360)%360,s=q(e/100,0,1),r=q(i/100,0,1),o=(1-Math.abs(2*r-1))*s,a=o*(1-Math.abs(n/60%2-1)),l=r-o/2;let p,h,c;return[p,h,c]=n>=0&&n<60?[o,a,0]:n>=60&&n<120?[a,o,0]:n>=120&&n<180?[0,o,a]:n>=180&&n<240?[0,a,o]:n>=240&&n<300?[a,0,o]:[o,0,a],[255*(p+l),255*(h+l),255*(c+l)]}},hsv:{hsl:function(t,e,i){const n=100-Math.abs(i*(200-e)/100-100);return[t,0!==n?e*i/n:0,i*(200-e)/200]},hsv:(t,e,i)=>[t,e,i],rgb:Oi},rgb:{hsl:function(t,e,i){const n=q(t/255,0,1),s=q(e/255,0,1),r=q(i/255,0,1),o=Math.max(n,s,r),a=Math.min(n,s,r),l=o-a;let p=0,h=0;const c=(a+o)/2;return 0!==l&&(h=l/(1-Math.abs(o+a-1)),p=n===o?(s-r)/l:s===o?2+(r-n)/l:4+(n-s)/l,p=p/6+(p<0?1:0)),[360*p,100*h,100*c]},hsv:function(t,e,i){const n=q(t/255,0,1),s=q(e/255,0,1),r=q(i/255,0,1),o=Math.max(n,s,r),a=o-Math.min(n,s,r);let l;return l=0===a?0:o===n?((s-r)/a%6+6)%6*60:o===s?60*((r-n)/a+2):60*((n-s)/a+4),[l,100*(0===o?0:a/o),100*o]},rgb:(t,e,i)=>[t,e,i]}};function Ri(t,e){return["float"===e?1:"rgb"===t?255:360,"float"===e?1:"rgb"===t?255:100,"float"===e?1:"rgb"===t?255:100]}function Ni(t,e,i){var n;const s=Ri(e,i);return["rgb"===e?q(t[0],0,s[0]):(r=t[0],o=s[0],r===o?o:H(r,o)),q(t[1],0,s[1]),q(t[2],0,s[2]),q(null!==(n=t[3])&&void 0!==n?n:1,0,1)];var r,o}function Ki(t,e,i,n){const s=Ri(e,i),r=Ri(e,n);return t.map((t,e)=>t/s[e]*r[e])}function Ii(t,e,i){const n=Ki(t,e.mode,e.type,"int");return Ki(zi[e.mode][i.mode](...n),i.mode,"int",i.type)}var Ui=class t{static black(){return new t([0,0,0],"rgb")}constructor(t,e){this.type="int",this.mode=e,this.comps_=Ni(t,e,this.type)}getComponents(t){return Ti(Ii(Bi(this.comps_),{mode:this.mode,type:this.type},{mode:null!=t?t:this.mode,type:this.type}),this.comps_[3])}toRgbaObject(){const t=this.getComponents("rgb");return{r:t[0],g:t[1],b:t[2],a:t[3]}}},Fi=Mt("colp"),$i=class{constructor(t,e){this.alphaViews_=null,this.element=t.createElement("div"),this.element.classList.add(Fi()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("div");i.classList.add(Fi("hsv"));const n=t.createElement("div");n.classList.add(Fi("sv")),this.svPaletteView_=e.svPaletteView,n.appendChild(this.svPaletteView_.element),i.appendChild(n);const s=t.createElement("div");s.classList.add(Fi("h")),this.hPaletteView_=e.hPaletteView,s.appendChild(this.hPaletteView_.element),i.appendChild(s),this.element.appendChild(i);const r=t.createElement("div");if(r.classList.add(Fi("rgb")),this.textsView_=e.textsView,r.appendChild(this.textsView_.element),this.element.appendChild(r),e.alphaViews){this.alphaViews_={palette:e.alphaViews.palette,text:e.alphaViews.text};const i=t.createElement("div");i.classList.add(Fi("a"));const n=t.createElement("div");n.classList.add(Fi("ap")),n.appendChild(this.alphaViews_.palette.element),i.appendChild(n);const s=t.createElement("div");s.classList.add(Fi("at")),s.appendChild(this.alphaViews_.text.element),i.appendChild(s),this.element.appendChild(i)}}get allFocusableElements(){const t=[this.svPaletteView_.element,this.hPaletteView_.element,this.textsView_.modeSelectElement,...this.textsView_.inputViews.map(t=>t.inputElement)];return this.alphaViews_&&t.push(this.alphaViews_.palette.element,this.alphaViews_.text.inputElement),t}};function qi(t){return"int"===t?"int":"float"===t?"float":void 0}function Hi(t){return dt(t,t=>({color:t.optional.object({alpha:t.optional.boolean,type:t.optional.custom(qi)}),expanded:t.optional.boolean,picker:t.optional.custom(ki),readonly:t.optional.constant(!1)}))}function Gi(t){return t?.1:1}function Yi(t){var e;return null===(e=t.color)||void 0===e?void 0:e.type}var Xi=class{constructor(t,e){this.type="float",this.mode=e,this.comps_=Ni(t,e,this.type)}getComponents(t){return Ti(Ii(Bi(this.comps_),{mode:this.mode,type:this.type},{mode:null!=t?t:this.mode,type:this.type}),this.comps_[3])}toRgbaObject(){const t=this.getComponents("rgb");return{r:t[0],g:t[1],b:t[2],a:t[3]}}},Wi={int:(t,e)=>new Ui(t,e),float:(t,e)=>new Xi(t,e)};function Qi(t,e,i){return Wi[i](t,e)}function Ji(t,e){if(t.type===e)return t;if(function(t){return"int"===t.type}(t)&&"float"===e)return function(t){const e=t.getComponents(),i=Ri(t.mode,"int");return new Xi([F(e[0],0,i[0],0,1),F(e[1],0,i[1],0,1),F(e[2],0,i[2],0,1),e[3]],t.mode)}(t);if(function(t){return"float"===t.type}(t)&&"int"===e)return function(t){const e=t.getComponents(),i=Ri(t.mode,"int");return new Ui([Math.round(F(e[0],0,1,0,i[0])),Math.round(F(e[1],0,1,0,i[1])),Math.round(F(e[2],0,1,0,i[2])),e[3]],t.mode)}(t);throw u.shouldNeverHappen()}function Zi(t,e){const i=t.match(/^(.+)%$/);return i?Math.min(.01*parseFloat(i[1])*e,e):Math.min(parseFloat(t),e)}var tn={deg:t=>t,grad:t=>360*t/400,rad:t=>360*t/(2*Math.PI),turn:t=>360*t};function en(t){const e=t.match(/^([0-9.]+?)(deg|grad|rad|turn)$/);if(!e)return parseFloat(t);const i=parseFloat(e[1]);return tn[e[2]](i)}function nn(t){const e=t.match(/^rgb\(\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!e)return null;const i=[Zi(e[1],255),Zi(e[2],255),Zi(e[3],255)];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])?null:i}function sn(t){const e=nn(t);return e?new Ui(e,"rgb"):null}function rn(t){const e=t.match(/^rgba\(\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!e)return null;const i=[Zi(e[1],255),Zi(e[2],255),Zi(e[3],255),Zi(e[4],1)];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])||isNaN(i[3])?null:i}function on(t){const e=rn(t);return e?new Ui(e,"rgb"):null}function an(t){const e=t.match(/^hsl\(\s*([0-9A-Fa-f.]+(?:deg|grad|rad|turn)?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!e)return null;const i=[en(e[1]),Zi(e[2],100),Zi(e[3],100)];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])?null:i}function ln(t){const e=an(t);return e?new Ui(e,"hsl"):null}function pn(t){const e=t.match(/^hsla\(\s*([0-9A-Fa-f.]+(?:deg|grad|rad|turn)?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!e)return null;const i=[en(e[1]),Zi(e[2],100),Zi(e[3],100),Zi(e[4],1)];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])||isNaN(i[3])?null:i}function hn(t){const e=pn(t);return e?new Ui(e,"hsl"):null}function cn(t){const e=t.match(/^#([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])$/);if(e)return[parseInt(e[1]+e[1],16),parseInt(e[2]+e[2],16),parseInt(e[3]+e[3],16)];const i=t.match(/^(?:#|0x)([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})$/);return i?[parseInt(i[1],16),parseInt(i[2],16),parseInt(i[3],16)]:null}function dn(t){const e=cn(t);return e?new Ui(e,"rgb"):null}function un(t){const e=t.match(/^#([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])$/);if(e)return[parseInt(e[1]+e[1],16),parseInt(e[2]+e[2],16),parseInt(e[3]+e[3],16),F(parseInt(e[4]+e[4],16),0,255,0,1)];const i=t.match(/^(?:#|0x)?([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})$/);return i?[parseInt(i[1],16),parseInt(i[2],16),parseInt(i[3],16),F(parseInt(i[4],16),0,255,0,1)]:null}function vn(t){const e=un(t);return e?new Ui(e,"rgb"):null}function mn(t){const e=t.match(/^\{\s*r\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*g\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*b\s*:\s*([0-9A-Fa-f.]+%?)\s*\}$/);if(!e)return null;const i=[parseFloat(e[1]),parseFloat(e[2]),parseFloat(e[3])];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])?null:i}function bn(t){return e=>{const i=mn(e);return i?Qi(i,"rgb",t):null}}function gn(t){const e=t.match(/^\{\s*r\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*g\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*b\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*a\s*:\s*([0-9A-Fa-f.]+%?)\s*\}$/);if(!e)return null;const i=[parseFloat(e[1]),parseFloat(e[2]),parseFloat(e[3]),parseFloat(e[4])];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])||isNaN(i[3])?null:i}function wn(t){return e=>{const i=gn(e);return i?Qi(i,"rgb",t):null}}var _n=[{parser:cn,result:{alpha:!1,mode:"rgb",notation:"hex"}},{parser:un,result:{alpha:!0,mode:"rgb",notation:"hex"}},{parser:nn,result:{alpha:!1,mode:"rgb",notation:"func"}},{parser:rn,result:{alpha:!0,mode:"rgb",notation:"func"}},{parser:an,result:{alpha:!1,mode:"hsl",notation:"func"}},{parser:pn,result:{alpha:!0,mode:"hsl",notation:"func"}},{parser:mn,result:{alpha:!1,mode:"rgb",notation:"object"}},{parser:gn,result:{alpha:!0,mode:"rgb",notation:"object"}}];function fn(t){const e=[dn,vn,sn,on,ln,hn];"int"===t&&e.push(bn("int"),wn("int")),"float"===t&&e.push(bn("float"),wn("float"));const i=function(t){return e=>t.reduce((t,i)=>null!==t?t:i(e),null)}(e);return e=>{const n=i(e);return n?Ji(n,t):null}}function xn(t){const e=fn("int");if("string"!=typeof t)return Ui.black();const i=e(t);return null!=i?i:Ui.black()}function Cn(t){const e=q(Math.floor(t),0,255).toString(16);return 1===e.length?`0${e}`:e}function yn(t,e="#"){return`${e}${Bi(t.getComponents("rgb")).map(Cn).join("")}`}function Pn(t,e="#"){const i=t.getComponents("rgb");return`${e}${[i[0],i[1],i[2],255*i[3]].map(Cn).join("")}`}function En(t){const e=U(0);return`rgb(${Bi(Ji(t,"int").getComponents("rgb")).map(t=>e(t)).join(", ")})`}function kn(t){const e=U(2),i=U(0);return`rgba(${Ji(t,"int").getComponents("rgb").map((t,n)=>(3===n?e:i)(t)).join(", ")})`}function Vn(t,e){const i=U("float"===e?2:0),n=["r","g","b"];return`{${Bi(Ji(t,e).getComponents("rgb")).map((t,e)=>`${n[e]}: ${i(t)}`).join(", ")}}`}function Ln(t){return e=>Vn(e,t)}function Mn(t,e){const i=U(2),n=U("float"===e?2:0),s=["r","g","b","a"];return`{${Ji(t,e).getComponents("rgb").map((t,e)=>`${s[e]}: ${(3===e?i:n)(t)}`).join(", ")}}`}function Sn(t){return e=>Mn(e,t)}var jn=[{format:{alpha:!1,mode:"rgb",notation:"hex",type:"int"},stringifier:yn},{format:{alpha:!0,mode:"rgb",notation:"hex",type:"int"},stringifier:Pn},{format:{alpha:!1,mode:"rgb",notation:"func",type:"int"},stringifier:En},{format:{alpha:!0,mode:"rgb",notation:"func",type:"int"},stringifier:kn},{format:{alpha:!1,mode:"hsl",notation:"func",type:"int"},stringifier:function(t){const e=[U(0),ei,ei];return`hsl(${Bi(Ji(t,"int").getComponents("hsl")).map((t,i)=>e[i](t)).join(", ")})`}},{format:{alpha:!0,mode:"hsl",notation:"func",type:"int"},stringifier:function(t){const e=[U(0),ei,ei,U(2)];return`hsla(${Ji(t,"int").getComponents("hsl").map((t,i)=>e[i](t)).join(", ")})`}},...["int","float"].reduce((t,e)=>[...t,{format:{alpha:!1,mode:"rgb",notation:"object",type:e},stringifier:Ln(e)},{format:{alpha:!0,mode:"rgb",notation:"object",type:e},stringifier:Sn(e)}],[])];function Dn(t){return jn.reduce((e,i)=>{return e||(n=i.format,s=t,n.alpha===s.alpha&&n.mode===s.mode&&n.notation===s.notation&&n.type===s.type?i.stringifier:null);var n,s},null)}var An=Mt("apl"),On=class{constructor(t,e){this.onValueChange_=this.onValueChange_.bind(this),this.value=e.value,this.value.emitter.on("change",this.onValueChange_),this.element=t.createElement("div"),this.element.classList.add(An()),e.viewProps.bindClassModifiers(this.element),e.viewProps.bindTabIndex(this.element);const i=t.createElement("div");i.classList.add(An("b")),this.element.appendChild(i);const n=t.createElement("div");n.classList.add(An("c")),i.appendChild(n),this.colorElem_=n;const s=t.createElement("div");s.classList.add(An("m")),this.element.appendChild(s),this.markerElem_=s;const r=t.createElement("div");r.classList.add(An("p")),this.markerElem_.appendChild(r),this.previewElem_=r,this.update_()}update_(){const t=this.value.rawValue,e=t.getComponents("rgb"),i=new Ui([e[0],e[1],e[2],0],"rgb"),n=new Ui([e[0],e[1],e[2],255],"rgb"),s=["to right",kn(i),kn(n)];this.colorElem_.style.background=`linear-gradient(${s.join(",")})`,this.previewElem_.style.backgroundColor=kn(t);const r=F(e[3],0,1,0,100);this.markerElem_.style.left=`${r}%`}onValueChange_(){this.update_()}},Bn=class{constructor(t,e){this.onKeyDown_=this.onKeyDown_.bind(this),this.onKeyUp_=this.onKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.value=e.value,this.viewProps=e.viewProps,this.view=new On(t,{value:this.value,viewProps:this.viewProps}),this.ptHandler_=new hi(this.view.element),this.ptHandler_.emitter.on("down",this.onPointerDown_),this.ptHandler_.emitter.on("move",this.onPointerMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.element.addEventListener("keydown",this.onKeyDown_),this.view.element.addEventListener("keyup",this.onKeyUp_)}handlePointerEvent_(t,e){if(!t.point)return;const i=t.point.x/t.bounds.width,[n,s,r]=this.value.rawValue.getComponents("hsv");this.value.setRawValue(new Ui([n,s,r,i],"hsv"),e)}onPointerDown_(t){this.handlePointerEvent_(t.data,{forceEmit:!1,last:!1})}onPointerMove_(t){this.handlePointerEvent_(t.data,{forceEmit:!1,last:!1})}onPointerUp_(t){this.handlePointerEvent_(t.data,{forceEmit:!0,last:!0})}onKeyDown_(t){const e=ri(Gi(!0),ai(t));if(0===e)return;const[i,n,s,r]=this.value.rawValue.getComponents("hsv");this.value.setRawValue(new Ui([i,n,s,r+e],"hsv"),{forceEmit:!1,last:!1})}onKeyUp_(t){0!==ri(Gi(!0),ai(t))&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}},Tn=Mt("coltxt"),zn=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(Tn()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("div");i.classList.add(Tn("m")),this.modeElem_=function(t){const e=t.createElement("select");return e.appendChild([{text:"RGB",value:"rgb"},{text:"HSL",value:"hsl"},{text:"HSV",value:"hsv"},{text:"HEX",value:"hex"}].reduce((e,i)=>{const n=t.createElement("option");return n.textContent=i.text,n.value=i.value,e.appendChild(n),e},t.createDocumentFragment())),e}(t),this.modeElem_.classList.add(Tn("ms")),i.appendChild(this.modeSelectElement),e.viewProps.bindDisabled(this.modeElem_);const n=t.createElement("div");n.classList.add(Tn("mm")),n.appendChild(xt(t,"dropdown")),i.appendChild(n),this.element.appendChild(i);const s=t.createElement("div");s.classList.add(Tn("w")),this.element.appendChild(s),this.inputsElem_=s,this.inputViews_=e.inputViews,this.applyInputViews_(),kt(e.mode,t=>{this.modeElem_.value=t})}get modeSelectElement(){return this.modeElem_}get inputViews(){return this.inputViews_}set inputViews(t){this.inputViews_=t,this.applyInputViews_()}applyInputViews_(){Pt(this.inputsElem_);const t=this.element.ownerDocument;this.inputViews_.forEach(e=>{const i=t.createElement("div");i.classList.add(Tn("c")),i.appendChild(e.element),this.inputsElem_.appendChild(i)})}};function Rn(t,e,i){const n=Ri(t,e)[i];return new x({min:0,max:n})}var Nn=class{constructor(t,e){this.onModeSelectChange_=this.onModeSelectChange_.bind(this),this.colorType_=e.colorType,this.value=e.value,this.viewProps=e.viewProps,this.colorMode=_(this.value.rawValue.mode),this.ccs_=this.createComponentControllers_(t),this.view=new zn(t,{mode:this.colorMode,inputViews:[this.ccs_[0].view,this.ccs_[1].view,this.ccs_[2].view],viewProps:this.viewProps}),this.view.modeSelectElement.addEventListener("change",this.onModeSelectChange_)}createComponentControllers_(t){const e=this.colorMode.rawValue;return function(t){return"hex"!==t}(e)?function(t,e){const i={colorMode:e.colorMode,colorType:e.colorType,parser:N,viewProps:e.viewProps};return[0,1,2].map(n=>{const s=function(t,e,i){return new ui(t,{arrayPosition:0===i?"fst":2===i?"lst":"mid",parser:e.parser,props:f.fromObject({formatter:(n=e.colorType,U("float"===n?2:0)),keyScale:Gi(!1),pointerScale:"float"===e.colorType?.01:1}),value:_(0,{constraint:Rn(e.colorMode,e.colorType,i)}),viewProps:e.viewProps});var n}(t,i,n);return si({primary:e.value,secondary:s.value,forward:t=>Ji(t,e.colorType).getComponents(e.colorMode)[n],backward(t,i){const s=e.colorMode,r=Ji(t,e.colorType).getComponents(s);return r[n]=i,Ji(Qi(Ti(Bi(r),r[3]),s,e.colorType),"int")}}),s})}(t,{colorMode:e,colorType:this.colorType_,value:this.value,viewProps:this.viewProps}):function(t,e){const i=new Qe(t,{parser:fn("int"),props:f.fromObject({formatter:yn}),value:_(Ui.black()),viewProps:e.viewProps});return si({primary:e.value,secondary:i.value,forward:t=>new Ui(Bi(t.getComponents()),t.mode),backward:(t,e)=>new Ui(Ti(Bi(e.getComponents(t.mode)),t.getComponents()[3]),t.mode)}),[i]}(t,{value:this.value,viewProps:this.viewProps})}onModeSelectChange_(t){const e=t.currentTarget;this.colorMode.rawValue=e.value,this.ccs_=this.createComponentControllers_(this.view.element.ownerDocument),this.view.inputViews=this.ccs_.map(t=>t.view)}},Kn=Mt("hpl"),In=class{constructor(t,e){this.onValueChange_=this.onValueChange_.bind(this),this.value=e.value,this.value.emitter.on("change",this.onValueChange_),this.element=t.createElement("div"),this.element.classList.add(Kn()),e.viewProps.bindClassModifiers(this.element),e.viewProps.bindTabIndex(this.element);const i=t.createElement("div");i.classList.add(Kn("c")),this.element.appendChild(i);const n=t.createElement("div");n.classList.add(Kn("m")),this.element.appendChild(n),this.markerElem_=n,this.update_()}update_(){const[t]=this.value.rawValue.getComponents("hsv");this.markerElem_.style.backgroundColor=En(new Ui([t,100,100],"hsv"));const e=F(t,0,360,0,100);this.markerElem_.style.left=`${e}%`}onValueChange_(){this.update_()}},Un=class{constructor(t,e){this.onKeyDown_=this.onKeyDown_.bind(this),this.onKeyUp_=this.onKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.value=e.value,this.viewProps=e.viewProps,this.view=new In(t,{value:this.value,viewProps:this.viewProps}),this.ptHandler_=new hi(this.view.element),this.ptHandler_.emitter.on("down",this.onPointerDown_),this.ptHandler_.emitter.on("move",this.onPointerMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.element.addEventListener("keydown",this.onKeyDown_),this.view.element.addEventListener("keyup",this.onKeyUp_)}handlePointerEvent_(t,e){if(!t.point)return;const i=F(q(t.point.x,0,t.bounds.width),0,t.bounds.width,0,360),[,n,s,r]=this.value.rawValue.getComponents("hsv");this.value.setRawValue(new Ui([i,n,s,r],"hsv"),e)}onPointerDown_(t){this.handlePointerEvent_(t.data,{forceEmit:!1,last:!1})}onPointerMove_(t){this.handlePointerEvent_(t.data,{forceEmit:!1,last:!1})}onPointerUp_(t){this.handlePointerEvent_(t.data,{forceEmit:!0,last:!0})}onKeyDown_(t){const e=ri(Gi(!1),ai(t));if(0===e)return;const[i,n,s,r]=this.value.rawValue.getComponents("hsv");this.value.setRawValue(new Ui([i+e,n,s,r],"hsv"),{forceEmit:!1,last:!1})}onKeyUp_(t){0!==ri(Gi(!1),ai(t))&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}},Fn=Mt("svp"),$n=class{constructor(t,e){this.onValueChange_=this.onValueChange_.bind(this),this.value=e.value,this.value.emitter.on("change",this.onValueChange_),this.element=t.createElement("div"),this.element.classList.add(Fn()),e.viewProps.bindClassModifiers(this.element),e.viewProps.bindTabIndex(this.element);const i=t.createElement("canvas");i.height=64,i.width=64,i.classList.add(Fn("c")),this.element.appendChild(i),this.canvasElement=i;const n=t.createElement("div");n.classList.add(Fn("m")),this.element.appendChild(n),this.markerElem_=n,this.update_()}update_(){const t=function(t){const e=t.ownerDocument.defaultView;return e&&"document"in e?t.getContext("2d",{willReadFrequently:!0}):null}(this.canvasElement);if(!t)return;const e=this.value.rawValue.getComponents("hsv"),i=this.canvasElement.width,n=this.canvasElement.height,s=t.getImageData(0,0,i,n),r=s.data;for(let l=0;lt.getComponents()[3],backward:(t,e)=>{const i=t.getComponents();return i[3]=e,new Ui(i,t.mode)}}),this.textsC_=new Nn(t,{colorType:e.colorType,value:this.value,viewProps:this.viewProps}),this.view=new $i(t,{alphaViews:this.alphaIcs_?{palette:this.alphaIcs_.palette.view,text:this.alphaIcs_.text.view}:null,hPaletteView:this.hPaletteC_.view,supportsAlpha:e.supportsAlpha,svPaletteView:this.svPaletteC_.view,textsView:this.textsC_.view,viewProps:this.viewProps})}get textsController(){return this.textsC_}},Gn=Mt("colsw"),Yn=class{constructor(t,e){this.onValueChange_=this.onValueChange_.bind(this),e.value.emitter.on("change",this.onValueChange_),this.value=e.value,this.element=t.createElement("div"),this.element.classList.add(Gn()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("div");i.classList.add(Gn("sw")),this.element.appendChild(i),this.swatchElem_=i;const n=t.createElement("button");n.classList.add(Gn("b")),e.viewProps.bindDisabled(n),this.element.appendChild(n),this.buttonElement=n,this.update_()}update_(){const t=this.value.rawValue;this.swatchElem_.style.backgroundColor=Pn(t)}onValueChange_(){this.update_()}},Xn=class{constructor(t,e){this.value=e.value,this.viewProps=e.viewProps,this.view=new Yn(t,{value:this.value,viewProps:this.viewProps})}},Wn=class{constructor(t,e){this.onButtonBlur_=this.onButtonBlur_.bind(this),this.onButtonClick_=this.onButtonClick_.bind(this),this.onPopupChildBlur_=this.onPopupChildBlur_.bind(this),this.onPopupChildKeydown_=this.onPopupChildKeydown_.bind(this),this.value=e.value,this.viewProps=e.viewProps,this.foldable_=he.create(e.expanded),this.swatchC_=new Xn(t,{value:this.value,viewProps:this.viewProps});const i=this.swatchC_.view.buttonElement;i.addEventListener("blur",this.onButtonBlur_),i.addEventListener("click",this.onButtonClick_),this.textC_=new Qe(t,{parser:e.parser,props:f.fromObject({formatter:e.formatter}),value:this.value,viewProps:this.viewProps}),this.view=new Ai(t,{foldable:this.foldable_,pickerLayout:e.pickerLayout}),this.view.swatchElement.appendChild(this.swatchC_.view.element),this.view.textElement.appendChild(this.textC_.view.element),this.popC_="popup"===e.pickerLayout?new Ye(t,{viewProps:this.viewProps}):null;const n=new Hn(t,{colorType:e.colorType,supportsAlpha:e.supportsAlpha,value:this.value,viewProps:this.viewProps});n.view.allFocusableElements.forEach(t=>{t.addEventListener("blur",this.onPopupChildBlur_),t.addEventListener("keydown",this.onPopupChildKeydown_)}),this.pickerC_=n,this.popC_?(this.view.element.appendChild(this.popC_.view.element),this.popC_.view.element.appendChild(n.view.element),si({primary:this.foldable_.value("expanded"),secondary:this.popC_.shows,forward:t=>t,backward:(t,e)=>e})):this.view.pickerElement&&(this.view.pickerElement.appendChild(this.pickerC_.view.element),de(this.foldable_,this.view.pickerElement))}get textController(){return this.textC_}onButtonBlur_(t){if(!this.popC_)return;const e=this.view.element,i=t.relatedTarget;i&&e.contains(i)||(this.popC_.shows.rawValue=!1)}onButtonClick_(){this.foldable_.set("expanded",!this.foldable_.get("expanded")),this.foldable_.get("expanded")&&this.pickerC_.view.allFocusableElements[0].focus()}onPopupChildBlur_(t){if(!this.popC_)return;const e=this.popC_.view.element,i=Et(t);i&&e.contains(i)||i&&i===this.swatchC_.view.buttonElement&&!_t(e.ownerDocument)||(this.popC_.shows.rawValue=!1)}onPopupChildKeydown_(t){this.popC_?"Escape"===t.key&&(this.popC_.shows.rawValue=!1):this.view.pickerElement&&"Escape"===t.key&&this.swatchC_.view.buttonElement.focus()}};function Qn(t){return Bi(t.getComponents("rgb")).reduce((t,e)=>t<<8|255&Math.floor(e),0)}function Jn(t){return t.getComponents("rgb").reduce((t,e,i)=>t<<8|255&Math.floor(3===i?255*e:e),0)>>>0}function Zn(t){return"number"!=typeof t?Ui.black():new Ui([(e=t)>>16&255,e>>8&255,255&e],"rgb");var e}function ts(t){return"number"!=typeof t?Ui.black():new Ui([(e=t)>>24&255,e>>16&255,e>>8&255,F(255&e,0,255,0,1)],"rgb");var e}function es(t,e){return"object"==typeof t&&!o(t)&&e in t&&"number"==typeof t[e]}function is(t){return es(t,"r")&&es(t,"g")&&es(t,"b")}function ns(t){return is(t)&&es(t,"a")}function ss(t){return is(t)}function rs(t,e){if(t.mode!==e.mode)return!1;if(t.type!==e.type)return!1;const i=t.getComponents(),n=e.getComponents();for(let s=0;s{if("number"!=typeof t)return null;if(!function(t){return"color"in t||"color"===t.view}(e))return null;const i=Hi(e);return i?{initialValue:t,params:Object.assign(Object.assign({},i),{supportsAlpha:(n=e,!!(null===(s=null==n?void 0:n.color)||void 0===s?void 0:s.alpha))})}:null;var n,s},binding:{reader:t=>t.params.supportsAlpha?ts:Zn,equals:rs,writer:t=>function(t){const e=t?Jn:Qn;return(t,i)=>{Vi(t,e(i))}}(t.params.supportsAlpha)},controller:t=>{var e,i,n;return new Wn(t.document,{colorType:"int",expanded:null!==(e=t.params.expanded)&&void 0!==e&&e,formatter:(n=t.params.supportsAlpha,n?t=>Pn(t,"0x"):t=>yn(t,"0x")),parser:fn("int"),pickerLayout:null!==(i=t.params.picker)&&void 0!==i?i:"popup",supportsAlpha:t.params.supportsAlpha,value:t.value,viewProps:t.viewProps})}});function ls(t,e){return i=>t?Mn(i,e):Vn(i,e)}var ps=Zt({id:"input-color-object",type:"input",accept:(t,e)=>{var i;if(!ss(t))return null;const n=Hi(e);return n?{initialValue:t,params:Object.assign(Object.assign({},n),{colorType:null!==(i=Yi(e))&&void 0!==i?i:"int"})}:null},binding:{reader:t=>{return e=t.params.colorType,t=>Ji(function(t,e){return ss(t)?"int"===e?new Ui(os(t),"rgb"):"float"===e?new Xi(os(t),"rgb"):Ji(Ui.black(),"int"):Ji(Ui.black(),e)}(t,e),"int");var e},equals:rs,writer:t=>{return e=ns(t.initialValue),i=t.params.colorType,(t,n)=>{e?function(t,e,i){const n=Ji(e,i).toRgbaObject();t.writeProperty("r",n.r),t.writeProperty("g",n.g),t.writeProperty("b",n.b),t.writeProperty("a",n.a)}(t,n,i):function(t,e,i){const n=Ji(e,i).toRgbaObject();t.writeProperty("r",n.r),t.writeProperty("g",n.g),t.writeProperty("b",n.b)}(t,n,i)};var e,i}},controller:t=>{var e,i;const n=ns(t.initialValue);return new Wn(t.document,{colorType:t.params.colorType,expanded:null!==(e=t.params.expanded)&&void 0!==e&&e,formatter:ls(n,t.params.colorType),parser:fn("int"),pickerLayout:null!==(i=t.params.picker)&&void 0!==i?i:"popup",supportsAlpha:n,value:t.value,viewProps:t.viewProps})}}),hs=Zt({id:"input-color-string",type:"input",accept:(t,e)=>{if("string"!=typeof t)return null;if("text"===e.view)return null;const i=function(t,e="int"){const i=function(t){return _n.reduce((e,{parser:i,result:n})=>e||(i(t)?n:null),null)}(t);return i?"hex"===i.notation&&"float"!==e?Object.assign(Object.assign({},i),{type:"int"}):"func"===i.notation?Object.assign(Object.assign({},i),{type:e}):null:null}(t,Yi(e));if(!i)return null;const n=Dn(i);if(!n)return null;const s=Hi(e);return s?{initialValue:t,params:Object.assign(Object.assign({},s),{format:i,stringifier:n})}:null},binding:{reader:()=>xn,equals:rs,writer:t=>{const e=function(t){const e=Dn(t);return e?(t,i)=>{Vi(t,e(i))}:null}(t.params.format);if(!e)throw u.notBindable();return e}},controller:t=>{var e,i;return new Wn(t.document,{colorType:t.params.format.type,expanded:null!==(e=t.params.expanded)&&void 0!==e&&e,formatter:t.params.stringifier,parser:fn("int"),pickerLayout:null!==(i=t.params.picker)&&void 0!==i?i:"popup",supportsAlpha:t.params.format.alpha,value:t.value,viewProps:t.viewProps})}}),cs=class{constructor(t){this.components=t.components,this.asm_=t.assembly}constrain(t){const e=this.asm_.toComponents(t).map((t,e)=>{var i,n;return null!==(n=null===(i=this.components[e])||void 0===i?void 0:i.constrain(t))&&void 0!==n?n:t});return this.asm_.fromComponents(e)}},ds=Mt("pndtxt"),us=class{constructor(t,e){this.textViews=e.textViews,this.element=t.createElement("div"),this.element.classList.add(ds()),this.textViews.forEach(e=>{const i=t.createElement("div");i.classList.add(ds("a")),i.appendChild(e.element),this.element.appendChild(i)})}},vs=class{constructor(t,e){this.value=e.value,this.viewProps=e.viewProps,this.acs_=e.axes.map((i,n)=>function(t,e,i){return new ui(t,{arrayPosition:0===i?"fst":i===e.axes.length-1?"lst":"mid",parser:e.parser,props:e.axes[i].textProps,value:_(0,{constraint:e.axes[i].constraint}),viewProps:e.viewProps})}(t,e,n)),this.acs_.forEach((t,i)=>{si({primary:this.value,secondary:t.value,forward:t=>e.assembly.toComponents(t)[i],backward:(t,n)=>{const s=e.assembly.toComponents(t);return s[i]=n,e.assembly.fromComponents(s)}})}),this.view=new us(t,{textViews:this.acs_.map(t=>t.view)})}get textControllers(){return this.acs_}},ms=class extends at{get max(){return this.controller.valueController.sliderController.props.get("max")}set max(t){this.controller.valueController.sliderController.props.set("max",t)}get min(){return this.controller.valueController.sliderController.props.get("min")}set min(t){this.controller.valueController.sliderController.props.set("min",t)}},bs=Zt({id:"input-number",type:"input",accept:(t,e)=>{if("number"!=typeof t)return null;const i=dt(e,t=>Object.assign(Object.assign({},Z(t)),{options:t.optional.custom(Ke),readonly:t.optional.constant(!1)}));return i?{initialValue:t,params:i}:null},binding:{reader:t=>K,constraint:t=>function(t,e){const i=[],n=W(t,e);n&&i.push(n);const s=Q(t);s&&i.push(s);const r=Ue(t.options);return r&&i.push(r),new ze(i)}(t.params,t.initialValue),writer:t=>Vi},controller:t=>{const e=t.value,i=t.constraint,n=i&&Re(i,Ne);if(n)return new qe(t.document,{props:new f({options:n.values.value("options")}),value:e,viewProps:t.viewProps});const s=J(t.params,e.rawValue),r=i&&Re(i,x);return r?new _i(t.document,Object.assign(Object.assign({},fi(Object.assign(Object.assign({},s),{keyScale:_(s.keyScale),max:r.values.value("max"),min:r.values.value("min")}))),{parser:N,value:e,viewProps:t.viewProps})):new ui(t.document,{parser:N,props:f.fromObject(s),value:e,viewProps:t.viewProps})},api:t=>"number"!=typeof t.controller.value.rawValue?null:t.controller.valueController instanceof _i?new ms(t.controller):t.controller.valueController instanceof qe?new Oe(t.controller):null}),gs=class{constructor(t=0,e=0){this.x=t,this.y=e}getComponents(){return[this.x,this.y]}static isObject(t){if(o(t))return!1;const e=t.x,i=t.y;return"number"==typeof e&&"number"==typeof i}static equals(t,e){return t.x===e.x&&t.y===e.y}toObject(){return{x:this.x,y:this.y}}},ws={toComponents:t=>t.getComponents(),fromComponents:t=>new gs(...t)},_s=Mt("p2d"),fs=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(_s()),e.viewProps.bindClassModifiers(this.element),kt(e.expanded,qt(this.element,_s(void 0,"expanded")));const i=t.createElement("div");i.classList.add(_s("h")),this.element.appendChild(i);const n=t.createElement("button");n.classList.add(_s("b")),n.appendChild(xt(t,"p2dpad")),e.viewProps.bindDisabled(n),i.appendChild(n),this.buttonElement=n;const s=t.createElement("div");if(s.classList.add(_s("t")),i.appendChild(s),this.textElement=s,"inline"===e.pickerLayout){const e=t.createElement("div");e.classList.add(_s("p")),this.element.appendChild(e),this.pickerElement=e}else this.pickerElement=null}},xs=Mt("p2dp"),Cs=class{constructor(t,e){this.onFoldableChange_=this.onFoldableChange_.bind(this),this.onPropsChange_=this.onPropsChange_.bind(this),this.onValueChange_=this.onValueChange_.bind(this),this.props_=e.props,this.props_.emitter.on("change",this.onPropsChange_),this.element=t.createElement("div"),this.element.classList.add(xs()),"popup"===e.layout&&this.element.classList.add(xs(void 0,"p")),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("div");i.classList.add(xs("p")),e.viewProps.bindTabIndex(i),this.element.appendChild(i),this.padElement=i;const n=t.createElementNS(gt,"svg");n.classList.add(xs("g")),this.padElement.appendChild(n),this.svgElem_=n;const s=t.createElementNS(gt,"line");s.classList.add(xs("ax")),s.setAttributeNS(null,"x1","0"),s.setAttributeNS(null,"y1","50%"),s.setAttributeNS(null,"x2","100%"),s.setAttributeNS(null,"y2","50%"),this.svgElem_.appendChild(s);const r=t.createElementNS(gt,"line");r.classList.add(xs("ax")),r.setAttributeNS(null,"x1","50%"),r.setAttributeNS(null,"y1","0"),r.setAttributeNS(null,"x2","50%"),r.setAttributeNS(null,"y2","100%"),this.svgElem_.appendChild(r);const o=t.createElementNS(gt,"line");o.classList.add(xs("l")),o.setAttributeNS(null,"x1","50%"),o.setAttributeNS(null,"y1","50%"),this.svgElem_.appendChild(o),this.lineElem_=o;const a=t.createElement("div");a.classList.add(xs("m")),this.padElement.appendChild(a),this.markerElem_=a,e.value.emitter.on("change",this.onValueChange_),this.value=e.value,this.update_()}get allFocusableElements(){return[this.padElement]}update_(){const[t,e]=this.value.rawValue.getComponents(),i=this.props_.get("max"),n=F(t,-i,+i,0,100),s=F(e,-i,+i,0,100),r=this.props_.get("invertsY")?100-s:s;this.lineElem_.setAttributeNS(null,"x2",`${n}%`),this.lineElem_.setAttributeNS(null,"y2",`${r}%`),this.markerElem_.style.left=`${n}%`,this.markerElem_.style.top=`${r}%`}onValueChange_(){this.update_()}onPropsChange_(){this.update_()}onFoldableChange_(){this.update_()}};function ys(t,e,i){return[ri(e[0],ai(t)),ri(e[1],oi(t))*(i?1:-1)]}var Ps=class{constructor(t,e){this.onPadKeyDown_=this.onPadKeyDown_.bind(this),this.onPadKeyUp_=this.onPadKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.props=e.props,this.value=e.value,this.viewProps=e.viewProps,this.view=new Cs(t,{layout:e.layout,props:this.props,value:this.value,viewProps:this.viewProps}),this.ptHandler_=new hi(this.view.padElement),this.ptHandler_.emitter.on("down",this.onPointerDown_),this.ptHandler_.emitter.on("move",this.onPointerMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.padElement.addEventListener("keydown",this.onPadKeyDown_),this.view.padElement.addEventListener("keyup",this.onPadKeyUp_)}handlePointerEvent_(t,e){if(!t.point)return;const i=this.props.get("max"),n=F(t.point.x,0,t.bounds.width,-i,+i),s=F(this.props.get("invertsY")?t.bounds.height-t.point.y:t.point.y,0,t.bounds.height,-i,+i);this.value.setRawValue(new gs(n,s),e)}onPointerDown_(t){this.handlePointerEvent_(t.data,{forceEmit:!1,last:!1})}onPointerMove_(t){this.handlePointerEvent_(t.data,{forceEmit:!1,last:!1})}onPointerUp_(t){this.handlePointerEvent_(t.data,{forceEmit:!0,last:!0})}onPadKeyDown_(t){li(t.key)&&t.preventDefault();const[e,i]=ys(t,[this.props.get("xKeyScale"),this.props.get("yKeyScale")],this.props.get("invertsY"));0===e&&0===i||this.value.setRawValue(new gs(this.value.rawValue.x+e,this.value.rawValue.y+i),{forceEmit:!1,last:!1})}onPadKeyUp_(t){const[e,i]=ys(t,[this.props.get("xKeyScale"),this.props.get("yKeyScale")],this.props.get("invertsY"));0===e&&0===i||this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}},Es=class{constructor(t,e){var i,n;this.onPopupChildBlur_=this.onPopupChildBlur_.bind(this),this.onPopupChildKeydown_=this.onPopupChildKeydown_.bind(this),this.onPadButtonBlur_=this.onPadButtonBlur_.bind(this),this.onPadButtonClick_=this.onPadButtonClick_.bind(this),this.value=e.value,this.viewProps=e.viewProps,this.foldable_=he.create(e.expanded),this.popC_="popup"===e.pickerLayout?new Ye(t,{viewProps:this.viewProps}):null;const s=new Ps(t,{layout:e.pickerLayout,props:new f({invertsY:_(e.invertsY),max:_(e.max),xKeyScale:e.axes[0].textProps.value("keyScale"),yKeyScale:e.axes[1].textProps.value("keyScale")}),value:this.value,viewProps:this.viewProps});s.view.allFocusableElements.forEach(t=>{t.addEventListener("blur",this.onPopupChildBlur_),t.addEventListener("keydown",this.onPopupChildKeydown_)}),this.pickerC_=s,this.textC_=new vs(t,{assembly:ws,axes:e.axes,parser:e.parser,value:this.value,viewProps:this.viewProps}),this.view=new fs(t,{expanded:this.foldable_.value("expanded"),pickerLayout:e.pickerLayout,viewProps:this.viewProps}),this.view.textElement.appendChild(this.textC_.view.element),null===(i=this.view.buttonElement)||void 0===i||i.addEventListener("blur",this.onPadButtonBlur_),null===(n=this.view.buttonElement)||void 0===n||n.addEventListener("click",this.onPadButtonClick_),this.popC_?(this.view.element.appendChild(this.popC_.view.element),this.popC_.view.element.appendChild(this.pickerC_.view.element),si({primary:this.foldable_.value("expanded"),secondary:this.popC_.shows,forward:t=>t,backward:(t,e)=>e})):this.view.pickerElement&&(this.view.pickerElement.appendChild(this.pickerC_.view.element),de(this.foldable_,this.view.pickerElement))}get textController(){return this.textC_}onPadButtonBlur_(t){if(!this.popC_)return;const e=this.view.element,i=t.relatedTarget;i&&e.contains(i)||(this.popC_.shows.rawValue=!1)}onPadButtonClick_(){this.foldable_.set("expanded",!this.foldable_.get("expanded")),this.foldable_.get("expanded")&&this.pickerC_.view.allFocusableElements[0].focus()}onPopupChildBlur_(t){if(!this.popC_)return;const e=this.popC_.view.element,i=Et(t);i&&e.contains(i)||i&&i===this.view.buttonElement&&!_t(e.ownerDocument)||(this.popC_.shows.rawValue=!1)}onPopupChildKeydown_(t){this.popC_?"Escape"===t.key&&(this.popC_.shows.rawValue=!1):this.view.pickerElement&&"Escape"===t.key&&this.view.buttonElement.focus()}};function ks(t){return gs.isObject(t)?new gs(t.x,t.y):new gs}function Vs(t,e){t.writeProperty("x",e.x),t.writeProperty("y",e.y)}function Ls(t,e){var i,n;if(!o(t.min)||!o(t.max))return Math.max(Math.abs(null!==(i=t.min)&&void 0!==i?i:0),Math.abs(null!==(n=t.max)&&void 0!==n?n:0));const s=Y(t);return Math.max(10*Math.abs(s),10*Math.abs(e))}function Ms(t,e){var i,n;const s=Ls(h(t,null!==(i=t.x)&&void 0!==i?i:{}),e.x),r=Ls(h(t,null!==(n=t.y)&&void 0!==n?n:{}),e.y);return Math.max(s,r)}function Ss(t){if(!("y"in t))return!1;const e=t.y;return!!e&&"inverted"in e&&!!e.inverted}var js=Zt({id:"input-point2d",type:"input",accept:(t,e)=>{if(!gs.isObject(t))return null;const i=dt(e,t=>Object.assign(Object.assign({},yi(t)),{expanded:t.optional.boolean,picker:t.optional.custom(ki),readonly:t.optional.constant(!1),x:t.optional.custom(Pi),y:t.optional.object(Object.assign(Object.assign({},yi(t)),{inverted:t.optional.boolean}))}));return i?{initialValue:t,params:i}:null},binding:{reader:()=>ks,constraint:t=>{return e=t.params,i=t.initialValue,new cs({assembly:ws,components:[Ei(Object.assign(Object.assign({},e),e.x),i.x),Ei(Object.assign(Object.assign({},e),e.y),i.y)]});var e,i},equals:gs.equals,writer:()=>Vs},controller:t=>{var e,i;const n=t.document,s=t.value,r=t.constraint,o=[t.params.x,t.params.y];return new Es(n,{axes:s.rawValue.getComponents().map((e,i)=>{var n;return tt({constraint:r.components[i],initialValue:e,params:h(t.params,null!==(n=o[i])&&void 0!==n?n:{})})}),expanded:null!==(e=t.params.expanded)&&void 0!==e&&e,invertsY:Ss(t.params),max:Ms(t.params,s.rawValue),parser:N,pickerLayout:null!==(i=t.params.picker)&&void 0!==i?i:"popup",value:s,viewProps:t.viewProps})}}),Ds=class{constructor(t=0,e=0,i=0){this.x=t,this.y=e,this.z=i}getComponents(){return[this.x,this.y,this.z]}static isObject(t){if(o(t))return!1;const e=t.x,i=t.y,n=t.z;return"number"==typeof e&&"number"==typeof i&&"number"==typeof n}static equals(t,e){return t.x===e.x&&t.y===e.y&&t.z===e.z}toObject(){return{x:this.x,y:this.y,z:this.z}}},As={toComponents:t=>t.getComponents(),fromComponents:t=>new Ds(...t)};function Os(t){return Ds.isObject(t)?new Ds(t.x,t.y,t.z):new Ds}function Bs(t,e){t.writeProperty("x",e.x),t.writeProperty("y",e.y),t.writeProperty("z",e.z)}var Ts=Zt({id:"input-point3d",type:"input",accept:(t,e)=>{if(!Ds.isObject(t))return null;const i=dt(e,t=>Object.assign(Object.assign({},yi(t)),{readonly:t.optional.constant(!1),x:t.optional.custom(Pi),y:t.optional.custom(Pi),z:t.optional.custom(Pi)}));return i?{initialValue:t,params:i}:null},binding:{reader:t=>Os,constraint:t=>{return e=t.params,i=t.initialValue,new cs({assembly:As,components:[Ei(Object.assign(Object.assign({},e),e.x),i.x),Ei(Object.assign(Object.assign({},e),e.y),i.y),Ei(Object.assign(Object.assign({},e),e.z),i.z)]});var e,i},equals:Ds.equals,writer:t=>Bs},controller:t=>{const e=t.value,i=t.constraint,n=[t.params.x,t.params.y,t.params.z];return new vs(t.document,{assembly:As,axes:e.rawValue.getComponents().map((e,s)=>{var r;return tt({constraint:i.components[s],initialValue:e,params:h(t.params,null!==(r=n[s])&&void 0!==r?r:{})})}),parser:N,value:e,viewProps:t.viewProps})}}),zs=class{constructor(t=0,e=0,i=0,n=0){this.x=t,this.y=e,this.z=i,this.w=n}getComponents(){return[this.x,this.y,this.z,this.w]}static isObject(t){if(o(t))return!1;const e=t.x,i=t.y,n=t.z,s=t.w;return"number"==typeof e&&"number"==typeof i&&"number"==typeof n&&"number"==typeof s}static equals(t,e){return t.x===e.x&&t.y===e.y&&t.z===e.z&&t.w===e.w}toObject(){return{x:this.x,y:this.y,z:this.z,w:this.w}}},Rs={toComponents:t=>t.getComponents(),fromComponents:t=>new zs(...t)};function Ns(t){return zs.isObject(t)?new zs(t.x,t.y,t.z,t.w):new zs}function Ks(t,e){t.writeProperty("x",e.x),t.writeProperty("y",e.y),t.writeProperty("z",e.z),t.writeProperty("w",e.w)}var Is=Zt({id:"input-point4d",type:"input",accept:(t,e)=>{if(!zs.isObject(t))return null;const i=dt(e,t=>Object.assign(Object.assign({},yi(t)),{readonly:t.optional.constant(!1),w:t.optional.custom(Pi),x:t.optional.custom(Pi),y:t.optional.custom(Pi),z:t.optional.custom(Pi)}));return i?{initialValue:t,params:i}:null},binding:{reader:t=>Ns,constraint:t=>{return e=t.params,i=t.initialValue,new cs({assembly:Rs,components:[Ei(Object.assign(Object.assign({},e),e.x),i.x),Ei(Object.assign(Object.assign({},e),e.y),i.y),Ei(Object.assign(Object.assign({},e),e.z),i.z),Ei(Object.assign(Object.assign({},e),e.w),i.w)]});var e,i},equals:zs.equals,writer:t=>Ks},controller:t=>{const e=t.value,i=t.constraint,n=[t.params.x,t.params.y,t.params.z,t.params.w];return new vs(t.document,{assembly:Rs,axes:e.rawValue.getComponents().map((e,s)=>{var r;return tt({constraint:i.components[s],initialValue:e,params:h(t.params,null!==(r=n[s])&&void 0!==r?r:{})})}),parser:N,value:e,viewProps:t.viewProps})}}),Us=Zt({id:"input-string",type:"input",accept:(t,e)=>{if("string"!=typeof t)return null;const i=dt(e,t=>({readonly:t.optional.constant(!1),options:t.optional.custom(Ke)}));return i?{initialValue:t,params:i}:null},binding:{reader:t=>ii,constraint:t=>function(t){const e=[],i=Ue(t.options);return i&&e.push(i),new ze(e)}(t.params),writer:t=>Vi},controller:t=>{const e=t.document,i=t.value,n=t.constraint,s=n&&Re(n,Ne);return s?new qe(e,{props:new f({options:s.values.value("options")}),value:i,viewProps:t.viewProps}):new Qe(e,{parser:t=>t,props:f.fromObject({formatter:ni}),value:i,viewProps:t.viewProps})},api:t=>"string"!=typeof t.controller.value.rawValue?null:t.controller.valueController instanceof qe?new Oe(t.controller):null}),Fs=200,$s=3,qs=Mt("mll"),Hs=class{constructor(t,e){this.onValueUpdate_=this.onValueUpdate_.bind(this),this.formatter_=e.formatter,this.element=t.createElement("div"),this.element.classList.add(qs()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("textarea");i.classList.add(qs("i")),i.style.height=`calc(var(${Ci("containerUnitSize")}) * ${e.rows})`,i.readOnly=!0,e.viewProps.bindDisabled(i),this.element.appendChild(i),this.textareaElem_=i,e.value.emitter.on("change",this.onValueUpdate_),this.value=e.value,this.update_()}update_(){const t=this.textareaElem_,e=t.scrollTop===t.scrollHeight-t.clientHeight,i=[];this.value.rawValue.forEach(t=>{void 0!==t&&i.push(this.formatter_(t))}),t.textContent=i.join("\n"),e&&(t.scrollTop=t.scrollHeight)}onValueUpdate_(){this.update_()}},Gs=class{constructor(t,e){this.value=e.value,this.viewProps=e.viewProps,this.view=new Hs(t,{formatter:e.formatter,rows:e.rows,value:this.value,viewProps:this.viewProps})}},Ys=Mt("sgl"),Xs=class{constructor(t,e){this.onValueUpdate_=this.onValueUpdate_.bind(this),this.formatter_=e.formatter,this.element=t.createElement("div"),this.element.classList.add(Ys()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("input");i.classList.add(Ys("i")),i.readOnly=!0,i.type="text",e.viewProps.bindDisabled(i),this.element.appendChild(i),this.inputElement=i,e.value.emitter.on("change",this.onValueUpdate_),this.value=e.value,this.update_()}update_(){const t=this.value.rawValue,e=t[t.length-1];this.inputElement.value=void 0!==e?this.formatter_(e):""}onValueUpdate_(){this.update_()}},Ws=class{constructor(t,e){this.value=e.value,this.viewProps=e.viewProps,this.view=new Xs(t,{formatter:e.formatter,value:this.value,viewProps:this.viewProps})}},Qs=Zt({id:"monitor-bool",type:"monitor",accept:(t,e)=>{if("boolean"!=typeof t)return null;const i=dt(e,t=>({readonly:t.required.constant(!0),rows:t.optional.number}));return i?{initialValue:t,params:i}:null},binding:{reader:t=>Je},controller:t=>{var e;return 1===t.value.rawValue.length?new Ws(t.document,{formatter:Ze,value:t.value,viewProps:t.viewProps}):new Gs(t.document,{formatter:Ze,rows:null!==(e=t.params.rows)&&void 0!==e?e:$s,value:t.value,viewProps:t.viewProps})}}),Js=class extends at{get max(){return this.controller.valueController.props.get("max")}set max(t){this.controller.valueController.props.set("max",t)}get min(){return this.controller.valueController.props.get("min")}set min(t){this.controller.valueController.props.set("min",t)}},Zs=Mt("grl"),tr=class{constructor(t,e){this.onCursorChange_=this.onCursorChange_.bind(this),this.onValueUpdate_=this.onValueUpdate_.bind(this),this.element=t.createElement("div"),this.element.classList.add(Zs()),e.viewProps.bindClassModifiers(this.element),this.formatter_=e.formatter,this.props_=e.props,this.cursor_=e.cursor,this.cursor_.emitter.on("change",this.onCursorChange_);const i=t.createElementNS(gt,"svg");i.classList.add(Zs("g")),i.style.height=`calc(var(${Ci("containerUnitSize")}) * ${e.rows})`,this.element.appendChild(i),this.svgElem_=i;const n=t.createElementNS(gt,"polyline");this.svgElem_.appendChild(n),this.lineElem_=n;const s=t.createElement("div");s.classList.add(Zs("t"),Mt("tt")()),this.element.appendChild(s),this.tooltipElem_=s,e.value.emitter.on("change",this.onValueUpdate_),this.value=e.value,this.update_()}get graphElement(){return this.svgElem_}update_(){const{clientWidth:t,clientHeight:e}=this.element,i=this.value.rawValue.length-1,n=this.props_.get("min"),s=this.props_.get("max"),r=[];this.value.rawValue.forEach((o,a)=>{if(void 0===o)return;const l=F(a,0,i,0,t),p=F(o,n,s,e,0);r.push([l,p].join(","))}),this.lineElem_.setAttributeNS(null,"points",r.join(" "));const o=this.tooltipElem_,a=this.value.rawValue[this.cursor_.rawValue];if(void 0===a)return void o.classList.remove(Zs("t","a"));const l=F(this.cursor_.rawValue,0,i,0,t),p=F(a,n,s,e,0);o.style.left=`${l}px`,o.style.top=`${p}px`,o.textContent=`${this.formatter_(a)}`,o.classList.contains(Zs("t","a"))||(o.classList.add(Zs("t","a"),Zs("t","in")),wt(o),o.classList.remove(Zs("t","in")))}onValueUpdate_(){this.update_()}onCursorChange_(){this.update_()}},er=class{constructor(t,e){if(this.onGraphMouseMove_=this.onGraphMouseMove_.bind(this),this.onGraphMouseLeave_=this.onGraphMouseLeave_.bind(this),this.onGraphPointerDown_=this.onGraphPointerDown_.bind(this),this.onGraphPointerMove_=this.onGraphPointerMove_.bind(this),this.onGraphPointerUp_=this.onGraphPointerUp_.bind(this),this.props=e.props,this.value=e.value,this.viewProps=e.viewProps,this.cursor_=_(-1),this.view=new tr(t,{cursor:this.cursor_,formatter:e.formatter,rows:e.rows,props:this.props,value:this.value,viewProps:this.viewProps}),_t(t)){const t=new hi(this.view.element);t.emitter.on("down",this.onGraphPointerDown_),t.emitter.on("move",this.onGraphPointerMove_),t.emitter.on("up",this.onGraphPointerUp_)}else this.view.element.addEventListener("mousemove",this.onGraphMouseMove_),this.view.element.addEventListener("mouseleave",this.onGraphMouseLeave_)}importProps(t){return ut(t,null,t=>({max:t.required.number,min:t.required.number}),t=>(this.props.set("max",t.max),this.props.set("min",t.min),!0))}exportProps(){return vt(null,{max:this.props.get("max"),min:this.props.get("min")})}onGraphMouseLeave_(){this.cursor_.rawValue=-1}onGraphMouseMove_(t){const{clientWidth:e}=this.view.element;this.cursor_.rawValue=Math.floor(F(t.offsetX,0,e,0,this.value.rawValue.length))}onGraphPointerDown_(t){this.onGraphPointerMove_(t)}onGraphPointerMove_(t){t.data.point?this.cursor_.rawValue=Math.floor(F(t.data.point.x,0,t.data.bounds.width,0,this.value.rawValue.length)):this.cursor_.rawValue=-1}onGraphPointerUp_(){this.cursor_.rawValue=-1}};function ir(t){return o(t.format)?U(2):t.format}function nr(t){return"graph"===t.view}var sr=Zt({id:"monitor-number",type:"monitor",accept:(t,e)=>{if("number"!=typeof t)return null;const i=dt(e,t=>({format:t.optional.function,max:t.optional.number,min:t.optional.number,readonly:t.required.constant(!0),rows:t.optional.number,view:t.optional.string}));return i?{initialValue:t,params:i}:null},binding:{defaultBufferSize:t=>nr(t)?64:1,reader:t=>K},controller:t=>nr(t.params)?function(t){var e,i,n;return new er(t.document,{formatter:ir(t.params),rows:null!==(e=t.params.rows)&&void 0!==e?e:$s,props:f.fromObject({max:null!==(i=t.params.max)&&void 0!==i?i:100,min:null!==(n=t.params.min)&&void 0!==n?n:0}),value:t.value,viewProps:t.viewProps})}(t):function(t){var e;return 1===t.value.rawValue.length?new Ws(t.document,{formatter:ir(t.params),value:t.value,viewProps:t.viewProps}):new Gs(t.document,{formatter:ir(t.params),rows:null!==(e=t.params.rows)&&void 0!==e?e:$s,value:t.value,viewProps:t.viewProps})}(t),api:t=>t.controller.valueController instanceof er?new Js(t.controller):null}),rr=Zt({id:"monitor-string",type:"monitor",accept:(t,e)=>{if("string"!=typeof t)return null;const i=dt(e,t=>({multiline:t.optional.boolean,readonly:t.required.constant(!0),rows:t.optional.number}));return i?{initialValue:t,params:i}:null},binding:{reader:t=>ii},controller:t=>{var e;const i=t.value;return i.rawValue.length>1||t.params.multiline?new Gs(t.document,{formatter:ni,rows:null!==(e=t.params.rows)&&void 0!==e?e:$s,value:i,viewProps:t.viewProps}):new Ws(t.document,{formatter:ni,value:i,viewProps:t.viewProps})}}),or=class{constructor(t){this.target=t.target,this.reader_=t.reader,this.writer_=t.writer}read(){return this.reader_(this.target.read())}write(t){this.writer_(this.target,t)}inject(t){this.write(this.reader_(t))}},ar=class{constructor(t){this.target=t.target,this.reader_=t.reader}read(){return this.reader_(this.target.read())}},lr=class{constructor(t){this.pluginsMap_={blades:[],inputs:[],monitors:[]},this.apiCache_=t}getAll(){return[...this.pluginsMap_.blades,...this.pluginsMap_.inputs,...this.pluginsMap_.monitors]}register(t,e){if(!(i=e.core)||i.major!==Jt.major)throw u.notCompatible(t,e.id);var i;"blade"===e.type?this.pluginsMap_.blades.unshift(e):"input"===e.type?this.pluginsMap_.inputs.unshift(e):"monitor"===e.type&&this.pluginsMap_.monitors.unshift(e)}createInput_(t,e,i){return this.pluginsMap_.inputs.reduce((n,s)=>null!=n?n:function(t,e){var i;const n=t.accept(e.target.read(),e.params);if(o(n))return null;const s={target:e.target,initialValue:n.initialValue,params:n.params},r=dt(e.params,t=>({disabled:t.optional.boolean,hidden:t.optional.boolean,label:t.optional.string,tag:t.optional.string})),a=t.binding.reader(s),l=t.binding.constraint?t.binding.constraint(s):void 0,p=new or({reader:a,target:e.target,writer:t.binding.writer(s)}),h=new lt(_(a(n.initialValue),{constraint:l,equals:t.binding.equals}),p),c=t.controller({constraint:l,document:e.document,initialValue:n.initialValue,params:n.params,value:h,viewProps:fe.create({disabled:null==r?void 0:r.disabled,hidden:null==r?void 0:r.hidden})});return new Nt(e.document,{blade:pe(),props:f.fromObject({label:"label"in e.params?null!==(i=null==r?void 0:r.label)&&void 0!==i?i:null:e.target.key}),tag:null==r?void 0:r.tag,value:h,valueController:c})}(s,{document:t,target:e,params:i}),null)}createMonitor_(t,e,i){return this.pluginsMap_.monitors.reduce((n,s)=>null!=n?n:function(t,e){var i,n,s;const r=t.accept(e.target.read(),e.params);if(o(r))return null;const a={target:e.target,initialValue:r.initialValue,params:r.params},l=dt(e.params,t=>({bufferSize:t.optional.number,disabled:t.optional.boolean,hidden:t.optional.boolean,interval:t.optional.number,label:t.optional.string})),p=t.binding.reader(a),h=null!==(n=null!==(i=null==l?void 0:l.bufferSize)&&void 0!==i?i:t.binding.defaultBufferSize&&t.binding.defaultBufferSize(r.params))&&void 0!==n?n:1,c=new Ut({binding:new ar({reader:p,target:e.target}),bufferSize:h,ticker:(d=e.document,u=null==l?void 0:l.interval,0===u?new Be:new Te(d,null!=u?u:Fs))});var d,u;const v=t.controller({document:e.document,params:r.params,value:c,viewProps:fe.create({disabled:null==l?void 0:l.disabled,hidden:null==l?void 0:l.hidden})});return v.viewProps.bindDisabled(c.ticker),v.viewProps.handleDispose(()=>{c.ticker.dispose()}),new Ft(e.document,{blade:pe(),props:f.fromObject({label:"label"in e.params?null!==(s=null==l?void 0:l.label)&&void 0!==s?s:null:e.target.key}),value:c,valueController:v})}(s,{document:t,params:i,target:e}),null)}createBinding(t,e,i){if(o(e.read()))throw new u({context:{key:e.key},type:"nomatchingcontroller"});const n=this.createInput_(t,e,i);if(n)return n;const s=this.createMonitor_(t,e,i);if(s)return s;throw new u({context:{key:e.key},type:"nomatchingcontroller"})}createBlade(t,e){const i=this.pluginsMap_.blades.reduce((i,n)=>null!=i?i:function(t,e){const i=t.accept(e.params);if(!i)return null;const n=dt(e.params,t=>({disabled:t.optional.boolean,hidden:t.optional.boolean}));return t.controller({blade:pe(),document:e.document,params:Object.assign(Object.assign({},i.params),{disabled:null==n?void 0:n.disabled,hidden:null==n?void 0:n.hidden}),viewProps:fe.create({disabled:null==n?void 0:n.disabled,hidden:null==n?void 0:n.hidden})})}(n,{document:t,params:e}),null);if(!i)throw new u({type:"nomatchingview",context:{params:e}});return i}createInputBindingApi_(t){const e=this.pluginsMap_.inputs.reduce((e,i)=>{var n,s;return e||(null!==(s=null===(n=i.api)||void 0===n?void 0:n.call(i,{controller:t}))&&void 0!==s?s:null)},null);return this.apiCache_.add(t,null!=e?e:new at(t))}createMonitorBindingApi_(t){const e=this.pluginsMap_.monitors.reduce((e,i)=>{var n,s;return e||(null!==(s=null===(n=i.api)||void 0===n?void 0:n.call(i,{controller:t}))&&void 0!==s?s:null)},null);return this.apiCache_.add(t,null!=e?e:new at(t))}createBindingApi(t){if(this.apiCache_.has(t))return this.apiCache_.get(t);if(function(t){return mt(t)&&function(t){if(!("binding"in t))return!1;const e=t.binding;return c(e)&&"read"in e&&"write"in e}(t.value)}(t))return this.createInputBindingApi_(t);if(function(t){return mt(t)&&function(t){if(!("binding"in t))return!1;const e=t.binding;return c(e)&&"read"in e&&!("write"in e)}(t.value)}(t))return this.createMonitorBindingApi_(t);throw u.shouldNeverHappen()}createApi(t){if(this.apiCache_.has(t))return this.apiCache_.get(t);if(function(t){return mt(t)&&bt(t.value)}(t))return this.createBindingApi(t);const e=this.pluginsMap_.blades.reduce((e,i)=>null!=e?e:i.api({controller:t,pool:this}),null);if(!e)throw u.shouldNeverHappen();return this.apiCache_.add(t,e)}},pr=new class{constructor(){this.map_=new Map}get(t){var e;return null!==(e=this.map_.get(t))&&void 0!==e?e:null}has(t){return this.map_.has(t)}add(t,e){return this.map_.set(t,e),t.viewProps.handleDispose(()=>{this.map_.delete(t)}),e}},hr=class extends et{constructor(t){super(t),this.emitter_=new m,this.controller.value.emitter.on("change",t=>{this.emitter_.emit("change",new nt(this,t.rawValue))})}get label(){return this.controller.labelController.props.get("label")}set label(t){this.controller.labelController.props.set("label",t)}get options(){return this.controller.valueController.props.get("options")}set options(t){this.controller.valueController.props.set("options",t)}get value(){return this.controller.value.rawValue}set value(t){this.controller.value.rawValue=t}on(t,e){const i=e.bind(this);return this.emitter_.on(t,t=>{i(t)},{key:e}),this}off(t,e){return this.emitter_.off(t,e),this}},cr=class extends et{},dr=class extends et{constructor(t){super(t),this.emitter_=new m,this.controller.value.emitter.on("change",t=>{this.emitter_.emit("change",new nt(this,t.rawValue))})}get label(){return this.controller.labelController.props.get("label")}set label(t){this.controller.labelController.props.set("label",t)}get max(){return this.controller.valueController.sliderController.props.get("max")}set max(t){this.controller.valueController.sliderController.props.set("max",t)}get min(){return this.controller.valueController.sliderController.props.get("min")}set min(t){this.controller.valueController.sliderController.props.set("min",t)}get value(){return this.controller.value.rawValue}set value(t){this.controller.value.rawValue=t}on(t,e){const i=e.bind(this);return this.emitter_.on(t,t=>{i(t)},{key:e}),this}off(t,e){return this.emitter_.off(t,e),this}},ur=class extends et{constructor(t){super(t),this.emitter_=new m,this.controller.value.emitter.on("change",t=>{this.emitter_.emit("change",new nt(this,t.rawValue))})}get label(){return this.controller.labelController.props.get("label")}set label(t){this.controller.labelController.props.set("label",t)}get formatter(){return this.controller.valueController.props.get("formatter")}set formatter(t){this.controller.valueController.props.set("formatter",t)}get value(){return this.controller.value.rawValue}set value(t){this.controller.value.rawValue=t}on(t,e){const i=e.bind(this);return this.emitter_.on(t,t=>{i(t)},{key:e}),this}off(t,e){return this.emitter_.off(t,e),this}},vr={id:"list",type:"blade",core:Jt,accept(t){const e=dt(t,t=>({options:t.required.custom(Ke),value:t.required.raw,view:t.required.constant("list"),label:t.optional.string}));return e?{params:e}:null},controller(t){const e=new Ne(Ie(t.params.options)),i=_(t.params.value,{constraint:e}),n=new qe(t.document,{props:new f({options:e.values.value("options")}),value:i,viewProps:t.viewProps});return new Tt(t.document,{blade:t.blade,props:f.fromObject({label:t.params.label}),value:i,valueController:n})},api:t=>t.controller instanceof Tt&&t.controller.valueController instanceof qe?new hr(t.controller):null},mr=class extends ue{constructor(t,e){super(t,e)}get element(){return this.controller.view.element}},br=class extends be{constructor(t,e){super(t,{expanded:e.expanded,blade:e.blade,props:e.props,root:!0,viewProps:e.viewProps})}},gr=Mt("spr"),wr=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(gr()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("hr");i.classList.add(gr("r")),this.element.appendChild(i)}},_r=class extends Bt{constructor(t,e){super(Object.assign(Object.assign({},e),{view:new wr(t,{viewProps:e.viewProps})}))}},fr={id:"separator",type:"blade",core:Jt,accept(t){const e=dt(t,t=>({view:t.required.constant("separator")}));return e?{params:e}:null},controller:t=>new _r(t.document,{blade:t.blade,viewProps:t.viewProps}),api:t=>t.controller instanceof _r?new cr(t.controller):null},xr={id:"slider",type:"blade",core:Jt,accept(t){const e=dt(t,t=>({max:t.required.number,min:t.required.number,view:t.required.constant("slider"),format:t.optional.function,label:t.optional.string,value:t.optional.number}));return e?{params:e}:null},controller(t){var e,i;const n=null!==(e=t.params.value)&&void 0!==e?e:0,s=new x({max:t.params.max,min:t.params.min}),r=_(n,{constraint:s}),o=new _i(t.document,Object.assign(Object.assign({},fi({formatter:null!==(i=t.params.format)&&void 0!==i?i:I,keyScale:_(1),max:s.values.value("max"),min:s.values.value("min"),pointerScale:X(t.params,n)})),{parser:N,value:r,viewProps:t.viewProps}));return new Tt(t.document,{blade:t.blade,props:f.fromObject({label:t.params.label}),value:r,valueController:o})},api:t=>t.controller instanceof Tt&&t.controller.valueController instanceof _i?new dr(t.controller):null},Cr={id:"text",type:"blade",core:Jt,accept(t){const e=dt(t,t=>({parse:t.required.function,value:t.required.raw,view:t.required.constant("text"),format:t.optional.function,label:t.optional.string}));return e?{params:e}:null},controller(t){var e;const i=_(t.params.value),n=new Qe(t.document,{parser:t.params.parse,props:f.fromObject({formatter:null!==(e=t.params.format)&&void 0!==e?e:t=>String(t)}),value:i,viewProps:t.viewProps});return new Tt(t.document,{blade:t.blade,props:f.fromObject({label:t.params.label}),value:i,valueController:n})},api:t=>t.controller instanceof Tt&&t.controller.valueController instanceof Qe?new ur(t.controller):null},yr=class extends mr{constructor(t){var e,i;const n=null!=t?t:{},s=null!==(e=n.document)&&void 0!==e?e:globalThis.document,r=function(){const t=new lr(pr);return[js,Ts,Is,Us,bs,hs,ps,as,ji,Qs,rr,sr,te,ge,Ae].forEach(e=>{t.register("core",e)}),t}();super(new br(s,{expanded:n.expanded,blade:pe(),props:f.fromObject({title:n.title}),viewProps:fe.create()}),r),this.pool_=r,this.containerElem_=null!==(i=n.container)&&void 0!==i?i:function(t){const e=t.createElement("div");return e.classList.add(Mt("dfw")()),t.body&&t.body.appendChild(e),e}(s),this.containerElem_.appendChild(this.element),this.doc_=s,this.usesDefaultWrapper_=!n.container,this.setUpDefaultPlugins_()}get document(){if(!this.doc_)throw u.alreadyDisposed();return this.doc_}dispose(){const t=this.containerElem_;if(!t)throw u.alreadyDisposed();if(this.usesDefaultWrapper_){const e=t.parentElement;e&&e.removeChild(t)}this.containerElem_=null,this.doc_=null,super.dispose()}registerPlugin(t){t.css&&function(t,e,i){if(t.querySelector(`style[data-tp-style=${e}]`))return;const n=t.createElement("style");n.dataset.tpStyle=e,n.textContent=i,t.head.appendChild(n)}(this.document,`plugin-${t.id}`,t.css),("plugin"in t?[t.plugin]:"plugins"in t?t.plugins:[]).forEach(e=>{this.pool_.register(t.id,e)})}setUpDefaultPlugins_(){this.registerPlugin({id:"default",css:'.tp-tbiv_b,.tp-coltxtv_ms,.tp-colswv_b,.tp-ckbv_i,.tp-sglv_i,.tp-mllv_i,.tp-grlv_g,.tp-txtv_i,.tp-p2dpv_p,.tp-colswv_sw,.tp-rotv_b,.tp-fldv_b,.tp-p2dv_b,.tp-btnv_b,.tp-lstv_s{-webkit-appearance:none;-moz-appearance:none;appearance:none;background-color:rgba(0,0,0,0);border-width:0;font-family:inherit;font-size:inherit;font-weight:inherit;margin:0;outline:none;padding:0}.tp-p2dv_b,.tp-btnv_b,.tp-lstv_s{background-color:var(--btn-bg);border-radius:var(--bld-br);color:var(--btn-fg);cursor:pointer;display:block;font-weight:bold;height:var(--cnt-usz);line-height:var(--cnt-usz);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.tp-p2dv_b:hover,.tp-btnv_b:hover,.tp-lstv_s:hover{background-color:var(--btn-bg-h)}.tp-p2dv_b:focus,.tp-btnv_b:focus,.tp-lstv_s:focus{background-color:var(--btn-bg-f)}.tp-p2dv_b:active,.tp-btnv_b:active,.tp-lstv_s:active{background-color:var(--btn-bg-a)}.tp-p2dv_b:disabled,.tp-btnv_b:disabled,.tp-lstv_s:disabled{opacity:.5}.tp-rotv_c>.tp-cntv.tp-v-lst,.tp-tbpv_c>.tp-cntv.tp-v-lst,.tp-fldv_c>.tp-cntv.tp-v-lst{margin-bottom:calc(-1*var(--cnt-vp))}.tp-rotv_c>.tp-fldv.tp-v-lst .tp-fldv_c,.tp-tbpv_c>.tp-fldv.tp-v-lst .tp-fldv_c,.tp-fldv_c>.tp-fldv.tp-v-lst .tp-fldv_c{border-bottom-left-radius:0}.tp-rotv_c>.tp-fldv.tp-v-lst .tp-fldv_b,.tp-tbpv_c>.tp-fldv.tp-v-lst .tp-fldv_b,.tp-fldv_c>.tp-fldv.tp-v-lst .tp-fldv_b{border-bottom-left-radius:0}.tp-rotv_c>*:not(.tp-v-fst),.tp-tbpv_c>*:not(.tp-v-fst),.tp-fldv_c>*:not(.tp-v-fst){margin-top:var(--cnt-usp)}.tp-rotv_c>.tp-sprv:not(.tp-v-fst),.tp-tbpv_c>.tp-sprv:not(.tp-v-fst),.tp-fldv_c>.tp-sprv:not(.tp-v-fst),.tp-rotv_c>.tp-cntv:not(.tp-v-fst),.tp-tbpv_c>.tp-cntv:not(.tp-v-fst),.tp-fldv_c>.tp-cntv:not(.tp-v-fst){margin-top:var(--cnt-vp)}.tp-rotv_c>.tp-sprv+*:not(.tp-v-hidden),.tp-tbpv_c>.tp-sprv+*:not(.tp-v-hidden),.tp-fldv_c>.tp-sprv+*:not(.tp-v-hidden),.tp-rotv_c>.tp-cntv+*:not(.tp-v-hidden),.tp-tbpv_c>.tp-cntv+*:not(.tp-v-hidden),.tp-fldv_c>.tp-cntv+*:not(.tp-v-hidden){margin-top:var(--cnt-vp)}.tp-rotv_c>.tp-sprv:not(.tp-v-hidden)+.tp-sprv,.tp-tbpv_c>.tp-sprv:not(.tp-v-hidden)+.tp-sprv,.tp-fldv_c>.tp-sprv:not(.tp-v-hidden)+.tp-sprv,.tp-rotv_c>.tp-cntv:not(.tp-v-hidden)+.tp-cntv,.tp-tbpv_c>.tp-cntv:not(.tp-v-hidden)+.tp-cntv,.tp-fldv_c>.tp-cntv:not(.tp-v-hidden)+.tp-cntv{margin-top:0}.tp-tbpv_c>.tp-cntv,.tp-fldv_c>.tp-cntv{margin-left:4px}.tp-tbpv_c>.tp-fldv>.tp-fldv_b,.tp-fldv_c>.tp-fldv>.tp-fldv_b{border-top-left-radius:var(--bld-br);border-bottom-left-radius:var(--bld-br)}.tp-tbpv_c>.tp-fldv.tp-fldv-expanded>.tp-fldv_b,.tp-fldv_c>.tp-fldv.tp-fldv-expanded>.tp-fldv_b{border-bottom-left-radius:0}.tp-tbpv_c .tp-fldv>.tp-fldv_c,.tp-fldv_c .tp-fldv>.tp-fldv_c{border-bottom-left-radius:var(--bld-br)}.tp-tbpv_c>.tp-cntv+.tp-fldv>.tp-fldv_b,.tp-fldv_c>.tp-cntv+.tp-fldv>.tp-fldv_b{border-top-left-radius:0}.tp-tbpv_c>.tp-cntv+.tp-tabv>.tp-tabv_t,.tp-fldv_c>.tp-cntv+.tp-tabv>.tp-tabv_t{border-top-left-radius:0}.tp-tbpv_c>.tp-tabv>.tp-tabv_t,.tp-fldv_c>.tp-tabv>.tp-tabv_t{border-top-left-radius:var(--bld-br)}.tp-tbpv_c .tp-tabv>.tp-tabv_c,.tp-fldv_c .tp-tabv>.tp-tabv_c{border-bottom-left-radius:var(--bld-br)}.tp-rotv_b,.tp-fldv_b{background-color:var(--cnt-bg);color:var(--cnt-fg);cursor:pointer;display:block;height:calc(var(--cnt-usz) + 4px);line-height:calc(var(--cnt-usz) + 4px);overflow:hidden;padding-left:var(--cnt-hp);padding-right:calc(4px + var(--cnt-usz) + var(--cnt-hp));position:relative;text-align:left;text-overflow:ellipsis;white-space:nowrap;width:100%;transition:border-radius .2s ease-in-out .2s}.tp-rotv_b:hover,.tp-fldv_b:hover{background-color:var(--cnt-bg-h)}.tp-rotv_b:focus,.tp-fldv_b:focus{background-color:var(--cnt-bg-f)}.tp-rotv_b:active,.tp-fldv_b:active{background-color:var(--cnt-bg-a)}.tp-rotv_b:disabled,.tp-fldv_b:disabled{opacity:.5}.tp-rotv_m,.tp-fldv_m{background:linear-gradient(to left, var(--cnt-fg), var(--cnt-fg) 2px, transparent 2px, transparent 4px, var(--cnt-fg) 4px);border-radius:2px;bottom:0;content:"";display:block;height:6px;right:calc(var(--cnt-hp) + (var(--cnt-usz) + 4px - 6px)/2 - 2px);margin:auto;opacity:.5;position:absolute;top:0;transform:rotate(90deg);transition:transform .2s ease-in-out;width:6px}.tp-rotv.tp-rotv-expanded .tp-rotv_m,.tp-fldv.tp-fldv-expanded>.tp-fldv_b>.tp-fldv_m{transform:none}.tp-rotv_c,.tp-fldv_c{box-sizing:border-box;height:0;opacity:0;overflow:hidden;padding-bottom:0;padding-top:0;position:relative;transition:height .2s ease-in-out,opacity .2s linear,padding .2s ease-in-out}.tp-rotv.tp-rotv-cpl:not(.tp-rotv-expanded) .tp-rotv_c,.tp-fldv.tp-fldv-cpl:not(.tp-fldv-expanded)>.tp-fldv_c{display:none}.tp-rotv.tp-rotv-expanded .tp-rotv_c,.tp-fldv.tp-fldv-expanded>.tp-fldv_c{opacity:1;padding-bottom:var(--cnt-vp);padding-top:var(--cnt-vp);transform:none;overflow:visible;transition:height .2s ease-in-out,opacity .2s linear .2s,padding .2s ease-in-out}.tp-txtv_i,.tp-p2dpv_p,.tp-colswv_sw{background-color:var(--in-bg);border-radius:var(--bld-br);box-sizing:border-box;color:var(--in-fg);font-family:inherit;height:var(--cnt-usz);line-height:var(--cnt-usz);min-width:0;width:100%}.tp-txtv_i:hover,.tp-p2dpv_p:hover,.tp-colswv_sw:hover{background-color:var(--in-bg-h)}.tp-txtv_i:focus,.tp-p2dpv_p:focus,.tp-colswv_sw:focus{background-color:var(--in-bg-f)}.tp-txtv_i:active,.tp-p2dpv_p:active,.tp-colswv_sw:active{background-color:var(--in-bg-a)}.tp-txtv_i:disabled,.tp-p2dpv_p:disabled,.tp-colswv_sw:disabled{opacity:.5}.tp-lstv,.tp-coltxtv_m{position:relative}.tp-lstv_s{padding:0 20px 0 4px;width:100%}.tp-lstv_m,.tp-coltxtv_mm{bottom:0;margin:auto;pointer-events:none;position:absolute;right:2px;top:0}.tp-lstv_m svg,.tp-coltxtv_mm svg{bottom:0;height:16px;margin:auto;position:absolute;right:0;top:0;width:16px}.tp-lstv_m svg path,.tp-coltxtv_mm svg path{fill:currentColor}.tp-sglv_i,.tp-mllv_i,.tp-grlv_g{background-color:var(--mo-bg);border-radius:var(--bld-br);box-sizing:border-box;color:var(--mo-fg);height:var(--cnt-usz);scrollbar-color:currentColor rgba(0,0,0,0);scrollbar-width:thin;width:100%}.tp-sglv_i::-webkit-scrollbar,.tp-mllv_i::-webkit-scrollbar,.tp-grlv_g::-webkit-scrollbar{height:8px;width:8px}.tp-sglv_i::-webkit-scrollbar-corner,.tp-mllv_i::-webkit-scrollbar-corner,.tp-grlv_g::-webkit-scrollbar-corner{background-color:rgba(0,0,0,0)}.tp-sglv_i::-webkit-scrollbar-thumb,.tp-mllv_i::-webkit-scrollbar-thumb,.tp-grlv_g::-webkit-scrollbar-thumb{background-clip:padding-box;background-color:currentColor;border:rgba(0,0,0,0) solid 2px;border-radius:4px}.tp-pndtxtv,.tp-coltxtv_w{display:flex}.tp-pndtxtv_a,.tp-coltxtv_c{width:100%}.tp-pndtxtv_a+.tp-pndtxtv_a,.tp-coltxtv_c+.tp-pndtxtv_a,.tp-pndtxtv_a+.tp-coltxtv_c,.tp-coltxtv_c+.tp-coltxtv_c{margin-left:2px}.tp-rotv{--bs-bg: var(--tp-base-background-color, hsl(230, 7%, 17%));--bs-br: var(--tp-base-border-radius, 6px);--bs-ff: var(--tp-base-font-family, Roboto Mono, Source Code Pro, Menlo, Courier, monospace);--bs-sh: var(--tp-base-shadow-color, rgba(0, 0, 0, 0.2));--bld-br: var(--tp-blade-border-radius, 2px);--bld-hp: var(--tp-blade-horizontal-padding, 4px);--bld-vw: var(--tp-blade-value-width, 160px);--btn-bg: var(--tp-button-background-color, hsl(230, 7%, 70%));--btn-bg-a: var(--tp-button-background-color-active, #d6d7db);--btn-bg-f: var(--tp-button-background-color-focus, #c8cad0);--btn-bg-h: var(--tp-button-background-color-hover, #bbbcc4);--btn-fg: var(--tp-button-foreground-color, hsl(230, 7%, 17%));--cnt-bg: var(--tp-container-background-color, rgba(187, 188, 196, 0.1));--cnt-bg-a: var(--tp-container-background-color-active, rgba(187, 188, 196, 0.25));--cnt-bg-f: var(--tp-container-background-color-focus, rgba(187, 188, 196, 0.2));--cnt-bg-h: var(--tp-container-background-color-hover, rgba(187, 188, 196, 0.15));--cnt-fg: var(--tp-container-foreground-color, hsl(230, 7%, 75%));--cnt-hp: var(--tp-container-horizontal-padding, 4px);--cnt-vp: var(--tp-container-vertical-padding, 4px);--cnt-usp: var(--tp-container-unit-spacing, 4px);--cnt-usz: var(--tp-container-unit-size, 20px);--in-bg: var(--tp-input-background-color, rgba(187, 188, 196, 0.1));--in-bg-a: var(--tp-input-background-color-active, rgba(187, 188, 196, 0.25));--in-bg-f: var(--tp-input-background-color-focus, rgba(187, 188, 196, 0.2));--in-bg-h: var(--tp-input-background-color-hover, rgba(187, 188, 196, 0.15));--in-fg: var(--tp-input-foreground-color, hsl(230, 7%, 75%));--lbl-fg: var(--tp-label-foreground-color, rgba(187, 188, 196, 0.7));--mo-bg: var(--tp-monitor-background-color, rgba(0, 0, 0, 0.2));--mo-fg: var(--tp-monitor-foreground-color, rgba(187, 188, 196, 0.7));--grv-fg: var(--tp-groove-foreground-color, rgba(187, 188, 196, 0.1))}.tp-btnv_b{width:100%}.tp-btnv_t{text-align:center}.tp-ckbv_l{display:block;position:relative}.tp-ckbv_i{left:0;opacity:0;position:absolute;top:0}.tp-ckbv_w{background-color:var(--in-bg);border-radius:var(--bld-br);cursor:pointer;display:block;height:var(--cnt-usz);position:relative;width:var(--cnt-usz)}.tp-ckbv_w svg{display:block;height:16px;inset:0;margin:auto;opacity:0;position:absolute;width:16px}.tp-ckbv_w svg path{fill:none;stroke:var(--in-fg);stroke-width:2}.tp-ckbv_i:hover+.tp-ckbv_w{background-color:var(--in-bg-h)}.tp-ckbv_i:focus+.tp-ckbv_w{background-color:var(--in-bg-f)}.tp-ckbv_i:active+.tp-ckbv_w{background-color:var(--in-bg-a)}.tp-ckbv_i:checked+.tp-ckbv_w svg{opacity:1}.tp-ckbv.tp-v-disabled .tp-ckbv_w{opacity:.5}.tp-colv{position:relative}.tp-colv_h{display:flex}.tp-colv_s{flex-grow:0;flex-shrink:0;width:var(--cnt-usz)}.tp-colv_t{flex:1;margin-left:4px}.tp-colv_p{height:0;margin-top:0;opacity:0;overflow:hidden;transition:height .2s ease-in-out,opacity .2s linear,margin .2s ease-in-out}.tp-colv.tp-colv-expanded.tp-colv-cpl .tp-colv_p{overflow:visible}.tp-colv.tp-colv-expanded .tp-colv_p{margin-top:var(--cnt-usp);opacity:1}.tp-colv .tp-popv{left:calc(-1*var(--cnt-hp));right:calc(-1*var(--cnt-hp));top:var(--cnt-usz)}.tp-colpv_h,.tp-colpv_ap{margin-left:6px;margin-right:6px}.tp-colpv_h{margin-top:var(--cnt-usp)}.tp-colpv_rgb{display:flex;margin-top:var(--cnt-usp);width:100%}.tp-colpv_a{display:flex;margin-top:var(--cnt-vp);padding-top:calc(var(--cnt-vp) + 2px);position:relative}.tp-colpv_a::before{background-color:var(--grv-fg);content:"";height:2px;left:calc(-1*var(--cnt-hp));position:absolute;right:calc(-1*var(--cnt-hp));top:0}.tp-colpv.tp-v-disabled .tp-colpv_a::before{opacity:.5}.tp-colpv_ap{align-items:center;display:flex;flex:3}.tp-colpv_at{flex:1;margin-left:4px}.tp-svpv{border-radius:var(--bld-br);outline:none;overflow:hidden;position:relative}.tp-svpv.tp-v-disabled{opacity:.5}.tp-svpv_c{cursor:crosshair;display:block;height:calc(var(--cnt-usz)*4);width:100%}.tp-svpv_m{border-radius:100%;border:rgba(255,255,255,.75) solid 2px;box-sizing:border-box;filter:drop-shadow(0 0 1px rgba(0, 0, 0, 0.3));height:12px;margin-left:-6px;margin-top:-6px;pointer-events:none;position:absolute;width:12px}.tp-svpv:focus .tp-svpv_m{border-color:#fff}.tp-hplv{cursor:pointer;height:var(--cnt-usz);outline:none;position:relative}.tp-hplv.tp-v-disabled{opacity:.5}.tp-hplv_c{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAAABCAYAAABubagXAAAAQ0lEQVQoU2P8z8Dwn0GCgQEDi2OK/RBgYHjBgIpfovFh8j8YBIgzFGQxuqEgPhaDOT5gOhPkdCxOZeBg+IDFZZiGAgCaSSMYtcRHLgAAAABJRU5ErkJggg==);background-position:left top;background-repeat:no-repeat;background-size:100% 100%;border-radius:2px;display:block;height:4px;left:0;margin-top:-2px;position:absolute;top:50%;width:100%}.tp-hplv_m{border-radius:var(--bld-br);border:rgba(255,255,255,.75) solid 2px;box-shadow:0 0 2px rgba(0,0,0,.1);box-sizing:border-box;height:12px;left:50%;margin-left:-6px;margin-top:-6px;position:absolute;top:50%;width:12px}.tp-hplv:focus .tp-hplv_m{border-color:#fff}.tp-aplv{cursor:pointer;height:var(--cnt-usz);outline:none;position:relative;width:100%}.tp-aplv.tp-v-disabled{opacity:.5}.tp-aplv_b{background-color:#fff;background-image:linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%),linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%);background-size:4px 4px;background-position:0 0,2px 2px;border-radius:2px;display:block;height:4px;left:0;margin-top:-2px;overflow:hidden;position:absolute;top:50%;width:100%}.tp-aplv_c{inset:0;position:absolute}.tp-aplv_m{background-color:#fff;background-image:linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%),linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%);background-size:12px 12px;background-position:0 0,6px 6px;border-radius:var(--bld-br);box-shadow:0 0 2px rgba(0,0,0,.1);height:12px;left:50%;margin-left:-6px;margin-top:-6px;overflow:hidden;position:absolute;top:50%;width:12px}.tp-aplv_p{border-radius:var(--bld-br);border:rgba(255,255,255,.75) solid 2px;box-sizing:border-box;inset:0;position:absolute}.tp-aplv:focus .tp-aplv_p{border-color:#fff}.tp-colswv{background-color:#fff;background-image:linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%),linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%);background-size:10px 10px;background-position:0 0,5px 5px;border-radius:var(--bld-br);overflow:hidden}.tp-colswv.tp-v-disabled{opacity:.5}.tp-colswv_sw{border-radius:0}.tp-colswv_b{cursor:pointer;display:block;height:var(--cnt-usz);left:0;position:absolute;top:0;width:var(--cnt-usz)}.tp-colswv_b:focus::after{border:rgba(255,255,255,.75) solid 2px;border-radius:var(--bld-br);content:"";display:block;inset:0;position:absolute}.tp-coltxtv{display:flex;width:100%}.tp-coltxtv_m{margin-right:4px}.tp-coltxtv_ms{border-radius:var(--bld-br);color:var(--lbl-fg);cursor:pointer;height:var(--cnt-usz);line-height:var(--cnt-usz);padding:0 18px 0 4px}.tp-coltxtv_ms:hover{background-color:var(--in-bg-h)}.tp-coltxtv_ms:focus{background-color:var(--in-bg-f)}.tp-coltxtv_ms:active{background-color:var(--in-bg-a)}.tp-coltxtv_mm{color:var(--lbl-fg)}.tp-coltxtv.tp-v-disabled .tp-coltxtv_mm{opacity:.5}.tp-coltxtv_w{flex:1}.tp-dfwv{position:absolute;top:8px;right:8px;width:256px}.tp-fldv{position:relative}.tp-fldv_t{padding-left:4px}.tp-fldv_b:disabled .tp-fldv_m{display:none}.tp-fldv_c{padding-left:4px}.tp-fldv_i{bottom:0;color:var(--cnt-bg);left:0;overflow:hidden;position:absolute;top:calc(var(--cnt-usz) + 4px);width:max(var(--bs-br),4px)}.tp-fldv_i::before{background-color:currentColor;bottom:0;content:"";left:0;position:absolute;top:0;width:4px}.tp-fldv_b:hover+.tp-fldv_i{color:var(--cnt-bg-h)}.tp-fldv_b:focus+.tp-fldv_i{color:var(--cnt-bg-f)}.tp-fldv_b:active+.tp-fldv_i{color:var(--cnt-bg-a)}.tp-fldv.tp-v-disabled>.tp-fldv_i{opacity:.5}.tp-grlv{position:relative}.tp-grlv_g{display:block;height:calc(var(--cnt-usz)*3)}.tp-grlv_g polyline{fill:none;stroke:var(--mo-fg);stroke-linejoin:round}.tp-grlv_t{margin-top:-4px;transition:left .05s,top .05s;visibility:hidden}.tp-grlv_t.tp-grlv_t-a{visibility:visible}.tp-grlv_t.tp-grlv_t-in{transition:none}.tp-grlv.tp-v-disabled .tp-grlv_g{opacity:.5}.tp-grlv .tp-ttv{background-color:var(--mo-fg)}.tp-grlv .tp-ttv::before{border-top-color:var(--mo-fg)}.tp-lblv{align-items:center;display:flex;line-height:1.3;padding-left:var(--cnt-hp);padding-right:var(--cnt-hp)}.tp-lblv.tp-lblv-nol{display:block}.tp-lblv_l{color:var(--lbl-fg);flex:1;-webkit-hyphens:auto;hyphens:auto;overflow:hidden;padding-left:4px;padding-right:16px}.tp-lblv.tp-v-disabled .tp-lblv_l{opacity:.5}.tp-lblv.tp-lblv-nol .tp-lblv_l{display:none}.tp-lblv_v{align-self:flex-start;flex-grow:0;flex-shrink:0;width:var(--bld-vw)}.tp-lblv.tp-lblv-nol .tp-lblv_v{width:100%}.tp-lstv_s{padding:0 20px 0 var(--bld-hp);width:100%}.tp-lstv_m{color:var(--btn-fg)}.tp-sglv_i{padding-left:var(--bld-hp);padding-right:var(--bld-hp)}.tp-sglv.tp-v-disabled .tp-sglv_i{opacity:.5}.tp-mllv_i{display:block;height:calc(var(--cnt-usz)*3);line-height:var(--cnt-usz);padding-left:var(--bld-hp);padding-right:var(--bld-hp);resize:none;white-space:pre}.tp-mllv.tp-v-disabled .tp-mllv_i{opacity:.5}.tp-p2dv{position:relative}.tp-p2dv_h{display:flex}.tp-p2dv_b{height:var(--cnt-usz);margin-right:4px;position:relative;width:var(--cnt-usz)}.tp-p2dv_b svg{display:block;height:16px;left:50%;margin-left:-8px;margin-top:-8px;position:absolute;top:50%;width:16px}.tp-p2dv_b svg path{stroke:currentColor;stroke-width:2}.tp-p2dv_b svg circle{fill:currentColor}.tp-p2dv_t{flex:1}.tp-p2dv_p{height:0;margin-top:0;opacity:0;overflow:hidden;transition:height .2s ease-in-out,opacity .2s linear,margin .2s ease-in-out}.tp-p2dv.tp-p2dv-expanded .tp-p2dv_p{margin-top:var(--cnt-usp);opacity:1}.tp-p2dv .tp-popv{left:calc(-1*var(--cnt-hp));right:calc(-1*var(--cnt-hp));top:var(--cnt-usz)}.tp-p2dpv{padding-left:calc(var(--cnt-usz) + 4px)}.tp-p2dpv_p{cursor:crosshair;height:0;overflow:hidden;padding-bottom:100%;position:relative}.tp-p2dpv.tp-v-disabled .tp-p2dpv_p{opacity:.5}.tp-p2dpv_g{display:block;height:100%;left:0;pointer-events:none;position:absolute;top:0;width:100%}.tp-p2dpv_ax{opacity:.1;stroke:var(--in-fg);stroke-dasharray:1}.tp-p2dpv_l{opacity:.5;stroke:var(--in-fg);stroke-dasharray:1}.tp-p2dpv_m{border:var(--in-fg) solid 1px;border-radius:50%;box-sizing:border-box;height:4px;margin-left:-2px;margin-top:-2px;position:absolute;width:4px}.tp-p2dpv_p:focus .tp-p2dpv_m{background-color:var(--in-fg);border-width:0}.tp-popv{background-color:var(--bs-bg);border-radius:var(--bs-br);box-shadow:0 2px 4px var(--bs-sh);display:none;max-width:var(--bld-vw);padding:var(--cnt-vp) var(--cnt-hp);position:absolute;visibility:hidden;z-index:1000}.tp-popv.tp-popv-v{display:block;visibility:visible}.tp-sldv.tp-v-disabled{opacity:.5}.tp-sldv_t{box-sizing:border-box;cursor:pointer;height:var(--cnt-usz);margin:0 6px;outline:none;position:relative}.tp-sldv_t::before{background-color:var(--in-bg);border-radius:1px;content:"";display:block;height:2px;inset:0;margin:auto;position:absolute}.tp-sldv_k{height:100%;left:0;position:absolute;top:0}.tp-sldv_k::before{background-color:var(--in-fg);border-radius:1px;content:"";display:block;height:2px;inset:0;margin-bottom:auto;margin-top:auto;position:absolute}.tp-sldv_k::after{background-color:var(--btn-bg);border-radius:var(--bld-br);bottom:0;content:"";display:block;height:12px;margin-bottom:auto;margin-top:auto;position:absolute;right:-6px;top:0;width:12px}.tp-sldv_t:hover .tp-sldv_k::after{background-color:var(--btn-bg-h)}.tp-sldv_t:focus .tp-sldv_k::after{background-color:var(--btn-bg-f)}.tp-sldv_t:active .tp-sldv_k::after{background-color:var(--btn-bg-a)}.tp-sldtxtv{display:flex}.tp-sldtxtv_s{flex:2}.tp-sldtxtv_t{flex:1;margin-left:4px}.tp-tabv{position:relative}.tp-tabv_t{align-items:flex-end;color:var(--cnt-bg);display:flex;overflow:hidden;position:relative}.tp-tabv_t:hover{color:var(--cnt-bg-h)}.tp-tabv_t:has(*:focus){color:var(--cnt-bg-f)}.tp-tabv_t:has(*:active){color:var(--cnt-bg-a)}.tp-tabv_t::before{background-color:currentColor;bottom:0;content:"";height:2px;left:0;pointer-events:none;position:absolute;right:0}.tp-tabv.tp-v-disabled .tp-tabv_t::before{opacity:.5}.tp-tabv.tp-tabv-nop .tp-tabv_t{height:calc(var(--cnt-usz) + 4px);position:relative}.tp-tabv.tp-tabv-nop .tp-tabv_t::before{background-color:var(--cnt-bg);bottom:0;content:"";height:2px;left:0;position:absolute;right:0}.tp-tabv_i{bottom:0;color:var(--cnt-bg);left:0;overflow:hidden;position:absolute;top:calc(var(--cnt-usz) + 4px);width:max(var(--bs-br),4px)}.tp-tabv_i::before{background-color:currentColor;bottom:0;content:"";left:0;position:absolute;top:0;width:4px}.tp-tabv_t:hover+.tp-tabv_i{color:var(--cnt-bg-h)}.tp-tabv_t:has(*:focus)+.tp-tabv_i{color:var(--cnt-bg-f)}.tp-tabv_t:has(*:active)+.tp-tabv_i{color:var(--cnt-bg-a)}.tp-tabv.tp-v-disabled>.tp-tabv_i{opacity:.5}.tp-tbiv{flex:1;min-width:0;position:relative}.tp-tbiv+.tp-tbiv{margin-left:2px}.tp-tbiv+.tp-tbiv.tp-v-disabled::before{opacity:.5}.tp-tbiv_b{display:block;padding-left:calc(var(--cnt-hp) + 4px);padding-right:calc(var(--cnt-hp) + 4px);position:relative;width:100%}.tp-tbiv_b:disabled{opacity:.5}.tp-tbiv_b::before{background-color:var(--cnt-bg);content:"";inset:0 0 2px;pointer-events:none;position:absolute}.tp-tbiv_b:hover::before{background-color:var(--cnt-bg-h)}.tp-tbiv_b:focus::before{background-color:var(--cnt-bg-f)}.tp-tbiv_b:active::before{background-color:var(--cnt-bg-a)}.tp-tbiv_t{color:var(--cnt-fg);height:calc(var(--cnt-usz) + 4px);line-height:calc(var(--cnt-usz) + 4px);opacity:.5;overflow:hidden;position:relative;text-overflow:ellipsis}.tp-tbiv.tp-tbiv-sel .tp-tbiv_t{opacity:1}.tp-tbpv_c{padding-bottom:var(--cnt-vp);padding-left:4px;padding-top:var(--cnt-vp)}.tp-txtv{position:relative}.tp-txtv_i{padding-left:var(--bld-hp);padding-right:var(--bld-hp)}.tp-txtv.tp-txtv-fst .tp-txtv_i{border-bottom-right-radius:0;border-top-right-radius:0}.tp-txtv.tp-txtv-mid .tp-txtv_i{border-radius:0}.tp-txtv.tp-txtv-lst .tp-txtv_i{border-bottom-left-radius:0;border-top-left-radius:0}.tp-txtv.tp-txtv-num .tp-txtv_i{text-align:right}.tp-txtv.tp-txtv-drg .tp-txtv_i{opacity:.3}.tp-txtv_k{cursor:pointer;height:100%;left:calc(var(--bld-hp) - 5px);position:absolute;top:0;width:12px}.tp-txtv_k::before{background-color:var(--in-fg);border-radius:1px;bottom:0;content:"";height:calc(var(--cnt-usz) - 4px);left:50%;margin-bottom:auto;margin-left:-1px;margin-top:auto;opacity:.1;position:absolute;top:0;transition:border-radius .1s,height .1s,transform .1s,width .1s;width:2px}.tp-txtv_k:hover::before,.tp-txtv.tp-txtv-drg .tp-txtv_k::before{opacity:1}.tp-txtv.tp-txtv-drg .tp-txtv_k::before{border-radius:50%;height:4px;transform:translateX(-1px);width:4px}.tp-txtv_g{bottom:0;display:block;height:8px;left:50%;margin:auto;overflow:visible;pointer-events:none;position:absolute;top:0;visibility:hidden;width:100%}.tp-txtv.tp-txtv-drg .tp-txtv_g{visibility:visible}.tp-txtv_gb{fill:none;stroke:var(--in-fg);stroke-dasharray:1}.tp-txtv_gh{fill:none;stroke:var(--in-fg)}.tp-txtv .tp-ttv{margin-left:6px;visibility:hidden}.tp-txtv.tp-txtv-drg .tp-ttv{visibility:visible}.tp-ttv{background-color:var(--in-fg);border-radius:var(--bld-br);color:var(--bs-bg);padding:2px 4px;pointer-events:none;position:absolute;transform:translate(-50%, -100%)}.tp-ttv::before{border-color:var(--in-fg) rgba(0,0,0,0) rgba(0,0,0,0) rgba(0,0,0,0);border-style:solid;border-width:2px;box-sizing:border-box;content:"";font-size:.9em;height:4px;left:50%;margin-left:-2px;position:absolute;top:100%;width:4px}.tp-rotv{background-color:var(--bs-bg);border-radius:var(--bs-br);box-shadow:0 2px 4px var(--bs-sh);font-family:var(--bs-ff);font-size:11px;font-weight:500;line-height:1;text-align:left}.tp-rotv_b{border-bottom-left-radius:var(--bs-br);border-bottom-right-radius:var(--bs-br);border-top-left-radius:var(--bs-br);border-top-right-radius:var(--bs-br);padding-left:calc(4px + var(--cnt-usz) + var(--cnt-hp));text-align:center}.tp-rotv.tp-rotv-expanded .tp-rotv_b{border-bottom-left-radius:0;border-bottom-right-radius:0;transition-delay:0s;transition-duration:0s}.tp-rotv.tp-rotv-not>.tp-rotv_b{display:none}.tp-rotv_b:disabled .tp-rotv_m{display:none}.tp-rotv_c>.tp-fldv.tp-v-lst>.tp-fldv_c{border-bottom-left-radius:var(--bs-br);border-bottom-right-radius:var(--bs-br)}.tp-rotv_c>.tp-fldv.tp-v-lst>.tp-fldv_i{border-bottom-left-radius:var(--bs-br)}.tp-rotv_c>.tp-fldv.tp-v-lst:not(.tp-fldv-expanded)>.tp-fldv_b{border-bottom-left-radius:var(--bs-br);border-bottom-right-radius:var(--bs-br)}.tp-rotv_c>.tp-fldv.tp-v-lst.tp-fldv-expanded>.tp-fldv_b{transition-delay:0s;transition-duration:0s}.tp-rotv_c .tp-fldv.tp-v-vlst:not(.tp-fldv-expanded)>.tp-fldv_b{border-bottom-right-radius:var(--bs-br)}.tp-rotv.tp-rotv-not .tp-rotv_c>.tp-fldv.tp-v-fst{margin-top:calc(-1*var(--cnt-vp))}.tp-rotv.tp-rotv-not .tp-rotv_c>.tp-fldv.tp-v-fst>.tp-fldv_b{border-top-left-radius:var(--bs-br);border-top-right-radius:var(--bs-br)}.tp-rotv_c>.tp-tabv.tp-v-lst>.tp-tabv_c{border-bottom-left-radius:var(--bs-br);border-bottom-right-radius:var(--bs-br)}.tp-rotv_c>.tp-tabv.tp-v-lst>.tp-tabv_i{border-bottom-left-radius:var(--bs-br)}.tp-rotv.tp-rotv-not .tp-rotv_c>.tp-tabv.tp-v-fst{margin-top:calc(-1*var(--cnt-vp))}.tp-rotv.tp-rotv-not .tp-rotv_c>.tp-tabv.tp-v-fst>.tp-tabv_t{border-top-left-radius:var(--bs-br);border-top-right-radius:var(--bs-br)}.tp-rotv.tp-v-disabled,.tp-rotv .tp-v-disabled{pointer-events:none}.tp-rotv.tp-v-hidden,.tp-rotv .tp-v-hidden{display:none}.tp-sprv_r{background-color:var(--grv-fg);border-width:0;display:block;height:2px;margin:0;width:100%}.tp-sprv.tp-v-disabled .tp-sprv_r{opacity:.5}',plugins:[vr,fr,xr,Ae,Cr]})}},Pr=(new Qt("4.0.5"),t({ButtonCellApi:()=>tc,ButtonGridApi:()=>ic,ButtonGridController:()=>nc,CubicBezier:()=>pc,CubicBezierApi:()=>oc,CubicBezierAssembly:()=>hc,CubicBezierController:()=>kc,CubicBezierGraphController:()=>Pc,CubicBezierGraphView:()=>fc,CubicBezierPickerController:()=>Ec,CubicBezierPickerView:()=>gc,CubicBezierPreviewView:()=>Cc,CubicBezierView:()=>mc,FpsGraphBladeApi:()=>Lc,FpsGraphController:()=>Dc,FpsView:()=>jc,Fpswatch:()=>Mc,Interval:()=>Tc,IntervalAssembly:()=>zc,IntervalConstraint:()=>Rc,RadioCellApi:()=>Yc,RadioController:()=>Zc,RadioGridApi:()=>Wc,RadioGridController:()=>td,RadioView:()=>Jc,RangeSliderController:()=>Fc,RangeSliderTextController:()=>$c,RangeSliderTextView:()=>Kc,RangeSliderView:()=>Uc,TpRadioGridChangeEvent:()=>Xc,css:()=>ad,id:()=>od,plugins:()=>ld}));function Er(t){return null==t}function kr(t){return null!==t&&"object"==typeof t}function Vr(t){return null!==t&&"object"==typeof t}function Lr(t,e){if(t.length!==e.length)return!1;for(let i=0;i{const s=t[n],r=e[n];return Vr(s)&&Vr(r)?Object.assign(Object.assign({},i),{[n]:Mr(s,r)}):Object.assign(Object.assign({},i),{[n]:n in e?r:s})},{})}var Sr={alreadydisposed:()=>"View has been already disposed",invalidparams:t=>`Invalid parameters for '${t.name}'`,nomatchingcontroller:t=>`No matching controller for '${t.key}'`,nomatchingview:t=>`No matching view for '${JSON.stringify(t.params)}'`,notbindable:()=>"Value is not bindable",notcompatible:t=>`Not compatible with plugin '${t.id}'`,propertynotfound:t=>`Property '${t.name}' not found`,shouldneverhappen:()=>"This error should never happen"},jr=class t{static alreadyDisposed(){return new t({type:"alreadydisposed"})}static notBindable(){return new t({type:"notbindable"})}static notCompatible(e,i){return new t({type:"notcompatible",context:{id:`${e}.${i}`}})}static propertyNotFound(e){return new t({type:"propertynotfound",context:{name:e}})}static shouldNeverHappen(){return new t({type:"shouldneverhappen"})}constructor(t){var e;this.message=null!==(e=Sr[t.type](t.context))&&void 0!==e?e:"Unexpected error",this.name=this.constructor.name,this.stack=new Error(this.message).stack,this.type=t.type}toString(){return this.message}},Dr=class t{constructor(t,e){this.obj_=t,this.key=e}static isBindable(t){return null!==t&&("object"==typeof t||"function"==typeof t)}read(){return this.obj_[this.key]}write(t){this.obj_[this.key]=t}writeProperty(e,i){const n=this.read();if(!t.isBindable(n))throw jr.notBindable();if(!(e in n))throw jr.propertyNotFound(e);n[e]=i}},Ar=class{constructor(){this.observers_={}}on(t,e){let i=this.observers_[t];return i||(i=this.observers_[t]=[]),i.push({handler:e}),this}off(t,e){const i=this.observers_[t];return i&&(this.observers_[t]=i.filter(t=>t.handler!==e)),this}emit(t,e){const i=this.observers_[t];i&&i.forEach(t=>{t.handler(e)})}},Or=class{constructor(t,e){var i;this.constraint_=null==e?void 0:e.constraint,this.equals_=null!==(i=null==e?void 0:e.equals)&&void 0!==i?i:(t,e)=>t===e,this.emitter=new Ar,this.rawValue_=t}get constraint(){return this.constraint_}get rawValue(){return this.rawValue_}set rawValue(t){this.setRawValue(t,{forceEmit:!1,last:!0})}setRawValue(t,e){const i=null!=e?e:{forceEmit:!1,last:!0},n=this.constraint_?this.constraint_.constrain(t):t,s=this.rawValue_;this.equals_(s,n)&&!i.forceEmit||(this.emitter.emit("beforechange",{sender:this}),this.rawValue_=n,this.emitter.emit("change",{options:i,previousRawValue:s,rawValue:n,sender:this}))}},Br=class{constructor(t){this.emitter=new Ar,this.value_=t}get rawValue(){return this.value_}set rawValue(t){this.setRawValue(t,{forceEmit:!1,last:!0})}setRawValue(t,e){const i=null!=e?e:{forceEmit:!1,last:!0},n=this.value_;(n!==t||i.forceEmit)&&(this.emitter.emit("beforechange",{sender:this}),this.value_=t,this.emitter.emit("change",{options:i,previousRawValue:n,rawValue:this.value_,sender:this}))}},Tr=class{constructor(t){this.emitter=new Ar,this.onValueBeforeChange_=this.onValueBeforeChange_.bind(this),this.onValueChange_=this.onValueChange_.bind(this),this.value_=t,this.value_.emitter.on("beforechange",this.onValueBeforeChange_),this.value_.emitter.on("change",this.onValueChange_)}get rawValue(){return this.value_.rawValue}onValueBeforeChange_(t){this.emitter.emit("beforechange",Object.assign(Object.assign({},t),{sender:this}))}onValueChange_(t){this.emitter.emit("change",Object.assign(Object.assign({},t),{sender:this}))}};function zr(t,e){const i=null==e?void 0:e.constraint,n=null==e?void 0:e.equals;return i||n?new Or(t,e):new Br(t)}var Rr=class t{constructor(t){this.emitter=new Ar,this.valMap_=t;for(const e in this.valMap_)this.valMap_[e].emitter.on("change",()=>{this.emitter.emit("change",{key:e,sender:this})})}static createCore(t){return Object.keys(t).reduce((e,i)=>Object.assign(e,{[i]:zr(t[i])}),{})}static fromObject(e){return new t(this.createCore(e))}get(t){return this.valMap_[t].rawValue}set(t,e){this.valMap_[t].rawValue=e}value(t){return this.valMap_[t]}},Nr=class{constructor(t){this.values=Rr.fromObject({max:t.max,min:t.min})}constrain(t){const e=this.values.get("max"),i=this.values.get("min");return Math.min(Math.max(t,i),e)}},Kr=class{constructor(t){this.values=Rr.fromObject({max:t.max,min:t.min})}constrain(t){const e=this.values.get("max"),i=this.values.get("min");let n=t;return Er(i)||(n=Math.max(n,i)),Er(e)||(n=Math.min(n,e)),n}},Ir=class{constructor(t,e=0){this.step=t,this.origin=e}constrain(t){const e=this.origin%this.step;return e+Math.round((t-e)/this.step)*this.step}},Ur=class{constructor(t){this.text=t}evaluate(){return Number(this.text)}toString(){return this.text}},Fr={"**":(t,e)=>Math.pow(t,e),"*":(t,e)=>t*e,"/":(t,e)=>t/e,"%":(t,e)=>t%e,"+":(t,e)=>t+e,"-":(t,e)=>t-e,"<<":(t,e)=>t<>":(t,e)=>t>>e,">>>":(t,e)=>t>>>e,"&":(t,e)=>t&e,"^":(t,e)=>t^e,"|":(t,e)=>t|e},$r=class{constructor(t,e,i){this.left=e,this.operator=t,this.right=i}evaluate(){const t=Fr[this.operator];if(!t)throw new Error(`unexpected binary operator: '${this.operator}`);return t(this.left.evaluate(),this.right.evaluate())}toString(){return["b(",this.left.toString(),this.operator,this.right.toString(),")"].join(" ")}},qr={"+":t=>t,"-":t=>-t,"~":t=>~t},Hr=class{constructor(t,e){this.operator=t,this.expression=e}evaluate(){const t=qr[this.operator];if(!t)throw new Error(`unexpected unary operator: '${this.operator}`);return t(this.expression.evaluate())}toString(){return["u(",this.operator,this.expression.toString(),")"].join(" ")}};function Gr(t){return(e,i)=>{for(let n=0;ne.startsWith(t,i))[0];return n?(i+=n.length,{cursor:i+=Yr(e,i).length,operator:n}):null}var eo=[["**"],["*","/","%"],["+","-"],["<<",">>>",">>"],["&"],["^"],["|"]].reduce((t,e)=>function(t,e){return(i,n)=>{const s=t(i,n);if(!s)return null;n=s.cursor;let r=s.evaluable;for(;;){const s=to(e,i,n);if(!s)break;n=s.cursor;const o=t(i,n);if(!o)return null;n=o.cursor,r=new $r(s.operator,r,o.evaluable)}return r?{cursor:n,evaluable:r}:null}}(t,e),function t(e,i){const n=function(t,e){var i;return null!==(i=function(t,e){const i=Zr(t,e);return e+=i.length,""===i?null:{evaluable:new Ur(i),cursor:e}}(t,e))&&void 0!==i?i:function(t,e){const i=t.substr(e,1);if(e+=i.length,"("!==i)return null;const n=io(t,e);if(!n)return null;e=n.cursor,e+=Yr(t,e).length;const s=t.substr(e,1);return e+=s.length,")"!==s?null:{evaluable:n.evaluable,cursor:e}}(t,e)}(e,i);if(n)return n;const s=e.substr(i,1);if(i+=s.length,"+"!==s&&"-"!==s&&"~"!==s)return null;const r=t(e,i);return r?{cursor:i=r.cursor,evaluable:new Hr(s,r.evaluable)}:null});function io(t,e){return e+=Yr(t,e).length,eo(t,e)}function no(t){var e;const i=function(t){const e=io(t,0);return e?e.cursor+Yr(t,e.cursor).length!==t.length?null:e.evaluable:null}(t);return null!==(e=null==i?void 0:i.evaluate())&&void 0!==e?e:null}function so(t){if("number"==typeof t)return t;if("string"==typeof t){const e=no(t);if(!Er(e))return e}return 0}function ro(t){return e=>e.toFixed(Math.max(Math.min(t,20),0))}function oo(t,e,i,n,s){return n+(t-e)/(i-e)*(s-n)}function ao(t){return String(t.toFixed(10)).split(".")[1].replace(/0+$/,"").length}function lo(t,e,i){return Math.min(Math.max(t,e),i)}function po(t,e){return(t%e+e)%e}function ho(t,e){return Er(t.step)?Math.max(ao(e),2):ao(t.step)}function co(t){var e;return null!==(e=t.step)&&void 0!==e?e:1}function uo(t,e){var i;const n=Math.abs(null!==(i=t.step)&&void 0!==i?i:e);return 0===n?.1:Math.pow(10,Math.floor(Math.log10(n))-1)}function vo(t,e){return Er(t.step)?null:new Ir(t.step,e)}function mo(t){return Er(t.max)||Er(t.min)?Er(t.max)&&Er(t.min)?null:new Kr({max:t.max,min:t.min}):new Nr({max:t.max,min:t.min})}function bo(t,e){var i,n,s;return{formatter:null!==(i=t.format)&&void 0!==i?i:ro(ho(t,e)),keyScale:null!==(n=t.keyScale)&&void 0!==n?n:co(t),pointerScale:null!==(s=t.pointerScale)&&void 0!==s?s:uo(t,e)}}function go(t){return{format:t.optional.function,keyScale:t.optional.number,max:t.optional.number,min:t.optional.number,pointerScale:t.optional.number,step:t.optional.number}}function wo(t){return{constraint:t.constraint,textProps:Rr.fromObject(bo(t.params,t.initialValue))}}var _o=class{constructor(t){this.controller=t}get element(){return this.controller.view.element}get disabled(){return this.controller.viewProps.get("disabled")}set disabled(t){this.controller.viewProps.set("disabled",t)}get hidden(){return this.controller.viewProps.get("hidden")}set hidden(t){this.controller.viewProps.set("hidden",t)}dispose(){this.controller.viewProps.set("disposed",!0)}importState(t){return this.controller.importState(t)}exportState(){return this.controller.exportState()}},fo=class{constructor(t){this.target=t}},xo=class extends fo{constructor(t,e,i){super(t),this.value=e,this.last=null==i||i}},Co=class extends fo{constructor(t,e){super(t),this.expanded=e}},yo=class extends fo{constructor(t,e){super(t),this.index=e}},Po=class extends _o{constructor(t){super(t),this.onValueChange_=this.onValueChange_.bind(this),this.emitter_=new Ar,this.controller.value.emitter.on("change",this.onValueChange_)}get label(){return this.controller.labelController.props.get("label")}set label(t){this.controller.labelController.props.set("label",t)}get key(){return this.controller.value.binding.target.key}get tag(){return this.controller.tag}set tag(t){this.controller.tag=t}on(t,e){const i=e.bind(this);return this.emitter_.on(t,t=>{i(t)}),this}refresh(){this.controller.value.fetch()}onValueChange_(t){const e=this.controller.value;this.emitter_.emit("change",new xo(this,e.binding.target.read(),t.options.last))}};function Eo(t){return e=>i=>{if(!e&&void 0===i)return{succeeded:!1,value:void 0};if(e&&void 0===i)return{succeeded:!0,value:void 0};const n=t(i);return void 0!==n?{succeeded:!0,value:n}:{succeeded:!1,value:void 0}}}function ko(t){return{custom:e=>Eo(e)(t),boolean:Eo(t=>"boolean"==typeof t?t:void 0)(t),number:Eo(t=>"number"==typeof t?t:void 0)(t),string:Eo(t=>"string"==typeof t?t:void 0)(t),function:Eo(t=>"function"==typeof t?t:void 0)(t),constant:e=>Eo(t=>t===e?e:void 0)(t),raw:Eo(t=>t)(t),object:e=>Eo(t=>{var i;if(null!==(i=t)&&"object"==typeof i)return function(t,e){return Object.keys(e).reduce((i,n)=>{if(void 0===i)return;const s=(0,e[n])(t[n]);return s.succeeded?Object.assign(Object.assign({},i),{[n]:s.value}):void 0},{})}(t,e)})(t),array:e=>Eo(t=>{var i;if(Array.isArray(t))return i=e,t.reduce((t,e)=>{if(void 0===t)return;const n=i(e);return n.succeeded&&void 0!==n.value?[...t,n.value]:void 0},[])})(t)}}var Vo={optional:ko(!0),required:ko(!1)};function Lo(t,e){const i=e(Vo),n=Vo.required.object(i)(t);return n.succeeded?n.value:void 0}function Mo(t,e,i,n){if(e&&!e(t))return!1;const s=Lo(t,i);return!!s&&n(s)}function So(t,e){var i;return Mr(null!==(i=null==t?void 0:t())&&void 0!==i?i:{},e)}function jo(t){return"value"in t}var Do="http://www.w3.org/2000/svg";function Ao(t){t.offsetHeight}function Oo(t){return void 0!==t.ontouchstart}var Bo={check:'',dropdown:'',p2dpad:''};function To(t,e){const i=t.createElementNS(Do,"svg");return i.innerHTML=Bo[e],i}function zo(t,e,i){t.insertBefore(e,t.children[i])}function Ro(t){t.parentElement&&t.parentElement.removeChild(t)}function No(t){for(;t.children.length>0;)t.removeChild(t.children[0])}function Ko(t){return t.relatedTarget?t.relatedTarget:"explicitOriginalTarget"in t?t.explicitOriginalTarget:null}function Io(t,e){t.emitter.on("change",t=>{e(t.rawValue)}),e(t.rawValue)}function Uo(t,e,i){Io(t.value(e),i)}var Fo="tp";function $o(t){return(e,i)=>[Fo,"-",t,"v",e?`_${e}`:"",i?`-${i}`:""].join("")}var qo=$o("lbl"),Ho=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(qo()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("div");i.classList.add(qo("l")),Uo(e.props,"label",e=>{Er(e)?this.element.classList.add(qo(void 0,"nol")):(this.element.classList.remove(qo(void 0,"nol")),function(t){for(;t.childNodes.length>0;)t.removeChild(t.childNodes[0])}(i),i.appendChild(function(t,e){const i=t.createDocumentFragment();return e.split("\n").map(e=>t.createTextNode(e)).forEach((e,n)=>{n>0&&i.appendChild(t.createElement("br")),i.appendChild(e)}),i}(t,e)))}),this.element.appendChild(i),this.labelElement=i;const n=t.createElement("div");n.classList.add(qo("v")),this.element.appendChild(n),this.valueElement=n}},Go=class{constructor(t,e){this.props=e.props,this.valueController=e.valueController,this.viewProps=e.valueController.viewProps,this.view=new Ho(t,{props:e.props,viewProps:this.viewProps}),this.view.valueElement.appendChild(this.valueController.view.element)}importProps(t){return Mo(t,null,t=>({label:t.optional.string}),t=>(this.props.set("label",t.label),!0))}exportProps(){return So(null,{label:this.props.get("label")})}},Yo=$o(""),Xo={veryfirst:"vfst",first:"fst",last:"lst",verylast:"vlst"},Wo=class{constructor(t){this.parent_=null,this.blade=t.blade,this.view=t.view,this.viewProps=t.viewProps;const e=this.view.element;this.blade.value("positions").emitter.on("change",()=>{["veryfirst","first","last","verylast"].forEach(t=>{e.classList.remove(Yo(void 0,Xo[t]))}),this.blade.get("positions").forEach(t=>{e.classList.add(Yo(void 0,Xo[t]))})}),this.viewProps.handleDispose(()=>{Ro(e)})}get parent(){return this.parent_}set parent(t){this.parent_=t,this.viewProps.set("parent",this.parent_?this.parent_.viewProps:null)}importState(t){return Mo(t,null,t=>({disabled:t.required.boolean,hidden:t.required.boolean}),t=>(this.viewProps.importState(t),!0))}exportState(){return So(null,Object.assign({},this.viewProps.exportState()))}},Qo=class extends Wo{constructor(t,e){if(e.value!==e.valueController.value)throw jr.shouldNeverHappen();const i=e.valueController.viewProps,n=new Go(t,{blade:e.blade,props:e.props,valueController:e.valueController});super(Object.assign(Object.assign({},e),{view:new Ho(t,{props:e.props,viewProps:i}),viewProps:i})),this.labelController=n,this.value=e.value,this.valueController=e.valueController,this.view.valueElement.appendChild(this.valueController.view.element)}importState(t){return Mo(t,e=>{var i,n,s;return super.importState(e)&&this.labelController.importProps(e)&&(null===(s=null===(n=(i=this.valueController).importProps)||void 0===n?void 0:n.call(i,t))||void 0===s||s)},t=>({value:t.optional.raw}),t=>(t.value&&(this.value.rawValue=t.value),!0))}exportState(){var t,e,i;return So(()=>super.exportState(),Object.assign(Object.assign({value:this.value.rawValue},this.labelController.exportProps()),null!==(i=null===(e=(t=this.valueController).exportProps)||void 0===e?void 0:e.call(t))&&void 0!==i?i:{}))}};function Jo(t,e){for(;t.length{i(new fo(this))}),this}};function ia(t,e){return i=>{!function(t,e,i){i?t.classList.add(e):t.classList.remove(e)}(t,e,i)}}function na(t,e){Io(t,t=>{e.textContent=null!=t?t:""})}var sa=$o("btn"),ra=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(sa()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("button");i.classList.add(sa("b")),e.viewProps.bindDisabled(i),this.element.appendChild(i),this.buttonElement=i;const n=t.createElement("div");n.classList.add(sa("t")),na(e.props.value("title"),n),this.buttonElement.appendChild(n)}},oa=class{constructor(t,e){this.emitter=new Ar,this.onClick_=this.onClick_.bind(this),this.props=e.props,this.viewProps=e.viewProps,this.view=new ra(t,{props:this.props,viewProps:this.viewProps}),this.view.buttonElement.addEventListener("click",this.onClick_)}importProps(t){return Mo(t,null,t=>({title:t.optional.string}),t=>(this.props.set("title",t.title),!0))}exportProps(){return So(null,{title:this.props.get("title")})}onClick_(){this.emitter.emit("click",{sender:this})}},aa=class extends Wo{constructor(t,e){const i=new oa(t,{props:e.buttonProps,viewProps:e.viewProps}),n=new Go(t,{blade:e.blade,props:e.labelProps,valueController:i});super({blade:e.blade,view:n.view,viewProps:e.viewProps}),this.buttonController=i,this.labelController=n}importState(t){return Mo(t,t=>super.importState(t)&&this.buttonController.importProps(t)&&this.labelController.importProps(t),()=>({}),()=>!0)}exportState(){return So(()=>super.exportState(),Object.assign(Object.assign({},this.buttonController.exportProps()),this.labelController.exportProps()))}},la=new class{constructor(t){const[e,i]=t.split("-"),n=e.split(".");this.major=parseInt(n[0],10),this.minor=parseInt(n[1],10),this.patch=parseInt(n[2],10),this.prerelease=null!=i?i:null}toString(){const t=[this.major,this.minor,this.patch].join(".");return null!==this.prerelease?[t,this.prerelease].join("-"):t}}("2.0.0-beta.2");function pa(t){return Object.assign({core:la},t)}pa({id:"button",type:"blade",accept(t){const e=Lo(t,t=>({title:t.required.string,view:t.required.constant("button"),label:t.optional.string}));return e?{params:e}:null},controller:t=>new aa(t.document,{blade:t.blade,buttonProps:Rr.fromObject({title:t.params.title}),labelProps:Rr.fromObject({label:t.params.label}),viewProps:t.viewProps}),api:t=>t.controller instanceof aa?new ea(t.controller):null});var ha=class{constructor(t,e){this.onRackValueChange_=this.onRackValueChange_.bind(this),this.controller_=t,this.emitter_=new Ar,this.pool_=e,this.controller_.rack.emitter.on("valuechange",this.onRackValueChange_)}get children(){return this.controller_.rack.children.map(t=>this.pool_.createApi(t))}addBinding(t,e,i){const n=null!=i?i:{},s=this.controller_.element.ownerDocument,r=this.pool_.createBinding(s,function(t,e){if(!Dr.isBindable(t))throw jr.notBindable();return new Dr(t,e)}(t,e),n),o=this.pool_.createBindingApi(r);return this.add(o,n.index)}addFolder(t){return function(t,e){return t.addBlade(Object.assign(Object.assign({},e),{view:"folder"}))}(this,t)}addButton(t){return function(t,e){return t.addBlade(Object.assign(Object.assign({},e),{view:"button"}))}(this,t)}addTab(t){return function(t,e){return t.addBlade(Object.assign(Object.assign({},e),{view:"tab"}))}(this,t)}add(t,e){const i=t.controller;return this.controller_.rack.add(i,e),t}remove(t){this.controller_.rack.remove(t.controller)}addBlade(t){const e=this.controller_.element.ownerDocument,i=this.pool_.createBlade(e,t),n=this.pool_.createApi(i);return this.add(n,t.index)}on(t,e){const i=e.bind(this);return this.emitter_.on(t,t=>{i(t)}),this}refresh(){this.children.forEach(t=>{var e;kr(e=t)&&"refresh"in e&&"function"==typeof e.refresh&&t.refresh()})}onRackValueChange_(t){const e=t.bladeController,i=this.pool_.createApi(e),n=kr(s=e.value)&&"binding"in s&&kr(r=s.binding)&&"target"in r?e.value.binding:null;var s,r;this.emitter_.emit("change",new xo(i,n?n.target.read():e.value.rawValue,t.options.last))}},ca=class extends _o{constructor(t,e){super(t),this.rackApi_=new ha(t.rackController,e)}},da=class extends Wo{constructor(t){super({blade:t.blade,view:t.view,viewProps:t.rackController.viewProps}),this.rackController=t.rackController}importState(t){return Mo(t,t=>super.importState(t),t=>({children:t.required.array(t.required.raw)}),t=>this.rackController.rack.children.every((e,i)=>e.importState(t.children[i])))}exportState(){return So(()=>super.exportState(),{children:this.rackController.rack.children.map(t=>t.exportState())})}};function ua(t){return"rackController"in t}var va=class{constructor(t){this.emitter=new Ar,this.items_=[],this.cache_=new Set,this.onSubListAdd_=this.onSubListAdd_.bind(this),this.onSubListRemove_=this.onSubListRemove_.bind(this),this.extract_=t}get items(){return this.items_}allItems(){return Array.from(this.cache_)}find(t){for(const e of this.allItems())if(t(e))return e;return null}includes(t){return this.cache_.has(t)}add(t,e){if(this.includes(t))throw jr.shouldNeverHappen();const i=void 0!==e?e:this.items_.length;this.items_.splice(i,0,t),this.cache_.add(t);const n=this.extract_(t);n&&(n.emitter.on("add",this.onSubListAdd_),n.emitter.on("remove",this.onSubListRemove_),n.allItems().forEach(t=>{this.cache_.add(t)})),this.emitter.emit("add",{index:i,item:t,root:this,target:this})}remove(t){const e=this.items_.indexOf(t);if(e<0)return;this.items_.splice(e,1),this.cache_.delete(t);const i=this.extract_(t);i&&(i.allItems().forEach(t=>{this.cache_.delete(t)}),i.emitter.off("add",this.onSubListAdd_),i.emitter.off("remove",this.onSubListRemove_)),this.emitter.emit("remove",{index:e,item:t,root:this,target:this})}onSubListAdd_(t){this.cache_.add(t.item),this.emitter.emit("add",{index:t.index,item:t.item,root:this,target:t.target})}onSubListRemove_(t){this.cache_.delete(t.item),this.emitter.emit("remove",{index:t.index,item:t.item,root:this,target:t.target})}};function ma(t){return ua(t)?t.rackController.rack.bcSet_:null}var ba=class{constructor(t){var e,i;this.emitter=new Ar,this.onBladePositionsChange_=this.onBladePositionsChange_.bind(this),this.onSetAdd_=this.onSetAdd_.bind(this),this.onSetRemove_=this.onSetRemove_.bind(this),this.onChildDispose_=this.onChildDispose_.bind(this),this.onChildPositionsChange_=this.onChildPositionsChange_.bind(this),this.onChildValueChange_=this.onChildValueChange_.bind(this),this.onChildViewPropsChange_=this.onChildViewPropsChange_.bind(this),this.onRackLayout_=this.onRackLayout_.bind(this),this.onRackValueChange_=this.onRackValueChange_.bind(this),this.blade_=null!==(e=t.blade)&&void 0!==e?e:null,null===(i=this.blade_)||void 0===i||i.value("positions").emitter.on("change",this.onBladePositionsChange_),this.viewProps=t.viewProps,this.bcSet_=new va(ma),this.bcSet_.emitter.on("add",this.onSetAdd_),this.bcSet_.emitter.on("remove",this.onSetRemove_)}get children(){return this.bcSet_.items}add(t,e){var i;null===(i=t.parent)||void 0===i||i.remove(t),t.parent=this,this.bcSet_.add(t,e)}remove(t){t.parent=null,this.bcSet_.remove(t)}find(t){return this.bcSet_.allItems().filter(t)}onSetAdd_(t){this.updatePositions_();const e=t.target===t.root;if(this.emitter.emit("add",{bladeController:t.item,index:t.index,root:e,sender:this}),!e)return;const i=t.item;if(i.viewProps.emitter.on("change",this.onChildViewPropsChange_),i.blade.value("positions").emitter.on("change",this.onChildPositionsChange_),i.viewProps.handleDispose(this.onChildDispose_),jo(i))i.value.emitter.on("change",this.onChildValueChange_);else if(ua(i)){const t=i.rackController.rack;if(t){const e=t.emitter;e.on("layout",this.onRackLayout_),e.on("valuechange",this.onRackValueChange_)}}}onSetRemove_(t){this.updatePositions_();const e=t.target===t.root;if(this.emitter.emit("remove",{bladeController:t.item,root:e,sender:this}),!e)return;const i=t.item;if(jo(i))i.value.emitter.off("change",this.onChildValueChange_);else if(ua(i)){const t=i.rackController.rack;if(t){const e=t.emitter;e.off("layout",this.onRackLayout_),e.off("valuechange",this.onRackValueChange_)}}}updatePositions_(){const t=this.bcSet_.items.filter(t=>!t.viewProps.get("hidden")),e=t[0],i=t[t.length-1];this.bcSet_.items.forEach(t=>{const n=[];t===e&&(n.push("first"),this.blade_&&!this.blade_.get("positions").includes("veryfirst")||n.push("veryfirst")),t===i&&(n.push("last"),this.blade_&&!this.blade_.get("positions").includes("verylast")||n.push("verylast")),t.blade.set("positions",n)})}onChildPositionsChange_(){this.updatePositions_(),this.emitter.emit("layout",{sender:this})}onChildViewPropsChange_(t){this.updatePositions_(),this.emitter.emit("layout",{sender:this})}onChildDispose_(){this.bcSet_.items.filter(t=>t.viewProps.get("disposed")).forEach(t=>{this.bcSet_.remove(t)})}onChildValueChange_(t){const e=function(t,e){for(let i=0;i{for(let t=this.rack.children.length-1;t>=0;t--)this.rack.children[t].viewProps.set("disposed",!0)})}onRackAdd_(t){t.root&&zo(this.element,t.bladeController.view.element,t.index)}onRackRemove_(t){t.root&&Ro(t.bladeController.view.element)}};function wa(){return new Rr({positions:zr([],{equals:Lr})})}var _a=class t extends Rr{constructor(t){super(t)}static create(e){const i={completed:!0,expanded:e,expandedHeight:null,shouldFixHeight:!1,temporaryExpanded:null};return new t(Rr.createCore(i))}get styleExpanded(){var t;return null!==(t=this.get("temporaryExpanded"))&&void 0!==t?t:this.get("expanded")}get styleHeight(){if(!this.styleExpanded)return"0";const t=this.get("expandedHeight");return this.get("shouldFixHeight")&&!Er(t)?`${t}px`:"auto"}bindExpandedClass(t,e){const i=()=>{this.styleExpanded?t.classList.add(e):t.classList.remove(e)};Uo(this,"expanded",i),Uo(this,"temporaryExpanded",i)}cleanUpTransition(){this.set("shouldFixHeight",!1),this.set("expandedHeight",null),this.set("completed",!0)}};function fa(t,e){e.style.height=t.styleHeight}function xa(t,e){t.value("expanded").emitter.on("beforechange",()=>{if(t.set("completed",!1),Er(t.get("expandedHeight"))){const i=function(t,e){let i=0;return function(n){const s=n.style.transition;n.style.transition="none",t.set("expandedHeight",null),t.set("temporaryExpanded",!0),Ao(e),i=e.clientHeight,t.set("temporaryExpanded",null),Ao(e),n.style.transition=s}(e),i}(t,e);i>0&&t.set("expandedHeight",i)}t.set("shouldFixHeight",!0),Ao(e)}),t.emitter.on("change",()=>{fa(t,e)}),fa(t,e),e.addEventListener("transitionend",e=>{"height"===e.propertyName&&t.cleanUpTransition()})}var Ca=class extends ca{constructor(t,e){super(t,e),this.emitter_=new Ar,this.controller.foldable.value("expanded").emitter.on("change",t=>{this.emitter_.emit("fold",new Co(this,t.sender.rawValue))}),this.rackApi_.on("change",t=>{this.emitter_.emit("change",t)})}get expanded(){return this.controller.foldable.get("expanded")}set expanded(t){this.controller.foldable.set("expanded",t)}get title(){return this.controller.props.get("title")}set title(t){this.controller.props.set("title",t)}get children(){return this.rackApi_.children}addBinding(t,e,i){return this.rackApi_.addBinding(t,e,i)}addFolder(t){return this.rackApi_.addFolder(t)}addButton(t){return this.rackApi_.addButton(t)}addTab(t){return this.rackApi_.addTab(t)}add(t,e){return this.rackApi_.add(t,e)}remove(t){this.rackApi_.remove(t)}addBlade(t){return this.rackApi_.addBlade(t)}on(t,e){const i=e.bind(this);return this.emitter_.on(t,t=>{i(t)}),this}refresh(){this.rackApi_.refresh()}},ya=$o("cnt"),Pa=class{constructor(t,e){var i;this.className_=$o(null!==(i=e.viewName)&&void 0!==i?i:"fld"),this.element=t.createElement("div"),this.element.classList.add(this.className_(),ya()),e.viewProps.bindClassModifiers(this.element),this.foldable_=e.foldable,this.foldable_.bindExpandedClass(this.element,this.className_(void 0,"expanded")),Uo(this.foldable_,"completed",ia(this.element,this.className_(void 0,"cpl")));const n=t.createElement("button");n.classList.add(this.className_("b")),Uo(e.props,"title",t=>{Er(t)?this.element.classList.add(this.className_(void 0,"not")):this.element.classList.remove(this.className_(void 0,"not"))}),e.viewProps.bindDisabled(n),this.element.appendChild(n),this.buttonElement=n;const s=t.createElement("div");s.classList.add(this.className_("i")),this.element.appendChild(s);const r=t.createElement("div");r.classList.add(this.className_("t")),na(e.props.value("title"),r),this.buttonElement.appendChild(r),this.titleElement=r;const o=t.createElement("div");o.classList.add(this.className_("m")),this.buttonElement.appendChild(o);const a=t.createElement("div");a.classList.add(this.className_("c")),this.element.appendChild(a),this.containerElement=a}},Ea=class extends da{constructor(t,e){var i;const n=_a.create(null===(i=e.expanded)||void 0===i||i),s=new Pa(t,{foldable:n,props:e.props,viewName:e.root?"rot":void 0,viewProps:e.viewProps});super(Object.assign(Object.assign({},e),{rackController:new ga({blade:e.blade,element:s.containerElement,root:e.root,viewProps:e.viewProps}),view:s})),this.onTitleClick_=this.onTitleClick_.bind(this),this.props=e.props,this.foldable=n,xa(this.foldable,this.view.containerElement),this.rackController.rack.emitter.on("add",()=>{this.foldable.cleanUpTransition()}),this.rackController.rack.emitter.on("remove",()=>{this.foldable.cleanUpTransition()}),this.view.buttonElement.addEventListener("click",this.onTitleClick_)}get document(){return this.view.element.ownerDocument}importState(t){return Mo(t,t=>super.importState(t),t=>({expanded:t.required.boolean,title:t.optional.string}),t=>(this.foldable.set("expanded",t.expanded),this.props.set("title",t.title),!0))}exportState(){return So(()=>super.exportState(),{expanded:this.foldable.get("expanded"),title:this.props.get("title")})}onTitleClick_(){this.foldable.set("expanded",!this.foldable.get("expanded"))}};pa({id:"folder",type:"blade",accept(t){const e=Lo(t,t=>({title:t.required.string,view:t.required.constant("folder"),expanded:t.optional.boolean}));return e?{params:e}:null},controller:t=>new Ea(t.document,{blade:t.blade,expanded:t.params.expanded,props:Rr.fromObject({title:t.params.title}),viewProps:t.viewProps}),api:t=>t.controller instanceof Ea?new Ca(t.controller,t.pool):null});var ka=$o("");function Va(t,e){return ia(t,ka(void 0,e))}var La=class t extends Rr{constructor(t){var e,i;super(t),this.onDisabledChange_=this.onDisabledChange_.bind(this),this.onParentChange_=this.onParentChange_.bind(this),this.onParentGlobalDisabledChange_=this.onParentGlobalDisabledChange_.bind(this),[this.globalDisabled_,this.setGlobalDisabled_]=(i=zr(this.getGlobalDisabled_()),[new Tr(i),(t,e)=>{i.setRawValue(t,e)}]),this.value("disabled").emitter.on("change",this.onDisabledChange_),this.value("parent").emitter.on("change",this.onParentChange_),null===(e=this.get("parent"))||void 0===e||e.globalDisabled.emitter.on("change",this.onParentGlobalDisabledChange_)}static create(e){var i,n,s;const r=null!=e?e:{};return new t(Rr.createCore({disabled:null!==(i=r.disabled)&&void 0!==i&&i,disposed:!1,hidden:null!==(n=r.hidden)&&void 0!==n&&n,parent:null!==(s=r.parent)&&void 0!==s?s:null}))}get globalDisabled(){return this.globalDisabled_}bindClassModifiers(t){Io(this.globalDisabled_,Va(t,"disabled")),Uo(this,"hidden",Va(t,"hidden"))}bindDisabled(t){Io(this.globalDisabled_,e=>{t.disabled=e})}bindTabIndex(t){Io(this.globalDisabled_,e=>{t.tabIndex=e?-1:0})}handleDispose(t){this.value("disposed").emitter.on("change",e=>{e&&t()})}importState(t){this.set("disabled",t.disabled),this.set("hidden",t.hidden)}exportState(){return{disabled:this.get("disabled"),hidden:this.get("hidden")}}getGlobalDisabled_(){const t=this.get("parent");return!!t&&t.globalDisabled.rawValue||this.get("disabled")}updateGlobalDisabled_(){this.setGlobalDisabled_(this.getGlobalDisabled_())}onDisabledChange_(){this.updateGlobalDisabled_()}onParentGlobalDisabledChange_(){this.updateGlobalDisabled_()}onParentChange_(t){var e;const i=t.previousRawValue;null==i||i.globalDisabled.emitter.off("change",this.onParentGlobalDisabledChange_),null===(e=this.get("parent"))||void 0===e||e.globalDisabled.emitter.on("change",this.onParentGlobalDisabledChange_),this.updateGlobalDisabled_()}},Ma=$o("tbp"),Sa=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(Ma()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("div");i.classList.add(Ma("c")),this.element.appendChild(i),this.containerElement=i}},ja=$o("tbi"),Da=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(ja()),e.viewProps.bindClassModifiers(this.element),Uo(e.props,"selected",t=>{t?this.element.classList.add(ja(void 0,"sel")):this.element.classList.remove(ja(void 0,"sel"))});const i=t.createElement("button");i.classList.add(ja("b")),e.viewProps.bindDisabled(i),this.element.appendChild(i),this.buttonElement=i;const n=t.createElement("div");n.classList.add(ja("t")),na(e.props.value("title"),n),this.buttonElement.appendChild(n),this.titleElement=n}},Aa=class{constructor(t,e){this.emitter=new Ar,this.onClick_=this.onClick_.bind(this),this.props=e.props,this.viewProps=e.viewProps,this.view=new Da(t,{props:e.props,viewProps:e.viewProps}),this.view.buttonElement.addEventListener("click",this.onClick_)}onClick_(){this.emitter.emit("click",{sender:this})}},Oa=class extends da{constructor(t,e){const i=new Sa(t,{viewProps:e.viewProps});super(Object.assign(Object.assign({},e),{rackController:new ga({blade:e.blade,element:i.containerElement,viewProps:e.viewProps}),view:i})),this.onItemClick_=this.onItemClick_.bind(this),this.ic_=new Aa(t,{props:e.itemProps,viewProps:La.create()}),this.ic_.emitter.on("click",this.onItemClick_),this.props=e.props,Uo(this.props,"selected",t=>{this.itemController.props.set("selected",t),this.viewProps.set("hidden",!t)})}get itemController(){return this.ic_}importState(t){return Mo(t,t=>super.importState(t),t=>({selected:t.required.boolean,title:t.required.string}),t=>(this.ic_.props.set("selected",t.selected),this.ic_.props.set("title",t.title),!0))}exportState(){return So(()=>super.exportState(),{selected:this.ic_.props.get("selected"),title:this.ic_.props.get("title")})}onItemClick_(){this.props.set("selected",!0)}},Ba=class extends ca{constructor(t,e){super(t,e),this.emitter_=new Ar,this.onSelect_=this.onSelect_.bind(this),this.pool_=e,this.rackApi_.on("change",t=>{this.emitter_.emit("change",t)}),this.controller.tab.selectedIndex.emitter.on("change",this.onSelect_)}get pages(){return this.rackApi_.children}addPage(t){const e=this.controller.view.element.ownerDocument,i=new Oa(e,{blade:wa(),itemProps:Rr.fromObject({selected:!1,title:t.title}),props:Rr.fromObject({selected:!1}),viewProps:La.create()}),n=this.pool_.createApi(i);return this.rackApi_.add(n,t.index)}removePage(t){this.rackApi_.remove(this.rackApi_.children[t])}on(t,e){const i=e.bind(this);return this.emitter_.on(t,t=>{i(t)}),this}onSelect_(t){this.emitter_.emit("select",new yo(this,t.rawValue))}},Ta=class extends ca{get title(){var t;return null!==(t=this.controller.itemController.props.get("title"))&&void 0!==t?t:""}set title(t){this.controller.itemController.props.set("title",t)}get selected(){return this.controller.props.get("selected")}set selected(t){this.controller.props.set("selected",t)}get children(){return this.rackApi_.children}addButton(t){return this.rackApi_.addButton(t)}addFolder(t){return this.rackApi_.addFolder(t)}addTab(t){return this.rackApi_.addTab(t)}add(t,e){this.rackApi_.add(t,e)}remove(t){this.rackApi_.remove(t)}addBinding(t,e,i){return this.rackApi_.addBinding(t,e,i)}addBlade(t){return this.rackApi_.addBlade(t)}refresh(){this.rackApi_.refresh()}},za=class{constructor(){this.onItemSelectedChange_=this.onItemSelectedChange_.bind(this),this.empty=zr(!0),this.selectedIndex=zr(-1),this.items_=[]}add(t,e){const i=null!=e?e:this.items_.length;this.items_.splice(i,0,t),t.emitter.on("change",this.onItemSelectedChange_),this.keepSelection_()}remove(t){const e=this.items_.indexOf(t);e<0||(this.items_.splice(e,1),t.emitter.off("change",this.onItemSelectedChange_),this.keepSelection_())}keepSelection_(){if(0===this.items_.length)return this.selectedIndex.rawValue=-1,void(this.empty.rawValue=!0);const t=this.items_.findIndex(t=>t.rawValue);t<0?(this.items_.forEach((t,e)=>{t.rawValue=0===e}),this.selectedIndex.rawValue=0):(this.items_.forEach((e,i)=>{e.rawValue=i===t}),this.selectedIndex.rawValue=t),this.empty.rawValue=!1}onItemSelectedChange_(t){if(t.rawValue){const e=this.items_.findIndex(e=>e===t.sender);this.items_.forEach((t,i)=>{t.rawValue=i===e}),this.selectedIndex.rawValue=e}else this.keepSelection_()}},Ra=$o("tab"),Na=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(Ra(),ya()),e.viewProps.bindClassModifiers(this.element),Io(e.empty,ia(this.element,Ra(void 0,"nop")));const i=t.createElement("div");i.classList.add(Ra("t")),this.element.appendChild(i),this.itemsElement=i;const n=t.createElement("div");n.classList.add(Ra("i")),this.element.appendChild(n);const s=t.createElement("div");s.classList.add(Ra("c")),this.element.appendChild(s),this.contentsElement=s}},Ka=class extends da{constructor(t,e){const i=new za,n=new Na(t,{empty:i.empty,viewProps:e.viewProps});super({blade:e.blade,rackController:new ga({blade:e.blade,element:n.contentsElement,viewProps:e.viewProps}),view:n}),this.onRackAdd_=this.onRackAdd_.bind(this),this.onRackRemove_=this.onRackRemove_.bind(this);const s=this.rackController.rack;s.emitter.on("add",this.onRackAdd_),s.emitter.on("remove",this.onRackRemove_),this.tab=i}add(t,e){this.rackController.rack.add(t,e)}remove(t){this.rackController.rack.remove(this.rackController.rack.children[t])}onRackAdd_(t){if(!t.root)return;const e=t.bladeController;zo(this.view.itemsElement,e.itemController.view.element,t.index),e.itemController.viewProps.set("parent",this.viewProps),this.tab.add(e.props.value("selected"))}onRackRemove_(t){if(!t.root)return;const e=t.bladeController;Ro(e.itemController.view.element),e.itemController.viewProps.set("parent",null),this.tab.remove(e.props.value("selected"))}};pa({id:"tab",type:"blade",accept(t){const e=Lo(t,t=>({pages:t.required.array(t.required.object({title:t.required.string})),view:t.required.constant("tab")}));return e&&0!==e.pages.length?{params:e}:null},controller(t){const e=new Ka(t.document,{blade:t.blade,viewProps:t.viewProps});return t.params.pages.forEach(i=>{const n=new Oa(t.document,{blade:wa(),itemProps:Rr.fromObject({selected:!1,title:i.title}),props:Rr.fromObject({selected:!1}),viewProps:La.create()});e.add(n)}),e},api:t=>t.controller instanceof Ka?new Ba(t.controller,t.pool):t.controller instanceof Oa?new Ta(t.controller,t.pool):null});var Ia=class extends Po{get options(){return this.controller.valueController.props.get("options")}set options(t){this.controller.valueController.props.set("options",t)}},Ua=class{constructor(){this.disabled=!1,this.emitter=new Ar}dispose(){}tick(){this.disabled||this.emitter.emit("tick",{sender:this})}},Fa=class{constructor(t,e){this.disabled_=!1,this.timerId_=null,this.onTick_=this.onTick_.bind(this),this.doc_=t,this.emitter=new Ar,this.interval_=e,this.setTimer_()}get disabled(){return this.disabled_}set disabled(t){this.disabled_=t,this.disabled_?this.clearTimer_():this.setTimer_()}dispose(){this.clearTimer_()}clearTimer_(){if(null===this.timerId_)return;const t=this.doc_.defaultView;t&&t.clearInterval(this.timerId_),this.timerId_=null}setTimer_(){if(this.clearTimer_(),this.interval_<=0)return;const t=this.doc_.defaultView;t&&(this.timerId_=t.setInterval(this.onTick_,this.interval_))}onTick_(){this.disabled_||this.emitter.emit("tick",{sender:this})}},$a=class{constructor(t){this.constraints=t}constrain(t){return this.constraints.reduce((t,e)=>e.constrain(t),t)}};function qa(t,e){if(t instanceof e)return t;if(t instanceof $a){const i=t.constraints.reduce((t,i)=>t||(i instanceof e?i:null),null);if(i)return i}return null}var Ha=class{constructor(t){this.values=Rr.fromObject({options:t})}constrain(t){const e=this.values.get("options");return 0===e.length||e.filter(e=>e.value===t).length>0?t:e[0].value}};function Ga(t){var e;const i=Vo;return Array.isArray(t)?null===(e=Lo({items:t},t=>({items:t.required.array(t.required.object({text:t.required.string,value:t.required.raw}))})))||void 0===e?void 0:e.items:"object"==typeof t?i.required.raw(t).value:void 0}function Ya(t){if(Array.isArray(t))return t;const e=[];return Object.keys(t).forEach(i=>{e.push({text:i,value:t[i]})}),e}function Xa(t){return Er(t)?null:new Ha(Ya(t))}var Wa=$o("lst"),Qa=class{constructor(t,e){this.onValueChange_=this.onValueChange_.bind(this),this.props_=e.props,this.element=t.createElement("div"),this.element.classList.add(Wa()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("select");i.classList.add(Wa("s")),e.viewProps.bindDisabled(i),this.element.appendChild(i),this.selectElement=i;const n=t.createElement("div");n.classList.add(Wa("m")),n.appendChild(To(t,"dropdown")),this.element.appendChild(n),e.value.emitter.on("change",this.onValueChange_),this.value_=e.value,Uo(this.props_,"options",e=>{No(this.selectElement),e.forEach(e=>{const i=t.createElement("option");i.textContent=e.text,this.selectElement.appendChild(i)}),this.update_()})}update_(){const t=this.props_.get("options").map(t=>t.value);this.selectElement.selectedIndex=t.indexOf(this.value_.rawValue)}onValueChange_(){this.update_()}},Ja=class{constructor(t,e){this.onSelectChange_=this.onSelectChange_.bind(this),this.props=e.props,this.value=e.value,this.viewProps=e.viewProps,this.view=new Qa(t,{props:this.props,value:this.value,viewProps:this.viewProps}),this.view.selectElement.addEventListener("change",this.onSelectChange_)}onSelectChange_(t){const e=t.currentTarget;this.value.rawValue=this.props.get("options")[e.selectedIndex].value}importProps(t){return Mo(t,null,t=>({options:t.required.custom(Ga)}),t=>(this.props.set("options",Ya(t.options)),!0))}exportProps(){return So(null,{options:this.props.get("options")})}},Za=$o("pop"),tl=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(Za()),e.viewProps.bindClassModifiers(this.element),Io(e.shows,ia(this.element,Za(void 0,"v")))}},el=class{constructor(t,e){this.shows=zr(!1),this.viewProps=e.viewProps,this.view=new tl(t,{shows:this.shows,viewProps:this.viewProps})}},il=$o("txt"),nl=class{constructor(t,e){this.onChange_=this.onChange_.bind(this),this.element=t.createElement("div"),this.element.classList.add(il()),e.viewProps.bindClassModifiers(this.element),this.props_=e.props,this.props_.emitter.on("change",this.onChange_);const i=t.createElement("input");i.classList.add(il("i")),i.type="text",e.viewProps.bindDisabled(i),this.element.appendChild(i),this.inputElement=i,e.value.emitter.on("change",this.onChange_),this.value_=e.value,this.refresh()}refresh(){const t=this.props_.get("formatter");this.inputElement.value=t(this.value_.rawValue)}onChange_(){this.refresh()}},sl=class{constructor(t,e){this.onInputChange_=this.onInputChange_.bind(this),this.parser_=e.parser,this.props=e.props,this.value=e.value,this.viewProps=e.viewProps,this.view=new nl(t,{props:e.props,value:this.value,viewProps:this.viewProps}),this.view.inputElement.addEventListener("change",this.onInputChange_)}onInputChange_(t){const e=t.currentTarget.value,i=this.parser_(e);Er(i)||(this.value.rawValue=i),this.view.refresh()}};function rl(t){return"false"!==t&&!!t}function ol(t){return function(t){return String(t)}(t)}var al=ro(0);function ll(t){return al(t)+"%"}function pl(t){return String(t)}function hl(t){return t}function cl({primary:t,secondary:e,forward:i,backward:n}){let s=!1;function r(t){s||(s=!0,t(),s=!1)}t.emitter.on("change",n=>{r(()=>{e.setRawValue(i(t.rawValue,e.rawValue),n.options)})}),e.emitter.on("change",s=>{r(()=>{t.setRawValue(n(t.rawValue,e.rawValue),s.options)}),r(()=>{e.setRawValue(i(t.rawValue,e.rawValue),s.options)})}),r(()=>{e.setRawValue(i(t.rawValue,e.rawValue),{forceEmit:!1,last:!0})})}function dl(t,e){const i=t*(e.altKey?.1:1)*(e.shiftKey?10:1);return e.upKey?+i:e.downKey?-i:0}function ul(t){return{altKey:t.altKey,downKey:"ArrowDown"===t.key,shiftKey:t.shiftKey,upKey:"ArrowUp"===t.key}}function vl(t){return{altKey:t.altKey,downKey:"ArrowLeft"===t.key,shiftKey:t.shiftKey,upKey:"ArrowRight"===t.key}}function ml(t){return function(t){return"ArrowUp"===t||"ArrowDown"===t}(t)||"ArrowLeft"===t||"ArrowRight"===t}function bl(t,e){var i,n;const s=e.ownerDocument.defaultView,r=e.getBoundingClientRect();return{x:t.pageX-((null!==(i=s&&s.scrollX)&&void 0!==i?i:0)+r.left),y:t.pageY-((null!==(n=s&&s.scrollY)&&void 0!==n?n:0)+r.top)}}var gl=class{constructor(t){this.lastTouch_=null,this.onDocumentMouseMove_=this.onDocumentMouseMove_.bind(this),this.onDocumentMouseUp_=this.onDocumentMouseUp_.bind(this),this.onMouseDown_=this.onMouseDown_.bind(this),this.onTouchEnd_=this.onTouchEnd_.bind(this),this.onTouchMove_=this.onTouchMove_.bind(this),this.onTouchStart_=this.onTouchStart_.bind(this),this.elem_=t,this.emitter=new Ar,t.addEventListener("touchstart",this.onTouchStart_,{passive:!1}),t.addEventListener("touchmove",this.onTouchMove_,{passive:!0}),t.addEventListener("touchend",this.onTouchEnd_),t.addEventListener("mousedown",this.onMouseDown_)}computePosition_(t){const e=this.elem_.getBoundingClientRect();return{bounds:{width:e.width,height:e.height},point:t?{x:t.x,y:t.y}:null}}onMouseDown_(t){var e;t.preventDefault(),null===(e=t.currentTarget)||void 0===e||e.focus();const i=this.elem_.ownerDocument;i.addEventListener("mousemove",this.onDocumentMouseMove_),i.addEventListener("mouseup",this.onDocumentMouseUp_),this.emitter.emit("down",{altKey:t.altKey,data:this.computePosition_(bl(t,this.elem_)),sender:this,shiftKey:t.shiftKey})}onDocumentMouseMove_(t){this.emitter.emit("move",{altKey:t.altKey,data:this.computePosition_(bl(t,this.elem_)),sender:this,shiftKey:t.shiftKey})}onDocumentMouseUp_(t){const e=this.elem_.ownerDocument;e.removeEventListener("mousemove",this.onDocumentMouseMove_),e.removeEventListener("mouseup",this.onDocumentMouseUp_),this.emitter.emit("up",{altKey:t.altKey,data:this.computePosition_(bl(t,this.elem_)),sender:this,shiftKey:t.shiftKey})}onTouchStart_(t){t.preventDefault();const e=t.targetTouches.item(0),i=this.elem_.getBoundingClientRect();this.emitter.emit("down",{altKey:t.altKey,data:this.computePosition_(e?{x:e.clientX-i.left,y:e.clientY-i.top}:void 0),sender:this,shiftKey:t.shiftKey}),this.lastTouch_=e}onTouchMove_(t){const e=t.targetTouches.item(0),i=this.elem_.getBoundingClientRect();this.emitter.emit("move",{altKey:t.altKey,data:this.computePosition_(e?{x:e.clientX-i.left,y:e.clientY-i.top}:void 0),sender:this,shiftKey:t.shiftKey}),this.lastTouch_=e}onTouchEnd_(t){var e;const i=null!==(e=t.targetTouches.item(0))&&void 0!==e?e:this.lastTouch_,n=this.elem_.getBoundingClientRect();this.emitter.emit("up",{altKey:t.altKey,data:this.computePosition_(i?{x:i.clientX-n.left,y:i.clientY-n.top}:void 0),sender:this,shiftKey:t.shiftKey})}},wl=$o("txt"),_l=class{constructor(t,e){this.onChange_=this.onChange_.bind(this),this.props_=e.props,this.props_.emitter.on("change",this.onChange_),this.element=t.createElement("div"),this.element.classList.add(wl(),wl(void 0,"num")),e.arrayPosition&&this.element.classList.add(wl(void 0,e.arrayPosition)),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("input");i.classList.add(wl("i")),i.type="text",e.viewProps.bindDisabled(i),this.element.appendChild(i),this.inputElement=i,this.onDraggingChange_=this.onDraggingChange_.bind(this),this.dragging_=e.dragging,this.dragging_.emitter.on("change",this.onDraggingChange_),this.element.classList.add(wl()),this.inputElement.classList.add(wl("i"));const n=t.createElement("div");n.classList.add(wl("k")),this.element.appendChild(n),this.knobElement=n;const s=t.createElementNS(Do,"svg");s.classList.add(wl("g")),this.knobElement.appendChild(s);const r=t.createElementNS(Do,"path");r.classList.add(wl("gb")),s.appendChild(r),this.guideBodyElem_=r;const o=t.createElementNS(Do,"path");o.classList.add(wl("gh")),s.appendChild(o),this.guideHeadElem_=o;const a=t.createElement("div");a.classList.add($o("tt")()),this.knobElement.appendChild(a),this.tooltipElem_=a,e.value.emitter.on("change",this.onChange_),this.value=e.value,this.refresh()}onDraggingChange_(t){if(null===t.rawValue)return void this.element.classList.remove(wl(void 0,"drg"));this.element.classList.add(wl(void 0,"drg"));const e=t.rawValue/this.props_.get("pointerScale"),i=e+(e>0?-1:e<0?1:0),n=lo(-i,-4,4);this.guideHeadElem_.setAttributeNS(null,"d",[`M ${i+n},0 L${i},4 L${i+n},8`,`M ${e},-1 L${e},9`].join(" ")),this.guideBodyElem_.setAttributeNS(null,"d",`M 0,4 L${e},4`);const s=this.props_.get("formatter");this.tooltipElem_.textContent=s(this.value.rawValue),this.tooltipElem_.style.left=`${e}px`}refresh(){const t=this.props_.get("formatter");this.inputElement.value=t(this.value.rawValue)}onChange_(){this.refresh()}},fl=class{constructor(t,e){var i;this.originRawValue_=0,this.onInputChange_=this.onInputChange_.bind(this),this.onInputKeyDown_=this.onInputKeyDown_.bind(this),this.onInputKeyUp_=this.onInputKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.parser_=e.parser,this.props=e.props,this.sliderProps_=null!==(i=e.sliderProps)&&void 0!==i?i:null,this.value=e.value,this.viewProps=e.viewProps,this.dragging_=zr(null),this.view=new _l(t,{arrayPosition:e.arrayPosition,dragging:this.dragging_,props:this.props,value:this.value,viewProps:this.viewProps}),this.view.inputElement.addEventListener("change",this.onInputChange_),this.view.inputElement.addEventListener("keydown",this.onInputKeyDown_),this.view.inputElement.addEventListener("keyup",this.onInputKeyUp_);const n=new gl(this.view.knobElement);n.emitter.on("down",this.onPointerDown_),n.emitter.on("move",this.onPointerMove_),n.emitter.on("up",this.onPointerUp_)}constrainValue_(t){var e,i;const n=null===(e=this.sliderProps_)||void 0===e?void 0:e.get("min"),s=null===(i=this.sliderProps_)||void 0===i?void 0:i.get("max");let r=t;return void 0!==n&&(r=Math.max(r,n)),void 0!==s&&(r=Math.min(r,s)),r}onInputChange_(t){const e=t.currentTarget.value,i=this.parser_(e);Er(i)||(this.value.rawValue=this.constrainValue_(i)),this.view.refresh()}onInputKeyDown_(t){const e=dl(this.props.get("keyScale"),ul(t));0!==e&&this.value.setRawValue(this.constrainValue_(this.value.rawValue+e),{forceEmit:!1,last:!1})}onInputKeyUp_(t){0!==dl(this.props.get("keyScale"),ul(t))&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}onPointerDown_(){this.originRawValue_=this.value.rawValue,this.dragging_.rawValue=0}computeDraggingValue_(t){if(!t.point)return null;const e=t.point.x-t.bounds.width/2;return this.constrainValue_(this.originRawValue_+e*this.props.get("pointerScale"))}onPointerMove_(t){const e=this.computeDraggingValue_(t.data);null!==e&&(this.value.setRawValue(e,{forceEmit:!1,last:!1}),this.dragging_.rawValue=this.value.rawValue-this.originRawValue_)}onPointerUp_(t){const e=this.computeDraggingValue_(t.data);null!==e&&(this.value.setRawValue(e,{forceEmit:!0,last:!0}),this.dragging_.rawValue=null)}},xl=$o("sld"),Cl=class{constructor(t,e){this.onChange_=this.onChange_.bind(this),this.props_=e.props,this.props_.emitter.on("change",this.onChange_),this.element=t.createElement("div"),this.element.classList.add(xl()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("div");i.classList.add(xl("t")),e.viewProps.bindTabIndex(i),this.element.appendChild(i),this.trackElement=i;const n=t.createElement("div");n.classList.add(xl("k")),this.trackElement.appendChild(n),this.knobElement=n,e.value.emitter.on("change",this.onChange_),this.value=e.value,this.update_()}update_(){const t=lo(oo(this.value.rawValue,this.props_.get("min"),this.props_.get("max"),0,100),0,100);this.knobElement.style.width=`${t}%`}onChange_(){this.update_()}},yl=class{constructor(t,e){this.onKeyDown_=this.onKeyDown_.bind(this),this.onKeyUp_=this.onKeyUp_.bind(this),this.onPointerDownOrMove_=this.onPointerDownOrMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.value=e.value,this.viewProps=e.viewProps,this.props=e.props,this.view=new Cl(t,{props:this.props,value:this.value,viewProps:this.viewProps}),this.ptHandler_=new gl(this.view.trackElement),this.ptHandler_.emitter.on("down",this.onPointerDownOrMove_),this.ptHandler_.emitter.on("move",this.onPointerDownOrMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.trackElement.addEventListener("keydown",this.onKeyDown_),this.view.trackElement.addEventListener("keyup",this.onKeyUp_)}handlePointerEvent_(t,e){t.point&&this.value.setRawValue(oo(lo(t.point.x,0,t.bounds.width),0,t.bounds.width,this.props.get("min"),this.props.get("max")),e)}onPointerDownOrMove_(t){this.handlePointerEvent_(t.data,{forceEmit:!1,last:!1})}onPointerUp_(t){this.handlePointerEvent_(t.data,{forceEmit:!0,last:!0})}onKeyDown_(t){const e=dl(this.props.get("keyScale"),vl(t));0!==e&&this.value.setRawValue(this.value.rawValue+e,{forceEmit:!1,last:!1})}onKeyUp_(t){0!==dl(this.props.get("keyScale"),vl(t))&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}},Pl=$o("sldtxt"),El=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(Pl());const i=t.createElement("div");i.classList.add(Pl("s")),this.sliderView_=e.sliderView,i.appendChild(this.sliderView_.element),this.element.appendChild(i);const n=t.createElement("div");n.classList.add(Pl("t")),this.textView_=e.textView,n.appendChild(this.textView_.element),this.element.appendChild(n)}},kl=class{constructor(t,e){this.value=e.value,this.viewProps=e.viewProps,this.sliderC_=new yl(t,{props:e.sliderProps,value:e.value,viewProps:this.viewProps}),this.textC_=new fl(t,{parser:e.parser,props:e.textProps,sliderProps:e.sliderProps,value:e.value,viewProps:e.viewProps}),this.view=new El(t,{sliderView:this.sliderC_.view,textView:this.textC_.view})}get sliderController(){return this.sliderC_}get textController(){return this.textC_}importProps(t){return Mo(t,null,t=>({max:t.required.number,min:t.required.number}),t=>{const e=this.sliderC_.props;return e.set("max",t.max),e.set("min",t.min),!0})}exportProps(){const t=this.sliderC_.props;return So(null,{max:t.get("max"),min:t.get("min")})}},Vl={containerUnitSize:"cnt-usz"};function Ll(t){return`--${Vl[t]}`}var Ml=class{constructor(t,e){const i=$o(e.viewName);this.element=t.createElement("div"),this.element.classList.add(i()),e.viewProps.bindClassModifiers(this.element)}};function Sl(t){return go(t)}function jl(t){if(Vr(t))return Lo(t,Sl)}function Dl(t,e){if(!t)return;const i=[],n=vo(t,e);n&&i.push(n);const s=mo(t);return s&&i.push(s),new $a(i)}function Al(t){if("inline"===t||"popup"===t)return t}function Ol(t,e){t.write(e)}var Bl=$o("ckb"),Tl=class{constructor(t,e){this.onValueChange_=this.onValueChange_.bind(this),this.element=t.createElement("div"),this.element.classList.add(Bl()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("label");i.classList.add(Bl("l")),this.element.appendChild(i);const n=t.createElement("input");n.classList.add(Bl("i")),n.type="checkbox",i.appendChild(n),this.inputElement=n,e.viewProps.bindDisabled(this.inputElement);const s=t.createElement("div");s.classList.add(Bl("w")),i.appendChild(s);const r=To(t,"check");s.appendChild(r),e.value.emitter.on("change",this.onValueChange_),this.value=e.value,this.update_()}update_(){this.inputElement.checked=this.value.rawValue}onValueChange_(){this.update_()}},zl=class{constructor(t,e){this.onInputChange_=this.onInputChange_.bind(this),this.value=e.value,this.viewProps=e.viewProps,this.view=new Tl(t,{value:this.value,viewProps:this.viewProps}),this.view.inputElement.addEventListener("change",this.onInputChange_)}onInputChange_(t){const e=t.currentTarget;this.value.rawValue=e.checked}};pa({id:"input-bool",type:"input",accept:(t,e)=>{if("boolean"!=typeof t)return null;const i=Lo(e,t=>({options:t.optional.custom(Ga),readonly:t.optional.constant(!1)}));return i?{initialValue:t,params:i}:null},binding:{reader:t=>rl,constraint:t=>function(t){const e=[],i=Xa(t.options);return i&&e.push(i),new $a(e)}(t.params),writer:t=>Ol},controller:t=>{const e=t.document,i=t.value,n=t.constraint,s=n&&qa(n,Ha);return s?new Ja(e,{props:new Rr({options:s.values.value("options")}),value:i,viewProps:t.viewProps}):new zl(e,{value:i,viewProps:t.viewProps})},api:t=>"boolean"!=typeof t.controller.value.rawValue?null:t.controller.valueController instanceof Ja?new Ia(t.controller):null});var Rl=$o("col"),Nl=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(Rl()),e.foldable.bindExpandedClass(this.element,Rl(void 0,"expanded")),Uo(e.foldable,"completed",ia(this.element,Rl(void 0,"cpl")));const i=t.createElement("div");i.classList.add(Rl("h")),this.element.appendChild(i);const n=t.createElement("div");n.classList.add(Rl("s")),i.appendChild(n),this.swatchElement=n;const s=t.createElement("div");if(s.classList.add(Rl("t")),i.appendChild(s),this.textElement=s,"inline"===e.pickerLayout){const e=t.createElement("div");e.classList.add(Rl("p")),this.element.appendChild(e),this.pickerElement=e}else this.pickerElement=null}};function Kl(t,e,i){const n=po(t,360),s=lo(e/100,0,1),r=lo(i/100,0,1),o=r*s,a=o*(1-Math.abs(n/60%2-1)),l=r-o;let p,h,c;return[p,h,c]=n>=0&&n<60?[o,a,0]:n>=60&&n<120?[a,o,0]:n>=120&&n<180?[0,o,a]:n>=180&&n<240?[0,a,o]:n>=240&&n<300?[a,0,o]:[o,0,a],[255*(p+l),255*(h+l),255*(c+l)]}function Il(t){return[t[0],t[1],t[2]]}function Ul(t,e){return[t[0],t[1],t[2],e]}var Fl={hsl:{hsl:(t,e,i)=>[t,e,i],hsv:function(t,e,i){const n=i+e*(100-Math.abs(2*i-100))/200;return[t,0!==n?e*(100-Math.abs(2*i-100))/n:0,i+e*(100-Math.abs(2*i-100))/200]},rgb:function(t,e,i){const n=(t%360+360)%360,s=lo(e/100,0,1),r=lo(i/100,0,1),o=(1-Math.abs(2*r-1))*s,a=o*(1-Math.abs(n/60%2-1)),l=r-o/2;let p,h,c;return[p,h,c]=n>=0&&n<60?[o,a,0]:n>=60&&n<120?[a,o,0]:n>=120&&n<180?[0,o,a]:n>=180&&n<240?[0,a,o]:n>=240&&n<300?[a,0,o]:[o,0,a],[255*(p+l),255*(h+l),255*(c+l)]}},hsv:{hsl:function(t,e,i){const n=100-Math.abs(i*(200-e)/100-100);return[t,0!==n?e*i/n:0,i*(200-e)/200]},hsv:(t,e,i)=>[t,e,i],rgb:Kl},rgb:{hsl:function(t,e,i){const n=lo(t/255,0,1),s=lo(e/255,0,1),r=lo(i/255,0,1),o=Math.max(n,s,r),a=Math.min(n,s,r),l=o-a;let p=0,h=0;const c=(a+o)/2;return 0!==l&&(h=l/(1-Math.abs(o+a-1)),p=n===o?(s-r)/l:s===o?2+(r-n)/l:4+(n-s)/l,p=p/6+(p<0?1:0)),[360*p,100*h,100*c]},hsv:function(t,e,i){const n=lo(t/255,0,1),s=lo(e/255,0,1),r=lo(i/255,0,1),o=Math.max(n,s,r),a=o-Math.min(n,s,r);let l;return l=0===a?0:o===n?((s-r)/a%6+6)%6*60:o===s?60*((r-n)/a+2):60*((n-s)/a+4),[l,100*(0===o?0:a/o),100*o]},rgb:(t,e,i)=>[t,e,i]}};function $l(t,e){return["float"===e?1:"rgb"===t?255:360,"float"===e?1:"rgb"===t?255:100,"float"===e?1:"rgb"===t?255:100]}function ql(t,e,i){var n;const s=$l(e,i);return["rgb"===e?lo(t[0],0,s[0]):(r=t[0],o=s[0],r===o?o:po(r,o)),lo(t[1],0,s[1]),lo(t[2],0,s[2]),lo(null!==(n=t[3])&&void 0!==n?n:1,0,1)];var r,o}function Hl(t,e,i,n){const s=$l(e,i),r=$l(e,n);return t.map((t,e)=>t/s[e]*r[e])}function Gl(t,e,i){const n=Hl(t,e.mode,e.type,"int");return Hl(Fl[e.mode][i.mode](...n),i.mode,"int",i.type)}var Yl=class t{static black(){return new t([0,0,0],"rgb")}constructor(t,e){this.type="int",this.mode=e,this.comps_=ql(t,e,this.type)}getComponents(t){return Ul(Gl(Il(this.comps_),{mode:this.mode,type:this.type},{mode:null!=t?t:this.mode,type:this.type}),this.comps_[3])}toRgbaObject(){const t=this.getComponents("rgb");return{r:t[0],g:t[1],b:t[2],a:t[3]}}},Xl=$o("colp"),Wl=class{constructor(t,e){this.alphaViews_=null,this.element=t.createElement("div"),this.element.classList.add(Xl()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("div");i.classList.add(Xl("hsv"));const n=t.createElement("div");n.classList.add(Xl("sv")),this.svPaletteView_=e.svPaletteView,n.appendChild(this.svPaletteView_.element),i.appendChild(n);const s=t.createElement("div");s.classList.add(Xl("h")),this.hPaletteView_=e.hPaletteView,s.appendChild(this.hPaletteView_.element),i.appendChild(s),this.element.appendChild(i);const r=t.createElement("div");if(r.classList.add(Xl("rgb")),this.textsView_=e.textsView,r.appendChild(this.textsView_.element),this.element.appendChild(r),e.alphaViews){this.alphaViews_={palette:e.alphaViews.palette,text:e.alphaViews.text};const i=t.createElement("div");i.classList.add(Xl("a"));const n=t.createElement("div");n.classList.add(Xl("ap")),n.appendChild(this.alphaViews_.palette.element),i.appendChild(n);const s=t.createElement("div");s.classList.add(Xl("at")),s.appendChild(this.alphaViews_.text.element),i.appendChild(s),this.element.appendChild(i)}}get allFocusableElements(){const t=[this.svPaletteView_.element,this.hPaletteView_.element,this.textsView_.modeSelectElement,...this.textsView_.inputViews.map(t=>t.inputElement)];return this.alphaViews_&&t.push(this.alphaViews_.palette.element,this.alphaViews_.text.inputElement),t}};function Ql(t){return"int"===t?"int":"float"===t?"float":void 0}function Jl(t){return Lo(t,t=>({color:t.optional.object({alpha:t.optional.boolean,type:t.optional.custom(Ql)}),expanded:t.optional.boolean,picker:t.optional.custom(Al),readonly:t.optional.constant(!1)}))}function Zl(t){return t?.1:1}function tp(t){var e;return null===(e=t.color)||void 0===e?void 0:e.type}var ep=class{constructor(t,e){this.type="float",this.mode=e,this.comps_=ql(t,e,this.type)}getComponents(t){return Ul(Gl(Il(this.comps_),{mode:this.mode,type:this.type},{mode:null!=t?t:this.mode,type:this.type}),this.comps_[3])}toRgbaObject(){const t=this.getComponents("rgb");return{r:t[0],g:t[1],b:t[2],a:t[3]}}},ip={int:(t,e)=>new Yl(t,e),float:(t,e)=>new ep(t,e)};function np(t,e,i){return ip[i](t,e)}function sp(t,e){if(t.type===e)return t;if(function(t){return"int"===t.type}(t)&&"float"===e)return function(t){const e=t.getComponents(),i=$l(t.mode,"int");return new ep([oo(e[0],0,i[0],0,1),oo(e[1],0,i[1],0,1),oo(e[2],0,i[2],0,1),e[3]],t.mode)}(t);if(function(t){return"float"===t.type}(t)&&"int"===e)return function(t){const e=t.getComponents(),i=$l(t.mode,"int");return new Yl([Math.round(oo(e[0],0,1,0,i[0])),Math.round(oo(e[1],0,1,0,i[1])),Math.round(oo(e[2],0,1,0,i[2])),e[3]],t.mode)}(t);throw jr.shouldNeverHappen()}function rp(t,e){const i=t.match(/^(.+)%$/);return i?Math.min(.01*parseFloat(i[1])*e,e):Math.min(parseFloat(t),e)}var op={deg:t=>t,grad:t=>360*t/400,rad:t=>360*t/(2*Math.PI),turn:t=>360*t};function ap(t){const e=t.match(/^([0-9.]+?)(deg|grad|rad|turn)$/);if(!e)return parseFloat(t);const i=parseFloat(e[1]);return op[e[2]](i)}function lp(t){const e=t.match(/^rgb\(\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!e)return null;const i=[rp(e[1],255),rp(e[2],255),rp(e[3],255)];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])?null:i}function pp(t){const e=lp(t);return e?new Yl(e,"rgb"):null}function hp(t){const e=t.match(/^rgba\(\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!e)return null;const i=[rp(e[1],255),rp(e[2],255),rp(e[3],255),rp(e[4],1)];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])||isNaN(i[3])?null:i}function cp(t){const e=hp(t);return e?new Yl(e,"rgb"):null}function dp(t){const e=t.match(/^hsl\(\s*([0-9A-Fa-f.]+(?:deg|grad|rad|turn)?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!e)return null;const i=[ap(e[1]),rp(e[2],100),rp(e[3],100)];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])?null:i}function up(t){const e=dp(t);return e?new Yl(e,"hsl"):null}function vp(t){const e=t.match(/^hsla\(\s*([0-9A-Fa-f.]+(?:deg|grad|rad|turn)?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!e)return null;const i=[ap(e[1]),rp(e[2],100),rp(e[3],100),rp(e[4],1)];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])||isNaN(i[3])?null:i}function mp(t){const e=vp(t);return e?new Yl(e,"hsl"):null}function bp(t){const e=t.match(/^#([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])$/);if(e)return[parseInt(e[1]+e[1],16),parseInt(e[2]+e[2],16),parseInt(e[3]+e[3],16)];const i=t.match(/^(?:#|0x)([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})$/);return i?[parseInt(i[1],16),parseInt(i[2],16),parseInt(i[3],16)]:null}function gp(t){const e=bp(t);return e?new Yl(e,"rgb"):null}function wp(t){const e=t.match(/^#?([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])$/);if(e)return[parseInt(e[1]+e[1],16),parseInt(e[2]+e[2],16),parseInt(e[3]+e[3],16),oo(parseInt(e[4]+e[4],16),0,255,0,1)];const i=t.match(/^(?:#|0x)?([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})$/);return i?[parseInt(i[1],16),parseInt(i[2],16),parseInt(i[3],16),oo(parseInt(i[4],16),0,255,0,1)]:null}function _p(t){const e=wp(t);return e?new Yl(e,"rgb"):null}function fp(t){const e=t.match(/^\{\s*r\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*g\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*b\s*:\s*([0-9A-Fa-f.]+%?)\s*\}$/);if(!e)return null;const i=[parseFloat(e[1]),parseFloat(e[2]),parseFloat(e[3])];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])?null:i}function xp(t){return e=>{const i=fp(e);return i?np(i,"rgb",t):null}}function Cp(t){const e=t.match(/^\{\s*r\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*g\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*b\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*a\s*:\s*([0-9A-Fa-f.]+%?)\s*\}$/);if(!e)return null;const i=[parseFloat(e[1]),parseFloat(e[2]),parseFloat(e[3]),parseFloat(e[4])];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])||isNaN(i[3])?null:i}function yp(t){return e=>{const i=Cp(e);return i?np(i,"rgb",t):null}}var Pp=[{parser:bp,result:{alpha:!1,mode:"rgb",notation:"hex"}},{parser:wp,result:{alpha:!0,mode:"rgb",notation:"hex"}},{parser:lp,result:{alpha:!1,mode:"rgb",notation:"func"}},{parser:hp,result:{alpha:!0,mode:"rgb",notation:"func"}},{parser:dp,result:{alpha:!1,mode:"hsl",notation:"func"}},{parser:vp,result:{alpha:!0,mode:"hsl",notation:"func"}},{parser:fp,result:{alpha:!1,mode:"rgb",notation:"object"}},{parser:Cp,result:{alpha:!0,mode:"rgb",notation:"object"}}];function Ep(t){const e=[gp,_p,pp,cp,up,mp];"int"===t&&e.push(xp("int"),yp("int")),"float"===t&&e.push(xp("float"),yp("float"));const i=function(t){return e=>t.reduce((t,i)=>null!==t?t:i(e),null)}(e);return e=>{const n=i(e);return n?sp(n,t):null}}function kp(t){const e=Ep("int");if("string"!=typeof t)return Yl.black();const i=e(t);return null!=i?i:Yl.black()}function Vp(t){const e=lo(Math.floor(t),0,255).toString(16);return 1===e.length?`0${e}`:e}function Lp(t,e="#"){return`${e}${Il(t.getComponents("rgb")).map(Vp).join("")}`}function Mp(t,e="#"){const i=t.getComponents("rgb");return`${e}${[i[0],i[1],i[2],255*i[3]].map(Vp).join("")}`}function Sp(t){const e=ro(0);return`rgb(${Il(sp(t,"int").getComponents("rgb")).map(t=>e(t)).join(", ")})`}function jp(t){const e=ro(2),i=ro(0);return`rgba(${sp(t,"int").getComponents("rgb").map((t,n)=>(3===n?e:i)(t)).join(", ")})`}function Dp(t,e){const i=ro("float"===e?2:0),n=["r","g","b"];return`{${Il(sp(t,e).getComponents("rgb")).map((t,e)=>`${n[e]}: ${i(t)}`).join(", ")}}`}function Ap(t){return e=>Dp(e,t)}function Op(t,e){const i=ro(2),n=ro("float"===e?2:0),s=["r","g","b","a"];return`{${sp(t,e).getComponents("rgb").map((t,e)=>`${s[e]}: ${(3===e?i:n)(t)}`).join(", ")}}`}function Bp(t){return e=>Op(e,t)}var Tp=[{format:{alpha:!1,mode:"rgb",notation:"hex",type:"int"},stringifier:Lp},{format:{alpha:!0,mode:"rgb",notation:"hex",type:"int"},stringifier:Mp},{format:{alpha:!1,mode:"rgb",notation:"func",type:"int"},stringifier:Sp},{format:{alpha:!0,mode:"rgb",notation:"func",type:"int"},stringifier:jp},{format:{alpha:!1,mode:"hsl",notation:"func",type:"int"},stringifier:function(t){const e=[ro(0),ll,ll];return`hsl(${Il(sp(t,"int").getComponents("hsl")).map((t,i)=>e[i](t)).join(", ")})`}},{format:{alpha:!0,mode:"hsl",notation:"func",type:"int"},stringifier:function(t){const e=[ro(0),ll,ll,ro(2)];return`hsla(${sp(t,"int").getComponents("hsl").map((t,i)=>e[i](t)).join(", ")})`}},...["int","float"].reduce((t,e)=>[...t,{format:{alpha:!1,mode:"rgb",notation:"object",type:e},stringifier:Ap(e)},{format:{alpha:!0,mode:"rgb",notation:"object",type:e},stringifier:Bp(e)}],[])];function zp(t){return Tp.reduce((e,i)=>{return e||(n=i.format,s=t,n.alpha===s.alpha&&n.mode===s.mode&&n.notation===s.notation&&n.type===s.type?i.stringifier:null);var n,s},null)}var Rp=$o("apl"),Np=class{constructor(t,e){this.onValueChange_=this.onValueChange_.bind(this),this.value=e.value,this.value.emitter.on("change",this.onValueChange_),this.element=t.createElement("div"),this.element.classList.add(Rp()),e.viewProps.bindClassModifiers(this.element),e.viewProps.bindTabIndex(this.element);const i=t.createElement("div");i.classList.add(Rp("b")),this.element.appendChild(i);const n=t.createElement("div");n.classList.add(Rp("c")),i.appendChild(n),this.colorElem_=n;const s=t.createElement("div");s.classList.add(Rp("m")),this.element.appendChild(s),this.markerElem_=s;const r=t.createElement("div");r.classList.add(Rp("p")),this.markerElem_.appendChild(r),this.previewElem_=r,this.update_()}update_(){const t=this.value.rawValue,e=t.getComponents("rgb"),i=new Yl([e[0],e[1],e[2],0],"rgb"),n=new Yl([e[0],e[1],e[2],255],"rgb"),s=["to right",jp(i),jp(n)];this.colorElem_.style.background=`linear-gradient(${s.join(",")})`,this.previewElem_.style.backgroundColor=jp(t);const r=oo(e[3],0,1,0,100);this.markerElem_.style.left=`${r}%`}onValueChange_(){this.update_()}},Kp=class{constructor(t,e){this.onKeyDown_=this.onKeyDown_.bind(this),this.onKeyUp_=this.onKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.value=e.value,this.viewProps=e.viewProps,this.view=new Np(t,{value:this.value,viewProps:this.viewProps}),this.ptHandler_=new gl(this.view.element),this.ptHandler_.emitter.on("down",this.onPointerDown_),this.ptHandler_.emitter.on("move",this.onPointerMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.element.addEventListener("keydown",this.onKeyDown_),this.view.element.addEventListener("keyup",this.onKeyUp_)}handlePointerEvent_(t,e){if(!t.point)return;const i=t.point.x/t.bounds.width,[n,s,r]=this.value.rawValue.getComponents("hsv");this.value.setRawValue(new Yl([n,s,r,i],"hsv"),e)}onPointerDown_(t){this.handlePointerEvent_(t.data,{forceEmit:!1,last:!1})}onPointerMove_(t){this.handlePointerEvent_(t.data,{forceEmit:!1,last:!1})}onPointerUp_(t){this.handlePointerEvent_(t.data,{forceEmit:!0,last:!0})}onKeyDown_(t){const e=dl(Zl(!0),vl(t));if(0===e)return;const[i,n,s,r]=this.value.rawValue.getComponents("hsv");this.value.setRawValue(new Yl([i,n,s,r+e],"hsv"),{forceEmit:!1,last:!1})}onKeyUp_(t){0!==dl(Zl(!0),vl(t))&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}},Ip=$o("coltxt"),Up=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(Ip()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("div");i.classList.add(Ip("m")),this.modeElem_=function(t){const e=t.createElement("select");return e.appendChild([{text:"RGB",value:"rgb"},{text:"HSL",value:"hsl"},{text:"HSV",value:"hsv"},{text:"HEX",value:"hex"}].reduce((e,i)=>{const n=t.createElement("option");return n.textContent=i.text,n.value=i.value,e.appendChild(n),e},t.createDocumentFragment())),e}(t),this.modeElem_.classList.add(Ip("ms")),i.appendChild(this.modeSelectElement),e.viewProps.bindDisabled(this.modeElem_);const n=t.createElement("div");n.classList.add(Ip("mm")),n.appendChild(To(t,"dropdown")),i.appendChild(n),this.element.appendChild(i);const s=t.createElement("div");s.classList.add(Ip("w")),this.element.appendChild(s),this.inputsElem_=s,this.inputViews_=e.inputViews,this.applyInputViews_(),Io(e.mode,t=>{this.modeElem_.value=t})}get modeSelectElement(){return this.modeElem_}get inputViews(){return this.inputViews_}set inputViews(t){this.inputViews_=t,this.applyInputViews_()}applyInputViews_(){No(this.inputsElem_);const t=this.element.ownerDocument;this.inputViews_.forEach(e=>{const i=t.createElement("div");i.classList.add(Ip("c")),i.appendChild(e.element),this.inputsElem_.appendChild(i)})}};function Fp(t,e,i){const n=$l(t,e)[i];return new Nr({min:0,max:n})}var $p=class{constructor(t,e){this.onModeSelectChange_=this.onModeSelectChange_.bind(this),this.colorType_=e.colorType,this.value=e.value,this.viewProps=e.viewProps,this.colorMode=zr(this.value.rawValue.mode),this.ccs_=this.createComponentControllers_(t),this.view=new Up(t,{mode:this.colorMode,inputViews:[this.ccs_[0].view,this.ccs_[1].view,this.ccs_[2].view],viewProps:this.viewProps}),this.view.modeSelectElement.addEventListener("change",this.onModeSelectChange_)}createComponentControllers_(t){const e=this.colorMode.rawValue;return function(t){return"hex"!==t}(e)?function(t,e){const i={colorMode:e.colorMode,colorType:e.colorType,parser:no,viewProps:e.viewProps};return[0,1,2].map(n=>{const s=function(t,e,i){return new fl(t,{arrayPosition:0===i?"fst":2===i?"lst":"mid",parser:e.parser,props:Rr.fromObject({formatter:(n=e.colorType,ro("float"===n?2:0)),keyScale:Zl(!1),pointerScale:"float"===e.colorType?.01:1}),value:zr(0,{constraint:Fp(e.colorMode,e.colorType,i)}),viewProps:e.viewProps});var n}(t,i,n);return cl({primary:e.value,secondary:s.value,forward:t=>sp(t,e.colorType).getComponents(e.colorMode)[n],backward(t,i){const s=e.colorMode,r=sp(t,e.colorType).getComponents(s);return r[n]=i,sp(np(Ul(Il(r),r[3]),s,e.colorType),"int")}}),s})}(t,{colorMode:e,colorType:this.colorType_,value:this.value,viewProps:this.viewProps}):function(t,e){const i=new sl(t,{parser:Ep("int"),props:Rr.fromObject({formatter:Lp}),value:zr(Yl.black()),viewProps:e.viewProps});return cl({primary:e.value,secondary:i.value,forward:t=>new Yl(Il(t.getComponents()),t.mode),backward:(t,e)=>new Yl(Ul(Il(e.getComponents(t.mode)),t.getComponents()[3]),t.mode)}),[i]}(t,{value:this.value,viewProps:this.viewProps})}onModeSelectChange_(t){const e=t.currentTarget;this.colorMode.rawValue=e.value,this.ccs_=this.createComponentControllers_(this.view.element.ownerDocument),this.view.inputViews=this.ccs_.map(t=>t.view)}},qp=$o("hpl"),Hp=class{constructor(t,e){this.onValueChange_=this.onValueChange_.bind(this),this.value=e.value,this.value.emitter.on("change",this.onValueChange_),this.element=t.createElement("div"),this.element.classList.add(qp()),e.viewProps.bindClassModifiers(this.element),e.viewProps.bindTabIndex(this.element);const i=t.createElement("div");i.classList.add(qp("c")),this.element.appendChild(i);const n=t.createElement("div");n.classList.add(qp("m")),this.element.appendChild(n),this.markerElem_=n,this.update_()}update_(){const[t]=this.value.rawValue.getComponents("hsv");this.markerElem_.style.backgroundColor=Sp(new Yl([t,100,100],"hsv"));const e=oo(t,0,360,0,100);this.markerElem_.style.left=`${e}%`}onValueChange_(){this.update_()}},Gp=class{constructor(t,e){this.onKeyDown_=this.onKeyDown_.bind(this),this.onKeyUp_=this.onKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.value=e.value,this.viewProps=e.viewProps,this.view=new Hp(t,{value:this.value,viewProps:this.viewProps}),this.ptHandler_=new gl(this.view.element),this.ptHandler_.emitter.on("down",this.onPointerDown_),this.ptHandler_.emitter.on("move",this.onPointerMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.element.addEventListener("keydown",this.onKeyDown_),this.view.element.addEventListener("keyup",this.onKeyUp_)}handlePointerEvent_(t,e){if(!t.point)return;const i=oo(lo(t.point.x,0,t.bounds.width),0,t.bounds.width,0,360),[,n,s,r]=this.value.rawValue.getComponents("hsv");this.value.setRawValue(new Yl([i,n,s,r],"hsv"),e)}onPointerDown_(t){this.handlePointerEvent_(t.data,{forceEmit:!1,last:!1})}onPointerMove_(t){this.handlePointerEvent_(t.data,{forceEmit:!1,last:!1})}onPointerUp_(t){this.handlePointerEvent_(t.data,{forceEmit:!0,last:!0})}onKeyDown_(t){const e=dl(Zl(!1),vl(t));if(0===e)return;const[i,n,s,r]=this.value.rawValue.getComponents("hsv");this.value.setRawValue(new Yl([i+e,n,s,r],"hsv"),{forceEmit:!1,last:!1})}onKeyUp_(t){0!==dl(Zl(!1),vl(t))&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}},Yp=$o("svp"),Xp=class{constructor(t,e){this.onValueChange_=this.onValueChange_.bind(this),this.value=e.value,this.value.emitter.on("change",this.onValueChange_),this.element=t.createElement("div"),this.element.classList.add(Yp()),e.viewProps.bindClassModifiers(this.element),e.viewProps.bindTabIndex(this.element);const i=t.createElement("canvas");i.height=64,i.width=64,i.classList.add(Yp("c")),this.element.appendChild(i),this.canvasElement=i;const n=t.createElement("div");n.classList.add(Yp("m")),this.element.appendChild(n),this.markerElem_=n,this.update_()}update_(){const t=function(t){const e=t.ownerDocument.defaultView;return e&&"document"in e?t.getContext("2d",{willReadFrequently:!0}):null}(this.canvasElement);if(!t)return;const e=this.value.rawValue.getComponents("hsv"),i=this.canvasElement.width,n=this.canvasElement.height,s=t.getImageData(0,0,i,n),r=s.data;for(let l=0;lt.getComponents()[3],backward:(t,e)=>{const i=t.getComponents();return i[3]=e,new Yl(i,t.mode)}}),this.textsC_=new $p(t,{colorType:e.colorType,value:this.value,viewProps:this.viewProps}),this.view=new Wl(t,{alphaViews:this.alphaIcs_?{palette:this.alphaIcs_.palette.view,text:this.alphaIcs_.text.view}:null,hPaletteView:this.hPaletteC_.view,supportsAlpha:e.supportsAlpha,svPaletteView:this.svPaletteC_.view,textsView:this.textsC_.view,viewProps:this.viewProps})}get textsController(){return this.textsC_}},Jp=$o("colsw"),Zp=class{constructor(t,e){this.onValueChange_=this.onValueChange_.bind(this),e.value.emitter.on("change",this.onValueChange_),this.value=e.value,this.element=t.createElement("div"),this.element.classList.add(Jp()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("div");i.classList.add(Jp("sw")),this.element.appendChild(i),this.swatchElem_=i;const n=t.createElement("button");n.classList.add(Jp("b")),e.viewProps.bindDisabled(n),this.element.appendChild(n),this.buttonElement=n,this.update_()}update_(){const t=this.value.rawValue;this.swatchElem_.style.backgroundColor=Mp(t)}onValueChange_(){this.update_()}},th=class{constructor(t,e){this.value=e.value,this.viewProps=e.viewProps,this.view=new Zp(t,{value:this.value,viewProps:this.viewProps})}},eh=class{constructor(t,e){this.onButtonBlur_=this.onButtonBlur_.bind(this),this.onButtonClick_=this.onButtonClick_.bind(this),this.onPopupChildBlur_=this.onPopupChildBlur_.bind(this),this.onPopupChildKeydown_=this.onPopupChildKeydown_.bind(this),this.value=e.value,this.viewProps=e.viewProps,this.foldable_=_a.create(e.expanded),this.swatchC_=new th(t,{value:this.value,viewProps:this.viewProps});const i=this.swatchC_.view.buttonElement;i.addEventListener("blur",this.onButtonBlur_),i.addEventListener("click",this.onButtonClick_),this.textC_=new sl(t,{parser:e.parser,props:Rr.fromObject({formatter:e.formatter}),value:this.value,viewProps:this.viewProps}),this.view=new Nl(t,{foldable:this.foldable_,pickerLayout:e.pickerLayout}),this.view.swatchElement.appendChild(this.swatchC_.view.element),this.view.textElement.appendChild(this.textC_.view.element),this.popC_="popup"===e.pickerLayout?new el(t,{viewProps:this.viewProps}):null;const n=new Qp(t,{colorType:e.colorType,supportsAlpha:e.supportsAlpha,value:this.value,viewProps:this.viewProps});n.view.allFocusableElements.forEach(t=>{t.addEventListener("blur",this.onPopupChildBlur_),t.addEventListener("keydown",this.onPopupChildKeydown_)}),this.pickerC_=n,this.popC_?(this.view.element.appendChild(this.popC_.view.element),this.popC_.view.element.appendChild(n.view.element),cl({primary:this.foldable_.value("expanded"),secondary:this.popC_.shows,forward:t=>t,backward:(t,e)=>e})):this.view.pickerElement&&(this.view.pickerElement.appendChild(this.pickerC_.view.element),xa(this.foldable_,this.view.pickerElement))}get textController(){return this.textC_}onButtonBlur_(t){if(!this.popC_)return;const e=this.view.element,i=t.relatedTarget;i&&e.contains(i)||(this.popC_.shows.rawValue=!1)}onButtonClick_(){this.foldable_.set("expanded",!this.foldable_.get("expanded")),this.foldable_.get("expanded")&&this.pickerC_.view.allFocusableElements[0].focus()}onPopupChildBlur_(t){if(!this.popC_)return;const e=this.popC_.view.element,i=Ko(t);i&&e.contains(i)||i&&i===this.swatchC_.view.buttonElement&&!Oo(e.ownerDocument)||(this.popC_.shows.rawValue=!1)}onPopupChildKeydown_(t){this.popC_?"Escape"===t.key&&(this.popC_.shows.rawValue=!1):this.view.pickerElement&&"Escape"===t.key&&this.swatchC_.view.buttonElement.focus()}};function ih(t){return Il(t.getComponents("rgb")).reduce((t,e)=>t<<8|255&Math.floor(e),0)}function nh(t){return t.getComponents("rgb").reduce((t,e,i)=>t<<8|255&Math.floor(3===i?255*e:e),0)>>>0}function sh(t){return"number"!=typeof t?Yl.black():new Yl([(e=t)>>16&255,e>>8&255,255&e],"rgb");var e}function rh(t){return"number"!=typeof t?Yl.black():new Yl([(e=t)>>24&255,e>>16&255,e>>8&255,oo(255&e,0,255,0,1)],"rgb");var e}function oh(t,e){return"object"==typeof t&&!Er(t)&&e in t&&"number"==typeof t[e]}function ah(t){return oh(t,"r")&&oh(t,"g")&&oh(t,"b")}function lh(t){return ah(t)&&oh(t,"a")}function ph(t){return ah(t)}function hh(t,e){if(t.mode!==e.mode)return!1;if(t.type!==e.type)return!1;const i=t.getComponents(),n=e.getComponents();for(let s=0;st?Op(i,e):Dp(i,e)}pa({id:"input-color-number",type:"input",accept:(t,e)=>{if("number"!=typeof t)return null;if(!function(t){return"color"in t||"color"===t.view}(e))return null;const i=Jl(e);return i?{initialValue:t,params:Object.assign(Object.assign({},i),{supportsAlpha:(n=e,!!(null===(s=null==n?void 0:n.color)||void 0===s?void 0:s.alpha))})}:null;var n,s},binding:{reader:t=>t.params.supportsAlpha?rh:sh,equals:hh,writer:t=>function(t){const e=t?nh:ih;return(t,i)=>{Ol(t,e(i))}}(t.params.supportsAlpha)},controller:t=>{var e,i,n;return new eh(t.document,{colorType:"int",expanded:null!==(e=t.params.expanded)&&void 0!==e&&e,formatter:(n=t.params.supportsAlpha,n?t=>Mp(t,"0x"):t=>Lp(t,"0x")),parser:Ep("int"),pickerLayout:null!==(i=t.params.picker)&&void 0!==i?i:"popup",supportsAlpha:t.params.supportsAlpha,value:t.value,viewProps:t.viewProps})}}),pa({id:"input-color-object",type:"input",accept:(t,e)=>{var i;if(!ph(t))return null;const n=Jl(e);return n?{initialValue:t,params:Object.assign(Object.assign({},n),{colorType:null!==(i=tp(e))&&void 0!==i?i:"int"})}:null},binding:{reader:t=>{return e=t.params.colorType,t=>sp(function(t,e){return ph(t)?"int"===e?new Yl(ch(t),"rgb"):"float"===e?new ep(ch(t),"rgb"):sp(Yl.black(),"int"):sp(Yl.black(),e)}(t,e),"int");var e},equals:hh,writer:t=>{return e=lh(t.initialValue),i=t.params.colorType,(t,n)=>{e?function(t,e,i){const n=sp(e,i).toRgbaObject();t.writeProperty("r",n.r),t.writeProperty("g",n.g),t.writeProperty("b",n.b),t.writeProperty("a",n.a)}(t,n,i):function(t,e,i){const n=sp(e,i).toRgbaObject();t.writeProperty("r",n.r),t.writeProperty("g",n.g),t.writeProperty("b",n.b)}(t,n,i)};var e,i}},controller:t=>{var e,i;const n=lh(t.initialValue);return new eh(t.document,{colorType:t.params.colorType,expanded:null!==(e=t.params.expanded)&&void 0!==e&&e,formatter:dh(n,t.params.colorType),parser:Ep("int"),pickerLayout:null!==(i=t.params.picker)&&void 0!==i?i:"popup",supportsAlpha:n,value:t.value,viewProps:t.viewProps})}}),pa({id:"input-color-string",type:"input",accept:(t,e)=>{if("string"!=typeof t)return null;if("text"===e.view)return null;const i=function(t,e="int"){const i=function(t){return Pp.reduce((e,{parser:i,result:n})=>e||(i(t)?n:null),null)}(t);return i?"hex"===i.notation&&"float"!==e?Object.assign(Object.assign({},i),{type:"int"}):"func"===i.notation?Object.assign(Object.assign({},i),{type:e}):null:null}(t,tp(e));if(!i)return null;const n=zp(i);if(!n)return null;const s=Jl(e);return s?{initialValue:t,params:Object.assign(Object.assign({},s),{format:i,stringifier:n})}:null},binding:{reader:()=>kp,equals:hh,writer:t=>{const e=function(t){const e=zp(t);return e?(t,i)=>{Ol(t,e(i))}:null}(t.params.format);if(!e)throw jr.notBindable();return e}},controller:t=>{var e,i;return new eh(t.document,{colorType:t.params.format.type,expanded:null!==(e=t.params.expanded)&&void 0!==e&&e,formatter:t.params.stringifier,parser:Ep("int"),pickerLayout:null!==(i=t.params.picker)&&void 0!==i?i:"popup",supportsAlpha:t.params.format.alpha,value:t.value,viewProps:t.viewProps})}});var uh=class{constructor(t){this.components=t.components,this.asm_=t.assembly}constrain(t){const e=this.asm_.toComponents(t).map((t,e)=>{var i,n;return null!==(n=null===(i=this.components[e])||void 0===i?void 0:i.constrain(t))&&void 0!==n?n:t});return this.asm_.fromComponents(e)}},vh=$o("pndtxt"),mh=class{constructor(t,e){this.textViews=e.textViews,this.element=t.createElement("div"),this.element.classList.add(vh()),this.textViews.forEach(e=>{const i=t.createElement("div");i.classList.add(vh("a")),i.appendChild(e.element),this.element.appendChild(i)})}},bh=class{constructor(t,e){this.value=e.value,this.viewProps=e.viewProps,this.acs_=e.axes.map((i,n)=>function(t,e,i){return new fl(t,{arrayPosition:0===i?"fst":i===e.axes.length-1?"lst":"mid",parser:e.parser,props:e.axes[i].textProps,value:zr(0,{constraint:e.axes[i].constraint}),viewProps:e.viewProps})}(t,e,n)),this.acs_.forEach((t,i)=>{cl({primary:this.value,secondary:t.value,forward:t=>e.assembly.toComponents(t)[i],backward:(t,n)=>{const s=e.assembly.toComponents(t);return s[i]=n,e.assembly.fromComponents(s)}})}),this.view=new mh(t,{textViews:this.acs_.map(t=>t.view)})}get textControllers(){return this.acs_}},gh=class extends Po{get max(){return this.controller.valueController.sliderController.props.get("max")}set max(t){this.controller.valueController.sliderController.props.set("max",t)}get min(){return this.controller.valueController.sliderController.props.get("min")}set min(t){this.controller.valueController.sliderController.props.set("min",t)}};pa({id:"input-number",type:"input",accept:(t,e)=>{if("number"!=typeof t)return null;const i=Lo(e,t=>Object.assign(Object.assign({},go(t)),{options:t.optional.custom(Ga),readonly:t.optional.constant(!1)}));return i?{initialValue:t,params:i}:null},binding:{reader:t=>so,constraint:t=>function(t,e){const i=[],n=vo(t,e);n&&i.push(n);const s=mo(t);s&&i.push(s);const r=Xa(t.options);return r&&i.push(r),new $a(i)}(t.params,t.initialValue),writer:t=>Ol},controller:t=>{const e=t.value,i=t.constraint,n=i&&qa(i,Ha);if(n)return new Ja(t.document,{props:new Rr({options:n.values.value("options")}),value:e,viewProps:t.viewProps});const s=bo(t.params,e.rawValue),r=i&&qa(i,Nr);return r?new kl(t.document,Object.assign(Object.assign({},(o=Object.assign(Object.assign({},s),{keyScale:zr(s.keyScale),max:r.values.value("max"),min:r.values.value("min")}),{sliderProps:new Rr({keyScale:o.keyScale,max:o.max,min:o.min}),textProps:new Rr({formatter:zr(o.formatter),keyScale:o.keyScale,pointerScale:zr(o.pointerScale)})})),{parser:no,value:e,viewProps:t.viewProps})):new fl(t.document,{parser:no,props:Rr.fromObject(s),value:e,viewProps:t.viewProps});var o},api:t=>"number"!=typeof t.controller.value.rawValue?null:t.controller.valueController instanceof kl?new gh(t.controller):t.controller.valueController instanceof Ja?new Ia(t.controller):null});var wh=class{constructor(t=0,e=0){this.x=t,this.y=e}getComponents(){return[this.x,this.y]}static isObject(t){if(Er(t))return!1;const e=t.x,i=t.y;return"number"==typeof e&&"number"==typeof i}static equals(t,e){return t.x===e.x&&t.y===e.y}toObject(){return{x:this.x,y:this.y}}},_h={toComponents:t=>t.getComponents(),fromComponents:t=>new wh(...t)},fh=$o("p2d"),xh=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(fh()),e.viewProps.bindClassModifiers(this.element),Io(e.expanded,ia(this.element,fh(void 0,"expanded")));const i=t.createElement("div");i.classList.add(fh("h")),this.element.appendChild(i);const n=t.createElement("button");n.classList.add(fh("b")),n.appendChild(To(t,"p2dpad")),e.viewProps.bindDisabled(n),i.appendChild(n),this.buttonElement=n;const s=t.createElement("div");if(s.classList.add(fh("t")),i.appendChild(s),this.textElement=s,"inline"===e.pickerLayout){const e=t.createElement("div");e.classList.add(fh("p")),this.element.appendChild(e),this.pickerElement=e}else this.pickerElement=null}},Ch=$o("p2dp"),yh=class{constructor(t,e){this.onFoldableChange_=this.onFoldableChange_.bind(this),this.onPropsChange_=this.onPropsChange_.bind(this),this.onValueChange_=this.onValueChange_.bind(this),this.props_=e.props,this.props_.emitter.on("change",this.onPropsChange_),this.element=t.createElement("div"),this.element.classList.add(Ch()),"popup"===e.layout&&this.element.classList.add(Ch(void 0,"p")),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("div");i.classList.add(Ch("p")),e.viewProps.bindTabIndex(i),this.element.appendChild(i),this.padElement=i;const n=t.createElementNS(Do,"svg");n.classList.add(Ch("g")),this.padElement.appendChild(n),this.svgElem_=n;const s=t.createElementNS(Do,"line");s.classList.add(Ch("ax")),s.setAttributeNS(null,"x1","0"),s.setAttributeNS(null,"y1","50%"),s.setAttributeNS(null,"x2","100%"),s.setAttributeNS(null,"y2","50%"),this.svgElem_.appendChild(s);const r=t.createElementNS(Do,"line");r.classList.add(Ch("ax")),r.setAttributeNS(null,"x1","50%"),r.setAttributeNS(null,"y1","0"),r.setAttributeNS(null,"x2","50%"),r.setAttributeNS(null,"y2","100%"),this.svgElem_.appendChild(r);const o=t.createElementNS(Do,"line");o.classList.add(Ch("l")),o.setAttributeNS(null,"x1","50%"),o.setAttributeNS(null,"y1","50%"),this.svgElem_.appendChild(o),this.lineElem_=o;const a=t.createElement("div");a.classList.add(Ch("m")),this.padElement.appendChild(a),this.markerElem_=a,e.value.emitter.on("change",this.onValueChange_),this.value=e.value,this.update_()}get allFocusableElements(){return[this.padElement]}update_(){const[t,e]=this.value.rawValue.getComponents(),i=this.props_.get("max"),n=oo(t,-i,+i,0,100),s=oo(e,-i,+i,0,100),r=this.props_.get("invertsY")?100-s:s;this.lineElem_.setAttributeNS(null,"x2",`${n}%`),this.lineElem_.setAttributeNS(null,"y2",`${r}%`),this.markerElem_.style.left=`${n}%`,this.markerElem_.style.top=`${r}%`}onValueChange_(){this.update_()}onPropsChange_(){this.update_()}onFoldableChange_(){this.update_()}};function Ph(t,e,i){return[dl(e[0],vl(t)),dl(e[1],ul(t))*(i?1:-1)]}var Eh=class{constructor(t,e){this.onPadKeyDown_=this.onPadKeyDown_.bind(this),this.onPadKeyUp_=this.onPadKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.props=e.props,this.value=e.value,this.viewProps=e.viewProps,this.view=new yh(t,{layout:e.layout,props:this.props,value:this.value,viewProps:this.viewProps}),this.ptHandler_=new gl(this.view.padElement),this.ptHandler_.emitter.on("down",this.onPointerDown_),this.ptHandler_.emitter.on("move",this.onPointerMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.padElement.addEventListener("keydown",this.onPadKeyDown_),this.view.padElement.addEventListener("keyup",this.onPadKeyUp_)}handlePointerEvent_(t,e){if(!t.point)return;const i=this.props.get("max"),n=oo(t.point.x,0,t.bounds.width,-i,+i),s=oo(this.props.get("invertsY")?t.bounds.height-t.point.y:t.point.y,0,t.bounds.height,-i,+i);this.value.setRawValue(new wh(n,s),e)}onPointerDown_(t){this.handlePointerEvent_(t.data,{forceEmit:!1,last:!1})}onPointerMove_(t){this.handlePointerEvent_(t.data,{forceEmit:!1,last:!1})}onPointerUp_(t){this.handlePointerEvent_(t.data,{forceEmit:!0,last:!0})}onPadKeyDown_(t){ml(t.key)&&t.preventDefault();const[e,i]=Ph(t,[this.props.get("xKeyScale"),this.props.get("yKeyScale")],this.props.get("invertsY"));0===e&&0===i||this.value.setRawValue(new wh(this.value.rawValue.x+e,this.value.rawValue.y+i),{forceEmit:!1,last:!1})}onPadKeyUp_(t){const[e,i]=Ph(t,[this.props.get("xKeyScale"),this.props.get("yKeyScale")],this.props.get("invertsY"));0===e&&0===i||this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}},kh=class{constructor(t,e){var i,n;this.onPopupChildBlur_=this.onPopupChildBlur_.bind(this),this.onPopupChildKeydown_=this.onPopupChildKeydown_.bind(this),this.onPadButtonBlur_=this.onPadButtonBlur_.bind(this),this.onPadButtonClick_=this.onPadButtonClick_.bind(this),this.value=e.value,this.viewProps=e.viewProps,this.foldable_=_a.create(e.expanded),this.popC_="popup"===e.pickerLayout?new el(t,{viewProps:this.viewProps}):null;const s=new Eh(t,{layout:e.pickerLayout,props:new Rr({invertsY:zr(e.invertsY),max:zr(e.max),xKeyScale:e.axes[0].textProps.value("keyScale"),yKeyScale:e.axes[1].textProps.value("keyScale")}),value:this.value,viewProps:this.viewProps});s.view.allFocusableElements.forEach(t=>{t.addEventListener("blur",this.onPopupChildBlur_),t.addEventListener("keydown",this.onPopupChildKeydown_)}),this.pickerC_=s,this.textC_=new bh(t,{assembly:_h,axes:e.axes,parser:e.parser,value:this.value,viewProps:this.viewProps}),this.view=new xh(t,{expanded:this.foldable_.value("expanded"),pickerLayout:e.pickerLayout,viewProps:this.viewProps}),this.view.textElement.appendChild(this.textC_.view.element),null===(i=this.view.buttonElement)||void 0===i||i.addEventListener("blur",this.onPadButtonBlur_),null===(n=this.view.buttonElement)||void 0===n||n.addEventListener("click",this.onPadButtonClick_),this.popC_?(this.view.element.appendChild(this.popC_.view.element),this.popC_.view.element.appendChild(this.pickerC_.view.element),cl({primary:this.foldable_.value("expanded"),secondary:this.popC_.shows,forward:t=>t,backward:(t,e)=>e})):this.view.pickerElement&&(this.view.pickerElement.appendChild(this.pickerC_.view.element),xa(this.foldable_,this.view.pickerElement))}get textController(){return this.textC_}onPadButtonBlur_(t){if(!this.popC_)return;const e=this.view.element,i=t.relatedTarget;i&&e.contains(i)||(this.popC_.shows.rawValue=!1)}onPadButtonClick_(){this.foldable_.set("expanded",!this.foldable_.get("expanded")),this.foldable_.get("expanded")&&this.pickerC_.view.allFocusableElements[0].focus()}onPopupChildBlur_(t){if(!this.popC_)return;const e=this.popC_.view.element,i=Ko(t);i&&e.contains(i)||i&&i===this.view.buttonElement&&!Oo(e.ownerDocument)||(this.popC_.shows.rawValue=!1)}onPopupChildKeydown_(t){this.popC_?"Escape"===t.key&&(this.popC_.shows.rawValue=!1):this.view.pickerElement&&"Escape"===t.key&&this.view.buttonElement.focus()}};function Vh(t){return wh.isObject(t)?new wh(t.x,t.y):new wh}function Lh(t,e){t.writeProperty("x",e.x),t.writeProperty("y",e.y)}function Mh(t,e){var i,n;if(!Er(t.min)||!Er(t.max))return Math.max(Math.abs(null!==(i=t.min)&&void 0!==i?i:0),Math.abs(null!==(n=t.max)&&void 0!==n?n:0));const s=co(t);return Math.max(10*Math.abs(s),10*Math.abs(e))}function Sh(t,e){var i,n;const s=Mh(Mr(t,null!==(i=t.x)&&void 0!==i?i:{}),e.x),r=Mh(Mr(t,null!==(n=t.y)&&void 0!==n?n:{}),e.y);return Math.max(s,r)}function jh(t){if(!("y"in t))return!1;const e=t.y;return!!e&&"inverted"in e&&!!e.inverted}pa({id:"input-point2d",type:"input",accept:(t,e)=>{if(!wh.isObject(t))return null;const i=Lo(e,t=>Object.assign(Object.assign({},Sl(t)),{expanded:t.optional.boolean,picker:t.optional.custom(Al),readonly:t.optional.constant(!1),x:t.optional.custom(jl),y:t.optional.object(Object.assign(Object.assign({},Sl(t)),{inverted:t.optional.boolean}))}));return i?{initialValue:t,params:i}:null},binding:{reader:()=>Vh,constraint:t=>{return e=t.params,i=t.initialValue,new uh({assembly:_h,components:[Dl(Object.assign(Object.assign({},e),e.x),i.x),Dl(Object.assign(Object.assign({},e),e.y),i.y)]});var e,i},equals:wh.equals,writer:()=>Lh},controller:t=>{var e,i;const n=t.document,s=t.value,r=t.constraint,o=[t.params.x,t.params.y];return new kh(n,{axes:s.rawValue.getComponents().map((e,i)=>{var n;return wo({constraint:r.components[i],initialValue:e,params:Mr(t.params,null!==(n=o[i])&&void 0!==n?n:{})})}),expanded:null!==(e=t.params.expanded)&&void 0!==e&&e,invertsY:jh(t.params),max:Sh(t.params,s.rawValue),parser:no,pickerLayout:null!==(i=t.params.picker)&&void 0!==i?i:"popup",value:s,viewProps:t.viewProps})}});var Dh=class{constructor(t=0,e=0,i=0){this.x=t,this.y=e,this.z=i}getComponents(){return[this.x,this.y,this.z]}static isObject(t){if(Er(t))return!1;const e=t.x,i=t.y,n=t.z;return"number"==typeof e&&"number"==typeof i&&"number"==typeof n}static equals(t,e){return t.x===e.x&&t.y===e.y&&t.z===e.z}toObject(){return{x:this.x,y:this.y,z:this.z}}},Ah={toComponents:t=>t.getComponents(),fromComponents:t=>new Dh(...t)};function Oh(t){return Dh.isObject(t)?new Dh(t.x,t.y,t.z):new Dh}function Bh(t,e){t.writeProperty("x",e.x),t.writeProperty("y",e.y),t.writeProperty("z",e.z)}pa({id:"input-point3d",type:"input",accept:(t,e)=>{if(!Dh.isObject(t))return null;const i=Lo(e,t=>Object.assign(Object.assign({},Sl(t)),{readonly:t.optional.constant(!1),x:t.optional.custom(jl),y:t.optional.custom(jl),z:t.optional.custom(jl)}));return i?{initialValue:t,params:i}:null},binding:{reader:t=>Oh,constraint:t=>{return e=t.params,i=t.initialValue,new uh({assembly:Ah,components:[Dl(Object.assign(Object.assign({},e),e.x),i.x),Dl(Object.assign(Object.assign({},e),e.y),i.y),Dl(Object.assign(Object.assign({},e),e.z),i.z)]});var e,i},equals:Dh.equals,writer:t=>Bh},controller:t=>{const e=t.value,i=t.constraint,n=[t.params.x,t.params.y,t.params.z];return new bh(t.document,{assembly:Ah,axes:e.rawValue.getComponents().map((e,s)=>{var r;return wo({constraint:i.components[s],initialValue:e,params:Mr(t.params,null!==(r=n[s])&&void 0!==r?r:{})})}),parser:no,value:e,viewProps:t.viewProps})}});var Th=class{constructor(t=0,e=0,i=0,n=0){this.x=t,this.y=e,this.z=i,this.w=n}getComponents(){return[this.x,this.y,this.z,this.w]}static isObject(t){if(Er(t))return!1;const e=t.x,i=t.y,n=t.z,s=t.w;return"number"==typeof e&&"number"==typeof i&&"number"==typeof n&&"number"==typeof s}static equals(t,e){return t.x===e.x&&t.y===e.y&&t.z===e.z&&t.w===e.w}toObject(){return{x:this.x,y:this.y,z:this.z,w:this.w}}},zh={toComponents:t=>t.getComponents(),fromComponents:t=>new Th(...t)};function Rh(t){return Th.isObject(t)?new Th(t.x,t.y,t.z,t.w):new Th}function Nh(t,e){t.writeProperty("x",e.x),t.writeProperty("y",e.y),t.writeProperty("z",e.z),t.writeProperty("w",e.w)}pa({id:"input-point4d",type:"input",accept:(t,e)=>{if(!Th.isObject(t))return null;const i=Lo(e,t=>Object.assign(Object.assign({},Sl(t)),{readonly:t.optional.constant(!1),w:t.optional.custom(jl),x:t.optional.custom(jl),y:t.optional.custom(jl),z:t.optional.custom(jl)}));return i?{initialValue:t,params:i}:null},binding:{reader:t=>Rh,constraint:t=>{return e=t.params,i=t.initialValue,new uh({assembly:zh,components:[Dl(Object.assign(Object.assign({},e),e.x),i.x),Dl(Object.assign(Object.assign({},e),e.y),i.y),Dl(Object.assign(Object.assign({},e),e.z),i.z),Dl(Object.assign(Object.assign({},e),e.w),i.w)]});var e,i},equals:Th.equals,writer:t=>Nh},controller:t=>{const e=t.value,i=t.constraint,n=[t.params.x,t.params.y,t.params.z,t.params.w];return new bh(t.document,{assembly:zh,axes:e.rawValue.getComponents().map((e,s)=>{var r;return wo({constraint:i.components[s],initialValue:e,params:Mr(t.params,null!==(r=n[s])&&void 0!==r?r:{})})}),parser:no,value:e,viewProps:t.viewProps})}}),pa({id:"input-string",type:"input",accept:(t,e)=>{if("string"!=typeof t)return null;const i=Lo(e,t=>({readonly:t.optional.constant(!1),options:t.optional.custom(Ga)}));return i?{initialValue:t,params:i}:null},binding:{reader:t=>pl,constraint:t=>function(t){const e=[],i=Xa(t.options);return i&&e.push(i),new $a(e)}(t.params),writer:t=>Ol},controller:t=>{const e=t.document,i=t.value,n=t.constraint,s=n&&qa(n,Ha);return s?new Ja(e,{props:new Rr({options:s.values.value("options")}),value:i,viewProps:t.viewProps}):new sl(e,{parser:t=>t,props:Rr.fromObject({formatter:hl}),value:i,viewProps:t.viewProps})},api:t=>"string"!=typeof t.controller.value.rawValue?null:t.controller.valueController instanceof Ja?new Ia(t.controller):null});var Kh=200,Ih=3,Uh=$o("mll"),Fh=class{constructor(t,e){this.onValueUpdate_=this.onValueUpdate_.bind(this),this.formatter_=e.formatter,this.element=t.createElement("div"),this.element.classList.add(Uh()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("textarea");i.classList.add(Uh("i")),i.style.height=`calc(var(${Ll("containerUnitSize")}) * ${e.rows})`,i.readOnly=!0,e.viewProps.bindDisabled(i),this.element.appendChild(i),this.textareaElem_=i,e.value.emitter.on("change",this.onValueUpdate_),this.value=e.value,this.update_()}update_(){const t=this.textareaElem_,e=t.scrollTop===t.scrollHeight-t.clientHeight,i=[];this.value.rawValue.forEach(t=>{void 0!==t&&i.push(this.formatter_(t))}),t.textContent=i.join("\n"),e&&(t.scrollTop=t.scrollHeight)}onValueUpdate_(){this.update_()}},$h=class{constructor(t,e){this.value=e.value,this.viewProps=e.viewProps,this.view=new Fh(t,{formatter:e.formatter,rows:e.rows,value:this.value,viewProps:this.viewProps})}},qh=$o("sgl"),Hh=class{constructor(t,e){this.onValueUpdate_=this.onValueUpdate_.bind(this),this.formatter_=e.formatter,this.element=t.createElement("div"),this.element.classList.add(qh()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("input");i.classList.add(qh("i")),i.readOnly=!0,i.type="text",e.viewProps.bindDisabled(i),this.element.appendChild(i),this.inputElement=i,e.value.emitter.on("change",this.onValueUpdate_),this.value=e.value,this.update_()}update_(){const t=this.value.rawValue,e=t[t.length-1];this.inputElement.value=void 0!==e?this.formatter_(e):""}onValueUpdate_(){this.update_()}},Gh=class{constructor(t,e){this.value=e.value,this.viewProps=e.viewProps,this.view=new Hh(t,{formatter:e.formatter,value:this.value,viewProps:this.viewProps})}};pa({id:"monitor-bool",type:"monitor",accept:(t,e)=>{if("boolean"!=typeof t)return null;const i=Lo(e,t=>({readonly:t.required.constant(!0),rows:t.optional.number}));return i?{initialValue:t,params:i}:null},binding:{reader:t=>rl},controller:t=>{var e;return 1===t.value.rawValue.length?new Gh(t.document,{formatter:ol,value:t.value,viewProps:t.viewProps}):new $h(t.document,{formatter:ol,rows:null!==(e=t.params.rows)&&void 0!==e?e:Ih,value:t.value,viewProps:t.viewProps})}});var Yh=class extends Po{get max(){return this.controller.valueController.props.get("max")}set max(t){this.controller.valueController.props.set("max",t)}get min(){return this.controller.valueController.props.get("min")}set min(t){this.controller.valueController.props.set("min",t)}},Xh=$o("grl"),Wh=class{constructor(t,e){this.onCursorChange_=this.onCursorChange_.bind(this),this.onValueUpdate_=this.onValueUpdate_.bind(this),this.element=t.createElement("div"),this.element.classList.add(Xh()),e.viewProps.bindClassModifiers(this.element),this.formatter_=e.formatter,this.props_=e.props,this.cursor_=e.cursor,this.cursor_.emitter.on("change",this.onCursorChange_);const i=t.createElementNS(Do,"svg");i.classList.add(Xh("g")),i.style.height=`calc(var(${Ll("containerUnitSize")}) * ${e.rows})`,this.element.appendChild(i),this.svgElem_=i;const n=t.createElementNS(Do,"polyline");this.svgElem_.appendChild(n),this.lineElem_=n;const s=t.createElement("div");s.classList.add(Xh("t"),$o("tt")()),this.element.appendChild(s),this.tooltipElem_=s,e.value.emitter.on("change",this.onValueUpdate_),this.value=e.value,this.update_()}get graphElement(){return this.svgElem_}update_(){const t=this.svgElem_.getBoundingClientRect(),e=this.value.rawValue.length-1,i=this.props_.get("min"),n=this.props_.get("max"),s=[];this.value.rawValue.forEach((r,o)=>{if(void 0===r)return;const a=oo(o,0,e,0,t.width),l=oo(r,i,n,t.height,0);s.push([a,l].join(","))}),this.lineElem_.setAttributeNS(null,"points",s.join(" "));const r=this.tooltipElem_,o=this.value.rawValue[this.cursor_.rawValue];if(void 0===o)return void r.classList.remove(Xh("t","a"));const a=oo(this.cursor_.rawValue,0,e,0,t.width),l=oo(o,i,n,t.height,0);r.style.left=`${a}px`,r.style.top=`${l}px`,r.textContent=`${this.formatter_(o)}`,r.classList.contains(Xh("t","a"))||(r.classList.add(Xh("t","a"),Xh("t","in")),Ao(r),r.classList.remove(Xh("t","in")))}onValueUpdate_(){this.update_()}onCursorChange_(){this.update_()}},Qh=class{constructor(t,e){if(this.onGraphMouseMove_=this.onGraphMouseMove_.bind(this),this.onGraphMouseLeave_=this.onGraphMouseLeave_.bind(this),this.onGraphPointerDown_=this.onGraphPointerDown_.bind(this),this.onGraphPointerMove_=this.onGraphPointerMove_.bind(this),this.onGraphPointerUp_=this.onGraphPointerUp_.bind(this),this.props=e.props,this.value=e.value,this.viewProps=e.viewProps,this.cursor_=zr(-1),this.view=new Wh(t,{cursor:this.cursor_,formatter:e.formatter,rows:e.rows,props:this.props,value:this.value,viewProps:this.viewProps}),Oo(t)){const t=new gl(this.view.element);t.emitter.on("down",this.onGraphPointerDown_),t.emitter.on("move",this.onGraphPointerMove_),t.emitter.on("up",this.onGraphPointerUp_)}else this.view.element.addEventListener("mousemove",this.onGraphMouseMove_),this.view.element.addEventListener("mouseleave",this.onGraphMouseLeave_)}importProps(t){return Mo(t,null,t=>({max:t.required.number,min:t.required.number}),t=>(this.props.set("max",t.max),this.props.set("min",t.min),!0))}exportProps(){return So(null,{max:this.props.get("max"),min:this.props.get("min")})}onGraphMouseLeave_(){this.cursor_.rawValue=-1}onGraphMouseMove_(t){const e=this.view.element.getBoundingClientRect();this.cursor_.rawValue=Math.floor(oo(t.offsetX,0,e.width,0,this.value.rawValue.length))}onGraphPointerDown_(t){this.onGraphPointerMove_(t)}onGraphPointerMove_(t){t.data.point?this.cursor_.rawValue=Math.floor(oo(t.data.point.x,0,t.data.bounds.width,0,this.value.rawValue.length)):this.cursor_.rawValue=-1}onGraphPointerUp_(){this.cursor_.rawValue=-1}};function Jh(t){return Er(t.format)?ro(2):t.format}function Zh(t){return"graph"===t.view}pa({id:"monitor-number",type:"monitor",accept:(t,e)=>{if("number"!=typeof t)return null;const i=Lo(e,t=>({format:t.optional.function,max:t.optional.number,min:t.optional.number,readonly:t.required.constant(!0),rows:t.optional.number,view:t.optional.string}));return i?{initialValue:t,params:i}:null},binding:{defaultBufferSize:t=>Zh(t)?64:1,reader:t=>so},controller:t=>Zh(t.params)?function(t){var e,i,n;return new Qh(t.document,{formatter:Jh(t.params),rows:null!==(e=t.params.rows)&&void 0!==e?e:Ih,props:Rr.fromObject({max:null!==(i=t.params.max)&&void 0!==i?i:100,min:null!==(n=t.params.min)&&void 0!==n?n:0}),value:t.value,viewProps:t.viewProps})}(t):function(t){var e;return 1===t.value.rawValue.length?new Gh(t.document,{formatter:Jh(t.params),value:t.value,viewProps:t.viewProps}):new $h(t.document,{formatter:Jh(t.params),rows:null!==(e=t.params.rows)&&void 0!==e?e:Ih,value:t.value,viewProps:t.viewProps})}(t),api:t=>t.controller.valueController instanceof Qh?new Yh(t.controller):null}),pa({id:"monitor-string",type:"monitor",accept:(t,e)=>{if("string"!=typeof t)return null;const i=Lo(e,t=>({multiline:t.optional.boolean,readonly:t.required.constant(!0),rows:t.optional.number}));return i?{initialValue:t,params:i}:null},binding:{reader:t=>pl},controller:t=>{var e;const i=t.value;return i.rawValue.length>1||t.params.multiline?new $h(t.document,{formatter:hl,rows:null!==(e=t.params.rows)&&void 0!==e?e:Ih,value:i,viewProps:t.viewProps}):new Gh(t.document,{formatter:hl,value:i,viewProps:t.viewProps})}});var tc=class{constructor(t){this.controller_=t}get disabled(){return this.controller_.viewProps.get("disabled")}set disabled(t){this.controller_.viewProps.set("disabled",t)}get title(){var t;return null!==(t=this.controller_.props.get("title"))&&void 0!==t?t:""}set title(t){this.controller_.props.set("title",t)}on(t,e){const i=e.bind(this);return this.controller_.emitter.on(t,()=>{i(new fo(this))}),this}},ec=class extends fo{constructor(t,e,i){super(t),this.cell=e,this.index=i}},ic=class extends _o{constructor(t){super(t),this.cellToApiMap_=new Map,this.emitter_=new Ar;const e=this.controller.valueController;e.cellControllers.forEach((t,i)=>{const n=new tc(t);this.cellToApiMap_.set(t,n),t.emitter.on("click",()=>{const t=i%e.size[0],s=Math.floor(i/e.size[0]);this.emitter_.emit("click",{event:new ec(this,n,[t,s])})})})}cell(t,e){const i=this.controller.valueController,n=i.cellControllers[e*i.size[0]+t];return this.cellToApiMap_.get(n)}on(t,e){const i=e.bind(this);return this.emitter_.on(t,t=>{i(t.event)}),this}},nc=class{constructor(t,e){this.size=e.size;const[i,n]=this.size,s=[];for(let r=0;r{this.cellCs_.forEach(t=>{t.viewProps.set("disposed",!0)})}),this.view=new Ml(t,{viewProps:this.viewProps,viewName:"btngrid"}),this.view.element.style.gridTemplateColumns=`repeat(${i}, 1fr)`,this.cellCs_.forEach(t=>{this.view.element.appendChild(t.view.element)})}get cellControllers(){return this.cellCs_}},sc=class extends Wo{constructor(t,e){const i=e.valueController,n=new Go(t,{blade:e.blade,props:e.labelProps,valueController:i});super({blade:e.blade,view:n.view,viewProps:i.viewProps}),this.valueController=i,this.labelController=n}},rc=pa({id:"buttongrid",type:"blade",accept(t){const e=Lo(t,t=>({cells:t.required.function,size:t.required.array(t.required.number),view:t.required.constant("buttongrid"),label:t.optional.string}));return e?{params:e}:null},controller:t=>new sc(t.document,{blade:t.blade,labelProps:Rr.fromObject({label:t.params.label}),valueController:new nc(t.document,{cellConfig:t.params.cells,size:t.params.size})}),api:t=>t.controller instanceof sc?new ic(t.controller):null}),oc=class extends _o{get label(){return this.controller.labelController.props.get("label")}set label(t){this.controller.labelController.props.set("label",t)}get value(){return this.controller.valueController.value.rawValue}set value(t){this.controller.valueController.value.rawValue=t}on(t,e){const i=e.bind(this);return this.controller.valueController.value.emitter.on(t,t=>{i(new xo(this,t.rawValue,t.options.last))}),this}};function ac(t,e,i){return t*(1-i)+e*i}function lc(t,e){let i=.25,n=.5,s=-1;for(let r=0;r<20;r++){const[r,o]=t.curve(n);if(n+=i*(rt.toObject(),fromComponents:t=>new pc(...t)};function cc(t){const e=ro(2);return`cubic-bezier(${t.toObject().map(t=>e(t)).join(", ")})`}var dc=[0,.5,.5,1];function uc(t){const e=t.match(/^cubic-bezier\s*\(\s*([0-9.]+)\s*,\s*([0-9.]+)\s*,\s*([0-9.]+)\s*,\s*([0-9.]+)\s*\)$/);if(!e)return new pc(...dc);const i=[e[1],e[2],e[3],e[4]].reduce((t,e)=>{if(!t)return null;const i=Number(e);return isNaN(i)?null:[...t,i]},[]);return new pc(...null!=i?i:dc)}var vc=$o("cbz"),mc=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(vc()),e.viewProps.bindClassModifiers(this.element),e.foldable.bindExpandedClass(this.element,vc(void 0,"expanded")),Uo(e.foldable,"completed",ia(this.element,vc(void 0,"cpl")));const i=t.createElement("div");i.classList.add(vc("h")),this.element.appendChild(i);const n=t.createElement("button");n.classList.add(vc("b")),e.viewProps.bindDisabled(n);const s=t.createElementNS(Do,"svg");s.innerHTML='',n.appendChild(s),i.appendChild(n),this.buttonElement=n;const r=t.createElement("div");if(r.classList.add(vc("t")),i.appendChild(r),this.textElement=r,"inline"===e.pickerLayout){const e=t.createElement("div");e.classList.add(vc("p")),this.element.appendChild(e),this.pickerElement=e}else this.pickerElement=null}},bc=$o("cbzp"),gc=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(bc()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("div");i.classList.add(bc("g")),this.element.appendChild(i),this.graphElement=i;const n=t.createElement("div");n.classList.add(bc("t")),this.element.appendChild(n),this.textElement=n}};function wc(t,e){const i=new MutationObserver(t=>{for(const n of t)"childList"===n.type&&n.addedNodes.forEach(t=>{t.contains(t)&&(e(),i.disconnect())})}),n=t.ownerDocument;i.observe(n.body,{attributes:!0,childList:!0,subtree:!0})}var _c=$o("cbzg"),fc=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(_c()),e.viewProps.bindClassModifiers(this.element),e.viewProps.bindTabIndex(this.element);const i=t.createElement("div");i.classList.add(_c("p")),this.element.appendChild(i),this.previewElement=i;const n=t.createElementNS(Do,"svg");n.classList.add(_c("g")),this.element.appendChild(n),this.svgElem_=n;const s=t.createElementNS(Do,"path");s.classList.add(_c("u")),this.svgElem_.appendChild(s),this.guideElem_=s;const r=t.createElementNS(Do,"polyline");r.classList.add(_c("l")),this.svgElem_.appendChild(r),this.lineElem_=r,this.handleElems_=[t.createElement("div"),t.createElement("div")],this.handleElems_.forEach(t=>{t.classList.add(_c("h")),this.element.appendChild(t)}),this.vectorElems_=[t.createElementNS(Do,"line"),t.createElementNS(Do,"line")],this.vectorElems_.forEach(t=>{t.classList.add(_c("v")),this.svgElem_.appendChild(t)}),this.value_=e.value,this.value_.emitter.on("change",this.onValueChange_.bind(this)),this.sel_=e.selection,this.handleElems_.forEach((t,e)=>{var i,n;Io(this.sel_,(i=t=>t===e,n=ia(t,_c("h","sel")),t=>n(i(t))))}),wc(this.element,()=>{this.refresh()})}getVertMargin_(t){return.25*t}valueToPosition(t,e){const{clientWidth:i,clientHeight:n}=this.element,s=this.getVertMargin_(n);return{x:oo(t,0,1,0,i),y:oo(e,0,1,n-s,s)}}positionToValue(t,e){const i=this.element.getBoundingClientRect(),n=i.width,s=i.height,r=this.getVertMargin_(s);return{x:lo(oo(t,0,n,0,1),0,1),y:oo(e,s-r,r,0,1)}}refresh(){this.guideElem_.setAttributeNS(null,"d",[0,1].map(t=>{const e=this.valueToPosition(0,t),i=this.valueToPosition(1,t);return[`M ${e.x},${e.y}`,`L ${i.x},${i.y}`].join(" ")}).join(" "));const t=this.value_.rawValue,e=[];let i=0;for(;;){const n=this.valueToPosition(...t.curve(i));if(e.push([n.x,n.y].join(",")),i>=1)break;i=Math.min(i+.05,1)}this.lineElem_.setAttributeNS(null,"points",e.join(" "));const n=t.toObject();[0,1].forEach(t=>{const e=this.valueToPosition(t,t),i=this.valueToPosition(n[2*t],n[2*t+1]),s=this.vectorElems_[t];s.setAttributeNS(null,"x1",String(e.x)),s.setAttributeNS(null,"y1",String(e.y)),s.setAttributeNS(null,"x2",String(i.x)),s.setAttributeNS(null,"y2",String(i.y));const r=this.handleElems_[t];r.style.left=`${i.x}px`,r.style.top=`${i.y}px`})}onValueChange_(){this.refresh()}},xc=$o("cbzprv"),Cc=class{constructor(t,e){this.stopped_=!0,this.startTime_=-1,this.onDispose_=this.onDispose_.bind(this),this.onTimer_=this.onTimer_.bind(this),this.onValueChange_=this.onValueChange_.bind(this),this.element=t.createElement("div"),this.element.classList.add(xc()),e.viewProps.bindClassModifiers(this.element);const i=t.createElementNS(Do,"svg");i.classList.add(xc("g")),this.element.appendChild(i),this.svgElem_=i;const n=t.createElementNS(Do,"path");n.classList.add(xc("t")),this.svgElem_.appendChild(n),this.ticksElem_=n;const s=t.createElement("div");s.classList.add(xc("m")),this.element.appendChild(s),this.markerElem_=s,this.value_=e.value,this.value_.emitter.on("change",this.onValueChange_),e.viewProps.handleDispose(this.onDispose_),wc(this.element,()=>{this.refresh()})}play(){this.stop(),this.updateMarker_(0),this.markerElem_.classList.add(xc("m","a")),this.startTime_=(new Date).getTime()+400,this.stopped_=!1,requestAnimationFrame(this.onTimer_)}stop(){this.stopped_=!0,this.markerElem_.classList.remove(xc("m","a"))}onDispose_(){this.stop()}updateMarker_(t){const e=this.value_.rawValue.y(lo(t,0,1));this.markerElem_.style.left=100*e+"%"}refresh(){const{clientWidth:t,clientHeight:e}=this.svgElem_,i=[],n=this.value_.rawValue;for(let s=0;s<24;s++){const r=oo(s,0,23,0,1),o=oo(n.y(r),0,1,0,t);i.push(`M ${o},0 v${e}`)}this.ticksElem_.setAttributeNS(null,"d",i.join(" "))}onTimer_(){if(null===this.startTime_)return;const t=(new Date).getTime()-this.startTime_,e=t/1e3;this.updateMarker_(e),t>1400&&this.stop(),this.stopped_||requestAnimationFrame(this.onTimer_)}onValueChange_(){this.refresh(),this.play()}};function yc(t,e,i,n){const s=i-t,r=n-e;return Math.sqrt(s*s+r*r)}var Pc=class{constructor(t,e){this.onKeyDown_=this.onKeyDown_.bind(this),this.onKeyUp_=this.onKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.keyScale_=e.keyScale,this.value=e.value,this.sel_=zr(0),this.viewProps=e.viewProps,this.view=new fc(t,{selection:this.sel_,value:this.value,viewProps:this.viewProps}),this.view.element.addEventListener("keydown",this.onKeyDown_),this.view.element.addEventListener("keyup",this.onKeyUp_),this.prevView_=new Cc(t,{value:this.value,viewProps:this.viewProps}),this.prevView_.element.addEventListener("mousedown",t=>{t.stopImmediatePropagation(),t.preventDefault(),this.prevView_.play()}),this.view.previewElement.appendChild(this.prevView_.element);const i=new gl(this.view.element);i.emitter.on("down",this.onPointerDown_),i.emitter.on("move",this.onPointerMove_),i.emitter.on("up",this.onPointerUp_)}refresh(){this.view.refresh(),this.prevView_.refresh(),this.prevView_.play()}updateValue_(t,e,i){const n=this.sel_.rawValue,s=this.value.rawValue.toObject(),r=this.view.positionToValue(t.x,t.y),o=e?function(t,e,i,n){const s=yc(t,e,i,n),r=Math.atan2(n-e,i-t),o=Math.round(r/(Math.PI/4))*Math.PI/4;return{x:t+Math.cos(o)*s,y:e+Math.sin(o)*s}}(n,n,r.x,r.y):r;s[2*n]=o.x,s[2*n+1]=o.y,this.value.setRawValue(new pc(...s),i)}onPointerDown_(t){const e=t.data;if(!e.point)return;const i=this.value.rawValue,n=this.view.valueToPosition(i.x1,i.y1),s=yc(e.point.x,e.point.y,n.x,n.y),r=this.view.valueToPosition(i.x2,i.y2),o=yc(e.point.x,e.point.y,r.x,r.y);this.sel_.rawValue=s<=o?0:1,this.updateValue_(e.point,t.shiftKey,{forceEmit:!1,last:!1})}onPointerMove_(t){const e=t.data;e.point&&this.updateValue_(e.point,t.shiftKey,{forceEmit:!1,last:!1})}onPointerUp_(t){const e=t.data;e.point&&this.updateValue_(e.point,t.shiftKey,{forceEmit:!0,last:!0})}onKeyDown_(t){ml(t.key)&&t.preventDefault();const e=this.sel_.rawValue,i=this.value.rawValue.toObject(),n=this.keyScale_.rawValue;i[2*e]+=dl(n,vl(t)),i[2*e+1]+=dl(n,ul(t)),this.value.setRawValue(new pc(...i),{forceEmit:!1,last:!1})}onKeyUp_(t){ml(t.key)&&t.preventDefault();const e=this.keyScale_.rawValue,i=dl(e,vl(t)),n=dl(e,ul(t));0===i&&0===n||this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}},Ec=class{constructor(t,e){this.value=e.value,this.viewProps=e.viewProps,this.view=new gc(t,{viewProps:this.viewProps}),this.gc_=new Pc(t,{keyScale:e.axis.textProps.value("keyScale"),value:this.value,viewProps:this.viewProps}),this.view.graphElement.appendChild(this.gc_.view.element);const i=Object.assign(Object.assign({},e.axis),{constraint:new Kr({max:1,min:0})}),n=Object.assign(Object.assign({},e.axis),{constraint:void 0});this.tc_=new bh(t,{assembly:hc,axes:[i,n,i,n],parser:no,value:this.value,viewProps:this.viewProps}),this.view.textElement.appendChild(this.tc_.view.element)}get allFocusableElements(){return[this.gc_.view.element,...this.tc_.view.textViews.map(t=>t.inputElement)]}refresh(){this.gc_.refresh()}},kc=class{constructor(t,e){this.onButtonBlur_=this.onButtonBlur_.bind(this),this.onButtonClick_=this.onButtonClick_.bind(this),this.onPopupChildBlur_=this.onPopupChildBlur_.bind(this),this.onPopupChildKeydown_=this.onPopupChildKeydown_.bind(this),this.value=e.value,this.viewProps=e.viewProps,this.foldable_=_a.create(e.expanded),this.view=new mc(t,{foldable:this.foldable_,pickerLayout:e.pickerLayout,viewProps:this.viewProps}),this.view.buttonElement.addEventListener("blur",this.onButtonBlur_),this.view.buttonElement.addEventListener("click",this.onButtonClick_),this.tc_=new sl(t,{parser:uc,props:Rr.fromObject({formatter:cc}),value:this.value,viewProps:this.viewProps}),this.view.textElement.appendChild(this.tc_.view.element),this.popC_="popup"===e.pickerLayout?new el(t,{viewProps:this.viewProps}):null;const i=new Ec(t,{axis:e.axis,value:this.value,viewProps:this.viewProps});i.allFocusableElements.forEach(t=>{t.addEventListener("blur",this.onPopupChildBlur_),t.addEventListener("keydown",this.onPopupChildKeydown_)}),this.pickerC_=i,this.popC_?(this.view.element.appendChild(this.popC_.view.element),this.popC_.view.element.appendChild(this.pickerC_.view.element),Io(this.popC_.shows,t=>{t&&i.refresh()}),cl({primary:this.foldable_.value("expanded"),secondary:this.popC_.shows,forward:t=>t,backward:(t,e)=>e})):this.view.pickerElement&&(this.view.pickerElement.appendChild(this.pickerC_.view.element),xa(this.foldable_,this.view.pickerElement))}onButtonBlur_(t){if(!this.popC_)return;const e=t.relatedTarget;e&&this.popC_.view.element.contains(e)||(this.popC_.shows.rawValue=!1)}onButtonClick_(){this.foldable_.set("expanded",!this.foldable_.get("expanded")),this.foldable_.get("expanded")&&this.pickerC_.allFocusableElements[0].focus()}onPopupChildBlur_(t){if(!this.popC_)return;const e=this.popC_.view.element,i=Ko(t);i&&e.contains(i)||i&&i===this.view.buttonElement&&!Oo(e.ownerDocument)||(this.popC_.shows.rawValue=!1)}onPopupChildKeydown_(t){this.popC_&&"Escape"===t.key&&(this.popC_.shows.rawValue=!1)}},Vc=pa({id:"cubicbezier",type:"blade",accept(t){const e=Lo(t,t=>({value:t.required.array(t.required.number),view:t.required.constant("cubicbezier"),expanded:t.optional.boolean,label:t.optional.string,picker:t.optional.custom(t=>"inline"===t||"popup"===t?t:void 0)}));return e?{params:e}:null},controller(t){var e,i;const n=zr(new pc(...t.params.value),{constraint:new uh({assembly:hc,components:[0,1,2,3].map(t=>t%2==0?new Kr({min:0,max:1}):void 0)}),equals:pc.equals}),s=new kc(t.document,{axis:{textProps:Rr.fromObject({keyScale:.1,pointerScale:.01,formatter:ro(2)})},expanded:null!==(e=t.params.expanded)&&void 0!==e&&e,pickerLayout:null!==(i=t.params.picker)&&void 0!==i?i:"popup",value:n,viewProps:t.viewProps});return new Qo(t.document,{blade:t.blade,props:Rr.fromObject({label:t.params.label}),value:n,valueController:s})},api:t=>t.controller instanceof Qo&&t.controller.valueController instanceof kc?new oc(t.controller):null}),Lc=class extends _o{get fps(){return this.controller.valueController.fps}get max(){return this.controller.valueController.props.get("max")}set max(t){this.controller.valueController.props.set("max",t)}get min(){return this.controller.valueController.props.get("min")}set min(t){this.controller.valueController.props.set("min",t)}begin(){this.controller.valueController.begin()}end(){this.controller.valueController.end()}on(t,e){const i=e.bind(this);return this.controller.valueController.ticker.emitter.on(t,()=>{i(new fo(this))}),this}},Mc=class{constructor(){this.start_=null,this.duration_=0,this.fps_=null,this.frameCount_=0,this.timestamps_=[]}get duration(){return this.duration_}get fps(){return this.fps_}begin(t){this.start_=t.getTime()}calculateFps_(t){if(0===this.timestamps_.length)return null;const e=this.timestamps_[0];return 1e3*(this.frameCount_-e.frameCount)/(t-e.time)}compactTimestamps_(){if(this.timestamps_.length<=20)return;const t=this.timestamps_.length-20;this.timestamps_.splice(0,t);const e=this.timestamps_[0].frameCount;this.timestamps_.forEach(t=>{t.frameCount-=e}),this.frameCount_-=e}end(t){if(null===this.start_)return;const e=t.getTime();this.duration_=e-this.start_,this.start_=null,this.fps_=this.calculateFps_(e),this.timestamps_.push({frameCount:this.frameCount_,time:e}),++this.frameCount_,this.compactTimestamps_()}},Sc=$o("fps"),jc=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(Sc()),e.viewProps.bindClassModifiers(this.element),this.graphElement=t.createElement("div"),this.graphElement.classList.add(Sc("g")),this.element.appendChild(this.graphElement);const i=t.createElement("div");i.classList.add(Sc("l")),this.element.appendChild(i);const n=t.createElement("span");n.classList.add(Sc("v")),n.textContent="--",i.appendChild(n),this.valueElement=n;const s=t.createElement("span");s.classList.add(Sc("u")),s.textContent="FPS",i.appendChild(s)}},Dc=class{constructor(t,e){this.stopwatch_=new Mc,this.onTick_=this.onTick_.bind(this),this.ticker=e.ticker,this.ticker.emitter.on("tick",this.onTick_),this.props=e.props,this.value_=e.value,this.viewProps=e.viewProps,this.view=new jc(t,{viewProps:this.viewProps}),this.graphC_=new Qh(t,{formatter:ro(0),props:this.props,rows:e.rows,value:this.value_,viewProps:this.viewProps}),this.view.graphElement.appendChild(this.graphC_.view.element),this.viewProps.handleDispose(()=>{this.graphC_.viewProps.set("disposed",!0),this.ticker.dispose()})}get fps(){return this.stopwatch_.fps}begin(){this.stopwatch_.begin(new Date)}end(){this.stopwatch_.end(new Date)}onTick_(){const t=this.fps;if(null!==t){const e=this.value_.rawValue;this.value_.rawValue=function(t,e){const i=[...ta(t),e];return i.length>t.length?i.splice(0,i.length-t.length):Jo(i,t.length),i}(e,t),this.view.valueElement.textContent=t.toFixed(0)}}},Ac=class extends Wo{constructor(t,e){const i=e.valueController,n=new Go(t,{blade:e.blade,props:e.labelProps,valueController:i});super({blade:e.blade,view:n.view,viewProps:i.viewProps}),this.valueController=i,this.labelController=n}};function Oc(t,e){return 0===e?new Ua:new Fa(t,null!=e?e:Kh)}var Bc=pa({id:"fpsgraph",type:"blade",accept(t){const e=Lo(t,t=>({view:t.required.constant("fpsgraph"),interval:t.optional.number,label:t.optional.string,rows:t.optional.number,max:t.optional.number,min:t.optional.number}));return e?{params:e}:null},controller(t){var e,i,n,s;const r=null!==(e=t.params.interval)&&void 0!==e?e:500;return new Ac(t.document,{blade:t.blade,labelProps:Rr.fromObject({label:t.params.label}),valueController:new Dc(t.document,{props:Rr.fromObject({max:null!==(i=t.params.max)&&void 0!==i?i:90,min:null!==(n=t.params.min)&&void 0!==n?n:0}),rows:null!==(s=t.params.rows)&&void 0!==s?s:2,ticker:Oc(t.document,r),value:zr(Zo(80)),viewProps:t.viewProps})})},api:t=>t.controller instanceof Ac?new Lc(t.controller):null}),Tc=class{constructor(t,e){this.min=t,this.max=e}static isObject(t){if("object"!=typeof t||null===t)return!1;const e=t.min,i=t.max;return"number"==typeof e&&"number"==typeof i}static equals(t,e){return t.min===e.min&&t.max===e.max}get length(){return this.max-this.min}toObject(){return{min:this.min,max:this.max}}},zc={fromComponents:t=>new Tc(t[0],t[1]),toComponents:t=>[t.min,t.max]},Rc=class{constructor(t){this.edge=t}constrain(t){var e,i,n,s,r,o,a,l;if(t.min<=t.max)return new Tc(null!==(i=null===(e=this.edge)||void 0===e?void 0:e.constrain(t.min))&&void 0!==i?i:t.min,null!==(s=null===(n=this.edge)||void 0===n?void 0:n.constrain(t.max))&&void 0!==s?s:t.max);const p=(t.min+t.max)/2;return new Tc(null!==(o=null===(r=this.edge)||void 0===r?void 0:r.constrain(p))&&void 0!==o?o:p,null!==(l=null===(a=this.edge)||void 0===a?void 0:a.constrain(p))&&void 0!==l?l:p)}},Nc=$o("rsltxt"),Kc=class{constructor(t,e){this.sliderView_=e.sliderView,this.textView_=e.textView,this.element=t.createElement("div"),this.element.classList.add(Nc());const i=t.createElement("div");i.classList.add(Nc("s")),i.appendChild(this.sliderView_.element),this.element.appendChild(i);const n=t.createElement("div");n.classList.add(Nc("t")),n.appendChild(this.textView_.element),this.element.appendChild(n)}},Ic=$o("rsl"),Uc=class{constructor(t,e){this.onSliderPropsChange_=this.onSliderPropsChange_.bind(this),this.onValueChange_=this.onValueChange_.bind(this),this.sliderProps_=e.sliderProps,this.sliderProps_.emitter.on("change",this.onSliderPropsChange_),this.element=t.createElement("div"),this.element.classList.add(Ic()),e.viewProps.bindClassModifiers(this.element),this.value_=e.value,this.value_.emitter.on("change",this.onValueChange_);const i=t.createElement("div");i.classList.add(Ic("t")),this.element.appendChild(i),this.trackElement=i;const n=t.createElement("div");n.classList.add(Ic("b")),i.appendChild(n),this.barElement=n;const s=["min","max"].map(e=>{const n=t.createElement("div");return n.classList.add(Ic("k"),Ic("k",e)),i.appendChild(n),n});this.knobElements=[s[0],s[1]],this.update_()}valueToX_(t){return 100*lo(oo(t,this.sliderProps_.get("min"),this.sliderProps_.get("max"),0,1),0,1)}update_(){const t=this.value_.rawValue;0===t.length?this.element.classList.add(Ic(void 0,"zero")):this.element.classList.remove(Ic(void 0,"zero"));const e=[this.valueToX_(t.min),this.valueToX_(t.max)];this.barElement.style.left=`${e[0]}%`,this.barElement.style.right=100-e[1]+"%",this.knobElements.forEach((t,i)=>{t.style.left=`${e[i]}%`})}onSliderPropsChange_(){this.update_()}onValueChange_(){this.update_()}},Fc=class{constructor(t,e){this.grabbing_=null,this.grabOffset_=0,this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.sliderProps=e.sliderProps,this.viewProps=e.viewProps,this.value=e.value,this.view=new Uc(t,{sliderProps:this.sliderProps,value:this.value,viewProps:e.viewProps});const i=new gl(this.view.trackElement);i.emitter.on("down",this.onPointerDown_),i.emitter.on("move",this.onPointerMove_),i.emitter.on("up",this.onPointerUp_)}ofs_(){return"min"===this.grabbing_?this.view.knobElements[0].getBoundingClientRect().width/2:"max"===this.grabbing_?-this.view.knobElements[1].getBoundingClientRect().width/2:0}valueFromData_(t){return t.point?oo((t.point.x+this.ofs_())/t.bounds.width,0,1,this.sliderProps.get("min"),this.sliderProps.get("max")):null}onPointerDown_(t){if(!t.data.point)return;const e=t.data.point.x/t.data.bounds.width,i=this.value.rawValue,n=this.sliderProps.get("min"),s=this.sliderProps.get("max"),r=oo(i.min,n,s,0,1),o=oo(i.max,n,s,0,1);Math.abs(o-e)<=.025?this.grabbing_="max":Math.abs(r-e)<=.025?this.grabbing_="min":e>=r&&e<=o?(this.grabbing_="length",this.grabOffset_=oo(e-r,0,1,0,s-n)):eo&&(this.grabbing_="max",this.onPointerMove_(t))}applyPointToValue_(t,e){const i=this.valueFromData_(t);if(null===i)return;const n=this.sliderProps.get("min"),s=this.sliderProps.get("max");if("min"===this.grabbing_)this.value.setRawValue(new Tc(i,this.value.rawValue.max),e);else if("max"===this.grabbing_)this.value.setRawValue(new Tc(this.value.rawValue.min,i),e);else if("length"===this.grabbing_){const t=this.value.rawValue.length;let r=i-this.grabOffset_,o=r+t;rs&&(r=s-t,o=s),this.value.setRawValue(new Tc(r,o),e)}}onPointerMove_(t){this.applyPointToValue_(t.data,{forceEmit:!1,last:!1})}onPointerUp_(t){this.applyPointToValue_(t.data,{forceEmit:!0,last:!0}),this.grabbing_=null}},$c=class{constructor(t,e){this.value=e.value,this.viewProps=e.viewProps,this.sc_=new Fc(t,e);const i={constraint:e.constraint,textProps:e.textProps};this.tc_=new bh(t,{assembly:zc,axes:[i,i],parser:e.parser,value:this.value,viewProps:e.viewProps}),this.view=new Kc(t,{sliderView:this.sc_.view,textView:this.tc_.view})}get textController(){return this.tc_}};function qc(t){return Tc.isObject(t)?new Tc(t.min,t.max):new Tc(0,0)}function Hc(t,e){t.writeProperty("max",e.max),t.writeProperty("min",e.min)}var Gc=pa({id:"input-interval",type:"input",accept:(t,e)=>{if(!Tc.isObject(t))return null;const i=Lo(e,t=>Object.assign(Object.assign({},go(t)),{readonly:t.optional.constant(!1)}));return i?{initialValue:new Tc(t.min,t.max),params:i}:null},binding:{reader:t=>qc,constraint:t=>function(t){const e=[],i=mo(t);i&&e.push(i);const n=vo(t);return n&&e.push(n),new Rc(new $a(e))}(t.params),equals:Tc.equals,writer:t=>Hc},controller(t){const e=t.value,i=t.constraint;if(!(i instanceof Rc))throw jr.shouldNeverHappen();const n=(e.rawValue.min+e.rawValue.max)/2,s=Rr.fromObject(bo(t.params,n)),r=i.edge&&qa(i.edge,Nr);if(r)return new $c(t.document,{constraint:i.edge,parser:no,sliderProps:new Rr({keyScale:s.value("keyScale"),max:r.values.value("max"),min:r.values.value("min")}),textProps:s,value:e,viewProps:t.viewProps});const o={constraint:i.edge,textProps:s};return new bh(t.document,{assembly:zc,axes:[o,o],parser:no,value:e,viewProps:t.viewProps})}}),Yc=class{constructor(t){this.controller_=t}get disabled(){return this.controller_.viewProps.get("disabled")}set disabled(t){this.controller_.viewProps.set("disabled",t)}get title(){var t;return null!==(t=this.controller_.props.get("title"))&&void 0!==t?t:""}set title(t){this.controller_.props.set("title",t)}},Xc=class extends xo{constructor(t,e,i,n,s){super(t,n,s),this.cell=e,this.index=i}},Wc=class extends _o{constructor(t){super(t),this.cellToApiMap_=new Map,this.controller.valueController.cellControllers.forEach(t=>{const e=new Yc(t);this.cellToApiMap_.set(t,e)})}get value(){return this.controller.value}cell(t,e){const i=this.controller.valueController,n=i.cellControllers[e*i.size[0]+t];return this.cellToApiMap_.get(n)}on(t,e){const i=e.bind(this);this.controller.value.emitter.on(t,t=>{const e=this.controller.valueController,n=e.findCellByValue(t.rawValue);if(!n)return;const s=this.cellToApiMap_.get(n);if(!s)return;const r=e.cellControllers.indexOf(n);i(new Xc(this,s,[r%e.size[0],Math.floor(r/e.size[0])],t.rawValue))})}},Qc=$o("rad"),Jc=class{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(Qc()),e.viewProps.bindClassModifiers(this.element);const i=t.createElement("label");i.classList.add(Qc("l")),this.element.appendChild(i);const n=t.createElement("input");n.classList.add(Qc("i")),n.name=e.name,n.type="radio",e.viewProps.bindDisabled(n),i.appendChild(n),this.inputElement=n;const s=t.createElement("div");s.classList.add(Qc("b")),i.appendChild(s);const r=t.createElement("div");r.classList.add(Qc("t")),s.appendChild(r),Uo(e.props,"title",t=>{r.textContent=t})}},Zc=class{constructor(t,e){this.props=e.props,this.viewProps=e.viewProps,this.view=new Jc(t,{name:e.name,props:this.props,viewProps:this.viewProps})}},td=class{constructor(t,e){this.cellCs_=[],this.cellValues_=[],this.onCellInputChange_=this.onCellInputChange_.bind(this),this.size=e.size;const[i,n]=this.size;for(let s=0;s{const e=this.findCellByValue(t);e&&(e.view.inputElement.checked=!0)}),this.viewProps=La.create(),this.view=new Ml(t,{viewProps:this.viewProps,viewName:"radgrid"}),this.view.element.style.gridTemplateColumns=`repeat(${i}, 1fr)`,this.cellCs_.forEach(t=>{t.view.inputElement.addEventListener("change",this.onCellInputChange_),this.view.element.appendChild(t.view.element)})}get cellControllers(){return this.cellCs_}findCellByValue(t){const e=this.cellValues_.findIndex(e=>e===t);return e<0?null:this.cellCs_[e]}onCellInputChange_(t){const e=t.currentTarget,i=this.cellCs_.findIndex(t=>t.view.inputElement===e);i<0||(this.value.rawValue=this.cellValues_[i])}},ed=pa({id:"radiogrid",type:"blade",accept(t){const e=Lo(t,t=>({cells:t.required.function,groupName:t.required.string,size:t.required.array(t.required.number),value:t.required.raw,view:t.required.constant("radiogrid"),label:t.optional.string}));return e?{params:e}:null},controller(t){const e=zr(t.params.value);return new Qo(t.document,{blade:t.blade,props:Rr.fromObject({label:t.params.label}),value:e,valueController:new td(t.document,{groupName:t.params.groupName,cellConfig:t.params.cells,size:t.params.size,value:e})})},api:t=>t.controller instanceof Qo&&t.controller.valueController instanceof td?new Wc(t.controller):null});function id(t){return pa({id:"input-radiogrid",type:"input",accept(e,i){if(!t.isType(e))return null;const n=Lo(i,t=>({cells:t.required.function,groupName:t.required.string,size:t.required.array(t.required.number),view:t.required.constant("radiogrid")}));return n?{initialValue:e,params:n}:null},binding:t.binding,controller:t=>new td(t.document,{cellConfig:t.params.cells,groupName:t.params.groupName,size:t.params.size,value:t.value})})}var nd=id({isType:t=>"number"==typeof t,binding:{reader:t=>so,writer:t=>Ol}}),sd=id({isType:t=>"string"==typeof t,binding:{reader:t=>pl,writer:t=>Ol}}),rd=id({isType:t=>"boolean"==typeof t,binding:{reader:t=>rl,writer:t=>Ol}}),od="essentials",ad='.tp-cbzgv,.tp-radv_b,.tp-rslv_k,.tp-cbzv_b{-webkit-appearance:none;-moz-appearance:none;appearance:none;background-color:rgba(0,0,0,0);border-width:0;font-family:inherit;font-size:inherit;font-weight:inherit;margin:0;outline:none;padding:0}.tp-radv_b,.tp-rslv_k,.tp-cbzv_b{background-color:var(--btn-bg);border-radius:var(--bld-br);color:var(--btn-fg);cursor:pointer;display:block;font-weight:bold;height:var(--cnt-usz);line-height:var(--cnt-usz);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.tp-radv_b:hover,.tp-rslv_k:hover,.tp-cbzv_b:hover{background-color:var(--btn-bg-h)}.tp-radv_b:focus,.tp-rslv_k:focus,.tp-cbzv_b:focus{background-color:var(--btn-bg-f)}.tp-radv_b:active,.tp-rslv_k:active,.tp-cbzv_b:active{background-color:var(--btn-bg-a)}.tp-radv_b:disabled,.tp-rslv_k:disabled,.tp-cbzv_b:disabled{opacity:.5}.tp-cbzgv{background-color:var(--in-bg);border-radius:var(--bld-br);box-sizing:border-box;color:var(--in-fg);font-family:inherit;height:var(--cnt-usz);line-height:var(--cnt-usz);min-width:0;width:100%}.tp-cbzgv:hover{background-color:var(--in-bg-h)}.tp-cbzgv:focus{background-color:var(--in-bg-f)}.tp-cbzgv:active{background-color:var(--in-bg-a)}.tp-cbzgv:disabled{opacity:.5}.tp-btngridv{border-radius:var(--bld-br);display:grid;overflow:hidden;gap:2px}.tp-btngridv.tp-v-disabled{opacity:.5}.tp-btngridv .tp-btnv_b:disabled{opacity:1}.tp-btngridv .tp-btnv_b:disabled .tp-btnv_t{opacity:.5}.tp-btngridv .tp-btnv_b{border-radius:0}.tp-cbzv{position:relative}.tp-cbzv_h{display:flex}.tp-cbzv_b{margin-right:4px;position:relative;width:var(--cnt-usz)}.tp-cbzv_b svg{display:block;height:16px;left:50%;margin-left:-8px;margin-top:-8px;position:absolute;top:50%;width:16px}.tp-cbzv_b svg path{stroke:var(--bs-bg);stroke-width:2}.tp-cbzv_t{flex:1}.tp-cbzv_p{height:0;margin-top:0;opacity:0;overflow:hidden;transition:height .2s ease-in-out,opacity .2s linear,margin .2s ease-in-out}.tp-cbzv.tp-cbzv-expanded .tp-cbzv_p{margin-top:var(--cnt-usp);opacity:1}.tp-cbzv.tp-cbzv-cpl .tp-cbzv_p{overflow:visible}.tp-cbzv .tp-popv{left:calc(-1 * var(--cnt-hp));position:absolute;right:calc(-1 * var(--cnt-hp));top:var(--cnt-usz)}.tp-cbzpv_t{margin-top:var(--cnt-usp)}.tp-cbzgv{height:auto;overflow:hidden;position:relative}.tp-cbzgv.tp-v-disabled{opacity:.5}.tp-cbzgv_p{left:16px;position:absolute;right:16px;top:0}.tp-cbzgv_g{cursor:pointer;display:block;height:calc(var(--cnt-usz) * 5);width:100%}.tp-cbzgv_u{opacity:.1;stroke:var(--in-fg);stroke-dasharray:1}.tp-cbzgv_l{fill:rgba(0,0,0,0);stroke:var(--in-fg)}.tp-cbzgv_v{opacity:.5;stroke:var(--in-fg);stroke-dasharray:1}.tp-cbzgv_h{border:var(--in-fg) solid 1px;border-radius:50%;box-sizing:border-box;height:4px;margin-left:-2px;margin-top:-2px;pointer-events:none;position:absolute;width:4px}.tp-cbzgv:focus .tp-cbzgv_h-sel{background-color:var(--in-fg);border-width:0}.tp-cbzprvv{cursor:pointer;height:4px;padding:4px 0;position:relative}.tp-cbzprvv_g{display:block;height:100%;overflow:visible;width:100%}.tp-cbzprvv_t{opacity:.5;stroke:var(--mo-fg)}.tp-cbzprvv_m{background-color:var(--mo-fg);border-radius:50%;height:4px;margin-left:-2px;margin-top:-2px;opacity:0;position:absolute;top:50%;transition:opacity .2s ease-out;width:4px}.tp-cbzprvv_m.tp-cbzprvv_m-a{opacity:1}.tp-fpsv{position:relative}.tp-fpsv_l{bottom:4px;color:var(--mo-fg);line-height:1;right:4px;pointer-events:none;position:absolute}.tp-fpsv_u{margin-left:.2em;opacity:.7}.tp-rslv{cursor:pointer;padding-left:8px;padding-right:8px}.tp-rslv.tp-v-disabled{opacity:.5}.tp-rslv_t{height:calc(var(--cnt-usz));position:relative}.tp-rslv_t::before{background-color:var(--in-bg);border-radius:1px;content:"";height:2px;margin-top:-1px;position:absolute;top:50%;left:-4px;right:-4px}.tp-rslv_b{bottom:0;top:0;position:absolute}.tp-rslv_b::before{background-color:var(--in-fg);content:"";height:2px;margin-top:-1px;position:absolute;top:50%;left:0;right:0}.tp-rslv_k{height:calc(var(--cnt-usz) - 8px);margin-top:calc((var(--cnt-usz) - 8px)/-2);position:absolute;top:50%;width:8px}.tp-rslv_k.tp-rslv_k-min{margin-left:-8px}.tp-rslv_k.tp-rslv_k-max{margin-left:0}.tp-rslv.tp-rslv-zero .tp-rslv_k.tp-rslv_k-min{border-bottom-right-radius:0;border-top-right-radius:0}.tp-rslv.tp-rslv-zero .tp-rslv_k.tp-rslv_k-max{border-bottom-left-radius:0;border-top-left-radius:0}.tp-rsltxtv{display:flex}.tp-rsltxtv_s{flex:1}.tp-rsltxtv_t{flex:1;margin-left:4px}.tp-radv_l{display:block;position:relative}.tp-radv_i{left:0;opacity:0;position:absolute;top:0}.tp-radv_b{opacity:.5}.tp-radv_i:hover+.tp-radv_b{background-color:var(--btn-bg-h)}.tp-radv_i:focus+.tp-radv_b{background-color:var(--btn-bg-f)}.tp-radv_i:active+.tp-radv_b{background-color:var(--btn-bg-a)}.tp-radv_i:checked+.tp-radv_b{opacity:1}.tp-radv_t{bottom:0;color:inherit;left:0;overflow:hidden;position:absolute;right:0;text-align:center;text-overflow:ellipsis;top:0}.tp-radv_i:disabled+.tp-radv_b>.tp-radv_t{opacity:.5}.tp-radgridv{border-radius:var(--bld-br);display:grid;overflow:hidden;gap:2px}.tp-radgridv.tp-v-disabled{opacity:.5}.tp-radgridv .tp-radv_b{border-radius:0}',ld=[rc,Vc,Bc,Gc,ed,rd,nd,sd],pd=(t,e,i="BG")=>{const n="a"in e;t.addBinding({get color(){return e.hex},set color(t){e.setColorByHEX(t)}},"color",{label:`${i} Color`,picker:"inline",expanded:!0}),n&&t.addBinding(e,"a",{min:0,max:1,step:.01,label:`${i} Alpha`})},hd=t=>{const e=(()=>{const t=window.location.pathname.split("/"),e=t.indexOf("examples"),i=Math.max(0,t.length-e-2);return"../".repeat(i)})(),i=t=>e+t;return Array.isArray(t)?t.map(i):i(t)},cd=t=>{if("number"==typeof t)return{value:t,unit:"number"};const e=String(t);return e.endsWith("%")?{value:parseFloat(e),unit:"%"}:(e.endsWith("px"),{value:parseFloat(e),unit:"px"})},dd=({gui:t,redGPUContext:e})=>((0,r.useEffect)(()=>{const i=t.addFolder({title:"RedGPUContext"});i.addBinding(e,"renderScale",{min:.01,max:1,step:.01}),i.addBlade({view:"separator"}),e.backgroundColor&&(pd(i,e.backgroundColor),i.addBlade({view:"separator"})),i.addBinding(e,"alphaMode",{options:{opaque:"opaque",premultiplied:"premultiplied"}}),i.addBlade({view:"separator"});const n=cd(e.width),s=cd(e.height),r={width:n.value,widthUnit:n.unit,height:s.value,heightUnit:s.unit},o=i.addFolder({title:"Size"}),a=()=>{e.width="number"===r.widthUnit?r.width:`${r.width}${r.widthUnit}`};o.addBinding(r,"width",{min:0,max:"%"===n.unit?200:4096,step:.01}).on("change",a),o.addBinding(r,"widthUnit",{options:{"%":"%",px:"px",number:"number"}}).on("change",t=>{a()});const l=()=>{e.height="number"===r.heightUnit?r.height:`${r.height}${r.heightUnit}`};o.addBinding(r,"height",{min:0,max:"%"===s.unit?200:4096,step:.01}).on("change",l),o.addBinding(r,"heightUnit",{options:{"%":"%",px:"px",number:"number"}}).on("change",()=>{l()});const p=i.addFolder({title:"setSize method test",expanded:!1});[["300","300"],["600","300"],["50%","300"],["300","50%"],["100%","100%"]].forEach(([t,i])=>{const n=`setSize(${t}, ${i})`;p.addButton({title:n}).on("click",()=>e.setSize(t,i))}),i.addBlade({view:"separator"});const h=i.addFolder({title:"Rect Info",expanded:!0});h.addBinding({get dpr(){return window.devicePixelRatio}},"dpr",{readonly:!0,label:"DPR",interval:500});const c={get screen(){const t=e.screenRectObject;return`x: ${t.x.toFixed(2)}, y: ${t.y.toFixed(2)}\nw: ${t.width.toFixed(2)}, h: ${t.height.toFixed(2)}`},get pixel(){const t=e.pixelRectObject;return`x: ${t.x}, y: ${t.y}\nw: ${t.width}, h: ${t.height}`}};return h.addBinding(c,"screen",{readonly:!0,label:"Screen Rect",multiline:!0,rows:2,interval:32}),h.addBinding(c,"pixel",{readonly:!0,label:"Pixel Rect",multiline:!0,rows:2,interval:32}),()=>{i.dispose()}},[t,e]),null),ud=(t,e)=>{e.addBinding(t,"useBackgroundColor"),t.backgroundColor&&pd(e,t.backgroundColor)},vd=({gui:t,scene:e})=>((0,r.useEffect)(()=>{if(!e)return;const i=e.name||"Scene",n=t.addFolder({title:i});return ud(e,n),()=>{n.dispose()}},[t,e]),null),md=({gui:t,redGPUContext:e})=>((0,r.useEffect)(()=>{const i=e.viewList;if(0===i.length)return;const n=1===i.length?i[0].name?.replace(/Instance/g,"")||"View 0":"ViewList",s=t.addFolder({title:n}),r=(t,e)=>{if("View3D"===t.constructor.name){e.addBinding(t,"useFrustumCulling"),e.addBinding(t,"useDistanceCulling"),e.addBinding(t,"distanceCulling",{min:0,max:1e3,step:1}),e.addBlade({view:"separator"});const i=e.addFolder({title:"Debug Helpers"}),n={get grid(){return!!t.grid},set grid(e){t.grid=e},get axis(){return!!t.axis},set axis(e){t.axis=e}};i.addBinding(n,"grid",{label:"Show Grid"}),i.addBinding(n,"axis",{label:"Show Axis"}),e.addBlade({view:"separator"})}const i={width:cd(t.width).value,widthUnit:cd(t.width).unit,height:cd(t.height).value,heightUnit:cd(t.height).unit,x:cd(t.x).value,xUnit:cd(t.x).unit,y:cd(t.y).value,yUnit:cd(t.y).unit},n=e.addFolder({title:"Size & Position"}),s=e=>{const n=i[e],s=i[`${e}Unit`];t[e]="number"===s?n:`${n}${s}`};if(["width","height","x","y"].forEach(t=>{const e=t,r=`${e}Unit`;n.addBinding(i,e,{min:0,max:"%"===i[r]?200:4096,step:.01}).on("change",()=>s(e)),n.addBinding(i,r,{label:`${e} Unit`,options:{"%":"%",px:"px",number:"number"}}).on("change",()=>s(e))}),t.scene){e.addBlade({view:"separator"});const i=e.addFolder({title:t.scene.name||"Scene",expanded:!0});ud(t.scene,i)}};if(1===i.length)r(i[0],s);else{const t=s.addTab({pages:i.map((t,e)=>({title:t.name?.replace(/Instance/g,"")||`View ${e}`}))});i.forEach((e,i)=>{r(e,t.pages[i])})}return()=>{s.dispose()}},[t,e]),null),bd=[{name:"2K - the sky is on fire",path:"assets/hdr/2k/the_sky_is_on_fire_2k.hdr",nit:3e4},{name:"Cannon_Exterior",path:"assets/hdr/Cannon_Exterior.hdr",nit:25e3},{name:"field",path:"assets/hdr/field.hdr",nit:3e4},{name:"neutral.37290948",path:"assets/hdr/neutral.37290948.hdr",nit:2e4},{name:"pisa",path:"assets/hdr/pisa.hdr",nit:25e3},{name:"6 cube face asset",path:["assets/skybox/px.jpg","assets/skybox/nx.jpg","assets/skybox/py.jpg","assets/skybox/ny.jpg","assets/skybox/pz.jpg","assets/skybox/nz.jpg"],nit:100}],gd=({gui:t,view:e})=>{const i=s(t=>t.RedGPU);return(0,r.useEffect)(()=>{if(!e)return;const n=t.addFolder({title:"Lighting",expanded:!0}),s={texture:bd[0].name,useLight:e.scene.lightManager.directionalLights.length>0,lux:e.scene.lightManager.directionalLights[0]?.lux||1e5,useIBL:!0,intensityMultiplier:e.ibl?.intensityMultiplier||1},r={finalPath:""};let o;const a=n=>{if(!s.useIBL)return;const a=bd.find(t=>t.name===n);if(!a)return;const l=a.path;(t=>{const e=t=>t.split("/").pop()||t;r.finalPath=Array.isArray(t)?t.map(e).join("\n"):e(t),o&&o.refresh()})(l);const p=hd(l),h=a.nit||2e4;if(i){const t=new i.Resource.IBL(e.redGPUContext,p,h);t.intensityMultiplier=s.intensityMultiplier,e.ibl=t}t.refresh()},l=n=>{if(n){if(0===e.scene.lightManager.directionalLights.length&&i){const t=new i.Light.DirectionalLight;t.lux=s.lux,e.scene.lightManager.addDirectionalLight(t)}}else e.scene.lightManager.removeAllLight();t.refresh()};n.addBinding(s,"useLight").on("change",t=>l(t.value)),n.addBinding(s,"lux",{min:0,max:1e5,step:1}).on("change",t=>{const i=e.scene.lightManager.directionalLights;i.length>0&&(i[0].lux=t.value)}),n.addBinding(s,"useIBL").on("change",t=>{t.value?(a(s.texture),p.disabled=!1):(e.ibl=null,p.disabled=!0)});const p=n.addFolder({title:"IBL Settings",expanded:!0});return p.addBinding(s,"texture",{options:bd.reduce((t,e)=>({...t,[e.name]:e.name}),{})}).on("change",t=>a(t.value)),p.addBinding(s,"intensityMultiplier",{min:0,max:5,step:.1}).on("change",t=>{e.ibl&&(e.ibl.intensityMultiplier=t.value)}),p.addBinding({get luminance(){return e.ibl?e.ibl.luminance:0},set luminance(t){e.ibl&&(e.ibl.luminance=t)}},"luminance",{min:0,max:1e5,step:100}),o=p.addBinding(r,"finalPath",{readonly:!0,label:"source",multiline:!0,rows:2}),l(s.useLight),s.useIBL?a(s.texture):p.disabled=!0,()=>{n.dispose()}},[t,e,i]),null},wd=({gui:t,view:e})=>{const i=s(t=>t.RedGPU);return(0,r.useEffect)(()=>{if(!e)return;const n=t.addFolder({title:"SkyBox",expanded:!0}),s={useSkyBox:!0,texture:bd[0].name,blur:e.skybox?.blur||0,intensityMultiplier:e.skybox?.intensityMultiplier||1,opacity:e.skybox?.opacity||1},r={finalPath:""};let o;const a=n=>{if(!s.useSkyBox)return;const a=bd.find(t=>t.name===n);if(!a)return;const l=a.path;(t=>{const e=t=>t.split("/").pop()||t;r.finalPath=Array.isArray(t)?t.map(e).join("\n"):e(t),o&&o.refresh()})(l);const p=hd(l),h=a.nit||2e4;if(i){const t="string"==typeof l&&l.toLowerCase().endsWith(".hdr")?new i.Resource.IBL(e.redGPUContext,p,h).environmentTexture:new i.Resource.CubeTexture(e.redGPUContext,p,!0);e.skybox?(e.skybox.texture=t,e.skybox.luminance=h):e.skybox=new i.Display.SkyBox(e.redGPUContext,t,h),e.skybox.blur=s.blur,e.skybox.intensityMultiplier=s.intensityMultiplier,e.skybox.opacity=s.opacity}t.refresh()};n.addBinding(s,"useSkyBox").on("change",t=>{t.value?(a(s.texture),l.disabled=!1):(e.skybox=null,l.disabled=!0)});const l=n.addFolder({title:"SkyBox Settings",expanded:!0});return l.addBinding(s,"texture",{options:bd.reduce((t,e)=>({...t,[e.name]:e.name}),{})}).on("change",t=>a(t.value)),l.addBinding(s,"blur",{min:0,max:1,step:.01}).on("change",t=>{e.skybox&&(e.skybox.blur=t.value)}),l.addBinding(s,"intensityMultiplier",{min:0,max:5,step:.1}).on("change",t=>{e.skybox&&(e.skybox.intensityMultiplier=t.value)}),l.addBinding(s,"opacity",{min:0,max:1,step:.01}).on("change",t=>{e.skybox&&(e.skybox.opacity=t.value)}),l.addBinding({get luminance(){return e.skybox?e.skybox.luminance:0},set luminance(t){e.skybox&&(e.skybox.luminance=t)}},"luminance",{min:0,max:1e5,step:100}),o=l.addBinding(r,"finalPath",{readonly:!0,label:"source",multiline:!0,rows:2}),s.useSkyBox?a(s.texture):l.disabled=!0,()=>{n.dispose()}},[t,e,i]),null},_d=n(),fd=()=>{const t=s(t=>t.guiConfig),e=s(t=>t.redGPUContext),i=(0,r.useRef)(null),[n,o]=(0,r.useState)(null);return(0,r.useEffect)(()=>{if(i.current&&t){const n=new yr({container:i.current});if(n.registerPlugin(Pr),o(n),t.gui)try{t.gui(n)}catch(e){console.error("Error in custom GUI callback:",e)}return()=>{n.dispose(),o(null)}}},[t]),t? (0,_d.jsxs)(_d.Fragment,{children:[ (0,_d.jsx)("div",{ref:i,style:xd}),n&&t.redGPUContext&&e&& (0,_d.jsx)(dd,{gui:n,redGPUContext:e}),n&&t.viewList&&e&& (0,_d.jsx)(md,{gui:n,redGPUContext:e}),n&&t.scene&&e&& (0,_d.jsx)(vd,{gui:n,scene:e.viewList[0]?.scene}),n&&t.ibl&&e&&e.viewList[0]&& (0,_d.jsx)(gd,{gui:n,view:e.viewList[0]}),n&&t.skybox&&e&&e.viewList[0]&& (0,_d.jsx)(wd,{gui:n,view:e.viewList[0]})]}):null},xd={width:"100%",display:"flex",flexDirection:"column"};export{fd as default}; \ No newline at end of file diff --git a/examples/exampleHelper/dist/IconButton-D8-442jY.js b/examples/exampleHelper/dist/IconButton-D8-442jY.js index 8b8a5607cc..96b9e6c5ec 100644 --- a/examples/exampleHelper/dist/IconButton-D8-442jY.js +++ b/examples/exampleHelper/dist/IconButton-D8-442jY.js @@ -1,4 +1,4 @@ -import{r as t}from"./rolldown-runtime-BztV3taV.js?t=1781132971803";import{r as e,t as i}from"./vendor-react-BwJpJ84T.js?t=1781132971803";var o=t(e(),1),s=t=>{let e;const i=new Set,o=(t,o)=>{const s="function"==typeof t?t(e):t;if(!Object.is(s,e)){const t=e;e=(null!=o?o:"object"!=typeof s||null===s)?s:Object.assign({},e,s),i.forEach(i=>i(e,t))}},s=()=>e,l={setState:o,getState:s,getInitialState:()=>r,subscribe:t=>(i.add(t),()=>i.delete(t))},r=e=t(o,s,l);return l},l=t=>t,r=t=>{const e=(t=>t?s(t):s)(t),i=t=>function(t,e=l){const i=o.useSyncExternalStore(t.subscribe,o.useCallback(()=>e(t.getState()),[t,e]),o.useCallback(()=>e(t.getInitialState()),[t,e]));return o.useDebugValue(i),i}(e,t);return Object.assign(i,e),i},n=t=>t?r(t):r,c=i(),a=({label:t,isActive:e=!0,onClick:i,title:s,style:l})=>{const[r,n]=(0,o.useState)(!1); +import{r as t}from"./rolldown-runtime-BztV3taV.js?t=1781136546834";import{r as e,t as i}from"./vendor-react-BwJpJ84T.js?t=1781136546834";var o=t(e(),1),s=t=>{let e;const i=new Set,o=(t,o)=>{const s="function"==typeof t?t(e):t;if(!Object.is(s,e)){const t=e;e=(null!=o?o:"object"!=typeof s||null===s)?s:Object.assign({},e,s),i.forEach(i=>i(e,t))}},s=()=>e,l={setState:o,getState:s,getInitialState:()=>r,subscribe:t=>(i.add(t),()=>i.delete(t))},r=e=t(o,s,l);return l},l=t=>t,r=t=>{const e=(t=>t?s(t):s)(t),i=t=>function(t,e=l){const i=o.useSyncExternalStore(t.subscribe,o.useCallback(()=>e(t.getState()),[t,e]),o.useCallback(()=>e(t.getInitialState()),[t,e]));return o.useDebugValue(i),i}(e,t);return Object.assign(i,e),i},n=t=>t?r(t):r,c=i(),a=({label:t,isActive:e=!0,onClick:i,title:s,style:l})=>{const[r,n]=(0,o.useState)(!1); return(0,c.jsx)("button",{style:{...C,backgroundColor:r?"#1a1a1c":"#111112",color:"#fdb48d",...l},onClick:i,title:s||t,onMouseEnter:()=>n(!0),onMouseLeave:()=>n(!1),children: (0,c.jsx)("span",{style:{opacity:e?1:.4,transition:"opacity 0.2s"},children:t})})},C={display:"flex",alignItems:"center",justifyContent:"center",height:"100%",padding:"0 20px",backgroundColor:"#111112",border:"none",fontSize:"11px",fontWeight:"bold",cursor:"pointer",transition:"background-color 0.2s, opacity 0.2s",letterSpacing:"0.05em",flexShrink:0},d=({useSourceModal:t=!0,narrowTitle:e,narrowSettings:i,isNarrow:o=!1,onShowSource:s})=>{const l=new URL("./assets/github.png",import.meta.url).href; return(0,c.jsxs)("div",{style:p,children:[t&&o&&e&& (0,c.jsx)("div",{style:h,children:e}),t&&o&&i&& (0,c.jsx)("div",{style:x,children:i}), diff --git a/examples/exampleHelper/dist/exampleList-B00YxcCV.js b/examples/exampleHelper/dist/exampleList-B00YxcCV.js index 79c3c83a72..ceb9095ea2 100644 --- a/examples/exampleHelper/dist/exampleList-B00YxcCV.js +++ b/examples/exampleHelper/dist/exampleList-B00YxcCV.js @@ -1 +1 @@ -import{n as e}from"./rolldown-runtime-BztV3taV.js?t=1781132971803";var t=e({ExampleList:()=>i,default:()=>i}),i=[{name:"3D",list:[{name:"Hello RedGPU",path:"3d/helloWorld",description:{ko:"RedGPU의 기본 초기화 방법을 보여주는 샘플입니다.
초기화 성공 시 제공되는 RedGPUContext 객체의 기본 옵션들을 실시간으로 테스트할 수 있습니다.",en:"This example is a sample of the basic initialization of RedGPU.
\n It also provides a live test of the basic options provided to the RedGPUContext object provided upon successful initialization."}},{name:"View3D",list:[{name:"Single View3D",path:"3d/view/singleView",description:{ko:"RedGPU의 View 객체에 대한 샘플입니다. View 객체에 제공되는 기본 옵션들을 실시간으로 테스트할 수 있습니다.",en:"This example is a sample for a View object in RedGPU.
\n It provides real-time testing of the basic options provided to a View object."}},{name:"Multi View3D",path:"3d/view/multiView",description:{ko:"RedGPU의 멀티 뷰 기능을 보여주는 샘플입니다.
RedGPUContext는 여러 개의 View를 소유하고 관리할 수 있습니다.",en:"This example is a sample of RedGPU's Multi View.
RedGPUContext can own and manage multiple MultiViews."}}]},{name:"Scene",list:[{name:"Scene",path:"3d/scene",description:{ko:"RedGPU의 Scene 객체에 대한 샘플입니다.
Scene 객체에 제공되는 기본 옵션들을 실시간으로 테스트할 수 있습니다.",en:"This example is a sample of a Scene object in RedGPU.
It provides real-time testing of the basic options provided to the Scene object."}}]},{name:"Camera Controller",list:[{name:"FreeController",path:"3d/controller/freeController",description:{ko:"FreeController는 키보드(WASD/QERTFG)와 마우스/터치 입력을 사용하여 1인칭 카메라 제어를 제공합니다.
3D 공간에서의 자유로운 이동, 회전 제어, 속도/가속도 조절 및 키 바인딩 설정 기능을 포함합니다.",en:"FreeController provides first-person camera control with keyboard (WASD/QERTFG) and mouse/touch input.
Features include free movement in 3D space, rotation control, customizable speed/acceleration, and key binding configuration."}},{name:"OrbitController",path:"3d/controller/orbitController",description:{ko:"OrbitController는 중심점을 기준으로 회전하는 궤도형 카메라 제어를 제공합니다.
마우스 드래그 회전, 휠 줌, 터치 핀치 줌, 중심점 위치 사용자 정의, 거리 제어 및 팬/틸트 제한 기능을 포함합니다.",en:"OrbitController provides orbital camera control that rotates around a center point.
Features include mouse drag rotation, wheel zoom, touch pinch zoom, customizable center position, distance control, and pan/tilt limits."}},{name:"FollowController",path:"3d/controller/followController",description:{ko:"FollowController는 타겟 메쉬를 따라다니는 3인칭 카메라 제어를 제공합니다.
부드러운 카메라 추적, 거리 및 높이 조절, 팬/틸트 제어, 타겟 회전 추적 및 휠/핀치 줌 기능을 포함합니다.
3인칭 게임 및 객체 추적 시나리오에 적합합니다.",en:"FollowController provides third-person camera control that follows a target mesh.
Features include smooth camera following, customizable distance and height, pan/tilt control, target rotation tracking, and wheel/pinch zoom.
Perfect for third-person games and object tracking scenarios."}},{name:"IsometricController",path:"3d/controller/isometricController",description:{ko:"IsometricController는 아이소메트릭 뷰를 위한 고정 각도 직교 투영 카메라 제어를 제공합니다.
타겟 메쉬 추적, 키보드(WASD) 및 마우스 이동, 휠/핀치 줌 제어, 카메라 각도 및 뷰 높이 사용자 정의 기능을 포함합니다.
아이소메트릭 게임, 전략 게임 및 건축 시각화에 이상적입니다.",en:"IsometricController provides fixed-angle orthographic camera control for isometric views.
Features include target mesh tracking, keyboard (WASD) and mouse movement, wheel/pinch zoom control, and customizable camera angle and view height.
Ideal for isometric games, strategy games, and architectural visualization."}}]},{name:"Primitive",list:[{name:"Primitives",path:"3d/primitive/primitives",description:{ko:"RedGPU가 지원하는 기본적인 프리미티브 지오메트리들의 샘플입니다.",en:"Samples of basic primitive geometries supported by RedGPU."}},{name:"Box",path:"3d/primitive/box",description:{ko:"RedGPU가 지원하는 기본 Box 프리미티브에 대한 샘플입니다. Box 설정 옵션을 실시간으로 테스트할 수 있습니다.",en:"Samples for the basic Box Primitives supported by RedGPU. Provides real-time testing of Box configuration options."}},{name:"RoundedBox",path:"3d/primitive/roundedBox",description:{ko:"모서리가 둥근 박스 프리미티브에 대한 샘플입니다. 반지름(radius) 및 분할 수 설정을 통해 부드러운 모서리를 가진 박스를 생성하고 테스트할 수 있습니다.",en:"Samples for the RoundedBox Primitive. You can create and test boxes with smooth corners by configuring radius and segment settings."}},{name:"Circle",path:"3d/primitive/circle",description:{ko:"RedGPU가 지원하는 기본 Circle 프리미티브에 대한 샘플입니다. Circle 설정 옵션을 실시간으로 테스트할 수 있습니다.",en:"Samples for the basic Circle Primitives supported by RedGPU. Provides real-time testing of Circle configuration options."}},{name:"Cone",path:"3d/primitive/cone",description:{ko:"RedGPU가 지원하는 기본 Cone 프리미티브에 대한 샘플입니다. Cone 설정 옵션을 실시간으로 테스트할 수 있습니다.",en:"Samples for the basic Cone Primitives supported by RedGPU. Provides real-time testing of Cone configuration options."}},{name:"Cylinder",path:"3d/primitive/cylinder",description:{ko:"RedGPU가 지원하는 기본 Cylinder 프리미티브에 대한 샘플입니다. Cylinder 설정 옵션을 실시간으로 테스트할 수 있습니다.",en:"Samples for the basic Cylinder Primitives supported by RedGPU. Provides real-time testing of Cylinder configuration options."}},{name:"Plane",path:"3d/primitive/plane",description:{ko:"RedGPU가 지원하는 기본 Plane 프리미티브에 대한 샘플입니다. Plane 설정 옵션을 실시간으로 테스트할 수 있습니다.",en:"Samples for the basic Plane Primitives supported by RedGPU. Provides real-time testing of Plane configuration options."}},{name:"Ground",path:"3d/primitive/ground",description:{ko:"RedGPU가 지원하는 기본 Ground 프리미티브에 대한 샘플입니다. Ground 설정 옵션을 실시간으로 테스트할 수 있습니다.",en:"Samples for the basic Ground Primitives supported by RedGPU. Provides real-time testing of Ground configuration options."}},{name:"Sphere",path:"3d/primitive/sphere",description:{ko:"RedGPU가 지원하는 기본 Sphere 프리미티브에 대한 샘플입니다. Sphere 설정 옵션을 실시간으로 테스트할 수 있습니다.",en:"Samples for the basic Sphere Primitives supported by RedGPU. Provides real-time testing of Sphere configuration options."}},{name:"Capsule",path:"3d/primitive/capsule",description:{ko:"RedGPU가 지원하는 기본 Capsule 프리미티브에 대한 샘플입니다. Capsule 설정 옵션을 실시간으로 테스트할 수 있습니다.",en:"Samples for the basic Capsule Primitives supported by RedGPU. Provides real-time testing of Capsule configuration options."}},{name:"Torus",path:"3d/primitive/torus",description:{ko:"RedGPU가 지원하는 기본 Torus 프리미티브에 대한 샘플입니다. Torus 설정 옵션을 실시간으로 테스트할 수 있습니다.",en:"Samples for the basic Torus Primitives supported by RedGPU. Provides real-time testing of Torus configuration options."}},{name:"TorusKnot",path:"3d/primitive/torusKnot",description:{ko:"RedGPU가 지원하는 기본 TorusKnot 프리미티브에 대한 샘플입니다. TorusKnot 설정 옵션을 실시간으로 테스트할 수 있습니다.",en:"Samples for the basic TorusKnot Primitives supported by RedGPU. Provides real-time testing of TorusKnot configuration options."}},{name:"Ring",path:"3d/primitive/ring",description:{ko:"RedGPU가 지원하는 기본 Ring 프리미티브에 대한 샘플입니다. Ring 설정 옵션을 실시간으로 테스트할 수 있습니다.",en:"Samples for the basic Ring Primitives supported by RedGPU. Provides real-time testing of Ring configuration options."}}]},{name:"Mesh",list:[{name:"Basic Mesh",path:"3d/mesh/basicMesh",description:{ko:"이 코드는 기본 메쉬를 생성하고 위치, 크기, 회전, 재질 등 주요 속성을 실시간으로 조작하는 방법을 보여주는 샘플입니다.
RedGPU를 사용하여 Box 메쉬를 생성하고 속성과 재질을 조정하는 방법을 보여줍니다.",en:"this code is a sample that shows how to create a basic mesh and how to manipulate its main properties (position, scale, rotation, material, etc.) in real time.
This example shows how to create a Box mesh using RedGPU and how to adjust its properties and material."}},{name:"Hierarchy Mesh",path:"3d/mesh/hierarchy",description:{ko:"RedGPU를 사용하여 부모-자식 메쉬 계층 구조를 생성하고, 위치, 회전 및 스케일을 조작하는 예제입니다.",en:"An example of creating a parent-child mesh hierarchy using RedGPU, and manipulating its position, rotation, and scale."}},{name:"Pivot Mesh",path:"3d/mesh/pivot",description:{ko:"RedGPU를 사용하여 부모 및 자식 메쉬를 생성하고 피벗 설정을 통해 회전 중심을 변경하는 방법을 보여주는 실습 예제입니다.",en:"A hands-on example that demonstrates how to create parent and child meshes using RedGPU and change the center of rotation via pivot settings."}},{name:"Child Methods",path:"3d/mesh/childMethod",description:{ko:"RedGPU를 사용한 자식 노드 관리 예제로, 자식 추가, 삭제, 인덱스 변경, 교체 및 자식 색상 무작위화 등을 통해 노드를 동적으로 제어하는 방법을 보여줍니다.",en:"An example of child node management using RedGPU, showing how to dynamically control nodes by adding, deleting, changing index, replacing, and randomizing color of children."}},{name:"lookAt Methods",path:"3d/mesh/lookAt",description:{ko:"객체가 특정 지점이나 다른 객체를 바라보도록 하는 lookAt 메서드의 사용법을 보여주는 예제입니다.",en:"An example demonstrating the usage of the lookAt method to make an object face a specific point or another object."}},{name:"BoundingBox",list:[{name:"BoundingBox",path:"3d/mesh/boundBox/meshBoundBox",description:{ko:"메쉬의 바운딩 박스(AABB)를 시각화하고 확인하는 예제입니다.",en:"An example of visualizing and checking the bounding box (AABB) of a mesh."}},{name:"AABB - intersects",path:"3d/mesh/boundBox/meshAABBIntersects",description:{ko:"AABB(Axis-Aligned Bounding Box) 간의 교차 검사 기능을 테스트하는 예제입니다.",en:"An example testing the intersection check function between AABBs (Axis-Aligned Bounding Boxes)."}},{name:"OBB - intersects",path:"3d/mesh/boundBox/meshOBBIntersects",description:{ko:"OBB(Oriented Bounding Box) 간의 교차 검사 기능을 테스트하는 예제입니다.",en:"An example testing the intersection check function between OBBs (Oriented Bounding Boxes)."}}]}]},{name:"Coordinate Transformation",list:[{name:"worldToLocal / localToWorld",path:"3d/coordinateTransformation/worldToLocal",description:{ko:"월드 좌표와 로컬 좌표 간의 변환을 테스트하는 예제입니다.",en:"An example testing the transformation between world coordinates and local coordinates."}},{name:"screenToWorld",path:"3d/coordinateTransformation/screenToWorld",description:{ko:"화면(스크린) 좌표를 월드 좌표로 변환하는 방법을 보여주는 예제입니다.",en:"An example showing how to convert screen coordinates to world coordinates."}}]},{name:"Material",list:[{name:"ColorMaterial",path:"3d/material/colorMaterial",description:{ko:"RedGPU ColorMaterial의 기본 색상 조작 및 색상 설정을 위한 편의 메서드들에 대한 실시간 샘플을 제공합니다.",en:"Provides real-time samples of the basic color manipulations of RedGPU's ColorMaterial and convenience methods for setting colors."}},{name:"BitmapMaterial",path:"3d/material/bitmapMaterial",description:{ko:"RedGPU의 BitmapMaterial 샘플로, 다양한 텍스처 포맷(PNG, JPG, WEBP, SVG)을 적용하여 텍스처 변경을 실시간으로 테스트할 수 있습니다.",en:"RedGPU's BitmapMaterial sample allows you to test texture changes in real time by applying various texture formats (PNG, JPG, WEBP, SVG)."}},{name:"PhongMaterial",path:"3d/material/phongMaterial",description:{ko:"RedGPU를 사용하여 PhongMaterial의 기본 속성을 조작하고 다양한 텍스처 조합을 실험하는 방법을 보여주는 샘플 예제입니다.",en:"A sample example that demonstrates how to manipulate the basic properties of PhongMaterial using RedGPU and experiment with different texture combinations."}},{name:"PhongMaterial Texture Combination",path:"3d/material/phongMaterialTextures",description:{ko:"RedGPU를 사용하여 PhongMaterial의 다양한 텍스처 조합과 효과를 시각적으로 보여주는 샘플 예제입니다.",en:"A sample example that visually demonstrates different texture combinations and effects of PhongMaterial using RedGPU."}},{name:"UV Transform",path:"3d/material/uvTransform",description:{ko:"재질의 텍스처 오프셋과 스케일을 조절하여 흐르는 효과나 타일링을 구현하는 방법을 테스트합니다.",en:"Tests how to implement scrolling effects or tiling by adjusting the texture offset and scale of the material."}},{name:"Material Opacity",path:"3d/material/opacity",description:{ko:"재질의 불투명도(Opacity)를 조절하여 반투명 효과를 테스트하는 예제입니다.",en:"An example testing the translucency effect by adjusting the opacity of the material."}},{name:"Fragment Variant Test",path:"3d/material/fragmentVariantTest",description:{ko:"쉐이더의 프래그먼트 변형을 테스트하는 예제입니다.",en:"An example testing fragment variants of shaders."}}]},{name:"Texture & Sampler",list:[{name:"BitmapTexture & Sampler",path:"3d/texture/bitmapTextureSampler",description:{ko:"텍스처 샘플러 옵션과 밉맵 지원을 시연하는 샘플입니다.",en:"A sample that demonstrates texture sampler options and mipmap support."}},{name:"Sampler Combination",path:"3d/texture/samplerCombination",description:{ko:"텍스처 샘플러의 다양한 조합을 한눈에 보여주는 예제입니다.",en:"Here's an example showing the different combinations of texture samplers at a glance."}},{name:"Sampler SamplerAddressMode",path:"3d/texture/samplerAddressMode",description:{ko:"텍스처 샘플러의 AddressMode 옵션 조합을 보여주는 예제입니다.",en:"An example showing combinations of AddressMode options for a texture sampler."}},{name:"MaxAnisotropy",path:"3d/texture/maxAnisotropy",description:{ko:"텍스처의 비등방성 필터링(Anisotropy) 옵션을 보여주는 예제입니다.",en:"example showing the Anisotropy option for a texture."}}]},{name:"SkyBox & IBL",list:[{name:"SkyBox",list:[{name:"Skybox using 6 assets",path:"3d/skybox/skybox",description:{ko:"6개의 이미지를 사용하여 스카이박스를 구성하는 예제입니다.",en:"An example of constructing a skybox using 6 images."}},{name:"Skybox transition",list:[{name:"Basic transition",path:"3d/skybox/transition/skyboxTransition",description:{ko:"스카이박스 간의 부드러운 전환 효과를 보여주는 예제입니다.",en:"An example showing smooth transition effects between skyboxes."}},{name:"transitionAlphaTexture - with NoiseTexture",path:"3d/skybox/transition/skyboxTransitionWithNoiseTexture",description:{ko:"노이즈 텍스처와 알파 텍스처를 사용하여 스카이박스 전환 효과를 연출하는 예제입니다.",en:"An example creating skybox transition effects using noise textures and alpha textures."}}]}]},{name:"IBL",list:[{name:"Skybox using IBL",path:"3d/skybox/ibl/skyboxWithIbl",description:{ko:"IBL(Image Based Lighting)을 사용하여 스카이박스를 생성하는 방법을 보여줍니다.",en:"Demonstrates how to create a skybox using IBL (Image Based Lighting)."}},{name:"IBL Test",path:"3d/skybox/ibl/iblTest",description:{ko:"이미지 기반 조명(IBL)을 테스트하는 예제입니다.",en:"An example testing Image-Based Lighting (IBL)."}},{name:"Custom IBL Texture Size",path:"3d/skybox/ibl/iblTextureSize",description:{ko:"IBL 텍스처의 크기를 사용자 정의하는 예제입니다.",en:"An example of customizing the size of the IBL texture."}},{name:"BRDF LUT Test (Dev Only)",path:"3d/skybox/ibl/brdfLutTest",description:{ko:"새로운 IBL 시스템의 기초인 BRDF LUT 생성을 테스트합니다. (개발 확인용)",en:"Tests BRDF LUT generation, the foundation of the new IBL system. (For development verification)"}},{name:"Irradiance Test (Dev Only)",path:"3d/skybox/ibl/irradianceTest",description:{ko:"분리된 IrradianceGenerator를 사용하여 환경맵으로부터 Irradiance 맵을 생성하고 테스트합니다. (개발 확인용)",en:"Generates and tests an Irradiance map from an environment map using the separated IrradianceGenerator. (For development verification)"}}]},{name:"FrustumCulling",list:[{name:"FrustumCulling",path:"3d/frustumCulling/frustumCulling",description:{ko:"카메라 시야 밖의 객체를 렌더링에서 제외하는 절두체 컬링(Frustum Culling) 기능을 시연합니다.",en:"Demonstrates Frustum Culling, which excludes objects outside the camera view from rendering."}},{name:"DistanceCulling",path:"3d/frustumCulling/distanceCulling",description:{ko:"카메라와의 거리에 따라 객체를 렌더링에서 제외하는 거리 컬링 기능을 시연합니다.",en:"Demonstrates Distance Culling, which excludes objects from rendering based on their distance from the camera."}}]},{name:"SkyAtmosphere",list:[{name:"SkyAtmosphere Basic",path:"3d/skyAtmosphere/skyAtmosphere",description:{ko:"물리 기반 대기 산란 시스템인 SkyAtmosphere의 기본적인 설정과 실시간 태양 광원 연동을 시연합니다.",en:"Demonstrates basic configuration and real-time sun light synchronization of the SkyAtmosphere, a physics-based atmospheric scattering system."}},{name:"Material Scattering (Aerial Perspective)",path:"3d/skyAtmosphere/scatteringTest",description:{ko:"거리에 따른 대기 산란(공중 투시) 효과가 다양한 재질(Color, Phong, PBR 등)에 어떻게 적용되는지 활주로 레이아웃을 통해 직관적으로 비교합니다.",en:"Provides an intuitive comparison of how atmospheric scattering (Aerial Perspective) affects various materials (Color, Phong, PBR, etc.) along a distance runway."}},{name:"Atmosphere & IBL Harmony",path:"3d/skyAtmosphere/gltf",description:{ko:"대기 산란, IBL 환경광, 스카이박스 배경이 유기적으로 조화되어 glTF PBR 모델에 물리적 사실감을 부여하는 통합 환경 시뮬레이션입니다.",en:"An integrated simulation showing how atmospheric scattering, IBL, and skybox work in harmony to provide physical realism to a glTF PBR model."}},{name:"SkyAtmosphere LUT Generator",path:"3d/skyAtmosphere/generator",description:{ko:"대기 산란 계산을 위해 내부적으로 생성되는 투과율, 하늘 뷰 등 다양한 LUT(Look-Up Table) 데이터를 시각화하여 분석합니다.",en:"Visualizes and analyzes various internal LUT (Look-Up Table) data such as Transmittance and SkyView generated for atmospheric scattering calculations."}}]}]},{name:"DrawDebugger",list:[{name:"DrawDebugger",path:"3d/drawDebugger/basic",description:{ko:"렌더링 정보를 디버깅하기 위한 도구를 시연하는 예제입니다.",en:"An example demonstrating tools for debugging rendering information."}}]},{name:"Transparent Sort",list:[{name:"Transparent Sort",path:"3d/transparentSort",description:{ko:"메쉬의 재질에 `transparent` 옵션을 적용하여 반투명 객체가 렌더링되는 순서를 확인하는 예제입니다. `transparent`를 사용하여 올바른 렌더링 결과를 확인할 수 있습니다.",en:" example of how to apply the `transparent` option to the mesh's material to see the order in which translucent objects are rendered. You can use `transparent` to see the correct rendering results."}}]},{name:"Noise Texture",experimental:!0,list:[{name:"SimplexTexture",experimental:!0,list:[{experimental:!0,name:"SimplexTexture",path:"3d/noiseTexture/simplex/basic",description:{ko:"심플렉스 노이즈 텍스처를 생성하고 적용하는 기본 예제입니다.",en:"Basic example of generating and applying Simplex Noise Texture."}},{experimental:!0,name:"Custom SimplexTexture - Fire",path:"3d/noiseTexture/simplex/fire",description:{ko:"심플렉스 노이즈를 활용하여 불꽃 효과를 연출하는 커스텀 텍스처 예제입니다.",en:"Custom texture example creating a fire effect using Simplex Noise."}},{experimental:!0,name:"Custom SimplexTexture - Displacement",path:"3d/noiseTexture/simplex/displacement",description:{ko:"심플렉스 노이즈를 활용하여 변위(Displacement) 효과를 주는 예제입니다.",en:"Example applying displacement effects using Simplex Noise."}}]},{name:"VoronoiTexture",experimental:!0,list:[{experimental:!0,name:"VoronoiTexture",path:"3d/noiseTexture/voronoi/basic",description:{ko:"보로노이 노이즈 텍스처를 생성하고 적용하는 예제입니다.",en:"Example of generating and applying Voronoi Noise Texture."}}]}]},{name:"Sprite3D & SpriteSheet3D",list:[{name:"Sprite3D",path:"3d/sprite/sprite3D",description:{ko:"Sprite3D 객체의 사용법을 보여주는 예제입니다.",en:"example of a Sprite3D object."}},{name:"Sprite3D Comparison (World vs Pixel)",path:"3d/sprite/sprite3DCompare",description:{ko:"Sprite3D의 월드 단위 크기(worldSize)와 고정 픽셀 크기(pixelSize) 설정을 비교 시연하는 예제입니다.",en:"A comparison example demonstrating Sprite3D's world unit size (worldSize) and fixed pixel size (pixelSize) settings."}},{name:"SpriteSheet3D",path:"3d/sprite/spriteSheet3D",description:{ko:"SpriteSheet3D 객체의 사용법을 보여주는 예제입니다.",en:"example of a SpriteSheet3D object."}},{name:"SpriteSheet3D Comparison (World vs Pixel)",path:"3d/sprite/spriteSheet3DCompare",description:{ko:"SpriteSheet3D의 월드 단위 크기(worldSize)와 고정 픽셀 크기(pixelSize) 설정을 비교 시연하는 예제입니다.",en:"A comparison example demonstrating SpriteSheet3D's world unit size (worldSize) and fixed pixel size (pixelSize) settings."}}]},{name:"TextField3D",list:[{name:"TextField3D",path:"3d/textField/textField3D",description:{ko:"TextField3D 객체의 사용법을 보여주는 예제입니다.",en:"example of a TextField3D object."}},{name:"TextField3D Comparison (World vs Pixel)",path:"3d/textField/textField3DCompare",description:{ko:"TextField3D의 월드 단위 크기(worldSize)와 고정 픽셀 크기(usePixelSize) 설정을 비교 시연하는 예제입니다.",en:"A comparison example demonstrating TextField3D's world unit size (worldSize) and fixed pixel size (usePixelSize) settings."}}]},{name:"Light",list:[{name:"DirectionalLight",path:"3d/light/directionalLight",description:{ko:"태양광과 같은 직사광(Directional Light)을 시연하는 예제입니다.",en:"An example demonstrating Directional Light, simulating sunlight."}},{name:"PointLight",path:"3d/light/pointLight",description:{ko:"한 지점에서 모든 방향으로 빛을 방출하는 점광원(Point Light)을 시연하는 예제입니다.",en:"An example demonstrating Point Light, emitting light in all directions from a point."}},{name:"PointLight with glTF",path:"3d/light/pointLightWithGltf",description:{ko:"현대적인 감쇄(Attenuation) 수식이 적용된 Point Light와 glTF PBR 모델의 상호작용 예제입니다.",en:"An example of interaction between Point Light with modern attenuation formula and glTF PBR model."}},{name:"SpotLight",path:"3d/light/spotLight",description:{ko:"특정 방향으로 원뿔형 빛을 방출하는 스포트라이트(Spot Light)를 시연하는 예제입니다.",en:"An example demonstrating Spot Light, cone-shaped light in a specific direction."}},{name:"SpotLight with glTF",path:"3d/light/spotLightWithGltf",description:{ko:"현대적인 원뿔 감쇄(Angle Attenuation) 수식이 적용된 Spot Light와 glTF PBR 모델의 상호작용 예제입니다.",en:"An example of interaction between Spot Light with modern angle attenuation formula and glTF PBR model."}},{name:"PointLight Performance(cluster)",path:"3d/light/pointLightPerformance",description:{ko:"PointLight는 클러스터 타일 렌더링을 지원합니다. 1024개의 포인트 라이트를 지원합니다.",en:"PointLight supports clustered tile rendering. Supports 1024 point lights."}},{name:"SpotLight Performance(cluster)",path:"3d/light/spotLightPerformance",description:{ko:"SpotLight의 대량 렌더링 성능(클러스터링)을 테스트하는 예제입니다.",en:"An example testing the mass rendering performance (clustering) of SpotLights."}}]},{name:"Group3D",list:[{name:"Basic Group3D",path:"3d/group3D/basic",description:{ko:"3D 객체들을 그룹화할 수 있는 Group3D 객체의 예제입니다.",en:"Here's an example of a Group3D object that can group 3D objects."}}]},{name:"Tint",experimental:!0,list:[{experimental:!0,name:"Tint",path:"3d/tint/basic",description:{ko:"재질 기반 틴트를 지원합니다. 틴트 사용, tintBlendMode 설정 및 색상 사용 예제입니다.",en:"Supports material-based tint. Examples of using tint, setting tintBlendMode, and color."}}]},{name:"Line3D",experimental:!0,list:[{experimental:!0,name:"Linear Type",path:"3d/line3D/linear",description:{ko:"직선 형태의 라인을 그리는 예제입니다.",en:"An example of drawing linear lines."}},{experimental:!0,name:"Bezier Type",path:"3d/line3D/bezier",description:{ko:"베지에 곡선 형태의 라인을 그리는 예제입니다.",en:"An example of drawing Bezier curve lines."}},{experimental:!0,name:"CatmullRom Type",path:"3d/line3D/catmullRom",description:{ko:"캣멀-롬 스플라인 형태의 라인을 그리는 예제입니다.",en:"An example of drawing Catmull-Rom spline lines."}}]},{name:"Interaction",list:[{name:"MouseEvent",list:[{name:"Mesh",path:"3d/interaction/mouseEvent/mesh",description:{ko:"Mesh에 마우스 이벤트를 설정하는 예제입니다.",en:"Here's an example of setting up mouse events on a Mesh."}},{name:"Sprite3D",path:"3d/interaction/mouseEvent/sprite3D",description:{ko:"Sprite3D에 마우스 이벤트를 설정하는 예제입니다.",en:"Here's an example of setting up mouse events on a Sprite3D."}},{name:"SpriteSheet3D",path:"3d/interaction/mouseEvent/spriteSheet3D",description:{ko:"SpriteSheet3D에 마우스 이벤트를 설정하는 예제입니다.",en:"Here's an example of setting up mouse events on a SpriteSheet3D."}},{name:"TextField3D",path:"3d/interaction/mouseEvent/textField3D",description:{ko:"TextField3D에 마우스 이벤트를 설정하는 예제입니다.",en:"Here's an example of setting up mouse events on a TextField3D."}},{name:"Raycasting (Precision Picking)",path:"3d/interaction/mouseEvent/raycasting",description:{ko:"이 예제는 복잡한 지오메트리(TorusKnot)에 대한 고정밀 레이캐스팅을 보여줍니다.
버텍스 버퍼를 분석하여 정확한 교차 지점, 면 인덱스 및 로컬 좌표를 CPU에서 계산합니다.",en:"This example demonstrates high-precision raycasting on complex geometry (TorusKnot).
It calculates the exact intersection point, face index, and local coordinates on the CPU by analyzing vertex buffers."}}]},{name:"KeyboardEvent",list:[{name:"Keyboard Interaction",path:"3d/interaction/keyboardEvent",description:{ko:"keyboardKeyBuffer를 사용하여 매 프레임 키보드 상태를 체크하고 객체를 제어하는 기초적인 방법을 보여줍니다.",en:"Shows basic way to check keyboard state every frame and control an object using keyboardKeyBuffer."}}]}]},{name:"Shadow",list:[{name:"DirectionalLight Shadow",path:"3d/shadow/directionalShadow",description:{ko:"DirectionalLight에 의한 그림자 효과를 시연하는 예제입니다.",en:"An example demonstrating shadow effects caused by DirectionalLight."}},{name:"DirectionalLight Shadow - GLTF",path:"3d/shadow/gltfDirectionalShadow",description:{ko:"GLTF 모델에 대한 DirectionalLight 그림자 효과를 시연하는 예제입니다.",en:"An example demonstrating DirectionalLight shadow effects on a GLTF model."}}]},{name:"InstancedMesh",list:[{name:"InstancedMesh Simple",path:"3d/instancedMesh/simple",description:{ko:"이 데모는 간단한 Plane을 사용한 인스턴스 성능 테스트를 보여줍니다. ",en:"This demo demonstrates instance performance testing using a simple Plane. "}},{name:"InstancedMesh Sphere",path:"3d/instancedMesh/sphere",description:{ko:"이 데모는 Sphere를 사용한 인스턴스 성능 테스트를 보여줍니다. ",en:"This demo demonstrates instance performance testing using Sphere. "}}]},{name:"LOD",list:[{name:"InstancedMesh GPU LOD",path:"3d/lod/InstanceMeshGPULOD",description:{ko:"InstancedMesh에 GPU 기반 LOD를 적용하여 수만 개의 객체를 효율적으로 최적화하는 성능을 시연합니다.",en:"Demonstrates efficient optimization of tens of thousands of objects by applying GPU-based LOD to InstancedMesh."}},{name:"InstancedMesh Multi-Material GPU LOD",path:"3d/lod/InstanceMeshGPULOD_material",description:{ko:"인스턴싱 메시에서 거리에 따라 지오메트리와 머티리얼을 동시에 변경하는 GPU 기반 LOD 기능을 보여줍니다.",en:"Shows GPU-based LOD functionality that simultaneously changes geometry and materials by distance in instanced meshes."}},{name:"Mesh CPU LOD",path:"3d/lod/MeshCPULOD",description:{ko:"수천 개의 개별 Mesh 객체들에 CPU 기반 LOD를 적용하여 거리별 최적화 성능을 테스트합니다.",en:"Tests distance-based optimization performance by applying CPU-based LOD to thousands of individual Mesh objects."}},{name:"Mesh Multi-Material CPU LOD",path:"3d/lod/MeshCPULOD_material",description:{ko:"개별 메시 객체들에 대해 거리에 따라 지오메트리와 머티리얼이 함께 변화하는 CPU 기반 LOD를 시연합니다.",en:"Demonstrates CPU-based LOD where both geometry and materials change together by distance for individual mesh objects."}}]},{name:"ParticleSystem",list:[{name:"Particle",path:"3d/particle/basic",description:{ko:"기본적인 파티클 시스템을 시연하는 예제입니다.",en:"An example demonstrating a basic particle system."}},{name:"Multi Particle Performance",path:"3d/particle/performance",description:{ko:"다수의 파티클 시스템을 동시에 렌더링하여 성능을 테스트하는 예제입니다.",en:"An example testing performance by rendering multiple particle systems simultaneously."}}]},{name:"Indirect Draw Test",list:[{name:"drawIndexedIndirect Test",path:"3d/indirectDrawTest",description:{ko:"drawIndexedIndirect 기능을 테스트하는 예제입니다.",en:"An example testing the drawIndexedIndirect function."}}]}]},{name:"GLTF",list:[{name:"Basic",list:[{name:"TextureEncodingTest",path:"gltf/basic/textureEncodingTest",description:{ko:"텍스처가 올바른 전달 함수(Transfer Function)로 샘플링되는지 테스트합니다. Base Color와 Emissive가 sRGB에서 올바르게 디코딩되는지 확인합니다.",en:"Tests that textures are sampled with the correct transfer functions. Verifies base color and emissive textures are decoded from sRGB."}},{name:"TextureLinear InterpolationTest",path:"gltf/basic/textureLinearInterpolationTest",description:{ko:"sRGB 디코딩 후 선형 값에 대해 텍스처 선형 보간이 올바르게 수행되는지 테스트합니다.",en:"Tests that linear texture interpolation is correctly performed on linear values (after sRGB decoding)."}},{name:"VertexColorTest",path:"gltf/basic/vertexColorTest",description:{ko:"뷰어가 정점 색상(COLORS_0 속성)을 올바르게 지원하는지 테스트합니다.",en:"Tests proper support for vertex colors (COLORS_0 attribute) in the viewer."}},{name:"BoxVertexColors",path:"gltf/basic/boxVertexColors",description:{ko:"각 면에 정점 색상이 적용된 간단한 박스 모델입니다.",en:"A simple box model with vertex colors applied to each face."}},{name:"OrientationTest",path:"gltf/basic/orientationTest",description:{ko:"노드의 회전 및 방향(Quaternion) 처리가 올바른지 테스트합니다.",en:"Tests the correctness of node rotation and orientation (Quaternion) handling."}},{name:"TextureCoordinateTest",path:"gltf/basic/textureCoordinateTest",description:{ko:"XYZ 위치(3D 공간 좌표)와 UV 위치(2D 텍스처 좌표) 간의 관계를 보여줍니다.",en:"Demonstrates the relationship between XYZ positions and UV texture coordinates."}},{name:"AlphaBlendModeTest",path:"gltf/basic/alphaBlendModeTest",description:{ko:"다양한 알파 모드(OPAQUE, BLEND, MASK)가 올바르게 렌더링되는지 테스트합니다.",en:"Tests the various alpha modes (OPAQUE, BLEND, MASK) to verify correct rendering."}},{name:"TextureSettingsTest",path:"gltf/basic/textureSettingsTest",description:{ko:"텍스처 샘플링 설정(Wrap 모드, 필터링)을 테스트합니다.",en:"Tests texture sampling settings (Wrap modes, Filtering)."}},{name:"MultiUVTest",path:"gltf/basic/multiUVTest",description:{ko:"다중 텍스처 좌표 속성(예: 색상용 TEXCOORD_0, 기타 요소용 TEXCOORD_1)의 사용을 시연합니다.",en:"Demonstrates the usage of multiple texture coordinate attributes (e.g., TEXCOORD_0 for color, TEXCOORD_1 for other elements)."}},{name:"MetalRoughSpheres",path:"gltf/basic/metalRoughSpheres",description:{ko:"다양한 금속성(Metallic)과 거칠기(Roughness) 값을 가진 구체들을 통해 PBR 렌더링을 테스트합니다.",en:"Tests PBR rendering via spheres with varying Metallic and Roughness values."}},{name:"MetalRoughSpheresNoTextures",path:"gltf/basic/metalRoughSpheresNoTextures",description:{ko:"텍스처 없이 재질의 요소(Factor) 값만으로 금속성과 거칠기를 표현하는 테스트입니다.",en:"Tests representing metallic and roughness using only material factor values without textures."}},{name:"WaterBottle",path:"gltf/basic/waterBottle",description:{ko:"Normal, Occlusion, Emissive 맵을 사용하는 기본적인 금속/거칠기(Metal/Roughness) PBR 물병 모델입니다.",en:"A basic Metal/Roughness PBR water bottle model using Normal, Occlusion, and Emissive maps."}},{name:"NormalTangentTest",path:"gltf/basic/normalTangentTest",description:{ko:"노멀 맵핑과 탄젠트 공간 계산의 정확성을 테스트합니다.",en:"Tests the accuracy of normal mapping and tangent space calculations."}},{name:"NormalTangentMirrorTest",path:"gltf/basic/normalTangentMirrorTest",description:{ko:"미러링된 텍스처 좌표에서의 노멀 맵핑 처리를 테스트합니다.",en:"Tests normal mapping handling with mirrored texture coordinates."}},{name:"NegativeScaleTest",path:"gltf/basic/negativeScaleTest",description:{ko:"음수 스케일(반전)이 적용된 노드의 렌더링을 테스트합니다.",en:"Tests rendering of nodes with negative scale (inversion) applied."}},{name:"EnvironmentTest",path:"gltf/basic/environmentTest",description:{ko:"금속 표면에서의 환경 맵 반사 효과를 테스트합니다.",en:"Tests environment map reflection effects on metallic surfaces."}},{name:"Generate normal vector test",path:"gltf/basic/generateNormalTest",description:{ko:"모델에 노멀 정보가 없을 때 자동으로 노멀 벡터를 생성하는 기능을 테스트합니다.",en:"Tests the automatic generation of normal vectors when the model lacks normal information."}}]},{name:"Basic Compare",list:[{name:"CompareBaseColor",path:"gltf/basic/compareBaseColor",description:{ko:"기본 색상(Base Color) 렌더링 결과를 비교합니다.",en:"Compares Base Color rendering results."}},{name:"CompareAlphaCoverage",path:"gltf/basic/compareAlphaCoverage",description:{ko:"알파 커버리지(Alpha Coverage) 렌더링 결과를 비교합니다.",en:"Compares Alpha Coverage rendering results."}},{name:"CompareMetallic",path:"gltf/basic/compareMetallic",description:{ko:"금속성(Metallic) 렌더링 결과를 비교합니다.",en:"Compares Metallic rendering results."}},{name:"CompareNormal",path:"gltf/basic/compareNormal",description:{ko:"노멀 맵(Normal Map) 렌더링 결과를 비교합니다.",en:"Compares Normal Map rendering results."}},{name:"CompareRoughness",path:"gltf/basic/compareRoughness",description:{ko:"거칠기(Roughness) 렌더링 결과를 비교합니다.",en:"Compares Roughness rendering results."}},{name:"CompareAmbientOcclusion",path:"gltf/basic/compareAmbientOcclusion",description:{ko:"앰비언트 오클루전(AO) 렌더링 결과를 비교합니다.",en:"Compares Ambient Occlusion (AO) rendering results."}}]},{name:"Animation",list:[{name:"Basic Animations",path:"gltf/animation/basicAnimations",description:{ko:"노드의 이동, 회전, 크기 조절 애니메이션을 보여주는 기본 예제입니다.",en:"Basic example showing node translation, rotation, and scaling animations."}},{name:"SimpleSkin",path:"gltf/animation/simpleSkin",description:{ko:"가장 기본적인 형태의 스키닝(Skinning) 애니메이션 예제입니다.",en:"The most basic example of skinning animation."}},{name:"SimpleMorph",path:"gltf/animation/simpleMorph",description:{ko:"간단한 모프 타겟(Morph Target) 애니메이션 예제입니다.",en:"Simple Morph Target animation example."}},{name:"RiggedSimple",path:"gltf/animation/riggedSimple",description:{ko:"간단하게 리깅된 원통형 메쉬를 통해 스키닝 동작을 확인합니다.",en:"Verifies skinning behavior via a simply rigged cylindrical mesh."}},{name:"RiggedFigure",path:"gltf/animation/riggedFigure",description:{ko:"리깅된 인간형 캐릭터 모델의 애니메이션을 테스트합니다.",en:"Tests animation of a rigged humanoid character model."}},{name:"InterpolationTest",path:"gltf/animation/interpolationTest",description:{ko:"애니메이션 보간 모드(Step, Linear, Cubic Spline)의 차이를 보여줍니다.",en:"Demonstrates the differences between animation interpolation modes (Step, Linear, Cubic Spline)."}},{name:"CesiumMan & MilkTruck",path:"gltf/animation/cesiumMan",description:{ko:"스키닝된 CesiumMan과 애니메이션이 적용된 우유 트럭 모델입니다.",en:"Skinned CesiumMan and animated Milk Truck models."}},{name:"BrainStem",path:"gltf/animation/brainStem",description:{ko:"복잡한 계층 구조와 스키닝을 가진 BrainStem 모델 애니메이션입니다.",en:"BrainStem model animation with complex hierarchy and skinning."}},{name:"MorphStressTest",path:"gltf/animation/morphStressTest",description:{ko:"다수의 활성 정점 속성(최대 18개)을 사용하여 모프 타겟 구현을 스트레스 테스트합니다.",en:"Stress-tests morph target implementations with a high number of active vertex attributes (up to 18)."}},{name:"RecursiveSkeletons",path:"gltf/animation/recursiveSkeletons",description:{ko:"복잡한 스키닝 케이스(다른 스킨으로 메쉬 재사용, 단일 스켈레톤에 다중 스킨 바인딩)를 테스트합니다.",en:"Tests complex skinning cases: reusing meshes with different skins and binding multiple skins to a single skeleton."}},{name:"Animation Performance Test",list:[{name:"Medium load Skinning",path:"gltf/animation/performance/mediumLoadSkinning",description:{ko:"19개의 관절과 57개의 애니메이션 채널을 가진 다수의 모델을 계산하는 성능 데모입니다.",en:"This is a performance demo that computes a large number of models with 19 joints and 57 animation channels."}},{name:"High vertex load Skinning",path:"gltf/animation/performance/highVertexLoadSkinning",description:{ko:"많은 정점과 관절을 가진 모델에 대한 스키닝 성능을 측정하는 테스트를 수행합니다. 각 장치의 성능 한계를 확인하기 위해 FPS와 GPU/CPU 사용량을 모니터링합니다.",en:"perform tests to measure skinning performance for models with many vertices and joints. We monitor FPS and GPU/CPU utilization to determine performance limits for each device."}},{name:"Morph target load Test",path:"gltf/animation/performance/highMorphTarget",description:{ko:"수백 개의 MorphStressTest 모델을 인스턴스화하여 모프 스트레스 테스트를 수행합니다.
\n실시간 모프 타겟 스키닝 성능을 극한까지 벤치마킹합니다. 세 가지 애니메이션 중 가장 무거운 모프 타겟 애니메이션의 성능을 테스트합니다.
\n각 장치의 성능 한계를 확인하세요.",en:"Perform morph stress tests by instantiating hundreds of MorphStressTest models.
\nBenchmark real-time morph target skinning performance to the limit. Test the performance of the heaviest of the three animations, the morph target animation.
\nCheck performance limits on each device."}}]}]},{name:"3D Models",list:[{name:"corset",path:"gltf/models/corset",description:{ko:"복잡한 형상과 텍스처를 가진 고해상도 코르셋 모델입니다.",en:"High-resolution Corset model with complex geometry and textures."}},{name:"Helmets",path:"gltf/models/helmets",description:{ko:"손상된 헬멧(Damaged Helmet) 등 고품질 PBR 텍스처를 보여주는 모델들입니다.",en:"Models showcasing high-quality PBR textures, such as the Damaged Helmet."}},{name:"Sponza",path:"gltf/models/sponza",description:{ko:"조명 테스트에 널리 사용되는 건물 내부 모델입니다. 현대적인 PBR 파이프라인을 위해 고해상도 지오메트리로 리메이크되었습니다.",en:"Building interior commonly used for testing lighting. Remade for modern PBR pipelines with high-resolution geometry."}},{name:"Tokyo",path:"gltf/models/tokyo",description:{ko:"수많은 드로우 콜과 대규모 씬 렌더링을 테스트하는 도쿄 도시 모델입니다.",en:"Tokyo city model testing large-scale scene rendering and numerous draw calls."}},{name:"texcooredNTest",path:"gltf/models/texcooredNTest",description:{ko:"다중 텍스처 좌표 채널의 동작을 확인하는 테스트 모델입니다.",en:"Test model verifying the behavior of multiple texture coordinate channels."}},{name:"ABeautifulGame",path:"gltf/models/aBeautifulGame",extensionList:["KHR_materials_transmission","KHR_materials_volume"],description:{ko:"투과(Transmission)와 볼륨(Volume) 효과를 시연하는 체스 세트입니다.",en:"A chess set demonstrating transmission and volume."}}]},{name:"GLTF Extensions",list:[{name:"KHR_materials_anisotropy",list:[{name:"CompareAnisotropy",path:"gltf/gltfExtensions/anisotropy/compareAnisotropy",extensionList:["KHR_materials_anisotropy"],description:{ko:"비등방성(Anisotropy)이 있는 렌더링과 없는 렌더링을 비교합니다.",en:"Compares rendering with and without anisotropy."}},{name:"AnisotropyDiscTest",path:"gltf/gltfExtensions/anisotropy/anisotropyDiscTest",extensionList:["KHR_materials_anisotropy"],description:{ko:"원판 형태의 비등방성 하이라이트 회전을 테스트합니다.",en:"Tests anisotropic highlight rotation on a disc shape."}},{name:"AnisotropyRotationTest",path:"gltf/gltfExtensions/anisotropy/anisotropyRotationTest",extensionList:["KHR_materials_anisotropy"],description:{ko:"비등방성 방향 회전에 따른 렌더링 변화를 테스트합니다.",en:"Tests rendering changes based on anisotropy direction rotation."}},{name:"AnisotropyStrengthTest",path:"gltf/gltfExtensions/anisotropy/anisotropyStrengthTest",extensionList:["KHR_materials_anisotropy"],description:{ko:"비등방성 강도(Strength)에 따른 하이라이트 변화를 테스트합니다.",en:"Tests highlight changes based on anisotropy strength."}},{name:"AnisotropyBarnLamp",path:"gltf/gltfExtensions/anisotropy/anisotropyBarnLamp",extensionList:["KHR_materials_anisotropy"],description:{ko:"비등방성(Anisotropic) 재질 속성을 보여주는 헛간 램프 모델입니다.",en:"A barn lamp model showcasing anisotropic material properties."}}]},{name:"KHR_materials_iridescence",list:[{name:"CompareIridescence",path:"gltf/gltfExtensions/iridescence/compareIridescence",extensionList:["KHR_materials_iridescence"],description:{ko:"무지개빛(Iridescence) 박막 간섭 효과를 비교합니다.",en:"Compares Iridescence thin-film interference effects."}},{name:"IridescenceDielectricSpheres",path:"gltf/gltfExtensions/iridescence/iridescenceDielectricSpheres",extensionList:["KHR_materials_iridescence","KHR_materials_transmission","KHR_materials_volume"],description:{ko:"비금속(유전체) 재질에서 KHR_materials_iridescence 확장을 테스트합니다.",en:"Tests the KHR_materials_iridescence extension on non-metallic (dielectric) materials."}},{name:"IridescenceMetallicSpheres",path:"gltf/gltfExtensions/iridescence/iridescenceMetallicSpheres",extensionList:["KHR_materials_iridescence"],description:{ko:"금속 구체에 적용된 무지개빛 효과를 테스트합니다.",en:"Tests iridescence effects applied to metallic spheres."}},{name:"IridescenceSuzanne",path:"gltf/gltfExtensions/iridescence/iridescenceSuzanne",extensionList:["KHR_materials_iridescence"],description:{ko:"Suzanne 모델에 적용된 무지개빛 쉐이더 테스트입니다.",en:"Iridescence shader test applied to the Suzanne model."}},{name:"IridescenceLamp",path:"gltf/gltfExtensions/iridescence/iridescenceLamp",extensionList:["KHR_materials_iridescence","KHR_materials_transmission","KHR_materials_volume"],description:{ko:"투과 및 볼륨 효과와 함께 KHR_materials_iridescence를 보여주는 Wayfair 램프 모델입니다.",en:"A Wayfair lamp model showcasing transmission, volume, and KHR_materials_iridescence."}},{name:"SunglassesKhronos",path:"gltf/gltfExtensions/iridescence/sunglassesKhronos",extensionList:["KHR_materials_iridescence","KHR_materials_transmission"],description:{ko:"렌즈에 얇은 막 무지개빛 효과가 적용된 선글라스 모델입니다.",en:"Sunglasses model with thin-film iridescence effects applied to the lenses."}},{name:"IridescentDishWithOlives",path:"gltf/gltfExtensions/iridescence/iridescentDishWithOlives",extensionList:["KHR_materials_iridescence","KHR_materials_transmission","KHR_materials_volume","KHR_materials_ior","KHR_materials_specular"],description:{ko:"투과, 볼륨, IOR 및 스펙큘러 속성을 보여주는 접시 모델입니다.",en:"A dish demonstrating transmission, volume, IOR, and specular properties."}}]},{name:"KHR_materials_clearcoat",list:[{name:"CompareClearcoat",path:"gltf/gltfExtensions/clearcoat/compareClearcoat",extensionList:["KHR_materials_clearcoat"],description:{ko:"클리어코트(Clearcoat) 재질 렌더링 결과를 비교합니다.",en:"Compares Clearcoat material rendering results."}},{name:"ClearCoatTest",path:"gltf/gltfExtensions/clearcoat/clearCoatTest",extensionList:["KHR_materials_clearcoat"],description:{ko:"다양한 거칠기와 클리어코트 강도를 테스트합니다.",en:"Tests various roughness and clearcoat strengths."}},{name:"ClearcoatWicker",path:"gltf/gltfExtensions/clearcoat/clearcoatWicker",extensionList:["KHR_materials_clearcoat"],description:{ko:"직물 표면 위에 코팅된 클리어코트 효과를 보여주는 위커 모델입니다.",en:"Wicker model showing clearcoat effect coated over a woven surface."}},{name:"ClearCoatCarPaint",path:"gltf/gltfExtensions/clearcoat/clearCoatCarPaint",extensionList:["KHR_materials_clearcoat"],description:{ko:"자동차 페인트와 같은 다중 레이어 재질 표현을 테스트합니다.",en:"Tests multi-layer material representation like car paint."}}]},{name:"KHR_materials_dispersion",list:[{name:"CompareDispersion",path:"gltf/gltfExtensions/dispersion/compareDispersion",extensionList:["KHR_materials_dispersion","KHR_materials_transmission"],description:{ko:"빛의 분산(Dispersion) 효과를 비교합니다.",en:"Compares light dispersion effects."}},{name:"DispersionTest",path:"gltf/gltfExtensions/dispersion/dispersionTest",extensionList:["KHR_materials_dispersion","KHR_materials_transmission"],description:{ko:"프리즘과 같은 빛의 분산 현상을 테스트합니다.",en:"Tests light dispersion phenomena like a prism."}},{name:"DragonDispersion",path:"gltf/gltfExtensions/dispersion/dragonDispersion",extensionList:["KHR_materials_dispersion","KHR_materials_transmission","KHR_materials_volume"],description:{ko:"용 모델에 적용된 보석 같은 분산 효과를 보여줍니다.",en:"Shows gem-like dispersion effects applied to a Dragon model."}}]},{name:"KHR_materials_emissive_strength",list:[{name:"CompareEmissiveStrength",path:"gltf/gltfExtensions/emissiveStrength/compareEmissiveStrength",extensionList:["KHR_materials_emissive_strength"],description:{ko:"발광(Emissive) 강도 증폭 효과를 비교합니다.",en:"Compares Emissive Strength amplification effects."}},{name:"EmissiveStrengthTest",path:"gltf/gltfExtensions/emissiveStrength/emissiveStrengthTest",extensionList:["KHR_materials_emissive_strength"],description:{ko:"1.0을 초과하는 고강도 발광 표현을 테스트합니다.",en:"Tests high-intensity emissive representation exceeding 1.0."}}]},{name:"KHR_materials_sheen",list:[{name:"CompareSheen",path:"gltf/gltfExtensions/sheen/compareSheen",extensionList:["KHR_materials_sheen"],description:{ko:"직물 등의 미세한 반사광(Sheen) 효과를 비교합니다.",en:"Compares Sheen effects seen on fabrics etc."}},{name:"SheenTestGrid",path:"gltf/gltfExtensions/sheen/sheenTestGrid",extensionList:["KHR_materials_sheen"],description:{ko:"Sheen 색상과 거칠기에 따른 변화를 그리드로 테스트합니다.",en:"Tests changes based on Sheen color and roughness in a grid."}},{name:"SheenCloth",path:"gltf/gltfExtensions/sheen/sheenCloth",extensionList:["KHR_materials_sheen"],description:{ko:"Sheen 효과를 보여주는 직물 예제입니다.",en:"A fabric example showcasing sheen."}},{name:"SheenChair",path:"gltf/gltfExtensions/sheen/sheenChair",extensionList:["KHR_materials_sheen","KHR_materials_variants"],description:{ko:"재질 변형(Variant)과 Sheen 효과를 보여주는 의자 모델입니다.",en:"A chair model demonstrating material variants and sheen."}},{name:"GlamVelvetSofa",path:"gltf/gltfExtensions/sheen/glamVelvetSofa",extensionList:["KHR_materials_sheen","KHR_materials_specular","KHR_materials_variants"],description:{ko:"고급 벨벳 소파의 질감을 표현하는 Sheen 모델입니다.",en:"Sheen model expressing the texture of a luxury velvet sofa."}},{name:"ChairDamaskPurplegold",path:"gltf/gltfExtensions/sheen/chairDamaskPurplegold",extensionList:["KHR_materials_sheen"],description:{ko:"다마스크 패턴 의자의 직물 느낌을 표현합니다.",en:"Expresses the fabric feel of a damask pattern chair."}},{name:"SheenWoodLeatherSofa",path:"gltf/gltfExtensions/sheen/sheenWoodLeatherSofa",extensionList:["KHR_materials_sheen"],description:{ko:"가죽과 나무 재질이 혼합된 소파에서의 Sheen 효과입니다.",en:"Sheen effect on a sofa combining leather and wood materials."}}]},{name:"KHR_materials_specular",list:[{name:"CompareSpecular",path:"gltf/gltfExtensions/specular/compareSpecular",extensionList:["KHR_materials_specular"],description:{ko:"스펙큘러(Specular) 반사 강도 및 색상 제어를 비교합니다.",en:"Compares Specular reflection strength and color control."}},{name:"SpecularTest",path:"gltf/gltfExtensions/specular/specularTest",extensionList:["KHR_materials_specular"],description:{ko:"유전체 재질의 스펙큘러 하이라이트 조절을 테스트합니다.",en:"Tests specular highlight adjustments on dielectric materials."}},{name:"SpecularSilkPouf",path:"gltf/gltfExtensions/specular/specularSilkPouf",extensionList:["KHR_materials_specular"],description:{ko:"스펙큘러 속성을 보여주는 실크 푸프 모델입니다.",en:"A silk pouf model demonstrating specular properties."}}]},{name:"KHR_materials_unlit",list:[{name:"UnlitTest",path:"gltf/gltfExtensions/unlit/unlitTest",extensionList:["KHR_materials_unlit"],description:{ko:"조명의 영향을 받지 않는 Unlit(무광) 재질을 테스트합니다.",en:"Tests Unlit materials not affected by lighting."}}]},{name:"KHR_texture_transform",list:[{name:"TextureTransformTest",path:"gltf/gltfExtensions/textureTransform/textureTransformTest",extensionList:["KHR_texture_transform"],description:{ko:"KHR_texture_transform 확장의 사용법(스케일, 회전, 이동)을 시연합니다.",en:"Demonstrates the usage of the KHR_texture_transform extension (scaling, rotation, translation)."}},{name:"TextureTransformMultiTest",path:"gltf/gltfExtensions/textureTransform/textureTransformMultiTest",extensionList:["KHR_texture_transform"],description:{ko:"여러 텍스처에 서로 다른 변환을 적용하는 테스트입니다.",en:"Tests applying different transforms to multiple textures."}}]},{name:"KHR_materials_diffuseTransmission",list:[{name:"DiffuseTransmissionTest",path:"gltf/gltfExtensions/diffuseTransmission/diffuseTransmissionTest",extensionList:["KHR_materials_diffuseTransmission"],description:{ko:"반투명한 물체의 확산 투과(Diffuse Transmission) 효과를 테스트합니다.",en:"Tests Diffuse Transmission effects on translucent objects."}},{name:"DiffuseTransmissionTeacup",path:"gltf/gltfExtensions/diffuseTransmission/diffuseTransmissionTeacup",extensionList:["KHR_materials_diffuseTransmission"],description:{ko:"얇은 찻잔을 통과하는 빛의 확산을 보여줍니다.",en:"Shows light diffusion passing through a thin teacup."}}]},{name:"KHR_materials_transmission",list:[{name:"CompareTransmission",path:"gltf/gltfExtensions/transmission/compareTransmission",extensionList:["KHR_materials_transmission"],description:{ko:"투명한 물체의 투과(Transmission) 렌더링을 비교합니다.",en:"Compares Transmission rendering of transparent objects."}},{name:"TransmissionTest",path:"gltf/gltfExtensions/transmission/transmissionTest",extensionList:["KHR_materials_transmission","KHR_materials_ior"],description:{ko:"다양한 투과율과 거칠기에 따른 굴절 효과를 테스트합니다.",en:"Tests refraction effects based on various transmission rates and roughness."}},{name:"TransmissionRoughnessTest",path:"gltf/gltfExtensions/transmission/transmissionRoughnessTest",extensionList:["KHR_materials_transmission"],description:{ko:"거친 표면을 가진 투명 재질의 흐림 효과를 테스트합니다.",en:"Tests blurring effects on transparent materials with rough surfaces."}},{name:"StainedGlassLamp",path:"gltf/gltfExtensions/transmission/stainedGlassLamp",extensionList:["KHR_materials_transmission"],description:{ko:"스테인드글라스 램프를 통해 색상이 있는 투과광을 보여줍니다.",en:"Shows colored transmitted light through a stained glass lamp."}},{name:"ChronographWatch",path:"gltf/gltfExtensions/transmission/chronographWatch",extensionList:["KHR_materials_transmission","KHR_materials_variants"],description:{ko:"시계 유리의 투명도와 내부 디테일을 보여주는 고품질 모델입니다.",en:"High-quality model showing watch glass transparency and internal details."}},{name:"MosquitoInAmber",path:"gltf/gltfExtensions/transmission/mosquitoInAmber",extensionList:["KHR_materials_transmission","KHR_materials_volume","KHR_materials_ior"],description:{ko:"호박(Amber) 속에 갇힌 모기를 통해 투과, 굴절률(IOR), 볼륨 속성을 시연합니다.",en:"A mosquito encased in amber, demonstrating the use of transmission, IOR, and volume properties."}},{name:"CommercialRefrigerator",path:"gltf/gltfExtensions/transmission/commercialRefrigerator",extensionList:["KHR_materials_transmission"],description:{ko:"유리 문을 가진 상업용 냉장고 모델입니다.",en:"Commercial refrigerator model with glass doors."}}]},{name:"KHR_materials_volume",list:[{name:"CompareIor",path:"gltf/gltfExtensions/volume/compareIor",extensionList:["KHR_materials_ior"],description:{ko:"굴절률(IOR)에 따른 빛의 굴절 차이를 비교합니다.",en:"Compares light refraction differences based on Index of Refraction (IOR)."}},{name:"IORTestGrid",path:"gltf/gltfExtensions/volume/IORTestGrid",extensionList:["KHR_materials_ior"],description:{ko:"다양한 IOR 값에 따른 굴절 변화를 그리드로 테스트합니다.",en:"Tests refraction changes based on various IOR values in a grid."}},{name:"CompareVolume",path:"gltf/gltfExtensions/volume/compareVolume",extensionList:["KHR_materials_volume"],description:{ko:"볼륨(Volume) 흡수 및 산란 효과를 비교합니다.",en:"Compares Volume absorption and scattering effects."}},{name:"TransmissionThinwallTestGrid",path:"gltf/gltfExtensions/volume/transmissionThinwallTestGrid",extensionList:["KHR_materials_transmission","KHR_materials_volume"],description:{ko:"얇은 벽(Thin-walled) 옵션 활성화 여부에 따른 투과 차이를 테스트합니다.",en:"Tests transmission differences based on Thin-walled option activation."}},{name:"AttenuationTest",path:"gltf/gltfExtensions/volume/attenuationTest",extensionList:["KHR_materials_volume"],description:{ko:"빛이 매질을 통과할 때의 감쇠(Attenuation) 거리와 색상을 테스트합니다.",en:"Tests attenuation distance and color as light passes through a medium."}},{name:"GlassVaseFlowers",path:"gltf/gltfExtensions/volume/glassVaseFlowers",extensionList:["KHR_materials_transmission","KHR_materials_volume","KHR_materials_ior"],description:{ko:"유리 꽃병과 물의 볼륨 효과를 보여주는 모델입니다.",en:"Model showing volume effects of a glass vase and water."}},{name:"GlassBrokenWindow",path:"gltf/gltfExtensions/volume/glassBrokenWindow",extensionList:["KHR_materials_transmission","KHR_materials_volume","KHR_materials_ior"],description:{ko:"깨진 유리창의 두께감과 굴절을 표현합니다.",en:"Expresses the thickness and refraction of a broken window."}},{name:"GlassHurricaneCandleHolder",path:"gltf/gltfExtensions/volume/glassHurricaneCandleHolder",extensionList:["KHR_materials_transmission","KHR_materials_volume","KHR_materials_ior"],description:{ko:"복잡한 유리 형태의 굴절과 반사를 보여주는 캔들 홀더입니다.",en:"Candle holder showing refraction and reflection of complex glass shapes."}},{name:"DragonAttenuation",path:"gltf/gltfExtensions/volume/dragonAttenuation",extensionList:["KHR_materials_transmission","KHR_materials_volume"],description:{ko:"KHR_materials_transmission과 KHR_materials_volume을 사용하여 색유리와 같은 객체를 표현합니다.",en:"Showcases KHR_materials_transmission and KHR_materials_volume, creating an object that resembles colored glass."}}]}]}]},{name:"PostEffect",list:[{name:"Convolution",path:"postEffect/convolution",description:{ko:"컨볼루션 필터 효과를 시연하는 예제입니다.",en:"An example demonstrating convolution filter effects."}},{name:"FilmGrain",path:"postEffect/filmGrain",description:{ko:"필름 그레인 효과를 시연하는 예제입니다.",en:"An example demonstrating film grain effects."}},{name:"OldBloom",path:"postEffect/oldBloom",description:{ko:"고전적인 블룸 효과를 시연하는 예제입니다.",en:"An example demonstrating classic bloom effects."}},{name:"Sharpen",path:"postEffect/sharpen",description:{ko:"선명도(Sharpen) 효과를 시연하는 예제입니다.",en:"An example demonstrating sharpen effects."}},{name:"Adjustments",list:[{name:"Grayscale",path:"postEffect/adjustments/grayscale",description:{ko:"그레이스케일 색상 보정 효과 예제입니다.",en:"Example of Grayscale color adjustment effect."}},{name:"Invert",path:"postEffect/adjustments/invert",description:{ko:"색상 반전 효과 예제입니다.",en:"Example of Invert color adjustment effect."}},{name:"ColorBalance",path:"postEffect/adjustments/colorBalance",description:{ko:"컬러 밸런스 색상 보정 효과 예제입니다.",en:"Example of Color Balance color adjustment effect."}},{name:"ColorTemperatureTint",path:"postEffect/adjustments/colorTemperatureTint",description:{ko:"색온도 및 틴트 색상 보정 효과 예제입니다.",en:"Example of Color Temperature & Tint color adjustment effect."}},{name:"BrightnessContrast",path:"postEffect/adjustments/brightnessContrast",description:{ko:"밝기 및 대비 색상 보정 효과 예제입니다.",en:"Example of Brightness & Contrast color adjustment effect."}},{name:"HueSaturation",path:"postEffect/adjustments/hueSaturation",description:{ko:"색조 및 채도 색상 보정 효과 예제입니다.",en:"Example of Hue & Saturation color adjustment effect."}},{name:"Threshold",path:"postEffect/adjustments/threshold",description:{ko:"임계값(Threshold) 색상 보정 효과 예제입니다.",en:"Example of Threshold color adjustment effect."}},{name:"Vibrance",path:"postEffect/adjustments/vibrance",description:{ko:"활기(Vibrance) 색상 보정 효과 예제입니다.",en:"Example of Vibrance color adjustment effect."}}]},{name:"Blur",list:[{name:"Blur",path:"postEffect/blur/blur",description:{ko:"기본 블러 효과 예제입니다.",en:"Example of Basic Blur effect."}},{name:"BlurX",path:"postEffect/blur/blurX",description:{ko:"가로 방향 블러 효과 예제입니다.",en:"Example of Horizontal Blur effect."}},{name:"BlurY",path:"postEffect/blur/blurY",description:{ko:"세로 방향 블러 효과 예제입니다.",en:"Example of Vertical Blur effect."}},{name:"DirectionalBlur",path:"postEffect/blur/directionalBlur",description:{ko:"방향성 블러 효과 예제입니다.",en:"Example of Directional Blur effect."}},{name:"GaussianBlur",path:"postEffect/blur/gaussianBlur",description:{ko:"가우시안 블러 효과 예제입니다.",en:"Example of Gaussian Blur effect."}},{name:"RadialBlur",path:"postEffect/blur/radialBlur",description:{ko:"방사형 블러 효과 예제입니다.",en:"Example of Radial Blur effect."}},{name:"ZoomBlur",path:"postEffect/blur/zoomBlur",description:{ko:"줌 블러 효과 예제입니다.",en:"Example of Zoom Blur effect."}}]},{name:"Lens",list:[{name:"LensDistortion",path:"postEffect/lens/lensDistortion",description:{ko:"렌즈 왜곡 효과 예제입니다.",en:"Example of Lens Distortion effect."}},{name:"ChromaticAberration",path:"postEffect/lens/chromaticAberration",description:{ko:"색수차 효과 예제입니다.",en:"Example of Chromatic Aberration effect."}},{name:"DepthOfField",path:"postEffect/lens/dof",description:{ko:"피사계 심도(DoF) 효과 예제입니다.",en:"Example of Depth of Field effect."}},{name:"Vignetting",path:"postEffect/lens/vignetting",description:{ko:"비네팅 효과 예제입니다.",en:"Example of Vignetting effect."}}]},{name:"Fog",list:[{name:"Fog",path:"postEffect/fog/fog",description:{ko:"안개 효과를 시연하는 예제입니다.",en:"An example demonstrating fog effects."}},{name:"HeightFog",path:"postEffect/fog/heightFog",description:{ko:"높이 기반 안개 효과를 시연하는 예제입니다.",en:"An example demonstrating height-based fog effects."}}]},{name:"Screen Space Reflection",experimental:!0,list:[{experimental:!0,name:"SSR",path:"postEffect/ssr",description:{ko:"화면 공간 반사(SSR) 효과를 시연하는 예제입니다.",en:"An example demonstrating Screen Space Reflection (SSR) effects."}}]},{name:"Screen Space Ambient Occlusion",list:[{name:"SSAO",path:"postEffect/ssao",description:{ko:"화면 공간 앰비언트 오클루전(SSAO) 효과를 시연하는 예제입니다.",en:"An example demonstrating Screen Space Ambient Occlusion (SSAO) effects."}}]}]},{name:"2D",list:[{name:"Hello RedGPU - 2D Mode",path:"2d/helloWorld2D",description:{ko:"RedGPU의 2D 모드 초기화 샘플입니다.",en:"Sample of RedGPU's 2D mode initialization."}},{name:"View2D",list:[{name:"Multi View (2D + 2D)",path:"2d/view/multiView",description:{ko:"여러 개의 2D View를 사용하는 멀티 뷰 예제입니다.",en:"Multi-view example using multiple 2D Views."}},{name:"Multi View (3D + 2D)",path:"2d/view/multiViewWith3D",description:{ko:"3D View와 2D View를 함께 사용하는 복합 멀티 뷰 예제입니다.",en:"Complex multi-view example using both 3D View and 2D View."}}]},{name:"Sprite2D",list:[{name:"Basic Sprite2D",path:"2d/sprite2D/basic",description:{ko:"기본적인 Sprite2D 객체 사용법을 보여주는 예제입니다.",en:"An example showing basic usage of Sprite2D object."}},{name:"Hierarchy Sprite2D",path:"2d/sprite2D/hierarchy",description:{ko:"2D 공간에서 Sprite2D의 계층 구조를 구성하는 예제입니다.",en:"An example constructing a hierarchy of Sprite2D in 2D space."}},{name:"Pivot Sprite2D",path:"2d/sprite2D/pivot",description:{ko:"Sprite2D의 피벗(중심점)을 변경하여 회전 및 위치를 제어하는 예제입니다.",en:"An example controlling rotation and position by changing the pivot of Sprite2D."}},{name:"Child Methods",path:"2d/sprite2D/childMethod",description:{ko:"2D 객체의 자식 노드를 관리하는 다양한 메서드를 시연하는 예제입니다.",en:"An example demonstrating various methods for managing child nodes of 2D objects."}}]},{name:"SpriteSheet2D",list:[{name:"Basic SpriteSheet2D",path:"2d/spriteSheet2D/basic",description:{ko:"스프라이트 시트 애니메이션을 재생하는 기본적인 SpriteSheet2D 예제입니다.",en:"Basic SpriteSheet2D example playing sprite sheet animation."}}]},{name:"TextField2D",list:[{name:"Basic TextField2D",path:"2d/textField2D/basic",description:{ko:"2D 텍스트를 렌더링하는 TextField2D 객체의 기본 사용법 예제입니다.",en:"Basic usage example of TextField2D object for rendering 2D text."}}]},{name:"Group2D",list:[{name:"Basic Group2D",path:"2d/group2D/basic",description:{ko:"2D 객체들을 그룹화하여 관리하는 Group2D 예제입니다.",en:"Group2D example managing 2D objects by grouping them."}}]},{name:"2D Object Opacity",list:[{name:"2D Object Opacity",path:"2d/opacity/basic",description:{ko:"2D 객체의 투명도(Opacity)를 조절하는 예제입니다.",en:"An example adjusting the opacity of 2D objects."}}]},{name:"2D Object BlendMode",list:[{name:"BlendMode",path:"2d/blendMode/basic",description:{ko:"2D 객체의 다양한 블렌딩 모드를 테스트하는 예제입니다.",en:"An example testing various blending modes of 2D objects."}}]},{name:"2D Tint",experimental:!0,list:[{experimental:!0,name:"Tint Basic",path:"2d/tint/basic",description:{ko:"2D 객체에 색상을 입히는 기본 틴트 예제입니다.",en:"Basic tint example applying color to 2D objects."}},{experimental:!0,name:"Tint Objects",path:"2d/tint/2dObjectTint",description:{ko:"다양한 2D 객체에 틴트를 적용하는 예제입니다.",en:"An example applying tint to various 2D objects."}}]},{name:"Interaction",list:[{name:"MouseEvent",list:[{name:"Sprite2D",path:"2d/interaction/mouseEvent/sprite2D",description:{ko:"Sprite2D에 대한 마우스 이벤트를 처리하는 예제입니다.",en:"An example handling mouse events on Sprite2D."}},{name:"SpriteSheet2D",path:"2d/interaction/mouseEvent/spriteSheet2D",description:{ko:"SpriteSheet2D에 대한 마우스 이벤트를 처리하는 예제입니다.",en:"An example handling mouse events on SpriteSheet2D."}},{name:"TextField2D",path:"2d/interaction/mouseEvent/textField2D",description:{ko:"TextField2D에 대한 마우스 이벤트를 처리하는 예제입니다.",en:"An example handling mouse events on TextField2D."}}]},{name:"KeyboardEvent",list:[{name:"Keyboard Interaction",path:"2d/interaction/keyboardEvent",description:{ko:"keyboardKeyBuffer를 사용하여 2D 환경에서 객체를 제어하는 방법을 보여줍니다.",en:"Demonstrates how to control an object in a 2D environment using keyboardKeyBuffer."}}]}]}]},{name:"Physics",experimental:!0,list:[{name:"Fundamentals",experimental:!0,list:[{experimental:!0,name:"Basic Physics",path:"physics/basic",description:{ko:"Rapier 물리 엔진을 사용한 기본적인 물리 시뮬레이션 예제입니다.",en:"Basic physics simulation example using the Rapier physics engine."}},{experimental:!0,name:"Shapes & Materials",path:"physics/shapes",description:{ko:"다양한 충돌체 형상(Box, Sphere, Cylinder, Capsule)과 탄성/마찰 설정을 테스트합니다.",en:"Tests various collider shapes (Box, Sphere, Cylinder, Capsule) and restitution/friction settings."}},{experimental:!0,name:"Kinematic Interaction",path:"physics/kinematic",description:{ko:"코드에 의해 제어되는 키네마틱 객체가 동적 객체들과 상호작용하는 모습을 보여줍니다.",en:"Demonstrates how kinematic objects controlled by code interact with dynamic objects."}},{experimental:!0,name:"Mesh Collider",path:"physics/meshCollider",description:{ko:"커스텀 기하구조를 물리 충돌체로 변환하는 방법을 테스트합니다.",en:"Tests how to convert custom geometries into physics engine colliders."}},{experimental:!0,name:"HeightField",path:"physics/heightField",description:{ko:"높이맵 데이터를 사용하여 지형과 같은 복잡한 표면의 물리 충돌을 구현하는 방법을 테스트합니다.",en:"Tests how to implement physics collisions for complex surfaces like terrain using heightmap data."}},{experimental:!0,name:"GLTF Physics",path:"physics/gltfPhysics",description:{ko:"로드된 GLTF 모델의 복잡한 계층 구조와 메쉬 데이터를 분석하여 자동으로 물리 충돌체를 생성하는 방법을 테스트합니다.",en:"Tests how to automatically generate physics colliders by analyzing the complex hierarchy and mesh data of a loaded GLTF model."}}]},{name:"Interaction & Events",experimental:!0,list:[{experimental:!0,name:"Raycasting Interaction",path:"physics/raycast",description:{ko:"마우스 클릭 지점에서 광선을 쏘아 물리 객체를 검출하고, 힘을 가해 밀어내는 등의 상호작용을 구현합니다.",en:"Casts rays from mouse click positions to detect physics objects and implements interactions like pushing them with force."}},{experimental:!0,name:"Collision Events",path:"physics/collisionEvents",description:{ko:"물체 간의 충돌 이벤트를 감지하여 실시간으로 색상을 변경하는 등 물리 연동 로직을 테스트합니다.",en:"Tests physics integration logic by detecting collision events between objects and changing colors in real-time."}},{experimental:!0,name:"Triggers & Sensors",path:"physics/triggers",description:{ko:"물체와 물리적인 충돌은 발생하지 않으나 영역 진입을 감지하는 센서(Trigger) 기능을 테스트합니다.",en:"Tests the sensor (Trigger) function that detects area entry without physical collision."}},{experimental:!0,name:"Collision Filtering",path:"physics/collisionFiltering",description:{ko:"Bitmask 기반의 충돌 그룹 설정을 통해 특정 객체들끼리만 선택적으로 충돌하도록 제어하는 고급 물리 기술을 구현합니다.",en:"Implements advanced physics techniques to selectively control collisions between specific objects through Bitmask-based collision group settings."}}]},{name:"Joints & Constraints",experimental:!0,list:[{experimental:!0,name:"Basic Joints",path:"physics/joints",description:{ko:"물체들을 서로 연결하는 관절(Joint) 기능을 사용하여 체인이나 진자 운동과 같은 복잡한 물리 구조를 구현합니다.",en:"Implements complex physical structures like chains or pendulums using joints to connect objects together."}},{experimental:!0,name:"Revolute Joints & Motors",path:"physics/revoluteJoint",description:{ko:"특정 축을 기준으로 회전하는 관절(Revolute Joint)과 모터 기능을 사용하여 풍차나 선풍기와 같은 회전 장치를 구현합니다.",en:"Implements rotating devices like windmills or fans using revolute joints that rotate around a specific axis and motor functions."}},{experimental:!0,name:"Prismatic Joints & Sliders",path:"physics/prismaticJoint",description:{ko:"직선 방향으로만 왕복 이동이 가능한 프리즈매틱 관절(Prismatic Joint)을 사용하여 승강기나 슬라이더 장치를 구현합니다.",en:"Implements elevators or slider devices using prismatic joints that allow reciprocal movement only in a straight line."}},{experimental:!0,name:"Spring Joint",path:"physics/springJoint",description:{ko:"스프링 조인트를 사용하여 탄성 있는 연결을 구현하는 방법을 테스트합니다.",en:"Tests how to implement elastic connections using spring joints."}},{experimental:!0,name:"Soft Body",path:"physics/softBody",description:{ko:"다수의 노드를 스프링으로 연결하여 젤리와 같은 소프트 바디 효과를 구현합니다.",en:"Implements a jelly-like soft body effect by connecting multiple nodes with springs."}},{experimental:!0,name:"Compound Shapes",path:"physics/compound",description:{ko:"여러 개의 지오메트리를 결합하여 하나의 복잡한 물리 객체를 만드는 복합 형상 기능을 테스트합니다.",en:"Tests the compound shape function that combines multiple geometries to create a single complex physics object."}}]},{name:"Simulation & Systems",experimental:!0,list:[{experimental:!0,name:"Surface Velocity (Conveyor)",path:"physics/surfaceVelocity",description:{ko:"컨베이어 벨트와 같이 표면이 움직이는 물체를 시뮬레이션합니다. 물체가 닿았을 때 특정 방향으로 힘을 가하여 이동시킵니다.",en:"Simulates objects with moving surfaces like conveyor belts. Applies force to move objects in a specific direction when they make contact."}},{experimental:!0,name:"Buoyancy Basics",path:"physics/buoyancy",description:{ko:"물속에서 물체가 떠오르는 부력과 유체 저항을 시뮬레이션합니다. 잠긴 깊이에 따라 상향 힘을 조절합니다.",en:"Simulates buoyancy and fluid resistance for objects in water. Adjusts upward force based on submerged depth."}},{experimental:!0,name:"Ragdoll System",path:"physics/ragdoll",description:{ko:"인간형 캐릭터의 뼈대를 관절(Joint)로 연결하여, 중력에 의해 자연스럽게 쓰러지는 래그돌 물리 효과를 시뮬레이션합니다.",en:"Simulates ragdoll physics where a humanoid skeleton is connected with joints and falls naturally under gravity."}},{experimental:!0,name:"Character Controller",path:"physics/characterController",description:{ko:"지면을 걷고 계단을 오르는 1인칭/3인칭 캐릭터 이동의 기초를 구현합니다.",en:"Implements the basics of 1st/3rd person character movement walking on the ground and climbing stairs."}},{experimental:!0,name:"Advanced Character Controller",path:"physics/advancedCharacterController",description:{ko:"관성 이동, 공중 제어, 이중 점프 등 게임적인 조작감이 가미된 고급 캐릭터 컨트롤러를 구현합니다.",en:"Implements an advanced character controller with game-like controls such as inertial movement, air control, and double jumping."}}]},{name:"Performance & Stress Test",experimental:!0,list:[{experimental:!0,name:"Galton Board",path:"physics/galton",description:{ko:"수많은 구슬이 핀 사이를 떨어지며 통계적 분포를 형성하는 과정을 시뮬레이션합니다.",en:"Simulates the process where numerous balls fall between pins and form a statistical distribution."}},{experimental:!0,name:"Physics Bowling",path:"physics/bowling",description:{ko:"고속으로 이동하는 볼과 핀 사이의 충돌 및 연쇄 반응을 테스트합니다. CCD(Continuous Collision Detection) 기술이 적용되었습니다.",en:"Tests collisions and chain reactions between a fast-moving ball and pins. CCD (Continuous Collision Detection) technology is applied."}},{experimental:!0,name:"Impulse Explosion",path:"physics/explosion",description:{ko:"폭발 지점으로부터 주변 객체들에 충격량을 가하여 날려버리는 물리 효과를 구현합니다.",en:"Implements physics effects where impulse is applied from an explosion point to blow away surrounding objects."}},{experimental:!0,name:"Ultimate Stress Test",path:"physics/stressTest",description:{ko:"수천 개의 물리 객체를 동시에 시뮬레이션하여 엔진의 한계 성능을 테스트합니다. 휴면(Sleep) 모드 활성화를 통한 최적화 효과를 확인합니다.",en:"Tests the engine's performance limits by simulating thousands of physics objects simultaneously. Demonstrates optimization through Sleep mode."}}]}]}];Object.freeze(i);export{t as n,i as t}; \ No newline at end of file +import{n as e}from"./rolldown-runtime-BztV3taV.js?t=1781136546834";var t=e({ExampleList:()=>i,default:()=>i}),i=[{name:"3D",list:[{name:"Hello RedGPU",path:"3d/helloWorld",description:{ko:"RedGPU의 기본 초기화 방법을 보여주는 샘플입니다.
초기화 성공 시 제공되는 RedGPUContext 객체의 기본 옵션들을 실시간으로 테스트할 수 있습니다.",en:"This example is a sample of the basic initialization of RedGPU.
\n It also provides a live test of the basic options provided to the RedGPUContext object provided upon successful initialization."}},{name:"View3D",list:[{name:"Single View3D",path:"3d/view/singleView",description:{ko:"RedGPU의 View 객체에 대한 샘플입니다. View 객체에 제공되는 기본 옵션들을 실시간으로 테스트할 수 있습니다.",en:"This example is a sample for a View object in RedGPU.
\n It provides real-time testing of the basic options provided to a View object."}},{name:"Multi View3D",path:"3d/view/multiView",description:{ko:"RedGPU의 멀티 뷰 기능을 보여주는 샘플입니다.
RedGPUContext는 여러 개의 View를 소유하고 관리할 수 있습니다.",en:"This example is a sample of RedGPU's Multi View.
RedGPUContext can own and manage multiple MultiViews."}}]},{name:"Scene",list:[{name:"Scene",path:"3d/scene",description:{ko:"RedGPU의 Scene 객체에 대한 샘플입니다.
Scene 객체에 제공되는 기본 옵션들을 실시간으로 테스트할 수 있습니다.",en:"This example is a sample of a Scene object in RedGPU.
It provides real-time testing of the basic options provided to the Scene object."}}]},{name:"Camera Controller",list:[{name:"FreeController",path:"3d/controller/freeController",description:{ko:"FreeController는 키보드(WASD/QERTFG)와 마우스/터치 입력을 사용하여 1인칭 카메라 제어를 제공합니다.
3D 공간에서의 자유로운 이동, 회전 제어, 속도/가속도 조절 및 키 바인딩 설정 기능을 포함합니다.",en:"FreeController provides first-person camera control with keyboard (WASD/QERTFG) and mouse/touch input.
Features include free movement in 3D space, rotation control, customizable speed/acceleration, and key binding configuration."}},{name:"OrbitController",path:"3d/controller/orbitController",description:{ko:"OrbitController는 중심점을 기준으로 회전하는 궤도형 카메라 제어를 제공합니다.
마우스 드래그 회전, 휠 줌, 터치 핀치 줌, 중심점 위치 사용자 정의, 거리 제어 및 팬/틸트 제한 기능을 포함합니다.",en:"OrbitController provides orbital camera control that rotates around a center point.
Features include mouse drag rotation, wheel zoom, touch pinch zoom, customizable center position, distance control, and pan/tilt limits."}},{name:"FollowController",path:"3d/controller/followController",description:{ko:"FollowController는 타겟 메쉬를 따라다니는 3인칭 카메라 제어를 제공합니다.
부드러운 카메라 추적, 거리 및 높이 조절, 팬/틸트 제어, 타겟 회전 추적 및 휠/핀치 줌 기능을 포함합니다.
3인칭 게임 및 객체 추적 시나리오에 적합합니다.",en:"FollowController provides third-person camera control that follows a target mesh.
Features include smooth camera following, customizable distance and height, pan/tilt control, target rotation tracking, and wheel/pinch zoom.
Perfect for third-person games and object tracking scenarios."}},{name:"IsometricController",path:"3d/controller/isometricController",description:{ko:"IsometricController는 아이소메트릭 뷰를 위한 고정 각도 직교 투영 카메라 제어를 제공합니다.
타겟 메쉬 추적, 키보드(WASD) 및 마우스 이동, 휠/핀치 줌 제어, 카메라 각도 및 뷰 높이 사용자 정의 기능을 포함합니다.
아이소메트릭 게임, 전략 게임 및 건축 시각화에 이상적입니다.",en:"IsometricController provides fixed-angle orthographic camera control for isometric views.
Features include target mesh tracking, keyboard (WASD) and mouse movement, wheel/pinch zoom control, and customizable camera angle and view height.
Ideal for isometric games, strategy games, and architectural visualization."}}]},{name:"Primitive",list:[{name:"Primitives",path:"3d/primitive/primitives",description:{ko:"RedGPU가 지원하는 기본적인 프리미티브 지오메트리들의 샘플입니다.",en:"Samples of basic primitive geometries supported by RedGPU."}},{name:"Box",path:"3d/primitive/box",description:{ko:"RedGPU가 지원하는 기본 Box 프리미티브에 대한 샘플입니다. Box 설정 옵션을 실시간으로 테스트할 수 있습니다.",en:"Samples for the basic Box Primitives supported by RedGPU. Provides real-time testing of Box configuration options."}},{name:"RoundedBox",path:"3d/primitive/roundedBox",description:{ko:"모서리가 둥근 박스 프리미티브에 대한 샘플입니다. 반지름(radius) 및 분할 수 설정을 통해 부드러운 모서리를 가진 박스를 생성하고 테스트할 수 있습니다.",en:"Samples for the RoundedBox Primitive. You can create and test boxes with smooth corners by configuring radius and segment settings."}},{name:"Circle",path:"3d/primitive/circle",description:{ko:"RedGPU가 지원하는 기본 Circle 프리미티브에 대한 샘플입니다. Circle 설정 옵션을 실시간으로 테스트할 수 있습니다.",en:"Samples for the basic Circle Primitives supported by RedGPU. Provides real-time testing of Circle configuration options."}},{name:"Cone",path:"3d/primitive/cone",description:{ko:"RedGPU가 지원하는 기본 Cone 프리미티브에 대한 샘플입니다. Cone 설정 옵션을 실시간으로 테스트할 수 있습니다.",en:"Samples for the basic Cone Primitives supported by RedGPU. Provides real-time testing of Cone configuration options."}},{name:"Cylinder",path:"3d/primitive/cylinder",description:{ko:"RedGPU가 지원하는 기본 Cylinder 프리미티브에 대한 샘플입니다. Cylinder 설정 옵션을 실시간으로 테스트할 수 있습니다.",en:"Samples for the basic Cylinder Primitives supported by RedGPU. Provides real-time testing of Cylinder configuration options."}},{name:"Plane",path:"3d/primitive/plane",description:{ko:"RedGPU가 지원하는 기본 Plane 프리미티브에 대한 샘플입니다. Plane 설정 옵션을 실시간으로 테스트할 수 있습니다.",en:"Samples for the basic Plane Primitives supported by RedGPU. Provides real-time testing of Plane configuration options."}},{name:"Ground",path:"3d/primitive/ground",description:{ko:"RedGPU가 지원하는 기본 Ground 프리미티브에 대한 샘플입니다. Ground 설정 옵션을 실시간으로 테스트할 수 있습니다.",en:"Samples for the basic Ground Primitives supported by RedGPU. Provides real-time testing of Ground configuration options."}},{name:"Sphere",path:"3d/primitive/sphere",description:{ko:"RedGPU가 지원하는 기본 Sphere 프리미티브에 대한 샘플입니다. Sphere 설정 옵션을 실시간으로 테스트할 수 있습니다.",en:"Samples for the basic Sphere Primitives supported by RedGPU. Provides real-time testing of Sphere configuration options."}},{name:"Capsule",path:"3d/primitive/capsule",description:{ko:"RedGPU가 지원하는 기본 Capsule 프리미티브에 대한 샘플입니다. Capsule 설정 옵션을 실시간으로 테스트할 수 있습니다.",en:"Samples for the basic Capsule Primitives supported by RedGPU. Provides real-time testing of Capsule configuration options."}},{name:"Torus",path:"3d/primitive/torus",description:{ko:"RedGPU가 지원하는 기본 Torus 프리미티브에 대한 샘플입니다. Torus 설정 옵션을 실시간으로 테스트할 수 있습니다.",en:"Samples for the basic Torus Primitives supported by RedGPU. Provides real-time testing of Torus configuration options."}},{name:"TorusKnot",path:"3d/primitive/torusKnot",description:{ko:"RedGPU가 지원하는 기본 TorusKnot 프리미티브에 대한 샘플입니다. TorusKnot 설정 옵션을 실시간으로 테스트할 수 있습니다.",en:"Samples for the basic TorusKnot Primitives supported by RedGPU. Provides real-time testing of TorusKnot configuration options."}},{name:"Ring",path:"3d/primitive/ring",description:{ko:"RedGPU가 지원하는 기본 Ring 프리미티브에 대한 샘플입니다. Ring 설정 옵션을 실시간으로 테스트할 수 있습니다.",en:"Samples for the basic Ring Primitives supported by RedGPU. Provides real-time testing of Ring configuration options."}}]},{name:"Mesh",list:[{name:"Basic Mesh",path:"3d/mesh/basicMesh",description:{ko:"이 코드는 기본 메쉬를 생성하고 위치, 크기, 회전, 재질 등 주요 속성을 실시간으로 조작하는 방법을 보여주는 샘플입니다.
RedGPU를 사용하여 Box 메쉬를 생성하고 속성과 재질을 조정하는 방법을 보여줍니다.",en:"this code is a sample that shows how to create a basic mesh and how to manipulate its main properties (position, scale, rotation, material, etc.) in real time.
This example shows how to create a Box mesh using RedGPU and how to adjust its properties and material."}},{name:"Hierarchy Mesh",path:"3d/mesh/hierarchy",description:{ko:"RedGPU를 사용하여 부모-자식 메쉬 계층 구조를 생성하고, 위치, 회전 및 스케일을 조작하는 예제입니다.",en:"An example of creating a parent-child mesh hierarchy using RedGPU, and manipulating its position, rotation, and scale."}},{name:"Pivot Mesh",path:"3d/mesh/pivot",description:{ko:"RedGPU를 사용하여 부모 및 자식 메쉬를 생성하고 피벗 설정을 통해 회전 중심을 변경하는 방법을 보여주는 실습 예제입니다.",en:"A hands-on example that demonstrates how to create parent and child meshes using RedGPU and change the center of rotation via pivot settings."}},{name:"Child Methods",path:"3d/mesh/childMethod",description:{ko:"RedGPU를 사용한 자식 노드 관리 예제로, 자식 추가, 삭제, 인덱스 변경, 교체 및 자식 색상 무작위화 등을 통해 노드를 동적으로 제어하는 방법을 보여줍니다.",en:"An example of child node management using RedGPU, showing how to dynamically control nodes by adding, deleting, changing index, replacing, and randomizing color of children."}},{name:"lookAt Methods",path:"3d/mesh/lookAt",description:{ko:"객체가 특정 지점이나 다른 객체를 바라보도록 하는 lookAt 메서드의 사용법을 보여주는 예제입니다.",en:"An example demonstrating the usage of the lookAt method to make an object face a specific point or another object."}},{name:"BoundingBox",list:[{name:"BoundingBox",path:"3d/mesh/boundBox/meshBoundBox",description:{ko:"메쉬의 바운딩 박스(AABB)를 시각화하고 확인하는 예제입니다.",en:"An example of visualizing and checking the bounding box (AABB) of a mesh."}},{name:"AABB - intersects",path:"3d/mesh/boundBox/meshAABBIntersects",description:{ko:"AABB(Axis-Aligned Bounding Box) 간의 교차 검사 기능을 테스트하는 예제입니다.",en:"An example testing the intersection check function between AABBs (Axis-Aligned Bounding Boxes)."}},{name:"OBB - intersects",path:"3d/mesh/boundBox/meshOBBIntersects",description:{ko:"OBB(Oriented Bounding Box) 간의 교차 검사 기능을 테스트하는 예제입니다.",en:"An example testing the intersection check function between OBBs (Oriented Bounding Boxes)."}}]}]},{name:"Coordinate Transformation",list:[{name:"worldToLocal / localToWorld",path:"3d/coordinateTransformation/worldToLocal",description:{ko:"월드 좌표와 로컬 좌표 간의 변환을 테스트하는 예제입니다.",en:"An example testing the transformation between world coordinates and local coordinates."}},{name:"screenToWorld",path:"3d/coordinateTransformation/screenToWorld",description:{ko:"화면(스크린) 좌표를 월드 좌표로 변환하는 방법을 보여주는 예제입니다.",en:"An example showing how to convert screen coordinates to world coordinates."}}]},{name:"Material",list:[{name:"ColorMaterial",path:"3d/material/colorMaterial",description:{ko:"RedGPU ColorMaterial의 기본 색상 조작 및 색상 설정을 위한 편의 메서드들에 대한 실시간 샘플을 제공합니다.",en:"Provides real-time samples of the basic color manipulations of RedGPU's ColorMaterial and convenience methods for setting colors."}},{name:"BitmapMaterial",path:"3d/material/bitmapMaterial",description:{ko:"RedGPU의 BitmapMaterial 샘플로, 다양한 텍스처 포맷(PNG, JPG, WEBP, SVG)을 적용하여 텍스처 변경을 실시간으로 테스트할 수 있습니다.",en:"RedGPU's BitmapMaterial sample allows you to test texture changes in real time by applying various texture formats (PNG, JPG, WEBP, SVG)."}},{name:"PhongMaterial",path:"3d/material/phongMaterial",description:{ko:"RedGPU를 사용하여 PhongMaterial의 기본 속성을 조작하고 다양한 텍스처 조합을 실험하는 방법을 보여주는 샘플 예제입니다.",en:"A sample example that demonstrates how to manipulate the basic properties of PhongMaterial using RedGPU and experiment with different texture combinations."}},{name:"PhongMaterial Texture Combination",path:"3d/material/phongMaterialTextures",description:{ko:"RedGPU를 사용하여 PhongMaterial의 다양한 텍스처 조합과 효과를 시각적으로 보여주는 샘플 예제입니다.",en:"A sample example that visually demonstrates different texture combinations and effects of PhongMaterial using RedGPU."}},{name:"UV Transform",path:"3d/material/uvTransform",description:{ko:"재질의 텍스처 오프셋과 스케일을 조절하여 흐르는 효과나 타일링을 구현하는 방법을 테스트합니다.",en:"Tests how to implement scrolling effects or tiling by adjusting the texture offset and scale of the material."}},{name:"Material Opacity",path:"3d/material/opacity",description:{ko:"재질의 불투명도(Opacity)를 조절하여 반투명 효과를 테스트하는 예제입니다.",en:"An example testing the translucency effect by adjusting the opacity of the material."}},{name:"Fragment Variant Test",path:"3d/material/fragmentVariantTest",description:{ko:"쉐이더의 프래그먼트 변형을 테스트하는 예제입니다.",en:"An example testing fragment variants of shaders."}}]},{name:"Texture & Sampler",list:[{name:"BitmapTexture & Sampler",path:"3d/texture/bitmapTextureSampler",description:{ko:"텍스처 샘플러 옵션과 밉맵 지원을 시연하는 샘플입니다.",en:"A sample that demonstrates texture sampler options and mipmap support."}},{name:"Sampler Combination",path:"3d/texture/samplerCombination",description:{ko:"텍스처 샘플러의 다양한 조합을 한눈에 보여주는 예제입니다.",en:"Here's an example showing the different combinations of texture samplers at a glance."}},{name:"Sampler SamplerAddressMode",path:"3d/texture/samplerAddressMode",description:{ko:"텍스처 샘플러의 AddressMode 옵션 조합을 보여주는 예제입니다.",en:"An example showing combinations of AddressMode options for a texture sampler."}},{name:"MaxAnisotropy",path:"3d/texture/maxAnisotropy",description:{ko:"텍스처의 비등방성 필터링(Anisotropy) 옵션을 보여주는 예제입니다.",en:"example showing the Anisotropy option for a texture."}}]},{name:"SkyBox & IBL",list:[{name:"SkyBox",list:[{name:"Skybox using 6 assets",path:"3d/skybox/skybox",description:{ko:"6개의 이미지를 사용하여 스카이박스를 구성하는 예제입니다.",en:"An example of constructing a skybox using 6 images."}},{name:"Skybox transition",list:[{name:"Basic transition",path:"3d/skybox/transition/skyboxTransition",description:{ko:"스카이박스 간의 부드러운 전환 효과를 보여주는 예제입니다.",en:"An example showing smooth transition effects between skyboxes."}},{name:"transitionAlphaTexture - with NoiseTexture",path:"3d/skybox/transition/skyboxTransitionWithNoiseTexture",description:{ko:"노이즈 텍스처와 알파 텍스처를 사용하여 스카이박스 전환 효과를 연출하는 예제입니다.",en:"An example creating skybox transition effects using noise textures and alpha textures."}}]}]},{name:"IBL",list:[{name:"Skybox using IBL",path:"3d/skybox/ibl/skyboxWithIbl",description:{ko:"IBL(Image Based Lighting)을 사용하여 스카이박스를 생성하는 방법을 보여줍니다.",en:"Demonstrates how to create a skybox using IBL (Image Based Lighting)."}},{name:"IBL Test",path:"3d/skybox/ibl/iblTest",description:{ko:"이미지 기반 조명(IBL)을 테스트하는 예제입니다.",en:"An example testing Image-Based Lighting (IBL)."}},{name:"Custom IBL Texture Size",path:"3d/skybox/ibl/iblTextureSize",description:{ko:"IBL 텍스처의 크기를 사용자 정의하는 예제입니다.",en:"An example of customizing the size of the IBL texture."}},{name:"BRDF LUT Test (Dev Only)",path:"3d/skybox/ibl/brdfLutTest",description:{ko:"새로운 IBL 시스템의 기초인 BRDF LUT 생성을 테스트합니다. (개발 확인용)",en:"Tests BRDF LUT generation, the foundation of the new IBL system. (For development verification)"}},{name:"Irradiance Test (Dev Only)",path:"3d/skybox/ibl/irradianceTest",description:{ko:"분리된 IrradianceGenerator를 사용하여 환경맵으로부터 Irradiance 맵을 생성하고 테스트합니다. (개발 확인용)",en:"Generates and tests an Irradiance map from an environment map using the separated IrradianceGenerator. (For development verification)"}}]},{name:"FrustumCulling",list:[{name:"FrustumCulling",path:"3d/frustumCulling/frustumCulling",description:{ko:"카메라 시야 밖의 객체를 렌더링에서 제외하는 절두체 컬링(Frustum Culling) 기능을 시연합니다.",en:"Demonstrates Frustum Culling, which excludes objects outside the camera view from rendering."}},{name:"DistanceCulling",path:"3d/frustumCulling/distanceCulling",description:{ko:"카메라와의 거리에 따라 객체를 렌더링에서 제외하는 거리 컬링 기능을 시연합니다.",en:"Demonstrates Distance Culling, which excludes objects from rendering based on their distance from the camera."}}]},{name:"SkyAtmosphere",list:[{name:"SkyAtmosphere Basic",path:"3d/skyAtmosphere/skyAtmosphere",description:{ko:"물리 기반 대기 산란 시스템인 SkyAtmosphere의 기본적인 설정과 실시간 태양 광원 연동을 시연합니다.",en:"Demonstrates basic configuration and real-time sun light synchronization of the SkyAtmosphere, a physics-based atmospheric scattering system."}},{name:"Material Scattering (Aerial Perspective)",path:"3d/skyAtmosphere/scatteringTest",description:{ko:"거리에 따른 대기 산란(공중 투시) 효과가 다양한 재질(Color, Phong, PBR 등)에 어떻게 적용되는지 활주로 레이아웃을 통해 직관적으로 비교합니다.",en:"Provides an intuitive comparison of how atmospheric scattering (Aerial Perspective) affects various materials (Color, Phong, PBR, etc.) along a distance runway."}},{name:"Atmosphere & IBL Harmony",path:"3d/skyAtmosphere/gltf",description:{ko:"대기 산란, IBL 환경광, 스카이박스 배경이 유기적으로 조화되어 glTF PBR 모델에 물리적 사실감을 부여하는 통합 환경 시뮬레이션입니다.",en:"An integrated simulation showing how atmospheric scattering, IBL, and skybox work in harmony to provide physical realism to a glTF PBR model."}},{name:"SkyAtmosphere LUT Generator",path:"3d/skyAtmosphere/generator",description:{ko:"대기 산란 계산을 위해 내부적으로 생성되는 투과율, 하늘 뷰 등 다양한 LUT(Look-Up Table) 데이터를 시각화하여 분석합니다.",en:"Visualizes and analyzes various internal LUT (Look-Up Table) data such as Transmittance and SkyView generated for atmospheric scattering calculations."}}]}]},{name:"DrawDebugger",list:[{name:"DrawDebugger",path:"3d/drawDebugger/basic",description:{ko:"렌더링 정보를 디버깅하기 위한 도구를 시연하는 예제입니다.",en:"An example demonstrating tools for debugging rendering information."}}]},{name:"Transparent Sort",list:[{name:"Transparent Sort",path:"3d/transparentSort",description:{ko:"메쉬의 재질에 `transparent` 옵션을 적용하여 반투명 객체가 렌더링되는 순서를 확인하는 예제입니다. `transparent`를 사용하여 올바른 렌더링 결과를 확인할 수 있습니다.",en:" example of how to apply the `transparent` option to the mesh's material to see the order in which translucent objects are rendered. You can use `transparent` to see the correct rendering results."}}]},{name:"Noise Texture",experimental:!0,list:[{name:"SimplexTexture",experimental:!0,list:[{experimental:!0,name:"SimplexTexture",path:"3d/noiseTexture/simplex/basic",description:{ko:"심플렉스 노이즈 텍스처를 생성하고 적용하는 기본 예제입니다.",en:"Basic example of generating and applying Simplex Noise Texture."}},{experimental:!0,name:"Custom SimplexTexture - Fire",path:"3d/noiseTexture/simplex/fire",description:{ko:"심플렉스 노이즈를 활용하여 불꽃 효과를 연출하는 커스텀 텍스처 예제입니다.",en:"Custom texture example creating a fire effect using Simplex Noise."}},{experimental:!0,name:"Custom SimplexTexture - Displacement",path:"3d/noiseTexture/simplex/displacement",description:{ko:"심플렉스 노이즈를 활용하여 변위(Displacement) 효과를 주는 예제입니다.",en:"Example applying displacement effects using Simplex Noise."}}]},{name:"VoronoiTexture",experimental:!0,list:[{experimental:!0,name:"VoronoiTexture",path:"3d/noiseTexture/voronoi/basic",description:{ko:"보로노이 노이즈 텍스처를 생성하고 적용하는 예제입니다.",en:"Example of generating and applying Voronoi Noise Texture."}}]}]},{name:"Sprite3D & SpriteSheet3D",list:[{name:"Sprite3D",path:"3d/sprite/sprite3D",description:{ko:"Sprite3D 객체의 사용법을 보여주는 예제입니다.",en:"example of a Sprite3D object."}},{name:"Sprite3D Comparison (World vs Pixel)",path:"3d/sprite/sprite3DCompare",description:{ko:"Sprite3D의 월드 단위 크기(worldSize)와 고정 픽셀 크기(pixelSize) 설정을 비교 시연하는 예제입니다.",en:"A comparison example demonstrating Sprite3D's world unit size (worldSize) and fixed pixel size (pixelSize) settings."}},{name:"SpriteSheet3D",path:"3d/sprite/spriteSheet3D",description:{ko:"SpriteSheet3D 객체의 사용법을 보여주는 예제입니다.",en:"example of a SpriteSheet3D object."}},{name:"SpriteSheet3D Comparison (World vs Pixel)",path:"3d/sprite/spriteSheet3DCompare",description:{ko:"SpriteSheet3D의 월드 단위 크기(worldSize)와 고정 픽셀 크기(pixelSize) 설정을 비교 시연하는 예제입니다.",en:"A comparison example demonstrating SpriteSheet3D's world unit size (worldSize) and fixed pixel size (pixelSize) settings."}}]},{name:"TextField3D",list:[{name:"TextField3D",path:"3d/textField/textField3D",description:{ko:"TextField3D 객체의 사용법을 보여주는 예제입니다.",en:"example of a TextField3D object."}},{name:"TextField3D Comparison (World vs Pixel)",path:"3d/textField/textField3DCompare",description:{ko:"TextField3D의 월드 단위 크기(worldSize)와 고정 픽셀 크기(usePixelSize) 설정을 비교 시연하는 예제입니다.",en:"A comparison example demonstrating TextField3D's world unit size (worldSize) and fixed pixel size (usePixelSize) settings."}}]},{name:"Light",list:[{name:"DirectionalLight",path:"3d/light/directionalLight",description:{ko:"태양광과 같은 직사광(Directional Light)을 시연하는 예제입니다.",en:"An example demonstrating Directional Light, simulating sunlight."}},{name:"PointLight",path:"3d/light/pointLight",description:{ko:"한 지점에서 모든 방향으로 빛을 방출하는 점광원(Point Light)을 시연하는 예제입니다.",en:"An example demonstrating Point Light, emitting light in all directions from a point."}},{name:"PointLight with glTF",path:"3d/light/pointLightWithGltf",description:{ko:"현대적인 감쇄(Attenuation) 수식이 적용된 Point Light와 glTF PBR 모델의 상호작용 예제입니다.",en:"An example of interaction between Point Light with modern attenuation formula and glTF PBR model."}},{name:"SpotLight",path:"3d/light/spotLight",description:{ko:"특정 방향으로 원뿔형 빛을 방출하는 스포트라이트(Spot Light)를 시연하는 예제입니다.",en:"An example demonstrating Spot Light, cone-shaped light in a specific direction."}},{name:"SpotLight with glTF",path:"3d/light/spotLightWithGltf",description:{ko:"현대적인 원뿔 감쇄(Angle Attenuation) 수식이 적용된 Spot Light와 glTF PBR 모델의 상호작용 예제입니다.",en:"An example of interaction between Spot Light with modern angle attenuation formula and glTF PBR model."}},{name:"PointLight Performance(cluster)",path:"3d/light/pointLightPerformance",description:{ko:"PointLight는 클러스터 타일 렌더링을 지원합니다. 1024개의 포인트 라이트를 지원합니다.",en:"PointLight supports clustered tile rendering. Supports 1024 point lights."}},{name:"SpotLight Performance(cluster)",path:"3d/light/spotLightPerformance",description:{ko:"SpotLight의 대량 렌더링 성능(클러스터링)을 테스트하는 예제입니다.",en:"An example testing the mass rendering performance (clustering) of SpotLights."}}]},{name:"Group3D",list:[{name:"Basic Group3D",path:"3d/group3D/basic",description:{ko:"3D 객체들을 그룹화할 수 있는 Group3D 객체의 예제입니다.",en:"Here's an example of a Group3D object that can group 3D objects."}}]},{name:"Tint",experimental:!0,list:[{experimental:!0,name:"Tint",path:"3d/tint/basic",description:{ko:"재질 기반 틴트를 지원합니다. 틴트 사용, tintBlendMode 설정 및 색상 사용 예제입니다.",en:"Supports material-based tint. Examples of using tint, setting tintBlendMode, and color."}}]},{name:"Line3D",experimental:!0,list:[{experimental:!0,name:"Linear Type",path:"3d/line3D/linear",description:{ko:"직선 형태의 라인을 그리는 예제입니다.",en:"An example of drawing linear lines."}},{experimental:!0,name:"Bezier Type",path:"3d/line3D/bezier",description:{ko:"베지에 곡선 형태의 라인을 그리는 예제입니다.",en:"An example of drawing Bezier curve lines."}},{experimental:!0,name:"CatmullRom Type",path:"3d/line3D/catmullRom",description:{ko:"캣멀-롬 스플라인 형태의 라인을 그리는 예제입니다.",en:"An example of drawing Catmull-Rom spline lines."}}]},{name:"Interaction",list:[{name:"MouseEvent",list:[{name:"Mesh",path:"3d/interaction/mouseEvent/mesh",description:{ko:"Mesh에 마우스 이벤트를 설정하는 예제입니다.",en:"Here's an example of setting up mouse events on a Mesh."}},{name:"Sprite3D",path:"3d/interaction/mouseEvent/sprite3D",description:{ko:"Sprite3D에 마우스 이벤트를 설정하는 예제입니다.",en:"Here's an example of setting up mouse events on a Sprite3D."}},{name:"SpriteSheet3D",path:"3d/interaction/mouseEvent/spriteSheet3D",description:{ko:"SpriteSheet3D에 마우스 이벤트를 설정하는 예제입니다.",en:"Here's an example of setting up mouse events on a SpriteSheet3D."}},{name:"TextField3D",path:"3d/interaction/mouseEvent/textField3D",description:{ko:"TextField3D에 마우스 이벤트를 설정하는 예제입니다.",en:"Here's an example of setting up mouse events on a TextField3D."}},{name:"Raycasting (Precision Picking)",path:"3d/interaction/mouseEvent/raycasting",description:{ko:"이 예제는 복잡한 지오메트리(TorusKnot)에 대한 고정밀 레이캐스팅을 보여줍니다.
버텍스 버퍼를 분석하여 정확한 교차 지점, 면 인덱스 및 로컬 좌표를 CPU에서 계산합니다.",en:"This example demonstrates high-precision raycasting on complex geometry (TorusKnot).
It calculates the exact intersection point, face index, and local coordinates on the CPU by analyzing vertex buffers."}}]},{name:"KeyboardEvent",list:[{name:"Keyboard Interaction",path:"3d/interaction/keyboardEvent",description:{ko:"keyboardKeyBuffer를 사용하여 매 프레임 키보드 상태를 체크하고 객체를 제어하는 기초적인 방법을 보여줍니다.",en:"Shows basic way to check keyboard state every frame and control an object using keyboardKeyBuffer."}}]}]},{name:"Shadow",list:[{name:"DirectionalLight Shadow",path:"3d/shadow/directionalShadow",description:{ko:"DirectionalLight에 의한 그림자 효과를 시연하는 예제입니다.",en:"An example demonstrating shadow effects caused by DirectionalLight."}},{name:"DirectionalLight Shadow - GLTF",path:"3d/shadow/gltfDirectionalShadow",description:{ko:"GLTF 모델에 대한 DirectionalLight 그림자 효과를 시연하는 예제입니다.",en:"An example demonstrating DirectionalLight shadow effects on a GLTF model."}}]},{name:"InstancedMesh",list:[{name:"InstancedMesh Simple",path:"3d/instancedMesh/simple",description:{ko:"이 데모는 간단한 Plane을 사용한 인스턴스 성능 테스트를 보여줍니다. ",en:"This demo demonstrates instance performance testing using a simple Plane. "}},{name:"InstancedMesh Sphere",path:"3d/instancedMesh/sphere",description:{ko:"이 데모는 Sphere를 사용한 인스턴스 성능 테스트를 보여줍니다. ",en:"This demo demonstrates instance performance testing using Sphere. "}}]},{name:"LOD",list:[{name:"InstancedMesh GPU LOD",path:"3d/lod/InstanceMeshGPULOD",description:{ko:"InstancedMesh에 GPU 기반 LOD를 적용하여 수만 개의 객체를 효율적으로 최적화하는 성능을 시연합니다.",en:"Demonstrates efficient optimization of tens of thousands of objects by applying GPU-based LOD to InstancedMesh."}},{name:"InstancedMesh Multi-Material GPU LOD",path:"3d/lod/InstanceMeshGPULOD_material",description:{ko:"인스턴싱 메시에서 거리에 따라 지오메트리와 머티리얼을 동시에 변경하는 GPU 기반 LOD 기능을 보여줍니다.",en:"Shows GPU-based LOD functionality that simultaneously changes geometry and materials by distance in instanced meshes."}},{name:"Mesh CPU LOD",path:"3d/lod/MeshCPULOD",description:{ko:"수천 개의 개별 Mesh 객체들에 CPU 기반 LOD를 적용하여 거리별 최적화 성능을 테스트합니다.",en:"Tests distance-based optimization performance by applying CPU-based LOD to thousands of individual Mesh objects."}},{name:"Mesh Multi-Material CPU LOD",path:"3d/lod/MeshCPULOD_material",description:{ko:"개별 메시 객체들에 대해 거리에 따라 지오메트리와 머티리얼이 함께 변화하는 CPU 기반 LOD를 시연합니다.",en:"Demonstrates CPU-based LOD where both geometry and materials change together by distance for individual mesh objects."}}]},{name:"ParticleSystem",list:[{name:"Particle",path:"3d/particle/basic",description:{ko:"기본적인 파티클 시스템을 시연하는 예제입니다.",en:"An example demonstrating a basic particle system."}},{name:"Multi Particle Performance",path:"3d/particle/performance",description:{ko:"다수의 파티클 시스템을 동시에 렌더링하여 성능을 테스트하는 예제입니다.",en:"An example testing performance by rendering multiple particle systems simultaneously."}}]},{name:"Indirect Draw Test",list:[{name:"drawIndexedIndirect Test",path:"3d/indirectDrawTest",description:{ko:"drawIndexedIndirect 기능을 테스트하는 예제입니다.",en:"An example testing the drawIndexedIndirect function."}}]}]},{name:"GLTF",list:[{name:"Basic",list:[{name:"TextureEncodingTest",path:"gltf/basic/textureEncodingTest",description:{ko:"텍스처가 올바른 전달 함수(Transfer Function)로 샘플링되는지 테스트합니다. Base Color와 Emissive가 sRGB에서 올바르게 디코딩되는지 확인합니다.",en:"Tests that textures are sampled with the correct transfer functions. Verifies base color and emissive textures are decoded from sRGB."}},{name:"TextureLinear InterpolationTest",path:"gltf/basic/textureLinearInterpolationTest",description:{ko:"sRGB 디코딩 후 선형 값에 대해 텍스처 선형 보간이 올바르게 수행되는지 테스트합니다.",en:"Tests that linear texture interpolation is correctly performed on linear values (after sRGB decoding)."}},{name:"VertexColorTest",path:"gltf/basic/vertexColorTest",description:{ko:"뷰어가 정점 색상(COLORS_0 속성)을 올바르게 지원하는지 테스트합니다.",en:"Tests proper support for vertex colors (COLORS_0 attribute) in the viewer."}},{name:"BoxVertexColors",path:"gltf/basic/boxVertexColors",description:{ko:"각 면에 정점 색상이 적용된 간단한 박스 모델입니다.",en:"A simple box model with vertex colors applied to each face."}},{name:"OrientationTest",path:"gltf/basic/orientationTest",description:{ko:"노드의 회전 및 방향(Quaternion) 처리가 올바른지 테스트합니다.",en:"Tests the correctness of node rotation and orientation (Quaternion) handling."}},{name:"TextureCoordinateTest",path:"gltf/basic/textureCoordinateTest",description:{ko:"XYZ 위치(3D 공간 좌표)와 UV 위치(2D 텍스처 좌표) 간의 관계를 보여줍니다.",en:"Demonstrates the relationship between XYZ positions and UV texture coordinates."}},{name:"AlphaBlendModeTest",path:"gltf/basic/alphaBlendModeTest",description:{ko:"다양한 알파 모드(OPAQUE, BLEND, MASK)가 올바르게 렌더링되는지 테스트합니다.",en:"Tests the various alpha modes (OPAQUE, BLEND, MASK) to verify correct rendering."}},{name:"TextureSettingsTest",path:"gltf/basic/textureSettingsTest",description:{ko:"텍스처 샘플링 설정(Wrap 모드, 필터링)을 테스트합니다.",en:"Tests texture sampling settings (Wrap modes, Filtering)."}},{name:"MultiUVTest",path:"gltf/basic/multiUVTest",description:{ko:"다중 텍스처 좌표 속성(예: 색상용 TEXCOORD_0, 기타 요소용 TEXCOORD_1)의 사용을 시연합니다.",en:"Demonstrates the usage of multiple texture coordinate attributes (e.g., TEXCOORD_0 for color, TEXCOORD_1 for other elements)."}},{name:"MetalRoughSpheres",path:"gltf/basic/metalRoughSpheres",description:{ko:"다양한 금속성(Metallic)과 거칠기(Roughness) 값을 가진 구체들을 통해 PBR 렌더링을 테스트합니다.",en:"Tests PBR rendering via spheres with varying Metallic and Roughness values."}},{name:"MetalRoughSpheresNoTextures",path:"gltf/basic/metalRoughSpheresNoTextures",description:{ko:"텍스처 없이 재질의 요소(Factor) 값만으로 금속성과 거칠기를 표현하는 테스트입니다.",en:"Tests representing metallic and roughness using only material factor values without textures."}},{name:"WaterBottle",path:"gltf/basic/waterBottle",description:{ko:"Normal, Occlusion, Emissive 맵을 사용하는 기본적인 금속/거칠기(Metal/Roughness) PBR 물병 모델입니다.",en:"A basic Metal/Roughness PBR water bottle model using Normal, Occlusion, and Emissive maps."}},{name:"NormalTangentTest",path:"gltf/basic/normalTangentTest",description:{ko:"노멀 맵핑과 탄젠트 공간 계산의 정확성을 테스트합니다.",en:"Tests the accuracy of normal mapping and tangent space calculations."}},{name:"NormalTangentMirrorTest",path:"gltf/basic/normalTangentMirrorTest",description:{ko:"미러링된 텍스처 좌표에서의 노멀 맵핑 처리를 테스트합니다.",en:"Tests normal mapping handling with mirrored texture coordinates."}},{name:"NegativeScaleTest",path:"gltf/basic/negativeScaleTest",description:{ko:"음수 스케일(반전)이 적용된 노드의 렌더링을 테스트합니다.",en:"Tests rendering of nodes with negative scale (inversion) applied."}},{name:"EnvironmentTest",path:"gltf/basic/environmentTest",description:{ko:"금속 표면에서의 환경 맵 반사 효과를 테스트합니다.",en:"Tests environment map reflection effects on metallic surfaces."}},{name:"Generate normal vector test",path:"gltf/basic/generateNormalTest",description:{ko:"모델에 노멀 정보가 없을 때 자동으로 노멀 벡터를 생성하는 기능을 테스트합니다.",en:"Tests the automatic generation of normal vectors when the model lacks normal information."}}]},{name:"Basic Compare",list:[{name:"CompareBaseColor",path:"gltf/basic/compareBaseColor",description:{ko:"기본 색상(Base Color) 렌더링 결과를 비교합니다.",en:"Compares Base Color rendering results."}},{name:"CompareAlphaCoverage",path:"gltf/basic/compareAlphaCoverage",description:{ko:"알파 커버리지(Alpha Coverage) 렌더링 결과를 비교합니다.",en:"Compares Alpha Coverage rendering results."}},{name:"CompareMetallic",path:"gltf/basic/compareMetallic",description:{ko:"금속성(Metallic) 렌더링 결과를 비교합니다.",en:"Compares Metallic rendering results."}},{name:"CompareNormal",path:"gltf/basic/compareNormal",description:{ko:"노멀 맵(Normal Map) 렌더링 결과를 비교합니다.",en:"Compares Normal Map rendering results."}},{name:"CompareRoughness",path:"gltf/basic/compareRoughness",description:{ko:"거칠기(Roughness) 렌더링 결과를 비교합니다.",en:"Compares Roughness rendering results."}},{name:"CompareAmbientOcclusion",path:"gltf/basic/compareAmbientOcclusion",description:{ko:"앰비언트 오클루전(AO) 렌더링 결과를 비교합니다.",en:"Compares Ambient Occlusion (AO) rendering results."}}]},{name:"Animation",list:[{name:"Basic Animations",path:"gltf/animation/basicAnimations",description:{ko:"노드의 이동, 회전, 크기 조절 애니메이션을 보여주는 기본 예제입니다.",en:"Basic example showing node translation, rotation, and scaling animations."}},{name:"SimpleSkin",path:"gltf/animation/simpleSkin",description:{ko:"가장 기본적인 형태의 스키닝(Skinning) 애니메이션 예제입니다.",en:"The most basic example of skinning animation."}},{name:"SimpleMorph",path:"gltf/animation/simpleMorph",description:{ko:"간단한 모프 타겟(Morph Target) 애니메이션 예제입니다.",en:"Simple Morph Target animation example."}},{name:"RiggedSimple",path:"gltf/animation/riggedSimple",description:{ko:"간단하게 리깅된 원통형 메쉬를 통해 스키닝 동작을 확인합니다.",en:"Verifies skinning behavior via a simply rigged cylindrical mesh."}},{name:"RiggedFigure",path:"gltf/animation/riggedFigure",description:{ko:"리깅된 인간형 캐릭터 모델의 애니메이션을 테스트합니다.",en:"Tests animation of a rigged humanoid character model."}},{name:"InterpolationTest",path:"gltf/animation/interpolationTest",description:{ko:"애니메이션 보간 모드(Step, Linear, Cubic Spline)의 차이를 보여줍니다.",en:"Demonstrates the differences between animation interpolation modes (Step, Linear, Cubic Spline)."}},{name:"CesiumMan & MilkTruck",path:"gltf/animation/cesiumMan",description:{ko:"스키닝된 CesiumMan과 애니메이션이 적용된 우유 트럭 모델입니다.",en:"Skinned CesiumMan and animated Milk Truck models."}},{name:"BrainStem",path:"gltf/animation/brainStem",description:{ko:"복잡한 계층 구조와 스키닝을 가진 BrainStem 모델 애니메이션입니다.",en:"BrainStem model animation with complex hierarchy and skinning."}},{name:"MorphStressTest",path:"gltf/animation/morphStressTest",description:{ko:"다수의 활성 정점 속성(최대 18개)을 사용하여 모프 타겟 구현을 스트레스 테스트합니다.",en:"Stress-tests morph target implementations with a high number of active vertex attributes (up to 18)."}},{name:"RecursiveSkeletons",path:"gltf/animation/recursiveSkeletons",description:{ko:"복잡한 스키닝 케이스(다른 스킨으로 메쉬 재사용, 단일 스켈레톤에 다중 스킨 바인딩)를 테스트합니다.",en:"Tests complex skinning cases: reusing meshes with different skins and binding multiple skins to a single skeleton."}},{name:"Animation Performance Test",list:[{name:"Medium load Skinning",path:"gltf/animation/performance/mediumLoadSkinning",description:{ko:"19개의 관절과 57개의 애니메이션 채널을 가진 다수의 모델을 계산하는 성능 데모입니다.",en:"This is a performance demo that computes a large number of models with 19 joints and 57 animation channels."}},{name:"High vertex load Skinning",path:"gltf/animation/performance/highVertexLoadSkinning",description:{ko:"많은 정점과 관절을 가진 모델에 대한 스키닝 성능을 측정하는 테스트를 수행합니다. 각 장치의 성능 한계를 확인하기 위해 FPS와 GPU/CPU 사용량을 모니터링합니다.",en:"perform tests to measure skinning performance for models with many vertices and joints. We monitor FPS and GPU/CPU utilization to determine performance limits for each device."}},{name:"Morph target load Test",path:"gltf/animation/performance/highMorphTarget",description:{ko:"수백 개의 MorphStressTest 모델을 인스턴스화하여 모프 스트레스 테스트를 수행합니다.
\n실시간 모프 타겟 스키닝 성능을 극한까지 벤치마킹합니다. 세 가지 애니메이션 중 가장 무거운 모프 타겟 애니메이션의 성능을 테스트합니다.
\n각 장치의 성능 한계를 확인하세요.",en:"Perform morph stress tests by instantiating hundreds of MorphStressTest models.
\nBenchmark real-time morph target skinning performance to the limit. Test the performance of the heaviest of the three animations, the morph target animation.
\nCheck performance limits on each device."}}]}]},{name:"3D Models",list:[{name:"corset",path:"gltf/models/corset",description:{ko:"복잡한 형상과 텍스처를 가진 고해상도 코르셋 모델입니다.",en:"High-resolution Corset model with complex geometry and textures."}},{name:"Helmets",path:"gltf/models/helmets",description:{ko:"손상된 헬멧(Damaged Helmet) 등 고품질 PBR 텍스처를 보여주는 모델들입니다.",en:"Models showcasing high-quality PBR textures, such as the Damaged Helmet."}},{name:"Sponza",path:"gltf/models/sponza",description:{ko:"조명 테스트에 널리 사용되는 건물 내부 모델입니다. 현대적인 PBR 파이프라인을 위해 고해상도 지오메트리로 리메이크되었습니다.",en:"Building interior commonly used for testing lighting. Remade for modern PBR pipelines with high-resolution geometry."}},{name:"Tokyo",path:"gltf/models/tokyo",description:{ko:"수많은 드로우 콜과 대규모 씬 렌더링을 테스트하는 도쿄 도시 모델입니다.",en:"Tokyo city model testing large-scale scene rendering and numerous draw calls."}},{name:"texcooredNTest",path:"gltf/models/texcooredNTest",description:{ko:"다중 텍스처 좌표 채널의 동작을 확인하는 테스트 모델입니다.",en:"Test model verifying the behavior of multiple texture coordinate channels."}},{name:"ABeautifulGame",path:"gltf/models/aBeautifulGame",extensionList:["KHR_materials_transmission","KHR_materials_volume"],description:{ko:"투과(Transmission)와 볼륨(Volume) 효과를 시연하는 체스 세트입니다.",en:"A chess set demonstrating transmission and volume."}}]},{name:"GLTF Extensions",list:[{name:"KHR_materials_anisotropy",list:[{name:"CompareAnisotropy",path:"gltf/gltfExtensions/anisotropy/compareAnisotropy",extensionList:["KHR_materials_anisotropy"],description:{ko:"비등방성(Anisotropy)이 있는 렌더링과 없는 렌더링을 비교합니다.",en:"Compares rendering with and without anisotropy."}},{name:"AnisotropyDiscTest",path:"gltf/gltfExtensions/anisotropy/anisotropyDiscTest",extensionList:["KHR_materials_anisotropy"],description:{ko:"원판 형태의 비등방성 하이라이트 회전을 테스트합니다.",en:"Tests anisotropic highlight rotation on a disc shape."}},{name:"AnisotropyRotationTest",path:"gltf/gltfExtensions/anisotropy/anisotropyRotationTest",extensionList:["KHR_materials_anisotropy"],description:{ko:"비등방성 방향 회전에 따른 렌더링 변화를 테스트합니다.",en:"Tests rendering changes based on anisotropy direction rotation."}},{name:"AnisotropyStrengthTest",path:"gltf/gltfExtensions/anisotropy/anisotropyStrengthTest",extensionList:["KHR_materials_anisotropy"],description:{ko:"비등방성 강도(Strength)에 따른 하이라이트 변화를 테스트합니다.",en:"Tests highlight changes based on anisotropy strength."}},{name:"AnisotropyBarnLamp",path:"gltf/gltfExtensions/anisotropy/anisotropyBarnLamp",extensionList:["KHR_materials_anisotropy"],description:{ko:"비등방성(Anisotropic) 재질 속성을 보여주는 헛간 램프 모델입니다.",en:"A barn lamp model showcasing anisotropic material properties."}}]},{name:"KHR_materials_iridescence",list:[{name:"CompareIridescence",path:"gltf/gltfExtensions/iridescence/compareIridescence",extensionList:["KHR_materials_iridescence"],description:{ko:"무지개빛(Iridescence) 박막 간섭 효과를 비교합니다.",en:"Compares Iridescence thin-film interference effects."}},{name:"IridescenceDielectricSpheres",path:"gltf/gltfExtensions/iridescence/iridescenceDielectricSpheres",extensionList:["KHR_materials_iridescence","KHR_materials_transmission","KHR_materials_volume"],description:{ko:"비금속(유전체) 재질에서 KHR_materials_iridescence 확장을 테스트합니다.",en:"Tests the KHR_materials_iridescence extension on non-metallic (dielectric) materials."}},{name:"IridescenceMetallicSpheres",path:"gltf/gltfExtensions/iridescence/iridescenceMetallicSpheres",extensionList:["KHR_materials_iridescence"],description:{ko:"금속 구체에 적용된 무지개빛 효과를 테스트합니다.",en:"Tests iridescence effects applied to metallic spheres."}},{name:"IridescenceSuzanne",path:"gltf/gltfExtensions/iridescence/iridescenceSuzanne",extensionList:["KHR_materials_iridescence"],description:{ko:"Suzanne 모델에 적용된 무지개빛 쉐이더 테스트입니다.",en:"Iridescence shader test applied to the Suzanne model."}},{name:"IridescenceLamp",path:"gltf/gltfExtensions/iridescence/iridescenceLamp",extensionList:["KHR_materials_iridescence","KHR_materials_transmission","KHR_materials_volume"],description:{ko:"투과 및 볼륨 효과와 함께 KHR_materials_iridescence를 보여주는 Wayfair 램프 모델입니다.",en:"A Wayfair lamp model showcasing transmission, volume, and KHR_materials_iridescence."}},{name:"SunglassesKhronos",path:"gltf/gltfExtensions/iridescence/sunglassesKhronos",extensionList:["KHR_materials_iridescence","KHR_materials_transmission"],description:{ko:"렌즈에 얇은 막 무지개빛 효과가 적용된 선글라스 모델입니다.",en:"Sunglasses model with thin-film iridescence effects applied to the lenses."}},{name:"IridescentDishWithOlives",path:"gltf/gltfExtensions/iridescence/iridescentDishWithOlives",extensionList:["KHR_materials_iridescence","KHR_materials_transmission","KHR_materials_volume","KHR_materials_ior","KHR_materials_specular"],description:{ko:"투과, 볼륨, IOR 및 스펙큘러 속성을 보여주는 접시 모델입니다.",en:"A dish demonstrating transmission, volume, IOR, and specular properties."}}]},{name:"KHR_materials_clearcoat",list:[{name:"CompareClearcoat",path:"gltf/gltfExtensions/clearcoat/compareClearcoat",extensionList:["KHR_materials_clearcoat"],description:{ko:"클리어코트(Clearcoat) 재질 렌더링 결과를 비교합니다.",en:"Compares Clearcoat material rendering results."}},{name:"ClearCoatTest",path:"gltf/gltfExtensions/clearcoat/clearCoatTest",extensionList:["KHR_materials_clearcoat"],description:{ko:"다양한 거칠기와 클리어코트 강도를 테스트합니다.",en:"Tests various roughness and clearcoat strengths."}},{name:"ClearcoatWicker",path:"gltf/gltfExtensions/clearcoat/clearcoatWicker",extensionList:["KHR_materials_clearcoat"],description:{ko:"직물 표면 위에 코팅된 클리어코트 효과를 보여주는 위커 모델입니다.",en:"Wicker model showing clearcoat effect coated over a woven surface."}},{name:"ClearCoatCarPaint",path:"gltf/gltfExtensions/clearcoat/clearCoatCarPaint",extensionList:["KHR_materials_clearcoat"],description:{ko:"자동차 페인트와 같은 다중 레이어 재질 표현을 테스트합니다.",en:"Tests multi-layer material representation like car paint."}}]},{name:"KHR_materials_dispersion",list:[{name:"CompareDispersion",path:"gltf/gltfExtensions/dispersion/compareDispersion",extensionList:["KHR_materials_dispersion","KHR_materials_transmission"],description:{ko:"빛의 분산(Dispersion) 효과를 비교합니다.",en:"Compares light dispersion effects."}},{name:"DispersionTest",path:"gltf/gltfExtensions/dispersion/dispersionTest",extensionList:["KHR_materials_dispersion","KHR_materials_transmission"],description:{ko:"프리즘과 같은 빛의 분산 현상을 테스트합니다.",en:"Tests light dispersion phenomena like a prism."}},{name:"DragonDispersion",path:"gltf/gltfExtensions/dispersion/dragonDispersion",extensionList:["KHR_materials_dispersion","KHR_materials_transmission","KHR_materials_volume"],description:{ko:"용 모델에 적용된 보석 같은 분산 효과를 보여줍니다.",en:"Shows gem-like dispersion effects applied to a Dragon model."}}]},{name:"KHR_materials_emissive_strength",list:[{name:"CompareEmissiveStrength",path:"gltf/gltfExtensions/emissiveStrength/compareEmissiveStrength",extensionList:["KHR_materials_emissive_strength"],description:{ko:"발광(Emissive) 강도 증폭 효과를 비교합니다.",en:"Compares Emissive Strength amplification effects."}},{name:"EmissiveStrengthTest",path:"gltf/gltfExtensions/emissiveStrength/emissiveStrengthTest",extensionList:["KHR_materials_emissive_strength"],description:{ko:"1.0을 초과하는 고강도 발광 표현을 테스트합니다.",en:"Tests high-intensity emissive representation exceeding 1.0."}}]},{name:"KHR_materials_sheen",list:[{name:"CompareSheen",path:"gltf/gltfExtensions/sheen/compareSheen",extensionList:["KHR_materials_sheen"],description:{ko:"직물 등의 미세한 반사광(Sheen) 효과를 비교합니다.",en:"Compares Sheen effects seen on fabrics etc."}},{name:"SheenTestGrid",path:"gltf/gltfExtensions/sheen/sheenTestGrid",extensionList:["KHR_materials_sheen"],description:{ko:"Sheen 색상과 거칠기에 따른 변화를 그리드로 테스트합니다.",en:"Tests changes based on Sheen color and roughness in a grid."}},{name:"SheenCloth",path:"gltf/gltfExtensions/sheen/sheenCloth",extensionList:["KHR_materials_sheen"],description:{ko:"Sheen 효과를 보여주는 직물 예제입니다.",en:"A fabric example showcasing sheen."}},{name:"SheenChair",path:"gltf/gltfExtensions/sheen/sheenChair",extensionList:["KHR_materials_sheen","KHR_materials_variants"],description:{ko:"재질 변형(Variant)과 Sheen 효과를 보여주는 의자 모델입니다.",en:"A chair model demonstrating material variants and sheen."}},{name:"GlamVelvetSofa",path:"gltf/gltfExtensions/sheen/glamVelvetSofa",extensionList:["KHR_materials_sheen","KHR_materials_specular","KHR_materials_variants"],description:{ko:"고급 벨벳 소파의 질감을 표현하는 Sheen 모델입니다.",en:"Sheen model expressing the texture of a luxury velvet sofa."}},{name:"ChairDamaskPurplegold",path:"gltf/gltfExtensions/sheen/chairDamaskPurplegold",extensionList:["KHR_materials_sheen"],description:{ko:"다마스크 패턴 의자의 직물 느낌을 표현합니다.",en:"Expresses the fabric feel of a damask pattern chair."}},{name:"SheenWoodLeatherSofa",path:"gltf/gltfExtensions/sheen/sheenWoodLeatherSofa",extensionList:["KHR_materials_sheen"],description:{ko:"가죽과 나무 재질이 혼합된 소파에서의 Sheen 효과입니다.",en:"Sheen effect on a sofa combining leather and wood materials."}}]},{name:"KHR_materials_specular",list:[{name:"CompareSpecular",path:"gltf/gltfExtensions/specular/compareSpecular",extensionList:["KHR_materials_specular"],description:{ko:"스펙큘러(Specular) 반사 강도 및 색상 제어를 비교합니다.",en:"Compares Specular reflection strength and color control."}},{name:"SpecularTest",path:"gltf/gltfExtensions/specular/specularTest",extensionList:["KHR_materials_specular"],description:{ko:"유전체 재질의 스펙큘러 하이라이트 조절을 테스트합니다.",en:"Tests specular highlight adjustments on dielectric materials."}},{name:"SpecularSilkPouf",path:"gltf/gltfExtensions/specular/specularSilkPouf",extensionList:["KHR_materials_specular"],description:{ko:"스펙큘러 속성을 보여주는 실크 푸프 모델입니다.",en:"A silk pouf model demonstrating specular properties."}}]},{name:"KHR_materials_unlit",list:[{name:"UnlitTest",path:"gltf/gltfExtensions/unlit/unlitTest",extensionList:["KHR_materials_unlit"],description:{ko:"조명의 영향을 받지 않는 Unlit(무광) 재질을 테스트합니다.",en:"Tests Unlit materials not affected by lighting."}}]},{name:"KHR_texture_transform",list:[{name:"TextureTransformTest",path:"gltf/gltfExtensions/textureTransform/textureTransformTest",extensionList:["KHR_texture_transform"],description:{ko:"KHR_texture_transform 확장의 사용법(스케일, 회전, 이동)을 시연합니다.",en:"Demonstrates the usage of the KHR_texture_transform extension (scaling, rotation, translation)."}},{name:"TextureTransformMultiTest",path:"gltf/gltfExtensions/textureTransform/textureTransformMultiTest",extensionList:["KHR_texture_transform"],description:{ko:"여러 텍스처에 서로 다른 변환을 적용하는 테스트입니다.",en:"Tests applying different transforms to multiple textures."}}]},{name:"KHR_materials_diffuseTransmission",list:[{name:"DiffuseTransmissionTest",path:"gltf/gltfExtensions/diffuseTransmission/diffuseTransmissionTest",extensionList:["KHR_materials_diffuseTransmission"],description:{ko:"반투명한 물체의 확산 투과(Diffuse Transmission) 효과를 테스트합니다.",en:"Tests Diffuse Transmission effects on translucent objects."}},{name:"DiffuseTransmissionTeacup",path:"gltf/gltfExtensions/diffuseTransmission/diffuseTransmissionTeacup",extensionList:["KHR_materials_diffuseTransmission"],description:{ko:"얇은 찻잔을 통과하는 빛의 확산을 보여줍니다.",en:"Shows light diffusion passing through a thin teacup."}}]},{name:"KHR_materials_transmission",list:[{name:"CompareTransmission",path:"gltf/gltfExtensions/transmission/compareTransmission",extensionList:["KHR_materials_transmission"],description:{ko:"투명한 물체의 투과(Transmission) 렌더링을 비교합니다.",en:"Compares Transmission rendering of transparent objects."}},{name:"TransmissionTest",path:"gltf/gltfExtensions/transmission/transmissionTest",extensionList:["KHR_materials_transmission","KHR_materials_ior"],description:{ko:"다양한 투과율과 거칠기에 따른 굴절 효과를 테스트합니다.",en:"Tests refraction effects based on various transmission rates and roughness."}},{name:"TransmissionRoughnessTest",path:"gltf/gltfExtensions/transmission/transmissionRoughnessTest",extensionList:["KHR_materials_transmission"],description:{ko:"거친 표면을 가진 투명 재질의 흐림 효과를 테스트합니다.",en:"Tests blurring effects on transparent materials with rough surfaces."}},{name:"StainedGlassLamp",path:"gltf/gltfExtensions/transmission/stainedGlassLamp",extensionList:["KHR_materials_transmission"],description:{ko:"스테인드글라스 램프를 통해 색상이 있는 투과광을 보여줍니다.",en:"Shows colored transmitted light through a stained glass lamp."}},{name:"ChronographWatch",path:"gltf/gltfExtensions/transmission/chronographWatch",extensionList:["KHR_materials_transmission","KHR_materials_variants"],description:{ko:"시계 유리의 투명도와 내부 디테일을 보여주는 고품질 모델입니다.",en:"High-quality model showing watch glass transparency and internal details."}},{name:"MosquitoInAmber",path:"gltf/gltfExtensions/transmission/mosquitoInAmber",extensionList:["KHR_materials_transmission","KHR_materials_volume","KHR_materials_ior"],description:{ko:"호박(Amber) 속에 갇힌 모기를 통해 투과, 굴절률(IOR), 볼륨 속성을 시연합니다.",en:"A mosquito encased in amber, demonstrating the use of transmission, IOR, and volume properties."}},{name:"CommercialRefrigerator",path:"gltf/gltfExtensions/transmission/commercialRefrigerator",extensionList:["KHR_materials_transmission"],description:{ko:"유리 문을 가진 상업용 냉장고 모델입니다.",en:"Commercial refrigerator model with glass doors."}}]},{name:"KHR_materials_volume",list:[{name:"CompareIor",path:"gltf/gltfExtensions/volume/compareIor",extensionList:["KHR_materials_ior"],description:{ko:"굴절률(IOR)에 따른 빛의 굴절 차이를 비교합니다.",en:"Compares light refraction differences based on Index of Refraction (IOR)."}},{name:"IORTestGrid",path:"gltf/gltfExtensions/volume/IORTestGrid",extensionList:["KHR_materials_ior"],description:{ko:"다양한 IOR 값에 따른 굴절 변화를 그리드로 테스트합니다.",en:"Tests refraction changes based on various IOR values in a grid."}},{name:"CompareVolume",path:"gltf/gltfExtensions/volume/compareVolume",extensionList:["KHR_materials_volume"],description:{ko:"볼륨(Volume) 흡수 및 산란 효과를 비교합니다.",en:"Compares Volume absorption and scattering effects."}},{name:"TransmissionThinwallTestGrid",path:"gltf/gltfExtensions/volume/transmissionThinwallTestGrid",extensionList:["KHR_materials_transmission","KHR_materials_volume"],description:{ko:"얇은 벽(Thin-walled) 옵션 활성화 여부에 따른 투과 차이를 테스트합니다.",en:"Tests transmission differences based on Thin-walled option activation."}},{name:"AttenuationTest",path:"gltf/gltfExtensions/volume/attenuationTest",extensionList:["KHR_materials_volume"],description:{ko:"빛이 매질을 통과할 때의 감쇠(Attenuation) 거리와 색상을 테스트합니다.",en:"Tests attenuation distance and color as light passes through a medium."}},{name:"GlassVaseFlowers",path:"gltf/gltfExtensions/volume/glassVaseFlowers",extensionList:["KHR_materials_transmission","KHR_materials_volume","KHR_materials_ior"],description:{ko:"유리 꽃병과 물의 볼륨 효과를 보여주는 모델입니다.",en:"Model showing volume effects of a glass vase and water."}},{name:"GlassBrokenWindow",path:"gltf/gltfExtensions/volume/glassBrokenWindow",extensionList:["KHR_materials_transmission","KHR_materials_volume","KHR_materials_ior"],description:{ko:"깨진 유리창의 두께감과 굴절을 표현합니다.",en:"Expresses the thickness and refraction of a broken window."}},{name:"GlassHurricaneCandleHolder",path:"gltf/gltfExtensions/volume/glassHurricaneCandleHolder",extensionList:["KHR_materials_transmission","KHR_materials_volume","KHR_materials_ior"],description:{ko:"복잡한 유리 형태의 굴절과 반사를 보여주는 캔들 홀더입니다.",en:"Candle holder showing refraction and reflection of complex glass shapes."}},{name:"DragonAttenuation",path:"gltf/gltfExtensions/volume/dragonAttenuation",extensionList:["KHR_materials_transmission","KHR_materials_volume"],description:{ko:"KHR_materials_transmission과 KHR_materials_volume을 사용하여 색유리와 같은 객체를 표현합니다.",en:"Showcases KHR_materials_transmission and KHR_materials_volume, creating an object that resembles colored glass."}}]}]}]},{name:"PostEffect",list:[{name:"Convolution",path:"postEffect/convolution",description:{ko:"컨볼루션 필터 효과를 시연하는 예제입니다.",en:"An example demonstrating convolution filter effects."}},{name:"FilmGrain",path:"postEffect/filmGrain",description:{ko:"필름 그레인 효과를 시연하는 예제입니다.",en:"An example demonstrating film grain effects."}},{name:"OldBloom",path:"postEffect/oldBloom",description:{ko:"고전적인 블룸 효과를 시연하는 예제입니다.",en:"An example demonstrating classic bloom effects."}},{name:"Sharpen",path:"postEffect/sharpen",description:{ko:"선명도(Sharpen) 효과를 시연하는 예제입니다.",en:"An example demonstrating sharpen effects."}},{name:"Adjustments",list:[{name:"Grayscale",path:"postEffect/adjustments/grayscale",description:{ko:"그레이스케일 색상 보정 효과 예제입니다.",en:"Example of Grayscale color adjustment effect."}},{name:"Invert",path:"postEffect/adjustments/invert",description:{ko:"색상 반전 효과 예제입니다.",en:"Example of Invert color adjustment effect."}},{name:"ColorBalance",path:"postEffect/adjustments/colorBalance",description:{ko:"컬러 밸런스 색상 보정 효과 예제입니다.",en:"Example of Color Balance color adjustment effect."}},{name:"ColorTemperatureTint",path:"postEffect/adjustments/colorTemperatureTint",description:{ko:"색온도 및 틴트 색상 보정 효과 예제입니다.",en:"Example of Color Temperature & Tint color adjustment effect."}},{name:"BrightnessContrast",path:"postEffect/adjustments/brightnessContrast",description:{ko:"밝기 및 대비 색상 보정 효과 예제입니다.",en:"Example of Brightness & Contrast color adjustment effect."}},{name:"HueSaturation",path:"postEffect/adjustments/hueSaturation",description:{ko:"색조 및 채도 색상 보정 효과 예제입니다.",en:"Example of Hue & Saturation color adjustment effect."}},{name:"Threshold",path:"postEffect/adjustments/threshold",description:{ko:"임계값(Threshold) 색상 보정 효과 예제입니다.",en:"Example of Threshold color adjustment effect."}},{name:"Vibrance",path:"postEffect/adjustments/vibrance",description:{ko:"활기(Vibrance) 색상 보정 효과 예제입니다.",en:"Example of Vibrance color adjustment effect."}}]},{name:"Blur",list:[{name:"Blur",path:"postEffect/blur/blur",description:{ko:"기본 블러 효과 예제입니다.",en:"Example of Basic Blur effect."}},{name:"BlurX",path:"postEffect/blur/blurX",description:{ko:"가로 방향 블러 효과 예제입니다.",en:"Example of Horizontal Blur effect."}},{name:"BlurY",path:"postEffect/blur/blurY",description:{ko:"세로 방향 블러 효과 예제입니다.",en:"Example of Vertical Blur effect."}},{name:"DirectionalBlur",path:"postEffect/blur/directionalBlur",description:{ko:"방향성 블러 효과 예제입니다.",en:"Example of Directional Blur effect."}},{name:"GaussianBlur",path:"postEffect/blur/gaussianBlur",description:{ko:"가우시안 블러 효과 예제입니다.",en:"Example of Gaussian Blur effect."}},{name:"RadialBlur",path:"postEffect/blur/radialBlur",description:{ko:"방사형 블러 효과 예제입니다.",en:"Example of Radial Blur effect."}},{name:"ZoomBlur",path:"postEffect/blur/zoomBlur",description:{ko:"줌 블러 효과 예제입니다.",en:"Example of Zoom Blur effect."}}]},{name:"Lens",list:[{name:"LensDistortion",path:"postEffect/lens/lensDistortion",description:{ko:"렌즈 왜곡 효과 예제입니다.",en:"Example of Lens Distortion effect."}},{name:"ChromaticAberration",path:"postEffect/lens/chromaticAberration",description:{ko:"색수차 효과 예제입니다.",en:"Example of Chromatic Aberration effect."}},{name:"DepthOfField",path:"postEffect/lens/dof",description:{ko:"피사계 심도(DoF) 효과 예제입니다.",en:"Example of Depth of Field effect."}},{name:"Vignetting",path:"postEffect/lens/vignetting",description:{ko:"비네팅 효과 예제입니다.",en:"Example of Vignetting effect."}}]},{name:"Fog",list:[{name:"Fog",path:"postEffect/fog/fog",description:{ko:"안개 효과를 시연하는 예제입니다.",en:"An example demonstrating fog effects."}},{name:"HeightFog",path:"postEffect/fog/heightFog",description:{ko:"높이 기반 안개 효과를 시연하는 예제입니다.",en:"An example demonstrating height-based fog effects."}}]},{name:"Screen Space Reflection",experimental:!0,list:[{experimental:!0,name:"SSR",path:"postEffect/ssr",description:{ko:"화면 공간 반사(SSR) 효과를 시연하는 예제입니다.",en:"An example demonstrating Screen Space Reflection (SSR) effects."}}]},{name:"Screen Space Ambient Occlusion",list:[{name:"SSAO",path:"postEffect/ssao",description:{ko:"화면 공간 앰비언트 오클루전(SSAO) 효과를 시연하는 예제입니다.",en:"An example demonstrating Screen Space Ambient Occlusion (SSAO) effects."}}]}]},{name:"2D",list:[{name:"Hello RedGPU - 2D Mode",path:"2d/helloWorld2D",description:{ko:"RedGPU의 2D 모드 초기화 샘플입니다.",en:"Sample of RedGPU's 2D mode initialization."}},{name:"View2D",list:[{name:"Multi View (2D + 2D)",path:"2d/view/multiView",description:{ko:"여러 개의 2D View를 사용하는 멀티 뷰 예제입니다.",en:"Multi-view example using multiple 2D Views."}},{name:"Multi View (3D + 2D)",path:"2d/view/multiViewWith3D",description:{ko:"3D View와 2D View를 함께 사용하는 복합 멀티 뷰 예제입니다.",en:"Complex multi-view example using both 3D View and 2D View."}}]},{name:"Sprite2D",list:[{name:"Basic Sprite2D",path:"2d/sprite2D/basic",description:{ko:"기본적인 Sprite2D 객체 사용법을 보여주는 예제입니다.",en:"An example showing basic usage of Sprite2D object."}},{name:"Hierarchy Sprite2D",path:"2d/sprite2D/hierarchy",description:{ko:"2D 공간에서 Sprite2D의 계층 구조를 구성하는 예제입니다.",en:"An example constructing a hierarchy of Sprite2D in 2D space."}},{name:"Pivot Sprite2D",path:"2d/sprite2D/pivot",description:{ko:"Sprite2D의 피벗(중심점)을 변경하여 회전 및 위치를 제어하는 예제입니다.",en:"An example controlling rotation and position by changing the pivot of Sprite2D."}},{name:"Child Methods",path:"2d/sprite2D/childMethod",description:{ko:"2D 객체의 자식 노드를 관리하는 다양한 메서드를 시연하는 예제입니다.",en:"An example demonstrating various methods for managing child nodes of 2D objects."}}]},{name:"SpriteSheet2D",list:[{name:"Basic SpriteSheet2D",path:"2d/spriteSheet2D/basic",description:{ko:"스프라이트 시트 애니메이션을 재생하는 기본적인 SpriteSheet2D 예제입니다.",en:"Basic SpriteSheet2D example playing sprite sheet animation."}}]},{name:"TextField2D",list:[{name:"Basic TextField2D",path:"2d/textField2D/basic",description:{ko:"2D 텍스트를 렌더링하는 TextField2D 객체의 기본 사용법 예제입니다.",en:"Basic usage example of TextField2D object for rendering 2D text."}}]},{name:"Group2D",list:[{name:"Basic Group2D",path:"2d/group2D/basic",description:{ko:"2D 객체들을 그룹화하여 관리하는 Group2D 예제입니다.",en:"Group2D example managing 2D objects by grouping them."}}]},{name:"2D Object Opacity",list:[{name:"2D Object Opacity",path:"2d/opacity/basic",description:{ko:"2D 객체의 투명도(Opacity)를 조절하는 예제입니다.",en:"An example adjusting the opacity of 2D objects."}}]},{name:"2D Object BlendMode",list:[{name:"BlendMode",path:"2d/blendMode/basic",description:{ko:"2D 객체의 다양한 블렌딩 모드를 테스트하는 예제입니다.",en:"An example testing various blending modes of 2D objects."}}]},{name:"2D Tint",experimental:!0,list:[{experimental:!0,name:"Tint Basic",path:"2d/tint/basic",description:{ko:"2D 객체에 색상을 입히는 기본 틴트 예제입니다.",en:"Basic tint example applying color to 2D objects."}},{experimental:!0,name:"Tint Objects",path:"2d/tint/2dObjectTint",description:{ko:"다양한 2D 객체에 틴트를 적용하는 예제입니다.",en:"An example applying tint to various 2D objects."}}]},{name:"Interaction",list:[{name:"MouseEvent",list:[{name:"Sprite2D",path:"2d/interaction/mouseEvent/sprite2D",description:{ko:"Sprite2D에 대한 마우스 이벤트를 처리하는 예제입니다.",en:"An example handling mouse events on Sprite2D."}},{name:"SpriteSheet2D",path:"2d/interaction/mouseEvent/spriteSheet2D",description:{ko:"SpriteSheet2D에 대한 마우스 이벤트를 처리하는 예제입니다.",en:"An example handling mouse events on SpriteSheet2D."}},{name:"TextField2D",path:"2d/interaction/mouseEvent/textField2D",description:{ko:"TextField2D에 대한 마우스 이벤트를 처리하는 예제입니다.",en:"An example handling mouse events on TextField2D."}}]},{name:"KeyboardEvent",list:[{name:"Keyboard Interaction",path:"2d/interaction/keyboardEvent",description:{ko:"keyboardKeyBuffer를 사용하여 2D 환경에서 객체를 제어하는 방법을 보여줍니다.",en:"Demonstrates how to control an object in a 2D environment using keyboardKeyBuffer."}}]}]}]},{name:"Physics",experimental:!0,list:[{name:"Fundamentals",experimental:!0,list:[{experimental:!0,name:"Basic Physics",path:"physics/basic",description:{ko:"Rapier 물리 엔진을 사용한 기본적인 물리 시뮬레이션 예제입니다.",en:"Basic physics simulation example using the Rapier physics engine."}},{experimental:!0,name:"Shapes & Materials",path:"physics/shapes",description:{ko:"다양한 충돌체 형상(Box, Sphere, Cylinder, Capsule)과 탄성/마찰 설정을 테스트합니다.",en:"Tests various collider shapes (Box, Sphere, Cylinder, Capsule) and restitution/friction settings."}},{experimental:!0,name:"Kinematic Interaction",path:"physics/kinematic",description:{ko:"코드에 의해 제어되는 키네마틱 객체가 동적 객체들과 상호작용하는 모습을 보여줍니다.",en:"Demonstrates how kinematic objects controlled by code interact with dynamic objects."}},{experimental:!0,name:"Mesh Collider",path:"physics/meshCollider",description:{ko:"커스텀 기하구조를 물리 충돌체로 변환하는 방법을 테스트합니다.",en:"Tests how to convert custom geometries into physics engine colliders."}},{experimental:!0,name:"HeightField",path:"physics/heightField",description:{ko:"높이맵 데이터를 사용하여 지형과 같은 복잡한 표면의 물리 충돌을 구현하는 방법을 테스트합니다.",en:"Tests how to implement physics collisions for complex surfaces like terrain using heightmap data."}},{experimental:!0,name:"GLTF Physics",path:"physics/gltfPhysics",description:{ko:"로드된 GLTF 모델의 복잡한 계층 구조와 메쉬 데이터를 분석하여 자동으로 물리 충돌체를 생성하는 방법을 테스트합니다.",en:"Tests how to automatically generate physics colliders by analyzing the complex hierarchy and mesh data of a loaded GLTF model."}}]},{name:"Interaction & Events",experimental:!0,list:[{experimental:!0,name:"Raycasting Interaction",path:"physics/raycast",description:{ko:"마우스 클릭 지점에서 광선을 쏘아 물리 객체를 검출하고, 힘을 가해 밀어내는 등의 상호작용을 구현합니다.",en:"Casts rays from mouse click positions to detect physics objects and implements interactions like pushing them with force."}},{experimental:!0,name:"Collision Events",path:"physics/collisionEvents",description:{ko:"물체 간의 충돌 이벤트를 감지하여 실시간으로 색상을 변경하는 등 물리 연동 로직을 테스트합니다.",en:"Tests physics integration logic by detecting collision events between objects and changing colors in real-time."}},{experimental:!0,name:"Triggers & Sensors",path:"physics/triggers",description:{ko:"물체와 물리적인 충돌은 발생하지 않으나 영역 진입을 감지하는 센서(Trigger) 기능을 테스트합니다.",en:"Tests the sensor (Trigger) function that detects area entry without physical collision."}},{experimental:!0,name:"Collision Filtering",path:"physics/collisionFiltering",description:{ko:"Bitmask 기반의 충돌 그룹 설정을 통해 특정 객체들끼리만 선택적으로 충돌하도록 제어하는 고급 물리 기술을 구현합니다.",en:"Implements advanced physics techniques to selectively control collisions between specific objects through Bitmask-based collision group settings."}}]},{name:"Joints & Constraints",experimental:!0,list:[{experimental:!0,name:"Basic Joints",path:"physics/joints",description:{ko:"물체들을 서로 연결하는 관절(Joint) 기능을 사용하여 체인이나 진자 운동과 같은 복잡한 물리 구조를 구현합니다.",en:"Implements complex physical structures like chains or pendulums using joints to connect objects together."}},{experimental:!0,name:"Revolute Joints & Motors",path:"physics/revoluteJoint",description:{ko:"특정 축을 기준으로 회전하는 관절(Revolute Joint)과 모터 기능을 사용하여 풍차나 선풍기와 같은 회전 장치를 구현합니다.",en:"Implements rotating devices like windmills or fans using revolute joints that rotate around a specific axis and motor functions."}},{experimental:!0,name:"Prismatic Joints & Sliders",path:"physics/prismaticJoint",description:{ko:"직선 방향으로만 왕복 이동이 가능한 프리즈매틱 관절(Prismatic Joint)을 사용하여 승강기나 슬라이더 장치를 구현합니다.",en:"Implements elevators or slider devices using prismatic joints that allow reciprocal movement only in a straight line."}},{experimental:!0,name:"Spring Joint",path:"physics/springJoint",description:{ko:"스프링 조인트를 사용하여 탄성 있는 연결을 구현하는 방법을 테스트합니다.",en:"Tests how to implement elastic connections using spring joints."}},{experimental:!0,name:"Soft Body",path:"physics/softBody",description:{ko:"다수의 노드를 스프링으로 연결하여 젤리와 같은 소프트 바디 효과를 구현합니다.",en:"Implements a jelly-like soft body effect by connecting multiple nodes with springs."}},{experimental:!0,name:"Compound Shapes",path:"physics/compound",description:{ko:"여러 개의 지오메트리를 결합하여 하나의 복잡한 물리 객체를 만드는 복합 형상 기능을 테스트합니다.",en:"Tests the compound shape function that combines multiple geometries to create a single complex physics object."}}]},{name:"Simulation & Systems",experimental:!0,list:[{experimental:!0,name:"Surface Velocity (Conveyor)",path:"physics/surfaceVelocity",description:{ko:"컨베이어 벨트와 같이 표면이 움직이는 물체를 시뮬레이션합니다. 물체가 닿았을 때 특정 방향으로 힘을 가하여 이동시킵니다.",en:"Simulates objects with moving surfaces like conveyor belts. Applies force to move objects in a specific direction when they make contact."}},{experimental:!0,name:"Buoyancy Basics",path:"physics/buoyancy",description:{ko:"물속에서 물체가 떠오르는 부력과 유체 저항을 시뮬레이션합니다. 잠긴 깊이에 따라 상향 힘을 조절합니다.",en:"Simulates buoyancy and fluid resistance for objects in water. Adjusts upward force based on submerged depth."}},{experimental:!0,name:"Ragdoll System",path:"physics/ragdoll",description:{ko:"인간형 캐릭터의 뼈대를 관절(Joint)로 연결하여, 중력에 의해 자연스럽게 쓰러지는 래그돌 물리 효과를 시뮬레이션합니다.",en:"Simulates ragdoll physics where a humanoid skeleton is connected with joints and falls naturally under gravity."}},{experimental:!0,name:"Character Controller",path:"physics/characterController",description:{ko:"지면을 걷고 계단을 오르는 1인칭/3인칭 캐릭터 이동의 기초를 구현합니다.",en:"Implements the basics of 1st/3rd person character movement walking on the ground and climbing stairs."}},{experimental:!0,name:"Advanced Character Controller",path:"physics/advancedCharacterController",description:{ko:"관성 이동, 공중 제어, 이중 점프 등 게임적인 조작감이 가미된 고급 캐릭터 컨트롤러를 구현합니다.",en:"Implements an advanced character controller with game-like controls such as inertial movement, air control, and double jumping."}}]},{name:"Performance & Stress Test",experimental:!0,list:[{experimental:!0,name:"Galton Board",path:"physics/galton",description:{ko:"수많은 구슬이 핀 사이를 떨어지며 통계적 분포를 형성하는 과정을 시뮬레이션합니다.",en:"Simulates the process where numerous balls fall between pins and form a statistical distribution."}},{experimental:!0,name:"Physics Bowling",path:"physics/bowling",description:{ko:"고속으로 이동하는 볼과 핀 사이의 충돌 및 연쇄 반응을 테스트합니다. CCD(Continuous Collision Detection) 기술이 적용되었습니다.",en:"Tests collisions and chain reactions between a fast-moving ball and pins. CCD (Continuous Collision Detection) technology is applied."}},{experimental:!0,name:"Impulse Explosion",path:"physics/explosion",description:{ko:"폭발 지점으로부터 주변 객체들에 충격량을 가하여 날려버리는 물리 효과를 구현합니다.",en:"Implements physics effects where impulse is applied from an explosion point to blow away surrounding objects."}},{experimental:!0,name:"Ultimate Stress Test",path:"physics/stressTest",description:{ko:"수천 개의 물리 객체를 동시에 시뮬레이션하여 엔진의 한계 성능을 테스트합니다. 휴면(Sleep) 모드 활성화를 통한 최적화 효과를 확인합니다.",en:"Tests the engine's performance limits by simulating thousands of physics objects simultaneously. Demonstrates optimization through Sleep mode."}}]}]}];Object.freeze(i);export{t as n,i as t}; \ No newline at end of file diff --git a/examples/exampleHelper/dist/examples.js b/examples/exampleHelper/dist/examples.js index 27fe5ee7b9..56e88edca0 100644 --- a/examples/exampleHelper/dist/examples.js +++ b/examples/exampleHelper/dist/examples.js @@ -1,5 +1,5 @@ !function(i){try{if("undefined"!=typeof document){var e=document.createElement("style");e.appendChild(document.createTextNode(i)),document.head.appendChild(e)}}catch(o){console.error("vite-plugin-css-injected-by-js",o)}}("*{box-sizing:border-box}html,body{height:100%;margin:0;padding:0;overflow:hidden}.examples-app{color:#fff;flex-direction:column;height:100dvh;font-family:Arial,sans-serif;display:flex;overflow:hidden}.layout-wrapper{flex:1;min-height:0;display:flex;position:relative;overflow:hidden}::-webkit-scrollbar{width:6px;height:6px}::-webkit-scrollbar-track{background:0 0}::-webkit-scrollbar-thumb{background:#333;border-radius:3px}::-webkit-scrollbar-thumb:hover{background:#fdb48d}@keyframes fadeIn{0%{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}.fade-in{animation:.3s ease-out forwards fadeIn}.loading-ui{color:#fff;z-index:10005;pointer-events:none;opacity:1;-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);background:#0006;border:1px solid #ffffff1a;border-radius:10px;flex-direction:column;gap:10px;width:auto;min-width:240px;height:auto;padding:15px;font-family:monospace;font-size:11px;transition:opacity .3s,height .16s,width .16s;display:flex;position:fixed;top:50%;left:50%;overflow:hidden;transform:translate(-50%,-50%);box-shadow:0 10px 30px #00000080}.loading-ui-title{color:#aaa;margin-bottom:2px;font-weight:700}.loading-ui-info{border-top:1px solid #fff0;grid-template-rows:0fr;transition:grid-template-rows .3s ease-in-out,padding .3s,border-top .3s;display:grid;overflow:hidden}.loading-ui-info.active{border-top:1px solid #ffffff0d;grid-template-rows:1fr;padding-top:8px}.loading-ui-info-wrapper{flex-direction:column;gap:4px;min-height:0;display:flex}.loading-ui-info-title{color:#fff;text-transform:uppercase;letter-spacing:1px;justify-content:space-between;font-size:10px;display:flex}.loading-ui-info-detail{font-variant-numeric:tabular-nums;justify-content:space-between;display:flex}.loading-ui-progress{background:#ffffff1a;border-radius:2px;width:100%;height:4px;overflow:hidden}.loading-ui-progress .bar{will-change:width;background:#0078d4;height:100%;transition:width .4s}.loading-ui-info-file{color:#ffffff80;flex-direction:column;gap:4px;margin-top:4px;display:flex}.loading-ui-info-file .file{justify-content:space-between;display:flex}.total-progress-section{border-top:1px solid #ffffff0d;padding-top:6px}.total-progress-bar{box-shadow:0 0 10px #4caf5080}\n/*$vite$:1*/"); -import{r as e}from"./rolldown-runtime-BztV3taV.js?t=1781132971803";import{n as t,r as o,t as i}from"./vendor-react-BwJpJ84T.js?t=1781132971803";import{c as r,d as n,t as s,u as l}from"./IconButton-D8-442jY.js?t=1781132971803";import{t as a}from"./exampleList-B00YxcCV.js?t=1781132971803";var d=e(o(),1),p=e(t(),1),c="redgpu_examples_app_state",x=n((e,t)=>({activeTab:"3D",searchQuery:"",viewMode:"grid",language:"undefined"!=typeof navigator&&navigator.language.startsWith("ko")?"ko":"en",sidebarOpen:"undefined"==typeof window||window.innerWidth>1024,scrollPosition:0,isNarrow:"undefined"!=typeof window&&window.innerWidth<=768,setActiveTab:o=>{e({activeTab:o}),t().saveState()},setSearchQuery:o=>{e({searchQuery:o}),t().saveState()},setViewMode:o=>{e({viewMode:o}),t().saveState()},setLanguage:o=>{e({language:o}),t().saveState()},setSidebarOpen:t=>e({sidebarOpen:t}),setScrollPosition:t=>e({scrollPosition:t}),setIsNarrow:t=>e({isNarrow:t}),saveState:()=>{const{activeTab:e,searchQuery:o,viewMode:i,language:r,scrollPosition:n}=t(),s={activeTab:e,searchQuery:o,viewMode:i,language:r,scrollPosition:n};sessionStorage.setItem(c,JSON.stringify(s));const l=new URL(window.location.href);l.searchParams.set("tab",e),o?l.searchParams.set("q",o):l.searchParams.delete("q"),window.history.replaceState({},"",l.toString())},restoreState:()=>{const t=new URLSearchParams(window.location.search),o=t.get("tab"),i=t.get("q");o&&e({activeTab:o}),i&&e({searchQuery:i});const r=sessionStorage.getItem(c);if(r)try{const t=JSON.parse(r);e(e=>({...t,activeTab:o||t.activeTab||e.activeTab,searchQuery:i||t.searchQuery||e.searchQuery,scrollPosition:Number(t.scrollPosition)||0}))}catch(n){console.error("Failed to restore examples state:",n)}}}));x.getState().restoreState();var h=i(),m=()=>{const e=x(e=>e.isNarrow); +import{r as e}from"./rolldown-runtime-BztV3taV.js?t=1781136546834";import{n as t,r as o,t as i}from"./vendor-react-BwJpJ84T.js?t=1781136546834";import{c as r,d as n,t as s,u as l}from"./IconButton-D8-442jY.js?t=1781136546834";import{t as a}from"./exampleList-B00YxcCV.js?t=1781136546834";var d=e(o(),1),p=e(t(),1),c="redgpu_examples_app_state",x=n((e,t)=>({activeTab:"3D",searchQuery:"",viewMode:"grid",language:"undefined"!=typeof navigator&&navigator.language.startsWith("ko")?"ko":"en",sidebarOpen:"undefined"==typeof window||window.innerWidth>1024,scrollPosition:0,isNarrow:"undefined"!=typeof window&&window.innerWidth<=768,setActiveTab:o=>{e({activeTab:o}),t().saveState()},setSearchQuery:o=>{e({searchQuery:o}),t().saveState()},setViewMode:o=>{e({viewMode:o}),t().saveState()},setLanguage:o=>{e({language:o}),t().saveState()},setSidebarOpen:t=>e({sidebarOpen:t}),setScrollPosition:t=>e({scrollPosition:t}),setIsNarrow:t=>e({isNarrow:t}),saveState:()=>{const{activeTab:e,searchQuery:o,viewMode:i,language:r,scrollPosition:n}=t(),s={activeTab:e,searchQuery:o,viewMode:i,language:r,scrollPosition:n};sessionStorage.setItem(c,JSON.stringify(s));const l=new URL(window.location.href);l.searchParams.set("tab",e),o?l.searchParams.set("q",o):l.searchParams.delete("q"),window.history.replaceState({},"",l.toString())},restoreState:()=>{const t=new URLSearchParams(window.location.search),o=t.get("tab"),i=t.get("q");o&&e({activeTab:o}),i&&e({searchQuery:i});const r=sessionStorage.getItem(c);if(r)try{const t=JSON.parse(r);e(e=>({...t,activeTab:o||t.activeTab||e.activeTab,searchQuery:i||t.searchQuery||e.searchQuery,scrollPosition:Number(t.scrollPosition)||0}))}catch(n){console.error("Failed to restore examples state:",n)}}}));x.getState().restoreState();var h=i(),m=()=>{const e=x(e=>e.isNarrow); return(0,h.jsx)("div",{style:u,children: (0,h.jsxs)("div",{style:{display:"flex",flexDirection:e?"column":"row",alignItems:e?"flex-start":"center",gap:e?"0":"12px"},children:[ (0,h.jsx)("h1",{style:{...g,fontSize:e?"14px":"18px",lineHeight:"1.2",margin:0},children:"RedGPU"}), (0,h.jsx)("span",{style:{...f,fontSize:e?"12px":"18px",marginTop:e?"-2px":"0",opacity:e?.7:1},children:"Examples"})]})})},u={display:"flex",alignItems:"center"},g={fontSize:"18px",fontWeight:"bold",letterSpacing:"0.02em",color:"#fff"},f={color:"#fdb48d",fontWeight:"normal"},b=()=>{const e=x(e=>e.searchQuery),t=x(e=>e.setSearchQuery),o=x(e=>e.isNarrow); return(0,h.jsxs)("div",{style:y,children:[ (0,h.jsx)("input",{type:"text",placeholder:o?"Search...":"Search examples...","aria-label":"Search examples",value:e,onChange:e=>t(e.target.value),style:{...w,height:o?"32px":"36px"}}),e&& (0,h.jsx)("button",{onClick:()=>t(""),style:v,"aria-label":"Clear search",title:"Clear search",children:"×"})]})},y={position:"relative",width:"100%"},w={width:"100%",height:"36px",backgroundColor:"#1e1e1f",border:"1px solid #333",borderRadius:"18px",padding:"0 40px 0 16px",color:"#fff",fontSize:"14px",outline:"none",transition:"border-color 0.2s"},v={position:"absolute",right:"12px",top:"50%",transform:"translateY(-50%)",background:"none",border:"none",color:"#999",fontSize:"18px",cursor:"pointer"},S=()=>{const e=x(e=>e.isNarrow),t=x(e=>e.language),o=e=>window.open(e,"_blank"); return(0,h.jsxs)("div",{style:j,children:[ (0,h.jsx)(s,{icon: (0,h.jsx)(r,{color:"#fff",size:e?14:18}),label:"GITHUB",onClick:()=>o("https://github.com/redcamel/RedGPU"),title:"GitHub Repository"}),!e&& (0,h.jsxs)(h.Fragment,{children:[ (0,h.jsx)("button",{style:C,onClick:()=>o("/RedGPU/manual/"),children:"MANUAL"}), (0,h.jsx)("button",{style:C,onClick:()=>o(`/RedGPU/manual/${t}/api/RedGPU-API/namespaces/RedGPU/README.html`),children:"API"})]})]})},j={display:"flex",alignItems:"stretch",gap:"1px"},C={backgroundColor:"transparent",border:"none",color:"#e0e0e0",fontSize:"11px",fontWeight:"bold",cursor:"pointer",padding:"0 15px",transition:"color 0.2s"},R=()=>{const e=x(e=>e.isNarrow); diff --git a/examples/exampleHelper/dist/index.js b/examples/exampleHelper/dist/index.js index 5e7d0bae11..5c8c569b8f 100644 --- a/examples/exampleHelper/dist/index.js +++ b/examples/exampleHelper/dist/index.js @@ -1,17 +1,17 @@ !function(i){try{if("undefined"!=typeof document){var e=document.createElement("style");e.appendChild(document.createTextNode(i)),document.head.appendChild(e)}}catch(o){console.error("vite-plugin-css-injected-by-js",o)}}("*{box-sizing:border-box}html,body{height:100%;margin:0;padding:0;overflow:hidden}.examples-app{color:#fff;flex-direction:column;height:100dvh;font-family:Arial,sans-serif;display:flex;overflow:hidden}.layout-wrapper{flex:1;min-height:0;display:flex;position:relative;overflow:hidden}::-webkit-scrollbar{width:6px;height:6px}::-webkit-scrollbar-track{background:0 0}::-webkit-scrollbar-thumb{background:#333;border-radius:3px}::-webkit-scrollbar-thumb:hover{background:#fdb48d}@keyframes fadeIn{0%{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}.fade-in{animation:.3s ease-out forwards fadeIn}.loading-ui{color:#fff;z-index:10005;pointer-events:none;opacity:1;-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);background:#0006;border:1px solid #ffffff1a;border-radius:10px;flex-direction:column;gap:10px;width:auto;min-width:240px;height:auto;padding:15px;font-family:monospace;font-size:11px;transition:opacity .3s,height .16s,width .16s;display:flex;position:fixed;top:50%;left:50%;overflow:hidden;transform:translate(-50%,-50%);box-shadow:0 10px 30px #00000080}.loading-ui-title{color:#aaa;margin-bottom:2px;font-weight:700}.loading-ui-info{border-top:1px solid #fff0;grid-template-rows:0fr;transition:grid-template-rows .3s ease-in-out,padding .3s,border-top .3s;display:grid;overflow:hidden}.loading-ui-info.active{border-top:1px solid #ffffff0d;grid-template-rows:1fr;padding-top:8px}.loading-ui-info-wrapper{flex-direction:column;gap:4px;min-height:0;display:flex}.loading-ui-info-title{color:#fff;text-transform:uppercase;letter-spacing:1px;justify-content:space-between;font-size:10px;display:flex}.loading-ui-info-detail{font-variant-numeric:tabular-nums;justify-content:space-between;display:flex}.loading-ui-progress{background:#ffffff1a;border-radius:2px;width:100%;height:4px;overflow:hidden}.loading-ui-progress .bar{will-change:width;background:#0078d4;height:100%;transition:width .4s}.loading-ui-info-file{color:#ffffff80;flex-direction:column;gap:4px;margin-top:4px;display:flex}.loading-ui-info-file .file{justify-content:space-between;display:flex}.total-progress-section{border-top:1px solid #ffffff0d;padding-top:6px}.total-progress-bar{box-shadow:0 0 10px #4caf5080}\n/*$vite$:1*/"); -import{r as e}from"./rolldown-runtime-BztV3taV.js?t=1781132971803";import{n as t,r as o,t as n}from"./vendor-react-BwJpJ84T.js?t=1781132971803";import{a as i,i as s,l as r,n as a,o as l,r as c,s as d,t as u,u as p}from"./IconButton-D8-442jY.js?t=1781132971803";import{t as x}from"./store-2JcZHIgY.js?t=1781132971803";var f=e(t(),1),h=e(o(),1),g=n(),m=({icon:e,label:t,isActive:o,onClick:n,title:i})=>{const[s,r]=(0,h.useState)(!1); +import{r as e}from"./rolldown-runtime-BztV3taV.js?t=1781136546834";import{n as t,r as o,t as n}from"./vendor-react-BwJpJ84T.js?t=1781136546834";import{a as i,i as s,l as r,n as a,o as l,r as c,s as d,t as u,u as p}from"./IconButton-D8-442jY.js?t=1781136546834";import{t as x}from"./store-2JcZHIgY.js?t=1781136546834";var f=e(t(),1),h=e(o(),1),g=n(),m=({icon:e,label:t,isActive:o,onClick:n,title:i})=>{const[s,r]=(0,h.useState)(!1); return(0,g.jsx)("button",{style:{...b,width:e?"52px":"auto",padding:e?"0":"0 20px",backgroundColor:s?"#1a1a1c":"#111112",color:"#fff"},onClick:n,title:i||t,"aria-label":i||t,"aria-pressed":o,onMouseEnter:()=>r(!0),onMouseLeave:()=>r(!1),children: (0,g.jsx)("div",{style:{opacity:o?1:.2,display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:"100%",transition:"opacity 0.2s"},children:e?"string"==typeof e? (0,g.jsx)("img",{src:e,style:w,alt:t}):e:t})})},b={display:"flex",alignItems:"center",justifyContent:"center",height:"100%",backgroundColor:"#111112",border:"none",fontSize:"11px",fontWeight:"bold",cursor:"pointer",transition:"background-color 0.2s, opacity 0.2s",letterSpacing:"0.05em",flexShrink:0,boxSizing:"border-box"},w={width:"24px",height:"24px"},v=({label:e,value:t,options:o,onChange:n})=>{const[i,s]=(0,h.useState)(!1),[r,a]=(0,h.useState)(!1),[l,c]=(0,h.useState)("down"),[d,u]=(0,h.useState)(null),p=(0,h.useRef)(null);(0,h.useEffect)(()=>{const e=e=>{p.current&&!p.current.contains(e.target)&&a(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]);const x=o.find(e=>e.value===t)?.label||t; return(0,g.jsxs)("div",{ref:p,style:{...j,backgroundColor:i||r?"#1a1a1c":"#111112"},onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!1),onClick:()=>{if(!r&&p.current){const e=p.current.getBoundingClientRect(),t=window.innerHeight;e.bottom>t/2?c("up"):c("down")}a(!r)},children:[ (0,g.jsx)("span",{style:y,children:e}), (0,g.jsxs)("div",{style:S,children:[ (0,g.jsx)("span",{style:C,children:x}), (0,g.jsx)("div",{style:{...E,transform:r?"up"===l?"rotate(0deg)":"rotate(180deg)":"up"===l?"rotate(180deg)":"rotate(0deg)"}})]}),r&& (0,g.jsx)("div",{style:{...k,top:"down"===l?"100%":"auto",bottom:"up"===l?"100%":"auto",borderTop:"down"===l?"1px solid rgba(255, 255, 255, 0.05)":"none",borderBottom:"up"===l?"1px solid rgba(255, 255, 255, 0.05)":"none",boxShadow:"down"===l?"0 10px 20px rgba(0,0,0,0.5)":"0 -10px 20px rgba(0,0,0,0.5)"},children:o.map(e=>{const o=t===e.value,i=d===e.value; -return(0,g.jsx)("div",{style:{...A,backgroundColor:o?"#2a2a2c":i?"#252527":"transparent",color:o||i?"#fff":"#fdb48d"},onMouseEnter:()=>u(e.value),onMouseLeave:()=>u(null),onClick:t=>{t.stopPropagation(),n(e.value),a(!1)},children:e.label},e.value)})})]})},j={position:"relative",display:"flex",flexDirection:"column",justifyContent:"center",padding:"0 16px",backgroundColor:"#111112",minWidth:"110px",flexShrink:0,cursor:"pointer",transition:"background-color 0.2s",userSelect:"none"},y={fontSize:"9px",color:"#666",fontWeight:"bold",marginBottom:"2px"},S={display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%"},C={fontSize:"11px",color:"#fdb48d",fontWeight:"bold"},E={width:"10px",height:"10px",marginLeft:"8px",backgroundImage:'url("data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2212%22%20height%3D%2212%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%23fdb48d%22%20stroke-width%3D%223%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpolyline%20points%3D%226%209%2012%2015%2018%209%22%3E%3C%2Fpolyline%3E%3C%2Fsvg%3E")',backgroundRepeat:"no-repeat",backgroundPosition:"center",backgroundSize:"contain",transition:"transform 0.2s ease-in-out"},k={position:"absolute",top:"100%",left:0,right:0,backgroundColor:"#1a1a1c",borderTop:"1px solid rgba(255, 255, 255, 0.05)",boxShadow:"0 10px 20px rgba(0,0,0,0.5)",zIndex:10004,display:"flex",flexDirection:"column",padding:"4px 0"},A={padding:"10px 16px",fontSize:"11px",fontWeight:"bold",cursor:"pointer",transition:"background-color 0.1s, color 0.1s"},M={LINEAR:"linear",KHRONOS_PBR_NEUTRAL:"khronosPBRNeutral",ACES_FILMIC_HILL:"ACESFilmicHill",ACES_FILMIC_NARKOWICZ:"ACESFilmicNarkowicz"};Object.freeze(M);var N=()=>{const e=x(e=>e.redGPUContext),[t,o]=(0,h.useState)("useMSAA"),[n,i]=(0,h.useState)(M.KHRONOS_PBR_NEUTRAL);return(0,h.useEffect)(()=>{if(e){const t=e.antialiasingManager;if(t.useMSAA?o("useMSAA"):t.useFXAA?o("useFXAA"):t.useTAA?o("useTAA"):o("NONE"),e.viewList.length>0){const t=e.viewList[0];t.toneMappingManager&&i(t.toneMappingManager.mode)}}},[e]), (0,g.jsxs)(g.Fragment,{children:[ (0,g.jsx)(v,{label:"TONE MAPPING",value:n,options:Object.entries(M).map(([e,t])=>({value:t,label:e.replace(/_/g," ")})),onChange:t=>{i(t),e&&e.viewList.forEach(e=>{e.toneMappingManager&&(e.toneMappingManager.mode=t)})}}), (0,g.jsx)(v,{label:"ANTIALIASING",value:t,options:[{value:"NONE",label:"NONE"},{value:"useMSAA",label:"MSAA"},{value:"useFXAA",label:"FXAA"},{value:"useTAA",label:"TAA"}],onChange:t=>{if(o(t),e){const o=e.antialiasingManager;o.useMSAA=!1,o.useFXAA=!1,o.useTAA=!1,"useMSAA"===t?o.useMSAA=!0:"useFXAA"===t?o.useFXAA=!0:"useTAA"===t&&(o.useTAA=!0)}}})]})},L=()=>{const e=x(e=>e.currentExample),t=x(e=>e.isNarrow),[o,n]=(0,h.useState)([]);(0,h.useEffect)(()=>{(async()=>{n(await(async()=>{const{ExampleList:e}=await import("./exampleList-B00YxcCV.js?t=1781132971803").then(e=>e.n),t=[],o=e=>{for(const n of e)n.path&&t.push(n),n.list&&o(n.list)};return o(e),t})())})()},[]);const i=(0,h.useMemo)(()=>e&&0!==o.length?o.findIndex(t=>t.path===e.path):-1,[e,o]),r=i>0?o[i-1]:null,a=i{const t=window.location.pathname,o=t.indexOf("/examples/");if(-1===o)window.location.href=`${window.location.origin}/examples/${e}/index.html`;else{const n=t.substring(0,o);window.location.href=`${window.location.origin}${n}/examples/${e}/index.html`}}; +return(0,g.jsx)("div",{style:{...A,backgroundColor:o?"#2a2a2c":i?"#252527":"transparent",color:o||i?"#fff":"#fdb48d"},onMouseEnter:()=>u(e.value),onMouseLeave:()=>u(null),onClick:t=>{t.stopPropagation(),n(e.value),a(!1)},children:e.label},e.value)})})]})},j={position:"relative",display:"flex",flexDirection:"column",justifyContent:"center",padding:"0 16px",backgroundColor:"#111112",minWidth:"110px",flexShrink:0,cursor:"pointer",transition:"background-color 0.2s",userSelect:"none"},y={fontSize:"9px",color:"#666",fontWeight:"bold",marginBottom:"2px"},S={display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%"},C={fontSize:"11px",color:"#fdb48d",fontWeight:"bold"},E={width:"10px",height:"10px",marginLeft:"8px",backgroundImage:'url("data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2212%22%20height%3D%2212%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%23fdb48d%22%20stroke-width%3D%223%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpolyline%20points%3D%226%209%2012%2015%2018%209%22%3E%3C%2Fpolyline%3E%3C%2Fsvg%3E")',backgroundRepeat:"no-repeat",backgroundPosition:"center",backgroundSize:"contain",transition:"transform 0.2s ease-in-out"},k={position:"absolute",top:"100%",left:0,right:0,backgroundColor:"#1a1a1c",borderTop:"1px solid rgba(255, 255, 255, 0.05)",boxShadow:"0 10px 20px rgba(0,0,0,0.5)",zIndex:10004,display:"flex",flexDirection:"column",padding:"4px 0"},A={padding:"10px 16px",fontSize:"11px",fontWeight:"bold",cursor:"pointer",transition:"background-color 0.1s, color 0.1s"},M={LINEAR:"linear",KHRONOS_PBR_NEUTRAL:"khronosPBRNeutral",ACES_FILMIC_HILL:"ACESFilmicHill",ACES_FILMIC_NARKOWICZ:"ACESFilmicNarkowicz"};Object.freeze(M);var N=()=>{const e=x(e=>e.redGPUContext),[t,o]=(0,h.useState)("useMSAA"),[n,i]=(0,h.useState)(M.KHRONOS_PBR_NEUTRAL);return(0,h.useEffect)(()=>{if(e){const t=e.antialiasingManager;if(t.useMSAA?o("useMSAA"):t.useFXAA?o("useFXAA"):t.useTAA?o("useTAA"):o("NONE"),e.viewList.length>0){const t=e.viewList[0];t.toneMappingManager&&i(t.toneMappingManager.mode)}}},[e]), (0,g.jsxs)(g.Fragment,{children:[ (0,g.jsx)(v,{label:"TONE MAPPING",value:n,options:Object.entries(M).map(([e,t])=>({value:t,label:e.replace(/_/g," ")})),onChange:t=>{i(t),e&&e.viewList.forEach(e=>{e.toneMappingManager&&(e.toneMappingManager.mode=t)})}}), (0,g.jsx)(v,{label:"ANTIALIASING",value:t,options:[{value:"NONE",label:"NONE"},{value:"useMSAA",label:"MSAA"},{value:"useFXAA",label:"FXAA"},{value:"useTAA",label:"TAA"}],onChange:t=>{if(o(t),e){const o=e.antialiasingManager;o.useMSAA=!1,o.useFXAA=!1,o.useTAA=!1,"useMSAA"===t?o.useMSAA=!0:"useFXAA"===t?o.useFXAA=!0:"useTAA"===t&&(o.useTAA=!0)}}})]})},L=()=>{const e=x(e=>e.currentExample),t=x(e=>e.isNarrow),[o,n]=(0,h.useState)([]);(0,h.useEffect)(()=>{(async()=>{n(await(async()=>{const{ExampleList:e}=await import("./exampleList-B00YxcCV.js?t=1781136546834").then(e=>e.n),t=[],o=e=>{for(const n of e)n.path&&t.push(n),n.list&&o(n.list)};return o(e),t})())})()},[]);const i=(0,h.useMemo)(()=>e&&0!==o.length?o.findIndex(t=>t.path===e.path):-1,[e,o]),r=i>0?o[i-1]:null,a=i{const t=window.location.pathname,o=t.indexOf("/examples/");if(-1===o)window.location.href=`${window.location.origin}/examples/${e}/index.html`;else{const n=t.substring(0,o);window.location.href=`${window.location.origin}${n}/examples/${e}/index.html`}}; return(0,g.jsx)(g.Fragment,{children: (0,g.jsx)("div",{style:t?I:P,children: (0,g.jsxs)("div",{style:{display:"flex",alignItems:"stretch",height:"100%",gap:"1px",backgroundColor:"#222",justifyContent:t?"center":"flex-start"},children:[r&& (0,g.jsx)("button",{style:{...T,width:t?"46px":"52px",backgroundColor:l?"#1a1a1c":"#111112"},onClick:()=>f(r.path),title:`Previous Example : ${r.name}`,onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),children: (0,g.jsx)(c,{color:"#fdb48d"})}), (0,g.jsxs)("div",{style:{...R,textAlign:t?"center":"left"},children:[(!t||e?.experimental)&& (0,g.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:t?"center":"flex-start",gap:"6px",marginBottom:"2px"},children:[!t&& (0,g.jsx)("span",{style:{...z,marginBottom:0},children:"Example"}),e?.experimental&& (0,g.jsx)("span",{style:O,children:"EXPERIMENTAL"})]}), (0,g.jsx)("span",{style:F,children:e?e.name:"empty example name"})]}),a&& (0,g.jsx)("button",{style:{...T,width:t?"46px":"52px",backgroundColor:u?"#1a1a1c":"#111112"},onClick:()=>f(a.path),title:`Next Example : ${a.name}`,onMouseEnter:()=>p(!0),onMouseLeave:()=>p(!1),children: (0,g.jsx)(s,{color:"#fdb48d"})})]})})})},I={display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"stretch",backgroundColor:"#111112",width:"100%",flexShrink:0},P={display:"flex",flexDirection:"column",justifyContent:"center",backgroundColor:"#111112",minWidth:"200px",flexShrink:0,alignItems:"stretch"},R={display:"flex",flexDirection:"column",justifyContent:"center",padding:"0 16px",flexGrow:1,minWidth:"100px",textAlign:"center"},z={fontSize:"9px",color:"#666",fontWeight:"bold",marginBottom:"2px"},O={fontSize:"8px",backgroundColor:"#ff4d4d",color:"#fff",padding:"4px 5px",borderRadius:"4px",fontWeight:"bold",lineHeight:"1",display:"inline-block"},F={fontSize:"11px",color:"#ccc",fontWeight:"bold",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},T={backgroundColor:"#111112",color:"#fdb48d",border:"none",width:"40px",cursor:"pointer",fontSize:"14px",fontWeight:"bold",display:"flex",alignItems:"center",justifyContent:"center",transition:"background-color 0.2s",padding:0},G=()=>{const e=x(e=>e.topBarRightActions),t=x(e=>e.redGPUContext),o=x(e=>e.isNarrow),[n,i]=(0,h.useState)(!1);return(0,h.useEffect)(()=>{if(t&&t.viewList.length>0){const e=t.viewList[0];e.postEffectManager&&i(e.postEffectManager.useSSAO)}},[t]), (0,g.jsx)("header",{style:D,children: (0,g.jsxs)("div",{style:B,children:[ (0,g.jsxs)("div",{style:U,children:[ (0,g.jsx)(u,{icon: (0,g.jsx)(d,{color:"#fff",size:24}),label:"HOME",onClick:()=>{window.location.href="/RedGPU/examples/index.html"},title:"HOME"}),!o&& (0,g.jsx)(L,{})]}), (0,g.jsxs)("div",{style:W,children:[!o&& (0,g.jsx)(g.Fragment,{children: (0,g.jsx)(N,{})}), -(0,g.jsx)(m,{label:"SSAO",onClick:()=>{const e=!n;i(e),t&&t.viewList.forEach(t=>{t.postEffectManager&&(t.postEffectManager.useSSAO=e)})},isActive:n}),e.map(e=> (0,g.jsx)(m,{icon:e.icon,label:e.label,onClick:e.onClick,isActive:!!e.isActive},e.id))]})]})})},D={position:"fixed",top:0,left:0,right:0,height:"52px",backgroundColor:"#111112",borderBottom:"1px solid rgba(255, 255, 255, 0.05)",zIndex:10003,display:"flex",flexDirection:"column",wordBreak:"keep-all"},B={display:"flex",height:"100%",width:"100%",alignItems:"stretch",justifyContent:"space-between",backgroundColor:"#222"},U={display:"flex",alignItems:"stretch",gap:"1px"},W={display:"flex",alignItems:"stretch",gap:"1px"},X=()=>{const e=x(e=>e.currentExample),t=x(e=>e.language),o=x(e=>e.setLanguage),n=x(e=>e.showSettingsPanel),i=x(e=>e.isNarrow);if(!e||!e.description)return null;const s=e.description[t]||e.description.en||"";return s? (0,g.jsxs)("div",{style:{...H,right:n&&!i?"320px":0},children:[ (0,g.jsx)("div",{style:$,children: (0,g.jsx)("span",{dangerouslySetInnerHTML:{__html:s}})}), (0,g.jsx)("button",{style:_,onClick:()=>o("ko"===t?"en":"ko"),children:"ko"===t?"ENGLISH":"한국어"})]}):null},H={position:"fixed",top:"52px",left:0,right:0,backgroundColor:"transparent",padding:"12px 20px",zIndex:10002,display:"flex",flexDirection:"column",alignItems:"flex-start",justifyContent:"flex-start",gap:"10px",pointerEvents:"none"},$={fontSize:"12px",color:"#eee",lineHeight:"1.6",maxWidth:"800px",wordBreak:"keep-all",textShadow:"1px 1px 2px rgba(0,0,0,0.8), 0 0 10px rgba(0,0,0,0.5)",pointerEvents:"auto"},_={backgroundColor:"rgba(255, 255, 255, 0.1)",color:"#ccc",border:"1px solid rgba(255, 255, 255, 0.2)",padding:"3px 10px",fontSize:"9px",fontWeight:"bold",cursor:"pointer",borderRadius:"4px",flexShrink:0,transition:"all 0.2s",pointerEvents:"auto",backdropFilter:"blur(4px)"},Y=()=>{const e=x(e=>e.showSourceModal),t=x(e=>e.setShowSourceModal),o=x(e=>e.currentExample),[n,i]=(0,h.useState)(""),[s,r]=(0,h.useState)(!1),a=(0,h.useRef)(null),{loadPrism:l}=(()=>{const e="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/prism.min.js",t="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-tomorrow.min.css";return{loadPrism:()=>new Promise(o=>{const n=window;if(n.Prism)o();else{if(!document.querySelector(`link[href="${t}"]`)){const e=document.createElement("link");e.rel="stylesheet",e.href=t,document.head.appendChild(e)}if(document.querySelector(`script[src="${e}"]`)){const e=setInterval(()=>{n.Prism&&(clearInterval(e),o())},100)}else{const t=document.createElement("script");t.src=e,t.onload=()=>o(),document.head.appendChild(t)}}})}})();return(0,h.useEffect)(()=>{e&&(r(!0),fetch("./index.js?t=1781132971803").then(e=>{if(!e.ok)throw new Error("Failed to load source code");return e.text()}).then(async e=>{i(e),r(!1),await l(),a.current&&window.Prism.highlightElement(a.current)}).catch(e=>{console.error(e),i("// Failed to load source code."),r(!1)}))},[e,l]),(0,h.useEffect)(()=>{e&&!s&&n&&window.Prism&&a.current&&window.Prism.highlightElement(a.current)},[n,s,e]),e? (0,g.jsx)("div",{style:Z,onClick:()=>t(!1),children: (0,g.jsxs)("div",{style:K,onClick:e=>e.stopPropagation(),children:[ (0,g.jsxs)("div",{style:q,children:[ (0,g.jsxs)("div",{style:V,children:["SOURCE CODE : ",o?.name]}), (0,g.jsx)("button",{style:J,onClick:()=>t(!1),children:"CLOSE"})]}), (0,g.jsx)("div",{style:Q,children:s? (0,g.jsx)("div",{style:ee,children:"Loading source code..."}): (0,g.jsx)("pre",{style:te,children: (0,g.jsx)("code",{ref:a,className:"language-javascript",style:oe,children:n})})})]})}):null},Z={position:"fixed",top:0,left:0,right:0,bottom:0,backgroundColor:"rgba(0, 0, 0, 0.85)",zIndex:2e4,display:"flex",alignItems:"center",justifyContent:"center",padding:"40px",backdropFilter:"blur(10px)"},K={width:"100%",maxWidth:"1200px",height:"100%",backgroundColor:"#111112",border:"1px solid #333",borderRadius:"8px",display:"flex",flexDirection:"column",overflow:"hidden",boxShadow:"0 20px 50px rgba(0,0,0,0.5)"},q={padding:"16px 24px",borderBottom:"1px solid #333",display:"flex",justifyContent:"space-between",alignItems:"center",backgroundColor:"#1a1a1b"},V={fontSize:"13px",fontWeight:"bold",color:"#fdb48d",letterSpacing:"0.05em"},J={backgroundColor:"#333",color:"#ccc",border:"none",padding:"6px 16px",fontSize:"11px",fontWeight:"bold",cursor:"pointer",borderRadius:"4px",transition:"all 0.2s"},Q={flex:1,overflow:"auto",backgroundColor:"#000"},ee={height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"#666",fontSize:"13px"},te={margin:0,padding:"20px",backgroundColor:"transparent"},oe={fontSize:"13px",lineHeight:"1.6",fontFamily:'Consolas, "Courier New", monospace',textShadow:"none",color:"#ccc"},ne=()=>{const e=x(e=>e.guiConfig),t=x(e=>e.redGPUContext),o=x(e=>e.isNarrow),[n,i]=(0,h.useState)(null),s=(0,h.useCallback)(()=>{const t=e?.compareLabel?.targetContainer;if(t){const e=o?148:50;Object.assign(t.style,{position:"fixed",top:"51px",left:"0",width:"100%",bottom:`${e}px`}),i(t.getBoundingClientRect())}else i(null)},[e?.compareLabel?.targetContainer,o]);if((0,h.useLayoutEffect)(()=>{s()},[s]),(0,h.useEffect)(()=>{const t=e?.compareLabel?.targetContainer;if(!t)return;const o=new ResizeObserver(()=>{s()});return o.observe(t),window.addEventListener("resize",s),()=>{o.disconnect(),window.removeEventListener("resize",s),Object.assign(t.style,{position:"",top:"",left:"",width:"",bottom:""})}},[s,e?.compareLabel?.targetContainer]),!e?.compareLabel||!t)return null;const{title:r,normalTitle:a="Normal"}=e.compareLabel,l={position:"fixed",display:"flex",alignItems:"center",justifyContent:"center",padding:"8px 10px",backgroundColor:"#5b52aa",color:"#fff",fontSize:"12px",fontWeight:600,pointerEvents:"none",lineHeight:1,zIndex:10},c=e=>{const t=n?n.top:51,i=n?n.left:0,s=n?n.width:window.innerWidth,r=o?148:50,a=n?n.height:window.innerHeight-(51+r);return o?{...l,left:i,[e?"bottom":"top"]:e?window.innerHeight-(t+a/2):t+a/2+1}:{...l,bottom:window.innerHeight-(t+a),left:i+s/2,...e?{transform:"translateX(calc(-100% - 1px))"}:{}}}; +(0,g.jsx)(m,{label:"SSAO",onClick:()=>{const e=!n;i(e),t&&t.viewList.forEach(t=>{t.postEffectManager&&(t.postEffectManager.useSSAO=e)})},isActive:n}),e.map(e=> (0,g.jsx)(m,{icon:e.icon,label:e.label,onClick:e.onClick,isActive:!!e.isActive},e.id))]})]})})},D={position:"fixed",top:0,left:0,right:0,height:"52px",backgroundColor:"#111112",borderBottom:"1px solid rgba(255, 255, 255, 0.05)",zIndex:10003,display:"flex",flexDirection:"column",wordBreak:"keep-all"},B={display:"flex",height:"100%",width:"100%",alignItems:"stretch",justifyContent:"space-between",backgroundColor:"#222"},U={display:"flex",alignItems:"stretch",gap:"1px"},W={display:"flex",alignItems:"stretch",gap:"1px"},X=()=>{const e=x(e=>e.currentExample),t=x(e=>e.language),o=x(e=>e.setLanguage),n=x(e=>e.showSettingsPanel),i=x(e=>e.isNarrow);if(!e||!e.description)return null;const s=e.description[t]||e.description.en||"";return s? (0,g.jsxs)("div",{style:{...H,right:n&&!i?"320px":0},children:[ (0,g.jsx)("div",{style:$,children: (0,g.jsx)("span",{dangerouslySetInnerHTML:{__html:s}})}), (0,g.jsx)("button",{style:_,onClick:()=>o("ko"===t?"en":"ko"),children:"ko"===t?"ENGLISH":"한국어"})]}):null},H={position:"fixed",top:"52px",left:0,right:0,backgroundColor:"transparent",padding:"12px 20px",zIndex:10002,display:"flex",flexDirection:"column",alignItems:"flex-start",justifyContent:"flex-start",gap:"10px",pointerEvents:"none"},$={fontSize:"12px",color:"#eee",lineHeight:"1.6",maxWidth:"800px",wordBreak:"keep-all",textShadow:"1px 1px 2px rgba(0,0,0,0.8), 0 0 10px rgba(0,0,0,0.5)",pointerEvents:"auto"},_={backgroundColor:"rgba(255, 255, 255, 0.1)",color:"#ccc",border:"1px solid rgba(255, 255, 255, 0.2)",padding:"3px 10px",fontSize:"9px",fontWeight:"bold",cursor:"pointer",borderRadius:"4px",flexShrink:0,transition:"all 0.2s",pointerEvents:"auto",backdropFilter:"blur(4px)"},Y=()=>{const e=x(e=>e.showSourceModal),t=x(e=>e.setShowSourceModal),o=x(e=>e.currentExample),[n,i]=(0,h.useState)(""),[s,r]=(0,h.useState)(!1),a=(0,h.useRef)(null),{loadPrism:l}=(()=>{const e="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/prism.min.js",t="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-tomorrow.min.css";return{loadPrism:()=>new Promise(o=>{const n=window;if(n.Prism)o();else{if(!document.querySelector(`link[href="${t}"]`)){const e=document.createElement("link");e.rel="stylesheet",e.href=t,document.head.appendChild(e)}if(document.querySelector(`script[src="${e}"]`)){const e=setInterval(()=>{n.Prism&&(clearInterval(e),o())},100)}else{const t=document.createElement("script");t.src=e,t.onload=()=>o(),document.head.appendChild(t)}}})}})();return(0,h.useEffect)(()=>{e&&(r(!0),fetch("./index.js?t=1781136546834").then(e=>{if(!e.ok)throw new Error("Failed to load source code");return e.text()}).then(async e=>{i(e),r(!1),await l(),a.current&&window.Prism.highlightElement(a.current)}).catch(e=>{console.error(e),i("// Failed to load source code."),r(!1)}))},[e,l]),(0,h.useEffect)(()=>{e&&!s&&n&&window.Prism&&a.current&&window.Prism.highlightElement(a.current)},[n,s,e]),e? (0,g.jsx)("div",{style:Z,onClick:()=>t(!1),children: (0,g.jsxs)("div",{style:K,onClick:e=>e.stopPropagation(),children:[ (0,g.jsxs)("div",{style:q,children:[ (0,g.jsxs)("div",{style:V,children:["SOURCE CODE : ",o?.name]}), (0,g.jsx)("button",{style:J,onClick:()=>t(!1),children:"CLOSE"})]}), (0,g.jsx)("div",{style:Q,children:s? (0,g.jsx)("div",{style:ee,children:"Loading source code..."}): (0,g.jsx)("pre",{style:te,children: (0,g.jsx)("code",{ref:a,className:"language-javascript",style:oe,children:n})})})]})}):null},Z={position:"fixed",top:0,left:0,right:0,bottom:0,backgroundColor:"rgba(0, 0, 0, 0.85)",zIndex:2e4,display:"flex",alignItems:"center",justifyContent:"center",padding:"40px",backdropFilter:"blur(10px)"},K={width:"100%",maxWidth:"1200px",height:"100%",backgroundColor:"#111112",border:"1px solid #333",borderRadius:"8px",display:"flex",flexDirection:"column",overflow:"hidden",boxShadow:"0 20px 50px rgba(0,0,0,0.5)"},q={padding:"16px 24px",borderBottom:"1px solid #333",display:"flex",justifyContent:"space-between",alignItems:"center",backgroundColor:"#1a1a1b"},V={fontSize:"13px",fontWeight:"bold",color:"#fdb48d",letterSpacing:"0.05em"},J={backgroundColor:"#333",color:"#ccc",border:"none",padding:"6px 16px",fontSize:"11px",fontWeight:"bold",cursor:"pointer",borderRadius:"4px",transition:"all 0.2s"},Q={flex:1,overflow:"auto",backgroundColor:"#000"},ee={height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"#666",fontSize:"13px"},te={margin:0,padding:"20px",backgroundColor:"transparent"},oe={fontSize:"13px",lineHeight:"1.6",fontFamily:'Consolas, "Courier New", monospace',textShadow:"none",color:"#ccc"},ne=()=>{const e=x(e=>e.guiConfig),t=x(e=>e.redGPUContext),o=x(e=>e.isNarrow),[n,i]=(0,h.useState)(null),s=(0,h.useCallback)(()=>{const t=e?.compareLabel?.targetContainer;if(t){const e=o?148:50;Object.assign(t.style,{position:"fixed",top:"51px",left:"0",width:"100%",bottom:`${e}px`}),i(t.getBoundingClientRect())}else i(null)},[e?.compareLabel?.targetContainer,o]);if((0,h.useLayoutEffect)(()=>{s()},[s]),(0,h.useEffect)(()=>{const t=e?.compareLabel?.targetContainer;if(!t)return;const o=new ResizeObserver(()=>{s()});return o.observe(t),window.addEventListener("resize",s),()=>{o.disconnect(),window.removeEventListener("resize",s),Object.assign(t.style,{position:"",top:"",left:"",width:"",bottom:""})}},[s,e?.compareLabel?.targetContainer]),!e?.compareLabel||!t)return null;const{title:r,normalTitle:a="Normal"}=e.compareLabel,l={position:"fixed",display:"flex",alignItems:"center",justifyContent:"center",padding:"8px 10px",backgroundColor:"#5b52aa",color:"#fff",fontSize:"12px",fontWeight:600,pointerEvents:"none",lineHeight:1,zIndex:10},c=e=>{const t=n?n.top:51,i=n?n.left:0,s=n?n.width:window.innerWidth,r=o?148:50,a=n?n.height:window.innerHeight-(51+r);return o?{...l,left:i,[e?"bottom":"top"]:e?window.innerHeight-(t+a/2):t+a/2+1}:{...l,bottom:window.innerHeight-(t+a),left:i+s/2,...e?{transform:"translateX(calc(-100% - 1px))"}:{}}}; return(0,g.jsxs)(g.Fragment,{children:[ (0,g.jsx)("div",{style:c(!0),children:a}), (0,g.jsx)("div",{style:c(!1),children:r})]})},ie=e=>{if(0===e)return"0 B";const t=Math.floor(Math.log(e)/Math.log(1024));return parseFloat((e/Math.pow(1024,t)).toFixed(2))+" "+["B","KB","MB","GB"][t]},se=()=>{const e=x(e=>e.loadingStates),t=x(e=>e.clearLoadingStates),[o,n]=(0,h.useState)(!1),[i,s]=(0,h.useState)(1),r=(0,h.useMemo)(()=>{const t={model:{loaded:0,total:0},buffers:{loaded:0,total:0},textures:{loaded:0,total:0}};return Object.values(e).forEach(e=>{e.model&&(t.model.loaded+=e.model.loaded||0,t.model.total+=e.model.total||0),e.buffers&&(t.buffers.loaded+=e.buffers.loaded||0,t.buffers.total+=e.buffers.total||0),e.textures&&(t.textures.loaded+=e.textures.loaded||0,t.textures.total+=e.textures.total||0)}),t},[e]),a=r.model.total>0?r.model.loaded/r.model.total:1,l=r.buffers.total>0?r.buffers.loaded/r.buffers.total:1,c=r.textures.total>0?r.textures.loaded/r.textures.total:1,d=(0,h.useMemo)(()=>0!==Object.values(e).length&&a>=1&&l>=1&&c>=1,[e,a,l,c]);if((0,h.useEffect)(()=>{Object.keys(e).length>0&&(n(!0),s(1))},[e]),(0,h.useEffect)(()=>{if(d){const e=setTimeout(()=>{s(0)},1e3);return()=>clearTimeout(e)}},[d]),!o)return null;const u=[r.model.total,r.buffers.total,r.textures.total].filter(e=>e>0).length,p=u>0?((r.model.total>0?a:0)+(r.buffers.total>0?l:0)+(r.textures.total>0?c:0))/u*100:100; return(0,g.jsxs)("div",{className:"loading-ui",style:{opacity:i,transition:"opacity 0.5s ease"},onTransitionEnd:()=>{0===i&&(n(!1),t())},children:[ @@ -35,7 +35,7 @@ return(0,g.jsxs)("div",{className:"loading-ui",style:{opacity:i,transition:"opac (0,g.jsxs)("div",{className:"loading-ui-info-detail",children:[ (0,g.jsxs)("span",{className:"percent",children:[Math.floor(100*c),"%"]}), (0,g.jsxs)("span",{className:"count",style:{marginLeft:"10px",opacity:.7},children:[r.textures.loaded," / ",r.textures.total]})]}), -(0,g.jsx)("div",{className:"loading-ui-progress",children: (0,g.jsx)("div",{className:"bar",style:{width:100*c+"%"}})})]})}),Object.keys(e).length>=2&& (0,g.jsxs)("div",{className:"total-progress-section",style:{display:"block"},children:[ (0,g.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",fontSize:"12px",marginBottom:"5px"},children:[ (0,g.jsx)("span",{children:"TOTAL PROGRESS"}), (0,g.jsxs)("span",{className:"total-percent-text",children:[Math.floor(p),"%"]})]}), (0,g.jsx)("div",{className:"loading-ui-progress",style:{height:"8px",background:"#111"},children: (0,g.jsx)("div",{className:"total-progress-bar",style:{width:`${p}%`,background:"#4caf50",height:"100%",transition:"width 0.2s"}})})]})]})};Object.freeze(class{static idMaps=new Map;static getNextId(e){let t=this.idMaps.get(e)||0;return this.idMaps.set(e,t+1),t}});var re=console.log.bind(console),ae=h.lazy(()=>import("./GuiPanel-D7hqjzkr.js?t=1781132971803")),le=()=>{const e=x(e=>e.redGPUContext),t=x(e=>e.showSettingsPanel),o=x(e=>e.isNarrow),n=x(e=>e.setShowSourceModal),s=x(e=>e.setShowSettingsPanel),c=h.useRef(!1);h.useEffect(()=>{if(o&&t&&!c.current){c.current=!0;const e=setTimeout(()=>{s(!1),re("Auto close settings panel")},1e3);return()=>clearTimeout(e)}},[]),(()=>{const e=x(e=>e.setIsNarrow),t=(()=>{const[e,t]=(0,h.useState)(!1);return(0,h.useEffect)(()=>{const e=e=>{e.matches?t(!0):t(!1)},o=window.matchMedia("(max-width: 768px)");return o.addEventListener("change",e),o.matches&&t(!0),()=>o.removeEventListener("change",e)},[768]),e})();(0,h.useEffect)(()=>{e(t)},[t,e])})();const{setDebugActive:d}=(()=>{const e=x(e=>e.redGPUContext),t=x(e=>e.addTopBarRightAction),o=x(e=>e.guiConfig),n=x(e=>e.showSettingsPanel),s=x(e=>e.setShowSettingsPanel),[c,d]=(0,h.useState)(!1),[u,p]=(0,h.useState)(!1),[f,g]=(0,h.useState)(!1);return(0,h.useEffect)(()=>{if(e&&e.viewList.length>0){const t=e.viewList[e.viewList.length-1];d(!!t.axis),p(!!t.grid),window.redGPUInspector&&g(window.redGPUInspector.useDebugPanel)}},[e]),(0,h.useEffect)(()=>{e&&(t({id:"axis-toggle",label:"AXIS",icon:h.createElement(a,{color:"#ccc",size:18}),isActive:c,onClick:()=>{const t=!c;e.viewList.forEach(e=>{"axis"in e&&(e.axis=t)}),d(t)}}),t({id:"grid-toggle",label:"GRID",icon:h.createElement(l,{color:"#ccc",size:24}),isActive:u,onClick:()=>{const t=!u;e.viewList.forEach(e=>{"grid"in e&&(e.grid=t)}),p(t)}}),t({id:"debug-toggle",label:"DEBUG",icon:h.createElement(i,{color:"#ccc",size:24}),isActive:f,onClick:()=>{const e=!f;window.redGPUInspector&&(window.redGPUInspector.useDebugPanel=e),g(e)}}),(o?.redGPUContext||o?.viewList||o?.scene||o?.ibl||o?.skybox||o?.gui)&&t({id:"setting-toggle",label:"SETTING",icon:h.createElement(r,{color:"#ccc",size:24}),isActive:n,onClick:()=>{s(!n)}}))},[e,t,c,u,f,o,n,s]),{debugActive:f,setDebugActive:g}})();((e,t)=>{(0,h.useEffect)(()=>{e&&(async()=>{try{const{default:o}=await import(new URL("../../../inspector/dist/index.js?t=1781132971803",import.meta.url).href);window.redGPUInspector||(window.redGPUInspector=new o(e),t(window.redGPUInspector.useDebugPanel))}catch(o){console.error("Failed to load Inspector:",o)}})()},[e,t])})(e,d);const u={...ce,maxHeight:o?"calc(100vh - 160px)":"calc(100vh - 103px)",transform:t?"translateX(0)":"translateX(calc(100% + 10px))",opacity:t?1:0,pointerEvents:t?"auto":"none",transition:"transform 0.3s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.3s cubic-bezier(0.4, 0, 0.2, 1)"}; +(0,g.jsx)("div",{className:"loading-ui-progress",children: (0,g.jsx)("div",{className:"bar",style:{width:100*c+"%"}})})]})}),Object.keys(e).length>=2&& (0,g.jsxs)("div",{className:"total-progress-section",style:{display:"block"},children:[ (0,g.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",fontSize:"12px",marginBottom:"5px"},children:[ (0,g.jsx)("span",{children:"TOTAL PROGRESS"}), (0,g.jsxs)("span",{className:"total-percent-text",children:[Math.floor(p),"%"]})]}), (0,g.jsx)("div",{className:"loading-ui-progress",style:{height:"8px",background:"#111"},children: (0,g.jsx)("div",{className:"total-progress-bar",style:{width:`${p}%`,background:"#4caf50",height:"100%",transition:"width 0.2s"}})})]})]})};Object.freeze(class{static idMaps=new Map;static getNextId(e){let t=this.idMaps.get(e)||0;return this.idMaps.set(e,t+1),t}});var re=console.log.bind(console),ae=h.lazy(()=>import("./GuiPanel-D7hqjzkr.js?t=1781136546834")),le=()=>{const e=x(e=>e.redGPUContext),t=x(e=>e.showSettingsPanel),o=x(e=>e.isNarrow),n=x(e=>e.setShowSourceModal),s=x(e=>e.setShowSettingsPanel),c=h.useRef(!1);h.useEffect(()=>{if(o&&t&&!c.current){c.current=!0;const e=setTimeout(()=>{s(!1),re("Auto close settings panel")},1e3);return()=>clearTimeout(e)}},[]),(()=>{const e=x(e=>e.setIsNarrow),t=(()=>{const[e,t]=(0,h.useState)(!1);return(0,h.useEffect)(()=>{const e=e=>{e.matches?t(!0):t(!1)},o=window.matchMedia("(max-width: 768px)");return o.addEventListener("change",e),o.matches&&t(!0),()=>o.removeEventListener("change",e)},[768]),e})();(0,h.useEffect)(()=>{e(t)},[t,e])})();const{setDebugActive:d}=(()=>{const e=x(e=>e.redGPUContext),t=x(e=>e.addTopBarRightAction),o=x(e=>e.guiConfig),n=x(e=>e.showSettingsPanel),s=x(e=>e.setShowSettingsPanel),[c,d]=(0,h.useState)(!1),[u,p]=(0,h.useState)(!1),[f,g]=(0,h.useState)(!1);return(0,h.useEffect)(()=>{if(e&&e.viewList.length>0){const t=e.viewList[e.viewList.length-1];d(!!t.axis),p(!!t.grid),window.redGPUInspector&&g(window.redGPUInspector.useDebugPanel)}},[e]),(0,h.useEffect)(()=>{e&&(t({id:"axis-toggle",label:"AXIS",icon:h.createElement(a,{color:"#ccc",size:18}),isActive:c,onClick:()=>{const t=!c;e.viewList.forEach(e=>{"axis"in e&&(e.axis=t)}),d(t)}}),t({id:"grid-toggle",label:"GRID",icon:h.createElement(l,{color:"#ccc",size:24}),isActive:u,onClick:()=>{const t=!u;e.viewList.forEach(e=>{"grid"in e&&(e.grid=t)}),p(t)}}),t({id:"debug-toggle",label:"DEBUG",icon:h.createElement(i,{color:"#ccc",size:24}),isActive:f,onClick:()=>{const e=!f;window.redGPUInspector&&(window.redGPUInspector.useDebugPanel=e),g(e)}}),(o?.redGPUContext||o?.viewList||o?.scene||o?.ibl||o?.skybox||o?.gui)&&t({id:"setting-toggle",label:"SETTING",icon:h.createElement(r,{color:"#ccc",size:24}),isActive:n,onClick:()=>{s(!n)}}))},[e,t,c,u,f,o,n,s]),{debugActive:f,setDebugActive:g}})();((e,t)=>{(0,h.useEffect)(()=>{e&&(async()=>{try{const{default:o}=await import(new URL("../../../inspector/dist/index.js?t=1781136546834",import.meta.url).href);window.redGPUInspector||(window.redGPUInspector=new o(e),t(window.redGPUInspector.useDebugPanel))}catch(o){console.error("Failed to load Inspector:",o)}})()},[e,t])})(e,d);const u={...ce,maxHeight:o?"calc(100vh - 160px)":"calc(100vh - 103px)",transform:t?"translateX(0)":"translateX(calc(100% + 10px))",opacity:t?1:0,pointerEvents:t?"auto":"none",transition:"transform 0.3s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.3s cubic-bezier(0.4, 0, 0.2, 1)"}; return(0,g.jsxs)(g.Fragment,{children:[ (0,g.jsx)(G,{}), @@ -50,4 +50,4 @@ return(0,g.jsxs)(g.Fragment,{children:[ (0,g.jsx)(Y,{}), -(0,g.jsx)(se,{})]})},ce={position:"fixed",right:"6px",top:"60px",display:"flex",flexDirection:"column",color:"white",fontFamily:"monospace",zIndex:10002,borderLeft:"1px solid rgba(255,255,255,0.05)",overflow:"hidden"},de={fontSize:"12px",flex:1,overflowY:"auto",display:"flex",flexDirection:"column",gap:"24px"};function ue(e,t,o){var n,i,s,r,a,l,c,d,u,p,x,f,h=o[0],g=o[1],m=o[2];return t===e?(e[12]=t[0]*h+t[4]*g+t[8]*m+t[12],e[13]=t[1]*h+t[5]*g+t[9]*m+t[13],e[14]=t[2]*h+t[6]*g+t[10]*m+t[14],e[15]=t[3]*h+t[7]*g+t[11]*m+t[15]):(n=t[0],i=t[1],s=t[2],r=t[3],a=t[4],l=t[5],c=t[6],d=t[7],u=t[8],p=t[9],x=t[10],f=t[11],e[0]=n,e[1]=i,e[2]=s,e[3]=r,e[4]=a,e[5]=l,e[6]=c,e[7]=d,e[8]=u,e[9]=p,e[10]=x,e[11]=f,e[12]=n*h+a*g+u*m+t[12],e[13]=i*h+l*g+p*m+t[13],e[14]=s*h+c*g+x*m+t[14],e[15]=r*h+d*g+f*m+t[15]),e}var pe=Math.PI/180,xe=(e,t)=>{((e,t)=>{const{pixelRectObject:o}=t,n=e.parent,i=e.localMatrix;var s;(s=i)[0]=1,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=1,s[11]=0,s[12]=0,s[13]=0,s[14]=0,s[15]=1,ue(i,i,[e.x,e.y,e.z]),function(e,t,o){var n=Math.sin(o),i=Math.cos(o),s=t[0],r=t[1],a=t[2],l=t[3],c=t[8],d=t[9],u=t[10],p=t[11];t!==e&&(e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15]),e[0]=s*i-c*n,e[1]=r*i-d*n,e[2]=a*i-u*n,e[3]=l*i-p*n,e[8]=s*n+c*i,e[9]=r*n+d*i,e[10]=a*n+u*i,e[11]=l*n+p*i}(i,i,e.rotationY*pe),function(e,t,o){var n=Math.sin(o),i=Math.cos(o),s=t[4],r=t[5],a=t[6],l=t[7],c=t[8],d=t[9],u=t[10],p=t[11];t!==e&&(e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15]),e[4]=s*i+c*n,e[5]=r*i+d*n,e[6]=a*i+u*n,e[7]=l*i+p*n,e[8]=c*i-s*n,e[9]=d*i-r*n,e[10]=u*i-a*n,e[11]=p*i-l*n}(i,i,e.rotationX*pe),function(e,t,o){var n=Math.sin(o),i=Math.cos(o),s=t[0],r=t[1],a=t[2],l=t[3],c=t[4],d=t[5],u=t[6],p=t[7];t!==e&&(e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15]),e[0]=s*i+c*n,e[1]=r*i+d*n,e[2]=a*i+u*n,e[3]=l*i+p*n,e[4]=c*i-s*n,e[5]=d*i-r*n,e[6]=u*i-a*n,e[7]=p*i-l*n}(i,i,e.rotationZ*pe);let r=[e.scaleX,e.scaleY,e.scaleZ];e.renderTextureWidth&&(r[0]*=e.renderTextureWidth/o.height,r[1]*=e.renderTextureHeight/o.height),function(e,t,o){var n=o[0],i=o[1],s=o[2];e[0]=t[0]*n,e[1]=t[1]*n,e[2]=t[2]*n,e[3]=t[3]*n,e[4]=t[4]*i,e[5]=t[5]*i,e[6]=t[6]*i,e[7]=t[7]*i,e[8]=t[8]*s,e[9]=t[9]*s,e[10]=t[10]*s,e[11]=t[11]*s,e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15]}(i,i,r),(e.pivotX||e.pivotY||e.pivotZ)&&ue(i,i,[-e.pivotX,-e.pivotY,-e.pivotZ]),n?.modelMatrix?function(e,t,o){var n=t[0],i=t[1],s=t[2],r=t[3],a=t[4],l=t[5],c=t[6],d=t[7],u=t[8],p=t[9],x=t[10],f=t[11],h=t[12],g=t[13],m=t[14],b=t[15],w=o[0],v=o[1],j=o[2],y=o[3];e[0]=w*n+v*a+j*u+y*h,e[1]=w*i+v*l+j*p+y*g,e[2]=w*s+v*c+j*x+y*m,e[3]=w*r+v*d+j*f+y*b,w=o[4],v=o[5],j=o[6],y=o[7],e[4]=w*n+v*a+j*u+y*h,e[5]=w*i+v*l+j*p+y*g,e[6]=w*s+v*c+j*x+y*m,e[7]=w*r+v*d+j*f+y*b,w=o[8],v=o[9],j=o[10],y=o[11],e[8]=w*n+v*a+j*u+y*h,e[9]=w*i+v*l+j*p+y*g,e[10]=w*s+v*c+j*x+y*m,e[11]=w*r+v*d+j*f+y*b,w=o[12],v=o[13],j=o[14],y=o[15],e[12]=w*n+v*a+j*u+y*h,e[13]=w*i+v*l+j*p+y*g,e[14]=w*s+v*c+j*x+y*m,e[15]=w*r+v*d+j*f+y*b}(e.modelMatrix,n.modelMatrix,e.localMatrix):function(e,t){e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15]}(e.modelMatrix,e.localMatrix)})(e,t);let o=e.children.length;for(let n=0;n{x.getState().updateLoadingState(e)};static fitMeshToScreenCenter(e,t){const o=t.camera;xe(e,t);const n=e.combinedBoundingAABB;if(!n||n.minX===1/0||isNaN(n.centerX))return;const i=t.rawCamera.fieldOfView*Math.PI/180,s=Math.tan(i/2),r=s*t.aspect,a=n.xSize,l=n.ySize,c=n.zSize,d=a/2/r,u=l/2/s,p=1.15*Math.max(d,u)+c/2;if(o.centerX=n.centerX,o.centerY=n.centerY,o.centerZ=n.centerZ,o.distance=Math.max(p,2*t.rawCamera.nearClipping),o.distance<1){const t=1/o.distance;e.setScale(t),o.centerX*=t,o.centerY*=t,o.centerZ*=t,o.distance=1}o.speedDistance=Math.max(.1,.1*p)}root=null;domRoot=null;constructor(e,t){x.getState().setRedGPUContext(e),t&&("function"==typeof t?x.getState().setGuiConfig({gui:t}):(t.RedGPU&&x.getState().setRedGPU(t.RedGPU),x.getState().setGuiConfig(t))),this.init()}destroy(){this.root&&(this.root.unmount(),this.root=null),this.domRoot&&(this.domRoot.remove(),this.domRoot=null)}async init(){const e=await(async e=>{const{ExampleList:t}=await import("./exampleList-B00YxcCV.js?t=1781132971803").then(e=>e.n),o=e.replace(/\/$/,"").replace(/\/index\.html$/,"").replace(/.*\/examples\//,""),n=e=>{for(const t of e){if((t.path?t.path.replace(/\/$/,""):void 0)===o)return t;if(t.list){const e=n(t.list);if(e)return e}}return null};return n(t)})(window.location.pathname);x.getState().setCurrentExample(e),this.domRoot||(this.domRoot=document.createElement("div"),this.domRoot.className="RedGPUExampleHelper",document.body.appendChild(this.domRoot),this.root=f.createRoot(this.domRoot),this.root.render( (0,g.jsx)(h.StrictMode,{children: (0,g.jsx)(le,{})})))}};export{fe as default}; \ No newline at end of file +(0,g.jsx)(se,{})]})},ce={position:"fixed",right:"6px",top:"60px",display:"flex",flexDirection:"column",color:"white",fontFamily:"monospace",zIndex:10002,borderLeft:"1px solid rgba(255,255,255,0.05)",overflow:"hidden"},de={fontSize:"12px",flex:1,overflowY:"auto",display:"flex",flexDirection:"column",gap:"24px"};function ue(e,t,o){var n,i,s,r,a,l,c,d,u,p,x,f,h=o[0],g=o[1],m=o[2];return t===e?(e[12]=t[0]*h+t[4]*g+t[8]*m+t[12],e[13]=t[1]*h+t[5]*g+t[9]*m+t[13],e[14]=t[2]*h+t[6]*g+t[10]*m+t[14],e[15]=t[3]*h+t[7]*g+t[11]*m+t[15]):(n=t[0],i=t[1],s=t[2],r=t[3],a=t[4],l=t[5],c=t[6],d=t[7],u=t[8],p=t[9],x=t[10],f=t[11],e[0]=n,e[1]=i,e[2]=s,e[3]=r,e[4]=a,e[5]=l,e[6]=c,e[7]=d,e[8]=u,e[9]=p,e[10]=x,e[11]=f,e[12]=n*h+a*g+u*m+t[12],e[13]=i*h+l*g+p*m+t[13],e[14]=s*h+c*g+x*m+t[14],e[15]=r*h+d*g+f*m+t[15]),e}var pe=Math.PI/180,xe=(e,t)=>{((e,t)=>{const{pixelRectObject:o}=t,n=e.parent,i=e.localMatrix;var s;(s=i)[0]=1,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=1,s[11]=0,s[12]=0,s[13]=0,s[14]=0,s[15]=1,ue(i,i,[e.x,e.y,e.z]),function(e,t,o){var n=Math.sin(o),i=Math.cos(o),s=t[0],r=t[1],a=t[2],l=t[3],c=t[8],d=t[9],u=t[10],p=t[11];t!==e&&(e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15]),e[0]=s*i-c*n,e[1]=r*i-d*n,e[2]=a*i-u*n,e[3]=l*i-p*n,e[8]=s*n+c*i,e[9]=r*n+d*i,e[10]=a*n+u*i,e[11]=l*n+p*i}(i,i,e.rotationY*pe),function(e,t,o){var n=Math.sin(o),i=Math.cos(o),s=t[4],r=t[5],a=t[6],l=t[7],c=t[8],d=t[9],u=t[10],p=t[11];t!==e&&(e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15]),e[4]=s*i+c*n,e[5]=r*i+d*n,e[6]=a*i+u*n,e[7]=l*i+p*n,e[8]=c*i-s*n,e[9]=d*i-r*n,e[10]=u*i-a*n,e[11]=p*i-l*n}(i,i,e.rotationX*pe),function(e,t,o){var n=Math.sin(o),i=Math.cos(o),s=t[0],r=t[1],a=t[2],l=t[3],c=t[4],d=t[5],u=t[6],p=t[7];t!==e&&(e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15]),e[0]=s*i+c*n,e[1]=r*i+d*n,e[2]=a*i+u*n,e[3]=l*i+p*n,e[4]=c*i-s*n,e[5]=d*i-r*n,e[6]=u*i-a*n,e[7]=p*i-l*n}(i,i,e.rotationZ*pe);let r=[e.scaleX,e.scaleY,e.scaleZ];e.renderTextureWidth&&(r[0]*=e.renderTextureWidth/o.height,r[1]*=e.renderTextureHeight/o.height),function(e,t,o){var n=o[0],i=o[1],s=o[2];e[0]=t[0]*n,e[1]=t[1]*n,e[2]=t[2]*n,e[3]=t[3]*n,e[4]=t[4]*i,e[5]=t[5]*i,e[6]=t[6]*i,e[7]=t[7]*i,e[8]=t[8]*s,e[9]=t[9]*s,e[10]=t[10]*s,e[11]=t[11]*s,e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15]}(i,i,r),(e.pivotX||e.pivotY||e.pivotZ)&&ue(i,i,[-e.pivotX,-e.pivotY,-e.pivotZ]),n?.modelMatrix?function(e,t,o){var n=t[0],i=t[1],s=t[2],r=t[3],a=t[4],l=t[5],c=t[6],d=t[7],u=t[8],p=t[9],x=t[10],f=t[11],h=t[12],g=t[13],m=t[14],b=t[15],w=o[0],v=o[1],j=o[2],y=o[3];e[0]=w*n+v*a+j*u+y*h,e[1]=w*i+v*l+j*p+y*g,e[2]=w*s+v*c+j*x+y*m,e[3]=w*r+v*d+j*f+y*b,w=o[4],v=o[5],j=o[6],y=o[7],e[4]=w*n+v*a+j*u+y*h,e[5]=w*i+v*l+j*p+y*g,e[6]=w*s+v*c+j*x+y*m,e[7]=w*r+v*d+j*f+y*b,w=o[8],v=o[9],j=o[10],y=o[11],e[8]=w*n+v*a+j*u+y*h,e[9]=w*i+v*l+j*p+y*g,e[10]=w*s+v*c+j*x+y*m,e[11]=w*r+v*d+j*f+y*b,w=o[12],v=o[13],j=o[14],y=o[15],e[12]=w*n+v*a+j*u+y*h,e[13]=w*i+v*l+j*p+y*g,e[14]=w*s+v*c+j*x+y*m,e[15]=w*r+v*d+j*f+y*b}(e.modelMatrix,n.modelMatrix,e.localMatrix):function(e,t){e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15]}(e.modelMatrix,e.localMatrix)})(e,t);let o=e.children.length;for(let n=0;n{x.getState().updateLoadingState(e)};static fitMeshToScreenCenter(e,t){const o=t.camera;xe(e,t);const n=e.combinedBoundingAABB;if(!n||n.minX===1/0||isNaN(n.centerX))return;const i=t.rawCamera.fieldOfView*Math.PI/180,s=Math.tan(i/2),r=s*t.aspect,a=n.xSize,l=n.ySize,c=n.zSize,d=a/2/r,u=l/2/s,p=1.15*Math.max(d,u)+c/2;if(o.centerX=n.centerX,o.centerY=n.centerY,o.centerZ=n.centerZ,o.distance=Math.max(p,2*t.rawCamera.nearClipping),o.distance<1){const t=1/o.distance;e.setScale(t),o.centerX*=t,o.centerY*=t,o.centerZ*=t,o.distance=1}o.speedDistance=Math.max(.1,.1*p)}root=null;domRoot=null;constructor(e,t){x.getState().setRedGPUContext(e),t&&("function"==typeof t?x.getState().setGuiConfig({gui:t}):(t.RedGPU&&x.getState().setRedGPU(t.RedGPU),x.getState().setGuiConfig(t))),this.init()}destroy(){this.root&&(this.root.unmount(),this.root=null),this.domRoot&&(this.domRoot.remove(),this.domRoot=null)}async init(){const e=await(async e=>{const{ExampleList:t}=await import("./exampleList-B00YxcCV.js?t=1781136546834").then(e=>e.n),o=e.replace(/\/$/,"").replace(/\/index\.html$/,"").replace(/.*\/examples\//,""),n=e=>{for(const t of e){if((t.path?t.path.replace(/\/$/,""):void 0)===o)return t;if(t.list){const e=n(t.list);if(e)return e}}return null};return n(t)})(window.location.pathname);x.getState().setCurrentExample(e),this.domRoot||(this.domRoot=document.createElement("div"),this.domRoot.className="RedGPUExampleHelper",document.body.appendChild(this.domRoot),this.root=f.createRoot(this.domRoot),this.root.render( (0,g.jsx)(h.StrictMode,{children: (0,g.jsx)(le,{})})))}};export{fe as default}; \ No newline at end of file diff --git a/examples/exampleHelper/dist/store-2JcZHIgY.js b/examples/exampleHelper/dist/store-2JcZHIgY.js index a619fa3b52..aeed414707 100644 --- a/examples/exampleHelper/dist/store-2JcZHIgY.js +++ b/examples/exampleHelper/dist/store-2JcZHIgY.js @@ -1 +1 @@ -import{d as t}from"./IconButton-D8-442jY.js?t=1781132971803";var e=t(t=>({RedGPU:null,redGPUContext:null,currentExample:null,language:"undefined"!=typeof navigator&&navigator.language.startsWith("ko")?"ko":"en",showSourceModal:!1,showSettingsPanel:!1,topBarRightActions:[],guiConfig:null,isNarrow:"undefined"!=typeof window&&window.innerWidth<=768,loadingStates:{},setRedGPU:e=>t({RedGPU:e}),setRedGPUContext:e=>t({redGPUContext:e}),setCurrentExample:e=>t({currentExample:e}),setLanguage:e=>t({language:e}),setShowSourceModal:e=>t({showSourceModal:e}),setShowSettingsPanel:e=>t({showSettingsPanel:e}),addTopBarRightAction:e=>t(t=>({topBarRightActions:[...t.topBarRightActions.filter(t=>t.id!==e.id),e]})),removeTopBarRightAction:e=>t(t=>({topBarRightActions:t.topBarRightActions.filter(t=>t.id!==e)})),clearTopBarRightActions:()=>t({topBarRightActions:[]}),setGuiConfig:e=>{t({guiConfig:e,showSettingsPanel:!!(e?.redGPUContext||e?.viewList||e?.scene||e?.ibl||e?.skybox||e?.gui)})},setIsNarrow:e=>t({isNarrow:e}),updateLoadingState:e=>t(t=>{const o=e.url||"default";return{loadingStates:{...t.loadingStates,[o]:e}}}),clearLoadingStates:()=>t({loadingStates:{}})}));export{e as t}; \ No newline at end of file +import{d as t}from"./IconButton-D8-442jY.js?t=1781136546834";var e=t(t=>({RedGPU:null,redGPUContext:null,currentExample:null,language:"undefined"!=typeof navigator&&navigator.language.startsWith("ko")?"ko":"en",showSourceModal:!1,showSettingsPanel:!1,topBarRightActions:[],guiConfig:null,isNarrow:"undefined"!=typeof window&&window.innerWidth<=768,loadingStates:{},setRedGPU:e=>t({RedGPU:e}),setRedGPUContext:e=>t({redGPUContext:e}),setCurrentExample:e=>t({currentExample:e}),setLanguage:e=>t({language:e}),setShowSourceModal:e=>t({showSourceModal:e}),setShowSettingsPanel:e=>t({showSettingsPanel:e}),addTopBarRightAction:e=>t(t=>({topBarRightActions:[...t.topBarRightActions.filter(t=>t.id!==e.id),e]})),removeTopBarRightAction:e=>t(t=>({topBarRightActions:t.topBarRightActions.filter(t=>t.id!==e)})),clearTopBarRightActions:()=>t({topBarRightActions:[]}),setGuiConfig:e=>{t({guiConfig:e,showSettingsPanel:!!(e?.redGPUContext||e?.viewList||e?.scene||e?.ibl||e?.skybox||e?.gui)})},setIsNarrow:e=>t({isNarrow:e}),updateLoadingState:e=>t(t=>{const o=e.url||"default";return{loadingStates:{...t.loadingStates,[o]:e}}}),clearLoadingStates:()=>t({loadingStates:{}})}));export{e as t}; \ No newline at end of file diff --git a/examples/exampleHelper/dist/vendor-react-BwJpJ84T.js b/examples/exampleHelper/dist/vendor-react-BwJpJ84T.js index de2daf9542..b6665db4ba 100644 --- a/examples/exampleHelper/dist/vendor-react-BwJpJ84T.js +++ b/examples/exampleHelper/dist/vendor-react-BwJpJ84T.js @@ -1 +1 @@ -import{t as e}from"./rolldown-runtime-BztV3taV.js?t=1781132971803";var t=e(e=>{var t=Symbol.for("react.transitional.element"),n=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),l=Symbol.for("react.strict_mode"),a=Symbol.for("react.profiler"),o=Symbol.for("react.consumer"),i=Symbol.for("react.context"),u=Symbol.for("react.forward_ref"),s=Symbol.for("react.suspense"),c=Symbol.for("react.memo"),f=Symbol.for("react.lazy"),d=Symbol.for("react.activity"),p=Symbol.iterator,m={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},h=Object.assign,g={};function y(e,t,n){this.props=e,this.context=t,this.refs=g,this.updater=n||m}function v(){}function b(e,t,n){this.props=e,this.context=t,this.refs=g,this.updater=n||m}y.prototype.isReactComponent={},y.prototype.setState=function(e,t){if("object"!=typeof e&&"function"!=typeof e&&null!=e)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")},y.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")},v.prototype=y.prototype;var k=b.prototype=new v;k.constructor=b,h(k,y.prototype),k.isPureReactComponent=!0;var w=Array.isArray;function S(){}var E={H:null,A:null,T:null,S:null},C=Object.prototype.hasOwnProperty;function x(e,n,r){var l=r.ref;return{$$typeof:t,type:e,key:n,ref:void 0!==l?l:null,props:r}}function z(e){return"object"==typeof e&&null!==e&&e.$$typeof===t}var _=/\/+/g;function P(e,t){return"object"==typeof e&&null!==e&&null!=e.key?(n=""+e.key,r={"=":"=0",":":"=2"},"$"+n.replace(/[=:]/g,function(e){return r[e]})):t.toString(36);var n,r}function N(e,r,l,a,o){var i=typeof e;"undefined"!==i&&"boolean"!==i||(e=null);var u,s,c=!1;if(null===e)c=!0;else switch(i){case"bigint":case"string":case"number":c=!0;break;case"object":switch(e.$$typeof){case t:case n:c=!0;break;case f:return N((c=e._init)(e._payload),r,l,a,o)}}if(c)return o=o(e),c=""===a?"."+P(e,0):a,w(o)?(l="",null!=c&&(l=c.replace(_,"$&/")+"/"),N(o,r,l,"",function(e){return e})):null!=o&&(z(o)&&(u=o,s=l+(null==o.key||e&&e.key===o.key?"":(""+o.key).replace(_,"$&/")+"/")+c,o=x(u.type,s,u.props)),r.push(o)),1;c=0;var d,m=""===a?".":a+":";if(w(e))for(var h=0;h{n.exports=t()}),r=e(e=>{function t(e,t){var n=e.length;e.push(t);e:for(;0>>1,a=e[r];if(!(0>>1;rl(u,n))sl(c,u)?(e[r]=c,e[s]=n,r=s):(e[r]=u,e[i]=n,r=i);else{if(!(sl(c,n)))break e;e[r]=c,e[s]=n,r=s}}}return t}function l(e,t){var n=e.sortIndex-t.sortIndex;return 0!==n?n:e.id-t.id}if(e.unstable_now=void 0,"object"==typeof performance&&"function"==typeof performance.now){var a=performance;e.unstable_now=function(){return a.now()}}else{var o=Date,i=o.now();e.unstable_now=function(){return o.now()-i}}var u=[],s=[],c=1,f=null,d=3,p=!1,m=!1,h=!1,g=!1,y="function"==typeof setTimeout?setTimeout:null,v="function"==typeof clearTimeout?clearTimeout:null,b="undefined"!=typeof setImmediate?setImmediate:null;function k(e){for(var l=n(s);null!==l;){if(null===l.callback)r(s);else{if(!(l.startTime<=e))break;r(s),l.sortIndex=l.expirationTime,t(u,l)}l=n(s)}}function w(e){if(h=!1,k(e),!m)if(null!==n(u))m=!0,E||(E=!0,S());else{var t=n(s);null!==t&&L(w,t.startTime-e)}}var S,E=!1,C=-1,x=5,z=-1;function _(){return!(!g&&e.unstable_now()-zt&&_());){var o=f.callback;if("function"==typeof o){f.callback=null,d=f.priorityLevel;var i=o(f.expirationTime<=t);if(t=e.unstable_now(),"function"==typeof i){f.callback=i,k(t),l=!0;break t}f===n(u)&&r(u),k(t)}else r(u);f=n(u)}if(null!==f)l=!0;else{var c=n(s);null!==c&&L(w,c.startTime-t),l=!1}}break e}finally{f=null,d=a,p=!1}l=void 0}}finally{l?S():E=!1}}}if("function"==typeof b)S=function(){b(P)};else if("undefined"!=typeof MessageChannel){var N=new MessageChannel,T=N.port2;N.port1.onmessage=P,S=function(){T.postMessage(null)}}else S=function(){y(P,0)};function L(t,n){C=y(function(){t(e.unstable_now())},n)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(e){e.callback=null},e.unstable_forceFrameRate=function(e){0>e||125o?(r.sortIndex=a,t(s,r),null===n(u)&&r===n(s)&&(h?(v(C),C=-1):h=!0,L(w,a-o))):(r.sortIndex=i,t(u,r),m||p||(m=!0,E||(E=!0,S()))),r},e.unstable_shouldYield=_,e.unstable_wrapCallback=function(e){var t=d;return function(){var n=d;d=t;try{return e.apply(this,arguments)}finally{d=n}}}}),l=e((e,t)=>{t.exports=r()}),a=e(e=>{var t=n();function r(e){var t="https://react.dev/errors/"+e;if(1{!function e(){if("undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE)try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}(),t.exports=a()}),i=e(e=>{var t=l(),r=n(),a=o();function i(e){var t="https://react.dev/errors/"+e;if(1I||(e.current=M[I],M[I]=null,I--)}function H(e,t){I++,M[I]=e.current,e.current=t}var $,V,B=U(null),Q=U(null),W=U(null),q=U(null);function K(e,t){switch(H(W,t),H(Q,e),H(B,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?vf(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)e=bf(t=vf(t),e);else switch(e){case"svg":e=1;break;case"math":e=2;break;default:e=0}}j(B),H(B,e)}function Y(){j(B),j(Q),j(W)}function G(e){null!==e.memoizedState&&H(q,e);var t=B.current,n=bf(t,e.type);t!==n&&(H(Q,e),H(B,n))}function X(e){Q.current===e&&(j(B),j(Q)),q.current===e&&(j(q),fd._currentValue=A)}function Z(e){if(void 0===$)try{throw Error()}catch(n){var t=n.stack.trim().match(/\n( *(at )?)/);$=t&&t[1]||"",V=-1)":-1--l||u[r]!==s[l]){var c="\n"+u[r].replace(" at new "," at ");return e.displayName&&c.includes("")&&(c=c.replace("",e.displayName)),c}}while(1<=r&&0<=l);break}}}finally{J=!1,Error.prepareStackTrace=n}return(n=e?e.displayName||e.name:"")?Z(n):""}function te(e,t){switch(e.tag){case 26:case 27:case 5:return Z(e.type);case 16:return Z("Lazy");case 13:return e.child!==t&&null!==t?Z("Suspense Fallback"):Z("Suspense");case 19:return Z("SuspenseList");case 0:case 15:return ee(e.type,!1);case 11:return ee(e.type.render,!1);case 1:return ee(e.type,!0);case 31:return Z("Activity");default:return""}}function ne(e){try{var t="",n=null;do{t+=te(e,n),n=e,e=e.return}while(e);return t}catch(r){return"\nError generating stack: "+r.message+"\n"+r.stack}}var re=Object.prototype.hasOwnProperty,le=t.unstable_scheduleCallback,ae=t.unstable_cancelCallback,oe=t.unstable_shouldYield,ie=t.unstable_requestPaint,ue=t.unstable_now,se=t.unstable_getCurrentPriorityLevel,ce=t.unstable_ImmediatePriority,fe=t.unstable_UserBlockingPriority,de=t.unstable_NormalPriority,pe=t.unstable_LowPriority,me=t.unstable_IdlePriority,he=t.log,ge=t.unstable_setDisableYieldValue,ye=null,ve=null;function be(e){if("function"==typeof he&&ge(e),ve&&"function"==typeof ve.setStrictMode)try{ve.setStrictMode(ye,e)}catch(t){}}var ke=Math.clz32?Math.clz32:function(e){return 0==(e>>>=0)?32:31-(we(e)/Se|0)|0},we=Math.log,Se=Math.LN2,Ee=256,Ce=262144,xe=4194304;function ze(e){var t=42&e;if(0!==t)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return 261888&e;case 262144:case 524288:case 1048576:case 2097152:return 3932160&e;case 4194304:case 8388608:case 16777216:case 33554432:return 62914560&e;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function _e(e,t,n){var r=e.pendingLanes;if(0===r)return 0;var l=0,a=e.suspendedLanes,o=e.pingedLanes;e=e.warmLanes;var i=134217727&r;return 0!==i?0!==(r=i&~a)?l=ze(r):0!==(o&=i)?l=ze(o):n||0!==(n=i&~e)&&(l=ze(n)):0!==(i=r&~a)?l=ze(i):0!==o?l=ze(o):n||0!==(n=r&~e)&&(l=ze(n)),0===l?0:0!==t&&t!==l&&0===(t&a)&&((a=l&-l)>=(n=t&-t)||32===a&&4194048&n)?t:l}function Pe(e,t){return 0===(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)}function Ne(e,t){switch(e){case 1:case 2:case 4:case 8:case 64:return t+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;default:return-1}}function Te(){var e=xe;return!(62914560&(xe<<=1))&&(xe=4194304),e}function Le(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function Oe(e,t){e.pendingLanes|=t,268435456!==t&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function De(e,t,n){e.pendingLanes|=t,e.suspendedLanes&=~t;var r=31-ke(t);e.entangledLanes|=t,e.entanglements[r]=1073741824|e.entanglements[r]|261930&n}function Fe(e,t){var n=e.entangledLanes|=t;for(e=e.entanglements;n;){var r=31-ke(n),l=1<=zn),Nn=String.fromCharCode(32),Tn=!1;function Ln(e,t){switch(e){case"keyup":return-1!==Cn.indexOf(t.keyCode);case"keydown":return 229!==t.keyCode;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function On(e){return"object"==typeof(e=e.detail)&&"data"in e?e.data:null}var Dn=!1,Fn={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function Rn(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return"input"===t?!!Fn[e.type]:"textarea"===t}function An(e,t,n,r){Rt?At?At.push(r):At=[r]:Rt=r,0<(t=rf(t,"onChange")).length&&(n=new nn("onChange","change",null,n,r),e.push({event:n,listeners:t}))}var Mn=null,In=null;function Un(e){Yc(e,0)}function jn(e){if(mt(Ze(e)))return e}function Hn(e,t){if("change"===e)return t}var $n=!1;if(Ht){var Vn;if(Ht){var Bn="oninput"in document;if(!Bn){var Qn=document.createElement("div");Qn.setAttribute("oninput","return;"),Bn="function"==typeof Qn.oninput}Vn=Bn}else Vn=!1;$n=Vn&&(!document.documentMode||9=t)return{node:r,offset:t-e};e=n}e:{for(;r;){if(r.nextSibling){r=r.nextSibling;break e}r=r.parentNode}r=void 0}r=er(r)}}function nr(e,t){return!(!e||!t)&&(e===t||(!e||3!==e.nodeType)&&(t&&3===t.nodeType?nr(e,t.parentNode):"contains"in e?e.contains(t):!!e.compareDocumentPosition&&!!(16&e.compareDocumentPosition(t))))}function rr(e){for(var t=ht((e=null!=e&&null!=e.ownerDocument&&null!=e.ownerDocument.defaultView?e.ownerDocument.defaultView:window).document);t instanceof e.HTMLIFrameElement;){try{var n="string"==typeof t.contentWindow.location.href}catch(r){n=!1}if(!n)break;t=ht((e=t.contentWindow).document)}return t}function lr(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&("input"===t&&("text"===e.type||"search"===e.type||"tel"===e.type||"url"===e.type||"password"===e.type)||"textarea"===t||"true"===e.contentEditable)}var ar=Ht&&"documentMode"in document&&11>=document.documentMode,or=null,ir=null,ur=null,sr=!1;function cr(e,t,n){var r=n.window===n?n.document:9===n.nodeType?n:n.ownerDocument;sr||null==or||or!==ht(r)||(r="selectionStart"in(r=or)&&lr(r)?{start:r.selectionStart,end:r.selectionEnd}:{anchorNode:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection()).anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset},ur&&Jn(ur,r)||(ur=r,0<(r=rf(ir,"onSelect")).length&&(t=new nn("onSelect","select",null,t,n),e.push({event:t,listeners:r}),t.target=or)))}function fr(e,t){var n={};return n[e.toLowerCase()]=t.toLowerCase(),n["Webkit"+e]="webkit"+t,n["Moz"+e]="moz"+t,n}var dr={animationend:fr("Animation","AnimationEnd"),animationiteration:fr("Animation","AnimationIteration"),animationstart:fr("Animation","AnimationStart"),transitionrun:fr("Transition","TransitionRun"),transitionstart:fr("Transition","TransitionStart"),transitioncancel:fr("Transition","TransitionCancel"),transitionend:fr("Transition","TransitionEnd")},pr={},mr={};function hr(e){if(pr[e])return pr[e];if(!dr[e])return e;var t,n=dr[e];for(t in n)if(n.hasOwnProperty(t)&&t in mr)return pr[e]=n[t];return e}Ht&&(mr=document.createElement("div").style,"AnimationEvent"in window||(delete dr.animationend.animation,delete dr.animationiteration.animation,delete dr.animationstart.animation),"TransitionEvent"in window||delete dr.transitionend.transition);var gr=hr("animationend"),yr=hr("animationiteration"),vr=hr("animationstart"),br=hr("transitionrun"),kr=hr("transitionstart"),wr=hr("transitioncancel"),Sr=hr("transitionend"),Er=new Map,Cr="abort auxClick beforeToggle cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");function xr(e,t){Er.set(e,t),rt(t,[e])}Cr.push("scrollEnd");var zr="function"==typeof reportError?reportError:function(e){if("object"==typeof window&&"function"==typeof window.ErrorEvent){var t=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:"object"==typeof e&&null!==e&&"string"==typeof e.message?String(e.message):String(e),error:e});if(!window.dispatchEvent(t))return}else if("object"==typeof process&&"function"==typeof process.emit)return void process.emit("uncaughtException",e);console.error(e)},_r=[],Pr=0,Nr=0;function Tr(){for(var e=Pr,t=Nr=Pr=0;t>=o,l-=o,nl=1<<32-ke(t)+l|n<h?(g=f,f=null):g=f.sibling;var y=p(l,f,i[h],u);if(null===y){null===f&&(f=g);break}e&&f&&null===y.alternate&&t(l,f),o=a(y,o,h),null===c?s=y:c.sibling=y,c=y,f=g}if(h===i.length)return n(l,f),fl&&ll(l,h),s;if(null===f){for(;hg?(y=h,h=null):y=h.sibling;var b=p(l,h,v.value,s);if(null===b){null===h&&(h=y);break}e&&h&&null===b.alternate&&t(l,h),o=a(b,o,g),null===f?c=b:f.sibling=b,f=b,h=y}if(v.done)return n(l,h),fl&&ll(l,g),c;if(null===h){for(;!v.done;g++,v=u.next())null!==(v=d(l,v.value,s))&&(o=a(v,o,g),null===f?c=v:f.sibling=v,f=v);return fl&&ll(l,g),c}for(h=r(h);!v.done;g++,v=u.next())null!==(v=m(h,l,g,v.value,s))&&(e&&null!==v.alternate&&h.delete(null===v.key?g:v.key),o=a(v,o,g),null===f?c=v:f.sibling=v,f=v);return e&&h.forEach(function(e){return t(l,e)}),fl&&ll(l,g),c}(u,s,c=b.call(c),f)}if("function"==typeof c.then)return v(u,s,sa(c),f);if(c.$$typeof===w)return v(u,s,Dl(u,c),f);fa(u,c)}return"string"==typeof c&&""!==c||"number"==typeof c||"bigint"==typeof c?(c=""+c,null!==s&&6===s.tag?(n(u,s.sibling),(f=l(s,c)).return=u,u=f):(n(u,s),(f=Br(c,u.mode,f)).return=u,u=f),o(u)):n(u,s)}return function(e,t,n,r){try{ua=0;var l=v(e,t,n,r);return ia=null,l}catch(o){if(o===Xl||o===Jl)throw o;var a=Ir(29,o,null,e.mode);return a.lanes=r,a.return=e,a}}}var pa=da(!0),ma=da(!1),ha=!1;function ga(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function ya(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function va(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function ba(e,t,n){var r=e.updateQueue;if(null===r)return null;if(r=r.shared,2&ps){var l=r.pending;return null===l?t.next=t:(t.next=l.next,l.next=t),r.pending=t,t=Rr(e),Fr(e,null,n),t}return Lr(e,r,t,n),Rr(e)}function ka(e,t,n){if(null!==(t=t.updateQueue)&&(t=t.shared,4194048&n)){var r=t.lanes;n|=r&=e.pendingLanes,t.lanes=n,Fe(e,n)}}function wa(e,t){var n=e.updateQueue,r=e.alternate;if(null!==r&&n===(r=r.updateQueue)){var l=null,a=null;if(null!==(n=n.firstBaseUpdate)){do{var o={lane:n.lane,tag:n.tag,payload:n.payload,callback:null,next:null};null===a?l=a=o:a=a.next=o,n=n.next}while(null!==n);null===a?l=a=t:a=a.next=t}else l=a=t;return n={baseState:r.baseState,firstBaseUpdate:l,lastBaseUpdate:a,shared:r.shared,callbacks:r.callbacks},void(e.updateQueue=n)}null===(e=n.lastBaseUpdate)?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}var Sa=!1;function Ea(){if(Sa&&null!==Bl)throw Bl}function Ca(e,t,n,r){Sa=!1;var l=e.updateQueue;ha=!1;var a=l.firstBaseUpdate,o=l.lastBaseUpdate,i=l.shared.pending;if(null!==i){l.shared.pending=null;var u=i,s=u.next;u.next=null,null===o?a=s:o.next=s,o=u;var c=e.alternate;null!==c&&(i=(c=c.updateQueue).lastBaseUpdate)!==o&&(null===i?c.firstBaseUpdate=s:i.next=s,c.lastBaseUpdate=u)}if(null!==a){var f=l.baseState;for(o=0,c=s=u=null,i=a;;){var d=-536870913&i.lane,m=d!==i.lane;if(m?(gs&d)===d:(r&d)===d){0!==d&&d===Vl&&(Sa=!0),null!==c&&(c=c.next={lane:0,tag:i.tag,payload:i.payload,callback:null,next:null});e:{var h=e,g=i;d=t;var y=n;switch(g.tag){case 1:if("function"==typeof(h=g.payload)){f=h.call(y,f,d);break e}f=h;break e;case 3:h.flags=-65537&h.flags|128;case 0:if(null==(d="function"==typeof(h=g.payload)?h.call(y,f,d):h))break e;f=p({},f,d);break e;case 2:ha=!0}}null!==(d=i.callback)&&(e.flags|=64,m&&(e.flags|=8192),null===(m=l.callbacks)?l.callbacks=[d]:m.push(d))}else m={lane:d,tag:i.tag,payload:i.payload,callback:i.callback,next:null},null===c?(s=c=m,u=f):c=c.next=m,o|=d;if(null===(i=i.next)){if(null===(i=l.shared.pending))break;i=(m=i).next,m.next=null,l.lastBaseUpdate=m,l.shared.pending=null}}null===c&&(u=f),l.baseState=u,l.firstBaseUpdate=s,l.lastBaseUpdate=c,null===a&&(l.shared.lanes=0),Cs|=o,e.lanes=o,e.memoizedState=f}}function xa(e,t){if("function"!=typeof e)throw Error(i(191,e));e.call(t)}function za(e,t){var n=e.callbacks;if(null!==n)for(e.callbacks=null,e=0;ea?a:8;var o,i,u,s=F.T,c={};F.T=c,fi(e,!1,t,n);try{var f=l(),d=F.S;null!==d&&d(c,f),null!==f&&"object"==typeof f&&"function"==typeof f.then?ci(e,t,(o=r,i=[],u={status:"pending",value:null,reason:null,then:function(e){i.push(e)}},f.then(function(){u.status="fulfilled",u.value=o;for(var e=0;e<\/script>",a=a.removeChild(a.firstChild);break;case"select":a="string"==typeof r.is?o.createElement("select",{is:r.is}):o.createElement("select"),r.multiple?a.multiple=!0:r.size&&(a.size=r.size);break;default:a="string"==typeof r.is?o.createElement(l,{is:r.is}):o.createElement(l)}}a[He]=t,a[$e]=r;e:for(o=t.child;null!==o;){if(5===o.tag||6===o.tag)a.appendChild(o.stateNode);else if(4!==o.tag&&27!==o.tag&&null!==o.child){o.child.return=o,o=o.child;continue}if(o===t)break e;for(;null===o.sibling;){if(null===o.return||o.return===t)break e;o=o.return}o.sibling.return=o.return,o=o.sibling}t.stateNode=a;e:switch(pf(a,l,r),l){case"button":case"input":case"select":case"textarea":r=!!r.autoFocus;break e;case"img":r=!0;break e;default:r=!1}r&&iu(t)}}return du(t),uu(t,t.type,null===e||e.memoizedProps,t.pendingProps,n),null;case 6:if(e&&null!=t.stateNode)e.memoizedProps!==r&&iu(t);else{if("string"!=typeof r&&null===t.stateNode)throw Error(i(166));if(e=W.current,vl(t)){if(e=t.stateNode,n=t.memoizedProps,r=null,null!==(l=sl))switch(l.tag){case 27:case 5:r=l.memoizedProps}e[He]=t,(e=!!(e.nodeValue===n||null!==r&&!0===r.suppressHydrationWarning||cf(e.nodeValue,n)))||hl(t,!0)}else(e=yf(e).createTextNode(r))[He]=t,t.stateNode=e}return du(t),null;case 31:if(n=t.memoizedState,null===e||null!==e.memoizedState){if(r=vl(t),null!==n){if(null===e){if(!r)throw Error(i(318));if(!(e=null!==(e=t.memoizedState)?e.dehydrated:null))throw Error(i(557));e[He]=t}else bl(),!(128&t.flags)&&(t.memoizedState=null),t.flags|=4;du(t),e=!1}else n=kl(),null!==e&&null!==e.memoizedState&&(e.memoizedState.hydrationErrors=n),e=!0;if(!e)return 256&t.flags?(Ia(t),t):(Ia(t),null);if(128&t.flags)throw Error(i(558))}return du(t),null;case 13:if(r=t.memoizedState,null===e||null!==e.memoizedState&&null!==e.memoizedState.dehydrated){if(l=vl(t),null!==r&&null!==r.dehydrated){if(null===e){if(!l)throw Error(i(318));if(!(l=null!==(l=t.memoizedState)?l.dehydrated:null))throw Error(i(317));l[He]=t}else bl(),!(128&t.flags)&&(t.memoizedState=null),t.flags|=4;du(t),l=!1}else l=kl(),null!==e&&null!==e.memoizedState&&(e.memoizedState.hydrationErrors=l),l=!0;if(!l)return 256&t.flags?(Ia(t),t):(Ia(t),null)}return Ia(t),128&t.flags?(t.lanes=n,t):(n=null!==r,e=null!==e&&null!==e.memoizedState,n&&(l=null,null!==(r=t.child).alternate&&null!==r.alternate.memoizedState&&null!==r.alternate.memoizedState.cachePool&&(l=r.alternate.memoizedState.cachePool.pool),a=null,null!==r.memoizedState&&null!==r.memoizedState.cachePool&&(a=r.memoizedState.cachePool.pool),a!==l&&(r.flags|=2048)),n!==e&&n&&(t.child.flags|=8192),cu(t,t.updateQueue),du(t),null);case 4:return Y(),null===e&&Jc(t.stateNode.containerInfo),du(t),null;case 10:return zl(t.type),du(t),null;case 19:if(j(Ua),null===(r=t.memoizedState))return du(t),null;if(l=!!(128&t.flags),null===(a=r.rendering))if(l)fu(r,!1);else{if(0!==Es||null!==e&&128&e.flags)for(e=t.child;null!==e;){if(null!==(a=ja(e))){for(t.flags|=128,fu(r,!1),e=a.updateQueue,t.updateQueue=e,cu(t,e),t.subtreeFlags=0,e=n,n=t.child;null!==n;)Hr(n,e),n=n.sibling;return H(Ua,1&Ua.current|2),fl&&ll(t,r.treeForkCount),t.child}e=e.sibling}null!==r.tail&&ue()>Fs&&(t.flags|=128,l=!0,fu(r,!1),t.lanes=4194304)}else{if(!l)if(null!==(e=ja(a))){if(t.flags|=128,l=!0,e=e.updateQueue,t.updateQueue=e,cu(t,e),fu(r,!0),null===r.tail&&"hidden"===r.tailMode&&!a.alternate&&!fl)return du(t),null}else 2*ue()-r.renderingStartTime>Fs&&536870912!==n&&(t.flags|=128,l=!0,fu(r,!1),t.lanes=4194304);r.isBackwards?(a.sibling=t.child,t.child=a):(null!==(e=r.last)?e.sibling=a:t.child=a,r.last=a)}return null!==r.tail?(e=r.tail,r.rendering=e,r.tail=e.sibling,r.renderingStartTime=ue(),e.sibling=null,n=Ua.current,H(Ua,l?1&n|2:1&n),fl&&ll(t,r.treeForkCount),e):(du(t),null);case 22:case 23:return Ia(t),La(),r=null!==t.memoizedState,null!==e?null!==e.memoizedState!==r&&(t.flags|=8192):r&&(t.flags|=8192),r?!!(536870912&n)&&!(128&t.flags)&&(du(t),6&t.subtreeFlags&&(t.flags|=8192)):du(t),null!==(n=t.updateQueue)&&cu(t,n.retryQueue),n=null,null!==e&&null!==e.memoizedState&&null!==e.memoizedState.cachePool&&(n=e.memoizedState.cachePool.pool),r=null,null!==t.memoizedState&&null!==t.memoizedState.cachePool&&(r=t.memoizedState.cachePool.pool),r!==n&&(t.flags|=2048),null!==e&&j(ql),null;case 24:return n=null,null!==e&&(n=e.memoizedState.cache),t.memoizedState.cache!==n&&(t.flags|=2048),zl(Il),du(t),null;case 25:case 30:return null}throw Error(i(156,t.tag))}function mu(e,t){switch(il(t),t.tag){case 1:return 65536&(e=t.flags)?(t.flags=-65537&e|128,t):null;case 3:return zl(Il),Y(),65536&(e=t.flags)&&!(128&e)?(t.flags=-65537&e|128,t):null;case 26:case 27:case 5:return X(t),null;case 31:if(null!==t.memoizedState){if(Ia(t),null===t.alternate)throw Error(i(340));bl()}return 65536&(e=t.flags)?(t.flags=-65537&e|128,t):null;case 13:if(Ia(t),null!==(e=t.memoizedState)&&null!==e.dehydrated){if(null===t.alternate)throw Error(i(340));bl()}return 65536&(e=t.flags)?(t.flags=-65537&e|128,t):null;case 19:return j(Ua),null;case 4:return Y(),null;case 10:return zl(t.type),null;case 22:case 23:return Ia(t),La(),null!==e&&j(ql),65536&(e=t.flags)?(t.flags=-65537&e|128,t):null;case 24:return zl(Il),null;default:return null}}function hu(e,t){switch(il(t),t.tag){case 3:zl(Il),Y();break;case 26:case 27:case 5:X(t);break;case 4:Y();break;case 31:null!==t.memoizedState&&Ia(t);break;case 13:Ia(t);break;case 19:j(Ua);break;case 10:zl(t.type);break;case 22:case 23:Ia(t),La(),null!==e&&j(ql);break;case 24:zl(Il)}}function gu(e,t){try{var n=t.updateQueue,r=null!==n?n.lastEffect:null;if(null!==r){var l=r.next;n=l;do{if((n.tag&e)===e){r=void 0;var a=n.create,o=n.inst;r=a(),o.destroy=r}n=n.next}while(n!==l)}}catch(i){Ec(t,t.return,i)}}function yu(e,t,n){try{var r=t.updateQueue,l=null!==r?r.lastEffect:null;if(null!==l){var a=l.next;r=a;do{if((r.tag&e)===e){var o=r.inst,i=o.destroy;if(void 0!==i){o.destroy=void 0,l=t;var u=n,s=i;try{s()}catch(c){Ec(l,u,c)}}}r=r.next}while(r!==a)}}catch(c){Ec(t,t.return,c)}}function vu(e){var t=e.updateQueue;if(null!==t){var n=e.stateNode;try{za(t,n)}catch(r){Ec(e,e.return,r)}}}function bu(e,t,n){n.props=Ei(e.type,e.memoizedProps),n.state=e.memoizedState;try{n.componentWillUnmount()}catch(r){Ec(e,t,r)}}function ku(e,t){try{var n=e.ref;if(null!==n){switch(e.tag){case 26:case 27:case 5:var r=e.stateNode;break;default:r=e.stateNode}"function"==typeof n?e.refCleanup=n(r):n.current=r}}catch(l){Ec(e,t,l)}}function wu(e,t){var n=e.ref,r=e.refCleanup;if(null!==n)if("function"==typeof r)try{r()}catch(l){Ec(e,t,l)}finally{e.refCleanup=null,null!=(e=e.alternate)&&(e.refCleanup=null)}else if("function"==typeof n)try{n(null)}catch(a){Ec(e,t,a)}else n.current=null}function Su(e){var t=e.type,n=e.memoizedProps,r=e.stateNode;try{e:switch(t){case"button":case"input":case"select":case"textarea":n.autoFocus&&r.focus();break e;case"img":n.src?r.src=n.src:n.srcSet&&(r.srcset=n.srcSet)}}catch(l){Ec(e,e.return,l)}}function Eu(e,t,n){try{var r=e.stateNode;!function(e,t,n,r){switch(t){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"input":var l=null,a=null,o=null,u=null,s=null,c=null,f=null;for(m in n){var d=n[m];if(n.hasOwnProperty(m)&&null!=d)switch(m){case"checked":case"value":break;case"defaultValue":s=d;default:r.hasOwnProperty(m)||ff(e,t,m,null,r,d)}}for(var p in r){var m=r[p];if(d=n[p],r.hasOwnProperty(p)&&(null!=m||null!=d))switch(p){case"type":a=m;break;case"name":l=m;break;case"checked":c=m;break;case"defaultChecked":f=m;break;case"value":o=m;break;case"defaultValue":u=m;break;case"children":case"dangerouslySetInnerHTML":if(null!=m)throw Error(i(137,t));break;default:m!==d&&ff(e,t,p,m,r,d)}}return void vt(e,o,u,s,c,f,a,l);case"select":for(a in m=o=u=p=null,n)if(s=n[a],n.hasOwnProperty(a)&&null!=s)switch(a){case"value":break;case"multiple":m=s;default:r.hasOwnProperty(a)||ff(e,t,a,null,r,s)}for(l in r)if(a=r[l],s=n[l],r.hasOwnProperty(l)&&(null!=a||null!=s))switch(l){case"value":p=a;break;case"defaultValue":u=a;break;case"multiple":o=a;default:a!==s&&ff(e,t,l,a,r,s)}return t=u,n=o,r=m,void(null!=p?wt(e,!!n,p,!1):!!r!=!!n&&(null!=t?wt(e,!!n,t,!0):wt(e,!!n,n?[]:"",!1)));case"textarea":for(u in m=p=null,n)if(l=n[u],n.hasOwnProperty(u)&&null!=l&&!r.hasOwnProperty(u))switch(u){case"value":case"children":break;default:ff(e,t,u,null,r,l)}for(o in r)if(l=r[o],a=n[o],r.hasOwnProperty(o)&&(null!=l||null!=a))switch(o){case"value":p=l;break;case"defaultValue":m=l;break;case"children":break;case"dangerouslySetInnerHTML":if(null!=l)throw Error(i(91));break;default:l!==a&&ff(e,t,o,l,r,a)}return void St(e,p,m);case"option":for(var h in n)p=n[h],n.hasOwnProperty(h)&&null!=p&&!r.hasOwnProperty(h)&&("selected"===h?e.selected=!1:ff(e,t,h,null,r,p));for(s in r)p=r[s],m=n[s],!r.hasOwnProperty(s)||p===m||null==p&&null==m||("selected"===s?e.selected=p&&"function"!=typeof p&&"symbol"!=typeof p:ff(e,t,s,p,r,m));return;case"img":case"link":case"area":case"base":case"br":case"col":case"embed":case"hr":case"keygen":case"meta":case"param":case"source":case"track":case"wbr":case"menuitem":for(var g in n)p=n[g],n.hasOwnProperty(g)&&null!=p&&!r.hasOwnProperty(g)&&ff(e,t,g,null,r,p);for(c in r)if(p=r[c],m=n[c],r.hasOwnProperty(c)&&p!==m&&(null!=p||null!=m))switch(c){case"children":case"dangerouslySetInnerHTML":if(null!=p)throw Error(i(137,t));break;default:ff(e,t,c,p,r,m)}return;default:if(Pt(t)){for(var y in n)p=n[y],n.hasOwnProperty(y)&&void 0!==p&&!r.hasOwnProperty(y)&&df(e,t,y,void 0,r,p);for(f in r)p=r[f],m=n[f],!r.hasOwnProperty(f)||p===m||void 0===p&&void 0===m||df(e,t,f,p,r,m);return}}for(var v in n)p=n[v],n.hasOwnProperty(v)&&null!=p&&!r.hasOwnProperty(v)&&ff(e,t,v,null,r,p);for(d in r)p=r[d],m=n[d],!r.hasOwnProperty(d)||p===m||null==p&&null==m||ff(e,t,d,p,r,m)}(r,e.type,n,t),r[$e]=t}catch(l){Ec(e,e.return,l)}}function Cu(e){return 5===e.tag||3===e.tag||26===e.tag||27===e.tag&&_f(e.type)||4===e.tag}function xu(e){e:for(;;){for(;null===e.sibling;){if(null===e.return||Cu(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;5!==e.tag&&6!==e.tag&&18!==e.tag;){if(27===e.tag&&_f(e.type))continue e;if(2&e.flags)continue e;if(null===e.child||4===e.tag)continue e;e.child.return=e,e=e.child}if(!(2&e.flags))return e.stateNode}}function zu(e,t,n){var r=e.tag;if(5===r||6===r)e=e.stateNode,t?(9===n.nodeType?n.body:"HTML"===n.nodeName?n.ownerDocument.body:n).insertBefore(e,t):((t=9===n.nodeType?n.body:"HTML"===n.nodeName?n.ownerDocument.body:n).appendChild(e),null!=(n=n._reactRootContainer)||null!==t.onclick||(t.onclick=Ot));else if(4!==r&&(27===r&&_f(e.type)&&(n=e.stateNode,t=null),null!==(e=e.child)))for(zu(e,t,n),e=e.sibling;null!==e;)zu(e,t,n),e=e.sibling}function _u(e,t,n){var r=e.tag;if(5===r||6===r)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(4!==r&&(27===r&&_f(e.type)&&(n=e.stateNode),null!==(e=e.child)))for(_u(e,t,n),e=e.sibling;null!==e;)_u(e,t,n),e=e.sibling}function Pu(e){var t=e.stateNode,n=e.memoizedProps;try{for(var r=e.type,l=t.attributes;l.length;)t.removeAttributeNode(l[0]);pf(t,r,n),t[He]=e,t[$e]=n}catch(a){Ec(e,e.return,a)}}var Nu=!1,Tu=!1,Lu=!1,Ou="function"==typeof WeakSet?WeakSet:Set,Du=null;function Fu(e,t,n){var r=n.flags;switch(n.tag){case 0:case 11:case 15:Ku(e,n),4&r&&gu(5,n);break;case 1:if(Ku(e,n),4&r)if(e=n.stateNode,null===t)try{e.componentDidMount()}catch(o){Ec(n,n.return,o)}else{var l=Ei(n.type,t.memoizedProps);t=t.memoizedState;try{e.componentDidUpdate(l,t,e.__reactInternalSnapshotBeforeUpdate)}catch(i){Ec(n,n.return,i)}}64&r&&vu(n),512&r&&ku(n,n.return);break;case 3:if(Ku(e,n),64&r&&null!==(e=n.updateQueue)){if(t=null,null!==n.child)switch(n.child.tag){case 27:case 5:case 1:t=n.child.stateNode}try{za(e,t)}catch(o){Ec(n,n.return,o)}}break;case 27:null===t&&4&r&&Pu(n);case 26:case 5:Ku(e,n),null===t&&4&r&&Su(n),512&r&&ku(n,n.return);break;case 12:Ku(e,n);break;case 31:Ku(e,n),4&r&&ju(e,n);break;case 13:Ku(e,n),4&r&&Hu(e,n),64&r&&null!==(e=n.memoizedState)&&null!==(e=e.dehydrated)&&function(e,t){var n=e.ownerDocument;if("$~"===e.data)e._reactRetry=t;else if("$?"!==e.data||"loading"!==n.readyState)t();else{var r=function(){t(),n.removeEventListener("DOMContentLoaded",r)};n.addEventListener("DOMContentLoaded",r),e._reactRetry=r}}(e,n=_c.bind(null,n));break;case 22:if(!(r=null!==n.memoizedState||Nu)){t=null!==t&&null!==t.memoizedState||Tu,l=Nu;var a=Tu;Nu=r,(Tu=t)&&!a?Gu(e,n,!!(8772&n.subtreeFlags)):Ku(e,n),Nu=l,Tu=a}break;case 30:break;default:Ku(e,n)}}function Ru(e){var t=e.alternate;null!==t&&(e.alternate=null,Ru(t)),e.child=null,e.deletions=null,e.sibling=null,5===e.tag&&null!==(t=e.stateNode)&&Ye(t),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}var Au=null,Mu=!1;function Iu(e,t,n){for(n=n.child;null!==n;)Uu(e,t,n),n=n.sibling}function Uu(e,t,n){if(ve&&"function"==typeof ve.onCommitFiberUnmount)try{ve.onCommitFiberUnmount(ye,n)}catch(a){}switch(n.tag){case 26:Tu||wu(n,t),Iu(e,t,n),n.memoizedState?n.memoizedState.count--:n.stateNode&&(n=n.stateNode).parentNode.removeChild(n);break;case 27:Tu||wu(n,t);var r=Au,l=Mu;_f(n.type)&&(Au=n.stateNode,Mu=!1),Iu(e,t,n),Uf(n.stateNode),Au=r,Mu=l;break;case 5:Tu||wu(n,t);case 6:if(r=Au,l=Mu,Au=null,Iu(e,t,n),Mu=l,null!==(Au=r))if(Mu)try{(9===Au.nodeType?Au.body:"HTML"===Au.nodeName?Au.ownerDocument.body:Au).removeChild(n.stateNode)}catch(o){Ec(n,t,o)}else try{Au.removeChild(n.stateNode)}catch(o){Ec(n,t,o)}break;case 18:null!==Au&&(Mu?(Pf(9===(e=Au).nodeType?e.body:"HTML"===e.nodeName?e.ownerDocument.body:e,n.stateNode),Vd(e)):Pf(Au,n.stateNode));break;case 4:r=Au,l=Mu,Au=n.stateNode.containerInfo,Mu=!0,Iu(e,t,n),Au=r,Mu=l;break;case 0:case 11:case 14:case 15:yu(2,n,t),Tu||yu(4,n,t),Iu(e,t,n);break;case 1:Tu||(wu(n,t),"function"==typeof(r=n.stateNode).componentWillUnmount&&bu(n,t,r)),Iu(e,t,n);break;case 21:Iu(e,t,n);break;case 22:Tu=(r=Tu)||null!==n.memoizedState,Iu(e,t,n),Tu=r;break;default:Iu(e,t,n)}}function ju(e,t){if(null===t.memoizedState&&null!==(e=t.alternate)&&null!==(e=e.memoizedState)){e=e.dehydrated;try{Vd(e)}catch(n){Ec(t,t.return,n)}}}function Hu(e,t){if(null===t.memoizedState&&null!==(e=t.alternate)&&null!==(e=e.memoizedState)&&null!==(e=e.dehydrated))try{Vd(e)}catch(n){Ec(t,t.return,n)}}function $u(e,t){var n=function(e){switch(e.tag){case 31:case 13:case 19:var t=e.stateNode;return null===t&&(t=e.stateNode=new Ou),t;case 22:return null===(t=(e=e.stateNode)._retryCache)&&(t=e._retryCache=new Ou),t;default:throw Error(i(435,e.tag))}}(e);t.forEach(function(t){if(!n.has(t)){n.add(t);var r=Pc.bind(null,e,t);t.then(r,r)}})}function Vu(e,t){var n=t.deletions;if(null!==n)for(var r=0;r title"))),pf(a,r,n),a[He]=e,et(a),r=a;break e;case"link":var o=rd("link","href",l).get(r+(n.href||""));if(o)for(var u=0;ui)break;var c=u.transferSize,f=u.initiatorType;c&&mf(f)&&(o+=c*((u=u.responseEnd)od?50:800)+t);return e.unsuspend=n,function(){e.unsuspend=null,clearTimeout(r),clearTimeout(l)}}:null}(f,m)))return js=a,e.cancelPendingCommit=m(hc.bind(null,e,t,a,n,r,l,o,i,u,c,f,null,d,p)),void Zs(e,a,o,!s)}hc(e,t,a,n,r,l,o,i,u)}function Xs(e){for(var t=e;;){var n=t.tag;if((0===n||11===n||15===n)&&16384&t.flags&&null!==(n=t.updateQueue)&&null!==(n=n.stores))for(var r=0;rg&&(o=g,g=h,h=o);var y=tr(i,h),v=tr(i,g);if(y&&v&&(1!==p.rangeCount||p.anchorNode!==y.node||p.anchorOffset!==y.offset||p.focusNode!==v.node||p.focusOffset!==v.offset)){var b=f.createRange();b.setStart(y.node,y.offset),p.removeAllRanges(),h>g?(p.addRange(b),p.extend(v.node,v.offset)):(b.setEnd(v.node,v.offset),p.addRange(b))}}}}for(f=[],p=i;p=p.parentNode;)1===p.nodeType&&f.push({element:p,left:p.scrollLeft,top:p.scrollTop});for("function"==typeof i.focus&&i.focus(),i=0;in?32:n,F.T=null,n=$s,$s=null;var a=Is,o=js;if(Ms=0,Us=Is=null,js=0,6&ps)throw Error(i(331));var u=ps;if(ps|=4,us(a.current),es(a,a.current,o,n),ps=u,Ac(0,!1),ve&&"function"==typeof ve.onPostCommitFiberRoot)try{ve.onPostCommitFiberRoot(ye,a)}catch(s){}return!0}finally{R.p=l,F.T=r,bc(e,t)}}function Sc(e,t,n){t=Kr(n,t),null!==(e=ba(e,t=Ni(e.stateNode,t,2),2))&&(Oe(e,2),Rc(e))}function Ec(e,t,n){if(3===e.tag)Sc(e,e,n);else for(;null!==t;){if(3===t.tag){Sc(t,e,n);break}if(1===t.tag){var r=t.stateNode;if("function"==typeof t.type.getDerivedStateFromError||"function"==typeof r.componentDidCatch&&(null===As||!As.has(r))){e=Kr(n,e),null!==(r=ba(t,n=Ti(2),2))&&(Li(n,r,t,e),Oe(r,2),Rc(r));break}}t=t.return}}function Cc(e,t,n){var r=e.pingCache;if(null===r){r=e.pingCache=new ds;var l=new Set;r.set(t,l)}else void 0===(l=r.get(t))&&(l=new Set,r.set(t,l));l.has(n)||(ws=!0,l.add(n),e=xc.bind(null,e,t,n),t.then(e,e))}function xc(e,t,n){var r=e.pingCache;null!==r&&r.delete(t),e.pingedLanes|=e.suspendedLanes&n,e.warmLanes&=~n,ms===e&&(gs&n)===n&&(4===Es||3===Es&&(62914560&gs)===gs&&300>ue()-Os?!(2&ps)&&tc(e,0):zs|=n,Ps===gs&&(Ps=0)),Rc(e)}function zc(e,t){0===t&&(t=Te()),null!==(e=Dr(e,t))&&(Oe(e,t),Rc(e))}function _c(e){var t=e.memoizedState,n=0;null!==t&&(n=t.retryLane),zc(e,n)}function Pc(e,t){var n=0;switch(e.tag){case 31:case 13:var r=e.stateNode,l=e.memoizedState;null!==l&&(n=l.retryLane);break;case 19:r=e.stateNode;break;case 22:r=e.stateNode._retryCache;break;default:throw Error(i(314))}null!==r&&r.delete(t),zc(e,n)}var Nc=null,Tc=null,Lc=!1,Oc=!1,Dc=!1,Fc=0;function Rc(e){e!==Tc&&null===e.next&&(null===Tc?Nc=Tc=e:Tc=Tc.next=e),Oc=!0,Lc||(Lc=!0,xf(function(){6&ps?le(ce,Mc):Ic()}))}function Ac(e,t){if(!Dc&&Oc){Dc=!0;do{for(var n=!1,r=Nc;null!==r;){if(!t)if(0!==e){var l=r.pendingLanes;if(0===l)var a=0;else{var o=r.suspendedLanes,i=r.pingedLanes;a=(1<<31-ke(42|e)+1)-1,a=201326741&(a&=l&~(o&~i))?201326741&a|1:a?2|a:0}0!==a&&(n=!0,Hc(r,a))}else a=gs,!(3&(a=_e(r,r===ms?a:0,null!==r.cancelPendingCommit||-1!==r.timeoutHandle)))||Pe(r,a)||(n=!0,Hc(r,a));r=r.next}}while(n);Dc=!1}}function Mc(){Ic()}function Ic(){Oc=Lc=!1;var e,t=0;0!==Fc&&((e=window.event)&&"popstate"===e.type?e!==wf&&(wf=e,1):(wf=null,0))&&(t=Fc);for(var n=ue(),r=null,l=Nc;null!==l;){var a=l.next,o=Uc(l,n);0===o?(l.next=null,null===r?Nc=a:r.next=a,null===a&&(Tc=r)):(r=l,(0!==t||3&o)&&(Oc=!0)),l=a}0!==Ms&&5!==Ms||Ac(t,!1),0!==Fc&&(Fc=0)}function Uc(e,t){for(var n=e.suspendedLanes,r=e.pingedLanes,l=e.expirationTimes,a=-62914561&e.pendingLanes;0 title"):null)}function ad(e){return!!("stylesheet"!==e.type||3&e.state.loading)}var od=0;function id(){if(this.count--,0===this.count&&(0===this.imgCount||!this.waitingForImages))if(this.stylesheets)sd(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}var ud=null;function sd(e,t){e.stylesheets=null,null!==e.unsuspend&&(e.count++,ud=new Map,t.forEach(cd,e),ud=null,id.call(e))}function cd(e,t){if(!(4&t.state.loading)){var n=ud.get(e);if(n)var r=n.get(null);else{n=new Map,ud.set(e,n);for(var l=e.querySelectorAll("link[data-precedence],style[data-precedence]"),a=0;a{!function e(){if("undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE)try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}(),t.exports=i()}),s=e(e=>{var t=Symbol.for("react.transitional.element"),n=Symbol.for("react.fragment");function r(e,n,r){var l=null;if(void 0!==r&&(l=""+r),void 0!==n.key&&(l=""+n.key),"key"in n)for(var a in r={},n)"key"!==a&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:l,ref:void 0!==n?n:null,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r}),c=e((e,t)=>{t.exports=s()});export{u as n,n as r,c as t}; \ No newline at end of file +import{t as e}from"./rolldown-runtime-BztV3taV.js?t=1781136546834";var t=e(e=>{var t=Symbol.for("react.transitional.element"),n=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),l=Symbol.for("react.strict_mode"),a=Symbol.for("react.profiler"),o=Symbol.for("react.consumer"),i=Symbol.for("react.context"),u=Symbol.for("react.forward_ref"),s=Symbol.for("react.suspense"),c=Symbol.for("react.memo"),f=Symbol.for("react.lazy"),d=Symbol.for("react.activity"),p=Symbol.iterator,m={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},h=Object.assign,g={};function y(e,t,n){this.props=e,this.context=t,this.refs=g,this.updater=n||m}function v(){}function b(e,t,n){this.props=e,this.context=t,this.refs=g,this.updater=n||m}y.prototype.isReactComponent={},y.prototype.setState=function(e,t){if("object"!=typeof e&&"function"!=typeof e&&null!=e)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")},y.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")},v.prototype=y.prototype;var k=b.prototype=new v;k.constructor=b,h(k,y.prototype),k.isPureReactComponent=!0;var w=Array.isArray;function S(){}var E={H:null,A:null,T:null,S:null},C=Object.prototype.hasOwnProperty;function x(e,n,r){var l=r.ref;return{$$typeof:t,type:e,key:n,ref:void 0!==l?l:null,props:r}}function z(e){return"object"==typeof e&&null!==e&&e.$$typeof===t}var _=/\/+/g;function P(e,t){return"object"==typeof e&&null!==e&&null!=e.key?(n=""+e.key,r={"=":"=0",":":"=2"},"$"+n.replace(/[=:]/g,function(e){return r[e]})):t.toString(36);var n,r}function N(e,r,l,a,o){var i=typeof e;"undefined"!==i&&"boolean"!==i||(e=null);var u,s,c=!1;if(null===e)c=!0;else switch(i){case"bigint":case"string":case"number":c=!0;break;case"object":switch(e.$$typeof){case t:case n:c=!0;break;case f:return N((c=e._init)(e._payload),r,l,a,o)}}if(c)return o=o(e),c=""===a?"."+P(e,0):a,w(o)?(l="",null!=c&&(l=c.replace(_,"$&/")+"/"),N(o,r,l,"",function(e){return e})):null!=o&&(z(o)&&(u=o,s=l+(null==o.key||e&&e.key===o.key?"":(""+o.key).replace(_,"$&/")+"/")+c,o=x(u.type,s,u.props)),r.push(o)),1;c=0;var d,m=""===a?".":a+":";if(w(e))for(var h=0;h{n.exports=t()}),r=e(e=>{function t(e,t){var n=e.length;e.push(t);e:for(;0>>1,a=e[r];if(!(0>>1;rl(u,n))sl(c,u)?(e[r]=c,e[s]=n,r=s):(e[r]=u,e[i]=n,r=i);else{if(!(sl(c,n)))break e;e[r]=c,e[s]=n,r=s}}}return t}function l(e,t){var n=e.sortIndex-t.sortIndex;return 0!==n?n:e.id-t.id}if(e.unstable_now=void 0,"object"==typeof performance&&"function"==typeof performance.now){var a=performance;e.unstable_now=function(){return a.now()}}else{var o=Date,i=o.now();e.unstable_now=function(){return o.now()-i}}var u=[],s=[],c=1,f=null,d=3,p=!1,m=!1,h=!1,g=!1,y="function"==typeof setTimeout?setTimeout:null,v="function"==typeof clearTimeout?clearTimeout:null,b="undefined"!=typeof setImmediate?setImmediate:null;function k(e){for(var l=n(s);null!==l;){if(null===l.callback)r(s);else{if(!(l.startTime<=e))break;r(s),l.sortIndex=l.expirationTime,t(u,l)}l=n(s)}}function w(e){if(h=!1,k(e),!m)if(null!==n(u))m=!0,E||(E=!0,S());else{var t=n(s);null!==t&&L(w,t.startTime-e)}}var S,E=!1,C=-1,x=5,z=-1;function _(){return!(!g&&e.unstable_now()-zt&&_());){var o=f.callback;if("function"==typeof o){f.callback=null,d=f.priorityLevel;var i=o(f.expirationTime<=t);if(t=e.unstable_now(),"function"==typeof i){f.callback=i,k(t),l=!0;break t}f===n(u)&&r(u),k(t)}else r(u);f=n(u)}if(null!==f)l=!0;else{var c=n(s);null!==c&&L(w,c.startTime-t),l=!1}}break e}finally{f=null,d=a,p=!1}l=void 0}}finally{l?S():E=!1}}}if("function"==typeof b)S=function(){b(P)};else if("undefined"!=typeof MessageChannel){var N=new MessageChannel,T=N.port2;N.port1.onmessage=P,S=function(){T.postMessage(null)}}else S=function(){y(P,0)};function L(t,n){C=y(function(){t(e.unstable_now())},n)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(e){e.callback=null},e.unstable_forceFrameRate=function(e){0>e||125o?(r.sortIndex=a,t(s,r),null===n(u)&&r===n(s)&&(h?(v(C),C=-1):h=!0,L(w,a-o))):(r.sortIndex=i,t(u,r),m||p||(m=!0,E||(E=!0,S()))),r},e.unstable_shouldYield=_,e.unstable_wrapCallback=function(e){var t=d;return function(){var n=d;d=t;try{return e.apply(this,arguments)}finally{d=n}}}}),l=e((e,t)=>{t.exports=r()}),a=e(e=>{var t=n();function r(e){var t="https://react.dev/errors/"+e;if(1{!function e(){if("undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE)try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}(),t.exports=a()}),i=e(e=>{var t=l(),r=n(),a=o();function i(e){var t="https://react.dev/errors/"+e;if(1I||(e.current=M[I],M[I]=null,I--)}function H(e,t){I++,M[I]=e.current,e.current=t}var $,V,B=U(null),Q=U(null),W=U(null),q=U(null);function K(e,t){switch(H(W,t),H(Q,e),H(B,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?vf(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)e=bf(t=vf(t),e);else switch(e){case"svg":e=1;break;case"math":e=2;break;default:e=0}}j(B),H(B,e)}function Y(){j(B),j(Q),j(W)}function G(e){null!==e.memoizedState&&H(q,e);var t=B.current,n=bf(t,e.type);t!==n&&(H(Q,e),H(B,n))}function X(e){Q.current===e&&(j(B),j(Q)),q.current===e&&(j(q),fd._currentValue=A)}function Z(e){if(void 0===$)try{throw Error()}catch(n){var t=n.stack.trim().match(/\n( *(at )?)/);$=t&&t[1]||"",V=-1)":-1--l||u[r]!==s[l]){var c="\n"+u[r].replace(" at new "," at ");return e.displayName&&c.includes("")&&(c=c.replace("",e.displayName)),c}}while(1<=r&&0<=l);break}}}finally{J=!1,Error.prepareStackTrace=n}return(n=e?e.displayName||e.name:"")?Z(n):""}function te(e,t){switch(e.tag){case 26:case 27:case 5:return Z(e.type);case 16:return Z("Lazy");case 13:return e.child!==t&&null!==t?Z("Suspense Fallback"):Z("Suspense");case 19:return Z("SuspenseList");case 0:case 15:return ee(e.type,!1);case 11:return ee(e.type.render,!1);case 1:return ee(e.type,!0);case 31:return Z("Activity");default:return""}}function ne(e){try{var t="",n=null;do{t+=te(e,n),n=e,e=e.return}while(e);return t}catch(r){return"\nError generating stack: "+r.message+"\n"+r.stack}}var re=Object.prototype.hasOwnProperty,le=t.unstable_scheduleCallback,ae=t.unstable_cancelCallback,oe=t.unstable_shouldYield,ie=t.unstable_requestPaint,ue=t.unstable_now,se=t.unstable_getCurrentPriorityLevel,ce=t.unstable_ImmediatePriority,fe=t.unstable_UserBlockingPriority,de=t.unstable_NormalPriority,pe=t.unstable_LowPriority,me=t.unstable_IdlePriority,he=t.log,ge=t.unstable_setDisableYieldValue,ye=null,ve=null;function be(e){if("function"==typeof he&&ge(e),ve&&"function"==typeof ve.setStrictMode)try{ve.setStrictMode(ye,e)}catch(t){}}var ke=Math.clz32?Math.clz32:function(e){return 0==(e>>>=0)?32:31-(we(e)/Se|0)|0},we=Math.log,Se=Math.LN2,Ee=256,Ce=262144,xe=4194304;function ze(e){var t=42&e;if(0!==t)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return 261888&e;case 262144:case 524288:case 1048576:case 2097152:return 3932160&e;case 4194304:case 8388608:case 16777216:case 33554432:return 62914560&e;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function _e(e,t,n){var r=e.pendingLanes;if(0===r)return 0;var l=0,a=e.suspendedLanes,o=e.pingedLanes;e=e.warmLanes;var i=134217727&r;return 0!==i?0!==(r=i&~a)?l=ze(r):0!==(o&=i)?l=ze(o):n||0!==(n=i&~e)&&(l=ze(n)):0!==(i=r&~a)?l=ze(i):0!==o?l=ze(o):n||0!==(n=r&~e)&&(l=ze(n)),0===l?0:0!==t&&t!==l&&0===(t&a)&&((a=l&-l)>=(n=t&-t)||32===a&&4194048&n)?t:l}function Pe(e,t){return 0===(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)}function Ne(e,t){switch(e){case 1:case 2:case 4:case 8:case 64:return t+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;default:return-1}}function Te(){var e=xe;return!(62914560&(xe<<=1))&&(xe=4194304),e}function Le(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function Oe(e,t){e.pendingLanes|=t,268435456!==t&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function De(e,t,n){e.pendingLanes|=t,e.suspendedLanes&=~t;var r=31-ke(t);e.entangledLanes|=t,e.entanglements[r]=1073741824|e.entanglements[r]|261930&n}function Fe(e,t){var n=e.entangledLanes|=t;for(e=e.entanglements;n;){var r=31-ke(n),l=1<=zn),Nn=String.fromCharCode(32),Tn=!1;function Ln(e,t){switch(e){case"keyup":return-1!==Cn.indexOf(t.keyCode);case"keydown":return 229!==t.keyCode;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function On(e){return"object"==typeof(e=e.detail)&&"data"in e?e.data:null}var Dn=!1,Fn={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function Rn(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return"input"===t?!!Fn[e.type]:"textarea"===t}function An(e,t,n,r){Rt?At?At.push(r):At=[r]:Rt=r,0<(t=rf(t,"onChange")).length&&(n=new nn("onChange","change",null,n,r),e.push({event:n,listeners:t}))}var Mn=null,In=null;function Un(e){Yc(e,0)}function jn(e){if(mt(Ze(e)))return e}function Hn(e,t){if("change"===e)return t}var $n=!1;if(Ht){var Vn;if(Ht){var Bn="oninput"in document;if(!Bn){var Qn=document.createElement("div");Qn.setAttribute("oninput","return;"),Bn="function"==typeof Qn.oninput}Vn=Bn}else Vn=!1;$n=Vn&&(!document.documentMode||9=t)return{node:r,offset:t-e};e=n}e:{for(;r;){if(r.nextSibling){r=r.nextSibling;break e}r=r.parentNode}r=void 0}r=er(r)}}function nr(e,t){return!(!e||!t)&&(e===t||(!e||3!==e.nodeType)&&(t&&3===t.nodeType?nr(e,t.parentNode):"contains"in e?e.contains(t):!!e.compareDocumentPosition&&!!(16&e.compareDocumentPosition(t))))}function rr(e){for(var t=ht((e=null!=e&&null!=e.ownerDocument&&null!=e.ownerDocument.defaultView?e.ownerDocument.defaultView:window).document);t instanceof e.HTMLIFrameElement;){try{var n="string"==typeof t.contentWindow.location.href}catch(r){n=!1}if(!n)break;t=ht((e=t.contentWindow).document)}return t}function lr(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&("input"===t&&("text"===e.type||"search"===e.type||"tel"===e.type||"url"===e.type||"password"===e.type)||"textarea"===t||"true"===e.contentEditable)}var ar=Ht&&"documentMode"in document&&11>=document.documentMode,or=null,ir=null,ur=null,sr=!1;function cr(e,t,n){var r=n.window===n?n.document:9===n.nodeType?n:n.ownerDocument;sr||null==or||or!==ht(r)||(r="selectionStart"in(r=or)&&lr(r)?{start:r.selectionStart,end:r.selectionEnd}:{anchorNode:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection()).anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset},ur&&Jn(ur,r)||(ur=r,0<(r=rf(ir,"onSelect")).length&&(t=new nn("onSelect","select",null,t,n),e.push({event:t,listeners:r}),t.target=or)))}function fr(e,t){var n={};return n[e.toLowerCase()]=t.toLowerCase(),n["Webkit"+e]="webkit"+t,n["Moz"+e]="moz"+t,n}var dr={animationend:fr("Animation","AnimationEnd"),animationiteration:fr("Animation","AnimationIteration"),animationstart:fr("Animation","AnimationStart"),transitionrun:fr("Transition","TransitionRun"),transitionstart:fr("Transition","TransitionStart"),transitioncancel:fr("Transition","TransitionCancel"),transitionend:fr("Transition","TransitionEnd")},pr={},mr={};function hr(e){if(pr[e])return pr[e];if(!dr[e])return e;var t,n=dr[e];for(t in n)if(n.hasOwnProperty(t)&&t in mr)return pr[e]=n[t];return e}Ht&&(mr=document.createElement("div").style,"AnimationEvent"in window||(delete dr.animationend.animation,delete dr.animationiteration.animation,delete dr.animationstart.animation),"TransitionEvent"in window||delete dr.transitionend.transition);var gr=hr("animationend"),yr=hr("animationiteration"),vr=hr("animationstart"),br=hr("transitionrun"),kr=hr("transitionstart"),wr=hr("transitioncancel"),Sr=hr("transitionend"),Er=new Map,Cr="abort auxClick beforeToggle cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");function xr(e,t){Er.set(e,t),rt(t,[e])}Cr.push("scrollEnd");var zr="function"==typeof reportError?reportError:function(e){if("object"==typeof window&&"function"==typeof window.ErrorEvent){var t=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:"object"==typeof e&&null!==e&&"string"==typeof e.message?String(e.message):String(e),error:e});if(!window.dispatchEvent(t))return}else if("object"==typeof process&&"function"==typeof process.emit)return void process.emit("uncaughtException",e);console.error(e)},_r=[],Pr=0,Nr=0;function Tr(){for(var e=Pr,t=Nr=Pr=0;t>=o,l-=o,nl=1<<32-ke(t)+l|n<h?(g=f,f=null):g=f.sibling;var y=p(l,f,i[h],u);if(null===y){null===f&&(f=g);break}e&&f&&null===y.alternate&&t(l,f),o=a(y,o,h),null===c?s=y:c.sibling=y,c=y,f=g}if(h===i.length)return n(l,f),fl&&ll(l,h),s;if(null===f){for(;hg?(y=h,h=null):y=h.sibling;var b=p(l,h,v.value,s);if(null===b){null===h&&(h=y);break}e&&h&&null===b.alternate&&t(l,h),o=a(b,o,g),null===f?c=b:f.sibling=b,f=b,h=y}if(v.done)return n(l,h),fl&&ll(l,g),c;if(null===h){for(;!v.done;g++,v=u.next())null!==(v=d(l,v.value,s))&&(o=a(v,o,g),null===f?c=v:f.sibling=v,f=v);return fl&&ll(l,g),c}for(h=r(h);!v.done;g++,v=u.next())null!==(v=m(h,l,g,v.value,s))&&(e&&null!==v.alternate&&h.delete(null===v.key?g:v.key),o=a(v,o,g),null===f?c=v:f.sibling=v,f=v);return e&&h.forEach(function(e){return t(l,e)}),fl&&ll(l,g),c}(u,s,c=b.call(c),f)}if("function"==typeof c.then)return v(u,s,sa(c),f);if(c.$$typeof===w)return v(u,s,Dl(u,c),f);fa(u,c)}return"string"==typeof c&&""!==c||"number"==typeof c||"bigint"==typeof c?(c=""+c,null!==s&&6===s.tag?(n(u,s.sibling),(f=l(s,c)).return=u,u=f):(n(u,s),(f=Br(c,u.mode,f)).return=u,u=f),o(u)):n(u,s)}return function(e,t,n,r){try{ua=0;var l=v(e,t,n,r);return ia=null,l}catch(o){if(o===Xl||o===Jl)throw o;var a=Ir(29,o,null,e.mode);return a.lanes=r,a.return=e,a}}}var pa=da(!0),ma=da(!1),ha=!1;function ga(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function ya(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function va(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function ba(e,t,n){var r=e.updateQueue;if(null===r)return null;if(r=r.shared,2&ps){var l=r.pending;return null===l?t.next=t:(t.next=l.next,l.next=t),r.pending=t,t=Rr(e),Fr(e,null,n),t}return Lr(e,r,t,n),Rr(e)}function ka(e,t,n){if(null!==(t=t.updateQueue)&&(t=t.shared,4194048&n)){var r=t.lanes;n|=r&=e.pendingLanes,t.lanes=n,Fe(e,n)}}function wa(e,t){var n=e.updateQueue,r=e.alternate;if(null!==r&&n===(r=r.updateQueue)){var l=null,a=null;if(null!==(n=n.firstBaseUpdate)){do{var o={lane:n.lane,tag:n.tag,payload:n.payload,callback:null,next:null};null===a?l=a=o:a=a.next=o,n=n.next}while(null!==n);null===a?l=a=t:a=a.next=t}else l=a=t;return n={baseState:r.baseState,firstBaseUpdate:l,lastBaseUpdate:a,shared:r.shared,callbacks:r.callbacks},void(e.updateQueue=n)}null===(e=n.lastBaseUpdate)?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}var Sa=!1;function Ea(){if(Sa&&null!==Bl)throw Bl}function Ca(e,t,n,r){Sa=!1;var l=e.updateQueue;ha=!1;var a=l.firstBaseUpdate,o=l.lastBaseUpdate,i=l.shared.pending;if(null!==i){l.shared.pending=null;var u=i,s=u.next;u.next=null,null===o?a=s:o.next=s,o=u;var c=e.alternate;null!==c&&(i=(c=c.updateQueue).lastBaseUpdate)!==o&&(null===i?c.firstBaseUpdate=s:i.next=s,c.lastBaseUpdate=u)}if(null!==a){var f=l.baseState;for(o=0,c=s=u=null,i=a;;){var d=-536870913&i.lane,m=d!==i.lane;if(m?(gs&d)===d:(r&d)===d){0!==d&&d===Vl&&(Sa=!0),null!==c&&(c=c.next={lane:0,tag:i.tag,payload:i.payload,callback:null,next:null});e:{var h=e,g=i;d=t;var y=n;switch(g.tag){case 1:if("function"==typeof(h=g.payload)){f=h.call(y,f,d);break e}f=h;break e;case 3:h.flags=-65537&h.flags|128;case 0:if(null==(d="function"==typeof(h=g.payload)?h.call(y,f,d):h))break e;f=p({},f,d);break e;case 2:ha=!0}}null!==(d=i.callback)&&(e.flags|=64,m&&(e.flags|=8192),null===(m=l.callbacks)?l.callbacks=[d]:m.push(d))}else m={lane:d,tag:i.tag,payload:i.payload,callback:i.callback,next:null},null===c?(s=c=m,u=f):c=c.next=m,o|=d;if(null===(i=i.next)){if(null===(i=l.shared.pending))break;i=(m=i).next,m.next=null,l.lastBaseUpdate=m,l.shared.pending=null}}null===c&&(u=f),l.baseState=u,l.firstBaseUpdate=s,l.lastBaseUpdate=c,null===a&&(l.shared.lanes=0),Cs|=o,e.lanes=o,e.memoizedState=f}}function xa(e,t){if("function"!=typeof e)throw Error(i(191,e));e.call(t)}function za(e,t){var n=e.callbacks;if(null!==n)for(e.callbacks=null,e=0;ea?a:8;var o,i,u,s=F.T,c={};F.T=c,fi(e,!1,t,n);try{var f=l(),d=F.S;null!==d&&d(c,f),null!==f&&"object"==typeof f&&"function"==typeof f.then?ci(e,t,(o=r,i=[],u={status:"pending",value:null,reason:null,then:function(e){i.push(e)}},f.then(function(){u.status="fulfilled",u.value=o;for(var e=0;e<\/script>",a=a.removeChild(a.firstChild);break;case"select":a="string"==typeof r.is?o.createElement("select",{is:r.is}):o.createElement("select"),r.multiple?a.multiple=!0:r.size&&(a.size=r.size);break;default:a="string"==typeof r.is?o.createElement(l,{is:r.is}):o.createElement(l)}}a[He]=t,a[$e]=r;e:for(o=t.child;null!==o;){if(5===o.tag||6===o.tag)a.appendChild(o.stateNode);else if(4!==o.tag&&27!==o.tag&&null!==o.child){o.child.return=o,o=o.child;continue}if(o===t)break e;for(;null===o.sibling;){if(null===o.return||o.return===t)break e;o=o.return}o.sibling.return=o.return,o=o.sibling}t.stateNode=a;e:switch(pf(a,l,r),l){case"button":case"input":case"select":case"textarea":r=!!r.autoFocus;break e;case"img":r=!0;break e;default:r=!1}r&&iu(t)}}return du(t),uu(t,t.type,null===e||e.memoizedProps,t.pendingProps,n),null;case 6:if(e&&null!=t.stateNode)e.memoizedProps!==r&&iu(t);else{if("string"!=typeof r&&null===t.stateNode)throw Error(i(166));if(e=W.current,vl(t)){if(e=t.stateNode,n=t.memoizedProps,r=null,null!==(l=sl))switch(l.tag){case 27:case 5:r=l.memoizedProps}e[He]=t,(e=!!(e.nodeValue===n||null!==r&&!0===r.suppressHydrationWarning||cf(e.nodeValue,n)))||hl(t,!0)}else(e=yf(e).createTextNode(r))[He]=t,t.stateNode=e}return du(t),null;case 31:if(n=t.memoizedState,null===e||null!==e.memoizedState){if(r=vl(t),null!==n){if(null===e){if(!r)throw Error(i(318));if(!(e=null!==(e=t.memoizedState)?e.dehydrated:null))throw Error(i(557));e[He]=t}else bl(),!(128&t.flags)&&(t.memoizedState=null),t.flags|=4;du(t),e=!1}else n=kl(),null!==e&&null!==e.memoizedState&&(e.memoizedState.hydrationErrors=n),e=!0;if(!e)return 256&t.flags?(Ia(t),t):(Ia(t),null);if(128&t.flags)throw Error(i(558))}return du(t),null;case 13:if(r=t.memoizedState,null===e||null!==e.memoizedState&&null!==e.memoizedState.dehydrated){if(l=vl(t),null!==r&&null!==r.dehydrated){if(null===e){if(!l)throw Error(i(318));if(!(l=null!==(l=t.memoizedState)?l.dehydrated:null))throw Error(i(317));l[He]=t}else bl(),!(128&t.flags)&&(t.memoizedState=null),t.flags|=4;du(t),l=!1}else l=kl(),null!==e&&null!==e.memoizedState&&(e.memoizedState.hydrationErrors=l),l=!0;if(!l)return 256&t.flags?(Ia(t),t):(Ia(t),null)}return Ia(t),128&t.flags?(t.lanes=n,t):(n=null!==r,e=null!==e&&null!==e.memoizedState,n&&(l=null,null!==(r=t.child).alternate&&null!==r.alternate.memoizedState&&null!==r.alternate.memoizedState.cachePool&&(l=r.alternate.memoizedState.cachePool.pool),a=null,null!==r.memoizedState&&null!==r.memoizedState.cachePool&&(a=r.memoizedState.cachePool.pool),a!==l&&(r.flags|=2048)),n!==e&&n&&(t.child.flags|=8192),cu(t,t.updateQueue),du(t),null);case 4:return Y(),null===e&&Jc(t.stateNode.containerInfo),du(t),null;case 10:return zl(t.type),du(t),null;case 19:if(j(Ua),null===(r=t.memoizedState))return du(t),null;if(l=!!(128&t.flags),null===(a=r.rendering))if(l)fu(r,!1);else{if(0!==Es||null!==e&&128&e.flags)for(e=t.child;null!==e;){if(null!==(a=ja(e))){for(t.flags|=128,fu(r,!1),e=a.updateQueue,t.updateQueue=e,cu(t,e),t.subtreeFlags=0,e=n,n=t.child;null!==n;)Hr(n,e),n=n.sibling;return H(Ua,1&Ua.current|2),fl&&ll(t,r.treeForkCount),t.child}e=e.sibling}null!==r.tail&&ue()>Fs&&(t.flags|=128,l=!0,fu(r,!1),t.lanes=4194304)}else{if(!l)if(null!==(e=ja(a))){if(t.flags|=128,l=!0,e=e.updateQueue,t.updateQueue=e,cu(t,e),fu(r,!0),null===r.tail&&"hidden"===r.tailMode&&!a.alternate&&!fl)return du(t),null}else 2*ue()-r.renderingStartTime>Fs&&536870912!==n&&(t.flags|=128,l=!0,fu(r,!1),t.lanes=4194304);r.isBackwards?(a.sibling=t.child,t.child=a):(null!==(e=r.last)?e.sibling=a:t.child=a,r.last=a)}return null!==r.tail?(e=r.tail,r.rendering=e,r.tail=e.sibling,r.renderingStartTime=ue(),e.sibling=null,n=Ua.current,H(Ua,l?1&n|2:1&n),fl&&ll(t,r.treeForkCount),e):(du(t),null);case 22:case 23:return Ia(t),La(),r=null!==t.memoizedState,null!==e?null!==e.memoizedState!==r&&(t.flags|=8192):r&&(t.flags|=8192),r?!!(536870912&n)&&!(128&t.flags)&&(du(t),6&t.subtreeFlags&&(t.flags|=8192)):du(t),null!==(n=t.updateQueue)&&cu(t,n.retryQueue),n=null,null!==e&&null!==e.memoizedState&&null!==e.memoizedState.cachePool&&(n=e.memoizedState.cachePool.pool),r=null,null!==t.memoizedState&&null!==t.memoizedState.cachePool&&(r=t.memoizedState.cachePool.pool),r!==n&&(t.flags|=2048),null!==e&&j(ql),null;case 24:return n=null,null!==e&&(n=e.memoizedState.cache),t.memoizedState.cache!==n&&(t.flags|=2048),zl(Il),du(t),null;case 25:case 30:return null}throw Error(i(156,t.tag))}function mu(e,t){switch(il(t),t.tag){case 1:return 65536&(e=t.flags)?(t.flags=-65537&e|128,t):null;case 3:return zl(Il),Y(),65536&(e=t.flags)&&!(128&e)?(t.flags=-65537&e|128,t):null;case 26:case 27:case 5:return X(t),null;case 31:if(null!==t.memoizedState){if(Ia(t),null===t.alternate)throw Error(i(340));bl()}return 65536&(e=t.flags)?(t.flags=-65537&e|128,t):null;case 13:if(Ia(t),null!==(e=t.memoizedState)&&null!==e.dehydrated){if(null===t.alternate)throw Error(i(340));bl()}return 65536&(e=t.flags)?(t.flags=-65537&e|128,t):null;case 19:return j(Ua),null;case 4:return Y(),null;case 10:return zl(t.type),null;case 22:case 23:return Ia(t),La(),null!==e&&j(ql),65536&(e=t.flags)?(t.flags=-65537&e|128,t):null;case 24:return zl(Il),null;default:return null}}function hu(e,t){switch(il(t),t.tag){case 3:zl(Il),Y();break;case 26:case 27:case 5:X(t);break;case 4:Y();break;case 31:null!==t.memoizedState&&Ia(t);break;case 13:Ia(t);break;case 19:j(Ua);break;case 10:zl(t.type);break;case 22:case 23:Ia(t),La(),null!==e&&j(ql);break;case 24:zl(Il)}}function gu(e,t){try{var n=t.updateQueue,r=null!==n?n.lastEffect:null;if(null!==r){var l=r.next;n=l;do{if((n.tag&e)===e){r=void 0;var a=n.create,o=n.inst;r=a(),o.destroy=r}n=n.next}while(n!==l)}}catch(i){Ec(t,t.return,i)}}function yu(e,t,n){try{var r=t.updateQueue,l=null!==r?r.lastEffect:null;if(null!==l){var a=l.next;r=a;do{if((r.tag&e)===e){var o=r.inst,i=o.destroy;if(void 0!==i){o.destroy=void 0,l=t;var u=n,s=i;try{s()}catch(c){Ec(l,u,c)}}}r=r.next}while(r!==a)}}catch(c){Ec(t,t.return,c)}}function vu(e){var t=e.updateQueue;if(null!==t){var n=e.stateNode;try{za(t,n)}catch(r){Ec(e,e.return,r)}}}function bu(e,t,n){n.props=Ei(e.type,e.memoizedProps),n.state=e.memoizedState;try{n.componentWillUnmount()}catch(r){Ec(e,t,r)}}function ku(e,t){try{var n=e.ref;if(null!==n){switch(e.tag){case 26:case 27:case 5:var r=e.stateNode;break;default:r=e.stateNode}"function"==typeof n?e.refCleanup=n(r):n.current=r}}catch(l){Ec(e,t,l)}}function wu(e,t){var n=e.ref,r=e.refCleanup;if(null!==n)if("function"==typeof r)try{r()}catch(l){Ec(e,t,l)}finally{e.refCleanup=null,null!=(e=e.alternate)&&(e.refCleanup=null)}else if("function"==typeof n)try{n(null)}catch(a){Ec(e,t,a)}else n.current=null}function Su(e){var t=e.type,n=e.memoizedProps,r=e.stateNode;try{e:switch(t){case"button":case"input":case"select":case"textarea":n.autoFocus&&r.focus();break e;case"img":n.src?r.src=n.src:n.srcSet&&(r.srcset=n.srcSet)}}catch(l){Ec(e,e.return,l)}}function Eu(e,t,n){try{var r=e.stateNode;!function(e,t,n,r){switch(t){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"input":var l=null,a=null,o=null,u=null,s=null,c=null,f=null;for(m in n){var d=n[m];if(n.hasOwnProperty(m)&&null!=d)switch(m){case"checked":case"value":break;case"defaultValue":s=d;default:r.hasOwnProperty(m)||ff(e,t,m,null,r,d)}}for(var p in r){var m=r[p];if(d=n[p],r.hasOwnProperty(p)&&(null!=m||null!=d))switch(p){case"type":a=m;break;case"name":l=m;break;case"checked":c=m;break;case"defaultChecked":f=m;break;case"value":o=m;break;case"defaultValue":u=m;break;case"children":case"dangerouslySetInnerHTML":if(null!=m)throw Error(i(137,t));break;default:m!==d&&ff(e,t,p,m,r,d)}}return void vt(e,o,u,s,c,f,a,l);case"select":for(a in m=o=u=p=null,n)if(s=n[a],n.hasOwnProperty(a)&&null!=s)switch(a){case"value":break;case"multiple":m=s;default:r.hasOwnProperty(a)||ff(e,t,a,null,r,s)}for(l in r)if(a=r[l],s=n[l],r.hasOwnProperty(l)&&(null!=a||null!=s))switch(l){case"value":p=a;break;case"defaultValue":u=a;break;case"multiple":o=a;default:a!==s&&ff(e,t,l,a,r,s)}return t=u,n=o,r=m,void(null!=p?wt(e,!!n,p,!1):!!r!=!!n&&(null!=t?wt(e,!!n,t,!0):wt(e,!!n,n?[]:"",!1)));case"textarea":for(u in m=p=null,n)if(l=n[u],n.hasOwnProperty(u)&&null!=l&&!r.hasOwnProperty(u))switch(u){case"value":case"children":break;default:ff(e,t,u,null,r,l)}for(o in r)if(l=r[o],a=n[o],r.hasOwnProperty(o)&&(null!=l||null!=a))switch(o){case"value":p=l;break;case"defaultValue":m=l;break;case"children":break;case"dangerouslySetInnerHTML":if(null!=l)throw Error(i(91));break;default:l!==a&&ff(e,t,o,l,r,a)}return void St(e,p,m);case"option":for(var h in n)p=n[h],n.hasOwnProperty(h)&&null!=p&&!r.hasOwnProperty(h)&&("selected"===h?e.selected=!1:ff(e,t,h,null,r,p));for(s in r)p=r[s],m=n[s],!r.hasOwnProperty(s)||p===m||null==p&&null==m||("selected"===s?e.selected=p&&"function"!=typeof p&&"symbol"!=typeof p:ff(e,t,s,p,r,m));return;case"img":case"link":case"area":case"base":case"br":case"col":case"embed":case"hr":case"keygen":case"meta":case"param":case"source":case"track":case"wbr":case"menuitem":for(var g in n)p=n[g],n.hasOwnProperty(g)&&null!=p&&!r.hasOwnProperty(g)&&ff(e,t,g,null,r,p);for(c in r)if(p=r[c],m=n[c],r.hasOwnProperty(c)&&p!==m&&(null!=p||null!=m))switch(c){case"children":case"dangerouslySetInnerHTML":if(null!=p)throw Error(i(137,t));break;default:ff(e,t,c,p,r,m)}return;default:if(Pt(t)){for(var y in n)p=n[y],n.hasOwnProperty(y)&&void 0!==p&&!r.hasOwnProperty(y)&&df(e,t,y,void 0,r,p);for(f in r)p=r[f],m=n[f],!r.hasOwnProperty(f)||p===m||void 0===p&&void 0===m||df(e,t,f,p,r,m);return}}for(var v in n)p=n[v],n.hasOwnProperty(v)&&null!=p&&!r.hasOwnProperty(v)&&ff(e,t,v,null,r,p);for(d in r)p=r[d],m=n[d],!r.hasOwnProperty(d)||p===m||null==p&&null==m||ff(e,t,d,p,r,m)}(r,e.type,n,t),r[$e]=t}catch(l){Ec(e,e.return,l)}}function Cu(e){return 5===e.tag||3===e.tag||26===e.tag||27===e.tag&&_f(e.type)||4===e.tag}function xu(e){e:for(;;){for(;null===e.sibling;){if(null===e.return||Cu(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;5!==e.tag&&6!==e.tag&&18!==e.tag;){if(27===e.tag&&_f(e.type))continue e;if(2&e.flags)continue e;if(null===e.child||4===e.tag)continue e;e.child.return=e,e=e.child}if(!(2&e.flags))return e.stateNode}}function zu(e,t,n){var r=e.tag;if(5===r||6===r)e=e.stateNode,t?(9===n.nodeType?n.body:"HTML"===n.nodeName?n.ownerDocument.body:n).insertBefore(e,t):((t=9===n.nodeType?n.body:"HTML"===n.nodeName?n.ownerDocument.body:n).appendChild(e),null!=(n=n._reactRootContainer)||null!==t.onclick||(t.onclick=Ot));else if(4!==r&&(27===r&&_f(e.type)&&(n=e.stateNode,t=null),null!==(e=e.child)))for(zu(e,t,n),e=e.sibling;null!==e;)zu(e,t,n),e=e.sibling}function _u(e,t,n){var r=e.tag;if(5===r||6===r)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(4!==r&&(27===r&&_f(e.type)&&(n=e.stateNode),null!==(e=e.child)))for(_u(e,t,n),e=e.sibling;null!==e;)_u(e,t,n),e=e.sibling}function Pu(e){var t=e.stateNode,n=e.memoizedProps;try{for(var r=e.type,l=t.attributes;l.length;)t.removeAttributeNode(l[0]);pf(t,r,n),t[He]=e,t[$e]=n}catch(a){Ec(e,e.return,a)}}var Nu=!1,Tu=!1,Lu=!1,Ou="function"==typeof WeakSet?WeakSet:Set,Du=null;function Fu(e,t,n){var r=n.flags;switch(n.tag){case 0:case 11:case 15:Ku(e,n),4&r&&gu(5,n);break;case 1:if(Ku(e,n),4&r)if(e=n.stateNode,null===t)try{e.componentDidMount()}catch(o){Ec(n,n.return,o)}else{var l=Ei(n.type,t.memoizedProps);t=t.memoizedState;try{e.componentDidUpdate(l,t,e.__reactInternalSnapshotBeforeUpdate)}catch(i){Ec(n,n.return,i)}}64&r&&vu(n),512&r&&ku(n,n.return);break;case 3:if(Ku(e,n),64&r&&null!==(e=n.updateQueue)){if(t=null,null!==n.child)switch(n.child.tag){case 27:case 5:case 1:t=n.child.stateNode}try{za(e,t)}catch(o){Ec(n,n.return,o)}}break;case 27:null===t&&4&r&&Pu(n);case 26:case 5:Ku(e,n),null===t&&4&r&&Su(n),512&r&&ku(n,n.return);break;case 12:Ku(e,n);break;case 31:Ku(e,n),4&r&&ju(e,n);break;case 13:Ku(e,n),4&r&&Hu(e,n),64&r&&null!==(e=n.memoizedState)&&null!==(e=e.dehydrated)&&function(e,t){var n=e.ownerDocument;if("$~"===e.data)e._reactRetry=t;else if("$?"!==e.data||"loading"!==n.readyState)t();else{var r=function(){t(),n.removeEventListener("DOMContentLoaded",r)};n.addEventListener("DOMContentLoaded",r),e._reactRetry=r}}(e,n=_c.bind(null,n));break;case 22:if(!(r=null!==n.memoizedState||Nu)){t=null!==t&&null!==t.memoizedState||Tu,l=Nu;var a=Tu;Nu=r,(Tu=t)&&!a?Gu(e,n,!!(8772&n.subtreeFlags)):Ku(e,n),Nu=l,Tu=a}break;case 30:break;default:Ku(e,n)}}function Ru(e){var t=e.alternate;null!==t&&(e.alternate=null,Ru(t)),e.child=null,e.deletions=null,e.sibling=null,5===e.tag&&null!==(t=e.stateNode)&&Ye(t),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}var Au=null,Mu=!1;function Iu(e,t,n){for(n=n.child;null!==n;)Uu(e,t,n),n=n.sibling}function Uu(e,t,n){if(ve&&"function"==typeof ve.onCommitFiberUnmount)try{ve.onCommitFiberUnmount(ye,n)}catch(a){}switch(n.tag){case 26:Tu||wu(n,t),Iu(e,t,n),n.memoizedState?n.memoizedState.count--:n.stateNode&&(n=n.stateNode).parentNode.removeChild(n);break;case 27:Tu||wu(n,t);var r=Au,l=Mu;_f(n.type)&&(Au=n.stateNode,Mu=!1),Iu(e,t,n),Uf(n.stateNode),Au=r,Mu=l;break;case 5:Tu||wu(n,t);case 6:if(r=Au,l=Mu,Au=null,Iu(e,t,n),Mu=l,null!==(Au=r))if(Mu)try{(9===Au.nodeType?Au.body:"HTML"===Au.nodeName?Au.ownerDocument.body:Au).removeChild(n.stateNode)}catch(o){Ec(n,t,o)}else try{Au.removeChild(n.stateNode)}catch(o){Ec(n,t,o)}break;case 18:null!==Au&&(Mu?(Pf(9===(e=Au).nodeType?e.body:"HTML"===e.nodeName?e.ownerDocument.body:e,n.stateNode),Vd(e)):Pf(Au,n.stateNode));break;case 4:r=Au,l=Mu,Au=n.stateNode.containerInfo,Mu=!0,Iu(e,t,n),Au=r,Mu=l;break;case 0:case 11:case 14:case 15:yu(2,n,t),Tu||yu(4,n,t),Iu(e,t,n);break;case 1:Tu||(wu(n,t),"function"==typeof(r=n.stateNode).componentWillUnmount&&bu(n,t,r)),Iu(e,t,n);break;case 21:Iu(e,t,n);break;case 22:Tu=(r=Tu)||null!==n.memoizedState,Iu(e,t,n),Tu=r;break;default:Iu(e,t,n)}}function ju(e,t){if(null===t.memoizedState&&null!==(e=t.alternate)&&null!==(e=e.memoizedState)){e=e.dehydrated;try{Vd(e)}catch(n){Ec(t,t.return,n)}}}function Hu(e,t){if(null===t.memoizedState&&null!==(e=t.alternate)&&null!==(e=e.memoizedState)&&null!==(e=e.dehydrated))try{Vd(e)}catch(n){Ec(t,t.return,n)}}function $u(e,t){var n=function(e){switch(e.tag){case 31:case 13:case 19:var t=e.stateNode;return null===t&&(t=e.stateNode=new Ou),t;case 22:return null===(t=(e=e.stateNode)._retryCache)&&(t=e._retryCache=new Ou),t;default:throw Error(i(435,e.tag))}}(e);t.forEach(function(t){if(!n.has(t)){n.add(t);var r=Pc.bind(null,e,t);t.then(r,r)}})}function Vu(e,t){var n=t.deletions;if(null!==n)for(var r=0;r title"))),pf(a,r,n),a[He]=e,et(a),r=a;break e;case"link":var o=rd("link","href",l).get(r+(n.href||""));if(o)for(var u=0;ui)break;var c=u.transferSize,f=u.initiatorType;c&&mf(f)&&(o+=c*((u=u.responseEnd)od?50:800)+t);return e.unsuspend=n,function(){e.unsuspend=null,clearTimeout(r),clearTimeout(l)}}:null}(f,m)))return js=a,e.cancelPendingCommit=m(hc.bind(null,e,t,a,n,r,l,o,i,u,c,f,null,d,p)),void Zs(e,a,o,!s)}hc(e,t,a,n,r,l,o,i,u)}function Xs(e){for(var t=e;;){var n=t.tag;if((0===n||11===n||15===n)&&16384&t.flags&&null!==(n=t.updateQueue)&&null!==(n=n.stores))for(var r=0;rg&&(o=g,g=h,h=o);var y=tr(i,h),v=tr(i,g);if(y&&v&&(1!==p.rangeCount||p.anchorNode!==y.node||p.anchorOffset!==y.offset||p.focusNode!==v.node||p.focusOffset!==v.offset)){var b=f.createRange();b.setStart(y.node,y.offset),p.removeAllRanges(),h>g?(p.addRange(b),p.extend(v.node,v.offset)):(b.setEnd(v.node,v.offset),p.addRange(b))}}}}for(f=[],p=i;p=p.parentNode;)1===p.nodeType&&f.push({element:p,left:p.scrollLeft,top:p.scrollTop});for("function"==typeof i.focus&&i.focus(),i=0;in?32:n,F.T=null,n=$s,$s=null;var a=Is,o=js;if(Ms=0,Us=Is=null,js=0,6&ps)throw Error(i(331));var u=ps;if(ps|=4,us(a.current),es(a,a.current,o,n),ps=u,Ac(0,!1),ve&&"function"==typeof ve.onPostCommitFiberRoot)try{ve.onPostCommitFiberRoot(ye,a)}catch(s){}return!0}finally{R.p=l,F.T=r,bc(e,t)}}function Sc(e,t,n){t=Kr(n,t),null!==(e=ba(e,t=Ni(e.stateNode,t,2),2))&&(Oe(e,2),Rc(e))}function Ec(e,t,n){if(3===e.tag)Sc(e,e,n);else for(;null!==t;){if(3===t.tag){Sc(t,e,n);break}if(1===t.tag){var r=t.stateNode;if("function"==typeof t.type.getDerivedStateFromError||"function"==typeof r.componentDidCatch&&(null===As||!As.has(r))){e=Kr(n,e),null!==(r=ba(t,n=Ti(2),2))&&(Li(n,r,t,e),Oe(r,2),Rc(r));break}}t=t.return}}function Cc(e,t,n){var r=e.pingCache;if(null===r){r=e.pingCache=new ds;var l=new Set;r.set(t,l)}else void 0===(l=r.get(t))&&(l=new Set,r.set(t,l));l.has(n)||(ws=!0,l.add(n),e=xc.bind(null,e,t,n),t.then(e,e))}function xc(e,t,n){var r=e.pingCache;null!==r&&r.delete(t),e.pingedLanes|=e.suspendedLanes&n,e.warmLanes&=~n,ms===e&&(gs&n)===n&&(4===Es||3===Es&&(62914560&gs)===gs&&300>ue()-Os?!(2&ps)&&tc(e,0):zs|=n,Ps===gs&&(Ps=0)),Rc(e)}function zc(e,t){0===t&&(t=Te()),null!==(e=Dr(e,t))&&(Oe(e,t),Rc(e))}function _c(e){var t=e.memoizedState,n=0;null!==t&&(n=t.retryLane),zc(e,n)}function Pc(e,t){var n=0;switch(e.tag){case 31:case 13:var r=e.stateNode,l=e.memoizedState;null!==l&&(n=l.retryLane);break;case 19:r=e.stateNode;break;case 22:r=e.stateNode._retryCache;break;default:throw Error(i(314))}null!==r&&r.delete(t),zc(e,n)}var Nc=null,Tc=null,Lc=!1,Oc=!1,Dc=!1,Fc=0;function Rc(e){e!==Tc&&null===e.next&&(null===Tc?Nc=Tc=e:Tc=Tc.next=e),Oc=!0,Lc||(Lc=!0,xf(function(){6&ps?le(ce,Mc):Ic()}))}function Ac(e,t){if(!Dc&&Oc){Dc=!0;do{for(var n=!1,r=Nc;null!==r;){if(!t)if(0!==e){var l=r.pendingLanes;if(0===l)var a=0;else{var o=r.suspendedLanes,i=r.pingedLanes;a=(1<<31-ke(42|e)+1)-1,a=201326741&(a&=l&~(o&~i))?201326741&a|1:a?2|a:0}0!==a&&(n=!0,Hc(r,a))}else a=gs,!(3&(a=_e(r,r===ms?a:0,null!==r.cancelPendingCommit||-1!==r.timeoutHandle)))||Pe(r,a)||(n=!0,Hc(r,a));r=r.next}}while(n);Dc=!1}}function Mc(){Ic()}function Ic(){Oc=Lc=!1;var e,t=0;0!==Fc&&((e=window.event)&&"popstate"===e.type?e!==wf&&(wf=e,1):(wf=null,0))&&(t=Fc);for(var n=ue(),r=null,l=Nc;null!==l;){var a=l.next,o=Uc(l,n);0===o?(l.next=null,null===r?Nc=a:r.next=a,null===a&&(Tc=r)):(r=l,(0!==t||3&o)&&(Oc=!0)),l=a}0!==Ms&&5!==Ms||Ac(t,!1),0!==Fc&&(Fc=0)}function Uc(e,t){for(var n=e.suspendedLanes,r=e.pingedLanes,l=e.expirationTimes,a=-62914561&e.pendingLanes;0 title"):null)}function ad(e){return!!("stylesheet"!==e.type||3&e.state.loading)}var od=0;function id(){if(this.count--,0===this.count&&(0===this.imgCount||!this.waitingForImages))if(this.stylesheets)sd(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}var ud=null;function sd(e,t){e.stylesheets=null,null!==e.unsuspend&&(e.count++,ud=new Map,t.forEach(cd,e),ud=null,id.call(e))}function cd(e,t){if(!(4&t.state.loading)){var n=ud.get(e);if(n)var r=n.get(null);else{n=new Map,ud.set(e,n);for(var l=e.querySelectorAll("link[data-precedence],style[data-precedence]"),a=0;a{!function e(){if("undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE)try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}(),t.exports=i()}),s=e(e=>{var t=Symbol.for("react.transitional.element"),n=Symbol.for("react.fragment");function r(e,n,r){var l=null;if(void 0!==r&&(l=""+r),void 0!==n.key&&(l=""+n.key),"key"in n)for(var a in r={},n)"key"!==a&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:l,ref:void 0!==n?n:null,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r}),c=e((e,t)=>{t.exports=s()});export{u as n,n as r,c as t}; \ No newline at end of file diff --git a/examples/gltf/animation/basicAnimations/index.html b/examples/gltf/animation/basicAnimations/index.html index 10c47c2e29..940f8bcbb8 100644 --- a/examples/gltf/animation/basicAnimations/index.html +++ b/examples/gltf/animation/basicAnimations/index.html @@ -39,12 +39,12 @@ } - - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - + + - - + + @@ -52,5 +52,8 @@

- - - - - + + + + +