@npm9912/v-map 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/README.md +17 -5
  2. package/dist/cjs/{cesium-provider-BiFFyAl9.js → cesium-provider-CTtu9eTD.js} +6 -5
  3. package/dist/cjs/{deck-provider-Ctq3Q8a1.js → deck-provider-fNa818HH.js} +9 -9
  4. package/dist/cjs/events-BMG7RKne.js +11 -0
  5. package/dist/cjs/{geotiff-source-RaNzzWkC.js → geotiff-source-B9ARUE9z.js} +1 -1
  6. package/dist/cjs/{index-ISOEpMC3.js → index-9APmzoa2.js} +6 -6
  7. package/dist/cjs/{index-CbVT-Con.js → index-BJg0ncfC.js} +4 -4
  8. package/dist/cjs/{index-CJvvX4yx.js → index-C1ubapwF.js} +4 -4
  9. package/dist/cjs/{index-B8LHqjyg.js → index-ChrKyU6i.js} +4 -4
  10. package/dist/cjs/{index-JSwBbvGA.js → index-DmGHwivM.js} +1 -0
  11. package/dist/cjs/{layer-extension-B_olS0rc.js → layer-extension-D3a-1DFI.js} +1 -1
  12. package/dist/cjs/{leaflet-provider-DOqfs7g5.js → leaflet-provider-7Nw-AdV_.js} +6 -5
  13. package/dist/cjs/loader.cjs.js +2 -2
  14. package/dist/cjs/{messages-D7h4m8Tx.js → messages-CFCxeG8p.js} +0 -9
  15. package/dist/cjs/{openlayers-provider-Dfeg6L4n.js → openlayers-provider-DMxYtFkS.js} +5 -4
  16. package/dist/cjs/{polygon-layer-B9PrN7vr.js → polygon-layer-Dx1ZWZP0.js} +1 -1
  17. package/dist/cjs/{scenegraph-layer-DwNoxQdi.js → scenegraph-layer-ctLehP0q.js} +1 -1
  18. package/dist/cjs/v-map-builder.cjs.entry.js +4 -3
  19. package/dist/cjs/v-map-error.cjs.entry.js +121 -0
  20. package/dist/cjs/v-map-layer-geojson_12.cjs.entry.js +11 -10
  21. package/dist/cjs/{v-map-layer-helper-iAzxAg9I.js → v-map-layer-helper-DnWpjZ_Q.js} +7 -6
  22. package/dist/cjs/v-map-layer-terrain-geotiff.cjs.entry.js +5 -4
  23. package/dist/cjs/v-map-layercontrol.cjs.entry.js +1 -1
  24. package/dist/cjs/v-map.cjs.js +2 -2
  25. package/dist/cjs/{v-map.v-map-layer-osm.v-map-layergroup-BsXp3BoL.js → v-map.v-map-layer-osm.v-map-layergroup-BJ3_NqAj.js} +16 -15
  26. package/dist/cjs/v-map_3.cjs.entry.js +5 -4
  27. package/dist/collection/collection-manifest.json +1 -0
  28. package/dist/collection/components/v-map/v-map.css +3 -0
  29. package/dist/collection/components/v-map-error/v-map-error.css +136 -0
  30. package/dist/collection/components/v-map-error/v-map-error.js +277 -0
  31. package/dist/collection/components/v-map-layer-geojson/v-map-layer-geojson.js +1 -1
  32. package/dist/collection/components/v-map-layer-terrain/v-map-layer-terrain.js +1 -1
  33. package/dist/collection/components/v-map-layer-terrain-geotiff/v-map-layer-terrain-geotiff.js +1 -1
  34. package/dist/collection/components/v-map-layer-tile3d/v-map-layer-tile3d.js +1 -1
  35. package/dist/collection/components/v-map-layer-wcs/v-map-layer-wcs.js +1 -1
  36. package/dist/collection/components/v-map-layer-wfs/v-map-layer-wfs.js +1 -1
  37. package/dist/collection/components/v-map-layergroup/v-map-layergroup.js +1 -1
  38. package/dist/collection/components/v-map-style/v-map-style.js +1 -1
  39. package/dist/components/cesium-provider.js +1 -1
  40. package/dist/components/deck-provider.js +1 -1
  41. package/dist/components/events.js +1 -1
  42. package/dist/components/geotiff-source.js +1 -1
  43. package/dist/components/leaflet-provider.js +1 -1
  44. package/dist/components/logger.js +1 -0
  45. package/dist/components/openlayers-provider.js +1 -1
  46. package/dist/components/v-map-builder.js +2 -2
  47. package/dist/components/v-map-error.d.ts +11 -0
  48. package/dist/components/v-map-error.js +1 -0
  49. package/dist/components/v-map-layer-geojson2.js +1 -1
  50. package/dist/components/v-map-layer-geotiff2.js +1 -1
  51. package/dist/components/v-map-layer-google2.js +1 -1
  52. package/dist/components/v-map-layer-helper.js +1 -1
  53. package/dist/components/v-map-layer-osm2.js +1 -1
  54. package/dist/components/v-map-layer-scatterplot2.js +1 -1
  55. package/dist/components/v-map-layer-terrain-geotiff.js +1 -1
  56. package/dist/components/v-map-layer-terrain2.js +1 -1
  57. package/dist/components/v-map-layer-tile3d2.js +1 -1
  58. package/dist/components/v-map-layer-wcs2.js +1 -1
  59. package/dist/components/v-map-layer-wfs2.js +1 -1
  60. package/dist/components/v-map-layer-wkt2.js +1 -1
  61. package/dist/components/v-map-layer-wms2.js +1 -1
  62. package/dist/components/v-map-layer-xyz2.js +1 -1
  63. package/dist/components/v-map-layergroup2.js +1 -1
  64. package/dist/components/v-map-style2.js +2 -2
  65. package/dist/components/v-map2.js +1 -1
  66. package/dist/esm/{cesium-provider-BJfAup3w.js → cesium-provider-Bh__cBGf.js} +6 -5
  67. package/dist/esm/{deck-provider-C7U9VDEq.js → deck-provider-DxIpS4lY.js} +9 -9
  68. package/dist/esm/events-CrV_misM.js +9 -0
  69. package/dist/esm/{geotiff-source-esnDnC-u.js → geotiff-source-BRjO-Dvr.js} +1 -1
  70. package/dist/esm/{index-BIEmlzCf.js → index-Bh2gBu9u.js} +5 -5
  71. package/dist/esm/{index-jzneDarq.js → index-BoNyIrdq.js} +1 -1
  72. package/dist/esm/{index-jN06TXUp.js → index-C3mnOs0I.js} +4 -4
  73. package/dist/esm/{index-B1zwA4IC.js → index-C63kfbil.js} +6 -6
  74. package/dist/esm/{index-DbSdn93t.js → index-DxbztwCv.js} +7 -7
  75. package/dist/esm/{layer-extension-CZXK5goK.js → layer-extension-C5Y2UES3.js} +1 -1
  76. package/dist/esm/{leaflet-provider-Q41TB6ku.js → leaflet-provider-k6JSYiYX.js} +6 -5
  77. package/dist/esm/loader.js +3 -3
  78. package/dist/esm/{messages-CMKJzsgL.js → messages-QJHuuz0g.js} +1 -9
  79. package/dist/esm/{openlayers-provider-CMsDsQTQ.js → openlayers-provider-DIquf3Tx.js} +5 -4
  80. package/dist/esm/{polygon-layer-ByhxGhWC.js → polygon-layer-ZIT5mJy5.js} +1 -1
  81. package/dist/esm/{scenegraph-layer-09K_B6DT.js → scenegraph-layer-CNIRd2uu.js} +1 -1
  82. package/dist/esm/v-map-builder.entry.js +3 -2
  83. package/dist/esm/v-map-error.entry.js +119 -0
  84. package/dist/esm/v-map-layer-geojson_12.entry.js +10 -9
  85. package/dist/esm/{v-map-layer-helper-Dys44Cgo.js → v-map-layer-helper-CuHYsU9f.js} +2 -1
  86. package/dist/esm/v-map-layer-terrain-geotiff.entry.js +5 -4
  87. package/dist/esm/v-map-layercontrol.entry.js +1 -1
  88. package/dist/esm/v-map.js +3 -3
  89. package/dist/esm/{v-map.v-map-layer-osm.v-map-layergroup-B4pFHuSf.js → v-map.v-map-layer-osm.v-map-layergroup-Zwdvm9PG.js} +10 -9
  90. package/dist/esm/v-map_3.entry.js +5 -4
  91. package/dist/types/components/v-map-error/v-map-error.d.ts +79 -0
  92. package/dist/types/components.d.ts +128 -0
  93. package/dist/v-map/p-05ee633f.entry.js +1 -0
  94. package/dist/v-map/p-08ad1392.entry.js +1 -0
  95. package/dist/v-map/p-2-mR3oVa.js +1 -0
  96. package/dist/v-map/{p-c21c93fe.entry.js → p-3a57b64a.entry.js} +1 -1
  97. package/dist/v-map/p-58dda864.entry.js +1 -0
  98. package/dist/v-map/p-915314c0.entry.js +10 -0
  99. package/dist/v-map/{p-MyTSFnEk.js → p-9Rt23jlQ.js} +1 -1
  100. package/dist/v-map/p-BSsFEMZP.js +1 -0
  101. package/dist/v-map/{p-jzneDarq.js → p-BoNyIrdq.js} +2 -2
  102. package/dist/v-map/p-BpE6L1g0.js +1 -0
  103. package/dist/v-map/{p-DvHXtWUg.js → p-C0M0-Kvt.js} +1 -1
  104. package/dist/v-map/p-CbiLpFhO.js +1 -0
  105. package/dist/v-map/p-Ci70E1EM.js +1 -0
  106. package/dist/v-map/p-CrV_misM.js +1 -0
  107. package/dist/v-map/{p-DrOQ9V4h.js → p-DAf4itFZ.js} +1 -1
  108. package/dist/v-map/p-DVBtCUtQ.js +1 -0
  109. package/dist/v-map/{p-CZqY0yW4.js → p-DuJ_mTaq.js} +1 -1
  110. package/dist/v-map/p-G6iftXUC.js +1 -0
  111. package/dist/v-map/{p-CMKJzsgL.js → p-QJHuuz0g.js} +1 -1
  112. package/dist/v-map/{p-aa410e64.entry.js → p-e21ea0ce.entry.js} +2 -2
  113. package/dist/v-map/{p-DmICdG34.js → p-rCyRSFJb.js} +2 -2
  114. package/dist/v-map/{p-CafTHT9i.js → p-vhbi5XXi.js} +1 -1
  115. package/dist/v-map/{p-Dckgonw8.js → p-yXLNXXx-.js} +1 -1
  116. package/dist/v-map/v-map.esm.js +1 -1
  117. package/package.json +1 -1
  118. package/dist/v-map/p--vVleK-M.js +0 -1
  119. package/dist/v-map/p-09d10db0.entry.js +0 -1
  120. package/dist/v-map/p-5eba6058.entry.js +0 -10
  121. package/dist/v-map/p-6b102336.entry.js +0 -1
  122. package/dist/v-map/p-BdijL4Av.js +0 -1
  123. package/dist/v-map/p-BeFu0ap4.js +0 -1
  124. package/dist/v-map/p-BxFJezdK.js +0 -1
  125. package/dist/v-map/p-DCTHyf58.js +0 -1
  126. package/dist/v-map/p-WaMDUuAz.js +0 -1
  127. package/dist/v-map/p-uiIP-taz.js +0 -1
