@mapvx/web-kit 1.2.0-develop.11 → 1.2.0-develop.13
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.
- package/dist/cjs/chunks/{DRACOLoader-CjN7nfMz.cjs → DRACOLoader-gEI4jG0V.cjs} +2 -2
- package/dist/cjs/chunks/{GLTFLoader-C33v_eKh.cjs → GLTFLoader-Cd9ix-wY.cjs} +2 -2
- package/dist/cjs/chunks/{KTX2Loader-GfgRciKI.cjs → KTX2Loader-Dk2GlCFI.cjs} +2 -2
- package/dist/cjs/chunks/{accessibility-CamvBQ8h.cjs → accessibility-C9U1mv_p.cjs} +2 -2
- package/dist/cjs/chunks/{back_arrow-BrByZltA.cjs → back_arrow-tpfWrGJ9.cjs} +2 -2
- package/dist/cjs/chunks/{debug-hooks-C_m1SbH2.cjs → debug-hooks-xLx1YP8n.cjs} +2 -2
- package/dist/cjs/chunks/{dist-B3zxScE2.cjs → dist-1oZjernx.cjs} +2 -2
- package/dist/cjs/chunks/{dist-DRfr3UXp.cjs → dist-CYGLkXos.cjs} +2 -2
- package/dist/cjs/chunks/{dist-CpCOzc73.cjs → dist-ENDZf7Zh.cjs} +2 -2
- package/dist/cjs/chunks/{expression-EUvjFYH4.cjs → expression-q70ZQCYv.cjs} +2 -2
- package/dist/cjs/chunks/{globe-viewport-SZrSWKdf.cjs → globe-viewport-CIe_h8dV.cjs} +2 -2
- package/dist/cjs/chunks/{icon-origin-point-DW7v7TzN.cjs → icon-origin-point-D_DBb1gM.cjs} +2 -2
- package/dist/cjs/chunks/{meshopt_decoder.module-Dk924uu3.cjs → meshopt_decoder.module-B5j8Tze_.cjs} +2 -2
- package/dist/cjs/chunks/{repeat_icon-Bpef1DPh.cjs → repeat_icon-F6Q7hnPl.cjs} +2 -2
- package/dist/cjs/chunks/{rolldown-runtime-1If4f64F.cjs → rolldown-runtime-BOxlEPsq.cjs} +2 -2
- package/dist/cjs/chunks/{shader-type-decoder-BqFbHaKB.cjs → shader-type-decoder-B16cQ7H3.cjs} +2 -2
- package/dist/cjs/chunks/{styles-DP9KZtXl.cjs → styles-zP5lXn9p.cjs} +2 -2
- package/dist/cjs/chunks/{three.module-Drz560ge.cjs → three.module-BHURJnCD.cjs} +2 -2
- package/dist/cjs/chunks/{walking-BfKvsH3Y.cjs → walking-CMpmZTw3.cjs} +2 -2
- package/dist/cjs/chunks/{webgl-CxZNw2p_.cjs → webgl-CJbVWdD9.cjs} +2 -2
- package/dist/cjs/chunks/{webgl-device-Dpif38ir.cjs → webgl-device-D7wKHxQy.cjs} +2 -2
- package/dist/cjs/web-kit.cjs +22 -22
- package/dist/es/chunks/{DRACOLoader-CudX8012.js → DRACOLoader-r8VXQ8hj.js} +2 -2
- package/dist/es/chunks/{GLTFLoader-BLc_n6C7.js → GLTFLoader-IbJ3eCNr.js} +2 -2
- package/dist/es/chunks/{KTX2Loader-CnBac9vX.js → KTX2Loader-DZlQyAGv.js} +2 -2
- package/dist/es/chunks/{accessibility-BTRW5qzF.js → accessibility-BldDqm74.js} +2 -2
- package/dist/es/chunks/{back_arrow-DaE2mYq8.js → back_arrow-BeeCYF4P.js} +2 -2
- package/dist/es/chunks/{debug-hooks-A7fGcVSJ.js → debug-hooks-NzJ2oy3C.js} +2 -2
- package/dist/es/chunks/{dist-B8bewEN3.js → dist-B3-nPsaF.js} +2 -2
- package/dist/es/chunks/{dist-Cq65fMeu.js → dist-DNNWa2bQ.js} +2 -2
- package/dist/es/chunks/{dist-CeI9yzhC.js → dist-DOcsJa1u.js} +2 -2
- package/dist/es/chunks/{expression-BFfy7ZSj.js → expression-Dpos4VqC.js} +2 -2
- package/dist/es/chunks/{globe-viewport-C_lLyBu9.js → globe-viewport-BmqhgdhG.js} +2 -2
- package/dist/es/chunks/{icon-origin-point-bHQmYXyG.js → icon-origin-point-CkHTMtFu.js} +2 -2
- package/dist/es/chunks/{meshopt_decoder.module-ClKO_vyv.js → meshopt_decoder.module-YGVnWwV0.js} +2 -2
- package/dist/es/chunks/{repeat_icon-BDjNCPIN.js → repeat_icon-B_t3ecTa.js} +2 -2
- package/dist/es/chunks/{rolldown-runtime-CGJB3Nua.js → rolldown-runtime-BSTMnvUK.js} +2 -2
- package/dist/es/chunks/{shader-type-decoder-DV9QwQh3.js → shader-type-decoder-CFX5sij5.js} +2 -2
- package/dist/es/chunks/{styles-BPMrJs_x.js → styles-DTTMB3rI.js} +2 -2
- package/dist/es/chunks/{three.module-DUnMDXpm.js → three.module-Cj5xe6gn.js} +2 -2
- package/dist/es/chunks/{walking-CUOW_o2S.js → walking--SMEsH_B.js} +2 -2
- package/dist/es/chunks/{webgl-B16MrmDy.js → webgl-ZcaUll7k.js} +2 -2
- package/dist/es/chunks/{webgl-device-Bht0bA0i.js → webgl-device-KnEQ5CNv.js} +2 -2
- package/dist/es/web-kit.mjs +25 -25
- package/dist/iife/web-kit.iife.js +22 -22
- package/dist/sw/mvx-tiles-sw.js +97 -49
- package/dist/types/index.d.ts +40 -42
- package/package.json +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! Web-kit v1.2.0-develop.
|
|
2
|
-
!function(){try{var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},t=(new e.Error).stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="590ab567-0fbd-4d84-a673-3e386e395fb4",e._sentryDebugIdIdentifier="sentry-dbid-590ab567-0fbd-4d84-a673-3e386e395fb4")}catch(e){}}();import{i as e,n as t,t as n}from"./rolldown-runtime-CGJB3Nua.js";import{B as i,Bt as o,D as s,F as r,Ft as a,M as l,N as c,Q as u,S as f,U as d,Ut as p,_ as g,a as h,c as v,d as m,f as _,ft as x,g as y,h as b,in as P,j as C,l as w,m as S,o as L,p as A,rn as I,s as E,tn as T,u as O,w as z,x as M,y as R,zt as B}from"./debug-hooks-A7fGcVSJ.js";import{a as k,c as F,d as N,i as D,p as j,u as U}from"./shader-type-decoder-DV9QwQh3.js";import{a as G,d as V,f as $,g as W,h as H,i as Z,o as Y,p as q,r as K,t as X}from"./webgl-device-Bht0bA0i.js";import{C as J,S as Q,_ as ee,a as te,b as ne,d as ie,f as oe,g as se,h as re,i as ae,l as le,m as ce,n as ue,o as fe,p as de,r as pe,s as ge,t as he,u as ve,v as me,w as _e,x as xe,y as ye}from"./expression-BFfy7ZSj.js";var be=class e extends N{width;height;updateTimestamp;get[Symbol.toStringTag](){return"ExternalTexture"}constructor(t,n){super(t,n,e.defaultProps);const i=this.props.source?t.getExternalImageSize(this.props.source):null;this.width=this.props.width||i?.width||0,this.height=this.props.height||i?.height||0,this.updateTimestamp=t.incrementTimestamp()}static defaultProps={...N.defaultProps,source:void 0,width:0,height:0,colorSpace:"srgb",sampler:{}}};function Pe(e){const{input:t,inputChannels:n,output:i}=e||{};if(!t)return"#version 300 es\nout vec4 transform_output;\nvoid main() {\n transform_output = vec4(0);\n}";if(!n)throw new Error("inputChannels");return`#version 300 es\nin ${function(e){switch(e){case 1:return"float";case 2:return"vec2";case 3:return"vec3";case 4:return"vec4";default:throw new Error(`invalid channels: ${e}`)}}(n)} ${t};\nout vec4 ${i};\nvoid main() {\n ${i} = ${function(e,t){switch(t){case 1:return`vec4(${e}, 0.0, 0.0, 1.0)`;case 2:return`vec4(${e}, 0.0, 1.0)`;case 3:return`vec4(${e}, 1.0)`;case 4:return e;default:throw new Error(`invalid channels: ${t}`)}}(t,n)};\n}`}function Ce(e,t=[],n=0){const i=Math.fround(e),o=e-i;return t[n]=i,t[n+1]=o,t}function we(e,t=!0){return e??t}function Se(e=[0,0,0],t=!0){return t?e.map(e=>e/255):[...e]}var Le="\nlayout(std140) uniform fp64arithmeticUniforms {\n uniform float ONE;\n uniform float SPLIT;\n} fp64;\n\n/*\nAbout LUMA_FP64_CODE_ELIMINATION_WORKAROUND\n\nThe purpose of this workaround is to prevent shader compilers from\noptimizing away necessary arithmetic operations by swapping their sequences\nor transform the equation to some 'equivalent' form.\n\nThese helpers implement Dekker/Veltkamp-style error tracking. If the compiler\nfolds constants or reassociates the arithmetic, the high/low split can stop\ntracking the rounding error correctly. That failure mode tends to look fine in\nsimple coordinate setup, but then breaks down inside iterative arithmetic such\nas fp64 Mandelbrot loops.\n\nThe method is to multiply an artifical variable, ONE, which will be known to\nthe compiler to be 1 only at runtime. The whole expression is then represented\nas a polynomial with respective to ONE. In the coefficients of all terms, only one a\nand one b should appear\n\nerr = (a + b) * ONE^6 - a * ONE^5 - (a + b) * ONE^4 + a * ONE^3 - b - (a + b) * ONE^2 + a * ONE\n*/\n\nfloat prevent_fp64_optimization(float value) {\n#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND)\n return value + fp64.ONE * 0.0;\n#else\n return value;\n#endif\n}\n\n// Divide float number to high and low floats to extend fraction bits\nvec2 split(float a) {\n // Keep SPLIT as a runtime uniform so the compiler cannot fold the Dekker\n // split into a constant expression and reassociate the recovery steps.\n float split = prevent_fp64_optimization(fp64.SPLIT);\n float t = prevent_fp64_optimization(a * split);\n float temp = t - a;\n float a_hi = t - temp;\n float a_lo = a - a_hi;\n return vec2(a_hi, a_lo);\n}\n\n// Divide float number again when high float uses too many fraction bits\nvec2 split2(vec2 a) {\n vec2 b = split(a.x);\n b.y += a.y;\n return b;\n}\n\n// Special sum operation when a > b\nvec2 quickTwoSum(float a, float b) {\n#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND)\n float sum = (a + b) * fp64.ONE;\n float err = b - (sum - a) * fp64.ONE;\n#else\n float sum = a + b;\n float err = b - (sum - a);\n#endif\n return vec2(sum, err);\n}\n\n// General sum operation\nvec2 twoSum(float a, float b) {\n float s = (a + b);\n#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND)\n float v = (s * fp64.ONE - a) * fp64.ONE;\n float err = (a - (s - v) * fp64.ONE) * fp64.ONE * fp64.ONE * fp64.ONE + (b - v);\n#else\n float v = s - a;\n float err = (a - (s - v)) + (b - v);\n#endif\n return vec2(s, err);\n}\n\nvec2 twoSub(float a, float b) {\n float s = (a - b);\n#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND)\n float v = (s * fp64.ONE - a) * fp64.ONE;\n float err = (a - (s - v) * fp64.ONE) * fp64.ONE * fp64.ONE * fp64.ONE - (b + v);\n#else\n float v = s - a;\n float err = (a - (s - v)) - (b + v);\n#endif\n return vec2(s, err);\n}\n\nvec2 twoSqr(float a) {\n float prod = a * a;\n vec2 a_fp64 = split(a);\n#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND)\n float err = ((a_fp64.x * a_fp64.x - prod) * fp64.ONE + 2.0 * a_fp64.x *\n a_fp64.y * fp64.ONE * fp64.ONE) + a_fp64.y * a_fp64.y * fp64.ONE * fp64.ONE * fp64.ONE;\n#else\n float err = ((a_fp64.x * a_fp64.x - prod) + 2.0 * a_fp64.x * a_fp64.y) + a_fp64.y * a_fp64.y;\n#endif\n return vec2(prod, err);\n}\n\nvec2 twoProd(float a, float b) {\n float prod = a * b;\n vec2 a_fp64 = split(a);\n vec2 b_fp64 = split(b);\n // twoProd is especially sensitive because mul_fp64 and div_fp64 both depend\n // on the split terms and cross terms staying in the original evaluation\n // order. If the compiler folds or reassociates them, the low part tends to\n // collapse to zero or NaN on some drivers.\n float highProduct = prevent_fp64_optimization(a_fp64.x * b_fp64.x);\n float crossProduct1 = prevent_fp64_optimization(a_fp64.x * b_fp64.y);\n float crossProduct2 = prevent_fp64_optimization(a_fp64.y * b_fp64.x);\n float lowProduct = prevent_fp64_optimization(a_fp64.y * b_fp64.y);\n#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND)\n float err1 = (highProduct - prod) * fp64.ONE;\n float err2 = crossProduct1 * fp64.ONE * fp64.ONE;\n float err3 = crossProduct2 * fp64.ONE * fp64.ONE * fp64.ONE;\n float err4 = lowProduct * fp64.ONE * fp64.ONE * fp64.ONE * fp64.ONE;\n#else\n float err1 = highProduct - prod;\n float err2 = crossProduct1;\n float err3 = crossProduct2;\n float err4 = lowProduct;\n#endif\n float err = ((err1 + err2) + err3) + err4;\n return vec2(prod, err);\n}\n\nvec2 sum_fp64(vec2 a, vec2 b) {\n vec2 s, t;\n s = twoSum(a.x, b.x);\n t = twoSum(a.y, b.y);\n s.y += t.x;\n s = quickTwoSum(s.x, s.y);\n s.y += t.y;\n s = quickTwoSum(s.x, s.y);\n return s;\n}\n\nvec2 sub_fp64(vec2 a, vec2 b) {\n vec2 s, t;\n s = twoSub(a.x, b.x);\n t = twoSub(a.y, b.y);\n s.y += t.x;\n s = quickTwoSum(s.x, s.y);\n s.y += t.y;\n s = quickTwoSum(s.x, s.y);\n return s;\n}\n\nvec2 mul_fp64(vec2 a, vec2 b) {\n vec2 prod = twoProd(a.x, b.x);\n // y component is for the error\n prod.y += a.x * b.y;\n#if defined(LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND)\n prod = split2(prod);\n#endif\n prod = quickTwoSum(prod.x, prod.y);\n prod.y += a.y * b.x;\n#if defined(LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND)\n prod = split2(prod);\n#endif\n prod = quickTwoSum(prod.x, prod.y);\n return prod;\n}\n\nvec2 div_fp64(vec2 a, vec2 b) {\n float xn = 1.0 / b.x;\n#if defined(LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND)\n vec2 yn = mul_fp64(a, vec2(xn, 0));\n#else\n vec2 yn = a * xn;\n#endif\n float diff = (sub_fp64(a, mul_fp64(b, yn))).x;\n vec2 prod = twoProd(xn, diff);\n return sum_fp64(yn, prod);\n}\n\nvec2 sqrt_fp64(vec2 a) {\n if (a.x == 0.0 && a.y == 0.0) return vec2(0.0, 0.0);\n if (a.x < 0.0) return vec2(0.0 / 0.0, 0.0 / 0.0);\n\n float x = 1.0 / sqrt(a.x);\n float yn = a.x * x;\n#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND)\n vec2 yn_sqr = twoSqr(yn) * fp64.ONE;\n#else\n vec2 yn_sqr = twoSqr(yn);\n#endif\n float diff = sub_fp64(a, yn_sqr).x;\n vec2 prod = twoProd(x * 0.5, diff);\n#if defined(LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND)\n return sum_fp64(split(yn), prod);\n#else\n return sum_fp64(vec2(yn, 0.0), prod);\n#endif\n}\n",Ae={name:"fp64arithmetic",source:"struct Fp64ArithmeticUniforms {\n ONE: f32,\n SPLIT: f32,\n};\n\n@group(0) @binding(auto) var<uniform> fp64arithmetic : Fp64ArithmeticUniforms;\n\n#ifndef LUMA_FP64_F32_INPUT_ONLY\nstruct Fp64Bits {\n sign: u32,\n exponent: i32,\n significand: vec2u,\n isZero: bool,\n isInf: bool,\n isNan: bool,\n};\n#endif\n\n#ifndef LUMA_FP64_PREDICATE_ONLY\nfn fp64_nan(seed: f32) -> f32 {\n let nanBits = 0x7fc00000u | select(0u, 1u, seed < 0.0);\n return bitcast<f32>(nanBits);\n}\n#endif\n\nfn fp64_u64_is_zero(value: vec2u) -> bool {\n return value.x == 0u && value.y == 0u;\n}\n\nfn fp64_u64_compare(a: vec2u, b: vec2u) -> i32 {\n if (a.x != b.x) {\n return select(-1, 1, a.x > b.x);\n }\n if (a.y != b.y) {\n return select(-1, 1, a.y > b.y);\n }\n return 0;\n}\n\nfn fp64_u64_add(a: vec2u, b: vec2u) -> vec2u {\n let low = a.y + b.y;\n let carry = select(0u, 1u, low < a.y);\n return vec2u(a.x + b.x + carry, low);\n}\n\nfn fp64_u64_sub(a: vec2u, b: vec2u) -> vec2u {\n let borrow = select(0u, 1u, a.y < b.y);\n return vec2u(a.x - b.x - borrow, a.y - b.y);\n}\n\nfn fp64_u64_shift_left(value: vec2u, shift: u32) -> vec2u {\n if (shift == 0u) {\n return value;\n }\n if (shift < 32u) {\n return vec2u((value.x << shift) | (value.y >> (32u - shift)), value.y << shift);\n }\n if (shift == 32u) {\n return vec2u(value.y, 0u);\n }\n if (shift < 64u) {\n return vec2u(value.y << (shift - 32u), 0u);\n }\n return vec2u(0u);\n}\n\nfn fp64_u64_shift_right(value: vec2u, shift: u32) -> vec2u {\n if (shift == 0u) {\n return value;\n }\n if (shift < 32u) {\n return vec2u(value.x >> shift, (value.y >> shift) | (value.x << (32u - shift)));\n }\n if (shift == 32u) {\n return vec2u(0u, value.x);\n }\n if (shift < 64u) {\n return vec2u(0u, value.x >> (shift - 32u));\n }\n return vec2u(0u);\n}\n\nfn fp64_u64_get_bit(value: vec2u, bitIndex: u32) -> bool {\n if (bitIndex >= 64u) {\n return false;\n }\n if (bitIndex >= 32u) {\n return ((value.x >> (bitIndex - 32u)) & 1u) != 0u;\n }\n return ((value.y >> bitIndex) & 1u) != 0u;\n}\n\nfn fp64_u64_has_bits_below(value: vec2u, bitCount: u32) -> bool {\n if (bitCount == 0u) {\n return false;\n }\n if (bitCount >= 64u) {\n return !fp64_u64_is_zero(value);\n }\n if (bitCount > 32u) {\n let highBitCount = bitCount - 32u;\n let highMask = (1u << highBitCount) - 1u;\n return value.y != 0u || (value.x & highMask) != 0u;\n }\n if (bitCount == 32u) {\n return value.y != 0u;\n }\n let lowMask = (1u << bitCount) - 1u;\n return (value.y & lowMask) != 0u;\n}\n\n#ifndef LUMA_FP64_F32_INPUT_ONLY\nfn fp64_u64_shift_right_sticky(value: vec2u, shift: u32) -> vec2u {\n var shifted = fp64_u64_shift_right(value, shift);\n if (fp64_u64_has_bits_below(value, shift)) {\n shifted.y = shifted.y | 1u;\n }\n return shifted;\n}\n#endif\n\nfn fp64_u64_count_leading_zeros(value: vec2u) -> u32 {\n if (value.x != 0u) {\n return countLeadingZeros(value.x);\n }\n return 32u + countLeadingZeros(value.y);\n}\n\nfn fp64_round_shift_right_to_u32(value: vec2u, shift: u32) -> u32 {\n if (shift == 0u) {\n return value.y;\n }\n\n let truncated = fp64_u64_shift_right(value, shift);\n var rounded = truncated.y;\n let guard = fp64_u64_get_bit(value, shift - 1u);\n let hasTrailingBits = fp64_u64_has_bits_below(value, shift - 1u);\n if (guard && (hasTrailingBits || (rounded & 1u) == 1u)) {\n rounded = rounded + 1u;\n }\n return rounded;\n}\n\n#ifndef LUMA_FP64_F32_INPUT_ONLY\nfn fp64_round_shift_right(value: vec2u, shift: u32) -> vec2u {\n if (shift == 0u) {\n return value;\n }\n\n var rounded = fp64_u64_shift_right(value, shift);\n let guard = fp64_u64_get_bit(value, shift - 1u);\n let hasTrailingBits = fp64_u64_has_bits_below(value, shift - 1u);\n if (guard && (hasTrailingBits || (rounded.y & 1u) == 1u)) {\n rounded = fp64_u64_add(rounded, vec2u(0u, 1u));\n }\n return rounded;\n}\n#endif\n\nfn fp64_make_f32_bits_from_u64(sign: u32, significand: vec2u, baseExponent: i32) -> u32 {\n if (fp64_u64_is_zero(significand)) {\n return sign << 31u;\n }\n\n let leadingZeros = fp64_u64_count_leading_zeros(significand);\n let mostSignificantBit = 63u - leadingZeros;\n var exponent = baseExponent + i32(mostSignificantBit);\n\n if (exponent > 127) {\n return (sign << 31u) | 0x7f800000u;\n }\n\n if (exponent >= -126) {\n let shift = i32(mostSignificantBit) - 23;\n var significand24: u32;\n if (shift > 0) {\n significand24 = fp64_round_shift_right_to_u32(significand, u32(shift));\n } else {\n significand24 = fp64_u64_shift_left(significand, u32(-shift)).y;\n }\n\n if (significand24 >= 0x1000000u) {\n significand24 = significand24 >> 1u;\n exponent = exponent + 1;\n if (exponent > 127) {\n return (sign << 31u) | 0x7f800000u;\n }\n }\n\n return (sign << 31u) | (u32(exponent + 127) << 23u) | (significand24 & 0x7fffffu);\n }\n\n let scaleExponent = baseExponent + 149;\n var mantissa: u32;\n if (scaleExponent >= 0) {\n mantissa = fp64_u64_shift_left(significand, u32(scaleExponent)).y;\n } else {\n mantissa = fp64_round_shift_right_to_u32(significand, u32(-scaleExponent));\n }\n\n if (mantissa >= 0x800000u) {\n return (sign << 31u) | 0x00800000u;\n }\n return (sign << 31u) | mantissa;\n}\n\n#ifndef LUMA_FP64_F32_INPUT_ONLY\nfn fp64_decode_bits(bits: vec2u) -> Fp64Bits {\n let sign = bits.x >> 31u;\n let exponentBits = (bits.x >> 20u) & 0x7ffu;\n let fractionHigh = bits.x & 0xfffffu;\n let fractionLow = bits.y;\n let fraction = vec2u(fractionHigh, fractionLow);\n\n if (exponentBits == 0x7ffu) {\n let isInf = fp64_u64_is_zero(fraction);\n return Fp64Bits(sign, 0, vec2u(0u), false, isInf, !isInf);\n }\n\n if (exponentBits == 0u) {\n let isZero = fp64_u64_is_zero(fraction);\n return Fp64Bits(sign, -1022, fraction, isZero, false, false);\n }\n\n return Fp64Bits(sign, i32(exponentBits) - 1023, vec2u((1u << 20u) | fractionHigh, fractionLow), false, false, false);\n}\n\nfn fp64_finite_magnitude_compare(a: Fp64Bits, b: Fp64Bits) -> i32 {\n if (a.exponent != b.exponent) {\n return select(-1, 1, a.exponent > b.exponent);\n }\n return fp64_u64_compare(a.significand, b.significand);\n}\n#endif\n\n#ifndef LUMA_FP64_F32_INPUT_ONLY\nstruct Fp64RawF32Bits {\n sign: u32,\n baseExponent: i32,\n significand: u32,\n isZero: bool,\n isInf: bool,\n isNan: bool,\n};\n\n// Decode an f32 as (-1)^sign * significand * 2^baseExponent. This shared\n// integer representation lets normalization remain independent of the\n// selected double-single arithmetic implementation.\nfn fp64_decode_raw_f32_bits(bits: u32) -> Fp64RawF32Bits {\n let sign = bits >> 31u;\n let exponentBits = (bits >> 23u) & 0xffu;\n let fraction = bits & 0x7fffffu;\n\n if (exponentBits == 0xffu) {\n return Fp64RawF32Bits(sign, 0, 0u, false, fraction == 0u, fraction != 0u);\n }\n if (exponentBits == 0u) {\n return Fp64RawF32Bits(sign, -149, fraction, fraction == 0u, false, false);\n }\n return Fp64RawF32Bits(\n sign,\n i32(exponentBits) - 150,\n 0x800000u | fraction,\n false,\n false,\n false\n );\n}\n\nfn fp64_raw_f32_magnitude_compare(aBits: u32, bBits: u32) -> i32 {\n let aMagnitude = aBits & 0x7fffffffu;\n let bMagnitude = bBits & 0x7fffffffu;\n if (aMagnitude == bMagnitude) {\n return 0;\n }\n return select(-1, 1, aMagnitude > bMagnitude);\n}\n\nfn fp64_make_raw_residual_f32_bits(\n exactSign: u32,\n exactMagnitude: vec2u,\n exactBaseExponent: i32,\n highBits: u32\n) -> u32 {\n if (fp64_u64_is_zero(exactMagnitude)) {\n return 0u;\n }\n\n let high = fp64_decode_raw_f32_bits(highBits);\n if (high.isInf || high.isNan) {\n return 0u;\n }\n if (high.isZero) {\n return fp64_make_f32_bits_from_u64(exactSign, exactMagnitude, exactBaseExponent);\n }\n\n let commonBaseExponent = min(exactBaseExponent, high.baseExponent);\n let exactShift = exactBaseExponent - commonBaseExponent;\n let highShift = high.baseExponent - commonBaseExponent;\n if (exactShift >= 64 || highShift >= 64) {\n return 0u;\n }\n\n let exactAligned = fp64_u64_shift_left(exactMagnitude, u32(exactShift));\n let highAligned = fp64_u64_shift_left(vec2u(0u, high.significand), u32(highShift));\n let comparison = fp64_u64_compare(exactAligned, highAligned);\n if (comparison == 0) {\n return 0u;\n }\n\n var residualSign = exactSign;\n var residualMagnitude: vec2u;\n if (comparison > 0) {\n residualMagnitude = fp64_u64_sub(exactAligned, highAligned);\n } else {\n residualSign = exactSign ^ 1u;\n residualMagnitude = fp64_u64_sub(highAligned, exactAligned);\n }\n return fp64_make_f32_bits_from_u64(\n residualSign,\n residualMagnitude,\n commonBaseExponent\n );\n}\n\nfn fp64_split_raw_accumulator_bits(\n sign: u32,\n magnitude: vec2u,\n baseExponent: i32\n) -> vec2u {\n if (fp64_u64_is_zero(magnitude)) {\n return vec2u(0u);\n }\n let highBits = fp64_make_f32_bits_from_u64(sign, magnitude, baseExponent);\n let rawLowBits = fp64_make_raw_residual_f32_bits(sign, magnitude, baseExponent, highBits);\n let lowBits = select(rawLowBits, 0u, (rawLowBits & 0x7fffffffu) == 0u);\n if ((highBits & 0x7fffffffu) == 0u && (lowBits & 0x7fffffffu) == 0u) {\n return vec2u(0u);\n }\n return vec2u(highBits, lowBits);\n}\n#endif\n\n#ifndef LUMA_FP64_F32_INPUT_ONLY\n// Round an arithmetic accumulator to binary64 before splitting it. The\n// aligned add/subtract paths retain three guard bits plus a sticky bit, which\n// is sufficient for round-to-nearest-even at the binary64 boundary.\nfn fp64_split_binary64_accumulator_bits(\n sign: u32,\n magnitude: vec2u,\n baseExponent: i32\n) -> vec2u {\n if (fp64_u64_is_zero(magnitude)) {\n return vec2u(0u);\n }\n\n let mostSignificantBit = 63u - fp64_u64_count_leading_zeros(magnitude);\n let exponent = baseExponent + i32(mostSignificantBit);\n if (exponent > 1023) {\n return vec2u((sign << 31u) | 0x7f800000u, 0u);\n }\n\n var roundedMagnitude = magnitude;\n var roundedBaseExponent = baseExponent;\n if (exponent >= -1022) {\n if (mostSignificantBit > 52u) {\n let shift = mostSignificantBit - 52u;\n roundedMagnitude = fp64_round_shift_right(magnitude, shift);\n roundedBaseExponent = baseExponent + i32(shift);\n }\n } else {\n let shift = -1074 - baseExponent;\n if (shift > 0) {\n roundedMagnitude = fp64_round_shift_right(magnitude, u32(shift));\n roundedBaseExponent = -1074;\n }\n }\n\n if (fp64_u64_is_zero(roundedMagnitude)) {\n return vec2u(0u);\n }\n return fp64_split_raw_accumulator_bits(sign, roundedMagnitude, roundedBaseExponent);\n}\n#endif\n\n#ifndef LUMA_FP64_PREDICATE_ONLY\nfn fp64_add_raw_f32_bits(aBits: u32, bBits: u32) -> vec2u {\n let a = fp64_decode_raw_f32_bits(aBits);\n let b = fp64_decode_raw_f32_bits(bBits);\n\n if (a.isNan || b.isNan) {\n return vec2u(0x7fc00000u, 0u);\n }\n if (a.isInf || b.isInf) {\n if (a.isInf && b.isInf && a.sign != b.sign) {\n return vec2u(0x7fc00000u, 0u);\n }\n return select(vec2u(bBits, 0u), vec2u(aBits, 0u), a.isInf);\n }\n if (a.isZero && b.isZero) {\n return vec2u(0u);\n }\n if (a.isZero) {\n return vec2u(bBits, 0u);\n }\n if (b.isZero) {\n return vec2u(aBits, 0u);\n }\n\n let exponentDifference = abs(a.baseExponent - b.baseExponent);\n if (exponentDifference > 25) {\n if (fp64_raw_f32_magnitude_compare(aBits, bBits) >= 0) {\n return vec2u(aBits, bBits);\n }\n return vec2u(bBits, aBits);\n }\n\n let commonBaseExponent = min(a.baseExponent, b.baseExponent);\n let aMagnitude = fp64_u64_shift_left(\n vec2u(0u, a.significand),\n u32(a.baseExponent - commonBaseExponent)\n );\n let bMagnitude = fp64_u64_shift_left(\n vec2u(0u, b.significand),\n u32(b.baseExponent - commonBaseExponent)\n );\n\n var resultSign = a.sign;\n var resultMagnitude: vec2u;\n if (a.sign == b.sign) {\n resultMagnitude = fp64_u64_add(aMagnitude, bMagnitude);\n } else {\n let comparison = fp64_u64_compare(aMagnitude, bMagnitude);\n if (comparison == 0) {\n return vec2u(0u);\n }\n if (comparison > 0) {\n resultMagnitude = fp64_u64_sub(aMagnitude, bMagnitude);\n } else {\n resultSign = b.sign;\n resultMagnitude = fp64_u64_sub(bMagnitude, aMagnitude);\n }\n }\n\n return fp64_split_raw_accumulator_bits(\n resultSign,\n resultMagnitude,\n commonBaseExponent\n );\n}\n#endif\n\n#ifndef LUMA_FP64_F32_INPUT_ONLY\nfn fp64_add_aligned_magnitudes_to_fp64_bits(\n sign: u32,\n larger: Fp64Bits,\n smaller: Fp64Bits\n) -> vec2u {\n let largeSignificand = fp64_u64_shift_left(larger.significand, 3u);\n let smallSignificand = fp64_u64_shift_right_sticky(\n fp64_u64_shift_left(smaller.significand, 3u),\n u32(larger.exponent - smaller.exponent)\n );\n let resultSignificand = fp64_u64_add(largeSignificand, smallSignificand);\n return fp64_split_binary64_accumulator_bits(\n sign,\n resultSignificand,\n larger.exponent - 55\n );\n}\n\nfn fp64_sub_aligned_magnitudes_to_fp64_bits(\n sign: u32,\n larger: Fp64Bits,\n smaller: Fp64Bits\n) -> vec2u {\n let largeSignificand = fp64_u64_shift_left(larger.significand, 3u);\n let smallSignificand = fp64_u64_shift_right_sticky(\n fp64_u64_shift_left(smaller.significand, 3u),\n u32(larger.exponent - smaller.exponent)\n );\n let resultSignificand = fp64_u64_sub(largeSignificand, smallSignificand);\n return fp64_split_binary64_accumulator_bits(\n sign,\n resultSignificand,\n larger.exponent - 55\n );\n}\n\nfn fp64_add_aligned_magnitudes_to_f32_bits(sign: u32, larger: Fp64Bits, smaller: Fp64Bits) -> u32 {\n let largeSignificand = fp64_u64_shift_left(larger.significand, 3u);\n let smallSignificand = fp64_u64_shift_right_sticky(\n fp64_u64_shift_left(smaller.significand, 3u),\n u32(larger.exponent - smaller.exponent)\n );\n let resultSignificand = fp64_u64_add(largeSignificand, smallSignificand);\n return fp64_make_f32_bits_from_u64(sign, resultSignificand, larger.exponent - 55);\n}\n\nfn fp64_sub_aligned_magnitudes_to_f32_bits(sign: u32, larger: Fp64Bits, smaller: Fp64Bits) -> u32 {\n let largeSignificand = fp64_u64_shift_left(larger.significand, 3u);\n let smallSignificand = fp64_u64_shift_right_sticky(\n fp64_u64_shift_left(smaller.significand, 3u),\n u32(larger.exponent - smaller.exponent)\n );\n let resultSignificand = fp64_u64_sub(largeSignificand, smallSignificand);\n return fp64_make_f32_bits_from_u64(sign, resultSignificand, larger.exponent - 55);\n}\n\n// Subtract two raw binary64 values and round the exact result once to f32.\n// The input words are canonical high/low words: .x contains sign/exponent/high\n// fraction bits, and .y contains the low 32 fraction bits.\nfn sub_fp64u32_to_f32_bits(aBits: vec2u, bBits: vec2u) -> u32 {\n let a = fp64_decode_bits(aBits);\n let b = fp64_decode_bits(bBits);\n let bSubtractionSign = b.sign ^ 1u;\n\n if (a.isNan || b.isNan) {\n return 0x7fc00000u;\n }\n if (a.isInf && b.isInf) {\n if (a.sign == bSubtractionSign) {\n return (a.sign << 31u) | 0x7f800000u;\n }\n return 0x7fc00000u;\n }\n if (a.isInf) {\n return (a.sign << 31u) | 0x7f800000u;\n }\n if (b.isInf) {\n return (bSubtractionSign << 31u) | 0x7f800000u;\n }\n if (a.isZero && b.isZero) {\n return select(0u, 0x80000000u, a.sign == 1u && b.sign == 0u);\n }\n\n let magnitudeComparison = fp64_finite_magnitude_compare(a, b);\n if (a.sign == bSubtractionSign) {\n if (magnitudeComparison >= 0) {\n return fp64_add_aligned_magnitudes_to_f32_bits(a.sign, a, b);\n }\n return fp64_add_aligned_magnitudes_to_f32_bits(a.sign, b, a);\n }\n\n if (magnitudeComparison == 0) {\n return 0u;\n }\n if (magnitudeComparison > 0) {\n return fp64_sub_aligned_magnitudes_to_f32_bits(a.sign, a, b);\n }\n return fp64_sub_aligned_magnitudes_to_f32_bits(bSubtractionSign, b, a);\n}\n\nfn sub_fp64u32_to_f32(aBits: vec2u, bBits: vec2u) -> f32 {\n return bitcast<f32>(sub_fp64u32_to_f32_bits(aBits, bBits));\n}\n\n// Subtract two raw binary64 values, round once to binary64, then split the\n// result into normalized f32 limbs. Finite results must fit within the f32\n// exponent range; larger magnitudes map to infinity and smaller magnitudes\n// map to zero. The input words use canonical high/low word order.\nfn sub_fp64u32_to_fp64_bits(aBits: vec2u, bBits: vec2u) -> vec2u {\n let a = fp64_decode_bits(aBits);\n let b = fp64_decode_bits(bBits);\n let bSubtractionSign = b.sign ^ 1u;\n\n if (a.isNan || b.isNan) {\n return vec2u(0x7fc00000u, 0u);\n }\n if (a.isInf && b.isInf) {\n if (a.sign == bSubtractionSign) {\n return vec2u((a.sign << 31u) | 0x7f800000u, 0u);\n }\n return vec2u(0x7fc00000u, 0u);\n }\n if (a.isInf) {\n return vec2u((a.sign << 31u) | 0x7f800000u, 0u);\n }\n if (b.isInf) {\n return vec2u((bSubtractionSign << 31u) | 0x7f800000u, 0u);\n }\n if (a.isZero && b.isZero) {\n return vec2u(0u);\n }\n\n let magnitudeComparison = fp64_finite_magnitude_compare(a, b);\n if (a.sign == bSubtractionSign) {\n if (magnitudeComparison >= 0) {\n return fp64_add_aligned_magnitudes_to_fp64_bits(a.sign, a, b);\n }\n return fp64_add_aligned_magnitudes_to_fp64_bits(a.sign, b, a);\n }\n\n if (magnitudeComparison == 0) {\n return vec2u(0u);\n }\n if (magnitudeComparison > 0) {\n return fp64_sub_aligned_magnitudes_to_fp64_bits(a.sign, a, b);\n }\n return fp64_sub_aligned_magnitudes_to_fp64_bits(bSubtractionSign, b, a);\n}\n\nfn sub_fp64u32_to_fp64(aBits: vec2u, bBits: vec2u) -> vec2f {\n let resultBits = sub_fp64u32_to_fp64_bits(aBits, bBits);\n return vec2f(bitcast<f32>(resultBits.x), bitcast<f32>(resultBits.y));\n}\n#endif\n\n#ifndef LUMA_FP64_PREDICATE_ONLY\nfn fp64_runtime_zero() -> f32 {\n return fp64arithmetic.ONE * 0.0;\n}\n\nfn prevent_fp64_optimization(value: f32) -> f32 {\n#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND\n return value + fp64_runtime_zero();\n#else\n return value;\n#endif\n}\n#endif\n\n#ifdef LUMA_FP64_INTEGER_ARITHMETIC\nstruct Fp64F32Bits {\n sign: u32,\n baseExponent: i32,\n significand: u32,\n isZero: bool,\n isInf: bool,\n isNan: bool,\n};\n\n// Decode an f32 as (-1)^sign * significand * 2^baseExponent.\nfn fp64_decode_f32_bits(bits: u32) -> Fp64F32Bits {\n let sign = bits >> 31u;\n let exponentBits = (bits >> 23u) & 0xffu;\n let fraction = bits & 0x7fffffu;\n\n if (exponentBits == 0xffu) {\n return Fp64F32Bits(sign, 0, 0u, false, fraction == 0u, fraction != 0u);\n }\n if (exponentBits == 0u) {\n return Fp64F32Bits(sign, -149, fraction, fraction == 0u, false, false);\n }\n return Fp64F32Bits(sign, i32(exponentBits) - 150, 0x800000u | fraction, false, false, false);\n}\n\nfn fp64_f32_magnitude_compare(aBits: u32, bBits: u32) -> i32 {\n let aMagnitude = aBits & 0x7fffffffu;\n let bMagnitude = bBits & 0x7fffffffu;\n if (aMagnitude == bMagnitude) {\n return 0;\n }\n return select(-1, 1, aMagnitude > bMagnitude);\n}\n\nfn fp64_make_residual_f32_bits(\n exactSign: u32,\n exactMagnitude: vec2u,\n exactBaseExponent: i32,\n highBits: u32\n) -> u32 {\n if (fp64_u64_is_zero(exactMagnitude)) {\n return 0u;\n }\n\n let high = fp64_decode_f32_bits(highBits);\n if (high.isInf || high.isNan) {\n return exactSign << 31u;\n }\n if (high.isZero) {\n return fp64_make_f32_bits_from_u64(exactSign, exactMagnitude, exactBaseExponent);\n }\n\n let commonBaseExponent = min(exactBaseExponent, high.baseExponent);\n let exactShift = exactBaseExponent - commonBaseExponent;\n let highShift = high.baseExponent - commonBaseExponent;\n\n // A normal two-sum/two-product residual never needs a shift this large.\n // This guard gives deterministic underflow behavior outside that contract.\n if (exactShift >= 64 || highShift >= 64) {\n return exactSign << 31u;\n }\n\n let exactAligned = fp64_u64_shift_left(exactMagnitude, u32(exactShift));\n let highAligned = fp64_u64_shift_left(vec2u(0u, high.significand), u32(highShift));\n let comparison = fp64_u64_compare(exactAligned, highAligned);\n if (comparison == 0) {\n return 0u;\n }\n\n var residualSign = exactSign;\n var residualMagnitude: vec2u;\n if (comparison > 0) {\n residualMagnitude = fp64_u64_sub(exactAligned, highAligned);\n } else {\n residualSign = exactSign ^ 1u;\n residualMagnitude = fp64_u64_sub(highAligned, exactAligned);\n }\n return fp64_make_f32_bits_from_u64(\n residualSign,\n residualMagnitude,\n commonBaseExponent\n );\n}\n\nfn fp64_split_accumulator_bits(\n sign: u32,\n magnitude: vec2u,\n baseExponent: i32\n) -> vec2u {\n let highBits = fp64_make_f32_bits_from_u64(sign, magnitude, baseExponent);\n let lowBits = fp64_make_residual_f32_bits(sign, magnitude, baseExponent, highBits);\n return vec2u(highBits, lowBits);\n}\n\nfn fp64_two_sum_integer_bits(aBits: u32, bBits: u32) -> vec2u {\n let a = fp64_decode_f32_bits(aBits);\n let b = fp64_decode_f32_bits(bBits);\n\n if (a.isNan || b.isNan) {\n return vec2u(0x7fc00000u, 0u);\n }\n if (a.isInf || b.isInf) {\n if (a.isInf && b.isInf && a.sign != b.sign) {\n return vec2u(0x7fc00000u, 0u);\n }\n return select(vec2u(bBits, 0u), vec2u(aBits, 0u), a.isInf);\n }\n if (a.isZero && b.isZero) {\n return vec2u((a.sign & b.sign) << 31u, 0u);\n }\n if (a.isZero) {\n return vec2u(bBits, 0u);\n }\n if (b.isZero) {\n return vec2u(aBits, 0u);\n }\n\n let exponentDifference = select(\n b.baseExponent - a.baseExponent,\n a.baseExponent - b.baseExponent,\n a.baseExponent >= b.baseExponent\n );\n\n // Beyond half an ulp, rounding cannot change the larger operand. Returning\n // the smaller operand intact also avoids an unbounded integer alignment.\n // At a power-of-two boundary the spacing below the larger operand is half\n // the spacing above it, so an opposite-sign gap-25 operand can still change\n // the rounded high limb. Gap 26 is the first universally safe early-out.\n if (exponentDifference > 25) {\n if (fp64_f32_magnitude_compare(aBits, bBits) >= 0) {\n return vec2u(aBits, bBits);\n }\n return vec2u(bBits, aBits);\n }\n\n let commonBaseExponent = min(a.baseExponent, b.baseExponent);\n let aMagnitude = fp64_u64_shift_left(\n vec2u(0u, a.significand),\n u32(a.baseExponent - commonBaseExponent)\n );\n let bMagnitude = fp64_u64_shift_left(\n vec2u(0u, b.significand),\n u32(b.baseExponent - commonBaseExponent)\n );\n\n var resultSign = a.sign;\n var resultMagnitude: vec2u;\n if (a.sign == b.sign) {\n resultMagnitude = fp64_u64_add(aMagnitude, bMagnitude);\n } else {\n let comparison = fp64_u64_compare(aMagnitude, bMagnitude);\n if (comparison == 0) {\n return vec2u(0u, 0u);\n }\n if (comparison > 0) {\n resultMagnitude = fp64_u64_sub(aMagnitude, bMagnitude);\n } else {\n resultSign = b.sign;\n resultMagnitude = fp64_u64_sub(bMagnitude, aMagnitude);\n }\n }\n\n return fp64_split_accumulator_bits(resultSign, resultMagnitude, commonBaseExponent);\n}\n\nfn fp64_two_sum_integer(a: f32, b: f32) -> vec2f {\n let resultBits = fp64_two_sum_integer_bits(bitcast<u32>(a), bitcast<u32>(b));\n return vec2f(bitcast<f32>(resultBits.x), bitcast<f32>(resultBits.y));\n}\n\nfn fp64_multiply_significands(a: u32, b: u32) -> vec2u {\n let aLow = a & 0xffffu;\n let aHigh = a >> 16u;\n let bLow = b & 0xffffu;\n let bHigh = b >> 16u;\n let lowProduct = aLow * bLow;\n let crossProduct = aLow * bHigh + aHigh * bLow;\n let highProduct = aHigh * bHigh;\n\n var result = vec2u(0u, lowProduct);\n result = fp64_u64_add(\n result,\n fp64_u64_shift_left(vec2u(0u, crossProduct), 16u)\n );\n result = fp64_u64_add(result, vec2u(highProduct, 0u));\n return result;\n}\n\nfn fp64_two_prod_integer_bits(aBits: u32, bBits: u32) -> vec2u {\n let a = fp64_decode_f32_bits(aBits);\n let b = fp64_decode_f32_bits(bBits);\n let resultSign = a.sign ^ b.sign;\n\n if (a.isNan || b.isNan || ((a.isZero || b.isZero) && (a.isInf || b.isInf))) {\n return vec2u(0x7fc00000u, 0u);\n }\n if (a.isInf || b.isInf) {\n return vec2u((resultSign << 31u) | 0x7f800000u, resultSign << 31u);\n }\n if (a.isZero || b.isZero) {\n return vec2u(resultSign << 31u, resultSign << 31u);\n }\n\n let magnitude = fp64_multiply_significands(a.significand, b.significand);\n return fp64_split_accumulator_bits(\n resultSign,\n magnitude,\n a.baseExponent + b.baseExponent\n );\n}\n\nfn fp64_two_prod_integer(a: f32, b: f32) -> vec2f {\n let resultBits = fp64_two_prod_integer_bits(bitcast<u32>(a), bitcast<u32>(b));\n return vec2f(bitcast<f32>(resultBits.x), bitcast<f32>(resultBits.y));\n}\n\nfn fp64_round_add_integer(a: f32, b: f32) -> f32 {\n return fp64_two_sum_integer(a, b).x;\n}\n\nfn fp64_round_mul_integer(a: f32, b: f32) -> f32 {\n return fp64_two_prod_integer(a, b).x;\n}\n\n#ifndef LUMA_FP64_PREDICATE_ONLY\nfn fp64_f32_finite_exponent(value: Fp64F32Bits) -> i32 {\n let mostSignificantBit = 31u - countLeadingZeros(value.significand);\n return value.baseExponent + i32(mostSignificantBit);\n}\n\nfn fp64_scale_f32_integer(value: f32, exponent: i32) -> f32 {\n let decoded = fp64_decode_f32_bits(bitcast<u32>(value));\n if (decoded.isZero || decoded.isInf || decoded.isNan) {\n return value;\n }\n let resultBits = fp64_make_f32_bits_from_u64(\n decoded.sign,\n vec2u(0u, decoded.significand),\n decoded.baseExponent + exponent\n );\n return bitcast<f32>(resultBits);\n}\n\n// Divide normalized significands so the hardware operation cannot overflow,\n// underflow, or flush a subnormal result. Reapply the exponent with integer\n// packing, which also produces subnormal correction limbs without relying on\n// floating-point arithmetic to preserve them.\nfn fp64_divide_f32_integer(aValue: f32, bValue: f32) -> f32 {\n let a = fp64_decode_f32_bits(bitcast<u32>(aValue));\n let b = fp64_decode_f32_bits(bitcast<u32>(bValue));\n if (a.isZero || b.isZero || a.isInf || b.isInf || a.isNan || b.isNan) {\n return aValue / bValue;\n }\n\n let aMostSignificantBit = 31u - countLeadingZeros(a.significand);\n let bMostSignificantBit = 31u - countLeadingZeros(b.significand);\n let normalizedABits = fp64_make_f32_bits_from_u64(\n a.sign,\n vec2u(0u, a.significand),\n -i32(aMostSignificantBit)\n );\n let normalizedBBits = fp64_make_f32_bits_from_u64(\n b.sign,\n vec2u(0u, b.significand),\n -i32(bMostSignificantBit)\n );\n let normalizedQuotient = bitcast<f32>(normalizedABits) / bitcast<f32>(normalizedBBits);\n let quotient = fp64_decode_f32_bits(bitcast<u32>(normalizedQuotient));\n let exponentShift =\n a.baseExponent + i32(aMostSignificantBit) -\n b.baseExponent - i32(bMostSignificantBit);\n let quotientBits = fp64_make_f32_bits_from_u64(\n quotient.sign,\n vec2u(0u, quotient.significand),\n quotient.baseExponent + exponentShift\n );\n return bitcast<f32>(quotientBits);\n}\n#endif\n\n#ifndef LUMA_FP64_PREDICATE_ONLY\nfn split(a: f32) -> vec2f {\n let aBits = bitcast<u32>(a);\n let decoded = fp64_decode_f32_bits(aBits);\n if (decoded.isZero || decoded.isInf || decoded.isNan) {\n return vec2f(a, 0.0);\n }\n\n var roundedHigh = decoded.significand >> 12u;\n let remainder = decoded.significand & 0xfffu;\n if (remainder > 0x800u || (remainder == 0x800u && (roundedHigh & 1u) == 1u)) {\n roundedHigh = roundedHigh + 1u;\n }\n var highMagnitude = vec2u(0u, roundedHigh << 12u);\n var highBits = fp64_make_f32_bits_from_u64(\n decoded.sign,\n highMagnitude,\n decoded.baseExponent\n );\n // Rounding the high limb of a maximum-exponent value can overflow even\n // though the original value is finite. Truncate only in that boundary case\n // so split remains an exact finite decomposition.\n if (fp64_decode_f32_bits(highBits).isInf) {\n roundedHigh = decoded.significand >> 12u;\n highMagnitude = vec2u(0u, roundedHigh << 12u);\n highBits = fp64_make_f32_bits_from_u64(\n decoded.sign,\n highMagnitude,\n decoded.baseExponent\n );\n }\n let lowBits = fp64_make_residual_f32_bits(\n decoded.sign,\n vec2u(0u, decoded.significand),\n decoded.baseExponent,\n highBits\n );\n return vec2f(bitcast<f32>(highBits), bitcast<f32>(lowBits));\n}\n\nfn split2(a: vec2f) -> vec2f {\n var result = split(a.x);\n result.y = fp64_round_add_integer(result.y, a.y);\n return result;\n}\n#endif\n\n#ifndef LUMA_FP64_PREDICATE_ONLY\nfn quickTwoSum(a: f32, b: f32) -> vec2f {\n return fp64_two_sum_integer(a, b);\n}\n#endif\n\nfn twoSum(a: f32, b: f32) -> vec2f {\n return fp64_two_sum_integer(a, b);\n}\n\nfn twoSub(a: f32, b: f32) -> vec2f {\n let bBits = bitcast<u32>(b) ^ 0x80000000u;\n let resultBits = fp64_two_sum_integer_bits(bitcast<u32>(a), bBits);\n return vec2f(bitcast<f32>(resultBits.x), bitcast<f32>(resultBits.y));\n}\n\n#ifndef LUMA_FP64_PREDICATE_ONLY\nfn twoSqr(a: f32) -> vec2f {\n return fp64_two_prod_integer(a, a);\n}\n\nfn twoProd(a: f32, b: f32) -> vec2f {\n return fp64_two_prod_integer(a, b);\n}\n#endif\n\nfn sum_fp64(a: vec2f, b: vec2f) -> vec2f {\n var sum = fp64_two_sum_integer(a.x, b.x);\n let lowSum = fp64_two_sum_integer(a.y, b.y);\n sum.y = fp64_round_add_integer(sum.y, lowSum.x);\n sum = fp64_two_sum_integer(sum.x, sum.y);\n sum.y = fp64_round_add_integer(sum.y, lowSum.y);\n return fp64_two_sum_integer(sum.x, sum.y);\n}\n\nfn sub_fp64(a: vec2f, b: vec2f) -> vec2f {\n let negatedB = vec2f(\n bitcast<f32>(bitcast<u32>(b.x) ^ 0x80000000u),\n bitcast<f32>(bitcast<u32>(b.y) ^ 0x80000000u)\n );\n return sum_fp64(a, negatedB);\n}\n\nfn mul_fp64(a: vec2f, b: vec2f) -> vec2f {\n var product = fp64_two_prod_integer(a.x, b.x);\n let crossProduct1 = fp64_round_mul_integer(a.x, b.y);\n product.y = fp64_round_add_integer(product.y, crossProduct1);\n product = fp64_two_sum_integer(product.x, product.y);\n let crossProduct2 = fp64_round_mul_integer(a.y, b.x);\n product.y = fp64_round_add_integer(product.y, crossProduct2);\n return fp64_two_sum_integer(product.x, product.y);\n}\n\n#ifndef LUMA_FP64_PREDICATE_ONLY\nfn fp64_scale_fp64_integer(value: vec2f, exponent: i32) -> vec2f {\n let high = fp64_scale_f32_integer(value.x, exponent);\n let low = fp64_scale_f32_integer(value.y, exponent);\n return sum_fp64(vec2f(high, 0.0), vec2f(low, 0.0));\n}\n\nfn fp64_div_fp64_normalized(a: vec2f, b: vec2f) -> vec2f {\n let quotientHigh = fp64_divide_f32_integer(a.x, b.x);\n var quotient = vec2f(quotientHigh, 0.0);\n\n let remainder = sub_fp64(a, mul_fp64(b, quotient));\n let quotientLow = fp64_divide_f32_integer(remainder.x, b.x);\n quotient = sum_fp64(quotient, vec2f(quotientLow, 0.0));\n\n let secondRemainder = sub_fp64(a, mul_fp64(b, quotient));\n let correction = fp64_divide_f32_integer(secondRemainder.x, b.x);\n return sum_fp64(quotient, vec2f(correction, 0.0));\n}\n\nfn div_fp64(a: vec2f, b: vec2f) -> vec2f {\n let decodedA = fp64_decode_f32_bits(bitcast<u32>(a.x));\n let decodedB = fp64_decode_f32_bits(bitcast<u32>(b.x));\n if (\n decodedA.isZero || decodedB.isZero ||\n decodedA.isInf || decodedB.isInf ||\n decodedA.isNan || decodedB.isNan\n ) {\n return fp64_div_fp64_normalized(a, b);\n }\n\n let exponentA = fp64_f32_finite_exponent(decodedA);\n let exponentB = fp64_f32_finite_exponent(decodedB);\n // Correct the quotient near unity so b * q and the remainder stay clear of\n // both f32 underflow and overflow. The exponent difference is applied once.\n let normalizedA = fp64_scale_fp64_integer(a, -exponentA);\n let normalizedB = fp64_scale_fp64_integer(b, -exponentB);\n let normalizedQuotient = fp64_div_fp64_normalized(normalizedA, normalizedB);\n return fp64_scale_fp64_integer(normalizedQuotient, exponentA - exponentB);\n}\n\nfn fp64_sqrt_fp64_normalized(a: vec2f) -> vec2f {\n let estimate = sqrt(a.x);\n let difference = sub_fp64(a, fp64_two_prod_integer(estimate, estimate)).x;\n let denominator = fp64_round_add_integer(estimate, estimate);\n let correction = fp64_divide_f32_integer(difference, denominator);\n return sum_fp64(vec2f(estimate, 0.0), vec2f(correction, 0.0));\n}\n\nfn sqrt_fp64(a: vec2f) -> vec2f {\n let decoded = fp64_decode_f32_bits(bitcast<u32>(a.x));\n let decodedLow = fp64_decode_f32_bits(bitcast<u32>(a.y));\n if (decoded.isZero && decodedLow.isZero) {\n return vec2f(0.0, 0.0);\n }\n if (decoded.sign == 1u) {\n let nanValue = fp64_nan(a.x);\n return vec2f(nanValue, nanValue);\n }\n\n if (decoded.isInf || decoded.isNan) {\n return fp64_sqrt_fp64_normalized(a);\n }\n let exponent = fp64_f32_finite_exponent(decoded);\n // An even scale lets the final square-root rescale use an integer exponent.\n let evenExponent = exponent - (exponent & 1);\n let normalizedA = fp64_scale_fp64_integer(a, -evenExponent);\n let normalizedRoot = fp64_sqrt_fp64_normalized(normalizedA);\n return fp64_scale_fp64_integer(normalizedRoot, evenExponent / 2);\n}\n#endif\n\n#else\nfn split(a: f32) -> vec2f {\n let splitValue = prevent_fp64_optimization(fp64arithmetic.SPLIT + fp64_runtime_zero());\n let t = prevent_fp64_optimization(a * splitValue);\n let temp = prevent_fp64_optimization(t - a);\n let aHi = prevent_fp64_optimization(t - temp);\n let aLo = prevent_fp64_optimization(a - aHi);\n return vec2f(aHi, aLo);\n}\n\nfn split2(a: vec2f) -> vec2f {\n var b = split(a.x);\n b.y = b.y + a.y;\n return b;\n}\n\nfn quickTwoSum(a: f32, b: f32) -> vec2f {\n#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND\n let sum = prevent_fp64_optimization((a + b) * fp64arithmetic.ONE);\n let err = prevent_fp64_optimization(b - (sum - a) * fp64arithmetic.ONE);\n#else\n let sum = prevent_fp64_optimization(a + b);\n let err = prevent_fp64_optimization(b - (sum - a));\n#endif\n return vec2f(sum, err);\n}\n\nfn twoSum(a: f32, b: f32) -> vec2f {\n let s = prevent_fp64_optimization(a + b);\n#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND\n let v = prevent_fp64_optimization((s * fp64arithmetic.ONE - a) * fp64arithmetic.ONE);\n let err =\n prevent_fp64_optimization((a - (s - v) * fp64arithmetic.ONE) *\n fp64arithmetic.ONE *\n fp64arithmetic.ONE *\n fp64arithmetic.ONE) +\n prevent_fp64_optimization(b - v);\n#else\n let v = prevent_fp64_optimization(s - a);\n let err = prevent_fp64_optimization(a - (s - v)) + prevent_fp64_optimization(b - v);\n#endif\n return vec2f(s, err);\n}\n\nfn twoSub(a: f32, b: f32) -> vec2f {\n let s = prevent_fp64_optimization(a - b);\n#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND\n let v = prevent_fp64_optimization((s * fp64arithmetic.ONE - a) * fp64arithmetic.ONE);\n let err =\n prevent_fp64_optimization((a - (s - v) * fp64arithmetic.ONE) *\n fp64arithmetic.ONE *\n fp64arithmetic.ONE *\n fp64arithmetic.ONE) -\n prevent_fp64_optimization(b + v);\n#else\n let v = prevent_fp64_optimization(s - a);\n let err = prevent_fp64_optimization(a - (s - v)) - prevent_fp64_optimization(b + v);\n#endif\n return vec2f(s, err);\n}\n\nfn twoSqr(a: f32) -> vec2f {\n let prod = prevent_fp64_optimization(a * a);\n let aFp64 = split(a);\n let highProduct = prevent_fp64_optimization(aFp64.x * aFp64.x);\n let crossProduct = prevent_fp64_optimization(2.0 * aFp64.x * aFp64.y);\n let lowProduct = prevent_fp64_optimization(aFp64.y * aFp64.y);\n#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND\n let err =\n (prevent_fp64_optimization(highProduct - prod) * fp64arithmetic.ONE +\n crossProduct * fp64arithmetic.ONE * fp64arithmetic.ONE) +\n lowProduct * fp64arithmetic.ONE * fp64arithmetic.ONE * fp64arithmetic.ONE;\n#else\n let err = ((prevent_fp64_optimization(highProduct - prod) + crossProduct) + lowProduct);\n#endif\n return vec2f(prod, err);\n}\n\nfn twoProd(a: f32, b: f32) -> vec2f {\n let prod = prevent_fp64_optimization(a * b);\n let aFp64 = split(a);\n let bFp64 = split(b);\n let highProduct = prevent_fp64_optimization(aFp64.x * bFp64.x);\n let crossProduct1 = prevent_fp64_optimization(aFp64.x * bFp64.y);\n let crossProduct2 = prevent_fp64_optimization(aFp64.y * bFp64.x);\n let lowProduct = prevent_fp64_optimization(aFp64.y * bFp64.y);\n#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND\n let err1 = (highProduct - prod) * fp64arithmetic.ONE;\n let err2 = crossProduct1 * fp64arithmetic.ONE * fp64arithmetic.ONE;\n let err3 = crossProduct2 * fp64arithmetic.ONE * fp64arithmetic.ONE * fp64arithmetic.ONE;\n let err4 =\n lowProduct *\n fp64arithmetic.ONE *\n fp64arithmetic.ONE *\n fp64arithmetic.ONE *\n fp64arithmetic.ONE;\n#else\n let err1 = highProduct - prod;\n let err2 = crossProduct1;\n let err3 = crossProduct2;\n let err4 = lowProduct;\n#endif\n let err12InputA = prevent_fp64_optimization(err1);\n let err12InputB = prevent_fp64_optimization(err2);\n let err12 = prevent_fp64_optimization(err12InputA + err12InputB);\n let err123InputA = prevent_fp64_optimization(err12);\n let err123InputB = prevent_fp64_optimization(err3);\n let err123 = prevent_fp64_optimization(err123InputA + err123InputB);\n let err1234InputA = prevent_fp64_optimization(err123);\n let err1234InputB = prevent_fp64_optimization(err4);\n let err = prevent_fp64_optimization(err1234InputA + err1234InputB);\n return vec2f(prod, err);\n}\n\nfn sum_fp64(a: vec2f, b: vec2f) -> vec2f {\n var s = twoSum(a.x, b.x);\n let t = twoSum(a.y, b.y);\n s.y = prevent_fp64_optimization(s.y + t.x);\n s = quickTwoSum(s.x, s.y);\n s.y = prevent_fp64_optimization(s.y + t.y);\n s = quickTwoSum(s.x, s.y);\n return s;\n}\n\nfn sub_fp64(a: vec2f, b: vec2f) -> vec2f {\n var s = twoSub(a.x, b.x);\n let t = twoSub(a.y, b.y);\n s.y = prevent_fp64_optimization(s.y + t.x);\n s = quickTwoSum(s.x, s.y);\n s.y = prevent_fp64_optimization(s.y + t.y);\n s = quickTwoSum(s.x, s.y);\n return s;\n}\n\nfn mul_fp64(a: vec2f, b: vec2f) -> vec2f {\n var prod = twoProd(a.x, b.x);\n let crossProduct1 = prevent_fp64_optimization(a.x * b.y);\n prod.y = prevent_fp64_optimization(prod.y + crossProduct1);\n#ifdef LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND\n prod = split2(prod);\n#endif\n prod = quickTwoSum(prod.x, prod.y);\n let crossProduct2 = prevent_fp64_optimization(a.y * b.x);\n prod.y = prevent_fp64_optimization(prod.y + crossProduct2);\n#ifdef LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND\n prod = split2(prod);\n#endif\n prod = quickTwoSum(prod.x, prod.y);\n return prod;\n}\n\n#ifndef LUMA_FP64_PREDICATE_ONLY\nfn div_fp64(a: vec2f, b: vec2f) -> vec2f {\n let xn = prevent_fp64_optimization(1.0 / b.x);\n let yn = mul_fp64(a, vec2f(xn, fp64_runtime_zero()));\n let diff = prevent_fp64_optimization(sub_fp64(a, mul_fp64(b, yn)).x);\n let prod = twoProd(xn, diff);\n return sum_fp64(yn, prod);\n}\n\nfn sqrt_fp64(a: vec2f) -> vec2f {\n if (a.x == 0.0 && a.y == 0.0) {\n return vec2f(0.0, 0.0);\n }\n if (a.x < 0.0) {\n let nanValue = fp64_nan(a.x);\n return vec2f(nanValue, nanValue);\n }\n\n let x = prevent_fp64_optimization(1.0 / sqrt(a.x));\n let yn = prevent_fp64_optimization(a.x * x);\n#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND\n let ynSqr = twoSqr(yn) * fp64arithmetic.ONE;\n#else\n let ynSqr = twoSqr(yn);\n#endif\n let diff = prevent_fp64_optimization(sub_fp64(a, ynSqr).x);\n let prod = twoProd(prevent_fp64_optimization(x * 0.5), diff);\n#ifdef LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND\n return sum_fp64(split(yn), prod);\n#else\n return sum_fp64(vec2f(yn, 0.0), prod);\n#endif\n}\n#endif\n#endif\n\n#ifndef LUMA_FP64_PREDICATE_ONLY\nfn fp64_f32_bits_is_nan(bits: u32) -> bool {\n return (bits & 0x7fffffffu) > 0x7f800000u;\n}\n\nfn fp64_f32_bits_is_inf(bits: u32) -> bool {\n return (bits & 0x7fffffffu) == 0x7f800000u;\n}\n\nfn fp64_compare_f32_bits(aBits: u32, bBits: u32) -> i32 {\n let aMagnitude = aBits & 0x7fffffffu;\n let bMagnitude = bBits & 0x7fffffffu;\n if (aMagnitude == 0u && bMagnitude == 0u) {\n return 0;\n }\n let aSign = aBits >> 31u;\n let bSign = bBits >> 31u;\n if (aSign != bSign) {\n return select(1, -1, aSign == 1u);\n }\n if (aMagnitude == bMagnitude) {\n return 0;\n }\n let magnitudeComparison = select(-1, 1, aMagnitude > bMagnitude);\n return select(magnitudeComparison, -magnitudeComparison, aSign == 1u);\n}\n\n// Normalize an arbitrary pair of finite f32 limbs with integer accumulation.\n// This is independent of LUMA_FP64_INTEGER_ARITHMETIC and canonicalizes every\n// representation of zero to vec2f(+0.0, +0.0).\nfn normalize_fp64(value: vec2f) -> vec2f {\n let resultBits = fp64_add_raw_f32_bits(bitcast<u32>(value.x), bitcast<u32>(value.y));\n return vec2f(bitcast<f32>(resultBits.x), bitcast<f32>(resultBits.y));\n}\n\nfn is_nan_fp64(value: vec2f) -> bool {\n let normalized = normalize_fp64(value);\n return fp64_f32_bits_is_nan(bitcast<u32>(normalized.x)) ||\n fp64_f32_bits_is_nan(bitcast<u32>(normalized.y));\n}\n\nfn is_finite_fp64(value: vec2f) -> bool {\n let normalized = normalize_fp64(value);\n let highBits = bitcast<u32>(normalized.x);\n let lowBits = bitcast<u32>(normalized.y);\n return !fp64_f32_bits_is_nan(highBits) && !fp64_f32_bits_is_nan(lowBits) &&\n !fp64_f32_bits_is_inf(highBits) && !fp64_f32_bits_is_inf(lowBits);\n}\n\n// Returns -1, 0, or 1. NaN is unordered and returns 0; call is_nan_fp64 or\n// is_finite_fp64 first when 0 must mean a finite zero.\nfn sign_fp64(value: vec2f) -> i32 {\n let normalized = normalize_fp64(value);\n let highBits = bitcast<u32>(normalized.x);\n let lowBits = bitcast<u32>(normalized.y);\n if (fp64_f32_bits_is_nan(highBits) || fp64_f32_bits_is_nan(lowBits)) {\n return 0;\n }\n if ((highBits & 0x7fffffffu) != 0u) {\n return select(1, -1, (highBits >> 31u) == 1u);\n }\n if ((lowBits & 0x7fffffffu) != 0u) {\n return select(1, -1, (lowBits >> 31u) == 1u);\n }\n return 0;\n}\n\n// Compares double-single values and returns -1, 0, or 1. NaN is unordered\n// and returns 0; callers that require equality semantics must first check\n// is_nan_fp64 or is_finite_fp64.\nfn compare_fp64(a: vec2f, b: vec2f) -> i32 {\n let normalizedA = normalize_fp64(a);\n let normalizedB = normalize_fp64(b);\n let aHighBits = bitcast<u32>(normalizedA.x);\n let aLowBits = bitcast<u32>(normalizedA.y);\n let bHighBits = bitcast<u32>(normalizedB.x);\n let bLowBits = bitcast<u32>(normalizedB.y);\n if (fp64_f32_bits_is_nan(aHighBits) || fp64_f32_bits_is_nan(aLowBits) ||\n fp64_f32_bits_is_nan(bHighBits) || fp64_f32_bits_is_nan(bLowBits)) {\n return 0;\n }\n let highComparison = fp64_compare_f32_bits(aHighBits, bHighBits);\n if (highComparison != 0) {\n return highComparison;\n }\n return fp64_compare_f32_bits(aLowBits, bLowBits);\n}\n#endif\n",fs:Le,vs:Le,defaultUniforms:{ONE:1,SPLIT:4097},uniformTypes:{ONE:"f32",SPLIT:"f32"},fp64ify:Ce,fp64LowPart:function(e){return e-Math.fround(e)},fp64ifyMatrix4:function(e){const t=/* @__PURE__ */new Float32Array(32);for(let n=0;n<4;++n)for(let i=0;i<4;++i){const o=4*n+i;Ce(e[4*i+n],t,2*o)}return t}},Ie={rgba8unorm:4,rgba16float:8,rgba32float:16},Ee=(Uint32Array.BYTES_PER_ELEMENT,Te("colors"),Te("floatColors"));Oe("colors");function Te(e){return`layout(std140) uniform ${e}Uniforms {\n float useByteColors;\n} ${e};\n\nvec3 ${e}_normalize(vec3 inputColor) {\n return ${e}.useByteColors > 0.5 ? inputColor / 255.0 : inputColor;\n}\n\nvec4 ${e}_normalize(vec4 inputColor) {\n return ${e}.useByteColors > 0.5 ? inputColor / 255.0 : inputColor;\n}\n\nvec4 ${e}_premultiplyAlpha(vec4 inputColor) {\n return vec4(inputColor.rgb * inputColor.a, inputColor.a);\n}\n\nvec4 ${e}_unpremultiplyAlpha(vec4 inputColor) {\n return inputColor.a > 0.0 ? vec4(inputColor.rgb / inputColor.a, inputColor.a) : vec4(0.0);\n}\n\nvec4 ${e}_premultiply_alpha(vec4 inputColor) {\n return ${e}_premultiplyAlpha(inputColor);\n}\n\nvec4 ${e}_unpremultiply_alpha(vec4 inputColor) {\n return ${e}_unpremultiplyAlpha(inputColor);\n}\n`}function Oe(e){return`struct ${e}Uniforms {\n useByteColors: f32\n};\n\n@group(0) @binding(auto) var<uniform> ${e} : ${e}Uniforms;\n\nfn ${e}_normalize(inputColor: vec3<f32>) -> vec3<f32> {\n return select(inputColor, inputColor / 255.0, ${e}.useByteColors > 0.5);\n}\n\nfn ${e}_normalize4(inputColor: vec4<f32>) -> vec4<f32> {\n return select(inputColor, inputColor / 255.0, ${e}.useByteColors > 0.5);\n}\n\nfn ${e}_premultiplyAlpha(inputColor: vec4<f32>) -> vec4<f32> {\n return vec4<f32>(inputColor.rgb * inputColor.a, inputColor.a);\n}\n\nfn ${e}_unpremultiplyAlpha(inputColor: vec4<f32>) -> vec4<f32> {\n return select(\n vec4<f32>(0.0),\n vec4<f32>(inputColor.rgb / inputColor.a, inputColor.a),\n inputColor.a > 0.0\n );\n}\n\nfn ${e}_premultiply_alpha(inputColor: vec4<f32>) -> vec4<f32> {\n return ${e}_premultiplyAlpha(inputColor);\n}\n\nfn ${e}_unpremultiply_alpha(inputColor: vec4<f32>) -> vec4<f32> {\n return ${e}_unpremultiplyAlpha(inputColor);\n}\n`}var ze={name:"floatColors",props:{},uniforms:{},vs:Ee,fs:Ee,source:Oe("floatColors"),uniformTypes:{useByteColors:"f32"},defaultUniforms:{useByteColors:!0}},Me={props:{},uniforms:{},name:"picking",uniformTypes:{isActive:"f32",isAttribute:"f32",isHighlightActive:"f32",useByteColors:"f32",highlightedObjectColor:"vec3<f32>",highlightColor:"vec4<f32>"},defaultUniforms:{isActive:!1,isAttribute:!1,isHighlightActive:!1,useByteColors:!0,highlightedObjectColor:[0,0,0],highlightColor:[0,1,1,1]},vs:"layout(std140) uniform pickingUniforms {\n float isActive;\n float isAttribute;\n float isHighlightActive;\n float useByteColors;\n vec3 highlightedObjectColor;\n vec4 highlightColor;\n} picking;\n\nout vec4 picking_vRGBcolor_Avalid;\n\n// Normalize unsigned byte color to 0-1 range\nvec3 picking_normalizeColor(vec3 color) {\n return picking.useByteColors > 0.5 ? color / 255.0 : color;\n}\n\n// Normalize unsigned byte color to 0-1 range\nvec4 picking_normalizeColor(vec4 color) {\n return picking.useByteColors > 0.5 ? color / 255.0 : color;\n}\n\nbool picking_isColorZero(vec3 color) {\n return dot(color, vec3(1.0)) < 0.00001;\n}\n\nbool picking_isColorValid(vec3 color) {\n return dot(color, vec3(1.0)) > 0.00001;\n}\n\n// Check if this vertex is highlighted \nbool isVertexHighlighted(vec3 vertexColor) {\n vec3 highlightedObjectColor = picking_normalizeColor(picking.highlightedObjectColor);\n return\n bool(picking.isHighlightActive) && picking_isColorZero(abs(vertexColor - highlightedObjectColor));\n}\n\n// Set the current picking color\nvoid picking_setPickingColor(vec3 pickingColor) {\n pickingColor = picking_normalizeColor(pickingColor);\n\n if (bool(picking.isActive)) {\n // Use alpha as the validity flag. If pickingColor is [0, 0, 0] fragment is non-pickable\n picking_vRGBcolor_Avalid.a = float(picking_isColorValid(pickingColor));\n\n if (!bool(picking.isAttribute)) {\n // Stores the picking color so that the fragment shader can render it during picking\n picking_vRGBcolor_Avalid.rgb = pickingColor;\n }\n } else {\n // Do the comparison with selected item color in vertex shader as it should mean fewer compares\n picking_vRGBcolor_Avalid.a = float(isVertexHighlighted(pickingColor));\n }\n}\n\nvoid picking_setPickingAttribute(float value) {\n if (bool(picking.isAttribute)) {\n picking_vRGBcolor_Avalid.r = value;\n }\n}\n\nvoid picking_setPickingAttribute(vec2 value) {\n if (bool(picking.isAttribute)) {\n picking_vRGBcolor_Avalid.rg = value;\n }\n}\n\nvoid picking_setPickingAttribute(vec3 value) {\n if (bool(picking.isAttribute)) {\n picking_vRGBcolor_Avalid.rgb = value;\n }\n}\n",fs:"layout(std140) uniform pickingUniforms {\n float isActive;\n float isAttribute;\n float isHighlightActive;\n float useByteColors;\n vec3 highlightedObjectColor;\n vec4 highlightColor;\n} picking;\n\nin vec4 picking_vRGBcolor_Avalid;\n\n/*\n * Returns highlight color if this item is selected.\n */\nvec4 picking_filterHighlightColor(vec4 color) {\n // If we are still picking, we don't highlight\n if (picking.isActive > 0.5) {\n return color;\n }\n\n bool selected = bool(picking_vRGBcolor_Avalid.a);\n\n if (selected) {\n // Blend in highlight color based on its alpha value\n float highLightAlpha = picking.highlightColor.a;\n float blendedAlpha = highLightAlpha + color.a * (1.0 - highLightAlpha);\n float highLightRatio = highLightAlpha / blendedAlpha;\n\n vec3 blendedRGB = mix(color.rgb, picking.highlightColor.rgb, highLightRatio);\n return vec4(blendedRGB, blendedAlpha);\n } else {\n return color;\n }\n}\n\n/*\n * Returns picking color if picking enabled else unmodified argument.\n */\nvec4 picking_filterPickingColor(vec4 color) {\n if (bool(picking.isActive)) {\n if (picking_vRGBcolor_Avalid.a == 0.0) {\n discard;\n }\n return picking_vRGBcolor_Avalid;\n }\n return color;\n}\n\n/*\n * Returns picking color if picking is enabled if not\n * highlight color if this item is selected, otherwise unmodified argument.\n */\nvec4 picking_filterColor(vec4 color) {\n vec4 highlightColor = picking_filterHighlightColor(color);\n return picking_filterPickingColor(highlightColor);\n}\n",getUniforms:function(e={},t){const n={},i=we(e.useByteColors,!0);void 0===e.highlightedObjectColor||(null===e.highlightedObjectColor?n.isHighlightActive=!1:(n.isHighlightActive=!0,n.highlightedObjectColor=e.highlightedObjectColor.slice(0,3)));e.highlightColor&&(n.highlightColor=function(e,t=!0){const n=Se(e.slice(0,3),t),i=Number.isFinite(e[3]),o=i?e[3]:1;return[n[0],n[1],n[2],t&&i?o/255:o]}(e.highlightColor,i));void 0!==e.isActive&&(n.isActive=Boolean(e.isActive),n.isAttribute=Boolean(e.isAttribute));void 0!==e.useByteColors&&(n.useByteColors=Boolean(e.useByteColors));return n}};var Re="precision highp int;\n\n// #if (defined(SHADER_TYPE_FRAGMENT) && defined(LIGHTING_FRAGMENT)) || (defined(SHADER_TYPE_VERTEX) && defined(LIGHTING_VERTEX))\nstruct AmbientLight {\n vec3 color;\n};\n\nstruct PointLight {\n vec3 color;\n vec3 position;\n vec3 attenuation; // 2nd order x:Constant-y:Linear-z:Exponential\n};\n\nstruct SpotLight {\n vec3 color;\n vec3 position;\n vec3 direction;\n vec3 attenuation;\n vec2 coneCos;\n};\n\nstruct DirectionalLight {\n vec3 color;\n vec3 direction;\n};\n\nstruct UniformLight {\n vec3 color;\n vec3 position;\n vec3 direction;\n vec3 attenuation;\n vec2 coneCos;\n};\n\nlayout(std140) uniform lightingUniforms {\n int enabled;\n int directionalLightCount;\n int pointLightCount;\n int spotLightCount;\n vec3 ambientColor;\n UniformLight lights[5];\n} lighting;\n\nPointLight lighting_getPointLight(int index) {\n UniformLight light = lighting.lights[index];\n return PointLight(light.color, light.position, light.attenuation);\n}\n\nSpotLight lighting_getSpotLight(int index) {\n UniformLight light = lighting.lights[lighting.pointLightCount + index];\n return SpotLight(light.color, light.position, light.direction, light.attenuation, light.coneCos);\n}\n\nDirectionalLight lighting_getDirectionalLight(int index) {\n UniformLight light =\n lighting.lights[lighting.pointLightCount + lighting.spotLightCount + index];\n return DirectionalLight(light.color, light.direction);\n}\n\nfloat getPointLightAttenuation(PointLight pointLight, float distance) {\n return pointLight.attenuation.x\n + pointLight.attenuation.y * distance\n + pointLight.attenuation.z * distance * distance;\n}\n\nfloat getSpotLightAttenuation(SpotLight spotLight, vec3 positionWorldspace) {\n vec3 light_direction = normalize(positionWorldspace - spotLight.position);\n float coneFactor = smoothstep(\n spotLight.coneCos.y,\n spotLight.coneCos.x,\n dot(normalize(spotLight.direction), light_direction)\n );\n float distanceAttenuation = getPointLightAttenuation(\n PointLight(spotLight.color, spotLight.position, spotLight.attenuation),\n distance(spotLight.position, positionWorldspace)\n );\n return distanceAttenuation / max(coneFactor, 0.0001);\n}\n\n// #endif\n",Be={props:{},uniforms:{},name:"lighting",defines:{},uniformTypes:{enabled:"i32",directionalLightCount:"i32",pointLightCount:"i32",spotLightCount:"i32",ambientColor:"vec3<f32>",lights:[{color:"vec3<f32>",position:"vec3<f32>",direction:"vec3<f32>",attenuation:"vec3<f32>",coneCos:"vec2<f32>"},5]},defaultUniforms:De(),bindingLayout:[{name:"lighting",group:2}],firstBindingSlot:0,source:"// #if (defined(SHADER_TYPE_FRAGMENT) && defined(LIGHTING_FRAGMENT)) || (defined(SHADER_TYPE_VERTEX) && defined(LIGHTING_VERTEX))\nconst MAX_LIGHTS: i32 = 5;\n\nstruct AmbientLight {\n color: vec3<f32>,\n};\n\nstruct PointLight {\n color: vec3<f32>,\n position: vec3<f32>,\n attenuation: vec3<f32>, // 2nd order x:Constant-y:Linear-z:Exponential\n};\n\nstruct SpotLight {\n color: vec3<f32>,\n position: vec3<f32>,\n direction: vec3<f32>,\n attenuation: vec3<f32>,\n coneCos: vec2<f32>,\n};\n\nstruct DirectionalLight {\n color: vec3<f32>,\n direction: vec3<f32>,\n};\n\nstruct UniformLight {\n color: vec3<f32>,\n position: vec3<f32>,\n direction: vec3<f32>,\n attenuation: vec3<f32>,\n coneCos: vec2<f32>,\n};\n\nstruct lightingUniforms {\n enabled: i32,\n directionalLightCount: i32,\n pointLightCount: i32,\n spotLightCount: i32,\n ambientColor: vec3<f32>,\n lights: array<UniformLight, 5>,\n};\n\n@group(2) @binding(auto) var<uniform> lighting : lightingUniforms;\n\nfn lighting_getPointLight(index: i32) -> PointLight {\n let light = lighting.lights[index];\n return PointLight(light.color, light.position, light.attenuation);\n}\n\nfn lighting_getSpotLight(index: i32) -> SpotLight {\n let light = lighting.lights[lighting.pointLightCount + index];\n return SpotLight(light.color, light.position, light.direction, light.attenuation, light.coneCos);\n}\n\nfn lighting_getDirectionalLight(index: i32) -> DirectionalLight {\n let light = lighting.lights[lighting.pointLightCount + lighting.spotLightCount + index];\n return DirectionalLight(light.color, light.direction);\n}\n\nfn getPointLightAttenuation(pointLight: PointLight, distance: f32) -> f32 {\n return pointLight.attenuation.x\n + pointLight.attenuation.y * distance\n + pointLight.attenuation.z * distance * distance;\n}\n\nfn getSpotLightAttenuation(spotLight: SpotLight, positionWorldspace: vec3<f32>) -> f32 {\n let lightDirection = normalize(positionWorldspace - spotLight.position);\n let coneFactor = smoothstep(\n spotLight.coneCos.y,\n spotLight.coneCos.x,\n dot(normalize(spotLight.direction), lightDirection)\n );\n let distanceAttenuation = getPointLightAttenuation(\n PointLight(spotLight.color, spotLight.position, spotLight.attenuation),\n distance(spotLight.position, positionWorldspace)\n );\n return distanceAttenuation / max(coneFactor, 0.0001);\n}\n",vs:Re,fs:Re,getUniforms:function(e,t={}){if(!(e=e?{...e}:e))return De();e.lights&&(e={...e,...Fe(e.lights),lights:void 0});const{useByteColors:n,ambientLight:i,pointLights:o,spotLights:s,directionalLights:r}=e||{};if(!(i||o&&o.length>0||s&&s.length>0||r&&r.length>0))return{...De(),enabled:0};const a={...De(),...ke({useByteColors:n,ambientLight:i,pointLights:o,spotLights:s,directionalLights:r})};void 0!==e.enabled&&(a.enabled=e.enabled?1:0);return a}};function ke({useByteColors:e,ambientLight:t,pointLights:n=[],spotLights:i=[],directionalLights:o=[]}){const s=je();let r=0,a=0,l=0,c=0;for(const u of n){if(r>=5)break;s[r]={...s[r],color:Ne(u,e),position:u.position,attenuation:u.attenuation||[1,0,0]},r++,a++}for(const u of i){if(r>=5)break;s[r]={...s[r],color:Ne(u,e),position:u.position,direction:u.direction,attenuation:u.attenuation||[1,0,0],coneCos:Ue(u)},r++,l++}for(const u of o){if(r>=5)break;s[r]={...s[r],color:Ne(u,e),direction:u.direction},r++,c++}return n.length+i.length+o.length>5&&j.warn("MAX_LIGHTS exceeded, truncating to 5")(),{ambientColor:Ne(t,e),directionalLightCount:c,pointLightCount:a,spotLightCount:l,lights:s}}function Fe(e){const t={pointLights:[],spotLights:[],directionalLights:[]};for(const n of e||[])switch(n.type){case"ambient":t.ambientLight=n;break;case"directional":t.directionalLights?.push(n);break;case"point":t.pointLights?.push(n);break;case"spot":t.spotLights?.push(n)}return t}function Ne(e={},t){const{color:n=[0,0,0],intensity:i=1}=e;return Se(n,we(t,!0)).map(e=>e*i)}function De(){return{enabled:1,directionalLightCount:0,pointLightCount:0,spotLightCount:0,ambientColor:[.1,.1,.1],lights:je()}}function je(){return Array.from({length:5},()=>({color:[1,1,1],position:[1,1,2],direction:[1,1,1],attenuation:[1,0,0],coneCos:[1,0]}))}function Ue(e){const t=e.innerConeAngle??0,n=e.outerConeAngle??Math.PI/4;return[Math.cos(t),Math.cos(n)]}var Ge="layout(std140) uniform phongMaterialUniforms {\n uniform bool unlit;\n uniform float ambient;\n uniform float diffuse;\n uniform float shininess;\n uniform vec3 specularColor;\n} material;\n",Ve="layout(std140) uniform phongMaterialUniforms {\n uniform bool unlit;\n uniform float ambient;\n uniform float diffuse;\n uniform float shininess;\n uniform vec3 specularColor;\n} material;\n\nvec3 lighting_getLightColor(vec3 surfaceColor, vec3 light_direction, vec3 view_direction, vec3 normal_worldspace, vec3 color) {\n vec3 halfway_direction = normalize(light_direction + view_direction);\n float lambertian = dot(light_direction, normal_worldspace);\n float specular = 0.0;\n if (lambertian > 0.0) {\n float specular_angle = max(dot(normal_worldspace, halfway_direction), 0.0);\n specular = pow(specular_angle, material.shininess);\n }\n lambertian = max(lambertian, 0.0);\n return (lambertian * material.diffuse * surfaceColor + specular * floatColors_normalize(material.specularColor)) * color;\n}\n\nvec3 lighting_getLightColor(vec3 surfaceColor, vec3 cameraPosition, vec3 position_worldspace, vec3 normal_worldspace) {\n vec3 lightColor = surfaceColor;\n\n if (material.unlit) {\n return surfaceColor;\n }\n\n if (lighting.enabled == 0) {\n return lightColor;\n }\n\n vec3 view_direction = normalize(cameraPosition - position_worldspace);\n lightColor = material.ambient * surfaceColor * lighting.ambientColor;\n\n for (int i = 0; i < lighting.pointLightCount; i++) {\n PointLight pointLight = lighting_getPointLight(i);\n vec3 light_position_worldspace = pointLight.position;\n vec3 light_direction = normalize(light_position_worldspace - position_worldspace);\n float light_attenuation = getPointLightAttenuation(pointLight, distance(light_position_worldspace, position_worldspace));\n lightColor += lighting_getLightColor(surfaceColor, light_direction, view_direction, normal_worldspace, pointLight.color / light_attenuation);\n }\n\n for (int i = 0; i < lighting.spotLightCount; i++) {\n SpotLight spotLight = lighting_getSpotLight(i);\n vec3 light_position_worldspace = spotLight.position;\n vec3 light_direction = normalize(light_position_worldspace - position_worldspace);\n float light_attenuation = getSpotLightAttenuation(spotLight, position_worldspace);\n lightColor += lighting_getLightColor(surfaceColor, light_direction, view_direction, normal_worldspace, spotLight.color / light_attenuation);\n }\n\n for (int i = 0; i < lighting.directionalLightCount; i++) {\n DirectionalLight directionalLight = lighting_getDirectionalLight(i);\n lightColor += lighting_getLightColor(surfaceColor, -directionalLight.direction, view_direction, normal_worldspace, directionalLight.color);\n }\n \n return lightColor;\n}\n",$e="struct phongMaterialUniforms {\n unlit: u32,\n ambient: f32,\n diffuse: f32,\n shininess: f32,\n specularColor: vec3<f32>,\n};\n\n@group(3) @binding(auto) var<uniform> phongMaterial : phongMaterialUniforms;\n\nfn lighting_getLightColor(surfaceColor: vec3<f32>, light_direction: vec3<f32>, view_direction: vec3<f32>, normal_worldspace: vec3<f32>, color: vec3<f32>) -> vec3<f32> {\n let halfway_direction: vec3<f32> = normalize(light_direction + view_direction);\n var lambertian: f32 = dot(light_direction, normal_worldspace);\n var specular: f32 = 0.0;\n if (lambertian > 0.0) {\n let specular_angle = max(dot(normal_worldspace, halfway_direction), 0.0);\n specular = pow(specular_angle, phongMaterial.shininess);\n }\n lambertian = max(lambertian, 0.0);\n return (\n lambertian * phongMaterial.diffuse * surfaceColor +\n specular * floatColors_normalize(phongMaterial.specularColor)\n ) * color;\n}\n\nfn lighting_getLightColor2(surfaceColor: vec3<f32>, cameraPosition: vec3<f32>, position_worldspace: vec3<f32>, normal_worldspace: vec3<f32>) -> vec3<f32> {\n var lightColor: vec3<f32> = surfaceColor;\n\n if (phongMaterial.unlit != 0u) {\n return surfaceColor;\n }\n\n if (lighting.enabled == 0) {\n return lightColor;\n }\n\n let view_direction: vec3<f32> = normalize(cameraPosition - position_worldspace);\n lightColor = phongMaterial.ambient * surfaceColor * lighting.ambientColor;\n\n for (var i: i32 = 0; i < lighting.pointLightCount; i++) {\n let pointLight: PointLight = lighting_getPointLight(i);\n let light_position_worldspace: vec3<f32> = pointLight.position;\n let light_direction: vec3<f32> = normalize(light_position_worldspace - position_worldspace);\n let light_attenuation = getPointLightAttenuation(\n pointLight,\n distance(light_position_worldspace, position_worldspace)\n );\n lightColor += lighting_getLightColor(\n surfaceColor,\n light_direction,\n view_direction,\n normal_worldspace,\n pointLight.color / light_attenuation\n );\n }\n\n for (var i: i32 = 0; i < lighting.spotLightCount; i++) {\n let spotLight: SpotLight = lighting_getSpotLight(i);\n let light_position_worldspace: vec3<f32> = spotLight.position;\n let light_direction: vec3<f32> = normalize(light_position_worldspace - position_worldspace);\n let light_attenuation = getSpotLightAttenuation(spotLight, position_worldspace);\n lightColor += lighting_getLightColor(\n surfaceColor,\n light_direction,\n view_direction,\n normal_worldspace,\n spotLight.color / light_attenuation\n );\n }\n\n for (var i: i32 = 0; i < lighting.directionalLightCount; i++) {\n let directionalLight: DirectionalLight = lighting_getDirectionalLight(i);\n lightColor += lighting_getLightColor(surfaceColor, -directionalLight.direction, view_direction, normal_worldspace, directionalLight.color);\n } \n \n return lightColor;\n}\n\nfn lighting_getSpecularLightColor(cameraPosition: vec3<f32>, position_worldspace: vec3<f32>, normal_worldspace: vec3<f32>) -> vec3<f32>{\n var lightColor = vec3<f32>(0, 0, 0);\n let surfaceColor = vec3<f32>(0, 0, 0);\n\n if (lighting.enabled != 0) {\n let view_direction = normalize(cameraPosition - position_worldspace);\n\n for (var i: i32 = 0; i < lighting.pointLightCount; i++) {\n let pointLight: PointLight = lighting_getPointLight(i);\n let light_position_worldspace: vec3<f32> = pointLight.position;\n let light_direction: vec3<f32> = normalize(light_position_worldspace - position_worldspace);\n let light_attenuation = getPointLightAttenuation(\n pointLight,\n distance(light_position_worldspace, position_worldspace)\n );\n lightColor += lighting_getLightColor(\n surfaceColor,\n light_direction,\n view_direction,\n normal_worldspace,\n pointLight.color / light_attenuation\n );\n }\n\n for (var i: i32 = 0; i < lighting.spotLightCount; i++) {\n let spotLight: SpotLight = lighting_getSpotLight(i);\n let light_position_worldspace: vec3<f32> = spotLight.position;\n let light_direction: vec3<f32> = normalize(light_position_worldspace - position_worldspace);\n let light_attenuation = getSpotLightAttenuation(spotLight, position_worldspace);\n lightColor += lighting_getLightColor(\n surfaceColor,\n light_direction,\n view_direction,\n normal_worldspace,\n spotLight.color / light_attenuation\n );\n }\n\n for (var i: i32 = 0; i < lighting.directionalLightCount; i++) {\n let directionalLight: DirectionalLight = lighting_getDirectionalLight(i);\n lightColor += lighting_getLightColor(surfaceColor, -directionalLight.direction, view_direction, normal_worldspace, directionalLight.color);\n }\n }\n return lightColor;\n}\n",We={props:{},name:"gouraudMaterial",bindingLayout:[{name:"gouraudMaterial",group:3}],vs:Ve.replace("phongMaterial","gouraudMaterial"),fs:Ge.replace("phongMaterial","gouraudMaterial"),source:$e.replaceAll("phongMaterial","gouraudMaterial"),defines:{LIGHTING_VERTEX:!0},dependencies:[Be,ze],uniformTypes:{unlit:"i32",ambient:"f32",diffuse:"f32",shininess:"f32",specularColor:"vec3<f32>"},defaultUniforms:{unlit:!1,ambient:.35,diffuse:.6,shininess:32,specularColor:[38.25,38.25,38.25]},getUniforms:e=>({...We.defaultUniforms,...e})},He={name:"phongMaterial",firstBindingSlot:0,bindingLayout:[{name:"phongMaterial",group:3}],dependencies:[Be,ze],source:$e,vs:Ge,fs:Ve,defines:{LIGHTING_FRAGMENT:!0},uniformTypes:{unlit:"i32",ambient:"f32",diffuse:"f32",shininess:"f32",specularColor:"vec3<f32>"},defaultUniforms:{unlit:!1,ambient:.35,diffuse:.6,shininess:32,specularColor:[38.25,38.25,38.25]},getUniforms:e=>({...He.defaultUniforms,...e})},Ze={name:"color",dependencies:[],source:"\n\n@must_use\nfn deckgl_premultiplied_alpha(fragColor: vec4<f32>) -> vec4<f32> {\n return vec4(fragColor.rgb * fragColor.a, fragColor.a); \n};\n",getUniforms:e=>({})},Ye={name:"project32",dependencies:[l],source:"// Define a structure to hold both the clip-space position and the common position.\nstruct ProjectResult {\n clipPosition: vec4<f32>,\n commonPosition: vec4<f32>,\n};\n\n// This function mimics the GLSL version with the 'out' parameter by returning both values.\nfn project_position_to_clipspace_and_commonspace(\n position: vec3<f32>,\n position64Low: vec3<f32>,\n offset: vec3<f32>\n) -> ProjectResult {\n // Compute the projected position.\n let projectedPosition: vec3<f32> = project_position_vec3_f64(position, position64Low);\n\n // Start with the provided offset.\n var finalOffset: vec3<f32> = offset;\n\n // Get whether a rotation is needed and the rotation matrix.\n let rotationResult = project_needs_rotation(projectedPosition);\n\n // If rotation is needed, update the offset.\n if (rotationResult.needsRotation) {\n finalOffset = rotationResult.transform * offset;\n }\n\n // Compute the common position.\n let commonPosition: vec4<f32> = vec4<f32>(projectedPosition + finalOffset, 1.0);\n\n // Convert to clip-space.\n let clipPosition: vec4<f32> = project_common_position_to_clipspace(commonPosition);\n\n return ProjectResult(clipPosition, commonPosition);\n}\n\n// A convenience overload that returns only the clip-space position.\nfn project_position_to_clipspace(\n position: vec3<f32>,\n position64Low: vec3<f32>,\n offset: vec3<f32>\n) -> vec4<f32> {\n return project_position_to_clipspace_and_commonspace(position, position64Low, offset).clipPosition;\n}\n",vs:"vec4 project_position_to_clipspace(\n vec3 position, vec3 position64Low, vec3 offset, out vec4 commonPosition\n) {\n vec3 projectedPosition = project_position(position, position64Low);\n mat3 rotation;\n if (project_needs_rotation(projectedPosition, rotation)) {\n // offset is specified as ENU\n // when in globe projection, rotate offset so that the ground alighs with the surface of the globe\n offset = rotation * offset;\n }\n commonPosition = vec4(projectedPosition + offset, 1.0);\n return project_common_position_to_clipspace(commonPosition);\n}\n\nvec4 project_position_to_clipspace(\n vec3 position, vec3 position64Low, vec3 offset\n) {\n vec4 commonPosition;\n return project_position_to_clipspace(position, position64Low, offset, commonPosition);\n}\n"},qe=16777215;function Ke(e){return e.replace(" vec4 highlightColor;\n} picking;"," vec4 highlightColor;\n float disabledPickingIndexCount;\n vec4 disabledPickingIndices0;\n vec4 disabledPickingIndices1;\n vec4 disabledPickingIndices2;\n} picking;")}function Xe(e,t){return[e[t]||0,e[t+1]||0,e[t+2]||0,e[t+3]||0]}var Je={...Me,vs:`${Ke(Me.vs)}\nvec3 picking_getPickingColorFromIndex(float objectIndex) {\n if (objectIndex < 0.0 || objectIndex >= 16777215.0) {\n return vec3(0.0);\n }\n\n for (int i = 0; i < 10; i++) {\n if (float(i) >= picking.disabledPickingIndexCount) {\n break;\n }\n vec4 disabledIndices = i < 4\n ? picking.disabledPickingIndices0\n : (i < 8 ? picking.disabledPickingIndices1 : picking.disabledPickingIndices2);\n float disabledIndex = disabledIndices[i - (i / 4) * 4];\n if (disabledIndex == objectIndex) {\n return vec3(0.0);\n }\n }\n\n float encodedIndex = objectIndex + 1.0;\n return vec3(\n mod(encodedIndex, 256.0),\n mod(floor(encodedIndex / 256.0), 256.0),\n mod(floor(encodedIndex / 65536.0), 256.0)\n );\n}\n\nvec3 picking_getPickingColorFromIndex(uint objectIndex) {\n return picking_getPickingColorFromIndex(float(objectIndex));\n}\n\nvec3 picking_getPickingColorFromInstanceID() {\n return picking_getPickingColorFromIndex(float(gl_InstanceID));\n}\n\nvoid picking_setPickingColorFromInstanceID() {\n picking_setPickingColor(picking_getPickingColorFromInstanceID());\n}\n`,fs:Ke(Me.fs),source:"struct pickingUniforms {\n isActive: f32,\n isAttribute: f32,\n isHighlightActive: f32,\n useByteColors: f32,\n highlightedObjectColor: vec3<f32>,\n highlightColor: vec4<f32>,\n disabledPickingIndexCount: f32,\n disabledPickingIndices0: vec4<f32>,\n disabledPickingIndices1: vec4<f32>,\n disabledPickingIndices2: vec4<f32>,\n};\n\n@group(0) @binding(auto) var<uniform> picking: pickingUniforms;\n\nfn picking_normalizeColor(color: vec3<f32>) -> vec3<f32> {\n return select(color, color / 255.0, picking.useByteColors > 0.5);\n}\n\nfn picking_normalizeColor4(color: vec4<f32>) -> vec4<f32> {\n return select(color, color / 255.0, picking.useByteColors > 0.5);\n}\n\nfn picking_isColorZero(color: vec3<f32>) -> bool {\n return dot(color, vec3<f32>(1.0)) < 0.00001;\n}\n\nfn picking_isColorValid(color: vec3<f32>) -> bool {\n return dot(color, vec3<f32>(1.0)) > 0.00001;\n}\n\nfn picking_getPickingColorFromIndex(objectIndex: u32) -> vec3<f32> {\n if (objectIndex >= 16777215u) {\n return vec3<f32>(0.0);\n }\n\n for (var i = 0; i < 10; i = i + 1) {\n if (f32(i) >= picking.disabledPickingIndexCount) {\n break;\n }\n let disabledIndices = select(\n picking.disabledPickingIndices2,\n select(picking.disabledPickingIndices1, picking.disabledPickingIndices0, i < 4),\n i < 8\n );\n let disabledIndex = disabledIndices[i % 4];\n if (disabledIndex == f32(objectIndex)) {\n return vec3<f32>(0.0);\n }\n }\n\n let encodedIndex = objectIndex + 1u;\n return vec3<f32>(\n f32(encodedIndex % 256u),\n f32((encodedIndex / 256u) % 256u),\n f32((encodedIndex / 65536u) % 256u)\n ) / 255.0;\n}\n",uniformTypes:{...Me.uniformTypes,disabledPickingIndexCount:"f32",disabledPickingIndices0:"vec4<f32>",disabledPickingIndices1:"vec4<f32>",disabledPickingIndices2:"vec4<f32>"},defaultUniforms:{...Me.defaultUniforms,useByteColors:!0,disabledPickingIndexCount:0,disabledPickingIndices0:[0,0,0,0],disabledPickingIndices1:[0,0,0,0],disabledPickingIndices2:[0,0,0,0]},getUniforms(e,t){const n=Me.getUniforms(e,t),i=e.disabledPickingIndices||[];return n.disabledPickingIndexCount=i.length,n.disabledPickingIndices0=Xe(i,0),n.disabledPickingIndices1=Xe(i,4),n.disabledPickingIndices2=Xe(i,8),n},inject:{"vs:DECKGL_FILTER_GL_POSITION":"\n // for picking depth values\n picking_setPickingAttribute(position.z / position.w);\n ","vs:DECKGL_FILTER_COLOR":"\n picking_setPickingColor(geometry.pickingColor);\n ","fs:DECKGL_FILTER_COLOR":{order:99,injection:"\n // use highlight color if this fragment belongs to the selected object.\n color = picking_filterHighlightColor(color);\n\n // use picking color if rendering to picking FBO.\n color = picking_filterPickingColor(color);\n "}}},Qe=[0,0,0];function et(e,t,n=!1){const i=t.projectPosition(e);if(n&&t instanceof g){const[n,o,s=0]=e;i[2]=s*t.getDistanceScales([n,o]).unitsPerMeter[2]}return i}function tt(e,{viewport:t,modelMatrix:n,coordinateSystem:i,coordinateOrigin:o,offsetMode:s}){let[r,a,l=0]=e;switch(n&&([r,a,l]=u([],[r,a,l,1],n)),i){case"default":return tt(e,{viewport:t,modelMatrix:n,coordinateSystem:t.isGeospatial?"lnglat":"cartesian",coordinateOrigin:o,offsetMode:s});case"lnglat":return et([r,a,l],t,s);case"lnglat-offsets":return et([r+o[0],a+o[1],l+(o[2]||0)],t,s);case"meter-offsets":return et(z(o,[r,a,l]),t,s);case"cartesian":return t.isGeospatial?[r+o[0],a+o[1],l+o[2]]:t.projectPosition([r,a,l]);default:throw new Error(`Invalid coordinateSystem: ${i}`)}}var nt=class{id;topology;vertexCount;indices;attributes;bufferLayout;userData={};constructor(e){const{attributes:t={},indices:n=null,vertexCount:i=null}=e;this.id=e.id||ee("geometry"),this.topology=e.topology,n&&(this.indices=ArrayBuffer.isView(n)?{value:n,size:1}:n),this.attributes={};for(const[o,s]of Object.entries(t)){const e=ArrayBuffer.isView(s)?{value:s}:s;if(!ArrayBuffer.isView(e.value))throw new Error(`${this._print(o)}: must be typed array or object with value as typed array`);if("POSITION"!==o&&"positions"!==o||e.size||(e.size=3),"indices"===o){if(this.indices)throw new Error("Multiple indices detected");this.indices=e}else{const t=it(o),n=Object.keys(this.attributes).find(e=>it(e)===t);n&&delete this.attributes[n],this.attributes[o]=e}}this.indices&&void 0!==this.indices.isIndexed&&(this.indices=Object.assign({},this.indices),delete this.indices.isIndexed),this.vertexCount=i||this._calculateVertexCount(this.attributes,this.indices),this.bufferLayout=e.bufferLayout||function(e){const t=[];for(const[n,i]of Object.entries(e)){if(!i)continue;const{value:e,size:o,normalized:s}=i;if(void 0===o)throw new Error(`Attribute ${n} is missing a size`);t.push({name:it(n),format:D.getVertexFormatFromAttribute(e,o,s)})}return t}(this.attributes)}getVertexCount(){return this.vertexCount}getAttributes(){return this.indices?{indices:this.indices,...this.attributes}:this.attributes}_print(e){return`Geometry ${this.id} attribute ${e}`}_setAttributes(e,t){return this}_calculateVertexCount(e,t){if(t)return t.value.length;let n=1/0;for(const i of Object.values(e)){if(!i)continue;const{value:e,size:t,constant:o}=i;!o&&e&&void 0!==t&&t>=1&&(n=Math.min(n,e.length/t))}return n}};function it(e){switch(e){case"POSITION":return"positions";case"NORMAL":return"normals";case"TEXCOORD_0":return"texCoords";case"TEXCOORD_1":return"texCoords1";case"COLOR_0":return"colors";default:return e}}function ot(e,t={}){const n=t.bufferName||"geometry";if(function(e,t){if(1!==e.bufferLayout.length)return!1;const n=e.bufferLayout[0];return n.name===t&&Boolean(n.attributes?.length)&&Boolean(e.attributes[t])}(e,n))return e;const i=t.minAttributeAlignment||4,o=function(e,t){return t?t.map(t=>[t,e.attributes[t]]):Object.entries(e.attributes)}(e,t.attributes),s=[];let r=0,a=1/0;for(const[u,f]of o){if(!f)continue;if(f.constant)throw new Error(`Attribute ${u} is constant`);const{value:e,size:t,normalized:n}=f;if(!ArrayBuffer.isView(e))throw new Error(`Attribute ${u} is missing typed array data`);if(void 0===t)throw new Error(`Attribute ${u} is missing a size`);const o=D.getVertexFormatFromAttribute(e,t,n),l=D.getVertexFormatInfo(o);r=rt(r,i),s.push({sourceName:u,attributeName:it(u),value:e,size:t,format:o,byteOffset:r,byteLength:l.byteLength}),r+=l.byteLength;const c=e.length/t;if(!Number.isInteger(c))throw new Error(`Attribute ${u} length is not divisible by size`);a=Math.min(a,c)}if(0===s.length||!Number.isFinite(a))throw new Error(`Geometry ${e.id} has no interleavable attributes`);const l=rt(r,i),c=new ArrayBuffer(a*l);for(const u of s)st(c,a,l,u);return new nt({id:e.id,topology:e.topology||"triangle-list",vertexCount:e.vertexCount,indices:e.indices,attributes:{[n]:{value:new Uint8Array(c),size:l,byteStride:l}},bufferLayout:[{name:n,stepMode:"vertex",byteStride:l,attributes:s.map(e=>({attribute:e.attributeName,format:e.format,byteOffset:e.byteOffset}))}]})}function st(e,t,n,i){const o=i.value.constructor,s=o.BYTES_PER_ELEMENT;if(i.byteOffset%s!==0||n%s!==0)throw new Error(`Attribute ${i.sourceName} is not aligned to its component type`);const r=new o(e),a=i.value,l=i.byteOffset/s,c=n/s;for(let u=0;u<t;u++){const e=u*i.size,t=u*c+l;for(let n=0;n<i.size;n++)r[t+n]=a[e+n]}}function rt(e,t){return Math.ceil(e/t)*t}var at=class{id;userData={};topology;bufferLayout=[];vertexCount;indices;attributes;constructor(e){if(this.id=e.id||ee("geometry"),this.topology=e.topology,this.indices=e.indices||null,this.attributes=e.attributes,this.vertexCount=e.vertexCount,this.bufferLayout=e.bufferLayout||[],this.indices&&!(this.indices.usage&U.INDEX))throw new Error("Index buffer must have INDEX usage")}destroy(){this.indices?.destroy();for(const e of Object.values(this.attributes))e.destroy()}getVertexCount(){return this.vertexCount}getAttributes(){return this.attributes}getIndexes(){return this.indices||null}_calculateVertexCount(e){return e.byteLength/12}};function lt(e,t){if(t instanceof at)return t;const n=ot(t),i=function(e,t){if(!t.indices)return;const n=t.indices.value;return e.createBuffer({usage:U.INDEX,data:n})}(e,n),{attributes:o,bufferLayout:s}=function(e,t){const n={};for(const[i,o]of Object.entries(t.attributes)){const s=t.bufferLayout.find(e=>e.name===i)?.name||it(i);o&&(n[s]=e.createBuffer({data:o.value,id:`${i}-buffer`}))}return{attributes:n,bufferLayout:t.bufferLayout,vertexCount:t.vertexCount}}(e,n);return new at({topology:n.topology||"triangle-list",bufferLayout:s,vertexCount:n.vertexCount,indices:i,attributes:o})}var ct="__debugFramebufferState";function ut(e,t,n){if("webgl"!==e.device.type)return;const i=(o=e.device,o.userData[ct]||={flushing:!1,queuedFramebuffers:[]},o.userData[ct]);var o;i.flushing||(!function(e){const t=e.props.framebuffer;return!t||null===t.handle}(e)?t&&"colorAttachments"in t&&null!==t.handle&&(i.queuedFramebuffers.includes(t)||i.queuedFramebuffers.push(t)):function(e,t,n){if(0===n.queuedFramebuffers.length)return;const{gl:i}=e.device,o=i.getParameter(36010),s=i.getParameter(36006),[r,a]=e.device.getDefaultCanvasContext().getDrawingBufferSize();let l=dt(t.top,8);const c=dt(t.left,8);n.flushing=!0;try{for(const e of n.queuedFramebuffers){const[n,o,s,u,f]=ft({framebuffer:e,targetWidth:r,targetHeight:a,topPx:l,leftPx:c,minimap:t.minimap});i.bindFramebuffer(36008,e.handle),i.bindFramebuffer(36009,null),i.blitFramebuffer(0,0,e.width,e.height,n,o,s,u,16384,9728),l+=f+8}}finally{i.bindFramebuffer(36008,o),i.bindFramebuffer(36009,s),n.flushing=!1}}(e,n,i))}function ft(e){const{framebuffer:t,targetWidth:n,targetHeight:i,topPx:o,leftPx:s,minimap:r}=e,a=r?Math.max(Math.floor(n/4),1):n,l=r?Math.max(Math.floor(i/4),1):i,c=Math.min(a/t.width,l/t.height),u=Math.max(Math.floor(t.width*c),1),f=Math.max(Math.floor(t.height*c),1),d=s,p=Math.max(i-o-f,0);return[d,p,d+u,p+f,f]}function dt(e,t){if(!e)return t;const n=Number.parseInt(e,10);return Number.isFinite(n)?n:t}function pt(e,t,n){if(e===t)return!0;if(!n||!e||!t)return!1;if(Array.isArray(e)){if(!Array.isArray(t)||e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!pt(e[i],t[i],n-1))return!1;return!0}if(Array.isArray(t))return!1;if("object"==typeof e&&"object"==typeof t){const i=Object.keys(e),o=Object.keys(t);if(i.length!==o.length)return!1;for(const s of i){if(!t.hasOwnProperty(s))return!1;if(!pt(e[s],t[s],n-1))return!1}return!0}return!1}var gt=class{bufferLayouts;constructor(e){this.bufferLayouts=e}getBufferLayout(e){return this.bufferLayouts.find(t=>t.name===e)||null}getAttributeNamesForBuffer(e){return Z(e)}mergeBufferLayouts(e,t){const n=[...e];for(const i of t){const e=n.findIndex(e=>e.name===i.name);e<0?n.push(i):n[e]=i}return n}};function ht(e){return null!==e&&"object"==typeof e&&"resolveTextureBinding"in e&&"function"==typeof e.resolveTextureBinding}function vt(e,t,n){const i=V(e,t,{ignoreWarnings:!0});return function(e){return"texture"===e?.type||"external-texture"===e?.type}(i)?i:0===e.bindings.length&&void 0!==n?.fallbackGroup?{type:"texture",name:t,group:n.fallbackGroup,location:0}:null}var mt="render pipeline initialization failed",_t=["stencil8","depth16unorm","depth24plus","depth24plus-stencil8","depth32float","depth32float-stencil8"],xt=class e{static defaultProps={...q.defaultProps,source:void 0,vs:null,fs:null,id:"unnamed",handle:void 0,userData:{},defines:{},modules:[],plugins:[],geometry:null,indexBuffer:null,indexCount:void 0,firstVertex:0,firstIndex:0,attributes:{},constantAttributes:{},bindings:{},uniforms:{},varyings:[],isInstanced:void 0,instanceCount:0,vertexCount:0,shaderInputs:void 0,material:void 0,pipelineFactory:void 0,shaderFactory:void 0,transformFeedback:void 0,shaderAssembler:B.getDefaultShaderAssembler("glsl"),debugShaders:void 0,disableWarnings:void 0};device;id;source;vs;fs;pipelineFactory;shaderFactory;userData={};parameters;topology;bufferLayout;isInstanced=void 0;instanceCount=0;vertexCount;indexCount;firstVertex;firstIndex;indexBuffer=null;bufferAttributes={};constantAttributes={};bindings={};vertexArray;transformFeedback=null;pipeline;shaderInputs;material=null;_uniformStore;_attributeInfos={};_gpuGeometry=null;props;_dynamicIndexBufferSource=null;_dynamicAttributeBufferSources={};_colorAttachmentFormats;_depthStencilAttachmentFormat;_pipelineNeedsUpdate="newly created";_needsRedraw="initializing";_drawBlockedReason=!1;_destroyed=!1;_vertexCountSet=!1;_lastDrawTimestamp=-1;_bindingTable=[];get[Symbol.toStringTag](){return"Model"}toString(){return`Model(${this.id})`}constructor(t,n){const i=e.defaultProps.shaderAssembler,o=void 0!==n.vertexCount;this.props={...e.defaultProps,...n,shaderAssembler:n.shaderAssembler??(yt(i,t.info.shadingLanguage)?i:B.getDefaultShaderAssembler(t.info.shadingLanguage))},this._vertexCountSet=o,n=this.props,this.id=n.id||ee("model"),this.device=t,Object.assign(this.userData,n.userData),this.material=n.material||null;const s=function(e){return{type:e.type,shaderLanguage:e.info.shadingLanguage,shaderLanguageVersion:e.info.shadingLanguageVersion,gpu:e.info.gpu,limits:e.limits,features:e.features}}(t),r=ye(this.props.plugins,s.shaderLanguage),a=me(this.props.modules,r.modules),l=Object.fromEntries(a.map(e=>[e.name,e])),c=n.shaderInputs||new ie(l,{disableWarnings:this.props.disableWarnings});n.shaderInputs&&r.modules.length>0&&c.addModules(r.modules),this.setShaderInputs(c);const u=re(this.props.modules,c.getModules()),f={...r.defines,...this.props.defines};if("webgl"===this.device.type&&(this.props._uniformBlockLayouts=oe(u)),this.props.shaderLayout=ce(this.props.shaderLayout,u)||null,"webgpu"===this.device.type&&this.props.source){const e=this.props.shaderAssembler;W(yt(e,"wgsl"));const{source:n,getUniforms:i,bindingTable:o,shaderLayout:a}=e.assembleWGSLShader({platformInfo:s,...this.props,modules:u,defines:f,pluginInjections:r.injections,pluginVertexInputs:r.vertexInputs,pluginVaryings:r.varyings});this.source=n,this._getModuleUniforms=i,this._bindingTable=o;const l=function(e,t){return e&&0!==Object.keys(t).length?{...e,attributes:e.attributes.map(e=>{const n=e.name.startsWith("_luma_")?e.name.slice(6):null;return n&&t[n]?{...e,name:n}:e})}:e}(a??t.getShaderLayout?.(this.source),r.vertexInputs),c=de(this.props.shaderLayout,l,Object.keys(r.vertexInputs));this.props.shaderLayout=ce(c||null,u)||null}else{const e=this.props.shaderAssembler;W(yt(e,"glsl"));const{vs:t,fs:n,getUniforms:i}=e.assembleGLSLShaderPair({platformInfo:s,...this.props,modules:u,defines:f,pluginInjections:r.injections,pluginVertexInputs:r.vertexInputs,pluginVaryings:r.varyings});this.vs=t,this.fs=n,this._getModuleUniforms=i,this._bindingTable=[]}this.vertexCount=this.props.vertexCount,this.indexCount=this.props.indexCount,this.firstVertex=this.props.firstVertex,this.firstIndex=this.props.firstIndex,this.instanceCount=this.props.instanceCount,this.topology=this.props.topology,this.bufferLayout=this.props.bufferLayout,this.parameters=this.props.parameters,this._colorAttachmentFormats=this.props.colorAttachmentFormats,this._depthStencilAttachmentFormat=this.props.depthStencilAttachmentFormat,n.geometry&&this.setGeometry(n.geometry),this.pipelineFactory=n.pipelineFactory||Q.getDefaultPipelineFactory(this.device),this.shaderFactory=n.shaderFactory||xe.getDefaultShaderFactory(this.device),this.pipeline=this._updatePipeline(),this.vertexArray=t.createVertexArray({shaderLayout:this.pipeline.shaderLayout,bufferLayout:this.pipeline.bufferLayout}),this._gpuGeometry&&this._setGeometryAttributes(this._gpuGeometry),"isInstanced"in n&&(this.isInstanced=n.isInstanced),n.instanceCount&&this.setInstanceCount(n.instanceCount),n.vertexCount&&this.setVertexCount(n.vertexCount),n.indexBuffer&&this.setIndexBuffer(n.indexBuffer),n.attributes&&this.setAttributes(n.attributes),n.constantAttributes&&this.setConstantAttributes(n.constantAttributes),n.bindings&&this.setBindings(n.bindings),n.transformFeedback&&(this.transformFeedback=n.transformFeedback)}destroy(){this._destroyed||(this.pipelineFactory.release(this.pipeline),this.shaderFactory.release(this.pipeline.vs),this.pipeline.fs&&this.pipeline.fs!==this.pipeline.vs&&this.shaderFactory.release(this.pipeline.fs),this._uniformStore.destroy(),this._gpuGeometry?.destroy(),this._destroyed=!0)}needsRedraw(){this._getBindingsUpdateTimestamp()>this._lastDrawTimestamp&&this.setNeedsRedraw("contents of bound textures or buffers updated");const e=this._needsRedraw;return this._needsRedraw=!1,e}setNeedsRedraw(e){this._needsRedraw||=e}getBindingDebugTable(){return this._bindingTable}predraw(e){this._syncDynamicBuffers(),this.updateShaderInputs(e),this.material?.updateShaderInputs(e),this.pipeline=this._updatePipeline()}draw(e){if(this._drawBlockedReason&&!this._pipelineNeedsUpdate)return j.info(2,`>>> DRAWING ABORTED ${this.id}: ${this._drawBlockedReason}`)(),!1;const t=this._areBindingsLoading();if(t)return j.info(2,`>>> DRAWING ABORTED ${this.id}: ${t} not loaded`)(),!1;this._syncAttachmentFormats(e);try{e.pushDebugGroup(`${this}.predraw(${e})`),"webgpu"===this.device.type?(this.updateShaderInputs(),this.material?.updateShaderInputs(),this._syncDynamicBuffers(),this.pipeline=this._updatePipeline()):this.predraw(this.device.commandEncoder)}finally{e.popDebugGroup()}let n,i=this.pipeline.isErrored;try{if(e.pushDebugGroup(`${this}.draw(${e})`),this._logDrawCallStart(),this.pipeline=this._updatePipeline(),i=this.pipeline.isErrored,i)j.info(2,`>>> DRAWING ABORTED ${this.id}: ${mt}`)(),n=!1;else{const t=this.vertexArray.getDrawValidationError();if(t)j.info(2,`>>> DRAWING ABORTED ${this.id}: ${t}`)(),this._drawBlockedReason=t,n=!1;else{const t=this._getCurrentShaderLayout(),i=this._getBindings(t),o=this._getBindGroups(t,i),{indexBuffer:s}=this.vertexArray,r=s?this.indexCount??(this._vertexCountSet?this.vertexCount:s.byteLength/("uint32"===s.indexType?4:2)):void 0;e.setPipeline(this.pipeline),e.setBindings(o,{_bindGroupCacheKeys:this._getBindGroupCacheKeys()}),e.setVertexArray(this.vertexArray),n=!0===this.isInstanced&&0===this.instanceCount||e.draw({isInstanced:this.isInstanced,vertexCount:this.vertexCount,instanceCount:this.isInstanced?this.instanceCount:void 0,indexCount:r,firstVertex:this.firstVertex,firstIndex:this.firstIndex,transformFeedback:this.transformFeedback||void 0,uniforms:this.props.uniforms,parameters:this.parameters,topology:this.topology})}}}finally{e.popDebugGroup(),this._logDrawCallEnd()}return this._logFramebuffer(e),n?(this._lastDrawTimestamp=this.device.timestamp,this._needsRedraw=!1):i?(this._needsRedraw=mt,this._drawBlockedReason=mt):this._drawBlockedReason?this._needsRedraw=this._drawBlockedReason:this._needsRedraw="waiting for resource initialization",n}setGeometry(e){this._gpuGeometry?.destroy();const t=e&<(this.device,e);if(t){this.setTopology(t.topology||"triangle-list");const e=new gt(this.bufferLayout);this.bufferLayout=e.mergeBufferLayouts(t.bufferLayout,this.bufferLayout),this.vertexArray&&this._setGeometryAttributes(t)}this._gpuGeometry=t}setTopology(e){e!==this.topology&&(this.topology=e,this._setPipelineNeedsUpdate("topology"))}setBufferLayout(e){const t=new gt(this.bufferLayout),n=this._gpuGeometry?t.mergeBufferLayouts(e,this._gpuGeometry.bufferLayout):e;pt(n,this.bufferLayout,-1)||(this.bufferLayout=n,this._setPipelineNeedsUpdate("bufferLayout"),this.pipeline=this._updatePipeline(),this.vertexArray=this.device.createVertexArray({shaderLayout:this.pipeline.shaderLayout,bufferLayout:this.pipeline.bufferLayout}),this._gpuGeometry&&this._setGeometryAttributes(this._gpuGeometry))}setParameters(e){pt(e,this.parameters,2)||(this.parameters=e,this._setPipelineNeedsUpdate("parameters"))}setInstanceCount(e){this.instanceCount=e,void 0===this.isInstanced&&e>0&&(this.isInstanced=!0),this.setNeedsRedraw("instanceCount")}setVertexCount(e){this.vertexCount=e,this._vertexCountSet=!0,this.setNeedsRedraw("vertexCount")}setIndexCount(e){this.indexCount=e,this.setNeedsRedraw("indexCount")}setDrawOffsets({firstVertex:e,firstIndex:t}){this.firstVertex=e,this.firstIndex=t,this.setNeedsRedraw("drawOffsets")}setShaderInputs(e){this.shaderInputs=e,this._uniformStore=new ne(this.device,this.shaderInputs.modules);for(const[t,n]of Object.entries(this.shaderInputs.modules))if(se(n)&&!this.material?.ownsModule(t)){const e=this._uniformStore.getManagedUniformBuffer(t);this.bindings[`${t}Uniforms`]=e}this.setNeedsRedraw("shaderInputs")}setMaterial(e){this.material=e,this.setNeedsRedraw("material")}updateShaderInputs(e){this._uniformStore.setUniforms(this.shaderInputs.getUniformValues(),e),this.setBindings(this._getNonMaterialBindings(this.shaderInputs.getBindingValues())),this.setNeedsRedraw("shaderInputs")}setBindings(e){Object.assign(this.bindings,e),this.setNeedsRedraw("bindings")}setTransformFeedback(e){this.transformFeedback=e,this.setNeedsRedraw("transformFeedback")}setIndexBuffer(e){const t=e instanceof ge?e.buffer:e;this.indexBuffer=t,this._dynamicIndexBufferSource=e instanceof ge?{source:e,generation:e.generation}:null,this.vertexArray.setIndexBuffer(t),this.setNeedsRedraw("indexBuffer")}setAttributes(e,t){this._drawBlockedReason=!1;const n=t?.disableWarnings??this.props.disableWarnings;e.indices&&j.warn(`Model:${this.id} setAttributes() - indexBuffer should be set using setIndexBuffer()`)(),this.bufferLayout=function(e,t){const n=Y(e),i=t.slice();return i.sort((e,t)=>G(Z(e).map(e=>n[e]))-G(Z(t).map(e=>n[e]))),i}(this.pipeline.shaderLayout,this.bufferLayout);const i=new gt(this.bufferLayout);for(const[o,s]of Object.entries(e)){const e=s instanceof ge?s.buffer:s,t=i.getBufferLayout(o);if(!t){n||j.warn(`Model(${this.id}): Missing layout for buffer "${o}".`)();continue}const r=i.getAttributeNamesForBuffer(t);let a=!1;for(const i of r){const t=this._attributeInfos[i];if(t){const i="webgpu"===this.device.type?this.vertexArray.getBufferSlot(t.bufferName):t.location;if(null===i){n||j.warn(`Model(${this.id}): Missing vertex array slot for buffer "${t.bufferName}".`)();continue}this.vertexArray.setBuffer(i,e),s instanceof ge?this._dynamicAttributeBufferSources[i]={source:s,generation:s.generation}:delete this._dynamicAttributeBufferSources[i],a=!0}}a||n||j.warn(`Model(${this.id}): Ignoring buffer "${e.id}" for unknown attribute "${o}"`)()}this.setNeedsRedraw("attributes")}setConstantAttributes(e,t){for(const[n,i]of Object.entries(e)){const e=this._attributeInfos[n];e?this.vertexArray.setConstantWebGL(e.location,i):(t?.disableWarnings??this.props.disableWarnings)||j.warn(`Model "${this.id}: Ignoring constant supplied for unknown attribute "${n}"`)()}this.setNeedsRedraw("constants")}_areBindingsLoading(){for(const e of Object.values(this.bindings))if(ht(e)&&!e.isReady)return e.id;for(const e of Object.values(this.material?.bindings||{}))if(ht(e)&&!e.isReady)return e.id;return!1}_getBindings(e=this._getCurrentShaderLayout()){const t={};for(const[n,i]of Object.entries(this.bindings)){const o=bt(n,i,e);o&&(t[n]=o)}return t}_getBindGroups(e=this._getCurrentShaderLayout(),t=this._getBindings(e)){const n=e.bindings.length?$(e,t):{0:t};if(!this.material)return n;for(const[i,o]of Object.entries(this.material.getBindingsByGroup(e))){const e=Number(i);n[e]={...n[e]||{},...o}}return n}_getBindGroupCacheKeys(){const e=this.material?.getBindGroupCacheKey(3);return e?{3:e}:{}}_getBindingsUpdateTimestamp(){let e=0;this._dynamicIndexBufferSource&&(e=Math.max(e,this._dynamicIndexBufferSource.source.updateTimestamp));for(const t of Object.values(this._dynamicAttributeBufferSources))e=Math.max(e,t.source.updateTimestamp);for(const t of Object.values(this.bindings))t instanceof H?e=Math.max(e,t.texture.updateTimestamp):t instanceof U||t instanceof p||t instanceof be||t instanceof ge?e=Math.max(e,t.updateTimestamp):ht(t)?e=t.isReady?Math.max(e,t.updateTimestamp):1/0:le(t)&&(e=Math.max(e,(t.buffer,t.buffer.updateTimestamp)));return Math.max(e,this.material?.getBindingsUpdateTimestamp()||0)}_setGeometryAttributes(e){const t={...e.attributes};for(const[n]of Object.entries(t))this.pipeline.shaderLayout.attributes.find(e=>e.name===n)||"positions"===n||delete t[n];this.vertexCount=e.vertexCount,this._vertexCountSet=!0,this.setIndexBuffer(e.indices||null),this.setAttributes(e.attributes,{disableWarnings:!0}),this.setAttributes(t,{disableWarnings:this.props.disableWarnings}),this.setNeedsRedraw("geometry attributes")}_setPipelineNeedsUpdate(e){this._pipelineNeedsUpdate||=e,this._drawBlockedReason=!1,this.setNeedsRedraw(e)}_updatePipeline(){if(this._pipelineNeedsUpdate){let e=null,t=null;this.pipeline&&(j.log(1,`Model ${this.id}: Recreating pipeline because "${this._pipelineNeedsUpdate}".`)(),e=this.pipeline.vs,t=this.pipeline.fs),this._pipelineNeedsUpdate=!1;const n=this.shaderFactory.createShader({id:`${this.id}-vertex`,stage:"vertex",source:this.source||this.vs,debugShaders:this.props.debugShaders});let i=null;this.source?i=n:this.fs&&(i=this.shaderFactory.createShader({id:`${this.id}-fragment`,stage:"fragment",source:this.source||this.fs,debugShaders:this.props.debugShaders})),this.pipeline=this.pipelineFactory.createRenderPipeline({...this.props,bindings:void 0,bufferLayout:this.bufferLayout,colorAttachmentFormats:this._colorAttachmentFormats,depthStencilAttachmentFormat:this._depthStencilAttachmentFormat,topology:this.topology,parameters:this.parameters,bindGroups:void 0,vs:n,fs:i}),this._attributeInfos=K(this.pipeline.shaderLayout,this.bufferLayout),e&&this.shaderFactory.release(e),t&&t!==e&&this.shaderFactory.release(t)}return this.pipeline}_lastLogTime=0;_logOpen=!1;_logDrawCallStart(){const e=j.level>3?0:1e4;j.level<2||Date.now()-this._lastLogTime<e||(this._lastLogTime=Date.now(),this._logOpen=!0,j.group(2,`>>> DRAWING MODEL ${this.id}`,{collapsed:j.level<=2})())}_logDrawCallEnd(){if(this._logOpen){const e=function(e){const t={},n="Values";if(0===e.attributes.length&&!e.varyings?.length)return{"No attributes or varyings":{[n]:"N/A"}};for(const i of e.attributes)i&&(t[`in ${i.location} ${i.name}: ${i.type}`]={[n]:i.stepMode||"vertex"});for(const i of e.varyings||[])t[`out ${i.location} ${i.name}`]={[n]:JSON.stringify(i)};return t}(this.pipeline.shaderLayout,this.id);j.table(2,e)();const t=this.shaderInputs.getDebugTable();j.table(2,t)();const n=this._getAttributeDebugTable();j.table(2,this._attributeInfos)(),j.table(2,n)(),j.groupEnd(2)(),this._logOpen=!1}}_drawCount=0;_logFramebuffer(e){const t=this.device.props.debugFramebuffers;if(this._drawCount++,!t)return;const n=e.props.framebuffer;ut(e,n,{id:n?.id||`${this.id}-framebuffer`,minimap:!0})}_getAttributeDebugTable(){const e={};for(const[t,n]of Object.entries(this._attributeInfos)){const i=this.vertexArray.attributes[n.location];e[n.location]={name:t,type:n.shaderType,values:i?this._getBufferOrConstantValues(i,n.bufferDataType):"null"}}if(this.vertexArray.indexBuffer){const{indexBuffer:t}=this.vertexArray,n="uint32"===t.indexType?new Uint32Array(t.debugData):new Uint16Array(t.debugData);e.indices={name:"indices",type:t.indexType,values:n.toString()}}return e}_getBufferOrConstantValues(e,t){const n=k.getTypedArrayConstructor(t);return(e instanceof U?new n(e.debugData):e).toString()}_getNonMaterialBindings(e){if(!this.material)return e;const t={};for(const[n,i]of Object.entries(e))this.material.ownsBinding(n)||(t[n]=i);return t}_getCurrentShaderLayout(){return this.pipeline?.shaderLayout||this.props.shaderLayout||{bindings:[]}}_syncDynamicBuffers(){if(this._dynamicIndexBufferSource&&this._dynamicIndexBufferSource.generation!==this._dynamicIndexBufferSource.source.generation){const e=this._dynamicIndexBufferSource.source.buffer;this.indexBuffer=e,this.vertexArray.setIndexBuffer(e),this._dynamicIndexBufferSource.generation=this._dynamicIndexBufferSource.source.generation,this.setNeedsRedraw("dynamic index buffer")}for(const[e,t]of Object.entries(this._dynamicAttributeBufferSources))t.generation!==t.source.generation&&(this.vertexArray.setBuffer(Number(e),t.source.buffer),t.generation=t.source.generation,this.setNeedsRedraw("dynamic attribute buffer"))}_syncAttachmentFormats(e){if("webgpu"!==this.device.type)return;const t=e.framebuffer||e.props.framebuffer,n=e.props,i=n.colorAttachmentFormats??t?.colorAttachments?.map(e=>{return t=e?.texture?.format,t&&!Pt(t)?t:null;var t}),o=!1===n.depthStencilAttachmentFormat?void 0:n.depthStencilAttachmentFormat??(s=t?.depthStencilAttachment?.texture?.format,s&&Pt(s)?s:void 0);var s;pt(this._colorAttachmentFormats,i,1)&&this._depthStencilAttachmentFormat===o||(this._colorAttachmentFormats=i,this._depthStencilAttachmentFormat=o,this._setPipelineNeedsUpdate("attachment formats"))}};function yt(e,t){return(void 0===e.shaderLanguage||e.shaderLanguage===t)&&("glsl"===t?"assembleGLSLShaderPair"in e&&"function"==typeof e.assembleGLSLShaderPair:"assembleWGSLShader"in e&&"function"==typeof e.assembleWGSLShader)}function bt(e,t,n){if(ht(t)){const i=vt(n,e,{fallbackGroup:0});return i?t.resolveTextureBinding(i):null}return t instanceof ge?t.buffer:le(t)?ve(t):t}function Pt(e){return _t.includes(e)}var Ct=class e{device;model;transformFeedback;static defaultProps={...xt.defaultProps,feedbackBufferMode:"separate",outputs:void 0,feedbackBuffers:void 0};static isSupported(e){return"webgl"===e?.info?.type}constructor(t,n=e.defaultProps){if(!e.isSupported(t))throw new Error("BufferTransform not yet implemented on WebGPU");this.device=t,this.model=new xt(this.device,{id:n.id||"buffer-transform-model",fs:n.fs||Pe(),topology:n.topology||"point-list",varyings:n.outputs||n.varyings,...n,bufferMode:n.bufferMode||("interleaved"===n.feedbackBufferMode?35980:35981)}),this.transformFeedback=this.device.createTransformFeedback({layout:this.model.pipeline.shaderLayout,buffers:n.feedbackBuffers}),this.model.setTransformFeedback(this.transformFeedback)}destroy(){this.model&&this.model.destroy()}delete(){this.destroy()}run(e){e?.inputBuffers&&this.model.setAttributes(e.inputBuffers),e?.outputBuffers&&this.transformFeedback.setBuffers(e.outputBuffers);const t=this.device.beginRenderPass({discard:!0,...e});this.model.draw(t),t.end()}getBuffer(e){return this.transformFeedback.getBuffer(e)}readAsync(e){const t=this.getBuffer(e);if(!t)throw new Error("BufferTransform#getBuffer");if(t instanceof U)return t.readAsync();const{buffer:n,byteOffset:i=0,byteLength:o=n.byteLength}=t;return n.readAsync(i,o)}},wt=class extends nt{constructor(e={}){const{id:t=ee("cube-geometry"),indices:n=!0}=e;super(n?{...e,id:t,topology:"triangle-list",indices:{size:1,value:St},attributes:{...Rt,...e.attributes}}:{...e,id:t,topology:"triangle-list",indices:void 0,attributes:{...Bt,...e.attributes}})}},St=new Uint16Array([0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]),Lt=new Float32Array([-1,-1,1,1,-1,1,1,1,1,-1,1,1,-1,-1,-1,-1,1,-1,1,1,-1,1,-1,-1,-1,1,-1,-1,1,1,1,1,1,1,1,-1,-1,-1,-1,1,-1,-1,1,-1,1,-1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,-1,1,-1,-1,-1,-1,-1,1,-1,1,1,-1,1,-1]),At=new Float32Array([0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0]),It=new Float32Array([0,0,1,0,1,1,0,1,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,1,1,1,0,1,0,0,1,0,1,0,1,1,0,1,0,0,0,0,1,0,1,1,0,1]),Et=new Uint32Array([0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5]),Tt=new Float32Array([1,-1,1,-1,-1,1,-1,-1,-1,1,-1,-1,1,-1,1,-1,-1,-1,1,1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,-1,-1,-1,1,1,1,1,1,1,1,-1,-1,1,-1,-1,1,1,1,1,-1,-1,-1,1,-1,1,1,-1,1,-1,-1,-1,-1,-1,-1,1,-1,1,-1,1,1,1,-1,1,1,-1,-1,1,-1,-1,1,1,-1,1,1,1,1,1,-1,-1,-1,-1,-1,-1,1,-1,1,1,-1,1,-1,-1,-1,1,-1]),Ot=new Float32Array([1,1,0,1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,0,0,1,0,1,1,1,1,0,1,0,0,1,0,1,1,0,0]),zt=new Float32Array([1,0,1,1,0,0,1,1,0,0,0,1,1,0,0,1,1,0,1,1,0,0,0,1,1,1,1,1,1,0,1,1,1,0,0,1,1,1,0,1,1,1,1,1,1,0,0,1,0,1,1,1,1,1,1,1,1,1,0,1,0,1,0,1,0,1,1,1,1,1,0,1,0,0,1,1,0,1,1,1,0,1,0,1,0,0,0,1,0,0,1,1,0,1,0,1,1,1,1,1,0,1,1,1,0,0,1,1,0,0,1,1,1,0,1,1,1,1,1,1,1,0,0,1,0,0,0,1,0,1,0,1,1,1,0,1,1,0,0,1,0,1,0,1]),Mt=new Uint32Array([3,3,3,3,3,3,4,4,4,4,4,4,2,2,2,2,2,2,5,5,5,5,5,5,0,0,0,0,0,0,1,1,1,1,1,1]),Rt={POSITION:{size:3,value:Lt},NORMAL:{size:3,value:At},TEXCOORD_0:{size:2,value:It},faceIndex:{size:1,value:Et}},Bt={POSITION:{size:3,value:Tt},TEXCOORD_0:{size:2,value:Ot},COLOR_0:{size:3,value:zt},faceIndex:{size:1,value:Mt}},kt=class e{static defaultProps={...J.defaultProps,id:"unnamed",handle:void 0,userData:{},source:"",modules:[],defines:{},plugins:[],bindings:void 0,shaderInputs:void 0,pipelineFactory:void 0,shaderFactory:void 0,shaderAssembler:B.getDefaultShaderAssembler("wgsl"),debugShaders:void 0};device;id;pipelineFactory;shaderFactory;userData={};bindings={};pipeline;source;shader;shaderInputs;_uniformStore;_pipelineNeedsUpdate="newly created";_getModuleUniforms;props;_destroyed=!1;constructor(t,n){if("webgpu"!==t.type)throw new Error("Computation is only supported in WebGPU");this.props={...e.defaultProps,...n},n=this.props,this.id=n.id||ee("model"),this.device=t,Object.assign(this.userData,n.userData);const i=function(e){return{type:e.type,shaderLanguage:e.info.shadingLanguage,shaderLanguageVersion:e.info.shadingLanguageVersion,gpu:e.info.gpu,limits:e.limits,features:e.features}}(t),s=ye(this.props.plugins,i.shaderLanguage);if(Object.keys(s.vertexInputs).length>0||Object.keys(s.varyings).length>0)throw new Error("Computation does not support ShaderPlugin vertex inputs or varyings");const r=me(this.props.modules,s.modules),a=Object.fromEntries(r.map(e=>[e.name,e]));this.shaderInputs=n.shaderInputs||new ie(a),n.shaderInputs&&s.modules.length>0&&this.shaderInputs.addModules(s.modules),this.setShaderInputs(this.shaderInputs);const l=re(this.props.modules,this.shaderInputs?.getModules()),c={...s.defines,...this.props.defines};this.props.shaderLayout=ce(this.props.shaderLayout,l)||null,this.pipelineFactory=n.pipelineFactory||Q.getDefaultPipelineFactory(this.device),this.shaderFactory=n.shaderFactory||xe.getDefaultShaderFactory(this.device);const u=this.props.shaderAssembler;W(u instanceof o);const{source:f,getUniforms:d,shaderLayout:p}=u.assembleWGSLShader({platformInfo:i,...this.props,modules:l,defines:c,scanVertexAttributes:!1,pluginInjections:s.injections});this.source=f,this._getModuleUniforms=d;const g=p??t.getShaderLayout?.(this.source,{scanVertexAttributes:!1});this.props.shaderLayout=ce(this.props.shaderLayout||g||null,l)||null,this.pipeline=this._updatePipeline(),n.bindings&&this.setBindings(n.bindings)}destroy(){this._destroyed||(this.pipelineFactory.release(this.pipeline),this.shaderFactory.release(this.shader),this._uniformStore.destroy(),this._destroyed=!0)}predraw(e){this.updateShaderInputs(e)}dispatch(e,t,n,i){try{this._logDrawCallStart(),this._setPipeline(e),e.dispatch(t,n,i)}finally{this._logDrawCallEnd()}}dispatchIndirect(e,t,n=0){try{this._logDrawCallStart(),this._setPipeline(e),e.dispatchIndirect(t,n)}finally{this._logDrawCallEnd()}}_setPipeline(e){this.pipeline=this._updatePipeline(),this.pipeline.setBindings(this.bindings),e.setPipeline(this.pipeline),e.setBindings({})}setVertexCount(e){}setInstanceCount(e){}setShaderInputs(e){this.shaderInputs=e,this._uniformStore=new ne(this.device,this.shaderInputs.modules);for(const[t,n]of Object.entries(this.shaderInputs.modules))if(se(n)){const e=this._uniformStore.getManagedUniformBuffer(t);this.bindings[`${t}Uniforms`]=e}}setShaderModuleProps(e){const t=this._getModuleUniforms(e),n=Object.keys(t).filter(e=>{const n=t[e];return!_e(n)&&"number"!=typeof n&&"boolean"!=typeof n}),i={};for(const o of n)i[o]=t[o],delete t[o]}updateShaderInputs(e){this._uniformStore.setUniforms(this.shaderInputs.getUniformValues(),e)}setBindings(e){Object.assign(this.bindings,e)}_setPipelineNeedsUpdate(e){this._pipelineNeedsUpdate=this._pipelineNeedsUpdate||e}_updatePipeline(){if(this._pipelineNeedsUpdate){let e=null;this.pipeline&&(j.log(1,`Model ${this.id}: Recreating pipeline because "${this._pipelineNeedsUpdate}".`)(),e=this.shader),this._pipelineNeedsUpdate=!1,this.shader=this.shaderFactory.createShader({id:`${this.id}-fragment`,stage:"compute",source:this.source,debugShaders:this.props.debugShaders}),this.pipeline=this.pipelineFactory.createComputePipeline({...this.props,shader:this.shader}),e&&this.shaderFactory.release(e)}return this.pipeline}_lastLogTime=0;_logOpen=!1;_logDrawCallStart(){const e=j.level>3?0:1e4;j.level<2||Date.now()-this._lastLogTime<e||(this._lastLogTime=Date.now(),this._logOpen=!0,j.group(2,`>>> DRAWING MODEL ${this.id}`,{collapsed:j.level<=2})())}_logDrawCallEnd(){if(this._logOpen){const e=this.shaderInputs.getDebugTable();j.table(2,e)(),j.groupEnd(2)(),this._logOpen=!1}}_drawCount=0;_getBufferOrConstantValues(e,t){const n=k.getTypedArrayConstructor(t);return(e instanceof U?new n(e.debugData):e).toString()}};var Ft=k.getDataType.bind(k);function Nt(e,t,n){if(t.size>4)return null;const i="webgpu"===n&&"uint8"===t.type?"unorm8":t.type,o=t.size,s=Boolean("webgpu"!==n&&3===o&&i&&["uint8","sint8","unorm8","snorm8","uint16","sint16","unorm16","snorm16"].includes(i));return{attribute:e,format:o>1?`${i}x${o}${s?"-webgl":""}`:t.type,byteOffset:t.offset||0}}function Dt(e){return e.stride||e.size*e.bytesPerElement}function jt(e,t){t.offset&&I.removed("shaderAttribute.offset","vertexOffset, elementOffset")();const n=Dt(e),i=(void 0!==t.vertexOffset?t.vertexOffset:e.vertexOffset||0)*n+(t.elementOffset||0)*e.bytesPerElement+(e.offset||0);return{...t,offset:i,stride:n}}var Ut=class{constructor(e,t,n){this._buffer=null,this.device=e,this.id=t.id||"",this.size=t.size||1;const i=t.logicalType||t.type,o="float64"===i;let s,{defaultValue:r}=t;r=Number.isFinite(r)?[r]:r||new Array(this.size).fill(0),s=o?"float32":!i&&t.isIndexed?"uint32":i||"float32";let a=function(e){switch(e){case"float64":return Float64Array;case"uint8":case"unorm8":return Uint8ClampedArray;default:return F(e)}}(i||s);this.doublePrecision=o,o&&!1===t.fp64&&(a=Float32Array),this.value=null,this.settings={...t,defaultType:a,defaultValue:r,logicalType:i,type:s,normalized:s.includes("norm"),size:this.size,bytesPerElement:a.BYTES_PER_ELEMENT},this.state={...n,externalBuffer:null,bufferAccessor:this.settings,allocatedValue:null,numInstances:0,bounds:null,constant:!1}}get isConstant(){return this.state.constant}get buffer(){return this._buffer}get byteOffset(){const e=this.getAccessor();return e.vertexOffset?e.vertexOffset*Dt(e):0}get numInstances(){return this.state.numInstances}set numInstances(e){this.state.numInstances=e}get isDoublePrecisionBuffer(){return this._shouldSplitDoublePrecisionValue(this.value)}delete(){this._buffer&&(this._buffer.delete(),this._buffer=null),f.release(this.state.allocatedValue),this.state.allocatedValue=null}getBuffer(){return this.state.constant&&"webgpu"!==this.device.type?null:this.state.externalBuffer||this._buffer}getValue(e=this.id,t=null){const n={};if(this.state.constant){const i=this.value;if("webgpu"===this.device.type&&this._buffer)n[e]=this._buffer;else if(t){const o=jt(this.getAccessor(),t),s=o.offset/i.BYTES_PER_ELEMENT,r=o.size||this.size;n[e]=i.subarray(s,s+r)}else n[e]=i}else n[e]=this.getBuffer();return this.doublePrecision&&(this.isDoublePrecisionBuffer?n[`${e}64Low`]=n[e]:n[`${e}64Low`]=new Float32Array(this.size)),n}_getBufferLayout(e=this.id,t=null){const n=this.getAccessor(),i=[],o={name:this.id,byteStride:"webgpu"===this.device.type&&this.state.constant?0:Dt(n)};if(this.doublePrecision){const o=function(e,t){const n=jt(e,t);return{high:n,low:{...n,offset:n.offset+4*e.size}}}(n,t||{});i.push(Nt(e,{...n,...o.high},this.device.type),Nt(`${e}64Low`,{...n,...o.low},this.device.type))}else if(t){const o=jt(n,t);i.push(Nt(e,{...n,...o},this.device.type))}else i.push(Nt(e,n,this.device.type));return o.attributes=i.filter(Boolean),o}setAccessor(e){this.state.bufferAccessor=e}getAccessor(){return this.state.bufferAccessor}getBounds(){if(this.state.bounds)return this.state.bounds;let e=null;if(this.state.constant&&this.value){const t=Array.from(this.value);e=[t,t]}else{const{value:t,numInstances:n,size:i}=this,o=n*i;if(t&&o&&t.length>=o){const n=new Array(i).fill(1/0),s=new Array(i).fill(-1/0);for(let e=0;e<o;)for(let o=0;o<i;o++){const i=t[e++];i<n[o]&&(n[o]=i),i>s[o]&&(s[o]=i)}e=[n,s]}}return this.state.bounds=e,e}setData(e){const{state:t}=this;let n;n=ArrayBuffer.isView(e)?{value:e}:e instanceof U?{buffer:e}:e;const i={...this.settings,...n};if(ArrayBuffer.isView(n.value)){if(!n.type)if(this.doublePrecision&&n.value instanceof Float64Array)i.type="float32";else{const e=Ft(n.value);i.type=i.normalized?e.replace("int","norm"):e}i.bytesPerElement=n.value.BYTES_PER_ELEMENT,i.stride=Dt(i)}if(t.bounds=null,n.constant){let e=n.value;if(e=this._normalizeValue(e,[],0),this.settings.normalized&&(e=this.normalizeConstant(e)),t.constant&&this._areValuesEqual(e,this.value))return!1;t.externalBuffer=null,t.constant=!0,this.value=ArrayBuffer.isView(e)?e:new Float32Array(e)}else if(n.buffer)t.externalBuffer=n.buffer,t.constant=!1,this.value=n.value||null;else if(n.value){this._checkExternalBuffer(n);const e=n.value;let o=e;t.externalBuffer=null,t.constant=!1,this.value=e,this._shouldSplitDoublePrecisionValue(o)&&(o=M(o,i),e instanceof Float32Array&&(i.stride=2*i.size*Float32Array.BYTES_PER_ELEMENT));let{buffer:s}=this;const r=Dt(i),a=(i.vertexOffset||0)*r;if(this.settings.isIndexed){const e=this.settings.defaultType;o.constructor!==e&&(o=new e(o))}const l=o.byteLength+a+2*r;(!s||s.byteLength<l)&&(s=this._createBuffer(l)),s.write(o,a)}return this.setAccessor(i),!0}updateSubBuffer(e={}){this.state.bounds=null;const t=this.value,{startOffset:n=0,endOffset:i}=e,o=this._shouldSplitDoublePrecisionValue(t);this.buffer.write(o?M(t,{size:this.size,startIndex:n,endIndex:i}):t.subarray(n,i),n*(o?8:t.BYTES_PER_ELEMENT)+this.byteOffset)}allocate(e,t=!1){const{state:n}=this,i=n.allocatedValue,o=f.allocate(i,e+1,{size:this.size,type:this.settings.defaultType,copy:t});this.value=o;const s=this._shouldSplitDoublePrecisionValue(o),r=s&&o instanceof Float32Array?{...this.settings,stride:2*this.size*Float32Array.BYTES_PER_ELEMENT}:this.settings;this.setAccessor(r);const{byteOffset:a}=this;let{buffer:l}=this;const c=o.byteLength*(s&&o instanceof Float32Array?2:1);return(!l||l.byteLength<c+a)&&(l=this._createBuffer(c+a),t&&i&&l.write(this._shouldSplitDoublePrecisionValue(i)?M(i,this):i,a)),n.allocatedValue=o,n.constant=!1,n.externalBuffer=null,!0}_shouldSplitDoublePrecisionValue(e){return Boolean(this.doublePrecision&&(e instanceof Float64Array||"webgpu"===this.device.type&&e instanceof Float32Array))}_checkExternalBuffer(e){const{value:t}=e;if(!ArrayBuffer.isView(t))throw new Error(`Attribute ${this.id} value is not TypedArray`);const n=this.settings.defaultType;let i=!1;if(this.doublePrecision&&(i=t.BYTES_PER_ELEMENT<4),i)throw new Error(`Attribute ${this.id} does not support ${t.constructor.name}`);t instanceof n||!this.settings.normalized||"normalized"in e||I.warn(`Attribute ${this.id} is normalized`)()}normalizeConstant(e){switch(this.settings.type){case"snorm8":return new Float32Array(e).map(e=>(e+128)/255*2-1);case"snorm16":return new Float32Array(e).map(e=>(e+32768)/65535*2-1);case"unorm8":return new Float32Array(e).map(e=>e/255);case"unorm16":return new Float32Array(e).map(e=>e/65535);default:return e}}_normalizeValue(e,t,n){const{defaultValue:i,size:o}=this.settings;if(Number.isFinite(e))return t[n]=e,t;if(!e){let e=o;for(;--e>=0;)t[n+e]=i[e];return t}switch(o){case 4:t[n+3]=Number.isFinite(e[3])?e[3]:i[3];case 3:t[n+2]=Number.isFinite(e[2])?e[2]:i[2];case 2:t[n+1]=Number.isFinite(e[1])?e[1]:i[1];case 1:t[n+0]=Number.isFinite(e[0])?e[0]:i[0];break;default:let s=o;for(;--s>=0;)t[n+s]=Number.isFinite(e[s])?e[s]:i[s]}return t}_areValuesEqual(e,t){if(!e||!t)return!1;const{size:n}=this;for(let i=0;i<n;i++)if(e[i]!==t[i])return!1;return!0}_createBuffer(e){this._buffer&&this._buffer.destroy();const{isIndexed:t,type:n}=this.settings,i="webgpu"!==this.device.type||t?(t?U.INDEX:U.VERTEX)|U.COPY_DST:U.VERTEX|U.STORAGE|U.COPY_DST|U.COPY_SRC;return this._buffer=this.device.createBuffer({...this._buffer?.props,id:this.id,usage:i,indexType:t?n:void 0,byteLength:e}),this._buffer}},Gt=[],Vt=[];function $t(e,t=0,n=1/0){let i=Gt;const o={index:-1,data:e,target:[]};return e?"function"==typeof e[Symbol.iterator]?i=e:e.length>0&&(Vt.length=e.length,i=Vt):i=Gt,(t>0||Number.isFinite(n))&&(i=(Array.isArray(i)?i:Array.from(i)).slice(t,n),o.index=t-1),{iterable:i,objectInfo:o}}function Wt(e){return e&&e[Symbol.asyncIterator]}function Ht(e,t){const{size:n,stride:i,offset:o,startIndices:s,nested:r}=t,a=e.BYTES_PER_ELEMENT,l=i?i/a:n,c=o?o/a:0,u=Math.floor((e.length-c)/l);return(t,{index:i,target:o})=>{if(!s){const t=i*l+c;for(let i=0;i<n;i++)o[i]=e[t+i];return o}const a=s[i],f=s[i+1]||u;let d;if(r){d=new Array(f-a);for(let t=a;t<f;t++){const i=t*l+c;o=new Array(n);for(let t=0;t<n;t++)o[t]=e[i+t];d[t-a]=o}}else if(l===n)d=e.subarray(a*n+c,f*n+c);else{d=new e.constructor((f-a)*n);let t=0;for(let i=a;i<f;i++){const o=i*l+c;for(let i=0;i<n;i++)d[t++]=e[o+i]}}return d}}var Zt=[],Yt=[[0,1/0]];var qt={interpolation:{duration:0,easing:e=>e},spring:{stiffness:.05,damping:.5}};function Kt(e,t){if(!e)return null;Number.isFinite(e)&&(e={type:"interpolation",duration:e});const n=e.type||"interpolation";return{...qt[n],...t,...e,type:n}}var Xt=class extends Ut{constructor(e,t){super(e,t,{startIndices:null,constantValue:null,lastExternalBuffer:null,binaryValue:null,binaryAccessor:null,needsUpdate:!0,needsRedraw:!1,layoutChanged:!1,updateRanges:Yt}),this.constant=!1,this.settings.update=t.update||(t.accessor?this._autoUpdater:void 0),Object.seal(this.settings),Object.seal(this.state),this._validateAttributeUpdaters()}get startIndices(){return this.state.startIndices}set startIndices(e){this.state.startIndices=e}needsUpdate(){return this.state.needsUpdate}needsRedraw({clearChangedFlags:e=!1}={}){const t=this.state.needsRedraw;return this.state.needsRedraw=t&&!e,t}layoutChanged(){return this.state.layoutChanged}setAccessor(e){var t,n,i;(t=this.state).layoutChanged||(t.layoutChanged=(n=e,i=this.getAccessor(),!(n.type===i.type&&n.size===i.size&&Dt(n)===Dt(i)&&(n.offset||0)===(i.offset||0)))),super.setAccessor(e)}getUpdateTriggers(){const{accessor:e}=this.settings;return[this.id].concat("function"!=typeof e&&e||[])}supportsTransition(){return Boolean(this.settings.transition)}getTransitionSetting(e){if(!e||!this.supportsTransition())return null;const{accessor:t}=this.settings,n=this.settings.transition;return Kt(Array.isArray(t)?e[t.find(t=>e[t])]:e[t],n)}setNeedsUpdate(e=this.id,t){if(this.state.needsUpdate=this.state.needsUpdate||e,this.setNeedsRedraw(e),t){const{startRow:e=0,endRow:n=1/0}=t;this.state.updateRanges=function(e,t){if(e===Yt)return e;if(t[0]<0&&(t[0]=0),t[0]>=t[1])return e;const n=[],i=e.length;let o=0;for(let s=0;s<i;s++){const i=e[s];i[1]<t[0]?(n.push(i),o=s+1):i[0]>t[1]?n.push(i):t=[Math.min(i[0],t[0]),Math.max(i[1],t[1])]}return n.splice(o,0,t),n}(this.state.updateRanges,[e,n])}else this.state.updateRanges=Yt}clearNeedsUpdate(){this.state.needsUpdate=!1,this.state.updateRanges=Zt}setNeedsRedraw(e=this.id){this.state.needsRedraw=this.state.needsRedraw||e}allocate(e){const{state:t,settings:n}=this;if(n.noAlloc)return!1;if(n.update){const n=this.isConstant;return super.allocate(e,t.updateRanges!==Yt),t.layoutChanged||(t.layoutChanged=n&&"webgpu"===this.device.type),!0}return!1}updateBuffer({numInstances:e,data:t,props:n,context:i}){if(!this.needsUpdate())return!1;const{state:{updateRanges:o},settings:{update:s,noAlloc:r}}=this;let a=!0;if(s){for(const[r,a]of o)s.call(i,this,{data:t,startRow:r,endRow:a,props:n,numInstances:e});if(this.value)if(this.constant||!this.buffer||this.buffer.byteLength<this.value.byteLength+this.byteOffset){if(this.constant){const e=this.value;this.value=null,this.setConstantValue(i,e)}else this.setData({value:this.value,constant:this.constant});this.constant=!1}else for(const[t,n]of o){const i=Number.isFinite(t)?this.getVertexOffset(t):0,o=Number.isFinite(n)?this.getVertexOffset(n):r||!Number.isFinite(e)?this.value.length:e*this.size;super.updateSubBuffer({startOffset:i,endOffset:o})}else;this._checkAttributeArray()}else a=!1;return this.clearNeedsUpdate(),this.setNeedsRedraw(),a}setConstantValue(e,t){var n;if(void 0===t||"function"==typeof t)return!1;const i=this.isConstant,o=this.settings.transform&&e?this.settings.transform.call(e,t):t,s=this.settings.defaultType;this.state.constantValue=this._normalizeValue(o,new s(this.size),0);const r=this.setData({constant:!0,value:o});if("webgpu"===this.device.type){let e=this.state.constantValue;this.doublePrecision&&(e instanceof Float32Array||e instanceof Float64Array)&&(e=M(e,{size:this.size}),this.setAccessor({...this.getAccessor(),stride:2*this.size*Float32Array.BYTES_PER_ELEMENT}));let t=this._buffer;(!t||t.byteLength<e.byteLength)&&(t=this._createBuffer(e.byteLength)),t.write(e),(n=this.state).layoutChanged||(n.layoutChanged=!i),this.constant=!1}return r&&this.setNeedsRedraw(),this.clearNeedsUpdate(),!0}getConstantValue(){return this.isConstant?this.state.constantValue:null}setExternalBuffer(e){const{state:t}=this;return e?(this.clearNeedsUpdate(),t.lastExternalBuffer===e||(t.lastExternalBuffer=e,this.setNeedsRedraw(),this.setData(e)),!0):(t.lastExternalBuffer=null,!1)}setBinaryValue(e,t=null){const{state:n,settings:i}=this;if(!e)return n.binaryValue=null,n.binaryAccessor=null,!1;if(i.noAlloc)return!1;if(n.binaryValue===e)return this.clearNeedsUpdate(),!0;if(n.binaryValue=e,this.setNeedsRedraw(),i.transform||t!==this.startIndices){ArrayBuffer.isView(e)&&(e={value:e});const o=e;h(ArrayBuffer.isView(o.value),`invalid ${i.accessor}`);const s=Boolean(o.size)&&o.size!==this.size;return n.binaryAccessor=Ht(o.value,{size:o.size||this.size,stride:o.stride,offset:o.offset,startIndices:t,nested:s}),!1}return this.clearNeedsUpdate(),this.setData(e),!0}getVertexOffset(e){const{startIndices:t}=this;return(t?e<t.length?t[e]:this.numInstances:e)*this.size}getValue(){const e=this.settings.shaderAttributes,t=super.getValue();if(!e)return t;for(const n in e)Object.assign(t,super.getValue(n,e[n]));return t}getBufferLayout(e){this.state.layoutChanged=!1;const t=this.settings.shaderAttributes,n=super._getBufferLayout(),{stepMode:i}=this.settings;if(n.stepMode="dynamic"===i?e?e.isInstanced?"instance":"vertex":"instance":i??"vertex",!t)return n;for(const o in t){const e=super._getBufferLayout(o,t[o]);n.attributes.push(...e.attributes)}return n}_autoUpdater(e,{data:t,startRow:n,endRow:i,props:o,numInstances:s}){const{settings:r,state:a,value:l,size:c,startIndices:u}=e,{accessor:f,transform:d}=r,p=a.binaryAccessor||("function"==typeof f?f:o[f]);h("function"==typeof p,`accessor "${f}" is not a function`);let g=e.getVertexOffset(n);const{iterable:m,objectInfo:_}=$t(t,n,i);for(const h of m){_.index++;let t=p(h,_);if(d&&(t=d.call(this,t)),u){const n=(_.index<u.length-1?u[_.index+1]:s)-u[_.index];if(t&&Array.isArray(t[0])){let n=g;for(const i of t)e._normalizeValue(i,l,n),n+=c}else t&&t.length>c?l.set(t,g):(e._normalizeValue(t,_.target,0),v({target:l,source:_.target,start:g,count:n}));g+=n*c}else e._normalizeValue(t,l,g),g+=c}}_validateAttributeUpdaters(){const{settings:e}=this;if(!e.noAlloc&&"function"!=typeof e.update)throw new Error(`Attribute ${this.id} missing update or accessor`)}_checkAttributeArray(){const{value:e}=this,t=Math.min(4,this.size);if(e&&e.length>=t){let n=!0;switch(t){case 4:n=n&&Number.isFinite(e[3]);case 3:n=n&&Number.isFinite(e[2]);case 2:n=n&&Number.isFinite(e[1]);case 1:n=n&&Number.isFinite(e[0]);break;default:n=!1}if(!n)throw new Error(`Illegal attribute generated for ${this.id}`)}}},Jt=class e{gpuDataEvaluators;format;length;id;_gpuVector;_ownsGPUDataEvaluators;_destroyed=!1;static fromGPUVector(t){if(t.bufferLayout)throw new Error(`GPUVectorEvaluator.fromGPUVector() does not accept interleaved vector "${t.name}"`);if(0===t.data.length)throw new Error(`GPUVectorEvaluator.fromGPUVector() requires GPUData for "${t.name}"`);return new e({id:t.name,gpuDataEvaluators:t.data.map(e=>pe.fromGPUData(e,{id:t.name})),gpuVector:t,format:t.format})}static fromGPUDataEvaluators(t,n={}){return new e({id:n.id,gpuDataEvaluators:t,format:n.format})}constructor({id:e,gpuDataEvaluators:t,gpuVector:n,format:i}){if(0===t.length)throw new Error("GPUVectorEvaluator requires at least one GPUData evaluator");!function(e){const t=e[0];for(const n of e.slice(1))if(n.type!==t.type||n.size!==t.size||n.normalized!==t.normalized||n.format!==t.format)throw new Error("GPUVectorEvaluator requires matching GPUData evaluator layouts")}(t),this.id=e,this.gpuDataEvaluators=t,this.format=i??t[0].format,this.length=t.reduce((e,t)=>e+t.length,0),this._gpuVector=n,this._ownsGPUDataEvaluators=!n}get evaluated(){return Boolean(this._gpuVector)}get gpuVector(){if(!this._gpuVector)throw new Error(`${this} not evaluated`);return this._gpuVector}mapGPUData(t){return e.fromGPUDataEvaluators(this.gpuDataEvaluators.map((e,n)=>t(e,n)),{id:this.id})}async evaluate(e,t={}){if(this._destroyed)throw new Error(`GPUVectorEvaluator ${this} already destroyed`);if(this._gpuVector)return this._gpuVector;const n=await Promise.all(this.gpuDataEvaluators.map(n=>n.evaluate(e,t))),i=n[0],o=n.map(Qt),s=t.format??this.format??i.format;return this._gpuVector=new fe({type:"data",name:t.name??this.id??"vector",format:s,data:o,stride:i.stride,byteStride:i.byteStride,rowByteLength:i.rowByteLength,bufferLayout:i.bufferLayout}),this._gpuVector}evaluateSync(e,t={}){if(this._destroyed)throw new Error(`GPUVectorEvaluator ${this} already destroyed`);if(this._gpuVector)return this._gpuVector;const n=this.gpuDataEvaluators.map(n=>n.evaluateSync(e,t)),i=n[0],o=n.map(Qt),s=t.format??this.format??i.format;return this._gpuVector=new fe({type:"data",name:t.name??this.id??"vector",format:s,data:o,stride:i.stride,byteStride:i.byteStride,rowByteLength:i.rowByteLength,bufferLayout:i.bufferLayout}),this._gpuVector}destroy(){if(this._ownsGPUDataEvaluators)for(const e of this.gpuDataEvaluators)e.destroy();this._gpuVector=void 0,this._destroyed=!0}toString(){return this.id??this.constructor.name}};function Qt(e){const[t,...n]=e.data;if(!t||n.length>0)throw new Error(`GPUVectorEvaluator requires one GPUData chunk for "${e.name}"`);return t}function en({elementWise:e,func:t,inputs:n,output:i,outputBuffer:o}){const s=Array.isArray(n)?n:Object.values(n);for(const g of s)if(!g.value)throw new Error(`${g} does not have CPU value`);const r=i.length,a=i.size,l=new i.ValueType(r*a);for(let g=0;g<r;g++){const n=s.map(e=>tn(e,g));if(e)for(let e=0;e<a;e++)l[g*a+e]=t.apply(null,n.map(t=>t[e]));else t.call(null,l.subarray(g*a,g*a+a),...n)}const c=i.ValueType.BYTES_PER_ELEMENT,u=i.offset/c,f=i.stride/c,d=a;let p=l;if(0!==u||f!==d){p=new i.ValueType(u+i.byteLength/c);for(let e=0;e<r;e++){const t=e*d,n=u+e*f,i=l.subarray(t,t+a);p.set(i,n),o.write(i,n*c)}}else o.write(l);return{success:!0,value:p}}function tn(e,t){const n=e.value,i=e.size,o=e.offset/e.ValueType.BYTES_PER_ELEMENT,s=e.stride/e.ValueType.BYTES_PER_ELEMENT,r=o+(e.isConstant?0:t)*s,a=n.slice(r,r+i);if(!e.normalized)return a;const l=new Float32Array(i);for(let c=0;c<i;c++)l[c]=nn(a[c],e.type);return l}function nn(e,t){switch(t){case"uint8":return e/255;case"uint16":return e/65535;case"uint32":return e/4294967295;case"sint8":return Math.max(e/127,-1);case"sint16":return Math.max(e/32767,-1);case"sint32":return Math.max(e/2147483647,-1);case"float32":return e;default:throw new Error(`Unsupported normalized source type ${t}`)}}var on=({inputs:e,output:t,target:n})=>{for(const o of Object.values(e.namedInputs))if(!o.value)throw new Error(`${o} does not have CPU value`);const i=new t.ValueType(t.length*t.size);for(let o=0;o<t.length;o++){const n=Object.fromEntries(Object.entries(e.namedInputs).map(([e,t])=>[e,tn(t,o)]));for(let s=0;s<t.size;s++)i[o*t.size+s]=sn(e.expression,n,s)}return n.write(i),{success:!0,value:i}};function sn(e,t,n){switch(e.kind){case"input":{const i=t[e.name];return n<i.length?i[n]:1===i.length?i[0]:0}case"literal":return Array.isArray(e.value)?e.value[n]??0:e.value;case"call":{!function(e,t){const n=ue[e].arity;if(t!==n)throw new Error(`Arithmetic op '${e}' expects ${n} args, got ${t}`)}(e.op,e.args.length);const i=e.args.map(e=>sn(e,t,n));switch(e.op){case"add":return i[0]+i[1];case"subtract":return i[0]-i[1];case"multiply":return i[0]*i[1];case"divide":return i[0]/i[1];case"pow":return Math.pow(i[0],i[1]);case"sqrt":return Math.sqrt(i[0]);case"abs":return Math.abs(i[0]);case"sin":return Math.sin(i[0]);case"cos":return Math.cos(i[0]);case"tan":return Math.tan(i[0]);case"exp":return Math.exp(i[0]);case"log":return Math.log(i[0]);default:{const t=e.op;throw new Error(`Unsupported arithmetic op ${t}`)}}}default:throw new Error(`Unsupported expression node ${e.kind}`)}}var rn=({inputs:e,output:t,target:n})=>{const{sourceValues:i}=e;if(!i.value)throw new Error(`${i} does not have CPU value`);const o=new t.ValueType(t.length*t.size);if(0===i.length)return{success:!1,error:/* @__PURE__ */new Error(`${i} is empty`)};for(let s=0;s<i.size;s++){const e=tn(i,0)[s],n=s*t.size,r=n+1;o[n]=e,o[r]=e;for(let t=1;t<i.length;t++){const e=tn(i,t)[s];e<o[n]&&(o[n]=e),e>o[r]&&(o[r]=e)}}return n.write(o),{success:!0,value:o}},an=({inputs:e,output:t,target:n})=>en({func:(e,t)=>{const n=e.length/2,i=new Float64Array(t.buffer);for(let o=0;o<n;o++){const t=i[o];e[o]=Math.fround(t),e[o+n]=t-e[o]}return e},inputs:e,output:t,outputBuffer:n}),ln=async({inputs:e,output:t,target:n})=>{const{ids:i,sourceValues:o}=e,s=i.value,r=o.value;if(!s)throw new Error(`${i} does not have CPU value`);if(!r)throw new Error(`${o} does not have CPU value`);const a=new t.ValueType(t.length*t.size),l=new Array(t.size).fill(0);for(let c=0;c<t.length;c++){const e=tn(i,c),n=Number(e[0]),s=cn(n,o.length)?tn(o,n):l;a.set(s,c*t.size)}return n.write(a),{success:!0,value:a}};function cn(e,t){return Number.isInteger(e)&&e>=0&&e<t}var un=({inputs:e,output:t,target:n})=>en({func:(e,...t)=>{let n=0;for(const i of t)e.set(i,n),n+=i.length},inputs:e,output:t,outputBuffer:n}),fn=({inputs:e,output:t,target:n})=>{const{x:i,y:o}=e,s=new t.ValueType(t.length);for(let r=0;r<t.length;r++){const e=tn(i,r),t=tn(o,r);let n=0;for(let o=0;o<i.size;o++)n+=e[o]*t[o];s[r]=n}return n.write(s),{success:!0,value:s}},dn=({inputs:e,output:t,target:n})=>{const{x:i,y:o}=e,s=new t.ValueType(t.length);for(let r=0;r<t.length;r++){const e=tn(i,r),t=tn(o,r);let n=1;for(let o=0;o<i.size;o++)if(e[o]!==t[o]){n=0;break}s[r]=n}return n.write(s),{success:!0,value:s}},pn=({inputs:e,output:t,target:n})=>{const{x:i}=e,o=new t.ValueType(t.length);for(let s=0;s<t.length;s++){const e=tn(i,s);let t=0;for(let n=0;n<i.size;n++)t+=e[n]*e[n];o[s]=Math.sqrt(t)}return n.write(o),{success:!0,value:o}},gn=async({inputs:e,output:t,target:n})=>{const{segments:i,vertexCount:o}=e,s=i.value;if(!s)throw new Error(`${i} does not have CPU value`);!function(e,t,n){if(t.length<1)throw new Error("segmentedMap segments must contain at least one segment start");let i=0;for(let o=0;o<t.length;o++){const n=e[hn(t,o)];if(0===o&&0!==n)throw new Error(`segmentedMap segments must start at 0, got ${n}`);if(o>0&&n<i)throw new Error(`segmentedMap segments must be non-decreasing, got ${n} after ${i}`);i=n}if(i>n)throw new Error(`segmentedMap last segment start must be <= vertexCount, got ${i} > ${n}`)}(s,i,o);const r=new t.ValueType(t.length*t.size);let a=0;for(let l=0;l<o;l++){for(;a+1<i.length&&s[hn(i,a+1)]<=l;)a++;const e=s[hn(i,a)],n=l*t.size;r[n]=a,r[n+1]=l-e}return n.write(r),{success:!0,value:r}};function hn(e,t){return e.offset/e.ValueType.BYTES_PER_ELEMENT+t*(e.stride/e.ValueType.BYTES_PER_ELEMENT)}var vn=async({inputs:e,output:t,target:n})=>{const{condition:i,whenTrue:o,whenFalse:s}=e,r=new t.ValueType(t.length*t.size);for(let a=0;a<t.length;a++){const e=tn(i,a),n=tn(o,a),l=tn(s,a);for(let c=0;c<t.size;c++){const u=mn(e,i.size,c);r[a*t.size+c]=0!==u?mn(n,o.size,c):mn(l,s.size,c)}}return n.write(r),{success:!0,value:r}};function mn(e,t,n){return n<t?e[n]:1===t?e[0]:0}var _n=({inputs:e,output:t,target:n})=>{const i=new t.ValueType(t.length);for(let o=0;o<t.length;o++)i[o]=e.start+o*e.step;return n.write(i),{success:!0,value:i}},xn=({inputs:e,output:t,target:n})=>{const{columns:i}=e;return en({func:(e,t)=>{for(let n=0;n<i.length;n++)e[n]=t[i[n]]},inputs:{x:e.x},output:t,outputBuffer:n})},yn=/* @__PURE__ */t({arithmetic:()=>on,dot:()=>fn,equalAll:()=>dn,extent:()=>rn,fround:()=>an,gather:()=>ln,interleave:()=>un,length:()=>pn,segmentedMap:()=>gn,select:()=>vn,sequence:()=>_n,swizzle:()=>xn}),bn=new class{_modules={cpu:yn};add(e,t){const n=this._modules[e];if("function"==typeof t.then){const i=Promise.all([Promise.resolve(n||{}),t]).then(([e,t])=>({...e,...t}));return this._modules[e]=i,i.then(t=>{this._modules[e]=t}).catch(t=>{j.error(`Failed to register ${e} backend: ${t}`)()}),i}if(n&&"function"==typeof n.then){const i=Promise.resolve(n).then(e=>({...e,...t})).then(t=>(this._modules[e]=t,t)).catch(t=>{throw j.error(`Failed to register ${e} backend: ${t}`)(),t});return this._modules[e]=i,i}const i={...n||{},...t};return this._modules[e]=i,Promise.resolve(i)}async get(e,t){let n=this._modules[e];if(!n)if("webgl"===e)n=this.add("webgl",import("./webgl-B16MrmDy.js"));else{if("webgpu"!==e)throw new Error(`${e} backend not registered`);n=this.add("webgpu",Promise.resolve().then(()=>ii))}const i=(await n)[t];if("function"!=typeof i)throw new Error(`${e} backend does not implement ${t}`);return i}getSync(e,t){const n=this._modules[e];if(!n)throw new Error(`${e} backend not registered`);if("function"==typeof n.then)throw new Error(`${e} backend is not loaded yet`);const i=n[t];if("function"!=typeof i)throw new Error(`${e} backend does not implement ${t}`);return i}clear(){this._modules={}}},Pn=class{inputs;dependencies;constructor(e){this.inputs=e,this.dependencies=Array.from(e instanceof Array?e:Object.values(e)).filter(e=>e instanceof pe)}async execute(e,t){return await this._resolveDependencies(e),await this._executeWithHandler(await bn.get(this._getHandlerRegistry(e),this.name),t)}executeSync(e,t){this._resolveDependenciesSync(e);const n=this._executeWithHandler(bn.getSync(this._getHandlerRegistry(e),this.name),t);if(i=n,"function"==typeof i?.then)throw new Error(`${this.name} returned a Promise in executeSync()`);var i;return n}shouldExecuteOnCPU(){return this.output.length<=1&&Array.from(this.dependencies).every(e=>Boolean(e.value))}_getHandlerRegistry(e){return this.shouldExecuteOnCPU()?"cpu":e.type}async _resolveDependencies(e){for(const t of this.dependencies)await t.evaluate(e);if("cpu"===this._getHandlerRegistry(e)||"null"===e.type)for(const t of this.dependencies)await t.ensureCPUValue()}_resolveDependenciesSync(e){for(const t of this.dependencies)t.evaluateSync(e);if("cpu"===this._getHandlerRegistry(e)||"null"===e.type)for(const t of this.dependencies)t.ensureCPUValueSync()}_executeWithHandler(e,t){return e({device:t.device,inputs:this.inputs,output:this.output,target:t})}};function Cn(...e){let t=function(e){let t=0,n=0;for(const i of e){if("f"===i[0])return"float32";const e=i.endsWith("8")?8:i.endsWith("6")?16:32;"u"===i[0]?t=Math.max(t,e):n=Math.max(n,e)}return t&&!n?`uint${t}`:n&&t<32?`sint${Math.max(n,2*t)}`:"float32"}(e.map(e=>e.type));return"f"!==t[0]&&e.some(e=>e.normalized)&&(t="float32"),{isConstant:e.every(e=>e.isConstant),type:t,size:e.reduce((e,t)=>Math.max(e,t.size),0),length:e.reduce((e,t)=>Math.max(e,t.length),0)}}var wn=class extends Pn{name="interleave";output;constructor(e){super(e);const{isConstant:t,type:n,length:i}=Cn(...e);this.output=new pe({isConstant:t,type:n,size:e.reduce((e,t)=>e+t.size,0),length:i,source:this})}toString(){return`_${this.inputs.join("_")}_`}};function Sn(e,t){const n=function(e){const t=/* @__PURE__ */new Set;return Ln(e,t,/* @__PURE__ */new Set),Array.from(t)}(t);for(const i of n)i.evaluateSync(e);return function(e){const t=new Set(e.flatMap(In)),n=/* @__PURE__ */new Set;for(const i of e)An(i,n);for(const i of n)i.evaluated&&!t.has(i.buffer)&&i.destroy()}(n),t}function Ln(e,t,n){if(function(e){return e instanceof pe||e instanceof Jt}(e))t.add(e);else if(e&&"object"==typeof e&&!n.has(e))if(n.add(e),Array.isArray(e))for(const i of e)Ln(i,t,n);else if(function(e){const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}(e))for(const i of Object.values(e))Ln(i,t,n)}function An(e,t){if(e instanceof Jt){for(const n of e.gpuDataEvaluators)An(n,t);return}const n=e.source;if(n)if(n instanceof pe)t.has(n)||(t.add(n),An(n,t));else for(const i of n.dependencies)t.has(i)||(t.add(i),An(i,t))}function In(e){return e instanceof pe?[e.buffer]:e.gpuVector.data.map(e=>e.buffer instanceof ge?e.buffer.buffer:e.buffer)}function En(e,t){const n=function(e){return Number.isFinite(e)&&e>0?Math.floor(e):65535}(t),i=Math.max(1,Math.ceil(e)),o=Math.min(i,n),s=Math.min(Math.ceil(i/o),n),r=Math.ceil(i/o/s);if(r>n)throw new Error(`WebGPU dispatch requires ${i} workgroups, exceeding the 3D dispatch limit of ${n} per dimension`);return{x:o,y:s,z:r}}function Tn(e,t="workgroupId"){return`((${t}.z * ${e.y}u + ${t}.y) * ${e.x}u + ${t}.x)`}function On(e,t,n="workgroupId",i="localId"){return`(${Tn(e,n)} * ${t}u + ${i}.x)`}function zn(e,t){switch(e){case"u32":return`${t}u`;case"f32":return Number.isInteger(t)?`${t}.0`:`${t}`;default:return`${t}`}}function Mn(e){switch(e){case"uint32":return"0u";case"sint32":return"0";case"float32":return"0.0";default:throw new Error(`WebGPU operations only support 32-bit output types, got ${e}`)}}function Rn(e){switch(e){case"uint32":return"u32";case"sint32":return"i32";case"float32":return"f32";default:throw new Error(`WebGPU operations only support 32-bit storage types, got ${e}`)}}var Bn=new o;function kn({module:e,elementWise:t=!1,expression:n,inputs:i,output:o,operationType:s=o.type,outputBuffer:r}){if(!e.source)throw new Error(`WebGPU computation ${e.name} requires WGSL source`);const a=function(e){return Array.isArray(e)?e.map((e,t)=>[`x${t}`,e]):Object.entries(e)}(i),l=a.map(([e,t])=>({name:e,input:t})),c=l.filter(({input:e})=>!e.isConstant).map((e,t)=>({...e,index:t})),u=Rn(s),f=Rn(o.type),d={TYPE:u,RESULT_LEN:o.size.toString()},p=En(Math.ceil(o.length/64),r.device.limits.maxComputeWorkgroupsPerDimension);for(const[_,x]of a)d[`${_.toUpperCase()}_LEN`]=x.size.toString();const g=`\n${function(e,t){for(const n in t)e=e.replaceAll(`{${n}}`,t[n]);return e}(e.source,d)}\n${c.map(({name:e,input:t,index:n})=>function(e,t,n){return t.isConstant?"":`@group(0) @binding(${n}) var<storage, read> ${e}: array<${Rn(t.type)}>;`}(e,t,n)).join("\n")}\n${l.map(({name:e,input:t})=>function(e,t,n){const i=Rn(n),o=t.type===n?"":i,s=t.stride/t.ValueType.BYTES_PER_ELEMENT,r=t.offset/t.ValueType.BYTES_PER_ELEMENT;return t.isConstant?`fn read_${e}(_rowIndex: u32) -> array<${i}, ${t.size}> {\n return array<${i}, ${t.size}>(${function(e,t){const n=e.value;if(!n)throw new Error(`Constant input ${e} is missing CPU values`);return Array.from({length:e.size},(e,i)=>zn(t,n[i]??0)).join(", ")}(t,o)});\n}`:`fn read_${e}(rowIndex: u32) -> array<${i}, ${t.size}> {\n var value: array<${i}, ${t.size}>;\n let rowOffset = ${r}u + rowIndex * ${s}u;\n${Array.from({length:t.size},(t,n)=>o?` value[${n}] = ${o}(${e}[rowOffset + ${n}u]);`:` value[${n}] = ${e}[rowOffset + ${n}u];`).join("\n")}\n return value;\n}`}(e,t,s)).join("\n")}\n${function(e,t){return`@group(0) @binding(${t}) var<storage, read_write> result: array<${Rn(e.type)}>;`}(o,c.length)}\n${function(e){const t=e.stride/e.ValueType.BYTES_PER_ELEMENT,n=e.offset/e.ValueType.BYTES_PER_ELEMENT;return`fn write_result(rowIndex: u32, value: array<${Rn(e.type)}, ${e.size}>) {\n let rowOffset = ${n}u + rowIndex * ${t}u;\n${Array.from({length:e.size},(e,t)=>` result[rowOffset + ${t}u] = value[${t}];`).join("\n")}\n}`}(o)}\n\n@compute @workgroup_size(64) fn main(\n @builtin(workgroup_id) workgroupId: vec3<u32>,\n @builtin(local_invocation_id) localId: vec3<u32>\n) {\n let rowIndex = ${On(p,64)};\n if (rowIndex >= ${o.length}u) {\n return;\n }\n\n${l.map(({name:e})=>` let ${e} = read_${e}(rowIndex);`).join("\n")}\n var result: array<${f}, ${o.size}>;\n${function(e,t,n,i,o){let s="";if(o)for(let r=0;r<n.size;r++)s+=` result[${r}] = ${o(r)};\n`;else if(i){const i=Mn(n.type),o=Rn(n.type);for(let r=0;r<n.size;r++){const n=t.map(([e,t])=>r<t.size?Rn(t.type)===o?`${e}[${r}]`:`${o}(${e}[${r}])`:i);s+=` result[${r}] = ${e}(${n.join(", ")});\n`}}else s+=`result = ${e}(${t.map(([e])=>e).join(", ")});`;return s.trimEnd()}(e.name,a,o,t,n)}\n write_result(rowIndex, result);\n}\n`,h=new kt(r.device,{source:g,modules:e.dependencies,shaderAssembler:Bn,shaderLayout:{bindings:[...c.map(({name:e},t)=>({name:e,type:"storage",group:0,location:t})),{name:"result",type:"storage",group:0,location:c.length}]}}),v=Object.fromEntries(c.map(({name:e,input:t})=>[e,t.buffer]));v.result=r,h.setBindings(v);const m=r.device.beginComputePass({});r.device.statsManager.getStats("GPGPU Operation Counts").get("Computation Runs").incrementCount(),h.dispatch(m,p.x,p.y,p.z),m.end(),r.device.submit(),h.destroy()}var Fn=({inputs:e,output:t,target:n})=>{const i=t.type,o=Rn(i),s=Mn(i),r=e.namedInputs;return kn({module:{name:"arithmetic",source:"fn arithmetic_add(x: {TYPE}, y: {TYPE}) -> {TYPE} {\n return x + y;\n}\n\nfn arithmetic_subtract(x: {TYPE}, y: {TYPE}) -> {TYPE} {\n return x - y;\n}\n\nfn arithmetic_multiply(x: {TYPE}, y: {TYPE}) -> {TYPE} {\n return x * y;\n}\n\nfn arithmetic_divide(x: {TYPE}, y: {TYPE}) -> {TYPE} {\n return x / y;\n}\n\nfn arithmetic_tan(x: f32) -> f32 {\n return tan_fp32(x);\n}\n",dependencies:[d]},inputs:r,output:t,operationType:i,outputBuffer:n,expression:t=>he(e.expression,{operations:ue,inputs:r,laneIndex:t,formatInput:e=>`${e}[${t}]`,formatOutOfBoundsInput:e=>1===r[e].size?`${e}[0]`:s,formatLiteral:e=>{const n=Array.isArray(e)?e[t]??0:e;return`${o}(${function(e,t){switch(e){case"uint32":return zn("u32",Math.trunc(t));case"sint32":return`${Math.trunc(t)}`;case"float32":return zn("f32",t);default:throw new Error(`WebGPU operations only support 32-bit output types, got ${e}`)}}(i,n)})`},formatCall:(e,t)=>`${e}(${t.join(", ")})`})}),{success:!0}},Nn=({inputs:e,output:t,target:n})=>(kn({module:{name:"row_dot",source:"fn row_dot(x: array<{TYPE}, {X_LEN}>, y: array<{TYPE}, {Y_LEN}>) -> array<f32, 1> {\n var sum = 0.0;\n for (var i = 0u; i < {X_LEN}u; i = i + 1u) {\n sum += f32(x[i]) * f32(y[i]);\n }\n return array<f32, 1>(sum);\n}\n"},inputs:e,output:t,operationType:"float32",outputBuffer:n}),{success:!0}),Dn=({inputs:e,output:t,target:n})=>(kn({module:{name:"equalAll",source:"fn equalAll(x: array<{TYPE}, {X_LEN}>, y: array<{TYPE}, {Y_LEN}>) -> array<u32, 1> {\n var allEqual = 1u;\n for (var i = 0u; i < {X_LEN}u; i = i + 1u) {\n if (x[i] != y[i]) {\n allEqual = 0u;\n break;\n }\n }\n return array<u32, 1>(allEqual);\n}\n"},inputs:e,output:t,operationType:e.x.type,outputBuffer:n}),{success:!0});function jn(e,t,n){return`@group(0) @binding(${n}) var<storage, read> ${e}: array<${Rn(t.type)}>;`}function Un(e,t,n,i=e){const o=Rn(n);if(t.isConstant){const e=t.value;if(!e)throw new Error(`Constant input ${t} is missing CPU values`);return`fn read_${i}(_sourceIndex: u32) -> array<${o}, ${t.size}> {\n return array<${o}, ${t.size}>(${Array.from({length:t.size},(t,n)=>zn(o,e[n]??0)).join(", ")});\n}`}const s=t.stride/t.ValueType.BYTES_PER_ELEMENT,r=t.offset/t.ValueType.BYTES_PER_ELEMENT,a=Rn(t.type)===o?"":`${o}`;return`fn read_${i}(sourceIndex: u32) -> array<${o}, ${t.size}> {\n var value: array<${o}, ${t.size}>;\n let rowOffset = ${r}u + sourceIndex * ${s}u;\n${Array.from({length:t.size},(t,n)=>a?` value[${n}] = ${a}(${e}[rowOffset + ${n}u]);`:` value[${n}] = ${e}[rowOffset + ${n}u];`).join("\n")}\n return value;\n}`}function Gn(e,t){return Un("sourceValues",e,t,"source_values")}function Vn(e,t){return`@group(0) @binding(${t}) var<storage, read_write> result: array<${Rn(e.type)}>;`}function $n(e){const t=e.stride/e.ValueType.BYTES_PER_ELEMENT,n=e.offset/e.ValueType.BYTES_PER_ELEMENT;return`fn write_result(rowIndex: u32, value: array<${Rn(e.type)}, ${e.size}>) {\n let rowOffset = ${n}u + rowIndex * ${t}u;\n${Array.from({length:e.size},(e,t)=>` result[rowOffset + ${t}u] = value[${t}];`).join("\n")}\n}`}var Wn=({inputs:e,output:t,target:n})=>{const{sourceValues:i}=e;if(0===i.length){const e=new t.ValueType(t.length*t.size);return n.write(e),{success:!0,value:e}}if(i.isConstant){const e=i.value;if(!e)throw new Error(`Constant input ${i} is missing CPU values`);const o=new t.ValueType(t.length*t.size);for(let n=0;n<t.length;n++){const t=e[n];o[2*n]=t,o[2*n+1]=t}return n.write(o),{success:!0,value:o}}const o=[];let s=i,r="raw",a=i.length;try{for(;;){const e=Math.ceil(a/64),i=t.length*e,l=1===e?n:te.createOrReuse(n.device,i*t.stride);if(e>1&&o.push(l),Hn({input:s,inputMode:r,inputGroupCount:a,channelCount:t.length,outputType:t.type,outputBuffer:l,outputLength:i,outputStride:t.stride,outputOffset:t.offset}),1===e)break;s=new pe({buffer:l,type:t.type,size:2,length:i}),r="partial",a=e}return{success:!0}}finally{for(const e of o)te.recycle(e)}};function Hn({input:e,inputMode:t,inputGroupCount:n,channelCount:i,outputType:o,outputBuffer:s,outputLength:r,outputStride:a,outputOffset:l}){const c=Rn(o),u=En(r,s.device.limits.maxComputeWorkgroupsPerDimension),f=new pe({buffer:s,type:o,size:2,length:r,stride:a,offset:l}),d=`\n${e.isConstant?"":jn("sourceValues",e,0)}\n${Gn(e,o)}\n${Vn(f,e.isConstant?0:1)}\n${$n(f)}\n${function(e,t,n,i){const o=Rn(t),[s,r]=function(e){switch(e){case"uint32":return["0xffffffffu","0u"];case"sint32":return["2147483647","-2147483648"];case"float32":return["3.402823e38","-3.402823e38"];default:throw new Error(`Unsupported WebGPU extent type for ${e}`)}}(t);return"raw"===e?`fn extent_pass(channelIndex: u32, inputGroupIndex: u32) -> array<${o}, 2> {\n var result: array<${o}, 2>;\n result[0] = ${s};\n result[1] = ${r};\n\n if (inputGroupIndex < ${i}u) {\n let value = read_source_values(inputGroupIndex);\n result[0] = value[channelIndex];\n result[1] = value[channelIndex];\n }\n\n return result;\n}`:`fn extent_pass(channelIndex: u32, inputGroupIndex: u32) -> array<${o}, 2> {\n var result: array<${o}, 2>;\n result[0] = ${s};\n result[1] = ${r};\n\n if (inputGroupIndex < ${i}u) {\n let rowIndex = inputGroupIndex * ${n}u + channelIndex;\n let value = read_source_values(rowIndex);\n result[0] = value[0];\n result[1] = value[1];\n }\n\n return result;\n}`}(t,o,i,n)}\n\nvar<workgroup> sharedMin: array<${c}, 64>;\nvar<workgroup> sharedMax: array<${c}, 64>;\n\n@compute @workgroup_size(64) fn main(\n @builtin(workgroup_id) workgroupId: vec3<u32>,\n @builtin(local_invocation_id) localId: vec3<u32>\n) {\n let outputRowIndex = ${Tn(u)};\n if (outputRowIndex >= ${r}u) {\n return;\n }\n\n let channelIndex = outputRowIndex % ${i}u;\n let outputGroupIndex = outputRowIndex / ${i}u;\n let inputGroupIndex = outputGroupIndex * 64u + localId.x;\n\n let result = extent_pass(channelIndex, inputGroupIndex);\n sharedMin[localId.x] = result[0];\n sharedMax[localId.x] = result[1];\n workgroupBarrier();\n\n var stride = ${Math.floor(32)}u;\n loop {\n if (stride == 0u) {\n break;\n }\n if (localId.x < stride) {\n let compareIndex = localId.x + stride;\n if (sharedMin[compareIndex] < sharedMin[localId.x]) {\n sharedMin[localId.x] = sharedMin[compareIndex];\n }\n if (sharedMax[compareIndex] > sharedMax[localId.x]) {\n sharedMax[localId.x] = sharedMax[compareIndex];\n }\n }\n workgroupBarrier();\n stride = stride / 2u;\n }\n\n if (localId.x == 0u) {\n write_result(outputRowIndex, array<${c}, 2>(sharedMin[0], sharedMax[0]));\n }\n}\n`,p=new kt(s.device,{source:d,shaderLayout:{bindings:[...e.isConstant?[]:[{name:"sourceValues",type:"storage",group:0,location:0}],{name:"result",type:"storage",group:0,location:e.isConstant?0:1}]}}),g={result:s};e.isConstant||(g.sourceValues=e.buffer),p.setBindings(g);const h=s.device.beginComputePass({});p.dispatch(h,u.x,u.y,u.z),h.end(),s.device.submit(),p.destroy()}var Zn=`const LE: bool = ${function(){const e=new Uint16Array([255]);return new Uint8Array(e.buffer)[0]>0}()?"true":"false"};\nconst F32_NAN: u32 = 0xffffffffu;\nconst F32_INF: u32 = 0x7f800000u;\n\nfn roundShiftRight(value: u32, shift: i32) -> u32 {\n if (shift <= 0) {\n return value << u32(-shift);\n }\n\n if (shift >= 32) {\n if (shift == 32 && value > 0x80000000u) {\n return 1u;\n }\n return 0u;\n }\n\n let shiftU32 = u32(shift);\n let truncated = value >> shiftU32;\n let halfShift = 1u << u32(shift - 1);\n let remainder = value & ((1u << shiftU32) - 1u);\n if (remainder > halfShift || (remainder == halfShift && (truncated & 1u) == 1u)) {\n return truncated + 1u;\n }\n return truncated;\n}\n\nfn makeFloatImmediate(sign: u32, exponent: i32, mantissa: u32) -> u32 {\n return (sign << 31u) | (u32(exponent + 127) << 23u) | (mantissa & 0x7fffffu);\n}\n\nfn makeFloat(sign: u32, exponent: i32, significand: u32) -> u32 {\n if (significand == 0u) {\n return sign << 31u;\n }\n\n let leadingZeros = i32(countLeadingZeros(significand));\n var normalizedExponent = exponent + 31 - leadingZeros;\n\n if (normalizedExponent > 127) {\n return (sign << 31u) | F32_INF;\n }\n\n var mantissa: u32;\n if (normalizedExponent >= -126) {\n mantissa = roundShiftRight(significand, 8 - leadingZeros);\n if (mantissa >= 0x1000000u) {\n mantissa = mantissa >> 1u;\n normalizedExponent += 1;\n if (normalizedExponent > 127) {\n return (sign << 31u) | F32_INF;\n }\n }\n return makeFloatImmediate(sign, normalizedExponent, mantissa);\n }\n\n let subnormalShift = -149 - exponent;\n mantissa = roundShiftRight(significand, subnormalShift);\n if (mantissa >= 0x800000u) {\n return (sign << 31u) | (1u << 23u);\n }\n return (sign << 31u) | mantissa;\n}\n\nfn parseAsDouble(words: vec2<u32>) -> vec2<u32> {\n var d = words;\n if (LE) {\n d = d.yx;\n }\n\n let sign = (d.x >> 31u) & 1u;\n let exponentBits = (d.x >> 20u) & 0x7ffu;\n let exponent = i32(exponentBits) - 1023;\n let fractionHigh = d.x & 0xfffffu;\n let fractionLow = d.y;\n\n if (exponentBits == 0x7ffu) {\n if (fractionHigh == 0u && fractionLow == 0u) {\n return vec2<u32>((sign << 31u) | F32_INF, F32_NAN);\n }\n return vec2<u32>(F32_NAN);\n }\n\n if (exponentBits == 0u) {\n return vec2<u32>(sign << 31u);\n }\n\n if (exponent > 127) {\n return vec2<u32>((sign << 31u) | F32_INF, ((1u - sign) << 31u) | F32_INF);\n }\n\n let highSignificand = 0x800000u | (fractionHigh << 3u) | (fractionLow >> 29u);\n let lowSignificand = fractionLow & 0x1fffffffu;\n\n if (exponent < -126) {\n let highPart = makeFloat(sign, exponent - 23, highSignificand);\n let lowPart = makeFloat(sign, exponent - 52, lowSignificand);\n return vec2<u32>(highPart, lowPart);\n }\n\n let roundUp = lowSignificand > 0x10000000u ||\n (lowSignificand == 0x10000000u && (highSignificand & 1u) == 1u);\n\n var roundedSignificand = highSignificand + select(0u, 1u, roundUp);\n var highExponent = exponent;\n if (roundedSignificand == 0x1000000u) {\n roundedSignificand = 0x800000u;\n highExponent += 1;\n }\n\n if (highExponent > 127) {\n return vec2<u32>((sign << 31u) | F32_INF, ((1u - sign) << 31u) | F32_INF);\n }\n\n let highPart = makeFloatImmediate(sign, highExponent, roundedSignificand);\n\n var remainder = i32(lowSignificand);\n var lowSign = sign;\n if (roundUp) {\n remainder -= 0x20000000;\n }\n if (remainder < 0) {\n lowSign = 1u - sign;\n remainder = -remainder;\n }\n\n let lowPart = makeFloat(lowSign, exponent - 52, u32(remainder));\n return vec2<u32>(highPart, lowPart);\n}\n\nfn fround(x: array<u32, {X_LEN}>) -> array<f32, {RESULT_LEN}> {\n var result: array<f32, {RESULT_LEN}>;\n let n = {X_LEN}u / 2u;\n for (var i = 0u; i < n; i = i + 1u) {\n let parts = parseAsDouble(vec2<u32>(x[i * 2u], x[i * 2u + 1u]));\n result[i] = bitcast<f32>(parts.x);\n result[i + n] = bitcast<f32>(parts.y);\n }\n return result;\n}\n`,Yn=({inputs:e,output:t,target:n})=>(kn({module:{name:"fround",source:Zn},inputs:e,output:t,operationType:"uint32",outputBuffer:n}),{success:!0}),qn=async({inputs:e,output:t,target:n})=>{const{ids:i,sourceValues:o}=e,s=Rn(i.type),r=[];i.isConstant||r.push({name:"ids",input:i,index:r.length}),o.isConstant||r.push({name:"sourceValues",input:o,index:r.length});const a=En(Math.ceil(t.length/64),n.device.limits.maxComputeWorkgroupsPerDimension),l=`\n${r.map(({name:e,input:t,index:n})=>jn(e,t,n)).join("\n")}\n${function(e,t){if(e.isConstant){const n=e.value;if(!n)throw new Error(`Constant input ${e} is missing CPU values`);return`fn read_ids(_rowIndex: u32) -> ${t} {\n return ${zn(t,n[0]??0)};\n}`}const n=e.stride/e.ValueType.BYTES_PER_ELEMENT;return`fn read_ids(rowIndex: u32) -> ${t} {\n let rowOffset = ${e.offset/e.ValueType.BYTES_PER_ELEMENT}u + rowIndex * ${n}u;\n return ids[rowOffset];\n}`}(i,s)}\n${Gn(o,t.type)}\n${Vn(t,r.length)}\n${$n(t)}\n${function(e,t){const n=Mn(e);return`fn zero_result() -> array<${Rn(e)}, ${t}> {\n var result: array<${Rn(e)}, ${t}>;\n${Array.from({length:t},(e,t)=>` result[${t}] = ${n};`).join("\n")}\n return result;\n}`}(t.type,t.size)}\n${function(e,t,n,i){const o=Rn(e);return`fn gather(idsValue: ${o}) -> array<${Rn(t)}, ${n}> {\n let sourceIndex = ${"u32"===o?"i32(idsValue)":"i32"===o?"idsValue":"i32(idsValue)"};\n if (sourceIndex < 0 || sourceIndex >= ${i}) {\n return zero_result();\n }\n return read_source_values(u32(sourceIndex));\n}`}(i.type,t.type,t.size,o.length)}\n\n@compute @workgroup_size(64) fn main(\n @builtin(workgroup_id) workgroupId: vec3<u32>,\n @builtin(local_invocation_id) localId: vec3<u32>\n) {\n let rowIndex = ${On(a,64)};\n if (rowIndex >= ${t.length}u) {\n return;\n }\n\n let idsValue = read_ids(rowIndex);\n let result = gather(idsValue);\n write_result(rowIndex, result);\n}\n`,c=new kt(n.device,{source:l,shaderLayout:{bindings:[...r.map(({name:e,index:t})=>({name:e,type:"storage",group:0,location:t})),{name:"result",type:"storage",group:0,location:r.length}]}}),u={};i.isConstant||(u.ids=i.buffer),o.isConstant||(u.sourceValues=o.buffer),u.result=n,c.setBindings(u);const f=n.device.beginComputePass({});return c.dispatch(f,a.x,a.y,a.z),f.end(),n.device.submit(),c.destroy(),{success:!0}};var Kn=async({inputs:e,output:t,target:n})=>{const{segments:i}=e,o=i.isConstant?[]:[{name:"segments",input:i,index:0}],s=En(Math.ceil(t.length/64),n.device.limits.maxComputeWorkgroupsPerDimension),r=`\n${o.map(({name:e,input:t,index:n})=>jn(e,t,n)).join("\n")}\n${Un("segments",i,"uint32")}\n${Vn(t,o.length)}\n${$n(t)}\n${a=i.length,`fn segmented_map(vertexIndex: u32) -> array<u32, 2> {\n var low = 0i;\n var high = ${a}i;\n while (low < high) {\n let mid = low + (high - low) / 2i;\n let midStart = read_segments(u32(mid))[0];\n if (midStart <= vertexIndex) {\n low = mid + 1i;\n } else {\n high = mid;\n }\n }\n\n let segmentIndex = u32(max(low - 1i, 0i));\n let segmentStart = read_segments(segmentIndex)[0];\n return array<u32, 2>(segmentIndex, vertexIndex - segmentStart);\n}`}\n\n@compute @workgroup_size(64) fn main(\n @builtin(workgroup_id) workgroupId: vec3<u32>,\n @builtin(local_invocation_id) localId: vec3<u32>\n) {\n let rowIndex = ${On(s,64)};\n if (rowIndex >= ${t.length}u) {\n return;\n }\n\n let result = segmented_map(rowIndex);\n write_result(rowIndex, result);\n}\n`;var a;const l=new kt(n.device,{source:r,shaderLayout:{bindings:[...o.map(({name:e,index:t})=>({name:e,type:"storage",group:0,location:t})),{name:"result",type:"storage",group:0,location:o.length}]}}),c=Object.fromEntries(o.map(({name:e,input:t})=>[e,t.buffer]));c.result=n,l.setBindings(c);const u=n.device.beginComputePass({});return l.dispatch(u,s.x,s.y,s.z),u.end(),n.device.submit(),l.destroy(),{success:!0}};var Xn=({inputs:e,output:t,target:n})=>{const i=e.map((e,t)=>[`x${t}`,e]);!function(e,t){const n=t.filter(([,e])=>!e.isConstant).length+1;if(n>e.maxStorageBuffersPerShaderStage)throw new Error(`interleave() requires ${n} storage buffers, exceeding device limit ${e.maxStorageBuffersPerShaderStage}`);if(n>e.maxBindingsPerBindGroup)throw new Error(`interleave() requires ${n} bindings, exceeding bind group limit ${e.maxBindingsPerBindGroup}`)}(n.device.limits,i);const o=i.map(([e,t])=>`${e}: array<{TYPE}, ${t.size}>`).join(", ");let s=0;return kn({module:{name:"interleave",source:`fn interleave(${o}) -> array<{TYPE}, {RESULT_LEN}> {\n var out: array<{TYPE}, {RESULT_LEN}>;\n${i.map(([e,t])=>{const n=Array.from({length:t.size},(t,n)=>` out[${s+n}] = ${e}[${n}];`).join("\n");return s+=t.size,n}).join("\n")}\n return out;\n}\n`},inputs:e,output:t,outputBuffer:n}),{success:!0}};var Jn=({inputs:e,output:t,target:n})=>(kn({module:{name:"row_length",source:"fn row_length(x: array<{TYPE}, {X_LEN}>) -> array<f32, 1> {\n var sum = 0.0;\n for (var i = 0u; i < {X_LEN}u; i = i + 1u) {\n sum += f32(x[i]) * f32(x[i]);\n }\n return array<f32, 1>(sqrt(sum));\n}\n"},inputs:e,output:t,operationType:"float32",outputBuffer:n}),{success:!0}),Qn=async({inputs:e,output:t,target:n})=>{const i=Mn(t.type);return kn({module:{name:"select",source:"// inline expression select\n"},inputs:e,output:t,operationType:t.type,outputBuffer:n,expression:t=>{const n=ei("condition",e.condition,t,i),o=ei("whenTrue",e.whenTrue,t,i);return`select(${ei("whenFalse",e.whenFalse,t,i)}, ${o}, ${n} != ${i})`}}),{success:!0}};function ei(e,t,n,i){return n<t.size?`${e}[${n}]`:1===t.size?`${e}[0]`:i}var ti=({inputs:e,output:t,target:n})=>{const i=En(Math.ceil(t.length/64),n.device.limits.maxComputeWorkgroupsPerDimension),o=`@group(0) @binding(0) var<storage, read_write> result: array<i32>;\n\n@compute @workgroup_size(64) fn main(\n @builtin(workgroup_id) workgroupId: vec3<u32>,\n @builtin(local_invocation_id) localId: vec3<u32>\n) {\n let rowIndex = ${On(i,64)};\n if (rowIndex >= ${t.length}u) {\n return;\n }\n\n let rowOffset = ${t.offset/t.ValueType.BYTES_PER_ELEMENT}u + rowIndex * ${t.stride/t.ValueType.BYTES_PER_ELEMENT}u;\n result[rowOffset] = ${e.start} + i32(rowIndex) * ${e.step};\n}\n`,s=new kt(n.device,{source:o,shaderLayout:{bindings:[{name:"result",type:"storage",group:0,location:0}]}});s.setBindings({result:n});const r=n.device.beginComputePass({});return s.dispatch(r,i.x,i.y,i.z),r.end(),n.device.submit(),s.destroy(),{success:!0}},ni=({inputs:e,output:t,target:n})=>{const{columns:i}=e;return kn({module:{name:"swizzle",source:"// swizzle expression handled inline"},expression:e=>`x[${i[e]}]`,inputs:{x:e.x},output:t,outputBuffer:n}),{success:!0}},ii=/* @__PURE__ */t({arithmetic:()=>Fn,dot:()=>Nn,equalAll:()=>Dn,extent:()=>Wn,fround:()=>Yn,gather:()=>qn,interleave:()=>Xn,length:()=>Jn,segmentedMap:()=>Kn,select:()=>Qn,sequence:()=>ti,swizzle:()=>ni}),oi=class{constructor(e,{id:t,isTransitionAttribute:n}){this.packedBuffers={},this.device=e,this.id=t,this.isTransitionAttribute=n,"webgpu"===this.device.type&&bn.add("webgpu",{interleave:Xn})}hasGroups(e){return"webgpu"===this.device.type&&Object.values(e).some(e=>Boolean(e.settings.bufferGroup))}finalize(){for(const e of Object.values(this.packedBuffers))e.packed.destroy();this.packedBuffers={}}getBufferLayouts(e,t){const n=this._getPackedGroups(e,t,{requireValues:!1,excludeAttributes:{}});return this._getBufferLayouts(e,n,t)}getBindings(e,t,n,i){const o=this._getPackedGroups(e,n,{requireValues:!0,excludeAttributes:i}),s={},r=/* @__PURE__ */new Set;for(const a of o.values()){const e=!this.packedBuffers[a.id]||a.attributes.some(e=>Boolean(t[e.id]));s[a.id]=this._getPackedBuffer(a,e);for(const t of a.attributes)r.add(t.id)}return{bufferLayouts:this._getBufferLayouts(e,o,n).filter(t=>!i[t.name]&&!e[t.name]?.settings.isIndexed),buffers:s,groupedAttributeIds:r}}_getPackedGroups(e,t,{requireValues:n,excludeAttributes:i}){const o=/* @__PURE__ */new Map;for(const r of Object.values(e)){const e=r.settings.bufferGroup;if(!e)continue;const t=o.get(e)||[];t.push(r),o.set(e,t)}const s=/* @__PURE__ */new Map;for(const[r,a]of o){const e=this._getPackedGroup(r,a,t,n,i);e&&s.set(r,e)}return s}_getPackedGroup(e,t,n,i,o){if(t.length<2)return null;const s=t.map(e=>e.getBufferLayout(n)),r=s[0].stepMode,a=Math.max(1,t[0].numInstances),l=i&&t.every(e=>e.isConstant);for(let d=0;d<t.length;d++){const e=t[d],n=e.getAccessor(),l=n.size*n.bytesPerElement;if(o[e.id]||e.settings.isIndexed||e.settings.noAlloc||e.doublePrecision||this.isTransitionAttribute(e.id)||s[d].stepMode!==r||e.numInstances!==t[0].numInstances||0!==(n.offset||0)||0!==(n.vertexOffset||0)||Dt(n)!==l||i&&(e.isConstant?!e.getConstantValue()||e.getConstantValue().byteLength<l:!ArrayBuffer.isView(e.value)||e.value.byteLength<a*l))return null}const c={},u=[];let f=0;for(let d=0;d<t.length;d++){const e=t[d];f=si(f),c[e.id]=f;for(const t of s[d].attributes||[])u.push({...t,byteOffset:f+(t.byteOffset||0)});f+=Dt(e.getAccessor())}return f=si(f),{id:e,attributes:t,byteStride:f,byteOffsets:c,rowCount:a,layout:{name:e,byteStride:l?0:f,stepMode:r,attributes:u}}}_getBufferLayouts(e,t,n){const i=[],o=/* @__PURE__ */new Set,s=/* @__PURE__ */new Set;for(const r of t.values())for(const e of r.attributes)s.add(e.id);for(const r of Object.values(e)){const e=r.settings.bufferGroup,a=e&&t.get(e);a&&s.has(r.id)?o.has(a.id)||(i.push(a.layout),o.add(a.id)):i.push(r.getBufferLayout(n))}return i}_getPackedBuffer(e,t){const n=JSON.stringify({byteStride:e.layout.byteStride,attributes:e.layout.attributes}),i=this.packedBuffers[e.id];if(i&&i.layoutKey===n||(t=!0),t){i&&(i.packed.destroy(),delete this.packedBuffers[e.id]);const t=this._interleavePackedGroup(e);return this.packedBuffers[e.id]={packed:t,layoutKey:n},t.buffer}if(!i)throw new Error(`Attribute buffer group ${e.id} has no packed buffer`);return i.packed.buffer}_interleavePackedGroup(e){const t=function(...e){if(0===e.length)throw new Error("interleave() requires at least one input");return 1===e.length?ae(e[0]):new wn(e.map(ae)).output}(...e.attributes.map(t=>this._getInterleaveInput(e,t)));return Sn(this.device,t),t}_getInterleaveInput(e,t){const n=Dt(t.getAccessor()),i=e.byteOffsets[t.id];if(ri(`${e.id}.${t.id} rowByteLength`,n),ri(`${e.id}.${t.id} groupByteOffset`,i),t.isConstant){const i=t.getConstantValue();if(!i)throw new Error(`Attribute group ${e.id} is missing constant value ${t.id}`);return ri(`${e.id}.${t.id} constant byteOffset`,i.byteOffset),new pe({id:t.id,type:"uint32",size:n/4,isConstant:!0,value:new Uint32Array(i.buffer,i.byteOffset,n/Uint32Array.BYTES_PER_ELEMENT)})}const o=t.getBuffer(),s=t.byteOffset,r=t.getAccessor().stride||n;if(ri(`${e.id}.${t.id} byteOffset`,s),ri(`${e.id}.${t.id} stride`,r),!o)throw new Error(`Attribute group ${e.id} cannot interleave missing buffer ${t.id}`);return new pe({id:t.id,type:"uint32",size:n/4,offset:s,stride:r,length:e.rowCount,buffer:o})}};function si(e){return 4*Math.ceil(e/4)}function ri(e,t){if(t%4!=0)throw new Error(`Attribute buffer groups require 32-bit alignment: ${e}=${t}`)}function ai(e){const{source:t,target:n,start:i=0,size:o,getData:s}=e,r=e.end||n.length,a=t.length,l=r-i;if(a>l)return void n.set(t.subarray(0,l),i);if(n.set(t,i),!s)return;let c=a;for(;c<l;){const e=s(c,t);for(let t=0;t<o;t++)n[i+c]=e[t]||0,c++}}function li(e){switch(e){case 1:return"float";case 2:return"vec2";case 3:return"vec3";case 4:return"vec4";default:throw new Error(`No defined attribute type for size "${e}"`)}}function ci(e){switch(e){case 1:return"float32";case 2:return"float32x2";case 3:return"float32x3";case 4:return"float32x4";default:throw new Error("invalid type size")}}function ui(e){e.push(e.shift())}function fi({device:e,source:t,target:n}){return(!n||n.byteLength<t.byteLength)&&(n?.destroy(),n=e.createBuffer({byteLength:t.byteLength,usage:t.usage})),n}function di({device:e,buffer:t,attribute:n,fromLength:i,toLength:o,fromStartIndices:s,getData:r=e=>e}){const a=n.isDoublePrecisionBuffer?2:1,l=n.size*a,c=n.byteOffset,u=n.settings.bytesPerElement<4?c/n.settings.bytesPerElement*4:c,f=n.startIndices,d=s&&f,p=n.isConstant;if(!d&&t&&i>=o)return t;const g=n.value instanceof Float64Array?Float32Array:n.value.constructor,h=p?n.value:new g(n.getBuffer().readSyncWebGL(c,o*g.BYTES_PER_ELEMENT).buffer);if(n.settings.normalized&&!p){const e=r;r=(t,i)=>n.normalizeConstant(e(t,i))}const v=p?(e,t)=>r(h,t):(e,t)=>r(h.subarray(e,e+l),t),m=t?new Float32Array(t.readSyncWebGL(u,4*i).buffer):/* @__PURE__ */new Float32Array(0),_=new Float32Array(o);return function({source:e,target:t,size:n,getData:i,sourceStartIndices:o,targetStartIndices:s}){if(!o||!s)return ai({source:e,target:t,size:n,getData:i}),t;let r=0,a=0;const l=i&&((e,t)=>i(e+a,t)),c=Math.min(o.length,s.length);for(let u=1;u<c;u++){const i=o[u]*n,c=s[u]*n;ai({source:e.subarray(r,i),target:t,start:a,end:c,size:n,getData:l}),r=i,a=c}a<t.length&&ai({source:[],target:t,start:a,size:n,getData:l})}({source:m,target:_,sourceStartIndices:s,targetStartIndices:f,size:l,getData:v}),(!t||t.byteLength<_.byteLength+u)&&(t?.destroy(),t=e.createBuffer({byteLength:_.byteLength+u,usage:35050})),t.write(_,u),t}var pi=class{constructor({device:e,attribute:t,timeline:n}){this.buffers=[],this.currentLength=0,this.device=e,this.transition=new L(n),this.attribute=t,this.attributeInTransition=function(e){const{device:t,settings:n,value:i}=e,o=new Xt(t,n);return o.setData({value:i instanceof Float64Array?/* @__PURE__ */new Float64Array(0):/* @__PURE__ */new Float32Array(0),normalized:n.normalized}),o}(t),this.currentStartIndices=t.startIndices}get inProgress(){return this.transition.inProgress}start(e,t,n=1/0){this.settings=e,this.currentStartIndices=this.attribute.startIndices,this.currentLength=function(e,t){const{settings:n,value:i,size:o}=e,s=e.isDoublePrecisionBuffer?2:1;let r=0;const{shaderAttributes:a}=e.settings;if(a)for(const l of Object.values(a))r=Math.max(r,l.vertexOffset??0);return(n.noAlloc?i.length:(t+r)*o)*s}(this.attribute,t),this.transition.start({...e,duration:n})}update(){const e=this.transition.update();return e&&this.onUpdate(),e}setBuffer(e){const{stride:t}=this.attributeInTransition.getAccessor();this.attributeInTransition.setData({buffer:e,normalized:this.attribute.settings.normalized,value:this.attributeInTransition.value,stride:t})}cancel(){this.transition.cancel()}delete(){this.cancel();for(const e of this.buffers)e.destroy();this.buffers.length=0}},gi={name:"interpolation",vs:"layout(std140) uniform interpolationUniforms {\n float time;\n} interpolation;\n",uniformTypes:{time:"f32"}},hi="#version 300 es\n#define SHADER_NAME interpolation-transition-vertex-shader\n\nin ATTRIBUTE_TYPE aFrom;\nin ATTRIBUTE_TYPE aTo;\nout ATTRIBUTE_TYPE vCurrent;\n\nvoid main(void) {\n vCurrent = mix(aFrom, aTo, interpolation.time);\n gl_Position = vec4(0.0);\n}\n",vi="#version 300 es\n#define SHADER_NAME interpolation-transition-vertex-shader\n\nin ATTRIBUTE_TYPE aFrom;\nin ATTRIBUTE_TYPE aFrom64Low;\nin ATTRIBUTE_TYPE aTo;\nin ATTRIBUTE_TYPE aTo64Low;\nout ATTRIBUTE_TYPE vCurrent;\nout ATTRIBUTE_TYPE vCurrent64Low;\n\nvec2 mix_fp64(vec2 a, vec2 b, float x) {\n vec2 range = sub_fp64(b, a);\n return sum_fp64(a, mul_fp64(range, vec2(x, 0.0)));\n}\n\nvoid main(void) {\n for (int i=0; i<ATTRIBUTE_SIZE; i++) {\n vec2 value = mix_fp64(vec2(aFrom[i], aFrom64Low[i]), vec2(aTo[i], aTo64Low[i]), interpolation.time);\n vCurrent[i] = value.x;\n vCurrent64Low[i] = value.y;\n }\n gl_Position = vec4(0.0);\n}\n";function mi(e){return e.isDoublePrecisionBuffer}var _i={name:"spring",vs:"layout(std140) uniform springUniforms {\n float damping;\n float stiffness;\n} spring;\n",uniformTypes:{damping:"f32",stiffness:"f32"}},xi="#version 300 es\n#define SHADER_NAME spring-transition-vertex-shader\n\n#define EPSILON 0.00001\n\nin ATTRIBUTE_TYPE aPrev;\nin ATTRIBUTE_TYPE aCur;\nin ATTRIBUTE_TYPE aTo;\nout ATTRIBUTE_TYPE vNext;\nout float vIsTransitioningFlag;\n\nATTRIBUTE_TYPE getNextValue(ATTRIBUTE_TYPE cur, ATTRIBUTE_TYPE prev, ATTRIBUTE_TYPE dest) {\n ATTRIBUTE_TYPE velocity = cur - prev;\n ATTRIBUTE_TYPE delta = dest - cur;\n ATTRIBUTE_TYPE force = delta * spring.stiffness;\n ATTRIBUTE_TYPE resistance = velocity * spring.damping;\n return force - resistance + velocity + cur;\n}\n\nvoid main(void) {\n bool isTransitioning = length(aCur - aPrev) > EPSILON || length(aTo - aCur) > EPSILON;\n vIsTransitioningFlag = isTransitioning ? 1.0 : 0.0;\n\n vNext = getNextValue(aCur, aPrev, aTo);\n gl_Position = vec4(0, 0, 0, 1);\n gl_PointSize = 100.0;\n}\n",yi="#version 300 es\n#define SHADER_NAME spring-transition-is-transitioning-fragment-shader\n\nin float vIsTransitioningFlag;\n\nout vec4 fragColor;\n\nvoid main(void) {\n if (vIsTransitioningFlag == 0.0) {\n discard;\n }\n fragColor = vec4(1.0);\n}";var bi={interpolation:class extends pi{constructor({device:e,attribute:t,timeline:n}){super({device:e,attribute:t,timeline:n}),this.type="interpolation",this.hasUpdated=!1,this.transform=function(e,t){const n=t.size,i=li(n),o=ci(n),s=t.getBufferLayout();return mi(t)?new Ct(e,{vs:vi,bufferLayout:[{name:"aFrom",byteStride:8*n,attributes:[{attribute:"aFrom",format:o,byteOffset:0},{attribute:"aFrom64Low",format:o,byteOffset:4*n}]},{name:"aTo",byteStride:8*n,attributes:[{attribute:"aTo",format:o,byteOffset:0},{attribute:"aTo64Low",format:o,byteOffset:4*n}]}],modules:[Ae,gi],defines:{ATTRIBUTE_TYPE:i,ATTRIBUTE_SIZE:n},moduleSettings:{},varyings:["vCurrent","vCurrent64Low"],bufferMode:35980,disableWarnings:!0}):new Ct(e,{vs:hi,bufferLayout:[{name:"aFrom",format:o},{name:"aTo",format:s.attributes[0].format}],modules:[gi],defines:{ATTRIBUTE_TYPE:i},varyings:["vCurrent"],disableWarnings:!0})}(e,t)}start(e,t){const n=this.currentLength,i=this.currentStartIndices;if(super.start(e,t,e.duration),e.duration<=0)return void this.transition.cancel();const{buffers:o,attribute:s}=this;this.hasUpdated&&ui(o),this.hasUpdated=!1,o[0]=di({device:this.device,buffer:o[0],attribute:s,fromLength:n,toLength:this.currentLength,fromStartIndices:i,getData:e.enter}),o[1]=fi({device:this.device,source:o[0],target:o[1]}),this.setBuffer(o[1]);const{transform:r}=this,a=r.model;let l=Math.floor(this.currentLength/s.size);mi(s)&&(l/=2),a.setVertexCount(l),s.isConstant?(a.setAttributes({aFrom:o[0]}),a.setConstantAttributes({aTo:s.value})):a.setAttributes({aFrom:o[0],aTo:s.getBuffer()}),r.transformFeedback.setBuffers({vCurrent:o[1]})}onUpdate(){const{duration:e,easing:t}=this.settings,{time:n}=this.transition;let i=n/e;t&&(i=t(i));const{model:o}=this.transform,s={time:i};o.shaderInputs.setProps({interpolation:s}),this.transform.run({discard:!0}),this.hasUpdated=!0}delete(){super.delete(),this.transform.destroy()}},spring:class extends pi{constructor({device:e,attribute:t,timeline:n}){super({device:e,attribute:t,timeline:n}),this.type="spring",this.texture=function(e){return e.createTexture({data:/* @__PURE__ */new Uint8Array(4),format:"rgba8unorm",width:1,height:1})}(e),this.framebuffer=function(e,t){return e.createFramebuffer({id:"spring-transition-is-transitioning-framebuffer",width:1,height:1,colorAttachments:[t]})}(e,this.texture),this.transform=function(e,t){const n=li(t.size),i=ci(t.size);return new Ct(e,{vs:xi,fs:yi,bufferLayout:[{name:"aPrev",format:i},{name:"aCur",format:i},{name:"aTo",format:t.getBufferLayout().attributes[0].format}],varyings:["vNext"],modules:[_i],defines:{ATTRIBUTE_TYPE:n},parameters:{depthCompare:"always",blendColorOperation:"max",blendColorSrcFactor:"one",blendColorDstFactor:"one",blendAlphaOperation:"max",blendAlphaSrcFactor:"one",blendAlphaDstFactor:"one"}})}(e,t)}start(e,t){const n=this.currentLength,i=this.currentStartIndices;super.start(e,t);const{buffers:o,attribute:s}=this;for(let a=0;a<2;a++)o[a]=di({device:this.device,buffer:o[a],attribute:s,fromLength:n,toLength:this.currentLength,fromStartIndices:i,getData:e.enter});o[2]=fi({device:this.device,source:o[0],target:o[2]}),this.setBuffer(o[1]);const{model:r}=this.transform;r.setVertexCount(Math.floor(this.currentLength/s.size)),s.isConstant?r.setConstantAttributes({aTo:s.value}):r.setAttributes({aTo:s.getBuffer()})}onUpdate(){const{buffers:e,transform:t,framebuffer:n,transition:i}=this,o=this.settings;t.model.setAttributes({aPrev:e[0],aCur:e[1]}),t.transformFeedback.setBuffers({vNext:e[2]});const s={stiffness:o.stiffness,damping:o.damping};t.model.shaderInputs.setProps({spring:s}),t.run({framebuffer:n,discard:!1,parameters:{viewport:[0,0,1,1]},clearColor:[0,0,0,0]}),ui(e),this.setBuffer(e[1]),this.device.readPixelsToArrayWebGL(n)[0]>0||i.end()}delete(){super.delete(),this.transform.destroy(),this.texture.destroy(),this.framebuffer.destroy()}}},Pi=class{constructor(e,{id:t,timeline:n}){if(!e)throw new Error("AttributeTransitionManager is constructed without device");this.id=t,this.device=e,this.timeline=n,this.transitions={},this.needsRedraw=!1,this.numInstances=1}finalize(){for(const e in this.transitions)this._removeTransition(e)}update({attributes:e,transitions:t,numInstances:n}){this.numInstances=n||1;for(const i in e){const n=e[i],o=n.getTransitionSetting(t);o&&this._updateAttribute(i,n,o)}for(const i in this.transitions){const n=e[i];n&&n.getTransitionSetting(t)||this._removeTransition(i)}}hasAttribute(e){const t=this.transitions[e];return t&&t.inProgress}getAttributes(){const e={};for(const t in this.transitions){const n=this.transitions[t];n.inProgress&&(e[t]=n.attributeInTransition)}return e}run(){if(0===this.numInstances)return!1;for(const t in this.transitions)this.transitions[t].update()&&(this.needsRedraw=!0);const e=this.needsRedraw;return this.needsRedraw=!1,e}_removeTransition(e){this.transitions[e].delete(),delete this.transitions[e]}_updateAttribute(e,t,n){const i=this.transitions[e];let o=!i||i.type!==n.type;if(o){i&&this._removeTransition(e);const s=bi[n.type];s?this.transitions[e]=new s({attribute:t,timeline:this.timeline,device:this.device}):(I.error(`unsupported transition type '${n.type}'`)(),o=!1)}(o||t.needsRedraw())&&(this.needsRedraw=!0,this.transitions[e].start(n,this.numInstances))}},Ci="attributeManager.invalidate",wi=class{constructor(e,{id:t="attribute-manager",stats:n,timeline:i}={}){this.mergeBoundsMemoized=r(R),this.id=t,this.device=e,this.attributes={},this.updateTriggers={},this.needsRedraw=!0,this.userData={},this.stats=n,this.attributeTransitionManager=new Pi(e,{id:`${t}-transitions`,timeline:i}),this.attributeBufferGroups="webgpu"===e.type?new oi(e,{id:t,isTransitionAttribute:e=>this.attributeTransitionManager.hasAttribute(e)}):null,Object.seal(this)}finalize(){this.attributeBufferGroups?.finalize();for(const e in this.attributes)this.attributes[e].delete();this.attributeTransitionManager.finalize()}getNeedsRedraw(e={clearRedrawFlags:!1}){const t=this.needsRedraw;return this.needsRedraw=this.needsRedraw&&!e.clearRedrawFlags,t&&this.id}setNeedsRedraw(){this.needsRedraw=!0}add(e){this._add(e)}addInstanced(e){this._add(e,{stepMode:"instance"})}remove(e){for(const t of e)void 0!==this.attributes[t]&&(this.attributes[t].delete(),delete this.attributes[t])}invalidate(e,t){const n=this._invalidateTrigger(e,t);T(Ci,this,e,n)}invalidateAll(e){for(const t in this.attributes)this.attributes[t].setNeedsUpdate(t,e);T(Ci,this,"all")}update({data:e,numInstances:t,startIndices:n=null,transitions:i,props:o={},buffers:s={},context:r={}}){let a=!1;T("attributeManager.updateStart",this),this.stats&&this.stats.get("Update Attributes").timeStart();for(const l in this.attributes){const i=this.attributes[l],c=i.settings.accessor;i.startIndices=n,i.numInstances=t,o[l]&&I.removed(`props.${l}`,`data.attributes.${l}`)(),i.setExternalBuffer(s[l])||i.setBinaryValue("string"==typeof c?s[c]:void 0,e.startIndices)||"string"==typeof c&&!s[c]&&i.setConstantValue(r,o[c])||i.needsUpdate()&&(a=!0,this._updateAttribute({attribute:i,numInstances:t,data:e,props:o,context:r})),this.needsRedraw=this.needsRedraw||i.needsRedraw()}a&&T("attributeManager.updateEnd",this,t),this.stats&&(this.stats.get("Update Attributes").timeEnd(),a&&this.stats.get("Attributes updated").incrementCount()),this.attributeTransitionManager.update({attributes:this.attributes,numInstances:t,transitions:i})}updateTransition(){const{attributeTransitionManager:e}=this,t=e.run();return this.needsRedraw=this.needsRedraw||t,t}getAttributes(){return{...this.attributes,...this.attributeTransitionManager.getAttributes()}}getBounds(e){const t=e.map(e=>this.attributes[e]?.getBounds());return this.mergeBoundsMemoized(t)}getChangedAttributes(e={clearChangedFlags:!1}){const{attributes:t,attributeTransitionManager:n}=this,i={...n.getAttributes()};for(const o in t){const s=t[o];s.needsRedraw(e)&&!n.hasAttribute(o)&&(i[o]=s)}return i}getBufferLayouts(e){return this.hasBufferGroups()?this.attributeBufferGroups.getBufferLayouts(this.getAttributes(),e):Object.values(this.getAttributes()).map(t=>t.getBufferLayout(e))}hasBufferGroups(){return Boolean(this.attributeBufferGroups?.hasGroups(this.attributes))}getBufferGroupBindings(e,t,n={}){return this.attributeBufferGroups?this.attributeBufferGroups.getBindings(this.getAttributes(),e,t,n):{bufferLayouts:this.getBufferLayouts(t),buffers:{},groupedAttributeIds:/* @__PURE__ */new Set}}_add(e,t){for(const n in e){const i=e[n],o={...i,id:n,size:(i.isIndexed?1:i.size)||1,...t};this.attributes[n]=new Xt(this.device,o)}this._mapUpdateTriggersToAttributes()}_mapUpdateTriggersToAttributes(){const e={};for(const t in this.attributes)this.attributes[t].getUpdateTriggers().forEach(n=>{e[n]||(e[n]=[]),e[n].push(t)});this.updateTriggers=e}_invalidateTrigger(e,t){const{attributes:n,updateTriggers:i}=this,o=i[e];return o&&o.forEach(e=>{const i=n[e];i&&i.setNeedsUpdate(i.id,t)}),o}_updateAttribute(e){const{attribute:t,numInstances:n}=e;T("attribute.updateStart",t),t.constant?t.setConstantValue(e.context,t.value):(t.allocate(n)&&T("attribute.allocate",t,n),t.updateBuffer(e)&&(this.needsRedraw=!0,T("attribute.updateEnd",t,n)))}},Si=1e-5;function Li(e,t,n,i,o){const s=t-e;return(n-t)*o+-s*i+s+t}function Ai(e,t){if(Array.isArray(e)){let n=0;for(let i=0;i<e.length;i++){const o=e[i]-t[i];n+=o*o}return Math.sqrt(n)}return Math.abs(e-t)}var Ii={interpolation:class extends L{get value(){return this._value}_onUpdate(){const{time:e,settings:{fromValue:t,toValue:n,duration:i,easing:o}}=this,s=o(e/i);this._value=a(t,n,s)}},spring:class extends L{get value(){return this._currValue}_onUpdate(){const{fromValue:e,toValue:t,damping:n,stiffness:i}=this.settings,{_prevValue:o=e,_currValue:s=e}=this;let r=function(e,t,n,i,o){if(Array.isArray(n)){const s=[];for(let r=0;r<n.length;r++)s[r]=Li(e[r],t[r],n[r],i,o);return s}return Li(e,t,n,i,o)}(o,s,t,n,i);const a=Ai(r,t),l=Ai(r,s);a<Si&&l<Si&&(r=t,this.end()),this._prevValue=s,this._currValue=r}}},Ei=class{constructor(e){this.transitions=/* @__PURE__ */new Map,this.timeline=e}get active(){return this.transitions.size>0}add(e,t,n,i){const{transitions:o}=this;if(o.has(e)){const n=o.get(e),{value:i=n.settings.fromValue}=n;t=i,this.remove(e)}if(!(i=Kt(i)))return;const s=Ii[i.type];if(!s)return void I.error(`unsupported transition type '${i.type}'`)();const r=new s(this.timeline);r.start({...i,fromValue:t,toValue:n}),o.set(e,r)}remove(e){const{transitions:t}=this;t.has(e)&&(t.get(e).cancel(),t.delete(e))}update(){const e={};for(const[t,n]of this.transitions)n.update(),e[t]=n.value,n.inProgress||this.remove(t);return e}clear(){for(const e of this.transitions.keys())this.remove(e)}};function Ti(e,t){const n=zi({newProps:e,oldProps:t,propTypes:e[y],ignoreProps:{data:null,updateTriggers:null,extensions:null,transitions:null}}),i=function(e,t){if(null===t)return"oldProps is null, initial diff";let n=!1;const{dataComparator:i,_dataDiff:o}=e;i?i(e.data,t.data)||(n="Data comparator detected a change"):e.data!==t.data&&(n="A new data container was supplied");n&&o&&(n=o(e.data,t.data)||n);return n}(e,t);let o=!1;return i||(o=function(e,t){if(null===t)return{all:!0};if("all"in e.updateTriggers&&Bi(e,t,"all"))return{all:!0};const n={};let i=!1;for(const o in e.updateTriggers)"all"!==o&&Bi(e,t,o)&&(n[o]=!0,i=!0);return!!i&&n}(e,t)),{dataChanged:i,propsChanged:n,updateTriggersChanged:o,extensionsChanged:Ri(e,t),transitionsChanged:Oi(e,t)}}function Oi(e,t){if(!e.transitions)return!1;const n={},i=e[y];let o=!1;for(const s in e.transitions){const r=i[s],a=r&&r.type;"number"!==a&&"color"!==a&&"array"!==a||!Mi(e[s],t[s],r)||(n[s]=!0,o=!0)}return!!o&&n}function zi({newProps:e,oldProps:t,ignoreProps:n={},propTypes:i={},triggerName:o="props"}){if(t===e)return!1;if("object"!=typeof e||null===e)return`${o} changed shallowly`;if("object"!=typeof t||null===t)return`${o} changed shallowly`;for(const s of Object.keys(e))if(!(s in n)){if(!(s in t))return`${o}.${s} added`;const n=Mi(e[s],t[s],i[s]);if(n)return`${o}.${s} ${n}`}for(const s of Object.keys(t))if(!(s in n)){if(!(s in e))return`${o}.${s} dropped`;if(!Object.hasOwnProperty.call(e,s)){const n=Mi(e[s],t[s],i[s]);if(n)return`${o}.${s} ${n}`}}return!1}function Mi(e,t,n){let i=n&&n.equal;return i&&!i(e,t,n)?"changed deeply":i||(i=e&&t&&e.equals,!i||i.call(e,t))?i||t===e?null:"changed shallowly":"changed deeply"}function Ri(e,t){if(null===t)return!0;const n=t.extensions,{extensions:i}=e;if(i===n)return!1;if(!n||!i)return!0;if(i.length!==n.length)return!0;for(let o=0;o<i.length;o++)if(!i[o].equals(n[o]))return!0;return!1}function Bi(e,t,n){let i=e.updateTriggers[n];i=null==i?{}:i;let o=t.updateTriggers[n];return o=null==o?{}:o,zi({oldProps:o,newProps:i,triggerName:n})}function ki(e){if(null===(t=e)||"object"!=typeof t)throw new Error("count(): argument not an object");var t;if("function"==typeof e.count)return e.count();if(Number.isFinite(e.size))return e.size;if(Number.isFinite(e.length))return e.length;if(function(e){return null!==e&&"object"==typeof e&&e.constructor===Object}(e))return Object.keys(e).length;throw new Error("count(): argument not a container")}function Fi(e,t){if(!t)return e;const n={...e,...t};if("defines"in t&&(n.defines={...e.defines,...t.defines}),"modules"in t&&(n.modules=(e.modules||[]).concat(t.modules),t.modules.some(e=>"project64"===e.name))){const e=n.modules.findIndex(e=>"project32"===e.name);e>=0&&n.modules.splice(e,1)}if("inject"in t)if(e.inject){const i={...e.inject};for(const e in t.inject)i[e]=(i[e]||"")+t.inject[e];n.inject=i}else n.inject=t.inject;return n}var Ni={minFilter:"linear",mipmapFilter:"linear",magFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"},Di={};var ji={boolean:{validate:(e,t)=>!0,equal:(e,t,n)=>Boolean(e)===Boolean(t)},number:{validate:(e,t)=>Number.isFinite(e)&&(!("max"in t)||e<=t.max)&&(!("min"in t)||e>=t.min)},color:{validate:(e,t)=>t.optional&&!e||Vi(e)&&(3===e.length||4===e.length),equal:(e,t,n)=>E(e,t,1)},accessor:{validate(e,t){const n=$i(e);return"function"===n||n===$i(t.value)},equal:(e,t,n)=>"function"==typeof t||E(e,t,1)},array:{validate:(e,t)=>t.optional&&!e||Vi(e),equal(e,t,n){const{compare:i}=n;return i?E(e,t,Number.isInteger(i)?i:i?1:0):e===t}},object:{equal(e,t,n){if(n.ignore)return!0;const{compare:i}=n;return i?E(e,t,Number.isInteger(i)?i:i?1:0):e===t}},function:{validate:(e,t)=>t.optional&&!e||"function"==typeof e,equal:(e,t,n)=>!n.compare&&!1!==n.ignore||e===t},data:{transform:(e,t,n)=>{if(!e)return e;const{dataTransform:i}=n.props;return i?i(e):"string"==typeof e.shape&&e.shape.endsWith("-table")&&Array.isArray(e.data)?e.data:e}},image:{transform:(e,t,n)=>{const i=n.context;return i&&i.device?function(e,t,n,i){if(n instanceof p)return n;n.constructor&&"Object"!==n.constructor.name&&(n={data:n});let o=null;n.compressed&&(o={minFilter:"linear",mipmapFilter:n.data.length>1?"nearest":"linear"});const{width:s,height:r}=n.data,a=t.createTexture({...n,sampler:{...Ni,...o,...i},mipLevels:t.getMipLevelCount(s,r)});return"webgl"===t.type?a.generateMipmapsWebGL():"webgpu"===t.type&&t.generateMipmapsWebGPU(a),Di[a.id]=e,a}(n.id,i.device,e,{...t.parameters,...n.props.textureParameters}):null},release:(e,t,n)=>{var i,o;i=n.id,(o=e)&&o instanceof p&&Di[o.id]===i&&(o.delete(),delete Di[o.id])}}};function Ui(e,t){switch($i(t)){case"object":return Gi(e,t);case"array":return Gi(e,{type:"array",value:t,compare:!1});case"boolean":return Gi(e,{type:"boolean",value:t});case"number":return Gi(e,{type:"number",value:t});case"function":return Gi(e,{type:"function",value:t,compare:!0});default:return{name:e,type:"unknown",value:t}}}function Gi(e,t){return"type"in t?{name:e,...ji[t.type],...t}:"value"in t?{name:e,type:$i(t.value),...t}:{name:e,type:"object",value:t}}function Vi(e){return Array.isArray(e)||ArrayBuffer.isView(e)}function $i(e){return Vi(e)?"array":null===e?"null":typeof e}var Wi="_mergedDefaultProps";function Hi(e,t){if(!(e instanceof Xi.constructor))return{};let n=Wi;if(t)for(const o of t){const e=o.constructor;e&&(n+=`:${e.extensionName||e.name}`)}const i=qi(e,n);return i||(e[n]=function(e,t){if(!e.prototype)return null;const n=Hi(Object.getPrototypeOf(e)),i=qi(e,"defaultProps")||{},o=function(e){const t={},n={},i={};for(const[o,s]of Object.entries(e)){const e=s?.deprecatedFor;if(e)i[o]=Array.isArray(e)?e:[e];else{const e=Ui(o,s);t[o]=e,n[o]=e.value}}return{propTypes:t,defaultProps:n,deprecatedProps:i}}(i),s=Object.assign(Object.create(null),n,o.defaultProps),r=Object.assign(Object.create(null),n?.[y],o.propTypes),a=Object.assign(Object.create(null),n?.[S],o.deprecatedProps);for(const l of t){const e=Hi(l.constructor);e&&(Object.assign(s,e),Object.assign(r,e[y]),Object.assign(a,e[S]))}(function(e,t){const n=function(e){const t=e.componentName;t||I.warn(`${e.name}.componentName not specified`)();return t||e.name}(t);Object.defineProperties(e,{id:{writable:!0,value:n}})})(s,e),function(e,t){const n={},i={};for(const o in t){const e=t[o],{name:s,value:r}=e;e.async&&(n[s]=r,i[s]=Zi(s))}e[O]=n,e[m]={},Object.defineProperties(e,i)}(s,r),function(e,t){for(const n in t)Object.defineProperty(e,n,{enumerable:!1,set(e){const i=`${this.id}: ${n}`;for(const o of t[n])Yi(this,o)||(this[o]=e);I.deprecated(i,t[n].join("/"))()}})}(s,a),s[y]=r,s[S]=a,0!==t.length||Yi(e,"_propTypes")||(e._propTypes=r);return s}(e,t||[]))}function Zi(e){return{enumerable:!0,set(t){"string"==typeof t||t instanceof Promise||Wt(t)?this[m][e]=t:this[_][e]=t},get(){if(this[_]){if(e in this[_])return this[_][e]||this[O][e];if(e in this[m]){const t=this[A]&&this[A].internalState;if(t&&t.hasAsyncProp(e))return t.getAsyncProp(e)||this[O][e]}}return this[O][e]}}}function Yi(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function qi(e,t){return Yi(e,t)&&e[t]}var Ki=0,Xi=class{constructor(...e){this.props=function(e,t){let n;for(let s=t.length-1;s>=0;s--){const e=t[s];"extensions"in e&&(n=e.extensions)}const i=Hi(e.constructor,n),o=Object.create(i);o[A]=e,o[m]={},o[_]={};for(let s=0;s<t.length;++s){const e=t[s];for(const t in e)o[t]=e[t]}return Object.freeze(o),o}(this,e),this.id=this.props.id,this.count=Ki++}clone(e){const{props:t}=this,n={};for(const i in t[O])i in t[_]?n[i]=t[_][i]:i in t[m]&&(n[i]=t[m][i]);return new this.constructor({...t,...n,...e})}};Xi.componentName="Component",Xi.defaultProps={};var Ji=Object.freeze({}),Qi=class{constructor(e){this.component=e,this.asyncProps={},this.onAsyncPropUpdated=()=>{},this.oldProps=null,this.oldAsyncProps=null}finalize(){for(const e in this.asyncProps){const t=this.asyncProps[e];t&&t.type&&t.type.release&&t.type.release(t.resolvedValue,t.type,this.component)}this.asyncProps={},this.component=null,this.resetOldProps()}getOldProps(){return this.oldAsyncProps||this.oldProps||Ji}resetOldProps(){this.oldAsyncProps=null,this.oldProps=this.component?this.component.props:null}hasAsyncProp(e){return e in this.asyncProps}getAsyncProp(e){const t=this.asyncProps[e];return t&&t.resolvedValue}isAsyncPropLoading(e){if(e){const t=this.asyncProps[e];return Boolean(t&&t.pendingLoadCount>0&&t.pendingLoadCount!==t.resolvedLoadCount)}for(const t in this.asyncProps)if(this.isAsyncPropLoading(t))return!0;return!1}reloadAsyncProp(e,t){this._watchPromise(e,Promise.resolve(t))}setAsyncProps(e){this.component=e[A]||this.component;const t=e[_]||{},n=e[m]||e,i=e[O]||{};for(const o in t){const e=t[o];this._createAsyncPropData(o,i[o]),this._updateAsyncProp(o,e),t[o]=this.getAsyncProp(o)}for(const o in n){const e=n[o];this._createAsyncPropData(o,i[o]),this._updateAsyncProp(o,e)}}_fetch(e,t){return null}_onResolve(e,t){}_onError(e,t){}_updateAsyncProp(e,t){this._didAsyncInputValueChange(e,t)&&("string"==typeof t&&(t=this._fetch(e,t)),t instanceof Promise?this._watchPromise(e,t):Wt(t)?this._resolveAsyncIterable(e,t):this._setPropValue(e,t))}_freezeAsyncOldProps(){if(!this.oldAsyncProps&&this.oldProps){this.oldAsyncProps=Object.create(this.oldProps);for(const e in this.asyncProps)Object.defineProperty(this.oldAsyncProps,e,{enumerable:!0,value:this.oldProps[e]})}}_didAsyncInputValueChange(e,t){const n=this.asyncProps[e];return t!==n.resolvedValue&&t!==n.lastValue&&(n.lastValue=t,!0)}_setPropValue(e,t){this._freezeAsyncOldProps();const n=this.asyncProps[e];n&&(t=this._postProcessValue(n,t),n.resolvedValue=t,n.pendingLoadCount++,n.resolvedLoadCount=n.pendingLoadCount)}_setAsyncPropValue(e,t,n){const i=this.asyncProps[e];i&&n>=i.resolvedLoadCount&&void 0!==t&&(this._freezeAsyncOldProps(),i.resolvedValue=t,i.resolvedLoadCount=n,this.onAsyncPropUpdated(e,t))}_watchPromise(e,t){const n=this.asyncProps[e];if(n){n.pendingLoadCount++;const i=n.pendingLoadCount;t.then(t=>{this.component&&(t=this._postProcessValue(n,t),this._setAsyncPropValue(e,t,i),this._onResolve(e,t))}).catch(t=>{this._onError(e,t)})}}async _resolveAsyncIterable(e,t){if("data"!==e)return void this._setPropValue(e,t);const n=this.asyncProps[e];if(!n)return;n.pendingLoadCount++;const i=n.pendingLoadCount;let o=[],s=0;for await(const r of t){if(!this.component)return;const{dataTransform:t}=this.component.props;o=t?t(r,o):o.concat(r),Object.defineProperty(o,"__diff",{enumerable:!1,value:[{startRow:s,endRow:o.length}]}),s=o.length,this._setAsyncPropValue(e,o,i)}this._onResolve(e,o)}_postProcessValue(e,t){const n=e.type;return n&&this.component&&(n.release&&n.release(e.resolvedValue,n,this.component),n.transform)?n.transform(t,n,this.component):t}_createAsyncPropData(e,t){if(!this.asyncProps[e]){const n=this.component&&this.component.props[y];this.asyncProps[e]={type:n&&n[e],lastValue:null,resolvedValue:t,pendingLoadCount:0,resolvedLoadCount:0}}}},eo=class extends Qi{constructor({attributeManager:e,layer:t}){super(t),this.attributeManager=e,this.needsRedraw=!0,this.needsUpdate=!0,this.subLayers=null,this.usesPickingColorCache=!1,this.disabledPickingIndices=[]}get layer(){return this.component}_fetch(e,t){const n=this.layer,i=n?.props.fetch;return i?i(t,{propName:e,layer:n}):super._fetch(e,t)}_onResolve(e,t){const n=this.layer;if(n){const i=n.props.onDataLoad;"data"===e&&i&&i(t,{propName:e,layer:n})}}_onError(e,t){const n=this.layer;n&&n.raiseError(t,`loading ${e} of ${this.layer}`)}},to=2**24-1,no=Object.freeze([]),io=r(({oldViewport:e,viewport:t})=>e.equals(t)),oo=/* @__PURE__ */new Uint8ClampedArray(0);function so(e){return e.rowIndexes||e.pickingColors||e.instancePickingColors}function ro(e){return e.rowIndexes}function ao(e){return e.pickingColors||e.instancePickingColors}var lo={data:{type:"data",value:no,async:!0},dataComparator:{type:"function",value:null,optional:!0},_dataDiff:{type:"function",value:e=>e&&e.__diff,optional:!0},dataTransform:{type:"function",value:null,optional:!0},onDataLoad:{type:"function",value:null,optional:!0},onError:{type:"function",value:null,optional:!0},fetch:{type:"function",value:(e,{propName:t,layer:n,loaders:i,loadOptions:o,signal:s})=>{const{resourceManager:r}=n.context;o=o||n.getLoadOptions(),i=i||n.props.loaders,s&&(o={...o,core:{...o?.core,fetch:{...o?.core?.fetch,signal:s}}});let a=r.contains(e);return a||o||(r.add({resourceId:e,data:P(e,i),persistent:!1}),a=!0),a?r.subscribe({resourceId:e,onChange:e=>n.internalState?.reloadAsyncProp(t,e),consumerId:n.id,requestId:t}):P(e,i,o)}},updateTriggers:{},visible:!0,pickable:!1,opacity:{type:"number",min:0,max:1,value:1},operation:"draw",onHover:{type:"function",value:null,optional:!0},onClick:{type:"function",value:null,optional:!0},onDragStart:{type:"function",value:null,optional:!0},onDrag:{type:"function",value:null,optional:!0},onDragEnd:{type:"function",value:null,optional:!0},coordinateSystem:"default",coordinateOrigin:{type:"array",value:[0,0,0],compare:!0},modelMatrix:{type:"array",value:null,compare:!0,optional:!0},wrapLongitude:!1,positionFormat:"XYZ",colorFormat:"RGBA",parameters:{type:"object",value:{},optional:!0,compare:2},loadOptions:{type:"object",value:null,optional:!0,ignore:!0},transitions:null,extensions:[],loaders:{type:"array",value:[],optional:!0,ignore:!0},getPolygonOffset:{type:"function",value:({layerIndex:e})=>[0,100*-e]},highlightedObjectIndex:null,autoHighlight:!1,highlightColor:{type:"accessor",value:[0,0,128,128]}},co=class extends Xi{constructor(){super(...arguments),this.internalState=null,this.lifecycle=b.NO_STATE,this.parent=null}static get componentName(){return Object.prototype.hasOwnProperty.call(this,"layerName")?this.layerName:""}get root(){let e=this;for(;e.parent;)e=e.parent;return e}toString(){return`${this.constructor.layerName||this.constructor.name}({id: '${this.props.id}'})`}project(e){h(this.internalState);const t=this.internalState.viewport||this.context.viewport,n=tt(e,{viewport:t,modelMatrix:this.props.modelMatrix,coordinateOrigin:this.props.coordinateOrigin,coordinateSystem:this.props.coordinateSystem}),[i,o,s]=C(n,t.pixelProjectionMatrix);return 2===e.length?[i,o]:[i,o,s]}unproject(e){return h(this.internalState),(this.internalState.viewport||this.context.viewport).unproject(e)}projectPosition(e,t){h(this.internalState);return function(e,t){const{viewport:n,coordinateSystem:i,coordinateOrigin:o,modelMatrix:s,fromCoordinateSystem:r,fromCoordinateOrigin:a}=function(e){const{viewport:t,modelMatrix:n,coordinateOrigin:i}=e;let{coordinateSystem:o,fromCoordinateSystem:s,fromCoordinateOrigin:r}=e;return"default"===o&&(o=t.isGeospatial?"lnglat":"cartesian"),void 0===s?s=o:"default"===s&&(s=t.isGeospatial?"lnglat":"cartesian"),void 0===r&&(r=i),{viewport:t,coordinateSystem:o,coordinateOrigin:i,modelMatrix:n,fromCoordinateSystem:s,fromCoordinateOrigin:r}}(t),{autoOffset:l=!0}=t,{geospatialOrigin:u=Qe,shaderCoordinateOrigin:f=Qe,offsetMode:d=!1}=l?c(n,i,o):{},p=tt(e,{viewport:n,modelMatrix:s,coordinateSystem:r,coordinateOrigin:a,offsetMode:d});if(d){const e=n.projectPosition(u||f);x(p,p,e)}return p}(e,{viewport:this.internalState.viewport||this.context.viewport,modelMatrix:this.props.modelMatrix,coordinateOrigin:this.props.coordinateOrigin,coordinateSystem:this.props.coordinateSystem,...t})}get isComposite(){return!1}get isDrawable(){return!0}setState(e){this.setChangeFlags({stateChanged:!0}),Object.assign(this.state,e),this.setNeedsRedraw()}setNeedsRedraw(){this.internalState&&(this.internalState.needsRedraw=!0)}setNeedsUpdate(){this.internalState&&(this.context.layerManager.setNeedsUpdate(String(this)),this.internalState.needsUpdate=!0)}get isLoaded(){return!!this.internalState&&!this.internalState.isAsyncPropLoading()}get wrapLongitude(){return this.props.wrapLongitude}isPickable(){return this.props.pickable&&this.props.visible}getModels(){const e=this.state;return e&&(e.models||e.model&&[e.model])||[]}setShaderModuleProps(...e){for(const t of this.getModels())t.shaderInputs.setProps(...e)}getAttributeManager(){return this.internalState&&this.internalState.attributeManager}getCurrentLayer(){return this.internalState&&this.internalState.layer}getLoadOptions(){return this.props.loadOptions}use64bitPositions(){const{coordinateSystem:e}=this.props;return"default"===e||"lnglat"===e||"cartesian"===e}onHover(e,t){return this.props.onHover&&this.props.onHover(e,t)||!1}onClick(e,t){return this.props.onClick&&this.props.onClick(e,t)||!1}nullPickingColor(){return[0,0,0]}encodePickingColor(e,t=[]){return t[0]=e+1&255,t[1]=e+1>>8&255,t[2]=e+1>>8>>8&255,t}decodePickingColor(e){h(e instanceof Uint8Array);const[t,n,i]=e;return t+256*n+65536*i-1}getNumInstances(){return Number.isFinite(this.props.numInstances)?this.props.numInstances:this.state&&void 0!==this.state.numInstances?this.state.numInstances:ki(this.props.data)}getStartIndices(){return this.props.startIndices?this.props.startIndices:this.state&&this.state.startIndices?this.state.startIndices:null}getBounds(){return this.getAttributeManager()?.getBounds(["positions","instancePositions"])}getShaders(e){e=Fi(e,{disableWarnings:!0,modules:this.context.defaultShaderModules});for(const t of this.props.extensions)e=Fi(e,t.getShaders.call(this,t));return e}shouldUpdateState(e){return e.changeFlags.propsOrDataChanged}updateState(e){const t=this.getAttributeManager(),{dataChanged:n}=e.changeFlags;if(n&&t)if(Array.isArray(n))for(const i of n)t.invalidateAll(i);else t.invalidateAll();if(t){const{props:n}=e,i=this.internalState.hasPickingBuffer,o=Number.isInteger(n.highlightedObjectIndex)||Boolean(n.pickable)||n.extensions.some(e=>e.getNeedsPickingBuffer.call(this,e));if(i!==o){this.internalState.hasPickingBuffer=o;const e=so(t.attributes);e&&(o&&e.constant&&(e.constant=!1,t.invalidate(e.id)),e.value||o||(e.constant=!0,e.value=ro(t.attributes)?[qe]:[0,0,0]))}}}finalizeState(e){for(const n of this.getModels())n.destroy();const t=this.getAttributeManager();t&&t.finalize(),this.context&&this.context.resourceManager.unsubscribe({consumerId:this.id}),this.internalState&&(this.internalState.uniformTransitions.clear(),this.internalState.finalize())}draw(e){for(const t of this.getModels())t.draw(e.renderPass)}getPickingInfo({info:e,mode:t,sourceLayer:n}){const{index:i}=e;return i>=0&&Array.isArray(this.props.data)&&(e.object=this.props.data[i]),e}raiseError(e,t){t&&(e=new Error(`${t}: ${e.message}`,{cause:e})),this.props.onError?.(e)||this.context?.onError?.(e,this)}getNeedsRedraw(e={clearRedrawFlags:!1}){return this._getNeedsRedraw(e)}needsUpdate(){return!!this.internalState&&(this.internalState.needsUpdate||this.hasUniformTransition()||this.shouldUpdateState(this._getUpdateParams()))}hasUniformTransition(){return this.internalState?.uniformTransitions.active||!1}activateViewport(e){if(!this.internalState)return;const t=this.internalState.viewport;this.internalState.viewport=e,t&&io({oldViewport:t,viewport:e})||(this.setChangeFlags({viewportChanged:!0}),this.isComposite?this.needsUpdate()&&this.setNeedsUpdate():this._update())}invalidateAttribute(e="all"){const t=this.getAttributeManager();t&&("all"===e?t.invalidateAll():t.invalidate(e))}updateAttributes(e){let t=!1;for(const n in e)e[n].layoutChanged()&&(t=!0);for(const n of this.getModels())this._setModelAttributes(n,e,t)}_updateAttributes(){const e=this.getAttributeManager();if(!e)return;const t=this.props,n=this.getNumInstances(),i=this.getStartIndices();e.update({data:t.data,numInstances:n,startIndices:i,props:t,transitions:t.transitions,buffers:t.data.attributes,context:this});const o=e.getChangedAttributes({clearChangedFlags:!0});this.updateAttributes(o)}_updateAttributeTransition(){const e=this.getAttributeManager();e&&e.updateTransition()}_updateUniformTransition(){const{uniformTransitions:e}=this.internalState;if(e.active){const t=e.update(),n=Object.create(this.props);for(const e in t)Object.defineProperty(n,e,{value:t[e]});return n}return this.props}calculateInstancePickingColors(e,{numInstances:t}){if(e.constant)return;const n=Math.floor(oo.length/4);this.internalState.usesPickingColorCache=!0;const i=t>0&&0===oo[0];if(n<t||i){t>to&&I.warn("Layer has too many data objects. Picking might not be able to distinguish all objects.")(),oo=f.allocate(oo,t,{size:4,copy:!0,maxCount:Math.max(t,to)});const e=Math.floor(oo.length/4),o=[0,0,0];for(let t=i?0:n;t<e;t++)this.encodePickingColor(t,o),oo[4*t+0]=o[0],oo[4*t+1]=o[1],oo[4*t+2]=o[2],oo[4*t+3]=0}e.value=oo.subarray(0,4*t)}_setModelAttributes(e,t,n=!1){if(!Object.keys(t).length)return;const i=this.getAttributeManager();if(i?.hasBufferGroups())return void this._setGroupedModelAttributes(e,i,t);if(n){const n=this.getAttributeManager();e.setBufferLayout(n.getBufferLayouts(e)),t=n.getAttributes()}const o=e.userData?.excludeAttributes||{},s={},r={};for(const a in t){if(o[a])continue;const n=t[a].getValue();for(const i in n){const o=n[i];o instanceof U?t[a].settings.isIndexed?e.setIndexBuffer(o):s[i]=o:o&&(r[i]=o)}}e.setAttributes(s),e.setConstantAttributes(r)}_setGroupedModelAttributes(e,t,n){const i=e.userData?.excludeAttributes||{},o=t.getBufferGroupBindings(n,e,i);e.setBufferLayout(o.bufferLayouts);const s={...o.buffers},r={},a=t.getAttributes();for(const l in a){if(i[l]||o.groupedAttributeIds.has(l))continue;const t=a[l],n=t.getValue();for(const i in n){const o=n[i];o instanceof U?t.settings.isIndexed?e.setIndexBuffer(o):s[i]=o:o&&(r[i]=o)}}e.setAttributes(s),e.setConstantAttributes(r)}disablePickingIndex(e){const t=this.props.data;if(!("attributes"in t))return void this._disablePickingIndex(e);const n=this.getAttributeManager().attributes,i=ro(n),o=ao(n),s=i&&t.attributes&&t.attributes[i.id];if(s&&s.value){const n=s.value;for(let o=0;o<t.length;o++)n[i.getVertexOffset(o)]===e&&this._disablePickingIndex(o);return}const r=o&&t.attributes&&t.attributes[o.id];if(r&&r.value){const n=r.value,i=this.encodePickingColor(e);for(let e=0;e<t.length;e++){const t=o.getVertexOffset(e);n[t]===i[0]&&n[t+1]===i[1]&&n[t+2]===i[2]&&this._disablePickingIndex(e)}}else this._disablePickingIndex(e)}_disablePickingIndex(e){const t=this.getAttributeManager().attributes,n=ro(t);if(n){const t=n.getVertexOffset(e),i=n.getVertexOffset(e+1),o=new Uint32Array(i-t);return o.fill(qe),void n.buffer.write(o,t*o.BYTES_PER_ELEMENT)}const i=ao(t);if(!i)return void(this.internalState&&function(e,t){10===e.length?I.warn("pickMultipleObjects can only exclude 10 previously picked objects for layers without picking buffers")():e.push(t)}(this.internalState.disabledPickingIndices,e));const o=i.getVertexOffset(e),s=i.getVertexOffset(e+1);i.buffer.write(new Uint8Array(s-o),o)}restorePickingColors(){const e=this.getAttributeManager().attributes,t=so(e);if(!t)return void(this.internalState&&(this.internalState.disabledPickingIndices.length=0));const n=ao(e);this.internalState.usesPickingColorCache&&n&&n.value.buffer!==oo.buffer&&(n.value=oo.subarray(0,n.value.length)),t.updateSubBuffer({startOffset:0})}_initialize(){h(!this.internalState),T("layer.initialize",this);const e=this._getAttributeManager();this.internalState=new eo({attributeManager:e,layer:this}),this._clearChangeFlags(),this.state={},Object.defineProperty(this.state,"attributeManager",{get:()=>(I.deprecated("layer.state.attributeManager","layer.getAttributeManager()")(),e)}),this.internalState.uniformTransitions=new Ei(this.context.timeline),this.internalState.onAsyncPropUpdated=this._onAsyncPropUpdated.bind(this),this.internalState.setAsyncProps(this.props),this.initializeState(this.context);for(const t of this.props.extensions)t.initializeState.call(this,this.context,t);this.setChangeFlags({dataChanged:"init",propsChanged:"init",viewportChanged:!0,extensionsChanged:!0}),this._update()}_transferState(e){T("layer.matched",this,this===e);const{state:t,internalState:n}=e;this!==e&&(this.internalState=n,this.state=t,this.internalState.setAsyncProps(this.props),this._diffProps(this.props,this.internalState.getOldProps()))}_update(){const e=this.needsUpdate();if(T("layer.update",this,e),!e)return;this.context.stats.get("Layer updates").incrementCount();const t=this.props,n=this.context,i=this.internalState,o=n.viewport,s=this._updateUniformTransition();i.propsInTransition=s,n.viewport=i.viewport||o,this.props=s;try{const e=this._getUpdateParams(),t=this.getModels();if(n.device)this.updateState(e);else try{this.updateState(e)}catch(r){}for(const n of this.props.extensions)n.updateState.call(this,e,n);this.setNeedsRedraw(),this._updateAttributes();const i=this.getModels()[0]!==t[0];this._postUpdate(e,i)}finally{n.viewport=o,this.props=t,this._clearChangeFlags(),i.needsUpdate=!1,i.resetOldProps()}}_finalize(){T("layer.finalize",this),this.finalizeState(this.context);for(const e of this.props.extensions)e.finalizeState.call(this,this.context,e)}_drawLayer({renderPass:e,shaderModuleProps:t=null,uniforms:n={},parameters:i={}}){this._updateAttributeTransition();const o=this.props,s=this.context;this.props=this.internalState.propsInTransition||o;try{t&&this.setShaderModuleProps(t);const{getPolygonOffset:o}=this.props,r=o&&o(n)||[0,0];s.device instanceof X&&s.device.setParametersWebGL({polygonOffset:r});const a=s.device instanceof X?null:function(e){const{blendConstant:t,...n}=e;return t?{pipelineParameters:n,renderPassParameters:{blendConstant:t}}:{pipelineParameters:n}}(i);if(function(e,t,n,i){for(const o of e)"webgpu"===o.device.type?(uo(o,t),o.setParameters({...o.parameters,...i?.pipelineParameters})):o.setParameters(n)}(this.getModels(),e,i,a),s.device instanceof X)s.device.withParametersWebGL(i,()=>{const o={renderPass:e,shaderModuleProps:t,uniforms:n,parameters:i,context:s};for(const e of this.props.extensions)e.draw.call(this,o,e);this.draw(o)});else{a?.renderPassParameters&&e.setParameters(a.renderPassParameters);const o={renderPass:e,shaderModuleProps:t,uniforms:n,parameters:i,context:s};for(const e of this.props.extensions)e.draw.call(this,o,e);this.draw(o)}}finally{this.props=o}}getChangeFlags(){return this.internalState?.changeFlags}setChangeFlags(e){if(!this.internalState)return;const{changeFlags:t}=this.internalState;for(const i in e)if(e[i]){let n=!1;if("dataChanged"===i){const o=e[i],s=t[i];o&&Array.isArray(s)&&(t.dataChanged=Array.isArray(o)?s.concat(o):o,n=!0)}t[i]||(t[i]=e[i],n=!0),n&&T("layer.changeFlag",this,i,e)}const n=Boolean(t.dataChanged||t.updateTriggersChanged||t.propsChanged||t.extensionsChanged);t.propsOrDataChanged=n,t.somethingChanged=n||t.viewportChanged||t.stateChanged}_clearChangeFlags(){this.internalState.changeFlags={dataChanged:!1,propsChanged:!1,updateTriggersChanged:!1,viewportChanged:!1,stateChanged:!1,extensionsChanged:!1,propsOrDataChanged:!1,somethingChanged:!1}}_diffProps(e,t){const n=Ti(e,t);if(n.updateTriggersChanged)for(const i in n.updateTriggersChanged)n.updateTriggersChanged[i]&&this.invalidateAttribute(i);if(n.transitionsChanged)for(const i in n.transitionsChanged)this.internalState.uniformTransitions.add(i,t[i],e[i],e.transitions?.[i]);return this.setChangeFlags(n)}validateProps(){!function(e){const t=e[y];for(const n in t){const i=t[n],{validate:o}=i;if(o&&!o(e[n],i))throw new Error(`Invalid prop ${n}: ${e[n]}`)}}(this.props)}updateAutoHighlight(e){this.props.autoHighlight&&!Number.isInteger(this.props.highlightedObjectIndex)&&this._updateAutoHighlight(e)}_updateAutoHighlight(e){const t={highlightedObjectColor:e.picked?e.color:null},{highlightColor:n}=this.props;e.picked&&"function"==typeof n&&(t.highlightColor=n(e)),this.setShaderModuleProps({picking:t}),this.setNeedsRedraw()}_getAttributeManager(){const e=this.context;return new wi(e.device,{id:this.props.id,stats:e.stats,timeline:e.timeline})}_postUpdate(e,t){const{props:n,oldProps:i}=e,o=this.state.model;o?.isInstanced&&o.setInstanceCount(this.getNumInstances());const{autoHighlight:s,highlightedObjectIndex:r,highlightColor:a}=n;if(t||i.autoHighlight!==s||i.highlightedObjectIndex!==r||i.highlightColor!==a){const e={};Array.isArray(a)&&(e.highlightColor=a),(t||i.autoHighlight!==s||r!==i.highlightedObjectIndex)&&(e.highlightedObjectColor=Number.isFinite(r)&&r>=0?this.encodePickingColor(r):null),this.setShaderModuleProps({picking:e})}}_getUpdateParams(){return{props:this.props,oldProps:this.internalState.getOldProps(),context:this.context,changeFlags:this.internalState.changeFlags}}_getNeedsRedraw(e){if(!this.internalState)return!1;let t=!1;t=t||this.internalState.needsRedraw&&this.id;const n=this.getAttributeManager(),i=!!n&&n.getNeedsRedraw(e);if(t=t||i,t)for(const o of this.props.extensions)o.onNeedsRedraw.call(this,o);return this.internalState.needsRedraw=this.internalState.needsRedraw&&!e.clearRedrawFlags,t}_onAsyncPropUpdated(){this._diffProps(this.props,this.internalState.getOldProps()),this.setNeedsUpdate()}};function uo(e,t){const n=t.props.framebuffer||(t.framebuffer??null);if(!n)return;const i=n.colorAttachments.map(e=>e?.texture?.format??null),o=n.depthStencilAttachment?.texture?.format,s=e;(function(e,t){if(e===t)return!0;if(!e||!t||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0})(s.props.colorAttachmentFormats,i)&&s.props.depthStencilAttachmentFormat===o||(s.props.colorAttachmentFormats=i,s.props.depthStencilAttachmentFormat=o,s._setPipelineNeedsUpdate("attachment formats"))}co.defaultProps=lo,co.layerName="Layer";var fo=class extends co{get isComposite(){return!0}get isDrawable(){return!1}get isLoaded(){return super.isLoaded&&this.getSubLayers().every(e=>e.isLoaded)}getSubLayers(){return this.internalState&&this.internalState.subLayers||[]}initializeState(e){}setState(e){super.setState(e),this.setNeedsUpdate()}getPickingInfo({info:e}){const{object:t}=e;return t&&t.__source&&t.__source.parent&&t.__source.parent.id===this.id?(e.object=t.__source.object,e.index=t.__source.index,e):e}filterSubLayer(e){return!0}shouldRenderSubLayer(e,t){return t&&t.length}getSubLayerClass(e,t){const{_subLayerProps:n}=this.props;return n&&n[e]&&n[e].type||t}getSubLayerRow(e,t,n){return e.__source={parent:this,object:t,index:n},e}getSubLayerAccessor(e){if("function"==typeof e){const t={index:-1,data:this.props.data,target:[]};return(n,i)=>n&&n.__source?(t.index=n.__source.index,e(n.__source.object,t)):e(n,i)}return e}getSubLayerProps(e={}){const{opacity:t,pickable:n,visible:i,parameters:o,getPolygonOffset:s,highlightedObjectIndex:r,autoHighlight:a,highlightColor:l,coordinateSystem:c,coordinateOrigin:u,wrapLongitude:f,positionFormat:d,modelMatrix:p,extensions:g,fetch:h,operation:v,_subLayerProps:m}=this.props,_={id:"",updateTriggers:{},opacity:t,pickable:n,visible:i,parameters:o,getPolygonOffset:s,highlightedObjectIndex:r,autoHighlight:a,highlightColor:l,coordinateSystem:c,coordinateOrigin:u,wrapLongitude:f,positionFormat:d,modelMatrix:p,extensions:g,fetch:h,operation:v},x=m&&e.id&&m[e.id],b=x&&x.updateTriggers,P=e.id||"sublayer";if(x){const t=this.props[y],n=e.type?e.type._propTypes:{};for(const e in x){const i=n[e]||t[e];i&&"accessor"===i.type&&(x[e]=this.getSubLayerAccessor(x[e]))}}Object.assign(_,e,x),_.id=`${this.props.id}-${P}`,_.updateTriggers={all:this.props.updateTriggers?.all,...e.updateTriggers,...b};for(const y of g){const e=y.getSubLayerProps.call(this,y);e&&Object.assign(_,e,{updateTriggers:Object.assign(_.updateTriggers,e.updateTriggers)})}return _}_updateAutoHighlight(e){for(const t of this.getSubLayers())t.updateAutoHighlight(e)}_getAttributeManager(){return null}_postUpdate(e,t){let n=this.internalState.subLayers;const i=!n||this.needsUpdate();if(i){const e=this.renderLayers();n=w(e,Boolean),this.internalState.subLayers=n}T("compositeLayer.renderLayers",this,i,n);for(const o of n)o.parent=this}};fo.layerName="CompositeLayer";var po=class{constructor(e){this.indexStarts=[0],this.vertexStarts=[0],this.vertexCount=0,this.instanceCount=0;const{attributes:t={}}=e;this.typedArrayManager=f,this.attributes={},this._attributeDefs=t,this.opts=e,this.updateGeometry(e)}updateGeometry(e){Object.assign(this.opts,e);const{data:t,buffers:n={},getGeometry:i,geometryBuffer:o,positionFormat:s,dataChanged:r,normalize:a=!0}=this.opts;if(this.data=t,this.getGeometry=i,this.positionSize=o&&o.size||("XY"===s?2:3),this.buffers=n,this.normalize=a,o&&(h(t.startIndices),this.getGeometry=this.getGeometryFromBuffer(o),a||(n.vertexPositions=o)),this.geometryBuffer=n.vertexPositions,Array.isArray(r))for(const l of r)this._rebuildGeometry(l);else this._rebuildGeometry()}updatePartialGeometry({startRow:e,endRow:t}){this._rebuildGeometry({startRow:e,endRow:t})}getGeometryFromBuffer(e){const t=e.value||e;return ArrayBuffer.isView(t)?Ht(t,{size:this.positionSize,offset:e.offset,stride:e.stride,startIndices:this.data.startIndices}):null}_allocate(e,t){const{attributes:n,buffers:i,_attributeDefs:o,typedArrayManager:s}=this;for(const r in o)if(r in i)s.release(n[r]),n[r]=null;else{const i=o[r];i.copy=t,n[r]=s.allocate(n[r],e,i)}}_forEachGeometry(e,t,n){const{data:i,getGeometry:o}=this,{iterable:s,objectInfo:r}=$t(i,t,n);for(const a of s)r.index++,e(o?o(a,r):null,r.index)}_rebuildGeometry(e){if(!this.data)return;let{indexStarts:t,vertexStarts:n,instanceCount:i}=this;const{data:o,geometryBuffer:s}=this,{startRow:r=0,endRow:a=1/0}=e||{},l={};if(e||(t=[0],n=[0]),this.normalize||!s)this._forEachGeometry((e,t)=>{const i=e&&this.normalizeGeometry(e);l[t]=i,n[t+1]=n[t]+(i?this.getGeometrySize(i):0)},r,a),i=n[n.length-1];else if(n=o.startIndices,i=n[o.length]||0,ArrayBuffer.isView(s))i=i||s.length/this.positionSize;else if(s instanceof U){const e=4*this.positionSize;i=i||s.byteLength/e}else if(s.buffer){const e=s.stride||4*this.positionSize;i=i||s.buffer.byteLength/e}else if(s.value){const e=s.value,t=s.stride/e.BYTES_PER_ELEMENT||this.positionSize;i=i||e.length/t}this._allocate(i,Boolean(e)),this.indexStarts=t,this.vertexStarts=n,this.instanceCount=i;const c={};this._forEachGeometry((e,o)=>{const s=l[o]||e;c.vertexStart=n[o],c.indexStart=t[o];const r=o<n.length-1?n[o+1]:i;c.geometrySize=r-n[o],c.geometryIndex=o,this.updateGeometryAttributes(s,c)},r,a),this.vertexCount=t[t.length-1]}},go="layout(std140) uniform arcUniforms {\n bool greatCircle;\n bool useShortestPath;\n float numSegments;\n float widthScale;\n float widthMinPixels;\n float widthMaxPixels;\n highp int widthUnits;\n} arc;\n",ho={name:"arc",source:"struct ArcUniforms {\n greatCircle: f32,\n useShortestPath: f32,\n numSegments: f32,\n widthScale: f32,\n widthMinPixels: f32,\n widthMaxPixels: f32,\n widthUnits: i32,\n};\n\n@group(0) @binding(auto) var<uniform> arc: ArcUniforms;\n",vs:go,fs:go,uniformTypes:{greatCircle:"f32",useShortestPath:"f32",numSegments:"f32",widthScale:"f32",widthMinPixels:"f32",widthMaxPixels:"f32",widthUnits:"i32"}},vo=[0,0,0,255],mo={getSourcePosition:{type:"accessor",value:e=>e.sourcePosition},getTargetPosition:{type:"accessor",value:e=>e.targetPosition},getSourceColor:{type:"accessor",value:vo},getTargetColor:{type:"accessor",value:vo},getWidth:{type:"accessor",value:1},getHeight:{type:"accessor",value:1},getTilt:{type:"accessor",value:0},greatCircle:!1,numSegments:{type:"number",value:50,min:1},widthUnits:"pixels",widthScale:{type:"number",value:1,min:0},widthMinPixels:{type:"number",value:0,min:0},widthMaxPixels:{type:"number",value:Number.MAX_SAFE_INTEGER,min:0},antialiasing:!1},_o=class extends co{getBounds(){return this.getAttributeManager()?.getBounds(["instanceSourcePositions","instanceTargetPositions"])}getShaders(){const{antialiasing:e}=this.props;return super.getShaders({vs:"#version 300 es\n#define SHADER_NAME arc-layer-vertex-shader\nin vec4 instanceSourceColors;\nin vec4 instanceTargetColors;\nin vec3 instanceSourcePositions;\nin vec3 instanceSourcePositions64Low;\nin vec3 instanceTargetPositions;\nin vec3 instanceTargetPositions64Low;\nin float instanceWidths;\nin float instanceHeights;\nin float instanceTilts;\nout vec4 vColor;\nout vec2 uv;\nout float isValid;\nfloat paraboloid(float distance, float sourceZ, float targetZ, float ratio) {\nfloat deltaZ = targetZ - sourceZ;\nfloat dh = distance * instanceHeights;\nif (dh == 0.0) {\nreturn sourceZ + deltaZ * ratio;\n}\nfloat unitZ = deltaZ / dh;\nfloat p2 = unitZ * unitZ + 1.0;\nfloat dir = step(deltaZ, 0.0);\nfloat z0 = mix(sourceZ, targetZ, dir);\nfloat r = mix(ratio, 1.0 - ratio, dir);\nreturn sqrt(r * (p2 - r)) * dh + z0;\n}\nvec2 getExtrusionOffset(vec2 line_clipspace, float offset_direction, float width) {\nvec2 dir_screenspace = normalize(line_clipspace * project.viewportSize);\ndir_screenspace = vec2(-dir_screenspace.y, dir_screenspace.x);\nreturn dir_screenspace * offset_direction * width / 2.0;\n}\nfloat getSegmentRatio(float index) {\nreturn smoothstep(0.0, 1.0, index / (arc.numSegments - 1.0));\n}\nvec3 interpolateFlat(vec3 source, vec3 target, float segmentRatio) {\nfloat distance = length(source.xy - target.xy);\nfloat z = paraboloid(distance, source.z, target.z, segmentRatio);\nfloat tiltAngle = radians(instanceTilts);\nvec2 tiltDirection = normalize(target.xy - source.xy);\nvec2 tilt = vec2(-tiltDirection.y, tiltDirection.x) * z * sin(tiltAngle);\nreturn vec3(\nmix(source.xy, target.xy, segmentRatio) + tilt,\nz * cos(tiltAngle)\n);\n}\nfloat getAngularDist (vec2 source, vec2 target) {\nvec2 sourceRadians = radians(source);\nvec2 targetRadians = radians(target);\nvec2 sin_half_delta = sin((sourceRadians - targetRadians) / 2.0);\nvec2 shd_sq = sin_half_delta * sin_half_delta;\nfloat a = shd_sq.y + cos(sourceRadians.y) * cos(targetRadians.y) * shd_sq.x;\nreturn 2.0 * asin(sqrt(a));\n}\nvec3 interpolateGreatCircle(vec3 source, vec3 target, vec3 source3D, vec3 target3D, float angularDist, float t) {\nvec2 lngLat;\nif(abs(angularDist - PI) < 0.001) {\nlngLat = (1.0 - t) * source.xy + t * target.xy;\n} else {\nfloat a = sin((1.0 - t) * angularDist);\nfloat b = sin(t * angularDist);\nvec3 p = source3D.yxz * a + target3D.yxz * b;\nlngLat = degrees(vec2(atan(p.y, -p.x), atan(p.z, length(p.xy))));\n}\nfloat z = paraboloid(angularDist * EARTH_RADIUS, source.z, target.z, t);\nreturn vec3(lngLat, z);\n}\nvoid main(void) {\ngeometry.worldPosition = instanceSourcePositions;\ngeometry.worldPositionAlt = instanceTargetPositions;\nfloat segmentIndex = float(gl_VertexID / 2);\nfloat segmentSide = mod(float(gl_VertexID), 2.) == 0. ? -1. : 1.;\nfloat segmentRatio = getSegmentRatio(segmentIndex);\nfloat prevSegmentRatio = getSegmentRatio(max(0.0, segmentIndex - 1.0));\nfloat nextSegmentRatio = getSegmentRatio(min(arc.numSegments - 1.0, segmentIndex + 1.0));\nfloat indexDir = mix(-1.0, 1.0, step(segmentIndex, 0.0));\nisValid = 1.0;\nuv = vec2(segmentRatio, segmentSide);\ngeometry.uv = uv;\ngeometry.pickingColor = picking_getPickingColorFromInstanceID();\nvec4 curr;\nvec4 next;\nvec3 source;\nvec3 target;\nif ((arc.greatCircle || project.projectionMode == PROJECTION_MODE_GLOBE) && project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT) {\nsource = project_globe_(vec3(instanceSourcePositions.xy, 0.0));\ntarget = project_globe_(vec3(instanceTargetPositions.xy, 0.0));\nfloat angularDist = getAngularDist(instanceSourcePositions.xy, instanceTargetPositions.xy);\nvec3 prevPos = interpolateGreatCircle(instanceSourcePositions, instanceTargetPositions, source, target, angularDist, prevSegmentRatio);\nvec3 currPos = interpolateGreatCircle(instanceSourcePositions, instanceTargetPositions, source, target, angularDist, segmentRatio);\nvec3 nextPos = interpolateGreatCircle(instanceSourcePositions, instanceTargetPositions, source, target, angularDist, nextSegmentRatio);\nif (abs(currPos.x - prevPos.x) > 180.0) {\nindexDir = -1.0;\nisValid = 0.0;\n} else if (abs(currPos.x - nextPos.x) > 180.0) {\nindexDir = 1.0;\nisValid = 0.0;\n}\nnextPos = indexDir < 0.0 ? prevPos : nextPos;\nnextSegmentRatio = indexDir < 0.0 ? prevSegmentRatio : nextSegmentRatio;\nif (isValid == 0.0) {\nnextPos.x += nextPos.x > 0.0 ? -360.0 : 360.0;\nfloat t = ((currPos.x > 0.0 ? 180.0 : -180.0) - currPos.x) / (nextPos.x - currPos.x);\ncurrPos = mix(currPos, nextPos, t);\nsegmentRatio = mix(segmentRatio, nextSegmentRatio, t);\n}\nvec3 currPos64Low = mix(instanceSourcePositions64Low, instanceTargetPositions64Low, segmentRatio);\nvec3 nextPos64Low = mix(instanceSourcePositions64Low, instanceTargetPositions64Low, nextSegmentRatio);\ncurr = project_position_to_clipspace(currPos, currPos64Low, vec3(0.0), geometry.position);\nnext = project_position_to_clipspace(nextPos, nextPos64Low, vec3(0.0));\n} else {\nvec3 source_world = instanceSourcePositions;\nvec3 target_world = instanceTargetPositions;\nif (arc.useShortestPath) {\nsource_world.x = mod(source_world.x + 180., 360.0) - 180.;\ntarget_world.x = mod(target_world.x + 180., 360.0) - 180.;\nfloat deltaLng = target_world.x - source_world.x;\nif (deltaLng > 180.) target_world.x -= 360.;\nif (deltaLng < -180.) source_world.x -= 360.;\n}\nsource = project_position(source_world, instanceSourcePositions64Low);\ntarget = project_position(target_world, instanceTargetPositions64Low);\nfloat antiMeridianX = 0.0;\nif (arc.useShortestPath) {\nif (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR_AUTO_OFFSET) {\nantiMeridianX = -(project.coordinateOrigin.x + 180.) / 360. * TILE_SIZE;\n}\nfloat thresholdRatio = (antiMeridianX - source.x) / (target.x - source.x);\nif (prevSegmentRatio <= thresholdRatio && nextSegmentRatio > thresholdRatio) {\nisValid = 0.0;\nindexDir = sign(segmentRatio - thresholdRatio);\nsegmentRatio = thresholdRatio;\n}\n}\nnextSegmentRatio = indexDir < 0.0 ? prevSegmentRatio : nextSegmentRatio;\nvec3 currPos = interpolateFlat(source, target, segmentRatio);\nvec3 nextPos = interpolateFlat(source, target, nextSegmentRatio);\nif (arc.useShortestPath) {\nif (nextPos.x < antiMeridianX) {\ncurrPos.x += TILE_SIZE;\nnextPos.x += TILE_SIZE;\n}\n}\ncurr = project_common_position_to_clipspace(vec4(currPos, 1.0));\nnext = project_common_position_to_clipspace(vec4(nextPos, 1.0));\ngeometry.position = vec4(currPos, 1.0);\n}\nfloat widthPixels = clamp(\nproject_size_to_pixel(instanceWidths * arc.widthScale, arc.widthUnits),\narc.widthMinPixels, arc.widthMaxPixels\n);\nvec3 offset = vec3(\ngetExtrusionOffset((next.xy - curr.xy) * indexDir, segmentSide, widthPixels),\n0.0);\nDECKGL_FILTER_SIZE(offset, geometry);\n#ifdef ANTIALIASING\nfloat halfWidthPixels = length(offset.xy);\nif (halfWidthPixels > 0.0) {\nfloat coverageScale = 1.0 + 0.5 / project.devicePixelRatio / halfWidthPixels;\noffset.xy *= coverageScale;\nuv.y *= coverageScale;\n}\ngeometry.uv = uv;\n#endif\nDECKGL_FILTER_GL_POSITION(curr, geometry);\ngl_Position = curr + vec4(project_pixel_size_to_clipspace(offset.xy), 0.0, 0.0);\nvec4 color = mix(instanceSourceColors, instanceTargetColors, segmentRatio);\nvColor = vec4(color.rgb, color.a * layer.opacity);\nDECKGL_FILTER_COLOR(vColor, geometry);\n}\n",fs:"#version 300 es\n#define SHADER_NAME arc-layer-fragment-shader\nprecision highp float;\nin vec4 vColor;\nin vec2 uv;\nin float isValid;\nout vec4 fragColor;\nvoid main(void) {\n#ifdef ANTIALIASING\nfloat edgeCoord = abs(uv.y);\nfloat edgePixels = (1.0 - edgeCoord) / max(fwidth(edgeCoord), 1e-6);\n#endif\nif (isValid == 0.0) {\ndiscard;\n}\n#ifdef ANTIALIASING\nif (edgePixels <= -SMOOTH_EDGE_RADIUS) {\ndiscard;\n}\n#endif\nfragColor = vColor;\ngeometry.uv = uv;\n#ifdef ANTIALIASING\nfragColor.a *= smoothedge(0.0, edgePixels);\n#endif\nDECKGL_FILTER_COLOR(fragColor, geometry);\n}\n",source:"const ZERO_OFFSET: vec3<f32> = vec3<f32>(0.0, 0.0, 0.0);\n\nstruct Attributes {\n @location(0) instanceSourcePositions: vec3<f32>,\n @location(1) instanceSourcePositions64Low: vec3<f32>,\n @location(2) instanceTargetPositions: vec3<f32>,\n @location(3) instanceTargetPositions64Low: vec3<f32>,\n @location(4) instanceSourceColors: vec4<f32>,\n @location(5) instanceTargetColors: vec4<f32>,\n @location(6) instanceWidths: f32,\n @location(7) instanceHeights: f32,\n @location(8) instanceTilts: f32,\n};\n\nstruct Varyings {\n @builtin(position) position: vec4<f32>,\n @location(0) color: vec4<f32>,\n @location(1) uv: vec2<f32>,\n @location(2) pickingColor: vec3<f32>,\n @location(3) isValid: f32,\n};\n\nfn paraboloid(\n distance: f32,\n sourceZ: f32,\n targetZ: f32,\n ratio: f32,\n height: f32\n) -> f32 {\n let deltaZ = targetZ - sourceZ;\n let dh = distance * height;\n if (dh == 0.0) {\n return sourceZ + deltaZ * ratio;\n }\n let unitZ = deltaZ / dh;\n let p2 = unitZ * unitZ + 1.0;\n let dir = select(0.0, 1.0, deltaZ <= 0.0);\n let z0 = mix(sourceZ, targetZ, dir);\n let r = mix(ratio, 1.0 - ratio, dir);\n return sqrt(max(r * (p2 - r), 0.0)) * dh + z0;\n}\n\nfn getExtrusionOffset(lineClipspace: vec2<f32>, side: f32, width: f32) -> vec2<f32> {\n var direction = normalize(lineClipspace * project.viewportSize);\n direction = vec2<f32>(-direction.y, direction.x);\n return direction * side * width / 2.0;\n}\n\nfn getSegmentRatio(index: f32) -> f32 {\n return smoothstep(0.0, 1.0, index / max(arc.numSegments - 1.0, 1.0));\n}\n\nfn interpolateFlat(\n source: vec3<f32>,\n targetPosition: vec3<f32>,\n ratio: f32,\n height: f32,\n tiltDegrees: f32\n) -> vec3<f32> {\n let distance = length(source.xy - targetPosition.xy);\n let z = paraboloid(distance, source.z, targetPosition.z, ratio, height);\n let tiltAngle = radians(tiltDegrees);\n let tiltDirection = normalize(targetPosition.xy - source.xy);\n let tilt = vec2<f32>(-tiltDirection.y, tiltDirection.x) * z * sin(tiltAngle);\n return vec3<f32>(mix(source.xy, targetPosition.xy, ratio) + tilt, z * cos(tiltAngle));\n}\n\n// Great circle interpolation\n// http://www.movable-type.co.uk/scripts/latlong.html\nfn getAngularDistance(source: vec2<f32>, targetPosition: vec2<f32>) -> f32 {\n let sourceRadians = radians(source);\n let targetRadians = radians(targetPosition);\n let sinHalfDelta = sin((sourceRadians - targetRadians) / 2.0);\n let sinHalfDeltaSquared = sinHalfDelta * sinHalfDelta;\n let a = sinHalfDeltaSquared.y +\n cos(sourceRadians.y) * cos(targetRadians.y) * sinHalfDeltaSquared.x;\n return 2.0 * asin(sqrt(a));\n}\n\nfn interpolateGreatCircle(\n source: vec3<f32>,\n targetPosition: vec3<f32>,\n source3D: vec3<f32>,\n target3D: vec3<f32>,\n angularDistance: f32,\n ratio: f32,\n height: f32\n) -> vec3<f32> {\n var longitudeLatitude: vec2<f32>;\n\n // If the angular distance is PI, use linear interpolation. Otherwise use spherical interpolation.\n if (abs(angularDistance - PI) < 0.001) {\n longitudeLatitude = (1.0 - ratio) * source.xy + ratio * targetPosition.xy;\n } else {\n let a = sin((1.0 - ratio) * angularDistance);\n let b = sin(ratio * angularDistance);\n let p = source3D.yxz * a + target3D.yxz * b;\n longitudeLatitude = degrees(vec2<f32>(\n atan2(p.y, -p.x),\n atan2(p.z, length(p.xy))\n ));\n }\n\n let z = paraboloid(\n angularDistance * EARTH_RADIUS,\n source.z,\n targetPosition.z,\n ratio,\n height\n );\n return vec3<f32>(longitudeLatitude, z);\n}\n\n@vertex\nfn vertexMain(\n attributes: Attributes,\n @builtin(vertex_index) vertexIndex: u32,\n @builtin(instance_index) instanceIndex: u32\n) -> Varyings {\n geometry.worldPosition = attributes.instanceSourcePositions;\n geometry.worldPositionAlt = attributes.instanceTargetPositions;\n\n let segmentIndex = f32(vertexIndex / 2u);\n let segmentSide = select(-1.0, 1.0, vertexIndex % 2u == 1u);\n var segmentRatio = getSegmentRatio(segmentIndex);\n let previousRatio = getSegmentRatio(max(0.0, segmentIndex - 1.0));\n var nextRatio = getSegmentRatio(min(arc.numSegments - 1.0, segmentIndex + 1.0));\n // If this is the first point, use next - current as direction.\n var indexDirection = select(-1.0, 1.0, segmentIndex <= 0.0);\n var isValid = 1.0;\n\n var currentClip: vec4<f32>;\n var nextClip: vec4<f32>;\n\n if (\n (arc.greatCircle != 0.0 || project.projectionMode == PROJECTION_MODE_GLOBE) &&\n project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT\n ) {\n let source = project_globe_(vec3<f32>(attributes.instanceSourcePositions.xy, 0.0));\n let targetPosition = project_globe_(vec3<f32>(attributes.instanceTargetPositions.xy, 0.0));\n let angularDistance = getAngularDistance(\n attributes.instanceSourcePositions.xy,\n attributes.instanceTargetPositions.xy\n );\n\n let previousPosition = interpolateGreatCircle(\n attributes.instanceSourcePositions,\n attributes.instanceTargetPositions,\n source,\n targetPosition,\n angularDistance,\n previousRatio,\n attributes.instanceHeights\n );\n var currentPosition = interpolateGreatCircle(\n attributes.instanceSourcePositions,\n attributes.instanceTargetPositions,\n source,\n targetPosition,\n angularDistance,\n segmentRatio,\n attributes.instanceHeights\n );\n var nextPosition = interpolateGreatCircle(\n attributes.instanceSourcePositions,\n attributes.instanceTargetPositions,\n source,\n targetPosition,\n angularDistance,\n nextRatio,\n attributes.instanceHeights\n );\n\n if (abs(currentPosition.x - previousPosition.x) > 180.0) {\n indexDirection = -1.0;\n isValid = 0.0;\n } else if (abs(currentPosition.x - nextPosition.x) > 180.0) {\n indexDirection = 1.0;\n isValid = 0.0;\n }\n nextPosition = select(nextPosition, previousPosition, indexDirection < 0.0);\n nextRatio = select(nextRatio, previousRatio, indexDirection < 0.0);\n\n if (isValid == 0.0) {\n // Split at the antimeridian.\n nextPosition.x += select(360.0, -360.0, nextPosition.x > 0.0);\n let ratio = (\n select(-180.0, 180.0, currentPosition.x > 0.0) - currentPosition.x\n ) / (nextPosition.x - currentPosition.x);\n currentPosition = mix(currentPosition, nextPosition, ratio);\n segmentRatio = mix(segmentRatio, nextRatio, ratio);\n }\n\n let currentPosition64Low = mix(\n attributes.instanceSourcePositions64Low,\n attributes.instanceTargetPositions64Low,\n segmentRatio\n );\n let nextPosition64Low = mix(\n attributes.instanceSourcePositions64Low,\n attributes.instanceTargetPositions64Low,\n nextRatio\n );\n let currentProjection = project_position_to_clipspace_and_commonspace(\n currentPosition,\n currentPosition64Low,\n ZERO_OFFSET\n );\n currentClip = currentProjection.clipPosition;\n nextClip = project_position_to_clipspace(nextPosition, nextPosition64Low, ZERO_OFFSET);\n geometry.position = currentProjection.commonPosition;\n } else {\n var sourceWorld = attributes.instanceSourcePositions;\n var targetWorld = attributes.instanceTargetPositions;\n if (arc.useShortestPath != 0.0) {\n sourceWorld.x = ((sourceWorld.x + 180.0) % 360.0) - 180.0;\n targetWorld.x = ((targetWorld.x + 180.0) % 360.0) - 180.0;\n let deltaLongitude = targetWorld.x - sourceWorld.x;\n if (deltaLongitude > 180.0) {\n targetWorld.x -= 360.0;\n }\n if (deltaLongitude < -180.0) {\n sourceWorld.x -= 360.0;\n }\n }\n\n let source = project_position_vec3_f64(\n sourceWorld,\n attributes.instanceSourcePositions64Low\n );\n let targetPosition = project_position_vec3_f64(\n targetWorld,\n attributes.instanceTargetPositions64Low\n );\n\n // Common x at longitude=-180.\n var antimeridianX = 0.0;\n if (arc.useShortestPath != 0.0) {\n if (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR_AUTO_OFFSET) {\n antimeridianX = -(project.coordinateOrigin.x + 180.0) / 360.0 * TILE_SIZE;\n }\n let thresholdRatio = (antimeridianX - source.x) / (targetPosition.x - source.x);\n if (previousRatio <= thresholdRatio && nextRatio > thresholdRatio) {\n isValid = 0.0;\n indexDirection = sign(segmentRatio - thresholdRatio);\n segmentRatio = thresholdRatio;\n }\n }\n\n nextRatio = select(nextRatio, previousRatio, indexDirection < 0.0);\n var currentPosition = interpolateFlat(\n source,\n targetPosition,\n segmentRatio,\n attributes.instanceHeights,\n attributes.instanceTilts\n );\n var nextPosition = interpolateFlat(\n source,\n targetPosition,\n nextRatio,\n attributes.instanceHeights,\n attributes.instanceTilts\n );\n\n if (arc.useShortestPath != 0.0 && nextPosition.x < antimeridianX) {\n currentPosition.x += TILE_SIZE;\n nextPosition.x += TILE_SIZE;\n }\n\n currentClip = project_common_position_to_clipspace(vec4<f32>(currentPosition, 1.0));\n nextClip = project_common_position_to_clipspace(vec4<f32>(nextPosition, 1.0));\n geometry.position = vec4<f32>(currentPosition, 1.0);\n }\n\n geometry.uv = vec2<f32>(segmentRatio, segmentSide);\n geometry.pickingColor = picking_getPickingColorFromIndex(instanceIndex);\n\n let widthPixels = clamp(\n project_unit_size_to_pixel(attributes.instanceWidths * arc.widthScale, arc.widthUnits),\n arc.widthMinPixels,\n arc.widthMaxPixels\n );\n#ifdef ANTIALIASING\n var offset = getExtrusionOffset(\n#else\n let offset = getExtrusionOffset(\n#endif\n (nextClip.xy - currentClip.xy) * indexDirection,\n segmentSide,\n widthPixels\n );\n#ifdef ANTIALIASING\n let halfWidthPixels = length(offset);\n if (halfWidthPixels > 0.0) {\n // Keep the declared edge at abs(uv.y) == 1 while rasterizing the outer half of the centered\n // one-device-pixel coverage ramp.\n let coverageScale = 1.0 + 0.5 / project.devicePixelRatio / halfWidthPixels;\n offset *= coverageScale;\n geometry.uv.y *= coverageScale;\n }\n#endif\n\n var output: Varyings;\n output.position = currentClip + vec4<f32>(project_pixel_size_to_clipspace(offset), 0.0, 0.0);\n let color = mix(attributes.instanceSourceColors, attributes.instanceTargetColors, segmentRatio);\n output.color = vec4<f32>(color.rgb, color.a * layer.opacity);\n output.uv = geometry.uv;\n output.pickingColor = geometry.pickingColor;\n output.isValid = isValid;\n return output;\n}\n\n@fragment\nfn fragmentMain(varyings: Varyings) -> @location(0) vec4<f32> {\n#ifdef ANTIALIASING\n let edgeCoord = abs(varyings.uv.y);\n let edgePixels = (1.0 - edgeCoord) / max(fwidth(edgeCoord), 1e-6);\n#endif\n\n if (varyings.isValid == 0.0) {\n discard;\n }\n\n#ifdef ANTIALIASING\n // Fragments outside the coverage ramp must not write depth or picking colors.\n if (edgePixels <= -SMOOTH_EDGE_RADIUS) {\n discard;\n }\n#endif\n var color = varyings.color;\n#ifdef ANTIALIASING\n // Feather one device pixel across the width. Arc segments meet lengthwise, so only soften the\n // two outer edges of the strip.\n color.a *= smoothedge(0.0, edgePixels);\n#endif\n if (picking.isActive > 0.5) {\n if (!picking_isColorValid(varyings.pickingColor)) {\n discard;\n }\n return vec4<f32>(varyings.pickingColor, 1.0);\n }\n if (picking.isHighlightActive > 0.5) {\n let highlightedObjectColor = picking_normalizeColor(picking.highlightedObjectColor);\n if (picking_isColorZero(abs(varyings.pickingColor - highlightedObjectColor))) {\n let highlightAlpha = picking.highlightColor.a;\n let blendedAlpha = highlightAlpha + color.a * (1.0 - highlightAlpha);\n if (blendedAlpha > 0.0) {\n let highlightRatio = highlightAlpha / blendedAlpha;\n color = vec4<f32>(\n mix(color.rgb, picking.highlightColor.rgb, highlightRatio),\n blendedAlpha\n );\n }\n }\n }\n return deckgl_premultiplied_alpha(color);\n}\n",defines:e?{ANTIALIASING:1}:{},modules:[Ye,Ze,Je,ho]})}get wrapLongitude(){return!1}initializeState(){this.getAttributeManager().addInstanced({instanceSourcePositions:{size:3,type:"float64",fp64:this.use64bitPositions(),transition:!0,accessor:"getSourcePosition"},instanceTargetPositions:{size:3,type:"float64",fp64:this.use64bitPositions(),transition:!0,accessor:"getTargetPosition"},instanceSourceColors:{size:this.props.colorFormat.length,type:"unorm8",transition:!0,accessor:"getSourceColor",defaultValue:vo},instanceTargetColors:{size:this.props.colorFormat.length,type:"unorm8",transition:!0,accessor:"getTargetColor",defaultValue:vo},instanceWidths:{size:1,transition:!0,accessor:"getWidth",defaultValue:1},instanceHeights:{size:1,transition:!0,accessor:"getHeight",defaultValue:1},instanceTilts:{size:1,transition:!0,accessor:"getTilt",defaultValue:0}})}updateState(e){super.updateState(e);const{props:t,oldProps:n,changeFlags:i}=e;(i.extensionsChanged||t.antialiasing!==n.antialiasing)&&(this.state.model?.destroy(),this.state.model=this._getModel(),this.getAttributeManager().invalidateAll())}draw({uniforms:e}){const{widthUnits:t,widthScale:n,widthMinPixels:o,widthMaxPixels:s,greatCircle:r,wrapLongitude:a,numSegments:l}=this.props,c={numSegments:l,widthUnits:i[t],widthScale:n,widthMinPixels:o,widthMaxPixels:s,greatCircle:r,useShortestPath:a},u=this.state.model;u.shaderInputs.setProps({arc:c}),u.setVertexCount(2*l),u.draw(this.context.renderPass)}_getModel(){return new xt(this.context.device,{...this.getShaders(),id:this.props.id,bufferLayout:this.getAttributeManager().getBufferLayouts(),topology:"triangle-strip",isInstanced:!0})}};_o.layerName="ArcLayer",_o.defaultProps=mo;var xo=new Uint32Array([0,2,1,0,3,2]),yo=new Float32Array([0,1,0,0,1,0,1,1]);function bo(e,t){if(!t)return function(e){const t=/* @__PURE__ */new Float64Array(12);for(let n=0;n<e.length;n++)t[3*n+0]=e[n][0],t[3*n+1]=e[n][1],t[3*n+2]=e[n][2]||0;return{vertexCount:6,positions:t,indices:xo,texCoords:yo}}(e);const n=Math.max(Math.abs(e[0][0]-e[3][0]),Math.abs(e[1][0]-e[2][0])),i=Math.max(Math.abs(e[1][1]-e[0][1]),Math.abs(e[2][1]-e[3][1])),o=Math.ceil(n/t)+1,s=Math.ceil(i/t)+1,r=(o-1)*(s-1)*6,a=new Uint32Array(r),l=new Float32Array(o*s*2),c=new Float64Array(o*s*3);let u=0,f=0;for(let d=0;d<o;d++){const t=d/(o-1);for(let n=0;n<s;n++){const i=n/(s-1),o=Po(e,t,i);c[3*u+0]=o[0],c[3*u+1]=o[1],c[3*u+2]=o[2]||0,l[2*u+0]=t,l[2*u+1]=1-i,d>0&&n>0&&(a[f++]=u-s,a[f++]=u-s-1,a[f++]=u-1,a[f++]=u-s,a[f++]=u-1,a[f++]=u),u++}}return{vertexCount:r,positions:c,indices:a,texCoords:l}}function Po(e,t,n){return a(a(e[0],e[1],n),a(e[3],e[2],n),t)}var Co="layout(std140) uniform bitmapUniforms {\n vec4 bounds;\n float coordinateConversion;\n float desaturate;\n vec3 tintColor;\n vec4 transparentColor;\n} bitmap;\n",wo={name:"bitmap",source:"\nstruct BitmapUniforms {\n bounds: vec4<f32>,\n coordinateConversion: f32,\n desaturate: f32,\n tintColor: vec3<f32>,\n transparentColor: vec4<f32>,\n};\n\n@group(0) @binding(auto) var<uniform> bitmap: BitmapUniforms;\n@group(0) @binding(auto) var bitmapTexture: texture_2d<f32>;\n@group(0) @binding(auto) var bitmapTextureSampler: sampler;\n",vs:Co,fs:Co,uniformTypes:{bounds:"vec4<f32>",coordinateConversion:"f32",desaturate:"f32",tintColor:"vec3<f32>",transparentColor:"vec4<f32>"}},So=class extends co{getShaders(){return super.getShaders({vs:"#version 300 es\n#define SHADER_NAME bitmap-layer-vertex-shader\n\nin vec2 texCoords;\nin vec3 positions;\nin vec3 positions64Low;\n\nout vec2 vTexCoord;\nout vec2 vTexPos;\n\nconst vec3 pickingColor = vec3(1.0, 0.0, 0.0);\n\nvoid main(void) {\n geometry.worldPosition = positions;\n geometry.uv = texCoords;\n geometry.pickingColor = pickingColor;\n\n gl_Position = project_position_to_clipspace(positions, positions64Low, vec3(0.0), geometry.position);\n DECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n\n vTexCoord = texCoords;\n\n if (bitmap.coordinateConversion < -0.5) {\n vTexPos = geometry.position.xy + project.commonOrigin.xy;\n } else if (bitmap.coordinateConversion > 0.5) {\n vTexPos = geometry.worldPosition.xy;\n }\n\n vec4 color = vec4(0.0);\n DECKGL_FILTER_COLOR(color, geometry);\n}\n",fs:"#version 300 es\n#define SHADER_NAME bitmap-layer-fragment-shader\n\n#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D bitmapTexture;\n\nin vec2 vTexCoord;\nin vec2 vTexPos;\n\nout vec4 fragColor;\n\n/* projection utils */\nconst float TILE_SIZE = 512.0;\nconst float PI = 3.1415926536;\nconst float WORLD_SCALE = TILE_SIZE / PI / 2.0;\n\n// from degrees to Web Mercator\nvec2 lnglat_to_mercator(vec2 lnglat) {\n float x = lnglat.x;\n float y = clamp(lnglat.y, -89.9, 89.9);\n return vec2(\n radians(x) + PI,\n PI + log(tan(PI * 0.25 + radians(y) * 0.5))\n ) * WORLD_SCALE;\n}\n\n// from Web Mercator to degrees\nvec2 mercator_to_lnglat(vec2 xy) {\n xy /= WORLD_SCALE;\n return degrees(vec2(\n xy.x - PI,\n atan(exp(xy.y - PI)) * 2.0 - PI * 0.5\n ));\n}\n/* End projection utils */\n\n// apply desaturation\nvec3 color_desaturate(vec3 color) {\n float luminance = (color.r + color.g + color.b) * 0.333333333;\n return mix(color, vec3(luminance), bitmap.desaturate);\n}\n\n// apply tint\nvec3 color_tint(vec3 color) {\n return color * bitmap.tintColor;\n}\n\n// blend with background color\nvec4 apply_opacity(vec3 color, float alpha) {\n if (bitmap.transparentColor.a == 0.0) {\n return vec4(color, alpha);\n }\n float blendedAlpha = alpha + bitmap.transparentColor.a * (1.0 - alpha);\n float highLightRatio = alpha / blendedAlpha;\n vec3 blendedRGB = mix(bitmap.transparentColor.rgb, color, highLightRatio);\n return vec4(blendedRGB, blendedAlpha);\n}\n\nvec2 getUV(vec2 pos) {\n return vec2(\n (pos.x - bitmap.bounds[0]) / (bitmap.bounds[2] - bitmap.bounds[0]),\n (pos.y - bitmap.bounds[3]) / (bitmap.bounds[1] - bitmap.bounds[3])\n );\n}\n\n\nvec3 packUVsIntoRGB(vec2 uv) {\n // Extract the top 8 bits. We want values to be truncated down so we can add a fraction\n vec2 uv8bit = floor(uv * 256.);\n\n // Calculate the normalized remainders of u and v parts that do not fit into 8 bits\n // Scale and clamp to 0-1 range\n vec2 uvFraction = fract(uv * 256.);\n vec2 uvFraction4bit = floor(uvFraction * 16.);\n\n // Remainder can be encoded in blue channel, encode as 4 bits for pixel coordinates\n float fractions = uvFraction4bit.x + uvFraction4bit.y * 16.;\n\n return vec3(uv8bit, fractions) / 255.;\n}\n\n\nvoid main(void) {\n vec2 uv = vTexCoord;\n if (bitmap.coordinateConversion < -0.5) {\n vec2 lnglat = mercator_to_lnglat(vTexPos);\n uv = getUV(lnglat);\n } else if (bitmap.coordinateConversion > 0.5) {\n vec2 commonPos = lnglat_to_mercator(vTexPos);\n uv = getUV(commonPos);\n }\n vec4 bitmapColor = texture(bitmapTexture, uv);\n\n fragColor = apply_opacity(color_tint(color_desaturate(bitmapColor.rgb)), bitmapColor.a * layer.opacity);\n\n geometry.uv = uv;\n DECKGL_FILTER_COLOR(fragColor, geometry);\n\n if (bool(picking.isActive) && !bool(picking.isAttribute)) {\n // Since instance information is not used, we can use picking color for pixel index\n fragColor.rgb = packUVsIntoRGB(uv);\n }\n}\n",source:"struct Attributes {\n @location(0) positions: vec3<f32>,\n @location(1) positions64Low: vec3<f32>,\n @location(2) texCoords: vec2<f32>,\n};\n\nstruct Varyings {\n @builtin(position) position: vec4<f32>,\n @location(0) vTexCoord: vec2<f32>,\n @location(1) vTexPos: vec2<f32>,\n @location(2) pickingColor: vec3<f32>,\n @location(3) pickingDepth: f32,\n};\n\n// from degrees to Web Mercator\nfn lnglat_to_mercator(lnglat: vec2<f32>) -> vec2<f32> {\n let x = lnglat.x;\n let y = clamp(lnglat.y, -89.9, 89.9);\n return vec2<f32>(\n radians(x) + PI,\n PI + log(tan(PI * 0.25 + radians(y) * 0.5))\n ) * WORLD_SCALE;\n}\n\n// from Web Mercator to degrees\nfn mercator_to_lnglat(xy: vec2<f32>) -> vec2<f32> {\n let position = xy / WORLD_SCALE;\n return degrees(vec2<f32>(\n position.x - PI,\n atan(exp(position.y - PI)) * 2.0 - PI * 0.5\n ));\n}\n\nfn color_desaturate(colorValue: vec3<f32>) -> vec3<f32> {\n let luminance = (colorValue.r + colorValue.g + colorValue.b) * 0.333333333;\n return mix(colorValue, vec3<f32>(luminance), bitmap.desaturate);\n}\n\nfn color_tint(colorValue: vec3<f32>) -> vec3<f32> {\n return colorValue * bitmap.tintColor;\n}\n\nfn apply_opacity(colorValue: vec3<f32>, alpha: f32) -> vec4<f32> {\n if (bitmap.transparentColor.a == 0.0) {\n return vec4<f32>(colorValue, alpha);\n }\n let blendedAlpha = alpha + bitmap.transparentColor.a * (1.0 - alpha);\n let highLightRatio = alpha / blendedAlpha;\n let blendedRGB = mix(bitmap.transparentColor.rgb, colorValue, highLightRatio);\n return vec4<f32>(blendedRGB, blendedAlpha);\n}\n\nfn getUV(position: vec2<f32>) -> vec2<f32> {\n return vec2<f32>(\n (position.x - bitmap.bounds[0]) / (bitmap.bounds[2] - bitmap.bounds[0]),\n (position.y - bitmap.bounds[3]) / (bitmap.bounds[1] - bitmap.bounds[3])\n );\n}\n\n// Pack the top 12 bits of two normalized floats into three 8-bit values.\nfn packUVsIntoRGB(uv: vec2<f32>) -> vec3<f32> {\n let uv8bit = floor(uv * 256.0);\n let uvFraction = fract(uv * 256.0);\n let uvFraction4bit = floor(uvFraction * 16.0);\n let fractions = uvFraction4bit.x + uvFraction4bit.y * 16.0;\n return vec3<f32>(uv8bit, fractions) / 255.0;\n}\n\n@vertex\nfn vertexMain(attributes: Attributes) -> Varyings {\n var output: Varyings;\n geometry.worldPosition = attributes.positions;\n geometry.uv = attributes.texCoords;\n geometry.pickingColor = picking_getPickingColorFromIndex(0u);\n\n let projectedPosition = project_position_to_clipspace_and_commonspace(\n attributes.positions,\n attributes.positions64Low,\n vec3<f32>(0.0)\n );\n geometry.position = projectedPosition.commonPosition;\n output.position = projectedPosition.clipPosition;\n output.vTexCoord = attributes.texCoords;\n output.vTexPos = vec2<f32>(0.0);\n output.pickingColor = geometry.pickingColor;\n output.pickingDepth = output.position.z / output.position.w;\n\n if (bitmap.coordinateConversion < -0.5) {\n output.vTexPos = geometry.position.xy + project.commonOrigin.xy;\n } else if (bitmap.coordinateConversion > 0.5) {\n output.vTexPos = geometry.worldPosition.xy;\n }\n\n return output;\n}\n\n@fragment\nfn fragmentMain(input: Varyings) -> @location(0) vec4<f32> {\n var uv = input.vTexCoord;\n if (bitmap.coordinateConversion < -0.5) {\n uv = getUV(mercator_to_lnglat(input.vTexPos));\n } else if (bitmap.coordinateConversion > 0.5) {\n uv = getUV(lnglat_to_mercator(input.vTexPos));\n }\n\n let bitmapColor = textureSample(bitmapTexture, bitmapTextureSampler, uv);\n var fragColor = apply_opacity(\n color_tint(color_desaturate(bitmapColor.rgb)),\n bitmapColor.a * layer.opacity\n );\n\n geometry.uv = uv;\n\n if (picking.isActive > 0.5) {\n if (picking.isAttribute > 0.5) {\n return vec4<f32>(input.pickingDepth, 0.0, 0.0, 1.0);\n }\n return vec4<f32>(packUVsIntoRGB(uv), 1.0);\n }\n\n if (picking.isHighlightActive > 0.5) {\n let highlightedObjectColor = picking_normalizeColor(picking.highlightedObjectColor);\n if (picking_isColorZero(abs(input.pickingColor - highlightedObjectColor))) {\n let highLightAlpha = picking.highlightColor.a;\n let blendedAlpha = highLightAlpha + fragColor.a * (1.0 - highLightAlpha);\n if (blendedAlpha > 0.0) {\n let highLightRatio = highLightAlpha / blendedAlpha;\n fragColor = vec4<f32>(\n mix(fragColor.rgb, picking.highlightColor.rgb, highLightRatio),\n blendedAlpha\n );\n } else {\n fragColor = vec4<f32>(fragColor.rgb, 0.0);\n }\n }\n }\n\n return deckgl_premultiplied_alpha(fragColor);\n}\n",modules:[Ze,Ye,Je,wo]})}initializeState(){const e=!0;this.getAttributeManager().add({indices:{size:1,isIndexed:!0,update:e=>e.value=this.state.mesh.indices,noAlloc:e},positions:{size:3,type:"float64",fp64:this.use64bitPositions(),update:e=>e.value=this.state.mesh.positions,noAlloc:e},texCoords:{size:2,update:e=>e.value=this.state.mesh.texCoords,noAlloc:e}})}updateState({props:e,oldProps:t,changeFlags:n}){const i=this.getAttributeManager();if(n.extensionsChanged&&(this.state.model?.destroy(),this.state.model=this._getModel(),i.invalidateAll()),e.bounds!==t.bounds){const e=this.state.mesh,t=this._createMesh();this.state.model.setVertexCount(t.vertexCount);for(const n in t)e&&e[n]!==t[n]&&i.invalidate(n);this.setState({mesh:t,...this._getCoordinateUniforms()})}else e._imageCoordinateSystem!==t._imageCoordinateSystem&&this.setState(this._getCoordinateUniforms())}getPickingInfo(e){const{image:t}=this.props,n=e.info;if(!n.color||!t)return n.bitmap=null,n;const{width:i,height:o}=t;n.index=0;const s=function(e){const[t,n,i]=e;return[(t+(15&i)/16)/256,(n+(240&i)/256)/256]}(n.color);return n.bitmap={size:{width:i,height:o},uv:s,pixel:[Math.floor(s[0]*i),Math.floor(s[1]*o)]},n}disablePickingIndex(){this.setState({disablePicking:!0})}restorePickingColors(){this.setState({disablePicking:!1})}_updateAutoHighlight(e){super._updateAutoHighlight({...e,color:this.encodePickingColor(0)})}_createMesh(){const{bounds:e}=this.props;let t=e;return Lo(e)&&(t=[[e[0],e[1]],[e[0],e[3]],[e[2],e[3]],[e[2],e[1]]]),bo(t,this.context.viewport.resolution)}_getModel(){const e="webgpu"===this.context.device.type?this.getAttributeManager().getBufferLayouts({isInstanced:!1}).filter(e=>"indices"!==e.name):this.getAttributeManager().getBufferLayouts();return new xt(this.context.device,{...this.getShaders(),id:this.props.id,bufferLayout:e,topology:"triangle-list",isInstanced:!1})}draw(e){const{shaderModuleProps:t}=e,{model:n,coordinateConversion:i,bounds:o,disablePicking:s}=this.state,{image:r,desaturate:a,transparentColor:l,tintColor:c}=this.props;if((!t.picking.isActive||!s)&&r&&n){const e={bitmapTexture:r,bounds:o,coordinateConversion:i,desaturate:a,tintColor:c.slice(0,3).map(e=>e/255),transparentColor:l.map(e=>e/255)};n.shaderInputs.setProps({bitmap:e}),n.draw(this.context.renderPass)}}_getCoordinateUniforms(){let{_imageCoordinateSystem:e}=this.props;if("default"!==e){const{bounds:t}=this.props;if(!Lo(t))throw new Error("_imageCoordinateSystem only supports rectangular bounds");const n=this.context.viewport.resolution?"lnglat":"cartesian";if(e="lnglat"===e?"lnglat":"cartesian","lnglat"===e&&"cartesian"===n)return{coordinateConversion:-1,bounds:t};if("cartesian"===e&&"lnglat"===n){const e=s([t[0],t[1]]),n=s([t[2],t[3]]);return{coordinateConversion:1,bounds:[e[0],e[1],n[0],n[1]]}}}return{coordinateConversion:0,bounds:[0,0,0,0]}}};function Lo(e){return Number.isFinite(e[0])}So.layerName="BitmapLayer",So.defaultProps={image:{type:"image",value:null,async:!0},bounds:{type:"array",value:[1,0,0,1],compare:!0},_imageCoordinateSystem:"default",desaturate:{type:"number",min:0,max:1,value:0},transparentColor:{type:"color",value:[0,0,0,0]},tintColor:{type:"color",value:[255,255,255]},textureParameters:{type:"object",ignore:!0,value:null}};var Ao="layout(std140) uniform iconUniforms {\n float sizeScale;\n vec2 iconsTextureDim;\n float sizeBasis;\n float sizeMinPixels;\n float sizeMaxPixels;\n bool billboard;\n highp int sizeUnits;\n float alphaCutoff;\n} icon;\n",Io={name:"icon",vs:Ao,fs:Ao,uniformTypes:{sizeScale:"f32",iconsTextureDim:"vec2<f32>",sizeBasis:"f32",sizeMinPixels:"f32",sizeMaxPixels:"f32",billboard:"f32",sizeUnits:"i32",alphaCutoff:"f32"}},Eo='struct IconUniforms {\n sizeScale: f32,\n iconsTextureDim: vec2<f32>,\n sizeBasis: f32,\n sizeMinPixels: f32,\n sizeMaxPixels: f32,\n billboard: i32,\n sizeUnits: i32,\n alphaCutoff: f32\n};\n\n@group(0) @binding(auto) var<uniform> icon: IconUniforms;\n@group(0) @binding(auto) var iconsTexture : texture_2d<f32>;\n@group(0) @binding(auto) var iconsTextureSampler : sampler;\n\nfn rotate_by_angle(vertex: vec2<f32>, angle_deg: f32) -> vec2<f32> {\n let angle_radian = angle_deg * PI / 180.0;\n let c = cos(angle_radian);\n let s = sin(angle_radian);\n let rotation = mat2x2<f32>(vec2<f32>(c, s), vec2<f32>(-s, c));\n return rotation * vertex;\n}\n\nstruct Attributes {\n @builtin(instance_index) instanceIndex : u32,\n @location(0) positions: vec2<f32>,\n\n @location(1) instancePositions: vec3<f32>,\n @location(2) instancePositions64Low: vec3<f32>,\n @location(3) instanceSizes: f32,\n @location(4) instanceAngles: f32,\n @location(5) instanceColors: vec4<f32>,\n @location(6) instanceIconFrames: vec4<f32>,\n @location(7) instanceColorModes: f32,\n @location(8) instanceOffsets: vec2<f32>,\n @location(9) instancePixelOffset: vec2<f32>,\n PICKING_COLOR_ATTRIBUTE\n};\n\nstruct Varyings {\n @builtin(position) position: vec4<f32>,\n\n @location(0) vColorMode: f32,\n @location(1) vColor: vec4<f32>,\n @location(2) vTextureCoords: vec2<f32>,\n @location(3) uv: vec2<f32>,\n @location(4) pickingColor: vec3<f32>,\n};\n\n@vertex\nfn vertexMain(inp: Attributes) -> Varyings {\n // write geometry fields used by filters + FS\n geometry.worldPosition = inp.instancePositions;\n geometry.uv = inp.positions;\n geometry.pickingColor = PICKING_COLOR_VALUE;\n\n var outp: Varyings;\n outp.uv = inp.positions;\n\n let iconSize = inp.instanceIconFrames.zw;\n\n // convert size in meters to pixels, then clamp\n let sizePixels = clamp(\n project_unit_size_to_pixel(inp.instanceSizes * icon.sizeScale, icon.sizeUnits),\n icon.sizeMinPixels, icon.sizeMaxPixels\n );\n\n // scale icon height to match instanceSize\n let iconConstraint = select(iconSize.y, iconSize.x, icon.sizeBasis == 0.0);\n let instanceScale = select(sizePixels / iconConstraint, 0.0, iconConstraint == 0.0);\n\n // scale and rotate vertex in "pixel" units; then add per-instance pixel offset\n var pixelOffset = inp.positions / 2.0 * iconSize + inp.instanceOffsets;\n pixelOffset = rotate_by_angle(pixelOffset, inp.instanceAngles) * instanceScale;\n pixelOffset = pixelOffset + inp.instancePixelOffset;\n pixelOffset.y = pixelOffset.y * -1.0;\n\n if (icon.billboard != 0) {\n var pos = project_position_to_clipspace(inp.instancePositions, inp.instancePositions64Low, vec3<f32>(0.0)); // TODO, &geometry.position);\n // DECKGL_FILTER_GL_POSITION(pos, geometry);\n\n var offset = vec3<f32>(pixelOffset, 0.0);\n // DECKGL_FILTER_SIZE(offset, geometry);\n let clipOffset = project_pixel_size_to_clipspace(offset.xy);\n pos = vec4<f32>(pos.x + clipOffset.x, pos.y + clipOffset.y, pos.z, pos.w);\n outp.position = pos;\n } else {\n var offset_common = vec3<f32>(project_pixel_size_vec2(pixelOffset), 0.0);\n // DECKGL_FILTER_SIZE(offset_common, geometry);\n var pos = project_position_to_clipspace(inp.instancePositions, inp.instancePositions64Low, offset_common); // TODO, &geometry.position);\n // DECKGL_FILTER_GL_POSITION(pos, geometry);\n outp.position = pos;\n }\n\n let uvMix = (inp.positions.xy + vec2<f32>(1.0, 1.0)) * 0.5;\n outp.vTextureCoords = mix(inp.instanceIconFrames.xy, inp.instanceIconFrames.xy + iconSize, uvMix) / icon.iconsTextureDim;\n\n outp.vColor = inp.instanceColors;\n // DECKGL_FILTER_COLOR(outp.vColor, geometry);\n\n outp.vColorMode = inp.instanceColorModes;\n outp.pickingColor = geometry.pickingColor;\n\n return outp;\n}\n\n@fragment\nfn fragmentMain(inp: Varyings) -> @location(0) vec4<f32> {\n // expose to deck.gl filter hooks\n geometry.uv = inp.uv;\n\n let texColor = textureSample(iconsTexture, iconsTextureSampler, inp.vTextureCoords);\n\n // if colorMode == 0, use pixel color from the texture\n // if colorMode == 1 (or picking), use texture as transparency mask\n let rgb = mix(texColor.rgb, inp.vColor.rgb, inp.vColorMode);\n let a = texColor.a * layer.opacity * inp.vColor.a;\n\n if (a < icon.alphaCutoff) {\n discard;\n }\n\n if (picking.isActive > 0.5) {\n if (!picking_isColorValid(inp.pickingColor)) {\n discard;\n }\n return vec4<f32>(inp.pickingColor, 1.0);\n }\n\n var fragColor = deckgl_premultiplied_alpha(vec4<f32>(rgb, a));\n\n if (picking.isHighlightActive > 0.5) {\n let highlightedObjectColor = picking_normalizeColor(picking.highlightedObjectColor);\n if (picking_isColorZero(abs(inp.pickingColor - highlightedObjectColor))) {\n let highLightAlpha = picking.highlightColor.a;\n let blendedAlpha = highLightAlpha + fragColor.a * (1.0 - highLightAlpha);\n if (blendedAlpha > 0.0) {\n let highLightRatio = highLightAlpha / blendedAlpha;\n fragColor = vec4<f32>(\n mix(fragColor.rgb, picking.highlightColor.rgb, highLightRatio),\n blendedAlpha\n );\n } else {\n fragColor = vec4<f32>(fragColor.rgb, 0.0);\n }\n }\n }\n\n return fragColor;\n}\n';function To(e){return Eo.replace("PICKING_COLOR_ATTRIBUTE",e?"@location(10) rowIndexes: u32,":"").replace("PICKING_COLOR_VALUE",e?"picking_getPickingColorFromIndex(inp.rowIndexes)":"picking_getPickingColorFromIndex(inp.instanceIndex)")}var Oo=()=>{},zo={minFilter:"linear",mipmapFilter:"linear",magFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"},Mo={x:0,y:0,width:0,height:0};function Ro(e,t,n,i){const o=Math.min(n/t.width,i/t.height),s=Math.floor(t.width*o),r=Math.floor(t.height*o);return 1===o?{image:t,width:s,height:r}:(e.canvas.height=r,e.canvas.width=s,e.clearRect(0,0,s,r),e.drawImage(t,0,0,t.width,t.height,0,0,s,r),{image:e.canvas,width:s,height:r})}function Bo(e){return e&&(e.id||e.url)}function ko(e){const{device:t}=e;"webgl"===t.type?e.generateMipmapsWebGL():"webgpu"===t.type&&t.generateMipmapsWebGPU(e)}function Fo(e,t,n){for(let i=0;i<t.length;i++){const{icon:o,xOffset:s}=t[i];e[Bo(o)]={...o,x:s,y:n}}}var No=class{constructor(e,{onUpdate:t=Oo,onError:n=Oo}){this._loadOptions=null,this._texture=null,this._externalTexture=null,this._mapping={},this._samplerParameters=null,this._pendingCount=0,this._autoPacking=!1,this._xOffset=0,this._yOffset=0,this._rowHeight=0,this._buffer=4,this._canvasWidth=1024,this._canvasHeight=0,this._canvas=null,this.device=e,this.onUpdate=t,this.onError=n}finalize(){this._texture?.delete()}getTexture(){return this._texture||this._externalTexture}getIconMapping(e){const t=this._autoPacking?Bo(e):e;return this._mapping[t]||Mo}setProps({loadOptions:e,autoPacking:t,iconAtlas:n,iconMapping:i,textureParameters:o}){e&&(this._loadOptions=e),void 0!==t&&(this._autoPacking=t),i&&(this._mapping=i),n&&(this._texture?.delete(),this._texture=null,this._externalTexture=n),o&&(this._samplerParameters=o)}get isLoaded(){return 0===this._pendingCount}packIcons(e,t){if(!this._autoPacking||"undefined"==typeof document)return;const n=Object.values(function(e,t,n){if(!e||!t)return null;n=n||{};const i={},{iterable:o,objectInfo:s}=$t(e);for(const r of o){s.index++;const e=t(r,s),o=Bo(e);if(!e)throw new Error("Icon is missing.");if(!e.url)throw new Error("Icon url is missing.");i[o]||n[o]&&e.url===n[o].url||(i[o]={...e,source:r,sourceIndex:s.index})}return i}(e,t,this._mapping)||{});if(n.length>0){const{mapping:e,xOffset:t,yOffset:i,rowHeight:o,canvasHeight:s}=function({icons:e,buffer:t,mapping:n={},xOffset:i=0,yOffset:o=0,rowHeight:s=0,canvasWidth:r}){let a=[];for(let c=0;c<e.length;c++){const l=e[c];if(!n[Bo(l)]){const{height:e,width:c}=l;i+c+t>r&&(Fo(n,a,o),i=0,o=s+o+t,s=0,a=[]),a.push({icon:l,xOffset:i}),i=i+c+t,s=Math.max(s,e)}}return a.length>0&&Fo(n,a,o),{mapping:n,rowHeight:s,xOffset:i,yOffset:o,canvasWidth:r,canvasHeight:(l=s+o+t,Math.pow(2,Math.ceil(Math.log2(l))))};var l}({icons:n,buffer:this._buffer,canvasWidth:this._canvasWidth,mapping:this._mapping,rowHeight:this._rowHeight,xOffset:this._xOffset,yOffset:this._yOffset});this._rowHeight=o,this._mapping=e,this._xOffset=t,this._yOffset=i,this._canvasHeight=s,this._texture||(this._texture=this.device.createTexture({format:"rgba8unorm",data:null,width:this._canvasWidth,height:this._canvasHeight,sampler:this._samplerParameters||zo,mipLevels:this.device.getMipLevelCount(this._canvasWidth,this._canvasHeight)})),this._texture.height!==this._canvasHeight&&(this._texture=function(e,t,n,i){const{width:o,height:s,device:r}=e,a=r.createTexture({format:"rgba8unorm",width:t,height:n,sampler:i,mipLevels:r.getMipLevelCount(t,n)}),l=r.createCommandEncoder();l.copyTextureToTexture({sourceTexture:e,destinationTexture:a,width:o,height:s});const c=l.finish();return r.submit(c),ko(a),e.destroy(),a}(this._texture,this._canvasWidth,this._canvasHeight,this._samplerParameters||zo)),this.onUpdate(!0),this._canvas=this._canvas||document.createElement("canvas"),this._loadIcons(n)}}_loadIcons(e){const t=this._canvas.getContext("2d",{willReadFrequently:!0});for(const n of e)this._pendingCount++,P(n.url,this._loadOptions).then(e=>{const i=Bo(n),o=this._mapping[i],{x:s,y:r,width:a,height:l}=o,{image:c,width:u,height:f}=Ro(t,e,a,l),d=s+(a-u)/2,p=r+(l-f)/2;this._texture?.copyExternalImage({image:c,x:d,y:p,width:u,height:f}),o.x=d,o.y=p,o.width=u,o.height=f,this._texture&&ko(this._texture),this.onUpdate(u!==a||f!==l)}).catch(e=>{this.onError({url:n.url,source:n.source,sourceIndex:n.sourceIndex,loadOptions:this._loadOptions,error:e})}).finally(()=>{this._pendingCount--})}},Do=[0,0,0,255],jo={iconAtlas:{type:"image",value:null,async:!0},iconMapping:{type:"object",value:{},async:!0},sizeScale:{type:"number",value:1,min:0},billboard:!0,sizeUnits:"pixels",sizeBasis:"height",sizeMinPixels:{type:"number",min:0,value:0},sizeMaxPixels:{type:"number",min:0,value:Number.MAX_SAFE_INTEGER},alphaCutoff:{type:"number",value:.05,min:0,max:1},getPosition:{type:"accessor",value:e=>e.position},getIcon:{type:"accessor",value:e=>e.icon},getColor:{type:"accessor",value:Do},getSize:{type:"accessor",value:1},getAngle:{type:"accessor",value:0},getPixelOffset:{type:"accessor",value:[0,0]},onIconError:{type:"function",value:null,optional:!0},textureParameters:{type:"object",ignore:!0,value:null}},Uo=class extends co{getShaders(){const e=Boolean(this.props.data?.attributes?.rowIndexes);return super.getShaders({vs:"#version 300 es\n#define SHADER_NAME icon-layer-vertex-shader\nin vec2 positions;\nin vec3 instancePositions;\nin vec3 instancePositions64Low;\nin float instanceSizes;\nin float instanceAngles;\nin vec4 instanceColors;\n#ifdef USE_ROW_INDEXES\nin float rowIndexes;\n#endif\nin vec4 instanceIconFrames;\nin float instanceColorModes;\nin vec2 instanceOffsets;\nin vec2 instancePixelOffset;\nout float vColorMode;\nout vec4 vColor;\nout vec2 vTextureCoords;\nout vec2 uv;\nvec2 rotate_by_angle(vec2 vertex, float angle) {\nfloat angle_radian = angle * PI / 180.0;\nfloat cos_angle = cos(angle_radian);\nfloat sin_angle = sin(angle_radian);\nmat2 rotationMatrix = mat2(cos_angle, -sin_angle, sin_angle, cos_angle);\nreturn rotationMatrix * vertex;\n}\nvoid main(void) {\ngeometry.worldPosition = instancePositions;\ngeometry.uv = positions;\n#ifdef USE_ROW_INDEXES\ngeometry.pickingColor = picking_getPickingColorFromIndex(rowIndexes);\n#else\ngeometry.pickingColor = picking_getPickingColorFromInstanceID();\n#endif\nuv = positions;\nvec2 iconSize = instanceIconFrames.zw;\nfloat sizePixels = clamp(\nproject_size_to_pixel(instanceSizes * icon.sizeScale, icon.sizeUnits),\nicon.sizeMinPixels, icon.sizeMaxPixels\n);\nfloat iconConstraint = icon.sizeBasis == 0.0 ? iconSize.x : iconSize.y;\nfloat instanceScale = iconConstraint == 0.0 ? 0.0 : sizePixels / iconConstraint;\nvec2 pixelOffset = positions / 2.0 * iconSize + instanceOffsets;\npixelOffset = rotate_by_angle(pixelOffset, instanceAngles) * instanceScale;\npixelOffset += instancePixelOffset;\npixelOffset.y *= -1.0;\nif (icon.billboard) {\ngl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.0), geometry.position);\nDECKGL_FILTER_GL_POSITION(gl_Position, geometry);\nvec3 offset = vec3(pixelOffset, 0.0);\nDECKGL_FILTER_SIZE(offset, geometry);\ngl_Position.xy += project_pixel_size_to_clipspace(offset.xy);\n} else {\nvec3 offset_common = vec3(project_pixel_size(pixelOffset), 0.0);\nDECKGL_FILTER_SIZE(offset_common, geometry);\ngl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, offset_common, geometry.position);\nDECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n}\nvTextureCoords = mix(\ninstanceIconFrames.xy,\ninstanceIconFrames.xy + iconSize,\n(positions.xy + 1.0) / 2.0\n) / icon.iconsTextureDim;\nvColor = instanceColors;\nDECKGL_FILTER_COLOR(vColor, geometry);\nvColorMode = instanceColorModes;\n}\n",fs:"#version 300 es\n#define SHADER_NAME icon-layer-fragment-shader\nprecision highp float;\nuniform sampler2D iconsTexture;\nin float vColorMode;\nin vec4 vColor;\nin vec2 vTextureCoords;\nin vec2 uv;\nout vec4 fragColor;\nvoid main(void) {\ngeometry.uv = uv;\nvec4 texColor = texture(iconsTexture, vTextureCoords);\nvec3 color = mix(texColor.rgb, vColor.rgb, vColorMode);\nfloat a = texColor.a * layer.opacity * vColor.a;\nif (a < icon.alphaCutoff) {\ndiscard;\n}\nfragColor = vec4(color, a);\nDECKGL_FILTER_COLOR(fragColor, geometry);\n}\n",source:To(e),defines:e?{USE_ROW_INDEXES:!0}:{},modules:[Ye,Ze,Je,Io]})}initializeState(){this.state={iconManager:new No(this.context.device,{onUpdate:this._onUpdate.bind(this),onError:this._onError.bind(this)})},this.getAttributeManager().addInstanced({instancePositions:{size:3,type:"float64",fp64:this.use64bitPositions(),transition:!0,accessor:"getPosition"},instanceSizes:{size:1,transition:!0,bufferGroup:"icon-instance-data",accessor:"getSize",defaultValue:1},instanceIconDefs:{size:7,bufferGroup:"icon-instance-data",accessor:"getIcon",transform:this.getInstanceIconDef,shaderAttributes:{instanceOffsets:{size:2,elementOffset:0},instanceIconFrames:{size:4,elementOffset:2},instanceColorModes:{size:1,elementOffset:6}}},instanceColors:{size:this.props.colorFormat.length,type:"unorm8",transition:!0,bufferGroup:"icon-instance-data",accessor:"getColor",defaultValue:Do},instanceAngles:{size:1,transition:!0,bufferGroup:"icon-instance-data",accessor:"getAngle"},instancePixelOffset:{size:2,transition:!0,bufferGroup:"icon-instance-data",accessor:"getPixelOffset"},...this.props.data?.attributes?.rowIndexes?{rowIndexes:{size:1,type:"uint32",noAlloc:!0}}:{}})}updateState(e){super.updateState(e);const{props:t,oldProps:n,changeFlags:i}=e,o=this.getAttributeManager(),{iconAtlas:s,iconMapping:r,data:a,getIcon:l,textureParameters:c}=t,{iconManager:u}=this.state;if("string"==typeof s)return;const f=s||this.internalState.isAsyncPropLoading("iconAtlas");u.setProps({loadOptions:t.loadOptions,autoPacking:!f,iconAtlas:s,iconMapping:f?r:null,textureParameters:c}),f?n.iconMapping!==t.iconMapping&&o.invalidate("getIcon"):(i.dataChanged||i.updateTriggersChanged&&(i.updateTriggersChanged.all||i.updateTriggersChanged.getIcon))&&u.packIcons(a,l),i.extensionsChanged&&(this.state.model?.destroy(),this.state.model=this._getModel(),o.invalidateAll())}get isLoaded(){return super.isLoaded&&this.state.iconManager.isLoaded}finalizeState(e){super.finalizeState(e),this.state.iconManager.finalize()}draw({uniforms:e}){this._drawModel(this.state.model)}_drawModel(e){const{sizeScale:t,sizeBasis:n,sizeMinPixels:o,sizeMaxPixels:s,sizeUnits:r,billboard:a,alphaCutoff:l}=this.props,{iconManager:c}=this.state,u=c.getTexture();if(u){const c={iconsTexture:u,iconsTextureDim:[u.width,u.height],sizeUnits:i[r],sizeScale:t,sizeBasis:"height"===n?1:0,sizeMinPixels:o,sizeMaxPixels:s,billboard:a,alphaCutoff:l};e.shaderInputs.setProps({icon:c}),e.draw(this.context.renderPass)}}_getModel(e=this.props.id){return new xt(this.context.device,{...this.getShaders(),id:e,bufferLayout:this.getAttributeManager().getBufferLayouts(),geometry:new nt({topology:"triangle-strip",attributes:{positions:{size:2,value:new Float32Array([-1,-1,1,-1,-1,1,1,1])}}}),isInstanced:!0})}_onUpdate(e){e?(this.getAttributeManager()?.invalidate("getIcon"),this.setNeedsUpdate()):this.setNeedsRedraw()}_onError(e){const t=this.getCurrentLayer()?.props.onIconError;t?t(e):I.error(e.error.message)()}getInstanceIconDef(e){const{x:t,y:n,width:i,height:o,mask:s,anchorX:r=i/2,anchorY:a=o/2}=this.state.iconManager.getIconMapping(e);return[i/2-r,o/2-a,t,n,i,o,s?1:0]}};Uo.defaultProps=jo,Uo.layerName="IconLayer";var Go="layout(std140) uniform lineUniforms {\n float widthScale;\n float widthMinPixels;\n float widthMaxPixels;\n float useShortestPath;\n highp int widthUnits;\n} line;\n",Vo={name:"line",source:"",vs:Go,fs:Go,uniformTypes:{widthScale:"f32",widthMinPixels:"f32",widthMaxPixels:"f32",useShortestPath:"f32",widthUnits:"i32"}},$o={getSourcePosition:{type:"accessor",value:e=>e.sourcePosition},getTargetPosition:{type:"accessor",value:e=>e.targetPosition},getColor:{type:"accessor",value:[0,0,0,255]},getWidth:{type:"accessor",value:1},widthUnits:"pixels",widthScale:{type:"number",value:1,min:0},widthMinPixels:{type:"number",value:0,min:0},widthMaxPixels:{type:"number",value:Number.MAX_SAFE_INTEGER,min:0},antialiasing:!1},Wo=class extends co{getBounds(){return this.getAttributeManager()?.getBounds(["instanceSourcePositions","instanceTargetPositions"])}getShaders(){const{antialiasing:e}=this.props;return super.getShaders({vs:"#version 300 es\n#define SHADER_NAME line-layer-vertex-shader\nin vec3 positions;\nin vec3 instanceSourcePositions;\nin vec3 instanceTargetPositions;\nin vec3 instanceSourcePositions64Low;\nin vec3 instanceTargetPositions64Low;\nin vec4 instanceColors;\nin float instanceWidths;\nout vec4 vColor;\nout vec2 uv;\nvec2 getExtrusionOffset(vec2 line_clipspace, float offset_direction, float width) {\nvec2 dir_screenspace = normalize(line_clipspace * project.viewportSize);\ndir_screenspace = vec2(-dir_screenspace.y, dir_screenspace.x);\nreturn dir_screenspace * offset_direction * width / 2.0;\n}\nvec3 splitLine(vec3 a, vec3 b, float x) {\nfloat t = (x - a.x) / (b.x - a.x);\nreturn vec3(x, mix(a.yz, b.yz, t));\n}\nvoid main(void) {\ngeometry.worldPosition = instanceSourcePositions;\ngeometry.worldPositionAlt = instanceTargetPositions;\nvec3 source_world = instanceSourcePositions;\nvec3 target_world = instanceTargetPositions;\nvec3 source_world_64low = instanceSourcePositions64Low;\nvec3 target_world_64low = instanceTargetPositions64Low;\nif (line.useShortestPath > 0.5 || line.useShortestPath < -0.5) {\nsource_world.x = mod(source_world.x + 180., 360.0) - 180.;\ntarget_world.x = mod(target_world.x + 180., 360.0) - 180.;\nfloat deltaLng = target_world.x - source_world.x;\nif (deltaLng * line.useShortestPath > 180.) {\nsource_world.x += 360. * line.useShortestPath;\nsource_world = splitLine(source_world, target_world, 180. * line.useShortestPath);\nsource_world_64low = vec3(0.0);\n} else if (deltaLng * line.useShortestPath < -180.) {\ntarget_world.x += 360. * line.useShortestPath;\ntarget_world = splitLine(source_world, target_world, 180. * line.useShortestPath);\ntarget_world_64low = vec3(0.0);\n} else if (line.useShortestPath < 0.) {\ngl_Position = vec4(0.);\nreturn;\n}\n}\nvec4 source_commonspace;\nvec4 target_commonspace;\nvec4 source = project_position_to_clipspace(source_world, source_world_64low, vec3(0.), source_commonspace);\nvec4 target = project_position_to_clipspace(target_world, target_world_64low, vec3(0.), target_commonspace);\nfloat segmentIndex = positions.x;\nvec4 p = mix(source, target, segmentIndex);\ngeometry.position = mix(source_commonspace, target_commonspace, segmentIndex);\nuv = positions.xy;\ngeometry.uv = uv;\ngeometry.pickingColor = picking_getPickingColorFromInstanceID();\nfloat widthPixels = clamp(\nproject_size_to_pixel(instanceWidths * line.widthScale, line.widthUnits),\nline.widthMinPixels, line.widthMaxPixels\n);\nvec3 offset = vec3(\ngetExtrusionOffset(target.xy - source.xy, positions.y, widthPixels),\n0.0);\nDECKGL_FILTER_SIZE(offset, geometry);\n#ifdef ANTIALIASING\nfloat halfWidthPixels = length(offset.xy);\nif (halfWidthPixels > 0.0) {\nfloat coverageScale = 1.0 + 0.5 / project.devicePixelRatio / halfWidthPixels;\noffset.xy *= coverageScale;\nuv.y *= coverageScale;\n}\ngeometry.uv = uv;\n#endif\nDECKGL_FILTER_GL_POSITION(p, geometry);\ngl_Position = p + vec4(project_pixel_size_to_clipspace(offset.xy), 0.0, 0.0);\nvColor = vec4(instanceColors.rgb, instanceColors.a * layer.opacity);\nDECKGL_FILTER_COLOR(vColor, geometry);\n}\n",fs:"#version 300 es\n#define SHADER_NAME line-layer-fragment-shader\nprecision highp float;\nin vec4 vColor;\nin vec2 uv;\nout vec4 fragColor;\nvoid main(void) {\ngeometry.uv = uv;\nfragColor = vColor;\n#ifdef ANTIALIASING\nfloat edgeCoord = abs(uv.y);\nfloat edgePixels = (1.0 - edgeCoord) / max(fwidth(edgeCoord), 1e-6);\nif (edgePixels <= -SMOOTH_EDGE_RADIUS) {\ndiscard;\n}\nfragColor.a *= smoothedge(0.0, edgePixels);\n#endif\nDECKGL_FILTER_COLOR(fragColor, geometry);\n}\n",source:'// ---------- Helper Structures & Functions ----------\n\n// Placeholder filter functions.\nfn deckgl_filter_size(offset: vec3<f32>, geometry: Geometry) -> vec3<f32> {\n return offset;\n}\nfn deckgl_filter_gl_position(p: vec4<f32>, geometry: Geometry) -> vec4<f32> {\n if (picking.isAttribute > 0.5) {\n // For depth picking, write normalized depth into the picking payload.\n // This mirrors the legacy DECKGL_FILTER_GL_POSITION hook on WebGL.\n }\n return p;\n}\n\n// Compute an extrusion offset given a line direction (in clipspace),\n// an offset direction (-1 or 1), and a width in pixels.\n// Assumes a uniform "project" with a viewportSize field is available.\nfn getExtrusionOffset(line_clipspace: vec2<f32>, offset_direction: f32, width: f32) -> vec2<f32> {\n // project.viewportSize should be provided as a uniform (not shown here)\n let dir_screenspace = normalize(line_clipspace * project.viewportSize);\n // Rotate by 90°: (x,y) becomes (-y,x)\n let rotated = vec2<f32>(-dir_screenspace.y, dir_screenspace.x);\n return rotated * offset_direction * width / 2.0;\n}\n\n// Splits the line between two points at a given x coordinate.\n// Interpolates the y and z components.\nfn splitLine(a: vec3<f32>, b: vec3<f32>, x: f32) -> vec3<f32> {\n let t: f32 = (x - a.x) / (b.x - a.x);\n return vec3<f32>(x, a.yz + t * (b.yz - a.yz));\n}\n\n// ---------- Uniforms & Global Structures ----------\n\nstruct LineUniforms {\n widthScale: f32,\n widthMinPixels: f32,\n widthMaxPixels: f32,\n useShortestPath: f32,\n widthUnits: i32,\n};\n\n@group(0) @binding(0)\nvar<uniform> line: LineUniforms;\n\n\n\n// ---------- Vertex Output Structure ----------\n\nstruct Varyings {\n @builtin(position) gl_Position: vec4<f32>,\n @location(0) vColor: vec4<f32>,\n @location(1) uv: vec2<f32>,\n @location(2) pickingColor: vec3<f32>,\n};\n\n// ---------- Vertex Shader Entry Point ----------\n\n@vertex\nfn vertexMain(\n @builtin(instance_index) instanceIndex: u32,\n @location(0) positions: vec3<f32>,\n @location(1) instanceSourcePositions: vec3<f32>,\n @location(2) instanceTargetPositions: vec3<f32>,\n @location(3) instanceSourcePositions64Low: vec3<f32>,\n @location(4) instanceTargetPositions64Low: vec3<f32>,\n @location(5) instanceColors: vec4<f32>,\n @location(6) instanceWidths: f32\n) -> Varyings {\n geometry.worldPosition = instanceSourcePositions;\n geometry.worldPositionAlt = instanceTargetPositions;\n\n var source_world: vec3<f32> = instanceSourcePositions;\n var target_world: vec3<f32> = instanceTargetPositions;\n var source_world_64low: vec3<f32> = instanceSourcePositions64Low;\n var target_world_64low: vec3<f32> = instanceTargetPositions64Low;\n\n // Apply shortest-path adjustments if needed.\n if (line.useShortestPath > 0.5 || line.useShortestPath < -0.5) {\n source_world.x = (source_world.x + 180.0 % 360.0) - 180.0;\n target_world.x = (target_world.x + 180.0 % 360.0) - 180.0;\n let deltaLng: f32 = target_world.x - source_world.x;\n\n if (deltaLng * line.useShortestPath > 180.0) {\n source_world.x = source_world.x + 360.0 * line.useShortestPath;\n source_world = splitLine(source_world, target_world, 180.0 * line.useShortestPath);\n source_world_64low = vec3<f32>(0.0, 0.0, 0.0);\n } else if (deltaLng * line.useShortestPath < -180.0) {\n target_world.x = target_world.x + 360.0 * line.useShortestPath;\n target_world = splitLine(source_world, target_world, 180.0 * line.useShortestPath);\n target_world_64low = vec3<f32>(0.0, 0.0, 0.0);\n } else if (line.useShortestPath < 0.0) {\n var abortOut: Varyings;\n abortOut.gl_Position = vec4<f32>(0.0);\n abortOut.vColor = vec4<f32>(0.0);\n abortOut.uv = vec2<f32>(0.0);\n return abortOut;\n }\n }\n\n // Project Pos and target positions to clip space.\n let sourceResult = project_position_to_clipspace_and_commonspace(source_world, source_world_64low, vec3<f32>(0.0));\n let targetResult = project_position_to_clipspace_and_commonspace(target_world, target_world_64low, vec3<f32>(0.0));\n let sourcePos: vec4<f32> = sourceResult.clipPosition;\n let targetPos: vec4<f32> = targetResult.clipPosition;\n let source_commonspace: vec4<f32> = sourceResult.commonPosition;\n let target_commonspace: vec4<f32> = targetResult.commonPosition;\n\n // Interpolate along the line segment.\n let segmentIndex: f32 = positions.x;\n let p: vec4<f32> = sourcePos + segmentIndex * (targetPos - sourcePos);\n geometry.position = source_commonspace + segmentIndex * (target_commonspace - source_commonspace);\n#ifdef ANTIALIASING\n var uv: vec2<f32> = positions.xy;\n#else\n let uv: vec2<f32> = positions.xy;\n#endif\n geometry.uv = uv;\n geometry.pickingColor = picking_getPickingColorFromIndex(instanceIndex);\n\n // Determine width in pixels.\n let widthPixels: f32 = clamp(\n project_unit_size_to_pixel(instanceWidths * line.widthScale, line.widthUnits),\n line.widthMinPixels, line.widthMaxPixels\n );\n\n // Compute extrusion offset.\n let extrusion: vec2<f32> = getExtrusionOffset(targetPos.xy - sourcePos.xy, positions.y, widthPixels);\n let offset: vec3<f32> = vec3<f32>(extrusion, 0.0);\n\n // Apply deck.gl filter functions.\n#ifdef ANTIALIASING\n var filteredOffset = deckgl_filter_size(offset, geometry);\n let halfWidthPixels = length(filteredOffset.xy);\n if (halfWidthPixels > 0.0) {\n // Keep the declared edge at abs(uv.y) == 1 while rasterizing the outer half of the centered\n // one-device-pixel coverage ramp.\n let coverageScale = 1.0 + 0.5 / project.devicePixelRatio / halfWidthPixels;\n filteredOffset *= coverageScale;\n uv.y *= coverageScale;\n }\n geometry.uv = uv;\n#else\n let filteredOffset = deckgl_filter_size(offset, geometry);\n#endif\n let filteredP = deckgl_filter_gl_position(p, geometry);\n\n let clipOffset: vec2<f32> = project_pixel_size_to_clipspace(filteredOffset.xy);\n let finalPosition: vec4<f32> = filteredP + vec4<f32>(clipOffset, 0.0, 0.0);\n\n // Compute color.\n var vColor: vec4<f32> = vec4<f32>(instanceColors.rgb, instanceColors.a * layer.opacity);\n // vColor = deckgl_filter_color(vColor, geometry);\n\n var output: Varyings;\n output.gl_Position = finalPosition;\n output.vColor = vColor;\n output.uv = uv;\n output.pickingColor = geometry.pickingColor;\n return output;\n}\n\n@fragment\nfn fragmentMain(\n @location(0) vColor: vec4<f32>,\n @location(1) uv: vec2<f32>,\n @location(2) pickingColor: vec3<f32>\n) -> @location(0) vec4<f32> {\n // Create and initialize geometry with the provided uv.\n var geometry: Geometry;\n geometry.uv = uv;\n\n // Start with the input color.\n var fragColor: vec4<f32> = vColor;\n\n#ifdef ANTIALIASING\n // Distance to the edge in device pixels, from the derivative of uv.y. Taken in uniform control\n // flow, ahead of the picking discard below\n let edgeCoord = abs(uv.y);\n let edgePixels = (1.0 - edgeCoord) / max(fwidth(edgeCoord), 1e-6);\n\n // Fragments outside the coverage ramp must not write depth or picking colors.\n if (edgePixels <= -SMOOTH_EDGE_RADIUS) {\n discard;\n }\n\n // Feather one device pixel across the width, before premultiplication below. The ends are left\n // hard - they abut neighbors\n fragColor.a *= smoothedge(0.0, edgePixels);\n#endif\n\n if (picking.isActive > 0.5) {\n if (!picking_isColorValid(pickingColor)) {\n discard;\n }\n return vec4<f32>(pickingColor, 1.0);\n }\n\n if (picking.isHighlightActive > 0.5) {\n let highlightedObjectColor = picking_normalizeColor(picking.highlightedObjectColor);\n if (picking_isColorZero(abs(pickingColor - highlightedObjectColor))) {\n let highLightAlpha = picking.highlightColor.a;\n let blendedAlpha = highLightAlpha + fragColor.a * (1.0 - highLightAlpha);\n if (blendedAlpha > 0.0) {\n let highLightRatio = highLightAlpha / blendedAlpha;\n fragColor = vec4<f32>(\n mix(fragColor.rgb, picking.highlightColor.rgb, highLightRatio),\n blendedAlpha\n );\n } else {\n fragColor = vec4<f32>(fragColor.rgb, 0.0);\n }\n }\n }\n\n // Apply premultiplied alpha as required by transparent canvas\n fragColor = deckgl_premultiplied_alpha(fragColor);\n\n return fragColor;\n}\n',defines:e?{ANTIALIASING:1}:{},modules:[Ye,Ze,Je,Vo]})}get wrapLongitude(){return!1}initializeState(){this.getAttributeManager().addInstanced({instanceSourcePositions:{size:3,type:"float64",fp64:this.use64bitPositions(),transition:!0,accessor:"getSourcePosition"},instanceTargetPositions:{size:3,type:"float64",fp64:this.use64bitPositions(),transition:!0,accessor:"getTargetPosition"},instanceColors:{size:this.props.colorFormat.length,type:"unorm8",transition:!0,accessor:"getColor",defaultValue:[0,0,0,255]},instanceWidths:{size:1,transition:!0,accessor:"getWidth",defaultValue:1}})}updateState(e){super.updateState(e);const{props:t,oldProps:n,changeFlags:i}=e;(i.extensionsChanged||t.antialiasing!==n.antialiasing)&&(this.state.model?.destroy(),this.state.model=this._getModel(),this.getAttributeManager().invalidateAll())}draw({uniforms:e}){const{widthUnits:t,widthScale:n,widthMinPixels:o,widthMaxPixels:s,wrapLongitude:r}=this.props,a=this.state.model,l={widthUnits:i[t],widthScale:n,widthMinPixels:o,widthMaxPixels:s,useShortestPath:r?1:0};a.shaderInputs.setProps({line:l}),a.draw(this.context.renderPass),r&&(a.shaderInputs.setProps({line:{...l,useShortestPath:-1}}),a.draw(this.context.renderPass))}_getModel(){return new xt(this.context.device,{...this.getShaders(),id:this.props.id,bufferLayout:this.getAttributeManager().getBufferLayouts(),geometry:new nt({topology:"triangle-strip",attributes:{positions:{size:3,value:new Float32Array([0,-1,0,0,1,0,1,-1,0,1,1,0])}}}),isInstanced:!0})}};Wo.layerName="LineLayer",Wo.defaultProps=$o;var Ho="layout(std140) uniform pointCloudUniforms {\n float radiusPixels;\n highp int sizeUnits;\n} pointCloud;\n",Zo={name:"pointCloud",source:"",vs:Ho,fs:Ho,uniformTypes:{radiusPixels:"f32",sizeUnits:"i32"}},Yo=[0,0,0,255],qo=[0,0,1],Ko={sizeUnits:"pixels",pointSize:{type:"number",min:0,value:10},antialiasing:!1,getPosition:{type:"accessor",value:e=>e.position},getNormal:{type:"accessor",value:qo},getColor:{type:"accessor",value:Yo},material:!0,radiusPixels:{deprecatedFor:"pointSize"}};var Xo=class extends co{getShaders(){const{antialiasing:e}=this.props;return super.getShaders({vs:"#version 300 es\n#define SHADER_NAME point-cloud-layer-vertex-shader\nin vec3 positions;\nin vec3 instanceNormals;\nin vec4 instanceColors;\nin vec3 instancePositions;\nin vec3 instancePositions64Low;\nout vec4 vColor;\nout vec2 unitPosition;\nvoid main(void) {\ngeometry.worldPosition = instancePositions;\ngeometry.normal = project_normal(instanceNormals);\nunitPosition = positions.xy;\ngeometry.uv = unitPosition;\ngeometry.pickingColor = picking_getPickingColorFromInstanceID();\nvec3 offset = vec3(positions.xy * project_size_to_pixel(pointCloud.radiusPixels, pointCloud.sizeUnits), 0.0);\nDECKGL_FILTER_SIZE(offset, geometry);\n#ifdef ANTIALIASING\nfloat triangleRadiusPixels = length(offset.xy);\nif (triangleRadiusPixels > 0.0) {\nfloat coverageScale = 1.0 + 1.0 / project.devicePixelRatio / triangleRadiusPixels;\noffset.xy *= coverageScale;\nunitPosition *= coverageScale;\ngeometry.uv = unitPosition;\n}\n#endif\ngl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.), geometry.position);\nDECKGL_FILTER_GL_POSITION(gl_Position, geometry);\ngl_Position.xy += project_pixel_size_to_clipspace(offset.xy);\nvec3 lightColor = lighting_getLightColor(instanceColors.rgb, project.cameraPosition, geometry.position.xyz, geometry.normal);\nvColor = vec4(lightColor, instanceColors.a * layer.opacity);\nDECKGL_FILTER_COLOR(vColor, geometry);\n}\n",fs:"#version 300 es\n#define SHADER_NAME point-cloud-layer-fragment-shader\nprecision highp float;\nin vec4 vColor;\nin vec2 unitPosition;\nout vec4 fragColor;\nvoid main(void) {\ngeometry.uv = unitPosition.xy;\nfloat distToCenter = length(unitPosition);\n#ifdef ANTIALIASING\nfloat edgePixels = (1.0 - distToCenter) / max(fwidth(distToCenter), 1e-6);\nif (edgePixels <= -SMOOTH_EDGE_RADIUS) {\n#else\nif (distToCenter > 1.0) {\n#endif\ndiscard;\n}\nfragColor = vColor;\n#ifdef ANTIALIASING\nfragColor.a *= smoothedge(0.0, edgePixels);\n#endif\nDECKGL_FILTER_COLOR(fragColor, geometry);\n}\n",source:"struct PointCloudUniforms {\n radiusPixels: f32,\n sizeUnits: i32,\n};\n\n@group(0) @binding(0)\nvar<uniform> pointCloudUniforms: PointCloudUniforms;\n\nstruct Attributes {\n @builtin(instance_index) instanceIndex : u32,\n @builtin(vertex_index) vertexIndex : u32,\n @location(0) positions: vec3<f32>,\n @location(1) instancePositions: vec3<f32>,\n @location(2) instancePositions64Low: vec3<f32>,\n @location(3) instanceNormals: vec3<f32>,\n @location(4) instanceColors: vec4<f32>\n};\n\nstruct Varyings {\n @builtin(position) position: vec4<f32>,\n @location(0) vColor: vec4<f32>,\n @location(1) unitPosition: vec2<f32>,\n @location(2) pickingColor: vec3<f32>,\n};\n\n@vertex\nfn vertexMain(attributes: Attributes) -> Varyings {\n var varyings: Varyings;\n\n geometry.worldPosition = attributes.instancePositions;\n\n let centerResult = project_position_to_clipspace_and_commonspace(\n attributes.instancePositions,\n attributes.instancePositions64Low,\n vec3<f32>(0.0)\n );\n geometry.position = centerResult.commonPosition;\n geometry.normal = project_normal(attributes.instanceNormals);\n\n // Position on the enclosing triangle. Its edges are tangent to the unit circle.\n varyings.unitPosition = attributes.positions.xy;\n geometry.uv = varyings.unitPosition;\n geometry.pickingColor = picking_getPickingColorFromIndex(attributes.instanceIndex);\n\n // Find the center of the point and add the current vertex\n#ifdef ANTIALIASING\n var offset = vec3<f32>(\n#else\n let offset = vec3<f32>(\n#endif\n attributes.positions.xy *\n project_unit_size_to_pixel(pointCloudUniforms.radiusPixels, pointCloudUniforms.sizeUnits),\n 0.0\n );\n // DECKGL_FILTER_SIZE(offset, geometry);\n#ifdef ANTIALIASING\n let triangleRadiusPixels = length(offset.xy);\n if (triangleRadiusPixels > 0.0) {\n // The triangle's inradius is half its vertex radius. Scaling its vertex radius by one device\n // pixel therefore adds half a device pixel around all three tangent points.\n let coverageScale = 1.0 + 1.0 / project.devicePixelRatio / triangleRadiusPixels;\n offset *= coverageScale;\n varyings.unitPosition *= coverageScale;\n geometry.uv = varyings.unitPosition;\n }\n#endif\n\n varyings.position = centerResult.clipPosition;\n // DECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n let clipPixels = project_pixel_size_to_clipspace(offset.xy);\n varyings.position.x += clipPixels.x;\n varyings.position.y += clipPixels.y;\n\n // Apply lighting\n let lightColor = lighting_getLightColor2(attributes.instanceColors.rgb, project.cameraPosition, geometry.position.xyz, geometry.normal);\n\n // Apply opacity to instance color, or return instance picking color\n varyings.vColor = vec4(lightColor, attributes.instanceColors.a * layer.opacity);\n // DECKGL_FILTER_COLOR(vColor, geometry);\n varyings.pickingColor = geometry.pickingColor;\n\n return varyings;\n}\n\n@fragment\nfn fragmentMain(varyings: Varyings) -> @location(0) vec4<f32> {\n // var geometry: Geometry;\n // geometry.uv = unitPosition.xy;\n\n let distToCenter = length(varyings.unitPosition);\n#ifdef ANTIALIASING\n let edgePixels = (1.0 - distToCenter) / max(fwidth(distToCenter), 1e-6);\n if (edgePixels <= -SMOOTH_EDGE_RADIUS) {\n#else\n if (distToCenter > 1.0) {\n#endif\n discard;\n }\n\n var fragColor: vec4<f32>;\n\n fragColor = varyings.vColor;\n\n#ifdef ANTIALIASING\n fragColor.a *= smoothedge(0.0, edgePixels);\n#endif\n\n if (picking.isActive > 0.5) {\n if (!picking_isColorValid(varyings.pickingColor)) {\n discard;\n }\n return vec4<f32>(varyings.pickingColor, 1.0);\n }\n\n if (picking.isHighlightActive > 0.5) {\n let highlightedObjectColor = picking_normalizeColor(picking.highlightedObjectColor);\n if (picking_isColorZero(abs(varyings.pickingColor - highlightedObjectColor))) {\n let highLightAlpha = picking.highlightColor.a;\n let blendedAlpha = highLightAlpha + fragColor.a * (1.0 - highLightAlpha);\n if (blendedAlpha > 0.0) {\n let highLightRatio = highLightAlpha / blendedAlpha;\n fragColor = vec4<f32>(\n mix(fragColor.rgb, picking.highlightColor.rgb, highLightRatio),\n blendedAlpha\n );\n } else {\n fragColor = vec4<f32>(fragColor.rgb, 0.0);\n }\n }\n }\n\n // Apply premultiplied alpha as required by transparent canvas\n fragColor = deckgl_premultiplied_alpha(fragColor);\n\n return fragColor;\n}\n",defines:e?{ANTIALIASING:1}:{},modules:[Ye,Ze,We,Je,Zo]})}initializeState(){this.getAttributeManager().addInstanced({instancePositions:{size:3,type:"float64",fp64:this.use64bitPositions(),transition:!0,accessor:"getPosition"},instanceNormals:{size:3,transition:!0,accessor:"getNormal",defaultValue:qo},instanceColors:{size:this.props.colorFormat.length,type:"unorm8",transition:!0,accessor:"getColor",defaultValue:Yo}})}updateState(e){const{changeFlags:t,props:n,oldProps:i}=e;super.updateState(e),(t.extensionsChanged||n.antialiasing!==i.antialiasing)&&(this.state.model?.destroy(),this.state.model=this._getModel(),this.getAttributeManager().invalidateAll()),t.dataChanged&&function(e){const{header:t,attributes:n}=e;if(t&&n&&(e.length=t.vertexCount,n.POSITION&&(n.instancePositions=n.POSITION),n.NORMAL&&(n.instanceNormals=n.NORMAL),n.COLOR_0)){const{size:e,value:t}=n.COLOR_0;n.instanceColors={size:e,type:"unorm8",value:t}}}(n.data)}draw({uniforms:e}){const{pointSize:t,sizeUnits:n}=this.props,o=this.state.model,s={sizeUnits:i[n],radiusPixels:t};o.shaderInputs.setProps({pointCloud:s}),o.draw(this.context.renderPass)}_getModel(){const e=[];for(let t=0;t<3;t++){const n=t/3*Math.PI*2;e.push(2*Math.cos(n),2*Math.sin(n),0)}return new xt(this.context.device,{...this.getShaders(),id:this.props.id,bufferLayout:this.getAttributeManager().getBufferLayouts(),geometry:new nt({topology:"triangle-list",attributes:{positions:new Float32Array(e)}}),isInstanced:!0})}};Xo.layerName="PointCloudLayer",Xo.defaultProps=Ko;var Jo="layout(std140) uniform scatterplotUniforms {\n float radiusScale;\n float radiusMinPixels;\n float radiusMaxPixels;\n float lineWidthScale;\n float lineWidthMinPixels;\n float lineWidthMaxPixels;\n float stroked;\n float filled;\n bool antialiasing;\n bool billboard;\n highp int radiusUnits;\n highp int lineWidthUnits;\n} scatterplot;\n",Qo={name:"scatterplot",vs:Jo,fs:Jo,source:"",uniformTypes:{radiusScale:"f32",radiusMinPixels:"f32",radiusMaxPixels:"f32",lineWidthScale:"f32",lineWidthMinPixels:"f32",lineWidthMaxPixels:"f32",stroked:"f32",filled:"f32",antialiasing:"f32",billboard:"f32",radiusUnits:"i32",lineWidthUnits:"i32"}},es="// Main shaders\n\nstruct ScatterplotUniforms {\n radiusScale: f32,\n radiusMinPixels: f32,\n radiusMaxPixels: f32,\n lineWidthScale: f32,\n lineWidthMinPixels: f32,\n lineWidthMaxPixels: f32,\n stroked: f32,\n filled: i32,\n antialiasing: i32,\n billboard: i32,\n radiusUnits: i32,\n lineWidthUnits: i32,\n};\n\n@group(0) @binding(0) var<uniform> scatterplot: ScatterplotUniforms;\n\nstruct Attributes {\n @builtin(instance_index) instanceIndex : u32,\n @builtin(vertex_index) vertexIndex : u32,\n @location(0) positions: vec3<f32>,\n @location(1) instancePositions: vec3<f32>,\n @location(2) instancePositions64Low: vec3<f32>,\n @location(3) instanceRadius: f32,\n @location(4) instanceLineWidths: f32,\n @location(5) instanceFillColors: vec4<f32>,\n @location(6) instanceLineColors: vec4<f32>,\n @location(7) instancePixelOffset: vec2<f32>,\n PICKING_COLOR_ATTRIBUTE\n};\n\nstruct Varyings {\n @builtin(position) position: vec4<f32>,\n @location(0) vFillColor: vec4<f32>,\n @location(1) vLineColor: vec4<f32>,\n @location(2) unitPosition: vec2<f32>,\n @location(3) innerUnitRadius: f32,\n @location(4) outerRadiusPixels: f32,\n @location(5) pickingColor: vec3<f32>,\n @location(6) clipCoordinates: vec2<f32>,\n};\n\n@vertex\nfn vertexMain(attributes: Attributes) -> Varyings {\n var varyings: Varyings;\n\n // Draw an inline geometry constant array clip space triangle to verify that rendering works.\n // var positions = array<vec2<f32>, 3>(vec2(0.0, 0.5), vec2(-0.5, -0.5), vec2(0.5, -0.5));\n // if (attributes.instanceIndex == 0) {\n // varyings.position = vec4<f32>(positions[attributes.vertexIndex], 0.0, 1.0);\n // return varyings;\n // }\n\n geometry.worldPosition = attributes.instancePositions;\n\n // Multiply out radius and clamp to limits\n varyings.outerRadiusPixels = clamp(\n project_unit_size_to_pixel(scatterplot.radiusScale * attributes.instanceRadius, scatterplot.radiusUnits),\n scatterplot.radiusMinPixels, scatterplot.radiusMaxPixels\n );\n\n // Multiply out line width and clamp to limits\n let lineWidthPixels = clamp(\n project_unit_size_to_pixel(scatterplot.lineWidthScale * attributes.instanceLineWidths, scatterplot.lineWidthUnits),\n scatterplot.lineWidthMinPixels, scatterplot.lineWidthMaxPixels\n );\n\n // outer radius needs to offset by half stroke width\n varyings.outerRadiusPixels += scatterplot.stroked * lineWidthPixels / 2.0;\n // Expand geometry to accommodate edge smoothing\n // WGSL selects the second value when the condition is true, so keep the antialiased path second.\n let edgePadding = select(\n 1.0,\n (varyings.outerRadiusPixels + SMOOTH_EDGE_RADIUS) / varyings.outerRadiusPixels,\n scatterplot.antialiasing != 0\n );\n\n // position on the containing square in [-1, 1] space\n varyings.unitPosition = edgePadding * attributes.positions.xy;\n geometry.uv = varyings.unitPosition;\n geometry.pickingColor = PICKING_COLOR_VALUE;\n\n varyings.innerUnitRadius = 1.0 - scatterplot.stroked * lineWidthPixels / varyings.outerRadiusPixels;\n\n if (scatterplot.billboard != 0) {\n let projectedPosition = project_position_to_clipspace_and_commonspace(\n attributes.instancePositions,\n attributes.instancePositions64Low,\n vec3<f32>(0.0)\n );\n geometry.position = projectedPosition.commonPosition;\n varyings.position = projectedPosition.clipPosition;\n // DECKGL_FILTER_GL_POSITION(varyings.position, geometry);\n var offset = edgePadding * attributes.positions * varyings.outerRadiusPixels;\n offset = vec3<f32>(offset.xy + attributes.instancePixelOffset, offset.z);\n // DECKGL_FILTER_SIZE(offset, geometry);\n let clipPixels = project_pixel_size_to_clipspace(offset.xy);\n varyings.position = vec4<f32>(varyings.position.x + clipPixels.x, varyings.position.y + clipPixels.y, varyings.position.z, varyings.position.w);\n geometry.position = vec4<f32>(\n geometry.position.xy + project_pixel_size_vec2(offset.xy),\n geometry.position.zw\n );\n } else {\n var offset = edgePadding * attributes.positions * project_pixel_size_float(varyings.outerRadiusPixels);\n offset = vec3<f32>(offset.xy + project_pixel_size_vec2(attributes.instancePixelOffset), offset.z);\n // DECKGL_FILTER_SIZE(offset, geometry);\n let projectedPosition = project_position_to_clipspace_and_commonspace(\n attributes.instancePositions,\n attributes.instancePositions64Low,\n offset\n );\n geometry.position = projectedPosition.commonPosition;\n varyings.position = projectedPosition.clipPosition;\n // DECKGL_FILTER_GL_POSITION(varyings.position, geometry);\n }\n\n varyings.clipCoordinates = geometry.position.xy;\n clip_filterPosition(&varyings.position, geometry.worldPosition.xy);\n\n // Apply opacity to instance color, or return instance picking color\n varyings.vFillColor = vec4<f32>(attributes.instanceFillColors.rgb, attributes.instanceFillColors.a * layer.opacity);\n // DECKGL_FILTER_COLOR(varyings.vFillColor, geometry);\n varyings.vLineColor = vec4<f32>(attributes.instanceLineColors.rgb, attributes.instanceLineColors.a * layer.opacity);\n // DECKGL_FILTER_COLOR(varyings.vLineColor, geometry);\n varyings.pickingColor = geometry.pickingColor;\n\n return varyings;\n}\n\n@fragment\nfn fragmentMain(varyings: Varyings) -> @location(0) vec4<f32> {\n // var geometry: Geometry;\n // geometry.uv = unitPosition;\n\n let distToCenter = length(varyings.unitPosition) * varyings.outerRadiusPixels;\n let inCircle = select(\n step(distToCenter, varyings.outerRadiusPixels),\n smoothedge(distToCenter, varyings.outerRadiusPixels),\n scatterplot.antialiasing != 0\n );\n\n if (inCircle == 0.0) {\n discard;\n }\n\n var fragColor: vec4<f32>;\n\n if (scatterplot.stroked != 0) {\n let isLine = select(\n step(varyings.innerUnitRadius * varyings.outerRadiusPixels, distToCenter),\n smoothedge(varyings.innerUnitRadius * varyings.outerRadiusPixels, distToCenter),\n scatterplot.antialiasing != 0\n );\n\n if (scatterplot.filled != 0) {\n fragColor = mix(varyings.vFillColor, varyings.vLineColor, isLine);\n } else {\n if (isLine == 0.0) {\n discard;\n }\n fragColor = vec4<f32>(varyings.vLineColor.rgb, varyings.vLineColor.a * isLine);\n }\n } else if (scatterplot.filled == 0) {\n discard;\n } else {\n fragColor = varyings.vFillColor;\n }\n\n fragColor.a *= inCircle;\n\n clip_filterColor(varyings.clipCoordinates);\n\n if (picking.isActive > 0.5) {\n if (!picking_isColorValid(varyings.pickingColor)) {\n discard;\n }\n return vec4<f32>(varyings.pickingColor, 1.0);\n }\n\n if (picking.isHighlightActive > 0.5) {\n let highlightedObjectColor = picking_normalizeColor(picking.highlightedObjectColor);\n if (picking_isColorZero(abs(varyings.pickingColor - highlightedObjectColor))) {\n let highLightAlpha = picking.highlightColor.a;\n let blendedAlpha = highLightAlpha + fragColor.a * (1.0 - highLightAlpha);\n if (blendedAlpha > 0.0) {\n let highLightRatio = highLightAlpha / blendedAlpha;\n fragColor = vec4<f32>(\n mix(fragColor.rgb, picking.highlightColor.rgb, highLightRatio),\n blendedAlpha\n );\n } else {\n fragColor = vec4<f32>(fragColor.rgb, 0.0);\n }\n }\n }\n\n // Apply premultiplied alpha as required by transparent canvas\n fragColor = deckgl_premultiplied_alpha(fragColor);\n\n return fragColor;\n // return vec4<f32>(0, 0, 1, 1);\n}\n";function ts(e){return es.replace("PICKING_COLOR_ATTRIBUTE",e?"@location(8) rowIndexes: u32,":"").replace("PICKING_COLOR_VALUE",e?"picking_getPickingColorFromIndex(attributes.rowIndexes)":"picking_getPickingColorFromIndex(attributes.instanceIndex)")}var ns={name:"clip",source:"struct ClipUniforms {\n enabled: i32,\n mode: i32,\n bounds: vec4<f32>,\n};\n\n@group(2) @binding(auto) var<uniform> clipUniforms: ClipUniforms;\n\nfn clip_isInBounds(coordinates: vec2<f32>) -> bool {\n return coordinates.x >= clipUniforms.bounds.x &&\n coordinates.y >= clipUniforms.bounds.y &&\n coordinates.x < clipUniforms.bounds.z &&\n coordinates.y < clipUniforms.bounds.w;\n}\n\nfn clip_filterPosition(position: ptr<function, vec4<f32>>, instanceCoordinates: vec2<f32>) {\n if (\n clipUniforms.enabled != 0 &&\n clipUniforms.mode == 1 &&\n !clip_isInBounds(instanceCoordinates)\n ) {\n *position = vec4<f32>(2.0, 2.0, 2.0, 1.0);\n }\n}\n\nfn clip_filterColor(geometryCoordinates: vec2<f32>) {\n if (\n clipUniforms.enabled != 0 &&\n clipUniforms.mode == 0 &&\n !clip_isInBounds(geometryCoordinates)\n ) {\n discard;\n }\n}\n",props:{},uniforms:{},bindingLayout:[{name:"clip",group:2}],uniformTypes:{enabled:"i32",mode:"i32",bounds:"vec4<f32>"},defaultUniforms:{enabled:0,mode:0,bounds:[0,0,1,1]},getUniforms(e={}){const t={};return void 0!==e.enabled&&(t.enabled=e.enabled?1:0),void 0!==e.mode&&(t.mode="instance"===e.mode?1:0),void 0!==e.bounds&&(t.bounds=e.bounds),t}},is=[0,0,0,255],os={radiusUnits:"meters",radiusScale:{type:"number",min:0,value:1},radiusMinPixels:{type:"number",min:0,value:0},radiusMaxPixels:{type:"number",min:0,value:Number.MAX_SAFE_INTEGER},lineWidthUnits:"meters",lineWidthScale:{type:"number",min:0,value:1},lineWidthMinPixels:{type:"number",min:0,value:0},lineWidthMaxPixels:{type:"number",min:0,value:Number.MAX_SAFE_INTEGER},stroked:!1,filled:!0,billboard:!1,antialiasing:!0,getPosition:{type:"accessor",value:e=>e.position},getRadius:{type:"accessor",value:1},getFillColor:{type:"accessor",value:is},getLineColor:{type:"accessor",value:is},getLineWidth:{type:"accessor",value:1},getPixelOffset:{type:"accessor",value:[0,0]},strokeWidth:{deprecatedFor:"getLineWidth"},outline:{deprecatedFor:"stroked"},getColor:{deprecatedFor:["getFillColor","getLineColor"]}},ss=class extends co{getShaders(){const e=Boolean(this.props.data?.attributes?.rowIndexes);return super.getShaders({vs:"#version 300 es\n#define SHADER_NAME scatterplot-layer-vertex-shader\nin vec3 positions;\nin vec3 instancePositions;\nin vec3 instancePositions64Low;\nin float instanceRadius;\nin float instanceLineWidths;\nin vec4 instanceFillColors;\nin vec4 instanceLineColors;\n#ifdef USE_ROW_INDEXES\nin float rowIndexes;\n#endif\nin vec2 instancePixelOffset;\nout vec4 vFillColor;\nout vec4 vLineColor;\nout vec2 unitPosition;\nout float innerUnitRadius;\nout float outerRadiusPixels;\nvoid main(void) {\ngeometry.worldPosition = instancePositions;\nouterRadiusPixels = clamp(\nproject_size_to_pixel(scatterplot.radiusScale * instanceRadius, scatterplot.radiusUnits),\nscatterplot.radiusMinPixels, scatterplot.radiusMaxPixels\n);\nfloat lineWidthPixels = clamp(\nproject_size_to_pixel(scatterplot.lineWidthScale * instanceLineWidths, scatterplot.lineWidthUnits),\nscatterplot.lineWidthMinPixels, scatterplot.lineWidthMaxPixels\n);\nouterRadiusPixels += scatterplot.stroked * lineWidthPixels / 2.0;\nfloat edgePadding = scatterplot.antialiasing ? (outerRadiusPixels + SMOOTH_EDGE_RADIUS) / outerRadiusPixels : 1.0;\nunitPosition = edgePadding * positions.xy;\ngeometry.uv = unitPosition;\n#ifdef USE_ROW_INDEXES\ngeometry.pickingColor = picking_getPickingColorFromIndex(rowIndexes);\n#else\ngeometry.pickingColor = picking_getPickingColorFromInstanceID();\n#endif\ninnerUnitRadius = 1.0 - scatterplot.stroked * lineWidthPixels / outerRadiusPixels;\nif (scatterplot.billboard) {\ngl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.0), geometry.position);\nDECKGL_FILTER_GL_POSITION(gl_Position, geometry);\nvec3 offset = edgePadding * positions * outerRadiusPixels;\noffset.xy += instancePixelOffset;\nDECKGL_FILTER_SIZE(offset, geometry);\ngl_Position.xy += project_pixel_size_to_clipspace(offset.xy);\n} else {\nvec3 offset = edgePadding * positions * project_pixel_size(outerRadiusPixels);\noffset.xy += project_pixel_size(instancePixelOffset);\nDECKGL_FILTER_SIZE(offset, geometry);\ngl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, offset, geometry.position);\nDECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n}\nvFillColor = vec4(instanceFillColors.rgb, instanceFillColors.a * layer.opacity);\nDECKGL_FILTER_COLOR(vFillColor, geometry);\nvLineColor = vec4(instanceLineColors.rgb, instanceLineColors.a * layer.opacity);\nDECKGL_FILTER_COLOR(vLineColor, geometry);\n}\n",fs:"#version 300 es\n#define SHADER_NAME scatterplot-layer-fragment-shader\nprecision highp float;\nin vec4 vFillColor;\nin vec4 vLineColor;\nin vec2 unitPosition;\nin float innerUnitRadius;\nin float outerRadiusPixels;\nout vec4 fragColor;\nvoid main(void) {\ngeometry.uv = unitPosition;\nfloat distToCenter = length(unitPosition) * outerRadiusPixels;\nfloat inCircle = scatterplot.antialiasing ?\nsmoothedge(distToCenter, outerRadiusPixels) :\nstep(distToCenter, outerRadiusPixels);\nif (inCircle == 0.0) {\ndiscard;\n}\nif (scatterplot.stroked > 0.5) {\nfloat isLine = scatterplot.antialiasing ?\nsmoothedge(innerUnitRadius * outerRadiusPixels, distToCenter) :\nstep(innerUnitRadius * outerRadiusPixels, distToCenter);\nif (scatterplot.filled > 0.5) {\nfragColor = mix(vFillColor, vLineColor, isLine);\n} else {\nif (isLine == 0.0) {\ndiscard;\n}\nfragColor = vec4(vLineColor.rgb, vLineColor.a * isLine);\n}\n} else if (scatterplot.filled < 0.5) {\ndiscard;\n} else {\nfragColor = vFillColor;\n}\nfragColor.a *= inCircle;\nDECKGL_FILTER_COLOR(fragColor, geometry);\n}\n",source:ts(e),defines:e?{USE_ROW_INDEXES:!0}:{},modules:[Ye,Ze,Je,Qo,..."webgpu"===this.context.device.type?[ns]:[]]})}initializeState(){const e=this.props.data?.attributes?.rowIndexes?{rowIndexes:{size:1,type:"uint32",noAlloc:!0}}:{};this.getAttributeManager().addInstanced({instancePositions:{size:3,type:"float64",fp64:this.use64bitPositions(),transition:!0,accessor:"getPosition"},instanceRadius:{size:1,transition:!0,accessor:"getRadius",defaultValue:1,bufferGroup:"scatterplot-instance-data"},instanceFillColors:{size:this.props.colorFormat.length,transition:!0,type:"unorm8",accessor:"getFillColor",defaultValue:[0,0,0,255],bufferGroup:"scatterplot-instance-data"},instanceLineColors:{size:this.props.colorFormat.length,transition:!0,type:"unorm8",accessor:"getLineColor",defaultValue:[0,0,0,255],bufferGroup:"scatterplot-instance-data"},instanceLineWidths:{size:1,transition:!0,accessor:"getLineWidth",defaultValue:1,bufferGroup:"scatterplot-instance-data"},instancePixelOffset:{size:2,transition:!0,accessor:"getPixelOffset",bufferGroup:"scatterplot-instance-data"},...e})}updateState(e){super.updateState(e),e.changeFlags.extensionsChanged&&(this.state.model?.destroy(),this.state.model=this._getModel(),this.getAttributeManager().invalidateAll())}draw({uniforms:e}){const{radiusUnits:t,radiusScale:n,radiusMinPixels:o,radiusMaxPixels:s,stroked:r,filled:a,billboard:l,antialiasing:c,lineWidthUnits:u,lineWidthScale:f,lineWidthMinPixels:d,lineWidthMaxPixels:p}=this.props,g={stroked:r,filled:a,billboard:l,antialiasing:c,radiusUnits:i[t],radiusScale:n,radiusMinPixels:o,radiusMaxPixels:s,lineWidthUnits:i[u],lineWidthScale:f,lineWidthMinPixels:d,lineWidthMaxPixels:p},h=this.state.model;h.shaderInputs.setProps({scatterplot:g}),h.draw(this.context.renderPass)}_getModel(){return new xt(this.context.device,{...this.getShaders(),id:this.props.id,bufferLayout:this.getAttributeManager().getBufferLayouts(),geometry:new nt({topology:"triangle-strip",attributes:{positions:{size:3,value:new Float32Array([-1,-1,0,1,-1,0,-1,1,0,1,1,0])}}}),isInstanced:!0})}};ss.defaultProps=os,ss.layerName="ScatterplotLayer";var rs=1,as=-1;function ls(e,t,n={}){return function(e,t={}){return Math.sign(us(e,t))}(e,n)!==t&&(function(e,t){const{start:n=0,end:i=e.length,size:o=2}=t,s=(i-n)/o,r=Math.floor(s/2);for(let a=0;a<r;++a){const t=n+a*o,i=n+(s-1-a)*o;for(let n=0;n<o;++n){const o=e[t+n];e[t+n]=e[i+n],e[i+n]=o}}}(e,n),!0)}var cs={x:0,y:1,z:2};function us(e,t={}){const{start:n=0,end:i=e.length,plane:o="xy"}=t,s=t.size||2;let r=0;const a=cs[o[0]],l=cs[o[1]];for(let c=n,u=i-s;c<i;c+=s)r+=(e[c+a]-e[u+a])*(e[c+l]+e[u+l]),u=c;return r/2}function fs(e,t){const n=t.length,i=e.length;if(i>0){let o=!0;for(let s=0;s<n;s++)if(e[i-n+s]!==t[s]){o=!1;break}if(o)return!1}for(let o=0;o<n;o++)e[i+o]=t[o];return!0}function ds(e,t){const n=t.length;for(let i=0;i<n;i++)e[i]=t[i]}function ps(e,t,n,i,o=[]){const s=i+t*n;for(let r=0;r<n;r++)o[r]=e[s+r];return o}function gs(e,t,n,i,o=[]){let s,r;if(8&n)s=(i[3]-e[1])/(t[1]-e[1]),r=3;else if(4&n)s=(i[1]-e[1])/(t[1]-e[1]),r=1;else if(2&n)s=(i[2]-e[0])/(t[0]-e[0]),r=2;else{if(!(1&n))return null;s=(i[0]-e[0])/(t[0]-e[0]),r=0}for(let a=0;a<e.length;a++)o[a]=(1&r)===a?i[r]:s*(t[a]-e[a])+e[a];return o}function hs(e,t){let n=0;return e[0]<t[0]?n|=1:e[0]>t[2]&&(n|=2),e[1]<t[1]?n|=4:e[1]>t[3]&&(n|=8),n}function vs(e,t){const{size:n=2,broken:i=!1,gridResolution:o=10,gridOffset:s=[0,0],startIndex:r=0,endIndex:a=e.length}=t||{},l=(a-r)/n;let c=[];const u=[c],f=ps(e,0,n,r);let d,p;const g=xs(f,o,s,[]),h=[];fs(c,f);for(let v=1;v<l;v++){for(d=ps(e,v,n,r,d),p=hs(d,g);p;){gs(f,d,p,g,h);const e=hs(h,g);e&&(gs(f,h,e,g,h),p=e),fs(c,h),ds(f,h),ys(g,o,p),i&&c.length>n&&(c=[],u.push(c),fs(c,f)),p=hs(d,g)}fs(c,d),ds(f,d)}return i?u:u[0]}function ms(e,t=null,n){if(!e.length)return[];const{size:i=2,gridResolution:o=10,gridOffset:s=[0,0],edgeTypes:r=!1}=n||{},a=[],l=[{pos:e,types:r?new Array(e.length/i).fill(1):null,holes:t||[]}],c=[[],[]];let u=[];for(;l.length;){const{pos:e,types:t,holes:n}=l.shift();bs(e,i,n[0]||e.length,c),u=xs(c[0],o,s,u);const f=hs(c[1],u);if(f){let o=_s(e,t,i,0,n[0]||e.length,u,f);const s={pos:o[0].pos,types:o[0].types,holes:[]},a={pos:o[1].pos,types:o[1].types,holes:[]};l.push(s,a);for(let l=0;l<n.length;l++)o=_s(e,t,i,n[l],n[l+1]||e.length,u,f),o[0]&&(s.holes.push(s.pos.length),s.pos=Ps(s.pos,o[0].pos),r&&(s.types=Ps(s.types,o[0].types))),o[1]&&(a.holes.push(a.pos.length),a.pos=Ps(a.pos,o[1].pos),r&&(a.types=Ps(a.types,o[1].types)))}else{const i={positions:e};r&&(i.edgeTypes=t),n.length&&(i.holeIndices=n),a.push(i)}}return a}function _s(e,t,n,i,o,s,r){const a=(o-i)/n,l=[],c=[],u=[],f=[],d=[];let p,g,h;const v=ps(e,a-1,n,i);let m=Math.sign(8&r?v[1]-s[3]:v[0]-s[2]),_=t&&t[a-1],x=0,y=0;for(let b=0;b<a;b++)p=ps(e,b,n,i,p),g=Math.sign(8&r?p[1]-s[3]:p[0]-s[2]),h=t&&t[i/n+b],g&&m&&m!==g&&(gs(v,p,r,s,d),fs(l,d)&&u.push(_),fs(c,d)&&f.push(_)),g<=0?(fs(l,p)&&u.push(h),x-=g):u.length&&(u[u.length-1]=0),g>=0?(fs(c,p)&&f.push(h),y+=g):f.length&&(f[f.length-1]=0),ds(v,p),m=g,_=h;return[x?{pos:l,types:t&&u}:null,y?{pos:c,types:t&&f}:null]}function xs(e,t,n,i){const o=Math.floor((e[0]-n[0])/t)*t+n[0],s=Math.floor((e[1]-n[1])/t)*t+n[1];return i[0]=o,i[1]=s,i[2]=o+t,i[3]=s+t,i}function ys(e,t,n){8&n?(e[1]+=t,e[3]+=t):4&n?(e[1]-=t,e[3]-=t):2&n?(e[0]+=t,e[2]+=t):1&n&&(e[0]-=t,e[2]-=t)}function bs(e,t,n,i){let o=1/0,s=-1/0,r=1/0,a=-1/0;for(let l=0;l<n;l+=t){const t=e[l],n=e[l+1];o=t<o?t:o,s=t>s?t:s,r=n<r?n:r,a=n>a?n:a}return i[0][0]=o,i[0][1]=r,i[1][0]=s,i[1][1]=a,i}function Ps(e,t){for(let n=0;n<t.length;n++)e.push(t[n]);return e}function Cs(e,t,n,i){let o=-1,s=-1;for(let r=n+1;r<i;r+=t){const t=Math.abs(e[r]);t>o&&(o=t,s=r-1)}return s}function ws(e,t,n,i,o=85.051129){const s=e[n],r=e[i-t];if(Math.abs(s-r)>180){const i=ps(e,0,t,n);i[0]+=360*Math.round((r-s)/360),fs(e,i),i[1]=Math.sign(i[1])*o,fs(e,i),i[0]=s,fs(e,i)}}function Ss(e,t,n,i){let o,s=e[0];for(let r=n;r<i;r+=t){o=e[r];const t=o-s;(t>180||t<-180)&&(o-=360*Math.round(t/360)),e[r]=s=o}}function Ls(e,t){let n;const i=e.length/t;for(let s=0;s<i&&(n=e[s*t],(n+180)%360==0);s++);const o=360*-Math.round(n/360);if(0!==o)for(let s=0;s<i;s++)e[s*t]+=o}var As=class extends nt{constructor(e){const{indices:t,attributes:n}=function(e){const{radius:t,height:n=1,nradial:i=10}=e;let{vertices:o}=e;o&&(I.assert(o.length>=i),o=o.flatMap(e=>[e[0],e[1]]),ls(o,as));const s=n>0,r=i+1,a=s?3*r+1:i,l=2*Math.PI/i,c=new Uint16Array(s?3*i*2:0),u=new Float32Array(3*a),f=new Float32Array(3*a);let d=0;if(s){for(let e=0;e<r;e++){const s=e*l,r=e%i,a=Math.sin(s),c=Math.cos(s);for(let e=0;e<2;e++)u[d+0]=o?o[2*r]:c*t,u[d+1]=o?o[2*r+1]:a*t,u[d+2]=(.5-e)*n,f[d+0]=o?o[2*r]:c,f[d+1]=o?o[2*r+1]:a,d+=3}u[d+0]=u[d-3],u[d+1]=u[d-2],u[d+2]=u[d-1],d+=3}for(let p=s?0:1;p<r;p++){const e=Math.floor(p/2)*Math.sign(.5-p%2),s=e*l,r=(e+i)%i,a=Math.sin(s),c=Math.cos(s);u[d+0]=o?o[2*r]:c*t,u[d+1]=o?o[2*r+1]:a*t,u[d+2]=n/2,f[d+2]=1,d+=3}if(s){let e=0;for(let t=0;t<i;t++)c[e++]=2*t+0,c[e++]=2*t+2,c[e++]=2*t+0,c[e++]=2*t+1,c[e++]=2*t+1,c[e++]=2*t+3}return{indices:c,attributes:{POSITION:{size:3,value:u},NORMAL:{size:3,value:f}}}}(e);super({...e,topology:"line-list",indices:t,attributes:n})}};var Is="layout(std140) uniform columnUniforms {\n float radius;\n float angle;\n vec2 offset;\n bool extruded;\n bool stroked;\n bool isStroke;\n float coverage;\n float elevationScale;\n float edgeDistance;\n float widthScale;\n float widthMinPixels;\n float widthMaxPixels;\n highp int radiusUnits;\n highp int widthUnits;\n} column;\n",Es={name:"column",source:"struct ColumnUniforms {\n radius: f32,\n angle: f32,\n offset: vec2<f32>,\n extruded: f32,\n stroked: f32,\n isStroke: f32,\n coverage: f32,\n elevationScale: f32,\n edgeDistance: f32,\n widthScale: f32,\n widthMinPixels: f32,\n widthMaxPixels: f32,\n radiusUnits: i32,\n widthUnits: i32,\n};\n\n@group(0) @binding(auto) var<uniform> column: ColumnUniforms;\n",vs:Is,fs:Is,uniformTypes:{radius:"f32",angle:"f32",offset:"vec2<f32>",extruded:"f32",stroked:"f32",isStroke:"f32",coverage:"f32",elevationScale:"f32",edgeDistance:"f32",widthScale:"f32",widthMinPixels:"f32",widthMaxPixels:"f32",radiusUnits:"i32",widthUnits:"i32"}},Ts="struct Attributes {\n @builtin(instance_index) instanceIndex: u32,\n @location(0) positions: vec3<f32>,\n @location(1) normals: vec3<f32>,\n @location(2) instancePositions: vec3<f32>,\n @location(3) instancePositions64Low: vec3<f32>,\n @location(4) instanceElevations: f32,\n @location(5) instanceFillColors: vec4<f32>,\n @location(6) instanceLineColors: vec4<f32>,\n @location(7) instanceStrokeWidths: f32\n};\n\nfn getRotationMatrix(angle: f32) -> mat2x2<f32> {\n let s = sin(angle);\n let c = cos(angle);\n return mat2x2<f32>(\n vec2<f32>(c, s),\n vec2<f32>(-s, c)\n );\n}\n\nfn getOffset(\n positions: vec3<f32>,\n strokeOffsetRatio: f32,\n dotRadius: f32,\n rotationMatrix: mat2x2<f32>\n) -> vec3<f32> {\n var offset = (rotationMatrix * positions.xy * strokeOffsetRatio + column.offset) * dotRadius;\n if (column.radiusUnits == UNIT_METERS) {\n offset = project_size_vec2(offset);\n } else if (column.radiusUnits == UNIT_PIXELS) {\n offset = project_pixel_size_vec2(offset);\n }\n return vec3<f32>(offset, 0.0);\n}\n",Os=`${Ts}\n\nstruct Varyings {\n @builtin(position) position: vec4<f32>,\n @location(0) color: vec4<f32>\n};\n\n@vertex\nfn vertexMain(attributes: Attributes) -> Varyings {\n var varyings: Varyings;\n\n geometry.worldPosition = attributes.instancePositions;\n geometry.pickingColor = picking_getPickingColorFromIndex(attributes.instanceIndex);\n\n let isStroke = column.isStroke > 0.5;\n let baseColor = select(attributes.instanceFillColors, attributes.instanceLineColors, isStroke);\n let rotationMatrix = getRotationMatrix(column.angle);\n\n var elevation = 0.0;\n var strokeOffsetRatio = 1.0;\n\n if (column.extruded > 0.5) {\n elevation =\n attributes.instanceElevations * (attributes.positions.z + 1.0) / 2.0 * column.elevationScale;\n } else if (column.stroked > 0.5) {\n let widthPixels = clamp(\n project_unit_size_to_pixel(attributes.instanceStrokeWidths * column.widthScale, column.widthUnits),\n column.widthMinPixels,\n column.widthMaxPixels\n ) / 2.0;\n let halfOffset =\n project_pixel_size_float(widthPixels) /\n project_size_float(column.edgeDistance * column.coverage * column.radius);\n if (isStroke) {\n strokeOffsetRatio -= sign(attributes.positions.z) * halfOffset;\n } else {\n strokeOffsetRatio -= halfOffset;\n }\n }\n\n let shouldRender = select(0.0, 1.0, baseColor.a > 0.0 && attributes.instanceElevations >= 0.0);\n let dotRadius = column.radius * column.coverage * shouldRender;\n let centroidPosition =\n vec3<f32>(\n attributes.instancePositions.xy,\n attributes.instancePositions.z + elevation\n );\n let offset = getOffset(attributes.positions, strokeOffsetRatio, dotRadius, rotationMatrix);\n let projected = project_position_to_clipspace_and_commonspace(\n centroidPosition,\n attributes.instancePositions64Low,\n offset\n );\n\n geometry.position = projected.commonPosition;\n geometry.normal = project_normal(vec3<f32>(rotationMatrix * attributes.normals.xy, attributes.normals.z));\n\n let lightColor = lighting_getLightColor2(\n baseColor.rgb,\n project.cameraPosition,\n geometry.position.xyz,\n geometry.normal\n );\n\n varyings.position = projected.clipPosition;\n varyings.color = vec4<f32>(\n select(baseColor.rgb, lightColor, column.extruded > 0.5 && !isStroke),\n baseColor.a * layer.opacity\n );\n\n return varyings;\n}\n\n@fragment\nfn fragmentMain(varyings: Varyings) -> @location(0) vec4<f32> {\n geometry.uv = vec2<f32>(0.0);\n return deckgl_premultiplied_alpha(varyings.color);\n}\n`,zs=`${Ts}\n\nstruct Varyings {\n @builtin(position) position: vec4<f32>,\n @location(0) color: vec4<f32>,\n @location(1) cameraPosition: vec3<f32>,\n @location(2) positionCommonspace: vec4<f32>\n};\n\n@vertex\nfn vertexMain(attributes: Attributes) -> Varyings {\n var varyings: Varyings;\n\n geometry.worldPosition = attributes.instancePositions;\n geometry.pickingColor = picking_getPickingColorFromIndex(attributes.instanceIndex);\n\n let isStroke = column.isStroke > 0.5;\n let baseColor = select(attributes.instanceFillColors, attributes.instanceLineColors, isStroke);\n let rotationMatrix = getRotationMatrix(column.angle);\n\n var elevation = 0.0;\n var strokeOffsetRatio = 1.0;\n\n if (column.extruded > 0.5) {\n elevation =\n attributes.instanceElevations * (attributes.positions.z + 1.0) / 2.0 * column.elevationScale;\n } else if (column.stroked > 0.5) {\n let widthPixels = clamp(\n project_unit_size_to_pixel(attributes.instanceStrokeWidths * column.widthScale, column.widthUnits),\n column.widthMinPixels,\n column.widthMaxPixels\n ) / 2.0;\n let halfOffset =\n project_pixel_size_float(widthPixels) /\n project_size_float(column.edgeDistance * column.coverage * column.radius);\n if (isStroke) {\n strokeOffsetRatio -= sign(attributes.positions.z) * halfOffset;\n } else {\n strokeOffsetRatio -= halfOffset;\n }\n }\n\n let shouldRender = select(0.0, 1.0, baseColor.a > 0.0 && attributes.instanceElevations >= 0.0);\n let dotRadius = column.radius * column.coverage * shouldRender;\n let centroidPosition =\n vec3<f32>(\n attributes.instancePositions.xy,\n attributes.instancePositions.z + elevation\n );\n let offset = getOffset(attributes.positions, strokeOffsetRatio, dotRadius, rotationMatrix);\n let projected = project_position_to_clipspace_and_commonspace(\n centroidPosition,\n attributes.instancePositions64Low,\n offset\n );\n\n geometry.position = projected.commonPosition;\n geometry.normal = project_normal(vec3<f32>(rotationMatrix * attributes.normals.xy, attributes.normals.z));\n\n varyings.position = projected.clipPosition;\n varyings.color = vec4<f32>(baseColor.rgb, baseColor.a * layer.opacity);\n varyings.cameraPosition = project.cameraPosition;\n varyings.positionCommonspace = projected.commonPosition;\n\n return varyings;\n}\n\n@fragment\nfn fragmentMain(varyings: Varyings) -> @location(0) vec4<f32> {\n geometry.uv = vec2<f32>(0.0);\n\n var fragColor = varyings.color;\n if (column.extruded > 0.5 && column.isStroke < 0.5) {\n // WebGPU's screen-space Y axis reverses the derivative orientation used by GLSL flat shading.\n let normal = normalize(cross(dpdy(varyings.positionCommonspace.xyz), dpdx(varyings.positionCommonspace.xyz)));\n fragColor = vec4<f32>(\n lighting_getLightColor2(\n varyings.color.rgb,\n varyings.cameraPosition,\n varyings.positionCommonspace.xyz,\n normal\n ),\n varyings.color.a\n );\n }\n\n return deckgl_premultiplied_alpha(fragColor);\n}\n`;function Ms(e){return e?zs:Os}var Rs=[0,0,0,255],Bs={name:"geometry",stepMode:"vertex",byteStride:24,attributes:[{attribute:"positions",format:"float32x3",byteOffset:0},{attribute:"normals",format:"float32x3",byteOffset:12}]},ks={diskResolution:{type:"number",min:4,value:20},vertices:null,radius:{type:"number",min:0,value:1e3},angle:{type:"number",value:0},offset:{type:"array",value:[0,0]},coverage:{type:"number",min:0,max:1,value:1},elevationScale:{type:"number",min:0,value:1},radiusUnits:"meters",lineWidthUnits:"meters",lineWidthScale:1,lineWidthMinPixels:0,lineWidthMaxPixels:Number.MAX_SAFE_INTEGER,extruded:!0,wireframe:!1,filled:!0,stroked:!1,flatShading:!1,getPosition:{type:"accessor",value:e=>e.position},getFillColor:{type:"accessor",value:Rs},getLineColor:{type:"accessor",value:Rs},getLineWidth:{type:"accessor",value:1},getElevation:{type:"accessor",value:1e3},material:!0,getColor:{deprecatedFor:["getFillColor","getLineColor"]}},Fs=class extends co{getShaders(){const e={},{flatShading:t}=this.props;return t&&(e.FLAT_SHADING=1),super.getShaders({vs:"#version 300 es\n#define SHADER_NAME column-layer-vertex-shader\nin vec3 positions;\nin vec3 normals;\nin vec3 instancePositions;\nin float instanceElevations;\nin vec3 instancePositions64Low;\nin vec4 instanceFillColors;\nin vec4 instanceLineColors;\nin float instanceStrokeWidths;\nout vec4 vColor;\n#ifdef FLAT_SHADING\nout vec3 cameraPosition;\nout vec4 position_commonspace;\n#endif\nvoid main(void) {\ngeometry.worldPosition = instancePositions;\nvec4 color = column.isStroke ? instanceLineColors : instanceFillColors;\nmat2 rotationMatrix = mat2(cos(column.angle), sin(column.angle), -sin(column.angle), cos(column.angle));\nfloat elevation = 0.0;\nfloat strokeOffsetRatio = 1.0;\nif (column.extruded) {\nelevation = instanceElevations * (positions.z + 1.0) / 2.0 * column.elevationScale;\n} else if (column.stroked) {\nfloat widthPixels = clamp(\nproject_size_to_pixel(instanceStrokeWidths * column.widthScale, column.widthUnits),\ncolumn.widthMinPixels, column.widthMaxPixels) / 2.0;\nfloat halfOffset = project_pixel_size(widthPixels) / project_size(column.edgeDistance * column.coverage * column.radius);\nif (column.isStroke) {\nstrokeOffsetRatio -= sign(positions.z) * halfOffset;\n} else {\nstrokeOffsetRatio -= halfOffset;\n}\n}\nfloat shouldRender = float(color.a > 0.0 && instanceElevations >= 0.0);\nfloat dotRadius = column.radius * column.coverage * shouldRender;\ngeometry.pickingColor = picking_getPickingColorFromInstanceID();\nvec3 centroidPosition = vec3(instancePositions.xy, instancePositions.z + elevation);\nvec3 centroidPosition64Low = instancePositions64Low;\nvec2 offset = (rotationMatrix * positions.xy * strokeOffsetRatio + column.offset) * dotRadius;\nif (column.radiusUnits == UNIT_METERS) {\noffset = project_size(offset);\n} else if (column.radiusUnits == UNIT_PIXELS) {\noffset = project_pixel_size(offset);\n}\nvec3 pos = vec3(offset, 0.);\nDECKGL_FILTER_SIZE(pos, geometry);\ngl_Position = project_position_to_clipspace(centroidPosition, centroidPosition64Low, pos, geometry.position);\ngeometry.normal = project_normal(vec3(rotationMatrix * normals.xy, normals.z));\nDECKGL_FILTER_GL_POSITION(gl_Position, geometry);\nif (column.extruded && !column.isStroke) {\n#ifdef FLAT_SHADING\ncameraPosition = project.cameraPosition;\nposition_commonspace = geometry.position;\nvColor = vec4(color.rgb, color.a * layer.opacity);\n#else\nvec3 lightColor = lighting_getLightColor(color.rgb, project.cameraPosition, geometry.position.xyz, geometry.normal);\nvColor = vec4(lightColor, color.a * layer.opacity);\n#endif\n} else {\nvColor = vec4(color.rgb, color.a * layer.opacity);\n}\nDECKGL_FILTER_COLOR(vColor, geometry);\n}\n",fs:"#version 300 es\n#define SHADER_NAME column-layer-fragment-shader\nprecision highp float;\nout vec4 fragColor;\nin vec4 vColor;\n#ifdef FLAT_SHADING\nin vec3 cameraPosition;\nin vec4 position_commonspace;\n#endif\nvoid main(void) {\nfragColor = vColor;\ngeometry.uv = vec2(0.);\n#ifdef FLAT_SHADING\nif (column.extruded && !column.isStroke && !bool(picking.isActive)) {\nvec3 normal = normalize(cross(dFdx(position_commonspace.xyz), dFdy(position_commonspace.xyz)));\nfragColor.rgb = lighting_getLightColor(vColor.rgb, cameraPosition, position_commonspace.xyz, normal);\n}\n#endif\nDECKGL_FILTER_COLOR(fragColor, geometry);\n}\n",source:Ms(t),defines:e,modules:[Ye,Ze,t?He:We,Je,Es]})}initializeState(){this.getAttributeManager().addInstanced({instancePositions:{size:3,type:"float64",fp64:this.use64bitPositions(),transition:!0,accessor:"getPosition"},instanceElevations:{size:1,transition:!0,accessor:"getElevation"},instanceFillColors:{size:this.props.colorFormat.length,type:"unorm8",transition:!0,accessor:"getFillColor",defaultValue:Rs},instanceLineColors:{size:this.props.colorFormat.length,type:"unorm8",transition:!0,accessor:"getLineColor",defaultValue:Rs},instanceStrokeWidths:{size:1,accessor:"getLineWidth",transition:!0}})}updateState(e){super.updateState(e);const{props:t,oldProps:n,changeFlags:i}=e,o=i.extensionsChanged||t.flatShading!==n.flatShading;o&&(this.state.models?.forEach(e=>e.destroy()),this.setState(this._getModels()),this.getAttributeManager().invalidateAll());const s=this.getNumInstances();this.state.fillModel.setInstanceCount(s),this.state.strokeModel.setInstanceCount(s),this.state.wireframeModel.setInstanceCount(s),(o||t.diskResolution!==n.diskResolution||t.vertices!==n.vertices||t.extruded!==n.extruded||t.stroked!==n.stroked)&&this._updateGeometry(t)}getGeometry(e,t,n){const i=new As({radius:1,height:n?2:0,vertices:t,nradial:e});let o=0;if(t)for(let s=0;s<e;s++){const n=t[s];o+=Math.sqrt(n[0]*n[0]+n[1]*n[1])/e}else o=1;return this.setState({edgeDistance:Math.cos(Math.PI/e)*o}),i}_getModels(){const e=this.getShaders(),t=[...this.getAttributeManager().getBufferLayouts(),Bs],n=new xt(this.context.device,{...e,id:`${this.props.id}-fill`,bufferLayout:t,isInstanced:!0}),i=new xt(this.context.device,{...e,id:`${this.props.id}-stroke`,bufferLayout:t,isInstanced:!0}),o=new xt(this.context.device,{...e,id:`${this.props.id}-wireframe`,bufferLayout:t,isInstanced:!0});return{fillModel:n,strokeModel:i,wireframeModel:o,models:[o,n,i]}}_updateGeometry({diskResolution:e,vertices:t,extruded:n,stroked:i}){const o=this.getGeometry(e,t,n||i),s=o.attributes.POSITION,r=o.attributes.NORMAL;if(this._setFillGeometry(new nt({topology:"triangle-strip",attributes:{POSITION:s,NORMAL:r}})),!n&&i){const t=s.value.length/3;this._setStrokeGeometry(new nt({topology:"triangle-strip",vertexCount:t-e-1,attributes:{POSITION:s,NORMAL:r}}))}n&&this._setWireframeGeometry(o)}_setFillGeometry(e){const t=ot(e,{attributes:["POSITION","NORMAL"]});this.state.fillModel.setGeometry(t)}_setStrokeGeometry(e){const t=ot(e,{attributes:["POSITION","NORMAL"]});this.state.strokeModel.setGeometry(t)}_setWireframeGeometry(e){const t=ot(e,{attributes:["POSITION","NORMAL"]}),n=this.state.wireframeModel;n.setGeometry(t),n.setTopology("line-list")}draw({uniforms:e}){const{lineWidthUnits:t,lineWidthScale:n,lineWidthMinPixels:o,lineWidthMaxPixels:s,radiusUnits:r,elevationScale:a,extruded:l,filled:c,stroked:u,wireframe:f,offset:d,coverage:p,radius:g,angle:h}=this.props,v=this.state.fillModel,m=this.state.strokeModel,_=this.state.wireframeModel,{edgeDistance:x}=this.state,y={radius:g,angle:h/180*Math.PI,offset:d,extruded:l,stroked:u,coverage:p,elevationScale:a,edgeDistance:x,radiusUnits:i[r],widthUnits:i[t],widthScale:n,widthMinPixels:o,widthMaxPixels:s};l&&f&&(_.shaderInputs.setProps({column:{...y,isStroke:!0}}),_.draw(this.context.renderPass)),c&&(v.shaderInputs.setProps({column:{...y,isStroke:!1}}),v.draw(this.context.renderPass)),!l&&u&&(m.shaderInputs.setProps({column:{...y,isStroke:!0}}),m.draw(this.context.renderPass))}};Fs.layerName="ColumnLayer",Fs.defaultProps=ks;var Ns=class extends Fs{_updateGeometry(){const e=new wt;this._setFillGeometry(e)}draw({uniforms:e}){const{elevationScale:t,extruded:n,offset:o,coverage:s,cellSize:r,angle:a,radiusUnits:l}=this.props,c=this.state.fillModel,u={radius:r/2,radiusUnits:i[l],angle:a,offset:o,extruded:n,stroked:!1,coverage:s,elevationScale:t,edgeDistance:1,isStroke:!1,widthUnits:0,widthScale:0,widthMinPixels:0,widthMaxPixels:0};c.shaderInputs.setProps({column:u}),c.draw(this.context.renderPass)}};function Ds(e,t,n,i){let o;if(Array.isArray(e[0])){const n=e.length*t;o=new Array(n);for(let i=0;i<e.length;i++)for(let n=0;n<t;n++)o[i*t+n]=e[i][n]||0}else o=e;return n?vs(o,{size:t,gridResolution:n}):i?function(e,t){const{size:n=2,startIndex:i=0,endIndex:o=e.length,normalize:s=!0}=t||{},r=e.slice(i,o);Ss(r,n,0,o-i);const a=vs(r,{size:n,broken:!0,gridResolution:360,gridOffset:[-180,-180]});if(s)for(const l of a)Ls(l,n);return a}(o,{size:t}):o}Ns.layerName="GridCellLayer",Ns.defaultProps={cellSize:{type:"number",min:0,value:1e3},offset:{type:"array",value:[1,1]}};var js=class extends po{constructor(e){super({...e,attributes:{positions:{size:3,padding:18,initialize:!0,type:e.fp64?Float64Array:Float32Array},segmentTypes:{size:1,type:e.isWebGPU?Float32Array:Uint8ClampedArray}}})}get(e){return this.attributes[e]}getPathSegmentIndices(e){const t=this.attributes.segmentTypes,n=this.vertexStarts[e],i=Math.min(this.vertexStarts[e+1]??this.instanceCount,this.instanceCount),o=[];for(let s=n;s<i-1;s++)4&t[s]||o.push(s);return o.length&&4&t[n]&&o.unshift(o.pop()),o}getGeometryFromBuffer(e){return this.normalize||this.opts.isWebGPU?super.getGeometryFromBuffer(e):null}normalizeGeometry(e){return this.normalize?Ds(e,this.positionSize,this.opts.resolution,this.opts.wrapLongitude):e}getGeometrySize(e){if(Us(e)){let t=0;for(const n of e)t+=this.getGeometrySize(n);return t}const t=this.getPathLength(e);return t<2?0:this.isClosed(e)?t<3?0:t+2:t}updateGeometryAttributes(e,t){if(0!==t.geometrySize)if(e&&Us(e))for(const n of e){const e=this.getGeometrySize(n);t.geometrySize=e,this.updateGeometryAttributes(n,t),t.vertexStart+=e}else this._updateSegmentTypes(e,t),this._updatePositions(e,t)}_updateSegmentTypes(e,t){const n=this.attributes.segmentTypes,i=!!e&&this.isClosed(e),{vertexStart:o,geometrySize:s}=t;n.fill(0,o,o+s),i?(n[o]=4,n[o+s-2]=4):(n[o]+=1,n[o+s-2]+=2),n[o+s-1]=4}_updatePositions(e,t){const{positions:n}=this.attributes;if(!n||!e)return;const{vertexStart:i,geometrySize:o}=t,s=new Array(3);for(let r=i,a=0;a<o;r++,a++)this.getPointOnPath(e,a,s),n[3*r]=s[0],n[3*r+1]=s[1],n[3*r+2]=s[2]}getPathLength(e){return e.length/this.positionSize}getPointOnPath(e,t,n=[]){const{positionSize:i}=this;t*i>=e.length&&(t+=1-e.length/i);const o=t*i;return n[0]=e[o],n[1]=e[o+1],n[2]=3===i&&e[o+2]||0,n}isClosed(e){if(!this.normalize)return Boolean(this.opts.loop);const{positionSize:t}=this,n=e.length-t;return e[0]===e[n]&&e[1]===e[n+1]&&(2===t||e[2]===e[n+2])}};function Us(e){return Array.isArray(e[0])}var Gs="layout(std140) uniform pathUniforms {\n float widthScale;\n float widthMinPixels;\n float widthMaxPixels;\n float jointType;\n float capType;\n float miterLimit;\n bool billboard;\n highp int widthUnits;\n} path;\n",Vs={name:"path",source:"struct PathUniforms {\n widthScale: f32,\n widthMinPixels: f32,\n widthMaxPixels: f32,\n jointType: f32,\n capType: f32,\n miterLimit: f32,\n billboard: f32,\n widthUnits: i32,\n};\n\n@group(0) @binding(auto)\nvar<uniform> path: PathUniforms;\n",vs:Gs,fs:Gs,uniformTypes:{widthScale:"f32",widthMinPixels:"f32",widthMaxPixels:"f32",jointType:"f32",capType:"f32",miterLimit:"f32",billboard:"f32",widthUnits:"i32"}},$s=[0,0,0,255],Ws={widthUnits:"meters",widthScale:{type:"number",min:0,value:1},widthMinPixels:{type:"number",min:0,value:0},widthMaxPixels:{type:"number",min:0,value:Number.MAX_SAFE_INTEGER},jointRounded:!1,capRounded:!1,miterLimit:{type:"number",min:0,value:4},antialiasing:!1,billboard:!1,_pathType:null,getPath:{type:"accessor",value:e=>e.path},getColor:{type:"accessor",value:$s},getWidth:{type:"accessor",value:1},rounded:{deprecatedFor:["jointRounded","capRounded"]}},Hs={enter:(e,t)=>t.length?t.subarray(t.length-e.length):e};function Zs(e,t){return e===t||Boolean(e&&t&&e.length===t.length&&e.every((e,n)=>e===t[n]))}var Ys=class extends co{getShaders(){const{antialiasing:e}=this.props;return super.getShaders({vs:"#version 300 es\n#define SHADER_NAME path-layer-vertex-shader\nin vec2 positions;\nin float instanceTypes;\nin vec3 instanceStartPositions;\nin vec3 instanceEndPositions;\nin vec3 instanceLeftPositions;\nin vec3 instanceRightPositions;\nin vec3 instanceLeftPositions64Low;\nin vec3 instanceStartPositions64Low;\nin vec3 instanceEndPositions64Low;\nin vec3 instanceRightPositions64Low;\nin float instanceStrokeWidths;\nin vec4 instanceColors;\nin float rowIndexes;\nuniform float opacity;\nout vec4 vColor;\nout vec2 vCornerOffset;\nout float vMiterLength;\nout vec2 vPathPosition;\nout float vPathLength;\nout float vJointType;\n#ifdef DASH_ENABLED\nout vec2 vPathBounds;\n#endif\nconst float EPSILON = 0.001;\nconst vec3 ZERO_OFFSET = vec3(0.0);\nfloat flipIfTrue(bool flag) {\nreturn -(float(flag) * 2. - 1.);\n}\nvec3 getLineJoinOffset(\nvec3 prevPoint, vec3 currPoint, vec3 nextPoint,\nvec2 width\n#ifdef DASH_ENABLED\n, float sourcePathLength, vec2 sourcePathRange\n#endif\n#ifdef ANTIALIASING\n, float coverageScale\n#endif\n) {\nbool isEnd = positions.x > 0.0;\nfloat sideOfPath = positions.y;\nfloat isJoint = float(sideOfPath == 0.0);\nvec3 deltaA3 = (currPoint - prevPoint);\nvec3 deltaB3 = (nextPoint - currPoint);\nmat3 rotationMatrix;\nbool needsRotation = !path.billboard && project_needs_rotation(currPoint, rotationMatrix);\nif (needsRotation) {\ndeltaA3 = deltaA3 * rotationMatrix;\ndeltaB3 = deltaB3 * rotationMatrix;\n}\nvec2 deltaA = deltaA3.xy / width;\nvec2 deltaB = deltaB3.xy / width;\nfloat lenA = length(deltaA);\nfloat lenB = length(deltaB);\nvec2 dirA = lenA > 0. ? normalize(deltaA) : vec2(0.0, 0.0);\nvec2 dirB = lenB > 0. ? normalize(deltaB) : vec2(0.0, 0.0);\nvec2 perpA = vec2(-dirA.y, dirA.x);\nvec2 perpB = vec2(-dirB.y, dirB.x);\nvec2 tangent = dirA + dirB;\ntangent = length(tangent) > 0. ? normalize(tangent) : perpA;\nvec2 miterVec = vec2(-tangent.y, tangent.x);\nvec2 dir = isEnd ? dirA : dirB;\nvec2 perp = isEnd ? perpA : perpB;\nfloat L = isEnd ? lenA : lenB;\n#ifdef DASH_ENABLED\nvec3 currDelta3 = isEnd ? deltaA3 : deltaB3;\nfloat currLength2D = length(currDelta3.xy);\nfloat arcLengthRatio = 1.0;\nfloat pathPositionOffset = 0.0;\nfloat pathLength = L;\nif (path.billboard) {\nfloat visiblePathLength = sourcePathLength * (sourcePathRange.y - sourcePathRange.x);\narcLengthRatio = L > 0.0 ? visiblePathLength / L : 0.0;\npathPositionOffset = sourcePathLength * sourcePathRange.x;\npathLength = sourcePathLength;\n} else if (currLength2D > 0.0) {\narcLengthRatio = length(currDelta3) / currLength2D;\npathLength = L * arcLengthRatio;\n}\n#endif\nfloat sinHalfA = abs(dot(miterVec, perp));\nfloat cosHalfA = abs(dot(dirA, miterVec));\nfloat turnDirection = flipIfTrue(dirA.x * dirB.y >= dirA.y * dirB.x);\nfloat cornerPosition = sideOfPath * turnDirection;\nfloat miterSize = 1.0 / max(sinHalfA, EPSILON);\nmiterSize = mix(\nmin(miterSize, max(lenA, lenB) / max(cosHalfA, EPSILON)),\nmiterSize,\nstep(0.0, cornerPosition)\n);\nvec2 offsetVec = mix(miterVec * miterSize, perp, step(0.5, cornerPosition))\n* (sideOfPath + isJoint * turnDirection);\nbool isStartCap = lenA == 0.0 || (!isEnd && (instanceTypes == 1.0 || instanceTypes == 3.0));\nbool isEndCap = lenB == 0.0 || (isEnd && (instanceTypes == 2.0 || instanceTypes == 3.0));\nbool isCap = isStartCap || isEndCap;\nif (isCap) {\noffsetVec = mix(perp * sideOfPath, dir * path.capType * 4.0 * flipIfTrue(isStartCap), isJoint);\nvJointType = path.capType;\n} else {\nvJointType = path.jointType;\n}\n#ifdef ANTIALIASING\nvec2 coverageOffsetVec = offsetVec * coverageScale;\n#ifdef DASH_ENABLED\nvPathLength = pathLength;\n#else\nvPathLength = L;\n#endif\nvCornerOffset = coverageOffsetVec;\nvMiterLength = dot(vCornerOffset, miterVec * turnDirection);\nvMiterLength = isCap ? isJoint : vMiterLength;\nvec2 offsetFromStartOfPath = coverageOffsetVec + deltaA * float(isEnd);\nvPathPosition = vec2(\ndot(offsetFromStartOfPath, perp),\n#ifdef DASH_ENABLED\npathPositionOffset + dot(offsetFromStartOfPath, dir) * arcLengthRatio\n#else\ndot(offsetFromStartOfPath, dir)\n#endif\n);\ngeometry.uv = vPathPosition;\nfloat isValid = step(instanceTypes, 3.5);\nvec3 offset = vec3(coverageOffsetVec * width * isValid, 0.0);\n#else\n#ifdef DASH_ENABLED\nvPathLength = pathLength;\n#else\nvPathLength = L;\n#endif\nvCornerOffset = offsetVec;\nvMiterLength = dot(vCornerOffset, miterVec * turnDirection);\nvMiterLength = isCap ? isJoint : vMiterLength;\nvec2 offsetFromStartOfPath = vCornerOffset + deltaA * float(isEnd);\nvPathPosition = vec2(\ndot(offsetFromStartOfPath, perp),\n#ifdef DASH_ENABLED\npathPositionOffset + dot(offsetFromStartOfPath, dir) * arcLengthRatio\n#else\ndot(offsetFromStartOfPath, dir)\n#endif\n);\ngeometry.uv = vPathPosition;\nfloat isValid = step(instanceTypes, 3.5);\nvec3 offset = vec3(offsetVec * width * isValid, 0.0);\n#endif\nif (needsRotation) {\noffset = rotationMatrix * offset;\n}\nreturn offset;\n}\nvoid clipLine(inout vec4 position, vec4 refPosition) {\nif (position.w < EPSILON) {\nfloat r = (EPSILON - refPosition.w) / (position.w - refPosition.w);\nposition = refPosition + (position - refPosition) * r;\n}\n}\n#ifdef DASH_ENABLED\nvec2 getClippedPathRange(float startW, float endW) {\nbool startClipped = startW < EPSILON;\nbool endClipped = endW < EPSILON;\nif (startClipped && endClipped) {\nreturn vec2(0.0);\n}\nif (startClipped || endClipped) {\nfloat intersection = clamp((EPSILON - startW) / (endW - startW), 0.0, 1.0);\nreturn startClipped ? vec2(intersection, 1.0) : vec2(0.0, intersection);\n}\nreturn vec2(0.0, 1.0);\n}\n#endif\nvoid main() {\ngeometry.pickingColor = picking_getPickingColorFromIndex(rowIndexes);\nvColor = vec4(instanceColors.rgb, instanceColors.a * layer.opacity);\nfloat isEnd = positions.x;\nvec3 prevPosition = mix(instanceLeftPositions, instanceStartPositions, isEnd);\nvec3 prevPosition64Low = mix(instanceLeftPositions64Low, instanceStartPositions64Low, isEnd);\nvec3 currPosition = mix(instanceStartPositions, instanceEndPositions, isEnd);\nvec3 currPosition64Low = mix(instanceStartPositions64Low, instanceEndPositions64Low, isEnd);\nvec3 nextPosition = mix(instanceEndPositions, instanceRightPositions, isEnd);\nvec3 nextPosition64Low = mix(instanceEndPositions64Low, instanceRightPositions64Low, isEnd);\ngeometry.worldPosition = currPosition;\nvec2 widthPixels = vec2(clamp(\nproject_size_to_pixel(instanceStrokeWidths * path.widthScale, path.widthUnits),\npath.widthMinPixels, path.widthMaxPixels) / 2.0);\nvec3 width;\nif (path.billboard) {\n#ifdef DASH_ENABLED\nvec4 prevPositionCommon;\nvec4 nextPositionCommon;\nvec4 prevPositionScreen = project_position_to_clipspace(\nprevPosition, prevPosition64Low, ZERO_OFFSET, prevPositionCommon\n);\n#else\nvec4 prevPositionScreen = project_position_to_clipspace(\nprevPosition, prevPosition64Low, ZERO_OFFSET\n);\n#endif\nvec4 currPositionScreen = project_position_to_clipspace(currPosition, currPosition64Low, ZERO_OFFSET, geometry.position);\n#ifdef DASH_ENABLED\nvec4 nextPositionScreen = project_position_to_clipspace(\nnextPosition, nextPosition64Low, ZERO_OFFSET, nextPositionCommon\n);\n#else\nvec4 nextPositionScreen = project_position_to_clipspace(\nnextPosition, nextPosition64Low, ZERO_OFFSET\n);\n#endif\n#ifdef DASH_ENABLED\nvec4 sourcePathStartScreen = mix(currPositionScreen, prevPositionScreen, isEnd);\nvec4 sourcePathEndScreen = mix(nextPositionScreen, currPositionScreen, isEnd);\nvec2 billboardPathRange = getClippedPathRange(\nsourcePathStartScreen.w, sourcePathEndScreen.w\n);\n#endif\nclipLine(prevPositionScreen, currPositionScreen);\nclipLine(nextPositionScreen, currPositionScreen);\nclipLine(currPositionScreen, mix(nextPositionScreen, prevPositionScreen, isEnd));\nwidth = vec3(widthPixels, 0.0);\nDECKGL_FILTER_SIZE(width, geometry);\n#ifdef ANTIALIASING\nvec2 coveragePadding = vec2(0.5 / project.devicePixelRatio);\nfloat coverageScale = length(width.xy) > 0.0\n? length(width.xy + coveragePadding) / length(width.xy)\n: 1.0;\n#endif\n#ifdef DASH_ENABLED\nvec3 currentDeltaCommon = isEnd > 0.0\n? geometry.position.xyz - prevPositionCommon.xyz\n: nextPositionCommon.xyz - geometry.position.xyz;\nfloat billboardPathLength = width.x > 0.0\n? length(currentDeltaCommon) * project.scale / (width.x * project.focalDistance)\n: 0.0;\n#endif\nvec3 offset = getLineJoinOffset(\nprevPositionScreen.xyz / prevPositionScreen.w,\ncurrPositionScreen.xyz / currPositionScreen.w,\nnextPositionScreen.xyz / nextPositionScreen.w,\nproject_pixel_size_to_clipspace(width.xy)\n#ifdef DASH_ENABLED\n,\nbillboardPathLength, billboardPathRange\n#endif\n#ifdef ANTIALIASING\n,\ncoverageScale\n#endif\n);\n#ifdef DASH_ENABLED\nvPathBounds = billboardPathLength * billboardPathRange;\n#endif\nDECKGL_FILTER_GL_POSITION(currPositionScreen, geometry);\ngl_Position = vec4(currPositionScreen.xyz + offset * currPositionScreen.w, currPositionScreen.w);\n} else {\nprevPosition = project_position(prevPosition, prevPosition64Low);\ncurrPosition = project_position(currPosition, currPosition64Low);\nnextPosition = project_position(nextPosition, nextPosition64Low);\nwidth = vec3(project_pixel_size(widthPixels), 0.0);\nDECKGL_FILTER_SIZE(width, geometry);\n#ifdef ANTIALIASING\nvec2 coveragePadding = project_pixel_size(vec2(0.5 / project.devicePixelRatio));\nfloat coverageScale = length(width.xy) > 0.0\n? length(width.xy + coveragePadding) / length(width.xy)\n: 1.0;\n#endif\nvec3 offset = getLineJoinOffset(\nprevPosition, currPosition, nextPosition, width.xy\n#ifdef DASH_ENABLED\n, 1.0, vec2(0.0, 1.0)\n#endif\n#ifdef ANTIALIASING\n, coverageScale\n#endif\n);\n#ifdef DASH_ENABLED\nvPathBounds = vec2(0.0, vPathLength);\n#endif\ngeometry.position = vec4(currPosition + offset, 1.0);\ngl_Position = project_common_position_to_clipspace(geometry.position);\nDECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n}\nDECKGL_FILTER_COLOR(vColor, geometry);\n}\n",fs:"#version 300 es\n#define SHADER_NAME path-layer-fragment-shader\nprecision highp float;\nin vec4 vColor;\nin vec2 vCornerOffset;\nin float vMiterLength;\nin vec2 vPathPosition;\nin float vPathLength;\nin float vJointType;\n#ifdef DASH_ENABLED\nin vec2 vPathBounds;\n#endif\nout vec4 fragColor;\nvoid main(void) {\ngeometry.uv = vPathPosition;\n#ifdef ANTIALIASING\n#ifdef DASH_ENABLED\nbool isCorner = vPathPosition.y < vPathBounds.x || vPathPosition.y > vPathBounds.y;\n#else\nbool isCorner = vPathPosition.y < 0.0 || vPathPosition.y > vPathLength;\n#endif\nbool isRound = vJointType > 0.5;\nfloat bodyCoord = abs(vPathPosition.x);\nfloat cornerCoord = length(vCornerOffset);\nfloat bodyPixels = (1.0 - bodyCoord) / max(fwidth(bodyCoord), 1e-6);\nfloat cornerPixels = (1.0 - cornerCoord) / max(fwidth(cornerCoord), 1e-6);\n#ifdef PATH_STYLE_OFFSET\nfloat edgePixels = isRound && isCorner ? min(cornerPixels, bodyPixels) : bodyPixels;\n#else\nfloat edgePixels = isRound && isCorner ? cornerPixels : bodyPixels;\n#endif\nif (edgePixels <= -SMOOTH_EDGE_RADIUS) {\ndiscard;\n}\nif (isCorner) {\nif (!isRound && vMiterLength > path.miterLimit + 1.0) {\ndiscard;\n}\n}\nfragColor = vColor;\nfragColor.a *= smoothedge(0.0, edgePixels);\n#else\n#ifdef DASH_ENABLED\nif (vPathPosition.y < vPathBounds.x || vPathPosition.y > vPathBounds.y) {\n#else\nif (vPathPosition.y < 0.0 || vPathPosition.y > vPathLength) {\n#endif\nif (vJointType > 0.5 && length(vCornerOffset) > 1.0) {\ndiscard;\n}\nif (vJointType < 0.5 && vMiterLength > path.miterLimit + 1.0) {\ndiscard;\n}\n}\nfragColor = vColor;\n#endif\nDECKGL_FILTER_COLOR(fragColor, geometry);\n}\n",source:"const EPSILON: f32 = 0.001;\nconst ZERO_OFFSET: vec3<f32> = vec3<f32>(0.0, 0.0, 0.0);\n\nstruct JoinResult {\n offset: vec3<f32>,\n cornerOffset: vec2<f32>,\n miterLength: f32,\n pathPosition: vec2<f32>,\n pathLength: f32,\n jointType: f32,\n};\n\nstruct Attributes {\n @location(0) positions: vec2<f32>,\n @location(1) instanceTypes: f32,\n @location(2) instanceLeftPositions: vec3<f32>,\n @location(3) instanceStartPositions: vec3<f32>,\n @location(4) instanceEndPositions: vec3<f32>,\n @location(5) instanceRightPositions: vec3<f32>,\n @location(6) instanceLeftPositions64Low: vec3<f32>,\n @location(7) instanceStartPositions64Low: vec3<f32>,\n @location(8) instanceEndPositions64Low: vec3<f32>,\n @location(9) instanceRightPositions64Low: vec3<f32>,\n @location(10) instanceStrokeWidths: f32,\n @location(11) instanceColors: vec4<f32>,\n @location(12) rowIndexes: u32,\n};\n\nstruct Varyings {\n @builtin(position) position: vec4<f32>,\n @location(0) vColor: vec4<f32>,\n @location(1) vCornerOffset: vec2<f32>,\n @location(2) vMiterLength: f32,\n @location(3) vPathPosition: vec2<f32>,\n @location(4) vPathLength: f32,\n @location(5) vJointType: f32,\n // Location 6 is reserved for TripsLayer's injected vTime varying.\n @location(7) clipCoordinates: vec2<f32>,\n#ifdef DASH_ENABLED\n @location(8) vPathBounds: vec2<f32>,\n#endif\n};\n\nfn flipIfTrue(flag: bool) -> f32 {\n return select(1.0, -1.0, flag);\n}\n\nfn clipLine(position: vec4<f32>, refPosition: vec4<f32>) -> vec4<f32> {\n if (position.w < EPSILON) {\n let r = (EPSILON - refPosition.w) / (position.w - refPosition.w);\n return refPosition + (position - refPosition) * r;\n }\n return position;\n}\n\n#ifdef DASH_ENABLED\n// Return the visible interval of the original segment before clipLine moves either endpoint.\nfn getClippedPathRange(startW: f32, endW: f32) -> vec2<f32> {\n let startClipped = startW < EPSILON;\n let endClipped = endW < EPSILON;\n if (startClipped && endClipped) {\n return vec2<f32>(0.0, 0.0);\n }\n if (startClipped || endClipped) {\n let intersection = clamp((EPSILON - startW) / (endW - startW), 0.0, 1.0);\n if (startClipped) {\n return vec2<f32>(intersection, 1.0);\n }\n return vec2<f32>(0.0, intersection);\n }\n return vec2<f32>(0.0, 1.0);\n}\n#endif\n\nfn getLineJoinOffset(\n prevPoint: vec3<f32>,\n currPoint: vec3<f32>,\n nextPoint: vec3<f32>,\n width: vec2<f32>,\n#ifdef DASH_ENABLED\n sourcePathLength: f32,\n sourcePathRange: vec2<f32>,\n#endif\n#ifdef ANTIALIASING\n coverageScale: f32,\n#endif\n positions: vec2<f32>,\n instanceTypes: f32\n) -> JoinResult {\n let isEnd = positions.x > 0.0;\n let sideOfPath = positions.y;\n let isJoint = select(0.0, 1.0, sideOfPath == 0.0);\n\n var deltaA3 = currPoint - prevPoint;\n var deltaB3 = nextPoint - currPoint;\n\n let rotationResult = project_needs_rotation(currPoint);\n if (path.billboard == 0.0 && rotationResult.needsRotation) {\n deltaA3 = rotationResult.transform * deltaA3;\n deltaB3 = rotationResult.transform * deltaB3;\n }\n\n let deltaA = deltaA3.xy / width;\n let deltaB = deltaB3.xy / width;\n\n let lenA = length(deltaA);\n let lenB = length(deltaB);\n\n let dirA = select(vec2<f32>(0.0, 0.0), normalize(deltaA), lenA > 0.0);\n let dirB = select(vec2<f32>(0.0, 0.0), normalize(deltaB), lenB > 0.0);\n\n let perpA = vec2<f32>(-dirA.y, dirA.x);\n let perpB = vec2<f32>(-dirB.y, dirB.x);\n\n var tangent = dirA + dirB;\n tangent = select(perpA, normalize(tangent), length(tangent) > 0.0);\n let miterVec = vec2<f32>(-tangent.y, tangent.x);\n let dir = select(dirB, dirA, isEnd);\n let perp = select(perpB, perpA, isEnd);\n#ifdef DASH_ENABLED\n let segmentLength2D = select(lenB, lenA, isEnd);\n\n // Extrusion happens in the XY plane, so segmentLength2D is a 2D length and pathPosition.y\n // below measures 2D distance along the segment. For a path that also moves in Z the true\n // arc length is longer by this ratio. Scaling pathLength and pathPosition.y by it makes\n // the coordinate measure real 3D distance while leaving the joint tests unchanged, since\n // they compare the two against each other and both are scaled alike. Billboard mode\n // extrudes in clip space, where the perspective divide has already reduced the segment to\n // its screen projection, so its complete common-space length is supplied by the caller.\n // Mirrors path-layer-vertex.glsl.ts.\n let currDelta3 = select(deltaB3, deltaA3, isEnd);\n let currLength2D = length(currDelta3.xy);\n // Do not clamp a valid denominator to EPSILON: high-zoom Web Mercator deltas are often\n // smaller than that in common space, and changing their scale corrupts even flat paths.\n let safeLength2D = select(1.0, currLength2D, currLength2D > 0.0);\n var arcLengthRatio = 1.0;\n var pathPositionOffset = 0.0;\n var pathLength = segmentLength2D;\n if (path.billboard != 0.0) {\n // clipLine may shorten the visible screen-space segment. Preserve the corresponding interval\n // of the complete common-space arclength instead of compressing the full dash period into the\n // visible span. Keep pathLength complete so justification is stable as the camera clips it.\n let visiblePathLength = sourcePathLength * (sourcePathRange.y - sourcePathRange.x);\n arcLengthRatio = 0.0;\n if (segmentLength2D > 0.0) {\n arcLengthRatio = visiblePathLength / segmentLength2D;\n }\n pathPositionOffset = sourcePathLength * sourcePathRange.x;\n pathLength = sourcePathLength;\n } else if (currLength2D > 0.0) {\n arcLengthRatio = length(currDelta3) / safeLength2D;\n pathLength = segmentLength2D * arcLengthRatio;\n }\n#else\n let pathLength = select(lenB, lenA, isEnd);\n#endif\n\n let sinHalfA = abs(dot(miterVec, perp));\n let cosHalfA = abs(dot(dirA, miterVec));\n let turnDirection = flipIfTrue(dirA.x * dirB.y >= dirA.y * dirB.x);\n let cornerPosition = sideOfPath * turnDirection;\n\n var miterSize = 1.0 / max(sinHalfA, EPSILON);\n miterSize = mix(\n min(miterSize, max(lenA, lenB) / max(cosHalfA, EPSILON)),\n miterSize,\n step(0.0, cornerPosition)\n );\n\n var offsetVec =\n mix(miterVec * miterSize, perp, step(0.5, cornerPosition)) *\n (sideOfPath + isJoint * turnDirection);\n\n let isStartCap = lenA == 0.0 || (!isEnd && (instanceTypes == 1.0 || instanceTypes == 3.0));\n let isEndCap = lenB == 0.0 || (isEnd && (instanceTypes == 2.0 || instanceTypes == 3.0));\n let isCap = isStartCap || isEndCap;\n\n var jointType = path.jointType;\n if (isCap) {\n offsetVec = mix(\n perp * sideOfPath,\n dir * path.capType * 4.0 * flipIfTrue(isStartCap),\n isJoint\n );\n jointType = path.capType;\n }\n\n#ifdef ANTIALIASING\n let coverageOffsetVec = offsetVec * coverageScale;\n var miterLength = dot(coverageOffsetVec, miterVec * turnDirection);\n#else\n var miterLength = dot(offsetVec, miterVec * turnDirection);\n#endif\n miterLength = select(miterLength, isJoint, isCap);\n\n#ifdef ANTIALIASING\n let offsetFromStartOfPath = coverageOffsetVec + deltaA * select(0.0, 1.0, isEnd);\n#else\n let offsetFromStartOfPath = offsetVec + deltaA * select(0.0, 1.0, isEnd);\n#endif\n let pathPosition = vec2<f32>(\n dot(offsetFromStartOfPath, perp),\n#ifdef DASH_ENABLED\n pathPositionOffset + dot(offsetFromStartOfPath, dir) * arcLengthRatio\n#else\n dot(offsetFromStartOfPath, dir)\n#endif\n );\n let isValid = step(f32(instanceTypes), 3.5);\n#ifdef ANTIALIASING\n var offset = vec3<f32>(coverageOffsetVec * width * isValid, 0.0);\n#else\n var offset = vec3<f32>(offsetVec * width * isValid, 0.0);\n#endif\n\n if (path.billboard == 0.0 && rotationResult.needsRotation) {\n offset = rotationResult.transform * offset;\n }\n\n#ifdef ANTIALIASING\n return JoinResult(\n offset, coverageOffsetVec, miterLength, pathPosition, pathLength, jointType\n );\n#else\n return JoinResult(offset, offsetVec, miterLength, pathPosition, pathLength, jointType);\n#endif\n}\n\n@vertex\nfn vertexMain(attributes: Attributes) -> Varyings {\n var varyings: Varyings;\n\n geometry.pickingColor = picking_getPickingColorFromIndex(attributes.rowIndexes);\n\n let isEnd = attributes.positions.x;\n\n let prevPosition = mix(attributes.instanceLeftPositions, attributes.instanceStartPositions, isEnd);\n let prevPosition64Low = mix(\n attributes.instanceLeftPositions64Low,\n attributes.instanceStartPositions64Low,\n isEnd\n );\n let currPosition = mix(attributes.instanceStartPositions, attributes.instanceEndPositions, isEnd);\n let currPosition64Low = mix(\n attributes.instanceStartPositions64Low,\n attributes.instanceEndPositions64Low,\n isEnd\n );\n let nextPosition = mix(attributes.instanceEndPositions, attributes.instanceRightPositions, isEnd);\n let nextPosition64Low = mix(\n attributes.instanceEndPositions64Low,\n attributes.instanceRightPositions64Low,\n isEnd\n );\n\n geometry.worldPosition = currPosition;\n\n let widthPixels =\n clamp(\n project_unit_size_to_pixel(attributes.instanceStrokeWidths * path.widthScale, path.widthUnits),\n path.widthMinPixels,\n path.widthMaxPixels\n ) / 2.0;\n\n if (path.billboard != 0.0) {\n#ifdef DASH_ENABLED\n let prevProjection = project_position_to_clipspace_and_commonspace(\n prevPosition, prevPosition64Low, ZERO_OFFSET\n );\n let nextProjection = project_position_to_clipspace_and_commonspace(\n nextPosition, nextPosition64Low, ZERO_OFFSET\n );\n let prevPositionCommon = prevProjection.commonPosition.xyz;\n let nextPositionCommon = nextProjection.commonPosition.xyz;\n var prevPositionScreen = prevProjection.clipPosition;\n var nextPositionScreen = nextProjection.clipPosition;\n#else\n var prevPositionScreen = project_position_to_clipspace(\n prevPosition, prevPosition64Low, ZERO_OFFSET\n );\n var nextPositionScreen = project_position_to_clipspace(\n nextPosition, nextPosition64Low, ZERO_OFFSET\n );\n#endif\n let currProjection = project_position_to_clipspace_and_commonspace(\n currPosition, currPosition64Low, ZERO_OFFSET\n );\n geometry.position = currProjection.commonPosition;\n var currPositionScreen = currProjection.clipPosition;\n#ifdef DASH_ENABLED\n let currPositionCommon = currProjection.commonPosition.xyz;\n let sourcePathStartScreen = mix(currPositionScreen, prevPositionScreen, isEnd);\n let sourcePathEndScreen = mix(nextPositionScreen, currPositionScreen, isEnd);\n let billboardPathRange = getClippedPathRange(\n sourcePathStartScreen.w, sourcePathEndScreen.w\n );\n#endif\n\n prevPositionScreen = clipLine(prevPositionScreen, currPositionScreen);\n nextPositionScreen = clipLine(nextPositionScreen, currPositionScreen);\n currPositionScreen = clipLine(currPositionScreen, mix(nextPositionScreen, prevPositionScreen, isEnd));\n\n#ifdef ANTIALIASING\n let coverageScale = select(\n 1.0,\n (widthPixels + 0.5 / project.devicePixelRatio) / max(widthPixels, 1e-6),\n widthPixels > 0.0\n );\n#endif\n#ifdef DASH_ENABLED\n let currentDeltaCommon = select(\n nextPositionCommon - currPositionCommon,\n currPositionCommon - prevPositionCommon,\n isEnd > 0.0\n );\n let billboardPathLength = select(\n 0.0,\n length(currentDeltaCommon) * project.scale / (widthPixels * project.focalDistance),\n widthPixels > 0.0\n );\n#endif\n let join = getLineJoinOffset(\n prevPositionScreen.xyz / prevPositionScreen.w,\n currPositionScreen.xyz / currPositionScreen.w,\n nextPositionScreen.xyz / nextPositionScreen.w,\n project_pixel_size_to_clipspace(vec2<f32>(widthPixels, widthPixels)),\n#ifdef DASH_ENABLED\n billboardPathLength,\n billboardPathRange,\n#endif\n#ifdef ANTIALIASING\n coverageScale,\n#endif\n attributes.positions,\n attributes.instanceTypes\n );\n#ifdef DASH_ENABLED\n // Phase and justification use the complete source segment, while cap and joint coverage\n // must still recognize the endpoints moved by clipLine.\n varyings.vPathBounds = billboardPathLength * billboardPathRange;\n#endif\n\n geometry.uv = join.pathPosition;\n varyings.position = vec4<f32>(\n currPositionScreen.xyz + join.offset * currPositionScreen.w,\n currPositionScreen.w\n );\n varyings.vCornerOffset = join.cornerOffset;\n varyings.vMiterLength = join.miterLength;\n varyings.vPathPosition = join.pathPosition;\n varyings.vPathLength = join.pathLength;\n varyings.vJointType = join.jointType;\n } else {\n let prevPositionCommon = project_position_vec3_f64(prevPosition, prevPosition64Low);\n let currPositionCommon = project_position_vec3_f64(currPosition, currPosition64Low);\n let nextPositionCommon = project_position_vec3_f64(nextPosition, nextPosition64Low);\n\n let width = vec2<f32>(\n project_pixel_size_float(widthPixels),\n project_pixel_size_float(widthPixels)\n );\n#ifdef ANTIALIASING\n let coverageScale = select(\n 1.0,\n (widthPixels + 0.5 / project.devicePixelRatio) / max(widthPixels, 1e-6),\n widthPixels > 0.0\n );\n#endif\n let join = getLineJoinOffset(\n prevPositionCommon,\n currPositionCommon,\n nextPositionCommon,\n width,\n#ifdef DASH_ENABLED\n 1.0,\n vec2<f32>(0.0, 1.0),\n#endif\n#ifdef ANTIALIASING\n coverageScale,\n#endif\n attributes.positions,\n attributes.instanceTypes\n );\n#ifdef DASH_ENABLED\n varyings.vPathBounds = vec2<f32>(0.0, join.pathLength);\n#endif\n\n geometry.position = vec4<f32>(currPositionCommon + join.offset, 1.0);\n geometry.uv = join.pathPosition;\n varyings.position = project_common_position_to_clipspace(geometry.position);\n varyings.vCornerOffset = join.cornerOffset;\n varyings.vMiterLength = join.miterLength;\n varyings.vPathPosition = join.pathPosition;\n varyings.vPathLength = join.pathLength;\n varyings.vJointType = join.jointType;\n }\n\n varyings.clipCoordinates = geometry.position.xy;\n clip_filterPosition(&varyings.position, geometry.worldPosition.xy);\n\n varyings.vColor = vec4<f32>(\n attributes.instanceColors.rgb,\n attributes.instanceColors.a * layer.opacity\n );\n return varyings;\n}\n\n@fragment\nfn fragmentMain(varyings: Varyings) -> @location(0) vec4<f32> {\n geometry.uv = varyings.vPathPosition;\n\n#ifdef ANTIALIASING\n // Coordinates of the outer silhouette, in units of half-width: rounded joints and caps are\n // bounded by the corner offset, everywhere else by the edge of the stroke. Dividing by the\n // screen-space derivative converts the distance to the boundary into device pixels, which stays\n // correct under perspective foreshortening and under extensions that rescale the stroke.\n#ifdef DASH_ENABLED\n let isCorner =\n varyings.vPathPosition.y < varyings.vPathBounds.x ||\n varyings.vPathPosition.y > varyings.vPathBounds.y;\n#else\n let isCorner = varyings.vPathPosition.y < 0.0 || varyings.vPathPosition.y > varyings.vPathLength;\n#endif\n let isRound = varyings.vJointType > 0.5;\n\n // Distance to the silhouette in device pixels, from the derivative of the coordinate that\n // bounds it. Computed before the discards below: derivatives need uniform control flow and are\n // undefined after a discard in the quad. See dev-docs/RFCs/v9.4/analytic-antialiasing-rfc.md\n let bodyCoord = abs(varyings.vPathPosition.x);\n let cornerCoord = length(varyings.vCornerOffset);\n // Both evaluated so each derivative stays on one field across the corner/body boundary\n let bodyPixels = (1.0 - bodyCoord) / max(fwidth(bodyCoord), 1e-6);\n let cornerPixels = (1.0 - cornerCoord) / max(fwidth(cornerCoord), 1e-6);\n#ifdef PATH_STYLE_OFFSET\n // Rounded corners still intersect the stroke-width envelope. Extensions may remap\n // vPathPosition.x independently of vCornerOffset, as PathStyleExtension does for offsets.\n let edgePixels = select(bodyPixels, min(cornerPixels, bodyPixels), isRound && isCorner);\n#else\n let edgePixels = select(bodyPixels, cornerPixels, isRound && isCorner);\n#endif\n\n // Fragments outside the coverage ramp must not write depth or picking colors.\n if (edgePixels <= -SMOOTH_EDGE_RADIUS) {\n discard;\n }\n\n if (isCorner) {\n if (!isRound && varyings.vMiterLength > path.miterLimit + 1.0) {\n discard;\n }\n }\n\n var color = varyings.vColor;\n\n // Feather one device pixel across the width only, before premultiplication. edgePixels is a\n // signed device-pixel distance and SMOOTH_EDGE_RADIUS is 0.5, so this ramps across one pixel.\n color.a *= smoothedge(0.0, edgePixels);\n#else\n#ifdef DASH_ENABLED\n if (\n varyings.vPathPosition.y < varyings.vPathBounds.x ||\n varyings.vPathPosition.y > varyings.vPathBounds.y\n ) {\n#else\n if (\n varyings.vPathPosition.y < 0.0 ||\n varyings.vPathPosition.y > varyings.vPathLength\n ) {\n#endif\n if (varyings.vJointType > 0.5 && length(varyings.vCornerOffset) > 1.0) {\n discard;\n }\n if (\n varyings.vJointType < 0.5 &&\n varyings.vMiterLength > path.miterLimit + 1.0\n ) {\n discard;\n }\n }\n#endif\n\n // Fragment-layer injections that discard pixels must run after analytic coverage derivatives.\n // See TripsLayer, which rejects fragments outside of the active time window at this anchor.\n // DECKGL_FILTER_COLOR\n clip_filterColor(varyings.clipCoordinates);\n#ifdef ANTIALIASING\n return deckgl_premultiplied_alpha(color);\n#else\n return deckgl_premultiplied_alpha(varyings.vColor);\n#endif\n}\n",defines:e?{ANTIALIASING:1}:{},modules:[Ye,Ze,Je,Vs,..."webgpu"===this.context.device.type?[ns]:[]]})}get wrapLongitude(){return!1}getBounds(){return"webgpu"===this.context.device.type?null:this.getAttributeManager()?.getBounds(["vertexPositions"])}getPathProjectionScale(e){const t=this.props.coordinateSystem;if(!Boolean(this.getAttributeManager()?.getAttributes().instanceDashOffsets))return null;if(e instanceof g&&e.zoom>=12&&("default"===t||"lnglat"===t||"cartesian"===t)){const n=l.getUniforms({viewport:e,coordinateSystem:t,coordinateOrigin:this.props.coordinateOrigin,autoWrapLongitude:this.wrapLongitude});return[e.projectionMode,n.coordinateOrigin[1],n.commonOrigin[1],...n.commonUnitsPerWorldUnit,...n.commonUnitsPerWorldUnit2,n.commonUnitsPerMeter[2]]}const n=function(e){if(e.isGeospatial)return null;const{unitsPerMeter:t}=e.distanceScales;return[t[0],t[1],t[2]]}(e);return n?[e.projectionMode,...n]:[e.projectionMode]}shouldUpdateState(e){const{viewport:t}=this.context;return super.shouldUpdateState(e)||this.state?.tessellationResolution!==t.resolution||!Zs(this.state?.pathProjectionScale,this.getPathProjectionScale(t))}initializeState(){const e=!0,t="webgpu"===this.context.device.type;this.getAttributeManager().addInstanced({...t?{pathPositions:{size:24,type:"float32",transition:!1,accessor:"getPath",update:this.calculateWebGPUPositions,shaderAttributes:{instanceLeftPositions:{size:3,elementOffset:0},instanceStartPositions:{size:3,elementOffset:3},instanceEndPositions:{size:3,elementOffset:6},instanceRightPositions:{size:3,elementOffset:9},instanceLeftPositions64Low:{size:3,elementOffset:12},instanceStartPositions64Low:{size:3,elementOffset:15},instanceEndPositions64Low:{size:3,elementOffset:18},instanceRightPositions64Low:{size:3,elementOffset:21}},noAlloc:e}}:{vertexPositions:{size:3,vertexOffset:1,type:"float64",fp64:this.use64bitPositions(),transition:Hs,accessor:"getPath",update:this.calculatePositions,noAlloc:e,shaderAttributes:{instanceLeftPositions:{vertexOffset:0},instanceStartPositions:{vertexOffset:1},instanceEndPositions:{vertexOffset:2},instanceRightPositions:{vertexOffset:3}}}},instanceTypes:{size:1,type:t?"float32":"uint8",update:this.calculateSegmentTypes,noAlloc:e},instanceStrokeWidths:{size:1,accessor:"getWidth",transition:!t&&Hs,defaultValue:1,bufferGroup:"path-instance-data"},instanceColors:{size:this.props.colorFormat.length,type:"unorm8",accessor:"getColor",transition:!t&&Hs,defaultValue:$s,bufferGroup:"path-instance-data"},rowIndexes:{size:1,type:"uint32",accessor:(e,{index:t})=>e&&e.__source?e.__source.index:t,bufferGroup:"path-instance-data"}}),this.setState({pathTesselator:new js({fp64:this.use64bitPositions(),isWebGPU:t}),tessellationResolution:this.context.viewport.resolution,pathProjectionScale:this.getPathProjectionScale(this.context.viewport)})}updateState(e){super.updateState(e);const{props:t,oldProps:n,changeFlags:i}=e,o=this.getAttributeManager(),{viewport:s}=this.context,r=this.state.tessellationResolution!==s.resolution,a=this.getPathProjectionScale(s),l=!Zs(this.state.pathProjectionScale,a),c=i.updateTriggersChanged&&(i.updateTriggersChanged.all||i.updateTriggersChanged.getPath)||t._pathType!==n._pathType||t.positionFormat!==n.positionFormat||t.wrapLongitude!==n.wrapLongitude||r;if(i.dataChanged||c){const{pathTesselator:e}=this.state,n=t.data.attributes||{};e.updateGeometry({data:t.data,geometryBuffer:n.getPath,buffers:n,normalize:!t._pathType,loop:"loop"===t._pathType,getGeometry:t.getPath,positionFormat:t.positionFormat,wrapLongitude:t.wrapLongitude,resolution:s.resolution,dataChanged:c?void 0:i.dataChanged}),this.setState({numInstances:e.instanceCount,startIndices:e.vertexStarts,tessellationResolution:s.resolution,pathProjectionScale:a}),!i.dataChanged||c?o.invalidateAll():l&&o.invalidate("instanceDashOffsets")}else l&&(this.setState({pathProjectionScale:a}),o.invalidate("instanceDashOffsets"));(i.extensionsChanged||t.antialiasing!==n.antialiasing)&&(this.state.model?.destroy(),this.state.model=this._getModel(),o.invalidateAll())}getPickingInfo(e){const t=super.getPickingInfo(e),{index:n}=t,i=this.props.data;return i[0]&&i[0].__source&&(t.object=i.find(e=>e.__source.index===n)),t}disablePickingIndex(e){const t=this.props.data;if(t[0]&&t[0].__source)for(let n=0;n<t.length;n++)t[n].__source.index===e&&this._disablePickingIndex(n);else super.disablePickingIndex(e)}draw({uniforms:e}){const{jointRounded:t,capRounded:n,billboard:o,miterLimit:s,widthUnits:r,widthScale:a,widthMinPixels:l,widthMaxPixels:c}=this.props,u=this.state.model,f={jointType:Number(t),capType:Number(n),billboard:o,widthUnits:i[r],widthScale:a,miterLimit:s,widthMinPixels:l,widthMaxPixels:c};u.shaderInputs.setProps({path:f}),u.draw(this.context.renderPass)}_getModel(){return new xt(this.context.device,{...this.getShaders(),id:this.props.id,bufferLayout:this.getAttributeManager().getBufferLayouts(),geometry:new nt({topology:"triangle-list",attributes:{indices:new Uint16Array([0,1,2,1,4,2,1,3,4,3,5,4]),positions:{value:new Float32Array([0,0,0,-1,0,1,1,-1,1,1,1,0]),size:2}}}),isInstanced:!0})}calculatePositions(e){const{pathTesselator:t}=this.state;e.startIndices=t.vertexStarts,e.value=t.get("positions")}calculateSegmentTypes(e){const{pathTesselator:t}=this.state;e.startIndices=t.vertexStarts,e.value=t.get("segmentTypes")}calculateWebGPUPositions(e){const{pathTesselator:t}=this.state,n=t.get("positions");if(!n)return void(e.value=null);const i=t.instanceCount,o=new Float32Array(24*i),s=[-1,0,1,2];for(let r=0;r<i;r++){const e=24*r;for(let t=0;t<4;t++){const a=r+s[t],l=e+3*t;for(let e=0;e<3;e++){const t=a>=0&&a<i?n[3*a+e]:0,s=Math.fround(t);o[l+e]=s,o[l+e+12]=t-s}}}e.startIndices=t.vertexStarts,e.value=o}};Ys.defaultProps=Ws,Ys.layerName="PathLayer";var qs=/* @__PURE__ */e(/* @__PURE__ */n((e,t)=>{function n(e,t,n){n=n||2;var o,r,a,l,c,d,p,h=t&&t.length,v=h?t[0]*n:e.length,m=i(e,0,v,n,!0),_=[];if(!m||m.next===m.prev)return _;if(h&&(m=function(e,t,n,o){for(var s,r=[],a=0,l=t.length;a<l;a++)(s=i(e,t[a]*o,a<l-1?t[a+1]*o:e.length,o,!1))===s.next&&(s.steiner=!0),r.push(g(s));for(r.sort(u),a=0;a<r.length;a++)n=f(r[a],n);return n}(e,t,m,n)),e.length>80*n){o=a=e[0],r=l=e[1];for(var x=n;x<v;x+=n)(c=e[x])<o&&(o=c),(d=e[x+1])<r&&(r=d),c>a&&(a=c),d>l&&(l=d);p=0!==(p=Math.max(a-o,l-r))?32767/p:0}return s(m,_,n,o,r,p,0),_}function i(e,t,n,i,o){var s,r;if(o===A(e,t,n,i)>0)for(s=t;s<n;s+=i)r=w(s,e[s],e[s+1],r);else for(s=n-i;s>=t;s-=i)r=w(s,e[s],e[s+1],r);return r&&_(r,r.next)&&(S(r),r=r.next),r}function o(e,t){if(!e)return e;t||(t=e);var n,i=e;do{if(n=!1,i.steiner||!_(i,i.next)&&0!==m(i.prev,i,i.next))i=i.next;else{if(S(i),(i=t=i.prev)===i.next)break;n=!0}}while(n||i!==t);return t}function s(e,t,n,i,u,f,d){if(e){!d&&f&&function(e,t,n,i){var o=e;do{0===o.z&&(o.z=p(o.x,o.y,t,n,i)),o.prevZ=o.prev,o.nextZ=o.next,o=o.next}while(o!==e);o.prevZ.nextZ=null,o.prevZ=null,function(e){var t,n,i,o,s,r,a,l,c=1;do{for(n=e,e=null,s=null,r=0;n;){for(r++,i=n,a=0,t=0;t<c&&(a++,i=i.nextZ);t++);for(l=c;a>0||l>0&&i;)0!==a&&(0===l||!i||n.z<=i.z)?(o=n,n=n.nextZ,a--):(o=i,i=i.nextZ,l--),s?s.nextZ=o:e=o,o.prevZ=s,s=o;n=i}s.nextZ=null,c*=2}while(r>1)}(o)}(e,i,u,f);for(var g,h,v=e;e.prev!==e.next;)if(g=e.prev,h=e.next,f?a(e,i,u,f):r(e))t.push(g.i/n|0),t.push(e.i/n|0),t.push(h.i/n|0),S(e),e=h.next,v=h.next;else if((e=h)===v){d?1===d?s(e=l(o(e),t,n),t,n,i,u,f,2):2===d&&c(e,t,n,i,u,f):s(o(e),t,n,i,u,f,1);break}}}function r(e){var t=e.prev,n=e,i=e.next;if(m(t,n,i)>=0)return!1;for(var o=t.x,s=n.x,r=i.x,a=t.y,l=n.y,c=i.y,u=o<s?o<r?o:r:s<r?s:r,f=a<l?a<c?a:c:l<c?l:c,d=o>s?o>r?o:r:s>r?s:r,p=a>l?a>c?a:c:l>c?l:c,g=i.next;g!==t;){if(g.x>=u&&g.x<=d&&g.y>=f&&g.y<=p&&h(o,a,s,l,r,c,g.x,g.y)&&m(g.prev,g,g.next)>=0)return!1;g=g.next}return!0}function a(e,t,n,i){var o=e.prev,s=e,r=e.next;if(m(o,s,r)>=0)return!1;for(var a=o.x,l=s.x,c=r.x,u=o.y,f=s.y,d=r.y,g=a<l?a<c?a:c:l<c?l:c,v=u<f?u<d?u:d:f<d?f:d,_=a>l?a>c?a:c:l>c?l:c,x=u>f?u>d?u:d:f>d?f:d,y=p(g,v,t,n,i),b=p(_,x,t,n,i),P=e.prevZ,C=e.nextZ;P&&P.z>=y&&C&&C.z<=b;){if(P.x>=g&&P.x<=_&&P.y>=v&&P.y<=x&&P!==o&&P!==r&&h(a,u,l,f,c,d,P.x,P.y)&&m(P.prev,P,P.next)>=0)return!1;if(P=P.prevZ,C.x>=g&&C.x<=_&&C.y>=v&&C.y<=x&&C!==o&&C!==r&&h(a,u,l,f,c,d,C.x,C.y)&&m(C.prev,C,C.next)>=0)return!1;C=C.nextZ}for(;P&&P.z>=y;){if(P.x>=g&&P.x<=_&&P.y>=v&&P.y<=x&&P!==o&&P!==r&&h(a,u,l,f,c,d,P.x,P.y)&&m(P.prev,P,P.next)>=0)return!1;P=P.prevZ}for(;C&&C.z<=b;){if(C.x>=g&&C.x<=_&&C.y>=v&&C.y<=x&&C!==o&&C!==r&&h(a,u,l,f,c,d,C.x,C.y)&&m(C.prev,C,C.next)>=0)return!1;C=C.nextZ}return!0}function l(e,t,n){var i=e;do{var s=i.prev,r=i.next.next;!_(s,r)&&x(s,i,i.next,r)&&P(s,r)&&P(r,s)&&(t.push(s.i/n|0),t.push(i.i/n|0),t.push(r.i/n|0),S(i),S(i.next),i=e=r),i=i.next}while(i!==e);return o(i)}function c(e,t,n,i,r,a){var l=e;do{for(var c=l.next.next;c!==l.prev;){if(l.i!==c.i&&v(l,c)){var u=C(l,c);return l=o(l,l.next),u=o(u,u.next),s(l,t,n,i,r,a,0),void s(u,t,n,i,r,a,0)}c=c.next}l=l.next}while(l!==e)}function u(e,t){return e.x-t.x}function f(e,t){var n=function(e,t){var n,i=t,o=e.x,s=e.y,r=-1/0;do{if(s<=i.y&&s>=i.next.y&&i.next.y!==i.y){var a=i.x+(s-i.y)*(i.next.x-i.x)/(i.next.y-i.y);if(a<=o&&a>r&&(r=a,n=i.x<i.next.x?i:i.next,a===o))return n}i=i.next}while(i!==t);if(!n)return null;var l,c=n,u=n.x,f=n.y,p=1/0;i=n;do{o>=i.x&&i.x>=u&&o!==i.x&&h(s<f?o:r,s,u,f,s<f?r:o,s,i.x,i.y)&&(l=Math.abs(s-i.y)/(o-i.x),P(i,e)&&(l<p||l===p&&(i.x>n.x||i.x===n.x&&d(n,i)))&&(n=i,p=l)),i=i.next}while(i!==c);return n}(e,t);if(!n)return t;var i=C(n,e);return o(i,i.next),o(n,n.next)}function d(e,t){return m(e.prev,e,t.prev)<0&&m(t.next,e,e.next)<0}function p(e,t,n,i,o){return(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-n)*o|0)|e<<8))|e<<4))|e<<2))|e<<1))|(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-i)*o|0)|t<<8))|t<<4))|t<<2))|t<<1))<<1}function g(e){var t=e,n=e;do{(t.x<n.x||t.x===n.x&&t.y<n.y)&&(n=t),t=t.next}while(t!==e);return n}function h(e,t,n,i,o,s,r,a){return(o-r)*(t-a)>=(e-r)*(s-a)&&(e-r)*(i-a)>=(n-r)*(t-a)&&(n-r)*(s-a)>=(o-r)*(i-a)}function v(e,t){return e.next.i!==t.i&&e.prev.i!==t.i&&!function(e,t){var n=e;do{if(n.i!==e.i&&n.next.i!==e.i&&n.i!==t.i&&n.next.i!==t.i&&x(n,n.next,e,t))return!0;n=n.next}while(n!==e);return!1}(e,t)&&(P(e,t)&&P(t,e)&&function(e,t){var n=e,i=!1,o=(e.x+t.x)/2,s=(e.y+t.y)/2;do{n.y>s!=n.next.y>s&&n.next.y!==n.y&&o<(n.next.x-n.x)*(s-n.y)/(n.next.y-n.y)+n.x&&(i=!i),n=n.next}while(n!==e);return i}(e,t)&&(m(e.prev,e,t.prev)||m(e,t.prev,t))||_(e,t)&&m(e.prev,e,e.next)>0&&m(t.prev,t,t.next)>0)}function m(e,t,n){return(t.y-e.y)*(n.x-t.x)-(t.x-e.x)*(n.y-t.y)}function _(e,t){return e.x===t.x&&e.y===t.y}function x(e,t,n,i){var o=b(m(e,t,n)),s=b(m(e,t,i)),r=b(m(n,i,e)),a=b(m(n,i,t));return o!==s&&r!==a||(!(0!==o||!y(e,n,t))||(!(0!==s||!y(e,i,t))||(!(0!==r||!y(n,e,i))||!(0!==a||!y(n,t,i)))))}function y(e,t,n){return t.x<=Math.max(e.x,n.x)&&t.x>=Math.min(e.x,n.x)&&t.y<=Math.max(e.y,n.y)&&t.y>=Math.min(e.y,n.y)}function b(e){return e>0?1:e<0?-1:0}function P(e,t){return m(e.prev,e,e.next)<0?m(e,t,e.next)>=0&&m(e,e.prev,t)>=0:m(e,t,e.prev)<0||m(e,e.next,t)<0}function C(e,t){var n=new L(e.i,e.x,e.y),i=new L(t.i,t.x,t.y),o=e.next,s=t.prev;return e.next=t,t.prev=e,n.next=o,o.prev=n,i.next=n,n.prev=i,s.next=i,i.prev=s,i}function w(e,t,n,i){var o=new L(e,t,n);return i?(o.next=i.next,o.prev=i,i.next.prev=o,i.next=o):(o.prev=o,o.next=o),o}function S(e){e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ)}function L(e,t,n){this.i=e,this.x=t,this.y=n,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}function A(e,t,n,i){for(var o=0,s=t,r=n-i;s<n;s+=i)o+=(e[r]-e[s])*(e[s+1]+e[r+1]),r=s;return o}t.exports=n,t.exports.default=n,n.deviation=function(e,t,n,i){var o=t&&t.length,s=o?t[0]*n:e.length,r=Math.abs(A(e,0,s,n));if(o)for(var a=0,l=t.length;a<l;a++){var c=t[a]*n,u=a<l-1?t[a+1]*n:e.length;r-=Math.abs(A(e,c,u,n))}var f=0;for(a=0;a<i.length;a+=3){var d=i[a]*n,p=i[a+1]*n,g=i[a+2]*n;f+=Math.abs((e[d]-e[g])*(e[p+1]-e[d+1])-(e[d]-e[p])*(e[g+1]-e[d+1]))}return 0===r&&0===f?0:Math.abs((f-r)/r)},n.flatten=function(e){for(var t=e[0][0].length,n={vertices:[],holes:[],dimensions:t},i=0,o=0;o<e.length;o++){for(var s=0;s<e[o].length;s++)for(var r=0;r<t;r++)n.vertices.push(e[o][s][r]);o>0&&(i+=e[o-1].length,n.holes.push(i))}return n}})(),1),Ks=rs,Xs=as,Js={isClosed:!0};function Qs(e){return"positions"in e?e.positions:e}function er(e){return"holeIndices"in e?e.holeIndices:null}function tr(e,t,n,i,o){let s=t;const r=n.length;for(let a=0;a<r;a++)for(let t=0;t<i;t++)e[s++]=n[a][t]||0;if(!function(e){const t=e[0],n=e[e.length-1];return t[0]===n[0]&&t[1]===n[1]&&t[2]===n[2]}(n))for(let a=0;a<i;a++)e[s++]=n[0][a]||0;return Js.start=t,Js.end=s,Js.size=i,ls(e,o,Js),s}function nr(e,t,n,i,o=0,s,r){const a=(s=s||n.length)-o;if(a<=0)return t;let l=t;for(let c=0;c<a;c++)e[l++]=n[o+c];if(!function(e,t,n,i){for(let o=0;o<t;o++)if(e[n+o]!==e[i-t+o])return!1;return!0}(n,i,o,s))for(let c=0;c<i;c++)e[l++]=n[o+c];return Js.start=t,Js.end=l,Js.size=i,ls(e,r,Js),l}function ir(e,t){!function(e){if(e=e&&e.positions||e,!Array.isArray(e)&&!ArrayBuffer.isView(e))throw new Error("invalid polygon")}(e);const n=[],i=[];if("positions"in e){const{positions:o,holeIndices:s}=e;if(s){let e=0;for(let r=0;r<=s.length;r++)e=nr(n,e,o,t,s[r-1],s[r],0===r?Ks:Xs),i.push(e);return i.pop(),{positions:n,holeIndices:i}}e=o}if(!function(e){return Array.isArray(e[0])}(e))return nr(n,0,e,t,0,n.length,Ks),n;if(!function(e){return e.length>=1&&e[0].length>=2&&Number.isFinite(e[0][0])}(e)){let o=0;for(const[s,r]of e.entries())o=tr(n,o,r,t,0===s?Ks:Xs),i.push(o);return i.pop(),{positions:n,holeIndices:i}}return tr(n,0,e,t,Ks),n}function or(e,t,n){const i=e.length/3;let o=0;for(let s=0;s<i;s++){const r=(s+1)%i;o+=e[3*s+t]*e[3*r+n],o-=e[3*r+t]*e[3*s+n]}return Math.abs(o/2)}function sr(e,t,n,i){const o=e.length/3;for(let s=0;s<o;s++){const o=3*s,r=e[o+0],a=e[o+1],l=e[o+2];e[o+t]=r,e[o+n]=a,e[o+i]=l}}var rr=class extends po{constructor(e){const{fp64:t,IndexType:n=Uint32Array}=e;super({...e,attributes:{positions:{size:3,type:t?Float64Array:Float32Array},vertexValid:{type:Uint16Array,size:1},indices:{type:n,size:1}}})}get(e){const{attributes:t}=this;return"indices"===e?t.indices&&t.indices.subarray(0,this.vertexCount):t[e]}updateGeometry(e){super.updateGeometry(e);const t=this.buffers.indices;if(t)this.vertexCount=(t.value||t).length;else if(this.data&&!this.getGeometry)throw new Error("missing indices buffer")}normalizeGeometry(e){if(this.normalize){const t=ir(e,this.positionSize);return this.opts.resolution?ms(Qs(t),er(t),{size:this.positionSize,gridResolution:this.opts.resolution,edgeTypes:!0}):this.opts.wrapLongitude?function(e,t=null,n){const{size:i=2,normalize:o=!0,edgeTypes:s=!1}=n||{};t=t||[];const r=[],a=[];let l=0,c=0;for(let f=0;f<=t.length;f++){const o=t[f]||e.length,s=c,u=Cs(e,i,l,o);for(let t=u;t<o;t++)r[c++]=e[t];for(let t=l;t<u;t++)r[c++]=e[t];Ss(r,i,s,c),ws(r,i,s,c,n?.maxLatitude),l=o,a[f]=c}a.pop();const u=ms(r,a,{size:i,gridResolution:360,gridOffset:[-180,-180],edgeTypes:s});if(o)for(const f of u)Ls(f.positions,i);return u}(Qs(t),er(t),{size:this.positionSize,maxLatitude:86,edgeTypes:!0}):t}return e}getGeometrySize(e){if(ar(e)){let t=0;for(const n of e)t+=this.getGeometrySize(n);return t}return Qs(e).length/this.positionSize}getGeometryFromBuffer(e){return this.normalize||!this.buffers.indices?super.getGeometryFromBuffer(e):null}updateGeometryAttributes(e,t){if(e&&ar(e))for(const n of e){const e=this.getGeometrySize(n);t.geometrySize=e,this.updateGeometryAttributes(n,t),t.vertexStart+=e,t.indexStart=this.indexStarts[t.geometryIndex+1]}else{const n=e;this._updateIndices(n,t),this._updatePositions(n,t),this._updateVertexValid(n,t)}}_updateIndices(e,{geometryIndex:t,vertexStart:n,indexStart:i}){const{attributes:o,indexStarts:s,typedArrayManager:r}=this;let a=o.indices;if(!a||!e)return;let l=i;const c=function(e,t,n,i){let o=er(e);o&&(o=o.map(e=>e/t));let s=Qs(e);const r=i&&3===t;if(n){const e=s.length;s=s.slice();const i=[];for(let o=0;o<e;o+=t){i[0]=s[o],i[1]=s[o+1],r&&(i[2]=s[o+2]);const e=n(i);s[o]=e[0],s[o+1]=e[1],r&&(s[o+2]=e[2])}}if(r){const e=or(s,0,1),t=or(s,0,2),i=or(s,1,2);if(!e&&!t&&!i)return[];e>t&&e>i||(t>i?(n||(s=s.slice()),sr(s,0,2,1)):(n||(s=s.slice()),sr(s,2,0,1)))}return(0,qs.default)(s,o,t)}(e,this.positionSize,this.opts.preproject,this.opts.full3d);a=r.allocate(a,i+c.length,{copy:!0});for(let u=0;u<c.length;u++)a[l++]=c[u]+n;s[t+1]=i+c.length,o.indices=a}_updatePositions(e,{vertexStart:t,geometrySize:n}){const{attributes:{positions:i},positionSize:o}=this;if(!i||!e)return;const s=Qs(e);for(let r=t,a=0;a<n;r++,a++){const e=s[a*o],t=s[a*o+1],n=o>2?s[a*o+2]:0;i[3*r]=e,i[3*r+1]=t,i[3*r+2]=n}}_updateVertexValid(e,{vertexStart:t,geometrySize:n}){const{positionSize:i}=this,o=this.attributes.vertexValid,s=e&&er(e);if(e&&e.edgeTypes?o.set(e.edgeTypes,t):o.fill(1,t,t+n),s)for(let r=0;r<s.length;r++)o[t+s[r]/i-1]=0;o[t+n-1]=0}};function ar(e){return Array.isArray(e)&&e.length>0&&!Number.isFinite(e[0])}var lr="layout(std140) uniform solidPolygonUniforms {\n bool extruded;\n bool isWireframe;\n float elevationScale;\n} solidPolygon;\n",cr={name:"solidPolygon",source:"struct SolidPolygonUniforms {\n extruded: f32,\n isWireframe: f32,\n elevationScale: f32,\n};\n\n@group(0) @binding(auto) var<uniform> solidPolygon: SolidPolygonUniforms;\n",vs:lr,fs:lr,uniformTypes:{extruded:"f32",isWireframe:"f32",elevationScale:"f32"}},ur="in vec4 fillColors;\nin vec4 lineColors;\nin float rowIndexes;\nout vec4 vColor;\nstruct PolygonProps {\nvec3 positions;\nvec3 positions64Low;\nvec3 normal;\nfloat elevations;\n};\nvec3 project_offset_normal(vec3 vector) {\nif (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT ||\nproject.coordinateSystem == COORDINATE_SYSTEM_LNGLAT_OFFSETS) {\nreturn normalize(vector * project.commonUnitsPerWorldUnit);\n}\nreturn project_normal(vector);\n}\nvoid calculatePosition(PolygonProps props) {\nvec3 pos = props.positions;\nvec3 pos64Low = props.positions64Low;\nvec3 normal = props.normal;\nvec4 colors = solidPolygon.isWireframe ? lineColors : fillColors;\ngeometry.worldPosition = props.positions;\ngeometry.pickingColor = picking_getPickingColorFromIndex(rowIndexes);\nif (solidPolygon.extruded) {\npos.z += props.elevations * solidPolygon.elevationScale;\n}\ngl_Position = project_position_to_clipspace(pos, pos64Low, vec3(0.), geometry.position);\nDECKGL_FILTER_GL_POSITION(gl_Position, geometry);\nif (solidPolygon.extruded) {\n#ifdef IS_SIDE_VERTEX\nnormal = project_offset_normal(normal);\n#else\nnormal = project_normal(normal);\n#endif\ngeometry.normal = normal;\nvec3 lightColor = lighting_getLightColor(colors.rgb, project.cameraPosition, geometry.position.xyz, geometry.normal);\nvColor = vec4(lightColor, colors.a * layer.opacity);\n} else {\nvColor = vec4(colors.rgb, colors.a * layer.opacity);\n}\nDECKGL_FILTER_COLOR(vColor, geometry);\n}\n",fr=`#version 300 es\n#define SHADER_NAME solid-polygon-layer-vertex-shader\nin vec3 vertexPositions;\nin vec3 vertexPositions64Low;\nin float elevations;\n${ur}\nvoid main(void) {\nPolygonProps props;\nprops.positions = vertexPositions;\nprops.positions64Low = vertexPositions64Low;\nprops.elevations = elevations;\nprops.normal = vec3(0.0, 0.0, 1.0);\ncalculatePosition(props);\n}\n`,dr=`#version 300 es\n#define SHADER_NAME solid-polygon-layer-vertex-shader-side\n#define IS_SIDE_VERTEX\nin vec2 positions;\nin vec3 vertexPositions;\nin vec3 nextVertexPositions;\nin vec3 vertexPositions64Low;\nin vec3 nextVertexPositions64Low;\nin float elevations;\nin float instanceVertexValid;\n${ur}\nvoid main(void) {\nif(instanceVertexValid < 0.5){\ngl_Position = vec4(0.);\nreturn;\n}\nPolygonProps props;\nvec3 pos;\nvec3 pos64Low;\nvec3 nextPos;\nvec3 nextPos64Low;\n#if RING_WINDING_ORDER_CW == 1\npos = vertexPositions;\npos64Low = vertexPositions64Low;\nnextPos = nextVertexPositions;\nnextPos64Low = nextVertexPositions64Low;\n#else\npos = nextVertexPositions;\npos64Low = nextVertexPositions64Low;\nnextPos = vertexPositions;\nnextPos64Low = vertexPositions64Low;\n#endif\nprops.positions = mix(pos, nextPos, positions.x);\nprops.positions64Low = mix(pos64Low, nextPos64Low, positions.x);\nprops.normal = vec3(\npos.y - nextPos.y + (pos64Low.y - nextPos64Low.y),\nnextPos.x - pos.x + (nextPos64Low.x - pos64Low.x),\n0.0);\nprops.elevations = elevations * positions.y;\ncalculatePosition(props);\n}\n`;function pr(e,t){return"top"===e?"fn project_offset_normal(vector: vec3<f32>) -> vec3<f32> {\n if (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT ||\n project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT_OFFSETS) {\n return normalize(vector * project.commonUnitsPerWorldUnit);\n }\n return project_normal(vector);\n}\n\nfn apply_polygon_color(\n colors: vec4<f32>,\n normal: vec3<f32>,\n position: vec4<f32>\n) -> vec4<f32> {\n if (solidPolygon.extruded > 0.5) {\n let lightColor = lighting_getLightColor2(\n colors.rgb,\n project.cameraPosition,\n position.xyz,\n normal\n );\n return vec4<f32>(lightColor, colors.a * layer.opacity);\n }\n return vec4<f32>(colors.rgb, colors.a * layer.opacity);\n}\n\n\nstruct Attributes {\n @location(0) vertexPositions: vec3<f32>,\n @location(1) vertexPositions64Low: vec3<f32>,\n @location(2) elevations: f32,\n @location(3) fillColors: vec4<f32>,\n @location(4) lineColors: vec4<f32>,\n @location(5) rowIndexes: u32,\n};\n\nstruct Varyings {\n @builtin(position) position: vec4<f32>,\n @location(0) vColor: vec4<f32>,\n @location(1) pickingColor: vec3<f32>,\n @location(2) clipCoordinates: vec2<f32>,\n};\n\n@vertex\nfn vertexMain(attributes: Attributes) -> Varyings {\n var outp: Varyings;\n\n var pos = attributes.vertexPositions;\n if (solidPolygon.extruded > 0.5) {\n pos.z += attributes.elevations * solidPolygon.elevationScale;\n }\n\n geometry.worldPosition = attributes.vertexPositions;\n geometry.pickingColor = picking_getPickingColorFromIndex(attributes.rowIndexes);\n\n let projectedPosition = project_position_to_clipspace_and_commonspace(\n pos,\n attributes.vertexPositions64Low,\n vec3<f32>(0.0)\n );\n geometry.position = projectedPosition.commonPosition;\n outp.position = projectedPosition.clipPosition;\n\n let normal = project_normal(vec3<f32>(0.0, 0.0, 1.0));\n geometry.normal = normal;\n\n let colors = select(\n attributes.fillColors,\n attributes.lineColors,\n solidPolygon.isWireframe > 0.5\n );\n outp.vColor = apply_polygon_color(colors, normal, geometry.position);\n outp.pickingColor = geometry.pickingColor;\n\n outp.clipCoordinates = geometry.position.xy;\n clip_filterPosition(&outp.position, geometry.worldPosition.xy);\n\n return outp;\n}\n\n@fragment\nfn fragmentMain(inp: Varyings) -> @location(0) vec4<f32> {\n geometry.uv = vec2<f32>(0.0, 0.0);\n\n clip_filterColor(inp.clipCoordinates);\n\n if (picking.isActive > 0.5) {\n if (!picking_isColorValid(inp.pickingColor)) {\n discard;\n }\n return vec4<f32>(inp.pickingColor, 1.0);\n }\n\n var fragColor = inp.vColor;\n\n if (picking.isHighlightActive > 0.5) {\n let highlightedObjectColor = picking_normalizeColor(picking.highlightedObjectColor);\n if (picking_isColorZero(abs(inp.pickingColor - highlightedObjectColor))) {\n let highLightAlpha = picking.highlightColor.a;\n let blendedAlpha = highLightAlpha + fragColor.a * (1.0 - highLightAlpha);\n if (blendedAlpha > 0.0) {\n let highLightRatio = highLightAlpha / blendedAlpha;\n fragColor = vec4<f32>(\n mix(fragColor.rgb, picking.highlightColor.rgb, highLightRatio),\n blendedAlpha\n );\n } else {\n fragColor = vec4<f32>(fragColor.rgb, 0.0);\n }\n }\n }\n\n return deckgl_premultiplied_alpha(fragColor);\n}\n\n":function(e){return`const RING_WINDING_ORDER_CW: bool = ${e?"true":"false"};\n\nfn project_offset_normal(vector: vec3<f32>) -> vec3<f32> {\n if (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT ||\n project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT_OFFSETS) {\n return normalize(vector * project.commonUnitsPerWorldUnit);\n }\n return project_normal(vector);\n}\n\nfn apply_polygon_color(\n colors: vec4<f32>,\n normal: vec3<f32>,\n position: vec4<f32>\n) -> vec4<f32> {\n if (solidPolygon.extruded > 0.5) {\n let lightColor = lighting_getLightColor2(\n colors.rgb,\n project.cameraPosition,\n position.xyz,\n normal\n );\n return vec4<f32>(lightColor, colors.a * layer.opacity);\n }\n return vec4<f32>(colors.rgb, colors.a * layer.opacity);\n}\n\n\nstruct Attributes {\n @location(0) positions: vec2<f32>,\n @location(1) vertexPositions: vec3<f32>,\n @location(2) vertexPositions64Low: vec3<f32>,\n @location(3) nextVertexPositions: vec3<f32>,\n @location(4) nextVertexPositions64Low: vec3<f32>,\n @location(5) vertexValid: f32,\n @location(6) elevations: f32,\n @location(7) fillColors: vec4<f32>,\n @location(8) lineColors: vec4<f32>,\n @location(9) rowIndexes: u32,\n};\n\nstruct Varyings {\n @builtin(position) position: vec4<f32>,\n @location(0) vColor: vec4<f32>,\n @location(1) pickingColor: vec3<f32>,\n @location(2) clipCoordinates: vec2<f32>,\n};\n\n@vertex\nfn vertexMain(attributes: Attributes) -> Varyings {\n var outp: Varyings;\n outp.position = vec4<f32>(0.0);\n outp.vColor = vec4<f32>(0.0);\n outp.pickingColor = picking_getPickingColorFromIndex(attributes.rowIndexes);\n outp.clipCoordinates = vec2<f32>(0.0);\n\n if (attributes.vertexValid < 0.5) {\n return outp;\n }\n\n let pos = select(attributes.nextVertexPositions, attributes.vertexPositions, RING_WINDING_ORDER_CW);\n let pos64Low = select(\n attributes.nextVertexPositions64Low,\n attributes.vertexPositions64Low,\n RING_WINDING_ORDER_CW\n );\n let nextPos = select(attributes.vertexPositions, attributes.nextVertexPositions, RING_WINDING_ORDER_CW);\n let nextPos64Low = select(\n attributes.vertexPositions64Low,\n attributes.nextVertexPositions64Low,\n RING_WINDING_ORDER_CW\n );\n\n let position = mix(pos, nextPos, attributes.positions.x);\n let position64Low = mix(pos64Low, nextPos64Low, attributes.positions.x);\n\n var worldPosition = position;\n if (solidPolygon.extruded > 0.5) {\n worldPosition.z += attributes.elevations * attributes.positions.y * solidPolygon.elevationScale;\n }\n\n geometry.worldPosition = position;\n geometry.pickingColor = picking_getPickingColorFromIndex(attributes.rowIndexes);\n\n let projectedPosition = project_position_to_clipspace_and_commonspace(\n worldPosition,\n position64Low,\n vec3<f32>(0.0)\n );\n geometry.position = projectedPosition.commonPosition;\n outp.position = projectedPosition.clipPosition;\n\n let normal = project_offset_normal(vec3<f32>(\n pos.y - nextPos.y + (pos64Low.y - nextPos64Low.y),\n nextPos.x - pos.x + (nextPos64Low.x - pos64Low.x),\n 0.0\n ));\n geometry.normal = normal;\n\n let colors = select(\n attributes.fillColors,\n attributes.lineColors,\n solidPolygon.isWireframe > 0.5\n );\n outp.vColor = apply_polygon_color(colors, normal, geometry.position);\n outp.pickingColor = geometry.pickingColor;\n\n outp.clipCoordinates = geometry.position.xy;\n clip_filterPosition(&outp.position, geometry.worldPosition.xy);\n\n return outp;\n}\n\n@fragment\nfn fragmentMain(inp: Varyings) -> @location(0) vec4<f32> {\n geometry.uv = vec2<f32>(0.0, 0.0);\n\n clip_filterColor(inp.clipCoordinates);\n\n if (picking.isActive > 0.5) {\n if (!picking_isColorValid(inp.pickingColor)) {\n discard;\n }\n return vec4<f32>(inp.pickingColor, 1.0);\n }\n\n var fragColor = inp.vColor;\n\n if (picking.isHighlightActive > 0.5) {\n let highlightedObjectColor = picking_normalizeColor(picking.highlightedObjectColor);\n if (picking_isColorZero(abs(inp.pickingColor - highlightedObjectColor))) {\n let highLightAlpha = picking.highlightColor.a;\n let blendedAlpha = highLightAlpha + fragColor.a * (1.0 - highLightAlpha);\n if (blendedAlpha > 0.0) {\n let highLightRatio = highLightAlpha / blendedAlpha;\n fragColor = vec4<f32>(\n mix(fragColor.rgb, picking.highlightColor.rgb, highLightRatio),\n blendedAlpha\n );\n } else {\n fragColor = vec4<f32>(fragColor.rgb, 0.0);\n }\n }\n }\n\n return deckgl_premultiplied_alpha(fragColor);\n}\n\n`}(t)}var gr=[0,0,0,255],hr={filled:!0,extruded:!1,wireframe:!1,_normalize:!0,_windingOrder:"CW",_full3d:!1,elevationScale:{type:"number",min:0,value:1},getPolygon:{type:"accessor",value:e=>e.polygon},getElevation:{type:"accessor",value:1e3},getFillColor:{type:"accessor",value:gr},getLineColor:{type:"accessor",value:gr},material:!0},vr={enter:(e,t)=>t.length?t.subarray(t.length-e.length):e},mr=class extends co{getShaders(e){const t=this.props._normalize||"CCW"!==this.props._windingOrder?1:0;return super.getShaders({vs:"top"===e?fr:dr,fs:"#version 300 es\n#define SHADER_NAME solid-polygon-layer-fragment-shader\nprecision highp float;\nin vec4 vColor;\nout vec4 fragColor;\nvoid main(void) {\nfragColor = vColor;\ngeometry.uv = vec2(0.);\nDECKGL_FILTER_COLOR(fragColor, geometry);\n}\n",source:pr(e,Boolean(t)),defines:{RING_WINDING_ORDER_CW:t},modules:[Ye,Ze,We,Je,cr,..."webgpu"===this.context.device.type?[ns]:[]]})}get wrapLongitude(){return!1}getBounds(){return this.getAttributeManager()?.getBounds(["vertexPositions"])}initializeState(){const{viewport:e}=this.context;let{coordinateSystem:t}=this.props;const{_full3d:n}=this.props;let i;e.isGeospatial&&"default"===t&&(t="lnglat"),"lnglat"===t&&(i=n?e.projectPosition.bind(e):e.projectFlat.bind(e)),this.setState({numInstances:0,polygonTesselator:new rr({preproject:i,fp64:this.use64bitPositions(),IndexType:Uint32Array})});const o=this.getAttributeManager(),s=!0,r="webgpu"===this.context.device.type;o.add({indices:{size:1,isIndexed:!0,update:this.calculateIndices,noAlloc:s},vertexPositions:{size:3,type:"float64",stepMode:"dynamic",fp64:this.use64bitPositions(),transition:vr,accessor:"getPolygon",update:this.calculatePositions,noAlloc:s,shaderAttributes:{nextVertexPositions:{vertexOffset:1}}},[r?"vertexValid":"instanceVertexValid"]:{size:1,type:r?"float32":"uint16",stepMode:"instance",update:this.calculateVertexValid,noAlloc:s},elevations:{size:1,stepMode:"dynamic",transition:vr,accessor:"getElevation",bufferGroup:"solid-polygon-instance-data"},fillColors:{size:this.props.colorFormat.length,type:"unorm8",stepMode:"dynamic",transition:vr,accessor:"getFillColor",defaultValue:gr,bufferGroup:"solid-polygon-instance-data"},lineColors:{size:this.props.colorFormat.length,type:"unorm8",stepMode:"dynamic",transition:vr,accessor:"getLineColor",defaultValue:gr,bufferGroup:"solid-polygon-instance-data"},rowIndexes:{size:1,type:"uint32",stepMode:"dynamic",accessor:(e,{index:t})=>e&&e.__source?e.__source.index:t,bufferGroup:"solid-polygon-instance-data"}})}getPickingInfo(e){const t=super.getPickingInfo(e),{index:n}=t,i=this.props.data;return i[0]&&i[0].__source&&(t.object=i.find(e=>e.__source.index===n)),t}disablePickingIndex(e){const t=this.props.data;if(t[0]&&t[0].__source)for(let n=0;n<t.length;n++)t[n].__source.index===e&&this._disablePickingIndex(n);else super.disablePickingIndex(e)}draw({uniforms:e}){const{extruded:t,filled:n,wireframe:i,elevationScale:o}=this.props,{topModel:s,sideModel:r,wireframeModel:a,polygonTesselator:l}=this.state,c={extruded:Boolean(t),elevationScale:o,isWireframe:!1};a&&i&&(a.setInstanceCount(l.instanceCount-1),a.shaderInputs.setProps({solidPolygon:{...c,isWireframe:!0}}),a.draw(this.context.renderPass)),r&&n&&(r.setInstanceCount(l.instanceCount-1),r.shaderInputs.setProps({solidPolygon:c}),r.draw(this.context.renderPass)),s&&n&&(s.setVertexCount(l.vertexCount),s.shaderInputs.setProps({solidPolygon:c}),s.draw(this.context.renderPass))}updateState(e){super.updateState(e),this.updateGeometry(e);const{props:t,oldProps:n,changeFlags:i}=e,o=this.getAttributeManager();(i.extensionsChanged||t.filled!==n.filled||t.extruded!==n.extruded)&&(this.state.models?.forEach(e=>e.destroy()),this.setState(this._getModels()),o.invalidateAll())}updateGeometry({props:e,oldProps:t,changeFlags:n}){if(n.dataChanged||n.updateTriggersChanged&&(n.updateTriggersChanged.all||n.updateTriggersChanged.getPolygon)){const{polygonTesselator:t}=this.state,i=e.data.attributes||{};t.updateGeometry({data:e.data,normalize:e._normalize,geometryBuffer:i.getPolygon,buffers:i,getGeometry:e.getPolygon,positionFormat:e.positionFormat,wrapLongitude:e.wrapLongitude,resolution:this.context.viewport.resolution,fp64:this.use64bitPositions(),dataChanged:n.dataChanged,full3d:e._full3d}),this.setState({numInstances:t.instanceCount,startIndices:t.vertexStarts}),n.dataChanged||this.getAttributeManager().invalidateAll()}}_getModels(){const{id:e,filled:t,extruded:n}=this.props;let i,o,s;if(t){const t=this.getShaders("top");t.defines={...t.defines,NON_INSTANCED_MODEL:1};let n=this.getAttributeManager().getBufferLayouts({isInstanced:!1});"webgpu"===this.context.device.type&&(n=n.filter(e=>"indices"!==e.name&&"vertexValid"!==e.name&&"instanceVertexValid"!==e.name&&"nextVertexPositions"!==e.name)),i=new xt(this.context.device,{...t,id:`${e}-top`,topology:"triangle-list",bufferLayout:n,isIndexed:!0,userData:{excludeAttributes:{vertexValid:!0,instanceVertexValid:!0,nextVertexPositions:!0}}})}if(n){let t=this.getAttributeManager().getBufferLayouts({isInstanced:!0});"webgpu"===this.context.device.type&&(t=t.filter(e=>"indices"!==e.name)),o=new xt(this.context.device,{...this.getShaders("side"),id:`${e}-side`,bufferLayout:t,geometry:new nt({topology:"triangle-strip",attributes:{positions:{size:2,value:new Float32Array([1,0,0,0,1,1,0,1])}}}),isInstanced:!0,userData:{excludeAttributes:{indices:!0}}}),s=new xt(this.context.device,{...this.getShaders("side"),id:`${e}-wireframe`,bufferLayout:t,geometry:new nt({topology:"line-strip",attributes:{positions:{size:2,value:new Float32Array([1,0,0,0,0,1,1,1])}}}),isInstanced:!0,userData:{excludeAttributes:{indices:!0}}})}return{models:[o,s,i].filter(Boolean),topModel:i,sideModel:o,wireframeModel:s}}calculateIndices(e){const{polygonTesselator:t}=this.state;e.startIndices=t.indexStarts,e.value=t.get("indices")}calculatePositions(e){const{polygonTesselator:t}=this.state;e.startIndices=t.vertexStarts,e.value=t.get("positions")}calculateVertexValid(e){const t=this.props.data.attributes?.instanceVertexValid?.value,n="webgpu"===this.context.device.type&&t?t:this.state.polygonTesselator.get("vertexValid");e.value="webgpu"===this.context.device.type&&n?Float32Array.from(n):n}};function _r({data:e,getIndex:t,dataRange:n,replace:i}){const{startRow:o=0,endRow:s=1/0}=n,r=e.length;let a=r,l=r;for(let f=0;f<r;f++){const n=t(e[f]);if(a>f&&n>=o&&(a=f),n>=s){l=f;break}}let c=a;const u=l-a!==i.length?e.slice(l):void 0;for(let f=0;f<i.length;f++)e[c++]=i[f];if(u){for(let t=0;t<u.length;t++)e[c++]=u[t];e.length=c}return{startRow:a,endRow:a+i.length}}mr.defaultProps=hr,mr.layerName="SolidPolygonLayer";var xr=[0,0,0,255],yr={stroked:!0,filled:!0,extruded:!1,elevationScale:1,wireframe:!1,_normalize:!0,_windingOrder:"CW",lineWidthUnits:"meters",lineWidthScale:1,lineWidthMinPixels:0,lineWidthMaxPixels:Number.MAX_SAFE_INTEGER,lineJointRounded:!1,lineMiterLimit:4,lineAntialiasing:!1,getPolygon:{type:"accessor",value:e=>e.polygon},getFillColor:{type:"accessor",value:[0,0,0,255]},getLineColor:{type:"accessor",value:xr},getLineWidth:{type:"accessor",value:1},getElevation:{type:"accessor",value:1e3},material:!0},br=class extends fo{initializeState(){this.state={paths:[],pathsDiff:null},this.props.getLineDashArray&&I.removed("getLineDashArray","PathStyleExtension")()}updateState({changeFlags:e}){const t=e.dataChanged||e.updateTriggersChanged&&(e.updateTriggersChanged.all||e.updateTriggersChanged.getPolygon);if(t&&Array.isArray(e.dataChanged)){const t=this.state.paths.slice(),n=e.dataChanged.map(e=>_r({data:t,getIndex:e=>e.__source.index,dataRange:e,replace:this._getPaths(e)}));this.setState({paths:t,pathsDiff:n})}else t&&this.setState({paths:this._getPaths(),pathsDiff:null})}_getPaths(e={}){const{data:t,getPolygon:n,positionFormat:i,_normalize:o}=this.props,s=[],r="XY"===i?2:3,{startRow:a,endRow:l}=e,{iterable:c,objectInfo:u}=$t(t,a,l);for(const f of c){u.index++;let e=n(f,u);o&&(e=ir(e,r));const{holeIndices:t}=e,i=e.positions||e;if(t)for(let n=0;n<=t.length;n++){const e=i.slice(t[n-1]||0,t[n]||i.length);s.push(this.getSubLayerRow({path:e},f,u.index))}else s.push(this.getSubLayerRow({path:i},f,u.index))}return s}renderLayers(){const{data:e,_dataDiff:t,stroked:n,filled:i,extruded:o,wireframe:s,_normalize:r,_windingOrder:a,elevationScale:l,transitions:c,positionFormat:u}=this.props,{lineWidthUnits:f,lineWidthScale:d,lineWidthMinPixels:p,lineWidthMaxPixels:g,lineJointRounded:h,lineMiterLimit:v,lineAntialiasing:m,lineDashJustified:_}=this.props,{getFillColor:x,getLineColor:y,getLineWidth:b,getLineDashArray:P,getElevation:C,getPolygon:w,updateTriggers:S,material:L}=this.props,{paths:A,pathsDiff:I}=this.state,E=this.getSubLayerClass("fill",mr),T=this.getSubLayerClass("stroke",Ys),O=this.shouldRenderSubLayer("fill",A)&&new E({_dataDiff:t,extruded:o,elevationScale:l,filled:i,wireframe:s,_normalize:r,_windingOrder:a,getElevation:C,getFillColor:x,getLineColor:o&&s?y:xr,material:L,transitions:c},this.getSubLayerProps({id:"fill",updateTriggers:S&&{getPolygon:S.getPolygon,getElevation:S.getElevation,getFillColor:S.getFillColor,lineColors:o&&s,getLineColor:S.getLineColor}}),{data:e,positionFormat:u,getPolygon:w});return[!o&&O,!o&&n&&this.shouldRenderSubLayer("stroke",A)&&new T({_dataDiff:I&&(()=>I),widthUnits:f,widthScale:d,widthMinPixels:p,widthMaxPixels:g,jointRounded:h,miterLimit:v,antialiasing:m,dashJustified:_,_pathType:"loop",transitions:c&&{getWidth:c.getLineWidth,getColor:c.getLineColor,getPath:c.getPolygon},getColor:this.getSubLayerAccessor(y),getWidth:this.getSubLayerAccessor(b),getDashArray:this.getSubLayerAccessor(P)},this.getSubLayerProps({id:"stroke",updateTriggers:S&&{getWidth:S.getLineWidth,getColor:S.getLineColor,getDashArray:S.getLineDashArray}}),{data:A,positionFormat:u,getPath:e=>e.path}),o&&O]}};br.layerName="PolygonLayer",br.defaultProps=yr;var Pr="layout(std140) uniform sdfUniforms {\n float gamma;\n bool enabled;\n float buffer;\n float outlineBuffer;\n vec4 outlineColor;\n} sdf;\n",Cr={name:"sdf",vs:Pr,fs:Pr,uniformTypes:{gamma:"f32",enabled:"f32",buffer:"f32",outlineBuffer:"f32",outlineColor:"vec4<f32>"}},wr={none:0,start:1,center:2,end:3},Sr={name:"text",vs:`layout(std140) uniform textUniforms {\n highp vec2 cutoffPixels;\n highp ivec2 align;\n highp float fontSize;\n bool flipY;\n} text;\n\n#define ALIGN_MODE_START ${wr.start}\n#define ALIGN_MODE_CENTER ${wr.center}\n#define ALIGN_MODE_END ${wr.end}\n`,getUniforms:({contentCutoffPixels:e=[0,0],contentAlignHorizontal:t="none",contentAlignVertical:n="none",fontSize:i,viewport:o})=>({cutoffPixels:e,align:[wr[t],wr[n]],fontSize:i,flipY:o?.flipY??!1}),uniformTypes:{cutoffPixels:"vec2<f32>",align:"vec2<i32>",fontSize:"f32",flipY:"f32"}};var Lr=function({collision:e=!1}={}){return`struct IconUniforms {\n sizeScale: f32,\n iconsTextureDim: vec2<f32>,\n sizeBasis: f32,\n sizeMinPixels: f32,\n sizeMaxPixels: f32,\n billboard: i32,\n sizeUnits: i32,\n alphaCutoff: f32\n};\n\nstruct TextUniforms {\n cutoffPixels: vec2<f32>,\n align: vec2<i32>,\n fontSize: f32,\n flipY: f32\n};\n\nstruct SdfUniforms {\n gamma: f32,\n enabled: f32,\n buffer: f32,\n outlineBuffer: f32,\n outlineColor: vec4<f32>\n};\n\n${e?"struct CollisionUniforms {\n sort: i32,\n enabled: i32\n};\n":""}\n\nconst ALIGN_MODE_START: i32 = 1;\nconst ALIGN_MODE_CENTER: i32 = 2;\nconst ALIGN_MODE_END: i32 = 3;\n\n@group(0) @binding(auto) var<uniform> icon: IconUniforms;\n@group(0) @binding(auto) var<uniform> text: TextUniforms;\n@group(0) @binding(auto) var<uniform> sdf: SdfUniforms;\n${e?"@group(0) @binding(auto) var<uniform> collision: CollisionUniforms;":""}\n@group(0) @binding(auto) var iconsTexture : texture_2d<f32>;\n@group(0) @binding(auto) var iconsTextureSampler : sampler;\n${e?"@group(0) @binding(auto) var collision_texture : texture_2d<f32>;\n":""}\n\nfn rotate_by_angle(vertex: vec2<f32>, angle_deg: f32) -> vec2<f32> {\n let angle_radian = angle_deg * PI / 180.0;\n let c = cos(angle_radian);\n let s = sin(angle_radian);\n let rotation = mat2x2<f32>(vec2<f32>(c, -s), vec2<f32>(s, c));\n return rotation * vertex;\n}\n\nfn get_pixel_offset_from_alignment(\n anchor: f32,\n extent: f32,\n clipStart: f32,\n clipEnd: f32,\n mode: i32\n) -> f32 {\n if (clipEnd < clipStart) {\n return 0.0;\n }\n if (mode == ALIGN_MODE_START) {\n return max(-(anchor + clipStart), 0.0);\n }\n if (mode == ALIGN_MODE_CENTER) {\n let minValue = max(0.0, anchor + clipStart);\n let maxValue = min(extent, anchor + clipEnd);\n if (minValue < maxValue) {\n return (minValue + maxValue) / 2.0 - anchor;\n }\n return 0.0;\n }\n if (mode == ALIGN_MODE_END) {\n return min(extent - (anchor + clipEnd), 0.0);\n }\n return 0.0;\n}\n\n${e?"fn collision_match(texCoords: vec2<f32>, pickingColor: vec3<f32>) -> f32 {\n let textureSize = vec2<i32>(textureDimensions(collision_texture));\n let pixelCoords = clamp(\n vec2<i32>(texCoords * vec2<f32>(textureSize)),\n vec2<i32>(0),\n textureSize - vec2<i32>(1)\n );\n let collisionPickingColor = textureLoad(collision_texture, pixelCoords, 0);\n let delta = dot(abs(collisionPickingColor.rgb - pickingColor), vec3<f32>(1.0));\n return step(delta, 0.001);\n}\n\nfn collision_is_visible(texCoords: vec2<f32>, pickingColor: vec3<f32>) -> f32 {\n if (collision.enabled == 0) {\n return 1.0;\n }\n\n var accumulator = 0.0;\n let stepSize = vec2<f32>(1.0) / project.viewportSize;\n\n for (var i: i32 = -2; i <= 2; i = i + 1) {\n for (var j: i32 = -2; j <= 2; j = j + 1) {\n let delta = vec2<f32>(f32(j), f32(i)) * stepSize;\n accumulator = accumulator + collision_match(texCoords + delta, pickingColor);\n }\n }\n\n return pow(accumulator / 25.0, 2.2);\n}\n":""}\n\nstruct Attributes {\n @location(0) positions: vec2<f32>,\n\n @location(1) instancePositions: vec3<f32>,\n @location(2) instancePositions64Low: vec3<f32>,\n @location(3) instanceSizes: f32,\n @location(4) instanceAngles: f32,\n @location(5) instanceColors: vec4<f32>,\n @location(6) instanceIconFrames: vec4<f32>,\n @location(7) instanceColorModes: f32,\n @location(8) instanceOffsets: vec2<f32>,\n @location(9) instancePixelOffset: vec2<f32>,\n @location(10) rowIndexes: u32,\n @location(11) instanceClipRect: vec4<f32>,\n ${e?"@location(12) collisionPriorities: f32,":""}\n};\n\nstruct Varyings {\n @builtin(position) position: vec4<f32>,\n\n @location(0) vColorMode: f32,\n @location(1) vColor: vec4<f32>,\n @location(2) vTextureCoords: vec2<f32>,\n @location(3) uv: vec2<f32>,\n @location(4) pickingColor: vec3<f32>,\n};\n\n@vertex\nfn vertexMain(inp: Attributes) -> Varyings {\n geometry.worldPosition = inp.instancePositions;\n geometry.uv = inp.positions;\n geometry.pickingColor = picking_getPickingColorFromIndex(inp.rowIndexes);\n\n var outp: Varyings;\n outp.uv = inp.positions;\n\n let iconSize = inp.instanceIconFrames.zw;\n\n let sizePixels = clamp(\n project_unit_size_to_pixel(inp.instanceSizes * icon.sizeScale, icon.sizeUnits),\n icon.sizeMinPixels, icon.sizeMaxPixels\n );\n let instanceScale = sizePixels / text.fontSize;\n\n var pixelOffset = inp.positions / 2.0 * iconSize + inp.instanceOffsets;\n pixelOffset = rotate_by_angle(pixelOffset, inp.instanceAngles) * instanceScale;\n pixelOffset = pixelOffset + inp.instancePixelOffset;\n pixelOffset.y = pixelOffset.y * -1.0;\n\n var pos: vec4<f32>;\n var anchorPosScreen: vec2<f32>;\n if (icon.billboard != 0) {\n pos = project_position_to_clipspace(inp.instancePositions, inp.instancePositions64Low, vec3<f32>(0.0));\n anchorPosScreen = pos.xy / pos.w;\n\n let clipOffset = project_pixel_size_to_clipspace(pixelOffset);\n pos = vec4<f32>(pos.x + clipOffset.x, pos.y + clipOffset.y, pos.z, pos.w);\n } else {\n var offsetCommon = vec3<f32>(project_pixel_size_vec2(pixelOffset), 0.0);\n if (text.flipY > 0.5) {\n offsetCommon.y = offsetCommon.y * -1.0;\n }\n let anchorPos = project_position_to_clipspace(inp.instancePositions, inp.instancePositions64Low, vec3<f32>(0.0));\n anchorPosScreen = anchorPos.xy / anchorPos.w;\n pos = project_position_to_clipspace(inp.instancePositions, inp.instancePositions64Low, offsetCommon);\n }\n\n anchorPosScreen = vec2<f32>(anchorPosScreen.x + 1.0, 1.0 - anchorPosScreen.y) / 2.0 *\n project.viewportSize / project.devicePixelRatio;\n var xy = project_size_vec2(inp.instanceClipRect.xy) * project.scale;\n var wh = project_size_vec2(inp.instanceClipRect.zw) * project.scale;\n\n if (text.flipY > 0.5) {\n xy.y = -xy.y - wh.y;\n }\n if (text.align.x > 0 || text.align.y > 0) {\n let viewportPixels = project.viewportSize / project.devicePixelRatio;\n let scrollPixels = vec2<f32>(\n get_pixel_offset_from_alignment(anchorPosScreen.x, viewportPixels.x, xy.x, xy.x + wh.x, text.align.x),\n -get_pixel_offset_from_alignment(anchorPosScreen.y, viewportPixels.y, -xy.y - wh.y, -xy.y, text.align.y)\n );\n pixelOffset = pixelOffset + scrollPixels;\n let scrollClipOffset = project_pixel_size_to_clipspace(scrollPixels);\n pos.x = pos.x + scrollClipOffset.x;\n pos.y = pos.y + scrollClipOffset.y;\n }\n\n if (inp.instanceClipRect.z >= 0.0) {\n if (pixelOffset.x < xy.x || pixelOffset.x > xy.x + wh.x) {\n pos = vec4<f32>(0.0);\n } else if (text.cutoffPixels.x > 0.0) {\n let viewportWidth = project.viewportSize.x / project.devicePixelRatio;\n let left = max(anchorPosScreen.x + xy.x, 0.0);\n let right = min(anchorPosScreen.x + xy.x + wh.x, viewportWidth);\n if (right - left < text.cutoffPixels.x) {\n pos = vec4<f32>(0.0);\n }\n }\n }\n if (inp.instanceClipRect.w >= 0.0) {\n if (pixelOffset.y < xy.y || pixelOffset.y > xy.y + wh.y) {\n pos = vec4<f32>(0.0);\n } else if (text.cutoffPixels.y > 0.0) {\n let viewportHeight = project.viewportSize.y / project.devicePixelRatio;\n let top = max(anchorPosScreen.y - xy.y - wh.y, 0.0);\n let bottom = min(anchorPosScreen.y - xy.y, viewportHeight);\n if (bottom - top < text.cutoffPixels.y) {\n pos = vec4<f32>(0.0);\n }\n }\n }\n\n ${e?" if (collision.sort != 0) {\n pos.z = -0.001 * inp.collisionPriorities * pos.w;\n }\n ":""}\n\n let uvMix = (inp.positions.xy + vec2<f32>(1.0, 1.0)) * 0.5;\n outp.vTextureCoords = mix(inp.instanceIconFrames.xy, inp.instanceIconFrames.xy + iconSize, uvMix) / icon.iconsTextureDim;\n\n outp.position = pos;\n outp.vColor = inp.instanceColors;\n outp.vColorMode = inp.instanceColorModes;\n outp.pickingColor = picking_getPickingColorFromIndex(inp.rowIndexes);\n\n return outp;\n}\n\n@fragment\nfn fragmentMain(inp: Varyings) -> @location(0) vec4<f32> {\n geometry.uv = inp.uv;\n\n let texColor = textureSample(iconsTexture, iconsTextureSampler, inp.vTextureCoords);\n var alpha = texColor.a;\n var color = inp.vColor;\n\n if (sdf.enabled > 0.5) {\n let distance = alpha;\n alpha = smoothstep(sdf.buffer - sdf.gamma, sdf.buffer + sdf.gamma, distance);\n\n if (sdf.outlineBuffer > 0.0) {\n let inFill = alpha;\n let inBorder = smoothstep(sdf.outlineBuffer - sdf.gamma, sdf.outlineBuffer + sdf.gamma, distance);\n color = mix(sdf.outlineColor, inp.vColor, inFill);\n alpha = inBorder;\n }\n } else if (inp.vColorMode == 0.0) {\n color = texColor;\n }\n\n var a = alpha * color.a * layer.opacity;\n if (a < icon.alphaCutoff) {\n discard;\n }\n\n if (picking.isActive > 0.5) {\n if (!picking_isColorValid(inp.pickingColor)) {\n discard;\n }\n return vec4<f32>(inp.pickingColor, 1.0);\n }\n\n ${e?" let collisionFade = collision_is_visible(inp.position.xy / project.viewportSize, inp.pickingColor);\n a = a * collisionFade;\n if (a <= 0.0001) {\n discard;\n }\n ":""}\n\n var fragColor = deckgl_premultiplied_alpha(vec4<f32>(color.rgb, a));\n\n if (picking.isHighlightActive > 0.5) {\n let highlightedObjectColor = picking_normalizeColor(picking.highlightedObjectColor);\n if (picking_isColorZero(abs(inp.pickingColor - highlightedObjectColor))) {\n let highLightAlpha = picking.highlightColor.a;\n let blendedAlpha = highLightAlpha + fragColor.a * (1.0 - highLightAlpha);\n if (blendedAlpha > 0.0) {\n let highLightRatio = highLightAlpha / blendedAlpha;\n fragColor = vec4<f32>(\n mix(fragColor.rgb, picking.highlightColor.rgb, highLightRatio),\n blendedAlpha\n );\n } else {\n fragColor = vec4<f32>(fragColor.rgb, 0.0);\n }\n }\n }\n\n return fragColor;\n}\n`}(),Ar=.75,Ir=class extends Uo{getShaders(){const e=super.getShaders();return{...e,modules:[...e.modules,Sr,Cr],vs:"#version 300 es\n#define SHADER_NAME multi-icon-layer-vertex-shader\nin vec2 positions;\nin vec3 instancePositions;\nin vec3 instancePositions64Low;\nin float instanceSizes;\nin float instanceAngles;\nin vec4 instanceColors;\nin float rowIndexes;\nin vec4 instanceIconFrames;\nin float instanceColorModes;\nin vec2 instanceOffsets;\nin vec2 instancePixelOffset;\nin vec4 instanceClipRect;\nout float vColorMode;\nout vec4 vColor;\nout vec2 vTextureCoords;\nout vec2 uv;\nvec2 rotate_by_angle(vec2 vertex, float angle) {\nfloat angle_radian = angle * PI / 180.0;\nfloat cos_angle = cos(angle_radian);\nfloat sin_angle = sin(angle_radian);\nmat2 rotationMatrix = mat2(cos_angle, -sin_angle, sin_angle, cos_angle);\nreturn rotationMatrix * vertex;\n}\nfloat getPixelOffsetFromAlignment(float anchor, float extent, float clipStart, float clipEnd, int mode) {\nif (clipEnd < clipStart) return 0.0;\nif (mode == ALIGN_MODE_START) {\nreturn max(- (anchor + clipStart), 0.0);\n}\nif (mode == ALIGN_MODE_CENTER) {\nfloat _min = max(0., anchor + clipStart);\nfloat _max = min(extent, anchor + clipEnd);\nreturn _min < _max ? (_min + _max) / 2.0 - anchor : 0.0;\n}\nif (mode == ALIGN_MODE_END) {\nreturn min(extent - (anchor + clipEnd), 0.);\n}\nreturn 0.0;\n}\nvoid main(void) {\ngeometry.worldPosition = instancePositions;\ngeometry.uv = positions;\ngeometry.pickingColor = picking_getPickingColorFromIndex(rowIndexes);\nuv = positions;\nvec2 iconSize = instanceIconFrames.zw;\nfloat sizePixels = clamp(\nproject_size_to_pixel(instanceSizes * icon.sizeScale, icon.sizeUnits),\nicon.sizeMinPixels, icon.sizeMaxPixels\n);\nfloat instanceScale = sizePixels / text.fontSize;\nvec2 pixelOffset = positions / 2.0 * iconSize + instanceOffsets;\npixelOffset = rotate_by_angle(pixelOffset, instanceAngles) * instanceScale;\npixelOffset += instancePixelOffset;\npixelOffset.y *= -1.0;\nvec2 anchorPosScreen;\nif (icon.billboard) {\ngl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.0), geometry.position);\nanchorPosScreen = gl_Position.xy / gl_Position.w;\nDECKGL_FILTER_GL_POSITION(gl_Position, geometry);\nvec3 offset = vec3(pixelOffset, 0.0);\nDECKGL_FILTER_SIZE(offset, geometry);\ngl_Position.xy += project_pixel_size_to_clipspace(offset.xy);\n} else {\nvec3 offset_common = vec3(project_pixel_size(pixelOffset), 0.0);\nif (text.flipY) {\noffset_common.y *= -1.;\n}\nDECKGL_FILTER_SIZE(offset_common, geometry);\nvec4 anchorPos = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.0));\nanchorPosScreen = anchorPos.xy / anchorPos.w;\ngl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, offset_common, geometry.position);\nDECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n}\nanchorPosScreen = vec2(anchorPosScreen.x + 1.0, 1.0 - anchorPosScreen.y) / 2.0 * project.viewportSize / project.devicePixelRatio;\nvec2 xy = project_size_to_pixel(instanceClipRect.xy);\nvec2 wh = project_size_to_pixel(instanceClipRect.zw);\nif (text.flipY) {\nxy.y = -xy.y - wh.y;\n}\nif (text.align.x > 0 || text.align.y > 0) {\nvec2 viewportPixels = project.viewportSize / project.devicePixelRatio;\nvec2 scrollPixels = vec2(\ngetPixelOffsetFromAlignment(anchorPosScreen.x, viewportPixels.x, xy.x, xy.x + wh.x, text.align.x),\n-getPixelOffsetFromAlignment(anchorPosScreen.y, viewportPixels.y, -xy.y - wh.y, -xy.y, text.align.y)\n);\npixelOffset += scrollPixels;\ngl_Position.xy += project_pixel_size_to_clipspace(scrollPixels);\n}\nif (instanceClipRect.z >= 0.) {\nif (pixelOffset.x < xy.x || pixelOffset.x > xy.x + wh.x) {\ngl_Position = vec4(0.0);\n}\nelse if (text.cutoffPixels.x > 0.) {\nfloat vpWidth = project.viewportSize.x / project.devicePixelRatio;\nfloat l = max(anchorPosScreen.x + xy.x, 0.0);\nfloat r = min(anchorPosScreen.x + xy.x + wh.x, vpWidth);\nif (r - l < text.cutoffPixels.x) {\ngl_Position = vec4(0.0);\n}\n}\n}\nif (instanceClipRect.w >= 0.) {\nif (pixelOffset.y < xy.y || pixelOffset.y > xy.y + wh.y) {\ngl_Position = vec4(0.0);\n}\nelse if (text.cutoffPixels.y > 0.) {\nfloat vpHeight = project.viewportSize.y / project.devicePixelRatio;\nfloat t = max(anchorPosScreen.y - xy.y - wh.y, 0.0);\nfloat b = min(anchorPosScreen.y - xy.y, vpHeight);\nif (b - t < text.cutoffPixels.y) {\ngl_Position = vec4(0.0);\n}\n}\n}\nvTextureCoords = mix(\ninstanceIconFrames.xy,\ninstanceIconFrames.xy + iconSize,\n(positions.xy + 1.0) / 2.0\n) / icon.iconsTextureDim;\nvColor = instanceColors;\nDECKGL_FILTER_COLOR(vColor, geometry);\nvColorMode = instanceColorModes;\n}\n",fs:"#version 300 es\n#define SHADER_NAME multi-icon-layer-fragment-shader\nprecision highp float;\nuniform sampler2D iconsTexture;\nin vec4 vColor;\nin vec2 vTextureCoords;\nin vec2 uv;\nout vec4 fragColor;\nvoid main(void) {\ngeometry.uv = uv;\nif (!bool(picking.isActive)) {\nfloat alpha = texture(iconsTexture, vTextureCoords).a;\nvec4 color = vColor;\nif (sdf.enabled) {\nfloat distance = alpha;\nalpha = smoothstep(sdf.buffer - sdf.gamma, sdf.buffer + sdf.gamma, distance);\nif (sdf.outlineBuffer > 0.0) {\nfloat inFill = alpha;\nfloat inBorder = smoothstep(sdf.outlineBuffer - sdf.gamma, sdf.outlineBuffer + sdf.gamma, distance);\ncolor = mix(sdf.outlineColor, vColor, inFill);\nalpha = inBorder;\n}\n}\nfloat a = alpha * color.a;\nif (a < icon.alphaCutoff) {\ndiscard;\n}\nfragColor = vec4(color.rgb, a * layer.opacity);\n}\nDECKGL_FILTER_COLOR(fragColor, geometry);\n}\n",source:Lr}}initializeState(){super.initializeState();const e=this.getAttributeManager();e.attributes.instanceIconDefs.settings.update=this.calculateInstanceIconDefs,e.addInstanced({rowIndexes:{type:"uint32",size:1,bufferGroup:"icon-instance-data",accessor:(e,{index:t})=>t},instanceClipRect:{size:4,bufferGroup:"icon-instance-data",accessor:"getContentBox",defaultValue:[0,0,-1,-1]}})}updateState(e){super.updateState(e);const{props:t,oldProps:n,changeFlags:i}=e,{outlineColor:o}=t;if(i.extensionsChanged){this.state.fillModel?.destroy();const e="webgpu"===this.context.device.type?this._getModel(`${this.props.id}-fill`):void 0;this.setState({fillModel:e,models:e?[this.state.model,e]:[this.state.model]})}if(i.updateTriggersChanged&&(i.updateTriggersChanged.getIcon||i.updateTriggersChanged.getIconOffsets)&&this.getAttributeManager().invalidate("instanceIconDefs"),o!==n.outlineColor){const e=[o[0]/255,o[1]/255,o[2]/255,(o[3]??255)/255];this.setState({outlineColor:e})}!t.sdf&&t.outlineWidth&&I.warn(`${this.id}: fontSettings.sdf is required to render outline`)()}draw(e){const{sdf:t,smoothing:n,fontSize:i,outlineWidth:o,contentCutoffPixels:s,contentAlignHorizontal:r,contentAlignVertical:a}=this.props,{outlineColor:l}=this.state,c=o?Math.max(n,Ar*(1-o)):-1,u=this.state.model,f={buffer:Ar,outlineBuffer:c,gamma:n,enabled:Boolean(t),outlineColor:l},d={contentCutoffPixels:s,contentAlignHorizontal:r,contentAlignVertical:a,fontSize:i,viewport:this.context.viewport};if(u.shaderInputs.setProps({sdf:f,text:d}),super.draw(e),t&&o){const{iconManager:e}=this.state;if(e.getTexture()){const e=this.state.fillModel||u;e.shaderInputs.setProps({sdf:{...f,outlineBuffer:Ar},text:d}),this._drawModel(e)}}}calculateInstanceIconDefs(e,{startRow:t,endRow:n}){const{data:i,getIcon:o,getIconOffsets:s}=this.props;let r=e.getVertexOffset(t);const a=e.value,{iterable:l,objectInfo:c}=$t(i,t,n);for(const u of l){c.index++;const t=o(u,c),n=s(u,c);if(t){let i=0;for(const o of Array.from(t)){const t=super.getInstanceIconDef(o);t[0]=n[2*i],t[1]+=n[2*i+1],t[6]=1,a.set(t,r),r+=e.size,i++}}}}};Ir.defaultProps={getIconOffsets:{type:"accessor",value:e=>e.offsets},getContentBox:{type:"accessor",value:[0,0,-1,-1]},fontSize:1,alphaCutoff:.001,smoothing:.1,outlineWidth:0,outlineColor:{type:"color",value:[0,0,0,255]},contentCutoffPixels:{type:"array",value:[0,0]},contentAlignHorizontal:"none",contentAlignVertical:"none"},Ir.layerName="MultiIconLayer";var Er=1e20,Tr=/* @__PURE__ */new Float64Array(256);for(let ga=0;ga<256;ga++){const e=.5-Math.pow(ga/255,1/2.2);Tr[ga]=e*Math.abs(e)}Tr[255]=-1e20;var Or=class{constructor({fontSize:e=24,buffer:t=3,radius:n=8,cutoff:i=.25,fontFamily:o="sans-serif",fontWeight:s="normal",fontStyle:r="normal",lang:a=null}={}){t=this.buffer=Math.round(t),this.radius=n,this.cutoff=i,this.lang=a;const l=this.size=Math.ceil(e)+4*t,c=this._createCanvas(l),u=this.ctx=c.getContext("2d",{willReadFrequently:!0});u.font=`${r} ${s} ${e}px ${o}`,u.textBaseline="alphabetic",u.textAlign="left",u.fillStyle="black",a&&(u.lang=a);const f=(this.maxGlyphDim=l-t)+2*t;this.gridOuter=new Float64Array(f*f),this.gridInner=new Float64Array(f*f),this.f=new Float64Array(f),this.z=new Float64Array(f+1),this.v=new Uint16Array(f)}_createCanvas(e){if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(e,e);const t=document.createElement("canvas");return t.width=t.height=e,t}draw(e){const{width:t,actualBoundingBoxAscent:n,actualBoundingBoxDescent:i,actualBoundingBoxLeft:o,actualBoundingBoxRight:s}=this.ctx.measureText(e),r=Math.ceil(n),a=Math.floor(-o),l=Math.max(0,Math.min(this.maxGlyphDim,Math.ceil(s)-a)),c=Math.max(0,Math.min(this.maxGlyphDim,r+Math.ceil(i))),u=l+2*this.buffer,f=c+2*this.buffer,d=u*f,p=new Uint8ClampedArray(d),g={data:p,width:u,height:f,glyphWidth:l,glyphHeight:c,glyphTop:r,glyphLeft:a,glyphAdvance:t};if(0===l||0===c)return g;const{ctx:h,buffer:v,gridInner:m,gridOuter:_}=this;h.clearRect(v,v,l,c),h.fillText(e,v-a,v+r);const x=h.getImageData(v,v,l,c);_.fill(Er,0,d),m.fill(0,0,d);let y=3;for(let w=0;w<c;w++){let e=(w+v)*u+v;for(let t=0;t<l;t++,y+=4,e++){const t=x.data[y];if(0===t)continue;const n=Tr[t];_[e]=Math.max(0,n),m[e]=Math.max(0,-n)}}zr(_,0,0,u,f,u,this.f,this.v,this.z,v);const b=Math.min(v,1);zr(m,v-b,v-b,l+2*b,c+2*b,u,this.f,this.v,this.z);const P=255/this.radius,C=255*(1-this.cutoff);for(let w=0;w<d;w++){const e=Math.sqrt(_[w])-Math.sqrt(m[w]);p[w]=C-P*e}return g}};function zr(e,t,n,i,o,s,r,a,l,c=0){for(let u=t+c;u<t+i-c;u++)Mr(e,n*s+u,s,o,r,a,l);for(let u=n;u<n+o;u++)Mr(e,u*s+t,1,i,r,a,l)}function Mr(e,t,n,i,o,s,r){s[0]=0,r[0]=-1e20,r[1]=Er,o[0]=e[t];for(let a=1,l=0;a<i;a++){const i=o[a]=e[t+a*n],c=a*a;let u;do{const e=s[l];u=(i-o[e]+c-e*e)/(a-e)/2}while(u<=r[l]&&--l>-1);l++,s[l]=a,r[l]=u,r[l+1]=Er}for(let a=0,l=0;a<i;a++){for(;r[l+1]<a;)l++;const i=s[l],c=a-i;e[t+a*n]=o[i]+c*c}}var Rr=[];function Br(e,t,n,i){let o=0;for(let s=t;s<n;s++){const t=e[s];o+=i[t]?.advance||0}return o}function kr(e,t,n,i,o,s){let r=t,a=0;for(let l=t;l<n;l++){const t=Br(e,l,l+1,o);a+t>i&&(r<l&&s.push(l),r=l,a=0),a+=t}return a}function Fr(e,t,n,i,o=0,s){void 0===s&&(s=e.length);const r=[];return"break-all"===t?kr(e,o,s,n,i,r):function(e,t,n,i,o,s){let r=t,a=t,l=t,c=0;for(let u=t;u<n;u++)if(" "===e[u]?l=u+1:" "!==e[u+1]&&u+1!==n||(l=u+1),l>a){let t=Br(e,a,l,o);c+t>i&&(r<a&&(s.push(a),r=a,c=0),t>i&&(t=kr(e,a,l,i,o,s),r=s[s.length-1])),a=l,c+=t}}(e,o,s,n,i,r),r}function Nr(e,t,n,i,o,s){let r=0,a=0;for(let l=t;l<n;l++){const t=i[e[l]];t&&(a=Math.max(a,t.height))}for(let l=t;l<n;l++){const t=e[l],n=i[t];n?(o[l]=r+n.anchorX,r+=n.advance):(I.warn(`Missing character: ${t} (${t.codePointAt(0)})`)(),o[l]=r,r+=32)}s[0]=r,s[1]=a}var Dr=class{constructor(e=5){this._cache={},this._order=[],this.limit=e}get(e){const t=this._cache[e];return t&&(this._deleteOrder(e),this._appendOrder(e)),t}set(e,t){this._cache[e]?(this.delete(e),this._cache[e]=t,this._appendOrder(e)):(Object.keys(this._cache).length===this.limit&&this.delete(this._order[0]),this._cache[e]=t,this._appendOrder(e))}delete(e){this._cache[e]&&(delete this._cache[e],this._deleteOrder(e))}_deleteOrder(e){const t=this._order.indexOf(e);t>=0&&this._order.splice(t,1)}_appendOrder(e){this._order.push(e)}};var jr={fontFamily:"Monaco, monospace",fontWeight:"normal",characterSet:function(){const e=[];for(let t=32;t<128;t++)e.push(String.fromCharCode(t));return e}(),fontSize:64,buffer:4,sdf:!1,cutoff:.25,radius:12,smoothing:.1},Ur=new Dr(3);function Gr(e,t,n,i){e.font=`${i} ${n}px ${t}`,e.fillStyle="#000",e.textBaseline="alphabetic",e.textAlign="left"}var Vr=class{constructor(){this.props={...jr}}get atlas(){return this._atlas}get mapping(){return this._atlas&&this._atlas.mapping}setProps(e={}){Object.assign(this.props,e),e._getFontRenderer&&(this._getFontRenderer=e._getFontRenderer),this._key=this._getKey();const t=function(e,t){let n;n="string"==typeof t?new Set(Array.from(t)):new Set(t);const i=Ur.get(e);if(!i)return n;for(const o in i.mapping)n.has(o)&&n.delete(o);return n}(this._key,this.props.characterSet),n=Ur.get(this._key);if(n&&0===t.size)return void(this._atlas!==n&&(this._atlas=n));const i=this._generateFontAtlas(t,n);this._atlas=i,Ur.set(this._key,i)}_generateFontAtlas(e,t){const{fontFamily:n,fontWeight:i,fontSize:o,buffer:s,sdf:r,radius:a,cutoff:l}=this.props;let c=t&&t.data;c||(c=document.createElement("canvas"),c.width=1024);const u=c.getContext("2d",{willReadFrequently:!0});Gr(u,n,o,i);const f=e=>function(e,t,n){if(void 0===n){const n=e.measureText("A");return n.fontBoundingBoxAscent?{advance:0,width:0,ascent:Math.ceil(n.fontBoundingBoxAscent),descent:Math.ceil(n.fontBoundingBoxDescent)}:{advance:0,width:0,ascent:.9*t,descent:.3*t}}const i=e.measureText(n);return i.actualBoundingBoxAscent?{advance:i.width,width:Math.ceil(i.actualBoundingBoxRight-i.actualBoundingBoxLeft),ascent:Math.ceil(i.actualBoundingBoxAscent),descent:Math.ceil(i.actualBoundingBoxDescent)}:{advance:i.width,width:i.width,ascent:.9*t,descent:.3*t}}(u,o,e);let d;this._getFontRenderer?d=this._getFontRenderer(this.props):r&&(d={measure:f,draw:$r(this.props)});const{mapping:p,canvasHeight:g,xOffset:h,yOffsetMin:v,yOffsetMax:m}=function({characterSet:e,measureText:t,buffer:n,maxCanvasWidth:i,mapping:o={},xOffset:s=0,yOffsetMin:r=0,yOffsetMax:a=0}){let l=s,c=r,u=a;for(const d of e)if(!o[d]){const{advance:e,width:s,ascent:r,descent:a}=t(d),f=r+a;l+s+2*n>i&&(l=0,c=u),o[d]={x:l+n,y:c+n,width:s,height:f,advance:e,anchorX:s/2,anchorY:r},l+=s+2*n,u=Math.max(u,c+f+2*n)}return{mapping:o,xOffset:l,yOffsetMin:c,yOffsetMax:u,canvasHeight:(f=u,Math.pow(2,Math.ceil(Math.log2(f))))};var f}({measureText:e=>d?d.measure(e):f(e),buffer:s,characterSet:e,maxCanvasWidth:1024,...t&&{mapping:t.mapping,xOffset:t.xOffset,yOffsetMin:t.yOffsetMin,yOffsetMax:t.yOffsetMax}});if(c.height!==g){const e=c.height>0?u.getImageData(0,0,c.width,c.height):null;c.height=g,e&&u.putImageData(e,0,0)}if(Gr(u,n,o,i),d)for(const x of e){const e=p[x],t=e.width,{data:n,left:i=0,top:o=0}=d.draw(x),s=e.x-i,r=e.y-o,a=Math.max(0,Math.round(s)),l=Math.max(0,Math.round(r)),f=Math.min(n.width,c.width-a),g=Math.min(n.height,c.height-l);u.putImageData(n,a,l,0,0,f,g),e.x=a,e.y=l,e.width=f,e.height=g,e.anchorX+=f/2-i-t/2,e.anchorY+=o}else for(const x of e){const e=p[x];u.fillText(x,e.x,e.y+e.anchorY)}const _=d?d.measure():f();return{baselineOffset:(_.ascent-_.descent)/2,xOffset:h,yOffsetMin:v,yOffsetMax:m,mapping:p,data:c,width:c.width,height:c.height}}_getKey(){const{fontFamily:e,fontWeight:t,fontSize:n,buffer:i,sdf:o,radius:s,cutoff:r}=this.props;return o?`${e} ${t} ${n} ${i} ${s} ${r}`:`${e} ${t} ${n} ${i}`}};function $r({fontSize:e,buffer:t,radius:n,cutoff:i,fontFamily:o,fontWeight:s}){const r=new Or({fontSize:e,buffer:t,radius:n,cutoff:i,fontFamily:o,fontWeight:`${s}`});return e=>{const{data:n,width:i,height:o}=r.draw(e),s=new ImageData(i,o);return function(e,t){for(let n=0;n<e.length;n++)t.data[4*n+3]=e[n]}(n,s),{data:s,left:t,top:t}}}var Wr="layout(std140) uniform textBackgroundUniforms {\n bool billboard;\n float sizeScale;\n float sizeMinPixels;\n float sizeMaxPixels;\n vec4 borderRadius;\n vec4 padding;\n highp int sizeUnits;\n bool stroked;\n} textBackground;\n",Hr={name:"textBackground",source:"struct TextBackgroundUniforms {\n billboard: f32,\n sizeScale: f32,\n sizeMinPixels: f32,\n sizeMaxPixels: f32,\n borderRadius: vec4<f32>,\n padding: vec4<f32>,\n sizeUnits: i32,\n stroked: f32,\n};\n\n@group(0) @binding(auto) var<uniform> textBackground: TextBackgroundUniforms;\n",vs:Wr,fs:Wr,uniformTypes:{billboard:"f32",sizeScale:"f32",sizeMinPixels:"f32",sizeMaxPixels:"f32",borderRadius:"vec4<f32>",padding:"vec4<f32>",sizeUnits:"i32",stroked:"f32"}},Zr={billboard:!0,sizeScale:1,sizeUnits:"pixels",sizeMinPixels:0,sizeMaxPixels:Number.MAX_SAFE_INTEGER,fontSize:1,borderRadius:{type:"object",value:0},padding:{type:"array",value:[0,0,0,0]},getPosition:{type:"accessor",value:e=>e.position},getSize:{type:"accessor",value:1},getAngle:{type:"accessor",value:0},getPixelOffset:{type:"accessor",value:[0,0]},getBoundingRect:{type:"accessor",value:[0,0,0,0]},getClipRect:{type:"accessor",value:[0,0,-1,-1]},getFillColor:{type:"accessor",value:[0,0,0,255]},getLineColor:{type:"accessor",value:[0,0,0,255]},getLineWidth:{type:"accessor",value:1}},Yr=class extends co{getShaders(){return super.getShaders({vs:"#version 300 es\n#define SHADER_NAME text-background-layer-vertex-shader\nin vec2 positions;\nin vec3 instancePositions;\nin vec3 instancePositions64Low;\nin vec4 instanceRects;\nin vec4 instanceClipRect;\nin float instanceSizes;\nin float instanceAngles;\nin vec2 instancePixelOffsets;\nin float instanceLineWidths;\nin vec4 instanceFillColors;\nin vec4 instanceLineColors;\nout vec4 vFillColor;\nout vec4 vLineColor;\nout float vLineWidth;\nout vec2 uv;\nout vec2 dimensions;\nvec2 rotate_by_angle(vec2 vertex, float angle) {\nfloat angle_radian = radians(angle);\nfloat cos_angle = cos(angle_radian);\nfloat sin_angle = sin(angle_radian);\nmat2 rotationMatrix = mat2(cos_angle, -sin_angle, sin_angle, cos_angle);\nreturn rotationMatrix * vertex;\n}\nvoid main(void) {\ngeometry.worldPosition = instancePositions;\ngeometry.uv = positions;\ngeometry.pickingColor = picking_getPickingColorFromInstanceID();\nuv = positions;\nvLineWidth = instanceLineWidths;\nfloat sizePixels = clamp(\nproject_size_to_pixel(instanceSizes * textBackground.sizeScale, textBackground.sizeUnits),\ntextBackground.sizeMinPixels, textBackground.sizeMaxPixels\n);\nfloat instanceScale = sizePixels / text.fontSize;\ndimensions = instanceRects.zw * instanceScale + textBackground.padding.xy + textBackground.padding.zw;\nvec2 pixelOffset = (positions * instanceRects.zw + instanceRects.xy) * instanceScale + mix(-textBackground.padding.xy, textBackground.padding.zw, positions);\npixelOffset = rotate_by_angle(pixelOffset, instanceAngles);\npixelOffset += instancePixelOffsets;\npixelOffset.y *= -1.0;\nvec2 xy = project_size_to_pixel(instanceClipRect.xy);\nvec2 wh = project_size_to_pixel(instanceClipRect.zw);\nif (text.flipY) {\nxy.y = -xy.y - wh.y;\n}\nif (instanceClipRect.z >= 0.0) {\ndimensions.x = wh.x;\npixelOffset.x = xy.x + uv.x * wh.x + mix(-textBackground.padding.x, textBackground.padding.z, uv.x);\n}\nif (instanceClipRect.w >= 0.0) {\ndimensions.y = wh.y;\npixelOffset.y = xy.y + uv.y * wh.y + mix(-textBackground.padding.y, textBackground.padding.w, uv.y);\n}\nif (textBackground.billboard) {\ngl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.0), geometry.position);\nDECKGL_FILTER_GL_POSITION(gl_Position, geometry);\nvec3 offset = vec3(pixelOffset, 0.0);\nDECKGL_FILTER_SIZE(offset, geometry);\ngl_Position.xy += project_pixel_size_to_clipspace(offset.xy);\n} else {\nvec3 offset_common = vec3(project_pixel_size(pixelOffset), 0.0);\nif (text.flipY) {\noffset_common.y *= -1.;\n}\nDECKGL_FILTER_SIZE(offset_common, geometry);\ngl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, offset_common, geometry.position);\nDECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n}\nvFillColor = vec4(instanceFillColors.rgb, instanceFillColors.a * layer.opacity);\nDECKGL_FILTER_COLOR(vFillColor, geometry);\nvLineColor = vec4(instanceLineColors.rgb, instanceLineColors.a * layer.opacity);\nDECKGL_FILTER_COLOR(vLineColor, geometry);\n}\n",fs:"#version 300 es\n#define SHADER_NAME text-background-layer-fragment-shader\nprecision highp float;\nin vec4 vFillColor;\nin vec4 vLineColor;\nin float vLineWidth;\nin vec2 uv;\nin vec2 dimensions;\nout vec4 fragColor;\nfloat round_rect(vec2 p, vec2 size, vec4 radii) {\nvec2 pixelPositionCB = (p - 0.5) * size;\nvec2 sizeCB = size * 0.5;\nfloat maxBorderRadius = min(size.x, size.y) * 0.5;\nvec4 borderRadius = vec4(min(radii, maxBorderRadius));\nborderRadius.xy =\n(pixelPositionCB.x > 0.0) ? borderRadius.xy : borderRadius.zw;\nborderRadius.x = (pixelPositionCB.y > 0.0) ? borderRadius.x : borderRadius.y;\nvec2 q = abs(pixelPositionCB) - sizeCB + borderRadius.x;\nreturn -(min(max(q.x, q.y), 0.0) + length(max(q, 0.0)) - borderRadius.x);\n}\nfloat rect(vec2 p, vec2 size) {\nvec2 pixelPosition = p * size;\nreturn min(min(pixelPosition.x, size.x - pixelPosition.x),\nmin(pixelPosition.y, size.y - pixelPosition.y));\n}\nvec4 get_stroked_fragColor(float dist) {\nfloat isBorder = smoothedge(dist, vLineWidth);\nreturn mix(vFillColor, vLineColor, isBorder);\n}\nvoid main(void) {\ngeometry.uv = uv;\nif (textBackground.borderRadius != vec4(0.0)) {\nfloat distToEdge = round_rect(uv, dimensions, textBackground.borderRadius);\nfloat shapeAlpha = smoothedge(-distToEdge, 0.0);\nif (shapeAlpha == 0.0) {\ndiscard;\n}\nif (textBackground.stroked) {\nfragColor = get_stroked_fragColor(distToEdge);\n} else {\nfragColor = vFillColor;\n}\nfragColor.a *= shapeAlpha;\n} else {\nif (textBackground.stroked) {\nfloat distToEdge = rect(uv, dimensions);\nfragColor = get_stroked_fragColor(distToEdge);\n} else {\nfragColor = vFillColor;\n}\n}\nDECKGL_FILTER_COLOR(fragColor, geometry);\n}\n",source:"struct TextUniforms {\n cutoffPixels: vec2<f32>,\n align: vec2<i32>,\n fontSize: f32,\n flipY: f32,\n};\n\n@group(0) @binding(auto) var<uniform> text: TextUniforms;\n\nfn rotate_by_angle(vertex: vec2<f32>, angle: f32) -> vec2<f32> {\n let angleRadian = radians(angle);\n let cosine = cos(angleRadian);\n let sine = sin(angleRadian);\n let rotationMatrix = mat2x2<f32>(\n vec2<f32>(cosine, -sine),\n vec2<f32>(sine, cosine)\n );\n return rotationMatrix * vertex;\n}\n\nstruct Attributes {\n @builtin(instance_index) instanceIndex: u32,\n @location(0) positions: vec2<f32>,\n @location(1) instancePositions: vec3<f32>,\n @location(2) instancePositions64Low: vec3<f32>,\n @location(3) instanceSizes: f32,\n @location(4) instanceAngles: f32,\n @location(5) instanceRects: vec4<f32>,\n @location(6) instanceClipRect: vec4<f32>,\n @location(7) instancePixelOffsets: vec2<f32>,\n @location(8) instanceFillColors: vec4<f32>,\n @location(9) instanceLineColors: vec4<f32>,\n @location(10) instanceLineWidths: f32,\n};\n\nstruct Varyings {\n @builtin(position) position: vec4<f32>,\n @location(0) vFillColor: vec4<f32>,\n @location(1) vLineColor: vec4<f32>,\n @location(2) vLineWidth: f32,\n @location(3) uv: vec2<f32>,\n @location(4) dimensions: vec2<f32>,\n @location(5) pickingColor: vec3<f32>,\n};\n\n@vertex\nfn vertexMain(attributes: Attributes) -> Varyings {\n geometry.worldPosition = attributes.instancePositions;\n geometry.uv = attributes.positions;\n geometry.pickingColor = picking_getPickingColorFromIndex(attributes.instanceIndex);\n\n var varyings: Varyings;\n varyings.uv = attributes.positions;\n varyings.vLineWidth = attributes.instanceLineWidths;\n\n let sizePixels = clamp(\n project_unit_size_to_pixel(\n attributes.instanceSizes * textBackground.sizeScale,\n textBackground.sizeUnits\n ),\n textBackground.sizeMinPixels,\n textBackground.sizeMaxPixels\n );\n let instanceScale = sizePixels / text.fontSize;\n\n varyings.dimensions = attributes.instanceRects.zw * instanceScale +\n textBackground.padding.xy + textBackground.padding.zw;\n\n var pixelOffset =\n (attributes.positions * attributes.instanceRects.zw + attributes.instanceRects.xy) *\n instanceScale +\n mix(-textBackground.padding.xy, textBackground.padding.zw, attributes.positions);\n pixelOffset = rotate_by_angle(pixelOffset, attributes.instanceAngles);\n pixelOffset = pixelOffset + attributes.instancePixelOffsets;\n pixelOffset.y = pixelOffset.y * -1.0;\n\n var xy = project_size_vec2(attributes.instanceClipRect.xy) * project.scale;\n let wh = project_size_vec2(attributes.instanceClipRect.zw) * project.scale;\n if (text.flipY > 0.5) {\n xy.y = -xy.y - wh.y;\n }\n if (attributes.instanceClipRect.z >= 0.0) {\n varyings.dimensions.x = wh.x;\n pixelOffset.x = xy.x + varyings.uv.x * wh.x + mix(\n -textBackground.padding.x,\n textBackground.padding.z,\n varyings.uv.x\n );\n }\n if (attributes.instanceClipRect.w >= 0.0) {\n varyings.dimensions.y = wh.y;\n pixelOffset.y = xy.y + varyings.uv.y * wh.y + mix(\n -textBackground.padding.y,\n textBackground.padding.w,\n varyings.uv.y\n );\n }\n\n if (textBackground.billboard > 0.5) {\n var position = project_position_to_clipspace(\n attributes.instancePositions,\n attributes.instancePositions64Low,\n vec3<f32>(0.0)\n );\n let clipOffset = project_pixel_size_to_clipspace(pixelOffset);\n position = vec4<f32>(\n position.x + clipOffset.x,\n position.y + clipOffset.y,\n position.z,\n position.w\n );\n varyings.position = position;\n } else {\n var offsetCommon = vec3<f32>(project_pixel_size_vec2(pixelOffset), 0.0);\n if (text.flipY > 0.5) {\n offsetCommon.y = offsetCommon.y * -1.0;\n }\n varyings.position = project_position_to_clipspace(\n attributes.instancePositions,\n attributes.instancePositions64Low,\n offsetCommon\n );\n }\n\n varyings.vFillColor = vec4<f32>(\n attributes.instanceFillColors.rgb,\n attributes.instanceFillColors.a * layer.opacity\n );\n varyings.vLineColor = vec4<f32>(\n attributes.instanceLineColors.rgb,\n attributes.instanceLineColors.a * layer.opacity\n );\n varyings.pickingColor = geometry.pickingColor;\n return varyings;\n}\n\nfn round_rect(point: vec2<f32>, size: vec2<f32>, radii: vec4<f32>) -> f32 {\n let pixelPosition = (point - 0.5) * size;\n let halfSize = size * 0.5;\n let maxBorderRadius = min(size.x, size.y) * 0.5;\n var borderRadius = min(radii, vec4<f32>(maxBorderRadius));\n\n borderRadius = select(borderRadius.zwxy, borderRadius, pixelPosition.x > 0.0);\n let radius = select(borderRadius.y, borderRadius.x, pixelPosition.y > 0.0);\n let q = abs(pixelPosition) - halfSize + radius;\n return -(min(max(q.x, q.y), 0.0) + length(max(q, vec2<f32>(0.0))) - radius);\n}\n\nfn rect(point: vec2<f32>, size: vec2<f32>) -> f32 {\n let pixelPosition = point * size;\n return min(\n min(pixelPosition.x, size.x - pixelPosition.x),\n min(pixelPosition.y, size.y - pixelPosition.y)\n );\n}\n\nfn get_stroked_frag_color(\n distanceToEdge: f32,\n lineWidth: f32,\n fillColor: vec4<f32>,\n lineColor: vec4<f32>\n) -> vec4<f32> {\n let isBorder = smoothedge(distanceToEdge, lineWidth);\n return mix(fillColor, lineColor, isBorder);\n}\n\n@fragment\nfn fragmentMain(varyings: Varyings) -> @location(0) vec4<f32> {\n geometry.uv = varyings.uv;\n var fragColor: vec4<f32>;\n\n if (any(textBackground.borderRadius != vec4<f32>(0.0))) {\n let distanceToEdge = round_rect(\n varyings.uv,\n varyings.dimensions,\n textBackground.borderRadius\n );\n let shapeAlpha = smoothedge(-distanceToEdge, 0.0);\n if (shapeAlpha == 0.0) {\n discard;\n }\n if (textBackground.stroked > 0.5) {\n fragColor = get_stroked_frag_color(\n distanceToEdge,\n varyings.vLineWidth,\n varyings.vFillColor,\n varyings.vLineColor\n );\n } else {\n fragColor = varyings.vFillColor;\n }\n fragColor.a = fragColor.a * shapeAlpha;\n } else if (textBackground.stroked > 0.5) {\n let distanceToEdge = rect(varyings.uv, varyings.dimensions);\n fragColor = get_stroked_frag_color(\n distanceToEdge,\n varyings.vLineWidth,\n varyings.vFillColor,\n varyings.vLineColor\n );\n } else {\n fragColor = varyings.vFillColor;\n }\n\n if (picking.isActive > 0.5) {\n if (!picking_isColorValid(varyings.pickingColor)) {\n discard;\n }\n return vec4<f32>(varyings.pickingColor, 1.0);\n }\n\n if (picking.isHighlightActive > 0.5) {\n let highlightedObjectColor = picking_normalizeColor(picking.highlightedObjectColor);\n if (picking_isColorZero(abs(varyings.pickingColor - highlightedObjectColor))) {\n let highlightAlpha = picking.highlightColor.a;\n let blendedAlpha = highlightAlpha + fragColor.a * (1.0 - highlightAlpha);\n if (blendedAlpha > 0.0) {\n let highlightRatio = highlightAlpha / blendedAlpha;\n fragColor = vec4<f32>(\n mix(fragColor.rgb, picking.highlightColor.rgb, highlightRatio),\n blendedAlpha\n );\n } else {\n fragColor = vec4<f32>(fragColor.rgb, 0.0);\n }\n }\n }\n\n return deckgl_premultiplied_alpha(fragColor);\n}\n",modules:[Ye,Ze,Je,Hr,Sr]})}initializeState(){this.getAttributeManager().addInstanced({instancePositions:{size:3,type:"float64",fp64:this.use64bitPositions(),transition:!0,accessor:"getPosition"},instanceSizes:{size:1,transition:!0,bufferGroup:"text-background-instance-data",accessor:"getSize",defaultValue:1},instanceAngles:{size:1,transition:!0,bufferGroup:"text-background-instance-data",accessor:"getAngle"},instanceRects:{size:4,bufferGroup:"text-background-instance-data",accessor:"getBoundingRect"},instanceClipRect:{size:4,bufferGroup:"text-background-instance-data",accessor:"getClipRect",defaultValue:[0,0,-1,-1]},instancePixelOffsets:{size:2,transition:!0,bufferGroup:"text-background-instance-data",accessor:"getPixelOffset"},instanceFillColors:{size:4,transition:!0,type:"unorm8",accessor:"getFillColor",defaultValue:[0,0,0,255]},instanceLineColors:{size:4,transition:!0,type:"unorm8",accessor:"getLineColor",defaultValue:[0,0,0,255]},instanceLineWidths:{size:1,transition:!0,bufferGroup:"text-background-instance-data",accessor:"getLineWidth",defaultValue:1}})}updateState(e){super.updateState(e);const{changeFlags:t}=e;t.extensionsChanged&&(this.state.model?.destroy(),this.state.model=this._getModel(),this.getAttributeManager().invalidateAll())}draw({uniforms:e}){const{billboard:t,sizeScale:n,sizeUnits:o,sizeMinPixels:s,sizeMaxPixels:r,getLineWidth:a,fontSize:l}=this.props;let{padding:c,borderRadius:u}=this.props;c.length<4&&(c=[c[0],c[1],c[0],c[1]]),Array.isArray(u)||(u=[u,u,u,u]);const f=this.state.model,d={billboard:t,stroked:Boolean(a),borderRadius:u,padding:c,sizeUnits:i[o],sizeScale:n,sizeMinPixels:s,sizeMaxPixels:r},p={fontSize:l,viewport:this.context.viewport};f.shaderInputs.setProps({textBackground:d,text:p}),f.draw(this.context.renderPass)}_getModel(){return new xt(this.context.device,{...this.getShaders(),id:this.props.id,bufferLayout:this.getAttributeManager().getBufferLayouts(),geometry:new nt({topology:"triangle-strip",vertexCount:4,attributes:{positions:{size:2,value:new Float32Array([0,0,1,0,0,1,1,1])}}}),isInstanced:!0})}};Yr.defaultProps=Zr,Yr.layerName="TextBackgroundLayer";var qr={start:1,middle:0,end:-1},Kr={top:1,center:0,bottom:-1},Xr=[0,0,0,255],Jr={billboard:!0,sizeScale:1,sizeUnits:"pixels",sizeMinPixels:0,sizeMaxPixels:Number.MAX_SAFE_INTEGER,background:!1,getBackgroundColor:{type:"accessor",value:[255,255,255,255]},getBorderColor:{type:"accessor",value:Xr},getBorderWidth:{type:"accessor",value:0},backgroundBorderRadius:{type:"object",value:0},backgroundPadding:{type:"array",value:[0,0,0,0]},characterSet:{type:"object",value:jr.characterSet},fontFamily:jr.fontFamily,fontWeight:jr.fontWeight,lineHeight:1,outlineWidth:{type:"number",value:0,min:0},outlineColor:{type:"color",value:Xr},fontSettings:{type:"object",value:{},compare:1},wordBreak:"break-word",maxWidth:{type:"number",value:-1},contentCutoffPixels:{type:"array",value:[0,0]},contentAlignHorizontal:"none",contentAlignVertical:"none",getText:{type:"accessor",value:e=>e.text},getPosition:{type:"accessor",value:e=>e.position},getColor:{type:"accessor",value:Xr},getSize:{type:"accessor",value:32},getAngle:{type:"accessor",value:0},getTextAnchor:{type:"accessor",value:"middle"},getAlignmentBaseline:{type:"accessor",value:"center"},getPixelOffset:{type:"accessor",value:[0,0]},getContentBox:{type:"accessor",value:[0,0,-1,-1]},backgroundColor:{deprecatedFor:["background","getBackgroundColor"]}},Qr=class extends fo{constructor(){super(...arguments),this.getBoundingRect=(e,t)=>{const{size:[n,i]}=this.transformParagraph(e,t),{getTextAnchor:o,getAlignmentBaseline:s}=this.props;return[(qr["function"==typeof o?o(e,t):o]-1)*n/2,(Kr["function"==typeof s?s(e,t):s]-1)*i/2,n,i]},this.getIconOffsets=(e,t)=>{const{getTextAnchor:n,getAlignmentBaseline:i}=this.props,{x:o,y:s,rowWidth:r,size:[,a]}=this.transformParagraph(e,t),l=qr["function"==typeof n?n(e,t):n],c=Kr["function"==typeof i?i(e,t):i],u=o.length,f=new Array(2*u);let d=0;for(let p=0;p<u;p++)f[d++]=(l-1)*r[p]/2+o[p],f[d++]=(c-1)*a/2+s[p];return f}}initializeState(){this.state={styleVersion:0,fontAtlasManager:new Vr},this.props.maxWidth>0&&I.once(1,"v8.9 breaking change: TextLayer maxWidth is now relative to text size")()}updateState(e){const{props:t,oldProps:n,changeFlags:i}=e;(i.dataChanged||i.updateTriggersChanged&&(i.updateTriggersChanged.all||i.updateTriggersChanged.getText))&&this._updateText(),(this._updateFontAtlas()||t.lineHeight!==n.lineHeight||t.wordBreak!==n.wordBreak||t.maxWidth!==n.maxWidth)&&this.setState({styleVersion:this.state.styleVersion+1})}getPickingInfo({info:e}){return e.object=e.index>=0?this.props.data[e.index]:null,e}_updateFontAtlas(){const{fontSettings:e,fontFamily:t,fontWeight:n,_getFontRenderer:i}=this.props,{fontAtlasManager:o,characterSet:s}=this.state,r={...e,characterSet:s,fontFamily:t,fontWeight:n,_getFontRenderer:i};if(!o.mapping)return o.setProps(r),!0;for(const a in r)if(r[a]!==o.props[a])return o.setProps(r),!0;return!1}_updateText(){const{data:e,characterSet:t}=this.props,n=e.attributes?.getText;let i,{getText:o}=this.props,s=e.startIndices;const r="auto"===t&&/* @__PURE__ */new Set;if(n&&s){const{texts:t,characterCount:a}=function({value:e,length:t,stride:n,offset:i,startIndices:o,characterSet:s}){const r=e.BYTES_PER_ELEMENT,a=n?n/r:1,l=i?i/r:0,c=o[t]||Math.ceil((e.length-l)/a),u=s&&/* @__PURE__ */new Set,f=new Array(t);let d=e;if(a>1||l>0){d=new(0,e.constructor)(c);for(let t=0;t<c;t++)d[t]=e[t*a+l]}for(let p=0;p<t;p++){const e=o[p],t=o[p+1]||c,n=d.subarray(e,t);f[p]=String.fromCodePoint.apply(null,n),u&&n.forEach(u.add,u)}if(u)for(const p of u)s.add(String.fromCodePoint(p));return{texts:f,characterCount:c}}({...ArrayBuffer.isView(n)?{value:n}:n,length:e.length,startIndices:s,characterSet:r});i=a,o=(e,{index:n})=>t[n]}else{const{iterable:t,objectInfo:n}=$t(e);s=[0],i=0;for(const e of t){n.index++;const t=Array.from(o(e,n)||"");r&&t.forEach(r.add,r),i+=t.length,s.push(i)}}this.setState({getText:o,startIndices:s,numInstances:i,characterSet:r||t})}transformParagraph(e,t){const{fontAtlasManager:n}=this.state,i=n.mapping,{baselineOffset:o}=n.atlas,{fontSize:s}=n.props,r=this.state.getText,{wordBreak:a,lineHeight:l,maxWidth:c}=this.props;return function(e,t,n,i,o,s){const r=Array.from(e),a=r.length,l=new Array(a),c=new Array(a),u=new Array(a),f=("break-word"===i||"break-all"===i)&&isFinite(o)&&o>0,d=[0,0],p=[0,0];let g=0,h=t+n/2,v=0,m=0;for(let _=0;_<=a;_++){const e=r[_];if("\n"!==e&&_!==a||(m=_),m>v){const e=f?Fr(r,i,o,s,v,m):Rr;for(let t=0;t<=e.length;t++){const i=0===t?v:e[t-1],o=t<e.length?e[t]:m;Nr(r,i,o,s,l,p);for(let e=i;e<o;e++)c[e]=h,u[e]=p[0];g++,h+=n,d[0]=Math.max(d[0],p[0])}v=m}"\n"===e&&(l[v]=0,c[v]=0,u[v]=0,v++)}return d[1]=g*n,{x:l,y:c,rowWidth:u,size:d}}(r(e,t)||"",o,l*s,a,c*s,i)}renderLayers(){const{startIndices:e,numInstances:t,getText:n,fontAtlasManager:{atlas:i,mapping:o},styleVersion:s}=this.state,{data:r,_dataDiff:a,getPosition:l,getColor:c,getSize:u,getAngle:f,getPixelOffset:d,getBackgroundColor:p,getBorderColor:g,getBorderWidth:h,getContentBox:v,backgroundBorderRadius:m,backgroundPadding:_,background:x,billboard:y,fontSettings:b,outlineWidth:P,outlineColor:C,sizeScale:w,sizeUnits:S,sizeMinPixels:L,sizeMaxPixels:A,contentCutoffPixels:I,contentAlignHorizontal:E,contentAlignVertical:T,transitions:O,updateTriggers:z}=this.props,M=this.getSubLayerClass("characters",Ir),R=this.getSubLayerClass("background",Yr),{fontSize:B}=this.state.fontAtlasManager.props;return[x&&new R({getFillColor:p,getLineColor:g,getLineWidth:h,borderRadius:m,padding:_,getPosition:l,getSize:u,getAngle:f,getPixelOffset:d,getClipRect:v,billboard:y,sizeScale:w,sizeUnits:S,sizeMinPixels:L,sizeMaxPixels:A,fontSize:B,transitions:O&&{getPosition:O.getPosition,getAngle:O.getAngle,getSize:O.getSize,getFillColor:O.getBackgroundColor,getLineColor:O.getBorderColor,getLineWidth:O.getBorderWidth,getPixelOffset:O.getPixelOffset}},this.getSubLayerProps({id:"background",updateTriggers:{getPosition:z.getPosition,getAngle:z.getAngle,getSize:z.getSize,getFillColor:z.getBackgroundColor,getLineColor:z.getBorderColor,getLineWidth:z.getBorderWidth,getPixelOffset:z.getPixelOffset,getBoundingRect:{getText:z.getText,getTextAnchor:z.getTextAnchor,getAlignmentBaseline:z.getAlignmentBaseline,styleVersion:s}}}),{data:r.attributes&&r.attributes.background?{length:r.length,attributes:r.attributes.background}:r,_dataDiff:a,autoHighlight:!1,getBoundingRect:this.getBoundingRect}),new M({sdf:b.sdf,smoothing:Number.isFinite(b.smoothing)?b.smoothing:jr.smoothing,outlineWidth:P/(b.radius||jr.radius),outlineColor:C,iconAtlas:i,iconMapping:o,getPosition:l,getColor:c,getSize:u,getAngle:f,getPixelOffset:d,getContentBox:v,billboard:y,sizeScale:w,sizeUnits:S,sizeMinPixels:L,sizeMaxPixels:A,fontSize:B,contentCutoffPixels:I,contentAlignHorizontal:E,contentAlignVertical:T,transitions:O&&{getPosition:O.getPosition,getAngle:O.getAngle,getColor:O.getColor,getSize:O.getSize,getPixelOffset:O.getPixelOffset,getContentBox:O.getContentBox}},this.getSubLayerProps({id:"characters",updateTriggers:{all:z.getText,getPosition:z.getPosition,getAngle:z.getAngle,getColor:z.getColor,getSize:z.getSize,getPixelOffset:z.getPixelOffset,getContentBox:z.getContentBox,getIconOffsets:{getTextAnchor:z.getTextAnchor,getAlignmentBaseline:z.getAlignmentBaseline,styleVersion:s}}}),{data:r,_dataDiff:a,startIndices:e,numInstances:t,getIconOffsets:this.getIconOffsets,getIcon:n})]}static set fontAtlasCacheLimit(e){!function(e){I.assert(Number.isFinite(e)&&e>=3,"Invalid cache limit"),Ur=new Dr(e)}(e)}};Qr.defaultProps=Jr,Qr.layerName="TextLayer";var ea={circle:{type:ss,props:{filled:"filled",stroked:"stroked",lineWidthMaxPixels:"lineWidthMaxPixels",lineWidthMinPixels:"lineWidthMinPixels",lineWidthScale:"lineWidthScale",lineWidthUnits:"lineWidthUnits",pointRadiusMaxPixels:"radiusMaxPixels",pointRadiusMinPixels:"radiusMinPixels",pointRadiusScale:"radiusScale",pointRadiusUnits:"radiusUnits",pointAntialiasing:"antialiasing",pointBillboard:"billboard",getFillColor:"getFillColor",getLineColor:"getLineColor",getLineWidth:"getLineWidth",getPointRadius:"getRadius"}},icon:{type:Uo,props:{iconAtlas:"iconAtlas",iconMapping:"iconMapping",iconSizeMaxPixels:"sizeMaxPixels",iconSizeMinPixels:"sizeMinPixels",iconSizeScale:"sizeScale",iconSizeUnits:"sizeUnits",iconAlphaCutoff:"alphaCutoff",iconBillboard:"billboard",getIcon:"getIcon",getIconAngle:"getAngle",getIconColor:"getColor",getIconPixelOffset:"getPixelOffset",getIconSize:"getSize"}},text:{type:Qr,props:{textSizeMaxPixels:"sizeMaxPixels",textSizeMinPixels:"sizeMinPixels",textSizeScale:"sizeScale",textSizeUnits:"sizeUnits",textBackground:"background",textBackgroundPadding:"backgroundPadding",textFontFamily:"fontFamily",textFontWeight:"fontWeight",textLineHeight:"lineHeight",textMaxWidth:"maxWidth",textOutlineColor:"outlineColor",textOutlineWidth:"outlineWidth",textWordBreak:"wordBreak",textCharacterSet:"characterSet",textBillboard:"billboard",textFontSettings:"fontSettings",getText:"getText",getTextAngle:"getAngle",getTextColor:"getColor",getTextPixelOffset:"getPixelOffset",getTextSize:"getSize",getTextAnchor:"getTextAnchor",getTextAlignmentBaseline:"getAlignmentBaseline",getTextBackgroundColor:"getBackgroundColor",getTextBorderColor:"getBorderColor",getTextBorderWidth:"getBorderWidth"}}},ta={type:Ys,props:{lineWidthUnits:"widthUnits",lineWidthScale:"widthScale",lineWidthMinPixels:"widthMinPixels",lineWidthMaxPixels:"widthMaxPixels",lineJointRounded:"jointRounded",lineCapRounded:"capRounded",lineMiterLimit:"miterLimit",lineBillboard:"billboard",lineAntialiasing:"antialiasing",getLineColor:"getColor",getLineWidth:"getWidth"}},na={type:mr,props:{extruded:"extruded",filled:"filled",wireframe:"wireframe",elevationScale:"elevationScale",material:"material",_full3d:"_full3d",getElevation:"getElevation",getFillColor:"getFillColor",getLineColor:"getLineColor"}};function ia({type:e,props:t}){const n={};for(const i in t)n[i]=e.defaultProps[t[i]];return n}function oa(e,t,n="getPosition"){const{transitions:i,updateTriggers:o}=e.props,s={updateTriggers:{},transitions:i&&{[n]:i.geometry}};for(const r in t){const n=t[r];let a=e.props[r];r.startsWith("get")&&(a=e.getSubLayerAccessor(a),s.updateTriggers[n]=o[r],i&&(s.transitions[n]=i[r])),s[n]=a}return s}function sa(e,t,n={}){const i={pointFeatures:[],lineFeatures:[],polygonFeatures:[],polygonOutlineFeatures:[]},{startRow:o=0,endRow:s=e.length}=n;for(let r=o;r<s;r++){const n=e[r],{geometry:o}=n;if(o)if("GeometryCollection"===o.type){I.assert(Array.isArray(o.geometries),"GeoJSON does not have geometries array");const{geometries:e}=o;for(let o=0;o<e.length;o++){ra(e[o],i,t,n,r)}}else ra(o,i,t,n,r)}return i}function ra(e,t,n,i,o){const{type:s,coordinates:r}=e,{pointFeatures:a,lineFeatures:l,polygonFeatures:c,polygonOutlineFeatures:u}=t;if(function(e,t){let n=aa[e];I.assert(n,`Unknown GeoJSON type ${e}`);for(;t&&--n>0;)t=t[0];return t&&Number.isFinite(t[0])}(s,r))switch(s){case"Point":a.push(n({geometry:e},i,o));break;case"MultiPoint":r.forEach(e=>{a.push(n({geometry:{type:"Point",coordinates:e}},i,o))});break;case"LineString":l.push(n({geometry:e},i,o));break;case"MultiLineString":r.forEach(e=>{l.push(n({geometry:{type:"LineString",coordinates:e}},i,o))});break;case"Polygon":c.push(n({geometry:e},i,o)),r.forEach(e=>{u.push(n({geometry:{type:"LineString",coordinates:e}},i,o))});break;case"MultiPolygon":r.forEach(e=>{c.push(n({geometry:{type:"Polygon",coordinates:e}},i,o)),e.forEach(e=>{u.push(n({geometry:{type:"LineString",coordinates:e}},i,o))})})}else I.warn(`${s} coordinates are malformed`)()}var aa={Point:1,MultiPoint:2,LineString:2,MultiLineString:3,Polygon:3,MultiPolygon:4};function la(e){return e.geometry.coordinates}function ca(e){const t={points:{},lines:{},polygons:{},polygonsOutline:{}},{points:n,lines:i,polygons:o}=e,s=function(e){const t={points:null,lines:null,polygons:null};for(const n in t){const i=e[n].globalFeatureIds.value;t[n]=new Uint32Array(i)}return t}(e);t.points.data={length:n.positions.value.length/n.positions.size,attributes:{...n.attributes,getPosition:n.positions,rowIndexes:{size:1,type:"uint32",value:s.points}},properties:n.properties,numericProps:n.numericProps,featureIds:n.featureIds},t.lines.data={length:i.pathIndices.value.length-1,startIndices:i.pathIndices.value,attributes:{...i.attributes,getPath:i.positions,rowIndexes:{size:1,type:"uint32",value:s.lines}},properties:i.properties,numericProps:i.numericProps,featureIds:i.featureIds},t.lines._pathType="open";const r=o.positions.value.length/o.positions.size,a=Array(r).fill(1);for(const l of o.primitivePolygonIndices.value)a[l-1]=0;return t.polygons.data={length:o.polygonIndices.value.length-1,startIndices:o.polygonIndices.value,attributes:{...o.attributes,getPolygon:o.positions,instanceVertexValid:{size:1,value:new Uint16Array(a)},rowIndexes:{size:1,type:"uint32",value:s.polygons}},properties:o.properties,numericProps:o.numericProps,featureIds:o.featureIds},t.polygons._normalize=!1,o.triangles&&(t.polygons.data.attributes.indices=o.triangles.value),t.polygonsOutline.data={length:o.primitivePolygonIndices.value.length-1,startIndices:o.primitivePolygonIndices.value,attributes:{...o.attributes,getPath:o.positions,rowIndexes:{size:1,type:"uint32",value:s.polygons}},properties:o.properties,numericProps:o.numericProps,featureIds:o.featureIds},t.polygonsOutline._pathType="open",t}var ua=["points","linestrings","polygons"],fa={...ia(ea.circle),...ia(ea.icon),...ia(ea.text),...ia(ta),...ia(na),stroked:!0,filled:!0,extruded:!1,wireframe:!1,_full3d:!1,iconAtlas:{type:"object",value:null},iconMapping:{type:"object",value:{}},getIcon:{type:"accessor",value:e=>e.properties.icon},getText:{type:"accessor",value:e=>e.properties.text},pointType:"circle",getRadius:{deprecatedFor:"getPointRadius"}},da=class extends fo{initializeState(){this.state={layerProps:{},features:{},featuresDiff:{}}}updateState({props:e,changeFlags:t}){if(!t.dataChanged)return;const{data:n}=this.props,i=n&&"points"in n&&"polygons"in n&&"lines"in n;this.setState({binary:i}),i?this._updateStateBinary({props:e,changeFlags:t}):this._updateStateJSON({props:e,changeFlags:t})}_updateStateBinary({props:e,changeFlags:t}){const n=ca(e.data);this.setState({layerProps:n})}_updateStateJSON({props:e,changeFlags:t}){const n=function(e){if(Array.isArray(e))return e;switch(I.assert(e.type,"GeoJSON does not have type"),e.type){case"Feature":return[e];case"FeatureCollection":return I.assert(Array.isArray(e.features),"GeoJSON does not have features array"),e.features;default:return[{geometry:e}]}}(e.data),i=this.getSubLayerRow.bind(this);let o={};const s={};if(Array.isArray(t.dataChanged)){const e=this.state.features;for(const t in e)o[t]=e[t].slice(),s[t]=[];for(const r of t.dataChanged){const t=sa(n,i,r);for(const n in e)s[n].push(_r({data:o[n],getIndex:e=>e.__source.index,dataRange:r,replace:t[n]}))}}else o=sa(n,i);const r=function(e,t){const n={points:{},lines:{},polygons:{},polygonsOutline:{}},{pointFeatures:i,lineFeatures:o,polygonFeatures:s,polygonOutlineFeatures:r}=e;return n.points.data=i,n.points._dataDiff=t.pointFeatures&&(()=>t.pointFeatures),n.points.getPosition=la,n.lines.data=o,n.lines._dataDiff=t.lineFeatures&&(()=>t.lineFeatures),n.lines.getPath=la,n.polygons.data=s,n.polygons._dataDiff=t.polygonFeatures&&(()=>t.polygonFeatures),n.polygons.getPolygon=la,n.polygonsOutline.data=r,n.polygonsOutline._dataDiff=t.polygonOutlineFeatures&&(()=>t.polygonOutlineFeatures),n.polygonsOutline.getPath=la,n}(o,s);this.setState({features:o,featuresDiff:s,layerProps:r})}getPickingInfo(e){const t=super.getPickingInfo(e),{index:n,sourceLayer:i}=t;return t.featureType=ua.find(e=>i.id.startsWith(`${this.id}-${e}-`)),n>=0&&i.id.startsWith(`${this.id}-points-text`)&&this.state.binary&&(t.index=this.props.data.points.globalFeatureIds.value[n]),t}_updateAutoHighlight(e){const t=`${this.id}-points-`,n="points"===e.featureType;for(const i of this.getSubLayers())i.id.startsWith(t)===n&&i.updateAutoHighlight(e)}_renderPolygonLayer(){const{extruded:e,wireframe:t}=this.props,{layerProps:n}=this.state,i="polygons-fill",o=this.shouldRenderSubLayer(i,n.polygons?.data)&&this.getSubLayerClass(i,na.type);if(o){const s=oa(this,na.props,"getPolygon"),r=e&&t;return r||delete s.getLineColor,s.updateTriggers.lineColors=r,new o(s,this.getSubLayerProps({id:i,updateTriggers:s.updateTriggers}),n.polygons)}return null}_renderLineLayers(){const{extruded:e,stroked:t}=this.props,{layerProps:n}=this.state,i="polygons-stroke",o="linestrings",s=!e&&t&&this.shouldRenderSubLayer(i,n.polygonsOutline?.data)&&this.getSubLayerClass(i,ta.type),r=this.shouldRenderSubLayer(o,n.lines?.data)&&this.getSubLayerClass(o,ta.type);if(s||r){const e=oa(this,ta.props,"getPath");return[s&&new s(e,this.getSubLayerProps({id:i,updateTriggers:e.updateTriggers}),n.polygonsOutline),r&&new r(e,this.getSubLayerProps({id:o,updateTriggers:e.updateTriggers}),n.lines)]}return null}_renderPointLayers(){const{pointType:e}=this.props,{layerProps:t,binary:n}=this.state;let{highlightedObjectIndex:i}=this.props;!n&&Number.isFinite(i)&&(i=t.points.data.findIndex(e=>e.__source.index===i));const o=new Set(e.split("+")),s=[];for(const r of o){const e=`points-${r}`,o=ea[r],a=o&&this.shouldRenderSubLayer(e,t.points?.data)&&this.getSubLayerClass(e,o.type);if(a){const l=oa(this,o.props);let c=t.points;if("text"===r&&n){const{rowIndexes:e,...t}=c.data.attributes;c={...c,data:{...c.data,attributes:t}}}s.push(new a(l,this.getSubLayerProps({id:e,updateTriggers:l.updateTriggers,highlightedObjectIndex:i}),c))}}return s}renderLayers(){const{extruded:e}=this.props,t=this._renderPolygonLayer();return[!e&&t,this._renderLineLayers(),this._renderPointLayers(),e&&t]}getSubLayerAccessor(e){const{binary:t}=this.state;return t&&"function"==typeof e?(t,n)=>{const{data:i,index:o}=n;return e(function(e,t){if(!e)return null;const n="startIndices"in e?e.startIndices[t]:t,i=e.featureIds.value[n];return-1!==n?function(e,t,n){const i={properties:{...e.properties[t]}};for(const o in e.numericProps)i.properties[o]=e.numericProps[o].value[n];return i}(e,i,n):null}(i,o),n)}:super.getSubLayerAccessor(e)}};da.layerName="GeoJsonLayer",da.defaultProps=fa;var pa=/* @__PURE__ */t({ArcLayer:()=>_o,BitmapLayer:()=>So,ColumnLayer:()=>Fs,GeoJsonLayer:()=>da,GridCellLayer:()=>Ns,IconLayer:()=>Uo,LineLayer:()=>Wo,PathLayer:()=>Ys,PointCloudLayer:()=>Xo,PolygonLayer:()=>br,ScatterplotLayer:()=>ss,SolidPolygonLayer:()=>mr,TextLayer:()=>Qr,_MultiIconLayer:()=>Ir,_TextBackgroundLayer:()=>Yr});export{He as C,be as E,Ze as S,Se as T,ht as _,Fs as a,Je as b,Xo as c,fo as d,co as f,vt as g,xt as h,Ys as i,So as l,Ct as m,da as n,cs as o,$t as p,br as r,us as s,pa as t,_o as u,ot as v,Be as w,Ye as x,nt as y};
|
|
1
|
+
/*! Web-kit v1.2.0-develop.13 | (c) 2026 MapVX */
|
|
2
|
+
!function(){try{var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},t=(new e.Error).stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a75a5f10-7273-491d-9330-0ccbc0d03cda",e._sentryDebugIdIdentifier="sentry-dbid-a75a5f10-7273-491d-9330-0ccbc0d03cda")}catch(e){}}();import{i as e,n as t,t as n}from"./rolldown-runtime-BSTMnvUK.js";import{B as i,Bt as o,D as s,F as r,Ft as a,M as l,N as c,Q as u,S as f,U as d,Ut as p,_ as g,a as h,c as v,d as m,f as _,ft as x,g as y,h as b,in as P,j as C,l as w,m as S,o as L,p as A,rn as I,s as E,tn as T,u as O,w as z,x as M,y as R,zt as B}from"./debug-hooks-NzJ2oy3C.js";import{a as k,c as F,d as N,i as D,p as j,u as U}from"./shader-type-decoder-CFX5sij5.js";import{a as G,d as V,f as $,g as W,h as H,i as Z,o as Y,p as q,r as K,t as X}from"./webgl-device-KnEQ5CNv.js";import{C as J,S as Q,_ as ee,a as te,b as ne,d as ie,f as oe,g as se,h as re,i as ae,l as le,m as ce,n as ue,o as fe,p as de,r as pe,s as ge,t as he,u as ve,v as me,w as _e,x as xe,y as ye}from"./expression-Dpos4VqC.js";var be=class e extends N{width;height;updateTimestamp;get[Symbol.toStringTag](){return"ExternalTexture"}constructor(t,n){super(t,n,e.defaultProps);const i=this.props.source?t.getExternalImageSize(this.props.source):null;this.width=this.props.width||i?.width||0,this.height=this.props.height||i?.height||0,this.updateTimestamp=t.incrementTimestamp()}static defaultProps={...N.defaultProps,source:void 0,width:0,height:0,colorSpace:"srgb",sampler:{}}};function Pe(e){const{input:t,inputChannels:n,output:i}=e||{};if(!t)return"#version 300 es\nout vec4 transform_output;\nvoid main() {\n transform_output = vec4(0);\n}";if(!n)throw new Error("inputChannels");return`#version 300 es\nin ${function(e){switch(e){case 1:return"float";case 2:return"vec2";case 3:return"vec3";case 4:return"vec4";default:throw new Error(`invalid channels: ${e}`)}}(n)} ${t};\nout vec4 ${i};\nvoid main() {\n ${i} = ${function(e,t){switch(t){case 1:return`vec4(${e}, 0.0, 0.0, 1.0)`;case 2:return`vec4(${e}, 0.0, 1.0)`;case 3:return`vec4(${e}, 1.0)`;case 4:return e;default:throw new Error(`invalid channels: ${t}`)}}(t,n)};\n}`}function Ce(e,t=[],n=0){const i=Math.fround(e),o=e-i;return t[n]=i,t[n+1]=o,t}function we(e,t=!0){return e??t}function Se(e=[0,0,0],t=!0){return t?e.map(e=>e/255):[...e]}var Le="\nlayout(std140) uniform fp64arithmeticUniforms {\n uniform float ONE;\n uniform float SPLIT;\n} fp64;\n\n/*\nAbout LUMA_FP64_CODE_ELIMINATION_WORKAROUND\n\nThe purpose of this workaround is to prevent shader compilers from\noptimizing away necessary arithmetic operations by swapping their sequences\nor transform the equation to some 'equivalent' form.\n\nThese helpers implement Dekker/Veltkamp-style error tracking. If the compiler\nfolds constants or reassociates the arithmetic, the high/low split can stop\ntracking the rounding error correctly. That failure mode tends to look fine in\nsimple coordinate setup, but then breaks down inside iterative arithmetic such\nas fp64 Mandelbrot loops.\n\nThe method is to multiply an artifical variable, ONE, which will be known to\nthe compiler to be 1 only at runtime. The whole expression is then represented\nas a polynomial with respective to ONE. In the coefficients of all terms, only one a\nand one b should appear\n\nerr = (a + b) * ONE^6 - a * ONE^5 - (a + b) * ONE^4 + a * ONE^3 - b - (a + b) * ONE^2 + a * ONE\n*/\n\nfloat prevent_fp64_optimization(float value) {\n#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND)\n return value + fp64.ONE * 0.0;\n#else\n return value;\n#endif\n}\n\n// Divide float number to high and low floats to extend fraction bits\nvec2 split(float a) {\n // Keep SPLIT as a runtime uniform so the compiler cannot fold the Dekker\n // split into a constant expression and reassociate the recovery steps.\n float split = prevent_fp64_optimization(fp64.SPLIT);\n float t = prevent_fp64_optimization(a * split);\n float temp = t - a;\n float a_hi = t - temp;\n float a_lo = a - a_hi;\n return vec2(a_hi, a_lo);\n}\n\n// Divide float number again when high float uses too many fraction bits\nvec2 split2(vec2 a) {\n vec2 b = split(a.x);\n b.y += a.y;\n return b;\n}\n\n// Special sum operation when a > b\nvec2 quickTwoSum(float a, float b) {\n#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND)\n float sum = (a + b) * fp64.ONE;\n float err = b - (sum - a) * fp64.ONE;\n#else\n float sum = a + b;\n float err = b - (sum - a);\n#endif\n return vec2(sum, err);\n}\n\n// General sum operation\nvec2 twoSum(float a, float b) {\n float s = (a + b);\n#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND)\n float v = (s * fp64.ONE - a) * fp64.ONE;\n float err = (a - (s - v) * fp64.ONE) * fp64.ONE * fp64.ONE * fp64.ONE + (b - v);\n#else\n float v = s - a;\n float err = (a - (s - v)) + (b - v);\n#endif\n return vec2(s, err);\n}\n\nvec2 twoSub(float a, float b) {\n float s = (a - b);\n#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND)\n float v = (s * fp64.ONE - a) * fp64.ONE;\n float err = (a - (s - v) * fp64.ONE) * fp64.ONE * fp64.ONE * fp64.ONE - (b + v);\n#else\n float v = s - a;\n float err = (a - (s - v)) - (b + v);\n#endif\n return vec2(s, err);\n}\n\nvec2 twoSqr(float a) {\n float prod = a * a;\n vec2 a_fp64 = split(a);\n#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND)\n float err = ((a_fp64.x * a_fp64.x - prod) * fp64.ONE + 2.0 * a_fp64.x *\n a_fp64.y * fp64.ONE * fp64.ONE) + a_fp64.y * a_fp64.y * fp64.ONE * fp64.ONE * fp64.ONE;\n#else\n float err = ((a_fp64.x * a_fp64.x - prod) + 2.0 * a_fp64.x * a_fp64.y) + a_fp64.y * a_fp64.y;\n#endif\n return vec2(prod, err);\n}\n\nvec2 twoProd(float a, float b) {\n float prod = a * b;\n vec2 a_fp64 = split(a);\n vec2 b_fp64 = split(b);\n // twoProd is especially sensitive because mul_fp64 and div_fp64 both depend\n // on the split terms and cross terms staying in the original evaluation\n // order. If the compiler folds or reassociates them, the low part tends to\n // collapse to zero or NaN on some drivers.\n float highProduct = prevent_fp64_optimization(a_fp64.x * b_fp64.x);\n float crossProduct1 = prevent_fp64_optimization(a_fp64.x * b_fp64.y);\n float crossProduct2 = prevent_fp64_optimization(a_fp64.y * b_fp64.x);\n float lowProduct = prevent_fp64_optimization(a_fp64.y * b_fp64.y);\n#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND)\n float err1 = (highProduct - prod) * fp64.ONE;\n float err2 = crossProduct1 * fp64.ONE * fp64.ONE;\n float err3 = crossProduct2 * fp64.ONE * fp64.ONE * fp64.ONE;\n float err4 = lowProduct * fp64.ONE * fp64.ONE * fp64.ONE * fp64.ONE;\n#else\n float err1 = highProduct - prod;\n float err2 = crossProduct1;\n float err3 = crossProduct2;\n float err4 = lowProduct;\n#endif\n float err = ((err1 + err2) + err3) + err4;\n return vec2(prod, err);\n}\n\nvec2 sum_fp64(vec2 a, vec2 b) {\n vec2 s, t;\n s = twoSum(a.x, b.x);\n t = twoSum(a.y, b.y);\n s.y += t.x;\n s = quickTwoSum(s.x, s.y);\n s.y += t.y;\n s = quickTwoSum(s.x, s.y);\n return s;\n}\n\nvec2 sub_fp64(vec2 a, vec2 b) {\n vec2 s, t;\n s = twoSub(a.x, b.x);\n t = twoSub(a.y, b.y);\n s.y += t.x;\n s = quickTwoSum(s.x, s.y);\n s.y += t.y;\n s = quickTwoSum(s.x, s.y);\n return s;\n}\n\nvec2 mul_fp64(vec2 a, vec2 b) {\n vec2 prod = twoProd(a.x, b.x);\n // y component is for the error\n prod.y += a.x * b.y;\n#if defined(LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND)\n prod = split2(prod);\n#endif\n prod = quickTwoSum(prod.x, prod.y);\n prod.y += a.y * b.x;\n#if defined(LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND)\n prod = split2(prod);\n#endif\n prod = quickTwoSum(prod.x, prod.y);\n return prod;\n}\n\nvec2 div_fp64(vec2 a, vec2 b) {\n float xn = 1.0 / b.x;\n#if defined(LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND)\n vec2 yn = mul_fp64(a, vec2(xn, 0));\n#else\n vec2 yn = a * xn;\n#endif\n float diff = (sub_fp64(a, mul_fp64(b, yn))).x;\n vec2 prod = twoProd(xn, diff);\n return sum_fp64(yn, prod);\n}\n\nvec2 sqrt_fp64(vec2 a) {\n if (a.x == 0.0 && a.y == 0.0) return vec2(0.0, 0.0);\n if (a.x < 0.0) return vec2(0.0 / 0.0, 0.0 / 0.0);\n\n float x = 1.0 / sqrt(a.x);\n float yn = a.x * x;\n#if defined(LUMA_FP64_CODE_ELIMINATION_WORKAROUND)\n vec2 yn_sqr = twoSqr(yn) * fp64.ONE;\n#else\n vec2 yn_sqr = twoSqr(yn);\n#endif\n float diff = sub_fp64(a, yn_sqr).x;\n vec2 prod = twoProd(x * 0.5, diff);\n#if defined(LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND)\n return sum_fp64(split(yn), prod);\n#else\n return sum_fp64(vec2(yn, 0.0), prod);\n#endif\n}\n",Ae={name:"fp64arithmetic",source:"struct Fp64ArithmeticUniforms {\n ONE: f32,\n SPLIT: f32,\n};\n\n@group(0) @binding(auto) var<uniform> fp64arithmetic : Fp64ArithmeticUniforms;\n\n#ifndef LUMA_FP64_F32_INPUT_ONLY\nstruct Fp64Bits {\n sign: u32,\n exponent: i32,\n significand: vec2u,\n isZero: bool,\n isInf: bool,\n isNan: bool,\n};\n#endif\n\n#ifndef LUMA_FP64_PREDICATE_ONLY\nfn fp64_nan(seed: f32) -> f32 {\n let nanBits = 0x7fc00000u | select(0u, 1u, seed < 0.0);\n return bitcast<f32>(nanBits);\n}\n#endif\n\nfn fp64_u64_is_zero(value: vec2u) -> bool {\n return value.x == 0u && value.y == 0u;\n}\n\nfn fp64_u64_compare(a: vec2u, b: vec2u) -> i32 {\n if (a.x != b.x) {\n return select(-1, 1, a.x > b.x);\n }\n if (a.y != b.y) {\n return select(-1, 1, a.y > b.y);\n }\n return 0;\n}\n\nfn fp64_u64_add(a: vec2u, b: vec2u) -> vec2u {\n let low = a.y + b.y;\n let carry = select(0u, 1u, low < a.y);\n return vec2u(a.x + b.x + carry, low);\n}\n\nfn fp64_u64_sub(a: vec2u, b: vec2u) -> vec2u {\n let borrow = select(0u, 1u, a.y < b.y);\n return vec2u(a.x - b.x - borrow, a.y - b.y);\n}\n\nfn fp64_u64_shift_left(value: vec2u, shift: u32) -> vec2u {\n if (shift == 0u) {\n return value;\n }\n if (shift < 32u) {\n return vec2u((value.x << shift) | (value.y >> (32u - shift)), value.y << shift);\n }\n if (shift == 32u) {\n return vec2u(value.y, 0u);\n }\n if (shift < 64u) {\n return vec2u(value.y << (shift - 32u), 0u);\n }\n return vec2u(0u);\n}\n\nfn fp64_u64_shift_right(value: vec2u, shift: u32) -> vec2u {\n if (shift == 0u) {\n return value;\n }\n if (shift < 32u) {\n return vec2u(value.x >> shift, (value.y >> shift) | (value.x << (32u - shift)));\n }\n if (shift == 32u) {\n return vec2u(0u, value.x);\n }\n if (shift < 64u) {\n return vec2u(0u, value.x >> (shift - 32u));\n }\n return vec2u(0u);\n}\n\nfn fp64_u64_get_bit(value: vec2u, bitIndex: u32) -> bool {\n if (bitIndex >= 64u) {\n return false;\n }\n if (bitIndex >= 32u) {\n return ((value.x >> (bitIndex - 32u)) & 1u) != 0u;\n }\n return ((value.y >> bitIndex) & 1u) != 0u;\n}\n\nfn fp64_u64_has_bits_below(value: vec2u, bitCount: u32) -> bool {\n if (bitCount == 0u) {\n return false;\n }\n if (bitCount >= 64u) {\n return !fp64_u64_is_zero(value);\n }\n if (bitCount > 32u) {\n let highBitCount = bitCount - 32u;\n let highMask = (1u << highBitCount) - 1u;\n return value.y != 0u || (value.x & highMask) != 0u;\n }\n if (bitCount == 32u) {\n return value.y != 0u;\n }\n let lowMask = (1u << bitCount) - 1u;\n return (value.y & lowMask) != 0u;\n}\n\n#ifndef LUMA_FP64_F32_INPUT_ONLY\nfn fp64_u64_shift_right_sticky(value: vec2u, shift: u32) -> vec2u {\n var shifted = fp64_u64_shift_right(value, shift);\n if (fp64_u64_has_bits_below(value, shift)) {\n shifted.y = shifted.y | 1u;\n }\n return shifted;\n}\n#endif\n\nfn fp64_u64_count_leading_zeros(value: vec2u) -> u32 {\n if (value.x != 0u) {\n return countLeadingZeros(value.x);\n }\n return 32u + countLeadingZeros(value.y);\n}\n\nfn fp64_round_shift_right_to_u32(value: vec2u, shift: u32) -> u32 {\n if (shift == 0u) {\n return value.y;\n }\n\n let truncated = fp64_u64_shift_right(value, shift);\n var rounded = truncated.y;\n let guard = fp64_u64_get_bit(value, shift - 1u);\n let hasTrailingBits = fp64_u64_has_bits_below(value, shift - 1u);\n if (guard && (hasTrailingBits || (rounded & 1u) == 1u)) {\n rounded = rounded + 1u;\n }\n return rounded;\n}\n\n#ifndef LUMA_FP64_F32_INPUT_ONLY\nfn fp64_round_shift_right(value: vec2u, shift: u32) -> vec2u {\n if (shift == 0u) {\n return value;\n }\n\n var rounded = fp64_u64_shift_right(value, shift);\n let guard = fp64_u64_get_bit(value, shift - 1u);\n let hasTrailingBits = fp64_u64_has_bits_below(value, shift - 1u);\n if (guard && (hasTrailingBits || (rounded.y & 1u) == 1u)) {\n rounded = fp64_u64_add(rounded, vec2u(0u, 1u));\n }\n return rounded;\n}\n#endif\n\nfn fp64_make_f32_bits_from_u64(sign: u32, significand: vec2u, baseExponent: i32) -> u32 {\n if (fp64_u64_is_zero(significand)) {\n return sign << 31u;\n }\n\n let leadingZeros = fp64_u64_count_leading_zeros(significand);\n let mostSignificantBit = 63u - leadingZeros;\n var exponent = baseExponent + i32(mostSignificantBit);\n\n if (exponent > 127) {\n return (sign << 31u) | 0x7f800000u;\n }\n\n if (exponent >= -126) {\n let shift = i32(mostSignificantBit) - 23;\n var significand24: u32;\n if (shift > 0) {\n significand24 = fp64_round_shift_right_to_u32(significand, u32(shift));\n } else {\n significand24 = fp64_u64_shift_left(significand, u32(-shift)).y;\n }\n\n if (significand24 >= 0x1000000u) {\n significand24 = significand24 >> 1u;\n exponent = exponent + 1;\n if (exponent > 127) {\n return (sign << 31u) | 0x7f800000u;\n }\n }\n\n return (sign << 31u) | (u32(exponent + 127) << 23u) | (significand24 & 0x7fffffu);\n }\n\n let scaleExponent = baseExponent + 149;\n var mantissa: u32;\n if (scaleExponent >= 0) {\n mantissa = fp64_u64_shift_left(significand, u32(scaleExponent)).y;\n } else {\n mantissa = fp64_round_shift_right_to_u32(significand, u32(-scaleExponent));\n }\n\n if (mantissa >= 0x800000u) {\n return (sign << 31u) | 0x00800000u;\n }\n return (sign << 31u) | mantissa;\n}\n\n#ifndef LUMA_FP64_F32_INPUT_ONLY\nfn fp64_decode_bits(bits: vec2u) -> Fp64Bits {\n let sign = bits.x >> 31u;\n let exponentBits = (bits.x >> 20u) & 0x7ffu;\n let fractionHigh = bits.x & 0xfffffu;\n let fractionLow = bits.y;\n let fraction = vec2u(fractionHigh, fractionLow);\n\n if (exponentBits == 0x7ffu) {\n let isInf = fp64_u64_is_zero(fraction);\n return Fp64Bits(sign, 0, vec2u(0u), false, isInf, !isInf);\n }\n\n if (exponentBits == 0u) {\n let isZero = fp64_u64_is_zero(fraction);\n return Fp64Bits(sign, -1022, fraction, isZero, false, false);\n }\n\n return Fp64Bits(sign, i32(exponentBits) - 1023, vec2u((1u << 20u) | fractionHigh, fractionLow), false, false, false);\n}\n\nfn fp64_finite_magnitude_compare(a: Fp64Bits, b: Fp64Bits) -> i32 {\n if (a.exponent != b.exponent) {\n return select(-1, 1, a.exponent > b.exponent);\n }\n return fp64_u64_compare(a.significand, b.significand);\n}\n#endif\n\n#ifndef LUMA_FP64_F32_INPUT_ONLY\nstruct Fp64RawF32Bits {\n sign: u32,\n baseExponent: i32,\n significand: u32,\n isZero: bool,\n isInf: bool,\n isNan: bool,\n};\n\n// Decode an f32 as (-1)^sign * significand * 2^baseExponent. This shared\n// integer representation lets normalization remain independent of the\n// selected double-single arithmetic implementation.\nfn fp64_decode_raw_f32_bits(bits: u32) -> Fp64RawF32Bits {\n let sign = bits >> 31u;\n let exponentBits = (bits >> 23u) & 0xffu;\n let fraction = bits & 0x7fffffu;\n\n if (exponentBits == 0xffu) {\n return Fp64RawF32Bits(sign, 0, 0u, false, fraction == 0u, fraction != 0u);\n }\n if (exponentBits == 0u) {\n return Fp64RawF32Bits(sign, -149, fraction, fraction == 0u, false, false);\n }\n return Fp64RawF32Bits(\n sign,\n i32(exponentBits) - 150,\n 0x800000u | fraction,\n false,\n false,\n false\n );\n}\n\nfn fp64_raw_f32_magnitude_compare(aBits: u32, bBits: u32) -> i32 {\n let aMagnitude = aBits & 0x7fffffffu;\n let bMagnitude = bBits & 0x7fffffffu;\n if (aMagnitude == bMagnitude) {\n return 0;\n }\n return select(-1, 1, aMagnitude > bMagnitude);\n}\n\nfn fp64_make_raw_residual_f32_bits(\n exactSign: u32,\n exactMagnitude: vec2u,\n exactBaseExponent: i32,\n highBits: u32\n) -> u32 {\n if (fp64_u64_is_zero(exactMagnitude)) {\n return 0u;\n }\n\n let high = fp64_decode_raw_f32_bits(highBits);\n if (high.isInf || high.isNan) {\n return 0u;\n }\n if (high.isZero) {\n return fp64_make_f32_bits_from_u64(exactSign, exactMagnitude, exactBaseExponent);\n }\n\n let commonBaseExponent = min(exactBaseExponent, high.baseExponent);\n let exactShift = exactBaseExponent - commonBaseExponent;\n let highShift = high.baseExponent - commonBaseExponent;\n if (exactShift >= 64 || highShift >= 64) {\n return 0u;\n }\n\n let exactAligned = fp64_u64_shift_left(exactMagnitude, u32(exactShift));\n let highAligned = fp64_u64_shift_left(vec2u(0u, high.significand), u32(highShift));\n let comparison = fp64_u64_compare(exactAligned, highAligned);\n if (comparison == 0) {\n return 0u;\n }\n\n var residualSign = exactSign;\n var residualMagnitude: vec2u;\n if (comparison > 0) {\n residualMagnitude = fp64_u64_sub(exactAligned, highAligned);\n } else {\n residualSign = exactSign ^ 1u;\n residualMagnitude = fp64_u64_sub(highAligned, exactAligned);\n }\n return fp64_make_f32_bits_from_u64(\n residualSign,\n residualMagnitude,\n commonBaseExponent\n );\n}\n\nfn fp64_split_raw_accumulator_bits(\n sign: u32,\n magnitude: vec2u,\n baseExponent: i32\n) -> vec2u {\n if (fp64_u64_is_zero(magnitude)) {\n return vec2u(0u);\n }\n let highBits = fp64_make_f32_bits_from_u64(sign, magnitude, baseExponent);\n let rawLowBits = fp64_make_raw_residual_f32_bits(sign, magnitude, baseExponent, highBits);\n let lowBits = select(rawLowBits, 0u, (rawLowBits & 0x7fffffffu) == 0u);\n if ((highBits & 0x7fffffffu) == 0u && (lowBits & 0x7fffffffu) == 0u) {\n return vec2u(0u);\n }\n return vec2u(highBits, lowBits);\n}\n#endif\n\n#ifndef LUMA_FP64_F32_INPUT_ONLY\n// Round an arithmetic accumulator to binary64 before splitting it. The\n// aligned add/subtract paths retain three guard bits plus a sticky bit, which\n// is sufficient for round-to-nearest-even at the binary64 boundary.\nfn fp64_split_binary64_accumulator_bits(\n sign: u32,\n magnitude: vec2u,\n baseExponent: i32\n) -> vec2u {\n if (fp64_u64_is_zero(magnitude)) {\n return vec2u(0u);\n }\n\n let mostSignificantBit = 63u - fp64_u64_count_leading_zeros(magnitude);\n let exponent = baseExponent + i32(mostSignificantBit);\n if (exponent > 1023) {\n return vec2u((sign << 31u) | 0x7f800000u, 0u);\n }\n\n var roundedMagnitude = magnitude;\n var roundedBaseExponent = baseExponent;\n if (exponent >= -1022) {\n if (mostSignificantBit > 52u) {\n let shift = mostSignificantBit - 52u;\n roundedMagnitude = fp64_round_shift_right(magnitude, shift);\n roundedBaseExponent = baseExponent + i32(shift);\n }\n } else {\n let shift = -1074 - baseExponent;\n if (shift > 0) {\n roundedMagnitude = fp64_round_shift_right(magnitude, u32(shift));\n roundedBaseExponent = -1074;\n }\n }\n\n if (fp64_u64_is_zero(roundedMagnitude)) {\n return vec2u(0u);\n }\n return fp64_split_raw_accumulator_bits(sign, roundedMagnitude, roundedBaseExponent);\n}\n#endif\n\n#ifndef LUMA_FP64_PREDICATE_ONLY\nfn fp64_add_raw_f32_bits(aBits: u32, bBits: u32) -> vec2u {\n let a = fp64_decode_raw_f32_bits(aBits);\n let b = fp64_decode_raw_f32_bits(bBits);\n\n if (a.isNan || b.isNan) {\n return vec2u(0x7fc00000u, 0u);\n }\n if (a.isInf || b.isInf) {\n if (a.isInf && b.isInf && a.sign != b.sign) {\n return vec2u(0x7fc00000u, 0u);\n }\n return select(vec2u(bBits, 0u), vec2u(aBits, 0u), a.isInf);\n }\n if (a.isZero && b.isZero) {\n return vec2u(0u);\n }\n if (a.isZero) {\n return vec2u(bBits, 0u);\n }\n if (b.isZero) {\n return vec2u(aBits, 0u);\n }\n\n let exponentDifference = abs(a.baseExponent - b.baseExponent);\n if (exponentDifference > 25) {\n if (fp64_raw_f32_magnitude_compare(aBits, bBits) >= 0) {\n return vec2u(aBits, bBits);\n }\n return vec2u(bBits, aBits);\n }\n\n let commonBaseExponent = min(a.baseExponent, b.baseExponent);\n let aMagnitude = fp64_u64_shift_left(\n vec2u(0u, a.significand),\n u32(a.baseExponent - commonBaseExponent)\n );\n let bMagnitude = fp64_u64_shift_left(\n vec2u(0u, b.significand),\n u32(b.baseExponent - commonBaseExponent)\n );\n\n var resultSign = a.sign;\n var resultMagnitude: vec2u;\n if (a.sign == b.sign) {\n resultMagnitude = fp64_u64_add(aMagnitude, bMagnitude);\n } else {\n let comparison = fp64_u64_compare(aMagnitude, bMagnitude);\n if (comparison == 0) {\n return vec2u(0u);\n }\n if (comparison > 0) {\n resultMagnitude = fp64_u64_sub(aMagnitude, bMagnitude);\n } else {\n resultSign = b.sign;\n resultMagnitude = fp64_u64_sub(bMagnitude, aMagnitude);\n }\n }\n\n return fp64_split_raw_accumulator_bits(\n resultSign,\n resultMagnitude,\n commonBaseExponent\n );\n}\n#endif\n\n#ifndef LUMA_FP64_F32_INPUT_ONLY\nfn fp64_add_aligned_magnitudes_to_fp64_bits(\n sign: u32,\n larger: Fp64Bits,\n smaller: Fp64Bits\n) -> vec2u {\n let largeSignificand = fp64_u64_shift_left(larger.significand, 3u);\n let smallSignificand = fp64_u64_shift_right_sticky(\n fp64_u64_shift_left(smaller.significand, 3u),\n u32(larger.exponent - smaller.exponent)\n );\n let resultSignificand = fp64_u64_add(largeSignificand, smallSignificand);\n return fp64_split_binary64_accumulator_bits(\n sign,\n resultSignificand,\n larger.exponent - 55\n );\n}\n\nfn fp64_sub_aligned_magnitudes_to_fp64_bits(\n sign: u32,\n larger: Fp64Bits,\n smaller: Fp64Bits\n) -> vec2u {\n let largeSignificand = fp64_u64_shift_left(larger.significand, 3u);\n let smallSignificand = fp64_u64_shift_right_sticky(\n fp64_u64_shift_left(smaller.significand, 3u),\n u32(larger.exponent - smaller.exponent)\n );\n let resultSignificand = fp64_u64_sub(largeSignificand, smallSignificand);\n return fp64_split_binary64_accumulator_bits(\n sign,\n resultSignificand,\n larger.exponent - 55\n );\n}\n\nfn fp64_add_aligned_magnitudes_to_f32_bits(sign: u32, larger: Fp64Bits, smaller: Fp64Bits) -> u32 {\n let largeSignificand = fp64_u64_shift_left(larger.significand, 3u);\n let smallSignificand = fp64_u64_shift_right_sticky(\n fp64_u64_shift_left(smaller.significand, 3u),\n u32(larger.exponent - smaller.exponent)\n );\n let resultSignificand = fp64_u64_add(largeSignificand, smallSignificand);\n return fp64_make_f32_bits_from_u64(sign, resultSignificand, larger.exponent - 55);\n}\n\nfn fp64_sub_aligned_magnitudes_to_f32_bits(sign: u32, larger: Fp64Bits, smaller: Fp64Bits) -> u32 {\n let largeSignificand = fp64_u64_shift_left(larger.significand, 3u);\n let smallSignificand = fp64_u64_shift_right_sticky(\n fp64_u64_shift_left(smaller.significand, 3u),\n u32(larger.exponent - smaller.exponent)\n );\n let resultSignificand = fp64_u64_sub(largeSignificand, smallSignificand);\n return fp64_make_f32_bits_from_u64(sign, resultSignificand, larger.exponent - 55);\n}\n\n// Subtract two raw binary64 values and round the exact result once to f32.\n// The input words are canonical high/low words: .x contains sign/exponent/high\n// fraction bits, and .y contains the low 32 fraction bits.\nfn sub_fp64u32_to_f32_bits(aBits: vec2u, bBits: vec2u) -> u32 {\n let a = fp64_decode_bits(aBits);\n let b = fp64_decode_bits(bBits);\n let bSubtractionSign = b.sign ^ 1u;\n\n if (a.isNan || b.isNan) {\n return 0x7fc00000u;\n }\n if (a.isInf && b.isInf) {\n if (a.sign == bSubtractionSign) {\n return (a.sign << 31u) | 0x7f800000u;\n }\n return 0x7fc00000u;\n }\n if (a.isInf) {\n return (a.sign << 31u) | 0x7f800000u;\n }\n if (b.isInf) {\n return (bSubtractionSign << 31u) | 0x7f800000u;\n }\n if (a.isZero && b.isZero) {\n return select(0u, 0x80000000u, a.sign == 1u && b.sign == 0u);\n }\n\n let magnitudeComparison = fp64_finite_magnitude_compare(a, b);\n if (a.sign == bSubtractionSign) {\n if (magnitudeComparison >= 0) {\n return fp64_add_aligned_magnitudes_to_f32_bits(a.sign, a, b);\n }\n return fp64_add_aligned_magnitudes_to_f32_bits(a.sign, b, a);\n }\n\n if (magnitudeComparison == 0) {\n return 0u;\n }\n if (magnitudeComparison > 0) {\n return fp64_sub_aligned_magnitudes_to_f32_bits(a.sign, a, b);\n }\n return fp64_sub_aligned_magnitudes_to_f32_bits(bSubtractionSign, b, a);\n}\n\nfn sub_fp64u32_to_f32(aBits: vec2u, bBits: vec2u) -> f32 {\n return bitcast<f32>(sub_fp64u32_to_f32_bits(aBits, bBits));\n}\n\n// Subtract two raw binary64 values, round once to binary64, then split the\n// result into normalized f32 limbs. Finite results must fit within the f32\n// exponent range; larger magnitudes map to infinity and smaller magnitudes\n// map to zero. The input words use canonical high/low word order.\nfn sub_fp64u32_to_fp64_bits(aBits: vec2u, bBits: vec2u) -> vec2u {\n let a = fp64_decode_bits(aBits);\n let b = fp64_decode_bits(bBits);\n let bSubtractionSign = b.sign ^ 1u;\n\n if (a.isNan || b.isNan) {\n return vec2u(0x7fc00000u, 0u);\n }\n if (a.isInf && b.isInf) {\n if (a.sign == bSubtractionSign) {\n return vec2u((a.sign << 31u) | 0x7f800000u, 0u);\n }\n return vec2u(0x7fc00000u, 0u);\n }\n if (a.isInf) {\n return vec2u((a.sign << 31u) | 0x7f800000u, 0u);\n }\n if (b.isInf) {\n return vec2u((bSubtractionSign << 31u) | 0x7f800000u, 0u);\n }\n if (a.isZero && b.isZero) {\n return vec2u(0u);\n }\n\n let magnitudeComparison = fp64_finite_magnitude_compare(a, b);\n if (a.sign == bSubtractionSign) {\n if (magnitudeComparison >= 0) {\n return fp64_add_aligned_magnitudes_to_fp64_bits(a.sign, a, b);\n }\n return fp64_add_aligned_magnitudes_to_fp64_bits(a.sign, b, a);\n }\n\n if (magnitudeComparison == 0) {\n return vec2u(0u);\n }\n if (magnitudeComparison > 0) {\n return fp64_sub_aligned_magnitudes_to_fp64_bits(a.sign, a, b);\n }\n return fp64_sub_aligned_magnitudes_to_fp64_bits(bSubtractionSign, b, a);\n}\n\nfn sub_fp64u32_to_fp64(aBits: vec2u, bBits: vec2u) -> vec2f {\n let resultBits = sub_fp64u32_to_fp64_bits(aBits, bBits);\n return vec2f(bitcast<f32>(resultBits.x), bitcast<f32>(resultBits.y));\n}\n#endif\n\n#ifndef LUMA_FP64_PREDICATE_ONLY\nfn fp64_runtime_zero() -> f32 {\n return fp64arithmetic.ONE * 0.0;\n}\n\nfn prevent_fp64_optimization(value: f32) -> f32 {\n#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND\n return value + fp64_runtime_zero();\n#else\n return value;\n#endif\n}\n#endif\n\n#ifdef LUMA_FP64_INTEGER_ARITHMETIC\nstruct Fp64F32Bits {\n sign: u32,\n baseExponent: i32,\n significand: u32,\n isZero: bool,\n isInf: bool,\n isNan: bool,\n};\n\n// Decode an f32 as (-1)^sign * significand * 2^baseExponent.\nfn fp64_decode_f32_bits(bits: u32) -> Fp64F32Bits {\n let sign = bits >> 31u;\n let exponentBits = (bits >> 23u) & 0xffu;\n let fraction = bits & 0x7fffffu;\n\n if (exponentBits == 0xffu) {\n return Fp64F32Bits(sign, 0, 0u, false, fraction == 0u, fraction != 0u);\n }\n if (exponentBits == 0u) {\n return Fp64F32Bits(sign, -149, fraction, fraction == 0u, false, false);\n }\n return Fp64F32Bits(sign, i32(exponentBits) - 150, 0x800000u | fraction, false, false, false);\n}\n\nfn fp64_f32_magnitude_compare(aBits: u32, bBits: u32) -> i32 {\n let aMagnitude = aBits & 0x7fffffffu;\n let bMagnitude = bBits & 0x7fffffffu;\n if (aMagnitude == bMagnitude) {\n return 0;\n }\n return select(-1, 1, aMagnitude > bMagnitude);\n}\n\nfn fp64_make_residual_f32_bits(\n exactSign: u32,\n exactMagnitude: vec2u,\n exactBaseExponent: i32,\n highBits: u32\n) -> u32 {\n if (fp64_u64_is_zero(exactMagnitude)) {\n return 0u;\n }\n\n let high = fp64_decode_f32_bits(highBits);\n if (high.isInf || high.isNan) {\n return exactSign << 31u;\n }\n if (high.isZero) {\n return fp64_make_f32_bits_from_u64(exactSign, exactMagnitude, exactBaseExponent);\n }\n\n let commonBaseExponent = min(exactBaseExponent, high.baseExponent);\n let exactShift = exactBaseExponent - commonBaseExponent;\n let highShift = high.baseExponent - commonBaseExponent;\n\n // A normal two-sum/two-product residual never needs a shift this large.\n // This guard gives deterministic underflow behavior outside that contract.\n if (exactShift >= 64 || highShift >= 64) {\n return exactSign << 31u;\n }\n\n let exactAligned = fp64_u64_shift_left(exactMagnitude, u32(exactShift));\n let highAligned = fp64_u64_shift_left(vec2u(0u, high.significand), u32(highShift));\n let comparison = fp64_u64_compare(exactAligned, highAligned);\n if (comparison == 0) {\n return 0u;\n }\n\n var residualSign = exactSign;\n var residualMagnitude: vec2u;\n if (comparison > 0) {\n residualMagnitude = fp64_u64_sub(exactAligned, highAligned);\n } else {\n residualSign = exactSign ^ 1u;\n residualMagnitude = fp64_u64_sub(highAligned, exactAligned);\n }\n return fp64_make_f32_bits_from_u64(\n residualSign,\n residualMagnitude,\n commonBaseExponent\n );\n}\n\nfn fp64_split_accumulator_bits(\n sign: u32,\n magnitude: vec2u,\n baseExponent: i32\n) -> vec2u {\n let highBits = fp64_make_f32_bits_from_u64(sign, magnitude, baseExponent);\n let lowBits = fp64_make_residual_f32_bits(sign, magnitude, baseExponent, highBits);\n return vec2u(highBits, lowBits);\n}\n\nfn fp64_two_sum_integer_bits(aBits: u32, bBits: u32) -> vec2u {\n let a = fp64_decode_f32_bits(aBits);\n let b = fp64_decode_f32_bits(bBits);\n\n if (a.isNan || b.isNan) {\n return vec2u(0x7fc00000u, 0u);\n }\n if (a.isInf || b.isInf) {\n if (a.isInf && b.isInf && a.sign != b.sign) {\n return vec2u(0x7fc00000u, 0u);\n }\n return select(vec2u(bBits, 0u), vec2u(aBits, 0u), a.isInf);\n }\n if (a.isZero && b.isZero) {\n return vec2u((a.sign & b.sign) << 31u, 0u);\n }\n if (a.isZero) {\n return vec2u(bBits, 0u);\n }\n if (b.isZero) {\n return vec2u(aBits, 0u);\n }\n\n let exponentDifference = select(\n b.baseExponent - a.baseExponent,\n a.baseExponent - b.baseExponent,\n a.baseExponent >= b.baseExponent\n );\n\n // Beyond half an ulp, rounding cannot change the larger operand. Returning\n // the smaller operand intact also avoids an unbounded integer alignment.\n // At a power-of-two boundary the spacing below the larger operand is half\n // the spacing above it, so an opposite-sign gap-25 operand can still change\n // the rounded high limb. Gap 26 is the first universally safe early-out.\n if (exponentDifference > 25) {\n if (fp64_f32_magnitude_compare(aBits, bBits) >= 0) {\n return vec2u(aBits, bBits);\n }\n return vec2u(bBits, aBits);\n }\n\n let commonBaseExponent = min(a.baseExponent, b.baseExponent);\n let aMagnitude = fp64_u64_shift_left(\n vec2u(0u, a.significand),\n u32(a.baseExponent - commonBaseExponent)\n );\n let bMagnitude = fp64_u64_shift_left(\n vec2u(0u, b.significand),\n u32(b.baseExponent - commonBaseExponent)\n );\n\n var resultSign = a.sign;\n var resultMagnitude: vec2u;\n if (a.sign == b.sign) {\n resultMagnitude = fp64_u64_add(aMagnitude, bMagnitude);\n } else {\n let comparison = fp64_u64_compare(aMagnitude, bMagnitude);\n if (comparison == 0) {\n return vec2u(0u, 0u);\n }\n if (comparison > 0) {\n resultMagnitude = fp64_u64_sub(aMagnitude, bMagnitude);\n } else {\n resultSign = b.sign;\n resultMagnitude = fp64_u64_sub(bMagnitude, aMagnitude);\n }\n }\n\n return fp64_split_accumulator_bits(resultSign, resultMagnitude, commonBaseExponent);\n}\n\nfn fp64_two_sum_integer(a: f32, b: f32) -> vec2f {\n let resultBits = fp64_two_sum_integer_bits(bitcast<u32>(a), bitcast<u32>(b));\n return vec2f(bitcast<f32>(resultBits.x), bitcast<f32>(resultBits.y));\n}\n\nfn fp64_multiply_significands(a: u32, b: u32) -> vec2u {\n let aLow = a & 0xffffu;\n let aHigh = a >> 16u;\n let bLow = b & 0xffffu;\n let bHigh = b >> 16u;\n let lowProduct = aLow * bLow;\n let crossProduct = aLow * bHigh + aHigh * bLow;\n let highProduct = aHigh * bHigh;\n\n var result = vec2u(0u, lowProduct);\n result = fp64_u64_add(\n result,\n fp64_u64_shift_left(vec2u(0u, crossProduct), 16u)\n );\n result = fp64_u64_add(result, vec2u(highProduct, 0u));\n return result;\n}\n\nfn fp64_two_prod_integer_bits(aBits: u32, bBits: u32) -> vec2u {\n let a = fp64_decode_f32_bits(aBits);\n let b = fp64_decode_f32_bits(bBits);\n let resultSign = a.sign ^ b.sign;\n\n if (a.isNan || b.isNan || ((a.isZero || b.isZero) && (a.isInf || b.isInf))) {\n return vec2u(0x7fc00000u, 0u);\n }\n if (a.isInf || b.isInf) {\n return vec2u((resultSign << 31u) | 0x7f800000u, resultSign << 31u);\n }\n if (a.isZero || b.isZero) {\n return vec2u(resultSign << 31u, resultSign << 31u);\n }\n\n let magnitude = fp64_multiply_significands(a.significand, b.significand);\n return fp64_split_accumulator_bits(\n resultSign,\n magnitude,\n a.baseExponent + b.baseExponent\n );\n}\n\nfn fp64_two_prod_integer(a: f32, b: f32) -> vec2f {\n let resultBits = fp64_two_prod_integer_bits(bitcast<u32>(a), bitcast<u32>(b));\n return vec2f(bitcast<f32>(resultBits.x), bitcast<f32>(resultBits.y));\n}\n\nfn fp64_round_add_integer(a: f32, b: f32) -> f32 {\n return fp64_two_sum_integer(a, b).x;\n}\n\nfn fp64_round_mul_integer(a: f32, b: f32) -> f32 {\n return fp64_two_prod_integer(a, b).x;\n}\n\n#ifndef LUMA_FP64_PREDICATE_ONLY\nfn fp64_f32_finite_exponent(value: Fp64F32Bits) -> i32 {\n let mostSignificantBit = 31u - countLeadingZeros(value.significand);\n return value.baseExponent + i32(mostSignificantBit);\n}\n\nfn fp64_scale_f32_integer(value: f32, exponent: i32) -> f32 {\n let decoded = fp64_decode_f32_bits(bitcast<u32>(value));\n if (decoded.isZero || decoded.isInf || decoded.isNan) {\n return value;\n }\n let resultBits = fp64_make_f32_bits_from_u64(\n decoded.sign,\n vec2u(0u, decoded.significand),\n decoded.baseExponent + exponent\n );\n return bitcast<f32>(resultBits);\n}\n\n// Divide normalized significands so the hardware operation cannot overflow,\n// underflow, or flush a subnormal result. Reapply the exponent with integer\n// packing, which also produces subnormal correction limbs without relying on\n// floating-point arithmetic to preserve them.\nfn fp64_divide_f32_integer(aValue: f32, bValue: f32) -> f32 {\n let a = fp64_decode_f32_bits(bitcast<u32>(aValue));\n let b = fp64_decode_f32_bits(bitcast<u32>(bValue));\n if (a.isZero || b.isZero || a.isInf || b.isInf || a.isNan || b.isNan) {\n return aValue / bValue;\n }\n\n let aMostSignificantBit = 31u - countLeadingZeros(a.significand);\n let bMostSignificantBit = 31u - countLeadingZeros(b.significand);\n let normalizedABits = fp64_make_f32_bits_from_u64(\n a.sign,\n vec2u(0u, a.significand),\n -i32(aMostSignificantBit)\n );\n let normalizedBBits = fp64_make_f32_bits_from_u64(\n b.sign,\n vec2u(0u, b.significand),\n -i32(bMostSignificantBit)\n );\n let normalizedQuotient = bitcast<f32>(normalizedABits) / bitcast<f32>(normalizedBBits);\n let quotient = fp64_decode_f32_bits(bitcast<u32>(normalizedQuotient));\n let exponentShift =\n a.baseExponent + i32(aMostSignificantBit) -\n b.baseExponent - i32(bMostSignificantBit);\n let quotientBits = fp64_make_f32_bits_from_u64(\n quotient.sign,\n vec2u(0u, quotient.significand),\n quotient.baseExponent + exponentShift\n );\n return bitcast<f32>(quotientBits);\n}\n#endif\n\n#ifndef LUMA_FP64_PREDICATE_ONLY\nfn split(a: f32) -> vec2f {\n let aBits = bitcast<u32>(a);\n let decoded = fp64_decode_f32_bits(aBits);\n if (decoded.isZero || decoded.isInf || decoded.isNan) {\n return vec2f(a, 0.0);\n }\n\n var roundedHigh = decoded.significand >> 12u;\n let remainder = decoded.significand & 0xfffu;\n if (remainder > 0x800u || (remainder == 0x800u && (roundedHigh & 1u) == 1u)) {\n roundedHigh = roundedHigh + 1u;\n }\n var highMagnitude = vec2u(0u, roundedHigh << 12u);\n var highBits = fp64_make_f32_bits_from_u64(\n decoded.sign,\n highMagnitude,\n decoded.baseExponent\n );\n // Rounding the high limb of a maximum-exponent value can overflow even\n // though the original value is finite. Truncate only in that boundary case\n // so split remains an exact finite decomposition.\n if (fp64_decode_f32_bits(highBits).isInf) {\n roundedHigh = decoded.significand >> 12u;\n highMagnitude = vec2u(0u, roundedHigh << 12u);\n highBits = fp64_make_f32_bits_from_u64(\n decoded.sign,\n highMagnitude,\n decoded.baseExponent\n );\n }\n let lowBits = fp64_make_residual_f32_bits(\n decoded.sign,\n vec2u(0u, decoded.significand),\n decoded.baseExponent,\n highBits\n );\n return vec2f(bitcast<f32>(highBits), bitcast<f32>(lowBits));\n}\n\nfn split2(a: vec2f) -> vec2f {\n var result = split(a.x);\n result.y = fp64_round_add_integer(result.y, a.y);\n return result;\n}\n#endif\n\n#ifndef LUMA_FP64_PREDICATE_ONLY\nfn quickTwoSum(a: f32, b: f32) -> vec2f {\n return fp64_two_sum_integer(a, b);\n}\n#endif\n\nfn twoSum(a: f32, b: f32) -> vec2f {\n return fp64_two_sum_integer(a, b);\n}\n\nfn twoSub(a: f32, b: f32) -> vec2f {\n let bBits = bitcast<u32>(b) ^ 0x80000000u;\n let resultBits = fp64_two_sum_integer_bits(bitcast<u32>(a), bBits);\n return vec2f(bitcast<f32>(resultBits.x), bitcast<f32>(resultBits.y));\n}\n\n#ifndef LUMA_FP64_PREDICATE_ONLY\nfn twoSqr(a: f32) -> vec2f {\n return fp64_two_prod_integer(a, a);\n}\n\nfn twoProd(a: f32, b: f32) -> vec2f {\n return fp64_two_prod_integer(a, b);\n}\n#endif\n\nfn sum_fp64(a: vec2f, b: vec2f) -> vec2f {\n var sum = fp64_two_sum_integer(a.x, b.x);\n let lowSum = fp64_two_sum_integer(a.y, b.y);\n sum.y = fp64_round_add_integer(sum.y, lowSum.x);\n sum = fp64_two_sum_integer(sum.x, sum.y);\n sum.y = fp64_round_add_integer(sum.y, lowSum.y);\n return fp64_two_sum_integer(sum.x, sum.y);\n}\n\nfn sub_fp64(a: vec2f, b: vec2f) -> vec2f {\n let negatedB = vec2f(\n bitcast<f32>(bitcast<u32>(b.x) ^ 0x80000000u),\n bitcast<f32>(bitcast<u32>(b.y) ^ 0x80000000u)\n );\n return sum_fp64(a, negatedB);\n}\n\nfn mul_fp64(a: vec2f, b: vec2f) -> vec2f {\n var product = fp64_two_prod_integer(a.x, b.x);\n let crossProduct1 = fp64_round_mul_integer(a.x, b.y);\n product.y = fp64_round_add_integer(product.y, crossProduct1);\n product = fp64_two_sum_integer(product.x, product.y);\n let crossProduct2 = fp64_round_mul_integer(a.y, b.x);\n product.y = fp64_round_add_integer(product.y, crossProduct2);\n return fp64_two_sum_integer(product.x, product.y);\n}\n\n#ifndef LUMA_FP64_PREDICATE_ONLY\nfn fp64_scale_fp64_integer(value: vec2f, exponent: i32) -> vec2f {\n let high = fp64_scale_f32_integer(value.x, exponent);\n let low = fp64_scale_f32_integer(value.y, exponent);\n return sum_fp64(vec2f(high, 0.0), vec2f(low, 0.0));\n}\n\nfn fp64_div_fp64_normalized(a: vec2f, b: vec2f) -> vec2f {\n let quotientHigh = fp64_divide_f32_integer(a.x, b.x);\n var quotient = vec2f(quotientHigh, 0.0);\n\n let remainder = sub_fp64(a, mul_fp64(b, quotient));\n let quotientLow = fp64_divide_f32_integer(remainder.x, b.x);\n quotient = sum_fp64(quotient, vec2f(quotientLow, 0.0));\n\n let secondRemainder = sub_fp64(a, mul_fp64(b, quotient));\n let correction = fp64_divide_f32_integer(secondRemainder.x, b.x);\n return sum_fp64(quotient, vec2f(correction, 0.0));\n}\n\nfn div_fp64(a: vec2f, b: vec2f) -> vec2f {\n let decodedA = fp64_decode_f32_bits(bitcast<u32>(a.x));\n let decodedB = fp64_decode_f32_bits(bitcast<u32>(b.x));\n if (\n decodedA.isZero || decodedB.isZero ||\n decodedA.isInf || decodedB.isInf ||\n decodedA.isNan || decodedB.isNan\n ) {\n return fp64_div_fp64_normalized(a, b);\n }\n\n let exponentA = fp64_f32_finite_exponent(decodedA);\n let exponentB = fp64_f32_finite_exponent(decodedB);\n // Correct the quotient near unity so b * q and the remainder stay clear of\n // both f32 underflow and overflow. The exponent difference is applied once.\n let normalizedA = fp64_scale_fp64_integer(a, -exponentA);\n let normalizedB = fp64_scale_fp64_integer(b, -exponentB);\n let normalizedQuotient = fp64_div_fp64_normalized(normalizedA, normalizedB);\n return fp64_scale_fp64_integer(normalizedQuotient, exponentA - exponentB);\n}\n\nfn fp64_sqrt_fp64_normalized(a: vec2f) -> vec2f {\n let estimate = sqrt(a.x);\n let difference = sub_fp64(a, fp64_two_prod_integer(estimate, estimate)).x;\n let denominator = fp64_round_add_integer(estimate, estimate);\n let correction = fp64_divide_f32_integer(difference, denominator);\n return sum_fp64(vec2f(estimate, 0.0), vec2f(correction, 0.0));\n}\n\nfn sqrt_fp64(a: vec2f) -> vec2f {\n let decoded = fp64_decode_f32_bits(bitcast<u32>(a.x));\n let decodedLow = fp64_decode_f32_bits(bitcast<u32>(a.y));\n if (decoded.isZero && decodedLow.isZero) {\n return vec2f(0.0, 0.0);\n }\n if (decoded.sign == 1u) {\n let nanValue = fp64_nan(a.x);\n return vec2f(nanValue, nanValue);\n }\n\n if (decoded.isInf || decoded.isNan) {\n return fp64_sqrt_fp64_normalized(a);\n }\n let exponent = fp64_f32_finite_exponent(decoded);\n // An even scale lets the final square-root rescale use an integer exponent.\n let evenExponent = exponent - (exponent & 1);\n let normalizedA = fp64_scale_fp64_integer(a, -evenExponent);\n let normalizedRoot = fp64_sqrt_fp64_normalized(normalizedA);\n return fp64_scale_fp64_integer(normalizedRoot, evenExponent / 2);\n}\n#endif\n\n#else\nfn split(a: f32) -> vec2f {\n let splitValue = prevent_fp64_optimization(fp64arithmetic.SPLIT + fp64_runtime_zero());\n let t = prevent_fp64_optimization(a * splitValue);\n let temp = prevent_fp64_optimization(t - a);\n let aHi = prevent_fp64_optimization(t - temp);\n let aLo = prevent_fp64_optimization(a - aHi);\n return vec2f(aHi, aLo);\n}\n\nfn split2(a: vec2f) -> vec2f {\n var b = split(a.x);\n b.y = b.y + a.y;\n return b;\n}\n\nfn quickTwoSum(a: f32, b: f32) -> vec2f {\n#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND\n let sum = prevent_fp64_optimization((a + b) * fp64arithmetic.ONE);\n let err = prevent_fp64_optimization(b - (sum - a) * fp64arithmetic.ONE);\n#else\n let sum = prevent_fp64_optimization(a + b);\n let err = prevent_fp64_optimization(b - (sum - a));\n#endif\n return vec2f(sum, err);\n}\n\nfn twoSum(a: f32, b: f32) -> vec2f {\n let s = prevent_fp64_optimization(a + b);\n#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND\n let v = prevent_fp64_optimization((s * fp64arithmetic.ONE - a) * fp64arithmetic.ONE);\n let err =\n prevent_fp64_optimization((a - (s - v) * fp64arithmetic.ONE) *\n fp64arithmetic.ONE *\n fp64arithmetic.ONE *\n fp64arithmetic.ONE) +\n prevent_fp64_optimization(b - v);\n#else\n let v = prevent_fp64_optimization(s - a);\n let err = prevent_fp64_optimization(a - (s - v)) + prevent_fp64_optimization(b - v);\n#endif\n return vec2f(s, err);\n}\n\nfn twoSub(a: f32, b: f32) -> vec2f {\n let s = prevent_fp64_optimization(a - b);\n#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND\n let v = prevent_fp64_optimization((s * fp64arithmetic.ONE - a) * fp64arithmetic.ONE);\n let err =\n prevent_fp64_optimization((a - (s - v) * fp64arithmetic.ONE) *\n fp64arithmetic.ONE *\n fp64arithmetic.ONE *\n fp64arithmetic.ONE) -\n prevent_fp64_optimization(b + v);\n#else\n let v = prevent_fp64_optimization(s - a);\n let err = prevent_fp64_optimization(a - (s - v)) - prevent_fp64_optimization(b + v);\n#endif\n return vec2f(s, err);\n}\n\nfn twoSqr(a: f32) -> vec2f {\n let prod = prevent_fp64_optimization(a * a);\n let aFp64 = split(a);\n let highProduct = prevent_fp64_optimization(aFp64.x * aFp64.x);\n let crossProduct = prevent_fp64_optimization(2.0 * aFp64.x * aFp64.y);\n let lowProduct = prevent_fp64_optimization(aFp64.y * aFp64.y);\n#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND\n let err =\n (prevent_fp64_optimization(highProduct - prod) * fp64arithmetic.ONE +\n crossProduct * fp64arithmetic.ONE * fp64arithmetic.ONE) +\n lowProduct * fp64arithmetic.ONE * fp64arithmetic.ONE * fp64arithmetic.ONE;\n#else\n let err = ((prevent_fp64_optimization(highProduct - prod) + crossProduct) + lowProduct);\n#endif\n return vec2f(prod, err);\n}\n\nfn twoProd(a: f32, b: f32) -> vec2f {\n let prod = prevent_fp64_optimization(a * b);\n let aFp64 = split(a);\n let bFp64 = split(b);\n let highProduct = prevent_fp64_optimization(aFp64.x * bFp64.x);\n let crossProduct1 = prevent_fp64_optimization(aFp64.x * bFp64.y);\n let crossProduct2 = prevent_fp64_optimization(aFp64.y * bFp64.x);\n let lowProduct = prevent_fp64_optimization(aFp64.y * bFp64.y);\n#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND\n let err1 = (highProduct - prod) * fp64arithmetic.ONE;\n let err2 = crossProduct1 * fp64arithmetic.ONE * fp64arithmetic.ONE;\n let err3 = crossProduct2 * fp64arithmetic.ONE * fp64arithmetic.ONE * fp64arithmetic.ONE;\n let err4 =\n lowProduct *\n fp64arithmetic.ONE *\n fp64arithmetic.ONE *\n fp64arithmetic.ONE *\n fp64arithmetic.ONE;\n#else\n let err1 = highProduct - prod;\n let err2 = crossProduct1;\n let err3 = crossProduct2;\n let err4 = lowProduct;\n#endif\n let err12InputA = prevent_fp64_optimization(err1);\n let err12InputB = prevent_fp64_optimization(err2);\n let err12 = prevent_fp64_optimization(err12InputA + err12InputB);\n let err123InputA = prevent_fp64_optimization(err12);\n let err123InputB = prevent_fp64_optimization(err3);\n let err123 = prevent_fp64_optimization(err123InputA + err123InputB);\n let err1234InputA = prevent_fp64_optimization(err123);\n let err1234InputB = prevent_fp64_optimization(err4);\n let err = prevent_fp64_optimization(err1234InputA + err1234InputB);\n return vec2f(prod, err);\n}\n\nfn sum_fp64(a: vec2f, b: vec2f) -> vec2f {\n var s = twoSum(a.x, b.x);\n let t = twoSum(a.y, b.y);\n s.y = prevent_fp64_optimization(s.y + t.x);\n s = quickTwoSum(s.x, s.y);\n s.y = prevent_fp64_optimization(s.y + t.y);\n s = quickTwoSum(s.x, s.y);\n return s;\n}\n\nfn sub_fp64(a: vec2f, b: vec2f) -> vec2f {\n var s = twoSub(a.x, b.x);\n let t = twoSub(a.y, b.y);\n s.y = prevent_fp64_optimization(s.y + t.x);\n s = quickTwoSum(s.x, s.y);\n s.y = prevent_fp64_optimization(s.y + t.y);\n s = quickTwoSum(s.x, s.y);\n return s;\n}\n\nfn mul_fp64(a: vec2f, b: vec2f) -> vec2f {\n var prod = twoProd(a.x, b.x);\n let crossProduct1 = prevent_fp64_optimization(a.x * b.y);\n prod.y = prevent_fp64_optimization(prod.y + crossProduct1);\n#ifdef LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND\n prod = split2(prod);\n#endif\n prod = quickTwoSum(prod.x, prod.y);\n let crossProduct2 = prevent_fp64_optimization(a.y * b.x);\n prod.y = prevent_fp64_optimization(prod.y + crossProduct2);\n#ifdef LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND\n prod = split2(prod);\n#endif\n prod = quickTwoSum(prod.x, prod.y);\n return prod;\n}\n\n#ifndef LUMA_FP64_PREDICATE_ONLY\nfn div_fp64(a: vec2f, b: vec2f) -> vec2f {\n let xn = prevent_fp64_optimization(1.0 / b.x);\n let yn = mul_fp64(a, vec2f(xn, fp64_runtime_zero()));\n let diff = prevent_fp64_optimization(sub_fp64(a, mul_fp64(b, yn)).x);\n let prod = twoProd(xn, diff);\n return sum_fp64(yn, prod);\n}\n\nfn sqrt_fp64(a: vec2f) -> vec2f {\n if (a.x == 0.0 && a.y == 0.0) {\n return vec2f(0.0, 0.0);\n }\n if (a.x < 0.0) {\n let nanValue = fp64_nan(a.x);\n return vec2f(nanValue, nanValue);\n }\n\n let x = prevent_fp64_optimization(1.0 / sqrt(a.x));\n let yn = prevent_fp64_optimization(a.x * x);\n#ifdef LUMA_FP64_CODE_ELIMINATION_WORKAROUND\n let ynSqr = twoSqr(yn) * fp64arithmetic.ONE;\n#else\n let ynSqr = twoSqr(yn);\n#endif\n let diff = prevent_fp64_optimization(sub_fp64(a, ynSqr).x);\n let prod = twoProd(prevent_fp64_optimization(x * 0.5), diff);\n#ifdef LUMA_FP64_HIGH_BITS_OVERFLOW_WORKAROUND\n return sum_fp64(split(yn), prod);\n#else\n return sum_fp64(vec2f(yn, 0.0), prod);\n#endif\n}\n#endif\n#endif\n\n#ifndef LUMA_FP64_PREDICATE_ONLY\nfn fp64_f32_bits_is_nan(bits: u32) -> bool {\n return (bits & 0x7fffffffu) > 0x7f800000u;\n}\n\nfn fp64_f32_bits_is_inf(bits: u32) -> bool {\n return (bits & 0x7fffffffu) == 0x7f800000u;\n}\n\nfn fp64_compare_f32_bits(aBits: u32, bBits: u32) -> i32 {\n let aMagnitude = aBits & 0x7fffffffu;\n let bMagnitude = bBits & 0x7fffffffu;\n if (aMagnitude == 0u && bMagnitude == 0u) {\n return 0;\n }\n let aSign = aBits >> 31u;\n let bSign = bBits >> 31u;\n if (aSign != bSign) {\n return select(1, -1, aSign == 1u);\n }\n if (aMagnitude == bMagnitude) {\n return 0;\n }\n let magnitudeComparison = select(-1, 1, aMagnitude > bMagnitude);\n return select(magnitudeComparison, -magnitudeComparison, aSign == 1u);\n}\n\n// Normalize an arbitrary pair of finite f32 limbs with integer accumulation.\n// This is independent of LUMA_FP64_INTEGER_ARITHMETIC and canonicalizes every\n// representation of zero to vec2f(+0.0, +0.0).\nfn normalize_fp64(value: vec2f) -> vec2f {\n let resultBits = fp64_add_raw_f32_bits(bitcast<u32>(value.x), bitcast<u32>(value.y));\n return vec2f(bitcast<f32>(resultBits.x), bitcast<f32>(resultBits.y));\n}\n\nfn is_nan_fp64(value: vec2f) -> bool {\n let normalized = normalize_fp64(value);\n return fp64_f32_bits_is_nan(bitcast<u32>(normalized.x)) ||\n fp64_f32_bits_is_nan(bitcast<u32>(normalized.y));\n}\n\nfn is_finite_fp64(value: vec2f) -> bool {\n let normalized = normalize_fp64(value);\n let highBits = bitcast<u32>(normalized.x);\n let lowBits = bitcast<u32>(normalized.y);\n return !fp64_f32_bits_is_nan(highBits) && !fp64_f32_bits_is_nan(lowBits) &&\n !fp64_f32_bits_is_inf(highBits) && !fp64_f32_bits_is_inf(lowBits);\n}\n\n// Returns -1, 0, or 1. NaN is unordered and returns 0; call is_nan_fp64 or\n// is_finite_fp64 first when 0 must mean a finite zero.\nfn sign_fp64(value: vec2f) -> i32 {\n let normalized = normalize_fp64(value);\n let highBits = bitcast<u32>(normalized.x);\n let lowBits = bitcast<u32>(normalized.y);\n if (fp64_f32_bits_is_nan(highBits) || fp64_f32_bits_is_nan(lowBits)) {\n return 0;\n }\n if ((highBits & 0x7fffffffu) != 0u) {\n return select(1, -1, (highBits >> 31u) == 1u);\n }\n if ((lowBits & 0x7fffffffu) != 0u) {\n return select(1, -1, (lowBits >> 31u) == 1u);\n }\n return 0;\n}\n\n// Compares double-single values and returns -1, 0, or 1. NaN is unordered\n// and returns 0; callers that require equality semantics must first check\n// is_nan_fp64 or is_finite_fp64.\nfn compare_fp64(a: vec2f, b: vec2f) -> i32 {\n let normalizedA = normalize_fp64(a);\n let normalizedB = normalize_fp64(b);\n let aHighBits = bitcast<u32>(normalizedA.x);\n let aLowBits = bitcast<u32>(normalizedA.y);\n let bHighBits = bitcast<u32>(normalizedB.x);\n let bLowBits = bitcast<u32>(normalizedB.y);\n if (fp64_f32_bits_is_nan(aHighBits) || fp64_f32_bits_is_nan(aLowBits) ||\n fp64_f32_bits_is_nan(bHighBits) || fp64_f32_bits_is_nan(bLowBits)) {\n return 0;\n }\n let highComparison = fp64_compare_f32_bits(aHighBits, bHighBits);\n if (highComparison != 0) {\n return highComparison;\n }\n return fp64_compare_f32_bits(aLowBits, bLowBits);\n}\n#endif\n",fs:Le,vs:Le,defaultUniforms:{ONE:1,SPLIT:4097},uniformTypes:{ONE:"f32",SPLIT:"f32"},fp64ify:Ce,fp64LowPart:function(e){return e-Math.fround(e)},fp64ifyMatrix4:function(e){const t=/* @__PURE__ */new Float32Array(32);for(let n=0;n<4;++n)for(let i=0;i<4;++i){const o=4*n+i;Ce(e[4*i+n],t,2*o)}return t}},Ie={rgba8unorm:4,rgba16float:8,rgba32float:16},Ee=(Uint32Array.BYTES_PER_ELEMENT,Te("colors"),Te("floatColors"));Oe("colors");function Te(e){return`layout(std140) uniform ${e}Uniforms {\n float useByteColors;\n} ${e};\n\nvec3 ${e}_normalize(vec3 inputColor) {\n return ${e}.useByteColors > 0.5 ? inputColor / 255.0 : inputColor;\n}\n\nvec4 ${e}_normalize(vec4 inputColor) {\n return ${e}.useByteColors > 0.5 ? inputColor / 255.0 : inputColor;\n}\n\nvec4 ${e}_premultiplyAlpha(vec4 inputColor) {\n return vec4(inputColor.rgb * inputColor.a, inputColor.a);\n}\n\nvec4 ${e}_unpremultiplyAlpha(vec4 inputColor) {\n return inputColor.a > 0.0 ? vec4(inputColor.rgb / inputColor.a, inputColor.a) : vec4(0.0);\n}\n\nvec4 ${e}_premultiply_alpha(vec4 inputColor) {\n return ${e}_premultiplyAlpha(inputColor);\n}\n\nvec4 ${e}_unpremultiply_alpha(vec4 inputColor) {\n return ${e}_unpremultiplyAlpha(inputColor);\n}\n`}function Oe(e){return`struct ${e}Uniforms {\n useByteColors: f32\n};\n\n@group(0) @binding(auto) var<uniform> ${e} : ${e}Uniforms;\n\nfn ${e}_normalize(inputColor: vec3<f32>) -> vec3<f32> {\n return select(inputColor, inputColor / 255.0, ${e}.useByteColors > 0.5);\n}\n\nfn ${e}_normalize4(inputColor: vec4<f32>) -> vec4<f32> {\n return select(inputColor, inputColor / 255.0, ${e}.useByteColors > 0.5);\n}\n\nfn ${e}_premultiplyAlpha(inputColor: vec4<f32>) -> vec4<f32> {\n return vec4<f32>(inputColor.rgb * inputColor.a, inputColor.a);\n}\n\nfn ${e}_unpremultiplyAlpha(inputColor: vec4<f32>) -> vec4<f32> {\n return select(\n vec4<f32>(0.0),\n vec4<f32>(inputColor.rgb / inputColor.a, inputColor.a),\n inputColor.a > 0.0\n );\n}\n\nfn ${e}_premultiply_alpha(inputColor: vec4<f32>) -> vec4<f32> {\n return ${e}_premultiplyAlpha(inputColor);\n}\n\nfn ${e}_unpremultiply_alpha(inputColor: vec4<f32>) -> vec4<f32> {\n return ${e}_unpremultiplyAlpha(inputColor);\n}\n`}var ze={name:"floatColors",props:{},uniforms:{},vs:Ee,fs:Ee,source:Oe("floatColors"),uniformTypes:{useByteColors:"f32"},defaultUniforms:{useByteColors:!0}},Me={props:{},uniforms:{},name:"picking",uniformTypes:{isActive:"f32",isAttribute:"f32",isHighlightActive:"f32",useByteColors:"f32",highlightedObjectColor:"vec3<f32>",highlightColor:"vec4<f32>"},defaultUniforms:{isActive:!1,isAttribute:!1,isHighlightActive:!1,useByteColors:!0,highlightedObjectColor:[0,0,0],highlightColor:[0,1,1,1]},vs:"layout(std140) uniform pickingUniforms {\n float isActive;\n float isAttribute;\n float isHighlightActive;\n float useByteColors;\n vec3 highlightedObjectColor;\n vec4 highlightColor;\n} picking;\n\nout vec4 picking_vRGBcolor_Avalid;\n\n// Normalize unsigned byte color to 0-1 range\nvec3 picking_normalizeColor(vec3 color) {\n return picking.useByteColors > 0.5 ? color / 255.0 : color;\n}\n\n// Normalize unsigned byte color to 0-1 range\nvec4 picking_normalizeColor(vec4 color) {\n return picking.useByteColors > 0.5 ? color / 255.0 : color;\n}\n\nbool picking_isColorZero(vec3 color) {\n return dot(color, vec3(1.0)) < 0.00001;\n}\n\nbool picking_isColorValid(vec3 color) {\n return dot(color, vec3(1.0)) > 0.00001;\n}\n\n// Check if this vertex is highlighted \nbool isVertexHighlighted(vec3 vertexColor) {\n vec3 highlightedObjectColor = picking_normalizeColor(picking.highlightedObjectColor);\n return\n bool(picking.isHighlightActive) && picking_isColorZero(abs(vertexColor - highlightedObjectColor));\n}\n\n// Set the current picking color\nvoid picking_setPickingColor(vec3 pickingColor) {\n pickingColor = picking_normalizeColor(pickingColor);\n\n if (bool(picking.isActive)) {\n // Use alpha as the validity flag. If pickingColor is [0, 0, 0] fragment is non-pickable\n picking_vRGBcolor_Avalid.a = float(picking_isColorValid(pickingColor));\n\n if (!bool(picking.isAttribute)) {\n // Stores the picking color so that the fragment shader can render it during picking\n picking_vRGBcolor_Avalid.rgb = pickingColor;\n }\n } else {\n // Do the comparison with selected item color in vertex shader as it should mean fewer compares\n picking_vRGBcolor_Avalid.a = float(isVertexHighlighted(pickingColor));\n }\n}\n\nvoid picking_setPickingAttribute(float value) {\n if (bool(picking.isAttribute)) {\n picking_vRGBcolor_Avalid.r = value;\n }\n}\n\nvoid picking_setPickingAttribute(vec2 value) {\n if (bool(picking.isAttribute)) {\n picking_vRGBcolor_Avalid.rg = value;\n }\n}\n\nvoid picking_setPickingAttribute(vec3 value) {\n if (bool(picking.isAttribute)) {\n picking_vRGBcolor_Avalid.rgb = value;\n }\n}\n",fs:"layout(std140) uniform pickingUniforms {\n float isActive;\n float isAttribute;\n float isHighlightActive;\n float useByteColors;\n vec3 highlightedObjectColor;\n vec4 highlightColor;\n} picking;\n\nin vec4 picking_vRGBcolor_Avalid;\n\n/*\n * Returns highlight color if this item is selected.\n */\nvec4 picking_filterHighlightColor(vec4 color) {\n // If we are still picking, we don't highlight\n if (picking.isActive > 0.5) {\n return color;\n }\n\n bool selected = bool(picking_vRGBcolor_Avalid.a);\n\n if (selected) {\n // Blend in highlight color based on its alpha value\n float highLightAlpha = picking.highlightColor.a;\n float blendedAlpha = highLightAlpha + color.a * (1.0 - highLightAlpha);\n float highLightRatio = highLightAlpha / blendedAlpha;\n\n vec3 blendedRGB = mix(color.rgb, picking.highlightColor.rgb, highLightRatio);\n return vec4(blendedRGB, blendedAlpha);\n } else {\n return color;\n }\n}\n\n/*\n * Returns picking color if picking enabled else unmodified argument.\n */\nvec4 picking_filterPickingColor(vec4 color) {\n if (bool(picking.isActive)) {\n if (picking_vRGBcolor_Avalid.a == 0.0) {\n discard;\n }\n return picking_vRGBcolor_Avalid;\n }\n return color;\n}\n\n/*\n * Returns picking color if picking is enabled if not\n * highlight color if this item is selected, otherwise unmodified argument.\n */\nvec4 picking_filterColor(vec4 color) {\n vec4 highlightColor = picking_filterHighlightColor(color);\n return picking_filterPickingColor(highlightColor);\n}\n",getUniforms:function(e={},t){const n={},i=we(e.useByteColors,!0);void 0===e.highlightedObjectColor||(null===e.highlightedObjectColor?n.isHighlightActive=!1:(n.isHighlightActive=!0,n.highlightedObjectColor=e.highlightedObjectColor.slice(0,3)));e.highlightColor&&(n.highlightColor=function(e,t=!0){const n=Se(e.slice(0,3),t),i=Number.isFinite(e[3]),o=i?e[3]:1;return[n[0],n[1],n[2],t&&i?o/255:o]}(e.highlightColor,i));void 0!==e.isActive&&(n.isActive=Boolean(e.isActive),n.isAttribute=Boolean(e.isAttribute));void 0!==e.useByteColors&&(n.useByteColors=Boolean(e.useByteColors));return n}};var Re="precision highp int;\n\n// #if (defined(SHADER_TYPE_FRAGMENT) && defined(LIGHTING_FRAGMENT)) || (defined(SHADER_TYPE_VERTEX) && defined(LIGHTING_VERTEX))\nstruct AmbientLight {\n vec3 color;\n};\n\nstruct PointLight {\n vec3 color;\n vec3 position;\n vec3 attenuation; // 2nd order x:Constant-y:Linear-z:Exponential\n};\n\nstruct SpotLight {\n vec3 color;\n vec3 position;\n vec3 direction;\n vec3 attenuation;\n vec2 coneCos;\n};\n\nstruct DirectionalLight {\n vec3 color;\n vec3 direction;\n};\n\nstruct UniformLight {\n vec3 color;\n vec3 position;\n vec3 direction;\n vec3 attenuation;\n vec2 coneCos;\n};\n\nlayout(std140) uniform lightingUniforms {\n int enabled;\n int directionalLightCount;\n int pointLightCount;\n int spotLightCount;\n vec3 ambientColor;\n UniformLight lights[5];\n} lighting;\n\nPointLight lighting_getPointLight(int index) {\n UniformLight light = lighting.lights[index];\n return PointLight(light.color, light.position, light.attenuation);\n}\n\nSpotLight lighting_getSpotLight(int index) {\n UniformLight light = lighting.lights[lighting.pointLightCount + index];\n return SpotLight(light.color, light.position, light.direction, light.attenuation, light.coneCos);\n}\n\nDirectionalLight lighting_getDirectionalLight(int index) {\n UniformLight light =\n lighting.lights[lighting.pointLightCount + lighting.spotLightCount + index];\n return DirectionalLight(light.color, light.direction);\n}\n\nfloat getPointLightAttenuation(PointLight pointLight, float distance) {\n return pointLight.attenuation.x\n + pointLight.attenuation.y * distance\n + pointLight.attenuation.z * distance * distance;\n}\n\nfloat getSpotLightAttenuation(SpotLight spotLight, vec3 positionWorldspace) {\n vec3 light_direction = normalize(positionWorldspace - spotLight.position);\n float coneFactor = smoothstep(\n spotLight.coneCos.y,\n spotLight.coneCos.x,\n dot(normalize(spotLight.direction), light_direction)\n );\n float distanceAttenuation = getPointLightAttenuation(\n PointLight(spotLight.color, spotLight.position, spotLight.attenuation),\n distance(spotLight.position, positionWorldspace)\n );\n return distanceAttenuation / max(coneFactor, 0.0001);\n}\n\n// #endif\n",Be={props:{},uniforms:{},name:"lighting",defines:{},uniformTypes:{enabled:"i32",directionalLightCount:"i32",pointLightCount:"i32",spotLightCount:"i32",ambientColor:"vec3<f32>",lights:[{color:"vec3<f32>",position:"vec3<f32>",direction:"vec3<f32>",attenuation:"vec3<f32>",coneCos:"vec2<f32>"},5]},defaultUniforms:De(),bindingLayout:[{name:"lighting",group:2}],firstBindingSlot:0,source:"// #if (defined(SHADER_TYPE_FRAGMENT) && defined(LIGHTING_FRAGMENT)) || (defined(SHADER_TYPE_VERTEX) && defined(LIGHTING_VERTEX))\nconst MAX_LIGHTS: i32 = 5;\n\nstruct AmbientLight {\n color: vec3<f32>,\n};\n\nstruct PointLight {\n color: vec3<f32>,\n position: vec3<f32>,\n attenuation: vec3<f32>, // 2nd order x:Constant-y:Linear-z:Exponential\n};\n\nstruct SpotLight {\n color: vec3<f32>,\n position: vec3<f32>,\n direction: vec3<f32>,\n attenuation: vec3<f32>,\n coneCos: vec2<f32>,\n};\n\nstruct DirectionalLight {\n color: vec3<f32>,\n direction: vec3<f32>,\n};\n\nstruct UniformLight {\n color: vec3<f32>,\n position: vec3<f32>,\n direction: vec3<f32>,\n attenuation: vec3<f32>,\n coneCos: vec2<f32>,\n};\n\nstruct lightingUniforms {\n enabled: i32,\n directionalLightCount: i32,\n pointLightCount: i32,\n spotLightCount: i32,\n ambientColor: vec3<f32>,\n lights: array<UniformLight, 5>,\n};\n\n@group(2) @binding(auto) var<uniform> lighting : lightingUniforms;\n\nfn lighting_getPointLight(index: i32) -> PointLight {\n let light = lighting.lights[index];\n return PointLight(light.color, light.position, light.attenuation);\n}\n\nfn lighting_getSpotLight(index: i32) -> SpotLight {\n let light = lighting.lights[lighting.pointLightCount + index];\n return SpotLight(light.color, light.position, light.direction, light.attenuation, light.coneCos);\n}\n\nfn lighting_getDirectionalLight(index: i32) -> DirectionalLight {\n let light = lighting.lights[lighting.pointLightCount + lighting.spotLightCount + index];\n return DirectionalLight(light.color, light.direction);\n}\n\nfn getPointLightAttenuation(pointLight: PointLight, distance: f32) -> f32 {\n return pointLight.attenuation.x\n + pointLight.attenuation.y * distance\n + pointLight.attenuation.z * distance * distance;\n}\n\nfn getSpotLightAttenuation(spotLight: SpotLight, positionWorldspace: vec3<f32>) -> f32 {\n let lightDirection = normalize(positionWorldspace - spotLight.position);\n let coneFactor = smoothstep(\n spotLight.coneCos.y,\n spotLight.coneCos.x,\n dot(normalize(spotLight.direction), lightDirection)\n );\n let distanceAttenuation = getPointLightAttenuation(\n PointLight(spotLight.color, spotLight.position, spotLight.attenuation),\n distance(spotLight.position, positionWorldspace)\n );\n return distanceAttenuation / max(coneFactor, 0.0001);\n}\n",vs:Re,fs:Re,getUniforms:function(e,t={}){if(!(e=e?{...e}:e))return De();e.lights&&(e={...e,...Fe(e.lights),lights:void 0});const{useByteColors:n,ambientLight:i,pointLights:o,spotLights:s,directionalLights:r}=e||{};if(!(i||o&&o.length>0||s&&s.length>0||r&&r.length>0))return{...De(),enabled:0};const a={...De(),...ke({useByteColors:n,ambientLight:i,pointLights:o,spotLights:s,directionalLights:r})};void 0!==e.enabled&&(a.enabled=e.enabled?1:0);return a}};function ke({useByteColors:e,ambientLight:t,pointLights:n=[],spotLights:i=[],directionalLights:o=[]}){const s=je();let r=0,a=0,l=0,c=0;for(const u of n){if(r>=5)break;s[r]={...s[r],color:Ne(u,e),position:u.position,attenuation:u.attenuation||[1,0,0]},r++,a++}for(const u of i){if(r>=5)break;s[r]={...s[r],color:Ne(u,e),position:u.position,direction:u.direction,attenuation:u.attenuation||[1,0,0],coneCos:Ue(u)},r++,l++}for(const u of o){if(r>=5)break;s[r]={...s[r],color:Ne(u,e),direction:u.direction},r++,c++}return n.length+i.length+o.length>5&&j.warn("MAX_LIGHTS exceeded, truncating to 5")(),{ambientColor:Ne(t,e),directionalLightCount:c,pointLightCount:a,spotLightCount:l,lights:s}}function Fe(e){const t={pointLights:[],spotLights:[],directionalLights:[]};for(const n of e||[])switch(n.type){case"ambient":t.ambientLight=n;break;case"directional":t.directionalLights?.push(n);break;case"point":t.pointLights?.push(n);break;case"spot":t.spotLights?.push(n)}return t}function Ne(e={},t){const{color:n=[0,0,0],intensity:i=1}=e;return Se(n,we(t,!0)).map(e=>e*i)}function De(){return{enabled:1,directionalLightCount:0,pointLightCount:0,spotLightCount:0,ambientColor:[.1,.1,.1],lights:je()}}function je(){return Array.from({length:5},()=>({color:[1,1,1],position:[1,1,2],direction:[1,1,1],attenuation:[1,0,0],coneCos:[1,0]}))}function Ue(e){const t=e.innerConeAngle??0,n=e.outerConeAngle??Math.PI/4;return[Math.cos(t),Math.cos(n)]}var Ge="layout(std140) uniform phongMaterialUniforms {\n uniform bool unlit;\n uniform float ambient;\n uniform float diffuse;\n uniform float shininess;\n uniform vec3 specularColor;\n} material;\n",Ve="layout(std140) uniform phongMaterialUniforms {\n uniform bool unlit;\n uniform float ambient;\n uniform float diffuse;\n uniform float shininess;\n uniform vec3 specularColor;\n} material;\n\nvec3 lighting_getLightColor(vec3 surfaceColor, vec3 light_direction, vec3 view_direction, vec3 normal_worldspace, vec3 color) {\n vec3 halfway_direction = normalize(light_direction + view_direction);\n float lambertian = dot(light_direction, normal_worldspace);\n float specular = 0.0;\n if (lambertian > 0.0) {\n float specular_angle = max(dot(normal_worldspace, halfway_direction), 0.0);\n specular = pow(specular_angle, material.shininess);\n }\n lambertian = max(lambertian, 0.0);\n return (lambertian * material.diffuse * surfaceColor + specular * floatColors_normalize(material.specularColor)) * color;\n}\n\nvec3 lighting_getLightColor(vec3 surfaceColor, vec3 cameraPosition, vec3 position_worldspace, vec3 normal_worldspace) {\n vec3 lightColor = surfaceColor;\n\n if (material.unlit) {\n return surfaceColor;\n }\n\n if (lighting.enabled == 0) {\n return lightColor;\n }\n\n vec3 view_direction = normalize(cameraPosition - position_worldspace);\n lightColor = material.ambient * surfaceColor * lighting.ambientColor;\n\n for (int i = 0; i < lighting.pointLightCount; i++) {\n PointLight pointLight = lighting_getPointLight(i);\n vec3 light_position_worldspace = pointLight.position;\n vec3 light_direction = normalize(light_position_worldspace - position_worldspace);\n float light_attenuation = getPointLightAttenuation(pointLight, distance(light_position_worldspace, position_worldspace));\n lightColor += lighting_getLightColor(surfaceColor, light_direction, view_direction, normal_worldspace, pointLight.color / light_attenuation);\n }\n\n for (int i = 0; i < lighting.spotLightCount; i++) {\n SpotLight spotLight = lighting_getSpotLight(i);\n vec3 light_position_worldspace = spotLight.position;\n vec3 light_direction = normalize(light_position_worldspace - position_worldspace);\n float light_attenuation = getSpotLightAttenuation(spotLight, position_worldspace);\n lightColor += lighting_getLightColor(surfaceColor, light_direction, view_direction, normal_worldspace, spotLight.color / light_attenuation);\n }\n\n for (int i = 0; i < lighting.directionalLightCount; i++) {\n DirectionalLight directionalLight = lighting_getDirectionalLight(i);\n lightColor += lighting_getLightColor(surfaceColor, -directionalLight.direction, view_direction, normal_worldspace, directionalLight.color);\n }\n \n return lightColor;\n}\n",$e="struct phongMaterialUniforms {\n unlit: u32,\n ambient: f32,\n diffuse: f32,\n shininess: f32,\n specularColor: vec3<f32>,\n};\n\n@group(3) @binding(auto) var<uniform> phongMaterial : phongMaterialUniforms;\n\nfn lighting_getLightColor(surfaceColor: vec3<f32>, light_direction: vec3<f32>, view_direction: vec3<f32>, normal_worldspace: vec3<f32>, color: vec3<f32>) -> vec3<f32> {\n let halfway_direction: vec3<f32> = normalize(light_direction + view_direction);\n var lambertian: f32 = dot(light_direction, normal_worldspace);\n var specular: f32 = 0.0;\n if (lambertian > 0.0) {\n let specular_angle = max(dot(normal_worldspace, halfway_direction), 0.0);\n specular = pow(specular_angle, phongMaterial.shininess);\n }\n lambertian = max(lambertian, 0.0);\n return (\n lambertian * phongMaterial.diffuse * surfaceColor +\n specular * floatColors_normalize(phongMaterial.specularColor)\n ) * color;\n}\n\nfn lighting_getLightColor2(surfaceColor: vec3<f32>, cameraPosition: vec3<f32>, position_worldspace: vec3<f32>, normal_worldspace: vec3<f32>) -> vec3<f32> {\n var lightColor: vec3<f32> = surfaceColor;\n\n if (phongMaterial.unlit != 0u) {\n return surfaceColor;\n }\n\n if (lighting.enabled == 0) {\n return lightColor;\n }\n\n let view_direction: vec3<f32> = normalize(cameraPosition - position_worldspace);\n lightColor = phongMaterial.ambient * surfaceColor * lighting.ambientColor;\n\n for (var i: i32 = 0; i < lighting.pointLightCount; i++) {\n let pointLight: PointLight = lighting_getPointLight(i);\n let light_position_worldspace: vec3<f32> = pointLight.position;\n let light_direction: vec3<f32> = normalize(light_position_worldspace - position_worldspace);\n let light_attenuation = getPointLightAttenuation(\n pointLight,\n distance(light_position_worldspace, position_worldspace)\n );\n lightColor += lighting_getLightColor(\n surfaceColor,\n light_direction,\n view_direction,\n normal_worldspace,\n pointLight.color / light_attenuation\n );\n }\n\n for (var i: i32 = 0; i < lighting.spotLightCount; i++) {\n let spotLight: SpotLight = lighting_getSpotLight(i);\n let light_position_worldspace: vec3<f32> = spotLight.position;\n let light_direction: vec3<f32> = normalize(light_position_worldspace - position_worldspace);\n let light_attenuation = getSpotLightAttenuation(spotLight, position_worldspace);\n lightColor += lighting_getLightColor(\n surfaceColor,\n light_direction,\n view_direction,\n normal_worldspace,\n spotLight.color / light_attenuation\n );\n }\n\n for (var i: i32 = 0; i < lighting.directionalLightCount; i++) {\n let directionalLight: DirectionalLight = lighting_getDirectionalLight(i);\n lightColor += lighting_getLightColor(surfaceColor, -directionalLight.direction, view_direction, normal_worldspace, directionalLight.color);\n } \n \n return lightColor;\n}\n\nfn lighting_getSpecularLightColor(cameraPosition: vec3<f32>, position_worldspace: vec3<f32>, normal_worldspace: vec3<f32>) -> vec3<f32>{\n var lightColor = vec3<f32>(0, 0, 0);\n let surfaceColor = vec3<f32>(0, 0, 0);\n\n if (lighting.enabled != 0) {\n let view_direction = normalize(cameraPosition - position_worldspace);\n\n for (var i: i32 = 0; i < lighting.pointLightCount; i++) {\n let pointLight: PointLight = lighting_getPointLight(i);\n let light_position_worldspace: vec3<f32> = pointLight.position;\n let light_direction: vec3<f32> = normalize(light_position_worldspace - position_worldspace);\n let light_attenuation = getPointLightAttenuation(\n pointLight,\n distance(light_position_worldspace, position_worldspace)\n );\n lightColor += lighting_getLightColor(\n surfaceColor,\n light_direction,\n view_direction,\n normal_worldspace,\n pointLight.color / light_attenuation\n );\n }\n\n for (var i: i32 = 0; i < lighting.spotLightCount; i++) {\n let spotLight: SpotLight = lighting_getSpotLight(i);\n let light_position_worldspace: vec3<f32> = spotLight.position;\n let light_direction: vec3<f32> = normalize(light_position_worldspace - position_worldspace);\n let light_attenuation = getSpotLightAttenuation(spotLight, position_worldspace);\n lightColor += lighting_getLightColor(\n surfaceColor,\n light_direction,\n view_direction,\n normal_worldspace,\n spotLight.color / light_attenuation\n );\n }\n\n for (var i: i32 = 0; i < lighting.directionalLightCount; i++) {\n let directionalLight: DirectionalLight = lighting_getDirectionalLight(i);\n lightColor += lighting_getLightColor(surfaceColor, -directionalLight.direction, view_direction, normal_worldspace, directionalLight.color);\n }\n }\n return lightColor;\n}\n",We={props:{},name:"gouraudMaterial",bindingLayout:[{name:"gouraudMaterial",group:3}],vs:Ve.replace("phongMaterial","gouraudMaterial"),fs:Ge.replace("phongMaterial","gouraudMaterial"),source:$e.replaceAll("phongMaterial","gouraudMaterial"),defines:{LIGHTING_VERTEX:!0},dependencies:[Be,ze],uniformTypes:{unlit:"i32",ambient:"f32",diffuse:"f32",shininess:"f32",specularColor:"vec3<f32>"},defaultUniforms:{unlit:!1,ambient:.35,diffuse:.6,shininess:32,specularColor:[38.25,38.25,38.25]},getUniforms:e=>({...We.defaultUniforms,...e})},He={name:"phongMaterial",firstBindingSlot:0,bindingLayout:[{name:"phongMaterial",group:3}],dependencies:[Be,ze],source:$e,vs:Ge,fs:Ve,defines:{LIGHTING_FRAGMENT:!0},uniformTypes:{unlit:"i32",ambient:"f32",diffuse:"f32",shininess:"f32",specularColor:"vec3<f32>"},defaultUniforms:{unlit:!1,ambient:.35,diffuse:.6,shininess:32,specularColor:[38.25,38.25,38.25]},getUniforms:e=>({...He.defaultUniforms,...e})},Ze={name:"color",dependencies:[],source:"\n\n@must_use\nfn deckgl_premultiplied_alpha(fragColor: vec4<f32>) -> vec4<f32> {\n return vec4(fragColor.rgb * fragColor.a, fragColor.a); \n};\n",getUniforms:e=>({})},Ye={name:"project32",dependencies:[l],source:"// Define a structure to hold both the clip-space position and the common position.\nstruct ProjectResult {\n clipPosition: vec4<f32>,\n commonPosition: vec4<f32>,\n};\n\n// This function mimics the GLSL version with the 'out' parameter by returning both values.\nfn project_position_to_clipspace_and_commonspace(\n position: vec3<f32>,\n position64Low: vec3<f32>,\n offset: vec3<f32>\n) -> ProjectResult {\n // Compute the projected position.\n let projectedPosition: vec3<f32> = project_position_vec3_f64(position, position64Low);\n\n // Start with the provided offset.\n var finalOffset: vec3<f32> = offset;\n\n // Get whether a rotation is needed and the rotation matrix.\n let rotationResult = project_needs_rotation(projectedPosition);\n\n // If rotation is needed, update the offset.\n if (rotationResult.needsRotation) {\n finalOffset = rotationResult.transform * offset;\n }\n\n // Compute the common position.\n let commonPosition: vec4<f32> = vec4<f32>(projectedPosition + finalOffset, 1.0);\n\n // Convert to clip-space.\n let clipPosition: vec4<f32> = project_common_position_to_clipspace(commonPosition);\n\n return ProjectResult(clipPosition, commonPosition);\n}\n\n// A convenience overload that returns only the clip-space position.\nfn project_position_to_clipspace(\n position: vec3<f32>,\n position64Low: vec3<f32>,\n offset: vec3<f32>\n) -> vec4<f32> {\n return project_position_to_clipspace_and_commonspace(position, position64Low, offset).clipPosition;\n}\n",vs:"vec4 project_position_to_clipspace(\n vec3 position, vec3 position64Low, vec3 offset, out vec4 commonPosition\n) {\n vec3 projectedPosition = project_position(position, position64Low);\n mat3 rotation;\n if (project_needs_rotation(projectedPosition, rotation)) {\n // offset is specified as ENU\n // when in globe projection, rotate offset so that the ground alighs with the surface of the globe\n offset = rotation * offset;\n }\n commonPosition = vec4(projectedPosition + offset, 1.0);\n return project_common_position_to_clipspace(commonPosition);\n}\n\nvec4 project_position_to_clipspace(\n vec3 position, vec3 position64Low, vec3 offset\n) {\n vec4 commonPosition;\n return project_position_to_clipspace(position, position64Low, offset, commonPosition);\n}\n"},qe=16777215;function Ke(e){return e.replace(" vec4 highlightColor;\n} picking;"," vec4 highlightColor;\n float disabledPickingIndexCount;\n vec4 disabledPickingIndices0;\n vec4 disabledPickingIndices1;\n vec4 disabledPickingIndices2;\n} picking;")}function Xe(e,t){return[e[t]||0,e[t+1]||0,e[t+2]||0,e[t+3]||0]}var Je={...Me,vs:`${Ke(Me.vs)}\nvec3 picking_getPickingColorFromIndex(float objectIndex) {\n if (objectIndex < 0.0 || objectIndex >= 16777215.0) {\n return vec3(0.0);\n }\n\n for (int i = 0; i < 10; i++) {\n if (float(i) >= picking.disabledPickingIndexCount) {\n break;\n }\n vec4 disabledIndices = i < 4\n ? picking.disabledPickingIndices0\n : (i < 8 ? picking.disabledPickingIndices1 : picking.disabledPickingIndices2);\n float disabledIndex = disabledIndices[i - (i / 4) * 4];\n if (disabledIndex == objectIndex) {\n return vec3(0.0);\n }\n }\n\n float encodedIndex = objectIndex + 1.0;\n return vec3(\n mod(encodedIndex, 256.0),\n mod(floor(encodedIndex / 256.0), 256.0),\n mod(floor(encodedIndex / 65536.0), 256.0)\n );\n}\n\nvec3 picking_getPickingColorFromIndex(uint objectIndex) {\n return picking_getPickingColorFromIndex(float(objectIndex));\n}\n\nvec3 picking_getPickingColorFromInstanceID() {\n return picking_getPickingColorFromIndex(float(gl_InstanceID));\n}\n\nvoid picking_setPickingColorFromInstanceID() {\n picking_setPickingColor(picking_getPickingColorFromInstanceID());\n}\n`,fs:Ke(Me.fs),source:"struct pickingUniforms {\n isActive: f32,\n isAttribute: f32,\n isHighlightActive: f32,\n useByteColors: f32,\n highlightedObjectColor: vec3<f32>,\n highlightColor: vec4<f32>,\n disabledPickingIndexCount: f32,\n disabledPickingIndices0: vec4<f32>,\n disabledPickingIndices1: vec4<f32>,\n disabledPickingIndices2: vec4<f32>,\n};\n\n@group(0) @binding(auto) var<uniform> picking: pickingUniforms;\n\nfn picking_normalizeColor(color: vec3<f32>) -> vec3<f32> {\n return select(color, color / 255.0, picking.useByteColors > 0.5);\n}\n\nfn picking_normalizeColor4(color: vec4<f32>) -> vec4<f32> {\n return select(color, color / 255.0, picking.useByteColors > 0.5);\n}\n\nfn picking_isColorZero(color: vec3<f32>) -> bool {\n return dot(color, vec3<f32>(1.0)) < 0.00001;\n}\n\nfn picking_isColorValid(color: vec3<f32>) -> bool {\n return dot(color, vec3<f32>(1.0)) > 0.00001;\n}\n\nfn picking_getPickingColorFromIndex(objectIndex: u32) -> vec3<f32> {\n if (objectIndex >= 16777215u) {\n return vec3<f32>(0.0);\n }\n\n for (var i = 0; i < 10; i = i + 1) {\n if (f32(i) >= picking.disabledPickingIndexCount) {\n break;\n }\n let disabledIndices = select(\n picking.disabledPickingIndices2,\n select(picking.disabledPickingIndices1, picking.disabledPickingIndices0, i < 4),\n i < 8\n );\n let disabledIndex = disabledIndices[i % 4];\n if (disabledIndex == f32(objectIndex)) {\n return vec3<f32>(0.0);\n }\n }\n\n let encodedIndex = objectIndex + 1u;\n return vec3<f32>(\n f32(encodedIndex % 256u),\n f32((encodedIndex / 256u) % 256u),\n f32((encodedIndex / 65536u) % 256u)\n ) / 255.0;\n}\n",uniformTypes:{...Me.uniformTypes,disabledPickingIndexCount:"f32",disabledPickingIndices0:"vec4<f32>",disabledPickingIndices1:"vec4<f32>",disabledPickingIndices2:"vec4<f32>"},defaultUniforms:{...Me.defaultUniforms,useByteColors:!0,disabledPickingIndexCount:0,disabledPickingIndices0:[0,0,0,0],disabledPickingIndices1:[0,0,0,0],disabledPickingIndices2:[0,0,0,0]},getUniforms(e,t){const n=Me.getUniforms(e,t),i=e.disabledPickingIndices||[];return n.disabledPickingIndexCount=i.length,n.disabledPickingIndices0=Xe(i,0),n.disabledPickingIndices1=Xe(i,4),n.disabledPickingIndices2=Xe(i,8),n},inject:{"vs:DECKGL_FILTER_GL_POSITION":"\n // for picking depth values\n picking_setPickingAttribute(position.z / position.w);\n ","vs:DECKGL_FILTER_COLOR":"\n picking_setPickingColor(geometry.pickingColor);\n ","fs:DECKGL_FILTER_COLOR":{order:99,injection:"\n // use highlight color if this fragment belongs to the selected object.\n color = picking_filterHighlightColor(color);\n\n // use picking color if rendering to picking FBO.\n color = picking_filterPickingColor(color);\n "}}},Qe=[0,0,0];function et(e,t,n=!1){const i=t.projectPosition(e);if(n&&t instanceof g){const[n,o,s=0]=e;i[2]=s*t.getDistanceScales([n,o]).unitsPerMeter[2]}return i}function tt(e,{viewport:t,modelMatrix:n,coordinateSystem:i,coordinateOrigin:o,offsetMode:s}){let[r,a,l=0]=e;switch(n&&([r,a,l]=u([],[r,a,l,1],n)),i){case"default":return tt(e,{viewport:t,modelMatrix:n,coordinateSystem:t.isGeospatial?"lnglat":"cartesian",coordinateOrigin:o,offsetMode:s});case"lnglat":return et([r,a,l],t,s);case"lnglat-offsets":return et([r+o[0],a+o[1],l+(o[2]||0)],t,s);case"meter-offsets":return et(z(o,[r,a,l]),t,s);case"cartesian":return t.isGeospatial?[r+o[0],a+o[1],l+o[2]]:t.projectPosition([r,a,l]);default:throw new Error(`Invalid coordinateSystem: ${i}`)}}var nt=class{id;topology;vertexCount;indices;attributes;bufferLayout;userData={};constructor(e){const{attributes:t={},indices:n=null,vertexCount:i=null}=e;this.id=e.id||ee("geometry"),this.topology=e.topology,n&&(this.indices=ArrayBuffer.isView(n)?{value:n,size:1}:n),this.attributes={};for(const[o,s]of Object.entries(t)){const e=ArrayBuffer.isView(s)?{value:s}:s;if(!ArrayBuffer.isView(e.value))throw new Error(`${this._print(o)}: must be typed array or object with value as typed array`);if("POSITION"!==o&&"positions"!==o||e.size||(e.size=3),"indices"===o){if(this.indices)throw new Error("Multiple indices detected");this.indices=e}else{const t=it(o),n=Object.keys(this.attributes).find(e=>it(e)===t);n&&delete this.attributes[n],this.attributes[o]=e}}this.indices&&void 0!==this.indices.isIndexed&&(this.indices=Object.assign({},this.indices),delete this.indices.isIndexed),this.vertexCount=i||this._calculateVertexCount(this.attributes,this.indices),this.bufferLayout=e.bufferLayout||function(e){const t=[];for(const[n,i]of Object.entries(e)){if(!i)continue;const{value:e,size:o,normalized:s}=i;if(void 0===o)throw new Error(`Attribute ${n} is missing a size`);t.push({name:it(n),format:D.getVertexFormatFromAttribute(e,o,s)})}return t}(this.attributes)}getVertexCount(){return this.vertexCount}getAttributes(){return this.indices?{indices:this.indices,...this.attributes}:this.attributes}_print(e){return`Geometry ${this.id} attribute ${e}`}_setAttributes(e,t){return this}_calculateVertexCount(e,t){if(t)return t.value.length;let n=1/0;for(const i of Object.values(e)){if(!i)continue;const{value:e,size:t,constant:o}=i;!o&&e&&void 0!==t&&t>=1&&(n=Math.min(n,e.length/t))}return n}};function it(e){switch(e){case"POSITION":return"positions";case"NORMAL":return"normals";case"TEXCOORD_0":return"texCoords";case"TEXCOORD_1":return"texCoords1";case"COLOR_0":return"colors";default:return e}}function ot(e,t={}){const n=t.bufferName||"geometry";if(function(e,t){if(1!==e.bufferLayout.length)return!1;const n=e.bufferLayout[0];return n.name===t&&Boolean(n.attributes?.length)&&Boolean(e.attributes[t])}(e,n))return e;const i=t.minAttributeAlignment||4,o=function(e,t){return t?t.map(t=>[t,e.attributes[t]]):Object.entries(e.attributes)}(e,t.attributes),s=[];let r=0,a=1/0;for(const[u,f]of o){if(!f)continue;if(f.constant)throw new Error(`Attribute ${u} is constant`);const{value:e,size:t,normalized:n}=f;if(!ArrayBuffer.isView(e))throw new Error(`Attribute ${u} is missing typed array data`);if(void 0===t)throw new Error(`Attribute ${u} is missing a size`);const o=D.getVertexFormatFromAttribute(e,t,n),l=D.getVertexFormatInfo(o);r=rt(r,i),s.push({sourceName:u,attributeName:it(u),value:e,size:t,format:o,byteOffset:r,byteLength:l.byteLength}),r+=l.byteLength;const c=e.length/t;if(!Number.isInteger(c))throw new Error(`Attribute ${u} length is not divisible by size`);a=Math.min(a,c)}if(0===s.length||!Number.isFinite(a))throw new Error(`Geometry ${e.id} has no interleavable attributes`);const l=rt(r,i),c=new ArrayBuffer(a*l);for(const u of s)st(c,a,l,u);return new nt({id:e.id,topology:e.topology||"triangle-list",vertexCount:e.vertexCount,indices:e.indices,attributes:{[n]:{value:new Uint8Array(c),size:l,byteStride:l}},bufferLayout:[{name:n,stepMode:"vertex",byteStride:l,attributes:s.map(e=>({attribute:e.attributeName,format:e.format,byteOffset:e.byteOffset}))}]})}function st(e,t,n,i){const o=i.value.constructor,s=o.BYTES_PER_ELEMENT;if(i.byteOffset%s!==0||n%s!==0)throw new Error(`Attribute ${i.sourceName} is not aligned to its component type`);const r=new o(e),a=i.value,l=i.byteOffset/s,c=n/s;for(let u=0;u<t;u++){const e=u*i.size,t=u*c+l;for(let n=0;n<i.size;n++)r[t+n]=a[e+n]}}function rt(e,t){return Math.ceil(e/t)*t}var at=class{id;userData={};topology;bufferLayout=[];vertexCount;indices;attributes;constructor(e){if(this.id=e.id||ee("geometry"),this.topology=e.topology,this.indices=e.indices||null,this.attributes=e.attributes,this.vertexCount=e.vertexCount,this.bufferLayout=e.bufferLayout||[],this.indices&&!(this.indices.usage&U.INDEX))throw new Error("Index buffer must have INDEX usage")}destroy(){this.indices?.destroy();for(const e of Object.values(this.attributes))e.destroy()}getVertexCount(){return this.vertexCount}getAttributes(){return this.attributes}getIndexes(){return this.indices||null}_calculateVertexCount(e){return e.byteLength/12}};function lt(e,t){if(t instanceof at)return t;const n=ot(t),i=function(e,t){if(!t.indices)return;const n=t.indices.value;return e.createBuffer({usage:U.INDEX,data:n})}(e,n),{attributes:o,bufferLayout:s}=function(e,t){const n={};for(const[i,o]of Object.entries(t.attributes)){const s=t.bufferLayout.find(e=>e.name===i)?.name||it(i);o&&(n[s]=e.createBuffer({data:o.value,id:`${i}-buffer`}))}return{attributes:n,bufferLayout:t.bufferLayout,vertexCount:t.vertexCount}}(e,n);return new at({topology:n.topology||"triangle-list",bufferLayout:s,vertexCount:n.vertexCount,indices:i,attributes:o})}var ct="__debugFramebufferState";function ut(e,t,n){if("webgl"!==e.device.type)return;const i=(o=e.device,o.userData[ct]||={flushing:!1,queuedFramebuffers:[]},o.userData[ct]);var o;i.flushing||(!function(e){const t=e.props.framebuffer;return!t||null===t.handle}(e)?t&&"colorAttachments"in t&&null!==t.handle&&(i.queuedFramebuffers.includes(t)||i.queuedFramebuffers.push(t)):function(e,t,n){if(0===n.queuedFramebuffers.length)return;const{gl:i}=e.device,o=i.getParameter(36010),s=i.getParameter(36006),[r,a]=e.device.getDefaultCanvasContext().getDrawingBufferSize();let l=dt(t.top,8);const c=dt(t.left,8);n.flushing=!0;try{for(const e of n.queuedFramebuffers){const[n,o,s,u,f]=ft({framebuffer:e,targetWidth:r,targetHeight:a,topPx:l,leftPx:c,minimap:t.minimap});i.bindFramebuffer(36008,e.handle),i.bindFramebuffer(36009,null),i.blitFramebuffer(0,0,e.width,e.height,n,o,s,u,16384,9728),l+=f+8}}finally{i.bindFramebuffer(36008,o),i.bindFramebuffer(36009,s),n.flushing=!1}}(e,n,i))}function ft(e){const{framebuffer:t,targetWidth:n,targetHeight:i,topPx:o,leftPx:s,minimap:r}=e,a=r?Math.max(Math.floor(n/4),1):n,l=r?Math.max(Math.floor(i/4),1):i,c=Math.min(a/t.width,l/t.height),u=Math.max(Math.floor(t.width*c),1),f=Math.max(Math.floor(t.height*c),1),d=s,p=Math.max(i-o-f,0);return[d,p,d+u,p+f,f]}function dt(e,t){if(!e)return t;const n=Number.parseInt(e,10);return Number.isFinite(n)?n:t}function pt(e,t,n){if(e===t)return!0;if(!n||!e||!t)return!1;if(Array.isArray(e)){if(!Array.isArray(t)||e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!pt(e[i],t[i],n-1))return!1;return!0}if(Array.isArray(t))return!1;if("object"==typeof e&&"object"==typeof t){const i=Object.keys(e),o=Object.keys(t);if(i.length!==o.length)return!1;for(const s of i){if(!t.hasOwnProperty(s))return!1;if(!pt(e[s],t[s],n-1))return!1}return!0}return!1}var gt=class{bufferLayouts;constructor(e){this.bufferLayouts=e}getBufferLayout(e){return this.bufferLayouts.find(t=>t.name===e)||null}getAttributeNamesForBuffer(e){return Z(e)}mergeBufferLayouts(e,t){const n=[...e];for(const i of t){const e=n.findIndex(e=>e.name===i.name);e<0?n.push(i):n[e]=i}return n}};function ht(e){return null!==e&&"object"==typeof e&&"resolveTextureBinding"in e&&"function"==typeof e.resolveTextureBinding}function vt(e,t,n){const i=V(e,t,{ignoreWarnings:!0});return function(e){return"texture"===e?.type||"external-texture"===e?.type}(i)?i:0===e.bindings.length&&void 0!==n?.fallbackGroup?{type:"texture",name:t,group:n.fallbackGroup,location:0}:null}var mt="render pipeline initialization failed",_t=["stencil8","depth16unorm","depth24plus","depth24plus-stencil8","depth32float","depth32float-stencil8"],xt=class e{static defaultProps={...q.defaultProps,source:void 0,vs:null,fs:null,id:"unnamed",handle:void 0,userData:{},defines:{},modules:[],plugins:[],geometry:null,indexBuffer:null,indexCount:void 0,firstVertex:0,firstIndex:0,attributes:{},constantAttributes:{},bindings:{},uniforms:{},varyings:[],isInstanced:void 0,instanceCount:0,vertexCount:0,shaderInputs:void 0,material:void 0,pipelineFactory:void 0,shaderFactory:void 0,transformFeedback:void 0,shaderAssembler:B.getDefaultShaderAssembler("glsl"),debugShaders:void 0,disableWarnings:void 0};device;id;source;vs;fs;pipelineFactory;shaderFactory;userData={};parameters;topology;bufferLayout;isInstanced=void 0;instanceCount=0;vertexCount;indexCount;firstVertex;firstIndex;indexBuffer=null;bufferAttributes={};constantAttributes={};bindings={};vertexArray;transformFeedback=null;pipeline;shaderInputs;material=null;_uniformStore;_attributeInfos={};_gpuGeometry=null;props;_dynamicIndexBufferSource=null;_dynamicAttributeBufferSources={};_colorAttachmentFormats;_depthStencilAttachmentFormat;_pipelineNeedsUpdate="newly created";_needsRedraw="initializing";_drawBlockedReason=!1;_destroyed=!1;_vertexCountSet=!1;_lastDrawTimestamp=-1;_bindingTable=[];get[Symbol.toStringTag](){return"Model"}toString(){return`Model(${this.id})`}constructor(t,n){const i=e.defaultProps.shaderAssembler,o=void 0!==n.vertexCount;this.props={...e.defaultProps,...n,shaderAssembler:n.shaderAssembler??(yt(i,t.info.shadingLanguage)?i:B.getDefaultShaderAssembler(t.info.shadingLanguage))},this._vertexCountSet=o,n=this.props,this.id=n.id||ee("model"),this.device=t,Object.assign(this.userData,n.userData),this.material=n.material||null;const s=function(e){return{type:e.type,shaderLanguage:e.info.shadingLanguage,shaderLanguageVersion:e.info.shadingLanguageVersion,gpu:e.info.gpu,limits:e.limits,features:e.features}}(t),r=ye(this.props.plugins,s.shaderLanguage),a=me(this.props.modules,r.modules),l=Object.fromEntries(a.map(e=>[e.name,e])),c=n.shaderInputs||new ie(l,{disableWarnings:this.props.disableWarnings});n.shaderInputs&&r.modules.length>0&&c.addModules(r.modules),this.setShaderInputs(c);const u=re(this.props.modules,c.getModules()),f={...r.defines,...this.props.defines};if("webgl"===this.device.type&&(this.props._uniformBlockLayouts=oe(u)),this.props.shaderLayout=ce(this.props.shaderLayout,u)||null,"webgpu"===this.device.type&&this.props.source){const e=this.props.shaderAssembler;W(yt(e,"wgsl"));const{source:n,getUniforms:i,bindingTable:o,shaderLayout:a}=e.assembleWGSLShader({platformInfo:s,...this.props,modules:u,defines:f,pluginInjections:r.injections,pluginVertexInputs:r.vertexInputs,pluginVaryings:r.varyings});this.source=n,this._getModuleUniforms=i,this._bindingTable=o;const l=function(e,t){return e&&0!==Object.keys(t).length?{...e,attributes:e.attributes.map(e=>{const n=e.name.startsWith("_luma_")?e.name.slice(6):null;return n&&t[n]?{...e,name:n}:e})}:e}(a??t.getShaderLayout?.(this.source),r.vertexInputs),c=de(this.props.shaderLayout,l,Object.keys(r.vertexInputs));this.props.shaderLayout=ce(c||null,u)||null}else{const e=this.props.shaderAssembler;W(yt(e,"glsl"));const{vs:t,fs:n,getUniforms:i}=e.assembleGLSLShaderPair({platformInfo:s,...this.props,modules:u,defines:f,pluginInjections:r.injections,pluginVertexInputs:r.vertexInputs,pluginVaryings:r.varyings});this.vs=t,this.fs=n,this._getModuleUniforms=i,this._bindingTable=[]}this.vertexCount=this.props.vertexCount,this.indexCount=this.props.indexCount,this.firstVertex=this.props.firstVertex,this.firstIndex=this.props.firstIndex,this.instanceCount=this.props.instanceCount,this.topology=this.props.topology,this.bufferLayout=this.props.bufferLayout,this.parameters=this.props.parameters,this._colorAttachmentFormats=this.props.colorAttachmentFormats,this._depthStencilAttachmentFormat=this.props.depthStencilAttachmentFormat,n.geometry&&this.setGeometry(n.geometry),this.pipelineFactory=n.pipelineFactory||Q.getDefaultPipelineFactory(this.device),this.shaderFactory=n.shaderFactory||xe.getDefaultShaderFactory(this.device),this.pipeline=this._updatePipeline(),this.vertexArray=t.createVertexArray({shaderLayout:this.pipeline.shaderLayout,bufferLayout:this.pipeline.bufferLayout}),this._gpuGeometry&&this._setGeometryAttributes(this._gpuGeometry),"isInstanced"in n&&(this.isInstanced=n.isInstanced),n.instanceCount&&this.setInstanceCount(n.instanceCount),n.vertexCount&&this.setVertexCount(n.vertexCount),n.indexBuffer&&this.setIndexBuffer(n.indexBuffer),n.attributes&&this.setAttributes(n.attributes),n.constantAttributes&&this.setConstantAttributes(n.constantAttributes),n.bindings&&this.setBindings(n.bindings),n.transformFeedback&&(this.transformFeedback=n.transformFeedback)}destroy(){this._destroyed||(this.pipelineFactory.release(this.pipeline),this.shaderFactory.release(this.pipeline.vs),this.pipeline.fs&&this.pipeline.fs!==this.pipeline.vs&&this.shaderFactory.release(this.pipeline.fs),this._uniformStore.destroy(),this._gpuGeometry?.destroy(),this._destroyed=!0)}needsRedraw(){this._getBindingsUpdateTimestamp()>this._lastDrawTimestamp&&this.setNeedsRedraw("contents of bound textures or buffers updated");const e=this._needsRedraw;return this._needsRedraw=!1,e}setNeedsRedraw(e){this._needsRedraw||=e}getBindingDebugTable(){return this._bindingTable}predraw(e){this._syncDynamicBuffers(),this.updateShaderInputs(e),this.material?.updateShaderInputs(e),this.pipeline=this._updatePipeline()}draw(e){if(this._drawBlockedReason&&!this._pipelineNeedsUpdate)return j.info(2,`>>> DRAWING ABORTED ${this.id}: ${this._drawBlockedReason}`)(),!1;const t=this._areBindingsLoading();if(t)return j.info(2,`>>> DRAWING ABORTED ${this.id}: ${t} not loaded`)(),!1;this._syncAttachmentFormats(e);try{e.pushDebugGroup(`${this}.predraw(${e})`),"webgpu"===this.device.type?(this.updateShaderInputs(),this.material?.updateShaderInputs(),this._syncDynamicBuffers(),this.pipeline=this._updatePipeline()):this.predraw(this.device.commandEncoder)}finally{e.popDebugGroup()}let n,i=this.pipeline.isErrored;try{if(e.pushDebugGroup(`${this}.draw(${e})`),this._logDrawCallStart(),this.pipeline=this._updatePipeline(),i=this.pipeline.isErrored,i)j.info(2,`>>> DRAWING ABORTED ${this.id}: ${mt}`)(),n=!1;else{const t=this.vertexArray.getDrawValidationError();if(t)j.info(2,`>>> DRAWING ABORTED ${this.id}: ${t}`)(),this._drawBlockedReason=t,n=!1;else{const t=this._getCurrentShaderLayout(),i=this._getBindings(t),o=this._getBindGroups(t,i),{indexBuffer:s}=this.vertexArray,r=s?this.indexCount??(this._vertexCountSet?this.vertexCount:s.byteLength/("uint32"===s.indexType?4:2)):void 0;e.setPipeline(this.pipeline),e.setBindings(o,{_bindGroupCacheKeys:this._getBindGroupCacheKeys()}),e.setVertexArray(this.vertexArray),n=!0===this.isInstanced&&0===this.instanceCount||e.draw({isInstanced:this.isInstanced,vertexCount:this.vertexCount,instanceCount:this.isInstanced?this.instanceCount:void 0,indexCount:r,firstVertex:this.firstVertex,firstIndex:this.firstIndex,transformFeedback:this.transformFeedback||void 0,uniforms:this.props.uniforms,parameters:this.parameters,topology:this.topology})}}}finally{e.popDebugGroup(),this._logDrawCallEnd()}return this._logFramebuffer(e),n?(this._lastDrawTimestamp=this.device.timestamp,this._needsRedraw=!1):i?(this._needsRedraw=mt,this._drawBlockedReason=mt):this._drawBlockedReason?this._needsRedraw=this._drawBlockedReason:this._needsRedraw="waiting for resource initialization",n}setGeometry(e){this._gpuGeometry?.destroy();const t=e&<(this.device,e);if(t){this.setTopology(t.topology||"triangle-list");const e=new gt(this.bufferLayout);this.bufferLayout=e.mergeBufferLayouts(t.bufferLayout,this.bufferLayout),this.vertexArray&&this._setGeometryAttributes(t)}this._gpuGeometry=t}setTopology(e){e!==this.topology&&(this.topology=e,this._setPipelineNeedsUpdate("topology"))}setBufferLayout(e){const t=new gt(this.bufferLayout),n=this._gpuGeometry?t.mergeBufferLayouts(e,this._gpuGeometry.bufferLayout):e;pt(n,this.bufferLayout,-1)||(this.bufferLayout=n,this._setPipelineNeedsUpdate("bufferLayout"),this.pipeline=this._updatePipeline(),this.vertexArray=this.device.createVertexArray({shaderLayout:this.pipeline.shaderLayout,bufferLayout:this.pipeline.bufferLayout}),this._gpuGeometry&&this._setGeometryAttributes(this._gpuGeometry))}setParameters(e){pt(e,this.parameters,2)||(this.parameters=e,this._setPipelineNeedsUpdate("parameters"))}setInstanceCount(e){this.instanceCount=e,void 0===this.isInstanced&&e>0&&(this.isInstanced=!0),this.setNeedsRedraw("instanceCount")}setVertexCount(e){this.vertexCount=e,this._vertexCountSet=!0,this.setNeedsRedraw("vertexCount")}setIndexCount(e){this.indexCount=e,this.setNeedsRedraw("indexCount")}setDrawOffsets({firstVertex:e,firstIndex:t}){this.firstVertex=e,this.firstIndex=t,this.setNeedsRedraw("drawOffsets")}setShaderInputs(e){this.shaderInputs=e,this._uniformStore=new ne(this.device,this.shaderInputs.modules);for(const[t,n]of Object.entries(this.shaderInputs.modules))if(se(n)&&!this.material?.ownsModule(t)){const e=this._uniformStore.getManagedUniformBuffer(t);this.bindings[`${t}Uniforms`]=e}this.setNeedsRedraw("shaderInputs")}setMaterial(e){this.material=e,this.setNeedsRedraw("material")}updateShaderInputs(e){this._uniformStore.setUniforms(this.shaderInputs.getUniformValues(),e),this.setBindings(this._getNonMaterialBindings(this.shaderInputs.getBindingValues())),this.setNeedsRedraw("shaderInputs")}setBindings(e){Object.assign(this.bindings,e),this.setNeedsRedraw("bindings")}setTransformFeedback(e){this.transformFeedback=e,this.setNeedsRedraw("transformFeedback")}setIndexBuffer(e){const t=e instanceof ge?e.buffer:e;this.indexBuffer=t,this._dynamicIndexBufferSource=e instanceof ge?{source:e,generation:e.generation}:null,this.vertexArray.setIndexBuffer(t),this.setNeedsRedraw("indexBuffer")}setAttributes(e,t){this._drawBlockedReason=!1;const n=t?.disableWarnings??this.props.disableWarnings;e.indices&&j.warn(`Model:${this.id} setAttributes() - indexBuffer should be set using setIndexBuffer()`)(),this.bufferLayout=function(e,t){const n=Y(e),i=t.slice();return i.sort((e,t)=>G(Z(e).map(e=>n[e]))-G(Z(t).map(e=>n[e]))),i}(this.pipeline.shaderLayout,this.bufferLayout);const i=new gt(this.bufferLayout);for(const[o,s]of Object.entries(e)){const e=s instanceof ge?s.buffer:s,t=i.getBufferLayout(o);if(!t){n||j.warn(`Model(${this.id}): Missing layout for buffer "${o}".`)();continue}const r=i.getAttributeNamesForBuffer(t);let a=!1;for(const i of r){const t=this._attributeInfos[i];if(t){const i="webgpu"===this.device.type?this.vertexArray.getBufferSlot(t.bufferName):t.location;if(null===i){n||j.warn(`Model(${this.id}): Missing vertex array slot for buffer "${t.bufferName}".`)();continue}this.vertexArray.setBuffer(i,e),s instanceof ge?this._dynamicAttributeBufferSources[i]={source:s,generation:s.generation}:delete this._dynamicAttributeBufferSources[i],a=!0}}a||n||j.warn(`Model(${this.id}): Ignoring buffer "${e.id}" for unknown attribute "${o}"`)()}this.setNeedsRedraw("attributes")}setConstantAttributes(e,t){for(const[n,i]of Object.entries(e)){const e=this._attributeInfos[n];e?this.vertexArray.setConstantWebGL(e.location,i):(t?.disableWarnings??this.props.disableWarnings)||j.warn(`Model "${this.id}: Ignoring constant supplied for unknown attribute "${n}"`)()}this.setNeedsRedraw("constants")}_areBindingsLoading(){for(const e of Object.values(this.bindings))if(ht(e)&&!e.isReady)return e.id;for(const e of Object.values(this.material?.bindings||{}))if(ht(e)&&!e.isReady)return e.id;return!1}_getBindings(e=this._getCurrentShaderLayout()){const t={};for(const[n,i]of Object.entries(this.bindings)){const o=bt(n,i,e);o&&(t[n]=o)}return t}_getBindGroups(e=this._getCurrentShaderLayout(),t=this._getBindings(e)){const n=e.bindings.length?$(e,t):{0:t};if(!this.material)return n;for(const[i,o]of Object.entries(this.material.getBindingsByGroup(e))){const e=Number(i);n[e]={...n[e]||{},...o}}return n}_getBindGroupCacheKeys(){const e=this.material?.getBindGroupCacheKey(3);return e?{3:e}:{}}_getBindingsUpdateTimestamp(){let e=0;this._dynamicIndexBufferSource&&(e=Math.max(e,this._dynamicIndexBufferSource.source.updateTimestamp));for(const t of Object.values(this._dynamicAttributeBufferSources))e=Math.max(e,t.source.updateTimestamp);for(const t of Object.values(this.bindings))t instanceof H?e=Math.max(e,t.texture.updateTimestamp):t instanceof U||t instanceof p||t instanceof be||t instanceof ge?e=Math.max(e,t.updateTimestamp):ht(t)?e=t.isReady?Math.max(e,t.updateTimestamp):1/0:le(t)&&(e=Math.max(e,(t.buffer,t.buffer.updateTimestamp)));return Math.max(e,this.material?.getBindingsUpdateTimestamp()||0)}_setGeometryAttributes(e){const t={...e.attributes};for(const[n]of Object.entries(t))this.pipeline.shaderLayout.attributes.find(e=>e.name===n)||"positions"===n||delete t[n];this.vertexCount=e.vertexCount,this._vertexCountSet=!0,this.setIndexBuffer(e.indices||null),this.setAttributes(e.attributes,{disableWarnings:!0}),this.setAttributes(t,{disableWarnings:this.props.disableWarnings}),this.setNeedsRedraw("geometry attributes")}_setPipelineNeedsUpdate(e){this._pipelineNeedsUpdate||=e,this._drawBlockedReason=!1,this.setNeedsRedraw(e)}_updatePipeline(){if(this._pipelineNeedsUpdate){let e=null,t=null;this.pipeline&&(j.log(1,`Model ${this.id}: Recreating pipeline because "${this._pipelineNeedsUpdate}".`)(),e=this.pipeline.vs,t=this.pipeline.fs),this._pipelineNeedsUpdate=!1;const n=this.shaderFactory.createShader({id:`${this.id}-vertex`,stage:"vertex",source:this.source||this.vs,debugShaders:this.props.debugShaders});let i=null;this.source?i=n:this.fs&&(i=this.shaderFactory.createShader({id:`${this.id}-fragment`,stage:"fragment",source:this.source||this.fs,debugShaders:this.props.debugShaders})),this.pipeline=this.pipelineFactory.createRenderPipeline({...this.props,bindings:void 0,bufferLayout:this.bufferLayout,colorAttachmentFormats:this._colorAttachmentFormats,depthStencilAttachmentFormat:this._depthStencilAttachmentFormat,topology:this.topology,parameters:this.parameters,bindGroups:void 0,vs:n,fs:i}),this._attributeInfos=K(this.pipeline.shaderLayout,this.bufferLayout),e&&this.shaderFactory.release(e),t&&t!==e&&this.shaderFactory.release(t)}return this.pipeline}_lastLogTime=0;_logOpen=!1;_logDrawCallStart(){const e=j.level>3?0:1e4;j.level<2||Date.now()-this._lastLogTime<e||(this._lastLogTime=Date.now(),this._logOpen=!0,j.group(2,`>>> DRAWING MODEL ${this.id}`,{collapsed:j.level<=2})())}_logDrawCallEnd(){if(this._logOpen){const e=function(e){const t={},n="Values";if(0===e.attributes.length&&!e.varyings?.length)return{"No attributes or varyings":{[n]:"N/A"}};for(const i of e.attributes)i&&(t[`in ${i.location} ${i.name}: ${i.type}`]={[n]:i.stepMode||"vertex"});for(const i of e.varyings||[])t[`out ${i.location} ${i.name}`]={[n]:JSON.stringify(i)};return t}(this.pipeline.shaderLayout,this.id);j.table(2,e)();const t=this.shaderInputs.getDebugTable();j.table(2,t)();const n=this._getAttributeDebugTable();j.table(2,this._attributeInfos)(),j.table(2,n)(),j.groupEnd(2)(),this._logOpen=!1}}_drawCount=0;_logFramebuffer(e){const t=this.device.props.debugFramebuffers;if(this._drawCount++,!t)return;const n=e.props.framebuffer;ut(e,n,{id:n?.id||`${this.id}-framebuffer`,minimap:!0})}_getAttributeDebugTable(){const e={};for(const[t,n]of Object.entries(this._attributeInfos)){const i=this.vertexArray.attributes[n.location];e[n.location]={name:t,type:n.shaderType,values:i?this._getBufferOrConstantValues(i,n.bufferDataType):"null"}}if(this.vertexArray.indexBuffer){const{indexBuffer:t}=this.vertexArray,n="uint32"===t.indexType?new Uint32Array(t.debugData):new Uint16Array(t.debugData);e.indices={name:"indices",type:t.indexType,values:n.toString()}}return e}_getBufferOrConstantValues(e,t){const n=k.getTypedArrayConstructor(t);return(e instanceof U?new n(e.debugData):e).toString()}_getNonMaterialBindings(e){if(!this.material)return e;const t={};for(const[n,i]of Object.entries(e))this.material.ownsBinding(n)||(t[n]=i);return t}_getCurrentShaderLayout(){return this.pipeline?.shaderLayout||this.props.shaderLayout||{bindings:[]}}_syncDynamicBuffers(){if(this._dynamicIndexBufferSource&&this._dynamicIndexBufferSource.generation!==this._dynamicIndexBufferSource.source.generation){const e=this._dynamicIndexBufferSource.source.buffer;this.indexBuffer=e,this.vertexArray.setIndexBuffer(e),this._dynamicIndexBufferSource.generation=this._dynamicIndexBufferSource.source.generation,this.setNeedsRedraw("dynamic index buffer")}for(const[e,t]of Object.entries(this._dynamicAttributeBufferSources))t.generation!==t.source.generation&&(this.vertexArray.setBuffer(Number(e),t.source.buffer),t.generation=t.source.generation,this.setNeedsRedraw("dynamic attribute buffer"))}_syncAttachmentFormats(e){if("webgpu"!==this.device.type)return;const t=e.framebuffer||e.props.framebuffer,n=e.props,i=n.colorAttachmentFormats??t?.colorAttachments?.map(e=>{return t=e?.texture?.format,t&&!Pt(t)?t:null;var t}),o=!1===n.depthStencilAttachmentFormat?void 0:n.depthStencilAttachmentFormat??(s=t?.depthStencilAttachment?.texture?.format,s&&Pt(s)?s:void 0);var s;pt(this._colorAttachmentFormats,i,1)&&this._depthStencilAttachmentFormat===o||(this._colorAttachmentFormats=i,this._depthStencilAttachmentFormat=o,this._setPipelineNeedsUpdate("attachment formats"))}};function yt(e,t){return(void 0===e.shaderLanguage||e.shaderLanguage===t)&&("glsl"===t?"assembleGLSLShaderPair"in e&&"function"==typeof e.assembleGLSLShaderPair:"assembleWGSLShader"in e&&"function"==typeof e.assembleWGSLShader)}function bt(e,t,n){if(ht(t)){const i=vt(n,e,{fallbackGroup:0});return i?t.resolveTextureBinding(i):null}return t instanceof ge?t.buffer:le(t)?ve(t):t}function Pt(e){return _t.includes(e)}var Ct=class e{device;model;transformFeedback;static defaultProps={...xt.defaultProps,feedbackBufferMode:"separate",outputs:void 0,feedbackBuffers:void 0};static isSupported(e){return"webgl"===e?.info?.type}constructor(t,n=e.defaultProps){if(!e.isSupported(t))throw new Error("BufferTransform not yet implemented on WebGPU");this.device=t,this.model=new xt(this.device,{id:n.id||"buffer-transform-model",fs:n.fs||Pe(),topology:n.topology||"point-list",varyings:n.outputs||n.varyings,...n,bufferMode:n.bufferMode||("interleaved"===n.feedbackBufferMode?35980:35981)}),this.transformFeedback=this.device.createTransformFeedback({layout:this.model.pipeline.shaderLayout,buffers:n.feedbackBuffers}),this.model.setTransformFeedback(this.transformFeedback)}destroy(){this.model&&this.model.destroy()}delete(){this.destroy()}run(e){e?.inputBuffers&&this.model.setAttributes(e.inputBuffers),e?.outputBuffers&&this.transformFeedback.setBuffers(e.outputBuffers);const t=this.device.beginRenderPass({discard:!0,...e});this.model.draw(t),t.end()}getBuffer(e){return this.transformFeedback.getBuffer(e)}readAsync(e){const t=this.getBuffer(e);if(!t)throw new Error("BufferTransform#getBuffer");if(t instanceof U)return t.readAsync();const{buffer:n,byteOffset:i=0,byteLength:o=n.byteLength}=t;return n.readAsync(i,o)}},wt=class extends nt{constructor(e={}){const{id:t=ee("cube-geometry"),indices:n=!0}=e;super(n?{...e,id:t,topology:"triangle-list",indices:{size:1,value:St},attributes:{...Rt,...e.attributes}}:{...e,id:t,topology:"triangle-list",indices:void 0,attributes:{...Bt,...e.attributes}})}},St=new Uint16Array([0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]),Lt=new Float32Array([-1,-1,1,1,-1,1,1,1,1,-1,1,1,-1,-1,-1,-1,1,-1,1,1,-1,1,-1,-1,-1,1,-1,-1,1,1,1,1,1,1,1,-1,-1,-1,-1,1,-1,-1,1,-1,1,-1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,-1,1,-1,-1,-1,-1,-1,1,-1,1,1,-1,1,-1]),At=new Float32Array([0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0]),It=new Float32Array([0,0,1,0,1,1,0,1,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,1,1,1,0,1,0,0,1,0,1,0,1,1,0,1,0,0,0,0,1,0,1,1,0,1]),Et=new Uint32Array([0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5]),Tt=new Float32Array([1,-1,1,-1,-1,1,-1,-1,-1,1,-1,-1,1,-1,1,-1,-1,-1,1,1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,-1,-1,-1,1,1,1,1,1,1,1,-1,-1,1,-1,-1,1,1,1,1,-1,-1,-1,1,-1,1,1,-1,1,-1,-1,-1,-1,-1,-1,1,-1,1,-1,1,1,1,-1,1,1,-1,-1,1,-1,-1,1,1,-1,1,1,1,1,1,-1,-1,-1,-1,-1,-1,1,-1,1,1,-1,1,-1,-1,-1,1,-1]),Ot=new Float32Array([1,1,0,1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,0,0,1,0,1,1,1,1,0,1,0,0,1,0,1,1,0,0]),zt=new Float32Array([1,0,1,1,0,0,1,1,0,0,0,1,1,0,0,1,1,0,1,1,0,0,0,1,1,1,1,1,1,0,1,1,1,0,0,1,1,1,0,1,1,1,1,1,1,0,0,1,0,1,1,1,1,1,1,1,1,1,0,1,0,1,0,1,0,1,1,1,1,1,0,1,0,0,1,1,0,1,1,1,0,1,0,1,0,0,0,1,0,0,1,1,0,1,0,1,1,1,1,1,0,1,1,1,0,0,1,1,0,0,1,1,1,0,1,1,1,1,1,1,1,0,0,1,0,0,0,1,0,1,0,1,1,1,0,1,1,0,0,1,0,1,0,1]),Mt=new Uint32Array([3,3,3,3,3,3,4,4,4,4,4,4,2,2,2,2,2,2,5,5,5,5,5,5,0,0,0,0,0,0,1,1,1,1,1,1]),Rt={POSITION:{size:3,value:Lt},NORMAL:{size:3,value:At},TEXCOORD_0:{size:2,value:It},faceIndex:{size:1,value:Et}},Bt={POSITION:{size:3,value:Tt},TEXCOORD_0:{size:2,value:Ot},COLOR_0:{size:3,value:zt},faceIndex:{size:1,value:Mt}},kt=class e{static defaultProps={...J.defaultProps,id:"unnamed",handle:void 0,userData:{},source:"",modules:[],defines:{},plugins:[],bindings:void 0,shaderInputs:void 0,pipelineFactory:void 0,shaderFactory:void 0,shaderAssembler:B.getDefaultShaderAssembler("wgsl"),debugShaders:void 0};device;id;pipelineFactory;shaderFactory;userData={};bindings={};pipeline;source;shader;shaderInputs;_uniformStore;_pipelineNeedsUpdate="newly created";_getModuleUniforms;props;_destroyed=!1;constructor(t,n){if("webgpu"!==t.type)throw new Error("Computation is only supported in WebGPU");this.props={...e.defaultProps,...n},n=this.props,this.id=n.id||ee("model"),this.device=t,Object.assign(this.userData,n.userData);const i=function(e){return{type:e.type,shaderLanguage:e.info.shadingLanguage,shaderLanguageVersion:e.info.shadingLanguageVersion,gpu:e.info.gpu,limits:e.limits,features:e.features}}(t),s=ye(this.props.plugins,i.shaderLanguage);if(Object.keys(s.vertexInputs).length>0||Object.keys(s.varyings).length>0)throw new Error("Computation does not support ShaderPlugin vertex inputs or varyings");const r=me(this.props.modules,s.modules),a=Object.fromEntries(r.map(e=>[e.name,e]));this.shaderInputs=n.shaderInputs||new ie(a),n.shaderInputs&&s.modules.length>0&&this.shaderInputs.addModules(s.modules),this.setShaderInputs(this.shaderInputs);const l=re(this.props.modules,this.shaderInputs?.getModules()),c={...s.defines,...this.props.defines};this.props.shaderLayout=ce(this.props.shaderLayout,l)||null,this.pipelineFactory=n.pipelineFactory||Q.getDefaultPipelineFactory(this.device),this.shaderFactory=n.shaderFactory||xe.getDefaultShaderFactory(this.device);const u=this.props.shaderAssembler;W(u instanceof o);const{source:f,getUniforms:d,shaderLayout:p}=u.assembleWGSLShader({platformInfo:i,...this.props,modules:l,defines:c,scanVertexAttributes:!1,pluginInjections:s.injections});this.source=f,this._getModuleUniforms=d;const g=p??t.getShaderLayout?.(this.source,{scanVertexAttributes:!1});this.props.shaderLayout=ce(this.props.shaderLayout||g||null,l)||null,this.pipeline=this._updatePipeline(),n.bindings&&this.setBindings(n.bindings)}destroy(){this._destroyed||(this.pipelineFactory.release(this.pipeline),this.shaderFactory.release(this.shader),this._uniformStore.destroy(),this._destroyed=!0)}predraw(e){this.updateShaderInputs(e)}dispatch(e,t,n,i){try{this._logDrawCallStart(),this._setPipeline(e),e.dispatch(t,n,i)}finally{this._logDrawCallEnd()}}dispatchIndirect(e,t,n=0){try{this._logDrawCallStart(),this._setPipeline(e),e.dispatchIndirect(t,n)}finally{this._logDrawCallEnd()}}_setPipeline(e){this.pipeline=this._updatePipeline(),this.pipeline.setBindings(this.bindings),e.setPipeline(this.pipeline),e.setBindings({})}setVertexCount(e){}setInstanceCount(e){}setShaderInputs(e){this.shaderInputs=e,this._uniformStore=new ne(this.device,this.shaderInputs.modules);for(const[t,n]of Object.entries(this.shaderInputs.modules))if(se(n)){const e=this._uniformStore.getManagedUniformBuffer(t);this.bindings[`${t}Uniforms`]=e}}setShaderModuleProps(e){const t=this._getModuleUniforms(e),n=Object.keys(t).filter(e=>{const n=t[e];return!_e(n)&&"number"!=typeof n&&"boolean"!=typeof n}),i={};for(const o of n)i[o]=t[o],delete t[o]}updateShaderInputs(e){this._uniformStore.setUniforms(this.shaderInputs.getUniformValues(),e)}setBindings(e){Object.assign(this.bindings,e)}_setPipelineNeedsUpdate(e){this._pipelineNeedsUpdate=this._pipelineNeedsUpdate||e}_updatePipeline(){if(this._pipelineNeedsUpdate){let e=null;this.pipeline&&(j.log(1,`Model ${this.id}: Recreating pipeline because "${this._pipelineNeedsUpdate}".`)(),e=this.shader),this._pipelineNeedsUpdate=!1,this.shader=this.shaderFactory.createShader({id:`${this.id}-fragment`,stage:"compute",source:this.source,debugShaders:this.props.debugShaders}),this.pipeline=this.pipelineFactory.createComputePipeline({...this.props,shader:this.shader}),e&&this.shaderFactory.release(e)}return this.pipeline}_lastLogTime=0;_logOpen=!1;_logDrawCallStart(){const e=j.level>3?0:1e4;j.level<2||Date.now()-this._lastLogTime<e||(this._lastLogTime=Date.now(),this._logOpen=!0,j.group(2,`>>> DRAWING MODEL ${this.id}`,{collapsed:j.level<=2})())}_logDrawCallEnd(){if(this._logOpen){const e=this.shaderInputs.getDebugTable();j.table(2,e)(),j.groupEnd(2)(),this._logOpen=!1}}_drawCount=0;_getBufferOrConstantValues(e,t){const n=k.getTypedArrayConstructor(t);return(e instanceof U?new n(e.debugData):e).toString()}};var Ft=k.getDataType.bind(k);function Nt(e,t,n){if(t.size>4)return null;const i="webgpu"===n&&"uint8"===t.type?"unorm8":t.type,o=t.size,s=Boolean("webgpu"!==n&&3===o&&i&&["uint8","sint8","unorm8","snorm8","uint16","sint16","unorm16","snorm16"].includes(i));return{attribute:e,format:o>1?`${i}x${o}${s?"-webgl":""}`:t.type,byteOffset:t.offset||0}}function Dt(e){return e.stride||e.size*e.bytesPerElement}function jt(e,t){t.offset&&I.removed("shaderAttribute.offset","vertexOffset, elementOffset")();const n=Dt(e),i=(void 0!==t.vertexOffset?t.vertexOffset:e.vertexOffset||0)*n+(t.elementOffset||0)*e.bytesPerElement+(e.offset||0);return{...t,offset:i,stride:n}}var Ut=class{constructor(e,t,n){this._buffer=null,this.device=e,this.id=t.id||"",this.size=t.size||1;const i=t.logicalType||t.type,o="float64"===i;let s,{defaultValue:r}=t;r=Number.isFinite(r)?[r]:r||new Array(this.size).fill(0),s=o?"float32":!i&&t.isIndexed?"uint32":i||"float32";let a=function(e){switch(e){case"float64":return Float64Array;case"uint8":case"unorm8":return Uint8ClampedArray;default:return F(e)}}(i||s);this.doublePrecision=o,o&&!1===t.fp64&&(a=Float32Array),this.value=null,this.settings={...t,defaultType:a,defaultValue:r,logicalType:i,type:s,normalized:s.includes("norm"),size:this.size,bytesPerElement:a.BYTES_PER_ELEMENT},this.state={...n,externalBuffer:null,bufferAccessor:this.settings,allocatedValue:null,numInstances:0,bounds:null,constant:!1}}get isConstant(){return this.state.constant}get buffer(){return this._buffer}get byteOffset(){const e=this.getAccessor();return e.vertexOffset?e.vertexOffset*Dt(e):0}get numInstances(){return this.state.numInstances}set numInstances(e){this.state.numInstances=e}get isDoublePrecisionBuffer(){return this._shouldSplitDoublePrecisionValue(this.value)}delete(){this._buffer&&(this._buffer.delete(),this._buffer=null),f.release(this.state.allocatedValue),this.state.allocatedValue=null}getBuffer(){return this.state.constant&&"webgpu"!==this.device.type?null:this.state.externalBuffer||this._buffer}getValue(e=this.id,t=null){const n={};if(this.state.constant){const i=this.value;if("webgpu"===this.device.type&&this._buffer)n[e]=this._buffer;else if(t){const o=jt(this.getAccessor(),t),s=o.offset/i.BYTES_PER_ELEMENT,r=o.size||this.size;n[e]=i.subarray(s,s+r)}else n[e]=i}else n[e]=this.getBuffer();return this.doublePrecision&&(this.isDoublePrecisionBuffer?n[`${e}64Low`]=n[e]:n[`${e}64Low`]=new Float32Array(this.size)),n}_getBufferLayout(e=this.id,t=null){const n=this.getAccessor(),i=[],o={name:this.id,byteStride:"webgpu"===this.device.type&&this.state.constant?0:Dt(n)};if(this.doublePrecision){const o=function(e,t){const n=jt(e,t);return{high:n,low:{...n,offset:n.offset+4*e.size}}}(n,t||{});i.push(Nt(e,{...n,...o.high},this.device.type),Nt(`${e}64Low`,{...n,...o.low},this.device.type))}else if(t){const o=jt(n,t);i.push(Nt(e,{...n,...o},this.device.type))}else i.push(Nt(e,n,this.device.type));return o.attributes=i.filter(Boolean),o}setAccessor(e){this.state.bufferAccessor=e}getAccessor(){return this.state.bufferAccessor}getBounds(){if(this.state.bounds)return this.state.bounds;let e=null;if(this.state.constant&&this.value){const t=Array.from(this.value);e=[t,t]}else{const{value:t,numInstances:n,size:i}=this,o=n*i;if(t&&o&&t.length>=o){const n=new Array(i).fill(1/0),s=new Array(i).fill(-1/0);for(let e=0;e<o;)for(let o=0;o<i;o++){const i=t[e++];i<n[o]&&(n[o]=i),i>s[o]&&(s[o]=i)}e=[n,s]}}return this.state.bounds=e,e}setData(e){const{state:t}=this;let n;n=ArrayBuffer.isView(e)?{value:e}:e instanceof U?{buffer:e}:e;const i={...this.settings,...n};if(ArrayBuffer.isView(n.value)){if(!n.type)if(this.doublePrecision&&n.value instanceof Float64Array)i.type="float32";else{const e=Ft(n.value);i.type=i.normalized?e.replace("int","norm"):e}i.bytesPerElement=n.value.BYTES_PER_ELEMENT,i.stride=Dt(i)}if(t.bounds=null,n.constant){let e=n.value;if(e=this._normalizeValue(e,[],0),this.settings.normalized&&(e=this.normalizeConstant(e)),t.constant&&this._areValuesEqual(e,this.value))return!1;t.externalBuffer=null,t.constant=!0,this.value=ArrayBuffer.isView(e)?e:new Float32Array(e)}else if(n.buffer)t.externalBuffer=n.buffer,t.constant=!1,this.value=n.value||null;else if(n.value){this._checkExternalBuffer(n);const e=n.value;let o=e;t.externalBuffer=null,t.constant=!1,this.value=e,this._shouldSplitDoublePrecisionValue(o)&&(o=M(o,i),e instanceof Float32Array&&(i.stride=2*i.size*Float32Array.BYTES_PER_ELEMENT));let{buffer:s}=this;const r=Dt(i),a=(i.vertexOffset||0)*r;if(this.settings.isIndexed){const e=this.settings.defaultType;o.constructor!==e&&(o=new e(o))}const l=o.byteLength+a+2*r;(!s||s.byteLength<l)&&(s=this._createBuffer(l)),s.write(o,a)}return this.setAccessor(i),!0}updateSubBuffer(e={}){this.state.bounds=null;const t=this.value,{startOffset:n=0,endOffset:i}=e,o=this._shouldSplitDoublePrecisionValue(t);this.buffer.write(o?M(t,{size:this.size,startIndex:n,endIndex:i}):t.subarray(n,i),n*(o?8:t.BYTES_PER_ELEMENT)+this.byteOffset)}allocate(e,t=!1){const{state:n}=this,i=n.allocatedValue,o=f.allocate(i,e+1,{size:this.size,type:this.settings.defaultType,copy:t});this.value=o;const s=this._shouldSplitDoublePrecisionValue(o),r=s&&o instanceof Float32Array?{...this.settings,stride:2*this.size*Float32Array.BYTES_PER_ELEMENT}:this.settings;this.setAccessor(r);const{byteOffset:a}=this;let{buffer:l}=this;const c=o.byteLength*(s&&o instanceof Float32Array?2:1);return(!l||l.byteLength<c+a)&&(l=this._createBuffer(c+a),t&&i&&l.write(this._shouldSplitDoublePrecisionValue(i)?M(i,this):i,a)),n.allocatedValue=o,n.constant=!1,n.externalBuffer=null,!0}_shouldSplitDoublePrecisionValue(e){return Boolean(this.doublePrecision&&(e instanceof Float64Array||"webgpu"===this.device.type&&e instanceof Float32Array))}_checkExternalBuffer(e){const{value:t}=e;if(!ArrayBuffer.isView(t))throw new Error(`Attribute ${this.id} value is not TypedArray`);const n=this.settings.defaultType;let i=!1;if(this.doublePrecision&&(i=t.BYTES_PER_ELEMENT<4),i)throw new Error(`Attribute ${this.id} does not support ${t.constructor.name}`);t instanceof n||!this.settings.normalized||"normalized"in e||I.warn(`Attribute ${this.id} is normalized`)()}normalizeConstant(e){switch(this.settings.type){case"snorm8":return new Float32Array(e).map(e=>(e+128)/255*2-1);case"snorm16":return new Float32Array(e).map(e=>(e+32768)/65535*2-1);case"unorm8":return new Float32Array(e).map(e=>e/255);case"unorm16":return new Float32Array(e).map(e=>e/65535);default:return e}}_normalizeValue(e,t,n){const{defaultValue:i,size:o}=this.settings;if(Number.isFinite(e))return t[n]=e,t;if(!e){let e=o;for(;--e>=0;)t[n+e]=i[e];return t}switch(o){case 4:t[n+3]=Number.isFinite(e[3])?e[3]:i[3];case 3:t[n+2]=Number.isFinite(e[2])?e[2]:i[2];case 2:t[n+1]=Number.isFinite(e[1])?e[1]:i[1];case 1:t[n+0]=Number.isFinite(e[0])?e[0]:i[0];break;default:let s=o;for(;--s>=0;)t[n+s]=Number.isFinite(e[s])?e[s]:i[s]}return t}_areValuesEqual(e,t){if(!e||!t)return!1;const{size:n}=this;for(let i=0;i<n;i++)if(e[i]!==t[i])return!1;return!0}_createBuffer(e){this._buffer&&this._buffer.destroy();const{isIndexed:t,type:n}=this.settings,i="webgpu"!==this.device.type||t?(t?U.INDEX:U.VERTEX)|U.COPY_DST:U.VERTEX|U.STORAGE|U.COPY_DST|U.COPY_SRC;return this._buffer=this.device.createBuffer({...this._buffer?.props,id:this.id,usage:i,indexType:t?n:void 0,byteLength:e}),this._buffer}},Gt=[],Vt=[];function $t(e,t=0,n=1/0){let i=Gt;const o={index:-1,data:e,target:[]};return e?"function"==typeof e[Symbol.iterator]?i=e:e.length>0&&(Vt.length=e.length,i=Vt):i=Gt,(t>0||Number.isFinite(n))&&(i=(Array.isArray(i)?i:Array.from(i)).slice(t,n),o.index=t-1),{iterable:i,objectInfo:o}}function Wt(e){return e&&e[Symbol.asyncIterator]}function Ht(e,t){const{size:n,stride:i,offset:o,startIndices:s,nested:r}=t,a=e.BYTES_PER_ELEMENT,l=i?i/a:n,c=o?o/a:0,u=Math.floor((e.length-c)/l);return(t,{index:i,target:o})=>{if(!s){const t=i*l+c;for(let i=0;i<n;i++)o[i]=e[t+i];return o}const a=s[i],f=s[i+1]||u;let d;if(r){d=new Array(f-a);for(let t=a;t<f;t++){const i=t*l+c;o=new Array(n);for(let t=0;t<n;t++)o[t]=e[i+t];d[t-a]=o}}else if(l===n)d=e.subarray(a*n+c,f*n+c);else{d=new e.constructor((f-a)*n);let t=0;for(let i=a;i<f;i++){const o=i*l+c;for(let i=0;i<n;i++)d[t++]=e[o+i]}}return d}}var Zt=[],Yt=[[0,1/0]];var qt={interpolation:{duration:0,easing:e=>e},spring:{stiffness:.05,damping:.5}};function Kt(e,t){if(!e)return null;Number.isFinite(e)&&(e={type:"interpolation",duration:e});const n=e.type||"interpolation";return{...qt[n],...t,...e,type:n}}var Xt=class extends Ut{constructor(e,t){super(e,t,{startIndices:null,constantValue:null,lastExternalBuffer:null,binaryValue:null,binaryAccessor:null,needsUpdate:!0,needsRedraw:!1,layoutChanged:!1,updateRanges:Yt}),this.constant=!1,this.settings.update=t.update||(t.accessor?this._autoUpdater:void 0),Object.seal(this.settings),Object.seal(this.state),this._validateAttributeUpdaters()}get startIndices(){return this.state.startIndices}set startIndices(e){this.state.startIndices=e}needsUpdate(){return this.state.needsUpdate}needsRedraw({clearChangedFlags:e=!1}={}){const t=this.state.needsRedraw;return this.state.needsRedraw=t&&!e,t}layoutChanged(){return this.state.layoutChanged}setAccessor(e){var t,n,i;(t=this.state).layoutChanged||(t.layoutChanged=(n=e,i=this.getAccessor(),!(n.type===i.type&&n.size===i.size&&Dt(n)===Dt(i)&&(n.offset||0)===(i.offset||0)))),super.setAccessor(e)}getUpdateTriggers(){const{accessor:e}=this.settings;return[this.id].concat("function"!=typeof e&&e||[])}supportsTransition(){return Boolean(this.settings.transition)}getTransitionSetting(e){if(!e||!this.supportsTransition())return null;const{accessor:t}=this.settings,n=this.settings.transition;return Kt(Array.isArray(t)?e[t.find(t=>e[t])]:e[t],n)}setNeedsUpdate(e=this.id,t){if(this.state.needsUpdate=this.state.needsUpdate||e,this.setNeedsRedraw(e),t){const{startRow:e=0,endRow:n=1/0}=t;this.state.updateRanges=function(e,t){if(e===Yt)return e;if(t[0]<0&&(t[0]=0),t[0]>=t[1])return e;const n=[],i=e.length;let o=0;for(let s=0;s<i;s++){const i=e[s];i[1]<t[0]?(n.push(i),o=s+1):i[0]>t[1]?n.push(i):t=[Math.min(i[0],t[0]),Math.max(i[1],t[1])]}return n.splice(o,0,t),n}(this.state.updateRanges,[e,n])}else this.state.updateRanges=Yt}clearNeedsUpdate(){this.state.needsUpdate=!1,this.state.updateRanges=Zt}setNeedsRedraw(e=this.id){this.state.needsRedraw=this.state.needsRedraw||e}allocate(e){const{state:t,settings:n}=this;if(n.noAlloc)return!1;if(n.update){const n=this.isConstant;return super.allocate(e,t.updateRanges!==Yt),t.layoutChanged||(t.layoutChanged=n&&"webgpu"===this.device.type),!0}return!1}updateBuffer({numInstances:e,data:t,props:n,context:i}){if(!this.needsUpdate())return!1;const{state:{updateRanges:o},settings:{update:s,noAlloc:r}}=this;let a=!0;if(s){for(const[r,a]of o)s.call(i,this,{data:t,startRow:r,endRow:a,props:n,numInstances:e});if(this.value)if(this.constant||!this.buffer||this.buffer.byteLength<this.value.byteLength+this.byteOffset){if(this.constant){const e=this.value;this.value=null,this.setConstantValue(i,e)}else this.setData({value:this.value,constant:this.constant});this.constant=!1}else for(const[t,n]of o){const i=Number.isFinite(t)?this.getVertexOffset(t):0,o=Number.isFinite(n)?this.getVertexOffset(n):r||!Number.isFinite(e)?this.value.length:e*this.size;super.updateSubBuffer({startOffset:i,endOffset:o})}else;this._checkAttributeArray()}else a=!1;return this.clearNeedsUpdate(),this.setNeedsRedraw(),a}setConstantValue(e,t){var n;if(void 0===t||"function"==typeof t)return!1;const i=this.isConstant,o=this.settings.transform&&e?this.settings.transform.call(e,t):t,s=this.settings.defaultType;this.state.constantValue=this._normalizeValue(o,new s(this.size),0);const r=this.setData({constant:!0,value:o});if("webgpu"===this.device.type){let e=this.state.constantValue;this.doublePrecision&&(e instanceof Float32Array||e instanceof Float64Array)&&(e=M(e,{size:this.size}),this.setAccessor({...this.getAccessor(),stride:2*this.size*Float32Array.BYTES_PER_ELEMENT}));let t=this._buffer;(!t||t.byteLength<e.byteLength)&&(t=this._createBuffer(e.byteLength)),t.write(e),(n=this.state).layoutChanged||(n.layoutChanged=!i),this.constant=!1}return r&&this.setNeedsRedraw(),this.clearNeedsUpdate(),!0}getConstantValue(){return this.isConstant?this.state.constantValue:null}setExternalBuffer(e){const{state:t}=this;return e?(this.clearNeedsUpdate(),t.lastExternalBuffer===e||(t.lastExternalBuffer=e,this.setNeedsRedraw(),this.setData(e)),!0):(t.lastExternalBuffer=null,!1)}setBinaryValue(e,t=null){const{state:n,settings:i}=this;if(!e)return n.binaryValue=null,n.binaryAccessor=null,!1;if(i.noAlloc)return!1;if(n.binaryValue===e)return this.clearNeedsUpdate(),!0;if(n.binaryValue=e,this.setNeedsRedraw(),i.transform||t!==this.startIndices){ArrayBuffer.isView(e)&&(e={value:e});const o=e;h(ArrayBuffer.isView(o.value),`invalid ${i.accessor}`);const s=Boolean(o.size)&&o.size!==this.size;return n.binaryAccessor=Ht(o.value,{size:o.size||this.size,stride:o.stride,offset:o.offset,startIndices:t,nested:s}),!1}return this.clearNeedsUpdate(),this.setData(e),!0}getVertexOffset(e){const{startIndices:t}=this;return(t?e<t.length?t[e]:this.numInstances:e)*this.size}getValue(){const e=this.settings.shaderAttributes,t=super.getValue();if(!e)return t;for(const n in e)Object.assign(t,super.getValue(n,e[n]));return t}getBufferLayout(e){this.state.layoutChanged=!1;const t=this.settings.shaderAttributes,n=super._getBufferLayout(),{stepMode:i}=this.settings;if(n.stepMode="dynamic"===i?e?e.isInstanced?"instance":"vertex":"instance":i??"vertex",!t)return n;for(const o in t){const e=super._getBufferLayout(o,t[o]);n.attributes.push(...e.attributes)}return n}_autoUpdater(e,{data:t,startRow:n,endRow:i,props:o,numInstances:s}){const{settings:r,state:a,value:l,size:c,startIndices:u}=e,{accessor:f,transform:d}=r,p=a.binaryAccessor||("function"==typeof f?f:o[f]);h("function"==typeof p,`accessor "${f}" is not a function`);let g=e.getVertexOffset(n);const{iterable:m,objectInfo:_}=$t(t,n,i);for(const h of m){_.index++;let t=p(h,_);if(d&&(t=d.call(this,t)),u){const n=(_.index<u.length-1?u[_.index+1]:s)-u[_.index];if(t&&Array.isArray(t[0])){let n=g;for(const i of t)e._normalizeValue(i,l,n),n+=c}else t&&t.length>c?l.set(t,g):(e._normalizeValue(t,_.target,0),v({target:l,source:_.target,start:g,count:n}));g+=n*c}else e._normalizeValue(t,l,g),g+=c}}_validateAttributeUpdaters(){const{settings:e}=this;if(!e.noAlloc&&"function"!=typeof e.update)throw new Error(`Attribute ${this.id} missing update or accessor`)}_checkAttributeArray(){const{value:e}=this,t=Math.min(4,this.size);if(e&&e.length>=t){let n=!0;switch(t){case 4:n=n&&Number.isFinite(e[3]);case 3:n=n&&Number.isFinite(e[2]);case 2:n=n&&Number.isFinite(e[1]);case 1:n=n&&Number.isFinite(e[0]);break;default:n=!1}if(!n)throw new Error(`Illegal attribute generated for ${this.id}`)}}},Jt=class e{gpuDataEvaluators;format;length;id;_gpuVector;_ownsGPUDataEvaluators;_destroyed=!1;static fromGPUVector(t){if(t.bufferLayout)throw new Error(`GPUVectorEvaluator.fromGPUVector() does not accept interleaved vector "${t.name}"`);if(0===t.data.length)throw new Error(`GPUVectorEvaluator.fromGPUVector() requires GPUData for "${t.name}"`);return new e({id:t.name,gpuDataEvaluators:t.data.map(e=>pe.fromGPUData(e,{id:t.name})),gpuVector:t,format:t.format})}static fromGPUDataEvaluators(t,n={}){return new e({id:n.id,gpuDataEvaluators:t,format:n.format})}constructor({id:e,gpuDataEvaluators:t,gpuVector:n,format:i}){if(0===t.length)throw new Error("GPUVectorEvaluator requires at least one GPUData evaluator");!function(e){const t=e[0];for(const n of e.slice(1))if(n.type!==t.type||n.size!==t.size||n.normalized!==t.normalized||n.format!==t.format)throw new Error("GPUVectorEvaluator requires matching GPUData evaluator layouts")}(t),this.id=e,this.gpuDataEvaluators=t,this.format=i??t[0].format,this.length=t.reduce((e,t)=>e+t.length,0),this._gpuVector=n,this._ownsGPUDataEvaluators=!n}get evaluated(){return Boolean(this._gpuVector)}get gpuVector(){if(!this._gpuVector)throw new Error(`${this} not evaluated`);return this._gpuVector}mapGPUData(t){return e.fromGPUDataEvaluators(this.gpuDataEvaluators.map((e,n)=>t(e,n)),{id:this.id})}async evaluate(e,t={}){if(this._destroyed)throw new Error(`GPUVectorEvaluator ${this} already destroyed`);if(this._gpuVector)return this._gpuVector;const n=await Promise.all(this.gpuDataEvaluators.map(n=>n.evaluate(e,t))),i=n[0],o=n.map(Qt),s=t.format??this.format??i.format;return this._gpuVector=new fe({type:"data",name:t.name??this.id??"vector",format:s,data:o,stride:i.stride,byteStride:i.byteStride,rowByteLength:i.rowByteLength,bufferLayout:i.bufferLayout}),this._gpuVector}evaluateSync(e,t={}){if(this._destroyed)throw new Error(`GPUVectorEvaluator ${this} already destroyed`);if(this._gpuVector)return this._gpuVector;const n=this.gpuDataEvaluators.map(n=>n.evaluateSync(e,t)),i=n[0],o=n.map(Qt),s=t.format??this.format??i.format;return this._gpuVector=new fe({type:"data",name:t.name??this.id??"vector",format:s,data:o,stride:i.stride,byteStride:i.byteStride,rowByteLength:i.rowByteLength,bufferLayout:i.bufferLayout}),this._gpuVector}destroy(){if(this._ownsGPUDataEvaluators)for(const e of this.gpuDataEvaluators)e.destroy();this._gpuVector=void 0,this._destroyed=!0}toString(){return this.id??this.constructor.name}};function Qt(e){const[t,...n]=e.data;if(!t||n.length>0)throw new Error(`GPUVectorEvaluator requires one GPUData chunk for "${e.name}"`);return t}function en({elementWise:e,func:t,inputs:n,output:i,outputBuffer:o}){const s=Array.isArray(n)?n:Object.values(n);for(const g of s)if(!g.value)throw new Error(`${g} does not have CPU value`);const r=i.length,a=i.size,l=new i.ValueType(r*a);for(let g=0;g<r;g++){const n=s.map(e=>tn(e,g));if(e)for(let e=0;e<a;e++)l[g*a+e]=t.apply(null,n.map(t=>t[e]));else t.call(null,l.subarray(g*a,g*a+a),...n)}const c=i.ValueType.BYTES_PER_ELEMENT,u=i.offset/c,f=i.stride/c,d=a;let p=l;if(0!==u||f!==d){p=new i.ValueType(u+i.byteLength/c);for(let e=0;e<r;e++){const t=e*d,n=u+e*f,i=l.subarray(t,t+a);p.set(i,n),o.write(i,n*c)}}else o.write(l);return{success:!0,value:p}}function tn(e,t){const n=e.value,i=e.size,o=e.offset/e.ValueType.BYTES_PER_ELEMENT,s=e.stride/e.ValueType.BYTES_PER_ELEMENT,r=o+(e.isConstant?0:t)*s,a=n.slice(r,r+i);if(!e.normalized)return a;const l=new Float32Array(i);for(let c=0;c<i;c++)l[c]=nn(a[c],e.type);return l}function nn(e,t){switch(t){case"uint8":return e/255;case"uint16":return e/65535;case"uint32":return e/4294967295;case"sint8":return Math.max(e/127,-1);case"sint16":return Math.max(e/32767,-1);case"sint32":return Math.max(e/2147483647,-1);case"float32":return e;default:throw new Error(`Unsupported normalized source type ${t}`)}}var on=({inputs:e,output:t,target:n})=>{for(const o of Object.values(e.namedInputs))if(!o.value)throw new Error(`${o} does not have CPU value`);const i=new t.ValueType(t.length*t.size);for(let o=0;o<t.length;o++){const n=Object.fromEntries(Object.entries(e.namedInputs).map(([e,t])=>[e,tn(t,o)]));for(let s=0;s<t.size;s++)i[o*t.size+s]=sn(e.expression,n,s)}return n.write(i),{success:!0,value:i}};function sn(e,t,n){switch(e.kind){case"input":{const i=t[e.name];return n<i.length?i[n]:1===i.length?i[0]:0}case"literal":return Array.isArray(e.value)?e.value[n]??0:e.value;case"call":{!function(e,t){const n=ue[e].arity;if(t!==n)throw new Error(`Arithmetic op '${e}' expects ${n} args, got ${t}`)}(e.op,e.args.length);const i=e.args.map(e=>sn(e,t,n));switch(e.op){case"add":return i[0]+i[1];case"subtract":return i[0]-i[1];case"multiply":return i[0]*i[1];case"divide":return i[0]/i[1];case"pow":return Math.pow(i[0],i[1]);case"sqrt":return Math.sqrt(i[0]);case"abs":return Math.abs(i[0]);case"sin":return Math.sin(i[0]);case"cos":return Math.cos(i[0]);case"tan":return Math.tan(i[0]);case"exp":return Math.exp(i[0]);case"log":return Math.log(i[0]);default:{const t=e.op;throw new Error(`Unsupported arithmetic op ${t}`)}}}default:throw new Error(`Unsupported expression node ${e.kind}`)}}var rn=({inputs:e,output:t,target:n})=>{const{sourceValues:i}=e;if(!i.value)throw new Error(`${i} does not have CPU value`);const o=new t.ValueType(t.length*t.size);if(0===i.length)return{success:!1,error:/* @__PURE__ */new Error(`${i} is empty`)};for(let s=0;s<i.size;s++){const e=tn(i,0)[s],n=s*t.size,r=n+1;o[n]=e,o[r]=e;for(let t=1;t<i.length;t++){const e=tn(i,t)[s];e<o[n]&&(o[n]=e),e>o[r]&&(o[r]=e)}}return n.write(o),{success:!0,value:o}},an=({inputs:e,output:t,target:n})=>en({func:(e,t)=>{const n=e.length/2,i=new Float64Array(t.buffer);for(let o=0;o<n;o++){const t=i[o];e[o]=Math.fround(t),e[o+n]=t-e[o]}return e},inputs:e,output:t,outputBuffer:n}),ln=async({inputs:e,output:t,target:n})=>{const{ids:i,sourceValues:o}=e,s=i.value,r=o.value;if(!s)throw new Error(`${i} does not have CPU value`);if(!r)throw new Error(`${o} does not have CPU value`);const a=new t.ValueType(t.length*t.size),l=new Array(t.size).fill(0);for(let c=0;c<t.length;c++){const e=tn(i,c),n=Number(e[0]),s=cn(n,o.length)?tn(o,n):l;a.set(s,c*t.size)}return n.write(a),{success:!0,value:a}};function cn(e,t){return Number.isInteger(e)&&e>=0&&e<t}var un=({inputs:e,output:t,target:n})=>en({func:(e,...t)=>{let n=0;for(const i of t)e.set(i,n),n+=i.length},inputs:e,output:t,outputBuffer:n}),fn=({inputs:e,output:t,target:n})=>{const{x:i,y:o}=e,s=new t.ValueType(t.length);for(let r=0;r<t.length;r++){const e=tn(i,r),t=tn(o,r);let n=0;for(let o=0;o<i.size;o++)n+=e[o]*t[o];s[r]=n}return n.write(s),{success:!0,value:s}},dn=({inputs:e,output:t,target:n})=>{const{x:i,y:o}=e,s=new t.ValueType(t.length);for(let r=0;r<t.length;r++){const e=tn(i,r),t=tn(o,r);let n=1;for(let o=0;o<i.size;o++)if(e[o]!==t[o]){n=0;break}s[r]=n}return n.write(s),{success:!0,value:s}},pn=({inputs:e,output:t,target:n})=>{const{x:i}=e,o=new t.ValueType(t.length);for(let s=0;s<t.length;s++){const e=tn(i,s);let t=0;for(let n=0;n<i.size;n++)t+=e[n]*e[n];o[s]=Math.sqrt(t)}return n.write(o),{success:!0,value:o}},gn=async({inputs:e,output:t,target:n})=>{const{segments:i,vertexCount:o}=e,s=i.value;if(!s)throw new Error(`${i} does not have CPU value`);!function(e,t,n){if(t.length<1)throw new Error("segmentedMap segments must contain at least one segment start");let i=0;for(let o=0;o<t.length;o++){const n=e[hn(t,o)];if(0===o&&0!==n)throw new Error(`segmentedMap segments must start at 0, got ${n}`);if(o>0&&n<i)throw new Error(`segmentedMap segments must be non-decreasing, got ${n} after ${i}`);i=n}if(i>n)throw new Error(`segmentedMap last segment start must be <= vertexCount, got ${i} > ${n}`)}(s,i,o);const r=new t.ValueType(t.length*t.size);let a=0;for(let l=0;l<o;l++){for(;a+1<i.length&&s[hn(i,a+1)]<=l;)a++;const e=s[hn(i,a)],n=l*t.size;r[n]=a,r[n+1]=l-e}return n.write(r),{success:!0,value:r}};function hn(e,t){return e.offset/e.ValueType.BYTES_PER_ELEMENT+t*(e.stride/e.ValueType.BYTES_PER_ELEMENT)}var vn=async({inputs:e,output:t,target:n})=>{const{condition:i,whenTrue:o,whenFalse:s}=e,r=new t.ValueType(t.length*t.size);for(let a=0;a<t.length;a++){const e=tn(i,a),n=tn(o,a),l=tn(s,a);for(let c=0;c<t.size;c++){const u=mn(e,i.size,c);r[a*t.size+c]=0!==u?mn(n,o.size,c):mn(l,s.size,c)}}return n.write(r),{success:!0,value:r}};function mn(e,t,n){return n<t?e[n]:1===t?e[0]:0}var _n=({inputs:e,output:t,target:n})=>{const i=new t.ValueType(t.length);for(let o=0;o<t.length;o++)i[o]=e.start+o*e.step;return n.write(i),{success:!0,value:i}},xn=({inputs:e,output:t,target:n})=>{const{columns:i}=e;return en({func:(e,t)=>{for(let n=0;n<i.length;n++)e[n]=t[i[n]]},inputs:{x:e.x},output:t,outputBuffer:n})},yn=/* @__PURE__ */t({arithmetic:()=>on,dot:()=>fn,equalAll:()=>dn,extent:()=>rn,fround:()=>an,gather:()=>ln,interleave:()=>un,length:()=>pn,segmentedMap:()=>gn,select:()=>vn,sequence:()=>_n,swizzle:()=>xn}),bn=new class{_modules={cpu:yn};add(e,t){const n=this._modules[e];if("function"==typeof t.then){const i=Promise.all([Promise.resolve(n||{}),t]).then(([e,t])=>({...e,...t}));return this._modules[e]=i,i.then(t=>{this._modules[e]=t}).catch(t=>{j.error(`Failed to register ${e} backend: ${t}`)()}),i}if(n&&"function"==typeof n.then){const i=Promise.resolve(n).then(e=>({...e,...t})).then(t=>(this._modules[e]=t,t)).catch(t=>{throw j.error(`Failed to register ${e} backend: ${t}`)(),t});return this._modules[e]=i,i}const i={...n||{},...t};return this._modules[e]=i,Promise.resolve(i)}async get(e,t){let n=this._modules[e];if(!n)if("webgl"===e)n=this.add("webgl",import("./webgl-ZcaUll7k.js"));else{if("webgpu"!==e)throw new Error(`${e} backend not registered`);n=this.add("webgpu",Promise.resolve().then(()=>ii))}const i=(await n)[t];if("function"!=typeof i)throw new Error(`${e} backend does not implement ${t}`);return i}getSync(e,t){const n=this._modules[e];if(!n)throw new Error(`${e} backend not registered`);if("function"==typeof n.then)throw new Error(`${e} backend is not loaded yet`);const i=n[t];if("function"!=typeof i)throw new Error(`${e} backend does not implement ${t}`);return i}clear(){this._modules={}}},Pn=class{inputs;dependencies;constructor(e){this.inputs=e,this.dependencies=Array.from(e instanceof Array?e:Object.values(e)).filter(e=>e instanceof pe)}async execute(e,t){return await this._resolveDependencies(e),await this._executeWithHandler(await bn.get(this._getHandlerRegistry(e),this.name),t)}executeSync(e,t){this._resolveDependenciesSync(e);const n=this._executeWithHandler(bn.getSync(this._getHandlerRegistry(e),this.name),t);if(i=n,"function"==typeof i?.then)throw new Error(`${this.name} returned a Promise in executeSync()`);var i;return n}shouldExecuteOnCPU(){return this.output.length<=1&&Array.from(this.dependencies).every(e=>Boolean(e.value))}_getHandlerRegistry(e){return this.shouldExecuteOnCPU()?"cpu":e.type}async _resolveDependencies(e){for(const t of this.dependencies)await t.evaluate(e);if("cpu"===this._getHandlerRegistry(e)||"null"===e.type)for(const t of this.dependencies)await t.ensureCPUValue()}_resolveDependenciesSync(e){for(const t of this.dependencies)t.evaluateSync(e);if("cpu"===this._getHandlerRegistry(e)||"null"===e.type)for(const t of this.dependencies)t.ensureCPUValueSync()}_executeWithHandler(e,t){return e({device:t.device,inputs:this.inputs,output:this.output,target:t})}};function Cn(...e){let t=function(e){let t=0,n=0;for(const i of e){if("f"===i[0])return"float32";const e=i.endsWith("8")?8:i.endsWith("6")?16:32;"u"===i[0]?t=Math.max(t,e):n=Math.max(n,e)}return t&&!n?`uint${t}`:n&&t<32?`sint${Math.max(n,2*t)}`:"float32"}(e.map(e=>e.type));return"f"!==t[0]&&e.some(e=>e.normalized)&&(t="float32"),{isConstant:e.every(e=>e.isConstant),type:t,size:e.reduce((e,t)=>Math.max(e,t.size),0),length:e.reduce((e,t)=>Math.max(e,t.length),0)}}var wn=class extends Pn{name="interleave";output;constructor(e){super(e);const{isConstant:t,type:n,length:i}=Cn(...e);this.output=new pe({isConstant:t,type:n,size:e.reduce((e,t)=>e+t.size,0),length:i,source:this})}toString(){return`_${this.inputs.join("_")}_`}};function Sn(e,t){const n=function(e){const t=/* @__PURE__ */new Set;return Ln(e,t,/* @__PURE__ */new Set),Array.from(t)}(t);for(const i of n)i.evaluateSync(e);return function(e){const t=new Set(e.flatMap(In)),n=/* @__PURE__ */new Set;for(const i of e)An(i,n);for(const i of n)i.evaluated&&!t.has(i.buffer)&&i.destroy()}(n),t}function Ln(e,t,n){if(function(e){return e instanceof pe||e instanceof Jt}(e))t.add(e);else if(e&&"object"==typeof e&&!n.has(e))if(n.add(e),Array.isArray(e))for(const i of e)Ln(i,t,n);else if(function(e){const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}(e))for(const i of Object.values(e))Ln(i,t,n)}function An(e,t){if(e instanceof Jt){for(const n of e.gpuDataEvaluators)An(n,t);return}const n=e.source;if(n)if(n instanceof pe)t.has(n)||(t.add(n),An(n,t));else for(const i of n.dependencies)t.has(i)||(t.add(i),An(i,t))}function In(e){return e instanceof pe?[e.buffer]:e.gpuVector.data.map(e=>e.buffer instanceof ge?e.buffer.buffer:e.buffer)}function En(e,t){const n=function(e){return Number.isFinite(e)&&e>0?Math.floor(e):65535}(t),i=Math.max(1,Math.ceil(e)),o=Math.min(i,n),s=Math.min(Math.ceil(i/o),n),r=Math.ceil(i/o/s);if(r>n)throw new Error(`WebGPU dispatch requires ${i} workgroups, exceeding the 3D dispatch limit of ${n} per dimension`);return{x:o,y:s,z:r}}function Tn(e,t="workgroupId"){return`((${t}.z * ${e.y}u + ${t}.y) * ${e.x}u + ${t}.x)`}function On(e,t,n="workgroupId",i="localId"){return`(${Tn(e,n)} * ${t}u + ${i}.x)`}function zn(e,t){switch(e){case"u32":return`${t}u`;case"f32":return Number.isInteger(t)?`${t}.0`:`${t}`;default:return`${t}`}}function Mn(e){switch(e){case"uint32":return"0u";case"sint32":return"0";case"float32":return"0.0";default:throw new Error(`WebGPU operations only support 32-bit output types, got ${e}`)}}function Rn(e){switch(e){case"uint32":return"u32";case"sint32":return"i32";case"float32":return"f32";default:throw new Error(`WebGPU operations only support 32-bit storage types, got ${e}`)}}var Bn=new o;function kn({module:e,elementWise:t=!1,expression:n,inputs:i,output:o,operationType:s=o.type,outputBuffer:r}){if(!e.source)throw new Error(`WebGPU computation ${e.name} requires WGSL source`);const a=function(e){return Array.isArray(e)?e.map((e,t)=>[`x${t}`,e]):Object.entries(e)}(i),l=a.map(([e,t])=>({name:e,input:t})),c=l.filter(({input:e})=>!e.isConstant).map((e,t)=>({...e,index:t})),u=Rn(s),f=Rn(o.type),d={TYPE:u,RESULT_LEN:o.size.toString()},p=En(Math.ceil(o.length/64),r.device.limits.maxComputeWorkgroupsPerDimension);for(const[_,x]of a)d[`${_.toUpperCase()}_LEN`]=x.size.toString();const g=`\n${function(e,t){for(const n in t)e=e.replaceAll(`{${n}}`,t[n]);return e}(e.source,d)}\n${c.map(({name:e,input:t,index:n})=>function(e,t,n){return t.isConstant?"":`@group(0) @binding(${n}) var<storage, read> ${e}: array<${Rn(t.type)}>;`}(e,t,n)).join("\n")}\n${l.map(({name:e,input:t})=>function(e,t,n){const i=Rn(n),o=t.type===n?"":i,s=t.stride/t.ValueType.BYTES_PER_ELEMENT,r=t.offset/t.ValueType.BYTES_PER_ELEMENT;return t.isConstant?`fn read_${e}(_rowIndex: u32) -> array<${i}, ${t.size}> {\n return array<${i}, ${t.size}>(${function(e,t){const n=e.value;if(!n)throw new Error(`Constant input ${e} is missing CPU values`);return Array.from({length:e.size},(e,i)=>zn(t,n[i]??0)).join(", ")}(t,o)});\n}`:`fn read_${e}(rowIndex: u32) -> array<${i}, ${t.size}> {\n var value: array<${i}, ${t.size}>;\n let rowOffset = ${r}u + rowIndex * ${s}u;\n${Array.from({length:t.size},(t,n)=>o?` value[${n}] = ${o}(${e}[rowOffset + ${n}u]);`:` value[${n}] = ${e}[rowOffset + ${n}u];`).join("\n")}\n return value;\n}`}(e,t,s)).join("\n")}\n${function(e,t){return`@group(0) @binding(${t}) var<storage, read_write> result: array<${Rn(e.type)}>;`}(o,c.length)}\n${function(e){const t=e.stride/e.ValueType.BYTES_PER_ELEMENT,n=e.offset/e.ValueType.BYTES_PER_ELEMENT;return`fn write_result(rowIndex: u32, value: array<${Rn(e.type)}, ${e.size}>) {\n let rowOffset = ${n}u + rowIndex * ${t}u;\n${Array.from({length:e.size},(e,t)=>` result[rowOffset + ${t}u] = value[${t}];`).join("\n")}\n}`}(o)}\n\n@compute @workgroup_size(64) fn main(\n @builtin(workgroup_id) workgroupId: vec3<u32>,\n @builtin(local_invocation_id) localId: vec3<u32>\n) {\n let rowIndex = ${On(p,64)};\n if (rowIndex >= ${o.length}u) {\n return;\n }\n\n${l.map(({name:e})=>` let ${e} = read_${e}(rowIndex);`).join("\n")}\n var result: array<${f}, ${o.size}>;\n${function(e,t,n,i,o){let s="";if(o)for(let r=0;r<n.size;r++)s+=` result[${r}] = ${o(r)};\n`;else if(i){const i=Mn(n.type),o=Rn(n.type);for(let r=0;r<n.size;r++){const n=t.map(([e,t])=>r<t.size?Rn(t.type)===o?`${e}[${r}]`:`${o}(${e}[${r}])`:i);s+=` result[${r}] = ${e}(${n.join(", ")});\n`}}else s+=`result = ${e}(${t.map(([e])=>e).join(", ")});`;return s.trimEnd()}(e.name,a,o,t,n)}\n write_result(rowIndex, result);\n}\n`,h=new kt(r.device,{source:g,modules:e.dependencies,shaderAssembler:Bn,shaderLayout:{bindings:[...c.map(({name:e},t)=>({name:e,type:"storage",group:0,location:t})),{name:"result",type:"storage",group:0,location:c.length}]}}),v=Object.fromEntries(c.map(({name:e,input:t})=>[e,t.buffer]));v.result=r,h.setBindings(v);const m=r.device.beginComputePass({});r.device.statsManager.getStats("GPGPU Operation Counts").get("Computation Runs").incrementCount(),h.dispatch(m,p.x,p.y,p.z),m.end(),r.device.submit(),h.destroy()}var Fn=({inputs:e,output:t,target:n})=>{const i=t.type,o=Rn(i),s=Mn(i),r=e.namedInputs;return kn({module:{name:"arithmetic",source:"fn arithmetic_add(x: {TYPE}, y: {TYPE}) -> {TYPE} {\n return x + y;\n}\n\nfn arithmetic_subtract(x: {TYPE}, y: {TYPE}) -> {TYPE} {\n return x - y;\n}\n\nfn arithmetic_multiply(x: {TYPE}, y: {TYPE}) -> {TYPE} {\n return x * y;\n}\n\nfn arithmetic_divide(x: {TYPE}, y: {TYPE}) -> {TYPE} {\n return x / y;\n}\n\nfn arithmetic_tan(x: f32) -> f32 {\n return tan_fp32(x);\n}\n",dependencies:[d]},inputs:r,output:t,operationType:i,outputBuffer:n,expression:t=>he(e.expression,{operations:ue,inputs:r,laneIndex:t,formatInput:e=>`${e}[${t}]`,formatOutOfBoundsInput:e=>1===r[e].size?`${e}[0]`:s,formatLiteral:e=>{const n=Array.isArray(e)?e[t]??0:e;return`${o}(${function(e,t){switch(e){case"uint32":return zn("u32",Math.trunc(t));case"sint32":return`${Math.trunc(t)}`;case"float32":return zn("f32",t);default:throw new Error(`WebGPU operations only support 32-bit output types, got ${e}`)}}(i,n)})`},formatCall:(e,t)=>`${e}(${t.join(", ")})`})}),{success:!0}},Nn=({inputs:e,output:t,target:n})=>(kn({module:{name:"row_dot",source:"fn row_dot(x: array<{TYPE}, {X_LEN}>, y: array<{TYPE}, {Y_LEN}>) -> array<f32, 1> {\n var sum = 0.0;\n for (var i = 0u; i < {X_LEN}u; i = i + 1u) {\n sum += f32(x[i]) * f32(y[i]);\n }\n return array<f32, 1>(sum);\n}\n"},inputs:e,output:t,operationType:"float32",outputBuffer:n}),{success:!0}),Dn=({inputs:e,output:t,target:n})=>(kn({module:{name:"equalAll",source:"fn equalAll(x: array<{TYPE}, {X_LEN}>, y: array<{TYPE}, {Y_LEN}>) -> array<u32, 1> {\n var allEqual = 1u;\n for (var i = 0u; i < {X_LEN}u; i = i + 1u) {\n if (x[i] != y[i]) {\n allEqual = 0u;\n break;\n }\n }\n return array<u32, 1>(allEqual);\n}\n"},inputs:e,output:t,operationType:e.x.type,outputBuffer:n}),{success:!0});function jn(e,t,n){return`@group(0) @binding(${n}) var<storage, read> ${e}: array<${Rn(t.type)}>;`}function Un(e,t,n,i=e){const o=Rn(n);if(t.isConstant){const e=t.value;if(!e)throw new Error(`Constant input ${t} is missing CPU values`);return`fn read_${i}(_sourceIndex: u32) -> array<${o}, ${t.size}> {\n return array<${o}, ${t.size}>(${Array.from({length:t.size},(t,n)=>zn(o,e[n]??0)).join(", ")});\n}`}const s=t.stride/t.ValueType.BYTES_PER_ELEMENT,r=t.offset/t.ValueType.BYTES_PER_ELEMENT,a=Rn(t.type)===o?"":`${o}`;return`fn read_${i}(sourceIndex: u32) -> array<${o}, ${t.size}> {\n var value: array<${o}, ${t.size}>;\n let rowOffset = ${r}u + sourceIndex * ${s}u;\n${Array.from({length:t.size},(t,n)=>a?` value[${n}] = ${a}(${e}[rowOffset + ${n}u]);`:` value[${n}] = ${e}[rowOffset + ${n}u];`).join("\n")}\n return value;\n}`}function Gn(e,t){return Un("sourceValues",e,t,"source_values")}function Vn(e,t){return`@group(0) @binding(${t}) var<storage, read_write> result: array<${Rn(e.type)}>;`}function $n(e){const t=e.stride/e.ValueType.BYTES_PER_ELEMENT,n=e.offset/e.ValueType.BYTES_PER_ELEMENT;return`fn write_result(rowIndex: u32, value: array<${Rn(e.type)}, ${e.size}>) {\n let rowOffset = ${n}u + rowIndex * ${t}u;\n${Array.from({length:e.size},(e,t)=>` result[rowOffset + ${t}u] = value[${t}];`).join("\n")}\n}`}var Wn=({inputs:e,output:t,target:n})=>{const{sourceValues:i}=e;if(0===i.length){const e=new t.ValueType(t.length*t.size);return n.write(e),{success:!0,value:e}}if(i.isConstant){const e=i.value;if(!e)throw new Error(`Constant input ${i} is missing CPU values`);const o=new t.ValueType(t.length*t.size);for(let n=0;n<t.length;n++){const t=e[n];o[2*n]=t,o[2*n+1]=t}return n.write(o),{success:!0,value:o}}const o=[];let s=i,r="raw",a=i.length;try{for(;;){const e=Math.ceil(a/64),i=t.length*e,l=1===e?n:te.createOrReuse(n.device,i*t.stride);if(e>1&&o.push(l),Hn({input:s,inputMode:r,inputGroupCount:a,channelCount:t.length,outputType:t.type,outputBuffer:l,outputLength:i,outputStride:t.stride,outputOffset:t.offset}),1===e)break;s=new pe({buffer:l,type:t.type,size:2,length:i}),r="partial",a=e}return{success:!0}}finally{for(const e of o)te.recycle(e)}};function Hn({input:e,inputMode:t,inputGroupCount:n,channelCount:i,outputType:o,outputBuffer:s,outputLength:r,outputStride:a,outputOffset:l}){const c=Rn(o),u=En(r,s.device.limits.maxComputeWorkgroupsPerDimension),f=new pe({buffer:s,type:o,size:2,length:r,stride:a,offset:l}),d=`\n${e.isConstant?"":jn("sourceValues",e,0)}\n${Gn(e,o)}\n${Vn(f,e.isConstant?0:1)}\n${$n(f)}\n${function(e,t,n,i){const o=Rn(t),[s,r]=function(e){switch(e){case"uint32":return["0xffffffffu","0u"];case"sint32":return["2147483647","-2147483648"];case"float32":return["3.402823e38","-3.402823e38"];default:throw new Error(`Unsupported WebGPU extent type for ${e}`)}}(t);return"raw"===e?`fn extent_pass(channelIndex: u32, inputGroupIndex: u32) -> array<${o}, 2> {\n var result: array<${o}, 2>;\n result[0] = ${s};\n result[1] = ${r};\n\n if (inputGroupIndex < ${i}u) {\n let value = read_source_values(inputGroupIndex);\n result[0] = value[channelIndex];\n result[1] = value[channelIndex];\n }\n\n return result;\n}`:`fn extent_pass(channelIndex: u32, inputGroupIndex: u32) -> array<${o}, 2> {\n var result: array<${o}, 2>;\n result[0] = ${s};\n result[1] = ${r};\n\n if (inputGroupIndex < ${i}u) {\n let rowIndex = inputGroupIndex * ${n}u + channelIndex;\n let value = read_source_values(rowIndex);\n result[0] = value[0];\n result[1] = value[1];\n }\n\n return result;\n}`}(t,o,i,n)}\n\nvar<workgroup> sharedMin: array<${c}, 64>;\nvar<workgroup> sharedMax: array<${c}, 64>;\n\n@compute @workgroup_size(64) fn main(\n @builtin(workgroup_id) workgroupId: vec3<u32>,\n @builtin(local_invocation_id) localId: vec3<u32>\n) {\n let outputRowIndex = ${Tn(u)};\n if (outputRowIndex >= ${r}u) {\n return;\n }\n\n let channelIndex = outputRowIndex % ${i}u;\n let outputGroupIndex = outputRowIndex / ${i}u;\n let inputGroupIndex = outputGroupIndex * 64u + localId.x;\n\n let result = extent_pass(channelIndex, inputGroupIndex);\n sharedMin[localId.x] = result[0];\n sharedMax[localId.x] = result[1];\n workgroupBarrier();\n\n var stride = ${Math.floor(32)}u;\n loop {\n if (stride == 0u) {\n break;\n }\n if (localId.x < stride) {\n let compareIndex = localId.x + stride;\n if (sharedMin[compareIndex] < sharedMin[localId.x]) {\n sharedMin[localId.x] = sharedMin[compareIndex];\n }\n if (sharedMax[compareIndex] > sharedMax[localId.x]) {\n sharedMax[localId.x] = sharedMax[compareIndex];\n }\n }\n workgroupBarrier();\n stride = stride / 2u;\n }\n\n if (localId.x == 0u) {\n write_result(outputRowIndex, array<${c}, 2>(sharedMin[0], sharedMax[0]));\n }\n}\n`,p=new kt(s.device,{source:d,shaderLayout:{bindings:[...e.isConstant?[]:[{name:"sourceValues",type:"storage",group:0,location:0}],{name:"result",type:"storage",group:0,location:e.isConstant?0:1}]}}),g={result:s};e.isConstant||(g.sourceValues=e.buffer),p.setBindings(g);const h=s.device.beginComputePass({});p.dispatch(h,u.x,u.y,u.z),h.end(),s.device.submit(),p.destroy()}var Zn=`const LE: bool = ${function(){const e=new Uint16Array([255]);return new Uint8Array(e.buffer)[0]>0}()?"true":"false"};\nconst F32_NAN: u32 = 0xffffffffu;\nconst F32_INF: u32 = 0x7f800000u;\n\nfn roundShiftRight(value: u32, shift: i32) -> u32 {\n if (shift <= 0) {\n return value << u32(-shift);\n }\n\n if (shift >= 32) {\n if (shift == 32 && value > 0x80000000u) {\n return 1u;\n }\n return 0u;\n }\n\n let shiftU32 = u32(shift);\n let truncated = value >> shiftU32;\n let halfShift = 1u << u32(shift - 1);\n let remainder = value & ((1u << shiftU32) - 1u);\n if (remainder > halfShift || (remainder == halfShift && (truncated & 1u) == 1u)) {\n return truncated + 1u;\n }\n return truncated;\n}\n\nfn makeFloatImmediate(sign: u32, exponent: i32, mantissa: u32) -> u32 {\n return (sign << 31u) | (u32(exponent + 127) << 23u) | (mantissa & 0x7fffffu);\n}\n\nfn makeFloat(sign: u32, exponent: i32, significand: u32) -> u32 {\n if (significand == 0u) {\n return sign << 31u;\n }\n\n let leadingZeros = i32(countLeadingZeros(significand));\n var normalizedExponent = exponent + 31 - leadingZeros;\n\n if (normalizedExponent > 127) {\n return (sign << 31u) | F32_INF;\n }\n\n var mantissa: u32;\n if (normalizedExponent >= -126) {\n mantissa = roundShiftRight(significand, 8 - leadingZeros);\n if (mantissa >= 0x1000000u) {\n mantissa = mantissa >> 1u;\n normalizedExponent += 1;\n if (normalizedExponent > 127) {\n return (sign << 31u) | F32_INF;\n }\n }\n return makeFloatImmediate(sign, normalizedExponent, mantissa);\n }\n\n let subnormalShift = -149 - exponent;\n mantissa = roundShiftRight(significand, subnormalShift);\n if (mantissa >= 0x800000u) {\n return (sign << 31u) | (1u << 23u);\n }\n return (sign << 31u) | mantissa;\n}\n\nfn parseAsDouble(words: vec2<u32>) -> vec2<u32> {\n var d = words;\n if (LE) {\n d = d.yx;\n }\n\n let sign = (d.x >> 31u) & 1u;\n let exponentBits = (d.x >> 20u) & 0x7ffu;\n let exponent = i32(exponentBits) - 1023;\n let fractionHigh = d.x & 0xfffffu;\n let fractionLow = d.y;\n\n if (exponentBits == 0x7ffu) {\n if (fractionHigh == 0u && fractionLow == 0u) {\n return vec2<u32>((sign << 31u) | F32_INF, F32_NAN);\n }\n return vec2<u32>(F32_NAN);\n }\n\n if (exponentBits == 0u) {\n return vec2<u32>(sign << 31u);\n }\n\n if (exponent > 127) {\n return vec2<u32>((sign << 31u) | F32_INF, ((1u - sign) << 31u) | F32_INF);\n }\n\n let highSignificand = 0x800000u | (fractionHigh << 3u) | (fractionLow >> 29u);\n let lowSignificand = fractionLow & 0x1fffffffu;\n\n if (exponent < -126) {\n let highPart = makeFloat(sign, exponent - 23, highSignificand);\n let lowPart = makeFloat(sign, exponent - 52, lowSignificand);\n return vec2<u32>(highPart, lowPart);\n }\n\n let roundUp = lowSignificand > 0x10000000u ||\n (lowSignificand == 0x10000000u && (highSignificand & 1u) == 1u);\n\n var roundedSignificand = highSignificand + select(0u, 1u, roundUp);\n var highExponent = exponent;\n if (roundedSignificand == 0x1000000u) {\n roundedSignificand = 0x800000u;\n highExponent += 1;\n }\n\n if (highExponent > 127) {\n return vec2<u32>((sign << 31u) | F32_INF, ((1u - sign) << 31u) | F32_INF);\n }\n\n let highPart = makeFloatImmediate(sign, highExponent, roundedSignificand);\n\n var remainder = i32(lowSignificand);\n var lowSign = sign;\n if (roundUp) {\n remainder -= 0x20000000;\n }\n if (remainder < 0) {\n lowSign = 1u - sign;\n remainder = -remainder;\n }\n\n let lowPart = makeFloat(lowSign, exponent - 52, u32(remainder));\n return vec2<u32>(highPart, lowPart);\n}\n\nfn fround(x: array<u32, {X_LEN}>) -> array<f32, {RESULT_LEN}> {\n var result: array<f32, {RESULT_LEN}>;\n let n = {X_LEN}u / 2u;\n for (var i = 0u; i < n; i = i + 1u) {\n let parts = parseAsDouble(vec2<u32>(x[i * 2u], x[i * 2u + 1u]));\n result[i] = bitcast<f32>(parts.x);\n result[i + n] = bitcast<f32>(parts.y);\n }\n return result;\n}\n`,Yn=({inputs:e,output:t,target:n})=>(kn({module:{name:"fround",source:Zn},inputs:e,output:t,operationType:"uint32",outputBuffer:n}),{success:!0}),qn=async({inputs:e,output:t,target:n})=>{const{ids:i,sourceValues:o}=e,s=Rn(i.type),r=[];i.isConstant||r.push({name:"ids",input:i,index:r.length}),o.isConstant||r.push({name:"sourceValues",input:o,index:r.length});const a=En(Math.ceil(t.length/64),n.device.limits.maxComputeWorkgroupsPerDimension),l=`\n${r.map(({name:e,input:t,index:n})=>jn(e,t,n)).join("\n")}\n${function(e,t){if(e.isConstant){const n=e.value;if(!n)throw new Error(`Constant input ${e} is missing CPU values`);return`fn read_ids(_rowIndex: u32) -> ${t} {\n return ${zn(t,n[0]??0)};\n}`}const n=e.stride/e.ValueType.BYTES_PER_ELEMENT;return`fn read_ids(rowIndex: u32) -> ${t} {\n let rowOffset = ${e.offset/e.ValueType.BYTES_PER_ELEMENT}u + rowIndex * ${n}u;\n return ids[rowOffset];\n}`}(i,s)}\n${Gn(o,t.type)}\n${Vn(t,r.length)}\n${$n(t)}\n${function(e,t){const n=Mn(e);return`fn zero_result() -> array<${Rn(e)}, ${t}> {\n var result: array<${Rn(e)}, ${t}>;\n${Array.from({length:t},(e,t)=>` result[${t}] = ${n};`).join("\n")}\n return result;\n}`}(t.type,t.size)}\n${function(e,t,n,i){const o=Rn(e);return`fn gather(idsValue: ${o}) -> array<${Rn(t)}, ${n}> {\n let sourceIndex = ${"u32"===o?"i32(idsValue)":"i32"===o?"idsValue":"i32(idsValue)"};\n if (sourceIndex < 0 || sourceIndex >= ${i}) {\n return zero_result();\n }\n return read_source_values(u32(sourceIndex));\n}`}(i.type,t.type,t.size,o.length)}\n\n@compute @workgroup_size(64) fn main(\n @builtin(workgroup_id) workgroupId: vec3<u32>,\n @builtin(local_invocation_id) localId: vec3<u32>\n) {\n let rowIndex = ${On(a,64)};\n if (rowIndex >= ${t.length}u) {\n return;\n }\n\n let idsValue = read_ids(rowIndex);\n let result = gather(idsValue);\n write_result(rowIndex, result);\n}\n`,c=new kt(n.device,{source:l,shaderLayout:{bindings:[...r.map(({name:e,index:t})=>({name:e,type:"storage",group:0,location:t})),{name:"result",type:"storage",group:0,location:r.length}]}}),u={};i.isConstant||(u.ids=i.buffer),o.isConstant||(u.sourceValues=o.buffer),u.result=n,c.setBindings(u);const f=n.device.beginComputePass({});return c.dispatch(f,a.x,a.y,a.z),f.end(),n.device.submit(),c.destroy(),{success:!0}};var Kn=async({inputs:e,output:t,target:n})=>{const{segments:i}=e,o=i.isConstant?[]:[{name:"segments",input:i,index:0}],s=En(Math.ceil(t.length/64),n.device.limits.maxComputeWorkgroupsPerDimension),r=`\n${o.map(({name:e,input:t,index:n})=>jn(e,t,n)).join("\n")}\n${Un("segments",i,"uint32")}\n${Vn(t,o.length)}\n${$n(t)}\n${a=i.length,`fn segmented_map(vertexIndex: u32) -> array<u32, 2> {\n var low = 0i;\n var high = ${a}i;\n while (low < high) {\n let mid = low + (high - low) / 2i;\n let midStart = read_segments(u32(mid))[0];\n if (midStart <= vertexIndex) {\n low = mid + 1i;\n } else {\n high = mid;\n }\n }\n\n let segmentIndex = u32(max(low - 1i, 0i));\n let segmentStart = read_segments(segmentIndex)[0];\n return array<u32, 2>(segmentIndex, vertexIndex - segmentStart);\n}`}\n\n@compute @workgroup_size(64) fn main(\n @builtin(workgroup_id) workgroupId: vec3<u32>,\n @builtin(local_invocation_id) localId: vec3<u32>\n) {\n let rowIndex = ${On(s,64)};\n if (rowIndex >= ${t.length}u) {\n return;\n }\n\n let result = segmented_map(rowIndex);\n write_result(rowIndex, result);\n}\n`;var a;const l=new kt(n.device,{source:r,shaderLayout:{bindings:[...o.map(({name:e,index:t})=>({name:e,type:"storage",group:0,location:t})),{name:"result",type:"storage",group:0,location:o.length}]}}),c=Object.fromEntries(o.map(({name:e,input:t})=>[e,t.buffer]));c.result=n,l.setBindings(c);const u=n.device.beginComputePass({});return l.dispatch(u,s.x,s.y,s.z),u.end(),n.device.submit(),l.destroy(),{success:!0}};var Xn=({inputs:e,output:t,target:n})=>{const i=e.map((e,t)=>[`x${t}`,e]);!function(e,t){const n=t.filter(([,e])=>!e.isConstant).length+1;if(n>e.maxStorageBuffersPerShaderStage)throw new Error(`interleave() requires ${n} storage buffers, exceeding device limit ${e.maxStorageBuffersPerShaderStage}`);if(n>e.maxBindingsPerBindGroup)throw new Error(`interleave() requires ${n} bindings, exceeding bind group limit ${e.maxBindingsPerBindGroup}`)}(n.device.limits,i);const o=i.map(([e,t])=>`${e}: array<{TYPE}, ${t.size}>`).join(", ");let s=0;return kn({module:{name:"interleave",source:`fn interleave(${o}) -> array<{TYPE}, {RESULT_LEN}> {\n var out: array<{TYPE}, {RESULT_LEN}>;\n${i.map(([e,t])=>{const n=Array.from({length:t.size},(t,n)=>` out[${s+n}] = ${e}[${n}];`).join("\n");return s+=t.size,n}).join("\n")}\n return out;\n}\n`},inputs:e,output:t,outputBuffer:n}),{success:!0}};var Jn=({inputs:e,output:t,target:n})=>(kn({module:{name:"row_length",source:"fn row_length(x: array<{TYPE}, {X_LEN}>) -> array<f32, 1> {\n var sum = 0.0;\n for (var i = 0u; i < {X_LEN}u; i = i + 1u) {\n sum += f32(x[i]) * f32(x[i]);\n }\n return array<f32, 1>(sqrt(sum));\n}\n"},inputs:e,output:t,operationType:"float32",outputBuffer:n}),{success:!0}),Qn=async({inputs:e,output:t,target:n})=>{const i=Mn(t.type);return kn({module:{name:"select",source:"// inline expression select\n"},inputs:e,output:t,operationType:t.type,outputBuffer:n,expression:t=>{const n=ei("condition",e.condition,t,i),o=ei("whenTrue",e.whenTrue,t,i);return`select(${ei("whenFalse",e.whenFalse,t,i)}, ${o}, ${n} != ${i})`}}),{success:!0}};function ei(e,t,n,i){return n<t.size?`${e}[${n}]`:1===t.size?`${e}[0]`:i}var ti=({inputs:e,output:t,target:n})=>{const i=En(Math.ceil(t.length/64),n.device.limits.maxComputeWorkgroupsPerDimension),o=`@group(0) @binding(0) var<storage, read_write> result: array<i32>;\n\n@compute @workgroup_size(64) fn main(\n @builtin(workgroup_id) workgroupId: vec3<u32>,\n @builtin(local_invocation_id) localId: vec3<u32>\n) {\n let rowIndex = ${On(i,64)};\n if (rowIndex >= ${t.length}u) {\n return;\n }\n\n let rowOffset = ${t.offset/t.ValueType.BYTES_PER_ELEMENT}u + rowIndex * ${t.stride/t.ValueType.BYTES_PER_ELEMENT}u;\n result[rowOffset] = ${e.start} + i32(rowIndex) * ${e.step};\n}\n`,s=new kt(n.device,{source:o,shaderLayout:{bindings:[{name:"result",type:"storage",group:0,location:0}]}});s.setBindings({result:n});const r=n.device.beginComputePass({});return s.dispatch(r,i.x,i.y,i.z),r.end(),n.device.submit(),s.destroy(),{success:!0}},ni=({inputs:e,output:t,target:n})=>{const{columns:i}=e;return kn({module:{name:"swizzle",source:"// swizzle expression handled inline"},expression:e=>`x[${i[e]}]`,inputs:{x:e.x},output:t,outputBuffer:n}),{success:!0}},ii=/* @__PURE__ */t({arithmetic:()=>Fn,dot:()=>Nn,equalAll:()=>Dn,extent:()=>Wn,fround:()=>Yn,gather:()=>qn,interleave:()=>Xn,length:()=>Jn,segmentedMap:()=>Kn,select:()=>Qn,sequence:()=>ti,swizzle:()=>ni}),oi=class{constructor(e,{id:t,isTransitionAttribute:n}){this.packedBuffers={},this.device=e,this.id=t,this.isTransitionAttribute=n,"webgpu"===this.device.type&&bn.add("webgpu",{interleave:Xn})}hasGroups(e){return"webgpu"===this.device.type&&Object.values(e).some(e=>Boolean(e.settings.bufferGroup))}finalize(){for(const e of Object.values(this.packedBuffers))e.packed.destroy();this.packedBuffers={}}getBufferLayouts(e,t){const n=this._getPackedGroups(e,t,{requireValues:!1,excludeAttributes:{}});return this._getBufferLayouts(e,n,t)}getBindings(e,t,n,i){const o=this._getPackedGroups(e,n,{requireValues:!0,excludeAttributes:i}),s={},r=/* @__PURE__ */new Set;for(const a of o.values()){const e=!this.packedBuffers[a.id]||a.attributes.some(e=>Boolean(t[e.id]));s[a.id]=this._getPackedBuffer(a,e);for(const t of a.attributes)r.add(t.id)}return{bufferLayouts:this._getBufferLayouts(e,o,n).filter(t=>!i[t.name]&&!e[t.name]?.settings.isIndexed),buffers:s,groupedAttributeIds:r}}_getPackedGroups(e,t,{requireValues:n,excludeAttributes:i}){const o=/* @__PURE__ */new Map;for(const r of Object.values(e)){const e=r.settings.bufferGroup;if(!e)continue;const t=o.get(e)||[];t.push(r),o.set(e,t)}const s=/* @__PURE__ */new Map;for(const[r,a]of o){const e=this._getPackedGroup(r,a,t,n,i);e&&s.set(r,e)}return s}_getPackedGroup(e,t,n,i,o){if(t.length<2)return null;const s=t.map(e=>e.getBufferLayout(n)),r=s[0].stepMode,a=Math.max(1,t[0].numInstances),l=i&&t.every(e=>e.isConstant);for(let d=0;d<t.length;d++){const e=t[d],n=e.getAccessor(),l=n.size*n.bytesPerElement;if(o[e.id]||e.settings.isIndexed||e.settings.noAlloc||e.doublePrecision||this.isTransitionAttribute(e.id)||s[d].stepMode!==r||e.numInstances!==t[0].numInstances||0!==(n.offset||0)||0!==(n.vertexOffset||0)||Dt(n)!==l||i&&(e.isConstant?!e.getConstantValue()||e.getConstantValue().byteLength<l:!ArrayBuffer.isView(e.value)||e.value.byteLength<a*l))return null}const c={},u=[];let f=0;for(let d=0;d<t.length;d++){const e=t[d];f=si(f),c[e.id]=f;for(const t of s[d].attributes||[])u.push({...t,byteOffset:f+(t.byteOffset||0)});f+=Dt(e.getAccessor())}return f=si(f),{id:e,attributes:t,byteStride:f,byteOffsets:c,rowCount:a,layout:{name:e,byteStride:l?0:f,stepMode:r,attributes:u}}}_getBufferLayouts(e,t,n){const i=[],o=/* @__PURE__ */new Set,s=/* @__PURE__ */new Set;for(const r of t.values())for(const e of r.attributes)s.add(e.id);for(const r of Object.values(e)){const e=r.settings.bufferGroup,a=e&&t.get(e);a&&s.has(r.id)?o.has(a.id)||(i.push(a.layout),o.add(a.id)):i.push(r.getBufferLayout(n))}return i}_getPackedBuffer(e,t){const n=JSON.stringify({byteStride:e.layout.byteStride,attributes:e.layout.attributes}),i=this.packedBuffers[e.id];if(i&&i.layoutKey===n||(t=!0),t){i&&(i.packed.destroy(),delete this.packedBuffers[e.id]);const t=this._interleavePackedGroup(e);return this.packedBuffers[e.id]={packed:t,layoutKey:n},t.buffer}if(!i)throw new Error(`Attribute buffer group ${e.id} has no packed buffer`);return i.packed.buffer}_interleavePackedGroup(e){const t=function(...e){if(0===e.length)throw new Error("interleave() requires at least one input");return 1===e.length?ae(e[0]):new wn(e.map(ae)).output}(...e.attributes.map(t=>this._getInterleaveInput(e,t)));return Sn(this.device,t),t}_getInterleaveInput(e,t){const n=Dt(t.getAccessor()),i=e.byteOffsets[t.id];if(ri(`${e.id}.${t.id} rowByteLength`,n),ri(`${e.id}.${t.id} groupByteOffset`,i),t.isConstant){const i=t.getConstantValue();if(!i)throw new Error(`Attribute group ${e.id} is missing constant value ${t.id}`);return ri(`${e.id}.${t.id} constant byteOffset`,i.byteOffset),new pe({id:t.id,type:"uint32",size:n/4,isConstant:!0,value:new Uint32Array(i.buffer,i.byteOffset,n/Uint32Array.BYTES_PER_ELEMENT)})}const o=t.getBuffer(),s=t.byteOffset,r=t.getAccessor().stride||n;if(ri(`${e.id}.${t.id} byteOffset`,s),ri(`${e.id}.${t.id} stride`,r),!o)throw new Error(`Attribute group ${e.id} cannot interleave missing buffer ${t.id}`);return new pe({id:t.id,type:"uint32",size:n/4,offset:s,stride:r,length:e.rowCount,buffer:o})}};function si(e){return 4*Math.ceil(e/4)}function ri(e,t){if(t%4!=0)throw new Error(`Attribute buffer groups require 32-bit alignment: ${e}=${t}`)}function ai(e){const{source:t,target:n,start:i=0,size:o,getData:s}=e,r=e.end||n.length,a=t.length,l=r-i;if(a>l)return void n.set(t.subarray(0,l),i);if(n.set(t,i),!s)return;let c=a;for(;c<l;){const e=s(c,t);for(let t=0;t<o;t++)n[i+c]=e[t]||0,c++}}function li(e){switch(e){case 1:return"float";case 2:return"vec2";case 3:return"vec3";case 4:return"vec4";default:throw new Error(`No defined attribute type for size "${e}"`)}}function ci(e){switch(e){case 1:return"float32";case 2:return"float32x2";case 3:return"float32x3";case 4:return"float32x4";default:throw new Error("invalid type size")}}function ui(e){e.push(e.shift())}function fi({device:e,source:t,target:n}){return(!n||n.byteLength<t.byteLength)&&(n?.destroy(),n=e.createBuffer({byteLength:t.byteLength,usage:t.usage})),n}function di({device:e,buffer:t,attribute:n,fromLength:i,toLength:o,fromStartIndices:s,getData:r=e=>e}){const a=n.isDoublePrecisionBuffer?2:1,l=n.size*a,c=n.byteOffset,u=n.settings.bytesPerElement<4?c/n.settings.bytesPerElement*4:c,f=n.startIndices,d=s&&f,p=n.isConstant;if(!d&&t&&i>=o)return t;const g=n.value instanceof Float64Array?Float32Array:n.value.constructor,h=p?n.value:new g(n.getBuffer().readSyncWebGL(c,o*g.BYTES_PER_ELEMENT).buffer);if(n.settings.normalized&&!p){const e=r;r=(t,i)=>n.normalizeConstant(e(t,i))}const v=p?(e,t)=>r(h,t):(e,t)=>r(h.subarray(e,e+l),t),m=t?new Float32Array(t.readSyncWebGL(u,4*i).buffer):/* @__PURE__ */new Float32Array(0),_=new Float32Array(o);return function({source:e,target:t,size:n,getData:i,sourceStartIndices:o,targetStartIndices:s}){if(!o||!s)return ai({source:e,target:t,size:n,getData:i}),t;let r=0,a=0;const l=i&&((e,t)=>i(e+a,t)),c=Math.min(o.length,s.length);for(let u=1;u<c;u++){const i=o[u]*n,c=s[u]*n;ai({source:e.subarray(r,i),target:t,start:a,end:c,size:n,getData:l}),r=i,a=c}a<t.length&&ai({source:[],target:t,start:a,size:n,getData:l})}({source:m,target:_,sourceStartIndices:s,targetStartIndices:f,size:l,getData:v}),(!t||t.byteLength<_.byteLength+u)&&(t?.destroy(),t=e.createBuffer({byteLength:_.byteLength+u,usage:35050})),t.write(_,u),t}var pi=class{constructor({device:e,attribute:t,timeline:n}){this.buffers=[],this.currentLength=0,this.device=e,this.transition=new L(n),this.attribute=t,this.attributeInTransition=function(e){const{device:t,settings:n,value:i}=e,o=new Xt(t,n);return o.setData({value:i instanceof Float64Array?/* @__PURE__ */new Float64Array(0):/* @__PURE__ */new Float32Array(0),normalized:n.normalized}),o}(t),this.currentStartIndices=t.startIndices}get inProgress(){return this.transition.inProgress}start(e,t,n=1/0){this.settings=e,this.currentStartIndices=this.attribute.startIndices,this.currentLength=function(e,t){const{settings:n,value:i,size:o}=e,s=e.isDoublePrecisionBuffer?2:1;let r=0;const{shaderAttributes:a}=e.settings;if(a)for(const l of Object.values(a))r=Math.max(r,l.vertexOffset??0);return(n.noAlloc?i.length:(t+r)*o)*s}(this.attribute,t),this.transition.start({...e,duration:n})}update(){const e=this.transition.update();return e&&this.onUpdate(),e}setBuffer(e){const{stride:t}=this.attributeInTransition.getAccessor();this.attributeInTransition.setData({buffer:e,normalized:this.attribute.settings.normalized,value:this.attributeInTransition.value,stride:t})}cancel(){this.transition.cancel()}delete(){this.cancel();for(const e of this.buffers)e.destroy();this.buffers.length=0}},gi={name:"interpolation",vs:"layout(std140) uniform interpolationUniforms {\n float time;\n} interpolation;\n",uniformTypes:{time:"f32"}},hi="#version 300 es\n#define SHADER_NAME interpolation-transition-vertex-shader\n\nin ATTRIBUTE_TYPE aFrom;\nin ATTRIBUTE_TYPE aTo;\nout ATTRIBUTE_TYPE vCurrent;\n\nvoid main(void) {\n vCurrent = mix(aFrom, aTo, interpolation.time);\n gl_Position = vec4(0.0);\n}\n",vi="#version 300 es\n#define SHADER_NAME interpolation-transition-vertex-shader\n\nin ATTRIBUTE_TYPE aFrom;\nin ATTRIBUTE_TYPE aFrom64Low;\nin ATTRIBUTE_TYPE aTo;\nin ATTRIBUTE_TYPE aTo64Low;\nout ATTRIBUTE_TYPE vCurrent;\nout ATTRIBUTE_TYPE vCurrent64Low;\n\nvec2 mix_fp64(vec2 a, vec2 b, float x) {\n vec2 range = sub_fp64(b, a);\n return sum_fp64(a, mul_fp64(range, vec2(x, 0.0)));\n}\n\nvoid main(void) {\n for (int i=0; i<ATTRIBUTE_SIZE; i++) {\n vec2 value = mix_fp64(vec2(aFrom[i], aFrom64Low[i]), vec2(aTo[i], aTo64Low[i]), interpolation.time);\n vCurrent[i] = value.x;\n vCurrent64Low[i] = value.y;\n }\n gl_Position = vec4(0.0);\n}\n";function mi(e){return e.isDoublePrecisionBuffer}var _i={name:"spring",vs:"layout(std140) uniform springUniforms {\n float damping;\n float stiffness;\n} spring;\n",uniformTypes:{damping:"f32",stiffness:"f32"}},xi="#version 300 es\n#define SHADER_NAME spring-transition-vertex-shader\n\n#define EPSILON 0.00001\n\nin ATTRIBUTE_TYPE aPrev;\nin ATTRIBUTE_TYPE aCur;\nin ATTRIBUTE_TYPE aTo;\nout ATTRIBUTE_TYPE vNext;\nout float vIsTransitioningFlag;\n\nATTRIBUTE_TYPE getNextValue(ATTRIBUTE_TYPE cur, ATTRIBUTE_TYPE prev, ATTRIBUTE_TYPE dest) {\n ATTRIBUTE_TYPE velocity = cur - prev;\n ATTRIBUTE_TYPE delta = dest - cur;\n ATTRIBUTE_TYPE force = delta * spring.stiffness;\n ATTRIBUTE_TYPE resistance = velocity * spring.damping;\n return force - resistance + velocity + cur;\n}\n\nvoid main(void) {\n bool isTransitioning = length(aCur - aPrev) > EPSILON || length(aTo - aCur) > EPSILON;\n vIsTransitioningFlag = isTransitioning ? 1.0 : 0.0;\n\n vNext = getNextValue(aCur, aPrev, aTo);\n gl_Position = vec4(0, 0, 0, 1);\n gl_PointSize = 100.0;\n}\n",yi="#version 300 es\n#define SHADER_NAME spring-transition-is-transitioning-fragment-shader\n\nin float vIsTransitioningFlag;\n\nout vec4 fragColor;\n\nvoid main(void) {\n if (vIsTransitioningFlag == 0.0) {\n discard;\n }\n fragColor = vec4(1.0);\n}";var bi={interpolation:class extends pi{constructor({device:e,attribute:t,timeline:n}){super({device:e,attribute:t,timeline:n}),this.type="interpolation",this.hasUpdated=!1,this.transform=function(e,t){const n=t.size,i=li(n),o=ci(n),s=t.getBufferLayout();return mi(t)?new Ct(e,{vs:vi,bufferLayout:[{name:"aFrom",byteStride:8*n,attributes:[{attribute:"aFrom",format:o,byteOffset:0},{attribute:"aFrom64Low",format:o,byteOffset:4*n}]},{name:"aTo",byteStride:8*n,attributes:[{attribute:"aTo",format:o,byteOffset:0},{attribute:"aTo64Low",format:o,byteOffset:4*n}]}],modules:[Ae,gi],defines:{ATTRIBUTE_TYPE:i,ATTRIBUTE_SIZE:n},moduleSettings:{},varyings:["vCurrent","vCurrent64Low"],bufferMode:35980,disableWarnings:!0}):new Ct(e,{vs:hi,bufferLayout:[{name:"aFrom",format:o},{name:"aTo",format:s.attributes[0].format}],modules:[gi],defines:{ATTRIBUTE_TYPE:i},varyings:["vCurrent"],disableWarnings:!0})}(e,t)}start(e,t){const n=this.currentLength,i=this.currentStartIndices;if(super.start(e,t,e.duration),e.duration<=0)return void this.transition.cancel();const{buffers:o,attribute:s}=this;this.hasUpdated&&ui(o),this.hasUpdated=!1,o[0]=di({device:this.device,buffer:o[0],attribute:s,fromLength:n,toLength:this.currentLength,fromStartIndices:i,getData:e.enter}),o[1]=fi({device:this.device,source:o[0],target:o[1]}),this.setBuffer(o[1]);const{transform:r}=this,a=r.model;let l=Math.floor(this.currentLength/s.size);mi(s)&&(l/=2),a.setVertexCount(l),s.isConstant?(a.setAttributes({aFrom:o[0]}),a.setConstantAttributes({aTo:s.value})):a.setAttributes({aFrom:o[0],aTo:s.getBuffer()}),r.transformFeedback.setBuffers({vCurrent:o[1]})}onUpdate(){const{duration:e,easing:t}=this.settings,{time:n}=this.transition;let i=n/e;t&&(i=t(i));const{model:o}=this.transform,s={time:i};o.shaderInputs.setProps({interpolation:s}),this.transform.run({discard:!0}),this.hasUpdated=!0}delete(){super.delete(),this.transform.destroy()}},spring:class extends pi{constructor({device:e,attribute:t,timeline:n}){super({device:e,attribute:t,timeline:n}),this.type="spring",this.texture=function(e){return e.createTexture({data:/* @__PURE__ */new Uint8Array(4),format:"rgba8unorm",width:1,height:1})}(e),this.framebuffer=function(e,t){return e.createFramebuffer({id:"spring-transition-is-transitioning-framebuffer",width:1,height:1,colorAttachments:[t]})}(e,this.texture),this.transform=function(e,t){const n=li(t.size),i=ci(t.size);return new Ct(e,{vs:xi,fs:yi,bufferLayout:[{name:"aPrev",format:i},{name:"aCur",format:i},{name:"aTo",format:t.getBufferLayout().attributes[0].format}],varyings:["vNext"],modules:[_i],defines:{ATTRIBUTE_TYPE:n},parameters:{depthCompare:"always",blendColorOperation:"max",blendColorSrcFactor:"one",blendColorDstFactor:"one",blendAlphaOperation:"max",blendAlphaSrcFactor:"one",blendAlphaDstFactor:"one"}})}(e,t)}start(e,t){const n=this.currentLength,i=this.currentStartIndices;super.start(e,t);const{buffers:o,attribute:s}=this;for(let a=0;a<2;a++)o[a]=di({device:this.device,buffer:o[a],attribute:s,fromLength:n,toLength:this.currentLength,fromStartIndices:i,getData:e.enter});o[2]=fi({device:this.device,source:o[0],target:o[2]}),this.setBuffer(o[1]);const{model:r}=this.transform;r.setVertexCount(Math.floor(this.currentLength/s.size)),s.isConstant?r.setConstantAttributes({aTo:s.value}):r.setAttributes({aTo:s.getBuffer()})}onUpdate(){const{buffers:e,transform:t,framebuffer:n,transition:i}=this,o=this.settings;t.model.setAttributes({aPrev:e[0],aCur:e[1]}),t.transformFeedback.setBuffers({vNext:e[2]});const s={stiffness:o.stiffness,damping:o.damping};t.model.shaderInputs.setProps({spring:s}),t.run({framebuffer:n,discard:!1,parameters:{viewport:[0,0,1,1]},clearColor:[0,0,0,0]}),ui(e),this.setBuffer(e[1]),this.device.readPixelsToArrayWebGL(n)[0]>0||i.end()}delete(){super.delete(),this.transform.destroy(),this.texture.destroy(),this.framebuffer.destroy()}}},Pi=class{constructor(e,{id:t,timeline:n}){if(!e)throw new Error("AttributeTransitionManager is constructed without device");this.id=t,this.device=e,this.timeline=n,this.transitions={},this.needsRedraw=!1,this.numInstances=1}finalize(){for(const e in this.transitions)this._removeTransition(e)}update({attributes:e,transitions:t,numInstances:n}){this.numInstances=n||1;for(const i in e){const n=e[i],o=n.getTransitionSetting(t);o&&this._updateAttribute(i,n,o)}for(const i in this.transitions){const n=e[i];n&&n.getTransitionSetting(t)||this._removeTransition(i)}}hasAttribute(e){const t=this.transitions[e];return t&&t.inProgress}getAttributes(){const e={};for(const t in this.transitions){const n=this.transitions[t];n.inProgress&&(e[t]=n.attributeInTransition)}return e}run(){if(0===this.numInstances)return!1;for(const t in this.transitions)this.transitions[t].update()&&(this.needsRedraw=!0);const e=this.needsRedraw;return this.needsRedraw=!1,e}_removeTransition(e){this.transitions[e].delete(),delete this.transitions[e]}_updateAttribute(e,t,n){const i=this.transitions[e];let o=!i||i.type!==n.type;if(o){i&&this._removeTransition(e);const s=bi[n.type];s?this.transitions[e]=new s({attribute:t,timeline:this.timeline,device:this.device}):(I.error(`unsupported transition type '${n.type}'`)(),o=!1)}(o||t.needsRedraw())&&(this.needsRedraw=!0,this.transitions[e].start(n,this.numInstances))}},Ci="attributeManager.invalidate",wi=class{constructor(e,{id:t="attribute-manager",stats:n,timeline:i}={}){this.mergeBoundsMemoized=r(R),this.id=t,this.device=e,this.attributes={},this.updateTriggers={},this.needsRedraw=!0,this.userData={},this.stats=n,this.attributeTransitionManager=new Pi(e,{id:`${t}-transitions`,timeline:i}),this.attributeBufferGroups="webgpu"===e.type?new oi(e,{id:t,isTransitionAttribute:e=>this.attributeTransitionManager.hasAttribute(e)}):null,Object.seal(this)}finalize(){this.attributeBufferGroups?.finalize();for(const e in this.attributes)this.attributes[e].delete();this.attributeTransitionManager.finalize()}getNeedsRedraw(e={clearRedrawFlags:!1}){const t=this.needsRedraw;return this.needsRedraw=this.needsRedraw&&!e.clearRedrawFlags,t&&this.id}setNeedsRedraw(){this.needsRedraw=!0}add(e){this._add(e)}addInstanced(e){this._add(e,{stepMode:"instance"})}remove(e){for(const t of e)void 0!==this.attributes[t]&&(this.attributes[t].delete(),delete this.attributes[t])}invalidate(e,t){const n=this._invalidateTrigger(e,t);T(Ci,this,e,n)}invalidateAll(e){for(const t in this.attributes)this.attributes[t].setNeedsUpdate(t,e);T(Ci,this,"all")}update({data:e,numInstances:t,startIndices:n=null,transitions:i,props:o={},buffers:s={},context:r={}}){let a=!1;T("attributeManager.updateStart",this),this.stats&&this.stats.get("Update Attributes").timeStart();for(const l in this.attributes){const i=this.attributes[l],c=i.settings.accessor;i.startIndices=n,i.numInstances=t,o[l]&&I.removed(`props.${l}`,`data.attributes.${l}`)(),i.setExternalBuffer(s[l])||i.setBinaryValue("string"==typeof c?s[c]:void 0,e.startIndices)||"string"==typeof c&&!s[c]&&i.setConstantValue(r,o[c])||i.needsUpdate()&&(a=!0,this._updateAttribute({attribute:i,numInstances:t,data:e,props:o,context:r})),this.needsRedraw=this.needsRedraw||i.needsRedraw()}a&&T("attributeManager.updateEnd",this,t),this.stats&&(this.stats.get("Update Attributes").timeEnd(),a&&this.stats.get("Attributes updated").incrementCount()),this.attributeTransitionManager.update({attributes:this.attributes,numInstances:t,transitions:i})}updateTransition(){const{attributeTransitionManager:e}=this,t=e.run();return this.needsRedraw=this.needsRedraw||t,t}getAttributes(){return{...this.attributes,...this.attributeTransitionManager.getAttributes()}}getBounds(e){const t=e.map(e=>this.attributes[e]?.getBounds());return this.mergeBoundsMemoized(t)}getChangedAttributes(e={clearChangedFlags:!1}){const{attributes:t,attributeTransitionManager:n}=this,i={...n.getAttributes()};for(const o in t){const s=t[o];s.needsRedraw(e)&&!n.hasAttribute(o)&&(i[o]=s)}return i}getBufferLayouts(e){return this.hasBufferGroups()?this.attributeBufferGroups.getBufferLayouts(this.getAttributes(),e):Object.values(this.getAttributes()).map(t=>t.getBufferLayout(e))}hasBufferGroups(){return Boolean(this.attributeBufferGroups?.hasGroups(this.attributes))}getBufferGroupBindings(e,t,n={}){return this.attributeBufferGroups?this.attributeBufferGroups.getBindings(this.getAttributes(),e,t,n):{bufferLayouts:this.getBufferLayouts(t),buffers:{},groupedAttributeIds:/* @__PURE__ */new Set}}_add(e,t){for(const n in e){const i=e[n],o={...i,id:n,size:(i.isIndexed?1:i.size)||1,...t};this.attributes[n]=new Xt(this.device,o)}this._mapUpdateTriggersToAttributes()}_mapUpdateTriggersToAttributes(){const e={};for(const t in this.attributes)this.attributes[t].getUpdateTriggers().forEach(n=>{e[n]||(e[n]=[]),e[n].push(t)});this.updateTriggers=e}_invalidateTrigger(e,t){const{attributes:n,updateTriggers:i}=this,o=i[e];return o&&o.forEach(e=>{const i=n[e];i&&i.setNeedsUpdate(i.id,t)}),o}_updateAttribute(e){const{attribute:t,numInstances:n}=e;T("attribute.updateStart",t),t.constant?t.setConstantValue(e.context,t.value):(t.allocate(n)&&T("attribute.allocate",t,n),t.updateBuffer(e)&&(this.needsRedraw=!0,T("attribute.updateEnd",t,n)))}},Si=1e-5;function Li(e,t,n,i,o){const s=t-e;return(n-t)*o+-s*i+s+t}function Ai(e,t){if(Array.isArray(e)){let n=0;for(let i=0;i<e.length;i++){const o=e[i]-t[i];n+=o*o}return Math.sqrt(n)}return Math.abs(e-t)}var Ii={interpolation:class extends L{get value(){return this._value}_onUpdate(){const{time:e,settings:{fromValue:t,toValue:n,duration:i,easing:o}}=this,s=o(e/i);this._value=a(t,n,s)}},spring:class extends L{get value(){return this._currValue}_onUpdate(){const{fromValue:e,toValue:t,damping:n,stiffness:i}=this.settings,{_prevValue:o=e,_currValue:s=e}=this;let r=function(e,t,n,i,o){if(Array.isArray(n)){const s=[];for(let r=0;r<n.length;r++)s[r]=Li(e[r],t[r],n[r],i,o);return s}return Li(e,t,n,i,o)}(o,s,t,n,i);const a=Ai(r,t),l=Ai(r,s);a<Si&&l<Si&&(r=t,this.end()),this._prevValue=s,this._currValue=r}}},Ei=class{constructor(e){this.transitions=/* @__PURE__ */new Map,this.timeline=e}get active(){return this.transitions.size>0}add(e,t,n,i){const{transitions:o}=this;if(o.has(e)){const n=o.get(e),{value:i=n.settings.fromValue}=n;t=i,this.remove(e)}if(!(i=Kt(i)))return;const s=Ii[i.type];if(!s)return void I.error(`unsupported transition type '${i.type}'`)();const r=new s(this.timeline);r.start({...i,fromValue:t,toValue:n}),o.set(e,r)}remove(e){const{transitions:t}=this;t.has(e)&&(t.get(e).cancel(),t.delete(e))}update(){const e={};for(const[t,n]of this.transitions)n.update(),e[t]=n.value,n.inProgress||this.remove(t);return e}clear(){for(const e of this.transitions.keys())this.remove(e)}};function Ti(e,t){const n=zi({newProps:e,oldProps:t,propTypes:e[y],ignoreProps:{data:null,updateTriggers:null,extensions:null,transitions:null}}),i=function(e,t){if(null===t)return"oldProps is null, initial diff";let n=!1;const{dataComparator:i,_dataDiff:o}=e;i?i(e.data,t.data)||(n="Data comparator detected a change"):e.data!==t.data&&(n="A new data container was supplied");n&&o&&(n=o(e.data,t.data)||n);return n}(e,t);let o=!1;return i||(o=function(e,t){if(null===t)return{all:!0};if("all"in e.updateTriggers&&Bi(e,t,"all"))return{all:!0};const n={};let i=!1;for(const o in e.updateTriggers)"all"!==o&&Bi(e,t,o)&&(n[o]=!0,i=!0);return!!i&&n}(e,t)),{dataChanged:i,propsChanged:n,updateTriggersChanged:o,extensionsChanged:Ri(e,t),transitionsChanged:Oi(e,t)}}function Oi(e,t){if(!e.transitions)return!1;const n={},i=e[y];let o=!1;for(const s in e.transitions){const r=i[s],a=r&&r.type;"number"!==a&&"color"!==a&&"array"!==a||!Mi(e[s],t[s],r)||(n[s]=!0,o=!0)}return!!o&&n}function zi({newProps:e,oldProps:t,ignoreProps:n={},propTypes:i={},triggerName:o="props"}){if(t===e)return!1;if("object"!=typeof e||null===e)return`${o} changed shallowly`;if("object"!=typeof t||null===t)return`${o} changed shallowly`;for(const s of Object.keys(e))if(!(s in n)){if(!(s in t))return`${o}.${s} added`;const n=Mi(e[s],t[s],i[s]);if(n)return`${o}.${s} ${n}`}for(const s of Object.keys(t))if(!(s in n)){if(!(s in e))return`${o}.${s} dropped`;if(!Object.hasOwnProperty.call(e,s)){const n=Mi(e[s],t[s],i[s]);if(n)return`${o}.${s} ${n}`}}return!1}function Mi(e,t,n){let i=n&&n.equal;return i&&!i(e,t,n)?"changed deeply":i||(i=e&&t&&e.equals,!i||i.call(e,t))?i||t===e?null:"changed shallowly":"changed deeply"}function Ri(e,t){if(null===t)return!0;const n=t.extensions,{extensions:i}=e;if(i===n)return!1;if(!n||!i)return!0;if(i.length!==n.length)return!0;for(let o=0;o<i.length;o++)if(!i[o].equals(n[o]))return!0;return!1}function Bi(e,t,n){let i=e.updateTriggers[n];i=null==i?{}:i;let o=t.updateTriggers[n];return o=null==o?{}:o,zi({oldProps:o,newProps:i,triggerName:n})}function ki(e){if(null===(t=e)||"object"!=typeof t)throw new Error("count(): argument not an object");var t;if("function"==typeof e.count)return e.count();if(Number.isFinite(e.size))return e.size;if(Number.isFinite(e.length))return e.length;if(function(e){return null!==e&&"object"==typeof e&&e.constructor===Object}(e))return Object.keys(e).length;throw new Error("count(): argument not a container")}function Fi(e,t){if(!t)return e;const n={...e,...t};if("defines"in t&&(n.defines={...e.defines,...t.defines}),"modules"in t&&(n.modules=(e.modules||[]).concat(t.modules),t.modules.some(e=>"project64"===e.name))){const e=n.modules.findIndex(e=>"project32"===e.name);e>=0&&n.modules.splice(e,1)}if("inject"in t)if(e.inject){const i={...e.inject};for(const e in t.inject)i[e]=(i[e]||"")+t.inject[e];n.inject=i}else n.inject=t.inject;return n}var Ni={minFilter:"linear",mipmapFilter:"linear",magFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"},Di={};var ji={boolean:{validate:(e,t)=>!0,equal:(e,t,n)=>Boolean(e)===Boolean(t)},number:{validate:(e,t)=>Number.isFinite(e)&&(!("max"in t)||e<=t.max)&&(!("min"in t)||e>=t.min)},color:{validate:(e,t)=>t.optional&&!e||Vi(e)&&(3===e.length||4===e.length),equal:(e,t,n)=>E(e,t,1)},accessor:{validate(e,t){const n=$i(e);return"function"===n||n===$i(t.value)},equal:(e,t,n)=>"function"==typeof t||E(e,t,1)},array:{validate:(e,t)=>t.optional&&!e||Vi(e),equal(e,t,n){const{compare:i}=n;return i?E(e,t,Number.isInteger(i)?i:i?1:0):e===t}},object:{equal(e,t,n){if(n.ignore)return!0;const{compare:i}=n;return i?E(e,t,Number.isInteger(i)?i:i?1:0):e===t}},function:{validate:(e,t)=>t.optional&&!e||"function"==typeof e,equal:(e,t,n)=>!n.compare&&!1!==n.ignore||e===t},data:{transform:(e,t,n)=>{if(!e)return e;const{dataTransform:i}=n.props;return i?i(e):"string"==typeof e.shape&&e.shape.endsWith("-table")&&Array.isArray(e.data)?e.data:e}},image:{transform:(e,t,n)=>{const i=n.context;return i&&i.device?function(e,t,n,i){if(n instanceof p)return n;n.constructor&&"Object"!==n.constructor.name&&(n={data:n});let o=null;n.compressed&&(o={minFilter:"linear",mipmapFilter:n.data.length>1?"nearest":"linear"});const{width:s,height:r}=n.data,a=t.createTexture({...n,sampler:{...Ni,...o,...i},mipLevels:t.getMipLevelCount(s,r)});return"webgl"===t.type?a.generateMipmapsWebGL():"webgpu"===t.type&&t.generateMipmapsWebGPU(a),Di[a.id]=e,a}(n.id,i.device,e,{...t.parameters,...n.props.textureParameters}):null},release:(e,t,n)=>{var i,o;i=n.id,(o=e)&&o instanceof p&&Di[o.id]===i&&(o.delete(),delete Di[o.id])}}};function Ui(e,t){switch($i(t)){case"object":return Gi(e,t);case"array":return Gi(e,{type:"array",value:t,compare:!1});case"boolean":return Gi(e,{type:"boolean",value:t});case"number":return Gi(e,{type:"number",value:t});case"function":return Gi(e,{type:"function",value:t,compare:!0});default:return{name:e,type:"unknown",value:t}}}function Gi(e,t){return"type"in t?{name:e,...ji[t.type],...t}:"value"in t?{name:e,type:$i(t.value),...t}:{name:e,type:"object",value:t}}function Vi(e){return Array.isArray(e)||ArrayBuffer.isView(e)}function $i(e){return Vi(e)?"array":null===e?"null":typeof e}var Wi="_mergedDefaultProps";function Hi(e,t){if(!(e instanceof Xi.constructor))return{};let n=Wi;if(t)for(const o of t){const e=o.constructor;e&&(n+=`:${e.extensionName||e.name}`)}const i=qi(e,n);return i||(e[n]=function(e,t){if(!e.prototype)return null;const n=Hi(Object.getPrototypeOf(e)),i=qi(e,"defaultProps")||{},o=function(e){const t={},n={},i={};for(const[o,s]of Object.entries(e)){const e=s?.deprecatedFor;if(e)i[o]=Array.isArray(e)?e:[e];else{const e=Ui(o,s);t[o]=e,n[o]=e.value}}return{propTypes:t,defaultProps:n,deprecatedProps:i}}(i),s=Object.assign(Object.create(null),n,o.defaultProps),r=Object.assign(Object.create(null),n?.[y],o.propTypes),a=Object.assign(Object.create(null),n?.[S],o.deprecatedProps);for(const l of t){const e=Hi(l.constructor);e&&(Object.assign(s,e),Object.assign(r,e[y]),Object.assign(a,e[S]))}(function(e,t){const n=function(e){const t=e.componentName;t||I.warn(`${e.name}.componentName not specified`)();return t||e.name}(t);Object.defineProperties(e,{id:{writable:!0,value:n}})})(s,e),function(e,t){const n={},i={};for(const o in t){const e=t[o],{name:s,value:r}=e;e.async&&(n[s]=r,i[s]=Zi(s))}e[O]=n,e[m]={},Object.defineProperties(e,i)}(s,r),function(e,t){for(const n in t)Object.defineProperty(e,n,{enumerable:!1,set(e){const i=`${this.id}: ${n}`;for(const o of t[n])Yi(this,o)||(this[o]=e);I.deprecated(i,t[n].join("/"))()}})}(s,a),s[y]=r,s[S]=a,0!==t.length||Yi(e,"_propTypes")||(e._propTypes=r);return s}(e,t||[]))}function Zi(e){return{enumerable:!0,set(t){"string"==typeof t||t instanceof Promise||Wt(t)?this[m][e]=t:this[_][e]=t},get(){if(this[_]){if(e in this[_])return this[_][e]||this[O][e];if(e in this[m]){const t=this[A]&&this[A].internalState;if(t&&t.hasAsyncProp(e))return t.getAsyncProp(e)||this[O][e]}}return this[O][e]}}}function Yi(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function qi(e,t){return Yi(e,t)&&e[t]}var Ki=0,Xi=class{constructor(...e){this.props=function(e,t){let n;for(let s=t.length-1;s>=0;s--){const e=t[s];"extensions"in e&&(n=e.extensions)}const i=Hi(e.constructor,n),o=Object.create(i);o[A]=e,o[m]={},o[_]={};for(let s=0;s<t.length;++s){const e=t[s];for(const t in e)o[t]=e[t]}return Object.freeze(o),o}(this,e),this.id=this.props.id,this.count=Ki++}clone(e){const{props:t}=this,n={};for(const i in t[O])i in t[_]?n[i]=t[_][i]:i in t[m]&&(n[i]=t[m][i]);return new this.constructor({...t,...n,...e})}};Xi.componentName="Component",Xi.defaultProps={};var Ji=Object.freeze({}),Qi=class{constructor(e){this.component=e,this.asyncProps={},this.onAsyncPropUpdated=()=>{},this.oldProps=null,this.oldAsyncProps=null}finalize(){for(const e in this.asyncProps){const t=this.asyncProps[e];t&&t.type&&t.type.release&&t.type.release(t.resolvedValue,t.type,this.component)}this.asyncProps={},this.component=null,this.resetOldProps()}getOldProps(){return this.oldAsyncProps||this.oldProps||Ji}resetOldProps(){this.oldAsyncProps=null,this.oldProps=this.component?this.component.props:null}hasAsyncProp(e){return e in this.asyncProps}getAsyncProp(e){const t=this.asyncProps[e];return t&&t.resolvedValue}isAsyncPropLoading(e){if(e){const t=this.asyncProps[e];return Boolean(t&&t.pendingLoadCount>0&&t.pendingLoadCount!==t.resolvedLoadCount)}for(const t in this.asyncProps)if(this.isAsyncPropLoading(t))return!0;return!1}reloadAsyncProp(e,t){this._watchPromise(e,Promise.resolve(t))}setAsyncProps(e){this.component=e[A]||this.component;const t=e[_]||{},n=e[m]||e,i=e[O]||{};for(const o in t){const e=t[o];this._createAsyncPropData(o,i[o]),this._updateAsyncProp(o,e),t[o]=this.getAsyncProp(o)}for(const o in n){const e=n[o];this._createAsyncPropData(o,i[o]),this._updateAsyncProp(o,e)}}_fetch(e,t){return null}_onResolve(e,t){}_onError(e,t){}_updateAsyncProp(e,t){this._didAsyncInputValueChange(e,t)&&("string"==typeof t&&(t=this._fetch(e,t)),t instanceof Promise?this._watchPromise(e,t):Wt(t)?this._resolveAsyncIterable(e,t):this._setPropValue(e,t))}_freezeAsyncOldProps(){if(!this.oldAsyncProps&&this.oldProps){this.oldAsyncProps=Object.create(this.oldProps);for(const e in this.asyncProps)Object.defineProperty(this.oldAsyncProps,e,{enumerable:!0,value:this.oldProps[e]})}}_didAsyncInputValueChange(e,t){const n=this.asyncProps[e];return t!==n.resolvedValue&&t!==n.lastValue&&(n.lastValue=t,!0)}_setPropValue(e,t){this._freezeAsyncOldProps();const n=this.asyncProps[e];n&&(t=this._postProcessValue(n,t),n.resolvedValue=t,n.pendingLoadCount++,n.resolvedLoadCount=n.pendingLoadCount)}_setAsyncPropValue(e,t,n){const i=this.asyncProps[e];i&&n>=i.resolvedLoadCount&&void 0!==t&&(this._freezeAsyncOldProps(),i.resolvedValue=t,i.resolvedLoadCount=n,this.onAsyncPropUpdated(e,t))}_watchPromise(e,t){const n=this.asyncProps[e];if(n){n.pendingLoadCount++;const i=n.pendingLoadCount;t.then(t=>{this.component&&(t=this._postProcessValue(n,t),this._setAsyncPropValue(e,t,i),this._onResolve(e,t))}).catch(t=>{this._onError(e,t)})}}async _resolveAsyncIterable(e,t){if("data"!==e)return void this._setPropValue(e,t);const n=this.asyncProps[e];if(!n)return;n.pendingLoadCount++;const i=n.pendingLoadCount;let o=[],s=0;for await(const r of t){if(!this.component)return;const{dataTransform:t}=this.component.props;o=t?t(r,o):o.concat(r),Object.defineProperty(o,"__diff",{enumerable:!1,value:[{startRow:s,endRow:o.length}]}),s=o.length,this._setAsyncPropValue(e,o,i)}this._onResolve(e,o)}_postProcessValue(e,t){const n=e.type;return n&&this.component&&(n.release&&n.release(e.resolvedValue,n,this.component),n.transform)?n.transform(t,n,this.component):t}_createAsyncPropData(e,t){if(!this.asyncProps[e]){const n=this.component&&this.component.props[y];this.asyncProps[e]={type:n&&n[e],lastValue:null,resolvedValue:t,pendingLoadCount:0,resolvedLoadCount:0}}}},eo=class extends Qi{constructor({attributeManager:e,layer:t}){super(t),this.attributeManager=e,this.needsRedraw=!0,this.needsUpdate=!0,this.subLayers=null,this.usesPickingColorCache=!1,this.disabledPickingIndices=[]}get layer(){return this.component}_fetch(e,t){const n=this.layer,i=n?.props.fetch;return i?i(t,{propName:e,layer:n}):super._fetch(e,t)}_onResolve(e,t){const n=this.layer;if(n){const i=n.props.onDataLoad;"data"===e&&i&&i(t,{propName:e,layer:n})}}_onError(e,t){const n=this.layer;n&&n.raiseError(t,`loading ${e} of ${this.layer}`)}},to=2**24-1,no=Object.freeze([]),io=r(({oldViewport:e,viewport:t})=>e.equals(t)),oo=/* @__PURE__ */new Uint8ClampedArray(0);function so(e){return e.rowIndexes||e.pickingColors||e.instancePickingColors}function ro(e){return e.rowIndexes}function ao(e){return e.pickingColors||e.instancePickingColors}var lo={data:{type:"data",value:no,async:!0},dataComparator:{type:"function",value:null,optional:!0},_dataDiff:{type:"function",value:e=>e&&e.__diff,optional:!0},dataTransform:{type:"function",value:null,optional:!0},onDataLoad:{type:"function",value:null,optional:!0},onError:{type:"function",value:null,optional:!0},fetch:{type:"function",value:(e,{propName:t,layer:n,loaders:i,loadOptions:o,signal:s})=>{const{resourceManager:r}=n.context;o=o||n.getLoadOptions(),i=i||n.props.loaders,s&&(o={...o,core:{...o?.core,fetch:{...o?.core?.fetch,signal:s}}});let a=r.contains(e);return a||o||(r.add({resourceId:e,data:P(e,i),persistent:!1}),a=!0),a?r.subscribe({resourceId:e,onChange:e=>n.internalState?.reloadAsyncProp(t,e),consumerId:n.id,requestId:t}):P(e,i,o)}},updateTriggers:{},visible:!0,pickable:!1,opacity:{type:"number",min:0,max:1,value:1},operation:"draw",onHover:{type:"function",value:null,optional:!0},onClick:{type:"function",value:null,optional:!0},onDragStart:{type:"function",value:null,optional:!0},onDrag:{type:"function",value:null,optional:!0},onDragEnd:{type:"function",value:null,optional:!0},coordinateSystem:"default",coordinateOrigin:{type:"array",value:[0,0,0],compare:!0},modelMatrix:{type:"array",value:null,compare:!0,optional:!0},wrapLongitude:!1,positionFormat:"XYZ",colorFormat:"RGBA",parameters:{type:"object",value:{},optional:!0,compare:2},loadOptions:{type:"object",value:null,optional:!0,ignore:!0},transitions:null,extensions:[],loaders:{type:"array",value:[],optional:!0,ignore:!0},getPolygonOffset:{type:"function",value:({layerIndex:e})=>[0,100*-e]},highlightedObjectIndex:null,autoHighlight:!1,highlightColor:{type:"accessor",value:[0,0,128,128]}},co=class extends Xi{constructor(){super(...arguments),this.internalState=null,this.lifecycle=b.NO_STATE,this.parent=null}static get componentName(){return Object.prototype.hasOwnProperty.call(this,"layerName")?this.layerName:""}get root(){let e=this;for(;e.parent;)e=e.parent;return e}toString(){return`${this.constructor.layerName||this.constructor.name}({id: '${this.props.id}'})`}project(e){h(this.internalState);const t=this.internalState.viewport||this.context.viewport,n=tt(e,{viewport:t,modelMatrix:this.props.modelMatrix,coordinateOrigin:this.props.coordinateOrigin,coordinateSystem:this.props.coordinateSystem}),[i,o,s]=C(n,t.pixelProjectionMatrix);return 2===e.length?[i,o]:[i,o,s]}unproject(e){return h(this.internalState),(this.internalState.viewport||this.context.viewport).unproject(e)}projectPosition(e,t){h(this.internalState);return function(e,t){const{viewport:n,coordinateSystem:i,coordinateOrigin:o,modelMatrix:s,fromCoordinateSystem:r,fromCoordinateOrigin:a}=function(e){const{viewport:t,modelMatrix:n,coordinateOrigin:i}=e;let{coordinateSystem:o,fromCoordinateSystem:s,fromCoordinateOrigin:r}=e;return"default"===o&&(o=t.isGeospatial?"lnglat":"cartesian"),void 0===s?s=o:"default"===s&&(s=t.isGeospatial?"lnglat":"cartesian"),void 0===r&&(r=i),{viewport:t,coordinateSystem:o,coordinateOrigin:i,modelMatrix:n,fromCoordinateSystem:s,fromCoordinateOrigin:r}}(t),{autoOffset:l=!0}=t,{geospatialOrigin:u=Qe,shaderCoordinateOrigin:f=Qe,offsetMode:d=!1}=l?c(n,i,o):{},p=tt(e,{viewport:n,modelMatrix:s,coordinateSystem:r,coordinateOrigin:a,offsetMode:d});if(d){const e=n.projectPosition(u||f);x(p,p,e)}return p}(e,{viewport:this.internalState.viewport||this.context.viewport,modelMatrix:this.props.modelMatrix,coordinateOrigin:this.props.coordinateOrigin,coordinateSystem:this.props.coordinateSystem,...t})}get isComposite(){return!1}get isDrawable(){return!0}setState(e){this.setChangeFlags({stateChanged:!0}),Object.assign(this.state,e),this.setNeedsRedraw()}setNeedsRedraw(){this.internalState&&(this.internalState.needsRedraw=!0)}setNeedsUpdate(){this.internalState&&(this.context.layerManager.setNeedsUpdate(String(this)),this.internalState.needsUpdate=!0)}get isLoaded(){return!!this.internalState&&!this.internalState.isAsyncPropLoading()}get wrapLongitude(){return this.props.wrapLongitude}isPickable(){return this.props.pickable&&this.props.visible}getModels(){const e=this.state;return e&&(e.models||e.model&&[e.model])||[]}setShaderModuleProps(...e){for(const t of this.getModels())t.shaderInputs.setProps(...e)}getAttributeManager(){return this.internalState&&this.internalState.attributeManager}getCurrentLayer(){return this.internalState&&this.internalState.layer}getLoadOptions(){return this.props.loadOptions}use64bitPositions(){const{coordinateSystem:e}=this.props;return"default"===e||"lnglat"===e||"cartesian"===e}onHover(e,t){return this.props.onHover&&this.props.onHover(e,t)||!1}onClick(e,t){return this.props.onClick&&this.props.onClick(e,t)||!1}nullPickingColor(){return[0,0,0]}encodePickingColor(e,t=[]){return t[0]=e+1&255,t[1]=e+1>>8&255,t[2]=e+1>>8>>8&255,t}decodePickingColor(e){h(e instanceof Uint8Array);const[t,n,i]=e;return t+256*n+65536*i-1}getNumInstances(){return Number.isFinite(this.props.numInstances)?this.props.numInstances:this.state&&void 0!==this.state.numInstances?this.state.numInstances:ki(this.props.data)}getStartIndices(){return this.props.startIndices?this.props.startIndices:this.state&&this.state.startIndices?this.state.startIndices:null}getBounds(){return this.getAttributeManager()?.getBounds(["positions","instancePositions"])}getShaders(e){e=Fi(e,{disableWarnings:!0,modules:this.context.defaultShaderModules});for(const t of this.props.extensions)e=Fi(e,t.getShaders.call(this,t));return e}shouldUpdateState(e){return e.changeFlags.propsOrDataChanged}updateState(e){const t=this.getAttributeManager(),{dataChanged:n}=e.changeFlags;if(n&&t)if(Array.isArray(n))for(const i of n)t.invalidateAll(i);else t.invalidateAll();if(t){const{props:n}=e,i=this.internalState.hasPickingBuffer,o=Number.isInteger(n.highlightedObjectIndex)||Boolean(n.pickable)||n.extensions.some(e=>e.getNeedsPickingBuffer.call(this,e));if(i!==o){this.internalState.hasPickingBuffer=o;const e=so(t.attributes);e&&(o&&e.constant&&(e.constant=!1,t.invalidate(e.id)),e.value||o||(e.constant=!0,e.value=ro(t.attributes)?[qe]:[0,0,0]))}}}finalizeState(e){for(const n of this.getModels())n.destroy();const t=this.getAttributeManager();t&&t.finalize(),this.context&&this.context.resourceManager.unsubscribe({consumerId:this.id}),this.internalState&&(this.internalState.uniformTransitions.clear(),this.internalState.finalize())}draw(e){for(const t of this.getModels())t.draw(e.renderPass)}getPickingInfo({info:e,mode:t,sourceLayer:n}){const{index:i}=e;return i>=0&&Array.isArray(this.props.data)&&(e.object=this.props.data[i]),e}raiseError(e,t){t&&(e=new Error(`${t}: ${e.message}`,{cause:e})),this.props.onError?.(e)||this.context?.onError?.(e,this)}getNeedsRedraw(e={clearRedrawFlags:!1}){return this._getNeedsRedraw(e)}needsUpdate(){return!!this.internalState&&(this.internalState.needsUpdate||this.hasUniformTransition()||this.shouldUpdateState(this._getUpdateParams()))}hasUniformTransition(){return this.internalState?.uniformTransitions.active||!1}activateViewport(e){if(!this.internalState)return;const t=this.internalState.viewport;this.internalState.viewport=e,t&&io({oldViewport:t,viewport:e})||(this.setChangeFlags({viewportChanged:!0}),this.isComposite?this.needsUpdate()&&this.setNeedsUpdate():this._update())}invalidateAttribute(e="all"){const t=this.getAttributeManager();t&&("all"===e?t.invalidateAll():t.invalidate(e))}updateAttributes(e){let t=!1;for(const n in e)e[n].layoutChanged()&&(t=!0);for(const n of this.getModels())this._setModelAttributes(n,e,t)}_updateAttributes(){const e=this.getAttributeManager();if(!e)return;const t=this.props,n=this.getNumInstances(),i=this.getStartIndices();e.update({data:t.data,numInstances:n,startIndices:i,props:t,transitions:t.transitions,buffers:t.data.attributes,context:this});const o=e.getChangedAttributes({clearChangedFlags:!0});this.updateAttributes(o)}_updateAttributeTransition(){const e=this.getAttributeManager();e&&e.updateTransition()}_updateUniformTransition(){const{uniformTransitions:e}=this.internalState;if(e.active){const t=e.update(),n=Object.create(this.props);for(const e in t)Object.defineProperty(n,e,{value:t[e]});return n}return this.props}calculateInstancePickingColors(e,{numInstances:t}){if(e.constant)return;const n=Math.floor(oo.length/4);this.internalState.usesPickingColorCache=!0;const i=t>0&&0===oo[0];if(n<t||i){t>to&&I.warn("Layer has too many data objects. Picking might not be able to distinguish all objects.")(),oo=f.allocate(oo,t,{size:4,copy:!0,maxCount:Math.max(t,to)});const e=Math.floor(oo.length/4),o=[0,0,0];for(let t=i?0:n;t<e;t++)this.encodePickingColor(t,o),oo[4*t+0]=o[0],oo[4*t+1]=o[1],oo[4*t+2]=o[2],oo[4*t+3]=0}e.value=oo.subarray(0,4*t)}_setModelAttributes(e,t,n=!1){if(!Object.keys(t).length)return;const i=this.getAttributeManager();if(i?.hasBufferGroups())return void this._setGroupedModelAttributes(e,i,t);if(n){const n=this.getAttributeManager();e.setBufferLayout(n.getBufferLayouts(e)),t=n.getAttributes()}const o=e.userData?.excludeAttributes||{},s={},r={};for(const a in t){if(o[a])continue;const n=t[a].getValue();for(const i in n){const o=n[i];o instanceof U?t[a].settings.isIndexed?e.setIndexBuffer(o):s[i]=o:o&&(r[i]=o)}}e.setAttributes(s),e.setConstantAttributes(r)}_setGroupedModelAttributes(e,t,n){const i=e.userData?.excludeAttributes||{},o=t.getBufferGroupBindings(n,e,i);e.setBufferLayout(o.bufferLayouts);const s={...o.buffers},r={},a=t.getAttributes();for(const l in a){if(i[l]||o.groupedAttributeIds.has(l))continue;const t=a[l],n=t.getValue();for(const i in n){const o=n[i];o instanceof U?t.settings.isIndexed?e.setIndexBuffer(o):s[i]=o:o&&(r[i]=o)}}e.setAttributes(s),e.setConstantAttributes(r)}disablePickingIndex(e){const t=this.props.data;if(!("attributes"in t))return void this._disablePickingIndex(e);const n=this.getAttributeManager().attributes,i=ro(n),o=ao(n),s=i&&t.attributes&&t.attributes[i.id];if(s&&s.value){const n=s.value;for(let o=0;o<t.length;o++)n[i.getVertexOffset(o)]===e&&this._disablePickingIndex(o);return}const r=o&&t.attributes&&t.attributes[o.id];if(r&&r.value){const n=r.value,i=this.encodePickingColor(e);for(let e=0;e<t.length;e++){const t=o.getVertexOffset(e);n[t]===i[0]&&n[t+1]===i[1]&&n[t+2]===i[2]&&this._disablePickingIndex(e)}}else this._disablePickingIndex(e)}_disablePickingIndex(e){const t=this.getAttributeManager().attributes,n=ro(t);if(n){const t=n.getVertexOffset(e),i=n.getVertexOffset(e+1),o=new Uint32Array(i-t);return o.fill(qe),void n.buffer.write(o,t*o.BYTES_PER_ELEMENT)}const i=ao(t);if(!i)return void(this.internalState&&function(e,t){10===e.length?I.warn("pickMultipleObjects can only exclude 10 previously picked objects for layers without picking buffers")():e.push(t)}(this.internalState.disabledPickingIndices,e));const o=i.getVertexOffset(e),s=i.getVertexOffset(e+1);i.buffer.write(new Uint8Array(s-o),o)}restorePickingColors(){const e=this.getAttributeManager().attributes,t=so(e);if(!t)return void(this.internalState&&(this.internalState.disabledPickingIndices.length=0));const n=ao(e);this.internalState.usesPickingColorCache&&n&&n.value.buffer!==oo.buffer&&(n.value=oo.subarray(0,n.value.length)),t.updateSubBuffer({startOffset:0})}_initialize(){h(!this.internalState),T("layer.initialize",this);const e=this._getAttributeManager();this.internalState=new eo({attributeManager:e,layer:this}),this._clearChangeFlags(),this.state={},Object.defineProperty(this.state,"attributeManager",{get:()=>(I.deprecated("layer.state.attributeManager","layer.getAttributeManager()")(),e)}),this.internalState.uniformTransitions=new Ei(this.context.timeline),this.internalState.onAsyncPropUpdated=this._onAsyncPropUpdated.bind(this),this.internalState.setAsyncProps(this.props),this.initializeState(this.context);for(const t of this.props.extensions)t.initializeState.call(this,this.context,t);this.setChangeFlags({dataChanged:"init",propsChanged:"init",viewportChanged:!0,extensionsChanged:!0}),this._update()}_transferState(e){T("layer.matched",this,this===e);const{state:t,internalState:n}=e;this!==e&&(this.internalState=n,this.state=t,this.internalState.setAsyncProps(this.props),this._diffProps(this.props,this.internalState.getOldProps()))}_update(){const e=this.needsUpdate();if(T("layer.update",this,e),!e)return;this.context.stats.get("Layer updates").incrementCount();const t=this.props,n=this.context,i=this.internalState,o=n.viewport,s=this._updateUniformTransition();i.propsInTransition=s,n.viewport=i.viewport||o,this.props=s;try{const e=this._getUpdateParams(),t=this.getModels();if(n.device)this.updateState(e);else try{this.updateState(e)}catch(r){}for(const n of this.props.extensions)n.updateState.call(this,e,n);this.setNeedsRedraw(),this._updateAttributes();const i=this.getModels()[0]!==t[0];this._postUpdate(e,i)}finally{n.viewport=o,this.props=t,this._clearChangeFlags(),i.needsUpdate=!1,i.resetOldProps()}}_finalize(){T("layer.finalize",this),this.finalizeState(this.context);for(const e of this.props.extensions)e.finalizeState.call(this,this.context,e)}_drawLayer({renderPass:e,shaderModuleProps:t=null,uniforms:n={},parameters:i={}}){this._updateAttributeTransition();const o=this.props,s=this.context;this.props=this.internalState.propsInTransition||o;try{t&&this.setShaderModuleProps(t);const{getPolygonOffset:o}=this.props,r=o&&o(n)||[0,0];s.device instanceof X&&s.device.setParametersWebGL({polygonOffset:r});const a=s.device instanceof X?null:function(e){const{blendConstant:t,...n}=e;return t?{pipelineParameters:n,renderPassParameters:{blendConstant:t}}:{pipelineParameters:n}}(i);if(function(e,t,n,i){for(const o of e)"webgpu"===o.device.type?(uo(o,t),o.setParameters({...o.parameters,...i?.pipelineParameters})):o.setParameters(n)}(this.getModels(),e,i,a),s.device instanceof X)s.device.withParametersWebGL(i,()=>{const o={renderPass:e,shaderModuleProps:t,uniforms:n,parameters:i,context:s};for(const e of this.props.extensions)e.draw.call(this,o,e);this.draw(o)});else{a?.renderPassParameters&&e.setParameters(a.renderPassParameters);const o={renderPass:e,shaderModuleProps:t,uniforms:n,parameters:i,context:s};for(const e of this.props.extensions)e.draw.call(this,o,e);this.draw(o)}}finally{this.props=o}}getChangeFlags(){return this.internalState?.changeFlags}setChangeFlags(e){if(!this.internalState)return;const{changeFlags:t}=this.internalState;for(const i in e)if(e[i]){let n=!1;if("dataChanged"===i){const o=e[i],s=t[i];o&&Array.isArray(s)&&(t.dataChanged=Array.isArray(o)?s.concat(o):o,n=!0)}t[i]||(t[i]=e[i],n=!0),n&&T("layer.changeFlag",this,i,e)}const n=Boolean(t.dataChanged||t.updateTriggersChanged||t.propsChanged||t.extensionsChanged);t.propsOrDataChanged=n,t.somethingChanged=n||t.viewportChanged||t.stateChanged}_clearChangeFlags(){this.internalState.changeFlags={dataChanged:!1,propsChanged:!1,updateTriggersChanged:!1,viewportChanged:!1,stateChanged:!1,extensionsChanged:!1,propsOrDataChanged:!1,somethingChanged:!1}}_diffProps(e,t){const n=Ti(e,t);if(n.updateTriggersChanged)for(const i in n.updateTriggersChanged)n.updateTriggersChanged[i]&&this.invalidateAttribute(i);if(n.transitionsChanged)for(const i in n.transitionsChanged)this.internalState.uniformTransitions.add(i,t[i],e[i],e.transitions?.[i]);return this.setChangeFlags(n)}validateProps(){!function(e){const t=e[y];for(const n in t){const i=t[n],{validate:o}=i;if(o&&!o(e[n],i))throw new Error(`Invalid prop ${n}: ${e[n]}`)}}(this.props)}updateAutoHighlight(e){this.props.autoHighlight&&!Number.isInteger(this.props.highlightedObjectIndex)&&this._updateAutoHighlight(e)}_updateAutoHighlight(e){const t={highlightedObjectColor:e.picked?e.color:null},{highlightColor:n}=this.props;e.picked&&"function"==typeof n&&(t.highlightColor=n(e)),this.setShaderModuleProps({picking:t}),this.setNeedsRedraw()}_getAttributeManager(){const e=this.context;return new wi(e.device,{id:this.props.id,stats:e.stats,timeline:e.timeline})}_postUpdate(e,t){const{props:n,oldProps:i}=e,o=this.state.model;o?.isInstanced&&o.setInstanceCount(this.getNumInstances());const{autoHighlight:s,highlightedObjectIndex:r,highlightColor:a}=n;if(t||i.autoHighlight!==s||i.highlightedObjectIndex!==r||i.highlightColor!==a){const e={};Array.isArray(a)&&(e.highlightColor=a),(t||i.autoHighlight!==s||r!==i.highlightedObjectIndex)&&(e.highlightedObjectColor=Number.isFinite(r)&&r>=0?this.encodePickingColor(r):null),this.setShaderModuleProps({picking:e})}}_getUpdateParams(){return{props:this.props,oldProps:this.internalState.getOldProps(),context:this.context,changeFlags:this.internalState.changeFlags}}_getNeedsRedraw(e){if(!this.internalState)return!1;let t=!1;t=t||this.internalState.needsRedraw&&this.id;const n=this.getAttributeManager(),i=!!n&&n.getNeedsRedraw(e);if(t=t||i,t)for(const o of this.props.extensions)o.onNeedsRedraw.call(this,o);return this.internalState.needsRedraw=this.internalState.needsRedraw&&!e.clearRedrawFlags,t}_onAsyncPropUpdated(){this._diffProps(this.props,this.internalState.getOldProps()),this.setNeedsUpdate()}};function uo(e,t){const n=t.props.framebuffer||(t.framebuffer??null);if(!n)return;const i=n.colorAttachments.map(e=>e?.texture?.format??null),o=n.depthStencilAttachment?.texture?.format,s=e;(function(e,t){if(e===t)return!0;if(!e||!t||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0})(s.props.colorAttachmentFormats,i)&&s.props.depthStencilAttachmentFormat===o||(s.props.colorAttachmentFormats=i,s.props.depthStencilAttachmentFormat=o,s._setPipelineNeedsUpdate("attachment formats"))}co.defaultProps=lo,co.layerName="Layer";var fo=class extends co{get isComposite(){return!0}get isDrawable(){return!1}get isLoaded(){return super.isLoaded&&this.getSubLayers().every(e=>e.isLoaded)}getSubLayers(){return this.internalState&&this.internalState.subLayers||[]}initializeState(e){}setState(e){super.setState(e),this.setNeedsUpdate()}getPickingInfo({info:e}){const{object:t}=e;return t&&t.__source&&t.__source.parent&&t.__source.parent.id===this.id?(e.object=t.__source.object,e.index=t.__source.index,e):e}filterSubLayer(e){return!0}shouldRenderSubLayer(e,t){return t&&t.length}getSubLayerClass(e,t){const{_subLayerProps:n}=this.props;return n&&n[e]&&n[e].type||t}getSubLayerRow(e,t,n){return e.__source={parent:this,object:t,index:n},e}getSubLayerAccessor(e){if("function"==typeof e){const t={index:-1,data:this.props.data,target:[]};return(n,i)=>n&&n.__source?(t.index=n.__source.index,e(n.__source.object,t)):e(n,i)}return e}getSubLayerProps(e={}){const{opacity:t,pickable:n,visible:i,parameters:o,getPolygonOffset:s,highlightedObjectIndex:r,autoHighlight:a,highlightColor:l,coordinateSystem:c,coordinateOrigin:u,wrapLongitude:f,positionFormat:d,modelMatrix:p,extensions:g,fetch:h,operation:v,_subLayerProps:m}=this.props,_={id:"",updateTriggers:{},opacity:t,pickable:n,visible:i,parameters:o,getPolygonOffset:s,highlightedObjectIndex:r,autoHighlight:a,highlightColor:l,coordinateSystem:c,coordinateOrigin:u,wrapLongitude:f,positionFormat:d,modelMatrix:p,extensions:g,fetch:h,operation:v},x=m&&e.id&&m[e.id],b=x&&x.updateTriggers,P=e.id||"sublayer";if(x){const t=this.props[y],n=e.type?e.type._propTypes:{};for(const e in x){const i=n[e]||t[e];i&&"accessor"===i.type&&(x[e]=this.getSubLayerAccessor(x[e]))}}Object.assign(_,e,x),_.id=`${this.props.id}-${P}`,_.updateTriggers={all:this.props.updateTriggers?.all,...e.updateTriggers,...b};for(const y of g){const e=y.getSubLayerProps.call(this,y);e&&Object.assign(_,e,{updateTriggers:Object.assign(_.updateTriggers,e.updateTriggers)})}return _}_updateAutoHighlight(e){for(const t of this.getSubLayers())t.updateAutoHighlight(e)}_getAttributeManager(){return null}_postUpdate(e,t){let n=this.internalState.subLayers;const i=!n||this.needsUpdate();if(i){const e=this.renderLayers();n=w(e,Boolean),this.internalState.subLayers=n}T("compositeLayer.renderLayers",this,i,n);for(const o of n)o.parent=this}};fo.layerName="CompositeLayer";var po=class{constructor(e){this.indexStarts=[0],this.vertexStarts=[0],this.vertexCount=0,this.instanceCount=0;const{attributes:t={}}=e;this.typedArrayManager=f,this.attributes={},this._attributeDefs=t,this.opts=e,this.updateGeometry(e)}updateGeometry(e){Object.assign(this.opts,e);const{data:t,buffers:n={},getGeometry:i,geometryBuffer:o,positionFormat:s,dataChanged:r,normalize:a=!0}=this.opts;if(this.data=t,this.getGeometry=i,this.positionSize=o&&o.size||("XY"===s?2:3),this.buffers=n,this.normalize=a,o&&(h(t.startIndices),this.getGeometry=this.getGeometryFromBuffer(o),a||(n.vertexPositions=o)),this.geometryBuffer=n.vertexPositions,Array.isArray(r))for(const l of r)this._rebuildGeometry(l);else this._rebuildGeometry()}updatePartialGeometry({startRow:e,endRow:t}){this._rebuildGeometry({startRow:e,endRow:t})}getGeometryFromBuffer(e){const t=e.value||e;return ArrayBuffer.isView(t)?Ht(t,{size:this.positionSize,offset:e.offset,stride:e.stride,startIndices:this.data.startIndices}):null}_allocate(e,t){const{attributes:n,buffers:i,_attributeDefs:o,typedArrayManager:s}=this;for(const r in o)if(r in i)s.release(n[r]),n[r]=null;else{const i=o[r];i.copy=t,n[r]=s.allocate(n[r],e,i)}}_forEachGeometry(e,t,n){const{data:i,getGeometry:o}=this,{iterable:s,objectInfo:r}=$t(i,t,n);for(const a of s)r.index++,e(o?o(a,r):null,r.index)}_rebuildGeometry(e){if(!this.data)return;let{indexStarts:t,vertexStarts:n,instanceCount:i}=this;const{data:o,geometryBuffer:s}=this,{startRow:r=0,endRow:a=1/0}=e||{},l={};if(e||(t=[0],n=[0]),this.normalize||!s)this._forEachGeometry((e,t)=>{const i=e&&this.normalizeGeometry(e);l[t]=i,n[t+1]=n[t]+(i?this.getGeometrySize(i):0)},r,a),i=n[n.length-1];else if(n=o.startIndices,i=n[o.length]||0,ArrayBuffer.isView(s))i=i||s.length/this.positionSize;else if(s instanceof U){const e=4*this.positionSize;i=i||s.byteLength/e}else if(s.buffer){const e=s.stride||4*this.positionSize;i=i||s.buffer.byteLength/e}else if(s.value){const e=s.value,t=s.stride/e.BYTES_PER_ELEMENT||this.positionSize;i=i||e.length/t}this._allocate(i,Boolean(e)),this.indexStarts=t,this.vertexStarts=n,this.instanceCount=i;const c={};this._forEachGeometry((e,o)=>{const s=l[o]||e;c.vertexStart=n[o],c.indexStart=t[o];const r=o<n.length-1?n[o+1]:i;c.geometrySize=r-n[o],c.geometryIndex=o,this.updateGeometryAttributes(s,c)},r,a),this.vertexCount=t[t.length-1]}},go="layout(std140) uniform arcUniforms {\n bool greatCircle;\n bool useShortestPath;\n float numSegments;\n float widthScale;\n float widthMinPixels;\n float widthMaxPixels;\n highp int widthUnits;\n} arc;\n",ho={name:"arc",source:"struct ArcUniforms {\n greatCircle: f32,\n useShortestPath: f32,\n numSegments: f32,\n widthScale: f32,\n widthMinPixels: f32,\n widthMaxPixels: f32,\n widthUnits: i32,\n};\n\n@group(0) @binding(auto) var<uniform> arc: ArcUniforms;\n",vs:go,fs:go,uniformTypes:{greatCircle:"f32",useShortestPath:"f32",numSegments:"f32",widthScale:"f32",widthMinPixels:"f32",widthMaxPixels:"f32",widthUnits:"i32"}},vo=[0,0,0,255],mo={getSourcePosition:{type:"accessor",value:e=>e.sourcePosition},getTargetPosition:{type:"accessor",value:e=>e.targetPosition},getSourceColor:{type:"accessor",value:vo},getTargetColor:{type:"accessor",value:vo},getWidth:{type:"accessor",value:1},getHeight:{type:"accessor",value:1},getTilt:{type:"accessor",value:0},greatCircle:!1,numSegments:{type:"number",value:50,min:1},widthUnits:"pixels",widthScale:{type:"number",value:1,min:0},widthMinPixels:{type:"number",value:0,min:0},widthMaxPixels:{type:"number",value:Number.MAX_SAFE_INTEGER,min:0},antialiasing:!1},_o=class extends co{getBounds(){return this.getAttributeManager()?.getBounds(["instanceSourcePositions","instanceTargetPositions"])}getShaders(){const{antialiasing:e}=this.props;return super.getShaders({vs:"#version 300 es\n#define SHADER_NAME arc-layer-vertex-shader\nin vec4 instanceSourceColors;\nin vec4 instanceTargetColors;\nin vec3 instanceSourcePositions;\nin vec3 instanceSourcePositions64Low;\nin vec3 instanceTargetPositions;\nin vec3 instanceTargetPositions64Low;\nin float instanceWidths;\nin float instanceHeights;\nin float instanceTilts;\nout vec4 vColor;\nout vec2 uv;\nout float isValid;\nfloat paraboloid(float distance, float sourceZ, float targetZ, float ratio) {\nfloat deltaZ = targetZ - sourceZ;\nfloat dh = distance * instanceHeights;\nif (dh == 0.0) {\nreturn sourceZ + deltaZ * ratio;\n}\nfloat unitZ = deltaZ / dh;\nfloat p2 = unitZ * unitZ + 1.0;\nfloat dir = step(deltaZ, 0.0);\nfloat z0 = mix(sourceZ, targetZ, dir);\nfloat r = mix(ratio, 1.0 - ratio, dir);\nreturn sqrt(r * (p2 - r)) * dh + z0;\n}\nvec2 getExtrusionOffset(vec2 line_clipspace, float offset_direction, float width) {\nvec2 dir_screenspace = normalize(line_clipspace * project.viewportSize);\ndir_screenspace = vec2(-dir_screenspace.y, dir_screenspace.x);\nreturn dir_screenspace * offset_direction * width / 2.0;\n}\nfloat getSegmentRatio(float index) {\nreturn smoothstep(0.0, 1.0, index / (arc.numSegments - 1.0));\n}\nvec3 interpolateFlat(vec3 source, vec3 target, float segmentRatio) {\nfloat distance = length(source.xy - target.xy);\nfloat z = paraboloid(distance, source.z, target.z, segmentRatio);\nfloat tiltAngle = radians(instanceTilts);\nvec2 tiltDirection = normalize(target.xy - source.xy);\nvec2 tilt = vec2(-tiltDirection.y, tiltDirection.x) * z * sin(tiltAngle);\nreturn vec3(\nmix(source.xy, target.xy, segmentRatio) + tilt,\nz * cos(tiltAngle)\n);\n}\nfloat getAngularDist (vec2 source, vec2 target) {\nvec2 sourceRadians = radians(source);\nvec2 targetRadians = radians(target);\nvec2 sin_half_delta = sin((sourceRadians - targetRadians) / 2.0);\nvec2 shd_sq = sin_half_delta * sin_half_delta;\nfloat a = shd_sq.y + cos(sourceRadians.y) * cos(targetRadians.y) * shd_sq.x;\nreturn 2.0 * asin(sqrt(a));\n}\nvec3 interpolateGreatCircle(vec3 source, vec3 target, vec3 source3D, vec3 target3D, float angularDist, float t) {\nvec2 lngLat;\nif(abs(angularDist - PI) < 0.001) {\nlngLat = (1.0 - t) * source.xy + t * target.xy;\n} else {\nfloat a = sin((1.0 - t) * angularDist);\nfloat b = sin(t * angularDist);\nvec3 p = source3D.yxz * a + target3D.yxz * b;\nlngLat = degrees(vec2(atan(p.y, -p.x), atan(p.z, length(p.xy))));\n}\nfloat z = paraboloid(angularDist * EARTH_RADIUS, source.z, target.z, t);\nreturn vec3(lngLat, z);\n}\nvoid main(void) {\ngeometry.worldPosition = instanceSourcePositions;\ngeometry.worldPositionAlt = instanceTargetPositions;\nfloat segmentIndex = float(gl_VertexID / 2);\nfloat segmentSide = mod(float(gl_VertexID), 2.) == 0. ? -1. : 1.;\nfloat segmentRatio = getSegmentRatio(segmentIndex);\nfloat prevSegmentRatio = getSegmentRatio(max(0.0, segmentIndex - 1.0));\nfloat nextSegmentRatio = getSegmentRatio(min(arc.numSegments - 1.0, segmentIndex + 1.0));\nfloat indexDir = mix(-1.0, 1.0, step(segmentIndex, 0.0));\nisValid = 1.0;\nuv = vec2(segmentRatio, segmentSide);\ngeometry.uv = uv;\ngeometry.pickingColor = picking_getPickingColorFromInstanceID();\nvec4 curr;\nvec4 next;\nvec3 source;\nvec3 target;\nif ((arc.greatCircle || project.projectionMode == PROJECTION_MODE_GLOBE) && project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT) {\nsource = project_globe_(vec3(instanceSourcePositions.xy, 0.0));\ntarget = project_globe_(vec3(instanceTargetPositions.xy, 0.0));\nfloat angularDist = getAngularDist(instanceSourcePositions.xy, instanceTargetPositions.xy);\nvec3 prevPos = interpolateGreatCircle(instanceSourcePositions, instanceTargetPositions, source, target, angularDist, prevSegmentRatio);\nvec3 currPos = interpolateGreatCircle(instanceSourcePositions, instanceTargetPositions, source, target, angularDist, segmentRatio);\nvec3 nextPos = interpolateGreatCircle(instanceSourcePositions, instanceTargetPositions, source, target, angularDist, nextSegmentRatio);\nif (abs(currPos.x - prevPos.x) > 180.0) {\nindexDir = -1.0;\nisValid = 0.0;\n} else if (abs(currPos.x - nextPos.x) > 180.0) {\nindexDir = 1.0;\nisValid = 0.0;\n}\nnextPos = indexDir < 0.0 ? prevPos : nextPos;\nnextSegmentRatio = indexDir < 0.0 ? prevSegmentRatio : nextSegmentRatio;\nif (isValid == 0.0) {\nnextPos.x += nextPos.x > 0.0 ? -360.0 : 360.0;\nfloat t = ((currPos.x > 0.0 ? 180.0 : -180.0) - currPos.x) / (nextPos.x - currPos.x);\ncurrPos = mix(currPos, nextPos, t);\nsegmentRatio = mix(segmentRatio, nextSegmentRatio, t);\n}\nvec3 currPos64Low = mix(instanceSourcePositions64Low, instanceTargetPositions64Low, segmentRatio);\nvec3 nextPos64Low = mix(instanceSourcePositions64Low, instanceTargetPositions64Low, nextSegmentRatio);\ncurr = project_position_to_clipspace(currPos, currPos64Low, vec3(0.0), geometry.position);\nnext = project_position_to_clipspace(nextPos, nextPos64Low, vec3(0.0));\n} else {\nvec3 source_world = instanceSourcePositions;\nvec3 target_world = instanceTargetPositions;\nif (arc.useShortestPath) {\nsource_world.x = mod(source_world.x + 180., 360.0) - 180.;\ntarget_world.x = mod(target_world.x + 180., 360.0) - 180.;\nfloat deltaLng = target_world.x - source_world.x;\nif (deltaLng > 180.) target_world.x -= 360.;\nif (deltaLng < -180.) source_world.x -= 360.;\n}\nsource = project_position(source_world, instanceSourcePositions64Low);\ntarget = project_position(target_world, instanceTargetPositions64Low);\nfloat antiMeridianX = 0.0;\nif (arc.useShortestPath) {\nif (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR_AUTO_OFFSET) {\nantiMeridianX = -(project.coordinateOrigin.x + 180.) / 360. * TILE_SIZE;\n}\nfloat thresholdRatio = (antiMeridianX - source.x) / (target.x - source.x);\nif (prevSegmentRatio <= thresholdRatio && nextSegmentRatio > thresholdRatio) {\nisValid = 0.0;\nindexDir = sign(segmentRatio - thresholdRatio);\nsegmentRatio = thresholdRatio;\n}\n}\nnextSegmentRatio = indexDir < 0.0 ? prevSegmentRatio : nextSegmentRatio;\nvec3 currPos = interpolateFlat(source, target, segmentRatio);\nvec3 nextPos = interpolateFlat(source, target, nextSegmentRatio);\nif (arc.useShortestPath) {\nif (nextPos.x < antiMeridianX) {\ncurrPos.x += TILE_SIZE;\nnextPos.x += TILE_SIZE;\n}\n}\ncurr = project_common_position_to_clipspace(vec4(currPos, 1.0));\nnext = project_common_position_to_clipspace(vec4(nextPos, 1.0));\ngeometry.position = vec4(currPos, 1.0);\n}\nfloat widthPixels = clamp(\nproject_size_to_pixel(instanceWidths * arc.widthScale, arc.widthUnits),\narc.widthMinPixels, arc.widthMaxPixels\n);\nvec3 offset = vec3(\ngetExtrusionOffset((next.xy - curr.xy) * indexDir, segmentSide, widthPixels),\n0.0);\nDECKGL_FILTER_SIZE(offset, geometry);\n#ifdef ANTIALIASING\nfloat halfWidthPixels = length(offset.xy);\nif (halfWidthPixels > 0.0) {\nfloat coverageScale = 1.0 + 0.5 / project.devicePixelRatio / halfWidthPixels;\noffset.xy *= coverageScale;\nuv.y *= coverageScale;\n}\ngeometry.uv = uv;\n#endif\nDECKGL_FILTER_GL_POSITION(curr, geometry);\ngl_Position = curr + vec4(project_pixel_size_to_clipspace(offset.xy), 0.0, 0.0);\nvec4 color = mix(instanceSourceColors, instanceTargetColors, segmentRatio);\nvColor = vec4(color.rgb, color.a * layer.opacity);\nDECKGL_FILTER_COLOR(vColor, geometry);\n}\n",fs:"#version 300 es\n#define SHADER_NAME arc-layer-fragment-shader\nprecision highp float;\nin vec4 vColor;\nin vec2 uv;\nin float isValid;\nout vec4 fragColor;\nvoid main(void) {\n#ifdef ANTIALIASING\nfloat edgeCoord = abs(uv.y);\nfloat edgePixels = (1.0 - edgeCoord) / max(fwidth(edgeCoord), 1e-6);\n#endif\nif (isValid == 0.0) {\ndiscard;\n}\n#ifdef ANTIALIASING\nif (edgePixels <= -SMOOTH_EDGE_RADIUS) {\ndiscard;\n}\n#endif\nfragColor = vColor;\ngeometry.uv = uv;\n#ifdef ANTIALIASING\nfragColor.a *= smoothedge(0.0, edgePixels);\n#endif\nDECKGL_FILTER_COLOR(fragColor, geometry);\n}\n",source:"const ZERO_OFFSET: vec3<f32> = vec3<f32>(0.0, 0.0, 0.0);\n\nstruct Attributes {\n @location(0) instanceSourcePositions: vec3<f32>,\n @location(1) instanceSourcePositions64Low: vec3<f32>,\n @location(2) instanceTargetPositions: vec3<f32>,\n @location(3) instanceTargetPositions64Low: vec3<f32>,\n @location(4) instanceSourceColors: vec4<f32>,\n @location(5) instanceTargetColors: vec4<f32>,\n @location(6) instanceWidths: f32,\n @location(7) instanceHeights: f32,\n @location(8) instanceTilts: f32,\n};\n\nstruct Varyings {\n @builtin(position) position: vec4<f32>,\n @location(0) color: vec4<f32>,\n @location(1) uv: vec2<f32>,\n @location(2) pickingColor: vec3<f32>,\n @location(3) isValid: f32,\n};\n\nfn paraboloid(\n distance: f32,\n sourceZ: f32,\n targetZ: f32,\n ratio: f32,\n height: f32\n) -> f32 {\n let deltaZ = targetZ - sourceZ;\n let dh = distance * height;\n if (dh == 0.0) {\n return sourceZ + deltaZ * ratio;\n }\n let unitZ = deltaZ / dh;\n let p2 = unitZ * unitZ + 1.0;\n let dir = select(0.0, 1.0, deltaZ <= 0.0);\n let z0 = mix(sourceZ, targetZ, dir);\n let r = mix(ratio, 1.0 - ratio, dir);\n return sqrt(max(r * (p2 - r), 0.0)) * dh + z0;\n}\n\nfn getExtrusionOffset(lineClipspace: vec2<f32>, side: f32, width: f32) -> vec2<f32> {\n var direction = normalize(lineClipspace * project.viewportSize);\n direction = vec2<f32>(-direction.y, direction.x);\n return direction * side * width / 2.0;\n}\n\nfn getSegmentRatio(index: f32) -> f32 {\n return smoothstep(0.0, 1.0, index / max(arc.numSegments - 1.0, 1.0));\n}\n\nfn interpolateFlat(\n source: vec3<f32>,\n targetPosition: vec3<f32>,\n ratio: f32,\n height: f32,\n tiltDegrees: f32\n) -> vec3<f32> {\n let distance = length(source.xy - targetPosition.xy);\n let z = paraboloid(distance, source.z, targetPosition.z, ratio, height);\n let tiltAngle = radians(tiltDegrees);\n let tiltDirection = normalize(targetPosition.xy - source.xy);\n let tilt = vec2<f32>(-tiltDirection.y, tiltDirection.x) * z * sin(tiltAngle);\n return vec3<f32>(mix(source.xy, targetPosition.xy, ratio) + tilt, z * cos(tiltAngle));\n}\n\n// Great circle interpolation\n// http://www.movable-type.co.uk/scripts/latlong.html\nfn getAngularDistance(source: vec2<f32>, targetPosition: vec2<f32>) -> f32 {\n let sourceRadians = radians(source);\n let targetRadians = radians(targetPosition);\n let sinHalfDelta = sin((sourceRadians - targetRadians) / 2.0);\n let sinHalfDeltaSquared = sinHalfDelta * sinHalfDelta;\n let a = sinHalfDeltaSquared.y +\n cos(sourceRadians.y) * cos(targetRadians.y) * sinHalfDeltaSquared.x;\n return 2.0 * asin(sqrt(a));\n}\n\nfn interpolateGreatCircle(\n source: vec3<f32>,\n targetPosition: vec3<f32>,\n source3D: vec3<f32>,\n target3D: vec3<f32>,\n angularDistance: f32,\n ratio: f32,\n height: f32\n) -> vec3<f32> {\n var longitudeLatitude: vec2<f32>;\n\n // If the angular distance is PI, use linear interpolation. Otherwise use spherical interpolation.\n if (abs(angularDistance - PI) < 0.001) {\n longitudeLatitude = (1.0 - ratio) * source.xy + ratio * targetPosition.xy;\n } else {\n let a = sin((1.0 - ratio) * angularDistance);\n let b = sin(ratio * angularDistance);\n let p = source3D.yxz * a + target3D.yxz * b;\n longitudeLatitude = degrees(vec2<f32>(\n atan2(p.y, -p.x),\n atan2(p.z, length(p.xy))\n ));\n }\n\n let z = paraboloid(\n angularDistance * EARTH_RADIUS,\n source.z,\n targetPosition.z,\n ratio,\n height\n );\n return vec3<f32>(longitudeLatitude, z);\n}\n\n@vertex\nfn vertexMain(\n attributes: Attributes,\n @builtin(vertex_index) vertexIndex: u32,\n @builtin(instance_index) instanceIndex: u32\n) -> Varyings {\n geometry.worldPosition = attributes.instanceSourcePositions;\n geometry.worldPositionAlt = attributes.instanceTargetPositions;\n\n let segmentIndex = f32(vertexIndex / 2u);\n let segmentSide = select(-1.0, 1.0, vertexIndex % 2u == 1u);\n var segmentRatio = getSegmentRatio(segmentIndex);\n let previousRatio = getSegmentRatio(max(0.0, segmentIndex - 1.0));\n var nextRatio = getSegmentRatio(min(arc.numSegments - 1.0, segmentIndex + 1.0));\n // If this is the first point, use next - current as direction.\n var indexDirection = select(-1.0, 1.0, segmentIndex <= 0.0);\n var isValid = 1.0;\n\n var currentClip: vec4<f32>;\n var nextClip: vec4<f32>;\n\n if (\n (arc.greatCircle != 0.0 || project.projectionMode == PROJECTION_MODE_GLOBE) &&\n project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT\n ) {\n let source = project_globe_(vec3<f32>(attributes.instanceSourcePositions.xy, 0.0));\n let targetPosition = project_globe_(vec3<f32>(attributes.instanceTargetPositions.xy, 0.0));\n let angularDistance = getAngularDistance(\n attributes.instanceSourcePositions.xy,\n attributes.instanceTargetPositions.xy\n );\n\n let previousPosition = interpolateGreatCircle(\n attributes.instanceSourcePositions,\n attributes.instanceTargetPositions,\n source,\n targetPosition,\n angularDistance,\n previousRatio,\n attributes.instanceHeights\n );\n var currentPosition = interpolateGreatCircle(\n attributes.instanceSourcePositions,\n attributes.instanceTargetPositions,\n source,\n targetPosition,\n angularDistance,\n segmentRatio,\n attributes.instanceHeights\n );\n var nextPosition = interpolateGreatCircle(\n attributes.instanceSourcePositions,\n attributes.instanceTargetPositions,\n source,\n targetPosition,\n angularDistance,\n nextRatio,\n attributes.instanceHeights\n );\n\n if (abs(currentPosition.x - previousPosition.x) > 180.0) {\n indexDirection = -1.0;\n isValid = 0.0;\n } else if (abs(currentPosition.x - nextPosition.x) > 180.0) {\n indexDirection = 1.0;\n isValid = 0.0;\n }\n nextPosition = select(nextPosition, previousPosition, indexDirection < 0.0);\n nextRatio = select(nextRatio, previousRatio, indexDirection < 0.0);\n\n if (isValid == 0.0) {\n // Split at the antimeridian.\n nextPosition.x += select(360.0, -360.0, nextPosition.x > 0.0);\n let ratio = (\n select(-180.0, 180.0, currentPosition.x > 0.0) - currentPosition.x\n ) / (nextPosition.x - currentPosition.x);\n currentPosition = mix(currentPosition, nextPosition, ratio);\n segmentRatio = mix(segmentRatio, nextRatio, ratio);\n }\n\n let currentPosition64Low = mix(\n attributes.instanceSourcePositions64Low,\n attributes.instanceTargetPositions64Low,\n segmentRatio\n );\n let nextPosition64Low = mix(\n attributes.instanceSourcePositions64Low,\n attributes.instanceTargetPositions64Low,\n nextRatio\n );\n let currentProjection = project_position_to_clipspace_and_commonspace(\n currentPosition,\n currentPosition64Low,\n ZERO_OFFSET\n );\n currentClip = currentProjection.clipPosition;\n nextClip = project_position_to_clipspace(nextPosition, nextPosition64Low, ZERO_OFFSET);\n geometry.position = currentProjection.commonPosition;\n } else {\n var sourceWorld = attributes.instanceSourcePositions;\n var targetWorld = attributes.instanceTargetPositions;\n if (arc.useShortestPath != 0.0) {\n sourceWorld.x = ((sourceWorld.x + 180.0) % 360.0) - 180.0;\n targetWorld.x = ((targetWorld.x + 180.0) % 360.0) - 180.0;\n let deltaLongitude = targetWorld.x - sourceWorld.x;\n if (deltaLongitude > 180.0) {\n targetWorld.x -= 360.0;\n }\n if (deltaLongitude < -180.0) {\n sourceWorld.x -= 360.0;\n }\n }\n\n let source = project_position_vec3_f64(\n sourceWorld,\n attributes.instanceSourcePositions64Low\n );\n let targetPosition = project_position_vec3_f64(\n targetWorld,\n attributes.instanceTargetPositions64Low\n );\n\n // Common x at longitude=-180.\n var antimeridianX = 0.0;\n if (arc.useShortestPath != 0.0) {\n if (project.projectionMode == PROJECTION_MODE_WEB_MERCATOR_AUTO_OFFSET) {\n antimeridianX = -(project.coordinateOrigin.x + 180.0) / 360.0 * TILE_SIZE;\n }\n let thresholdRatio = (antimeridianX - source.x) / (targetPosition.x - source.x);\n if (previousRatio <= thresholdRatio && nextRatio > thresholdRatio) {\n isValid = 0.0;\n indexDirection = sign(segmentRatio - thresholdRatio);\n segmentRatio = thresholdRatio;\n }\n }\n\n nextRatio = select(nextRatio, previousRatio, indexDirection < 0.0);\n var currentPosition = interpolateFlat(\n source,\n targetPosition,\n segmentRatio,\n attributes.instanceHeights,\n attributes.instanceTilts\n );\n var nextPosition = interpolateFlat(\n source,\n targetPosition,\n nextRatio,\n attributes.instanceHeights,\n attributes.instanceTilts\n );\n\n if (arc.useShortestPath != 0.0 && nextPosition.x < antimeridianX) {\n currentPosition.x += TILE_SIZE;\n nextPosition.x += TILE_SIZE;\n }\n\n currentClip = project_common_position_to_clipspace(vec4<f32>(currentPosition, 1.0));\n nextClip = project_common_position_to_clipspace(vec4<f32>(nextPosition, 1.0));\n geometry.position = vec4<f32>(currentPosition, 1.0);\n }\n\n geometry.uv = vec2<f32>(segmentRatio, segmentSide);\n geometry.pickingColor = picking_getPickingColorFromIndex(instanceIndex);\n\n let widthPixels = clamp(\n project_unit_size_to_pixel(attributes.instanceWidths * arc.widthScale, arc.widthUnits),\n arc.widthMinPixels,\n arc.widthMaxPixels\n );\n#ifdef ANTIALIASING\n var offset = getExtrusionOffset(\n#else\n let offset = getExtrusionOffset(\n#endif\n (nextClip.xy - currentClip.xy) * indexDirection,\n segmentSide,\n widthPixels\n );\n#ifdef ANTIALIASING\n let halfWidthPixels = length(offset);\n if (halfWidthPixels > 0.0) {\n // Keep the declared edge at abs(uv.y) == 1 while rasterizing the outer half of the centered\n // one-device-pixel coverage ramp.\n let coverageScale = 1.0 + 0.5 / project.devicePixelRatio / halfWidthPixels;\n offset *= coverageScale;\n geometry.uv.y *= coverageScale;\n }\n#endif\n\n var output: Varyings;\n output.position = currentClip + vec4<f32>(project_pixel_size_to_clipspace(offset), 0.0, 0.0);\n let color = mix(attributes.instanceSourceColors, attributes.instanceTargetColors, segmentRatio);\n output.color = vec4<f32>(color.rgb, color.a * layer.opacity);\n output.uv = geometry.uv;\n output.pickingColor = geometry.pickingColor;\n output.isValid = isValid;\n return output;\n}\n\n@fragment\nfn fragmentMain(varyings: Varyings) -> @location(0) vec4<f32> {\n#ifdef ANTIALIASING\n let edgeCoord = abs(varyings.uv.y);\n let edgePixels = (1.0 - edgeCoord) / max(fwidth(edgeCoord), 1e-6);\n#endif\n\n if (varyings.isValid == 0.0) {\n discard;\n }\n\n#ifdef ANTIALIASING\n // Fragments outside the coverage ramp must not write depth or picking colors.\n if (edgePixels <= -SMOOTH_EDGE_RADIUS) {\n discard;\n }\n#endif\n var color = varyings.color;\n#ifdef ANTIALIASING\n // Feather one device pixel across the width. Arc segments meet lengthwise, so only soften the\n // two outer edges of the strip.\n color.a *= smoothedge(0.0, edgePixels);\n#endif\n if (picking.isActive > 0.5) {\n if (!picking_isColorValid(varyings.pickingColor)) {\n discard;\n }\n return vec4<f32>(varyings.pickingColor, 1.0);\n }\n if (picking.isHighlightActive > 0.5) {\n let highlightedObjectColor = picking_normalizeColor(picking.highlightedObjectColor);\n if (picking_isColorZero(abs(varyings.pickingColor - highlightedObjectColor))) {\n let highlightAlpha = picking.highlightColor.a;\n let blendedAlpha = highlightAlpha + color.a * (1.0 - highlightAlpha);\n if (blendedAlpha > 0.0) {\n let highlightRatio = highlightAlpha / blendedAlpha;\n color = vec4<f32>(\n mix(color.rgb, picking.highlightColor.rgb, highlightRatio),\n blendedAlpha\n );\n }\n }\n }\n return deckgl_premultiplied_alpha(color);\n}\n",defines:e?{ANTIALIASING:1}:{},modules:[Ye,Ze,Je,ho]})}get wrapLongitude(){return!1}initializeState(){this.getAttributeManager().addInstanced({instanceSourcePositions:{size:3,type:"float64",fp64:this.use64bitPositions(),transition:!0,accessor:"getSourcePosition"},instanceTargetPositions:{size:3,type:"float64",fp64:this.use64bitPositions(),transition:!0,accessor:"getTargetPosition"},instanceSourceColors:{size:this.props.colorFormat.length,type:"unorm8",transition:!0,accessor:"getSourceColor",defaultValue:vo},instanceTargetColors:{size:this.props.colorFormat.length,type:"unorm8",transition:!0,accessor:"getTargetColor",defaultValue:vo},instanceWidths:{size:1,transition:!0,accessor:"getWidth",defaultValue:1},instanceHeights:{size:1,transition:!0,accessor:"getHeight",defaultValue:1},instanceTilts:{size:1,transition:!0,accessor:"getTilt",defaultValue:0}})}updateState(e){super.updateState(e);const{props:t,oldProps:n,changeFlags:i}=e;(i.extensionsChanged||t.antialiasing!==n.antialiasing)&&(this.state.model?.destroy(),this.state.model=this._getModel(),this.getAttributeManager().invalidateAll())}draw({uniforms:e}){const{widthUnits:t,widthScale:n,widthMinPixels:o,widthMaxPixels:s,greatCircle:r,wrapLongitude:a,numSegments:l}=this.props,c={numSegments:l,widthUnits:i[t],widthScale:n,widthMinPixels:o,widthMaxPixels:s,greatCircle:r,useShortestPath:a},u=this.state.model;u.shaderInputs.setProps({arc:c}),u.setVertexCount(2*l),u.draw(this.context.renderPass)}_getModel(){return new xt(this.context.device,{...this.getShaders(),id:this.props.id,bufferLayout:this.getAttributeManager().getBufferLayouts(),topology:"triangle-strip",isInstanced:!0})}};_o.layerName="ArcLayer",_o.defaultProps=mo;var xo=new Uint32Array([0,2,1,0,3,2]),yo=new Float32Array([0,1,0,0,1,0,1,1]);function bo(e,t){if(!t)return function(e){const t=/* @__PURE__ */new Float64Array(12);for(let n=0;n<e.length;n++)t[3*n+0]=e[n][0],t[3*n+1]=e[n][1],t[3*n+2]=e[n][2]||0;return{vertexCount:6,positions:t,indices:xo,texCoords:yo}}(e);const n=Math.max(Math.abs(e[0][0]-e[3][0]),Math.abs(e[1][0]-e[2][0])),i=Math.max(Math.abs(e[1][1]-e[0][1]),Math.abs(e[2][1]-e[3][1])),o=Math.ceil(n/t)+1,s=Math.ceil(i/t)+1,r=(o-1)*(s-1)*6,a=new Uint32Array(r),l=new Float32Array(o*s*2),c=new Float64Array(o*s*3);let u=0,f=0;for(let d=0;d<o;d++){const t=d/(o-1);for(let n=0;n<s;n++){const i=n/(s-1),o=Po(e,t,i);c[3*u+0]=o[0],c[3*u+1]=o[1],c[3*u+2]=o[2]||0,l[2*u+0]=t,l[2*u+1]=1-i,d>0&&n>0&&(a[f++]=u-s,a[f++]=u-s-1,a[f++]=u-1,a[f++]=u-s,a[f++]=u-1,a[f++]=u),u++}}return{vertexCount:r,positions:c,indices:a,texCoords:l}}function Po(e,t,n){return a(a(e[0],e[1],n),a(e[3],e[2],n),t)}var Co="layout(std140) uniform bitmapUniforms {\n vec4 bounds;\n float coordinateConversion;\n float desaturate;\n vec3 tintColor;\n vec4 transparentColor;\n} bitmap;\n",wo={name:"bitmap",source:"\nstruct BitmapUniforms {\n bounds: vec4<f32>,\n coordinateConversion: f32,\n desaturate: f32,\n tintColor: vec3<f32>,\n transparentColor: vec4<f32>,\n};\n\n@group(0) @binding(auto) var<uniform> bitmap: BitmapUniforms;\n@group(0) @binding(auto) var bitmapTexture: texture_2d<f32>;\n@group(0) @binding(auto) var bitmapTextureSampler: sampler;\n",vs:Co,fs:Co,uniformTypes:{bounds:"vec4<f32>",coordinateConversion:"f32",desaturate:"f32",tintColor:"vec3<f32>",transparentColor:"vec4<f32>"}},So=class extends co{getShaders(){return super.getShaders({vs:"#version 300 es\n#define SHADER_NAME bitmap-layer-vertex-shader\n\nin vec2 texCoords;\nin vec3 positions;\nin vec3 positions64Low;\n\nout vec2 vTexCoord;\nout vec2 vTexPos;\n\nconst vec3 pickingColor = vec3(1.0, 0.0, 0.0);\n\nvoid main(void) {\n geometry.worldPosition = positions;\n geometry.uv = texCoords;\n geometry.pickingColor = pickingColor;\n\n gl_Position = project_position_to_clipspace(positions, positions64Low, vec3(0.0), geometry.position);\n DECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n\n vTexCoord = texCoords;\n\n if (bitmap.coordinateConversion < -0.5) {\n vTexPos = geometry.position.xy + project.commonOrigin.xy;\n } else if (bitmap.coordinateConversion > 0.5) {\n vTexPos = geometry.worldPosition.xy;\n }\n\n vec4 color = vec4(0.0);\n DECKGL_FILTER_COLOR(color, geometry);\n}\n",fs:"#version 300 es\n#define SHADER_NAME bitmap-layer-fragment-shader\n\n#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D bitmapTexture;\n\nin vec2 vTexCoord;\nin vec2 vTexPos;\n\nout vec4 fragColor;\n\n/* projection utils */\nconst float TILE_SIZE = 512.0;\nconst float PI = 3.1415926536;\nconst float WORLD_SCALE = TILE_SIZE / PI / 2.0;\n\n// from degrees to Web Mercator\nvec2 lnglat_to_mercator(vec2 lnglat) {\n float x = lnglat.x;\n float y = clamp(lnglat.y, -89.9, 89.9);\n return vec2(\n radians(x) + PI,\n PI + log(tan(PI * 0.25 + radians(y) * 0.5))\n ) * WORLD_SCALE;\n}\n\n// from Web Mercator to degrees\nvec2 mercator_to_lnglat(vec2 xy) {\n xy /= WORLD_SCALE;\n return degrees(vec2(\n xy.x - PI,\n atan(exp(xy.y - PI)) * 2.0 - PI * 0.5\n ));\n}\n/* End projection utils */\n\n// apply desaturation\nvec3 color_desaturate(vec3 color) {\n float luminance = (color.r + color.g + color.b) * 0.333333333;\n return mix(color, vec3(luminance), bitmap.desaturate);\n}\n\n// apply tint\nvec3 color_tint(vec3 color) {\n return color * bitmap.tintColor;\n}\n\n// blend with background color\nvec4 apply_opacity(vec3 color, float alpha) {\n if (bitmap.transparentColor.a == 0.0) {\n return vec4(color, alpha);\n }\n float blendedAlpha = alpha + bitmap.transparentColor.a * (1.0 - alpha);\n float highLightRatio = alpha / blendedAlpha;\n vec3 blendedRGB = mix(bitmap.transparentColor.rgb, color, highLightRatio);\n return vec4(blendedRGB, blendedAlpha);\n}\n\nvec2 getUV(vec2 pos) {\n return vec2(\n (pos.x - bitmap.bounds[0]) / (bitmap.bounds[2] - bitmap.bounds[0]),\n (pos.y - bitmap.bounds[3]) / (bitmap.bounds[1] - bitmap.bounds[3])\n );\n}\n\n\nvec3 packUVsIntoRGB(vec2 uv) {\n // Extract the top 8 bits. We want values to be truncated down so we can add a fraction\n vec2 uv8bit = floor(uv * 256.);\n\n // Calculate the normalized remainders of u and v parts that do not fit into 8 bits\n // Scale and clamp to 0-1 range\n vec2 uvFraction = fract(uv * 256.);\n vec2 uvFraction4bit = floor(uvFraction * 16.);\n\n // Remainder can be encoded in blue channel, encode as 4 bits for pixel coordinates\n float fractions = uvFraction4bit.x + uvFraction4bit.y * 16.;\n\n return vec3(uv8bit, fractions) / 255.;\n}\n\n\nvoid main(void) {\n vec2 uv = vTexCoord;\n if (bitmap.coordinateConversion < -0.5) {\n vec2 lnglat = mercator_to_lnglat(vTexPos);\n uv = getUV(lnglat);\n } else if (bitmap.coordinateConversion > 0.5) {\n vec2 commonPos = lnglat_to_mercator(vTexPos);\n uv = getUV(commonPos);\n }\n vec4 bitmapColor = texture(bitmapTexture, uv);\n\n fragColor = apply_opacity(color_tint(color_desaturate(bitmapColor.rgb)), bitmapColor.a * layer.opacity);\n\n geometry.uv = uv;\n DECKGL_FILTER_COLOR(fragColor, geometry);\n\n if (bool(picking.isActive) && !bool(picking.isAttribute)) {\n // Since instance information is not used, we can use picking color for pixel index\n fragColor.rgb = packUVsIntoRGB(uv);\n }\n}\n",source:"struct Attributes {\n @location(0) positions: vec3<f32>,\n @location(1) positions64Low: vec3<f32>,\n @location(2) texCoords: vec2<f32>,\n};\n\nstruct Varyings {\n @builtin(position) position: vec4<f32>,\n @location(0) vTexCoord: vec2<f32>,\n @location(1) vTexPos: vec2<f32>,\n @location(2) pickingColor: vec3<f32>,\n @location(3) pickingDepth: f32,\n};\n\n// from degrees to Web Mercator\nfn lnglat_to_mercator(lnglat: vec2<f32>) -> vec2<f32> {\n let x = lnglat.x;\n let y = clamp(lnglat.y, -89.9, 89.9);\n return vec2<f32>(\n radians(x) + PI,\n PI + log(tan(PI * 0.25 + radians(y) * 0.5))\n ) * WORLD_SCALE;\n}\n\n// from Web Mercator to degrees\nfn mercator_to_lnglat(xy: vec2<f32>) -> vec2<f32> {\n let position = xy / WORLD_SCALE;\n return degrees(vec2<f32>(\n position.x - PI,\n atan(exp(position.y - PI)) * 2.0 - PI * 0.5\n ));\n}\n\nfn color_desaturate(colorValue: vec3<f32>) -> vec3<f32> {\n let luminance = (colorValue.r + colorValue.g + colorValue.b) * 0.333333333;\n return mix(colorValue, vec3<f32>(luminance), bitmap.desaturate);\n}\n\nfn color_tint(colorValue: vec3<f32>) -> vec3<f32> {\n return colorValue * bitmap.tintColor;\n}\n\nfn apply_opacity(colorValue: vec3<f32>, alpha: f32) -> vec4<f32> {\n if (bitmap.transparentColor.a == 0.0) {\n return vec4<f32>(colorValue, alpha);\n }\n let blendedAlpha = alpha + bitmap.transparentColor.a * (1.0 - alpha);\n let highLightRatio = alpha / blendedAlpha;\n let blendedRGB = mix(bitmap.transparentColor.rgb, colorValue, highLightRatio);\n return vec4<f32>(blendedRGB, blendedAlpha);\n}\n\nfn getUV(position: vec2<f32>) -> vec2<f32> {\n return vec2<f32>(\n (position.x - bitmap.bounds[0]) / (bitmap.bounds[2] - bitmap.bounds[0]),\n (position.y - bitmap.bounds[3]) / (bitmap.bounds[1] - bitmap.bounds[3])\n );\n}\n\n// Pack the top 12 bits of two normalized floats into three 8-bit values.\nfn packUVsIntoRGB(uv: vec2<f32>) -> vec3<f32> {\n let uv8bit = floor(uv * 256.0);\n let uvFraction = fract(uv * 256.0);\n let uvFraction4bit = floor(uvFraction * 16.0);\n let fractions = uvFraction4bit.x + uvFraction4bit.y * 16.0;\n return vec3<f32>(uv8bit, fractions) / 255.0;\n}\n\n@vertex\nfn vertexMain(attributes: Attributes) -> Varyings {\n var output: Varyings;\n geometry.worldPosition = attributes.positions;\n geometry.uv = attributes.texCoords;\n geometry.pickingColor = picking_getPickingColorFromIndex(0u);\n\n let projectedPosition = project_position_to_clipspace_and_commonspace(\n attributes.positions,\n attributes.positions64Low,\n vec3<f32>(0.0)\n );\n geometry.position = projectedPosition.commonPosition;\n output.position = projectedPosition.clipPosition;\n output.vTexCoord = attributes.texCoords;\n output.vTexPos = vec2<f32>(0.0);\n output.pickingColor = geometry.pickingColor;\n output.pickingDepth = output.position.z / output.position.w;\n\n if (bitmap.coordinateConversion < -0.5) {\n output.vTexPos = geometry.position.xy + project.commonOrigin.xy;\n } else if (bitmap.coordinateConversion > 0.5) {\n output.vTexPos = geometry.worldPosition.xy;\n }\n\n return output;\n}\n\n@fragment\nfn fragmentMain(input: Varyings) -> @location(0) vec4<f32> {\n var uv = input.vTexCoord;\n if (bitmap.coordinateConversion < -0.5) {\n uv = getUV(mercator_to_lnglat(input.vTexPos));\n } else if (bitmap.coordinateConversion > 0.5) {\n uv = getUV(lnglat_to_mercator(input.vTexPos));\n }\n\n let bitmapColor = textureSample(bitmapTexture, bitmapTextureSampler, uv);\n var fragColor = apply_opacity(\n color_tint(color_desaturate(bitmapColor.rgb)),\n bitmapColor.a * layer.opacity\n );\n\n geometry.uv = uv;\n\n if (picking.isActive > 0.5) {\n if (picking.isAttribute > 0.5) {\n return vec4<f32>(input.pickingDepth, 0.0, 0.0, 1.0);\n }\n return vec4<f32>(packUVsIntoRGB(uv), 1.0);\n }\n\n if (picking.isHighlightActive > 0.5) {\n let highlightedObjectColor = picking_normalizeColor(picking.highlightedObjectColor);\n if (picking_isColorZero(abs(input.pickingColor - highlightedObjectColor))) {\n let highLightAlpha = picking.highlightColor.a;\n let blendedAlpha = highLightAlpha + fragColor.a * (1.0 - highLightAlpha);\n if (blendedAlpha > 0.0) {\n let highLightRatio = highLightAlpha / blendedAlpha;\n fragColor = vec4<f32>(\n mix(fragColor.rgb, picking.highlightColor.rgb, highLightRatio),\n blendedAlpha\n );\n } else {\n fragColor = vec4<f32>(fragColor.rgb, 0.0);\n }\n }\n }\n\n return deckgl_premultiplied_alpha(fragColor);\n}\n",modules:[Ze,Ye,Je,wo]})}initializeState(){const e=!0;this.getAttributeManager().add({indices:{size:1,isIndexed:!0,update:e=>e.value=this.state.mesh.indices,noAlloc:e},positions:{size:3,type:"float64",fp64:this.use64bitPositions(),update:e=>e.value=this.state.mesh.positions,noAlloc:e},texCoords:{size:2,update:e=>e.value=this.state.mesh.texCoords,noAlloc:e}})}updateState({props:e,oldProps:t,changeFlags:n}){const i=this.getAttributeManager();if(n.extensionsChanged&&(this.state.model?.destroy(),this.state.model=this._getModel(),i.invalidateAll()),e.bounds!==t.bounds){const e=this.state.mesh,t=this._createMesh();this.state.model.setVertexCount(t.vertexCount);for(const n in t)e&&e[n]!==t[n]&&i.invalidate(n);this.setState({mesh:t,...this._getCoordinateUniforms()})}else e._imageCoordinateSystem!==t._imageCoordinateSystem&&this.setState(this._getCoordinateUniforms())}getPickingInfo(e){const{image:t}=this.props,n=e.info;if(!n.color||!t)return n.bitmap=null,n;const{width:i,height:o}=t;n.index=0;const s=function(e){const[t,n,i]=e;return[(t+(15&i)/16)/256,(n+(240&i)/256)/256]}(n.color);return n.bitmap={size:{width:i,height:o},uv:s,pixel:[Math.floor(s[0]*i),Math.floor(s[1]*o)]},n}disablePickingIndex(){this.setState({disablePicking:!0})}restorePickingColors(){this.setState({disablePicking:!1})}_updateAutoHighlight(e){super._updateAutoHighlight({...e,color:this.encodePickingColor(0)})}_createMesh(){const{bounds:e}=this.props;let t=e;return Lo(e)&&(t=[[e[0],e[1]],[e[0],e[3]],[e[2],e[3]],[e[2],e[1]]]),bo(t,this.context.viewport.resolution)}_getModel(){const e="webgpu"===this.context.device.type?this.getAttributeManager().getBufferLayouts({isInstanced:!1}).filter(e=>"indices"!==e.name):this.getAttributeManager().getBufferLayouts();return new xt(this.context.device,{...this.getShaders(),id:this.props.id,bufferLayout:e,topology:"triangle-list",isInstanced:!1})}draw(e){const{shaderModuleProps:t}=e,{model:n,coordinateConversion:i,bounds:o,disablePicking:s}=this.state,{image:r,desaturate:a,transparentColor:l,tintColor:c}=this.props;if((!t.picking.isActive||!s)&&r&&n){const e={bitmapTexture:r,bounds:o,coordinateConversion:i,desaturate:a,tintColor:c.slice(0,3).map(e=>e/255),transparentColor:l.map(e=>e/255)};n.shaderInputs.setProps({bitmap:e}),n.draw(this.context.renderPass)}}_getCoordinateUniforms(){let{_imageCoordinateSystem:e}=this.props;if("default"!==e){const{bounds:t}=this.props;if(!Lo(t))throw new Error("_imageCoordinateSystem only supports rectangular bounds");const n=this.context.viewport.resolution?"lnglat":"cartesian";if(e="lnglat"===e?"lnglat":"cartesian","lnglat"===e&&"cartesian"===n)return{coordinateConversion:-1,bounds:t};if("cartesian"===e&&"lnglat"===n){const e=s([t[0],t[1]]),n=s([t[2],t[3]]);return{coordinateConversion:1,bounds:[e[0],e[1],n[0],n[1]]}}}return{coordinateConversion:0,bounds:[0,0,0,0]}}};function Lo(e){return Number.isFinite(e[0])}So.layerName="BitmapLayer",So.defaultProps={image:{type:"image",value:null,async:!0},bounds:{type:"array",value:[1,0,0,1],compare:!0},_imageCoordinateSystem:"default",desaturate:{type:"number",min:0,max:1,value:0},transparentColor:{type:"color",value:[0,0,0,0]},tintColor:{type:"color",value:[255,255,255]},textureParameters:{type:"object",ignore:!0,value:null}};var Ao="layout(std140) uniform iconUniforms {\n float sizeScale;\n vec2 iconsTextureDim;\n float sizeBasis;\n float sizeMinPixels;\n float sizeMaxPixels;\n bool billboard;\n highp int sizeUnits;\n float alphaCutoff;\n} icon;\n",Io={name:"icon",vs:Ao,fs:Ao,uniformTypes:{sizeScale:"f32",iconsTextureDim:"vec2<f32>",sizeBasis:"f32",sizeMinPixels:"f32",sizeMaxPixels:"f32",billboard:"f32",sizeUnits:"i32",alphaCutoff:"f32"}},Eo='struct IconUniforms {\n sizeScale: f32,\n iconsTextureDim: vec2<f32>,\n sizeBasis: f32,\n sizeMinPixels: f32,\n sizeMaxPixels: f32,\n billboard: i32,\n sizeUnits: i32,\n alphaCutoff: f32\n};\n\n@group(0) @binding(auto) var<uniform> icon: IconUniforms;\n@group(0) @binding(auto) var iconsTexture : texture_2d<f32>;\n@group(0) @binding(auto) var iconsTextureSampler : sampler;\n\nfn rotate_by_angle(vertex: vec2<f32>, angle_deg: f32) -> vec2<f32> {\n let angle_radian = angle_deg * PI / 180.0;\n let c = cos(angle_radian);\n let s = sin(angle_radian);\n let rotation = mat2x2<f32>(vec2<f32>(c, s), vec2<f32>(-s, c));\n return rotation * vertex;\n}\n\nstruct Attributes {\n @builtin(instance_index) instanceIndex : u32,\n @location(0) positions: vec2<f32>,\n\n @location(1) instancePositions: vec3<f32>,\n @location(2) instancePositions64Low: vec3<f32>,\n @location(3) instanceSizes: f32,\n @location(4) instanceAngles: f32,\n @location(5) instanceColors: vec4<f32>,\n @location(6) instanceIconFrames: vec4<f32>,\n @location(7) instanceColorModes: f32,\n @location(8) instanceOffsets: vec2<f32>,\n @location(9) instancePixelOffset: vec2<f32>,\n PICKING_COLOR_ATTRIBUTE\n};\n\nstruct Varyings {\n @builtin(position) position: vec4<f32>,\n\n @location(0) vColorMode: f32,\n @location(1) vColor: vec4<f32>,\n @location(2) vTextureCoords: vec2<f32>,\n @location(3) uv: vec2<f32>,\n @location(4) pickingColor: vec3<f32>,\n};\n\n@vertex\nfn vertexMain(inp: Attributes) -> Varyings {\n // write geometry fields used by filters + FS\n geometry.worldPosition = inp.instancePositions;\n geometry.uv = inp.positions;\n geometry.pickingColor = PICKING_COLOR_VALUE;\n\n var outp: Varyings;\n outp.uv = inp.positions;\n\n let iconSize = inp.instanceIconFrames.zw;\n\n // convert size in meters to pixels, then clamp\n let sizePixels = clamp(\n project_unit_size_to_pixel(inp.instanceSizes * icon.sizeScale, icon.sizeUnits),\n icon.sizeMinPixels, icon.sizeMaxPixels\n );\n\n // scale icon height to match instanceSize\n let iconConstraint = select(iconSize.y, iconSize.x, icon.sizeBasis == 0.0);\n let instanceScale = select(sizePixels / iconConstraint, 0.0, iconConstraint == 0.0);\n\n // scale and rotate vertex in "pixel" units; then add per-instance pixel offset\n var pixelOffset = inp.positions / 2.0 * iconSize + inp.instanceOffsets;\n pixelOffset = rotate_by_angle(pixelOffset, inp.instanceAngles) * instanceScale;\n pixelOffset = pixelOffset + inp.instancePixelOffset;\n pixelOffset.y = pixelOffset.y * -1.0;\n\n if (icon.billboard != 0) {\n var pos = project_position_to_clipspace(inp.instancePositions, inp.instancePositions64Low, vec3<f32>(0.0)); // TODO, &geometry.position);\n // DECKGL_FILTER_GL_POSITION(pos, geometry);\n\n var offset = vec3<f32>(pixelOffset, 0.0);\n // DECKGL_FILTER_SIZE(offset, geometry);\n let clipOffset = project_pixel_size_to_clipspace(offset.xy);\n pos = vec4<f32>(pos.x + clipOffset.x, pos.y + clipOffset.y, pos.z, pos.w);\n outp.position = pos;\n } else {\n var offset_common = vec3<f32>(project_pixel_size_vec2(pixelOffset), 0.0);\n // DECKGL_FILTER_SIZE(offset_common, geometry);\n var pos = project_position_to_clipspace(inp.instancePositions, inp.instancePositions64Low, offset_common); // TODO, &geometry.position);\n // DECKGL_FILTER_GL_POSITION(pos, geometry);\n outp.position = pos;\n }\n\n let uvMix = (inp.positions.xy + vec2<f32>(1.0, 1.0)) * 0.5;\n outp.vTextureCoords = mix(inp.instanceIconFrames.xy, inp.instanceIconFrames.xy + iconSize, uvMix) / icon.iconsTextureDim;\n\n outp.vColor = inp.instanceColors;\n // DECKGL_FILTER_COLOR(outp.vColor, geometry);\n\n outp.vColorMode = inp.instanceColorModes;\n outp.pickingColor = geometry.pickingColor;\n\n return outp;\n}\n\n@fragment\nfn fragmentMain(inp: Varyings) -> @location(0) vec4<f32> {\n // expose to deck.gl filter hooks\n geometry.uv = inp.uv;\n\n let texColor = textureSample(iconsTexture, iconsTextureSampler, inp.vTextureCoords);\n\n // if colorMode == 0, use pixel color from the texture\n // if colorMode == 1 (or picking), use texture as transparency mask\n let rgb = mix(texColor.rgb, inp.vColor.rgb, inp.vColorMode);\n let a = texColor.a * layer.opacity * inp.vColor.a;\n\n if (a < icon.alphaCutoff) {\n discard;\n }\n\n if (picking.isActive > 0.5) {\n if (!picking_isColorValid(inp.pickingColor)) {\n discard;\n }\n return vec4<f32>(inp.pickingColor, 1.0);\n }\n\n var fragColor = deckgl_premultiplied_alpha(vec4<f32>(rgb, a));\n\n if (picking.isHighlightActive > 0.5) {\n let highlightedObjectColor = picking_normalizeColor(picking.highlightedObjectColor);\n if (picking_isColorZero(abs(inp.pickingColor - highlightedObjectColor))) {\n let highLightAlpha = picking.highlightColor.a;\n let blendedAlpha = highLightAlpha + fragColor.a * (1.0 - highLightAlpha);\n if (blendedAlpha > 0.0) {\n let highLightRatio = highLightAlpha / blendedAlpha;\n fragColor = vec4<f32>(\n mix(fragColor.rgb, picking.highlightColor.rgb, highLightRatio),\n blendedAlpha\n );\n } else {\n fragColor = vec4<f32>(fragColor.rgb, 0.0);\n }\n }\n }\n\n return fragColor;\n}\n';function To(e){return Eo.replace("PICKING_COLOR_ATTRIBUTE",e?"@location(10) rowIndexes: u32,":"").replace("PICKING_COLOR_VALUE",e?"picking_getPickingColorFromIndex(inp.rowIndexes)":"picking_getPickingColorFromIndex(inp.instanceIndex)")}var Oo=()=>{},zo={minFilter:"linear",mipmapFilter:"linear",magFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"},Mo={x:0,y:0,width:0,height:0};function Ro(e,t,n,i){const o=Math.min(n/t.width,i/t.height),s=Math.floor(t.width*o),r=Math.floor(t.height*o);return 1===o?{image:t,width:s,height:r}:(e.canvas.height=r,e.canvas.width=s,e.clearRect(0,0,s,r),e.drawImage(t,0,0,t.width,t.height,0,0,s,r),{image:e.canvas,width:s,height:r})}function Bo(e){return e&&(e.id||e.url)}function ko(e){const{device:t}=e;"webgl"===t.type?e.generateMipmapsWebGL():"webgpu"===t.type&&t.generateMipmapsWebGPU(e)}function Fo(e,t,n){for(let i=0;i<t.length;i++){const{icon:o,xOffset:s}=t[i];e[Bo(o)]={...o,x:s,y:n}}}var No=class{constructor(e,{onUpdate:t=Oo,onError:n=Oo}){this._loadOptions=null,this._texture=null,this._externalTexture=null,this._mapping={},this._samplerParameters=null,this._pendingCount=0,this._autoPacking=!1,this._xOffset=0,this._yOffset=0,this._rowHeight=0,this._buffer=4,this._canvasWidth=1024,this._canvasHeight=0,this._canvas=null,this.device=e,this.onUpdate=t,this.onError=n}finalize(){this._texture?.delete()}getTexture(){return this._texture||this._externalTexture}getIconMapping(e){const t=this._autoPacking?Bo(e):e;return this._mapping[t]||Mo}setProps({loadOptions:e,autoPacking:t,iconAtlas:n,iconMapping:i,textureParameters:o}){e&&(this._loadOptions=e),void 0!==t&&(this._autoPacking=t),i&&(this._mapping=i),n&&(this._texture?.delete(),this._texture=null,this._externalTexture=n),o&&(this._samplerParameters=o)}get isLoaded(){return 0===this._pendingCount}packIcons(e,t){if(!this._autoPacking||"undefined"==typeof document)return;const n=Object.values(function(e,t,n){if(!e||!t)return null;n=n||{};const i={},{iterable:o,objectInfo:s}=$t(e);for(const r of o){s.index++;const e=t(r,s),o=Bo(e);if(!e)throw new Error("Icon is missing.");if(!e.url)throw new Error("Icon url is missing.");i[o]||n[o]&&e.url===n[o].url||(i[o]={...e,source:r,sourceIndex:s.index})}return i}(e,t,this._mapping)||{});if(n.length>0){const{mapping:e,xOffset:t,yOffset:i,rowHeight:o,canvasHeight:s}=function({icons:e,buffer:t,mapping:n={},xOffset:i=0,yOffset:o=0,rowHeight:s=0,canvasWidth:r}){let a=[];for(let c=0;c<e.length;c++){const l=e[c];if(!n[Bo(l)]){const{height:e,width:c}=l;i+c+t>r&&(Fo(n,a,o),i=0,o=s+o+t,s=0,a=[]),a.push({icon:l,xOffset:i}),i=i+c+t,s=Math.max(s,e)}}return a.length>0&&Fo(n,a,o),{mapping:n,rowHeight:s,xOffset:i,yOffset:o,canvasWidth:r,canvasHeight:(l=s+o+t,Math.pow(2,Math.ceil(Math.log2(l))))};var l}({icons:n,buffer:this._buffer,canvasWidth:this._canvasWidth,mapping:this._mapping,rowHeight:this._rowHeight,xOffset:this._xOffset,yOffset:this._yOffset});this._rowHeight=o,this._mapping=e,this._xOffset=t,this._yOffset=i,this._canvasHeight=s,this._texture||(this._texture=this.device.createTexture({format:"rgba8unorm",data:null,width:this._canvasWidth,height:this._canvasHeight,sampler:this._samplerParameters||zo,mipLevels:this.device.getMipLevelCount(this._canvasWidth,this._canvasHeight)})),this._texture.height!==this._canvasHeight&&(this._texture=function(e,t,n,i){const{width:o,height:s,device:r}=e,a=r.createTexture({format:"rgba8unorm",width:t,height:n,sampler:i,mipLevels:r.getMipLevelCount(t,n)}),l=r.createCommandEncoder();l.copyTextureToTexture({sourceTexture:e,destinationTexture:a,width:o,height:s});const c=l.finish();return r.submit(c),ko(a),e.destroy(),a}(this._texture,this._canvasWidth,this._canvasHeight,this._samplerParameters||zo)),this.onUpdate(!0),this._canvas=this._canvas||document.createElement("canvas"),this._loadIcons(n)}}_loadIcons(e){const t=this._canvas.getContext("2d",{willReadFrequently:!0});for(const n of e)this._pendingCount++,P(n.url,this._loadOptions).then(e=>{const i=Bo(n),o=this._mapping[i],{x:s,y:r,width:a,height:l}=o,{image:c,width:u,height:f}=Ro(t,e,a,l),d=s+(a-u)/2,p=r+(l-f)/2;this._texture?.copyExternalImage({image:c,x:d,y:p,width:u,height:f}),o.x=d,o.y=p,o.width=u,o.height=f,this._texture&&ko(this._texture),this.onUpdate(u!==a||f!==l)}).catch(e=>{this.onError({url:n.url,source:n.source,sourceIndex:n.sourceIndex,loadOptions:this._loadOptions,error:e})}).finally(()=>{this._pendingCount--})}},Do=[0,0,0,255],jo={iconAtlas:{type:"image",value:null,async:!0},iconMapping:{type:"object",value:{},async:!0},sizeScale:{type:"number",value:1,min:0},billboard:!0,sizeUnits:"pixels",sizeBasis:"height",sizeMinPixels:{type:"number",min:0,value:0},sizeMaxPixels:{type:"number",min:0,value:Number.MAX_SAFE_INTEGER},alphaCutoff:{type:"number",value:.05,min:0,max:1},getPosition:{type:"accessor",value:e=>e.position},getIcon:{type:"accessor",value:e=>e.icon},getColor:{type:"accessor",value:Do},getSize:{type:"accessor",value:1},getAngle:{type:"accessor",value:0},getPixelOffset:{type:"accessor",value:[0,0]},onIconError:{type:"function",value:null,optional:!0},textureParameters:{type:"object",ignore:!0,value:null}},Uo=class extends co{getShaders(){const e=Boolean(this.props.data?.attributes?.rowIndexes);return super.getShaders({vs:"#version 300 es\n#define SHADER_NAME icon-layer-vertex-shader\nin vec2 positions;\nin vec3 instancePositions;\nin vec3 instancePositions64Low;\nin float instanceSizes;\nin float instanceAngles;\nin vec4 instanceColors;\n#ifdef USE_ROW_INDEXES\nin float rowIndexes;\n#endif\nin vec4 instanceIconFrames;\nin float instanceColorModes;\nin vec2 instanceOffsets;\nin vec2 instancePixelOffset;\nout float vColorMode;\nout vec4 vColor;\nout vec2 vTextureCoords;\nout vec2 uv;\nvec2 rotate_by_angle(vec2 vertex, float angle) {\nfloat angle_radian = angle * PI / 180.0;\nfloat cos_angle = cos(angle_radian);\nfloat sin_angle = sin(angle_radian);\nmat2 rotationMatrix = mat2(cos_angle, -sin_angle, sin_angle, cos_angle);\nreturn rotationMatrix * vertex;\n}\nvoid main(void) {\ngeometry.worldPosition = instancePositions;\ngeometry.uv = positions;\n#ifdef USE_ROW_INDEXES\ngeometry.pickingColor = picking_getPickingColorFromIndex(rowIndexes);\n#else\ngeometry.pickingColor = picking_getPickingColorFromInstanceID();\n#endif\nuv = positions;\nvec2 iconSize = instanceIconFrames.zw;\nfloat sizePixels = clamp(\nproject_size_to_pixel(instanceSizes * icon.sizeScale, icon.sizeUnits),\nicon.sizeMinPixels, icon.sizeMaxPixels\n);\nfloat iconConstraint = icon.sizeBasis == 0.0 ? iconSize.x : iconSize.y;\nfloat instanceScale = iconConstraint == 0.0 ? 0.0 : sizePixels / iconConstraint;\nvec2 pixelOffset = positions / 2.0 * iconSize + instanceOffsets;\npixelOffset = rotate_by_angle(pixelOffset, instanceAngles) * instanceScale;\npixelOffset += instancePixelOffset;\npixelOffset.y *= -1.0;\nif (icon.billboard) {\ngl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.0), geometry.position);\nDECKGL_FILTER_GL_POSITION(gl_Position, geometry);\nvec3 offset = vec3(pixelOffset, 0.0);\nDECKGL_FILTER_SIZE(offset, geometry);\ngl_Position.xy += project_pixel_size_to_clipspace(offset.xy);\n} else {\nvec3 offset_common = vec3(project_pixel_size(pixelOffset), 0.0);\nDECKGL_FILTER_SIZE(offset_common, geometry);\ngl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, offset_common, geometry.position);\nDECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n}\nvTextureCoords = mix(\ninstanceIconFrames.xy,\ninstanceIconFrames.xy + iconSize,\n(positions.xy + 1.0) / 2.0\n) / icon.iconsTextureDim;\nvColor = instanceColors;\nDECKGL_FILTER_COLOR(vColor, geometry);\nvColorMode = instanceColorModes;\n}\n",fs:"#version 300 es\n#define SHADER_NAME icon-layer-fragment-shader\nprecision highp float;\nuniform sampler2D iconsTexture;\nin float vColorMode;\nin vec4 vColor;\nin vec2 vTextureCoords;\nin vec2 uv;\nout vec4 fragColor;\nvoid main(void) {\ngeometry.uv = uv;\nvec4 texColor = texture(iconsTexture, vTextureCoords);\nvec3 color = mix(texColor.rgb, vColor.rgb, vColorMode);\nfloat a = texColor.a * layer.opacity * vColor.a;\nif (a < icon.alphaCutoff) {\ndiscard;\n}\nfragColor = vec4(color, a);\nDECKGL_FILTER_COLOR(fragColor, geometry);\n}\n",source:To(e),defines:e?{USE_ROW_INDEXES:!0}:{},modules:[Ye,Ze,Je,Io]})}initializeState(){this.state={iconManager:new No(this.context.device,{onUpdate:this._onUpdate.bind(this),onError:this._onError.bind(this)})},this.getAttributeManager().addInstanced({instancePositions:{size:3,type:"float64",fp64:this.use64bitPositions(),transition:!0,accessor:"getPosition"},instanceSizes:{size:1,transition:!0,bufferGroup:"icon-instance-data",accessor:"getSize",defaultValue:1},instanceIconDefs:{size:7,bufferGroup:"icon-instance-data",accessor:"getIcon",transform:this.getInstanceIconDef,shaderAttributes:{instanceOffsets:{size:2,elementOffset:0},instanceIconFrames:{size:4,elementOffset:2},instanceColorModes:{size:1,elementOffset:6}}},instanceColors:{size:this.props.colorFormat.length,type:"unorm8",transition:!0,bufferGroup:"icon-instance-data",accessor:"getColor",defaultValue:Do},instanceAngles:{size:1,transition:!0,bufferGroup:"icon-instance-data",accessor:"getAngle"},instancePixelOffset:{size:2,transition:!0,bufferGroup:"icon-instance-data",accessor:"getPixelOffset"},...this.props.data?.attributes?.rowIndexes?{rowIndexes:{size:1,type:"uint32",noAlloc:!0}}:{}})}updateState(e){super.updateState(e);const{props:t,oldProps:n,changeFlags:i}=e,o=this.getAttributeManager(),{iconAtlas:s,iconMapping:r,data:a,getIcon:l,textureParameters:c}=t,{iconManager:u}=this.state;if("string"==typeof s)return;const f=s||this.internalState.isAsyncPropLoading("iconAtlas");u.setProps({loadOptions:t.loadOptions,autoPacking:!f,iconAtlas:s,iconMapping:f?r:null,textureParameters:c}),f?n.iconMapping!==t.iconMapping&&o.invalidate("getIcon"):(i.dataChanged||i.updateTriggersChanged&&(i.updateTriggersChanged.all||i.updateTriggersChanged.getIcon))&&u.packIcons(a,l),i.extensionsChanged&&(this.state.model?.destroy(),this.state.model=this._getModel(),o.invalidateAll())}get isLoaded(){return super.isLoaded&&this.state.iconManager.isLoaded}finalizeState(e){super.finalizeState(e),this.state.iconManager.finalize()}draw({uniforms:e}){this._drawModel(this.state.model)}_drawModel(e){const{sizeScale:t,sizeBasis:n,sizeMinPixels:o,sizeMaxPixels:s,sizeUnits:r,billboard:a,alphaCutoff:l}=this.props,{iconManager:c}=this.state,u=c.getTexture();if(u){const c={iconsTexture:u,iconsTextureDim:[u.width,u.height],sizeUnits:i[r],sizeScale:t,sizeBasis:"height"===n?1:0,sizeMinPixels:o,sizeMaxPixels:s,billboard:a,alphaCutoff:l};e.shaderInputs.setProps({icon:c}),e.draw(this.context.renderPass)}}_getModel(e=this.props.id){return new xt(this.context.device,{...this.getShaders(),id:e,bufferLayout:this.getAttributeManager().getBufferLayouts(),geometry:new nt({topology:"triangle-strip",attributes:{positions:{size:2,value:new Float32Array([-1,-1,1,-1,-1,1,1,1])}}}),isInstanced:!0})}_onUpdate(e){e?(this.getAttributeManager()?.invalidate("getIcon"),this.setNeedsUpdate()):this.setNeedsRedraw()}_onError(e){const t=this.getCurrentLayer()?.props.onIconError;t?t(e):I.error(e.error.message)()}getInstanceIconDef(e){const{x:t,y:n,width:i,height:o,mask:s,anchorX:r=i/2,anchorY:a=o/2}=this.state.iconManager.getIconMapping(e);return[i/2-r,o/2-a,t,n,i,o,s?1:0]}};Uo.defaultProps=jo,Uo.layerName="IconLayer";var Go="layout(std140) uniform lineUniforms {\n float widthScale;\n float widthMinPixels;\n float widthMaxPixels;\n float useShortestPath;\n highp int widthUnits;\n} line;\n",Vo={name:"line",source:"",vs:Go,fs:Go,uniformTypes:{widthScale:"f32",widthMinPixels:"f32",widthMaxPixels:"f32",useShortestPath:"f32",widthUnits:"i32"}},$o={getSourcePosition:{type:"accessor",value:e=>e.sourcePosition},getTargetPosition:{type:"accessor",value:e=>e.targetPosition},getColor:{type:"accessor",value:[0,0,0,255]},getWidth:{type:"accessor",value:1},widthUnits:"pixels",widthScale:{type:"number",value:1,min:0},widthMinPixels:{type:"number",value:0,min:0},widthMaxPixels:{type:"number",value:Number.MAX_SAFE_INTEGER,min:0},antialiasing:!1},Wo=class extends co{getBounds(){return this.getAttributeManager()?.getBounds(["instanceSourcePositions","instanceTargetPositions"])}getShaders(){const{antialiasing:e}=this.props;return super.getShaders({vs:"#version 300 es\n#define SHADER_NAME line-layer-vertex-shader\nin vec3 positions;\nin vec3 instanceSourcePositions;\nin vec3 instanceTargetPositions;\nin vec3 instanceSourcePositions64Low;\nin vec3 instanceTargetPositions64Low;\nin vec4 instanceColors;\nin float instanceWidths;\nout vec4 vColor;\nout vec2 uv;\nvec2 getExtrusionOffset(vec2 line_clipspace, float offset_direction, float width) {\nvec2 dir_screenspace = normalize(line_clipspace * project.viewportSize);\ndir_screenspace = vec2(-dir_screenspace.y, dir_screenspace.x);\nreturn dir_screenspace * offset_direction * width / 2.0;\n}\nvec3 splitLine(vec3 a, vec3 b, float x) {\nfloat t = (x - a.x) / (b.x - a.x);\nreturn vec3(x, mix(a.yz, b.yz, t));\n}\nvoid main(void) {\ngeometry.worldPosition = instanceSourcePositions;\ngeometry.worldPositionAlt = instanceTargetPositions;\nvec3 source_world = instanceSourcePositions;\nvec3 target_world = instanceTargetPositions;\nvec3 source_world_64low = instanceSourcePositions64Low;\nvec3 target_world_64low = instanceTargetPositions64Low;\nif (line.useShortestPath > 0.5 || line.useShortestPath < -0.5) {\nsource_world.x = mod(source_world.x + 180., 360.0) - 180.;\ntarget_world.x = mod(target_world.x + 180., 360.0) - 180.;\nfloat deltaLng = target_world.x - source_world.x;\nif (deltaLng * line.useShortestPath > 180.) {\nsource_world.x += 360. * line.useShortestPath;\nsource_world = splitLine(source_world, target_world, 180. * line.useShortestPath);\nsource_world_64low = vec3(0.0);\n} else if (deltaLng * line.useShortestPath < -180.) {\ntarget_world.x += 360. * line.useShortestPath;\ntarget_world = splitLine(source_world, target_world, 180. * line.useShortestPath);\ntarget_world_64low = vec3(0.0);\n} else if (line.useShortestPath < 0.) {\ngl_Position = vec4(0.);\nreturn;\n}\n}\nvec4 source_commonspace;\nvec4 target_commonspace;\nvec4 source = project_position_to_clipspace(source_world, source_world_64low, vec3(0.), source_commonspace);\nvec4 target = project_position_to_clipspace(target_world, target_world_64low, vec3(0.), target_commonspace);\nfloat segmentIndex = positions.x;\nvec4 p = mix(source, target, segmentIndex);\ngeometry.position = mix(source_commonspace, target_commonspace, segmentIndex);\nuv = positions.xy;\ngeometry.uv = uv;\ngeometry.pickingColor = picking_getPickingColorFromInstanceID();\nfloat widthPixels = clamp(\nproject_size_to_pixel(instanceWidths * line.widthScale, line.widthUnits),\nline.widthMinPixels, line.widthMaxPixels\n);\nvec3 offset = vec3(\ngetExtrusionOffset(target.xy - source.xy, positions.y, widthPixels),\n0.0);\nDECKGL_FILTER_SIZE(offset, geometry);\n#ifdef ANTIALIASING\nfloat halfWidthPixels = length(offset.xy);\nif (halfWidthPixels > 0.0) {\nfloat coverageScale = 1.0 + 0.5 / project.devicePixelRatio / halfWidthPixels;\noffset.xy *= coverageScale;\nuv.y *= coverageScale;\n}\ngeometry.uv = uv;\n#endif\nDECKGL_FILTER_GL_POSITION(p, geometry);\ngl_Position = p + vec4(project_pixel_size_to_clipspace(offset.xy), 0.0, 0.0);\nvColor = vec4(instanceColors.rgb, instanceColors.a * layer.opacity);\nDECKGL_FILTER_COLOR(vColor, geometry);\n}\n",fs:"#version 300 es\n#define SHADER_NAME line-layer-fragment-shader\nprecision highp float;\nin vec4 vColor;\nin vec2 uv;\nout vec4 fragColor;\nvoid main(void) {\ngeometry.uv = uv;\nfragColor = vColor;\n#ifdef ANTIALIASING\nfloat edgeCoord = abs(uv.y);\nfloat edgePixels = (1.0 - edgeCoord) / max(fwidth(edgeCoord), 1e-6);\nif (edgePixels <= -SMOOTH_EDGE_RADIUS) {\ndiscard;\n}\nfragColor.a *= smoothedge(0.0, edgePixels);\n#endif\nDECKGL_FILTER_COLOR(fragColor, geometry);\n}\n",source:'// ---------- Helper Structures & Functions ----------\n\n// Placeholder filter functions.\nfn deckgl_filter_size(offset: vec3<f32>, geometry: Geometry) -> vec3<f32> {\n return offset;\n}\nfn deckgl_filter_gl_position(p: vec4<f32>, geometry: Geometry) -> vec4<f32> {\n if (picking.isAttribute > 0.5) {\n // For depth picking, write normalized depth into the picking payload.\n // This mirrors the legacy DECKGL_FILTER_GL_POSITION hook on WebGL.\n }\n return p;\n}\n\n// Compute an extrusion offset given a line direction (in clipspace),\n// an offset direction (-1 or 1), and a width in pixels.\n// Assumes a uniform "project" with a viewportSize field is available.\nfn getExtrusionOffset(line_clipspace: vec2<f32>, offset_direction: f32, width: f32) -> vec2<f32> {\n // project.viewportSize should be provided as a uniform (not shown here)\n let dir_screenspace = normalize(line_clipspace * project.viewportSize);\n // Rotate by 90°: (x,y) becomes (-y,x)\n let rotated = vec2<f32>(-dir_screenspace.y, dir_screenspace.x);\n return rotated * offset_direction * width / 2.0;\n}\n\n// Splits the line between two points at a given x coordinate.\n// Interpolates the y and z components.\nfn splitLine(a: vec3<f32>, b: vec3<f32>, x: f32) -> vec3<f32> {\n let t: f32 = (x - a.x) / (b.x - a.x);\n return vec3<f32>(x, a.yz + t * (b.yz - a.yz));\n}\n\n// ---------- Uniforms & Global Structures ----------\n\nstruct LineUniforms {\n widthScale: f32,\n widthMinPixels: f32,\n widthMaxPixels: f32,\n useShortestPath: f32,\n widthUnits: i32,\n};\n\n@group(0) @binding(0)\nvar<uniform> line: LineUniforms;\n\n\n\n// ---------- Vertex Output Structure ----------\n\nstruct Varyings {\n @builtin(position) gl_Position: vec4<f32>,\n @location(0) vColor: vec4<f32>,\n @location(1) uv: vec2<f32>,\n @location(2) pickingColor: vec3<f32>,\n};\n\n// ---------- Vertex Shader Entry Point ----------\n\n@vertex\nfn vertexMain(\n @builtin(instance_index) instanceIndex: u32,\n @location(0) positions: vec3<f32>,\n @location(1) instanceSourcePositions: vec3<f32>,\n @location(2) instanceTargetPositions: vec3<f32>,\n @location(3) instanceSourcePositions64Low: vec3<f32>,\n @location(4) instanceTargetPositions64Low: vec3<f32>,\n @location(5) instanceColors: vec4<f32>,\n @location(6) instanceWidths: f32\n) -> Varyings {\n geometry.worldPosition = instanceSourcePositions;\n geometry.worldPositionAlt = instanceTargetPositions;\n\n var source_world: vec3<f32> = instanceSourcePositions;\n var target_world: vec3<f32> = instanceTargetPositions;\n var source_world_64low: vec3<f32> = instanceSourcePositions64Low;\n var target_world_64low: vec3<f32> = instanceTargetPositions64Low;\n\n // Apply shortest-path adjustments if needed.\n if (line.useShortestPath > 0.5 || line.useShortestPath < -0.5) {\n source_world.x = (source_world.x + 180.0 % 360.0) - 180.0;\n target_world.x = (target_world.x + 180.0 % 360.0) - 180.0;\n let deltaLng: f32 = target_world.x - source_world.x;\n\n if (deltaLng * line.useShortestPath > 180.0) {\n source_world.x = source_world.x + 360.0 * line.useShortestPath;\n source_world = splitLine(source_world, target_world, 180.0 * line.useShortestPath);\n source_world_64low = vec3<f32>(0.0, 0.0, 0.0);\n } else if (deltaLng * line.useShortestPath < -180.0) {\n target_world.x = target_world.x + 360.0 * line.useShortestPath;\n target_world = splitLine(source_world, target_world, 180.0 * line.useShortestPath);\n target_world_64low = vec3<f32>(0.0, 0.0, 0.0);\n } else if (line.useShortestPath < 0.0) {\n var abortOut: Varyings;\n abortOut.gl_Position = vec4<f32>(0.0);\n abortOut.vColor = vec4<f32>(0.0);\n abortOut.uv = vec2<f32>(0.0);\n return abortOut;\n }\n }\n\n // Project Pos and target positions to clip space.\n let sourceResult = project_position_to_clipspace_and_commonspace(source_world, source_world_64low, vec3<f32>(0.0));\n let targetResult = project_position_to_clipspace_and_commonspace(target_world, target_world_64low, vec3<f32>(0.0));\n let sourcePos: vec4<f32> = sourceResult.clipPosition;\n let targetPos: vec4<f32> = targetResult.clipPosition;\n let source_commonspace: vec4<f32> = sourceResult.commonPosition;\n let target_commonspace: vec4<f32> = targetResult.commonPosition;\n\n // Interpolate along the line segment.\n let segmentIndex: f32 = positions.x;\n let p: vec4<f32> = sourcePos + segmentIndex * (targetPos - sourcePos);\n geometry.position = source_commonspace + segmentIndex * (target_commonspace - source_commonspace);\n#ifdef ANTIALIASING\n var uv: vec2<f32> = positions.xy;\n#else\n let uv: vec2<f32> = positions.xy;\n#endif\n geometry.uv = uv;\n geometry.pickingColor = picking_getPickingColorFromIndex(instanceIndex);\n\n // Determine width in pixels.\n let widthPixels: f32 = clamp(\n project_unit_size_to_pixel(instanceWidths * line.widthScale, line.widthUnits),\n line.widthMinPixels, line.widthMaxPixels\n );\n\n // Compute extrusion offset.\n let extrusion: vec2<f32> = getExtrusionOffset(targetPos.xy - sourcePos.xy, positions.y, widthPixels);\n let offset: vec3<f32> = vec3<f32>(extrusion, 0.0);\n\n // Apply deck.gl filter functions.\n#ifdef ANTIALIASING\n var filteredOffset = deckgl_filter_size(offset, geometry);\n let halfWidthPixels = length(filteredOffset.xy);\n if (halfWidthPixels > 0.0) {\n // Keep the declared edge at abs(uv.y) == 1 while rasterizing the outer half of the centered\n // one-device-pixel coverage ramp.\n let coverageScale = 1.0 + 0.5 / project.devicePixelRatio / halfWidthPixels;\n filteredOffset *= coverageScale;\n uv.y *= coverageScale;\n }\n geometry.uv = uv;\n#else\n let filteredOffset = deckgl_filter_size(offset, geometry);\n#endif\n let filteredP = deckgl_filter_gl_position(p, geometry);\n\n let clipOffset: vec2<f32> = project_pixel_size_to_clipspace(filteredOffset.xy);\n let finalPosition: vec4<f32> = filteredP + vec4<f32>(clipOffset, 0.0, 0.0);\n\n // Compute color.\n var vColor: vec4<f32> = vec4<f32>(instanceColors.rgb, instanceColors.a * layer.opacity);\n // vColor = deckgl_filter_color(vColor, geometry);\n\n var output: Varyings;\n output.gl_Position = finalPosition;\n output.vColor = vColor;\n output.uv = uv;\n output.pickingColor = geometry.pickingColor;\n return output;\n}\n\n@fragment\nfn fragmentMain(\n @location(0) vColor: vec4<f32>,\n @location(1) uv: vec2<f32>,\n @location(2) pickingColor: vec3<f32>\n) -> @location(0) vec4<f32> {\n // Create and initialize geometry with the provided uv.\n var geometry: Geometry;\n geometry.uv = uv;\n\n // Start with the input color.\n var fragColor: vec4<f32> = vColor;\n\n#ifdef ANTIALIASING\n // Distance to the edge in device pixels, from the derivative of uv.y. Taken in uniform control\n // flow, ahead of the picking discard below\n let edgeCoord = abs(uv.y);\n let edgePixels = (1.0 - edgeCoord) / max(fwidth(edgeCoord), 1e-6);\n\n // Fragments outside the coverage ramp must not write depth or picking colors.\n if (edgePixels <= -SMOOTH_EDGE_RADIUS) {\n discard;\n }\n\n // Feather one device pixel across the width, before premultiplication below. The ends are left\n // hard - they abut neighbors\n fragColor.a *= smoothedge(0.0, edgePixels);\n#endif\n\n if (picking.isActive > 0.5) {\n if (!picking_isColorValid(pickingColor)) {\n discard;\n }\n return vec4<f32>(pickingColor, 1.0);\n }\n\n if (picking.isHighlightActive > 0.5) {\n let highlightedObjectColor = picking_normalizeColor(picking.highlightedObjectColor);\n if (picking_isColorZero(abs(pickingColor - highlightedObjectColor))) {\n let highLightAlpha = picking.highlightColor.a;\n let blendedAlpha = highLightAlpha + fragColor.a * (1.0 - highLightAlpha);\n if (blendedAlpha > 0.0) {\n let highLightRatio = highLightAlpha / blendedAlpha;\n fragColor = vec4<f32>(\n mix(fragColor.rgb, picking.highlightColor.rgb, highLightRatio),\n blendedAlpha\n );\n } else {\n fragColor = vec4<f32>(fragColor.rgb, 0.0);\n }\n }\n }\n\n // Apply premultiplied alpha as required by transparent canvas\n fragColor = deckgl_premultiplied_alpha(fragColor);\n\n return fragColor;\n}\n',defines:e?{ANTIALIASING:1}:{},modules:[Ye,Ze,Je,Vo]})}get wrapLongitude(){return!1}initializeState(){this.getAttributeManager().addInstanced({instanceSourcePositions:{size:3,type:"float64",fp64:this.use64bitPositions(),transition:!0,accessor:"getSourcePosition"},instanceTargetPositions:{size:3,type:"float64",fp64:this.use64bitPositions(),transition:!0,accessor:"getTargetPosition"},instanceColors:{size:this.props.colorFormat.length,type:"unorm8",transition:!0,accessor:"getColor",defaultValue:[0,0,0,255]},instanceWidths:{size:1,transition:!0,accessor:"getWidth",defaultValue:1}})}updateState(e){super.updateState(e);const{props:t,oldProps:n,changeFlags:i}=e;(i.extensionsChanged||t.antialiasing!==n.antialiasing)&&(this.state.model?.destroy(),this.state.model=this._getModel(),this.getAttributeManager().invalidateAll())}draw({uniforms:e}){const{widthUnits:t,widthScale:n,widthMinPixels:o,widthMaxPixels:s,wrapLongitude:r}=this.props,a=this.state.model,l={widthUnits:i[t],widthScale:n,widthMinPixels:o,widthMaxPixels:s,useShortestPath:r?1:0};a.shaderInputs.setProps({line:l}),a.draw(this.context.renderPass),r&&(a.shaderInputs.setProps({line:{...l,useShortestPath:-1}}),a.draw(this.context.renderPass))}_getModel(){return new xt(this.context.device,{...this.getShaders(),id:this.props.id,bufferLayout:this.getAttributeManager().getBufferLayouts(),geometry:new nt({topology:"triangle-strip",attributes:{positions:{size:3,value:new Float32Array([0,-1,0,0,1,0,1,-1,0,1,1,0])}}}),isInstanced:!0})}};Wo.layerName="LineLayer",Wo.defaultProps=$o;var Ho="layout(std140) uniform pointCloudUniforms {\n float radiusPixels;\n highp int sizeUnits;\n} pointCloud;\n",Zo={name:"pointCloud",source:"",vs:Ho,fs:Ho,uniformTypes:{radiusPixels:"f32",sizeUnits:"i32"}},Yo=[0,0,0,255],qo=[0,0,1],Ko={sizeUnits:"pixels",pointSize:{type:"number",min:0,value:10},antialiasing:!1,getPosition:{type:"accessor",value:e=>e.position},getNormal:{type:"accessor",value:qo},getColor:{type:"accessor",value:Yo},material:!0,radiusPixels:{deprecatedFor:"pointSize"}};var Xo=class extends co{getShaders(){const{antialiasing:e}=this.props;return super.getShaders({vs:"#version 300 es\n#define SHADER_NAME point-cloud-layer-vertex-shader\nin vec3 positions;\nin vec3 instanceNormals;\nin vec4 instanceColors;\nin vec3 instancePositions;\nin vec3 instancePositions64Low;\nout vec4 vColor;\nout vec2 unitPosition;\nvoid main(void) {\ngeometry.worldPosition = instancePositions;\ngeometry.normal = project_normal(instanceNormals);\nunitPosition = positions.xy;\ngeometry.uv = unitPosition;\ngeometry.pickingColor = picking_getPickingColorFromInstanceID();\nvec3 offset = vec3(positions.xy * project_size_to_pixel(pointCloud.radiusPixels, pointCloud.sizeUnits), 0.0);\nDECKGL_FILTER_SIZE(offset, geometry);\n#ifdef ANTIALIASING\nfloat triangleRadiusPixels = length(offset.xy);\nif (triangleRadiusPixels > 0.0) {\nfloat coverageScale = 1.0 + 1.0 / project.devicePixelRatio / triangleRadiusPixels;\noffset.xy *= coverageScale;\nunitPosition *= coverageScale;\ngeometry.uv = unitPosition;\n}\n#endif\ngl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.), geometry.position);\nDECKGL_FILTER_GL_POSITION(gl_Position, geometry);\ngl_Position.xy += project_pixel_size_to_clipspace(offset.xy);\nvec3 lightColor = lighting_getLightColor(instanceColors.rgb, project.cameraPosition, geometry.position.xyz, geometry.normal);\nvColor = vec4(lightColor, instanceColors.a * layer.opacity);\nDECKGL_FILTER_COLOR(vColor, geometry);\n}\n",fs:"#version 300 es\n#define SHADER_NAME point-cloud-layer-fragment-shader\nprecision highp float;\nin vec4 vColor;\nin vec2 unitPosition;\nout vec4 fragColor;\nvoid main(void) {\ngeometry.uv = unitPosition.xy;\nfloat distToCenter = length(unitPosition);\n#ifdef ANTIALIASING\nfloat edgePixels = (1.0 - distToCenter) / max(fwidth(distToCenter), 1e-6);\nif (edgePixels <= -SMOOTH_EDGE_RADIUS) {\n#else\nif (distToCenter > 1.0) {\n#endif\ndiscard;\n}\nfragColor = vColor;\n#ifdef ANTIALIASING\nfragColor.a *= smoothedge(0.0, edgePixels);\n#endif\nDECKGL_FILTER_COLOR(fragColor, geometry);\n}\n",source:"struct PointCloudUniforms {\n radiusPixels: f32,\n sizeUnits: i32,\n};\n\n@group(0) @binding(0)\nvar<uniform> pointCloudUniforms: PointCloudUniforms;\n\nstruct Attributes {\n @builtin(instance_index) instanceIndex : u32,\n @builtin(vertex_index) vertexIndex : u32,\n @location(0) positions: vec3<f32>,\n @location(1) instancePositions: vec3<f32>,\n @location(2) instancePositions64Low: vec3<f32>,\n @location(3) instanceNormals: vec3<f32>,\n @location(4) instanceColors: vec4<f32>\n};\n\nstruct Varyings {\n @builtin(position) position: vec4<f32>,\n @location(0) vColor: vec4<f32>,\n @location(1) unitPosition: vec2<f32>,\n @location(2) pickingColor: vec3<f32>,\n};\n\n@vertex\nfn vertexMain(attributes: Attributes) -> Varyings {\n var varyings: Varyings;\n\n geometry.worldPosition = attributes.instancePositions;\n\n let centerResult = project_position_to_clipspace_and_commonspace(\n attributes.instancePositions,\n attributes.instancePositions64Low,\n vec3<f32>(0.0)\n );\n geometry.position = centerResult.commonPosition;\n geometry.normal = project_normal(attributes.instanceNormals);\n\n // Position on the enclosing triangle. Its edges are tangent to the unit circle.\n varyings.unitPosition = attributes.positions.xy;\n geometry.uv = varyings.unitPosition;\n geometry.pickingColor = picking_getPickingColorFromIndex(attributes.instanceIndex);\n\n // Find the center of the point and add the current vertex\n#ifdef ANTIALIASING\n var offset = vec3<f32>(\n#else\n let offset = vec3<f32>(\n#endif\n attributes.positions.xy *\n project_unit_size_to_pixel(pointCloudUniforms.radiusPixels, pointCloudUniforms.sizeUnits),\n 0.0\n );\n // DECKGL_FILTER_SIZE(offset, geometry);\n#ifdef ANTIALIASING\n let triangleRadiusPixels = length(offset.xy);\n if (triangleRadiusPixels > 0.0) {\n // The triangle's inradius is half its vertex radius. Scaling its vertex radius by one device\n // pixel therefore adds half a device pixel around all three tangent points.\n let coverageScale = 1.0 + 1.0 / project.devicePixelRatio / triangleRadiusPixels;\n offset *= coverageScale;\n varyings.unitPosition *= coverageScale;\n geometry.uv = varyings.unitPosition;\n }\n#endif\n\n varyings.position = centerResult.clipPosition;\n // DECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n let clipPixels = project_pixel_size_to_clipspace(offset.xy);\n varyings.position.x += clipPixels.x;\n varyings.position.y += clipPixels.y;\n\n // Apply lighting\n let lightColor = lighting_getLightColor2(attributes.instanceColors.rgb, project.cameraPosition, geometry.position.xyz, geometry.normal);\n\n // Apply opacity to instance color, or return instance picking color\n varyings.vColor = vec4(lightColor, attributes.instanceColors.a * layer.opacity);\n // DECKGL_FILTER_COLOR(vColor, geometry);\n varyings.pickingColor = geometry.pickingColor;\n\n return varyings;\n}\n\n@fragment\nfn fragmentMain(varyings: Varyings) -> @location(0) vec4<f32> {\n // var geometry: Geometry;\n // geometry.uv = unitPosition.xy;\n\n let distToCenter = length(varyings.unitPosition);\n#ifdef ANTIALIASING\n let edgePixels = (1.0 - distToCenter) / max(fwidth(distToCenter), 1e-6);\n if (edgePixels <= -SMOOTH_EDGE_RADIUS) {\n#else\n if (distToCenter > 1.0) {\n#endif\n discard;\n }\n\n var fragColor: vec4<f32>;\n\n fragColor = varyings.vColor;\n\n#ifdef ANTIALIASING\n fragColor.a *= smoothedge(0.0, edgePixels);\n#endif\n\n if (picking.isActive > 0.5) {\n if (!picking_isColorValid(varyings.pickingColor)) {\n discard;\n }\n return vec4<f32>(varyings.pickingColor, 1.0);\n }\n\n if (picking.isHighlightActive > 0.5) {\n let highlightedObjectColor = picking_normalizeColor(picking.highlightedObjectColor);\n if (picking_isColorZero(abs(varyings.pickingColor - highlightedObjectColor))) {\n let highLightAlpha = picking.highlightColor.a;\n let blendedAlpha = highLightAlpha + fragColor.a * (1.0 - highLightAlpha);\n if (blendedAlpha > 0.0) {\n let highLightRatio = highLightAlpha / blendedAlpha;\n fragColor = vec4<f32>(\n mix(fragColor.rgb, picking.highlightColor.rgb, highLightRatio),\n blendedAlpha\n );\n } else {\n fragColor = vec4<f32>(fragColor.rgb, 0.0);\n }\n }\n }\n\n // Apply premultiplied alpha as required by transparent canvas\n fragColor = deckgl_premultiplied_alpha(fragColor);\n\n return fragColor;\n}\n",defines:e?{ANTIALIASING:1}:{},modules:[Ye,Ze,We,Je,Zo]})}initializeState(){this.getAttributeManager().addInstanced({instancePositions:{size:3,type:"float64",fp64:this.use64bitPositions(),transition:!0,accessor:"getPosition"},instanceNormals:{size:3,transition:!0,accessor:"getNormal",defaultValue:qo},instanceColors:{size:this.props.colorFormat.length,type:"unorm8",transition:!0,accessor:"getColor",defaultValue:Yo}})}updateState(e){const{changeFlags:t,props:n,oldProps:i}=e;super.updateState(e),(t.extensionsChanged||n.antialiasing!==i.antialiasing)&&(this.state.model?.destroy(),this.state.model=this._getModel(),this.getAttributeManager().invalidateAll()),t.dataChanged&&function(e){const{header:t,attributes:n}=e;if(t&&n&&(e.length=t.vertexCount,n.POSITION&&(n.instancePositions=n.POSITION),n.NORMAL&&(n.instanceNormals=n.NORMAL),n.COLOR_0)){const{size:e,value:t}=n.COLOR_0;n.instanceColors={size:e,type:"unorm8",value:t}}}(n.data)}draw({uniforms:e}){const{pointSize:t,sizeUnits:n}=this.props,o=this.state.model,s={sizeUnits:i[n],radiusPixels:t};o.shaderInputs.setProps({pointCloud:s}),o.draw(this.context.renderPass)}_getModel(){const e=[];for(let t=0;t<3;t++){const n=t/3*Math.PI*2;e.push(2*Math.cos(n),2*Math.sin(n),0)}return new xt(this.context.device,{...this.getShaders(),id:this.props.id,bufferLayout:this.getAttributeManager().getBufferLayouts(),geometry:new nt({topology:"triangle-list",attributes:{positions:new Float32Array(e)}}),isInstanced:!0})}};Xo.layerName="PointCloudLayer",Xo.defaultProps=Ko;var Jo="layout(std140) uniform scatterplotUniforms {\n float radiusScale;\n float radiusMinPixels;\n float radiusMaxPixels;\n float lineWidthScale;\n float lineWidthMinPixels;\n float lineWidthMaxPixels;\n float stroked;\n float filled;\n bool antialiasing;\n bool billboard;\n highp int radiusUnits;\n highp int lineWidthUnits;\n} scatterplot;\n",Qo={name:"scatterplot",vs:Jo,fs:Jo,source:"",uniformTypes:{radiusScale:"f32",radiusMinPixels:"f32",radiusMaxPixels:"f32",lineWidthScale:"f32",lineWidthMinPixels:"f32",lineWidthMaxPixels:"f32",stroked:"f32",filled:"f32",antialiasing:"f32",billboard:"f32",radiusUnits:"i32",lineWidthUnits:"i32"}},es="// Main shaders\n\nstruct ScatterplotUniforms {\n radiusScale: f32,\n radiusMinPixels: f32,\n radiusMaxPixels: f32,\n lineWidthScale: f32,\n lineWidthMinPixels: f32,\n lineWidthMaxPixels: f32,\n stroked: f32,\n filled: i32,\n antialiasing: i32,\n billboard: i32,\n radiusUnits: i32,\n lineWidthUnits: i32,\n};\n\n@group(0) @binding(0) var<uniform> scatterplot: ScatterplotUniforms;\n\nstruct Attributes {\n @builtin(instance_index) instanceIndex : u32,\n @builtin(vertex_index) vertexIndex : u32,\n @location(0) positions: vec3<f32>,\n @location(1) instancePositions: vec3<f32>,\n @location(2) instancePositions64Low: vec3<f32>,\n @location(3) instanceRadius: f32,\n @location(4) instanceLineWidths: f32,\n @location(5) instanceFillColors: vec4<f32>,\n @location(6) instanceLineColors: vec4<f32>,\n @location(7) instancePixelOffset: vec2<f32>,\n PICKING_COLOR_ATTRIBUTE\n};\n\nstruct Varyings {\n @builtin(position) position: vec4<f32>,\n @location(0) vFillColor: vec4<f32>,\n @location(1) vLineColor: vec4<f32>,\n @location(2) unitPosition: vec2<f32>,\n @location(3) innerUnitRadius: f32,\n @location(4) outerRadiusPixels: f32,\n @location(5) pickingColor: vec3<f32>,\n @location(6) clipCoordinates: vec2<f32>,\n};\n\n@vertex\nfn vertexMain(attributes: Attributes) -> Varyings {\n var varyings: Varyings;\n\n // Draw an inline geometry constant array clip space triangle to verify that rendering works.\n // var positions = array<vec2<f32>, 3>(vec2(0.0, 0.5), vec2(-0.5, -0.5), vec2(0.5, -0.5));\n // if (attributes.instanceIndex == 0) {\n // varyings.position = vec4<f32>(positions[attributes.vertexIndex], 0.0, 1.0);\n // return varyings;\n // }\n\n geometry.worldPosition = attributes.instancePositions;\n\n // Multiply out radius and clamp to limits\n varyings.outerRadiusPixels = clamp(\n project_unit_size_to_pixel(scatterplot.radiusScale * attributes.instanceRadius, scatterplot.radiusUnits),\n scatterplot.radiusMinPixels, scatterplot.radiusMaxPixels\n );\n\n // Multiply out line width and clamp to limits\n let lineWidthPixels = clamp(\n project_unit_size_to_pixel(scatterplot.lineWidthScale * attributes.instanceLineWidths, scatterplot.lineWidthUnits),\n scatterplot.lineWidthMinPixels, scatterplot.lineWidthMaxPixels\n );\n\n // outer radius needs to offset by half stroke width\n varyings.outerRadiusPixels += scatterplot.stroked * lineWidthPixels / 2.0;\n // Expand geometry to accommodate edge smoothing\n // WGSL selects the second value when the condition is true, so keep the antialiased path second.\n let edgePadding = select(\n 1.0,\n (varyings.outerRadiusPixels + SMOOTH_EDGE_RADIUS) / varyings.outerRadiusPixels,\n scatterplot.antialiasing != 0\n );\n\n // position on the containing square in [-1, 1] space\n varyings.unitPosition = edgePadding * attributes.positions.xy;\n geometry.uv = varyings.unitPosition;\n geometry.pickingColor = PICKING_COLOR_VALUE;\n\n varyings.innerUnitRadius = 1.0 - scatterplot.stroked * lineWidthPixels / varyings.outerRadiusPixels;\n\n if (scatterplot.billboard != 0) {\n let projectedPosition = project_position_to_clipspace_and_commonspace(\n attributes.instancePositions,\n attributes.instancePositions64Low,\n vec3<f32>(0.0)\n );\n geometry.position = projectedPosition.commonPosition;\n varyings.position = projectedPosition.clipPosition;\n // DECKGL_FILTER_GL_POSITION(varyings.position, geometry);\n var offset = edgePadding * attributes.positions * varyings.outerRadiusPixels;\n offset = vec3<f32>(offset.xy + attributes.instancePixelOffset, offset.z);\n // DECKGL_FILTER_SIZE(offset, geometry);\n let clipPixels = project_pixel_size_to_clipspace(offset.xy);\n varyings.position = vec4<f32>(varyings.position.x + clipPixels.x, varyings.position.y + clipPixels.y, varyings.position.z, varyings.position.w);\n geometry.position = vec4<f32>(\n geometry.position.xy + project_pixel_size_vec2(offset.xy),\n geometry.position.zw\n );\n } else {\n var offset = edgePadding * attributes.positions * project_pixel_size_float(varyings.outerRadiusPixels);\n offset = vec3<f32>(offset.xy + project_pixel_size_vec2(attributes.instancePixelOffset), offset.z);\n // DECKGL_FILTER_SIZE(offset, geometry);\n let projectedPosition = project_position_to_clipspace_and_commonspace(\n attributes.instancePositions,\n attributes.instancePositions64Low,\n offset\n );\n geometry.position = projectedPosition.commonPosition;\n varyings.position = projectedPosition.clipPosition;\n // DECKGL_FILTER_GL_POSITION(varyings.position, geometry);\n }\n\n varyings.clipCoordinates = geometry.position.xy;\n clip_filterPosition(&varyings.position, geometry.worldPosition.xy);\n\n // Apply opacity to instance color, or return instance picking color\n varyings.vFillColor = vec4<f32>(attributes.instanceFillColors.rgb, attributes.instanceFillColors.a * layer.opacity);\n // DECKGL_FILTER_COLOR(varyings.vFillColor, geometry);\n varyings.vLineColor = vec4<f32>(attributes.instanceLineColors.rgb, attributes.instanceLineColors.a * layer.opacity);\n // DECKGL_FILTER_COLOR(varyings.vLineColor, geometry);\n varyings.pickingColor = geometry.pickingColor;\n\n return varyings;\n}\n\n@fragment\nfn fragmentMain(varyings: Varyings) -> @location(0) vec4<f32> {\n // var geometry: Geometry;\n // geometry.uv = unitPosition;\n\n let distToCenter = length(varyings.unitPosition) * varyings.outerRadiusPixels;\n let inCircle = select(\n step(distToCenter, varyings.outerRadiusPixels),\n smoothedge(distToCenter, varyings.outerRadiusPixels),\n scatterplot.antialiasing != 0\n );\n\n if (inCircle == 0.0) {\n discard;\n }\n\n var fragColor: vec4<f32>;\n\n if (scatterplot.stroked != 0) {\n let isLine = select(\n step(varyings.innerUnitRadius * varyings.outerRadiusPixels, distToCenter),\n smoothedge(varyings.innerUnitRadius * varyings.outerRadiusPixels, distToCenter),\n scatterplot.antialiasing != 0\n );\n\n if (scatterplot.filled != 0) {\n fragColor = mix(varyings.vFillColor, varyings.vLineColor, isLine);\n } else {\n if (isLine == 0.0) {\n discard;\n }\n fragColor = vec4<f32>(varyings.vLineColor.rgb, varyings.vLineColor.a * isLine);\n }\n } else if (scatterplot.filled == 0) {\n discard;\n } else {\n fragColor = varyings.vFillColor;\n }\n\n fragColor.a *= inCircle;\n\n clip_filterColor(varyings.clipCoordinates);\n\n if (picking.isActive > 0.5) {\n if (!picking_isColorValid(varyings.pickingColor)) {\n discard;\n }\n return vec4<f32>(varyings.pickingColor, 1.0);\n }\n\n if (picking.isHighlightActive > 0.5) {\n let highlightedObjectColor = picking_normalizeColor(picking.highlightedObjectColor);\n if (picking_isColorZero(abs(varyings.pickingColor - highlightedObjectColor))) {\n let highLightAlpha = picking.highlightColor.a;\n let blendedAlpha = highLightAlpha + fragColor.a * (1.0 - highLightAlpha);\n if (blendedAlpha > 0.0) {\n let highLightRatio = highLightAlpha / blendedAlpha;\n fragColor = vec4<f32>(\n mix(fragColor.rgb, picking.highlightColor.rgb, highLightRatio),\n blendedAlpha\n );\n } else {\n fragColor = vec4<f32>(fragColor.rgb, 0.0);\n }\n }\n }\n\n // Apply premultiplied alpha as required by transparent canvas\n fragColor = deckgl_premultiplied_alpha(fragColor);\n\n return fragColor;\n // return vec4<f32>(0, 0, 1, 1);\n}\n";function ts(e){return es.replace("PICKING_COLOR_ATTRIBUTE",e?"@location(8) rowIndexes: u32,":"").replace("PICKING_COLOR_VALUE",e?"picking_getPickingColorFromIndex(attributes.rowIndexes)":"picking_getPickingColorFromIndex(attributes.instanceIndex)")}var ns={name:"clip",source:"struct ClipUniforms {\n enabled: i32,\n mode: i32,\n bounds: vec4<f32>,\n};\n\n@group(2) @binding(auto) var<uniform> clipUniforms: ClipUniforms;\n\nfn clip_isInBounds(coordinates: vec2<f32>) -> bool {\n return coordinates.x >= clipUniforms.bounds.x &&\n coordinates.y >= clipUniforms.bounds.y &&\n coordinates.x < clipUniforms.bounds.z &&\n coordinates.y < clipUniforms.bounds.w;\n}\n\nfn clip_filterPosition(position: ptr<function, vec4<f32>>, instanceCoordinates: vec2<f32>) {\n if (\n clipUniforms.enabled != 0 &&\n clipUniforms.mode == 1 &&\n !clip_isInBounds(instanceCoordinates)\n ) {\n *position = vec4<f32>(2.0, 2.0, 2.0, 1.0);\n }\n}\n\nfn clip_filterColor(geometryCoordinates: vec2<f32>) {\n if (\n clipUniforms.enabled != 0 &&\n clipUniforms.mode == 0 &&\n !clip_isInBounds(geometryCoordinates)\n ) {\n discard;\n }\n}\n",props:{},uniforms:{},bindingLayout:[{name:"clip",group:2}],uniformTypes:{enabled:"i32",mode:"i32",bounds:"vec4<f32>"},defaultUniforms:{enabled:0,mode:0,bounds:[0,0,1,1]},getUniforms(e={}){const t={};return void 0!==e.enabled&&(t.enabled=e.enabled?1:0),void 0!==e.mode&&(t.mode="instance"===e.mode?1:0),void 0!==e.bounds&&(t.bounds=e.bounds),t}},is=[0,0,0,255],os={radiusUnits:"meters",radiusScale:{type:"number",min:0,value:1},radiusMinPixels:{type:"number",min:0,value:0},radiusMaxPixels:{type:"number",min:0,value:Number.MAX_SAFE_INTEGER},lineWidthUnits:"meters",lineWidthScale:{type:"number",min:0,value:1},lineWidthMinPixels:{type:"number",min:0,value:0},lineWidthMaxPixels:{type:"number",min:0,value:Number.MAX_SAFE_INTEGER},stroked:!1,filled:!0,billboard:!1,antialiasing:!0,getPosition:{type:"accessor",value:e=>e.position},getRadius:{type:"accessor",value:1},getFillColor:{type:"accessor",value:is},getLineColor:{type:"accessor",value:is},getLineWidth:{type:"accessor",value:1},getPixelOffset:{type:"accessor",value:[0,0]},strokeWidth:{deprecatedFor:"getLineWidth"},outline:{deprecatedFor:"stroked"},getColor:{deprecatedFor:["getFillColor","getLineColor"]}},ss=class extends co{getShaders(){const e=Boolean(this.props.data?.attributes?.rowIndexes);return super.getShaders({vs:"#version 300 es\n#define SHADER_NAME scatterplot-layer-vertex-shader\nin vec3 positions;\nin vec3 instancePositions;\nin vec3 instancePositions64Low;\nin float instanceRadius;\nin float instanceLineWidths;\nin vec4 instanceFillColors;\nin vec4 instanceLineColors;\n#ifdef USE_ROW_INDEXES\nin float rowIndexes;\n#endif\nin vec2 instancePixelOffset;\nout vec4 vFillColor;\nout vec4 vLineColor;\nout vec2 unitPosition;\nout float innerUnitRadius;\nout float outerRadiusPixels;\nvoid main(void) {\ngeometry.worldPosition = instancePositions;\nouterRadiusPixels = clamp(\nproject_size_to_pixel(scatterplot.radiusScale * instanceRadius, scatterplot.radiusUnits),\nscatterplot.radiusMinPixels, scatterplot.radiusMaxPixels\n);\nfloat lineWidthPixels = clamp(\nproject_size_to_pixel(scatterplot.lineWidthScale * instanceLineWidths, scatterplot.lineWidthUnits),\nscatterplot.lineWidthMinPixels, scatterplot.lineWidthMaxPixels\n);\nouterRadiusPixels += scatterplot.stroked * lineWidthPixels / 2.0;\nfloat edgePadding = scatterplot.antialiasing ? (outerRadiusPixels + SMOOTH_EDGE_RADIUS) / outerRadiusPixels : 1.0;\nunitPosition = edgePadding * positions.xy;\ngeometry.uv = unitPosition;\n#ifdef USE_ROW_INDEXES\ngeometry.pickingColor = picking_getPickingColorFromIndex(rowIndexes);\n#else\ngeometry.pickingColor = picking_getPickingColorFromInstanceID();\n#endif\ninnerUnitRadius = 1.0 - scatterplot.stroked * lineWidthPixels / outerRadiusPixels;\nif (scatterplot.billboard) {\ngl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.0), geometry.position);\nDECKGL_FILTER_GL_POSITION(gl_Position, geometry);\nvec3 offset = edgePadding * positions * outerRadiusPixels;\noffset.xy += instancePixelOffset;\nDECKGL_FILTER_SIZE(offset, geometry);\ngl_Position.xy += project_pixel_size_to_clipspace(offset.xy);\n} else {\nvec3 offset = edgePadding * positions * project_pixel_size(outerRadiusPixels);\noffset.xy += project_pixel_size(instancePixelOffset);\nDECKGL_FILTER_SIZE(offset, geometry);\ngl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, offset, geometry.position);\nDECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n}\nvFillColor = vec4(instanceFillColors.rgb, instanceFillColors.a * layer.opacity);\nDECKGL_FILTER_COLOR(vFillColor, geometry);\nvLineColor = vec4(instanceLineColors.rgb, instanceLineColors.a * layer.opacity);\nDECKGL_FILTER_COLOR(vLineColor, geometry);\n}\n",fs:"#version 300 es\n#define SHADER_NAME scatterplot-layer-fragment-shader\nprecision highp float;\nin vec4 vFillColor;\nin vec4 vLineColor;\nin vec2 unitPosition;\nin float innerUnitRadius;\nin float outerRadiusPixels;\nout vec4 fragColor;\nvoid main(void) {\ngeometry.uv = unitPosition;\nfloat distToCenter = length(unitPosition) * outerRadiusPixels;\nfloat inCircle = scatterplot.antialiasing ?\nsmoothedge(distToCenter, outerRadiusPixels) :\nstep(distToCenter, outerRadiusPixels);\nif (inCircle == 0.0) {\ndiscard;\n}\nif (scatterplot.stroked > 0.5) {\nfloat isLine = scatterplot.antialiasing ?\nsmoothedge(innerUnitRadius * outerRadiusPixels, distToCenter) :\nstep(innerUnitRadius * outerRadiusPixels, distToCenter);\nif (scatterplot.filled > 0.5) {\nfragColor = mix(vFillColor, vLineColor, isLine);\n} else {\nif (isLine == 0.0) {\ndiscard;\n}\nfragColor = vec4(vLineColor.rgb, vLineColor.a * isLine);\n}\n} else if (scatterplot.filled < 0.5) {\ndiscard;\n} else {\nfragColor = vFillColor;\n}\nfragColor.a *= inCircle;\nDECKGL_FILTER_COLOR(fragColor, geometry);\n}\n",source:ts(e),defines:e?{USE_ROW_INDEXES:!0}:{},modules:[Ye,Ze,Je,Qo,..."webgpu"===this.context.device.type?[ns]:[]]})}initializeState(){const e=this.props.data?.attributes?.rowIndexes?{rowIndexes:{size:1,type:"uint32",noAlloc:!0}}:{};this.getAttributeManager().addInstanced({instancePositions:{size:3,type:"float64",fp64:this.use64bitPositions(),transition:!0,accessor:"getPosition"},instanceRadius:{size:1,transition:!0,accessor:"getRadius",defaultValue:1,bufferGroup:"scatterplot-instance-data"},instanceFillColors:{size:this.props.colorFormat.length,transition:!0,type:"unorm8",accessor:"getFillColor",defaultValue:[0,0,0,255],bufferGroup:"scatterplot-instance-data"},instanceLineColors:{size:this.props.colorFormat.length,transition:!0,type:"unorm8",accessor:"getLineColor",defaultValue:[0,0,0,255],bufferGroup:"scatterplot-instance-data"},instanceLineWidths:{size:1,transition:!0,accessor:"getLineWidth",defaultValue:1,bufferGroup:"scatterplot-instance-data"},instancePixelOffset:{size:2,transition:!0,accessor:"getPixelOffset",bufferGroup:"scatterplot-instance-data"},...e})}updateState(e){super.updateState(e),e.changeFlags.extensionsChanged&&(this.state.model?.destroy(),this.state.model=this._getModel(),this.getAttributeManager().invalidateAll())}draw({uniforms:e}){const{radiusUnits:t,radiusScale:n,radiusMinPixels:o,radiusMaxPixels:s,stroked:r,filled:a,billboard:l,antialiasing:c,lineWidthUnits:u,lineWidthScale:f,lineWidthMinPixels:d,lineWidthMaxPixels:p}=this.props,g={stroked:r,filled:a,billboard:l,antialiasing:c,radiusUnits:i[t],radiusScale:n,radiusMinPixels:o,radiusMaxPixels:s,lineWidthUnits:i[u],lineWidthScale:f,lineWidthMinPixels:d,lineWidthMaxPixels:p},h=this.state.model;h.shaderInputs.setProps({scatterplot:g}),h.draw(this.context.renderPass)}_getModel(){return new xt(this.context.device,{...this.getShaders(),id:this.props.id,bufferLayout:this.getAttributeManager().getBufferLayouts(),geometry:new nt({topology:"triangle-strip",attributes:{positions:{size:3,value:new Float32Array([-1,-1,0,1,-1,0,-1,1,0,1,1,0])}}}),isInstanced:!0})}};ss.defaultProps=os,ss.layerName="ScatterplotLayer";var rs=1,as=-1;function ls(e,t,n={}){return function(e,t={}){return Math.sign(us(e,t))}(e,n)!==t&&(function(e,t){const{start:n=0,end:i=e.length,size:o=2}=t,s=(i-n)/o,r=Math.floor(s/2);for(let a=0;a<r;++a){const t=n+a*o,i=n+(s-1-a)*o;for(let n=0;n<o;++n){const o=e[t+n];e[t+n]=e[i+n],e[i+n]=o}}}(e,n),!0)}var cs={x:0,y:1,z:2};function us(e,t={}){const{start:n=0,end:i=e.length,plane:o="xy"}=t,s=t.size||2;let r=0;const a=cs[o[0]],l=cs[o[1]];for(let c=n,u=i-s;c<i;c+=s)r+=(e[c+a]-e[u+a])*(e[c+l]+e[u+l]),u=c;return r/2}function fs(e,t){const n=t.length,i=e.length;if(i>0){let o=!0;for(let s=0;s<n;s++)if(e[i-n+s]!==t[s]){o=!1;break}if(o)return!1}for(let o=0;o<n;o++)e[i+o]=t[o];return!0}function ds(e,t){const n=t.length;for(let i=0;i<n;i++)e[i]=t[i]}function ps(e,t,n,i,o=[]){const s=i+t*n;for(let r=0;r<n;r++)o[r]=e[s+r];return o}function gs(e,t,n,i,o=[]){let s,r;if(8&n)s=(i[3]-e[1])/(t[1]-e[1]),r=3;else if(4&n)s=(i[1]-e[1])/(t[1]-e[1]),r=1;else if(2&n)s=(i[2]-e[0])/(t[0]-e[0]),r=2;else{if(!(1&n))return null;s=(i[0]-e[0])/(t[0]-e[0]),r=0}for(let a=0;a<e.length;a++)o[a]=(1&r)===a?i[r]:s*(t[a]-e[a])+e[a];return o}function hs(e,t){let n=0;return e[0]<t[0]?n|=1:e[0]>t[2]&&(n|=2),e[1]<t[1]?n|=4:e[1]>t[3]&&(n|=8),n}function vs(e,t){const{size:n=2,broken:i=!1,gridResolution:o=10,gridOffset:s=[0,0],startIndex:r=0,endIndex:a=e.length}=t||{},l=(a-r)/n;let c=[];const u=[c],f=ps(e,0,n,r);let d,p;const g=xs(f,o,s,[]),h=[];fs(c,f);for(let v=1;v<l;v++){for(d=ps(e,v,n,r,d),p=hs(d,g);p;){gs(f,d,p,g,h);const e=hs(h,g);e&&(gs(f,h,e,g,h),p=e),fs(c,h),ds(f,h),ys(g,o,p),i&&c.length>n&&(c=[],u.push(c),fs(c,f)),p=hs(d,g)}fs(c,d),ds(f,d)}return i?u:u[0]}function ms(e,t=null,n){if(!e.length)return[];const{size:i=2,gridResolution:o=10,gridOffset:s=[0,0],edgeTypes:r=!1}=n||{},a=[],l=[{pos:e,types:r?new Array(e.length/i).fill(1):null,holes:t||[]}],c=[[],[]];let u=[];for(;l.length;){const{pos:e,types:t,holes:n}=l.shift();bs(e,i,n[0]||e.length,c),u=xs(c[0],o,s,u);const f=hs(c[1],u);if(f){let o=_s(e,t,i,0,n[0]||e.length,u,f);const s={pos:o[0].pos,types:o[0].types,holes:[]},a={pos:o[1].pos,types:o[1].types,holes:[]};l.push(s,a);for(let l=0;l<n.length;l++)o=_s(e,t,i,n[l],n[l+1]||e.length,u,f),o[0]&&(s.holes.push(s.pos.length),s.pos=Ps(s.pos,o[0].pos),r&&(s.types=Ps(s.types,o[0].types))),o[1]&&(a.holes.push(a.pos.length),a.pos=Ps(a.pos,o[1].pos),r&&(a.types=Ps(a.types,o[1].types)))}else{const i={positions:e};r&&(i.edgeTypes=t),n.length&&(i.holeIndices=n),a.push(i)}}return a}function _s(e,t,n,i,o,s,r){const a=(o-i)/n,l=[],c=[],u=[],f=[],d=[];let p,g,h;const v=ps(e,a-1,n,i);let m=Math.sign(8&r?v[1]-s[3]:v[0]-s[2]),_=t&&t[a-1],x=0,y=0;for(let b=0;b<a;b++)p=ps(e,b,n,i,p),g=Math.sign(8&r?p[1]-s[3]:p[0]-s[2]),h=t&&t[i/n+b],g&&m&&m!==g&&(gs(v,p,r,s,d),fs(l,d)&&u.push(_),fs(c,d)&&f.push(_)),g<=0?(fs(l,p)&&u.push(h),x-=g):u.length&&(u[u.length-1]=0),g>=0?(fs(c,p)&&f.push(h),y+=g):f.length&&(f[f.length-1]=0),ds(v,p),m=g,_=h;return[x?{pos:l,types:t&&u}:null,y?{pos:c,types:t&&f}:null]}function xs(e,t,n,i){const o=Math.floor((e[0]-n[0])/t)*t+n[0],s=Math.floor((e[1]-n[1])/t)*t+n[1];return i[0]=o,i[1]=s,i[2]=o+t,i[3]=s+t,i}function ys(e,t,n){8&n?(e[1]+=t,e[3]+=t):4&n?(e[1]-=t,e[3]-=t):2&n?(e[0]+=t,e[2]+=t):1&n&&(e[0]-=t,e[2]-=t)}function bs(e,t,n,i){let o=1/0,s=-1/0,r=1/0,a=-1/0;for(let l=0;l<n;l+=t){const t=e[l],n=e[l+1];o=t<o?t:o,s=t>s?t:s,r=n<r?n:r,a=n>a?n:a}return i[0][0]=o,i[0][1]=r,i[1][0]=s,i[1][1]=a,i}function Ps(e,t){for(let n=0;n<t.length;n++)e.push(t[n]);return e}function Cs(e,t,n,i){let o=-1,s=-1;for(let r=n+1;r<i;r+=t){const t=Math.abs(e[r]);t>o&&(o=t,s=r-1)}return s}function ws(e,t,n,i,o=85.051129){const s=e[n],r=e[i-t];if(Math.abs(s-r)>180){const i=ps(e,0,t,n);i[0]+=360*Math.round((r-s)/360),fs(e,i),i[1]=Math.sign(i[1])*o,fs(e,i),i[0]=s,fs(e,i)}}function Ss(e,t,n,i){let o,s=e[0];for(let r=n;r<i;r+=t){o=e[r];const t=o-s;(t>180||t<-180)&&(o-=360*Math.round(t/360)),e[r]=s=o}}function Ls(e,t){let n;const i=e.length/t;for(let s=0;s<i&&(n=e[s*t],(n+180)%360==0);s++);const o=360*-Math.round(n/360);if(0!==o)for(let s=0;s<i;s++)e[s*t]+=o}var As=class extends nt{constructor(e){const{indices:t,attributes:n}=function(e){const{radius:t,height:n=1,nradial:i=10}=e;let{vertices:o}=e;o&&(I.assert(o.length>=i),o=o.flatMap(e=>[e[0],e[1]]),ls(o,as));const s=n>0,r=i+1,a=s?3*r+1:i,l=2*Math.PI/i,c=new Uint16Array(s?3*i*2:0),u=new Float32Array(3*a),f=new Float32Array(3*a);let d=0;if(s){for(let e=0;e<r;e++){const s=e*l,r=e%i,a=Math.sin(s),c=Math.cos(s);for(let e=0;e<2;e++)u[d+0]=o?o[2*r]:c*t,u[d+1]=o?o[2*r+1]:a*t,u[d+2]=(.5-e)*n,f[d+0]=o?o[2*r]:c,f[d+1]=o?o[2*r+1]:a,d+=3}u[d+0]=u[d-3],u[d+1]=u[d-2],u[d+2]=u[d-1],d+=3}for(let p=s?0:1;p<r;p++){const e=Math.floor(p/2)*Math.sign(.5-p%2),s=e*l,r=(e+i)%i,a=Math.sin(s),c=Math.cos(s);u[d+0]=o?o[2*r]:c*t,u[d+1]=o?o[2*r+1]:a*t,u[d+2]=n/2,f[d+2]=1,d+=3}if(s){let e=0;for(let t=0;t<i;t++)c[e++]=2*t+0,c[e++]=2*t+2,c[e++]=2*t+0,c[e++]=2*t+1,c[e++]=2*t+1,c[e++]=2*t+3}return{indices:c,attributes:{POSITION:{size:3,value:u},NORMAL:{size:3,value:f}}}}(e);super({...e,topology:"line-list",indices:t,attributes:n})}};var Is="layout(std140) uniform columnUniforms {\n float radius;\n float angle;\n vec2 offset;\n bool extruded;\n bool stroked;\n bool isStroke;\n float coverage;\n float elevationScale;\n float edgeDistance;\n float widthScale;\n float widthMinPixels;\n float widthMaxPixels;\n highp int radiusUnits;\n highp int widthUnits;\n} column;\n",Es={name:"column",source:"struct ColumnUniforms {\n radius: f32,\n angle: f32,\n offset: vec2<f32>,\n extruded: f32,\n stroked: f32,\n isStroke: f32,\n coverage: f32,\n elevationScale: f32,\n edgeDistance: f32,\n widthScale: f32,\n widthMinPixels: f32,\n widthMaxPixels: f32,\n radiusUnits: i32,\n widthUnits: i32,\n};\n\n@group(0) @binding(auto) var<uniform> column: ColumnUniforms;\n",vs:Is,fs:Is,uniformTypes:{radius:"f32",angle:"f32",offset:"vec2<f32>",extruded:"f32",stroked:"f32",isStroke:"f32",coverage:"f32",elevationScale:"f32",edgeDistance:"f32",widthScale:"f32",widthMinPixels:"f32",widthMaxPixels:"f32",radiusUnits:"i32",widthUnits:"i32"}},Ts="struct Attributes {\n @builtin(instance_index) instanceIndex: u32,\n @location(0) positions: vec3<f32>,\n @location(1) normals: vec3<f32>,\n @location(2) instancePositions: vec3<f32>,\n @location(3) instancePositions64Low: vec3<f32>,\n @location(4) instanceElevations: f32,\n @location(5) instanceFillColors: vec4<f32>,\n @location(6) instanceLineColors: vec4<f32>,\n @location(7) instanceStrokeWidths: f32\n};\n\nfn getRotationMatrix(angle: f32) -> mat2x2<f32> {\n let s = sin(angle);\n let c = cos(angle);\n return mat2x2<f32>(\n vec2<f32>(c, s),\n vec2<f32>(-s, c)\n );\n}\n\nfn getOffset(\n positions: vec3<f32>,\n strokeOffsetRatio: f32,\n dotRadius: f32,\n rotationMatrix: mat2x2<f32>\n) -> vec3<f32> {\n var offset = (rotationMatrix * positions.xy * strokeOffsetRatio + column.offset) * dotRadius;\n if (column.radiusUnits == UNIT_METERS) {\n offset = project_size_vec2(offset);\n } else if (column.radiusUnits == UNIT_PIXELS) {\n offset = project_pixel_size_vec2(offset);\n }\n return vec3<f32>(offset, 0.0);\n}\n",Os=`${Ts}\n\nstruct Varyings {\n @builtin(position) position: vec4<f32>,\n @location(0) color: vec4<f32>\n};\n\n@vertex\nfn vertexMain(attributes: Attributes) -> Varyings {\n var varyings: Varyings;\n\n geometry.worldPosition = attributes.instancePositions;\n geometry.pickingColor = picking_getPickingColorFromIndex(attributes.instanceIndex);\n\n let isStroke = column.isStroke > 0.5;\n let baseColor = select(attributes.instanceFillColors, attributes.instanceLineColors, isStroke);\n let rotationMatrix = getRotationMatrix(column.angle);\n\n var elevation = 0.0;\n var strokeOffsetRatio = 1.0;\n\n if (column.extruded > 0.5) {\n elevation =\n attributes.instanceElevations * (attributes.positions.z + 1.0) / 2.0 * column.elevationScale;\n } else if (column.stroked > 0.5) {\n let widthPixels = clamp(\n project_unit_size_to_pixel(attributes.instanceStrokeWidths * column.widthScale, column.widthUnits),\n column.widthMinPixels,\n column.widthMaxPixels\n ) / 2.0;\n let halfOffset =\n project_pixel_size_float(widthPixels) /\n project_size_float(column.edgeDistance * column.coverage * column.radius);\n if (isStroke) {\n strokeOffsetRatio -= sign(attributes.positions.z) * halfOffset;\n } else {\n strokeOffsetRatio -= halfOffset;\n }\n }\n\n let shouldRender = select(0.0, 1.0, baseColor.a > 0.0 && attributes.instanceElevations >= 0.0);\n let dotRadius = column.radius * column.coverage * shouldRender;\n let centroidPosition =\n vec3<f32>(\n attributes.instancePositions.xy,\n attributes.instancePositions.z + elevation\n );\n let offset = getOffset(attributes.positions, strokeOffsetRatio, dotRadius, rotationMatrix);\n let projected = project_position_to_clipspace_and_commonspace(\n centroidPosition,\n attributes.instancePositions64Low,\n offset\n );\n\n geometry.position = projected.commonPosition;\n geometry.normal = project_normal(vec3<f32>(rotationMatrix * attributes.normals.xy, attributes.normals.z));\n\n let lightColor = lighting_getLightColor2(\n baseColor.rgb,\n project.cameraPosition,\n geometry.position.xyz,\n geometry.normal\n );\n\n varyings.position = projected.clipPosition;\n varyings.color = vec4<f32>(\n select(baseColor.rgb, lightColor, column.extruded > 0.5 && !isStroke),\n baseColor.a * layer.opacity\n );\n\n return varyings;\n}\n\n@fragment\nfn fragmentMain(varyings: Varyings) -> @location(0) vec4<f32> {\n geometry.uv = vec2<f32>(0.0);\n return deckgl_premultiplied_alpha(varyings.color);\n}\n`,zs=`${Ts}\n\nstruct Varyings {\n @builtin(position) position: vec4<f32>,\n @location(0) color: vec4<f32>,\n @location(1) cameraPosition: vec3<f32>,\n @location(2) positionCommonspace: vec4<f32>\n};\n\n@vertex\nfn vertexMain(attributes: Attributes) -> Varyings {\n var varyings: Varyings;\n\n geometry.worldPosition = attributes.instancePositions;\n geometry.pickingColor = picking_getPickingColorFromIndex(attributes.instanceIndex);\n\n let isStroke = column.isStroke > 0.5;\n let baseColor = select(attributes.instanceFillColors, attributes.instanceLineColors, isStroke);\n let rotationMatrix = getRotationMatrix(column.angle);\n\n var elevation = 0.0;\n var strokeOffsetRatio = 1.0;\n\n if (column.extruded > 0.5) {\n elevation =\n attributes.instanceElevations * (attributes.positions.z + 1.0) / 2.0 * column.elevationScale;\n } else if (column.stroked > 0.5) {\n let widthPixels = clamp(\n project_unit_size_to_pixel(attributes.instanceStrokeWidths * column.widthScale, column.widthUnits),\n column.widthMinPixels,\n column.widthMaxPixels\n ) / 2.0;\n let halfOffset =\n project_pixel_size_float(widthPixels) /\n project_size_float(column.edgeDistance * column.coverage * column.radius);\n if (isStroke) {\n strokeOffsetRatio -= sign(attributes.positions.z) * halfOffset;\n } else {\n strokeOffsetRatio -= halfOffset;\n }\n }\n\n let shouldRender = select(0.0, 1.0, baseColor.a > 0.0 && attributes.instanceElevations >= 0.0);\n let dotRadius = column.radius * column.coverage * shouldRender;\n let centroidPosition =\n vec3<f32>(\n attributes.instancePositions.xy,\n attributes.instancePositions.z + elevation\n );\n let offset = getOffset(attributes.positions, strokeOffsetRatio, dotRadius, rotationMatrix);\n let projected = project_position_to_clipspace_and_commonspace(\n centroidPosition,\n attributes.instancePositions64Low,\n offset\n );\n\n geometry.position = projected.commonPosition;\n geometry.normal = project_normal(vec3<f32>(rotationMatrix * attributes.normals.xy, attributes.normals.z));\n\n varyings.position = projected.clipPosition;\n varyings.color = vec4<f32>(baseColor.rgb, baseColor.a * layer.opacity);\n varyings.cameraPosition = project.cameraPosition;\n varyings.positionCommonspace = projected.commonPosition;\n\n return varyings;\n}\n\n@fragment\nfn fragmentMain(varyings: Varyings) -> @location(0) vec4<f32> {\n geometry.uv = vec2<f32>(0.0);\n\n var fragColor = varyings.color;\n if (column.extruded > 0.5 && column.isStroke < 0.5) {\n // WebGPU's screen-space Y axis reverses the derivative orientation used by GLSL flat shading.\n let normal = normalize(cross(dpdy(varyings.positionCommonspace.xyz), dpdx(varyings.positionCommonspace.xyz)));\n fragColor = vec4<f32>(\n lighting_getLightColor2(\n varyings.color.rgb,\n varyings.cameraPosition,\n varyings.positionCommonspace.xyz,\n normal\n ),\n varyings.color.a\n );\n }\n\n return deckgl_premultiplied_alpha(fragColor);\n}\n`;function Ms(e){return e?zs:Os}var Rs=[0,0,0,255],Bs={name:"geometry",stepMode:"vertex",byteStride:24,attributes:[{attribute:"positions",format:"float32x3",byteOffset:0},{attribute:"normals",format:"float32x3",byteOffset:12}]},ks={diskResolution:{type:"number",min:4,value:20},vertices:null,radius:{type:"number",min:0,value:1e3},angle:{type:"number",value:0},offset:{type:"array",value:[0,0]},coverage:{type:"number",min:0,max:1,value:1},elevationScale:{type:"number",min:0,value:1},radiusUnits:"meters",lineWidthUnits:"meters",lineWidthScale:1,lineWidthMinPixels:0,lineWidthMaxPixels:Number.MAX_SAFE_INTEGER,extruded:!0,wireframe:!1,filled:!0,stroked:!1,flatShading:!1,getPosition:{type:"accessor",value:e=>e.position},getFillColor:{type:"accessor",value:Rs},getLineColor:{type:"accessor",value:Rs},getLineWidth:{type:"accessor",value:1},getElevation:{type:"accessor",value:1e3},material:!0,getColor:{deprecatedFor:["getFillColor","getLineColor"]}},Fs=class extends co{getShaders(){const e={},{flatShading:t}=this.props;return t&&(e.FLAT_SHADING=1),super.getShaders({vs:"#version 300 es\n#define SHADER_NAME column-layer-vertex-shader\nin vec3 positions;\nin vec3 normals;\nin vec3 instancePositions;\nin float instanceElevations;\nin vec3 instancePositions64Low;\nin vec4 instanceFillColors;\nin vec4 instanceLineColors;\nin float instanceStrokeWidths;\nout vec4 vColor;\n#ifdef FLAT_SHADING\nout vec3 cameraPosition;\nout vec4 position_commonspace;\n#endif\nvoid main(void) {\ngeometry.worldPosition = instancePositions;\nvec4 color = column.isStroke ? instanceLineColors : instanceFillColors;\nmat2 rotationMatrix = mat2(cos(column.angle), sin(column.angle), -sin(column.angle), cos(column.angle));\nfloat elevation = 0.0;\nfloat strokeOffsetRatio = 1.0;\nif (column.extruded) {\nelevation = instanceElevations * (positions.z + 1.0) / 2.0 * column.elevationScale;\n} else if (column.stroked) {\nfloat widthPixels = clamp(\nproject_size_to_pixel(instanceStrokeWidths * column.widthScale, column.widthUnits),\ncolumn.widthMinPixels, column.widthMaxPixels) / 2.0;\nfloat halfOffset = project_pixel_size(widthPixels) / project_size(column.edgeDistance * column.coverage * column.radius);\nif (column.isStroke) {\nstrokeOffsetRatio -= sign(positions.z) * halfOffset;\n} else {\nstrokeOffsetRatio -= halfOffset;\n}\n}\nfloat shouldRender = float(color.a > 0.0 && instanceElevations >= 0.0);\nfloat dotRadius = column.radius * column.coverage * shouldRender;\ngeometry.pickingColor = picking_getPickingColorFromInstanceID();\nvec3 centroidPosition = vec3(instancePositions.xy, instancePositions.z + elevation);\nvec3 centroidPosition64Low = instancePositions64Low;\nvec2 offset = (rotationMatrix * positions.xy * strokeOffsetRatio + column.offset) * dotRadius;\nif (column.radiusUnits == UNIT_METERS) {\noffset = project_size(offset);\n} else if (column.radiusUnits == UNIT_PIXELS) {\noffset = project_pixel_size(offset);\n}\nvec3 pos = vec3(offset, 0.);\nDECKGL_FILTER_SIZE(pos, geometry);\ngl_Position = project_position_to_clipspace(centroidPosition, centroidPosition64Low, pos, geometry.position);\ngeometry.normal = project_normal(vec3(rotationMatrix * normals.xy, normals.z));\nDECKGL_FILTER_GL_POSITION(gl_Position, geometry);\nif (column.extruded && !column.isStroke) {\n#ifdef FLAT_SHADING\ncameraPosition = project.cameraPosition;\nposition_commonspace = geometry.position;\nvColor = vec4(color.rgb, color.a * layer.opacity);\n#else\nvec3 lightColor = lighting_getLightColor(color.rgb, project.cameraPosition, geometry.position.xyz, geometry.normal);\nvColor = vec4(lightColor, color.a * layer.opacity);\n#endif\n} else {\nvColor = vec4(color.rgb, color.a * layer.opacity);\n}\nDECKGL_FILTER_COLOR(vColor, geometry);\n}\n",fs:"#version 300 es\n#define SHADER_NAME column-layer-fragment-shader\nprecision highp float;\nout vec4 fragColor;\nin vec4 vColor;\n#ifdef FLAT_SHADING\nin vec3 cameraPosition;\nin vec4 position_commonspace;\n#endif\nvoid main(void) {\nfragColor = vColor;\ngeometry.uv = vec2(0.);\n#ifdef FLAT_SHADING\nif (column.extruded && !column.isStroke && !bool(picking.isActive)) {\nvec3 normal = normalize(cross(dFdx(position_commonspace.xyz), dFdy(position_commonspace.xyz)));\nfragColor.rgb = lighting_getLightColor(vColor.rgb, cameraPosition, position_commonspace.xyz, normal);\n}\n#endif\nDECKGL_FILTER_COLOR(fragColor, geometry);\n}\n",source:Ms(t),defines:e,modules:[Ye,Ze,t?He:We,Je,Es]})}initializeState(){this.getAttributeManager().addInstanced({instancePositions:{size:3,type:"float64",fp64:this.use64bitPositions(),transition:!0,accessor:"getPosition"},instanceElevations:{size:1,transition:!0,accessor:"getElevation"},instanceFillColors:{size:this.props.colorFormat.length,type:"unorm8",transition:!0,accessor:"getFillColor",defaultValue:Rs},instanceLineColors:{size:this.props.colorFormat.length,type:"unorm8",transition:!0,accessor:"getLineColor",defaultValue:Rs},instanceStrokeWidths:{size:1,accessor:"getLineWidth",transition:!0}})}updateState(e){super.updateState(e);const{props:t,oldProps:n,changeFlags:i}=e,o=i.extensionsChanged||t.flatShading!==n.flatShading;o&&(this.state.models?.forEach(e=>e.destroy()),this.setState(this._getModels()),this.getAttributeManager().invalidateAll());const s=this.getNumInstances();this.state.fillModel.setInstanceCount(s),this.state.strokeModel.setInstanceCount(s),this.state.wireframeModel.setInstanceCount(s),(o||t.diskResolution!==n.diskResolution||t.vertices!==n.vertices||t.extruded!==n.extruded||t.stroked!==n.stroked)&&this._updateGeometry(t)}getGeometry(e,t,n){const i=new As({radius:1,height:n?2:0,vertices:t,nradial:e});let o=0;if(t)for(let s=0;s<e;s++){const n=t[s];o+=Math.sqrt(n[0]*n[0]+n[1]*n[1])/e}else o=1;return this.setState({edgeDistance:Math.cos(Math.PI/e)*o}),i}_getModels(){const e=this.getShaders(),t=[...this.getAttributeManager().getBufferLayouts(),Bs],n=new xt(this.context.device,{...e,id:`${this.props.id}-fill`,bufferLayout:t,isInstanced:!0}),i=new xt(this.context.device,{...e,id:`${this.props.id}-stroke`,bufferLayout:t,isInstanced:!0}),o=new xt(this.context.device,{...e,id:`${this.props.id}-wireframe`,bufferLayout:t,isInstanced:!0});return{fillModel:n,strokeModel:i,wireframeModel:o,models:[o,n,i]}}_updateGeometry({diskResolution:e,vertices:t,extruded:n,stroked:i}){const o=this.getGeometry(e,t,n||i),s=o.attributes.POSITION,r=o.attributes.NORMAL;if(this._setFillGeometry(new nt({topology:"triangle-strip",attributes:{POSITION:s,NORMAL:r}})),!n&&i){const t=s.value.length/3;this._setStrokeGeometry(new nt({topology:"triangle-strip",vertexCount:t-e-1,attributes:{POSITION:s,NORMAL:r}}))}n&&this._setWireframeGeometry(o)}_setFillGeometry(e){const t=ot(e,{attributes:["POSITION","NORMAL"]});this.state.fillModel.setGeometry(t)}_setStrokeGeometry(e){const t=ot(e,{attributes:["POSITION","NORMAL"]});this.state.strokeModel.setGeometry(t)}_setWireframeGeometry(e){const t=ot(e,{attributes:["POSITION","NORMAL"]}),n=this.state.wireframeModel;n.setGeometry(t),n.setTopology("line-list")}draw({uniforms:e}){const{lineWidthUnits:t,lineWidthScale:n,lineWidthMinPixels:o,lineWidthMaxPixels:s,radiusUnits:r,elevationScale:a,extruded:l,filled:c,stroked:u,wireframe:f,offset:d,coverage:p,radius:g,angle:h}=this.props,v=this.state.fillModel,m=this.state.strokeModel,_=this.state.wireframeModel,{edgeDistance:x}=this.state,y={radius:g,angle:h/180*Math.PI,offset:d,extruded:l,stroked:u,coverage:p,elevationScale:a,edgeDistance:x,radiusUnits:i[r],widthUnits:i[t],widthScale:n,widthMinPixels:o,widthMaxPixels:s};l&&f&&(_.shaderInputs.setProps({column:{...y,isStroke:!0}}),_.draw(this.context.renderPass)),c&&(v.shaderInputs.setProps({column:{...y,isStroke:!1}}),v.draw(this.context.renderPass)),!l&&u&&(m.shaderInputs.setProps({column:{...y,isStroke:!0}}),m.draw(this.context.renderPass))}};Fs.layerName="ColumnLayer",Fs.defaultProps=ks;var Ns=class extends Fs{_updateGeometry(){const e=new wt;this._setFillGeometry(e)}draw({uniforms:e}){const{elevationScale:t,extruded:n,offset:o,coverage:s,cellSize:r,angle:a,radiusUnits:l}=this.props,c=this.state.fillModel,u={radius:r/2,radiusUnits:i[l],angle:a,offset:o,extruded:n,stroked:!1,coverage:s,elevationScale:t,edgeDistance:1,isStroke:!1,widthUnits:0,widthScale:0,widthMinPixels:0,widthMaxPixels:0};c.shaderInputs.setProps({column:u}),c.draw(this.context.renderPass)}};function Ds(e,t,n,i){let o;if(Array.isArray(e[0])){const n=e.length*t;o=new Array(n);for(let i=0;i<e.length;i++)for(let n=0;n<t;n++)o[i*t+n]=e[i][n]||0}else o=e;return n?vs(o,{size:t,gridResolution:n}):i?function(e,t){const{size:n=2,startIndex:i=0,endIndex:o=e.length,normalize:s=!0}=t||{},r=e.slice(i,o);Ss(r,n,0,o-i);const a=vs(r,{size:n,broken:!0,gridResolution:360,gridOffset:[-180,-180]});if(s)for(const l of a)Ls(l,n);return a}(o,{size:t}):o}Ns.layerName="GridCellLayer",Ns.defaultProps={cellSize:{type:"number",min:0,value:1e3},offset:{type:"array",value:[1,1]}};var js=class extends po{constructor(e){super({...e,attributes:{positions:{size:3,padding:18,initialize:!0,type:e.fp64?Float64Array:Float32Array},segmentTypes:{size:1,type:e.isWebGPU?Float32Array:Uint8ClampedArray}}})}get(e){return this.attributes[e]}getPathSegmentIndices(e){const t=this.attributes.segmentTypes,n=this.vertexStarts[e],i=Math.min(this.vertexStarts[e+1]??this.instanceCount,this.instanceCount),o=[];for(let s=n;s<i-1;s++)4&t[s]||o.push(s);return o.length&&4&t[n]&&o.unshift(o.pop()),o}getGeometryFromBuffer(e){return this.normalize||this.opts.isWebGPU?super.getGeometryFromBuffer(e):null}normalizeGeometry(e){return this.normalize?Ds(e,this.positionSize,this.opts.resolution,this.opts.wrapLongitude):e}getGeometrySize(e){if(Us(e)){let t=0;for(const n of e)t+=this.getGeometrySize(n);return t}const t=this.getPathLength(e);return t<2?0:this.isClosed(e)?t<3?0:t+2:t}updateGeometryAttributes(e,t){if(0!==t.geometrySize)if(e&&Us(e))for(const n of e){const e=this.getGeometrySize(n);t.geometrySize=e,this.updateGeometryAttributes(n,t),t.vertexStart+=e}else this._updateSegmentTypes(e,t),this._updatePositions(e,t)}_updateSegmentTypes(e,t){const n=this.attributes.segmentTypes,i=!!e&&this.isClosed(e),{vertexStart:o,geometrySize:s}=t;n.fill(0,o,o+s),i?(n[o]=4,n[o+s-2]=4):(n[o]+=1,n[o+s-2]+=2),n[o+s-1]=4}_updatePositions(e,t){const{positions:n}=this.attributes;if(!n||!e)return;const{vertexStart:i,geometrySize:o}=t,s=new Array(3);for(let r=i,a=0;a<o;r++,a++)this.getPointOnPath(e,a,s),n[3*r]=s[0],n[3*r+1]=s[1],n[3*r+2]=s[2]}getPathLength(e){return e.length/this.positionSize}getPointOnPath(e,t,n=[]){const{positionSize:i}=this;t*i>=e.length&&(t+=1-e.length/i);const o=t*i;return n[0]=e[o],n[1]=e[o+1],n[2]=3===i&&e[o+2]||0,n}isClosed(e){if(!this.normalize)return Boolean(this.opts.loop);const{positionSize:t}=this,n=e.length-t;return e[0]===e[n]&&e[1]===e[n+1]&&(2===t||e[2]===e[n+2])}};function Us(e){return Array.isArray(e[0])}var Gs="layout(std140) uniform pathUniforms {\n float widthScale;\n float widthMinPixels;\n float widthMaxPixels;\n float jointType;\n float capType;\n float miterLimit;\n bool billboard;\n highp int widthUnits;\n} path;\n",Vs={name:"path",source:"struct PathUniforms {\n widthScale: f32,\n widthMinPixels: f32,\n widthMaxPixels: f32,\n jointType: f32,\n capType: f32,\n miterLimit: f32,\n billboard: f32,\n widthUnits: i32,\n};\n\n@group(0) @binding(auto)\nvar<uniform> path: PathUniforms;\n",vs:Gs,fs:Gs,uniformTypes:{widthScale:"f32",widthMinPixels:"f32",widthMaxPixels:"f32",jointType:"f32",capType:"f32",miterLimit:"f32",billboard:"f32",widthUnits:"i32"}},$s=[0,0,0,255],Ws={widthUnits:"meters",widthScale:{type:"number",min:0,value:1},widthMinPixels:{type:"number",min:0,value:0},widthMaxPixels:{type:"number",min:0,value:Number.MAX_SAFE_INTEGER},jointRounded:!1,capRounded:!1,miterLimit:{type:"number",min:0,value:4},antialiasing:!1,billboard:!1,_pathType:null,getPath:{type:"accessor",value:e=>e.path},getColor:{type:"accessor",value:$s},getWidth:{type:"accessor",value:1},rounded:{deprecatedFor:["jointRounded","capRounded"]}},Hs={enter:(e,t)=>t.length?t.subarray(t.length-e.length):e};function Zs(e,t){return e===t||Boolean(e&&t&&e.length===t.length&&e.every((e,n)=>e===t[n]))}var Ys=class extends co{getShaders(){const{antialiasing:e}=this.props;return super.getShaders({vs:"#version 300 es\n#define SHADER_NAME path-layer-vertex-shader\nin vec2 positions;\nin float instanceTypes;\nin vec3 instanceStartPositions;\nin vec3 instanceEndPositions;\nin vec3 instanceLeftPositions;\nin vec3 instanceRightPositions;\nin vec3 instanceLeftPositions64Low;\nin vec3 instanceStartPositions64Low;\nin vec3 instanceEndPositions64Low;\nin vec3 instanceRightPositions64Low;\nin float instanceStrokeWidths;\nin vec4 instanceColors;\nin float rowIndexes;\nuniform float opacity;\nout vec4 vColor;\nout vec2 vCornerOffset;\nout float vMiterLength;\nout vec2 vPathPosition;\nout float vPathLength;\nout float vJointType;\n#ifdef DASH_ENABLED\nout vec2 vPathBounds;\n#endif\nconst float EPSILON = 0.001;\nconst vec3 ZERO_OFFSET = vec3(0.0);\nfloat flipIfTrue(bool flag) {\nreturn -(float(flag) * 2. - 1.);\n}\nvec3 getLineJoinOffset(\nvec3 prevPoint, vec3 currPoint, vec3 nextPoint,\nvec2 width\n#ifdef DASH_ENABLED\n, float sourcePathLength, vec2 sourcePathRange\n#endif\n#ifdef ANTIALIASING\n, float coverageScale\n#endif\n) {\nbool isEnd = positions.x > 0.0;\nfloat sideOfPath = positions.y;\nfloat isJoint = float(sideOfPath == 0.0);\nvec3 deltaA3 = (currPoint - prevPoint);\nvec3 deltaB3 = (nextPoint - currPoint);\nmat3 rotationMatrix;\nbool needsRotation = !path.billboard && project_needs_rotation(currPoint, rotationMatrix);\nif (needsRotation) {\ndeltaA3 = deltaA3 * rotationMatrix;\ndeltaB3 = deltaB3 * rotationMatrix;\n}\nvec2 deltaA = deltaA3.xy / width;\nvec2 deltaB = deltaB3.xy / width;\nfloat lenA = length(deltaA);\nfloat lenB = length(deltaB);\nvec2 dirA = lenA > 0. ? normalize(deltaA) : vec2(0.0, 0.0);\nvec2 dirB = lenB > 0. ? normalize(deltaB) : vec2(0.0, 0.0);\nvec2 perpA = vec2(-dirA.y, dirA.x);\nvec2 perpB = vec2(-dirB.y, dirB.x);\nvec2 tangent = dirA + dirB;\ntangent = length(tangent) > 0. ? normalize(tangent) : perpA;\nvec2 miterVec = vec2(-tangent.y, tangent.x);\nvec2 dir = isEnd ? dirA : dirB;\nvec2 perp = isEnd ? perpA : perpB;\nfloat L = isEnd ? lenA : lenB;\n#ifdef DASH_ENABLED\nvec3 currDelta3 = isEnd ? deltaA3 : deltaB3;\nfloat currLength2D = length(currDelta3.xy);\nfloat arcLengthRatio = 1.0;\nfloat pathPositionOffset = 0.0;\nfloat pathLength = L;\nif (path.billboard) {\nfloat visiblePathLength = sourcePathLength * (sourcePathRange.y - sourcePathRange.x);\narcLengthRatio = L > 0.0 ? visiblePathLength / L : 0.0;\npathPositionOffset = sourcePathLength * sourcePathRange.x;\npathLength = sourcePathLength;\n} else if (currLength2D > 0.0) {\narcLengthRatio = length(currDelta3) / currLength2D;\npathLength = L * arcLengthRatio;\n}\n#endif\nfloat sinHalfA = abs(dot(miterVec, perp));\nfloat cosHalfA = abs(dot(dirA, miterVec));\nfloat turnDirection = flipIfTrue(dirA.x * dirB.y >= dirA.y * dirB.x);\nfloat cornerPosition = sideOfPath * turnDirection;\nfloat miterSize = 1.0 / max(sinHalfA, EPSILON);\nmiterSize = mix(\nmin(miterSize, max(lenA, lenB) / max(cosHalfA, EPSILON)),\nmiterSize,\nstep(0.0, cornerPosition)\n);\nvec2 offsetVec = mix(miterVec * miterSize, perp, step(0.5, cornerPosition))\n* (sideOfPath + isJoint * turnDirection);\nbool isStartCap = lenA == 0.0 || (!isEnd && (instanceTypes == 1.0 || instanceTypes == 3.0));\nbool isEndCap = lenB == 0.0 || (isEnd && (instanceTypes == 2.0 || instanceTypes == 3.0));\nbool isCap = isStartCap || isEndCap;\nif (isCap) {\noffsetVec = mix(perp * sideOfPath, dir * path.capType * 4.0 * flipIfTrue(isStartCap), isJoint);\nvJointType = path.capType;\n} else {\nvJointType = path.jointType;\n}\n#ifdef ANTIALIASING\nvec2 coverageOffsetVec = offsetVec * coverageScale;\n#ifdef DASH_ENABLED\nvPathLength = pathLength;\n#else\nvPathLength = L;\n#endif\nvCornerOffset = coverageOffsetVec;\nvMiterLength = dot(vCornerOffset, miterVec * turnDirection);\nvMiterLength = isCap ? isJoint : vMiterLength;\nvec2 offsetFromStartOfPath = coverageOffsetVec + deltaA * float(isEnd);\nvPathPosition = vec2(\ndot(offsetFromStartOfPath, perp),\n#ifdef DASH_ENABLED\npathPositionOffset + dot(offsetFromStartOfPath, dir) * arcLengthRatio\n#else\ndot(offsetFromStartOfPath, dir)\n#endif\n);\ngeometry.uv = vPathPosition;\nfloat isValid = step(instanceTypes, 3.5);\nvec3 offset = vec3(coverageOffsetVec * width * isValid, 0.0);\n#else\n#ifdef DASH_ENABLED\nvPathLength = pathLength;\n#else\nvPathLength = L;\n#endif\nvCornerOffset = offsetVec;\nvMiterLength = dot(vCornerOffset, miterVec * turnDirection);\nvMiterLength = isCap ? isJoint : vMiterLength;\nvec2 offsetFromStartOfPath = vCornerOffset + deltaA * float(isEnd);\nvPathPosition = vec2(\ndot(offsetFromStartOfPath, perp),\n#ifdef DASH_ENABLED\npathPositionOffset + dot(offsetFromStartOfPath, dir) * arcLengthRatio\n#else\ndot(offsetFromStartOfPath, dir)\n#endif\n);\ngeometry.uv = vPathPosition;\nfloat isValid = step(instanceTypes, 3.5);\nvec3 offset = vec3(offsetVec * width * isValid, 0.0);\n#endif\nif (needsRotation) {\noffset = rotationMatrix * offset;\n}\nreturn offset;\n}\nvoid clipLine(inout vec4 position, vec4 refPosition) {\nif (position.w < EPSILON) {\nfloat r = (EPSILON - refPosition.w) / (position.w - refPosition.w);\nposition = refPosition + (position - refPosition) * r;\n}\n}\n#ifdef DASH_ENABLED\nvec2 getClippedPathRange(float startW, float endW) {\nbool startClipped = startW < EPSILON;\nbool endClipped = endW < EPSILON;\nif (startClipped && endClipped) {\nreturn vec2(0.0);\n}\nif (startClipped || endClipped) {\nfloat intersection = clamp((EPSILON - startW) / (endW - startW), 0.0, 1.0);\nreturn startClipped ? vec2(intersection, 1.0) : vec2(0.0, intersection);\n}\nreturn vec2(0.0, 1.0);\n}\n#endif\nvoid main() {\ngeometry.pickingColor = picking_getPickingColorFromIndex(rowIndexes);\nvColor = vec4(instanceColors.rgb, instanceColors.a * layer.opacity);\nfloat isEnd = positions.x;\nvec3 prevPosition = mix(instanceLeftPositions, instanceStartPositions, isEnd);\nvec3 prevPosition64Low = mix(instanceLeftPositions64Low, instanceStartPositions64Low, isEnd);\nvec3 currPosition = mix(instanceStartPositions, instanceEndPositions, isEnd);\nvec3 currPosition64Low = mix(instanceStartPositions64Low, instanceEndPositions64Low, isEnd);\nvec3 nextPosition = mix(instanceEndPositions, instanceRightPositions, isEnd);\nvec3 nextPosition64Low = mix(instanceEndPositions64Low, instanceRightPositions64Low, isEnd);\ngeometry.worldPosition = currPosition;\nvec2 widthPixels = vec2(clamp(\nproject_size_to_pixel(instanceStrokeWidths * path.widthScale, path.widthUnits),\npath.widthMinPixels, path.widthMaxPixels) / 2.0);\nvec3 width;\nif (path.billboard) {\n#ifdef DASH_ENABLED\nvec4 prevPositionCommon;\nvec4 nextPositionCommon;\nvec4 prevPositionScreen = project_position_to_clipspace(\nprevPosition, prevPosition64Low, ZERO_OFFSET, prevPositionCommon\n);\n#else\nvec4 prevPositionScreen = project_position_to_clipspace(\nprevPosition, prevPosition64Low, ZERO_OFFSET\n);\n#endif\nvec4 currPositionScreen = project_position_to_clipspace(currPosition, currPosition64Low, ZERO_OFFSET, geometry.position);\n#ifdef DASH_ENABLED\nvec4 nextPositionScreen = project_position_to_clipspace(\nnextPosition, nextPosition64Low, ZERO_OFFSET, nextPositionCommon\n);\n#else\nvec4 nextPositionScreen = project_position_to_clipspace(\nnextPosition, nextPosition64Low, ZERO_OFFSET\n);\n#endif\n#ifdef DASH_ENABLED\nvec4 sourcePathStartScreen = mix(currPositionScreen, prevPositionScreen, isEnd);\nvec4 sourcePathEndScreen = mix(nextPositionScreen, currPositionScreen, isEnd);\nvec2 billboardPathRange = getClippedPathRange(\nsourcePathStartScreen.w, sourcePathEndScreen.w\n);\n#endif\nclipLine(prevPositionScreen, currPositionScreen);\nclipLine(nextPositionScreen, currPositionScreen);\nclipLine(currPositionScreen, mix(nextPositionScreen, prevPositionScreen, isEnd));\nwidth = vec3(widthPixels, 0.0);\nDECKGL_FILTER_SIZE(width, geometry);\n#ifdef ANTIALIASING\nvec2 coveragePadding = vec2(0.5 / project.devicePixelRatio);\nfloat coverageScale = length(width.xy) > 0.0\n? length(width.xy + coveragePadding) / length(width.xy)\n: 1.0;\n#endif\n#ifdef DASH_ENABLED\nvec3 currentDeltaCommon = isEnd > 0.0\n? geometry.position.xyz - prevPositionCommon.xyz\n: nextPositionCommon.xyz - geometry.position.xyz;\nfloat billboardPathLength = width.x > 0.0\n? length(currentDeltaCommon) * project.scale / (width.x * project.focalDistance)\n: 0.0;\n#endif\nvec3 offset = getLineJoinOffset(\nprevPositionScreen.xyz / prevPositionScreen.w,\ncurrPositionScreen.xyz / currPositionScreen.w,\nnextPositionScreen.xyz / nextPositionScreen.w,\nproject_pixel_size_to_clipspace(width.xy)\n#ifdef DASH_ENABLED\n,\nbillboardPathLength, billboardPathRange\n#endif\n#ifdef ANTIALIASING\n,\ncoverageScale\n#endif\n);\n#ifdef DASH_ENABLED\nvPathBounds = billboardPathLength * billboardPathRange;\n#endif\nDECKGL_FILTER_GL_POSITION(currPositionScreen, geometry);\ngl_Position = vec4(currPositionScreen.xyz + offset * currPositionScreen.w, currPositionScreen.w);\n} else {\nprevPosition = project_position(prevPosition, prevPosition64Low);\ncurrPosition = project_position(currPosition, currPosition64Low);\nnextPosition = project_position(nextPosition, nextPosition64Low);\nwidth = vec3(project_pixel_size(widthPixels), 0.0);\nDECKGL_FILTER_SIZE(width, geometry);\n#ifdef ANTIALIASING\nvec2 coveragePadding = project_pixel_size(vec2(0.5 / project.devicePixelRatio));\nfloat coverageScale = length(width.xy) > 0.0\n? length(width.xy + coveragePadding) / length(width.xy)\n: 1.0;\n#endif\nvec3 offset = getLineJoinOffset(\nprevPosition, currPosition, nextPosition, width.xy\n#ifdef DASH_ENABLED\n, 1.0, vec2(0.0, 1.0)\n#endif\n#ifdef ANTIALIASING\n, coverageScale\n#endif\n);\n#ifdef DASH_ENABLED\nvPathBounds = vec2(0.0, vPathLength);\n#endif\ngeometry.position = vec4(currPosition + offset, 1.0);\ngl_Position = project_common_position_to_clipspace(geometry.position);\nDECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n}\nDECKGL_FILTER_COLOR(vColor, geometry);\n}\n",fs:"#version 300 es\n#define SHADER_NAME path-layer-fragment-shader\nprecision highp float;\nin vec4 vColor;\nin vec2 vCornerOffset;\nin float vMiterLength;\nin vec2 vPathPosition;\nin float vPathLength;\nin float vJointType;\n#ifdef DASH_ENABLED\nin vec2 vPathBounds;\n#endif\nout vec4 fragColor;\nvoid main(void) {\ngeometry.uv = vPathPosition;\n#ifdef ANTIALIASING\n#ifdef DASH_ENABLED\nbool isCorner = vPathPosition.y < vPathBounds.x || vPathPosition.y > vPathBounds.y;\n#else\nbool isCorner = vPathPosition.y < 0.0 || vPathPosition.y > vPathLength;\n#endif\nbool isRound = vJointType > 0.5;\nfloat bodyCoord = abs(vPathPosition.x);\nfloat cornerCoord = length(vCornerOffset);\nfloat bodyPixels = (1.0 - bodyCoord) / max(fwidth(bodyCoord), 1e-6);\nfloat cornerPixels = (1.0 - cornerCoord) / max(fwidth(cornerCoord), 1e-6);\n#ifdef PATH_STYLE_OFFSET\nfloat edgePixels = isRound && isCorner ? min(cornerPixels, bodyPixels) : bodyPixels;\n#else\nfloat edgePixels = isRound && isCorner ? cornerPixels : bodyPixels;\n#endif\nif (edgePixels <= -SMOOTH_EDGE_RADIUS) {\ndiscard;\n}\nif (isCorner) {\nif (!isRound && vMiterLength > path.miterLimit + 1.0) {\ndiscard;\n}\n}\nfragColor = vColor;\nfragColor.a *= smoothedge(0.0, edgePixels);\n#else\n#ifdef DASH_ENABLED\nif (vPathPosition.y < vPathBounds.x || vPathPosition.y > vPathBounds.y) {\n#else\nif (vPathPosition.y < 0.0 || vPathPosition.y > vPathLength) {\n#endif\nif (vJointType > 0.5 && length(vCornerOffset) > 1.0) {\ndiscard;\n}\nif (vJointType < 0.5 && vMiterLength > path.miterLimit + 1.0) {\ndiscard;\n}\n}\nfragColor = vColor;\n#endif\nDECKGL_FILTER_COLOR(fragColor, geometry);\n}\n",source:"const EPSILON: f32 = 0.001;\nconst ZERO_OFFSET: vec3<f32> = vec3<f32>(0.0, 0.0, 0.0);\n\nstruct JoinResult {\n offset: vec3<f32>,\n cornerOffset: vec2<f32>,\n miterLength: f32,\n pathPosition: vec2<f32>,\n pathLength: f32,\n jointType: f32,\n};\n\nstruct Attributes {\n @location(0) positions: vec2<f32>,\n @location(1) instanceTypes: f32,\n @location(2) instanceLeftPositions: vec3<f32>,\n @location(3) instanceStartPositions: vec3<f32>,\n @location(4) instanceEndPositions: vec3<f32>,\n @location(5) instanceRightPositions: vec3<f32>,\n @location(6) instanceLeftPositions64Low: vec3<f32>,\n @location(7) instanceStartPositions64Low: vec3<f32>,\n @location(8) instanceEndPositions64Low: vec3<f32>,\n @location(9) instanceRightPositions64Low: vec3<f32>,\n @location(10) instanceStrokeWidths: f32,\n @location(11) instanceColors: vec4<f32>,\n @location(12) rowIndexes: u32,\n};\n\nstruct Varyings {\n @builtin(position) position: vec4<f32>,\n @location(0) vColor: vec4<f32>,\n @location(1) vCornerOffset: vec2<f32>,\n @location(2) vMiterLength: f32,\n @location(3) vPathPosition: vec2<f32>,\n @location(4) vPathLength: f32,\n @location(5) vJointType: f32,\n // Location 6 is reserved for TripsLayer's injected vTime varying.\n @location(7) clipCoordinates: vec2<f32>,\n#ifdef DASH_ENABLED\n @location(8) vPathBounds: vec2<f32>,\n#endif\n};\n\nfn flipIfTrue(flag: bool) -> f32 {\n return select(1.0, -1.0, flag);\n}\n\nfn clipLine(position: vec4<f32>, refPosition: vec4<f32>) -> vec4<f32> {\n if (position.w < EPSILON) {\n let r = (EPSILON - refPosition.w) / (position.w - refPosition.w);\n return refPosition + (position - refPosition) * r;\n }\n return position;\n}\n\n#ifdef DASH_ENABLED\n// Return the visible interval of the original segment before clipLine moves either endpoint.\nfn getClippedPathRange(startW: f32, endW: f32) -> vec2<f32> {\n let startClipped = startW < EPSILON;\n let endClipped = endW < EPSILON;\n if (startClipped && endClipped) {\n return vec2<f32>(0.0, 0.0);\n }\n if (startClipped || endClipped) {\n let intersection = clamp((EPSILON - startW) / (endW - startW), 0.0, 1.0);\n if (startClipped) {\n return vec2<f32>(intersection, 1.0);\n }\n return vec2<f32>(0.0, intersection);\n }\n return vec2<f32>(0.0, 1.0);\n}\n#endif\n\nfn getLineJoinOffset(\n prevPoint: vec3<f32>,\n currPoint: vec3<f32>,\n nextPoint: vec3<f32>,\n width: vec2<f32>,\n#ifdef DASH_ENABLED\n sourcePathLength: f32,\n sourcePathRange: vec2<f32>,\n#endif\n#ifdef ANTIALIASING\n coverageScale: f32,\n#endif\n positions: vec2<f32>,\n instanceTypes: f32\n) -> JoinResult {\n let isEnd = positions.x > 0.0;\n let sideOfPath = positions.y;\n let isJoint = select(0.0, 1.0, sideOfPath == 0.0);\n\n var deltaA3 = currPoint - prevPoint;\n var deltaB3 = nextPoint - currPoint;\n\n let rotationResult = project_needs_rotation(currPoint);\n if (path.billboard == 0.0 && rotationResult.needsRotation) {\n deltaA3 = rotationResult.transform * deltaA3;\n deltaB3 = rotationResult.transform * deltaB3;\n }\n\n let deltaA = deltaA3.xy / width;\n let deltaB = deltaB3.xy / width;\n\n let lenA = length(deltaA);\n let lenB = length(deltaB);\n\n let dirA = select(vec2<f32>(0.0, 0.0), normalize(deltaA), lenA > 0.0);\n let dirB = select(vec2<f32>(0.0, 0.0), normalize(deltaB), lenB > 0.0);\n\n let perpA = vec2<f32>(-dirA.y, dirA.x);\n let perpB = vec2<f32>(-dirB.y, dirB.x);\n\n var tangent = dirA + dirB;\n tangent = select(perpA, normalize(tangent), length(tangent) > 0.0);\n let miterVec = vec2<f32>(-tangent.y, tangent.x);\n let dir = select(dirB, dirA, isEnd);\n let perp = select(perpB, perpA, isEnd);\n#ifdef DASH_ENABLED\n let segmentLength2D = select(lenB, lenA, isEnd);\n\n // Extrusion happens in the XY plane, so segmentLength2D is a 2D length and pathPosition.y\n // below measures 2D distance along the segment. For a path that also moves in Z the true\n // arc length is longer by this ratio. Scaling pathLength and pathPosition.y by it makes\n // the coordinate measure real 3D distance while leaving the joint tests unchanged, since\n // they compare the two against each other and both are scaled alike. Billboard mode\n // extrudes in clip space, where the perspective divide has already reduced the segment to\n // its screen projection, so its complete common-space length is supplied by the caller.\n // Mirrors path-layer-vertex.glsl.ts.\n let currDelta3 = select(deltaB3, deltaA3, isEnd);\n let currLength2D = length(currDelta3.xy);\n // Do not clamp a valid denominator to EPSILON: high-zoom Web Mercator deltas are often\n // smaller than that in common space, and changing their scale corrupts even flat paths.\n let safeLength2D = select(1.0, currLength2D, currLength2D > 0.0);\n var arcLengthRatio = 1.0;\n var pathPositionOffset = 0.0;\n var pathLength = segmentLength2D;\n if (path.billboard != 0.0) {\n // clipLine may shorten the visible screen-space segment. Preserve the corresponding interval\n // of the complete common-space arclength instead of compressing the full dash period into the\n // visible span. Keep pathLength complete so justification is stable as the camera clips it.\n let visiblePathLength = sourcePathLength * (sourcePathRange.y - sourcePathRange.x);\n arcLengthRatio = 0.0;\n if (segmentLength2D > 0.0) {\n arcLengthRatio = visiblePathLength / segmentLength2D;\n }\n pathPositionOffset = sourcePathLength * sourcePathRange.x;\n pathLength = sourcePathLength;\n } else if (currLength2D > 0.0) {\n arcLengthRatio = length(currDelta3) / safeLength2D;\n pathLength = segmentLength2D * arcLengthRatio;\n }\n#else\n let pathLength = select(lenB, lenA, isEnd);\n#endif\n\n let sinHalfA = abs(dot(miterVec, perp));\n let cosHalfA = abs(dot(dirA, miterVec));\n let turnDirection = flipIfTrue(dirA.x * dirB.y >= dirA.y * dirB.x);\n let cornerPosition = sideOfPath * turnDirection;\n\n var miterSize = 1.0 / max(sinHalfA, EPSILON);\n miterSize = mix(\n min(miterSize, max(lenA, lenB) / max(cosHalfA, EPSILON)),\n miterSize,\n step(0.0, cornerPosition)\n );\n\n var offsetVec =\n mix(miterVec * miterSize, perp, step(0.5, cornerPosition)) *\n (sideOfPath + isJoint * turnDirection);\n\n let isStartCap = lenA == 0.0 || (!isEnd && (instanceTypes == 1.0 || instanceTypes == 3.0));\n let isEndCap = lenB == 0.0 || (isEnd && (instanceTypes == 2.0 || instanceTypes == 3.0));\n let isCap = isStartCap || isEndCap;\n\n var jointType = path.jointType;\n if (isCap) {\n offsetVec = mix(\n perp * sideOfPath,\n dir * path.capType * 4.0 * flipIfTrue(isStartCap),\n isJoint\n );\n jointType = path.capType;\n }\n\n#ifdef ANTIALIASING\n let coverageOffsetVec = offsetVec * coverageScale;\n var miterLength = dot(coverageOffsetVec, miterVec * turnDirection);\n#else\n var miterLength = dot(offsetVec, miterVec * turnDirection);\n#endif\n miterLength = select(miterLength, isJoint, isCap);\n\n#ifdef ANTIALIASING\n let offsetFromStartOfPath = coverageOffsetVec + deltaA * select(0.0, 1.0, isEnd);\n#else\n let offsetFromStartOfPath = offsetVec + deltaA * select(0.0, 1.0, isEnd);\n#endif\n let pathPosition = vec2<f32>(\n dot(offsetFromStartOfPath, perp),\n#ifdef DASH_ENABLED\n pathPositionOffset + dot(offsetFromStartOfPath, dir) * arcLengthRatio\n#else\n dot(offsetFromStartOfPath, dir)\n#endif\n );\n let isValid = step(f32(instanceTypes), 3.5);\n#ifdef ANTIALIASING\n var offset = vec3<f32>(coverageOffsetVec * width * isValid, 0.0);\n#else\n var offset = vec3<f32>(offsetVec * width * isValid, 0.0);\n#endif\n\n if (path.billboard == 0.0 && rotationResult.needsRotation) {\n offset = rotationResult.transform * offset;\n }\n\n#ifdef ANTIALIASING\n return JoinResult(\n offset, coverageOffsetVec, miterLength, pathPosition, pathLength, jointType\n );\n#else\n return JoinResult(offset, offsetVec, miterLength, pathPosition, pathLength, jointType);\n#endif\n}\n\n@vertex\nfn vertexMain(attributes: Attributes) -> Varyings {\n var varyings: Varyings;\n\n geometry.pickingColor = picking_getPickingColorFromIndex(attributes.rowIndexes);\n\n let isEnd = attributes.positions.x;\n\n let prevPosition = mix(attributes.instanceLeftPositions, attributes.instanceStartPositions, isEnd);\n let prevPosition64Low = mix(\n attributes.instanceLeftPositions64Low,\n attributes.instanceStartPositions64Low,\n isEnd\n );\n let currPosition = mix(attributes.instanceStartPositions, attributes.instanceEndPositions, isEnd);\n let currPosition64Low = mix(\n attributes.instanceStartPositions64Low,\n attributes.instanceEndPositions64Low,\n isEnd\n );\n let nextPosition = mix(attributes.instanceEndPositions, attributes.instanceRightPositions, isEnd);\n let nextPosition64Low = mix(\n attributes.instanceEndPositions64Low,\n attributes.instanceRightPositions64Low,\n isEnd\n );\n\n geometry.worldPosition = currPosition;\n\n let widthPixels =\n clamp(\n project_unit_size_to_pixel(attributes.instanceStrokeWidths * path.widthScale, path.widthUnits),\n path.widthMinPixels,\n path.widthMaxPixels\n ) / 2.0;\n\n if (path.billboard != 0.0) {\n#ifdef DASH_ENABLED\n let prevProjection = project_position_to_clipspace_and_commonspace(\n prevPosition, prevPosition64Low, ZERO_OFFSET\n );\n let nextProjection = project_position_to_clipspace_and_commonspace(\n nextPosition, nextPosition64Low, ZERO_OFFSET\n );\n let prevPositionCommon = prevProjection.commonPosition.xyz;\n let nextPositionCommon = nextProjection.commonPosition.xyz;\n var prevPositionScreen = prevProjection.clipPosition;\n var nextPositionScreen = nextProjection.clipPosition;\n#else\n var prevPositionScreen = project_position_to_clipspace(\n prevPosition, prevPosition64Low, ZERO_OFFSET\n );\n var nextPositionScreen = project_position_to_clipspace(\n nextPosition, nextPosition64Low, ZERO_OFFSET\n );\n#endif\n let currProjection = project_position_to_clipspace_and_commonspace(\n currPosition, currPosition64Low, ZERO_OFFSET\n );\n geometry.position = currProjection.commonPosition;\n var currPositionScreen = currProjection.clipPosition;\n#ifdef DASH_ENABLED\n let currPositionCommon = currProjection.commonPosition.xyz;\n let sourcePathStartScreen = mix(currPositionScreen, prevPositionScreen, isEnd);\n let sourcePathEndScreen = mix(nextPositionScreen, currPositionScreen, isEnd);\n let billboardPathRange = getClippedPathRange(\n sourcePathStartScreen.w, sourcePathEndScreen.w\n );\n#endif\n\n prevPositionScreen = clipLine(prevPositionScreen, currPositionScreen);\n nextPositionScreen = clipLine(nextPositionScreen, currPositionScreen);\n currPositionScreen = clipLine(currPositionScreen, mix(nextPositionScreen, prevPositionScreen, isEnd));\n\n#ifdef ANTIALIASING\n let coverageScale = select(\n 1.0,\n (widthPixels + 0.5 / project.devicePixelRatio) / max(widthPixels, 1e-6),\n widthPixels > 0.0\n );\n#endif\n#ifdef DASH_ENABLED\n let currentDeltaCommon = select(\n nextPositionCommon - currPositionCommon,\n currPositionCommon - prevPositionCommon,\n isEnd > 0.0\n );\n let billboardPathLength = select(\n 0.0,\n length(currentDeltaCommon) * project.scale / (widthPixels * project.focalDistance),\n widthPixels > 0.0\n );\n#endif\n let join = getLineJoinOffset(\n prevPositionScreen.xyz / prevPositionScreen.w,\n currPositionScreen.xyz / currPositionScreen.w,\n nextPositionScreen.xyz / nextPositionScreen.w,\n project_pixel_size_to_clipspace(vec2<f32>(widthPixels, widthPixels)),\n#ifdef DASH_ENABLED\n billboardPathLength,\n billboardPathRange,\n#endif\n#ifdef ANTIALIASING\n coverageScale,\n#endif\n attributes.positions,\n attributes.instanceTypes\n );\n#ifdef DASH_ENABLED\n // Phase and justification use the complete source segment, while cap and joint coverage\n // must still recognize the endpoints moved by clipLine.\n varyings.vPathBounds = billboardPathLength * billboardPathRange;\n#endif\n\n geometry.uv = join.pathPosition;\n varyings.position = vec4<f32>(\n currPositionScreen.xyz + join.offset * currPositionScreen.w,\n currPositionScreen.w\n );\n varyings.vCornerOffset = join.cornerOffset;\n varyings.vMiterLength = join.miterLength;\n varyings.vPathPosition = join.pathPosition;\n varyings.vPathLength = join.pathLength;\n varyings.vJointType = join.jointType;\n } else {\n let prevPositionCommon = project_position_vec3_f64(prevPosition, prevPosition64Low);\n let currPositionCommon = project_position_vec3_f64(currPosition, currPosition64Low);\n let nextPositionCommon = project_position_vec3_f64(nextPosition, nextPosition64Low);\n\n let width = vec2<f32>(\n project_pixel_size_float(widthPixels),\n project_pixel_size_float(widthPixels)\n );\n#ifdef ANTIALIASING\n let coverageScale = select(\n 1.0,\n (widthPixels + 0.5 / project.devicePixelRatio) / max(widthPixels, 1e-6),\n widthPixels > 0.0\n );\n#endif\n let join = getLineJoinOffset(\n prevPositionCommon,\n currPositionCommon,\n nextPositionCommon,\n width,\n#ifdef DASH_ENABLED\n 1.0,\n vec2<f32>(0.0, 1.0),\n#endif\n#ifdef ANTIALIASING\n coverageScale,\n#endif\n attributes.positions,\n attributes.instanceTypes\n );\n#ifdef DASH_ENABLED\n varyings.vPathBounds = vec2<f32>(0.0, join.pathLength);\n#endif\n\n geometry.position = vec4<f32>(currPositionCommon + join.offset, 1.0);\n geometry.uv = join.pathPosition;\n varyings.position = project_common_position_to_clipspace(geometry.position);\n varyings.vCornerOffset = join.cornerOffset;\n varyings.vMiterLength = join.miterLength;\n varyings.vPathPosition = join.pathPosition;\n varyings.vPathLength = join.pathLength;\n varyings.vJointType = join.jointType;\n }\n\n varyings.clipCoordinates = geometry.position.xy;\n clip_filterPosition(&varyings.position, geometry.worldPosition.xy);\n\n varyings.vColor = vec4<f32>(\n attributes.instanceColors.rgb,\n attributes.instanceColors.a * layer.opacity\n );\n return varyings;\n}\n\n@fragment\nfn fragmentMain(varyings: Varyings) -> @location(0) vec4<f32> {\n geometry.uv = varyings.vPathPosition;\n\n#ifdef ANTIALIASING\n // Coordinates of the outer silhouette, in units of half-width: rounded joints and caps are\n // bounded by the corner offset, everywhere else by the edge of the stroke. Dividing by the\n // screen-space derivative converts the distance to the boundary into device pixels, which stays\n // correct under perspective foreshortening and under extensions that rescale the stroke.\n#ifdef DASH_ENABLED\n let isCorner =\n varyings.vPathPosition.y < varyings.vPathBounds.x ||\n varyings.vPathPosition.y > varyings.vPathBounds.y;\n#else\n let isCorner = varyings.vPathPosition.y < 0.0 || varyings.vPathPosition.y > varyings.vPathLength;\n#endif\n let isRound = varyings.vJointType > 0.5;\n\n // Distance to the silhouette in device pixels, from the derivative of the coordinate that\n // bounds it. Computed before the discards below: derivatives need uniform control flow and are\n // undefined after a discard in the quad. See dev-docs/RFCs/v9.4/analytic-antialiasing-rfc.md\n let bodyCoord = abs(varyings.vPathPosition.x);\n let cornerCoord = length(varyings.vCornerOffset);\n // Both evaluated so each derivative stays on one field across the corner/body boundary\n let bodyPixels = (1.0 - bodyCoord) / max(fwidth(bodyCoord), 1e-6);\n let cornerPixels = (1.0 - cornerCoord) / max(fwidth(cornerCoord), 1e-6);\n#ifdef PATH_STYLE_OFFSET\n // Rounded corners still intersect the stroke-width envelope. Extensions may remap\n // vPathPosition.x independently of vCornerOffset, as PathStyleExtension does for offsets.\n let edgePixels = select(bodyPixels, min(cornerPixels, bodyPixels), isRound && isCorner);\n#else\n let edgePixels = select(bodyPixels, cornerPixels, isRound && isCorner);\n#endif\n\n // Fragments outside the coverage ramp must not write depth or picking colors.\n if (edgePixels <= -SMOOTH_EDGE_RADIUS) {\n discard;\n }\n\n if (isCorner) {\n if (!isRound && varyings.vMiterLength > path.miterLimit + 1.0) {\n discard;\n }\n }\n\n var color = varyings.vColor;\n\n // Feather one device pixel across the width only, before premultiplication. edgePixels is a\n // signed device-pixel distance and SMOOTH_EDGE_RADIUS is 0.5, so this ramps across one pixel.\n color.a *= smoothedge(0.0, edgePixels);\n#else\n#ifdef DASH_ENABLED\n if (\n varyings.vPathPosition.y < varyings.vPathBounds.x ||\n varyings.vPathPosition.y > varyings.vPathBounds.y\n ) {\n#else\n if (\n varyings.vPathPosition.y < 0.0 ||\n varyings.vPathPosition.y > varyings.vPathLength\n ) {\n#endif\n if (varyings.vJointType > 0.5 && length(varyings.vCornerOffset) > 1.0) {\n discard;\n }\n if (\n varyings.vJointType < 0.5 &&\n varyings.vMiterLength > path.miterLimit + 1.0\n ) {\n discard;\n }\n }\n#endif\n\n // Fragment-layer injections that discard pixels must run after analytic coverage derivatives.\n // See TripsLayer, which rejects fragments outside of the active time window at this anchor.\n // DECKGL_FILTER_COLOR\n clip_filterColor(varyings.clipCoordinates);\n#ifdef ANTIALIASING\n return deckgl_premultiplied_alpha(color);\n#else\n return deckgl_premultiplied_alpha(varyings.vColor);\n#endif\n}\n",defines:e?{ANTIALIASING:1}:{},modules:[Ye,Ze,Je,Vs,..."webgpu"===this.context.device.type?[ns]:[]]})}get wrapLongitude(){return!1}getBounds(){return"webgpu"===this.context.device.type?null:this.getAttributeManager()?.getBounds(["vertexPositions"])}getPathProjectionScale(e){const t=this.props.coordinateSystem;if(!Boolean(this.getAttributeManager()?.getAttributes().instanceDashOffsets))return null;if(e instanceof g&&e.zoom>=12&&("default"===t||"lnglat"===t||"cartesian"===t)){const n=l.getUniforms({viewport:e,coordinateSystem:t,coordinateOrigin:this.props.coordinateOrigin,autoWrapLongitude:this.wrapLongitude});return[e.projectionMode,n.coordinateOrigin[1],n.commonOrigin[1],...n.commonUnitsPerWorldUnit,...n.commonUnitsPerWorldUnit2,n.commonUnitsPerMeter[2]]}const n=function(e){if(e.isGeospatial)return null;const{unitsPerMeter:t}=e.distanceScales;return[t[0],t[1],t[2]]}(e);return n?[e.projectionMode,...n]:[e.projectionMode]}shouldUpdateState(e){const{viewport:t}=this.context;return super.shouldUpdateState(e)||this.state?.tessellationResolution!==t.resolution||!Zs(this.state?.pathProjectionScale,this.getPathProjectionScale(t))}initializeState(){const e=!0,t="webgpu"===this.context.device.type;this.getAttributeManager().addInstanced({...t?{pathPositions:{size:24,type:"float32",transition:!1,accessor:"getPath",update:this.calculateWebGPUPositions,shaderAttributes:{instanceLeftPositions:{size:3,elementOffset:0},instanceStartPositions:{size:3,elementOffset:3},instanceEndPositions:{size:3,elementOffset:6},instanceRightPositions:{size:3,elementOffset:9},instanceLeftPositions64Low:{size:3,elementOffset:12},instanceStartPositions64Low:{size:3,elementOffset:15},instanceEndPositions64Low:{size:3,elementOffset:18},instanceRightPositions64Low:{size:3,elementOffset:21}},noAlloc:e}}:{vertexPositions:{size:3,vertexOffset:1,type:"float64",fp64:this.use64bitPositions(),transition:Hs,accessor:"getPath",update:this.calculatePositions,noAlloc:e,shaderAttributes:{instanceLeftPositions:{vertexOffset:0},instanceStartPositions:{vertexOffset:1},instanceEndPositions:{vertexOffset:2},instanceRightPositions:{vertexOffset:3}}}},instanceTypes:{size:1,type:t?"float32":"uint8",update:this.calculateSegmentTypes,noAlloc:e},instanceStrokeWidths:{size:1,accessor:"getWidth",transition:!t&&Hs,defaultValue:1,bufferGroup:"path-instance-data"},instanceColors:{size:this.props.colorFormat.length,type:"unorm8",accessor:"getColor",transition:!t&&Hs,defaultValue:$s,bufferGroup:"path-instance-data"},rowIndexes:{size:1,type:"uint32",accessor:(e,{index:t})=>e&&e.__source?e.__source.index:t,bufferGroup:"path-instance-data"}}),this.setState({pathTesselator:new js({fp64:this.use64bitPositions(),isWebGPU:t}),tessellationResolution:this.context.viewport.resolution,pathProjectionScale:this.getPathProjectionScale(this.context.viewport)})}updateState(e){super.updateState(e);const{props:t,oldProps:n,changeFlags:i}=e,o=this.getAttributeManager(),{viewport:s}=this.context,r=this.state.tessellationResolution!==s.resolution,a=this.getPathProjectionScale(s),l=!Zs(this.state.pathProjectionScale,a),c=i.updateTriggersChanged&&(i.updateTriggersChanged.all||i.updateTriggersChanged.getPath)||t._pathType!==n._pathType||t.positionFormat!==n.positionFormat||t.wrapLongitude!==n.wrapLongitude||r;if(i.dataChanged||c){const{pathTesselator:e}=this.state,n=t.data.attributes||{};e.updateGeometry({data:t.data,geometryBuffer:n.getPath,buffers:n,normalize:!t._pathType,loop:"loop"===t._pathType,getGeometry:t.getPath,positionFormat:t.positionFormat,wrapLongitude:t.wrapLongitude,resolution:s.resolution,dataChanged:c?void 0:i.dataChanged}),this.setState({numInstances:e.instanceCount,startIndices:e.vertexStarts,tessellationResolution:s.resolution,pathProjectionScale:a}),!i.dataChanged||c?o.invalidateAll():l&&o.invalidate("instanceDashOffsets")}else l&&(this.setState({pathProjectionScale:a}),o.invalidate("instanceDashOffsets"));(i.extensionsChanged||t.antialiasing!==n.antialiasing)&&(this.state.model?.destroy(),this.state.model=this._getModel(),o.invalidateAll())}getPickingInfo(e){const t=super.getPickingInfo(e),{index:n}=t,i=this.props.data;return i[0]&&i[0].__source&&(t.object=i.find(e=>e.__source.index===n)),t}disablePickingIndex(e){const t=this.props.data;if(t[0]&&t[0].__source)for(let n=0;n<t.length;n++)t[n].__source.index===e&&this._disablePickingIndex(n);else super.disablePickingIndex(e)}draw({uniforms:e}){const{jointRounded:t,capRounded:n,billboard:o,miterLimit:s,widthUnits:r,widthScale:a,widthMinPixels:l,widthMaxPixels:c}=this.props,u=this.state.model,f={jointType:Number(t),capType:Number(n),billboard:o,widthUnits:i[r],widthScale:a,miterLimit:s,widthMinPixels:l,widthMaxPixels:c};u.shaderInputs.setProps({path:f}),u.draw(this.context.renderPass)}_getModel(){return new xt(this.context.device,{...this.getShaders(),id:this.props.id,bufferLayout:this.getAttributeManager().getBufferLayouts(),geometry:new nt({topology:"triangle-list",attributes:{indices:new Uint16Array([0,1,2,1,4,2,1,3,4,3,5,4]),positions:{value:new Float32Array([0,0,0,-1,0,1,1,-1,1,1,1,0]),size:2}}}),isInstanced:!0})}calculatePositions(e){const{pathTesselator:t}=this.state;e.startIndices=t.vertexStarts,e.value=t.get("positions")}calculateSegmentTypes(e){const{pathTesselator:t}=this.state;e.startIndices=t.vertexStarts,e.value=t.get("segmentTypes")}calculateWebGPUPositions(e){const{pathTesselator:t}=this.state,n=t.get("positions");if(!n)return void(e.value=null);const i=t.instanceCount,o=new Float32Array(24*i),s=[-1,0,1,2];for(let r=0;r<i;r++){const e=24*r;for(let t=0;t<4;t++){const a=r+s[t],l=e+3*t;for(let e=0;e<3;e++){const t=a>=0&&a<i?n[3*a+e]:0,s=Math.fround(t);o[l+e]=s,o[l+e+12]=t-s}}}e.startIndices=t.vertexStarts,e.value=o}};Ys.defaultProps=Ws,Ys.layerName="PathLayer";var qs=/* @__PURE__ */e(/* @__PURE__ */n((e,t)=>{function n(e,t,n){n=n||2;var o,r,a,l,c,d,p,h=t&&t.length,v=h?t[0]*n:e.length,m=i(e,0,v,n,!0),_=[];if(!m||m.next===m.prev)return _;if(h&&(m=function(e,t,n,o){for(var s,r=[],a=0,l=t.length;a<l;a++)(s=i(e,t[a]*o,a<l-1?t[a+1]*o:e.length,o,!1))===s.next&&(s.steiner=!0),r.push(g(s));for(r.sort(u),a=0;a<r.length;a++)n=f(r[a],n);return n}(e,t,m,n)),e.length>80*n){o=a=e[0],r=l=e[1];for(var x=n;x<v;x+=n)(c=e[x])<o&&(o=c),(d=e[x+1])<r&&(r=d),c>a&&(a=c),d>l&&(l=d);p=0!==(p=Math.max(a-o,l-r))?32767/p:0}return s(m,_,n,o,r,p,0),_}function i(e,t,n,i,o){var s,r;if(o===A(e,t,n,i)>0)for(s=t;s<n;s+=i)r=w(s,e[s],e[s+1],r);else for(s=n-i;s>=t;s-=i)r=w(s,e[s],e[s+1],r);return r&&_(r,r.next)&&(S(r),r=r.next),r}function o(e,t){if(!e)return e;t||(t=e);var n,i=e;do{if(n=!1,i.steiner||!_(i,i.next)&&0!==m(i.prev,i,i.next))i=i.next;else{if(S(i),(i=t=i.prev)===i.next)break;n=!0}}while(n||i!==t);return t}function s(e,t,n,i,u,f,d){if(e){!d&&f&&function(e,t,n,i){var o=e;do{0===o.z&&(o.z=p(o.x,o.y,t,n,i)),o.prevZ=o.prev,o.nextZ=o.next,o=o.next}while(o!==e);o.prevZ.nextZ=null,o.prevZ=null,function(e){var t,n,i,o,s,r,a,l,c=1;do{for(n=e,e=null,s=null,r=0;n;){for(r++,i=n,a=0,t=0;t<c&&(a++,i=i.nextZ);t++);for(l=c;a>0||l>0&&i;)0!==a&&(0===l||!i||n.z<=i.z)?(o=n,n=n.nextZ,a--):(o=i,i=i.nextZ,l--),s?s.nextZ=o:e=o,o.prevZ=s,s=o;n=i}s.nextZ=null,c*=2}while(r>1)}(o)}(e,i,u,f);for(var g,h,v=e;e.prev!==e.next;)if(g=e.prev,h=e.next,f?a(e,i,u,f):r(e))t.push(g.i/n|0),t.push(e.i/n|0),t.push(h.i/n|0),S(e),e=h.next,v=h.next;else if((e=h)===v){d?1===d?s(e=l(o(e),t,n),t,n,i,u,f,2):2===d&&c(e,t,n,i,u,f):s(o(e),t,n,i,u,f,1);break}}}function r(e){var t=e.prev,n=e,i=e.next;if(m(t,n,i)>=0)return!1;for(var o=t.x,s=n.x,r=i.x,a=t.y,l=n.y,c=i.y,u=o<s?o<r?o:r:s<r?s:r,f=a<l?a<c?a:c:l<c?l:c,d=o>s?o>r?o:r:s>r?s:r,p=a>l?a>c?a:c:l>c?l:c,g=i.next;g!==t;){if(g.x>=u&&g.x<=d&&g.y>=f&&g.y<=p&&h(o,a,s,l,r,c,g.x,g.y)&&m(g.prev,g,g.next)>=0)return!1;g=g.next}return!0}function a(e,t,n,i){var o=e.prev,s=e,r=e.next;if(m(o,s,r)>=0)return!1;for(var a=o.x,l=s.x,c=r.x,u=o.y,f=s.y,d=r.y,g=a<l?a<c?a:c:l<c?l:c,v=u<f?u<d?u:d:f<d?f:d,_=a>l?a>c?a:c:l>c?l:c,x=u>f?u>d?u:d:f>d?f:d,y=p(g,v,t,n,i),b=p(_,x,t,n,i),P=e.prevZ,C=e.nextZ;P&&P.z>=y&&C&&C.z<=b;){if(P.x>=g&&P.x<=_&&P.y>=v&&P.y<=x&&P!==o&&P!==r&&h(a,u,l,f,c,d,P.x,P.y)&&m(P.prev,P,P.next)>=0)return!1;if(P=P.prevZ,C.x>=g&&C.x<=_&&C.y>=v&&C.y<=x&&C!==o&&C!==r&&h(a,u,l,f,c,d,C.x,C.y)&&m(C.prev,C,C.next)>=0)return!1;C=C.nextZ}for(;P&&P.z>=y;){if(P.x>=g&&P.x<=_&&P.y>=v&&P.y<=x&&P!==o&&P!==r&&h(a,u,l,f,c,d,P.x,P.y)&&m(P.prev,P,P.next)>=0)return!1;P=P.prevZ}for(;C&&C.z<=b;){if(C.x>=g&&C.x<=_&&C.y>=v&&C.y<=x&&C!==o&&C!==r&&h(a,u,l,f,c,d,C.x,C.y)&&m(C.prev,C,C.next)>=0)return!1;C=C.nextZ}return!0}function l(e,t,n){var i=e;do{var s=i.prev,r=i.next.next;!_(s,r)&&x(s,i,i.next,r)&&P(s,r)&&P(r,s)&&(t.push(s.i/n|0),t.push(i.i/n|0),t.push(r.i/n|0),S(i),S(i.next),i=e=r),i=i.next}while(i!==e);return o(i)}function c(e,t,n,i,r,a){var l=e;do{for(var c=l.next.next;c!==l.prev;){if(l.i!==c.i&&v(l,c)){var u=C(l,c);return l=o(l,l.next),u=o(u,u.next),s(l,t,n,i,r,a,0),void s(u,t,n,i,r,a,0)}c=c.next}l=l.next}while(l!==e)}function u(e,t){return e.x-t.x}function f(e,t){var n=function(e,t){var n,i=t,o=e.x,s=e.y,r=-1/0;do{if(s<=i.y&&s>=i.next.y&&i.next.y!==i.y){var a=i.x+(s-i.y)*(i.next.x-i.x)/(i.next.y-i.y);if(a<=o&&a>r&&(r=a,n=i.x<i.next.x?i:i.next,a===o))return n}i=i.next}while(i!==t);if(!n)return null;var l,c=n,u=n.x,f=n.y,p=1/0;i=n;do{o>=i.x&&i.x>=u&&o!==i.x&&h(s<f?o:r,s,u,f,s<f?r:o,s,i.x,i.y)&&(l=Math.abs(s-i.y)/(o-i.x),P(i,e)&&(l<p||l===p&&(i.x>n.x||i.x===n.x&&d(n,i)))&&(n=i,p=l)),i=i.next}while(i!==c);return n}(e,t);if(!n)return t;var i=C(n,e);return o(i,i.next),o(n,n.next)}function d(e,t){return m(e.prev,e,t.prev)<0&&m(t.next,e,e.next)<0}function p(e,t,n,i,o){return(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-n)*o|0)|e<<8))|e<<4))|e<<2))|e<<1))|(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-i)*o|0)|t<<8))|t<<4))|t<<2))|t<<1))<<1}function g(e){var t=e,n=e;do{(t.x<n.x||t.x===n.x&&t.y<n.y)&&(n=t),t=t.next}while(t!==e);return n}function h(e,t,n,i,o,s,r,a){return(o-r)*(t-a)>=(e-r)*(s-a)&&(e-r)*(i-a)>=(n-r)*(t-a)&&(n-r)*(s-a)>=(o-r)*(i-a)}function v(e,t){return e.next.i!==t.i&&e.prev.i!==t.i&&!function(e,t){var n=e;do{if(n.i!==e.i&&n.next.i!==e.i&&n.i!==t.i&&n.next.i!==t.i&&x(n,n.next,e,t))return!0;n=n.next}while(n!==e);return!1}(e,t)&&(P(e,t)&&P(t,e)&&function(e,t){var n=e,i=!1,o=(e.x+t.x)/2,s=(e.y+t.y)/2;do{n.y>s!=n.next.y>s&&n.next.y!==n.y&&o<(n.next.x-n.x)*(s-n.y)/(n.next.y-n.y)+n.x&&(i=!i),n=n.next}while(n!==e);return i}(e,t)&&(m(e.prev,e,t.prev)||m(e,t.prev,t))||_(e,t)&&m(e.prev,e,e.next)>0&&m(t.prev,t,t.next)>0)}function m(e,t,n){return(t.y-e.y)*(n.x-t.x)-(t.x-e.x)*(n.y-t.y)}function _(e,t){return e.x===t.x&&e.y===t.y}function x(e,t,n,i){var o=b(m(e,t,n)),s=b(m(e,t,i)),r=b(m(n,i,e)),a=b(m(n,i,t));return o!==s&&r!==a||(!(0!==o||!y(e,n,t))||(!(0!==s||!y(e,i,t))||(!(0!==r||!y(n,e,i))||!(0!==a||!y(n,t,i)))))}function y(e,t,n){return t.x<=Math.max(e.x,n.x)&&t.x>=Math.min(e.x,n.x)&&t.y<=Math.max(e.y,n.y)&&t.y>=Math.min(e.y,n.y)}function b(e){return e>0?1:e<0?-1:0}function P(e,t){return m(e.prev,e,e.next)<0?m(e,t,e.next)>=0&&m(e,e.prev,t)>=0:m(e,t,e.prev)<0||m(e,e.next,t)<0}function C(e,t){var n=new L(e.i,e.x,e.y),i=new L(t.i,t.x,t.y),o=e.next,s=t.prev;return e.next=t,t.prev=e,n.next=o,o.prev=n,i.next=n,n.prev=i,s.next=i,i.prev=s,i}function w(e,t,n,i){var o=new L(e,t,n);return i?(o.next=i.next,o.prev=i,i.next.prev=o,i.next=o):(o.prev=o,o.next=o),o}function S(e){e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ)}function L(e,t,n){this.i=e,this.x=t,this.y=n,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}function A(e,t,n,i){for(var o=0,s=t,r=n-i;s<n;s+=i)o+=(e[r]-e[s])*(e[s+1]+e[r+1]),r=s;return o}t.exports=n,t.exports.default=n,n.deviation=function(e,t,n,i){var o=t&&t.length,s=o?t[0]*n:e.length,r=Math.abs(A(e,0,s,n));if(o)for(var a=0,l=t.length;a<l;a++){var c=t[a]*n,u=a<l-1?t[a+1]*n:e.length;r-=Math.abs(A(e,c,u,n))}var f=0;for(a=0;a<i.length;a+=3){var d=i[a]*n,p=i[a+1]*n,g=i[a+2]*n;f+=Math.abs((e[d]-e[g])*(e[p+1]-e[d+1])-(e[d]-e[p])*(e[g+1]-e[d+1]))}return 0===r&&0===f?0:Math.abs((f-r)/r)},n.flatten=function(e){for(var t=e[0][0].length,n={vertices:[],holes:[],dimensions:t},i=0,o=0;o<e.length;o++){for(var s=0;s<e[o].length;s++)for(var r=0;r<t;r++)n.vertices.push(e[o][s][r]);o>0&&(i+=e[o-1].length,n.holes.push(i))}return n}})(),1),Ks=rs,Xs=as,Js={isClosed:!0};function Qs(e){return"positions"in e?e.positions:e}function er(e){return"holeIndices"in e?e.holeIndices:null}function tr(e,t,n,i,o){let s=t;const r=n.length;for(let a=0;a<r;a++)for(let t=0;t<i;t++)e[s++]=n[a][t]||0;if(!function(e){const t=e[0],n=e[e.length-1];return t[0]===n[0]&&t[1]===n[1]&&t[2]===n[2]}(n))for(let a=0;a<i;a++)e[s++]=n[0][a]||0;return Js.start=t,Js.end=s,Js.size=i,ls(e,o,Js),s}function nr(e,t,n,i,o=0,s,r){const a=(s=s||n.length)-o;if(a<=0)return t;let l=t;for(let c=0;c<a;c++)e[l++]=n[o+c];if(!function(e,t,n,i){for(let o=0;o<t;o++)if(e[n+o]!==e[i-t+o])return!1;return!0}(n,i,o,s))for(let c=0;c<i;c++)e[l++]=n[o+c];return Js.start=t,Js.end=l,Js.size=i,ls(e,r,Js),l}function ir(e,t){!function(e){if(e=e&&e.positions||e,!Array.isArray(e)&&!ArrayBuffer.isView(e))throw new Error("invalid polygon")}(e);const n=[],i=[];if("positions"in e){const{positions:o,holeIndices:s}=e;if(s){let e=0;for(let r=0;r<=s.length;r++)e=nr(n,e,o,t,s[r-1],s[r],0===r?Ks:Xs),i.push(e);return i.pop(),{positions:n,holeIndices:i}}e=o}if(!function(e){return Array.isArray(e[0])}(e))return nr(n,0,e,t,0,n.length,Ks),n;if(!function(e){return e.length>=1&&e[0].length>=2&&Number.isFinite(e[0][0])}(e)){let o=0;for(const[s,r]of e.entries())o=tr(n,o,r,t,0===s?Ks:Xs),i.push(o);return i.pop(),{positions:n,holeIndices:i}}return tr(n,0,e,t,Ks),n}function or(e,t,n){const i=e.length/3;let o=0;for(let s=0;s<i;s++){const r=(s+1)%i;o+=e[3*s+t]*e[3*r+n],o-=e[3*r+t]*e[3*s+n]}return Math.abs(o/2)}function sr(e,t,n,i){const o=e.length/3;for(let s=0;s<o;s++){const o=3*s,r=e[o+0],a=e[o+1],l=e[o+2];e[o+t]=r,e[o+n]=a,e[o+i]=l}}var rr=class extends po{constructor(e){const{fp64:t,IndexType:n=Uint32Array}=e;super({...e,attributes:{positions:{size:3,type:t?Float64Array:Float32Array},vertexValid:{type:Uint16Array,size:1},indices:{type:n,size:1}}})}get(e){const{attributes:t}=this;return"indices"===e?t.indices&&t.indices.subarray(0,this.vertexCount):t[e]}updateGeometry(e){super.updateGeometry(e);const t=this.buffers.indices;if(t)this.vertexCount=(t.value||t).length;else if(this.data&&!this.getGeometry)throw new Error("missing indices buffer")}normalizeGeometry(e){if(this.normalize){const t=ir(e,this.positionSize);return this.opts.resolution?ms(Qs(t),er(t),{size:this.positionSize,gridResolution:this.opts.resolution,edgeTypes:!0}):this.opts.wrapLongitude?function(e,t=null,n){const{size:i=2,normalize:o=!0,edgeTypes:s=!1}=n||{};t=t||[];const r=[],a=[];let l=0,c=0;for(let f=0;f<=t.length;f++){const o=t[f]||e.length,s=c,u=Cs(e,i,l,o);for(let t=u;t<o;t++)r[c++]=e[t];for(let t=l;t<u;t++)r[c++]=e[t];Ss(r,i,s,c),ws(r,i,s,c,n?.maxLatitude),l=o,a[f]=c}a.pop();const u=ms(r,a,{size:i,gridResolution:360,gridOffset:[-180,-180],edgeTypes:s});if(o)for(const f of u)Ls(f.positions,i);return u}(Qs(t),er(t),{size:this.positionSize,maxLatitude:86,edgeTypes:!0}):t}return e}getGeometrySize(e){if(ar(e)){let t=0;for(const n of e)t+=this.getGeometrySize(n);return t}return Qs(e).length/this.positionSize}getGeometryFromBuffer(e){return this.normalize||!this.buffers.indices?super.getGeometryFromBuffer(e):null}updateGeometryAttributes(e,t){if(e&&ar(e))for(const n of e){const e=this.getGeometrySize(n);t.geometrySize=e,this.updateGeometryAttributes(n,t),t.vertexStart+=e,t.indexStart=this.indexStarts[t.geometryIndex+1]}else{const n=e;this._updateIndices(n,t),this._updatePositions(n,t),this._updateVertexValid(n,t)}}_updateIndices(e,{geometryIndex:t,vertexStart:n,indexStart:i}){const{attributes:o,indexStarts:s,typedArrayManager:r}=this;let a=o.indices;if(!a||!e)return;let l=i;const c=function(e,t,n,i){let o=er(e);o&&(o=o.map(e=>e/t));let s=Qs(e);const r=i&&3===t;if(n){const e=s.length;s=s.slice();const i=[];for(let o=0;o<e;o+=t){i[0]=s[o],i[1]=s[o+1],r&&(i[2]=s[o+2]);const e=n(i);s[o]=e[0],s[o+1]=e[1],r&&(s[o+2]=e[2])}}if(r){const e=or(s,0,1),t=or(s,0,2),i=or(s,1,2);if(!e&&!t&&!i)return[];e>t&&e>i||(t>i?(n||(s=s.slice()),sr(s,0,2,1)):(n||(s=s.slice()),sr(s,2,0,1)))}return(0,qs.default)(s,o,t)}(e,this.positionSize,this.opts.preproject,this.opts.full3d);a=r.allocate(a,i+c.length,{copy:!0});for(let u=0;u<c.length;u++)a[l++]=c[u]+n;s[t+1]=i+c.length,o.indices=a}_updatePositions(e,{vertexStart:t,geometrySize:n}){const{attributes:{positions:i},positionSize:o}=this;if(!i||!e)return;const s=Qs(e);for(let r=t,a=0;a<n;r++,a++){const e=s[a*o],t=s[a*o+1],n=o>2?s[a*o+2]:0;i[3*r]=e,i[3*r+1]=t,i[3*r+2]=n}}_updateVertexValid(e,{vertexStart:t,geometrySize:n}){const{positionSize:i}=this,o=this.attributes.vertexValid,s=e&&er(e);if(e&&e.edgeTypes?o.set(e.edgeTypes,t):o.fill(1,t,t+n),s)for(let r=0;r<s.length;r++)o[t+s[r]/i-1]=0;o[t+n-1]=0}};function ar(e){return Array.isArray(e)&&e.length>0&&!Number.isFinite(e[0])}var lr="layout(std140) uniform solidPolygonUniforms {\n bool extruded;\n bool isWireframe;\n float elevationScale;\n} solidPolygon;\n",cr={name:"solidPolygon",source:"struct SolidPolygonUniforms {\n extruded: f32,\n isWireframe: f32,\n elevationScale: f32,\n};\n\n@group(0) @binding(auto) var<uniform> solidPolygon: SolidPolygonUniforms;\n",vs:lr,fs:lr,uniformTypes:{extruded:"f32",isWireframe:"f32",elevationScale:"f32"}},ur="in vec4 fillColors;\nin vec4 lineColors;\nin float rowIndexes;\nout vec4 vColor;\nstruct PolygonProps {\nvec3 positions;\nvec3 positions64Low;\nvec3 normal;\nfloat elevations;\n};\nvec3 project_offset_normal(vec3 vector) {\nif (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT ||\nproject.coordinateSystem == COORDINATE_SYSTEM_LNGLAT_OFFSETS) {\nreturn normalize(vector * project.commonUnitsPerWorldUnit);\n}\nreturn project_normal(vector);\n}\nvoid calculatePosition(PolygonProps props) {\nvec3 pos = props.positions;\nvec3 pos64Low = props.positions64Low;\nvec3 normal = props.normal;\nvec4 colors = solidPolygon.isWireframe ? lineColors : fillColors;\ngeometry.worldPosition = props.positions;\ngeometry.pickingColor = picking_getPickingColorFromIndex(rowIndexes);\nif (solidPolygon.extruded) {\npos.z += props.elevations * solidPolygon.elevationScale;\n}\ngl_Position = project_position_to_clipspace(pos, pos64Low, vec3(0.), geometry.position);\nDECKGL_FILTER_GL_POSITION(gl_Position, geometry);\nif (solidPolygon.extruded) {\n#ifdef IS_SIDE_VERTEX\nnormal = project_offset_normal(normal);\n#else\nnormal = project_normal(normal);\n#endif\ngeometry.normal = normal;\nvec3 lightColor = lighting_getLightColor(colors.rgb, project.cameraPosition, geometry.position.xyz, geometry.normal);\nvColor = vec4(lightColor, colors.a * layer.opacity);\n} else {\nvColor = vec4(colors.rgb, colors.a * layer.opacity);\n}\nDECKGL_FILTER_COLOR(vColor, geometry);\n}\n",fr=`#version 300 es\n#define SHADER_NAME solid-polygon-layer-vertex-shader\nin vec3 vertexPositions;\nin vec3 vertexPositions64Low;\nin float elevations;\n${ur}\nvoid main(void) {\nPolygonProps props;\nprops.positions = vertexPositions;\nprops.positions64Low = vertexPositions64Low;\nprops.elevations = elevations;\nprops.normal = vec3(0.0, 0.0, 1.0);\ncalculatePosition(props);\n}\n`,dr=`#version 300 es\n#define SHADER_NAME solid-polygon-layer-vertex-shader-side\n#define IS_SIDE_VERTEX\nin vec2 positions;\nin vec3 vertexPositions;\nin vec3 nextVertexPositions;\nin vec3 vertexPositions64Low;\nin vec3 nextVertexPositions64Low;\nin float elevations;\nin float instanceVertexValid;\n${ur}\nvoid main(void) {\nif(instanceVertexValid < 0.5){\ngl_Position = vec4(0.);\nreturn;\n}\nPolygonProps props;\nvec3 pos;\nvec3 pos64Low;\nvec3 nextPos;\nvec3 nextPos64Low;\n#if RING_WINDING_ORDER_CW == 1\npos = vertexPositions;\npos64Low = vertexPositions64Low;\nnextPos = nextVertexPositions;\nnextPos64Low = nextVertexPositions64Low;\n#else\npos = nextVertexPositions;\npos64Low = nextVertexPositions64Low;\nnextPos = vertexPositions;\nnextPos64Low = vertexPositions64Low;\n#endif\nprops.positions = mix(pos, nextPos, positions.x);\nprops.positions64Low = mix(pos64Low, nextPos64Low, positions.x);\nprops.normal = vec3(\npos.y - nextPos.y + (pos64Low.y - nextPos64Low.y),\nnextPos.x - pos.x + (nextPos64Low.x - pos64Low.x),\n0.0);\nprops.elevations = elevations * positions.y;\ncalculatePosition(props);\n}\n`;function pr(e,t){return"top"===e?"fn project_offset_normal(vector: vec3<f32>) -> vec3<f32> {\n if (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT ||\n project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT_OFFSETS) {\n return normalize(vector * project.commonUnitsPerWorldUnit);\n }\n return project_normal(vector);\n}\n\nfn apply_polygon_color(\n colors: vec4<f32>,\n normal: vec3<f32>,\n position: vec4<f32>\n) -> vec4<f32> {\n if (solidPolygon.extruded > 0.5) {\n let lightColor = lighting_getLightColor2(\n colors.rgb,\n project.cameraPosition,\n position.xyz,\n normal\n );\n return vec4<f32>(lightColor, colors.a * layer.opacity);\n }\n return vec4<f32>(colors.rgb, colors.a * layer.opacity);\n}\n\n\nstruct Attributes {\n @location(0) vertexPositions: vec3<f32>,\n @location(1) vertexPositions64Low: vec3<f32>,\n @location(2) elevations: f32,\n @location(3) fillColors: vec4<f32>,\n @location(4) lineColors: vec4<f32>,\n @location(5) rowIndexes: u32,\n};\n\nstruct Varyings {\n @builtin(position) position: vec4<f32>,\n @location(0) vColor: vec4<f32>,\n @location(1) pickingColor: vec3<f32>,\n @location(2) clipCoordinates: vec2<f32>,\n};\n\n@vertex\nfn vertexMain(attributes: Attributes) -> Varyings {\n var outp: Varyings;\n\n var pos = attributes.vertexPositions;\n if (solidPolygon.extruded > 0.5) {\n pos.z += attributes.elevations * solidPolygon.elevationScale;\n }\n\n geometry.worldPosition = attributes.vertexPositions;\n geometry.pickingColor = picking_getPickingColorFromIndex(attributes.rowIndexes);\n\n let projectedPosition = project_position_to_clipspace_and_commonspace(\n pos,\n attributes.vertexPositions64Low,\n vec3<f32>(0.0)\n );\n geometry.position = projectedPosition.commonPosition;\n outp.position = projectedPosition.clipPosition;\n\n let normal = project_normal(vec3<f32>(0.0, 0.0, 1.0));\n geometry.normal = normal;\n\n let colors = select(\n attributes.fillColors,\n attributes.lineColors,\n solidPolygon.isWireframe > 0.5\n );\n outp.vColor = apply_polygon_color(colors, normal, geometry.position);\n outp.pickingColor = geometry.pickingColor;\n\n outp.clipCoordinates = geometry.position.xy;\n clip_filterPosition(&outp.position, geometry.worldPosition.xy);\n\n return outp;\n}\n\n@fragment\nfn fragmentMain(inp: Varyings) -> @location(0) vec4<f32> {\n geometry.uv = vec2<f32>(0.0, 0.0);\n\n clip_filterColor(inp.clipCoordinates);\n\n if (picking.isActive > 0.5) {\n if (!picking_isColorValid(inp.pickingColor)) {\n discard;\n }\n return vec4<f32>(inp.pickingColor, 1.0);\n }\n\n var fragColor = inp.vColor;\n\n if (picking.isHighlightActive > 0.5) {\n let highlightedObjectColor = picking_normalizeColor(picking.highlightedObjectColor);\n if (picking_isColorZero(abs(inp.pickingColor - highlightedObjectColor))) {\n let highLightAlpha = picking.highlightColor.a;\n let blendedAlpha = highLightAlpha + fragColor.a * (1.0 - highLightAlpha);\n if (blendedAlpha > 0.0) {\n let highLightRatio = highLightAlpha / blendedAlpha;\n fragColor = vec4<f32>(\n mix(fragColor.rgb, picking.highlightColor.rgb, highLightRatio),\n blendedAlpha\n );\n } else {\n fragColor = vec4<f32>(fragColor.rgb, 0.0);\n }\n }\n }\n\n return deckgl_premultiplied_alpha(fragColor);\n}\n\n":function(e){return`const RING_WINDING_ORDER_CW: bool = ${e?"true":"false"};\n\nfn project_offset_normal(vector: vec3<f32>) -> vec3<f32> {\n if (project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT ||\n project.coordinateSystem == COORDINATE_SYSTEM_LNGLAT_OFFSETS) {\n return normalize(vector * project.commonUnitsPerWorldUnit);\n }\n return project_normal(vector);\n}\n\nfn apply_polygon_color(\n colors: vec4<f32>,\n normal: vec3<f32>,\n position: vec4<f32>\n) -> vec4<f32> {\n if (solidPolygon.extruded > 0.5) {\n let lightColor = lighting_getLightColor2(\n colors.rgb,\n project.cameraPosition,\n position.xyz,\n normal\n );\n return vec4<f32>(lightColor, colors.a * layer.opacity);\n }\n return vec4<f32>(colors.rgb, colors.a * layer.opacity);\n}\n\n\nstruct Attributes {\n @location(0) positions: vec2<f32>,\n @location(1) vertexPositions: vec3<f32>,\n @location(2) vertexPositions64Low: vec3<f32>,\n @location(3) nextVertexPositions: vec3<f32>,\n @location(4) nextVertexPositions64Low: vec3<f32>,\n @location(5) vertexValid: f32,\n @location(6) elevations: f32,\n @location(7) fillColors: vec4<f32>,\n @location(8) lineColors: vec4<f32>,\n @location(9) rowIndexes: u32,\n};\n\nstruct Varyings {\n @builtin(position) position: vec4<f32>,\n @location(0) vColor: vec4<f32>,\n @location(1) pickingColor: vec3<f32>,\n @location(2) clipCoordinates: vec2<f32>,\n};\n\n@vertex\nfn vertexMain(attributes: Attributes) -> Varyings {\n var outp: Varyings;\n outp.position = vec4<f32>(0.0);\n outp.vColor = vec4<f32>(0.0);\n outp.pickingColor = picking_getPickingColorFromIndex(attributes.rowIndexes);\n outp.clipCoordinates = vec2<f32>(0.0);\n\n if (attributes.vertexValid < 0.5) {\n return outp;\n }\n\n let pos = select(attributes.nextVertexPositions, attributes.vertexPositions, RING_WINDING_ORDER_CW);\n let pos64Low = select(\n attributes.nextVertexPositions64Low,\n attributes.vertexPositions64Low,\n RING_WINDING_ORDER_CW\n );\n let nextPos = select(attributes.vertexPositions, attributes.nextVertexPositions, RING_WINDING_ORDER_CW);\n let nextPos64Low = select(\n attributes.vertexPositions64Low,\n attributes.nextVertexPositions64Low,\n RING_WINDING_ORDER_CW\n );\n\n let position = mix(pos, nextPos, attributes.positions.x);\n let position64Low = mix(pos64Low, nextPos64Low, attributes.positions.x);\n\n var worldPosition = position;\n if (solidPolygon.extruded > 0.5) {\n worldPosition.z += attributes.elevations * attributes.positions.y * solidPolygon.elevationScale;\n }\n\n geometry.worldPosition = position;\n geometry.pickingColor = picking_getPickingColorFromIndex(attributes.rowIndexes);\n\n let projectedPosition = project_position_to_clipspace_and_commonspace(\n worldPosition,\n position64Low,\n vec3<f32>(0.0)\n );\n geometry.position = projectedPosition.commonPosition;\n outp.position = projectedPosition.clipPosition;\n\n let normal = project_offset_normal(vec3<f32>(\n pos.y - nextPos.y + (pos64Low.y - nextPos64Low.y),\n nextPos.x - pos.x + (nextPos64Low.x - pos64Low.x),\n 0.0\n ));\n geometry.normal = normal;\n\n let colors = select(\n attributes.fillColors,\n attributes.lineColors,\n solidPolygon.isWireframe > 0.5\n );\n outp.vColor = apply_polygon_color(colors, normal, geometry.position);\n outp.pickingColor = geometry.pickingColor;\n\n outp.clipCoordinates = geometry.position.xy;\n clip_filterPosition(&outp.position, geometry.worldPosition.xy);\n\n return outp;\n}\n\n@fragment\nfn fragmentMain(inp: Varyings) -> @location(0) vec4<f32> {\n geometry.uv = vec2<f32>(0.0, 0.0);\n\n clip_filterColor(inp.clipCoordinates);\n\n if (picking.isActive > 0.5) {\n if (!picking_isColorValid(inp.pickingColor)) {\n discard;\n }\n return vec4<f32>(inp.pickingColor, 1.0);\n }\n\n var fragColor = inp.vColor;\n\n if (picking.isHighlightActive > 0.5) {\n let highlightedObjectColor = picking_normalizeColor(picking.highlightedObjectColor);\n if (picking_isColorZero(abs(inp.pickingColor - highlightedObjectColor))) {\n let highLightAlpha = picking.highlightColor.a;\n let blendedAlpha = highLightAlpha + fragColor.a * (1.0 - highLightAlpha);\n if (blendedAlpha > 0.0) {\n let highLightRatio = highLightAlpha / blendedAlpha;\n fragColor = vec4<f32>(\n mix(fragColor.rgb, picking.highlightColor.rgb, highLightRatio),\n blendedAlpha\n );\n } else {\n fragColor = vec4<f32>(fragColor.rgb, 0.0);\n }\n }\n }\n\n return deckgl_premultiplied_alpha(fragColor);\n}\n\n`}(t)}var gr=[0,0,0,255],hr={filled:!0,extruded:!1,wireframe:!1,_normalize:!0,_windingOrder:"CW",_full3d:!1,elevationScale:{type:"number",min:0,value:1},getPolygon:{type:"accessor",value:e=>e.polygon},getElevation:{type:"accessor",value:1e3},getFillColor:{type:"accessor",value:gr},getLineColor:{type:"accessor",value:gr},material:!0},vr={enter:(e,t)=>t.length?t.subarray(t.length-e.length):e},mr=class extends co{getShaders(e){const t=this.props._normalize||"CCW"!==this.props._windingOrder?1:0;return super.getShaders({vs:"top"===e?fr:dr,fs:"#version 300 es\n#define SHADER_NAME solid-polygon-layer-fragment-shader\nprecision highp float;\nin vec4 vColor;\nout vec4 fragColor;\nvoid main(void) {\nfragColor = vColor;\ngeometry.uv = vec2(0.);\nDECKGL_FILTER_COLOR(fragColor, geometry);\n}\n",source:pr(e,Boolean(t)),defines:{RING_WINDING_ORDER_CW:t},modules:[Ye,Ze,We,Je,cr,..."webgpu"===this.context.device.type?[ns]:[]]})}get wrapLongitude(){return!1}getBounds(){return this.getAttributeManager()?.getBounds(["vertexPositions"])}initializeState(){const{viewport:e}=this.context;let{coordinateSystem:t}=this.props;const{_full3d:n}=this.props;let i;e.isGeospatial&&"default"===t&&(t="lnglat"),"lnglat"===t&&(i=n?e.projectPosition.bind(e):e.projectFlat.bind(e)),this.setState({numInstances:0,polygonTesselator:new rr({preproject:i,fp64:this.use64bitPositions(),IndexType:Uint32Array})});const o=this.getAttributeManager(),s=!0,r="webgpu"===this.context.device.type;o.add({indices:{size:1,isIndexed:!0,update:this.calculateIndices,noAlloc:s},vertexPositions:{size:3,type:"float64",stepMode:"dynamic",fp64:this.use64bitPositions(),transition:vr,accessor:"getPolygon",update:this.calculatePositions,noAlloc:s,shaderAttributes:{nextVertexPositions:{vertexOffset:1}}},[r?"vertexValid":"instanceVertexValid"]:{size:1,type:r?"float32":"uint16",stepMode:"instance",update:this.calculateVertexValid,noAlloc:s},elevations:{size:1,stepMode:"dynamic",transition:vr,accessor:"getElevation",bufferGroup:"solid-polygon-instance-data"},fillColors:{size:this.props.colorFormat.length,type:"unorm8",stepMode:"dynamic",transition:vr,accessor:"getFillColor",defaultValue:gr,bufferGroup:"solid-polygon-instance-data"},lineColors:{size:this.props.colorFormat.length,type:"unorm8",stepMode:"dynamic",transition:vr,accessor:"getLineColor",defaultValue:gr,bufferGroup:"solid-polygon-instance-data"},rowIndexes:{size:1,type:"uint32",stepMode:"dynamic",accessor:(e,{index:t})=>e&&e.__source?e.__source.index:t,bufferGroup:"solid-polygon-instance-data"}})}getPickingInfo(e){const t=super.getPickingInfo(e),{index:n}=t,i=this.props.data;return i[0]&&i[0].__source&&(t.object=i.find(e=>e.__source.index===n)),t}disablePickingIndex(e){const t=this.props.data;if(t[0]&&t[0].__source)for(let n=0;n<t.length;n++)t[n].__source.index===e&&this._disablePickingIndex(n);else super.disablePickingIndex(e)}draw({uniforms:e}){const{extruded:t,filled:n,wireframe:i,elevationScale:o}=this.props,{topModel:s,sideModel:r,wireframeModel:a,polygonTesselator:l}=this.state,c={extruded:Boolean(t),elevationScale:o,isWireframe:!1};a&&i&&(a.setInstanceCount(l.instanceCount-1),a.shaderInputs.setProps({solidPolygon:{...c,isWireframe:!0}}),a.draw(this.context.renderPass)),r&&n&&(r.setInstanceCount(l.instanceCount-1),r.shaderInputs.setProps({solidPolygon:c}),r.draw(this.context.renderPass)),s&&n&&(s.setVertexCount(l.vertexCount),s.shaderInputs.setProps({solidPolygon:c}),s.draw(this.context.renderPass))}updateState(e){super.updateState(e),this.updateGeometry(e);const{props:t,oldProps:n,changeFlags:i}=e,o=this.getAttributeManager();(i.extensionsChanged||t.filled!==n.filled||t.extruded!==n.extruded)&&(this.state.models?.forEach(e=>e.destroy()),this.setState(this._getModels()),o.invalidateAll())}updateGeometry({props:e,oldProps:t,changeFlags:n}){if(n.dataChanged||n.updateTriggersChanged&&(n.updateTriggersChanged.all||n.updateTriggersChanged.getPolygon)){const{polygonTesselator:t}=this.state,i=e.data.attributes||{};t.updateGeometry({data:e.data,normalize:e._normalize,geometryBuffer:i.getPolygon,buffers:i,getGeometry:e.getPolygon,positionFormat:e.positionFormat,wrapLongitude:e.wrapLongitude,resolution:this.context.viewport.resolution,fp64:this.use64bitPositions(),dataChanged:n.dataChanged,full3d:e._full3d}),this.setState({numInstances:t.instanceCount,startIndices:t.vertexStarts}),n.dataChanged||this.getAttributeManager().invalidateAll()}}_getModels(){const{id:e,filled:t,extruded:n}=this.props;let i,o,s;if(t){const t=this.getShaders("top");t.defines={...t.defines,NON_INSTANCED_MODEL:1};let n=this.getAttributeManager().getBufferLayouts({isInstanced:!1});"webgpu"===this.context.device.type&&(n=n.filter(e=>"indices"!==e.name&&"vertexValid"!==e.name&&"instanceVertexValid"!==e.name&&"nextVertexPositions"!==e.name)),i=new xt(this.context.device,{...t,id:`${e}-top`,topology:"triangle-list",bufferLayout:n,isIndexed:!0,userData:{excludeAttributes:{vertexValid:!0,instanceVertexValid:!0,nextVertexPositions:!0}}})}if(n){let t=this.getAttributeManager().getBufferLayouts({isInstanced:!0});"webgpu"===this.context.device.type&&(t=t.filter(e=>"indices"!==e.name)),o=new xt(this.context.device,{...this.getShaders("side"),id:`${e}-side`,bufferLayout:t,geometry:new nt({topology:"triangle-strip",attributes:{positions:{size:2,value:new Float32Array([1,0,0,0,1,1,0,1])}}}),isInstanced:!0,userData:{excludeAttributes:{indices:!0}}}),s=new xt(this.context.device,{...this.getShaders("side"),id:`${e}-wireframe`,bufferLayout:t,geometry:new nt({topology:"line-strip",attributes:{positions:{size:2,value:new Float32Array([1,0,0,0,0,1,1,1])}}}),isInstanced:!0,userData:{excludeAttributes:{indices:!0}}})}return{models:[o,s,i].filter(Boolean),topModel:i,sideModel:o,wireframeModel:s}}calculateIndices(e){const{polygonTesselator:t}=this.state;e.startIndices=t.indexStarts,e.value=t.get("indices")}calculatePositions(e){const{polygonTesselator:t}=this.state;e.startIndices=t.vertexStarts,e.value=t.get("positions")}calculateVertexValid(e){const t=this.props.data.attributes?.instanceVertexValid?.value,n="webgpu"===this.context.device.type&&t?t:this.state.polygonTesselator.get("vertexValid");e.value="webgpu"===this.context.device.type&&n?Float32Array.from(n):n}};function _r({data:e,getIndex:t,dataRange:n,replace:i}){const{startRow:o=0,endRow:s=1/0}=n,r=e.length;let a=r,l=r;for(let f=0;f<r;f++){const n=t(e[f]);if(a>f&&n>=o&&(a=f),n>=s){l=f;break}}let c=a;const u=l-a!==i.length?e.slice(l):void 0;for(let f=0;f<i.length;f++)e[c++]=i[f];if(u){for(let t=0;t<u.length;t++)e[c++]=u[t];e.length=c}return{startRow:a,endRow:a+i.length}}mr.defaultProps=hr,mr.layerName="SolidPolygonLayer";var xr=[0,0,0,255],yr={stroked:!0,filled:!0,extruded:!1,elevationScale:1,wireframe:!1,_normalize:!0,_windingOrder:"CW",lineWidthUnits:"meters",lineWidthScale:1,lineWidthMinPixels:0,lineWidthMaxPixels:Number.MAX_SAFE_INTEGER,lineJointRounded:!1,lineMiterLimit:4,lineAntialiasing:!1,getPolygon:{type:"accessor",value:e=>e.polygon},getFillColor:{type:"accessor",value:[0,0,0,255]},getLineColor:{type:"accessor",value:xr},getLineWidth:{type:"accessor",value:1},getElevation:{type:"accessor",value:1e3},material:!0},br=class extends fo{initializeState(){this.state={paths:[],pathsDiff:null},this.props.getLineDashArray&&I.removed("getLineDashArray","PathStyleExtension")()}updateState({changeFlags:e}){const t=e.dataChanged||e.updateTriggersChanged&&(e.updateTriggersChanged.all||e.updateTriggersChanged.getPolygon);if(t&&Array.isArray(e.dataChanged)){const t=this.state.paths.slice(),n=e.dataChanged.map(e=>_r({data:t,getIndex:e=>e.__source.index,dataRange:e,replace:this._getPaths(e)}));this.setState({paths:t,pathsDiff:n})}else t&&this.setState({paths:this._getPaths(),pathsDiff:null})}_getPaths(e={}){const{data:t,getPolygon:n,positionFormat:i,_normalize:o}=this.props,s=[],r="XY"===i?2:3,{startRow:a,endRow:l}=e,{iterable:c,objectInfo:u}=$t(t,a,l);for(const f of c){u.index++;let e=n(f,u);o&&(e=ir(e,r));const{holeIndices:t}=e,i=e.positions||e;if(t)for(let n=0;n<=t.length;n++){const e=i.slice(t[n-1]||0,t[n]||i.length);s.push(this.getSubLayerRow({path:e},f,u.index))}else s.push(this.getSubLayerRow({path:i},f,u.index))}return s}renderLayers(){const{data:e,_dataDiff:t,stroked:n,filled:i,extruded:o,wireframe:s,_normalize:r,_windingOrder:a,elevationScale:l,transitions:c,positionFormat:u}=this.props,{lineWidthUnits:f,lineWidthScale:d,lineWidthMinPixels:p,lineWidthMaxPixels:g,lineJointRounded:h,lineMiterLimit:v,lineAntialiasing:m,lineDashJustified:_}=this.props,{getFillColor:x,getLineColor:y,getLineWidth:b,getLineDashArray:P,getElevation:C,getPolygon:w,updateTriggers:S,material:L}=this.props,{paths:A,pathsDiff:I}=this.state,E=this.getSubLayerClass("fill",mr),T=this.getSubLayerClass("stroke",Ys),O=this.shouldRenderSubLayer("fill",A)&&new E({_dataDiff:t,extruded:o,elevationScale:l,filled:i,wireframe:s,_normalize:r,_windingOrder:a,getElevation:C,getFillColor:x,getLineColor:o&&s?y:xr,material:L,transitions:c},this.getSubLayerProps({id:"fill",updateTriggers:S&&{getPolygon:S.getPolygon,getElevation:S.getElevation,getFillColor:S.getFillColor,lineColors:o&&s,getLineColor:S.getLineColor}}),{data:e,positionFormat:u,getPolygon:w});return[!o&&O,!o&&n&&this.shouldRenderSubLayer("stroke",A)&&new T({_dataDiff:I&&(()=>I),widthUnits:f,widthScale:d,widthMinPixels:p,widthMaxPixels:g,jointRounded:h,miterLimit:v,antialiasing:m,dashJustified:_,_pathType:"loop",transitions:c&&{getWidth:c.getLineWidth,getColor:c.getLineColor,getPath:c.getPolygon},getColor:this.getSubLayerAccessor(y),getWidth:this.getSubLayerAccessor(b),getDashArray:this.getSubLayerAccessor(P)},this.getSubLayerProps({id:"stroke",updateTriggers:S&&{getWidth:S.getLineWidth,getColor:S.getLineColor,getDashArray:S.getLineDashArray}}),{data:A,positionFormat:u,getPath:e=>e.path}),o&&O]}};br.layerName="PolygonLayer",br.defaultProps=yr;var Pr="layout(std140) uniform sdfUniforms {\n float gamma;\n bool enabled;\n float buffer;\n float outlineBuffer;\n vec4 outlineColor;\n} sdf;\n",Cr={name:"sdf",vs:Pr,fs:Pr,uniformTypes:{gamma:"f32",enabled:"f32",buffer:"f32",outlineBuffer:"f32",outlineColor:"vec4<f32>"}},wr={none:0,start:1,center:2,end:3},Sr={name:"text",vs:`layout(std140) uniform textUniforms {\n highp vec2 cutoffPixels;\n highp ivec2 align;\n highp float fontSize;\n bool flipY;\n} text;\n\n#define ALIGN_MODE_START ${wr.start}\n#define ALIGN_MODE_CENTER ${wr.center}\n#define ALIGN_MODE_END ${wr.end}\n`,getUniforms:({contentCutoffPixels:e=[0,0],contentAlignHorizontal:t="none",contentAlignVertical:n="none",fontSize:i,viewport:o})=>({cutoffPixels:e,align:[wr[t],wr[n]],fontSize:i,flipY:o?.flipY??!1}),uniformTypes:{cutoffPixels:"vec2<f32>",align:"vec2<i32>",fontSize:"f32",flipY:"f32"}};var Lr=function({collision:e=!1}={}){return`struct IconUniforms {\n sizeScale: f32,\n iconsTextureDim: vec2<f32>,\n sizeBasis: f32,\n sizeMinPixels: f32,\n sizeMaxPixels: f32,\n billboard: i32,\n sizeUnits: i32,\n alphaCutoff: f32\n};\n\nstruct TextUniforms {\n cutoffPixels: vec2<f32>,\n align: vec2<i32>,\n fontSize: f32,\n flipY: f32\n};\n\nstruct SdfUniforms {\n gamma: f32,\n enabled: f32,\n buffer: f32,\n outlineBuffer: f32,\n outlineColor: vec4<f32>\n};\n\n${e?"struct CollisionUniforms {\n sort: i32,\n enabled: i32\n};\n":""}\n\nconst ALIGN_MODE_START: i32 = 1;\nconst ALIGN_MODE_CENTER: i32 = 2;\nconst ALIGN_MODE_END: i32 = 3;\n\n@group(0) @binding(auto) var<uniform> icon: IconUniforms;\n@group(0) @binding(auto) var<uniform> text: TextUniforms;\n@group(0) @binding(auto) var<uniform> sdf: SdfUniforms;\n${e?"@group(0) @binding(auto) var<uniform> collision: CollisionUniforms;":""}\n@group(0) @binding(auto) var iconsTexture : texture_2d<f32>;\n@group(0) @binding(auto) var iconsTextureSampler : sampler;\n${e?"@group(0) @binding(auto) var collision_texture : texture_2d<f32>;\n":""}\n\nfn rotate_by_angle(vertex: vec2<f32>, angle_deg: f32) -> vec2<f32> {\n let angle_radian = angle_deg * PI / 180.0;\n let c = cos(angle_radian);\n let s = sin(angle_radian);\n let rotation = mat2x2<f32>(vec2<f32>(c, -s), vec2<f32>(s, c));\n return rotation * vertex;\n}\n\nfn get_pixel_offset_from_alignment(\n anchor: f32,\n extent: f32,\n clipStart: f32,\n clipEnd: f32,\n mode: i32\n) -> f32 {\n if (clipEnd < clipStart) {\n return 0.0;\n }\n if (mode == ALIGN_MODE_START) {\n return max(-(anchor + clipStart), 0.0);\n }\n if (mode == ALIGN_MODE_CENTER) {\n let minValue = max(0.0, anchor + clipStart);\n let maxValue = min(extent, anchor + clipEnd);\n if (minValue < maxValue) {\n return (minValue + maxValue) / 2.0 - anchor;\n }\n return 0.0;\n }\n if (mode == ALIGN_MODE_END) {\n return min(extent - (anchor + clipEnd), 0.0);\n }\n return 0.0;\n}\n\n${e?"fn collision_match(texCoords: vec2<f32>, pickingColor: vec3<f32>) -> f32 {\n let textureSize = vec2<i32>(textureDimensions(collision_texture));\n let pixelCoords = clamp(\n vec2<i32>(texCoords * vec2<f32>(textureSize)),\n vec2<i32>(0),\n textureSize - vec2<i32>(1)\n );\n let collisionPickingColor = textureLoad(collision_texture, pixelCoords, 0);\n let delta = dot(abs(collisionPickingColor.rgb - pickingColor), vec3<f32>(1.0));\n return step(delta, 0.001);\n}\n\nfn collision_is_visible(texCoords: vec2<f32>, pickingColor: vec3<f32>) -> f32 {\n if (collision.enabled == 0) {\n return 1.0;\n }\n\n var accumulator = 0.0;\n let stepSize = vec2<f32>(1.0) / project.viewportSize;\n\n for (var i: i32 = -2; i <= 2; i = i + 1) {\n for (var j: i32 = -2; j <= 2; j = j + 1) {\n let delta = vec2<f32>(f32(j), f32(i)) * stepSize;\n accumulator = accumulator + collision_match(texCoords + delta, pickingColor);\n }\n }\n\n return pow(accumulator / 25.0, 2.2);\n}\n":""}\n\nstruct Attributes {\n @location(0) positions: vec2<f32>,\n\n @location(1) instancePositions: vec3<f32>,\n @location(2) instancePositions64Low: vec3<f32>,\n @location(3) instanceSizes: f32,\n @location(4) instanceAngles: f32,\n @location(5) instanceColors: vec4<f32>,\n @location(6) instanceIconFrames: vec4<f32>,\n @location(7) instanceColorModes: f32,\n @location(8) instanceOffsets: vec2<f32>,\n @location(9) instancePixelOffset: vec2<f32>,\n @location(10) rowIndexes: u32,\n @location(11) instanceClipRect: vec4<f32>,\n ${e?"@location(12) collisionPriorities: f32,":""}\n};\n\nstruct Varyings {\n @builtin(position) position: vec4<f32>,\n\n @location(0) vColorMode: f32,\n @location(1) vColor: vec4<f32>,\n @location(2) vTextureCoords: vec2<f32>,\n @location(3) uv: vec2<f32>,\n @location(4) pickingColor: vec3<f32>,\n};\n\n@vertex\nfn vertexMain(inp: Attributes) -> Varyings {\n geometry.worldPosition = inp.instancePositions;\n geometry.uv = inp.positions;\n geometry.pickingColor = picking_getPickingColorFromIndex(inp.rowIndexes);\n\n var outp: Varyings;\n outp.uv = inp.positions;\n\n let iconSize = inp.instanceIconFrames.zw;\n\n let sizePixels = clamp(\n project_unit_size_to_pixel(inp.instanceSizes * icon.sizeScale, icon.sizeUnits),\n icon.sizeMinPixels, icon.sizeMaxPixels\n );\n let instanceScale = sizePixels / text.fontSize;\n\n var pixelOffset = inp.positions / 2.0 * iconSize + inp.instanceOffsets;\n pixelOffset = rotate_by_angle(pixelOffset, inp.instanceAngles) * instanceScale;\n pixelOffset = pixelOffset + inp.instancePixelOffset;\n pixelOffset.y = pixelOffset.y * -1.0;\n\n var pos: vec4<f32>;\n var anchorPosScreen: vec2<f32>;\n if (icon.billboard != 0) {\n pos = project_position_to_clipspace(inp.instancePositions, inp.instancePositions64Low, vec3<f32>(0.0));\n anchorPosScreen = pos.xy / pos.w;\n\n let clipOffset = project_pixel_size_to_clipspace(pixelOffset);\n pos = vec4<f32>(pos.x + clipOffset.x, pos.y + clipOffset.y, pos.z, pos.w);\n } else {\n var offsetCommon = vec3<f32>(project_pixel_size_vec2(pixelOffset), 0.0);\n if (text.flipY > 0.5) {\n offsetCommon.y = offsetCommon.y * -1.0;\n }\n let anchorPos = project_position_to_clipspace(inp.instancePositions, inp.instancePositions64Low, vec3<f32>(0.0));\n anchorPosScreen = anchorPos.xy / anchorPos.w;\n pos = project_position_to_clipspace(inp.instancePositions, inp.instancePositions64Low, offsetCommon);\n }\n\n anchorPosScreen = vec2<f32>(anchorPosScreen.x + 1.0, 1.0 - anchorPosScreen.y) / 2.0 *\n project.viewportSize / project.devicePixelRatio;\n var xy = project_size_vec2(inp.instanceClipRect.xy) * project.scale;\n var wh = project_size_vec2(inp.instanceClipRect.zw) * project.scale;\n\n if (text.flipY > 0.5) {\n xy.y = -xy.y - wh.y;\n }\n if (text.align.x > 0 || text.align.y > 0) {\n let viewportPixels = project.viewportSize / project.devicePixelRatio;\n let scrollPixels = vec2<f32>(\n get_pixel_offset_from_alignment(anchorPosScreen.x, viewportPixels.x, xy.x, xy.x + wh.x, text.align.x),\n -get_pixel_offset_from_alignment(anchorPosScreen.y, viewportPixels.y, -xy.y - wh.y, -xy.y, text.align.y)\n );\n pixelOffset = pixelOffset + scrollPixels;\n let scrollClipOffset = project_pixel_size_to_clipspace(scrollPixels);\n pos.x = pos.x + scrollClipOffset.x;\n pos.y = pos.y + scrollClipOffset.y;\n }\n\n if (inp.instanceClipRect.z >= 0.0) {\n if (pixelOffset.x < xy.x || pixelOffset.x > xy.x + wh.x) {\n pos = vec4<f32>(0.0);\n } else if (text.cutoffPixels.x > 0.0) {\n let viewportWidth = project.viewportSize.x / project.devicePixelRatio;\n let left = max(anchorPosScreen.x + xy.x, 0.0);\n let right = min(anchorPosScreen.x + xy.x + wh.x, viewportWidth);\n if (right - left < text.cutoffPixels.x) {\n pos = vec4<f32>(0.0);\n }\n }\n }\n if (inp.instanceClipRect.w >= 0.0) {\n if (pixelOffset.y < xy.y || pixelOffset.y > xy.y + wh.y) {\n pos = vec4<f32>(0.0);\n } else if (text.cutoffPixels.y > 0.0) {\n let viewportHeight = project.viewportSize.y / project.devicePixelRatio;\n let top = max(anchorPosScreen.y - xy.y - wh.y, 0.0);\n let bottom = min(anchorPosScreen.y - xy.y, viewportHeight);\n if (bottom - top < text.cutoffPixels.y) {\n pos = vec4<f32>(0.0);\n }\n }\n }\n\n ${e?" if (collision.sort != 0) {\n pos.z = -0.001 * inp.collisionPriorities * pos.w;\n }\n ":""}\n\n let uvMix = (inp.positions.xy + vec2<f32>(1.0, 1.0)) * 0.5;\n outp.vTextureCoords = mix(inp.instanceIconFrames.xy, inp.instanceIconFrames.xy + iconSize, uvMix) / icon.iconsTextureDim;\n\n outp.position = pos;\n outp.vColor = inp.instanceColors;\n outp.vColorMode = inp.instanceColorModes;\n outp.pickingColor = picking_getPickingColorFromIndex(inp.rowIndexes);\n\n return outp;\n}\n\n@fragment\nfn fragmentMain(inp: Varyings) -> @location(0) vec4<f32> {\n geometry.uv = inp.uv;\n\n let texColor = textureSample(iconsTexture, iconsTextureSampler, inp.vTextureCoords);\n var alpha = texColor.a;\n var color = inp.vColor;\n\n if (sdf.enabled > 0.5) {\n let distance = alpha;\n alpha = smoothstep(sdf.buffer - sdf.gamma, sdf.buffer + sdf.gamma, distance);\n\n if (sdf.outlineBuffer > 0.0) {\n let inFill = alpha;\n let inBorder = smoothstep(sdf.outlineBuffer - sdf.gamma, sdf.outlineBuffer + sdf.gamma, distance);\n color = mix(sdf.outlineColor, inp.vColor, inFill);\n alpha = inBorder;\n }\n } else if (inp.vColorMode == 0.0) {\n color = texColor;\n }\n\n var a = alpha * color.a * layer.opacity;\n if (a < icon.alphaCutoff) {\n discard;\n }\n\n if (picking.isActive > 0.5) {\n if (!picking_isColorValid(inp.pickingColor)) {\n discard;\n }\n return vec4<f32>(inp.pickingColor, 1.0);\n }\n\n ${e?" let collisionFade = collision_is_visible(inp.position.xy / project.viewportSize, inp.pickingColor);\n a = a * collisionFade;\n if (a <= 0.0001) {\n discard;\n }\n ":""}\n\n var fragColor = deckgl_premultiplied_alpha(vec4<f32>(color.rgb, a));\n\n if (picking.isHighlightActive > 0.5) {\n let highlightedObjectColor = picking_normalizeColor(picking.highlightedObjectColor);\n if (picking_isColorZero(abs(inp.pickingColor - highlightedObjectColor))) {\n let highLightAlpha = picking.highlightColor.a;\n let blendedAlpha = highLightAlpha + fragColor.a * (1.0 - highLightAlpha);\n if (blendedAlpha > 0.0) {\n let highLightRatio = highLightAlpha / blendedAlpha;\n fragColor = vec4<f32>(\n mix(fragColor.rgb, picking.highlightColor.rgb, highLightRatio),\n blendedAlpha\n );\n } else {\n fragColor = vec4<f32>(fragColor.rgb, 0.0);\n }\n }\n }\n\n return fragColor;\n}\n`}(),Ar=.75,Ir=class extends Uo{getShaders(){const e=super.getShaders();return{...e,modules:[...e.modules,Sr,Cr],vs:"#version 300 es\n#define SHADER_NAME multi-icon-layer-vertex-shader\nin vec2 positions;\nin vec3 instancePositions;\nin vec3 instancePositions64Low;\nin float instanceSizes;\nin float instanceAngles;\nin vec4 instanceColors;\nin float rowIndexes;\nin vec4 instanceIconFrames;\nin float instanceColorModes;\nin vec2 instanceOffsets;\nin vec2 instancePixelOffset;\nin vec4 instanceClipRect;\nout float vColorMode;\nout vec4 vColor;\nout vec2 vTextureCoords;\nout vec2 uv;\nvec2 rotate_by_angle(vec2 vertex, float angle) {\nfloat angle_radian = angle * PI / 180.0;\nfloat cos_angle = cos(angle_radian);\nfloat sin_angle = sin(angle_radian);\nmat2 rotationMatrix = mat2(cos_angle, -sin_angle, sin_angle, cos_angle);\nreturn rotationMatrix * vertex;\n}\nfloat getPixelOffsetFromAlignment(float anchor, float extent, float clipStart, float clipEnd, int mode) {\nif (clipEnd < clipStart) return 0.0;\nif (mode == ALIGN_MODE_START) {\nreturn max(- (anchor + clipStart), 0.0);\n}\nif (mode == ALIGN_MODE_CENTER) {\nfloat _min = max(0., anchor + clipStart);\nfloat _max = min(extent, anchor + clipEnd);\nreturn _min < _max ? (_min + _max) / 2.0 - anchor : 0.0;\n}\nif (mode == ALIGN_MODE_END) {\nreturn min(extent - (anchor + clipEnd), 0.);\n}\nreturn 0.0;\n}\nvoid main(void) {\ngeometry.worldPosition = instancePositions;\ngeometry.uv = positions;\ngeometry.pickingColor = picking_getPickingColorFromIndex(rowIndexes);\nuv = positions;\nvec2 iconSize = instanceIconFrames.zw;\nfloat sizePixels = clamp(\nproject_size_to_pixel(instanceSizes * icon.sizeScale, icon.sizeUnits),\nicon.sizeMinPixels, icon.sizeMaxPixels\n);\nfloat instanceScale = sizePixels / text.fontSize;\nvec2 pixelOffset = positions / 2.0 * iconSize + instanceOffsets;\npixelOffset = rotate_by_angle(pixelOffset, instanceAngles) * instanceScale;\npixelOffset += instancePixelOffset;\npixelOffset.y *= -1.0;\nvec2 anchorPosScreen;\nif (icon.billboard) {\ngl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.0), geometry.position);\nanchorPosScreen = gl_Position.xy / gl_Position.w;\nDECKGL_FILTER_GL_POSITION(gl_Position, geometry);\nvec3 offset = vec3(pixelOffset, 0.0);\nDECKGL_FILTER_SIZE(offset, geometry);\ngl_Position.xy += project_pixel_size_to_clipspace(offset.xy);\n} else {\nvec3 offset_common = vec3(project_pixel_size(pixelOffset), 0.0);\nif (text.flipY) {\noffset_common.y *= -1.;\n}\nDECKGL_FILTER_SIZE(offset_common, geometry);\nvec4 anchorPos = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.0));\nanchorPosScreen = anchorPos.xy / anchorPos.w;\ngl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, offset_common, geometry.position);\nDECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n}\nanchorPosScreen = vec2(anchorPosScreen.x + 1.0, 1.0 - anchorPosScreen.y) / 2.0 * project.viewportSize / project.devicePixelRatio;\nvec2 xy = project_size_to_pixel(instanceClipRect.xy);\nvec2 wh = project_size_to_pixel(instanceClipRect.zw);\nif (text.flipY) {\nxy.y = -xy.y - wh.y;\n}\nif (text.align.x > 0 || text.align.y > 0) {\nvec2 viewportPixels = project.viewportSize / project.devicePixelRatio;\nvec2 scrollPixels = vec2(\ngetPixelOffsetFromAlignment(anchorPosScreen.x, viewportPixels.x, xy.x, xy.x + wh.x, text.align.x),\n-getPixelOffsetFromAlignment(anchorPosScreen.y, viewportPixels.y, -xy.y - wh.y, -xy.y, text.align.y)\n);\npixelOffset += scrollPixels;\ngl_Position.xy += project_pixel_size_to_clipspace(scrollPixels);\n}\nif (instanceClipRect.z >= 0.) {\nif (pixelOffset.x < xy.x || pixelOffset.x > xy.x + wh.x) {\ngl_Position = vec4(0.0);\n}\nelse if (text.cutoffPixels.x > 0.) {\nfloat vpWidth = project.viewportSize.x / project.devicePixelRatio;\nfloat l = max(anchorPosScreen.x + xy.x, 0.0);\nfloat r = min(anchorPosScreen.x + xy.x + wh.x, vpWidth);\nif (r - l < text.cutoffPixels.x) {\ngl_Position = vec4(0.0);\n}\n}\n}\nif (instanceClipRect.w >= 0.) {\nif (pixelOffset.y < xy.y || pixelOffset.y > xy.y + wh.y) {\ngl_Position = vec4(0.0);\n}\nelse if (text.cutoffPixels.y > 0.) {\nfloat vpHeight = project.viewportSize.y / project.devicePixelRatio;\nfloat t = max(anchorPosScreen.y - xy.y - wh.y, 0.0);\nfloat b = min(anchorPosScreen.y - xy.y, vpHeight);\nif (b - t < text.cutoffPixels.y) {\ngl_Position = vec4(0.0);\n}\n}\n}\nvTextureCoords = mix(\ninstanceIconFrames.xy,\ninstanceIconFrames.xy + iconSize,\n(positions.xy + 1.0) / 2.0\n) / icon.iconsTextureDim;\nvColor = instanceColors;\nDECKGL_FILTER_COLOR(vColor, geometry);\nvColorMode = instanceColorModes;\n}\n",fs:"#version 300 es\n#define SHADER_NAME multi-icon-layer-fragment-shader\nprecision highp float;\nuniform sampler2D iconsTexture;\nin vec4 vColor;\nin vec2 vTextureCoords;\nin vec2 uv;\nout vec4 fragColor;\nvoid main(void) {\ngeometry.uv = uv;\nif (!bool(picking.isActive)) {\nfloat alpha = texture(iconsTexture, vTextureCoords).a;\nvec4 color = vColor;\nif (sdf.enabled) {\nfloat distance = alpha;\nalpha = smoothstep(sdf.buffer - sdf.gamma, sdf.buffer + sdf.gamma, distance);\nif (sdf.outlineBuffer > 0.0) {\nfloat inFill = alpha;\nfloat inBorder = smoothstep(sdf.outlineBuffer - sdf.gamma, sdf.outlineBuffer + sdf.gamma, distance);\ncolor = mix(sdf.outlineColor, vColor, inFill);\nalpha = inBorder;\n}\n}\nfloat a = alpha * color.a;\nif (a < icon.alphaCutoff) {\ndiscard;\n}\nfragColor = vec4(color.rgb, a * layer.opacity);\n}\nDECKGL_FILTER_COLOR(fragColor, geometry);\n}\n",source:Lr}}initializeState(){super.initializeState();const e=this.getAttributeManager();e.attributes.instanceIconDefs.settings.update=this.calculateInstanceIconDefs,e.addInstanced({rowIndexes:{type:"uint32",size:1,bufferGroup:"icon-instance-data",accessor:(e,{index:t})=>t},instanceClipRect:{size:4,bufferGroup:"icon-instance-data",accessor:"getContentBox",defaultValue:[0,0,-1,-1]}})}updateState(e){super.updateState(e);const{props:t,oldProps:n,changeFlags:i}=e,{outlineColor:o}=t;if(i.extensionsChanged){this.state.fillModel?.destroy();const e="webgpu"===this.context.device.type?this._getModel(`${this.props.id}-fill`):void 0;this.setState({fillModel:e,models:e?[this.state.model,e]:[this.state.model]})}if(i.updateTriggersChanged&&(i.updateTriggersChanged.getIcon||i.updateTriggersChanged.getIconOffsets)&&this.getAttributeManager().invalidate("instanceIconDefs"),o!==n.outlineColor){const e=[o[0]/255,o[1]/255,o[2]/255,(o[3]??255)/255];this.setState({outlineColor:e})}!t.sdf&&t.outlineWidth&&I.warn(`${this.id}: fontSettings.sdf is required to render outline`)()}draw(e){const{sdf:t,smoothing:n,fontSize:i,outlineWidth:o,contentCutoffPixels:s,contentAlignHorizontal:r,contentAlignVertical:a}=this.props,{outlineColor:l}=this.state,c=o?Math.max(n,Ar*(1-o)):-1,u=this.state.model,f={buffer:Ar,outlineBuffer:c,gamma:n,enabled:Boolean(t),outlineColor:l},d={contentCutoffPixels:s,contentAlignHorizontal:r,contentAlignVertical:a,fontSize:i,viewport:this.context.viewport};if(u.shaderInputs.setProps({sdf:f,text:d}),super.draw(e),t&&o){const{iconManager:e}=this.state;if(e.getTexture()){const e=this.state.fillModel||u;e.shaderInputs.setProps({sdf:{...f,outlineBuffer:Ar},text:d}),this._drawModel(e)}}}calculateInstanceIconDefs(e,{startRow:t,endRow:n}){const{data:i,getIcon:o,getIconOffsets:s}=this.props;let r=e.getVertexOffset(t);const a=e.value,{iterable:l,objectInfo:c}=$t(i,t,n);for(const u of l){c.index++;const t=o(u,c),n=s(u,c);if(t){let i=0;for(const o of Array.from(t)){const t=super.getInstanceIconDef(o);t[0]=n[2*i],t[1]+=n[2*i+1],t[6]=1,a.set(t,r),r+=e.size,i++}}}}};Ir.defaultProps={getIconOffsets:{type:"accessor",value:e=>e.offsets},getContentBox:{type:"accessor",value:[0,0,-1,-1]},fontSize:1,alphaCutoff:.001,smoothing:.1,outlineWidth:0,outlineColor:{type:"color",value:[0,0,0,255]},contentCutoffPixels:{type:"array",value:[0,0]},contentAlignHorizontal:"none",contentAlignVertical:"none"},Ir.layerName="MultiIconLayer";var Er=1e20,Tr=/* @__PURE__ */new Float64Array(256);for(let ga=0;ga<256;ga++){const e=.5-Math.pow(ga/255,1/2.2);Tr[ga]=e*Math.abs(e)}Tr[255]=-1e20;var Or=class{constructor({fontSize:e=24,buffer:t=3,radius:n=8,cutoff:i=.25,fontFamily:o="sans-serif",fontWeight:s="normal",fontStyle:r="normal",lang:a=null}={}){t=this.buffer=Math.round(t),this.radius=n,this.cutoff=i,this.lang=a;const l=this.size=Math.ceil(e)+4*t,c=this._createCanvas(l),u=this.ctx=c.getContext("2d",{willReadFrequently:!0});u.font=`${r} ${s} ${e}px ${o}`,u.textBaseline="alphabetic",u.textAlign="left",u.fillStyle="black",a&&(u.lang=a);const f=(this.maxGlyphDim=l-t)+2*t;this.gridOuter=new Float64Array(f*f),this.gridInner=new Float64Array(f*f),this.f=new Float64Array(f),this.z=new Float64Array(f+1),this.v=new Uint16Array(f)}_createCanvas(e){if("undefined"!=typeof OffscreenCanvas)return new OffscreenCanvas(e,e);const t=document.createElement("canvas");return t.width=t.height=e,t}draw(e){const{width:t,actualBoundingBoxAscent:n,actualBoundingBoxDescent:i,actualBoundingBoxLeft:o,actualBoundingBoxRight:s}=this.ctx.measureText(e),r=Math.ceil(n),a=Math.floor(-o),l=Math.max(0,Math.min(this.maxGlyphDim,Math.ceil(s)-a)),c=Math.max(0,Math.min(this.maxGlyphDim,r+Math.ceil(i))),u=l+2*this.buffer,f=c+2*this.buffer,d=u*f,p=new Uint8ClampedArray(d),g={data:p,width:u,height:f,glyphWidth:l,glyphHeight:c,glyphTop:r,glyphLeft:a,glyphAdvance:t};if(0===l||0===c)return g;const{ctx:h,buffer:v,gridInner:m,gridOuter:_}=this;h.clearRect(v,v,l,c),h.fillText(e,v-a,v+r);const x=h.getImageData(v,v,l,c);_.fill(Er,0,d),m.fill(0,0,d);let y=3;for(let w=0;w<c;w++){let e=(w+v)*u+v;for(let t=0;t<l;t++,y+=4,e++){const t=x.data[y];if(0===t)continue;const n=Tr[t];_[e]=Math.max(0,n),m[e]=Math.max(0,-n)}}zr(_,0,0,u,f,u,this.f,this.v,this.z,v);const b=Math.min(v,1);zr(m,v-b,v-b,l+2*b,c+2*b,u,this.f,this.v,this.z);const P=255/this.radius,C=255*(1-this.cutoff);for(let w=0;w<d;w++){const e=Math.sqrt(_[w])-Math.sqrt(m[w]);p[w]=C-P*e}return g}};function zr(e,t,n,i,o,s,r,a,l,c=0){for(let u=t+c;u<t+i-c;u++)Mr(e,n*s+u,s,o,r,a,l);for(let u=n;u<n+o;u++)Mr(e,u*s+t,1,i,r,a,l)}function Mr(e,t,n,i,o,s,r){s[0]=0,r[0]=-1e20,r[1]=Er,o[0]=e[t];for(let a=1,l=0;a<i;a++){const i=o[a]=e[t+a*n],c=a*a;let u;do{const e=s[l];u=(i-o[e]+c-e*e)/(a-e)/2}while(u<=r[l]&&--l>-1);l++,s[l]=a,r[l]=u,r[l+1]=Er}for(let a=0,l=0;a<i;a++){for(;r[l+1]<a;)l++;const i=s[l],c=a-i;e[t+a*n]=o[i]+c*c}}var Rr=[];function Br(e,t,n,i){let o=0;for(let s=t;s<n;s++){const t=e[s];o+=i[t]?.advance||0}return o}function kr(e,t,n,i,o,s){let r=t,a=0;for(let l=t;l<n;l++){const t=Br(e,l,l+1,o);a+t>i&&(r<l&&s.push(l),r=l,a=0),a+=t}return a}function Fr(e,t,n,i,o=0,s){void 0===s&&(s=e.length);const r=[];return"break-all"===t?kr(e,o,s,n,i,r):function(e,t,n,i,o,s){let r=t,a=t,l=t,c=0;for(let u=t;u<n;u++)if(" "===e[u]?l=u+1:" "!==e[u+1]&&u+1!==n||(l=u+1),l>a){let t=Br(e,a,l,o);c+t>i&&(r<a&&(s.push(a),r=a,c=0),t>i&&(t=kr(e,a,l,i,o,s),r=s[s.length-1])),a=l,c+=t}}(e,o,s,n,i,r),r}function Nr(e,t,n,i,o,s){let r=0,a=0;for(let l=t;l<n;l++){const t=i[e[l]];t&&(a=Math.max(a,t.height))}for(let l=t;l<n;l++){const t=e[l],n=i[t];n?(o[l]=r+n.anchorX,r+=n.advance):(I.warn(`Missing character: ${t} (${t.codePointAt(0)})`)(),o[l]=r,r+=32)}s[0]=r,s[1]=a}var Dr=class{constructor(e=5){this._cache={},this._order=[],this.limit=e}get(e){const t=this._cache[e];return t&&(this._deleteOrder(e),this._appendOrder(e)),t}set(e,t){this._cache[e]?(this.delete(e),this._cache[e]=t,this._appendOrder(e)):(Object.keys(this._cache).length===this.limit&&this.delete(this._order[0]),this._cache[e]=t,this._appendOrder(e))}delete(e){this._cache[e]&&(delete this._cache[e],this._deleteOrder(e))}_deleteOrder(e){const t=this._order.indexOf(e);t>=0&&this._order.splice(t,1)}_appendOrder(e){this._order.push(e)}};var jr={fontFamily:"Monaco, monospace",fontWeight:"normal",characterSet:function(){const e=[];for(let t=32;t<128;t++)e.push(String.fromCharCode(t));return e}(),fontSize:64,buffer:4,sdf:!1,cutoff:.25,radius:12,smoothing:.1},Ur=new Dr(3);function Gr(e,t,n,i){e.font=`${i} ${n}px ${t}`,e.fillStyle="#000",e.textBaseline="alphabetic",e.textAlign="left"}var Vr=class{constructor(){this.props={...jr}}get atlas(){return this._atlas}get mapping(){return this._atlas&&this._atlas.mapping}setProps(e={}){Object.assign(this.props,e),e._getFontRenderer&&(this._getFontRenderer=e._getFontRenderer),this._key=this._getKey();const t=function(e,t){let n;n="string"==typeof t?new Set(Array.from(t)):new Set(t);const i=Ur.get(e);if(!i)return n;for(const o in i.mapping)n.has(o)&&n.delete(o);return n}(this._key,this.props.characterSet),n=Ur.get(this._key);if(n&&0===t.size)return void(this._atlas!==n&&(this._atlas=n));const i=this._generateFontAtlas(t,n);this._atlas=i,Ur.set(this._key,i)}_generateFontAtlas(e,t){const{fontFamily:n,fontWeight:i,fontSize:o,buffer:s,sdf:r,radius:a,cutoff:l}=this.props;let c=t&&t.data;c||(c=document.createElement("canvas"),c.width=1024);const u=c.getContext("2d",{willReadFrequently:!0});Gr(u,n,o,i);const f=e=>function(e,t,n){if(void 0===n){const n=e.measureText("A");return n.fontBoundingBoxAscent?{advance:0,width:0,ascent:Math.ceil(n.fontBoundingBoxAscent),descent:Math.ceil(n.fontBoundingBoxDescent)}:{advance:0,width:0,ascent:.9*t,descent:.3*t}}const i=e.measureText(n);return i.actualBoundingBoxAscent?{advance:i.width,width:Math.ceil(i.actualBoundingBoxRight-i.actualBoundingBoxLeft),ascent:Math.ceil(i.actualBoundingBoxAscent),descent:Math.ceil(i.actualBoundingBoxDescent)}:{advance:i.width,width:i.width,ascent:.9*t,descent:.3*t}}(u,o,e);let d;this._getFontRenderer?d=this._getFontRenderer(this.props):r&&(d={measure:f,draw:$r(this.props)});const{mapping:p,canvasHeight:g,xOffset:h,yOffsetMin:v,yOffsetMax:m}=function({characterSet:e,measureText:t,buffer:n,maxCanvasWidth:i,mapping:o={},xOffset:s=0,yOffsetMin:r=0,yOffsetMax:a=0}){let l=s,c=r,u=a;for(const d of e)if(!o[d]){const{advance:e,width:s,ascent:r,descent:a}=t(d),f=r+a;l+s+2*n>i&&(l=0,c=u),o[d]={x:l+n,y:c+n,width:s,height:f,advance:e,anchorX:s/2,anchorY:r},l+=s+2*n,u=Math.max(u,c+f+2*n)}return{mapping:o,xOffset:l,yOffsetMin:c,yOffsetMax:u,canvasHeight:(f=u,Math.pow(2,Math.ceil(Math.log2(f))))};var f}({measureText:e=>d?d.measure(e):f(e),buffer:s,characterSet:e,maxCanvasWidth:1024,...t&&{mapping:t.mapping,xOffset:t.xOffset,yOffsetMin:t.yOffsetMin,yOffsetMax:t.yOffsetMax}});if(c.height!==g){const e=c.height>0?u.getImageData(0,0,c.width,c.height):null;c.height=g,e&&u.putImageData(e,0,0)}if(Gr(u,n,o,i),d)for(const x of e){const e=p[x],t=e.width,{data:n,left:i=0,top:o=0}=d.draw(x),s=e.x-i,r=e.y-o,a=Math.max(0,Math.round(s)),l=Math.max(0,Math.round(r)),f=Math.min(n.width,c.width-a),g=Math.min(n.height,c.height-l);u.putImageData(n,a,l,0,0,f,g),e.x=a,e.y=l,e.width=f,e.height=g,e.anchorX+=f/2-i-t/2,e.anchorY+=o}else for(const x of e){const e=p[x];u.fillText(x,e.x,e.y+e.anchorY)}const _=d?d.measure():f();return{baselineOffset:(_.ascent-_.descent)/2,xOffset:h,yOffsetMin:v,yOffsetMax:m,mapping:p,data:c,width:c.width,height:c.height}}_getKey(){const{fontFamily:e,fontWeight:t,fontSize:n,buffer:i,sdf:o,radius:s,cutoff:r}=this.props;return o?`${e} ${t} ${n} ${i} ${s} ${r}`:`${e} ${t} ${n} ${i}`}};function $r({fontSize:e,buffer:t,radius:n,cutoff:i,fontFamily:o,fontWeight:s}){const r=new Or({fontSize:e,buffer:t,radius:n,cutoff:i,fontFamily:o,fontWeight:`${s}`});return e=>{const{data:n,width:i,height:o}=r.draw(e),s=new ImageData(i,o);return function(e,t){for(let n=0;n<e.length;n++)t.data[4*n+3]=e[n]}(n,s),{data:s,left:t,top:t}}}var Wr="layout(std140) uniform textBackgroundUniforms {\n bool billboard;\n float sizeScale;\n float sizeMinPixels;\n float sizeMaxPixels;\n vec4 borderRadius;\n vec4 padding;\n highp int sizeUnits;\n bool stroked;\n} textBackground;\n",Hr={name:"textBackground",source:"struct TextBackgroundUniforms {\n billboard: f32,\n sizeScale: f32,\n sizeMinPixels: f32,\n sizeMaxPixels: f32,\n borderRadius: vec4<f32>,\n padding: vec4<f32>,\n sizeUnits: i32,\n stroked: f32,\n};\n\n@group(0) @binding(auto) var<uniform> textBackground: TextBackgroundUniforms;\n",vs:Wr,fs:Wr,uniformTypes:{billboard:"f32",sizeScale:"f32",sizeMinPixels:"f32",sizeMaxPixels:"f32",borderRadius:"vec4<f32>",padding:"vec4<f32>",sizeUnits:"i32",stroked:"f32"}},Zr={billboard:!0,sizeScale:1,sizeUnits:"pixels",sizeMinPixels:0,sizeMaxPixels:Number.MAX_SAFE_INTEGER,fontSize:1,borderRadius:{type:"object",value:0},padding:{type:"array",value:[0,0,0,0]},getPosition:{type:"accessor",value:e=>e.position},getSize:{type:"accessor",value:1},getAngle:{type:"accessor",value:0},getPixelOffset:{type:"accessor",value:[0,0]},getBoundingRect:{type:"accessor",value:[0,0,0,0]},getClipRect:{type:"accessor",value:[0,0,-1,-1]},getFillColor:{type:"accessor",value:[0,0,0,255]},getLineColor:{type:"accessor",value:[0,0,0,255]},getLineWidth:{type:"accessor",value:1}},Yr=class extends co{getShaders(){return super.getShaders({vs:"#version 300 es\n#define SHADER_NAME text-background-layer-vertex-shader\nin vec2 positions;\nin vec3 instancePositions;\nin vec3 instancePositions64Low;\nin vec4 instanceRects;\nin vec4 instanceClipRect;\nin float instanceSizes;\nin float instanceAngles;\nin vec2 instancePixelOffsets;\nin float instanceLineWidths;\nin vec4 instanceFillColors;\nin vec4 instanceLineColors;\nout vec4 vFillColor;\nout vec4 vLineColor;\nout float vLineWidth;\nout vec2 uv;\nout vec2 dimensions;\nvec2 rotate_by_angle(vec2 vertex, float angle) {\nfloat angle_radian = radians(angle);\nfloat cos_angle = cos(angle_radian);\nfloat sin_angle = sin(angle_radian);\nmat2 rotationMatrix = mat2(cos_angle, -sin_angle, sin_angle, cos_angle);\nreturn rotationMatrix * vertex;\n}\nvoid main(void) {\ngeometry.worldPosition = instancePositions;\ngeometry.uv = positions;\ngeometry.pickingColor = picking_getPickingColorFromInstanceID();\nuv = positions;\nvLineWidth = instanceLineWidths;\nfloat sizePixels = clamp(\nproject_size_to_pixel(instanceSizes * textBackground.sizeScale, textBackground.sizeUnits),\ntextBackground.sizeMinPixels, textBackground.sizeMaxPixels\n);\nfloat instanceScale = sizePixels / text.fontSize;\ndimensions = instanceRects.zw * instanceScale + textBackground.padding.xy + textBackground.padding.zw;\nvec2 pixelOffset = (positions * instanceRects.zw + instanceRects.xy) * instanceScale + mix(-textBackground.padding.xy, textBackground.padding.zw, positions);\npixelOffset = rotate_by_angle(pixelOffset, instanceAngles);\npixelOffset += instancePixelOffsets;\npixelOffset.y *= -1.0;\nvec2 xy = project_size_to_pixel(instanceClipRect.xy);\nvec2 wh = project_size_to_pixel(instanceClipRect.zw);\nif (text.flipY) {\nxy.y = -xy.y - wh.y;\n}\nif (instanceClipRect.z >= 0.0) {\ndimensions.x = wh.x;\npixelOffset.x = xy.x + uv.x * wh.x + mix(-textBackground.padding.x, textBackground.padding.z, uv.x);\n}\nif (instanceClipRect.w >= 0.0) {\ndimensions.y = wh.y;\npixelOffset.y = xy.y + uv.y * wh.y + mix(-textBackground.padding.y, textBackground.padding.w, uv.y);\n}\nif (textBackground.billboard) {\ngl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, vec3(0.0), geometry.position);\nDECKGL_FILTER_GL_POSITION(gl_Position, geometry);\nvec3 offset = vec3(pixelOffset, 0.0);\nDECKGL_FILTER_SIZE(offset, geometry);\ngl_Position.xy += project_pixel_size_to_clipspace(offset.xy);\n} else {\nvec3 offset_common = vec3(project_pixel_size(pixelOffset), 0.0);\nif (text.flipY) {\noffset_common.y *= -1.;\n}\nDECKGL_FILTER_SIZE(offset_common, geometry);\ngl_Position = project_position_to_clipspace(instancePositions, instancePositions64Low, offset_common, geometry.position);\nDECKGL_FILTER_GL_POSITION(gl_Position, geometry);\n}\nvFillColor = vec4(instanceFillColors.rgb, instanceFillColors.a * layer.opacity);\nDECKGL_FILTER_COLOR(vFillColor, geometry);\nvLineColor = vec4(instanceLineColors.rgb, instanceLineColors.a * layer.opacity);\nDECKGL_FILTER_COLOR(vLineColor, geometry);\n}\n",fs:"#version 300 es\n#define SHADER_NAME text-background-layer-fragment-shader\nprecision highp float;\nin vec4 vFillColor;\nin vec4 vLineColor;\nin float vLineWidth;\nin vec2 uv;\nin vec2 dimensions;\nout vec4 fragColor;\nfloat round_rect(vec2 p, vec2 size, vec4 radii) {\nvec2 pixelPositionCB = (p - 0.5) * size;\nvec2 sizeCB = size * 0.5;\nfloat maxBorderRadius = min(size.x, size.y) * 0.5;\nvec4 borderRadius = vec4(min(radii, maxBorderRadius));\nborderRadius.xy =\n(pixelPositionCB.x > 0.0) ? borderRadius.xy : borderRadius.zw;\nborderRadius.x = (pixelPositionCB.y > 0.0) ? borderRadius.x : borderRadius.y;\nvec2 q = abs(pixelPositionCB) - sizeCB + borderRadius.x;\nreturn -(min(max(q.x, q.y), 0.0) + length(max(q, 0.0)) - borderRadius.x);\n}\nfloat rect(vec2 p, vec2 size) {\nvec2 pixelPosition = p * size;\nreturn min(min(pixelPosition.x, size.x - pixelPosition.x),\nmin(pixelPosition.y, size.y - pixelPosition.y));\n}\nvec4 get_stroked_fragColor(float dist) {\nfloat isBorder = smoothedge(dist, vLineWidth);\nreturn mix(vFillColor, vLineColor, isBorder);\n}\nvoid main(void) {\ngeometry.uv = uv;\nif (textBackground.borderRadius != vec4(0.0)) {\nfloat distToEdge = round_rect(uv, dimensions, textBackground.borderRadius);\nfloat shapeAlpha = smoothedge(-distToEdge, 0.0);\nif (shapeAlpha == 0.0) {\ndiscard;\n}\nif (textBackground.stroked) {\nfragColor = get_stroked_fragColor(distToEdge);\n} else {\nfragColor = vFillColor;\n}\nfragColor.a *= shapeAlpha;\n} else {\nif (textBackground.stroked) {\nfloat distToEdge = rect(uv, dimensions);\nfragColor = get_stroked_fragColor(distToEdge);\n} else {\nfragColor = vFillColor;\n}\n}\nDECKGL_FILTER_COLOR(fragColor, geometry);\n}\n",source:"struct TextUniforms {\n cutoffPixels: vec2<f32>,\n align: vec2<i32>,\n fontSize: f32,\n flipY: f32,\n};\n\n@group(0) @binding(auto) var<uniform> text: TextUniforms;\n\nfn rotate_by_angle(vertex: vec2<f32>, angle: f32) -> vec2<f32> {\n let angleRadian = radians(angle);\n let cosine = cos(angleRadian);\n let sine = sin(angleRadian);\n let rotationMatrix = mat2x2<f32>(\n vec2<f32>(cosine, -sine),\n vec2<f32>(sine, cosine)\n );\n return rotationMatrix * vertex;\n}\n\nstruct Attributes {\n @builtin(instance_index) instanceIndex: u32,\n @location(0) positions: vec2<f32>,\n @location(1) instancePositions: vec3<f32>,\n @location(2) instancePositions64Low: vec3<f32>,\n @location(3) instanceSizes: f32,\n @location(4) instanceAngles: f32,\n @location(5) instanceRects: vec4<f32>,\n @location(6) instanceClipRect: vec4<f32>,\n @location(7) instancePixelOffsets: vec2<f32>,\n @location(8) instanceFillColors: vec4<f32>,\n @location(9) instanceLineColors: vec4<f32>,\n @location(10) instanceLineWidths: f32,\n};\n\nstruct Varyings {\n @builtin(position) position: vec4<f32>,\n @location(0) vFillColor: vec4<f32>,\n @location(1) vLineColor: vec4<f32>,\n @location(2) vLineWidth: f32,\n @location(3) uv: vec2<f32>,\n @location(4) dimensions: vec2<f32>,\n @location(5) pickingColor: vec3<f32>,\n};\n\n@vertex\nfn vertexMain(attributes: Attributes) -> Varyings {\n geometry.worldPosition = attributes.instancePositions;\n geometry.uv = attributes.positions;\n geometry.pickingColor = picking_getPickingColorFromIndex(attributes.instanceIndex);\n\n var varyings: Varyings;\n varyings.uv = attributes.positions;\n varyings.vLineWidth = attributes.instanceLineWidths;\n\n let sizePixels = clamp(\n project_unit_size_to_pixel(\n attributes.instanceSizes * textBackground.sizeScale,\n textBackground.sizeUnits\n ),\n textBackground.sizeMinPixels,\n textBackground.sizeMaxPixels\n );\n let instanceScale = sizePixels / text.fontSize;\n\n varyings.dimensions = attributes.instanceRects.zw * instanceScale +\n textBackground.padding.xy + textBackground.padding.zw;\n\n var pixelOffset =\n (attributes.positions * attributes.instanceRects.zw + attributes.instanceRects.xy) *\n instanceScale +\n mix(-textBackground.padding.xy, textBackground.padding.zw, attributes.positions);\n pixelOffset = rotate_by_angle(pixelOffset, attributes.instanceAngles);\n pixelOffset = pixelOffset + attributes.instancePixelOffsets;\n pixelOffset.y = pixelOffset.y * -1.0;\n\n var xy = project_size_vec2(attributes.instanceClipRect.xy) * project.scale;\n let wh = project_size_vec2(attributes.instanceClipRect.zw) * project.scale;\n if (text.flipY > 0.5) {\n xy.y = -xy.y - wh.y;\n }\n if (attributes.instanceClipRect.z >= 0.0) {\n varyings.dimensions.x = wh.x;\n pixelOffset.x = xy.x + varyings.uv.x * wh.x + mix(\n -textBackground.padding.x,\n textBackground.padding.z,\n varyings.uv.x\n );\n }\n if (attributes.instanceClipRect.w >= 0.0) {\n varyings.dimensions.y = wh.y;\n pixelOffset.y = xy.y + varyings.uv.y * wh.y + mix(\n -textBackground.padding.y,\n textBackground.padding.w,\n varyings.uv.y\n );\n }\n\n if (textBackground.billboard > 0.5) {\n var position = project_position_to_clipspace(\n attributes.instancePositions,\n attributes.instancePositions64Low,\n vec3<f32>(0.0)\n );\n let clipOffset = project_pixel_size_to_clipspace(pixelOffset);\n position = vec4<f32>(\n position.x + clipOffset.x,\n position.y + clipOffset.y,\n position.z,\n position.w\n );\n varyings.position = position;\n } else {\n var offsetCommon = vec3<f32>(project_pixel_size_vec2(pixelOffset), 0.0);\n if (text.flipY > 0.5) {\n offsetCommon.y = offsetCommon.y * -1.0;\n }\n varyings.position = project_position_to_clipspace(\n attributes.instancePositions,\n attributes.instancePositions64Low,\n offsetCommon\n );\n }\n\n varyings.vFillColor = vec4<f32>(\n attributes.instanceFillColors.rgb,\n attributes.instanceFillColors.a * layer.opacity\n );\n varyings.vLineColor = vec4<f32>(\n attributes.instanceLineColors.rgb,\n attributes.instanceLineColors.a * layer.opacity\n );\n varyings.pickingColor = geometry.pickingColor;\n return varyings;\n}\n\nfn round_rect(point: vec2<f32>, size: vec2<f32>, radii: vec4<f32>) -> f32 {\n let pixelPosition = (point - 0.5) * size;\n let halfSize = size * 0.5;\n let maxBorderRadius = min(size.x, size.y) * 0.5;\n var borderRadius = min(radii, vec4<f32>(maxBorderRadius));\n\n borderRadius = select(borderRadius.zwxy, borderRadius, pixelPosition.x > 0.0);\n let radius = select(borderRadius.y, borderRadius.x, pixelPosition.y > 0.0);\n let q = abs(pixelPosition) - halfSize + radius;\n return -(min(max(q.x, q.y), 0.0) + length(max(q, vec2<f32>(0.0))) - radius);\n}\n\nfn rect(point: vec2<f32>, size: vec2<f32>) -> f32 {\n let pixelPosition = point * size;\n return min(\n min(pixelPosition.x, size.x - pixelPosition.x),\n min(pixelPosition.y, size.y - pixelPosition.y)\n );\n}\n\nfn get_stroked_frag_color(\n distanceToEdge: f32,\n lineWidth: f32,\n fillColor: vec4<f32>,\n lineColor: vec4<f32>\n) -> vec4<f32> {\n let isBorder = smoothedge(distanceToEdge, lineWidth);\n return mix(fillColor, lineColor, isBorder);\n}\n\n@fragment\nfn fragmentMain(varyings: Varyings) -> @location(0) vec4<f32> {\n geometry.uv = varyings.uv;\n var fragColor: vec4<f32>;\n\n if (any(textBackground.borderRadius != vec4<f32>(0.0))) {\n let distanceToEdge = round_rect(\n varyings.uv,\n varyings.dimensions,\n textBackground.borderRadius\n );\n let shapeAlpha = smoothedge(-distanceToEdge, 0.0);\n if (shapeAlpha == 0.0) {\n discard;\n }\n if (textBackground.stroked > 0.5) {\n fragColor = get_stroked_frag_color(\n distanceToEdge,\n varyings.vLineWidth,\n varyings.vFillColor,\n varyings.vLineColor\n );\n } else {\n fragColor = varyings.vFillColor;\n }\n fragColor.a = fragColor.a * shapeAlpha;\n } else if (textBackground.stroked > 0.5) {\n let distanceToEdge = rect(varyings.uv, varyings.dimensions);\n fragColor = get_stroked_frag_color(\n distanceToEdge,\n varyings.vLineWidth,\n varyings.vFillColor,\n varyings.vLineColor\n );\n } else {\n fragColor = varyings.vFillColor;\n }\n\n if (picking.isActive > 0.5) {\n if (!picking_isColorValid(varyings.pickingColor)) {\n discard;\n }\n return vec4<f32>(varyings.pickingColor, 1.0);\n }\n\n if (picking.isHighlightActive > 0.5) {\n let highlightedObjectColor = picking_normalizeColor(picking.highlightedObjectColor);\n if (picking_isColorZero(abs(varyings.pickingColor - highlightedObjectColor))) {\n let highlightAlpha = picking.highlightColor.a;\n let blendedAlpha = highlightAlpha + fragColor.a * (1.0 - highlightAlpha);\n if (blendedAlpha > 0.0) {\n let highlightRatio = highlightAlpha / blendedAlpha;\n fragColor = vec4<f32>(\n mix(fragColor.rgb, picking.highlightColor.rgb, highlightRatio),\n blendedAlpha\n );\n } else {\n fragColor = vec4<f32>(fragColor.rgb, 0.0);\n }\n }\n }\n\n return deckgl_premultiplied_alpha(fragColor);\n}\n",modules:[Ye,Ze,Je,Hr,Sr]})}initializeState(){this.getAttributeManager().addInstanced({instancePositions:{size:3,type:"float64",fp64:this.use64bitPositions(),transition:!0,accessor:"getPosition"},instanceSizes:{size:1,transition:!0,bufferGroup:"text-background-instance-data",accessor:"getSize",defaultValue:1},instanceAngles:{size:1,transition:!0,bufferGroup:"text-background-instance-data",accessor:"getAngle"},instanceRects:{size:4,bufferGroup:"text-background-instance-data",accessor:"getBoundingRect"},instanceClipRect:{size:4,bufferGroup:"text-background-instance-data",accessor:"getClipRect",defaultValue:[0,0,-1,-1]},instancePixelOffsets:{size:2,transition:!0,bufferGroup:"text-background-instance-data",accessor:"getPixelOffset"},instanceFillColors:{size:4,transition:!0,type:"unorm8",accessor:"getFillColor",defaultValue:[0,0,0,255]},instanceLineColors:{size:4,transition:!0,type:"unorm8",accessor:"getLineColor",defaultValue:[0,0,0,255]},instanceLineWidths:{size:1,transition:!0,bufferGroup:"text-background-instance-data",accessor:"getLineWidth",defaultValue:1}})}updateState(e){super.updateState(e);const{changeFlags:t}=e;t.extensionsChanged&&(this.state.model?.destroy(),this.state.model=this._getModel(),this.getAttributeManager().invalidateAll())}draw({uniforms:e}){const{billboard:t,sizeScale:n,sizeUnits:o,sizeMinPixels:s,sizeMaxPixels:r,getLineWidth:a,fontSize:l}=this.props;let{padding:c,borderRadius:u}=this.props;c.length<4&&(c=[c[0],c[1],c[0],c[1]]),Array.isArray(u)||(u=[u,u,u,u]);const f=this.state.model,d={billboard:t,stroked:Boolean(a),borderRadius:u,padding:c,sizeUnits:i[o],sizeScale:n,sizeMinPixels:s,sizeMaxPixels:r},p={fontSize:l,viewport:this.context.viewport};f.shaderInputs.setProps({textBackground:d,text:p}),f.draw(this.context.renderPass)}_getModel(){return new xt(this.context.device,{...this.getShaders(),id:this.props.id,bufferLayout:this.getAttributeManager().getBufferLayouts(),geometry:new nt({topology:"triangle-strip",vertexCount:4,attributes:{positions:{size:2,value:new Float32Array([0,0,1,0,0,1,1,1])}}}),isInstanced:!0})}};Yr.defaultProps=Zr,Yr.layerName="TextBackgroundLayer";var qr={start:1,middle:0,end:-1},Kr={top:1,center:0,bottom:-1},Xr=[0,0,0,255],Jr={billboard:!0,sizeScale:1,sizeUnits:"pixels",sizeMinPixels:0,sizeMaxPixels:Number.MAX_SAFE_INTEGER,background:!1,getBackgroundColor:{type:"accessor",value:[255,255,255,255]},getBorderColor:{type:"accessor",value:Xr},getBorderWidth:{type:"accessor",value:0},backgroundBorderRadius:{type:"object",value:0},backgroundPadding:{type:"array",value:[0,0,0,0]},characterSet:{type:"object",value:jr.characterSet},fontFamily:jr.fontFamily,fontWeight:jr.fontWeight,lineHeight:1,outlineWidth:{type:"number",value:0,min:0},outlineColor:{type:"color",value:Xr},fontSettings:{type:"object",value:{},compare:1},wordBreak:"break-word",maxWidth:{type:"number",value:-1},contentCutoffPixels:{type:"array",value:[0,0]},contentAlignHorizontal:"none",contentAlignVertical:"none",getText:{type:"accessor",value:e=>e.text},getPosition:{type:"accessor",value:e=>e.position},getColor:{type:"accessor",value:Xr},getSize:{type:"accessor",value:32},getAngle:{type:"accessor",value:0},getTextAnchor:{type:"accessor",value:"middle"},getAlignmentBaseline:{type:"accessor",value:"center"},getPixelOffset:{type:"accessor",value:[0,0]},getContentBox:{type:"accessor",value:[0,0,-1,-1]},backgroundColor:{deprecatedFor:["background","getBackgroundColor"]}},Qr=class extends fo{constructor(){super(...arguments),this.getBoundingRect=(e,t)=>{const{size:[n,i]}=this.transformParagraph(e,t),{getTextAnchor:o,getAlignmentBaseline:s}=this.props;return[(qr["function"==typeof o?o(e,t):o]-1)*n/2,(Kr["function"==typeof s?s(e,t):s]-1)*i/2,n,i]},this.getIconOffsets=(e,t)=>{const{getTextAnchor:n,getAlignmentBaseline:i}=this.props,{x:o,y:s,rowWidth:r,size:[,a]}=this.transformParagraph(e,t),l=qr["function"==typeof n?n(e,t):n],c=Kr["function"==typeof i?i(e,t):i],u=o.length,f=new Array(2*u);let d=0;for(let p=0;p<u;p++)f[d++]=(l-1)*r[p]/2+o[p],f[d++]=(c-1)*a/2+s[p];return f}}initializeState(){this.state={styleVersion:0,fontAtlasManager:new Vr},this.props.maxWidth>0&&I.once(1,"v8.9 breaking change: TextLayer maxWidth is now relative to text size")()}updateState(e){const{props:t,oldProps:n,changeFlags:i}=e;(i.dataChanged||i.updateTriggersChanged&&(i.updateTriggersChanged.all||i.updateTriggersChanged.getText))&&this._updateText(),(this._updateFontAtlas()||t.lineHeight!==n.lineHeight||t.wordBreak!==n.wordBreak||t.maxWidth!==n.maxWidth)&&this.setState({styleVersion:this.state.styleVersion+1})}getPickingInfo({info:e}){return e.object=e.index>=0?this.props.data[e.index]:null,e}_updateFontAtlas(){const{fontSettings:e,fontFamily:t,fontWeight:n,_getFontRenderer:i}=this.props,{fontAtlasManager:o,characterSet:s}=this.state,r={...e,characterSet:s,fontFamily:t,fontWeight:n,_getFontRenderer:i};if(!o.mapping)return o.setProps(r),!0;for(const a in r)if(r[a]!==o.props[a])return o.setProps(r),!0;return!1}_updateText(){const{data:e,characterSet:t}=this.props,n=e.attributes?.getText;let i,{getText:o}=this.props,s=e.startIndices;const r="auto"===t&&/* @__PURE__ */new Set;if(n&&s){const{texts:t,characterCount:a}=function({value:e,length:t,stride:n,offset:i,startIndices:o,characterSet:s}){const r=e.BYTES_PER_ELEMENT,a=n?n/r:1,l=i?i/r:0,c=o[t]||Math.ceil((e.length-l)/a),u=s&&/* @__PURE__ */new Set,f=new Array(t);let d=e;if(a>1||l>0){d=new(0,e.constructor)(c);for(let t=0;t<c;t++)d[t]=e[t*a+l]}for(let p=0;p<t;p++){const e=o[p],t=o[p+1]||c,n=d.subarray(e,t);f[p]=String.fromCodePoint.apply(null,n),u&&n.forEach(u.add,u)}if(u)for(const p of u)s.add(String.fromCodePoint(p));return{texts:f,characterCount:c}}({...ArrayBuffer.isView(n)?{value:n}:n,length:e.length,startIndices:s,characterSet:r});i=a,o=(e,{index:n})=>t[n]}else{const{iterable:t,objectInfo:n}=$t(e);s=[0],i=0;for(const e of t){n.index++;const t=Array.from(o(e,n)||"");r&&t.forEach(r.add,r),i+=t.length,s.push(i)}}this.setState({getText:o,startIndices:s,numInstances:i,characterSet:r||t})}transformParagraph(e,t){const{fontAtlasManager:n}=this.state,i=n.mapping,{baselineOffset:o}=n.atlas,{fontSize:s}=n.props,r=this.state.getText,{wordBreak:a,lineHeight:l,maxWidth:c}=this.props;return function(e,t,n,i,o,s){const r=Array.from(e),a=r.length,l=new Array(a),c=new Array(a),u=new Array(a),f=("break-word"===i||"break-all"===i)&&isFinite(o)&&o>0,d=[0,0],p=[0,0];let g=0,h=t+n/2,v=0,m=0;for(let _=0;_<=a;_++){const e=r[_];if("\n"!==e&&_!==a||(m=_),m>v){const e=f?Fr(r,i,o,s,v,m):Rr;for(let t=0;t<=e.length;t++){const i=0===t?v:e[t-1],o=t<e.length?e[t]:m;Nr(r,i,o,s,l,p);for(let e=i;e<o;e++)c[e]=h,u[e]=p[0];g++,h+=n,d[0]=Math.max(d[0],p[0])}v=m}"\n"===e&&(l[v]=0,c[v]=0,u[v]=0,v++)}return d[1]=g*n,{x:l,y:c,rowWidth:u,size:d}}(r(e,t)||"",o,l*s,a,c*s,i)}renderLayers(){const{startIndices:e,numInstances:t,getText:n,fontAtlasManager:{atlas:i,mapping:o},styleVersion:s}=this.state,{data:r,_dataDiff:a,getPosition:l,getColor:c,getSize:u,getAngle:f,getPixelOffset:d,getBackgroundColor:p,getBorderColor:g,getBorderWidth:h,getContentBox:v,backgroundBorderRadius:m,backgroundPadding:_,background:x,billboard:y,fontSettings:b,outlineWidth:P,outlineColor:C,sizeScale:w,sizeUnits:S,sizeMinPixels:L,sizeMaxPixels:A,contentCutoffPixels:I,contentAlignHorizontal:E,contentAlignVertical:T,transitions:O,updateTriggers:z}=this.props,M=this.getSubLayerClass("characters",Ir),R=this.getSubLayerClass("background",Yr),{fontSize:B}=this.state.fontAtlasManager.props;return[x&&new R({getFillColor:p,getLineColor:g,getLineWidth:h,borderRadius:m,padding:_,getPosition:l,getSize:u,getAngle:f,getPixelOffset:d,getClipRect:v,billboard:y,sizeScale:w,sizeUnits:S,sizeMinPixels:L,sizeMaxPixels:A,fontSize:B,transitions:O&&{getPosition:O.getPosition,getAngle:O.getAngle,getSize:O.getSize,getFillColor:O.getBackgroundColor,getLineColor:O.getBorderColor,getLineWidth:O.getBorderWidth,getPixelOffset:O.getPixelOffset}},this.getSubLayerProps({id:"background",updateTriggers:{getPosition:z.getPosition,getAngle:z.getAngle,getSize:z.getSize,getFillColor:z.getBackgroundColor,getLineColor:z.getBorderColor,getLineWidth:z.getBorderWidth,getPixelOffset:z.getPixelOffset,getBoundingRect:{getText:z.getText,getTextAnchor:z.getTextAnchor,getAlignmentBaseline:z.getAlignmentBaseline,styleVersion:s}}}),{data:r.attributes&&r.attributes.background?{length:r.length,attributes:r.attributes.background}:r,_dataDiff:a,autoHighlight:!1,getBoundingRect:this.getBoundingRect}),new M({sdf:b.sdf,smoothing:Number.isFinite(b.smoothing)?b.smoothing:jr.smoothing,outlineWidth:P/(b.radius||jr.radius),outlineColor:C,iconAtlas:i,iconMapping:o,getPosition:l,getColor:c,getSize:u,getAngle:f,getPixelOffset:d,getContentBox:v,billboard:y,sizeScale:w,sizeUnits:S,sizeMinPixels:L,sizeMaxPixels:A,fontSize:B,contentCutoffPixels:I,contentAlignHorizontal:E,contentAlignVertical:T,transitions:O&&{getPosition:O.getPosition,getAngle:O.getAngle,getColor:O.getColor,getSize:O.getSize,getPixelOffset:O.getPixelOffset,getContentBox:O.getContentBox}},this.getSubLayerProps({id:"characters",updateTriggers:{all:z.getText,getPosition:z.getPosition,getAngle:z.getAngle,getColor:z.getColor,getSize:z.getSize,getPixelOffset:z.getPixelOffset,getContentBox:z.getContentBox,getIconOffsets:{getTextAnchor:z.getTextAnchor,getAlignmentBaseline:z.getAlignmentBaseline,styleVersion:s}}}),{data:r,_dataDiff:a,startIndices:e,numInstances:t,getIconOffsets:this.getIconOffsets,getIcon:n})]}static set fontAtlasCacheLimit(e){!function(e){I.assert(Number.isFinite(e)&&e>=3,"Invalid cache limit"),Ur=new Dr(e)}(e)}};Qr.defaultProps=Jr,Qr.layerName="TextLayer";var ea={circle:{type:ss,props:{filled:"filled",stroked:"stroked",lineWidthMaxPixels:"lineWidthMaxPixels",lineWidthMinPixels:"lineWidthMinPixels",lineWidthScale:"lineWidthScale",lineWidthUnits:"lineWidthUnits",pointRadiusMaxPixels:"radiusMaxPixels",pointRadiusMinPixels:"radiusMinPixels",pointRadiusScale:"radiusScale",pointRadiusUnits:"radiusUnits",pointAntialiasing:"antialiasing",pointBillboard:"billboard",getFillColor:"getFillColor",getLineColor:"getLineColor",getLineWidth:"getLineWidth",getPointRadius:"getRadius"}},icon:{type:Uo,props:{iconAtlas:"iconAtlas",iconMapping:"iconMapping",iconSizeMaxPixels:"sizeMaxPixels",iconSizeMinPixels:"sizeMinPixels",iconSizeScale:"sizeScale",iconSizeUnits:"sizeUnits",iconAlphaCutoff:"alphaCutoff",iconBillboard:"billboard",getIcon:"getIcon",getIconAngle:"getAngle",getIconColor:"getColor",getIconPixelOffset:"getPixelOffset",getIconSize:"getSize"}},text:{type:Qr,props:{textSizeMaxPixels:"sizeMaxPixels",textSizeMinPixels:"sizeMinPixels",textSizeScale:"sizeScale",textSizeUnits:"sizeUnits",textBackground:"background",textBackgroundPadding:"backgroundPadding",textFontFamily:"fontFamily",textFontWeight:"fontWeight",textLineHeight:"lineHeight",textMaxWidth:"maxWidth",textOutlineColor:"outlineColor",textOutlineWidth:"outlineWidth",textWordBreak:"wordBreak",textCharacterSet:"characterSet",textBillboard:"billboard",textFontSettings:"fontSettings",getText:"getText",getTextAngle:"getAngle",getTextColor:"getColor",getTextPixelOffset:"getPixelOffset",getTextSize:"getSize",getTextAnchor:"getTextAnchor",getTextAlignmentBaseline:"getAlignmentBaseline",getTextBackgroundColor:"getBackgroundColor",getTextBorderColor:"getBorderColor",getTextBorderWidth:"getBorderWidth"}}},ta={type:Ys,props:{lineWidthUnits:"widthUnits",lineWidthScale:"widthScale",lineWidthMinPixels:"widthMinPixels",lineWidthMaxPixels:"widthMaxPixels",lineJointRounded:"jointRounded",lineCapRounded:"capRounded",lineMiterLimit:"miterLimit",lineBillboard:"billboard",lineAntialiasing:"antialiasing",getLineColor:"getColor",getLineWidth:"getWidth"}},na={type:mr,props:{extruded:"extruded",filled:"filled",wireframe:"wireframe",elevationScale:"elevationScale",material:"material",_full3d:"_full3d",getElevation:"getElevation",getFillColor:"getFillColor",getLineColor:"getLineColor"}};function ia({type:e,props:t}){const n={};for(const i in t)n[i]=e.defaultProps[t[i]];return n}function oa(e,t,n="getPosition"){const{transitions:i,updateTriggers:o}=e.props,s={updateTriggers:{},transitions:i&&{[n]:i.geometry}};for(const r in t){const n=t[r];let a=e.props[r];r.startsWith("get")&&(a=e.getSubLayerAccessor(a),s.updateTriggers[n]=o[r],i&&(s.transitions[n]=i[r])),s[n]=a}return s}function sa(e,t,n={}){const i={pointFeatures:[],lineFeatures:[],polygonFeatures:[],polygonOutlineFeatures:[]},{startRow:o=0,endRow:s=e.length}=n;for(let r=o;r<s;r++){const n=e[r],{geometry:o}=n;if(o)if("GeometryCollection"===o.type){I.assert(Array.isArray(o.geometries),"GeoJSON does not have geometries array");const{geometries:e}=o;for(let o=0;o<e.length;o++){ra(e[o],i,t,n,r)}}else ra(o,i,t,n,r)}return i}function ra(e,t,n,i,o){const{type:s,coordinates:r}=e,{pointFeatures:a,lineFeatures:l,polygonFeatures:c,polygonOutlineFeatures:u}=t;if(function(e,t){let n=aa[e];I.assert(n,`Unknown GeoJSON type ${e}`);for(;t&&--n>0;)t=t[0];return t&&Number.isFinite(t[0])}(s,r))switch(s){case"Point":a.push(n({geometry:e},i,o));break;case"MultiPoint":r.forEach(e=>{a.push(n({geometry:{type:"Point",coordinates:e}},i,o))});break;case"LineString":l.push(n({geometry:e},i,o));break;case"MultiLineString":r.forEach(e=>{l.push(n({geometry:{type:"LineString",coordinates:e}},i,o))});break;case"Polygon":c.push(n({geometry:e},i,o)),r.forEach(e=>{u.push(n({geometry:{type:"LineString",coordinates:e}},i,o))});break;case"MultiPolygon":r.forEach(e=>{c.push(n({geometry:{type:"Polygon",coordinates:e}},i,o)),e.forEach(e=>{u.push(n({geometry:{type:"LineString",coordinates:e}},i,o))})})}else I.warn(`${s} coordinates are malformed`)()}var aa={Point:1,MultiPoint:2,LineString:2,MultiLineString:3,Polygon:3,MultiPolygon:4};function la(e){return e.geometry.coordinates}function ca(e){const t={points:{},lines:{},polygons:{},polygonsOutline:{}},{points:n,lines:i,polygons:o}=e,s=function(e){const t={points:null,lines:null,polygons:null};for(const n in t){const i=e[n].globalFeatureIds.value;t[n]=new Uint32Array(i)}return t}(e);t.points.data={length:n.positions.value.length/n.positions.size,attributes:{...n.attributes,getPosition:n.positions,rowIndexes:{size:1,type:"uint32",value:s.points}},properties:n.properties,numericProps:n.numericProps,featureIds:n.featureIds},t.lines.data={length:i.pathIndices.value.length-1,startIndices:i.pathIndices.value,attributes:{...i.attributes,getPath:i.positions,rowIndexes:{size:1,type:"uint32",value:s.lines}},properties:i.properties,numericProps:i.numericProps,featureIds:i.featureIds},t.lines._pathType="open";const r=o.positions.value.length/o.positions.size,a=Array(r).fill(1);for(const l of o.primitivePolygonIndices.value)a[l-1]=0;return t.polygons.data={length:o.polygonIndices.value.length-1,startIndices:o.polygonIndices.value,attributes:{...o.attributes,getPolygon:o.positions,instanceVertexValid:{size:1,value:new Uint16Array(a)},rowIndexes:{size:1,type:"uint32",value:s.polygons}},properties:o.properties,numericProps:o.numericProps,featureIds:o.featureIds},t.polygons._normalize=!1,o.triangles&&(t.polygons.data.attributes.indices=o.triangles.value),t.polygonsOutline.data={length:o.primitivePolygonIndices.value.length-1,startIndices:o.primitivePolygonIndices.value,attributes:{...o.attributes,getPath:o.positions,rowIndexes:{size:1,type:"uint32",value:s.polygons}},properties:o.properties,numericProps:o.numericProps,featureIds:o.featureIds},t.polygonsOutline._pathType="open",t}var ua=["points","linestrings","polygons"],fa={...ia(ea.circle),...ia(ea.icon),...ia(ea.text),...ia(ta),...ia(na),stroked:!0,filled:!0,extruded:!1,wireframe:!1,_full3d:!1,iconAtlas:{type:"object",value:null},iconMapping:{type:"object",value:{}},getIcon:{type:"accessor",value:e=>e.properties.icon},getText:{type:"accessor",value:e=>e.properties.text},pointType:"circle",getRadius:{deprecatedFor:"getPointRadius"}},da=class extends fo{initializeState(){this.state={layerProps:{},features:{},featuresDiff:{}}}updateState({props:e,changeFlags:t}){if(!t.dataChanged)return;const{data:n}=this.props,i=n&&"points"in n&&"polygons"in n&&"lines"in n;this.setState({binary:i}),i?this._updateStateBinary({props:e,changeFlags:t}):this._updateStateJSON({props:e,changeFlags:t})}_updateStateBinary({props:e,changeFlags:t}){const n=ca(e.data);this.setState({layerProps:n})}_updateStateJSON({props:e,changeFlags:t}){const n=function(e){if(Array.isArray(e))return e;switch(I.assert(e.type,"GeoJSON does not have type"),e.type){case"Feature":return[e];case"FeatureCollection":return I.assert(Array.isArray(e.features),"GeoJSON does not have features array"),e.features;default:return[{geometry:e}]}}(e.data),i=this.getSubLayerRow.bind(this);let o={};const s={};if(Array.isArray(t.dataChanged)){const e=this.state.features;for(const t in e)o[t]=e[t].slice(),s[t]=[];for(const r of t.dataChanged){const t=sa(n,i,r);for(const n in e)s[n].push(_r({data:o[n],getIndex:e=>e.__source.index,dataRange:r,replace:t[n]}))}}else o=sa(n,i);const r=function(e,t){const n={points:{},lines:{},polygons:{},polygonsOutline:{}},{pointFeatures:i,lineFeatures:o,polygonFeatures:s,polygonOutlineFeatures:r}=e;return n.points.data=i,n.points._dataDiff=t.pointFeatures&&(()=>t.pointFeatures),n.points.getPosition=la,n.lines.data=o,n.lines._dataDiff=t.lineFeatures&&(()=>t.lineFeatures),n.lines.getPath=la,n.polygons.data=s,n.polygons._dataDiff=t.polygonFeatures&&(()=>t.polygonFeatures),n.polygons.getPolygon=la,n.polygonsOutline.data=r,n.polygonsOutline._dataDiff=t.polygonOutlineFeatures&&(()=>t.polygonOutlineFeatures),n.polygonsOutline.getPath=la,n}(o,s);this.setState({features:o,featuresDiff:s,layerProps:r})}getPickingInfo(e){const t=super.getPickingInfo(e),{index:n,sourceLayer:i}=t;return t.featureType=ua.find(e=>i.id.startsWith(`${this.id}-${e}-`)),n>=0&&i.id.startsWith(`${this.id}-points-text`)&&this.state.binary&&(t.index=this.props.data.points.globalFeatureIds.value[n]),t}_updateAutoHighlight(e){const t=`${this.id}-points-`,n="points"===e.featureType;for(const i of this.getSubLayers())i.id.startsWith(t)===n&&i.updateAutoHighlight(e)}_renderPolygonLayer(){const{extruded:e,wireframe:t}=this.props,{layerProps:n}=this.state,i="polygons-fill",o=this.shouldRenderSubLayer(i,n.polygons?.data)&&this.getSubLayerClass(i,na.type);if(o){const s=oa(this,na.props,"getPolygon"),r=e&&t;return r||delete s.getLineColor,s.updateTriggers.lineColors=r,new o(s,this.getSubLayerProps({id:i,updateTriggers:s.updateTriggers}),n.polygons)}return null}_renderLineLayers(){const{extruded:e,stroked:t}=this.props,{layerProps:n}=this.state,i="polygons-stroke",o="linestrings",s=!e&&t&&this.shouldRenderSubLayer(i,n.polygonsOutline?.data)&&this.getSubLayerClass(i,ta.type),r=this.shouldRenderSubLayer(o,n.lines?.data)&&this.getSubLayerClass(o,ta.type);if(s||r){const e=oa(this,ta.props,"getPath");return[s&&new s(e,this.getSubLayerProps({id:i,updateTriggers:e.updateTriggers}),n.polygonsOutline),r&&new r(e,this.getSubLayerProps({id:o,updateTriggers:e.updateTriggers}),n.lines)]}return null}_renderPointLayers(){const{pointType:e}=this.props,{layerProps:t,binary:n}=this.state;let{highlightedObjectIndex:i}=this.props;!n&&Number.isFinite(i)&&(i=t.points.data.findIndex(e=>e.__source.index===i));const o=new Set(e.split("+")),s=[];for(const r of o){const e=`points-${r}`,o=ea[r],a=o&&this.shouldRenderSubLayer(e,t.points?.data)&&this.getSubLayerClass(e,o.type);if(a){const l=oa(this,o.props);let c=t.points;if("text"===r&&n){const{rowIndexes:e,...t}=c.data.attributes;c={...c,data:{...c.data,attributes:t}}}s.push(new a(l,this.getSubLayerProps({id:e,updateTriggers:l.updateTriggers,highlightedObjectIndex:i}),c))}}return s}renderLayers(){const{extruded:e}=this.props,t=this._renderPolygonLayer();return[!e&&t,this._renderLineLayers(),this._renderPointLayers(),e&&t]}getSubLayerAccessor(e){const{binary:t}=this.state;return t&&"function"==typeof e?(t,n)=>{const{data:i,index:o}=n;return e(function(e,t){if(!e)return null;const n="startIndices"in e?e.startIndices[t]:t,i=e.featureIds.value[n];return-1!==n?function(e,t,n){const i={properties:{...e.properties[t]}};for(const o in e.numericProps)i.properties[o]=e.numericProps[o].value[n];return i}(e,i,n):null}(i,o),n)}:super.getSubLayerAccessor(e)}};da.layerName="GeoJsonLayer",da.defaultProps=fa;var pa=/* @__PURE__ */t({ArcLayer:()=>_o,BitmapLayer:()=>So,ColumnLayer:()=>Fs,GeoJsonLayer:()=>da,GridCellLayer:()=>Ns,IconLayer:()=>Uo,LineLayer:()=>Wo,PathLayer:()=>Ys,PointCloudLayer:()=>Xo,PolygonLayer:()=>br,ScatterplotLayer:()=>ss,SolidPolygonLayer:()=>mr,TextLayer:()=>Qr,_MultiIconLayer:()=>Ir,_TextBackgroundLayer:()=>Yr});export{He as C,be as E,Ze as S,Se as T,ht as _,Fs as a,Je as b,Xo as c,fo as d,co as f,vt as g,xt as h,Ys as i,So as l,Ct as m,da as n,cs as o,$t as p,br as r,us as s,pa as t,_o as u,ot as v,Be as w,Ye as x,nt as y};
|