import{DoubleSide as P,Color as M,NoColorSpace as E}from"./three-Cut12-XQ.js";import{s as b,z as U}from"./fflate.module-Cv5q2yBc.js";class j{constructor(){this.textureUtils=null}setTextureUtils(n){this.textureUtils=n}parse(n,s,o,t){this.parseAsync(n,t).then(s).catch(o)}async parseAsync(n,s={}){s=Object.assign({ar:{anchoring:{type:"plane"},planeAnchoring:{alignment:"horizontal"}},includeAnchoringProperties:!0,quickLookCompatible:!1,maxTextureSize:1024},s);const o={},t="model.usda";o[t]=null;let i=T();i+=C(s);const c={},u={};n.traverseVisible(r=>{if(r.isMesh){const p=r.geometry,d=r.material;if(d.isMeshStandardMaterial){const h="geometries/Geometry_"+p.id+".usda";if(!(h in o)){const l=D(p);o[h]=A(l)}d.uuid in c||(c[d.uuid]=d),i+=O(r,p,d)}else console.warn("THREE.USDZExporter: Unsupported material type (USDZ only supports MeshStandardMaterial)",r)}else r.isCamera&&(i+=F(r))}),i+=k(),i+=N(c,u,s.quickLookCompatible),o[t]=b(i),i=null;for(const r in u){let p=u[r];if(p.isCompressedTexture===!0){if(this.textureUtils===null)throw new Error("THREE.USDZExporter: setTextureUtils() must be called to process compressed textures.");p=await this.textureUtils.decompress(p)}const d=R(p.image,p.flipY,s.maxTextureSize),h=await new Promise(l=>d.toBlob(l,"image/png",1));o[`textures/Texture_${r}.png`]=new Uint8Array(await h.arrayBuffer())}let $=0;for(const r in o){const p=o[r],d=34+r.length;$+=d;const h=$&63;if(h!==4){const l=64-h,f=new Uint8Array(l);o[r]=[p,{extra:{12345:f}}]}$=p.length}return U(o,{level:0})}}function R(e,n,s){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const o=s/Math.max(e.width,e.height),t=document.createElement("canvas");t.width=e.width*Math.min(1,o),t.height=e.height*Math.min(1,o);const i=t.getContext("2d");return n===!0&&(i.translate(0,t.height),i.scale(1,-1)),i.drawImage(e,0,0,t.width,t.height),t}else throw new Error("THREE.USDZExporter: No valid image data found. Unable to process texture.")}const a=7;function T(){return`#usda 1.0
(
	customLayerData = {
		string creator = "Three.js USDZExporter"
	}
	defaultPrim = "Root"
	metersPerUnit = 1
	upAxis = "Y"
)

`}function C(e){return`def Xform "Root"
{
	def Scope "Scenes" (
		kind = "sceneLibrary"
	)
	{
		def Xform "Scene" (
			customData = {
				bool preliminary_collidesWithEnvironment = 0
				string sceneName = "Scene"
			}
			sceneName = "Scene"
		)
		{${e.includeAnchoringProperties===!0?`
		token preliminary:anchoring:type = "${e.ar.anchoring.type}"
		token preliminary:planeAnchoring:alignment = "${e.ar.planeAnchoring.alignment}"
	`:""}
`}function k(){return`
		}
	}
}

`}function A(e){let n=T();return n+=e,b(n)}function O(e,n,s){const o="Object_"+e.id,t=w(e.matrixWorld);return e.matrixWorld.determinant()<0&&console.warn("THREE.USDZExporter: USDZ does not support negative scales",e),`def Xform "${o}" (
	prepend references = @./geometries/Geometry_${n.id}.usda@</Geometry>
	prepend apiSchemas = ["MaterialBindingAPI"]
)
{
	matrix4d xformOp:transform = ${t}
	uniform token[] xformOpOrder = ["xformOp:transform"]

	rel material:binding = </Materials/Material_${s.id}>
}

`}function w(e){const n=e.elements;return`( ${g(n,0)}, ${g(n,4)}, ${g(n,8)}, ${g(n,12)} )`}function g(e,n){return`(${e[n+0]}, ${e[n+1]}, ${e[n+2]}, ${e[n+3]})`}function D(e){return`
def "Geometry"
{
${I(e)}
}
`}function I(e){const n="Geometry",s=e.attributes,o=s.position.count;return`
	def Mesh "${n}"
	{
		int[] faceVertexCounts = [${Z(e)}]
		int[] faceVertexIndices = [${H(e)}]
		normal3f[] normals = [${m(s.normal,o)}] (
			interpolation = "vertex"
		)
		point3f[] points = [${m(s.position,o)}]
${z(s)}
		uniform token subdivisionScheme = "none"
	}
`}function Z(e){const n=e.index!==null?e.index.count:e.attributes.position.count;return Array(n/3).fill(3).join(", ")}function H(e){const n=e.index,s=[];if(n!==null)for(let o=0;o<n.count;o++)s.push(n.getX(o));else{const o=e.attributes.position.count;for(let t=0;t<o;t++)s.push(t)}return s.join(", ")}function m(e,n){if(e===void 0)return console.warn("USDZExporter: Normals missing."),Array(n).fill("(0, 0, 0)").join(", ");const s=[];for(let o=0;o<e.count;o++){const t=e.getX(o),i=e.getY(o),c=e.getZ(o);s.push(`(${t.toPrecision(a)}, ${i.toPrecision(a)}, ${c.toPrecision(a)})`)}return s.join(", ")}function L(e){const n=[];for(let s=0;s<e.count;s++){const o=e.getX(s),t=e.getY(s);n.push(`(${o.toPrecision(a)}, ${1-t.toPrecision(a)})`)}return n.join(", ")}function z(e){let n="";for(let o=0;o<4;o++){const t=o>0?o:"",i=e["uv"+t];i!==void 0&&(n+=`
		texCoord2f[] primvars:st${t} = [${L(i)}] (
			interpolation = "vertex"
		)`)}const s=e.color;if(s!==void 0){const o=s.count;n+=`
	color3f[] primvars:displayColor = [${m(s,o)}] (
		interpolation = "vertex"
		)`}return n}function N(e,n,s=!1){const o=[];for(const t in e){const i=e[t];o.push(V(i,n,s))}return`def "Materials"
{
${o.join("")}
}

`}function V(e,n,s=!1){const t=[],i=[];function c(u,$,r){const p=u.source.id+"_"+u.flipY;n[p]=u;const d=u.channel>0?"st"+u.channel:"st",h={1e3:"repeat",1001:"clamp",1002:"mirror"},l=u.repeat.clone(),f=u.offset.clone(),x=u.rotation,y=Math.sin(x),_=Math.cos(x);return f.y=1-f.y-l.y,s?(f.x=f.x/l.x,f.y=f.y/l.y,f.x+=y/l.x,f.y+=_-1):(f.x+=y*l.x,f.y+=(1-_)*l.y),`
		def Shader "PrimvarReader_${$}"
		{
			uniform token info:id = "UsdPrimvarReader_float2"
			float2 inputs:fallback = (0.0, 0.0)
			token inputs:varname = "${d}"
			float2 outputs:result
		}

		def Shader "Transform2d_${$}"
		{
			uniform token info:id = "UsdTransform2d"
			token inputs:in.connect = </Materials/Material_${e.id}/PrimvarReader_${$}.outputs:result>
			float inputs:rotation = ${(x*(180/Math.PI)).toFixed(a)}
			float2 inputs:scale = ${S(l)}
			float2 inputs:translation = ${S(f)}
			float2 outputs:result
		}

		def Shader "Texture_${u.id}_${$}"
		{
			uniform token info:id = "UsdUVTexture"
			asset inputs:file = @textures/Texture_${p}.png@
			float2 inputs:st.connect = </Materials/Material_${e.id}/Transform2d_${$}.outputs:result>
			${r!==void 0?"float4 inputs:scale = "+W(r):""}
			token inputs:sourceColorSpace = "${u.colorSpace===E?"raw":"sRGB"}"
			token inputs:wrapS = "${h[u.wrapS]}"
			token inputs:wrapT = "${h[u.wrapT]}"
			float outputs:r
			float outputs:g
			float outputs:b
			float3 outputs:rgb
			${e.transparent||e.alphaTest>0?"float outputs:a":""}
		}`}return e.side===P&&console.warn("THREE.USDZExporter: USDZ does not support double sided materials",e),e.map!==null?(t.push(`			color3f inputs:diffuseColor.connect = </Materials/Material_${e.id}/Texture_${e.map.id}_diffuse.outputs:rgb>`),e.transparent?t.push(`			float inputs:opacity.connect = </Materials/Material_${e.id}/Texture_${e.map.id}_diffuse.outputs:a>`):e.alphaTest>0&&(t.push(`			float inputs:opacity.connect = </Materials/Material_${e.id}/Texture_${e.map.id}_diffuse.outputs:a>`),t.push(`			float inputs:opacityThreshold = ${e.alphaTest}`)),i.push(c(e.map,"diffuse",e.color))):t.push(`			color3f inputs:diffuseColor = ${v(e.color)}`),e.emissiveMap!==null?(t.push(`			color3f inputs:emissiveColor.connect = </Materials/Material_${e.id}/Texture_${e.emissiveMap.id}_emissive.outputs:rgb>`),i.push(c(e.emissiveMap,"emissive",new M(e.emissive.r*e.emissiveIntensity,e.emissive.g*e.emissiveIntensity,e.emissive.b*e.emissiveIntensity)))):e.emissive.getHex()>0&&t.push(`			color3f inputs:emissiveColor = ${v(e.emissive)}`),e.normalMap!==null&&(t.push(`			normal3f inputs:normal.connect = </Materials/Material_${e.id}/Texture_${e.normalMap.id}_normal.outputs:rgb>`),i.push(c(e.normalMap,"normal"))),e.aoMap!==null&&(t.push(`			float inputs:occlusion.connect = </Materials/Material_${e.id}/Texture_${e.aoMap.id}_occlusion.outputs:r>`),i.push(c(e.aoMap,"occlusion",new M(e.aoMapIntensity,e.aoMapIntensity,e.aoMapIntensity)))),e.roughnessMap!==null?(t.push(`			float inputs:roughness.connect = </Materials/Material_${e.id}/Texture_${e.roughnessMap.id}_roughness.outputs:g>`),i.push(c(e.roughnessMap,"roughness",new M(e.roughness,e.roughness,e.roughness)))):t.push(`			float inputs:roughness = ${e.roughness}`),e.metalnessMap!==null?(t.push(`			float inputs:metallic.connect = </Materials/Material_${e.id}/Texture_${e.metalnessMap.id}_metallic.outputs:b>`),i.push(c(e.metalnessMap,"metallic",new M(e.metalness,e.metalness,e.metalness)))):t.push(`			float inputs:metallic = ${e.metalness}`),e.alphaMap!==null?(t.push(`			float inputs:opacity.connect = </Materials/Material_${e.id}/Texture_${e.alphaMap.id}_opacity.outputs:r>`),t.push("			float inputs:opacityThreshold = 0.0001"),i.push(c(e.alphaMap,"opacity"))):t.push(`			float inputs:opacity = ${e.opacity}`),e.isMeshPhysicalMaterial&&(e.clearcoatMap!==null?(t.push(`			float inputs:clearcoat.connect = </Materials/Material_${e.id}/Texture_${e.clearcoatMap.id}_clearcoat.outputs:r>`),i.push(c(e.clearcoatMap,"clearcoat",new M(e.clearcoat,e.clearcoat,e.clearcoat)))):t.push(`			float inputs:clearcoat = ${e.clearcoat}`),e.clearcoatRoughnessMap!==null?(t.push(`			float inputs:clearcoatRoughness.connect = </Materials/Material_${e.id}/Texture_${e.clearcoatRoughnessMap.id}_clearcoatRoughness.outputs:g>`),i.push(c(e.clearcoatRoughnessMap,"clearcoatRoughness",new M(e.clearcoatRoughness,e.clearcoatRoughness,e.clearcoatRoughness)))):t.push(`			float inputs:clearcoatRoughness = ${e.clearcoatRoughness}`),t.push(`			float inputs:ior = ${e.ior}`)),`
	def Material "Material_${e.id}"
	{
		def Shader "PreviewSurface"
		{
			uniform token info:id = "UsdPreviewSurface"
${t.join(`
`)}
			int inputs:useSpecularWorkflow = 0
			token outputs:surface
		}

		token outputs:surface.connect = </Materials/Material_${e.id}/PreviewSurface.outputs:surface>

${i.join(`
`)}

	}
`}function v(e){return`(${e.r}, ${e.g}, ${e.b})`}function W(e){return`(${e.r}, ${e.g}, ${e.b}, 1.0)`}function S(e){return`(${e.x}, ${e.y})`}function F(e){const n=e.name?e.name:"Camera_"+e.id,s=w(e.matrixWorld);return e.matrixWorld.determinant()<0&&console.warn("THREE.USDZExporter: USDZ does not support negative scales",e),e.isOrthographicCamera?`def Camera "${n}"
		{
			matrix4d xformOp:transform = ${s}
			uniform token[] xformOpOrder = ["xformOp:transform"]

			float2 clippingRange = (${e.near.toPrecision(a)}, ${e.far.toPrecision(a)})
			float horizontalAperture = ${((Math.abs(e.left)+Math.abs(e.right))*10).toPrecision(a)}
			float verticalAperture = ${((Math.abs(e.top)+Math.abs(e.bottom))*10).toPrecision(a)}
			token projection = "orthographic"
		}
	
	`:`def Camera "${n}"
		{
			matrix4d xformOp:transform = ${s}
			uniform token[] xformOpOrder = ["xformOp:transform"]

			float2 clippingRange = (${e.near.toPrecision(a)}, ${e.far.toPrecision(a)})
			float focalLength = ${e.getFocalLength().toPrecision(a)}
			float focusDistance = ${e.focus.toPrecision(a)}
			float horizontalAperture = ${e.getFilmWidth().toPrecision(a)}
			token projection = "perspective"
			float verticalAperture = ${e.getFilmHeight().toPrecision(a)}
		}
	
	`}export{j as USDZExporter};
//# sourceMappingURL=USDZExporter-mwQsHhSS.js.map