@@ -1 +1 @@
1
- import{postProcessGLTF as n,GLTFLoader as e}from"@loaders.gl/gltf";import{aK as t,a0 as o,V as r,u as i,aL as a,M as s,G as l,aM as c,L as f,p,a as d,aN as u,j as m,aO as b}from"./p-MyTSFnEk.js";const g="uniform pbrProjectionUniforms {\n mat4 modelViewProjectionMatrix;\n mat4 modelMatrix;\n mat4 normalMatrix;\n vec3 camera;\n} pbrProjection;\n",h={props:{},uniforms:{},name:"pbrMaterial",dependencies:[t,{name:"pbrProjection",vs:g,fs:g,getUniforms:n=>n,uniformTypes:{modelViewProjectionMatrix:"mat4x4<f32>",modelMatrix:"mat4x4<f32>",normalMatrix:"mat4x4<f32>",camera:"vec3<i32>"}}],source:"struct PBRFragmentInputs {\n pbr_vPosition: vec3f,\n pbr_vUV: vec2f,\n pbr_vTBN: mat3f,\n pbr_vNormal: vec3f\n};\n\nvar fragmentInputs: PBRFragmentInputs;\n\nfn pbr_setPositionNormalTangentUV(position: vec4f, normal: vec4f, tangent: vec4f, uv: vec2f)\n{\n var pos: vec4f = pbrProjection.modelMatrix * position;\n pbr_vPosition = vec3(pos.xyz) / pos.w;\n\n#ifdef HAS_NORMALS\n#ifdef HAS_TANGENTS\n let normalW: vec3f = normalize(vec3(pbrProjection.normalMatrix * vec4(normal.xyz, 0.0)));\n let tangentW: vec3f = normalize(vec3(pbrProjection.modelMatrix * vec4(tangent.xyz, 0.0)));\n let bitangentW: vec3f = cross(normalW, tangentW) * tangent.w;\n fragmentInputs,pbr_vTBN = mat3(tangentW, bitangentW, normalW);\n#else // HAS_TANGENTS != 1\n fragmentInputs.pbr_vNormal = normalize(vec3(pbrProjection.modelMatrix * vec4(normal.xyz, 0.0)));\n#endif\n#endif\n\n#ifdef HAS_UV\n pbr_vUV = uv;\n#else\n pbr_vUV = vec2(0.,0.);\n#endif\n}\n\nstruct pbrMaterialUniforms {\n // Material is unlit\n unlit: uint32,\n\n // Base color map\n baseColorMapEnabled: uint32,\n baseColorFactor: vec4f,\n\n normalMapEnabled : uint32,\n normalScale: f32, // #ifdef HAS_NORMALMAP\n\n emissiveMapEnabled: uint32,\n emissiveFactor: vec3f, // #ifdef HAS_EMISSIVEMAP\n\n metallicRoughnessValues: vec2f,\n metallicRoughnessMapEnabled: uint32,\n\n occlusionMapEnabled: i32,\n occlusionStrength: f32, // #ifdef HAS_OCCLUSIONMAP\n \n alphaCutoffEnabled: i32,\n alphaCutoff: f32, // #ifdef ALPHA_CUTOFF\n \n // IBL\n IBLenabled: i32,\n scaleIBLAmbient: vec2f, // #ifdef USE_IBL\n \n // debugging flags used for shader output of intermediate PBR variables\n // #ifdef PBR_DEBUG\n scaleDiffBaseMR: vec4f,\n scaleFGDSpec: vec4f\n // #endif\n} \n \n@binding(2) @group(0) var<uniform> material : pbrMaterialUniforms;\n\n// Samplers\n#ifdef HAS_BASECOLORMAP\nuniform sampler2D pbr_baseColorSampler;\n#endif\n#ifdef HAS_NORMALMAP\nuniform sampler2D pbr_normalSampler;\n#endif\n#ifdef HAS_EMISSIVEMAP\nuniform sampler2D pbr_emissiveSampler;\n#endif\n#ifdef HAS_METALROUGHNESSMAP\nuniform sampler2D pbr_metallicRoughnessSampler;\n#endif\n#ifdef HAS_OCCLUSIONMAP\nuniform sampler2D pbr_occlusionSampler;\n#endif\n#ifdef USE_IBL\nuniform samplerCube pbr_diffuseEnvSampler;\nuniform samplerCube pbr_specularEnvSampler;\nuniform sampler2D pbr_brdfLUT;\n#endif\n\n// Encapsulate the various inputs used by the various functions in the shading equation\n// We store values in this struct to simplify the integration of alternative implementations\n// of the shading terms, outlined in the Readme.MD Appendix.\nstruct PBRInfo {\n NdotL: f32, // cos angle between normal and light direction\n NdotV: f32, // cos angle between normal and view direction\n NdotH: f32, // cos angle between normal and half vector\n LdotH: f32, // cos angle between light direction and half vector\n VdotH: f32, // cos angle between view direction and half vector\n perceptualRoughness: f32, // roughness value, as authored by the model creator (input to shader)\n metalness: f32, // metallic value at the surface\n reflectance0: vec3f, // full reflectance color (normal incidence angle)\n reflectance90: vec3f, // reflectance color at grazing angle\n alphaRoughness: f32, // roughness mapped to a more linear change in the roughness (proposed by [2])\n diffuseColor: vec3f, // color contribution from diffuse lighting\n specularColor: vec3f, // color contribution from specular lighting\n n: vec3f, // normal at surface point\n v: vec3f, // vector from surface point to camera\n};\n\nconst M_PI = 3.141592653589793;\nconst c_MinRoughness = 0.04;\n\nfn SRGBtoLINEAR(srgbIn: vec4f ) -> vec4f\n{\n#ifdef MANUAL_SRGB\n#ifdef SRGB_FAST_APPROXIMATION\n var linOut: vec3f = pow(srgbIn.xyz,vec3(2.2));\n#else // SRGB_FAST_APPROXIMATION\n var bLess: vec3f = step(vec3(0.04045),srgbIn.xyz);\n var linOut: vec3f = mix( srgbIn.xyz/vec3(12.92), pow((srgbIn.xyz+vec3(0.055))/vec3(1.055),vec3(2.4)), bLess );\n#endif //SRGB_FAST_APPROXIMATION\n return vec4f(linOut,srgbIn.w);;\n#else //MANUAL_SRGB\n return srgbIn;\n#endif //MANUAL_SRGB\n}\n\n// Find the normal for this fragment, pulling either from a predefined normal map\n// or from the interpolated mesh normal and tangent attributes.\nfn getNormal() -> vec3f\n{\n // Retrieve the tangent space matrix\n#ifndef HAS_TANGENTS\n var pos_dx: vec3f = dFdx(pbr_vPosition);\n var pos_dy: vec3f = dFdy(pbr_vPosition);\n var tex_dx: vec3f = dFdx(vec3(pbr_vUV, 0.0));\n var tex_dy: vec3f = dFdy(vec3(pbr_vUV, 0.0));\n var t: vec3f = (tex_dy.t * pos_dx - tex_dx.t * pos_dy) / (tex_dx.s * tex_dy.t - tex_dy.s * tex_dx.t);\n\n#ifdef HAS_NORMALS\n var ng: vec3f = normalize(pbr_vNormal);\n#else\n var ng: vec3f = cross(pos_dx, pos_dy);\n#endif\n\n t = normalize(t - ng * dot(ng, t));\n var b: vec3f = normalize(cross(ng, t));\n var tbn: mat3f = mat3f(t, b, ng);\n#else // HAS_TANGENTS\n var tbn: mat3f = pbr_vTBN;\n#endif\n\n#ifdef HAS_NORMALMAP\n vec3 n = texture(pbr_normalSampler, pbr_vUV).rgb;\n n = normalize(tbn * ((2.0 * n - 1.0) * vec3(pbrMaterial.normalScale, pbrMaterial.normalScale, 1.0)));\n#else\n // The tbn matrix is linearly interpolated, so we need to re-normalize\n vec3 n = normalize(tbn[2].xyz);\n#endif\n\n return n;\n}\n\n// Calculation of the lighting contribution from an optional Image Based Light source.\n// Precomputed Environment Maps are required uniform inputs and are computed as outlined in [1].\n// See our README.md on Environment Maps [3] for additional discussion.\n#ifdef USE_IBL\nfn getIBLContribution(PBRInfo pbrInfo, vec3 n, vec3 reflection) -> vec3f\n{\n float mipCount = 9.0; // resolution of 512x512\n float lod = (pbrInfo.perceptualRoughness * mipCount);\n // retrieve a scale and bias to F0. See [1], Figure 3\n vec3 brdf = SRGBtoLINEAR(texture(pbr_brdfLUT,\n vec2(pbrInfo.NdotV, 1.0 - pbrInfo.perceptualRoughness))).rgb;\n vec3 diffuseLight = SRGBtoLINEAR(texture(pbr_diffuseEnvSampler, n)).rgb;\n\n#ifdef USE_TEX_LOD\n vec3 specularLight = SRGBtoLINEAR(texture(pbr_specularEnvSampler, reflection, lod)).rgb;\n#else\n vec3 specularLight = SRGBtoLINEAR(texture(pbr_specularEnvSampler, reflection)).rgb;\n#endif\n\n vec3 diffuse = diffuseLight * pbrInfo.diffuseColor;\n vec3 specular = specularLight * (pbrInfo.specularColor * brdf.x + brdf.y);\n\n // For presentation, this allows us to disable IBL terms\n diffuse *= pbrMaterial.scaleIBLAmbient.x;\n specular *= pbrMaterial.scaleIBLAmbient.y;\n\n return diffuse + specular;\n}\n#endif\n\n// Basic Lambertian diffuse\n// Implementation from Lambert's Photometria https://archive.org/details/lambertsphotome00lambgoog\n// See also [1], Equation 1\nfn diffuse(pbrInfo: PBRInfo) -> vec3<f32> {\n return pbrInfo.diffuseColor / PI;\n}\n\n// The following equation models the Fresnel reflectance term of the spec equation (aka F())\n// Implementation of fresnel from [4], Equation 15\nfn specularReflection(pbrInfo: PBRInfo) -> vec3<f32> {\n return pbrInfo.reflectance0 +\n (pbrInfo.reflectance90 - pbrInfo.reflectance0) *\n pow(clamp(1.0 - pbrInfo.VdotH, 0.0, 1.0), 5.0);\n}\n\n// This calculates the specular geometric attenuation (aka G()),\n// where rougher material will reflect less light back to the viewer.\n// This implementation is based on [1] Equation 4, and we adopt their modifications to\n// alphaRoughness as input as originally proposed in [2].\nfn geometricOcclusion(pbrInfo: PBRInfo) -> f32 {\n let NdotL: f32 = pbrInfo.NdotL;\n let NdotV: f32 = pbrInfo.NdotV;\n let r: f32 = pbrInfo.alphaRoughness;\n\n let attenuationL = 2.0 * NdotL / (NdotL + sqrt(r * r + (1.0 - r * r) * (NdotL * NdotL)));\n let attenuationV = 2.0 * NdotV / (NdotV + sqrt(r * r + (1.0 - r * r) * (NdotV * NdotV)));\n return attenuationL * attenuationV;\n}\n\n// The following equation(s) model the distribution of microfacet normals across\n// the area being drawn (aka D())\n// Implementation from \"Average Irregularity Representation of a Roughened Surface\n// for Ray Reflection\" by T. S. Trowbridge, and K. P. Reitz\n// Follows the distribution function recommended in the SIGGRAPH 2013 course notes\n// from EPIC Games [1], Equation 3.\nfn microfacetDistribution(pbrInfo: PBRInfo) -> f32 {\n let roughnessSq = pbrInfo.alphaRoughness * pbrInfo.alphaRoughness;\n let f = (pbrInfo.NdotH * roughnessSq - pbrInfo.NdotH) * pbrInfo.NdotH + 1.0;\n return roughnessSq / (PI * f * f);\n}\n\nfn PBRInfo_setAmbientLight(pbrInfo: ptr<function, PBRInfo>) {\n (*pbrInfo).NdotL = 1.0;\n (*pbrInfo).NdotH = 0.0;\n (*pbrInfo).LdotH = 0.0;\n (*pbrInfo).VdotH = 1.0;\n}\n\nfn PBRInfo_setDirectionalLight(pbrInfo: ptr<function, PBRInfo>, lightDirection: vec3<f32>) {\n let n = (*pbrInfo).n;\n let v = (*pbrInfo).v;\n let l = normalize(lightDirection); // Vector from surface point to light\n let h = normalize(l + v); // Half vector between both l and v\n\n (*pbrInfo).NdotL = clamp(dot(n, l), 0.001, 1.0);\n (*pbrInfo).NdotH = clamp(dot(n, h), 0.0, 1.0);\n (*pbrInfo).LdotH = clamp(dot(l, h), 0.0, 1.0);\n (*pbrInfo).VdotH = clamp(dot(v, h), 0.0, 1.0);\n}\n\nfn PBRInfo_setPointLight(pbrInfo: ptr<function, PBRInfo>, pointLight: PointLight) {\n let light_direction = normalize(pointLight.position - pbr_vPosition);\n PBRInfo_setDirectionalLight(pbrInfo, light_direction);\n}\n\nfn calculateFinalColor(pbrInfo: PBRInfo, lightColor: vec3<f32>) -> vec3<f32> {\n // Calculate the shading terms for the microfacet specular shading model\n let F = specularReflection(pbrInfo);\n let G = geometricOcclusion(pbrInfo);\n let D = microfacetDistribution(pbrInfo);\n\n // Calculation of analytical lighting contribution\n let diffuseContrib = (1.0 - F) * diffuse(pbrInfo);\n let specContrib = F * G * D / (4.0 * pbrInfo.NdotL * pbrInfo.NdotV);\n // Obtain final intensity as reflectance (BRDF) scaled by the energy of the light (cosine law)\n return pbrInfo.NdotL * lightColor * (diffuseContrib + specContrib);\n}\n\nfn pbr_filterColor(colorUnused: vec4<f32>) -> vec4<f32> {\n // The albedo may be defined from a base texture or a flat color\n var baseColor: vec4<f32>;\n #ifdef HAS_BASECOLORMAP\n baseColor = SRGBtoLINEAR(textureSample(pbr_baseColorSampler, pbr_baseColorSampler, pbr_vUV)) * pbrMaterial.baseColorFactor;\n #else\n baseColor = pbrMaterial.baseColorFactor;\n #endif\n\n #ifdef ALPHA_CUTOFF\n if (baseColor.a < pbrMaterial.alphaCutoff) {\n discard;\n }\n #endif\n\n var color = vec3<f32>(0.0, 0.0, 0.0);\n\n if (pbrMaterial.unlit) {\n color = baseColor.rgb;\n } else {\n // Metallic and Roughness material properties are packed together\n // In glTF, these factors can be specified by fixed scalar values\n // or from a metallic-roughness map\n var perceptualRoughness = pbrMaterial.metallicRoughnessValues.y;\n var metallic = pbrMaterial.metallicRoughnessValues.x;\n #ifdef HAS_METALROUGHNESSMAP\n // Roughness is stored in the 'g' channel, metallic is stored in the 'b' channel.\n // This layout intentionally reserves the 'r' channel for (optional) occlusion map data\n let mrSample = textureSample(pbr_metallicRoughnessSampler, pbr_metallicRoughnessSampler, pbr_vUV);\n perceptualRoughness = mrSample.g * perceptualRoughness;\n metallic = mrSample.b * metallic;\n #endif\n perceptualRoughness = clamp(perceptualRoughness, c_MinRoughness, 1.0);\n metallic = clamp(metallic, 0.0, 1.0);\n // Roughness is authored as perceptual roughness; as is convention,\n // convert to material roughness by squaring the perceptual roughness [2].\n let alphaRoughness = perceptualRoughness * perceptualRoughness;\n\n let f0 = vec3<f32>(0.04);\n var diffuseColor = baseColor.rgb * (vec3<f32>(1.0) - f0);\n diffuseColor *= 1.0 - metallic;\n let specularColor = mix(f0, baseColor.rgb, metallic);\n\n // Compute reflectance.\n let reflectance = max(max(specularColor.r, specularColor.g), specularColor.b);\n\n // For typical incident reflectance range (between 4% to 100%) set the grazing\n // reflectance to 100% for typical fresnel effect.\n // For very low reflectance range on highly diffuse objects (below 4%),\n // incrementally reduce grazing reflectance to 0%.\n let reflectance90 = clamp(reflectance * 25.0, 0.0, 1.0);\n let specularEnvironmentR0 = specularColor;\n let specularEnvironmentR90 = vec3<f32>(1.0, 1.0, 1.0) * reflectance90;\n\n let n = getNormal(); // normal at surface point\n let v = normalize(pbrProjection.camera - pbr_vPosition); // Vector from surface point to camera\n\n let NdotV = clamp(abs(dot(n, v)), 0.001, 1.0);\n let reflection = -normalize(reflect(v, n));\n\n var pbrInfo = PBRInfo(\n 0.0, // NdotL\n NdotV,\n 0.0, // NdotH\n 0.0, // LdotH\n 0.0, // VdotH\n perceptualRoughness,\n metallic,\n specularEnvironmentR0,\n specularEnvironmentR90,\n alphaRoughness,\n diffuseColor,\n specularColor,\n n,\n v\n );\n\n #ifdef USE_LIGHTS\n // Apply ambient light\n PBRInfo_setAmbientLight(&pbrInfo);\n color += calculateFinalColor(pbrInfo, lighting.ambientColor);\n\n // Apply directional light\n for (var i = 0; i < lighting.directionalLightCount; i++) {\n if (i < lighting.directionalLightCount) {\n PBRInfo_setDirectionalLight(&pbrInfo, lighting_getDirectionalLight(i).direction);\n color += calculateFinalColor(pbrInfo, lighting_getDirectionalLight(i).color);\n }\n }\n\n // Apply point light\n for (var i = 0; i < lighting.pointLightCount; i++) {\n if (i < lighting.pointLightCount) {\n PBRInfo_setPointLight(&pbrInfo, lighting_getPointLight(i));\n let attenuation = getPointLightAttenuation(lighting_getPointLight(i), distance(lighting_getPointLight(i).position, pbr_vPosition));\n color += calculateFinalColor(pbrInfo, lighting_getPointLight(i).color / attenuation);\n }\n }\n #endif\n\n // Calculate lighting contribution from image based lighting source (IBL)\n #ifdef USE_IBL\n if (pbrMaterial.IBLenabled) {\n color += getIBLContribution(pbrInfo, n, reflection);\n }\n #endif\n\n // Apply optional PBR terms for additional (optional) shading\n #ifdef HAS_OCCLUSIONMAP\n if (pbrMaterial.occlusionMapEnabled) {\n let ao = textureSample(pbr_occlusionSampler, pbr_occlusionSampler, pbr_vUV).r;\n color = mix(color, color * ao, pbrMaterial.occlusionStrength);\n }\n #endif\n\n #ifdef HAS_EMISSIVEMAP\n if (pbrMaterial.emissiveMapEnabled) {\n let emissive = SRGBtoLINEAR(textureSample(pbr_emissiveSampler, pbr_emissiveSampler, pbr_vUV)).rgb * pbrMaterial.emissiveFactor;\n color += emissive;\n }\n #endif\n\n // This section uses mix to override final color for reference app visualization\n // of various parameters in the lighting equation.\n #ifdef PBR_DEBUG\n // TODO: Figure out how to debug multiple lights\n\n // color = mix(color, F, pbr_scaleFGDSpec.x);\n // color = mix(color, vec3(G), pbr_scaleFGDSpec.y);\n // color = mix(color, vec3(D), pbr_scaleFGDSpec.z);\n // color = mix(color, specContrib, pbr_scaleFGDSpec.w);\n\n // color = mix(color, diffuseContrib, pbr_scaleDiffBaseMR.x);\n color = mix(color, baseColor.rgb, pbrMaterial.scaleDiffBaseMR.y);\n color = mix(color, vec3<f32>(metallic), pbrMaterial.scaleDiffBaseMR.z);\n color = mix(color, vec3<f32>(perceptualRoughness), pbrMaterial.scaleDiffBaseMR.w);\n #endif\n }\n\n return vec4<f32>(pow(color, vec3<f32>(1.0 / 2.2)), baseColor.a);\n}\n",vs:"out vec3 pbr_vPosition;\nout vec2 pbr_vUV;\n\n#ifdef HAS_NORMALS\n# ifdef HAS_TANGENTS\nout mat3 pbr_vTBN;\n# else\nout vec3 pbr_vNormal;\n# endif\n#endif\n\nvoid pbr_setPositionNormalTangentUV(vec4 position, vec4 normal, vec4 tangent, vec2 uv)\n{\n vec4 pos = pbrProjection.modelMatrix * position;\n pbr_vPosition = vec3(pos.xyz) / pos.w;\n\n#ifdef HAS_NORMALS\n#ifdef HAS_TANGENTS\n vec3 normalW = normalize(vec3(pbrProjection.normalMatrix * vec4(normal.xyz, 0.0)));\n vec3 tangentW = normalize(vec3(pbrProjection.modelMatrix * vec4(tangent.xyz, 0.0)));\n vec3 bitangentW = cross(normalW, tangentW) * tangent.w;\n pbr_vTBN = mat3(tangentW, bitangentW, normalW);\n#else // HAS_TANGENTS != 1\n pbr_vNormal = normalize(vec3(pbrProjection.modelMatrix * vec4(normal.xyz, 0.0)));\n#endif\n#endif\n\n#ifdef HAS_UV\n pbr_vUV = uv;\n#else\n pbr_vUV = vec2(0.,0.);\n#endif\n}\n",fs:"precision highp float;\n\nuniform pbrMaterialUniforms {\n // Material is unlit\n bool unlit;\n\n // Base color map\n bool baseColorMapEnabled;\n vec4 baseColorFactor;\n\n bool normalMapEnabled; \n float normalScale; // #ifdef HAS_NORMALMAP\n\n bool emissiveMapEnabled;\n vec3 emissiveFactor; // #ifdef HAS_EMISSIVEMAP\n\n vec2 metallicRoughnessValues;\n bool metallicRoughnessMapEnabled;\n\n bool occlusionMapEnabled;\n float occlusionStrength; // #ifdef HAS_OCCLUSIONMAP\n \n bool alphaCutoffEnabled;\n float alphaCutoff; // #ifdef ALPHA_CUTOFF\n \n // IBL\n bool IBLenabled;\n vec2 scaleIBLAmbient; // #ifdef USE_IBL\n \n // debugging flags used for shader output of intermediate PBR variables\n // #ifdef PBR_DEBUG\n vec4 scaleDiffBaseMR;\n vec4 scaleFGDSpec;\n // #endif\n} pbrMaterial;\n\n// Samplers\n#ifdef HAS_BASECOLORMAP\nuniform sampler2D pbr_baseColorSampler;\n#endif\n#ifdef HAS_NORMALMAP\nuniform sampler2D pbr_normalSampler;\n#endif\n#ifdef HAS_EMISSIVEMAP\nuniform sampler2D pbr_emissiveSampler;\n#endif\n#ifdef HAS_METALROUGHNESSMAP\nuniform sampler2D pbr_metallicRoughnessSampler;\n#endif\n#ifdef HAS_OCCLUSIONMAP\nuniform sampler2D pbr_occlusionSampler;\n#endif\n#ifdef USE_IBL\nuniform samplerCube pbr_diffuseEnvSampler;\nuniform samplerCube pbr_specularEnvSampler;\nuniform sampler2D pbr_brdfLUT;\n#endif\n\n// Inputs from vertex shader\n\nin vec3 pbr_vPosition;\nin vec2 pbr_vUV;\n\n#ifdef HAS_NORMALS\n#ifdef HAS_TANGENTS\nin mat3 pbr_vTBN;\n#else\nin vec3 pbr_vNormal;\n#endif\n#endif\n\n// Encapsulate the various inputs used by the various functions in the shading equation\n// We store values in this struct to simplify the integration of alternative implementations\n// of the shading terms, outlined in the Readme.MD Appendix.\nstruct PBRInfo {\n float NdotL; // cos angle between normal and light direction\n float NdotV; // cos angle between normal and view direction\n float NdotH; // cos angle between normal and half vector\n float LdotH; // cos angle between light direction and half vector\n float VdotH; // cos angle between view direction and half vector\n float perceptualRoughness; // roughness value, as authored by the model creator (input to shader)\n float metalness; // metallic value at the surface\n vec3 reflectance0; // full reflectance color (normal incidence angle)\n vec3 reflectance90; // reflectance color at grazing angle\n float alphaRoughness; // roughness mapped to a more linear change in the roughness (proposed by [2])\n vec3 diffuseColor; // color contribution from diffuse lighting\n vec3 specularColor; // color contribution from specular lighting\n vec3 n; // normal at surface point\n vec3 v; // vector from surface point to camera\n};\n\nconst float M_PI = 3.141592653589793;\nconst float c_MinRoughness = 0.04;\n\nvec4 SRGBtoLINEAR(vec4 srgbIn)\n{\n#ifdef MANUAL_SRGB\n#ifdef SRGB_FAST_APPROXIMATION\n vec3 linOut = pow(srgbIn.xyz,vec3(2.2));\n#else // SRGB_FAST_APPROXIMATION\n vec3 bLess = step(vec3(0.04045),srgbIn.xyz);\n vec3 linOut = mix( srgbIn.xyz/vec3(12.92), pow((srgbIn.xyz+vec3(0.055))/vec3(1.055),vec3(2.4)), bLess );\n#endif //SRGB_FAST_APPROXIMATION\n return vec4(linOut,srgbIn.w);;\n#else //MANUAL_SRGB\n return srgbIn;\n#endif //MANUAL_SRGB\n}\n\n// Find the normal for this fragment, pulling either from a predefined normal map\n// or from the interpolated mesh normal and tangent attributes.\nvec3 getNormal()\n{\n // Retrieve the tangent space matrix\n#ifndef HAS_TANGENTS\n vec3 pos_dx = dFdx(pbr_vPosition);\n vec3 pos_dy = dFdy(pbr_vPosition);\n vec3 tex_dx = dFdx(vec3(pbr_vUV, 0.0));\n vec3 tex_dy = dFdy(vec3(pbr_vUV, 0.0));\n vec3 t = (tex_dy.t * pos_dx - tex_dx.t * pos_dy) / (tex_dx.s * tex_dy.t - tex_dy.s * tex_dx.t);\n\n#ifdef HAS_NORMALS\n vec3 ng = normalize(pbr_vNormal);\n#else\n vec3 ng = cross(pos_dx, pos_dy);\n#endif\n\n t = normalize(t - ng * dot(ng, t));\n vec3 b = normalize(cross(ng, t));\n mat3 tbn = mat3(t, b, ng);\n#else // HAS_TANGENTS\n mat3 tbn = pbr_vTBN;\n#endif\n\n#ifdef HAS_NORMALMAP\n vec3 n = texture(pbr_normalSampler, pbr_vUV).rgb;\n n = normalize(tbn * ((2.0 * n - 1.0) * vec3(pbrMaterial.normalScale, pbrMaterial.normalScale, 1.0)));\n#else\n // The tbn matrix is linearly interpolated, so we need to re-normalize\n vec3 n = normalize(tbn[2].xyz);\n#endif\n\n return n;\n}\n\n// Calculation of the lighting contribution from an optional Image Based Light source.\n// Precomputed Environment Maps are required uniform inputs and are computed as outlined in [1].\n// See our README.md on Environment Maps [3] for additional discussion.\n#ifdef USE_IBL\nvec3 getIBLContribution(PBRInfo pbrInfo, vec3 n, vec3 reflection)\n{\n float mipCount = 9.0; // resolution of 512x512\n float lod = (pbrInfo.perceptualRoughness * mipCount);\n // retrieve a scale and bias to F0. See [1], Figure 3\n vec3 brdf = SRGBtoLINEAR(texture(pbr_brdfLUT,\n vec2(pbrInfo.NdotV, 1.0 - pbrInfo.perceptualRoughness))).rgb;\n vec3 diffuseLight = SRGBtoLINEAR(texture(pbr_diffuseEnvSampler, n)).rgb;\n\n#ifdef USE_TEX_LOD\n vec3 specularLight = SRGBtoLINEAR(texture(pbr_specularEnvSampler, reflection, lod)).rgb;\n#else\n vec3 specularLight = SRGBtoLINEAR(texture(pbr_specularEnvSampler, reflection)).rgb;\n#endif\n\n vec3 diffuse = diffuseLight * pbrInfo.diffuseColor;\n vec3 specular = specularLight * (pbrInfo.specularColor * brdf.x + brdf.y);\n\n // For presentation, this allows us to disable IBL terms\n diffuse *= pbrMaterial.scaleIBLAmbient.x;\n specular *= pbrMaterial.scaleIBLAmbient.y;\n\n return diffuse + specular;\n}\n#endif\n\n// Basic Lambertian diffuse\n// Implementation from Lambert's Photometria https://archive.org/details/lambertsphotome00lambgoog\n// See also [1], Equation 1\nvec3 diffuse(PBRInfo pbrInfo)\n{\n return pbrInfo.diffuseColor / M_PI;\n}\n\n// The following equation models the Fresnel reflectance term of the spec equation (aka F())\n// Implementation of fresnel from [4], Equation 15\nvec3 specularReflection(PBRInfo pbrInfo)\n{\n return pbrInfo.reflectance0 +\n (pbrInfo.reflectance90 - pbrInfo.reflectance0) *\n pow(clamp(1.0 - pbrInfo.VdotH, 0.0, 1.0), 5.0);\n}\n\n// This calculates the specular geometric attenuation (aka G()),\n// where rougher material will reflect less light back to the viewer.\n// This implementation is based on [1] Equation 4, and we adopt their modifications to\n// alphaRoughness as input as originally proposed in [2].\nfloat geometricOcclusion(PBRInfo pbrInfo)\n{\n float NdotL = pbrInfo.NdotL;\n float NdotV = pbrInfo.NdotV;\n float r = pbrInfo.alphaRoughness;\n\n float attenuationL = 2.0 * NdotL / (NdotL + sqrt(r * r + (1.0 - r * r) * (NdotL * NdotL)));\n float attenuationV = 2.0 * NdotV / (NdotV + sqrt(r * r + (1.0 - r * r) * (NdotV * NdotV)));\n return attenuationL * attenuationV;\n}\n\n// The following equation(s) model the distribution of microfacet normals across\n// the area being drawn (aka D())\n// Implementation from \"Average Irregularity Representation of a Roughened Surface\n// for Ray Reflection\" by T. S. Trowbridge, and K. P. Reitz\n// Follows the distribution function recommended in the SIGGRAPH 2013 course notes\n// from EPIC Games [1], Equation 3.\nfloat microfacetDistribution(PBRInfo pbrInfo)\n{\n float roughnessSq = pbrInfo.alphaRoughness * pbrInfo.alphaRoughness;\n float f = (pbrInfo.NdotH * roughnessSq - pbrInfo.NdotH) * pbrInfo.NdotH + 1.0;\n return roughnessSq / (M_PI * f * f);\n}\n\nvoid PBRInfo_setAmbientLight(inout PBRInfo pbrInfo) {\n pbrInfo.NdotL = 1.0;\n pbrInfo.NdotH = 0.0;\n pbrInfo.LdotH = 0.0;\n pbrInfo.VdotH = 1.0;\n}\n\nvoid PBRInfo_setDirectionalLight(inout PBRInfo pbrInfo, vec3 lightDirection) {\n vec3 n = pbrInfo.n;\n vec3 v = pbrInfo.v;\n vec3 l = normalize(lightDirection); // Vector from surface point to light\n vec3 h = normalize(l+v); // Half vector between both l and v\n\n pbrInfo.NdotL = clamp(dot(n, l), 0.001, 1.0);\n pbrInfo.NdotH = clamp(dot(n, h), 0.0, 1.0);\n pbrInfo.LdotH = clamp(dot(l, h), 0.0, 1.0);\n pbrInfo.VdotH = clamp(dot(v, h), 0.0, 1.0);\n}\n\nvoid PBRInfo_setPointLight(inout PBRInfo pbrInfo, PointLight pointLight) {\n vec3 light_direction = normalize(pointLight.position - pbr_vPosition);\n PBRInfo_setDirectionalLight(pbrInfo, light_direction);\n}\n\nvec3 calculateFinalColor(PBRInfo pbrInfo, vec3 lightColor) {\n // Calculate the shading terms for the microfacet specular shading model\n vec3 F = specularReflection(pbrInfo);\n float G = geometricOcclusion(pbrInfo);\n float D = microfacetDistribution(pbrInfo);\n\n // Calculation of analytical lighting contribution\n vec3 diffuseContrib = (1.0 - F) * diffuse(pbrInfo);\n vec3 specContrib = F * G * D / (4.0 * pbrInfo.NdotL * pbrInfo.NdotV);\n // Obtain final intensity as reflectance (BRDF) scaled by the energy of the light (cosine law)\n return pbrInfo.NdotL * lightColor * (diffuseContrib + specContrib);\n}\n\nvec4 pbr_filterColor(vec4 colorUnused)\n{\n // The albedo may be defined from a base texture or a flat color\n#ifdef HAS_BASECOLORMAP\n vec4 baseColor = SRGBtoLINEAR(texture(pbr_baseColorSampler, pbr_vUV)) * pbrMaterial.baseColorFactor;\n#else\n vec4 baseColor = pbrMaterial.baseColorFactor;\n#endif\n\n#ifdef ALPHA_CUTOFF\n if (baseColor.a < pbrMaterial.alphaCutoff) {\n discard;\n }\n#endif\n\n vec3 color = vec3(0, 0, 0);\n\n if(pbrMaterial.unlit){\n color.rgb = baseColor.rgb;\n }\n else{\n // Metallic and Roughness material properties are packed together\n // In glTF, these factors can be specified by fixed scalar values\n // or from a metallic-roughness map\n float perceptualRoughness = pbrMaterial.metallicRoughnessValues.y;\n float metallic = pbrMaterial.metallicRoughnessValues.x;\n#ifdef HAS_METALROUGHNESSMAP\n // Roughness is stored in the 'g' channel, metallic is stored in the 'b' channel.\n // This layout intentionally reserves the 'r' channel for (optional) occlusion map data\n vec4 mrSample = texture(pbr_metallicRoughnessSampler, pbr_vUV);\n perceptualRoughness = mrSample.g * perceptualRoughness;\n metallic = mrSample.b * metallic;\n#endif\n perceptualRoughness = clamp(perceptualRoughness, c_MinRoughness, 1.0);\n metallic = clamp(metallic, 0.0, 1.0);\n // Roughness is authored as perceptual roughness; as is convention,\n // convert to material roughness by squaring the perceptual roughness [2].\n float alphaRoughness = perceptualRoughness * perceptualRoughness;\n\n vec3 f0 = vec3(0.04);\n vec3 diffuseColor = baseColor.rgb * (vec3(1.0) - f0);\n diffuseColor *= 1.0 - metallic;\n vec3 specularColor = mix(f0, baseColor.rgb, metallic);\n\n // Compute reflectance.\n float reflectance = max(max(specularColor.r, specularColor.g), specularColor.b);\n\n // For typical incident reflectance range (between 4% to 100%) set the grazing\n // reflectance to 100% for typical fresnel effect.\n // For very low reflectance range on highly diffuse objects (below 4%),\n // incrementally reduce grazing reflecance to 0%.\n float reflectance90 = clamp(reflectance * 25.0, 0.0, 1.0);\n vec3 specularEnvironmentR0 = specularColor.rgb;\n vec3 specularEnvironmentR90 = vec3(1.0, 1.0, 1.0) * reflectance90;\n\n vec3 n = getNormal(); // normal at surface point\n vec3 v = normalize(pbrProjection.camera - pbr_vPosition); // Vector from surface point to camera\n\n float NdotV = clamp(abs(dot(n, v)), 0.001, 1.0);\n vec3 reflection = -normalize(reflect(v, n));\n\n PBRInfo pbrInfo = PBRInfo(\n 0.0, // NdotL\n NdotV,\n 0.0, // NdotH\n 0.0, // LdotH\n 0.0, // VdotH\n perceptualRoughness,\n metallic,\n specularEnvironmentR0,\n specularEnvironmentR90,\n alphaRoughness,\n diffuseColor,\n specularColor,\n n,\n v\n );\n\n\n#ifdef USE_LIGHTS\n // Apply ambient light\n PBRInfo_setAmbientLight(pbrInfo);\n color += calculateFinalColor(pbrInfo, lighting.ambientColor);\n\n // Apply directional light\n for(int i = 0; i < lighting.directionalLightCount; i++) {\n if (i < lighting.directionalLightCount) {\n PBRInfo_setDirectionalLight(pbrInfo, lighting_getDirectionalLight(i).direction);\n color += calculateFinalColor(pbrInfo, lighting_getDirectionalLight(i).color);\n }\n }\n\n // Apply point light\n for(int i = 0; i < lighting.pointLightCount; i++) {\n if (i < lighting.pointLightCount) {\n PBRInfo_setPointLight(pbrInfo, lighting_getPointLight(i));\n float attenuation = getPointLightAttenuation(lighting_getPointLight(i), distance(lighting_getPointLight(i).position, pbr_vPosition));\n color += calculateFinalColor(pbrInfo, lighting_getPointLight(i).color / attenuation);\n }\n }\n#endif\n\n // Calculate lighting contribution from image based lighting source (IBL)\n#ifdef USE_IBL\n if (pbrMaterial.IBLenabled) {\n color += getIBLContribution(pbrInfo, n, reflection);\n }\n#endif\n\n // Apply optional PBR terms for additional (optional) shading\n#ifdef HAS_OCCLUSIONMAP\n if (pbrMaterial.occlusionMapEnabled) {\n float ao = texture(pbr_occlusionSampler, pbr_vUV).r;\n color = mix(color, color * ao, pbrMaterial.occlusionStrength);\n }\n#endif\n\n#ifdef HAS_EMISSIVEMAP\n if (pbrMaterial.emissiveMapEnabled) {\n vec3 emissive = SRGBtoLINEAR(texture(pbr_emissiveSampler, pbr_vUV)).rgb * pbrMaterial.emissiveFactor;\n color += emissive;\n }\n#endif\n\n // This section uses mix to override final color for reference app visualization\n // of various parameters in the lighting equation.\n#ifdef PBR_DEBUG\n // TODO: Figure out how to debug multiple lights\n\n // color = mix(color, F, pbr_scaleFGDSpec.x);\n // color = mix(color, vec3(G), pbr_scaleFGDSpec.y);\n // color = mix(color, vec3(D), pbr_scaleFGDSpec.z);\n // color = mix(color, specContrib, pbr_scaleFGDSpec.w);\n\n // color = mix(color, diffuseContrib, pbr_scaleDiffBaseMR.x);\n color = mix(color, baseColor.rgb, pbrMaterial.scaleDiffBaseMR.y);\n color = mix(color, vec3(metallic), pbrMaterial.scaleDiffBaseMR.z);\n color = mix(color, vec3(perceptualRoughness), pbrMaterial.scaleDiffBaseMR.w);\n#endif\n\n }\n\n return vec4(pow(color,vec3(1.0/2.2)), baseColor.a);\n}\n",defines:{LIGHTING_FRAGMENT:!0,HAS_NORMALMAP:!1,HAS_EMISSIVEMAP:!1,HAS_OCCLUSIONMAP:!1,HAS_BASECOLORMAP:!1,HAS_METALROUGHNESSMAP:!1,ALPHA_CUTOFF:!1,USE_IBL:!1,PBR_DEBUG:!1},getUniforms:n=>n,uniformTypes:{unlit:"i32",baseColorMapEnabled:"i32",baseColorFactor:"vec4<f32>",normalMapEnabled:"i32",normalScale:"f32",emissiveMapEnabled:"i32",emissiveFactor:"vec3<f32>",metallicRoughnessValues:"vec2<f32>",metallicRoughnessMapEnabled:"i32",occlusionMapEnabled:"i32",occlusionStrength:"f32",alphaCutoffEnabled:"i32",alphaCutoff:"f32",IBLenabled:"i32",scaleIBLAmbient:"vec2<f32>",scaleDiffBaseMR:"vec4<f32>",scaleFGDSpec:"vec4<f32>"}};class v{id;matrix=new o;display=!0;position=new r;rotation=new r;scale=new r(1,1,1);userData={};props={};constructor(n={}){const{id:e}=n;this.id=e||i(this.constructor.name),this._setScenegraphNodeProps(n)}getBounds(){return null}destroy(){}delete(){this.destroy()}setProps(n){return this._setScenegraphNodeProps(n),this}toString(){return`{type: ScenegraphNode, id: ${this.id})}`}setPosition(n){return this.position=n,this}setRotation(n){return this.rotation=n,this}setScale(n){return this.scale=n,this}setMatrix(n,e=!0){e?this.matrix.copy(n):this.matrix=n}setMatrixComponents(n){const{position:e,rotation:t,scale:o,update:r=!0}=n;return e&&this.setPosition(e),t&&this.setRotation(t),o&&this.setScale(o),r&&this.updateMatrix(),this}updateMatrix(){const n=this.position,e=this.rotation,t=this.scale;return this.matrix.identity(),this.matrix.translate(n),this.matrix.rotateXYZ(e),this.matrix.scale(t),this}update(n={}){const{position:e,rotation:t,scale:o}=n;return e&&this.setPosition(e),t&&this.setRotation(t),o&&this.setScale(o),this.updateMatrix(),this}getCoordinateUniforms(n,e){e=e||this.matrix;const t=new o(n).multiplyRight(e),r=t.invert(),i=r.transpose();return{viewMatrix:n,modelMatrix:e,objectMatrix:e,worldMatrix:t,worldInverseMatrix:r,worldInverseTransposeMatrix:i}}_setScenegraphNodeProps(n){"position"in n&&this.setPosition(n.position),"rotation"in n&&this.setRotation(n.rotation),"scale"in n&&this.setScale(n.scale),"matrix"in n&&this.setMatrix(n.matrix),Object.assign(this.props,n)}}class _ extends v{children;constructor(n={}){n=Array.isArray(n)?{children:n}:n;const{children:e=[]}=n;a.assert(e.every((n=>n instanceof v)),"every child must an instance of ScenegraphNode"),super(n),this.children=e}getBounds(){const n=[[1/0,1/0,1/0],[-1/0,-1/0,-1/0]];return this.traverse(((e,{worldMatrix:t})=>{const o=e.getBounds();if(!o)return;const[i,a]=o,s=new r(i).add(a).divide([2,2,2]);t.transformAsPoint(s,s);const l=new r(a).subtract(i).divide([2,2,2]);t.transformAsVector(l,l);for(let e=0;e<8;e++){const t=new r(1&e?-1:1,2&e?-1:1,4&e?-1:1).multiply(l).add(s);for(let e=0;e<3;e++)n[0][e]=Math.min(n[0][e],t[e]),n[1][e]=Math.max(n[1][e],t[e])}})),Number.isFinite(n[0][0])?n:null}destroy(){this.children.forEach((n=>n.destroy())),this.removeAll(),super.destroy()}add(...n){for(const e of n)Array.isArray(e)?this.add(...e):this.children.push(e);return this}remove(n){const e=this.children,t=e.indexOf(n);return t>-1&&e.splice(t,1),this}removeAll(){return this.children=[],this}traverse(n,{worldMatrix:e=new o}={}){const t=new o(e).multiplyRight(this.matrix);for(const e of this.children)e instanceof _?e.traverse(n,{worldMatrix:t}):n(e,{worldMatrix:t})}}class S extends v{model;bounds=null;managedResources;constructor(n){super(n),this.model=n.model,this.managedResources=n.managedResources||[],this.bounds=n.bounds||null,this.setProps(n)}destroy(){this.model&&(this.model.destroy(),this.model=null),this.managedResources.forEach((n=>n.destroy())),this.managedResources=[]}getBounds(){return this.bounds}draw(n){return this.model.draw(n)}}function I(n){return{addressModeU:A(n.wrapS),addressModeV:A(n.wrapT),magFilter:M(n.magFilter),...R(n.minFilter)}}function A(n){switch(n){case 33071:return"clamp-to-edge";case 10497:return"repeat";case 33648:return"mirror-repeat";default:return}}function M(n){switch(n){case 9728:return"nearest";case 9729:return"linear";default:return}}function R(n){switch(n){case 9728:return{minFilter:"nearest"};case 9729:return{minFilter:"linear"};case 9984:return{minFilter:"nearest",mipmapFilter:"nearest"};case 9985:return{minFilter:"linear",mipmapFilter:"nearest"};case 9986:return{minFilter:"nearest",mipmapFilter:"linear"};case 9987:return{minFilter:"linear",mipmapFilter:"linear"};default:return{}}}function L(n,e,t,o){const r={defines:{MANUAL_SRGB:!0,SRGB_FAST_APPROXIMATION:!0},bindings:{},uniforms:{camera:[0,0,0],metallicRoughnessValues:[1,1]},parameters:{},glParameters:{},generatedTextures:[]};r.defines.USE_TEX_LOD=!0;const{imageBasedLightingEnvironment:i}=o;return i&&(r.bindings.pbr_diffuseEnvSampler=i.diffuseEnvSampler.texture,r.bindings.pbr_specularEnvSampler=i.specularEnvSampler.texture,r.bindings.pbr_BrdfLUT=i.brdfLutTexture.texture,r.uniforms.scaleIBLAmbient=[1,1]),o?.pbrDebug&&(r.defines.PBR_DEBUG=!0,r.uniforms.scaleDiffBaseMR=[0,0,0,0],r.uniforms.scaleFGDSpec=[0,0,0,0]),t.NORMAL&&(r.defines.HAS_NORMALS=!0),t.TANGENT&&o?.useTangents&&(r.defines.HAS_TANGENTS=!0),t.TEXCOORD_0&&(r.defines.HAS_UV=!0),o?.imageBasedLightingEnvironment&&(r.defines.USE_IBL=!0),o?.lights&&(r.defines.USE_LIGHTS=!0),e&&function(n,e,t){if(t.uniforms.unlit=Boolean(e.unlit),e.pbrMetallicRoughness&&function(n,e,t){e.baseColorTexture&&N(n,e.baseColorTexture,"pbr_baseColorSampler","HAS_BASECOLORMAP",t),t.uniforms.baseColorFactor=e.baseColorFactor||[1,1,1,1],e.metallicRoughnessTexture&&N(n,e.metallicRoughnessTexture,"pbr_metallicRoughnessSampler","HAS_METALROUGHNESSMAP",t);const{metallicFactor:o=1,roughnessFactor:r=1}=e;t.uniforms.metallicRoughnessValues=[o,r]}(n,e.pbrMetallicRoughness,t),e.normalTexture){N(n,e.normalTexture,"pbr_normalSampler","HAS_NORMALMAP",t);const{scale:o=1}=e.normalTexture;t.uniforms.normalScale=o}if(e.occlusionTexture){N(n,e.occlusionTexture,"pbr_occlusionSampler","HAS_OCCLUSIONMAP",t);const{strength:o=1}=e.occlusionTexture;t.uniforms.occlusionStrength=o}switch(e.emissiveTexture&&(N(n,e.emissiveTexture,"pbr_emissiveSampler","HAS_EMISSIVEMAP",t),t.uniforms.emissiveFactor=e.emissiveFactor||[0,0,0]),e.alphaMode||"MASK"){case"MASK":const{alphaCutoff:n=.5}=e;t.defines.ALPHA_CUTOFF=!0,t.uniforms.alphaCutoff=n;break;case"BLEND":a.warn("glTF BLEND alphaMode might not work well because it requires mesh sorting")(),t.parameters.blend=!0,t.parameters.blendColorOperation="add",t.parameters.blendColorSrcFactor="src-alpha",t.parameters.blendColorDstFactor="one-minus-src-alpha",t.parameters.blendAlphaOperation="add",t.parameters.blendAlphaSrcFactor="one",t.parameters.blendAlphaDstFactor="one-minus-src-alpha",t.glParameters.blend=!0,t.glParameters.blendEquation=32774,t.glParameters.blendFunc=[770,771,1,771]}}(n,e,r),r}function N(n,e,t,o,r){const i=e.texture.source.image;let a;a=i.compressed?i:{data:i};const s={wrapS:10497,wrapT:10497,...e?.texture?.sampler},l=n.createTexture({id:e.uniformName||e.id,sampler:I(s),...a});r.bindings[t]=l,o&&(r.defines[o]=!0),r.generatedTextures.push(l)}var P;!function(n){n[n.POINTS=0]="POINTS",n[n.LINES=1]="LINES",n[n.LINE_LOOP=2]="LINE_LOOP",n[n.LINE_STRIP=3]="LINE_STRIP",n[n.TRIANGLES=4]="TRIANGLES",n[n.TRIANGLE_STRIP=5]="TRIANGLE_STRIP",n[n.TRIANGLE_FAN=6]="TRIANGLE_FAN"}(P||(P={}));const C={modelOptions:{},pbrDebug:!1,imageBasedLightingEnvironment:void 0,lights:!0,useTangents:!1};function x(n,e,t={}){const o={...C,...t},r=e.scenes.map((t=>function(n,e,t,o){const r=(e.nodes||[]).map((e=>E(n,e,t,o)));return new _({id:e.name||e.id,children:r})}(n,t,e.nodes,o)));return r}function E(n,e,t,r){if(!e._node){const i=(e.children||[]).map((e=>E(n,e,t,r)));e.mesh&&i.push(function(n,e,t){if(!e._mesh){const o=(e.primitives||[]).map(((o,r)=>function(n,e,t,o,r){const i=e.name||`${o.name||o.id}-primitive-${t}`,l=function(n){switch(n){case P.POINTS:return"point-list";case P.LINES:return"line-list";case P.LINE_STRIP:return"line-strip";case P.TRIANGLES:return"triangle-list";case P.TRIANGLE_STRIP:return"triangle-strip";default:throw new Error(String(n))}}(e.mode||4),c=e.indices?e.indices.count:function(){throw new Error("getVertexCount not implemented")}(),f=y(i,e,l),p=L(n,e.material,f.attributes,r),d=function(n,e){const{id:t,geometry:o,parsedPPBRMaterial:r,vertexCount:i,modelOptions:l={}}=e;a.info(4,"createGLTFModel defines: ",r.defines)();const c={id:t,source:"\nlayout(0) positions: vec4; // in vec4 POSITION;\n\n #ifdef HAS_NORMALS\n in vec4 normals; // in vec4 NORMAL;\n #endif\n\n #ifdef HAS_TANGENTS\n in vec4 TANGENT;\n #endif\n\n #ifdef HAS_UV\n // in vec2 TEXCOORD_0;\n in vec2 texCoords;\n #endif\n\n@vertex\n void main(void) {\n vec4 _NORMAL = vec4(0.);\n vec4 _TANGENT = vec4(0.);\n vec2 _TEXCOORD_0 = vec2(0.);\n\n #ifdef HAS_NORMALS\n _NORMAL = normals;\n #endif\n\n #ifdef HAS_TANGENTS\n _TANGENT = TANGENT;\n #endif\n\n #ifdef HAS_UV\n _TEXCOORD_0 = texCoords;\n #endif\n\n pbr_setPositionNormalTangentUV(positions, _NORMAL, _TANGENT, _TEXCOORD_0);\n gl_Position = u_MVPMatrix * positions;\n }\n\n@fragment\n out vec4 fragmentColor;\n\n void main(void) {\n vec3 pos = pbr_vPosition;\n fragmentColor = pbr_filterColor(vec4(1.0));\n }\n",vs:"#version 300 es\n\n // in vec4 POSITION;\n in vec4 positions;\n\n #ifdef HAS_NORMALS\n // in vec4 NORMAL;\n in vec4 normals;\n #endif\n\n #ifdef HAS_TANGENTS\n in vec4 TANGENT;\n #endif\n\n #ifdef HAS_UV\n // in vec2 TEXCOORD_0;\n in vec2 texCoords;\n #endif\n\n void main(void) {\n vec4 _NORMAL = vec4(0.);\n vec4 _TANGENT = vec4(0.);\n vec2 _TEXCOORD_0 = vec2(0.);\n\n #ifdef HAS_NORMALS\n _NORMAL = normals;\n #endif\n\n #ifdef HAS_TANGENTS\n _TANGENT = TANGENT;\n #endif\n\n #ifdef HAS_UV\n _TEXCOORD_0 = texCoords;\n #endif\n\n pbr_setPositionNormalTangentUV(positions, _NORMAL, _TANGENT, _TEXCOORD_0);\n gl_Position = pbrProjection.modelViewProjectionMatrix * positions;\n }\n",fs:"#version 300 es\n out vec4 fragmentColor;\n\n void main(void) {\n vec3 pos = pbr_vPosition;\n fragmentColor = pbr_filterColor(vec4(1.0));\n }\n",geometry:o,topology:o.topology,vertexCount:i,modules:[h],...l,defines:{...r.defines,...l.defines},parameters:{depthWriteEnabled:!0,depthCompare:"less",depthFormat:"depth24plus",cullMode:"back",...r.parameters,...l.parameters}},f=new s(n,c),{camera:p,...d}={...r.uniforms,...l.uniforms,...r.bindings,...l.bindings};return f.shaderInputs.setProps({pbrMaterial:d,pbrProjection:{camera:p}}),new S({managedResources:[],model:f})}(n,{id:i,geometry:y(i,e,l),parsedPPBRMaterial:p,modelOptions:r.modelOptions,vertexCount:c});return d.bounds=[e.attributes.POSITION.min,e.attributes.POSITION.max],d}(n,o,r,e,t))),r=new _({id:e.name||e.id,children:o});e._mesh=r}return e._mesh}(n,e.mesh,r));const l=new _({id:e.name||e.id,children:i});if(e.matrix)l.setMatrix(e.matrix);else{if(l.matrix.identity(),e.translation&&l.matrix.translate(e.translation),e.rotation){const n=(new o).fromQuaternion(e.rotation);l.matrix.multiplyRight(n)}e.scale&&l.matrix.scale(e.scale)}e._node=l}return t.find((n=>n.id===e.id))._node=e._node,e._node}function y(n,e,t){const o={};for(const[n,t]of Object.entries(e.attributes)){const{components:e,size:r,value:i}=t;o[n]={size:r??e,value:i}}return new l({id:n,topology:t,indices:e.indices.value,attributes:o})}const T=new c;class B{animation;startTime=0;playing=!0;speed=1;constructor(n){this.animation=n.animation,this.animation.name||="unnamed",Object.assign(this,n)}setTime(n){if(!this.playing)return;const e=(n/1e3-this.startTime)*this.speed;this.animation.channels.forEach((({sampler:n,target:t,path:o})=>{(function(n,{input:e,interpolation:t,output:o},r,i){const s=n%e[e.length-1],l=e.findIndex((n=>n>=s)),c=Math.max(0,l-1);if(!Array.isArray(r[i]))switch(i){case"translation":r[i]=[0,0,0];break;case"rotation":r[i]=[0,0,0,1];break;case"scale":r[i]=[1,1,1];break;default:a.warn(`Bad animation path ${i}`)()}const f=e[c],p=e[l];switch(t){case"STEP":!function(n,e,t){if(!n[e])throw new Error;for(let o=0;o<t.length;o++)n[e][o]=t[o]}(r,i,o[c]);break;case"LINEAR":p>f&&function(n,e,t,o,r){if(!n[e])throw new Error;if("rotation"===e){T.slerp({start:t,target:o,ratio:r});for(let t=0;t<T.length;t++)n[e][t]=T[t]}else for(let i=0;i<t.length;i++)n[e][i]=r*o[i]+(1-r)*t[i]}(r,i,o[c],o[l],(s-f)/(p-f));break;case"CUBICSPLINE":p>f&&function(n,e,{p0:t,outTangent0:o,inTangent1:r,p1:i,tDiff:a,ratio:s}){if(!n[e])throw new Error;for(let l=0;l<n[e].length;l++){const c=o[l]*a,f=r[l]*a;n[e][l]=(2*Math.pow(s,3)-3*Math.pow(s,2)+1)*t[l]+(Math.pow(s,3)-2*Math.pow(s,2)+s)*c+(-2*Math.pow(s,3)+3*Math.pow(s,2))*i[l]+(Math.pow(s,3)-Math.pow(s,2))*f}}(r,i,{p0:o[3*c+1],outTangent0:o[3*c+2],inTangent1:o[3*l+0],p1:o[3*l+1],tDiff:p-f,ratio:(s-f)/(p-f)});break;default:a.warn(`Interpolation ${t} not supported`)()}})(e,n,t,o),function(n,e){if(e.matrix.identity(),n.translation&&e.matrix.translate(n.translation),n.rotation){const t=H.fromQuaternion(n.rotation);e.matrix.multiplyRight(t)}n.scale&&e.matrix.scale(n.scale)}(t,t._node)}))}}class O{animations;constructor(n){this.animations=n.animations.map(((n,e)=>new B({animation:{name:n.name||`Animation-${e}`,channels:n.channels}})))}animate(n){a.warn("GLTFAnimator#animate is deprecated. Use GLTFAnimator#setTime instead")(),this.setTime(n)}setTime(n){this.animations.forEach((e=>e.setTime(n)))}getAnimations(){return this.animations}}const H=new o,w={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},G={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array};function F(n){if(!n._animation){const{typedArray:e,components:t}=function(n){const e=G[n.componentType],t=w[n.type],o=t*n.count,{buffer:r,byteOffset:i=0}=n.bufferView?.data??{};return{typedArray:new e(r,i+(n.byteOffset||0),o),components:t}}(n);if(1===t)n._animation=Array.from(e);else{const o=[];for(let n=0;n<e.length;n+=t)o.push(Array.from(e.slice(n,n+t)));n._animation=o}}return n._animation}function V(n){if(ArrayBuffer.isView(n)||n instanceof ArrayBuffer||n instanceof ImageBitmap)return n;if(Array.isArray(n))return n.map(V);if(n&&"object"==typeof n){const e={};for(const t in n)e[t]=V(n[t]);return e}return n}const U="uniform scenegraphUniforms {\n float sizeScale;\n float sizeMinPixels;\n float sizeMaxPixels;\n mat4 sceneModelMatrix;\n bool composeModelMatrix;\n} scenegraph;\n",D={name:"scenegraph",vs:U,fs:U,uniformTypes:{sizeScale:"f32",sizeMinPixels:"f32",sizeMaxPixels:"f32",sceneModelMatrix:"mat4x4<f32>",composeModelMatrix:"f32"}},z=[255,255,255,255],j={scenegraph:{type:"object",value:null,async:!0},getScene:n=>n&&n.scenes?"object"==typeof n.scene?n.scene:n.scenes[n.scene||0]:n,getAnimator:n=>n&&n.animator,_animations:null,sizeScale:{type:"number",value:1,min:0},sizeMinPixels:{type:"number",min:0,value:0},sizeMaxPixels:{type:"number",min:0,value:Number.MAX_SAFE_INTEGER},getPosition:{type:"accessor",value:n=>n.position},getColor:{type:"accessor",value:z},_lighting:"flat",_imageBasedLightingEnvironment:void 0,getOrientation:{type:"accessor",value:[0,0,0]},getScale:{type:"accessor",value:[1,1,1]},getTranslation:{type:"accessor",value:[0,0,0]},getTransformMatrix:{type:"accessor",value:[]},loaders:[e]};class q extends f{getShaders(){const n={};let e;return"pbr"===this.props._lighting?(e=h,n.LIGHTING_PBR=1):e={name:"pbrMaterial"},super.getShaders({defines:n,vs:"#version 300 es\n#define SHADER_NAME scenegraph-layer-vertex-shader\nin vec3 instancePositions;\nin vec3 instancePositions64Low;\nin vec4 instanceColors;\nin vec3 instancePickingColors;\nin vec3 instanceModelMatrixCol0;\nin vec3 instanceModelMatrixCol1;\nin vec3 instanceModelMatrixCol2;\nin vec3 instanceTranslation;\nin vec3 positions;\n#ifdef HAS_UV\nin vec2 texCoords;\n#endif\n#ifdef LIGHTING_PBR\n#ifdef HAS_NORMALS\nin vec3 normals;\n#endif\n#endif\nout vec4 vColor;\n#ifndef LIGHTING_PBR\n#ifdef HAS_UV\nout vec2 vTEXCOORD_0;\n#endif\n#endif\nvoid main(void) {\n#if defined(HAS_UV) && !defined(LIGHTING_PBR)\nvTEXCOORD_0 = texCoords;\ngeometry.uv = texCoords;\n#endif\ngeometry.worldPosition = instancePositions;\ngeometry.pickingColor = instancePickingColors;\nmat3 instanceModelMatrix = mat3(instanceModelMatrixCol0, instanceModelMatrixCol1, instanceModelMatrixCol2);\nvec3 normal = vec3(0.0, 0.0, 1.0);\n#ifdef LIGHTING_PBR\n#ifdef HAS_NORMALS\nnormal = instanceModelMatrix * (scenegraph.sceneModelMatrix * vec4(normals, 0.0)).xyz;\n#endif\n#endif\nfloat originalSize = project_size_to_pixel(scenegraph.sizeScale);\nfloat clampedSize = clamp(originalSize, scenegraph.sizeMinPixels, scenegraph.sizeMaxPixels);\nvec3 pos = (instanceModelMatrix * (scenegraph.sceneModelMatrix * vec4(positions, 1.0)).xyz) * scenegraph.sizeScale * (clampedSize / originalSize) + instanceTranslation;\nif(scenegraph.composeModelMatrix) {\nDECKGL_FILTER_SIZE(pos, geometry);\ngeometry.normal = project_normal(normal);\ngeometry.worldPosition += pos;\ngl_Position = project_position_to_clipspace(pos + instancePositions, instancePositions64Low, vec3(0.0), geometry.position);\n}\nelse {\npos = project_size(pos);\nDECKGL_FILTER_SIZE(pos, geometry);\ngl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, pos, geometry.position);\ngeometry.normal = project_normal(normal);\n}\nDECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n#ifdef LIGHTING_PBR\npbr_vPosition = geometry.position.xyz;\n#ifdef HAS_NORMALS\npbr_vNormal = geometry.normal;\n#endif\n#ifdef HAS_UV\npbr_vUV = texCoords;\n#else\npbr_vUV = vec2(0., 0.);\n#endif\ngeometry.uv = pbr_vUV;\n#endif\nvColor = instanceColors;\nDECKGL_FILTER_COLOR(vColor, geometry);\n}\n",fs:"#version 300 es\n#define SHADER_NAME scenegraph-layer-fragment-shader\nin vec4 vColor;\nout vec4 fragColor;\n#ifndef LIGHTING_PBR\n#if defined(HAS_UV) && defined(HAS_BASECOLORMAP)\nin vec2 vTEXCOORD_0;\nuniform sampler2D pbr_baseColorSampler;\n#endif\n#endif\nvoid main(void) {\n#ifdef LIGHTING_PBR\nfragColor = vColor * pbr_filterColor(vec4(0));\ngeometry.uv = pbr_vUV;\n#else\n#if defined(HAS_UV) && defined(HAS_BASECOLORMAP)\nfragColor = vColor * texture(pbr_baseColorSampler, vTEXCOORD_0);\ngeometry.uv = vTEXCOORD_0;\n#else\nfragColor = vColor;\n#endif\n#endif\nfragColor.a *= layer.opacity;\nDECKGL_FILTER_COLOR(fragColor, geometry);\n}\n",modules:[p,d,D,e]})}initializeState(){this.getAttributeManager().addInstanced({instancePositions:{size:3,type:"float64",fp64:this.use64bitPositions(),accessor:"getPosition",transition:!0},instanceColors:{type:"unorm8",size:this.props.colorFormat.length,accessor:"getColor",defaultValue:z,transition:!0},instanceModelMatrix:u})}updateState(n){super.updateState(n);const{props:e,oldProps:t}=n;e.scenegraph!==t.scenegraph?this._updateScenegraph():e._animations!==t._animations&&this._applyAnimationsProp(this.state.animator,e._animations)}finalizeState(n){super.finalizeState(n),this.state.scenegraph?.destroy()}get isLoaded(){return Boolean(this.state?.scenegraph&&super.isLoaded)}_updateScenegraph(){const e=this.props,{device:t}=this.context;let o=null;if(e.scenegraph instanceof v)o={scenes:[e.scenegraph]};else if(e.scenegraph&&"object"==typeof e.scenegraph){const r=e.scenegraph,i=r.json?n(r):r,a=function(n,e,t){const o=x(n,e=V(e),t),r=function(n){return(n.animations||[]).map(((e,t)=>{const o=e.name||`Animation-${t}`,r=e.samplers.map((({input:e,interpolation:t="LINEAR",output:o})=>({input:F(n.accessors[e]),interpolation:t,output:F(n.accessors[o])})));return{name:o,channels:e.channels.map((({sampler:e,target:t})=>({sampler:r[e],target:n.nodes[t.node??0],path:t.path})))}}))}(e);return{scenes:o,animator:new O({animations:r})}}(t,i,this._getModelOptions());o={gltf:i,...a},async function(n){const e=[];return n.scenes.forEach((n=>{n.traverse((()=>{}))})),await async function(){for(;e.some((n=>!n.loaded));)await new Promise((n=>requestAnimationFrame(n)))}()}(a).then((()=>{this.setNeedsRedraw()})).catch((n=>{this.raiseError(n,"loading glTF")}))}const r={layer:this,device:this.context.device},i=e.getScene(o,r),a=e.getAnimator(o,r);if(i instanceof _){this.state.scenegraph?.destroy(),this._applyAnimationsProp(a,e._animations);const n=[];i.traverse((e=>{e instanceof S&&n.push(e.model)})),this.setState({scenegraph:i,animator:a,models:n}),this.getAttributeManager().invalidateAll()}else null!==i&&m.warn("invalid scenegraph:",i)()}_applyAnimationsProp(n,e){if(!n||!e)return;const t=n.getAnimations();Object.keys(e).sort().forEach((n=>{const o=e[n];if("*"===n)t.forEach((n=>{Object.assign(n,o)}));else if(Number.isFinite(Number(n))){const e=Number(n);e>=0&&e<t.length?Object.assign(t[e],o):m.warn(`animation ${n} not found`)()}else{const e=t.find((({animation:e})=>e.name===n));e?Object.assign(e,o):m.warn(`animation ${n} not found`)()}}))}_getModelOptions(){const{_imageBasedLightingEnvironment:n}=this.props;let e;return n&&(e="function"==typeof n?n({gl:this.context.gl,layer:this}):n),{imageBasedLightingEnvironment:e,modelOptions:{id:this.props.id,isInstanced:!0,bufferLayout:this.getAttributeManager().getBufferLayouts(),...this.getShaders()},useTangents:!1}}draw({context:n}){if(!this.state.scenegraph)return;this.props._animations&&this.state.animator&&(this.state.animator.animate(n.timeline.getTime()),this.setNeedsRedraw());const{viewport:e,renderPass:t}=this.context,{sizeScale:o,sizeMinPixels:r,sizeMaxPixels:i,coordinateSystem:a}=this.props,s={camera:e.cameraPosition},l=this.getNumInstances();this.state.scenegraph.traverse(((n,{worldMatrix:c})=>{if(n instanceof S){const{model:f}=n;f.setInstanceCount(l);const p={sizeScale:o,sizeMinPixels:r,sizeMaxPixels:i,composeModelMatrix:b(e,a),sceneModelMatrix:c};f.shaderInputs.setProps({pbrProjection:s,scenegraph:p}),f.draw(t)}}))}}q.defaultProps=j,q.layerName="ScenegraphLayer";export{q as S,L as a,h as p}
1
+ import{postProcessGLTF as n,GLTFLoader as e}from"@loaders.gl/gltf";import{aK as t,a0 as o,V as r,u as i,aL as a,M as s,G as l,aM as c,L as f,p,a as d,aN as u,j as m,aO as b}from"./p-9Rt23jlQ.js";const g="uniform pbrProjectionUniforms {\n mat4 modelViewProjectionMatrix;\n mat4 modelMatrix;\n mat4 normalMatrix;\n vec3 camera;\n} pbrProjection;\n",h={props:{},uniforms:{},name:"pbrMaterial",dependencies:[t,{name:"pbrProjection",vs:g,fs:g,getUniforms:n=>n,uniformTypes:{modelViewProjectionMatrix:"mat4x4<f32>",modelMatrix:"mat4x4<f32>",normalMatrix:"mat4x4<f32>",camera:"vec3<i32>"}}],source:"struct PBRFragmentInputs {\n pbr_vPosition: vec3f,\n pbr_vUV: vec2f,\n pbr_vTBN: mat3f,\n pbr_vNormal: vec3f\n};\n\nvar fragmentInputs: PBRFragmentInputs;\n\nfn pbr_setPositionNormalTangentUV(position: vec4f, normal: vec4f, tangent: vec4f, uv: vec2f)\n{\n var pos: vec4f = pbrProjection.modelMatrix * position;\n pbr_vPosition = vec3(pos.xyz) / pos.w;\n\n#ifdef HAS_NORMALS\n#ifdef HAS_TANGENTS\n let normalW: vec3f = normalize(vec3(pbrProjection.normalMatrix * vec4(normal.xyz, 0.0)));\n let tangentW: vec3f = normalize(vec3(pbrProjection.modelMatrix * vec4(tangent.xyz, 0.0)));\n let bitangentW: vec3f = cross(normalW, tangentW) * tangent.w;\n fragmentInputs,pbr_vTBN = mat3(tangentW, bitangentW, normalW);\n#else // HAS_TANGENTS != 1\n fragmentInputs.pbr_vNormal = normalize(vec3(pbrProjection.modelMatrix * vec4(normal.xyz, 0.0)));\n#endif\n#endif\n\n#ifdef HAS_UV\n pbr_vUV = uv;\n#else\n pbr_vUV = vec2(0.,0.);\n#endif\n}\n\nstruct pbrMaterialUniforms {\n // Material is unlit\n unlit: uint32,\n\n // Base color map\n baseColorMapEnabled: uint32,\n baseColorFactor: vec4f,\n\n normalMapEnabled : uint32,\n normalScale: f32, // #ifdef HAS_NORMALMAP\n\n emissiveMapEnabled: uint32,\n emissiveFactor: vec3f, // #ifdef HAS_EMISSIVEMAP\n\n metallicRoughnessValues: vec2f,\n metallicRoughnessMapEnabled: uint32,\n\n occlusionMapEnabled: i32,\n occlusionStrength: f32, // #ifdef HAS_OCCLUSIONMAP\n \n alphaCutoffEnabled: i32,\n alphaCutoff: f32, // #ifdef ALPHA_CUTOFF\n \n // IBL\n IBLenabled: i32,\n scaleIBLAmbient: vec2f, // #ifdef USE_IBL\n \n // debugging flags used for shader output of intermediate PBR variables\n // #ifdef PBR_DEBUG\n scaleDiffBaseMR: vec4f,\n scaleFGDSpec: vec4f\n // #endif\n} \n \n@binding(2) @group(0) var<uniform> material : pbrMaterialUniforms;\n\n// Samplers\n#ifdef HAS_BASECOLORMAP\nuniform sampler2D pbr_baseColorSampler;\n#endif\n#ifdef HAS_NORMALMAP\nuniform sampler2D pbr_normalSampler;\n#endif\n#ifdef HAS_EMISSIVEMAP\nuniform sampler2D pbr_emissiveSampler;\n#endif\n#ifdef HAS_METALROUGHNESSMAP\nuniform sampler2D pbr_metallicRoughnessSampler;\n#endif\n#ifdef HAS_OCCLUSIONMAP\nuniform sampler2D pbr_occlusionSampler;\n#endif\n#ifdef USE_IBL\nuniform samplerCube pbr_diffuseEnvSampler;\nuniform samplerCube pbr_specularEnvSampler;\nuniform sampler2D pbr_brdfLUT;\n#endif\n\n// Encapsulate the various inputs used by the various functions in the shading equation\n// We store values in this struct to simplify the integration of alternative implementations\n// of the shading terms, outlined in the Readme.MD Appendix.\nstruct PBRInfo {\n NdotL: f32, // cos angle between normal and light direction\n NdotV: f32, // cos angle between normal and view direction\n NdotH: f32, // cos angle between normal and half vector\n LdotH: f32, // cos angle between light direction and half vector\n VdotH: f32, // cos angle between view direction and half vector\n perceptualRoughness: f32, // roughness value, as authored by the model creator (input to shader)\n metalness: f32, // metallic value at the surface\n reflectance0: vec3f, // full reflectance color (normal incidence angle)\n reflectance90: vec3f, // reflectance color at grazing angle\n alphaRoughness: f32, // roughness mapped to a more linear change in the roughness (proposed by [2])\n diffuseColor: vec3f, // color contribution from diffuse lighting\n specularColor: vec3f, // color contribution from specular lighting\n n: vec3f, // normal at surface point\n v: vec3f, // vector from surface point to camera\n};\n\nconst M_PI = 3.141592653589793;\nconst c_MinRoughness = 0.04;\n\nfn SRGBtoLINEAR(srgbIn: vec4f ) -> vec4f\n{\n#ifdef MANUAL_SRGB\n#ifdef SRGB_FAST_APPROXIMATION\n var linOut: vec3f = pow(srgbIn.xyz,vec3(2.2));\n#else // SRGB_FAST_APPROXIMATION\n var bLess: vec3f = step(vec3(0.04045),srgbIn.xyz);\n var linOut: vec3f = mix( srgbIn.xyz/vec3(12.92), pow((srgbIn.xyz+vec3(0.055))/vec3(1.055),vec3(2.4)), bLess );\n#endif //SRGB_FAST_APPROXIMATION\n return vec4f(linOut,srgbIn.w);;\n#else //MANUAL_SRGB\n return srgbIn;\n#endif //MANUAL_SRGB\n}\n\n// Find the normal for this fragment, pulling either from a predefined normal map\n// or from the interpolated mesh normal and tangent attributes.\nfn getNormal() -> vec3f\n{\n // Retrieve the tangent space matrix\n#ifndef HAS_TANGENTS\n var pos_dx: vec3f = dFdx(pbr_vPosition);\n var pos_dy: vec3f = dFdy(pbr_vPosition);\n var tex_dx: vec3f = dFdx(vec3(pbr_vUV, 0.0));\n var tex_dy: vec3f = dFdy(vec3(pbr_vUV, 0.0));\n var t: vec3f = (tex_dy.t * pos_dx - tex_dx.t * pos_dy) / (tex_dx.s * tex_dy.t - tex_dy.s * tex_dx.t);\n\n#ifdef HAS_NORMALS\n var ng: vec3f = normalize(pbr_vNormal);\n#else\n var ng: vec3f = cross(pos_dx, pos_dy);\n#endif\n\n t = normalize(t - ng * dot(ng, t));\n var b: vec3f = normalize(cross(ng, t));\n var tbn: mat3f = mat3f(t, b, ng);\n#else // HAS_TANGENTS\n var tbn: mat3f = pbr_vTBN;\n#endif\n\n#ifdef HAS_NORMALMAP\n vec3 n = texture(pbr_normalSampler, pbr_vUV).rgb;\n n = normalize(tbn * ((2.0 * n - 1.0) * vec3(pbrMaterial.normalScale, pbrMaterial.normalScale, 1.0)));\n#else\n // The tbn matrix is linearly interpolated, so we need to re-normalize\n vec3 n = normalize(tbn[2].xyz);\n#endif\n\n return n;\n}\n\n// Calculation of the lighting contribution from an optional Image Based Light source.\n// Precomputed Environment Maps are required uniform inputs and are computed as outlined in [1].\n// See our README.md on Environment Maps [3] for additional discussion.\n#ifdef USE_IBL\nfn getIBLContribution(PBRInfo pbrInfo, vec3 n, vec3 reflection) -> vec3f\n{\n float mipCount = 9.0; // resolution of 512x512\n float lod = (pbrInfo.perceptualRoughness * mipCount);\n // retrieve a scale and bias to F0. See [1], Figure 3\n vec3 brdf = SRGBtoLINEAR(texture(pbr_brdfLUT,\n vec2(pbrInfo.NdotV, 1.0 - pbrInfo.perceptualRoughness))).rgb;\n vec3 diffuseLight = SRGBtoLINEAR(texture(pbr_diffuseEnvSampler, n)).rgb;\n\n#ifdef USE_TEX_LOD\n vec3 specularLight = SRGBtoLINEAR(texture(pbr_specularEnvSampler, reflection, lod)).rgb;\n#else\n vec3 specularLight = SRGBtoLINEAR(texture(pbr_specularEnvSampler, reflection)).rgb;\n#endif\n\n vec3 diffuse = diffuseLight * pbrInfo.diffuseColor;\n vec3 specular = specularLight * (pbrInfo.specularColor * brdf.x + brdf.y);\n\n // For presentation, this allows us to disable IBL terms\n diffuse *= pbrMaterial.scaleIBLAmbient.x;\n specular *= pbrMaterial.scaleIBLAmbient.y;\n\n return diffuse + specular;\n}\n#endif\n\n// Basic Lambertian diffuse\n// Implementation from Lambert's Photometria https://archive.org/details/lambertsphotome00lambgoog\n// See also [1], Equation 1\nfn diffuse(pbrInfo: PBRInfo) -> vec3<f32> {\n return pbrInfo.diffuseColor / PI;\n}\n\n// The following equation models the Fresnel reflectance term of the spec equation (aka F())\n// Implementation of fresnel from [4], Equation 15\nfn specularReflection(pbrInfo: PBRInfo) -> vec3<f32> {\n return pbrInfo.reflectance0 +\n (pbrInfo.reflectance90 - pbrInfo.reflectance0) *\n pow(clamp(1.0 - pbrInfo.VdotH, 0.0, 1.0), 5.0);\n}\n\n// This calculates the specular geometric attenuation (aka G()),\n// where rougher material will reflect less light back to the viewer.\n// This implementation is based on [1] Equation 4, and we adopt their modifications to\n// alphaRoughness as input as originally proposed in [2].\nfn geometricOcclusion(pbrInfo: PBRInfo) -> f32 {\n let NdotL: f32 = pbrInfo.NdotL;\n let NdotV: f32 = pbrInfo.NdotV;\n let r: f32 = pbrInfo.alphaRoughness;\n\n let attenuationL = 2.0 * NdotL / (NdotL + sqrt(r * r + (1.0 - r * r) * (NdotL * NdotL)));\n let attenuationV = 2.0 * NdotV / (NdotV + sqrt(r * r + (1.0 - r * r) * (NdotV * NdotV)));\n return attenuationL * attenuationV;\n}\n\n// The following equation(s) model the distribution of microfacet normals across\n// the area being drawn (aka D())\n// Implementation from \"Average Irregularity Representation of a Roughened Surface\n// for Ray Reflection\" by T. S. Trowbridge, and K. P. Reitz\n// Follows the distribution function recommended in the SIGGRAPH 2013 course notes\n// from EPIC Games [1], Equation 3.\nfn microfacetDistribution(pbrInfo: PBRInfo) -> f32 {\n let roughnessSq = pbrInfo.alphaRoughness * pbrInfo.alphaRoughness;\n let f = (pbrInfo.NdotH * roughnessSq - pbrInfo.NdotH) * pbrInfo.NdotH + 1.0;\n return roughnessSq / (PI * f * f);\n}\n\nfn PBRInfo_setAmbientLight(pbrInfo: ptr<function, PBRInfo>) {\n (*pbrInfo).NdotL = 1.0;\n (*pbrInfo).NdotH = 0.0;\n (*pbrInfo).LdotH = 0.0;\n (*pbrInfo).VdotH = 1.0;\n}\n\nfn PBRInfo_setDirectionalLight(pbrInfo: ptr<function, PBRInfo>, lightDirection: vec3<f32>) {\n let n = (*pbrInfo).n;\n let v = (*pbrInfo).v;\n let l = normalize(lightDirection); // Vector from surface point to light\n let h = normalize(l + v); // Half vector between both l and v\n\n (*pbrInfo).NdotL = clamp(dot(n, l), 0.001, 1.0);\n (*pbrInfo).NdotH = clamp(dot(n, h), 0.0, 1.0);\n (*pbrInfo).LdotH = clamp(dot(l, h), 0.0, 1.0);\n (*pbrInfo).VdotH = clamp(dot(v, h), 0.0, 1.0);\n}\n\nfn PBRInfo_setPointLight(pbrInfo: ptr<function, PBRInfo>, pointLight: PointLight) {\n let light_direction = normalize(pointLight.position - pbr_vPosition);\n PBRInfo_setDirectionalLight(pbrInfo, light_direction);\n}\n\nfn calculateFinalColor(pbrInfo: PBRInfo, lightColor: vec3<f32>) -> vec3<f32> {\n // Calculate the shading terms for the microfacet specular shading model\n let F = specularReflection(pbrInfo);\n let G = geometricOcclusion(pbrInfo);\n let D = microfacetDistribution(pbrInfo);\n\n // Calculation of analytical lighting contribution\n let diffuseContrib = (1.0 - F) * diffuse(pbrInfo);\n let specContrib = F * G * D / (4.0 * pbrInfo.NdotL * pbrInfo.NdotV);\n // Obtain final intensity as reflectance (BRDF) scaled by the energy of the light (cosine law)\n return pbrInfo.NdotL * lightColor * (diffuseContrib + specContrib);\n}\n\nfn pbr_filterColor(colorUnused: vec4<f32>) -> vec4<f32> {\n // The albedo may be defined from a base texture or a flat color\n var baseColor: vec4<f32>;\n #ifdef HAS_BASECOLORMAP\n baseColor = SRGBtoLINEAR(textureSample(pbr_baseColorSampler, pbr_baseColorSampler, pbr_vUV)) * pbrMaterial.baseColorFactor;\n #else\n baseColor = pbrMaterial.baseColorFactor;\n #endif\n\n #ifdef ALPHA_CUTOFF\n if (baseColor.a < pbrMaterial.alphaCutoff) {\n discard;\n }\n #endif\n\n var color = vec3<f32>(0.0, 0.0, 0.0);\n\n if (pbrMaterial.unlit) {\n color = baseColor.rgb;\n } else {\n // Metallic and Roughness material properties are packed together\n // In glTF, these factors can be specified by fixed scalar values\n // or from a metallic-roughness map\n var perceptualRoughness = pbrMaterial.metallicRoughnessValues.y;\n var metallic = pbrMaterial.metallicRoughnessValues.x;\n #ifdef HAS_METALROUGHNESSMAP\n // Roughness is stored in the 'g' channel, metallic is stored in the 'b' channel.\n // This layout intentionally reserves the 'r' channel for (optional) occlusion map data\n let mrSample = textureSample(pbr_metallicRoughnessSampler, pbr_metallicRoughnessSampler, pbr_vUV);\n perceptualRoughness = mrSample.g * perceptualRoughness;\n metallic = mrSample.b * metallic;\n #endif\n perceptualRoughness = clamp(perceptualRoughness, c_MinRoughness, 1.0);\n metallic = clamp(metallic, 0.0, 1.0);\n // Roughness is authored as perceptual roughness; as is convention,\n // convert to material roughness by squaring the perceptual roughness [2].\n let alphaRoughness = perceptualRoughness * perceptualRoughness;\n\n let f0 = vec3<f32>(0.04);\n var diffuseColor = baseColor.rgb * (vec3<f32>(1.0) - f0);\n diffuseColor *= 1.0 - metallic;\n let specularColor = mix(f0, baseColor.rgb, metallic);\n\n // Compute reflectance.\n let reflectance = max(max(specularColor.r, specularColor.g), specularColor.b);\n\n // For typical incident reflectance range (between 4% to 100%) set the grazing\n // reflectance to 100% for typical fresnel effect.\n // For very low reflectance range on highly diffuse objects (below 4%),\n // incrementally reduce grazing reflectance to 0%.\n let reflectance90 = clamp(reflectance * 25.0, 0.0, 1.0);\n let specularEnvironmentR0 = specularColor;\n let specularEnvironmentR90 = vec3<f32>(1.0, 1.0, 1.0) * reflectance90;\n\n let n = getNormal(); // normal at surface point\n let v = normalize(pbrProjection.camera - pbr_vPosition); // Vector from surface point to camera\n\n let NdotV = clamp(abs(dot(n, v)), 0.001, 1.0);\n let reflection = -normalize(reflect(v, n));\n\n var pbrInfo = PBRInfo(\n 0.0, // NdotL\n NdotV,\n 0.0, // NdotH\n 0.0, // LdotH\n 0.0, // VdotH\n perceptualRoughness,\n metallic,\n specularEnvironmentR0,\n specularEnvironmentR90,\n alphaRoughness,\n diffuseColor,\n specularColor,\n n,\n v\n );\n\n #ifdef USE_LIGHTS\n // Apply ambient light\n PBRInfo_setAmbientLight(&pbrInfo);\n color += calculateFinalColor(pbrInfo, lighting.ambientColor);\n\n // Apply directional light\n for (var i = 0; i < lighting.directionalLightCount; i++) {\n if (i < lighting.directionalLightCount) {\n PBRInfo_setDirectionalLight(&pbrInfo, lighting_getDirectionalLight(i).direction);\n color += calculateFinalColor(pbrInfo, lighting_getDirectionalLight(i).color);\n }\n }\n\n // Apply point light\n for (var i = 0; i < lighting.pointLightCount; i++) {\n if (i < lighting.pointLightCount) {\n PBRInfo_setPointLight(&pbrInfo, lighting_getPointLight(i));\n let attenuation = getPointLightAttenuation(lighting_getPointLight(i), distance(lighting_getPointLight(i).position, pbr_vPosition));\n color += calculateFinalColor(pbrInfo, lighting_getPointLight(i).color / attenuation);\n }\n }\n #endif\n\n // Calculate lighting contribution from image based lighting source (IBL)\n #ifdef USE_IBL\n if (pbrMaterial.IBLenabled) {\n color += getIBLContribution(pbrInfo, n, reflection);\n }\n #endif\n\n // Apply optional PBR terms for additional (optional) shading\n #ifdef HAS_OCCLUSIONMAP\n if (pbrMaterial.occlusionMapEnabled) {\n let ao = textureSample(pbr_occlusionSampler, pbr_occlusionSampler, pbr_vUV).r;\n color = mix(color, color * ao, pbrMaterial.occlusionStrength);\n }\n #endif\n\n #ifdef HAS_EMISSIVEMAP\n if (pbrMaterial.emissiveMapEnabled) {\n let emissive = SRGBtoLINEAR(textureSample(pbr_emissiveSampler, pbr_emissiveSampler, pbr_vUV)).rgb * pbrMaterial.emissiveFactor;\n color += emissive;\n }\n #endif\n\n // This section uses mix to override final color for reference app visualization\n // of various parameters in the lighting equation.\n #ifdef PBR_DEBUG\n // TODO: Figure out how to debug multiple lights\n\n // color = mix(color, F, pbr_scaleFGDSpec.x);\n // color = mix(color, vec3(G), pbr_scaleFGDSpec.y);\n // color = mix(color, vec3(D), pbr_scaleFGDSpec.z);\n // color = mix(color, specContrib, pbr_scaleFGDSpec.w);\n\n // color = mix(color, diffuseContrib, pbr_scaleDiffBaseMR.x);\n color = mix(color, baseColor.rgb, pbrMaterial.scaleDiffBaseMR.y);\n color = mix(color, vec3<f32>(metallic), pbrMaterial.scaleDiffBaseMR.z);\n color = mix(color, vec3<f32>(perceptualRoughness), pbrMaterial.scaleDiffBaseMR.w);\n #endif\n }\n\n return vec4<f32>(pow(color, vec3<f32>(1.0 / 2.2)), baseColor.a);\n}\n",vs:"out vec3 pbr_vPosition;\nout vec2 pbr_vUV;\n\n#ifdef HAS_NORMALS\n# ifdef HAS_TANGENTS\nout mat3 pbr_vTBN;\n# else\nout vec3 pbr_vNormal;\n# endif\n#endif\n\nvoid pbr_setPositionNormalTangentUV(vec4 position, vec4 normal, vec4 tangent, vec2 uv)\n{\n vec4 pos = pbrProjection.modelMatrix * position;\n pbr_vPosition = vec3(pos.xyz) / pos.w;\n\n#ifdef HAS_NORMALS\n#ifdef HAS_TANGENTS\n vec3 normalW = normalize(vec3(pbrProjection.normalMatrix * vec4(normal.xyz, 0.0)));\n vec3 tangentW = normalize(vec3(pbrProjection.modelMatrix * vec4(tangent.xyz, 0.0)));\n vec3 bitangentW = cross(normalW, tangentW) * tangent.w;\n pbr_vTBN = mat3(tangentW, bitangentW, normalW);\n#else // HAS_TANGENTS != 1\n pbr_vNormal = normalize(vec3(pbrProjection.modelMatrix * vec4(normal.xyz, 0.0)));\n#endif\n#endif\n\n#ifdef HAS_UV\n pbr_vUV = uv;\n#else\n pbr_vUV = vec2(0.,0.);\n#endif\n}\n",fs:"precision highp float;\n\nuniform pbrMaterialUniforms {\n // Material is unlit\n bool unlit;\n\n // Base color map\n bool baseColorMapEnabled;\n vec4 baseColorFactor;\n\n bool normalMapEnabled; \n float normalScale; // #ifdef HAS_NORMALMAP\n\n bool emissiveMapEnabled;\n vec3 emissiveFactor; // #ifdef HAS_EMISSIVEMAP\n\n vec2 metallicRoughnessValues;\n bool metallicRoughnessMapEnabled;\n\n bool occlusionMapEnabled;\n float occlusionStrength; // #ifdef HAS_OCCLUSIONMAP\n \n bool alphaCutoffEnabled;\n float alphaCutoff; // #ifdef ALPHA_CUTOFF\n \n // IBL\n bool IBLenabled;\n vec2 scaleIBLAmbient; // #ifdef USE_IBL\n \n // debugging flags used for shader output of intermediate PBR variables\n // #ifdef PBR_DEBUG\n vec4 scaleDiffBaseMR;\n vec4 scaleFGDSpec;\n // #endif\n} pbrMaterial;\n\n// Samplers\n#ifdef HAS_BASECOLORMAP\nuniform sampler2D pbr_baseColorSampler;\n#endif\n#ifdef HAS_NORMALMAP\nuniform sampler2D pbr_normalSampler;\n#endif\n#ifdef HAS_EMISSIVEMAP\nuniform sampler2D pbr_emissiveSampler;\n#endif\n#ifdef HAS_METALROUGHNESSMAP\nuniform sampler2D pbr_metallicRoughnessSampler;\n#endif\n#ifdef HAS_OCCLUSIONMAP\nuniform sampler2D pbr_occlusionSampler;\n#endif\n#ifdef USE_IBL\nuniform samplerCube pbr_diffuseEnvSampler;\nuniform samplerCube pbr_specularEnvSampler;\nuniform sampler2D pbr_brdfLUT;\n#endif\n\n// Inputs from vertex shader\n\nin vec3 pbr_vPosition;\nin vec2 pbr_vUV;\n\n#ifdef HAS_NORMALS\n#ifdef HAS_TANGENTS\nin mat3 pbr_vTBN;\n#else\nin vec3 pbr_vNormal;\n#endif\n#endif\n\n// Encapsulate the various inputs used by the various functions in the shading equation\n// We store values in this struct to simplify the integration of alternative implementations\n// of the shading terms, outlined in the Readme.MD Appendix.\nstruct PBRInfo {\n float NdotL; // cos angle between normal and light direction\n float NdotV; // cos angle between normal and view direction\n float NdotH; // cos angle between normal and half vector\n float LdotH; // cos angle between light direction and half vector\n float VdotH; // cos angle between view direction and half vector\n float perceptualRoughness; // roughness value, as authored by the model creator (input to shader)\n float metalness; // metallic value at the surface\n vec3 reflectance0; // full reflectance color (normal incidence angle)\n vec3 reflectance90; // reflectance color at grazing angle\n float alphaRoughness; // roughness mapped to a more linear change in the roughness (proposed by [2])\n vec3 diffuseColor; // color contribution from diffuse lighting\n vec3 specularColor; // color contribution from specular lighting\n vec3 n; // normal at surface point\n vec3 v; // vector from surface point to camera\n};\n\nconst float M_PI = 3.141592653589793;\nconst float c_MinRoughness = 0.04;\n\nvec4 SRGBtoLINEAR(vec4 srgbIn)\n{\n#ifdef MANUAL_SRGB\n#ifdef SRGB_FAST_APPROXIMATION\n vec3 linOut = pow(srgbIn.xyz,vec3(2.2));\n#else // SRGB_FAST_APPROXIMATION\n vec3 bLess = step(vec3(0.04045),srgbIn.xyz);\n vec3 linOut = mix( srgbIn.xyz/vec3(12.92), pow((srgbIn.xyz+vec3(0.055))/vec3(1.055),vec3(2.4)), bLess );\n#endif //SRGB_FAST_APPROXIMATION\n return vec4(linOut,srgbIn.w);;\n#else //MANUAL_SRGB\n return srgbIn;\n#endif //MANUAL_SRGB\n}\n\n// Find the normal for this fragment, pulling either from a predefined normal map\n// or from the interpolated mesh normal and tangent attributes.\nvec3 getNormal()\n{\n // Retrieve the tangent space matrix\n#ifndef HAS_TANGENTS\n vec3 pos_dx = dFdx(pbr_vPosition);\n vec3 pos_dy = dFdy(pbr_vPosition);\n vec3 tex_dx = dFdx(vec3(pbr_vUV, 0.0));\n vec3 tex_dy = dFdy(vec3(pbr_vUV, 0.0));\n vec3 t = (tex_dy.t * pos_dx - tex_dx.t * pos_dy) / (tex_dx.s * tex_dy.t - tex_dy.s * tex_dx.t);\n\n#ifdef HAS_NORMALS\n vec3 ng = normalize(pbr_vNormal);\n#else\n vec3 ng = cross(pos_dx, pos_dy);\n#endif\n\n t = normalize(t - ng * dot(ng, t));\n vec3 b = normalize(cross(ng, t));\n mat3 tbn = mat3(t, b, ng);\n#else // HAS_TANGENTS\n mat3 tbn = pbr_vTBN;\n#endif\n\n#ifdef HAS_NORMALMAP\n vec3 n = texture(pbr_normalSampler, pbr_vUV).rgb;\n n = normalize(tbn * ((2.0 * n - 1.0) * vec3(pbrMaterial.normalScale, pbrMaterial.normalScale, 1.0)));\n#else\n // The tbn matrix is linearly interpolated, so we need to re-normalize\n vec3 n = normalize(tbn[2].xyz);\n#endif\n\n return n;\n}\n\n// Calculation of the lighting contribution from an optional Image Based Light source.\n// Precomputed Environment Maps are required uniform inputs and are computed as outlined in [1].\n// See our README.md on Environment Maps [3] for additional discussion.\n#ifdef USE_IBL\nvec3 getIBLContribution(PBRInfo pbrInfo, vec3 n, vec3 reflection)\n{\n float mipCount = 9.0; // resolution of 512x512\n float lod = (pbrInfo.perceptualRoughness * mipCount);\n // retrieve a scale and bias to F0. See [1], Figure 3\n vec3 brdf = SRGBtoLINEAR(texture(pbr_brdfLUT,\n vec2(pbrInfo.NdotV, 1.0 - pbrInfo.perceptualRoughness))).rgb;\n vec3 diffuseLight = SRGBtoLINEAR(texture(pbr_diffuseEnvSampler, n)).rgb;\n\n#ifdef USE_TEX_LOD\n vec3 specularLight = SRGBtoLINEAR(texture(pbr_specularEnvSampler, reflection, lod)).rgb;\n#else\n vec3 specularLight = SRGBtoLINEAR(texture(pbr_specularEnvSampler, reflection)).rgb;\n#endif\n\n vec3 diffuse = diffuseLight * pbrInfo.diffuseColor;\n vec3 specular = specularLight * (pbrInfo.specularColor * brdf.x + brdf.y);\n\n // For presentation, this allows us to disable IBL terms\n diffuse *= pbrMaterial.scaleIBLAmbient.x;\n specular *= pbrMaterial.scaleIBLAmbient.y;\n\n return diffuse + specular;\n}\n#endif\n\n// Basic Lambertian diffuse\n// Implementation from Lambert's Photometria https://archive.org/details/lambertsphotome00lambgoog\n// See also [1], Equation 1\nvec3 diffuse(PBRInfo pbrInfo)\n{\n return pbrInfo.diffuseColor / M_PI;\n}\n\n// The following equation models the Fresnel reflectance term of the spec equation (aka F())\n// Implementation of fresnel from [4], Equation 15\nvec3 specularReflection(PBRInfo pbrInfo)\n{\n return pbrInfo.reflectance0 +\n (pbrInfo.reflectance90 - pbrInfo.reflectance0) *\n pow(clamp(1.0 - pbrInfo.VdotH, 0.0, 1.0), 5.0);\n}\n\n// This calculates the specular geometric attenuation (aka G()),\n// where rougher material will reflect less light back to the viewer.\n// This implementation is based on [1] Equation 4, and we adopt their modifications to\n// alphaRoughness as input as originally proposed in [2].\nfloat geometricOcclusion(PBRInfo pbrInfo)\n{\n float NdotL = pbrInfo.NdotL;\n float NdotV = pbrInfo.NdotV;\n float r = pbrInfo.alphaRoughness;\n\n float attenuationL = 2.0 * NdotL / (NdotL + sqrt(r * r + (1.0 - r * r) * (NdotL * NdotL)));\n float attenuationV = 2.0 * NdotV / (NdotV + sqrt(r * r + (1.0 - r * r) * (NdotV * NdotV)));\n return attenuationL * attenuationV;\n}\n\n// The following equation(s) model the distribution of microfacet normals across\n// the area being drawn (aka D())\n// Implementation from \"Average Irregularity Representation of a Roughened Surface\n// for Ray Reflection\" by T. S. Trowbridge, and K. P. Reitz\n// Follows the distribution function recommended in the SIGGRAPH 2013 course notes\n// from EPIC Games [1], Equation 3.\nfloat microfacetDistribution(PBRInfo pbrInfo)\n{\n float roughnessSq = pbrInfo.alphaRoughness * pbrInfo.alphaRoughness;\n float f = (pbrInfo.NdotH * roughnessSq - pbrInfo.NdotH) * pbrInfo.NdotH + 1.0;\n return roughnessSq / (M_PI * f * f);\n}\n\nvoid PBRInfo_setAmbientLight(inout PBRInfo pbrInfo) {\n pbrInfo.NdotL = 1.0;\n pbrInfo.NdotH = 0.0;\n pbrInfo.LdotH = 0.0;\n pbrInfo.VdotH = 1.0;\n}\n\nvoid PBRInfo_setDirectionalLight(inout PBRInfo pbrInfo, vec3 lightDirection) {\n vec3 n = pbrInfo.n;\n vec3 v = pbrInfo.v;\n vec3 l = normalize(lightDirection); // Vector from surface point to light\n vec3 h = normalize(l+v); // Half vector between both l and v\n\n pbrInfo.NdotL = clamp(dot(n, l), 0.001, 1.0);\n pbrInfo.NdotH = clamp(dot(n, h), 0.0, 1.0);\n pbrInfo.LdotH = clamp(dot(l, h), 0.0, 1.0);\n pbrInfo.VdotH = clamp(dot(v, h), 0.0, 1.0);\n}\n\nvoid PBRInfo_setPointLight(inout PBRInfo pbrInfo, PointLight pointLight) {\n vec3 light_direction = normalize(pointLight.position - pbr_vPosition);\n PBRInfo_setDirectionalLight(pbrInfo, light_direction);\n}\n\nvec3 calculateFinalColor(PBRInfo pbrInfo, vec3 lightColor) {\n // Calculate the shading terms for the microfacet specular shading model\n vec3 F = specularReflection(pbrInfo);\n float G = geometricOcclusion(pbrInfo);\n float D = microfacetDistribution(pbrInfo);\n\n // Calculation of analytical lighting contribution\n vec3 diffuseContrib = (1.0 - F) * diffuse(pbrInfo);\n vec3 specContrib = F * G * D / (4.0 * pbrInfo.NdotL * pbrInfo.NdotV);\n // Obtain final intensity as reflectance (BRDF) scaled by the energy of the light (cosine law)\n return pbrInfo.NdotL * lightColor * (diffuseContrib + specContrib);\n}\n\nvec4 pbr_filterColor(vec4 colorUnused)\n{\n // The albedo may be defined from a base texture or a flat color\n#ifdef HAS_BASECOLORMAP\n vec4 baseColor = SRGBtoLINEAR(texture(pbr_baseColorSampler, pbr_vUV)) * pbrMaterial.baseColorFactor;\n#else\n vec4 baseColor = pbrMaterial.baseColorFactor;\n#endif\n\n#ifdef ALPHA_CUTOFF\n if (baseColor.a < pbrMaterial.alphaCutoff) {\n discard;\n }\n#endif\n\n vec3 color = vec3(0, 0, 0);\n\n if(pbrMaterial.unlit){\n color.rgb = baseColor.rgb;\n }\n else{\n // Metallic and Roughness material properties are packed together\n // In glTF, these factors can be specified by fixed scalar values\n // or from a metallic-roughness map\n float perceptualRoughness = pbrMaterial.metallicRoughnessValues.y;\n float metallic = pbrMaterial.metallicRoughnessValues.x;\n#ifdef HAS_METALROUGHNESSMAP\n // Roughness is stored in the 'g' channel, metallic is stored in the 'b' channel.\n // This layout intentionally reserves the 'r' channel for (optional) occlusion map data\n vec4 mrSample = texture(pbr_metallicRoughnessSampler, pbr_vUV);\n perceptualRoughness = mrSample.g * perceptualRoughness;\n metallic = mrSample.b * metallic;\n#endif\n perceptualRoughness = clamp(perceptualRoughness, c_MinRoughness, 1.0);\n metallic = clamp(metallic, 0.0, 1.0);\n // Roughness is authored as perceptual roughness; as is convention,\n // convert to material roughness by squaring the perceptual roughness [2].\n float alphaRoughness = perceptualRoughness * perceptualRoughness;\n\n vec3 f0 = vec3(0.04);\n vec3 diffuseColor = baseColor.rgb * (vec3(1.0) - f0);\n diffuseColor *= 1.0 - metallic;\n vec3 specularColor = mix(f0, baseColor.rgb, metallic);\n\n // Compute reflectance.\n float reflectance = max(max(specularColor.r, specularColor.g), specularColor.b);\n\n // For typical incident reflectance range (between 4% to 100%) set the grazing\n // reflectance to 100% for typical fresnel effect.\n // For very low reflectance range on highly diffuse objects (below 4%),\n // incrementally reduce grazing reflecance to 0%.\n float reflectance90 = clamp(reflectance * 25.0, 0.0, 1.0);\n vec3 specularEnvironmentR0 = specularColor.rgb;\n vec3 specularEnvironmentR90 = vec3(1.0, 1.0, 1.0) * reflectance90;\n\n vec3 n = getNormal(); // normal at surface point\n vec3 v = normalize(pbrProjection.camera - pbr_vPosition); // Vector from surface point to camera\n\n float NdotV = clamp(abs(dot(n, v)), 0.001, 1.0);\n vec3 reflection = -normalize(reflect(v, n));\n\n PBRInfo pbrInfo = PBRInfo(\n 0.0, // NdotL\n NdotV,\n 0.0, // NdotH\n 0.0, // LdotH\n 0.0, // VdotH\n perceptualRoughness,\n metallic,\n specularEnvironmentR0,\n specularEnvironmentR90,\n alphaRoughness,\n diffuseColor,\n specularColor,\n n,\n v\n );\n\n\n#ifdef USE_LIGHTS\n // Apply ambient light\n PBRInfo_setAmbientLight(pbrInfo);\n color += calculateFinalColor(pbrInfo, lighting.ambientColor);\n\n // Apply directional light\n for(int i = 0; i < lighting.directionalLightCount; i++) {\n if (i < lighting.directionalLightCount) {\n PBRInfo_setDirectionalLight(pbrInfo, lighting_getDirectionalLight(i).direction);\n color += calculateFinalColor(pbrInfo, lighting_getDirectionalLight(i).color);\n }\n }\n\n // Apply point light\n for(int i = 0; i < lighting.pointLightCount; i++) {\n if (i < lighting.pointLightCount) {\n PBRInfo_setPointLight(pbrInfo, lighting_getPointLight(i));\n float attenuation = getPointLightAttenuation(lighting_getPointLight(i), distance(lighting_getPointLight(i).position, pbr_vPosition));\n color += calculateFinalColor(pbrInfo, lighting_getPointLight(i).color / attenuation);\n }\n }\n#endif\n\n // Calculate lighting contribution from image based lighting source (IBL)\n#ifdef USE_IBL\n if (pbrMaterial.IBLenabled) {\n color += getIBLContribution(pbrInfo, n, reflection);\n }\n#endif\n\n // Apply optional PBR terms for additional (optional) shading\n#ifdef HAS_OCCLUSIONMAP\n if (pbrMaterial.occlusionMapEnabled) {\n float ao = texture(pbr_occlusionSampler, pbr_vUV).r;\n color = mix(color, color * ao, pbrMaterial.occlusionStrength);\n }\n#endif\n\n#ifdef HAS_EMISSIVEMAP\n if (pbrMaterial.emissiveMapEnabled) {\n vec3 emissive = SRGBtoLINEAR(texture(pbr_emissiveSampler, pbr_vUV)).rgb * pbrMaterial.emissiveFactor;\n color += emissive;\n }\n#endif\n\n // This section uses mix to override final color for reference app visualization\n // of various parameters in the lighting equation.\n#ifdef PBR_DEBUG\n // TODO: Figure out how to debug multiple lights\n\n // color = mix(color, F, pbr_scaleFGDSpec.x);\n // color = mix(color, vec3(G), pbr_scaleFGDSpec.y);\n // color = mix(color, vec3(D), pbr_scaleFGDSpec.z);\n // color = mix(color, specContrib, pbr_scaleFGDSpec.w);\n\n // color = mix(color, diffuseContrib, pbr_scaleDiffBaseMR.x);\n color = mix(color, baseColor.rgb, pbrMaterial.scaleDiffBaseMR.y);\n color = mix(color, vec3(metallic), pbrMaterial.scaleDiffBaseMR.z);\n color = mix(color, vec3(perceptualRoughness), pbrMaterial.scaleDiffBaseMR.w);\n#endif\n\n }\n\n return vec4(pow(color,vec3(1.0/2.2)), baseColor.a);\n}\n",defines:{LIGHTING_FRAGMENT:!0,HAS_NORMALMAP:!1,HAS_EMISSIVEMAP:!1,HAS_OCCLUSIONMAP:!1,HAS_BASECOLORMAP:!1,HAS_METALROUGHNESSMAP:!1,ALPHA_CUTOFF:!1,USE_IBL:!1,PBR_DEBUG:!1},getUniforms:n=>n,uniformTypes:{unlit:"i32",baseColorMapEnabled:"i32",baseColorFactor:"vec4<f32>",normalMapEnabled:"i32",normalScale:"f32",emissiveMapEnabled:"i32",emissiveFactor:"vec3<f32>",metallicRoughnessValues:"vec2<f32>",metallicRoughnessMapEnabled:"i32",occlusionMapEnabled:"i32",occlusionStrength:"f32",alphaCutoffEnabled:"i32",alphaCutoff:"f32",IBLenabled:"i32",scaleIBLAmbient:"vec2<f32>",scaleDiffBaseMR:"vec4<f32>",scaleFGDSpec:"vec4<f32>"}};class v{id;matrix=new o;display=!0;position=new r;rotation=new r;scale=new r(1,1,1);userData={};props={};constructor(n={}){const{id:e}=n;this.id=e||i(this.constructor.name),this._setScenegraphNodeProps(n)}getBounds(){return null}destroy(){}delete(){this.destroy()}setProps(n){return this._setScenegraphNodeProps(n),this}toString(){return`{type: ScenegraphNode, id: ${this.id})}`}setPosition(n){return this.position=n,this}setRotation(n){return this.rotation=n,this}setScale(n){return this.scale=n,this}setMatrix(n,e=!0){e?this.matrix.copy(n):this.matrix=n}setMatrixComponents(n){const{position:e,rotation:t,scale:o,update:r=!0}=n;return e&&this.setPosition(e),t&&this.setRotation(t),o&&this.setScale(o),r&&this.updateMatrix(),this}updateMatrix(){const n=this.position,e=this.rotation,t=this.scale;return this.matrix.identity(),this.matrix.translate(n),this.matrix.rotateXYZ(e),this.matrix.scale(t),this}update(n={}){const{position:e,rotation:t,scale:o}=n;return e&&this.setPosition(e),t&&this.setRotation(t),o&&this.setScale(o),this.updateMatrix(),this}getCoordinateUniforms(n,e){e=e||this.matrix;const t=new o(n).multiplyRight(e),r=t.invert(),i=r.transpose();return{viewMatrix:n,modelMatrix:e,objectMatrix:e,worldMatrix:t,worldInverseMatrix:r,worldInverseTransposeMatrix:i}}_setScenegraphNodeProps(n){"position"in n&&this.setPosition(n.position),"rotation"in n&&this.setRotation(n.rotation),"scale"in n&&this.setScale(n.scale),"matrix"in n&&this.setMatrix(n.matrix),Object.assign(this.props,n)}}class _ extends v{children;constructor(n={}){n=Array.isArray(n)?{children:n}:n;const{children:e=[]}=n;a.assert(e.every((n=>n instanceof v)),"every child must an instance of ScenegraphNode"),super(n),this.children=e}getBounds(){const n=[[1/0,1/0,1/0],[-1/0,-1/0,-1/0]];return this.traverse(((e,{worldMatrix:t})=>{const o=e.getBounds();if(!o)return;const[i,a]=o,s=new r(i).add(a).divide([2,2,2]);t.transformAsPoint(s,s);const l=new r(a).subtract(i).divide([2,2,2]);t.transformAsVector(l,l);for(let e=0;e<8;e++){const t=new r(1&e?-1:1,2&e?-1:1,4&e?-1:1).multiply(l).add(s);for(let e=0;e<3;e++)n[0][e]=Math.min(n[0][e],t[e]),n[1][e]=Math.max(n[1][e],t[e])}})),Number.isFinite(n[0][0])?n:null}destroy(){this.children.forEach((n=>n.destroy())),this.removeAll(),super.destroy()}add(...n){for(const e of n)Array.isArray(e)?this.add(...e):this.children.push(e);return this}remove(n){const e=this.children,t=e.indexOf(n);return t>-1&&e.splice(t,1),this}removeAll(){return this.children=[],this}traverse(n,{worldMatrix:e=new o}={}){const t=new o(e).multiplyRight(this.matrix);for(const e of this.children)e instanceof _?e.traverse(n,{worldMatrix:t}):n(e,{worldMatrix:t})}}class S extends v{model;bounds=null;managedResources;constructor(n){super(n),this.model=n.model,this.managedResources=n.managedResources||[],this.bounds=n.bounds||null,this.setProps(n)}destroy(){this.model&&(this.model.destroy(),this.model=null),this.managedResources.forEach((n=>n.destroy())),this.managedResources=[]}getBounds(){return this.bounds}draw(n){return this.model.draw(n)}}function I(n){return{addressModeU:A(n.wrapS),addressModeV:A(n.wrapT),magFilter:M(n.magFilter),...R(n.minFilter)}}function A(n){switch(n){case 33071:return"clamp-to-edge";case 10497:return"repeat";case 33648:return"mirror-repeat";default:return}}function M(n){switch(n){case 9728:return"nearest";case 9729:return"linear";default:return}}function R(n){switch(n){case 9728:return{minFilter:"nearest"};case 9729:return{minFilter:"linear"};case 9984:return{minFilter:"nearest",mipmapFilter:"nearest"};case 9985:return{minFilter:"linear",mipmapFilter:"nearest"};case 9986:return{minFilter:"nearest",mipmapFilter:"linear"};case 9987:return{minFilter:"linear",mipmapFilter:"linear"};default:return{}}}function L(n,e,t,o){const r={defines:{MANUAL_SRGB:!0,SRGB_FAST_APPROXIMATION:!0},bindings:{},uniforms:{camera:[0,0,0],metallicRoughnessValues:[1,1]},parameters:{},glParameters:{},generatedTextures:[]};r.defines.USE_TEX_LOD=!0;const{imageBasedLightingEnvironment:i}=o;return i&&(r.bindings.pbr_diffuseEnvSampler=i.diffuseEnvSampler.texture,r.bindings.pbr_specularEnvSampler=i.specularEnvSampler.texture,r.bindings.pbr_BrdfLUT=i.brdfLutTexture.texture,r.uniforms.scaleIBLAmbient=[1,1]),o?.pbrDebug&&(r.defines.PBR_DEBUG=!0,r.uniforms.scaleDiffBaseMR=[0,0,0,0],r.uniforms.scaleFGDSpec=[0,0,0,0]),t.NORMAL&&(r.defines.HAS_NORMALS=!0),t.TANGENT&&o?.useTangents&&(r.defines.HAS_TANGENTS=!0),t.TEXCOORD_0&&(r.defines.HAS_UV=!0),o?.imageBasedLightingEnvironment&&(r.defines.USE_IBL=!0),o?.lights&&(r.defines.USE_LIGHTS=!0),e&&function(n,e,t){if(t.uniforms.unlit=Boolean(e.unlit),e.pbrMetallicRoughness&&function(n,e,t){e.baseColorTexture&&N(n,e.baseColorTexture,"pbr_baseColorSampler","HAS_BASECOLORMAP",t),t.uniforms.baseColorFactor=e.baseColorFactor||[1,1,1,1],e.metallicRoughnessTexture&&N(n,e.metallicRoughnessTexture,"pbr_metallicRoughnessSampler","HAS_METALROUGHNESSMAP",t);const{metallicFactor:o=1,roughnessFactor:r=1}=e;t.uniforms.metallicRoughnessValues=[o,r]}(n,e.pbrMetallicRoughness,t),e.normalTexture){N(n,e.normalTexture,"pbr_normalSampler","HAS_NORMALMAP",t);const{scale:o=1}=e.normalTexture;t.uniforms.normalScale=o}if(e.occlusionTexture){N(n,e.occlusionTexture,"pbr_occlusionSampler","HAS_OCCLUSIONMAP",t);const{strength:o=1}=e.occlusionTexture;t.uniforms.occlusionStrength=o}switch(e.emissiveTexture&&(N(n,e.emissiveTexture,"pbr_emissiveSampler","HAS_EMISSIVEMAP",t),t.uniforms.emissiveFactor=e.emissiveFactor||[0,0,0]),e.alphaMode||"MASK"){case"MASK":const{alphaCutoff:n=.5}=e;t.defines.ALPHA_CUTOFF=!0,t.uniforms.alphaCutoff=n;break;case"BLEND":a.warn("glTF BLEND alphaMode might not work well because it requires mesh sorting")(),t.parameters.blend=!0,t.parameters.blendColorOperation="add",t.parameters.blendColorSrcFactor="src-alpha",t.parameters.blendColorDstFactor="one-minus-src-alpha",t.parameters.blendAlphaOperation="add",t.parameters.blendAlphaSrcFactor="one",t.parameters.blendAlphaDstFactor="one-minus-src-alpha",t.glParameters.blend=!0,t.glParameters.blendEquation=32774,t.glParameters.blendFunc=[770,771,1,771]}}(n,e,r),r}function N(n,e,t,o,r){const i=e.texture.source.image;let a;a=i.compressed?i:{data:i};const s={wrapS:10497,wrapT:10497,...e?.texture?.sampler},l=n.createTexture({id:e.uniformName||e.id,sampler:I(s),...a});r.bindings[t]=l,o&&(r.defines[o]=!0),r.generatedTextures.push(l)}var P;!function(n){n[n.POINTS=0]="POINTS",n[n.LINES=1]="LINES",n[n.LINE_LOOP=2]="LINE_LOOP",n[n.LINE_STRIP=3]="LINE_STRIP",n[n.TRIANGLES=4]="TRIANGLES",n[n.TRIANGLE_STRIP=5]="TRIANGLE_STRIP",n[n.TRIANGLE_FAN=6]="TRIANGLE_FAN"}(P||(P={}));const C={modelOptions:{},pbrDebug:!1,imageBasedLightingEnvironment:void 0,lights:!0,useTangents:!1};function x(n,e,t={}){const o={...C,...t},r=e.scenes.map((t=>function(n,e,t,o){const r=(e.nodes||[]).map((e=>E(n,e,t,o)));return new _({id:e.name||e.id,children:r})}(n,t,e.nodes,o)));return r}function E(n,e,t,r){if(!e._node){const i=(e.children||[]).map((e=>E(n,e,t,r)));e.mesh&&i.push(function(n,e,t){if(!e._mesh){const o=(e.primitives||[]).map(((o,r)=>function(n,e,t,o,r){const i=e.name||`${o.name||o.id}-primitive-${t}`,l=function(n){switch(n){case P.POINTS:return"point-list";case P.LINES:return"line-list";case P.LINE_STRIP:return"line-strip";case P.TRIANGLES:return"triangle-list";case P.TRIANGLE_STRIP:return"triangle-strip";default:throw new Error(String(n))}}(e.mode||4),c=e.indices?e.indices.count:function(){throw new Error("getVertexCount not implemented")}(),f=y(i,e,l),p=L(n,e.material,f.attributes,r),d=function(n,e){const{id:t,geometry:o,parsedPPBRMaterial:r,vertexCount:i,modelOptions:l={}}=e;a.info(4,"createGLTFModel defines: ",r.defines)();const c={id:t,source:"\nlayout(0) positions: vec4; // in vec4 POSITION;\n\n #ifdef HAS_NORMALS\n in vec4 normals; // in vec4 NORMAL;\n #endif\n\n #ifdef HAS_TANGENTS\n in vec4 TANGENT;\n #endif\n\n #ifdef HAS_UV\n // in vec2 TEXCOORD_0;\n in vec2 texCoords;\n #endif\n\n@vertex\n void main(void) {\n vec4 _NORMAL = vec4(0.);\n vec4 _TANGENT = vec4(0.);\n vec2 _TEXCOORD_0 = vec2(0.);\n\n #ifdef HAS_NORMALS\n _NORMAL = normals;\n #endif\n\n #ifdef HAS_TANGENTS\n _TANGENT = TANGENT;\n #endif\n\n #ifdef HAS_UV\n _TEXCOORD_0 = texCoords;\n #endif\n\n pbr_setPositionNormalTangentUV(positions, _NORMAL, _TANGENT, _TEXCOORD_0);\n gl_Position = u_MVPMatrix * positions;\n }\n\n@fragment\n out vec4 fragmentColor;\n\n void main(void) {\n vec3 pos = pbr_vPosition;\n fragmentColor = pbr_filterColor(vec4(1.0));\n }\n",vs:"#version 300 es\n\n // in vec4 POSITION;\n in vec4 positions;\n\n #ifdef HAS_NORMALS\n // in vec4 NORMAL;\n in vec4 normals;\n #endif\n\n #ifdef HAS_TANGENTS\n in vec4 TANGENT;\n #endif\n\n #ifdef HAS_UV\n // in vec2 TEXCOORD_0;\n in vec2 texCoords;\n #endif\n\n void main(void) {\n vec4 _NORMAL = vec4(0.);\n vec4 _TANGENT = vec4(0.);\n vec2 _TEXCOORD_0 = vec2(0.);\n\n #ifdef HAS_NORMALS\n _NORMAL = normals;\n #endif\n\n #ifdef HAS_TANGENTS\n _TANGENT = TANGENT;\n #endif\n\n #ifdef HAS_UV\n _TEXCOORD_0 = texCoords;\n #endif\n\n pbr_setPositionNormalTangentUV(positions, _NORMAL, _TANGENT, _TEXCOORD_0);\n gl_Position = pbrProjection.modelViewProjectionMatrix * positions;\n }\n",fs:"#version 300 es\n out vec4 fragmentColor;\n\n void main(void) {\n vec3 pos = pbr_vPosition;\n fragmentColor = pbr_filterColor(vec4(1.0));\n }\n",geometry:o,topology:o.topology,vertexCount:i,modules:[h],...l,defines:{...r.defines,...l.defines},parameters:{depthWriteEnabled:!0,depthCompare:"less",depthFormat:"depth24plus",cullMode:"back",...r.parameters,...l.parameters}},f=new s(n,c),{camera:p,...d}={...r.uniforms,...l.uniforms,...r.bindings,...l.bindings};return f.shaderInputs.setProps({pbrMaterial:d,pbrProjection:{camera:p}}),new S({managedResources:[],model:f})}(n,{id:i,geometry:y(i,e,l),parsedPPBRMaterial:p,modelOptions:r.modelOptions,vertexCount:c});return d.bounds=[e.attributes.POSITION.min,e.attributes.POSITION.max],d}(n,o,r,e,t))),r=new _({id:e.name||e.id,children:o});e._mesh=r}return e._mesh}(n,e.mesh,r));const l=new _({id:e.name||e.id,children:i});if(e.matrix)l.setMatrix(e.matrix);else{if(l.matrix.identity(),e.translation&&l.matrix.translate(e.translation),e.rotation){const n=(new o).fromQuaternion(e.rotation);l.matrix.multiplyRight(n)}e.scale&&l.matrix.scale(e.scale)}e._node=l}return t.find((n=>n.id===e.id))._node=e._node,e._node}function y(n,e,t){const o={};for(const[n,t]of Object.entries(e.attributes)){const{components:e,size:r,value:i}=t;o[n]={size:r??e,value:i}}return new l({id:n,topology:t,indices:e.indices.value,attributes:o})}const T=new c;class B{animation;startTime=0;playing=!0;speed=1;constructor(n){this.animation=n.animation,this.animation.name||="unnamed",Object.assign(this,n)}setTime(n){if(!this.playing)return;const e=(n/1e3-this.startTime)*this.speed;this.animation.channels.forEach((({sampler:n,target:t,path:o})=>{(function(n,{input:e,interpolation:t,output:o},r,i){const s=n%e[e.length-1],l=e.findIndex((n=>n>=s)),c=Math.max(0,l-1);if(!Array.isArray(r[i]))switch(i){case"translation":r[i]=[0,0,0];break;case"rotation":r[i]=[0,0,0,1];break;case"scale":r[i]=[1,1,1];break;default:a.warn(`Bad animation path ${i}`)()}const f=e[c],p=e[l];switch(t){case"STEP":!function(n,e,t){if(!n[e])throw new Error;for(let o=0;o<t.length;o++)n[e][o]=t[o]}(r,i,o[c]);break;case"LINEAR":p>f&&function(n,e,t,o,r){if(!n[e])throw new Error;if("rotation"===e){T.slerp({start:t,target:o,ratio:r});for(let t=0;t<T.length;t++)n[e][t]=T[t]}else for(let i=0;i<t.length;i++)n[e][i]=r*o[i]+(1-r)*t[i]}(r,i,o[c],o[l],(s-f)/(p-f));break;case"CUBICSPLINE":p>f&&function(n,e,{p0:t,outTangent0:o,inTangent1:r,p1:i,tDiff:a,ratio:s}){if(!n[e])throw new Error;for(let l=0;l<n[e].length;l++){const c=o[l]*a,f=r[l]*a;n[e][l]=(2*Math.pow(s,3)-3*Math.pow(s,2)+1)*t[l]+(Math.pow(s,3)-2*Math.pow(s,2)+s)*c+(-2*Math.pow(s,3)+3*Math.pow(s,2))*i[l]+(Math.pow(s,3)-Math.pow(s,2))*f}}(r,i,{p0:o[3*c+1],outTangent0:o[3*c+2],inTangent1:o[3*l+0],p1:o[3*l+1],tDiff:p-f,ratio:(s-f)/(p-f)});break;default:a.warn(`Interpolation ${t} not supported`)()}})(e,n,t,o),function(n,e){if(e.matrix.identity(),n.translation&&e.matrix.translate(n.translation),n.rotation){const t=H.fromQuaternion(n.rotation);e.matrix.multiplyRight(t)}n.scale&&e.matrix.scale(n.scale)}(t,t._node)}))}}class O{animations;constructor(n){this.animations=n.animations.map(((n,e)=>new B({animation:{name:n.name||`Animation-${e}`,channels:n.channels}})))}animate(n){a.warn("GLTFAnimator#animate is deprecated. Use GLTFAnimator#setTime instead")(),this.setTime(n)}setTime(n){this.animations.forEach((e=>e.setTime(n)))}getAnimations(){return this.animations}}const H=new o,w={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},G={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array};function F(n){if(!n._animation){const{typedArray:e,components:t}=function(n){const e=G[n.componentType],t=w[n.type],o=t*n.count,{buffer:r,byteOffset:i=0}=n.bufferView?.data??{};return{typedArray:new e(r,i+(n.byteOffset||0),o),components:t}}(n);if(1===t)n._animation=Array.from(e);else{const o=[];for(let n=0;n<e.length;n+=t)o.push(Array.from(e.slice(n,n+t)));n._animation=o}}return n._animation}function V(n){if(ArrayBuffer.isView(n)||n instanceof ArrayBuffer||n instanceof ImageBitmap)return n;if(Array.isArray(n))return n.map(V);if(n&&"object"==typeof n){const e={};for(const t in n)e[t]=V(n[t]);return e}return n}const U="uniform scenegraphUniforms {\n float sizeScale;\n float sizeMinPixels;\n float sizeMaxPixels;\n mat4 sceneModelMatrix;\n bool composeModelMatrix;\n} scenegraph;\n",D={name:"scenegraph",vs:U,fs:U,uniformTypes:{sizeScale:"f32",sizeMinPixels:"f32",sizeMaxPixels:"f32",sceneModelMatrix:"mat4x4<f32>",composeModelMatrix:"f32"}},z=[255,255,255,255],j={scenegraph:{type:"object",value:null,async:!0},getScene:n=>n&&n.scenes?"object"==typeof n.scene?n.scene:n.scenes[n.scene||0]:n,getAnimator:n=>n&&n.animator,_animations:null,sizeScale:{type:"number",value:1,min:0},sizeMinPixels:{type:"number",min:0,value:0},sizeMaxPixels:{type:"number",min:0,value:Number.MAX_SAFE_INTEGER},getPosition:{type:"accessor",value:n=>n.position},getColor:{type:"accessor",value:z},_lighting:"flat",_imageBasedLightingEnvironment:void 0,getOrientation:{type:"accessor",value:[0,0,0]},getScale:{type:"accessor",value:[1,1,1]},getTranslation:{type:"accessor",value:[0,0,0]},getTransformMatrix:{type:"accessor",value:[]},loaders:[e]};class q extends f{getShaders(){const n={};let e;return"pbr"===this.props._lighting?(e=h,n.LIGHTING_PBR=1):e={name:"pbrMaterial"},super.getShaders({defines:n,vs:"#version 300 es\n#define SHADER_NAME scenegraph-layer-vertex-shader\nin vec3 instancePositions;\nin vec3 instancePositions64Low;\nin vec4 instanceColors;\nin vec3 instancePickingColors;\nin vec3 instanceModelMatrixCol0;\nin vec3 instanceModelMatrixCol1;\nin vec3 instanceModelMatrixCol2;\nin vec3 instanceTranslation;\nin vec3 positions;\n#ifdef HAS_UV\nin vec2 texCoords;\n#endif\n#ifdef LIGHTING_PBR\n#ifdef HAS_NORMALS\nin vec3 normals;\n#endif\n#endif\nout vec4 vColor;\n#ifndef LIGHTING_PBR\n#ifdef HAS_UV\nout vec2 vTEXCOORD_0;\n#endif\n#endif\nvoid main(void) {\n#if defined(HAS_UV) && !defined(LIGHTING_PBR)\nvTEXCOORD_0 = texCoords;\ngeometry.uv = texCoords;\n#endif\ngeometry.worldPosition = instancePositions;\ngeometry.pickingColor = instancePickingColors;\nmat3 instanceModelMatrix = mat3(instanceModelMatrixCol0, instanceModelMatrixCol1, instanceModelMatrixCol2);\nvec3 normal = vec3(0.0, 0.0, 1.0);\n#ifdef LIGHTING_PBR\n#ifdef HAS_NORMALS\nnormal = instanceModelMatrix * (scenegraph.sceneModelMatrix * vec4(normals, 0.0)).xyz;\n#endif\n#endif\nfloat originalSize = project_size_to_pixel(scenegraph.sizeScale);\nfloat clampedSize = clamp(originalSize, scenegraph.sizeMinPixels, scenegraph.sizeMaxPixels);\nvec3 pos = (instanceModelMatrix * (scenegraph.sceneModelMatrix * vec4(positions, 1.0)).xyz) * scenegraph.sizeScale * (clampedSize / originalSize) + instanceTranslation;\nif(scenegraph.composeModelMatrix) {\nDECKGL_FILTER_SIZE(pos, geometry);\ngeometry.normal = project_normal(normal);\ngeometry.worldPosition += pos;\ngl_Position = project_position_to_clipspace(pos + instancePositions, instancePositions64Low, vec3(0.0), geometry.position);\n}\nelse {\npos = project_size(pos);\nDECKGL_FILTER_SIZE(pos, geometry);\ngl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, pos, geometry.position);\ngeometry.normal = project_normal(normal);\n}\nDECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n#ifdef LIGHTING_PBR\npbr_vPosition = geometry.position.xyz;\n#ifdef HAS_NORMALS\npbr_vNormal = geometry.normal;\n#endif\n#ifdef HAS_UV\npbr_vUV = texCoords;\n#else\npbr_vUV = vec2(0., 0.);\n#endif\ngeometry.uv = pbr_vUV;\n#endif\nvColor = instanceColors;\nDECKGL_FILTER_COLOR(vColor, geometry);\n}\n",fs:"#version 300 es\n#define SHADER_NAME scenegraph-layer-fragment-shader\nin vec4 vColor;\nout vec4 fragColor;\n#ifndef LIGHTING_PBR\n#if defined(HAS_UV) && defined(HAS_BASECOLORMAP)\nin vec2 vTEXCOORD_0;\nuniform sampler2D pbr_baseColorSampler;\n#endif\n#endif\nvoid main(void) {\n#ifdef LIGHTING_PBR\nfragColor = vColor * pbr_filterColor(vec4(0));\ngeometry.uv = pbr_vUV;\n#else\n#if defined(HAS_UV) && defined(HAS_BASECOLORMAP)\nfragColor = vColor * texture(pbr_baseColorSampler, vTEXCOORD_0);\ngeometry.uv = vTEXCOORD_0;\n#else\nfragColor = vColor;\n#endif\n#endif\nfragColor.a *= layer.opacity;\nDECKGL_FILTER_COLOR(fragColor, geometry);\n}\n",modules:[p,d,D,e]})}initializeState(){this.getAttributeManager().addInstanced({instancePositions:{size:3,type:"float64",fp64:this.use64bitPositions(),accessor:"getPosition",transition:!0},instanceColors:{type:"unorm8",size:this.props.colorFormat.length,accessor:"getColor",defaultValue:z,transition:!0},instanceModelMatrix:u})}updateState(n){super.updateState(n);const{props:e,oldProps:t}=n;e.scenegraph!==t.scenegraph?this._updateScenegraph():e._animations!==t._animations&&this._applyAnimationsProp(this.state.animator,e._animations)}finalizeState(n){super.finalizeState(n),this.state.scenegraph?.destroy()}get isLoaded(){return Boolean(this.state?.scenegraph&&super.isLoaded)}_updateScenegraph(){const e=this.props,{device:t}=this.context;let o=null;if(e.scenegraph instanceof v)o={scenes:[e.scenegraph]};else if(e.scenegraph&&"object"==typeof e.scenegraph){const r=e.scenegraph,i=r.json?n(r):r,a=function(n,e,t){const o=x(n,e=V(e),t),r=function(n){return(n.animations||[]).map(((e,t)=>{const o=e.name||`Animation-${t}`,r=e.samplers.map((({input:e,interpolation:t="LINEAR",output:o})=>({input:F(n.accessors[e]),interpolation:t,output:F(n.accessors[o])})));return{name:o,channels:e.channels.map((({sampler:e,target:t})=>({sampler:r[e],target:n.nodes[t.node??0],path:t.path})))}}))}(e);return{scenes:o,animator:new O({animations:r})}}(t,i,this._getModelOptions());o={gltf:i,...a},async function(n){const e=[];return n.scenes.forEach((n=>{n.traverse((()=>{}))})),await async function(){for(;e.some((n=>!n.loaded));)await new Promise((n=>requestAnimationFrame(n)))}()}(a).then((()=>{this.setNeedsRedraw()})).catch((n=>{this.raiseError(n,"loading glTF")}))}const r={layer:this,device:this.context.device},i=e.getScene(o,r),a=e.getAnimator(o,r);if(i instanceof _){this.state.scenegraph?.destroy(),this._applyAnimationsProp(a,e._animations);const n=[];i.traverse((e=>{e instanceof S&&n.push(e.model)})),this.setState({scenegraph:i,animator:a,models:n}),this.getAttributeManager().invalidateAll()}else null!==i&&m.warn("invalid scenegraph:",i)()}_applyAnimationsProp(n,e){if(!n||!e)return;const t=n.getAnimations();Object.keys(e).sort().forEach((n=>{const o=e[n];if("*"===n)t.forEach((n=>{Object.assign(n,o)}));else if(Number.isFinite(Number(n))){const e=Number(n);e>=0&&e<t.length?Object.assign(t[e],o):m.warn(`animation ${n} not found`)()}else{const e=t.find((({animation:e})=>e.name===n));e?Object.assign(e,o):m.warn(`animation ${n} not found`)()}}))}_getModelOptions(){const{_imageBasedLightingEnvironment:n}=this.props;let e;return n&&(e="function"==typeof n?n({gl:this.context.gl,layer:this}):n),{imageBasedLightingEnvironment:e,modelOptions:{id:this.props.id,isInstanced:!0,bufferLayout:this.getAttributeManager().getBufferLayouts(),...this.getShaders()},useTangents:!1}}draw({context:n}){if(!this.state.scenegraph)return;this.props._animations&&this.state.animator&&(this.state.animator.animate(n.timeline.getTime()),this.setNeedsRedraw());const{viewport:e,renderPass:t}=this.context,{sizeScale:o,sizeMinPixels:r,sizeMaxPixels:i,coordinateSystem:a}=this.props,s={camera:e.cameraPosition},l=this.getNumInstances();this.state.scenegraph.traverse(((n,{worldMatrix:c})=>{if(n instanceof S){const{model:f}=n;f.setInstanceCount(l);const p={sizeScale:o,sizeMinPixels:r,sizeMaxPixels:i,composeModelMatrix:b(e,a),sceneModelMatrix:c};f.shaderInputs.setProps({pbrProjection:s,scenegraph:p}),f.draw(t)}}))}}q.defaultProps=j,q.layerName="ScenegraphLayer";export{q as S,L as a,h as p}
@@ -0,0 +1 @@
1
+ import{V as t}from"./p-CrV_misM.js";import{w as i,l as s}from"./p-QJHuuz0g.js";class e{el;static RUNTIME_ERROR_DEBOUNCE_MS=5e3;layerId=null;mapProvider=null;_error;host;initContext;listenersBound=!1;recreateInFlight=!1;lastRuntimeErrorTime=0;constructor(t,i){this.el=t,this.host=i}startLoading(){this.host?.setLoadState("loading")}markReady(){this.clearError(),this.host?.setLoadState("ready")}markUpdated(){this.markReady()}setError(s){this._error=s,this.host?.setLoadState("error"),this.el.dispatchEvent(new CustomEvent(t.Error,{detail:s,bubbles:!0,composed:!0})),i(`${this.el.nodeName.toLowerCase()} - ${s.message}`)}setRuntimeError(t){const i=Date.now();i-this.lastRuntimeErrorTime<e.RUNTIME_ERROR_DEBOUNCE_MS||(this.lastRuntimeErrorTime=i,this.setError(t))}clearError(){this._error=void 0,this.lastRuntimeErrorTime=0}getError(){return this._error}async addLayer(t,s,e,a,r){return this.mapProvider?t?await(this.mapProvider?.addBaseLayer({...a,groupId:s,groupVisible:e},t,r)):await(this.mapProvider?.addLayerToGroup({...a,groupId:s,groupVisible:e})):(i("Map provider not available."),null)}async addToMapInternal(t,i,e,a){if(this.layerId&&(this.unregisterLayerError(),await(this.mapProvider?.removeLayer(this.layerId)),this.layerId=null),!0===await(i.isMapProviderReady?.())){s(`${this.el.nodeName.toLowerCase()} - layer is being added`),this.mapProvider=i.__vMapProvider??null;const r=await t.getGroupId(),h=await t.visible;if(null===this.layerId&&this.mapProvider)try{this.layerId=await this.addLayer(t.basemapid,r,h,e(),a),this.layerId?(this.registerLayerError(),this.markReady()):this.setError({type:"provider",message:"Layer could not be added: provider returned no layer ID"})}catch(t){this.setError({type:"provider",message:`Layer could not be added: ${t instanceof Error?t.message:String(t)}`,cause:t})}}}bindMapEventsOnce(){if(this.listenersBound||!this.initContext)return;const{vmap:i}=this.initContext;i.addEventListener(t.MapProviderReady,this.onMapProviderReady),i.addEventListener(t.MapProviderWillShutdown,this.onMapProviderWillShutdown),this.listenersBound=!0}onMapProviderReady=async t=>{if(s(`${this.el.nodeName.toLowerCase()} - layer add deferred`),this.mapProvider=t.detail.mapProvider,!this.layerId&&this.initContext){this.startLoading();const{group:t,vmap:i,createLayerConfig:s,elementId:e}=this.initContext;await this.addToMapInternal(t,i,s,e)}};onMapProviderWillShutdown=async()=>{s(`${this.el.nodeName.toLowerCase()} - map provider shutting down`),this.mapProvider=null,this.layerId=null,this.clearError(),this.host?.setLoadState("idle")};async setVisible(t){if(this.layerId&&this.mapProvider)try{await this.mapProvider.setVisible(this.layerId,t)}catch(t){this.setError({type:"provider",message:`setVisible failed: ${t instanceof Error?t.message:String(t)}`,cause:t})}}async setOpacity(t){if(this.layerId&&this.mapProvider)try{await this.mapProvider.setOpacity(this.layerId,t)}catch(t){this.setError({type:"provider",message:`setOpacity failed: ${t instanceof Error?t.message:String(t)}`,cause:t})}}async setZIndex(t){if(this.layerId&&this.mapProvider)try{await this.mapProvider.setZIndex(this.layerId,t)}catch(t){this.setError({type:"provider",message:`setZIndex failed: ${t instanceof Error?t.message:String(t)}`,cause:t})}}async updateLayer(t){if(this.layerId&&this.mapProvider)try{await this.mapProvider.updateLayer(this.layerId,t),this.markUpdated()}catch(t){this.setError({type:"provider",message:`updateLayer failed: ${t instanceof Error?t.message:String(t)}`,cause:t})}else await this.recreateLayer()}async recreateLayer(){if(!this.initContext||this.recreateInFlight)return;this.recreateInFlight=!0,this.startLoading();const{group:t,vmap:i,createLayerConfig:s,elementId:e}=this.initContext;try{await this.addToMapInternal(t,i,s,e)}finally{this.recreateInFlight=!1}}async initLayer(t,s){const e=this.el.closest("v-map-layergroup");if(!e)return void i(`${this.el.nodeName.toLowerCase()} is not inside a v-map-layergroup`);const a=await this.getVMap();a?(this.initContext={group:e,vmap:a,createLayerConfig:t,elementId:s},this.bindMapEventsOnce(),await this.addToMapInternal(e,a,t,s)):i(`No parent v-map component found for ${this.el.nodeName.toLowerCase()}`)}async dispose(){if(this.initContext&&this.listenersBound){const{vmap:i}=this.initContext;i.removeEventListener(t.MapProviderReady,this.onMapProviderReady),i.removeEventListener(t.MapProviderWillShutdown,this.onMapProviderWillShutdown)}this.listenersBound=!1,await this.removeLayer(),this.clearError(),this.host?.setLoadState("idle")}getMapProvider(){return this.mapProvider}getLayerId(){return this.layerId}async removeLayer(){this.unregisterLayerError(),await(this.mapProvider?.removeLayer(this.layerId)),this.layerId=null}registerLayerError(){this.layerId&&this.mapProvider?.onLayerError&&this.mapProvider.onLayerError(this.layerId,(t=>{this.setRuntimeError({type:t.type,message:t.message,cause:t.cause})}))}unregisterLayerError(){this.layerId&&this.mapProvider?.offLayerError&&this.mapProvider.offLayerError(this.layerId)}async getVMap(){s(`${this.el.nodeName.toLowerCase()} - getVMap`);const t=this.el.closest("v-map");if(!t)return s(`${this.el.nodeName.toLowerCase()} - getVMap - v-map not found.`),null;await customElements.whenDefined("v-map");const i=t;return s(`${this.el.nodeName.toLowerCase()} - getVMap - assigned.`),i}}export{e as V}
@@ -1 +1 @@
1
- import{d as t}from"./p-MyTSFnEk.js";class e{static get componentName(){return Object.prototype.hasOwnProperty.call(this,"extensionName")?this.extensionName:""}constructor(t){t&&(this.opts=t)}equals(e){return this===e||this.constructor===e.constructor&&t(this.opts,e.opts,1)}getShaders(t){return null}getSubLayerProps(t){const{defaultProps:e}=t.constructor,s={updateTriggers:{}};for(const t in e)if(t in this.props){const i=e[t],r=this.props[t];s[t]=r,i&&"accessor"===i.type&&(s.updateTriggers[t]=this.props.updateTriggers[t],"function"==typeof r&&(s[t]=this.getSubLayerAccessor(r)))}return s}initializeState(t,e){}updateState(t,e){}onNeedsRedraw(t){}getNeedsPickingBuffer(t){return!1}draw(t,e){}finalizeState(t,e){}}e.defaultProps={},e.extensionName="LayerExtension";export{e as L}
1
+ import{d as t}from"./p-9Rt23jlQ.js";class e{static get componentName(){return Object.prototype.hasOwnProperty.call(this,"extensionName")?this.extensionName:""}constructor(t){t&&(this.opts=t)}equals(e){return this===e||this.constructor===e.constructor&&t(this.opts,e.opts,1)}getShaders(t){return null}getSubLayerProps(t){const{defaultProps:e}=t.constructor,s={updateTriggers:{}};for(const t in e)if(t in this.props){const i=e[t],r=this.props[t];s[t]=r,i&&"accessor"===i.type&&(s.updateTriggers[t]=this.props.updateTriggers[t],"function"==typeof r&&(s[t]=this.getSubLayerAccessor(r)))}return s}initializeState(t,e){}updateState(t,e){}onNeedsRedraw(t){}getNeedsPickingBuffer(t){return!1}draw(t,e){}finalizeState(t,e){}}e.defaultProps={},e.extensionName="LayerExtension";export{e as L}
@@ -0,0 +1 @@
1
+ import{w as t,l as e,e as i}from"./p-QJHuuz0g.js";import{C as s}from"./p-2-mR3oVa.js";import{l as r,a,b as n,G as o,g as h}from"./p-yXLNXXx-.js";import"./p-BoNyIrdq.js";import"./p-CrV_misM.js";import"./p-DVBtCUtQ.js";class c{id;_visible=!0;_basemap=null;_layers=new Map;_originalVisible=new Map;_dirty=!0;constructor(t,e=!0){this.id=t,this._visible=e}get visible(){return this._visible}set visible(t){this._visible!==t&&(this._visible=t,this._dirty=!0)}get basemap(){return this._basemap}set basemap(t){this._basemap!==t&&(this._basemap=t,this._dirty=!0)}isDirty(){return this._dirty}addLayer(t){this._layers.has(t.id)||(this._layers.set(t.id,t),this._originalVisible.set(t.id,t.layer.getVisible()),this._dirty=!0)}setLayerElementId(t,e){const i=this._layers.get(t);i&&i.elementId!==e&&(i.elementId=e??null,this._dirty=!0)}removeLayer(t){const e=this._layers.delete(t);return this._originalVisible.delete(t),e&&(this._dirty=!0),e}clear(){this._layers.clear(),this._originalVisible.clear(),this._dirty=!0}apply(){if(this._dirty){for(const[t,e]of this._layers){const i=this._originalVisible.get(t)??!0;let s=this._visible&&i;s&&this._basemap&&(s=e.elementId===this._basemap),e.layer.getVisible()!==s&&e.layer.setVisible(s)}this._dirty=!1}}}class l{_groups=[];_dirty=!0;get groups(){return[...this._groups]}getGroup(t){return this._groups.find((e=>e.id===t))}hasGroup(t){return this._groups.some((e=>e.id===t))}ensureGroup(t,e=!0){let i=this.getGroup(t);return i||(i=new c(t,e),this._groups.push(i),this._dirty=!0,i)}addLayerToGroup(t,e,i){this.ensureGroup(t,e).addLayer(i),this._dirty=!0}removeLayer(t,e=!0){let i=!1;for(const s of this._groups)if(s.removeLayer(t)&&(i=!0,!e))break;return i&&(this._dirty=!0),i}setGroupVisible(t,e){const i=this.getGroup(t);if(!i)throw new Error(`CesiumLayerGroup "${t}" nicht gefunden`);i.visible=e,this._dirty=!0}setBasemap(t,e){const i=this.getGroup(t);if(!i)throw new Error(`CesiumLayerGroup "${t}" nicht gefunden`);i.basemap=e,this._dirty=!0}apply(){if(this._dirty||this._groups.some((t=>t.isDirty()))){for(const t of this._groups)t.apply();this._dirty=!1}}clear(){this._groups=[],this._dirty=!0}}class u{Cesium;layers=new Map;viewer;constructor(t,e){this.viewer=e,this.Cesium=t}replaceLayer(t,e,i){if(!this.Cesium)throw new Error("Cesium must be initialized first. Call init() method.");const s=e.getZIndex(),r=e.getVisible(),a=e.getOpacity();this.removeLayer(t);const n=this.addLayer(t,i);return n.setZIndex(s),n.setVisible(r),n.setOpacity(a),n}addLayer(t,e){if(!this.Cesium)throw new Error("Cesium must be initialized first. Call init() method.");e instanceof this.Cesium.GeoJsonDataSource||e instanceof this.Cesium.DataSource?this.viewer.dataSources.add(e):e instanceof this.Cesium.Cesium3DTileset?(this.viewer.scene.primitives.add(e),e.style||(e.style=new this.Cesium.Cesium3DTileStyle)):e instanceof this.Cesium.ImageryLayer&&this.viewer.imageryLayers.add(e),e.id=t;const i=this.wrapLayer(e);return this.layers.set(t,i),i}addCustomLayer(t,e){return this.layers.set(t,e),e}getLayer(t){const e=this.layers.get(t);if(!e)throw new Error(`Layer mit ID "${t}" nicht gefunden.`);return e}getLayerById(t){return this.getLayer(t)}removeLayer(t){this.getLayer(t).remove(),this.layers.delete(t)}setVisible(t,e){this.getLayer(t).setVisible(e)}setOpacity(t,e){this.getLayer(t).setOpacity(e)}async setZIndex(t,e){const i=this.getLayer(t);await i.setZIndex(e)}wrapLayer(t){return t instanceof this.Cesium.ImageryLayer?this.wrapImageryLayer(t):t instanceof this.Cesium.Cesium3DTileset?this.wrapTilesetLayer(t):this.wrapDataSourceLayer(t)}async sortImageryLayers(t,e,i){const s=this.sort(t,e,i);t.removeAll(!1),s.forEach((e=>t.add(e)))}async sort3DTileSets(t,e,i){const s=this.sort(t,e,i);t.removeAll(),s.forEach((e=>t.add(e)))}async sortDataSources(t,e,i){const s=this.sort(t,e,i);t.removeAll(!1),s.forEach((async e=>await t.add(e)))}sort(t,e,i){t.remove(e,!1);const s=[];for(let e=0;e<t.length;e++)s.push(t.get(e));return s.sort(((t,e)=>(t.zIndex||0)-(e.zIndex||0))),e.zIndex=i,s.push(e),s.sort(((t,e)=>(t.zIndex||0)-(e.zIndex||0))),s}wrapImageryLayer(t){const e=this.viewer.imageryLayers;let i={};return{getOptions:()=>i,setOptions(t){i=t},getVisible:()=>t.show,setVisible:e=>{t.show=e},getOpacity:()=>t.alpha,setOpacity:e=>{t.alpha=e},getZIndex:()=>{for(let i=0;i<e.length;i++)if(e.get(i)===t)return i;return-1},setZIndex:async i=>{void 0!==i&&await this.sortImageryLayers(e,t,i)},remove:()=>e.remove(t)}}wrapTilesetLayer(t){const e=this.viewer.scene.primitives;let i={};return{getOptions:()=>i,setOptions(t){i=t},getVisible:()=>t.show,setVisible:e=>{t.show=e},getOpacity:()=>{const e=t.style;if(e.color&&"string"==typeof e.color){const t=e.color.match(/color\(.*?,([\d.]+)\)/);return t?parseFloat(t[1]):1}return 1},setOpacity:e=>{const i=t.style.color;let s;if("string"==typeof i){const t=i.replace(/color\((.*?),[\d.]+\)/,`color($1, ${e})`);s=t.includes("color")?t:`color('white', ${e})`}else s=`color('white', ${e})`;t.style=new this.Cesium.Cesium3DTileStyle({color:s,colorBlendMode:this.Cesium.ColorBlendMode.MIX})},getZIndex:()=>{const e=this.viewer.scene.primitives;for(let i=0;i<e.length;i++)if(e.get(i)===t)return i;return-1},setZIndex:async i=>{void 0!==i&&this.sort3DTileSets(e,t,i)},setColor:(e,i=1)=>{const s=e instanceof this.Cesium.Color?e.toCssHexString():e.replace(/[#\s]/g,"");t.style=new this.Cesium.Cesium3DTileStyle({color:`color('${s}', ${i})`,colorBlendMode:this.Cesium.ColorBlendMode.MIX})},setStyle:e=>{t.style=e instanceof this.Cesium.Cesium3DTileStyle?e:new this.Cesium.Cesium3DTileStyle(e)},remove:()=>this.viewer.scene.primitives.remove(t)}}wrapDataSourceLayer(t){const e=this.viewer.dataSources;let i={};return{getOptions:()=>i,setOptions(t){i=t},getVisible:()=>t.show,setVisible:e=>{t.show=e},getOpacity:()=>1,setOpacity:e=>{t.__vmapLockOpacity||t.entities.values.forEach((t=>{const i=(t,i)=>{const{Color:s,JulianDate:r}=this.Cesium,a=t=>s.fromAlpha(t??i,e,new s);if(!t)return new this.Cesium.ConstantProperty(a(i));const n=t;if(n&&"function"==typeof n.getValue){const t=a(n.getValue(this.viewer?.clock?.currentTime??new r,new s));return"function"==typeof n.setValue?(n.setValue(t),n):new this.Cesium.ConstantProperty(t)}return new this.Cesium.ConstantProperty(a(t instanceof this.Cesium.Color?t:i))};if(t.polygon){const e=t.polygon.material;(e instanceof Cesium.ColorMaterialProperty||e instanceof Cesium.ImageMaterialProperty)&&(e.color=i(e.color,Cesium.Color.WHITE))}if(t.polyline){const e=t.polyline.material;(e instanceof Cesium.ColorMaterialProperty||e instanceof Cesium.PolylineOutlineMaterialProperty)&&(e.color=i(e.color,Cesium.Color.WHITE))}t.point&&(t.point.color=i(t.point.color,Cesium.Color.WHITE)),t.billboard&&(t.billboard.color=i(t.billboard.color,Cesium.Color.WHITE)),t.label&&(t.label.fillColor=i(t.label.fillColor,Cesium.Color.BLACK),t.label.outlineColor&&(t.label.outlineColor=i(t.label.outlineColor,Cesium.Color.BLACK))),t.model&&(t.model.color=i(t.model.color,Cesium.Color.WHITE))}))},getZIndex:()=>{for(let i=0;i<e.length;i++)if(e.get(i)===t)return i;return-1},setZIndex:async i=>{void 0!==i&&await this.sortDataSources(e,t,i)},remove:()=>e.remove(t)}}}class w{locked=!1;queue=[];async runExclusive(t){await this.acquire();try{return await t()}finally{this.release()}}acquire(){return this.locked?new Promise((t=>this.queue.push(t))):(this.locked=!0,Promise.resolve())}release(){const t=this.queue.shift();t?t():this.locked=!1}}function p(t,e){if(!t)throw new Error(e)}const m=new w;class d{tileWidth;tileHeight;tilingScheme;rectangle;errorEvent;credit=void 0;tileDiscardPolicy=void 0;proxy=void 0;hasAlphaChannel=!0;minimumLevel;maximumLevel;Cesium;tileProcessor;resolution;resampleMethod;colorStops;readyPromiseInternal;ready=!1;constructor(t){const{Cesium:e,rectangleDegrees:i,tileProcessor:s,tileSize:r,resolution:a,resampleMethod:n,colorStops:o,minimumLevel:h,maximumLevel:c}=t;this.Cesium=e,this.tileProcessor=s,this.tileWidth=r,this.tileHeight=r,this.resolution=a,this.resampleMethod=n,this.colorStops=o,this.minimumLevel=h??0,this.maximumLevel=c,this.rectangle=e.Rectangle.fromDegrees(i[0],i[1],i[2],i[3]),this.tilingScheme=new e.WebMercatorTilingScheme,this.errorEvent=new e.Event,this.ready=!0,this.readyPromiseInternal=Promise.resolve(!0)}get tilingSchemeName(){return this.tilingScheme instanceof this.Cesium.WebMercatorTilingScheme?"WebMercator":void 0}get readyPromise(){return this.readyPromiseInternal}get tileCredits(){}getTileCredits(t,e,i){}get url(){}flipCanvasVertically(e,i,s){const r=document.createElement("canvas");r.width=i,r.height=s;const a=r.getContext("2d");return a?(a.translate(0,s),a.scale(1,-1),a.drawImage(e,0,0),r):(t("v-map - cesium - failed to get 2d context for flip"),e)}async createFlippedImageBitmap(e,i){if("function"==typeof createImageBitmap)try{const t=document.createElement("canvas");t.width=i,t.height=i;const s=t.getContext("2d");if(!s)throw new Error("Failed to get 2d context");const r=s.createImageData(i,i);r.data.set(e),s.putImageData(r,0,0);const a=this.flipCanvasVertically(t,i,i);return await createImageBitmap(a)}catch(e){return void t("v-map - cesium - createImageBitmap failed, falling back",e)}}async createFlippedImageFromRGBA(e){const i=Math.ceil(this.tileWidth*this.resolution),s=await this.createFlippedImageBitmap(e,i);if(s)return s;const r=document.createElement("canvas");r.width=i,r.height=i;const a=r.getContext("2d");if(!a)return void t("v-map - cesium - unable to acquire canvas 2d context");const n=a.createImageData(i,i);return n.data.set(e),a.putImageData(n,0,0),this.flipCanvasVertically(r,i,i)}async requestImage(i,s,r){if(!this.ready)return;if(r<this.minimumLevel||void 0!==this.maximumLevel&&r>this.maximumLevel)return;const a={x:i,y:s,z:r,tileSize:this.tileWidth,resolution:this.resolution,resampleMethod:this.resampleMethod,colorStops:this.colorStops};let n=null;try{if(n=await this.tileProcessor.getTileData(a),!n)return void e(`v-map - cesium - geotiff - requestImage(${i},${s},${r}): no data returned`);e(`v-map - cesium - geotiff - requestImage(${i},${s},${r}): rgba ${n.length} bytes, sampleSize=${Math.ceil(this.tileWidth*this.resolution)}`)}catch(e){return this.errorEvent.raiseEvent(e),void t("v-map - cesium - getTileData - GeoTIFF tile request failed",e)}try{const t=await this.createFlippedImageFromRGBA(n);return e(`v-map - cesium - geotiff - requestImage(${i},${s},${r}): result=${t?.constructor?.name??"undefined"}, size=${t instanceof HTMLCanvasElement||t instanceof ImageBitmap?`${t.width}x${t.height}`:"n/a"}`),t}catch(e){return this.errorEvent.raiseEvent(e),void t("v-map - cesium - createFlippedImageFromRGBA - GeoTIFF tile request failed",e)}}pickFeatures(){}}const y="v-map - cesium - terrain-geotiff - ";class f{Cesium;image;fromProjection="EPSG:4326";sourceBounds=[0,0,0,0];wgs84Bounds=[0,0,0,0];width=0;height=0;noDataValue=0;ready=!1;_readyPromise;heightmapWidth=65;heightmapHeight=65;proj4;tilingScheme;constructor(t){this.Cesium=t.Cesium,this.tilingScheme=new this.Cesium.GeographicTilingScheme,this._readyPromise=this.initialize(t)}async initialize(t){try{e(`${y}loadGeoTIFF: url=${t.url}`);const[i,{default:s},a]=await Promise.all([import("./p-Be3r33VF.js").then((function(t){return t.g})),import("./p-RpJarvr_.js"),import("./p-CXfA_q8m.js").then((function(t){return t.m}))]),n=await r(t.url,{projection:t.projection,forceProjection:t.forceProjection??!1,nodata:t.nodata},{geotiff:i,proj4:s,geokeysToProj4:a});return this.image=n.baseImage,this.fromProjection=n.fromProjection,this.sourceBounds=n.sourceBounds,this.wgs84Bounds=n.wgs84Bounds,this.width=n.width,this.height=n.height,this.noDataValue=n.noDataValue??0,this.proj4=n.proj4,e(`${y}loaded: projection=${this.fromProjection}, bounds=[${this.sourceBounds.map((t=>t.toFixed(0))).join(",")}], wgs84=[${this.wgs84Bounds.map((t=>t.toFixed(4))).join(",")}], size=${this.width}x${this.height}`),this.ready=!0,!0}catch(t){return i(`${y}failed to load GeoTIFF:`,t),this.ready=!1,!1}}get rectangle(){if(!this.ready||!this.wgs84Bounds)return this.Cesium.Rectangle.MAX_VALUE;const[t,e,i,s]=this.wgs84Bounds;return this.Cesium.Rectangle.fromDegrees(t,e,i,s)}async requestTileGeometry(e,i,s){if(this.ready&&this.image)try{const r=this.tilingScheme.tileXYToRectangle(e,i,s);let a=this.Cesium.Math.toDegrees(r.west),n=this.Cesium.Math.toDegrees(r.south),o=this.Cesium.Math.toDegrees(r.east),h=this.Cesium.Math.toDegrees(r.north);const[c,l,u,w]=this.wgs84Bounds;if(o<c||a>u||h<l||n>w)return this.createFlatHeightmap();a=Math.max(c,Math.min(u,a)),o=Math.max(c,Math.min(u,o)),n=Math.max(l,Math.min(w,n)),h=Math.max(l,Math.min(w,h));const p=e=>{try{return this.proj4("EPSG:4326",this.fromProjection,e)}catch(i){return t(`${y}transform failed:`,i),e}},m=p([a,n]),d=p([o,h]),[f,g,v,b]=this.sourceBounds,S=this.width,C=this.height,$=v-f,L=b-g,G=Math.floor((m[0]-f)/$*S),M=Math.floor((b-d[1])/L*C),k=Math.ceil((d[0]-f)/$*S),x=Math.ceil((b-m[1])/L*C),F=Math.max(0,Math.min(G,S)),E=Math.max(0,Math.min(M,C)),I=Math.max(1,Math.min(k-G,S-F)),T=Math.max(1,Math.min(x-M,C-E)),O=(await this.image.readRasters({window:[F,E,F+I,E+T],width:this.heightmapWidth,height:this.heightmapHeight,resampleMethod:"bilinear"}))[0],A=new Float32Array(this.heightmapWidth*this.heightmapHeight);for(let t=0;t<A.length;t++){let e=O[t];e!==this.noDataValue&&isFinite(e)||(e=0),A[t]=e}return new this.Cesium.HeightmapTerrainData({buffer:A,width:this.heightmapWidth,height:this.heightmapHeight,childTileMask:0,structure:{heightScale:1,heightOffset:0,elementsPerHeight:1,stride:1,elementMultiplier:1}})}catch(e){return t(`${y}failed to load tile geometry:`,e),this.createFlatHeightmap()}}createFlatHeightmap(){const t=new Float32Array(this.heightmapWidth*this.heightmapHeight);return t.fill(0),new this.Cesium.HeightmapTerrainData({buffer:t,width:this.heightmapWidth,height:this.heightmapHeight,childTileMask:0})}get availability(){}getTilingScheme(){return this.tilingScheme}getLevelMaximumGeometricError(t){return this.tilingScheme.ellipsoid.maximumRadius/(65*Math.pow(2,t))}loadTileDataAvailability(t,e,i){}getTileDataAvailable(t,e,i){if(!this.ready)return!1;const s=this.tilingScheme.tileXYToRectangle(t,e,i),r=this.Cesium.Math.toDegrees(s.west),a=this.Cesium.Math.toDegrees(s.south),n=this.Cesium.Math.toDegrees(s.east),o=this.Cesium.Math.toDegrees(s.north),[h,c,l,u]=this.wgs84Bounds;return!(n<h||r>l||o<c||a>u)}get readyPromise(){return this._readyPromise}get credit(){return new this.Cesium.Credit("GeoTIFF Terrain")}get hasWaterMask(){return!1}get hasVertexNormals(){return!1}get errorEvent(){return new this.Cesium.Event}}const g="v-map - cesium - terrain-geotiff - ";class v{Cesium;viewer;provider;options;opacity=1;previousProvider;constructor(t,e,i,s){this.Cesium=t,this.viewer=e,this.provider=i,this.options=s??{},this.previousProvider=e.terrainProvider,this.viewer.terrainProvider=this.provider}getOptions(){return this.options}setOptions(t){this.options=t}getVisible(){return this.viewer.scene.globe.show}setVisible(t){this.viewer.scene.globe.show=t}getOpacity(){return this.opacity}setOpacity(e){this.opacity=e;const i=this.viewer.scene.globe;if(!i.translucency)try{i.translucency=new this.Cesium.GlobeTranslucency,i.translucency.enabled=!0}catch(e){return void t("Cesium terrain opacity not supported",e)}i.translucency.enabled=e<1,i.translucency.frontFaceAlpha=e}getZIndex(){return 0}async setZIndex(t){}remove(){try{this.viewer.terrainProvider=this.previousProvider?this.previousProvider:new this.Cesium.EllipsoidTerrainProvider,this.viewer.scene.globe.show=!0}catch(e){t("Cesium terrain reset failed",e)}}}class b{viewer;Cesium;layerManager;shadowRoot;layerGroups=new l;layerManagerMutex=new w;layerErrorCallbacks=new Map;layerErrorCleanups=new Map;async init(t){this.shadowRoot=t.shadowRoot;const e=t.target.getRootNode()instanceof ShadowRoot?t.target.getRootNode():void 0;await async function(t){const e=`https://cdn.jsdelivr.net/npm/cesium@${s.replace(/^[^\d]*/,"")}/Build/Cesium`,i=`${e}/Widgets/widgets.css`,r=(await(await fetch(i)).text()).replace(/url\((?!['"]?data:)(['"]?)([^'")]+)\1\)/g,((t,i,s)=>`url(${e}/Widgets/${s.replace(/^\.?\//,"")})`));if(t)if("adoptedStyleSheets"in Document.prototype){const e=new CSSStyleSheet;await e.replace(r),t.adoptedStyleSheets=[...t.adoptedStyleSheets??[],e]}else{const e=document.createElement("style");e.textContent=r,t.appendChild(e)}}(e),this.Cesium=await async function(t=s){const e=`https://cdn.jsdelivr.net/npm/cesium@${t.replace(/^[^\d]*/,"")}/Build/Cesium`,i=`${e}/Cesium.js`;await m.runExclusive((async()=>{globalThis.Cesium||await new Promise(((t,e)=>{const s="cesium-cdn-script";if(document.getElementById(s))return t();const r=document.createElement("script");r.id=s,r.async=!0,r.src=i,r.addEventListener("load",(()=>t()),{once:!0}),r.addEventListener("error",(()=>e(new Error(`Laden fehlgeschlagen: ${i}`))),{once:!0}),document.head.appendChild(r)}))}));const r=globalThis.Cesium;p(r,"globalThis.Cesium nicht verfügbar.");const a=r.VERSION;var n,o;return p((n=String(t),o=a,n.match(/^\d+\.\d+/)?.[0]===o.match(/^\d+\.\d+/)?.[0]),`Cesium-Version abweichend: erwartet ~${t}, geladen ${a}`),globalThis.CESIUM_BASE_URL=e,r}(),Cesium.Ion.defaultAccessToken=null,this.viewer=new this.Cesium.Viewer(t.target,{baseLayer:!1,baseLayerPicker:!1,terrainProvider:new Cesium.EllipsoidTerrainProvider}),this.viewer.scene.primitives.removeAll(),this.viewer.scene.backgroundColor=this.Cesium.Color.WHITE,this.viewer.scene.globe.baseColor=this.Cesium.Color.WHITE,this.viewer.scene.globe.depthTestAgainstTerrain=!1,this.layerManager=new u(this.Cesium,this.viewer)}async destroy(){!function(t){if(!t)return;const i=Array.from(t.querySelectorAll("style"));for(const t of i)if(t.textContent?.includes(".cesium-credit-lightbox-overlay")){t.remove(),e("v-map - provider - cesium - Cesium‑Widget‑CSS entfernt");break}}(this.shadowRoot),this.viewer?.destroy(),this.viewer=void 0}async createLayer(t,e){let i=null;switch(t.type){case"geojson":{const s={},r=t,a=await this.createGeoJSONLayer(r,s);i=this.layerManager.addLayer(e,a),i.setOptions(s);break}case"osm":{const s=await this.createOSMLayer(t);i=this.layerManager.addLayer(e,s);break}case"google":{const s=await this.createGoogleLayer(t);i=this.layerManager.addLayer(e,s);break}case"terrain":{const s=await this.createTerrainLayer(t);i=this.layerManager.addCustomLayer(e,s);break}case"xyz":{const s=await this.createXYZLayer(t);i=this.layerManager.addLayer(e,s);break}case"wms":{const s=await this.addWMSLayer(t);i=this.layerManager.addLayer(e,s);break}case"wcs":{const s=await this.createWCSLayer(t);i=this.layerManager.addLayer(e,s);break}case"arcgis":await this.addArcGISLayer(t);break;case"wfs":{const s={clampToGround:!0},r=t,a=await this.createWFSLayer(r,s);i=this.layerManager.addLayer(e,a),i.setOptions(s);break}case"wkt":{const s={clampToGround:!0},r=t,a=await this.createWKTLayer(r,s);i=this.layerManager.addLayer(e,a),i.setOptions(s);break}case"geotiff":{const s=await this.createGeoTIFFLayer(t);i=this.layerManager.addLayer(e,s);break}case"tile3d":{const s=await this.createTile3DLayer(t);i=this.layerManager.addLayer(e,s);const r=t;i.setOptions(r.tilesetOptions??{}),r.cesiumStyle&&"setStyle"in i&&i.setStyle(r.cesiumStyle);break}case"terrain-geotiff":{const s=await this.createGeoTIFFTerrainLayer(t);i=this.layerManager.addCustomLayer(e,s);break}default:throw new Error(`Unsupported layer type: ${t.type}`)}if(!i)return null;const s=t;return void 0!==s.zIndex&&await i.setZIndex(s.zIndex),void 0!==s.opacity&&i.setOpacity(s.opacity),void 0!==s.visible&&i.setVisible(s.visible),i}async addLayerToGroup(t){return await this.layerManagerMutex.runExclusive((async()=>{const e=crypto.randomUUID(),i=await this.createLayer(t,e);return this.layerGroups.addLayerToGroup(t.groupId,void 0===typeof t.groupVisible||t.groupVisible,{id:e,elementId:t.layerElementId??t.elementId??null,layer:i}),this.layerGroups.apply(),e}))}async setBaseLayer(t,e){await this.layerManagerMutex.runExclusive((async()=>{this.layerGroups.setBasemap(t,e??null),this.layerGroups.apply()}))}async addBaseLayer(t,e,i){return i&&e?await this.layerManagerMutex.runExclusive((async()=>{const s=crypto.randomUUID(),r=await this.createLayer(t,s);return this.layerGroups.addLayerToGroup(t.groupId,void 0===typeof t.groupVisible||t.groupVisible,{id:s,elementId:i,layer:r}),this.layerGroups.setBasemap(t.groupId??"basemap",e),this.layerGroups.apply(),s})):null}async ensureGroup(t,e,i){this.layerGroups.ensureGroup(t,e)}async setGroupVisible(t,e){this.layerGroups.setGroupVisible(t,e),this.layerGroups.apply()}onLayerError(t,e){this.layerErrorCallbacks.set(t,e),this.attachCesiumErrorListeners(t)}offLayerError(t){this.layerErrorCleanups.get(t)?.(),this.layerErrorCleanups.delete(t),this.layerErrorCallbacks.delete(t)}attachCesiumErrorListeners(t){this.layerErrorCleanups.get(t)?.();const e=this.layerErrorCallbacks.get(t);if(!e)return;const i=this.layerManager.getLayer(t);if(!i)return;const s=[],r=()=>{e({type:"network",message:"Tile load error"})},a=i._imageryLayer;if(a?.imageryProvider?.errorEvent){const t=a.imageryProvider.errorEvent.addEventListener(r);s.push(t)}const n=i._tileset;if(n?.tileFailed){const t=n.tileFailed.addEventListener(r);s.push(t)}s.length>0&&this.layerErrorCleanups.set(t,(()=>s.forEach((t=>t()))))}async removeLayer(t){t&&(this.offLayerError(t),await this.layerManagerMutex.runExclusive((async()=>{this.layerManager.removeLayer(t),this.layerGroups.removeLayer(t,!0),this.layerGroups.apply()})))}async setOpacity(t,e){this.layerManager.setOpacity(t,e),this.layerGroups.apply()}async setVisible(t,e){this.layerManager.setVisible(t,e),this.layerGroups.apply()}async setZIndex(t,e){await this.layerManager.setZIndex(t,e),this.layerGroups.apply()}applyGeostylerStyling(t,i){t.__vmapLockOpacity=!0;const s=(t,e)=>null==t||"object"==typeof t&&null!==t&&"name"in t?e:t,r=(t,e)=>{if(null==t)return e;if("number"==typeof t)return t;const i=Number(t);return Number.isFinite(i)?i:e},a=t.entities.values;if(i.rules)for(const t of i.rules)if(t.symbolizers)for(const i of t.symbolizers)for(let t=0;t<a.length;t++){const n=a[t];switch(i.kind){case"Fill":if(n.polygon){const t=s(i.color,"rgba(0,100,255,0.3)"),a=r(s(i.opacity,.3),.3),o=s(i.outlineColor,"rgba(0,100,255,1)"),h=s(i.outlineWidth,1);let c=this.parseCesiumColor(t,this.Cesium.Color.BLUE.withAlpha(.3));null!=a&&(c=this.applyCesiumOpacity(c,a));const l=this.parseCesiumColor(o,this.Cesium.Color.BLUE);e("v-map - provider - cesium - applyGeostylerStyling: Fill",{fillColor:t,fillOpacity:a,computedFill:c?.toString?.(),outlineColor:o,outlineWidth:h}),n.polygon.fill=new this.Cesium.ConstantProperty(!0),n.polygon.material=new this.Cesium.ColorMaterialProperty(c),n.polygon.outline=new this.Cesium.ConstantProperty(!0),n.polygon.outlineColor=new this.Cesium.ConstantProperty(l),n.polygon.outlineWidth=new this.Cesium.ConstantProperty(h),n.polygon.extrudedHeight=void 0,n.polygon.heightReference=new this.Cesium.ConstantProperty(this.Cesium.HeightReference.CLAMP_TO_GROUND),n.polygon.perPositionHeight=new this.Cesium.ConstantProperty(!1),n.polygon.classificationType=new this.Cesium.ConstantProperty(this.Cesium.ClassificationType.BOTH)}break;case"Line":if(n.polyline){const t=s(i.color,"rgba(0,100,255,1)"),a=r(s(i.width,2),2),o=r(s(i.opacity,1),1);let h=this.parseCesiumColor(t,this.Cesium.Color.BLUE);null!=o&&(h=this.applyCesiumOpacity(h,o)),e("v-map - provider - cesium - applyGeostylerStyling: Line",{lineColor:t,lineOpacity:o,computedColor:h?.toString?.(),lineWidth:a}),n.polyline.material=new this.Cesium.ColorMaterialProperty(h),n.polyline.width=new this.Cesium.ConstantProperty(a)}break;case"Mark":if(n.point){const t=s(i.color,"rgba(0,100,255,1)"),a=r(s(i.radius,6),6),o=r(s(i.opacity,1),1);let h=this.parseCesiumColor(t,this.Cesium.Color.BLUE);null!=o&&(h=this.applyCesiumOpacity(h,o)),e("v-map - provider - cesium - applyGeostylerStyling: Mark",{pointColor:t,pointOpacity:o,computedColor:h?.toString?.(),pointRadius:a}),n.point.color=new this.Cesium.ConstantProperty(h),n.point.pixelSize=new this.Cesium.ConstantProperty(a)}break;case"Icon":if(n.point){const t=s(i.image),a=r(s(i.size,32),32),o=r(s(i.opacity,1),1);t&&"string"==typeof t&&(n.billboard=new this.Cesium.BillboardGraphics({image:new this.Cesium.ConstantProperty(t),width:new this.Cesium.ConstantProperty(a),height:new this.Cesium.ConstantProperty(a),verticalOrigin:new this.Cesium.ConstantProperty(this.Cesium.VerticalOrigin.BOTTOM),color:null!=o?new this.Cesium.ConstantProperty(this.Cesium.Color.WHITE.withAlpha(o)):void 0}),n.point.show=new this.Cesium.ConstantProperty(!1),e("v-map - provider - cesium - applyGeostylerStyling: Icon",{iconSrc:t,iconSize:a,iconOpacity:o}))}break;case"Text":const t=i.label,a="string"==typeof t?t:void 0;if(a&&n.properties&&n.properties[a]){const t=s(i.color,"#000000"),o=r(s(i.size,12),12),h=r(s(i.opacity,1),1);let c=this.parseCesiumColor(t,this.Cesium.Color.WHITE);null!=h&&(c=this.applyCesiumOpacity(c,h)),e("v-map - provider - cesium - applyGeostylerStyling: Text",{labelProp:a,textColor:t,textOpacity:h,computedColor:c?.toString?.(),textSize:o});const l=n.properties[a]?.getValue?.(this.viewer.clock.currentTime)??n.properties[a]?._value??"";n.label=new this.Cesium.LabelGraphics({text:new this.Cesium.ConstantProperty(String(l)),font:new this.Cesium.ConstantProperty(`${o}px Arial`),fillColor:new this.Cesium.ConstantProperty(c),verticalOrigin:new this.Cesium.ConstantProperty(this.Cesium.VerticalOrigin.BOTTOM)})}}}}parseCesiumColor(t,e){if(!t)return e;if(t.startsWith("#"))return this.Cesium.Color.fromCssColorString(t);if(t.includes("rgb"))return this.Cesium.Color.fromCssColorString(t);try{return this.Cesium.Color.fromCssColorString(t)}catch{return e}}applyCesiumOpacity(t,e){return t?t.withAlpha(e):t}createCesiumStyle(t={}){const e=this.Cesium.Color.BLUE.withAlpha(.3),i=this.Cesium.Color.BLUE,s=this.Cesium.Color.BLUE,r=this.parseCesiumColor(t.fillColor,e),a=this.parseCesiumColor(t.strokeColor,i),n=this.parseCesiumColor(t.pointColor,s),o=void 0!==t.fillOpacity?this.applyCesiumOpacity(r,t.fillOpacity):r,h=void 0!==t.strokeOpacity?this.applyCesiumOpacity(a,t.strokeOpacity):a,c=void 0!==t.pointOpacity?this.applyCesiumOpacity(n,t.pointOpacity):n;return{fill:!0,fillColor:o,outline:!0,outlineColor:h,outlineWidth:t.strokeWidth??2,extrudedHeight:t.extrudeHeight,heightReference:t.zOffset?this.Cesium.HeightReference.RELATIVE_TO_GROUND:this.Cesium.HeightReference.CLAMP_TO_GROUND,pixelSize:t.pointRadius??8,color:c,scaleByDistance:t.pointRadius?new this.Cesium.NearFarScalar(150,2,15e6,.5):void 0,width:t.strokeWidth??2,clampToGround:!t.zOffset,labelText:t.textProperty,labelFont:t.textSize?`${t.textSize}pt monospace`:"12pt monospace",labelFillColor:t.textColor?this.parseCesiumColor(t.textColor,this.Cesium.Color.WHITE):this.Cesium.Color.WHITE,labelOutlineColor:t.textHaloColor?this.parseCesiumColor(t.textHaloColor,this.Cesium.Color.BLACK):this.Cesium.Color.BLACK,labelOutlineWidth:t.textHaloWidth??1,labelPixelOffset:t.textOffset?new this.Cesium.Cartesian2(t.textOffset[0],t.textOffset[1]):this.Cesium.Cartesian2.ZERO,height:t.zOffset??0}}applyEnhancedStyling(t,e={}){const i=this.createCesiumStyle(e),s=t.entities.values;for(let t=0;t<s.length;t++){const r=s[t];let a=i;if(e.styleFunction&&r.properties){const t={properties:r.properties._propertyNames.reduce(((t,e)=>(t[e]=r.properties[e]?._value,t)),{}),geometry:r},s=e.styleFunction(t);s&&(a={...i,...this.createCesiumStyle(s)})}if(r.polygon&&(r.polygon.fill=new this.Cesium.ConstantProperty(a.fill),r.polygon.material=new this.Cesium.ColorMaterialProperty(a.fillColor),r.polygon.outline=new this.Cesium.ConstantProperty(a.outline),r.polygon.outlineColor=new this.Cesium.ConstantProperty(a.outlineColor),r.polygon.outlineWidth=new this.Cesium.ConstantProperty(a.outlineWidth),r.polygon.height=void 0!==a.height?new this.Cesium.ConstantProperty(a.height):void 0,r.polygon.extrudedHeight=void 0!==a.extrudedHeight?new this.Cesium.ConstantProperty(a.extrudedHeight):void 0,r.polygon.heightReference=void 0!==a.heightReference?new this.Cesium.ConstantProperty(a.heightReference):void 0),r.polyline&&(r.polyline.material=new this.Cesium.ColorMaterialProperty(a.outlineColor),r.polyline.width=new this.Cesium.ConstantProperty(a.width),r.polyline.clampToGround=new this.Cesium.ConstantProperty(a.clampToGround)),r.point){r.point.pixelSize=new this.Cesium.ConstantProperty(a.pixelSize),r.point.color=new this.Cesium.ConstantProperty(a.color);const t=a.scaleByDistance;r.point.scaleByDistance=t?new this.Cesium.ConstantProperty(t):void 0,e.iconUrl&&(r.billboard=new this.Cesium.BillboardGraphics({image:new this.Cesium.ConstantProperty(e.iconUrl),width:new this.Cesium.ConstantProperty(e.iconSize?e.iconSize[0]:32),height:new this.Cesium.ConstantProperty(e.iconSize?e.iconSize[1]:32),verticalOrigin:new this.Cesium.ConstantProperty(this.Cesium.VerticalOrigin.BOTTOM),scaleByDistance:t?new this.Cesium.ConstantProperty(t):void 0}),r.point.show=new this.Cesium.ConstantProperty(!1))}if(e.textProperty&&r.properties&&r.properties[e.textProperty]){const t=r.properties[e.textProperty]?.getValue?.(this.viewer.clock.currentTime)??r.properties[e.textProperty]?._value??"";r.label=new this.Cesium.LabelGraphics({text:new this.Cesium.ConstantProperty(String(t)),font:new this.Cesium.ConstantProperty(a.labelFont),fillColor:new this.Cesium.ConstantProperty(a.labelFillColor),outlineColor:new this.Cesium.ConstantProperty(a.labelOutlineColor),outlineWidth:new this.Cesium.ConstantProperty(a.labelOutlineWidth),pixelOffset:new this.Cesium.ConstantProperty(a.labelPixelOffset),verticalOrigin:new this.Cesium.ConstantProperty(this.Cesium.VerticalOrigin.BOTTOM)})}}}async createWKTLayer(t,e){const i=await this.wktToGeoJSON(t),s=await this.Cesium.GeoJsonDataSource.load(i,e);return t.geostylerStyle?this.applyGeostylerStyling(s,t.geostylerStyle):t.style&&this.applyEnhancedStyling(s,t.style),s}async wktToGeoJSON(t){const e=await this.resolveWktText(t),i=await import("./p-DR9McdNX.js").then((function(t){return t.i})),s="function"==typeof i.default?i.default:i.parse;if("function"!=typeof s)throw new Error("wellknown parser not available");const r=s(e);if(!r)throw new Error("Failed to parse WKT");return{type:"FeatureCollection",features:[{type:"Feature",properties:{},geometry:r}]}}async resolveWktText(t){if(t.wkt)return t.wkt;if(t.url){const e=await fetch(t.url);if(!e.ok)throw new Error(`Failed to fetch WKT: ${e.status}`);return await e.text()}throw new Error("Either wkt or url must be provided")}async createGeoJSONLayer(t,e){let i=null;i=t.geojson?JSON.parse(t.geojson):t.url;const s=await this.Cesium.GeoJsonDataSource.load(i,e);return t.geostylerStyle?this.applyGeostylerStyling(s,t.geostylerStyle):t.style&&this.applyEnhancedStyling(s,t.style),s}async createWFSLayer(t,e){const i=await this.fetchWFSFromUrl(t),s=await this.Cesium.GeoJsonDataSource.load(i,e);return t.geostylerStyle?this.applyGeostylerStyling(s,t.geostylerStyle):t.style&&this.applyEnhancedStyling(s,t.style),s}async createOSMLayer(t){return new this.Cesium.ImageryLayer(new this.Cesium.OpenStreetMapImageryProvider({url:t.url||"https://a.tile.openstreetmap.org"}))}async createGoogleLayer(t){if(!t.apiKey)throw new Error("Google-Layer benötigt 'apiKey' (Google Maps Platform).");await this.loadGoogleMapsApi(t.apiKey,{language:t.language,region:t.region,libraries:t.libraries});const e=this.getGoogleMapTypeId(t.mapType||"roadmap"),i=this.Cesium,s=new i.UrlTemplateImageryProvider({url:"https://maps.googleapis.com/maps/api/staticmap?template",maximumLevel:t.maxZoom||19,minimumLevel:0,tilingScheme:new i.WebMercatorTilingScheme,credit:"Google Maps",urlSchemeZeroPadding:{"{x}":"","{y}":"","{z}":""}});return s.buildImageResource=function(s,r,a){const n=(new i.WebMercatorTilingScheme).tileXYToRectangle(s,r,a),o=i.Math.toDegrees(n.west),h=i.Math.toDegrees(n.south),c=i.Math.toDegrees(n.east),l=i.Math.toDegrees(n.north),u=new URLSearchParams({center:`${(h+l)/2},${(o+c)/2}`,zoom:a.toString(),size:"256x256",scale:"scaleFactor1x"===t.scale?"1":"2",maptype:e,key:t.apiKey,format:"png"});t.language&&u.set("language",t.language),t.region&&u.set("region",t.region);const w=`https://maps.googleapis.com/maps/api/staticmap?${u.toString()}`;return new i.Resource({url:w})},this.ensureGoogleLogo(),new this.Cesium.ImageryLayer(s,{alpha:t.opacity??1,show:t.visible??!0})}getGoogleMapTypeId(t){switch(t){case"roadmap":default:return"roadmap";case"satellite":return"satellite";case"terrain":return"terrain";case"hybrid":return"hybrid"}}async loadGoogleMapsApi(t,e){const i=window,s=i.__mockGoogleMapsApi;"function"!=typeof s?i.google?.maps||await new Promise(((s,r)=>{const a="___cesiumGoogleInit___"+Math.random().toString(36).slice(2);i[a]=()=>s();const n=document.createElement("script"),o=new URLSearchParams({key:t,callback:a,v:"weekly"});e?.language&&o.set("language",e.language),e?.region&&o.set("region",e.region),e?.libraries?.length&&o.set("libraries",e.libraries.join(",")),n.src=`https://maps.googleapis.com/maps/api/js?${o.toString()}`,n.async=!0,n.onerror=()=>r(new Error("Google Maps JS API failed to load")),document.head.appendChild(n)})):await s(t,e)}ensureGoogleLogo(){if(!this.viewer?.container||this.viewer.container._googleLogoAdded)return;const t=document.createElement("img");t.src="https://developers.google.com/static/maps/documentation/images/google_on_white.png",t.alt="Google",t.style.position="absolute",t.style.bottom="6px",t.style.left="6px",t.style.height="18px",t.style.pointerEvents="none",t.style.zIndex="1000",this.viewer.container.appendChild(t),this.viewer.container._googleLogoAdded=!0}async createXYZLayer(t){if(!t.url)throw new Error("XYZ layer requires a url");const e=Array.isArray(t.attributions)?t.attributions.join(", "):t.attributions,i={url:t.url,credit:e,maximumLevel:t.maxZoom,...t.options||{}},s=new this.Cesium.UrlTemplateImageryProvider(i);return new this.Cesium.ImageryLayer(s,{alpha:t.opacity??1,show:t.visible??!0})}async createTerrainLayer(t){let e;e=t.elevationData?await this.Cesium.CesiumTerrainProvider.fromUrl(t.elevationData):await this.Cesium.createWorldTerrainAsync();const i=new v(this.Cesium,this.viewer,e,t);return void 0!==t.visible&&i.setVisible(t.visible),void 0!==t.opacity&&i.setOpacity(t.opacity),i}async createGeoTIFFTerrainLayer(t){if(!t.url){e(`${g}layer created without URL, waiting for URL to load`);const i=new this.Cesium.EllipsoidTerrainProvider,s=new v(this.Cesium,this.viewer,i,t);return s.setVisible(!1),s}try{e(`${g}create layer: url=${t.url}`);const i=await async function(t){const e=new f(t);return await e.readyPromise,e}({url:t.url,projection:t.projection,forceProjection:t.forceProjection,nodata:t.nodata,Cesium:this.Cesium}),s=new v(this.Cesium,this.viewer,i,t);return void 0!==t.visible&&s.setVisible(t.visible),void 0!==t.opacity&&s.setOpacity(t.opacity),e(`${g}layer created successfully`),s}catch(e){i(`${g}failed to create terrain layer:`,e);const s=new this.Cesium.EllipsoidTerrainProvider;return new v(this.Cesium,this.viewer,s,t)}}async addWMSLayer(t){return new this.Cesium.ImageryLayer(new this.Cesium.WebMapServiceImageryProvider({url:t.url,layers:t.layers,parameters:t.extraParams}))}async createWCSLayer(t){if(!t.url||!t.coverageName)throw new Error("WCS layer requires url and coverageName");const e=t.version??"2.0.1",i=t.format??"image/tiff",s=t.projection??"EPSG:4326",r=t.tileSize??256,a=this.Cesium,n=new a.UrlTemplateImageryProvider({url:`${t.url}?wcs_placeholder`,maximumLevel:t.maxZoom??18,minimumLevel:t.minZoom??0,tileWidth:r,tileHeight:r,tilingScheme:new a.GeographicTilingScheme,credit:"WCS"});return n.buildImageResource=function(n,o,h){const c=(new a.GeographicTilingScheme).tileXYToRectangle(n,o,h),l=a.Math.toDegrees(c.west),u=a.Math.toDegrees(c.south),w=a.Math.toDegrees(c.east),p=a.Math.toDegrees(c.north),m={SERVICE:"WCS",REQUEST:"GetCoverage",VERSION:e,FORMAT:i};let d;if(e.startsWith("2.0")){const e={...m,coverageId:t.coverageName,...t.params||{}};(i.includes("tiff")||i.includes("geotiff"))&&(e["geotiff:compression"]="LZW");const s=new URLSearchParams;Object.entries(e).forEach((([t,e])=>{null!=e&&s.set(t,String(e))}));const r=s.toString(),a=`subset=X(${l},${w})`,n=`subset=Y(${u},${p})`;d=`${t.url}${t.url.includes("?")?"&":"?"}${r}&${a}&${n}`}else{const e={...m,COVERAGE:t.coverageName,BBOX:`${l},${u},${w},${p}`,CRS:s,WIDTH:String(r),HEIGHT:String(r),...t.params||{}},i=new URLSearchParams;Object.entries(e).forEach((([t,e])=>{null!=e&&i.set(t,String(e))})),d=`${t.url}${t.url.includes("?")?"&":"?"}${i.toString()}`}return new a.Resource({url:d})},new this.Cesium.ImageryLayer(n,{alpha:t.opacity??1,show:t.visible??!0})}async addArcGISLayer(t){const e=await this.Cesium.ArcGisMapServerImageryProvider.fromUrl(t.url);this.viewer.imageryLayers.addImageryProvider(e)}async createGeoTIFFLayer(t){if(!t.url)throw new Error("GeoTIFF layer requires a URL");try{const e=t,i=await a(t.url,e.projection,e.forceProjection,t.nodata),s=await n(i,"EPSG:3857"),r=new o(s);let c;if(r.createGlobalTriangulation(),t.colorMap){const{stops:e}=h(t.colorMap,t.valueRange);c=e}const l=new d({Cesium:this.Cesium,rectangleDegrees:i.wgs84Bounds,tileProcessor:r,tileSize:t.tileSize??256,resolution:t.resolution??1,resampleMethod:t.resampleMethod??"bilinear",colorStops:c}),u=new this.Cesium.ImageryLayer(l,{alpha:t.opacity??1,show:t.visible??!0});return u.__vmapGeoTIFFMeta={url:t.url,width:i.width,height:i.height,samplesPerPixel:i.samplesPerPixel,noData:i.noDataValue},u}catch(t){i("v-map - provider - cesium - Failed to create GeoTIFF layer",t);const e=new this.Cesium.SingleTileImageryProvider({url:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==",rectangle:this.Cesium.Rectangle.fromDegrees(-180,-90,180,90)});return new this.Cesium.ImageryLayer(e,{alpha:0,show:!1})}}async createTile3DLayer(t){if(!t.url)throw new Error("Tile3D layer requires a URL");const e=await this.Cesium.Cesium3DTileset.fromUrl(t.url,t.tilesetOptions??{});return t.cesiumStyle&&(e.style=new this.Cesium.Cesium3DTileStyle(t.cesiumStyle)),e}async updateLayer(t,e){return await this.layerManagerMutex.runExclusive((async()=>{const i=this.layerErrorCallbacks.has(t);i&&this.offLayerError(t);const s=this.layerManager.getLayer(t);switch(e.type){case"geojson":{const i=e.data,r=s.getOptions(),a=await this.createGeoJSONLayer({geojson:i.geojson,url:i.url,style:i.style,geostylerStyle:i.geostylerStyle},r);this.layerManager.replaceLayer(t,s,a).setOptions(r)}break;case"wfs":{const i=e.data,r=s.getOptions(),a=await this.createWFSLayer(i,r);this.layerManager.replaceLayer(t,s,a).setOptions(r)}break;case"osm":{const i=s.getOptions(),r=new this.Cesium.ImageryLayer(new this.Cesium.OpenStreetMapImageryProvider({url:e.data.url||"https://a.tile.openstreetmap.org"}));this.layerManager.replaceLayer(t,s,r).setOptions(i)}break;case"google":{const i=s.getOptions(),r=await this.createGoogleLayer(e.data);this.layerManager.replaceLayer(t,s,r).setOptions(i)}break;case"xyz":{const i=s.getOptions(),r=await this.createXYZLayer(e.data);this.layerManager.replaceLayer(t,s,r).setOptions(i)}break;case"wcs":{const i=s.getOptions(),r=await this.createWCSLayer(e.data);this.layerManager.replaceLayer(t,s,r).setOptions(i)}break;case"wkt":{const i=e.data,r=s.getOptions(),a=await this.createWKTLayer({wkt:i.wkt,url:i.url,style:i.style,geostylerStyle:i.geostylerStyle},r);this.layerManager.replaceLayer(t,s,a).setOptions(r)}break;case"geotiff":{const i=e.data,r=await this.createGeoTIFFLayer({url:i.url});this.layerManager.replaceLayer(t,s,r)}break;case"tile3d":{const i=e.data??{};if(!i.url)throw new Error("tile3d update requires a url");const r=await this.createTile3DLayer({type:"tile3d",url:i.url,tilesetOptions:i.tilesetOptions,cesiumStyle:i.cesiumStyle}),a=this.layerManager.replaceLayer(t,s,r);a.setOptions(i.tilesetOptions??{}),i.cesiumStyle&&"setStyle"in a&&a.setStyle(i.cesiumStyle)}break;case"tile3d-style":"setStyle"in s&&s.setStyle((e.data??{}).style??{});break;case"terrain":{const i=s.getOptions(),r=s.getVisible(),a=s.getOpacity();s.remove();const n=await this.createTerrainLayer({type:"terrain",...i,...e.data??{}}),o=this.layerManager.addCustomLayer(t,n);o.setVisible(r),o.setOpacity(a)}break;case"terrain-geotiff":{s.remove();const i=await this.createGeoTIFFTerrainLayer({type:"terrain-geotiff",...e.data??{}});this.layerManager.addCustomLayer(t,i)}}i&&this.attachCesiumErrorListeners(t)}))}async setView(i,s){if(!this.viewer)return;const[r,a]=i;this.viewer.camera.flyTo({destination:this.Cesium.Cartesian3.fromDegrees(r,a,1e6/s),duration:2,orientation:{heading:this.Cesium.Math.toRadians(0),pitch:this.Cesium.Math.toRadians(-30),roll:0},complete:()=>e("v-map - provider - cesium - Fly‑to finished"),cancel:()=>t("v-map - provider - cesium - Fly‑to cancelled")})}async fetchWFSFromUrl(t){const e={service:"WFS",request:"GetFeature",version:t.version??"1.1.0",typeName:t.typeName,outputFormat:t.outputFormat??"application/json",srsName:t.srsName??"EPSG:4326",...t.params??{}},i=this.appendParams(t.url,e),s=await fetch(i);if(!s.ok)throw new Error(`WFS request failed (${s.status} ${s.statusText})`);const r=(t.outputFormat??"application/json").toLowerCase();if(r.includes("json")||r.includes("geojson")||"application/json"===r){const t=s.headers.get("content-type");if(t?.includes("application/json"))return await s.json();const e=await s.text();return JSON.parse(e)}if(r.includes("gml")||r.includes("xml")){const t=await s.text(),{GmlParser:e}=await import("./p-DhQAXuA7.js"),i=new e;return await i.parse(t)}return await s.json()}appendParams(t,e){const i=new URLSearchParams;return Object.entries(e).forEach((([t,e])=>{null!=e&&i.set(t,String(e))})),i.toString()?`${t}${t.includes("?")?"&":"?"}${i.toString()}`:t}}export{b as CesiumProvider}
@@ -1 +1 @@
1
- const n=(()=>{try{return"undefined"!=typeof location&&new URLSearchParams(location.search).has("vmapDebug")}catch{return!1}})()||"undefined"!=typeof localStorage&&"1"===localStorage.getItem("@pt9912/v-map:exposeConsoleAPI"),o="@pt9912/v-map:logLevel";function e(){try{if("undefined"!=typeof window&&"localStorage"in window)return window.localStorage}catch{}return null}let r=function(){const n=e();if(!n)return null;const r=n.getItem(o);return!r||"none"!==r&&"error"!==r&&"warn"!==r&&"info"!==r&&"debug"!==r?null:r}()??"warn",a=new class{log(n,o,e){const r=e?`[${e}]`:void 0,a=[...o];if("debug"===n||"warn"===n||"error"===n){const o="debug"===n||"warn"===n||"error"===n?(new Error).stack?.split("\n")[4]?.trim():null;o&&a.push(`${o}`)}switch(n){case"debug":case"info":r?console.log(r,...a):console.log(...a);break;case"warn":r?console.warn(r,...a):console.warn(...a);break;case"error":r?console.error(r,...a):console.error(...a)}}};function t(n,o,e){(function(n){const o={none:0,error:1,warn:2,info:3,debug:4};return o[n]<=o[r]})(n)&&a.log(n,o,e)}const c=(...n)=>t("debug",n),l=(...n)=>t("warn",n),i=(...n)=>t("error",n);if(n&&"undefined"!=typeof globalThis){const n=globalThis;n.setLogLevel=function(n){r=n,function(n){const r=e();if(r)try{r.setItem(o,n)}catch{}}(n)},n.getLogLevel=function(){return r},n.log=(...n)=>c(...n),n.info=(...n)=>((...n)=>t("info",n))(...n),n.warn=(...n)=>l(...n),n.error=(...n)=>i(...n)}const s={Error:"vmap-error",MapProviderReady:"map-provider-ready",MapProviderWillShutdown:"map-provider-will-shutdown",MapMouseMove:"map-mousemove"},d={COMPONENT_CONNECTED_CALLBACK:"connectedCallback",COMPONENT_WILL_LOAD:"componentWillLoad",COMPONENT_WILL_RENDER:"componentWillRender",COMPONENT_RENDER:"render",COMPONENT_DID_RENDER:"componentDidRender",COMPONENT_DID_LOAD:"componentDidLoad",COMPONENT_DISCONNECTED_CALLBACK:"disconnectedCallback"};export{d as M,s as V,i as e,c as l,l as w}
1
+ const n=(()=>{try{return"undefined"!=typeof location&&new URLSearchParams(location.search).has("vmapDebug")}catch{return!1}})()||"undefined"!=typeof localStorage&&"1"===localStorage.getItem("@pt9912/v-map:exposeConsoleAPI"),o="@pt9912/v-map:logLevel";function e(){try{if("undefined"!=typeof window&&"localStorage"in window)return window.localStorage}catch{}return null}let r=function(){const n=e();if(!n)return null;const r=n.getItem(o);return!r||"none"!==r&&"error"!==r&&"warn"!==r&&"info"!==r&&"debug"!==r?null:r}()??"warn",c=new class{log(n,o,e){const r=e?`[${e}]`:void 0,c=[...o];if("debug"===n||"warn"===n||"error"===n){const o="debug"===n||"warn"===n||"error"===n?(new Error).stack?.split("\n")[4]?.trim():null;o&&c.push(`${o}`)}switch(n){case"debug":case"info":r?console.log(r,...c):console.log(...c);break;case"warn":r?console.warn(r,...c):console.warn(...c);break;case"error":r?console.error(r,...c):console.error(...c)}}};function t(n,o,e){(function(n){const o={none:0,error:1,warn:2,info:3,debug:4};return o[n]<=o[r]})(n)&&c.log(n,o,e)}const a=(...n)=>t("debug",n),l=(...n)=>t("warn",n),i=(...n)=>t("error",n);if(n&&"undefined"!=typeof globalThis){const n=globalThis;n.setLogLevel=function(n){r=n,function(n){const r=e();if(r)try{r.setItem(o,n)}catch{}}(n)},n.getLogLevel=function(){return r},n.log=(...n)=>a(...n),n.info=(...n)=>((...n)=>t("info",n))(...n),n.warn=(...n)=>l(...n),n.error=(...n)=>i(...n)}const s={COMPONENT_CONNECTED_CALLBACK:"connectedCallback",COMPONENT_WILL_LOAD:"componentWillLoad",COMPONENT_WILL_RENDER:"componentWillRender",COMPONENT_RENDER:"render",COMPONENT_DID_RENDER:"componentDidRender",COMPONENT_DID_LOAD:"componentDidLoad",COMPONENT_DISCONNECTED_CALLBACK:"disconnectedCallback"};export{s as M,i as e,a as l,l as w}