fluidcad 0.0.36 → 0.0.38

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (188) hide show
  1. package/LICENSE.txt +21 -504
  2. package/README.md +1 -1
  3. package/lib/dist/common/edge.d.ts +1 -1
  4. package/lib/dist/common/face.d.ts +1 -1
  5. package/lib/dist/common/scene-object.d.ts +6 -0
  6. package/lib/dist/common/scene-object.js +8 -0
  7. package/lib/dist/common/shape-factory.d.ts +1 -1
  8. package/lib/dist/common/shape-history-tracker.d.ts +1 -1
  9. package/lib/dist/common/shape.d.ts +1 -1
  10. package/lib/dist/common/solid.d.ts +1 -1
  11. package/lib/dist/common/transformable-primitive.d.ts +12 -1
  12. package/lib/dist/common/transformable-primitive.js +27 -0
  13. package/lib/dist/common/vertex.d.ts +1 -1
  14. package/lib/dist/common/wire.d.ts +1 -1
  15. package/lib/dist/core/2d/index.d.ts +1 -0
  16. package/lib/dist/core/2d/index.js +1 -0
  17. package/lib/dist/core/2d/text.d.ts +30 -0
  18. package/lib/dist/core/2d/text.js +37 -0
  19. package/lib/dist/core/helix.d.ts +20 -0
  20. package/lib/dist/core/helix.js +36 -0
  21. package/lib/dist/core/index.d.ts +3 -1
  22. package/lib/dist/core/index.js +2 -0
  23. package/lib/dist/core/interfaces.d.ts +180 -0
  24. package/lib/dist/core/plane.d.ts +26 -6
  25. package/lib/dist/core/plane.js +21 -44
  26. package/lib/dist/core/wrap.d.ts +17 -0
  27. package/lib/dist/core/wrap.js +39 -0
  28. package/lib/dist/features/2d/offset.js +2 -2
  29. package/lib/dist/features/2d/text.d.ts +67 -0
  30. package/lib/dist/features/2d/text.js +320 -0
  31. package/lib/dist/features/cylinder.d.ts +3 -1
  32. package/lib/dist/features/cylinder.js +5 -2
  33. package/lib/dist/features/extrude-base.d.ts +1 -0
  34. package/lib/dist/features/extrude-to-face.d.ts +1 -0
  35. package/lib/dist/features/extrude-to-face.js +6 -0
  36. package/lib/dist/features/fillet.d.ts +1 -1
  37. package/lib/dist/features/helix.d.ts +41 -0
  38. package/lib/dist/features/helix.js +337 -0
  39. package/lib/dist/features/plane-from-object.d.ts +16 -4
  40. package/lib/dist/features/plane-from-object.js +101 -8
  41. package/lib/dist/features/select.js +32 -8
  42. package/lib/dist/features/simple-extruder.d.ts +1 -1
  43. package/lib/dist/features/simple-extruder.js +7 -2
  44. package/lib/dist/features/sphere.d.ts +3 -1
  45. package/lib/dist/features/sphere.js +5 -2
  46. package/lib/dist/features/sweep.js +7 -2
  47. package/lib/dist/features/wrap.d.ts +39 -0
  48. package/lib/dist/features/wrap.js +116 -0
  49. package/lib/dist/filters/edge/belongs-to-face.d.ts +3 -1
  50. package/lib/dist/filters/edge/belongs-to-face.js +14 -10
  51. package/lib/dist/filters/filter.d.ts +1 -1
  52. package/lib/dist/filters/from-object.d.ts +1 -1
  53. package/lib/dist/filters/tangent-expander.d.ts +1 -1
  54. package/lib/dist/filters/tangent-expander.js +57 -40
  55. package/lib/dist/helpers/scene-helpers.d.ts +2 -0
  56. package/lib/dist/helpers/scene-helpers.js +1 -1
  57. package/lib/dist/index.d.ts +2 -0
  58. package/lib/dist/index.js +3 -1
  59. package/lib/dist/io/file-import.d.ts +7 -0
  60. package/lib/dist/io/file-import.js +28 -1
  61. package/lib/dist/io/font-registry.d.ts +45 -0
  62. package/lib/dist/io/font-registry.js +272 -0
  63. package/lib/dist/math/bspline-interpolation.d.ts +29 -0
  64. package/lib/dist/math/bspline-interpolation.js +194 -0
  65. package/lib/dist/oc/boolean-ops.d.ts +3 -1
  66. package/lib/dist/oc/boolean-ops.js +15 -1
  67. package/lib/dist/oc/color-transfer.d.ts +1 -1
  68. package/lib/dist/oc/constraints/constraint-helpers.d.ts +4 -4
  69. package/lib/dist/oc/constraints/curve/tangent-circle-solver.js +10 -9
  70. package/lib/dist/oc/constraints/curve/tangent-line-solver.js +5 -6
  71. package/lib/dist/oc/convert.d.ts +1 -1
  72. package/lib/dist/oc/draft-ops.d.ts +1 -1
  73. package/lib/dist/oc/edge-ops.d.ts +2 -2
  74. package/lib/dist/oc/edge-ops.js +13 -14
  75. package/lib/dist/oc/edge-props.d.ts +1 -1
  76. package/lib/dist/oc/edge-query.d.ts +1 -1
  77. package/lib/dist/oc/edge-query.js +3 -8
  78. package/lib/dist/oc/errors.d.ts +8 -0
  79. package/lib/dist/oc/errors.js +27 -0
  80. package/lib/dist/oc/explorer.d.ts +2 -2
  81. package/lib/dist/oc/extrude-ops.d.ts +28 -2
  82. package/lib/dist/oc/extrude-ops.js +56 -7
  83. package/lib/dist/oc/face-ops.d.ts +2 -1
  84. package/lib/dist/oc/face-ops.js +11 -0
  85. package/lib/dist/oc/face-props.d.ts +1 -1
  86. package/lib/dist/oc/face-query.d.ts +12 -1
  87. package/lib/dist/oc/face-query.js +39 -0
  88. package/lib/dist/oc/fillet-ops.d.ts +1 -1
  89. package/lib/dist/oc/fillet-ops.js +4 -4
  90. package/lib/dist/oc/geometry.d.ts +1 -1
  91. package/lib/dist/oc/geometry.js +12 -14
  92. package/lib/dist/oc/helix-ops.d.ts +37 -0
  93. package/lib/dist/oc/helix-ops.js +88 -0
  94. package/lib/dist/oc/hit-test.d.ts +1 -1
  95. package/lib/dist/oc/index.d.ts +4 -0
  96. package/lib/dist/oc/index.js +2 -0
  97. package/lib/dist/oc/init.d.ts +1 -1
  98. package/lib/dist/oc/init.js +1 -1
  99. package/lib/dist/oc/intersection.js +1 -1
  100. package/lib/dist/oc/io.d.ts +6 -6
  101. package/lib/dist/oc/io.js +31 -24
  102. package/lib/dist/oc/measure/classify.d.ts +34 -0
  103. package/lib/dist/oc/measure/classify.js +246 -0
  104. package/lib/dist/oc/measure/measure-ops.d.ts +9 -0
  105. package/lib/dist/oc/measure/measure-ops.js +210 -0
  106. package/lib/dist/oc/measure/measure-types.d.ts +39 -0
  107. package/lib/dist/oc/measure/measure-types.js +1 -0
  108. package/lib/dist/oc/measure/sampling.d.ts +9 -0
  109. package/lib/dist/oc/measure/sampling.js +77 -0
  110. package/lib/dist/oc/measure/vec.d.ts +13 -0
  111. package/lib/dist/oc/measure/vec.js +23 -0
  112. package/lib/dist/oc/mesh.d.ts +1 -1
  113. package/lib/dist/oc/mesh.js +40 -28
  114. package/lib/dist/oc/path-sampler.d.ts +29 -0
  115. package/lib/dist/oc/path-sampler.js +63 -0
  116. package/lib/dist/oc/props.d.ts +1 -1
  117. package/lib/dist/oc/props.js +4 -1
  118. package/lib/dist/oc/shape-hash.d.ts +26 -0
  119. package/lib/dist/oc/shape-hash.js +32 -0
  120. package/lib/dist/oc/shape-ops.d.ts +5 -3
  121. package/lib/dist/oc/shape-ops.js +6 -5
  122. package/lib/dist/oc/sweep-ops.d.ts +13 -1
  123. package/lib/dist/oc/sweep-ops.js +174 -18
  124. package/lib/dist/oc/text-outline.d.ts +62 -0
  125. package/lib/dist/oc/text-outline.js +212 -0
  126. package/lib/dist/oc/thin-face-maker.d.ts +0 -19
  127. package/lib/dist/oc/thin-face-maker.js +3 -68
  128. package/lib/dist/oc/topology-index.d.ts +1 -1
  129. package/lib/dist/oc/vertex-ops.d.ts +1 -1
  130. package/lib/dist/oc/wire-ops.d.ts +18 -3
  131. package/lib/dist/oc/wire-ops.js +56 -5
  132. package/lib/dist/oc/wrap-development.d.ts +105 -0
  133. package/lib/dist/oc/wrap-development.js +179 -0
  134. package/lib/dist/oc/wrap-ops.d.ts +100 -0
  135. package/lib/dist/oc/wrap-ops.js +406 -0
  136. package/lib/dist/rendering/render-solid.js +10 -2
  137. package/lib/dist/scene-manager.d.ts +2 -0
  138. package/lib/dist/scene-manager.js +29 -0
  139. package/lib/dist/tests/features/2d/offset.test.js +74 -1
  140. package/lib/dist/tests/features/cylinder-curve-filter.test.js +3 -3
  141. package/lib/dist/tests/features/extrude-to-face.test.js +38 -1
  142. package/lib/dist/tests/features/helix.test.d.ts +1 -0
  143. package/lib/dist/tests/features/helix.test.js +295 -0
  144. package/lib/dist/tests/features/plane.test.js +95 -0
  145. package/lib/dist/tests/features/repeat-primitive.test.d.ts +1 -0
  146. package/lib/dist/tests/features/repeat-primitive.test.js +60 -0
  147. package/lib/dist/tests/features/rib.test.js +6 -1
  148. package/lib/dist/tests/features/sweep.test.js +170 -1
  149. package/lib/dist/tests/features/text.test.d.ts +1 -0
  150. package/lib/dist/tests/features/text.test.js +347 -0
  151. package/lib/dist/tests/features/wrap-development.test.d.ts +1 -0
  152. package/lib/dist/tests/features/wrap-development.test.js +130 -0
  153. package/lib/dist/tests/features/wrap-extruded-target.test.d.ts +1 -0
  154. package/lib/dist/tests/features/wrap-extruded-target.test.js +106 -0
  155. package/lib/dist/tests/features/wrap-repeat.test.d.ts +1 -0
  156. package/lib/dist/tests/features/wrap-repeat.test.js +93 -0
  157. package/lib/dist/tests/features/wrap.test.d.ts +1 -0
  158. package/lib/dist/tests/features/wrap.test.js +331 -0
  159. package/lib/dist/tests/math/bspline-interpolation.test.d.ts +1 -0
  160. package/lib/dist/tests/math/bspline-interpolation.test.js +119 -0
  161. package/lib/dist/tests/measure.test.d.ts +1 -0
  162. package/lib/dist/tests/measure.test.js +288 -0
  163. package/lib/dist/tsconfig.tsbuildinfo +1 -1
  164. package/llm-docs/api/helix.md +64 -0
  165. package/llm-docs/api/index.json +11 -2
  166. package/llm-docs/api/text.md +52 -0
  167. package/llm-docs/api/types/helix.md +105 -0
  168. package/llm-docs/api/types/text.md +138 -0
  169. package/llm-docs/api/types/wrap.md +131 -0
  170. package/llm-docs/api/wrap.md +62 -0
  171. package/llm-docs/index.json +121 -1
  172. package/mcp/dist/server.js +20 -1
  173. package/mcp/dist/tools/inspection.d.ts +17 -0
  174. package/mcp/dist/tools/inspection.js +14 -0
  175. package/package.json +7 -3
  176. package/server/dist/fluidcad-server.d.ts +11 -1
  177. package/server/dist/fluidcad-server.js +21 -1
  178. package/server/dist/index.js +4 -2
  179. package/server/dist/preferences.d.ts +4 -0
  180. package/server/dist/preferences.js +2 -0
  181. package/server/dist/routes/measure.d.ts +3 -0
  182. package/server/dist/routes/measure.js +32 -0
  183. package/server/dist/routes/params.js +1 -1
  184. package/server/dist/routes/preferences.js +6 -0
  185. package/server/dist/routes/sketch-edits.js +2 -1
  186. package/ui/dist/assets/{index-MRqwG9Vh.js → index-D8zV21wB.js} +149 -102
  187. package/ui/dist/assets/{index-CDJmUpFI.css → index-dAFdg2Un.css} +1 -1
  188. package/ui/dist/index.html +2 -2
@@ -1,8 +1,8 @@
1
- (function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin===`use-credentials`?t.credentials=`include`:e.crossOrigin===`anonymous`?t.credentials=`omit`:t.credentials=`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var e=1e3,t=1001,n=1002,r=1003,i=1004,a=1005,o=1006,s=1007,c=1008,l=1009,u=1010,d=1011,f=1012,p=1013,m=1014,h=1015,g=1016,_=1017,v=1018,y=1020,b=35902,x=35899,S=1021,C=1022,w=1023,T=1026,E=1027,D=1028,ee=1029,O=1030,k=1031,te=1033,ne=33776,A=33777,re=33778,ie=33779,j=35840,ae=35841,oe=35842,se=35843,ce=36196,le=37492,ue=37496,de=37808,fe=37809,pe=37810,me=37811,he=37812,ge=37813,_e=37814,ve=37815,M=37816,ye=37817,be=37818,xe=37819,N=37820,Se=37821,P=36492,F=36494,Ce=36495,we=36283,Te=36284,Ee=36285,De=36286,Oe=2300,ke=2301,Ae=2302,je=2400,Me=2401,Ne=2402,Pe=3200,Fe=3201,Ie=`srgb`,Le=`srgb-linear`,Re=`linear`,ze=`srgb`,Be=7680,Ve=35044,He=2e3,Ue=class{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});let n=this._listeners;n[e]===void 0&&(n[e]=[]),n[e].indexOf(t)===-1&&n[e].push(t)}hasEventListener(e,t){let n=this._listeners;return n===void 0?!1:n[e]!==void 0&&n[e].indexOf(t)!==-1}removeEventListener(e,t){let n=this._listeners;if(n===void 0)return;let r=n[e];if(r!==void 0){let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}dispatchEvent(e){let t=this._listeners;if(t===void 0)return;let n=t[e.type];if(n!==void 0){e.target=this;let t=n.slice(0);for(let n=0,r=t.length;n<r;n++)t[n].call(this,e);e.target=null}}},We=`00.01.02.03.04.05.06.07.08.09.0a.0b.0c.0d.0e.0f.10.11.12.13.14.15.16.17.18.19.1a.1b.1c.1d.1e.1f.20.21.22.23.24.25.26.27.28.29.2a.2b.2c.2d.2e.2f.30.31.32.33.34.35.36.37.38.39.3a.3b.3c.3d.3e.3f.40.41.42.43.44.45.46.47.48.49.4a.4b.4c.4d.4e.4f.50.51.52.53.54.55.56.57.58.59.5a.5b.5c.5d.5e.5f.60.61.62.63.64.65.66.67.68.69.6a.6b.6c.6d.6e.6f.70.71.72.73.74.75.76.77.78.79.7a.7b.7c.7d.7e.7f.80.81.82.83.84.85.86.87.88.89.8a.8b.8c.8d.8e.8f.90.91.92.93.94.95.96.97.98.99.9a.9b.9c.9d.9e.9f.a0.a1.a2.a3.a4.a5.a6.a7.a8.a9.aa.ab.ac.ad.ae.af.b0.b1.b2.b3.b4.b5.b6.b7.b8.b9.ba.bb.bc.bd.be.bf.c0.c1.c2.c3.c4.c5.c6.c7.c8.c9.ca.cb.cc.cd.ce.cf.d0.d1.d2.d3.d4.d5.d6.d7.d8.d9.da.db.dc.dd.de.df.e0.e1.e2.e3.e4.e5.e6.e7.e8.e9.ea.eb.ec.ed.ee.ef.f0.f1.f2.f3.f4.f5.f6.f7.f8.f9.fa.fb.fc.fd.fe.ff`.split(`.`),Ge=1234567,Ke=Math.PI/180,qe=180/Math.PI;function Je(){let e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,n=Math.random()*4294967295|0,r=Math.random()*4294967295|0;return(We[e&255]+We[e>>8&255]+We[e>>16&255]+We[e>>24&255]+`-`+We[t&255]+We[t>>8&255]+`-`+We[t>>16&15|64]+We[t>>24&255]+`-`+We[n&63|128]+We[n>>8&255]+`-`+We[n>>16&255]+We[n>>24&255]+We[r&255]+We[r>>8&255]+We[r>>16&255]+We[r>>24&255]).toLowerCase()}function I(e,t,n){return Math.max(t,Math.min(n,e))}function Ye(e,t){return(e%t+t)%t}function Xe(e,t,n,r,i){return r+(e-t)*(i-r)/(n-t)}function Ze(e,t,n){return e===t?0:(n-e)/(t-e)}function Qe(e,t,n){return(1-n)*e+n*t}function $e(e,t,n,r){return Qe(e,t,1-Math.exp(-n*r))}function et(e,t=1){return t-Math.abs(Ye(e,t*2)-t)}function tt(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t),e*e*(3-2*e))}function nt(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t),e*e*e*(e*(e*6-15)+10))}function rt(e,t){return e+Math.floor(Math.random()*(t-e+1))}function it(e,t){return e+Math.random()*(t-e)}function at(e){return e*(.5-Math.random())}function ot(e){e!==void 0&&(Ge=e);let t=Ge+=1831565813;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}function st(e){return e*Ke}function ct(e){return e*qe}function lt(e){return(e&e-1)==0&&e!==0}function ut(e){return 2**Math.ceil(Math.log(e)/Math.LN2)}function dt(e){return 2**Math.floor(Math.log(e)/Math.LN2)}function ft(e,t,n,r,i){let a=Math.cos,o=Math.sin,s=a(n/2),c=o(n/2),l=a((t+r)/2),u=o((t+r)/2),d=a((t-r)/2),f=o((t-r)/2),p=a((r-t)/2),m=o((r-t)/2);switch(i){case`XYX`:e.set(s*u,c*d,c*f,s*l);break;case`YZY`:e.set(c*f,s*u,c*d,s*l);break;case`ZXZ`:e.set(c*d,c*f,s*u,s*l);break;case`XZX`:e.set(s*u,c*m,c*p,s*l);break;case`YXY`:e.set(c*p,s*u,c*m,s*l);break;case`ZYZ`:e.set(c*m,c*p,s*u,s*l);break;default:console.warn(`THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: `+i)}}function pt(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return e/4294967295;case Uint16Array:return e/65535;case Uint8Array:return e/255;case Int32Array:return Math.max(e/2147483647,-1);case Int16Array:return Math.max(e/32767,-1);case Int8Array:return Math.max(e/127,-1);default:throw Error(`Invalid component type.`)}}function mt(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return Math.round(e*4294967295);case Uint16Array:return Math.round(e*65535);case Uint8Array:return Math.round(e*255);case Int32Array:return Math.round(e*2147483647);case Int16Array:return Math.round(e*32767);case Int8Array:return Math.round(e*127);default:throw Error(`Invalid component type.`)}}var ht={DEG2RAD:Ke,RAD2DEG:qe,generateUUID:Je,clamp:I,euclideanModulo:Ye,mapLinear:Xe,inverseLerp:Ze,lerp:Qe,damp:$e,pingpong:et,smoothstep:tt,smootherstep:nt,randInt:rt,randFloat:it,randFloatSpread:at,seededRandom:ot,degToRad:st,radToDeg:ct,isPowerOfTwo:lt,ceilPowerOfTwo:ut,floorPowerOfTwo:dt,setQuaternionFromProperEuler:ft,normalize:mt,denormalize:pt},L=class e{constructor(t=0,n=0){e.prototype.isVector2=!0,this.x=t,this.y=n}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw Error(`index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw Error(`index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){let t=this.x,n=this.y,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6],this.y=r[1]*t+r[4]*n+r[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=I(this.x,e.x,t.x),this.y=I(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=I(this.x,e,t),this.y=I(this.y,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(I(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(I(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y;return t*t+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){let n=Math.cos(t),r=Math.sin(t),i=this.x-e.x,a=this.y-e.y;return this.x=i*n-a*r+e.x,this.y=i*r+a*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}},gt=class{constructor(e=0,t=0,n=0,r=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=n,this._w=r}static slerpFlat(e,t,n,r,i,a,o){let s=n[r+0],c=n[r+1],l=n[r+2],u=n[r+3],d=i[a+0],f=i[a+1],p=i[a+2],m=i[a+3];if(o===0){e[t+0]=s,e[t+1]=c,e[t+2]=l,e[t+3]=u;return}if(o===1){e[t+0]=d,e[t+1]=f,e[t+2]=p,e[t+3]=m;return}if(u!==m||s!==d||c!==f||l!==p){let e=1-o,t=s*d+c*f+l*p+u*m,n=t>=0?1:-1,r=1-t*t;if(r>2**-52){let i=Math.sqrt(r),a=Math.atan2(i,t*n);e=Math.sin(e*a)/i,o=Math.sin(o*a)/i}let i=o*n;if(s=s*e+d*i,c=c*e+f*i,l=l*e+p*i,u=u*e+m*i,e===1-o){let e=1/Math.sqrt(s*s+c*c+l*l+u*u);s*=e,c*=e,l*=e,u*=e}}e[t]=s,e[t+1]=c,e[t+2]=l,e[t+3]=u}static multiplyQuaternionsFlat(e,t,n,r,i,a){let o=n[r],s=n[r+1],c=n[r+2],l=n[r+3],u=i[a],d=i[a+1],f=i[a+2],p=i[a+3];return e[t]=o*p+l*u+s*f-c*d,e[t+1]=s*p+l*d+c*u-o*f,e[t+2]=c*p+l*f+o*d-s*u,e[t+3]=l*p-o*u-s*d-c*f,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,n,r){return this._x=e,this._y=t,this._z=n,this._w=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){let n=e._x,r=e._y,i=e._z,a=e._order,o=Math.cos,s=Math.sin,c=o(n/2),l=o(r/2),u=o(i/2),d=s(n/2),f=s(r/2),p=s(i/2);switch(a){case`XYZ`:this._x=d*l*u+c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u-d*f*p;break;case`YXZ`:this._x=d*l*u+c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u+d*f*p;break;case`ZXY`:this._x=d*l*u-c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u-d*f*p;break;case`ZYX`:this._x=d*l*u-c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u+d*f*p;break;case`YZX`:this._x=d*l*u+c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u-d*f*p;break;case`XZY`:this._x=d*l*u-c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u+d*f*p;break;default:console.warn(`THREE.Quaternion: .setFromEuler() encountered an unknown order: `+a)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){let n=t/2,r=Math.sin(n);return this._x=e.x*r,this._y=e.y*r,this._z=e.z*r,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){let t=e.elements,n=t[0],r=t[4],i=t[8],a=t[1],o=t[5],s=t[9],c=t[2],l=t[6],u=t[10],d=n+o+u;if(d>0){let e=.5/Math.sqrt(d+1);this._w=.25/e,this._x=(l-s)*e,this._y=(i-c)*e,this._z=(a-r)*e}else if(n>o&&n>u){let e=2*Math.sqrt(1+n-o-u);this._w=(l-s)/e,this._x=.25*e,this._y=(r+a)/e,this._z=(i+c)/e}else if(o>u){let e=2*Math.sqrt(1+o-n-u);this._w=(i-c)/e,this._x=(r+a)/e,this._y=.25*e,this._z=(s+l)/e}else{let e=2*Math.sqrt(1+u-n-o);this._w=(a-r)/e,this._x=(i+c)/e,this._y=(s+l)/e,this._z=.25*e}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return n<1e-8?(n=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(I(this.dot(e),-1,1)))}rotateTowards(e,t){let n=this.angleTo(e);if(n===0)return this;let r=Math.min(1,t/n);return this.slerp(e,r),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x*=e,this._y*=e,this._z*=e,this._w*=e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){let n=e._x,r=e._y,i=e._z,a=e._w,o=t._x,s=t._y,c=t._z,l=t._w;return this._x=n*l+a*o+r*c-i*s,this._y=r*l+a*s+i*o-n*c,this._z=i*l+a*c+n*s-r*o,this._w=a*l-n*o-r*s-i*c,this._onChangeCallback(),this}slerp(e,t){if(t===0)return this;if(t===1)return this.copy(e);let n=this._x,r=this._y,i=this._z,a=this._w,o=a*e._w+n*e._x+r*e._y+i*e._z;if(o<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,o=-o):this.copy(e),o>=1)return this._w=a,this._x=n,this._y=r,this._z=i,this;let s=1-o*o;if(s<=2**-52){let e=1-t;return this._w=e*a+t*this._w,this._x=e*n+t*this._x,this._y=e*r+t*this._y,this._z=e*i+t*this._z,this.normalize(),this}let c=Math.sqrt(s),l=Math.atan2(c,o),u=Math.sin((1-t)*l)/c,d=Math.sin(t*l)/c;return this._w=a*u+this._w*d,this._x=n*u+this._x*d,this._y=r*u+this._y*d,this._z=i*u+this._z*d,this._onChangeCallback(),this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){let e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),n=Math.random(),r=Math.sqrt(1-n),i=Math.sqrt(n);return this.set(r*Math.sin(e),r*Math.cos(e),i*Math.sin(t),i*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}},R=class e{constructor(t=0,n=0,r=0){e.prototype.isVector3=!0,this.x=t,this.y=n,this.z=r}set(e,t,n){return n===void 0&&(n=this.z),this.x=e,this.y=t,this.z=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw Error(`index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw Error(`index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(vt.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(vt.setFromAxisAngle(e,t))}applyMatrix3(e){let t=this.x,n=this.y,r=this.z,i=e.elements;return this.x=i[0]*t+i[3]*n+i[6]*r,this.y=i[1]*t+i[4]*n+i[7]*r,this.z=i[2]*t+i[5]*n+i[8]*r,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){let t=this.x,n=this.y,r=this.z,i=e.elements,a=1/(i[3]*t+i[7]*n+i[11]*r+i[15]);return this.x=(i[0]*t+i[4]*n+i[8]*r+i[12])*a,this.y=(i[1]*t+i[5]*n+i[9]*r+i[13])*a,this.z=(i[2]*t+i[6]*n+i[10]*r+i[14])*a,this}applyQuaternion(e){let t=this.x,n=this.y,r=this.z,i=e.x,a=e.y,o=e.z,s=e.w,c=2*(a*r-o*n),l=2*(o*t-i*r),u=2*(i*n-a*t);return this.x=t+s*c+a*u-o*l,this.y=n+s*l+o*c-i*u,this.z=r+s*u+i*l-a*c,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){let t=this.x,n=this.y,r=this.z,i=e.elements;return this.x=i[0]*t+i[4]*n+i[8]*r,this.y=i[1]*t+i[5]*n+i[9]*r,this.z=i[2]*t+i[6]*n+i[10]*r,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=I(this.x,e.x,t.x),this.y=I(this.y,e.y,t.y),this.z=I(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=I(this.x,e,t),this.y=I(this.y,e,t),this.z=I(this.z,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(I(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){let n=e.x,r=e.y,i=e.z,a=t.x,o=t.y,s=t.z;return this.x=r*s-i*o,this.y=i*a-n*s,this.z=n*o-r*a,this}projectOnVector(e){let t=e.lengthSq();if(t===0)return this.set(0,0,0);let n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return _t.copy(this).projectOnVector(e),this.sub(_t)}reflect(e){return this.sub(_t.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(I(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y,r=this.z-e.z;return t*t+n*n+r*r}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,n){let r=Math.sin(t)*e;return this.x=r*Math.sin(n),this.y=Math.cos(t)*e,this.z=r*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){let t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),r=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=r,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){let e=Math.random()*Math.PI*2,t=Math.random()*2-1,n=Math.sqrt(1-t*t);return this.x=n*Math.cos(e),this.y=t,this.z=n*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}},_t=new R,vt=new gt,z=class e{constructor(t,n,r,i,a,o,s,c,l){e.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],t!==void 0&&this.set(t,n,r,i,a,o,s,c,l)}set(e,t,n,r,i,a,o,s,c){let l=this.elements;return l[0]=e,l[1]=r,l[2]=o,l[3]=t,l[4]=i,l[5]=s,l[6]=n,l[7]=a,l[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){let t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(e){let t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let n=e.elements,r=t.elements,i=this.elements,a=n[0],o=n[3],s=n[6],c=n[1],l=n[4],u=n[7],d=n[2],f=n[5],p=n[8],m=r[0],h=r[3],g=r[6],_=r[1],v=r[4],y=r[7],b=r[2],x=r[5],S=r[8];return i[0]=a*m+o*_+s*b,i[3]=a*h+o*v+s*x,i[6]=a*g+o*y+s*S,i[1]=c*m+l*_+u*b,i[4]=c*h+l*v+u*x,i[7]=c*g+l*y+u*S,i[2]=d*m+f*_+p*b,i[5]=d*h+f*v+p*x,i[8]=d*g+f*y+p*S,this}multiplyScalar(e){let t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8];return t*a*l-t*o*c-n*i*l+n*o*s+r*i*c-r*a*s}invert(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8],u=l*a-o*c,d=o*s-l*i,f=c*i-a*s,p=t*u+n*d+r*f;if(p===0)return this.set(0,0,0,0,0,0,0,0,0);let m=1/p;return e[0]=u*m,e[1]=(r*c-l*n)*m,e[2]=(o*n-r*a)*m,e[3]=d*m,e[4]=(l*t-r*s)*m,e[5]=(r*i-o*t)*m,e[6]=f*m,e[7]=(n*s-c*t)*m,e[8]=(a*t-n*i)*m,this}transpose(){let e,t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){let t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,n,r,i,a,o){let s=Math.cos(i),c=Math.sin(i);return this.set(n*s,n*c,-n*(s*a+c*o)+a+e,-r*c,r*s,-r*(-c*a+s*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply(yt.makeScale(e,t)),this}rotate(e){return this.premultiply(yt.makeRotation(-e)),this}translate(e,t){return this.premultiply(yt.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,n,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){let t=this.elements,n=e.elements;for(let e=0;e<9;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){let n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return new this.constructor().fromArray(this.elements)}},yt=new z;function bt(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}function xt(e){return document.createElementNS(`http://www.w3.org/1999/xhtml`,e)}function St(){let e=xt(`canvas`);return e.style.display=`block`,e}var Ct={};function wt(e){e in Ct||(Ct[e]=!0,console.warn(e))}function Tt(e,t,n){return new Promise(function(r,i){function a(){switch(e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0)){case e.WAIT_FAILED:i();break;case e.TIMEOUT_EXPIRED:setTimeout(a,n);break;default:r()}}setTimeout(a,n)})}var Et=new z().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),Dt=new z().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function Ot(){let e={enabled:!0,workingColorSpace:Le,spaces:{},convert:function(e,t,n){return this.enabled===!1||t===n||!t||!n?e:(this.spaces[t].transfer===`srgb`&&(e.r=At(e.r),e.g=At(e.g),e.b=At(e.b)),this.spaces[t].primaries!==this.spaces[n].primaries&&(e.applyMatrix3(this.spaces[t].toXYZ),e.applyMatrix3(this.spaces[n].fromXYZ)),this.spaces[n].transfer===`srgb`&&(e.r=jt(e.r),e.g=jt(e.g),e.b=jt(e.b)),e)},workingToColorSpace:function(e,t){return this.convert(e,this.workingColorSpace,t)},colorSpaceToWorking:function(e,t){return this.convert(e,t,this.workingColorSpace)},getPrimaries:function(e){return this.spaces[e].primaries},getTransfer:function(e){return e===``?Re:this.spaces[e].transfer},getToneMappingMode:function(e){return this.spaces[e].outputColorSpaceConfig.toneMappingMode||`standard`},getLuminanceCoefficients:function(e,t=this.workingColorSpace){return e.fromArray(this.spaces[t].luminanceCoefficients)},define:function(e){Object.assign(this.spaces,e)},_getMatrix:function(e,t,n){return e.copy(this.spaces[t].toXYZ).multiply(this.spaces[n].fromXYZ)},_getDrawingBufferColorSpace:function(e){return this.spaces[e].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(e=this.workingColorSpace){return this.spaces[e].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(t,n){return wt(`THREE.ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().`),e.workingToColorSpace(t,n)},toWorkingColorSpace:function(t,n){return wt(`THREE.ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking().`),e.colorSpaceToWorking(t,n)}},t=[.64,.33,.3,.6,.15,.06],n=[.2126,.7152,.0722],r=[.3127,.329];return e.define({[Le]:{primaries:t,whitePoint:r,transfer:Re,toXYZ:Et,fromXYZ:Dt,luminanceCoefficients:n,workingColorSpaceConfig:{unpackColorSpace:Ie},outputColorSpaceConfig:{drawingBufferColorSpace:Ie}},[Ie]:{primaries:t,whitePoint:r,transfer:ze,toXYZ:Et,fromXYZ:Dt,luminanceCoefficients:n,outputColorSpaceConfig:{drawingBufferColorSpace:Ie}}}),e}var kt=Ot();function At(e){return e<.04045?e*.0773993808:(e*.9478672986+.0521327014)**2.4}function jt(e){return e<.0031308?e*12.92:1.055*e**.41666-.055}var Mt,Nt=class{static getDataURL(e,t=`image/png`){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>`u`)return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{Mt===void 0&&(Mt=xt(`canvas`)),Mt.width=e.width,Mt.height=e.height;let t=Mt.getContext(`2d`);e instanceof ImageData?t.putImageData(e,0,0):t.drawImage(e,0,0,e.width,e.height),n=Mt}return n.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap){let t=xt(`canvas`);t.width=e.width,t.height=e.height;let n=t.getContext(`2d`);n.drawImage(e,0,0,e.width,e.height);let r=n.getImageData(0,0,e.width,e.height),i=r.data;for(let e=0;e<i.length;e++)i[e]=At(i[e]/255)*255;return n.putImageData(r,0,0),t}else if(e.data){let t=e.data.slice(0);for(let e=0;e<t.length;e++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[e]=Math.floor(At(t[e]/255)*255):t[e]=At(t[e]);return{data:t,width:e.width,height:e.height}}else return console.warn(`THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.`),e}},Pt=0,Ft=class{constructor(e=null){this.isSource=!0,Object.defineProperty(this,`id`,{value:Pt++}),this.uuid=Je(),this.data=e,this.dataReady=!0,this.version=0}getSize(e){let t=this.data;return typeof HTMLVideoElement<`u`&&t instanceof HTMLVideoElement?e.set(t.videoWidth,t.videoHeight,0):t instanceof VideoFrame?e.set(t.displayHeight,t.displayWidth,0):t===null?e.set(0,0,0):e.set(t.width,t.height,t.depth||0),e}set needsUpdate(e){e===!0&&this.version++}toJSON(e){let t=e===void 0||typeof e==`string`;if(!t&&e.images[this.uuid]!==void 0)return e.images[this.uuid];let n={uuid:this.uuid,url:``},r=this.data;if(r!==null){let e;if(Array.isArray(r)){e=[];for(let t=0,n=r.length;t<n;t++)r[t].isDataTexture?e.push(It(r[t].image)):e.push(It(r[t]))}else e=It(r);n.url=e}return t||(e.images[this.uuid]=n),n}};function It(e){return typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap?Nt.getDataURL(e):e.data?{data:Array.from(e.data),width:e.width,height:e.height,type:e.data.constructor.name}:(console.warn(`THREE.Texture: Unable to serialize Texture.`),{})}var Lt=0,Rt=new R,zt=class r extends Ue{constructor(e=r.DEFAULT_IMAGE,n=r.DEFAULT_MAPPING,i=t,a=t,s=o,u=c,d=w,f=l,p=r.DEFAULT_ANISOTROPY,m=``){super(),this.isTexture=!0,Object.defineProperty(this,`id`,{value:Lt++}),this.uuid=Je(),this.name=``,this.source=new Ft(e),this.mipmaps=[],this.mapping=n,this.channel=0,this.wrapS=i,this.wrapT=a,this.magFilter=s,this.minFilter=u,this.anisotropy=p,this.format=d,this.internalFormat=null,this.type=f,this.offset=new L(0,0),this.repeat=new L(1,1),this.center=new L(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new z,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=m,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(e&&e.depth&&e.depth>1),this.pmremVersion=0}get width(){return this.source.getSize(Rt).x}get height(){return this.source.getSize(Rt).y}get depth(){return this.source.getSize(Rt).z}get image(){return this.source.data}set image(e=null){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(let t in e){let n=e[t];if(n===void 0){console.warn(`THREE.Texture.setValues(): parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){console.warn(`THREE.Texture.setValues(): property '${t}' does not exist.`);continue}r&&n&&r.isVector2&&n.isVector2||r&&n&&r.isVector3&&n.isVector3||r&&n&&r.isMatrix3&&n.isMatrix3?r.copy(n):this[t]=n}}toJSON(e){let t=e===void 0||typeof e==`string`;if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];let n={metadata:{version:4.7,type:`Texture`,generator:`Texture.toJSON`},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(n.userData=this.userData),t||(e.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:`dispose`})}transformUv(r){if(this.mapping!==300)return r;if(r.applyMatrix3(this.matrix),r.x<0||r.x>1)switch(this.wrapS){case e:r.x-=Math.floor(r.x);break;case t:r.x=r.x<0?0:1;break;case n:Math.abs(Math.floor(r.x)%2)===1?r.x=Math.ceil(r.x)-r.x:r.x-=Math.floor(r.x);break}if(r.y<0||r.y>1)switch(this.wrapT){case e:r.y-=Math.floor(r.y);break;case t:r.y=r.y<0?0:1;break;case n:Math.abs(Math.floor(r.y)%2)===1?r.y=Math.ceil(r.y)-r.y:r.y-=Math.floor(r.y);break}return this.flipY&&(r.y=1-r.y),r}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}};zt.DEFAULT_IMAGE=null,zt.DEFAULT_MAPPING=300,zt.DEFAULT_ANISOTROPY=1;var Bt=class e{constructor(t=0,n=0,r=0,i=1){e.prototype.isVector4=!0,this.x=t,this.y=n,this.z=r,this.w=i}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,n,r){return this.x=e,this.y=t,this.z=n,this.w=r,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw Error(`index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw Error(`index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w===void 0?1:e.w,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){let t=this.x,n=this.y,r=this.z,i=this.w,a=e.elements;return this.x=a[0]*t+a[4]*n+a[8]*r+a[12]*i,this.y=a[1]*t+a[5]*n+a[9]*r+a[13]*i,this.z=a[2]*t+a[6]*n+a[10]*r+a[14]*i,this.w=a[3]*t+a[7]*n+a[11]*r+a[15]*i,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);let t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,n,r,i,a=.01,o=.1,s=e.elements,c=s[0],l=s[4],u=s[8],d=s[1],f=s[5],p=s[9],m=s[2],h=s[6],g=s[10];if(Math.abs(l-d)<a&&Math.abs(u-m)<a&&Math.abs(p-h)<a){if(Math.abs(l+d)<o&&Math.abs(u+m)<o&&Math.abs(p+h)<o&&Math.abs(c+f+g-3)<o)return this.set(1,0,0,0),this;t=Math.PI;let e=(c+1)/2,s=(f+1)/2,_=(g+1)/2,v=(l+d)/4,y=(u+m)/4,b=(p+h)/4;return e>s&&e>_?e<a?(n=0,r=.707106781,i=.707106781):(n=Math.sqrt(e),r=v/n,i=y/n):s>_?s<a?(n=.707106781,r=0,i=.707106781):(r=Math.sqrt(s),n=v/r,i=b/r):_<a?(n=.707106781,r=.707106781,i=0):(i=Math.sqrt(_),n=y/i,r=b/i),this.set(n,r,i,t),this}let _=Math.sqrt((h-p)*(h-p)+(u-m)*(u-m)+(d-l)*(d-l));return Math.abs(_)<.001&&(_=1),this.x=(h-p)/_,this.y=(u-m)/_,this.z=(d-l)/_,this.w=Math.acos((c+f+g-1)/2),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=I(this.x,e.x,t.x),this.y=I(this.y,e.y,t.y),this.z=I(this.z,e.z,t.z),this.w=I(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=I(this.x,e,t),this.y=I(this.y,e,t),this.z=I(this.z,e,t),this.w=I(this.w,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(I(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this.w=e.w+(t.w-e.w)*n,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}},Vt=class extends Ue{constructor(e=1,t=1,n={}){super(),n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:o,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},n),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=n.depth,this.scissor=new Bt(0,0,e,t),this.scissorTest=!1,this.viewport=new Bt(0,0,e,t);let r=new zt({width:e,height:t,depth:n.depth});this.textures=[];let i=n.count;for(let e=0;e<i;e++)this.textures[e]=r.clone(),this.textures[e].isRenderTargetTexture=!0,this.textures[e].renderTarget=this;this._setTextureOptions(n),this.depthBuffer=n.depthBuffer,this.stencilBuffer=n.stencilBuffer,this.resolveDepthBuffer=n.resolveDepthBuffer,this.resolveStencilBuffer=n.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=n.depthTexture,this.samples=n.samples,this.multiview=n.multiview}_setTextureOptions(e={}){let t={minFilter:o,generateMipmaps:!1,flipY:!1,internalFormat:null};e.mapping!==void 0&&(t.mapping=e.mapping),e.wrapS!==void 0&&(t.wrapS=e.wrapS),e.wrapT!==void 0&&(t.wrapT=e.wrapT),e.wrapR!==void 0&&(t.wrapR=e.wrapR),e.magFilter!==void 0&&(t.magFilter=e.magFilter),e.minFilter!==void 0&&(t.minFilter=e.minFilter),e.format!==void 0&&(t.format=e.format),e.type!==void 0&&(t.type=e.type),e.anisotropy!==void 0&&(t.anisotropy=e.anisotropy),e.colorSpace!==void 0&&(t.colorSpace=e.colorSpace),e.flipY!==void 0&&(t.flipY=e.flipY),e.generateMipmaps!==void 0&&(t.generateMipmaps=e.generateMipmaps),e.internalFormat!==void 0&&(t.internalFormat=e.internalFormat);for(let e=0;e<this.textures.length;e++)this.textures[e].setValues(t)}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}set depthTexture(e){this._depthTexture!==null&&(this._depthTexture.renderTarget=null),e!==null&&(e.renderTarget=this),this._depthTexture=e}get depthTexture(){return this._depthTexture}setSize(e,t,n=1){if(this.width!==e||this.height!==t||this.depth!==n){this.width=e,this.height=t,this.depth=n;for(let r=0,i=this.textures.length;r<i;r++)this.textures[r].image.width=e,this.textures[r].image.height=t,this.textures[r].image.depth=n,this.textures[r].isArrayTexture=this.textures[r].image.depth>1;this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,n=e.textures.length;t<n;t++){this.textures[t]=e.textures[t].clone(),this.textures[t].isRenderTargetTexture=!0,this.textures[t].renderTarget=this;let n=Object.assign({},e.textures[t].image);this.textures[t].source=new Ft(n)}return this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,e.depthTexture!==null&&(this.depthTexture=e.depthTexture.clone()),this.samples=e.samples,this}dispose(){this.dispatchEvent({type:`dispose`})}},Ht=class extends Vt{constructor(e=1,t=1,n={}){super(e,t,n),this.isWebGLRenderTarget=!0}},Ut=class extends zt{constructor(e=null,n=1,i=1,a=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:n,height:i,depth:a},this.magFilter=r,this.minFilter=r,this.wrapR=t,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}},Wt=class extends zt{constructor(e=null,n=1,i=1,a=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:n,height:i,depth:a},this.magFilter=r,this.minFilter=r,this.wrapR=t,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}},Gt=class{constructor(e=new R(1/0,1/0,1/0),t=new R(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t+=3)this.expandByPoint(qt.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,n=e.count;t<n;t++)this.expandByPoint(qt.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){let n=qt.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(n),this.max.copy(e).add(n),this}setFromObject(e,t=!1){return this.makeEmpty(),this.expandByObject(e,t)}clone(){return new this.constructor().copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,t=!1){e.updateWorldMatrix(!1,!1);let n=e.geometry;if(n!==void 0){let r=n.getAttribute(`position`);if(t===!0&&r!==void 0&&e.isInstancedMesh!==!0)for(let t=0,n=r.count;t<n;t++)e.isMesh===!0?e.getVertexPosition(t,qt):qt.fromBufferAttribute(r,t),qt.applyMatrix4(e.matrixWorld),this.expandByPoint(qt);else e.boundingBox===void 0?(n.boundingBox===null&&n.computeBoundingBox(),Jt.copy(n.boundingBox)):(e.boundingBox===null&&e.computeBoundingBox(),Jt.copy(e.boundingBox)),Jt.applyMatrix4(e.matrixWorld),this.union(Jt)}let r=e.children;for(let e=0,n=r.length;e<n;e++)this.expandByObject(r[e],t);return this}containsPoint(e){return e.x>=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,qt),qt.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(tn),nn.subVectors(this.max,tn),Yt.subVectors(e.a,tn),Xt.subVectors(e.b,tn),Zt.subVectors(e.c,tn),Qt.subVectors(Xt,Yt),$t.subVectors(Zt,Xt),en.subVectors(Yt,Zt);let t=[0,-Qt.z,Qt.y,0,-$t.z,$t.y,0,-en.z,en.y,Qt.z,0,-Qt.x,$t.z,0,-$t.x,en.z,0,-en.x,-Qt.y,Qt.x,0,-$t.y,$t.x,0,-en.y,en.x,0];return!on(t,Yt,Xt,Zt,nn)||(t=[1,0,0,0,1,0,0,0,1],!on(t,Yt,Xt,Zt,nn))?!1:(rn.crossVectors(Qt,$t),t=[rn.x,rn.y,rn.z],on(t,Yt,Xt,Zt,nn))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,qt).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(qt).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(Kt[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Kt[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Kt[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Kt[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Kt[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Kt[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Kt[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Kt[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Kt),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}},Kt=[new R,new R,new R,new R,new R,new R,new R,new R],qt=new R,Jt=new Gt,Yt=new R,Xt=new R,Zt=new R,Qt=new R,$t=new R,en=new R,tn=new R,nn=new R,rn=new R,an=new R;function on(e,t,n,r,i){for(let a=0,o=e.length-3;a<=o;a+=3){an.fromArray(e,a);let o=i.x*Math.abs(an.x)+i.y*Math.abs(an.y)+i.z*Math.abs(an.z),s=t.dot(an),c=n.dot(an),l=r.dot(an);if(Math.max(-Math.max(s,c,l),Math.min(s,c,l))>o)return!1}return!0}var sn=new Gt,cn=new R,ln=new R,un=class{constructor(e=new R,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){let n=this.center;t===void 0?sn.setFromPoints(e).getCenter(n):n.copy(t);let r=0;for(let t=0,i=e.length;t<i;t++)r=Math.max(r,n.distanceToSquared(e[t]));return this.radius=Math.sqrt(r),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){let t=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=t*t}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,t){let n=this.center.distanceToSquared(e);return t.copy(e),n>this.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius*=e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;cn.subVectors(e,this.center);let t=cn.lengthSq();if(t>this.radius*this.radius){let e=Math.sqrt(t),n=(e-this.radius)*.5;this.center.addScaledVector(cn,n/e),this.radius+=n}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(ln.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(cn.copy(e.center).add(ln)),this.expandByPoint(cn.copy(e.center).sub(ln))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}},dn=new R,fn=new R,pn=new R,mn=new R,hn=new R,gn=new R,_n=new R,vn=class{constructor(e=new R,t=new R(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,dn)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);let n=t.dot(this.direction);return n<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){let t=dn.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(dn.copy(this.origin).addScaledVector(this.direction,t),dn.distanceToSquared(e))}distanceSqToSegment(e,t,n,r){fn.copy(e).add(t).multiplyScalar(.5),pn.copy(t).sub(e).normalize(),mn.copy(this.origin).sub(fn);let i=e.distanceTo(t)*.5,a=-this.direction.dot(pn),o=mn.dot(this.direction),s=-mn.dot(pn),c=mn.lengthSq(),l=Math.abs(1-a*a),u,d,f,p;if(l>0)if(u=a*s-o,d=a*o-s,p=i*l,u>=0)if(d>=-p)if(d<=p){let e=1/l;u*=e,d*=e,f=u*(u+a*d+2*o)+d*(a*u+d+2*s)+c}else d=i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c;else d=-i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c;else d<=-p?(u=Math.max(0,-(-a*i+o)),d=u>0?-i:Math.min(Math.max(-i,-s),i),f=-u*u+d*(d+2*s)+c):d<=p?(u=0,d=Math.min(Math.max(-i,-s),i),f=d*(d+2*s)+c):(u=Math.max(0,-(a*i+o)),d=u>0?i:Math.min(Math.max(-i,-s),i),f=-u*u+d*(d+2*s)+c);else d=a>0?-i:i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c;return n&&n.copy(this.origin).addScaledVector(this.direction,u),r&&r.copy(fn).addScaledVector(pn,d),f}intersectSphere(e,t){dn.subVectors(e.center,this.origin);let n=dn.dot(this.direction),r=dn.dot(dn)-n*n,i=e.radius*e.radius;if(r>i)return null;let a=Math.sqrt(i-r),o=n-a,s=n+a;return s<0?null:o<0?this.at(s,t):this.at(o,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){let t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;let n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){let n=this.distanceToPlane(e);return n===null?null:this.at(n,t)}intersectsPlane(e){let t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,r,i,a,o,s,c=1/this.direction.x,l=1/this.direction.y,u=1/this.direction.z,d=this.origin;return c>=0?(n=(e.min.x-d.x)*c,r=(e.max.x-d.x)*c):(n=(e.max.x-d.x)*c,r=(e.min.x-d.x)*c),l>=0?(i=(e.min.y-d.y)*l,a=(e.max.y-d.y)*l):(i=(e.max.y-d.y)*l,a=(e.min.y-d.y)*l),n>a||i>r||((i>n||isNaN(n))&&(n=i),(a<r||isNaN(r))&&(r=a),u>=0?(o=(e.min.z-d.z)*u,s=(e.max.z-d.z)*u):(o=(e.max.z-d.z)*u,s=(e.min.z-d.z)*u),n>s||o>r)||((o>n||n!==n)&&(n=o),(s<r||r!==r)&&(r=s),r<0)?null:this.at(n>=0?n:r,t)}intersectsBox(e){return this.intersectBox(e,dn)!==null}intersectTriangle(e,t,n,r,i){hn.subVectors(t,e),gn.subVectors(n,e),_n.crossVectors(hn,gn);let a=this.direction.dot(_n),o;if(a>0){if(r)return null;o=1}else if(a<0)o=-1,a=-a;else return null;mn.subVectors(this.origin,e);let s=o*this.direction.dot(gn.crossVectors(mn,gn));if(s<0)return null;let c=o*this.direction.dot(hn.cross(mn));if(c<0||s+c>a)return null;let l=-o*mn.dot(_n);return l<0?null:this.at(l/a,i)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}},yn=class e{constructor(t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g){e.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],t!==void 0&&this.set(t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g)}set(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){let g=this.elements;return g[0]=e,g[4]=t,g[8]=n,g[12]=r,g[1]=i,g[5]=a,g[9]=o,g[13]=s,g[2]=c,g[6]=l,g[10]=u,g[14]=d,g[3]=f,g[7]=p,g[11]=m,g[15]=h,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new e().fromArray(this.elements)}copy(e){let t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],t[9]=n[9],t[10]=n[10],t[11]=n[11],t[12]=n[12],t[13]=n[13],t[14]=n[14],t[15]=n[15],this}copyPosition(e){let t=this.elements,n=e.elements;return t[12]=n[12],t[13]=n[13],t[14]=n[14],this}setFromMatrix3(e){let t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,n){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this}makeBasis(e,t,n){return this.set(e.x,t.x,n.x,0,e.y,t.y,n.y,0,e.z,t.z,n.z,0,0,0,0,1),this}extractRotation(e){let t=this.elements,n=e.elements,r=1/bn.setFromMatrixColumn(e,0).length(),i=1/bn.setFromMatrixColumn(e,1).length(),a=1/bn.setFromMatrixColumn(e,2).length();return t[0]=n[0]*r,t[1]=n[1]*r,t[2]=n[2]*r,t[3]=0,t[4]=n[4]*i,t[5]=n[5]*i,t[6]=n[6]*i,t[7]=0,t[8]=n[8]*a,t[9]=n[9]*a,t[10]=n[10]*a,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){let t=this.elements,n=e.x,r=e.y,i=e.z,a=Math.cos(n),o=Math.sin(n),s=Math.cos(r),c=Math.sin(r),l=Math.cos(i),u=Math.sin(i);if(e.order===`XYZ`){let e=a*l,n=a*u,r=o*l,i=o*u;t[0]=s*l,t[4]=-s*u,t[8]=c,t[1]=n+r*c,t[5]=e-i*c,t[9]=-o*s,t[2]=i-e*c,t[6]=r+n*c,t[10]=a*s}else if(e.order===`YXZ`){let e=s*l,n=s*u,r=c*l,i=c*u;t[0]=e+i*o,t[4]=r*o-n,t[8]=a*c,t[1]=a*u,t[5]=a*l,t[9]=-o,t[2]=n*o-r,t[6]=i+e*o,t[10]=a*s}else if(e.order===`ZXY`){let e=s*l,n=s*u,r=c*l,i=c*u;t[0]=e-i*o,t[4]=-a*u,t[8]=r+n*o,t[1]=n+r*o,t[5]=a*l,t[9]=i-e*o,t[2]=-a*c,t[6]=o,t[10]=a*s}else if(e.order===`ZYX`){let e=a*l,n=a*u,r=o*l,i=o*u;t[0]=s*l,t[4]=r*c-n,t[8]=e*c+i,t[1]=s*u,t[5]=i*c+e,t[9]=n*c-r,t[2]=-c,t[6]=o*s,t[10]=a*s}else if(e.order===`YZX`){let e=a*s,n=a*c,r=o*s,i=o*c;t[0]=s*l,t[4]=i-e*u,t[8]=r*u+n,t[1]=u,t[5]=a*l,t[9]=-o*l,t[2]=-c*l,t[6]=n*u+r,t[10]=e-i*u}else if(e.order===`XZY`){let e=a*s,n=a*c,r=o*s,i=o*c;t[0]=s*l,t[4]=-u,t[8]=c*l,t[1]=e*u+i,t[5]=a*l,t[9]=n*u-r,t[2]=r*u-n,t[6]=o*l,t[10]=i*u+e}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(Sn,e,Cn)}lookAt(e,t,n){let r=this.elements;return En.subVectors(e,t),En.lengthSq()===0&&(En.z=1),En.normalize(),wn.crossVectors(n,En),wn.lengthSq()===0&&(Math.abs(n.z)===1?En.x+=1e-4:En.z+=1e-4,En.normalize(),wn.crossVectors(n,En)),wn.normalize(),Tn.crossVectors(En,wn),r[0]=wn.x,r[4]=Tn.x,r[8]=En.x,r[1]=wn.y,r[5]=Tn.y,r[9]=En.y,r[2]=wn.z,r[6]=Tn.z,r[10]=En.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let n=e.elements,r=t.elements,i=this.elements,a=n[0],o=n[4],s=n[8],c=n[12],l=n[1],u=n[5],d=n[9],f=n[13],p=n[2],m=n[6],h=n[10],g=n[14],_=n[3],v=n[7],y=n[11],b=n[15],x=r[0],S=r[4],C=r[8],w=r[12],T=r[1],E=r[5],D=r[9],ee=r[13],O=r[2],k=r[6],te=r[10],ne=r[14],A=r[3],re=r[7],ie=r[11],j=r[15];return i[0]=a*x+o*T+s*O+c*A,i[4]=a*S+o*E+s*k+c*re,i[8]=a*C+o*D+s*te+c*ie,i[12]=a*w+o*ee+s*ne+c*j,i[1]=l*x+u*T+d*O+f*A,i[5]=l*S+u*E+d*k+f*re,i[9]=l*C+u*D+d*te+f*ie,i[13]=l*w+u*ee+d*ne+f*j,i[2]=p*x+m*T+h*O+g*A,i[6]=p*S+m*E+h*k+g*re,i[10]=p*C+m*D+h*te+g*ie,i[14]=p*w+m*ee+h*ne+g*j,i[3]=_*x+v*T+y*O+b*A,i[7]=_*S+v*E+y*k+b*re,i[11]=_*C+v*D+y*te+b*ie,i[15]=_*w+v*ee+y*ne+b*j,this}multiplyScalar(e){let t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){let e=this.elements,t=e[0],n=e[4],r=e[8],i=e[12],a=e[1],o=e[5],s=e[9],c=e[13],l=e[2],u=e[6],d=e[10],f=e[14],p=e[3],m=e[7],h=e[11],g=e[15];return p*(+i*s*u-r*c*u-i*o*d+n*c*d+r*o*f-n*s*f)+m*(+t*s*f-t*c*d+i*a*d-r*a*f+r*c*l-i*s*l)+h*(+t*c*u-t*o*f-i*a*u+n*a*f+i*o*l-n*c*l)+g*(-r*o*l-t*s*u+t*o*d+r*a*u-n*a*d+n*s*l)}transpose(){let e=this.elements,t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,n){let r=this.elements;return e.isVector3?(r[12]=e.x,r[13]=e.y,r[14]=e.z):(r[12]=e,r[13]=t,r[14]=n),this}invert(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8],u=e[9],d=e[10],f=e[11],p=e[12],m=e[13],h=e[14],g=e[15],_=u*h*c-m*d*c+m*s*f-o*h*f-u*s*g+o*d*g,v=p*d*c-l*h*c-p*s*f+a*h*f+l*s*g-a*d*g,y=l*m*c-p*u*c+p*o*f-a*m*f-l*o*g+a*u*g,b=p*u*s-l*m*s-p*o*d+a*m*d+l*o*h-a*u*h,x=t*_+n*v+r*y+i*b;if(x===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);let S=1/x;return e[0]=_*S,e[1]=(m*d*i-u*h*i-m*r*f+n*h*f+u*r*g-n*d*g)*S,e[2]=(o*h*i-m*s*i+m*r*c-n*h*c-o*r*g+n*s*g)*S,e[3]=(u*s*i-o*d*i-u*r*c+n*d*c+o*r*f-n*s*f)*S,e[4]=v*S,e[5]=(l*h*i-p*d*i+p*r*f-t*h*f-l*r*g+t*d*g)*S,e[6]=(p*s*i-a*h*i-p*r*c+t*h*c+a*r*g-t*s*g)*S,e[7]=(a*d*i-l*s*i+l*r*c-t*d*c-a*r*f+t*s*f)*S,e[8]=y*S,e[9]=(p*u*i-l*m*i-p*n*f+t*m*f+l*n*g-t*u*g)*S,e[10]=(a*m*i-p*o*i+p*n*c-t*m*c-a*n*g+t*o*g)*S,e[11]=(l*o*i-a*u*i-l*n*c+t*u*c+a*n*f-t*o*f)*S,e[12]=b*S,e[13]=(l*m*r-p*u*r+p*n*d-t*m*d-l*n*h+t*u*h)*S,e[14]=(p*o*r-a*m*r-p*n*s+t*m*s+a*n*h-t*o*h)*S,e[15]=(a*u*r-l*o*r+l*n*s-t*u*s-a*n*d+t*o*d)*S,this}scale(e){let t=this.elements,n=e.x,r=e.y,i=e.z;return t[0]*=n,t[4]*=r,t[8]*=i,t[1]*=n,t[5]*=r,t[9]*=i,t[2]*=n,t[6]*=r,t[10]*=i,t[3]*=n,t[7]*=r,t[11]*=i,this}getMaxScaleOnAxis(){let e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],n=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],r=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,r))}makeTranslation(e,t,n){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,n,0,0,0,1),this}makeRotationX(e){let t=Math.cos(e),n=Math.sin(e);return this.set(1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1),this}makeRotationY(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1),this}makeRotationZ(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){let n=Math.cos(t),r=Math.sin(t),i=1-n,a=e.x,o=e.y,s=e.z,c=i*a,l=i*o;return this.set(c*a+n,c*o-r*s,c*s+r*o,0,c*o+r*s,l*o+n,l*s-r*a,0,c*s-r*o,l*s+r*a,i*s*s+n,0,0,0,0,1),this}makeScale(e,t,n){return this.set(e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1),this}makeShear(e,t,n,r,i,a){return this.set(1,n,i,0,e,1,a,0,t,r,1,0,0,0,0,1),this}compose(e,t,n){let r=this.elements,i=t._x,a=t._y,o=t._z,s=t._w,c=i+i,l=a+a,u=o+o,d=i*c,f=i*l,p=i*u,m=a*l,h=a*u,g=o*u,_=s*c,v=s*l,y=s*u,b=n.x,x=n.y,S=n.z;return r[0]=(1-(m+g))*b,r[1]=(f+y)*b,r[2]=(p-v)*b,r[3]=0,r[4]=(f-y)*x,r[5]=(1-(d+g))*x,r[6]=(h+_)*x,r[7]=0,r[8]=(p+v)*S,r[9]=(h-_)*S,r[10]=(1-(d+m))*S,r[11]=0,r[12]=e.x,r[13]=e.y,r[14]=e.z,r[15]=1,this}decompose(e,t,n){let r=this.elements,i=bn.set(r[0],r[1],r[2]).length(),a=bn.set(r[4],r[5],r[6]).length(),o=bn.set(r[8],r[9],r[10]).length();this.determinant()<0&&(i=-i),e.x=r[12],e.y=r[13],e.z=r[14],xn.copy(this);let s=1/i,c=1/a,l=1/o;return xn.elements[0]*=s,xn.elements[1]*=s,xn.elements[2]*=s,xn.elements[4]*=c,xn.elements[5]*=c,xn.elements[6]*=c,xn.elements[8]*=l,xn.elements[9]*=l,xn.elements[10]*=l,t.setFromRotationMatrix(xn),n.x=i,n.y=a,n.z=o,this}makePerspective(e,t,n,r,i,a,o=He,s=!1){let c=this.elements,l=2*i/(t-e),u=2*i/(n-r),d=(t+e)/(t-e),f=(n+r)/(n-r),p,m;if(s)p=i/(a-i),m=a*i/(a-i);else if(o===2e3)p=-(a+i)/(a-i),m=-2*a*i/(a-i);else if(o===2001)p=-a/(a-i),m=-a*i/(a-i);else throw Error(`THREE.Matrix4.makePerspective(): Invalid coordinate system: `+o);return c[0]=l,c[4]=0,c[8]=d,c[12]=0,c[1]=0,c[5]=u,c[9]=f,c[13]=0,c[2]=0,c[6]=0,c[10]=p,c[14]=m,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,t,n,r,i,a,o=He,s=!1){let c=this.elements,l=2/(t-e),u=2/(n-r),d=-(t+e)/(t-e),f=-(n+r)/(n-r),p,m;if(s)p=1/(a-i),m=a/(a-i);else if(o===2e3)p=-2/(a-i),m=-(a+i)/(a-i);else if(o===2001)p=-1/(a-i),m=-i/(a-i);else throw Error(`THREE.Matrix4.makeOrthographic(): Invalid coordinate system: `+o);return c[0]=l,c[4]=0,c[8]=0,c[12]=d,c[1]=0,c[5]=u,c[9]=0,c[13]=f,c[2]=0,c[6]=0,c[10]=p,c[14]=m,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(e){let t=this.elements,n=e.elements;for(let e=0;e<16;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<16;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){let n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e[t+9]=n[9],e[t+10]=n[10],e[t+11]=n[11],e[t+12]=n[12],e[t+13]=n[13],e[t+14]=n[14],e[t+15]=n[15],e}},bn=new R,xn=new yn,Sn=new R(0,0,0),Cn=new R(1,1,1),wn=new R,Tn=new R,En=new R,Dn=new yn,On=new gt,kn=class e{constructor(t=0,n=0,r=0,i=e.DEFAULT_ORDER){this.isEuler=!0,this._x=t,this._y=n,this._z=r,this._order=i}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,n,r=this._order){return this._x=e,this._y=t,this._z=n,this._order=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,n=!0){let r=e.elements,i=r[0],a=r[4],o=r[8],s=r[1],c=r[5],l=r[9],u=r[2],d=r[6],f=r[10];switch(t){case`XYZ`:this._y=Math.asin(I(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-l,f),this._z=Math.atan2(-a,i)):(this._x=Math.atan2(d,c),this._z=0);break;case`YXZ`:this._x=Math.asin(-I(l,-1,1)),Math.abs(l)<.9999999?(this._y=Math.atan2(o,f),this._z=Math.atan2(s,c)):(this._y=Math.atan2(-u,i),this._z=0);break;case`ZXY`:this._x=Math.asin(I(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-u,f),this._z=Math.atan2(-a,c)):(this._y=0,this._z=Math.atan2(s,i));break;case`ZYX`:this._y=Math.asin(-I(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(d,f),this._z=Math.atan2(s,i)):(this._x=0,this._z=Math.atan2(-a,c));break;case`YZX`:this._z=Math.asin(I(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(-l,c),this._y=Math.atan2(-u,i)):(this._x=0,this._y=Math.atan2(o,f));break;case`XZY`:this._z=Math.asin(-I(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(d,c),this._y=Math.atan2(o,i)):(this._x=Math.atan2(-l,f),this._y=0);break;default:console.warn(`THREE.Euler: .setFromRotationMatrix() encountered an unknown order: `+t)}return this._order=t,n===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return Dn.makeRotationFromQuaternion(e),this.setFromRotationMatrix(Dn,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return On.setFromEuler(this),this.setFromQuaternion(On,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}};kn.DEFAULT_ORDER=`XYZ`;var An=class{constructor(){this.mask=1}set(e){this.mask=(1<<e|0)>>>0}enable(e){this.mask|=1<<e|0}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e|0}disable(e){this.mask&=~(1<<e|0)}disableAll(){this.mask=0}test(e){return(this.mask&e.mask)!==0}isEnabled(e){return(this.mask&(1<<e|0))!=0}},jn=0,Mn=new R,Nn=new gt,Pn=new yn,Fn=new R,In=new R,Ln=new R,Rn=new gt,zn=new R(1,0,0),Bn=new R(0,1,0),Vn=new R(0,0,1),Hn={type:`added`},Un={type:`removed`},Wn={type:`childadded`,child:null},Gn={type:`childremoved`,child:null},Kn=class e extends Ue{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,`id`,{value:jn++}),this.uuid=Je(),this.name=``,this.type=`Object3D`,this.parent=null,this.children=[],this.up=e.DEFAULT_UP.clone();let t=new R,n=new kn,r=new gt,i=new R(1,1,1);function a(){r.setFromEuler(n,!1)}function o(){n.setFromQuaternion(r,void 0,!1)}n._onChange(a),r._onChange(o),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:t},rotation:{configurable:!0,enumerable:!0,value:n},quaternion:{configurable:!0,enumerable:!0,value:r},scale:{configurable:!0,enumerable:!0,value:i},modelViewMatrix:{value:new yn},normalMatrix:{value:new z}}),this.matrix=new yn,this.matrixWorld=new yn,this.matrixAutoUpdate=e.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=e.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new An,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.userData={}}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,t){this.quaternion.setFromAxisAngle(e,t)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,t){return Nn.setFromAxisAngle(e,t),this.quaternion.multiply(Nn),this}rotateOnWorldAxis(e,t){return Nn.setFromAxisAngle(e,t),this.quaternion.premultiply(Nn),this}rotateX(e){return this.rotateOnAxis(zn,e)}rotateY(e){return this.rotateOnAxis(Bn,e)}rotateZ(e){return this.rotateOnAxis(Vn,e)}translateOnAxis(e,t){return Mn.copy(e).applyQuaternion(this.quaternion),this.position.add(Mn.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(zn,e)}translateY(e){return this.translateOnAxis(Bn,e)}translateZ(e){return this.translateOnAxis(Vn,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(Pn.copy(this.matrixWorld).invert())}lookAt(e,t,n){e.isVector3?Fn.copy(e):Fn.set(e,t,n);let r=this.parent;this.updateWorldMatrix(!0,!1),In.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?Pn.lookAt(In,Fn,this.up):Pn.lookAt(Fn,In,this.up),this.quaternion.setFromRotationMatrix(Pn),r&&(Pn.extractRotation(r.matrixWorld),Nn.setFromRotationMatrix(Pn),this.quaternion.premultiply(Nn.invert()))}add(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.add(arguments[e]);return this}return e===this?(console.error(`THREE.Object3D.add: object can't be added as a child of itself.`,e),this):(e&&e.isObject3D?(e.removeFromParent(),e.parent=this,this.children.push(e),e.dispatchEvent(Hn),Wn.child=e,this.dispatchEvent(Wn),Wn.child=null):console.error(`THREE.Object3D.add: object not an instance of THREE.Object3D.`,e),this)}remove(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.remove(arguments[e]);return this}let t=this.children.indexOf(e);return t!==-1&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent(Un),Gn.child=e,this.dispatchEvent(Gn),Gn.child=null),this}removeFromParent(){let e=this.parent;return e!==null&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),Pn.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),Pn.multiply(e.parent.matrixWorld)),e.applyMatrix4(Pn),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(Hn),Wn.child=e,this.dispatchEvent(Wn),Wn.child=null,this}getObjectById(e){return this.getObjectByProperty(`id`,e)}getObjectByName(e){return this.getObjectByProperty(`name`,e)}getObjectByProperty(e,t){if(this[e]===t)return this;for(let n=0,r=this.children.length;n<r;n++){let r=this.children[n].getObjectByProperty(e,t);if(r!==void 0)return r}}getObjectsByProperty(e,t,n=[]){this[e]===t&&n.push(this);let r=this.children;for(let i=0,a=r.length;i<a;i++)r[i].getObjectsByProperty(e,t,n);return n}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(In,e,Ln),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(In,Rn,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);let t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}traverse(e){e(this);let t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);let t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].traverseVisible(e)}traverseAncestors(e){let t=this.parent;t!==null&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale),this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,e=!0);let t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].updateMatrixWorld(e)}updateWorldMatrix(e,t){let n=this.parent;if(e===!0&&n!==null&&n.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),t===!0){let e=this.children;for(let t=0,n=e.length;t<n;t++)e[t].updateWorldMatrix(!1,!0)}}toJSON(e){let t=e===void 0||typeof e==`string`,n={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},n.metadata={version:4.7,type:`Object`,generator:`Object3D.toJSON`});let r={};r.uuid=this.uuid,r.type=this.type,this.name!==``&&(r.name=this.name),this.castShadow===!0&&(r.castShadow=!0),this.receiveShadow===!0&&(r.receiveShadow=!0),this.visible===!1&&(r.visible=!1),this.frustumCulled===!1&&(r.frustumCulled=!1),this.renderOrder!==0&&(r.renderOrder=this.renderOrder),Object.keys(this.userData).length>0&&(r.userData=this.userData),r.layers=this.layers.mask,r.matrix=this.matrix.toArray(),r.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(r.matrixAutoUpdate=!1),this.isInstancedMesh&&(r.type=`InstancedMesh`,r.count=this.count,r.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(r.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(r.type=`BatchedMesh`,r.perObjectFrustumCulled=this.perObjectFrustumCulled,r.sortObjects=this.sortObjects,r.drawRanges=this._drawRanges,r.reservedRanges=this._reservedRanges,r.geometryInfo=this._geometryInfo.map(e=>({...e,boundingBox:e.boundingBox?e.boundingBox.toJSON():void 0,boundingSphere:e.boundingSphere?e.boundingSphere.toJSON():void 0})),r.instanceInfo=this._instanceInfo.map(e=>({...e})),r.availableInstanceIds=this._availableInstanceIds.slice(),r.availableGeometryIds=this._availableGeometryIds.slice(),r.nextIndexStart=this._nextIndexStart,r.nextVertexStart=this._nextVertexStart,r.geometryCount=this._geometryCount,r.maxInstanceCount=this._maxInstanceCount,r.maxVertexCount=this._maxVertexCount,r.maxIndexCount=this._maxIndexCount,r.geometryInitialized=this._geometryInitialized,r.matricesTexture=this._matricesTexture.toJSON(e),r.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(r.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(r.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(r.boundingBox=this.boundingBox.toJSON()));function i(t,n){return t[n.uuid]===void 0&&(t[n.uuid]=n.toJSON(e)),n.uuid}if(this.isScene)this.background&&(this.background.isColor?r.background=this.background.toJSON():this.background.isTexture&&(r.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(r.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){r.geometry=i(e.geometries,this.geometry);let t=this.geometry.parameters;if(t!==void 0&&t.shapes!==void 0){let n=t.shapes;if(Array.isArray(n))for(let t=0,r=n.length;t<r;t++){let r=n[t];i(e.shapes,r)}else i(e.shapes,n)}}if(this.isSkinnedMesh&&(r.bindMode=this.bindMode,r.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(i(e.skeletons,this.skeleton),r.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){let t=[];for(let n=0,r=this.material.length;n<r;n++)t.push(i(e.materials,this.material[n]));r.material=t}else r.material=i(e.materials,this.material);if(this.children.length>0){r.children=[];for(let t=0;t<this.children.length;t++)r.children.push(this.children[t].toJSON(e).object)}if(this.animations.length>0){r.animations=[];for(let t=0;t<this.animations.length;t++){let n=this.animations[t];r.animations.push(i(e.animations,n))}}if(t){let t=a(e.geometries),r=a(e.materials),i=a(e.textures),o=a(e.images),s=a(e.shapes),c=a(e.skeletons),l=a(e.animations),u=a(e.nodes);t.length>0&&(n.geometries=t),r.length>0&&(n.materials=r),i.length>0&&(n.textures=i),o.length>0&&(n.images=o),s.length>0&&(n.shapes=s),c.length>0&&(n.skeletons=c),l.length>0&&(n.animations=l),u.length>0&&(n.nodes=u)}return n.object=r,n;function a(e){let t=[];for(let n in e){let r=e[n];delete r.metadata,t.push(r)}return t}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let t=0;t<e.children.length;t++){let n=e.children[t];this.add(n.clone())}return this}};Kn.DEFAULT_UP=new R(0,1,0),Kn.DEFAULT_MATRIX_AUTO_UPDATE=!0,Kn.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;var qn=new R,Jn=new R,Yn=new R,Xn=new R,Zn=new R,Qn=new R,$n=new R,er=new R,tr=new R,nr=new R,rr=new Bt,ir=new Bt,ar=new Bt,or=class e{constructor(e=new R,t=new R,n=new R){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,r){r.subVectors(n,t),qn.subVectors(e,t),r.cross(qn);let i=r.lengthSq();return i>0?r.multiplyScalar(1/Math.sqrt(i)):r.set(0,0,0)}static getBarycoord(e,t,n,r,i){qn.subVectors(r,t),Jn.subVectors(n,t),Yn.subVectors(e,t);let a=qn.dot(qn),o=qn.dot(Jn),s=qn.dot(Yn),c=Jn.dot(Jn),l=Jn.dot(Yn),u=a*c-o*o;if(u===0)return i.set(0,0,0),null;let d=1/u,f=(c*s-o*l)*d,p=(a*l-o*s)*d;return i.set(1-f-p,p,f)}static containsPoint(e,t,n,r){return this.getBarycoord(e,t,n,r,Xn)===null?!1:Xn.x>=0&&Xn.y>=0&&Xn.x+Xn.y<=1}static getInterpolation(e,t,n,r,i,a,o,s){return this.getBarycoord(e,t,n,r,Xn)===null?(s.x=0,s.y=0,`z`in s&&(s.z=0),`w`in s&&(s.w=0),null):(s.setScalar(0),s.addScaledVector(i,Xn.x),s.addScaledVector(a,Xn.y),s.addScaledVector(o,Xn.z),s)}static getInterpolatedAttribute(e,t,n,r,i,a){return rr.setScalar(0),ir.setScalar(0),ar.setScalar(0),rr.fromBufferAttribute(e,t),ir.fromBufferAttribute(e,n),ar.fromBufferAttribute(e,r),a.setScalar(0),a.addScaledVector(rr,i.x),a.addScaledVector(ir,i.y),a.addScaledVector(ar,i.z),a}static isFrontFacing(e,t,n,r){return qn.subVectors(n,t),Jn.subVectors(e,t),qn.cross(Jn).dot(r)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,r){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[r]),this}setFromAttributeAndIndices(e,t,n,r){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,r),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return qn.subVectors(this.c,this.b),Jn.subVectors(this.a,this.b),qn.cross(Jn).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return e.getNormal(this.a,this.b,this.c,t)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,n){return e.getBarycoord(t,this.a,this.b,this.c,n)}getInterpolation(t,n,r,i,a){return e.getInterpolation(t,this.a,this.b,this.c,n,r,i,a)}containsPoint(t){return e.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return e.isFrontFacing(this.a,this.b,this.c,t)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){let n=this.a,r=this.b,i=this.c,a,o;Zn.subVectors(r,n),Qn.subVectors(i,n),er.subVectors(e,n);let s=Zn.dot(er),c=Qn.dot(er);if(s<=0&&c<=0)return t.copy(n);tr.subVectors(e,r);let l=Zn.dot(tr),u=Qn.dot(tr);if(l>=0&&u<=l)return t.copy(r);let d=s*u-l*c;if(d<=0&&s>=0&&l<=0)return a=s/(s-l),t.copy(n).addScaledVector(Zn,a);nr.subVectors(e,i);let f=Zn.dot(nr),p=Qn.dot(nr);if(p>=0&&f<=p)return t.copy(i);let m=f*c-s*p;if(m<=0&&c>=0&&p<=0)return o=c/(c-p),t.copy(n).addScaledVector(Qn,o);let h=l*p-f*u;if(h<=0&&u-l>=0&&f-p>=0)return $n.subVectors(i,r),o=(u-l)/(u-l+(f-p)),t.copy(r).addScaledVector($n,o);let g=1/(h+m+d);return a=m*g,o=d*g,t.copy(n).addScaledVector(Zn,a).addScaledVector(Qn,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}},sr={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},cr={h:0,s:0,l:0},lr={h:0,s:0,l:0};function ur(e,t,n){return n<0&&(n+=1),n>1&&--n,n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*6*(2/3-n):e}var B=class{constructor(e,t,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,n)}set(e,t,n){if(t===void 0&&n===void 0){let t=e;t&&t.isColor?this.copy(t):typeof t==`number`?this.setHex(t):typeof t==`string`&&this.setStyle(t)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=Ie){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,kt.colorSpaceToWorking(this,t),this}setRGB(e,t,n,r=kt.workingColorSpace){return this.r=e,this.g=t,this.b=n,kt.colorSpaceToWorking(this,r),this}setHSL(e,t,n,r=kt.workingColorSpace){if(e=Ye(e,1),t=I(t,0,1),n=I(n,0,1),t===0)this.r=this.g=this.b=n;else{let r=n<=.5?n*(1+t):n+t-n*t,i=2*n-r;this.r=ur(i,r,e+1/3),this.g=ur(i,r,e),this.b=ur(i,r,e-1/3)}return kt.colorSpaceToWorking(this,r),this}setStyle(e,t=Ie){function n(t){t!==void 0&&parseFloat(t)<1&&console.warn(`THREE.Color: Alpha component of `+e+` will be ignored.`)}let r;if(r=/^(\w+)\(([^\)]*)\)/.exec(e)){let i,a=r[1],o=r[2];switch(a){case`rgb`:case`rgba`:if(i=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setRGB(Math.min(255,parseInt(i[1],10))/255,Math.min(255,parseInt(i[2],10))/255,Math.min(255,parseInt(i[3],10))/255,t);if(i=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setRGB(Math.min(100,parseInt(i[1],10))/100,Math.min(100,parseInt(i[2],10))/100,Math.min(100,parseInt(i[3],10))/100,t);break;case`hsl`:case`hsla`:if(i=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setHSL(parseFloat(i[1])/360,parseFloat(i[2])/100,parseFloat(i[3])/100,t);break;default:console.warn(`THREE.Color: Unknown color model `+e)}}else if(r=/^\#([A-Fa-f\d]+)$/.exec(e)){let n=r[1],i=n.length;if(i===3)return this.setRGB(parseInt(n.charAt(0),16)/15,parseInt(n.charAt(1),16)/15,parseInt(n.charAt(2),16)/15,t);if(i===6)return this.setHex(parseInt(n,16),t);console.warn(`THREE.Color: Invalid hex color `+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=Ie){let n=sr[e.toLowerCase()];return n===void 0?console.warn(`THREE.Color: Unknown color `+e):this.setHex(n,t),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=At(e.r),this.g=At(e.g),this.b=At(e.b),this}copyLinearToSRGB(e){return this.r=jt(e.r),this.g=jt(e.g),this.b=jt(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Ie){return kt.workingToColorSpace(dr.copy(this),e),Math.round(I(dr.r*255,0,255))*65536+Math.round(I(dr.g*255,0,255))*256+Math.round(I(dr.b*255,0,255))}getHexString(e=Ie){return(`000000`+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=kt.workingColorSpace){kt.workingToColorSpace(dr.copy(this),t);let n=dr.r,r=dr.g,i=dr.b,a=Math.max(n,r,i),o=Math.min(n,r,i),s,c,l=(o+a)/2;if(o===a)s=0,c=0;else{let e=a-o;switch(c=l<=.5?e/(a+o):e/(2-a-o),a){case n:s=(r-i)/e+(r<i?6:0);break;case r:s=(i-n)/e+2;break;case i:s=(n-r)/e+4;break}s/=6}return e.h=s,e.s=c,e.l=l,e}getRGB(e,t=kt.workingColorSpace){return kt.workingToColorSpace(dr.copy(this),t),e.r=dr.r,e.g=dr.g,e.b=dr.b,e}getStyle(e=Ie){kt.workingToColorSpace(dr.copy(this),e);let t=dr.r,n=dr.g,r=dr.b;return e===`srgb`?`rgb(${Math.round(t*255)},${Math.round(n*255)},${Math.round(r*255)})`:`color(${e} ${t.toFixed(3)} ${n.toFixed(3)} ${r.toFixed(3)})`}offsetHSL(e,t,n){return this.getHSL(cr),this.setHSL(cr.h+e,cr.s+t,cr.l+n)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,t){return this.r=e.r+t.r,this.g=e.g+t.g,this.b=e.b+t.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,t){return this.r+=(e.r-this.r)*t,this.g+=(e.g-this.g)*t,this.b+=(e.b-this.b)*t,this}lerpColors(e,t,n){return this.r=e.r+(t.r-e.r)*n,this.g=e.g+(t.g-e.g)*n,this.b=e.b+(t.b-e.b)*n,this}lerpHSL(e,t){this.getHSL(cr),e.getHSL(lr);let n=Qe(cr.h,lr.h,t),r=Qe(cr.s,lr.s,t),i=Qe(cr.l,lr.l,t);return this.setHSL(n,r,i),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){let t=this.r,n=this.g,r=this.b,i=e.elements;return this.r=i[0]*t+i[3]*n+i[6]*r,this.g=i[1]*t+i[4]*n+i[7]*r,this.b=i[2]*t+i[5]*n+i[8]*r,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}},dr=new B;B.NAMES=sr;var fr=0,pr=class extends Ue{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,`id`,{value:fr++}),this.uuid=Je(),this.name=``,this.type=`Material`,this.blending=1,this.side=0,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=204,this.blendDst=205,this.blendEquation=100,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new B(0,0,0),this.blendAlpha=0,this.depthFunc=3,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=519,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=Be,this.stencilZFail=Be,this.stencilZPass=Be,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(let t in e){let n=e[t];if(n===void 0){console.warn(`THREE.Material: parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){console.warn(`THREE.Material: '${t}' is not a property of THREE.${this.type}.`);continue}r&&r.isColor?r.set(n):r&&r.isVector3&&n&&n.isVector3?r.copy(n):this[t]=n}}toJSON(e){let t=e===void 0||typeof e==`string`;t&&(e={textures:{},images:{}});let n={metadata:{version:4.7,type:`Material`,generator:`Material.toJSON`}};n.uuid=this.uuid,n.type=this.type,this.name!==``&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),this.roughness!==void 0&&(n.roughness=this.roughness),this.metalness!==void 0&&(n.metalness=this.metalness),this.sheen!==void 0&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(n.shininess=this.shininess),this.clearcoat!==void 0&&(n.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(n.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(n.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(n.dispersion=this.dispersion),this.iridescence!==void 0&&(n.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(n.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(n.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(n.combine=this.combine)),this.envMapRotation!==void 0&&(n.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(n.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(n.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(n.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(n.size=this.size),this.shadowSide!==null&&(n.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),this.blending!==1&&(n.blending=this.blending),this.side!==0&&(n.side=this.side),this.vertexColors===!0&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),this.transparent===!0&&(n.transparent=!0),this.blendSrc!==204&&(n.blendSrc=this.blendSrc),this.blendDst!==205&&(n.blendDst=this.blendDst),this.blendEquation!==100&&(n.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(n.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(n.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(n.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(n.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(n.blendAlpha=this.blendAlpha),this.depthFunc!==3&&(n.depthFunc=this.depthFunc),this.depthTest===!1&&(n.depthTest=this.depthTest),this.depthWrite===!1&&(n.depthWrite=this.depthWrite),this.colorWrite===!1&&(n.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(n.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==519&&(n.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(n.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==7680&&(n.stencilFail=this.stencilFail),this.stencilZFail!==7680&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==7680&&(n.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(n.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(n.rotation=this.rotation),this.polygonOffset===!0&&(n.polygonOffset=!0),this.polygonOffsetFactor!==0&&(n.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(n.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(n.linewidth=this.linewidth),this.dashSize!==void 0&&(n.dashSize=this.dashSize),this.gapSize!==void 0&&(n.gapSize=this.gapSize),this.scale!==void 0&&(n.scale=this.scale),this.dithering===!0&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),this.alphaHash===!0&&(n.alphaHash=!0),this.alphaToCoverage===!0&&(n.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(n.premultipliedAlpha=!0),this.forceSinglePass===!0&&(n.forceSinglePass=!0),this.wireframe===!0&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!==`round`&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!==`round`&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(n.flatShading=!0),this.visible===!1&&(n.visible=!1),this.toneMapped===!1&&(n.toneMapped=!1),this.fog===!1&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData);function r(e){let t=[];for(let n in e){let r=e[n];delete r.metadata,t.push(r)}return t}if(t){let t=r(e.textures),i=r(e.images);t.length>0&&(n.textures=t),i.length>0&&(n.images=i)}return n}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;let t=e.clippingPlanes,n=null;if(t!==null){let e=t.length;n=Array(e);for(let r=0;r!==e;++r)n[r]=t[r].clone()}return this.clippingPlanes=n,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:`dispose`})}set needsUpdate(e){e===!0&&this.version++}},mr=class extends pr{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type=`MeshBasicMaterial`,this.color=new B(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new kn,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap=`round`,this.wireframeLinejoin=`round`,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}},hr=new R,gr=new L,_r=0,V=class{constructor(e,t,n=!1){if(Array.isArray(e))throw TypeError(`THREE.BufferAttribute: array should be a Typed Array.`);this.isBufferAttribute=!0,Object.defineProperty(this,`id`,{value:_r++}),this.name=``,this.array=e,this.itemSize=t,this.count=e===void 0?0:e.length/t,this.normalized=n,this.usage=Ve,this.updateRanges=[],this.gpuType=h,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,n){e*=this.itemSize,n*=t.itemSize;for(let r=0,i=this.itemSize;r<i;r++)this.array[e+r]=t.array[n+r];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let t=0,n=this.count;t<n;t++)gr.fromBufferAttribute(this,t),gr.applyMatrix3(e),this.setXY(t,gr.x,gr.y);else if(this.itemSize===3)for(let t=0,n=this.count;t<n;t++)hr.fromBufferAttribute(this,t),hr.applyMatrix3(e),this.setXYZ(t,hr.x,hr.y,hr.z);return this}applyMatrix4(e){for(let t=0,n=this.count;t<n;t++)hr.fromBufferAttribute(this,t),hr.applyMatrix4(e),this.setXYZ(t,hr.x,hr.y,hr.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)hr.fromBufferAttribute(this,t),hr.applyNormalMatrix(e),this.setXYZ(t,hr.x,hr.y,hr.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)hr.fromBufferAttribute(this,t),hr.transformDirection(e),this.setXYZ(t,hr.x,hr.y,hr.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let n=this.array[e*this.itemSize+t];return this.normalized&&(n=pt(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=mt(n,this.array)),this.array[e*this.itemSize+t]=n,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=pt(t,this.array)),t}setX(e,t){return this.normalized&&(t=mt(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=pt(t,this.array)),t}setY(e,t){return this.normalized&&(t=mt(t,this.array)),this.array[e*this.itemSize+1]=t,this}getZ(e){let t=this.array[e*this.itemSize+2];return this.normalized&&(t=pt(t,this.array)),t}setZ(e,t){return this.normalized&&(t=mt(t,this.array)),this.array[e*this.itemSize+2]=t,this}getW(e){let t=this.array[e*this.itemSize+3];return this.normalized&&(t=pt(t,this.array)),t}setW(e,t){return this.normalized&&(t=mt(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=mt(t,this.array),n=mt(n,this.array)),this.array[e+0]=t,this.array[e+1]=n,this}setXYZ(e,t,n,r){return e*=this.itemSize,this.normalized&&(t=mt(t,this.array),n=mt(n,this.array),r=mt(r,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=r,this}setXYZW(e,t,n,r,i){return e*=this.itemSize,this.normalized&&(t=mt(t,this.array),n=mt(n,this.array),r=mt(r,this.array),i=mt(i,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=r,this.array[e+3]=i,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){let e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return this.name!==``&&(e.name=this.name),this.usage!==35044&&(e.usage=this.usage),e}},vr=class extends V{constructor(e,t,n){super(new Uint16Array(e),t,n)}},yr=class extends V{constructor(e,t,n){super(new Uint32Array(e),t,n)}},br=class extends V{constructor(e,t,n){super(new Float32Array(e),t,n)}},xr=0,Sr=new yn,Cr=new Kn,wr=new R,Tr=new Gt,Er=new Gt,Dr=new R,Or=class e extends Ue{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,`id`,{value:xr++}),this.uuid=Je(),this.name=``,this.type=`BufferGeometry`,this.index=null,this.indirect=null,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(bt(e)?yr:vr)(e,1):this.index=e,this}setIndirect(e){return this.indirect=e,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,t,n=0){this.groups.push({start:e,count:t,materialIndex:n})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){let t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);let n=this.attributes.normal;if(n!==void 0){let t=new z().getNormalMatrix(e);n.applyNormalMatrix(t),n.needsUpdate=!0}let r=this.attributes.tangent;return r!==void 0&&(r.transformDirection(e),r.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(e){return Sr.makeRotationFromQuaternion(e),this.applyMatrix4(Sr),this}rotateX(e){return Sr.makeRotationX(e),this.applyMatrix4(Sr),this}rotateY(e){return Sr.makeRotationY(e),this.applyMatrix4(Sr),this}rotateZ(e){return Sr.makeRotationZ(e),this.applyMatrix4(Sr),this}translate(e,t,n){return Sr.makeTranslation(e,t,n),this.applyMatrix4(Sr),this}scale(e,t,n){return Sr.makeScale(e,t,n),this.applyMatrix4(Sr),this}lookAt(e){return Cr.lookAt(e),Cr.updateMatrix(),this.applyMatrix4(Cr.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(wr).negate(),this.translate(wr.x,wr.y,wr.z),this}setFromPoints(e){let t=this.getAttribute(`position`);if(t===void 0){let t=[];for(let n=0,r=e.length;n<r;n++){let r=e[n];t.push(r.x,r.y,r.z||0)}this.setAttribute(`position`,new br(t,3))}else{let n=Math.min(e.length,t.count);for(let r=0;r<n;r++){let n=e[r];t.setXYZ(r,n.x,n.y,n.z||0)}e.length>t.count&&console.warn(`THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.`),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Gt);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error(`THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.`,this),this.boundingBox.set(new R(-1/0,-1/0,-1/0),new R(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e<n;e++){let n=t[e];Tr.setFromBufferAttribute(n),this.morphTargetsRelative?(Dr.addVectors(this.boundingBox.min,Tr.min),this.boundingBox.expandByPoint(Dr),Dr.addVectors(this.boundingBox.max,Tr.max),this.boundingBox.expandByPoint(Dr)):(this.boundingBox.expandByPoint(Tr.min),this.boundingBox.expandByPoint(Tr.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&console.error(`THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.`,this)}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new un);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error(`THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.`,this),this.boundingSphere.set(new R,1/0);return}if(e){let n=this.boundingSphere.center;if(Tr.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e<n;e++){let n=t[e];Er.setFromBufferAttribute(n),this.morphTargetsRelative?(Dr.addVectors(Tr.min,Er.min),Tr.expandByPoint(Dr),Dr.addVectors(Tr.max,Er.max),Tr.expandByPoint(Dr)):(Tr.expandByPoint(Er.min),Tr.expandByPoint(Er.max))}Tr.getCenter(n);let r=0;for(let t=0,i=e.count;t<i;t++)Dr.fromBufferAttribute(e,t),r=Math.max(r,n.distanceToSquared(Dr));if(t)for(let i=0,a=t.length;i<a;i++){let a=t[i],o=this.morphTargetsRelative;for(let t=0,i=a.count;t<i;t++)Dr.fromBufferAttribute(a,t),o&&(wr.fromBufferAttribute(e,t),Dr.add(wr)),r=Math.max(r,n.distanceToSquared(Dr))}this.boundingSphere.radius=Math.sqrt(r),isNaN(this.boundingSphere.radius)&&console.error(`THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.`,this)}}computeTangents(){let e=this.index,t=this.attributes;if(e===null||t.position===void 0||t.normal===void 0||t.uv===void 0){console.error(`THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)`);return}let n=t.position,r=t.normal,i=t.uv;this.hasAttribute(`tangent`)===!1&&this.setAttribute(`tangent`,new V(new Float32Array(4*n.count),4));let a=this.getAttribute(`tangent`),o=[],s=[];for(let e=0;e<n.count;e++)o[e]=new R,s[e]=new R;let c=new R,l=new R,u=new R,d=new L,f=new L,p=new L,m=new R,h=new R;function g(e,t,r){c.fromBufferAttribute(n,e),l.fromBufferAttribute(n,t),u.fromBufferAttribute(n,r),d.fromBufferAttribute(i,e),f.fromBufferAttribute(i,t),p.fromBufferAttribute(i,r),l.sub(c),u.sub(c),f.sub(d),p.sub(d);let a=1/(f.x*p.y-p.x*f.y);isFinite(a)&&(m.copy(l).multiplyScalar(p.y).addScaledVector(u,-f.y).multiplyScalar(a),h.copy(u).multiplyScalar(f.x).addScaledVector(l,-p.x).multiplyScalar(a),o[e].add(m),o[t].add(m),o[r].add(m),s[e].add(h),s[t].add(h),s[r].add(h))}let _=this.groups;_.length===0&&(_=[{start:0,count:e.count}]);for(let t=0,n=_.length;t<n;++t){let n=_[t],r=n.start,i=n.count;for(let t=r,n=r+i;t<n;t+=3)g(e.getX(t+0),e.getX(t+1),e.getX(t+2))}let v=new R,y=new R,b=new R,x=new R;function S(e){b.fromBufferAttribute(r,e),x.copy(b);let t=o[e];v.copy(t),v.sub(b.multiplyScalar(b.dot(t))).normalize(),y.crossVectors(x,t);let n=y.dot(s[e])<0?-1:1;a.setXYZW(e,v.x,v.y,v.z,n)}for(let t=0,n=_.length;t<n;++t){let n=_[t],r=n.start,i=n.count;for(let t=r,n=r+i;t<n;t+=3)S(e.getX(t+0)),S(e.getX(t+1)),S(e.getX(t+2))}}computeVertexNormals(){let e=this.index,t=this.getAttribute(`position`);if(t!==void 0){let n=this.getAttribute(`normal`);if(n===void 0)n=new V(new Float32Array(t.count*3),3),this.setAttribute(`normal`,n);else for(let e=0,t=n.count;e<t;e++)n.setXYZ(e,0,0,0);let r=new R,i=new R,a=new R,o=new R,s=new R,c=new R,l=new R,u=new R;if(e)for(let d=0,f=e.count;d<f;d+=3){let f=e.getX(d+0),p=e.getX(d+1),m=e.getX(d+2);r.fromBufferAttribute(t,f),i.fromBufferAttribute(t,p),a.fromBufferAttribute(t,m),l.subVectors(a,i),u.subVectors(r,i),l.cross(u),o.fromBufferAttribute(n,f),s.fromBufferAttribute(n,p),c.fromBufferAttribute(n,m),o.add(l),s.add(l),c.add(l),n.setXYZ(f,o.x,o.y,o.z),n.setXYZ(p,s.x,s.y,s.z),n.setXYZ(m,c.x,c.y,c.z)}else for(let e=0,o=t.count;e<o;e+=3)r.fromBufferAttribute(t,e+0),i.fromBufferAttribute(t,e+1),a.fromBufferAttribute(t,e+2),l.subVectors(a,i),u.subVectors(r,i),l.cross(u),n.setXYZ(e+0,l.x,l.y,l.z),n.setXYZ(e+1,l.x,l.y,l.z),n.setXYZ(e+2,l.x,l.y,l.z);this.normalizeNormals(),n.needsUpdate=!0}}normalizeNormals(){let e=this.attributes.normal;for(let t=0,n=e.count;t<n;t++)Dr.fromBufferAttribute(e,t),Dr.normalize(),e.setXYZ(t,Dr.x,Dr.y,Dr.z)}toNonIndexed(){function t(e,t){let n=e.array,r=e.itemSize,i=e.normalized,a=new n.constructor(t.length*r),o=0,s=0;for(let i=0,c=t.length;i<c;i++){o=e.isInterleavedBufferAttribute?t[i]*e.data.stride+e.offset:t[i]*r;for(let e=0;e<r;e++)a[s++]=n[o++]}return new V(a,r,i)}if(this.index===null)return console.warn(`THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.`),this;let n=new e,r=this.index.array,i=this.attributes;for(let e in i){let a=i[e],o=t(a,r);n.setAttribute(e,o)}let a=this.morphAttributes;for(let e in a){let i=[],o=a[e];for(let e=0,n=o.length;e<n;e++){let n=o[e],a=t(n,r);i.push(a)}n.morphAttributes[e]=i}n.morphTargetsRelative=this.morphTargetsRelative;let o=this.groups;for(let e=0,t=o.length;e<t;e++){let t=o[e];n.addGroup(t.start,t.count,t.materialIndex)}return n}toJSON(){let e={metadata:{version:4.7,type:`BufferGeometry`,generator:`BufferGeometry.toJSON`}};if(e.uuid=this.uuid,e.type=this.type,this.name!==``&&(e.name=this.name),Object.keys(this.userData).length>0&&(e.userData=this.userData),this.parameters!==void 0){let t=this.parameters;for(let n in t)t[n]!==void 0&&(e[n]=t[n]);return e}e.data={attributes:{}};let t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});let n=this.attributes;for(let t in n){let r=n[t];e.data.attributes[t]=r.toJSON(e.data)}let r={},i=!1;for(let t in this.morphAttributes){let n=this.morphAttributes[t],a=[];for(let t=0,r=n.length;t<r;t++){let r=n[t];a.push(r.toJSON(e.data))}a.length>0&&(r[t]=a,i=!0)}i&&(e.data.morphAttributes=r,e.data.morphTargetsRelative=this.morphTargetsRelative);let a=this.groups;a.length>0&&(e.data.groups=JSON.parse(JSON.stringify(a)));let o=this.boundingSphere;return o!==null&&(e.data.boundingSphere=o.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;let t={};this.name=e.name;let n=e.index;n!==null&&this.setIndex(n.clone());let r=e.attributes;for(let e in r){let n=r[e];this.setAttribute(e,n.clone(t))}let i=e.morphAttributes;for(let e in i){let n=[],r=i[e];for(let e=0,i=r.length;e<i;e++)n.push(r[e].clone(t));this.morphAttributes[e]=n}this.morphTargetsRelative=e.morphTargetsRelative;let a=e.groups;for(let e=0,t=a.length;e<t;e++){let t=a[e];this.addGroup(t.start,t.count,t.materialIndex)}let o=e.boundingBox;o!==null&&(this.boundingBox=o.clone());let s=e.boundingSphere;return s!==null&&(this.boundingSphere=s.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this}dispose(){this.dispatchEvent({type:`dispose`})}},kr=new yn,Ar=new vn,jr=new un,Mr=new R,Nr=new R,Pr=new R,Fr=new R,Ir=new R,Lr=new R,Rr=new R,zr=new R,H=class extends Kn{constructor(e=new Or,t=new mr){super(),this.isMesh=!0,this.type=`Mesh`,this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),e.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),e.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){let e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){let n=e[t[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e<t;e++){let t=n[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[t]=e}}}}getVertexPosition(e,t){let n=this.geometry,r=n.attributes.position,i=n.morphAttributes.position,a=n.morphTargetsRelative;t.fromBufferAttribute(r,e);let o=this.morphTargetInfluences;if(i&&o){Lr.set(0,0,0);for(let n=0,r=i.length;n<r;n++){let r=o[n],s=i[n];r!==0&&(Ir.fromBufferAttribute(s,e),a?Lr.addScaledVector(Ir,r):Lr.addScaledVector(Ir.sub(t),r))}t.add(Lr)}return t}raycast(e,t){let n=this.geometry,r=this.material,i=this.matrixWorld;r!==void 0&&(n.boundingSphere===null&&n.computeBoundingSphere(),jr.copy(n.boundingSphere),jr.applyMatrix4(i),Ar.copy(e.ray).recast(e.near),!(jr.containsPoint(Ar.origin)===!1&&(Ar.intersectSphere(jr,Mr)===null||Ar.origin.distanceToSquared(Mr)>(e.far-e.near)**2))&&(kr.copy(i).invert(),Ar.copy(e.ray).applyMatrix4(kr),!(n.boundingBox!==null&&Ar.intersectsBox(n.boundingBox)===!1)&&this._computeIntersections(e,t,Ar)))}_computeIntersections(e,t,n){let r,i=this.geometry,a=this.material,o=i.index,s=i.attributes.position,c=i.attributes.uv,l=i.attributes.uv1,u=i.attributes.normal,d=i.groups,f=i.drawRange;if(o!==null)if(Array.isArray(a))for(let i=0,s=d.length;i<s;i++){let s=d[i],p=a[s.materialIndex],m=Math.max(s.start,f.start),h=Math.min(o.count,Math.min(s.start+s.count,f.start+f.count));for(let i=m,a=h;i<a;i+=3){let a=o.getX(i),d=o.getX(i+1),f=o.getX(i+2);r=Vr(this,p,e,n,c,l,u,a,d,f),r&&(r.faceIndex=Math.floor(i/3),r.face.materialIndex=s.materialIndex,t.push(r))}}else{let i=Math.max(0,f.start),s=Math.min(o.count,f.start+f.count);for(let d=i,f=s;d<f;d+=3){let i=o.getX(d),s=o.getX(d+1),f=o.getX(d+2);r=Vr(this,a,e,n,c,l,u,i,s,f),r&&(r.faceIndex=Math.floor(d/3),t.push(r))}}else if(s!==void 0)if(Array.isArray(a))for(let i=0,o=d.length;i<o;i++){let o=d[i],p=a[o.materialIndex],m=Math.max(o.start,f.start),h=Math.min(s.count,Math.min(o.start+o.count,f.start+f.count));for(let i=m,a=h;i<a;i+=3){let a=i,s=i+1,d=i+2;r=Vr(this,p,e,n,c,l,u,a,s,d),r&&(r.faceIndex=Math.floor(i/3),r.face.materialIndex=o.materialIndex,t.push(r))}}else{let i=Math.max(0,f.start),o=Math.min(s.count,f.start+f.count);for(let s=i,d=o;s<d;s+=3){let i=s,o=s+1,d=s+2;r=Vr(this,a,e,n,c,l,u,i,o,d),r&&(r.faceIndex=Math.floor(s/3),t.push(r))}}}};function Br(e,t,n,r,i,a,o,s){let c;if(c=t.side===1?r.intersectTriangle(o,a,i,!0,s):r.intersectTriangle(i,a,o,t.side===0,s),c===null)return null;zr.copy(s),zr.applyMatrix4(e.matrixWorld);let l=n.ray.origin.distanceTo(zr);return l<n.near||l>n.far?null:{distance:l,point:zr.clone(),object:e}}function Vr(e,t,n,r,i,a,o,s,c,l){e.getVertexPosition(s,Nr),e.getVertexPosition(c,Pr),e.getVertexPosition(l,Fr);let u=Br(e,t,n,r,Nr,Pr,Fr,Rr);if(u){let e=new R;or.getBarycoord(Rr,Nr,Pr,Fr,e),i&&(u.uv=or.getInterpolatedAttribute(i,s,c,l,e,new L)),a&&(u.uv1=or.getInterpolatedAttribute(a,s,c,l,e,new L)),o&&(u.normal=or.getInterpolatedAttribute(o,s,c,l,e,new R),u.normal.dot(r.direction)>0&&u.normal.multiplyScalar(-1));let t={a:s,b:c,c:l,normal:new R,materialIndex:0};or.getNormal(Nr,Pr,Fr,t.normal),u.face=t,u.barycoord=e}return u}var Hr=class e extends Or{constructor(e=1,t=1,n=1,r=1,i=1,a=1){super(),this.type=`BoxGeometry`,this.parameters={width:e,height:t,depth:n,widthSegments:r,heightSegments:i,depthSegments:a};let o=this;r=Math.floor(r),i=Math.floor(i),a=Math.floor(a);let s=[],c=[],l=[],u=[],d=0,f=0;p(`z`,`y`,`x`,-1,-1,n,t,e,a,i,0),p(`z`,`y`,`x`,1,-1,n,t,-e,a,i,1),p(`x`,`z`,`y`,1,1,e,n,t,r,a,2),p(`x`,`z`,`y`,1,-1,e,n,-t,r,a,3),p(`x`,`y`,`z`,1,-1,e,t,n,r,i,4),p(`x`,`y`,`z`,-1,-1,e,t,-n,r,i,5),this.setIndex(s),this.setAttribute(`position`,new br(c,3)),this.setAttribute(`normal`,new br(l,3)),this.setAttribute(`uv`,new br(u,2));function p(e,t,n,r,i,a,p,m,h,g,_){let v=a/h,y=p/g,b=a/2,x=p/2,S=m/2,C=h+1,w=g+1,T=0,E=0,D=new R;for(let a=0;a<w;a++){let o=a*y-x;for(let s=0;s<C;s++)D[e]=(s*v-b)*r,D[t]=o*i,D[n]=S,c.push(D.x,D.y,D.z),D[e]=0,D[t]=0,D[n]=m>0?1:-1,l.push(D.x,D.y,D.z),u.push(s/h),u.push(1-a/g),T+=1}for(let e=0;e<g;e++)for(let t=0;t<h;t++){let n=d+t+C*e,r=d+t+C*(e+1),i=d+(t+1)+C*(e+1),a=d+(t+1)+C*e;s.push(n,r,a),s.push(r,i,a),E+=6}o.addGroup(f,E,_),f+=E,d+=T}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(t){return new e(t.width,t.height,t.depth,t.widthSegments,t.heightSegments,t.depthSegments)}};function Ur(e){let t={};for(let n in e){t[n]={};for(let r in e[n]){let i=e[n][r];i&&(i.isColor||i.isMatrix3||i.isMatrix4||i.isVector2||i.isVector3||i.isVector4||i.isTexture||i.isQuaternion)?i.isRenderTargetTexture?(console.warn(`UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().`),t[n][r]=null):t[n][r]=i.clone():Array.isArray(i)?t[n][r]=i.slice():t[n][r]=i}}return t}function Wr(e){let t={};for(let n=0;n<e.length;n++){let r=Ur(e[n]);for(let e in r)t[e]=r[e]}return t}function Gr(e){let t=[];for(let n=0;n<e.length;n++)t.push(e[n].clone());return t}function Kr(e){let t=e.getRenderTarget();return t===null?e.outputColorSpace:t.isXRRenderTarget===!0?t.texture.colorSpace:kt.workingColorSpace}var qr={clone:Ur,merge:Wr},Jr=`void main() {
1
+ (function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin===`use-credentials`?t.credentials=`include`:e.crossOrigin===`anonymous`?t.credentials=`omit`:t.credentials=`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var e=1e3,t=1001,n=1002,r=1003,i=1004,a=1005,o=1006,s=1007,c=1008,l=1009,u=1010,d=1011,f=1012,p=1013,m=1014,h=1015,g=1016,_=1017,v=1018,y=1020,b=35902,x=35899,S=1021,C=1022,w=1023,T=1026,E=1027,D=1028,ee=1029,O=1030,k=1031,te=1033,ne=33776,A=33777,re=33778,ie=33779,j=35840,ae=35841,oe=35842,se=35843,ce=36196,le=37492,ue=37496,de=37808,fe=37809,pe=37810,me=37811,he=37812,ge=37813,_e=37814,ve=37815,M=37816,ye=37817,be=37818,xe=37819,N=37820,Se=37821,P=36492,F=36494,Ce=36495,we=36283,Te=36284,Ee=36285,De=36286,Oe=2300,ke=2301,Ae=2302,je=2400,Me=2401,Ne=2402,Pe=3200,Fe=3201,Ie=`srgb`,Le=`srgb-linear`,Re=`linear`,ze=`srgb`,Be=7680,Ve=35044,He=2e3,Ue=class{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});let n=this._listeners;n[e]===void 0&&(n[e]=[]),n[e].indexOf(t)===-1&&n[e].push(t)}hasEventListener(e,t){let n=this._listeners;return n===void 0?!1:n[e]!==void 0&&n[e].indexOf(t)!==-1}removeEventListener(e,t){let n=this._listeners;if(n===void 0)return;let r=n[e];if(r!==void 0){let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}dispatchEvent(e){let t=this._listeners;if(t===void 0)return;let n=t[e.type];if(n!==void 0){e.target=this;let t=n.slice(0);for(let n=0,r=t.length;n<r;n++)t[n].call(this,e);e.target=null}}},We=`00.01.02.03.04.05.06.07.08.09.0a.0b.0c.0d.0e.0f.10.11.12.13.14.15.16.17.18.19.1a.1b.1c.1d.1e.1f.20.21.22.23.24.25.26.27.28.29.2a.2b.2c.2d.2e.2f.30.31.32.33.34.35.36.37.38.39.3a.3b.3c.3d.3e.3f.40.41.42.43.44.45.46.47.48.49.4a.4b.4c.4d.4e.4f.50.51.52.53.54.55.56.57.58.59.5a.5b.5c.5d.5e.5f.60.61.62.63.64.65.66.67.68.69.6a.6b.6c.6d.6e.6f.70.71.72.73.74.75.76.77.78.79.7a.7b.7c.7d.7e.7f.80.81.82.83.84.85.86.87.88.89.8a.8b.8c.8d.8e.8f.90.91.92.93.94.95.96.97.98.99.9a.9b.9c.9d.9e.9f.a0.a1.a2.a3.a4.a5.a6.a7.a8.a9.aa.ab.ac.ad.ae.af.b0.b1.b2.b3.b4.b5.b6.b7.b8.b9.ba.bb.bc.bd.be.bf.c0.c1.c2.c3.c4.c5.c6.c7.c8.c9.ca.cb.cc.cd.ce.cf.d0.d1.d2.d3.d4.d5.d6.d7.d8.d9.da.db.dc.dd.de.df.e0.e1.e2.e3.e4.e5.e6.e7.e8.e9.ea.eb.ec.ed.ee.ef.f0.f1.f2.f3.f4.f5.f6.f7.f8.f9.fa.fb.fc.fd.fe.ff`.split(`.`),Ge=1234567,Ke=Math.PI/180,qe=180/Math.PI;function Je(){let e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,n=Math.random()*4294967295|0,r=Math.random()*4294967295|0;return(We[e&255]+We[e>>8&255]+We[e>>16&255]+We[e>>24&255]+`-`+We[t&255]+We[t>>8&255]+`-`+We[t>>16&15|64]+We[t>>24&255]+`-`+We[n&63|128]+We[n>>8&255]+`-`+We[n>>16&255]+We[n>>24&255]+We[r&255]+We[r>>8&255]+We[r>>16&255]+We[r>>24&255]).toLowerCase()}function I(e,t,n){return Math.max(t,Math.min(n,e))}function Ye(e,t){return(e%t+t)%t}function Xe(e,t,n,r,i){return r+(e-t)*(i-r)/(n-t)}function Ze(e,t,n){return e===t?0:(n-e)/(t-e)}function Qe(e,t,n){return(1-n)*e+n*t}function $e(e,t,n,r){return Qe(e,t,1-Math.exp(-n*r))}function et(e,t=1){return t-Math.abs(Ye(e,t*2)-t)}function tt(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t),e*e*(3-2*e))}function nt(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t),e*e*e*(e*(e*6-15)+10))}function rt(e,t){return e+Math.floor(Math.random()*(t-e+1))}function it(e,t){return e+Math.random()*(t-e)}function at(e){return e*(.5-Math.random())}function ot(e){e!==void 0&&(Ge=e);let t=Ge+=1831565813;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}function st(e){return e*Ke}function ct(e){return e*qe}function lt(e){return(e&e-1)==0&&e!==0}function ut(e){return 2**Math.ceil(Math.log(e)/Math.LN2)}function dt(e){return 2**Math.floor(Math.log(e)/Math.LN2)}function ft(e,t,n,r,i){let a=Math.cos,o=Math.sin,s=a(n/2),c=o(n/2),l=a((t+r)/2),u=o((t+r)/2),d=a((t-r)/2),f=o((t-r)/2),p=a((r-t)/2),m=o((r-t)/2);switch(i){case`XYX`:e.set(s*u,c*d,c*f,s*l);break;case`YZY`:e.set(c*f,s*u,c*d,s*l);break;case`ZXZ`:e.set(c*d,c*f,s*u,s*l);break;case`XZX`:e.set(s*u,c*m,c*p,s*l);break;case`YXY`:e.set(c*p,s*u,c*m,s*l);break;case`ZYZ`:e.set(c*m,c*p,s*u,s*l);break;default:console.warn(`THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: `+i)}}function pt(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return e/4294967295;case Uint16Array:return e/65535;case Uint8Array:return e/255;case Int32Array:return Math.max(e/2147483647,-1);case Int16Array:return Math.max(e/32767,-1);case Int8Array:return Math.max(e/127,-1);default:throw Error(`Invalid component type.`)}}function mt(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return Math.round(e*4294967295);case Uint16Array:return Math.round(e*65535);case Uint8Array:return Math.round(e*255);case Int32Array:return Math.round(e*2147483647);case Int16Array:return Math.round(e*32767);case Int8Array:return Math.round(e*127);default:throw Error(`Invalid component type.`)}}var ht={DEG2RAD:Ke,RAD2DEG:qe,generateUUID:Je,clamp:I,euclideanModulo:Ye,mapLinear:Xe,inverseLerp:Ze,lerp:Qe,damp:$e,pingpong:et,smoothstep:tt,smootherstep:nt,randInt:rt,randFloat:it,randFloatSpread:at,seededRandom:ot,degToRad:st,radToDeg:ct,isPowerOfTwo:lt,ceilPowerOfTwo:ut,floorPowerOfTwo:dt,setQuaternionFromProperEuler:ft,normalize:mt,denormalize:pt},L=class e{constructor(t=0,n=0){e.prototype.isVector2=!0,this.x=t,this.y=n}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw Error(`index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw Error(`index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){let t=this.x,n=this.y,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6],this.y=r[1]*t+r[4]*n+r[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=I(this.x,e.x,t.x),this.y=I(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=I(this.x,e,t),this.y=I(this.y,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(I(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(I(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y;return t*t+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){let n=Math.cos(t),r=Math.sin(t),i=this.x-e.x,a=this.y-e.y;return this.x=i*n-a*r+e.x,this.y=i*r+a*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}},gt=class{constructor(e=0,t=0,n=0,r=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=n,this._w=r}static slerpFlat(e,t,n,r,i,a,o){let s=n[r+0],c=n[r+1],l=n[r+2],u=n[r+3],d=i[a+0],f=i[a+1],p=i[a+2],m=i[a+3];if(o===0){e[t+0]=s,e[t+1]=c,e[t+2]=l,e[t+3]=u;return}if(o===1){e[t+0]=d,e[t+1]=f,e[t+2]=p,e[t+3]=m;return}if(u!==m||s!==d||c!==f||l!==p){let e=1-o,t=s*d+c*f+l*p+u*m,n=t>=0?1:-1,r=1-t*t;if(r>2**-52){let i=Math.sqrt(r),a=Math.atan2(i,t*n);e=Math.sin(e*a)/i,o=Math.sin(o*a)/i}let i=o*n;if(s=s*e+d*i,c=c*e+f*i,l=l*e+p*i,u=u*e+m*i,e===1-o){let e=1/Math.sqrt(s*s+c*c+l*l+u*u);s*=e,c*=e,l*=e,u*=e}}e[t]=s,e[t+1]=c,e[t+2]=l,e[t+3]=u}static multiplyQuaternionsFlat(e,t,n,r,i,a){let o=n[r],s=n[r+1],c=n[r+2],l=n[r+3],u=i[a],d=i[a+1],f=i[a+2],p=i[a+3];return e[t]=o*p+l*u+s*f-c*d,e[t+1]=s*p+l*d+c*u-o*f,e[t+2]=c*p+l*f+o*d-s*u,e[t+3]=l*p-o*u-s*d-c*f,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,n,r){return this._x=e,this._y=t,this._z=n,this._w=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){let n=e._x,r=e._y,i=e._z,a=e._order,o=Math.cos,s=Math.sin,c=o(n/2),l=o(r/2),u=o(i/2),d=s(n/2),f=s(r/2),p=s(i/2);switch(a){case`XYZ`:this._x=d*l*u+c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u-d*f*p;break;case`YXZ`:this._x=d*l*u+c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u+d*f*p;break;case`ZXY`:this._x=d*l*u-c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u-d*f*p;break;case`ZYX`:this._x=d*l*u-c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u+d*f*p;break;case`YZX`:this._x=d*l*u+c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u-d*f*p;break;case`XZY`:this._x=d*l*u-c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u+d*f*p;break;default:console.warn(`THREE.Quaternion: .setFromEuler() encountered an unknown order: `+a)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){let n=t/2,r=Math.sin(n);return this._x=e.x*r,this._y=e.y*r,this._z=e.z*r,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){let t=e.elements,n=t[0],r=t[4],i=t[8],a=t[1],o=t[5],s=t[9],c=t[2],l=t[6],u=t[10],d=n+o+u;if(d>0){let e=.5/Math.sqrt(d+1);this._w=.25/e,this._x=(l-s)*e,this._y=(i-c)*e,this._z=(a-r)*e}else if(n>o&&n>u){let e=2*Math.sqrt(1+n-o-u);this._w=(l-s)/e,this._x=.25*e,this._y=(r+a)/e,this._z=(i+c)/e}else if(o>u){let e=2*Math.sqrt(1+o-n-u);this._w=(i-c)/e,this._x=(r+a)/e,this._y=.25*e,this._z=(s+l)/e}else{let e=2*Math.sqrt(1+u-n-o);this._w=(a-r)/e,this._x=(i+c)/e,this._y=(s+l)/e,this._z=.25*e}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return n<1e-8?(n=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(I(this.dot(e),-1,1)))}rotateTowards(e,t){let n=this.angleTo(e);if(n===0)return this;let r=Math.min(1,t/n);return this.slerp(e,r),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x*=e,this._y*=e,this._z*=e,this._w*=e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){let n=e._x,r=e._y,i=e._z,a=e._w,o=t._x,s=t._y,c=t._z,l=t._w;return this._x=n*l+a*o+r*c-i*s,this._y=r*l+a*s+i*o-n*c,this._z=i*l+a*c+n*s-r*o,this._w=a*l-n*o-r*s-i*c,this._onChangeCallback(),this}slerp(e,t){if(t===0)return this;if(t===1)return this.copy(e);let n=this._x,r=this._y,i=this._z,a=this._w,o=a*e._w+n*e._x+r*e._y+i*e._z;if(o<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,o=-o):this.copy(e),o>=1)return this._w=a,this._x=n,this._y=r,this._z=i,this;let s=1-o*o;if(s<=2**-52){let e=1-t;return this._w=e*a+t*this._w,this._x=e*n+t*this._x,this._y=e*r+t*this._y,this._z=e*i+t*this._z,this.normalize(),this}let c=Math.sqrt(s),l=Math.atan2(c,o),u=Math.sin((1-t)*l)/c,d=Math.sin(t*l)/c;return this._w=a*u+this._w*d,this._x=n*u+this._x*d,this._y=r*u+this._y*d,this._z=i*u+this._z*d,this._onChangeCallback(),this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){let e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),n=Math.random(),r=Math.sqrt(1-n),i=Math.sqrt(n);return this.set(r*Math.sin(e),r*Math.cos(e),i*Math.sin(t),i*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}},R=class e{constructor(t=0,n=0,r=0){e.prototype.isVector3=!0,this.x=t,this.y=n,this.z=r}set(e,t,n){return n===void 0&&(n=this.z),this.x=e,this.y=t,this.z=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw Error(`index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw Error(`index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(vt.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(vt.setFromAxisAngle(e,t))}applyMatrix3(e){let t=this.x,n=this.y,r=this.z,i=e.elements;return this.x=i[0]*t+i[3]*n+i[6]*r,this.y=i[1]*t+i[4]*n+i[7]*r,this.z=i[2]*t+i[5]*n+i[8]*r,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){let t=this.x,n=this.y,r=this.z,i=e.elements,a=1/(i[3]*t+i[7]*n+i[11]*r+i[15]);return this.x=(i[0]*t+i[4]*n+i[8]*r+i[12])*a,this.y=(i[1]*t+i[5]*n+i[9]*r+i[13])*a,this.z=(i[2]*t+i[6]*n+i[10]*r+i[14])*a,this}applyQuaternion(e){let t=this.x,n=this.y,r=this.z,i=e.x,a=e.y,o=e.z,s=e.w,c=2*(a*r-o*n),l=2*(o*t-i*r),u=2*(i*n-a*t);return this.x=t+s*c+a*u-o*l,this.y=n+s*l+o*c-i*u,this.z=r+s*u+i*l-a*c,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){let t=this.x,n=this.y,r=this.z,i=e.elements;return this.x=i[0]*t+i[4]*n+i[8]*r,this.y=i[1]*t+i[5]*n+i[9]*r,this.z=i[2]*t+i[6]*n+i[10]*r,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=I(this.x,e.x,t.x),this.y=I(this.y,e.y,t.y),this.z=I(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=I(this.x,e,t),this.y=I(this.y,e,t),this.z=I(this.z,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(I(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){let n=e.x,r=e.y,i=e.z,a=t.x,o=t.y,s=t.z;return this.x=r*s-i*o,this.y=i*a-n*s,this.z=n*o-r*a,this}projectOnVector(e){let t=e.lengthSq();if(t===0)return this.set(0,0,0);let n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return _t.copy(this).projectOnVector(e),this.sub(_t)}reflect(e){return this.sub(_t.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(I(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y,r=this.z-e.z;return t*t+n*n+r*r}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,n){let r=Math.sin(t)*e;return this.x=r*Math.sin(n),this.y=Math.cos(t)*e,this.z=r*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){let t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),r=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=r,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){let e=Math.random()*Math.PI*2,t=Math.random()*2-1,n=Math.sqrt(1-t*t);return this.x=n*Math.cos(e),this.y=t,this.z=n*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}},_t=new R,vt=new gt,z=class e{constructor(t,n,r,i,a,o,s,c,l){e.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],t!==void 0&&this.set(t,n,r,i,a,o,s,c,l)}set(e,t,n,r,i,a,o,s,c){let l=this.elements;return l[0]=e,l[1]=r,l[2]=o,l[3]=t,l[4]=i,l[5]=s,l[6]=n,l[7]=a,l[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){let t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(e){let t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let n=e.elements,r=t.elements,i=this.elements,a=n[0],o=n[3],s=n[6],c=n[1],l=n[4],u=n[7],d=n[2],f=n[5],p=n[8],m=r[0],h=r[3],g=r[6],_=r[1],v=r[4],y=r[7],b=r[2],x=r[5],S=r[8];return i[0]=a*m+o*_+s*b,i[3]=a*h+o*v+s*x,i[6]=a*g+o*y+s*S,i[1]=c*m+l*_+u*b,i[4]=c*h+l*v+u*x,i[7]=c*g+l*y+u*S,i[2]=d*m+f*_+p*b,i[5]=d*h+f*v+p*x,i[8]=d*g+f*y+p*S,this}multiplyScalar(e){let t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8];return t*a*l-t*o*c-n*i*l+n*o*s+r*i*c-r*a*s}invert(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8],u=l*a-o*c,d=o*s-l*i,f=c*i-a*s,p=t*u+n*d+r*f;if(p===0)return this.set(0,0,0,0,0,0,0,0,0);let m=1/p;return e[0]=u*m,e[1]=(r*c-l*n)*m,e[2]=(o*n-r*a)*m,e[3]=d*m,e[4]=(l*t-r*s)*m,e[5]=(r*i-o*t)*m,e[6]=f*m,e[7]=(n*s-c*t)*m,e[8]=(a*t-n*i)*m,this}transpose(){let e,t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){let t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,n,r,i,a,o){let s=Math.cos(i),c=Math.sin(i);return this.set(n*s,n*c,-n*(s*a+c*o)+a+e,-r*c,r*s,-r*(-c*a+s*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply(yt.makeScale(e,t)),this}rotate(e){return this.premultiply(yt.makeRotation(-e)),this}translate(e,t){return this.premultiply(yt.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,n,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){let t=this.elements,n=e.elements;for(let e=0;e<9;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){let n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return new this.constructor().fromArray(this.elements)}},yt=new z;function bt(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}function xt(e){return document.createElementNS(`http://www.w3.org/1999/xhtml`,e)}function St(){let e=xt(`canvas`);return e.style.display=`block`,e}var Ct={};function wt(e){e in Ct||(Ct[e]=!0,console.warn(e))}function Tt(e,t,n){return new Promise(function(r,i){function a(){switch(e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0)){case e.WAIT_FAILED:i();break;case e.TIMEOUT_EXPIRED:setTimeout(a,n);break;default:r()}}setTimeout(a,n)})}var Et=new z().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),Dt=new z().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function Ot(){let e={enabled:!0,workingColorSpace:Le,spaces:{},convert:function(e,t,n){return this.enabled===!1||t===n||!t||!n?e:(this.spaces[t].transfer===`srgb`&&(e.r=At(e.r),e.g=At(e.g),e.b=At(e.b)),this.spaces[t].primaries!==this.spaces[n].primaries&&(e.applyMatrix3(this.spaces[t].toXYZ),e.applyMatrix3(this.spaces[n].fromXYZ)),this.spaces[n].transfer===`srgb`&&(e.r=jt(e.r),e.g=jt(e.g),e.b=jt(e.b)),e)},workingToColorSpace:function(e,t){return this.convert(e,this.workingColorSpace,t)},colorSpaceToWorking:function(e,t){return this.convert(e,t,this.workingColorSpace)},getPrimaries:function(e){return this.spaces[e].primaries},getTransfer:function(e){return e===``?Re:this.spaces[e].transfer},getToneMappingMode:function(e){return this.spaces[e].outputColorSpaceConfig.toneMappingMode||`standard`},getLuminanceCoefficients:function(e,t=this.workingColorSpace){return e.fromArray(this.spaces[t].luminanceCoefficients)},define:function(e){Object.assign(this.spaces,e)},_getMatrix:function(e,t,n){return e.copy(this.spaces[t].toXYZ).multiply(this.spaces[n].fromXYZ)},_getDrawingBufferColorSpace:function(e){return this.spaces[e].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(e=this.workingColorSpace){return this.spaces[e].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(t,n){return wt(`THREE.ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().`),e.workingToColorSpace(t,n)},toWorkingColorSpace:function(t,n){return wt(`THREE.ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking().`),e.colorSpaceToWorking(t,n)}},t=[.64,.33,.3,.6,.15,.06],n=[.2126,.7152,.0722],r=[.3127,.329];return e.define({[Le]:{primaries:t,whitePoint:r,transfer:Re,toXYZ:Et,fromXYZ:Dt,luminanceCoefficients:n,workingColorSpaceConfig:{unpackColorSpace:Ie},outputColorSpaceConfig:{drawingBufferColorSpace:Ie}},[Ie]:{primaries:t,whitePoint:r,transfer:ze,toXYZ:Et,fromXYZ:Dt,luminanceCoefficients:n,outputColorSpaceConfig:{drawingBufferColorSpace:Ie}}}),e}var kt=Ot();function At(e){return e<.04045?e*.0773993808:(e*.9478672986+.0521327014)**2.4}function jt(e){return e<.0031308?e*12.92:1.055*e**.41666-.055}var Mt,Nt=class{static getDataURL(e,t=`image/png`){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>`u`)return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{Mt===void 0&&(Mt=xt(`canvas`)),Mt.width=e.width,Mt.height=e.height;let t=Mt.getContext(`2d`);e instanceof ImageData?t.putImageData(e,0,0):t.drawImage(e,0,0,e.width,e.height),n=Mt}return n.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap){let t=xt(`canvas`);t.width=e.width,t.height=e.height;let n=t.getContext(`2d`);n.drawImage(e,0,0,e.width,e.height);let r=n.getImageData(0,0,e.width,e.height),i=r.data;for(let e=0;e<i.length;e++)i[e]=At(i[e]/255)*255;return n.putImageData(r,0,0),t}else if(e.data){let t=e.data.slice(0);for(let e=0;e<t.length;e++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[e]=Math.floor(At(t[e]/255)*255):t[e]=At(t[e]);return{data:t,width:e.width,height:e.height}}else return console.warn(`THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.`),e}},Pt=0,Ft=class{constructor(e=null){this.isSource=!0,Object.defineProperty(this,`id`,{value:Pt++}),this.uuid=Je(),this.data=e,this.dataReady=!0,this.version=0}getSize(e){let t=this.data;return typeof HTMLVideoElement<`u`&&t instanceof HTMLVideoElement?e.set(t.videoWidth,t.videoHeight,0):t instanceof VideoFrame?e.set(t.displayHeight,t.displayWidth,0):t===null?e.set(0,0,0):e.set(t.width,t.height,t.depth||0),e}set needsUpdate(e){e===!0&&this.version++}toJSON(e){let t=e===void 0||typeof e==`string`;if(!t&&e.images[this.uuid]!==void 0)return e.images[this.uuid];let n={uuid:this.uuid,url:``},r=this.data;if(r!==null){let e;if(Array.isArray(r)){e=[];for(let t=0,n=r.length;t<n;t++)r[t].isDataTexture?e.push(It(r[t].image)):e.push(It(r[t]))}else e=It(r);n.url=e}return t||(e.images[this.uuid]=n),n}};function It(e){return typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap?Nt.getDataURL(e):e.data?{data:Array.from(e.data),width:e.width,height:e.height,type:e.data.constructor.name}:(console.warn(`THREE.Texture: Unable to serialize Texture.`),{})}var Lt=0,Rt=new R,zt=class r extends Ue{constructor(e=r.DEFAULT_IMAGE,n=r.DEFAULT_MAPPING,i=t,a=t,s=o,u=c,d=w,f=l,p=r.DEFAULT_ANISOTROPY,m=``){super(),this.isTexture=!0,Object.defineProperty(this,`id`,{value:Lt++}),this.uuid=Je(),this.name=``,this.source=new Ft(e),this.mipmaps=[],this.mapping=n,this.channel=0,this.wrapS=i,this.wrapT=a,this.magFilter=s,this.minFilter=u,this.anisotropy=p,this.format=d,this.internalFormat=null,this.type=f,this.offset=new L(0,0),this.repeat=new L(1,1),this.center=new L(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new z,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=m,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(e&&e.depth&&e.depth>1),this.pmremVersion=0}get width(){return this.source.getSize(Rt).x}get height(){return this.source.getSize(Rt).y}get depth(){return this.source.getSize(Rt).z}get image(){return this.source.data}set image(e=null){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(let t in e){let n=e[t];if(n===void 0){console.warn(`THREE.Texture.setValues(): parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){console.warn(`THREE.Texture.setValues(): property '${t}' does not exist.`);continue}r&&n&&r.isVector2&&n.isVector2||r&&n&&r.isVector3&&n.isVector3||r&&n&&r.isMatrix3&&n.isMatrix3?r.copy(n):this[t]=n}}toJSON(e){let t=e===void 0||typeof e==`string`;if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];let n={metadata:{version:4.7,type:`Texture`,generator:`Texture.toJSON`},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(n.userData=this.userData),t||(e.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:`dispose`})}transformUv(r){if(this.mapping!==300)return r;if(r.applyMatrix3(this.matrix),r.x<0||r.x>1)switch(this.wrapS){case e:r.x-=Math.floor(r.x);break;case t:r.x=r.x<0?0:1;break;case n:Math.abs(Math.floor(r.x)%2)===1?r.x=Math.ceil(r.x)-r.x:r.x-=Math.floor(r.x);break}if(r.y<0||r.y>1)switch(this.wrapT){case e:r.y-=Math.floor(r.y);break;case t:r.y=r.y<0?0:1;break;case n:Math.abs(Math.floor(r.y)%2)===1?r.y=Math.ceil(r.y)-r.y:r.y-=Math.floor(r.y);break}return this.flipY&&(r.y=1-r.y),r}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}};zt.DEFAULT_IMAGE=null,zt.DEFAULT_MAPPING=300,zt.DEFAULT_ANISOTROPY=1;var Bt=class e{constructor(t=0,n=0,r=0,i=1){e.prototype.isVector4=!0,this.x=t,this.y=n,this.z=r,this.w=i}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,n,r){return this.x=e,this.y=t,this.z=n,this.w=r,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw Error(`index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw Error(`index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w===void 0?1:e.w,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){let t=this.x,n=this.y,r=this.z,i=this.w,a=e.elements;return this.x=a[0]*t+a[4]*n+a[8]*r+a[12]*i,this.y=a[1]*t+a[5]*n+a[9]*r+a[13]*i,this.z=a[2]*t+a[6]*n+a[10]*r+a[14]*i,this.w=a[3]*t+a[7]*n+a[11]*r+a[15]*i,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);let t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,n,r,i,a=.01,o=.1,s=e.elements,c=s[0],l=s[4],u=s[8],d=s[1],f=s[5],p=s[9],m=s[2],h=s[6],g=s[10];if(Math.abs(l-d)<a&&Math.abs(u-m)<a&&Math.abs(p-h)<a){if(Math.abs(l+d)<o&&Math.abs(u+m)<o&&Math.abs(p+h)<o&&Math.abs(c+f+g-3)<o)return this.set(1,0,0,0),this;t=Math.PI;let e=(c+1)/2,s=(f+1)/2,_=(g+1)/2,v=(l+d)/4,y=(u+m)/4,b=(p+h)/4;return e>s&&e>_?e<a?(n=0,r=.707106781,i=.707106781):(n=Math.sqrt(e),r=v/n,i=y/n):s>_?s<a?(n=.707106781,r=0,i=.707106781):(r=Math.sqrt(s),n=v/r,i=b/r):_<a?(n=.707106781,r=.707106781,i=0):(i=Math.sqrt(_),n=y/i,r=b/i),this.set(n,r,i,t),this}let _=Math.sqrt((h-p)*(h-p)+(u-m)*(u-m)+(d-l)*(d-l));return Math.abs(_)<.001&&(_=1),this.x=(h-p)/_,this.y=(u-m)/_,this.z=(d-l)/_,this.w=Math.acos((c+f+g-1)/2),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=I(this.x,e.x,t.x),this.y=I(this.y,e.y,t.y),this.z=I(this.z,e.z,t.z),this.w=I(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=I(this.x,e,t),this.y=I(this.y,e,t),this.z=I(this.z,e,t),this.w=I(this.w,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(I(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this.w=e.w+(t.w-e.w)*n,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}},Vt=class extends Ue{constructor(e=1,t=1,n={}){super(),n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:o,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},n),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=n.depth,this.scissor=new Bt(0,0,e,t),this.scissorTest=!1,this.viewport=new Bt(0,0,e,t);let r=new zt({width:e,height:t,depth:n.depth});this.textures=[];let i=n.count;for(let e=0;e<i;e++)this.textures[e]=r.clone(),this.textures[e].isRenderTargetTexture=!0,this.textures[e].renderTarget=this;this._setTextureOptions(n),this.depthBuffer=n.depthBuffer,this.stencilBuffer=n.stencilBuffer,this.resolveDepthBuffer=n.resolveDepthBuffer,this.resolveStencilBuffer=n.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=n.depthTexture,this.samples=n.samples,this.multiview=n.multiview}_setTextureOptions(e={}){let t={minFilter:o,generateMipmaps:!1,flipY:!1,internalFormat:null};e.mapping!==void 0&&(t.mapping=e.mapping),e.wrapS!==void 0&&(t.wrapS=e.wrapS),e.wrapT!==void 0&&(t.wrapT=e.wrapT),e.wrapR!==void 0&&(t.wrapR=e.wrapR),e.magFilter!==void 0&&(t.magFilter=e.magFilter),e.minFilter!==void 0&&(t.minFilter=e.minFilter),e.format!==void 0&&(t.format=e.format),e.type!==void 0&&(t.type=e.type),e.anisotropy!==void 0&&(t.anisotropy=e.anisotropy),e.colorSpace!==void 0&&(t.colorSpace=e.colorSpace),e.flipY!==void 0&&(t.flipY=e.flipY),e.generateMipmaps!==void 0&&(t.generateMipmaps=e.generateMipmaps),e.internalFormat!==void 0&&(t.internalFormat=e.internalFormat);for(let e=0;e<this.textures.length;e++)this.textures[e].setValues(t)}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}set depthTexture(e){this._depthTexture!==null&&(this._depthTexture.renderTarget=null),e!==null&&(e.renderTarget=this),this._depthTexture=e}get depthTexture(){return this._depthTexture}setSize(e,t,n=1){if(this.width!==e||this.height!==t||this.depth!==n){this.width=e,this.height=t,this.depth=n;for(let r=0,i=this.textures.length;r<i;r++)this.textures[r].image.width=e,this.textures[r].image.height=t,this.textures[r].image.depth=n,this.textures[r].isArrayTexture=this.textures[r].image.depth>1;this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,n=e.textures.length;t<n;t++){this.textures[t]=e.textures[t].clone(),this.textures[t].isRenderTargetTexture=!0,this.textures[t].renderTarget=this;let n=Object.assign({},e.textures[t].image);this.textures[t].source=new Ft(n)}return this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,e.depthTexture!==null&&(this.depthTexture=e.depthTexture.clone()),this.samples=e.samples,this}dispose(){this.dispatchEvent({type:`dispose`})}},Ht=class extends Vt{constructor(e=1,t=1,n={}){super(e,t,n),this.isWebGLRenderTarget=!0}},Ut=class extends zt{constructor(e=null,n=1,i=1,a=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:n,height:i,depth:a},this.magFilter=r,this.minFilter=r,this.wrapR=t,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}},Wt=class extends zt{constructor(e=null,n=1,i=1,a=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:n,height:i,depth:a},this.magFilter=r,this.minFilter=r,this.wrapR=t,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}},Gt=class{constructor(e=new R(1/0,1/0,1/0),t=new R(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t+=3)this.expandByPoint(qt.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,n=e.count;t<n;t++)this.expandByPoint(qt.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){let n=qt.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(n),this.max.copy(e).add(n),this}setFromObject(e,t=!1){return this.makeEmpty(),this.expandByObject(e,t)}clone(){return new this.constructor().copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,t=!1){e.updateWorldMatrix(!1,!1);let n=e.geometry;if(n!==void 0){let r=n.getAttribute(`position`);if(t===!0&&r!==void 0&&e.isInstancedMesh!==!0)for(let t=0,n=r.count;t<n;t++)e.isMesh===!0?e.getVertexPosition(t,qt):qt.fromBufferAttribute(r,t),qt.applyMatrix4(e.matrixWorld),this.expandByPoint(qt);else e.boundingBox===void 0?(n.boundingBox===null&&n.computeBoundingBox(),Jt.copy(n.boundingBox)):(e.boundingBox===null&&e.computeBoundingBox(),Jt.copy(e.boundingBox)),Jt.applyMatrix4(e.matrixWorld),this.union(Jt)}let r=e.children;for(let e=0,n=r.length;e<n;e++)this.expandByObject(r[e],t);return this}containsPoint(e){return e.x>=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,qt),qt.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(tn),nn.subVectors(this.max,tn),Yt.subVectors(e.a,tn),Xt.subVectors(e.b,tn),Zt.subVectors(e.c,tn),Qt.subVectors(Xt,Yt),$t.subVectors(Zt,Xt),en.subVectors(Yt,Zt);let t=[0,-Qt.z,Qt.y,0,-$t.z,$t.y,0,-en.z,en.y,Qt.z,0,-Qt.x,$t.z,0,-$t.x,en.z,0,-en.x,-Qt.y,Qt.x,0,-$t.y,$t.x,0,-en.y,en.x,0];return!on(t,Yt,Xt,Zt,nn)||(t=[1,0,0,0,1,0,0,0,1],!on(t,Yt,Xt,Zt,nn))?!1:(rn.crossVectors(Qt,$t),t=[rn.x,rn.y,rn.z],on(t,Yt,Xt,Zt,nn))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,qt).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(qt).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(Kt[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Kt[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Kt[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Kt[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Kt[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Kt[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Kt[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Kt[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Kt),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}},Kt=[new R,new R,new R,new R,new R,new R,new R,new R],qt=new R,Jt=new Gt,Yt=new R,Xt=new R,Zt=new R,Qt=new R,$t=new R,en=new R,tn=new R,nn=new R,rn=new R,an=new R;function on(e,t,n,r,i){for(let a=0,o=e.length-3;a<=o;a+=3){an.fromArray(e,a);let o=i.x*Math.abs(an.x)+i.y*Math.abs(an.y)+i.z*Math.abs(an.z),s=t.dot(an),c=n.dot(an),l=r.dot(an);if(Math.max(-Math.max(s,c,l),Math.min(s,c,l))>o)return!1}return!0}var sn=new Gt,cn=new R,ln=new R,un=class{constructor(e=new R,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){let n=this.center;t===void 0?sn.setFromPoints(e).getCenter(n):n.copy(t);let r=0;for(let t=0,i=e.length;t<i;t++)r=Math.max(r,n.distanceToSquared(e[t]));return this.radius=Math.sqrt(r),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){let t=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=t*t}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,t){let n=this.center.distanceToSquared(e);return t.copy(e),n>this.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius*=e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;cn.subVectors(e,this.center);let t=cn.lengthSq();if(t>this.radius*this.radius){let e=Math.sqrt(t),n=(e-this.radius)*.5;this.center.addScaledVector(cn,n/e),this.radius+=n}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(ln.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(cn.copy(e.center).add(ln)),this.expandByPoint(cn.copy(e.center).sub(ln))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}},dn=new R,fn=new R,pn=new R,mn=new R,hn=new R,gn=new R,_n=new R,vn=class{constructor(e=new R,t=new R(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,dn)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);let n=t.dot(this.direction);return n<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){let t=dn.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(dn.copy(this.origin).addScaledVector(this.direction,t),dn.distanceToSquared(e))}distanceSqToSegment(e,t,n,r){fn.copy(e).add(t).multiplyScalar(.5),pn.copy(t).sub(e).normalize(),mn.copy(this.origin).sub(fn);let i=e.distanceTo(t)*.5,a=-this.direction.dot(pn),o=mn.dot(this.direction),s=-mn.dot(pn),c=mn.lengthSq(),l=Math.abs(1-a*a),u,d,f,p;if(l>0)if(u=a*s-o,d=a*o-s,p=i*l,u>=0)if(d>=-p)if(d<=p){let e=1/l;u*=e,d*=e,f=u*(u+a*d+2*o)+d*(a*u+d+2*s)+c}else d=i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c;else d=-i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c;else d<=-p?(u=Math.max(0,-(-a*i+o)),d=u>0?-i:Math.min(Math.max(-i,-s),i),f=-u*u+d*(d+2*s)+c):d<=p?(u=0,d=Math.min(Math.max(-i,-s),i),f=d*(d+2*s)+c):(u=Math.max(0,-(a*i+o)),d=u>0?i:Math.min(Math.max(-i,-s),i),f=-u*u+d*(d+2*s)+c);else d=a>0?-i:i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c;return n&&n.copy(this.origin).addScaledVector(this.direction,u),r&&r.copy(fn).addScaledVector(pn,d),f}intersectSphere(e,t){dn.subVectors(e.center,this.origin);let n=dn.dot(this.direction),r=dn.dot(dn)-n*n,i=e.radius*e.radius;if(r>i)return null;let a=Math.sqrt(i-r),o=n-a,s=n+a;return s<0?null:o<0?this.at(s,t):this.at(o,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){let t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;let n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){let n=this.distanceToPlane(e);return n===null?null:this.at(n,t)}intersectsPlane(e){let t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,r,i,a,o,s,c=1/this.direction.x,l=1/this.direction.y,u=1/this.direction.z,d=this.origin;return c>=0?(n=(e.min.x-d.x)*c,r=(e.max.x-d.x)*c):(n=(e.max.x-d.x)*c,r=(e.min.x-d.x)*c),l>=0?(i=(e.min.y-d.y)*l,a=(e.max.y-d.y)*l):(i=(e.max.y-d.y)*l,a=(e.min.y-d.y)*l),n>a||i>r||((i>n||isNaN(n))&&(n=i),(a<r||isNaN(r))&&(r=a),u>=0?(o=(e.min.z-d.z)*u,s=(e.max.z-d.z)*u):(o=(e.max.z-d.z)*u,s=(e.min.z-d.z)*u),n>s||o>r)||((o>n||n!==n)&&(n=o),(s<r||r!==r)&&(r=s),r<0)?null:this.at(n>=0?n:r,t)}intersectsBox(e){return this.intersectBox(e,dn)!==null}intersectTriangle(e,t,n,r,i){hn.subVectors(t,e),gn.subVectors(n,e),_n.crossVectors(hn,gn);let a=this.direction.dot(_n),o;if(a>0){if(r)return null;o=1}else if(a<0)o=-1,a=-a;else return null;mn.subVectors(this.origin,e);let s=o*this.direction.dot(gn.crossVectors(mn,gn));if(s<0)return null;let c=o*this.direction.dot(hn.cross(mn));if(c<0||s+c>a)return null;let l=-o*mn.dot(_n);return l<0?null:this.at(l/a,i)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}},yn=class e{constructor(t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g){e.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],t!==void 0&&this.set(t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g)}set(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){let g=this.elements;return g[0]=e,g[4]=t,g[8]=n,g[12]=r,g[1]=i,g[5]=a,g[9]=o,g[13]=s,g[2]=c,g[6]=l,g[10]=u,g[14]=d,g[3]=f,g[7]=p,g[11]=m,g[15]=h,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new e().fromArray(this.elements)}copy(e){let t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],t[9]=n[9],t[10]=n[10],t[11]=n[11],t[12]=n[12],t[13]=n[13],t[14]=n[14],t[15]=n[15],this}copyPosition(e){let t=this.elements,n=e.elements;return t[12]=n[12],t[13]=n[13],t[14]=n[14],this}setFromMatrix3(e){let t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,n){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this}makeBasis(e,t,n){return this.set(e.x,t.x,n.x,0,e.y,t.y,n.y,0,e.z,t.z,n.z,0,0,0,0,1),this}extractRotation(e){let t=this.elements,n=e.elements,r=1/bn.setFromMatrixColumn(e,0).length(),i=1/bn.setFromMatrixColumn(e,1).length(),a=1/bn.setFromMatrixColumn(e,2).length();return t[0]=n[0]*r,t[1]=n[1]*r,t[2]=n[2]*r,t[3]=0,t[4]=n[4]*i,t[5]=n[5]*i,t[6]=n[6]*i,t[7]=0,t[8]=n[8]*a,t[9]=n[9]*a,t[10]=n[10]*a,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){let t=this.elements,n=e.x,r=e.y,i=e.z,a=Math.cos(n),o=Math.sin(n),s=Math.cos(r),c=Math.sin(r),l=Math.cos(i),u=Math.sin(i);if(e.order===`XYZ`){let e=a*l,n=a*u,r=o*l,i=o*u;t[0]=s*l,t[4]=-s*u,t[8]=c,t[1]=n+r*c,t[5]=e-i*c,t[9]=-o*s,t[2]=i-e*c,t[6]=r+n*c,t[10]=a*s}else if(e.order===`YXZ`){let e=s*l,n=s*u,r=c*l,i=c*u;t[0]=e+i*o,t[4]=r*o-n,t[8]=a*c,t[1]=a*u,t[5]=a*l,t[9]=-o,t[2]=n*o-r,t[6]=i+e*o,t[10]=a*s}else if(e.order===`ZXY`){let e=s*l,n=s*u,r=c*l,i=c*u;t[0]=e-i*o,t[4]=-a*u,t[8]=r+n*o,t[1]=n+r*o,t[5]=a*l,t[9]=i-e*o,t[2]=-a*c,t[6]=o,t[10]=a*s}else if(e.order===`ZYX`){let e=a*l,n=a*u,r=o*l,i=o*u;t[0]=s*l,t[4]=r*c-n,t[8]=e*c+i,t[1]=s*u,t[5]=i*c+e,t[9]=n*c-r,t[2]=-c,t[6]=o*s,t[10]=a*s}else if(e.order===`YZX`){let e=a*s,n=a*c,r=o*s,i=o*c;t[0]=s*l,t[4]=i-e*u,t[8]=r*u+n,t[1]=u,t[5]=a*l,t[9]=-o*l,t[2]=-c*l,t[6]=n*u+r,t[10]=e-i*u}else if(e.order===`XZY`){let e=a*s,n=a*c,r=o*s,i=o*c;t[0]=s*l,t[4]=-u,t[8]=c*l,t[1]=e*u+i,t[5]=a*l,t[9]=n*u-r,t[2]=r*u-n,t[6]=o*l,t[10]=i*u+e}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(Sn,e,Cn)}lookAt(e,t,n){let r=this.elements;return En.subVectors(e,t),En.lengthSq()===0&&(En.z=1),En.normalize(),wn.crossVectors(n,En),wn.lengthSq()===0&&(Math.abs(n.z)===1?En.x+=1e-4:En.z+=1e-4,En.normalize(),wn.crossVectors(n,En)),wn.normalize(),Tn.crossVectors(En,wn),r[0]=wn.x,r[4]=Tn.x,r[8]=En.x,r[1]=wn.y,r[5]=Tn.y,r[9]=En.y,r[2]=wn.z,r[6]=Tn.z,r[10]=En.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let n=e.elements,r=t.elements,i=this.elements,a=n[0],o=n[4],s=n[8],c=n[12],l=n[1],u=n[5],d=n[9],f=n[13],p=n[2],m=n[6],h=n[10],g=n[14],_=n[3],v=n[7],y=n[11],b=n[15],x=r[0],S=r[4],C=r[8],w=r[12],T=r[1],E=r[5],D=r[9],ee=r[13],O=r[2],k=r[6],te=r[10],ne=r[14],A=r[3],re=r[7],ie=r[11],j=r[15];return i[0]=a*x+o*T+s*O+c*A,i[4]=a*S+o*E+s*k+c*re,i[8]=a*C+o*D+s*te+c*ie,i[12]=a*w+o*ee+s*ne+c*j,i[1]=l*x+u*T+d*O+f*A,i[5]=l*S+u*E+d*k+f*re,i[9]=l*C+u*D+d*te+f*ie,i[13]=l*w+u*ee+d*ne+f*j,i[2]=p*x+m*T+h*O+g*A,i[6]=p*S+m*E+h*k+g*re,i[10]=p*C+m*D+h*te+g*ie,i[14]=p*w+m*ee+h*ne+g*j,i[3]=_*x+v*T+y*O+b*A,i[7]=_*S+v*E+y*k+b*re,i[11]=_*C+v*D+y*te+b*ie,i[15]=_*w+v*ee+y*ne+b*j,this}multiplyScalar(e){let t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){let e=this.elements,t=e[0],n=e[4],r=e[8],i=e[12],a=e[1],o=e[5],s=e[9],c=e[13],l=e[2],u=e[6],d=e[10],f=e[14],p=e[3],m=e[7],h=e[11],g=e[15];return p*(+i*s*u-r*c*u-i*o*d+n*c*d+r*o*f-n*s*f)+m*(+t*s*f-t*c*d+i*a*d-r*a*f+r*c*l-i*s*l)+h*(+t*c*u-t*o*f-i*a*u+n*a*f+i*o*l-n*c*l)+g*(-r*o*l-t*s*u+t*o*d+r*a*u-n*a*d+n*s*l)}transpose(){let e=this.elements,t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,n){let r=this.elements;return e.isVector3?(r[12]=e.x,r[13]=e.y,r[14]=e.z):(r[12]=e,r[13]=t,r[14]=n),this}invert(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8],u=e[9],d=e[10],f=e[11],p=e[12],m=e[13],h=e[14],g=e[15],_=u*h*c-m*d*c+m*s*f-o*h*f-u*s*g+o*d*g,v=p*d*c-l*h*c-p*s*f+a*h*f+l*s*g-a*d*g,y=l*m*c-p*u*c+p*o*f-a*m*f-l*o*g+a*u*g,b=p*u*s-l*m*s-p*o*d+a*m*d+l*o*h-a*u*h,x=t*_+n*v+r*y+i*b;if(x===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);let S=1/x;return e[0]=_*S,e[1]=(m*d*i-u*h*i-m*r*f+n*h*f+u*r*g-n*d*g)*S,e[2]=(o*h*i-m*s*i+m*r*c-n*h*c-o*r*g+n*s*g)*S,e[3]=(u*s*i-o*d*i-u*r*c+n*d*c+o*r*f-n*s*f)*S,e[4]=v*S,e[5]=(l*h*i-p*d*i+p*r*f-t*h*f-l*r*g+t*d*g)*S,e[6]=(p*s*i-a*h*i-p*r*c+t*h*c+a*r*g-t*s*g)*S,e[7]=(a*d*i-l*s*i+l*r*c-t*d*c-a*r*f+t*s*f)*S,e[8]=y*S,e[9]=(p*u*i-l*m*i-p*n*f+t*m*f+l*n*g-t*u*g)*S,e[10]=(a*m*i-p*o*i+p*n*c-t*m*c-a*n*g+t*o*g)*S,e[11]=(l*o*i-a*u*i-l*n*c+t*u*c+a*n*f-t*o*f)*S,e[12]=b*S,e[13]=(l*m*r-p*u*r+p*n*d-t*m*d-l*n*h+t*u*h)*S,e[14]=(p*o*r-a*m*r-p*n*s+t*m*s+a*n*h-t*o*h)*S,e[15]=(a*u*r-l*o*r+l*n*s-t*u*s-a*n*d+t*o*d)*S,this}scale(e){let t=this.elements,n=e.x,r=e.y,i=e.z;return t[0]*=n,t[4]*=r,t[8]*=i,t[1]*=n,t[5]*=r,t[9]*=i,t[2]*=n,t[6]*=r,t[10]*=i,t[3]*=n,t[7]*=r,t[11]*=i,this}getMaxScaleOnAxis(){let e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],n=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],r=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,r))}makeTranslation(e,t,n){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,n,0,0,0,1),this}makeRotationX(e){let t=Math.cos(e),n=Math.sin(e);return this.set(1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1),this}makeRotationY(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1),this}makeRotationZ(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){let n=Math.cos(t),r=Math.sin(t),i=1-n,a=e.x,o=e.y,s=e.z,c=i*a,l=i*o;return this.set(c*a+n,c*o-r*s,c*s+r*o,0,c*o+r*s,l*o+n,l*s-r*a,0,c*s-r*o,l*s+r*a,i*s*s+n,0,0,0,0,1),this}makeScale(e,t,n){return this.set(e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1),this}makeShear(e,t,n,r,i,a){return this.set(1,n,i,0,e,1,a,0,t,r,1,0,0,0,0,1),this}compose(e,t,n){let r=this.elements,i=t._x,a=t._y,o=t._z,s=t._w,c=i+i,l=a+a,u=o+o,d=i*c,f=i*l,p=i*u,m=a*l,h=a*u,g=o*u,_=s*c,v=s*l,y=s*u,b=n.x,x=n.y,S=n.z;return r[0]=(1-(m+g))*b,r[1]=(f+y)*b,r[2]=(p-v)*b,r[3]=0,r[4]=(f-y)*x,r[5]=(1-(d+g))*x,r[6]=(h+_)*x,r[7]=0,r[8]=(p+v)*S,r[9]=(h-_)*S,r[10]=(1-(d+m))*S,r[11]=0,r[12]=e.x,r[13]=e.y,r[14]=e.z,r[15]=1,this}decompose(e,t,n){let r=this.elements,i=bn.set(r[0],r[1],r[2]).length(),a=bn.set(r[4],r[5],r[6]).length(),o=bn.set(r[8],r[9],r[10]).length();this.determinant()<0&&(i=-i),e.x=r[12],e.y=r[13],e.z=r[14],xn.copy(this);let s=1/i,c=1/a,l=1/o;return xn.elements[0]*=s,xn.elements[1]*=s,xn.elements[2]*=s,xn.elements[4]*=c,xn.elements[5]*=c,xn.elements[6]*=c,xn.elements[8]*=l,xn.elements[9]*=l,xn.elements[10]*=l,t.setFromRotationMatrix(xn),n.x=i,n.y=a,n.z=o,this}makePerspective(e,t,n,r,i,a,o=He,s=!1){let c=this.elements,l=2*i/(t-e),u=2*i/(n-r),d=(t+e)/(t-e),f=(n+r)/(n-r),p,m;if(s)p=i/(a-i),m=a*i/(a-i);else if(o===2e3)p=-(a+i)/(a-i),m=-2*a*i/(a-i);else if(o===2001)p=-a/(a-i),m=-a*i/(a-i);else throw Error(`THREE.Matrix4.makePerspective(): Invalid coordinate system: `+o);return c[0]=l,c[4]=0,c[8]=d,c[12]=0,c[1]=0,c[5]=u,c[9]=f,c[13]=0,c[2]=0,c[6]=0,c[10]=p,c[14]=m,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,t,n,r,i,a,o=He,s=!1){let c=this.elements,l=2/(t-e),u=2/(n-r),d=-(t+e)/(t-e),f=-(n+r)/(n-r),p,m;if(s)p=1/(a-i),m=a/(a-i);else if(o===2e3)p=-2/(a-i),m=-(a+i)/(a-i);else if(o===2001)p=-1/(a-i),m=-i/(a-i);else throw Error(`THREE.Matrix4.makeOrthographic(): Invalid coordinate system: `+o);return c[0]=l,c[4]=0,c[8]=0,c[12]=d,c[1]=0,c[5]=u,c[9]=0,c[13]=f,c[2]=0,c[6]=0,c[10]=p,c[14]=m,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(e){let t=this.elements,n=e.elements;for(let e=0;e<16;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<16;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){let n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e[t+9]=n[9],e[t+10]=n[10],e[t+11]=n[11],e[t+12]=n[12],e[t+13]=n[13],e[t+14]=n[14],e[t+15]=n[15],e}},bn=new R,xn=new yn,Sn=new R(0,0,0),Cn=new R(1,1,1),wn=new R,Tn=new R,En=new R,Dn=new yn,On=new gt,kn=class e{constructor(t=0,n=0,r=0,i=e.DEFAULT_ORDER){this.isEuler=!0,this._x=t,this._y=n,this._z=r,this._order=i}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,n,r=this._order){return this._x=e,this._y=t,this._z=n,this._order=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,n=!0){let r=e.elements,i=r[0],a=r[4],o=r[8],s=r[1],c=r[5],l=r[9],u=r[2],d=r[6],f=r[10];switch(t){case`XYZ`:this._y=Math.asin(I(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-l,f),this._z=Math.atan2(-a,i)):(this._x=Math.atan2(d,c),this._z=0);break;case`YXZ`:this._x=Math.asin(-I(l,-1,1)),Math.abs(l)<.9999999?(this._y=Math.atan2(o,f),this._z=Math.atan2(s,c)):(this._y=Math.atan2(-u,i),this._z=0);break;case`ZXY`:this._x=Math.asin(I(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-u,f),this._z=Math.atan2(-a,c)):(this._y=0,this._z=Math.atan2(s,i));break;case`ZYX`:this._y=Math.asin(-I(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(d,f),this._z=Math.atan2(s,i)):(this._x=0,this._z=Math.atan2(-a,c));break;case`YZX`:this._z=Math.asin(I(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(-l,c),this._y=Math.atan2(-u,i)):(this._x=0,this._y=Math.atan2(o,f));break;case`XZY`:this._z=Math.asin(-I(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(d,c),this._y=Math.atan2(o,i)):(this._x=Math.atan2(-l,f),this._y=0);break;default:console.warn(`THREE.Euler: .setFromRotationMatrix() encountered an unknown order: `+t)}return this._order=t,n===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return Dn.makeRotationFromQuaternion(e),this.setFromRotationMatrix(Dn,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return On.setFromEuler(this),this.setFromQuaternion(On,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}};kn.DEFAULT_ORDER=`XYZ`;var An=class{constructor(){this.mask=1}set(e){this.mask=(1<<e|0)>>>0}enable(e){this.mask|=1<<e|0}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e|0}disable(e){this.mask&=~(1<<e|0)}disableAll(){this.mask=0}test(e){return(this.mask&e.mask)!==0}isEnabled(e){return(this.mask&(1<<e|0))!=0}},jn=0,Mn=new R,Nn=new gt,Pn=new yn,Fn=new R,In=new R,Ln=new R,Rn=new gt,zn=new R(1,0,0),Bn=new R(0,1,0),Vn=new R(0,0,1),Hn={type:`added`},Un={type:`removed`},Wn={type:`childadded`,child:null},Gn={type:`childremoved`,child:null},Kn=class e extends Ue{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,`id`,{value:jn++}),this.uuid=Je(),this.name=``,this.type=`Object3D`,this.parent=null,this.children=[],this.up=e.DEFAULT_UP.clone();let t=new R,n=new kn,r=new gt,i=new R(1,1,1);function a(){r.setFromEuler(n,!1)}function o(){n.setFromQuaternion(r,void 0,!1)}n._onChange(a),r._onChange(o),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:t},rotation:{configurable:!0,enumerable:!0,value:n},quaternion:{configurable:!0,enumerable:!0,value:r},scale:{configurable:!0,enumerable:!0,value:i},modelViewMatrix:{value:new yn},normalMatrix:{value:new z}}),this.matrix=new yn,this.matrixWorld=new yn,this.matrixAutoUpdate=e.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=e.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new An,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.userData={}}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,t){this.quaternion.setFromAxisAngle(e,t)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,t){return Nn.setFromAxisAngle(e,t),this.quaternion.multiply(Nn),this}rotateOnWorldAxis(e,t){return Nn.setFromAxisAngle(e,t),this.quaternion.premultiply(Nn),this}rotateX(e){return this.rotateOnAxis(zn,e)}rotateY(e){return this.rotateOnAxis(Bn,e)}rotateZ(e){return this.rotateOnAxis(Vn,e)}translateOnAxis(e,t){return Mn.copy(e).applyQuaternion(this.quaternion),this.position.add(Mn.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(zn,e)}translateY(e){return this.translateOnAxis(Bn,e)}translateZ(e){return this.translateOnAxis(Vn,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(Pn.copy(this.matrixWorld).invert())}lookAt(e,t,n){e.isVector3?Fn.copy(e):Fn.set(e,t,n);let r=this.parent;this.updateWorldMatrix(!0,!1),In.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?Pn.lookAt(In,Fn,this.up):Pn.lookAt(Fn,In,this.up),this.quaternion.setFromRotationMatrix(Pn),r&&(Pn.extractRotation(r.matrixWorld),Nn.setFromRotationMatrix(Pn),this.quaternion.premultiply(Nn.invert()))}add(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.add(arguments[e]);return this}return e===this?(console.error(`THREE.Object3D.add: object can't be added as a child of itself.`,e),this):(e&&e.isObject3D?(e.removeFromParent(),e.parent=this,this.children.push(e),e.dispatchEvent(Hn),Wn.child=e,this.dispatchEvent(Wn),Wn.child=null):console.error(`THREE.Object3D.add: object not an instance of THREE.Object3D.`,e),this)}remove(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.remove(arguments[e]);return this}let t=this.children.indexOf(e);return t!==-1&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent(Un),Gn.child=e,this.dispatchEvent(Gn),Gn.child=null),this}removeFromParent(){let e=this.parent;return e!==null&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),Pn.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),Pn.multiply(e.parent.matrixWorld)),e.applyMatrix4(Pn),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(Hn),Wn.child=e,this.dispatchEvent(Wn),Wn.child=null,this}getObjectById(e){return this.getObjectByProperty(`id`,e)}getObjectByName(e){return this.getObjectByProperty(`name`,e)}getObjectByProperty(e,t){if(this[e]===t)return this;for(let n=0,r=this.children.length;n<r;n++){let r=this.children[n].getObjectByProperty(e,t);if(r!==void 0)return r}}getObjectsByProperty(e,t,n=[]){this[e]===t&&n.push(this);let r=this.children;for(let i=0,a=r.length;i<a;i++)r[i].getObjectsByProperty(e,t,n);return n}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(In,e,Ln),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(In,Rn,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);let t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}traverse(e){e(this);let t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);let t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].traverseVisible(e)}traverseAncestors(e){let t=this.parent;t!==null&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale),this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,e=!0);let t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].updateMatrixWorld(e)}updateWorldMatrix(e,t){let n=this.parent;if(e===!0&&n!==null&&n.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),t===!0){let e=this.children;for(let t=0,n=e.length;t<n;t++)e[t].updateWorldMatrix(!1,!0)}}toJSON(e){let t=e===void 0||typeof e==`string`,n={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},n.metadata={version:4.7,type:`Object`,generator:`Object3D.toJSON`});let r={};r.uuid=this.uuid,r.type=this.type,this.name!==``&&(r.name=this.name),this.castShadow===!0&&(r.castShadow=!0),this.receiveShadow===!0&&(r.receiveShadow=!0),this.visible===!1&&(r.visible=!1),this.frustumCulled===!1&&(r.frustumCulled=!1),this.renderOrder!==0&&(r.renderOrder=this.renderOrder),Object.keys(this.userData).length>0&&(r.userData=this.userData),r.layers=this.layers.mask,r.matrix=this.matrix.toArray(),r.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(r.matrixAutoUpdate=!1),this.isInstancedMesh&&(r.type=`InstancedMesh`,r.count=this.count,r.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(r.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(r.type=`BatchedMesh`,r.perObjectFrustumCulled=this.perObjectFrustumCulled,r.sortObjects=this.sortObjects,r.drawRanges=this._drawRanges,r.reservedRanges=this._reservedRanges,r.geometryInfo=this._geometryInfo.map(e=>({...e,boundingBox:e.boundingBox?e.boundingBox.toJSON():void 0,boundingSphere:e.boundingSphere?e.boundingSphere.toJSON():void 0})),r.instanceInfo=this._instanceInfo.map(e=>({...e})),r.availableInstanceIds=this._availableInstanceIds.slice(),r.availableGeometryIds=this._availableGeometryIds.slice(),r.nextIndexStart=this._nextIndexStart,r.nextVertexStart=this._nextVertexStart,r.geometryCount=this._geometryCount,r.maxInstanceCount=this._maxInstanceCount,r.maxVertexCount=this._maxVertexCount,r.maxIndexCount=this._maxIndexCount,r.geometryInitialized=this._geometryInitialized,r.matricesTexture=this._matricesTexture.toJSON(e),r.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(r.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(r.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(r.boundingBox=this.boundingBox.toJSON()));function i(t,n){return t[n.uuid]===void 0&&(t[n.uuid]=n.toJSON(e)),n.uuid}if(this.isScene)this.background&&(this.background.isColor?r.background=this.background.toJSON():this.background.isTexture&&(r.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(r.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){r.geometry=i(e.geometries,this.geometry);let t=this.geometry.parameters;if(t!==void 0&&t.shapes!==void 0){let n=t.shapes;if(Array.isArray(n))for(let t=0,r=n.length;t<r;t++){let r=n[t];i(e.shapes,r)}else i(e.shapes,n)}}if(this.isSkinnedMesh&&(r.bindMode=this.bindMode,r.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(i(e.skeletons,this.skeleton),r.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){let t=[];for(let n=0,r=this.material.length;n<r;n++)t.push(i(e.materials,this.material[n]));r.material=t}else r.material=i(e.materials,this.material);if(this.children.length>0){r.children=[];for(let t=0;t<this.children.length;t++)r.children.push(this.children[t].toJSON(e).object)}if(this.animations.length>0){r.animations=[];for(let t=0;t<this.animations.length;t++){let n=this.animations[t];r.animations.push(i(e.animations,n))}}if(t){let t=a(e.geometries),r=a(e.materials),i=a(e.textures),o=a(e.images),s=a(e.shapes),c=a(e.skeletons),l=a(e.animations),u=a(e.nodes);t.length>0&&(n.geometries=t),r.length>0&&(n.materials=r),i.length>0&&(n.textures=i),o.length>0&&(n.images=o),s.length>0&&(n.shapes=s),c.length>0&&(n.skeletons=c),l.length>0&&(n.animations=l),u.length>0&&(n.nodes=u)}return n.object=r,n;function a(e){let t=[];for(let n in e){let r=e[n];delete r.metadata,t.push(r)}return t}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let t=0;t<e.children.length;t++){let n=e.children[t];this.add(n.clone())}return this}};Kn.DEFAULT_UP=new R(0,1,0),Kn.DEFAULT_MATRIX_AUTO_UPDATE=!0,Kn.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;var qn=new R,Jn=new R,Yn=new R,Xn=new R,Zn=new R,Qn=new R,$n=new R,er=new R,tr=new R,nr=new R,rr=new Bt,ir=new Bt,ar=new Bt,or=class e{constructor(e=new R,t=new R,n=new R){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,r){r.subVectors(n,t),qn.subVectors(e,t),r.cross(qn);let i=r.lengthSq();return i>0?r.multiplyScalar(1/Math.sqrt(i)):r.set(0,0,0)}static getBarycoord(e,t,n,r,i){qn.subVectors(r,t),Jn.subVectors(n,t),Yn.subVectors(e,t);let a=qn.dot(qn),o=qn.dot(Jn),s=qn.dot(Yn),c=Jn.dot(Jn),l=Jn.dot(Yn),u=a*c-o*o;if(u===0)return i.set(0,0,0),null;let d=1/u,f=(c*s-o*l)*d,p=(a*l-o*s)*d;return i.set(1-f-p,p,f)}static containsPoint(e,t,n,r){return this.getBarycoord(e,t,n,r,Xn)===null?!1:Xn.x>=0&&Xn.y>=0&&Xn.x+Xn.y<=1}static getInterpolation(e,t,n,r,i,a,o,s){return this.getBarycoord(e,t,n,r,Xn)===null?(s.x=0,s.y=0,`z`in s&&(s.z=0),`w`in s&&(s.w=0),null):(s.setScalar(0),s.addScaledVector(i,Xn.x),s.addScaledVector(a,Xn.y),s.addScaledVector(o,Xn.z),s)}static getInterpolatedAttribute(e,t,n,r,i,a){return rr.setScalar(0),ir.setScalar(0),ar.setScalar(0),rr.fromBufferAttribute(e,t),ir.fromBufferAttribute(e,n),ar.fromBufferAttribute(e,r),a.setScalar(0),a.addScaledVector(rr,i.x),a.addScaledVector(ir,i.y),a.addScaledVector(ar,i.z),a}static isFrontFacing(e,t,n,r){return qn.subVectors(n,t),Jn.subVectors(e,t),qn.cross(Jn).dot(r)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,r){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[r]),this}setFromAttributeAndIndices(e,t,n,r){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,r),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return qn.subVectors(this.c,this.b),Jn.subVectors(this.a,this.b),qn.cross(Jn).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return e.getNormal(this.a,this.b,this.c,t)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,n){return e.getBarycoord(t,this.a,this.b,this.c,n)}getInterpolation(t,n,r,i,a){return e.getInterpolation(t,this.a,this.b,this.c,n,r,i,a)}containsPoint(t){return e.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return e.isFrontFacing(this.a,this.b,this.c,t)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){let n=this.a,r=this.b,i=this.c,a,o;Zn.subVectors(r,n),Qn.subVectors(i,n),er.subVectors(e,n);let s=Zn.dot(er),c=Qn.dot(er);if(s<=0&&c<=0)return t.copy(n);tr.subVectors(e,r);let l=Zn.dot(tr),u=Qn.dot(tr);if(l>=0&&u<=l)return t.copy(r);let d=s*u-l*c;if(d<=0&&s>=0&&l<=0)return a=s/(s-l),t.copy(n).addScaledVector(Zn,a);nr.subVectors(e,i);let f=Zn.dot(nr),p=Qn.dot(nr);if(p>=0&&f<=p)return t.copy(i);let m=f*c-s*p;if(m<=0&&c>=0&&p<=0)return o=c/(c-p),t.copy(n).addScaledVector(Qn,o);let h=l*p-f*u;if(h<=0&&u-l>=0&&f-p>=0)return $n.subVectors(i,r),o=(u-l)/(u-l+(f-p)),t.copy(r).addScaledVector($n,o);let g=1/(h+m+d);return a=m*g,o=d*g,t.copy(n).addScaledVector(Zn,a).addScaledVector(Qn,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}},sr={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},cr={h:0,s:0,l:0},lr={h:0,s:0,l:0};function ur(e,t,n){return n<0&&(n+=1),n>1&&--n,n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*6*(2/3-n):e}var B=class{constructor(e,t,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,n)}set(e,t,n){if(t===void 0&&n===void 0){let t=e;t&&t.isColor?this.copy(t):typeof t==`number`?this.setHex(t):typeof t==`string`&&this.setStyle(t)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=Ie){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,kt.colorSpaceToWorking(this,t),this}setRGB(e,t,n,r=kt.workingColorSpace){return this.r=e,this.g=t,this.b=n,kt.colorSpaceToWorking(this,r),this}setHSL(e,t,n,r=kt.workingColorSpace){if(e=Ye(e,1),t=I(t,0,1),n=I(n,0,1),t===0)this.r=this.g=this.b=n;else{let r=n<=.5?n*(1+t):n+t-n*t,i=2*n-r;this.r=ur(i,r,e+1/3),this.g=ur(i,r,e),this.b=ur(i,r,e-1/3)}return kt.colorSpaceToWorking(this,r),this}setStyle(e,t=Ie){function n(t){t!==void 0&&parseFloat(t)<1&&console.warn(`THREE.Color: Alpha component of `+e+` will be ignored.`)}let r;if(r=/^(\w+)\(([^\)]*)\)/.exec(e)){let i,a=r[1],o=r[2];switch(a){case`rgb`:case`rgba`:if(i=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setRGB(Math.min(255,parseInt(i[1],10))/255,Math.min(255,parseInt(i[2],10))/255,Math.min(255,parseInt(i[3],10))/255,t);if(i=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setRGB(Math.min(100,parseInt(i[1],10))/100,Math.min(100,parseInt(i[2],10))/100,Math.min(100,parseInt(i[3],10))/100,t);break;case`hsl`:case`hsla`:if(i=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setHSL(parseFloat(i[1])/360,parseFloat(i[2])/100,parseFloat(i[3])/100,t);break;default:console.warn(`THREE.Color: Unknown color model `+e)}}else if(r=/^\#([A-Fa-f\d]+)$/.exec(e)){let n=r[1],i=n.length;if(i===3)return this.setRGB(parseInt(n.charAt(0),16)/15,parseInt(n.charAt(1),16)/15,parseInt(n.charAt(2),16)/15,t);if(i===6)return this.setHex(parseInt(n,16),t);console.warn(`THREE.Color: Invalid hex color `+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=Ie){let n=sr[e.toLowerCase()];return n===void 0?console.warn(`THREE.Color: Unknown color `+e):this.setHex(n,t),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=At(e.r),this.g=At(e.g),this.b=At(e.b),this}copyLinearToSRGB(e){return this.r=jt(e.r),this.g=jt(e.g),this.b=jt(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Ie){return kt.workingToColorSpace(dr.copy(this),e),Math.round(I(dr.r*255,0,255))*65536+Math.round(I(dr.g*255,0,255))*256+Math.round(I(dr.b*255,0,255))}getHexString(e=Ie){return(`000000`+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=kt.workingColorSpace){kt.workingToColorSpace(dr.copy(this),t);let n=dr.r,r=dr.g,i=dr.b,a=Math.max(n,r,i),o=Math.min(n,r,i),s,c,l=(o+a)/2;if(o===a)s=0,c=0;else{let e=a-o;switch(c=l<=.5?e/(a+o):e/(2-a-o),a){case n:s=(r-i)/e+(r<i?6:0);break;case r:s=(i-n)/e+2;break;case i:s=(n-r)/e+4;break}s/=6}return e.h=s,e.s=c,e.l=l,e}getRGB(e,t=kt.workingColorSpace){return kt.workingToColorSpace(dr.copy(this),t),e.r=dr.r,e.g=dr.g,e.b=dr.b,e}getStyle(e=Ie){kt.workingToColorSpace(dr.copy(this),e);let t=dr.r,n=dr.g,r=dr.b;return e===`srgb`?`rgb(${Math.round(t*255)},${Math.round(n*255)},${Math.round(r*255)})`:`color(${e} ${t.toFixed(3)} ${n.toFixed(3)} ${r.toFixed(3)})`}offsetHSL(e,t,n){return this.getHSL(cr),this.setHSL(cr.h+e,cr.s+t,cr.l+n)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,t){return this.r=e.r+t.r,this.g=e.g+t.g,this.b=e.b+t.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,t){return this.r+=(e.r-this.r)*t,this.g+=(e.g-this.g)*t,this.b+=(e.b-this.b)*t,this}lerpColors(e,t,n){return this.r=e.r+(t.r-e.r)*n,this.g=e.g+(t.g-e.g)*n,this.b=e.b+(t.b-e.b)*n,this}lerpHSL(e,t){this.getHSL(cr),e.getHSL(lr);let n=Qe(cr.h,lr.h,t),r=Qe(cr.s,lr.s,t),i=Qe(cr.l,lr.l,t);return this.setHSL(n,r,i),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){let t=this.r,n=this.g,r=this.b,i=e.elements;return this.r=i[0]*t+i[3]*n+i[6]*r,this.g=i[1]*t+i[4]*n+i[7]*r,this.b=i[2]*t+i[5]*n+i[8]*r,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}},dr=new B;B.NAMES=sr;var fr=0,pr=class extends Ue{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,`id`,{value:fr++}),this.uuid=Je(),this.name=``,this.type=`Material`,this.blending=1,this.side=0,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=204,this.blendDst=205,this.blendEquation=100,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new B(0,0,0),this.blendAlpha=0,this.depthFunc=3,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=519,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=Be,this.stencilZFail=Be,this.stencilZPass=Be,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(let t in e){let n=e[t];if(n===void 0){console.warn(`THREE.Material: parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){console.warn(`THREE.Material: '${t}' is not a property of THREE.${this.type}.`);continue}r&&r.isColor?r.set(n):r&&r.isVector3&&n&&n.isVector3?r.copy(n):this[t]=n}}toJSON(e){let t=e===void 0||typeof e==`string`;t&&(e={textures:{},images:{}});let n={metadata:{version:4.7,type:`Material`,generator:`Material.toJSON`}};n.uuid=this.uuid,n.type=this.type,this.name!==``&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),this.roughness!==void 0&&(n.roughness=this.roughness),this.metalness!==void 0&&(n.metalness=this.metalness),this.sheen!==void 0&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(n.shininess=this.shininess),this.clearcoat!==void 0&&(n.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(n.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(n.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(n.dispersion=this.dispersion),this.iridescence!==void 0&&(n.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(n.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(n.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(n.combine=this.combine)),this.envMapRotation!==void 0&&(n.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(n.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(n.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(n.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(n.size=this.size),this.shadowSide!==null&&(n.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),this.blending!==1&&(n.blending=this.blending),this.side!==0&&(n.side=this.side),this.vertexColors===!0&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),this.transparent===!0&&(n.transparent=!0),this.blendSrc!==204&&(n.blendSrc=this.blendSrc),this.blendDst!==205&&(n.blendDst=this.blendDst),this.blendEquation!==100&&(n.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(n.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(n.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(n.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(n.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(n.blendAlpha=this.blendAlpha),this.depthFunc!==3&&(n.depthFunc=this.depthFunc),this.depthTest===!1&&(n.depthTest=this.depthTest),this.depthWrite===!1&&(n.depthWrite=this.depthWrite),this.colorWrite===!1&&(n.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(n.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==519&&(n.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(n.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==7680&&(n.stencilFail=this.stencilFail),this.stencilZFail!==7680&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==7680&&(n.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(n.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(n.rotation=this.rotation),this.polygonOffset===!0&&(n.polygonOffset=!0),this.polygonOffsetFactor!==0&&(n.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(n.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(n.linewidth=this.linewidth),this.dashSize!==void 0&&(n.dashSize=this.dashSize),this.gapSize!==void 0&&(n.gapSize=this.gapSize),this.scale!==void 0&&(n.scale=this.scale),this.dithering===!0&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),this.alphaHash===!0&&(n.alphaHash=!0),this.alphaToCoverage===!0&&(n.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(n.premultipliedAlpha=!0),this.forceSinglePass===!0&&(n.forceSinglePass=!0),this.wireframe===!0&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!==`round`&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!==`round`&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(n.flatShading=!0),this.visible===!1&&(n.visible=!1),this.toneMapped===!1&&(n.toneMapped=!1),this.fog===!1&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData);function r(e){let t=[];for(let n in e){let r=e[n];delete r.metadata,t.push(r)}return t}if(t){let t=r(e.textures),i=r(e.images);t.length>0&&(n.textures=t),i.length>0&&(n.images=i)}return n}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;let t=e.clippingPlanes,n=null;if(t!==null){let e=t.length;n=Array(e);for(let r=0;r!==e;++r)n[r]=t[r].clone()}return this.clippingPlanes=n,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:`dispose`})}set needsUpdate(e){e===!0&&this.version++}},mr=class extends pr{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type=`MeshBasicMaterial`,this.color=new B(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new kn,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap=`round`,this.wireframeLinejoin=`round`,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}},hr=new R,gr=new L,_r=0,V=class{constructor(e,t,n=!1){if(Array.isArray(e))throw TypeError(`THREE.BufferAttribute: array should be a Typed Array.`);this.isBufferAttribute=!0,Object.defineProperty(this,`id`,{value:_r++}),this.name=``,this.array=e,this.itemSize=t,this.count=e===void 0?0:e.length/t,this.normalized=n,this.usage=Ve,this.updateRanges=[],this.gpuType=h,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,n){e*=this.itemSize,n*=t.itemSize;for(let r=0,i=this.itemSize;r<i;r++)this.array[e+r]=t.array[n+r];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let t=0,n=this.count;t<n;t++)gr.fromBufferAttribute(this,t),gr.applyMatrix3(e),this.setXY(t,gr.x,gr.y);else if(this.itemSize===3)for(let t=0,n=this.count;t<n;t++)hr.fromBufferAttribute(this,t),hr.applyMatrix3(e),this.setXYZ(t,hr.x,hr.y,hr.z);return this}applyMatrix4(e){for(let t=0,n=this.count;t<n;t++)hr.fromBufferAttribute(this,t),hr.applyMatrix4(e),this.setXYZ(t,hr.x,hr.y,hr.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)hr.fromBufferAttribute(this,t),hr.applyNormalMatrix(e),this.setXYZ(t,hr.x,hr.y,hr.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)hr.fromBufferAttribute(this,t),hr.transformDirection(e),this.setXYZ(t,hr.x,hr.y,hr.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let n=this.array[e*this.itemSize+t];return this.normalized&&(n=pt(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=mt(n,this.array)),this.array[e*this.itemSize+t]=n,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=pt(t,this.array)),t}setX(e,t){return this.normalized&&(t=mt(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=pt(t,this.array)),t}setY(e,t){return this.normalized&&(t=mt(t,this.array)),this.array[e*this.itemSize+1]=t,this}getZ(e){let t=this.array[e*this.itemSize+2];return this.normalized&&(t=pt(t,this.array)),t}setZ(e,t){return this.normalized&&(t=mt(t,this.array)),this.array[e*this.itemSize+2]=t,this}getW(e){let t=this.array[e*this.itemSize+3];return this.normalized&&(t=pt(t,this.array)),t}setW(e,t){return this.normalized&&(t=mt(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=mt(t,this.array),n=mt(n,this.array)),this.array[e+0]=t,this.array[e+1]=n,this}setXYZ(e,t,n,r){return e*=this.itemSize,this.normalized&&(t=mt(t,this.array),n=mt(n,this.array),r=mt(r,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=r,this}setXYZW(e,t,n,r,i){return e*=this.itemSize,this.normalized&&(t=mt(t,this.array),n=mt(n,this.array),r=mt(r,this.array),i=mt(i,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=r,this.array[e+3]=i,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){let e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return this.name!==``&&(e.name=this.name),this.usage!==35044&&(e.usage=this.usage),e}},vr=class extends V{constructor(e,t,n){super(new Uint16Array(e),t,n)}},yr=class extends V{constructor(e,t,n){super(new Uint32Array(e),t,n)}},br=class extends V{constructor(e,t,n){super(new Float32Array(e),t,n)}},xr=0,Sr=new yn,Cr=new Kn,wr=new R,Tr=new Gt,Er=new Gt,Dr=new R,H=class e extends Ue{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,`id`,{value:xr++}),this.uuid=Je(),this.name=``,this.type=`BufferGeometry`,this.index=null,this.indirect=null,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(bt(e)?yr:vr)(e,1):this.index=e,this}setIndirect(e){return this.indirect=e,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,t,n=0){this.groups.push({start:e,count:t,materialIndex:n})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){let t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);let n=this.attributes.normal;if(n!==void 0){let t=new z().getNormalMatrix(e);n.applyNormalMatrix(t),n.needsUpdate=!0}let r=this.attributes.tangent;return r!==void 0&&(r.transformDirection(e),r.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(e){return Sr.makeRotationFromQuaternion(e),this.applyMatrix4(Sr),this}rotateX(e){return Sr.makeRotationX(e),this.applyMatrix4(Sr),this}rotateY(e){return Sr.makeRotationY(e),this.applyMatrix4(Sr),this}rotateZ(e){return Sr.makeRotationZ(e),this.applyMatrix4(Sr),this}translate(e,t,n){return Sr.makeTranslation(e,t,n),this.applyMatrix4(Sr),this}scale(e,t,n){return Sr.makeScale(e,t,n),this.applyMatrix4(Sr),this}lookAt(e){return Cr.lookAt(e),Cr.updateMatrix(),this.applyMatrix4(Cr.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(wr).negate(),this.translate(wr.x,wr.y,wr.z),this}setFromPoints(e){let t=this.getAttribute(`position`);if(t===void 0){let t=[];for(let n=0,r=e.length;n<r;n++){let r=e[n];t.push(r.x,r.y,r.z||0)}this.setAttribute(`position`,new br(t,3))}else{let n=Math.min(e.length,t.count);for(let r=0;r<n;r++){let n=e[r];t.setXYZ(r,n.x,n.y,n.z||0)}e.length>t.count&&console.warn(`THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.`),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Gt);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error(`THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.`,this),this.boundingBox.set(new R(-1/0,-1/0,-1/0),new R(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e<n;e++){let n=t[e];Tr.setFromBufferAttribute(n),this.morphTargetsRelative?(Dr.addVectors(this.boundingBox.min,Tr.min),this.boundingBox.expandByPoint(Dr),Dr.addVectors(this.boundingBox.max,Tr.max),this.boundingBox.expandByPoint(Dr)):(this.boundingBox.expandByPoint(Tr.min),this.boundingBox.expandByPoint(Tr.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&console.error(`THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.`,this)}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new un);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error(`THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.`,this),this.boundingSphere.set(new R,1/0);return}if(e){let n=this.boundingSphere.center;if(Tr.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e<n;e++){let n=t[e];Er.setFromBufferAttribute(n),this.morphTargetsRelative?(Dr.addVectors(Tr.min,Er.min),Tr.expandByPoint(Dr),Dr.addVectors(Tr.max,Er.max),Tr.expandByPoint(Dr)):(Tr.expandByPoint(Er.min),Tr.expandByPoint(Er.max))}Tr.getCenter(n);let r=0;for(let t=0,i=e.count;t<i;t++)Dr.fromBufferAttribute(e,t),r=Math.max(r,n.distanceToSquared(Dr));if(t)for(let i=0,a=t.length;i<a;i++){let a=t[i],o=this.morphTargetsRelative;for(let t=0,i=a.count;t<i;t++)Dr.fromBufferAttribute(a,t),o&&(wr.fromBufferAttribute(e,t),Dr.add(wr)),r=Math.max(r,n.distanceToSquared(Dr))}this.boundingSphere.radius=Math.sqrt(r),isNaN(this.boundingSphere.radius)&&console.error(`THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.`,this)}}computeTangents(){let e=this.index,t=this.attributes;if(e===null||t.position===void 0||t.normal===void 0||t.uv===void 0){console.error(`THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)`);return}let n=t.position,r=t.normal,i=t.uv;this.hasAttribute(`tangent`)===!1&&this.setAttribute(`tangent`,new V(new Float32Array(4*n.count),4));let a=this.getAttribute(`tangent`),o=[],s=[];for(let e=0;e<n.count;e++)o[e]=new R,s[e]=new R;let c=new R,l=new R,u=new R,d=new L,f=new L,p=new L,m=new R,h=new R;function g(e,t,r){c.fromBufferAttribute(n,e),l.fromBufferAttribute(n,t),u.fromBufferAttribute(n,r),d.fromBufferAttribute(i,e),f.fromBufferAttribute(i,t),p.fromBufferAttribute(i,r),l.sub(c),u.sub(c),f.sub(d),p.sub(d);let a=1/(f.x*p.y-p.x*f.y);isFinite(a)&&(m.copy(l).multiplyScalar(p.y).addScaledVector(u,-f.y).multiplyScalar(a),h.copy(u).multiplyScalar(f.x).addScaledVector(l,-p.x).multiplyScalar(a),o[e].add(m),o[t].add(m),o[r].add(m),s[e].add(h),s[t].add(h),s[r].add(h))}let _=this.groups;_.length===0&&(_=[{start:0,count:e.count}]);for(let t=0,n=_.length;t<n;++t){let n=_[t],r=n.start,i=n.count;for(let t=r,n=r+i;t<n;t+=3)g(e.getX(t+0),e.getX(t+1),e.getX(t+2))}let v=new R,y=new R,b=new R,x=new R;function S(e){b.fromBufferAttribute(r,e),x.copy(b);let t=o[e];v.copy(t),v.sub(b.multiplyScalar(b.dot(t))).normalize(),y.crossVectors(x,t);let n=y.dot(s[e])<0?-1:1;a.setXYZW(e,v.x,v.y,v.z,n)}for(let t=0,n=_.length;t<n;++t){let n=_[t],r=n.start,i=n.count;for(let t=r,n=r+i;t<n;t+=3)S(e.getX(t+0)),S(e.getX(t+1)),S(e.getX(t+2))}}computeVertexNormals(){let e=this.index,t=this.getAttribute(`position`);if(t!==void 0){let n=this.getAttribute(`normal`);if(n===void 0)n=new V(new Float32Array(t.count*3),3),this.setAttribute(`normal`,n);else for(let e=0,t=n.count;e<t;e++)n.setXYZ(e,0,0,0);let r=new R,i=new R,a=new R,o=new R,s=new R,c=new R,l=new R,u=new R;if(e)for(let d=0,f=e.count;d<f;d+=3){let f=e.getX(d+0),p=e.getX(d+1),m=e.getX(d+2);r.fromBufferAttribute(t,f),i.fromBufferAttribute(t,p),a.fromBufferAttribute(t,m),l.subVectors(a,i),u.subVectors(r,i),l.cross(u),o.fromBufferAttribute(n,f),s.fromBufferAttribute(n,p),c.fromBufferAttribute(n,m),o.add(l),s.add(l),c.add(l),n.setXYZ(f,o.x,o.y,o.z),n.setXYZ(p,s.x,s.y,s.z),n.setXYZ(m,c.x,c.y,c.z)}else for(let e=0,o=t.count;e<o;e+=3)r.fromBufferAttribute(t,e+0),i.fromBufferAttribute(t,e+1),a.fromBufferAttribute(t,e+2),l.subVectors(a,i),u.subVectors(r,i),l.cross(u),n.setXYZ(e+0,l.x,l.y,l.z),n.setXYZ(e+1,l.x,l.y,l.z),n.setXYZ(e+2,l.x,l.y,l.z);this.normalizeNormals(),n.needsUpdate=!0}}normalizeNormals(){let e=this.attributes.normal;for(let t=0,n=e.count;t<n;t++)Dr.fromBufferAttribute(e,t),Dr.normalize(),e.setXYZ(t,Dr.x,Dr.y,Dr.z)}toNonIndexed(){function t(e,t){let n=e.array,r=e.itemSize,i=e.normalized,a=new n.constructor(t.length*r),o=0,s=0;for(let i=0,c=t.length;i<c;i++){o=e.isInterleavedBufferAttribute?t[i]*e.data.stride+e.offset:t[i]*r;for(let e=0;e<r;e++)a[s++]=n[o++]}return new V(a,r,i)}if(this.index===null)return console.warn(`THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.`),this;let n=new e,r=this.index.array,i=this.attributes;for(let e in i){let a=i[e],o=t(a,r);n.setAttribute(e,o)}let a=this.morphAttributes;for(let e in a){let i=[],o=a[e];for(let e=0,n=o.length;e<n;e++){let n=o[e],a=t(n,r);i.push(a)}n.morphAttributes[e]=i}n.morphTargetsRelative=this.morphTargetsRelative;let o=this.groups;for(let e=0,t=o.length;e<t;e++){let t=o[e];n.addGroup(t.start,t.count,t.materialIndex)}return n}toJSON(){let e={metadata:{version:4.7,type:`BufferGeometry`,generator:`BufferGeometry.toJSON`}};if(e.uuid=this.uuid,e.type=this.type,this.name!==``&&(e.name=this.name),Object.keys(this.userData).length>0&&(e.userData=this.userData),this.parameters!==void 0){let t=this.parameters;for(let n in t)t[n]!==void 0&&(e[n]=t[n]);return e}e.data={attributes:{}};let t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});let n=this.attributes;for(let t in n){let r=n[t];e.data.attributes[t]=r.toJSON(e.data)}let r={},i=!1;for(let t in this.morphAttributes){let n=this.morphAttributes[t],a=[];for(let t=0,r=n.length;t<r;t++){let r=n[t];a.push(r.toJSON(e.data))}a.length>0&&(r[t]=a,i=!0)}i&&(e.data.morphAttributes=r,e.data.morphTargetsRelative=this.morphTargetsRelative);let a=this.groups;a.length>0&&(e.data.groups=JSON.parse(JSON.stringify(a)));let o=this.boundingSphere;return o!==null&&(e.data.boundingSphere=o.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;let t={};this.name=e.name;let n=e.index;n!==null&&this.setIndex(n.clone());let r=e.attributes;for(let e in r){let n=r[e];this.setAttribute(e,n.clone(t))}let i=e.morphAttributes;for(let e in i){let n=[],r=i[e];for(let e=0,i=r.length;e<i;e++)n.push(r[e].clone(t));this.morphAttributes[e]=n}this.morphTargetsRelative=e.morphTargetsRelative;let a=e.groups;for(let e=0,t=a.length;e<t;e++){let t=a[e];this.addGroup(t.start,t.count,t.materialIndex)}let o=e.boundingBox;o!==null&&(this.boundingBox=o.clone());let s=e.boundingSphere;return s!==null&&(this.boundingSphere=s.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this}dispose(){this.dispatchEvent({type:`dispose`})}},Or=new yn,kr=new vn,Ar=new un,jr=new R,Mr=new R,Nr=new R,Pr=new R,Fr=new R,Ir=new R,Lr=new R,Rr=new R,U=class extends Kn{constructor(e=new H,t=new mr){super(),this.isMesh=!0,this.type=`Mesh`,this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),e.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),e.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){let e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){let n=e[t[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e<t;e++){let t=n[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[t]=e}}}}getVertexPosition(e,t){let n=this.geometry,r=n.attributes.position,i=n.morphAttributes.position,a=n.morphTargetsRelative;t.fromBufferAttribute(r,e);let o=this.morphTargetInfluences;if(i&&o){Ir.set(0,0,0);for(let n=0,r=i.length;n<r;n++){let r=o[n],s=i[n];r!==0&&(Fr.fromBufferAttribute(s,e),a?Ir.addScaledVector(Fr,r):Ir.addScaledVector(Fr.sub(t),r))}t.add(Ir)}return t}raycast(e,t){let n=this.geometry,r=this.material,i=this.matrixWorld;r!==void 0&&(n.boundingSphere===null&&n.computeBoundingSphere(),Ar.copy(n.boundingSphere),Ar.applyMatrix4(i),kr.copy(e.ray).recast(e.near),!(Ar.containsPoint(kr.origin)===!1&&(kr.intersectSphere(Ar,jr)===null||kr.origin.distanceToSquared(jr)>(e.far-e.near)**2))&&(Or.copy(i).invert(),kr.copy(e.ray).applyMatrix4(Or),!(n.boundingBox!==null&&kr.intersectsBox(n.boundingBox)===!1)&&this._computeIntersections(e,t,kr)))}_computeIntersections(e,t,n){let r,i=this.geometry,a=this.material,o=i.index,s=i.attributes.position,c=i.attributes.uv,l=i.attributes.uv1,u=i.attributes.normal,d=i.groups,f=i.drawRange;if(o!==null)if(Array.isArray(a))for(let i=0,s=d.length;i<s;i++){let s=d[i],p=a[s.materialIndex],m=Math.max(s.start,f.start),h=Math.min(o.count,Math.min(s.start+s.count,f.start+f.count));for(let i=m,a=h;i<a;i+=3){let a=o.getX(i),d=o.getX(i+1),f=o.getX(i+2);r=Br(this,p,e,n,c,l,u,a,d,f),r&&(r.faceIndex=Math.floor(i/3),r.face.materialIndex=s.materialIndex,t.push(r))}}else{let i=Math.max(0,f.start),s=Math.min(o.count,f.start+f.count);for(let d=i,f=s;d<f;d+=3){let i=o.getX(d),s=o.getX(d+1),f=o.getX(d+2);r=Br(this,a,e,n,c,l,u,i,s,f),r&&(r.faceIndex=Math.floor(d/3),t.push(r))}}else if(s!==void 0)if(Array.isArray(a))for(let i=0,o=d.length;i<o;i++){let o=d[i],p=a[o.materialIndex],m=Math.max(o.start,f.start),h=Math.min(s.count,Math.min(o.start+o.count,f.start+f.count));for(let i=m,a=h;i<a;i+=3){let a=i,s=i+1,d=i+2;r=Br(this,p,e,n,c,l,u,a,s,d),r&&(r.faceIndex=Math.floor(i/3),r.face.materialIndex=o.materialIndex,t.push(r))}}else{let i=Math.max(0,f.start),o=Math.min(s.count,f.start+f.count);for(let s=i,d=o;s<d;s+=3){let i=s,o=s+1,d=s+2;r=Br(this,a,e,n,c,l,u,i,o,d),r&&(r.faceIndex=Math.floor(s/3),t.push(r))}}}};function zr(e,t,n,r,i,a,o,s){let c;if(c=t.side===1?r.intersectTriangle(o,a,i,!0,s):r.intersectTriangle(i,a,o,t.side===0,s),c===null)return null;Rr.copy(s),Rr.applyMatrix4(e.matrixWorld);let l=n.ray.origin.distanceTo(Rr);return l<n.near||l>n.far?null:{distance:l,point:Rr.clone(),object:e}}function Br(e,t,n,r,i,a,o,s,c,l){e.getVertexPosition(s,Mr),e.getVertexPosition(c,Nr),e.getVertexPosition(l,Pr);let u=zr(e,t,n,r,Mr,Nr,Pr,Lr);if(u){let e=new R;or.getBarycoord(Lr,Mr,Nr,Pr,e),i&&(u.uv=or.getInterpolatedAttribute(i,s,c,l,e,new L)),a&&(u.uv1=or.getInterpolatedAttribute(a,s,c,l,e,new L)),o&&(u.normal=or.getInterpolatedAttribute(o,s,c,l,e,new R),u.normal.dot(r.direction)>0&&u.normal.multiplyScalar(-1));let t={a:s,b:c,c:l,normal:new R,materialIndex:0};or.getNormal(Mr,Nr,Pr,t.normal),u.face=t,u.barycoord=e}return u}var Vr=class e extends H{constructor(e=1,t=1,n=1,r=1,i=1,a=1){super(),this.type=`BoxGeometry`,this.parameters={width:e,height:t,depth:n,widthSegments:r,heightSegments:i,depthSegments:a};let o=this;r=Math.floor(r),i=Math.floor(i),a=Math.floor(a);let s=[],c=[],l=[],u=[],d=0,f=0;p(`z`,`y`,`x`,-1,-1,n,t,e,a,i,0),p(`z`,`y`,`x`,1,-1,n,t,-e,a,i,1),p(`x`,`z`,`y`,1,1,e,n,t,r,a,2),p(`x`,`z`,`y`,1,-1,e,n,-t,r,a,3),p(`x`,`y`,`z`,1,-1,e,t,n,r,i,4),p(`x`,`y`,`z`,-1,-1,e,t,-n,r,i,5),this.setIndex(s),this.setAttribute(`position`,new br(c,3)),this.setAttribute(`normal`,new br(l,3)),this.setAttribute(`uv`,new br(u,2));function p(e,t,n,r,i,a,p,m,h,g,_){let v=a/h,y=p/g,b=a/2,x=p/2,S=m/2,C=h+1,w=g+1,T=0,E=0,D=new R;for(let a=0;a<w;a++){let o=a*y-x;for(let s=0;s<C;s++)D[e]=(s*v-b)*r,D[t]=o*i,D[n]=S,c.push(D.x,D.y,D.z),D[e]=0,D[t]=0,D[n]=m>0?1:-1,l.push(D.x,D.y,D.z),u.push(s/h),u.push(1-a/g),T+=1}for(let e=0;e<g;e++)for(let t=0;t<h;t++){let n=d+t+C*e,r=d+t+C*(e+1),i=d+(t+1)+C*(e+1),a=d+(t+1)+C*e;s.push(n,r,a),s.push(r,i,a),E+=6}o.addGroup(f,E,_),f+=E,d+=T}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(t){return new e(t.width,t.height,t.depth,t.widthSegments,t.heightSegments,t.depthSegments)}};function Hr(e){let t={};for(let n in e){t[n]={};for(let r in e[n]){let i=e[n][r];i&&(i.isColor||i.isMatrix3||i.isMatrix4||i.isVector2||i.isVector3||i.isVector4||i.isTexture||i.isQuaternion)?i.isRenderTargetTexture?(console.warn(`UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().`),t[n][r]=null):t[n][r]=i.clone():Array.isArray(i)?t[n][r]=i.slice():t[n][r]=i}}return t}function Ur(e){let t={};for(let n=0;n<e.length;n++){let r=Hr(e[n]);for(let e in r)t[e]=r[e]}return t}function Wr(e){let t=[];for(let n=0;n<e.length;n++)t.push(e[n].clone());return t}function Gr(e){let t=e.getRenderTarget();return t===null?e.outputColorSpace:t.isXRRenderTarget===!0?t.texture.colorSpace:kt.workingColorSpace}var Kr={clone:Hr,merge:Ur},qr=`void main() {
2
2
  gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
3
- }`,Yr=`void main() {
3
+ }`,Jr=`void main() {
4
4
  gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
5
- }`,Xr=class extends pr{constructor(e){super(),this.isShaderMaterial=!0,this.type=`ShaderMaterial`,this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=Jr,this.fragmentShader=Yr,this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,e!==void 0&&this.setValues(e)}copy(e){return super.copy(e),this.fragmentShader=e.fragmentShader,this.vertexShader=e.vertexShader,this.uniforms=Ur(e.uniforms),this.uniformsGroups=Gr(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this}toJSON(e){let t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(let n in this.uniforms){let r=this.uniforms[n].value;r&&r.isTexture?t.uniforms[n]={type:`t`,value:r.toJSON(e).uuid}:r&&r.isColor?t.uniforms[n]={type:`c`,value:r.getHex()}:r&&r.isVector2?t.uniforms[n]={type:`v2`,value:r.toArray()}:r&&r.isVector3?t.uniforms[n]={type:`v3`,value:r.toArray()}:r&&r.isVector4?t.uniforms[n]={type:`v4`,value:r.toArray()}:r&&r.isMatrix3?t.uniforms[n]={type:`m3`,value:r.toArray()}:r&&r.isMatrix4?t.uniforms[n]={type:`m4`,value:r.toArray()}:t.uniforms[n]={value:r}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;let n={};for(let e in this.extensions)this.extensions[e]===!0&&(n[e]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}},Zr=class extends Kn{constructor(){super(),this.isCamera=!0,this.type=`Camera`,this.matrixWorldInverse=new yn,this.projectionMatrix=new yn,this.projectionMatrixInverse=new yn,this.coordinateSystem=He,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}},Qr=new R,$r=new L,ei=new L,ti=class extends Zr{constructor(e=50,t=1,n=.1,r=2e3){super(),this.isPerspectiveCamera=!0,this.type=`PerspectiveCamera`,this.fov=e,this.zoom=1,this.near=n,this.far=r,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){let t=.5*this.getFilmHeight()/e;this.fov=qe*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){let e=Math.tan(Ke*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return qe*2*Math.atan(Math.tan(Ke*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,n){Qr.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(Qr.x,Qr.y).multiplyScalar(-e/Qr.z),Qr.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(Qr.x,Qr.y).multiplyScalar(-e/Qr.z)}getViewSize(e,t){return this.getViewBounds(e,$r,ei),t.subVectors(ei,$r)}setViewOffset(e,t,n,r,i,a){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=r,this.view.width=i,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let e=this.near,t=e*Math.tan(Ke*.5*this.fov)/this.zoom,n=2*t,r=this.aspect*n,i=-.5*r,a=this.view;if(this.view!==null&&this.view.enabled){let e=a.fullWidth,o=a.fullHeight;i+=a.offsetX*r/e,t-=a.offsetY*n/o,r*=a.width/e,n*=a.height/o}let o=this.filmOffset;o!==0&&(i+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(i,i+r,t,t-n,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}},ni=-90,ri=1,ii=class extends Kn{constructor(e,t,n){super(),this.type=`CubeCamera`,this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;let r=new ti(ni,ri,e,t);r.layers=this.layers,this.add(r);let i=new ti(ni,ri,e,t);i.layers=this.layers,this.add(i);let a=new ti(ni,ri,e,t);a.layers=this.layers,this.add(a);let o=new ti(ni,ri,e,t);o.layers=this.layers,this.add(o);let s=new ti(ni,ri,e,t);s.layers=this.layers,this.add(s);let c=new ti(ni,ri,e,t);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){let e=this.coordinateSystem,t=this.children.concat(),[n,r,i,a,o,s]=t;for(let e of t)this.remove(e);if(e===2e3)n.up.set(0,1,0),n.lookAt(1,0,0),r.up.set(0,1,0),r.lookAt(-1,0,0),i.up.set(0,0,-1),i.lookAt(0,1,0),a.up.set(0,0,1),a.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),s.up.set(0,1,0),s.lookAt(0,0,-1);else if(e===2001)n.up.set(0,-1,0),n.lookAt(-1,0,0),r.up.set(0,-1,0),r.lookAt(1,0,0),i.up.set(0,0,1),i.lookAt(0,1,0),a.up.set(0,0,-1),a.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),s.up.set(0,-1,0),s.lookAt(0,0,-1);else throw Error(`THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: `+e);for(let e of t)this.add(e),e.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();let{renderTarget:n,activeMipmapLevel:r}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());let[i,a,o,s,c,l]=this.children,u=e.getRenderTarget(),d=e.getActiveCubeFace(),f=e.getActiveMipmapLevel(),p=e.xr.enabled;e.xr.enabled=!1;let m=n.texture.generateMipmaps;n.texture.generateMipmaps=!1,e.setRenderTarget(n,0,r),e.render(t,i),e.setRenderTarget(n,1,r),e.render(t,a),e.setRenderTarget(n,2,r),e.render(t,o),e.setRenderTarget(n,3,r),e.render(t,s),e.setRenderTarget(n,4,r),e.render(t,c),n.texture.generateMipmaps=m,e.setRenderTarget(n,5,r),e.render(t,l),e.setRenderTarget(u,d,f),e.xr.enabled=p,n.texture.needsPMREMUpdate=!0}},ai=class extends zt{constructor(e=[],t=301,n,r,i,a,o,s,c,l){super(e,t,n,r,i,a,o,s,c,l),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}},oi=class extends Ht{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;let n={width:e,height:e,depth:1};this.texture=new ai([n,n,n,n,n,n]),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;let n={uniforms:{tEquirect:{value:null}},vertexShader:`
5
+ }`,Yr=class extends pr{constructor(e){super(),this.isShaderMaterial=!0,this.type=`ShaderMaterial`,this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=qr,this.fragmentShader=Jr,this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,e!==void 0&&this.setValues(e)}copy(e){return super.copy(e),this.fragmentShader=e.fragmentShader,this.vertexShader=e.vertexShader,this.uniforms=Hr(e.uniforms),this.uniformsGroups=Wr(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this}toJSON(e){let t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(let n in this.uniforms){let r=this.uniforms[n].value;r&&r.isTexture?t.uniforms[n]={type:`t`,value:r.toJSON(e).uuid}:r&&r.isColor?t.uniforms[n]={type:`c`,value:r.getHex()}:r&&r.isVector2?t.uniforms[n]={type:`v2`,value:r.toArray()}:r&&r.isVector3?t.uniforms[n]={type:`v3`,value:r.toArray()}:r&&r.isVector4?t.uniforms[n]={type:`v4`,value:r.toArray()}:r&&r.isMatrix3?t.uniforms[n]={type:`m3`,value:r.toArray()}:r&&r.isMatrix4?t.uniforms[n]={type:`m4`,value:r.toArray()}:t.uniforms[n]={value:r}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;let n={};for(let e in this.extensions)this.extensions[e]===!0&&(n[e]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}},Xr=class extends Kn{constructor(){super(),this.isCamera=!0,this.type=`Camera`,this.matrixWorldInverse=new yn,this.projectionMatrix=new yn,this.projectionMatrixInverse=new yn,this.coordinateSystem=He,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}},Zr=new R,Qr=new L,$r=new L,ei=class extends Xr{constructor(e=50,t=1,n=.1,r=2e3){super(),this.isPerspectiveCamera=!0,this.type=`PerspectiveCamera`,this.fov=e,this.zoom=1,this.near=n,this.far=r,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){let t=.5*this.getFilmHeight()/e;this.fov=qe*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){let e=Math.tan(Ke*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return qe*2*Math.atan(Math.tan(Ke*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,n){Zr.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(Zr.x,Zr.y).multiplyScalar(-e/Zr.z),Zr.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(Zr.x,Zr.y).multiplyScalar(-e/Zr.z)}getViewSize(e,t){return this.getViewBounds(e,Qr,$r),t.subVectors($r,Qr)}setViewOffset(e,t,n,r,i,a){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=r,this.view.width=i,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let e=this.near,t=e*Math.tan(Ke*.5*this.fov)/this.zoom,n=2*t,r=this.aspect*n,i=-.5*r,a=this.view;if(this.view!==null&&this.view.enabled){let e=a.fullWidth,o=a.fullHeight;i+=a.offsetX*r/e,t-=a.offsetY*n/o,r*=a.width/e,n*=a.height/o}let o=this.filmOffset;o!==0&&(i+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(i,i+r,t,t-n,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}},ti=-90,ni=1,ri=class extends Kn{constructor(e,t,n){super(),this.type=`CubeCamera`,this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;let r=new ei(ti,ni,e,t);r.layers=this.layers,this.add(r);let i=new ei(ti,ni,e,t);i.layers=this.layers,this.add(i);let a=new ei(ti,ni,e,t);a.layers=this.layers,this.add(a);let o=new ei(ti,ni,e,t);o.layers=this.layers,this.add(o);let s=new ei(ti,ni,e,t);s.layers=this.layers,this.add(s);let c=new ei(ti,ni,e,t);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){let e=this.coordinateSystem,t=this.children.concat(),[n,r,i,a,o,s]=t;for(let e of t)this.remove(e);if(e===2e3)n.up.set(0,1,0),n.lookAt(1,0,0),r.up.set(0,1,0),r.lookAt(-1,0,0),i.up.set(0,0,-1),i.lookAt(0,1,0),a.up.set(0,0,1),a.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),s.up.set(0,1,0),s.lookAt(0,0,-1);else if(e===2001)n.up.set(0,-1,0),n.lookAt(-1,0,0),r.up.set(0,-1,0),r.lookAt(1,0,0),i.up.set(0,0,1),i.lookAt(0,1,0),a.up.set(0,0,-1),a.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),s.up.set(0,-1,0),s.lookAt(0,0,-1);else throw Error(`THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: `+e);for(let e of t)this.add(e),e.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();let{renderTarget:n,activeMipmapLevel:r}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());let[i,a,o,s,c,l]=this.children,u=e.getRenderTarget(),d=e.getActiveCubeFace(),f=e.getActiveMipmapLevel(),p=e.xr.enabled;e.xr.enabled=!1;let m=n.texture.generateMipmaps;n.texture.generateMipmaps=!1,e.setRenderTarget(n,0,r),e.render(t,i),e.setRenderTarget(n,1,r),e.render(t,a),e.setRenderTarget(n,2,r),e.render(t,o),e.setRenderTarget(n,3,r),e.render(t,s),e.setRenderTarget(n,4,r),e.render(t,c),n.texture.generateMipmaps=m,e.setRenderTarget(n,5,r),e.render(t,l),e.setRenderTarget(u,d,f),e.xr.enabled=p,n.texture.needsPMREMUpdate=!0}},ii=class extends zt{constructor(e=[],t=301,n,r,i,a,o,s,c,l){super(e,t,n,r,i,a,o,s,c,l),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}},ai=class extends Ht{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;let n={width:e,height:e,depth:1};this.texture=new ii([n,n,n,n,n,n]),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;let n={uniforms:{tEquirect:{value:null}},vertexShader:`
6
6
 
7
7
  varying vec3 vWorldDirection;
8
8
 
@@ -37,7 +37,7 @@
37
37
  gl_FragColor = texture2D( tEquirect, sampleUV );
38
38
 
39
39
  }
40
- `},r=new Hr(5,5,5),i=new Xr({name:`CubemapFromEquirect`,uniforms:Ur(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:1,blending:0});i.uniforms.tEquirect.value=t;let a=new H(r,i),s=t.minFilter;return t.minFilter===1008&&(t.minFilter=o),new ii(1,10,this).update(e,a),t.minFilter=s,a.geometry.dispose(),a.material.dispose(),this}clear(e,t=!0,n=!0,r=!0){let i=e.getRenderTarget();for(let i=0;i<6;i++)e.setRenderTarget(this,i),e.clear(t,n,r);e.setRenderTarget(i)}},si=class extends Kn{constructor(){super(),this.isGroup=!0,this.type=`Group`}},ci={type:`move`},li=class{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new si,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new si,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new R,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new R),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new si,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new R,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new R),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){let t=this._hand;if(t)for(let n of e.hand.values())this._getHandJoint(t,n)}return this.dispatchEvent({type:`connected`,data:e}),this}disconnect(e){return this.dispatchEvent({type:`disconnected`,data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,n){let r=null,i=null,a=null,o=this._targetRay,s=this._grip,c=this._hand;if(e&&t.session.visibilityState!==`visible-blurred`){if(c&&e.hand){a=!0;for(let r of e.hand.values()){let e=t.getJointPose(r,n),i=this._getHandJoint(c,r);e!==null&&(i.matrix.fromArray(e.transform.matrix),i.matrix.decompose(i.position,i.rotation,i.scale),i.matrixWorldNeedsUpdate=!0,i.jointRadius=e.radius),i.visible=e!==null}let r=c.joints[`index-finger-tip`],i=c.joints[`thumb-tip`],o=r.position.distanceTo(i.position),s=.02,l=.005;c.inputState.pinching&&o>s+l?(c.inputState.pinching=!1,this.dispatchEvent({type:`pinchend`,handedness:e.handedness,target:this})):!c.inputState.pinching&&o<=s-l&&(c.inputState.pinching=!0,this.dispatchEvent({type:`pinchstart`,handedness:e.handedness,target:this}))}else s!==null&&e.gripSpace&&(i=t.getPose(e.gripSpace,n),i!==null&&(s.matrix.fromArray(i.transform.matrix),s.matrix.decompose(s.position,s.rotation,s.scale),s.matrixWorldNeedsUpdate=!0,i.linearVelocity?(s.hasLinearVelocity=!0,s.linearVelocity.copy(i.linearVelocity)):s.hasLinearVelocity=!1,i.angularVelocity?(s.hasAngularVelocity=!0,s.angularVelocity.copy(i.angularVelocity)):s.hasAngularVelocity=!1));o!==null&&(r=t.getPose(e.targetRaySpace,n),r===null&&i!==null&&(r=i),r!==null&&(o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,r.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(r.linearVelocity)):o.hasLinearVelocity=!1,r.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(r.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(ci)))}return o!==null&&(o.visible=r!==null),s!==null&&(s.visible=i!==null),c!==null&&(c.visible=a!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){let n=new si;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}},ui=class extends Kn{constructor(){super(),this.isScene=!0,this.type=`Scene`,this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new kn,this.environmentIntensity=1,this.environmentRotation=new kn,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`observe`,{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){let t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}},di=class{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=e===void 0?0:e.length/t,this.usage=Ve,this.updateRanges=[],this.version=0,this.uuid=Je()}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,t,n){e*=this.stride,n*=t.stride;for(let r=0,i=this.stride;r<i;r++)this.array[e+r]=t.array[n+r];return this}set(e,t=0){return this.array.set(e,t),this}clone(e){e.arrayBuffers===void 0&&(e.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=Je()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=this.array.slice(0).buffer);let t=new this.array.constructor(e.arrayBuffers[this.array.buffer._uuid]),n=new this.constructor(t,this.stride);return n.setUsage(this.usage),n}onUpload(e){return this.onUploadCallback=e,this}toJSON(e){return e.arrayBuffers===void 0&&(e.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=Je()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=Array.from(new Uint32Array(this.array.buffer))),{uuid:this.uuid,buffer:this.array.buffer._uuid,type:this.array.constructor.name,stride:this.stride}}},fi=new R,pi=class e{constructor(e,t,n,r=!1){this.isInterleavedBufferAttribute=!0,this.name=``,this.data=e,this.itemSize=t,this.offset=n,this.normalized=r}get count(){return this.data.count}get array(){return this.data.array}set needsUpdate(e){this.data.needsUpdate=e}applyMatrix4(e){for(let t=0,n=this.data.count;t<n;t++)fi.fromBufferAttribute(this,t),fi.applyMatrix4(e),this.setXYZ(t,fi.x,fi.y,fi.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)fi.fromBufferAttribute(this,t),fi.applyNormalMatrix(e),this.setXYZ(t,fi.x,fi.y,fi.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)fi.fromBufferAttribute(this,t),fi.transformDirection(e),this.setXYZ(t,fi.x,fi.y,fi.z);return this}getComponent(e,t){let n=this.array[e*this.data.stride+this.offset+t];return this.normalized&&(n=pt(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=mt(n,this.array)),this.data.array[e*this.data.stride+this.offset+t]=n,this}setX(e,t){return this.normalized&&(t=mt(t,this.array)),this.data.array[e*this.data.stride+this.offset]=t,this}setY(e,t){return this.normalized&&(t=mt(t,this.array)),this.data.array[e*this.data.stride+this.offset+1]=t,this}setZ(e,t){return this.normalized&&(t=mt(t,this.array)),this.data.array[e*this.data.stride+this.offset+2]=t,this}setW(e,t){return this.normalized&&(t=mt(t,this.array)),this.data.array[e*this.data.stride+this.offset+3]=t,this}getX(e){let t=this.data.array[e*this.data.stride+this.offset];return this.normalized&&(t=pt(t,this.array)),t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(t=pt(t,this.array)),t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(t=pt(t,this.array)),t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(t=pt(t,this.array)),t}setXY(e,t,n){return e=e*this.data.stride+this.offset,this.normalized&&(t=mt(t,this.array),n=mt(n,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this}setXYZ(e,t,n,r){return e=e*this.data.stride+this.offset,this.normalized&&(t=mt(t,this.array),n=mt(n,this.array),r=mt(r,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this.data.array[e+2]=r,this}setXYZW(e,t,n,r,i){return e=e*this.data.stride+this.offset,this.normalized&&(t=mt(t,this.array),n=mt(n,this.array),r=mt(r,this.array),i=mt(i,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this.data.array[e+2]=r,this.data.array[e+3]=i,this}clone(t){if(t===void 0){console.log(`THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.`);let e=[];for(let t=0;t<this.count;t++){let n=t*this.data.stride+this.offset;for(let t=0;t<this.itemSize;t++)e.push(this.data.array[n+t])}return new V(new this.array.constructor(e),this.itemSize,this.normalized)}else return t.interleavedBuffers===void 0&&(t.interleavedBuffers={}),t.interleavedBuffers[this.data.uuid]===void 0&&(t.interleavedBuffers[this.data.uuid]=this.data.clone(t)),new e(t.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(e){if(e===void 0){console.log(`THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.`);let e=[];for(let t=0;t<this.count;t++){let n=t*this.data.stride+this.offset;for(let t=0;t<this.itemSize;t++)e.push(this.data.array[n+t])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:e,normalized:this.normalized}}else return e.interleavedBuffers===void 0&&(e.interleavedBuffers={}),e.interleavedBuffers[this.data.uuid]===void 0&&(e.interleavedBuffers[this.data.uuid]=this.data.toJSON(e)),{isInterleavedBufferAttribute:!0,itemSize:this.itemSize,data:this.data.uuid,offset:this.offset,normalized:this.normalized}}},mi=class extends pr{constructor(e){super(),this.isSpriteMaterial=!0,this.type=`SpriteMaterial`,this.color=new B(16777215),this.map=null,this.alphaMap=null,this.rotation=0,this.sizeAttenuation=!0,this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.rotation=e.rotation,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}},hi,gi=new R,_i=new R,vi=new R,yi=new L,bi=new L,xi=new yn,Si=new R,Ci=new R,wi=new R,Ti=new L,Ei=new L,Di=new L,Oi=class extends Kn{constructor(e=new mi){if(super(),this.isSprite=!0,this.type=`Sprite`,hi===void 0){hi=new Or;let e=new di(new Float32Array([-.5,-.5,0,0,0,.5,-.5,0,1,0,.5,.5,0,1,1,-.5,.5,0,0,1]),5);hi.setIndex([0,1,2,0,2,3]),hi.setAttribute(`position`,new pi(e,3,0,!1)),hi.setAttribute(`uv`,new pi(e,2,3,!1))}this.geometry=hi,this.material=e,this.center=new L(.5,.5),this.count=1}raycast(e,t){e.camera===null&&console.error(`THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.`),_i.setFromMatrixScale(this.matrixWorld),xi.copy(e.camera.matrixWorld),this.modelViewMatrix.multiplyMatrices(e.camera.matrixWorldInverse,this.matrixWorld),vi.setFromMatrixPosition(this.modelViewMatrix),e.camera.isPerspectiveCamera&&this.material.sizeAttenuation===!1&&_i.multiplyScalar(-vi.z);let n=this.material.rotation,r,i;n!==0&&(i=Math.cos(n),r=Math.sin(n));let a=this.center;ki(Si.set(-.5,-.5,0),vi,a,_i,r,i),ki(Ci.set(.5,-.5,0),vi,a,_i,r,i),ki(wi.set(.5,.5,0),vi,a,_i,r,i),Ti.set(0,0),Ei.set(1,0),Di.set(1,1);let o=e.ray.intersectTriangle(Si,Ci,wi,!1,gi);if(o===null&&(ki(Ci.set(-.5,.5,0),vi,a,_i,r,i),Ei.set(0,1),o=e.ray.intersectTriangle(Si,wi,Ci,!1,gi),o===null))return;let s=e.ray.origin.distanceTo(gi);s<e.near||s>e.far||t.push({distance:s,point:gi.clone(),uv:or.getInterpolation(gi,Si,Ci,wi,Ti,Ei,Di,new L),face:null,object:this})}copy(e,t){return super.copy(e,t),e.center!==void 0&&this.center.copy(e.center),this.material=e.material,this}};function ki(e,t,n,r,i,a){yi.subVectors(e,n).addScalar(.5).multiply(r),i===void 0?bi.copy(yi):(bi.x=a*yi.x-i*yi.y,bi.y=i*yi.x+a*yi.y),e.copy(t),e.x+=bi.x,e.y+=bi.y,e.applyMatrix4(xi)}var Ai=new R,ji=new R,Mi=new z,Ni=class{constructor(e=new R(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,n,r){return this.normal.set(e,t,n),this.constant=r,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,n){let r=Ai.subVectors(n,t).cross(ji.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(r,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){let e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t){let n=e.delta(Ai),r=this.normal.dot(n);if(r===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;let i=-(e.start.dot(this.normal)+this.constant)/r;return i<0||i>1?null:t.copy(e.start).addScaledVector(n,i)}intersectsLine(e){let t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){let n=t||Mi.getNormalMatrix(e),r=this.coplanarPoint(Ai).applyMatrix4(e),i=this.normal.applyMatrix3(n).normalize();return this.constant=-r.dot(i),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}},Pi=new un,Fi=new L(.5,.5),Ii=new R,Li=class{constructor(e=new Ni,t=new Ni,n=new Ni,r=new Ni,i=new Ni,a=new Ni){this.planes=[e,t,n,r,i,a]}set(e,t,n,r,i,a){let o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(n),o[3].copy(r),o[4].copy(i),o[5].copy(a),this}copy(e){let t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=He,n=!1){let r=this.planes,i=e.elements,a=i[0],o=i[1],s=i[2],c=i[3],l=i[4],u=i[5],d=i[6],f=i[7],p=i[8],m=i[9],h=i[10],g=i[11],_=i[12],v=i[13],y=i[14],b=i[15];if(r[0].setComponents(c-a,f-l,g-p,b-_).normalize(),r[1].setComponents(c+a,f+l,g+p,b+_).normalize(),r[2].setComponents(c+o,f+u,g+m,b+v).normalize(),r[3].setComponents(c-o,f-u,g-m,b-v).normalize(),n)r[4].setComponents(s,d,h,y).normalize(),r[5].setComponents(c-s,f-d,g-h,b-y).normalize();else if(r[4].setComponents(c-s,f-d,g-h,b-y).normalize(),t===2e3)r[5].setComponents(c+s,f+d,g+h,b+y).normalize();else if(t===2001)r[5].setComponents(s,d,h,y).normalize();else throw Error(`THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: `+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),Pi.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{let t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),Pi.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Pi)}intersectsSprite(e){return Pi.center.set(0,0,0),Pi.radius=.7071067811865476+Fi.distanceTo(e.center),Pi.applyMatrix4(e.matrixWorld),this.intersectsSphere(Pi)}intersectsSphere(e){let t=this.planes,n=e.center,r=-e.radius;for(let e=0;e<6;e++)if(t[e].distanceToPoint(n)<r)return!1;return!0}intersectsBox(e){let t=this.planes;for(let n=0;n<6;n++){let r=t[n];if(Ii.x=r.normal.x>0?e.max.x:e.min.x,Ii.y=r.normal.y>0?e.max.y:e.min.y,Ii.z=r.normal.z>0?e.max.z:e.min.z,r.distanceToPoint(Ii)<0)return!1}return!0}containsPoint(e){let t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}},Ri=class extends pr{constructor(e){super(),this.isLineBasicMaterial=!0,this.type=`LineBasicMaterial`,this.color=new B(16777215),this.map=null,this.linewidth=1,this.linecap=`round`,this.linejoin=`round`,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.linewidth=e.linewidth,this.linecap=e.linecap,this.linejoin=e.linejoin,this.fog=e.fog,this}},zi=new R,Bi=new R,Vi=new yn,Hi=new vn,Ui=new un,Wi=new R,Gi=new R,Ki=class extends Kn{constructor(e=new Or,t=new Ri){super(),this.isLine=!0,this.type=`Line`,this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}computeLineDistances(){let e=this.geometry;if(e.index===null){let t=e.attributes.position,n=[0];for(let e=1,r=t.count;e<r;e++)zi.fromBufferAttribute(t,e-1),Bi.fromBufferAttribute(t,e),n[e]=n[e-1],n[e]+=zi.distanceTo(Bi);e.setAttribute(`lineDistance`,new br(n,1))}else console.warn(`THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.`);return this}raycast(e,t){let n=this.geometry,r=this.matrixWorld,i=e.params.Line.threshold,a=n.drawRange;if(n.boundingSphere===null&&n.computeBoundingSphere(),Ui.copy(n.boundingSphere),Ui.applyMatrix4(r),Ui.radius+=i,e.ray.intersectsSphere(Ui)===!1)return;Vi.copy(r).invert(),Hi.copy(e.ray).applyMatrix4(Vi);let o=i/((this.scale.x+this.scale.y+this.scale.z)/3),s=o*o,c=this.isLineSegments?2:1,l=n.index,u=n.attributes.position;if(l!==null){let n=Math.max(0,a.start),r=Math.min(l.count,a.start+a.count);for(let i=n,a=r-1;i<a;i+=c){let n=l.getX(i),r=l.getX(i+1),a=qi(this,e,Hi,s,n,r,i);a&&t.push(a)}if(this.isLineLoop){let i=l.getX(r-1),a=l.getX(n),o=qi(this,e,Hi,s,i,a,r-1);o&&t.push(o)}}else{let n=Math.max(0,a.start),r=Math.min(u.count,a.start+a.count);for(let i=n,a=r-1;i<a;i+=c){let n=qi(this,e,Hi,s,i,i+1,i);n&&t.push(n)}if(this.isLineLoop){let i=qi(this,e,Hi,s,r-1,n,r-1);i&&t.push(i)}}}updateMorphTargets(){let e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){let n=e[t[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e<t;e++){let t=n[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[t]=e}}}}};function qi(e,t,n,r,i,a,o){let s=e.geometry.attributes.position;if(zi.fromBufferAttribute(s,i),Bi.fromBufferAttribute(s,a),n.distanceSqToSegment(zi,Bi,Wi,Gi)>r)return;Wi.applyMatrix4(e.matrixWorld);let c=t.ray.origin.distanceTo(Wi);if(!(c<t.near||c>t.far))return{distance:c,point:Gi.clone().applyMatrix4(e.matrixWorld),index:o,face:null,faceIndex:null,barycoord:null,object:e}}var Ji=new R,Yi=new R,Xi=class extends Ki{constructor(e,t){super(e,t),this.isLineSegments=!0,this.type=`LineSegments`}computeLineDistances(){let e=this.geometry;if(e.index===null){let t=e.attributes.position,n=[];for(let e=0,r=t.count;e<r;e+=2)Ji.fromBufferAttribute(t,e),Yi.fromBufferAttribute(t,e+1),n[e]=e===0?0:n[e-1],n[e+1]=n[e]+Ji.distanceTo(Yi);e.setAttribute(`lineDistance`,new br(n,1))}else console.warn(`THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.`);return this}},Zi=class extends zt{constructor(e,t,n,r,i,a,o,s,c){super(e,t,n,r,i,a,o,s,c),this.isCanvasTexture=!0,this.needsUpdate=!0}},Qi=class extends zt{constructor(e,t,n=m,i,a,o,s=r,c=r,l,u=T,d=1){if(u!==1026&&u!==1027)throw Error(`DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat`);super({width:e,height:t,depth:d},i,a,o,s,c,u,n,l),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new Ft(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){let t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}},$i=class extends zt{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}},ea=class e extends Or{constructor(e=1,t=32,n=0,r=Math.PI*2){super(),this.type=`CircleGeometry`,this.parameters={radius:e,segments:t,thetaStart:n,thetaLength:r},t=Math.max(3,t);let i=[],a=[],o=[],s=[],c=new R,l=new L;a.push(0,0,0),o.push(0,0,1),s.push(.5,.5);for(let i=0,u=3;i<=t;i++,u+=3){let d=n+i/t*r;c.x=e*Math.cos(d),c.y=e*Math.sin(d),a.push(c.x,c.y,c.z),o.push(0,0,1),l.x=(a[u]/e+1)/2,l.y=(a[u+1]/e+1)/2,s.push(l.x,l.y)}for(let e=1;e<=t;e++)i.push(e,e+1,0);this.setIndex(i),this.setAttribute(`position`,new br(a,3)),this.setAttribute(`normal`,new br(o,3)),this.setAttribute(`uv`,new br(s,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(t){return new e(t.radius,t.segments,t.thetaStart,t.thetaLength)}},ta=class e extends Or{constructor(e=1,t=1,n=1,r=32,i=1,a=!1,o=0,s=Math.PI*2){super(),this.type=`CylinderGeometry`,this.parameters={radiusTop:e,radiusBottom:t,height:n,radialSegments:r,heightSegments:i,openEnded:a,thetaStart:o,thetaLength:s};let c=this;r=Math.floor(r),i=Math.floor(i);let l=[],u=[],d=[],f=[],p=0,m=[],h=n/2,g=0;_(),a===!1&&(e>0&&v(!0),t>0&&v(!1)),this.setIndex(l),this.setAttribute(`position`,new br(u,3)),this.setAttribute(`normal`,new br(d,3)),this.setAttribute(`uv`,new br(f,2));function _(){let a=new R,_=new R,v=0,y=(t-e)/n;for(let c=0;c<=i;c++){let l=[],g=c/i,v=g*(t-e)+e;for(let e=0;e<=r;e++){let t=e/r,i=t*s+o,c=Math.sin(i),m=Math.cos(i);_.x=v*c,_.y=-g*n+h,_.z=v*m,u.push(_.x,_.y,_.z),a.set(c,y,m).normalize(),d.push(a.x,a.y,a.z),f.push(t,1-g),l.push(p++)}m.push(l)}for(let n=0;n<r;n++)for(let r=0;r<i;r++){let a=m[r][n],o=m[r+1][n],s=m[r+1][n+1],c=m[r][n+1];(e>0||r!==0)&&(l.push(a,o,c),v+=3),(t>0||r!==i-1)&&(l.push(o,s,c),v+=3)}c.addGroup(g,v,0),g+=v}function v(n){let i=p,a=new L,m=new R,_=0,v=n===!0?e:t,y=n===!0?1:-1;for(let e=1;e<=r;e++)u.push(0,h*y,0),d.push(0,y,0),f.push(.5,.5),p++;let b=p;for(let e=0;e<=r;e++){let t=e/r*s+o,n=Math.cos(t),i=Math.sin(t);m.x=v*i,m.y=h*y,m.z=v*n,u.push(m.x,m.y,m.z),d.push(0,y,0),a.x=n*.5+.5,a.y=i*.5*y+.5,f.push(a.x,a.y),p++}for(let e=0;e<r;e++){let t=i+e,r=b+e;n===!0?l.push(r,r+1,t):l.push(r+1,r,t),_+=3}c.addGroup(g,_,n===!0?1:2),g+=_}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(t){return new e(t.radiusTop,t.radiusBottom,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}},na=class e extends ta{constructor(e=1,t=1,n=32,r=1,i=!1,a=0,o=Math.PI*2){super(0,e,t,n,r,i,a,o),this.type=`ConeGeometry`,this.parameters={radius:e,height:t,radialSegments:n,heightSegments:r,openEnded:i,thetaStart:a,thetaLength:o}}static fromJSON(t){return new e(t.radius,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}},ra=new R,ia=new R,aa=new R,oa=new or,sa=class extends Or{constructor(e=null,t=1){if(super(),this.type=`EdgesGeometry`,this.parameters={geometry:e,thresholdAngle:t},e!==null){let n=10**4,r=Math.cos(Ke*t),i=e.getIndex(),a=e.getAttribute(`position`),o=i?i.count:a.count,s=[0,0,0],c=[`a`,`b`,`c`],l=[,,,],u={},d=[];for(let e=0;e<o;e+=3){i?(s[0]=i.getX(e),s[1]=i.getX(e+1),s[2]=i.getX(e+2)):(s[0]=e,s[1]=e+1,s[2]=e+2);let{a:t,b:o,c:f}=oa;if(t.fromBufferAttribute(a,s[0]),o.fromBufferAttribute(a,s[1]),f.fromBufferAttribute(a,s[2]),oa.getNormal(aa),l[0]=`${Math.round(t.x*n)},${Math.round(t.y*n)},${Math.round(t.z*n)}`,l[1]=`${Math.round(o.x*n)},${Math.round(o.y*n)},${Math.round(o.z*n)}`,l[2]=`${Math.round(f.x*n)},${Math.round(f.y*n)},${Math.round(f.z*n)}`,!(l[0]===l[1]||l[1]===l[2]||l[2]===l[0]))for(let e=0;e<3;e++){let t=(e+1)%3,n=l[e],i=l[t],a=oa[c[e]],o=oa[c[t]],f=`${n}_${i}`,p=`${i}_${n}`;p in u&&u[p]?(aa.dot(u[p].normal)<=r&&(d.push(a.x,a.y,a.z),d.push(o.x,o.y,o.z)),u[p]=null):f in u||(u[f]={index0:s[e],index1:s[t],normal:aa.clone()})}}for(let e in u)if(u[e]){let{index0:t,index1:n}=u[e];ra.fromBufferAttribute(a,t),ia.fromBufferAttribute(a,n),d.push(ra.x,ra.y,ra.z),d.push(ia.x,ia.y,ia.z)}this.setAttribute(`position`,new br(d,3))}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}},ca=class e extends Or{constructor(e=1,t=1,n=1,r=1){super(),this.type=`PlaneGeometry`,this.parameters={width:e,height:t,widthSegments:n,heightSegments:r};let i=e/2,a=t/2,o=Math.floor(n),s=Math.floor(r),c=o+1,l=s+1,u=e/o,d=t/s,f=[],p=[],m=[],h=[];for(let e=0;e<l;e++){let t=e*d-a;for(let n=0;n<c;n++){let r=n*u-i;p.push(r,-t,0),m.push(0,0,1),h.push(n/o),h.push(1-e/s)}}for(let e=0;e<s;e++)for(let t=0;t<o;t++){let n=t+c*e,r=t+c*(e+1),i=t+1+c*(e+1),a=t+1+c*e;f.push(n,r,a),f.push(r,i,a)}this.setIndex(f),this.setAttribute(`position`,new br(p,3)),this.setAttribute(`normal`,new br(m,3)),this.setAttribute(`uv`,new br(h,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(t){return new e(t.width,t.height,t.widthSegments,t.heightSegments)}},la=class e extends Or{constructor(e=1,t=32,n=16,r=0,i=Math.PI*2,a=0,o=Math.PI){super(),this.type=`SphereGeometry`,this.parameters={radius:e,widthSegments:t,heightSegments:n,phiStart:r,phiLength:i,thetaStart:a,thetaLength:o},t=Math.max(3,Math.floor(t)),n=Math.max(2,Math.floor(n));let s=Math.min(a+o,Math.PI),c=0,l=[],u=new R,d=new R,f=[],p=[],m=[],h=[];for(let f=0;f<=n;f++){let g=[],_=f/n,v=0;f===0&&a===0?v=.5/t:f===n&&s===Math.PI&&(v=-.5/t);for(let n=0;n<=t;n++){let s=n/t;u.x=-e*Math.cos(r+s*i)*Math.sin(a+_*o),u.y=e*Math.cos(a+_*o),u.z=e*Math.sin(r+s*i)*Math.sin(a+_*o),p.push(u.x,u.y,u.z),d.copy(u).normalize(),m.push(d.x,d.y,d.z),h.push(s+v,1-_),g.push(c++)}l.push(g)}for(let e=0;e<n;e++)for(let r=0;r<t;r++){let t=l[e][r+1],i=l[e][r],o=l[e+1][r],c=l[e+1][r+1];(e!==0||a>0)&&f.push(t,i,c),(e!==n-1||s<Math.PI)&&f.push(i,o,c)}this.setIndex(f),this.setAttribute(`position`,new br(p,3)),this.setAttribute(`normal`,new br(m,3)),this.setAttribute(`uv`,new br(h,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(t){return new e(t.radius,t.widthSegments,t.heightSegments,t.phiStart,t.phiLength,t.thetaStart,t.thetaLength)}},ua=class extends Or{constructor(e=null){if(super(),this.type=`WireframeGeometry`,this.parameters={geometry:e},e!==null){let t=[],n=new Set,r=new R,i=new R;if(e.index!==null){let a=e.attributes.position,o=e.index,s=e.groups;s.length===0&&(s=[{start:0,count:o.count,materialIndex:0}]);for(let e=0,c=s.length;e<c;++e){let c=s[e],l=c.start,u=c.count;for(let e=l,s=l+u;e<s;e+=3)for(let s=0;s<3;s++){let c=o.getX(e+s),l=o.getX(e+(s+1)%3);r.fromBufferAttribute(a,c),i.fromBufferAttribute(a,l),da(r,i,n)===!0&&(t.push(r.x,r.y,r.z),t.push(i.x,i.y,i.z))}}}else{let a=e.attributes.position;for(let e=0,o=a.count/3;e<o;e++)for(let o=0;o<3;o++){let s=3*e+o,c=3*e+(o+1)%3;r.fromBufferAttribute(a,s),i.fromBufferAttribute(a,c),da(r,i,n)===!0&&(t.push(r.x,r.y,r.z),t.push(i.x,i.y,i.z))}}this.setAttribute(`position`,new br(t,3))}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}};function da(e,t,n){let r=`${e.x},${e.y},${e.z}-${t.x},${t.y},${t.z}`,i=`${t.x},${t.y},${t.z}-${e.x},${e.y},${e.z}`;return n.has(r)===!0||n.has(i)===!0?!1:(n.add(r),n.add(i),!0)}var fa=class extends pr{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type=`MeshPhongMaterial`,this.color=new B(16777215),this.specular=new B(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new B(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new L(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new kn,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap=`round`,this.wireframeLinejoin=`round`,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}},pa=class extends pr{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type=`MeshDepthMaterial`,this.depthPacking=Pe,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}},ma=class extends pr{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type=`MeshDistanceMaterial`,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}},ha=class extends Ri{constructor(e){super(),this.isLineDashedMaterial=!0,this.type=`LineDashedMaterial`,this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(e)}copy(e){return super.copy(e),this.scale=e.scale,this.dashSize=e.dashSize,this.gapSize=e.gapSize,this}};function ga(e,t){return!e||e.constructor===t?e:typeof t.BYTES_PER_ELEMENT==`number`?new t(e):Array.prototype.slice.call(e)}function _a(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}var va=class{constructor(e,t,n,r){this.parameterPositions=e,this._cachedIndex=0,this.resultBuffer=r===void 0?new t.constructor(n):r,this.sampleValues=t,this.valueSize=n,this.settings=null,this.DefaultSettings_={}}evaluate(e){let t=this.parameterPositions,n=this._cachedIndex,r=t[n],i=t[n-1];validate_interval:{seek:{let a;linear_scan:{forward_scan:if(!(e<r)){for(let a=n+2;;){if(r===void 0){if(e<i)break forward_scan;return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}if(n===a)break;if(i=r,r=t[++n],e<r)break seek}a=t.length;break linear_scan}if(!(e>=i)){let o=t[1];e<o&&(n=2,i=o);for(let a=n-2;;){if(i===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(n===a)break;if(r=i,i=t[--n-1],e>=i)break seek}a=n,n=0;break linear_scan}break validate_interval}for(;n<a;){let r=n+a>>>1;e<t[r]?a=r:n=r+1}if(r=t[n],i=t[n-1],i===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(r===void 0)return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}this._cachedIndex=n,this.intervalChanged_(n,i,r)}return this.interpolate_(n,i,e,r)}getSettings_(){return this.settings||this.DefaultSettings_}copySampleValue_(e){let t=this.resultBuffer,n=this.sampleValues,r=this.valueSize,i=e*r;for(let e=0;e!==r;++e)t[e]=n[i+e];return t}interpolate_(){throw Error(`call to abstract method`)}intervalChanged_(){}},ya=class extends va{constructor(e,t,n,r){super(e,t,n,r),this._weightPrev=-0,this._offsetPrev=-0,this._weightNext=-0,this._offsetNext=-0,this.DefaultSettings_={endingStart:je,endingEnd:je}}intervalChanged_(e,t,n){let r=this.parameterPositions,i=e-2,a=e+1,o=r[i],s=r[a];if(o===void 0)switch(this.getSettings_().endingStart){case Me:i=e,o=2*t-n;break;case Ne:i=r.length-2,o=t+r[i]-r[i+1];break;default:i=e,o=n}if(s===void 0)switch(this.getSettings_().endingEnd){case Me:a=e,s=2*n-t;break;case Ne:a=1,s=n+r[1]-r[0];break;default:a=e-1,s=t}let c=(n-t)*.5,l=this.valueSize;this._weightPrev=c/(t-o),this._weightNext=c/(s-n),this._offsetPrev=i*l,this._offsetNext=a*l}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=e*o,c=s-o,l=this._offsetPrev,u=this._offsetNext,d=this._weightPrev,f=this._weightNext,p=(n-t)/(r-t),m=p*p,h=m*p,g=-d*h+2*d*m-d*p,_=(1+d)*h+(-1.5-2*d)*m+(-.5+d)*p+1,v=(-1-f)*h+(1.5+f)*m+.5*p,y=f*h-f*m;for(let e=0;e!==o;++e)i[e]=g*a[l+e]+_*a[c+e]+v*a[s+e]+y*a[u+e];return i}},ba=class extends va{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=e*o,c=s-o,l=(n-t)/(r-t),u=1-l;for(let e=0;e!==o;++e)i[e]=a[c+e]*u+a[s+e]*l;return i}},xa=class extends va{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e){return this.copySampleValue_(e-1)}},Sa=class{constructor(e,t,n,r){if(e===void 0)throw Error(`THREE.KeyframeTrack: track name is undefined`);if(t===void 0||t.length===0)throw Error(`THREE.KeyframeTrack: no keyframes in track named `+e);this.name=e,this.times=ga(t,this.TimeBufferType),this.values=ga(n,this.ValueBufferType),this.setInterpolation(r||this.DefaultInterpolation)}static toJSON(e){let t=e.constructor,n;if(t.toJSON!==this.toJSON)n=t.toJSON(e);else{n={name:e.name,times:ga(e.times,Array),values:ga(e.values,Array)};let t=e.getInterpolation();t!==e.DefaultInterpolation&&(n.interpolation=t)}return n.type=e.ValueTypeName,n}InterpolantFactoryMethodDiscrete(e){return new xa(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodLinear(e){return new ba(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodSmooth(e){return new ya(this.times,this.values,this.getValueSize(),e)}setInterpolation(e){let t;switch(e){case Oe:t=this.InterpolantFactoryMethodDiscrete;break;case ke:t=this.InterpolantFactoryMethodLinear;break;case Ae:t=this.InterpolantFactoryMethodSmooth;break}if(t===void 0){let t=`unsupported interpolation for `+this.ValueTypeName+` keyframe track named `+this.name;if(this.createInterpolant===void 0)if(e!==this.DefaultInterpolation)this.setInterpolation(this.DefaultInterpolation);else throw Error(t);return console.warn(`THREE.KeyframeTrack:`,t),this}return this.createInterpolant=t,this}getInterpolation(){switch(this.createInterpolant){case this.InterpolantFactoryMethodDiscrete:return Oe;case this.InterpolantFactoryMethodLinear:return ke;case this.InterpolantFactoryMethodSmooth:return Ae}}getValueSize(){return this.values.length/this.times.length}shift(e){if(e!==0){let t=this.times;for(let n=0,r=t.length;n!==r;++n)t[n]+=e}return this}scale(e){if(e!==1){let t=this.times;for(let n=0,r=t.length;n!==r;++n)t[n]*=e}return this}trim(e,t){let n=this.times,r=n.length,i=0,a=r-1;for(;i!==r&&n[i]<e;)++i;for(;a!==-1&&n[a]>t;)--a;if(++a,i!==0||a!==r){i>=a&&(a=Math.max(a,1),i=a-1);let e=this.getValueSize();this.times=n.slice(i,a),this.values=this.values.slice(i*e,a*e)}return this}validate(){let e=!0,t=this.getValueSize();t-Math.floor(t)!==0&&(console.error(`THREE.KeyframeTrack: Invalid value size in track.`,this),e=!1);let n=this.times,r=this.values,i=n.length;i===0&&(console.error(`THREE.KeyframeTrack: Track is empty.`,this),e=!1);let a=null;for(let t=0;t!==i;t++){let r=n[t];if(typeof r==`number`&&isNaN(r)){console.error(`THREE.KeyframeTrack: Time is not a valid number.`,this,t,r),e=!1;break}if(a!==null&&a>r){console.error(`THREE.KeyframeTrack: Out of order keys.`,this,t,r,a),e=!1;break}a=r}if(r!==void 0&&_a(r))for(let t=0,n=r.length;t!==n;++t){let n=r[t];if(isNaN(n)){console.error(`THREE.KeyframeTrack: Value is not a valid number.`,this,t,n),e=!1;break}}return e}optimize(){let e=this.times.slice(),t=this.values.slice(),n=this.getValueSize(),r=this.getInterpolation()===Ae,i=e.length-1,a=1;for(let o=1;o<i;++o){let i=!1,s=e[o];if(s!==e[o+1]&&(o!==1||s!==e[0]))if(r)i=!0;else{let e=o*n,r=e-n,a=e+n;for(let o=0;o!==n;++o){let n=t[e+o];if(n!==t[r+o]||n!==t[a+o]){i=!0;break}}}if(i){if(o!==a){e[a]=e[o];let r=o*n,i=a*n;for(let e=0;e!==n;++e)t[i+e]=t[r+e]}++a}}if(i>0){e[a]=e[i];for(let e=i*n,r=a*n,o=0;o!==n;++o)t[r+o]=t[e+o];++a}return a===e.length?(this.times=e,this.values=t):(this.times=e.slice(0,a),this.values=t.slice(0,a*n)),this}clone(){let e=this.times.slice(),t=this.values.slice(),n=this.constructor,r=new n(this.name,e,t);return r.createInterpolant=this.createInterpolant,r}};Sa.prototype.ValueTypeName=``,Sa.prototype.TimeBufferType=Float32Array,Sa.prototype.ValueBufferType=Float32Array,Sa.prototype.DefaultInterpolation=ke;var Ca=class extends Sa{constructor(e,t,n){super(e,t,n)}};Ca.prototype.ValueTypeName=`bool`,Ca.prototype.ValueBufferType=Array,Ca.prototype.DefaultInterpolation=Oe,Ca.prototype.InterpolantFactoryMethodLinear=void 0,Ca.prototype.InterpolantFactoryMethodSmooth=void 0;var wa=class extends Sa{constructor(e,t,n,r){super(e,t,n,r)}};wa.prototype.ValueTypeName=`color`;var Ta=class extends Sa{constructor(e,t,n,r){super(e,t,n,r)}};Ta.prototype.ValueTypeName=`number`;var Ea=class extends va{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=(n-t)/(r-t),c=e*o;for(let e=c+o;c!==e;c+=4)gt.slerpFlat(i,0,a,c-o,a,c,s);return i}},Da=class extends Sa{constructor(e,t,n,r){super(e,t,n,r)}InterpolantFactoryMethodLinear(e){return new Ea(this.times,this.values,this.getValueSize(),e)}};Da.prototype.ValueTypeName=`quaternion`,Da.prototype.InterpolantFactoryMethodSmooth=void 0;var Oa=class extends Sa{constructor(e,t,n){super(e,t,n)}};Oa.prototype.ValueTypeName=`string`,Oa.prototype.ValueBufferType=Array,Oa.prototype.DefaultInterpolation=Oe,Oa.prototype.InterpolantFactoryMethodLinear=void 0,Oa.prototype.InterpolantFactoryMethodSmooth=void 0;var ka=class extends Sa{constructor(e,t,n,r){super(e,t,n,r)}};ka.prototype.ValueTypeName=`vector`;var Aa=new class{constructor(e,t,n){let r=this,i=!1,a=0,o=0,s,c=[];this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=n,this.abortController=new AbortController,this.itemStart=function(e){o++,i===!1&&r.onStart!==void 0&&r.onStart(e,a,o),i=!0},this.itemEnd=function(e){a++,r.onProgress!==void 0&&r.onProgress(e,a,o),a===o&&(i=!1,r.onLoad!==void 0&&r.onLoad())},this.itemError=function(e){r.onError!==void 0&&r.onError(e)},this.resolveURL=function(e){return s?s(e):e},this.setURLModifier=function(e){return s=e,this},this.addHandler=function(e,t){return c.push(e,t),this},this.removeHandler=function(e){let t=c.indexOf(e);return t!==-1&&c.splice(t,2),this},this.getHandler=function(e){for(let t=0,n=c.length;t<n;t+=2){let n=c[t],r=c[t+1];if(n.global&&(n.lastIndex=0),n.test(e))return r}return null},this.abort=function(){return this.abortController.abort(),this.abortController=new AbortController,this}}},ja=class{constructor(e){this.manager=e===void 0?Aa:e,this.crossOrigin=`anonymous`,this.withCredentials=!1,this.path=``,this.resourcePath=``,this.requestHeader={}}load(){}loadAsync(e,t){let n=this;return new Promise(function(r,i){n.load(e,r,t,i)})}parse(){}setCrossOrigin(e){return this.crossOrigin=e,this}setWithCredentials(e){return this.withCredentials=e,this}setPath(e){return this.path=e,this}setResourcePath(e){return this.resourcePath=e,this}setRequestHeader(e){return this.requestHeader=e,this}abort(){return this}};ja.DEFAULT_MATERIAL_NAME=`__DEFAULT`;var Ma=class extends Kn{constructor(e,t=1){super(),this.isLight=!0,this.type=`Light`,this.color=new B(e),this.intensity=t}dispose(){}copy(e,t){return super.copy(e,t),this.color.copy(e.color),this.intensity=e.intensity,this}toJSON(e){let t=super.toJSON(e);return t.object.color=this.color.getHex(),t.object.intensity=this.intensity,this.groundColor!==void 0&&(t.object.groundColor=this.groundColor.getHex()),this.distance!==void 0&&(t.object.distance=this.distance),this.angle!==void 0&&(t.object.angle=this.angle),this.decay!==void 0&&(t.object.decay=this.decay),this.penumbra!==void 0&&(t.object.penumbra=this.penumbra),this.shadow!==void 0&&(t.object.shadow=this.shadow.toJSON()),this.target!==void 0&&(t.object.target=this.target.uuid),t}},Na=new yn,Pa=new R,Fa=new R,Ia=class{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new L(512,512),this.mapType=l,this.map=null,this.mapPass=null,this.matrix=new yn,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new Li,this._frameExtents=new L(1,1),this._viewportCount=1,this._viewports=[new Bt(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){let t=this.camera,n=this.matrix;Pa.setFromMatrixPosition(e.matrixWorld),t.position.copy(Pa),Fa.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(Fa),t.updateMatrixWorld(),Na.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(Na,t.coordinateSystem,t.reversedDepth),t.reversedDepth?n.set(.5,0,0,.5,0,.5,0,.5,0,0,1,0,0,0,0,1):n.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),n.multiply(Na)}getViewport(e){return this._viewports[e]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(e){return this.camera=e.camera.clone(),this.intensity=e.intensity,this.bias=e.bias,this.radius=e.radius,this.autoUpdate=e.autoUpdate,this.needsUpdate=e.needsUpdate,this.normalBias=e.normalBias,this.blurSamples=e.blurSamples,this.mapSize.copy(e.mapSize),this}clone(){return new this.constructor().copy(this)}toJSON(){let e={};return this.intensity!==1&&(e.intensity=this.intensity),this.bias!==0&&(e.bias=this.bias),this.normalBias!==0&&(e.normalBias=this.normalBias),this.radius!==1&&(e.radius=this.radius),(this.mapSize.x!==512||this.mapSize.y!==512)&&(e.mapSize=this.mapSize.toArray()),e.camera=this.camera.toJSON(!1).object,delete e.camera.matrix,e}},La=class extends Zr{constructor(e=-1,t=1,n=1,r=-1,i=.1,a=2e3){super(),this.isOrthographicCamera=!0,this.type=`OrthographicCamera`,this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=n,this.bottom=r,this.near=i,this.far=a,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,t,n,r,i,a){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=r,this.view.width=i,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),n=(this.right+this.left)/2,r=(this.top+this.bottom)/2,i=n-e,a=n+e,o=r+t,s=r-t;if(this.view!==null&&this.view.enabled){let e=(this.right-this.left)/this.view.fullWidth/this.zoom,t=(this.top-this.bottom)/this.view.fullHeight/this.zoom;i+=e*this.view.offsetX,a=i+e*this.view.width,o-=t*this.view.offsetY,s=o-t*this.view.height}this.projectionMatrix.makeOrthographic(i,a,o,s,this.near,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,this.view!==null&&(t.object.view=Object.assign({},this.view)),t}},Ra=class extends Ia{constructor(){super(new La(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}},za=class extends Ma{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type=`DirectionalLight`,this.position.copy(Kn.DEFAULT_UP),this.updateMatrix(),this.target=new Kn,this.shadow=new Ra}dispose(){this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}},Ba=class extends Ma{constructor(e,t){super(e,t),this.isAmbientLight=!0,this.type=`AmbientLight`}},Va=class extends Or{constructor(){super(),this.isInstancedBufferGeometry=!0,this.type=`InstancedBufferGeometry`,this.instanceCount=1/0}copy(e){return super.copy(e),this.instanceCount=e.instanceCount,this}toJSON(){let e=super.toJSON();return e.instanceCount=this.instanceCount,e.isInstancedBufferGeometry=!0,e}},Ha=class extends ti{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}},Ua=class{constructor(e=!0){this.autoStart=e,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=performance.now(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let e=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){let t=performance.now();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}},Wa=`\\[\\]\\.:\\/`,Ga=RegExp(`[`+Wa+`]`,`g`),Ka=`[^`+Wa+`]`,qa=`[^`+Wa.replace(`\\.`,``)+`]`,Ja=`((?:WC+[\\/:])*)`.replace(`WC`,Ka),Ya=`(WCOD+)?`.replace(`WCOD`,qa),Xa=`(?:\\.(WC+)(?:\\[(.+)\\])?)?`.replace(`WC`,Ka),Za=`\\.(WC+)(?:\\[(.+)\\])?`.replace(`WC`,Ka),Qa=RegExp(`^`+Ja+Ya+Xa+Za+`$`),$a=[`material`,`materials`,`bones`,`map`],eo=class{constructor(e,t,n){let r=n||to.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,r)}getValue(e,t){this.bind();let n=this._targetGroup.nCachedObjects_,r=this._bindings[n];r!==void 0&&r.getValue(e,t)}setValue(e,t){let n=this._bindings;for(let r=this._targetGroup.nCachedObjects_,i=n.length;r!==i;++r)n[r].setValue(e,t)}bind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].bind()}unbind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].unbind()}},to=class e{constructor(t,n,r){this.path=n,this.parsedPath=r||e.parseTrackName(n),this.node=e.findNode(t,this.parsedPath.nodeName),this.rootNode=t,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(t,n,r){return t&&t.isAnimationObjectGroup?new e.Composite(t,n,r):new e(t,n,r)}static sanitizeNodeName(e){return e.replace(/\s/g,`_`).replace(Ga,``)}static parseTrackName(e){let t=Qa.exec(e);if(t===null)throw Error(`PropertyBinding: Cannot parse trackName: `+e);let n={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},r=n.nodeName&&n.nodeName.lastIndexOf(`.`);if(r!==void 0&&r!==-1){let e=n.nodeName.substring(r+1);$a.indexOf(e)!==-1&&(n.nodeName=n.nodeName.substring(0,r),n.objectName=e)}if(n.propertyName===null||n.propertyName.length===0)throw Error(`PropertyBinding: can not parse propertyName from trackName: `+e);return n}static findNode(e,t){if(t===void 0||t===``||t===`.`||t===-1||t===e.name||t===e.uuid)return e;if(e.skeleton){let n=e.skeleton.getBoneByName(t);if(n!==void 0)return n}if(e.children){let n=function(e){for(let r=0;r<e.length;r++){let i=e[r];if(i.name===t||i.uuid===t)return i;let a=n(i.children);if(a)return a}return null},r=n(e.children);if(r)return r}return null}_getValue_unavailable(){}_setValue_unavailable(){}_getValue_direct(e,t){e[t]=this.targetObject[this.propertyName]}_getValue_array(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)e[t++]=n[r]}_getValue_arrayElement(e,t){e[t]=this.resolvedProperty[this.propertyIndex]}_getValue_toArray(e,t){this.resolvedProperty.toArray(e,t)}_setValue_direct(e,t){this.targetObject[this.propertyName]=e[t]}_setValue_direct_setNeedsUpdate(e,t){this.targetObject[this.propertyName]=e[t],this.targetObject.needsUpdate=!0}_setValue_direct_setMatrixWorldNeedsUpdate(e,t){this.targetObject[this.propertyName]=e[t],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_array(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)n[r]=e[t++]}_setValue_array_setNeedsUpdate(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)n[r]=e[t++];this.targetObject.needsUpdate=!0}_setValue_array_setMatrixWorldNeedsUpdate(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)n[r]=e[t++];this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_arrayElement(e,t){this.resolvedProperty[this.propertyIndex]=e[t]}_setValue_arrayElement_setNeedsUpdate(e,t){this.resolvedProperty[this.propertyIndex]=e[t],this.targetObject.needsUpdate=!0}_setValue_arrayElement_setMatrixWorldNeedsUpdate(e,t){this.resolvedProperty[this.propertyIndex]=e[t],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_fromArray(e,t){this.resolvedProperty.fromArray(e,t)}_setValue_fromArray_setNeedsUpdate(e,t){this.resolvedProperty.fromArray(e,t),this.targetObject.needsUpdate=!0}_setValue_fromArray_setMatrixWorldNeedsUpdate(e,t){this.resolvedProperty.fromArray(e,t),this.targetObject.matrixWorldNeedsUpdate=!0}_getValue_unbound(e,t){this.bind(),this.getValue(e,t)}_setValue_unbound(e,t){this.bind(),this.setValue(e,t)}bind(){let t=this.node,n=this.parsedPath,r=n.objectName,i=n.propertyName,a=n.propertyIndex;if(t||(t=e.findNode(this.rootNode,n.nodeName),this.node=t),this.getValue=this._getValue_unavailable,this.setValue=this._setValue_unavailable,!t){console.warn(`THREE.PropertyBinding: No target node found for track: `+this.path+`.`);return}if(r){let e=n.objectIndex;switch(r){case`materials`:if(!t.material){console.error(`THREE.PropertyBinding: Can not bind to material as node does not have a material.`,this);return}if(!t.material.materials){console.error(`THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.`,this);return}t=t.material.materials;break;case`bones`:if(!t.skeleton){console.error(`THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.`,this);return}t=t.skeleton.bones;for(let n=0;n<t.length;n++)if(t[n].name===e){e=n;break}break;case`map`:if(`map`in t){t=t.map;break}if(!t.material){console.error(`THREE.PropertyBinding: Can not bind to material as node does not have a material.`,this);return}if(!t.material.map){console.error(`THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.`,this);return}t=t.material.map;break;default:if(t[r]===void 0){console.error(`THREE.PropertyBinding: Can not bind to objectName of node undefined.`,this);return}t=t[r]}if(e!==void 0){if(t[e]===void 0){console.error(`THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.`,this,t);return}t=t[e]}}let o=t[i];if(o===void 0){let e=n.nodeName;console.error(`THREE.PropertyBinding: Trying to update property for track: `+e+`.`+i+` but it wasn't found.`,t);return}let s=this.Versioning.None;this.targetObject=t,t.isMaterial===!0?s=this.Versioning.NeedsUpdate:t.isObject3D===!0&&(s=this.Versioning.MatrixWorldNeedsUpdate);let c=this.BindingType.Direct;if(a!==void 0){if(i===`morphTargetInfluences`){if(!t.geometry){console.error(`THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.`,this);return}if(!t.geometry.morphAttributes){console.error(`THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.`,this);return}t.morphTargetDictionary[a]!==void 0&&(a=t.morphTargetDictionary[a])}c=this.BindingType.ArrayElement,this.resolvedProperty=o,this.propertyIndex=a}else o.fromArray!==void 0&&o.toArray!==void 0?(c=this.BindingType.HasFromToArray,this.resolvedProperty=o):Array.isArray(o)?(c=this.BindingType.EntireArray,this.resolvedProperty=o):this.propertyName=i;this.getValue=this.GetterByBindingType[c],this.setValue=this.SetterByBindingTypeAndVersioning[c][s]}unbind(){this.node=null,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}};to.Composite=eo,to.prototype.BindingType={Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3},to.prototype.Versioning={None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2},to.prototype.GetterByBindingType=[to.prototype._getValue_direct,to.prototype._getValue_array,to.prototype._getValue_arrayElement,to.prototype._getValue_toArray],to.prototype.SetterByBindingTypeAndVersioning=[[to.prototype._setValue_direct,to.prototype._setValue_direct_setNeedsUpdate,to.prototype._setValue_direct_setMatrixWorldNeedsUpdate],[to.prototype._setValue_array,to.prototype._setValue_array_setNeedsUpdate,to.prototype._setValue_array_setMatrixWorldNeedsUpdate],[to.prototype._setValue_arrayElement,to.prototype._setValue_arrayElement_setNeedsUpdate,to.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate],[to.prototype._setValue_fromArray,to.prototype._setValue_fromArray_setNeedsUpdate,to.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];var no=class extends di{constructor(e,t,n=1){super(e,t),this.isInstancedInterleavedBuffer=!0,this.meshPerAttribute=n}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}clone(e){let t=super.clone(e);return t.meshPerAttribute=this.meshPerAttribute,t}toJSON(e){let t=super.toJSON(e);return t.isInstancedInterleavedBuffer=!0,t.meshPerAttribute=this.meshPerAttribute,t}},ro=new yn,io=class{constructor(e,t,n=0,r=1/0){this.ray=new vn(e,t),this.near=n,this.far=r,this.camera=null,this.layers=new An,this.params={Mesh:{},Line:{threshold:1},LOD:{},Points:{threshold:1},Sprite:{}}}set(e,t){this.ray.set(e,t)}setFromCamera(e,t){t.isPerspectiveCamera?(this.ray.origin.setFromMatrixPosition(t.matrixWorld),this.ray.direction.set(e.x,e.y,.5).unproject(t).sub(this.ray.origin).normalize(),this.camera=t):t.isOrthographicCamera?(this.ray.origin.set(e.x,e.y,(t.near+t.far)/(t.near-t.far)).unproject(t),this.ray.direction.set(0,0,-1).transformDirection(t.matrixWorld),this.camera=t):console.error(`THREE.Raycaster: Unsupported camera type: `+t.type)}setFromXRController(e){return ro.identity().extractRotation(e.matrixWorld),this.ray.origin.setFromMatrixPosition(e.matrixWorld),this.ray.direction.set(0,0,-1).applyMatrix4(ro),this}intersectObject(e,t=!0,n=[]){return oo(e,this,n,t),n.sort(ao),n}intersectObjects(e,t=!0,n=[]){for(let r=0,i=e.length;r<i;r++)oo(e[r],this,n,t);return n.sort(ao),n}};function ao(e,t){return e.distance-t.distance}function oo(e,t,n,r){let i=!0;if(e.layers.test(t.layers)&&e.raycast(t,n)===!1&&(i=!1),i===!0&&r===!0){let r=e.children;for(let e=0,i=r.length;e<i;e++)oo(r[e],t,n,!0)}}var so=class{constructor(e=1,t=0,n=0){this.radius=e,this.phi=t,this.theta=n}set(e,t,n){return this.radius=e,this.phi=t,this.theta=n,this}copy(e){return this.radius=e.radius,this.phi=e.phi,this.theta=e.theta,this}makeSafe(){let e=1e-6;return this.phi=I(this.phi,e,Math.PI-e),this}setFromVector3(e){return this.setFromCartesianCoords(e.x,e.y,e.z)}setFromCartesianCoords(e,t,n){return this.radius=Math.sqrt(e*e+t*t+n*n),this.radius===0?(this.theta=0,this.phi=0):(this.theta=Math.atan2(e,n),this.phi=Math.acos(I(t/this.radius,-1,1))),this}clone(){return new this.constructor().copy(this)}},co=new R,lo=new R,uo=new R,fo=new R,po=new R,mo=new R,ho=new R,go=class{constructor(e=new R,t=new R){this.start=e,this.end=t}set(e,t){return this.start.copy(e),this.end.copy(t),this}copy(e){return this.start.copy(e.start),this.end.copy(e.end),this}getCenter(e){return e.addVectors(this.start,this.end).multiplyScalar(.5)}delta(e){return e.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(e,t){return this.delta(t).multiplyScalar(e).add(this.start)}closestPointToPointParameter(e,t){co.subVectors(e,this.start),lo.subVectors(this.end,this.start);let n=lo.dot(lo),r=lo.dot(co)/n;return t&&(r=I(r,0,1)),r}closestPointToPoint(e,t,n){let r=this.closestPointToPointParameter(e,t);return this.delta(n).multiplyScalar(r).add(this.start)}distanceSqToLine3(e,t=mo,n=ho){let r=1e-8*1e-8,i,a,o=this.start,s=e.start,c=this.end,l=e.end;uo.subVectors(c,o),fo.subVectors(l,s),po.subVectors(o,s);let u=uo.dot(uo),d=fo.dot(fo),f=fo.dot(po);if(u<=r&&d<=r)return t.copy(o),n.copy(s),t.sub(n),t.dot(t);if(u<=r)i=0,a=f/d,a=I(a,0,1);else{let e=uo.dot(po);if(d<=r)a=0,i=I(-e/u,0,1);else{let t=uo.dot(fo),n=u*d-t*t;i=n===0?0:I((t*f-e*d)/n,0,1),a=(t*i+f)/d,a<0?(a=0,i=I(-e/u,0,1)):a>1&&(a=1,i=I((t-e)/u,0,1))}}return t.copy(o).add(uo.multiplyScalar(i)),n.copy(s).add(fo.multiplyScalar(a)),t.sub(n),t.dot(t)}applyMatrix4(e){return this.start.applyMatrix4(e),this.end.applyMatrix4(e),this}equals(e){return e.start.equals(this.start)&&e.end.equals(this.end)}clone(){return new this.constructor().copy(this)}},_o=class extends Xi{constructor(e=1){let t=[0,0,0,e,0,0,0,0,0,0,e,0,0,0,0,0,0,e],n=[1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],r=new Or;r.setAttribute(`position`,new br(t,3)),r.setAttribute(`color`,new br(n,3));let i=new Ri({vertexColors:!0,toneMapped:!1});super(r,i),this.type=`AxesHelper`}setColors(e,t,n){let r=new B,i=this.geometry.attributes.color.array;return r.set(e),r.toArray(i,0),r.toArray(i,3),r.set(t),r.toArray(i,6),r.toArray(i,9),r.set(n),r.toArray(i,12),r.toArray(i,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}};function vo(e,t,n,r){let i=yo(r);switch(n){case S:return e*t;case D:return e*t/i.components*i.byteLength;case ee:return e*t/i.components*i.byteLength;case O:return e*t*2/i.components*i.byteLength;case k:return e*t*2/i.components*i.byteLength;case C:return e*t*3/i.components*i.byteLength;case w:return e*t*4/i.components*i.byteLength;case te:return e*t*4/i.components*i.byteLength;case ne:case A:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case re:case ie:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case ae:case se:return Math.max(e,16)*Math.max(t,8)/4;case j:case oe:return Math.max(e,8)*Math.max(t,8)/2;case ce:case le:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case ue:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case de:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case fe:return Math.floor((e+4)/5)*Math.floor((t+3)/4)*16;case pe:return Math.floor((e+4)/5)*Math.floor((t+4)/5)*16;case me:return Math.floor((e+5)/6)*Math.floor((t+4)/5)*16;case he:return Math.floor((e+5)/6)*Math.floor((t+5)/6)*16;case ge:return Math.floor((e+7)/8)*Math.floor((t+4)/5)*16;case _e:return Math.floor((e+7)/8)*Math.floor((t+5)/6)*16;case ve:return Math.floor((e+7)/8)*Math.floor((t+7)/8)*16;case M:return Math.floor((e+9)/10)*Math.floor((t+4)/5)*16;case ye:return Math.floor((e+9)/10)*Math.floor((t+5)/6)*16;case be:return Math.floor((e+9)/10)*Math.floor((t+7)/8)*16;case xe:return Math.floor((e+9)/10)*Math.floor((t+9)/10)*16;case N:return Math.floor((e+11)/12)*Math.floor((t+9)/10)*16;case Se:return Math.floor((e+11)/12)*Math.floor((t+11)/12)*16;case P:case F:case Ce:return Math.ceil(e/4)*Math.ceil(t/4)*16;case we:case Te:return Math.ceil(e/4)*Math.ceil(t/4)*8;case Ee:case De:return Math.ceil(e/4)*Math.ceil(t/4)*16}throw Error(`Unable to determine texture byte length for ${n} format.`)}function yo(e){switch(e){case l:case u:return{byteLength:1,components:1};case f:case d:case g:return{byteLength:2,components:1};case _:case v:return{byteLength:2,components:4};case m:case p:case h:return{byteLength:4,components:1};case b:case x:return{byteLength:4,components:3}}throw Error(`Unknown texture type ${e}.`)}typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`register`,{detail:{revision:`180`}})),typeof window<`u`&&(window.__THREE__?console.warn(`WARNING: Multiple instances of Three.js being imported.`):window.__THREE__=`180`);function bo(){let e=null,t=!1,n=null,r=null;function i(t,a){n(t,a),r=e.requestAnimationFrame(i)}return{start:function(){t!==!0&&n!==null&&(r=e.requestAnimationFrame(i),t=!0)},stop:function(){e.cancelAnimationFrame(r),t=!1},setAnimationLoop:function(e){n=e},setContext:function(t){e=t}}}function xo(e){let t=new WeakMap;function n(t,n){let r=t.array,i=t.usage,a=r.byteLength,o=e.createBuffer();e.bindBuffer(n,o),e.bufferData(n,r,i),t.onUploadCallback();let s;if(r instanceof Float32Array)s=e.FLOAT;else if(typeof Float16Array<`u`&&r instanceof Float16Array)s=e.HALF_FLOAT;else if(r instanceof Uint16Array)s=t.isFloat16BufferAttribute?e.HALF_FLOAT:e.UNSIGNED_SHORT;else if(r instanceof Int16Array)s=e.SHORT;else if(r instanceof Uint32Array)s=e.UNSIGNED_INT;else if(r instanceof Int32Array)s=e.INT;else if(r instanceof Int8Array)s=e.BYTE;else if(r instanceof Uint8Array)s=e.UNSIGNED_BYTE;else if(r instanceof Uint8ClampedArray)s=e.UNSIGNED_BYTE;else throw Error(`THREE.WebGLAttributes: Unsupported buffer data format: `+r);return{buffer:o,type:s,bytesPerElement:r.BYTES_PER_ELEMENT,version:t.version,size:a}}function r(t,n,r){let i=n.array,a=n.updateRanges;if(e.bindBuffer(r,t),a.length===0)e.bufferSubData(r,0,i);else{a.sort((e,t)=>e.start-t.start);let t=0;for(let e=1;e<a.length;e++){let n=a[t],r=a[e];r.start<=n.start+n.count+1?n.count=Math.max(n.count,r.start+r.count-n.start):(++t,a[t]=r)}a.length=t+1;for(let t=0,n=a.length;t<n;t++){let n=a[t];e.bufferSubData(r,n.start*i.BYTES_PER_ELEMENT,i,n.start,n.count)}n.clearUpdateRanges()}n.onUploadCallback()}function i(e){return e.isInterleavedBufferAttribute&&(e=e.data),t.get(e)}function a(n){n.isInterleavedBufferAttribute&&(n=n.data);let r=t.get(n);r&&(e.deleteBuffer(r.buffer),t.delete(n))}function o(e,i){if(e.isInterleavedBufferAttribute&&(e=e.data),e.isGLBufferAttribute){let n=t.get(e);(!n||n.version<e.version)&&t.set(e,{buffer:e.buffer,type:e.type,bytesPerElement:e.elementSize,version:e.version});return}let a=t.get(e);if(a===void 0)t.set(e,n(e,i));else if(a.version<e.version){if(a.size!==e.array.byteLength)throw Error(`THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported.`);r(a.buffer,e,i),a.version=e.version}}return{get:i,remove:a,update:o}}var U={alphahash_fragment:`#ifdef USE_ALPHAHASH
40
+ `},r=new Vr(5,5,5),i=new Yr({name:`CubemapFromEquirect`,uniforms:Hr(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:1,blending:0});i.uniforms.tEquirect.value=t;let a=new U(r,i),s=t.minFilter;return t.minFilter===1008&&(t.minFilter=o),new ri(1,10,this).update(e,a),t.minFilter=s,a.geometry.dispose(),a.material.dispose(),this}clear(e,t=!0,n=!0,r=!0){let i=e.getRenderTarget();for(let i=0;i<6;i++)e.setRenderTarget(this,i),e.clear(t,n,r);e.setRenderTarget(i)}},oi=class extends Kn{constructor(){super(),this.isGroup=!0,this.type=`Group`}},si={type:`move`},ci=class{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new oi,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new oi,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new R,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new R),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new oi,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new R,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new R),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){let t=this._hand;if(t)for(let n of e.hand.values())this._getHandJoint(t,n)}return this.dispatchEvent({type:`connected`,data:e}),this}disconnect(e){return this.dispatchEvent({type:`disconnected`,data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,n){let r=null,i=null,a=null,o=this._targetRay,s=this._grip,c=this._hand;if(e&&t.session.visibilityState!==`visible-blurred`){if(c&&e.hand){a=!0;for(let r of e.hand.values()){let e=t.getJointPose(r,n),i=this._getHandJoint(c,r);e!==null&&(i.matrix.fromArray(e.transform.matrix),i.matrix.decompose(i.position,i.rotation,i.scale),i.matrixWorldNeedsUpdate=!0,i.jointRadius=e.radius),i.visible=e!==null}let r=c.joints[`index-finger-tip`],i=c.joints[`thumb-tip`],o=r.position.distanceTo(i.position),s=.02,l=.005;c.inputState.pinching&&o>s+l?(c.inputState.pinching=!1,this.dispatchEvent({type:`pinchend`,handedness:e.handedness,target:this})):!c.inputState.pinching&&o<=s-l&&(c.inputState.pinching=!0,this.dispatchEvent({type:`pinchstart`,handedness:e.handedness,target:this}))}else s!==null&&e.gripSpace&&(i=t.getPose(e.gripSpace,n),i!==null&&(s.matrix.fromArray(i.transform.matrix),s.matrix.decompose(s.position,s.rotation,s.scale),s.matrixWorldNeedsUpdate=!0,i.linearVelocity?(s.hasLinearVelocity=!0,s.linearVelocity.copy(i.linearVelocity)):s.hasLinearVelocity=!1,i.angularVelocity?(s.hasAngularVelocity=!0,s.angularVelocity.copy(i.angularVelocity)):s.hasAngularVelocity=!1));o!==null&&(r=t.getPose(e.targetRaySpace,n),r===null&&i!==null&&(r=i),r!==null&&(o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,r.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(r.linearVelocity)):o.hasLinearVelocity=!1,r.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(r.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(si)))}return o!==null&&(o.visible=r!==null),s!==null&&(s.visible=i!==null),c!==null&&(c.visible=a!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){let n=new oi;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}},li=class extends Kn{constructor(){super(),this.isScene=!0,this.type=`Scene`,this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new kn,this.environmentIntensity=1,this.environmentRotation=new kn,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`observe`,{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){let t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}},ui=class{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=e===void 0?0:e.length/t,this.usage=Ve,this.updateRanges=[],this.version=0,this.uuid=Je()}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,t,n){e*=this.stride,n*=t.stride;for(let r=0,i=this.stride;r<i;r++)this.array[e+r]=t.array[n+r];return this}set(e,t=0){return this.array.set(e,t),this}clone(e){e.arrayBuffers===void 0&&(e.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=Je()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=this.array.slice(0).buffer);let t=new this.array.constructor(e.arrayBuffers[this.array.buffer._uuid]),n=new this.constructor(t,this.stride);return n.setUsage(this.usage),n}onUpload(e){return this.onUploadCallback=e,this}toJSON(e){return e.arrayBuffers===void 0&&(e.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=Je()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=Array.from(new Uint32Array(this.array.buffer))),{uuid:this.uuid,buffer:this.array.buffer._uuid,type:this.array.constructor.name,stride:this.stride}}},di=new R,fi=class e{constructor(e,t,n,r=!1){this.isInterleavedBufferAttribute=!0,this.name=``,this.data=e,this.itemSize=t,this.offset=n,this.normalized=r}get count(){return this.data.count}get array(){return this.data.array}set needsUpdate(e){this.data.needsUpdate=e}applyMatrix4(e){for(let t=0,n=this.data.count;t<n;t++)di.fromBufferAttribute(this,t),di.applyMatrix4(e),this.setXYZ(t,di.x,di.y,di.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)di.fromBufferAttribute(this,t),di.applyNormalMatrix(e),this.setXYZ(t,di.x,di.y,di.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)di.fromBufferAttribute(this,t),di.transformDirection(e),this.setXYZ(t,di.x,di.y,di.z);return this}getComponent(e,t){let n=this.array[e*this.data.stride+this.offset+t];return this.normalized&&(n=pt(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=mt(n,this.array)),this.data.array[e*this.data.stride+this.offset+t]=n,this}setX(e,t){return this.normalized&&(t=mt(t,this.array)),this.data.array[e*this.data.stride+this.offset]=t,this}setY(e,t){return this.normalized&&(t=mt(t,this.array)),this.data.array[e*this.data.stride+this.offset+1]=t,this}setZ(e,t){return this.normalized&&(t=mt(t,this.array)),this.data.array[e*this.data.stride+this.offset+2]=t,this}setW(e,t){return this.normalized&&(t=mt(t,this.array)),this.data.array[e*this.data.stride+this.offset+3]=t,this}getX(e){let t=this.data.array[e*this.data.stride+this.offset];return this.normalized&&(t=pt(t,this.array)),t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(t=pt(t,this.array)),t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(t=pt(t,this.array)),t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(t=pt(t,this.array)),t}setXY(e,t,n){return e=e*this.data.stride+this.offset,this.normalized&&(t=mt(t,this.array),n=mt(n,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this}setXYZ(e,t,n,r){return e=e*this.data.stride+this.offset,this.normalized&&(t=mt(t,this.array),n=mt(n,this.array),r=mt(r,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this.data.array[e+2]=r,this}setXYZW(e,t,n,r,i){return e=e*this.data.stride+this.offset,this.normalized&&(t=mt(t,this.array),n=mt(n,this.array),r=mt(r,this.array),i=mt(i,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this.data.array[e+2]=r,this.data.array[e+3]=i,this}clone(t){if(t===void 0){console.log(`THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.`);let e=[];for(let t=0;t<this.count;t++){let n=t*this.data.stride+this.offset;for(let t=0;t<this.itemSize;t++)e.push(this.data.array[n+t])}return new V(new this.array.constructor(e),this.itemSize,this.normalized)}else return t.interleavedBuffers===void 0&&(t.interleavedBuffers={}),t.interleavedBuffers[this.data.uuid]===void 0&&(t.interleavedBuffers[this.data.uuid]=this.data.clone(t)),new e(t.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(e){if(e===void 0){console.log(`THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.`);let e=[];for(let t=0;t<this.count;t++){let n=t*this.data.stride+this.offset;for(let t=0;t<this.itemSize;t++)e.push(this.data.array[n+t])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:e,normalized:this.normalized}}else return e.interleavedBuffers===void 0&&(e.interleavedBuffers={}),e.interleavedBuffers[this.data.uuid]===void 0&&(e.interleavedBuffers[this.data.uuid]=this.data.toJSON(e)),{isInterleavedBufferAttribute:!0,itemSize:this.itemSize,data:this.data.uuid,offset:this.offset,normalized:this.normalized}}},pi=class extends pr{constructor(e){super(),this.isSpriteMaterial=!0,this.type=`SpriteMaterial`,this.color=new B(16777215),this.map=null,this.alphaMap=null,this.rotation=0,this.sizeAttenuation=!0,this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.rotation=e.rotation,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}},mi,hi=new R,gi=new R,_i=new R,vi=new L,yi=new L,bi=new yn,xi=new R,Si=new R,Ci=new R,wi=new L,Ti=new L,Ei=new L,Di=class extends Kn{constructor(e=new pi){if(super(),this.isSprite=!0,this.type=`Sprite`,mi===void 0){mi=new H;let e=new ui(new Float32Array([-.5,-.5,0,0,0,.5,-.5,0,1,0,.5,.5,0,1,1,-.5,.5,0,0,1]),5);mi.setIndex([0,1,2,0,2,3]),mi.setAttribute(`position`,new fi(e,3,0,!1)),mi.setAttribute(`uv`,new fi(e,2,3,!1))}this.geometry=mi,this.material=e,this.center=new L(.5,.5),this.count=1}raycast(e,t){e.camera===null&&console.error(`THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.`),gi.setFromMatrixScale(this.matrixWorld),bi.copy(e.camera.matrixWorld),this.modelViewMatrix.multiplyMatrices(e.camera.matrixWorldInverse,this.matrixWorld),_i.setFromMatrixPosition(this.modelViewMatrix),e.camera.isPerspectiveCamera&&this.material.sizeAttenuation===!1&&gi.multiplyScalar(-_i.z);let n=this.material.rotation,r,i;n!==0&&(i=Math.cos(n),r=Math.sin(n));let a=this.center;Oi(xi.set(-.5,-.5,0),_i,a,gi,r,i),Oi(Si.set(.5,-.5,0),_i,a,gi,r,i),Oi(Ci.set(.5,.5,0),_i,a,gi,r,i),wi.set(0,0),Ti.set(1,0),Ei.set(1,1);let o=e.ray.intersectTriangle(xi,Si,Ci,!1,hi);if(o===null&&(Oi(Si.set(-.5,.5,0),_i,a,gi,r,i),Ti.set(0,1),o=e.ray.intersectTriangle(xi,Ci,Si,!1,hi),o===null))return;let s=e.ray.origin.distanceTo(hi);s<e.near||s>e.far||t.push({distance:s,point:hi.clone(),uv:or.getInterpolation(hi,xi,Si,Ci,wi,Ti,Ei,new L),face:null,object:this})}copy(e,t){return super.copy(e,t),e.center!==void 0&&this.center.copy(e.center),this.material=e.material,this}};function Oi(e,t,n,r,i,a){vi.subVectors(e,n).addScalar(.5).multiply(r),i===void 0?yi.copy(vi):(yi.x=a*vi.x-i*vi.y,yi.y=i*vi.x+a*vi.y),e.copy(t),e.x+=yi.x,e.y+=yi.y,e.applyMatrix4(bi)}var ki=new R,Ai=new R,ji=new z,Mi=class{constructor(e=new R(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,n,r){return this.normal.set(e,t,n),this.constant=r,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,n){let r=ki.subVectors(n,t).cross(Ai.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(r,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){let e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t){let n=e.delta(ki),r=this.normal.dot(n);if(r===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;let i=-(e.start.dot(this.normal)+this.constant)/r;return i<0||i>1?null:t.copy(e.start).addScaledVector(n,i)}intersectsLine(e){let t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){let n=t||ji.getNormalMatrix(e),r=this.coplanarPoint(ki).applyMatrix4(e),i=this.normal.applyMatrix3(n).normalize();return this.constant=-r.dot(i),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}},Ni=new un,Pi=new L(.5,.5),Fi=new R,Ii=class{constructor(e=new Mi,t=new Mi,n=new Mi,r=new Mi,i=new Mi,a=new Mi){this.planes=[e,t,n,r,i,a]}set(e,t,n,r,i,a){let o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(n),o[3].copy(r),o[4].copy(i),o[5].copy(a),this}copy(e){let t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=He,n=!1){let r=this.planes,i=e.elements,a=i[0],o=i[1],s=i[2],c=i[3],l=i[4],u=i[5],d=i[6],f=i[7],p=i[8],m=i[9],h=i[10],g=i[11],_=i[12],v=i[13],y=i[14],b=i[15];if(r[0].setComponents(c-a,f-l,g-p,b-_).normalize(),r[1].setComponents(c+a,f+l,g+p,b+_).normalize(),r[2].setComponents(c+o,f+u,g+m,b+v).normalize(),r[3].setComponents(c-o,f-u,g-m,b-v).normalize(),n)r[4].setComponents(s,d,h,y).normalize(),r[5].setComponents(c-s,f-d,g-h,b-y).normalize();else if(r[4].setComponents(c-s,f-d,g-h,b-y).normalize(),t===2e3)r[5].setComponents(c+s,f+d,g+h,b+y).normalize();else if(t===2001)r[5].setComponents(s,d,h,y).normalize();else throw Error(`THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: `+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),Ni.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{let t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),Ni.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Ni)}intersectsSprite(e){return Ni.center.set(0,0,0),Ni.radius=.7071067811865476+Pi.distanceTo(e.center),Ni.applyMatrix4(e.matrixWorld),this.intersectsSphere(Ni)}intersectsSphere(e){let t=this.planes,n=e.center,r=-e.radius;for(let e=0;e<6;e++)if(t[e].distanceToPoint(n)<r)return!1;return!0}intersectsBox(e){let t=this.planes;for(let n=0;n<6;n++){let r=t[n];if(Fi.x=r.normal.x>0?e.max.x:e.min.x,Fi.y=r.normal.y>0?e.max.y:e.min.y,Fi.z=r.normal.z>0?e.max.z:e.min.z,r.distanceToPoint(Fi)<0)return!1}return!0}containsPoint(e){let t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}},Li=class extends pr{constructor(e){super(),this.isLineBasicMaterial=!0,this.type=`LineBasicMaterial`,this.color=new B(16777215),this.map=null,this.linewidth=1,this.linecap=`round`,this.linejoin=`round`,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.linewidth=e.linewidth,this.linecap=e.linecap,this.linejoin=e.linejoin,this.fog=e.fog,this}},Ri=new R,zi=new R,Bi=new yn,Vi=new vn,Hi=new un,Ui=new R,Wi=new R,Gi=class extends Kn{constructor(e=new H,t=new Li){super(),this.isLine=!0,this.type=`Line`,this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}computeLineDistances(){let e=this.geometry;if(e.index===null){let t=e.attributes.position,n=[0];for(let e=1,r=t.count;e<r;e++)Ri.fromBufferAttribute(t,e-1),zi.fromBufferAttribute(t,e),n[e]=n[e-1],n[e]+=Ri.distanceTo(zi);e.setAttribute(`lineDistance`,new br(n,1))}else console.warn(`THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.`);return this}raycast(e,t){let n=this.geometry,r=this.matrixWorld,i=e.params.Line.threshold,a=n.drawRange;if(n.boundingSphere===null&&n.computeBoundingSphere(),Hi.copy(n.boundingSphere),Hi.applyMatrix4(r),Hi.radius+=i,e.ray.intersectsSphere(Hi)===!1)return;Bi.copy(r).invert(),Vi.copy(e.ray).applyMatrix4(Bi);let o=i/((this.scale.x+this.scale.y+this.scale.z)/3),s=o*o,c=this.isLineSegments?2:1,l=n.index,u=n.attributes.position;if(l!==null){let n=Math.max(0,a.start),r=Math.min(l.count,a.start+a.count);for(let i=n,a=r-1;i<a;i+=c){let n=l.getX(i),r=l.getX(i+1),a=Ki(this,e,Vi,s,n,r,i);a&&t.push(a)}if(this.isLineLoop){let i=l.getX(r-1),a=l.getX(n),o=Ki(this,e,Vi,s,i,a,r-1);o&&t.push(o)}}else{let n=Math.max(0,a.start),r=Math.min(u.count,a.start+a.count);for(let i=n,a=r-1;i<a;i+=c){let n=Ki(this,e,Vi,s,i,i+1,i);n&&t.push(n)}if(this.isLineLoop){let i=Ki(this,e,Vi,s,r-1,n,r-1);i&&t.push(i)}}}updateMorphTargets(){let e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){let n=e[t[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e<t;e++){let t=n[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[t]=e}}}}};function Ki(e,t,n,r,i,a,o){let s=e.geometry.attributes.position;if(Ri.fromBufferAttribute(s,i),zi.fromBufferAttribute(s,a),n.distanceSqToSegment(Ri,zi,Ui,Wi)>r)return;Ui.applyMatrix4(e.matrixWorld);let c=t.ray.origin.distanceTo(Ui);if(!(c<t.near||c>t.far))return{distance:c,point:Wi.clone().applyMatrix4(e.matrixWorld),index:o,face:null,faceIndex:null,barycoord:null,object:e}}var qi=new R,Ji=new R,Yi=class extends Gi{constructor(e,t){super(e,t),this.isLineSegments=!0,this.type=`LineSegments`}computeLineDistances(){let e=this.geometry;if(e.index===null){let t=e.attributes.position,n=[];for(let e=0,r=t.count;e<r;e+=2)qi.fromBufferAttribute(t,e),Ji.fromBufferAttribute(t,e+1),n[e]=e===0?0:n[e-1],n[e+1]=n[e]+qi.distanceTo(Ji);e.setAttribute(`lineDistance`,new br(n,1))}else console.warn(`THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.`);return this}},Xi=class extends pr{constructor(e){super(),this.isPointsMaterial=!0,this.type=`PointsMaterial`,this.color=new B(16777215),this.map=null,this.alphaMap=null,this.size=1,this.sizeAttenuation=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.size=e.size,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}},Zi=new yn,Qi=new vn,$i=new un,ea=new R,ta=class extends Kn{constructor(e=new H,t=new Xi){super(),this.isPoints=!0,this.type=`Points`,this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}raycast(e,t){let n=this.geometry,r=this.matrixWorld,i=e.params.Points.threshold,a=n.drawRange;if(n.boundingSphere===null&&n.computeBoundingSphere(),$i.copy(n.boundingSphere),$i.applyMatrix4(r),$i.radius+=i,e.ray.intersectsSphere($i)===!1)return;Zi.copy(r).invert(),Qi.copy(e.ray).applyMatrix4(Zi);let o=i/((this.scale.x+this.scale.y+this.scale.z)/3),s=o*o,c=n.index,l=n.attributes.position;if(c!==null){let n=Math.max(0,a.start),i=Math.min(c.count,a.start+a.count);for(let a=n,o=i;a<o;a++){let n=c.getX(a);ea.fromBufferAttribute(l,n),na(ea,n,s,r,e,t,this)}}else{let n=Math.max(0,a.start),i=Math.min(l.count,a.start+a.count);for(let a=n,o=i;a<o;a++)ea.fromBufferAttribute(l,a),na(ea,a,s,r,e,t,this)}}updateMorphTargets(){let e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){let n=e[t[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e<t;e++){let t=n[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[t]=e}}}}};function na(e,t,n,r,i,a,o){let s=Qi.distanceSqToPoint(e);if(s<n){let n=new R;Qi.closestPointToPoint(e,n),n.applyMatrix4(r);let c=i.ray.origin.distanceTo(n);if(c<i.near||c>i.far)return;a.push({distance:c,distanceToRay:Math.sqrt(s),point:n,index:t,face:null,faceIndex:null,barycoord:null,object:o})}}var ra=class extends zt{constructor(e,t,n,r,i,a,o,s,c){super(e,t,n,r,i,a,o,s,c),this.isCanvasTexture=!0,this.needsUpdate=!0}},ia=class extends zt{constructor(e,t,n=m,i,a,o,s=r,c=r,l,u=T,d=1){if(u!==1026&&u!==1027)throw Error(`DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat`);super({width:e,height:t,depth:d},i,a,o,s,c,u,n,l),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new Ft(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){let t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}},aa=class extends zt{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}},oa=class e extends H{constructor(e=1,t=32,n=0,r=Math.PI*2){super(),this.type=`CircleGeometry`,this.parameters={radius:e,segments:t,thetaStart:n,thetaLength:r},t=Math.max(3,t);let i=[],a=[],o=[],s=[],c=new R,l=new L;a.push(0,0,0),o.push(0,0,1),s.push(.5,.5);for(let i=0,u=3;i<=t;i++,u+=3){let d=n+i/t*r;c.x=e*Math.cos(d),c.y=e*Math.sin(d),a.push(c.x,c.y,c.z),o.push(0,0,1),l.x=(a[u]/e+1)/2,l.y=(a[u+1]/e+1)/2,s.push(l.x,l.y)}for(let e=1;e<=t;e++)i.push(e,e+1,0);this.setIndex(i),this.setAttribute(`position`,new br(a,3)),this.setAttribute(`normal`,new br(o,3)),this.setAttribute(`uv`,new br(s,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(t){return new e(t.radius,t.segments,t.thetaStart,t.thetaLength)}},sa=class e extends H{constructor(e=1,t=1,n=1,r=32,i=1,a=!1,o=0,s=Math.PI*2){super(),this.type=`CylinderGeometry`,this.parameters={radiusTop:e,radiusBottom:t,height:n,radialSegments:r,heightSegments:i,openEnded:a,thetaStart:o,thetaLength:s};let c=this;r=Math.floor(r),i=Math.floor(i);let l=[],u=[],d=[],f=[],p=0,m=[],h=n/2,g=0;_(),a===!1&&(e>0&&v(!0),t>0&&v(!1)),this.setIndex(l),this.setAttribute(`position`,new br(u,3)),this.setAttribute(`normal`,new br(d,3)),this.setAttribute(`uv`,new br(f,2));function _(){let a=new R,_=new R,v=0,y=(t-e)/n;for(let c=0;c<=i;c++){let l=[],g=c/i,v=g*(t-e)+e;for(let e=0;e<=r;e++){let t=e/r,i=t*s+o,c=Math.sin(i),m=Math.cos(i);_.x=v*c,_.y=-g*n+h,_.z=v*m,u.push(_.x,_.y,_.z),a.set(c,y,m).normalize(),d.push(a.x,a.y,a.z),f.push(t,1-g),l.push(p++)}m.push(l)}for(let n=0;n<r;n++)for(let r=0;r<i;r++){let a=m[r][n],o=m[r+1][n],s=m[r+1][n+1],c=m[r][n+1];(e>0||r!==0)&&(l.push(a,o,c),v+=3),(t>0||r!==i-1)&&(l.push(o,s,c),v+=3)}c.addGroup(g,v,0),g+=v}function v(n){let i=p,a=new L,m=new R,_=0,v=n===!0?e:t,y=n===!0?1:-1;for(let e=1;e<=r;e++)u.push(0,h*y,0),d.push(0,y,0),f.push(.5,.5),p++;let b=p;for(let e=0;e<=r;e++){let t=e/r*s+o,n=Math.cos(t),i=Math.sin(t);m.x=v*i,m.y=h*y,m.z=v*n,u.push(m.x,m.y,m.z),d.push(0,y,0),a.x=n*.5+.5,a.y=i*.5*y+.5,f.push(a.x,a.y),p++}for(let e=0;e<r;e++){let t=i+e,r=b+e;n===!0?l.push(r,r+1,t):l.push(r+1,r,t),_+=3}c.addGroup(g,_,n===!0?1:2),g+=_}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(t){return new e(t.radiusTop,t.radiusBottom,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}},ca=class e extends sa{constructor(e=1,t=1,n=32,r=1,i=!1,a=0,o=Math.PI*2){super(0,e,t,n,r,i,a,o),this.type=`ConeGeometry`,this.parameters={radius:e,height:t,radialSegments:n,heightSegments:r,openEnded:i,thetaStart:a,thetaLength:o}}static fromJSON(t){return new e(t.radius,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}},la=new R,ua=new R,da=new R,fa=new or,pa=class extends H{constructor(e=null,t=1){if(super(),this.type=`EdgesGeometry`,this.parameters={geometry:e,thresholdAngle:t},e!==null){let n=10**4,r=Math.cos(Ke*t),i=e.getIndex(),a=e.getAttribute(`position`),o=i?i.count:a.count,s=[0,0,0],c=[`a`,`b`,`c`],l=[,,,],u={},d=[];for(let e=0;e<o;e+=3){i?(s[0]=i.getX(e),s[1]=i.getX(e+1),s[2]=i.getX(e+2)):(s[0]=e,s[1]=e+1,s[2]=e+2);let{a:t,b:o,c:f}=fa;if(t.fromBufferAttribute(a,s[0]),o.fromBufferAttribute(a,s[1]),f.fromBufferAttribute(a,s[2]),fa.getNormal(da),l[0]=`${Math.round(t.x*n)},${Math.round(t.y*n)},${Math.round(t.z*n)}`,l[1]=`${Math.round(o.x*n)},${Math.round(o.y*n)},${Math.round(o.z*n)}`,l[2]=`${Math.round(f.x*n)},${Math.round(f.y*n)},${Math.round(f.z*n)}`,!(l[0]===l[1]||l[1]===l[2]||l[2]===l[0]))for(let e=0;e<3;e++){let t=(e+1)%3,n=l[e],i=l[t],a=fa[c[e]],o=fa[c[t]],f=`${n}_${i}`,p=`${i}_${n}`;p in u&&u[p]?(da.dot(u[p].normal)<=r&&(d.push(a.x,a.y,a.z),d.push(o.x,o.y,o.z)),u[p]=null):f in u||(u[f]={index0:s[e],index1:s[t],normal:da.clone()})}}for(let e in u)if(u[e]){let{index0:t,index1:n}=u[e];la.fromBufferAttribute(a,t),ua.fromBufferAttribute(a,n),d.push(la.x,la.y,la.z),d.push(ua.x,ua.y,ua.z)}this.setAttribute(`position`,new br(d,3))}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}},ma=class e extends H{constructor(e=1,t=1,n=1,r=1){super(),this.type=`PlaneGeometry`,this.parameters={width:e,height:t,widthSegments:n,heightSegments:r};let i=e/2,a=t/2,o=Math.floor(n),s=Math.floor(r),c=o+1,l=s+1,u=e/o,d=t/s,f=[],p=[],m=[],h=[];for(let e=0;e<l;e++){let t=e*d-a;for(let n=0;n<c;n++){let r=n*u-i;p.push(r,-t,0),m.push(0,0,1),h.push(n/o),h.push(1-e/s)}}for(let e=0;e<s;e++)for(let t=0;t<o;t++){let n=t+c*e,r=t+c*(e+1),i=t+1+c*(e+1),a=t+1+c*e;f.push(n,r,a),f.push(r,i,a)}this.setIndex(f),this.setAttribute(`position`,new br(p,3)),this.setAttribute(`normal`,new br(m,3)),this.setAttribute(`uv`,new br(h,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(t){return new e(t.width,t.height,t.widthSegments,t.heightSegments)}},ha=class e extends H{constructor(e=1,t=32,n=16,r=0,i=Math.PI*2,a=0,o=Math.PI){super(),this.type=`SphereGeometry`,this.parameters={radius:e,widthSegments:t,heightSegments:n,phiStart:r,phiLength:i,thetaStart:a,thetaLength:o},t=Math.max(3,Math.floor(t)),n=Math.max(2,Math.floor(n));let s=Math.min(a+o,Math.PI),c=0,l=[],u=new R,d=new R,f=[],p=[],m=[],h=[];for(let f=0;f<=n;f++){let g=[],_=f/n,v=0;f===0&&a===0?v=.5/t:f===n&&s===Math.PI&&(v=-.5/t);for(let n=0;n<=t;n++){let s=n/t;u.x=-e*Math.cos(r+s*i)*Math.sin(a+_*o),u.y=e*Math.cos(a+_*o),u.z=e*Math.sin(r+s*i)*Math.sin(a+_*o),p.push(u.x,u.y,u.z),d.copy(u).normalize(),m.push(d.x,d.y,d.z),h.push(s+v,1-_),g.push(c++)}l.push(g)}for(let e=0;e<n;e++)for(let r=0;r<t;r++){let t=l[e][r+1],i=l[e][r],o=l[e+1][r],c=l[e+1][r+1];(e!==0||a>0)&&f.push(t,i,c),(e!==n-1||s<Math.PI)&&f.push(i,o,c)}this.setIndex(f),this.setAttribute(`position`,new br(p,3)),this.setAttribute(`normal`,new br(m,3)),this.setAttribute(`uv`,new br(h,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(t){return new e(t.radius,t.widthSegments,t.heightSegments,t.phiStart,t.phiLength,t.thetaStart,t.thetaLength)}},ga=class extends H{constructor(e=null){if(super(),this.type=`WireframeGeometry`,this.parameters={geometry:e},e!==null){let t=[],n=new Set,r=new R,i=new R;if(e.index!==null){let a=e.attributes.position,o=e.index,s=e.groups;s.length===0&&(s=[{start:0,count:o.count,materialIndex:0}]);for(let e=0,c=s.length;e<c;++e){let c=s[e],l=c.start,u=c.count;for(let e=l,s=l+u;e<s;e+=3)for(let s=0;s<3;s++){let c=o.getX(e+s),l=o.getX(e+(s+1)%3);r.fromBufferAttribute(a,c),i.fromBufferAttribute(a,l),_a(r,i,n)===!0&&(t.push(r.x,r.y,r.z),t.push(i.x,i.y,i.z))}}}else{let a=e.attributes.position;for(let e=0,o=a.count/3;e<o;e++)for(let o=0;o<3;o++){let s=3*e+o,c=3*e+(o+1)%3;r.fromBufferAttribute(a,s),i.fromBufferAttribute(a,c),_a(r,i,n)===!0&&(t.push(r.x,r.y,r.z),t.push(i.x,i.y,i.z))}}this.setAttribute(`position`,new br(t,3))}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}};function _a(e,t,n){let r=`${e.x},${e.y},${e.z}-${t.x},${t.y},${t.z}`,i=`${t.x},${t.y},${t.z}-${e.x},${e.y},${e.z}`;return n.has(r)===!0||n.has(i)===!0?!1:(n.add(r),n.add(i),!0)}var va=class extends pr{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type=`MeshPhongMaterial`,this.color=new B(16777215),this.specular=new B(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new B(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new L(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new kn,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap=`round`,this.wireframeLinejoin=`round`,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}},ya=class extends pr{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type=`MeshDepthMaterial`,this.depthPacking=Pe,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}},ba=class extends pr{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type=`MeshDistanceMaterial`,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}},xa=class extends Li{constructor(e){super(),this.isLineDashedMaterial=!0,this.type=`LineDashedMaterial`,this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(e)}copy(e){return super.copy(e),this.scale=e.scale,this.dashSize=e.dashSize,this.gapSize=e.gapSize,this}};function Sa(e,t){return!e||e.constructor===t?e:typeof t.BYTES_PER_ELEMENT==`number`?new t(e):Array.prototype.slice.call(e)}function Ca(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}var wa=class{constructor(e,t,n,r){this.parameterPositions=e,this._cachedIndex=0,this.resultBuffer=r===void 0?new t.constructor(n):r,this.sampleValues=t,this.valueSize=n,this.settings=null,this.DefaultSettings_={}}evaluate(e){let t=this.parameterPositions,n=this._cachedIndex,r=t[n],i=t[n-1];validate_interval:{seek:{let a;linear_scan:{forward_scan:if(!(e<r)){for(let a=n+2;;){if(r===void 0){if(e<i)break forward_scan;return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}if(n===a)break;if(i=r,r=t[++n],e<r)break seek}a=t.length;break linear_scan}if(!(e>=i)){let o=t[1];e<o&&(n=2,i=o);for(let a=n-2;;){if(i===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(n===a)break;if(r=i,i=t[--n-1],e>=i)break seek}a=n,n=0;break linear_scan}break validate_interval}for(;n<a;){let r=n+a>>>1;e<t[r]?a=r:n=r+1}if(r=t[n],i=t[n-1],i===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(r===void 0)return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}this._cachedIndex=n,this.intervalChanged_(n,i,r)}return this.interpolate_(n,i,e,r)}getSettings_(){return this.settings||this.DefaultSettings_}copySampleValue_(e){let t=this.resultBuffer,n=this.sampleValues,r=this.valueSize,i=e*r;for(let e=0;e!==r;++e)t[e]=n[i+e];return t}interpolate_(){throw Error(`call to abstract method`)}intervalChanged_(){}},Ta=class extends wa{constructor(e,t,n,r){super(e,t,n,r),this._weightPrev=-0,this._offsetPrev=-0,this._weightNext=-0,this._offsetNext=-0,this.DefaultSettings_={endingStart:je,endingEnd:je}}intervalChanged_(e,t,n){let r=this.parameterPositions,i=e-2,a=e+1,o=r[i],s=r[a];if(o===void 0)switch(this.getSettings_().endingStart){case Me:i=e,o=2*t-n;break;case Ne:i=r.length-2,o=t+r[i]-r[i+1];break;default:i=e,o=n}if(s===void 0)switch(this.getSettings_().endingEnd){case Me:a=e,s=2*n-t;break;case Ne:a=1,s=n+r[1]-r[0];break;default:a=e-1,s=t}let c=(n-t)*.5,l=this.valueSize;this._weightPrev=c/(t-o),this._weightNext=c/(s-n),this._offsetPrev=i*l,this._offsetNext=a*l}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=e*o,c=s-o,l=this._offsetPrev,u=this._offsetNext,d=this._weightPrev,f=this._weightNext,p=(n-t)/(r-t),m=p*p,h=m*p,g=-d*h+2*d*m-d*p,_=(1+d)*h+(-1.5-2*d)*m+(-.5+d)*p+1,v=(-1-f)*h+(1.5+f)*m+.5*p,y=f*h-f*m;for(let e=0;e!==o;++e)i[e]=g*a[l+e]+_*a[c+e]+v*a[s+e]+y*a[u+e];return i}},Ea=class extends wa{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=e*o,c=s-o,l=(n-t)/(r-t),u=1-l;for(let e=0;e!==o;++e)i[e]=a[c+e]*u+a[s+e]*l;return i}},Da=class extends wa{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e){return this.copySampleValue_(e-1)}},Oa=class{constructor(e,t,n,r){if(e===void 0)throw Error(`THREE.KeyframeTrack: track name is undefined`);if(t===void 0||t.length===0)throw Error(`THREE.KeyframeTrack: no keyframes in track named `+e);this.name=e,this.times=Sa(t,this.TimeBufferType),this.values=Sa(n,this.ValueBufferType),this.setInterpolation(r||this.DefaultInterpolation)}static toJSON(e){let t=e.constructor,n;if(t.toJSON!==this.toJSON)n=t.toJSON(e);else{n={name:e.name,times:Sa(e.times,Array),values:Sa(e.values,Array)};let t=e.getInterpolation();t!==e.DefaultInterpolation&&(n.interpolation=t)}return n.type=e.ValueTypeName,n}InterpolantFactoryMethodDiscrete(e){return new Da(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodLinear(e){return new Ea(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodSmooth(e){return new Ta(this.times,this.values,this.getValueSize(),e)}setInterpolation(e){let t;switch(e){case Oe:t=this.InterpolantFactoryMethodDiscrete;break;case ke:t=this.InterpolantFactoryMethodLinear;break;case Ae:t=this.InterpolantFactoryMethodSmooth;break}if(t===void 0){let t=`unsupported interpolation for `+this.ValueTypeName+` keyframe track named `+this.name;if(this.createInterpolant===void 0)if(e!==this.DefaultInterpolation)this.setInterpolation(this.DefaultInterpolation);else throw Error(t);return console.warn(`THREE.KeyframeTrack:`,t),this}return this.createInterpolant=t,this}getInterpolation(){switch(this.createInterpolant){case this.InterpolantFactoryMethodDiscrete:return Oe;case this.InterpolantFactoryMethodLinear:return ke;case this.InterpolantFactoryMethodSmooth:return Ae}}getValueSize(){return this.values.length/this.times.length}shift(e){if(e!==0){let t=this.times;for(let n=0,r=t.length;n!==r;++n)t[n]+=e}return this}scale(e){if(e!==1){let t=this.times;for(let n=0,r=t.length;n!==r;++n)t[n]*=e}return this}trim(e,t){let n=this.times,r=n.length,i=0,a=r-1;for(;i!==r&&n[i]<e;)++i;for(;a!==-1&&n[a]>t;)--a;if(++a,i!==0||a!==r){i>=a&&(a=Math.max(a,1),i=a-1);let e=this.getValueSize();this.times=n.slice(i,a),this.values=this.values.slice(i*e,a*e)}return this}validate(){let e=!0,t=this.getValueSize();t-Math.floor(t)!==0&&(console.error(`THREE.KeyframeTrack: Invalid value size in track.`,this),e=!1);let n=this.times,r=this.values,i=n.length;i===0&&(console.error(`THREE.KeyframeTrack: Track is empty.`,this),e=!1);let a=null;for(let t=0;t!==i;t++){let r=n[t];if(typeof r==`number`&&isNaN(r)){console.error(`THREE.KeyframeTrack: Time is not a valid number.`,this,t,r),e=!1;break}if(a!==null&&a>r){console.error(`THREE.KeyframeTrack: Out of order keys.`,this,t,r,a),e=!1;break}a=r}if(r!==void 0&&Ca(r))for(let t=0,n=r.length;t!==n;++t){let n=r[t];if(isNaN(n)){console.error(`THREE.KeyframeTrack: Value is not a valid number.`,this,t,n),e=!1;break}}return e}optimize(){let e=this.times.slice(),t=this.values.slice(),n=this.getValueSize(),r=this.getInterpolation()===Ae,i=e.length-1,a=1;for(let o=1;o<i;++o){let i=!1,s=e[o];if(s!==e[o+1]&&(o!==1||s!==e[0]))if(r)i=!0;else{let e=o*n,r=e-n,a=e+n;for(let o=0;o!==n;++o){let n=t[e+o];if(n!==t[r+o]||n!==t[a+o]){i=!0;break}}}if(i){if(o!==a){e[a]=e[o];let r=o*n,i=a*n;for(let e=0;e!==n;++e)t[i+e]=t[r+e]}++a}}if(i>0){e[a]=e[i];for(let e=i*n,r=a*n,o=0;o!==n;++o)t[r+o]=t[e+o];++a}return a===e.length?(this.times=e,this.values=t):(this.times=e.slice(0,a),this.values=t.slice(0,a*n)),this}clone(){let e=this.times.slice(),t=this.values.slice(),n=this.constructor,r=new n(this.name,e,t);return r.createInterpolant=this.createInterpolant,r}};Oa.prototype.ValueTypeName=``,Oa.prototype.TimeBufferType=Float32Array,Oa.prototype.ValueBufferType=Float32Array,Oa.prototype.DefaultInterpolation=ke;var ka=class extends Oa{constructor(e,t,n){super(e,t,n)}};ka.prototype.ValueTypeName=`bool`,ka.prototype.ValueBufferType=Array,ka.prototype.DefaultInterpolation=Oe,ka.prototype.InterpolantFactoryMethodLinear=void 0,ka.prototype.InterpolantFactoryMethodSmooth=void 0;var Aa=class extends Oa{constructor(e,t,n,r){super(e,t,n,r)}};Aa.prototype.ValueTypeName=`color`;var ja=class extends Oa{constructor(e,t,n,r){super(e,t,n,r)}};ja.prototype.ValueTypeName=`number`;var Ma=class extends wa{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=(n-t)/(r-t),c=e*o;for(let e=c+o;c!==e;c+=4)gt.slerpFlat(i,0,a,c-o,a,c,s);return i}},Na=class extends Oa{constructor(e,t,n,r){super(e,t,n,r)}InterpolantFactoryMethodLinear(e){return new Ma(this.times,this.values,this.getValueSize(),e)}};Na.prototype.ValueTypeName=`quaternion`,Na.prototype.InterpolantFactoryMethodSmooth=void 0;var Pa=class extends Oa{constructor(e,t,n){super(e,t,n)}};Pa.prototype.ValueTypeName=`string`,Pa.prototype.ValueBufferType=Array,Pa.prototype.DefaultInterpolation=Oe,Pa.prototype.InterpolantFactoryMethodLinear=void 0,Pa.prototype.InterpolantFactoryMethodSmooth=void 0;var Fa=class extends Oa{constructor(e,t,n,r){super(e,t,n,r)}};Fa.prototype.ValueTypeName=`vector`;var Ia=new class{constructor(e,t,n){let r=this,i=!1,a=0,o=0,s,c=[];this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=n,this.abortController=new AbortController,this.itemStart=function(e){o++,i===!1&&r.onStart!==void 0&&r.onStart(e,a,o),i=!0},this.itemEnd=function(e){a++,r.onProgress!==void 0&&r.onProgress(e,a,o),a===o&&(i=!1,r.onLoad!==void 0&&r.onLoad())},this.itemError=function(e){r.onError!==void 0&&r.onError(e)},this.resolveURL=function(e){return s?s(e):e},this.setURLModifier=function(e){return s=e,this},this.addHandler=function(e,t){return c.push(e,t),this},this.removeHandler=function(e){let t=c.indexOf(e);return t!==-1&&c.splice(t,2),this},this.getHandler=function(e){for(let t=0,n=c.length;t<n;t+=2){let n=c[t],r=c[t+1];if(n.global&&(n.lastIndex=0),n.test(e))return r}return null},this.abort=function(){return this.abortController.abort(),this.abortController=new AbortController,this}}},La=class{constructor(e){this.manager=e===void 0?Ia:e,this.crossOrigin=`anonymous`,this.withCredentials=!1,this.path=``,this.resourcePath=``,this.requestHeader={}}load(){}loadAsync(e,t){let n=this;return new Promise(function(r,i){n.load(e,r,t,i)})}parse(){}setCrossOrigin(e){return this.crossOrigin=e,this}setWithCredentials(e){return this.withCredentials=e,this}setPath(e){return this.path=e,this}setResourcePath(e){return this.resourcePath=e,this}setRequestHeader(e){return this.requestHeader=e,this}abort(){return this}};La.DEFAULT_MATERIAL_NAME=`__DEFAULT`;var Ra=class extends Kn{constructor(e,t=1){super(),this.isLight=!0,this.type=`Light`,this.color=new B(e),this.intensity=t}dispose(){}copy(e,t){return super.copy(e,t),this.color.copy(e.color),this.intensity=e.intensity,this}toJSON(e){let t=super.toJSON(e);return t.object.color=this.color.getHex(),t.object.intensity=this.intensity,this.groundColor!==void 0&&(t.object.groundColor=this.groundColor.getHex()),this.distance!==void 0&&(t.object.distance=this.distance),this.angle!==void 0&&(t.object.angle=this.angle),this.decay!==void 0&&(t.object.decay=this.decay),this.penumbra!==void 0&&(t.object.penumbra=this.penumbra),this.shadow!==void 0&&(t.object.shadow=this.shadow.toJSON()),this.target!==void 0&&(t.object.target=this.target.uuid),t}},za=new yn,Ba=new R,Va=new R,Ha=class{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new L(512,512),this.mapType=l,this.map=null,this.mapPass=null,this.matrix=new yn,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new Ii,this._frameExtents=new L(1,1),this._viewportCount=1,this._viewports=[new Bt(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){let t=this.camera,n=this.matrix;Ba.setFromMatrixPosition(e.matrixWorld),t.position.copy(Ba),Va.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(Va),t.updateMatrixWorld(),za.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(za,t.coordinateSystem,t.reversedDepth),t.reversedDepth?n.set(.5,0,0,.5,0,.5,0,.5,0,0,1,0,0,0,0,1):n.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),n.multiply(za)}getViewport(e){return this._viewports[e]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(e){return this.camera=e.camera.clone(),this.intensity=e.intensity,this.bias=e.bias,this.radius=e.radius,this.autoUpdate=e.autoUpdate,this.needsUpdate=e.needsUpdate,this.normalBias=e.normalBias,this.blurSamples=e.blurSamples,this.mapSize.copy(e.mapSize),this}clone(){return new this.constructor().copy(this)}toJSON(){let e={};return this.intensity!==1&&(e.intensity=this.intensity),this.bias!==0&&(e.bias=this.bias),this.normalBias!==0&&(e.normalBias=this.normalBias),this.radius!==1&&(e.radius=this.radius),(this.mapSize.x!==512||this.mapSize.y!==512)&&(e.mapSize=this.mapSize.toArray()),e.camera=this.camera.toJSON(!1).object,delete e.camera.matrix,e}},Ua=class extends Xr{constructor(e=-1,t=1,n=1,r=-1,i=.1,a=2e3){super(),this.isOrthographicCamera=!0,this.type=`OrthographicCamera`,this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=n,this.bottom=r,this.near=i,this.far=a,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,t,n,r,i,a){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=r,this.view.width=i,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),n=(this.right+this.left)/2,r=(this.top+this.bottom)/2,i=n-e,a=n+e,o=r+t,s=r-t;if(this.view!==null&&this.view.enabled){let e=(this.right-this.left)/this.view.fullWidth/this.zoom,t=(this.top-this.bottom)/this.view.fullHeight/this.zoom;i+=e*this.view.offsetX,a=i+e*this.view.width,o-=t*this.view.offsetY,s=o-t*this.view.height}this.projectionMatrix.makeOrthographic(i,a,o,s,this.near,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,this.view!==null&&(t.object.view=Object.assign({},this.view)),t}},Wa=class extends Ha{constructor(){super(new Ua(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}},Ga=class extends Ra{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type=`DirectionalLight`,this.position.copy(Kn.DEFAULT_UP),this.updateMatrix(),this.target=new Kn,this.shadow=new Wa}dispose(){this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}},Ka=class extends Ra{constructor(e,t){super(e,t),this.isAmbientLight=!0,this.type=`AmbientLight`}},qa=class extends H{constructor(){super(),this.isInstancedBufferGeometry=!0,this.type=`InstancedBufferGeometry`,this.instanceCount=1/0}copy(e){return super.copy(e),this.instanceCount=e.instanceCount,this}toJSON(){let e=super.toJSON();return e.instanceCount=this.instanceCount,e.isInstancedBufferGeometry=!0,e}},Ja=class extends ei{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}},Ya=class{constructor(e=!0){this.autoStart=e,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=performance.now(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let e=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){let t=performance.now();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}},Xa=`\\[\\]\\.:\\/`,Za=RegExp(`[`+Xa+`]`,`g`),Qa=`[^`+Xa+`]`,$a=`[^`+Xa.replace(`\\.`,``)+`]`,eo=`((?:WC+[\\/:])*)`.replace(`WC`,Qa),to=`(WCOD+)?`.replace(`WCOD`,$a),no=`(?:\\.(WC+)(?:\\[(.+)\\])?)?`.replace(`WC`,Qa),ro=`\\.(WC+)(?:\\[(.+)\\])?`.replace(`WC`,Qa),io=RegExp(`^`+eo+to+no+ro+`$`),ao=[`material`,`materials`,`bones`,`map`],oo=class{constructor(e,t,n){let r=n||so.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,r)}getValue(e,t){this.bind();let n=this._targetGroup.nCachedObjects_,r=this._bindings[n];r!==void 0&&r.getValue(e,t)}setValue(e,t){let n=this._bindings;for(let r=this._targetGroup.nCachedObjects_,i=n.length;r!==i;++r)n[r].setValue(e,t)}bind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].bind()}unbind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].unbind()}},so=class e{constructor(t,n,r){this.path=n,this.parsedPath=r||e.parseTrackName(n),this.node=e.findNode(t,this.parsedPath.nodeName),this.rootNode=t,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(t,n,r){return t&&t.isAnimationObjectGroup?new e.Composite(t,n,r):new e(t,n,r)}static sanitizeNodeName(e){return e.replace(/\s/g,`_`).replace(Za,``)}static parseTrackName(e){let t=io.exec(e);if(t===null)throw Error(`PropertyBinding: Cannot parse trackName: `+e);let n={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},r=n.nodeName&&n.nodeName.lastIndexOf(`.`);if(r!==void 0&&r!==-1){let e=n.nodeName.substring(r+1);ao.indexOf(e)!==-1&&(n.nodeName=n.nodeName.substring(0,r),n.objectName=e)}if(n.propertyName===null||n.propertyName.length===0)throw Error(`PropertyBinding: can not parse propertyName from trackName: `+e);return n}static findNode(e,t){if(t===void 0||t===``||t===`.`||t===-1||t===e.name||t===e.uuid)return e;if(e.skeleton){let n=e.skeleton.getBoneByName(t);if(n!==void 0)return n}if(e.children){let n=function(e){for(let r=0;r<e.length;r++){let i=e[r];if(i.name===t||i.uuid===t)return i;let a=n(i.children);if(a)return a}return null},r=n(e.children);if(r)return r}return null}_getValue_unavailable(){}_setValue_unavailable(){}_getValue_direct(e,t){e[t]=this.targetObject[this.propertyName]}_getValue_array(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)e[t++]=n[r]}_getValue_arrayElement(e,t){e[t]=this.resolvedProperty[this.propertyIndex]}_getValue_toArray(e,t){this.resolvedProperty.toArray(e,t)}_setValue_direct(e,t){this.targetObject[this.propertyName]=e[t]}_setValue_direct_setNeedsUpdate(e,t){this.targetObject[this.propertyName]=e[t],this.targetObject.needsUpdate=!0}_setValue_direct_setMatrixWorldNeedsUpdate(e,t){this.targetObject[this.propertyName]=e[t],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_array(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)n[r]=e[t++]}_setValue_array_setNeedsUpdate(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)n[r]=e[t++];this.targetObject.needsUpdate=!0}_setValue_array_setMatrixWorldNeedsUpdate(e,t){let n=this.resolvedProperty;for(let r=0,i=n.length;r!==i;++r)n[r]=e[t++];this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_arrayElement(e,t){this.resolvedProperty[this.propertyIndex]=e[t]}_setValue_arrayElement_setNeedsUpdate(e,t){this.resolvedProperty[this.propertyIndex]=e[t],this.targetObject.needsUpdate=!0}_setValue_arrayElement_setMatrixWorldNeedsUpdate(e,t){this.resolvedProperty[this.propertyIndex]=e[t],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_fromArray(e,t){this.resolvedProperty.fromArray(e,t)}_setValue_fromArray_setNeedsUpdate(e,t){this.resolvedProperty.fromArray(e,t),this.targetObject.needsUpdate=!0}_setValue_fromArray_setMatrixWorldNeedsUpdate(e,t){this.resolvedProperty.fromArray(e,t),this.targetObject.matrixWorldNeedsUpdate=!0}_getValue_unbound(e,t){this.bind(),this.getValue(e,t)}_setValue_unbound(e,t){this.bind(),this.setValue(e,t)}bind(){let t=this.node,n=this.parsedPath,r=n.objectName,i=n.propertyName,a=n.propertyIndex;if(t||(t=e.findNode(this.rootNode,n.nodeName),this.node=t),this.getValue=this._getValue_unavailable,this.setValue=this._setValue_unavailable,!t){console.warn(`THREE.PropertyBinding: No target node found for track: `+this.path+`.`);return}if(r){let e=n.objectIndex;switch(r){case`materials`:if(!t.material){console.error(`THREE.PropertyBinding: Can not bind to material as node does not have a material.`,this);return}if(!t.material.materials){console.error(`THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.`,this);return}t=t.material.materials;break;case`bones`:if(!t.skeleton){console.error(`THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.`,this);return}t=t.skeleton.bones;for(let n=0;n<t.length;n++)if(t[n].name===e){e=n;break}break;case`map`:if(`map`in t){t=t.map;break}if(!t.material){console.error(`THREE.PropertyBinding: Can not bind to material as node does not have a material.`,this);return}if(!t.material.map){console.error(`THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.`,this);return}t=t.material.map;break;default:if(t[r]===void 0){console.error(`THREE.PropertyBinding: Can not bind to objectName of node undefined.`,this);return}t=t[r]}if(e!==void 0){if(t[e]===void 0){console.error(`THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.`,this,t);return}t=t[e]}}let o=t[i];if(o===void 0){let e=n.nodeName;console.error(`THREE.PropertyBinding: Trying to update property for track: `+e+`.`+i+` but it wasn't found.`,t);return}let s=this.Versioning.None;this.targetObject=t,t.isMaterial===!0?s=this.Versioning.NeedsUpdate:t.isObject3D===!0&&(s=this.Versioning.MatrixWorldNeedsUpdate);let c=this.BindingType.Direct;if(a!==void 0){if(i===`morphTargetInfluences`){if(!t.geometry){console.error(`THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.`,this);return}if(!t.geometry.morphAttributes){console.error(`THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.`,this);return}t.morphTargetDictionary[a]!==void 0&&(a=t.morphTargetDictionary[a])}c=this.BindingType.ArrayElement,this.resolvedProperty=o,this.propertyIndex=a}else o.fromArray!==void 0&&o.toArray!==void 0?(c=this.BindingType.HasFromToArray,this.resolvedProperty=o):Array.isArray(o)?(c=this.BindingType.EntireArray,this.resolvedProperty=o):this.propertyName=i;this.getValue=this.GetterByBindingType[c],this.setValue=this.SetterByBindingTypeAndVersioning[c][s]}unbind(){this.node=null,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}};so.Composite=oo,so.prototype.BindingType={Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3},so.prototype.Versioning={None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2},so.prototype.GetterByBindingType=[so.prototype._getValue_direct,so.prototype._getValue_array,so.prototype._getValue_arrayElement,so.prototype._getValue_toArray],so.prototype.SetterByBindingTypeAndVersioning=[[so.prototype._setValue_direct,so.prototype._setValue_direct_setNeedsUpdate,so.prototype._setValue_direct_setMatrixWorldNeedsUpdate],[so.prototype._setValue_array,so.prototype._setValue_array_setNeedsUpdate,so.prototype._setValue_array_setMatrixWorldNeedsUpdate],[so.prototype._setValue_arrayElement,so.prototype._setValue_arrayElement_setNeedsUpdate,so.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate],[so.prototype._setValue_fromArray,so.prototype._setValue_fromArray_setNeedsUpdate,so.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];var co=class extends ui{constructor(e,t,n=1){super(e,t),this.isInstancedInterleavedBuffer=!0,this.meshPerAttribute=n}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}clone(e){let t=super.clone(e);return t.meshPerAttribute=this.meshPerAttribute,t}toJSON(e){let t=super.toJSON(e);return t.isInstancedInterleavedBuffer=!0,t.meshPerAttribute=this.meshPerAttribute,t}},lo=new yn,uo=class{constructor(e,t,n=0,r=1/0){this.ray=new vn(e,t),this.near=n,this.far=r,this.camera=null,this.layers=new An,this.params={Mesh:{},Line:{threshold:1},LOD:{},Points:{threshold:1},Sprite:{}}}set(e,t){this.ray.set(e,t)}setFromCamera(e,t){t.isPerspectiveCamera?(this.ray.origin.setFromMatrixPosition(t.matrixWorld),this.ray.direction.set(e.x,e.y,.5).unproject(t).sub(this.ray.origin).normalize(),this.camera=t):t.isOrthographicCamera?(this.ray.origin.set(e.x,e.y,(t.near+t.far)/(t.near-t.far)).unproject(t),this.ray.direction.set(0,0,-1).transformDirection(t.matrixWorld),this.camera=t):console.error(`THREE.Raycaster: Unsupported camera type: `+t.type)}setFromXRController(e){return lo.identity().extractRotation(e.matrixWorld),this.ray.origin.setFromMatrixPosition(e.matrixWorld),this.ray.direction.set(0,0,-1).applyMatrix4(lo),this}intersectObject(e,t=!0,n=[]){return po(e,this,n,t),n.sort(fo),n}intersectObjects(e,t=!0,n=[]){for(let r=0,i=e.length;r<i;r++)po(e[r],this,n,t);return n.sort(fo),n}};function fo(e,t){return e.distance-t.distance}function po(e,t,n,r){let i=!0;if(e.layers.test(t.layers)&&e.raycast(t,n)===!1&&(i=!1),i===!0&&r===!0){let r=e.children;for(let e=0,i=r.length;e<i;e++)po(r[e],t,n,!0)}}var mo=class{constructor(e=1,t=0,n=0){this.radius=e,this.phi=t,this.theta=n}set(e,t,n){return this.radius=e,this.phi=t,this.theta=n,this}copy(e){return this.radius=e.radius,this.phi=e.phi,this.theta=e.theta,this}makeSafe(){let e=1e-6;return this.phi=I(this.phi,e,Math.PI-e),this}setFromVector3(e){return this.setFromCartesianCoords(e.x,e.y,e.z)}setFromCartesianCoords(e,t,n){return this.radius=Math.sqrt(e*e+t*t+n*n),this.radius===0?(this.theta=0,this.phi=0):(this.theta=Math.atan2(e,n),this.phi=Math.acos(I(t/this.radius,-1,1))),this}clone(){return new this.constructor().copy(this)}},ho=new R,go=new R,_o=new R,vo=new R,yo=new R,bo=new R,xo=new R,So=class{constructor(e=new R,t=new R){this.start=e,this.end=t}set(e,t){return this.start.copy(e),this.end.copy(t),this}copy(e){return this.start.copy(e.start),this.end.copy(e.end),this}getCenter(e){return e.addVectors(this.start,this.end).multiplyScalar(.5)}delta(e){return e.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(e,t){return this.delta(t).multiplyScalar(e).add(this.start)}closestPointToPointParameter(e,t){ho.subVectors(e,this.start),go.subVectors(this.end,this.start);let n=go.dot(go),r=go.dot(ho)/n;return t&&(r=I(r,0,1)),r}closestPointToPoint(e,t,n){let r=this.closestPointToPointParameter(e,t);return this.delta(n).multiplyScalar(r).add(this.start)}distanceSqToLine3(e,t=bo,n=xo){let r=1e-8*1e-8,i,a,o=this.start,s=e.start,c=this.end,l=e.end;_o.subVectors(c,o),vo.subVectors(l,s),yo.subVectors(o,s);let u=_o.dot(_o),d=vo.dot(vo),f=vo.dot(yo);if(u<=r&&d<=r)return t.copy(o),n.copy(s),t.sub(n),t.dot(t);if(u<=r)i=0,a=f/d,a=I(a,0,1);else{let e=_o.dot(yo);if(d<=r)a=0,i=I(-e/u,0,1);else{let t=_o.dot(vo),n=u*d-t*t;i=n===0?0:I((t*f-e*d)/n,0,1),a=(t*i+f)/d,a<0?(a=0,i=I(-e/u,0,1)):a>1&&(a=1,i=I((t-e)/u,0,1))}}return t.copy(o).add(_o.multiplyScalar(i)),n.copy(s).add(vo.multiplyScalar(a)),t.sub(n),t.dot(t)}applyMatrix4(e){return this.start.applyMatrix4(e),this.end.applyMatrix4(e),this}equals(e){return e.start.equals(this.start)&&e.end.equals(this.end)}clone(){return new this.constructor().copy(this)}},Co=class extends Yi{constructor(e=1){let t=[0,0,0,e,0,0,0,0,0,0,e,0,0,0,0,0,0,e],n=[1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],r=new H;r.setAttribute(`position`,new br(t,3)),r.setAttribute(`color`,new br(n,3));let i=new Li({vertexColors:!0,toneMapped:!1});super(r,i),this.type=`AxesHelper`}setColors(e,t,n){let r=new B,i=this.geometry.attributes.color.array;return r.set(e),r.toArray(i,0),r.toArray(i,3),r.set(t),r.toArray(i,6),r.toArray(i,9),r.set(n),r.toArray(i,12),r.toArray(i,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}};function wo(e,t,n,r){let i=To(r);switch(n){case S:return e*t;case D:return e*t/i.components*i.byteLength;case ee:return e*t/i.components*i.byteLength;case O:return e*t*2/i.components*i.byteLength;case k:return e*t*2/i.components*i.byteLength;case C:return e*t*3/i.components*i.byteLength;case w:return e*t*4/i.components*i.byteLength;case te:return e*t*4/i.components*i.byteLength;case ne:case A:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case re:case ie:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case ae:case se:return Math.max(e,16)*Math.max(t,8)/4;case j:case oe:return Math.max(e,8)*Math.max(t,8)/2;case ce:case le:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case ue:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case de:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case fe:return Math.floor((e+4)/5)*Math.floor((t+3)/4)*16;case pe:return Math.floor((e+4)/5)*Math.floor((t+4)/5)*16;case me:return Math.floor((e+5)/6)*Math.floor((t+4)/5)*16;case he:return Math.floor((e+5)/6)*Math.floor((t+5)/6)*16;case ge:return Math.floor((e+7)/8)*Math.floor((t+4)/5)*16;case _e:return Math.floor((e+7)/8)*Math.floor((t+5)/6)*16;case ve:return Math.floor((e+7)/8)*Math.floor((t+7)/8)*16;case M:return Math.floor((e+9)/10)*Math.floor((t+4)/5)*16;case ye:return Math.floor((e+9)/10)*Math.floor((t+5)/6)*16;case be:return Math.floor((e+9)/10)*Math.floor((t+7)/8)*16;case xe:return Math.floor((e+9)/10)*Math.floor((t+9)/10)*16;case N:return Math.floor((e+11)/12)*Math.floor((t+9)/10)*16;case Se:return Math.floor((e+11)/12)*Math.floor((t+11)/12)*16;case P:case F:case Ce:return Math.ceil(e/4)*Math.ceil(t/4)*16;case we:case Te:return Math.ceil(e/4)*Math.ceil(t/4)*8;case Ee:case De:return Math.ceil(e/4)*Math.ceil(t/4)*16}throw Error(`Unable to determine texture byte length for ${n} format.`)}function To(e){switch(e){case l:case u:return{byteLength:1,components:1};case f:case d:case g:return{byteLength:2,components:1};case _:case v:return{byteLength:2,components:4};case m:case p:case h:return{byteLength:4,components:1};case b:case x:return{byteLength:4,components:3}}throw Error(`Unknown texture type ${e}.`)}typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`register`,{detail:{revision:`180`}})),typeof window<`u`&&(window.__THREE__?console.warn(`WARNING: Multiple instances of Three.js being imported.`):window.__THREE__=`180`);function Eo(){let e=null,t=!1,n=null,r=null;function i(t,a){n(t,a),r=e.requestAnimationFrame(i)}return{start:function(){t!==!0&&n!==null&&(r=e.requestAnimationFrame(i),t=!0)},stop:function(){e.cancelAnimationFrame(r),t=!1},setAnimationLoop:function(e){n=e},setContext:function(t){e=t}}}function Do(e){let t=new WeakMap;function n(t,n){let r=t.array,i=t.usage,a=r.byteLength,o=e.createBuffer();e.bindBuffer(n,o),e.bufferData(n,r,i),t.onUploadCallback();let s;if(r instanceof Float32Array)s=e.FLOAT;else if(typeof Float16Array<`u`&&r instanceof Float16Array)s=e.HALF_FLOAT;else if(r instanceof Uint16Array)s=t.isFloat16BufferAttribute?e.HALF_FLOAT:e.UNSIGNED_SHORT;else if(r instanceof Int16Array)s=e.SHORT;else if(r instanceof Uint32Array)s=e.UNSIGNED_INT;else if(r instanceof Int32Array)s=e.INT;else if(r instanceof Int8Array)s=e.BYTE;else if(r instanceof Uint8Array)s=e.UNSIGNED_BYTE;else if(r instanceof Uint8ClampedArray)s=e.UNSIGNED_BYTE;else throw Error(`THREE.WebGLAttributes: Unsupported buffer data format: `+r);return{buffer:o,type:s,bytesPerElement:r.BYTES_PER_ELEMENT,version:t.version,size:a}}function r(t,n,r){let i=n.array,a=n.updateRanges;if(e.bindBuffer(r,t),a.length===0)e.bufferSubData(r,0,i);else{a.sort((e,t)=>e.start-t.start);let t=0;for(let e=1;e<a.length;e++){let n=a[t],r=a[e];r.start<=n.start+n.count+1?n.count=Math.max(n.count,r.start+r.count-n.start):(++t,a[t]=r)}a.length=t+1;for(let t=0,n=a.length;t<n;t++){let n=a[t];e.bufferSubData(r,n.start*i.BYTES_PER_ELEMENT,i,n.start,n.count)}n.clearUpdateRanges()}n.onUploadCallback()}function i(e){return e.isInterleavedBufferAttribute&&(e=e.data),t.get(e)}function a(n){n.isInterleavedBufferAttribute&&(n=n.data);let r=t.get(n);r&&(e.deleteBuffer(r.buffer),t.delete(n))}function o(e,i){if(e.isInterleavedBufferAttribute&&(e=e.data),e.isGLBufferAttribute){let n=t.get(e);(!n||n.version<e.version)&&t.set(e,{buffer:e.buffer,type:e.type,bytesPerElement:e.elementSize,version:e.version});return}let a=t.get(e);if(a===void 0)t.set(e,n(e,i));else if(a.version<e.version){if(a.size!==e.array.byteLength)throw Error(`THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported.`);r(a.buffer,e,i),a.version=e.version}}return{get:i,remove:a,update:o}}var W={alphahash_fragment:`#ifdef USE_ALPHAHASH
41
41
  if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;
42
42
  #endif`,alphahash_pars_fragment:`#ifdef USE_ALPHAHASH
43
43
  const float ALPHA_HASH_SCALE = 0.05;
@@ -3576,7 +3576,7 @@ void main() {
3576
3576
  #include <tonemapping_fragment>
3577
3577
  #include <colorspace_fragment>
3578
3578
  #include <fog_fragment>
3579
- }`},W={common:{diffuse:{value:new B(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new z},alphaMap:{value:null},alphaMapTransform:{value:new z},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new z}},envmap:{envMap:{value:null},envMapRotation:{value:new z},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new z}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new z}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new z},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new z},normalScale:{value:new L(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new z},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new z}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new z}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new z}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new B(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new B(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new z},alphaTest:{value:0},uvTransform:{value:new z}},sprite:{diffuse:{value:new B(16777215)},opacity:{value:1},center:{value:new L(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new z},alphaMap:{value:null},alphaMapTransform:{value:new z},alphaTest:{value:0}}},So={basic:{uniforms:Wr([W.common,W.specularmap,W.envmap,W.aomap,W.lightmap,W.fog]),vertexShader:U.meshbasic_vert,fragmentShader:U.meshbasic_frag},lambert:{uniforms:Wr([W.common,W.specularmap,W.envmap,W.aomap,W.lightmap,W.emissivemap,W.bumpmap,W.normalmap,W.displacementmap,W.fog,W.lights,{emissive:{value:new B(0)}}]),vertexShader:U.meshlambert_vert,fragmentShader:U.meshlambert_frag},phong:{uniforms:Wr([W.common,W.specularmap,W.envmap,W.aomap,W.lightmap,W.emissivemap,W.bumpmap,W.normalmap,W.displacementmap,W.fog,W.lights,{emissive:{value:new B(0)},specular:{value:new B(1118481)},shininess:{value:30}}]),vertexShader:U.meshphong_vert,fragmentShader:U.meshphong_frag},standard:{uniforms:Wr([W.common,W.envmap,W.aomap,W.lightmap,W.emissivemap,W.bumpmap,W.normalmap,W.displacementmap,W.roughnessmap,W.metalnessmap,W.fog,W.lights,{emissive:{value:new B(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:U.meshphysical_vert,fragmentShader:U.meshphysical_frag},toon:{uniforms:Wr([W.common,W.aomap,W.lightmap,W.emissivemap,W.bumpmap,W.normalmap,W.displacementmap,W.gradientmap,W.fog,W.lights,{emissive:{value:new B(0)}}]),vertexShader:U.meshtoon_vert,fragmentShader:U.meshtoon_frag},matcap:{uniforms:Wr([W.common,W.bumpmap,W.normalmap,W.displacementmap,W.fog,{matcap:{value:null}}]),vertexShader:U.meshmatcap_vert,fragmentShader:U.meshmatcap_frag},points:{uniforms:Wr([W.points,W.fog]),vertexShader:U.points_vert,fragmentShader:U.points_frag},dashed:{uniforms:Wr([W.common,W.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:U.linedashed_vert,fragmentShader:U.linedashed_frag},depth:{uniforms:Wr([W.common,W.displacementmap]),vertexShader:U.depth_vert,fragmentShader:U.depth_frag},normal:{uniforms:Wr([W.common,W.bumpmap,W.normalmap,W.displacementmap,{opacity:{value:1}}]),vertexShader:U.meshnormal_vert,fragmentShader:U.meshnormal_frag},sprite:{uniforms:Wr([W.sprite,W.fog]),vertexShader:U.sprite_vert,fragmentShader:U.sprite_frag},background:{uniforms:{uvTransform:{value:new z},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:U.background_vert,fragmentShader:U.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new z}},vertexShader:U.backgroundCube_vert,fragmentShader:U.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:U.cube_vert,fragmentShader:U.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:U.equirect_vert,fragmentShader:U.equirect_frag},distanceRGBA:{uniforms:Wr([W.common,W.displacementmap,{referencePosition:{value:new R},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:U.distanceRGBA_vert,fragmentShader:U.distanceRGBA_frag},shadow:{uniforms:Wr([W.lights,W.fog,{color:{value:new B(0)},opacity:{value:1}}]),vertexShader:U.shadow_vert,fragmentShader:U.shadow_frag}};So.physical={uniforms:Wr([So.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new z},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new z},clearcoatNormalScale:{value:new L(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new z},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new z},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new z},sheen:{value:0},sheenColor:{value:new B(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new z},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new z},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new z},transmissionSamplerSize:{value:new L},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new z},attenuationDistance:{value:0},attenuationColor:{value:new B(0)},specularColor:{value:new B(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new z},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new z},anisotropyVector:{value:new L},anisotropyMap:{value:null},anisotropyMapTransform:{value:new z}}]),vertexShader:U.meshphysical_vert,fragmentShader:U.meshphysical_frag};var Co={r:0,b:0,g:0},wo=new kn,To=new yn;function Eo(e,t,n,r,i,a,o){let s=new B(0),c=a===!0?0:1,l,u,d=null,f=0,p=null;function m(e){let r=e.isScene===!0?e.background:null;return r&&r.isTexture&&(r=(e.backgroundBlurriness>0?n:t).get(r)),r}function h(t){let n=!1,i=m(t);i===null?_(s,c):i&&i.isColor&&(_(i,1),n=!0);let a=e.xr.getEnvironmentBlendMode();a===`additive`?r.buffers.color.setClear(0,0,0,1,o):a===`alpha-blend`&&r.buffers.color.setClear(0,0,0,0,o),(e.autoClear||n)&&(r.buffers.depth.setTest(!0),r.buffers.depth.setMask(!0),r.buffers.color.setMask(!0),e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil))}function g(t,n){let r=m(n);r&&(r.isCubeTexture||r.mapping===306)?(u===void 0&&(u=new H(new Hr(1,1,1),new Xr({name:`BackgroundCubeMaterial`,uniforms:Ur(So.backgroundCube.uniforms),vertexShader:So.backgroundCube.vertexShader,fragmentShader:So.backgroundCube.fragmentShader,side:1,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),u.geometry.deleteAttribute(`normal`),u.geometry.deleteAttribute(`uv`),u.onBeforeRender=function(e,t,n){this.matrixWorld.copyPosition(n.matrixWorld)},Object.defineProperty(u.material,`envMap`,{get:function(){return this.uniforms.envMap.value}}),i.update(u)),wo.copy(n.backgroundRotation),wo.x*=-1,wo.y*=-1,wo.z*=-1,r.isCubeTexture&&r.isRenderTargetTexture===!1&&(wo.y*=-1,wo.z*=-1),u.material.uniforms.envMap.value=r,u.material.uniforms.flipEnvMap.value=r.isCubeTexture&&r.isRenderTargetTexture===!1?-1:1,u.material.uniforms.backgroundBlurriness.value=n.backgroundBlurriness,u.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,u.material.uniforms.backgroundRotation.value.setFromMatrix4(To.makeRotationFromEuler(wo)),u.material.toneMapped=kt.getTransfer(r.colorSpace)!==ze,(d!==r||f!==r.version||p!==e.toneMapping)&&(u.material.needsUpdate=!0,d=r,f=r.version,p=e.toneMapping),u.layers.enableAll(),t.unshift(u,u.geometry,u.material,0,0,null)):r&&r.isTexture&&(l===void 0&&(l=new H(new ca(2,2),new Xr({name:`BackgroundMaterial`,uniforms:Ur(So.background.uniforms),vertexShader:So.background.vertexShader,fragmentShader:So.background.fragmentShader,side:0,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute(`normal`),Object.defineProperty(l.material,`map`,{get:function(){return this.uniforms.t2D.value}}),i.update(l)),l.material.uniforms.t2D.value=r,l.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,l.material.toneMapped=kt.getTransfer(r.colorSpace)!==ze,r.matrixAutoUpdate===!0&&r.updateMatrix(),l.material.uniforms.uvTransform.value.copy(r.matrix),(d!==r||f!==r.version||p!==e.toneMapping)&&(l.material.needsUpdate=!0,d=r,f=r.version,p=e.toneMapping),l.layers.enableAll(),t.unshift(l,l.geometry,l.material,0,0,null))}function _(t,n){t.getRGB(Co,Kr(e)),r.buffers.color.setClear(Co.r,Co.g,Co.b,n,o)}function v(){u!==void 0&&(u.geometry.dispose(),u.material.dispose(),u=void 0),l!==void 0&&(l.geometry.dispose(),l.material.dispose(),l=void 0)}return{getClearColor:function(){return s},setClearColor:function(e,t=1){s.set(e),c=t,_(s,c)},getClearAlpha:function(){return c},setClearAlpha:function(e){c=e,_(s,c)},render:h,addToRenderList:g,dispose:v}}function Do(e,t){let n=e.getParameter(e.MAX_VERTEX_ATTRIBS),r={},i=f(null),a=i,o=!1;function s(n,r,i,s,c){let u=!1,f=d(s,i,r);a!==f&&(a=f,l(a.object)),u=p(n,s,i,c),u&&m(n,s,i,c),c!==null&&t.update(c,e.ELEMENT_ARRAY_BUFFER),(u||o)&&(o=!1,b(n,r,i,s),c!==null&&e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,t.get(c).buffer))}function c(){return e.createVertexArray()}function l(t){return e.bindVertexArray(t)}function u(t){return e.deleteVertexArray(t)}function d(e,t,n){let i=n.wireframe===!0,a=r[e.id];a===void 0&&(a={},r[e.id]=a);let o=a[t.id];o===void 0&&(o={},a[t.id]=o);let s=o[i];return s===void 0&&(s=f(c()),o[i]=s),s}function f(e){let t=[],r=[],i=[];for(let e=0;e<n;e++)t[e]=0,r[e]=0,i[e]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:t,enabledAttributes:r,attributeDivisors:i,object:e,attributes:{},index:null}}function p(e,t,n,r){let i=a.attributes,o=t.attributes,s=0,c=n.getAttributes();for(let t in c)if(c[t].location>=0){let n=i[t],r=o[t];if(r===void 0&&(t===`instanceMatrix`&&e.instanceMatrix&&(r=e.instanceMatrix),t===`instanceColor`&&e.instanceColor&&(r=e.instanceColor)),n===void 0||n.attribute!==r||r&&n.data!==r.data)return!0;s++}return a.attributesNum!==s||a.index!==r}function m(e,t,n,r){let i={},o=t.attributes,s=0,c=n.getAttributes();for(let t in c)if(c[t].location>=0){let n=o[t];n===void 0&&(t===`instanceMatrix`&&e.instanceMatrix&&(n=e.instanceMatrix),t===`instanceColor`&&e.instanceColor&&(n=e.instanceColor));let r={};r.attribute=n,n&&n.data&&(r.data=n.data),i[t]=r,s++}a.attributes=i,a.attributesNum=s,a.index=r}function h(){let e=a.newAttributes;for(let t=0,n=e.length;t<n;t++)e[t]=0}function g(e){_(e,0)}function _(t,n){let r=a.newAttributes,i=a.enabledAttributes,o=a.attributeDivisors;r[t]=1,i[t]===0&&(e.enableVertexAttribArray(t),i[t]=1),o[t]!==n&&(e.vertexAttribDivisor(t,n),o[t]=n)}function v(){let t=a.newAttributes,n=a.enabledAttributes;for(let r=0,i=n.length;r<i;r++)n[r]!==t[r]&&(e.disableVertexAttribArray(r),n[r]=0)}function y(t,n,r,i,a,o,s){s===!0?e.vertexAttribIPointer(t,n,r,a,o):e.vertexAttribPointer(t,n,r,i,a,o)}function b(n,r,i,a){h();let o=a.attributes,s=i.getAttributes(),c=r.defaultAttributeValues;for(let r in s){let i=s[r];if(i.location>=0){let s=o[r];if(s===void 0&&(r===`instanceMatrix`&&n.instanceMatrix&&(s=n.instanceMatrix),r===`instanceColor`&&n.instanceColor&&(s=n.instanceColor)),s!==void 0){let r=s.normalized,o=s.itemSize,c=t.get(s);if(c===void 0)continue;let l=c.buffer,u=c.type,d=c.bytesPerElement,f=u===e.INT||u===e.UNSIGNED_INT||s.gpuType===1013;if(s.isInterleavedBufferAttribute){let t=s.data,c=t.stride,p=s.offset;if(t.isInstancedInterleavedBuffer){for(let e=0;e<i.locationSize;e++)_(i.location+e,t.meshPerAttribute);n.isInstancedMesh!==!0&&a._maxInstanceCount===void 0&&(a._maxInstanceCount=t.meshPerAttribute*t.count)}else for(let e=0;e<i.locationSize;e++)g(i.location+e);e.bindBuffer(e.ARRAY_BUFFER,l);for(let e=0;e<i.locationSize;e++)y(i.location+e,o/i.locationSize,u,r,c*d,(p+o/i.locationSize*e)*d,f)}else{if(s.isInstancedBufferAttribute){for(let e=0;e<i.locationSize;e++)_(i.location+e,s.meshPerAttribute);n.isInstancedMesh!==!0&&a._maxInstanceCount===void 0&&(a._maxInstanceCount=s.meshPerAttribute*s.count)}else for(let e=0;e<i.locationSize;e++)g(i.location+e);e.bindBuffer(e.ARRAY_BUFFER,l);for(let e=0;e<i.locationSize;e++)y(i.location+e,o/i.locationSize,u,r,o*d,o/i.locationSize*e*d,f)}}else if(c!==void 0){let t=c[r];if(t!==void 0)switch(t.length){case 2:e.vertexAttrib2fv(i.location,t);break;case 3:e.vertexAttrib3fv(i.location,t);break;case 4:e.vertexAttrib4fv(i.location,t);break;default:e.vertexAttrib1fv(i.location,t)}}}}v()}function x(){w();for(let e in r){let t=r[e];for(let e in t){let n=t[e];for(let e in n)u(n[e].object),delete n[e];delete t[e]}delete r[e]}}function S(e){if(r[e.id]===void 0)return;let t=r[e.id];for(let e in t){let n=t[e];for(let e in n)u(n[e].object),delete n[e];delete t[e]}delete r[e.id]}function C(e){for(let t in r){let n=r[t];if(n[e.id]===void 0)continue;let i=n[e.id];for(let e in i)u(i[e].object),delete i[e];delete n[e.id]}}function w(){T(),o=!0,a!==i&&(a=i,l(a.object))}function T(){i.geometry=null,i.program=null,i.wireframe=!1}return{setup:s,reset:w,resetDefaultState:T,dispose:x,releaseStatesOfGeometry:S,releaseStatesOfProgram:C,initAttributes:h,enableAttribute:g,disableUnusedAttributes:v}}function Oo(e,t,n){let r;function i(e){r=e}function a(t,i){e.drawArrays(r,t,i),n.update(i,r,1)}function o(t,i,a){a!==0&&(e.drawArraysInstanced(r,t,i,a),n.update(i,r,a))}function s(e,i,a){if(a===0)return;t.get(`WEBGL_multi_draw`).multiDrawArraysWEBGL(r,e,0,i,0,a);let o=0;for(let e=0;e<a;e++)o+=i[e];n.update(o,r,1)}function c(e,i,a,s){if(a===0)return;let c=t.get(`WEBGL_multi_draw`);if(c===null)for(let t=0;t<e.length;t++)o(e[t],i[t],s[t]);else{c.multiDrawArraysInstancedWEBGL(r,e,0,i,0,s,0,a);let t=0;for(let e=0;e<a;e++)t+=i[e]*s[e];n.update(t,r,1)}}this.setMode=i,this.render=a,this.renderInstances=o,this.renderMultiDraw=s,this.renderMultiDrawInstances=c}function ko(e,t,n,r){let i;function a(){if(i!==void 0)return i;if(t.has(`EXT_texture_filter_anisotropic`)===!0){let n=t.get(`EXT_texture_filter_anisotropic`);i=e.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else i=0;return i}function o(t){return!(t!==1023&&r.convert(t)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT))}function s(n){let i=n===1016&&(t.has(`EXT_color_buffer_half_float`)||t.has(`EXT_color_buffer_float`));return!(n!==1009&&r.convert(n)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)&&n!==1015&&!i)}function c(t){if(t===`highp`){if(e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.HIGH_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0)return`highp`;t=`mediump`}return t===`mediump`&&e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.MEDIUM_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?`mediump`:`lowp`}let l=n.precision===void 0?`highp`:n.precision,u=c(l);u!==l&&(console.warn(`THREE.WebGLRenderer:`,l,`not supported, using`,u,`instead.`),l=u);let d=n.logarithmicDepthBuffer===!0,f=n.reversedDepthBuffer===!0&&t.has(`EXT_clip_control`),p=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),m=e.getParameter(e.MAX_VERTEX_TEXTURE_IMAGE_UNITS),h=e.getParameter(e.MAX_TEXTURE_SIZE),g=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),_=e.getParameter(e.MAX_VERTEX_ATTRIBS),v=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),y=e.getParameter(e.MAX_VARYING_VECTORS),b=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),x=m>0,S=e.getParameter(e.MAX_SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:a,getMaxPrecision:c,textureFormatReadable:o,textureTypeReadable:s,precision:l,logarithmicDepthBuffer:d,reversedDepthBuffer:f,maxTextures:p,maxVertexTextures:m,maxTextureSize:h,maxCubemapSize:g,maxAttributes:_,maxVertexUniforms:v,maxVaryings:y,maxFragmentUniforms:b,vertexTextures:x,maxSamples:S}}function Ao(e){let t=this,n=null,r=0,i=!1,a=!1,o=new Ni,s=new z,c={value:null,needsUpdate:!1};this.uniform=c,this.numPlanes=0,this.numIntersection=0,this.init=function(e,t){let n=e.length!==0||t||r!==0||i;return i=t,r=e.length,n},this.beginShadows=function(){a=!0,u(null)},this.endShadows=function(){a=!1},this.setGlobalState=function(e,t){n=u(e,t,0)},this.setState=function(t,o,s){let d=t.clippingPlanes,f=t.clipIntersection,p=t.clipShadows,m=e.get(t);if(!i||d===null||d.length===0||a&&!p)a?u(null):l();else{let e=a?0:r,t=e*4,i=m.clippingState||null;c.value=i,i=u(d,o,t,s);for(let e=0;e!==t;++e)i[e]=n[e];m.clippingState=i,this.numIntersection=f?this.numPlanes:0,this.numPlanes+=e}};function l(){c.value!==n&&(c.value=n,c.needsUpdate=r>0),t.numPlanes=r,t.numIntersection=0}function u(e,n,r,i){let a=e===null?0:e.length,l=null;if(a!==0){if(l=c.value,i!==!0||l===null){let t=r+a*4,i=n.matrixWorldInverse;s.getNormalMatrix(i),(l===null||l.length<t)&&(l=new Float32Array(t));for(let t=0,n=r;t!==a;++t,n+=4)o.copy(e[t]).applyMatrix4(i,s),o.normal.toArray(l,n),l[n+3]=o.constant}c.value=l,c.needsUpdate=!0}return t.numPlanes=a,t.numIntersection=0,l}}function jo(e){let t=new WeakMap;function n(e,t){return t===303?e.mapping=301:t===304&&(e.mapping=302),e}function r(r){if(r&&r.isTexture){let a=r.mapping;if(a===303||a===304)if(t.has(r)){let e=t.get(r).texture;return n(e,r.mapping)}else{let a=r.image;if(a&&a.height>0){let o=new oi(a.height);return o.fromEquirectangularTexture(e,r),t.set(r,o),r.addEventListener(`dispose`,i),n(o.texture,r.mapping)}else return null}}return r}function i(e){let n=e.target;n.removeEventListener(`dispose`,i);let r=t.get(n);r!==void 0&&(t.delete(n),r.dispose())}function a(){t=new WeakMap}return{get:r,dispose:a}}var Mo=4,No=[.125,.215,.35,.446,.526,.582],Po=20,Fo=new La,Io=new B,Lo=null,Ro=0,zo=0,Bo=!1,Vo=(1+Math.sqrt(5))/2,Ho=1/Vo,Uo=[new R(-Vo,Ho,0),new R(Vo,Ho,0),new R(-Ho,0,Vo),new R(Ho,0,Vo),new R(0,Vo,-Ho),new R(0,Vo,Ho),new R(-1,1,-1),new R(1,1,-1),new R(-1,1,1),new R(1,1,1)],Wo=new R,Go=class{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(e,t=0,n=.1,r=100,i={}){let{size:a=256,position:o=Wo}=i;Lo=this._renderer.getRenderTarget(),Ro=this._renderer.getActiveCubeFace(),zo=this._renderer.getActiveMipmapLevel(),Bo=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(a);let s=this._allocateTargets();return s.depthBuffer=!0,this._sceneToCubeUV(e,n,r,s,o),t>0&&this._blur(s,0,0,t),this._applyPMREM(s),this._cleanup(s),s}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=Zo(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=Xo(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose()}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=2**this._lodMax}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodPlanes.length;e++)this._lodPlanes[e].dispose()}_cleanup(e){this._renderer.setRenderTarget(Lo,Ro,zo),this._renderer.xr.enabled=Bo,e.scissorTest=!1,Jo(e,0,0,e.width,e.height)}_fromTexture(e,t){e.mapping===301||e.mapping===302?this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4),Lo=this._renderer.getRenderTarget(),Ro=this._renderer.getActiveCubeFace(),zo=this._renderer.getActiveMipmapLevel(),Bo=this._renderer.xr.enabled,this._renderer.xr.enabled=!1;let n=t||this._allocateTargets();return this._textureToCubeUV(e,n),this._applyPMREM(n),this._cleanup(n),n}_allocateTargets(){let e=3*Math.max(this._cubeSize,112),t=4*this._cubeSize,n={magFilter:o,minFilter:o,generateMipmaps:!1,type:g,format:w,colorSpace:Le,depthBuffer:!1},r=qo(e,t,n);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=qo(e,t,n);let{_lodMax:r}=this;({sizeLods:this._sizeLods,lodPlanes:this._lodPlanes,sigmas:this._sigmas}=Ko(r)),this._blurMaterial=Yo(r,e,t)}return r}_compileMaterial(e){let t=new H(this._lodPlanes[0],e);this._renderer.compile(t,Fo)}_sceneToCubeUV(e,t,n,r,i){let a=new ti(90,1,t,n),o=[1,-1,1,1,1,1],s=[1,1,1,-1,-1,-1],c=this._renderer,l=c.autoClear,u=c.toneMapping;c.getClearColor(Io),c.toneMapping=0,c.autoClear=!1,c.state.buffers.depth.getReversed()&&(c.setRenderTarget(r),c.clearDepth(),c.setRenderTarget(null));let d=new mr({name:`PMREM.Background`,side:1,depthWrite:!1,depthTest:!1}),f=new H(new Hr,d),p=!1,m=e.background;m?m.isColor&&(d.color.copy(m),e.background=null,p=!0):(d.color.copy(Io),p=!0);for(let t=0;t<6;t++){let n=t%3;n===0?(a.up.set(0,o[t],0),a.position.set(i.x,i.y,i.z),a.lookAt(i.x+s[t],i.y,i.z)):n===1?(a.up.set(0,0,o[t]),a.position.set(i.x,i.y,i.z),a.lookAt(i.x,i.y+s[t],i.z)):(a.up.set(0,o[t],0),a.position.set(i.x,i.y,i.z),a.lookAt(i.x,i.y,i.z+s[t]));let l=this._cubeSize;Jo(r,n*l,t>2?l:0,l,l),c.setRenderTarget(r),p&&c.render(f,a),c.render(e,a)}f.geometry.dispose(),f.material.dispose(),c.toneMapping=u,c.autoClear=l,e.background=m}_textureToCubeUV(e,t){let n=this._renderer,r=e.mapping===301||e.mapping===302;r?(this._cubemapMaterial===null&&(this._cubemapMaterial=Zo()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=Xo());let i=r?this._cubemapMaterial:this._equirectMaterial,a=new H(this._lodPlanes[0],i),o=i.uniforms;o.envMap.value=e;let s=this._cubeSize;Jo(t,0,0,3*s,2*s),n.setRenderTarget(t),n.render(a,Fo)}_applyPMREM(e){let t=this._renderer,n=t.autoClear;t.autoClear=!1;let r=this._lodPlanes.length;for(let t=1;t<r;t++){let n=Math.sqrt(this._sigmas[t]*this._sigmas[t]-this._sigmas[t-1]*this._sigmas[t-1]),i=Uo[(r-t-1)%Uo.length];this._blur(e,t-1,t,n,i)}t.autoClear=n}_blur(e,t,n,r,i){let a=this._pingPongRenderTarget;this._halfBlur(e,a,t,n,r,`latitudinal`,i),this._halfBlur(a,e,n,n,r,`longitudinal`,i)}_halfBlur(e,t,n,r,i,a,o){let s=this._renderer,c=this._blurMaterial;a!==`latitudinal`&&a!==`longitudinal`&&console.error(`blur direction must be either latitudinal or longitudinal!`);let l=new H(this._lodPlanes[r],c),u=c.uniforms,d=this._sizeLods[n]-1,f=isFinite(i)?Math.PI/(2*d):2*Math.PI/(2*Po-1),p=i/f,m=isFinite(i)?1+Math.floor(3*p):Po;m>Po&&console.warn(`sigmaRadians, ${i}, is too large and will clip, as it requested ${m} samples when the maximum is set to ${Po}`);let h=[],g=0;for(let e=0;e<Po;++e){let t=e/p,n=Math.exp(-t*t/2);h.push(n),e===0?g+=n:e<m&&(g+=2*n)}for(let e=0;e<h.length;e++)h[e]=h[e]/g;u.envMap.value=e.texture,u.samples.value=m,u.weights.value=h,u.latitudinal.value=a===`latitudinal`,o&&(u.poleAxis.value=o);let{_lodMax:_}=this;u.dTheta.value=f,u.mipInt.value=_-n;let v=this._sizeLods[r];Jo(t,3*v*(r>_-Mo?r-_+Mo:0),4*(this._cubeSize-v),3*v,2*v),s.setRenderTarget(t),s.render(l,Fo)}};function Ko(e){let t=[],n=[],r=[],i=e,a=e-Mo+1+No.length;for(let o=0;o<a;o++){let a=2**i;n.push(a);let s=1/a;o>e-Mo?s=No[o-e+Mo-1]:o===0&&(s=0),r.push(s);let c=1/(a-2),l=-c,u=1+c,d=[l,l,u,l,u,u,l,l,u,u,l,u],f=new Float32Array(108),p=new Float32Array(72),m=new Float32Array(36);for(let e=0;e<6;e++){let t=e%3*2/3-1,n=e>2?0:-1,r=[t,n,0,t+2/3,n,0,t+2/3,n+1,0,t,n,0,t+2/3,n+1,0,t,n+1,0];f.set(r,18*e),p.set(d,12*e);let i=[e,e,e,e,e,e];m.set(i,6*e)}let h=new Or;h.setAttribute(`position`,new V(f,3)),h.setAttribute(`uv`,new V(p,2)),h.setAttribute(`faceIndex`,new V(m,1)),t.push(h),i>Mo&&i--}return{lodPlanes:t,sizeLods:n,sigmas:r}}function qo(e,t,n){let r=new Ht(e,t,n);return r.texture.mapping=306,r.texture.name=`PMREM.cubeUv`,r.scissorTest=!0,r}function Jo(e,t,n,r,i){e.viewport.set(t,n,r,i),e.scissor.set(t,n,r,i)}function Yo(e,t,n){let r=new Float32Array(Po),i=new R(0,1,0);return new Xr({name:`SphericalGaussianBlur`,defines:{n:Po,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:r},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:i}},vertexShader:Qo(),fragmentShader:`
3579
+ }`},G={common:{diffuse:{value:new B(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new z},alphaMap:{value:null},alphaMapTransform:{value:new z},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new z}},envmap:{envMap:{value:null},envMapRotation:{value:new z},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new z}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new z}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new z},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new z},normalScale:{value:new L(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new z},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new z}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new z}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new z}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new B(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new B(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new z},alphaTest:{value:0},uvTransform:{value:new z}},sprite:{diffuse:{value:new B(16777215)},opacity:{value:1},center:{value:new L(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new z},alphaMap:{value:null},alphaMapTransform:{value:new z},alphaTest:{value:0}}},Oo={basic:{uniforms:Ur([G.common,G.specularmap,G.envmap,G.aomap,G.lightmap,G.fog]),vertexShader:W.meshbasic_vert,fragmentShader:W.meshbasic_frag},lambert:{uniforms:Ur([G.common,G.specularmap,G.envmap,G.aomap,G.lightmap,G.emissivemap,G.bumpmap,G.normalmap,G.displacementmap,G.fog,G.lights,{emissive:{value:new B(0)}}]),vertexShader:W.meshlambert_vert,fragmentShader:W.meshlambert_frag},phong:{uniforms:Ur([G.common,G.specularmap,G.envmap,G.aomap,G.lightmap,G.emissivemap,G.bumpmap,G.normalmap,G.displacementmap,G.fog,G.lights,{emissive:{value:new B(0)},specular:{value:new B(1118481)},shininess:{value:30}}]),vertexShader:W.meshphong_vert,fragmentShader:W.meshphong_frag},standard:{uniforms:Ur([G.common,G.envmap,G.aomap,G.lightmap,G.emissivemap,G.bumpmap,G.normalmap,G.displacementmap,G.roughnessmap,G.metalnessmap,G.fog,G.lights,{emissive:{value:new B(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:W.meshphysical_vert,fragmentShader:W.meshphysical_frag},toon:{uniforms:Ur([G.common,G.aomap,G.lightmap,G.emissivemap,G.bumpmap,G.normalmap,G.displacementmap,G.gradientmap,G.fog,G.lights,{emissive:{value:new B(0)}}]),vertexShader:W.meshtoon_vert,fragmentShader:W.meshtoon_frag},matcap:{uniforms:Ur([G.common,G.bumpmap,G.normalmap,G.displacementmap,G.fog,{matcap:{value:null}}]),vertexShader:W.meshmatcap_vert,fragmentShader:W.meshmatcap_frag},points:{uniforms:Ur([G.points,G.fog]),vertexShader:W.points_vert,fragmentShader:W.points_frag},dashed:{uniforms:Ur([G.common,G.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:W.linedashed_vert,fragmentShader:W.linedashed_frag},depth:{uniforms:Ur([G.common,G.displacementmap]),vertexShader:W.depth_vert,fragmentShader:W.depth_frag},normal:{uniforms:Ur([G.common,G.bumpmap,G.normalmap,G.displacementmap,{opacity:{value:1}}]),vertexShader:W.meshnormal_vert,fragmentShader:W.meshnormal_frag},sprite:{uniforms:Ur([G.sprite,G.fog]),vertexShader:W.sprite_vert,fragmentShader:W.sprite_frag},background:{uniforms:{uvTransform:{value:new z},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:W.background_vert,fragmentShader:W.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new z}},vertexShader:W.backgroundCube_vert,fragmentShader:W.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:W.cube_vert,fragmentShader:W.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:W.equirect_vert,fragmentShader:W.equirect_frag},distanceRGBA:{uniforms:Ur([G.common,G.displacementmap,{referencePosition:{value:new R},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:W.distanceRGBA_vert,fragmentShader:W.distanceRGBA_frag},shadow:{uniforms:Ur([G.lights,G.fog,{color:{value:new B(0)},opacity:{value:1}}]),vertexShader:W.shadow_vert,fragmentShader:W.shadow_frag}};Oo.physical={uniforms:Ur([Oo.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new z},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new z},clearcoatNormalScale:{value:new L(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new z},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new z},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new z},sheen:{value:0},sheenColor:{value:new B(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new z},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new z},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new z},transmissionSamplerSize:{value:new L},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new z},attenuationDistance:{value:0},attenuationColor:{value:new B(0)},specularColor:{value:new B(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new z},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new z},anisotropyVector:{value:new L},anisotropyMap:{value:null},anisotropyMapTransform:{value:new z}}]),vertexShader:W.meshphysical_vert,fragmentShader:W.meshphysical_frag};var ko={r:0,b:0,g:0},Ao=new kn,jo=new yn;function Mo(e,t,n,r,i,a,o){let s=new B(0),c=a===!0?0:1,l,u,d=null,f=0,p=null;function m(e){let r=e.isScene===!0?e.background:null;return r&&r.isTexture&&(r=(e.backgroundBlurriness>0?n:t).get(r)),r}function h(t){let n=!1,i=m(t);i===null?_(s,c):i&&i.isColor&&(_(i,1),n=!0);let a=e.xr.getEnvironmentBlendMode();a===`additive`?r.buffers.color.setClear(0,0,0,1,o):a===`alpha-blend`&&r.buffers.color.setClear(0,0,0,0,o),(e.autoClear||n)&&(r.buffers.depth.setTest(!0),r.buffers.depth.setMask(!0),r.buffers.color.setMask(!0),e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil))}function g(t,n){let r=m(n);r&&(r.isCubeTexture||r.mapping===306)?(u===void 0&&(u=new U(new Vr(1,1,1),new Yr({name:`BackgroundCubeMaterial`,uniforms:Hr(Oo.backgroundCube.uniforms),vertexShader:Oo.backgroundCube.vertexShader,fragmentShader:Oo.backgroundCube.fragmentShader,side:1,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),u.geometry.deleteAttribute(`normal`),u.geometry.deleteAttribute(`uv`),u.onBeforeRender=function(e,t,n){this.matrixWorld.copyPosition(n.matrixWorld)},Object.defineProperty(u.material,`envMap`,{get:function(){return this.uniforms.envMap.value}}),i.update(u)),Ao.copy(n.backgroundRotation),Ao.x*=-1,Ao.y*=-1,Ao.z*=-1,r.isCubeTexture&&r.isRenderTargetTexture===!1&&(Ao.y*=-1,Ao.z*=-1),u.material.uniforms.envMap.value=r,u.material.uniforms.flipEnvMap.value=r.isCubeTexture&&r.isRenderTargetTexture===!1?-1:1,u.material.uniforms.backgroundBlurriness.value=n.backgroundBlurriness,u.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,u.material.uniforms.backgroundRotation.value.setFromMatrix4(jo.makeRotationFromEuler(Ao)),u.material.toneMapped=kt.getTransfer(r.colorSpace)!==ze,(d!==r||f!==r.version||p!==e.toneMapping)&&(u.material.needsUpdate=!0,d=r,f=r.version,p=e.toneMapping),u.layers.enableAll(),t.unshift(u,u.geometry,u.material,0,0,null)):r&&r.isTexture&&(l===void 0&&(l=new U(new ma(2,2),new Yr({name:`BackgroundMaterial`,uniforms:Hr(Oo.background.uniforms),vertexShader:Oo.background.vertexShader,fragmentShader:Oo.background.fragmentShader,side:0,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute(`normal`),Object.defineProperty(l.material,`map`,{get:function(){return this.uniforms.t2D.value}}),i.update(l)),l.material.uniforms.t2D.value=r,l.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,l.material.toneMapped=kt.getTransfer(r.colorSpace)!==ze,r.matrixAutoUpdate===!0&&r.updateMatrix(),l.material.uniforms.uvTransform.value.copy(r.matrix),(d!==r||f!==r.version||p!==e.toneMapping)&&(l.material.needsUpdate=!0,d=r,f=r.version,p=e.toneMapping),l.layers.enableAll(),t.unshift(l,l.geometry,l.material,0,0,null))}function _(t,n){t.getRGB(ko,Gr(e)),r.buffers.color.setClear(ko.r,ko.g,ko.b,n,o)}function v(){u!==void 0&&(u.geometry.dispose(),u.material.dispose(),u=void 0),l!==void 0&&(l.geometry.dispose(),l.material.dispose(),l=void 0)}return{getClearColor:function(){return s},setClearColor:function(e,t=1){s.set(e),c=t,_(s,c)},getClearAlpha:function(){return c},setClearAlpha:function(e){c=e,_(s,c)},render:h,addToRenderList:g,dispose:v}}function No(e,t){let n=e.getParameter(e.MAX_VERTEX_ATTRIBS),r={},i=f(null),a=i,o=!1;function s(n,r,i,s,c){let u=!1,f=d(s,i,r);a!==f&&(a=f,l(a.object)),u=p(n,s,i,c),u&&m(n,s,i,c),c!==null&&t.update(c,e.ELEMENT_ARRAY_BUFFER),(u||o)&&(o=!1,b(n,r,i,s),c!==null&&e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,t.get(c).buffer))}function c(){return e.createVertexArray()}function l(t){return e.bindVertexArray(t)}function u(t){return e.deleteVertexArray(t)}function d(e,t,n){let i=n.wireframe===!0,a=r[e.id];a===void 0&&(a={},r[e.id]=a);let o=a[t.id];o===void 0&&(o={},a[t.id]=o);let s=o[i];return s===void 0&&(s=f(c()),o[i]=s),s}function f(e){let t=[],r=[],i=[];for(let e=0;e<n;e++)t[e]=0,r[e]=0,i[e]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:t,enabledAttributes:r,attributeDivisors:i,object:e,attributes:{},index:null}}function p(e,t,n,r){let i=a.attributes,o=t.attributes,s=0,c=n.getAttributes();for(let t in c)if(c[t].location>=0){let n=i[t],r=o[t];if(r===void 0&&(t===`instanceMatrix`&&e.instanceMatrix&&(r=e.instanceMatrix),t===`instanceColor`&&e.instanceColor&&(r=e.instanceColor)),n===void 0||n.attribute!==r||r&&n.data!==r.data)return!0;s++}return a.attributesNum!==s||a.index!==r}function m(e,t,n,r){let i={},o=t.attributes,s=0,c=n.getAttributes();for(let t in c)if(c[t].location>=0){let n=o[t];n===void 0&&(t===`instanceMatrix`&&e.instanceMatrix&&(n=e.instanceMatrix),t===`instanceColor`&&e.instanceColor&&(n=e.instanceColor));let r={};r.attribute=n,n&&n.data&&(r.data=n.data),i[t]=r,s++}a.attributes=i,a.attributesNum=s,a.index=r}function h(){let e=a.newAttributes;for(let t=0,n=e.length;t<n;t++)e[t]=0}function g(e){_(e,0)}function _(t,n){let r=a.newAttributes,i=a.enabledAttributes,o=a.attributeDivisors;r[t]=1,i[t]===0&&(e.enableVertexAttribArray(t),i[t]=1),o[t]!==n&&(e.vertexAttribDivisor(t,n),o[t]=n)}function v(){let t=a.newAttributes,n=a.enabledAttributes;for(let r=0,i=n.length;r<i;r++)n[r]!==t[r]&&(e.disableVertexAttribArray(r),n[r]=0)}function y(t,n,r,i,a,o,s){s===!0?e.vertexAttribIPointer(t,n,r,a,o):e.vertexAttribPointer(t,n,r,i,a,o)}function b(n,r,i,a){h();let o=a.attributes,s=i.getAttributes(),c=r.defaultAttributeValues;for(let r in s){let i=s[r];if(i.location>=0){let s=o[r];if(s===void 0&&(r===`instanceMatrix`&&n.instanceMatrix&&(s=n.instanceMatrix),r===`instanceColor`&&n.instanceColor&&(s=n.instanceColor)),s!==void 0){let r=s.normalized,o=s.itemSize,c=t.get(s);if(c===void 0)continue;let l=c.buffer,u=c.type,d=c.bytesPerElement,f=u===e.INT||u===e.UNSIGNED_INT||s.gpuType===1013;if(s.isInterleavedBufferAttribute){let t=s.data,c=t.stride,p=s.offset;if(t.isInstancedInterleavedBuffer){for(let e=0;e<i.locationSize;e++)_(i.location+e,t.meshPerAttribute);n.isInstancedMesh!==!0&&a._maxInstanceCount===void 0&&(a._maxInstanceCount=t.meshPerAttribute*t.count)}else for(let e=0;e<i.locationSize;e++)g(i.location+e);e.bindBuffer(e.ARRAY_BUFFER,l);for(let e=0;e<i.locationSize;e++)y(i.location+e,o/i.locationSize,u,r,c*d,(p+o/i.locationSize*e)*d,f)}else{if(s.isInstancedBufferAttribute){for(let e=0;e<i.locationSize;e++)_(i.location+e,s.meshPerAttribute);n.isInstancedMesh!==!0&&a._maxInstanceCount===void 0&&(a._maxInstanceCount=s.meshPerAttribute*s.count)}else for(let e=0;e<i.locationSize;e++)g(i.location+e);e.bindBuffer(e.ARRAY_BUFFER,l);for(let e=0;e<i.locationSize;e++)y(i.location+e,o/i.locationSize,u,r,o*d,o/i.locationSize*e*d,f)}}else if(c!==void 0){let t=c[r];if(t!==void 0)switch(t.length){case 2:e.vertexAttrib2fv(i.location,t);break;case 3:e.vertexAttrib3fv(i.location,t);break;case 4:e.vertexAttrib4fv(i.location,t);break;default:e.vertexAttrib1fv(i.location,t)}}}}v()}function x(){w();for(let e in r){let t=r[e];for(let e in t){let n=t[e];for(let e in n)u(n[e].object),delete n[e];delete t[e]}delete r[e]}}function S(e){if(r[e.id]===void 0)return;let t=r[e.id];for(let e in t){let n=t[e];for(let e in n)u(n[e].object),delete n[e];delete t[e]}delete r[e.id]}function C(e){for(let t in r){let n=r[t];if(n[e.id]===void 0)continue;let i=n[e.id];for(let e in i)u(i[e].object),delete i[e];delete n[e.id]}}function w(){T(),o=!0,a!==i&&(a=i,l(a.object))}function T(){i.geometry=null,i.program=null,i.wireframe=!1}return{setup:s,reset:w,resetDefaultState:T,dispose:x,releaseStatesOfGeometry:S,releaseStatesOfProgram:C,initAttributes:h,enableAttribute:g,disableUnusedAttributes:v}}function Po(e,t,n){let r;function i(e){r=e}function a(t,i){e.drawArrays(r,t,i),n.update(i,r,1)}function o(t,i,a){a!==0&&(e.drawArraysInstanced(r,t,i,a),n.update(i,r,a))}function s(e,i,a){if(a===0)return;t.get(`WEBGL_multi_draw`).multiDrawArraysWEBGL(r,e,0,i,0,a);let o=0;for(let e=0;e<a;e++)o+=i[e];n.update(o,r,1)}function c(e,i,a,s){if(a===0)return;let c=t.get(`WEBGL_multi_draw`);if(c===null)for(let t=0;t<e.length;t++)o(e[t],i[t],s[t]);else{c.multiDrawArraysInstancedWEBGL(r,e,0,i,0,s,0,a);let t=0;for(let e=0;e<a;e++)t+=i[e]*s[e];n.update(t,r,1)}}this.setMode=i,this.render=a,this.renderInstances=o,this.renderMultiDraw=s,this.renderMultiDrawInstances=c}function Fo(e,t,n,r){let i;function a(){if(i!==void 0)return i;if(t.has(`EXT_texture_filter_anisotropic`)===!0){let n=t.get(`EXT_texture_filter_anisotropic`);i=e.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else i=0;return i}function o(t){return!(t!==1023&&r.convert(t)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT))}function s(n){let i=n===1016&&(t.has(`EXT_color_buffer_half_float`)||t.has(`EXT_color_buffer_float`));return!(n!==1009&&r.convert(n)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)&&n!==1015&&!i)}function c(t){if(t===`highp`){if(e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.HIGH_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0)return`highp`;t=`mediump`}return t===`mediump`&&e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.MEDIUM_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?`mediump`:`lowp`}let l=n.precision===void 0?`highp`:n.precision,u=c(l);u!==l&&(console.warn(`THREE.WebGLRenderer:`,l,`not supported, using`,u,`instead.`),l=u);let d=n.logarithmicDepthBuffer===!0,f=n.reversedDepthBuffer===!0&&t.has(`EXT_clip_control`),p=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),m=e.getParameter(e.MAX_VERTEX_TEXTURE_IMAGE_UNITS),h=e.getParameter(e.MAX_TEXTURE_SIZE),g=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),_=e.getParameter(e.MAX_VERTEX_ATTRIBS),v=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),y=e.getParameter(e.MAX_VARYING_VECTORS),b=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),x=m>0,S=e.getParameter(e.MAX_SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:a,getMaxPrecision:c,textureFormatReadable:o,textureTypeReadable:s,precision:l,logarithmicDepthBuffer:d,reversedDepthBuffer:f,maxTextures:p,maxVertexTextures:m,maxTextureSize:h,maxCubemapSize:g,maxAttributes:_,maxVertexUniforms:v,maxVaryings:y,maxFragmentUniforms:b,vertexTextures:x,maxSamples:S}}function Io(e){let t=this,n=null,r=0,i=!1,a=!1,o=new Mi,s=new z,c={value:null,needsUpdate:!1};this.uniform=c,this.numPlanes=0,this.numIntersection=0,this.init=function(e,t){let n=e.length!==0||t||r!==0||i;return i=t,r=e.length,n},this.beginShadows=function(){a=!0,u(null)},this.endShadows=function(){a=!1},this.setGlobalState=function(e,t){n=u(e,t,0)},this.setState=function(t,o,s){let d=t.clippingPlanes,f=t.clipIntersection,p=t.clipShadows,m=e.get(t);if(!i||d===null||d.length===0||a&&!p)a?u(null):l();else{let e=a?0:r,t=e*4,i=m.clippingState||null;c.value=i,i=u(d,o,t,s);for(let e=0;e!==t;++e)i[e]=n[e];m.clippingState=i,this.numIntersection=f?this.numPlanes:0,this.numPlanes+=e}};function l(){c.value!==n&&(c.value=n,c.needsUpdate=r>0),t.numPlanes=r,t.numIntersection=0}function u(e,n,r,i){let a=e===null?0:e.length,l=null;if(a!==0){if(l=c.value,i!==!0||l===null){let t=r+a*4,i=n.matrixWorldInverse;s.getNormalMatrix(i),(l===null||l.length<t)&&(l=new Float32Array(t));for(let t=0,n=r;t!==a;++t,n+=4)o.copy(e[t]).applyMatrix4(i,s),o.normal.toArray(l,n),l[n+3]=o.constant}c.value=l,c.needsUpdate=!0}return t.numPlanes=a,t.numIntersection=0,l}}function Lo(e){let t=new WeakMap;function n(e,t){return t===303?e.mapping=301:t===304&&(e.mapping=302),e}function r(r){if(r&&r.isTexture){let a=r.mapping;if(a===303||a===304)if(t.has(r)){let e=t.get(r).texture;return n(e,r.mapping)}else{let a=r.image;if(a&&a.height>0){let o=new ai(a.height);return o.fromEquirectangularTexture(e,r),t.set(r,o),r.addEventListener(`dispose`,i),n(o.texture,r.mapping)}else return null}}return r}function i(e){let n=e.target;n.removeEventListener(`dispose`,i);let r=t.get(n);r!==void 0&&(t.delete(n),r.dispose())}function a(){t=new WeakMap}return{get:r,dispose:a}}var Ro=4,zo=[.125,.215,.35,.446,.526,.582],Bo=20,Vo=new Ua,Ho=new B,Uo=null,Wo=0,Go=0,Ko=!1,qo=(1+Math.sqrt(5))/2,Jo=1/qo,Yo=[new R(-qo,Jo,0),new R(qo,Jo,0),new R(-Jo,0,qo),new R(Jo,0,qo),new R(0,qo,-Jo),new R(0,qo,Jo),new R(-1,1,-1),new R(1,1,-1),new R(-1,1,1),new R(1,1,1)],Xo=new R,Zo=class{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(e,t=0,n=.1,r=100,i={}){let{size:a=256,position:o=Xo}=i;Uo=this._renderer.getRenderTarget(),Wo=this._renderer.getActiveCubeFace(),Go=this._renderer.getActiveMipmapLevel(),Ko=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(a);let s=this._allocateTargets();return s.depthBuffer=!0,this._sceneToCubeUV(e,n,r,s,o),t>0&&this._blur(s,0,0,t),this._applyPMREM(s),this._cleanup(s),s}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=rs(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=ns(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose()}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=2**this._lodMax}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodPlanes.length;e++)this._lodPlanes[e].dispose()}_cleanup(e){this._renderer.setRenderTarget(Uo,Wo,Go),this._renderer.xr.enabled=Ko,e.scissorTest=!1,es(e,0,0,e.width,e.height)}_fromTexture(e,t){e.mapping===301||e.mapping===302?this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4),Uo=this._renderer.getRenderTarget(),Wo=this._renderer.getActiveCubeFace(),Go=this._renderer.getActiveMipmapLevel(),Ko=this._renderer.xr.enabled,this._renderer.xr.enabled=!1;let n=t||this._allocateTargets();return this._textureToCubeUV(e,n),this._applyPMREM(n),this._cleanup(n),n}_allocateTargets(){let e=3*Math.max(this._cubeSize,112),t=4*this._cubeSize,n={magFilter:o,minFilter:o,generateMipmaps:!1,type:g,format:w,colorSpace:Le,depthBuffer:!1},r=$o(e,t,n);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=$o(e,t,n);let{_lodMax:r}=this;({sizeLods:this._sizeLods,lodPlanes:this._lodPlanes,sigmas:this._sigmas}=Qo(r)),this._blurMaterial=ts(r,e,t)}return r}_compileMaterial(e){let t=new U(this._lodPlanes[0],e);this._renderer.compile(t,Vo)}_sceneToCubeUV(e,t,n,r,i){let a=new ei(90,1,t,n),o=[1,-1,1,1,1,1],s=[1,1,1,-1,-1,-1],c=this._renderer,l=c.autoClear,u=c.toneMapping;c.getClearColor(Ho),c.toneMapping=0,c.autoClear=!1,c.state.buffers.depth.getReversed()&&(c.setRenderTarget(r),c.clearDepth(),c.setRenderTarget(null));let d=new mr({name:`PMREM.Background`,side:1,depthWrite:!1,depthTest:!1}),f=new U(new Vr,d),p=!1,m=e.background;m?m.isColor&&(d.color.copy(m),e.background=null,p=!0):(d.color.copy(Ho),p=!0);for(let t=0;t<6;t++){let n=t%3;n===0?(a.up.set(0,o[t],0),a.position.set(i.x,i.y,i.z),a.lookAt(i.x+s[t],i.y,i.z)):n===1?(a.up.set(0,0,o[t]),a.position.set(i.x,i.y,i.z),a.lookAt(i.x,i.y+s[t],i.z)):(a.up.set(0,o[t],0),a.position.set(i.x,i.y,i.z),a.lookAt(i.x,i.y,i.z+s[t]));let l=this._cubeSize;es(r,n*l,t>2?l:0,l,l),c.setRenderTarget(r),p&&c.render(f,a),c.render(e,a)}f.geometry.dispose(),f.material.dispose(),c.toneMapping=u,c.autoClear=l,e.background=m}_textureToCubeUV(e,t){let n=this._renderer,r=e.mapping===301||e.mapping===302;r?(this._cubemapMaterial===null&&(this._cubemapMaterial=rs()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=ns());let i=r?this._cubemapMaterial:this._equirectMaterial,a=new U(this._lodPlanes[0],i),o=i.uniforms;o.envMap.value=e;let s=this._cubeSize;es(t,0,0,3*s,2*s),n.setRenderTarget(t),n.render(a,Vo)}_applyPMREM(e){let t=this._renderer,n=t.autoClear;t.autoClear=!1;let r=this._lodPlanes.length;for(let t=1;t<r;t++){let n=Math.sqrt(this._sigmas[t]*this._sigmas[t]-this._sigmas[t-1]*this._sigmas[t-1]),i=Yo[(r-t-1)%Yo.length];this._blur(e,t-1,t,n,i)}t.autoClear=n}_blur(e,t,n,r,i){let a=this._pingPongRenderTarget;this._halfBlur(e,a,t,n,r,`latitudinal`,i),this._halfBlur(a,e,n,n,r,`longitudinal`,i)}_halfBlur(e,t,n,r,i,a,o){let s=this._renderer,c=this._blurMaterial;a!==`latitudinal`&&a!==`longitudinal`&&console.error(`blur direction must be either latitudinal or longitudinal!`);let l=new U(this._lodPlanes[r],c),u=c.uniforms,d=this._sizeLods[n]-1,f=isFinite(i)?Math.PI/(2*d):2*Math.PI/(2*Bo-1),p=i/f,m=isFinite(i)?1+Math.floor(3*p):Bo;m>Bo&&console.warn(`sigmaRadians, ${i}, is too large and will clip, as it requested ${m} samples when the maximum is set to ${Bo}`);let h=[],g=0;for(let e=0;e<Bo;++e){let t=e/p,n=Math.exp(-t*t/2);h.push(n),e===0?g+=n:e<m&&(g+=2*n)}for(let e=0;e<h.length;e++)h[e]=h[e]/g;u.envMap.value=e.texture,u.samples.value=m,u.weights.value=h,u.latitudinal.value=a===`latitudinal`,o&&(u.poleAxis.value=o);let{_lodMax:_}=this;u.dTheta.value=f,u.mipInt.value=_-n;let v=this._sizeLods[r];es(t,3*v*(r>_-Ro?r-_+Ro:0),4*(this._cubeSize-v),3*v,2*v),s.setRenderTarget(t),s.render(l,Vo)}};function Qo(e){let t=[],n=[],r=[],i=e,a=e-Ro+1+zo.length;for(let o=0;o<a;o++){let a=2**i;n.push(a);let s=1/a;o>e-Ro?s=zo[o-e+Ro-1]:o===0&&(s=0),r.push(s);let c=1/(a-2),l=-c,u=1+c,d=[l,l,u,l,u,u,l,l,u,u,l,u],f=new Float32Array(108),p=new Float32Array(72),m=new Float32Array(36);for(let e=0;e<6;e++){let t=e%3*2/3-1,n=e>2?0:-1,r=[t,n,0,t+2/3,n,0,t+2/3,n+1,0,t,n,0,t+2/3,n+1,0,t,n+1,0];f.set(r,18*e),p.set(d,12*e);let i=[e,e,e,e,e,e];m.set(i,6*e)}let h=new H;h.setAttribute(`position`,new V(f,3)),h.setAttribute(`uv`,new V(p,2)),h.setAttribute(`faceIndex`,new V(m,1)),t.push(h),i>Ro&&i--}return{lodPlanes:t,sizeLods:n,sigmas:r}}function $o(e,t,n){let r=new Ht(e,t,n);return r.texture.mapping=306,r.texture.name=`PMREM.cubeUv`,r.scissorTest=!0,r}function es(e,t,n,r,i){e.viewport.set(t,n,r,i),e.scissor.set(t,n,r,i)}function ts(e,t,n){let r=new Float32Array(Bo),i=new R(0,1,0);return new Yr({name:`SphericalGaussianBlur`,defines:{n:Bo,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:r},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:i}},vertexShader:is(),fragmentShader:`
3580
3580
 
3581
3581
  precision mediump float;
3582
3582
  precision mediump int;
@@ -3636,7 +3636,7 @@ void main() {
3636
3636
  }
3637
3637
 
3638
3638
  }
3639
- `,blending:0,depthTest:!1,depthWrite:!1})}function Xo(){return new Xr({name:`EquirectangularToCubeUV`,uniforms:{envMap:{value:null}},vertexShader:Qo(),fragmentShader:`
3639
+ `,blending:0,depthTest:!1,depthWrite:!1})}function ns(){return new Yr({name:`EquirectangularToCubeUV`,uniforms:{envMap:{value:null}},vertexShader:is(),fragmentShader:`
3640
3640
 
3641
3641
  precision mediump float;
3642
3642
  precision mediump int;
@@ -3655,7 +3655,7 @@ void main() {
3655
3655
  gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
3656
3656
 
3657
3657
  }
3658
- `,blending:0,depthTest:!1,depthWrite:!1})}function Zo(){return new Xr({name:`CubemapToCubeUV`,uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:Qo(),fragmentShader:`
3658
+ `,blending:0,depthTest:!1,depthWrite:!1})}function rs(){return new Yr({name:`CubemapToCubeUV`,uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:is(),fragmentShader:`
3659
3659
 
3660
3660
  precision mediump float;
3661
3661
  precision mediump int;
@@ -3671,7 +3671,7 @@ void main() {
3671
3671
  gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
3672
3672
 
3673
3673
  }
3674
- `,blending:0,depthTest:!1,depthWrite:!1})}function Qo(){return`
3674
+ `,blending:0,depthTest:!1,depthWrite:!1})}function is(){return`
3675
3675
 
3676
3676
  precision mediump float;
3677
3677
  precision mediump int;
@@ -3726,17 +3726,17 @@ void main() {
3726
3726
  gl_Position = vec4( position, 1.0 );
3727
3727
 
3728
3728
  }
3729
- `}function $o(e){let t=new WeakMap,n=null;function r(r){if(r&&r.isTexture){let o=r.mapping,s=o===303||o===304,c=o===301||o===302;if(s||c){let o=t.get(r),l=o===void 0?0:o.texture.pmremVersion;if(r.isRenderTargetTexture&&r.pmremVersion!==l)return n===null&&(n=new Go(e)),o=s?n.fromEquirectangular(r,o):n.fromCubemap(r,o),o.texture.pmremVersion=r.pmremVersion,t.set(r,o),o.texture;if(o!==void 0)return o.texture;{let l=r.image;return s&&l&&l.height>0||c&&l&&i(l)?(n===null&&(n=new Go(e)),o=s?n.fromEquirectangular(r):n.fromCubemap(r),o.texture.pmremVersion=r.pmremVersion,t.set(r,o),r.addEventListener(`dispose`,a),o.texture):null}}}return r}function i(e){let t=0;for(let n=0;n<6;n++)e[n]!==void 0&&t++;return t===6}function a(e){let n=e.target;n.removeEventListener(`dispose`,a);let r=t.get(n);r!==void 0&&(t.delete(n),r.dispose())}function o(){t=new WeakMap,n!==null&&(n.dispose(),n=null)}return{get:r,dispose:o}}function es(e){let t={};function n(n){if(t[n]!==void 0)return t[n];let r;switch(n){case`WEBGL_depth_texture`:r=e.getExtension(`WEBGL_depth_texture`)||e.getExtension(`MOZ_WEBGL_depth_texture`)||e.getExtension(`WEBKIT_WEBGL_depth_texture`);break;case`EXT_texture_filter_anisotropic`:r=e.getExtension(`EXT_texture_filter_anisotropic`)||e.getExtension(`MOZ_EXT_texture_filter_anisotropic`)||e.getExtension(`WEBKIT_EXT_texture_filter_anisotropic`);break;case`WEBGL_compressed_texture_s3tc`:r=e.getExtension(`WEBGL_compressed_texture_s3tc`)||e.getExtension(`MOZ_WEBGL_compressed_texture_s3tc`)||e.getExtension(`WEBKIT_WEBGL_compressed_texture_s3tc`);break;case`WEBGL_compressed_texture_pvrtc`:r=e.getExtension(`WEBGL_compressed_texture_pvrtc`)||e.getExtension(`WEBKIT_WEBGL_compressed_texture_pvrtc`);break;default:r=e.getExtension(n)}return t[n]=r,r}return{has:function(e){return n(e)!==null},init:function(){n(`EXT_color_buffer_float`),n(`WEBGL_clip_cull_distance`),n(`OES_texture_float_linear`),n(`EXT_color_buffer_half_float`),n(`WEBGL_multisampled_render_to_texture`),n(`WEBGL_render_shared_exponent`)},get:function(e){let t=n(e);return t===null&&wt(`THREE.WebGLRenderer: `+e+` extension not supported.`),t}}}function ts(e,t,n,r){let i={},a=new WeakMap;function o(e){let s=e.target;s.index!==null&&t.remove(s.index);for(let e in s.attributes)t.remove(s.attributes[e]);s.removeEventListener(`dispose`,o),delete i[s.id];let c=a.get(s);c&&(t.remove(c),a.delete(s)),r.releaseStatesOfGeometry(s),s.isInstancedBufferGeometry===!0&&delete s._maxInstanceCount,n.memory.geometries--}function s(e,t){return i[t.id]===!0?t:(t.addEventListener(`dispose`,o),i[t.id]=!0,n.memory.geometries++,t)}function c(n){let r=n.attributes;for(let n in r)t.update(r[n],e.ARRAY_BUFFER)}function l(e){let n=[],r=e.index,i=e.attributes.position,o=0;if(r!==null){let e=r.array;o=r.version;for(let t=0,r=e.length;t<r;t+=3){let r=e[t+0],i=e[t+1],a=e[t+2];n.push(r,i,i,a,a,r)}}else if(i!==void 0){let e=i.array;o=i.version;for(let t=0,r=e.length/3-1;t<r;t+=3){let e=t+0,r=t+1,i=t+2;n.push(e,r,r,i,i,e)}}else return;let s=new(bt(n)?yr:vr)(n,1);s.version=o;let c=a.get(e);c&&t.remove(c),a.set(e,s)}function u(e){let t=a.get(e);if(t){let n=e.index;n!==null&&t.version<n.version&&l(e)}else l(e);return a.get(e)}return{get:s,update:c,getWireframeAttribute:u}}function ns(e,t,n){let r;function i(e){r=e}let a,o;function s(e){a=e.type,o=e.bytesPerElement}function c(t,i){e.drawElements(r,i,a,t*o),n.update(i,r,1)}function l(t,i,s){s!==0&&(e.drawElementsInstanced(r,i,a,t*o,s),n.update(i,r,s))}function u(e,i,o){if(o===0)return;t.get(`WEBGL_multi_draw`).multiDrawElementsWEBGL(r,i,0,a,e,0,o);let s=0;for(let e=0;e<o;e++)s+=i[e];n.update(s,r,1)}function d(e,i,s,c){if(s===0)return;let u=t.get(`WEBGL_multi_draw`);if(u===null)for(let t=0;t<e.length;t++)l(e[t]/o,i[t],c[t]);else{u.multiDrawElementsInstancedWEBGL(r,i,0,a,e,0,c,0,s);let t=0;for(let e=0;e<s;e++)t+=i[e]*c[e];n.update(t,r,1)}}this.setMode=i,this.setIndex=s,this.render=c,this.renderInstances=l,this.renderMultiDraw=u,this.renderMultiDrawInstances=d}function rs(e){let t={geometries:0,textures:0},n={frame:0,calls:0,triangles:0,points:0,lines:0};function r(t,r,i){switch(n.calls++,r){case e.TRIANGLES:n.triangles+=t/3*i;break;case e.LINES:n.lines+=t/2*i;break;case e.LINE_STRIP:n.lines+=i*(t-1);break;case e.LINE_LOOP:n.lines+=i*t;break;case e.POINTS:n.points+=i*t;break;default:console.error(`THREE.WebGLInfo: Unknown draw mode:`,r);break}}function i(){n.calls=0,n.triangles=0,n.points=0,n.lines=0}return{memory:t,render:n,programs:null,autoReset:!0,reset:i,update:r}}function is(e,t,n){let r=new WeakMap,i=new Bt;function a(a,o,s){let c=a.morphTargetInfluences,l=o.morphAttributes.position||o.morphAttributes.normal||o.morphAttributes.color,u=l===void 0?0:l.length,d=r.get(o);if(d===void 0||d.count!==u){d!==void 0&&d.texture.dispose();let e=o.morphAttributes.position!==void 0,n=o.morphAttributes.normal!==void 0,a=o.morphAttributes.color!==void 0,s=o.morphAttributes.position||[],c=o.morphAttributes.normal||[],l=o.morphAttributes.color||[],f=0;e===!0&&(f=1),n===!0&&(f=2),a===!0&&(f=3);let p=o.attributes.position.count*f,m=1;p>t.maxTextureSize&&(m=Math.ceil(p/t.maxTextureSize),p=t.maxTextureSize);let g=new Float32Array(p*m*4*u),_=new Ut(g,p,m,u);_.type=h,_.needsUpdate=!0;let v=f*4;for(let t=0;t<u;t++){let r=s[t],o=c[t],u=l[t],d=p*m*4*t;for(let t=0;t<r.count;t++){let s=t*v;e===!0&&(i.fromBufferAttribute(r,t),g[d+s+0]=i.x,g[d+s+1]=i.y,g[d+s+2]=i.z,g[d+s+3]=0),n===!0&&(i.fromBufferAttribute(o,t),g[d+s+4]=i.x,g[d+s+5]=i.y,g[d+s+6]=i.z,g[d+s+7]=0),a===!0&&(i.fromBufferAttribute(u,t),g[d+s+8]=i.x,g[d+s+9]=i.y,g[d+s+10]=i.z,g[d+s+11]=u.itemSize===4?i.w:1)}}d={count:u,texture:_,size:new L(p,m)},r.set(o,d);function y(){_.dispose(),r.delete(o),o.removeEventListener(`dispose`,y)}o.addEventListener(`dispose`,y)}if(a.isInstancedMesh===!0&&a.morphTexture!==null)s.getUniforms().setValue(e,`morphTexture`,a.morphTexture,n);else{let t=0;for(let e=0;e<c.length;e++)t+=c[e];let n=o.morphTargetsRelative?1:1-t;s.getUniforms().setValue(e,`morphTargetBaseInfluence`,n),s.getUniforms().setValue(e,`morphTargetInfluences`,c)}s.getUniforms().setValue(e,`morphTargetsTexture`,d.texture,n),s.getUniforms().setValue(e,`morphTargetsTextureSize`,d.size)}return{update:a}}function as(e,t,n,r){let i=new WeakMap;function a(a){let o=r.render.frame,c=a.geometry,l=t.get(a,c);if(i.get(l)!==o&&(t.update(l),i.set(l,o)),a.isInstancedMesh&&(a.hasEventListener(`dispose`,s)===!1&&a.addEventListener(`dispose`,s),i.get(a)!==o&&(n.update(a.instanceMatrix,e.ARRAY_BUFFER),a.instanceColor!==null&&n.update(a.instanceColor,e.ARRAY_BUFFER),i.set(a,o))),a.isSkinnedMesh){let e=a.skeleton;i.get(e)!==o&&(e.update(),i.set(e,o))}return l}function o(){i=new WeakMap}function s(e){let t=e.target;t.removeEventListener(`dispose`,s),n.remove(t.instanceMatrix),t.instanceColor!==null&&n.remove(t.instanceColor)}return{update:a,dispose:o}}var os=new zt,ss=new Qi(1,1),cs=new Ut,ls=new Wt,us=new ai,ds=[],fs=[],ps=new Float32Array(16),ms=new Float32Array(9),hs=new Float32Array(4);function gs(e,t,n){let r=e[0];if(r<=0||r>0)return e;let i=t*n,a=ds[i];if(a===void 0&&(a=new Float32Array(i),ds[i]=a),t!==0){r.toArray(a,0);for(let r=1,i=0;r!==t;++r)i+=n,e[r].toArray(a,i)}return a}function _s(e,t){if(e.length!==t.length)return!1;for(let n=0,r=e.length;n<r;n++)if(e[n]!==t[n])return!1;return!0}function vs(e,t){for(let n=0,r=t.length;n<r;n++)e[n]=t[n]}function ys(e,t){let n=fs[t];n===void 0&&(n=new Int32Array(t),fs[t]=n);for(let r=0;r!==t;++r)n[r]=e.allocateTextureUnit();return n}function bs(e,t){let n=this.cache;n[0]!==t&&(e.uniform1f(this.addr,t),n[0]=t)}function xs(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y)&&(e.uniform2f(this.addr,t.x,t.y),n[0]=t.x,n[1]=t.y);else{if(_s(n,t))return;e.uniform2fv(this.addr,t),vs(n,t)}}function Ss(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z)&&(e.uniform3f(this.addr,t.x,t.y,t.z),n[0]=t.x,n[1]=t.y,n[2]=t.z);else if(t.r!==void 0)(n[0]!==t.r||n[1]!==t.g||n[2]!==t.b)&&(e.uniform3f(this.addr,t.r,t.g,t.b),n[0]=t.r,n[1]=t.g,n[2]=t.b);else{if(_s(n,t))return;e.uniform3fv(this.addr,t),vs(n,t)}}function Cs(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z||n[3]!==t.w)&&(e.uniform4f(this.addr,t.x,t.y,t.z,t.w),n[0]=t.x,n[1]=t.y,n[2]=t.z,n[3]=t.w);else{if(_s(n,t))return;e.uniform4fv(this.addr,t),vs(n,t)}}function ws(e,t){let n=this.cache,r=t.elements;if(r===void 0){if(_s(n,t))return;e.uniformMatrix2fv(this.addr,!1,t),vs(n,t)}else{if(_s(n,r))return;hs.set(r),e.uniformMatrix2fv(this.addr,!1,hs),vs(n,r)}}function Ts(e,t){let n=this.cache,r=t.elements;if(r===void 0){if(_s(n,t))return;e.uniformMatrix3fv(this.addr,!1,t),vs(n,t)}else{if(_s(n,r))return;ms.set(r),e.uniformMatrix3fv(this.addr,!1,ms),vs(n,r)}}function Es(e,t){let n=this.cache,r=t.elements;if(r===void 0){if(_s(n,t))return;e.uniformMatrix4fv(this.addr,!1,t),vs(n,t)}else{if(_s(n,r))return;ps.set(r),e.uniformMatrix4fv(this.addr,!1,ps),vs(n,r)}}function Ds(e,t){let n=this.cache;n[0]!==t&&(e.uniform1i(this.addr,t),n[0]=t)}function Os(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y)&&(e.uniform2i(this.addr,t.x,t.y),n[0]=t.x,n[1]=t.y);else{if(_s(n,t))return;e.uniform2iv(this.addr,t),vs(n,t)}}function ks(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z)&&(e.uniform3i(this.addr,t.x,t.y,t.z),n[0]=t.x,n[1]=t.y,n[2]=t.z);else{if(_s(n,t))return;e.uniform3iv(this.addr,t),vs(n,t)}}function As(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z||n[3]!==t.w)&&(e.uniform4i(this.addr,t.x,t.y,t.z,t.w),n[0]=t.x,n[1]=t.y,n[2]=t.z,n[3]=t.w);else{if(_s(n,t))return;e.uniform4iv(this.addr,t),vs(n,t)}}function js(e,t){let n=this.cache;n[0]!==t&&(e.uniform1ui(this.addr,t),n[0]=t)}function Ms(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y)&&(e.uniform2ui(this.addr,t.x,t.y),n[0]=t.x,n[1]=t.y);else{if(_s(n,t))return;e.uniform2uiv(this.addr,t),vs(n,t)}}function Ns(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z)&&(e.uniform3ui(this.addr,t.x,t.y,t.z),n[0]=t.x,n[1]=t.y,n[2]=t.z);else{if(_s(n,t))return;e.uniform3uiv(this.addr,t),vs(n,t)}}function Ps(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z||n[3]!==t.w)&&(e.uniform4ui(this.addr,t.x,t.y,t.z,t.w),n[0]=t.x,n[1]=t.y,n[2]=t.z,n[3]=t.w);else{if(_s(n,t))return;e.uniform4uiv(this.addr,t),vs(n,t)}}function Fs(e,t,n){let r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(e.uniform1i(this.addr,i),r[0]=i);let a;this.type===e.SAMPLER_2D_SHADOW?(ss.compareFunction=515,a=ss):a=os,n.setTexture2D(t||a,i)}function Is(e,t,n){let r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(e.uniform1i(this.addr,i),r[0]=i),n.setTexture3D(t||ls,i)}function Ls(e,t,n){let r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(e.uniform1i(this.addr,i),r[0]=i),n.setTextureCube(t||us,i)}function Rs(e,t,n){let r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(e.uniform1i(this.addr,i),r[0]=i),n.setTexture2DArray(t||cs,i)}function zs(e){switch(e){case 5126:return bs;case 35664:return xs;case 35665:return Ss;case 35666:return Cs;case 35674:return ws;case 35675:return Ts;case 35676:return Es;case 5124:case 35670:return Ds;case 35667:case 35671:return Os;case 35668:case 35672:return ks;case 35669:case 35673:return As;case 5125:return js;case 36294:return Ms;case 36295:return Ns;case 36296:return Ps;case 35678:case 36198:case 36298:case 36306:case 35682:return Fs;case 35679:case 36299:case 36307:return Is;case 35680:case 36300:case 36308:case 36293:return Ls;case 36289:case 36303:case 36311:case 36292:return Rs}}function Bs(e,t){e.uniform1fv(this.addr,t)}function Vs(e,t){let n=gs(t,this.size,2);e.uniform2fv(this.addr,n)}function Hs(e,t){let n=gs(t,this.size,3);e.uniform3fv(this.addr,n)}function Us(e,t){let n=gs(t,this.size,4);e.uniform4fv(this.addr,n)}function Ws(e,t){let n=gs(t,this.size,4);e.uniformMatrix2fv(this.addr,!1,n)}function Gs(e,t){let n=gs(t,this.size,9);e.uniformMatrix3fv(this.addr,!1,n)}function Ks(e,t){let n=gs(t,this.size,16);e.uniformMatrix4fv(this.addr,!1,n)}function qs(e,t){e.uniform1iv(this.addr,t)}function Js(e,t){e.uniform2iv(this.addr,t)}function Ys(e,t){e.uniform3iv(this.addr,t)}function Xs(e,t){e.uniform4iv(this.addr,t)}function Zs(e,t){e.uniform1uiv(this.addr,t)}function Qs(e,t){e.uniform2uiv(this.addr,t)}function $s(e,t){e.uniform3uiv(this.addr,t)}function ec(e,t){e.uniform4uiv(this.addr,t)}function tc(e,t,n){let r=this.cache,i=t.length,a=ys(n,i);_s(r,a)||(e.uniform1iv(this.addr,a),vs(r,a));for(let e=0;e!==i;++e)n.setTexture2D(t[e]||os,a[e])}function nc(e,t,n){let r=this.cache,i=t.length,a=ys(n,i);_s(r,a)||(e.uniform1iv(this.addr,a),vs(r,a));for(let e=0;e!==i;++e)n.setTexture3D(t[e]||ls,a[e])}function rc(e,t,n){let r=this.cache,i=t.length,a=ys(n,i);_s(r,a)||(e.uniform1iv(this.addr,a),vs(r,a));for(let e=0;e!==i;++e)n.setTextureCube(t[e]||us,a[e])}function ic(e,t,n){let r=this.cache,i=t.length,a=ys(n,i);_s(r,a)||(e.uniform1iv(this.addr,a),vs(r,a));for(let e=0;e!==i;++e)n.setTexture2DArray(t[e]||cs,a[e])}function ac(e){switch(e){case 5126:return Bs;case 35664:return Vs;case 35665:return Hs;case 35666:return Us;case 35674:return Ws;case 35675:return Gs;case 35676:return Ks;case 5124:case 35670:return qs;case 35667:case 35671:return Js;case 35668:case 35672:return Ys;case 35669:case 35673:return Xs;case 5125:return Zs;case 36294:return Qs;case 36295:return $s;case 36296:return ec;case 35678:case 36198:case 36298:case 36306:case 35682:return tc;case 35679:case 36299:case 36307:return nc;case 35680:case 36300:case 36308:case 36293:return rc;case 36289:case 36303:case 36311:case 36292:return ic}}var oc=class{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.setValue=zs(t.type)}},sc=class{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.size=t.size,this.setValue=ac(t.type)}},cc=class{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,t,n){let r=this.seq;for(let i=0,a=r.length;i!==a;++i){let a=r[i];a.setValue(e,t[a.id],n)}}},lc=/(\w+)(\])?(\[|\.)?/g;function uc(e,t){e.seq.push(t),e.map[t.id]=t}function dc(e,t,n){let r=e.name,i=r.length;for(lc.lastIndex=0;;){let a=lc.exec(r),o=lc.lastIndex,s=a[1],c=a[2]===`]`,l=a[3];if(c&&(s|=0),l===void 0||l===`[`&&o+2===i){uc(n,l===void 0?new oc(s,e,t):new sc(s,e,t));break}else{let e=n.map[s];e===void 0&&(e=new cc(s),uc(n,e)),n=e}}}var fc=class{constructor(e,t){this.seq=[],this.map={};let n=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let r=0;r<n;++r){let n=e.getActiveUniform(t,r);dc(n,e.getUniformLocation(t,n.name),this)}}setValue(e,t,n,r){let i=this.map[t];i!==void 0&&i.setValue(e,n,r)}setOptional(e,t,n){let r=t[n];r!==void 0&&this.setValue(e,n,r)}static upload(e,t,n,r){for(let i=0,a=t.length;i!==a;++i){let a=t[i],o=n[a.id];o.needsUpdate!==!1&&a.setValue(e,o.value,r)}}static seqWithValue(e,t){let n=[];for(let r=0,i=e.length;r!==i;++r){let i=e[r];i.id in t&&n.push(i)}return n}};function pc(e,t,n){let r=e.createShader(t);return e.shaderSource(r,n),e.compileShader(r),r}var mc=37297,hc=0;function gc(e,t){let n=e.split(`
3729
+ `}function as(e){let t=new WeakMap,n=null;function r(r){if(r&&r.isTexture){let o=r.mapping,s=o===303||o===304,c=o===301||o===302;if(s||c){let o=t.get(r),l=o===void 0?0:o.texture.pmremVersion;if(r.isRenderTargetTexture&&r.pmremVersion!==l)return n===null&&(n=new Zo(e)),o=s?n.fromEquirectangular(r,o):n.fromCubemap(r,o),o.texture.pmremVersion=r.pmremVersion,t.set(r,o),o.texture;if(o!==void 0)return o.texture;{let l=r.image;return s&&l&&l.height>0||c&&l&&i(l)?(n===null&&(n=new Zo(e)),o=s?n.fromEquirectangular(r):n.fromCubemap(r),o.texture.pmremVersion=r.pmremVersion,t.set(r,o),r.addEventListener(`dispose`,a),o.texture):null}}}return r}function i(e){let t=0;for(let n=0;n<6;n++)e[n]!==void 0&&t++;return t===6}function a(e){let n=e.target;n.removeEventListener(`dispose`,a);let r=t.get(n);r!==void 0&&(t.delete(n),r.dispose())}function o(){t=new WeakMap,n!==null&&(n.dispose(),n=null)}return{get:r,dispose:o}}function os(e){let t={};function n(n){if(t[n]!==void 0)return t[n];let r;switch(n){case`WEBGL_depth_texture`:r=e.getExtension(`WEBGL_depth_texture`)||e.getExtension(`MOZ_WEBGL_depth_texture`)||e.getExtension(`WEBKIT_WEBGL_depth_texture`);break;case`EXT_texture_filter_anisotropic`:r=e.getExtension(`EXT_texture_filter_anisotropic`)||e.getExtension(`MOZ_EXT_texture_filter_anisotropic`)||e.getExtension(`WEBKIT_EXT_texture_filter_anisotropic`);break;case`WEBGL_compressed_texture_s3tc`:r=e.getExtension(`WEBGL_compressed_texture_s3tc`)||e.getExtension(`MOZ_WEBGL_compressed_texture_s3tc`)||e.getExtension(`WEBKIT_WEBGL_compressed_texture_s3tc`);break;case`WEBGL_compressed_texture_pvrtc`:r=e.getExtension(`WEBGL_compressed_texture_pvrtc`)||e.getExtension(`WEBKIT_WEBGL_compressed_texture_pvrtc`);break;default:r=e.getExtension(n)}return t[n]=r,r}return{has:function(e){return n(e)!==null},init:function(){n(`EXT_color_buffer_float`),n(`WEBGL_clip_cull_distance`),n(`OES_texture_float_linear`),n(`EXT_color_buffer_half_float`),n(`WEBGL_multisampled_render_to_texture`),n(`WEBGL_render_shared_exponent`)},get:function(e){let t=n(e);return t===null&&wt(`THREE.WebGLRenderer: `+e+` extension not supported.`),t}}}function ss(e,t,n,r){let i={},a=new WeakMap;function o(e){let s=e.target;s.index!==null&&t.remove(s.index);for(let e in s.attributes)t.remove(s.attributes[e]);s.removeEventListener(`dispose`,o),delete i[s.id];let c=a.get(s);c&&(t.remove(c),a.delete(s)),r.releaseStatesOfGeometry(s),s.isInstancedBufferGeometry===!0&&delete s._maxInstanceCount,n.memory.geometries--}function s(e,t){return i[t.id]===!0?t:(t.addEventListener(`dispose`,o),i[t.id]=!0,n.memory.geometries++,t)}function c(n){let r=n.attributes;for(let n in r)t.update(r[n],e.ARRAY_BUFFER)}function l(e){let n=[],r=e.index,i=e.attributes.position,o=0;if(r!==null){let e=r.array;o=r.version;for(let t=0,r=e.length;t<r;t+=3){let r=e[t+0],i=e[t+1],a=e[t+2];n.push(r,i,i,a,a,r)}}else if(i!==void 0){let e=i.array;o=i.version;for(let t=0,r=e.length/3-1;t<r;t+=3){let e=t+0,r=t+1,i=t+2;n.push(e,r,r,i,i,e)}}else return;let s=new(bt(n)?yr:vr)(n,1);s.version=o;let c=a.get(e);c&&t.remove(c),a.set(e,s)}function u(e){let t=a.get(e);if(t){let n=e.index;n!==null&&t.version<n.version&&l(e)}else l(e);return a.get(e)}return{get:s,update:c,getWireframeAttribute:u}}function cs(e,t,n){let r;function i(e){r=e}let a,o;function s(e){a=e.type,o=e.bytesPerElement}function c(t,i){e.drawElements(r,i,a,t*o),n.update(i,r,1)}function l(t,i,s){s!==0&&(e.drawElementsInstanced(r,i,a,t*o,s),n.update(i,r,s))}function u(e,i,o){if(o===0)return;t.get(`WEBGL_multi_draw`).multiDrawElementsWEBGL(r,i,0,a,e,0,o);let s=0;for(let e=0;e<o;e++)s+=i[e];n.update(s,r,1)}function d(e,i,s,c){if(s===0)return;let u=t.get(`WEBGL_multi_draw`);if(u===null)for(let t=0;t<e.length;t++)l(e[t]/o,i[t],c[t]);else{u.multiDrawElementsInstancedWEBGL(r,i,0,a,e,0,c,0,s);let t=0;for(let e=0;e<s;e++)t+=i[e]*c[e];n.update(t,r,1)}}this.setMode=i,this.setIndex=s,this.render=c,this.renderInstances=l,this.renderMultiDraw=u,this.renderMultiDrawInstances=d}function ls(e){let t={geometries:0,textures:0},n={frame:0,calls:0,triangles:0,points:0,lines:0};function r(t,r,i){switch(n.calls++,r){case e.TRIANGLES:n.triangles+=t/3*i;break;case e.LINES:n.lines+=t/2*i;break;case e.LINE_STRIP:n.lines+=i*(t-1);break;case e.LINE_LOOP:n.lines+=i*t;break;case e.POINTS:n.points+=i*t;break;default:console.error(`THREE.WebGLInfo: Unknown draw mode:`,r);break}}function i(){n.calls=0,n.triangles=0,n.points=0,n.lines=0}return{memory:t,render:n,programs:null,autoReset:!0,reset:i,update:r}}function us(e,t,n){let r=new WeakMap,i=new Bt;function a(a,o,s){let c=a.morphTargetInfluences,l=o.morphAttributes.position||o.morphAttributes.normal||o.morphAttributes.color,u=l===void 0?0:l.length,d=r.get(o);if(d===void 0||d.count!==u){d!==void 0&&d.texture.dispose();let e=o.morphAttributes.position!==void 0,n=o.morphAttributes.normal!==void 0,a=o.morphAttributes.color!==void 0,s=o.morphAttributes.position||[],c=o.morphAttributes.normal||[],l=o.morphAttributes.color||[],f=0;e===!0&&(f=1),n===!0&&(f=2),a===!0&&(f=3);let p=o.attributes.position.count*f,m=1;p>t.maxTextureSize&&(m=Math.ceil(p/t.maxTextureSize),p=t.maxTextureSize);let g=new Float32Array(p*m*4*u),_=new Ut(g,p,m,u);_.type=h,_.needsUpdate=!0;let v=f*4;for(let t=0;t<u;t++){let r=s[t],o=c[t],u=l[t],d=p*m*4*t;for(let t=0;t<r.count;t++){let s=t*v;e===!0&&(i.fromBufferAttribute(r,t),g[d+s+0]=i.x,g[d+s+1]=i.y,g[d+s+2]=i.z,g[d+s+3]=0),n===!0&&(i.fromBufferAttribute(o,t),g[d+s+4]=i.x,g[d+s+5]=i.y,g[d+s+6]=i.z,g[d+s+7]=0),a===!0&&(i.fromBufferAttribute(u,t),g[d+s+8]=i.x,g[d+s+9]=i.y,g[d+s+10]=i.z,g[d+s+11]=u.itemSize===4?i.w:1)}}d={count:u,texture:_,size:new L(p,m)},r.set(o,d);function y(){_.dispose(),r.delete(o),o.removeEventListener(`dispose`,y)}o.addEventListener(`dispose`,y)}if(a.isInstancedMesh===!0&&a.morphTexture!==null)s.getUniforms().setValue(e,`morphTexture`,a.morphTexture,n);else{let t=0;for(let e=0;e<c.length;e++)t+=c[e];let n=o.morphTargetsRelative?1:1-t;s.getUniforms().setValue(e,`morphTargetBaseInfluence`,n),s.getUniforms().setValue(e,`morphTargetInfluences`,c)}s.getUniforms().setValue(e,`morphTargetsTexture`,d.texture,n),s.getUniforms().setValue(e,`morphTargetsTextureSize`,d.size)}return{update:a}}function ds(e,t,n,r){let i=new WeakMap;function a(a){let o=r.render.frame,c=a.geometry,l=t.get(a,c);if(i.get(l)!==o&&(t.update(l),i.set(l,o)),a.isInstancedMesh&&(a.hasEventListener(`dispose`,s)===!1&&a.addEventListener(`dispose`,s),i.get(a)!==o&&(n.update(a.instanceMatrix,e.ARRAY_BUFFER),a.instanceColor!==null&&n.update(a.instanceColor,e.ARRAY_BUFFER),i.set(a,o))),a.isSkinnedMesh){let e=a.skeleton;i.get(e)!==o&&(e.update(),i.set(e,o))}return l}function o(){i=new WeakMap}function s(e){let t=e.target;t.removeEventListener(`dispose`,s),n.remove(t.instanceMatrix),t.instanceColor!==null&&n.remove(t.instanceColor)}return{update:a,dispose:o}}var fs=new zt,ps=new ia(1,1),ms=new Ut,hs=new Wt,gs=new ii,_s=[],vs=[],ys=new Float32Array(16),bs=new Float32Array(9),xs=new Float32Array(4);function Ss(e,t,n){let r=e[0];if(r<=0||r>0)return e;let i=t*n,a=_s[i];if(a===void 0&&(a=new Float32Array(i),_s[i]=a),t!==0){r.toArray(a,0);for(let r=1,i=0;r!==t;++r)i+=n,e[r].toArray(a,i)}return a}function Cs(e,t){if(e.length!==t.length)return!1;for(let n=0,r=e.length;n<r;n++)if(e[n]!==t[n])return!1;return!0}function ws(e,t){for(let n=0,r=t.length;n<r;n++)e[n]=t[n]}function Ts(e,t){let n=vs[t];n===void 0&&(n=new Int32Array(t),vs[t]=n);for(let r=0;r!==t;++r)n[r]=e.allocateTextureUnit();return n}function Es(e,t){let n=this.cache;n[0]!==t&&(e.uniform1f(this.addr,t),n[0]=t)}function Ds(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y)&&(e.uniform2f(this.addr,t.x,t.y),n[0]=t.x,n[1]=t.y);else{if(Cs(n,t))return;e.uniform2fv(this.addr,t),ws(n,t)}}function Os(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z)&&(e.uniform3f(this.addr,t.x,t.y,t.z),n[0]=t.x,n[1]=t.y,n[2]=t.z);else if(t.r!==void 0)(n[0]!==t.r||n[1]!==t.g||n[2]!==t.b)&&(e.uniform3f(this.addr,t.r,t.g,t.b),n[0]=t.r,n[1]=t.g,n[2]=t.b);else{if(Cs(n,t))return;e.uniform3fv(this.addr,t),ws(n,t)}}function ks(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z||n[3]!==t.w)&&(e.uniform4f(this.addr,t.x,t.y,t.z,t.w),n[0]=t.x,n[1]=t.y,n[2]=t.z,n[3]=t.w);else{if(Cs(n,t))return;e.uniform4fv(this.addr,t),ws(n,t)}}function As(e,t){let n=this.cache,r=t.elements;if(r===void 0){if(Cs(n,t))return;e.uniformMatrix2fv(this.addr,!1,t),ws(n,t)}else{if(Cs(n,r))return;xs.set(r),e.uniformMatrix2fv(this.addr,!1,xs),ws(n,r)}}function js(e,t){let n=this.cache,r=t.elements;if(r===void 0){if(Cs(n,t))return;e.uniformMatrix3fv(this.addr,!1,t),ws(n,t)}else{if(Cs(n,r))return;bs.set(r),e.uniformMatrix3fv(this.addr,!1,bs),ws(n,r)}}function Ms(e,t){let n=this.cache,r=t.elements;if(r===void 0){if(Cs(n,t))return;e.uniformMatrix4fv(this.addr,!1,t),ws(n,t)}else{if(Cs(n,r))return;ys.set(r),e.uniformMatrix4fv(this.addr,!1,ys),ws(n,r)}}function Ns(e,t){let n=this.cache;n[0]!==t&&(e.uniform1i(this.addr,t),n[0]=t)}function Ps(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y)&&(e.uniform2i(this.addr,t.x,t.y),n[0]=t.x,n[1]=t.y);else{if(Cs(n,t))return;e.uniform2iv(this.addr,t),ws(n,t)}}function Fs(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z)&&(e.uniform3i(this.addr,t.x,t.y,t.z),n[0]=t.x,n[1]=t.y,n[2]=t.z);else{if(Cs(n,t))return;e.uniform3iv(this.addr,t),ws(n,t)}}function Is(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z||n[3]!==t.w)&&(e.uniform4i(this.addr,t.x,t.y,t.z,t.w),n[0]=t.x,n[1]=t.y,n[2]=t.z,n[3]=t.w);else{if(Cs(n,t))return;e.uniform4iv(this.addr,t),ws(n,t)}}function Ls(e,t){let n=this.cache;n[0]!==t&&(e.uniform1ui(this.addr,t),n[0]=t)}function Rs(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y)&&(e.uniform2ui(this.addr,t.x,t.y),n[0]=t.x,n[1]=t.y);else{if(Cs(n,t))return;e.uniform2uiv(this.addr,t),ws(n,t)}}function zs(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z)&&(e.uniform3ui(this.addr,t.x,t.y,t.z),n[0]=t.x,n[1]=t.y,n[2]=t.z);else{if(Cs(n,t))return;e.uniform3uiv(this.addr,t),ws(n,t)}}function Bs(e,t){let n=this.cache;if(t.x!==void 0)(n[0]!==t.x||n[1]!==t.y||n[2]!==t.z||n[3]!==t.w)&&(e.uniform4ui(this.addr,t.x,t.y,t.z,t.w),n[0]=t.x,n[1]=t.y,n[2]=t.z,n[3]=t.w);else{if(Cs(n,t))return;e.uniform4uiv(this.addr,t),ws(n,t)}}function Vs(e,t,n){let r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(e.uniform1i(this.addr,i),r[0]=i);let a;this.type===e.SAMPLER_2D_SHADOW?(ps.compareFunction=515,a=ps):a=fs,n.setTexture2D(t||a,i)}function Hs(e,t,n){let r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(e.uniform1i(this.addr,i),r[0]=i),n.setTexture3D(t||hs,i)}function Us(e,t,n){let r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(e.uniform1i(this.addr,i),r[0]=i),n.setTextureCube(t||gs,i)}function Ws(e,t,n){let r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(e.uniform1i(this.addr,i),r[0]=i),n.setTexture2DArray(t||ms,i)}function Gs(e){switch(e){case 5126:return Es;case 35664:return Ds;case 35665:return Os;case 35666:return ks;case 35674:return As;case 35675:return js;case 35676:return Ms;case 5124:case 35670:return Ns;case 35667:case 35671:return Ps;case 35668:case 35672:return Fs;case 35669:case 35673:return Is;case 5125:return Ls;case 36294:return Rs;case 36295:return zs;case 36296:return Bs;case 35678:case 36198:case 36298:case 36306:case 35682:return Vs;case 35679:case 36299:case 36307:return Hs;case 35680:case 36300:case 36308:case 36293:return Us;case 36289:case 36303:case 36311:case 36292:return Ws}}function Ks(e,t){e.uniform1fv(this.addr,t)}function qs(e,t){let n=Ss(t,this.size,2);e.uniform2fv(this.addr,n)}function Js(e,t){let n=Ss(t,this.size,3);e.uniform3fv(this.addr,n)}function Ys(e,t){let n=Ss(t,this.size,4);e.uniform4fv(this.addr,n)}function Xs(e,t){let n=Ss(t,this.size,4);e.uniformMatrix2fv(this.addr,!1,n)}function Zs(e,t){let n=Ss(t,this.size,9);e.uniformMatrix3fv(this.addr,!1,n)}function Qs(e,t){let n=Ss(t,this.size,16);e.uniformMatrix4fv(this.addr,!1,n)}function $s(e,t){e.uniform1iv(this.addr,t)}function ec(e,t){e.uniform2iv(this.addr,t)}function tc(e,t){e.uniform3iv(this.addr,t)}function nc(e,t){e.uniform4iv(this.addr,t)}function rc(e,t){e.uniform1uiv(this.addr,t)}function ic(e,t){e.uniform2uiv(this.addr,t)}function ac(e,t){e.uniform3uiv(this.addr,t)}function oc(e,t){e.uniform4uiv(this.addr,t)}function sc(e,t,n){let r=this.cache,i=t.length,a=Ts(n,i);Cs(r,a)||(e.uniform1iv(this.addr,a),ws(r,a));for(let e=0;e!==i;++e)n.setTexture2D(t[e]||fs,a[e])}function cc(e,t,n){let r=this.cache,i=t.length,a=Ts(n,i);Cs(r,a)||(e.uniform1iv(this.addr,a),ws(r,a));for(let e=0;e!==i;++e)n.setTexture3D(t[e]||hs,a[e])}function lc(e,t,n){let r=this.cache,i=t.length,a=Ts(n,i);Cs(r,a)||(e.uniform1iv(this.addr,a),ws(r,a));for(let e=0;e!==i;++e)n.setTextureCube(t[e]||gs,a[e])}function uc(e,t,n){let r=this.cache,i=t.length,a=Ts(n,i);Cs(r,a)||(e.uniform1iv(this.addr,a),ws(r,a));for(let e=0;e!==i;++e)n.setTexture2DArray(t[e]||ms,a[e])}function dc(e){switch(e){case 5126:return Ks;case 35664:return qs;case 35665:return Js;case 35666:return Ys;case 35674:return Xs;case 35675:return Zs;case 35676:return Qs;case 5124:case 35670:return $s;case 35667:case 35671:return ec;case 35668:case 35672:return tc;case 35669:case 35673:return nc;case 5125:return rc;case 36294:return ic;case 36295:return ac;case 36296:return oc;case 35678:case 36198:case 36298:case 36306:case 35682:return sc;case 35679:case 36299:case 36307:return cc;case 35680:case 36300:case 36308:case 36293:return lc;case 36289:case 36303:case 36311:case 36292:return uc}}var fc=class{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.setValue=Gs(t.type)}},pc=class{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.size=t.size,this.setValue=dc(t.type)}},mc=class{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,t,n){let r=this.seq;for(let i=0,a=r.length;i!==a;++i){let a=r[i];a.setValue(e,t[a.id],n)}}},hc=/(\w+)(\])?(\[|\.)?/g;function gc(e,t){e.seq.push(t),e.map[t.id]=t}function _c(e,t,n){let r=e.name,i=r.length;for(hc.lastIndex=0;;){let a=hc.exec(r),o=hc.lastIndex,s=a[1],c=a[2]===`]`,l=a[3];if(c&&(s|=0),l===void 0||l===`[`&&o+2===i){gc(n,l===void 0?new fc(s,e,t):new pc(s,e,t));break}else{let e=n.map[s];e===void 0&&(e=new mc(s),gc(n,e)),n=e}}}var vc=class{constructor(e,t){this.seq=[],this.map={};let n=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let r=0;r<n;++r){let n=e.getActiveUniform(t,r);_c(n,e.getUniformLocation(t,n.name),this)}}setValue(e,t,n,r){let i=this.map[t];i!==void 0&&i.setValue(e,n,r)}setOptional(e,t,n){let r=t[n];r!==void 0&&this.setValue(e,n,r)}static upload(e,t,n,r){for(let i=0,a=t.length;i!==a;++i){let a=t[i],o=n[a.id];o.needsUpdate!==!1&&a.setValue(e,o.value,r)}}static seqWithValue(e,t){let n=[];for(let r=0,i=e.length;r!==i;++r){let i=e[r];i.id in t&&n.push(i)}return n}};function yc(e,t,n){let r=e.createShader(t);return e.shaderSource(r,n),e.compileShader(r),r}var bc=37297,xc=0;function Sc(e,t){let n=e.split(`
3730
3730
  `),r=[],i=Math.max(t-6,0),a=Math.min(t+6,n.length);for(let e=i;e<a;e++){let i=e+1;r.push(`${i===t?`>`:` `} ${i}: ${n[e]}`)}return r.join(`
3731
- `)}var _c=new z;function vc(e){kt._getMatrix(_c,kt.workingColorSpace,e);let t=`mat3( ${_c.elements.map(e=>e.toFixed(4))} )`;switch(kt.getTransfer(e)){case Re:return[t,`LinearTransferOETF`];case ze:return[t,`sRGBTransferOETF`];default:return console.warn(`THREE.WebGLProgram: Unsupported color space: `,e),[t,`LinearTransferOETF`]}}function yc(e,t,n){let r=e.getShaderParameter(t,e.COMPILE_STATUS),i=(e.getShaderInfoLog(t)||``).trim();if(r&&i===``)return``;let a=/ERROR: 0:(\d+)/.exec(i);if(a){let r=parseInt(a[1]);return n.toUpperCase()+`
3731
+ `)}var Cc=new z;function wc(e){kt._getMatrix(Cc,kt.workingColorSpace,e);let t=`mat3( ${Cc.elements.map(e=>e.toFixed(4))} )`;switch(kt.getTransfer(e)){case Re:return[t,`LinearTransferOETF`];case ze:return[t,`sRGBTransferOETF`];default:return console.warn(`THREE.WebGLProgram: Unsupported color space: `,e),[t,`LinearTransferOETF`]}}function Tc(e,t,n){let r=e.getShaderParameter(t,e.COMPILE_STATUS),i=(e.getShaderInfoLog(t)||``).trim();if(r&&i===``)return``;let a=/ERROR: 0:(\d+)/.exec(i);if(a){let r=parseInt(a[1]);return n.toUpperCase()+`
3732
3732
 
3733
3733
  `+i+`
3734
3734
 
3735
- `+gc(e.getShaderSource(t),r)}else return i}function bc(e,t){let n=vc(t);return[`vec4 ${e}( vec4 value ) {`,` return ${n[1]}( vec4( value.rgb * ${n[0]}, value.a ) );`,`}`].join(`
3736
- `)}function xc(e,t){let n;switch(t){case 1:n=`Linear`;break;case 2:n=`Reinhard`;break;case 3:n=`Cineon`;break;case 4:n=`ACESFilmic`;break;case 6:n=`AgX`;break;case 7:n=`Neutral`;break;case 5:n=`Custom`;break;default:console.warn(`THREE.WebGLProgram: Unsupported toneMapping:`,t),n=`Linear`}return`vec3 `+e+`( vec3 color ) { return `+n+`ToneMapping( color ); }`}var Sc=new R;function Cc(){return kt.getLuminanceCoefficients(Sc),[`float luminance( const in vec3 rgb ) {`,` const vec3 weights = vec3( ${Sc.x.toFixed(4)}, ${Sc.y.toFixed(4)}, ${Sc.z.toFixed(4)} );`,` return dot( weights, rgb );`,`}`].join(`
3737
- `)}function wc(e){return[e.extensionClipCullDistance?`#extension GL_ANGLE_clip_cull_distance : require`:``,e.extensionMultiDraw?`#extension GL_ANGLE_multi_draw : require`:``].filter(Dc).join(`
3738
- `)}function Tc(e){let t=[];for(let n in e){let r=e[n];r!==!1&&t.push(`#define `+n+` `+r)}return t.join(`
3739
- `)}function Ec(e,t){let n={},r=e.getProgramParameter(t,e.ACTIVE_ATTRIBUTES);for(let i=0;i<r;i++){let r=e.getActiveAttrib(t,i),a=r.name,o=1;r.type===e.FLOAT_MAT2&&(o=2),r.type===e.FLOAT_MAT3&&(o=3),r.type===e.FLOAT_MAT4&&(o=4),n[a]={type:r.type,location:e.getAttribLocation(t,a),locationSize:o}}return n}function Dc(e){return e!==``}function Oc(e,t){let n=t.numSpotLightShadows+t.numSpotLightMaps-t.numSpotLightShadowsWithMaps;return e.replace(/NUM_DIR_LIGHTS/g,t.numDirLights).replace(/NUM_SPOT_LIGHTS/g,t.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,t.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,n).replace(/NUM_RECT_AREA_LIGHTS/g,t.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,t.numPointLights).replace(/NUM_HEMI_LIGHTS/g,t.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g,t.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,t.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,t.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,t.numPointLightShadows)}function kc(e,t){return e.replace(/NUM_CLIPPING_PLANES/g,t.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,t.numClippingPlanes-t.numClipIntersection)}var Ac=/^[ \t]*#include +<([\w\d./]+)>/gm;function jc(e){return e.replace(Ac,Nc)}var Mc=new Map;function Nc(e,t){let n=U[t];if(n===void 0){let e=Mc.get(t);if(e!==void 0)n=U[e],console.warn(`THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.`,t,e);else throw Error(`Can not resolve #include <`+t+`>`)}return jc(n)}var Pc=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function Fc(e){return e.replace(Pc,Ic)}function Ic(e,t,n,r){let i=``;for(let e=parseInt(t);e<parseInt(n);e++)i+=r.replace(/\[\s*i\s*\]/g,`[ `+e+` ]`).replace(/UNROLLED_LOOP_INDEX/g,e);return i}function Lc(e){let t=`precision ${e.precision} float;
3735
+ `+Sc(e.getShaderSource(t),r)}else return i}function Ec(e,t){let n=wc(t);return[`vec4 ${e}( vec4 value ) {`,` return ${n[1]}( vec4( value.rgb * ${n[0]}, value.a ) );`,`}`].join(`
3736
+ `)}function Dc(e,t){let n;switch(t){case 1:n=`Linear`;break;case 2:n=`Reinhard`;break;case 3:n=`Cineon`;break;case 4:n=`ACESFilmic`;break;case 6:n=`AgX`;break;case 7:n=`Neutral`;break;case 5:n=`Custom`;break;default:console.warn(`THREE.WebGLProgram: Unsupported toneMapping:`,t),n=`Linear`}return`vec3 `+e+`( vec3 color ) { return `+n+`ToneMapping( color ); }`}var Oc=new R;function kc(){return kt.getLuminanceCoefficients(Oc),[`float luminance( const in vec3 rgb ) {`,` const vec3 weights = vec3( ${Oc.x.toFixed(4)}, ${Oc.y.toFixed(4)}, ${Oc.z.toFixed(4)} );`,` return dot( weights, rgb );`,`}`].join(`
3737
+ `)}function Ac(e){return[e.extensionClipCullDistance?`#extension GL_ANGLE_clip_cull_distance : require`:``,e.extensionMultiDraw?`#extension GL_ANGLE_multi_draw : require`:``].filter(Nc).join(`
3738
+ `)}function jc(e){let t=[];for(let n in e){let r=e[n];r!==!1&&t.push(`#define `+n+` `+r)}return t.join(`
3739
+ `)}function Mc(e,t){let n={},r=e.getProgramParameter(t,e.ACTIVE_ATTRIBUTES);for(let i=0;i<r;i++){let r=e.getActiveAttrib(t,i),a=r.name,o=1;r.type===e.FLOAT_MAT2&&(o=2),r.type===e.FLOAT_MAT3&&(o=3),r.type===e.FLOAT_MAT4&&(o=4),n[a]={type:r.type,location:e.getAttribLocation(t,a),locationSize:o}}return n}function Nc(e){return e!==``}function Pc(e,t){let n=t.numSpotLightShadows+t.numSpotLightMaps-t.numSpotLightShadowsWithMaps;return e.replace(/NUM_DIR_LIGHTS/g,t.numDirLights).replace(/NUM_SPOT_LIGHTS/g,t.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,t.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,n).replace(/NUM_RECT_AREA_LIGHTS/g,t.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,t.numPointLights).replace(/NUM_HEMI_LIGHTS/g,t.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g,t.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,t.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,t.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,t.numPointLightShadows)}function Fc(e,t){return e.replace(/NUM_CLIPPING_PLANES/g,t.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,t.numClippingPlanes-t.numClipIntersection)}var Ic=/^[ \t]*#include +<([\w\d./]+)>/gm;function Lc(e){return e.replace(Ic,zc)}var Rc=new Map;function zc(e,t){let n=W[t];if(n===void 0){let e=Rc.get(t);if(e!==void 0)n=W[e],console.warn(`THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.`,t,e);else throw Error(`Can not resolve #include <`+t+`>`)}return Lc(n)}var Bc=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function Vc(e){return e.replace(Bc,Hc)}function Hc(e,t,n,r){let i=``;for(let e=parseInt(t);e<parseInt(n);e++)i+=r.replace(/\[\s*i\s*\]/g,`[ `+e+` ]`).replace(/UNROLLED_LOOP_INDEX/g,e);return i}function Uc(e){let t=`precision ${e.precision} float;
3740
3740
  precision ${e.precision} int;
3741
3741
  precision ${e.precision} sampler2D;
3742
3742
  precision ${e.precision} samplerCube;
@@ -3756,30 +3756,30 @@ void main() {
3756
3756
  `;return e.precision===`highp`?t+=`
3757
3757
  #define HIGH_PRECISION`:e.precision===`mediump`?t+=`
3758
3758
  #define MEDIUM_PRECISION`:e.precision===`lowp`&&(t+=`
3759
- #define LOW_PRECISION`),t}function Rc(e){let t=`SHADOWMAP_TYPE_BASIC`;return e.shadowMapType===1?t=`SHADOWMAP_TYPE_PCF`:e.shadowMapType===2?t=`SHADOWMAP_TYPE_PCF_SOFT`:e.shadowMapType===3&&(t=`SHADOWMAP_TYPE_VSM`),t}function zc(e){let t=`ENVMAP_TYPE_CUBE`;if(e.envMap)switch(e.envMapMode){case 301:case 302:t=`ENVMAP_TYPE_CUBE`;break;case 306:t=`ENVMAP_TYPE_CUBE_UV`;break}return t}function Bc(e){let t=`ENVMAP_MODE_REFLECTION`;if(e.envMap)switch(e.envMapMode){case 302:t=`ENVMAP_MODE_REFRACTION`;break}return t}function Vc(e){let t=`ENVMAP_BLENDING_NONE`;if(e.envMap)switch(e.combine){case 0:t=`ENVMAP_BLENDING_MULTIPLY`;break;case 1:t=`ENVMAP_BLENDING_MIX`;break;case 2:t=`ENVMAP_BLENDING_ADD`;break}return t}function Hc(e){let t=e.envMapCubeUVHeight;if(t===null)return null;let n=Math.log2(t)-2,r=1/t;return{texelWidth:1/(3*Math.max(2**n,112)),texelHeight:r,maxMip:n}}function Uc(e,t,n,r){let i=e.getContext(),a=n.defines,o=n.vertexShader,s=n.fragmentShader,c=Rc(n),l=zc(n),u=Bc(n),d=Vc(n),f=Hc(n),p=wc(n),m=Tc(a),h=i.createProgram(),g,_,v=n.glslVersion?`#version `+n.glslVersion+`
3760
- `:``;n.isRawShaderMaterial?(g=[`#define SHADER_TYPE `+n.shaderType,`#define SHADER_NAME `+n.shaderName,m].filter(Dc).join(`
3759
+ #define LOW_PRECISION`),t}function Wc(e){let t=`SHADOWMAP_TYPE_BASIC`;return e.shadowMapType===1?t=`SHADOWMAP_TYPE_PCF`:e.shadowMapType===2?t=`SHADOWMAP_TYPE_PCF_SOFT`:e.shadowMapType===3&&(t=`SHADOWMAP_TYPE_VSM`),t}function Gc(e){let t=`ENVMAP_TYPE_CUBE`;if(e.envMap)switch(e.envMapMode){case 301:case 302:t=`ENVMAP_TYPE_CUBE`;break;case 306:t=`ENVMAP_TYPE_CUBE_UV`;break}return t}function Kc(e){let t=`ENVMAP_MODE_REFLECTION`;if(e.envMap)switch(e.envMapMode){case 302:t=`ENVMAP_MODE_REFRACTION`;break}return t}function qc(e){let t=`ENVMAP_BLENDING_NONE`;if(e.envMap)switch(e.combine){case 0:t=`ENVMAP_BLENDING_MULTIPLY`;break;case 1:t=`ENVMAP_BLENDING_MIX`;break;case 2:t=`ENVMAP_BLENDING_ADD`;break}return t}function Jc(e){let t=e.envMapCubeUVHeight;if(t===null)return null;let n=Math.log2(t)-2,r=1/t;return{texelWidth:1/(3*Math.max(2**n,112)),texelHeight:r,maxMip:n}}function Yc(e,t,n,r){let i=e.getContext(),a=n.defines,o=n.vertexShader,s=n.fragmentShader,c=Wc(n),l=Gc(n),u=Kc(n),d=qc(n),f=Jc(n),p=Ac(n),m=jc(a),h=i.createProgram(),g,_,v=n.glslVersion?`#version `+n.glslVersion+`
3760
+ `:``;n.isRawShaderMaterial?(g=[`#define SHADER_TYPE `+n.shaderType,`#define SHADER_NAME `+n.shaderName,m].filter(Nc).join(`
3761
3761
  `),g.length>0&&(g+=`
3762
- `),_=[`#define SHADER_TYPE `+n.shaderType,`#define SHADER_NAME `+n.shaderName,m].filter(Dc).join(`
3762
+ `),_=[`#define SHADER_TYPE `+n.shaderType,`#define SHADER_NAME `+n.shaderName,m].filter(Nc).join(`
3763
3763
  `),_.length>0&&(_+=`
3764
- `)):(g=[Lc(n),`#define SHADER_TYPE `+n.shaderType,`#define SHADER_NAME `+n.shaderName,m,n.extensionClipCullDistance?`#define USE_CLIP_DISTANCE`:``,n.batching?`#define USE_BATCHING`:``,n.batchingColor?`#define USE_BATCHING_COLOR`:``,n.instancing?`#define USE_INSTANCING`:``,n.instancingColor?`#define USE_INSTANCING_COLOR`:``,n.instancingMorph?`#define USE_INSTANCING_MORPH`:``,n.useFog&&n.fog?`#define USE_FOG`:``,n.useFog&&n.fogExp2?`#define FOG_EXP2`:``,n.map?`#define USE_MAP`:``,n.envMap?`#define USE_ENVMAP`:``,n.envMap?`#define `+u:``,n.lightMap?`#define USE_LIGHTMAP`:``,n.aoMap?`#define USE_AOMAP`:``,n.bumpMap?`#define USE_BUMPMAP`:``,n.normalMap?`#define USE_NORMALMAP`:``,n.normalMapObjectSpace?`#define USE_NORMALMAP_OBJECTSPACE`:``,n.normalMapTangentSpace?`#define USE_NORMALMAP_TANGENTSPACE`:``,n.displacementMap?`#define USE_DISPLACEMENTMAP`:``,n.emissiveMap?`#define USE_EMISSIVEMAP`:``,n.anisotropy?`#define USE_ANISOTROPY`:``,n.anisotropyMap?`#define USE_ANISOTROPYMAP`:``,n.clearcoatMap?`#define USE_CLEARCOATMAP`:``,n.clearcoatRoughnessMap?`#define USE_CLEARCOAT_ROUGHNESSMAP`:``,n.clearcoatNormalMap?`#define USE_CLEARCOAT_NORMALMAP`:``,n.iridescenceMap?`#define USE_IRIDESCENCEMAP`:``,n.iridescenceThicknessMap?`#define USE_IRIDESCENCE_THICKNESSMAP`:``,n.specularMap?`#define USE_SPECULARMAP`:``,n.specularColorMap?`#define USE_SPECULAR_COLORMAP`:``,n.specularIntensityMap?`#define USE_SPECULAR_INTENSITYMAP`:``,n.roughnessMap?`#define USE_ROUGHNESSMAP`:``,n.metalnessMap?`#define USE_METALNESSMAP`:``,n.alphaMap?`#define USE_ALPHAMAP`:``,n.alphaHash?`#define USE_ALPHAHASH`:``,n.transmission?`#define USE_TRANSMISSION`:``,n.transmissionMap?`#define USE_TRANSMISSIONMAP`:``,n.thicknessMap?`#define USE_THICKNESSMAP`:``,n.sheenColorMap?`#define USE_SHEEN_COLORMAP`:``,n.sheenRoughnessMap?`#define USE_SHEEN_ROUGHNESSMAP`:``,n.mapUv?`#define MAP_UV `+n.mapUv:``,n.alphaMapUv?`#define ALPHAMAP_UV `+n.alphaMapUv:``,n.lightMapUv?`#define LIGHTMAP_UV `+n.lightMapUv:``,n.aoMapUv?`#define AOMAP_UV `+n.aoMapUv:``,n.emissiveMapUv?`#define EMISSIVEMAP_UV `+n.emissiveMapUv:``,n.bumpMapUv?`#define BUMPMAP_UV `+n.bumpMapUv:``,n.normalMapUv?`#define NORMALMAP_UV `+n.normalMapUv:``,n.displacementMapUv?`#define DISPLACEMENTMAP_UV `+n.displacementMapUv:``,n.metalnessMapUv?`#define METALNESSMAP_UV `+n.metalnessMapUv:``,n.roughnessMapUv?`#define ROUGHNESSMAP_UV `+n.roughnessMapUv:``,n.anisotropyMapUv?`#define ANISOTROPYMAP_UV `+n.anisotropyMapUv:``,n.clearcoatMapUv?`#define CLEARCOATMAP_UV `+n.clearcoatMapUv:``,n.clearcoatNormalMapUv?`#define CLEARCOAT_NORMALMAP_UV `+n.clearcoatNormalMapUv:``,n.clearcoatRoughnessMapUv?`#define CLEARCOAT_ROUGHNESSMAP_UV `+n.clearcoatRoughnessMapUv:``,n.iridescenceMapUv?`#define IRIDESCENCEMAP_UV `+n.iridescenceMapUv:``,n.iridescenceThicknessMapUv?`#define IRIDESCENCE_THICKNESSMAP_UV `+n.iridescenceThicknessMapUv:``,n.sheenColorMapUv?`#define SHEEN_COLORMAP_UV `+n.sheenColorMapUv:``,n.sheenRoughnessMapUv?`#define SHEEN_ROUGHNESSMAP_UV `+n.sheenRoughnessMapUv:``,n.specularMapUv?`#define SPECULARMAP_UV `+n.specularMapUv:``,n.specularColorMapUv?`#define SPECULAR_COLORMAP_UV `+n.specularColorMapUv:``,n.specularIntensityMapUv?`#define SPECULAR_INTENSITYMAP_UV `+n.specularIntensityMapUv:``,n.transmissionMapUv?`#define TRANSMISSIONMAP_UV `+n.transmissionMapUv:``,n.thicknessMapUv?`#define THICKNESSMAP_UV `+n.thicknessMapUv:``,n.vertexTangents&&n.flatShading===!1?`#define USE_TANGENT`:``,n.vertexColors?`#define USE_COLOR`:``,n.vertexAlphas?`#define USE_COLOR_ALPHA`:``,n.vertexUv1s?`#define USE_UV1`:``,n.vertexUv2s?`#define USE_UV2`:``,n.vertexUv3s?`#define USE_UV3`:``,n.pointsUvs?`#define USE_POINTS_UV`:``,n.flatShading?`#define FLAT_SHADED`:``,n.skinning?`#define USE_SKINNING`:``,n.morphTargets?`#define USE_MORPHTARGETS`:``,n.morphNormals&&n.flatShading===!1?`#define USE_MORPHNORMALS`:``,n.morphColors?`#define USE_MORPHCOLORS`:``,n.morphTargetsCount>0?`#define MORPHTARGETS_TEXTURE_STRIDE `+n.morphTextureStride:``,n.morphTargetsCount>0?`#define MORPHTARGETS_COUNT `+n.morphTargetsCount:``,n.doubleSided?`#define DOUBLE_SIDED`:``,n.flipSided?`#define FLIP_SIDED`:``,n.shadowMapEnabled?`#define USE_SHADOWMAP`:``,n.shadowMapEnabled?`#define `+c:``,n.sizeAttenuation?`#define USE_SIZEATTENUATION`:``,n.numLightProbes>0?`#define USE_LIGHT_PROBES`:``,n.logarithmicDepthBuffer?`#define USE_LOGARITHMIC_DEPTH_BUFFER`:``,n.reversedDepthBuffer?`#define USE_REVERSED_DEPTH_BUFFER`:``,`uniform mat4 modelMatrix;`,`uniform mat4 modelViewMatrix;`,`uniform mat4 projectionMatrix;`,`uniform mat4 viewMatrix;`,`uniform mat3 normalMatrix;`,`uniform vec3 cameraPosition;`,`uniform bool isOrthographic;`,`#ifdef USE_INSTANCING`,` attribute mat4 instanceMatrix;`,`#endif`,`#ifdef USE_INSTANCING_COLOR`,` attribute vec3 instanceColor;`,`#endif`,`#ifdef USE_INSTANCING_MORPH`,` uniform sampler2D morphTexture;`,`#endif`,`attribute vec3 position;`,`attribute vec3 normal;`,`attribute vec2 uv;`,`#ifdef USE_UV1`,` attribute vec2 uv1;`,`#endif`,`#ifdef USE_UV2`,` attribute vec2 uv2;`,`#endif`,`#ifdef USE_UV3`,` attribute vec2 uv3;`,`#endif`,`#ifdef USE_TANGENT`,` attribute vec4 tangent;`,`#endif`,`#if defined( USE_COLOR_ALPHA )`,` attribute vec4 color;`,`#elif defined( USE_COLOR )`,` attribute vec3 color;`,`#endif`,`#ifdef USE_SKINNING`,` attribute vec4 skinIndex;`,` attribute vec4 skinWeight;`,`#endif`,`
3765
- `].filter(Dc).join(`
3766
- `),_=[Lc(n),`#define SHADER_TYPE `+n.shaderType,`#define SHADER_NAME `+n.shaderName,m,n.useFog&&n.fog?`#define USE_FOG`:``,n.useFog&&n.fogExp2?`#define FOG_EXP2`:``,n.alphaToCoverage?`#define ALPHA_TO_COVERAGE`:``,n.map?`#define USE_MAP`:``,n.matcap?`#define USE_MATCAP`:``,n.envMap?`#define USE_ENVMAP`:``,n.envMap?`#define `+l:``,n.envMap?`#define `+u:``,n.envMap?`#define `+d:``,f?`#define CUBEUV_TEXEL_WIDTH `+f.texelWidth:``,f?`#define CUBEUV_TEXEL_HEIGHT `+f.texelHeight:``,f?`#define CUBEUV_MAX_MIP `+f.maxMip+`.0`:``,n.lightMap?`#define USE_LIGHTMAP`:``,n.aoMap?`#define USE_AOMAP`:``,n.bumpMap?`#define USE_BUMPMAP`:``,n.normalMap?`#define USE_NORMALMAP`:``,n.normalMapObjectSpace?`#define USE_NORMALMAP_OBJECTSPACE`:``,n.normalMapTangentSpace?`#define USE_NORMALMAP_TANGENTSPACE`:``,n.emissiveMap?`#define USE_EMISSIVEMAP`:``,n.anisotropy?`#define USE_ANISOTROPY`:``,n.anisotropyMap?`#define USE_ANISOTROPYMAP`:``,n.clearcoat?`#define USE_CLEARCOAT`:``,n.clearcoatMap?`#define USE_CLEARCOATMAP`:``,n.clearcoatRoughnessMap?`#define USE_CLEARCOAT_ROUGHNESSMAP`:``,n.clearcoatNormalMap?`#define USE_CLEARCOAT_NORMALMAP`:``,n.dispersion?`#define USE_DISPERSION`:``,n.iridescence?`#define USE_IRIDESCENCE`:``,n.iridescenceMap?`#define USE_IRIDESCENCEMAP`:``,n.iridescenceThicknessMap?`#define USE_IRIDESCENCE_THICKNESSMAP`:``,n.specularMap?`#define USE_SPECULARMAP`:``,n.specularColorMap?`#define USE_SPECULAR_COLORMAP`:``,n.specularIntensityMap?`#define USE_SPECULAR_INTENSITYMAP`:``,n.roughnessMap?`#define USE_ROUGHNESSMAP`:``,n.metalnessMap?`#define USE_METALNESSMAP`:``,n.alphaMap?`#define USE_ALPHAMAP`:``,n.alphaTest?`#define USE_ALPHATEST`:``,n.alphaHash?`#define USE_ALPHAHASH`:``,n.sheen?`#define USE_SHEEN`:``,n.sheenColorMap?`#define USE_SHEEN_COLORMAP`:``,n.sheenRoughnessMap?`#define USE_SHEEN_ROUGHNESSMAP`:``,n.transmission?`#define USE_TRANSMISSION`:``,n.transmissionMap?`#define USE_TRANSMISSIONMAP`:``,n.thicknessMap?`#define USE_THICKNESSMAP`:``,n.vertexTangents&&n.flatShading===!1?`#define USE_TANGENT`:``,n.vertexColors||n.instancingColor||n.batchingColor?`#define USE_COLOR`:``,n.vertexAlphas?`#define USE_COLOR_ALPHA`:``,n.vertexUv1s?`#define USE_UV1`:``,n.vertexUv2s?`#define USE_UV2`:``,n.vertexUv3s?`#define USE_UV3`:``,n.pointsUvs?`#define USE_POINTS_UV`:``,n.gradientMap?`#define USE_GRADIENTMAP`:``,n.flatShading?`#define FLAT_SHADED`:``,n.doubleSided?`#define DOUBLE_SIDED`:``,n.flipSided?`#define FLIP_SIDED`:``,n.shadowMapEnabled?`#define USE_SHADOWMAP`:``,n.shadowMapEnabled?`#define `+c:``,n.premultipliedAlpha?`#define PREMULTIPLIED_ALPHA`:``,n.numLightProbes>0?`#define USE_LIGHT_PROBES`:``,n.decodeVideoTexture?`#define DECODE_VIDEO_TEXTURE`:``,n.decodeVideoTextureEmissive?`#define DECODE_VIDEO_TEXTURE_EMISSIVE`:``,n.logarithmicDepthBuffer?`#define USE_LOGARITHMIC_DEPTH_BUFFER`:``,n.reversedDepthBuffer?`#define USE_REVERSED_DEPTH_BUFFER`:``,`uniform mat4 viewMatrix;`,`uniform vec3 cameraPosition;`,`uniform bool isOrthographic;`,n.toneMapping===0?``:`#define TONE_MAPPING`,n.toneMapping===0?``:U.tonemapping_pars_fragment,n.toneMapping===0?``:xc(`toneMapping`,n.toneMapping),n.dithering?`#define DITHERING`:``,n.opaque?`#define OPAQUE`:``,U.colorspace_pars_fragment,bc(`linearToOutputTexel`,n.outputColorSpace),Cc(),n.useDepthPacking?`#define DEPTH_PACKING `+n.depthPacking:``,`
3767
- `].filter(Dc).join(`
3768
- `)),o=jc(o),o=Oc(o,n),o=kc(o,n),s=jc(s),s=Oc(s,n),s=kc(s,n),o=Fc(o),s=Fc(s),n.isRawShaderMaterial!==!0&&(v=`#version 300 es
3764
+ `)):(g=[Uc(n),`#define SHADER_TYPE `+n.shaderType,`#define SHADER_NAME `+n.shaderName,m,n.extensionClipCullDistance?`#define USE_CLIP_DISTANCE`:``,n.batching?`#define USE_BATCHING`:``,n.batchingColor?`#define USE_BATCHING_COLOR`:``,n.instancing?`#define USE_INSTANCING`:``,n.instancingColor?`#define USE_INSTANCING_COLOR`:``,n.instancingMorph?`#define USE_INSTANCING_MORPH`:``,n.useFog&&n.fog?`#define USE_FOG`:``,n.useFog&&n.fogExp2?`#define FOG_EXP2`:``,n.map?`#define USE_MAP`:``,n.envMap?`#define USE_ENVMAP`:``,n.envMap?`#define `+u:``,n.lightMap?`#define USE_LIGHTMAP`:``,n.aoMap?`#define USE_AOMAP`:``,n.bumpMap?`#define USE_BUMPMAP`:``,n.normalMap?`#define USE_NORMALMAP`:``,n.normalMapObjectSpace?`#define USE_NORMALMAP_OBJECTSPACE`:``,n.normalMapTangentSpace?`#define USE_NORMALMAP_TANGENTSPACE`:``,n.displacementMap?`#define USE_DISPLACEMENTMAP`:``,n.emissiveMap?`#define USE_EMISSIVEMAP`:``,n.anisotropy?`#define USE_ANISOTROPY`:``,n.anisotropyMap?`#define USE_ANISOTROPYMAP`:``,n.clearcoatMap?`#define USE_CLEARCOATMAP`:``,n.clearcoatRoughnessMap?`#define USE_CLEARCOAT_ROUGHNESSMAP`:``,n.clearcoatNormalMap?`#define USE_CLEARCOAT_NORMALMAP`:``,n.iridescenceMap?`#define USE_IRIDESCENCEMAP`:``,n.iridescenceThicknessMap?`#define USE_IRIDESCENCE_THICKNESSMAP`:``,n.specularMap?`#define USE_SPECULARMAP`:``,n.specularColorMap?`#define USE_SPECULAR_COLORMAP`:``,n.specularIntensityMap?`#define USE_SPECULAR_INTENSITYMAP`:``,n.roughnessMap?`#define USE_ROUGHNESSMAP`:``,n.metalnessMap?`#define USE_METALNESSMAP`:``,n.alphaMap?`#define USE_ALPHAMAP`:``,n.alphaHash?`#define USE_ALPHAHASH`:``,n.transmission?`#define USE_TRANSMISSION`:``,n.transmissionMap?`#define USE_TRANSMISSIONMAP`:``,n.thicknessMap?`#define USE_THICKNESSMAP`:``,n.sheenColorMap?`#define USE_SHEEN_COLORMAP`:``,n.sheenRoughnessMap?`#define USE_SHEEN_ROUGHNESSMAP`:``,n.mapUv?`#define MAP_UV `+n.mapUv:``,n.alphaMapUv?`#define ALPHAMAP_UV `+n.alphaMapUv:``,n.lightMapUv?`#define LIGHTMAP_UV `+n.lightMapUv:``,n.aoMapUv?`#define AOMAP_UV `+n.aoMapUv:``,n.emissiveMapUv?`#define EMISSIVEMAP_UV `+n.emissiveMapUv:``,n.bumpMapUv?`#define BUMPMAP_UV `+n.bumpMapUv:``,n.normalMapUv?`#define NORMALMAP_UV `+n.normalMapUv:``,n.displacementMapUv?`#define DISPLACEMENTMAP_UV `+n.displacementMapUv:``,n.metalnessMapUv?`#define METALNESSMAP_UV `+n.metalnessMapUv:``,n.roughnessMapUv?`#define ROUGHNESSMAP_UV `+n.roughnessMapUv:``,n.anisotropyMapUv?`#define ANISOTROPYMAP_UV `+n.anisotropyMapUv:``,n.clearcoatMapUv?`#define CLEARCOATMAP_UV `+n.clearcoatMapUv:``,n.clearcoatNormalMapUv?`#define CLEARCOAT_NORMALMAP_UV `+n.clearcoatNormalMapUv:``,n.clearcoatRoughnessMapUv?`#define CLEARCOAT_ROUGHNESSMAP_UV `+n.clearcoatRoughnessMapUv:``,n.iridescenceMapUv?`#define IRIDESCENCEMAP_UV `+n.iridescenceMapUv:``,n.iridescenceThicknessMapUv?`#define IRIDESCENCE_THICKNESSMAP_UV `+n.iridescenceThicknessMapUv:``,n.sheenColorMapUv?`#define SHEEN_COLORMAP_UV `+n.sheenColorMapUv:``,n.sheenRoughnessMapUv?`#define SHEEN_ROUGHNESSMAP_UV `+n.sheenRoughnessMapUv:``,n.specularMapUv?`#define SPECULARMAP_UV `+n.specularMapUv:``,n.specularColorMapUv?`#define SPECULAR_COLORMAP_UV `+n.specularColorMapUv:``,n.specularIntensityMapUv?`#define SPECULAR_INTENSITYMAP_UV `+n.specularIntensityMapUv:``,n.transmissionMapUv?`#define TRANSMISSIONMAP_UV `+n.transmissionMapUv:``,n.thicknessMapUv?`#define THICKNESSMAP_UV `+n.thicknessMapUv:``,n.vertexTangents&&n.flatShading===!1?`#define USE_TANGENT`:``,n.vertexColors?`#define USE_COLOR`:``,n.vertexAlphas?`#define USE_COLOR_ALPHA`:``,n.vertexUv1s?`#define USE_UV1`:``,n.vertexUv2s?`#define USE_UV2`:``,n.vertexUv3s?`#define USE_UV3`:``,n.pointsUvs?`#define USE_POINTS_UV`:``,n.flatShading?`#define FLAT_SHADED`:``,n.skinning?`#define USE_SKINNING`:``,n.morphTargets?`#define USE_MORPHTARGETS`:``,n.morphNormals&&n.flatShading===!1?`#define USE_MORPHNORMALS`:``,n.morphColors?`#define USE_MORPHCOLORS`:``,n.morphTargetsCount>0?`#define MORPHTARGETS_TEXTURE_STRIDE `+n.morphTextureStride:``,n.morphTargetsCount>0?`#define MORPHTARGETS_COUNT `+n.morphTargetsCount:``,n.doubleSided?`#define DOUBLE_SIDED`:``,n.flipSided?`#define FLIP_SIDED`:``,n.shadowMapEnabled?`#define USE_SHADOWMAP`:``,n.shadowMapEnabled?`#define `+c:``,n.sizeAttenuation?`#define USE_SIZEATTENUATION`:``,n.numLightProbes>0?`#define USE_LIGHT_PROBES`:``,n.logarithmicDepthBuffer?`#define USE_LOGARITHMIC_DEPTH_BUFFER`:``,n.reversedDepthBuffer?`#define USE_REVERSED_DEPTH_BUFFER`:``,`uniform mat4 modelMatrix;`,`uniform mat4 modelViewMatrix;`,`uniform mat4 projectionMatrix;`,`uniform mat4 viewMatrix;`,`uniform mat3 normalMatrix;`,`uniform vec3 cameraPosition;`,`uniform bool isOrthographic;`,`#ifdef USE_INSTANCING`,` attribute mat4 instanceMatrix;`,`#endif`,`#ifdef USE_INSTANCING_COLOR`,` attribute vec3 instanceColor;`,`#endif`,`#ifdef USE_INSTANCING_MORPH`,` uniform sampler2D morphTexture;`,`#endif`,`attribute vec3 position;`,`attribute vec3 normal;`,`attribute vec2 uv;`,`#ifdef USE_UV1`,` attribute vec2 uv1;`,`#endif`,`#ifdef USE_UV2`,` attribute vec2 uv2;`,`#endif`,`#ifdef USE_UV3`,` attribute vec2 uv3;`,`#endif`,`#ifdef USE_TANGENT`,` attribute vec4 tangent;`,`#endif`,`#if defined( USE_COLOR_ALPHA )`,` attribute vec4 color;`,`#elif defined( USE_COLOR )`,` attribute vec3 color;`,`#endif`,`#ifdef USE_SKINNING`,` attribute vec4 skinIndex;`,` attribute vec4 skinWeight;`,`#endif`,`
3765
+ `].filter(Nc).join(`
3766
+ `),_=[Uc(n),`#define SHADER_TYPE `+n.shaderType,`#define SHADER_NAME `+n.shaderName,m,n.useFog&&n.fog?`#define USE_FOG`:``,n.useFog&&n.fogExp2?`#define FOG_EXP2`:``,n.alphaToCoverage?`#define ALPHA_TO_COVERAGE`:``,n.map?`#define USE_MAP`:``,n.matcap?`#define USE_MATCAP`:``,n.envMap?`#define USE_ENVMAP`:``,n.envMap?`#define `+l:``,n.envMap?`#define `+u:``,n.envMap?`#define `+d:``,f?`#define CUBEUV_TEXEL_WIDTH `+f.texelWidth:``,f?`#define CUBEUV_TEXEL_HEIGHT `+f.texelHeight:``,f?`#define CUBEUV_MAX_MIP `+f.maxMip+`.0`:``,n.lightMap?`#define USE_LIGHTMAP`:``,n.aoMap?`#define USE_AOMAP`:``,n.bumpMap?`#define USE_BUMPMAP`:``,n.normalMap?`#define USE_NORMALMAP`:``,n.normalMapObjectSpace?`#define USE_NORMALMAP_OBJECTSPACE`:``,n.normalMapTangentSpace?`#define USE_NORMALMAP_TANGENTSPACE`:``,n.emissiveMap?`#define USE_EMISSIVEMAP`:``,n.anisotropy?`#define USE_ANISOTROPY`:``,n.anisotropyMap?`#define USE_ANISOTROPYMAP`:``,n.clearcoat?`#define USE_CLEARCOAT`:``,n.clearcoatMap?`#define USE_CLEARCOATMAP`:``,n.clearcoatRoughnessMap?`#define USE_CLEARCOAT_ROUGHNESSMAP`:``,n.clearcoatNormalMap?`#define USE_CLEARCOAT_NORMALMAP`:``,n.dispersion?`#define USE_DISPERSION`:``,n.iridescence?`#define USE_IRIDESCENCE`:``,n.iridescenceMap?`#define USE_IRIDESCENCEMAP`:``,n.iridescenceThicknessMap?`#define USE_IRIDESCENCE_THICKNESSMAP`:``,n.specularMap?`#define USE_SPECULARMAP`:``,n.specularColorMap?`#define USE_SPECULAR_COLORMAP`:``,n.specularIntensityMap?`#define USE_SPECULAR_INTENSITYMAP`:``,n.roughnessMap?`#define USE_ROUGHNESSMAP`:``,n.metalnessMap?`#define USE_METALNESSMAP`:``,n.alphaMap?`#define USE_ALPHAMAP`:``,n.alphaTest?`#define USE_ALPHATEST`:``,n.alphaHash?`#define USE_ALPHAHASH`:``,n.sheen?`#define USE_SHEEN`:``,n.sheenColorMap?`#define USE_SHEEN_COLORMAP`:``,n.sheenRoughnessMap?`#define USE_SHEEN_ROUGHNESSMAP`:``,n.transmission?`#define USE_TRANSMISSION`:``,n.transmissionMap?`#define USE_TRANSMISSIONMAP`:``,n.thicknessMap?`#define USE_THICKNESSMAP`:``,n.vertexTangents&&n.flatShading===!1?`#define USE_TANGENT`:``,n.vertexColors||n.instancingColor||n.batchingColor?`#define USE_COLOR`:``,n.vertexAlphas?`#define USE_COLOR_ALPHA`:``,n.vertexUv1s?`#define USE_UV1`:``,n.vertexUv2s?`#define USE_UV2`:``,n.vertexUv3s?`#define USE_UV3`:``,n.pointsUvs?`#define USE_POINTS_UV`:``,n.gradientMap?`#define USE_GRADIENTMAP`:``,n.flatShading?`#define FLAT_SHADED`:``,n.doubleSided?`#define DOUBLE_SIDED`:``,n.flipSided?`#define FLIP_SIDED`:``,n.shadowMapEnabled?`#define USE_SHADOWMAP`:``,n.shadowMapEnabled?`#define `+c:``,n.premultipliedAlpha?`#define PREMULTIPLIED_ALPHA`:``,n.numLightProbes>0?`#define USE_LIGHT_PROBES`:``,n.decodeVideoTexture?`#define DECODE_VIDEO_TEXTURE`:``,n.decodeVideoTextureEmissive?`#define DECODE_VIDEO_TEXTURE_EMISSIVE`:``,n.logarithmicDepthBuffer?`#define USE_LOGARITHMIC_DEPTH_BUFFER`:``,n.reversedDepthBuffer?`#define USE_REVERSED_DEPTH_BUFFER`:``,`uniform mat4 viewMatrix;`,`uniform vec3 cameraPosition;`,`uniform bool isOrthographic;`,n.toneMapping===0?``:`#define TONE_MAPPING`,n.toneMapping===0?``:W.tonemapping_pars_fragment,n.toneMapping===0?``:Dc(`toneMapping`,n.toneMapping),n.dithering?`#define DITHERING`:``,n.opaque?`#define OPAQUE`:``,W.colorspace_pars_fragment,Ec(`linearToOutputTexel`,n.outputColorSpace),kc(),n.useDepthPacking?`#define DEPTH_PACKING `+n.depthPacking:``,`
3767
+ `].filter(Nc).join(`
3768
+ `)),o=Lc(o),o=Pc(o,n),o=Fc(o,n),s=Lc(s),s=Pc(s,n),s=Fc(s,n),o=Vc(o),s=Vc(s),n.isRawShaderMaterial!==!0&&(v=`#version 300 es
3769
3769
  `,g=[p,`#define attribute in`,`#define varying out`,`#define texture2D texture`].join(`
3770
3770
  `)+`
3771
3771
  `+g,_=[`#define varying in`,n.glslVersion===`300 es`?``:`layout(location = 0) out highp vec4 pc_fragColor;`,n.glslVersion===`300 es`?``:`#define gl_FragColor pc_fragColor`,`#define gl_FragDepthEXT gl_FragDepth`,`#define texture2D texture`,`#define textureCube texture`,`#define texture2DProj textureProj`,`#define texture2DLodEXT textureLod`,`#define texture2DProjLodEXT textureProjLod`,`#define textureCubeLodEXT textureLod`,`#define texture2DGradEXT textureGrad`,`#define texture2DProjGradEXT textureProjGrad`,`#define textureCubeGradEXT textureGrad`].join(`
3772
3772
  `)+`
3773
- `+_);let y=v+g+o,b=v+_+s,x=pc(i,i.VERTEX_SHADER,y),S=pc(i,i.FRAGMENT_SHADER,b);i.attachShader(h,x),i.attachShader(h,S),n.index0AttributeName===void 0?n.morphTargets===!0&&i.bindAttribLocation(h,0,`position`):i.bindAttribLocation(h,0,n.index0AttributeName),i.linkProgram(h);function C(t){if(e.debug.checkShaderErrors){let n=i.getProgramInfoLog(h)||``,r=i.getShaderInfoLog(x)||``,a=i.getShaderInfoLog(S)||``,o=n.trim(),s=r.trim(),c=a.trim(),l=!0,u=!0;if(i.getProgramParameter(h,i.LINK_STATUS)===!1)if(l=!1,typeof e.debug.onShaderError==`function`)e.debug.onShaderError(i,h,x,S);else{let e=yc(i,x,`vertex`),n=yc(i,S,`fragment`);console.error(`THREE.WebGLProgram: Shader Error `+i.getError()+` - VALIDATE_STATUS `+i.getProgramParameter(h,i.VALIDATE_STATUS)+`
3773
+ `+_);let y=v+g+o,b=v+_+s,x=yc(i,i.VERTEX_SHADER,y),S=yc(i,i.FRAGMENT_SHADER,b);i.attachShader(h,x),i.attachShader(h,S),n.index0AttributeName===void 0?n.morphTargets===!0&&i.bindAttribLocation(h,0,`position`):i.bindAttribLocation(h,0,n.index0AttributeName),i.linkProgram(h);function C(t){if(e.debug.checkShaderErrors){let n=i.getProgramInfoLog(h)||``,r=i.getShaderInfoLog(x)||``,a=i.getShaderInfoLog(S)||``,o=n.trim(),s=r.trim(),c=a.trim(),l=!0,u=!0;if(i.getProgramParameter(h,i.LINK_STATUS)===!1)if(l=!1,typeof e.debug.onShaderError==`function`)e.debug.onShaderError(i,h,x,S);else{let e=Tc(i,x,`vertex`),n=Tc(i,S,`fragment`);console.error(`THREE.WebGLProgram: Shader Error `+i.getError()+` - VALIDATE_STATUS `+i.getProgramParameter(h,i.VALIDATE_STATUS)+`
3774
3774
 
3775
3775
  Material Name: `+t.name+`
3776
3776
  Material Type: `+t.type+`
3777
3777
 
3778
3778
  Program Info Log: `+o+`
3779
3779
  `+e+`
3780
- `+n)}else o===``?(s===``||c===``)&&(u=!1):console.warn(`THREE.WebGLProgram: Program Info Log:`,o);u&&(t.diagnostics={runnable:l,programLog:o,vertexShader:{log:s,prefix:g},fragmentShader:{log:c,prefix:_}})}i.deleteShader(x),i.deleteShader(S),w=new fc(i,h),T=Ec(i,h)}let w;this.getUniforms=function(){return w===void 0&&C(this),w};let T;this.getAttributes=function(){return T===void 0&&C(this),T};let E=n.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return E===!1&&(E=i.getProgramParameter(h,mc)),E},this.destroy=function(){r.releaseStatesOfProgram(this),i.deleteProgram(h),this.program=void 0},this.type=n.shaderType,this.name=n.shaderName,this.id=hc++,this.cacheKey=t,this.usedTimes=1,this.program=h,this.vertexShader=x,this.fragmentShader=S,this}var Wc=0,Gc=class{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){let t=e.vertexShader,n=e.fragmentShader,r=this._getShaderStage(t),i=this._getShaderStage(n),a=this._getShaderCacheForMaterial(e);return a.has(r)===!1&&(a.add(r),r.usedTimes++),a.has(i)===!1&&(a.add(i),i.usedTimes++),this}remove(e){let t=this.materialCache.get(e);for(let e of t)e.usedTimes--,e.usedTimes===0&&this.shaderCache.delete(e.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){let t=this.materialCache,n=t.get(e);return n===void 0&&(n=new Set,t.set(e,n)),n}_getShaderStage(e){let t=this.shaderCache,n=t.get(e);return n===void 0&&(n=new Kc(e),t.set(e,n)),n}},Kc=class{constructor(e){this.id=Wc++,this.code=e,this.usedTimes=0}};function qc(e,t,n,r,i,a,o){let s=new An,c=new Gc,l=new Set,u=[],d=i.logarithmicDepthBuffer,f=i.vertexTextures,p=i.precision,m={MeshDepthMaterial:`depth`,MeshDistanceMaterial:`distanceRGBA`,MeshNormalMaterial:`normal`,MeshBasicMaterial:`basic`,MeshLambertMaterial:`lambert`,MeshPhongMaterial:`phong`,MeshToonMaterial:`toon`,MeshStandardMaterial:`physical`,MeshPhysicalMaterial:`physical`,MeshMatcapMaterial:`matcap`,LineBasicMaterial:`basic`,LineDashedMaterial:`dashed`,PointsMaterial:`points`,ShadowMaterial:`shadow`,SpriteMaterial:`sprite`};function h(e){return l.add(e),e===0?`uv`:`uv${e}`}function g(a,s,u,g,_){let v=g.fog,y=_.geometry,b=a.isMeshStandardMaterial?g.environment:null,x=(a.isMeshStandardMaterial?n:t).get(a.envMap||b),S=x&&x.mapping===306?x.image.height:null,C=m[a.type];a.precision!==null&&(p=i.getMaxPrecision(a.precision),p!==a.precision&&console.warn(`THREE.WebGLProgram.getParameters:`,a.precision,`not supported, using`,p,`instead.`));let w=y.morphAttributes.position||y.morphAttributes.normal||y.morphAttributes.color,T=w===void 0?0:w.length,E=0;y.morphAttributes.position!==void 0&&(E=1),y.morphAttributes.normal!==void 0&&(E=2),y.morphAttributes.color!==void 0&&(E=3);let D,ee,O,k;if(C){let e=So[C];D=e.vertexShader,ee=e.fragmentShader}else D=a.vertexShader,ee=a.fragmentShader,c.update(a),O=c.getVertexShaderID(a),k=c.getFragmentShaderID(a);let te=e.getRenderTarget(),ne=e.state.buffers.depth.getReversed(),A=_.isInstancedMesh===!0,re=_.isBatchedMesh===!0,ie=!!a.map,j=!!a.matcap,ae=!!x,oe=!!a.aoMap,se=!!a.lightMap,ce=!!a.bumpMap,le=!!a.normalMap,ue=!!a.displacementMap,de=!!a.emissiveMap,fe=!!a.metalnessMap,pe=!!a.roughnessMap,me=a.anisotropy>0,he=a.clearcoat>0,ge=a.dispersion>0,_e=a.iridescence>0,ve=a.sheen>0,M=a.transmission>0,ye=me&&!!a.anisotropyMap,be=he&&!!a.clearcoatMap,xe=he&&!!a.clearcoatNormalMap,N=he&&!!a.clearcoatRoughnessMap,Se=_e&&!!a.iridescenceMap,P=_e&&!!a.iridescenceThicknessMap,F=ve&&!!a.sheenColorMap,Ce=ve&&!!a.sheenRoughnessMap,we=!!a.specularMap,Te=!!a.specularColorMap,Ee=!!a.specularIntensityMap,De=M&&!!a.transmissionMap,Oe=M&&!!a.thicknessMap,ke=!!a.gradientMap,Ae=!!a.alphaMap,je=a.alphaTest>0,Me=!!a.alphaHash,Ne=!!a.extensions,Pe=0;a.toneMapped&&(te===null||te.isXRRenderTarget===!0)&&(Pe=e.toneMapping);let Fe={shaderID:C,shaderType:a.type,shaderName:a.name,vertexShader:D,fragmentShader:ee,defines:a.defines,customVertexShaderID:O,customFragmentShaderID:k,isRawShaderMaterial:a.isRawShaderMaterial===!0,glslVersion:a.glslVersion,precision:p,batching:re,batchingColor:re&&_._colorsTexture!==null,instancing:A,instancingColor:A&&_.instanceColor!==null,instancingMorph:A&&_.morphTexture!==null,supportsVertexTextures:f,outputColorSpace:te===null?e.outputColorSpace:te.isXRRenderTarget===!0?te.texture.colorSpace:Le,alphaToCoverage:!!a.alphaToCoverage,map:ie,matcap:j,envMap:ae,envMapMode:ae&&x.mapping,envMapCubeUVHeight:S,aoMap:oe,lightMap:se,bumpMap:ce,normalMap:le,displacementMap:f&&ue,emissiveMap:de,normalMapObjectSpace:le&&a.normalMapType===1,normalMapTangentSpace:le&&a.normalMapType===0,metalnessMap:fe,roughnessMap:pe,anisotropy:me,anisotropyMap:ye,clearcoat:he,clearcoatMap:be,clearcoatNormalMap:xe,clearcoatRoughnessMap:N,dispersion:ge,iridescence:_e,iridescenceMap:Se,iridescenceThicknessMap:P,sheen:ve,sheenColorMap:F,sheenRoughnessMap:Ce,specularMap:we,specularColorMap:Te,specularIntensityMap:Ee,transmission:M,transmissionMap:De,thicknessMap:Oe,gradientMap:ke,opaque:a.transparent===!1&&a.blending===1&&a.alphaToCoverage===!1,alphaMap:Ae,alphaTest:je,alphaHash:Me,combine:a.combine,mapUv:ie&&h(a.map.channel),aoMapUv:oe&&h(a.aoMap.channel),lightMapUv:se&&h(a.lightMap.channel),bumpMapUv:ce&&h(a.bumpMap.channel),normalMapUv:le&&h(a.normalMap.channel),displacementMapUv:ue&&h(a.displacementMap.channel),emissiveMapUv:de&&h(a.emissiveMap.channel),metalnessMapUv:fe&&h(a.metalnessMap.channel),roughnessMapUv:pe&&h(a.roughnessMap.channel),anisotropyMapUv:ye&&h(a.anisotropyMap.channel),clearcoatMapUv:be&&h(a.clearcoatMap.channel),clearcoatNormalMapUv:xe&&h(a.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:N&&h(a.clearcoatRoughnessMap.channel),iridescenceMapUv:Se&&h(a.iridescenceMap.channel),iridescenceThicknessMapUv:P&&h(a.iridescenceThicknessMap.channel),sheenColorMapUv:F&&h(a.sheenColorMap.channel),sheenRoughnessMapUv:Ce&&h(a.sheenRoughnessMap.channel),specularMapUv:we&&h(a.specularMap.channel),specularColorMapUv:Te&&h(a.specularColorMap.channel),specularIntensityMapUv:Ee&&h(a.specularIntensityMap.channel),transmissionMapUv:De&&h(a.transmissionMap.channel),thicknessMapUv:Oe&&h(a.thicknessMap.channel),alphaMapUv:Ae&&h(a.alphaMap.channel),vertexTangents:!!y.attributes.tangent&&(le||me),vertexColors:a.vertexColors,vertexAlphas:a.vertexColors===!0&&!!y.attributes.color&&y.attributes.color.itemSize===4,pointsUvs:_.isPoints===!0&&!!y.attributes.uv&&(ie||Ae),fog:!!v,useFog:a.fog===!0,fogExp2:!!v&&v.isFogExp2,flatShading:a.flatShading===!0&&a.wireframe===!1,sizeAttenuation:a.sizeAttenuation===!0,logarithmicDepthBuffer:d,reversedDepthBuffer:ne,skinning:_.isSkinnedMesh===!0,morphTargets:y.morphAttributes.position!==void 0,morphNormals:y.morphAttributes.normal!==void 0,morphColors:y.morphAttributes.color!==void 0,morphTargetsCount:T,morphTextureStride:E,numDirLights:s.directional.length,numPointLights:s.point.length,numSpotLights:s.spot.length,numSpotLightMaps:s.spotLightMap.length,numRectAreaLights:s.rectArea.length,numHemiLights:s.hemi.length,numDirLightShadows:s.directionalShadowMap.length,numPointLightShadows:s.pointShadowMap.length,numSpotLightShadows:s.spotShadowMap.length,numSpotLightShadowsWithMaps:s.numSpotLightShadowsWithMaps,numLightProbes:s.numLightProbes,numClippingPlanes:o.numPlanes,numClipIntersection:o.numIntersection,dithering:a.dithering,shadowMapEnabled:e.shadowMap.enabled&&u.length>0,shadowMapType:e.shadowMap.type,toneMapping:Pe,decodeVideoTexture:ie&&a.map.isVideoTexture===!0&&kt.getTransfer(a.map.colorSpace)===`srgb`,decodeVideoTextureEmissive:de&&a.emissiveMap.isVideoTexture===!0&&kt.getTransfer(a.emissiveMap.colorSpace)===`srgb`,premultipliedAlpha:a.premultipliedAlpha,doubleSided:a.side===2,flipSided:a.side===1,useDepthPacking:a.depthPacking>=0,depthPacking:a.depthPacking||0,index0AttributeName:a.index0AttributeName,extensionClipCullDistance:Ne&&a.extensions.clipCullDistance===!0&&r.has(`WEBGL_clip_cull_distance`),extensionMultiDraw:(Ne&&a.extensions.multiDraw===!0||re)&&r.has(`WEBGL_multi_draw`),rendererExtensionParallelShaderCompile:r.has(`KHR_parallel_shader_compile`),customProgramCacheKey:a.customProgramCacheKey()};return Fe.vertexUv1s=l.has(1),Fe.vertexUv2s=l.has(2),Fe.vertexUv3s=l.has(3),l.clear(),Fe}function _(t){let n=[];if(t.shaderID?n.push(t.shaderID):(n.push(t.customVertexShaderID),n.push(t.customFragmentShaderID)),t.defines!==void 0)for(let e in t.defines)n.push(e),n.push(t.defines[e]);return t.isRawShaderMaterial===!1&&(v(n,t),y(n,t),n.push(e.outputColorSpace)),n.push(t.customProgramCacheKey),n.join()}function v(e,t){e.push(t.precision),e.push(t.outputColorSpace),e.push(t.envMapMode),e.push(t.envMapCubeUVHeight),e.push(t.mapUv),e.push(t.alphaMapUv),e.push(t.lightMapUv),e.push(t.aoMapUv),e.push(t.bumpMapUv),e.push(t.normalMapUv),e.push(t.displacementMapUv),e.push(t.emissiveMapUv),e.push(t.metalnessMapUv),e.push(t.roughnessMapUv),e.push(t.anisotropyMapUv),e.push(t.clearcoatMapUv),e.push(t.clearcoatNormalMapUv),e.push(t.clearcoatRoughnessMapUv),e.push(t.iridescenceMapUv),e.push(t.iridescenceThicknessMapUv),e.push(t.sheenColorMapUv),e.push(t.sheenRoughnessMapUv),e.push(t.specularMapUv),e.push(t.specularColorMapUv),e.push(t.specularIntensityMapUv),e.push(t.transmissionMapUv),e.push(t.thicknessMapUv),e.push(t.combine),e.push(t.fogExp2),e.push(t.sizeAttenuation),e.push(t.morphTargetsCount),e.push(t.morphAttributeCount),e.push(t.numDirLights),e.push(t.numPointLights),e.push(t.numSpotLights),e.push(t.numSpotLightMaps),e.push(t.numHemiLights),e.push(t.numRectAreaLights),e.push(t.numDirLightShadows),e.push(t.numPointLightShadows),e.push(t.numSpotLightShadows),e.push(t.numSpotLightShadowsWithMaps),e.push(t.numLightProbes),e.push(t.shadowMapType),e.push(t.toneMapping),e.push(t.numClippingPlanes),e.push(t.numClipIntersection),e.push(t.depthPacking)}function y(e,t){s.disableAll(),t.supportsVertexTextures&&s.enable(0),t.instancing&&s.enable(1),t.instancingColor&&s.enable(2),t.instancingMorph&&s.enable(3),t.matcap&&s.enable(4),t.envMap&&s.enable(5),t.normalMapObjectSpace&&s.enable(6),t.normalMapTangentSpace&&s.enable(7),t.clearcoat&&s.enable(8),t.iridescence&&s.enable(9),t.alphaTest&&s.enable(10),t.vertexColors&&s.enable(11),t.vertexAlphas&&s.enable(12),t.vertexUv1s&&s.enable(13),t.vertexUv2s&&s.enable(14),t.vertexUv3s&&s.enable(15),t.vertexTangents&&s.enable(16),t.anisotropy&&s.enable(17),t.alphaHash&&s.enable(18),t.batching&&s.enable(19),t.dispersion&&s.enable(20),t.batchingColor&&s.enable(21),t.gradientMap&&s.enable(22),e.push(s.mask),s.disableAll(),t.fog&&s.enable(0),t.useFog&&s.enable(1),t.flatShading&&s.enable(2),t.logarithmicDepthBuffer&&s.enable(3),t.reversedDepthBuffer&&s.enable(4),t.skinning&&s.enable(5),t.morphTargets&&s.enable(6),t.morphNormals&&s.enable(7),t.morphColors&&s.enable(8),t.premultipliedAlpha&&s.enable(9),t.shadowMapEnabled&&s.enable(10),t.doubleSided&&s.enable(11),t.flipSided&&s.enable(12),t.useDepthPacking&&s.enable(13),t.dithering&&s.enable(14),t.transmission&&s.enable(15),t.sheen&&s.enable(16),t.opaque&&s.enable(17),t.pointsUvs&&s.enable(18),t.decodeVideoTexture&&s.enable(19),t.decodeVideoTextureEmissive&&s.enable(20),t.alphaToCoverage&&s.enable(21),e.push(s.mask)}function b(e){let t=m[e.type],n;if(t){let e=So[t];n=qr.clone(e.uniforms)}else n=e.uniforms;return n}function x(t,n){let r;for(let e=0,t=u.length;e<t;e++){let t=u[e];if(t.cacheKey===n){r=t,++r.usedTimes;break}}return r===void 0&&(r=new Uc(e,n,t,a),u.push(r)),r}function S(e){if(--e.usedTimes===0){let t=u.indexOf(e);u[t]=u[u.length-1],u.pop(),e.destroy()}}function C(e){c.remove(e)}function w(){c.dispose()}return{getParameters:g,getProgramCacheKey:_,getUniforms:b,acquireProgram:x,releaseProgram:S,releaseShaderCache:C,programs:u,dispose:w}}function Jc(){let e=new WeakMap;function t(t){return e.has(t)}function n(t){let n=e.get(t);return n===void 0&&(n={},e.set(t,n)),n}function r(t){e.delete(t)}function i(t,n,r){e.get(t)[n]=r}function a(){e=new WeakMap}return{has:t,get:n,remove:r,update:i,dispose:a}}function Yc(e,t){return e.groupOrder===t.groupOrder?e.renderOrder===t.renderOrder?e.material.id===t.material.id?e.z===t.z?e.id-t.id:e.z-t.z:e.material.id-t.material.id:e.renderOrder-t.renderOrder:e.groupOrder-t.groupOrder}function Xc(e,t){return e.groupOrder===t.groupOrder?e.renderOrder===t.renderOrder?e.z===t.z?e.id-t.id:t.z-e.z:e.renderOrder-t.renderOrder:e.groupOrder-t.groupOrder}function Zc(){let e=[],t=0,n=[],r=[],i=[];function a(){t=0,n.length=0,r.length=0,i.length=0}function o(n,r,i,a,o,s){let c=e[t];return c===void 0?(c={id:n.id,object:n,geometry:r,material:i,groupOrder:a,renderOrder:n.renderOrder,z:o,group:s},e[t]=c):(c.id=n.id,c.object=n,c.geometry=r,c.material=i,c.groupOrder=a,c.renderOrder=n.renderOrder,c.z=o,c.group=s),t++,c}function s(e,t,a,s,c,l){let u=o(e,t,a,s,c,l);a.transmission>0?r.push(u):a.transparent===!0?i.push(u):n.push(u)}function c(e,t,a,s,c,l){let u=o(e,t,a,s,c,l);a.transmission>0?r.unshift(u):a.transparent===!0?i.unshift(u):n.unshift(u)}function l(e,t){n.length>1&&n.sort(e||Yc),r.length>1&&r.sort(t||Xc),i.length>1&&i.sort(t||Xc)}function u(){for(let n=t,r=e.length;n<r;n++){let t=e[n];if(t.id===null)break;t.id=null,t.object=null,t.geometry=null,t.material=null,t.group=null}}return{opaque:n,transmissive:r,transparent:i,init:a,push:s,unshift:c,finish:u,sort:l}}function Qc(){let e=new WeakMap;function t(t,n){let r=e.get(t),i;return r===void 0?(i=new Zc,e.set(t,[i])):n>=r.length?(i=new Zc,r.push(i)):i=r[n],i}function n(){e=new WeakMap}return{get:t,dispose:n}}function $c(){let e={};return{get:function(t){if(e[t.id]!==void 0)return e[t.id];let n;switch(t.type){case`DirectionalLight`:n={direction:new R,color:new B};break;case`SpotLight`:n={position:new R,direction:new R,color:new B,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case`PointLight`:n={position:new R,color:new B,distance:0,decay:0};break;case`HemisphereLight`:n={direction:new R,skyColor:new B,groundColor:new B};break;case`RectAreaLight`:n={color:new B,position:new R,halfWidth:new R,halfHeight:new R};break}return e[t.id]=n,n}}}function el(){let e={};return{get:function(t){if(e[t.id]!==void 0)return e[t.id];let n;switch(t.type){case`DirectionalLight`:n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new L};break;case`SpotLight`:n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new L};break;case`PointLight`:n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new L,shadowCameraNear:1,shadowCameraFar:1e3};break}return e[t.id]=n,n}}}var tl=0;function nl(e,t){return(t.castShadow?2:0)-(e.castShadow?2:0)+ +!!t.map-!!e.map}function rl(e){let t=new $c,n=el(),r={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let e=0;e<9;e++)r.probe.push(new R);let i=new R,a=new yn,o=new yn;function s(i){let a=0,o=0,s=0;for(let e=0;e<9;e++)r.probe[e].set(0,0,0);let c=0,l=0,u=0,d=0,f=0,p=0,m=0,h=0,g=0,_=0,v=0;i.sort(nl);for(let e=0,y=i.length;e<y;e++){let y=i[e],b=y.color,x=y.intensity,S=y.distance,C=y.shadow&&y.shadow.map?y.shadow.map.texture:null;if(y.isAmbientLight)a+=b.r*x,o+=b.g*x,s+=b.b*x;else if(y.isLightProbe){for(let e=0;e<9;e++)r.probe[e].addScaledVector(y.sh.coefficients[e],x);v++}else if(y.isDirectionalLight){let e=t.get(y);if(e.color.copy(y.color).multiplyScalar(y.intensity),y.castShadow){let e=y.shadow,t=n.get(y);t.shadowIntensity=e.intensity,t.shadowBias=e.bias,t.shadowNormalBias=e.normalBias,t.shadowRadius=e.radius,t.shadowMapSize=e.mapSize,r.directionalShadow[c]=t,r.directionalShadowMap[c]=C,r.directionalShadowMatrix[c]=y.shadow.matrix,p++}r.directional[c]=e,c++}else if(y.isSpotLight){let e=t.get(y);e.position.setFromMatrixPosition(y.matrixWorld),e.color.copy(b).multiplyScalar(x),e.distance=S,e.coneCos=Math.cos(y.angle),e.penumbraCos=Math.cos(y.angle*(1-y.penumbra)),e.decay=y.decay,r.spot[u]=e;let i=y.shadow;if(y.map&&(r.spotLightMap[g]=y.map,g++,i.updateMatrices(y),y.castShadow&&_++),r.spotLightMatrix[u]=i.matrix,y.castShadow){let e=n.get(y);e.shadowIntensity=i.intensity,e.shadowBias=i.bias,e.shadowNormalBias=i.normalBias,e.shadowRadius=i.radius,e.shadowMapSize=i.mapSize,r.spotShadow[u]=e,r.spotShadowMap[u]=C,h++}u++}else if(y.isRectAreaLight){let e=t.get(y);e.color.copy(b).multiplyScalar(x),e.halfWidth.set(y.width*.5,0,0),e.halfHeight.set(0,y.height*.5,0),r.rectArea[d]=e,d++}else if(y.isPointLight){let e=t.get(y);if(e.color.copy(y.color).multiplyScalar(y.intensity),e.distance=y.distance,e.decay=y.decay,y.castShadow){let e=y.shadow,t=n.get(y);t.shadowIntensity=e.intensity,t.shadowBias=e.bias,t.shadowNormalBias=e.normalBias,t.shadowRadius=e.radius,t.shadowMapSize=e.mapSize,t.shadowCameraNear=e.camera.near,t.shadowCameraFar=e.camera.far,r.pointShadow[l]=t,r.pointShadowMap[l]=C,r.pointShadowMatrix[l]=y.shadow.matrix,m++}r.point[l]=e,l++}else if(y.isHemisphereLight){let e=t.get(y);e.skyColor.copy(y.color).multiplyScalar(x),e.groundColor.copy(y.groundColor).multiplyScalar(x),r.hemi[f]=e,f++}}d>0&&(e.has(`OES_texture_float_linear`)===!0?(r.rectAreaLTC1=W.LTC_FLOAT_1,r.rectAreaLTC2=W.LTC_FLOAT_2):(r.rectAreaLTC1=W.LTC_HALF_1,r.rectAreaLTC2=W.LTC_HALF_2)),r.ambient[0]=a,r.ambient[1]=o,r.ambient[2]=s;let y=r.hash;(y.directionalLength!==c||y.pointLength!==l||y.spotLength!==u||y.rectAreaLength!==d||y.hemiLength!==f||y.numDirectionalShadows!==p||y.numPointShadows!==m||y.numSpotShadows!==h||y.numSpotMaps!==g||y.numLightProbes!==v)&&(r.directional.length=c,r.spot.length=u,r.rectArea.length=d,r.point.length=l,r.hemi.length=f,r.directionalShadow.length=p,r.directionalShadowMap.length=p,r.pointShadow.length=m,r.pointShadowMap.length=m,r.spotShadow.length=h,r.spotShadowMap.length=h,r.directionalShadowMatrix.length=p,r.pointShadowMatrix.length=m,r.spotLightMatrix.length=h+g-_,r.spotLightMap.length=g,r.numSpotLightShadowsWithMaps=_,r.numLightProbes=v,y.directionalLength=c,y.pointLength=l,y.spotLength=u,y.rectAreaLength=d,y.hemiLength=f,y.numDirectionalShadows=p,y.numPointShadows=m,y.numSpotShadows=h,y.numSpotMaps=g,y.numLightProbes=v,r.version=tl++)}function c(e,t){let n=0,s=0,c=0,l=0,u=0,d=t.matrixWorldInverse;for(let t=0,f=e.length;t<f;t++){let f=e[t];if(f.isDirectionalLight){let e=r.directional[n];e.direction.setFromMatrixPosition(f.matrixWorld),i.setFromMatrixPosition(f.target.matrixWorld),e.direction.sub(i),e.direction.transformDirection(d),n++}else if(f.isSpotLight){let e=r.spot[c];e.position.setFromMatrixPosition(f.matrixWorld),e.position.applyMatrix4(d),e.direction.setFromMatrixPosition(f.matrixWorld),i.setFromMatrixPosition(f.target.matrixWorld),e.direction.sub(i),e.direction.transformDirection(d),c++}else if(f.isRectAreaLight){let e=r.rectArea[l];e.position.setFromMatrixPosition(f.matrixWorld),e.position.applyMatrix4(d),o.identity(),a.copy(f.matrixWorld),a.premultiply(d),o.extractRotation(a),e.halfWidth.set(f.width*.5,0,0),e.halfHeight.set(0,f.height*.5,0),e.halfWidth.applyMatrix4(o),e.halfHeight.applyMatrix4(o),l++}else if(f.isPointLight){let e=r.point[s];e.position.setFromMatrixPosition(f.matrixWorld),e.position.applyMatrix4(d),s++}else if(f.isHemisphereLight){let e=r.hemi[u];e.direction.setFromMatrixPosition(f.matrixWorld),e.direction.transformDirection(d),u++}}}return{setup:s,setupView:c,state:r}}function il(e){let t=new rl(e),n=[],r=[];function i(e){l.camera=e,n.length=0,r.length=0}function a(e){n.push(e)}function o(e){r.push(e)}function s(){t.setup(n)}function c(e){t.setupView(n,e)}let l={lightsArray:n,shadowsArray:r,camera:null,lights:t,transmissionRenderTarget:{}};return{init:i,state:l,setupLights:s,setupLightsView:c,pushLight:a,pushShadow:o}}function al(e){let t=new WeakMap;function n(n,r=0){let i=t.get(n),a;return i===void 0?(a=new il(e),t.set(n,[a])):r>=i.length?(a=new il(e),i.push(a)):a=i[r],a}function r(){t=new WeakMap}return{get:n,dispose:r}}var ol=`void main() {
3780
+ `+n)}else o===``?(s===``||c===``)&&(u=!1):console.warn(`THREE.WebGLProgram: Program Info Log:`,o);u&&(t.diagnostics={runnable:l,programLog:o,vertexShader:{log:s,prefix:g},fragmentShader:{log:c,prefix:_}})}i.deleteShader(x),i.deleteShader(S),w=new vc(i,h),T=Mc(i,h)}let w;this.getUniforms=function(){return w===void 0&&C(this),w};let T;this.getAttributes=function(){return T===void 0&&C(this),T};let E=n.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return E===!1&&(E=i.getProgramParameter(h,bc)),E},this.destroy=function(){r.releaseStatesOfProgram(this),i.deleteProgram(h),this.program=void 0},this.type=n.shaderType,this.name=n.shaderName,this.id=xc++,this.cacheKey=t,this.usedTimes=1,this.program=h,this.vertexShader=x,this.fragmentShader=S,this}var Xc=0,Zc=class{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){let t=e.vertexShader,n=e.fragmentShader,r=this._getShaderStage(t),i=this._getShaderStage(n),a=this._getShaderCacheForMaterial(e);return a.has(r)===!1&&(a.add(r),r.usedTimes++),a.has(i)===!1&&(a.add(i),i.usedTimes++),this}remove(e){let t=this.materialCache.get(e);for(let e of t)e.usedTimes--,e.usedTimes===0&&this.shaderCache.delete(e.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){let t=this.materialCache,n=t.get(e);return n===void 0&&(n=new Set,t.set(e,n)),n}_getShaderStage(e){let t=this.shaderCache,n=t.get(e);return n===void 0&&(n=new Qc(e),t.set(e,n)),n}},Qc=class{constructor(e){this.id=Xc++,this.code=e,this.usedTimes=0}};function $c(e,t,n,r,i,a,o){let s=new An,c=new Zc,l=new Set,u=[],d=i.logarithmicDepthBuffer,f=i.vertexTextures,p=i.precision,m={MeshDepthMaterial:`depth`,MeshDistanceMaterial:`distanceRGBA`,MeshNormalMaterial:`normal`,MeshBasicMaterial:`basic`,MeshLambertMaterial:`lambert`,MeshPhongMaterial:`phong`,MeshToonMaterial:`toon`,MeshStandardMaterial:`physical`,MeshPhysicalMaterial:`physical`,MeshMatcapMaterial:`matcap`,LineBasicMaterial:`basic`,LineDashedMaterial:`dashed`,PointsMaterial:`points`,ShadowMaterial:`shadow`,SpriteMaterial:`sprite`};function h(e){return l.add(e),e===0?`uv`:`uv${e}`}function g(a,s,u,g,_){let v=g.fog,y=_.geometry,b=a.isMeshStandardMaterial?g.environment:null,x=(a.isMeshStandardMaterial?n:t).get(a.envMap||b),S=x&&x.mapping===306?x.image.height:null,C=m[a.type];a.precision!==null&&(p=i.getMaxPrecision(a.precision),p!==a.precision&&console.warn(`THREE.WebGLProgram.getParameters:`,a.precision,`not supported, using`,p,`instead.`));let w=y.morphAttributes.position||y.morphAttributes.normal||y.morphAttributes.color,T=w===void 0?0:w.length,E=0;y.morphAttributes.position!==void 0&&(E=1),y.morphAttributes.normal!==void 0&&(E=2),y.morphAttributes.color!==void 0&&(E=3);let D,ee,O,k;if(C){let e=Oo[C];D=e.vertexShader,ee=e.fragmentShader}else D=a.vertexShader,ee=a.fragmentShader,c.update(a),O=c.getVertexShaderID(a),k=c.getFragmentShaderID(a);let te=e.getRenderTarget(),ne=e.state.buffers.depth.getReversed(),A=_.isInstancedMesh===!0,re=_.isBatchedMesh===!0,ie=!!a.map,j=!!a.matcap,ae=!!x,oe=!!a.aoMap,se=!!a.lightMap,ce=!!a.bumpMap,le=!!a.normalMap,ue=!!a.displacementMap,de=!!a.emissiveMap,fe=!!a.metalnessMap,pe=!!a.roughnessMap,me=a.anisotropy>0,he=a.clearcoat>0,ge=a.dispersion>0,_e=a.iridescence>0,ve=a.sheen>0,M=a.transmission>0,ye=me&&!!a.anisotropyMap,be=he&&!!a.clearcoatMap,xe=he&&!!a.clearcoatNormalMap,N=he&&!!a.clearcoatRoughnessMap,Se=_e&&!!a.iridescenceMap,P=_e&&!!a.iridescenceThicknessMap,F=ve&&!!a.sheenColorMap,Ce=ve&&!!a.sheenRoughnessMap,we=!!a.specularMap,Te=!!a.specularColorMap,Ee=!!a.specularIntensityMap,De=M&&!!a.transmissionMap,Oe=M&&!!a.thicknessMap,ke=!!a.gradientMap,Ae=!!a.alphaMap,je=a.alphaTest>0,Me=!!a.alphaHash,Ne=!!a.extensions,Pe=0;a.toneMapped&&(te===null||te.isXRRenderTarget===!0)&&(Pe=e.toneMapping);let Fe={shaderID:C,shaderType:a.type,shaderName:a.name,vertexShader:D,fragmentShader:ee,defines:a.defines,customVertexShaderID:O,customFragmentShaderID:k,isRawShaderMaterial:a.isRawShaderMaterial===!0,glslVersion:a.glslVersion,precision:p,batching:re,batchingColor:re&&_._colorsTexture!==null,instancing:A,instancingColor:A&&_.instanceColor!==null,instancingMorph:A&&_.morphTexture!==null,supportsVertexTextures:f,outputColorSpace:te===null?e.outputColorSpace:te.isXRRenderTarget===!0?te.texture.colorSpace:Le,alphaToCoverage:!!a.alphaToCoverage,map:ie,matcap:j,envMap:ae,envMapMode:ae&&x.mapping,envMapCubeUVHeight:S,aoMap:oe,lightMap:se,bumpMap:ce,normalMap:le,displacementMap:f&&ue,emissiveMap:de,normalMapObjectSpace:le&&a.normalMapType===1,normalMapTangentSpace:le&&a.normalMapType===0,metalnessMap:fe,roughnessMap:pe,anisotropy:me,anisotropyMap:ye,clearcoat:he,clearcoatMap:be,clearcoatNormalMap:xe,clearcoatRoughnessMap:N,dispersion:ge,iridescence:_e,iridescenceMap:Se,iridescenceThicknessMap:P,sheen:ve,sheenColorMap:F,sheenRoughnessMap:Ce,specularMap:we,specularColorMap:Te,specularIntensityMap:Ee,transmission:M,transmissionMap:De,thicknessMap:Oe,gradientMap:ke,opaque:a.transparent===!1&&a.blending===1&&a.alphaToCoverage===!1,alphaMap:Ae,alphaTest:je,alphaHash:Me,combine:a.combine,mapUv:ie&&h(a.map.channel),aoMapUv:oe&&h(a.aoMap.channel),lightMapUv:se&&h(a.lightMap.channel),bumpMapUv:ce&&h(a.bumpMap.channel),normalMapUv:le&&h(a.normalMap.channel),displacementMapUv:ue&&h(a.displacementMap.channel),emissiveMapUv:de&&h(a.emissiveMap.channel),metalnessMapUv:fe&&h(a.metalnessMap.channel),roughnessMapUv:pe&&h(a.roughnessMap.channel),anisotropyMapUv:ye&&h(a.anisotropyMap.channel),clearcoatMapUv:be&&h(a.clearcoatMap.channel),clearcoatNormalMapUv:xe&&h(a.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:N&&h(a.clearcoatRoughnessMap.channel),iridescenceMapUv:Se&&h(a.iridescenceMap.channel),iridescenceThicknessMapUv:P&&h(a.iridescenceThicknessMap.channel),sheenColorMapUv:F&&h(a.sheenColorMap.channel),sheenRoughnessMapUv:Ce&&h(a.sheenRoughnessMap.channel),specularMapUv:we&&h(a.specularMap.channel),specularColorMapUv:Te&&h(a.specularColorMap.channel),specularIntensityMapUv:Ee&&h(a.specularIntensityMap.channel),transmissionMapUv:De&&h(a.transmissionMap.channel),thicknessMapUv:Oe&&h(a.thicknessMap.channel),alphaMapUv:Ae&&h(a.alphaMap.channel),vertexTangents:!!y.attributes.tangent&&(le||me),vertexColors:a.vertexColors,vertexAlphas:a.vertexColors===!0&&!!y.attributes.color&&y.attributes.color.itemSize===4,pointsUvs:_.isPoints===!0&&!!y.attributes.uv&&(ie||Ae),fog:!!v,useFog:a.fog===!0,fogExp2:!!v&&v.isFogExp2,flatShading:a.flatShading===!0&&a.wireframe===!1,sizeAttenuation:a.sizeAttenuation===!0,logarithmicDepthBuffer:d,reversedDepthBuffer:ne,skinning:_.isSkinnedMesh===!0,morphTargets:y.morphAttributes.position!==void 0,morphNormals:y.morphAttributes.normal!==void 0,morphColors:y.morphAttributes.color!==void 0,morphTargetsCount:T,morphTextureStride:E,numDirLights:s.directional.length,numPointLights:s.point.length,numSpotLights:s.spot.length,numSpotLightMaps:s.spotLightMap.length,numRectAreaLights:s.rectArea.length,numHemiLights:s.hemi.length,numDirLightShadows:s.directionalShadowMap.length,numPointLightShadows:s.pointShadowMap.length,numSpotLightShadows:s.spotShadowMap.length,numSpotLightShadowsWithMaps:s.numSpotLightShadowsWithMaps,numLightProbes:s.numLightProbes,numClippingPlanes:o.numPlanes,numClipIntersection:o.numIntersection,dithering:a.dithering,shadowMapEnabled:e.shadowMap.enabled&&u.length>0,shadowMapType:e.shadowMap.type,toneMapping:Pe,decodeVideoTexture:ie&&a.map.isVideoTexture===!0&&kt.getTransfer(a.map.colorSpace)===`srgb`,decodeVideoTextureEmissive:de&&a.emissiveMap.isVideoTexture===!0&&kt.getTransfer(a.emissiveMap.colorSpace)===`srgb`,premultipliedAlpha:a.premultipliedAlpha,doubleSided:a.side===2,flipSided:a.side===1,useDepthPacking:a.depthPacking>=0,depthPacking:a.depthPacking||0,index0AttributeName:a.index0AttributeName,extensionClipCullDistance:Ne&&a.extensions.clipCullDistance===!0&&r.has(`WEBGL_clip_cull_distance`),extensionMultiDraw:(Ne&&a.extensions.multiDraw===!0||re)&&r.has(`WEBGL_multi_draw`),rendererExtensionParallelShaderCompile:r.has(`KHR_parallel_shader_compile`),customProgramCacheKey:a.customProgramCacheKey()};return Fe.vertexUv1s=l.has(1),Fe.vertexUv2s=l.has(2),Fe.vertexUv3s=l.has(3),l.clear(),Fe}function _(t){let n=[];if(t.shaderID?n.push(t.shaderID):(n.push(t.customVertexShaderID),n.push(t.customFragmentShaderID)),t.defines!==void 0)for(let e in t.defines)n.push(e),n.push(t.defines[e]);return t.isRawShaderMaterial===!1&&(v(n,t),y(n,t),n.push(e.outputColorSpace)),n.push(t.customProgramCacheKey),n.join()}function v(e,t){e.push(t.precision),e.push(t.outputColorSpace),e.push(t.envMapMode),e.push(t.envMapCubeUVHeight),e.push(t.mapUv),e.push(t.alphaMapUv),e.push(t.lightMapUv),e.push(t.aoMapUv),e.push(t.bumpMapUv),e.push(t.normalMapUv),e.push(t.displacementMapUv),e.push(t.emissiveMapUv),e.push(t.metalnessMapUv),e.push(t.roughnessMapUv),e.push(t.anisotropyMapUv),e.push(t.clearcoatMapUv),e.push(t.clearcoatNormalMapUv),e.push(t.clearcoatRoughnessMapUv),e.push(t.iridescenceMapUv),e.push(t.iridescenceThicknessMapUv),e.push(t.sheenColorMapUv),e.push(t.sheenRoughnessMapUv),e.push(t.specularMapUv),e.push(t.specularColorMapUv),e.push(t.specularIntensityMapUv),e.push(t.transmissionMapUv),e.push(t.thicknessMapUv),e.push(t.combine),e.push(t.fogExp2),e.push(t.sizeAttenuation),e.push(t.morphTargetsCount),e.push(t.morphAttributeCount),e.push(t.numDirLights),e.push(t.numPointLights),e.push(t.numSpotLights),e.push(t.numSpotLightMaps),e.push(t.numHemiLights),e.push(t.numRectAreaLights),e.push(t.numDirLightShadows),e.push(t.numPointLightShadows),e.push(t.numSpotLightShadows),e.push(t.numSpotLightShadowsWithMaps),e.push(t.numLightProbes),e.push(t.shadowMapType),e.push(t.toneMapping),e.push(t.numClippingPlanes),e.push(t.numClipIntersection),e.push(t.depthPacking)}function y(e,t){s.disableAll(),t.supportsVertexTextures&&s.enable(0),t.instancing&&s.enable(1),t.instancingColor&&s.enable(2),t.instancingMorph&&s.enable(3),t.matcap&&s.enable(4),t.envMap&&s.enable(5),t.normalMapObjectSpace&&s.enable(6),t.normalMapTangentSpace&&s.enable(7),t.clearcoat&&s.enable(8),t.iridescence&&s.enable(9),t.alphaTest&&s.enable(10),t.vertexColors&&s.enable(11),t.vertexAlphas&&s.enable(12),t.vertexUv1s&&s.enable(13),t.vertexUv2s&&s.enable(14),t.vertexUv3s&&s.enable(15),t.vertexTangents&&s.enable(16),t.anisotropy&&s.enable(17),t.alphaHash&&s.enable(18),t.batching&&s.enable(19),t.dispersion&&s.enable(20),t.batchingColor&&s.enable(21),t.gradientMap&&s.enable(22),e.push(s.mask),s.disableAll(),t.fog&&s.enable(0),t.useFog&&s.enable(1),t.flatShading&&s.enable(2),t.logarithmicDepthBuffer&&s.enable(3),t.reversedDepthBuffer&&s.enable(4),t.skinning&&s.enable(5),t.morphTargets&&s.enable(6),t.morphNormals&&s.enable(7),t.morphColors&&s.enable(8),t.premultipliedAlpha&&s.enable(9),t.shadowMapEnabled&&s.enable(10),t.doubleSided&&s.enable(11),t.flipSided&&s.enable(12),t.useDepthPacking&&s.enable(13),t.dithering&&s.enable(14),t.transmission&&s.enable(15),t.sheen&&s.enable(16),t.opaque&&s.enable(17),t.pointsUvs&&s.enable(18),t.decodeVideoTexture&&s.enable(19),t.decodeVideoTextureEmissive&&s.enable(20),t.alphaToCoverage&&s.enable(21),e.push(s.mask)}function b(e){let t=m[e.type],n;if(t){let e=Oo[t];n=Kr.clone(e.uniforms)}else n=e.uniforms;return n}function x(t,n){let r;for(let e=0,t=u.length;e<t;e++){let t=u[e];if(t.cacheKey===n){r=t,++r.usedTimes;break}}return r===void 0&&(r=new Yc(e,n,t,a),u.push(r)),r}function S(e){if(--e.usedTimes===0){let t=u.indexOf(e);u[t]=u[u.length-1],u.pop(),e.destroy()}}function C(e){c.remove(e)}function w(){c.dispose()}return{getParameters:g,getProgramCacheKey:_,getUniforms:b,acquireProgram:x,releaseProgram:S,releaseShaderCache:C,programs:u,dispose:w}}function el(){let e=new WeakMap;function t(t){return e.has(t)}function n(t){let n=e.get(t);return n===void 0&&(n={},e.set(t,n)),n}function r(t){e.delete(t)}function i(t,n,r){e.get(t)[n]=r}function a(){e=new WeakMap}return{has:t,get:n,remove:r,update:i,dispose:a}}function tl(e,t){return e.groupOrder===t.groupOrder?e.renderOrder===t.renderOrder?e.material.id===t.material.id?e.z===t.z?e.id-t.id:e.z-t.z:e.material.id-t.material.id:e.renderOrder-t.renderOrder:e.groupOrder-t.groupOrder}function nl(e,t){return e.groupOrder===t.groupOrder?e.renderOrder===t.renderOrder?e.z===t.z?e.id-t.id:t.z-e.z:e.renderOrder-t.renderOrder:e.groupOrder-t.groupOrder}function rl(){let e=[],t=0,n=[],r=[],i=[];function a(){t=0,n.length=0,r.length=0,i.length=0}function o(n,r,i,a,o,s){let c=e[t];return c===void 0?(c={id:n.id,object:n,geometry:r,material:i,groupOrder:a,renderOrder:n.renderOrder,z:o,group:s},e[t]=c):(c.id=n.id,c.object=n,c.geometry=r,c.material=i,c.groupOrder=a,c.renderOrder=n.renderOrder,c.z=o,c.group=s),t++,c}function s(e,t,a,s,c,l){let u=o(e,t,a,s,c,l);a.transmission>0?r.push(u):a.transparent===!0?i.push(u):n.push(u)}function c(e,t,a,s,c,l){let u=o(e,t,a,s,c,l);a.transmission>0?r.unshift(u):a.transparent===!0?i.unshift(u):n.unshift(u)}function l(e,t){n.length>1&&n.sort(e||tl),r.length>1&&r.sort(t||nl),i.length>1&&i.sort(t||nl)}function u(){for(let n=t,r=e.length;n<r;n++){let t=e[n];if(t.id===null)break;t.id=null,t.object=null,t.geometry=null,t.material=null,t.group=null}}return{opaque:n,transmissive:r,transparent:i,init:a,push:s,unshift:c,finish:u,sort:l}}function il(){let e=new WeakMap;function t(t,n){let r=e.get(t),i;return r===void 0?(i=new rl,e.set(t,[i])):n>=r.length?(i=new rl,r.push(i)):i=r[n],i}function n(){e=new WeakMap}return{get:t,dispose:n}}function al(){let e={};return{get:function(t){if(e[t.id]!==void 0)return e[t.id];let n;switch(t.type){case`DirectionalLight`:n={direction:new R,color:new B};break;case`SpotLight`:n={position:new R,direction:new R,color:new B,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case`PointLight`:n={position:new R,color:new B,distance:0,decay:0};break;case`HemisphereLight`:n={direction:new R,skyColor:new B,groundColor:new B};break;case`RectAreaLight`:n={color:new B,position:new R,halfWidth:new R,halfHeight:new R};break}return e[t.id]=n,n}}}function ol(){let e={};return{get:function(t){if(e[t.id]!==void 0)return e[t.id];let n;switch(t.type){case`DirectionalLight`:n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new L};break;case`SpotLight`:n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new L};break;case`PointLight`:n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new L,shadowCameraNear:1,shadowCameraFar:1e3};break}return e[t.id]=n,n}}}var sl=0;function cl(e,t){return(t.castShadow?2:0)-(e.castShadow?2:0)+ +!!t.map-!!e.map}function ll(e){let t=new al,n=ol(),r={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let e=0;e<9;e++)r.probe.push(new R);let i=new R,a=new yn,o=new yn;function s(i){let a=0,o=0,s=0;for(let e=0;e<9;e++)r.probe[e].set(0,0,0);let c=0,l=0,u=0,d=0,f=0,p=0,m=0,h=0,g=0,_=0,v=0;i.sort(cl);for(let e=0,y=i.length;e<y;e++){let y=i[e],b=y.color,x=y.intensity,S=y.distance,C=y.shadow&&y.shadow.map?y.shadow.map.texture:null;if(y.isAmbientLight)a+=b.r*x,o+=b.g*x,s+=b.b*x;else if(y.isLightProbe){for(let e=0;e<9;e++)r.probe[e].addScaledVector(y.sh.coefficients[e],x);v++}else if(y.isDirectionalLight){let e=t.get(y);if(e.color.copy(y.color).multiplyScalar(y.intensity),y.castShadow){let e=y.shadow,t=n.get(y);t.shadowIntensity=e.intensity,t.shadowBias=e.bias,t.shadowNormalBias=e.normalBias,t.shadowRadius=e.radius,t.shadowMapSize=e.mapSize,r.directionalShadow[c]=t,r.directionalShadowMap[c]=C,r.directionalShadowMatrix[c]=y.shadow.matrix,p++}r.directional[c]=e,c++}else if(y.isSpotLight){let e=t.get(y);e.position.setFromMatrixPosition(y.matrixWorld),e.color.copy(b).multiplyScalar(x),e.distance=S,e.coneCos=Math.cos(y.angle),e.penumbraCos=Math.cos(y.angle*(1-y.penumbra)),e.decay=y.decay,r.spot[u]=e;let i=y.shadow;if(y.map&&(r.spotLightMap[g]=y.map,g++,i.updateMatrices(y),y.castShadow&&_++),r.spotLightMatrix[u]=i.matrix,y.castShadow){let e=n.get(y);e.shadowIntensity=i.intensity,e.shadowBias=i.bias,e.shadowNormalBias=i.normalBias,e.shadowRadius=i.radius,e.shadowMapSize=i.mapSize,r.spotShadow[u]=e,r.spotShadowMap[u]=C,h++}u++}else if(y.isRectAreaLight){let e=t.get(y);e.color.copy(b).multiplyScalar(x),e.halfWidth.set(y.width*.5,0,0),e.halfHeight.set(0,y.height*.5,0),r.rectArea[d]=e,d++}else if(y.isPointLight){let e=t.get(y);if(e.color.copy(y.color).multiplyScalar(y.intensity),e.distance=y.distance,e.decay=y.decay,y.castShadow){let e=y.shadow,t=n.get(y);t.shadowIntensity=e.intensity,t.shadowBias=e.bias,t.shadowNormalBias=e.normalBias,t.shadowRadius=e.radius,t.shadowMapSize=e.mapSize,t.shadowCameraNear=e.camera.near,t.shadowCameraFar=e.camera.far,r.pointShadow[l]=t,r.pointShadowMap[l]=C,r.pointShadowMatrix[l]=y.shadow.matrix,m++}r.point[l]=e,l++}else if(y.isHemisphereLight){let e=t.get(y);e.skyColor.copy(y.color).multiplyScalar(x),e.groundColor.copy(y.groundColor).multiplyScalar(x),r.hemi[f]=e,f++}}d>0&&(e.has(`OES_texture_float_linear`)===!0?(r.rectAreaLTC1=G.LTC_FLOAT_1,r.rectAreaLTC2=G.LTC_FLOAT_2):(r.rectAreaLTC1=G.LTC_HALF_1,r.rectAreaLTC2=G.LTC_HALF_2)),r.ambient[0]=a,r.ambient[1]=o,r.ambient[2]=s;let y=r.hash;(y.directionalLength!==c||y.pointLength!==l||y.spotLength!==u||y.rectAreaLength!==d||y.hemiLength!==f||y.numDirectionalShadows!==p||y.numPointShadows!==m||y.numSpotShadows!==h||y.numSpotMaps!==g||y.numLightProbes!==v)&&(r.directional.length=c,r.spot.length=u,r.rectArea.length=d,r.point.length=l,r.hemi.length=f,r.directionalShadow.length=p,r.directionalShadowMap.length=p,r.pointShadow.length=m,r.pointShadowMap.length=m,r.spotShadow.length=h,r.spotShadowMap.length=h,r.directionalShadowMatrix.length=p,r.pointShadowMatrix.length=m,r.spotLightMatrix.length=h+g-_,r.spotLightMap.length=g,r.numSpotLightShadowsWithMaps=_,r.numLightProbes=v,y.directionalLength=c,y.pointLength=l,y.spotLength=u,y.rectAreaLength=d,y.hemiLength=f,y.numDirectionalShadows=p,y.numPointShadows=m,y.numSpotShadows=h,y.numSpotMaps=g,y.numLightProbes=v,r.version=sl++)}function c(e,t){let n=0,s=0,c=0,l=0,u=0,d=t.matrixWorldInverse;for(let t=0,f=e.length;t<f;t++){let f=e[t];if(f.isDirectionalLight){let e=r.directional[n];e.direction.setFromMatrixPosition(f.matrixWorld),i.setFromMatrixPosition(f.target.matrixWorld),e.direction.sub(i),e.direction.transformDirection(d),n++}else if(f.isSpotLight){let e=r.spot[c];e.position.setFromMatrixPosition(f.matrixWorld),e.position.applyMatrix4(d),e.direction.setFromMatrixPosition(f.matrixWorld),i.setFromMatrixPosition(f.target.matrixWorld),e.direction.sub(i),e.direction.transformDirection(d),c++}else if(f.isRectAreaLight){let e=r.rectArea[l];e.position.setFromMatrixPosition(f.matrixWorld),e.position.applyMatrix4(d),o.identity(),a.copy(f.matrixWorld),a.premultiply(d),o.extractRotation(a),e.halfWidth.set(f.width*.5,0,0),e.halfHeight.set(0,f.height*.5,0),e.halfWidth.applyMatrix4(o),e.halfHeight.applyMatrix4(o),l++}else if(f.isPointLight){let e=r.point[s];e.position.setFromMatrixPosition(f.matrixWorld),e.position.applyMatrix4(d),s++}else if(f.isHemisphereLight){let e=r.hemi[u];e.direction.setFromMatrixPosition(f.matrixWorld),e.direction.transformDirection(d),u++}}}return{setup:s,setupView:c,state:r}}function ul(e){let t=new ll(e),n=[],r=[];function i(e){l.camera=e,n.length=0,r.length=0}function a(e){n.push(e)}function o(e){r.push(e)}function s(){t.setup(n)}function c(e){t.setupView(n,e)}let l={lightsArray:n,shadowsArray:r,camera:null,lights:t,transmissionRenderTarget:{}};return{init:i,state:l,setupLights:s,setupLightsView:c,pushLight:a,pushShadow:o}}function dl(e){let t=new WeakMap;function n(n,r=0){let i=t.get(n),a;return i===void 0?(a=new ul(e),t.set(n,[a])):r>=i.length?(a=new ul(e),i.push(a)):a=i[r],a}function r(){t=new WeakMap}return{get:n,dispose:r}}var fl=`void main() {
3781
3781
  gl_Position = vec4( position, 1.0 );
3782
- }`,sl=`uniform sampler2D shadow_pass;
3782
+ }`,pl=`uniform sampler2D shadow_pass;
3783
3783
  uniform vec2 resolution;
3784
3784
  uniform float radius;
3785
3785
  #include <packing>
@@ -3805,12 +3805,12 @@ void main() {
3805
3805
  squared_mean = squared_mean / samples;
3806
3806
  float std_dev = sqrt( squared_mean - mean * mean );
3807
3807
  gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );
3808
- }`;function cl(e,t,n){let i=new Li,a=new L,o=new L,s=new Bt,c=new pa({depthPacking:Fe}),l=new ma,u={},d=n.maxTextureSize,f={0:1,1:0,2:2},p=new Xr({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new L},radius:{value:4}},vertexShader:ol,fragmentShader:sl}),m=p.clone();m.defines.HORIZONTAL_PASS=1;let h=new Or;h.setAttribute(`position`,new V(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));let g=new H(h,p),_=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=1;let v=this.type;this.render=function(t,n,c){if(_.enabled===!1||_.autoUpdate===!1&&_.needsUpdate===!1||t.length===0)return;let l=e.getRenderTarget(),u=e.getActiveCubeFace(),f=e.getActiveMipmapLevel(),p=e.state;p.setBlending(0),p.buffers.depth.getReversed()===!0?p.buffers.color.setClear(0,0,0,0):p.buffers.color.setClear(1,1,1,1),p.buffers.depth.setTest(!0),p.setScissorTest(!1);let m=v!==3&&this.type===3,h=v===3&&this.type!==3;for(let l=0,u=t.length;l<u;l++){let u=t[l],f=u.shadow;if(f===void 0){console.warn(`THREE.WebGLShadowMap:`,u,`has no shadow.`);continue}if(f.autoUpdate===!1&&f.needsUpdate===!1)continue;a.copy(f.mapSize);let g=f.getFrameExtents();if(a.multiply(g),o.copy(f.mapSize),(a.x>d||a.y>d)&&(a.x>d&&(o.x=Math.floor(d/g.x),a.x=o.x*g.x,f.mapSize.x=o.x),a.y>d&&(o.y=Math.floor(d/g.y),a.y=o.y*g.y,f.mapSize.y=o.y)),f.map===null||m===!0||h===!0){let e=this.type===3?{}:{minFilter:r,magFilter:r};f.map!==null&&f.map.dispose(),f.map=new Ht(a.x,a.y,e),f.map.texture.name=u.name+`.shadowMap`,f.camera.updateProjectionMatrix()}e.setRenderTarget(f.map),e.clear();let _=f.getViewportCount();for(let e=0;e<_;e++){let t=f.getViewport(e);s.set(o.x*t.x,o.y*t.y,o.x*t.z,o.y*t.w),p.viewport(s),f.updateMatrices(u,e),i=f.getFrustum(),x(n,c,f.camera,u,this.type)}f.isPointLightShadow!==!0&&this.type===3&&y(f,c),f.needsUpdate=!1}v=this.type,_.needsUpdate=!1,e.setRenderTarget(l,u,f)};function y(n,r){let i=t.update(g);p.defines.VSM_SAMPLES!==n.blurSamples&&(p.defines.VSM_SAMPLES=n.blurSamples,m.defines.VSM_SAMPLES=n.blurSamples,p.needsUpdate=!0,m.needsUpdate=!0),n.mapPass===null&&(n.mapPass=new Ht(a.x,a.y)),p.uniforms.shadow_pass.value=n.map.texture,p.uniforms.resolution.value=n.mapSize,p.uniforms.radius.value=n.radius,e.setRenderTarget(n.mapPass),e.clear(),e.renderBufferDirect(r,null,i,p,g,null),m.uniforms.shadow_pass.value=n.mapPass.texture,m.uniforms.resolution.value=n.mapSize,m.uniforms.radius.value=n.radius,e.setRenderTarget(n.map),e.clear(),e.renderBufferDirect(r,null,i,m,g,null)}function b(t,n,r,i){let a=null,o=r.isPointLight===!0?t.customDistanceMaterial:t.customDepthMaterial;if(o!==void 0)a=o;else if(a=r.isPointLight===!0?l:c,e.localClippingEnabled&&n.clipShadows===!0&&Array.isArray(n.clippingPlanes)&&n.clippingPlanes.length!==0||n.displacementMap&&n.displacementScale!==0||n.alphaMap&&n.alphaTest>0||n.map&&n.alphaTest>0||n.alphaToCoverage===!0){let e=a.uuid,t=n.uuid,r=u[e];r===void 0&&(r={},u[e]=r);let i=r[t];i===void 0&&(i=a.clone(),r[t]=i,n.addEventListener(`dispose`,S)),a=i}if(a.visible=n.visible,a.wireframe=n.wireframe,i===3?a.side=n.shadowSide===null?n.side:n.shadowSide:a.side=n.shadowSide===null?f[n.side]:n.shadowSide,a.alphaMap=n.alphaMap,a.alphaTest=n.alphaToCoverage===!0?.5:n.alphaTest,a.map=n.map,a.clipShadows=n.clipShadows,a.clippingPlanes=n.clippingPlanes,a.clipIntersection=n.clipIntersection,a.displacementMap=n.displacementMap,a.displacementScale=n.displacementScale,a.displacementBias=n.displacementBias,a.wireframeLinewidth=n.wireframeLinewidth,a.linewidth=n.linewidth,r.isPointLight===!0&&a.isMeshDistanceMaterial===!0){let t=e.properties.get(a);t.light=r}return a}function x(n,r,a,o,s){if(n.visible===!1)return;if(n.layers.test(r.layers)&&(n.isMesh||n.isLine||n.isPoints)&&(n.castShadow||n.receiveShadow&&s===3)&&(!n.frustumCulled||i.intersectsObject(n))){n.modelViewMatrix.multiplyMatrices(a.matrixWorldInverse,n.matrixWorld);let i=t.update(n),c=n.material;if(Array.isArray(c)){let t=i.groups;for(let l=0,u=t.length;l<u;l++){let u=t[l],d=c[u.materialIndex];if(d&&d.visible){let t=b(n,d,o,s);n.onBeforeShadow(e,n,r,a,i,t,u),e.renderBufferDirect(a,null,i,t,n,u),n.onAfterShadow(e,n,r,a,i,t,u)}}}else if(c.visible){let t=b(n,c,o,s);n.onBeforeShadow(e,n,r,a,i,t,null),e.renderBufferDirect(a,null,i,t,n,null),n.onAfterShadow(e,n,r,a,i,t,null)}}let c=n.children;for(let e=0,t=c.length;e<t;e++)x(c[e],r,a,o,s)}function S(e){e.target.removeEventListener(`dispose`,S);for(let t in u){let n=u[t],r=e.target.uuid;r in n&&(n[r].dispose(),delete n[r])}}}var ll={0:1,2:6,4:7,3:5,1:0,6:2,7:4,5:3};function ul(e,t){function n(){let t=!1,n=new Bt,r=null,i=new Bt(0,0,0,0);return{setMask:function(n){r!==n&&!t&&(e.colorMask(n,n,n,n),r=n)},setLocked:function(e){t=e},setClear:function(t,r,a,o,s){s===!0&&(t*=o,r*=o,a*=o),n.set(t,r,a,o),i.equals(n)===!1&&(e.clearColor(t,r,a,o),i.copy(n))},reset:function(){t=!1,r=null,i.set(-1,0,0,0)}}}function r(){let n=!1,r=!1,i=null,a=null,o=null;return{setReversed:function(e){if(r!==e){let n=t.get(`EXT_clip_control`);e?n.clipControlEXT(n.LOWER_LEFT_EXT,n.ZERO_TO_ONE_EXT):n.clipControlEXT(n.LOWER_LEFT_EXT,n.NEGATIVE_ONE_TO_ONE_EXT),r=e;let i=o;o=null,this.setClear(i)}},getReversed:function(){return r},setTest:function(t){t?de(e.DEPTH_TEST):fe(e.DEPTH_TEST)},setMask:function(t){i!==t&&!n&&(e.depthMask(t),i=t)},setFunc:function(t){if(r&&(t=ll[t]),a!==t){switch(t){case 0:e.depthFunc(e.NEVER);break;case 1:e.depthFunc(e.ALWAYS);break;case 2:e.depthFunc(e.LESS);break;case 3:e.depthFunc(e.LEQUAL);break;case 4:e.depthFunc(e.EQUAL);break;case 5:e.depthFunc(e.GEQUAL);break;case 6:e.depthFunc(e.GREATER);break;case 7:e.depthFunc(e.NOTEQUAL);break;default:e.depthFunc(e.LEQUAL)}a=t}},setLocked:function(e){n=e},setClear:function(t){o!==t&&(r&&(t=1-t),e.clearDepth(t),o=t)},reset:function(){n=!1,i=null,a=null,o=null,r=!1}}}function i(){let t=!1,n=null,r=null,i=null,a=null,o=null,s=null,c=null,l=null;return{setTest:function(n){t||(n?de(e.STENCIL_TEST):fe(e.STENCIL_TEST))},setMask:function(r){n!==r&&!t&&(e.stencilMask(r),n=r)},setFunc:function(t,n,o){(r!==t||i!==n||a!==o)&&(e.stencilFunc(t,n,o),r=t,i=n,a=o)},setOp:function(t,n,r){(o!==t||s!==n||c!==r)&&(e.stencilOp(t,n,r),o=t,s=n,c=r)},setLocked:function(e){t=e},setClear:function(t){l!==t&&(e.clearStencil(t),l=t)},reset:function(){t=!1,n=null,r=null,i=null,a=null,o=null,s=null,c=null,l=null}}}let a=new n,o=new r,s=new i,c=new WeakMap,l=new WeakMap,u={},d={},f=new WeakMap,p=[],m=null,h=!1,g=null,_=null,v=null,y=null,b=null,x=null,S=null,C=new B(0,0,0),w=0,T=!1,E=null,D=null,ee=null,O=null,k=null,te=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),ne=!1,A=0,re=e.getParameter(e.VERSION);re.indexOf(`WebGL`)===-1?re.indexOf(`OpenGL ES`)!==-1&&(A=parseFloat(/^OpenGL ES (\d)/.exec(re)[1]),ne=A>=2):(A=parseFloat(/^WebGL (\d)/.exec(re)[1]),ne=A>=1);let ie=null,j={},ae=e.getParameter(e.SCISSOR_BOX),oe=e.getParameter(e.VIEWPORT),se=new Bt().fromArray(ae),ce=new Bt().fromArray(oe);function le(t,n,r,i){let a=new Uint8Array(4),o=e.createTexture();e.bindTexture(t,o),e.texParameteri(t,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(t,e.TEXTURE_MAG_FILTER,e.NEAREST);for(let o=0;o<r;o++)t===e.TEXTURE_3D||t===e.TEXTURE_2D_ARRAY?e.texImage3D(n,0,e.RGBA,1,1,i,0,e.RGBA,e.UNSIGNED_BYTE,a):e.texImage2D(n+o,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,a);return o}let ue={};ue[e.TEXTURE_2D]=le(e.TEXTURE_2D,e.TEXTURE_2D,1),ue[e.TEXTURE_CUBE_MAP]=le(e.TEXTURE_CUBE_MAP,e.TEXTURE_CUBE_MAP_POSITIVE_X,6),ue[e.TEXTURE_2D_ARRAY]=le(e.TEXTURE_2D_ARRAY,e.TEXTURE_2D_ARRAY,1,1),ue[e.TEXTURE_3D]=le(e.TEXTURE_3D,e.TEXTURE_3D,1,1),a.setClear(0,0,0,1),o.setClear(1),s.setClear(0),de(e.DEPTH_TEST),o.setFunc(3),ye(!1),be(1),de(e.CULL_FACE),ve(0);function de(t){u[t]!==!0&&(e.enable(t),u[t]=!0)}function fe(t){u[t]!==!1&&(e.disable(t),u[t]=!1)}function pe(t,n){return d[t]===n?!1:(e.bindFramebuffer(t,n),d[t]=n,t===e.DRAW_FRAMEBUFFER&&(d[e.FRAMEBUFFER]=n),t===e.FRAMEBUFFER&&(d[e.DRAW_FRAMEBUFFER]=n),!0)}function me(t,n){let r=p,i=!1;if(t){r=f.get(n),r===void 0&&(r=[],f.set(n,r));let a=t.textures;if(r.length!==a.length||r[0]!==e.COLOR_ATTACHMENT0){for(let t=0,n=a.length;t<n;t++)r[t]=e.COLOR_ATTACHMENT0+t;r.length=a.length,i=!0}}else r[0]!==e.BACK&&(r[0]=e.BACK,i=!0);i&&e.drawBuffers(r)}function he(t){return m===t?!1:(e.useProgram(t),m=t,!0)}let ge={100:e.FUNC_ADD,101:e.FUNC_SUBTRACT,102:e.FUNC_REVERSE_SUBTRACT};ge[103]=e.MIN,ge[104]=e.MAX;let _e={200:e.ZERO,201:e.ONE,202:e.SRC_COLOR,204:e.SRC_ALPHA,210:e.SRC_ALPHA_SATURATE,208:e.DST_COLOR,206:e.DST_ALPHA,203:e.ONE_MINUS_SRC_COLOR,205:e.ONE_MINUS_SRC_ALPHA,209:e.ONE_MINUS_DST_COLOR,207:e.ONE_MINUS_DST_ALPHA,211:e.CONSTANT_COLOR,212:e.ONE_MINUS_CONSTANT_COLOR,213:e.CONSTANT_ALPHA,214:e.ONE_MINUS_CONSTANT_ALPHA};function ve(t,n,r,i,a,o,s,c,l,u){if(t===0){h===!0&&(fe(e.BLEND),h=!1);return}if(h===!1&&(de(e.BLEND),h=!0),t!==5){if(t!==g||u!==T){if((_!==100||b!==100)&&(e.blendEquation(e.FUNC_ADD),_=100,b=100),u)switch(t){case 1:e.blendFuncSeparate(e.ONE,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case 2:e.blendFunc(e.ONE,e.ONE);break;case 3:e.blendFuncSeparate(e.ZERO,e.ONE_MINUS_SRC_COLOR,e.ZERO,e.ONE);break;case 4:e.blendFuncSeparate(e.DST_COLOR,e.ONE_MINUS_SRC_ALPHA,e.ZERO,e.ONE);break;default:console.error(`THREE.WebGLState: Invalid blending: `,t);break}else switch(t){case 1:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case 2:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE,e.ONE,e.ONE);break;case 3:console.error(`THREE.WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true`);break;case 4:console.error(`THREE.WebGLState: MultiplyBlending requires material.premultipliedAlpha = true`);break;default:console.error(`THREE.WebGLState: Invalid blending: `,t);break}v=null,y=null,x=null,S=null,C.set(0,0,0),w=0,g=t,T=u}return}a||=n,o||=r,s||=i,(n!==_||a!==b)&&(e.blendEquationSeparate(ge[n],ge[a]),_=n,b=a),(r!==v||i!==y||o!==x||s!==S)&&(e.blendFuncSeparate(_e[r],_e[i],_e[o],_e[s]),v=r,y=i,x=o,S=s),(c.equals(C)===!1||l!==w)&&(e.blendColor(c.r,c.g,c.b,l),C.copy(c),w=l),g=t,T=!1}function M(t,n){t.side===2?fe(e.CULL_FACE):de(e.CULL_FACE);let r=t.side===1;n&&(r=!r),ye(r),t.blending===1&&t.transparent===!1?ve(0):ve(t.blending,t.blendEquation,t.blendSrc,t.blendDst,t.blendEquationAlpha,t.blendSrcAlpha,t.blendDstAlpha,t.blendColor,t.blendAlpha,t.premultipliedAlpha),o.setFunc(t.depthFunc),o.setTest(t.depthTest),o.setMask(t.depthWrite),a.setMask(t.colorWrite);let i=t.stencilWrite;s.setTest(i),i&&(s.setMask(t.stencilWriteMask),s.setFunc(t.stencilFunc,t.stencilRef,t.stencilFuncMask),s.setOp(t.stencilFail,t.stencilZFail,t.stencilZPass)),N(t.polygonOffset,t.polygonOffsetFactor,t.polygonOffsetUnits),t.alphaToCoverage===!0?de(e.SAMPLE_ALPHA_TO_COVERAGE):fe(e.SAMPLE_ALPHA_TO_COVERAGE)}function ye(t){E!==t&&(t?e.frontFace(e.CW):e.frontFace(e.CCW),E=t)}function be(t){t===0?fe(e.CULL_FACE):(de(e.CULL_FACE),t!==D&&(t===1?e.cullFace(e.BACK):t===2?e.cullFace(e.FRONT):e.cullFace(e.FRONT_AND_BACK))),D=t}function xe(t){t!==ee&&(ne&&e.lineWidth(t),ee=t)}function N(t,n,r){t?(de(e.POLYGON_OFFSET_FILL),(O!==n||k!==r)&&(e.polygonOffset(n,r),O=n,k=r)):fe(e.POLYGON_OFFSET_FILL)}function Se(t){t?de(e.SCISSOR_TEST):fe(e.SCISSOR_TEST)}function P(t){t===void 0&&(t=e.TEXTURE0+te-1),ie!==t&&(e.activeTexture(t),ie=t)}function F(t,n,r){r===void 0&&(r=ie===null?e.TEXTURE0+te-1:ie);let i=j[r];i===void 0&&(i={type:void 0,texture:void 0},j[r]=i),(i.type!==t||i.texture!==n)&&(ie!==r&&(e.activeTexture(r),ie=r),e.bindTexture(t,n||ue[t]),i.type=t,i.texture=n)}function Ce(){let t=j[ie];t!==void 0&&t.type!==void 0&&(e.bindTexture(t.type,null),t.type=void 0,t.texture=void 0)}function we(){try{e.compressedTexImage2D(...arguments)}catch(e){console.error(`THREE.WebGLState:`,e)}}function Te(){try{e.compressedTexImage3D(...arguments)}catch(e){console.error(`THREE.WebGLState:`,e)}}function Ee(){try{e.texSubImage2D(...arguments)}catch(e){console.error(`THREE.WebGLState:`,e)}}function De(){try{e.texSubImage3D(...arguments)}catch(e){console.error(`THREE.WebGLState:`,e)}}function Oe(){try{e.compressedTexSubImage2D(...arguments)}catch(e){console.error(`THREE.WebGLState:`,e)}}function ke(){try{e.compressedTexSubImage3D(...arguments)}catch(e){console.error(`THREE.WebGLState:`,e)}}function Ae(){try{e.texStorage2D(...arguments)}catch(e){console.error(`THREE.WebGLState:`,e)}}function je(){try{e.texStorage3D(...arguments)}catch(e){console.error(`THREE.WebGLState:`,e)}}function Me(){try{e.texImage2D(...arguments)}catch(e){console.error(`THREE.WebGLState:`,e)}}function Ne(){try{e.texImage3D(...arguments)}catch(e){console.error(`THREE.WebGLState:`,e)}}function Pe(t){se.equals(t)===!1&&(e.scissor(t.x,t.y,t.z,t.w),se.copy(t))}function Fe(t){ce.equals(t)===!1&&(e.viewport(t.x,t.y,t.z,t.w),ce.copy(t))}function Ie(t,n){let r=l.get(n);r===void 0&&(r=new WeakMap,l.set(n,r));let i=r.get(t);i===void 0&&(i=e.getUniformBlockIndex(n,t.name),r.set(t,i))}function Le(t,n){let r=l.get(n).get(t);c.get(n)!==r&&(e.uniformBlockBinding(n,r,t.__bindingPointIndex),c.set(n,r))}function Re(){e.disable(e.BLEND),e.disable(e.CULL_FACE),e.disable(e.DEPTH_TEST),e.disable(e.POLYGON_OFFSET_FILL),e.disable(e.SCISSOR_TEST),e.disable(e.STENCIL_TEST),e.disable(e.SAMPLE_ALPHA_TO_COVERAGE),e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ZERO),e.blendFuncSeparate(e.ONE,e.ZERO,e.ONE,e.ZERO),e.blendColor(0,0,0,0),e.colorMask(!0,!0,!0,!0),e.clearColor(0,0,0,0),e.depthMask(!0),e.depthFunc(e.LESS),o.setReversed(!1),e.clearDepth(1),e.stencilMask(4294967295),e.stencilFunc(e.ALWAYS,0,4294967295),e.stencilOp(e.KEEP,e.KEEP,e.KEEP),e.clearStencil(0),e.cullFace(e.BACK),e.frontFace(e.CCW),e.polygonOffset(0,0),e.activeTexture(e.TEXTURE0),e.bindFramebuffer(e.FRAMEBUFFER,null),e.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),e.bindFramebuffer(e.READ_FRAMEBUFFER,null),e.useProgram(null),e.lineWidth(1),e.scissor(0,0,e.canvas.width,e.canvas.height),e.viewport(0,0,e.canvas.width,e.canvas.height),u={},ie=null,j={},d={},f=new WeakMap,p=[],m=null,h=!1,g=null,_=null,v=null,y=null,b=null,x=null,S=null,C=new B(0,0,0),w=0,T=!1,E=null,D=null,ee=null,O=null,k=null,se.set(0,0,e.canvas.width,e.canvas.height),ce.set(0,0,e.canvas.width,e.canvas.height),a.reset(),o.reset(),s.reset()}return{buffers:{color:a,depth:o,stencil:s},enable:de,disable:fe,bindFramebuffer:pe,drawBuffers:me,useProgram:he,setBlending:ve,setMaterial:M,setFlipSided:ye,setCullFace:be,setLineWidth:xe,setPolygonOffset:N,setScissorTest:Se,activeTexture:P,bindTexture:F,unbindTexture:Ce,compressedTexImage2D:we,compressedTexImage3D:Te,texImage2D:Me,texImage3D:Ne,updateUBOMapping:Ie,uniformBlockBinding:Le,texStorage2D:Ae,texStorage3D:je,texSubImage2D:Ee,texSubImage3D:De,compressedTexSubImage2D:Oe,compressedTexSubImage3D:ke,scissor:Pe,viewport:Fe,reset:Re}}function dl(l,u,d,f,p,m,h){let g=u.has(`WEBGL_multisampled_render_to_texture`)?u.get(`WEBGL_multisampled_render_to_texture`):null,_=typeof navigator>`u`?!1:/OculusBrowser/g.test(navigator.userAgent),v=new L,y=new WeakMap,b,x=new WeakMap,S=!1;try{S=typeof OffscreenCanvas<`u`&&new OffscreenCanvas(1,1).getContext(`2d`)!==null}catch{}function C(e,t){return S?new OffscreenCanvas(e,t):xt(`canvas`)}function w(e,t,n){let r=1,i=Me(e);if((i.width>n||i.height>n)&&(r=n/Math.max(i.width,i.height)),r<1)if(typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap||typeof VideoFrame<`u`&&e instanceof VideoFrame){let n=Math.floor(r*i.width),a=Math.floor(r*i.height);b===void 0&&(b=C(n,a));let o=t?C(n,a):b;return o.width=n,o.height=a,o.getContext(`2d`).drawImage(e,0,0,n,a),console.warn(`THREE.WebGLRenderer: Texture has been resized from (`+i.width+`x`+i.height+`) to (`+n+`x`+a+`).`),o}else return`data`in e&&console.warn(`THREE.WebGLRenderer: Image in DataTexture is too big (`+i.width+`x`+i.height+`).`),e;return e}function T(e){return e.generateMipmaps}function D(e){l.generateMipmap(e)}function ee(e){return e.isWebGLCubeRenderTarget?l.TEXTURE_CUBE_MAP:e.isWebGL3DRenderTarget?l.TEXTURE_3D:e.isWebGLArrayRenderTarget||e.isCompressedArrayTexture?l.TEXTURE_2D_ARRAY:l.TEXTURE_2D}function O(e,t,n,r,i=!1){if(e!==null){if(l[e]!==void 0)return l[e];console.warn(`THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '`+e+`'`)}let a=t;if(t===l.RED&&(n===l.FLOAT&&(a=l.R32F),n===l.HALF_FLOAT&&(a=l.R16F),n===l.UNSIGNED_BYTE&&(a=l.R8)),t===l.RED_INTEGER&&(n===l.UNSIGNED_BYTE&&(a=l.R8UI),n===l.UNSIGNED_SHORT&&(a=l.R16UI),n===l.UNSIGNED_INT&&(a=l.R32UI),n===l.BYTE&&(a=l.R8I),n===l.SHORT&&(a=l.R16I),n===l.INT&&(a=l.R32I)),t===l.RG&&(n===l.FLOAT&&(a=l.RG32F),n===l.HALF_FLOAT&&(a=l.RG16F),n===l.UNSIGNED_BYTE&&(a=l.RG8)),t===l.RG_INTEGER&&(n===l.UNSIGNED_BYTE&&(a=l.RG8UI),n===l.UNSIGNED_SHORT&&(a=l.RG16UI),n===l.UNSIGNED_INT&&(a=l.RG32UI),n===l.BYTE&&(a=l.RG8I),n===l.SHORT&&(a=l.RG16I),n===l.INT&&(a=l.RG32I)),t===l.RGB_INTEGER&&(n===l.UNSIGNED_BYTE&&(a=l.RGB8UI),n===l.UNSIGNED_SHORT&&(a=l.RGB16UI),n===l.UNSIGNED_INT&&(a=l.RGB32UI),n===l.BYTE&&(a=l.RGB8I),n===l.SHORT&&(a=l.RGB16I),n===l.INT&&(a=l.RGB32I)),t===l.RGBA_INTEGER&&(n===l.UNSIGNED_BYTE&&(a=l.RGBA8UI),n===l.UNSIGNED_SHORT&&(a=l.RGBA16UI),n===l.UNSIGNED_INT&&(a=l.RGBA32UI),n===l.BYTE&&(a=l.RGBA8I),n===l.SHORT&&(a=l.RGBA16I),n===l.INT&&(a=l.RGBA32I)),t===l.RGB&&(n===l.UNSIGNED_INT_5_9_9_9_REV&&(a=l.RGB9_E5),n===l.UNSIGNED_INT_10F_11F_11F_REV&&(a=l.R11F_G11F_B10F)),t===l.RGBA){let e=i?Re:kt.getTransfer(r);n===l.FLOAT&&(a=l.RGBA32F),n===l.HALF_FLOAT&&(a=l.RGBA16F),n===l.UNSIGNED_BYTE&&(a=e===`srgb`?l.SRGB8_ALPHA8:l.RGBA8),n===l.UNSIGNED_SHORT_4_4_4_4&&(a=l.RGBA4),n===l.UNSIGNED_SHORT_5_5_5_1&&(a=l.RGB5_A1)}return(a===l.R16F||a===l.R32F||a===l.RG16F||a===l.RG32F||a===l.RGBA16F||a===l.RGBA32F)&&u.get(`EXT_color_buffer_float`),a}function k(e,t){let n;return e?t===null||t===1014||t===1020?n=l.DEPTH24_STENCIL8:t===1015?n=l.DEPTH32F_STENCIL8:t===1012&&(n=l.DEPTH24_STENCIL8,console.warn(`DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.`)):t===null||t===1014||t===1020?n=l.DEPTH_COMPONENT24:t===1015?n=l.DEPTH_COMPONENT32F:t===1012&&(n=l.DEPTH_COMPONENT16),n}function te(e,t){return T(e)===!0||e.isFramebufferTexture&&e.minFilter!==1003&&e.minFilter!==1006?Math.log2(Math.max(t.width,t.height))+1:e.mipmaps!==void 0&&e.mipmaps.length>0?e.mipmaps.length:e.isCompressedTexture&&Array.isArray(e.image)?t.mipmaps.length:1}function ne(e){let t=e.target;t.removeEventListener(`dispose`,ne),re(t),t.isVideoTexture&&y.delete(t)}function A(e){let t=e.target;t.removeEventListener(`dispose`,A),j(t)}function re(e){let t=f.get(e);if(t.__webglInit===void 0)return;let n=e.source,r=x.get(n);if(r){let i=r[t.__cacheKey];i.usedTimes--,i.usedTimes===0&&ie(e),Object.keys(r).length===0&&x.delete(n)}f.remove(e)}function ie(e){let t=f.get(e);l.deleteTexture(t.__webglTexture);let n=e.source,r=x.get(n);delete r[t.__cacheKey],h.memory.textures--}function j(e){let t=f.get(e);if(e.depthTexture&&(e.depthTexture.dispose(),f.remove(e.depthTexture)),e.isWebGLCubeRenderTarget)for(let e=0;e<6;e++){if(Array.isArray(t.__webglFramebuffer[e]))for(let n=0;n<t.__webglFramebuffer[e].length;n++)l.deleteFramebuffer(t.__webglFramebuffer[e][n]);else l.deleteFramebuffer(t.__webglFramebuffer[e]);t.__webglDepthbuffer&&l.deleteRenderbuffer(t.__webglDepthbuffer[e])}else{if(Array.isArray(t.__webglFramebuffer))for(let e=0;e<t.__webglFramebuffer.length;e++)l.deleteFramebuffer(t.__webglFramebuffer[e]);else l.deleteFramebuffer(t.__webglFramebuffer);if(t.__webglDepthbuffer&&l.deleteRenderbuffer(t.__webglDepthbuffer),t.__webglMultisampledFramebuffer&&l.deleteFramebuffer(t.__webglMultisampledFramebuffer),t.__webglColorRenderbuffer)for(let e=0;e<t.__webglColorRenderbuffer.length;e++)t.__webglColorRenderbuffer[e]&&l.deleteRenderbuffer(t.__webglColorRenderbuffer[e]);t.__webglDepthRenderbuffer&&l.deleteRenderbuffer(t.__webglDepthRenderbuffer)}let n=e.textures;for(let e=0,t=n.length;e<t;e++){let t=f.get(n[e]);t.__webglTexture&&(l.deleteTexture(t.__webglTexture),h.memory.textures--),f.remove(n[e])}f.remove(e)}let ae=0;function oe(){ae=0}function se(){let e=ae;return e>=p.maxTextures&&console.warn(`THREE.WebGLTextures: Trying to use `+e+` texture units while this GPU supports only `+p.maxTextures),ae+=1,e}function ce(e){let t=[];return t.push(e.wrapS),t.push(e.wrapT),t.push(e.wrapR||0),t.push(e.magFilter),t.push(e.minFilter),t.push(e.anisotropy),t.push(e.internalFormat),t.push(e.format),t.push(e.type),t.push(e.generateMipmaps),t.push(e.premultiplyAlpha),t.push(e.flipY),t.push(e.unpackAlignment),t.push(e.colorSpace),t.join()}function le(e,t){let n=f.get(e);if(e.isVideoTexture&&Ae(e),e.isRenderTargetTexture===!1&&e.isExternalTexture!==!0&&e.version>0&&n.__version!==e.version){let r=e.image;if(r===null)console.warn(`THREE.WebGLRenderer: Texture marked for update but no image data found.`);else if(r.complete===!1)console.warn(`THREE.WebGLRenderer: Texture marked for update but image is incomplete`);else{ye(n,e,t);return}}else e.isExternalTexture&&(n.__webglTexture=e.sourceTexture?e.sourceTexture:null);d.bindTexture(l.TEXTURE_2D,n.__webglTexture,l.TEXTURE0+t)}function ue(e,t){let n=f.get(e);if(e.isRenderTargetTexture===!1&&e.version>0&&n.__version!==e.version){ye(n,e,t);return}d.bindTexture(l.TEXTURE_2D_ARRAY,n.__webglTexture,l.TEXTURE0+t)}function de(e,t){let n=f.get(e);if(e.isRenderTargetTexture===!1&&e.version>0&&n.__version!==e.version){ye(n,e,t);return}d.bindTexture(l.TEXTURE_3D,n.__webglTexture,l.TEXTURE0+t)}function fe(e,t){let n=f.get(e);if(e.version>0&&n.__version!==e.version){be(n,e,t);return}d.bindTexture(l.TEXTURE_CUBE_MAP,n.__webglTexture,l.TEXTURE0+t)}let pe={[e]:l.REPEAT,[t]:l.CLAMP_TO_EDGE,[n]:l.MIRRORED_REPEAT},me={[r]:l.NEAREST,[i]:l.NEAREST_MIPMAP_NEAREST,[a]:l.NEAREST_MIPMAP_LINEAR,[o]:l.LINEAR,[s]:l.LINEAR_MIPMAP_NEAREST,[c]:l.LINEAR_MIPMAP_LINEAR},he={512:l.NEVER,519:l.ALWAYS,513:l.LESS,515:l.LEQUAL,514:l.EQUAL,518:l.GEQUAL,516:l.GREATER,517:l.NOTEQUAL};function ge(e,t){if(t.type===1015&&u.has(`OES_texture_float_linear`)===!1&&(t.magFilter===1006||t.magFilter===1007||t.magFilter===1005||t.magFilter===1008||t.minFilter===1006||t.minFilter===1007||t.minFilter===1005||t.minFilter===1008)&&console.warn(`THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.`),l.texParameteri(e,l.TEXTURE_WRAP_S,pe[t.wrapS]),l.texParameteri(e,l.TEXTURE_WRAP_T,pe[t.wrapT]),(e===l.TEXTURE_3D||e===l.TEXTURE_2D_ARRAY)&&l.texParameteri(e,l.TEXTURE_WRAP_R,pe[t.wrapR]),l.texParameteri(e,l.TEXTURE_MAG_FILTER,me[t.magFilter]),l.texParameteri(e,l.TEXTURE_MIN_FILTER,me[t.minFilter]),t.compareFunction&&(l.texParameteri(e,l.TEXTURE_COMPARE_MODE,l.COMPARE_REF_TO_TEXTURE),l.texParameteri(e,l.TEXTURE_COMPARE_FUNC,he[t.compareFunction])),u.has(`EXT_texture_filter_anisotropic`)===!0){if(t.magFilter===1003||t.minFilter!==1005&&t.minFilter!==1008||t.type===1015&&u.has(`OES_texture_float_linear`)===!1)return;if(t.anisotropy>1||f.get(t).__currentAnisotropy){let n=u.get(`EXT_texture_filter_anisotropic`);l.texParameterf(e,n.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(t.anisotropy,p.getMaxAnisotropy())),f.get(t).__currentAnisotropy=t.anisotropy}}}function _e(e,t){let n=!1;e.__webglInit===void 0&&(e.__webglInit=!0,t.addEventListener(`dispose`,ne));let r=t.source,i=x.get(r);i===void 0&&(i={},x.set(r,i));let a=ce(t);if(a!==e.__cacheKey){i[a]===void 0&&(i[a]={texture:l.createTexture(),usedTimes:0},h.memory.textures++,n=!0),i[a].usedTimes++;let r=i[e.__cacheKey];r!==void 0&&(i[e.__cacheKey].usedTimes--,r.usedTimes===0&&ie(t)),e.__cacheKey=a,e.__webglTexture=i[a].texture}return n}function ve(e,t,n){return Math.floor(Math.floor(e/n)/t)}function M(e,t,n,r){let i=e.updateRanges;if(i.length===0)d.texSubImage2D(l.TEXTURE_2D,0,0,0,t.width,t.height,n,r,t.data);else{i.sort((e,t)=>e.start-t.start);let a=0;for(let e=1;e<i.length;e++){let n=i[a],r=i[e],o=n.start+n.count,s=ve(r.start,t.width,4),c=ve(n.start,t.width,4);r.start<=o+1&&s===c&&ve(r.start+r.count-1,t.width,4)===s?n.count=Math.max(n.count,r.start+r.count-n.start):(++a,i[a]=r)}i.length=a+1;let o=l.getParameter(l.UNPACK_ROW_LENGTH),s=l.getParameter(l.UNPACK_SKIP_PIXELS),c=l.getParameter(l.UNPACK_SKIP_ROWS);l.pixelStorei(l.UNPACK_ROW_LENGTH,t.width);for(let e=0,a=i.length;e<a;e++){let a=i[e],o=Math.floor(a.start/4),s=Math.ceil(a.count/4),c=o%t.width,u=Math.floor(o/t.width),f=s;l.pixelStorei(l.UNPACK_SKIP_PIXELS,c),l.pixelStorei(l.UNPACK_SKIP_ROWS,u),d.texSubImage2D(l.TEXTURE_2D,0,c,u,f,1,n,r,t.data)}e.clearUpdateRanges(),l.pixelStorei(l.UNPACK_ROW_LENGTH,o),l.pixelStorei(l.UNPACK_SKIP_PIXELS,s),l.pixelStorei(l.UNPACK_SKIP_ROWS,c)}}function ye(e,t,n){let r=l.TEXTURE_2D;(t.isDataArrayTexture||t.isCompressedArrayTexture)&&(r=l.TEXTURE_2D_ARRAY),t.isData3DTexture&&(r=l.TEXTURE_3D);let i=_e(e,t),a=t.source;d.bindTexture(r,e.__webglTexture,l.TEXTURE0+n);let o=f.get(a);if(a.version!==o.__version||i===!0){d.activeTexture(l.TEXTURE0+n);let e=kt.getPrimaries(kt.workingColorSpace),s=t.colorSpace===``?null:kt.getPrimaries(t.colorSpace),c=t.colorSpace===``||e===s?l.NONE:l.BROWSER_DEFAULT_WEBGL;l.pixelStorei(l.UNPACK_FLIP_Y_WEBGL,t.flipY),l.pixelStorei(l.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),l.pixelStorei(l.UNPACK_ALIGNMENT,t.unpackAlignment),l.pixelStorei(l.UNPACK_COLORSPACE_CONVERSION_WEBGL,c);let u=w(t.image,!1,p.maxTextureSize);u=je(t,u);let f=m.convert(t.format,t.colorSpace),h=m.convert(t.type),g=O(t.internalFormat,f,h,t.colorSpace,t.isVideoTexture);ge(r,t);let _,v=t.mipmaps,y=t.isVideoTexture!==!0,b=o.__version===void 0||i===!0,x=a.dataReady,S=te(t,u);if(t.isDepthTexture)g=k(t.format===E,t.type),b&&(y?d.texStorage2D(l.TEXTURE_2D,1,g,u.width,u.height):d.texImage2D(l.TEXTURE_2D,0,g,u.width,u.height,0,f,h,null));else if(t.isDataTexture)if(v.length>0){y&&b&&d.texStorage2D(l.TEXTURE_2D,S,g,v[0].width,v[0].height);for(let e=0,t=v.length;e<t;e++)_=v[e],y?x&&d.texSubImage2D(l.TEXTURE_2D,e,0,0,_.width,_.height,f,h,_.data):d.texImage2D(l.TEXTURE_2D,e,g,_.width,_.height,0,f,h,_.data);t.generateMipmaps=!1}else y?(b&&d.texStorage2D(l.TEXTURE_2D,S,g,u.width,u.height),x&&M(t,u,f,h)):d.texImage2D(l.TEXTURE_2D,0,g,u.width,u.height,0,f,h,u.data);else if(t.isCompressedTexture)if(t.isCompressedArrayTexture){y&&b&&d.texStorage3D(l.TEXTURE_2D_ARRAY,S,g,v[0].width,v[0].height,u.depth);for(let e=0,n=v.length;e<n;e++)if(_=v[e],t.format!==1023)if(f!==null)if(y){if(x)if(t.layerUpdates.size>0){let n=vo(_.width,_.height,t.format,t.type);for(let r of t.layerUpdates){let t=_.data.subarray(r*n/_.data.BYTES_PER_ELEMENT,(r+1)*n/_.data.BYTES_PER_ELEMENT);d.compressedTexSubImage3D(l.TEXTURE_2D_ARRAY,e,0,0,r,_.width,_.height,1,f,t)}t.clearLayerUpdates()}else d.compressedTexSubImage3D(l.TEXTURE_2D_ARRAY,e,0,0,0,_.width,_.height,u.depth,f,_.data)}else d.compressedTexImage3D(l.TEXTURE_2D_ARRAY,e,g,_.width,_.height,u.depth,0,_.data,0,0);else console.warn(`THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()`);else y?x&&d.texSubImage3D(l.TEXTURE_2D_ARRAY,e,0,0,0,_.width,_.height,u.depth,f,h,_.data):d.texImage3D(l.TEXTURE_2D_ARRAY,e,g,_.width,_.height,u.depth,0,f,h,_.data)}else{y&&b&&d.texStorage2D(l.TEXTURE_2D,S,g,v[0].width,v[0].height);for(let e=0,n=v.length;e<n;e++)_=v[e],t.format===1023?y?x&&d.texSubImage2D(l.TEXTURE_2D,e,0,0,_.width,_.height,f,h,_.data):d.texImage2D(l.TEXTURE_2D,e,g,_.width,_.height,0,f,h,_.data):f===null?console.warn(`THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()`):y?x&&d.compressedTexSubImage2D(l.TEXTURE_2D,e,0,0,_.width,_.height,f,_.data):d.compressedTexImage2D(l.TEXTURE_2D,e,g,_.width,_.height,0,_.data)}else if(t.isDataArrayTexture)if(y){if(b&&d.texStorage3D(l.TEXTURE_2D_ARRAY,S,g,u.width,u.height,u.depth),x)if(t.layerUpdates.size>0){let e=vo(u.width,u.height,t.format,t.type);for(let n of t.layerUpdates){let t=u.data.subarray(n*e/u.data.BYTES_PER_ELEMENT,(n+1)*e/u.data.BYTES_PER_ELEMENT);d.texSubImage3D(l.TEXTURE_2D_ARRAY,0,0,0,n,u.width,u.height,1,f,h,t)}t.clearLayerUpdates()}else d.texSubImage3D(l.TEXTURE_2D_ARRAY,0,0,0,0,u.width,u.height,u.depth,f,h,u.data)}else d.texImage3D(l.TEXTURE_2D_ARRAY,0,g,u.width,u.height,u.depth,0,f,h,u.data);else if(t.isData3DTexture)y?(b&&d.texStorage3D(l.TEXTURE_3D,S,g,u.width,u.height,u.depth),x&&d.texSubImage3D(l.TEXTURE_3D,0,0,0,0,u.width,u.height,u.depth,f,h,u.data)):d.texImage3D(l.TEXTURE_3D,0,g,u.width,u.height,u.depth,0,f,h,u.data);else if(t.isFramebufferTexture){if(b)if(y)d.texStorage2D(l.TEXTURE_2D,S,g,u.width,u.height);else{let e=u.width,t=u.height;for(let n=0;n<S;n++)d.texImage2D(l.TEXTURE_2D,n,g,e,t,0,f,h,null),e>>=1,t>>=1}}else if(v.length>0){if(y&&b){let e=Me(v[0]);d.texStorage2D(l.TEXTURE_2D,S,g,e.width,e.height)}for(let e=0,t=v.length;e<t;e++)_=v[e],y?x&&d.texSubImage2D(l.TEXTURE_2D,e,0,0,f,h,_):d.texImage2D(l.TEXTURE_2D,e,g,f,h,_);t.generateMipmaps=!1}else if(y){if(b){let e=Me(u);d.texStorage2D(l.TEXTURE_2D,S,g,e.width,e.height)}x&&d.texSubImage2D(l.TEXTURE_2D,0,0,0,f,h,u)}else d.texImage2D(l.TEXTURE_2D,0,g,f,h,u);T(t)&&D(r),o.__version=a.version,t.onUpdate&&t.onUpdate(t)}e.__version=t.version}function be(e,t,n){if(t.image.length!==6)return;let r=_e(e,t),i=t.source;d.bindTexture(l.TEXTURE_CUBE_MAP,e.__webglTexture,l.TEXTURE0+n);let a=f.get(i);if(i.version!==a.__version||r===!0){d.activeTexture(l.TEXTURE0+n);let e=kt.getPrimaries(kt.workingColorSpace),o=t.colorSpace===``?null:kt.getPrimaries(t.colorSpace),s=t.colorSpace===``||e===o?l.NONE:l.BROWSER_DEFAULT_WEBGL;l.pixelStorei(l.UNPACK_FLIP_Y_WEBGL,t.flipY),l.pixelStorei(l.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),l.pixelStorei(l.UNPACK_ALIGNMENT,t.unpackAlignment),l.pixelStorei(l.UNPACK_COLORSPACE_CONVERSION_WEBGL,s);let c=t.isCompressedTexture||t.image[0].isCompressedTexture,u=t.image[0]&&t.image[0].isDataTexture,f=[];for(let e=0;e<6;e++)!c&&!u?f[e]=w(t.image[e],!0,p.maxCubemapSize):f[e]=u?t.image[e].image:t.image[e],f[e]=je(t,f[e]);let h=f[0],g=m.convert(t.format,t.colorSpace),_=m.convert(t.type),v=O(t.internalFormat,g,_,t.colorSpace),y=t.isVideoTexture!==!0,b=a.__version===void 0||r===!0,x=i.dataReady,S=te(t,h);ge(l.TEXTURE_CUBE_MAP,t);let C;if(c){y&&b&&d.texStorage2D(l.TEXTURE_CUBE_MAP,S,v,h.width,h.height);for(let e=0;e<6;e++){C=f[e].mipmaps;for(let n=0;n<C.length;n++){let r=C[n];t.format===1023?y?x&&d.texSubImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+e,n,0,0,r.width,r.height,g,_,r.data):d.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+e,n,v,r.width,r.height,0,g,_,r.data):g===null?console.warn(`THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()`):y?x&&d.compressedTexSubImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+e,n,0,0,r.width,r.height,g,r.data):d.compressedTexImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+e,n,v,r.width,r.height,0,r.data)}}}else{if(C=t.mipmaps,y&&b){C.length>0&&S++;let e=Me(f[0]);d.texStorage2D(l.TEXTURE_CUBE_MAP,S,v,e.width,e.height)}for(let e=0;e<6;e++)if(u){y?x&&d.texSubImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,0,0,f[e].width,f[e].height,g,_,f[e].data):d.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,v,f[e].width,f[e].height,0,g,_,f[e].data);for(let t=0;t<C.length;t++){let n=C[t].image[e].image;y?x&&d.texSubImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+e,t+1,0,0,n.width,n.height,g,_,n.data):d.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+e,t+1,v,n.width,n.height,0,g,_,n.data)}}else{y?x&&d.texSubImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,0,0,g,_,f[e]):d.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,v,g,_,f[e]);for(let t=0;t<C.length;t++){let n=C[t];y?x&&d.texSubImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+e,t+1,0,0,g,_,n.image[e]):d.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+e,t+1,v,g,_,n.image[e])}}}T(t)&&D(l.TEXTURE_CUBE_MAP),a.__version=i.version,t.onUpdate&&t.onUpdate(t)}e.__version=t.version}function xe(e,t,n,r,i,a){let o=m.convert(n.format,n.colorSpace),s=m.convert(n.type),c=O(n.internalFormat,o,s,n.colorSpace),u=f.get(t),p=f.get(n);if(p.__renderTarget=t,!u.__hasExternalTextures){let e=Math.max(1,t.width>>a),n=Math.max(1,t.height>>a);i===l.TEXTURE_3D||i===l.TEXTURE_2D_ARRAY?d.texImage3D(i,a,c,e,n,t.depth,0,o,s,null):d.texImage2D(i,a,c,e,n,0,o,s,null)}d.bindFramebuffer(l.FRAMEBUFFER,e),ke(t)?g.framebufferTexture2DMultisampleEXT(l.FRAMEBUFFER,r,i,p.__webglTexture,0,Oe(t)):(i===l.TEXTURE_2D||i>=l.TEXTURE_CUBE_MAP_POSITIVE_X&&i<=l.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&l.framebufferTexture2D(l.FRAMEBUFFER,r,i,p.__webglTexture,a),d.bindFramebuffer(l.FRAMEBUFFER,null)}function N(e,t,n){if(l.bindRenderbuffer(l.RENDERBUFFER,e),t.depthBuffer){let r=t.depthTexture,i=r&&r.isDepthTexture?r.type:null,a=k(t.stencilBuffer,i),o=t.stencilBuffer?l.DEPTH_STENCIL_ATTACHMENT:l.DEPTH_ATTACHMENT,s=Oe(t);ke(t)?g.renderbufferStorageMultisampleEXT(l.RENDERBUFFER,s,a,t.width,t.height):n?l.renderbufferStorageMultisample(l.RENDERBUFFER,s,a,t.width,t.height):l.renderbufferStorage(l.RENDERBUFFER,a,t.width,t.height),l.framebufferRenderbuffer(l.FRAMEBUFFER,o,l.RENDERBUFFER,e)}else{let e=t.textures;for(let r=0;r<e.length;r++){let i=e[r],a=m.convert(i.format,i.colorSpace),o=m.convert(i.type),s=O(i.internalFormat,a,o,i.colorSpace),c=Oe(t);n&&ke(t)===!1?l.renderbufferStorageMultisample(l.RENDERBUFFER,c,s,t.width,t.height):ke(t)?g.renderbufferStorageMultisampleEXT(l.RENDERBUFFER,c,s,t.width,t.height):l.renderbufferStorage(l.RENDERBUFFER,s,t.width,t.height)}}l.bindRenderbuffer(l.RENDERBUFFER,null)}function Se(e,t){if(t&&t.isWebGLCubeRenderTarget)throw Error(`Depth Texture with cube render targets is not supported`);if(d.bindFramebuffer(l.FRAMEBUFFER,e),!(t.depthTexture&&t.depthTexture.isDepthTexture))throw Error(`renderTarget.depthTexture must be an instance of THREE.DepthTexture`);let n=f.get(t.depthTexture);n.__renderTarget=t,(!n.__webglTexture||t.depthTexture.image.width!==t.width||t.depthTexture.image.height!==t.height)&&(t.depthTexture.image.width=t.width,t.depthTexture.image.height=t.height,t.depthTexture.needsUpdate=!0),le(t.depthTexture,0);let r=n.__webglTexture,i=Oe(t);if(t.depthTexture.format===1026)ke(t)?g.framebufferTexture2DMultisampleEXT(l.FRAMEBUFFER,l.DEPTH_ATTACHMENT,l.TEXTURE_2D,r,0,i):l.framebufferTexture2D(l.FRAMEBUFFER,l.DEPTH_ATTACHMENT,l.TEXTURE_2D,r,0);else if(t.depthTexture.format===1027)ke(t)?g.framebufferTexture2DMultisampleEXT(l.FRAMEBUFFER,l.DEPTH_STENCIL_ATTACHMENT,l.TEXTURE_2D,r,0,i):l.framebufferTexture2D(l.FRAMEBUFFER,l.DEPTH_STENCIL_ATTACHMENT,l.TEXTURE_2D,r,0);else throw Error(`Unknown depthTexture format`)}function P(e){let t=f.get(e),n=e.isWebGLCubeRenderTarget===!0;if(t.__boundDepthTexture!==e.depthTexture){let n=e.depthTexture;if(t.__depthDisposeCallback&&t.__depthDisposeCallback(),n){let e=()=>{delete t.__boundDepthTexture,delete t.__depthDisposeCallback,n.removeEventListener(`dispose`,e)};n.addEventListener(`dispose`,e),t.__depthDisposeCallback=e}t.__boundDepthTexture=n}if(e.depthTexture&&!t.__autoAllocateDepthBuffer){if(n)throw Error(`target.depthTexture not supported in Cube render targets`);let r=e.texture.mipmaps;r&&r.length>0?Se(t.__webglFramebuffer[0],e):Se(t.__webglFramebuffer,e)}else if(n){t.__webglDepthbuffer=[];for(let n=0;n<6;n++)if(d.bindFramebuffer(l.FRAMEBUFFER,t.__webglFramebuffer[n]),t.__webglDepthbuffer[n]===void 0)t.__webglDepthbuffer[n]=l.createRenderbuffer(),N(t.__webglDepthbuffer[n],e,!1);else{let r=e.stencilBuffer?l.DEPTH_STENCIL_ATTACHMENT:l.DEPTH_ATTACHMENT,i=t.__webglDepthbuffer[n];l.bindRenderbuffer(l.RENDERBUFFER,i),l.framebufferRenderbuffer(l.FRAMEBUFFER,r,l.RENDERBUFFER,i)}}else{let n=e.texture.mipmaps;if(n&&n.length>0?d.bindFramebuffer(l.FRAMEBUFFER,t.__webglFramebuffer[0]):d.bindFramebuffer(l.FRAMEBUFFER,t.__webglFramebuffer),t.__webglDepthbuffer===void 0)t.__webglDepthbuffer=l.createRenderbuffer(),N(t.__webglDepthbuffer,e,!1);else{let n=e.stencilBuffer?l.DEPTH_STENCIL_ATTACHMENT:l.DEPTH_ATTACHMENT,r=t.__webglDepthbuffer;l.bindRenderbuffer(l.RENDERBUFFER,r),l.framebufferRenderbuffer(l.FRAMEBUFFER,n,l.RENDERBUFFER,r)}}d.bindFramebuffer(l.FRAMEBUFFER,null)}function F(e,t,n){let r=f.get(e);t!==void 0&&xe(r.__webglFramebuffer,e,e.texture,l.COLOR_ATTACHMENT0,l.TEXTURE_2D,0),n!==void 0&&P(e)}function Ce(e){let t=e.texture,n=f.get(e),r=f.get(t);e.addEventListener(`dispose`,A);let i=e.textures,a=e.isWebGLCubeRenderTarget===!0,o=i.length>1;if(o||(r.__webglTexture===void 0&&(r.__webglTexture=l.createTexture()),r.__version=t.version,h.memory.textures++),a){n.__webglFramebuffer=[];for(let e=0;e<6;e++)if(t.mipmaps&&t.mipmaps.length>0){n.__webglFramebuffer[e]=[];for(let r=0;r<t.mipmaps.length;r++)n.__webglFramebuffer[e][r]=l.createFramebuffer()}else n.__webglFramebuffer[e]=l.createFramebuffer()}else{if(t.mipmaps&&t.mipmaps.length>0){n.__webglFramebuffer=[];for(let e=0;e<t.mipmaps.length;e++)n.__webglFramebuffer[e]=l.createFramebuffer()}else n.__webglFramebuffer=l.createFramebuffer();if(o)for(let e=0,t=i.length;e<t;e++){let t=f.get(i[e]);t.__webglTexture===void 0&&(t.__webglTexture=l.createTexture(),h.memory.textures++)}if(e.samples>0&&ke(e)===!1){n.__webglMultisampledFramebuffer=l.createFramebuffer(),n.__webglColorRenderbuffer=[],d.bindFramebuffer(l.FRAMEBUFFER,n.__webglMultisampledFramebuffer);for(let t=0;t<i.length;t++){let r=i[t];n.__webglColorRenderbuffer[t]=l.createRenderbuffer(),l.bindRenderbuffer(l.RENDERBUFFER,n.__webglColorRenderbuffer[t]);let a=m.convert(r.format,r.colorSpace),o=m.convert(r.type),s=O(r.internalFormat,a,o,r.colorSpace,e.isXRRenderTarget===!0),c=Oe(e);l.renderbufferStorageMultisample(l.RENDERBUFFER,c,s,e.width,e.height),l.framebufferRenderbuffer(l.FRAMEBUFFER,l.COLOR_ATTACHMENT0+t,l.RENDERBUFFER,n.__webglColorRenderbuffer[t])}l.bindRenderbuffer(l.RENDERBUFFER,null),e.depthBuffer&&(n.__webglDepthRenderbuffer=l.createRenderbuffer(),N(n.__webglDepthRenderbuffer,e,!0)),d.bindFramebuffer(l.FRAMEBUFFER,null)}}if(a){d.bindTexture(l.TEXTURE_CUBE_MAP,r.__webglTexture),ge(l.TEXTURE_CUBE_MAP,t);for(let r=0;r<6;r++)if(t.mipmaps&&t.mipmaps.length>0)for(let i=0;i<t.mipmaps.length;i++)xe(n.__webglFramebuffer[r][i],e,t,l.COLOR_ATTACHMENT0,l.TEXTURE_CUBE_MAP_POSITIVE_X+r,i);else xe(n.__webglFramebuffer[r],e,t,l.COLOR_ATTACHMENT0,l.TEXTURE_CUBE_MAP_POSITIVE_X+r,0);T(t)&&D(l.TEXTURE_CUBE_MAP),d.unbindTexture()}else if(o){for(let t=0,r=i.length;t<r;t++){let r=i[t],a=f.get(r),o=l.TEXTURE_2D;(e.isWebGL3DRenderTarget||e.isWebGLArrayRenderTarget)&&(o=e.isWebGL3DRenderTarget?l.TEXTURE_3D:l.TEXTURE_2D_ARRAY),d.bindTexture(o,a.__webglTexture),ge(o,r),xe(n.__webglFramebuffer,e,r,l.COLOR_ATTACHMENT0+t,o,0),T(r)&&D(o)}d.unbindTexture()}else{let i=l.TEXTURE_2D;if((e.isWebGL3DRenderTarget||e.isWebGLArrayRenderTarget)&&(i=e.isWebGL3DRenderTarget?l.TEXTURE_3D:l.TEXTURE_2D_ARRAY),d.bindTexture(i,r.__webglTexture),ge(i,t),t.mipmaps&&t.mipmaps.length>0)for(let r=0;r<t.mipmaps.length;r++)xe(n.__webglFramebuffer[r],e,t,l.COLOR_ATTACHMENT0,i,r);else xe(n.__webglFramebuffer,e,t,l.COLOR_ATTACHMENT0,i,0);T(t)&&D(i),d.unbindTexture()}e.depthBuffer&&P(e)}function we(e){let t=e.textures;for(let n=0,r=t.length;n<r;n++){let r=t[n];if(T(r)){let t=ee(e),n=f.get(r).__webglTexture;d.bindTexture(t,n),D(t),d.unbindTexture()}}}let Te=[],Ee=[];function De(e){if(e.samples>0){if(ke(e)===!1){let t=e.textures,n=e.width,r=e.height,i=l.COLOR_BUFFER_BIT,a=e.stencilBuffer?l.DEPTH_STENCIL_ATTACHMENT:l.DEPTH_ATTACHMENT,o=f.get(e),s=t.length>1;if(s)for(let e=0;e<t.length;e++)d.bindFramebuffer(l.FRAMEBUFFER,o.__webglMultisampledFramebuffer),l.framebufferRenderbuffer(l.FRAMEBUFFER,l.COLOR_ATTACHMENT0+e,l.RENDERBUFFER,null),d.bindFramebuffer(l.FRAMEBUFFER,o.__webglFramebuffer),l.framebufferTexture2D(l.DRAW_FRAMEBUFFER,l.COLOR_ATTACHMENT0+e,l.TEXTURE_2D,null,0);d.bindFramebuffer(l.READ_FRAMEBUFFER,o.__webglMultisampledFramebuffer);let c=e.texture.mipmaps;c&&c.length>0?d.bindFramebuffer(l.DRAW_FRAMEBUFFER,o.__webglFramebuffer[0]):d.bindFramebuffer(l.DRAW_FRAMEBUFFER,o.__webglFramebuffer);for(let c=0;c<t.length;c++){if(e.resolveDepthBuffer&&(e.depthBuffer&&(i|=l.DEPTH_BUFFER_BIT),e.stencilBuffer&&e.resolveStencilBuffer&&(i|=l.STENCIL_BUFFER_BIT)),s){l.framebufferRenderbuffer(l.READ_FRAMEBUFFER,l.COLOR_ATTACHMENT0,l.RENDERBUFFER,o.__webglColorRenderbuffer[c]);let e=f.get(t[c]).__webglTexture;l.framebufferTexture2D(l.DRAW_FRAMEBUFFER,l.COLOR_ATTACHMENT0,l.TEXTURE_2D,e,0)}l.blitFramebuffer(0,0,n,r,0,0,n,r,i,l.NEAREST),_===!0&&(Te.length=0,Ee.length=0,Te.push(l.COLOR_ATTACHMENT0+c),e.depthBuffer&&e.resolveDepthBuffer===!1&&(Te.push(a),Ee.push(a),l.invalidateFramebuffer(l.DRAW_FRAMEBUFFER,Ee)),l.invalidateFramebuffer(l.READ_FRAMEBUFFER,Te))}if(d.bindFramebuffer(l.READ_FRAMEBUFFER,null),d.bindFramebuffer(l.DRAW_FRAMEBUFFER,null),s)for(let e=0;e<t.length;e++){d.bindFramebuffer(l.FRAMEBUFFER,o.__webglMultisampledFramebuffer),l.framebufferRenderbuffer(l.FRAMEBUFFER,l.COLOR_ATTACHMENT0+e,l.RENDERBUFFER,o.__webglColorRenderbuffer[e]);let n=f.get(t[e]).__webglTexture;d.bindFramebuffer(l.FRAMEBUFFER,o.__webglFramebuffer),l.framebufferTexture2D(l.DRAW_FRAMEBUFFER,l.COLOR_ATTACHMENT0+e,l.TEXTURE_2D,n,0)}d.bindFramebuffer(l.DRAW_FRAMEBUFFER,o.__webglMultisampledFramebuffer)}else if(e.depthBuffer&&e.resolveDepthBuffer===!1&&_){let t=e.stencilBuffer?l.DEPTH_STENCIL_ATTACHMENT:l.DEPTH_ATTACHMENT;l.invalidateFramebuffer(l.DRAW_FRAMEBUFFER,[t])}}}function Oe(e){return Math.min(p.maxSamples,e.samples)}function ke(e){let t=f.get(e);return e.samples>0&&u.has(`WEBGL_multisampled_render_to_texture`)===!0&&t.__useRenderToTexture!==!1}function Ae(e){let t=h.render.frame;y.get(e)!==t&&(y.set(e,t),e.update())}function je(e,t){let n=e.colorSpace,r=e.format,i=e.type;return e.isCompressedTexture===!0||e.isVideoTexture===!0||n!==`srgb-linear`&&n!==``&&(kt.getTransfer(n)===`srgb`?(r!==1023||i!==1009)&&console.warn(`THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.`):console.error(`THREE.WebGLTextures: Unsupported texture color space:`,n)),t}function Me(e){return typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement?(v.width=e.naturalWidth||e.width,v.height=e.naturalHeight||e.height):typeof VideoFrame<`u`&&e instanceof VideoFrame?(v.width=e.displayWidth,v.height=e.displayHeight):(v.width=e.width,v.height=e.height),v}this.allocateTextureUnit=se,this.resetTextureUnits=oe,this.setTexture2D=le,this.setTexture2DArray=ue,this.setTexture3D=de,this.setTextureCube=fe,this.rebindTextures=F,this.setupRenderTarget=Ce,this.updateRenderTargetMipmap=we,this.updateMultisampleRenderTarget=De,this.setupDepthRenderbuffer=P,this.setupFrameBufferTexture=xe,this.useMultisampledRTT=ke}function fl(e,t){function n(n,r=``){let i,a=kt.getTransfer(r);if(n===1009)return e.UNSIGNED_BYTE;if(n===1017)return e.UNSIGNED_SHORT_4_4_4_4;if(n===1018)return e.UNSIGNED_SHORT_5_5_5_1;if(n===35902)return e.UNSIGNED_INT_5_9_9_9_REV;if(n===35899)return e.UNSIGNED_INT_10F_11F_11F_REV;if(n===1010)return e.BYTE;if(n===1011)return e.SHORT;if(n===1012)return e.UNSIGNED_SHORT;if(n===1013)return e.INT;if(n===1014)return e.UNSIGNED_INT;if(n===1015)return e.FLOAT;if(n===1016)return e.HALF_FLOAT;if(n===1021)return e.ALPHA;if(n===1022)return e.RGB;if(n===1023)return e.RGBA;if(n===1026)return e.DEPTH_COMPONENT;if(n===1027)return e.DEPTH_STENCIL;if(n===1028)return e.RED;if(n===1029)return e.RED_INTEGER;if(n===1030)return e.RG;if(n===1031)return e.RG_INTEGER;if(n===1033)return e.RGBA_INTEGER;if(n===33776||n===33777||n===33778||n===33779)if(a===`srgb`)if(i=t.get(`WEBGL_compressed_texture_s3tc_srgb`),i!==null){if(n===33776)return i.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(n===33777)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(n===33778)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(n===33779)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(i=t.get(`WEBGL_compressed_texture_s3tc`),i!==null){if(n===33776)return i.COMPRESSED_RGB_S3TC_DXT1_EXT;if(n===33777)return i.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(n===33778)return i.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(n===33779)return i.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(n===35840||n===35841||n===35842||n===35843)if(i=t.get(`WEBGL_compressed_texture_pvrtc`),i!==null){if(n===35840)return i.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(n===35841)return i.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(n===35842)return i.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(n===35843)return i.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(n===36196||n===37492||n===37496)if(i=t.get(`WEBGL_compressed_texture_etc`),i!==null){if(n===36196||n===37492)return a===`srgb`?i.COMPRESSED_SRGB8_ETC2:i.COMPRESSED_RGB8_ETC2;if(n===37496)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:i.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(n===37808||n===37809||n===37810||n===37811||n===37812||n===37813||n===37814||n===37815||n===37816||n===37817||n===37818||n===37819||n===37820||n===37821)if(i=t.get(`WEBGL_compressed_texture_astc`),i!==null){if(n===37808)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:i.COMPRESSED_RGBA_ASTC_4x4_KHR;if(n===37809)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:i.COMPRESSED_RGBA_ASTC_5x4_KHR;if(n===37810)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:i.COMPRESSED_RGBA_ASTC_5x5_KHR;if(n===37811)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:i.COMPRESSED_RGBA_ASTC_6x5_KHR;if(n===37812)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:i.COMPRESSED_RGBA_ASTC_6x6_KHR;if(n===37813)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:i.COMPRESSED_RGBA_ASTC_8x5_KHR;if(n===37814)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:i.COMPRESSED_RGBA_ASTC_8x6_KHR;if(n===37815)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:i.COMPRESSED_RGBA_ASTC_8x8_KHR;if(n===37816)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:i.COMPRESSED_RGBA_ASTC_10x5_KHR;if(n===37817)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:i.COMPRESSED_RGBA_ASTC_10x6_KHR;if(n===37818)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:i.COMPRESSED_RGBA_ASTC_10x8_KHR;if(n===37819)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:i.COMPRESSED_RGBA_ASTC_10x10_KHR;if(n===37820)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:i.COMPRESSED_RGBA_ASTC_12x10_KHR;if(n===37821)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:i.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(n===36492||n===36494||n===36495)if(i=t.get(`EXT_texture_compression_bptc`),i!==null){if(n===36492)return a===`srgb`?i.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:i.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(n===36494)return i.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(n===36495)return i.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(n===36283||n===36284||n===36285||n===36286)if(i=t.get(`EXT_texture_compression_rgtc`),i!==null){if(n===36283)return i.COMPRESSED_RED_RGTC1_EXT;if(n===36284)return i.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(n===36285)return i.COMPRESSED_RED_GREEN_RGTC2_EXT;if(n===36286)return i.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return n===1020?e.UNSIGNED_INT_24_8:e[n]===void 0?null:e[n]}return{convert:n}}var pl=`
3808
+ }`;function ml(e,t,n){let i=new Ii,a=new L,o=new L,s=new Bt,c=new ya({depthPacking:Fe}),l=new ba,u={},d=n.maxTextureSize,f={0:1,1:0,2:2},p=new Yr({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new L},radius:{value:4}},vertexShader:fl,fragmentShader:pl}),m=p.clone();m.defines.HORIZONTAL_PASS=1;let h=new H;h.setAttribute(`position`,new V(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));let g=new U(h,p),_=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=1;let v=this.type;this.render=function(t,n,c){if(_.enabled===!1||_.autoUpdate===!1&&_.needsUpdate===!1||t.length===0)return;let l=e.getRenderTarget(),u=e.getActiveCubeFace(),f=e.getActiveMipmapLevel(),p=e.state;p.setBlending(0),p.buffers.depth.getReversed()===!0?p.buffers.color.setClear(0,0,0,0):p.buffers.color.setClear(1,1,1,1),p.buffers.depth.setTest(!0),p.setScissorTest(!1);let m=v!==3&&this.type===3,h=v===3&&this.type!==3;for(let l=0,u=t.length;l<u;l++){let u=t[l],f=u.shadow;if(f===void 0){console.warn(`THREE.WebGLShadowMap:`,u,`has no shadow.`);continue}if(f.autoUpdate===!1&&f.needsUpdate===!1)continue;a.copy(f.mapSize);let g=f.getFrameExtents();if(a.multiply(g),o.copy(f.mapSize),(a.x>d||a.y>d)&&(a.x>d&&(o.x=Math.floor(d/g.x),a.x=o.x*g.x,f.mapSize.x=o.x),a.y>d&&(o.y=Math.floor(d/g.y),a.y=o.y*g.y,f.mapSize.y=o.y)),f.map===null||m===!0||h===!0){let e=this.type===3?{}:{minFilter:r,magFilter:r};f.map!==null&&f.map.dispose(),f.map=new Ht(a.x,a.y,e),f.map.texture.name=u.name+`.shadowMap`,f.camera.updateProjectionMatrix()}e.setRenderTarget(f.map),e.clear();let _=f.getViewportCount();for(let e=0;e<_;e++){let t=f.getViewport(e);s.set(o.x*t.x,o.y*t.y,o.x*t.z,o.y*t.w),p.viewport(s),f.updateMatrices(u,e),i=f.getFrustum(),x(n,c,f.camera,u,this.type)}f.isPointLightShadow!==!0&&this.type===3&&y(f,c),f.needsUpdate=!1}v=this.type,_.needsUpdate=!1,e.setRenderTarget(l,u,f)};function y(n,r){let i=t.update(g);p.defines.VSM_SAMPLES!==n.blurSamples&&(p.defines.VSM_SAMPLES=n.blurSamples,m.defines.VSM_SAMPLES=n.blurSamples,p.needsUpdate=!0,m.needsUpdate=!0),n.mapPass===null&&(n.mapPass=new Ht(a.x,a.y)),p.uniforms.shadow_pass.value=n.map.texture,p.uniforms.resolution.value=n.mapSize,p.uniforms.radius.value=n.radius,e.setRenderTarget(n.mapPass),e.clear(),e.renderBufferDirect(r,null,i,p,g,null),m.uniforms.shadow_pass.value=n.mapPass.texture,m.uniforms.resolution.value=n.mapSize,m.uniforms.radius.value=n.radius,e.setRenderTarget(n.map),e.clear(),e.renderBufferDirect(r,null,i,m,g,null)}function b(t,n,r,i){let a=null,o=r.isPointLight===!0?t.customDistanceMaterial:t.customDepthMaterial;if(o!==void 0)a=o;else if(a=r.isPointLight===!0?l:c,e.localClippingEnabled&&n.clipShadows===!0&&Array.isArray(n.clippingPlanes)&&n.clippingPlanes.length!==0||n.displacementMap&&n.displacementScale!==0||n.alphaMap&&n.alphaTest>0||n.map&&n.alphaTest>0||n.alphaToCoverage===!0){let e=a.uuid,t=n.uuid,r=u[e];r===void 0&&(r={},u[e]=r);let i=r[t];i===void 0&&(i=a.clone(),r[t]=i,n.addEventListener(`dispose`,S)),a=i}if(a.visible=n.visible,a.wireframe=n.wireframe,i===3?a.side=n.shadowSide===null?n.side:n.shadowSide:a.side=n.shadowSide===null?f[n.side]:n.shadowSide,a.alphaMap=n.alphaMap,a.alphaTest=n.alphaToCoverage===!0?.5:n.alphaTest,a.map=n.map,a.clipShadows=n.clipShadows,a.clippingPlanes=n.clippingPlanes,a.clipIntersection=n.clipIntersection,a.displacementMap=n.displacementMap,a.displacementScale=n.displacementScale,a.displacementBias=n.displacementBias,a.wireframeLinewidth=n.wireframeLinewidth,a.linewidth=n.linewidth,r.isPointLight===!0&&a.isMeshDistanceMaterial===!0){let t=e.properties.get(a);t.light=r}return a}function x(n,r,a,o,s){if(n.visible===!1)return;if(n.layers.test(r.layers)&&(n.isMesh||n.isLine||n.isPoints)&&(n.castShadow||n.receiveShadow&&s===3)&&(!n.frustumCulled||i.intersectsObject(n))){n.modelViewMatrix.multiplyMatrices(a.matrixWorldInverse,n.matrixWorld);let i=t.update(n),c=n.material;if(Array.isArray(c)){let t=i.groups;for(let l=0,u=t.length;l<u;l++){let u=t[l],d=c[u.materialIndex];if(d&&d.visible){let t=b(n,d,o,s);n.onBeforeShadow(e,n,r,a,i,t,u),e.renderBufferDirect(a,null,i,t,n,u),n.onAfterShadow(e,n,r,a,i,t,u)}}}else if(c.visible){let t=b(n,c,o,s);n.onBeforeShadow(e,n,r,a,i,t,null),e.renderBufferDirect(a,null,i,t,n,null),n.onAfterShadow(e,n,r,a,i,t,null)}}let c=n.children;for(let e=0,t=c.length;e<t;e++)x(c[e],r,a,o,s)}function S(e){e.target.removeEventListener(`dispose`,S);for(let t in u){let n=u[t],r=e.target.uuid;r in n&&(n[r].dispose(),delete n[r])}}}var hl={0:1,2:6,4:7,3:5,1:0,6:2,7:4,5:3};function gl(e,t){function n(){let t=!1,n=new Bt,r=null,i=new Bt(0,0,0,0);return{setMask:function(n){r!==n&&!t&&(e.colorMask(n,n,n,n),r=n)},setLocked:function(e){t=e},setClear:function(t,r,a,o,s){s===!0&&(t*=o,r*=o,a*=o),n.set(t,r,a,o),i.equals(n)===!1&&(e.clearColor(t,r,a,o),i.copy(n))},reset:function(){t=!1,r=null,i.set(-1,0,0,0)}}}function r(){let n=!1,r=!1,i=null,a=null,o=null;return{setReversed:function(e){if(r!==e){let n=t.get(`EXT_clip_control`);e?n.clipControlEXT(n.LOWER_LEFT_EXT,n.ZERO_TO_ONE_EXT):n.clipControlEXT(n.LOWER_LEFT_EXT,n.NEGATIVE_ONE_TO_ONE_EXT),r=e;let i=o;o=null,this.setClear(i)}},getReversed:function(){return r},setTest:function(t){t?de(e.DEPTH_TEST):fe(e.DEPTH_TEST)},setMask:function(t){i!==t&&!n&&(e.depthMask(t),i=t)},setFunc:function(t){if(r&&(t=hl[t]),a!==t){switch(t){case 0:e.depthFunc(e.NEVER);break;case 1:e.depthFunc(e.ALWAYS);break;case 2:e.depthFunc(e.LESS);break;case 3:e.depthFunc(e.LEQUAL);break;case 4:e.depthFunc(e.EQUAL);break;case 5:e.depthFunc(e.GEQUAL);break;case 6:e.depthFunc(e.GREATER);break;case 7:e.depthFunc(e.NOTEQUAL);break;default:e.depthFunc(e.LEQUAL)}a=t}},setLocked:function(e){n=e},setClear:function(t){o!==t&&(r&&(t=1-t),e.clearDepth(t),o=t)},reset:function(){n=!1,i=null,a=null,o=null,r=!1}}}function i(){let t=!1,n=null,r=null,i=null,a=null,o=null,s=null,c=null,l=null;return{setTest:function(n){t||(n?de(e.STENCIL_TEST):fe(e.STENCIL_TEST))},setMask:function(r){n!==r&&!t&&(e.stencilMask(r),n=r)},setFunc:function(t,n,o){(r!==t||i!==n||a!==o)&&(e.stencilFunc(t,n,o),r=t,i=n,a=o)},setOp:function(t,n,r){(o!==t||s!==n||c!==r)&&(e.stencilOp(t,n,r),o=t,s=n,c=r)},setLocked:function(e){t=e},setClear:function(t){l!==t&&(e.clearStencil(t),l=t)},reset:function(){t=!1,n=null,r=null,i=null,a=null,o=null,s=null,c=null,l=null}}}let a=new n,o=new r,s=new i,c=new WeakMap,l=new WeakMap,u={},d={},f=new WeakMap,p=[],m=null,h=!1,g=null,_=null,v=null,y=null,b=null,x=null,S=null,C=new B(0,0,0),w=0,T=!1,E=null,D=null,ee=null,O=null,k=null,te=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),ne=!1,A=0,re=e.getParameter(e.VERSION);re.indexOf(`WebGL`)===-1?re.indexOf(`OpenGL ES`)!==-1&&(A=parseFloat(/^OpenGL ES (\d)/.exec(re)[1]),ne=A>=2):(A=parseFloat(/^WebGL (\d)/.exec(re)[1]),ne=A>=1);let ie=null,j={},ae=e.getParameter(e.SCISSOR_BOX),oe=e.getParameter(e.VIEWPORT),se=new Bt().fromArray(ae),ce=new Bt().fromArray(oe);function le(t,n,r,i){let a=new Uint8Array(4),o=e.createTexture();e.bindTexture(t,o),e.texParameteri(t,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(t,e.TEXTURE_MAG_FILTER,e.NEAREST);for(let o=0;o<r;o++)t===e.TEXTURE_3D||t===e.TEXTURE_2D_ARRAY?e.texImage3D(n,0,e.RGBA,1,1,i,0,e.RGBA,e.UNSIGNED_BYTE,a):e.texImage2D(n+o,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,a);return o}let ue={};ue[e.TEXTURE_2D]=le(e.TEXTURE_2D,e.TEXTURE_2D,1),ue[e.TEXTURE_CUBE_MAP]=le(e.TEXTURE_CUBE_MAP,e.TEXTURE_CUBE_MAP_POSITIVE_X,6),ue[e.TEXTURE_2D_ARRAY]=le(e.TEXTURE_2D_ARRAY,e.TEXTURE_2D_ARRAY,1,1),ue[e.TEXTURE_3D]=le(e.TEXTURE_3D,e.TEXTURE_3D,1,1),a.setClear(0,0,0,1),o.setClear(1),s.setClear(0),de(e.DEPTH_TEST),o.setFunc(3),ye(!1),be(1),de(e.CULL_FACE),ve(0);function de(t){u[t]!==!0&&(e.enable(t),u[t]=!0)}function fe(t){u[t]!==!1&&(e.disable(t),u[t]=!1)}function pe(t,n){return d[t]===n?!1:(e.bindFramebuffer(t,n),d[t]=n,t===e.DRAW_FRAMEBUFFER&&(d[e.FRAMEBUFFER]=n),t===e.FRAMEBUFFER&&(d[e.DRAW_FRAMEBUFFER]=n),!0)}function me(t,n){let r=p,i=!1;if(t){r=f.get(n),r===void 0&&(r=[],f.set(n,r));let a=t.textures;if(r.length!==a.length||r[0]!==e.COLOR_ATTACHMENT0){for(let t=0,n=a.length;t<n;t++)r[t]=e.COLOR_ATTACHMENT0+t;r.length=a.length,i=!0}}else r[0]!==e.BACK&&(r[0]=e.BACK,i=!0);i&&e.drawBuffers(r)}function he(t){return m===t?!1:(e.useProgram(t),m=t,!0)}let ge={100:e.FUNC_ADD,101:e.FUNC_SUBTRACT,102:e.FUNC_REVERSE_SUBTRACT};ge[103]=e.MIN,ge[104]=e.MAX;let _e={200:e.ZERO,201:e.ONE,202:e.SRC_COLOR,204:e.SRC_ALPHA,210:e.SRC_ALPHA_SATURATE,208:e.DST_COLOR,206:e.DST_ALPHA,203:e.ONE_MINUS_SRC_COLOR,205:e.ONE_MINUS_SRC_ALPHA,209:e.ONE_MINUS_DST_COLOR,207:e.ONE_MINUS_DST_ALPHA,211:e.CONSTANT_COLOR,212:e.ONE_MINUS_CONSTANT_COLOR,213:e.CONSTANT_ALPHA,214:e.ONE_MINUS_CONSTANT_ALPHA};function ve(t,n,r,i,a,o,s,c,l,u){if(t===0){h===!0&&(fe(e.BLEND),h=!1);return}if(h===!1&&(de(e.BLEND),h=!0),t!==5){if(t!==g||u!==T){if((_!==100||b!==100)&&(e.blendEquation(e.FUNC_ADD),_=100,b=100),u)switch(t){case 1:e.blendFuncSeparate(e.ONE,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case 2:e.blendFunc(e.ONE,e.ONE);break;case 3:e.blendFuncSeparate(e.ZERO,e.ONE_MINUS_SRC_COLOR,e.ZERO,e.ONE);break;case 4:e.blendFuncSeparate(e.DST_COLOR,e.ONE_MINUS_SRC_ALPHA,e.ZERO,e.ONE);break;default:console.error(`THREE.WebGLState: Invalid blending: `,t);break}else switch(t){case 1:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case 2:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE,e.ONE,e.ONE);break;case 3:console.error(`THREE.WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true`);break;case 4:console.error(`THREE.WebGLState: MultiplyBlending requires material.premultipliedAlpha = true`);break;default:console.error(`THREE.WebGLState: Invalid blending: `,t);break}v=null,y=null,x=null,S=null,C.set(0,0,0),w=0,g=t,T=u}return}a||=n,o||=r,s||=i,(n!==_||a!==b)&&(e.blendEquationSeparate(ge[n],ge[a]),_=n,b=a),(r!==v||i!==y||o!==x||s!==S)&&(e.blendFuncSeparate(_e[r],_e[i],_e[o],_e[s]),v=r,y=i,x=o,S=s),(c.equals(C)===!1||l!==w)&&(e.blendColor(c.r,c.g,c.b,l),C.copy(c),w=l),g=t,T=!1}function M(t,n){t.side===2?fe(e.CULL_FACE):de(e.CULL_FACE);let r=t.side===1;n&&(r=!r),ye(r),t.blending===1&&t.transparent===!1?ve(0):ve(t.blending,t.blendEquation,t.blendSrc,t.blendDst,t.blendEquationAlpha,t.blendSrcAlpha,t.blendDstAlpha,t.blendColor,t.blendAlpha,t.premultipliedAlpha),o.setFunc(t.depthFunc),o.setTest(t.depthTest),o.setMask(t.depthWrite),a.setMask(t.colorWrite);let i=t.stencilWrite;s.setTest(i),i&&(s.setMask(t.stencilWriteMask),s.setFunc(t.stencilFunc,t.stencilRef,t.stencilFuncMask),s.setOp(t.stencilFail,t.stencilZFail,t.stencilZPass)),N(t.polygonOffset,t.polygonOffsetFactor,t.polygonOffsetUnits),t.alphaToCoverage===!0?de(e.SAMPLE_ALPHA_TO_COVERAGE):fe(e.SAMPLE_ALPHA_TO_COVERAGE)}function ye(t){E!==t&&(t?e.frontFace(e.CW):e.frontFace(e.CCW),E=t)}function be(t){t===0?fe(e.CULL_FACE):(de(e.CULL_FACE),t!==D&&(t===1?e.cullFace(e.BACK):t===2?e.cullFace(e.FRONT):e.cullFace(e.FRONT_AND_BACK))),D=t}function xe(t){t!==ee&&(ne&&e.lineWidth(t),ee=t)}function N(t,n,r){t?(de(e.POLYGON_OFFSET_FILL),(O!==n||k!==r)&&(e.polygonOffset(n,r),O=n,k=r)):fe(e.POLYGON_OFFSET_FILL)}function Se(t){t?de(e.SCISSOR_TEST):fe(e.SCISSOR_TEST)}function P(t){t===void 0&&(t=e.TEXTURE0+te-1),ie!==t&&(e.activeTexture(t),ie=t)}function F(t,n,r){r===void 0&&(r=ie===null?e.TEXTURE0+te-1:ie);let i=j[r];i===void 0&&(i={type:void 0,texture:void 0},j[r]=i),(i.type!==t||i.texture!==n)&&(ie!==r&&(e.activeTexture(r),ie=r),e.bindTexture(t,n||ue[t]),i.type=t,i.texture=n)}function Ce(){let t=j[ie];t!==void 0&&t.type!==void 0&&(e.bindTexture(t.type,null),t.type=void 0,t.texture=void 0)}function we(){try{e.compressedTexImage2D(...arguments)}catch(e){console.error(`THREE.WebGLState:`,e)}}function Te(){try{e.compressedTexImage3D(...arguments)}catch(e){console.error(`THREE.WebGLState:`,e)}}function Ee(){try{e.texSubImage2D(...arguments)}catch(e){console.error(`THREE.WebGLState:`,e)}}function De(){try{e.texSubImage3D(...arguments)}catch(e){console.error(`THREE.WebGLState:`,e)}}function Oe(){try{e.compressedTexSubImage2D(...arguments)}catch(e){console.error(`THREE.WebGLState:`,e)}}function ke(){try{e.compressedTexSubImage3D(...arguments)}catch(e){console.error(`THREE.WebGLState:`,e)}}function Ae(){try{e.texStorage2D(...arguments)}catch(e){console.error(`THREE.WebGLState:`,e)}}function je(){try{e.texStorage3D(...arguments)}catch(e){console.error(`THREE.WebGLState:`,e)}}function Me(){try{e.texImage2D(...arguments)}catch(e){console.error(`THREE.WebGLState:`,e)}}function Ne(){try{e.texImage3D(...arguments)}catch(e){console.error(`THREE.WebGLState:`,e)}}function Pe(t){se.equals(t)===!1&&(e.scissor(t.x,t.y,t.z,t.w),se.copy(t))}function Fe(t){ce.equals(t)===!1&&(e.viewport(t.x,t.y,t.z,t.w),ce.copy(t))}function Ie(t,n){let r=l.get(n);r===void 0&&(r=new WeakMap,l.set(n,r));let i=r.get(t);i===void 0&&(i=e.getUniformBlockIndex(n,t.name),r.set(t,i))}function Le(t,n){let r=l.get(n).get(t);c.get(n)!==r&&(e.uniformBlockBinding(n,r,t.__bindingPointIndex),c.set(n,r))}function Re(){e.disable(e.BLEND),e.disable(e.CULL_FACE),e.disable(e.DEPTH_TEST),e.disable(e.POLYGON_OFFSET_FILL),e.disable(e.SCISSOR_TEST),e.disable(e.STENCIL_TEST),e.disable(e.SAMPLE_ALPHA_TO_COVERAGE),e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ZERO),e.blendFuncSeparate(e.ONE,e.ZERO,e.ONE,e.ZERO),e.blendColor(0,0,0,0),e.colorMask(!0,!0,!0,!0),e.clearColor(0,0,0,0),e.depthMask(!0),e.depthFunc(e.LESS),o.setReversed(!1),e.clearDepth(1),e.stencilMask(4294967295),e.stencilFunc(e.ALWAYS,0,4294967295),e.stencilOp(e.KEEP,e.KEEP,e.KEEP),e.clearStencil(0),e.cullFace(e.BACK),e.frontFace(e.CCW),e.polygonOffset(0,0),e.activeTexture(e.TEXTURE0),e.bindFramebuffer(e.FRAMEBUFFER,null),e.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),e.bindFramebuffer(e.READ_FRAMEBUFFER,null),e.useProgram(null),e.lineWidth(1),e.scissor(0,0,e.canvas.width,e.canvas.height),e.viewport(0,0,e.canvas.width,e.canvas.height),u={},ie=null,j={},d={},f=new WeakMap,p=[],m=null,h=!1,g=null,_=null,v=null,y=null,b=null,x=null,S=null,C=new B(0,0,0),w=0,T=!1,E=null,D=null,ee=null,O=null,k=null,se.set(0,0,e.canvas.width,e.canvas.height),ce.set(0,0,e.canvas.width,e.canvas.height),a.reset(),o.reset(),s.reset()}return{buffers:{color:a,depth:o,stencil:s},enable:de,disable:fe,bindFramebuffer:pe,drawBuffers:me,useProgram:he,setBlending:ve,setMaterial:M,setFlipSided:ye,setCullFace:be,setLineWidth:xe,setPolygonOffset:N,setScissorTest:Se,activeTexture:P,bindTexture:F,unbindTexture:Ce,compressedTexImage2D:we,compressedTexImage3D:Te,texImage2D:Me,texImage3D:Ne,updateUBOMapping:Ie,uniformBlockBinding:Le,texStorage2D:Ae,texStorage3D:je,texSubImage2D:Ee,texSubImage3D:De,compressedTexSubImage2D:Oe,compressedTexSubImage3D:ke,scissor:Pe,viewport:Fe,reset:Re}}function _l(l,u,d,f,p,m,h){let g=u.has(`WEBGL_multisampled_render_to_texture`)?u.get(`WEBGL_multisampled_render_to_texture`):null,_=typeof navigator>`u`?!1:/OculusBrowser/g.test(navigator.userAgent),v=new L,y=new WeakMap,b,x=new WeakMap,S=!1;try{S=typeof OffscreenCanvas<`u`&&new OffscreenCanvas(1,1).getContext(`2d`)!==null}catch{}function C(e,t){return S?new OffscreenCanvas(e,t):xt(`canvas`)}function w(e,t,n){let r=1,i=Me(e);if((i.width>n||i.height>n)&&(r=n/Math.max(i.width,i.height)),r<1)if(typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap||typeof VideoFrame<`u`&&e instanceof VideoFrame){let n=Math.floor(r*i.width),a=Math.floor(r*i.height);b===void 0&&(b=C(n,a));let o=t?C(n,a):b;return o.width=n,o.height=a,o.getContext(`2d`).drawImage(e,0,0,n,a),console.warn(`THREE.WebGLRenderer: Texture has been resized from (`+i.width+`x`+i.height+`) to (`+n+`x`+a+`).`),o}else return`data`in e&&console.warn(`THREE.WebGLRenderer: Image in DataTexture is too big (`+i.width+`x`+i.height+`).`),e;return e}function T(e){return e.generateMipmaps}function D(e){l.generateMipmap(e)}function ee(e){return e.isWebGLCubeRenderTarget?l.TEXTURE_CUBE_MAP:e.isWebGL3DRenderTarget?l.TEXTURE_3D:e.isWebGLArrayRenderTarget||e.isCompressedArrayTexture?l.TEXTURE_2D_ARRAY:l.TEXTURE_2D}function O(e,t,n,r,i=!1){if(e!==null){if(l[e]!==void 0)return l[e];console.warn(`THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '`+e+`'`)}let a=t;if(t===l.RED&&(n===l.FLOAT&&(a=l.R32F),n===l.HALF_FLOAT&&(a=l.R16F),n===l.UNSIGNED_BYTE&&(a=l.R8)),t===l.RED_INTEGER&&(n===l.UNSIGNED_BYTE&&(a=l.R8UI),n===l.UNSIGNED_SHORT&&(a=l.R16UI),n===l.UNSIGNED_INT&&(a=l.R32UI),n===l.BYTE&&(a=l.R8I),n===l.SHORT&&(a=l.R16I),n===l.INT&&(a=l.R32I)),t===l.RG&&(n===l.FLOAT&&(a=l.RG32F),n===l.HALF_FLOAT&&(a=l.RG16F),n===l.UNSIGNED_BYTE&&(a=l.RG8)),t===l.RG_INTEGER&&(n===l.UNSIGNED_BYTE&&(a=l.RG8UI),n===l.UNSIGNED_SHORT&&(a=l.RG16UI),n===l.UNSIGNED_INT&&(a=l.RG32UI),n===l.BYTE&&(a=l.RG8I),n===l.SHORT&&(a=l.RG16I),n===l.INT&&(a=l.RG32I)),t===l.RGB_INTEGER&&(n===l.UNSIGNED_BYTE&&(a=l.RGB8UI),n===l.UNSIGNED_SHORT&&(a=l.RGB16UI),n===l.UNSIGNED_INT&&(a=l.RGB32UI),n===l.BYTE&&(a=l.RGB8I),n===l.SHORT&&(a=l.RGB16I),n===l.INT&&(a=l.RGB32I)),t===l.RGBA_INTEGER&&(n===l.UNSIGNED_BYTE&&(a=l.RGBA8UI),n===l.UNSIGNED_SHORT&&(a=l.RGBA16UI),n===l.UNSIGNED_INT&&(a=l.RGBA32UI),n===l.BYTE&&(a=l.RGBA8I),n===l.SHORT&&(a=l.RGBA16I),n===l.INT&&(a=l.RGBA32I)),t===l.RGB&&(n===l.UNSIGNED_INT_5_9_9_9_REV&&(a=l.RGB9_E5),n===l.UNSIGNED_INT_10F_11F_11F_REV&&(a=l.R11F_G11F_B10F)),t===l.RGBA){let e=i?Re:kt.getTransfer(r);n===l.FLOAT&&(a=l.RGBA32F),n===l.HALF_FLOAT&&(a=l.RGBA16F),n===l.UNSIGNED_BYTE&&(a=e===`srgb`?l.SRGB8_ALPHA8:l.RGBA8),n===l.UNSIGNED_SHORT_4_4_4_4&&(a=l.RGBA4),n===l.UNSIGNED_SHORT_5_5_5_1&&(a=l.RGB5_A1)}return(a===l.R16F||a===l.R32F||a===l.RG16F||a===l.RG32F||a===l.RGBA16F||a===l.RGBA32F)&&u.get(`EXT_color_buffer_float`),a}function k(e,t){let n;return e?t===null||t===1014||t===1020?n=l.DEPTH24_STENCIL8:t===1015?n=l.DEPTH32F_STENCIL8:t===1012&&(n=l.DEPTH24_STENCIL8,console.warn(`DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.`)):t===null||t===1014||t===1020?n=l.DEPTH_COMPONENT24:t===1015?n=l.DEPTH_COMPONENT32F:t===1012&&(n=l.DEPTH_COMPONENT16),n}function te(e,t){return T(e)===!0||e.isFramebufferTexture&&e.minFilter!==1003&&e.minFilter!==1006?Math.log2(Math.max(t.width,t.height))+1:e.mipmaps!==void 0&&e.mipmaps.length>0?e.mipmaps.length:e.isCompressedTexture&&Array.isArray(e.image)?t.mipmaps.length:1}function ne(e){let t=e.target;t.removeEventListener(`dispose`,ne),re(t),t.isVideoTexture&&y.delete(t)}function A(e){let t=e.target;t.removeEventListener(`dispose`,A),j(t)}function re(e){let t=f.get(e);if(t.__webglInit===void 0)return;let n=e.source,r=x.get(n);if(r){let i=r[t.__cacheKey];i.usedTimes--,i.usedTimes===0&&ie(e),Object.keys(r).length===0&&x.delete(n)}f.remove(e)}function ie(e){let t=f.get(e);l.deleteTexture(t.__webglTexture);let n=e.source,r=x.get(n);delete r[t.__cacheKey],h.memory.textures--}function j(e){let t=f.get(e);if(e.depthTexture&&(e.depthTexture.dispose(),f.remove(e.depthTexture)),e.isWebGLCubeRenderTarget)for(let e=0;e<6;e++){if(Array.isArray(t.__webglFramebuffer[e]))for(let n=0;n<t.__webglFramebuffer[e].length;n++)l.deleteFramebuffer(t.__webglFramebuffer[e][n]);else l.deleteFramebuffer(t.__webglFramebuffer[e]);t.__webglDepthbuffer&&l.deleteRenderbuffer(t.__webglDepthbuffer[e])}else{if(Array.isArray(t.__webglFramebuffer))for(let e=0;e<t.__webglFramebuffer.length;e++)l.deleteFramebuffer(t.__webglFramebuffer[e]);else l.deleteFramebuffer(t.__webglFramebuffer);if(t.__webglDepthbuffer&&l.deleteRenderbuffer(t.__webglDepthbuffer),t.__webglMultisampledFramebuffer&&l.deleteFramebuffer(t.__webglMultisampledFramebuffer),t.__webglColorRenderbuffer)for(let e=0;e<t.__webglColorRenderbuffer.length;e++)t.__webglColorRenderbuffer[e]&&l.deleteRenderbuffer(t.__webglColorRenderbuffer[e]);t.__webglDepthRenderbuffer&&l.deleteRenderbuffer(t.__webglDepthRenderbuffer)}let n=e.textures;for(let e=0,t=n.length;e<t;e++){let t=f.get(n[e]);t.__webglTexture&&(l.deleteTexture(t.__webglTexture),h.memory.textures--),f.remove(n[e])}f.remove(e)}let ae=0;function oe(){ae=0}function se(){let e=ae;return e>=p.maxTextures&&console.warn(`THREE.WebGLTextures: Trying to use `+e+` texture units while this GPU supports only `+p.maxTextures),ae+=1,e}function ce(e){let t=[];return t.push(e.wrapS),t.push(e.wrapT),t.push(e.wrapR||0),t.push(e.magFilter),t.push(e.minFilter),t.push(e.anisotropy),t.push(e.internalFormat),t.push(e.format),t.push(e.type),t.push(e.generateMipmaps),t.push(e.premultiplyAlpha),t.push(e.flipY),t.push(e.unpackAlignment),t.push(e.colorSpace),t.join()}function le(e,t){let n=f.get(e);if(e.isVideoTexture&&Ae(e),e.isRenderTargetTexture===!1&&e.isExternalTexture!==!0&&e.version>0&&n.__version!==e.version){let r=e.image;if(r===null)console.warn(`THREE.WebGLRenderer: Texture marked for update but no image data found.`);else if(r.complete===!1)console.warn(`THREE.WebGLRenderer: Texture marked for update but image is incomplete`);else{ye(n,e,t);return}}else e.isExternalTexture&&(n.__webglTexture=e.sourceTexture?e.sourceTexture:null);d.bindTexture(l.TEXTURE_2D,n.__webglTexture,l.TEXTURE0+t)}function ue(e,t){let n=f.get(e);if(e.isRenderTargetTexture===!1&&e.version>0&&n.__version!==e.version){ye(n,e,t);return}d.bindTexture(l.TEXTURE_2D_ARRAY,n.__webglTexture,l.TEXTURE0+t)}function de(e,t){let n=f.get(e);if(e.isRenderTargetTexture===!1&&e.version>0&&n.__version!==e.version){ye(n,e,t);return}d.bindTexture(l.TEXTURE_3D,n.__webglTexture,l.TEXTURE0+t)}function fe(e,t){let n=f.get(e);if(e.version>0&&n.__version!==e.version){be(n,e,t);return}d.bindTexture(l.TEXTURE_CUBE_MAP,n.__webglTexture,l.TEXTURE0+t)}let pe={[e]:l.REPEAT,[t]:l.CLAMP_TO_EDGE,[n]:l.MIRRORED_REPEAT},me={[r]:l.NEAREST,[i]:l.NEAREST_MIPMAP_NEAREST,[a]:l.NEAREST_MIPMAP_LINEAR,[o]:l.LINEAR,[s]:l.LINEAR_MIPMAP_NEAREST,[c]:l.LINEAR_MIPMAP_LINEAR},he={512:l.NEVER,519:l.ALWAYS,513:l.LESS,515:l.LEQUAL,514:l.EQUAL,518:l.GEQUAL,516:l.GREATER,517:l.NOTEQUAL};function ge(e,t){if(t.type===1015&&u.has(`OES_texture_float_linear`)===!1&&(t.magFilter===1006||t.magFilter===1007||t.magFilter===1005||t.magFilter===1008||t.minFilter===1006||t.minFilter===1007||t.minFilter===1005||t.minFilter===1008)&&console.warn(`THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.`),l.texParameteri(e,l.TEXTURE_WRAP_S,pe[t.wrapS]),l.texParameteri(e,l.TEXTURE_WRAP_T,pe[t.wrapT]),(e===l.TEXTURE_3D||e===l.TEXTURE_2D_ARRAY)&&l.texParameteri(e,l.TEXTURE_WRAP_R,pe[t.wrapR]),l.texParameteri(e,l.TEXTURE_MAG_FILTER,me[t.magFilter]),l.texParameteri(e,l.TEXTURE_MIN_FILTER,me[t.minFilter]),t.compareFunction&&(l.texParameteri(e,l.TEXTURE_COMPARE_MODE,l.COMPARE_REF_TO_TEXTURE),l.texParameteri(e,l.TEXTURE_COMPARE_FUNC,he[t.compareFunction])),u.has(`EXT_texture_filter_anisotropic`)===!0){if(t.magFilter===1003||t.minFilter!==1005&&t.minFilter!==1008||t.type===1015&&u.has(`OES_texture_float_linear`)===!1)return;if(t.anisotropy>1||f.get(t).__currentAnisotropy){let n=u.get(`EXT_texture_filter_anisotropic`);l.texParameterf(e,n.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(t.anisotropy,p.getMaxAnisotropy())),f.get(t).__currentAnisotropy=t.anisotropy}}}function _e(e,t){let n=!1;e.__webglInit===void 0&&(e.__webglInit=!0,t.addEventListener(`dispose`,ne));let r=t.source,i=x.get(r);i===void 0&&(i={},x.set(r,i));let a=ce(t);if(a!==e.__cacheKey){i[a]===void 0&&(i[a]={texture:l.createTexture(),usedTimes:0},h.memory.textures++,n=!0),i[a].usedTimes++;let r=i[e.__cacheKey];r!==void 0&&(i[e.__cacheKey].usedTimes--,r.usedTimes===0&&ie(t)),e.__cacheKey=a,e.__webglTexture=i[a].texture}return n}function ve(e,t,n){return Math.floor(Math.floor(e/n)/t)}function M(e,t,n,r){let i=e.updateRanges;if(i.length===0)d.texSubImage2D(l.TEXTURE_2D,0,0,0,t.width,t.height,n,r,t.data);else{i.sort((e,t)=>e.start-t.start);let a=0;for(let e=1;e<i.length;e++){let n=i[a],r=i[e],o=n.start+n.count,s=ve(r.start,t.width,4),c=ve(n.start,t.width,4);r.start<=o+1&&s===c&&ve(r.start+r.count-1,t.width,4)===s?n.count=Math.max(n.count,r.start+r.count-n.start):(++a,i[a]=r)}i.length=a+1;let o=l.getParameter(l.UNPACK_ROW_LENGTH),s=l.getParameter(l.UNPACK_SKIP_PIXELS),c=l.getParameter(l.UNPACK_SKIP_ROWS);l.pixelStorei(l.UNPACK_ROW_LENGTH,t.width);for(let e=0,a=i.length;e<a;e++){let a=i[e],o=Math.floor(a.start/4),s=Math.ceil(a.count/4),c=o%t.width,u=Math.floor(o/t.width),f=s;l.pixelStorei(l.UNPACK_SKIP_PIXELS,c),l.pixelStorei(l.UNPACK_SKIP_ROWS,u),d.texSubImage2D(l.TEXTURE_2D,0,c,u,f,1,n,r,t.data)}e.clearUpdateRanges(),l.pixelStorei(l.UNPACK_ROW_LENGTH,o),l.pixelStorei(l.UNPACK_SKIP_PIXELS,s),l.pixelStorei(l.UNPACK_SKIP_ROWS,c)}}function ye(e,t,n){let r=l.TEXTURE_2D;(t.isDataArrayTexture||t.isCompressedArrayTexture)&&(r=l.TEXTURE_2D_ARRAY),t.isData3DTexture&&(r=l.TEXTURE_3D);let i=_e(e,t),a=t.source;d.bindTexture(r,e.__webglTexture,l.TEXTURE0+n);let o=f.get(a);if(a.version!==o.__version||i===!0){d.activeTexture(l.TEXTURE0+n);let e=kt.getPrimaries(kt.workingColorSpace),s=t.colorSpace===``?null:kt.getPrimaries(t.colorSpace),c=t.colorSpace===``||e===s?l.NONE:l.BROWSER_DEFAULT_WEBGL;l.pixelStorei(l.UNPACK_FLIP_Y_WEBGL,t.flipY),l.pixelStorei(l.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),l.pixelStorei(l.UNPACK_ALIGNMENT,t.unpackAlignment),l.pixelStorei(l.UNPACK_COLORSPACE_CONVERSION_WEBGL,c);let u=w(t.image,!1,p.maxTextureSize);u=je(t,u);let f=m.convert(t.format,t.colorSpace),h=m.convert(t.type),g=O(t.internalFormat,f,h,t.colorSpace,t.isVideoTexture);ge(r,t);let _,v=t.mipmaps,y=t.isVideoTexture!==!0,b=o.__version===void 0||i===!0,x=a.dataReady,S=te(t,u);if(t.isDepthTexture)g=k(t.format===E,t.type),b&&(y?d.texStorage2D(l.TEXTURE_2D,1,g,u.width,u.height):d.texImage2D(l.TEXTURE_2D,0,g,u.width,u.height,0,f,h,null));else if(t.isDataTexture)if(v.length>0){y&&b&&d.texStorage2D(l.TEXTURE_2D,S,g,v[0].width,v[0].height);for(let e=0,t=v.length;e<t;e++)_=v[e],y?x&&d.texSubImage2D(l.TEXTURE_2D,e,0,0,_.width,_.height,f,h,_.data):d.texImage2D(l.TEXTURE_2D,e,g,_.width,_.height,0,f,h,_.data);t.generateMipmaps=!1}else y?(b&&d.texStorage2D(l.TEXTURE_2D,S,g,u.width,u.height),x&&M(t,u,f,h)):d.texImage2D(l.TEXTURE_2D,0,g,u.width,u.height,0,f,h,u.data);else if(t.isCompressedTexture)if(t.isCompressedArrayTexture){y&&b&&d.texStorage3D(l.TEXTURE_2D_ARRAY,S,g,v[0].width,v[0].height,u.depth);for(let e=0,n=v.length;e<n;e++)if(_=v[e],t.format!==1023)if(f!==null)if(y){if(x)if(t.layerUpdates.size>0){let n=wo(_.width,_.height,t.format,t.type);for(let r of t.layerUpdates){let t=_.data.subarray(r*n/_.data.BYTES_PER_ELEMENT,(r+1)*n/_.data.BYTES_PER_ELEMENT);d.compressedTexSubImage3D(l.TEXTURE_2D_ARRAY,e,0,0,r,_.width,_.height,1,f,t)}t.clearLayerUpdates()}else d.compressedTexSubImage3D(l.TEXTURE_2D_ARRAY,e,0,0,0,_.width,_.height,u.depth,f,_.data)}else d.compressedTexImage3D(l.TEXTURE_2D_ARRAY,e,g,_.width,_.height,u.depth,0,_.data,0,0);else console.warn(`THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()`);else y?x&&d.texSubImage3D(l.TEXTURE_2D_ARRAY,e,0,0,0,_.width,_.height,u.depth,f,h,_.data):d.texImage3D(l.TEXTURE_2D_ARRAY,e,g,_.width,_.height,u.depth,0,f,h,_.data)}else{y&&b&&d.texStorage2D(l.TEXTURE_2D,S,g,v[0].width,v[0].height);for(let e=0,n=v.length;e<n;e++)_=v[e],t.format===1023?y?x&&d.texSubImage2D(l.TEXTURE_2D,e,0,0,_.width,_.height,f,h,_.data):d.texImage2D(l.TEXTURE_2D,e,g,_.width,_.height,0,f,h,_.data):f===null?console.warn(`THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()`):y?x&&d.compressedTexSubImage2D(l.TEXTURE_2D,e,0,0,_.width,_.height,f,_.data):d.compressedTexImage2D(l.TEXTURE_2D,e,g,_.width,_.height,0,_.data)}else if(t.isDataArrayTexture)if(y){if(b&&d.texStorage3D(l.TEXTURE_2D_ARRAY,S,g,u.width,u.height,u.depth),x)if(t.layerUpdates.size>0){let e=wo(u.width,u.height,t.format,t.type);for(let n of t.layerUpdates){let t=u.data.subarray(n*e/u.data.BYTES_PER_ELEMENT,(n+1)*e/u.data.BYTES_PER_ELEMENT);d.texSubImage3D(l.TEXTURE_2D_ARRAY,0,0,0,n,u.width,u.height,1,f,h,t)}t.clearLayerUpdates()}else d.texSubImage3D(l.TEXTURE_2D_ARRAY,0,0,0,0,u.width,u.height,u.depth,f,h,u.data)}else d.texImage3D(l.TEXTURE_2D_ARRAY,0,g,u.width,u.height,u.depth,0,f,h,u.data);else if(t.isData3DTexture)y?(b&&d.texStorage3D(l.TEXTURE_3D,S,g,u.width,u.height,u.depth),x&&d.texSubImage3D(l.TEXTURE_3D,0,0,0,0,u.width,u.height,u.depth,f,h,u.data)):d.texImage3D(l.TEXTURE_3D,0,g,u.width,u.height,u.depth,0,f,h,u.data);else if(t.isFramebufferTexture){if(b)if(y)d.texStorage2D(l.TEXTURE_2D,S,g,u.width,u.height);else{let e=u.width,t=u.height;for(let n=0;n<S;n++)d.texImage2D(l.TEXTURE_2D,n,g,e,t,0,f,h,null),e>>=1,t>>=1}}else if(v.length>0){if(y&&b){let e=Me(v[0]);d.texStorage2D(l.TEXTURE_2D,S,g,e.width,e.height)}for(let e=0,t=v.length;e<t;e++)_=v[e],y?x&&d.texSubImage2D(l.TEXTURE_2D,e,0,0,f,h,_):d.texImage2D(l.TEXTURE_2D,e,g,f,h,_);t.generateMipmaps=!1}else if(y){if(b){let e=Me(u);d.texStorage2D(l.TEXTURE_2D,S,g,e.width,e.height)}x&&d.texSubImage2D(l.TEXTURE_2D,0,0,0,f,h,u)}else d.texImage2D(l.TEXTURE_2D,0,g,f,h,u);T(t)&&D(r),o.__version=a.version,t.onUpdate&&t.onUpdate(t)}e.__version=t.version}function be(e,t,n){if(t.image.length!==6)return;let r=_e(e,t),i=t.source;d.bindTexture(l.TEXTURE_CUBE_MAP,e.__webglTexture,l.TEXTURE0+n);let a=f.get(i);if(i.version!==a.__version||r===!0){d.activeTexture(l.TEXTURE0+n);let e=kt.getPrimaries(kt.workingColorSpace),o=t.colorSpace===``?null:kt.getPrimaries(t.colorSpace),s=t.colorSpace===``||e===o?l.NONE:l.BROWSER_DEFAULT_WEBGL;l.pixelStorei(l.UNPACK_FLIP_Y_WEBGL,t.flipY),l.pixelStorei(l.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),l.pixelStorei(l.UNPACK_ALIGNMENT,t.unpackAlignment),l.pixelStorei(l.UNPACK_COLORSPACE_CONVERSION_WEBGL,s);let c=t.isCompressedTexture||t.image[0].isCompressedTexture,u=t.image[0]&&t.image[0].isDataTexture,f=[];for(let e=0;e<6;e++)!c&&!u?f[e]=w(t.image[e],!0,p.maxCubemapSize):f[e]=u?t.image[e].image:t.image[e],f[e]=je(t,f[e]);let h=f[0],g=m.convert(t.format,t.colorSpace),_=m.convert(t.type),v=O(t.internalFormat,g,_,t.colorSpace),y=t.isVideoTexture!==!0,b=a.__version===void 0||r===!0,x=i.dataReady,S=te(t,h);ge(l.TEXTURE_CUBE_MAP,t);let C;if(c){y&&b&&d.texStorage2D(l.TEXTURE_CUBE_MAP,S,v,h.width,h.height);for(let e=0;e<6;e++){C=f[e].mipmaps;for(let n=0;n<C.length;n++){let r=C[n];t.format===1023?y?x&&d.texSubImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+e,n,0,0,r.width,r.height,g,_,r.data):d.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+e,n,v,r.width,r.height,0,g,_,r.data):g===null?console.warn(`THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()`):y?x&&d.compressedTexSubImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+e,n,0,0,r.width,r.height,g,r.data):d.compressedTexImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+e,n,v,r.width,r.height,0,r.data)}}}else{if(C=t.mipmaps,y&&b){C.length>0&&S++;let e=Me(f[0]);d.texStorage2D(l.TEXTURE_CUBE_MAP,S,v,e.width,e.height)}for(let e=0;e<6;e++)if(u){y?x&&d.texSubImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,0,0,f[e].width,f[e].height,g,_,f[e].data):d.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,v,f[e].width,f[e].height,0,g,_,f[e].data);for(let t=0;t<C.length;t++){let n=C[t].image[e].image;y?x&&d.texSubImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+e,t+1,0,0,n.width,n.height,g,_,n.data):d.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+e,t+1,v,n.width,n.height,0,g,_,n.data)}}else{y?x&&d.texSubImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,0,0,g,_,f[e]):d.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,v,g,_,f[e]);for(let t=0;t<C.length;t++){let n=C[t];y?x&&d.texSubImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+e,t+1,0,0,g,_,n.image[e]):d.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+e,t+1,v,g,_,n.image[e])}}}T(t)&&D(l.TEXTURE_CUBE_MAP),a.__version=i.version,t.onUpdate&&t.onUpdate(t)}e.__version=t.version}function xe(e,t,n,r,i,a){let o=m.convert(n.format,n.colorSpace),s=m.convert(n.type),c=O(n.internalFormat,o,s,n.colorSpace),u=f.get(t),p=f.get(n);if(p.__renderTarget=t,!u.__hasExternalTextures){let e=Math.max(1,t.width>>a),n=Math.max(1,t.height>>a);i===l.TEXTURE_3D||i===l.TEXTURE_2D_ARRAY?d.texImage3D(i,a,c,e,n,t.depth,0,o,s,null):d.texImage2D(i,a,c,e,n,0,o,s,null)}d.bindFramebuffer(l.FRAMEBUFFER,e),ke(t)?g.framebufferTexture2DMultisampleEXT(l.FRAMEBUFFER,r,i,p.__webglTexture,0,Oe(t)):(i===l.TEXTURE_2D||i>=l.TEXTURE_CUBE_MAP_POSITIVE_X&&i<=l.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&l.framebufferTexture2D(l.FRAMEBUFFER,r,i,p.__webglTexture,a),d.bindFramebuffer(l.FRAMEBUFFER,null)}function N(e,t,n){if(l.bindRenderbuffer(l.RENDERBUFFER,e),t.depthBuffer){let r=t.depthTexture,i=r&&r.isDepthTexture?r.type:null,a=k(t.stencilBuffer,i),o=t.stencilBuffer?l.DEPTH_STENCIL_ATTACHMENT:l.DEPTH_ATTACHMENT,s=Oe(t);ke(t)?g.renderbufferStorageMultisampleEXT(l.RENDERBUFFER,s,a,t.width,t.height):n?l.renderbufferStorageMultisample(l.RENDERBUFFER,s,a,t.width,t.height):l.renderbufferStorage(l.RENDERBUFFER,a,t.width,t.height),l.framebufferRenderbuffer(l.FRAMEBUFFER,o,l.RENDERBUFFER,e)}else{let e=t.textures;for(let r=0;r<e.length;r++){let i=e[r],a=m.convert(i.format,i.colorSpace),o=m.convert(i.type),s=O(i.internalFormat,a,o,i.colorSpace),c=Oe(t);n&&ke(t)===!1?l.renderbufferStorageMultisample(l.RENDERBUFFER,c,s,t.width,t.height):ke(t)?g.renderbufferStorageMultisampleEXT(l.RENDERBUFFER,c,s,t.width,t.height):l.renderbufferStorage(l.RENDERBUFFER,s,t.width,t.height)}}l.bindRenderbuffer(l.RENDERBUFFER,null)}function Se(e,t){if(t&&t.isWebGLCubeRenderTarget)throw Error(`Depth Texture with cube render targets is not supported`);if(d.bindFramebuffer(l.FRAMEBUFFER,e),!(t.depthTexture&&t.depthTexture.isDepthTexture))throw Error(`renderTarget.depthTexture must be an instance of THREE.DepthTexture`);let n=f.get(t.depthTexture);n.__renderTarget=t,(!n.__webglTexture||t.depthTexture.image.width!==t.width||t.depthTexture.image.height!==t.height)&&(t.depthTexture.image.width=t.width,t.depthTexture.image.height=t.height,t.depthTexture.needsUpdate=!0),le(t.depthTexture,0);let r=n.__webglTexture,i=Oe(t);if(t.depthTexture.format===1026)ke(t)?g.framebufferTexture2DMultisampleEXT(l.FRAMEBUFFER,l.DEPTH_ATTACHMENT,l.TEXTURE_2D,r,0,i):l.framebufferTexture2D(l.FRAMEBUFFER,l.DEPTH_ATTACHMENT,l.TEXTURE_2D,r,0);else if(t.depthTexture.format===1027)ke(t)?g.framebufferTexture2DMultisampleEXT(l.FRAMEBUFFER,l.DEPTH_STENCIL_ATTACHMENT,l.TEXTURE_2D,r,0,i):l.framebufferTexture2D(l.FRAMEBUFFER,l.DEPTH_STENCIL_ATTACHMENT,l.TEXTURE_2D,r,0);else throw Error(`Unknown depthTexture format`)}function P(e){let t=f.get(e),n=e.isWebGLCubeRenderTarget===!0;if(t.__boundDepthTexture!==e.depthTexture){let n=e.depthTexture;if(t.__depthDisposeCallback&&t.__depthDisposeCallback(),n){let e=()=>{delete t.__boundDepthTexture,delete t.__depthDisposeCallback,n.removeEventListener(`dispose`,e)};n.addEventListener(`dispose`,e),t.__depthDisposeCallback=e}t.__boundDepthTexture=n}if(e.depthTexture&&!t.__autoAllocateDepthBuffer){if(n)throw Error(`target.depthTexture not supported in Cube render targets`);let r=e.texture.mipmaps;r&&r.length>0?Se(t.__webglFramebuffer[0],e):Se(t.__webglFramebuffer,e)}else if(n){t.__webglDepthbuffer=[];for(let n=0;n<6;n++)if(d.bindFramebuffer(l.FRAMEBUFFER,t.__webglFramebuffer[n]),t.__webglDepthbuffer[n]===void 0)t.__webglDepthbuffer[n]=l.createRenderbuffer(),N(t.__webglDepthbuffer[n],e,!1);else{let r=e.stencilBuffer?l.DEPTH_STENCIL_ATTACHMENT:l.DEPTH_ATTACHMENT,i=t.__webglDepthbuffer[n];l.bindRenderbuffer(l.RENDERBUFFER,i),l.framebufferRenderbuffer(l.FRAMEBUFFER,r,l.RENDERBUFFER,i)}}else{let n=e.texture.mipmaps;if(n&&n.length>0?d.bindFramebuffer(l.FRAMEBUFFER,t.__webglFramebuffer[0]):d.bindFramebuffer(l.FRAMEBUFFER,t.__webglFramebuffer),t.__webglDepthbuffer===void 0)t.__webglDepthbuffer=l.createRenderbuffer(),N(t.__webglDepthbuffer,e,!1);else{let n=e.stencilBuffer?l.DEPTH_STENCIL_ATTACHMENT:l.DEPTH_ATTACHMENT,r=t.__webglDepthbuffer;l.bindRenderbuffer(l.RENDERBUFFER,r),l.framebufferRenderbuffer(l.FRAMEBUFFER,n,l.RENDERBUFFER,r)}}d.bindFramebuffer(l.FRAMEBUFFER,null)}function F(e,t,n){let r=f.get(e);t!==void 0&&xe(r.__webglFramebuffer,e,e.texture,l.COLOR_ATTACHMENT0,l.TEXTURE_2D,0),n!==void 0&&P(e)}function Ce(e){let t=e.texture,n=f.get(e),r=f.get(t);e.addEventListener(`dispose`,A);let i=e.textures,a=e.isWebGLCubeRenderTarget===!0,o=i.length>1;if(o||(r.__webglTexture===void 0&&(r.__webglTexture=l.createTexture()),r.__version=t.version,h.memory.textures++),a){n.__webglFramebuffer=[];for(let e=0;e<6;e++)if(t.mipmaps&&t.mipmaps.length>0){n.__webglFramebuffer[e]=[];for(let r=0;r<t.mipmaps.length;r++)n.__webglFramebuffer[e][r]=l.createFramebuffer()}else n.__webglFramebuffer[e]=l.createFramebuffer()}else{if(t.mipmaps&&t.mipmaps.length>0){n.__webglFramebuffer=[];for(let e=0;e<t.mipmaps.length;e++)n.__webglFramebuffer[e]=l.createFramebuffer()}else n.__webglFramebuffer=l.createFramebuffer();if(o)for(let e=0,t=i.length;e<t;e++){let t=f.get(i[e]);t.__webglTexture===void 0&&(t.__webglTexture=l.createTexture(),h.memory.textures++)}if(e.samples>0&&ke(e)===!1){n.__webglMultisampledFramebuffer=l.createFramebuffer(),n.__webglColorRenderbuffer=[],d.bindFramebuffer(l.FRAMEBUFFER,n.__webglMultisampledFramebuffer);for(let t=0;t<i.length;t++){let r=i[t];n.__webglColorRenderbuffer[t]=l.createRenderbuffer(),l.bindRenderbuffer(l.RENDERBUFFER,n.__webglColorRenderbuffer[t]);let a=m.convert(r.format,r.colorSpace),o=m.convert(r.type),s=O(r.internalFormat,a,o,r.colorSpace,e.isXRRenderTarget===!0),c=Oe(e);l.renderbufferStorageMultisample(l.RENDERBUFFER,c,s,e.width,e.height),l.framebufferRenderbuffer(l.FRAMEBUFFER,l.COLOR_ATTACHMENT0+t,l.RENDERBUFFER,n.__webglColorRenderbuffer[t])}l.bindRenderbuffer(l.RENDERBUFFER,null),e.depthBuffer&&(n.__webglDepthRenderbuffer=l.createRenderbuffer(),N(n.__webglDepthRenderbuffer,e,!0)),d.bindFramebuffer(l.FRAMEBUFFER,null)}}if(a){d.bindTexture(l.TEXTURE_CUBE_MAP,r.__webglTexture),ge(l.TEXTURE_CUBE_MAP,t);for(let r=0;r<6;r++)if(t.mipmaps&&t.mipmaps.length>0)for(let i=0;i<t.mipmaps.length;i++)xe(n.__webglFramebuffer[r][i],e,t,l.COLOR_ATTACHMENT0,l.TEXTURE_CUBE_MAP_POSITIVE_X+r,i);else xe(n.__webglFramebuffer[r],e,t,l.COLOR_ATTACHMENT0,l.TEXTURE_CUBE_MAP_POSITIVE_X+r,0);T(t)&&D(l.TEXTURE_CUBE_MAP),d.unbindTexture()}else if(o){for(let t=0,r=i.length;t<r;t++){let r=i[t],a=f.get(r),o=l.TEXTURE_2D;(e.isWebGL3DRenderTarget||e.isWebGLArrayRenderTarget)&&(o=e.isWebGL3DRenderTarget?l.TEXTURE_3D:l.TEXTURE_2D_ARRAY),d.bindTexture(o,a.__webglTexture),ge(o,r),xe(n.__webglFramebuffer,e,r,l.COLOR_ATTACHMENT0+t,o,0),T(r)&&D(o)}d.unbindTexture()}else{let i=l.TEXTURE_2D;if((e.isWebGL3DRenderTarget||e.isWebGLArrayRenderTarget)&&(i=e.isWebGL3DRenderTarget?l.TEXTURE_3D:l.TEXTURE_2D_ARRAY),d.bindTexture(i,r.__webglTexture),ge(i,t),t.mipmaps&&t.mipmaps.length>0)for(let r=0;r<t.mipmaps.length;r++)xe(n.__webglFramebuffer[r],e,t,l.COLOR_ATTACHMENT0,i,r);else xe(n.__webglFramebuffer,e,t,l.COLOR_ATTACHMENT0,i,0);T(t)&&D(i),d.unbindTexture()}e.depthBuffer&&P(e)}function we(e){let t=e.textures;for(let n=0,r=t.length;n<r;n++){let r=t[n];if(T(r)){let t=ee(e),n=f.get(r).__webglTexture;d.bindTexture(t,n),D(t),d.unbindTexture()}}}let Te=[],Ee=[];function De(e){if(e.samples>0){if(ke(e)===!1){let t=e.textures,n=e.width,r=e.height,i=l.COLOR_BUFFER_BIT,a=e.stencilBuffer?l.DEPTH_STENCIL_ATTACHMENT:l.DEPTH_ATTACHMENT,o=f.get(e),s=t.length>1;if(s)for(let e=0;e<t.length;e++)d.bindFramebuffer(l.FRAMEBUFFER,o.__webglMultisampledFramebuffer),l.framebufferRenderbuffer(l.FRAMEBUFFER,l.COLOR_ATTACHMENT0+e,l.RENDERBUFFER,null),d.bindFramebuffer(l.FRAMEBUFFER,o.__webglFramebuffer),l.framebufferTexture2D(l.DRAW_FRAMEBUFFER,l.COLOR_ATTACHMENT0+e,l.TEXTURE_2D,null,0);d.bindFramebuffer(l.READ_FRAMEBUFFER,o.__webglMultisampledFramebuffer);let c=e.texture.mipmaps;c&&c.length>0?d.bindFramebuffer(l.DRAW_FRAMEBUFFER,o.__webglFramebuffer[0]):d.bindFramebuffer(l.DRAW_FRAMEBUFFER,o.__webglFramebuffer);for(let c=0;c<t.length;c++){if(e.resolveDepthBuffer&&(e.depthBuffer&&(i|=l.DEPTH_BUFFER_BIT),e.stencilBuffer&&e.resolveStencilBuffer&&(i|=l.STENCIL_BUFFER_BIT)),s){l.framebufferRenderbuffer(l.READ_FRAMEBUFFER,l.COLOR_ATTACHMENT0,l.RENDERBUFFER,o.__webglColorRenderbuffer[c]);let e=f.get(t[c]).__webglTexture;l.framebufferTexture2D(l.DRAW_FRAMEBUFFER,l.COLOR_ATTACHMENT0,l.TEXTURE_2D,e,0)}l.blitFramebuffer(0,0,n,r,0,0,n,r,i,l.NEAREST),_===!0&&(Te.length=0,Ee.length=0,Te.push(l.COLOR_ATTACHMENT0+c),e.depthBuffer&&e.resolveDepthBuffer===!1&&(Te.push(a),Ee.push(a),l.invalidateFramebuffer(l.DRAW_FRAMEBUFFER,Ee)),l.invalidateFramebuffer(l.READ_FRAMEBUFFER,Te))}if(d.bindFramebuffer(l.READ_FRAMEBUFFER,null),d.bindFramebuffer(l.DRAW_FRAMEBUFFER,null),s)for(let e=0;e<t.length;e++){d.bindFramebuffer(l.FRAMEBUFFER,o.__webglMultisampledFramebuffer),l.framebufferRenderbuffer(l.FRAMEBUFFER,l.COLOR_ATTACHMENT0+e,l.RENDERBUFFER,o.__webglColorRenderbuffer[e]);let n=f.get(t[e]).__webglTexture;d.bindFramebuffer(l.FRAMEBUFFER,o.__webglFramebuffer),l.framebufferTexture2D(l.DRAW_FRAMEBUFFER,l.COLOR_ATTACHMENT0+e,l.TEXTURE_2D,n,0)}d.bindFramebuffer(l.DRAW_FRAMEBUFFER,o.__webglMultisampledFramebuffer)}else if(e.depthBuffer&&e.resolveDepthBuffer===!1&&_){let t=e.stencilBuffer?l.DEPTH_STENCIL_ATTACHMENT:l.DEPTH_ATTACHMENT;l.invalidateFramebuffer(l.DRAW_FRAMEBUFFER,[t])}}}function Oe(e){return Math.min(p.maxSamples,e.samples)}function ke(e){let t=f.get(e);return e.samples>0&&u.has(`WEBGL_multisampled_render_to_texture`)===!0&&t.__useRenderToTexture!==!1}function Ae(e){let t=h.render.frame;y.get(e)!==t&&(y.set(e,t),e.update())}function je(e,t){let n=e.colorSpace,r=e.format,i=e.type;return e.isCompressedTexture===!0||e.isVideoTexture===!0||n!==`srgb-linear`&&n!==``&&(kt.getTransfer(n)===`srgb`?(r!==1023||i!==1009)&&console.warn(`THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.`):console.error(`THREE.WebGLTextures: Unsupported texture color space:`,n)),t}function Me(e){return typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement?(v.width=e.naturalWidth||e.width,v.height=e.naturalHeight||e.height):typeof VideoFrame<`u`&&e instanceof VideoFrame?(v.width=e.displayWidth,v.height=e.displayHeight):(v.width=e.width,v.height=e.height),v}this.allocateTextureUnit=se,this.resetTextureUnits=oe,this.setTexture2D=le,this.setTexture2DArray=ue,this.setTexture3D=de,this.setTextureCube=fe,this.rebindTextures=F,this.setupRenderTarget=Ce,this.updateRenderTargetMipmap=we,this.updateMultisampleRenderTarget=De,this.setupDepthRenderbuffer=P,this.setupFrameBufferTexture=xe,this.useMultisampledRTT=ke}function vl(e,t){function n(n,r=``){let i,a=kt.getTransfer(r);if(n===1009)return e.UNSIGNED_BYTE;if(n===1017)return e.UNSIGNED_SHORT_4_4_4_4;if(n===1018)return e.UNSIGNED_SHORT_5_5_5_1;if(n===35902)return e.UNSIGNED_INT_5_9_9_9_REV;if(n===35899)return e.UNSIGNED_INT_10F_11F_11F_REV;if(n===1010)return e.BYTE;if(n===1011)return e.SHORT;if(n===1012)return e.UNSIGNED_SHORT;if(n===1013)return e.INT;if(n===1014)return e.UNSIGNED_INT;if(n===1015)return e.FLOAT;if(n===1016)return e.HALF_FLOAT;if(n===1021)return e.ALPHA;if(n===1022)return e.RGB;if(n===1023)return e.RGBA;if(n===1026)return e.DEPTH_COMPONENT;if(n===1027)return e.DEPTH_STENCIL;if(n===1028)return e.RED;if(n===1029)return e.RED_INTEGER;if(n===1030)return e.RG;if(n===1031)return e.RG_INTEGER;if(n===1033)return e.RGBA_INTEGER;if(n===33776||n===33777||n===33778||n===33779)if(a===`srgb`)if(i=t.get(`WEBGL_compressed_texture_s3tc_srgb`),i!==null){if(n===33776)return i.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(n===33777)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(n===33778)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(n===33779)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(i=t.get(`WEBGL_compressed_texture_s3tc`),i!==null){if(n===33776)return i.COMPRESSED_RGB_S3TC_DXT1_EXT;if(n===33777)return i.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(n===33778)return i.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(n===33779)return i.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(n===35840||n===35841||n===35842||n===35843)if(i=t.get(`WEBGL_compressed_texture_pvrtc`),i!==null){if(n===35840)return i.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(n===35841)return i.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(n===35842)return i.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(n===35843)return i.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(n===36196||n===37492||n===37496)if(i=t.get(`WEBGL_compressed_texture_etc`),i!==null){if(n===36196||n===37492)return a===`srgb`?i.COMPRESSED_SRGB8_ETC2:i.COMPRESSED_RGB8_ETC2;if(n===37496)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:i.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(n===37808||n===37809||n===37810||n===37811||n===37812||n===37813||n===37814||n===37815||n===37816||n===37817||n===37818||n===37819||n===37820||n===37821)if(i=t.get(`WEBGL_compressed_texture_astc`),i!==null){if(n===37808)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:i.COMPRESSED_RGBA_ASTC_4x4_KHR;if(n===37809)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:i.COMPRESSED_RGBA_ASTC_5x4_KHR;if(n===37810)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:i.COMPRESSED_RGBA_ASTC_5x5_KHR;if(n===37811)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:i.COMPRESSED_RGBA_ASTC_6x5_KHR;if(n===37812)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:i.COMPRESSED_RGBA_ASTC_6x6_KHR;if(n===37813)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:i.COMPRESSED_RGBA_ASTC_8x5_KHR;if(n===37814)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:i.COMPRESSED_RGBA_ASTC_8x6_KHR;if(n===37815)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:i.COMPRESSED_RGBA_ASTC_8x8_KHR;if(n===37816)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:i.COMPRESSED_RGBA_ASTC_10x5_KHR;if(n===37817)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:i.COMPRESSED_RGBA_ASTC_10x6_KHR;if(n===37818)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:i.COMPRESSED_RGBA_ASTC_10x8_KHR;if(n===37819)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:i.COMPRESSED_RGBA_ASTC_10x10_KHR;if(n===37820)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:i.COMPRESSED_RGBA_ASTC_12x10_KHR;if(n===37821)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:i.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(n===36492||n===36494||n===36495)if(i=t.get(`EXT_texture_compression_bptc`),i!==null){if(n===36492)return a===`srgb`?i.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:i.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(n===36494)return i.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(n===36495)return i.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(n===36283||n===36284||n===36285||n===36286)if(i=t.get(`EXT_texture_compression_rgtc`),i!==null){if(n===36283)return i.COMPRESSED_RED_RGTC1_EXT;if(n===36284)return i.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(n===36285)return i.COMPRESSED_RED_GREEN_RGTC2_EXT;if(n===36286)return i.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return n===1020?e.UNSIGNED_INT_24_8:e[n]===void 0?null:e[n]}return{convert:n}}var yl=`
3809
3809
  void main() {
3810
3810
 
3811
3811
  gl_Position = vec4( position, 1.0 );
3812
3812
 
3813
- }`,ml=`
3813
+ }`,bl=`
3814
3814
  uniform sampler2DArray depthColor;
3815
3815
  uniform float depthWidth;
3816
3816
  uniform float depthHeight;
@@ -3829,7 +3829,7 @@ void main() {
3829
3829
 
3830
3830
  }
3831
3831
 
3832
- }`,hl=class{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){let n=new $i(e.texture);(e.depthNear!==t.depthNear||e.depthFar!==t.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=n}}getMesh(e){if(this.texture!==null&&this.mesh===null){let t=e.cameras[0].viewport,n=new Xr({vertexShader:pl,fragmentShader:ml,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new H(new ca(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}},gl=class extends Ue{constructor(e,t){super();let n=this,r=null,i=1,a=null,o=`local-floor`,s=1,c=null,u=null,d=null,f=null,p=null,h=null,g=typeof XRWebGLBinding<`u`,_=new hl,v={},b=t.getContextAttributes(),x=null,S=null,C=[],D=[],ee=new L,O=null,k=new ti;k.viewport=new Bt;let te=new ti;te.viewport=new Bt;let ne=[k,te],A=new Ha,re=null,ie=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(e){let t=C[e];return t===void 0&&(t=new li,C[e]=t),t.getTargetRaySpace()},this.getControllerGrip=function(e){let t=C[e];return t===void 0&&(t=new li,C[e]=t),t.getGripSpace()},this.getHand=function(e){let t=C[e];return t===void 0&&(t=new li,C[e]=t),t.getHandSpace()};function j(e){let t=D.indexOf(e.inputSource);if(t===-1)return;let n=C[t];n!==void 0&&(n.update(e.inputSource,e.frame,c||a),n.dispatchEvent({type:e.type,data:e.inputSource}))}function ae(){r.removeEventListener(`select`,j),r.removeEventListener(`selectstart`,j),r.removeEventListener(`selectend`,j),r.removeEventListener(`squeeze`,j),r.removeEventListener(`squeezestart`,j),r.removeEventListener(`squeezeend`,j),r.removeEventListener(`end`,ae),r.removeEventListener(`inputsourceschange`,oe);for(let e=0;e<C.length;e++){let t=D[e];t!==null&&(D[e]=null,C[e].disconnect(t))}re=null,ie=null,_.reset();for(let e in v)delete v[e];e.setRenderTarget(x),p=null,f=null,d=null,r=null,S=null,me.stop(),n.isPresenting=!1,e.setPixelRatio(O),e.setSize(ee.width,ee.height,!1),n.dispatchEvent({type:`sessionend`})}this.setFramebufferScaleFactor=function(e){i=e,n.isPresenting===!0&&console.warn(`THREE.WebXRManager: Cannot change framebuffer scale while presenting.`)},this.setReferenceSpaceType=function(e){o=e,n.isPresenting===!0&&console.warn(`THREE.WebXRManager: Cannot change reference space type while presenting.`)},this.getReferenceSpace=function(){return c||a},this.setReferenceSpace=function(e){c=e},this.getBaseLayer=function(){return f===null?p:f},this.getBinding=function(){return d===null&&g&&(d=new XRWebGLBinding(r,t)),d},this.getFrame=function(){return h},this.getSession=function(){return r},this.setSession=async function(u){if(r=u,r!==null){if(x=e.getRenderTarget(),r.addEventListener(`select`,j),r.addEventListener(`selectstart`,j),r.addEventListener(`selectend`,j),r.addEventListener(`squeeze`,j),r.addEventListener(`squeezestart`,j),r.addEventListener(`squeezeend`,j),r.addEventListener(`end`,ae),r.addEventListener(`inputsourceschange`,oe),b.xrCompatible!==!0&&await t.makeXRCompatible(),O=e.getPixelRatio(),e.getSize(ee),g&&`createProjectionLayer`in XRWebGLBinding.prototype){let n=null,a=null,o=null;b.depth&&(o=b.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,n=b.stencil?E:T,a=b.stencil?y:m);let s={colorFormat:t.RGBA8,depthFormat:o,scaleFactor:i};d=this.getBinding(),f=d.createProjectionLayer(s),r.updateRenderState({layers:[f]}),e.setPixelRatio(1),e.setSize(f.textureWidth,f.textureHeight,!1),S=new Ht(f.textureWidth,f.textureHeight,{format:w,type:l,depthTexture:new Qi(f.textureWidth,f.textureHeight,a,void 0,void 0,void 0,void 0,void 0,void 0,n),stencilBuffer:b.stencil,colorSpace:e.outputColorSpace,samples:b.antialias?4:0,resolveDepthBuffer:f.ignoreDepthValues===!1,resolveStencilBuffer:f.ignoreDepthValues===!1})}else{let n={antialias:b.antialias,alpha:!0,depth:b.depth,stencil:b.stencil,framebufferScaleFactor:i};p=new XRWebGLLayer(r,t,n),r.updateRenderState({baseLayer:p}),e.setPixelRatio(1),e.setSize(p.framebufferWidth,p.framebufferHeight,!1),S=new Ht(p.framebufferWidth,p.framebufferHeight,{format:w,type:l,colorSpace:e.outputColorSpace,stencilBuffer:b.stencil,resolveDepthBuffer:p.ignoreDepthValues===!1,resolveStencilBuffer:p.ignoreDepthValues===!1})}S.isXRRenderTarget=!0,this.setFoveation(s),c=null,a=await r.requestReferenceSpace(o),me.setContext(r),me.start(),n.isPresenting=!0,n.dispatchEvent({type:`sessionstart`})}},this.getEnvironmentBlendMode=function(){if(r!==null)return r.environmentBlendMode},this.getDepthTexture=function(){return _.getDepthTexture()};function oe(e){for(let t=0;t<e.removed.length;t++){let n=e.removed[t],r=D.indexOf(n);r>=0&&(D[r]=null,C[r].disconnect(n))}for(let t=0;t<e.added.length;t++){let n=e.added[t],r=D.indexOf(n);if(r===-1){for(let e=0;e<C.length;e++)if(e>=D.length){D.push(n),r=e;break}else if(D[e]===null){D[e]=n,r=e;break}if(r===-1)break}let i=C[r];i&&i.connect(n)}}let se=new R,ce=new R;function le(e,t,n){se.setFromMatrixPosition(t.matrixWorld),ce.setFromMatrixPosition(n.matrixWorld);let r=se.distanceTo(ce),i=t.projectionMatrix.elements,a=n.projectionMatrix.elements,o=i[14]/(i[10]-1),s=i[14]/(i[10]+1),c=(i[9]+1)/i[5],l=(i[9]-1)/i[5],u=(i[8]-1)/i[0],d=(a[8]+1)/a[0],f=o*u,p=o*d,m=r/(-u+d),h=m*-u;if(t.matrixWorld.decompose(e.position,e.quaternion,e.scale),e.translateX(h),e.translateZ(m),e.matrixWorld.compose(e.position,e.quaternion,e.scale),e.matrixWorldInverse.copy(e.matrixWorld).invert(),i[10]===-1)e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse);else{let t=o+m,n=s+m,i=f-h,a=p+(r-h),u=c*s/n*t,d=l*s/n*t;e.projectionMatrix.makePerspective(i,a,u,d,t,n),e.projectionMatrixInverse.copy(e.projectionMatrix).invert()}}function ue(e,t){t===null?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}this.updateCamera=function(e){if(r===null)return;let t=e.near,n=e.far;_.texture!==null&&(_.depthNear>0&&(t=_.depthNear),_.depthFar>0&&(n=_.depthFar)),A.near=te.near=k.near=t,A.far=te.far=k.far=n,(re!==A.near||ie!==A.far)&&(r.updateRenderState({depthNear:A.near,depthFar:A.far}),re=A.near,ie=A.far),A.layers.mask=e.layers.mask|6,k.layers.mask=A.layers.mask&3,te.layers.mask=A.layers.mask&5;let i=e.parent,a=A.cameras;ue(A,i);for(let e=0;e<a.length;e++)ue(a[e],i);a.length===2?le(A,k,te):A.projectionMatrix.copy(k.projectionMatrix),de(e,A,i)};function de(e,t,n){n===null?e.matrix.copy(t.matrixWorld):(e.matrix.copy(n.matrixWorld),e.matrix.invert(),e.matrix.multiply(t.matrixWorld)),e.matrix.decompose(e.position,e.quaternion,e.scale),e.updateMatrixWorld(!0),e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse),e.isPerspectiveCamera&&(e.fov=qe*2*Math.atan(1/e.projectionMatrix.elements[5]),e.zoom=1)}this.getCamera=function(){return A},this.getFoveation=function(){if(!(f===null&&p===null))return s},this.setFoveation=function(e){s=e,f!==null&&(f.fixedFoveation=e),p!==null&&p.fixedFoveation!==void 0&&(p.fixedFoveation=e)},this.hasDepthSensing=function(){return _.texture!==null},this.getDepthSensingMesh=function(){return _.getMesh(A)},this.getCameraTexture=function(e){return v[e]};let fe=null;function pe(t,i){if(u=i.getViewerPose(c||a),h=i,u!==null){let t=u.views;p!==null&&(e.setRenderTargetFramebuffer(S,p.framebuffer),e.setRenderTarget(S));let i=!1;t.length!==A.cameras.length&&(A.cameras.length=0,i=!0);for(let n=0;n<t.length;n++){let r=t[n],a=null;if(p!==null)a=p.getViewport(r);else{let t=d.getViewSubImage(f,r);a=t.viewport,n===0&&(e.setRenderTargetTextures(S,t.colorTexture,t.depthStencilTexture),e.setRenderTarget(S))}let o=ne[n];o===void 0&&(o=new ti,o.layers.enable(n),o.viewport=new Bt,ne[n]=o),o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.quaternion,o.scale),o.projectionMatrix.fromArray(r.projectionMatrix),o.projectionMatrixInverse.copy(o.projectionMatrix).invert(),o.viewport.set(a.x,a.y,a.width,a.height),n===0&&(A.matrix.copy(o.matrix),A.matrix.decompose(A.position,A.quaternion,A.scale)),i===!0&&A.cameras.push(o)}let a=r.enabledFeatures;if(a&&a.includes(`depth-sensing`)&&r.depthUsage==`gpu-optimized`&&g){d=n.getBinding();let e=d.getDepthInformation(t[0]);e&&e.isValid&&e.texture&&_.init(e,r.renderState)}if(a&&a.includes(`camera-access`)&&g){e.state.unbindTexture(),d=n.getBinding();for(let e=0;e<t.length;e++){let n=t[e].camera;if(n){let e=v[n];e||(e=new $i,v[n]=e);let t=d.getCameraImage(n);e.sourceTexture=t}}}}for(let e=0;e<C.length;e++){let t=D[e],n=C[e];t!==null&&n!==void 0&&n.update(t,i,c||a)}fe&&fe(t,i),i.detectedPlanes&&n.dispatchEvent({type:`planesdetected`,data:i}),h=null}let me=new bo;me.setAnimationLoop(pe),this.setAnimationLoop=function(e){fe=e},this.dispose=function(){}}},_l=new kn,vl=new yn;function yl(e,t){function n(e,t){e.matrixAutoUpdate===!0&&e.updateMatrix(),t.value.copy(e.matrix)}function r(t,n){n.color.getRGB(t.fogColor.value,Kr(e)),n.isFog?(t.fogNear.value=n.near,t.fogFar.value=n.far):n.isFogExp2&&(t.fogDensity.value=n.density)}function i(e,t,n,r,i){t.isMeshBasicMaterial||t.isMeshLambertMaterial?a(e,t):t.isMeshToonMaterial?(a(e,t),d(e,t)):t.isMeshPhongMaterial?(a(e,t),u(e,t)):t.isMeshStandardMaterial?(a(e,t),f(e,t),t.isMeshPhysicalMaterial&&p(e,t,i)):t.isMeshMatcapMaterial?(a(e,t),m(e,t)):t.isMeshDepthMaterial?a(e,t):t.isMeshDistanceMaterial?(a(e,t),h(e,t)):t.isMeshNormalMaterial?a(e,t):t.isLineBasicMaterial?(o(e,t),t.isLineDashedMaterial&&s(e,t)):t.isPointsMaterial?c(e,t,n,r):t.isSpriteMaterial?l(e,t):t.isShadowMaterial?(e.color.value.copy(t.color),e.opacity.value=t.opacity):t.isShaderMaterial&&(t.uniformsNeedUpdate=!1)}function a(e,r){e.opacity.value=r.opacity,r.color&&e.diffuse.value.copy(r.color),r.emissive&&e.emissive.value.copy(r.emissive).multiplyScalar(r.emissiveIntensity),r.map&&(e.map.value=r.map,n(r.map,e.mapTransform)),r.alphaMap&&(e.alphaMap.value=r.alphaMap,n(r.alphaMap,e.alphaMapTransform)),r.bumpMap&&(e.bumpMap.value=r.bumpMap,n(r.bumpMap,e.bumpMapTransform),e.bumpScale.value=r.bumpScale,r.side===1&&(e.bumpScale.value*=-1)),r.normalMap&&(e.normalMap.value=r.normalMap,n(r.normalMap,e.normalMapTransform),e.normalScale.value.copy(r.normalScale),r.side===1&&e.normalScale.value.negate()),r.displacementMap&&(e.displacementMap.value=r.displacementMap,n(r.displacementMap,e.displacementMapTransform),e.displacementScale.value=r.displacementScale,e.displacementBias.value=r.displacementBias),r.emissiveMap&&(e.emissiveMap.value=r.emissiveMap,n(r.emissiveMap,e.emissiveMapTransform)),r.specularMap&&(e.specularMap.value=r.specularMap,n(r.specularMap,e.specularMapTransform)),r.alphaTest>0&&(e.alphaTest.value=r.alphaTest);let i=t.get(r),a=i.envMap,o=i.envMapRotation;a&&(e.envMap.value=a,_l.copy(o),_l.x*=-1,_l.y*=-1,_l.z*=-1,a.isCubeTexture&&a.isRenderTargetTexture===!1&&(_l.y*=-1,_l.z*=-1),e.envMapRotation.value.setFromMatrix4(vl.makeRotationFromEuler(_l)),e.flipEnvMap.value=a.isCubeTexture&&a.isRenderTargetTexture===!1?-1:1,e.reflectivity.value=r.reflectivity,e.ior.value=r.ior,e.refractionRatio.value=r.refractionRatio),r.lightMap&&(e.lightMap.value=r.lightMap,e.lightMapIntensity.value=r.lightMapIntensity,n(r.lightMap,e.lightMapTransform)),r.aoMap&&(e.aoMap.value=r.aoMap,e.aoMapIntensity.value=r.aoMapIntensity,n(r.aoMap,e.aoMapTransform))}function o(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform))}function s(e,t){e.dashSize.value=t.dashSize,e.totalSize.value=t.dashSize+t.gapSize,e.scale.value=t.scale}function c(e,t,r,i){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.size.value=t.size*r,e.scale.value=i*.5,t.map&&(e.map.value=t.map,n(t.map,e.uvTransform)),t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform)),t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}function l(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.rotation.value=t.rotation,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform)),t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform)),t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}function u(e,t){e.specular.value.copy(t.specular),e.shininess.value=Math.max(t.shininess,1e-4)}function d(e,t){t.gradientMap&&(e.gradientMap.value=t.gradientMap)}function f(e,t){e.metalness.value=t.metalness,t.metalnessMap&&(e.metalnessMap.value=t.metalnessMap,n(t.metalnessMap,e.metalnessMapTransform)),e.roughness.value=t.roughness,t.roughnessMap&&(e.roughnessMap.value=t.roughnessMap,n(t.roughnessMap,e.roughnessMapTransform)),t.envMap&&(e.envMapIntensity.value=t.envMapIntensity)}function p(e,t,r){e.ior.value=t.ior,t.sheen>0&&(e.sheenColor.value.copy(t.sheenColor).multiplyScalar(t.sheen),e.sheenRoughness.value=t.sheenRoughness,t.sheenColorMap&&(e.sheenColorMap.value=t.sheenColorMap,n(t.sheenColorMap,e.sheenColorMapTransform)),t.sheenRoughnessMap&&(e.sheenRoughnessMap.value=t.sheenRoughnessMap,n(t.sheenRoughnessMap,e.sheenRoughnessMapTransform))),t.clearcoat>0&&(e.clearcoat.value=t.clearcoat,e.clearcoatRoughness.value=t.clearcoatRoughness,t.clearcoatMap&&(e.clearcoatMap.value=t.clearcoatMap,n(t.clearcoatMap,e.clearcoatMapTransform)),t.clearcoatRoughnessMap&&(e.clearcoatRoughnessMap.value=t.clearcoatRoughnessMap,n(t.clearcoatRoughnessMap,e.clearcoatRoughnessMapTransform)),t.clearcoatNormalMap&&(e.clearcoatNormalMap.value=t.clearcoatNormalMap,n(t.clearcoatNormalMap,e.clearcoatNormalMapTransform),e.clearcoatNormalScale.value.copy(t.clearcoatNormalScale),t.side===1&&e.clearcoatNormalScale.value.negate())),t.dispersion>0&&(e.dispersion.value=t.dispersion),t.iridescence>0&&(e.iridescence.value=t.iridescence,e.iridescenceIOR.value=t.iridescenceIOR,e.iridescenceThicknessMinimum.value=t.iridescenceThicknessRange[0],e.iridescenceThicknessMaximum.value=t.iridescenceThicknessRange[1],t.iridescenceMap&&(e.iridescenceMap.value=t.iridescenceMap,n(t.iridescenceMap,e.iridescenceMapTransform)),t.iridescenceThicknessMap&&(e.iridescenceThicknessMap.value=t.iridescenceThicknessMap,n(t.iridescenceThicknessMap,e.iridescenceThicknessMapTransform))),t.transmission>0&&(e.transmission.value=t.transmission,e.transmissionSamplerMap.value=r.texture,e.transmissionSamplerSize.value.set(r.width,r.height),t.transmissionMap&&(e.transmissionMap.value=t.transmissionMap,n(t.transmissionMap,e.transmissionMapTransform)),e.thickness.value=t.thickness,t.thicknessMap&&(e.thicknessMap.value=t.thicknessMap,n(t.thicknessMap,e.thicknessMapTransform)),e.attenuationDistance.value=t.attenuationDistance,e.attenuationColor.value.copy(t.attenuationColor)),t.anisotropy>0&&(e.anisotropyVector.value.set(t.anisotropy*Math.cos(t.anisotropyRotation),t.anisotropy*Math.sin(t.anisotropyRotation)),t.anisotropyMap&&(e.anisotropyMap.value=t.anisotropyMap,n(t.anisotropyMap,e.anisotropyMapTransform))),e.specularIntensity.value=t.specularIntensity,e.specularColor.value.copy(t.specularColor),t.specularColorMap&&(e.specularColorMap.value=t.specularColorMap,n(t.specularColorMap,e.specularColorMapTransform)),t.specularIntensityMap&&(e.specularIntensityMap.value=t.specularIntensityMap,n(t.specularIntensityMap,e.specularIntensityMapTransform))}function m(e,t){t.matcap&&(e.matcap.value=t.matcap)}function h(e,n){let r=t.get(n).light;e.referencePosition.value.setFromMatrixPosition(r.matrixWorld),e.nearDistance.value=r.shadow.camera.near,e.farDistance.value=r.shadow.camera.far}return{refreshFogUniforms:r,refreshMaterialUniforms:i}}function bl(e,t,n,r){let i={},a={},o=[],s=e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS);function c(e,t){let n=t.program;r.uniformBlockBinding(e,n)}function l(e,n){let o=i[e.id];o===void 0&&(m(e),o=u(e),i[e.id]=o,e.addEventListener(`dispose`,g));let s=n.program;r.updateUBOMapping(e,s);let c=t.render.frame;a[e.id]!==c&&(f(e),a[e.id]=c)}function u(t){let n=d();t.__bindingPointIndex=n;let r=e.createBuffer(),i=t.__size,a=t.usage;return e.bindBuffer(e.UNIFORM_BUFFER,r),e.bufferData(e.UNIFORM_BUFFER,i,a),e.bindBuffer(e.UNIFORM_BUFFER,null),e.bindBufferBase(e.UNIFORM_BUFFER,n,r),r}function d(){for(let e=0;e<s;e++)if(o.indexOf(e)===-1)return o.push(e),e;return console.error(`THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.`),0}function f(t){let n=i[t.id],r=t.uniforms,a=t.__cache;e.bindBuffer(e.UNIFORM_BUFFER,n);for(let t=0,n=r.length;t<n;t++){let n=Array.isArray(r[t])?r[t]:[r[t]];for(let r=0,i=n.length;r<i;r++){let i=n[r];if(p(i,t,r,a)===!0){let t=i.__offset,n=Array.isArray(i.value)?i.value:[i.value],r=0;for(let a=0;a<n.length;a++){let o=n[a],s=h(o);typeof o==`number`||typeof o==`boolean`?(i.__data[0]=o,e.bufferSubData(e.UNIFORM_BUFFER,t+r,i.__data)):o.isMatrix3?(i.__data[0]=o.elements[0],i.__data[1]=o.elements[1],i.__data[2]=o.elements[2],i.__data[3]=0,i.__data[4]=o.elements[3],i.__data[5]=o.elements[4],i.__data[6]=o.elements[5],i.__data[7]=0,i.__data[8]=o.elements[6],i.__data[9]=o.elements[7],i.__data[10]=o.elements[8],i.__data[11]=0):(o.toArray(i.__data,r),r+=s.storage/Float32Array.BYTES_PER_ELEMENT)}e.bufferSubData(e.UNIFORM_BUFFER,t,i.__data)}}}e.bindBuffer(e.UNIFORM_BUFFER,null)}function p(e,t,n,r){let i=e.value,a=t+`_`+n;if(r[a]===void 0)return typeof i==`number`||typeof i==`boolean`?r[a]=i:r[a]=i.clone(),!0;{let e=r[a];if(typeof i==`number`||typeof i==`boolean`){if(e!==i)return r[a]=i,!0}else if(e.equals(i)===!1)return e.copy(i),!0}return!1}function m(e){let t=e.uniforms,n=0;for(let e=0,r=t.length;e<r;e++){let r=Array.isArray(t[e])?t[e]:[t[e]];for(let e=0,t=r.length;e<t;e++){let t=r[e],i=Array.isArray(t.value)?t.value:[t.value];for(let e=0,r=i.length;e<r;e++){let r=i[e],a=h(r),o=n%16,s=o%a.boundary,c=o+s;n+=s,c!==0&&16-c<a.storage&&(n+=16-c),t.__data=new Float32Array(a.storage/Float32Array.BYTES_PER_ELEMENT),t.__offset=n,n+=a.storage}}}let r=n%16;return r>0&&(n+=16-r),e.__size=n,e.__cache={},this}function h(e){let t={boundary:0,storage:0};return typeof e==`number`||typeof e==`boolean`?(t.boundary=4,t.storage=4):e.isVector2?(t.boundary=8,t.storage=8):e.isVector3||e.isColor?(t.boundary=16,t.storage=12):e.isVector4?(t.boundary=16,t.storage=16):e.isMatrix3?(t.boundary=48,t.storage=48):e.isMatrix4?(t.boundary=64,t.storage=64):e.isTexture?console.warn(`THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.`):console.warn(`THREE.WebGLRenderer: Unsupported uniform value type.`,e),t}function g(t){let n=t.target;n.removeEventListener(`dispose`,g);let r=o.indexOf(n.__bindingPointIndex);o.splice(r,1),e.deleteBuffer(i[n.id]),delete i[n.id],delete a[n.id]}function _(){for(let t in i)e.deleteBuffer(i[t]);o=[],i={},a={}}return{bind:c,update:l,dispose:_}}var xl=class{constructor(e={}){let{canvas:t=St(),context:n=null,depth:r=!0,stencil:i=!1,alpha:a=!1,antialias:o=!1,premultipliedAlpha:s=!0,preserveDrawingBuffer:u=!1,powerPreference:d=`default`,failIfMajorPerformanceCaveat:f=!1,reversedDepthBuffer:p=!1}=e;this.isWebGLRenderer=!0;let m;if(n!==null){if(typeof WebGLRenderingContext<`u`&&n instanceof WebGLRenderingContext)throw Error(`THREE.WebGLRenderer: WebGL 1 is not supported since r163.`);m=n.getContextAttributes().alpha}else m=a;let h=new Uint32Array(4),_=new Int32Array(4),v=null,y=null,b=[],x=[];this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=0,this.toneMappingExposure=1,this.transmissionResolutionScale=1;let S=this,C=!1;this._outputColorSpace=Ie;let w=0,T=0,E=null,D=-1,ee=null,O=new Bt,k=new Bt,te=null,ne=new B(0),A=0,re=t.width,ie=t.height,j=1,ae=null,oe=null,se=new Bt(0,0,re,ie),ce=new Bt(0,0,re,ie),le=!1,ue=new Li,de=!1,fe=!1,pe=new yn,me=new R,he=new Bt,ge={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0},_e=!1;function ve(){return E===null?j:1}let M=n;function ye(e,n){return t.getContext(e,n)}try{let e={alpha:!0,depth:r,stencil:i,antialias:o,premultipliedAlpha:s,preserveDrawingBuffer:u,powerPreference:d,failIfMajorPerformanceCaveat:f};if(`setAttribute`in t&&t.setAttribute(`data-engine`,`three.js r180`),t.addEventListener(`webglcontextlost`,Ke,!1),t.addEventListener(`webglcontextrestored`,qe,!1),t.addEventListener(`webglcontextcreationerror`,Je,!1),M===null){let t=`webgl2`;if(M=ye(t,e),M===null)throw ye(t)?Error(`Error creating WebGL context with your selected attributes.`):Error(`Error creating WebGL context.`)}}catch(e){throw console.error(`THREE.WebGLRenderer: `+e.message),e}let be,xe,N,Se,P,F,Ce,we,Te,Ee,De,Oe,ke,Ae,je,Me,Ne,Pe,Fe,Re,ze,Be,Ve,Ue;function We(){be=new es(M),be.init(),Be=new fl(M,be),xe=new ko(M,be,e,Be),N=new ul(M,be),xe.reversedDepthBuffer&&p&&N.buffers.depth.setReversed(!0),Se=new rs(M),P=new Jc,F=new dl(M,be,N,P,xe,Be,Se),Ce=new jo(S),we=new $o(S),Te=new xo(M),Ve=new Do(M,Te),Ee=new ts(M,Te,Se,Ve),De=new as(M,Ee,Te,Se),Fe=new is(M,xe,F),Me=new Ao(P),Oe=new qc(S,Ce,we,be,xe,Ve,Me),ke=new yl(S,P),Ae=new Qc,je=new al(be),Pe=new Eo(S,Ce,we,N,De,m,s),Ne=new cl(S,De,xe),Ue=new bl(M,Se,xe,N),Re=new Oo(M,be,Se),ze=new ns(M,be,Se),Se.programs=Oe.programs,S.capabilities=xe,S.extensions=be,S.properties=P,S.renderLists=Ae,S.shadowMap=Ne,S.state=N,S.info=Se}We();let Ge=new gl(S,M);this.xr=Ge,this.getContext=function(){return M},this.getContextAttributes=function(){return M.getContextAttributes()},this.forceContextLoss=function(){let e=be.get(`WEBGL_lose_context`);e&&e.loseContext()},this.forceContextRestore=function(){let e=be.get(`WEBGL_lose_context`);e&&e.restoreContext()},this.getPixelRatio=function(){return j},this.setPixelRatio=function(e){e!==void 0&&(j=e,this.setSize(re,ie,!1))},this.getSize=function(e){return e.set(re,ie)},this.setSize=function(e,n,r=!0){if(Ge.isPresenting){console.warn(`THREE.WebGLRenderer: Can't change size while VR device is presenting.`);return}re=e,ie=n,t.width=Math.floor(e*j),t.height=Math.floor(n*j),r===!0&&(t.style.width=e+`px`,t.style.height=n+`px`),this.setViewport(0,0,e,n)},this.getDrawingBufferSize=function(e){return e.set(re*j,ie*j).floor()},this.setDrawingBufferSize=function(e,n,r){re=e,ie=n,j=r,t.width=Math.floor(e*r),t.height=Math.floor(n*r),this.setViewport(0,0,e,n)},this.getCurrentViewport=function(e){return e.copy(O)},this.getViewport=function(e){return e.copy(se)},this.setViewport=function(e,t,n,r){e.isVector4?se.set(e.x,e.y,e.z,e.w):se.set(e,t,n,r),N.viewport(O.copy(se).multiplyScalar(j).round())},this.getScissor=function(e){return e.copy(ce)},this.setScissor=function(e,t,n,r){e.isVector4?ce.set(e.x,e.y,e.z,e.w):ce.set(e,t,n,r),N.scissor(k.copy(ce).multiplyScalar(j).round())},this.getScissorTest=function(){return le},this.setScissorTest=function(e){N.setScissorTest(le=e)},this.setOpaqueSort=function(e){ae=e},this.setTransparentSort=function(e){oe=e},this.getClearColor=function(e){return e.copy(Pe.getClearColor())},this.setClearColor=function(){Pe.setClearColor(...arguments)},this.getClearAlpha=function(){return Pe.getClearAlpha()},this.setClearAlpha=function(){Pe.setClearAlpha(...arguments)},this.clear=function(e=!0,t=!0,n=!0){let r=0;if(e){let e=!1;if(E!==null){let t=E.texture.format;e=t===1033||t===1031||t===1029}if(e){let e=E.texture.type,t=e===1009||e===1014||e===1012||e===1020||e===1017||e===1018,n=Pe.getClearColor(),r=Pe.getClearAlpha(),i=n.r,a=n.g,o=n.b;t?(h[0]=i,h[1]=a,h[2]=o,h[3]=r,M.clearBufferuiv(M.COLOR,0,h)):(_[0]=i,_[1]=a,_[2]=o,_[3]=r,M.clearBufferiv(M.COLOR,0,_))}else r|=M.COLOR_BUFFER_BIT}t&&(r|=M.DEPTH_BUFFER_BIT),n&&(r|=M.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),M.clear(r)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){t.removeEventListener(`webglcontextlost`,Ke,!1),t.removeEventListener(`webglcontextrestored`,qe,!1),t.removeEventListener(`webglcontextcreationerror`,Je,!1),Pe.dispose(),Ae.dispose(),je.dispose(),P.dispose(),Ce.dispose(),we.dispose(),De.dispose(),Ve.dispose(),Ue.dispose(),Oe.dispose(),Ge.dispose(),Ge.removeEventListener(`sessionstart`,et),Ge.removeEventListener(`sessionend`,tt),nt.stop()};function Ke(e){e.preventDefault(),console.log(`THREE.WebGLRenderer: Context Lost.`),C=!0}function qe(){console.log(`THREE.WebGLRenderer: Context Restored.`),C=!1;let e=Se.autoReset,t=Ne.enabled,n=Ne.autoUpdate,r=Ne.needsUpdate,i=Ne.type;We(),Se.autoReset=e,Ne.enabled=t,Ne.autoUpdate=n,Ne.needsUpdate=r,Ne.type=i}function Je(e){console.error(`THREE.WebGLRenderer: A WebGL context could not be created. Reason: `,e.statusMessage)}function I(e){let t=e.target;t.removeEventListener(`dispose`,I),Ye(t)}function Ye(e){Xe(e),P.remove(e)}function Xe(e){let t=P.get(e).programs;t!==void 0&&(t.forEach(function(e){Oe.releaseProgram(e)}),e.isShaderMaterial&&Oe.releaseShaderCache(e))}this.renderBufferDirect=function(e,t,n,r,i,a){t===null&&(t=ge);let o=i.isMesh&&i.matrixWorld.determinant()<0,s=dt(e,t,n,r,i);N.setMaterial(r,o);let c=n.index,l=1;if(r.wireframe===!0){if(c=Ee.getWireframeAttribute(n),c===void 0)return;l=2}let u=n.drawRange,d=n.attributes.position,f=u.start*l,p=(u.start+u.count)*l;a!==null&&(f=Math.max(f,a.start*l),p=Math.min(p,(a.start+a.count)*l)),c===null?d!=null&&(f=Math.max(f,0),p=Math.min(p,d.count)):(f=Math.max(f,0),p=Math.min(p,c.count));let m=p-f;if(m<0||m===1/0)return;Ve.setup(i,r,s,n,c);let h,g=Re;if(c!==null&&(h=Te.get(c),g=ze,g.setIndex(h)),i.isMesh)r.wireframe===!0?(N.setLineWidth(r.wireframeLinewidth*ve()),g.setMode(M.LINES)):g.setMode(M.TRIANGLES);else if(i.isLine){let e=r.linewidth;e===void 0&&(e=1),N.setLineWidth(e*ve()),i.isLineSegments?g.setMode(M.LINES):i.isLineLoop?g.setMode(M.LINE_LOOP):g.setMode(M.LINE_STRIP)}else i.isPoints?g.setMode(M.POINTS):i.isSprite&&g.setMode(M.TRIANGLES);if(i.isBatchedMesh)if(i._multiDrawInstances!==null)wt(`THREE.WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.`),g.renderMultiDrawInstances(i._multiDrawStarts,i._multiDrawCounts,i._multiDrawCount,i._multiDrawInstances);else if(be.get(`WEBGL_multi_draw`))g.renderMultiDraw(i._multiDrawStarts,i._multiDrawCounts,i._multiDrawCount);else{let e=i._multiDrawStarts,t=i._multiDrawCounts,n=i._multiDrawCount,a=c?Te.get(c).bytesPerElement:1,o=P.get(r).currentProgram.getUniforms();for(let r=0;r<n;r++)o.setValue(M,`_gl_DrawID`,r),g.render(e[r]/a,t[r])}else if(i.isInstancedMesh)g.renderInstances(f,m,i.count);else if(n.isInstancedBufferGeometry){let e=n._maxInstanceCount===void 0?1/0:n._maxInstanceCount,t=Math.min(n.instanceCount,e);g.renderInstances(f,m,t)}else g.render(f,m)};function Ze(e,t,n){e.transparent===!0&&e.side===2&&e.forceSinglePass===!1?(e.side=1,e.needsUpdate=!0,ct(e,t,n),e.side=0,e.needsUpdate=!0,ct(e,t,n),e.side=2):ct(e,t,n)}this.compile=function(e,t,n=null){n===null&&(n=e),y=je.get(n),y.init(t),x.push(y),n.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&(y.pushLight(e),e.castShadow&&y.pushShadow(e))}),e!==n&&e.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&(y.pushLight(e),e.castShadow&&y.pushShadow(e))}),y.setupLights();let r=new Set;return e.traverse(function(e){if(!(e.isMesh||e.isPoints||e.isLine||e.isSprite))return;let t=e.material;if(t)if(Array.isArray(t))for(let i=0;i<t.length;i++){let a=t[i];Ze(a,n,e),r.add(a)}else Ze(t,n,e),r.add(t)}),y=x.pop(),r},this.compileAsync=function(e,t,n=null){let r=this.compile(e,t,n);return new Promise(t=>{function n(){if(r.forEach(function(e){P.get(e).currentProgram.isReady()&&r.delete(e)}),r.size===0){t(e);return}setTimeout(n,10)}be.get(`KHR_parallel_shader_compile`)===null?setTimeout(n,10):n()})};let Qe=null;function $e(e){Qe&&Qe(e)}function et(){nt.stop()}function tt(){nt.start()}let nt=new bo;nt.setAnimationLoop($e),typeof self<`u`&&nt.setContext(self),this.setAnimationLoop=function(e){Qe=e,Ge.setAnimationLoop(e),e===null?nt.stop():nt.start()},Ge.addEventListener(`sessionstart`,et),Ge.addEventListener(`sessionend`,tt),this.render=function(e,t){if(t!==void 0&&t.isCamera!==!0){console.error(`THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.`);return}if(C===!0)return;if(e.matrixWorldAutoUpdate===!0&&e.updateMatrixWorld(),t.parent===null&&t.matrixWorldAutoUpdate===!0&&t.updateMatrixWorld(),Ge.enabled===!0&&Ge.isPresenting===!0&&(Ge.cameraAutoUpdate===!0&&Ge.updateCamera(t),t=Ge.getCamera()),e.isScene===!0&&e.onBeforeRender(S,e,t,E),y=je.get(e,x.length),y.init(t),x.push(y),pe.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),ue.setFromProjectionMatrix(pe,He,t.reversedDepth),fe=this.localClippingEnabled,de=Me.init(this.clippingPlanes,fe),v=Ae.get(e,b.length),v.init(),b.push(v),Ge.enabled===!0&&Ge.isPresenting===!0){let e=S.xr.getDepthSensingMesh();e!==null&&rt(e,t,-1/0,S.sortObjects)}rt(e,t,0,S.sortObjects),v.finish(),S.sortObjects===!0&&v.sort(ae,oe),_e=Ge.enabled===!1||Ge.isPresenting===!1||Ge.hasDepthSensing()===!1,_e&&Pe.addToRenderList(v,e),this.info.render.frame++,de===!0&&Me.beginShadows();let n=y.state.shadowsArray;Ne.render(n,e,t),de===!0&&Me.endShadows(),this.info.autoReset===!0&&this.info.reset();let r=v.opaque,i=v.transmissive;if(y.setupLights(),t.isArrayCamera){let n=t.cameras;if(i.length>0)for(let t=0,a=n.length;t<a;t++){let a=n[t];at(r,i,e,a)}_e&&Pe.render(e);for(let t=0,r=n.length;t<r;t++){let r=n[t];it(v,e,r,r.viewport)}}else i.length>0&&at(r,i,e,t),_e&&Pe.render(e),it(v,e,t);E!==null&&T===0&&(F.updateMultisampleRenderTarget(E),F.updateRenderTargetMipmap(E)),e.isScene===!0&&e.onAfterRender(S,e,t),Ve.resetDefaultState(),D=-1,ee=null,x.pop(),x.length>0?(y=x[x.length-1],de===!0&&Me.setGlobalState(S.clippingPlanes,y.state.camera)):y=null,b.pop(),v=b.length>0?b[b.length-1]:null};function rt(e,t,n,r){if(e.visible===!1)return;if(e.layers.test(t.layers)){if(e.isGroup)n=e.renderOrder;else if(e.isLOD)e.autoUpdate===!0&&e.update(t);else if(e.isLight)y.pushLight(e),e.castShadow&&y.pushShadow(e);else if(e.isSprite){if(!e.frustumCulled||ue.intersectsSprite(e)){r&&he.setFromMatrixPosition(e.matrixWorld).applyMatrix4(pe);let t=De.update(e),i=e.material;i.visible&&v.push(e,t,i,n,he.z,null)}}else if((e.isMesh||e.isLine||e.isPoints)&&(!e.frustumCulled||ue.intersectsObject(e))){let t=De.update(e),i=e.material;if(r&&(e.boundingSphere===void 0?(t.boundingSphere===null&&t.computeBoundingSphere(),he.copy(t.boundingSphere.center)):(e.boundingSphere===null&&e.computeBoundingSphere(),he.copy(e.boundingSphere.center)),he.applyMatrix4(e.matrixWorld).applyMatrix4(pe)),Array.isArray(i)){let r=t.groups;for(let a=0,o=r.length;a<o;a++){let o=r[a],s=i[o.materialIndex];s&&s.visible&&v.push(e,t,s,n,he.z,o)}}else i.visible&&v.push(e,t,i,n,he.z,null)}}let i=e.children;for(let e=0,a=i.length;e<a;e++)rt(i[e],t,n,r)}function it(e,t,n,r){let i=e.opaque,a=e.transmissive,o=e.transparent;y.setupLightsView(n),de===!0&&Me.setGlobalState(S.clippingPlanes,n),r&&N.viewport(O.copy(r)),i.length>0&&ot(i,t,n),a.length>0&&ot(a,t,n),o.length>0&&ot(o,t,n),N.buffers.depth.setTest(!0),N.buffers.depth.setMask(!0),N.buffers.color.setMask(!0),N.setPolygonOffset(!1)}function at(e,t,n,r){if((n.isScene===!0?n.overrideMaterial:null)!==null)return;y.state.transmissionRenderTarget[r.id]===void 0&&(y.state.transmissionRenderTarget[r.id]=new Ht(1,1,{generateMipmaps:!0,type:be.has(`EXT_color_buffer_half_float`)||be.has(`EXT_color_buffer_float`)?g:l,minFilter:c,samples:4,stencilBuffer:i,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:kt.workingColorSpace}));let a=y.state.transmissionRenderTarget[r.id],o=r.viewport||O;a.setSize(o.z*S.transmissionResolutionScale,o.w*S.transmissionResolutionScale);let s=S.getRenderTarget(),u=S.getActiveCubeFace(),d=S.getActiveMipmapLevel();S.setRenderTarget(a),S.getClearColor(ne),A=S.getClearAlpha(),A<1&&S.setClearColor(16777215,.5),S.clear(),_e&&Pe.render(n);let f=S.toneMapping;S.toneMapping=0;let p=r.viewport;if(r.viewport!==void 0&&(r.viewport=void 0),y.setupLightsView(r),de===!0&&Me.setGlobalState(S.clippingPlanes,r),ot(e,n,r),F.updateMultisampleRenderTarget(a),F.updateRenderTargetMipmap(a),be.has(`WEBGL_multisampled_render_to_texture`)===!1){let e=!1;for(let i=0,a=t.length;i<a;i++){let a=t[i],o=a.object,s=a.geometry,c=a.material,l=a.group;if(c.side===2&&o.layers.test(r.layers)){let t=c.side;c.side=1,c.needsUpdate=!0,st(o,n,r,s,c,l),c.side=t,c.needsUpdate=!0,e=!0}}e===!0&&(F.updateMultisampleRenderTarget(a),F.updateRenderTargetMipmap(a))}S.setRenderTarget(s,u,d),S.setClearColor(ne,A),p!==void 0&&(r.viewport=p),S.toneMapping=f}function ot(e,t,n){let r=t.isScene===!0?t.overrideMaterial:null;for(let i=0,a=e.length;i<a;i++){let a=e[i],o=a.object,s=a.geometry,c=a.group,l=a.material;l.allowOverride===!0&&r!==null&&(l=r),o.layers.test(n.layers)&&st(o,t,n,s,l,c)}}function st(e,t,n,r,i,a){e.onBeforeRender(S,t,n,r,i,a),e.modelViewMatrix.multiplyMatrices(n.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix),i.onBeforeRender(S,t,n,r,e,a),i.transparent===!0&&i.side===2&&i.forceSinglePass===!1?(i.side=1,i.needsUpdate=!0,S.renderBufferDirect(n,t,r,i,e,a),i.side=0,i.needsUpdate=!0,S.renderBufferDirect(n,t,r,i,e,a),i.side=2):S.renderBufferDirect(n,t,r,i,e,a),e.onAfterRender(S,t,n,r,i,a)}function ct(e,t,n){t.isScene!==!0&&(t=ge);let r=P.get(e),i=y.state.lights,a=y.state.shadowsArray,o=i.state.version,s=Oe.getParameters(e,i.state,a,t,n),c=Oe.getProgramCacheKey(s),l=r.programs;r.environment=e.isMeshStandardMaterial?t.environment:null,r.fog=t.fog,r.envMap=(e.isMeshStandardMaterial?we:Ce).get(e.envMap||r.environment),r.envMapRotation=r.environment!==null&&e.envMap===null?t.environmentRotation:e.envMapRotation,l===void 0&&(e.addEventListener(`dispose`,I),l=new Map,r.programs=l);let u=l.get(c);if(u!==void 0){if(r.currentProgram===u&&r.lightsStateVersion===o)return ut(e,s),u}else s.uniforms=Oe.getUniforms(e),e.onBeforeCompile(s,S),u=Oe.acquireProgram(s,c),l.set(c,u),r.uniforms=s.uniforms;let d=r.uniforms;return(!e.isShaderMaterial&&!e.isRawShaderMaterial||e.clipping===!0)&&(d.clippingPlanes=Me.uniform),ut(e,s),r.needsLights=pt(e),r.lightsStateVersion=o,r.needsLights&&(d.ambientLightColor.value=i.state.ambient,d.lightProbe.value=i.state.probe,d.directionalLights.value=i.state.directional,d.directionalLightShadows.value=i.state.directionalShadow,d.spotLights.value=i.state.spot,d.spotLightShadows.value=i.state.spotShadow,d.rectAreaLights.value=i.state.rectArea,d.ltc_1.value=i.state.rectAreaLTC1,d.ltc_2.value=i.state.rectAreaLTC2,d.pointLights.value=i.state.point,d.pointLightShadows.value=i.state.pointShadow,d.hemisphereLights.value=i.state.hemi,d.directionalShadowMap.value=i.state.directionalShadowMap,d.directionalShadowMatrix.value=i.state.directionalShadowMatrix,d.spotShadowMap.value=i.state.spotShadowMap,d.spotLightMatrix.value=i.state.spotLightMatrix,d.spotLightMap.value=i.state.spotLightMap,d.pointShadowMap.value=i.state.pointShadowMap,d.pointShadowMatrix.value=i.state.pointShadowMatrix),r.currentProgram=u,r.uniformsList=null,u}function lt(e){if(e.uniformsList===null){let t=e.currentProgram.getUniforms();e.uniformsList=fc.seqWithValue(t.seq,e.uniforms)}return e.uniformsList}function ut(e,t){let n=P.get(e);n.outputColorSpace=t.outputColorSpace,n.batching=t.batching,n.batchingColor=t.batchingColor,n.instancing=t.instancing,n.instancingColor=t.instancingColor,n.instancingMorph=t.instancingMorph,n.skinning=t.skinning,n.morphTargets=t.morphTargets,n.morphNormals=t.morphNormals,n.morphColors=t.morphColors,n.morphTargetsCount=t.morphTargetsCount,n.numClippingPlanes=t.numClippingPlanes,n.numIntersection=t.numClipIntersection,n.vertexAlphas=t.vertexAlphas,n.vertexTangents=t.vertexTangents,n.toneMapping=t.toneMapping}function dt(e,t,n,r,i){t.isScene!==!0&&(t=ge),F.resetTextureUnits();let a=t.fog,o=r.isMeshStandardMaterial?t.environment:null,s=E===null?S.outputColorSpace:E.isXRRenderTarget===!0?E.texture.colorSpace:Le,c=(r.isMeshStandardMaterial?we:Ce).get(r.envMap||o),l=r.vertexColors===!0&&!!n.attributes.color&&n.attributes.color.itemSize===4,u=!!n.attributes.tangent&&(!!r.normalMap||r.anisotropy>0),d=!!n.morphAttributes.position,f=!!n.morphAttributes.normal,p=!!n.morphAttributes.color,m=0;r.toneMapped&&(E===null||E.isXRRenderTarget===!0)&&(m=S.toneMapping);let h=n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color,g=h===void 0?0:h.length,_=P.get(r),v=y.state.lights;if(de===!0&&(fe===!0||e!==ee)){let t=e===ee&&r.id===D;Me.setState(r,e,t)}let b=!1;r.version===_.__version?_.needsLights&&_.lightsStateVersion!==v.state.version?b=!0:_.outputColorSpace===s?i.isBatchedMesh&&_.batching===!1||!i.isBatchedMesh&&_.batching===!0||i.isBatchedMesh&&_.batchingColor===!0&&i.colorTexture===null||i.isBatchedMesh&&_.batchingColor===!1&&i.colorTexture!==null||i.isInstancedMesh&&_.instancing===!1||!i.isInstancedMesh&&_.instancing===!0||i.isSkinnedMesh&&_.skinning===!1||!i.isSkinnedMesh&&_.skinning===!0||i.isInstancedMesh&&_.instancingColor===!0&&i.instanceColor===null||i.isInstancedMesh&&_.instancingColor===!1&&i.instanceColor!==null||i.isInstancedMesh&&_.instancingMorph===!0&&i.morphTexture===null||i.isInstancedMesh&&_.instancingMorph===!1&&i.morphTexture!==null?b=!0:_.envMap===c?r.fog===!0&&_.fog!==a||_.numClippingPlanes!==void 0&&(_.numClippingPlanes!==Me.numPlanes||_.numIntersection!==Me.numIntersection)?b=!0:_.vertexAlphas===l&&_.vertexTangents===u&&_.morphTargets===d&&_.morphNormals===f&&_.morphColors===p&&_.toneMapping===m?_.morphTargetsCount!==g&&(b=!0):b=!0:b=!0:b=!0:(b=!0,_.__version=r.version);let x=_.currentProgram;b===!0&&(x=ct(r,t,i));let C=!1,w=!1,T=!1,O=x.getUniforms(),k=_.uniforms;if(N.useProgram(x.program)&&(C=!0,w=!0,T=!0),r.id!==D&&(D=r.id,w=!0),C||ee!==e){N.buffers.depth.getReversed()&&e.reversedDepth!==!0&&(e._reversedDepth=!0,e.updateProjectionMatrix()),O.setValue(M,`projectionMatrix`,e.projectionMatrix),O.setValue(M,`viewMatrix`,e.matrixWorldInverse);let t=O.map.cameraPosition;t!==void 0&&t.setValue(M,me.setFromMatrixPosition(e.matrixWorld)),xe.logarithmicDepthBuffer&&O.setValue(M,`logDepthBufFC`,2/(Math.log(e.far+1)/Math.LN2)),(r.isMeshPhongMaterial||r.isMeshToonMaterial||r.isMeshLambertMaterial||r.isMeshBasicMaterial||r.isMeshStandardMaterial||r.isShaderMaterial)&&O.setValue(M,`isOrthographic`,e.isOrthographicCamera===!0),ee!==e&&(ee=e,w=!0,T=!0)}if(i.isSkinnedMesh){O.setOptional(M,i,`bindMatrix`),O.setOptional(M,i,`bindMatrixInverse`);let e=i.skeleton;e&&(e.boneTexture===null&&e.computeBoneTexture(),O.setValue(M,`boneTexture`,e.boneTexture,F))}i.isBatchedMesh&&(O.setOptional(M,i,`batchingTexture`),O.setValue(M,`batchingTexture`,i._matricesTexture,F),O.setOptional(M,i,`batchingIdTexture`),O.setValue(M,`batchingIdTexture`,i._indirectTexture,F),O.setOptional(M,i,`batchingColorTexture`),i._colorsTexture!==null&&O.setValue(M,`batchingColorTexture`,i._colorsTexture,F));let te=n.morphAttributes;if((te.position!==void 0||te.normal!==void 0||te.color!==void 0)&&Fe.update(i,n,x),(w||_.receiveShadow!==i.receiveShadow)&&(_.receiveShadow=i.receiveShadow,O.setValue(M,`receiveShadow`,i.receiveShadow)),r.isMeshGouraudMaterial&&r.envMap!==null&&(k.envMap.value=c,k.flipEnvMap.value=c.isCubeTexture&&c.isRenderTargetTexture===!1?-1:1),r.isMeshStandardMaterial&&r.envMap===null&&t.environment!==null&&(k.envMapIntensity.value=t.environmentIntensity),w&&(O.setValue(M,`toneMappingExposure`,S.toneMappingExposure),_.needsLights&&ft(k,T),a&&r.fog===!0&&ke.refreshFogUniforms(k,a),ke.refreshMaterialUniforms(k,r,j,ie,y.state.transmissionRenderTarget[e.id]),fc.upload(M,lt(_),k,F)),r.isShaderMaterial&&r.uniformsNeedUpdate===!0&&(fc.upload(M,lt(_),k,F),r.uniformsNeedUpdate=!1),r.isSpriteMaterial&&O.setValue(M,`center`,i.center),O.setValue(M,`modelViewMatrix`,i.modelViewMatrix),O.setValue(M,`normalMatrix`,i.normalMatrix),O.setValue(M,`modelMatrix`,i.matrixWorld),r.isShaderMaterial||r.isRawShaderMaterial){let e=r.uniformsGroups;for(let t=0,n=e.length;t<n;t++){let n=e[t];Ue.update(n,x),Ue.bind(n,x)}}return x}function ft(e,t){e.ambientLightColor.needsUpdate=t,e.lightProbe.needsUpdate=t,e.directionalLights.needsUpdate=t,e.directionalLightShadows.needsUpdate=t,e.pointLights.needsUpdate=t,e.pointLightShadows.needsUpdate=t,e.spotLights.needsUpdate=t,e.spotLightShadows.needsUpdate=t,e.rectAreaLights.needsUpdate=t,e.hemisphereLights.needsUpdate=t}function pt(e){return e.isMeshLambertMaterial||e.isMeshToonMaterial||e.isMeshPhongMaterial||e.isMeshStandardMaterial||e.isShadowMaterial||e.isShaderMaterial&&e.lights===!0}this.getActiveCubeFace=function(){return w},this.getActiveMipmapLevel=function(){return T},this.getRenderTarget=function(){return E},this.setRenderTargetTextures=function(e,t,n){let r=P.get(e);r.__autoAllocateDepthBuffer=e.resolveDepthBuffer===!1,r.__autoAllocateDepthBuffer===!1&&(r.__useRenderToTexture=!1),P.get(e.texture).__webglTexture=t,P.get(e.depthTexture).__webglTexture=r.__autoAllocateDepthBuffer?void 0:n,r.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(e,t){let n=P.get(e);n.__webglFramebuffer=t,n.__useDefaultFramebuffer=t===void 0};let mt=M.createFramebuffer();this.setRenderTarget=function(e,t=0,n=0){E=e,w=t,T=n;let r=!0,i=null,a=!1,o=!1;if(e){let s=P.get(e);if(s.__useDefaultFramebuffer!==void 0)N.bindFramebuffer(M.FRAMEBUFFER,null),r=!1;else if(s.__webglFramebuffer===void 0)F.setupRenderTarget(e);else if(s.__hasExternalTextures)F.rebindTextures(e,P.get(e.texture).__webglTexture,P.get(e.depthTexture).__webglTexture);else if(e.depthBuffer){let t=e.depthTexture;if(s.__boundDepthTexture!==t){if(t!==null&&P.has(t)&&(e.width!==t.image.width||e.height!==t.image.height))throw Error(`WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.`);F.setupDepthRenderbuffer(e)}}let c=e.texture;(c.isData3DTexture||c.isDataArrayTexture||c.isCompressedArrayTexture)&&(o=!0);let l=P.get(e).__webglFramebuffer;e.isWebGLCubeRenderTarget?(i=Array.isArray(l[t])?l[t][n]:l[t],a=!0):i=e.samples>0&&F.useMultisampledRTT(e)===!1?P.get(e).__webglMultisampledFramebuffer:Array.isArray(l)?l[n]:l,O.copy(e.viewport),k.copy(e.scissor),te=e.scissorTest}else O.copy(se).multiplyScalar(j).floor(),k.copy(ce).multiplyScalar(j).floor(),te=le;if(n!==0&&(i=mt),N.bindFramebuffer(M.FRAMEBUFFER,i)&&r&&N.drawBuffers(e,i),N.viewport(O),N.scissor(k),N.setScissorTest(te),a){let r=P.get(e.texture);M.framebufferTexture2D(M.FRAMEBUFFER,M.COLOR_ATTACHMENT0,M.TEXTURE_CUBE_MAP_POSITIVE_X+t,r.__webglTexture,n)}else if(o){let r=t;for(let t=0;t<e.textures.length;t++){let i=P.get(e.textures[t]);M.framebufferTextureLayer(M.FRAMEBUFFER,M.COLOR_ATTACHMENT0+t,i.__webglTexture,n,r)}}else if(e!==null&&n!==0){let t=P.get(e.texture);M.framebufferTexture2D(M.FRAMEBUFFER,M.COLOR_ATTACHMENT0,M.TEXTURE_2D,t.__webglTexture,n)}D=-1},this.readRenderTargetPixels=function(e,t,n,r,i,a,o,s=0){if(!(e&&e.isWebGLRenderTarget)){console.error(`THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.`);return}let c=P.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&o!==void 0&&(c=c[o]),c){N.bindFramebuffer(M.FRAMEBUFFER,c);try{let o=e.textures[s],c=o.format,l=o.type;if(!xe.textureFormatReadable(c)){console.error(`THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.`);return}if(!xe.textureTypeReadable(l)){console.error(`THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.`);return}t>=0&&t<=e.width-r&&n>=0&&n<=e.height-i&&(e.textures.length>1&&M.readBuffer(M.COLOR_ATTACHMENT0+s),M.readPixels(t,n,r,i,Be.convert(c),Be.convert(l),a))}finally{let e=E===null?null:P.get(E).__webglFramebuffer;N.bindFramebuffer(M.FRAMEBUFFER,e)}}},this.readRenderTargetPixelsAsync=async function(e,t,n,r,i,a,o,s=0){if(!(e&&e.isWebGLRenderTarget))throw Error(`THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.`);let c=P.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&o!==void 0&&(c=c[o]),c)if(t>=0&&t<=e.width-r&&n>=0&&n<=e.height-i){N.bindFramebuffer(M.FRAMEBUFFER,c);let o=e.textures[s],l=o.format,u=o.type;if(!xe.textureFormatReadable(l))throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.`);if(!xe.textureTypeReadable(u))throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.`);let d=M.createBuffer();M.bindBuffer(M.PIXEL_PACK_BUFFER,d),M.bufferData(M.PIXEL_PACK_BUFFER,a.byteLength,M.STREAM_READ),e.textures.length>1&&M.readBuffer(M.COLOR_ATTACHMENT0+s),M.readPixels(t,n,r,i,Be.convert(l),Be.convert(u),0);let f=E===null?null:P.get(E).__webglFramebuffer;N.bindFramebuffer(M.FRAMEBUFFER,f);let p=M.fenceSync(M.SYNC_GPU_COMMANDS_COMPLETE,0);return M.flush(),await Tt(M,p,4),M.bindBuffer(M.PIXEL_PACK_BUFFER,d),M.getBufferSubData(M.PIXEL_PACK_BUFFER,0,a),M.deleteBuffer(d),M.deleteSync(p),a}else throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.`)},this.copyFramebufferToTexture=function(e,t=null,n=0){let r=2**-n,i=Math.floor(e.image.width*r),a=Math.floor(e.image.height*r),o=t===null?0:t.x,s=t===null?0:t.y;F.setTexture2D(e,0),M.copyTexSubImage2D(M.TEXTURE_2D,n,0,0,o,s,i,a),N.unbindTexture()};let ht=M.createFramebuffer(),L=M.createFramebuffer();this.copyTextureToTexture=function(e,t,n=null,r=null,i=0,a=null){a===null&&(i===0?a=0:(wt(`WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels.`),a=i,i=0));let o,s,c,l,u,d,f,p,m,h=e.isCompressedTexture?e.mipmaps[a]:e.image;if(n!==null)o=n.max.x-n.min.x,s=n.max.y-n.min.y,c=n.isBox3?n.max.z-n.min.z:1,l=n.min.x,u=n.min.y,d=n.isBox3?n.min.z:0;else{let t=2**-i;o=Math.floor(h.width*t),s=Math.floor(h.height*t),c=e.isDataArrayTexture?h.depth:e.isData3DTexture?Math.floor(h.depth*t):1,l=0,u=0,d=0}r===null?(f=0,p=0,m=0):(f=r.x,p=r.y,m=r.z);let g=Be.convert(t.format),_=Be.convert(t.type),v;t.isData3DTexture?(F.setTexture3D(t,0),v=M.TEXTURE_3D):t.isDataArrayTexture||t.isCompressedArrayTexture?(F.setTexture2DArray(t,0),v=M.TEXTURE_2D_ARRAY):(F.setTexture2D(t,0),v=M.TEXTURE_2D),M.pixelStorei(M.UNPACK_FLIP_Y_WEBGL,t.flipY),M.pixelStorei(M.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),M.pixelStorei(M.UNPACK_ALIGNMENT,t.unpackAlignment);let y=M.getParameter(M.UNPACK_ROW_LENGTH),b=M.getParameter(M.UNPACK_IMAGE_HEIGHT),x=M.getParameter(M.UNPACK_SKIP_PIXELS),S=M.getParameter(M.UNPACK_SKIP_ROWS),C=M.getParameter(M.UNPACK_SKIP_IMAGES);M.pixelStorei(M.UNPACK_ROW_LENGTH,h.width),M.pixelStorei(M.UNPACK_IMAGE_HEIGHT,h.height),M.pixelStorei(M.UNPACK_SKIP_PIXELS,l),M.pixelStorei(M.UNPACK_SKIP_ROWS,u),M.pixelStorei(M.UNPACK_SKIP_IMAGES,d);let w=e.isDataArrayTexture||e.isData3DTexture,T=t.isDataArrayTexture||t.isData3DTexture;if(e.isDepthTexture){let n=P.get(e),r=P.get(t),h=P.get(n.__renderTarget),g=P.get(r.__renderTarget);N.bindFramebuffer(M.READ_FRAMEBUFFER,h.__webglFramebuffer),N.bindFramebuffer(M.DRAW_FRAMEBUFFER,g.__webglFramebuffer);for(let n=0;n<c;n++)w&&(M.framebufferTextureLayer(M.READ_FRAMEBUFFER,M.COLOR_ATTACHMENT0,P.get(e).__webglTexture,i,d+n),M.framebufferTextureLayer(M.DRAW_FRAMEBUFFER,M.COLOR_ATTACHMENT0,P.get(t).__webglTexture,a,m+n)),M.blitFramebuffer(l,u,o,s,f,p,o,s,M.DEPTH_BUFFER_BIT,M.NEAREST);N.bindFramebuffer(M.READ_FRAMEBUFFER,null),N.bindFramebuffer(M.DRAW_FRAMEBUFFER,null)}else if(i!==0||e.isRenderTargetTexture||P.has(e)){let n=P.get(e),r=P.get(t);N.bindFramebuffer(M.READ_FRAMEBUFFER,ht),N.bindFramebuffer(M.DRAW_FRAMEBUFFER,L);for(let e=0;e<c;e++)w?M.framebufferTextureLayer(M.READ_FRAMEBUFFER,M.COLOR_ATTACHMENT0,n.__webglTexture,i,d+e):M.framebufferTexture2D(M.READ_FRAMEBUFFER,M.COLOR_ATTACHMENT0,M.TEXTURE_2D,n.__webglTexture,i),T?M.framebufferTextureLayer(M.DRAW_FRAMEBUFFER,M.COLOR_ATTACHMENT0,r.__webglTexture,a,m+e):M.framebufferTexture2D(M.DRAW_FRAMEBUFFER,M.COLOR_ATTACHMENT0,M.TEXTURE_2D,r.__webglTexture,a),i===0?T?M.copyTexSubImage3D(v,a,f,p,m+e,l,u,o,s):M.copyTexSubImage2D(v,a,f,p,l,u,o,s):M.blitFramebuffer(l,u,o,s,f,p,o,s,M.COLOR_BUFFER_BIT,M.NEAREST);N.bindFramebuffer(M.READ_FRAMEBUFFER,null),N.bindFramebuffer(M.DRAW_FRAMEBUFFER,null)}else T?e.isDataTexture||e.isData3DTexture?M.texSubImage3D(v,a,f,p,m,o,s,c,g,_,h.data):t.isCompressedArrayTexture?M.compressedTexSubImage3D(v,a,f,p,m,o,s,c,g,h.data):M.texSubImage3D(v,a,f,p,m,o,s,c,g,_,h):e.isDataTexture?M.texSubImage2D(M.TEXTURE_2D,a,f,p,o,s,g,_,h.data):e.isCompressedTexture?M.compressedTexSubImage2D(M.TEXTURE_2D,a,f,p,h.width,h.height,g,h.data):M.texSubImage2D(M.TEXTURE_2D,a,f,p,o,s,g,_,h);M.pixelStorei(M.UNPACK_ROW_LENGTH,y),M.pixelStorei(M.UNPACK_IMAGE_HEIGHT,b),M.pixelStorei(M.UNPACK_SKIP_PIXELS,x),M.pixelStorei(M.UNPACK_SKIP_ROWS,S),M.pixelStorei(M.UNPACK_SKIP_IMAGES,C),a===0&&t.generateMipmaps&&M.generateMipmap(v),N.unbindTexture()},this.initRenderTarget=function(e){P.get(e).__webglFramebuffer===void 0&&F.setupRenderTarget(e)},this.initTexture=function(e){e.isCubeTexture?F.setTextureCube(e,0):e.isData3DTexture?F.setTexture3D(e,0):e.isDataArrayTexture||e.isCompressedArrayTexture?F.setTexture2DArray(e,0):F.setTexture2D(e,0),N.unbindTexture()},this.resetState=function(){w=0,T=0,E=null,N.reset(),Ve.reset()},typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`observe`,{detail:this}))}get coordinateSystem(){return He}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;let t=this.getContext();t.drawingBufferColorSpace=kt._getDrawingBufferColorSpace(e),t.unpackColorSpace=kt._getUnpackColorSpace()}},Sl={LEFT:1,RIGHT:2,MIDDLE:4},G=Object.freeze({NONE:0,ROTATE:1,TRUCK:2,SCREEN_PAN:4,OFFSET:8,DOLLY:16,ZOOM:32,TOUCH_ROTATE:64,TOUCH_TRUCK:128,TOUCH_SCREEN_PAN:256,TOUCH_OFFSET:512,TOUCH_DOLLY:1024,TOUCH_ZOOM:2048,TOUCH_DOLLY_TRUCK:4096,TOUCH_DOLLY_SCREEN_PAN:8192,TOUCH_DOLLY_OFFSET:16384,TOUCH_DOLLY_ROTATE:32768,TOUCH_ZOOM_TRUCK:65536,TOUCH_ZOOM_OFFSET:131072,TOUCH_ZOOM_SCREEN_PAN:262144,TOUCH_ZOOM_ROTATE:524288}),Cl={NONE:0,IN:1,OUT:-1};function wl(e){return e.isPerspectiveCamera}function Tl(e){return e.isOrthographicCamera}var El=Math.PI*2,Dl=Math.PI/2,Ol=1e-5,kl=Math.PI/180;function Al(e,t,n){return Math.max(t,Math.min(n,e))}function jl(e,t=Ol){return Math.abs(e)<t}function Ml(e,t,n=Ol){return jl(e-t,n)}function Nl(e,t){return Math.round(e/t)*t}function Pl(e){return isFinite(e)?e:e<0?-Number.MAX_VALUE:Number.MAX_VALUE}function Fl(e){return Math.abs(e)<Number.MAX_VALUE?e:e*(1/0)}function Il(e,t,n,r,i=1/0,a){r=Math.max(1e-4,r);let o=2/r,s=o*a,c=1/(1+s+.48*s*s+.235*s*s*s),l=e-t,u=t,d=i*r;l=Al(l,-d,d),t=e-l;let f=(n.value+o*l)*a;n.value=(n.value-o*f)*c;let p=t+(l+f)*c;return u-e>0==p>u&&(p=u,n.value=(p-u)/a),p}function Ll(e,t,n,r,i=1/0,a,o){r=Math.max(1e-4,r);let s=2/r,c=s*a,l=1/(1+c+.48*c*c+.235*c*c*c),u=t.x,d=t.y,f=t.z,p=e.x-u,m=e.y-d,h=e.z-f,g=u,_=d,v=f,y=i*r,b=y*y,x=p*p+m*m+h*h;if(x>b){let e=Math.sqrt(x);p=p/e*y,m=m/e*y,h=h/e*y}u=e.x-p,d=e.y-m,f=e.z-h;let S=(n.x+s*p)*a,C=(n.y+s*m)*a,w=(n.z+s*h)*a;n.x=(n.x-s*S)*l,n.y=(n.y-s*C)*l,n.z=(n.z-s*w)*l,o.x=u+(p+S)*l,o.y=d+(m+C)*l,o.z=f+(h+w)*l;let T=g-e.x,E=_-e.y,D=v-e.z,ee=o.x-g,O=o.y-_,k=o.z-v;return T*ee+E*O+D*k>0&&(o.x=g,o.y=_,o.z=v,n.x=(o.x-g)/a,n.y=(o.y-_)/a,n.z=(o.z-v)/a),o}function Rl(e,t){t.set(0,0),e.forEach(e=>{t.x+=e.clientX,t.y+=e.clientY}),t.x/=e.length,t.y/=e.length}function zl(e,t){return Tl(e)?(console.warn(`${t} is not supported in OrthographicCamera`),!0):!1}var Bl=class{_listeners={};addEventListener(e,t){let n=this._listeners;n[e]===void 0&&(n[e]=[]),n[e].indexOf(t)===-1&&n[e].push(t)}hasEventListener(e,t){let n=this._listeners;return n[e]!==void 0&&n[e].indexOf(t)!==-1}removeEventListener(e,t){let n=this._listeners[e];if(n!==void 0){let e=n.indexOf(t);e!==-1&&n.splice(e,1)}}removeAllEventListeners(e){if(!e){this._listeners={};return}Array.isArray(this._listeners[e])&&(this._listeners[e].length=0)}dispatchEvent(e){let t=this._listeners[e.type];if(t!==void 0){e.target=this;let n=t.slice(0);for(let t=0,r=n.length;t<r;t++)n[t].call(this,e)}}},Vl=`3.1.2`,Hl=1/8,Ul=/Mac/.test(globalThis?.navigator?.platform),K,Wl,Gl,Kl,ql,q,Jl,Yl,Xl,Zl,Ql,$l,eu,tu,nu,ru,iu,au,ou,su,cu,lu,uu,du=class e extends Bl{static install(e){K=e.THREE,Wl=Object.freeze(new K.Vector3(0,0,0)),Gl=Object.freeze(new K.Vector3(0,1,0)),Kl=Object.freeze(new K.Vector3(0,0,1)),ql=new K.Vector2,q=new K.Vector3,Jl=new K.Vector3,Yl=new K.Vector3,Xl=new K.Vector3,Zl=new K.Vector3,Ql=new K.Vector3,$l=new K.Vector3,eu=new K.Vector3,tu=new K.Vector3,nu=new K.Spherical,ru=new K.Spherical,iu=new K.Box3,au=new K.Box3,ou=new K.Sphere,su=new K.Quaternion,cu=new K.Quaternion,lu=new K.Matrix4,uu=new K.Raycaster}static get ACTION(){return G}minPolarAngle=0;maxPolarAngle=Math.PI;minAzimuthAngle=-1/0;maxAzimuthAngle=1/0;minDistance=2**-52;maxDistance=1/0;infinityDolly=!1;minZoom=.01;maxZoom=1/0;smoothTime=.25;draggingSmoothTime=.125;maxSpeed=1/0;azimuthRotateSpeed=1;polarRotateSpeed=1;dollySpeed=1;dollyDragInverted=!1;truckSpeed=2;dollyToCursor=!1;dragToOffset=!1;boundaryFriction=0;restThreshold=.01;colliderMeshes=[];mouseButtons;touches;cancel=()=>{};lockPointer;unlockPointer;_enabled=!0;_camera;_yAxisUpSpace;_yAxisUpSpaceInverse;_state=G.NONE;_domElement;_viewport=null;_target;_targetEnd;_focalOffset;_focalOffsetEnd;_spherical;_sphericalEnd;_lastDistance;_zoom;_zoomEnd;_lastZoom;_cameraUp0;_target0;_position0;_zoom0;_focalOffset0;_dollyControlCoord;_changedDolly=0;_changedZoom=0;_nearPlaneCorners;_hasRested=!0;_boundary;_boundaryEnclosesCamera=!1;_needsUpdate=!0;_updatedLastTime=!1;_elementRect=new DOMRect;_isDragging=!1;_dragNeedsUpdate=!0;_activePointers=[];_lockedPointer=null;_interactiveArea=new DOMRect(0,0,1,1);_isUserControllingRotate=!1;_isUserControllingDolly=!1;_isUserControllingTruck=!1;_isUserControllingOffset=!1;_isUserControllingZoom=!1;_lastDollyDirection=Cl.NONE;_thetaVelocity={value:0};_phiVelocity={value:0};_radiusVelocity={value:0};_targetVelocity=new K.Vector3;_focalOffsetVelocity=new K.Vector3;_zoomVelocity={value:0};set verticalDragToForward(e){console.warn("camera-controls: `verticalDragToForward` was removed. Use `mouseButtons.left = CameraControls.ACTION.SCREEN_PAN` instead.")}constructor(t,n){super(),K===void 0&&console.error("camera-controls: `THREE` is undefined. You must first run `CameraControls.install( { THREE: THREE } )`. Check the docs for further information."),this._camera=t,this._yAxisUpSpace=new K.Quaternion().setFromUnitVectors(this._camera.up,Gl),this._yAxisUpSpaceInverse=this._yAxisUpSpace.clone().invert(),this._state=G.NONE,this._target=new K.Vector3,this._targetEnd=this._target.clone(),this._focalOffset=new K.Vector3,this._focalOffsetEnd=this._focalOffset.clone(),this._spherical=new K.Spherical().setFromVector3(q.copy(this._camera.position).applyQuaternion(this._yAxisUpSpace)),this._sphericalEnd=this._spherical.clone(),this._lastDistance=this._spherical.radius,this._zoom=this._camera.zoom,this._zoomEnd=this._zoom,this._lastZoom=this._zoom,this._nearPlaneCorners=[new K.Vector3,new K.Vector3,new K.Vector3,new K.Vector3],this._updateNearPlaneCorners(),this._boundary=new K.Box3(new K.Vector3(-1/0,-1/0,-1/0),new K.Vector3(1/0,1/0,1/0)),this._cameraUp0=this._camera.up.clone(),this._target0=this._target.clone(),this._position0=this._camera.position.clone(),this._zoom0=this._zoom,this._focalOffset0=this._focalOffset.clone(),this._dollyControlCoord=new K.Vector2,this.mouseButtons={left:G.ROTATE,middle:G.DOLLY,right:G.TRUCK,wheel:wl(this._camera)?G.DOLLY:Tl(this._camera)?G.ZOOM:G.NONE},this.touches={one:G.TOUCH_ROTATE,two:wl(this._camera)?G.TOUCH_DOLLY_TRUCK:Tl(this._camera)?G.TOUCH_ZOOM_TRUCK:G.NONE,three:G.TOUCH_TRUCK};let r=new K.Vector2,i=new K.Vector2,a=new K.Vector2,o=e=>{if(!this._enabled||!this._domElement)return;if(this._interactiveArea.left!==0||this._interactiveArea.top!==0||this._interactiveArea.width!==1||this._interactiveArea.height!==1){let t=this._domElement.getBoundingClientRect(),n=e.clientX/t.width,r=e.clientY/t.height;if(n<this._interactiveArea.left||n>this._interactiveArea.right||r<this._interactiveArea.top||r>this._interactiveArea.bottom)return}let t=e.pointerType===`mouse`?(e.buttons&Sl.LEFT)===Sl.LEFT?Sl.LEFT:(e.buttons&Sl.MIDDLE)===Sl.MIDDLE?Sl.MIDDLE:(e.buttons&Sl.RIGHT)===Sl.RIGHT?Sl.RIGHT:null:null;if(t!==null){let e=this._findPointerByMouseButton(t);e&&this._disposePointer(e)}if((e.buttons&Sl.LEFT)===Sl.LEFT&&this._lockedPointer)return;let n={pointerId:e.pointerId,clientX:e.clientX,clientY:e.clientY,deltaX:0,deltaY:0,mouseButton:t};this._activePointers.push(n),this._domElement.ownerDocument.removeEventListener(`pointermove`,s,{passive:!1}),this._domElement.ownerDocument.removeEventListener(`pointerup`,c),this._domElement.ownerDocument.addEventListener(`pointermove`,s,{passive:!1}),this._domElement.ownerDocument.addEventListener(`pointerup`,c),this._isDragging=!0,f(e)},s=e=>{e.cancelable&&e.preventDefault();let t=e.pointerId,n=this._lockedPointer||this._findPointerById(t);if(n){if(n.clientX=e.clientX,n.clientY=e.clientY,n.deltaX=e.movementX,n.deltaY=e.movementY,this._state=0,e.pointerType===`touch`)switch(this._activePointers.length){case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else (!this._isDragging&&this._lockedPointer||this._isDragging&&(e.buttons&Sl.LEFT)===Sl.LEFT)&&(this._state|=this.mouseButtons.left),this._isDragging&&(e.buttons&Sl.MIDDLE)===Sl.MIDDLE&&(this._state|=this.mouseButtons.middle),this._isDragging&&(e.buttons&Sl.RIGHT)===Sl.RIGHT&&(this._state|=this.mouseButtons.right);p()}},c=e=>{let t=this._findPointerById(e.pointerId);if(!(t&&t===this._lockedPointer)){if(t&&this._disposePointer(t),e.pointerType===`touch`)switch(this._activePointers.length){case 0:this._state=G.NONE;break;case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else this._state=G.NONE;m()}},l=-1,u=e=>{if(!this._domElement||!this._enabled||this.mouseButtons.wheel===G.NONE)return;if(this._interactiveArea.left!==0||this._interactiveArea.top!==0||this._interactiveArea.width!==1||this._interactiveArea.height!==1){let t=this._domElement.getBoundingClientRect(),n=e.clientX/t.width,r=e.clientY/t.height;if(n<this._interactiveArea.left||n>this._interactiveArea.right||r<this._interactiveArea.top||r>this._interactiveArea.bottom)return}if(e.preventDefault(),this.dollyToCursor||this.mouseButtons.wheel===G.ROTATE||this.mouseButtons.wheel===G.TRUCK){let e=performance.now();l-e<1e3&&this._getClientRect(this._elementRect),l=e}let t=Ul?-1:-3,n=e.deltaMode===1&&!e.ctrlKey?e.deltaY/t:e.deltaY/(t*10),r=this.dollyToCursor?(e.clientX-this._elementRect.x)/this._elementRect.width*2-1:0,i=this.dollyToCursor?(e.clientY-this._elementRect.y)/this._elementRect.height*-2+1:0;switch(e.ctrlKey?G.ZOOM:this.mouseButtons.wheel){case G.ROTATE:this._rotateInternal(e.deltaX,e.deltaY),this._isUserControllingRotate=!0;break;case G.TRUCK:this._truckInternal(e.deltaX,e.deltaY,!1,!1),this._isUserControllingTruck=!0;break;case G.SCREEN_PAN:this._truckInternal(e.deltaX,e.deltaY,!1,!0),this._isUserControllingTruck=!0;break;case G.OFFSET:this._truckInternal(e.deltaX,e.deltaY,!0,!1),this._isUserControllingOffset=!0;break;case G.DOLLY:this._dollyInternal(-n,r,i),this._isUserControllingDolly=!0;break;case G.ZOOM:this._zoomInternal(-n,r,i),this._isUserControllingZoom=!0;break}this.dispatchEvent({type:`control`})},d=t=>{if(!(!this._domElement||!this._enabled)){if(this.mouseButtons.right===e.ACTION.NONE){let e=t instanceof PointerEvent?t.pointerId:0,n=this._findPointerById(e);n&&this._disposePointer(n),this._domElement.ownerDocument.removeEventListener(`pointermove`,s,{passive:!1}),this._domElement.ownerDocument.removeEventListener(`pointerup`,c);return}t.preventDefault()}},f=e=>{if(this._enabled){if(Rl(this._activePointers,ql),this._getClientRect(this._elementRect),r.copy(ql),i.copy(ql),this._activePointers.length>=2){let e=ql.x-this._activePointers[1].clientX,t=ql.y-this._activePointers[1].clientY,n=Math.sqrt(e*e+t*t);a.set(0,n);let r=(this._activePointers[0].clientX+this._activePointers[1].clientX)*.5,o=(this._activePointers[0].clientY+this._activePointers[1].clientY)*.5;i.set(r,o)}if(this._state=0,!e)this._lockedPointer&&(this._state|=this.mouseButtons.left);else if(`pointerType`in e&&e.pointerType===`touch`)switch(this._activePointers.length){case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else !this._lockedPointer&&(e.buttons&Sl.LEFT)===Sl.LEFT&&(this._state|=this.mouseButtons.left),(e.buttons&Sl.MIDDLE)===Sl.MIDDLE&&(this._state|=this.mouseButtons.middle),(e.buttons&Sl.RIGHT)===Sl.RIGHT&&(this._state|=this.mouseButtons.right);((this._state&G.ROTATE)===G.ROTATE||(this._state&G.TOUCH_ROTATE)===G.TOUCH_ROTATE||(this._state&G.TOUCH_DOLLY_ROTATE)===G.TOUCH_DOLLY_ROTATE||(this._state&G.TOUCH_ZOOM_ROTATE)===G.TOUCH_ZOOM_ROTATE)&&(this._sphericalEnd.theta=this._spherical.theta,this._sphericalEnd.phi=this._spherical.phi,this._thetaVelocity.value=0,this._phiVelocity.value=0),((this._state&G.TRUCK)===G.TRUCK||(this._state&G.SCREEN_PAN)===G.SCREEN_PAN||(this._state&G.TOUCH_TRUCK)===G.TOUCH_TRUCK||(this._state&G.TOUCH_SCREEN_PAN)===G.TOUCH_SCREEN_PAN||(this._state&G.TOUCH_DOLLY_TRUCK)===G.TOUCH_DOLLY_TRUCK||(this._state&G.TOUCH_DOLLY_SCREEN_PAN)===G.TOUCH_DOLLY_SCREEN_PAN||(this._state&G.TOUCH_ZOOM_TRUCK)===G.TOUCH_ZOOM_TRUCK||(this._state&G.TOUCH_ZOOM_SCREEN_PAN)===G.TOUCH_DOLLY_SCREEN_PAN)&&(this._targetEnd.copy(this._target),this._targetVelocity.set(0,0,0)),((this._state&G.DOLLY)===G.DOLLY||(this._state&G.TOUCH_DOLLY)===G.TOUCH_DOLLY||(this._state&G.TOUCH_DOLLY_TRUCK)===G.TOUCH_DOLLY_TRUCK||(this._state&G.TOUCH_DOLLY_SCREEN_PAN)===G.TOUCH_DOLLY_SCREEN_PAN||(this._state&G.TOUCH_DOLLY_OFFSET)===G.TOUCH_DOLLY_OFFSET||(this._state&G.TOUCH_DOLLY_ROTATE)===G.TOUCH_DOLLY_ROTATE)&&(this._sphericalEnd.radius=this._spherical.radius,this._radiusVelocity.value=0),((this._state&G.ZOOM)===G.ZOOM||(this._state&G.TOUCH_ZOOM)===G.TOUCH_ZOOM||(this._state&G.TOUCH_ZOOM_TRUCK)===G.TOUCH_ZOOM_TRUCK||(this._state&G.TOUCH_ZOOM_SCREEN_PAN)===G.TOUCH_ZOOM_SCREEN_PAN||(this._state&G.TOUCH_ZOOM_OFFSET)===G.TOUCH_ZOOM_OFFSET||(this._state&G.TOUCH_ZOOM_ROTATE)===G.TOUCH_ZOOM_ROTATE)&&(this._zoomEnd=this._zoom,this._zoomVelocity.value=0),((this._state&G.OFFSET)===G.OFFSET||(this._state&G.TOUCH_OFFSET)===G.TOUCH_OFFSET||(this._state&G.TOUCH_DOLLY_OFFSET)===G.TOUCH_DOLLY_OFFSET||(this._state&G.TOUCH_ZOOM_OFFSET)===G.TOUCH_ZOOM_OFFSET)&&(this._focalOffsetEnd.copy(this._focalOffset),this._focalOffsetVelocity.set(0,0,0)),this.dispatchEvent({type:`controlstart`})}},p=()=>{if(!this._enabled||!this._dragNeedsUpdate)return;this._dragNeedsUpdate=!1,Rl(this._activePointers,ql);let e=this._domElement&&this._domElement.ownerDocument.pointerLockElement===this._domElement?this._lockedPointer||this._activePointers[0]:null,t=e?-e.deltaX:i.x-ql.x,n=e?-e.deltaY:i.y-ql.y;if(i.copy(ql),((this._state&G.ROTATE)===G.ROTATE||(this._state&G.TOUCH_ROTATE)===G.TOUCH_ROTATE||(this._state&G.TOUCH_DOLLY_ROTATE)===G.TOUCH_DOLLY_ROTATE||(this._state&G.TOUCH_ZOOM_ROTATE)===G.TOUCH_ZOOM_ROTATE)&&(this._rotateInternal(t,n),this._isUserControllingRotate=!0),(this._state&G.DOLLY)===G.DOLLY||(this._state&G.ZOOM)===G.ZOOM){let e=this.dollyToCursor?(r.x-this._elementRect.x)/this._elementRect.width*2-1:0,t=this.dollyToCursor?(r.y-this._elementRect.y)/this._elementRect.height*-2+1:0,i=this.dollyDragInverted?-1:1;(this._state&G.DOLLY)===G.DOLLY?(this._dollyInternal(i*n*Hl,e,t),this._isUserControllingDolly=!0):(this._zoomInternal(i*n*Hl,e,t),this._isUserControllingZoom=!0)}if((this._state&G.TOUCH_DOLLY)===G.TOUCH_DOLLY||(this._state&G.TOUCH_ZOOM)===G.TOUCH_ZOOM||(this._state&G.TOUCH_DOLLY_TRUCK)===G.TOUCH_DOLLY_TRUCK||(this._state&G.TOUCH_ZOOM_TRUCK)===G.TOUCH_ZOOM_TRUCK||(this._state&G.TOUCH_DOLLY_SCREEN_PAN)===G.TOUCH_DOLLY_SCREEN_PAN||(this._state&G.TOUCH_ZOOM_SCREEN_PAN)===G.TOUCH_ZOOM_SCREEN_PAN||(this._state&G.TOUCH_DOLLY_OFFSET)===G.TOUCH_DOLLY_OFFSET||(this._state&G.TOUCH_ZOOM_OFFSET)===G.TOUCH_ZOOM_OFFSET||(this._state&G.TOUCH_DOLLY_ROTATE)===G.TOUCH_DOLLY_ROTATE||(this._state&G.TOUCH_ZOOM_ROTATE)===G.TOUCH_ZOOM_ROTATE){let e=ql.x-this._activePointers[1].clientX,t=ql.y-this._activePointers[1].clientY,n=Math.sqrt(e*e+t*t),r=a.y-n;a.set(0,n);let o=this.dollyToCursor?(i.x-this._elementRect.x)/this._elementRect.width*2-1:0,s=this.dollyToCursor?(i.y-this._elementRect.y)/this._elementRect.height*-2+1:0;(this._state&G.TOUCH_DOLLY)===G.TOUCH_DOLLY||(this._state&G.TOUCH_DOLLY_ROTATE)===G.TOUCH_DOLLY_ROTATE||(this._state&G.TOUCH_DOLLY_TRUCK)===G.TOUCH_DOLLY_TRUCK||(this._state&G.TOUCH_DOLLY_SCREEN_PAN)===G.TOUCH_DOLLY_SCREEN_PAN||(this._state&G.TOUCH_DOLLY_OFFSET)===G.TOUCH_DOLLY_OFFSET?(this._dollyInternal(r*Hl,o,s),this._isUserControllingDolly=!0):(this._zoomInternal(r*Hl,o,s),this._isUserControllingZoom=!0)}((this._state&G.TRUCK)===G.TRUCK||(this._state&G.TOUCH_TRUCK)===G.TOUCH_TRUCK||(this._state&G.TOUCH_DOLLY_TRUCK)===G.TOUCH_DOLLY_TRUCK||(this._state&G.TOUCH_ZOOM_TRUCK)===G.TOUCH_ZOOM_TRUCK)&&(this._truckInternal(t,n,!1,!1),this._isUserControllingTruck=!0),((this._state&G.SCREEN_PAN)===G.SCREEN_PAN||(this._state&G.TOUCH_SCREEN_PAN)===G.TOUCH_SCREEN_PAN||(this._state&G.TOUCH_DOLLY_SCREEN_PAN)===G.TOUCH_DOLLY_SCREEN_PAN||(this._state&G.TOUCH_ZOOM_SCREEN_PAN)===G.TOUCH_ZOOM_SCREEN_PAN)&&(this._truckInternal(t,n,!1,!0),this._isUserControllingTruck=!0),((this._state&G.OFFSET)===G.OFFSET||(this._state&G.TOUCH_OFFSET)===G.TOUCH_OFFSET||(this._state&G.TOUCH_DOLLY_OFFSET)===G.TOUCH_DOLLY_OFFSET||(this._state&G.TOUCH_ZOOM_OFFSET)===G.TOUCH_ZOOM_OFFSET)&&(this._truckInternal(t,n,!0,!1),this._isUserControllingOffset=!0),this.dispatchEvent({type:`control`})},m=()=>{Rl(this._activePointers,ql),i.copy(ql),this._dragNeedsUpdate=!1,(this._activePointers.length===0||this._activePointers.length===1&&this._activePointers[0]===this._lockedPointer)&&(this._isDragging=!1),this._activePointers.length===0&&this._domElement&&(this._domElement.ownerDocument.removeEventListener(`pointermove`,s,{passive:!1}),this._domElement.ownerDocument.removeEventListener(`pointerup`,c),this.dispatchEvent({type:`controlend`}))};this.lockPointer=()=>{!this._enabled||!this._domElement||(this.cancel(),this._lockedPointer={pointerId:-1,clientX:0,clientY:0,deltaX:0,deltaY:0,mouseButton:null},this._activePointers.push(this._lockedPointer),this._domElement.ownerDocument.removeEventListener(`pointermove`,s,{passive:!1}),this._domElement.ownerDocument.removeEventListener(`pointerup`,c),this._domElement.requestPointerLock(),this._domElement.ownerDocument.addEventListener(`pointerlockchange`,h),this._domElement.ownerDocument.addEventListener(`pointerlockerror`,g),this._domElement.ownerDocument.addEventListener(`pointermove`,s,{passive:!1}),this._domElement.ownerDocument.addEventListener(`pointerup`,c),f())},this.unlockPointer=()=>{this._lockedPointer!==null&&(this._disposePointer(this._lockedPointer),this._lockedPointer=null),this._domElement?.ownerDocument.exitPointerLock(),this._domElement?.ownerDocument.removeEventListener(`pointerlockchange`,h),this._domElement?.ownerDocument.removeEventListener(`pointerlockerror`,g),this.cancel()};let h=()=>{this._domElement&&this._domElement.ownerDocument.pointerLockElement===this._domElement||this.unlockPointer()},g=()=>{this.unlockPointer()};this._addAllEventListeners=e=>{this._domElement=e,this._domElement.style.touchAction=`none`,this._domElement.style.userSelect=`none`,this._domElement.style.webkitUserSelect=`none`,this._domElement.addEventListener(`pointerdown`,o),this._domElement.addEventListener(`pointercancel`,c),this._domElement.addEventListener(`wheel`,u,{passive:!1}),this._domElement.addEventListener(`contextmenu`,d)},this._removeAllEventListeners=()=>{this._domElement&&(this._domElement.style.touchAction=``,this._domElement.style.userSelect=``,this._domElement.style.webkitUserSelect=``,this._domElement.removeEventListener(`pointerdown`,o),this._domElement.removeEventListener(`pointercancel`,c),this._domElement.removeEventListener(`wheel`,u,{passive:!1}),this._domElement.removeEventListener(`contextmenu`,d),this._domElement.ownerDocument.removeEventListener(`pointermove`,s,{passive:!1}),this._domElement.ownerDocument.removeEventListener(`pointerup`,c),this._domElement.ownerDocument.removeEventListener(`pointerlockchange`,h),this._domElement.ownerDocument.removeEventListener(`pointerlockerror`,g))},this.cancel=()=>{this._state!==G.NONE&&(this._state=G.NONE,this._activePointers.length=0,m())},n&&this.connect(n),this.update(0)}get camera(){return this._camera}set camera(e){this._camera=e,this.updateCameraUp(),this._camera.updateProjectionMatrix(),this._updateNearPlaneCorners(),this._needsUpdate=!0}get enabled(){return this._enabled}set enabled(e){this._enabled=e,this._domElement&&(e?(this._domElement.style.touchAction=`none`,this._domElement.style.userSelect=`none`,this._domElement.style.webkitUserSelect=`none`):(this.cancel(),this._domElement.style.touchAction=``,this._domElement.style.userSelect=``,this._domElement.style.webkitUserSelect=``))}get active(){return!this._hasRested}get currentAction(){return this._state}get distance(){return this._spherical.radius}set distance(e){this._spherical.radius===e&&this._sphericalEnd.radius===e||(this._spherical.radius=e,this._sphericalEnd.radius=e,this._needsUpdate=!0)}get azimuthAngle(){return this._spherical.theta}set azimuthAngle(e){this._spherical.theta===e&&this._sphericalEnd.theta===e||(this._spherical.theta=e,this._sphericalEnd.theta=e,this._needsUpdate=!0)}get polarAngle(){return this._spherical.phi}set polarAngle(e){this._spherical.phi===e&&this._sphericalEnd.phi===e||(this._spherical.phi=e,this._sphericalEnd.phi=e,this._needsUpdate=!0)}get boundaryEnclosesCamera(){return this._boundaryEnclosesCamera}set boundaryEnclosesCamera(e){this._boundaryEnclosesCamera=e,this._needsUpdate=!0}set interactiveArea(e){this._interactiveArea.width=Al(e.width,0,1),this._interactiveArea.height=Al(e.height,0,1),this._interactiveArea.x=Al(e.x,0,1-this._interactiveArea.width),this._interactiveArea.y=Al(e.y,0,1-this._interactiveArea.height)}addEventListener(e,t){super.addEventListener(e,t)}removeEventListener(e,t){super.removeEventListener(e,t)}rotate(e,t,n=!1){return this.rotateTo(this._sphericalEnd.theta+e,this._sphericalEnd.phi+t,n)}rotateAzimuthTo(e,t=!1){return this.rotateTo(e,this._sphericalEnd.phi,t)}rotatePolarTo(e,t=!1){return this.rotateTo(this._sphericalEnd.theta,e,t)}rotateTo(e,t,n=!1){this._isUserControllingRotate=!1;let r=Al(e,this.minAzimuthAngle,this.maxAzimuthAngle),i=Al(t,this.minPolarAngle,this.maxPolarAngle);this._sphericalEnd.theta=r,this._sphericalEnd.phi=i,this._sphericalEnd.makeSafe(),this._needsUpdate=!0,n||(this._spherical.theta=this._sphericalEnd.theta,this._spherical.phi=this._sphericalEnd.phi);let a=!n||Ml(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Ml(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold);return this._createOnRestPromise(a)}dolly(e,t=!1){return this.dollyTo(this._sphericalEnd.radius-e,t)}dollyTo(e,t=!1){return this._isUserControllingDolly=!1,this._lastDollyDirection=Cl.NONE,this._changedDolly=0,this._dollyToNoClamp(Al(e,this.minDistance,this.maxDistance),t)}_dollyToNoClamp(e,t=!1){let n=this._sphericalEnd.radius;if(this.colliderMeshes.length>=1){let t=this._collisionTest(),r=Ml(t,this._spherical.radius);if(!(n>e)&&r)return Promise.resolve();this._sphericalEnd.radius=Math.min(e,t)}else this._sphericalEnd.radius=e;this._needsUpdate=!0,t||(this._spherical.radius=this._sphericalEnd.radius);let r=!t||Ml(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(r)}dollyInFixed(e,t=!1){this._targetEnd.add(this._getCameraDirection(Xl).multiplyScalar(e)),t||this._target.copy(this._targetEnd);let n=!t||Ml(this._target.x,this._targetEnd.x,this.restThreshold)&&Ml(this._target.y,this._targetEnd.y,this.restThreshold)&&Ml(this._target.z,this._targetEnd.z,this.restThreshold);return this._createOnRestPromise(n)}zoom(e,t=!1){return this.zoomTo(this._zoomEnd+e,t)}zoomTo(e,t=!1){this._isUserControllingZoom=!1,this._zoomEnd=Al(e,this.minZoom,this.maxZoom),this._needsUpdate=!0,t||(this._zoom=this._zoomEnd);let n=!t||Ml(this._zoom,this._zoomEnd,this.restThreshold);return this._changedZoom=0,this._createOnRestPromise(n)}pan(e,t,n=!1){return console.warn("`pan` has been renamed to `truck`"),this.truck(e,t,n)}truck(e,t,n=!1){this._camera.updateMatrix(),Zl.setFromMatrixColumn(this._camera.matrix,0),Ql.setFromMatrixColumn(this._camera.matrix,1),Zl.multiplyScalar(e),Ql.multiplyScalar(-t);let r=q.copy(Zl).add(Ql),i=Jl.copy(this._targetEnd).add(r);return this.moveTo(i.x,i.y,i.z,n)}forward(e,t=!1){q.setFromMatrixColumn(this._camera.matrix,0),q.crossVectors(this._camera.up,q),q.multiplyScalar(e);let n=Jl.copy(this._targetEnd).add(q);return this.moveTo(n.x,n.y,n.z,t)}elevate(e,t=!1){return q.copy(this._camera.up).multiplyScalar(e),this.moveTo(this._targetEnd.x+q.x,this._targetEnd.y+q.y,this._targetEnd.z+q.z,t)}moveTo(e,t,n,r=!1){this._isUserControllingTruck=!1;let i=q.set(e,t,n).sub(this._targetEnd);this._encloseToBoundary(this._targetEnd,i,this.boundaryFriction),this._needsUpdate=!0,r||this._target.copy(this._targetEnd);let a=!r||Ml(this._target.x,this._targetEnd.x,this.restThreshold)&&Ml(this._target.y,this._targetEnd.y,this.restThreshold)&&Ml(this._target.z,this._targetEnd.z,this.restThreshold);return this._createOnRestPromise(a)}lookInDirectionOf(e,t,n,r=!1){let i=q.set(e,t,n).sub(this._targetEnd).normalize().multiplyScalar(-this._sphericalEnd.radius).add(this._targetEnd);return this.setPosition(i.x,i.y,i.z,r)}fitToBox(e,t,{cover:n=!1,paddingLeft:r=0,paddingRight:i=0,paddingBottom:a=0,paddingTop:o=0}={}){let s=[],c=e.isBox3?iu.copy(e):iu.setFromObject(e);c.isEmpty()&&(console.warn(`camera-controls: fitTo() cannot be used with an empty box. Aborting`),Promise.resolve());let l=Nl(this._sphericalEnd.theta,Dl),u=Nl(this._sphericalEnd.phi,Dl);s.push(this.rotateTo(l,u,t));let d=q.setFromSpherical(this._sphericalEnd).normalize(),f=su.setFromUnitVectors(d,Kl),p=Ml(Math.abs(d.y),1);p&&f.multiply(cu.setFromAxisAngle(Gl,l)),f.multiply(this._yAxisUpSpaceInverse);let m=au.makeEmpty();Jl.copy(c.min).applyQuaternion(f),m.expandByPoint(Jl),Jl.copy(c.min).setX(c.max.x).applyQuaternion(f),m.expandByPoint(Jl),Jl.copy(c.min).setY(c.max.y).applyQuaternion(f),m.expandByPoint(Jl),Jl.copy(c.max).setZ(c.min.z).applyQuaternion(f),m.expandByPoint(Jl),Jl.copy(c.min).setZ(c.max.z).applyQuaternion(f),m.expandByPoint(Jl),Jl.copy(c.max).setY(c.min.y).applyQuaternion(f),m.expandByPoint(Jl),Jl.copy(c.max).setX(c.min.x).applyQuaternion(f),m.expandByPoint(Jl),Jl.copy(c.max).applyQuaternion(f),m.expandByPoint(Jl),m.min.x-=r,m.min.y-=a,m.max.x+=i,m.max.y+=o,f.setFromUnitVectors(Kl,d),p&&f.premultiply(cu.invert()),f.premultiply(this._yAxisUpSpace);let h=m.getSize(q),g=m.getCenter(Jl).applyQuaternion(f);if(wl(this._camera)){let e=this.getDistanceToFitBox(h.x,h.y,h.z,n);s.push(this.moveTo(g.x,g.y,g.z,t)),s.push(this.dollyTo(e,t)),s.push(this.setFocalOffset(0,0,0,t))}else if(Tl(this._camera)){let e=this._camera,r=e.right-e.left,i=e.top-e.bottom,a=n?Math.max(r/h.x,i/h.y):Math.min(r/h.x,i/h.y);s.push(this.moveTo(g.x,g.y,g.z,t)),s.push(this.zoomTo(a,t)),s.push(this.setFocalOffset(0,0,0,t))}return Promise.all(s)}fitToSphere(t,n){let r=[],i=`isObject3D`in t?e.createBoundingSphere(t,ou):ou.copy(t);if(r.push(this.moveTo(i.center.x,i.center.y,i.center.z,n)),wl(this._camera)){let e=this.getDistanceToFitSphere(i.radius);r.push(this.dollyTo(e,n))}else if(Tl(this._camera)){let e=this._camera.right-this._camera.left,t=this._camera.top-this._camera.bottom,a=2*i.radius,o=Math.min(e/a,t/a);r.push(this.zoomTo(o,n))}return r.push(this.setFocalOffset(0,0,0,n)),Promise.all(r)}setLookAt(e,t,n,r,i,a,o=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._lastDollyDirection=Cl.NONE,this._changedDolly=0;let s=Jl.set(r,i,a),c=q.set(e,t,n);this._targetEnd.copy(s),this._sphericalEnd.setFromVector3(c.sub(s).applyQuaternion(this._yAxisUpSpace)),this._needsUpdate=!0,o||(this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd));let l=!o||Ml(this._target.x,this._targetEnd.x,this.restThreshold)&&Ml(this._target.y,this._targetEnd.y,this.restThreshold)&&Ml(this._target.z,this._targetEnd.z,this.restThreshold)&&Ml(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Ml(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&Ml(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(l)}lerp(e,t,n,r=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._lastDollyDirection=Cl.NONE,this._changedDolly=0;let i=q.set(...e.target);if(`spherical`in e)nu.set(...e.spherical);else{let t=Jl.set(...e.position);nu.setFromVector3(t.sub(i).applyQuaternion(this._yAxisUpSpace))}let a=Yl.set(...t.target);if(`spherical`in t)ru.set(...t.spherical);else{let e=Jl.set(...t.position);ru.setFromVector3(e.sub(a).applyQuaternion(this._yAxisUpSpace))}this._targetEnd.copy(i.lerp(a,n));let o=ru.theta-nu.theta,s=ru.phi-nu.phi,c=ru.radius-nu.radius;this._sphericalEnd.set(nu.radius+c*n,nu.phi+s*n,nu.theta+o*n),this._needsUpdate=!0,r||(this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd));let l=!r||Ml(this._target.x,this._targetEnd.x,this.restThreshold)&&Ml(this._target.y,this._targetEnd.y,this.restThreshold)&&Ml(this._target.z,this._targetEnd.z,this.restThreshold)&&Ml(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Ml(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&Ml(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(l)}lerpLookAt(e,t,n,r,i,a,o,s,c,l,u,d,f,p=!1){return this.lerp({position:[e,t,n],target:[r,i,a]},{position:[o,s,c],target:[l,u,d]},f,p)}setPosition(e,t,n,r=!1){return this.setLookAt(e,t,n,this._targetEnd.x,this._targetEnd.y,this._targetEnd.z,r)}setTarget(e,t,n,r=!1){let i=this.getPosition(q),a=this.setLookAt(i.x,i.y,i.z,e,t,n,r);return this._sphericalEnd.phi=Al(this._sphericalEnd.phi,this.minPolarAngle,this.maxPolarAngle),a}setFocalOffset(e,t,n,r=!1){this._isUserControllingOffset=!1,this._focalOffsetEnd.set(e,t,n),this._needsUpdate=!0,r||this._focalOffset.copy(this._focalOffsetEnd);let i=!r||Ml(this._focalOffset.x,this._focalOffsetEnd.x,this.restThreshold)&&Ml(this._focalOffset.y,this._focalOffsetEnd.y,this.restThreshold)&&Ml(this._focalOffset.z,this._focalOffsetEnd.z,this.restThreshold);return this._createOnRestPromise(i)}setOrbitPoint(e,t,n){this._camera.updateMatrixWorld(),Zl.setFromMatrixColumn(this._camera.matrixWorldInverse,0),Ql.setFromMatrixColumn(this._camera.matrixWorldInverse,1),$l.setFromMatrixColumn(this._camera.matrixWorldInverse,2);let r=q.set(e,t,n),i=r.distanceTo(this._camera.position),a=r.sub(this._camera.position);Zl.multiplyScalar(a.x),Ql.multiplyScalar(a.y),$l.multiplyScalar(a.z),q.copy(Zl).add(Ql).add($l),q.z+=i,this.dollyTo(i,!1),this.setFocalOffset(-q.x,q.y,-q.z,!1),this.moveTo(e,t,n,!1)}setBoundary(e){if(!e){this._boundary.min.set(-1/0,-1/0,-1/0),this._boundary.max.set(1/0,1/0,1/0),this._needsUpdate=!0;return}this._boundary.copy(e),this._boundary.clampPoint(this._targetEnd,this._targetEnd),this._needsUpdate=!0}setViewport(e,t,n,r){if(e===null){this._viewport=null;return}this._viewport=this._viewport||new K.Vector4,typeof e==`number`?this._viewport.set(e,t,n,r):this._viewport.copy(e)}getDistanceToFitBox(e,t,n,r=!1){if(zl(this._camera,`getDistanceToFitBox`))return this._spherical.radius;let i=e/t,a=this._camera.getEffectiveFOV()*kl,o=this._camera.aspect;return((r?i>o:i<o)?t:e/o)*.5/Math.tan(a*.5)+n*.5}getDistanceToFitSphere(e){if(zl(this._camera,`getDistanceToFitSphere`))return this._spherical.radius;let t=this._camera.getEffectiveFOV()*kl,n=Math.atan(Math.tan(t*.5)*this._camera.aspect)*2,r=1<this._camera.aspect?t:n;return e/Math.sin(r*.5)}getTarget(e,t=!0){return(e&&e.isVector3?e:new K.Vector3).copy(t?this._targetEnd:this._target)}getPosition(e,t=!0){return(e&&e.isVector3?e:new K.Vector3).setFromSpherical(t?this._sphericalEnd:this._spherical).applyQuaternion(this._yAxisUpSpaceInverse).add(t?this._targetEnd:this._target)}getSpherical(e,t=!0){return(e||new K.Spherical).copy(t?this._sphericalEnd:this._spherical)}getFocalOffset(e,t=!0){return(e&&e.isVector3?e:new K.Vector3).copy(t?this._focalOffsetEnd:this._focalOffset)}normalizeRotations(){return this._sphericalEnd.theta=(this._sphericalEnd.theta%El+El)%El,this._sphericalEnd.theta>Math.PI&&(this._sphericalEnd.theta-=El),this._spherical.theta+=El*Math.round((this._sphericalEnd.theta-this._spherical.theta)/El),this}stop(){this._focalOffset.copy(this._focalOffsetEnd),this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd),this._zoom=this._zoomEnd}reset(e=!1){if(!Ml(this._camera.up.x,this._cameraUp0.x)||!Ml(this._camera.up.y,this._cameraUp0.y)||!Ml(this._camera.up.z,this._cameraUp0.z)){this._camera.up.copy(this._cameraUp0);let e=this.getPosition(q);this.updateCameraUp(),this.setPosition(e.x,e.y,e.z)}let t=[this.setLookAt(this._position0.x,this._position0.y,this._position0.z,this._target0.x,this._target0.y,this._target0.z,e),this.setFocalOffset(this._focalOffset0.x,this._focalOffset0.y,this._focalOffset0.z,e),this.zoomTo(this._zoom0,e)];return Promise.all(t)}saveState(){this._cameraUp0.copy(this._camera.up),this.getTarget(this._target0),this.getPosition(this._position0),this._zoom0=this._zoom,this._focalOffset0.copy(this._focalOffset)}updateCameraUp(){this._yAxisUpSpace.setFromUnitVectors(this._camera.up,Gl),this._yAxisUpSpaceInverse.copy(this._yAxisUpSpace).invert()}applyCameraUp(){let e=q.subVectors(this._target,this._camera.position).normalize(),t=Jl.crossVectors(e,this._camera.up);this._camera.up.crossVectors(t,e).normalize(),this._camera.updateMatrixWorld();let n=this.getPosition(q);this.updateCameraUp(),this.setPosition(n.x,n.y,n.z)}update(e){let t=this._sphericalEnd.theta-this._spherical.theta,n=this._sphericalEnd.phi-this._spherical.phi,r=this._sphericalEnd.radius-this._spherical.radius,i=eu.subVectors(this._targetEnd,this._target),a=tu.subVectors(this._focalOffsetEnd,this._focalOffset),o=this._zoomEnd-this._zoom;if(jl(t))this._thetaVelocity.value=0,this._spherical.theta=this._sphericalEnd.theta;else{let t=this._isUserControllingRotate?this.draggingSmoothTime:this.smoothTime;this._spherical.theta=Il(this._spherical.theta,this._sphericalEnd.theta,this._thetaVelocity,t,1/0,e),this._needsUpdate=!0}if(jl(n))this._phiVelocity.value=0,this._spherical.phi=this._sphericalEnd.phi;else{let t=this._isUserControllingRotate?this.draggingSmoothTime:this.smoothTime;this._spherical.phi=Il(this._spherical.phi,this._sphericalEnd.phi,this._phiVelocity,t,1/0,e),this._needsUpdate=!0}if(jl(r))this._radiusVelocity.value=0,this._spherical.radius=this._sphericalEnd.radius;else{let t=this._isUserControllingDolly?this.draggingSmoothTime:this.smoothTime;this._spherical.radius=Il(this._spherical.radius,this._sphericalEnd.radius,this._radiusVelocity,t,this.maxSpeed,e),this._needsUpdate=!0}if(jl(i.x)&&jl(i.y)&&jl(i.z))this._targetVelocity.set(0,0,0),this._target.copy(this._targetEnd);else{let t=this._isUserControllingTruck?this.draggingSmoothTime:this.smoothTime;Ll(this._target,this._targetEnd,this._targetVelocity,t,this.maxSpeed,e,this._target),this._needsUpdate=!0}if(jl(a.x)&&jl(a.y)&&jl(a.z))this._focalOffsetVelocity.set(0,0,0),this._focalOffset.copy(this._focalOffsetEnd);else{let t=this._isUserControllingOffset?this.draggingSmoothTime:this.smoothTime;Ll(this._focalOffset,this._focalOffsetEnd,this._focalOffsetVelocity,t,this.maxSpeed,e,this._focalOffset),this._needsUpdate=!0}if(jl(o))this._zoomVelocity.value=0,this._zoom=this._zoomEnd;else{let t=this._isUserControllingZoom?this.draggingSmoothTime:this.smoothTime;this._zoom=Il(this._zoom,this._zoomEnd,this._zoomVelocity,t,1/0,e)}if(this.dollyToCursor){if(wl(this._camera)&&this._changedDolly!==0){let e=this._spherical.radius-this._lastDistance,t=this._camera,n=this._getCameraDirection(Xl),r=q.copy(n).cross(t.up).normalize();r.lengthSq()===0&&(r.x=1);let i=Jl.crossVectors(r,n),a=this._sphericalEnd.radius*Math.tan(t.getEffectiveFOV()*kl*.5),o=(this._sphericalEnd.radius-e-this._sphericalEnd.radius)/this._sphericalEnd.radius,s=Yl.copy(this._targetEnd).add(r.multiplyScalar(this._dollyControlCoord.x*a*t.aspect)).add(i.multiplyScalar(this._dollyControlCoord.y*a)),c=q.copy(this._targetEnd).lerp(s,o),l=this._lastDollyDirection===Cl.IN&&this._spherical.radius<=this.minDistance,u=this._lastDollyDirection===Cl.OUT&&this.maxDistance<=this._spherical.radius;if(this.infinityDolly&&(l||u)){this._sphericalEnd.radius-=e,this._spherical.radius-=e;let t=Jl.copy(n).multiplyScalar(-e);c.add(t)}this._boundary.clampPoint(c,c);let d=Jl.subVectors(c,this._targetEnd);this._targetEnd.copy(c),this._target.add(d),this._changedDolly-=e,jl(this._changedDolly)&&(this._changedDolly=0)}else if(Tl(this._camera)&&this._changedZoom!==0){let e=this._zoom-this._lastZoom,t=this._camera,n=q.set(this._dollyControlCoord.x,this._dollyControlCoord.y,(t.near+t.far)/(t.near-t.far)).unproject(t),r=Jl.set(0,0,-1).applyQuaternion(t.quaternion),i=Yl.copy(n).add(r.multiplyScalar(-n.dot(t.up))),a=-(this._zoom-e-this._zoom)/this._zoom,o=this._getCameraDirection(Xl),s=this._targetEnd.dot(o),c=q.copy(this._targetEnd).lerp(i,a),l=c.dot(o),u=o.multiplyScalar(l-s);c.sub(u),this._boundary.clampPoint(c,c);let d=Jl.subVectors(c,this._targetEnd);this._targetEnd.copy(c),this._target.add(d),this._changedZoom-=e,jl(this._changedZoom)&&(this._changedZoom=0)}}this._camera.zoom!==this._zoom&&(this._camera.zoom=this._zoom,this._camera.updateProjectionMatrix(),this._updateNearPlaneCorners(),this._needsUpdate=!0),this._dragNeedsUpdate=!0;let s=this._collisionTest();this._spherical.radius=Math.min(this._spherical.radius,s),this._spherical.makeSafe(),this._camera.position.setFromSpherical(this._spherical).applyQuaternion(this._yAxisUpSpaceInverse).add(this._target),this._camera.lookAt(this._target),(!jl(this._focalOffset.x)||!jl(this._focalOffset.y)||!jl(this._focalOffset.z))&&(this._camera.matrix.compose(this._camera.position,this._camera.quaternion,this._camera.scale),Zl.setFromMatrixColumn(this._camera.matrix,0),Ql.setFromMatrixColumn(this._camera.matrix,1),$l.setFromMatrixColumn(this._camera.matrix,2),Zl.multiplyScalar(this._focalOffset.x),Ql.multiplyScalar(-this._focalOffset.y),$l.multiplyScalar(this._focalOffset.z),q.copy(Zl).add(Ql).add($l),this._camera.position.add(q),this._camera.updateMatrixWorld()),this._boundaryEnclosesCamera&&this._encloseToBoundary(this._camera.position.copy(this._target),q.setFromSpherical(this._spherical).applyQuaternion(this._yAxisUpSpaceInverse),1);let c=this._needsUpdate;return c&&!this._updatedLastTime?(this._hasRested=!1,this.dispatchEvent({type:`wake`}),this.dispatchEvent({type:`update`})):c?(this.dispatchEvent({type:`update`}),jl(t,this.restThreshold)&&jl(n,this.restThreshold)&&jl(r,this.restThreshold)&&jl(i.x,this.restThreshold)&&jl(i.y,this.restThreshold)&&jl(i.z,this.restThreshold)&&jl(a.x,this.restThreshold)&&jl(a.y,this.restThreshold)&&jl(a.z,this.restThreshold)&&jl(o,this.restThreshold)&&!this._hasRested&&(this._hasRested=!0,this.dispatchEvent({type:`rest`}))):!c&&this._updatedLastTime&&this.dispatchEvent({type:`sleep`}),this._lastDistance=this._spherical.radius,this._lastZoom=this._zoom,this._updatedLastTime=c,this._needsUpdate=!1,c}toJSON(){return JSON.stringify({enabled:this._enabled,minDistance:this.minDistance,maxDistance:Pl(this.maxDistance),minZoom:this.minZoom,maxZoom:Pl(this.maxZoom),minPolarAngle:this.minPolarAngle,maxPolarAngle:Pl(this.maxPolarAngle),minAzimuthAngle:Pl(this.minAzimuthAngle),maxAzimuthAngle:Pl(this.maxAzimuthAngle),smoothTime:this.smoothTime,draggingSmoothTime:this.draggingSmoothTime,dollySpeed:this.dollySpeed,truckSpeed:this.truckSpeed,dollyToCursor:this.dollyToCursor,target:this._targetEnd.toArray(),position:q.setFromSpherical(this._sphericalEnd).add(this._targetEnd).toArray(),zoom:this._zoomEnd,focalOffset:this._focalOffsetEnd.toArray(),target0:this._target0.toArray(),position0:this._position0.toArray(),zoom0:this._zoom0,focalOffset0:this._focalOffset0.toArray()})}fromJSON(e,t=!1){let n=JSON.parse(e);this.enabled=n.enabled,this.minDistance=n.minDistance,this.maxDistance=Fl(n.maxDistance),this.minZoom=n.minZoom,this.maxZoom=Fl(n.maxZoom),this.minPolarAngle=n.minPolarAngle,this.maxPolarAngle=Fl(n.maxPolarAngle),this.minAzimuthAngle=Fl(n.minAzimuthAngle),this.maxAzimuthAngle=Fl(n.maxAzimuthAngle),this.smoothTime=n.smoothTime,this.draggingSmoothTime=n.draggingSmoothTime,this.dollySpeed=n.dollySpeed,this.truckSpeed=n.truckSpeed,this.dollyToCursor=n.dollyToCursor,this._target0.fromArray(n.target0),this._position0.fromArray(n.position0),this._zoom0=n.zoom0,this._focalOffset0.fromArray(n.focalOffset0),this.moveTo(n.target[0],n.target[1],n.target[2],t),nu.setFromVector3(q.fromArray(n.position).sub(this._targetEnd).applyQuaternion(this._yAxisUpSpace)),this.rotateTo(nu.theta,nu.phi,t),this.dollyTo(nu.radius,t),this.zoomTo(n.zoom,t),this.setFocalOffset(n.focalOffset[0],n.focalOffset[1],n.focalOffset[2],t),this._needsUpdate=!0}connect(e){if(this._domElement){console.warn(`camera-controls is already connected.`);return}e.setAttribute(`data-camera-controls-version`,Vl),this._addAllEventListeners(e),this._getClientRect(this._elementRect)}disconnect(){this.cancel(),this._removeAllEventListeners(),this._domElement&&=(this._domElement.removeAttribute(`data-camera-controls-version`),void 0)}dispose(){this.removeAllEventListeners(),this.disconnect()}_getTargetDirection(e){return e.setFromSpherical(this._spherical).divideScalar(this._spherical.radius).applyQuaternion(this._yAxisUpSpaceInverse)}_getCameraDirection(e){return this._getTargetDirection(e).negate()}_findPointerById(e){return this._activePointers.find(t=>t.pointerId===e)}_findPointerByMouseButton(e){return this._activePointers.find(t=>t.mouseButton===e)}_disposePointer(e){this._activePointers.splice(this._activePointers.indexOf(e),1)}_encloseToBoundary(e,t,n){let r=t.lengthSq();if(r===0)return e;let i=Jl.copy(t).add(e),a=this._boundary.clampPoint(i,Yl).sub(i),o=a.lengthSq();if(o===0)return e.add(t);if(o===r)return e;if(n===0)return e.add(t).add(a);{let r=1+n*o/t.dot(a);return e.add(Jl.copy(t).multiplyScalar(r)).add(a.multiplyScalar(1-n))}}_updateNearPlaneCorners(){if(wl(this._camera)){let e=this._camera,t=e.near,n=e.getEffectiveFOV()*kl,r=Math.tan(n*.5)*t,i=r*e.aspect;this._nearPlaneCorners[0].set(-i,-r,0),this._nearPlaneCorners[1].set(i,-r,0),this._nearPlaneCorners[2].set(i,r,0),this._nearPlaneCorners[3].set(-i,r,0)}else if(Tl(this._camera)){let e=this._camera,t=1/e.zoom,n=e.left*t,r=e.right*t,i=e.top*t,a=e.bottom*t;this._nearPlaneCorners[0].set(n,i,0),this._nearPlaneCorners[1].set(r,i,0),this._nearPlaneCorners[2].set(r,a,0),this._nearPlaneCorners[3].set(n,a,0)}}_truckInternal=(e,t,n,r)=>{let i,a;if(wl(this._camera)){let n=q.copy(this._camera.position).sub(this._target),r=this._camera.getEffectiveFOV()*kl,o=n.length()*Math.tan(r*.5);i=this.truckSpeed*e*o/this._elementRect.height,a=this.truckSpeed*t*o/this._elementRect.height}else if(Tl(this._camera)){let n=this._camera;i=this.truckSpeed*e*(n.right-n.left)/n.zoom/this._elementRect.width,a=this.truckSpeed*t*(n.top-n.bottom)/n.zoom/this._elementRect.height}else return;r?(n?this.setFocalOffset(this._focalOffsetEnd.x+i,this._focalOffsetEnd.y,this._focalOffsetEnd.z,!0):this.truck(i,0,!0),this.forward(-a,!0)):n?this.setFocalOffset(this._focalOffsetEnd.x+i,this._focalOffsetEnd.y+a,this._focalOffsetEnd.z,!0):this.truck(i,a,!0)};_rotateInternal=(e,t)=>{let n=El*this.azimuthRotateSpeed*e/this._elementRect.height,r=El*this.polarRotateSpeed*t/this._elementRect.height;this.rotate(n,r,!0)};_dollyInternal=(e,t,n)=>{let r=.95**(-e*this.dollySpeed),i=this._sphericalEnd.radius,a=this._sphericalEnd.radius*r,o=Al(a,this.minDistance,this.maxDistance),s=o-a;this.infinityDolly&&this.dollyToCursor?this._dollyToNoClamp(a,!0):(this.infinityDolly&&!this.dollyToCursor&&this.dollyInFixed(s,!0),this._dollyToNoClamp(o,!0)),this.dollyToCursor&&(this._changedDolly+=(this.infinityDolly?a:o)-i,this._dollyControlCoord.set(t,n)),this._lastDollyDirection=Math.sign(-e)};_zoomInternal=(e,t,n)=>{let r=.95**(e*this.dollySpeed),i=this._zoom,a=this._zoom*r;this.zoomTo(a,!0),this.dollyToCursor&&(this._changedZoom+=a-i,this._dollyControlCoord.set(t,n))};_collisionTest(){let e=1/0;if(!(this.colliderMeshes.length>=1)||zl(this._camera,`_collisionTest`))return e;let t=this._getTargetDirection(Xl);lu.lookAt(Wl,t,this._camera.up);for(let n=0;n<4;n++){let r=Jl.copy(this._nearPlaneCorners[n]);r.applyMatrix4(lu);let i=Yl.addVectors(this._target,r);uu.set(i,t),uu.far=this._spherical.radius+1;let a=uu.intersectObjects(this.colliderMeshes);a.length!==0&&a[0].distance<e&&(e=a[0].distance)}return e}_getClientRect(e){if(!this._domElement)return;let t=this._domElement.getBoundingClientRect();return e.x=t.left,e.y=t.top,this._viewport?(e.x+=this._viewport.x,e.y+=t.height-this._viewport.w-this._viewport.y,e.width=this._viewport.z,e.height=this._viewport.w):(e.width=t.width,e.height=t.height),e}_createOnRestPromise(e){return e?Promise.resolve():(this._hasRested=!1,this.dispatchEvent({type:`transitionstart`}),new Promise(e=>{let t=()=>{this.removeEventListener(`rest`,t),e()};this.addEventListener(`rest`,t)}))}_addAllEventListeners(e){}_removeAllEventListeners(){}get dampingFactor(){return console.warn(`.dampingFactor has been deprecated. use smoothTime (in seconds) instead.`),0}set dampingFactor(e){console.warn(`.dampingFactor has been deprecated. use smoothTime (in seconds) instead.`)}get draggingDampingFactor(){return console.warn(`.draggingDampingFactor has been deprecated. use draggingSmoothTime (in seconds) instead.`),0}set draggingDampingFactor(e){console.warn(`.draggingDampingFactor has been deprecated. use draggingSmoothTime (in seconds) instead.`)}static createBoundingSphere(e,t=new K.Sphere){let n=t,r=n.center;iu.makeEmpty(),e.traverseVisible(e=>{e.isMesh&&iu.expandByObject(e)}),iu.getCenter(r);let i=0;return e.traverseVisible(e=>{if(!e.isMesh)return;let t=e;if(!t.geometry)return;let n=t.geometry.clone();n.applyMatrix4(t.matrixWorld);let a=n.attributes.position;for(let e=0,t=a.count;e<t;e++)q.fromBufferAttribute(a,e),i=Math.max(i,r.distanceToSquared(q))}),n.radius=Math.sqrt(i),n}},fu=Object.defineProperty,pu=(e,t,n)=>t in e?fu(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,mu=(e,t,n)=>pu(e,typeof t==`symbol`?t:t+``,n),hu=(e,t)=>{let[n,r]=t.split(`-`);return Object.assign(e.style,{left:r===`left`?`0`:r===`center`?`50%`:``,right:r===`right`?`0`:``,top:n===`top`?`0`:n===`bottom`?``:`50%`,bottom:n===`bottom`?`0`:``,transform:`${r===`center`?`translateX(-50%)`:``} ${n===`center`?`translateY(-50%)`:``}`}),t},gu=({placement:e,size:t,offset:n,id:r,className:i})=>{let a=document.createElement(`div`),{top:o,left:s,right:c,bottom:l}=n;return Object.assign(a.style,{id:r,position:`absolute`,zIndex:`1000`,height:`${t}px`,width:`${t}px`,margin:`${o}px ${c}px ${l}px ${s}px`,borderRadius:`100%`}),hu(a,e),r&&(a.id=r),i&&(a.className=i),a},_u=e=>{let t=typeof e==`string`?document.querySelector(e):e;if(!t)throw Error(`Invalid DOM element`);return t};function vu(e,t,n){return Math.max(t,Math.min(n,e))}var yu=[[`x`,0,3],[`y`,1,4],[`z`,2,5]],bu=new R;function xu({isSphere:e},t,n){e&&(bu.set(0,0,1).applyQuaternion(n.quaternion),yu.forEach(([e,n,r])=>{let i=bu[e],a=t[n],o=a.userData.opacity;a.material.opacity=vu(i>=0?o:o/2,0,1),a=t[r],o=a.userData.opacity,a.material.opacity=vu(i>=0?o/2:o,0,1)}))}var Su=(e,t,n=10)=>Math.abs(e.clientX-t.x)<n&&Math.abs(e.clientY-t.y)<n,Cu=new io,wu=new L,Tu=(e,t,n,r)=>{wu.set((e.clientX-t.left)/t.width*2-1,-((e.clientY-t.top)/t.height)*2+1),Cu.setFromCamera(wu,n);let i=Cu.intersectObjects(r,!1),a=i.length?i[0]:null;return!a||!a.object.visible?null:a},Eu=1e-6,Du=2*Math.PI,Ou=[`x`,`y`,`z`],ku=[...Ou,`nx`,`ny`,`nz`],Au=[`x`,`z`,`y`,`nx`,`nz`,`ny`],ju=[`z`,`x`,`y`,`nz`,`nx`,`ny`],Mu=`Right`,Nu=`Top`,Pu=`Front`,Fu=`Left`,Iu=`Bottom`,Lu=`Back`,Ru=[Mu,Nu,Pu,Fu,Iu,Lu].map(e=>e.toLocaleLowerCase()),zu=1.3,Bu=(e,t=!0)=>{let{material:n,userData:r}=e,{color:i,opacity:a}=t?r.hover:r;n.color.set(i),n.opacity=a},Vu=e=>JSON.parse(JSON.stringify(e)),Hu=e=>{let t=e.type||`sphere`,n=t===`sphere`,r=e.resolution||n?64:128,i=Kn.DEFAULT_UP,a=i.z===1,o=i.x===1,{container:s}=e;e.container=void 0,e=JSON.parse(JSON.stringify(e)),e.container=s;let c=a?Au:o?ju:ku;Ru.forEach((t,n)=>{e[t]&&(e[c[n]]=e[t])});let l={enabled:!0,color:16777215,opacity:1,scale:.7,labelColor:2236962,line:!1,border:{size:0,color:14540253},hover:{color:n?16777215:9688043,labelColor:2236962,opacity:1,scale:.7,border:{size:0,color:14540253}}},u={line:!1,scale:n?.45:.7,hover:{scale:n?.5:.7}},d={type:t,container:document.body,size:128,placement:`top-right`,resolution:r,lineWidth:4,radius:n?1:.2,smoothness:18,animated:!0,speed:1,background:{enabled:!0,color:n?16777215:14739180,opacity:+!n,hover:{color:n?16777215:14739180,opacity:n?.2:1}},font:{family:`sans-serif`,weight:900},offset:{top:10,left:10,bottom:10,right:10},corners:{enabled:!n,color:n?15915362:16777215,opacity:1,scale:n?.15:.2,radius:1,smoothness:18,hover:{color:n?16777215:9688043,opacity:1,scale:n?.2:.225}},edges:{enabled:!n,color:n?15915362:16777215,opacity:+!!n,radius:n?1:.125,smoothness:18,scale:n?.15:1,hover:{color:n?16777215:9688043,opacity:1,scale:n?.2:1}},x:{...Vu(l),...n?{label:`X`,color:16725587,line:!0}:{label:o?Nu:Mu}},y:{...Vu(l),...n?{label:`Y`,color:9100032,line:!0}:{label:a||o?Pu:Nu}},z:{...Vu(l),...n?{label:`Z`,color:2920447,line:!0}:{label:a?Nu:o?Mu:Pu}},nx:{...Vu(u),label:n?``:o?Iu:Fu},ny:{...Vu(u),label:n?``:a||o?Lu:Iu},nz:{...Vu(u),label:n?``:a?Iu:o?Fu:Lu}};return Uu(e,d),Ou.forEach(t=>Uu(e[`n${t}`],Vu(e[t]))),{...e,isSphere:n}};function Uu(e,...t){if(e instanceof HTMLElement||typeof e!=`object`||!e)return e;for(let n of t)for(let t in n)t!==`container`&&t in n&&(e[t]===void 0?e[t]=n[t]:typeof n[t]==`object`&&!Array.isArray(n[t])&&(e[t]=Uu(e[t]||{},n[t])));return e}var Wu=(t,n=2)=>{let r=new B,i=n*2,{isSphere:a,resolution:o,radius:s,font:c,corners:l,edges:u}=t,d=ku.map(e=>({...t[e],radius:s}));a&&l.enabled&&d.push(l),a&&u.enabled&&d.push(u);let f=document.createElement(`canvas`),p=f.getContext(`2d`);f.width=o*2+i*2,f.height=o*d.length+i*d.length;let[m,h]=S(d,o,c);d.forEach(({radius:e,label:t,color:r,labelColor:a,border:s,hover:{color:c,labelColor:l,border:u}},d)=>{let f=o*d+d*i+n;x(n,f,n,o,e,t,s,r,a),x(o+n*3,f,n,o,e,t,u??s,c??r,l??a)});let g=d.length,_=n/(o*2),v=n/(o*6),y=1/g,b=new Zi(f);return b.repeat.set(.5-2*_,y-2*v),b.offset.set(_,1-v),Object.assign(b,{colorSpace:Ie,wrapS:e,wrapT:e,userData:{offsetX:_,offsetY:v,cellHeight:y}}),b;function x(e,t,n,i,a,o,s,c,l){if(a=i/2*a,c!=null&&c!==``&&(u(),p.fillStyle=r.set(c).getStyle(),p.fill()),s&&s.size){let n=s.size*i/2;e+=n,t+=n,i-=s.size*i,a=Math.max(0,a-n),u(),p.strokeStyle=r.set(s.color).getStyle(),p.lineWidth=s.size*i,p.stroke()}o&&C(p,e+i/2,t+(i+n)/2,o,r.set(l).getStyle());function u(){p.beginPath(),p.moveTo(e+a,t),p.lineTo(e+i-a,t),p.arcTo(e+i,t,e+i,t+a,a),p.lineTo(e+i,t+i-a),p.arcTo(e+i,t+i,e+i-a,t+i,a),p.lineTo(e+a,t+i),p.arcTo(e,t+i,e,t+i-a,a),p.lineTo(e,t+a),p.arcTo(e,t,e+a,t,a),p.closePath()}}function S(e,t,n){let r=[...e].sort((e,t)=>(e.label?.length||0)-(t.label?.length||0)).pop().label,{family:i,weight:o}=n,s=a?Math.sqrt((t*.7)**2/2):t,c=s,l=0,u=0;do{p.font=`${o} ${c}px ${i}`;let e=p.measureText(r);l=e.width,u=e.fontBoundingBoxDescent,c--}while(l>s&&c>0);let d=s/u,f=Math.min(s/l,d);return[`${o} ${Math.floor(c*f)}px ${i}`,d]}function C(e,t,n,r,i){e.font=m,e.textAlign=`center`,e.textBaseline=`middle`,e.fillStyle=i,e.fillText(r,t,n+(a?h:0))}},Gu=(e,t)=>e.offset.x=(t?.5:0)+e.userData.offsetX,Ku=(e,t)=>{let{offset:n,userData:{offsetY:r,cellHeight:i}}=e;n.y=1-(t+1)*i+r};function qu(e,t,n=2,r=2){let i=n/2-e,a=r/2-e,o=e/n,s=(n-e)/n,c=e/r,l=(r-e)/r,u=[i,a,0,-i,a,0,-i,-a,0,i,-a,0],d=[s,l,o,l,o,c,s,c],f=[3*(t+1)+3,3*(t+1)+4,t+4,t+5,2*(t+1)+4,2,1,2*(t+1)+3,3,4*(t+1)+3,4,0],p=[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11].map(e=>f[e]),m,h,g,_,v,y,b,x;for(let n=0;n<4;n++){_=n<1||n>2?i:-i,v=n<2?a:-a,y=n<1||n>2?s:o,b=n<2?l:c;for(let r=0;r<=t;r++)m=Math.PI/2*(n+r/t),h=Math.cos(m),g=Math.sin(m),u.push(_+e*h,v+e*g,0),d.push(y+o*h,b+c*g),r<t&&(x=(t+1)*n+r+4,p.push(n,x,x+1))}return new Or().setIndex(new V(new Uint32Array(p),1)).setAttribute(`position`,new V(new Float32Array(u),3)).setAttribute(`uv`,new V(new Float32Array(d),2))}var Ju=(e,t)=>{let n=new R,{isSphere:r,radius:i,smoothness:a}=e,o=qu(i,a);return ku.map((i,a)=>{let s=a<3,c=ku[a],l=a?t.clone():t;Ku(l,a);let{enabled:u,scale:d,opacity:f,hover:p}=e[c],m={map:l,opacity:f,transparent:!0},h=r?new Oi(new mi(m)):new H(o,new mr(m)),g=s?c:c[1];return h.position[g]=(s?1:-1)*(r?zu:1),r||h.lookAt(n.copy(h.position).multiplyScalar(1.7)),h.scale.setScalar(d),h.renderOrder=1,h.visible=u,h.userData={scale:d,opacity:f,hover:p},h})},Yu=(e,t)=>{let{isSphere:n,corners:r}=e;if(!r.enabled)return[];let{color:i,opacity:a,scale:o,radius:s,smoothness:c,hover:l}=r,u=n?null:qu(s,c),d={transparent:!0,opacity:a},f=[1,1,1,-1,1,1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,1,-1,-1,-1,-1,-1].map(e=>e*.85),p=new R;return Array(f.length/3).fill(0).map((e,r)=>{if(n){let e=t.clone();Ku(e,6),d.map=e}else d.color=i;let s=n?new Oi(new mi(d)):new H(u,new mr(d)),c=r*3;return s.position.set(f[c],f[c+1],f[c+2]),n&&s.position.normalize().multiplyScalar(1.7),s.scale.setScalar(o),s.lookAt(p.copy(s.position).multiplyScalar(2)),s.renderOrder=1,s.userData={color:i,opacity:a,scale:o,hover:l},s})},Xu=(e,t,n)=>{let{isSphere:r,edges:i}=e;if(!i.enabled)return[];let{color:a,opacity:o,scale:s,hover:c,radius:l,smoothness:u}=i,d=r?null:qu(l,u,1.2,.25),f={transparent:!0,opacity:o},p=[0,1,1,0,-1,1,1,0,1,-1,0,1,0,1,-1,0,-1,-1,1,0,-1,-1,0,-1,1,1,0,1,-1,0,-1,1,0,-1,-1,0].map(e=>e*.925),m=new R,h=new R(0,1,0);return Array(p.length/3).fill(0).map((e,i)=>{if(r){let e=t.clone();Ku(e,n),f.map=e}else f.color=a;let l=r?new Oi(new mi(f)):new H(d,new mr(f)),u=i*3;return l.position.set(p[u],p[u+1],p[u+2]),r&&l.position.normalize().multiplyScalar(1.7),l.scale.setScalar(s),l.up.copy(h),l.lookAt(m.copy(l.position).multiplyScalar(2)),!r&&!l.position.y&&(l.rotation.z=Math.PI/2),l.renderOrder=1,l.userData={color:a,opacity:o,scale:s,hover:c},l})};function Zu(e,t=!1){let n=e[0].index!==null,r=new Set(Object.keys(e[0].attributes)),i=new Set(Object.keys(e[0].morphAttributes)),a={},o={},s=e[0].morphTargetsRelative,c=new Or,l=0;for(let u=0;u<e.length;++u){let d=e[u],f=0;if(n!==(d.index!==null))return console.error(`THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index `+u+`. All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them.`),null;for(let e in d.attributes){if(!r.has(e))return console.error(`THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index `+u+`. All geometries must have compatible attributes; make sure "`+e+`" attribute exists among all geometries, or in none of them.`),null;a[e]===void 0&&(a[e]=[]),a[e].push(d.attributes[e]),f++}if(f!==r.size)return console.error(`THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index `+u+`. Make sure all geometries have the same number of attributes.`),null;if(s!==d.morphTargetsRelative)return console.error(`THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index `+u+`. .morphTargetsRelative must be consistent throughout all geometries.`),null;for(let e in d.morphAttributes){if(!i.has(e))return console.error(`THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index `+u+`. .morphAttributes must be consistent throughout all geometries.`),null;o[e]===void 0&&(o[e]=[]),o[e].push(d.morphAttributes[e])}if(t){let e;if(n)e=d.index.count;else if(d.attributes.position!==void 0)e=d.attributes.position.count;else return console.error(`THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index `+u+`. The geometry must have either an index or a position attribute`),null;c.addGroup(l,e,u),l+=e}}if(n){let t=0,n=[];for(let r=0;r<e.length;++r){let i=e[r].index;for(let e=0;e<i.count;++e)n.push(i.getX(e)+t);t+=e[r].attributes.position.count}c.setIndex(n)}for(let e in a){let t=Qu(a[e]);if(!t)return console.error(`THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the `+e+` attribute.`),null;c.setAttribute(e,t)}for(let e in o){let t=o[e][0].length;if(t===0)break;c.morphAttributes=c.morphAttributes||{},c.morphAttributes[e]=[];for(let n=0;n<t;++n){let t=[];for(let r=0;r<o[e].length;++r)t.push(o[e][r][n]);let r=Qu(t);if(!r)return console.error(`THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the `+e+` morphAttribute.`),null;c.morphAttributes[e].push(r)}}return c}function Qu(e){let t,n,r,i=-1,a=0;for(let o=0;o<e.length;++o){let s=e[o];if(t===void 0&&(t=s.array.constructor),t!==s.array.constructor)return console.error(`THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes.`),null;if(n===void 0&&(n=s.itemSize),n!==s.itemSize)return console.error(`THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes.`),null;if(r===void 0&&(r=s.normalized),r!==s.normalized)return console.error(`THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes.`),null;if(i===-1&&(i=s.gpuType),i!==s.gpuType)return console.error(`THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.gpuType must be consistent across matching attributes.`),null;a+=s.count*n}let o=new t(a),s=new V(o,n,r),c=0;for(let t=0;t<e.length;++t){let r=e[t];if(r.isInterleavedBufferAttribute){let e=c/n;for(let t=0,i=r.count;t<i;t++)for(let i=0;i<n;i++){let n=r.getComponent(t,i);s.setComponent(t+e,i,n)}}else o.set(r.array,c);c+=r.count*n}return i!==void 0&&(s.gpuType=i),s}var $u=(e,t)=>{let{isSphere:n,background:{enabled:r,color:i,opacity:a,hover:o}}=t,s,c=new mr({color:i,side:1,opacity:a,transparent:!0,depthWrite:!1});if(!r)return null;if(n)s=new H(new la(1.8,64,64),c);else{let t;e.forEach(e=>{let n=e.scale.x;e.scale.setScalar(.9),e.updateMatrix();let r=e.geometry.clone();r.applyMatrix4(e.matrix),t=t?Zu([t,r]):r,e.scale.setScalar(n)}),s=new H(t,c)}return s.userData={color:i,opacity:a,hover:o},s},ed=new Gt,td=new R,nd=class extends Va{constructor(){super(),this.isLineSegmentsGeometry=!0,this.type=`LineSegmentsGeometry`,this.setIndex([0,2,1,2,3,1,2,4,3,4,5,3,4,6,5,6,7,5]),this.setAttribute(`position`,new br([-1,2,0,1,2,0,-1,1,0,1,1,0,-1,0,0,1,0,0,-1,-1,0,1,-1,0],3)),this.setAttribute(`uv`,new br([-1,2,1,2,-1,1,1,1,-1,-1,1,-1,-1,-2,1,-2],2))}applyMatrix4(e){let t=this.attributes.instanceStart,n=this.attributes.instanceEnd;return t!==void 0&&(t.applyMatrix4(e),n.applyMatrix4(e),t.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}setPositions(e){let t;e instanceof Float32Array?t=e:Array.isArray(e)&&(t=new Float32Array(e));let n=new no(t,6,1);return this.setAttribute(`instanceStart`,new pi(n,3,0)),this.setAttribute(`instanceEnd`,new pi(n,3,3)),this.instanceCount=this.attributes.instanceStart.count,this.computeBoundingBox(),this.computeBoundingSphere(),this}setColors(e){let t;e instanceof Float32Array?t=e:Array.isArray(e)&&(t=new Float32Array(e));let n=new no(t,6,1);return this.setAttribute(`instanceColorStart`,new pi(n,3,0)),this.setAttribute(`instanceColorEnd`,new pi(n,3,3)),this}fromWireframeGeometry(e){return this.setPositions(e.attributes.position.array),this}fromEdgesGeometry(e){return this.setPositions(e.attributes.position.array),this}fromMesh(e){return this.fromWireframeGeometry(new ua(e.geometry)),this}fromLineSegments(e){let t=e.geometry;return this.setPositions(t.attributes.position.array),this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Gt);let e=this.attributes.instanceStart,t=this.attributes.instanceEnd;e!==void 0&&t!==void 0&&(this.boundingBox.setFromBufferAttribute(e),ed.setFromBufferAttribute(t),this.boundingBox.union(ed))}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new un),this.boundingBox===null&&this.computeBoundingBox();let e=this.attributes.instanceStart,t=this.attributes.instanceEnd;if(e!==void 0&&t!==void 0){let n=this.boundingSphere.center;this.boundingBox.getCenter(n);let r=0;for(let i=0,a=e.count;i<a;i++)td.fromBufferAttribute(e,i),r=Math.max(r,n.distanceToSquared(td)),td.fromBufferAttribute(t,i),r=Math.max(r,n.distanceToSquared(td));this.boundingSphere.radius=Math.sqrt(r),isNaN(this.boundingSphere.radius)&&console.error(`THREE.LineSegmentsGeometry.computeBoundingSphere(): Computed radius is NaN. The instanced position data is likely to have NaN values.`,this)}}toJSON(){}applyMatrix(e){return console.warn(`THREE.LineSegmentsGeometry: applyMatrix() has been renamed to applyMatrix4().`),this.applyMatrix4(e)}};W.line={worldUnits:{value:1},linewidth:{value:1},resolution:{value:new L(1,1)},dashOffset:{value:0},dashScale:{value:1},dashSize:{value:1},gapSize:{value:1}},So.line={uniforms:qr.merge([W.common,W.fog,W.line]),vertexShader:`
3832
+ }`,xl=class{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){let n=new aa(e.texture);(e.depthNear!==t.depthNear||e.depthFar!==t.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=n}}getMesh(e){if(this.texture!==null&&this.mesh===null){let t=e.cameras[0].viewport,n=new Yr({vertexShader:yl,fragmentShader:bl,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new U(new ma(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}},Sl=class extends Ue{constructor(e,t){super();let n=this,r=null,i=1,a=null,o=`local-floor`,s=1,c=null,u=null,d=null,f=null,p=null,h=null,g=typeof XRWebGLBinding<`u`,_=new xl,v={},b=t.getContextAttributes(),x=null,S=null,C=[],D=[],ee=new L,O=null,k=new ei;k.viewport=new Bt;let te=new ei;te.viewport=new Bt;let ne=[k,te],A=new Ja,re=null,ie=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(e){let t=C[e];return t===void 0&&(t=new ci,C[e]=t),t.getTargetRaySpace()},this.getControllerGrip=function(e){let t=C[e];return t===void 0&&(t=new ci,C[e]=t),t.getGripSpace()},this.getHand=function(e){let t=C[e];return t===void 0&&(t=new ci,C[e]=t),t.getHandSpace()};function j(e){let t=D.indexOf(e.inputSource);if(t===-1)return;let n=C[t];n!==void 0&&(n.update(e.inputSource,e.frame,c||a),n.dispatchEvent({type:e.type,data:e.inputSource}))}function ae(){r.removeEventListener(`select`,j),r.removeEventListener(`selectstart`,j),r.removeEventListener(`selectend`,j),r.removeEventListener(`squeeze`,j),r.removeEventListener(`squeezestart`,j),r.removeEventListener(`squeezeend`,j),r.removeEventListener(`end`,ae),r.removeEventListener(`inputsourceschange`,oe);for(let e=0;e<C.length;e++){let t=D[e];t!==null&&(D[e]=null,C[e].disconnect(t))}re=null,ie=null,_.reset();for(let e in v)delete v[e];e.setRenderTarget(x),p=null,f=null,d=null,r=null,S=null,me.stop(),n.isPresenting=!1,e.setPixelRatio(O),e.setSize(ee.width,ee.height,!1),n.dispatchEvent({type:`sessionend`})}this.setFramebufferScaleFactor=function(e){i=e,n.isPresenting===!0&&console.warn(`THREE.WebXRManager: Cannot change framebuffer scale while presenting.`)},this.setReferenceSpaceType=function(e){o=e,n.isPresenting===!0&&console.warn(`THREE.WebXRManager: Cannot change reference space type while presenting.`)},this.getReferenceSpace=function(){return c||a},this.setReferenceSpace=function(e){c=e},this.getBaseLayer=function(){return f===null?p:f},this.getBinding=function(){return d===null&&g&&(d=new XRWebGLBinding(r,t)),d},this.getFrame=function(){return h},this.getSession=function(){return r},this.setSession=async function(u){if(r=u,r!==null){if(x=e.getRenderTarget(),r.addEventListener(`select`,j),r.addEventListener(`selectstart`,j),r.addEventListener(`selectend`,j),r.addEventListener(`squeeze`,j),r.addEventListener(`squeezestart`,j),r.addEventListener(`squeezeend`,j),r.addEventListener(`end`,ae),r.addEventListener(`inputsourceschange`,oe),b.xrCompatible!==!0&&await t.makeXRCompatible(),O=e.getPixelRatio(),e.getSize(ee),g&&`createProjectionLayer`in XRWebGLBinding.prototype){let n=null,a=null,o=null;b.depth&&(o=b.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,n=b.stencil?E:T,a=b.stencil?y:m);let s={colorFormat:t.RGBA8,depthFormat:o,scaleFactor:i};d=this.getBinding(),f=d.createProjectionLayer(s),r.updateRenderState({layers:[f]}),e.setPixelRatio(1),e.setSize(f.textureWidth,f.textureHeight,!1),S=new Ht(f.textureWidth,f.textureHeight,{format:w,type:l,depthTexture:new ia(f.textureWidth,f.textureHeight,a,void 0,void 0,void 0,void 0,void 0,void 0,n),stencilBuffer:b.stencil,colorSpace:e.outputColorSpace,samples:b.antialias?4:0,resolveDepthBuffer:f.ignoreDepthValues===!1,resolveStencilBuffer:f.ignoreDepthValues===!1})}else{let n={antialias:b.antialias,alpha:!0,depth:b.depth,stencil:b.stencil,framebufferScaleFactor:i};p=new XRWebGLLayer(r,t,n),r.updateRenderState({baseLayer:p}),e.setPixelRatio(1),e.setSize(p.framebufferWidth,p.framebufferHeight,!1),S=new Ht(p.framebufferWidth,p.framebufferHeight,{format:w,type:l,colorSpace:e.outputColorSpace,stencilBuffer:b.stencil,resolveDepthBuffer:p.ignoreDepthValues===!1,resolveStencilBuffer:p.ignoreDepthValues===!1})}S.isXRRenderTarget=!0,this.setFoveation(s),c=null,a=await r.requestReferenceSpace(o),me.setContext(r),me.start(),n.isPresenting=!0,n.dispatchEvent({type:`sessionstart`})}},this.getEnvironmentBlendMode=function(){if(r!==null)return r.environmentBlendMode},this.getDepthTexture=function(){return _.getDepthTexture()};function oe(e){for(let t=0;t<e.removed.length;t++){let n=e.removed[t],r=D.indexOf(n);r>=0&&(D[r]=null,C[r].disconnect(n))}for(let t=0;t<e.added.length;t++){let n=e.added[t],r=D.indexOf(n);if(r===-1){for(let e=0;e<C.length;e++)if(e>=D.length){D.push(n),r=e;break}else if(D[e]===null){D[e]=n,r=e;break}if(r===-1)break}let i=C[r];i&&i.connect(n)}}let se=new R,ce=new R;function le(e,t,n){se.setFromMatrixPosition(t.matrixWorld),ce.setFromMatrixPosition(n.matrixWorld);let r=se.distanceTo(ce),i=t.projectionMatrix.elements,a=n.projectionMatrix.elements,o=i[14]/(i[10]-1),s=i[14]/(i[10]+1),c=(i[9]+1)/i[5],l=(i[9]-1)/i[5],u=(i[8]-1)/i[0],d=(a[8]+1)/a[0],f=o*u,p=o*d,m=r/(-u+d),h=m*-u;if(t.matrixWorld.decompose(e.position,e.quaternion,e.scale),e.translateX(h),e.translateZ(m),e.matrixWorld.compose(e.position,e.quaternion,e.scale),e.matrixWorldInverse.copy(e.matrixWorld).invert(),i[10]===-1)e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse);else{let t=o+m,n=s+m,i=f-h,a=p+(r-h),u=c*s/n*t,d=l*s/n*t;e.projectionMatrix.makePerspective(i,a,u,d,t,n),e.projectionMatrixInverse.copy(e.projectionMatrix).invert()}}function ue(e,t){t===null?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}this.updateCamera=function(e){if(r===null)return;let t=e.near,n=e.far;_.texture!==null&&(_.depthNear>0&&(t=_.depthNear),_.depthFar>0&&(n=_.depthFar)),A.near=te.near=k.near=t,A.far=te.far=k.far=n,(re!==A.near||ie!==A.far)&&(r.updateRenderState({depthNear:A.near,depthFar:A.far}),re=A.near,ie=A.far),A.layers.mask=e.layers.mask|6,k.layers.mask=A.layers.mask&3,te.layers.mask=A.layers.mask&5;let i=e.parent,a=A.cameras;ue(A,i);for(let e=0;e<a.length;e++)ue(a[e],i);a.length===2?le(A,k,te):A.projectionMatrix.copy(k.projectionMatrix),de(e,A,i)};function de(e,t,n){n===null?e.matrix.copy(t.matrixWorld):(e.matrix.copy(n.matrixWorld),e.matrix.invert(),e.matrix.multiply(t.matrixWorld)),e.matrix.decompose(e.position,e.quaternion,e.scale),e.updateMatrixWorld(!0),e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse),e.isPerspectiveCamera&&(e.fov=qe*2*Math.atan(1/e.projectionMatrix.elements[5]),e.zoom=1)}this.getCamera=function(){return A},this.getFoveation=function(){if(!(f===null&&p===null))return s},this.setFoveation=function(e){s=e,f!==null&&(f.fixedFoveation=e),p!==null&&p.fixedFoveation!==void 0&&(p.fixedFoveation=e)},this.hasDepthSensing=function(){return _.texture!==null},this.getDepthSensingMesh=function(){return _.getMesh(A)},this.getCameraTexture=function(e){return v[e]};let fe=null;function pe(t,i){if(u=i.getViewerPose(c||a),h=i,u!==null){let t=u.views;p!==null&&(e.setRenderTargetFramebuffer(S,p.framebuffer),e.setRenderTarget(S));let i=!1;t.length!==A.cameras.length&&(A.cameras.length=0,i=!0);for(let n=0;n<t.length;n++){let r=t[n],a=null;if(p!==null)a=p.getViewport(r);else{let t=d.getViewSubImage(f,r);a=t.viewport,n===0&&(e.setRenderTargetTextures(S,t.colorTexture,t.depthStencilTexture),e.setRenderTarget(S))}let o=ne[n];o===void 0&&(o=new ei,o.layers.enable(n),o.viewport=new Bt,ne[n]=o),o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.quaternion,o.scale),o.projectionMatrix.fromArray(r.projectionMatrix),o.projectionMatrixInverse.copy(o.projectionMatrix).invert(),o.viewport.set(a.x,a.y,a.width,a.height),n===0&&(A.matrix.copy(o.matrix),A.matrix.decompose(A.position,A.quaternion,A.scale)),i===!0&&A.cameras.push(o)}let a=r.enabledFeatures;if(a&&a.includes(`depth-sensing`)&&r.depthUsage==`gpu-optimized`&&g){d=n.getBinding();let e=d.getDepthInformation(t[0]);e&&e.isValid&&e.texture&&_.init(e,r.renderState)}if(a&&a.includes(`camera-access`)&&g){e.state.unbindTexture(),d=n.getBinding();for(let e=0;e<t.length;e++){let n=t[e].camera;if(n){let e=v[n];e||(e=new aa,v[n]=e);let t=d.getCameraImage(n);e.sourceTexture=t}}}}for(let e=0;e<C.length;e++){let t=D[e],n=C[e];t!==null&&n!==void 0&&n.update(t,i,c||a)}fe&&fe(t,i),i.detectedPlanes&&n.dispatchEvent({type:`planesdetected`,data:i}),h=null}let me=new Eo;me.setAnimationLoop(pe),this.setAnimationLoop=function(e){fe=e},this.dispose=function(){}}},Cl=new kn,wl=new yn;function Tl(e,t){function n(e,t){e.matrixAutoUpdate===!0&&e.updateMatrix(),t.value.copy(e.matrix)}function r(t,n){n.color.getRGB(t.fogColor.value,Gr(e)),n.isFog?(t.fogNear.value=n.near,t.fogFar.value=n.far):n.isFogExp2&&(t.fogDensity.value=n.density)}function i(e,t,n,r,i){t.isMeshBasicMaterial||t.isMeshLambertMaterial?a(e,t):t.isMeshToonMaterial?(a(e,t),d(e,t)):t.isMeshPhongMaterial?(a(e,t),u(e,t)):t.isMeshStandardMaterial?(a(e,t),f(e,t),t.isMeshPhysicalMaterial&&p(e,t,i)):t.isMeshMatcapMaterial?(a(e,t),m(e,t)):t.isMeshDepthMaterial?a(e,t):t.isMeshDistanceMaterial?(a(e,t),h(e,t)):t.isMeshNormalMaterial?a(e,t):t.isLineBasicMaterial?(o(e,t),t.isLineDashedMaterial&&s(e,t)):t.isPointsMaterial?c(e,t,n,r):t.isSpriteMaterial?l(e,t):t.isShadowMaterial?(e.color.value.copy(t.color),e.opacity.value=t.opacity):t.isShaderMaterial&&(t.uniformsNeedUpdate=!1)}function a(e,r){e.opacity.value=r.opacity,r.color&&e.diffuse.value.copy(r.color),r.emissive&&e.emissive.value.copy(r.emissive).multiplyScalar(r.emissiveIntensity),r.map&&(e.map.value=r.map,n(r.map,e.mapTransform)),r.alphaMap&&(e.alphaMap.value=r.alphaMap,n(r.alphaMap,e.alphaMapTransform)),r.bumpMap&&(e.bumpMap.value=r.bumpMap,n(r.bumpMap,e.bumpMapTransform),e.bumpScale.value=r.bumpScale,r.side===1&&(e.bumpScale.value*=-1)),r.normalMap&&(e.normalMap.value=r.normalMap,n(r.normalMap,e.normalMapTransform),e.normalScale.value.copy(r.normalScale),r.side===1&&e.normalScale.value.negate()),r.displacementMap&&(e.displacementMap.value=r.displacementMap,n(r.displacementMap,e.displacementMapTransform),e.displacementScale.value=r.displacementScale,e.displacementBias.value=r.displacementBias),r.emissiveMap&&(e.emissiveMap.value=r.emissiveMap,n(r.emissiveMap,e.emissiveMapTransform)),r.specularMap&&(e.specularMap.value=r.specularMap,n(r.specularMap,e.specularMapTransform)),r.alphaTest>0&&(e.alphaTest.value=r.alphaTest);let i=t.get(r),a=i.envMap,o=i.envMapRotation;a&&(e.envMap.value=a,Cl.copy(o),Cl.x*=-1,Cl.y*=-1,Cl.z*=-1,a.isCubeTexture&&a.isRenderTargetTexture===!1&&(Cl.y*=-1,Cl.z*=-1),e.envMapRotation.value.setFromMatrix4(wl.makeRotationFromEuler(Cl)),e.flipEnvMap.value=a.isCubeTexture&&a.isRenderTargetTexture===!1?-1:1,e.reflectivity.value=r.reflectivity,e.ior.value=r.ior,e.refractionRatio.value=r.refractionRatio),r.lightMap&&(e.lightMap.value=r.lightMap,e.lightMapIntensity.value=r.lightMapIntensity,n(r.lightMap,e.lightMapTransform)),r.aoMap&&(e.aoMap.value=r.aoMap,e.aoMapIntensity.value=r.aoMapIntensity,n(r.aoMap,e.aoMapTransform))}function o(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform))}function s(e,t){e.dashSize.value=t.dashSize,e.totalSize.value=t.dashSize+t.gapSize,e.scale.value=t.scale}function c(e,t,r,i){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.size.value=t.size*r,e.scale.value=i*.5,t.map&&(e.map.value=t.map,n(t.map,e.uvTransform)),t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform)),t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}function l(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.rotation.value=t.rotation,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform)),t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform)),t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}function u(e,t){e.specular.value.copy(t.specular),e.shininess.value=Math.max(t.shininess,1e-4)}function d(e,t){t.gradientMap&&(e.gradientMap.value=t.gradientMap)}function f(e,t){e.metalness.value=t.metalness,t.metalnessMap&&(e.metalnessMap.value=t.metalnessMap,n(t.metalnessMap,e.metalnessMapTransform)),e.roughness.value=t.roughness,t.roughnessMap&&(e.roughnessMap.value=t.roughnessMap,n(t.roughnessMap,e.roughnessMapTransform)),t.envMap&&(e.envMapIntensity.value=t.envMapIntensity)}function p(e,t,r){e.ior.value=t.ior,t.sheen>0&&(e.sheenColor.value.copy(t.sheenColor).multiplyScalar(t.sheen),e.sheenRoughness.value=t.sheenRoughness,t.sheenColorMap&&(e.sheenColorMap.value=t.sheenColorMap,n(t.sheenColorMap,e.sheenColorMapTransform)),t.sheenRoughnessMap&&(e.sheenRoughnessMap.value=t.sheenRoughnessMap,n(t.sheenRoughnessMap,e.sheenRoughnessMapTransform))),t.clearcoat>0&&(e.clearcoat.value=t.clearcoat,e.clearcoatRoughness.value=t.clearcoatRoughness,t.clearcoatMap&&(e.clearcoatMap.value=t.clearcoatMap,n(t.clearcoatMap,e.clearcoatMapTransform)),t.clearcoatRoughnessMap&&(e.clearcoatRoughnessMap.value=t.clearcoatRoughnessMap,n(t.clearcoatRoughnessMap,e.clearcoatRoughnessMapTransform)),t.clearcoatNormalMap&&(e.clearcoatNormalMap.value=t.clearcoatNormalMap,n(t.clearcoatNormalMap,e.clearcoatNormalMapTransform),e.clearcoatNormalScale.value.copy(t.clearcoatNormalScale),t.side===1&&e.clearcoatNormalScale.value.negate())),t.dispersion>0&&(e.dispersion.value=t.dispersion),t.iridescence>0&&(e.iridescence.value=t.iridescence,e.iridescenceIOR.value=t.iridescenceIOR,e.iridescenceThicknessMinimum.value=t.iridescenceThicknessRange[0],e.iridescenceThicknessMaximum.value=t.iridescenceThicknessRange[1],t.iridescenceMap&&(e.iridescenceMap.value=t.iridescenceMap,n(t.iridescenceMap,e.iridescenceMapTransform)),t.iridescenceThicknessMap&&(e.iridescenceThicknessMap.value=t.iridescenceThicknessMap,n(t.iridescenceThicknessMap,e.iridescenceThicknessMapTransform))),t.transmission>0&&(e.transmission.value=t.transmission,e.transmissionSamplerMap.value=r.texture,e.transmissionSamplerSize.value.set(r.width,r.height),t.transmissionMap&&(e.transmissionMap.value=t.transmissionMap,n(t.transmissionMap,e.transmissionMapTransform)),e.thickness.value=t.thickness,t.thicknessMap&&(e.thicknessMap.value=t.thicknessMap,n(t.thicknessMap,e.thicknessMapTransform)),e.attenuationDistance.value=t.attenuationDistance,e.attenuationColor.value.copy(t.attenuationColor)),t.anisotropy>0&&(e.anisotropyVector.value.set(t.anisotropy*Math.cos(t.anisotropyRotation),t.anisotropy*Math.sin(t.anisotropyRotation)),t.anisotropyMap&&(e.anisotropyMap.value=t.anisotropyMap,n(t.anisotropyMap,e.anisotropyMapTransform))),e.specularIntensity.value=t.specularIntensity,e.specularColor.value.copy(t.specularColor),t.specularColorMap&&(e.specularColorMap.value=t.specularColorMap,n(t.specularColorMap,e.specularColorMapTransform)),t.specularIntensityMap&&(e.specularIntensityMap.value=t.specularIntensityMap,n(t.specularIntensityMap,e.specularIntensityMapTransform))}function m(e,t){t.matcap&&(e.matcap.value=t.matcap)}function h(e,n){let r=t.get(n).light;e.referencePosition.value.setFromMatrixPosition(r.matrixWorld),e.nearDistance.value=r.shadow.camera.near,e.farDistance.value=r.shadow.camera.far}return{refreshFogUniforms:r,refreshMaterialUniforms:i}}function El(e,t,n,r){let i={},a={},o=[],s=e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS);function c(e,t){let n=t.program;r.uniformBlockBinding(e,n)}function l(e,n){let o=i[e.id];o===void 0&&(m(e),o=u(e),i[e.id]=o,e.addEventListener(`dispose`,g));let s=n.program;r.updateUBOMapping(e,s);let c=t.render.frame;a[e.id]!==c&&(f(e),a[e.id]=c)}function u(t){let n=d();t.__bindingPointIndex=n;let r=e.createBuffer(),i=t.__size,a=t.usage;return e.bindBuffer(e.UNIFORM_BUFFER,r),e.bufferData(e.UNIFORM_BUFFER,i,a),e.bindBuffer(e.UNIFORM_BUFFER,null),e.bindBufferBase(e.UNIFORM_BUFFER,n,r),r}function d(){for(let e=0;e<s;e++)if(o.indexOf(e)===-1)return o.push(e),e;return console.error(`THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.`),0}function f(t){let n=i[t.id],r=t.uniforms,a=t.__cache;e.bindBuffer(e.UNIFORM_BUFFER,n);for(let t=0,n=r.length;t<n;t++){let n=Array.isArray(r[t])?r[t]:[r[t]];for(let r=0,i=n.length;r<i;r++){let i=n[r];if(p(i,t,r,a)===!0){let t=i.__offset,n=Array.isArray(i.value)?i.value:[i.value],r=0;for(let a=0;a<n.length;a++){let o=n[a],s=h(o);typeof o==`number`||typeof o==`boolean`?(i.__data[0]=o,e.bufferSubData(e.UNIFORM_BUFFER,t+r,i.__data)):o.isMatrix3?(i.__data[0]=o.elements[0],i.__data[1]=o.elements[1],i.__data[2]=o.elements[2],i.__data[3]=0,i.__data[4]=o.elements[3],i.__data[5]=o.elements[4],i.__data[6]=o.elements[5],i.__data[7]=0,i.__data[8]=o.elements[6],i.__data[9]=o.elements[7],i.__data[10]=o.elements[8],i.__data[11]=0):(o.toArray(i.__data,r),r+=s.storage/Float32Array.BYTES_PER_ELEMENT)}e.bufferSubData(e.UNIFORM_BUFFER,t,i.__data)}}}e.bindBuffer(e.UNIFORM_BUFFER,null)}function p(e,t,n,r){let i=e.value,a=t+`_`+n;if(r[a]===void 0)return typeof i==`number`||typeof i==`boolean`?r[a]=i:r[a]=i.clone(),!0;{let e=r[a];if(typeof i==`number`||typeof i==`boolean`){if(e!==i)return r[a]=i,!0}else if(e.equals(i)===!1)return e.copy(i),!0}return!1}function m(e){let t=e.uniforms,n=0;for(let e=0,r=t.length;e<r;e++){let r=Array.isArray(t[e])?t[e]:[t[e]];for(let e=0,t=r.length;e<t;e++){let t=r[e],i=Array.isArray(t.value)?t.value:[t.value];for(let e=0,r=i.length;e<r;e++){let r=i[e],a=h(r),o=n%16,s=o%a.boundary,c=o+s;n+=s,c!==0&&16-c<a.storage&&(n+=16-c),t.__data=new Float32Array(a.storage/Float32Array.BYTES_PER_ELEMENT),t.__offset=n,n+=a.storage}}}let r=n%16;return r>0&&(n+=16-r),e.__size=n,e.__cache={},this}function h(e){let t={boundary:0,storage:0};return typeof e==`number`||typeof e==`boolean`?(t.boundary=4,t.storage=4):e.isVector2?(t.boundary=8,t.storage=8):e.isVector3||e.isColor?(t.boundary=16,t.storage=12):e.isVector4?(t.boundary=16,t.storage=16):e.isMatrix3?(t.boundary=48,t.storage=48):e.isMatrix4?(t.boundary=64,t.storage=64):e.isTexture?console.warn(`THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.`):console.warn(`THREE.WebGLRenderer: Unsupported uniform value type.`,e),t}function g(t){let n=t.target;n.removeEventListener(`dispose`,g);let r=o.indexOf(n.__bindingPointIndex);o.splice(r,1),e.deleteBuffer(i[n.id]),delete i[n.id],delete a[n.id]}function _(){for(let t in i)e.deleteBuffer(i[t]);o=[],i={},a={}}return{bind:c,update:l,dispose:_}}var Dl=class{constructor(e={}){let{canvas:t=St(),context:n=null,depth:r=!0,stencil:i=!1,alpha:a=!1,antialias:o=!1,premultipliedAlpha:s=!0,preserveDrawingBuffer:u=!1,powerPreference:d=`default`,failIfMajorPerformanceCaveat:f=!1,reversedDepthBuffer:p=!1}=e;this.isWebGLRenderer=!0;let m;if(n!==null){if(typeof WebGLRenderingContext<`u`&&n instanceof WebGLRenderingContext)throw Error(`THREE.WebGLRenderer: WebGL 1 is not supported since r163.`);m=n.getContextAttributes().alpha}else m=a;let h=new Uint32Array(4),_=new Int32Array(4),v=null,y=null,b=[],x=[];this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=0,this.toneMappingExposure=1,this.transmissionResolutionScale=1;let S=this,C=!1;this._outputColorSpace=Ie;let w=0,T=0,E=null,D=-1,ee=null,O=new Bt,k=new Bt,te=null,ne=new B(0),A=0,re=t.width,ie=t.height,j=1,ae=null,oe=null,se=new Bt(0,0,re,ie),ce=new Bt(0,0,re,ie),le=!1,ue=new Ii,de=!1,fe=!1,pe=new yn,me=new R,he=new Bt,ge={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0},_e=!1;function ve(){return E===null?j:1}let M=n;function ye(e,n){return t.getContext(e,n)}try{let e={alpha:!0,depth:r,stencil:i,antialias:o,premultipliedAlpha:s,preserveDrawingBuffer:u,powerPreference:d,failIfMajorPerformanceCaveat:f};if(`setAttribute`in t&&t.setAttribute(`data-engine`,`three.js r180`),t.addEventListener(`webglcontextlost`,Ke,!1),t.addEventListener(`webglcontextrestored`,qe,!1),t.addEventListener(`webglcontextcreationerror`,Je,!1),M===null){let t=`webgl2`;if(M=ye(t,e),M===null)throw ye(t)?Error(`Error creating WebGL context with your selected attributes.`):Error(`Error creating WebGL context.`)}}catch(e){throw console.error(`THREE.WebGLRenderer: `+e.message),e}let be,xe,N,Se,P,F,Ce,we,Te,Ee,De,Oe,ke,Ae,je,Me,Ne,Pe,Fe,Re,ze,Be,Ve,Ue;function We(){be=new os(M),be.init(),Be=new vl(M,be),xe=new Fo(M,be,e,Be),N=new gl(M,be),xe.reversedDepthBuffer&&p&&N.buffers.depth.setReversed(!0),Se=new ls(M),P=new el,F=new _l(M,be,N,P,xe,Be,Se),Ce=new Lo(S),we=new as(S),Te=new Do(M),Ve=new No(M,Te),Ee=new ss(M,Te,Se,Ve),De=new ds(M,Ee,Te,Se),Fe=new us(M,xe,F),Me=new Io(P),Oe=new $c(S,Ce,we,be,xe,Ve,Me),ke=new Tl(S,P),Ae=new il,je=new dl(be),Pe=new Mo(S,Ce,we,N,De,m,s),Ne=new ml(S,De,xe),Ue=new El(M,Se,xe,N),Re=new Po(M,be,Se),ze=new cs(M,be,Se),Se.programs=Oe.programs,S.capabilities=xe,S.extensions=be,S.properties=P,S.renderLists=Ae,S.shadowMap=Ne,S.state=N,S.info=Se}We();let Ge=new Sl(S,M);this.xr=Ge,this.getContext=function(){return M},this.getContextAttributes=function(){return M.getContextAttributes()},this.forceContextLoss=function(){let e=be.get(`WEBGL_lose_context`);e&&e.loseContext()},this.forceContextRestore=function(){let e=be.get(`WEBGL_lose_context`);e&&e.restoreContext()},this.getPixelRatio=function(){return j},this.setPixelRatio=function(e){e!==void 0&&(j=e,this.setSize(re,ie,!1))},this.getSize=function(e){return e.set(re,ie)},this.setSize=function(e,n,r=!0){if(Ge.isPresenting){console.warn(`THREE.WebGLRenderer: Can't change size while VR device is presenting.`);return}re=e,ie=n,t.width=Math.floor(e*j),t.height=Math.floor(n*j),r===!0&&(t.style.width=e+`px`,t.style.height=n+`px`),this.setViewport(0,0,e,n)},this.getDrawingBufferSize=function(e){return e.set(re*j,ie*j).floor()},this.setDrawingBufferSize=function(e,n,r){re=e,ie=n,j=r,t.width=Math.floor(e*r),t.height=Math.floor(n*r),this.setViewport(0,0,e,n)},this.getCurrentViewport=function(e){return e.copy(O)},this.getViewport=function(e){return e.copy(se)},this.setViewport=function(e,t,n,r){e.isVector4?se.set(e.x,e.y,e.z,e.w):se.set(e,t,n,r),N.viewport(O.copy(se).multiplyScalar(j).round())},this.getScissor=function(e){return e.copy(ce)},this.setScissor=function(e,t,n,r){e.isVector4?ce.set(e.x,e.y,e.z,e.w):ce.set(e,t,n,r),N.scissor(k.copy(ce).multiplyScalar(j).round())},this.getScissorTest=function(){return le},this.setScissorTest=function(e){N.setScissorTest(le=e)},this.setOpaqueSort=function(e){ae=e},this.setTransparentSort=function(e){oe=e},this.getClearColor=function(e){return e.copy(Pe.getClearColor())},this.setClearColor=function(){Pe.setClearColor(...arguments)},this.getClearAlpha=function(){return Pe.getClearAlpha()},this.setClearAlpha=function(){Pe.setClearAlpha(...arguments)},this.clear=function(e=!0,t=!0,n=!0){let r=0;if(e){let e=!1;if(E!==null){let t=E.texture.format;e=t===1033||t===1031||t===1029}if(e){let e=E.texture.type,t=e===1009||e===1014||e===1012||e===1020||e===1017||e===1018,n=Pe.getClearColor(),r=Pe.getClearAlpha(),i=n.r,a=n.g,o=n.b;t?(h[0]=i,h[1]=a,h[2]=o,h[3]=r,M.clearBufferuiv(M.COLOR,0,h)):(_[0]=i,_[1]=a,_[2]=o,_[3]=r,M.clearBufferiv(M.COLOR,0,_))}else r|=M.COLOR_BUFFER_BIT}t&&(r|=M.DEPTH_BUFFER_BIT),n&&(r|=M.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),M.clear(r)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){t.removeEventListener(`webglcontextlost`,Ke,!1),t.removeEventListener(`webglcontextrestored`,qe,!1),t.removeEventListener(`webglcontextcreationerror`,Je,!1),Pe.dispose(),Ae.dispose(),je.dispose(),P.dispose(),Ce.dispose(),we.dispose(),De.dispose(),Ve.dispose(),Ue.dispose(),Oe.dispose(),Ge.dispose(),Ge.removeEventListener(`sessionstart`,et),Ge.removeEventListener(`sessionend`,tt),nt.stop()};function Ke(e){e.preventDefault(),console.log(`THREE.WebGLRenderer: Context Lost.`),C=!0}function qe(){console.log(`THREE.WebGLRenderer: Context Restored.`),C=!1;let e=Se.autoReset,t=Ne.enabled,n=Ne.autoUpdate,r=Ne.needsUpdate,i=Ne.type;We(),Se.autoReset=e,Ne.enabled=t,Ne.autoUpdate=n,Ne.needsUpdate=r,Ne.type=i}function Je(e){console.error(`THREE.WebGLRenderer: A WebGL context could not be created. Reason: `,e.statusMessage)}function I(e){let t=e.target;t.removeEventListener(`dispose`,I),Ye(t)}function Ye(e){Xe(e),P.remove(e)}function Xe(e){let t=P.get(e).programs;t!==void 0&&(t.forEach(function(e){Oe.releaseProgram(e)}),e.isShaderMaterial&&Oe.releaseShaderCache(e))}this.renderBufferDirect=function(e,t,n,r,i,a){t===null&&(t=ge);let o=i.isMesh&&i.matrixWorld.determinant()<0,s=dt(e,t,n,r,i);N.setMaterial(r,o);let c=n.index,l=1;if(r.wireframe===!0){if(c=Ee.getWireframeAttribute(n),c===void 0)return;l=2}let u=n.drawRange,d=n.attributes.position,f=u.start*l,p=(u.start+u.count)*l;a!==null&&(f=Math.max(f,a.start*l),p=Math.min(p,(a.start+a.count)*l)),c===null?d!=null&&(f=Math.max(f,0),p=Math.min(p,d.count)):(f=Math.max(f,0),p=Math.min(p,c.count));let m=p-f;if(m<0||m===1/0)return;Ve.setup(i,r,s,n,c);let h,g=Re;if(c!==null&&(h=Te.get(c),g=ze,g.setIndex(h)),i.isMesh)r.wireframe===!0?(N.setLineWidth(r.wireframeLinewidth*ve()),g.setMode(M.LINES)):g.setMode(M.TRIANGLES);else if(i.isLine){let e=r.linewidth;e===void 0&&(e=1),N.setLineWidth(e*ve()),i.isLineSegments?g.setMode(M.LINES):i.isLineLoop?g.setMode(M.LINE_LOOP):g.setMode(M.LINE_STRIP)}else i.isPoints?g.setMode(M.POINTS):i.isSprite&&g.setMode(M.TRIANGLES);if(i.isBatchedMesh)if(i._multiDrawInstances!==null)wt(`THREE.WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.`),g.renderMultiDrawInstances(i._multiDrawStarts,i._multiDrawCounts,i._multiDrawCount,i._multiDrawInstances);else if(be.get(`WEBGL_multi_draw`))g.renderMultiDraw(i._multiDrawStarts,i._multiDrawCounts,i._multiDrawCount);else{let e=i._multiDrawStarts,t=i._multiDrawCounts,n=i._multiDrawCount,a=c?Te.get(c).bytesPerElement:1,o=P.get(r).currentProgram.getUniforms();for(let r=0;r<n;r++)o.setValue(M,`_gl_DrawID`,r),g.render(e[r]/a,t[r])}else if(i.isInstancedMesh)g.renderInstances(f,m,i.count);else if(n.isInstancedBufferGeometry){let e=n._maxInstanceCount===void 0?1/0:n._maxInstanceCount,t=Math.min(n.instanceCount,e);g.renderInstances(f,m,t)}else g.render(f,m)};function Ze(e,t,n){e.transparent===!0&&e.side===2&&e.forceSinglePass===!1?(e.side=1,e.needsUpdate=!0,ct(e,t,n),e.side=0,e.needsUpdate=!0,ct(e,t,n),e.side=2):ct(e,t,n)}this.compile=function(e,t,n=null){n===null&&(n=e),y=je.get(n),y.init(t),x.push(y),n.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&(y.pushLight(e),e.castShadow&&y.pushShadow(e))}),e!==n&&e.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&(y.pushLight(e),e.castShadow&&y.pushShadow(e))}),y.setupLights();let r=new Set;return e.traverse(function(e){if(!(e.isMesh||e.isPoints||e.isLine||e.isSprite))return;let t=e.material;if(t)if(Array.isArray(t))for(let i=0;i<t.length;i++){let a=t[i];Ze(a,n,e),r.add(a)}else Ze(t,n,e),r.add(t)}),y=x.pop(),r},this.compileAsync=function(e,t,n=null){let r=this.compile(e,t,n);return new Promise(t=>{function n(){if(r.forEach(function(e){P.get(e).currentProgram.isReady()&&r.delete(e)}),r.size===0){t(e);return}setTimeout(n,10)}be.get(`KHR_parallel_shader_compile`)===null?setTimeout(n,10):n()})};let Qe=null;function $e(e){Qe&&Qe(e)}function et(){nt.stop()}function tt(){nt.start()}let nt=new Eo;nt.setAnimationLoop($e),typeof self<`u`&&nt.setContext(self),this.setAnimationLoop=function(e){Qe=e,Ge.setAnimationLoop(e),e===null?nt.stop():nt.start()},Ge.addEventListener(`sessionstart`,et),Ge.addEventListener(`sessionend`,tt),this.render=function(e,t){if(t!==void 0&&t.isCamera!==!0){console.error(`THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.`);return}if(C===!0)return;if(e.matrixWorldAutoUpdate===!0&&e.updateMatrixWorld(),t.parent===null&&t.matrixWorldAutoUpdate===!0&&t.updateMatrixWorld(),Ge.enabled===!0&&Ge.isPresenting===!0&&(Ge.cameraAutoUpdate===!0&&Ge.updateCamera(t),t=Ge.getCamera()),e.isScene===!0&&e.onBeforeRender(S,e,t,E),y=je.get(e,x.length),y.init(t),x.push(y),pe.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),ue.setFromProjectionMatrix(pe,He,t.reversedDepth),fe=this.localClippingEnabled,de=Me.init(this.clippingPlanes,fe),v=Ae.get(e,b.length),v.init(),b.push(v),Ge.enabled===!0&&Ge.isPresenting===!0){let e=S.xr.getDepthSensingMesh();e!==null&&rt(e,t,-1/0,S.sortObjects)}rt(e,t,0,S.sortObjects),v.finish(),S.sortObjects===!0&&v.sort(ae,oe),_e=Ge.enabled===!1||Ge.isPresenting===!1||Ge.hasDepthSensing()===!1,_e&&Pe.addToRenderList(v,e),this.info.render.frame++,de===!0&&Me.beginShadows();let n=y.state.shadowsArray;Ne.render(n,e,t),de===!0&&Me.endShadows(),this.info.autoReset===!0&&this.info.reset();let r=v.opaque,i=v.transmissive;if(y.setupLights(),t.isArrayCamera){let n=t.cameras;if(i.length>0)for(let t=0,a=n.length;t<a;t++){let a=n[t];at(r,i,e,a)}_e&&Pe.render(e);for(let t=0,r=n.length;t<r;t++){let r=n[t];it(v,e,r,r.viewport)}}else i.length>0&&at(r,i,e,t),_e&&Pe.render(e),it(v,e,t);E!==null&&T===0&&(F.updateMultisampleRenderTarget(E),F.updateRenderTargetMipmap(E)),e.isScene===!0&&e.onAfterRender(S,e,t),Ve.resetDefaultState(),D=-1,ee=null,x.pop(),x.length>0?(y=x[x.length-1],de===!0&&Me.setGlobalState(S.clippingPlanes,y.state.camera)):y=null,b.pop(),v=b.length>0?b[b.length-1]:null};function rt(e,t,n,r){if(e.visible===!1)return;if(e.layers.test(t.layers)){if(e.isGroup)n=e.renderOrder;else if(e.isLOD)e.autoUpdate===!0&&e.update(t);else if(e.isLight)y.pushLight(e),e.castShadow&&y.pushShadow(e);else if(e.isSprite){if(!e.frustumCulled||ue.intersectsSprite(e)){r&&he.setFromMatrixPosition(e.matrixWorld).applyMatrix4(pe);let t=De.update(e),i=e.material;i.visible&&v.push(e,t,i,n,he.z,null)}}else if((e.isMesh||e.isLine||e.isPoints)&&(!e.frustumCulled||ue.intersectsObject(e))){let t=De.update(e),i=e.material;if(r&&(e.boundingSphere===void 0?(t.boundingSphere===null&&t.computeBoundingSphere(),he.copy(t.boundingSphere.center)):(e.boundingSphere===null&&e.computeBoundingSphere(),he.copy(e.boundingSphere.center)),he.applyMatrix4(e.matrixWorld).applyMatrix4(pe)),Array.isArray(i)){let r=t.groups;for(let a=0,o=r.length;a<o;a++){let o=r[a],s=i[o.materialIndex];s&&s.visible&&v.push(e,t,s,n,he.z,o)}}else i.visible&&v.push(e,t,i,n,he.z,null)}}let i=e.children;for(let e=0,a=i.length;e<a;e++)rt(i[e],t,n,r)}function it(e,t,n,r){let i=e.opaque,a=e.transmissive,o=e.transparent;y.setupLightsView(n),de===!0&&Me.setGlobalState(S.clippingPlanes,n),r&&N.viewport(O.copy(r)),i.length>0&&ot(i,t,n),a.length>0&&ot(a,t,n),o.length>0&&ot(o,t,n),N.buffers.depth.setTest(!0),N.buffers.depth.setMask(!0),N.buffers.color.setMask(!0),N.setPolygonOffset(!1)}function at(e,t,n,r){if((n.isScene===!0?n.overrideMaterial:null)!==null)return;y.state.transmissionRenderTarget[r.id]===void 0&&(y.state.transmissionRenderTarget[r.id]=new Ht(1,1,{generateMipmaps:!0,type:be.has(`EXT_color_buffer_half_float`)||be.has(`EXT_color_buffer_float`)?g:l,minFilter:c,samples:4,stencilBuffer:i,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:kt.workingColorSpace}));let a=y.state.transmissionRenderTarget[r.id],o=r.viewport||O;a.setSize(o.z*S.transmissionResolutionScale,o.w*S.transmissionResolutionScale);let s=S.getRenderTarget(),u=S.getActiveCubeFace(),d=S.getActiveMipmapLevel();S.setRenderTarget(a),S.getClearColor(ne),A=S.getClearAlpha(),A<1&&S.setClearColor(16777215,.5),S.clear(),_e&&Pe.render(n);let f=S.toneMapping;S.toneMapping=0;let p=r.viewport;if(r.viewport!==void 0&&(r.viewport=void 0),y.setupLightsView(r),de===!0&&Me.setGlobalState(S.clippingPlanes,r),ot(e,n,r),F.updateMultisampleRenderTarget(a),F.updateRenderTargetMipmap(a),be.has(`WEBGL_multisampled_render_to_texture`)===!1){let e=!1;for(let i=0,a=t.length;i<a;i++){let a=t[i],o=a.object,s=a.geometry,c=a.material,l=a.group;if(c.side===2&&o.layers.test(r.layers)){let t=c.side;c.side=1,c.needsUpdate=!0,st(o,n,r,s,c,l),c.side=t,c.needsUpdate=!0,e=!0}}e===!0&&(F.updateMultisampleRenderTarget(a),F.updateRenderTargetMipmap(a))}S.setRenderTarget(s,u,d),S.setClearColor(ne,A),p!==void 0&&(r.viewport=p),S.toneMapping=f}function ot(e,t,n){let r=t.isScene===!0?t.overrideMaterial:null;for(let i=0,a=e.length;i<a;i++){let a=e[i],o=a.object,s=a.geometry,c=a.group,l=a.material;l.allowOverride===!0&&r!==null&&(l=r),o.layers.test(n.layers)&&st(o,t,n,s,l,c)}}function st(e,t,n,r,i,a){e.onBeforeRender(S,t,n,r,i,a),e.modelViewMatrix.multiplyMatrices(n.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix),i.onBeforeRender(S,t,n,r,e,a),i.transparent===!0&&i.side===2&&i.forceSinglePass===!1?(i.side=1,i.needsUpdate=!0,S.renderBufferDirect(n,t,r,i,e,a),i.side=0,i.needsUpdate=!0,S.renderBufferDirect(n,t,r,i,e,a),i.side=2):S.renderBufferDirect(n,t,r,i,e,a),e.onAfterRender(S,t,n,r,i,a)}function ct(e,t,n){t.isScene!==!0&&(t=ge);let r=P.get(e),i=y.state.lights,a=y.state.shadowsArray,o=i.state.version,s=Oe.getParameters(e,i.state,a,t,n),c=Oe.getProgramCacheKey(s),l=r.programs;r.environment=e.isMeshStandardMaterial?t.environment:null,r.fog=t.fog,r.envMap=(e.isMeshStandardMaterial?we:Ce).get(e.envMap||r.environment),r.envMapRotation=r.environment!==null&&e.envMap===null?t.environmentRotation:e.envMapRotation,l===void 0&&(e.addEventListener(`dispose`,I),l=new Map,r.programs=l);let u=l.get(c);if(u!==void 0){if(r.currentProgram===u&&r.lightsStateVersion===o)return ut(e,s),u}else s.uniforms=Oe.getUniforms(e),e.onBeforeCompile(s,S),u=Oe.acquireProgram(s,c),l.set(c,u),r.uniforms=s.uniforms;let d=r.uniforms;return(!e.isShaderMaterial&&!e.isRawShaderMaterial||e.clipping===!0)&&(d.clippingPlanes=Me.uniform),ut(e,s),r.needsLights=pt(e),r.lightsStateVersion=o,r.needsLights&&(d.ambientLightColor.value=i.state.ambient,d.lightProbe.value=i.state.probe,d.directionalLights.value=i.state.directional,d.directionalLightShadows.value=i.state.directionalShadow,d.spotLights.value=i.state.spot,d.spotLightShadows.value=i.state.spotShadow,d.rectAreaLights.value=i.state.rectArea,d.ltc_1.value=i.state.rectAreaLTC1,d.ltc_2.value=i.state.rectAreaLTC2,d.pointLights.value=i.state.point,d.pointLightShadows.value=i.state.pointShadow,d.hemisphereLights.value=i.state.hemi,d.directionalShadowMap.value=i.state.directionalShadowMap,d.directionalShadowMatrix.value=i.state.directionalShadowMatrix,d.spotShadowMap.value=i.state.spotShadowMap,d.spotLightMatrix.value=i.state.spotLightMatrix,d.spotLightMap.value=i.state.spotLightMap,d.pointShadowMap.value=i.state.pointShadowMap,d.pointShadowMatrix.value=i.state.pointShadowMatrix),r.currentProgram=u,r.uniformsList=null,u}function lt(e){if(e.uniformsList===null){let t=e.currentProgram.getUniforms();e.uniformsList=vc.seqWithValue(t.seq,e.uniforms)}return e.uniformsList}function ut(e,t){let n=P.get(e);n.outputColorSpace=t.outputColorSpace,n.batching=t.batching,n.batchingColor=t.batchingColor,n.instancing=t.instancing,n.instancingColor=t.instancingColor,n.instancingMorph=t.instancingMorph,n.skinning=t.skinning,n.morphTargets=t.morphTargets,n.morphNormals=t.morphNormals,n.morphColors=t.morphColors,n.morphTargetsCount=t.morphTargetsCount,n.numClippingPlanes=t.numClippingPlanes,n.numIntersection=t.numClipIntersection,n.vertexAlphas=t.vertexAlphas,n.vertexTangents=t.vertexTangents,n.toneMapping=t.toneMapping}function dt(e,t,n,r,i){t.isScene!==!0&&(t=ge),F.resetTextureUnits();let a=t.fog,o=r.isMeshStandardMaterial?t.environment:null,s=E===null?S.outputColorSpace:E.isXRRenderTarget===!0?E.texture.colorSpace:Le,c=(r.isMeshStandardMaterial?we:Ce).get(r.envMap||o),l=r.vertexColors===!0&&!!n.attributes.color&&n.attributes.color.itemSize===4,u=!!n.attributes.tangent&&(!!r.normalMap||r.anisotropy>0),d=!!n.morphAttributes.position,f=!!n.morphAttributes.normal,p=!!n.morphAttributes.color,m=0;r.toneMapped&&(E===null||E.isXRRenderTarget===!0)&&(m=S.toneMapping);let h=n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color,g=h===void 0?0:h.length,_=P.get(r),v=y.state.lights;if(de===!0&&(fe===!0||e!==ee)){let t=e===ee&&r.id===D;Me.setState(r,e,t)}let b=!1;r.version===_.__version?_.needsLights&&_.lightsStateVersion!==v.state.version?b=!0:_.outputColorSpace===s?i.isBatchedMesh&&_.batching===!1||!i.isBatchedMesh&&_.batching===!0||i.isBatchedMesh&&_.batchingColor===!0&&i.colorTexture===null||i.isBatchedMesh&&_.batchingColor===!1&&i.colorTexture!==null||i.isInstancedMesh&&_.instancing===!1||!i.isInstancedMesh&&_.instancing===!0||i.isSkinnedMesh&&_.skinning===!1||!i.isSkinnedMesh&&_.skinning===!0||i.isInstancedMesh&&_.instancingColor===!0&&i.instanceColor===null||i.isInstancedMesh&&_.instancingColor===!1&&i.instanceColor!==null||i.isInstancedMesh&&_.instancingMorph===!0&&i.morphTexture===null||i.isInstancedMesh&&_.instancingMorph===!1&&i.morphTexture!==null?b=!0:_.envMap===c?r.fog===!0&&_.fog!==a||_.numClippingPlanes!==void 0&&(_.numClippingPlanes!==Me.numPlanes||_.numIntersection!==Me.numIntersection)?b=!0:_.vertexAlphas===l&&_.vertexTangents===u&&_.morphTargets===d&&_.morphNormals===f&&_.morphColors===p&&_.toneMapping===m?_.morphTargetsCount!==g&&(b=!0):b=!0:b=!0:b=!0:(b=!0,_.__version=r.version);let x=_.currentProgram;b===!0&&(x=ct(r,t,i));let C=!1,w=!1,T=!1,O=x.getUniforms(),k=_.uniforms;if(N.useProgram(x.program)&&(C=!0,w=!0,T=!0),r.id!==D&&(D=r.id,w=!0),C||ee!==e){N.buffers.depth.getReversed()&&e.reversedDepth!==!0&&(e._reversedDepth=!0,e.updateProjectionMatrix()),O.setValue(M,`projectionMatrix`,e.projectionMatrix),O.setValue(M,`viewMatrix`,e.matrixWorldInverse);let t=O.map.cameraPosition;t!==void 0&&t.setValue(M,me.setFromMatrixPosition(e.matrixWorld)),xe.logarithmicDepthBuffer&&O.setValue(M,`logDepthBufFC`,2/(Math.log(e.far+1)/Math.LN2)),(r.isMeshPhongMaterial||r.isMeshToonMaterial||r.isMeshLambertMaterial||r.isMeshBasicMaterial||r.isMeshStandardMaterial||r.isShaderMaterial)&&O.setValue(M,`isOrthographic`,e.isOrthographicCamera===!0),ee!==e&&(ee=e,w=!0,T=!0)}if(i.isSkinnedMesh){O.setOptional(M,i,`bindMatrix`),O.setOptional(M,i,`bindMatrixInverse`);let e=i.skeleton;e&&(e.boneTexture===null&&e.computeBoneTexture(),O.setValue(M,`boneTexture`,e.boneTexture,F))}i.isBatchedMesh&&(O.setOptional(M,i,`batchingTexture`),O.setValue(M,`batchingTexture`,i._matricesTexture,F),O.setOptional(M,i,`batchingIdTexture`),O.setValue(M,`batchingIdTexture`,i._indirectTexture,F),O.setOptional(M,i,`batchingColorTexture`),i._colorsTexture!==null&&O.setValue(M,`batchingColorTexture`,i._colorsTexture,F));let te=n.morphAttributes;if((te.position!==void 0||te.normal!==void 0||te.color!==void 0)&&Fe.update(i,n,x),(w||_.receiveShadow!==i.receiveShadow)&&(_.receiveShadow=i.receiveShadow,O.setValue(M,`receiveShadow`,i.receiveShadow)),r.isMeshGouraudMaterial&&r.envMap!==null&&(k.envMap.value=c,k.flipEnvMap.value=c.isCubeTexture&&c.isRenderTargetTexture===!1?-1:1),r.isMeshStandardMaterial&&r.envMap===null&&t.environment!==null&&(k.envMapIntensity.value=t.environmentIntensity),w&&(O.setValue(M,`toneMappingExposure`,S.toneMappingExposure),_.needsLights&&ft(k,T),a&&r.fog===!0&&ke.refreshFogUniforms(k,a),ke.refreshMaterialUniforms(k,r,j,ie,y.state.transmissionRenderTarget[e.id]),vc.upload(M,lt(_),k,F)),r.isShaderMaterial&&r.uniformsNeedUpdate===!0&&(vc.upload(M,lt(_),k,F),r.uniformsNeedUpdate=!1),r.isSpriteMaterial&&O.setValue(M,`center`,i.center),O.setValue(M,`modelViewMatrix`,i.modelViewMatrix),O.setValue(M,`normalMatrix`,i.normalMatrix),O.setValue(M,`modelMatrix`,i.matrixWorld),r.isShaderMaterial||r.isRawShaderMaterial){let e=r.uniformsGroups;for(let t=0,n=e.length;t<n;t++){let n=e[t];Ue.update(n,x),Ue.bind(n,x)}}return x}function ft(e,t){e.ambientLightColor.needsUpdate=t,e.lightProbe.needsUpdate=t,e.directionalLights.needsUpdate=t,e.directionalLightShadows.needsUpdate=t,e.pointLights.needsUpdate=t,e.pointLightShadows.needsUpdate=t,e.spotLights.needsUpdate=t,e.spotLightShadows.needsUpdate=t,e.rectAreaLights.needsUpdate=t,e.hemisphereLights.needsUpdate=t}function pt(e){return e.isMeshLambertMaterial||e.isMeshToonMaterial||e.isMeshPhongMaterial||e.isMeshStandardMaterial||e.isShadowMaterial||e.isShaderMaterial&&e.lights===!0}this.getActiveCubeFace=function(){return w},this.getActiveMipmapLevel=function(){return T},this.getRenderTarget=function(){return E},this.setRenderTargetTextures=function(e,t,n){let r=P.get(e);r.__autoAllocateDepthBuffer=e.resolveDepthBuffer===!1,r.__autoAllocateDepthBuffer===!1&&(r.__useRenderToTexture=!1),P.get(e.texture).__webglTexture=t,P.get(e.depthTexture).__webglTexture=r.__autoAllocateDepthBuffer?void 0:n,r.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(e,t){let n=P.get(e);n.__webglFramebuffer=t,n.__useDefaultFramebuffer=t===void 0};let mt=M.createFramebuffer();this.setRenderTarget=function(e,t=0,n=0){E=e,w=t,T=n;let r=!0,i=null,a=!1,o=!1;if(e){let s=P.get(e);if(s.__useDefaultFramebuffer!==void 0)N.bindFramebuffer(M.FRAMEBUFFER,null),r=!1;else if(s.__webglFramebuffer===void 0)F.setupRenderTarget(e);else if(s.__hasExternalTextures)F.rebindTextures(e,P.get(e.texture).__webglTexture,P.get(e.depthTexture).__webglTexture);else if(e.depthBuffer){let t=e.depthTexture;if(s.__boundDepthTexture!==t){if(t!==null&&P.has(t)&&(e.width!==t.image.width||e.height!==t.image.height))throw Error(`WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.`);F.setupDepthRenderbuffer(e)}}let c=e.texture;(c.isData3DTexture||c.isDataArrayTexture||c.isCompressedArrayTexture)&&(o=!0);let l=P.get(e).__webglFramebuffer;e.isWebGLCubeRenderTarget?(i=Array.isArray(l[t])?l[t][n]:l[t],a=!0):i=e.samples>0&&F.useMultisampledRTT(e)===!1?P.get(e).__webglMultisampledFramebuffer:Array.isArray(l)?l[n]:l,O.copy(e.viewport),k.copy(e.scissor),te=e.scissorTest}else O.copy(se).multiplyScalar(j).floor(),k.copy(ce).multiplyScalar(j).floor(),te=le;if(n!==0&&(i=mt),N.bindFramebuffer(M.FRAMEBUFFER,i)&&r&&N.drawBuffers(e,i),N.viewport(O),N.scissor(k),N.setScissorTest(te),a){let r=P.get(e.texture);M.framebufferTexture2D(M.FRAMEBUFFER,M.COLOR_ATTACHMENT0,M.TEXTURE_CUBE_MAP_POSITIVE_X+t,r.__webglTexture,n)}else if(o){let r=t;for(let t=0;t<e.textures.length;t++){let i=P.get(e.textures[t]);M.framebufferTextureLayer(M.FRAMEBUFFER,M.COLOR_ATTACHMENT0+t,i.__webglTexture,n,r)}}else if(e!==null&&n!==0){let t=P.get(e.texture);M.framebufferTexture2D(M.FRAMEBUFFER,M.COLOR_ATTACHMENT0,M.TEXTURE_2D,t.__webglTexture,n)}D=-1},this.readRenderTargetPixels=function(e,t,n,r,i,a,o,s=0){if(!(e&&e.isWebGLRenderTarget)){console.error(`THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.`);return}let c=P.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&o!==void 0&&(c=c[o]),c){N.bindFramebuffer(M.FRAMEBUFFER,c);try{let o=e.textures[s],c=o.format,l=o.type;if(!xe.textureFormatReadable(c)){console.error(`THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.`);return}if(!xe.textureTypeReadable(l)){console.error(`THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.`);return}t>=0&&t<=e.width-r&&n>=0&&n<=e.height-i&&(e.textures.length>1&&M.readBuffer(M.COLOR_ATTACHMENT0+s),M.readPixels(t,n,r,i,Be.convert(c),Be.convert(l),a))}finally{let e=E===null?null:P.get(E).__webglFramebuffer;N.bindFramebuffer(M.FRAMEBUFFER,e)}}},this.readRenderTargetPixelsAsync=async function(e,t,n,r,i,a,o,s=0){if(!(e&&e.isWebGLRenderTarget))throw Error(`THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.`);let c=P.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&o!==void 0&&(c=c[o]),c)if(t>=0&&t<=e.width-r&&n>=0&&n<=e.height-i){N.bindFramebuffer(M.FRAMEBUFFER,c);let o=e.textures[s],l=o.format,u=o.type;if(!xe.textureFormatReadable(l))throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.`);if(!xe.textureTypeReadable(u))throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.`);let d=M.createBuffer();M.bindBuffer(M.PIXEL_PACK_BUFFER,d),M.bufferData(M.PIXEL_PACK_BUFFER,a.byteLength,M.STREAM_READ),e.textures.length>1&&M.readBuffer(M.COLOR_ATTACHMENT0+s),M.readPixels(t,n,r,i,Be.convert(l),Be.convert(u),0);let f=E===null?null:P.get(E).__webglFramebuffer;N.bindFramebuffer(M.FRAMEBUFFER,f);let p=M.fenceSync(M.SYNC_GPU_COMMANDS_COMPLETE,0);return M.flush(),await Tt(M,p,4),M.bindBuffer(M.PIXEL_PACK_BUFFER,d),M.getBufferSubData(M.PIXEL_PACK_BUFFER,0,a),M.deleteBuffer(d),M.deleteSync(p),a}else throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.`)},this.copyFramebufferToTexture=function(e,t=null,n=0){let r=2**-n,i=Math.floor(e.image.width*r),a=Math.floor(e.image.height*r),o=t===null?0:t.x,s=t===null?0:t.y;F.setTexture2D(e,0),M.copyTexSubImage2D(M.TEXTURE_2D,n,0,0,o,s,i,a),N.unbindTexture()};let ht=M.createFramebuffer(),L=M.createFramebuffer();this.copyTextureToTexture=function(e,t,n=null,r=null,i=0,a=null){a===null&&(i===0?a=0:(wt(`WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels.`),a=i,i=0));let o,s,c,l,u,d,f,p,m,h=e.isCompressedTexture?e.mipmaps[a]:e.image;if(n!==null)o=n.max.x-n.min.x,s=n.max.y-n.min.y,c=n.isBox3?n.max.z-n.min.z:1,l=n.min.x,u=n.min.y,d=n.isBox3?n.min.z:0;else{let t=2**-i;o=Math.floor(h.width*t),s=Math.floor(h.height*t),c=e.isDataArrayTexture?h.depth:e.isData3DTexture?Math.floor(h.depth*t):1,l=0,u=0,d=0}r===null?(f=0,p=0,m=0):(f=r.x,p=r.y,m=r.z);let g=Be.convert(t.format),_=Be.convert(t.type),v;t.isData3DTexture?(F.setTexture3D(t,0),v=M.TEXTURE_3D):t.isDataArrayTexture||t.isCompressedArrayTexture?(F.setTexture2DArray(t,0),v=M.TEXTURE_2D_ARRAY):(F.setTexture2D(t,0),v=M.TEXTURE_2D),M.pixelStorei(M.UNPACK_FLIP_Y_WEBGL,t.flipY),M.pixelStorei(M.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),M.pixelStorei(M.UNPACK_ALIGNMENT,t.unpackAlignment);let y=M.getParameter(M.UNPACK_ROW_LENGTH),b=M.getParameter(M.UNPACK_IMAGE_HEIGHT),x=M.getParameter(M.UNPACK_SKIP_PIXELS),S=M.getParameter(M.UNPACK_SKIP_ROWS),C=M.getParameter(M.UNPACK_SKIP_IMAGES);M.pixelStorei(M.UNPACK_ROW_LENGTH,h.width),M.pixelStorei(M.UNPACK_IMAGE_HEIGHT,h.height),M.pixelStorei(M.UNPACK_SKIP_PIXELS,l),M.pixelStorei(M.UNPACK_SKIP_ROWS,u),M.pixelStorei(M.UNPACK_SKIP_IMAGES,d);let w=e.isDataArrayTexture||e.isData3DTexture,T=t.isDataArrayTexture||t.isData3DTexture;if(e.isDepthTexture){let n=P.get(e),r=P.get(t),h=P.get(n.__renderTarget),g=P.get(r.__renderTarget);N.bindFramebuffer(M.READ_FRAMEBUFFER,h.__webglFramebuffer),N.bindFramebuffer(M.DRAW_FRAMEBUFFER,g.__webglFramebuffer);for(let n=0;n<c;n++)w&&(M.framebufferTextureLayer(M.READ_FRAMEBUFFER,M.COLOR_ATTACHMENT0,P.get(e).__webglTexture,i,d+n),M.framebufferTextureLayer(M.DRAW_FRAMEBUFFER,M.COLOR_ATTACHMENT0,P.get(t).__webglTexture,a,m+n)),M.blitFramebuffer(l,u,o,s,f,p,o,s,M.DEPTH_BUFFER_BIT,M.NEAREST);N.bindFramebuffer(M.READ_FRAMEBUFFER,null),N.bindFramebuffer(M.DRAW_FRAMEBUFFER,null)}else if(i!==0||e.isRenderTargetTexture||P.has(e)){let n=P.get(e),r=P.get(t);N.bindFramebuffer(M.READ_FRAMEBUFFER,ht),N.bindFramebuffer(M.DRAW_FRAMEBUFFER,L);for(let e=0;e<c;e++)w?M.framebufferTextureLayer(M.READ_FRAMEBUFFER,M.COLOR_ATTACHMENT0,n.__webglTexture,i,d+e):M.framebufferTexture2D(M.READ_FRAMEBUFFER,M.COLOR_ATTACHMENT0,M.TEXTURE_2D,n.__webglTexture,i),T?M.framebufferTextureLayer(M.DRAW_FRAMEBUFFER,M.COLOR_ATTACHMENT0,r.__webglTexture,a,m+e):M.framebufferTexture2D(M.DRAW_FRAMEBUFFER,M.COLOR_ATTACHMENT0,M.TEXTURE_2D,r.__webglTexture,a),i===0?T?M.copyTexSubImage3D(v,a,f,p,m+e,l,u,o,s):M.copyTexSubImage2D(v,a,f,p,l,u,o,s):M.blitFramebuffer(l,u,o,s,f,p,o,s,M.COLOR_BUFFER_BIT,M.NEAREST);N.bindFramebuffer(M.READ_FRAMEBUFFER,null),N.bindFramebuffer(M.DRAW_FRAMEBUFFER,null)}else T?e.isDataTexture||e.isData3DTexture?M.texSubImage3D(v,a,f,p,m,o,s,c,g,_,h.data):t.isCompressedArrayTexture?M.compressedTexSubImage3D(v,a,f,p,m,o,s,c,g,h.data):M.texSubImage3D(v,a,f,p,m,o,s,c,g,_,h):e.isDataTexture?M.texSubImage2D(M.TEXTURE_2D,a,f,p,o,s,g,_,h.data):e.isCompressedTexture?M.compressedTexSubImage2D(M.TEXTURE_2D,a,f,p,h.width,h.height,g,h.data):M.texSubImage2D(M.TEXTURE_2D,a,f,p,o,s,g,_,h);M.pixelStorei(M.UNPACK_ROW_LENGTH,y),M.pixelStorei(M.UNPACK_IMAGE_HEIGHT,b),M.pixelStorei(M.UNPACK_SKIP_PIXELS,x),M.pixelStorei(M.UNPACK_SKIP_ROWS,S),M.pixelStorei(M.UNPACK_SKIP_IMAGES,C),a===0&&t.generateMipmaps&&M.generateMipmap(v),N.unbindTexture()},this.initRenderTarget=function(e){P.get(e).__webglFramebuffer===void 0&&F.setupRenderTarget(e)},this.initTexture=function(e){e.isCubeTexture?F.setTextureCube(e,0):e.isData3DTexture?F.setTexture3D(e,0):e.isDataArrayTexture||e.isCompressedArrayTexture?F.setTexture2DArray(e,0):F.setTexture2D(e,0),N.unbindTexture()},this.resetState=function(){w=0,T=0,E=null,N.reset(),Ve.reset()},typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`observe`,{detail:this}))}get coordinateSystem(){return He}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;let t=this.getContext();t.drawingBufferColorSpace=kt._getDrawingBufferColorSpace(e),t.unpackColorSpace=kt._getUnpackColorSpace()}},Ol={LEFT:1,RIGHT:2,MIDDLE:4},K=Object.freeze({NONE:0,ROTATE:1,TRUCK:2,SCREEN_PAN:4,OFFSET:8,DOLLY:16,ZOOM:32,TOUCH_ROTATE:64,TOUCH_TRUCK:128,TOUCH_SCREEN_PAN:256,TOUCH_OFFSET:512,TOUCH_DOLLY:1024,TOUCH_ZOOM:2048,TOUCH_DOLLY_TRUCK:4096,TOUCH_DOLLY_SCREEN_PAN:8192,TOUCH_DOLLY_OFFSET:16384,TOUCH_DOLLY_ROTATE:32768,TOUCH_ZOOM_TRUCK:65536,TOUCH_ZOOM_OFFSET:131072,TOUCH_ZOOM_SCREEN_PAN:262144,TOUCH_ZOOM_ROTATE:524288}),kl={NONE:0,IN:1,OUT:-1};function Al(e){return e.isPerspectiveCamera}function jl(e){return e.isOrthographicCamera}var Ml=Math.PI*2,Nl=Math.PI/2,Pl=1e-5,Fl=Math.PI/180;function Il(e,t,n){return Math.max(t,Math.min(n,e))}function Ll(e,t=Pl){return Math.abs(e)<t}function Rl(e,t,n=Pl){return Ll(e-t,n)}function zl(e,t){return Math.round(e/t)*t}function Bl(e){return isFinite(e)?e:e<0?-Number.MAX_VALUE:Number.MAX_VALUE}function Vl(e){return Math.abs(e)<Number.MAX_VALUE?e:e*(1/0)}function Hl(e,t,n,r,i=1/0,a){r=Math.max(1e-4,r);let o=2/r,s=o*a,c=1/(1+s+.48*s*s+.235*s*s*s),l=e-t,u=t,d=i*r;l=Il(l,-d,d),t=e-l;let f=(n.value+o*l)*a;n.value=(n.value-o*f)*c;let p=t+(l+f)*c;return u-e>0==p>u&&(p=u,n.value=(p-u)/a),p}function Ul(e,t,n,r,i=1/0,a,o){r=Math.max(1e-4,r);let s=2/r,c=s*a,l=1/(1+c+.48*c*c+.235*c*c*c),u=t.x,d=t.y,f=t.z,p=e.x-u,m=e.y-d,h=e.z-f,g=u,_=d,v=f,y=i*r,b=y*y,x=p*p+m*m+h*h;if(x>b){let e=Math.sqrt(x);p=p/e*y,m=m/e*y,h=h/e*y}u=e.x-p,d=e.y-m,f=e.z-h;let S=(n.x+s*p)*a,C=(n.y+s*m)*a,w=(n.z+s*h)*a;n.x=(n.x-s*S)*l,n.y=(n.y-s*C)*l,n.z=(n.z-s*w)*l,o.x=u+(p+S)*l,o.y=d+(m+C)*l,o.z=f+(h+w)*l;let T=g-e.x,E=_-e.y,D=v-e.z,ee=o.x-g,O=o.y-_,k=o.z-v;return T*ee+E*O+D*k>0&&(o.x=g,o.y=_,o.z=v,n.x=(o.x-g)/a,n.y=(o.y-_)/a,n.z=(o.z-v)/a),o}function Wl(e,t){t.set(0,0),e.forEach(e=>{t.x+=e.clientX,t.y+=e.clientY}),t.x/=e.length,t.y/=e.length}function Gl(e,t){return jl(e)?(console.warn(`${t} is not supported in OrthographicCamera`),!0):!1}var Kl=class{_listeners={};addEventListener(e,t){let n=this._listeners;n[e]===void 0&&(n[e]=[]),n[e].indexOf(t)===-1&&n[e].push(t)}hasEventListener(e,t){let n=this._listeners;return n[e]!==void 0&&n[e].indexOf(t)!==-1}removeEventListener(e,t){let n=this._listeners[e];if(n!==void 0){let e=n.indexOf(t);e!==-1&&n.splice(e,1)}}removeAllEventListeners(e){if(!e){this._listeners={};return}Array.isArray(this._listeners[e])&&(this._listeners[e].length=0)}dispatchEvent(e){let t=this._listeners[e.type];if(t!==void 0){e.target=this;let n=t.slice(0);for(let t=0,r=n.length;t<r;t++)n[t].call(this,e)}}},ql=`3.1.2`,Jl=1/8,Yl=/Mac/.test(globalThis?.navigator?.platform),q,Xl,Zl,Ql,$l,J,eu,tu,nu,ru,iu,au,ou,su,cu,lu,uu,du,fu,pu,mu,hu,gu,_u=class e extends Kl{static install(e){q=e.THREE,Xl=Object.freeze(new q.Vector3(0,0,0)),Zl=Object.freeze(new q.Vector3(0,1,0)),Ql=Object.freeze(new q.Vector3(0,0,1)),$l=new q.Vector2,J=new q.Vector3,eu=new q.Vector3,tu=new q.Vector3,nu=new q.Vector3,ru=new q.Vector3,iu=new q.Vector3,au=new q.Vector3,ou=new q.Vector3,su=new q.Vector3,cu=new q.Spherical,lu=new q.Spherical,uu=new q.Box3,du=new q.Box3,fu=new q.Sphere,pu=new q.Quaternion,mu=new q.Quaternion,hu=new q.Matrix4,gu=new q.Raycaster}static get ACTION(){return K}minPolarAngle=0;maxPolarAngle=Math.PI;minAzimuthAngle=-1/0;maxAzimuthAngle=1/0;minDistance=2**-52;maxDistance=1/0;infinityDolly=!1;minZoom=.01;maxZoom=1/0;smoothTime=.25;draggingSmoothTime=.125;maxSpeed=1/0;azimuthRotateSpeed=1;polarRotateSpeed=1;dollySpeed=1;dollyDragInverted=!1;truckSpeed=2;dollyToCursor=!1;dragToOffset=!1;boundaryFriction=0;restThreshold=.01;colliderMeshes=[];mouseButtons;touches;cancel=()=>{};lockPointer;unlockPointer;_enabled=!0;_camera;_yAxisUpSpace;_yAxisUpSpaceInverse;_state=K.NONE;_domElement;_viewport=null;_target;_targetEnd;_focalOffset;_focalOffsetEnd;_spherical;_sphericalEnd;_lastDistance;_zoom;_zoomEnd;_lastZoom;_cameraUp0;_target0;_position0;_zoom0;_focalOffset0;_dollyControlCoord;_changedDolly=0;_changedZoom=0;_nearPlaneCorners;_hasRested=!0;_boundary;_boundaryEnclosesCamera=!1;_needsUpdate=!0;_updatedLastTime=!1;_elementRect=new DOMRect;_isDragging=!1;_dragNeedsUpdate=!0;_activePointers=[];_lockedPointer=null;_interactiveArea=new DOMRect(0,0,1,1);_isUserControllingRotate=!1;_isUserControllingDolly=!1;_isUserControllingTruck=!1;_isUserControllingOffset=!1;_isUserControllingZoom=!1;_lastDollyDirection=kl.NONE;_thetaVelocity={value:0};_phiVelocity={value:0};_radiusVelocity={value:0};_targetVelocity=new q.Vector3;_focalOffsetVelocity=new q.Vector3;_zoomVelocity={value:0};set verticalDragToForward(e){console.warn("camera-controls: `verticalDragToForward` was removed. Use `mouseButtons.left = CameraControls.ACTION.SCREEN_PAN` instead.")}constructor(t,n){super(),q===void 0&&console.error("camera-controls: `THREE` is undefined. You must first run `CameraControls.install( { THREE: THREE } )`. Check the docs for further information."),this._camera=t,this._yAxisUpSpace=new q.Quaternion().setFromUnitVectors(this._camera.up,Zl),this._yAxisUpSpaceInverse=this._yAxisUpSpace.clone().invert(),this._state=K.NONE,this._target=new q.Vector3,this._targetEnd=this._target.clone(),this._focalOffset=new q.Vector3,this._focalOffsetEnd=this._focalOffset.clone(),this._spherical=new q.Spherical().setFromVector3(J.copy(this._camera.position).applyQuaternion(this._yAxisUpSpace)),this._sphericalEnd=this._spherical.clone(),this._lastDistance=this._spherical.radius,this._zoom=this._camera.zoom,this._zoomEnd=this._zoom,this._lastZoom=this._zoom,this._nearPlaneCorners=[new q.Vector3,new q.Vector3,new q.Vector3,new q.Vector3],this._updateNearPlaneCorners(),this._boundary=new q.Box3(new q.Vector3(-1/0,-1/0,-1/0),new q.Vector3(1/0,1/0,1/0)),this._cameraUp0=this._camera.up.clone(),this._target0=this._target.clone(),this._position0=this._camera.position.clone(),this._zoom0=this._zoom,this._focalOffset0=this._focalOffset.clone(),this._dollyControlCoord=new q.Vector2,this.mouseButtons={left:K.ROTATE,middle:K.DOLLY,right:K.TRUCK,wheel:Al(this._camera)?K.DOLLY:jl(this._camera)?K.ZOOM:K.NONE},this.touches={one:K.TOUCH_ROTATE,two:Al(this._camera)?K.TOUCH_DOLLY_TRUCK:jl(this._camera)?K.TOUCH_ZOOM_TRUCK:K.NONE,three:K.TOUCH_TRUCK};let r=new q.Vector2,i=new q.Vector2,a=new q.Vector2,o=e=>{if(!this._enabled||!this._domElement)return;if(this._interactiveArea.left!==0||this._interactiveArea.top!==0||this._interactiveArea.width!==1||this._interactiveArea.height!==1){let t=this._domElement.getBoundingClientRect(),n=e.clientX/t.width,r=e.clientY/t.height;if(n<this._interactiveArea.left||n>this._interactiveArea.right||r<this._interactiveArea.top||r>this._interactiveArea.bottom)return}let t=e.pointerType===`mouse`?(e.buttons&Ol.LEFT)===Ol.LEFT?Ol.LEFT:(e.buttons&Ol.MIDDLE)===Ol.MIDDLE?Ol.MIDDLE:(e.buttons&Ol.RIGHT)===Ol.RIGHT?Ol.RIGHT:null:null;if(t!==null){let e=this._findPointerByMouseButton(t);e&&this._disposePointer(e)}if((e.buttons&Ol.LEFT)===Ol.LEFT&&this._lockedPointer)return;let n={pointerId:e.pointerId,clientX:e.clientX,clientY:e.clientY,deltaX:0,deltaY:0,mouseButton:t};this._activePointers.push(n),this._domElement.ownerDocument.removeEventListener(`pointermove`,s,{passive:!1}),this._domElement.ownerDocument.removeEventListener(`pointerup`,c),this._domElement.ownerDocument.addEventListener(`pointermove`,s,{passive:!1}),this._domElement.ownerDocument.addEventListener(`pointerup`,c),this._isDragging=!0,f(e)},s=e=>{e.cancelable&&e.preventDefault();let t=e.pointerId,n=this._lockedPointer||this._findPointerById(t);if(n){if(n.clientX=e.clientX,n.clientY=e.clientY,n.deltaX=e.movementX,n.deltaY=e.movementY,this._state=0,e.pointerType===`touch`)switch(this._activePointers.length){case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else (!this._isDragging&&this._lockedPointer||this._isDragging&&(e.buttons&Ol.LEFT)===Ol.LEFT)&&(this._state|=this.mouseButtons.left),this._isDragging&&(e.buttons&Ol.MIDDLE)===Ol.MIDDLE&&(this._state|=this.mouseButtons.middle),this._isDragging&&(e.buttons&Ol.RIGHT)===Ol.RIGHT&&(this._state|=this.mouseButtons.right);p()}},c=e=>{let t=this._findPointerById(e.pointerId);if(!(t&&t===this._lockedPointer)){if(t&&this._disposePointer(t),e.pointerType===`touch`)switch(this._activePointers.length){case 0:this._state=K.NONE;break;case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else this._state=K.NONE;m()}},l=-1,u=e=>{if(!this._domElement||!this._enabled||this.mouseButtons.wheel===K.NONE)return;if(this._interactiveArea.left!==0||this._interactiveArea.top!==0||this._interactiveArea.width!==1||this._interactiveArea.height!==1){let t=this._domElement.getBoundingClientRect(),n=e.clientX/t.width,r=e.clientY/t.height;if(n<this._interactiveArea.left||n>this._interactiveArea.right||r<this._interactiveArea.top||r>this._interactiveArea.bottom)return}if(e.preventDefault(),this.dollyToCursor||this.mouseButtons.wheel===K.ROTATE||this.mouseButtons.wheel===K.TRUCK){let e=performance.now();l-e<1e3&&this._getClientRect(this._elementRect),l=e}let t=Yl?-1:-3,n=e.deltaMode===1&&!e.ctrlKey?e.deltaY/t:e.deltaY/(t*10),r=this.dollyToCursor?(e.clientX-this._elementRect.x)/this._elementRect.width*2-1:0,i=this.dollyToCursor?(e.clientY-this._elementRect.y)/this._elementRect.height*-2+1:0;switch(e.ctrlKey?K.ZOOM:this.mouseButtons.wheel){case K.ROTATE:this._rotateInternal(e.deltaX,e.deltaY),this._isUserControllingRotate=!0;break;case K.TRUCK:this._truckInternal(e.deltaX,e.deltaY,!1,!1),this._isUserControllingTruck=!0;break;case K.SCREEN_PAN:this._truckInternal(e.deltaX,e.deltaY,!1,!0),this._isUserControllingTruck=!0;break;case K.OFFSET:this._truckInternal(e.deltaX,e.deltaY,!0,!1),this._isUserControllingOffset=!0;break;case K.DOLLY:this._dollyInternal(-n,r,i),this._isUserControllingDolly=!0;break;case K.ZOOM:this._zoomInternal(-n,r,i),this._isUserControllingZoom=!0;break}this.dispatchEvent({type:`control`})},d=t=>{if(!(!this._domElement||!this._enabled)){if(this.mouseButtons.right===e.ACTION.NONE){let e=t instanceof PointerEvent?t.pointerId:0,n=this._findPointerById(e);n&&this._disposePointer(n),this._domElement.ownerDocument.removeEventListener(`pointermove`,s,{passive:!1}),this._domElement.ownerDocument.removeEventListener(`pointerup`,c);return}t.preventDefault()}},f=e=>{if(this._enabled){if(Wl(this._activePointers,$l),this._getClientRect(this._elementRect),r.copy($l),i.copy($l),this._activePointers.length>=2){let e=$l.x-this._activePointers[1].clientX,t=$l.y-this._activePointers[1].clientY,n=Math.sqrt(e*e+t*t);a.set(0,n);let r=(this._activePointers[0].clientX+this._activePointers[1].clientX)*.5,o=(this._activePointers[0].clientY+this._activePointers[1].clientY)*.5;i.set(r,o)}if(this._state=0,!e)this._lockedPointer&&(this._state|=this.mouseButtons.left);else if(`pointerType`in e&&e.pointerType===`touch`)switch(this._activePointers.length){case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else !this._lockedPointer&&(e.buttons&Ol.LEFT)===Ol.LEFT&&(this._state|=this.mouseButtons.left),(e.buttons&Ol.MIDDLE)===Ol.MIDDLE&&(this._state|=this.mouseButtons.middle),(e.buttons&Ol.RIGHT)===Ol.RIGHT&&(this._state|=this.mouseButtons.right);((this._state&K.ROTATE)===K.ROTATE||(this._state&K.TOUCH_ROTATE)===K.TOUCH_ROTATE||(this._state&K.TOUCH_DOLLY_ROTATE)===K.TOUCH_DOLLY_ROTATE||(this._state&K.TOUCH_ZOOM_ROTATE)===K.TOUCH_ZOOM_ROTATE)&&(this._sphericalEnd.theta=this._spherical.theta,this._sphericalEnd.phi=this._spherical.phi,this._thetaVelocity.value=0,this._phiVelocity.value=0),((this._state&K.TRUCK)===K.TRUCK||(this._state&K.SCREEN_PAN)===K.SCREEN_PAN||(this._state&K.TOUCH_TRUCK)===K.TOUCH_TRUCK||(this._state&K.TOUCH_SCREEN_PAN)===K.TOUCH_SCREEN_PAN||(this._state&K.TOUCH_DOLLY_TRUCK)===K.TOUCH_DOLLY_TRUCK||(this._state&K.TOUCH_DOLLY_SCREEN_PAN)===K.TOUCH_DOLLY_SCREEN_PAN||(this._state&K.TOUCH_ZOOM_TRUCK)===K.TOUCH_ZOOM_TRUCK||(this._state&K.TOUCH_ZOOM_SCREEN_PAN)===K.TOUCH_DOLLY_SCREEN_PAN)&&(this._targetEnd.copy(this._target),this._targetVelocity.set(0,0,0)),((this._state&K.DOLLY)===K.DOLLY||(this._state&K.TOUCH_DOLLY)===K.TOUCH_DOLLY||(this._state&K.TOUCH_DOLLY_TRUCK)===K.TOUCH_DOLLY_TRUCK||(this._state&K.TOUCH_DOLLY_SCREEN_PAN)===K.TOUCH_DOLLY_SCREEN_PAN||(this._state&K.TOUCH_DOLLY_OFFSET)===K.TOUCH_DOLLY_OFFSET||(this._state&K.TOUCH_DOLLY_ROTATE)===K.TOUCH_DOLLY_ROTATE)&&(this._sphericalEnd.radius=this._spherical.radius,this._radiusVelocity.value=0),((this._state&K.ZOOM)===K.ZOOM||(this._state&K.TOUCH_ZOOM)===K.TOUCH_ZOOM||(this._state&K.TOUCH_ZOOM_TRUCK)===K.TOUCH_ZOOM_TRUCK||(this._state&K.TOUCH_ZOOM_SCREEN_PAN)===K.TOUCH_ZOOM_SCREEN_PAN||(this._state&K.TOUCH_ZOOM_OFFSET)===K.TOUCH_ZOOM_OFFSET||(this._state&K.TOUCH_ZOOM_ROTATE)===K.TOUCH_ZOOM_ROTATE)&&(this._zoomEnd=this._zoom,this._zoomVelocity.value=0),((this._state&K.OFFSET)===K.OFFSET||(this._state&K.TOUCH_OFFSET)===K.TOUCH_OFFSET||(this._state&K.TOUCH_DOLLY_OFFSET)===K.TOUCH_DOLLY_OFFSET||(this._state&K.TOUCH_ZOOM_OFFSET)===K.TOUCH_ZOOM_OFFSET)&&(this._focalOffsetEnd.copy(this._focalOffset),this._focalOffsetVelocity.set(0,0,0)),this.dispatchEvent({type:`controlstart`})}},p=()=>{if(!this._enabled||!this._dragNeedsUpdate)return;this._dragNeedsUpdate=!1,Wl(this._activePointers,$l);let e=this._domElement&&this._domElement.ownerDocument.pointerLockElement===this._domElement?this._lockedPointer||this._activePointers[0]:null,t=e?-e.deltaX:i.x-$l.x,n=e?-e.deltaY:i.y-$l.y;if(i.copy($l),((this._state&K.ROTATE)===K.ROTATE||(this._state&K.TOUCH_ROTATE)===K.TOUCH_ROTATE||(this._state&K.TOUCH_DOLLY_ROTATE)===K.TOUCH_DOLLY_ROTATE||(this._state&K.TOUCH_ZOOM_ROTATE)===K.TOUCH_ZOOM_ROTATE)&&(this._rotateInternal(t,n),this._isUserControllingRotate=!0),(this._state&K.DOLLY)===K.DOLLY||(this._state&K.ZOOM)===K.ZOOM){let e=this.dollyToCursor?(r.x-this._elementRect.x)/this._elementRect.width*2-1:0,t=this.dollyToCursor?(r.y-this._elementRect.y)/this._elementRect.height*-2+1:0,i=this.dollyDragInverted?-1:1;(this._state&K.DOLLY)===K.DOLLY?(this._dollyInternal(i*n*Jl,e,t),this._isUserControllingDolly=!0):(this._zoomInternal(i*n*Jl,e,t),this._isUserControllingZoom=!0)}if((this._state&K.TOUCH_DOLLY)===K.TOUCH_DOLLY||(this._state&K.TOUCH_ZOOM)===K.TOUCH_ZOOM||(this._state&K.TOUCH_DOLLY_TRUCK)===K.TOUCH_DOLLY_TRUCK||(this._state&K.TOUCH_ZOOM_TRUCK)===K.TOUCH_ZOOM_TRUCK||(this._state&K.TOUCH_DOLLY_SCREEN_PAN)===K.TOUCH_DOLLY_SCREEN_PAN||(this._state&K.TOUCH_ZOOM_SCREEN_PAN)===K.TOUCH_ZOOM_SCREEN_PAN||(this._state&K.TOUCH_DOLLY_OFFSET)===K.TOUCH_DOLLY_OFFSET||(this._state&K.TOUCH_ZOOM_OFFSET)===K.TOUCH_ZOOM_OFFSET||(this._state&K.TOUCH_DOLLY_ROTATE)===K.TOUCH_DOLLY_ROTATE||(this._state&K.TOUCH_ZOOM_ROTATE)===K.TOUCH_ZOOM_ROTATE){let e=$l.x-this._activePointers[1].clientX,t=$l.y-this._activePointers[1].clientY,n=Math.sqrt(e*e+t*t),r=a.y-n;a.set(0,n);let o=this.dollyToCursor?(i.x-this._elementRect.x)/this._elementRect.width*2-1:0,s=this.dollyToCursor?(i.y-this._elementRect.y)/this._elementRect.height*-2+1:0;(this._state&K.TOUCH_DOLLY)===K.TOUCH_DOLLY||(this._state&K.TOUCH_DOLLY_ROTATE)===K.TOUCH_DOLLY_ROTATE||(this._state&K.TOUCH_DOLLY_TRUCK)===K.TOUCH_DOLLY_TRUCK||(this._state&K.TOUCH_DOLLY_SCREEN_PAN)===K.TOUCH_DOLLY_SCREEN_PAN||(this._state&K.TOUCH_DOLLY_OFFSET)===K.TOUCH_DOLLY_OFFSET?(this._dollyInternal(r*Jl,o,s),this._isUserControllingDolly=!0):(this._zoomInternal(r*Jl,o,s),this._isUserControllingZoom=!0)}((this._state&K.TRUCK)===K.TRUCK||(this._state&K.TOUCH_TRUCK)===K.TOUCH_TRUCK||(this._state&K.TOUCH_DOLLY_TRUCK)===K.TOUCH_DOLLY_TRUCK||(this._state&K.TOUCH_ZOOM_TRUCK)===K.TOUCH_ZOOM_TRUCK)&&(this._truckInternal(t,n,!1,!1),this._isUserControllingTruck=!0),((this._state&K.SCREEN_PAN)===K.SCREEN_PAN||(this._state&K.TOUCH_SCREEN_PAN)===K.TOUCH_SCREEN_PAN||(this._state&K.TOUCH_DOLLY_SCREEN_PAN)===K.TOUCH_DOLLY_SCREEN_PAN||(this._state&K.TOUCH_ZOOM_SCREEN_PAN)===K.TOUCH_ZOOM_SCREEN_PAN)&&(this._truckInternal(t,n,!1,!0),this._isUserControllingTruck=!0),((this._state&K.OFFSET)===K.OFFSET||(this._state&K.TOUCH_OFFSET)===K.TOUCH_OFFSET||(this._state&K.TOUCH_DOLLY_OFFSET)===K.TOUCH_DOLLY_OFFSET||(this._state&K.TOUCH_ZOOM_OFFSET)===K.TOUCH_ZOOM_OFFSET)&&(this._truckInternal(t,n,!0,!1),this._isUserControllingOffset=!0),this.dispatchEvent({type:`control`})},m=()=>{Wl(this._activePointers,$l),i.copy($l),this._dragNeedsUpdate=!1,(this._activePointers.length===0||this._activePointers.length===1&&this._activePointers[0]===this._lockedPointer)&&(this._isDragging=!1),this._activePointers.length===0&&this._domElement&&(this._domElement.ownerDocument.removeEventListener(`pointermove`,s,{passive:!1}),this._domElement.ownerDocument.removeEventListener(`pointerup`,c),this.dispatchEvent({type:`controlend`}))};this.lockPointer=()=>{!this._enabled||!this._domElement||(this.cancel(),this._lockedPointer={pointerId:-1,clientX:0,clientY:0,deltaX:0,deltaY:0,mouseButton:null},this._activePointers.push(this._lockedPointer),this._domElement.ownerDocument.removeEventListener(`pointermove`,s,{passive:!1}),this._domElement.ownerDocument.removeEventListener(`pointerup`,c),this._domElement.requestPointerLock(),this._domElement.ownerDocument.addEventListener(`pointerlockchange`,h),this._domElement.ownerDocument.addEventListener(`pointerlockerror`,g),this._domElement.ownerDocument.addEventListener(`pointermove`,s,{passive:!1}),this._domElement.ownerDocument.addEventListener(`pointerup`,c),f())},this.unlockPointer=()=>{this._lockedPointer!==null&&(this._disposePointer(this._lockedPointer),this._lockedPointer=null),this._domElement?.ownerDocument.exitPointerLock(),this._domElement?.ownerDocument.removeEventListener(`pointerlockchange`,h),this._domElement?.ownerDocument.removeEventListener(`pointerlockerror`,g),this.cancel()};let h=()=>{this._domElement&&this._domElement.ownerDocument.pointerLockElement===this._domElement||this.unlockPointer()},g=()=>{this.unlockPointer()};this._addAllEventListeners=e=>{this._domElement=e,this._domElement.style.touchAction=`none`,this._domElement.style.userSelect=`none`,this._domElement.style.webkitUserSelect=`none`,this._domElement.addEventListener(`pointerdown`,o),this._domElement.addEventListener(`pointercancel`,c),this._domElement.addEventListener(`wheel`,u,{passive:!1}),this._domElement.addEventListener(`contextmenu`,d)},this._removeAllEventListeners=()=>{this._domElement&&(this._domElement.style.touchAction=``,this._domElement.style.userSelect=``,this._domElement.style.webkitUserSelect=``,this._domElement.removeEventListener(`pointerdown`,o),this._domElement.removeEventListener(`pointercancel`,c),this._domElement.removeEventListener(`wheel`,u,{passive:!1}),this._domElement.removeEventListener(`contextmenu`,d),this._domElement.ownerDocument.removeEventListener(`pointermove`,s,{passive:!1}),this._domElement.ownerDocument.removeEventListener(`pointerup`,c),this._domElement.ownerDocument.removeEventListener(`pointerlockchange`,h),this._domElement.ownerDocument.removeEventListener(`pointerlockerror`,g))},this.cancel=()=>{this._state!==K.NONE&&(this._state=K.NONE,this._activePointers.length=0,m())},n&&this.connect(n),this.update(0)}get camera(){return this._camera}set camera(e){this._camera=e,this.updateCameraUp(),this._camera.updateProjectionMatrix(),this._updateNearPlaneCorners(),this._needsUpdate=!0}get enabled(){return this._enabled}set enabled(e){this._enabled=e,this._domElement&&(e?(this._domElement.style.touchAction=`none`,this._domElement.style.userSelect=`none`,this._domElement.style.webkitUserSelect=`none`):(this.cancel(),this._domElement.style.touchAction=``,this._domElement.style.userSelect=``,this._domElement.style.webkitUserSelect=``))}get active(){return!this._hasRested}get currentAction(){return this._state}get distance(){return this._spherical.radius}set distance(e){this._spherical.radius===e&&this._sphericalEnd.radius===e||(this._spherical.radius=e,this._sphericalEnd.radius=e,this._needsUpdate=!0)}get azimuthAngle(){return this._spherical.theta}set azimuthAngle(e){this._spherical.theta===e&&this._sphericalEnd.theta===e||(this._spherical.theta=e,this._sphericalEnd.theta=e,this._needsUpdate=!0)}get polarAngle(){return this._spherical.phi}set polarAngle(e){this._spherical.phi===e&&this._sphericalEnd.phi===e||(this._spherical.phi=e,this._sphericalEnd.phi=e,this._needsUpdate=!0)}get boundaryEnclosesCamera(){return this._boundaryEnclosesCamera}set boundaryEnclosesCamera(e){this._boundaryEnclosesCamera=e,this._needsUpdate=!0}set interactiveArea(e){this._interactiveArea.width=Il(e.width,0,1),this._interactiveArea.height=Il(e.height,0,1),this._interactiveArea.x=Il(e.x,0,1-this._interactiveArea.width),this._interactiveArea.y=Il(e.y,0,1-this._interactiveArea.height)}addEventListener(e,t){super.addEventListener(e,t)}removeEventListener(e,t){super.removeEventListener(e,t)}rotate(e,t,n=!1){return this.rotateTo(this._sphericalEnd.theta+e,this._sphericalEnd.phi+t,n)}rotateAzimuthTo(e,t=!1){return this.rotateTo(e,this._sphericalEnd.phi,t)}rotatePolarTo(e,t=!1){return this.rotateTo(this._sphericalEnd.theta,e,t)}rotateTo(e,t,n=!1){this._isUserControllingRotate=!1;let r=Il(e,this.minAzimuthAngle,this.maxAzimuthAngle),i=Il(t,this.minPolarAngle,this.maxPolarAngle);this._sphericalEnd.theta=r,this._sphericalEnd.phi=i,this._sphericalEnd.makeSafe(),this._needsUpdate=!0,n||(this._spherical.theta=this._sphericalEnd.theta,this._spherical.phi=this._sphericalEnd.phi);let a=!n||Rl(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Rl(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold);return this._createOnRestPromise(a)}dolly(e,t=!1){return this.dollyTo(this._sphericalEnd.radius-e,t)}dollyTo(e,t=!1){return this._isUserControllingDolly=!1,this._lastDollyDirection=kl.NONE,this._changedDolly=0,this._dollyToNoClamp(Il(e,this.minDistance,this.maxDistance),t)}_dollyToNoClamp(e,t=!1){let n=this._sphericalEnd.radius;if(this.colliderMeshes.length>=1){let t=this._collisionTest(),r=Rl(t,this._spherical.radius);if(!(n>e)&&r)return Promise.resolve();this._sphericalEnd.radius=Math.min(e,t)}else this._sphericalEnd.radius=e;this._needsUpdate=!0,t||(this._spherical.radius=this._sphericalEnd.radius);let r=!t||Rl(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(r)}dollyInFixed(e,t=!1){this._targetEnd.add(this._getCameraDirection(nu).multiplyScalar(e)),t||this._target.copy(this._targetEnd);let n=!t||Rl(this._target.x,this._targetEnd.x,this.restThreshold)&&Rl(this._target.y,this._targetEnd.y,this.restThreshold)&&Rl(this._target.z,this._targetEnd.z,this.restThreshold);return this._createOnRestPromise(n)}zoom(e,t=!1){return this.zoomTo(this._zoomEnd+e,t)}zoomTo(e,t=!1){this._isUserControllingZoom=!1,this._zoomEnd=Il(e,this.minZoom,this.maxZoom),this._needsUpdate=!0,t||(this._zoom=this._zoomEnd);let n=!t||Rl(this._zoom,this._zoomEnd,this.restThreshold);return this._changedZoom=0,this._createOnRestPromise(n)}pan(e,t,n=!1){return console.warn("`pan` has been renamed to `truck`"),this.truck(e,t,n)}truck(e,t,n=!1){this._camera.updateMatrix(),ru.setFromMatrixColumn(this._camera.matrix,0),iu.setFromMatrixColumn(this._camera.matrix,1),ru.multiplyScalar(e),iu.multiplyScalar(-t);let r=J.copy(ru).add(iu),i=eu.copy(this._targetEnd).add(r);return this.moveTo(i.x,i.y,i.z,n)}forward(e,t=!1){J.setFromMatrixColumn(this._camera.matrix,0),J.crossVectors(this._camera.up,J),J.multiplyScalar(e);let n=eu.copy(this._targetEnd).add(J);return this.moveTo(n.x,n.y,n.z,t)}elevate(e,t=!1){return J.copy(this._camera.up).multiplyScalar(e),this.moveTo(this._targetEnd.x+J.x,this._targetEnd.y+J.y,this._targetEnd.z+J.z,t)}moveTo(e,t,n,r=!1){this._isUserControllingTruck=!1;let i=J.set(e,t,n).sub(this._targetEnd);this._encloseToBoundary(this._targetEnd,i,this.boundaryFriction),this._needsUpdate=!0,r||this._target.copy(this._targetEnd);let a=!r||Rl(this._target.x,this._targetEnd.x,this.restThreshold)&&Rl(this._target.y,this._targetEnd.y,this.restThreshold)&&Rl(this._target.z,this._targetEnd.z,this.restThreshold);return this._createOnRestPromise(a)}lookInDirectionOf(e,t,n,r=!1){let i=J.set(e,t,n).sub(this._targetEnd).normalize().multiplyScalar(-this._sphericalEnd.radius).add(this._targetEnd);return this.setPosition(i.x,i.y,i.z,r)}fitToBox(e,t,{cover:n=!1,paddingLeft:r=0,paddingRight:i=0,paddingBottom:a=0,paddingTop:o=0}={}){let s=[],c=e.isBox3?uu.copy(e):uu.setFromObject(e);c.isEmpty()&&(console.warn(`camera-controls: fitTo() cannot be used with an empty box. Aborting`),Promise.resolve());let l=zl(this._sphericalEnd.theta,Nl),u=zl(this._sphericalEnd.phi,Nl);s.push(this.rotateTo(l,u,t));let d=J.setFromSpherical(this._sphericalEnd).normalize(),f=pu.setFromUnitVectors(d,Ql),p=Rl(Math.abs(d.y),1);p&&f.multiply(mu.setFromAxisAngle(Zl,l)),f.multiply(this._yAxisUpSpaceInverse);let m=du.makeEmpty();eu.copy(c.min).applyQuaternion(f),m.expandByPoint(eu),eu.copy(c.min).setX(c.max.x).applyQuaternion(f),m.expandByPoint(eu),eu.copy(c.min).setY(c.max.y).applyQuaternion(f),m.expandByPoint(eu),eu.copy(c.max).setZ(c.min.z).applyQuaternion(f),m.expandByPoint(eu),eu.copy(c.min).setZ(c.max.z).applyQuaternion(f),m.expandByPoint(eu),eu.copy(c.max).setY(c.min.y).applyQuaternion(f),m.expandByPoint(eu),eu.copy(c.max).setX(c.min.x).applyQuaternion(f),m.expandByPoint(eu),eu.copy(c.max).applyQuaternion(f),m.expandByPoint(eu),m.min.x-=r,m.min.y-=a,m.max.x+=i,m.max.y+=o,f.setFromUnitVectors(Ql,d),p&&f.premultiply(mu.invert()),f.premultiply(this._yAxisUpSpace);let h=m.getSize(J),g=m.getCenter(eu).applyQuaternion(f);if(Al(this._camera)){let e=this.getDistanceToFitBox(h.x,h.y,h.z,n);s.push(this.moveTo(g.x,g.y,g.z,t)),s.push(this.dollyTo(e,t)),s.push(this.setFocalOffset(0,0,0,t))}else if(jl(this._camera)){let e=this._camera,r=e.right-e.left,i=e.top-e.bottom,a=n?Math.max(r/h.x,i/h.y):Math.min(r/h.x,i/h.y);s.push(this.moveTo(g.x,g.y,g.z,t)),s.push(this.zoomTo(a,t)),s.push(this.setFocalOffset(0,0,0,t))}return Promise.all(s)}fitToSphere(t,n){let r=[],i=`isObject3D`in t?e.createBoundingSphere(t,fu):fu.copy(t);if(r.push(this.moveTo(i.center.x,i.center.y,i.center.z,n)),Al(this._camera)){let e=this.getDistanceToFitSphere(i.radius);r.push(this.dollyTo(e,n))}else if(jl(this._camera)){let e=this._camera.right-this._camera.left,t=this._camera.top-this._camera.bottom,a=2*i.radius,o=Math.min(e/a,t/a);r.push(this.zoomTo(o,n))}return r.push(this.setFocalOffset(0,0,0,n)),Promise.all(r)}setLookAt(e,t,n,r,i,a,o=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._lastDollyDirection=kl.NONE,this._changedDolly=0;let s=eu.set(r,i,a),c=J.set(e,t,n);this._targetEnd.copy(s),this._sphericalEnd.setFromVector3(c.sub(s).applyQuaternion(this._yAxisUpSpace)),this._needsUpdate=!0,o||(this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd));let l=!o||Rl(this._target.x,this._targetEnd.x,this.restThreshold)&&Rl(this._target.y,this._targetEnd.y,this.restThreshold)&&Rl(this._target.z,this._targetEnd.z,this.restThreshold)&&Rl(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Rl(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&Rl(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(l)}lerp(e,t,n,r=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._lastDollyDirection=kl.NONE,this._changedDolly=0;let i=J.set(...e.target);if(`spherical`in e)cu.set(...e.spherical);else{let t=eu.set(...e.position);cu.setFromVector3(t.sub(i).applyQuaternion(this._yAxisUpSpace))}let a=tu.set(...t.target);if(`spherical`in t)lu.set(...t.spherical);else{let e=eu.set(...t.position);lu.setFromVector3(e.sub(a).applyQuaternion(this._yAxisUpSpace))}this._targetEnd.copy(i.lerp(a,n));let o=lu.theta-cu.theta,s=lu.phi-cu.phi,c=lu.radius-cu.radius;this._sphericalEnd.set(cu.radius+c*n,cu.phi+s*n,cu.theta+o*n),this._needsUpdate=!0,r||(this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd));let l=!r||Rl(this._target.x,this._targetEnd.x,this.restThreshold)&&Rl(this._target.y,this._targetEnd.y,this.restThreshold)&&Rl(this._target.z,this._targetEnd.z,this.restThreshold)&&Rl(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&Rl(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&Rl(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(l)}lerpLookAt(e,t,n,r,i,a,o,s,c,l,u,d,f,p=!1){return this.lerp({position:[e,t,n],target:[r,i,a]},{position:[o,s,c],target:[l,u,d]},f,p)}setPosition(e,t,n,r=!1){return this.setLookAt(e,t,n,this._targetEnd.x,this._targetEnd.y,this._targetEnd.z,r)}setTarget(e,t,n,r=!1){let i=this.getPosition(J),a=this.setLookAt(i.x,i.y,i.z,e,t,n,r);return this._sphericalEnd.phi=Il(this._sphericalEnd.phi,this.minPolarAngle,this.maxPolarAngle),a}setFocalOffset(e,t,n,r=!1){this._isUserControllingOffset=!1,this._focalOffsetEnd.set(e,t,n),this._needsUpdate=!0,r||this._focalOffset.copy(this._focalOffsetEnd);let i=!r||Rl(this._focalOffset.x,this._focalOffsetEnd.x,this.restThreshold)&&Rl(this._focalOffset.y,this._focalOffsetEnd.y,this.restThreshold)&&Rl(this._focalOffset.z,this._focalOffsetEnd.z,this.restThreshold);return this._createOnRestPromise(i)}setOrbitPoint(e,t,n){this._camera.updateMatrixWorld(),ru.setFromMatrixColumn(this._camera.matrixWorldInverse,0),iu.setFromMatrixColumn(this._camera.matrixWorldInverse,1),au.setFromMatrixColumn(this._camera.matrixWorldInverse,2);let r=J.set(e,t,n),i=r.distanceTo(this._camera.position),a=r.sub(this._camera.position);ru.multiplyScalar(a.x),iu.multiplyScalar(a.y),au.multiplyScalar(a.z),J.copy(ru).add(iu).add(au),J.z+=i,this.dollyTo(i,!1),this.setFocalOffset(-J.x,J.y,-J.z,!1),this.moveTo(e,t,n,!1)}setBoundary(e){if(!e){this._boundary.min.set(-1/0,-1/0,-1/0),this._boundary.max.set(1/0,1/0,1/0),this._needsUpdate=!0;return}this._boundary.copy(e),this._boundary.clampPoint(this._targetEnd,this._targetEnd),this._needsUpdate=!0}setViewport(e,t,n,r){if(e===null){this._viewport=null;return}this._viewport=this._viewport||new q.Vector4,typeof e==`number`?this._viewport.set(e,t,n,r):this._viewport.copy(e)}getDistanceToFitBox(e,t,n,r=!1){if(Gl(this._camera,`getDistanceToFitBox`))return this._spherical.radius;let i=e/t,a=this._camera.getEffectiveFOV()*Fl,o=this._camera.aspect;return((r?i>o:i<o)?t:e/o)*.5/Math.tan(a*.5)+n*.5}getDistanceToFitSphere(e){if(Gl(this._camera,`getDistanceToFitSphere`))return this._spherical.radius;let t=this._camera.getEffectiveFOV()*Fl,n=Math.atan(Math.tan(t*.5)*this._camera.aspect)*2,r=1<this._camera.aspect?t:n;return e/Math.sin(r*.5)}getTarget(e,t=!0){return(e&&e.isVector3?e:new q.Vector3).copy(t?this._targetEnd:this._target)}getPosition(e,t=!0){return(e&&e.isVector3?e:new q.Vector3).setFromSpherical(t?this._sphericalEnd:this._spherical).applyQuaternion(this._yAxisUpSpaceInverse).add(t?this._targetEnd:this._target)}getSpherical(e,t=!0){return(e||new q.Spherical).copy(t?this._sphericalEnd:this._spherical)}getFocalOffset(e,t=!0){return(e&&e.isVector3?e:new q.Vector3).copy(t?this._focalOffsetEnd:this._focalOffset)}normalizeRotations(){return this._sphericalEnd.theta=(this._sphericalEnd.theta%Ml+Ml)%Ml,this._sphericalEnd.theta>Math.PI&&(this._sphericalEnd.theta-=Ml),this._spherical.theta+=Ml*Math.round((this._sphericalEnd.theta-this._spherical.theta)/Ml),this}stop(){this._focalOffset.copy(this._focalOffsetEnd),this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd),this._zoom=this._zoomEnd}reset(e=!1){if(!Rl(this._camera.up.x,this._cameraUp0.x)||!Rl(this._camera.up.y,this._cameraUp0.y)||!Rl(this._camera.up.z,this._cameraUp0.z)){this._camera.up.copy(this._cameraUp0);let e=this.getPosition(J);this.updateCameraUp(),this.setPosition(e.x,e.y,e.z)}let t=[this.setLookAt(this._position0.x,this._position0.y,this._position0.z,this._target0.x,this._target0.y,this._target0.z,e),this.setFocalOffset(this._focalOffset0.x,this._focalOffset0.y,this._focalOffset0.z,e),this.zoomTo(this._zoom0,e)];return Promise.all(t)}saveState(){this._cameraUp0.copy(this._camera.up),this.getTarget(this._target0),this.getPosition(this._position0),this._zoom0=this._zoom,this._focalOffset0.copy(this._focalOffset)}updateCameraUp(){this._yAxisUpSpace.setFromUnitVectors(this._camera.up,Zl),this._yAxisUpSpaceInverse.copy(this._yAxisUpSpace).invert()}applyCameraUp(){let e=J.subVectors(this._target,this._camera.position).normalize(),t=eu.crossVectors(e,this._camera.up);this._camera.up.crossVectors(t,e).normalize(),this._camera.updateMatrixWorld();let n=this.getPosition(J);this.updateCameraUp(),this.setPosition(n.x,n.y,n.z)}update(e){let t=this._sphericalEnd.theta-this._spherical.theta,n=this._sphericalEnd.phi-this._spherical.phi,r=this._sphericalEnd.radius-this._spherical.radius,i=ou.subVectors(this._targetEnd,this._target),a=su.subVectors(this._focalOffsetEnd,this._focalOffset),o=this._zoomEnd-this._zoom;if(Ll(t))this._thetaVelocity.value=0,this._spherical.theta=this._sphericalEnd.theta;else{let t=this._isUserControllingRotate?this.draggingSmoothTime:this.smoothTime;this._spherical.theta=Hl(this._spherical.theta,this._sphericalEnd.theta,this._thetaVelocity,t,1/0,e),this._needsUpdate=!0}if(Ll(n))this._phiVelocity.value=0,this._spherical.phi=this._sphericalEnd.phi;else{let t=this._isUserControllingRotate?this.draggingSmoothTime:this.smoothTime;this._spherical.phi=Hl(this._spherical.phi,this._sphericalEnd.phi,this._phiVelocity,t,1/0,e),this._needsUpdate=!0}if(Ll(r))this._radiusVelocity.value=0,this._spherical.radius=this._sphericalEnd.radius;else{let t=this._isUserControllingDolly?this.draggingSmoothTime:this.smoothTime;this._spherical.radius=Hl(this._spherical.radius,this._sphericalEnd.radius,this._radiusVelocity,t,this.maxSpeed,e),this._needsUpdate=!0}if(Ll(i.x)&&Ll(i.y)&&Ll(i.z))this._targetVelocity.set(0,0,0),this._target.copy(this._targetEnd);else{let t=this._isUserControllingTruck?this.draggingSmoothTime:this.smoothTime;Ul(this._target,this._targetEnd,this._targetVelocity,t,this.maxSpeed,e,this._target),this._needsUpdate=!0}if(Ll(a.x)&&Ll(a.y)&&Ll(a.z))this._focalOffsetVelocity.set(0,0,0),this._focalOffset.copy(this._focalOffsetEnd);else{let t=this._isUserControllingOffset?this.draggingSmoothTime:this.smoothTime;Ul(this._focalOffset,this._focalOffsetEnd,this._focalOffsetVelocity,t,this.maxSpeed,e,this._focalOffset),this._needsUpdate=!0}if(Ll(o))this._zoomVelocity.value=0,this._zoom=this._zoomEnd;else{let t=this._isUserControllingZoom?this.draggingSmoothTime:this.smoothTime;this._zoom=Hl(this._zoom,this._zoomEnd,this._zoomVelocity,t,1/0,e)}if(this.dollyToCursor){if(Al(this._camera)&&this._changedDolly!==0){let e=this._spherical.radius-this._lastDistance,t=this._camera,n=this._getCameraDirection(nu),r=J.copy(n).cross(t.up).normalize();r.lengthSq()===0&&(r.x=1);let i=eu.crossVectors(r,n),a=this._sphericalEnd.radius*Math.tan(t.getEffectiveFOV()*Fl*.5),o=(this._sphericalEnd.radius-e-this._sphericalEnd.radius)/this._sphericalEnd.radius,s=tu.copy(this._targetEnd).add(r.multiplyScalar(this._dollyControlCoord.x*a*t.aspect)).add(i.multiplyScalar(this._dollyControlCoord.y*a)),c=J.copy(this._targetEnd).lerp(s,o),l=this._lastDollyDirection===kl.IN&&this._spherical.radius<=this.minDistance,u=this._lastDollyDirection===kl.OUT&&this.maxDistance<=this._spherical.radius;if(this.infinityDolly&&(l||u)){this._sphericalEnd.radius-=e,this._spherical.radius-=e;let t=eu.copy(n).multiplyScalar(-e);c.add(t)}this._boundary.clampPoint(c,c);let d=eu.subVectors(c,this._targetEnd);this._targetEnd.copy(c),this._target.add(d),this._changedDolly-=e,Ll(this._changedDolly)&&(this._changedDolly=0)}else if(jl(this._camera)&&this._changedZoom!==0){let e=this._zoom-this._lastZoom,t=this._camera,n=J.set(this._dollyControlCoord.x,this._dollyControlCoord.y,(t.near+t.far)/(t.near-t.far)).unproject(t),r=eu.set(0,0,-1).applyQuaternion(t.quaternion),i=tu.copy(n).add(r.multiplyScalar(-n.dot(t.up))),a=-(this._zoom-e-this._zoom)/this._zoom,o=this._getCameraDirection(nu),s=this._targetEnd.dot(o),c=J.copy(this._targetEnd).lerp(i,a),l=c.dot(o),u=o.multiplyScalar(l-s);c.sub(u),this._boundary.clampPoint(c,c);let d=eu.subVectors(c,this._targetEnd);this._targetEnd.copy(c),this._target.add(d),this._changedZoom-=e,Ll(this._changedZoom)&&(this._changedZoom=0)}}this._camera.zoom!==this._zoom&&(this._camera.zoom=this._zoom,this._camera.updateProjectionMatrix(),this._updateNearPlaneCorners(),this._needsUpdate=!0),this._dragNeedsUpdate=!0;let s=this._collisionTest();this._spherical.radius=Math.min(this._spherical.radius,s),this._spherical.makeSafe(),this._camera.position.setFromSpherical(this._spherical).applyQuaternion(this._yAxisUpSpaceInverse).add(this._target),this._camera.lookAt(this._target),(!Ll(this._focalOffset.x)||!Ll(this._focalOffset.y)||!Ll(this._focalOffset.z))&&(this._camera.matrix.compose(this._camera.position,this._camera.quaternion,this._camera.scale),ru.setFromMatrixColumn(this._camera.matrix,0),iu.setFromMatrixColumn(this._camera.matrix,1),au.setFromMatrixColumn(this._camera.matrix,2),ru.multiplyScalar(this._focalOffset.x),iu.multiplyScalar(-this._focalOffset.y),au.multiplyScalar(this._focalOffset.z),J.copy(ru).add(iu).add(au),this._camera.position.add(J),this._camera.updateMatrixWorld()),this._boundaryEnclosesCamera&&this._encloseToBoundary(this._camera.position.copy(this._target),J.setFromSpherical(this._spherical).applyQuaternion(this._yAxisUpSpaceInverse),1);let c=this._needsUpdate;return c&&!this._updatedLastTime?(this._hasRested=!1,this.dispatchEvent({type:`wake`}),this.dispatchEvent({type:`update`})):c?(this.dispatchEvent({type:`update`}),Ll(t,this.restThreshold)&&Ll(n,this.restThreshold)&&Ll(r,this.restThreshold)&&Ll(i.x,this.restThreshold)&&Ll(i.y,this.restThreshold)&&Ll(i.z,this.restThreshold)&&Ll(a.x,this.restThreshold)&&Ll(a.y,this.restThreshold)&&Ll(a.z,this.restThreshold)&&Ll(o,this.restThreshold)&&!this._hasRested&&(this._hasRested=!0,this.dispatchEvent({type:`rest`}))):!c&&this._updatedLastTime&&this.dispatchEvent({type:`sleep`}),this._lastDistance=this._spherical.radius,this._lastZoom=this._zoom,this._updatedLastTime=c,this._needsUpdate=!1,c}toJSON(){return JSON.stringify({enabled:this._enabled,minDistance:this.minDistance,maxDistance:Bl(this.maxDistance),minZoom:this.minZoom,maxZoom:Bl(this.maxZoom),minPolarAngle:this.minPolarAngle,maxPolarAngle:Bl(this.maxPolarAngle),minAzimuthAngle:Bl(this.minAzimuthAngle),maxAzimuthAngle:Bl(this.maxAzimuthAngle),smoothTime:this.smoothTime,draggingSmoothTime:this.draggingSmoothTime,dollySpeed:this.dollySpeed,truckSpeed:this.truckSpeed,dollyToCursor:this.dollyToCursor,target:this._targetEnd.toArray(),position:J.setFromSpherical(this._sphericalEnd).add(this._targetEnd).toArray(),zoom:this._zoomEnd,focalOffset:this._focalOffsetEnd.toArray(),target0:this._target0.toArray(),position0:this._position0.toArray(),zoom0:this._zoom0,focalOffset0:this._focalOffset0.toArray()})}fromJSON(e,t=!1){let n=JSON.parse(e);this.enabled=n.enabled,this.minDistance=n.minDistance,this.maxDistance=Vl(n.maxDistance),this.minZoom=n.minZoom,this.maxZoom=Vl(n.maxZoom),this.minPolarAngle=n.minPolarAngle,this.maxPolarAngle=Vl(n.maxPolarAngle),this.minAzimuthAngle=Vl(n.minAzimuthAngle),this.maxAzimuthAngle=Vl(n.maxAzimuthAngle),this.smoothTime=n.smoothTime,this.draggingSmoothTime=n.draggingSmoothTime,this.dollySpeed=n.dollySpeed,this.truckSpeed=n.truckSpeed,this.dollyToCursor=n.dollyToCursor,this._target0.fromArray(n.target0),this._position0.fromArray(n.position0),this._zoom0=n.zoom0,this._focalOffset0.fromArray(n.focalOffset0),this.moveTo(n.target[0],n.target[1],n.target[2],t),cu.setFromVector3(J.fromArray(n.position).sub(this._targetEnd).applyQuaternion(this._yAxisUpSpace)),this.rotateTo(cu.theta,cu.phi,t),this.dollyTo(cu.radius,t),this.zoomTo(n.zoom,t),this.setFocalOffset(n.focalOffset[0],n.focalOffset[1],n.focalOffset[2],t),this._needsUpdate=!0}connect(e){if(this._domElement){console.warn(`camera-controls is already connected.`);return}e.setAttribute(`data-camera-controls-version`,ql),this._addAllEventListeners(e),this._getClientRect(this._elementRect)}disconnect(){this.cancel(),this._removeAllEventListeners(),this._domElement&&=(this._domElement.removeAttribute(`data-camera-controls-version`),void 0)}dispose(){this.removeAllEventListeners(),this.disconnect()}_getTargetDirection(e){return e.setFromSpherical(this._spherical).divideScalar(this._spherical.radius).applyQuaternion(this._yAxisUpSpaceInverse)}_getCameraDirection(e){return this._getTargetDirection(e).negate()}_findPointerById(e){return this._activePointers.find(t=>t.pointerId===e)}_findPointerByMouseButton(e){return this._activePointers.find(t=>t.mouseButton===e)}_disposePointer(e){this._activePointers.splice(this._activePointers.indexOf(e),1)}_encloseToBoundary(e,t,n){let r=t.lengthSq();if(r===0)return e;let i=eu.copy(t).add(e),a=this._boundary.clampPoint(i,tu).sub(i),o=a.lengthSq();if(o===0)return e.add(t);if(o===r)return e;if(n===0)return e.add(t).add(a);{let r=1+n*o/t.dot(a);return e.add(eu.copy(t).multiplyScalar(r)).add(a.multiplyScalar(1-n))}}_updateNearPlaneCorners(){if(Al(this._camera)){let e=this._camera,t=e.near,n=e.getEffectiveFOV()*Fl,r=Math.tan(n*.5)*t,i=r*e.aspect;this._nearPlaneCorners[0].set(-i,-r,0),this._nearPlaneCorners[1].set(i,-r,0),this._nearPlaneCorners[2].set(i,r,0),this._nearPlaneCorners[3].set(-i,r,0)}else if(jl(this._camera)){let e=this._camera,t=1/e.zoom,n=e.left*t,r=e.right*t,i=e.top*t,a=e.bottom*t;this._nearPlaneCorners[0].set(n,i,0),this._nearPlaneCorners[1].set(r,i,0),this._nearPlaneCorners[2].set(r,a,0),this._nearPlaneCorners[3].set(n,a,0)}}_truckInternal=(e,t,n,r)=>{let i,a;if(Al(this._camera)){let n=J.copy(this._camera.position).sub(this._target),r=this._camera.getEffectiveFOV()*Fl,o=n.length()*Math.tan(r*.5);i=this.truckSpeed*e*o/this._elementRect.height,a=this.truckSpeed*t*o/this._elementRect.height}else if(jl(this._camera)){let n=this._camera;i=this.truckSpeed*e*(n.right-n.left)/n.zoom/this._elementRect.width,a=this.truckSpeed*t*(n.top-n.bottom)/n.zoom/this._elementRect.height}else return;r?(n?this.setFocalOffset(this._focalOffsetEnd.x+i,this._focalOffsetEnd.y,this._focalOffsetEnd.z,!0):this.truck(i,0,!0),this.forward(-a,!0)):n?this.setFocalOffset(this._focalOffsetEnd.x+i,this._focalOffsetEnd.y+a,this._focalOffsetEnd.z,!0):this.truck(i,a,!0)};_rotateInternal=(e,t)=>{let n=Ml*this.azimuthRotateSpeed*e/this._elementRect.height,r=Ml*this.polarRotateSpeed*t/this._elementRect.height;this.rotate(n,r,!0)};_dollyInternal=(e,t,n)=>{let r=.95**(-e*this.dollySpeed),i=this._sphericalEnd.radius,a=this._sphericalEnd.radius*r,o=Il(a,this.minDistance,this.maxDistance),s=o-a;this.infinityDolly&&this.dollyToCursor?this._dollyToNoClamp(a,!0):(this.infinityDolly&&!this.dollyToCursor&&this.dollyInFixed(s,!0),this._dollyToNoClamp(o,!0)),this.dollyToCursor&&(this._changedDolly+=(this.infinityDolly?a:o)-i,this._dollyControlCoord.set(t,n)),this._lastDollyDirection=Math.sign(-e)};_zoomInternal=(e,t,n)=>{let r=.95**(e*this.dollySpeed),i=this._zoom,a=this._zoom*r;this.zoomTo(a,!0),this.dollyToCursor&&(this._changedZoom+=a-i,this._dollyControlCoord.set(t,n))};_collisionTest(){let e=1/0;if(!(this.colliderMeshes.length>=1)||Gl(this._camera,`_collisionTest`))return e;let t=this._getTargetDirection(nu);hu.lookAt(Xl,t,this._camera.up);for(let n=0;n<4;n++){let r=eu.copy(this._nearPlaneCorners[n]);r.applyMatrix4(hu);let i=tu.addVectors(this._target,r);gu.set(i,t),gu.far=this._spherical.radius+1;let a=gu.intersectObjects(this.colliderMeshes);a.length!==0&&a[0].distance<e&&(e=a[0].distance)}return e}_getClientRect(e){if(!this._domElement)return;let t=this._domElement.getBoundingClientRect();return e.x=t.left,e.y=t.top,this._viewport?(e.x+=this._viewport.x,e.y+=t.height-this._viewport.w-this._viewport.y,e.width=this._viewport.z,e.height=this._viewport.w):(e.width=t.width,e.height=t.height),e}_createOnRestPromise(e){return e?Promise.resolve():(this._hasRested=!1,this.dispatchEvent({type:`transitionstart`}),new Promise(e=>{let t=()=>{this.removeEventListener(`rest`,t),e()};this.addEventListener(`rest`,t)}))}_addAllEventListeners(e){}_removeAllEventListeners(){}get dampingFactor(){return console.warn(`.dampingFactor has been deprecated. use smoothTime (in seconds) instead.`),0}set dampingFactor(e){console.warn(`.dampingFactor has been deprecated. use smoothTime (in seconds) instead.`)}get draggingDampingFactor(){return console.warn(`.draggingDampingFactor has been deprecated. use draggingSmoothTime (in seconds) instead.`),0}set draggingDampingFactor(e){console.warn(`.draggingDampingFactor has been deprecated. use draggingSmoothTime (in seconds) instead.`)}static createBoundingSphere(e,t=new q.Sphere){let n=t,r=n.center;uu.makeEmpty(),e.traverseVisible(e=>{e.isMesh&&uu.expandByObject(e)}),uu.getCenter(r);let i=0;return e.traverseVisible(e=>{if(!e.isMesh)return;let t=e;if(!t.geometry)return;let n=t.geometry.clone();n.applyMatrix4(t.matrixWorld);let a=n.attributes.position;for(let e=0,t=a.count;e<t;e++)J.fromBufferAttribute(a,e),i=Math.max(i,r.distanceToSquared(J))}),n.radius=Math.sqrt(i),n}},vu=Object.defineProperty,yu=(e,t,n)=>t in e?vu(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,bu=(e,t,n)=>yu(e,typeof t==`symbol`?t:t+``,n),xu=(e,t)=>{let[n,r]=t.split(`-`);return Object.assign(e.style,{left:r===`left`?`0`:r===`center`?`50%`:``,right:r===`right`?`0`:``,top:n===`top`?`0`:n===`bottom`?``:`50%`,bottom:n===`bottom`?`0`:``,transform:`${r===`center`?`translateX(-50%)`:``} ${n===`center`?`translateY(-50%)`:``}`}),t},Su=({placement:e,size:t,offset:n,id:r,className:i})=>{let a=document.createElement(`div`),{top:o,left:s,right:c,bottom:l}=n;return Object.assign(a.style,{id:r,position:`absolute`,zIndex:`1000`,height:`${t}px`,width:`${t}px`,margin:`${o}px ${c}px ${l}px ${s}px`,borderRadius:`100%`}),xu(a,e),r&&(a.id=r),i&&(a.className=i),a},Cu=e=>{let t=typeof e==`string`?document.querySelector(e):e;if(!t)throw Error(`Invalid DOM element`);return t};function wu(e,t,n){return Math.max(t,Math.min(n,e))}var Tu=[[`x`,0,3],[`y`,1,4],[`z`,2,5]],Eu=new R;function Du({isSphere:e},t,n){e&&(Eu.set(0,0,1).applyQuaternion(n.quaternion),Tu.forEach(([e,n,r])=>{let i=Eu[e],a=t[n],o=a.userData.opacity;a.material.opacity=wu(i>=0?o:o/2,0,1),a=t[r],o=a.userData.opacity,a.material.opacity=wu(i>=0?o/2:o,0,1)}))}var Ou=(e,t,n=10)=>Math.abs(e.clientX-t.x)<n&&Math.abs(e.clientY-t.y)<n,ku=new uo,Au=new L,ju=(e,t,n,r)=>{Au.set((e.clientX-t.left)/t.width*2-1,-((e.clientY-t.top)/t.height)*2+1),ku.setFromCamera(Au,n);let i=ku.intersectObjects(r,!1),a=i.length?i[0]:null;return!a||!a.object.visible?null:a},Mu=1e-6,Nu=2*Math.PI,Pu=[`x`,`y`,`z`],Fu=[...Pu,`nx`,`ny`,`nz`],Iu=[`x`,`z`,`y`,`nx`,`nz`,`ny`],Lu=[`z`,`x`,`y`,`nz`,`nx`,`ny`],Ru=`Right`,zu=`Top`,Bu=`Front`,Vu=`Left`,Hu=`Bottom`,Uu=`Back`,Wu=[Ru,zu,Bu,Vu,Hu,Uu].map(e=>e.toLocaleLowerCase()),Gu=1.3,Ku=(e,t=!0)=>{let{material:n,userData:r}=e,{color:i,opacity:a}=t?r.hover:r;n.color.set(i),n.opacity=a},qu=e=>JSON.parse(JSON.stringify(e)),Ju=e=>{let t=e.type||`sphere`,n=t===`sphere`,r=e.resolution||n?64:128,i=Kn.DEFAULT_UP,a=i.z===1,o=i.x===1,{container:s}=e;e.container=void 0,e=JSON.parse(JSON.stringify(e)),e.container=s;let c=a?Iu:o?Lu:Fu;Wu.forEach((t,n)=>{e[t]&&(e[c[n]]=e[t])});let l={enabled:!0,color:16777215,opacity:1,scale:.7,labelColor:2236962,line:!1,border:{size:0,color:14540253},hover:{color:n?16777215:9688043,labelColor:2236962,opacity:1,scale:.7,border:{size:0,color:14540253}}},u={line:!1,scale:n?.45:.7,hover:{scale:n?.5:.7}},d={type:t,container:document.body,size:128,placement:`top-right`,resolution:r,lineWidth:4,radius:n?1:.2,smoothness:18,animated:!0,speed:1,background:{enabled:!0,color:n?16777215:14739180,opacity:+!n,hover:{color:n?16777215:14739180,opacity:n?.2:1}},font:{family:`sans-serif`,weight:900},offset:{top:10,left:10,bottom:10,right:10},corners:{enabled:!n,color:n?15915362:16777215,opacity:1,scale:n?.15:.2,radius:1,smoothness:18,hover:{color:n?16777215:9688043,opacity:1,scale:n?.2:.225}},edges:{enabled:!n,color:n?15915362:16777215,opacity:+!!n,radius:n?1:.125,smoothness:18,scale:n?.15:1,hover:{color:n?16777215:9688043,opacity:1,scale:n?.2:1}},x:{...qu(l),...n?{label:`X`,color:16725587,line:!0}:{label:o?zu:Ru}},y:{...qu(l),...n?{label:`Y`,color:9100032,line:!0}:{label:a||o?Bu:zu}},z:{...qu(l),...n?{label:`Z`,color:2920447,line:!0}:{label:a?zu:o?Ru:Bu}},nx:{...qu(u),label:n?``:o?Hu:Vu},ny:{...qu(u),label:n?``:a||o?Uu:Hu},nz:{...qu(u),label:n?``:a?Hu:o?Vu:Uu}};return Yu(e,d),Pu.forEach(t=>Yu(e[`n${t}`],qu(e[t]))),{...e,isSphere:n}};function Yu(e,...t){if(e instanceof HTMLElement||typeof e!=`object`||!e)return e;for(let n of t)for(let t in n)t!==`container`&&t in n&&(e[t]===void 0?e[t]=n[t]:typeof n[t]==`object`&&!Array.isArray(n[t])&&(e[t]=Yu(e[t]||{},n[t])));return e}var Xu=(t,n=2)=>{let r=new B,i=n*2,{isSphere:a,resolution:o,radius:s,font:c,corners:l,edges:u}=t,d=Fu.map(e=>({...t[e],radius:s}));a&&l.enabled&&d.push(l),a&&u.enabled&&d.push(u);let f=document.createElement(`canvas`),p=f.getContext(`2d`);f.width=o*2+i*2,f.height=o*d.length+i*d.length;let[m,h]=S(d,o,c);d.forEach(({radius:e,label:t,color:r,labelColor:a,border:s,hover:{color:c,labelColor:l,border:u}},d)=>{let f=o*d+d*i+n;x(n,f,n,o,e,t,s,r,a),x(o+n*3,f,n,o,e,t,u??s,c??r,l??a)});let g=d.length,_=n/(o*2),v=n/(o*6),y=1/g,b=new ra(f);return b.repeat.set(.5-2*_,y-2*v),b.offset.set(_,1-v),Object.assign(b,{colorSpace:Ie,wrapS:e,wrapT:e,userData:{offsetX:_,offsetY:v,cellHeight:y}}),b;function x(e,t,n,i,a,o,s,c,l){if(a=i/2*a,c!=null&&c!==``&&(u(),p.fillStyle=r.set(c).getStyle(),p.fill()),s&&s.size){let n=s.size*i/2;e+=n,t+=n,i-=s.size*i,a=Math.max(0,a-n),u(),p.strokeStyle=r.set(s.color).getStyle(),p.lineWidth=s.size*i,p.stroke()}o&&C(p,e+i/2,t+(i+n)/2,o,r.set(l).getStyle());function u(){p.beginPath(),p.moveTo(e+a,t),p.lineTo(e+i-a,t),p.arcTo(e+i,t,e+i,t+a,a),p.lineTo(e+i,t+i-a),p.arcTo(e+i,t+i,e+i-a,t+i,a),p.lineTo(e+a,t+i),p.arcTo(e,t+i,e,t+i-a,a),p.lineTo(e,t+a),p.arcTo(e,t,e+a,t,a),p.closePath()}}function S(e,t,n){let r=[...e].sort((e,t)=>(e.label?.length||0)-(t.label?.length||0)).pop().label,{family:i,weight:o}=n,s=a?Math.sqrt((t*.7)**2/2):t,c=s,l=0,u=0;do{p.font=`${o} ${c}px ${i}`;let e=p.measureText(r);l=e.width,u=e.fontBoundingBoxDescent,c--}while(l>s&&c>0);let d=s/u,f=Math.min(s/l,d);return[`${o} ${Math.floor(c*f)}px ${i}`,d]}function C(e,t,n,r,i){e.font=m,e.textAlign=`center`,e.textBaseline=`middle`,e.fillStyle=i,e.fillText(r,t,n+(a?h:0))}},Zu=(e,t)=>e.offset.x=(t?.5:0)+e.userData.offsetX,Qu=(e,t)=>{let{offset:n,userData:{offsetY:r,cellHeight:i}}=e;n.y=1-(t+1)*i+r};function $u(e,t,n=2,r=2){let i=n/2-e,a=r/2-e,o=e/n,s=(n-e)/n,c=e/r,l=(r-e)/r,u=[i,a,0,-i,a,0,-i,-a,0,i,-a,0],d=[s,l,o,l,o,c,s,c],f=[3*(t+1)+3,3*(t+1)+4,t+4,t+5,2*(t+1)+4,2,1,2*(t+1)+3,3,4*(t+1)+3,4,0],p=[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11].map(e=>f[e]),m,h,g,_,v,y,b,x;for(let n=0;n<4;n++){_=n<1||n>2?i:-i,v=n<2?a:-a,y=n<1||n>2?s:o,b=n<2?l:c;for(let r=0;r<=t;r++)m=Math.PI/2*(n+r/t),h=Math.cos(m),g=Math.sin(m),u.push(_+e*h,v+e*g,0),d.push(y+o*h,b+c*g),r<t&&(x=(t+1)*n+r+4,p.push(n,x,x+1))}return new H().setIndex(new V(new Uint32Array(p),1)).setAttribute(`position`,new V(new Float32Array(u),3)).setAttribute(`uv`,new V(new Float32Array(d),2))}var ed=(e,t)=>{let n=new R,{isSphere:r,radius:i,smoothness:a}=e,o=$u(i,a);return Fu.map((i,a)=>{let s=a<3,c=Fu[a],l=a?t.clone():t;Qu(l,a);let{enabled:u,scale:d,opacity:f,hover:p}=e[c],m={map:l,opacity:f,transparent:!0},h=r?new Di(new pi(m)):new U(o,new mr(m)),g=s?c:c[1];return h.position[g]=(s?1:-1)*(r?Gu:1),r||h.lookAt(n.copy(h.position).multiplyScalar(1.7)),h.scale.setScalar(d),h.renderOrder=1,h.visible=u,h.userData={scale:d,opacity:f,hover:p},h})},td=(e,t)=>{let{isSphere:n,corners:r}=e;if(!r.enabled)return[];let{color:i,opacity:a,scale:o,radius:s,smoothness:c,hover:l}=r,u=n?null:$u(s,c),d={transparent:!0,opacity:a},f=[1,1,1,-1,1,1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,1,-1,-1,-1,-1,-1].map(e=>e*.85),p=new R;return Array(f.length/3).fill(0).map((e,r)=>{if(n){let e=t.clone();Qu(e,6),d.map=e}else d.color=i;let s=n?new Di(new pi(d)):new U(u,new mr(d)),c=r*3;return s.position.set(f[c],f[c+1],f[c+2]),n&&s.position.normalize().multiplyScalar(1.7),s.scale.setScalar(o),s.lookAt(p.copy(s.position).multiplyScalar(2)),s.renderOrder=1,s.userData={color:i,opacity:a,scale:o,hover:l},s})},nd=(e,t,n)=>{let{isSphere:r,edges:i}=e;if(!i.enabled)return[];let{color:a,opacity:o,scale:s,hover:c,radius:l,smoothness:u}=i,d=r?null:$u(l,u,1.2,.25),f={transparent:!0,opacity:o},p=[0,1,1,0,-1,1,1,0,1,-1,0,1,0,1,-1,0,-1,-1,1,0,-1,-1,0,-1,1,1,0,1,-1,0,-1,1,0,-1,-1,0].map(e=>e*.925),m=new R,h=new R(0,1,0);return Array(p.length/3).fill(0).map((e,i)=>{if(r){let e=t.clone();Qu(e,n),f.map=e}else f.color=a;let l=r?new Di(new pi(f)):new U(d,new mr(f)),u=i*3;return l.position.set(p[u],p[u+1],p[u+2]),r&&l.position.normalize().multiplyScalar(1.7),l.scale.setScalar(s),l.up.copy(h),l.lookAt(m.copy(l.position).multiplyScalar(2)),!r&&!l.position.y&&(l.rotation.z=Math.PI/2),l.renderOrder=1,l.userData={color:a,opacity:o,scale:s,hover:c},l})};function rd(e,t=!1){let n=e[0].index!==null,r=new Set(Object.keys(e[0].attributes)),i=new Set(Object.keys(e[0].morphAttributes)),a={},o={},s=e[0].morphTargetsRelative,c=new H,l=0;for(let u=0;u<e.length;++u){let d=e[u],f=0;if(n!==(d.index!==null))return console.error(`THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index `+u+`. All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them.`),null;for(let e in d.attributes){if(!r.has(e))return console.error(`THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index `+u+`. All geometries must have compatible attributes; make sure "`+e+`" attribute exists among all geometries, or in none of them.`),null;a[e]===void 0&&(a[e]=[]),a[e].push(d.attributes[e]),f++}if(f!==r.size)return console.error(`THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index `+u+`. Make sure all geometries have the same number of attributes.`),null;if(s!==d.morphTargetsRelative)return console.error(`THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index `+u+`. .morphTargetsRelative must be consistent throughout all geometries.`),null;for(let e in d.morphAttributes){if(!i.has(e))return console.error(`THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index `+u+`. .morphAttributes must be consistent throughout all geometries.`),null;o[e]===void 0&&(o[e]=[]),o[e].push(d.morphAttributes[e])}if(t){let e;if(n)e=d.index.count;else if(d.attributes.position!==void 0)e=d.attributes.position.count;else return console.error(`THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index `+u+`. The geometry must have either an index or a position attribute`),null;c.addGroup(l,e,u),l+=e}}if(n){let t=0,n=[];for(let r=0;r<e.length;++r){let i=e[r].index;for(let e=0;e<i.count;++e)n.push(i.getX(e)+t);t+=e[r].attributes.position.count}c.setIndex(n)}for(let e in a){let t=id(a[e]);if(!t)return console.error(`THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the `+e+` attribute.`),null;c.setAttribute(e,t)}for(let e in o){let t=o[e][0].length;if(t===0)break;c.morphAttributes=c.morphAttributes||{},c.morphAttributes[e]=[];for(let n=0;n<t;++n){let t=[];for(let r=0;r<o[e].length;++r)t.push(o[e][r][n]);let r=id(t);if(!r)return console.error(`THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the `+e+` morphAttribute.`),null;c.morphAttributes[e].push(r)}}return c}function id(e){let t,n,r,i=-1,a=0;for(let o=0;o<e.length;++o){let s=e[o];if(t===void 0&&(t=s.array.constructor),t!==s.array.constructor)return console.error(`THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes.`),null;if(n===void 0&&(n=s.itemSize),n!==s.itemSize)return console.error(`THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes.`),null;if(r===void 0&&(r=s.normalized),r!==s.normalized)return console.error(`THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes.`),null;if(i===-1&&(i=s.gpuType),i!==s.gpuType)return console.error(`THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.gpuType must be consistent across matching attributes.`),null;a+=s.count*n}let o=new t(a),s=new V(o,n,r),c=0;for(let t=0;t<e.length;++t){let r=e[t];if(r.isInterleavedBufferAttribute){let e=c/n;for(let t=0,i=r.count;t<i;t++)for(let i=0;i<n;i++){let n=r.getComponent(t,i);s.setComponent(t+e,i,n)}}else o.set(r.array,c);c+=r.count*n}return i!==void 0&&(s.gpuType=i),s}var ad=(e,t)=>{let{isSphere:n,background:{enabled:r,color:i,opacity:a,hover:o}}=t,s,c=new mr({color:i,side:1,opacity:a,transparent:!0,depthWrite:!1});if(!r)return null;if(n)s=new U(new ha(1.8,64,64),c);else{let t;e.forEach(e=>{let n=e.scale.x;e.scale.setScalar(.9),e.updateMatrix();let r=e.geometry.clone();r.applyMatrix4(e.matrix),t=t?rd([t,r]):r,e.scale.setScalar(n)}),s=new U(t,c)}return s.userData={color:i,opacity:a,hover:o},s},od=new Gt,sd=new R,cd=class extends qa{constructor(){super(),this.isLineSegmentsGeometry=!0,this.type=`LineSegmentsGeometry`,this.setIndex([0,2,1,2,3,1,2,4,3,4,5,3,4,6,5,6,7,5]),this.setAttribute(`position`,new br([-1,2,0,1,2,0,-1,1,0,1,1,0,-1,0,0,1,0,0,-1,-1,0,1,-1,0],3)),this.setAttribute(`uv`,new br([-1,2,1,2,-1,1,1,1,-1,-1,1,-1,-1,-2,1,-2],2))}applyMatrix4(e){let t=this.attributes.instanceStart,n=this.attributes.instanceEnd;return t!==void 0&&(t.applyMatrix4(e),n.applyMatrix4(e),t.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}setPositions(e){let t;e instanceof Float32Array?t=e:Array.isArray(e)&&(t=new Float32Array(e));let n=new co(t,6,1);return this.setAttribute(`instanceStart`,new fi(n,3,0)),this.setAttribute(`instanceEnd`,new fi(n,3,3)),this.instanceCount=this.attributes.instanceStart.count,this.computeBoundingBox(),this.computeBoundingSphere(),this}setColors(e){let t;e instanceof Float32Array?t=e:Array.isArray(e)&&(t=new Float32Array(e));let n=new co(t,6,1);return this.setAttribute(`instanceColorStart`,new fi(n,3,0)),this.setAttribute(`instanceColorEnd`,new fi(n,3,3)),this}fromWireframeGeometry(e){return this.setPositions(e.attributes.position.array),this}fromEdgesGeometry(e){return this.setPositions(e.attributes.position.array),this}fromMesh(e){return this.fromWireframeGeometry(new ga(e.geometry)),this}fromLineSegments(e){let t=e.geometry;return this.setPositions(t.attributes.position.array),this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Gt);let e=this.attributes.instanceStart,t=this.attributes.instanceEnd;e!==void 0&&t!==void 0&&(this.boundingBox.setFromBufferAttribute(e),od.setFromBufferAttribute(t),this.boundingBox.union(od))}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new un),this.boundingBox===null&&this.computeBoundingBox();let e=this.attributes.instanceStart,t=this.attributes.instanceEnd;if(e!==void 0&&t!==void 0){let n=this.boundingSphere.center;this.boundingBox.getCenter(n);let r=0;for(let i=0,a=e.count;i<a;i++)sd.fromBufferAttribute(e,i),r=Math.max(r,n.distanceToSquared(sd)),sd.fromBufferAttribute(t,i),r=Math.max(r,n.distanceToSquared(sd));this.boundingSphere.radius=Math.sqrt(r),isNaN(this.boundingSphere.radius)&&console.error(`THREE.LineSegmentsGeometry.computeBoundingSphere(): Computed radius is NaN. The instanced position data is likely to have NaN values.`,this)}}toJSON(){}applyMatrix(e){return console.warn(`THREE.LineSegmentsGeometry: applyMatrix() has been renamed to applyMatrix4().`),this.applyMatrix4(e)}};G.line={worldUnits:{value:1},linewidth:{value:1},resolution:{value:new L(1,1)},dashOffset:{value:0},dashScale:{value:1},dashSize:{value:1},gapSize:{value:1}},Oo.line={uniforms:Kr.merge([G.common,G.fog,G.line]),vertexShader:`
3833
3833
  #include <common>
3834
3834
  #include <color_pars_vertex>
3835
3835
  #include <fog_pars_vertex>
@@ -4199,7 +4199,7 @@ void main() {
4199
4199
  #include <premultiplied_alpha_fragment>
4200
4200
 
4201
4201
  }
4202
- `};var rd=class extends Xr{constructor(e){super({type:`LineMaterial`,uniforms:qr.clone(So.line.uniforms),vertexShader:So.line.vertexShader,fragmentShader:So.line.fragmentShader,clipping:!0}),this.isLineMaterial=!0,this.setValues(e)}get color(){return this.uniforms.diffuse.value}set color(e){this.uniforms.diffuse.value=e}get worldUnits(){return`WORLD_UNITS`in this.defines}set worldUnits(e){e===!0?this.defines.WORLD_UNITS=``:delete this.defines.WORLD_UNITS}get linewidth(){return this.uniforms.linewidth.value}set linewidth(e){this.uniforms.linewidth&&(this.uniforms.linewidth.value=e)}get dashed(){return`USE_DASH`in this.defines}set dashed(e){e===!0!==this.dashed&&(this.needsUpdate=!0),e===!0?this.defines.USE_DASH=``:delete this.defines.USE_DASH}get dashScale(){return this.uniforms.dashScale.value}set dashScale(e){this.uniforms.dashScale.value=e}get dashSize(){return this.uniforms.dashSize.value}set dashSize(e){this.uniforms.dashSize.value=e}get dashOffset(){return this.uniforms.dashOffset.value}set dashOffset(e){this.uniforms.dashOffset.value=e}get gapSize(){return this.uniforms.gapSize.value}set gapSize(e){this.uniforms.gapSize.value=e}get opacity(){return this.uniforms.opacity.value}set opacity(e){this.uniforms&&(this.uniforms.opacity.value=e)}get resolution(){return this.uniforms.resolution.value}set resolution(e){this.uniforms.resolution.value.copy(e)}get alphaToCoverage(){return`USE_ALPHA_TO_COVERAGE`in this.defines}set alphaToCoverage(e){this.defines&&(e===!0!==this.alphaToCoverage&&(this.needsUpdate=!0),e===!0?this.defines.USE_ALPHA_TO_COVERAGE=``:delete this.defines.USE_ALPHA_TO_COVERAGE)}},id=new Bt,ad=new R,od=new R,sd=new Bt,cd=new Bt,ld=new Bt,ud=new R,dd=new yn,fd=new go,pd=new R,md=new Gt,hd=new un,gd=new Bt,_d,vd;function yd(e,t,n){return gd.set(0,0,-t,1).applyMatrix4(e.projectionMatrix),gd.multiplyScalar(1/gd.w),gd.x=vd/n.width,gd.y=vd/n.height,gd.applyMatrix4(e.projectionMatrixInverse),gd.multiplyScalar(1/gd.w),Math.abs(Math.max(gd.x,gd.y))}function bd(e,t){let n=e.matrixWorld,r=e.geometry,i=r.attributes.instanceStart,a=r.attributes.instanceEnd,o=Math.min(r.instanceCount,i.count);for(let r=0,s=o;r<s;r++){fd.start.fromBufferAttribute(i,r),fd.end.fromBufferAttribute(a,r),fd.applyMatrix4(n);let o=new R,s=new R;_d.distanceSqToSegment(fd.start,fd.end,s,o),s.distanceTo(o)<vd*.5&&t.push({point:s,pointOnLine:o,distance:_d.origin.distanceTo(s),object:e,face:null,faceIndex:r,uv:null,uv1:null})}}function xd(e,t,n){let r=t.projectionMatrix,i=e.material.resolution,a=e.matrixWorld,o=e.geometry,s=o.attributes.instanceStart,c=o.attributes.instanceEnd,l=Math.min(o.instanceCount,s.count),u=-t.near;_d.at(1,ld),ld.w=1,ld.applyMatrix4(t.matrixWorldInverse),ld.applyMatrix4(r),ld.multiplyScalar(1/ld.w),ld.x*=i.x/2,ld.y*=i.y/2,ld.z=0,ud.copy(ld),dd.multiplyMatrices(t.matrixWorldInverse,a);for(let t=0,o=l;t<o;t++){if(sd.fromBufferAttribute(s,t),cd.fromBufferAttribute(c,t),sd.w=1,cd.w=1,sd.applyMatrix4(dd),cd.applyMatrix4(dd),sd.z>u&&cd.z>u)continue;if(sd.z>u){let e=sd.z-cd.z,t=(sd.z-u)/e;sd.lerp(cd,t)}else if(cd.z>u){let e=cd.z-sd.z,t=(cd.z-u)/e;cd.lerp(sd,t)}sd.applyMatrix4(r),cd.applyMatrix4(r),sd.multiplyScalar(1/sd.w),cd.multiplyScalar(1/cd.w),sd.x*=i.x/2,sd.y*=i.y/2,cd.x*=i.x/2,cd.y*=i.y/2,fd.start.copy(sd),fd.start.z=0,fd.end.copy(cd),fd.end.z=0;let o=fd.closestPointToPointParameter(ud,!0);fd.at(o,pd);let l=ht.lerp(sd.z,cd.z,o),d=l>=-1&&l<=1,f=ud.distanceTo(pd)<vd*.5;if(d&&f){fd.start.fromBufferAttribute(s,t),fd.end.fromBufferAttribute(c,t),fd.start.applyMatrix4(a),fd.end.applyMatrix4(a);let r=new R,i=new R;_d.distanceSqToSegment(fd.start,fd.end,i,r),n.push({point:i,pointOnLine:r,distance:_d.origin.distanceTo(i),object:e,face:null,faceIndex:t,uv:null,uv1:null})}}}var Sd=class extends H{constructor(e=new nd,t=new rd({color:Math.random()*16777215})){super(e,t),this.isLineSegments2=!0,this.type=`LineSegments2`}computeLineDistances(){let e=this.geometry,t=e.attributes.instanceStart,n=e.attributes.instanceEnd,r=new Float32Array(2*t.count);for(let e=0,i=0,a=t.count;e<a;e++,i+=2)ad.fromBufferAttribute(t,e),od.fromBufferAttribute(n,e),r[i]=i===0?0:r[i-1],r[i+1]=r[i]+ad.distanceTo(od);let i=new no(r,2,1);return e.setAttribute(`instanceDistanceStart`,new pi(i,1,0)),e.setAttribute(`instanceDistanceEnd`,new pi(i,1,1)),this}raycast(e,t){let n=this.material.worldUnits,r=e.camera;r===null&&!n&&console.error(`LineSegments2: "Raycaster.camera" needs to be set in order to raycast against LineSegments2 while worldUnits is set to false.`);let i=e.params.Line2!==void 0&&e.params.Line2.threshold||0;_d=e.ray;let a=this.matrixWorld,o=this.geometry,s=this.material;vd=s.linewidth+i,o.boundingSphere===null&&o.computeBoundingSphere(),hd.copy(o.boundingSphere).applyMatrix4(a);let c;if(c=n?vd*.5:yd(r,Math.max(r.near,hd.distanceToPoint(_d.origin)),s.resolution),hd.radius+=c,_d.intersectsSphere(hd)===!1)return;o.boundingBox===null&&o.computeBoundingBox(),md.copy(o.boundingBox).applyMatrix4(a);let l;l=n?vd*.5:yd(r,Math.max(r.near,md.distanceToPoint(_d.origin)),s.resolution),md.expandByScalar(l),_d.intersectsBox(md)!==!1&&(n?bd(this,t):xd(this,r,t))}onBeforeRender(e){let t=this.material.uniforms;t&&t.resolution&&(e.getViewport(id),this.material.uniforms.resolution.value.set(id.z,id.w))}},Cd=class extends nd{constructor(){super(),this.isLineGeometry=!0,this.type=`LineGeometry`}setPositions(e){let t=e.length-3,n=new Float32Array(2*t);for(let r=0;r<t;r+=3)n[2*r]=e[r],n[2*r+1]=e[r+1],n[2*r+2]=e[r+2],n[2*r+3]=e[r+3],n[2*r+4]=e[r+4],n[2*r+5]=e[r+5];return super.setPositions(n),this}setColors(e){let t=e.length-3,n=new Float32Array(2*t);for(let r=0;r<t;r+=3)n[2*r]=e[r],n[2*r+1]=e[r+1],n[2*r+2]=e[r+2],n[2*r+3]=e[r+3],n[2*r+4]=e[r+4],n[2*r+5]=e[r+5];return super.setColors(n),this}setFromPoints(e){let t=e.length-1,n=new Float32Array(6*t);for(let r=0;r<t;r++)n[6*r]=e[r].x,n[6*r+1]=e[r].y,n[6*r+2]=e[r].z||0,n[6*r+3]=e[r+1].x,n[6*r+4]=e[r+1].y,n[6*r+5]=e[r+1].z||0;return super.setPositions(n),this}fromLine(e){let t=e.geometry;return this.setPositions(t.attributes.position.array),this}},wd=class extends Sd{constructor(e=new Cd,t=new rd({color:Math.random()*16777215})){super(e,t),this.isLine2=!0,this.type=`Line2`}},Td=e=>{let t=new B,n=[],r=[],{isSphere:i}=e;return ku.forEach((a,o)=>{let{enabled:s,line:c,scale:l,color:u}=e[a];if(!s||!c)return;let d=o<3?1:-1,f=(i?zu-l/2:.975)*d;n.push(a.includes(`x`)?f:0,a.includes(`y`)?f:0,a.includes(`z`)?f:0,0,0,0);let p=t.set(u).toArray();r.push(...p,...p)}),n.length?new wd(new Cd().setPositions(n).setColors(r),new rd({linewidth:e.lineWidth,vertexColors:!0,resolution:new L(window.innerWidth,window.innerHeight)})).computeLineDistances():null},Ed=e=>{let{corners:t,edges:n}=e,r=[],i=Wu(e),a=Ju(e,i);return r.push(...a),t.enabled&&r.push(...Yu(e,i)),n.enabled&&r.push(...Xu(e,i,t.enabled?7:6)),[r,$u(a,e),Td(e)]},Dd=(e,t=!0)=>{let{material:n,userData:r}=e,{opacity:i,color:a,scale:o}=t?r.hover:r;e.scale.setScalar(o),n.opacity=i,n.map?Gu(n.map,t):n.color.set(a)},Od=new yn,kd=new so,Ad=new L,jd=new R,Md=new Bt,Nd=class extends Kn{constructor(e,t,n={}){super(),mu(this,`enabled`,!0),mu(this,`camera`),mu(this,`renderer`),mu(this,`options`),mu(this,`target`,new R),mu(this,`animated`,!0),mu(this,`speed`,1),mu(this,`animating`,!1),mu(this,`_options`),mu(this,`_intersections`),mu(this,`_background`,null),mu(this,`_viewport`,[0,0,0,0]),mu(this,`_originalViewport`,[0,0,0,0]),mu(this,`_originalScissor`,[0,0,0,0]),mu(this,`_scene`),mu(this,`_camera`),mu(this,`_container`),mu(this,`_domElement`),mu(this,`_domRect`),mu(this,`_dragging`,!1),mu(this,`_distance`,0),mu(this,`_clock`,new Ua),mu(this,`_targetQuaternion`,new gt),mu(this,`_quaternionStart`,new gt),mu(this,`_quaternionEnd`,new gt),mu(this,`_pointerStart`,new L),mu(this,`_focus`,null),mu(this,`_placement`),mu(this,`_controls`),mu(this,`_controlsListeners`),this.camera=e,this.renderer=t,this._scene=new ui().add(this),this.set(n)}get placement(){return this._placement}set placement(e){this._placement=hu(this._domElement,e),this.domUpdate()}set(e={}){this.dispose(),this.options=e,this._options=Hu(e),this._camera=this._options.isSphere?new La(-1.8,1.8,1.8,-1.8,5,10):new ti(26,1,5,10),this._camera.position.set(0,0,7);let[t,n,r]=Ed(this._options);n&&this.add(n),r&&this.add(r),this.add(...t),this._background=n,this._intersections=t;let{container:i,animated:a,speed:o}=this._options;return this.animated=a,this.speed=o,this._container=i?_u(i):document.body,this._domElement=gu(this._options),this._domElement.onpointerdown=e=>this._onPointerDown(e),this._domElement.onpointermove=e=>this._onPointerMove(e),this._domElement.onpointerleave=()=>this._onPointerLeave(),this._container.appendChild(this._domElement),this._controls&&this.attachControls(this._controls),this.update(),this._updateOrientation(!0),this}render(){this.animating&&this._animate();let{renderer:e,_viewport:t}=this,n=e.getScissorTest(),r=e.autoClear;return e.autoClear=!1,e.setViewport(...t),n&&e.setScissor(...t),e.clear(!1,!0,!1),e.render(this._scene,this._camera),e.setViewport(...this._originalViewport),n&&e.setScissor(...this._originalScissor),e.autoClear=r,this}domUpdate(){this._domRect=this._domElement.getBoundingClientRect();let e=this.renderer,t=this._domRect,n=e.domElement.getBoundingClientRect();return this._viewport.splice(0,4,t.left-n.left,e.domElement.clientHeight-(t.top-n.top+t.height),t.width,t.height),e.getViewport(Md).toArray(this._originalViewport),e.getScissorTest()&&e.getScissor(Md).toArray(this._originalScissor),this}cameraUpdate(){return this._updateOrientation(),this}update(e=!0){return e&&this._controls&&this._controls.update(),this.domUpdate().cameraUpdate()}attachControls(e){return this.detachControls(),this.target=e.target,this._controlsListeners={start:()=>e.enabled=!1,end:()=>e.enabled=!0,change:()=>this.update(!1)},this.addEventListener(`start`,this._controlsListeners.start),this.addEventListener(`end`,this._controlsListeners.end),e.addEventListener(`change`,this._controlsListeners.change),this._controls=e,this}detachControls(){if(!(!this._controlsListeners||!this._controls))return this.target=new R().copy(this._controls.target),this.removeEventListener(`start`,this._controlsListeners.start),this.removeEventListener(`end`,this._controlsListeners.end),this._controls.removeEventListener(`change`,this._controlsListeners.change),this._controlsListeners=void 0,this._controls=void 0,this}dispose(){var e;this.detachControls(),this.children.forEach(e=>{var t,n,r;this.remove(e);let i=e;(t=i.material)==null||t.dispose(),(n=i.material?.map)==null||n.dispose(),(r=i.geometry)==null||r.dispose()}),(e=this._domElement)==null||e.remove()}_updateOrientation(e=!0){e&&(this.quaternion.copy(this.camera.quaternion).invert(),this.updateMatrixWorld()),xu(this._options,this._intersections,this.camera)}_animate(){let{position:e,quaternion:t}=this.camera;if(e.set(0,0,1),!this.animated){e.applyQuaternion(this._quaternionEnd).multiplyScalar(this._distance).add(this.target),t.copy(this._targetQuaternion),this._updateOrientation(),this.animating=!1,this.dispatchEvent({type:`change`}),this.dispatchEvent({type:`end`});return}this._controls&&(this._controls.enabled=!1);let n=this._clock.getDelta()*Du*this.speed;this._quaternionStart.rotateTowards(this._quaternionEnd,n),e.applyQuaternion(this._quaternionStart).multiplyScalar(this._distance).add(this.target),t.rotateTowards(this._targetQuaternion,n),this._updateOrientation(),requestAnimationFrame(()=>this.dispatchEvent({type:`change`})),this._quaternionStart.angleTo(this._quaternionEnd)<Eu&&(this._controls&&(this._controls.enabled=!0),this.animating=!1,this.dispatchEvent({type:`end`}))}_setOrientation(e){let t=this.camera,n=this.target;jd.copy(e).multiplyScalar(this._distance),Od.setPosition(jd).lookAt(jd,this.position,this.up),this._targetQuaternion.setFromRotationMatrix(Od),jd.add(n),Od.lookAt(jd,n,this.up),this._quaternionEnd.setFromRotationMatrix(Od),Od.setPosition(t.position).lookAt(t.position,n,this.up),this._quaternionStart.setFromRotationMatrix(Od),this.animating=!0,this._clock.start(),this.dispatchEvent({type:`start`})}_onPointerDown(e){if(!this.enabled)return;let t=e=>{if(!this._dragging){if(Su(e,this._pointerStart))return;this._dragging=!0}let t=Ad.set(e.clientX,e.clientY).sub(this._pointerStart).multiplyScalar(1/this._domRect.width*Math.PI),n=this.coordinateConversion(jd.subVectors(this.camera.position,this.target)),r=kd.setFromVector3(n);r.theta=a-t.x,r.phi=vu(o-t.y,Eu,Math.PI-Eu),this.coordinateConversion(this.camera.position.setFromSpherical(r),!0).add(this.target),this.camera.lookAt(this.target),this.quaternion.copy(this.camera.quaternion).invert(),this._updateOrientation(!1),this.dispatchEvent({type:`change`})},n=()=>{if(document.removeEventListener(`pointermove`,t,!1),document.removeEventListener(`pointerup`,n,!1),!this._dragging)return this._handleClick(e);this._focus&&=(Dd(this._focus,!1),null),this._dragging=!1,this.dispatchEvent({type:`end`})};if(this.animating)return;e.preventDefault(),this._pointerStart.set(e.clientX,e.clientY);let r=this.coordinateConversion(jd.subVectors(this.camera.position,this.target)),i=kd.setFromVector3(r),a=i.theta,o=i.phi;this._distance=i.radius,document.addEventListener(`pointermove`,t,!1),document.addEventListener(`pointerup`,n,!1),this.dispatchEvent({type:`start`})}coordinateConversion(e,t=!1){let{x:n,y:r,z:i}=e,a=Kn.DEFAULT_UP;return a.x===1?t?e.set(r,i,n):e.set(i,n,r):a.z===1?t?e.set(i,n,r):e.set(r,i,n):e}_onPointerMove(e){!this.enabled||this._dragging||(this._background&&Bu(this._background,!0),this._handleHover(e))}_onPointerLeave(){!this.enabled||this._dragging||(this._background&&Bu(this._background,!1),this._focus&&Dd(this._focus,!1),this._domElement.style.cursor=``)}_handleClick(e){let t=Tu(e,this._domRect,this._camera,this._intersections);this._focus&&=(Dd(this._focus,!1),null),t&&(this._setOrientation(t.object.position),this.dispatchEvent({type:`change`}))}_handleHover(e){let t=Tu(e,this._domRect,this._camera,this._intersections)?.object||null;this._focus!==t&&(this._domElement.style.cursor=t?`pointer`:``,this._focus&&Dd(this._focus,!1),(this._focus=t)?Dd(t,!0):xu(this._options,this._intersections,this.camera))}},Pd=class extends Ue{target=new R;constructor(e){super(),this.cc=e,e.addEventListener(`update`,()=>{e.getTarget(this.target),this.dispatchEvent({type:`change`})})}get enabled(){return this.cc.enabled}set enabled(e){this.cc.enabled=e}update(){let e=this.cc.camera.position,t=this.target;this.cc.setLookAt(e.x,e.y,e.z,t.x,t.y,t.z,!1)}},Fd=new Set;function Id(e,t){return getComputedStyle(document.documentElement).getPropertyValue(e).trim()||t}function Ld(){Rd.faceColor.set(Id(`--scene-face-color`,`#969696`)),Rd.edgeColor.set(Id(`--scene-edge-color`,`#000000`)),Rd.gridColor.set(Id(`--scene-grid-color`,`#6f6f6f`)),Rd.metaEdgeColor.set(Id(`--scene-meta-edge-color`,`#b0b0b0`)),Rd.highlightColor.set(Id(`--scene-highlight-color`,`#ffb433`)),Rd.selectEdgeColor.set(Id(`--scene-select-edge-color`,`#11a4ed`)),Rd.selectFaceColor.set(Id(`--scene-select-face-color`,`#5c9fcc`)),Rd.constraintColor.set(Id(`--scene-constraint-color`,`#cccccc`)),Rd.backgroundColor.set(Id(`--color-base-100`,`#1e1e1e`))}var Rd={faceColor:new B(`#969696`),edgeColor:new B(`#000000`),gridColor:new B(`#6f6f6f`),metaEdgeColor:new B(`#b0b0b0`),highlightColor:new B(`#ffb433`),selectEdgeColor:new B(`#11a4ed`),selectFaceColor:new B(`#5c9fcc`),constraintColor:new B(`#cccccc`),backgroundColor:new B(`#1e1e1e`)};Ld(),new MutationObserver(()=>{Ld();for(let e of Fd)e()}).observe(document.documentElement,{attributes:!0,attributeFilter:[`data-theme`]});function zd(e){return Fd.add(e),()=>Fd.delete(e)}var Bd=class e{static resolution=new L(window.innerWidth,window.innerHeight);static materials=new Set;static register(t){t.resolution.copy(e.resolution),e.materials.add(t),t.addEventListener(`dispose`,()=>{e.materials.delete(t)})}static setResolution(t,n){e.resolution.set(t,n);for(let t of e.materials)t.resolution.copy(e.resolution)}};du.install({THREE:{Vector2:L,Vector3:R,Vector4:Bt,Quaternion:gt,Matrix4:yn,Spherical:so,Box3:Gt,Sphere:un,Raycaster:io,MathUtils:{DEG2RAD:ht.DEG2RAD,clamp:ht.clamp}}});var Vd=new R(0,0,1),Hd=120,Ud=1.1,Wd=class{scene;renderer;gizmo;orthoCamera;perspCamera;activeCamera=`orthographic`;_cc;_adapter;dirLight;renderRequested=!1;resizeObserver;clock=new Ua;animFrameId=0;gizmoWasActive=!1;constructor(e){this.container=e,Kn.DEFAULT_UP=Vd.clone();let t=e.clientWidth||window.innerWidth,n=e.clientHeight||window.innerHeight;this.renderer=new xl({antialias:!0,alpha:!0}),this.renderer.setSize(t,n),this.renderer.setPixelRatio(window.devicePixelRatio),Bd.setResolution(t,n),this.renderer.toneMapping=4,this.renderer.outputColorSpace=Ie,this.renderer.localClippingEnabled=!0,e.appendChild(this.renderer.domElement),this.scene=new ui,this.scene.background=Rd.backgroundColor.clone();let r=t/n;this.orthoCamera=new La(-r*Hd/2,r*Hd/2,Hd/2,-Hd/2,-1e4,1e4),this.orthoCamera.position.set(50,-50,40),this.orthoCamera.up.copy(Vd),this.orthoCamera.lookAt(0,0,0),this.perspCamera=new ti(50,r,.5,1e4),this.perspCamera.position.set(50,-50,40),this.perspCamera.up.copy(Vd),this.perspCamera.lookAt(0,0,0),this.dirLight=new za(16777215,1),this.scene.add(this.dirLight),this.scene.add(new Ba(14544639,2.5)),this._cc=new du(this.orthoCamera,this.renderer.domElement),this._cc.dollyToCursor=!0,this._cc.smoothTime=.1,this._cc.draggingSmoothTime=.05,this.configureTouchForMode(`orthographic`),this._cc.updateCameraUp(),this._adapter=new Pd(this._cc),this.gizmo=new Nd(this.camera,this.renderer,{size:80,type:`sphere`}),this._cc.setLookAt(50,-50,40,0,0,0,!1),this._cc.getTarget(this._adapter.target),this.gizmo.target=this._adapter.target,this.gizmo.attachControls(this._adapter),this.gizmo.addEventListener(`change`,()=>this.requestRender()),this.resizeObserver=new ResizeObserver(()=>this.handleResize()),this.resizeObserver.observe(e),zd(()=>{this.scene.background=Rd.backgroundColor.clone(),this.requestRender()}),this.tick()}get camera(){return this.activeCamera===`orthographic`?this.orthoCamera:this.perspCamera}createPickingRaycaster(e,t){let n=this.camera;n.updateMatrixWorld(),n.updateProjectionMatrix();let r=new io;if(r.setFromCamera(new L(e,t),n),n.isOrthographicCamera){let e=n,t=Math.max(Math.abs(e.far-e.near),1);r.ray.origin.addScaledVector(r.ray.direction,-t)}return r}get cameraControls(){return this._cc}get controls(){return this._adapter}requestRender(){this.renderRequested=!0}fitToBox(e,t){let n=e.getCenter(new R),r=e.getSize(new R).length()/2;if(r===0)return;let i=new un(n,r*Ud);this._cc.fitToSphere(i,t)}switchCamera(e){if(e===this.activeCamera)return;let t=new R,n=new R;this._cc.getPosition(t),this._cc.getTarget(n);let r=this.camera.up.clone();if(this.activeCamera===`orthographic`&&e===`perspective`){let e=(this.orthoCamera.top-this.orthoCamera.bottom)/this.orthoCamera.zoom,r=ht.DEG2RAD*this.perspCamera.fov*.5,i=e*.5/Math.tan(r),a=t.clone().sub(n).normalize();t.copy(n).add(a.multiplyScalar(i))}this.activeCamera=e;let i=this.camera;i.position.copy(t),i.up.copy(r),i.lookAt(n),this._cc.dispose(),this._cc=new du(i,this.renderer.domElement),this._cc.dollyToCursor=!0,this._cc.smoothTime=.1,this._cc.draggingSmoothTime=.05,this._cc.setLookAt(t.x,t.y,t.z,n.x,n.y,n.z,!1),this._cc.updateCameraUp(),this.configureTouchForMode(e),this._adapter=new Pd(this._cc),this._cc.getTarget(this._adapter.target),this.gizmo.camera=i,this.gizmo.target=this._adapter.target,this.gizmo.attachControls(this._adapter),this.gizmo.update(),this.requestRender()}render(){this.updateLightPositions(),this.renderer.render(this.scene,this.camera),this.gizmo.render()}dispose(){cancelAnimationFrame(this.animFrameId),this.resizeObserver.disconnect(),this._cc.dispose(),this.scene.clear(),this.renderer.dispose()}tick=()=>{let e=this.clock.getDelta(),t=!1;if(this._cc.enabled){if(this.gizmoWasActive){this._cc.updateCameraUp();let e=this.camera.position,t=this._adapter.target;this._cc.setLookAt(e.x,e.y,e.z,t.x,t.y,t.z,!1),this.gizmoWasActive=!1}t=this._cc.update(e)}else this.gizmoWasActive=!0;(t||this.renderRequested||!this._cc.enabled)&&(this.render(),this.renderRequested=!1),this.animFrameId=requestAnimationFrame(this.tick)};configureTouchForMode(e){e===`orthographic`?(this._cc.touches.one=du.ACTION.TOUCH_ROTATE,this._cc.touches.two=du.ACTION.TOUCH_ZOOM_TRUCK):(this._cc.touches.one=du.ACTION.TOUCH_ROTATE,this._cc.touches.two=du.ACTION.TOUCH_DOLLY_TRUCK)}handleResize(){let e=this.container.clientWidth,t=this.container.clientHeight||window.innerHeight;if(e===0||t===0)return;let n=e/t;this.renderer.setSize(e,t),this.renderer.setPixelRatio(window.devicePixelRatio),Bd.setResolution(e,t),this.orthoCamera.left=-n*Hd/2,this.orthoCamera.right=n*Hd/2,this.orthoCamera.top=Hd/2,this.orthoCamera.bottom=-Hd/2,this.orthoCamera.updateProjectionMatrix(),this.perspCamera.aspect=n,this.perspCamera.updateProjectionMatrix(),this.gizmo.update(),this.requestRender()}updateLightPositions(){let e=new R;this.camera.getWorldDirection(e),this.dirLight.position.copy(e.multiplyScalar(-10)),this.dirLight.target.position.set(0,0,0),this.dirLight.target.updateMatrixWorld()}},Gd=class extends H{constructor(e=10,t=100,n=new B(`white`),r=8e3,i=new R(0,1,0)){let a=new ca(2,2,1,1),o=new Xr({side:0,polygonOffset:!0,polygonOffsetFactor:2,polygonOffsetUnits:2,uniforms:{uSize1:{value:e},uSize2:{value:t},uColor:{value:n},uDistance:{value:r},uNormal:{value:i.normalize()}},transparent:!0,vertexShader:`
4202
+ `};var ld=class extends Yr{constructor(e){super({type:`LineMaterial`,uniforms:Kr.clone(Oo.line.uniforms),vertexShader:Oo.line.vertexShader,fragmentShader:Oo.line.fragmentShader,clipping:!0}),this.isLineMaterial=!0,this.setValues(e)}get color(){return this.uniforms.diffuse.value}set color(e){this.uniforms.diffuse.value=e}get worldUnits(){return`WORLD_UNITS`in this.defines}set worldUnits(e){e===!0?this.defines.WORLD_UNITS=``:delete this.defines.WORLD_UNITS}get linewidth(){return this.uniforms.linewidth.value}set linewidth(e){this.uniforms.linewidth&&(this.uniforms.linewidth.value=e)}get dashed(){return`USE_DASH`in this.defines}set dashed(e){e===!0!==this.dashed&&(this.needsUpdate=!0),e===!0?this.defines.USE_DASH=``:delete this.defines.USE_DASH}get dashScale(){return this.uniforms.dashScale.value}set dashScale(e){this.uniforms.dashScale.value=e}get dashSize(){return this.uniforms.dashSize.value}set dashSize(e){this.uniforms.dashSize.value=e}get dashOffset(){return this.uniforms.dashOffset.value}set dashOffset(e){this.uniforms.dashOffset.value=e}get gapSize(){return this.uniforms.gapSize.value}set gapSize(e){this.uniforms.gapSize.value=e}get opacity(){return this.uniforms.opacity.value}set opacity(e){this.uniforms&&(this.uniforms.opacity.value=e)}get resolution(){return this.uniforms.resolution.value}set resolution(e){this.uniforms.resolution.value.copy(e)}get alphaToCoverage(){return`USE_ALPHA_TO_COVERAGE`in this.defines}set alphaToCoverage(e){this.defines&&(e===!0!==this.alphaToCoverage&&(this.needsUpdate=!0),e===!0?this.defines.USE_ALPHA_TO_COVERAGE=``:delete this.defines.USE_ALPHA_TO_COVERAGE)}},ud=new Bt,dd=new R,fd=new R,pd=new Bt,md=new Bt,hd=new Bt,gd=new R,_d=new yn,vd=new So,yd=new R,bd=new Gt,xd=new un,Sd=new Bt,Cd,wd;function Td(e,t,n){return Sd.set(0,0,-t,1).applyMatrix4(e.projectionMatrix),Sd.multiplyScalar(1/Sd.w),Sd.x=wd/n.width,Sd.y=wd/n.height,Sd.applyMatrix4(e.projectionMatrixInverse),Sd.multiplyScalar(1/Sd.w),Math.abs(Math.max(Sd.x,Sd.y))}function Ed(e,t){let n=e.matrixWorld,r=e.geometry,i=r.attributes.instanceStart,a=r.attributes.instanceEnd,o=Math.min(r.instanceCount,i.count);for(let r=0,s=o;r<s;r++){vd.start.fromBufferAttribute(i,r),vd.end.fromBufferAttribute(a,r),vd.applyMatrix4(n);let o=new R,s=new R;Cd.distanceSqToSegment(vd.start,vd.end,s,o),s.distanceTo(o)<wd*.5&&t.push({point:s,pointOnLine:o,distance:Cd.origin.distanceTo(s),object:e,face:null,faceIndex:r,uv:null,uv1:null})}}function Dd(e,t,n){let r=t.projectionMatrix,i=e.material.resolution,a=e.matrixWorld,o=e.geometry,s=o.attributes.instanceStart,c=o.attributes.instanceEnd,l=Math.min(o.instanceCount,s.count),u=-t.near;Cd.at(1,hd),hd.w=1,hd.applyMatrix4(t.matrixWorldInverse),hd.applyMatrix4(r),hd.multiplyScalar(1/hd.w),hd.x*=i.x/2,hd.y*=i.y/2,hd.z=0,gd.copy(hd),_d.multiplyMatrices(t.matrixWorldInverse,a);for(let t=0,o=l;t<o;t++){if(pd.fromBufferAttribute(s,t),md.fromBufferAttribute(c,t),pd.w=1,md.w=1,pd.applyMatrix4(_d),md.applyMatrix4(_d),pd.z>u&&md.z>u)continue;if(pd.z>u){let e=pd.z-md.z,t=(pd.z-u)/e;pd.lerp(md,t)}else if(md.z>u){let e=md.z-pd.z,t=(md.z-u)/e;md.lerp(pd,t)}pd.applyMatrix4(r),md.applyMatrix4(r),pd.multiplyScalar(1/pd.w),md.multiplyScalar(1/md.w),pd.x*=i.x/2,pd.y*=i.y/2,md.x*=i.x/2,md.y*=i.y/2,vd.start.copy(pd),vd.start.z=0,vd.end.copy(md),vd.end.z=0;let o=vd.closestPointToPointParameter(gd,!0);vd.at(o,yd);let l=ht.lerp(pd.z,md.z,o),d=l>=-1&&l<=1,f=gd.distanceTo(yd)<wd*.5;if(d&&f){vd.start.fromBufferAttribute(s,t),vd.end.fromBufferAttribute(c,t),vd.start.applyMatrix4(a),vd.end.applyMatrix4(a);let r=new R,i=new R;Cd.distanceSqToSegment(vd.start,vd.end,i,r),n.push({point:i,pointOnLine:r,distance:Cd.origin.distanceTo(i),object:e,face:null,faceIndex:t,uv:null,uv1:null})}}}var Od=class extends U{constructor(e=new cd,t=new ld({color:Math.random()*16777215})){super(e,t),this.isLineSegments2=!0,this.type=`LineSegments2`}computeLineDistances(){let e=this.geometry,t=e.attributes.instanceStart,n=e.attributes.instanceEnd,r=new Float32Array(2*t.count);for(let e=0,i=0,a=t.count;e<a;e++,i+=2)dd.fromBufferAttribute(t,e),fd.fromBufferAttribute(n,e),r[i]=i===0?0:r[i-1],r[i+1]=r[i]+dd.distanceTo(fd);let i=new co(r,2,1);return e.setAttribute(`instanceDistanceStart`,new fi(i,1,0)),e.setAttribute(`instanceDistanceEnd`,new fi(i,1,1)),this}raycast(e,t){let n=this.material.worldUnits,r=e.camera;r===null&&!n&&console.error(`LineSegments2: "Raycaster.camera" needs to be set in order to raycast against LineSegments2 while worldUnits is set to false.`);let i=e.params.Line2!==void 0&&e.params.Line2.threshold||0;Cd=e.ray;let a=this.matrixWorld,o=this.geometry,s=this.material;wd=s.linewidth+i,o.boundingSphere===null&&o.computeBoundingSphere(),xd.copy(o.boundingSphere).applyMatrix4(a);let c;if(c=n?wd*.5:Td(r,Math.max(r.near,xd.distanceToPoint(Cd.origin)),s.resolution),xd.radius+=c,Cd.intersectsSphere(xd)===!1)return;o.boundingBox===null&&o.computeBoundingBox(),bd.copy(o.boundingBox).applyMatrix4(a);let l;l=n?wd*.5:Td(r,Math.max(r.near,bd.distanceToPoint(Cd.origin)),s.resolution),bd.expandByScalar(l),Cd.intersectsBox(bd)!==!1&&(n?Ed(this,t):Dd(this,r,t))}onBeforeRender(e){let t=this.material.uniforms;t&&t.resolution&&(e.getViewport(ud),this.material.uniforms.resolution.value.set(ud.z,ud.w))}},kd=class extends cd{constructor(){super(),this.isLineGeometry=!0,this.type=`LineGeometry`}setPositions(e){let t=e.length-3,n=new Float32Array(2*t);for(let r=0;r<t;r+=3)n[2*r]=e[r],n[2*r+1]=e[r+1],n[2*r+2]=e[r+2],n[2*r+3]=e[r+3],n[2*r+4]=e[r+4],n[2*r+5]=e[r+5];return super.setPositions(n),this}setColors(e){let t=e.length-3,n=new Float32Array(2*t);for(let r=0;r<t;r+=3)n[2*r]=e[r],n[2*r+1]=e[r+1],n[2*r+2]=e[r+2],n[2*r+3]=e[r+3],n[2*r+4]=e[r+4],n[2*r+5]=e[r+5];return super.setColors(n),this}setFromPoints(e){let t=e.length-1,n=new Float32Array(6*t);for(let r=0;r<t;r++)n[6*r]=e[r].x,n[6*r+1]=e[r].y,n[6*r+2]=e[r].z||0,n[6*r+3]=e[r+1].x,n[6*r+4]=e[r+1].y,n[6*r+5]=e[r+1].z||0;return super.setPositions(n),this}fromLine(e){let t=e.geometry;return this.setPositions(t.attributes.position.array),this}},Ad=class extends Od{constructor(e=new kd,t=new ld({color:Math.random()*16777215})){super(e,t),this.isLine2=!0,this.type=`Line2`}},jd=e=>{let t=new B,n=[],r=[],{isSphere:i}=e;return Fu.forEach((a,o)=>{let{enabled:s,line:c,scale:l,color:u}=e[a];if(!s||!c)return;let d=o<3?1:-1,f=(i?Gu-l/2:.975)*d;n.push(a.includes(`x`)?f:0,a.includes(`y`)?f:0,a.includes(`z`)?f:0,0,0,0);let p=t.set(u).toArray();r.push(...p,...p)}),n.length?new Ad(new kd().setPositions(n).setColors(r),new ld({linewidth:e.lineWidth,vertexColors:!0,resolution:new L(window.innerWidth,window.innerHeight)})).computeLineDistances():null},Md=e=>{let{corners:t,edges:n}=e,r=[],i=Xu(e),a=ed(e,i);return r.push(...a),t.enabled&&r.push(...td(e,i)),n.enabled&&r.push(...nd(e,i,t.enabled?7:6)),[r,ad(a,e),jd(e)]},Nd=(e,t=!0)=>{let{material:n,userData:r}=e,{opacity:i,color:a,scale:o}=t?r.hover:r;e.scale.setScalar(o),n.opacity=i,n.map?Zu(n.map,t):n.color.set(a)},Pd=new yn,Fd=new mo,Id=new L,Ld=new R,Rd=new Bt,zd=class extends Kn{constructor(e,t,n={}){super(),bu(this,`enabled`,!0),bu(this,`camera`),bu(this,`renderer`),bu(this,`options`),bu(this,`target`,new R),bu(this,`animated`,!0),bu(this,`speed`,1),bu(this,`animating`,!1),bu(this,`_options`),bu(this,`_intersections`),bu(this,`_background`,null),bu(this,`_viewport`,[0,0,0,0]),bu(this,`_originalViewport`,[0,0,0,0]),bu(this,`_originalScissor`,[0,0,0,0]),bu(this,`_scene`),bu(this,`_camera`),bu(this,`_container`),bu(this,`_domElement`),bu(this,`_domRect`),bu(this,`_dragging`,!1),bu(this,`_distance`,0),bu(this,`_clock`,new Ya),bu(this,`_targetQuaternion`,new gt),bu(this,`_quaternionStart`,new gt),bu(this,`_quaternionEnd`,new gt),bu(this,`_pointerStart`,new L),bu(this,`_focus`,null),bu(this,`_placement`),bu(this,`_controls`),bu(this,`_controlsListeners`),this.camera=e,this.renderer=t,this._scene=new li().add(this),this.set(n)}get placement(){return this._placement}set placement(e){this._placement=xu(this._domElement,e),this.domUpdate()}set(e={}){this.dispose(),this.options=e,this._options=Ju(e),this._camera=this._options.isSphere?new Ua(-1.8,1.8,1.8,-1.8,5,10):new ei(26,1,5,10),this._camera.position.set(0,0,7);let[t,n,r]=Md(this._options);n&&this.add(n),r&&this.add(r),this.add(...t),this._background=n,this._intersections=t;let{container:i,animated:a,speed:o}=this._options;return this.animated=a,this.speed=o,this._container=i?Cu(i):document.body,this._domElement=Su(this._options),this._domElement.onpointerdown=e=>this._onPointerDown(e),this._domElement.onpointermove=e=>this._onPointerMove(e),this._domElement.onpointerleave=()=>this._onPointerLeave(),this._container.appendChild(this._domElement),this._controls&&this.attachControls(this._controls),this.update(),this._updateOrientation(!0),this}render(){this.animating&&this._animate();let{renderer:e,_viewport:t}=this,n=e.getScissorTest(),r=e.autoClear;return e.autoClear=!1,e.setViewport(...t),n&&e.setScissor(...t),e.clear(!1,!0,!1),e.render(this._scene,this._camera),e.setViewport(...this._originalViewport),n&&e.setScissor(...this._originalScissor),e.autoClear=r,this}domUpdate(){this._domRect=this._domElement.getBoundingClientRect();let e=this.renderer,t=this._domRect,n=e.domElement.getBoundingClientRect();return this._viewport.splice(0,4,t.left-n.left,e.domElement.clientHeight-(t.top-n.top+t.height),t.width,t.height),e.getViewport(Rd).toArray(this._originalViewport),e.getScissorTest()&&e.getScissor(Rd).toArray(this._originalScissor),this}cameraUpdate(){return this._updateOrientation(),this}update(e=!0){return e&&this._controls&&this._controls.update(),this.domUpdate().cameraUpdate()}attachControls(e){return this.detachControls(),this.target=e.target,this._controlsListeners={start:()=>e.enabled=!1,end:()=>e.enabled=!0,change:()=>this.update(!1)},this.addEventListener(`start`,this._controlsListeners.start),this.addEventListener(`end`,this._controlsListeners.end),e.addEventListener(`change`,this._controlsListeners.change),this._controls=e,this}detachControls(){if(!(!this._controlsListeners||!this._controls))return this.target=new R().copy(this._controls.target),this.removeEventListener(`start`,this._controlsListeners.start),this.removeEventListener(`end`,this._controlsListeners.end),this._controls.removeEventListener(`change`,this._controlsListeners.change),this._controlsListeners=void 0,this._controls=void 0,this}dispose(){var e;this.detachControls(),this.children.forEach(e=>{var t,n,r;this.remove(e);let i=e;(t=i.material)==null||t.dispose(),(n=i.material?.map)==null||n.dispose(),(r=i.geometry)==null||r.dispose()}),(e=this._domElement)==null||e.remove()}_updateOrientation(e=!0){e&&(this.quaternion.copy(this.camera.quaternion).invert(),this.updateMatrixWorld()),Du(this._options,this._intersections,this.camera)}_animate(){let{position:e,quaternion:t}=this.camera;if(e.set(0,0,1),!this.animated){e.applyQuaternion(this._quaternionEnd).multiplyScalar(this._distance).add(this.target),t.copy(this._targetQuaternion),this._updateOrientation(),this.animating=!1,this.dispatchEvent({type:`change`}),this.dispatchEvent({type:`end`});return}this._controls&&(this._controls.enabled=!1);let n=this._clock.getDelta()*Nu*this.speed;this._quaternionStart.rotateTowards(this._quaternionEnd,n),e.applyQuaternion(this._quaternionStart).multiplyScalar(this._distance).add(this.target),t.rotateTowards(this._targetQuaternion,n),this._updateOrientation(),requestAnimationFrame(()=>this.dispatchEvent({type:`change`})),this._quaternionStart.angleTo(this._quaternionEnd)<Mu&&(this._controls&&(this._controls.enabled=!0),this.animating=!1,this.dispatchEvent({type:`end`}))}_setOrientation(e){let t=this.camera,n=this.target;Ld.copy(e).multiplyScalar(this._distance),Pd.setPosition(Ld).lookAt(Ld,this.position,this.up),this._targetQuaternion.setFromRotationMatrix(Pd),Ld.add(n),Pd.lookAt(Ld,n,this.up),this._quaternionEnd.setFromRotationMatrix(Pd),Pd.setPosition(t.position).lookAt(t.position,n,this.up),this._quaternionStart.setFromRotationMatrix(Pd),this.animating=!0,this._clock.start(),this.dispatchEvent({type:`start`})}_onPointerDown(e){if(!this.enabled)return;let t=e=>{if(!this._dragging){if(Ou(e,this._pointerStart))return;this._dragging=!0}let t=Id.set(e.clientX,e.clientY).sub(this._pointerStart).multiplyScalar(1/this._domRect.width*Math.PI),n=this.coordinateConversion(Ld.subVectors(this.camera.position,this.target)),r=Fd.setFromVector3(n);r.theta=a-t.x,r.phi=wu(o-t.y,Mu,Math.PI-Mu),this.coordinateConversion(this.camera.position.setFromSpherical(r),!0).add(this.target),this.camera.lookAt(this.target),this.quaternion.copy(this.camera.quaternion).invert(),this._updateOrientation(!1),this.dispatchEvent({type:`change`})},n=()=>{if(document.removeEventListener(`pointermove`,t,!1),document.removeEventListener(`pointerup`,n,!1),!this._dragging)return this._handleClick(e);this._focus&&=(Nd(this._focus,!1),null),this._dragging=!1,this.dispatchEvent({type:`end`})};if(this.animating)return;e.preventDefault(),this._pointerStart.set(e.clientX,e.clientY);let r=this.coordinateConversion(Ld.subVectors(this.camera.position,this.target)),i=Fd.setFromVector3(r),a=i.theta,o=i.phi;this._distance=i.radius,document.addEventListener(`pointermove`,t,!1),document.addEventListener(`pointerup`,n,!1),this.dispatchEvent({type:`start`})}coordinateConversion(e,t=!1){let{x:n,y:r,z:i}=e,a=Kn.DEFAULT_UP;return a.x===1?t?e.set(r,i,n):e.set(i,n,r):a.z===1?t?e.set(i,n,r):e.set(r,i,n):e}_onPointerMove(e){!this.enabled||this._dragging||(this._background&&Ku(this._background,!0),this._handleHover(e))}_onPointerLeave(){!this.enabled||this._dragging||(this._background&&Ku(this._background,!1),this._focus&&Nd(this._focus,!1),this._domElement.style.cursor=``)}_handleClick(e){let t=ju(e,this._domRect,this._camera,this._intersections);this._focus&&=(Nd(this._focus,!1),null),t&&(this._setOrientation(t.object.position),this.dispatchEvent({type:`change`}))}_handleHover(e){let t=ju(e,this._domRect,this._camera,this._intersections)?.object||null;this._focus!==t&&(this._domElement.style.cursor=t?`pointer`:``,this._focus&&Nd(this._focus,!1),(this._focus=t)?Nd(t,!0):Du(this._options,this._intersections,this.camera))}},Bd=class extends Ue{target=new R;constructor(e){super(),this.cc=e,e.addEventListener(`update`,()=>{e.getTarget(this.target),this.dispatchEvent({type:`change`})})}get enabled(){return this.cc.enabled}set enabled(e){this.cc.enabled=e}update(){let e=this.cc.camera.position,t=this.target;this.cc.setLookAt(e.x,e.y,e.z,t.x,t.y,t.z,!1)}},Vd=new Set;function Hd(e,t){return getComputedStyle(document.documentElement).getPropertyValue(e).trim()||t}function Ud(){Wd.faceColor.set(Hd(`--scene-face-color`,`#969696`)),Wd.edgeColor.set(Hd(`--scene-edge-color`,`#000000`)),Wd.gridColor.set(Hd(`--scene-grid-color`,`#6f6f6f`)),Wd.metaEdgeColor.set(Hd(`--scene-meta-edge-color`,`#b0b0b0`)),Wd.highlightColor.set(Hd(`--scene-highlight-color`,`#ffb433`)),Wd.selectEdgeColor.set(Hd(`--scene-select-edge-color`,`#11a4ed`)),Wd.selectFaceColor.set(Hd(`--scene-select-face-color`,`#5c9fcc`)),Wd.constraintColor.set(Hd(`--scene-constraint-color`,`#cccccc`)),Wd.backgroundColor.set(Hd(`--color-base-100`,`#1e1e1e`))}var Wd={faceColor:new B(`#969696`),edgeColor:new B(`#000000`),gridColor:new B(`#6f6f6f`),metaEdgeColor:new B(`#b0b0b0`),highlightColor:new B(`#ffb433`),selectEdgeColor:new B(`#11a4ed`),selectFaceColor:new B(`#5c9fcc`),constraintColor:new B(`#cccccc`),backgroundColor:new B(`#1e1e1e`)};Ud(),new MutationObserver(()=>{Ud();for(let e of Vd)e()}).observe(document.documentElement,{attributes:!0,attributeFilter:[`data-theme`]});function Gd(e){return Vd.add(e),()=>Vd.delete(e)}var Kd=class e{static resolution=new L(window.innerWidth,window.innerHeight);static materials=new Set;static register(t){t.resolution.copy(e.resolution),e.materials.add(t),t.addEventListener(`dispose`,()=>{e.materials.delete(t)})}static setResolution(t,n){e.resolution.set(t,n);for(let t of e.materials)t.resolution.copy(e.resolution)}},qd=new L;function Jd(e){e.getSize(qd);let t=qd.y;return t>0?t:e.domElement.clientHeight||1}function Yd(e,t){if(e instanceof Ua)return(e.top-e.bottom)/e.zoom;if(e instanceof ei){let n=e.position.distanceTo(t),r=e.fov*Math.PI/180;return 2*n*Math.tan(r/2)}return 1}function Xd(e,t,n,r){let i=Jd(e),a=Yd(t,n);return r/i*a}function Zd(e,t,n,r,i){let a=Xd(e,t,n,r)/i;return!Number.isFinite(a)||a<=0?1e-4:Math.min(Math.max(a,1e-4),1e6)}var Qd=null,$d=null;function ef(e,t){Qd=e,$d=t}function tf(e,t,n,r,i){Qd&&$d&&(t.scale.setScalar(Zd(Qd,$d(),n,r,i)),t.updateMatrixWorld(!0)),e.onBeforeRender=(e,a,o)=>{t.scale.setScalar(Zd(e,o,n,r,i)),t.updateMatrixWorld(!0)}}_u.install({THREE:{Vector2:L,Vector3:R,Vector4:Bt,Quaternion:gt,Matrix4:yn,Spherical:mo,Box3:Gt,Sphere:un,Raycaster:uo,MathUtils:{DEG2RAD:ht.DEG2RAD,clamp:ht.clamp}}});var nf=new R(0,0,1),rf=120,af=1.1,of=class{scene;renderer;gizmo;orthoCamera;perspCamera;activeCamera=`orthographic`;_cc;_adapter;dirLight;renderRequested=!1;resizeObserver;clock=new Ya;animFrameId=0;gizmoWasActive=!1;constructor(e){this.container=e,Kn.DEFAULT_UP=nf.clone();let t=e.clientWidth||window.innerWidth,n=e.clientHeight||window.innerHeight;this.renderer=new Dl({antialias:!0,alpha:!0}),this.renderer.setSize(t,n),this.renderer.setPixelRatio(window.devicePixelRatio),Kd.setResolution(t,n),this.renderer.toneMapping=4,this.renderer.outputColorSpace=Ie,this.renderer.localClippingEnabled=!0,e.appendChild(this.renderer.domElement),this.scene=new li,this.scene.background=Wd.backgroundColor.clone();let r=t/n;this.orthoCamera=new Ua(-r*rf/2,r*rf/2,rf/2,-rf/2,-1e4,1e4),this.orthoCamera.position.set(50,-50,40),this.orthoCamera.up.copy(nf),this.orthoCamera.lookAt(0,0,0),this.perspCamera=new ei(50,r,.5,1e4),this.perspCamera.position.set(50,-50,40),this.perspCamera.up.copy(nf),this.perspCamera.lookAt(0,0,0),ef(this.renderer,()=>this.camera),this.dirLight=new Ga(16777215,1),this.scene.add(this.dirLight),this.scene.add(new Ka(14544639,2.5)),this._cc=new _u(this.orthoCamera,this.renderer.domElement),this._cc.dollyToCursor=!0,this._cc.smoothTime=.1,this._cc.draggingSmoothTime=.05,this.configureTouchForMode(`orthographic`),this._cc.updateCameraUp(),this._adapter=new Bd(this._cc),this.gizmo=new zd(this.camera,this.renderer,{size:80,type:`sphere`}),this._cc.setLookAt(50,-50,40,0,0,0,!1),this._cc.getTarget(this._adapter.target),this.gizmo.target=this._adapter.target,this.gizmo.attachControls(this._adapter),this.gizmo.addEventListener(`change`,()=>this.requestRender()),this.resizeObserver=new ResizeObserver(()=>this.handleResize()),this.resizeObserver.observe(e),Gd(()=>{this.scene.background=Wd.backgroundColor.clone(),this.requestRender()}),this.tick()}get camera(){return this.activeCamera===`orthographic`?this.orthoCamera:this.perspCamera}createPickingRaycaster(e,t){let n=this.camera;n.updateMatrixWorld(),n.updateProjectionMatrix();let r=new uo;if(r.setFromCamera(new L(e,t),n),n.isOrthographicCamera){let e=n,t=Math.max(Math.abs(e.far-e.near),1);r.ray.origin.addScaledVector(r.ray.direction,-t)}return r}get cameraControls(){return this._cc}get controls(){return this._adapter}requestRender(){this.renderRequested=!0}fitToBox(e,t){let n=e.getCenter(new R),r=e.getSize(new R).length()/2;if(r===0)return;let i=new un(n,r*af);this._cc.fitToSphere(i,t)}switchCamera(e){if(e===this.activeCamera)return;let t=new R,n=new R;this._cc.getPosition(t),this._cc.getTarget(n);let r=this.camera.up.clone();if(this.activeCamera===`orthographic`&&e===`perspective`){let e=(this.orthoCamera.top-this.orthoCamera.bottom)/this.orthoCamera.zoom,r=ht.DEG2RAD*this.perspCamera.fov*.5,i=e*.5/Math.tan(r),a=t.clone().sub(n).normalize();t.copy(n).add(a.multiplyScalar(i))}this.activeCamera=e;let i=this.camera;i.position.copy(t),i.up.copy(r),i.lookAt(n),this._cc.dispose(),this._cc=new _u(i,this.renderer.domElement),this._cc.dollyToCursor=!0,this._cc.smoothTime=.1,this._cc.draggingSmoothTime=.05,this._cc.setLookAt(t.x,t.y,t.z,n.x,n.y,n.z,!1),this._cc.updateCameraUp(),this.configureTouchForMode(e),this._adapter=new Bd(this._cc),this._cc.getTarget(this._adapter.target),this.gizmo.camera=i,this.gizmo.target=this._adapter.target,this.gizmo.attachControls(this._adapter),this.gizmo.update(),this.requestRender()}render(){this.updateLightPositions(),this.renderer.render(this.scene,this.camera),this.gizmo.render()}dispose(){cancelAnimationFrame(this.animFrameId),this.resizeObserver.disconnect(),this._cc.dispose(),this.scene.clear(),this.renderer.dispose()}tick=()=>{let e=this.clock.getDelta(),t=!1;if(this._cc.enabled){if(this.gizmoWasActive){this._cc.updateCameraUp();let e=this.camera.position,t=this._adapter.target;this._cc.setLookAt(e.x,e.y,e.z,t.x,t.y,t.z,!1),this.gizmoWasActive=!1}t=this._cc.update(e)}else this.gizmoWasActive=!0;(t||this.renderRequested||!this._cc.enabled)&&(this.render(),this.renderRequested=!1),this.animFrameId=requestAnimationFrame(this.tick)};configureTouchForMode(e){e===`orthographic`?(this._cc.touches.one=_u.ACTION.TOUCH_ROTATE,this._cc.touches.two=_u.ACTION.TOUCH_ZOOM_TRUCK):(this._cc.touches.one=_u.ACTION.TOUCH_ROTATE,this._cc.touches.two=_u.ACTION.TOUCH_DOLLY_TRUCK)}handleResize(){let e=this.container.clientWidth,t=this.container.clientHeight||window.innerHeight;if(e===0||t===0)return;let n=e/t;this.renderer.setSize(e,t),this.renderer.setPixelRatio(window.devicePixelRatio),Kd.setResolution(e,t),this.orthoCamera.left=-n*rf/2,this.orthoCamera.right=n*rf/2,this.orthoCamera.top=rf/2,this.orthoCamera.bottom=-rf/2,this.orthoCamera.updateProjectionMatrix(),this.perspCamera.aspect=n,this.perspCamera.updateProjectionMatrix(),this.gizmo.update(),this.requestRender()}updateLightPositions(){let e=new R;this.camera.getWorldDirection(e),this.dirLight.position.copy(e.multiplyScalar(-10)),this.dirLight.target.position.set(0,0,0),this.dirLight.target.updateMatrixWorld()}},sf=class extends U{constructor(e=10,t=100,n=new B(`white`),r=8e3,i=new R(0,1,0)){let a=new ma(2,2,1,1),o=new Yr({side:0,polygonOffset:!0,polygonOffsetFactor:2,polygonOffsetUnits:2,uniforms:{uSize1:{value:e},uSize2:{value:t},uColor:{value:n},uDistance:{value:r},uNormal:{value:i.normalize()}},transparent:!0,vertexShader:`
4203
4203
 
4204
4204
  varying vec3 worldPosition;
4205
4205
 
@@ -4272,7 +4272,7 @@ void main() {
4272
4272
 
4273
4273
  }
4274
4274
 
4275
- `,extensions:{clipCullDistance:!1,multiDraw:!1}});super(a,o),this.frustumCulled=!1}},Kd={cameraMode:`orthographic`,showGrid:!0,sectionView:!0},qd=new class{current={...Kd};listeners=new Set;update(e){Object.assign(this.current,e);for(let e of this.listeners)e(this.current)}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}};function Jd(e){qd.update({showGrid:e.showGrid,cameraMode:e.cameraMode})}var Yd=new R(0,0,1),Xd=new R(50,-50,40),Zd=50;function Qd(e){return new R(e.x,e.y,e.z)}var $d=class{mode=`default`;cameraBackup=null;cameraBackupMode=null;enabled=!0;lastGridNormal=Yd.clone();lastGridPosition;_sectionPlane=null;constructor(e){this.ctx=e,this.setupDefaultAxes(),this.setupGrid(Yd),qd.subscribe(()=>this.applyGridVisibility()),zd(()=>this.rebuildGrid())}get currentMode(){return this.mode}get isSketchMode(){return this.mode===`sketch`}get sectionPlane(){return this._sectionPlane}set sketchEnabled(e){this.enabled=e}enterDefaultMode(){this.mode===`sketch`&&(this._sectionPlane=null,this.restoreCamera(),this.cameraBackupMode===`perspective`&&(this.ctx.switchCamera(`perspective`),qd.update({cameraMode:`perspective`})),this.cameraBackupMode=null),this.mode=`default`,this.ctx.camera.up.copy(Kn.DEFAULT_UP),this.ctx.cameraControls.updateCameraUp(),this.showDefaultAxes(),this.setupGrid(Yd)}enterSketchMode(e){if(!this.enabled)return;this.mode=`sketch`,qd.current.cameraMode===`perspective`&&(this.cameraBackupMode=`perspective`,this.ctx.switchCamera(`orthographic`)),this.positionCameraForSketch(e),this.showSketchAxes(e);let t=Qd(e.normal),n=Qd(e.origin);this.setupGrid(t,n.add(t.clone().multiplyScalar(-.01))),this.createSectionPlane(e)}enforceSketchNormal(e){let t=this.ctx.cameraControls,n=Qd(e.normal),r=Qd(e.yDirection),i=new R;t.getTarget(i);let a=i.clone().add(n.clone().multiplyScalar(Zd));this.ctx.camera.up.copy(r),t.updateCameraUp(),t.normalizeRotations(),t.setLookAt(a.x,a.y,a.z,i.x,i.y,i.z,!1),t.getTarget(this.ctx.controls.target),this.ctx.gizmo.target=this.ctx.controls.target,this.showSketchAxes(e);let o=Qd(e.origin);this.setupGrid(n,o.add(n.clone().multiplyScalar(-.01))),this.createSectionPlane(e)}positionCameraForSketch(e){let t=this.ctx.cameraControls;if(!this.cameraBackup){let e=new R,n=new R;t.getPosition(e),t.getTarget(n),this.cameraBackup={position:e,target:n}}let n=Qd(e.center),r=Qd(e.normal),i=Qd(e.yDirection),a=n.clone().add(r.clone().multiplyScalar(Zd));this.ctx.camera.up.copy(i),t.updateCameraUp(),t.normalizeRotations(),t.setLookAt(a.x,a.y,a.z,n.x,n.y,n.z,!1),t.getTarget(this.ctx.controls.target),this.ctx.gizmo.target=this.ctx.controls.target}restoreCamera(){let e=this.ctx.cameraControls,t=this.cameraBackup,n=t?.position??Xd.clone(),r=t?.target??new R(0,0,0);this.ctx.camera.up.copy(Kn.DEFAULT_UP),e.updateCameraUp(),e.normalizeRotations(),e.setLookAt(n.x,n.y,n.z,r.x,r.y,r.z,!1),e.getTarget(this.ctx.controls.target),this.ctx.gizmo.target=this.ctx.controls.target,this.cameraBackup=null}setupDefaultAxes(){let e=new _o(1e3);e.name=`defaultAxesHelper`,this.ctx.scene.add(e)}showDefaultAxes(){this.removeByName(`sketchAxesHelper`);let e=this.ctx.scene.getObjectByName(`defaultAxesHelper`);e&&(e.visible=!0)}showSketchAxes(e){let t=this.ctx.scene.getObjectByName(`defaultAxesHelper`);t&&(t.visible=!1),this.removeByName(`sketchAxesHelper`);let n=new _o(1e3);n.name=`sketchAxesHelper`;let r=Qd(e.origin),i=Qd(e.xDirection),a=Qd(e.yDirection),o=Qd(e.normal),s=new yn().makeBasis(i,a,o);s.setPosition(r),n.matrix.copy(s),n.matrixAutoUpdate=!1,this.ctx.scene.add(n)}rebuildGrid(){this.setupGrid(this.lastGridNormal,this.lastGridPosition),this.ctx.requestRender()}setupGrid(e,t){this.lastGridNormal=e.clone(),this.lastGridPosition=t?.clone(),this.removeByName(`grid`);let n=new Gd(10,100,Rd.gridColor,1e5,e);n.name=`grid`,t&&n.position.copy(t),n.visible=this.mode===`sketch`||qd.current.showGrid,this.ctx.scene.add(n)}applyGridVisibility(){let e=this.ctx.scene.getObjectByName(`grid`);e&&(e.visible=this.mode===`sketch`||qd.current.showGrid,this.ctx.requestRender())}createSectionPlane(e){let t=Qd(e.normal).negate(),n=Qd(e.origin);this._sectionPlane||=new Ni,this._sectionPlane.setFromNormalAndCoplanarPoint(t,n)}removeByName(e){let t=this.ctx.scene.getObjectByName(e);t&&this.ctx.scene.remove(t)}},ef=new Gt,tf=new R,nf=class extends Va{constructor(){super(),this.isLineSegmentsGeometry=!0,this.type=`LineSegmentsGeometry`,this.setIndex([0,2,1,2,3,1,2,4,3,4,5,3,4,6,5,6,7,5]),this.setAttribute(`position`,new br([-1,2,0,1,2,0,-1,1,0,1,1,0,-1,0,0,1,0,0,-1,-1,0,1,-1,0],3)),this.setAttribute(`uv`,new br([-1,2,1,2,-1,1,1,1,-1,-1,1,-1,-1,-2,1,-2],2))}applyMatrix4(e){let t=this.attributes.instanceStart,n=this.attributes.instanceEnd;return t!==void 0&&(t.applyMatrix4(e),n.applyMatrix4(e),t.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}setPositions(e){let t;e instanceof Float32Array?t=e:Array.isArray(e)&&(t=new Float32Array(e));let n=new no(t,6,1);return this.setAttribute(`instanceStart`,new pi(n,3,0)),this.setAttribute(`instanceEnd`,new pi(n,3,3)),this.instanceCount=this.attributes.instanceStart.count,this.computeBoundingBox(),this.computeBoundingSphere(),this}setColors(e){let t;e instanceof Float32Array?t=e:Array.isArray(e)&&(t=new Float32Array(e));let n=new no(t,6,1);return this.setAttribute(`instanceColorStart`,new pi(n,3,0)),this.setAttribute(`instanceColorEnd`,new pi(n,3,3)),this}fromWireframeGeometry(e){return this.setPositions(e.attributes.position.array),this}fromEdgesGeometry(e){return this.setPositions(e.attributes.position.array),this}fromMesh(e){return this.fromWireframeGeometry(new ua(e.geometry)),this}fromLineSegments(e){let t=e.geometry;return this.setPositions(t.attributes.position.array),this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Gt);let e=this.attributes.instanceStart,t=this.attributes.instanceEnd;e!==void 0&&t!==void 0&&(this.boundingBox.setFromBufferAttribute(e),ef.setFromBufferAttribute(t),this.boundingBox.union(ef))}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new un),this.boundingBox===null&&this.computeBoundingBox();let e=this.attributes.instanceStart,t=this.attributes.instanceEnd;if(e!==void 0&&t!==void 0){let n=this.boundingSphere.center;this.boundingBox.getCenter(n);let r=0;for(let i=0,a=e.count;i<a;i++)tf.fromBufferAttribute(e,i),r=Math.max(r,n.distanceToSquared(tf)),tf.fromBufferAttribute(t,i),r=Math.max(r,n.distanceToSquared(tf));this.boundingSphere.radius=Math.sqrt(r),isNaN(this.boundingSphere.radius)&&console.error(`THREE.LineSegmentsGeometry.computeBoundingSphere(): Computed radius is NaN. The instanced position data is likely to have NaN values.`,this)}}toJSON(){}};W.line={worldUnits:{value:1},linewidth:{value:1},resolution:{value:new L(1,1)},dashOffset:{value:0},dashScale:{value:1},dashSize:{value:1},gapSize:{value:1}},So.line={uniforms:qr.merge([W.common,W.fog,W.line]),vertexShader:`
4275
+ `,extensions:{clipCullDistance:!1,multiDraw:!1}});super(a,o),this.frustumCulled=!1}},cf={cameraMode:`orthographic`,showGrid:!0,sectionView:!0},lf=new class{current={...cf};listeners=new Set;update(e){Object.assign(this.current,e);for(let e of this.listeners)e(this.current)}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}};function uf(e){lf.update({showGrid:e.showGrid,cameraMode:e.cameraMode})}var df=new R(0,0,1),ff=new R(50,-50,40),pf=50;function mf(e){return new R(e.x,e.y,e.z)}var hf=class{mode=`default`;cameraBackup=null;cameraBackupMode=null;enabled=!0;lastGridNormal=df.clone();lastGridPosition;_sectionPlane=null;constructor(e){this.ctx=e,this.setupDefaultAxes(),this.setupGrid(df),lf.subscribe(()=>this.applyGridVisibility()),Gd(()=>this.rebuildGrid())}get currentMode(){return this.mode}get isSketchMode(){return this.mode===`sketch`}get sectionPlane(){return this._sectionPlane}set sketchEnabled(e){this.enabled=e}enterDefaultMode(){this.mode===`sketch`&&(this._sectionPlane=null,this.restoreCamera(),this.cameraBackupMode===`perspective`&&(this.ctx.switchCamera(`perspective`),lf.update({cameraMode:`perspective`})),this.cameraBackupMode=null),this.mode=`default`,this.ctx.camera.up.copy(Kn.DEFAULT_UP),this.ctx.cameraControls.updateCameraUp(),this.showDefaultAxes(),this.setupGrid(df)}enterSketchMode(e){if(!this.enabled)return;this.mode=`sketch`,lf.current.cameraMode===`perspective`&&(this.cameraBackupMode=`perspective`,this.ctx.switchCamera(`orthographic`)),this.positionCameraForSketch(e),this.showSketchAxes(e);let t=mf(e.normal),n=mf(e.origin);this.setupGrid(t,n.add(t.clone().multiplyScalar(-.01))),this.createSectionPlane(e)}enforceSketchNormal(e){let t=this.ctx.cameraControls,n=mf(e.normal),r=mf(e.yDirection),i=new R;t.getTarget(i);let a=i.clone().add(n.clone().multiplyScalar(pf));this.ctx.camera.up.copy(r),t.updateCameraUp(),t.normalizeRotations(),t.setLookAt(a.x,a.y,a.z,i.x,i.y,i.z,!1),t.getTarget(this.ctx.controls.target),this.ctx.gizmo.target=this.ctx.controls.target,this.showSketchAxes(e);let o=mf(e.origin);this.setupGrid(n,o.add(n.clone().multiplyScalar(-.01))),this.createSectionPlane(e)}positionCameraForSketch(e){let t=this.ctx.cameraControls;if(!this.cameraBackup){let e=new R,n=new R;t.getPosition(e),t.getTarget(n),this.cameraBackup={position:e,target:n}}let n=mf(e.center),r=mf(e.normal),i=mf(e.yDirection),a=n.clone().add(r.clone().multiplyScalar(pf));this.ctx.camera.up.copy(i),t.updateCameraUp(),t.normalizeRotations(),t.setLookAt(a.x,a.y,a.z,n.x,n.y,n.z,!1),t.getTarget(this.ctx.controls.target),this.ctx.gizmo.target=this.ctx.controls.target}restoreCamera(){let e=this.ctx.cameraControls,t=this.cameraBackup,n=t?.position??ff.clone(),r=t?.target??new R(0,0,0);this.ctx.camera.up.copy(Kn.DEFAULT_UP),e.updateCameraUp(),e.normalizeRotations(),e.setLookAt(n.x,n.y,n.z,r.x,r.y,r.z,!1),e.getTarget(this.ctx.controls.target),this.ctx.gizmo.target=this.ctx.controls.target,this.cameraBackup=null}setupDefaultAxes(){let e=new Co(1e3);e.name=`defaultAxesHelper`,this.ctx.scene.add(e)}showDefaultAxes(){this.removeByName(`sketchAxesHelper`);let e=this.ctx.scene.getObjectByName(`defaultAxesHelper`);e&&(e.visible=!0)}showSketchAxes(e){let t=this.ctx.scene.getObjectByName(`defaultAxesHelper`);t&&(t.visible=!1),this.removeByName(`sketchAxesHelper`);let n=new Co(1e3);n.name=`sketchAxesHelper`;let r=mf(e.origin),i=mf(e.xDirection),a=mf(e.yDirection),o=mf(e.normal),s=new yn().makeBasis(i,a,o);s.setPosition(r),n.matrix.copy(s),n.matrixAutoUpdate=!1,this.ctx.scene.add(n)}rebuildGrid(){this.setupGrid(this.lastGridNormal,this.lastGridPosition),this.ctx.requestRender()}setupGrid(e,t){this.lastGridNormal=e.clone(),this.lastGridPosition=t?.clone(),this.removeByName(`grid`);let n=new sf(10,100,Wd.gridColor,1e5,e);n.name=`grid`,t&&n.position.copy(t),n.visible=this.mode===`sketch`||lf.current.showGrid,this.ctx.scene.add(n)}applyGridVisibility(){let e=this.ctx.scene.getObjectByName(`grid`);e&&(e.visible=this.mode===`sketch`||lf.current.showGrid,this.ctx.requestRender())}createSectionPlane(e){let t=mf(e.normal).negate(),n=mf(e.origin);this._sectionPlane||=new Mi,this._sectionPlane.setFromNormalAndCoplanarPoint(t,n)}removeByName(e){let t=this.ctx.scene.getObjectByName(e);t&&this.ctx.scene.remove(t)}},gf=new Gt,_f=new R,vf=class extends qa{constructor(){super(),this.isLineSegmentsGeometry=!0,this.type=`LineSegmentsGeometry`,this.setIndex([0,2,1,2,3,1,2,4,3,4,5,3,4,6,5,6,7,5]),this.setAttribute(`position`,new br([-1,2,0,1,2,0,-1,1,0,1,1,0,-1,0,0,1,0,0,-1,-1,0,1,-1,0],3)),this.setAttribute(`uv`,new br([-1,2,1,2,-1,1,1,1,-1,-1,1,-1,-1,-2,1,-2],2))}applyMatrix4(e){let t=this.attributes.instanceStart,n=this.attributes.instanceEnd;return t!==void 0&&(t.applyMatrix4(e),n.applyMatrix4(e),t.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}setPositions(e){let t;e instanceof Float32Array?t=e:Array.isArray(e)&&(t=new Float32Array(e));let n=new co(t,6,1);return this.setAttribute(`instanceStart`,new fi(n,3,0)),this.setAttribute(`instanceEnd`,new fi(n,3,3)),this.instanceCount=this.attributes.instanceStart.count,this.computeBoundingBox(),this.computeBoundingSphere(),this}setColors(e){let t;e instanceof Float32Array?t=e:Array.isArray(e)&&(t=new Float32Array(e));let n=new co(t,6,1);return this.setAttribute(`instanceColorStart`,new fi(n,3,0)),this.setAttribute(`instanceColorEnd`,new fi(n,3,3)),this}fromWireframeGeometry(e){return this.setPositions(e.attributes.position.array),this}fromEdgesGeometry(e){return this.setPositions(e.attributes.position.array),this}fromMesh(e){return this.fromWireframeGeometry(new ga(e.geometry)),this}fromLineSegments(e){let t=e.geometry;return this.setPositions(t.attributes.position.array),this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Gt);let e=this.attributes.instanceStart,t=this.attributes.instanceEnd;e!==void 0&&t!==void 0&&(this.boundingBox.setFromBufferAttribute(e),gf.setFromBufferAttribute(t),this.boundingBox.union(gf))}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new un),this.boundingBox===null&&this.computeBoundingBox();let e=this.attributes.instanceStart,t=this.attributes.instanceEnd;if(e!==void 0&&t!==void 0){let n=this.boundingSphere.center;this.boundingBox.getCenter(n);let r=0;for(let i=0,a=e.count;i<a;i++)_f.fromBufferAttribute(e,i),r=Math.max(r,n.distanceToSquared(_f)),_f.fromBufferAttribute(t,i),r=Math.max(r,n.distanceToSquared(_f));this.boundingSphere.radius=Math.sqrt(r),isNaN(this.boundingSphere.radius)&&console.error(`THREE.LineSegmentsGeometry.computeBoundingSphere(): Computed radius is NaN. The instanced position data is likely to have NaN values.`,this)}}toJSON(){}};G.line={worldUnits:{value:1},linewidth:{value:1},resolution:{value:new L(1,1)},dashOffset:{value:0},dashScale:{value:1},dashSize:{value:1},gapSize:{value:1}},Oo.line={uniforms:Kr.merge([G.common,G.fog,G.line]),vertexShader:`
4276
4276
  #include <common>
4277
4277
  #include <color_pars_vertex>
4278
4278
  #include <fog_pars_vertex>
@@ -4641,7 +4641,7 @@ void main() {
4641
4641
  #include <premultiplied_alpha_fragment>
4642
4642
 
4643
4643
  }
4644
- `};var rf=class extends Xr{constructor(e){super({type:`LineMaterial`,uniforms:qr.clone(So.line.uniforms),vertexShader:So.line.vertexShader,fragmentShader:So.line.fragmentShader,clipping:!0}),this.isLineMaterial=!0,this.setValues(e)}get color(){return this.uniforms.diffuse.value}set color(e){this.uniforms.diffuse.value=e}get worldUnits(){return`WORLD_UNITS`in this.defines}set worldUnits(e){e===!0?this.defines.WORLD_UNITS=``:delete this.defines.WORLD_UNITS}get linewidth(){return this.uniforms.linewidth.value}set linewidth(e){this.uniforms.linewidth&&(this.uniforms.linewidth.value=e)}get dashed(){return`USE_DASH`in this.defines}set dashed(e){e===!0!==this.dashed&&(this.needsUpdate=!0),e===!0?this.defines.USE_DASH=``:delete this.defines.USE_DASH}get dashScale(){return this.uniforms.dashScale.value}set dashScale(e){this.uniforms.dashScale.value=e}get dashSize(){return this.uniforms.dashSize.value}set dashSize(e){this.uniforms.dashSize.value=e}get dashOffset(){return this.uniforms.dashOffset.value}set dashOffset(e){this.uniforms.dashOffset.value=e}get gapSize(){return this.uniforms.gapSize.value}set gapSize(e){this.uniforms.gapSize.value=e}get opacity(){return this.uniforms.opacity.value}set opacity(e){this.uniforms&&(this.uniforms.opacity.value=e)}get resolution(){return this.uniforms.resolution.value}set resolution(e){this.uniforms.resolution.value.copy(e)}get alphaToCoverage(){return`USE_ALPHA_TO_COVERAGE`in this.defines}set alphaToCoverage(e){this.defines&&(e===!0!==this.alphaToCoverage&&(this.needsUpdate=!0),e===!0?this.defines.USE_ALPHA_TO_COVERAGE=``:delete this.defines.USE_ALPHA_TO_COVERAGE)}},af=new Bt,of=new R,sf=new R,cf=new Bt,lf=new Bt,uf=new Bt,df=new R,ff=new yn,pf=new go,mf=new R,hf=new Gt,gf=new un,_f=new Bt,vf,yf;function bf(e,t,n){return _f.set(0,0,-t,1).applyMatrix4(e.projectionMatrix),_f.multiplyScalar(1/_f.w),_f.x=yf/n.width,_f.y=yf/n.height,_f.applyMatrix4(e.projectionMatrixInverse),_f.multiplyScalar(1/_f.w),Math.abs(Math.max(_f.x,_f.y))}function xf(e,t){let n=e.matrixWorld,r=e.geometry,i=r.attributes.instanceStart,a=r.attributes.instanceEnd,o=Math.min(r.instanceCount,i.count);for(let r=0,s=o;r<s;r++){pf.start.fromBufferAttribute(i,r),pf.end.fromBufferAttribute(a,r),pf.applyMatrix4(n);let o=new R,s=new R;vf.distanceSqToSegment(pf.start,pf.end,s,o),s.distanceTo(o)<yf*.5&&t.push({point:s,pointOnLine:o,distance:vf.origin.distanceTo(s),object:e,face:null,faceIndex:r,uv:null,uv1:null})}}function Sf(e,t,n){let r=t.projectionMatrix,i=e.material.resolution,a=e.matrixWorld,o=e.geometry,s=o.attributes.instanceStart,c=o.attributes.instanceEnd,l=Math.min(o.instanceCount,s.count),u=-t.near;vf.at(1,uf),uf.w=1,uf.applyMatrix4(t.matrixWorldInverse),uf.applyMatrix4(r),uf.multiplyScalar(1/uf.w),uf.x*=i.x/2,uf.y*=i.y/2,uf.z=0,df.copy(uf),ff.multiplyMatrices(t.matrixWorldInverse,a);for(let t=0,o=l;t<o;t++){if(cf.fromBufferAttribute(s,t),lf.fromBufferAttribute(c,t),cf.w=1,lf.w=1,cf.applyMatrix4(ff),lf.applyMatrix4(ff),cf.z>u&&lf.z>u)continue;if(cf.z>u){let e=cf.z-lf.z,t=(cf.z-u)/e;cf.lerp(lf,t)}else if(lf.z>u){let e=lf.z-cf.z,t=(lf.z-u)/e;lf.lerp(cf,t)}cf.applyMatrix4(r),lf.applyMatrix4(r),cf.multiplyScalar(1/cf.w),lf.multiplyScalar(1/lf.w),cf.x*=i.x/2,cf.y*=i.y/2,lf.x*=i.x/2,lf.y*=i.y/2,pf.start.copy(cf),pf.start.z=0,pf.end.copy(lf),pf.end.z=0;let o=pf.closestPointToPointParameter(df,!0);pf.at(o,mf);let l=ht.lerp(cf.z,lf.z,o),d=l>=-1&&l<=1,f=df.distanceTo(mf)<yf*.5;if(d&&f){pf.start.fromBufferAttribute(s,t),pf.end.fromBufferAttribute(c,t),pf.start.applyMatrix4(a),pf.end.applyMatrix4(a);let r=new R,i=new R;vf.distanceSqToSegment(pf.start,pf.end,i,r),n.push({point:i,pointOnLine:r,distance:vf.origin.distanceTo(i),object:e,face:null,faceIndex:t,uv:null,uv1:null})}}}var Cf=class extends H{constructor(e=new nf,t=new rf({color:Math.random()*16777215})){super(e,t),this.isLineSegments2=!0,this.type=`LineSegments2`}computeLineDistances(){let e=this.geometry,t=e.attributes.instanceStart,n=e.attributes.instanceEnd,r=new Float32Array(2*t.count);for(let e=0,i=0,a=t.count;e<a;e++,i+=2)of.fromBufferAttribute(t,e),sf.fromBufferAttribute(n,e),r[i]=i===0?0:r[i-1],r[i+1]=r[i]+of.distanceTo(sf);let i=new no(r,2,1);return e.setAttribute(`instanceDistanceStart`,new pi(i,1,0)),e.setAttribute(`instanceDistanceEnd`,new pi(i,1,1)),this}raycast(e,t){let n=this.material.worldUnits,r=e.camera;r===null&&!n&&console.error(`LineSegments2: "Raycaster.camera" needs to be set in order to raycast against LineSegments2 while worldUnits is set to false.`);let i=e.params.Line2===void 0?0:e.params.Line2.threshold||0;vf=e.ray;let a=this.matrixWorld,o=this.geometry,s=this.material;yf=s.linewidth+i,o.boundingSphere===null&&o.computeBoundingSphere(),gf.copy(o.boundingSphere).applyMatrix4(a);let c;if(c=n?yf*.5:bf(r,Math.max(r.near,gf.distanceToPoint(vf.origin)),s.resolution),gf.radius+=c,vf.intersectsSphere(gf)===!1)return;o.boundingBox===null&&o.computeBoundingBox(),hf.copy(o.boundingBox).applyMatrix4(a);let l;l=n?yf*.5:bf(r,Math.max(r.near,hf.distanceToPoint(vf.origin)),s.resolution),hf.expandByScalar(l),vf.intersectsBox(hf)!==!1&&(n?xf(this,t):Sf(this,r,t))}onBeforeRender(e){let t=this.material.uniforms;t&&t.resolution&&(e.getViewport(af),this.material.uniforms.resolution.value.set(af.z,af.w))}},wf={color:``,lineWidth:1,opacity:1,depthWrite:!0,transparent:!1},Tf=class e extends si{constructor(t,n={}){super();let r={...wf,...n};for(let n of t.meshes){let t=e.expandIndexedPositions(n.vertices,n.indices),i=new nf;i.setPositions(t);let a=new rf({color:r.color||Rd.edgeColor.getHex(),linewidth:r.lineWidth,transparent:r.transparent||r.opacity<1,opacity:r.opacity,side:2,depthWrite:r.depthWrite,depthTest:r.depthWrite});Bd.register(a);let o=new Cf(i,a);o.userData.isEdgeLine=!0,n.edgeIndex!==void 0&&(o.userData.edgeIndex=n.edgeIndex),this.add(o)}}static expandIndexedPositions(e,t){let n=new Float32Array(t.length*3);for(let r=0;r<t.length;r++){let i=t[r]*3;n[r*3]=e[i],n[r*3+1]=e[i+1],n[r*3+2]=e[i+2]}return n}},Ef={color:``,opacity:1},Df=class extends si{constructor(e,t={}){super();let n={...Ef,...t};for(let r of e.meshes){let e=new Or;e.setAttribute(`position`,new V(new Float32Array(r.vertices),3)),e.setAttribute(`normal`,new V(new Float32Array(r.normals),3));let i=r.vertices.length/3>65535?Uint32Array:Uint16Array;e.setIndex(new V(new i(r.indices),1)),e.computeBoundingBox();let a=t?.color??r.color??`#`+Rd.faceColor.getHexString(),o=t?.color!==void 0||t?.opacity!==void 0,s=new H(e,new fa({color:a,transparent:o||n.opacity<1,opacity:n.opacity,depthWrite:!o,polygonOffset:!0,polygonOffsetFactor:o?-1:1,polygonOffsetUnits:1,side:2}));r.faceMapping&&(s.userData.faceMapping=r.faceMapping),this.add(s)}}},Of=class extends si{constructor(e,t){super();for(let n of e.meshes)if(n.label===`solid-faces`){let e=new Df({shapeType:`face`,meshes:[n]},t?.face);e.renderOrder=1,this.add(e)}else if(n.label===`solid-edges`){let e=new Tf({shapeType:`edge`,meshes:[n]},t?.edge);e.renderOrder=2,this.add(e)}}},kf=4,Af=1.5,jf=.6,Mf=kf+Af+jf+Af,Nf=`
4644
+ `};var yf=class extends Yr{constructor(e){super({type:`LineMaterial`,uniforms:Kr.clone(Oo.line.uniforms),vertexShader:Oo.line.vertexShader,fragmentShader:Oo.line.fragmentShader,clipping:!0}),this.isLineMaterial=!0,this.setValues(e)}get color(){return this.uniforms.diffuse.value}set color(e){this.uniforms.diffuse.value=e}get worldUnits(){return`WORLD_UNITS`in this.defines}set worldUnits(e){e===!0?this.defines.WORLD_UNITS=``:delete this.defines.WORLD_UNITS}get linewidth(){return this.uniforms.linewidth.value}set linewidth(e){this.uniforms.linewidth&&(this.uniforms.linewidth.value=e)}get dashed(){return`USE_DASH`in this.defines}set dashed(e){e===!0!==this.dashed&&(this.needsUpdate=!0),e===!0?this.defines.USE_DASH=``:delete this.defines.USE_DASH}get dashScale(){return this.uniforms.dashScale.value}set dashScale(e){this.uniforms.dashScale.value=e}get dashSize(){return this.uniforms.dashSize.value}set dashSize(e){this.uniforms.dashSize.value=e}get dashOffset(){return this.uniforms.dashOffset.value}set dashOffset(e){this.uniforms.dashOffset.value=e}get gapSize(){return this.uniforms.gapSize.value}set gapSize(e){this.uniforms.gapSize.value=e}get opacity(){return this.uniforms.opacity.value}set opacity(e){this.uniforms&&(this.uniforms.opacity.value=e)}get resolution(){return this.uniforms.resolution.value}set resolution(e){this.uniforms.resolution.value.copy(e)}get alphaToCoverage(){return`USE_ALPHA_TO_COVERAGE`in this.defines}set alphaToCoverage(e){this.defines&&(e===!0!==this.alphaToCoverage&&(this.needsUpdate=!0),e===!0?this.defines.USE_ALPHA_TO_COVERAGE=``:delete this.defines.USE_ALPHA_TO_COVERAGE)}},bf=new Bt,xf=new R,Sf=new R,Cf=new Bt,wf=new Bt,Tf=new Bt,Ef=new R,Df=new yn,Of=new So,kf=new R,Af=new Gt,jf=new un,Mf=new Bt,Nf,Pf;function Ff(e,t,n){return Mf.set(0,0,-t,1).applyMatrix4(e.projectionMatrix),Mf.multiplyScalar(1/Mf.w),Mf.x=Pf/n.width,Mf.y=Pf/n.height,Mf.applyMatrix4(e.projectionMatrixInverse),Mf.multiplyScalar(1/Mf.w),Math.abs(Math.max(Mf.x,Mf.y))}function If(e,t){let n=e.matrixWorld,r=e.geometry,i=r.attributes.instanceStart,a=r.attributes.instanceEnd,o=Math.min(r.instanceCount,i.count);for(let r=0,s=o;r<s;r++){Of.start.fromBufferAttribute(i,r),Of.end.fromBufferAttribute(a,r),Of.applyMatrix4(n);let o=new R,s=new R;Nf.distanceSqToSegment(Of.start,Of.end,s,o),s.distanceTo(o)<Pf*.5&&t.push({point:s,pointOnLine:o,distance:Nf.origin.distanceTo(s),object:e,face:null,faceIndex:r,uv:null,uv1:null})}}function Lf(e,t,n){let r=t.projectionMatrix,i=e.material.resolution,a=e.matrixWorld,o=e.geometry,s=o.attributes.instanceStart,c=o.attributes.instanceEnd,l=Math.min(o.instanceCount,s.count),u=-t.near;Nf.at(1,Tf),Tf.w=1,Tf.applyMatrix4(t.matrixWorldInverse),Tf.applyMatrix4(r),Tf.multiplyScalar(1/Tf.w),Tf.x*=i.x/2,Tf.y*=i.y/2,Tf.z=0,Ef.copy(Tf),Df.multiplyMatrices(t.matrixWorldInverse,a);for(let t=0,o=l;t<o;t++){if(Cf.fromBufferAttribute(s,t),wf.fromBufferAttribute(c,t),Cf.w=1,wf.w=1,Cf.applyMatrix4(Df),wf.applyMatrix4(Df),Cf.z>u&&wf.z>u)continue;if(Cf.z>u){let e=Cf.z-wf.z,t=(Cf.z-u)/e;Cf.lerp(wf,t)}else if(wf.z>u){let e=wf.z-Cf.z,t=(wf.z-u)/e;wf.lerp(Cf,t)}Cf.applyMatrix4(r),wf.applyMatrix4(r),Cf.multiplyScalar(1/Cf.w),wf.multiplyScalar(1/wf.w),Cf.x*=i.x/2,Cf.y*=i.y/2,wf.x*=i.x/2,wf.y*=i.y/2,Of.start.copy(Cf),Of.start.z=0,Of.end.copy(wf),Of.end.z=0;let o=Of.closestPointToPointParameter(Ef,!0);Of.at(o,kf);let l=ht.lerp(Cf.z,wf.z,o),d=l>=-1&&l<=1,f=Ef.distanceTo(kf)<Pf*.5;if(d&&f){Of.start.fromBufferAttribute(s,t),Of.end.fromBufferAttribute(c,t),Of.start.applyMatrix4(a),Of.end.applyMatrix4(a);let r=new R,i=new R;Nf.distanceSqToSegment(Of.start,Of.end,i,r),n.push({point:i,pointOnLine:r,distance:Nf.origin.distanceTo(i),object:e,face:null,faceIndex:t,uv:null,uv1:null})}}}var Rf=class extends U{constructor(e=new vf,t=new yf({color:Math.random()*16777215})){super(e,t),this.isLineSegments2=!0,this.type=`LineSegments2`}computeLineDistances(){let e=this.geometry,t=e.attributes.instanceStart,n=e.attributes.instanceEnd,r=new Float32Array(2*t.count);for(let e=0,i=0,a=t.count;e<a;e++,i+=2)xf.fromBufferAttribute(t,e),Sf.fromBufferAttribute(n,e),r[i]=i===0?0:r[i-1],r[i+1]=r[i]+xf.distanceTo(Sf);let i=new co(r,2,1);return e.setAttribute(`instanceDistanceStart`,new fi(i,1,0)),e.setAttribute(`instanceDistanceEnd`,new fi(i,1,1)),this}raycast(e,t){let n=this.material.worldUnits,r=e.camera;r===null&&!n&&console.error(`LineSegments2: "Raycaster.camera" needs to be set in order to raycast against LineSegments2 while worldUnits is set to false.`);let i=e.params.Line2===void 0?0:e.params.Line2.threshold||0;Nf=e.ray;let a=this.matrixWorld,o=this.geometry,s=this.material;Pf=s.linewidth+i,o.boundingSphere===null&&o.computeBoundingSphere(),jf.copy(o.boundingSphere).applyMatrix4(a);let c;if(c=n?Pf*.5:Ff(r,Math.max(r.near,jf.distanceToPoint(Nf.origin)),s.resolution),jf.radius+=c,Nf.intersectsSphere(jf)===!1)return;o.boundingBox===null&&o.computeBoundingBox(),Af.copy(o.boundingBox).applyMatrix4(a);let l;l=n?Pf*.5:Ff(r,Math.max(r.near,Af.distanceToPoint(Nf.origin)),s.resolution),Af.expandByScalar(l),Nf.intersectsBox(Af)!==!1&&(n?If(this,t):Lf(this,r,t))}onBeforeRender(e){let t=this.material.uniforms;t&&t.resolution&&(e.getViewport(bf),this.material.uniforms.resolution.value.set(bf.z,bf.w))}},zf={color:``,lineWidth:1,opacity:1,depthWrite:!0,transparent:!1},Bf=class e extends oi{constructor(t,n={}){super();let r={...zf,...n};for(let n of t.meshes){let t=e.expandIndexedPositions(n.vertices,n.indices),i=new vf;i.setPositions(t);let a=new yf({color:r.color||Wd.edgeColor.getHex(),linewidth:r.lineWidth,transparent:r.transparent||r.opacity<1,opacity:r.opacity,side:2,depthWrite:r.depthWrite,depthTest:r.depthWrite});Kd.register(a);let o=new Rf(i,a);o.userData.isEdgeLine=!0,n.edgeIndex!==void 0&&(o.userData.edgeIndex=n.edgeIndex),this.add(o)}}static expandIndexedPositions(e,t){let n=new Float32Array(t.length*3);for(let r=0;r<t.length;r++){let i=t[r]*3;n[r*3]=e[i],n[r*3+1]=e[i+1],n[r*3+2]=e[i+2]}return n}},Vf={color:``,opacity:1},Hf=class extends oi{constructor(e,t={}){super();let n={...Vf,...t};for(let r of e.meshes){let e=new H;e.setAttribute(`position`,new V(new Float32Array(r.vertices),3)),e.setAttribute(`normal`,new V(new Float32Array(r.normals),3));let i=r.vertices.length/3>65535?Uint32Array:Uint16Array;e.setIndex(new V(new i(r.indices),1)),e.computeBoundingBox();let a=t?.color??r.color??`#`+Wd.faceColor.getHexString(),o=t?.color!==void 0||t?.opacity!==void 0,s=new U(e,new va({color:a,transparent:o||n.opacity<1,opacity:n.opacity,depthWrite:!o,polygonOffset:!0,polygonOffsetFactor:o?-1:1,polygonOffsetUnits:1,side:2}));r.faceMapping&&(s.userData.faceMapping=r.faceMapping),this.add(s)}}},Uf=class extends oi{constructor(e,t){super();for(let n of e.meshes)if(n.label===`solid-faces`){let e=new Hf({shapeType:`face`,meshes:[n]},t?.face);e.renderOrder=1,this.add(e)}else if(n.label===`solid-edges`){let e=new Bf({shapeType:`edge`,meshes:[n]},t?.edge);e.renderOrder=2,this.add(e)}}},Wf=4,Gf=1.5,Kf=.6,qf=Wf+Gf+Kf+Gf,Jf=`
4645
4645
  attribute float lineDistance;
4646
4646
  varying float vLineDistance;
4647
4647
 
@@ -4649,7 +4649,7 @@ void main() {
4649
4649
  vLineDistance = lineDistance;
4650
4650
  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
4651
4651
  }
4652
- `,Pf=`
4652
+ `,Yf=`
4653
4653
  uniform vec3 color;
4654
4654
  uniform float dashLength;
4655
4655
  uniform float gapLength;
@@ -4674,7 +4674,7 @@ void main() {
4674
4674
 
4675
4675
  gl_FragColor = vec4(color, 1.0);
4676
4676
  }
4677
- `,Ff=class extends si{constructor(e){super(),this.userData.isMetaShape=!0;for(let t of e.meshes){let e=t.vertices,n=t.indices,r=[];for(let t=0;t<n.length;t+=2){let i=n[t]*3;r.push(e[i],e[i+1],e[i+2])}if(n.length>=2){let t=n[n.length-1]*3;r.push(e[t],e[t+1],e[t+2])}let i=new Or;i.setAttribute(`position`,new V(new Float32Array(r),3));let a=new Ki(i,new Xr({uniforms:{color:{value:Rd.metaEdgeColor},dashLength:{value:kf},gapLength:{value:Af},dotLength:{value:jf},patternLength:{value:Mf}},vertexShader:Nf,fragmentShader:Pf,side:2,transparent:!0,polygonOffset:!0,polygonOffsetFactor:2,polygonOffsetUnits:1}));a.computeLineDistances(),this.add(a)}}},If=`#2297ff`,Lf=2,Rf=class extends si{constructor(e){super(),this.userData.isMetaShape=!0;for(let t of e.meshes){let e=Tf.expandIndexedPositions(t.vertices,t.indices),n=new nf;n.setPositions(e);let r=new rf({color:If,linewidth:Lf,polygonOffset:!0,polygonOffsetFactor:-1,polygonOffsetUnits:-1,side:2,depthWrite:!0,depthTest:!0});Bd.register(r),this.add(new Cf(n,r))}}},zf=`#2297ff`,Bf=`#2297ff`,Vf=.15,Hf=.4,Uf=class extends si{constructor(e,t){super(),this.userData.isMetaShape=!0,this.userData.isPickRegion=!0,this.userData.isPickRegionSelected=t,e.metaData&&(this.userData.metaData=e.metaData);let n=t?Bf:zf,r=t?Hf:Vf;for(let t of e.meshes){let e=new Or;e.setAttribute(`position`,new V(new Float32Array(t.vertices),3)),e.setAttribute(`normal`,new V(new Float32Array(t.normals),3));let i=t.vertices.length/3>65535?Uint32Array:Uint16Array;e.setIndex(new V(new i(t.indices),1)),e.computeBoundingBox();let a=new H(e,new mr({color:n,transparent:!0,opacity:r,side:2,depthWrite:!1,polygonOffset:!0,polygonOffsetFactor:-1,polygonOffsetUnits:-1}));this.add(a)}}},Wf=new L;function Gf(e){e.getSize(Wf);let t=Wf.y;return t>0?t:e.domElement.clientHeight||1}function Kf(e,t){if(e instanceof La)return(e.top-e.bottom)/e.zoom;if(e instanceof ti){let n=e.position.distanceTo(t),r=e.fov*Math.PI/180;return 2*n*Math.tan(r/2)}return 1}function qf(e,t,n,r){let i=Gf(e),a=Kf(t,n);return r/i*a}function Jf(e,t,n,r,i){let a=qf(e,t,n,r)/i;return!Number.isFinite(a)||a<=0?1e-4:Math.min(Math.max(a,1e-4),1e6)}function Yf(e,t,n,r,i){e.onBeforeRender=(e,a,o)=>{t.scale.setScalar(Jf(e,o,n,r,i)),t.updateMatrixWorld(!0)}}var Xf=`#2297ff`,Zf=2,Qf=2,$f=16,ep=6,tp=1e-8,np=class extends si{constructor(e){super(),this.userData.isMetaShape=!0;let t=new ea(Qf,$f),n=new mr({color:Xf,side:2,depthTest:!0}),r=[];for(let t of e.meshes){let e=Tf.expandIndexedPositions(t.vertices,t.indices),n=new nf;n.setPositions(e);let i=new rf({color:Xf,linewidth:Zf,polygonOffset:!0,polygonOffsetFactor:-1,polygonOffsetUnits:-1,side:2,depthWrite:!0,depthTest:!0});Bd.register(i),this.add(new Cf(n,i));let a=t.vertices,o=t.indices,s=new Map;for(let e of o)s.set(e,(s.get(e)||0)+1);for(let[e,t]of s)if(t===1){let t=new R(a[e*3],a[e*3+1],a[e*3+2]);r.some(e=>e.distanceToSquared(t)<tp)||r.push(t)}}for(let e of r){let r=new H(t,n);r.renderOrder=2;let i=new si;i.renderOrder=2,i.userData.isVertexDot=!0,i.add(r),i.position.copy(e),Yf(r,i,e,ep,Qf),this.add(i)}}},rp={color:`#2297ff`,lineWidth:2},ip={trim:e=>new Rf(e),"pick-edge":e=>new np(e)};function ap(e){let t=e.metaType?ip[e.metaType]:void 0;return t?t(e):new Ff(e)}var op={"pick-region":e=>new Uf(e,!1),"pick-region-selected":e=>new Uf(e,!0)};function sp(e){let t=e.metaType?op[e.metaType]:void 0;return t?t(e):new Df(e)}var cp=class extends si{constructor(e,t,n){if(super(),!e.sceneShapes)return;let r=e.sceneShapes.every(e=>e.isMetaShape||e.shapeType===`wire`||e.shapeType===`edge`),i=[`pick-region`,`pick-region-selected`,`pick-edge`];for(let a of e.sceneShapes){if(!t&&a.isMetaShape&&a.metaType&&i.includes(a.metaType))continue;let e;if(a.isMetaShape)switch(a.shapeType){case`wire`:case`edge`:e=ap(a);break;case`face`:e=sp(a);break}else switch(a.shapeType){case`wire`:case`edge`:e=new Tf(a,n?.edge??(r?rp:void 0));break;case`face`:e=new Df(a,n?.face);break;case`solid`:e=new Of(a,n);break}e&&(a.shapeId&&(e.userData.shapeId=a.shapeId),this.add(e))}}},lp=new Set([`line-two-points`,`hline`,`vline`,`circle`,`arc`,`arc-from-center`,`tarc-to-point`,`tarc-to-point-tangent`,`tarc-with-tangent`,`tline`,`trim2d`,`rect`,`polygon`,`slot`]);function up(e){return e?e.startsWith(`bezier-`)?!0:lp.has(e):!1}function dp(e,t,n){let r=[],i=n.origin.x,a=n.origin.y,o=n.origin.z,s=n.xDirection.x,c=n.xDirection.y,l=n.xDirection.z,u=n.yDirection.x,d=n.yDirection.y,f=n.yDirection.z,p=e.some(e=>e.parentId===t&&e.sceneShapes.some(e=>e.metaType===`trim`));for(let n of e)if(n.parentId===t&&up(n.uniqueType))for(let e of n.sceneShapes){if(!e.shapeId)continue;if(p){if(e.metaType!==`trim`)continue}else if(e.isMetaShape||e.isGuide)continue;let t=[],n=[];for(let r of e.meshes){let e=r.vertices,p=r.indices;if(!p.length)continue;let m=new Map;for(let e of p)m.set(e,(m.get(e)||0)+1);for(let[t,r]of m)r===1&&n.push([e[t*3],e[t*3+1],e[t*3+2]]);for(let n=0;n<p.length;n+=2){let r=p[n]*3,m=p[n+1]*3,h=e[r]-i,g=e[r+1]-a,_=e[r+2]-o,v=h*s+g*c+_*l,y=h*u+g*d+_*f,b=e[m]-i,x=e[m+1]-a,S=e[m+2]-o,C=b*s+x*c+S*l,w=b*u+x*d+S*f;t.push({ax:v,ay:y,bx:C,by:w})}}t.length>0&&r.push({shapeId:e.shapeId,segments:t,endpoints:n})}return r}var fp=new Set([`arc`,`tarc-to-point`,`tarc-to-point-tangent`,`tarc-with-tangent`,`slot`]);function pp(e,t,n){let r=[],i=n.origin.x,a=n.origin.y,o=n.origin.z,s=n.xDirection.x,c=n.xDirection.y,l=n.xDirection.z,u=n.yDirection.x,d=n.yDirection.y,f=n.yDirection.z;for(let n of e){if(n.parentId!==t||!up(n.uniqueType))continue;let e=null;for(let t of n.sceneShapes)if(!t.isMetaShape&&t.shapeId){e=t.shapeId;break}if(!e)continue;let p=n.uniqueType??``;if(p.startsWith(`bezier-`)){let t=n.object?.startPoint,i=n.object?.resolvedPoints;if(t&&r.push({shapeId:e,point2d:[t[0],t[1]]}),i)for(let t of i)r.push({shapeId:e,point2d:[t[0],t[1]]});continue}if(fp.has(p)){for(let t of n.sceneShapes)if(t.isMetaShape){for(let n of t.meshes)if(n.vertices.length===3&&n.indices.length===0){let t=n.vertices[0]-i,p=n.vertices[1]-a,m=n.vertices[2]-o,h=t*s+p*c+m*l,g=t*u+p*d+m*f;r.push({shapeId:e,point2d:[h,g]})}}}}return r}function mp(e,t,n,r,i,a){return hp(e,t,n,r,i,a).dist}function hp(e,t,n,r,i,a){let o=i-n,s=a-r,c=o*o+s*s,l,u;if(c===0)l=n,u=r;else{let i=((e-n)*o+(t-r)*s)/c;i<0?i=0:i>1&&(i=1),l=n+i*o,u=r+i*s}let d=l-e,f=u-t;return{x:l,y:u,dist:Math.sqrt(d*d+f*f)}}function gp(e,t,n,r){let i=e.renderer.domElement.getBoundingClientRect(),a=(n-i.left)/i.width*2-1,o=-((r-i.top)/i.height)*2+1,s=e.createPickingRaycaster(a,o),c=s.ray.origin,l=s.ray.direction,u=xp(t.origin),d=xp(t.normal),f=l.dot(d);if(Math.abs(f)<1e-6)return null;let p=u.clone().sub(c).dot(d)/f;if(p<0)return null;let m=c.clone().add(l.clone().multiplyScalar(p)).clone().sub(u),h=xp(t.xDirection),g=xp(t.yDirection);return[m.dot(h),m.dot(g)]}function _p(e,t){let n=t.origin,r=t.xDirection,i=t.yDirection;return new R(n.x+r.x*e[0]+i.x*e[1],n.y+r.y*e[0]+i.y*e[1],n.z+r.z*e[0]+i.z*e[1])}function vp(e,t){let n=new R(e.x-t.origin.x,e.y-t.origin.y,e.z-t.origin.z),r=xp(t.xDirection),i=xp(t.yDirection);return[n.dot(r),n.dot(i)]}function J(e){return[Math.round(e[0]*100)/100,Math.round(e[1]*100)/100]}function yp(e,t){let n=e.camera,r=e.renderer.domElement.getBoundingClientRect().height||1,i,a=n;if(a.isOrthographicCamera)i=(a.top-a.bottom)/(a.zoom||1);else{let t=new R;e.cameraControls.getTarget(t);let r=n.position.distanceTo(t),o=a.fov*Math.PI/180;i=2*r*Math.tan(o/2)}return i/r*t}function bp(e,t){let n=e[0]-t[0],r=e[1]-t[1];return Math.sqrt(n*n+r*r)}function xp(e){return new R(e.x,e.y,e.z)}var Sp={hline:`H`,vline:`V`,"tarc-to-point":`T`,"tarc-to-point-tangent":`T`,"tarc-with-tangent":`T`},Cp=new Set([`tarc-to-point`,`tarc-to-point-tangent`,`tarc-with-tangent`]),wp=22,Tp=5,Ep=16,Dp=64,Op=3,kp=new Map;function Ap(e,t){let n=`${e}|${t}`,r=kp.get(n);if(r)return r;let i=document.createElement(`canvas`);i.width=Dp,i.height=Dp;let a=i.getContext(`2d`),o=Dp-8,s=Dp-8;a.beginPath(),a.moveTo(14,4),a.lineTo(4+o-10,4),a.quadraticCurveTo(4+o,4,4+o,14),a.lineTo(4+o,4+s-10),a.quadraticCurveTo(4+o,4+s,4+o-10,4+s),a.lineTo(14,4+s),a.quadraticCurveTo(4,4+s,4,4+s-10),a.lineTo(4,14),a.quadraticCurveTo(4,4,14,4),a.closePath(),a.lineWidth=4,a.strokeStyle=t,a.stroke(),a.fillStyle=t,a.font=`${Dp*.55}px sans-serif`,a.textAlign=`center`,a.textBaseline=`middle`,a.fillText(e,Dp/2,Dp/2);let c=new Zi(i);return kp.set(n,c),c}function jp(e,t,n){let r=[],i=0;for(let t of e.meshes){let e=t.vertices,n=t.indices;for(let t=0;t<n.length;t+=2){let a=n[t]*3,o=n[t+1]*3,s=new R(e[a],e[a+1],e[a+2]),c=new R(e[o],e[o+1],e[o+2]),l=s.distanceTo(c);r.push({from:s,to:c,length:l}),i+=l}}if(i<1e-10||r.length===0)return null;let a=i*Math.max(0,Math.min(1,t)),o=0;for(let e of r){if(o+e.length>=a||e===r[r.length-1]){let t=e.length>1e-10?(a-o)/e.length:0,r=e.from.clone().lerp(e.to,t),i=vp(e.from,n),s=vp(e.to,n),c=s[0]-i[0],l=s[1]-i[1],u=Math.sqrt(c*c+l*l);return{position:r,tangent2d:u>1e-10?[c/u,l/u]:[1,0]}}o+=e.length}return null}function Mp(e,t,n,r,i){let a=Ap(e,`#${Rd.constraintColor.getHexString()}`),o=new H(new ca(Tp,Tp),new mr({map:a,transparent:!0,depthTest:!1,side:2}));o.renderOrder=Op;let s=new si;s.renderOrder=Op,s.userData.isConstraintIcon=!0;let c=new R(r.xDirection.x*n[0]+r.yDirection.x*n[1],r.xDirection.y*n[0]+r.yDirection.y*n[1],r.xDirection.z*n[0]+r.yDirection.z*n[1]);return s.position.copy(t),s.up.set(r.yDirection.x,r.yDirection.y,r.yDirection.z),s.lookAt(new R(t.x+i.x,t.y+i.y,t.z+i.z)),s.add(o),o.onBeforeRender=(e,n,r)=>{let i=qf(e,r,t,wp);s.position.set(t.x+c.x*i,t.y+c.y*i,t.z+c.z*i),s.scale.setScalar(Jf(e,r,t,Ep,Tp)),s.updateMatrixWorld(!0)},s}function Np(e,t){let n=e.object?.plane?.normal,r=e.object?.plane;if(!n||!r)return[];let i=[];for(let a of t){if(a.parentId!==e.id||!a.sceneShapes.length)continue;let t=Sp[a.uniqueType??``];if(!t)continue;let o=Cp.has(a.uniqueType??``);for(let e of a.sceneShapes){if(e.isMetaShape||e.isGuide)continue;let a=jp(e,o?0:.5,r);if(!a)continue;let s=[-a.tangent2d[1],a.tangent2d[0]];i.push(Mp(t,a.position,s,r,n))}}return i}var Pp=`#2297ff`,Fp=`#6a5acd`,Ip=2,Lp=16,Rp=6,zp=`#8899aa`,Bp=1.5,Vp=4.5,Hp=15954511,Up=64,Wp=3,Gp=9,Kp=15954511,qp=.35,Jp=.6,Yp=18,Xp=5,Zp=2.5,Qp=Yp+Xp,$p=54,em=class extends si{constructor(e,t,n,r){super(),this.userData.isSketchRoot=!0,this.buildEdges(e,t),this.buildVertices(e,t),this.addConstraintIcons(e,t),n&&e.id===n&&(this.buildCursor(e),this.buildTangentArrow(e))}buildEdges(e,t){for(let n of t){if(n.parentId!==e.id||!n.sceneShapes.length)continue;let t=up(n.uniqueType)?Pp:Fp;for(let e of n.sceneShapes){if(e.isMetaShape||e.isGuide){if(e.shapeType===`wire`||e.shapeType===`edge`){let t=ap(e);t.traverse(e=>{e.renderOrder=1}),e.shapeId&&(t.userData.shapeId=e.shapeId),this.add(t)}continue}let n=new Tf(e,{color:t,lineWidth:2,depthWrite:!1,transparent:!0});n.traverse(e=>{e.renderOrder=1}),e.shapeId&&(n.userData.shapeId=e.shapeId),this.add(n)}}}buildVertices(e,t){let n=e.object?.plane?.normal,r=[],i=[],a=[];for(let n of t){if(n.parentId!==e.id||!n.sceneShapes.length)continue;let t=up(n.uniqueType);for(let e of n.sceneShapes){if(e.isGuide)continue;if(e.isMetaShape){for(let t of e.meshes)t.vertices.length===3&&t.indices.length===0&&a.push(new R(t.vertices[0],t.vertices[1],t.vertices[2]));continue}let n=t?r:i;for(let t of e.meshes){if(!t.indices.length)continue;let e=new Map;for(let n of t.indices)e.set(n,(e.get(n)||0)+1);for(let[r,i]of e)i===1&&n.push(new R(t.vertices[r*3],t.vertices[r*3+1],t.vertices[r*3+2]))}}}let o=1e-12,s=this.dedup(r,o),c=this.dedup(i,o),l=this.dedup(a,o);this.addVertexDots(s,n,Ip,Rp,Pp,1),this.addVertexDots(c,n,Ip,Rp,Fp,1),this.addVertexDots(l,n,Bp,Vp,zp,.5)}addConstraintIcons(e,t){for(let n of Np(e,t))this.add(n)}dedup(e,t){let n=[];for(let r of e)n.some(e=>e.distanceToSquared(r)<t)||n.push(r);return n}addVertexDots(e,t,n,r,i,a){let o=new ea(n,Lp),s=new mr({color:i,side:2,depthTest:!1,transparent:!0,opacity:a});for(let i of e){let e=new H(o,s);e.renderOrder=2;let a=new si;a.renderOrder=2,a.userData.isVertexDot=!0,a.add(e),a.position.copy(i),t&&a.lookAt(new R(i.x+t.x,i.y+t.y,i.z+t.z)),Yf(e,a,i,r,n),this.add(a)}}buildCursor(e){let t=e.object?.currentPosition;if(!t)return;let n=new ea(Wp,Up),r=new mr({color:Hp,side:2,depthTest:!1});r.transparent=!0,r.opacity=.8;let i=new H(n,r);i.renderOrder=1;let a=new si;a.renderOrder=1,a.add(i),a.position.set(t.x,t.y,t.z);let o=e.object?.plane?.normal;if(o){let e=new R(t.x+o.x,t.y+o.y,t.z+o.z);a.lookAt(e)}Yf(i,a,a.position,Gp,Wp),this.add(a)}buildTangentArrow(e){let t=e.object?.currentPosition,n=e.object?.currentTangent,r=e.object?.plane?.origin;if(!t||!n||!r)return;let i=new R(n.x-r.x,n.y-r.y,n.z-r.z).normalize(),a=new mr({color:Kp,transparent:!0,opacity:qp,side:2,depthTest:!1,depthWrite:!1}),o=new ta(Jp,Jp,Yp,16);o.translate(0,Yp/2,0);let s=new H(o,a),c=new na(Zp,Xp,16);c.translate(0,Yp+Xp/2,0);let l=new H(c,a),u=new si;u.renderOrder=1,u.add(s),u.add(l);let d=new R(0,1,0),f=new gt().setFromUnitVectors(d,i);u.quaternion.copy(f),u.position.set(t.x,t.y,t.z),Yf(s,u,u.position,$p,Qp),this.add(u)}},tm=`#ffc26c`,nm=`#c88f40`,rm=`#c88f40`,im=.1,am=20,om=3,sm=1.5,cm=.4,lm=96,um=class extends si{constructor(e,t){super();let n=e.sceneShapes[0]?.meshes[0];if(!n)return;this.userData.isMetaShape=!0,this.userData.isConstructionPlane=!0;let r=e.object.normal,i=e.object.center,a=new Or;a.setAttribute(`position`,new V(new Float32Array(n.vertices),3)),a.setAttribute(`normal`,new V(new Float32Array(n.normals),3)),a.setIndex(new V(new Uint16Array(n.indices),1)),a.computeBoundingBox();let o=new H(a,new mr({color:tm,transparent:!0,opacity:im,side:2,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}));this.add(o);let s=new Xi(new sa(a,18),new Ri({color:nm,linewidth:1}));this.add(s);let c=new R(r.x,r.y,r.z).normalize(),l=new R(i.x,i.y,i.z),u=new mr({color:rm}),d=am-om,f=new ta(cm,cm,d,8);f.translate(0,d/2,0);let p=new H(f,u),m=new na(sm,om,8);m.translate(0,d+om/2,0);let h=new H(m,u),g=new si;g.add(p),g.add(h);let _=new R(0,1,0),v=new gt().setFromUnitVectors(_,c);g.quaternion.copy(v),g.position.copy(l),Yf(p,g,g.position,lm,am),this.add(g),this.position.z=.01}},dm=`#c88f40`,fm=class extends si{constructor(e){super();let t=e.sceneShapes[0]?.meshes[0];if(!t)return;let n=new Or;n.setAttribute(`position`,new V(new Float32Array(t.vertices),3));let r=new Xi(n,new ha({color:dm,dashSize:5,gapSize:5}));r.computeLineDistances(),this.add(r)}};function pm(){let e=`#`+Rd.selectEdgeColor.getHexString(),t=`#`+Rd.selectFaceColor.getHexString();return{edge:{color:e,lineWidth:3,depthWrite:!1},face:{color:t,opacity:1}}}function mm(e,t){if(t)return t;if(e===`select`)return pm()}function hm(e,t,n,r,i,a){switch(e.type){case`sketch`:return new em(e,t,n,r);case`plane`:return new um(e,r);case`axis`:return new fm(e)}let o=e.uniqueType===`select`,s=mm(e.uniqueType,a),c=t.filter(t=>t.parentId===e.id),l;if(c.length>0){let e=new si;for(let a of c)e.add(hm(a,t,n,r,i,s));l=e}else l=new cp(e,i,s);return o&&l.traverse(e=>{e.renderOrder=999}),l}function gm(e,t,n,r=!1){let i=new si;i.name=`compiledMesh`;for(let a of e)a.parentId||!a.visible&&!(t&&a.type===`sketch`)||i.add(hm(a,e,t,n,r));return i}var _m={"Content-Type":`application/json`};function vm(e,t){fetch(e,{method:`POST`,headers:t===void 0?void 0:_m,body:t===void 0?void 0:JSON.stringify(t)}).catch(t=>console.error(`POST ${e} failed:`,t))}async function ym(e,t,n){try{let r=await fetch(e,{method:`POST`,headers:_m,body:JSON.stringify(t),signal:n});return r.ok?await r.json():null}catch(t){return t?.name!==`AbortError`&&console.error(`POST ${e} failed:`,t),null}}async function bm(e,t,n){try{let r=e;if(t){let e=new URLSearchParams;for(let[n,r]of Object.entries(t))e.set(n,String(r));r+=`?`+e.toString()}let i=await fetch(r,{signal:n});return i.ok?await i.json():null}catch(t){return t?.name!==`AbortError`&&console.error(`GET ${e} failed:`,t),null}}function xm(e,t){vm(`/api/insert-point`,{point:e,sourceLocation:t})}function Sm(e,t){vm(`/api/set-pick-points`,{points:e,sourceLocation:t})}function Cm(e){vm(`/api/add-pick`,{sourceLocation:e})}function wm(e){vm(`/api/remove-pick`,{sourceLocation:e})}function Tm(e,t,n){vm(`/api/insert-geometry`,{statement:e,sketchSourceLocation:t,newVariable:n??null})}function Em(e,t,n){vm(`/api/set-line-position`,{newStart:e,newEnd:t,sourceLocation:n})}function Dm(e,t,n){vm(`/api/update-position`,{newPosition:e,sourceLocation:t,pointIndex:n})}function Om(e,t){vm(`/api/set-chain-positions`,{updates:e,sourceLocation:t})}function km(e,t,n,r){vm(`/api/set-rect-dimensions`,{width:e,height:t,sourceLocation:n,startPoint:r??null})}function Am(e,t,n,r,i){vm(`/api/update-dimension-expression`,{expression:e,sourceLocation:t,sketchSourceLine:n,newVariable:r??null,dimensionOffset:i??0})}async function jm(e){return await ym(`/api/dimension-expression`,{sourceLine:e})??{expression:null}}async function Mm(e){return(await ym(`/api/scope-variables`,{sketchSourceLine:e}))?.variables??[]}function Nm(e,t,n){return bm(`/api/face-properties`,{shapeId:e,faceIndex:t},n)}function Pm(e,t,n){return bm(`/api/edge-properties`,{shapeId:e,edgeIndex:t},n)}function Fm(e){return bm(`/api/shape-properties`,{shapeId:e})}function Im(){return bm(`/api/materials`)}function Lm(){vm(`/api/recompute`)}function Rm(e){vm(`/api/rollback`,{index:e})}function zm(e){vm(`/api/add-breakpoint`,{sourceLocation:e})}function Bm(){vm(`/api/clear-breakpoints`)}function Vm(e){vm(`/api/code/goto-source`,e)}async function Hm(e,t){return await ym(`/api/import-file`,{fileName:e,data:t})??{success:!1,error:`Network error`}}async function Um(e){let t=await fetch(`/api/export`,{method:`POST`,headers:_m,body:JSON.stringify(e)});if(!t.ok){let e=await t.json();throw Error(e.error||`Export failed`)}return t.blob()}async function Wm(){return bm(`/api/preferences`)}function Gm(e,t){vm(`/api/preferences`,{[e]:t})}var Km=`<svg
4677
+ `,Xf=class extends oi{constructor(e){super(),this.userData.isMetaShape=!0;for(let t of e.meshes){let e=t.vertices,n=t.indices,r=[];for(let t=0;t<n.length;t+=2){let i=n[t]*3;r.push(e[i],e[i+1],e[i+2])}if(n.length>=2){let t=n[n.length-1]*3;r.push(e[t],e[t+1],e[t+2])}let i=new H;i.setAttribute(`position`,new V(new Float32Array(r),3));let a=new Gi(i,new Yr({uniforms:{color:{value:Wd.metaEdgeColor},dashLength:{value:Wf},gapLength:{value:Gf},dotLength:{value:Kf},patternLength:{value:qf}},vertexShader:Jf,fragmentShader:Yf,side:2,transparent:!0,polygonOffset:!0,polygonOffsetFactor:2,polygonOffsetUnits:1}));a.computeLineDistances(),this.add(a)}}},Zf=`#2297ff`,Qf=2,$f=class extends oi{constructor(e){super(),this.userData.isMetaShape=!0;for(let t of e.meshes){let e=Bf.expandIndexedPositions(t.vertices,t.indices),n=new vf;n.setPositions(e);let r=new yf({color:Zf,linewidth:Qf,polygonOffset:!0,polygonOffsetFactor:-1,polygonOffsetUnits:-1,side:2,depthWrite:!0,depthTest:!0});Kd.register(r),this.add(new Rf(n,r))}}},ep=`#2297ff`,tp=`#2297ff`,np=.15,rp=.4,ip=class extends oi{constructor(e,t){super(),this.userData.isMetaShape=!0,this.userData.isPickRegion=!0,this.userData.isPickRegionSelected=t,e.metaData&&(this.userData.metaData=e.metaData);let n=t?tp:ep,r=t?rp:np;for(let t of e.meshes){let e=new H;e.setAttribute(`position`,new V(new Float32Array(t.vertices),3)),e.setAttribute(`normal`,new V(new Float32Array(t.normals),3));let i=t.vertices.length/3>65535?Uint32Array:Uint16Array;e.setIndex(new V(new i(t.indices),1)),e.computeBoundingBox();let a=new U(e,new mr({color:n,transparent:!0,opacity:r,side:2,depthWrite:!1,polygonOffset:!0,polygonOffsetFactor:-1,polygonOffsetUnits:-1}));this.add(a)}}},ap=`#2297ff`,op=2,sp=2,cp=16,lp=6,up=1e-8,dp=class extends oi{constructor(e){super(),this.userData.isMetaShape=!0;let t=new oa(sp,cp),n=new mr({color:ap,side:2,depthTest:!0}),r=[];for(let t of e.meshes){let e=Bf.expandIndexedPositions(t.vertices,t.indices),n=new vf;n.setPositions(e);let i=new yf({color:ap,linewidth:op,polygonOffset:!0,polygonOffsetFactor:-1,polygonOffsetUnits:-1,side:2,depthWrite:!0,depthTest:!0});Kd.register(i),this.add(new Rf(n,i));let a=t.vertices,o=t.indices,s=new Map;for(let e of o)s.set(e,(s.get(e)||0)+1);for(let[e,t]of s)if(t===1){let t=new R(a[e*3],a[e*3+1],a[e*3+2]);r.some(e=>e.distanceToSquared(t)<up)||r.push(t)}}for(let e of r){let r=new U(t,n);r.renderOrder=2;let i=new oi;i.renderOrder=2,i.userData.isVertexDot=!0,i.add(r),i.position.copy(e),tf(r,i,e,lp,sp),this.add(i)}}},fp={color:`#2297ff`,lineWidth:2},pp={trim:e=>new $f(e),"pick-edge":e=>new dp(e)};function mp(e){let t=e.metaType?pp[e.metaType]:void 0;return t?t(e):new Xf(e)}var hp={"pick-region":e=>new ip(e,!1),"pick-region-selected":e=>new ip(e,!0)};function gp(e){let t=e.metaType?hp[e.metaType]:void 0;return t?t(e):new Hf(e)}var _p=class extends oi{constructor(e,t,n){if(super(),!e.sceneShapes)return;let r=e.sceneShapes.every(e=>e.isMetaShape||e.shapeType===`wire`||e.shapeType===`edge`),i=[`pick-region`,`pick-region-selected`,`pick-edge`];for(let a of e.sceneShapes){if(!t&&a.isMetaShape&&a.metaType&&i.includes(a.metaType))continue;let e;if(a.isMetaShape)switch(a.shapeType){case`wire`:case`edge`:e=mp(a);break;case`face`:e=gp(a);break}else switch(a.shapeType){case`wire`:case`edge`:e=new Bf(a,n?.edge??(r?fp:void 0));break;case`face`:e=new Hf(a,n?.face);break;case`solid`:e=new Uf(a,n);break}e&&(a.shapeId&&(e.userData.shapeId=a.shapeId),this.add(e))}}},vp=new Set([`line-two-points`,`hline`,`vline`,`circle`,`arc`,`arc-from-center`,`tarc-to-point`,`tarc-to-point-tangent`,`tarc-with-tangent`,`tline`,`trim2d`,`rect`,`polygon`,`slot`]);function yp(e){return e?e.startsWith(`bezier-`)?!0:vp.has(e):!1}function bp(e,t,n){let r=[],i=n.origin.x,a=n.origin.y,o=n.origin.z,s=n.xDirection.x,c=n.xDirection.y,l=n.xDirection.z,u=n.yDirection.x,d=n.yDirection.y,f=n.yDirection.z,p=e.some(e=>e.parentId===t&&e.sceneShapes.some(e=>e.metaType===`trim`));for(let n of e)if(n.parentId===t&&yp(n.uniqueType))for(let e of n.sceneShapes){if(!e.shapeId)continue;if(p){if(e.metaType!==`trim`)continue}else if(e.isMetaShape||e.isGuide)continue;let t=[],n=[];for(let r of e.meshes){let e=r.vertices,p=r.indices;if(!p.length)continue;let m=new Map;for(let e of p)m.set(e,(m.get(e)||0)+1);for(let[t,r]of m)r===1&&n.push([e[t*3],e[t*3+1],e[t*3+2]]);for(let n=0;n<p.length;n+=2){let r=p[n]*3,m=p[n+1]*3,h=e[r]-i,g=e[r+1]-a,_=e[r+2]-o,v=h*s+g*c+_*l,y=h*u+g*d+_*f,b=e[m]-i,x=e[m+1]-a,S=e[m+2]-o,C=b*s+x*c+S*l,w=b*u+x*d+S*f;t.push({ax:v,ay:y,bx:C,by:w})}}t.length>0&&r.push({shapeId:e.shapeId,segments:t,endpoints:n})}return r}var xp=new Set([`arc`,`tarc-to-point`,`tarc-to-point-tangent`,`tarc-with-tangent`,`slot`]);function Sp(e,t,n){let r=[],i=n.origin.x,a=n.origin.y,o=n.origin.z,s=n.xDirection.x,c=n.xDirection.y,l=n.xDirection.z,u=n.yDirection.x,d=n.yDirection.y,f=n.yDirection.z;for(let n of e){if(n.parentId!==t||!yp(n.uniqueType))continue;let e=null;for(let t of n.sceneShapes)if(!t.isMetaShape&&t.shapeId){e=t.shapeId;break}if(!e)continue;let p=n.uniqueType??``;if(p.startsWith(`bezier-`)){let t=n.object?.startPoint,i=n.object?.resolvedPoints;if(t&&r.push({shapeId:e,point2d:[t[0],t[1]]}),i)for(let t of i)r.push({shapeId:e,point2d:[t[0],t[1]]});continue}if(xp.has(p)){for(let t of n.sceneShapes)if(t.isMetaShape){for(let n of t.meshes)if(n.vertices.length===3&&n.indices.length===0){let t=n.vertices[0]-i,p=n.vertices[1]-a,m=n.vertices[2]-o,h=t*s+p*c+m*l,g=t*u+p*d+m*f;r.push({shapeId:e,point2d:[h,g]})}}}}return r}function Cp(e,t,n,r,i,a){return wp(e,t,n,r,i,a).dist}function wp(e,t,n,r,i,a){let o=i-n,s=a-r,c=o*o+s*s,l,u;if(c===0)l=n,u=r;else{let i=((e-n)*o+(t-r)*s)/c;i<0?i=0:i>1&&(i=1),l=n+i*o,u=r+i*s}let d=l-e,f=u-t;return{x:l,y:u,dist:Math.sqrt(d*d+f*f)}}function Tp(e,t,n,r){let i=e.renderer.domElement.getBoundingClientRect(),a=(n-i.left)/i.width*2-1,o=-((r-i.top)/i.height)*2+1,s=e.createPickingRaycaster(a,o),c=s.ray.origin,l=s.ray.direction,u=jp(t.origin),d=jp(t.normal),f=l.dot(d);if(Math.abs(f)<1e-6)return null;let p=u.clone().sub(c).dot(d)/f;if(p<0)return null;let m=c.clone().add(l.clone().multiplyScalar(p)).clone().sub(u),h=jp(t.xDirection),g=jp(t.yDirection);return[m.dot(h),m.dot(g)]}function Ep(e,t){let n=t.origin,r=t.xDirection,i=t.yDirection;return new R(n.x+r.x*e[0]+i.x*e[1],n.y+r.y*e[0]+i.y*e[1],n.z+r.z*e[0]+i.z*e[1])}function Dp(e,t,n){let r=Ep(n,t).project(e.camera),i=e.renderer.domElement.getBoundingClientRect();return{clientX:(r.x+1)/2*i.width+i.left,clientY:(1-r.y)/2*i.height+i.top}}function Op(e,t){let n=new R(e.x-t.origin.x,e.y-t.origin.y,e.z-t.origin.z),r=jp(t.xDirection),i=jp(t.yDirection);return[n.dot(r),n.dot(i)]}function Y(e){return[Math.round(e[0]*100)/100,Math.round(e[1]*100)/100]}function kp(e,t){let n=e.camera,r=e.renderer.domElement.getBoundingClientRect().height||1,i,a=n;if(a.isOrthographicCamera)i=(a.top-a.bottom)/(a.zoom||1);else{let t=new R;e.cameraControls.getTarget(t);let r=n.position.distanceTo(t),o=a.fov*Math.PI/180;i=2*r*Math.tan(o/2)}return i/r*t}function Ap(e,t){let n=e[0]-t[0],r=e[1]-t[1];return Math.sqrt(n*n+r*r)}function jp(e){return new R(e.x,e.y,e.z)}var Mp={hline:`H`,vline:`V`,"tarc-to-point":`T`,"tarc-to-point-tangent":`T`,"tarc-with-tangent":`T`},Np=new Set([`tarc-to-point`,`tarc-to-point-tangent`,`tarc-with-tangent`]),Pp=22,Fp=5,Ip=16,Lp=64,Rp=3,zp=new Map;function Bp(e,t){let n=`${e}|${t}`,r=zp.get(n);if(r)return r;let i=document.createElement(`canvas`);i.width=Lp,i.height=Lp;let a=i.getContext(`2d`),o=Lp-8,s=Lp-8;a.beginPath(),a.moveTo(14,4),a.lineTo(4+o-10,4),a.quadraticCurveTo(4+o,4,4+o,14),a.lineTo(4+o,4+s-10),a.quadraticCurveTo(4+o,4+s,4+o-10,4+s),a.lineTo(14,4+s),a.quadraticCurveTo(4,4+s,4,4+s-10),a.lineTo(4,14),a.quadraticCurveTo(4,4,14,4),a.closePath(),a.lineWidth=4,a.strokeStyle=t,a.stroke(),a.fillStyle=t,a.font=`${Lp*.55}px sans-serif`,a.textAlign=`center`,a.textBaseline=`middle`,a.fillText(e,Lp/2,Lp/2);let c=new ra(i);return zp.set(n,c),c}function Vp(e,t,n){let r=[],i=0;for(let t of e.meshes){let e=t.vertices,n=t.indices;for(let t=0;t<n.length;t+=2){let a=n[t]*3,o=n[t+1]*3,s=new R(e[a],e[a+1],e[a+2]),c=new R(e[o],e[o+1],e[o+2]),l=s.distanceTo(c);r.push({from:s,to:c,length:l}),i+=l}}if(i<1e-10||r.length===0)return null;let a=i*Math.max(0,Math.min(1,t)),o=0;for(let e of r){if(o+e.length>=a||e===r[r.length-1]){let t=e.length>1e-10?(a-o)/e.length:0,r=e.from.clone().lerp(e.to,t),i=Op(e.from,n),s=Op(e.to,n),c=s[0]-i[0],l=s[1]-i[1],u=Math.sqrt(c*c+l*l);return{position:r,tangent2d:u>1e-10?[c/u,l/u]:[1,0]}}o+=e.length}return null}function Hp(e,t,n,r,i){let a=Bp(e,`#${Wd.constraintColor.getHexString()}`),o=new U(new ma(Fp,Fp),new mr({map:a,transparent:!0,depthTest:!1,side:2}));o.renderOrder=Rp;let s=new oi;s.renderOrder=Rp,s.userData.isConstraintIcon=!0;let c=new R(r.xDirection.x*n[0]+r.yDirection.x*n[1],r.xDirection.y*n[0]+r.yDirection.y*n[1],r.xDirection.z*n[0]+r.yDirection.z*n[1]);return s.position.copy(t),s.up.set(r.yDirection.x,r.yDirection.y,r.yDirection.z),s.lookAt(new R(t.x+i.x,t.y+i.y,t.z+i.z)),s.add(o),o.onBeforeRender=(e,n,r)=>{let i=Xd(e,r,t,Pp);s.position.set(t.x+c.x*i,t.y+c.y*i,t.z+c.z*i),s.scale.setScalar(Zd(e,r,t,Ip,Fp)),s.updateMatrixWorld(!0)},s}function Up(e,t){let n=e.object?.plane?.normal,r=e.object?.plane;if(!n||!r)return[];let i=[];for(let a of t){if(a.parentId!==e.id||!a.sceneShapes.length)continue;let t=Mp[a.uniqueType??``];if(!t)continue;let o=Np.has(a.uniqueType??``);for(let e of a.sceneShapes){if(e.isMetaShape||e.isGuide)continue;let a=Vp(e,o?0:.5,r);if(!a)continue;let s=[-a.tangent2d[1],a.tangent2d[0]];i.push(Hp(t,a.position,s,r,n))}}return i}var Wp=`#2297ff`,Gp=`#6a5acd`,Kp=2,qp=16,Jp=6,Yp=3,Xp=.6,Zp=`#8899aa`,Qp=1.5,$p=4.5,em=15954511,tm=64,nm=3,rm=9,im=15954511,am=.35,om=.6,sm=18,cm=5,lm=2.5,um=sm+cm,dm=54,fm=class extends oi{constructor(e,t,n,r){super(),this.userData.isSketchRoot=!0,this.buildEdges(e,t),this.buildVertices(e,t),this.addConstraintIcons(e,t),n&&e.id===n&&(this.buildCursor(e),this.buildTangentArrow(e))}buildEdges(e,t){for(let n of t){if(n.parentId!==e.id||!n.sceneShapes.length)continue;let t=yp(n.uniqueType)?Wp:Gp;for(let e of n.sceneShapes){if(e.isMetaShape||e.isGuide){if(e.shapeType===`wire`||e.shapeType===`edge`){let t=mp(e);t.traverse(e=>{e.renderOrder=1}),e.shapeId&&(t.userData.shapeId=e.shapeId),this.add(t)}continue}let n=new Bf(e,{color:t,lineWidth:2,depthWrite:!1,transparent:!0});n.traverse(e=>{e.renderOrder=1}),e.shapeId&&(n.userData.shapeId=e.shapeId),this.add(n)}}}buildVertices(e,t){let n=e.object?.plane?.normal,r=[],i=[],a=[];for(let n of t){if(n.parentId!==e.id||!n.sceneShapes.length)continue;let t=yp(n.uniqueType);for(let e of n.sceneShapes){if(e.isGuide)continue;if(e.isMetaShape){for(let t of e.meshes)t.vertices.length===3&&t.indices.length===0&&a.push(new R(t.vertices[0],t.vertices[1],t.vertices[2]));continue}let n=t?r:i;for(let t of e.meshes){if(!t.indices.length)continue;let e=new Map;for(let n of t.indices)e.set(n,(e.get(n)||0)+1);for(let[r,i]of e)i===1&&n.push(new R(t.vertices[r*3],t.vertices[r*3+1],t.vertices[r*3+2]))}}}let o=1e-12,s=this.dedup(r,o),c=this.dedup(i,o),l=this.dedup(a,o);this.addVertexDots(s,n,Kp,Jp,Wp,1),this.addVertexDots(c,n,Kp,Yp,Gp,Xp),this.addVertexDots(l,n,Qp,$p,Zp,.5)}addConstraintIcons(e,t){for(let n of Up(e,t))this.add(n)}dedup(e,t){let n=[];for(let r of e)n.some(e=>e.distanceToSquared(r)<t)||n.push(r);return n}addVertexDots(e,t,n,r,i,a){let o=new oa(n,qp),s=new mr({color:i,side:2,depthTest:!1,transparent:!0,opacity:a});for(let i of e){let e=new U(o,s);e.renderOrder=2;let a=new oi;a.renderOrder=2,a.userData.isVertexDot=!0,a.add(e),a.position.copy(i),t&&a.lookAt(new R(i.x+t.x,i.y+t.y,i.z+t.z)),tf(e,a,i,r,n),this.add(a)}}buildCursor(e){let t=e.object?.currentPosition;if(!t)return;let n=new oa(nm,tm),r=new mr({color:em,side:2,depthTest:!1});r.transparent=!0,r.opacity=.8;let i=new U(n,r);i.renderOrder=1;let a=new oi;a.renderOrder=1,a.add(i),a.position.set(t.x,t.y,t.z);let o=e.object?.plane?.normal;if(o){let e=new R(t.x+o.x,t.y+o.y,t.z+o.z);a.lookAt(e)}tf(i,a,a.position,rm,nm),this.add(a)}buildTangentArrow(e){let t=e.object?.currentPosition,n=e.object?.currentTangent,r=e.object?.plane?.origin;if(!t||!n||!r)return;let i=new R(n.x-r.x,n.y-r.y,n.z-r.z).normalize(),a=new mr({color:im,transparent:!0,opacity:am,side:2,depthTest:!1,depthWrite:!1}),o=new sa(om,om,sm,16);o.translate(0,sm/2,0);let s=new U(o,a),c=new ca(lm,cm,16);c.translate(0,sm+cm/2,0);let l=new U(c,a),u=new oi;u.renderOrder=1,u.add(s),u.add(l);let d=new R(0,1,0),f=new gt().setFromUnitVectors(d,i);u.quaternion.copy(f),u.position.set(t.x,t.y,t.z),tf(s,u,u.position,dm,um),this.add(u)}},pm=`#ffc26c`,mm=`#c88f40`,hm=`#c88f40`,gm=.1,_m=20,vm=3,ym=1.5,bm=.4,xm=96,Sm=class extends oi{constructor(e,t){super();let n=e.sceneShapes[0]?.meshes[0];if(!n)return;this.userData.isMetaShape=!0,this.userData.isConstructionPlane=!0;let r=e.object.normal,i=e.object.center,a=new H;a.setAttribute(`position`,new V(new Float32Array(n.vertices),3)),a.setAttribute(`normal`,new V(new Float32Array(n.normals),3)),a.setIndex(new V(new Uint16Array(n.indices),1)),a.computeBoundingBox();let o=new U(a,new mr({color:pm,transparent:!0,opacity:gm,side:2,polygonOffset:!0,polygonOffsetFactor:1,polygonOffsetUnits:1}));this.add(o);let s=new Yi(new pa(a,18),new Li({color:mm,linewidth:1}));this.add(s);let c=new R(r.x,r.y,r.z).normalize(),l=new R(i.x,i.y,i.z),u=new mr({color:hm}),d=_m-vm,f=new sa(bm,bm,d,8);f.translate(0,d/2,0);let p=new U(f,u),m=new ca(ym,vm,8);m.translate(0,d+vm/2,0);let h=new U(m,u),g=new oi;g.add(p),g.add(h);let _=new R(0,1,0),v=new gt().setFromUnitVectors(_,c);g.quaternion.copy(v),g.position.copy(l),tf(p,g,g.position,xm,_m),this.add(g),this.position.z=.01}},Cm=`#c88f40`,wm=class extends oi{constructor(e){super();let t=e.sceneShapes[0]?.meshes[0];if(!t)return;let n=new H;n.setAttribute(`position`,new V(new Float32Array(t.vertices),3));let r=new Yi(n,new xa({color:Cm,dashSize:5,gapSize:5}));r.computeLineDistances(),this.add(r)}};function Tm(){let e=`#`+Wd.selectEdgeColor.getHexString(),t=`#`+Wd.selectFaceColor.getHexString();return{edge:{color:e,lineWidth:3,depthWrite:!1},face:{color:t,opacity:1}}}function Em(e,t){if(t)return t;if(e===`select`)return Tm()}function Dm(e,t,n,r,i,a){switch(e.type){case`sketch`:return new fm(e,t,n,r);case`plane`:return new Sm(e,r);case`axis`:return new wm(e)}let o=e.uniqueType===`select`,s=Em(e.uniqueType,a),c=t.filter(t=>t.parentId===e.id),l;if(c.length>0){let e=new oi;for(let a of c)e.add(Dm(a,t,n,r,i,s));l=e}else l=new _p(e,i,s);return o&&l.traverse(e=>{e.renderOrder=999}),l}function Om(e,t,n,r=!1){let i=new oi;i.name=`compiledMesh`;for(let a of e)a.parentId||!a.visible&&!(t&&a.type===`sketch`)||i.add(Dm(a,e,t,n,r));return i}var km={"Content-Type":`application/json`};function Am(e,t){fetch(e,{method:`POST`,headers:t===void 0?void 0:km,body:t===void 0?void 0:JSON.stringify(t)}).catch(t=>console.error(`POST ${e} failed:`,t))}async function jm(e,t,n){try{let r=await fetch(e,{method:`POST`,headers:km,body:JSON.stringify(t),signal:n});return r.ok?await r.json():null}catch(t){return t?.name!==`AbortError`&&console.error(`POST ${e} failed:`,t),null}}async function Mm(e,t,n){try{let r=e;if(t){let e=new URLSearchParams;for(let[n,r]of Object.entries(t))e.set(n,String(r));r+=`?`+e.toString()}let i=await fetch(r,{signal:n});return i.ok?await i.json():null}catch(t){return t?.name!==`AbortError`&&console.error(`GET ${e} failed:`,t),null}}function Nm(e,t){Am(`/api/insert-point`,{point:e,sourceLocation:t})}function Pm(e,t){Am(`/api/set-pick-points`,{points:e,sourceLocation:t})}function Fm(e){Am(`/api/add-pick`,{sourceLocation:e})}function Im(e){Am(`/api/remove-pick`,{sourceLocation:e})}function Lm(e,t,n){Am(`/api/insert-geometry`,{statement:e,sketchSourceLocation:t,newVariable:n??null})}function Rm(e,t,n){Am(`/api/set-line-position`,{newStart:e,newEnd:t,sourceLocation:n})}function zm(e,t,n){Am(`/api/update-position`,{newPosition:e,sourceLocation:t,pointIndex:n})}function Bm(e,t){Am(`/api/set-chain-positions`,{updates:e,sourceLocation:t})}function Vm(e,t,n,r){Am(`/api/set-rect-dimensions`,{width:e,height:t,sourceLocation:n,startPoint:r??null})}function Hm(e,t,n,r,i){Am(`/api/update-dimension-expression`,{expression:e,sourceLocation:t,sketchSourceLine:n,newVariable:r??null,dimensionOffset:i??0})}async function Um(e){return await jm(`/api/dimension-expression`,{sourceLine:e})??{expression:null}}async function Wm(e){return(await jm(`/api/scope-variables`,{sketchSourceLine:e}))?.variables??[]}function Gm(e,t,n){return Mm(`/api/face-properties`,{shapeId:e,faceIndex:t},n)}function Km(e,t,n){return Mm(`/api/edge-properties`,{shapeId:e,edgeIndex:t},n)}function qm(e){return Mm(`/api/shape-properties`,{shapeId:e})}function Jm(e,t){return jm(`/api/measure`,{entities:e},t)}function Ym(){return Mm(`/api/materials`)}function Xm(){Am(`/api/recompute`)}function Zm(e){Am(`/api/rollback`,{index:e})}function Qm(e){Am(`/api/add-breakpoint`,{sourceLocation:e})}function $m(){Am(`/api/clear-breakpoints`)}function eh(e){Am(`/api/code/goto-source`,e)}async function th(e,t){return await jm(`/api/import-file`,{fileName:e,data:t})??{success:!1,error:`Network error`}}async function nh(e){let t=await fetch(`/api/export`,{method:`POST`,headers:km,body:JSON.stringify(e)});if(!t.ok){let e=await t.json();throw Error(e.error||`Export failed`)}return t.blob()}async function rh(){return Mm(`/api/preferences`)}function ih(e,t){Am(`/api/preferences`,{[e]:t})}var ah=`<svg
4678
4678
  xmlns="http://www.w3.org/2000/svg"
4679
4679
  width="24"
4680
4680
  height="24"
@@ -4692,7 +4692,7 @@ void main() {
4692
4692
  <path d="M4 16a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v2a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2l0 -2" />
4693
4693
  <path d="M10 7h-7" />
4694
4694
  <path d="M21 7h-7" />
4695
- </svg>`,qm=`<svg
4695
+ </svg>`,oh=`<svg
4696
4696
  xmlns="http://www.w3.org/2000/svg"
4697
4697
  width="24"
4698
4698
  height="24"
@@ -4711,7 +4711,7 @@ void main() {
4711
4711
  <path d="M6 3v18" />
4712
4712
  <path d="M12 3v18" />
4713
4713
  <path d="M18 3v18" />
4714
- </svg>`,Jm=`<svg
4714
+ </svg>`,sh=`<svg
4715
4715
  xmlns="http://www.w3.org/2000/svg"
4716
4716
  width="24"
4717
4717
  height="24"
@@ -4729,7 +4729,7 @@ void main() {
4729
4729
  <path d="M12 3l0 17" />
4730
4730
  <path d="M9 12l-3 -6l-3 6a3 3 0 0 0 6 0" />
4731
4731
  <path d="M21 12l-3 -6l-3 6a3 3 0 0 0 6 0" />
4732
- </svg>`,Ym=`<svg
4732
+ </svg>`,ch=`<svg
4733
4733
  xmlns="http://www.w3.org/2000/svg"
4734
4734
  width="24"
4735
4735
  height="24"
@@ -4746,7 +4746,7 @@ void main() {
4746
4746
  <path d="M3 17a3 3 0 1 0 6 0a3 3 0 1 0 -6 0" />
4747
4747
  <path d="M8.6 8.6l10.4 10.4" />
4748
4748
  <path d="M8.6 15.4l10.4 -10.4" />
4749
- </svg>`,Xm=`<svg
4749
+ </svg>`,lh=`<svg
4750
4750
  xmlns="http://www.w3.org/2000/svg"
4751
4751
  width="24"
4752
4752
  height="24"
@@ -4761,7 +4761,7 @@ void main() {
4761
4761
  <path stroke="none" d="M0 0h24v24H0z" fill="none" />
4762
4762
  <path d="M7 9.667a2.667 2.667 0 0 1 2.667 -2.667h8.666a2.667 2.667 0 0 1 2.667 2.667v8.666a2.667 2.667 0 0 1 -2.667 2.667h-8.666a2.667 2.667 0 0 1 -2.667 -2.667l0 -8.666" />
4763
4763
  <path d="M4.012 16.737a2.005 2.005 0 0 1 -1.012 -1.737v-10c0 -1.1 .9 -2 2 -2h10c.75 0 1.158 .385 1.5 1" />
4764
- </svg>`,Zm=`<svg
4764
+ </svg>`,uh=`<svg
4765
4765
  xmlns="http://www.w3.org/2000/svg"
4766
4766
  width="24"
4767
4767
  height="24"
@@ -4776,7 +4776,7 @@ void main() {
4776
4776
  <path stroke="none" d="M0 0h24v24H0z" fill="none" />
4777
4777
  <path d="M3 12a9 9 0 1 0 18 0a9 9 0 1 0 -18 0" />
4778
4778
  <path d="M9 12l2 2l4 -4" />
4779
- </svg>`,Qm=`<svg
4779
+ </svg>`,dh=`<svg
4780
4780
  xmlns="http://www.w3.org/2000/svg"
4781
4781
  width="24"
4782
4782
  height="24"
@@ -4791,7 +4791,7 @@ void main() {
4791
4791
  <path stroke="none" d="M0 0h24v24H0z" fill="none" />
4792
4792
  <path d="M20 11a8.1 8.1 0 0 0 -15.5 -2m-.5 -4v4h4" />
4793
4793
  <path d="M4 13a8.1 8.1 0 0 0 15.5 2m.5 4v-4h-4" />
4794
- </svg>`,$m=`<svg
4794
+ </svg>`,fh=`<svg
4795
4795
  xmlns="http://www.w3.org/2000/svg"
4796
4796
  width="24"
4797
4797
  height="24"
@@ -4808,7 +4808,7 @@ void main() {
4808
4808
  <path d="M15 6l3 3" />
4809
4809
  <path d="M9 3a2 2 0 0 0 2 2a2 2 0 0 0 -2 2a2 2 0 0 0 -2 -2a2 2 0 0 0 2 -2" />
4810
4810
  <path d="M19 13a2 2 0 0 0 2 2a2 2 0 0 0 -2 2a2 2 0 0 0 -2 -2a2 2 0 0 0 2 -2" />
4811
- </svg>`,eh=`<svg
4811
+ </svg>`,ph=`<svg
4812
4812
  xmlns="http://www.w3.org/2000/svg"
4813
4813
  width="24"
4814
4814
  height="24"
@@ -4823,7 +4823,7 @@ void main() {
4823
4823
  <path stroke="none" d="M0 0h24v24H0z" fill="none" />
4824
4824
  <path d="M8 12a4 4 0 1 0 8 0a4 4 0 1 0 -8 0" />
4825
4825
  <path d="M3 12h1m8 -9v1m8 8h1m-9 8v1m-6.4 -15.4l.7 .7m12.1 -.7l-.7 .7m0 11.4l.7 .7m-12.1 -.7l-.7 .7" />
4826
- </svg>`,th=`<svg
4826
+ </svg>`,mh=`<svg
4827
4827
  xmlns="http://www.w3.org/2000/svg"
4828
4828
  width="24"
4829
4829
  height="24"
@@ -4837,7 +4837,7 @@ void main() {
4837
4837
  >
4838
4838
  <path stroke="none" d="M0 0h24v24H0z" fill="none" />
4839
4839
  <path d="M12 3c.132 0 .263 0 .393 0a7.5 7.5 0 0 0 7.92 12.446a9 9 0 1 1 -8.313 -12.454l0 .008" />
4840
- </svg>`,nh=`<svg
4840
+ </svg>`,hh=`<svg
4841
4841
  xmlns="http://www.w3.org/2000/svg"
4842
4842
  width="24"
4843
4843
  height="24"
@@ -4852,7 +4852,7 @@ void main() {
4852
4852
  <path stroke="none" d="M0 0h24v24H0z" fill="none" />
4853
4853
  <path d="M10 12a2 2 0 1 0 4 0a2 2 0 0 0 -4 0" />
4854
4854
  <path d="M21 12c-2.4 4 -5.4 6 -9 6c-3.6 0 -6.6 -2 -9 -6c2.4 -4 5.4 -6 9 -6c3.6 0 6.6 2 9 6" />
4855
- </svg>`,rh=`<svg
4855
+ </svg>`,gh=`<svg
4856
4856
  xmlns="http://www.w3.org/2000/svg"
4857
4857
  width="24"
4858
4858
  height="24"
@@ -4868,7 +4868,7 @@ void main() {
4868
4868
  <path d="M10.585 10.587a2 2 0 0 0 2.829 2.828" />
4869
4869
  <path d="M16.681 16.673a8.717 8.717 0 0 1 -4.681 1.327c-3.6 0 -6.6 -2 -9 -6c1.272 -2.12 2.712 -3.678 4.32 -4.674m2.86 -1.146a9.055 9.055 0 0 1 1.82 -.18c3.6 0 6.6 2 9 6c-.666 1.11 -1.379 2.067 -2.138 2.87" />
4870
4870
  <path d="M3 3l18 18" />
4871
- </svg>`,ih=`<svg
4871
+ </svg>`,_h=`<svg
4872
4872
  xmlns="http://www.w3.org/2000/svg"
4873
4873
  width="24"
4874
4874
  height="24"
@@ -4886,7 +4886,7 @@ void main() {
4886
4886
  <path d="M12 14l7 -7" />
4887
4887
  <path d="M12 19l8.5 -8.5" />
4888
4888
  <path d="M12 9l4.5 -4.5" />
4889
- </svg>`,ah=`<svg
4889
+ </svg>`,vh=`<svg
4890
4890
  xmlns="http://www.w3.org/2000/svg"
4891
4891
  width="24"
4892
4892
  height="24"
@@ -4901,7 +4901,7 @@ void main() {
4901
4901
  <path stroke="none" d="M0 0h24v24H0z" fill="none" />
4902
4902
  <path d="M6 6a1 1 0 0 1 1 -1h2a1 1 0 0 1 1 1v12a1 1 0 0 1 -1 1h-2a1 1 0 0 1 -1 -1l0 -12" />
4903
4903
  <path d="M14 6a1 1 0 0 1 1 -1h2a1 1 0 0 1 1 1v12a1 1 0 0 1 -1 1h-2a1 1 0 0 1 -1 -1l0 -12" />
4904
- </svg>`,oh=`<svg
4904
+ </svg>`,yh=`<svg
4905
4905
  xmlns="http://www.w3.org/2000/svg"
4906
4906
  width="24"
4907
4907
  height="24"
@@ -4917,7 +4917,7 @@ void main() {
4917
4917
  <path d="M12 9v4" />
4918
4918
  <path d="M10.363 3.591l-8.106 13.534a1.914 1.914 0 0 0 1.636 2.871h16.214a1.914 1.914 0 0 0 1.636 -2.87l-8.106 -13.536a1.914 1.914 0 0 0 -3.274 0" />
4919
4919
  <path d="M12 16h.01" />
4920
- </svg>`,sh=`<svg
4920
+ </svg>`,bh=`<svg
4921
4921
  xmlns="http://www.w3.org/2000/svg"
4922
4922
  width="24"
4923
4923
  height="24"
@@ -4939,7 +4939,7 @@ void main() {
4939
4939
  <path d="M16 7a2 2 0 1 0 4 0a2 2 0 0 0 -4 0" />
4940
4940
  <path d="M18 4v1" />
4941
4941
  <path d="M18 9v11" />
4942
- </svg>`,ch=`<svg
4942
+ </svg>`,xh=`<svg
4943
4943
  xmlns="http://www.w3.org/2000/svg"
4944
4944
  width="24"
4945
4945
  height="24"
@@ -4954,7 +4954,7 @@ void main() {
4954
4954
  <path stroke="none" d="M0 0h24v24H0z" fill="none" />
4955
4955
  <path d="M10.325 4.317c.426 -1.756 2.924 -1.756 3.35 0a1.724 1.724 0 0 0 2.573 1.066c1.543 -.94 3.31 .826 2.37 2.37a1.724 1.724 0 0 0 1.065 2.572c1.756 .426 1.756 2.924 0 3.35a1.724 1.724 0 0 0 -1.066 2.573c.94 1.543 -.826 3.31 -2.37 2.37a1.724 1.724 0 0 0 -2.572 1.065c-.426 1.756 -2.924 1.756 -3.35 0a1.724 1.724 0 0 0 -2.573 -1.066c-1.543 .94 -3.31 -.826 -2.37 -2.37a1.724 1.724 0 0 0 -1.065 -2.572c-1.756 -.426 -1.756 -2.924 0 -3.35a1.724 1.724 0 0 0 1.066 -2.573c-.94 -1.543 .826 -3.31 2.37 -2.37c1 .608 2.296 .07 2.572 -1.065" />
4956
4956
  <path d="M9 12a3 3 0 1 0 6 0a3 3 0 0 0 -6 0" />
4957
- </svg>`,lh=`<svg
4957
+ </svg>`,Sh=`<svg
4958
4958
  xmlns="http://www.w3.org/2000/svg"
4959
4959
  width="24"
4960
4960
  height="24"
@@ -4969,18 +4969,40 @@ void main() {
4969
4969
  <path stroke="none" d="M0 0h24v24H0z" fill="none" />
4970
4970
  <path d="M15 10l4.553 -2.276a1 1 0 0 1 1.447 .894v6.764a1 1 0 0 1 -1.447 .894l-4.553 -2.276v-4" />
4971
4971
  <path d="M3 8a2 2 0 0 1 2 -2h8a2 2 0 0 1 2 2v8a2 2 0 0 1 -2 2h-8a2 2 0 0 1 -2 -2l0 -8" />
4972
- </svg>`,uh=`<svg width="24" height="24" viewBox="0 0 24 24" stroke-width="1.5" fill="none" xmlns="http://www.w3.org/2000/svg">
4972
+ </svg>`,Ch=`<svg
4973
+ xmlns="http://www.w3.org/2000/svg"
4974
+ width="24"
4975
+ height="24"
4976
+ viewBox="0 0 24 24"
4977
+ fill="none"
4978
+ stroke="currentColor"
4979
+ stroke-width="2"
4980
+ stroke-linecap="round"
4981
+ stroke-linejoin="round"
4982
+ class="icon icon-tabler icons-tabler-outline icon-tabler-ruler-measure"
4983
+ >
4984
+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />
4985
+ <path d="M19.875 12c.621 0 1.125 .512 1.125 1.143v5.714c0 .631 -.504 1.143 -1.125 1.143h-15.875a1 1 0 0 1 -1 -1v-5.857c0 -.631 .504 -1.143 1.125 -1.143h15.75" />
4986
+ <path d="M9 12v2" />
4987
+ <path d="M6 12v3" />
4988
+ <path d="M12 12v3" />
4989
+ <path d="M18 12v3" />
4990
+ <path d="M15 12v2" />
4991
+ <path d="M3 3v4" />
4992
+ <path d="M3 5h18" />
4993
+ <path d="M21 3v4" />
4994
+ </svg>`,wh=`<svg width="24" height="24" viewBox="0 0 24 24" stroke-width="1.5" fill="none" xmlns="http://www.w3.org/2000/svg">
4973
4995
  <path d="M22 16C22 10.4772 17.5228 6 12 6C6.47715 6 2 10.4772 2 16" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>
4974
4996
  <path d="M2 17C2.55228 17 3 16.5523 3 16C3 15.4477 2.55228 15 2 15C1.44772 15 1 15.4477 1 16C1 16.5523 1.44772 17 2 17Z" fill="currentColor" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>
4975
4997
  <path d="M22 17C22.5523 17 23 16.5523 23 16C23 15.4477 22.5523 15 22 15C21.4477 15 21 15.4477 21 16C21 16.5523 21.4477 17 22 17Z" fill="currentColor" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>
4976
4998
  </svg>
4977
- `,dh=`<svg width="24" height="24" viewBox="0 0 24 24" stroke-width="1.5" fill="none" xmlns="http://www.w3.org/2000/svg">
4999
+ `,Th=`<svg width="24" height="24" viewBox="0 0 24 24" stroke-width="1.5" fill="none" xmlns="http://www.w3.org/2000/svg">
4978
5000
  <path d="M21.9999 16C21.9999 10.4772 17.5228 6 11.9999 6C7.89931 6 4.37514 8.46819 2.83203 12" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="3 3"/>
4979
5001
  <path d="M2 17C2.55228 17 3 16.5523 3 16C3 15.4477 2.55228 15 2 15C1.44772 15 1 15.4477 1 16C1 16.5523 1.44772 17 2 17Z" fill="currentColor" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>
4980
5002
  <path d="M2 16H12" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>
4981
5003
  <path d="M12 17C12.5523 17 13 16.5523 13 16C13 15.4477 12.5523 15 12 15C11.4477 15 11 15.4477 11 16C11 16.5523 11.4477 17 12 17Z" fill="currentColor" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>
4982
5004
  </svg>
4983
- `,fh=`<svg
5005
+ `,Eh=`<svg
4984
5006
  xmlns="http://www.w3.org/2000/svg"
4985
5007
  width="24"
4986
5008
  height="24"
@@ -4994,34 +5016,34 @@ void main() {
4994
5016
  >
4995
5017
  <path stroke="none" d="M0 0h24v24H0z" fill="none" />
4996
5018
  <path d="M3 7a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v10a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2v-10" />
4997
- </svg>`,ph=`<svg width="24" height="24" stroke-width="1.5" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
5019
+ </svg>`,Dh=`<svg width="24" height="24" stroke-width="1.5" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
4998
5020
  <path d="M3 20L21 4" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>
4999
5021
  </svg>
5000
- `,mh=`<svg width="24" height="24" viewBox="0 0 24 24" stroke-width="1.5" fill="none" xmlns="http://www.w3.org/2000/svg">
5022
+ `,Oh=`<svg width="24" height="24" viewBox="0 0 24 24" stroke-width="1.5" fill="none" xmlns="http://www.w3.org/2000/svg">
5001
5023
  <path d="M12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22Z" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>
5002
5024
  <path d="M12 13C12.5523 13 13 12.5523 13 12C13 11.4477 12.5523 11 12 11C11.4477 11 11 11.4477 11 12C11 12.5523 11.4477 13 12 13Z" fill="currentColor" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>
5003
5025
  <path d="M19 19L17.5 17.5" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>
5004
5026
  <path d="M15.5 15.5L14.5 14.5" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>
5005
5027
  </svg>
5006
- `,hh=Km,gh=qm,_h=Jm,vh=Ym,yh=Xm,bh=Zm,xh=Qm,Sh=$m,Ch=eh,wh=th,Th=nh,Eh=rh,Dh=ih,Oh=ah,kh=oh,Ah=sh,jh=ch,Mh=lh,Nh=ph,Ph=mh,Fh=dh,Ih=uh,Lh=fh,Rh=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="5" width="18" height="14" rx="5"/></svg>`,zh=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M9 5h6a5 5 0 0 1 0 10H9a5 5 0 0 1 0-10z"/><circle cx="9" cy="10" r="1.2" fill="currentColor" stroke="none"/><circle cx="15" cy="10" r="1.2" fill="currentColor" stroke="none"/></svg>`,Bh=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><polygon points="12,3 20,7.5 20,16.5 12,21 4,16.5 4,7.5"/></svg>`,Vh=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="4 18 8 10 14 14 20 6"/><circle cx="4" cy="18" r="1.5" fill="currentColor" stroke="none"/><circle cx="8" cy="10" r="1.5" fill="currentColor" stroke="none"/><circle cx="14" cy="14" r="1.5" fill="currentColor" stroke="none"/><circle cx="20" cy="6" r="1.5" fill="currentColor" stroke="none"/></svg>`,Hh=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 19 C 8 5, 16 5, 21 19"/><circle cx="3" cy="19" r="1.5" fill="currentColor" stroke="none"/><circle cx="21" cy="19" r="1.5" fill="currentColor" stroke="none"/></svg>`,Uh=`<svg width="14" height="14" viewBox="0 0 10 10" fill="currentColor"><path d="M3 1l5 4-5 4z"/></svg>`,Wh=`<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"/></svg>`,Gh=`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><circle cx="12" cy="5" r="2"/><circle cx="12" cy="12" r="2"/><circle cx="12" cy="19" r="2"/></svg>`,Kh=`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/><polyline points="3.27 6.96 12 12.01 20.73 6.96"/><line x1="12" y1="22.08" x2="12" y2="12"/></svg>`,qh=`<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>`,Jh=`<svg width="10" height="10" viewBox="0 0 24 24" fill="currentColor"><circle cx="12" cy="12" r="6"/></svg>`,Yh=`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>`,Xh=`btn btn-ghost btn-circle btn-sm text-base-content/60`,Zh=`btn btn-soft btn-primary btn-circle btn-sm`;function Qh(){return document.documentElement.getAttribute(`data-theme`)||`fluidcad-dark`}function $h(){return Qh()!==`fluidcad-light`}var eg=class{wrapper;fabEl;fitEl;paramsEl;sectionViewEl;onFitView=null;onParamsToggle=null;onSectionViewToggle=null;constructor(e,t){this.onCameraSwitch=t;let n=document.createElement(`style`);n.textContent=`
5028
+ `,kh=ah,Ah=oh,jh=sh,Mh=ch,Nh=lh,Ph=uh,Fh=dh,Ih=fh,Lh=ph,Rh=mh,zh=hh,Bh=gh,Vh=_h,Hh=vh,Uh=yh,Wh=bh,Gh=xh,Kh=Sh,qh=Ch,Jh=Dh,Yh=Oh,Xh=Th,Zh=wh,Qh=Eh,$h=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="5" width="18" height="14" rx="5"/></svg>`,eg=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M9 5h6a5 5 0 0 1 0 10H9a5 5 0 0 1 0-10z"/><circle cx="9" cy="10" r="1.2" fill="currentColor" stroke="none"/><circle cx="15" cy="10" r="1.2" fill="currentColor" stroke="none"/></svg>`,tg=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><polygon points="12,3 20,7.5 20,16.5 12,21 4,16.5 4,7.5"/></svg>`,ng=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="4 18 8 10 14 14 20 6"/><circle cx="4" cy="18" r="1.5" fill="currentColor" stroke="none"/><circle cx="8" cy="10" r="1.5" fill="currentColor" stroke="none"/><circle cx="14" cy="14" r="1.5" fill="currentColor" stroke="none"/><circle cx="20" cy="6" r="1.5" fill="currentColor" stroke="none"/></svg>`,rg=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 19 C 8 5, 16 5, 21 19"/><circle cx="3" cy="19" r="1.5" fill="currentColor" stroke="none"/><circle cx="21" cy="19" r="1.5" fill="currentColor" stroke="none"/></svg>`,ig=`<svg width="14" height="14" viewBox="0 0 10 10" fill="currentColor"><path d="M3 1l5 4-5 4z"/></svg>`,ag=`<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"/></svg>`,og=`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><circle cx="12" cy="5" r="2"/><circle cx="12" cy="12" r="2"/><circle cx="12" cy="19" r="2"/></svg>`,sg=`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/><polyline points="3.27 6.96 12 12.01 20.73 6.96"/><line x1="12" y1="22.08" x2="12" y2="12"/></svg>`,cg=`<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>`,lg=`<svg width="10" height="10" viewBox="0 0 24 24" fill="currentColor"><circle cx="12" cy="12" r="6"/></svg>`,ug=`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>`,dg=`btn btn-ghost btn-circle btn-sm text-base-content/60`,fg=`btn btn-soft btn-primary btn-circle btn-sm`;function pg(){return document.documentElement.getAttribute(`data-theme`)||`fluidcad-dark`}function mg(){return pg()!==`fluidcad-light`}var hg=class{wrapper;fabEl;fitEl;paramsEl;sectionViewEl;onFitView=null;onParamsToggle=null;onSectionViewToggle=null;constructor(e,t){this.onCameraSwitch=t;let n=document.createElement(`style`);n.textContent=`
5007
5029
  .settings-fab:not(:focus-within) > :nth-child(n+3) {
5008
5030
  display: none !important;
5009
5031
  }
5010
- `,document.head.appendChild(n),this.wrapper=document.createElement(`div`),this.wrapper.className=`absolute right-7 top-[100px] z-[100] flex flex-col items-end select-none`,e.appendChild(this.wrapper);let r=this.wrapper;this.sectionViewEl=document.createElement(`div`),this.sectionViewEl.className=`mb-2`,this.sectionViewEl.style.display=`none`,this.sectionViewEl.innerHTML=`<button class="${Zh}" data-action="section-view" title="Toggle section view">${Dh}</button>`,r.appendChild(this.sectionViewEl),this.fabEl=document.createElement(`div`),this.fabEl.className=`fab settings-fab !relative !bottom-auto !end-auto !flex-col`,this.fabEl.innerHTML=this.buildFabHTML(),r.appendChild(this.fabEl),this.fitEl=document.createElement(`button`),this.fitEl.className=`btn btn-circle btn-sm panel-bg border border-base-content/10 text-base-content/60 mt-2`,this.fitEl.title=`Fit to view`,this.fitEl.innerHTML=hh,r.appendChild(this.fitEl),this.paramsEl=document.createElement(`button`),this.paramsEl.className=`btn btn-circle btn-sm panel-bg border border-base-content/10 text-base-content/60 mt-2`,this.paramsEl.title=`Toggle parameters`,this.paramsEl.innerHTML=Ah,this.paramsEl.style.display=`none`,r.appendChild(this.paramsEl),this.bindEvents(),qd.subscribe(()=>this.sync())}buildFabHTML(){let e=qd.current,t=$h()?Ch:wh,n=$h()?`Light theme`:`Dark theme`,r=e.cameraMode===`orthographic`?`Orthographic`:`Perspective`;return`
5011
- <div tabindex="0" role="button" class="btn btn-circle btn-sm panel-bg border border-base-content/10 text-base-content/60" title="Scene settings">${jh}</div>
5032
+ `,document.head.appendChild(n),this.wrapper=document.createElement(`div`),this.wrapper.className=`absolute right-7 top-[100px] z-[100] flex flex-col items-end select-none`,e.appendChild(this.wrapper);let r=this.wrapper;this.sectionViewEl=document.createElement(`div`),this.sectionViewEl.className=`mb-2`,this.sectionViewEl.style.display=`none`,this.sectionViewEl.innerHTML=`<button class="${fg}" data-action="section-view" title="Toggle section view">${Vh}</button>`,r.appendChild(this.sectionViewEl),this.fabEl=document.createElement(`div`),this.fabEl.className=`fab settings-fab !relative !bottom-auto !end-auto !flex-col`,this.fabEl.innerHTML=this.buildFabHTML(),r.appendChild(this.fabEl),this.fitEl=document.createElement(`button`),this.fitEl.className=`btn btn-circle btn-sm panel-bg border border-base-content/10 text-base-content/60 mt-2`,this.fitEl.title=`Fit to view`,this.fitEl.innerHTML=kh,r.appendChild(this.fitEl),this.paramsEl=document.createElement(`button`),this.paramsEl.className=`btn btn-circle btn-sm panel-bg border border-base-content/10 text-base-content/60 mt-2`,this.paramsEl.title=`Toggle parameters`,this.paramsEl.innerHTML=Wh,this.paramsEl.style.display=`none`,r.appendChild(this.paramsEl),this.bindEvents(),lf.subscribe(()=>this.sync())}buildFabHTML(){let e=lf.current,t=mg()?Lh:Rh,n=mg()?`Light theme`:`Dark theme`,r=e.cameraMode===`orthographic`?`Orthographic`:`Perspective`;return`
5033
+ <div tabindex="0" role="button" class="btn btn-circle btn-sm panel-bg border border-base-content/10 text-base-content/60" title="Scene settings">${Gh}</div>
5012
5034
  <div class="fab-close !top-0 !bottom-auto">
5013
- <span class="btn btn-circle btn-sm panel-bg border border-base-content/10">${Yh}</span>
5035
+ <span class="btn btn-circle btn-sm panel-bg border border-base-content/10">${ug}</span>
5014
5036
  </div>
5015
- <div>Grid <button class="${e.showGrid?Zh:Xh}" data-action="grid" title="Toggle grid">${gh}</button></div>
5037
+ <div>Grid <button class="${e.showGrid?fg:dg}" data-action="grid" title="Toggle grid">${Ah}</button></div>
5016
5038
  <div>
5017
5039
  <span data-camera-label>${r}</span>
5018
- <button class="${Xh}" data-action="camera" title="Toggle projection">${Mh}</button>
5040
+ <button class="${dg}" data-action="camera" title="Toggle projection">${Kh}</button>
5019
5041
  </div>
5020
5042
  <div>
5021
5043
  <span data-theme-label>${n}</span>
5022
- <button class="${Xh}" data-action="theme" title="${$h()?`Switch to light theme`:`Switch to dark theme`}">${t}</button>
5044
+ <button class="${dg}" data-action="theme" title="${mg()?`Switch to light theme`:`Switch to dark theme`}">${t}</button>
5023
5045
  </div>
5024
- `}bindEvents(){this.fitEl.addEventListener(`click`,()=>{this.onFitView?.()}),this.paramsEl.addEventListener(`click`,()=>{this.onParamsToggle?.()}),this.fabEl.querySelector(`[data-action="camera"]`)?.addEventListener(`click`,()=>{let e=qd.current.cameraMode===`perspective`?`orthographic`:`perspective`;qd.update({cameraMode:e}),Gm(`cameraMode`,e),this.onCameraSwitch(e)}),this.fabEl.querySelector(`[data-action="grid"]`)?.addEventListener(`click`,()=>{let e=!qd.current.showGrid;qd.update({showGrid:e}),Gm(`showGrid`,e)}),this.sectionViewEl.querySelector(`[data-action="section-view"]`)?.addEventListener(`click`,()=>{let e=!qd.current.sectionView;qd.update({sectionView:e}),this.onSectionViewToggle?.(e)}),this.fabEl.querySelector(`[data-action="theme"]`)?.addEventListener(`click`,()=>{let e=$h()?`fluidcad-light`:`fluidcad-dark`;document.documentElement.setAttribute(`data-theme`,e),this.syncThemeButton(),Gm(`theme`,e)})}get panelHost(){return this.wrapper}setFitHandler(e){this.onFitView=e}setFitButtonVisible(e){this.fitEl.style.display=e?``:`none`}setParamsToggleHandler(e){this.onParamsToggle=e}setParamsButtonVisible(e){this.paramsEl.style.display=e?``:`none`}setParamsButtonActive(e){this.paramsEl.className=e?Zh+` mt-2`:`btn btn-circle btn-sm panel-bg border border-base-content/10 text-base-content/60 mt-2`}setSectionViewToggleHandler(e){this.onSectionViewToggle=e}setSectionViewVisible(e){this.sectionViewEl.style.display=e?``:`none`}setSectionViewActive(e){let t=this.sectionViewEl.querySelector(`[data-action="section-view"]`);t&&(t.className=e?Zh:Xh)}setProjectionLocked(e){let t=this.fabEl.querySelector(`[data-action="camera"]`);t&&(t.disabled=e)}syncThemeButton(){let e=this.fabEl.querySelector(`[data-action="theme"]`);e&&(e.innerHTML=$h()?Ch:wh,e.title=$h()?`Switch to light theme`:`Switch to dark theme`);let t=this.fabEl.querySelector(`[data-theme-label]`);t&&(t.textContent=$h()?`Light theme`:`Dark theme`)}sync(){let e=qd.current,t=this.fabEl.querySelector(`[data-action="grid"]`);t&&(t.className=e.showGrid?Zh:Xh);let n=this.fabEl.querySelector(`[data-camera-label]`);if(n&&(n.textContent=e.cameraMode===`orthographic`?`Orthographic`:`Perspective`),this.sectionViewEl.style.display!==`none`){let t=this.sectionViewEl.querySelector(`[data-action="section-view"]`);t&&(t.className=e.sectionView?Zh:Xh)}}},tg=class{mesh=null;show(e,t,n){this.clear(e);let r=new H(new la(n,16,16),new mr({color:16729088,depthTest:!1}));r.position.set(t.x,t.y,t.z),r.renderOrder=999,r.userData.isMetaShape=!0,e.add(r),this.mesh=r}clear(e){this.mesh&&=(this.mesh.geometry.dispose(),this.mesh.material.dispose(),e.remove(this.mesh),null)}};function ng(e,t){if(t.userData.isMetaShape)return;let n=t;(n.isMesh||n.isLine||n.isPoints)&&n.geometry&&(n.geometry.computeBoundingBox(),n.geometry.boundingBox&&e.union(n.geometry.boundingBox.clone().applyMatrix4(n.matrixWorld)));for(let n of t.children)ng(e,n)}var rg=2,ig=2,ag=.75,og=class{ctx;modeManager;settingsPanel;sceneObjects=[];highlightedShapeId=null;faceHighlightMeshes=[];hasRendered=!1;lastFitBox=null;isTrimming=!1;isRegionPicking=!1;isDrawing=!1;selectionHandler=null;centroidIndicator=new tg;hoverState=null;hoverFaceOverlayMeshes=[];hoverRafId=null;isMouseDown=!1;highlightedSub=null;activeSketchId=null;hiddenShapeIds=new Set;shapeOpacities=new Map;constructor(e){let t=document.getElementById(e);this.ctx=new Wd(t),this.modeManager=new $d(this.ctx),this.settingsPanel=new eg(t,e=>this.ctx.switchCamera(e)),this.settingsPanel.setFitHandler(()=>this.fitViewToScene()),qd.current.cameraMode===`perspective`&&this.ctx.switchCamera(`perspective`),this.settingsPanel.setSectionViewToggleHandler(e=>{e?this.applySectionView():this.clearSectionView()}),this.initClickDetection(),this.initHoverDetection()}get sceneContext(){return this.ctx}get currentSceneObjects(){return this.sceneObjects}setSelectionHandler(e){this.selectionHandler=e}get settingsPanelHost(){return this.settingsPanel.panelHost}setParamsToggleHandler(e){this.settingsPanel.setParamsToggleHandler(e)}setParamsButtonVisible(e){this.settingsPanel.setParamsButtonVisible(e)}setParamsButtonActive(e){this.settingsPanel.setParamsButtonActive(e)}lookAlongSketchNormal(e){this.modeManager.enforceSketchNormal(e)}initClickDetection(){let e=this.ctx.renderer.domElement,t=0,n=0;e.addEventListener(`mousedown`,e=>{t=e.clientX,n=e.clientY}),e.addEventListener(`mouseup`,e=>{if(!this.selectionHandler||this.isTrimming||this.isRegionPicking||this.modeManager.isSketchMode)return;let r=e.clientX-t,i=e.clientY-n;if(r*r+i*i>64)return;this.clearHover();let a=this.pickAt(e.clientX,e.clientY);a?this.selectionHandler(a.shapeId,a.sub):this.selectionHandler(null,null)})}pickAt(e,t){let n=this.ctx.camera,r=this.ctx.renderer.domElement.getBoundingClientRect(),i=(e-r.left)/r.width*2-1,a=-((t-r.top)/r.height)*2+1,o=this.ctx.createPickingRaycaster(i,a);o.params.Line={threshold:this.computeEdgePickThreshold()},o.params.Line2={threshold:8};let s=[],c=[];this.ctx.scene.traverse(e=>{e.userData.isMetaShape||(e.isMesh&&e.userData.faceMapping?s.push(e):(e.isLine||e.userData.isEdgeLine)&&e.userData.edgeIndex!==void 0&&c.push(e))});let l=s.length>0?o.intersectObjects(s,!1):[],u=c.length>0?o.intersectObjects(c,!1):[];if(l.length===0&&u.length===0)return null;let d=new R;n.getWorldDirection(d);let f;for(let e of l){if(!e.face){f=e;break}if(e.face.normal.clone().transformDirection(e.object.matrixWorld).dot(d)<0){f=e;break}}let p=f==null?1/0:f.distance,m=o.ray.origin,h=o.ray.direction,g=new R,_=new R;for(let e of u){let t=e.pointOnLine;if(t?g.copy(t):g.copy(e.point),h.dot(_.copy(g).sub(m))<=p+.001){let t=e.object.userData.edgeIndex,n=this.findShapeIdForObject(e.object);if(n)return{shapeId:n,sub:{type:`edge`,index:t}}}}if(f){let e=f.object.userData.faceMapping;if(!e||f.faceIndex==null)return null;let t=e[f.faceIndex];if(t==null)return null;let n=this.findShapeIdForObject(f.object);if(n)return{shapeId:n,sub:{type:`face`,index:t}}}return null}findShapeIdForObject(e){let t=e;for(;t;){if(t.userData.shapeId&&!t.userData.isMetaShape)return t.userData.shapeId;t=t.parent}return null}toggleSketchMode(e){this.modeManager.sketchEnabled=e}setFileName(e){}updateView(e,t=!1,n){if(this.sceneObjects=e,this.highlightedShapeId=null,this.highlightedSub=null,this.hoverState=null,this.hoverFaceOverlayMeshes=[],this.ctx.renderer.domElement.style.cursor=``,this.removeCompiledMesh(),t)this.activeSketchId=this.findRollbackActiveSketchId(e,n);else{let t=this.findActiveObject(e);t?.type===`sketch`&&t.object?.plane?(this.modeManager.isSketchMode?this.modeManager.enforceSketchNormal(t.object.plane):this.modeManager.enterSketchMode(t.object.plane),this.activeSketchId=t.id,this.settingsPanel.setProjectionLocked(!0),this.settingsPanel.setFitButtonVisible(!1)):(this.activeSketchId=null,this.modeManager.enterDefaultMode(),this.settingsPanel.setProjectionLocked(!1),this.settingsPanel.setFitButtonVisible(!0),this.lastFitBox=null)}let r=gm(e,this.activeSketchId,this.ctx.camera,this.isRegionPicking);if(this.ctx.scene.add(r),this.applyShapeOverridesAndPrune(e),this.activeSketchId&&this.applySketchModeGhosting(),this.settingsPanel.setSectionViewVisible(this.modeManager.isSketchMode),this.modeManager.isSketchMode&&(this.settingsPanel.setSectionViewActive(qd.current.sectionView),qd.current.sectionView&&this.applySectionView()),!this.hasRendered&&!this.modeManager.isSketchMode||this.modeManager.isSketchMode&&!t&&!this.isTrimming&&!this.isRegionPicking&&!this.isDrawing){let e=new Gt;ng(e,r),!e.isEmpty()&&!this.isBoxContained(e)&&(this.ctx.fitToBox(e,!0),this.lastFitBox=e.clone(),this.hasRendered=!0)}!this.hasRendered&&this.modeManager.isSketchMode&&(this.hasRendered=!0),this.ctx.requestRender()}highlightShape(e){this.clearHighlight();let t=this.findShapeById(e);if(!t)return;let n=this.findMeshByShapeId(e);if(!n)return;let r=t.shapeType===`solid`||t.shapeType===`face`;n.traverse(e=>{if(!e.material)return;let t=e.isLine||e.userData.isEdgeLine;if(r&&e instanceof H&&!t){let t=e.material;e.userData.originalColor=t.color.getHex(),t.color.set(Rd.highlightColor),(t.opacity<1||t.transparent)&&(e.userData.originalOpacity=t.opacity,e.userData.originalTransparent=t.transparent,t.opacity=1,t.transparent=!1)}else !r&&t&&(e.userData.originalColor=e.material.color.getHex(),e.material.color.set(Rd.highlightColor),e.userData.originalLineWidth=e.material.linewidth,e.material.linewidth=rg,e.material.opacity<1&&(e.userData.originalOpacity=e.material.opacity,e.material.opacity=1))}),this.highlightedShapeId=e,this.highlightedSub=null,this.ctx.render()}clearHighlight(){if(!(!this.highlightedShapeId&&this.faceHighlightMeshes.length===0)){this.ctx.scene.traverse(e=>{e.userData.originalColor!==void 0&&(e.material.color.setHex(e.userData.originalColor),delete e.userData.originalColor),e.userData.originalOpacity!==void 0&&(e.material.opacity=e.userData.originalOpacity,delete e.userData.originalOpacity),e.userData.originalTransparent!==void 0&&(e.material.transparent=e.userData.originalTransparent,delete e.userData.originalTransparent),e.userData.originalLineWidth!==void 0&&(e.material.linewidth=e.userData.originalLineWidth,delete e.userData.originalLineWidth)});for(let e of this.faceHighlightMeshes)e.parent?.remove(e),e.geometry.dispose(),e.material.dispose();this.faceHighlightMeshes=[],this.highlightedShapeId=null,this.highlightedSub=null,this.ctx.render()}}highlightFace(e,t){this.clearHighlight(),this.ctx.scene.traverse(n=>{if(!n.isMesh)return;let r=n.userData.faceMapping;if(!r)return;let i=!1,a=n;for(;a;){if(a.userData.shapeId===e&&!a.userData.isMetaShape){i=!0;break}a=a.parent}if(!i)return;let o=n,s=o.geometry,c=s.index;if(!c)return;let l=c.array,u=s.getAttribute(`position`).array,d=[];for(let e=0;e<r.length;e++)if(r[e]===t){let t=l[e*3]*3,n=l[e*3+1]*3,r=l[e*3+2]*3;d.push(u[t],u[t+1],u[t+2]),d.push(u[n],u[n+1],u[n+2]),d.push(u[r],u[r+1],u[r+2])}if(d.length===0)return;let f=new Or;f.setAttribute(`position`,new V(new Float32Array(d),3));let p=new H(f,new fa({color:Rd.highlightColor,polygonOffset:!0,polygonOffsetFactor:-2,polygonOffsetUnits:-1}));(o.parent??this.ctx.scene).add(p),this.faceHighlightMeshes.push(p)}),this.highlightedShapeId=e,this.highlightedSub={type:`face`,index:t},this.ctx.render()}highlightEdge(e,t){this.clearHighlight(),this.ctx.scene.traverse(n=>{if(!n.isLine&&!n.userData.isEdgeLine||n.userData.edgeIndex!==t)return;let r=!1,i=n;for(;i;){if(i.userData.shapeId===e&&!i.userData.isMetaShape){r=!0;break}i=i.parent}r&&(n.userData.originalColor=n.material.color.getHex(),n.material.color.set(Rd.highlightColor),n.userData.originalLineWidth=n.material.linewidth,n.material.linewidth=rg)}),this.highlightedShapeId=e,this.highlightedSub={type:`edge`,index:t},this.ctx.render()}initHoverDetection(){let e=this.ctx.renderer.domElement;e.addEventListener(`mousedown`,()=>{this.isMouseDown=!0,this.clearHover()}),e.addEventListener(`mouseup`,()=>{this.isMouseDown=!1}),e.addEventListener(`mousemove`,e=>{this.isMouseDown||this.isTrimming||this.isRegionPicking||this.modeManager.isSketchMode||this.hoverRafId===null&&(this.hoverRafId=requestAnimationFrame(()=>{this.hoverRafId=null,this.updateHover(e.clientX,e.clientY)}))}),e.addEventListener(`mouseleave`,()=>{this.clearHover()})}updateHover(e,t){if(!this.selectionHandler)return;let n=this.pickAt(e,t);if(!(this.hoverState&&n&&this.hoverState.shapeId===n.shapeId&&this.hoverState.sub?.type===n.sub?.type&&this.hoverState.sub?.index===n.sub?.index)){if(!n){this.hoverState&&this.clearHover();return}if(this.highlightedShapeId===n.shapeId&&this.highlightedSub?.type===n.sub?.type&&this.highlightedSub?.index===n.sub?.index){this.hoverState&&this.clearHover();return}this.clearHover(),this.hoverState=n,this.ctx.renderer.domElement.style.cursor=`pointer`,n.sub?.type===`face`?this.applyHoverFace(n.shapeId,n.sub.index):n.sub?.type===`edge`&&this.applyHoverEdge(n.shapeId,n.sub.index)}}clearHover(){for(let e of this.hoverFaceOverlayMeshes)e.parent?.remove(e),e.geometry.dispose(),e.material.dispose();this.hoverFaceOverlayMeshes=[],this.ctx.scene.traverse(e=>{e.userData.hoverOriginalColor!==void 0&&(e.material.color.setHex(e.userData.hoverOriginalColor),delete e.userData.hoverOriginalColor),e.userData.hoverOriginalLineWidth!==void 0&&(e.material.linewidth=e.userData.hoverOriginalLineWidth,delete e.userData.hoverOriginalLineWidth)}),this.hoverState=null,this.ctx.renderer.domElement.style.cursor=``,this.ctx.requestRender()}applyHoverFace(e,t){this.ctx.scene.traverse(n=>{if(!n.isMesh)return;let r=n.userData.faceMapping;if(!r)return;let i=!1,a=n;for(;a;){if(a.userData.shapeId===e&&!a.userData.isMetaShape){i=!0;break}a=a.parent}if(!i)return;let o=n,s=o.geometry,c=s.index;if(!c)return;let l=c.array,u=s.getAttribute(`position`).array,d=[];for(let e=0;e<r.length;e++)if(r[e]===t){let t=l[e*3]*3,n=l[e*3+1]*3,r=l[e*3+2]*3;d.push(u[t],u[t+1],u[t+2]),d.push(u[n],u[n+1],u[n+2]),d.push(u[r],u[r+1],u[r+2])}if(d.length===0)return;let f=new Or;f.setAttribute(`position`,new V(new Float32Array(d),3));let p=new H(f,new fa({color:Rd.highlightColor,polygonOffset:!0,polygonOffsetFactor:-2,polygonOffsetUnits:-1}));(o.parent??this.ctx.scene).add(p),this.hoverFaceOverlayMeshes.push(p)}),this.ctx.requestRender()}applyHoverEdge(e,t){this.ctx.scene.traverse(n=>{if(!n.isLine&&!n.userData.isEdgeLine||n.userData.edgeIndex!==t)return;let r=!1,i=n;for(;i;){if(i.userData.shapeId===e&&!i.userData.isMetaShape){r=!0;break}i=i.parent}r&&(n.userData.hoverOriginalColor=n.material.color.getHex(),n.material.color.set(Rd.highlightColor),n.userData.hoverOriginalLineWidth=n.material.linewidth,n.material.linewidth=ig)}),this.ctx.requestRender()}showCentroid(e){let t=this.computeCentroidRadius();this.centroidIndicator.show(this.ctx.scene,e,t),this.ctx.requestRender()}clearCentroid(){this.centroidIndicator.clear(this.ctx.scene),this.ctx.requestRender()}dispose(){this.ctx.dispose()}computeEdgePickThreshold(){let e=this.ctx.camera,t=this.ctx.renderer.domElement.getBoundingClientRect().height||1,n,r=e;if(r.isOrthographicCamera)n=(r.top-r.bottom)/(r.zoom||1);else{let t=new R;this.ctx.cameraControls.getTarget(t);let i=e.position.distanceTo(t),a=r.fov*Math.PI/180;n=2*i*Math.tan(a/2)}return n/t*8}computeCentroidRadius(){let e=this.ctx.scene.getObjectByName(`compiledMesh`);if(e){let t=new Gt;if(ng(t,e),!t.isEmpty())return t.getSize(new R).length()*.015}return 2}fitViewToScene(){let e=this.ctx.scene.getObjectByName(`compiledMesh`);if(!e)return;let t=new Gt;ng(t,e),t.isEmpty()||this.ctx.fitToBox(t,!0)}findShapeById(e){for(let t of this.sceneObjects)for(let n of t.sceneShapes)if(n.shapeId===e)return n}findMeshByShapeId(e){let t;return this.ctx.scene.traverse(n=>{n.userData.shapeId===e&&(t=n)}),t}findActiveObject(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(!n.parentId||e.find(e=>e.id===n.parentId)?.type===`part`)return n}}findRollbackActiveSketchId(e,t){if(t==null||t<0||t>=e.length)return null;let n=e[t];for(;n;){if(n.type===`sketch`)return n.id;if(!n.parentId)return null;n=e.find(e=>e.id===n.parentId)}return null}isBoxContained(e){if(!this.lastFitBox)return!1;let t=this.lastFitBox.getCenter(new R),n=this.lastFitBox.getSize(new R).length()/2*Ud;if(n===0)return!1;let r=e.getCenter(new R),i=e.getSize(new R).length()/2;return t.distanceTo(r)+i<=n}rebuildSceneMesh(){if(!this.sceneObjects)return;this.removeCompiledMesh();let e=gm(this.sceneObjects,this.activeSketchId,this.ctx.camera,this.isRegionPicking);this.ctx.scene.add(e),this.applyShapeOverridesAndPrune(this.sceneObjects),this.modeManager.isSketchMode&&qd.current.sectionView&&this.applySectionView(),this.ctx.requestRender()}setShapeVisibility(e,t){t?this.hiddenShapeIds.delete(e):this.hiddenShapeIds.add(e),this.applyVisibilityForId(e,t),this.ctx.requestRender()}isShapeHidden(e){return this.hiddenShapeIds.has(e)}applyVisibilityForId(e,t){this.ctx.scene.traverse(n=>{n.userData.shapeId===e&&(n.visible=t)})}setShapeTransparency(e,t){t>=1?this.shapeOpacities.delete(e):this.shapeOpacities.set(e,t),this.applyOpacityForId(e,t),this.ctx.requestRender()}getShapeTransparency(e){return this.shapeOpacities.get(e)??1}resetAllTransparency(){if(this.shapeOpacities.size===0)return;let e=Array.from(this.shapeOpacities.keys());this.shapeOpacities.clear();for(let t of e)this.applyOpacityForId(t,1);this.ctx.requestRender()}applyOpacityForId(e,t){let n=[];this.ctx.scene.traverse(t=>{t.userData.shapeId===e&&n.push(t)});for(let e of n)this.applyOpacityToSubtree(e,t)}applyOpacityToSubtree(e,t){e.traverse(e=>{let n=e.material;if(!n)return;let r=Array.isArray(n)?n:[n];for(let e of r)e.transparent=t<1,e.opacity=t,e.depthWrite=t>=1,e.needsUpdate=!0})}applyShapeOverridesAndPrune(e){let t=new Set;for(let n of e)if(n.sceneShapes)for(let e of n.sceneShapes)e.isMetaShape||e.shapeId&&t.add(e.shapeId);for(let e of this.hiddenShapeIds)t.has(e)||this.hiddenShapeIds.delete(e);for(let e of this.shapeOpacities.keys())t.has(e)||this.shapeOpacities.delete(e);this.ctx.scene.traverse(e=>{let t=e.userData.shapeId;if(typeof t!=`string`)return;this.hiddenShapeIds.has(t)&&(e.visible=!1);let n=this.shapeOpacities.get(t);n!==void 0&&this.applyOpacityToSubtree(e,n)})}applySketchModeGhosting(){let e=this.ctx.scene.getObjectByName(`compiledMesh`);if(!e)return;let t=Rd.backgroundColor;for(let n of e.children)this.tintForGhosting(n,t)}tintForGhosting(e,t){if(e.userData.isSketchRoot||e.renderOrder>=999)return;let n=e.material;if(n){let e=Array.isArray(n)?n:[n];for(let n of e)!n.color||!(n.color instanceof B)||(n.userData.ghostOriginalColor||(n.userData.ghostOriginalColor=n.color.clone()),n.color.copy(n.userData.ghostOriginalColor).lerp(t,ag))}for(let n of e.children)this.tintForGhosting(n,t)}applySectionView(){let e=this.modeManager.sectionPlane;if(!e)return;let t=this.ctx.scene.getObjectByName(`compiledMesh`);t&&(this.forEachClippableMaterial(t,t=>{t.clippingPlanes=[e]}),this.ctx.requestRender())}clearSectionView(){let e=this.ctx.scene.getObjectByName(`compiledMesh`);e&&(this.forEachClippableMaterial(e,e=>{e.clippingPlanes=[]}),this.ctx.requestRender())}forEachClippableMaterial(e,t){if(e.userData.isSketchRoot)return;let n=e.material;if(n){let e=Array.isArray(n)?n:[n];for(let n of e)t(n)}for(let n of e.children)this.forEachClippableMaterial(n,t)}removeCompiledMesh(){let e=this.ctx.scene.getObjectByName(`compiledMesh`);e&&(e.traverse(e=>{e.geometry?.dispose(),Array.isArray(e.material)?e.material.forEach(e=>e.dispose()):e.material?.dispose()}),this.ctx.scene.remove(e))}};function sg(e){switch(e){case`inch`:return 16.387064;case`foot`:return 28316.846592;case`yard`:return 764554.857984;case`meter`:return 1e6;default:return .001}}function cg(e){switch(e){case`inch`:return`in`;case`foot`:return`ft`;case`yard`:return`yd`;case`meter`:return`m`;default:return`mm`}}function lg(e,t,n){let r=t===`kg`?1e3:t===`lbs`?453.592:1;return e*sg(n)/r}function ug(e,t){switch(t){case`kg/m³`:return e*.001;case`g/mm³`:return e*1e3;case`lbs/in³`:return e*27.6799;default:return e}}function dg(e,t){switch(t){case`kg/m³`:return e/.001;case`g/mm³`:return e/1e3;case`lbs/in³`:return e/27.6799;default:return e}}function fg(e){return e===0?`0`:parseFloat(e.toPrecision(6)).toString()}var pg=class{btn;panel;placeholderEl;formEl;selectEl;densityEl;densityUnitSelectEl;lengthUnitEl;massUnitEl;calcBtn;resultsEl;errorEl;volVal;areaVal;massVal;centroidVal;selectedShapeId=null;rawProps=null;canonicalDensityGcm3=null;currentDensityUnit=`g/cm³`;centroidHandler=null;openHandler=null;constructor(e){this.btn=document.createElement(`button`),this.btn.className=`btn btn-ghost btn-square btn-sm rounded-md absolute bottom-6 right-8 z-[100] panel-bg border border-base-content/10 text-base-content/60`,this.btn.title=`Shape Properties`,this.btn.innerHTML=_h,e.appendChild(this.btn),this.panel=document.createElement(`div`),this.panel.className=`absolute bottom-[68px] right-6 w-[300px] bg-base-100/95 backdrop-blur-xl border border-base-content/10 rounded-lg p-4 z-[200] shadow-[0_4px_24px_rgba(0,0,0,0.5)] text-base-content text-[13px] hidden`,this.panel.innerHTML=this.buildHTML(),e.appendChild(this.panel),this.bindRefs(),this.bindEvents(),this.loadMaterials()}buildHTML(){return`
5046
+ `}bindEvents(){this.fitEl.addEventListener(`click`,()=>{this.onFitView?.()}),this.paramsEl.addEventListener(`click`,()=>{this.onParamsToggle?.()}),this.fabEl.querySelector(`[data-action="camera"]`)?.addEventListener(`click`,()=>{let e=lf.current.cameraMode===`perspective`?`orthographic`:`perspective`;lf.update({cameraMode:e}),ih(`cameraMode`,e),this.onCameraSwitch(e)}),this.fabEl.querySelector(`[data-action="grid"]`)?.addEventListener(`click`,()=>{let e=!lf.current.showGrid;lf.update({showGrid:e}),ih(`showGrid`,e)}),this.sectionViewEl.querySelector(`[data-action="section-view"]`)?.addEventListener(`click`,()=>{let e=!lf.current.sectionView;lf.update({sectionView:e}),this.onSectionViewToggle?.(e)}),this.fabEl.querySelector(`[data-action="theme"]`)?.addEventListener(`click`,()=>{let e=mg()?`fluidcad-light`:`fluidcad-dark`;document.documentElement.setAttribute(`data-theme`,e),this.syncThemeButton(),ih(`theme`,e)})}get panelHost(){return this.wrapper}setFitHandler(e){this.onFitView=e}setFitButtonVisible(e){this.fitEl.style.display=e?``:`none`}setParamsToggleHandler(e){this.onParamsToggle=e}setParamsButtonVisible(e){this.paramsEl.style.display=e?``:`none`}setParamsButtonActive(e){this.paramsEl.className=e?fg+` mt-2`:`btn btn-circle btn-sm panel-bg border border-base-content/10 text-base-content/60 mt-2`}setSectionViewToggleHandler(e){this.onSectionViewToggle=e}setSectionViewVisible(e){this.sectionViewEl.style.display=e?``:`none`}setSectionViewActive(e){let t=this.sectionViewEl.querySelector(`[data-action="section-view"]`);t&&(t.className=e?fg:dg)}setProjectionLocked(e){let t=this.fabEl.querySelector(`[data-action="camera"]`);t&&(t.disabled=e)}syncThemeButton(){let e=this.fabEl.querySelector(`[data-action="theme"]`);e&&(e.innerHTML=mg()?Lh:Rh,e.title=mg()?`Switch to light theme`:`Switch to dark theme`);let t=this.fabEl.querySelector(`[data-theme-label]`);t&&(t.textContent=mg()?`Light theme`:`Dark theme`)}sync(){let e=lf.current,t=this.fabEl.querySelector(`[data-action="grid"]`);t&&(t.className=e.showGrid?fg:dg);let n=this.fabEl.querySelector(`[data-camera-label]`);if(n&&(n.textContent=e.cameraMode===`orthographic`?`Orthographic`:`Perspective`),this.sectionViewEl.style.display!==`none`){let t=this.sectionViewEl.querySelector(`[data-action="section-view"]`);t&&(t.className=e.sectionView?fg:dg)}}},gg=class{mesh=null;show(e,t,n){this.clear(e);let r=new U(new ha(n,16,16),new mr({color:16729088,depthTest:!1}));r.position.set(t.x,t.y,t.z),r.renderOrder=999,r.userData.isMetaShape=!0,e.add(r),this.mesh=r}clear(e){this.mesh&&=(this.mesh.geometry.dispose(),this.mesh.material.dispose(),e.remove(this.mesh),null)}};function _g(e,t){if(t.userData.isMetaShape)return;let n=t;(n.isMesh||n.isLine||n.isPoints)&&n.geometry&&(n.geometry.computeBoundingBox(),n.geometry.boundingBox&&e.union(n.geometry.boundingBox.clone().applyMatrix4(n.matrixWorld)));for(let n of t.children)_g(e,n)}var vg=2,yg=2,bg=.75,xg=class{ctx;modeManager;settingsPanel;sceneObjects=[];highlightedShapeId=null;faceHighlightMeshes=[];hasRendered=!1;lastFitBox=null;isTrimming=!1;isRegionPicking=!1;isDrawing=!1;selectionHandler=null;centroidIndicator=new gg;hoverState=null;hoverFaceOverlayMeshes=[];hoverRafId=null;isMouseDown=!1;highlightedEntities=[];activeSketchId=null;hiddenShapeIds=new Set;shapeOpacities=new Map;constructor(e){let t=document.getElementById(e);this.ctx=new of(t),this.modeManager=new hf(this.ctx),this.settingsPanel=new hg(t,e=>this.ctx.switchCamera(e)),this.settingsPanel.setFitHandler(()=>this.fitViewToScene()),lf.current.cameraMode===`perspective`&&this.ctx.switchCamera(`perspective`),this.settingsPanel.setSectionViewToggleHandler(e=>{e?this.applySectionView():this.clearSectionView()}),this.initClickDetection(),this.initHoverDetection()}get sceneContext(){return this.ctx}get currentSceneObjects(){return this.sceneObjects}setSelectionHandler(e){this.selectionHandler=e}get settingsPanelHost(){return this.settingsPanel.panelHost}setParamsToggleHandler(e){this.settingsPanel.setParamsToggleHandler(e)}setParamsButtonVisible(e){this.settingsPanel.setParamsButtonVisible(e)}setParamsButtonActive(e){this.settingsPanel.setParamsButtonActive(e)}lookAlongSketchNormal(e){this.modeManager.enforceSketchNormal(e)}initClickDetection(){let e=this.ctx.renderer.domElement,t=0,n=0;e.addEventListener(`mousedown`,e=>{t=e.clientX,n=e.clientY}),e.addEventListener(`mouseup`,e=>{if(!this.selectionHandler||this.isTrimming||this.isRegionPicking||this.modeManager.isSketchMode)return;let r=e.clientX-t,i=e.clientY-n;if(r*r+i*i>64)return;this.clearHover();let a={additive:e.ctrlKey||e.metaKey||e.shiftKey},o=this.pickAt(e.clientX,e.clientY);o?this.selectionHandler(o.shapeId,o.sub,a):this.selectionHandler(null,null,a)})}pickAt(e,t){let n=this.ctx.camera,r=this.ctx.renderer.domElement.getBoundingClientRect(),i=(e-r.left)/r.width*2-1,a=-((t-r.top)/r.height)*2+1,o=this.ctx.createPickingRaycaster(i,a);o.params.Line={threshold:this.computeEdgePickThreshold()},o.params.Line2={threshold:8};let s=[],c=[];this.ctx.scene.traverse(e=>{e.userData.isMetaShape||(e.isMesh&&e.userData.faceMapping?s.push(e):(e.isLine||e.userData.isEdgeLine)&&e.userData.edgeIndex!==void 0&&c.push(e))});let l=s.length>0?o.intersectObjects(s,!1):[],u=c.length>0?o.intersectObjects(c,!1):[];if(l.length===0&&u.length===0)return null;let d=new R;n.getWorldDirection(d);let f;for(let e of l){if(!e.face){f=e;break}if(e.face.normal.clone().transformDirection(e.object.matrixWorld).dot(d)<0){f=e;break}}let p=f==null?1/0:f.distance,m=o.ray.origin,h=o.ray.direction,g=new R,_=new R;for(let e of u){let t=e.pointOnLine;if(t?g.copy(t):g.copy(e.point),h.dot(_.copy(g).sub(m))<=p+.001){let t=e.object.userData.edgeIndex,n=this.findShapeIdForObject(e.object);if(n)return{shapeId:n,sub:{type:`edge`,index:t}}}}if(f){let e=f.object.userData.faceMapping;if(!e||f.faceIndex==null)return null;let t=e[f.faceIndex];if(t==null)return null;let n=this.findShapeIdForObject(f.object);if(n)return{shapeId:n,sub:{type:`face`,index:t}}}return null}findShapeIdForObject(e){let t=e;for(;t;){if(t.userData.shapeId&&!t.userData.isMetaShape)return t.userData.shapeId;t=t.parent}return null}toggleSketchMode(e){this.modeManager.sketchEnabled=e}setFileName(e){}updateView(e,t=!1,n){if(this.sceneObjects=e,this.highlightedShapeId=null,this.highlightedEntities=[],this.faceHighlightMeshes=[],this.hoverState=null,this.hoverFaceOverlayMeshes=[],this.ctx.renderer.domElement.style.cursor=``,this.removeCompiledMesh(),t)this.activeSketchId=this.findRollbackActiveSketchId(e,n);else{let t=this.findActiveObject(e);t?.type===`sketch`&&t.object?.plane?(this.modeManager.isSketchMode?this.modeManager.enforceSketchNormal(t.object.plane):this.modeManager.enterSketchMode(t.object.plane),this.activeSketchId=t.id,this.settingsPanel.setProjectionLocked(!0),this.settingsPanel.setFitButtonVisible(!1)):(this.activeSketchId=null,this.modeManager.enterDefaultMode(),this.settingsPanel.setProjectionLocked(!1),this.settingsPanel.setFitButtonVisible(!0),this.lastFitBox=null)}let r=Om(e,this.activeSketchId,this.ctx.camera,this.isRegionPicking);if(this.ctx.scene.add(r),this.applyShapeOverridesAndPrune(e),this.activeSketchId&&this.applySketchModeGhosting(),this.settingsPanel.setSectionViewVisible(this.modeManager.isSketchMode),this.modeManager.isSketchMode&&(this.settingsPanel.setSectionViewActive(lf.current.sectionView),lf.current.sectionView&&this.applySectionView()),!this.hasRendered&&!this.modeManager.isSketchMode||this.modeManager.isSketchMode&&!t&&!this.isTrimming&&!this.isRegionPicking&&!this.isDrawing){let e=new Gt;_g(e,r),!e.isEmpty()&&!this.isBoxContained(e)&&(this.ctx.fitToBox(e,!0),this.lastFitBox=e.clone(),this.hasRendered=!0)}!this.hasRendered&&this.modeManager.isSketchMode&&(this.hasRendered=!0),this.ctx.requestRender()}highlightShape(e){this.clearHighlight();let t=this.findShapeById(e);if(!t)return;let n=this.findMeshByShapeId(e);if(!n)return;let r=t.shapeType===`solid`||t.shapeType===`face`;n.traverse(e=>{if(!e.material)return;let t=e.isLine||e.userData.isEdgeLine;if(r&&e instanceof U&&!t){let t=e.material;e.userData.originalColor=t.color.getHex(),t.color.set(Wd.highlightColor),(t.opacity<1||t.transparent)&&(e.userData.originalOpacity=t.opacity,e.userData.originalTransparent=t.transparent,t.opacity=1,t.transparent=!1)}else !r&&t&&(e.userData.originalColor=e.material.color.getHex(),e.material.color.set(Wd.highlightColor),e.userData.originalLineWidth=e.material.linewidth,e.material.linewidth=vg,e.material.opacity<1&&(e.userData.originalOpacity=e.material.opacity,e.material.opacity=1))}),this.highlightedShapeId=e,this.highlightedEntities=[],this.ctx.render()}clearHighlight(){if(!(!this.highlightedShapeId&&this.highlightedEntities.length===0&&this.faceHighlightMeshes.length===0)){this.ctx.scene.traverse(e=>{e.userData.originalColor!==void 0&&(e.material.color.setHex(e.userData.originalColor),delete e.userData.originalColor),e.userData.originalOpacity!==void 0&&(e.material.opacity=e.userData.originalOpacity,delete e.userData.originalOpacity),e.userData.originalTransparent!==void 0&&(e.material.transparent=e.userData.originalTransparent,delete e.userData.originalTransparent),e.userData.originalLineWidth!==void 0&&(e.material.linewidth=e.userData.originalLineWidth,delete e.userData.originalLineWidth)});for(let e of this.faceHighlightMeshes)e.parent?.remove(e),e.geometry.dispose(),e.material.dispose();this.faceHighlightMeshes=[],this.highlightedShapeId=null,this.highlightedEntities=[],this.ctx.render()}}highlightEntities(e){this.clearHighlight();for(let t of e)t.sub.type===`face`?this.applyFaceHighlight(t.shapeId,t.sub.index):this.applyEdgeHighlight(t.shapeId,t.sub.index);this.highlightedEntities=e,this.ctx.render()}highlightFace(e,t){this.highlightEntities([{shapeId:e,sub:{type:`face`,index:t}}])}highlightEdge(e,t){this.highlightEntities([{shapeId:e,sub:{type:`edge`,index:t}}])}applyFaceHighlight(e,t){this.ctx.scene.traverse(n=>{if(!n.isMesh)return;let r=n.userData.faceMapping;if(!r)return;let i=!1,a=n;for(;a;){if(a.userData.shapeId===e&&!a.userData.isMetaShape){i=!0;break}a=a.parent}if(!i)return;let o=n,s=o.geometry,c=s.index;if(!c)return;let l=c.array,u=s.getAttribute(`position`).array,d=[];for(let e=0;e<r.length;e++)if(r[e]===t){let t=l[e*3]*3,n=l[e*3+1]*3,r=l[e*3+2]*3;d.push(u[t],u[t+1],u[t+2]),d.push(u[n],u[n+1],u[n+2]),d.push(u[r],u[r+1],u[r+2])}if(d.length===0)return;let f=new H;f.setAttribute(`position`,new V(new Float32Array(d),3));let p=new U(f,new va({color:Wd.highlightColor,polygonOffset:!0,polygonOffsetFactor:-2,polygonOffsetUnits:-1}));(o.parent??this.ctx.scene).add(p),this.faceHighlightMeshes.push(p)})}applyEdgeHighlight(e,t){this.ctx.scene.traverse(n=>{if(!n.isLine&&!n.userData.isEdgeLine||n.userData.edgeIndex!==t)return;let r=!1,i=n;for(;i;){if(i.userData.shapeId===e&&!i.userData.isMetaShape){r=!0;break}i=i.parent}r&&n.userData.originalColor===void 0&&(n.userData.originalColor=n.material.color.getHex(),n.material.color.set(Wd.highlightColor),n.userData.originalLineWidth=n.material.linewidth,n.material.linewidth=vg)})}initHoverDetection(){let e=this.ctx.renderer.domElement;e.addEventListener(`mousedown`,()=>{this.isMouseDown=!0,this.clearHover()}),e.addEventListener(`mouseup`,()=>{this.isMouseDown=!1}),e.addEventListener(`mousemove`,e=>{this.isMouseDown||this.isTrimming||this.isRegionPicking||this.modeManager.isSketchMode||this.hoverRafId===null&&(this.hoverRafId=requestAnimationFrame(()=>{this.hoverRafId=null,this.updateHover(e.clientX,e.clientY)}))}),e.addEventListener(`mouseleave`,()=>{this.clearHover()})}updateHover(e,t){if(!this.selectionHandler)return;let n=this.pickAt(e,t);if(!(this.hoverState&&n&&this.hoverState.shapeId===n.shapeId&&this.hoverState.sub?.type===n.sub?.type&&this.hoverState.sub?.index===n.sub?.index)){if(!n){this.hoverState&&this.clearHover();return}if(this.highlightedEntities.some(e=>e.shapeId===n.shapeId&&e.sub.type===n.sub?.type&&e.sub.index===n.sub?.index)){this.hoverState&&this.clearHover();return}this.clearHover(),this.hoverState=n,this.ctx.renderer.domElement.style.cursor=`pointer`,n.sub?.type===`face`?this.applyHoverFace(n.shapeId,n.sub.index):n.sub?.type===`edge`&&this.applyHoverEdge(n.shapeId,n.sub.index)}}clearHover(){for(let e of this.hoverFaceOverlayMeshes)e.parent?.remove(e),e.geometry.dispose(),e.material.dispose();this.hoverFaceOverlayMeshes=[],this.ctx.scene.traverse(e=>{e.userData.hoverOriginalColor!==void 0&&(e.material.color.setHex(e.userData.hoverOriginalColor),delete e.userData.hoverOriginalColor),e.userData.hoverOriginalLineWidth!==void 0&&(e.material.linewidth=e.userData.hoverOriginalLineWidth,delete e.userData.hoverOriginalLineWidth)}),this.hoverState=null,this.ctx.renderer.domElement.style.cursor=``,this.ctx.requestRender()}applyHoverFace(e,t){this.ctx.scene.traverse(n=>{if(!n.isMesh)return;let r=n.userData.faceMapping;if(!r)return;let i=!1,a=n;for(;a;){if(a.userData.shapeId===e&&!a.userData.isMetaShape){i=!0;break}a=a.parent}if(!i)return;let o=n,s=o.geometry,c=s.index;if(!c)return;let l=c.array,u=s.getAttribute(`position`).array,d=[];for(let e=0;e<r.length;e++)if(r[e]===t){let t=l[e*3]*3,n=l[e*3+1]*3,r=l[e*3+2]*3;d.push(u[t],u[t+1],u[t+2]),d.push(u[n],u[n+1],u[n+2]),d.push(u[r],u[r+1],u[r+2])}if(d.length===0)return;let f=new H;f.setAttribute(`position`,new V(new Float32Array(d),3));let p=new U(f,new va({color:Wd.highlightColor,polygonOffset:!0,polygonOffsetFactor:-2,polygonOffsetUnits:-1}));(o.parent??this.ctx.scene).add(p),this.hoverFaceOverlayMeshes.push(p)}),this.ctx.requestRender()}applyHoverEdge(e,t){this.ctx.scene.traverse(n=>{if(!n.isLine&&!n.userData.isEdgeLine||n.userData.edgeIndex!==t)return;let r=!1,i=n;for(;i;){if(i.userData.shapeId===e&&!i.userData.isMetaShape){r=!0;break}i=i.parent}r&&(n.userData.hoverOriginalColor=n.material.color.getHex(),n.material.color.set(Wd.highlightColor),n.userData.hoverOriginalLineWidth=n.material.linewidth,n.material.linewidth=yg)}),this.ctx.requestRender()}showCentroid(e){let t=this.computeCentroidRadius();this.centroidIndicator.show(this.ctx.scene,e,t),this.ctx.requestRender()}clearCentroid(){this.centroidIndicator.clear(this.ctx.scene),this.ctx.requestRender()}dispose(){this.ctx.dispose()}computeEdgePickThreshold(){let e=this.ctx.camera,t=this.ctx.renderer.domElement.getBoundingClientRect().height||1,n,r=e;if(r.isOrthographicCamera)n=(r.top-r.bottom)/(r.zoom||1);else{let t=new R;this.ctx.cameraControls.getTarget(t);let i=e.position.distanceTo(t),a=r.fov*Math.PI/180;n=2*i*Math.tan(a/2)}return n/t*8}computeCentroidRadius(){let e=this.ctx.scene.getObjectByName(`compiledMesh`);if(e){let t=new Gt;if(_g(t,e),!t.isEmpty())return t.getSize(new R).length()*.015}return 2}fitViewToScene(){let e=this.ctx.scene.getObjectByName(`compiledMesh`);if(!e)return;let t=new Gt;_g(t,e),t.isEmpty()||this.ctx.fitToBox(t,!0)}findShapeById(e){for(let t of this.sceneObjects)for(let n of t.sceneShapes)if(n.shapeId===e)return n}findMeshByShapeId(e){let t;return this.ctx.scene.traverse(n=>{n.userData.shapeId===e&&(t=n)}),t}findActiveObject(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(!n.parentId||e.find(e=>e.id===n.parentId)?.type===`part`)return n}}findRollbackActiveSketchId(e,t){if(t==null||t<0||t>=e.length)return null;let n=e[t];for(;n;){if(n.type===`sketch`)return n.id;if(!n.parentId)return null;n=e.find(e=>e.id===n.parentId)}return null}isBoxContained(e){if(!this.lastFitBox)return!1;let t=this.lastFitBox.getCenter(new R),n=this.lastFitBox.getSize(new R).length()/2*af;if(n===0)return!1;let r=e.getCenter(new R),i=e.getSize(new R).length()/2;return t.distanceTo(r)+i<=n}rebuildSceneMesh(){if(!this.sceneObjects)return;this.removeCompiledMesh();let e=Om(this.sceneObjects,this.activeSketchId,this.ctx.camera,this.isRegionPicking);this.ctx.scene.add(e),this.applyShapeOverridesAndPrune(this.sceneObjects),this.modeManager.isSketchMode&&lf.current.sectionView&&this.applySectionView(),this.ctx.requestRender()}setShapeVisibility(e,t){t?this.hiddenShapeIds.delete(e):this.hiddenShapeIds.add(e),this.applyVisibilityForId(e,t),this.ctx.requestRender()}isShapeHidden(e){return this.hiddenShapeIds.has(e)}applyVisibilityForId(e,t){this.ctx.scene.traverse(n=>{n.userData.shapeId===e&&(n.visible=t)})}setShapeTransparency(e,t){t>=1?this.shapeOpacities.delete(e):this.shapeOpacities.set(e,t),this.applyOpacityForId(e,t),this.ctx.requestRender()}getShapeTransparency(e){return this.shapeOpacities.get(e)??1}resetAllTransparency(){if(this.shapeOpacities.size===0)return;let e=Array.from(this.shapeOpacities.keys());this.shapeOpacities.clear();for(let t of e)this.applyOpacityForId(t,1);this.ctx.requestRender()}applyOpacityForId(e,t){let n=[];this.ctx.scene.traverse(t=>{t.userData.shapeId===e&&n.push(t)});for(let e of n)this.applyOpacityToSubtree(e,t)}applyOpacityToSubtree(e,t){e.traverse(e=>{let n=e.material;if(!n)return;let r=Array.isArray(n)?n:[n];for(let e of r)e.transparent=t<1,e.opacity=t,e.depthWrite=t>=1,e.needsUpdate=!0})}applyShapeOverridesAndPrune(e){let t=new Set;for(let n of e)if(n.sceneShapes)for(let e of n.sceneShapes)e.isMetaShape||e.shapeId&&t.add(e.shapeId);for(let e of this.hiddenShapeIds)t.has(e)||this.hiddenShapeIds.delete(e);for(let e of this.shapeOpacities.keys())t.has(e)||this.shapeOpacities.delete(e);this.ctx.scene.traverse(e=>{let t=e.userData.shapeId;if(typeof t!=`string`)return;this.hiddenShapeIds.has(t)&&(e.visible=!1);let n=this.shapeOpacities.get(t);n!==void 0&&this.applyOpacityToSubtree(e,n)})}applySketchModeGhosting(){let e=this.ctx.scene.getObjectByName(`compiledMesh`);if(!e)return;let t=Wd.backgroundColor;for(let n of e.children)this.tintForGhosting(n,t)}tintForGhosting(e,t){if(e.userData.isSketchRoot||e.renderOrder>=999)return;let n=e.material;if(n){let e=Array.isArray(n)?n:[n];for(let n of e)!n.color||!(n.color instanceof B)||(n.userData.ghostOriginalColor||(n.userData.ghostOriginalColor=n.color.clone()),n.color.copy(n.userData.ghostOriginalColor).lerp(t,bg))}for(let n of e.children)this.tintForGhosting(n,t)}applySectionView(){let e=this.modeManager.sectionPlane;if(!e)return;let t=this.ctx.scene.getObjectByName(`compiledMesh`);t&&(this.forEachClippableMaterial(t,t=>{t.clippingPlanes=[e]}),this.ctx.requestRender())}clearSectionView(){let e=this.ctx.scene.getObjectByName(`compiledMesh`);e&&(this.forEachClippableMaterial(e,e=>{e.clippingPlanes=[]}),this.ctx.requestRender())}forEachClippableMaterial(e,t){if(e.userData.isSketchRoot)return;let n=e.material;if(n){let e=Array.isArray(n)?n:[n];for(let n of e)t(n)}for(let n of e.children)this.forEachClippableMaterial(n,t)}removeCompiledMesh(){let e=this.ctx.scene.getObjectByName(`compiledMesh`);e&&(e.traverse(e=>{e.geometry?.dispose(),Array.isArray(e.material)?e.material.forEach(e=>e.dispose()):e.material?.dispose()}),this.ctx.scene.remove(e))}};function Sg(e){switch(e){case`inch`:return 16.387064;case`foot`:return 28316.846592;case`yard`:return 764554.857984;case`meter`:return 1e6;default:return .001}}function Cg(e){switch(e){case`inch`:return`in`;case`foot`:return`ft`;case`yard`:return`yd`;case`meter`:return`m`;default:return`mm`}}function wg(e,t,n){let r=t===`kg`?1e3:t===`lbs`?453.592:1;return e*Sg(n)/r}function Tg(e,t){switch(t){case`kg/m³`:return e*.001;case`g/mm³`:return e*1e3;case`lbs/in³`:return e*27.6799;default:return e}}function Eg(e,t){switch(t){case`kg/m³`:return e/.001;case`g/mm³`:return e/1e3;case`lbs/in³`:return e/27.6799;default:return e}}function Dg(e){return e===0?`0`:parseFloat(e.toPrecision(6)).toString()}var Og=class{btn;panel;placeholderEl;formEl;selectEl;densityEl;densityUnitSelectEl;lengthUnitEl;massUnitEl;calcBtn;resultsEl;errorEl;volVal;areaVal;massVal;centroidVal;selectedShapeId=null;rawProps=null;canonicalDensityGcm3=null;currentDensityUnit=`g/cm³`;centroidHandler=null;openHandler=null;constructor(e){this.btn=document.createElement(`button`),this.btn.className=`btn btn-ghost btn-square btn-sm rounded-md absolute bottom-6 right-8 z-[100] panel-bg border border-base-content/10 text-base-content/60`,this.btn.title=`Shape Properties`,this.btn.innerHTML=jh,e.appendChild(this.btn),this.panel=document.createElement(`div`),this.panel.className=`absolute bottom-[68px] right-6 w-[300px] bg-base-100/95 backdrop-blur-xl border border-base-content/10 rounded-lg p-4 z-[200] shadow-[0_4px_24px_rgba(0,0,0,0.5)] text-base-content text-[13px] hidden`,this.panel.innerHTML=this.buildHTML(),e.appendChild(this.panel),this.bindRefs(),this.bindEvents(),this.loadMaterials()}buildHTML(){return`
5025
5047
  <div class="flex items-center justify-between mb-3">
5026
5048
  <span class="text-xs font-semibold text-base-content/70 uppercase tracking-wider">Shape Properties</span>
5027
5049
  <button class="btn btn-ghost btn-xs btn-square" data-action="panel-close">×</button>
@@ -5085,20 +5107,20 @@ void main() {
5085
5107
  <span class="text-base-content/90 text-xs font-medium" data-ref="centroid">—</span>
5086
5108
  </div>
5087
5109
  </div>
5088
- `}bindRefs(){this.placeholderEl=this.panel.querySelector(`[data-ref="placeholder"]`),this.formEl=this.panel.querySelector(`[data-ref="form"]`),this.selectEl=this.panel.querySelector(`[data-ref="material"]`),this.densityEl=this.panel.querySelector(`[data-ref="density"]`),this.densityUnitSelectEl=this.panel.querySelector(`[data-ref="density-unit"]`),this.lengthUnitEl=this.panel.querySelector(`[data-ref="length-unit"]`),this.massUnitEl=this.panel.querySelector(`[data-ref="mass-unit"]`),this.calcBtn=this.panel.querySelector(`[data-action="calculate"]`),this.resultsEl=this.panel.querySelector(`[data-ref="results"]`),this.errorEl=this.panel.querySelector(`[data-ref="error"]`),this.volVal=this.panel.querySelector(`[data-ref="vol"]`),this.areaVal=this.panel.querySelector(`[data-ref="area"]`),this.massVal=this.panel.querySelector(`[data-ref="mass"]`),this.centroidVal=this.panel.querySelector(`[data-ref="centroid"]`)}get isOpen(){return!this.panel.classList.contains(`hidden`)}setCentroidHandler(e){this.centroidHandler=e}setOpenHandler(e){this.openHandler=e}bindEvents(){this.btn.addEventListener(`click`,()=>this.toggle()),this.panel.querySelector(`[data-action="panel-close"]`).addEventListener(`click`,()=>this.close()),this.selectEl.addEventListener(`change`,()=>{let e=this.selectEl.options[this.selectEl.selectedIndex];e?.dataset.density&&(this.currentDensityUnit=e.dataset.densityUnit||`g/cm³`,this.canonicalDensityGcm3=ug(parseFloat(e.dataset.density),this.currentDensityUnit),this.updateDensityUnitSelect(),this.updateDensityDisplay())}),this.densityEl.addEventListener(`input`,()=>{let e=parseFloat(this.densityEl.value);isNaN(e)||(this.canonicalDensityGcm3=ug(e,this.currentDensityUnit))}),this.densityUnitSelectEl.addEventListener(`change`,()=>{this.currentDensityUnit=this.densityUnitSelectEl.value,this.updateDensityDisplay()}),this.lengthUnitEl.addEventListener(`change`,()=>this.renderResults()),this.massUnitEl.addEventListener(`change`,()=>this.renderResults()),this.calcBtn.addEventListener(`click`,()=>this.calculate())}updateDensityUnitSelect(){if(Array.from(this.densityUnitSelectEl.options).find(e=>e.value===this.currentDensityUnit))this.densityUnitSelectEl.value=this.currentDensityUnit;else{let e=document.createElement(`option`);e.value=this.currentDensityUnit,e.textContent=this.currentDensityUnit,this.densityUnitSelectEl.appendChild(e),this.densityUnitSelectEl.value=this.currentDensityUnit}}updateDensityDisplay(){this.canonicalDensityGcm3!==null&&(this.densityEl.value=fg(dg(this.canonicalDensityGcm3,this.currentDensityUnit)))}toggle(){this.panel.classList.contains(`hidden`)?this.open():this.close()}open(){this.openHandler?.(),this.panel.classList.remove(`hidden`),this.btn.className=`btn btn-soft btn-primary btn-square btn-sm rounded-md absolute bottom-6 right-8 z-[100] panel-bg border border-base-content/10`}close(){this.panel.classList.add(`hidden`),this.btn.className=`btn btn-ghost btn-square btn-sm rounded-md absolute bottom-6 right-8 z-[100] panel-bg border border-base-content/10 text-base-content/60`}async loadMaterials(){let e=await Im();if(!e)return;this.selectEl.innerHTML=``;for(let t of e){let e=document.createElement(`option`);e.textContent=t.name,e.dataset.density=String(t.density),e.dataset.densityUnit=t.densityUnit,this.selectEl.appendChild(e)}let t=this.selectEl.options[0];t?.dataset.density&&(this.currentDensityUnit=t.dataset.densityUnit||`g/cm³`,this.canonicalDensityGcm3=ug(parseFloat(t.dataset.density),this.currentDensityUnit),this.updateDensityUnitSelect(),this.updateDensityDisplay())}async calculate(){if(this.selectedShapeId){this.calcBtn.disabled=!0,this.errorEl.classList.add(`hidden`),this.resultsEl.classList.add(`hidden`);try{if(this.rawProps=await Fm(this.selectedShapeId),!this.rawProps){this.showError(`Failed to calculate properties.`);return}this.renderResults()}catch{this.showError(`Network error while fetching properties.`)}finally{this.calcBtn.disabled=!1}}}renderResults(){if(!this.rawProps)return;let e=this.lengthUnitEl.value,t=this.massUnitEl.value,n=cg(e),r=`${this.rawProps.volumeMm3.toFixed(4)} ${n}\u00B3`,i=`${this.rawProps.surfaceAreaMm2.toFixed(4)} ${n}\u00B2`,a=lg(this.canonicalDensityGcm3??0,`g`,e),o=this.rawProps.volumeMm3*a,s;s=t===`kg`?`${(o/1e3).toFixed(4)} kg`:t===`lbs`?`${(o/453.592).toFixed(4)} lbs`:`${o.toFixed(4)} g`;let{centroid:c}=this.rawProps,l=e=>e.toFixed(4),u=`(${l(c.x)}, ${l(c.y)}, ${l(c.z)}) ${n}`;this.volVal.textContent=r,this.areaVal.textContent=i,this.massVal.textContent=s,this.centroidVal.textContent=u,this.resultsEl.classList.remove(`hidden`),this.centroidHandler?.(c)}showError(e){this.errorEl.textContent=e,this.errorEl.classList.remove(`hidden`)}setSelectedShape(e){e!==this.selectedShapeId&&(this.rawProps=null,this.resultsEl.classList.add(`hidden`),this.errorEl.classList.add(`hidden`),this.centroidHandler?.(null),this.selectedShapeId=e,e?(this.placeholderEl.classList.add(`hidden`),this.formEl.classList.remove(`hidden`)):(this.placeholderEl.classList.remove(`hidden`),this.formEl.classList.add(`hidden`)))}show(e){this.setSelectedShape(e),this.open()}},mg={plane:`Plane`,circle:`Circle`,cylinder:`Cylinder`,sphere:`Sphere`,torus:`Torus`,cone:`Cone`,other:`Surface`},hg={line:`Line`,circle:`Circle`,arc:`Arc`,ellipse:`Ellipse`,other:`Curve`},gg=class{el;abortController=null;constructor(e){this.el=document.createElement(`div`),this.el.className=`absolute bottom-[22px] right-16 w-[200px] panel-bg border border-base-content/10 rounded-lg p-3 z-[150] shadow-[0_4px_24px_rgba(0,0,0,0.5)] text-base-content text-xs pointer-events-none select-none hidden`,e.appendChild(this.el)}async showForFace(e,t){this.abortController&&this.abortController.abort(),this.abortController=new AbortController,this.el.innerHTML=`<div class="text-base-content/50 text-[11px] text-center py-1">Loading…</div>`,this.el.classList.remove(`hidden`);let n=this.abortController.signal,r=await Nm(e,t,n);if(!r){n.aborted||this.el.classList.add(`hidden`);return}this.renderFace(r)}async showForEdge(e,t){this.abortController&&this.abortController.abort(),this.abortController=new AbortController,this.el.innerHTML=`<div class="text-base-content/50 text-[11px] text-center py-1">Loading…</div>`,this.el.classList.remove(`hidden`);let n=this.abortController.signal,r=await Pm(e,t,n);if(!r){n.aborted||this.el.classList.add(`hidden`);return}this.renderEdge(r)}hide(){this.abortController&&=(this.abortController.abort(),null),this.el.classList.add(`hidden`)}renderFace(e){let t=mg[e.surfaceType]??`Surface`,n=[];e.surfaceType===`plane`&&e.areaMm2!=null?n.push({label:`Area`,value:`${e.areaMm2.toFixed(4)} mm\u00B2`}):e.surfaceType===`circle`&&e.radius!=null||e.surfaceType===`cylinder`&&e.radius!=null||e.surfaceType===`sphere`&&e.radius!=null?n.push({label:`Radius`,value:`${e.radius.toFixed(4)} mm`}):e.surfaceType===`torus`?(e.majorRadius!=null&&n.push({label:`Major R`,value:`${e.majorRadius.toFixed(4)} mm`}),e.minorRadius!=null&&n.push({label:`Minor R`,value:`${e.minorRadius.toFixed(4)} mm`})):e.surfaceType===`cone`&&e.halfAngleDeg!=null?n.push({label:`Half-angle`,value:`${e.halfAngleDeg.toFixed(2)}\u00B0`}):e.areaMm2!=null&&n.push({label:`Area`,value:`${e.areaMm2.toFixed(4)} mm\u00B2`}),this.renderPanel(t,n)}renderEdge(e){let t=hg[e.curveType]??`Curve`,n=[];e.curveType===`line`?e.length!=null&&n.push({label:`Length`,value:`${e.length.toFixed(4)} mm`}):e.curveType===`circle`?e.radius!=null&&n.push({label:`Radius`,value:`${e.radius.toFixed(4)} mm`}):e.curveType===`arc`?(e.radius!=null&&n.push({label:`Radius`,value:`${e.radius.toFixed(4)} mm`}),e.length!=null&&n.push({label:`Length`,value:`${e.length.toFixed(4)} mm`})):e.curveType===`ellipse`?(e.majorRadius!=null&&n.push({label:`Major R`,value:`${e.majorRadius.toFixed(4)} mm`}),e.minorRadius!=null&&n.push({label:`Minor R`,value:`${e.minorRadius.toFixed(4)} mm`})):e.length!=null&&n.push({label:`Length`,value:`${e.length.toFixed(4)} mm`}),this.renderPanel(t,n)}renderPanel(e,t){let n=t.map(e=>`<div class="flex justify-between items-baseline py-0.5"><span class="text-base-content/50 text-[11px]">${e.label}</span><span class="text-base-content/90 text-xs font-medium">${e.value}</span></div>`).join(``);this.el.innerHTML=`<div class="badge badge-primary badge-outline badge-sm mb-2">${e}</div>${n}`,this.el.classList.remove(`hidden`)}},_g={aline:`aline`,"axis-from-edge":`axis`,"axis-middle":`axis`,"copy-circular-2d":`copy-circular2d`,"copy-linear-2d":`copy-linear2d`,cut:`cut`,"cut-symmetric":`cut`,"extrude-by-distance":`extrude`,"extrude-by-two-distance":`extrude`,"extrude-symmetric":`extrude`,"extrude-to-face":`extrude`,hline:`hline`,"lazy-select":`select`,"line-two-points":`line`,"mirror-feature":`mirror`,"mirror-shape":`mirror`,"mirror-shape-2d":`mirror2d`,"one-object-tline":`tline`,"plane-from-face":`plane`,"repeat-circular":`copy-circular`,"repeat-linear":`copy-linear`,"repeat-matrix":`copy-linear`,"slot-from-edge":`slot`,"tarc-to-point":`tarc`,"tarc-to-point-tangent":`tarc`,"tarc-with-tangent":`tarc`,tline:`tline`,"two-objects-tarc":`tarc`,"two-objects-tcircle":`arc`,"two-objects-tline":`tline`,vline:`vline`};function vg(e,t){return e&&_g[e]?_g[e]:t||`solid`}var yg=`flex items-center gap-2 px-3 py-2 panel-bg border border-base-content/10 rounded-md cursor-pointer select-none shrink-0`,bg=class{header;body;panel;sceneObjects=[];collapsedGroups=new Set;selectedIds=new Set;expanded=!0;activeDropdown=null;dropdownCleanup=null;activeTransparencyPopover=null;onHighlightShape;onExportShapes;onToggleVisibility;isShapeHidden;onSetTransparency;getTransparency;onResetAllTransparency;constructor(e,t,n,r,i,a,o,s){this.panel=e,this.onHighlightShape=t,this.onExportShapes=n,this.onToggleVisibility=r,this.isShapeHidden=i,this.onSetTransparency=a,this.getTransparency=o,this.onResetAllTransparency=s,this.header=document.createElement(`div`),this.header.className=yg,this.header.innerHTML=`
5089
- <span class="flex items-center justify-center w-5 h-5 opacity-50 transition-transform rotate-90">${Uh}</span>
5110
+ `}bindRefs(){this.placeholderEl=this.panel.querySelector(`[data-ref="placeholder"]`),this.formEl=this.panel.querySelector(`[data-ref="form"]`),this.selectEl=this.panel.querySelector(`[data-ref="material"]`),this.densityEl=this.panel.querySelector(`[data-ref="density"]`),this.densityUnitSelectEl=this.panel.querySelector(`[data-ref="density-unit"]`),this.lengthUnitEl=this.panel.querySelector(`[data-ref="length-unit"]`),this.massUnitEl=this.panel.querySelector(`[data-ref="mass-unit"]`),this.calcBtn=this.panel.querySelector(`[data-action="calculate"]`),this.resultsEl=this.panel.querySelector(`[data-ref="results"]`),this.errorEl=this.panel.querySelector(`[data-ref="error"]`),this.volVal=this.panel.querySelector(`[data-ref="vol"]`),this.areaVal=this.panel.querySelector(`[data-ref="area"]`),this.massVal=this.panel.querySelector(`[data-ref="mass"]`),this.centroidVal=this.panel.querySelector(`[data-ref="centroid"]`)}get isOpen(){return!this.panel.classList.contains(`hidden`)}setCentroidHandler(e){this.centroidHandler=e}setOpenHandler(e){this.openHandler=e}bindEvents(){this.btn.addEventListener(`click`,()=>this.toggle()),this.panel.querySelector(`[data-action="panel-close"]`).addEventListener(`click`,()=>this.close()),this.selectEl.addEventListener(`change`,()=>{let e=this.selectEl.options[this.selectEl.selectedIndex];e?.dataset.density&&(this.currentDensityUnit=e.dataset.densityUnit||`g/cm³`,this.canonicalDensityGcm3=Tg(parseFloat(e.dataset.density),this.currentDensityUnit),this.updateDensityUnitSelect(),this.updateDensityDisplay())}),this.densityEl.addEventListener(`input`,()=>{let e=parseFloat(this.densityEl.value);isNaN(e)||(this.canonicalDensityGcm3=Tg(e,this.currentDensityUnit))}),this.densityUnitSelectEl.addEventListener(`change`,()=>{this.currentDensityUnit=this.densityUnitSelectEl.value,this.updateDensityDisplay()}),this.lengthUnitEl.addEventListener(`change`,()=>this.renderResults()),this.massUnitEl.addEventListener(`change`,()=>this.renderResults()),this.calcBtn.addEventListener(`click`,()=>this.calculate())}updateDensityUnitSelect(){if(Array.from(this.densityUnitSelectEl.options).find(e=>e.value===this.currentDensityUnit))this.densityUnitSelectEl.value=this.currentDensityUnit;else{let e=document.createElement(`option`);e.value=this.currentDensityUnit,e.textContent=this.currentDensityUnit,this.densityUnitSelectEl.appendChild(e),this.densityUnitSelectEl.value=this.currentDensityUnit}}updateDensityDisplay(){this.canonicalDensityGcm3!==null&&(this.densityEl.value=Dg(Eg(this.canonicalDensityGcm3,this.currentDensityUnit)))}toggle(){this.panel.classList.contains(`hidden`)?this.open():this.close()}open(){this.openHandler?.(),this.panel.classList.remove(`hidden`),this.btn.className=`btn btn-soft btn-primary btn-square btn-sm rounded-md absolute bottom-6 right-8 z-[100] panel-bg border border-base-content/10`}close(){this.panel.classList.add(`hidden`),this.btn.className=`btn btn-ghost btn-square btn-sm rounded-md absolute bottom-6 right-8 z-[100] panel-bg border border-base-content/10 text-base-content/60`}async loadMaterials(){let e=await Ym();if(!e)return;this.selectEl.innerHTML=``;for(let t of e){let e=document.createElement(`option`);e.textContent=t.name,e.dataset.density=String(t.density),e.dataset.densityUnit=t.densityUnit,this.selectEl.appendChild(e)}let t=this.selectEl.options[0];t?.dataset.density&&(this.currentDensityUnit=t.dataset.densityUnit||`g/cm³`,this.canonicalDensityGcm3=Tg(parseFloat(t.dataset.density),this.currentDensityUnit),this.updateDensityUnitSelect(),this.updateDensityDisplay())}async calculate(){if(this.selectedShapeId){this.calcBtn.disabled=!0,this.errorEl.classList.add(`hidden`),this.resultsEl.classList.add(`hidden`);try{if(this.rawProps=await qm(this.selectedShapeId),!this.rawProps){this.showError(`Failed to calculate properties.`);return}this.renderResults()}catch{this.showError(`Network error while fetching properties.`)}finally{this.calcBtn.disabled=!1}}}renderResults(){if(!this.rawProps)return;let e=this.lengthUnitEl.value,t=this.massUnitEl.value,n=Cg(e),r=`${this.rawProps.volumeMm3.toFixed(4)} ${n}\u00B3`,i=`${this.rawProps.surfaceAreaMm2.toFixed(4)} ${n}\u00B2`,a=wg(this.canonicalDensityGcm3??0,`g`,e),o=this.rawProps.volumeMm3*a,s;s=t===`kg`?`${(o/1e3).toFixed(4)} kg`:t===`lbs`?`${(o/453.592).toFixed(4)} lbs`:`${o.toFixed(4)} g`;let{centroid:c}=this.rawProps,l=e=>e.toFixed(4),u=`(${l(c.x)}, ${l(c.y)}, ${l(c.z)}) ${n}`;this.volVal.textContent=r,this.areaVal.textContent=i,this.massVal.textContent=s,this.centroidVal.textContent=u,this.resultsEl.classList.remove(`hidden`),this.centroidHandler?.(c)}showError(e){this.errorEl.textContent=e,this.errorEl.classList.remove(`hidden`)}setSelectedShape(e){e!==this.selectedShapeId&&(this.rawProps=null,this.resultsEl.classList.add(`hidden`),this.errorEl.classList.add(`hidden`),this.centroidHandler?.(null),this.selectedShapeId=e,e?(this.placeholderEl.classList.add(`hidden`),this.formEl.classList.remove(`hidden`)):(this.placeholderEl.classList.remove(`hidden`),this.formEl.classList.add(`hidden`)))}show(e){this.setSelectedShape(e),this.open()}},kg={plane:`Plane`,circle:`Circle`,cylinder:`Cylinder`,sphere:`Sphere`,torus:`Torus`,cone:`Cone`,other:`Surface`},Ag={line:`Line`,circle:`Circle`,arc:`Arc`,ellipse:`Ellipse`,other:`Curve`},jg=class{el;abortController=null;constructor(e){this.el=document.createElement(`div`),this.el.className=`absolute bottom-6 right-[76px] w-[200px] panel-bg border border-base-content/10 rounded-lg p-3 z-[150] shadow-[0_4px_24px_rgba(0,0,0,0.5)] text-base-content text-xs pointer-events-none select-none hidden`,e.appendChild(this.el)}async showForFace(e,t){this.abortController&&this.abortController.abort(),this.abortController=new AbortController,this.el.innerHTML=`<div class="text-base-content/50 text-[11px] text-center py-1">Loading…</div>`,this.el.classList.remove(`hidden`);let n=this.abortController.signal,r=await Gm(e,t,n);if(!r){n.aborted||this.el.classList.add(`hidden`);return}this.renderFace(r)}async showForEdge(e,t){this.abortController&&this.abortController.abort(),this.abortController=new AbortController,this.el.innerHTML=`<div class="text-base-content/50 text-[11px] text-center py-1">Loading…</div>`,this.el.classList.remove(`hidden`);let n=this.abortController.signal,r=await Km(e,t,n);if(!r){n.aborted||this.el.classList.add(`hidden`);return}this.renderEdge(r)}hide(){this.abortController&&=(this.abortController.abort(),null),this.el.classList.add(`hidden`)}renderFace(e){let t=kg[e.surfaceType]??`Surface`,n=[];e.surfaceType===`plane`&&e.areaMm2!=null?n.push({label:`Area`,value:`${e.areaMm2.toFixed(4)} mm\u00B2`}):e.surfaceType===`circle`&&e.radius!=null||e.surfaceType===`cylinder`&&e.radius!=null||e.surfaceType===`sphere`&&e.radius!=null?n.push({label:`Radius`,value:`${e.radius.toFixed(4)} mm`}):e.surfaceType===`torus`?(e.majorRadius!=null&&n.push({label:`Major R`,value:`${e.majorRadius.toFixed(4)} mm`}),e.minorRadius!=null&&n.push({label:`Minor R`,value:`${e.minorRadius.toFixed(4)} mm`})):e.surfaceType===`cone`&&e.halfAngleDeg!=null?n.push({label:`Half-angle`,value:`${e.halfAngleDeg.toFixed(2)}\u00B0`}):e.areaMm2!=null&&n.push({label:`Area`,value:`${e.areaMm2.toFixed(4)} mm\u00B2`}),this.renderPanel(t,n)}renderEdge(e){let t=Ag[e.curveType]??`Curve`,n=[];e.curveType===`line`?e.length!=null&&n.push({label:`Length`,value:`${e.length.toFixed(4)} mm`}):e.curveType===`circle`?e.radius!=null&&n.push({label:`Radius`,value:`${e.radius.toFixed(4)} mm`}):e.curveType===`arc`?(e.radius!=null&&n.push({label:`Radius`,value:`${e.radius.toFixed(4)} mm`}),e.length!=null&&n.push({label:`Length`,value:`${e.length.toFixed(4)} mm`})):e.curveType===`ellipse`?(e.majorRadius!=null&&n.push({label:`Major R`,value:`${e.majorRadius.toFixed(4)} mm`}),e.minorRadius!=null&&n.push({label:`Minor R`,value:`${e.minorRadius.toFixed(4)} mm`})):e.length!=null&&n.push({label:`Length`,value:`${e.length.toFixed(4)} mm`}),this.renderPanel(t,n)}renderPanel(e,t){let n=t.map(e=>`<div class="flex justify-between items-baseline py-0.5"><span class="text-base-content/50 text-[11px]">${e.label}</span><span class="text-base-content/90 text-xs font-medium">${e.value}</span></div>`).join(``);this.el.innerHTML=`<div class="badge badge-primary badge-outline badge-sm mb-2">${e}</div>${n}<div class="text-[10px] text-base-content/40 mt-1.5 pt-1.5 border-t border-base-content/10">Ctrl+click another face/edge to measure</div>`,this.el.classList.remove(`hidden`)}},Mg={aline:`aline`,"axis-from-edge":`axis`,"axis-middle":`axis`,"copy-circular-2d":`copy-circular2d`,"copy-linear-2d":`copy-linear2d`,cut:`cut`,"cut-symmetric":`cut`,"extrude-by-distance":`extrude`,"extrude-by-two-distance":`extrude`,"extrude-symmetric":`extrude`,"extrude-to-face":`extrude`,hline:`hline`,"lazy-select":`select`,"line-two-points":`line`,"mirror-feature":`mirror`,"mirror-shape":`mirror`,"mirror-shape-2d":`mirror2d`,"one-object-tline":`tline`,"plane-from-face":`plane`,"repeat-circular":`copy-circular`,"repeat-linear":`copy-linear`,"repeat-matrix":`copy-linear`,"slot-from-edge":`slot`,"tarc-to-point":`tarc`,"tarc-to-point-tangent":`tarc`,"tarc-with-tangent":`tarc`,tline:`tline`,"two-objects-tarc":`tarc`,"two-objects-tcircle":`arc`,"two-objects-tline":`tline`,vline:`vline`};function Ng(e,t){return e&&Mg[e]?Mg[e]:t||`solid`}var Pg=`onerror="this.onerror=null;this.src='/icons/solid.png'"`,Fg=`flex items-center gap-2 px-3 py-2 panel-bg border border-base-content/10 rounded-md cursor-pointer select-none shrink-0`,Ig=class{header;body;panel;sceneObjects=[];collapsedGroups=new Set;selectedIds=new Set;expanded=!0;activeDropdown=null;dropdownCleanup=null;activeTransparencyPopover=null;onHighlightShape;onExportShapes;onToggleVisibility;isShapeHidden;onSetTransparency;getTransparency;onResetAllTransparency;constructor(e,t,n,r,i,a,o,s){this.panel=e,this.onHighlightShape=t,this.onExportShapes=n,this.onToggleVisibility=r,this.isShapeHidden=i,this.onSetTransparency=a,this.getTransparency=o,this.onResetAllTransparency=s,this.header=document.createElement(`div`),this.header.className=Fg,this.header.innerHTML=`
5111
+ <span class="flex items-center justify-center w-5 h-5 opacity-50 transition-transform rotate-90">${ig}</span>
5090
5112
  <span class="text-sm font-medium text-base-content/70">Shapes</span>
5091
5113
  `,this.body=document.createElement(`div`),this.body.className=`py-1 overflow-y-auto min-h-[33vh] flex-1`,this.header.addEventListener(`click`,()=>{this.expanded=!this.expanded,this.body.classList.toggle(`hidden`,!this.expanded),this.header.querySelector(`span`).classList.toggle(`rotate-90`,this.expanded)})}update(e){this.sceneObjects=e,this.render()}render(){let e=new Map;for(let t of this.sceneObjects)for(let n of t.sceneShapes){if(n.isMetaShape)continue;let r=n.shapeType||`unknown`;e.has(r)||e.set(r,[]),e.get(r).push({shapeId:n.shapeId||``,shapeType:r,sceneObjectName:t.name})}let t=``;for(let[n,r]of e){let e=n.charAt(0).toUpperCase()+n.slice(1),i=this.collapsedGroups.has(n);if(t+=`
5092
5114
  <div class="flex items-center gap-1 px-3 py-1.5 cursor-pointer hover:bg-base-content/[0.06] text-sm text-base-content/70 font-medium" data-shape-group="${n}">
5093
5115
  <span class="flex items-center justify-center w-5 h-5 opacity-50 hover:opacity-100 transition-transform ${i?``:`rotate-90`}">
5094
- ${Uh}
5116
+ ${ig}
5095
5117
  </span>
5096
5118
  <span>${e}</span>
5097
5119
  <span class="text-base-content/40 ml-1">${r.length}</span>
5098
5120
  </div>
5099
- `,!i){let e=new Map;for(let t of r)e.set(t.sceneObjectName,(e.get(t.sceneObjectName)??0)+1);let n=new Map;for(let i=0;i<r.length;i++){let a=r[i],o=(n.get(a.sceneObjectName)??0)+1;n.set(a.sceneObjectName,o);let s=(e.get(a.sceneObjectName)??1)>1?`${a.sceneObjectName} ${o}`:a.sceneObjectName,c=this.selectedIds.has(a.shapeId)?` bg-primary/10`:``,l=this.isShapeHidden(a.shapeId),u=l?Eh:Th,d=`<button class="ml-auto btn btn-ghost btn-square btn-xs ${l?`opacity-100 text-base-content/70`:`opacity-0 group-hover:opacity-100 text-base-content/40`} hover:text-base-content/70 shrink-0 [&>svg]:size-3.5" data-eye="${a.shapeId}">${u}</button>`,f=`<button class="opacity-0 group-hover:opacity-100 btn btn-ghost btn-square btn-xs text-base-content/40 hover:text-base-content/70 shrink-0" data-dots="${a.shapeId}">${Gh}</button>`;t+=`
5121
+ `,!i){let e=new Map;for(let t of r)e.set(t.sceneObjectName,(e.get(t.sceneObjectName)??0)+1);let n=new Map;for(let i=0;i<r.length;i++){let a=r[i],o=(n.get(a.sceneObjectName)??0)+1;n.set(a.sceneObjectName,o);let s=(e.get(a.sceneObjectName)??1)>1?`${a.sceneObjectName} ${o}`:a.sceneObjectName,c=this.selectedIds.has(a.shapeId)?` bg-primary/10`:``,l=this.isShapeHidden(a.shapeId),u=l?Bh:zh,d=`<button class="ml-auto btn btn-ghost btn-square btn-xs ${l?`opacity-100 text-base-content/70`:`opacity-0 group-hover:opacity-100 text-base-content/40`} hover:text-base-content/70 shrink-0 [&>svg]:size-3.5" data-eye="${a.shapeId}">${u}</button>`,f=`<button class="opacity-0 group-hover:opacity-100 btn btn-ghost btn-square btn-xs text-base-content/40 hover:text-base-content/70 shrink-0" data-dots="${a.shapeId}">${og}</button>`;t+=`
5100
5122
  <div class="group flex items-center gap-2 pl-9 pr-3 py-1 cursor-pointer hover:bg-base-content/[0.06] text-sm text-base-content/70${c}" data-shape-id="${a.shapeId}" data-shape-type="${a.shapeType}">
5101
- <img src="/icons/${a.shapeType}.png" class="w-4 h-4 object-contain" alt="" />
5123
+ <img src="/icons/${a.shapeType}.png" ${Pg} class="w-4 h-4 object-contain" alt="" />
5102
5124
  <span class="truncate">${s}</span>
5103
5125
  ${d}
5104
5126
  ${f}
@@ -5117,44 +5139,44 @@ void main() {
5117
5139
  <input type="range" min="0" max="100" value="${o}" class="range range-xs flex-1" data-ref="slider" />
5118
5140
  <span class="text-xs text-base-content/60 w-10 text-right" data-ref="value">${o}%</span>
5119
5141
  </div>
5120
- `,this.panel.appendChild(n),this.activeTransparencyPopover=n;let s=n.querySelector(`[data-ref="slider"]`),c=n.querySelector(`[data-ref="value"]`);s.addEventListener(`input`,()=>{let e=parseInt(s.value,10),n=e/100;c.textContent=`${e}%`;for(let e of t)this.onSetTransparency(e,n)}),n.querySelector(`[data-action="close"]`).addEventListener(`click`,()=>{this.closeTransparencyPopover()})}closeDropdown(){this.activeDropdown&&=(this.activeDropdown.remove(),null),this.dropdownCleanup&&=(this.dropdownCleanup(),null)}closeTransparencyPopover(){this.activeTransparencyPopover&&(this.activeTransparencyPopover.remove(),this.activeTransparencyPopover=null,this.onResetAllTransparency())}},xg=`flex items-center gap-2 px-3 py-2 panel-bg border border-base-content/10 rounded-md cursor-pointer select-none shrink-0`;function Sg(e){return e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`}var Cg=class{panel;fileLabel;timelineBody;contentWrapper;positioner;shapesPanel;loaded=!1;sceneObjects=[];rollbackStop=-1;collapsedIds=new Set;timelineExpanded=!0;activeDropdown=null;dropdownCleanup=null;showBuildTimings=!1;historyTotalLabel;hoverPopover=null;onImportFile;constructor(e,t,n,r,i,a,o,s,c){this.onImportFile=c,this.panel=document.createElement(`div`),this.panel.className=`absolute left-6 top-6 bottom-6 w-[220px] z-[99] flex flex-col gap-1 select-none hidden`,e.appendChild(this.panel),this.applyPanelWidth();let l=document.createElement(`div`);l.className=`flex items-center gap-1.5 px-1 pb-1 shrink-0`,l.innerHTML=`<img src="/logo.png" alt="FluidCAD" class="h-6 w-auto opacity-70" /><span class="text-[18px] font-bold text-base-content/70">FluidCAD</span>`,this.panel.appendChild(l);let u=document.createElement(`div`);u.className=`flex items-center gap-2 px-1 pb-1 shrink-0`,u.innerHTML=`
5121
- <span class="text-base-content/50 [&>svg]:size-4">${Kh}</span>
5142
+ `,this.panel.appendChild(n),this.activeTransparencyPopover=n;let s=n.querySelector(`[data-ref="slider"]`),c=n.querySelector(`[data-ref="value"]`);s.addEventListener(`input`,()=>{let e=parseInt(s.value,10),n=e/100;c.textContent=`${e}%`;for(let e of t)this.onSetTransparency(e,n)}),n.querySelector(`[data-action="close"]`).addEventListener(`click`,()=>{this.closeTransparencyPopover()})}closeDropdown(){this.activeDropdown&&=(this.activeDropdown.remove(),null),this.dropdownCleanup&&=(this.dropdownCleanup(),null)}closeTransparencyPopover(){this.activeTransparencyPopover&&(this.activeTransparencyPopover.remove(),this.activeTransparencyPopover=null,this.onResetAllTransparency())}},Lg=`flex items-center gap-2 px-3 py-2 panel-bg border border-base-content/10 rounded-md cursor-pointer select-none shrink-0`;function Rg(e){return e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`}var zg=class{panel;fileLabel;timelineBody;contentWrapper;positioner;shapesPanel;loaded=!1;sceneObjects=[];rollbackStop=-1;collapsedIds=new Set;timelineExpanded=!0;activeDropdown=null;dropdownCleanup=null;showBuildTimings=!1;historyTotalLabel;hoverPopover=null;onImportFile;constructor(e,t,n,r,i,a,o,s,c){this.onImportFile=c,this.panel=document.createElement(`div`),this.panel.className=`absolute left-6 top-6 bottom-6 w-[220px] z-[99] flex flex-col gap-1 select-none hidden`,e.appendChild(this.panel),this.applyPanelWidth();let l=document.createElement(`div`);l.className=`flex items-center gap-1.5 px-1 pb-1 shrink-0`,l.innerHTML=`<img src="/logo.png" alt="FluidCAD" class="h-6 w-auto opacity-70" /><span class="text-[18px] font-bold text-base-content/70">FluidCAD</span>`,this.panel.appendChild(l);let u=document.createElement(`div`);u.className=`flex items-center gap-2 px-1 pb-1 shrink-0`,u.innerHTML=`
5143
+ <span class="text-base-content/50 [&>svg]:size-4">${sg}</span>
5122
5144
  <span data-ref="filename" class="text-base text-base-content/70 truncate"></span>
5123
5145
  <button data-ref="import-btn" class="ml-auto w-5 h-5 min-h-0 btn btn-circle btn-ghost border border-base-content/30 hover:border-base-content/50 p-0 text-base-content/40 hover:text-base-content/70 shrink-0 tooltip tooltip-right" data-tip="Import File">
5124
5146
  <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
5125
5147
  </button>
5126
- `,this.panel.appendChild(u),this.fileLabel=u.querySelector(`[data-ref="filename"]`),u.querySelector(`[data-ref="import-btn"]`).addEventListener(`click`,()=>this.onImportFile()),this.positioner=document.createElement(`div`),this.positioner.className=`relative flex-1 min-h-0 overflow-hidden`,this.panel.appendChild(this.positioner),this.contentWrapper=document.createElement(`div`),this.contentWrapper.className=`absolute inset-0 flex flex-col gap-1 overflow-y-auto`,this.contentWrapper.style.transition=`transform 0.25s ease, opacity 0.25s ease`,this.positioner.appendChild(this.contentWrapper);let d=document.createElement(`div`);d.className=xg,d.innerHTML=`
5127
- <span data-ref="chevron" class="flex items-center justify-center w-5 h-5 opacity-50 transition-transform rotate-90">${Uh}</span>
5148
+ `,this.panel.appendChild(u),this.fileLabel=u.querySelector(`[data-ref="filename"]`),u.querySelector(`[data-ref="import-btn"]`).addEventListener(`click`,()=>this.onImportFile()),this.positioner=document.createElement(`div`),this.positioner.className=`relative flex-1 min-h-0 overflow-hidden`,this.panel.appendChild(this.positioner),this.contentWrapper=document.createElement(`div`),this.contentWrapper.className=`absolute inset-0 flex flex-col gap-1 overflow-y-auto`,this.contentWrapper.style.transition=`transform 0.25s ease, opacity 0.25s ease`,this.positioner.appendChild(this.contentWrapper);let d=document.createElement(`div`);d.className=Lg,d.innerHTML=`
5149
+ <span data-ref="chevron" class="flex items-center justify-center w-5 h-5 opacity-50 transition-transform rotate-90">${ig}</span>
5128
5150
  <span class="text-sm font-medium text-base-content/70">History</span>
5129
5151
  <span data-ref="history-total" class="text-xs text-base-content/40 tabular-nums hidden"></span>
5130
- <button data-ref="history-dots" class="ml-auto btn btn-ghost btn-square btn-xs text-base-content/40 hover:text-base-content/70 shrink-0">${Gh}</button>
5131
- `,this.contentWrapper.appendChild(d),this.historyTotalLabel=d.querySelector(`[data-ref="history-total"]`);let f=d.querySelector(`[data-ref="history-dots"]`);f.addEventListener(`click`,e=>{e.stopPropagation(),this.showHistoryDropdown(f)}),this.timelineBody=document.createElement(`div`),this.timelineBody.className=`py-1 overflow-y-auto min-h-0`,this.contentWrapper.appendChild(this.timelineBody),d.addEventListener(`click`,()=>{this.timelineExpanded=!this.timelineExpanded,this.timelineBody.classList.toggle(`hidden`,!this.timelineExpanded),d.querySelector(`[data-ref="chevron"]`).classList.toggle(`rotate-90`,this.timelineExpanded)}),this.shapesPanel=new bg(this.panel,t,n,r,i,a,o,s),this.contentWrapper.appendChild(this.shapesPanel.header),this.contentWrapper.appendChild(this.shapesPanel.body)}update(e,t,n){if(this.sceneObjects=e,this.rollbackStop=t,n){let e=n.split(`/`).pop()||n;this.fileLabel.textContent=e}this.loaded||(this.loaded=!0,this.panel.classList.remove(`hidden`)),this.renderTimeline(!0),this.shapesPanel.update(e),this.updateHistoryTotal()}setShowBuildTimings(e){this.showBuildTimings!==e&&(this.showBuildTimings=e,this.applyPanelWidth(),this.updateHistoryTotal(),this.loaded&&this.renderTimeline())}slideOut(){this.contentWrapper.style.transform=`translateX(-100%)`,this.contentWrapper.style.opacity=`0`,this.contentWrapper.style.pointerEvents=`none`}slideIn(){this.contentWrapper.style.transform=``,this.contentWrapper.style.opacity=``,this.contentWrapper.style.pointerEvents=``}get toolbarHost(){return this.positioner}renderTimeline(e=!1){let t=this.sceneObjects,n=this.rollbackStop,r=new Set,i=new Map;for(let e of t)e.uniqueType!==`lazy-select`&&e.parentId&&(r.add(e.parentId),e.hasError&&i.set(e.parentId,!0));let a=``;for(let e=0;e<t.length;e++){let o=t[e];if(o.parentId||o.uniqueType===`lazy-select`)continue;let s=o.id!=null&&r.has(o.id),c=o.id!=null&&this.collapsedIds.has(o.id),l=o.id!=null&&i.get(o.id)===!0,u=o.hasError===!0||l;if(a+=this.renderTimelineItem(o,e,n,!1,s,c,u),s&&!c)for(let e=0;e<t.length;e++)t[e].uniqueType!==`lazy-select`&&t[e].parentId===o.id&&(a+=this.renderTimelineItem(t[e],e,n,!0,!1,!1,t[e].hasError===!0))}if(this.timelineBody.innerHTML=a,this.timelineBody.querySelectorAll(`[data-index]`).forEach(e=>{e.addEventListener(`click`,t=>{if(t.target.closest(`[data-toggle]`))return;let n=parseInt(e.dataset.index,10);this.rollbackTo(n),this.goToSource(this.sceneObjects[n])}),e.addEventListener(`dblclick`,t=>{if(t.target.closest(`[data-toggle]`))return;let n=parseInt(e.dataset.index,10);this.addBreakpointAfter(n),this.goToSource(this.sceneObjects[n])})}),this.timelineBody.querySelectorAll(`[data-toggle]`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation();let n=e.dataset.toggle;this.collapsedIds.has(n)?this.collapsedIds.delete(n):this.collapsedIds.add(n),this.renderTimeline()})}),this.showBuildTimings&&this.timelineBody.querySelectorAll(`[data-index]`).forEach(e=>{let t=parseInt(e.dataset.index,10),n=this.sceneObjects[t];!n||!n.profileCategories||n.profileCategories.length===0||(e.addEventListener(`mouseenter`,()=>{this.showProfilePopover(e,n.profileCategories,n.buildDurationMs)}),e.addEventListener(`mouseleave`,()=>{this.closeProfilePopover()}))}),e){let e=this.timelineBody.querySelector(`[data-current="true"]`);e&&e.scrollIntoView({block:`nearest`})}}renderTimelineItem(e,t,n,r,i,a,o){let s=t===n,c=t>n,l=e.visible===!1,u=e.name||`Unknown`,d=e.type===`part`?`/icons/box.png`:`/icons/${vg(e.uniqueType,e.type)}.png`,f=`flex items-center gap-1 px-3 py-1.5 cursor-pointer hover:bg-base-content/[0.06] text-sm`;r&&(f+=` pl-7`),s&&(f+=` border-l-2 border-primary bg-primary/10`),o?f+=` text-error`:s?f+=` text-primary`:c||l?f+=` text-base-content/60`:f+=` text-base-content/80`;let p=l?`w-4 h-4 object-contain grayscale opacity-60`:`w-4 h-4 object-contain`,m=o?`<span class="text-error shrink-0 [&>svg]:w-2.5 [&>svg]:h-2.5">${Jh}</span>`:``,h=``;if(i){let t=a?``:`rotate-90`;h=`<span data-toggle="${e.id}" class="flex items-center justify-center w-5 h-5 opacity-50 hover:opacity-100 transition-transform ${t}">
5132
- ${Uh}
5133
- </span>`}else h=`<span class="w-4"></span>`;let g=this.showBuildTimings&&!e.fromCache&&e.buildDurationMs!=null,_=g?`<span class="ml-auto shrink-0 text-xs text-base-content/40 tabular-nums">${Sg(e.buildDurationMs)}</span>`:``,v=g?`shrink-0 text-base-content/40 [&>svg]:w-4 [&>svg]:h-4`:`ml-auto shrink-0 text-base-content/40 [&>svg]:w-4 [&>svg]:h-4`,y=e.fromCache?`<span class="${v}">${bh}</span>`:`<span class="${v}">${xh}</span>`;return`
5152
+ <button data-ref="history-dots" class="ml-auto btn btn-ghost btn-square btn-xs text-base-content/40 hover:text-base-content/70 shrink-0">${og}</button>
5153
+ `,this.contentWrapper.appendChild(d),this.historyTotalLabel=d.querySelector(`[data-ref="history-total"]`);let f=d.querySelector(`[data-ref="history-dots"]`);f.addEventListener(`click`,e=>{e.stopPropagation(),this.showHistoryDropdown(f)}),this.timelineBody=document.createElement(`div`),this.timelineBody.className=`py-1 overflow-y-auto min-h-0`,this.contentWrapper.appendChild(this.timelineBody),d.addEventListener(`click`,()=>{this.timelineExpanded=!this.timelineExpanded,this.timelineBody.classList.toggle(`hidden`,!this.timelineExpanded),d.querySelector(`[data-ref="chevron"]`).classList.toggle(`rotate-90`,this.timelineExpanded)}),this.shapesPanel=new Ig(this.panel,t,n,r,i,a,o,s),this.contentWrapper.appendChild(this.shapesPanel.header),this.contentWrapper.appendChild(this.shapesPanel.body)}update(e,t,n){if(this.sceneObjects=e,this.rollbackStop=t,n){let e=n.split(`/`).pop()||n;this.fileLabel.textContent=e}this.loaded||(this.loaded=!0,this.panel.classList.remove(`hidden`)),this.renderTimeline(!0),this.shapesPanel.update(e),this.updateHistoryTotal()}setShowBuildTimings(e){this.showBuildTimings!==e&&(this.showBuildTimings=e,this.applyPanelWidth(),this.updateHistoryTotal(),this.loaded&&this.renderTimeline())}slideOut(){this.contentWrapper.style.transform=`translateX(-100%)`,this.contentWrapper.style.opacity=`0`,this.contentWrapper.style.pointerEvents=`none`}slideIn(){this.contentWrapper.style.transform=``,this.contentWrapper.style.opacity=``,this.contentWrapper.style.pointerEvents=``}get toolbarHost(){return this.positioner}renderTimeline(e=!1){let t=this.sceneObjects,n=this.rollbackStop,r=new Set,i=new Map;for(let e of t)e.uniqueType!==`lazy-select`&&e.parentId&&(r.add(e.parentId),e.hasError&&i.set(e.parentId,!0));let a=``;for(let e=0;e<t.length;e++){let o=t[e];if(o.parentId||o.uniqueType===`lazy-select`)continue;let s=o.id!=null&&r.has(o.id),c=o.id!=null&&this.collapsedIds.has(o.id),l=o.id!=null&&i.get(o.id)===!0,u=o.hasError===!0||l;if(a+=this.renderTimelineItem(o,e,n,!1,s,c,u),s&&!c)for(let e=0;e<t.length;e++)t[e].uniqueType!==`lazy-select`&&t[e].parentId===o.id&&(a+=this.renderTimelineItem(t[e],e,n,!0,!1,!1,t[e].hasError===!0))}if(this.timelineBody.innerHTML=a,this.timelineBody.querySelectorAll(`[data-index]`).forEach(e=>{e.addEventListener(`click`,t=>{if(t.target.closest(`[data-toggle]`))return;let n=parseInt(e.dataset.index,10);this.rollbackTo(n),this.goToSource(this.sceneObjects[n])}),e.addEventListener(`dblclick`,t=>{if(t.target.closest(`[data-toggle]`))return;let n=parseInt(e.dataset.index,10);this.addBreakpointAfter(n),this.goToSource(this.sceneObjects[n])})}),this.timelineBody.querySelectorAll(`[data-toggle]`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation();let n=e.dataset.toggle;this.collapsedIds.has(n)?this.collapsedIds.delete(n):this.collapsedIds.add(n),this.renderTimeline()})}),this.showBuildTimings&&this.timelineBody.querySelectorAll(`[data-index]`).forEach(e=>{let t=parseInt(e.dataset.index,10),n=this.sceneObjects[t];!n||!n.profileCategories||n.profileCategories.length===0||(e.addEventListener(`mouseenter`,()=>{this.showProfilePopover(e,n.profileCategories,n.buildDurationMs)}),e.addEventListener(`mouseleave`,()=>{this.closeProfilePopover()}))}),e){let e=this.timelineBody.querySelector(`[data-current="true"]`);e&&e.scrollIntoView({block:`nearest`})}}renderTimelineItem(e,t,n,r,i,a,o){let s=t===n,c=t>n,l=e.visible===!1,u=e.name||`Unknown`,d=e.type===`part`?`/icons/box.png`:`/icons/${Ng(e.uniqueType,e.type)}.png`,f=`flex items-center gap-1 px-3 py-1.5 cursor-pointer hover:bg-base-content/[0.06] text-sm`;r&&(f+=` pl-7`),s&&(f+=` border-l-2 border-primary bg-primary/10`),o?f+=` text-error`:s?f+=` text-primary`:c||l?f+=` text-base-content/60`:f+=` text-base-content/80`;let p=l?`w-4 h-4 object-contain grayscale opacity-60`:`w-4 h-4 object-contain`,m=o?`<span class="text-error shrink-0 [&>svg]:w-2.5 [&>svg]:h-2.5">${lg}</span>`:``,h=``;if(i){let t=a?``:`rotate-90`;h=`<span data-toggle="${e.id}" class="flex items-center justify-center w-5 h-5 opacity-50 hover:opacity-100 transition-transform ${t}">
5154
+ ${ig}
5155
+ </span>`}else h=`<span class="w-4"></span>`;let g=this.showBuildTimings&&!e.fromCache&&e.buildDurationMs!=null,_=g?`<span class="ml-auto shrink-0 text-xs text-base-content/40 tabular-nums">${Rg(e.buildDurationMs)}</span>`:``,v=g?`shrink-0 text-base-content/40 [&>svg]:w-4 [&>svg]:h-4`:`ml-auto shrink-0 text-base-content/40 [&>svg]:w-4 [&>svg]:h-4`,y=e.fromCache?`<span class="${v}">${Ph}</span>`:`<span class="${v}">${Fh}</span>`;return`
5134
5156
  <div class="${f}" data-index="${t}" data-container="${e.isContainer??!1}" data-current="${s}">
5135
5157
  ${h}
5136
5158
  ${m}
5137
- <img src="${d}" class="${p}" alt="" />
5159
+ <img src="${d}" ${Pg} class="${p}" alt="" />
5138
5160
  <span class="truncate">${u}</span>
5139
5161
  ${_}
5140
5162
  ${y}
5141
5163
  </div>
5142
- `}updateHistoryTotal(){if(!this.showBuildTimings){this.historyTotalLabel.classList.add(`hidden`);return}let e=0,t=!1;for(let n of this.sceneObjects)n.parentId||n.fromCache||n.buildDurationMs==null||(e+=n.buildDurationMs,t=!0);if(!t){this.historyTotalLabel.classList.add(`hidden`);return}this.historyTotalLabel.textContent=`· ${Sg(e)}`,this.historyTotalLabel.classList.remove(`hidden`)}applyPanelWidth(){this.panel.classList.toggle(`w-[220px]`,!this.showBuildTimings),this.panel.classList.toggle(`w-[270px]`,this.showBuildTimings)}showHistoryDropdown(e){this.closeDropdown();let t=document.createElement(`div`);t.className=`absolute z-[200] panel-bg border border-base-content/10 rounded-md shadow-[0_4px_12px_rgba(0,0,0,0.4)]`;let n=e.getBoundingClientRect(),r=this.panel.getBoundingClientRect();t.style.top=`${n.bottom-r.top+2}px`,t.style.right=`${r.right-n.right}px`,t.innerHTML=`
5164
+ `}hasBuildTimings(){return this.sceneObjects.some(e=>!e.parentId&&!e.fromCache&&e.buildDurationMs!=null)}updateHistoryTotal(){if(!this.showBuildTimings){this.historyTotalLabel.classList.add(`hidden`);return}let e=0,t=!1;for(let n of this.sceneObjects)n.parentId||n.fromCache||n.buildDurationMs==null||(e+=n.buildDurationMs,t=!0);if(!t){this.historyTotalLabel.classList.add(`hidden`);return}this.historyTotalLabel.textContent=`· ${Rg(e)}`,this.historyTotalLabel.classList.remove(`hidden`)}applyPanelWidth(){this.panel.classList.toggle(`w-[220px]`,!this.showBuildTimings),this.panel.classList.toggle(`w-[270px]`,this.showBuildTimings)}showHistoryDropdown(e){this.closeDropdown();let t=document.createElement(`div`);t.className=`absolute z-[200] panel-bg border border-base-content/10 rounded-md shadow-[0_4px_12px_rgba(0,0,0,0.4)]`;let n=e.getBoundingClientRect(),r=this.panel.getBoundingClientRect();t.style.top=`${n.bottom-r.top+2}px`,t.style.right=`${r.right-n.right}px`,t.innerHTML=`
5143
5165
  <ul class="menu menu-xs p-1 min-w-[180px]">
5144
5166
  <li><button data-action="recompute" class="flex items-center gap-2">
5145
- <span class="flex items-center justify-center w-4 h-4 shrink-0 [&>svg]:size-3.5">${xh}</span>
5167
+ <span class="flex items-center justify-center w-4 h-4 shrink-0 [&>svg]:size-3.5">${Fh}</span>
5146
5168
  <span>Recompute scene</span>
5147
5169
  </button></li>
5148
5170
  <li><button data-action="toggle-timings" class="flex items-center gap-2">
5149
- ${this.showBuildTimings?`<span class="flex items-center justify-center w-4 h-4 shrink-0 text-primary [&>svg]:size-3">${qh}</span>`:`<span class="w-4 h-4 shrink-0"></span>`}
5171
+ ${this.showBuildTimings?`<span class="flex items-center justify-center w-4 h-4 shrink-0 text-primary [&>svg]:size-3">${cg}</span>`:`<span class="w-4 h-4 shrink-0"></span>`}
5150
5172
  <span>Show execution time</span>
5151
5173
  </button></li>
5152
5174
  </ul>
5153
- `,this.panel.appendChild(t),this.activeDropdown=t,t.querySelector(`[data-action="toggle-timings"]`).addEventListener(`click`,()=>{let e=!this.showBuildTimings;this.showBuildTimings=e,this.applyPanelWidth(),this.updateHistoryTotal(),Gm(`showBuildTimings`,e),this.closeDropdown(),this.renderTimeline()}),t.querySelector(`[data-action="recompute"]`).addEventListener(`click`,()=>{this.closeDropdown(),this.recomputeScene()});let i=n=>{!t.contains(n.target)&&!e.contains(n.target)&&this.closeDropdown()};setTimeout(()=>document.addEventListener(`click`,i),0),this.dropdownCleanup=()=>document.removeEventListener(`click`,i)}closeDropdown(){this.activeDropdown&&=(this.activeDropdown.remove(),null),this.dropdownCleanup&&=(this.dropdownCleanup(),null)}showProfilePopover(e,t,n){this.closeProfilePopover();let r=document.createElement(`div`);r.className=`absolute z-[201] panel-bg border border-base-content/10 rounded-md shadow-[0_4px_12px_rgba(0,0,0,0.4)] p-3 min-w-[200px] max-w-[280px]`;let i=e.getBoundingClientRect(),a=this.panel.getBoundingClientRect();r.style.left=`${i.right-a.left+8}px`,r.style.top=`${Math.max(0,i.top-a.top-4)}px`;let o=t.reduce((e,t)=>e+t.durationMs,0),s=t.map(e=>({...e}));n!==void 0&&n-o>.5&&s.push({category:`Other`,durationMs:Math.round((n-o)*10)/10,isOther:!0});let c=Math.max(...s.map(e=>e.durationMs),.1),l=``;for(let e of s){let t=c>0?e.durationMs/c*100:0,n=e.isOther?`bg-base-content/25`:t>60?`bg-warning/60`:`bg-primary/40`;l+=`
5175
+ `,this.panel.appendChild(t),this.activeDropdown=t,t.querySelector(`[data-action="toggle-timings"]`).addEventListener(`click`,()=>{let e=!this.showBuildTimings;this.showBuildTimings=e,this.applyPanelWidth(),this.updateHistoryTotal(),ih(`showBuildTimings`,e),this.closeDropdown(),this.renderTimeline(),e&&!this.hasBuildTimings()&&this.recomputeScene()}),t.querySelector(`[data-action="recompute"]`).addEventListener(`click`,()=>{this.closeDropdown(),this.recomputeScene()});let i=n=>{!t.contains(n.target)&&!e.contains(n.target)&&this.closeDropdown()};setTimeout(()=>document.addEventListener(`click`,i),0),this.dropdownCleanup=()=>document.removeEventListener(`click`,i)}closeDropdown(){this.activeDropdown&&=(this.activeDropdown.remove(),null),this.dropdownCleanup&&=(this.dropdownCleanup(),null)}showProfilePopover(e,t,n){this.closeProfilePopover();let r=document.createElement(`div`);r.className=`absolute z-[201] panel-bg border border-base-content/10 rounded-md shadow-[0_4px_12px_rgba(0,0,0,0.4)] p-3 min-w-[200px] max-w-[280px]`;let i=e.getBoundingClientRect(),a=this.panel.getBoundingClientRect();r.style.left=`${i.right-a.left+8}px`,r.style.top=`${Math.max(0,i.top-a.top-4)}px`;let o=t.reduce((e,t)=>e+t.durationMs,0),s=t.map(e=>({...e}));n!==void 0&&n-o>.5&&s.push({category:`Other`,durationMs:Math.round((n-o)*10)/10,isOther:!0});let c=Math.max(...s.map(e=>e.durationMs),.1),l=``;for(let e of s){let t=c>0?e.durationMs/c*100:0,n=e.isOther?`bg-base-content/25`:t>60?`bg-warning/60`:`bg-primary/40`;l+=`
5154
5176
  <div class="mb-1.5">
5155
5177
  <div class="flex justify-between text-xs mb-0.5">
5156
5178
  <span class="text-base-content/80 truncate mr-2">${this.escapeHtml(e.category)}</span>
5157
- <span class="text-base-content/50 tabular-nums shrink-0">${Sg(e.durationMs)}</span>
5179
+ <span class="text-base-content/50 tabular-nums shrink-0">${Rg(e.durationMs)}</span>
5158
5180
  </div>
5159
5181
  <div class="h-1 rounded-full bg-base-content/10 overflow-hidden">
5160
5182
  <div class="h-full rounded-full ${n}" style="width:${t}%"></div>
@@ -5162,12 +5184,12 @@ void main() {
5162
5184
  </div>
5163
5185
  `}let u=n===void 0?``:`<div class="flex justify-between text-xs text-base-content/40 mt-1 pt-1 border-t border-base-content/10">
5164
5186
  <span>Total</span>
5165
- <span class="tabular-nums">${Sg(n)}</span>
5187
+ <span class="tabular-nums">${Rg(n)}</span>
5166
5188
  </div>`;r.innerHTML=`
5167
5189
  <div class="text-xs font-medium text-base-content/60 mb-2">Build Time Breakdown</div>
5168
5190
  ${l}
5169
5191
  ${u}
5170
- `,this.panel.appendChild(r),this.hoverPopover=r}closeProfilePopover(){this.hoverPopover&&=(this.hoverPopover.remove(),null)}recomputeScene(){Lm()}rollbackTo(e){Rm(e)}addBreakpointAfter(e){let t=this.sceneObjects[e];!t||!t.sourceLocation||zm(t.sourceLocation)}goToSource(e){!e||!e.sourceLocation||Vm(e.sourceLocation)}escapeHtml(e){let t=document.createElement(`div`);return t.textContent=e,t.innerHTML}},wg=class{root;body;hasParams=!1;visible=!1;currentParams=[];debounceTimers=new Map;collapsedGroups=new Set;constructor(e){this.root=document.createElement(`div`),this.root.className=`w-[220px] mt-2 select-none hidden`,e.appendChild(this.root);let t=document.createElement(`div`);t.className=`panel-bg border border-base-content/10 rounded-md overflow-y-auto max-h-[60vh]`,this.root.appendChild(t);let n=document.createElement(`div`);n.className=`flex items-center justify-between px-3 pt-2 pb-1`,n.innerHTML=`
5192
+ `,this.panel.appendChild(r),this.hoverPopover=r}closeProfilePopover(){this.hoverPopover&&=(this.hoverPopover.remove(),null)}recomputeScene(){Xm()}rollbackTo(e){Zm(e)}addBreakpointAfter(e){let t=this.sceneObjects[e];!t||!t.sourceLocation||Qm(t.sourceLocation)}goToSource(e){!e||!e.sourceLocation||eh(e.sourceLocation)}escapeHtml(e){let t=document.createElement(`div`);return t.textContent=e,t.innerHTML}},Bg=class{root;body;hasParams=!1;visible=!1;currentParams=[];debounceTimers=new Map;collapsedGroups=new Set;constructor(e){this.root=document.createElement(`div`),this.root.className=`w-[220px] mt-2 select-none hidden`,e.appendChild(this.root);let t=document.createElement(`div`);t.className=`panel-bg border border-base-content/10 rounded-md overflow-y-auto max-h-[60vh]`,this.root.appendChild(t);let n=document.createElement(`div`);n.className=`flex items-center justify-between px-3 pt-2 pb-1`,n.innerHTML=`
5171
5193
  <span class="text-xs font-medium text-base-content/50 uppercase tracking-wider">Parameters</span>
5172
5194
  <button class="btn btn-ghost btn-xs btn-circle text-base-content/40 hover:text-base-content/70" title="Reset all to defaults" data-reset-params>
5173
5195
  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="w-3.5 h-3.5">
@@ -5252,12 +5274,12 @@ void main() {
5252
5274
  ${r}
5253
5275
  ${a}
5254
5276
  </div>
5255
- `}bindParamHandlers(){this.body.querySelectorAll(`[data-param-label]`).forEach(e=>{let t=e.dataset.paramLabel,n=e.dataset.paramType,r=e=>{let n=this.currentParams.find(e=>e.label===t),r=n&&typeof n.defaultValue==`number`?Number(e):e;fetch(`/api/set-param`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({label:t,value:r})}).catch(e=>console.error(`Set param failed:`,e))},i=e=>{let n=this.currentParams.find(e=>e.label===t),r=n?.options?.[0]&&typeof n.options[0].value==`number`?e.map(Number):e;fetch(`/api/set-param`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({label:t,value:r})}).catch(e=>console.error(`Set param failed:`,e))};n===`slider`?(e.addEventListener(`input`,()=>{let n=this.body.querySelector(`[data-param-display="${t}"]`);n&&(n.textContent=e.value)}),e.addEventListener(`change`,()=>{r(e.value)})):n===`number`||n===`text`?(e.addEventListener(`input`,()=>{this.debounceParam(t,()=>r(e.value))}),e.addEventListener(`blur`,()=>{this.flushParam(t,()=>r(e.value))})):n===`checkbox`?e.addEventListener(`change`,()=>{let n=e.checked;fetch(`/api/set-param`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({label:t,value:n})}).catch(e=>console.error(`Set param failed:`,e))}):n===`select`?e.addEventListener(`change`,()=>{r(e.value)}):n===`multi-select`?e.addEventListener(`change`,()=>{i(Array.from(e.selectedOptions,e=>e.value))}):n===`multi-checkboxes`?e.addEventListener(`change`,()=>{i(Array.from(e.querySelectorAll(`input[type="checkbox"]:checked`),e=>e.value))}):n===`color`?e.addEventListener(`input`,()=>{r(e.value)}):n===`multi-chips`&&e.addEventListener(`click`,t=>{let n=t.target.closest(`[data-chip-value]`);n&&(n.classList.toggle(`badge-primary`),n.classList.toggle(`badge-outline`),i(Array.from(e.querySelectorAll(`.badge-primary[data-chip-value]`),e=>e.dataset.chipValue)))})})}debounceParam(e,t){let n=this.debounceTimers.get(e);n&&clearTimeout(n),this.debounceTimers.set(e,setTimeout(()=>{this.debounceTimers.delete(e),t()},500))}flushParam(e,t){let n=this.debounceTimers.get(e);n&&(clearTimeout(n),this.debounceTimers.delete(e),t())}escapeHtml(e){let t=document.createElement(`div`);return t.textContent=e,t.innerHTML}},Tg={front:new R(0,-1,0),back:new R(0,1,0),left:new R(-1,0,0),right:new R(1,0,0),top:new R(0,0,1),bottom:new R(0,0,-1),"iso-ftr":new R(1,-1,1).normalize(),"iso-fbr":new R(1,-1,-1).normalize(),"iso-ftl":new R(-1,-1,1).normalize(),"iso-fbl":new R(-1,-1,-1).normalize(),"iso-btr":new R(1,1,1).normalize(),"iso-bbr":new R(1,1,-1).normalize(),"iso-btl":new R(-1,1,1).normalize(),"iso-bbl":new R(-1,1,-1).normalize()};function Eg(e,t,n){let r=Tg[e],i=Math.max(n,1);return{eye:t.clone().add(r.clone().multiplyScalar(i)),target:t.clone()}}function Dg(e,t,n,r){let i=e.clone().sub(t),a=i.length(),o=Math.acos(ht.clamp(i.z/Math.max(a,1e-9),-1,1)),s=Math.atan2(i.y,i.x);s+=n*ht.DEG2RAD,o=ht.clamp(o-r*ht.DEG2RAD,.001,Math.PI-.001);let c=Math.sin(o),l=new R(a*c*Math.cos(s),a*c*Math.sin(s),a*Math.cos(o));return{eye:t.clone().add(l),target:t.clone()}}function Og(e,t,n,r,i){switch(e.kind){case`current`:return null;case`named`:return Eg(e.name,t,n);case`orbit-from-current`:return Dg(r,i,e.azimuthDeg,e.elevationDeg);case`look-from`:return{eye:new R(e.eye[0],e.eye[1],e.eye[2]),target:e.target?new R(e.target[0],e.target[1],e.target[2]):t.clone()}}}function kg(e){let t=new Gt;return Ag(t,e),t}function Ag(e,t){if(t.userData.isConstructionPlane||!t.visible)return;let n=t;(n.isMesh||n.isLine||n.isPoints)&&n.geometry&&(n.geometry.computeBoundingBox(),n.geometry.boundingBox&&e.union(n.geometry.boundingBox.clone().applyMatrix4(n.matrixWorld)));for(let n of t.children)Ag(e,n)}var jg={width:800,height:800,showGrid:!1,showAxes:!1,transparent:!1,autoCrop:!1,fitToModel:!1,margin:0,view:{kind:`current`}};function Mg(e,t={}){return Fg(Pg(e,{...jg,...t}))}function Ng(e,t={}){let n={...jg,...t},r=Math.max(1,Math.floor(n.width/2)),i=Math.max(1,Math.floor(n.height/2)),a=[{x:0,y:0,view:{kind:`named`,name:`front`}},{x:r,y:0,view:{kind:`named`,name:`top`}},{x:0,y:i,view:{kind:`named`,name:`right`}},{x:r,y:i,view:{kind:`named`,name:`iso-ftr`}}],o=document.createElement(`canvas`);o.width=r*2,o.height=i*2;let s=o.getContext(`2d`);if(!s)return Promise.reject(Error(`Failed to get composite 2d context.`));n.transparent||(s.fillStyle=`#ffffff`,s.fillRect(0,0,o.width,o.height));for(let t of a){let a=Pg(e,{...n,width:r,height:i,view:t.view,autoCrop:!1,fitToModel:!0});s.drawImage(a,t.x,t.y)}return Fg(o)}function Pg(e,t){let{width:n,height:r,showGrid:i,showAxes:a,transparent:o,autoCrop:s,fitToModel:c,margin:l,view:u}=t,d=e.scene,f=e.camera,p=e.cameraControls,m=d.getObjectByName(`grid`),h=d.getObjectByName(`defaultAxesHelper`),g=d.getObjectByName(`sketchAxesHelper`),_=m?.visible,v=h?.visible,y=g?.visible,b=d.background,x=new R,S=new R;p.getPosition(x),p.getTarget(S);let C=f.zoom;m&&(m.visible=i),h&&(h.visible=a),g&&(g.visible=a),o&&(d.background=null);let w=n/r,T=f,E;if(T.isOrthographicCamera){E={left:T.left,right:T.right,top:T.top,bottom:T.bottom};let e=T.top-T.bottom;T.left=-w*e/2,T.right=w*e/2,T.updateProjectionMatrix()}else E={aspect:T.aspect},T.aspect=w,T.updateProjectionMatrix();let D=Lg(e);if(u.kind!==`current`){let e=Og(u,D.center,D.diameter,x,S);if(e){if(f.position.copy(e.eye),f.lookAt(e.target),T.isOrthographicCamera&&D.diameter>0){let e=T.right-T.left,t=T.top-T.bottom;T.zoom=Math.min(e/D.diameter,t/D.diameter)}else if(T.isPerspectiveCamera&&D.diameter>0){let t=T.fov*Math.PI/360,n=Math.atan(Math.tan(t)*T.aspect),r=Math.min(t,n),i=D.diameter/2/Math.sin(r),a=f.position.clone().sub(e.target).normalize();f.position.copy(e.target).add(a.multiplyScalar(i)),f.lookAt(e.target)}T.updateProjectionMatrix()}}else if(s||c){let e=d.getObjectByName(`compiledMesh`);if(e){let t=new Gt;if(zg(t,e),!t.isEmpty()){let e=t.getCenter(new R),n=t.getSize(new R).length()*Ud;if(n>0){let t=new R;if(f.getWorldDirection(t),f.position.copy(e).sub(t.clone().multiplyScalar(1e3)),f.lookAt(e),T.isOrthographicCamera){let e=T.right-T.left,t=T.top-T.bottom;T.zoom=Math.min(e/n,t/n)}T.updateProjectionMatrix()}}}}let ee=new xl({antialias:!0,alpha:!0,preserveDrawingBuffer:!0});ee.setSize(n,r),ee.setPixelRatio(1),ee.toneMapping=4,ee.outputColorSpace=Ie;let O=new R;f.getWorldDirection(O),d.traverse(e=>{e.isDirectionalLight&&e.position.copy(O.clone().multiplyScalar(-10))}),ee.render(d,f);let k=ee.domElement;if(s){let t=Rg(e,n,r,l);if(t){let e=document.createElement(`canvas`);e.width=t.w,e.height=t.h,e.getContext(`2d`).drawImage(ee.domElement,t.x,t.y,t.w,t.h,0,0,t.w,t.h),k=e}}let te=Ig(k,n,r);return m&&(m.visible=_),h&&(h.visible=v),g&&(g.visible=y),d.background=b,T.isOrthographicCamera?(T.left=E.left,T.right=E.right,T.top=E.top,T.bottom=E.bottom):T.aspect=E.aspect,f.zoom=C,f.position.copy(x),f.lookAt(S),T.updateProjectionMatrix(),p.setLookAt(x.x,x.y,x.z,S.x,S.y,S.z,!1),ee.dispose(),e.requestRender(),te}function Fg(e){return new Promise((t,n)=>{e.toBlob(e=>{e?t(e):n(Error(`Failed to create PNG blob.`))},`image/png`)})}function Ig(e,t,n){let r=document.createElement(`canvas`);r.width=e.width||t,r.height=e.height||n;let i=r.getContext(`2d`);return i?(i.drawImage(e,0,0),r):e}function Lg(e){let t=kg(e.scene.getObjectByName(`compiledMesh`)??e.scene);return t.isEmpty()?{center:new R,diameter:100}:{center:t.getCenter(new R),diameter:t.getSize(new R).length()*Ud}}function Rg(e,t,n,r){let i=e.scene.getObjectByName(`compiledMesh`);if(!i)return null;let a=new Gt;if(zg(a,i),a.isEmpty())return null;let o=e.camera,s=[new R(a.min.x,a.min.y,a.min.z),new R(a.max.x,a.min.y,a.min.z),new R(a.min.x,a.max.y,a.min.z),new R(a.max.x,a.max.y,a.min.z),new R(a.min.x,a.min.y,a.max.z),new R(a.max.x,a.min.y,a.max.z),new R(a.min.x,a.max.y,a.max.z),new R(a.max.x,a.max.y,a.max.z)],c=1/0,l=1/0,u=-1/0,d=-1/0;for(let e of s){e.project(o);let r=(e.x+1)/2*t,i=(1-e.y)/2*n;c=Math.min(c,r),l=Math.min(l,i),u=Math.max(u,r),d=Math.max(d,i)}let f=Math.max(0,Math.floor(c-r)),p=Math.max(0,Math.floor(l-r)),m=Math.min(t,Math.ceil(u+r)),h=Math.min(n,Math.ceil(d+r)),g=m-f,_=h-p;return g<=0||_<=0?null:{x:f,y:p,w:g,h:_}}function zg(e,t){if(t.userData.isConstructionPlane||!t.visible)return;let n=t;(n.isMesh||n.isLine||n.isPoints)&&n.geometry&&(n.geometry.computeBoundingBox(),n.geometry.boundingBox&&e.union(n.geometry.boundingBox.clone().applyMatrix4(n.matrixWorld)));for(let n of t.children)zg(e,n)}var Bg=class{overlay;pillsContainer;stepSection;stlSection;pngSection;includeColorsToggle;resolutionSelect;customSection;angularInput;linearInput;showGridToggle;showAxesToggle;transparentToggle;autoCropToggle;marginSection;marginInput;widthInput;heightInput;exportBtn;statusEl;shapeIds=[];selectedFormat=`step`;constructor(e,t){this.sceneCtx=t,this.overlay=document.createElement(`div`),this.overlay.className=`fixed inset-0 z-[300] bg-black/50 flex items-center justify-center hidden`,this.overlay.innerHTML=this.buildHTML(),e.appendChild(this.overlay),this.pillsContainer=this.overlay.querySelector(`[data-ref="format-pills"]`),this.stepSection=this.overlay.querySelector(`[data-ref="step-section"]`),this.stlSection=this.overlay.querySelector(`[data-ref="stl-section"]`),this.pngSection=this.overlay.querySelector(`[data-ref="png-section"]`),this.includeColorsToggle=this.overlay.querySelector(`[data-ref="include-colors"]`),this.resolutionSelect=this.overlay.querySelector(`[data-ref="resolution"]`),this.customSection=this.overlay.querySelector(`[data-ref="custom-section"]`),this.angularInput=this.overlay.querySelector(`[data-ref="angular"]`),this.linearInput=this.overlay.querySelector(`[data-ref="linear"]`),this.showGridToggle=this.overlay.querySelector(`[data-ref="show-grid"]`),this.showAxesToggle=this.overlay.querySelector(`[data-ref="show-axes"]`),this.transparentToggle=this.overlay.querySelector(`[data-ref="transparent"]`),this.autoCropToggle=this.overlay.querySelector(`[data-ref="auto-crop"]`),this.marginSection=this.overlay.querySelector(`[data-ref="margin-section"]`),this.marginInput=this.overlay.querySelector(`[data-ref="margin"]`),this.widthInput=this.overlay.querySelector(`[data-ref="png-width"]`),this.heightInput=this.overlay.querySelector(`[data-ref="png-height"]`),this.exportBtn=this.overlay.querySelector(`[data-ref="export-btn"]`),this.statusEl=this.overlay.querySelector(`[data-ref="status"]`),this.bindEvents()}show(e){this.shapeIds=e,this.statusEl.classList.add(`hidden`),this.exportBtn.disabled=!1,this.overlay.classList.remove(`hidden`)}hide(){this.overlay.classList.add(`hidden`)}buildHTML(){return`
5277
+ `}bindParamHandlers(){this.body.querySelectorAll(`[data-param-label]`).forEach(e=>{let t=e.dataset.paramLabel,n=e.dataset.paramType,r=e=>{let n=this.currentParams.find(e=>e.label===t),r=n&&typeof n.defaultValue==`number`?Number(e):e;fetch(`/api/set-param`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({label:t,value:r})}).catch(e=>console.error(`Set param failed:`,e))},i=e=>{let n=this.currentParams.find(e=>e.label===t),r=n?.options?.[0]&&typeof n.options[0].value==`number`?e.map(Number):e;fetch(`/api/set-param`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({label:t,value:r})}).catch(e=>console.error(`Set param failed:`,e))};n===`slider`?(e.addEventListener(`input`,()=>{let n=this.body.querySelector(`[data-param-display="${t}"]`);n&&(n.textContent=e.value)}),e.addEventListener(`change`,()=>{r(e.value)})):n===`number`||n===`text`?(e.addEventListener(`input`,()=>{this.debounceParam(t,()=>r(e.value))}),e.addEventListener(`blur`,()=>{this.flushParam(t,()=>r(e.value))})):n===`checkbox`?e.addEventListener(`change`,()=>{let n=e.checked;fetch(`/api/set-param`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({label:t,value:n})}).catch(e=>console.error(`Set param failed:`,e))}):n===`select`?e.addEventListener(`change`,()=>{r(e.value)}):n===`multi-select`?e.addEventListener(`change`,()=>{i(Array.from(e.selectedOptions,e=>e.value))}):n===`multi-checkboxes`?e.addEventListener(`change`,()=>{i(Array.from(e.querySelectorAll(`input[type="checkbox"]:checked`),e=>e.value))}):n===`color`?e.addEventListener(`input`,()=>{r(e.value)}):n===`multi-chips`&&e.addEventListener(`click`,t=>{let n=t.target.closest(`[data-chip-value]`);n&&(n.classList.toggle(`badge-primary`),n.classList.toggle(`badge-outline`),i(Array.from(e.querySelectorAll(`.badge-primary[data-chip-value]`),e=>e.dataset.chipValue)))})})}debounceParam(e,t){let n=this.debounceTimers.get(e);n&&clearTimeout(n),this.debounceTimers.set(e,setTimeout(()=>{this.debounceTimers.delete(e),t()},500))}flushParam(e,t){let n=this.debounceTimers.get(e);n&&(clearTimeout(n),this.debounceTimers.delete(e),t())}escapeHtml(e){let t=document.createElement(`div`);return t.textContent=e,t.innerHTML}},Vg={front:new R(0,-1,0),back:new R(0,1,0),left:new R(-1,0,0),right:new R(1,0,0),top:new R(0,0,1),bottom:new R(0,0,-1),"iso-ftr":new R(1,-1,1).normalize(),"iso-fbr":new R(1,-1,-1).normalize(),"iso-ftl":new R(-1,-1,1).normalize(),"iso-fbl":new R(-1,-1,-1).normalize(),"iso-btr":new R(1,1,1).normalize(),"iso-bbr":new R(1,1,-1).normalize(),"iso-btl":new R(-1,1,1).normalize(),"iso-bbl":new R(-1,1,-1).normalize()};function Hg(e,t,n){let r=Vg[e],i=Math.max(n,1);return{eye:t.clone().add(r.clone().multiplyScalar(i)),target:t.clone()}}function Ug(e,t,n,r){let i=e.clone().sub(t),a=i.length(),o=Math.acos(ht.clamp(i.z/Math.max(a,1e-9),-1,1)),s=Math.atan2(i.y,i.x);s+=n*ht.DEG2RAD,o=ht.clamp(o-r*ht.DEG2RAD,.001,Math.PI-.001);let c=Math.sin(o),l=new R(a*c*Math.cos(s),a*c*Math.sin(s),a*Math.cos(o));return{eye:t.clone().add(l),target:t.clone()}}function Wg(e,t,n,r,i){switch(e.kind){case`current`:return null;case`named`:return Hg(e.name,t,n);case`orbit-from-current`:return Ug(r,i,e.azimuthDeg,e.elevationDeg);case`look-from`:return{eye:new R(e.eye[0],e.eye[1],e.eye[2]),target:e.target?new R(e.target[0],e.target[1],e.target[2]):t.clone()}}}function Gg(e){let t=new Gt;return Kg(t,e),t}function Kg(e,t){if(t.userData.isConstructionPlane||!t.visible)return;let n=t;(n.isMesh||n.isLine||n.isPoints)&&n.geometry&&(n.geometry.computeBoundingBox(),n.geometry.boundingBox&&e.union(n.geometry.boundingBox.clone().applyMatrix4(n.matrixWorld)));for(let n of t.children)Kg(e,n)}var qg={width:800,height:800,showGrid:!1,showAxes:!1,transparent:!1,autoCrop:!1,fitToModel:!1,margin:0,view:{kind:`current`}};function Jg(e,t={}){return Zg(Xg(e,{...qg,...t}))}function Yg(e,t={}){let n={...qg,...t},r=Math.max(1,Math.floor(n.width/2)),i=Math.max(1,Math.floor(n.height/2)),a=[{x:0,y:0,view:{kind:`named`,name:`front`}},{x:r,y:0,view:{kind:`named`,name:`top`}},{x:0,y:i,view:{kind:`named`,name:`right`}},{x:r,y:i,view:{kind:`named`,name:`iso-ftr`}}],o=document.createElement(`canvas`);o.width=r*2,o.height=i*2;let s=o.getContext(`2d`);if(!s)return Promise.reject(Error(`Failed to get composite 2d context.`));n.transparent||(s.fillStyle=`#ffffff`,s.fillRect(0,0,o.width,o.height));for(let t of a){let a=Xg(e,{...n,width:r,height:i,view:t.view,autoCrop:!1,fitToModel:!0});s.drawImage(a,t.x,t.y)}return Zg(o)}function Xg(e,t){let{width:n,height:r,showGrid:i,showAxes:a,transparent:o,autoCrop:s,fitToModel:c,margin:l,view:u}=t,d=e.scene,f=e.camera,p=e.cameraControls,m=d.getObjectByName(`grid`),h=d.getObjectByName(`defaultAxesHelper`),g=d.getObjectByName(`sketchAxesHelper`),_=m?.visible,v=h?.visible,y=g?.visible,b=d.background,x=new R,S=new R;p.getPosition(x),p.getTarget(S);let C=f.zoom;m&&(m.visible=i),h&&(h.visible=a),g&&(g.visible=a),o&&(d.background=null);let w=n/r,T=f,E;if(T.isOrthographicCamera){E={left:T.left,right:T.right,top:T.top,bottom:T.bottom};let e=T.top-T.bottom;T.left=-w*e/2,T.right=w*e/2,T.updateProjectionMatrix()}else E={aspect:T.aspect},T.aspect=w,T.updateProjectionMatrix();let D=$g(e);if(u.kind!==`current`){let e=Wg(u,D.center,D.diameter,x,S);if(e){if(f.position.copy(e.eye),f.lookAt(e.target),T.isOrthographicCamera&&D.diameter>0){let e=T.right-T.left,t=T.top-T.bottom;T.zoom=Math.min(e/D.diameter,t/D.diameter)}else if(T.isPerspectiveCamera&&D.diameter>0){let t=T.fov*Math.PI/360,n=Math.atan(Math.tan(t)*T.aspect),r=Math.min(t,n),i=D.diameter/2/Math.sin(r),a=f.position.clone().sub(e.target).normalize();f.position.copy(e.target).add(a.multiplyScalar(i)),f.lookAt(e.target)}T.updateProjectionMatrix()}}else if(s||c){let e=d.getObjectByName(`compiledMesh`);if(e){let t=new Gt;if(t_(t,e),!t.isEmpty()){let e=t.getCenter(new R),n=t.getSize(new R).length()*af;if(n>0){let t=new R;if(f.getWorldDirection(t),f.position.copy(e).sub(t.clone().multiplyScalar(1e3)),f.lookAt(e),T.isOrthographicCamera){let e=T.right-T.left,t=T.top-T.bottom;T.zoom=Math.min(e/n,t/n)}T.updateProjectionMatrix()}}}}let ee=new Dl({antialias:!0,alpha:!0,preserveDrawingBuffer:!0});ee.setSize(n,r),ee.setPixelRatio(1),ee.toneMapping=4,ee.outputColorSpace=Ie;let O=new R;f.getWorldDirection(O),d.traverse(e=>{e.isDirectionalLight&&e.position.copy(O.clone().multiplyScalar(-10))}),ee.render(d,f);let k=ee.domElement;if(s){let t=e_(e,n,r,l);if(t){let e=document.createElement(`canvas`);e.width=t.w,e.height=t.h,e.getContext(`2d`).drawImage(ee.domElement,t.x,t.y,t.w,t.h,0,0,t.w,t.h),k=e}}let te=Qg(k,n,r);return m&&(m.visible=_),h&&(h.visible=v),g&&(g.visible=y),d.background=b,T.isOrthographicCamera?(T.left=E.left,T.right=E.right,T.top=E.top,T.bottom=E.bottom):T.aspect=E.aspect,f.zoom=C,f.position.copy(x),f.lookAt(S),T.updateProjectionMatrix(),p.setLookAt(x.x,x.y,x.z,S.x,S.y,S.z,!1),ee.dispose(),e.requestRender(),te}function Zg(e){return new Promise((t,n)=>{e.toBlob(e=>{e?t(e):n(Error(`Failed to create PNG blob.`))},`image/png`)})}function Qg(e,t,n){let r=document.createElement(`canvas`);r.width=e.width||t,r.height=e.height||n;let i=r.getContext(`2d`);return i?(i.drawImage(e,0,0),r):e}function $g(e){let t=Gg(e.scene.getObjectByName(`compiledMesh`)??e.scene);return t.isEmpty()?{center:new R,diameter:100}:{center:t.getCenter(new R),diameter:t.getSize(new R).length()*af}}function e_(e,t,n,r){let i=e.scene.getObjectByName(`compiledMesh`);if(!i)return null;let a=new Gt;if(t_(a,i),a.isEmpty())return null;let o=e.camera,s=[new R(a.min.x,a.min.y,a.min.z),new R(a.max.x,a.min.y,a.min.z),new R(a.min.x,a.max.y,a.min.z),new R(a.max.x,a.max.y,a.min.z),new R(a.min.x,a.min.y,a.max.z),new R(a.max.x,a.min.y,a.max.z),new R(a.min.x,a.max.y,a.max.z),new R(a.max.x,a.max.y,a.max.z)],c=1/0,l=1/0,u=-1/0,d=-1/0;for(let e of s){e.project(o);let r=(e.x+1)/2*t,i=(1-e.y)/2*n;c=Math.min(c,r),l=Math.min(l,i),u=Math.max(u,r),d=Math.max(d,i)}let f=Math.max(0,Math.floor(c-r)),p=Math.max(0,Math.floor(l-r)),m=Math.min(t,Math.ceil(u+r)),h=Math.min(n,Math.ceil(d+r)),g=m-f,_=h-p;return g<=0||_<=0?null:{x:f,y:p,w:g,h:_}}function t_(e,t){if(t.userData.isConstructionPlane||!t.visible)return;let n=t;(n.isMesh||n.isLine||n.isPoints)&&n.geometry&&(n.geometry.computeBoundingBox(),n.geometry.boundingBox&&e.union(n.geometry.boundingBox.clone().applyMatrix4(n.matrixWorld)));for(let n of t.children)t_(e,n)}var n_=class{overlay;pillsContainer;stepSection;stlSection;pngSection;includeColorsToggle;resolutionSelect;customSection;angularInput;linearInput;showGridToggle;showAxesToggle;transparentToggle;autoCropToggle;marginSection;marginInput;widthInput;heightInput;exportBtn;statusEl;shapeIds=[];selectedFormat=`step`;constructor(e,t){this.sceneCtx=t,this.overlay=document.createElement(`div`),this.overlay.className=`fixed inset-0 z-[300] bg-black/50 flex items-center justify-center hidden`,this.overlay.innerHTML=this.buildHTML(),e.appendChild(this.overlay),this.pillsContainer=this.overlay.querySelector(`[data-ref="format-pills"]`),this.stepSection=this.overlay.querySelector(`[data-ref="step-section"]`),this.stlSection=this.overlay.querySelector(`[data-ref="stl-section"]`),this.pngSection=this.overlay.querySelector(`[data-ref="png-section"]`),this.includeColorsToggle=this.overlay.querySelector(`[data-ref="include-colors"]`),this.resolutionSelect=this.overlay.querySelector(`[data-ref="resolution"]`),this.customSection=this.overlay.querySelector(`[data-ref="custom-section"]`),this.angularInput=this.overlay.querySelector(`[data-ref="angular"]`),this.linearInput=this.overlay.querySelector(`[data-ref="linear"]`),this.showGridToggle=this.overlay.querySelector(`[data-ref="show-grid"]`),this.showAxesToggle=this.overlay.querySelector(`[data-ref="show-axes"]`),this.transparentToggle=this.overlay.querySelector(`[data-ref="transparent"]`),this.autoCropToggle=this.overlay.querySelector(`[data-ref="auto-crop"]`),this.marginSection=this.overlay.querySelector(`[data-ref="margin-section"]`),this.marginInput=this.overlay.querySelector(`[data-ref="margin"]`),this.widthInput=this.overlay.querySelector(`[data-ref="png-width"]`),this.heightInput=this.overlay.querySelector(`[data-ref="png-height"]`),this.exportBtn=this.overlay.querySelector(`[data-ref="export-btn"]`),this.statusEl=this.overlay.querySelector(`[data-ref="status"]`),this.bindEvents()}show(e){this.shapeIds=e,this.statusEl.classList.add(`hidden`),this.exportBtn.disabled=!1,this.overlay.classList.remove(`hidden`)}hide(){this.overlay.classList.add(`hidden`)}buildHTML(){return`
5256
5278
  <div class="w-[380px] bg-base-100 border border-base-content/10 rounded-lg p-5 shadow-[0_4px_24px_rgba(0,0,0,0.5)]">
5257
5279
  <div class="flex items-center justify-between mb-4">
5258
5280
  <h3 class="text-sm font-medium text-base-content/90">Export</h3>
5259
5281
  <button data-ref="close-btn" class="btn btn-ghost btn-square btn-xs text-base-content/60">
5260
- <span class="[&>svg]:size-4">${Yh}</span>
5282
+ <span class="[&>svg]:size-4">${ug}</span>
5261
5283
  </button>
5262
5284
  </div>
5263
5285
 
@@ -5343,23 +5365,23 @@ void main() {
5343
5365
  <button data-ref="export-btn" class="btn btn-primary btn-sm">Export</button>
5344
5366
  </div>
5345
5367
  </div>
5346
- `}setFormat(e){this.selectedFormat=e,this.stepSection.classList.toggle(`hidden`,e!==`step`),this.stlSection.classList.toggle(`hidden`,e!==`stl`),this.pngSection.classList.toggle(`hidden`,e!==`png`)}bindEvents(){this.overlay.querySelector(`[data-ref="close-btn"]`).addEventListener(`click`,()=>this.hide()),this.overlay.querySelector(`[data-ref="cancel-btn"]`).addEventListener(`click`,()=>this.hide()),this.overlay.addEventListener(`click`,e=>{e.target===this.overlay&&this.hide()}),this.pillsContainer.querySelectorAll(`[data-format]`).forEach(e=>{e.addEventListener(`change`,()=>this.setFormat(e.dataset.format))}),this.resolutionSelect.addEventListener(`change`,()=>{this.customSection.classList.toggle(`hidden`,this.resolutionSelect.value!==`custom`)}),this.autoCropToggle.addEventListener(`change`,()=>{this.marginSection.classList.toggle(`hidden`,!this.autoCropToggle.checked)}),this.exportBtn.addEventListener(`click`,()=>this.onExport())}async onExport(){if(this.selectedFormat===`png`)return this.exportPng();let e=this.selectedFormat,t={format:e,shapeIds:this.shapeIds};e===`step`?t.includeColors=this.includeColorsToggle.checked:(t.resolution=this.resolutionSelect.value,t.resolution===`custom`&&(t.customAngularDeflectionDeg=parseFloat(this.angularInput.value),t.customLinearDeflection=parseFloat(this.linearInput.value))),this.exportBtn.disabled=!0,this.statusEl.classList.remove(`hidden`),this.statusEl.innerHTML=`<span class="loading loading-spinner loading-xs"></span><span>Exporting...</span>`;try{let n=await Um(t),r=e===`step`?`.step`:`.stl`,i=URL.createObjectURL(n),a=document.createElement(`a`);a.href=i,a.download=`export${r}`,a.click(),URL.revokeObjectURL(i),this.hide()}catch(e){this.statusEl.innerHTML=`<span class="text-error text-xs">${e.message}</span>`}finally{this.exportBtn.disabled=!1}}async exportPng(){this.exportBtn.disabled=!0;try{let e=await Mg(this.sceneCtx,{width:Math.max(1,Math.min(8192,parseInt(this.widthInput.value)||800)),height:Math.max(1,Math.min(8192,parseInt(this.heightInput.value)||800)),showGrid:this.showGridToggle.checked,showAxes:this.showAxesToggle.checked,transparent:this.transparentToggle.checked,autoCrop:this.autoCropToggle.checked,margin:this.autoCropToggle.checked?Math.max(0,parseInt(this.marginInput.value)||0):0}),t=URL.createObjectURL(e),n=document.createElement(`a`);n.href=t,n.download=`export.png`,n.click(),URL.revokeObjectURL(t),this.hide()}catch(e){this.statusEl.classList.remove(`hidden`),this.statusEl.innerHTML=`<span class="text-error text-xs">${e.message}</span>`}finally{this.exportBtn.disabled=!1}}},Vg=class{element;constructor(e,t){this.element=document.createElement(`div`),this.element.id=`fluidcad-breakpoint-indicator`,this.element.className=`absolute bottom-6 left-1/2 -translate-x-1/2 z-[999] pointer-events-auto hidden`,this.element.innerHTML=`
5368
+ `}setFormat(e){this.selectedFormat=e,this.stepSection.classList.toggle(`hidden`,e!==`step`),this.stlSection.classList.toggle(`hidden`,e!==`stl`),this.pngSection.classList.toggle(`hidden`,e!==`png`)}bindEvents(){this.overlay.querySelector(`[data-ref="close-btn"]`).addEventListener(`click`,()=>this.hide()),this.overlay.querySelector(`[data-ref="cancel-btn"]`).addEventListener(`click`,()=>this.hide()),this.overlay.addEventListener(`click`,e=>{e.target===this.overlay&&this.hide()}),this.pillsContainer.querySelectorAll(`[data-format]`).forEach(e=>{e.addEventListener(`change`,()=>this.setFormat(e.dataset.format))}),this.resolutionSelect.addEventListener(`change`,()=>{this.customSection.classList.toggle(`hidden`,this.resolutionSelect.value!==`custom`)}),this.autoCropToggle.addEventListener(`change`,()=>{this.marginSection.classList.toggle(`hidden`,!this.autoCropToggle.checked)}),this.exportBtn.addEventListener(`click`,()=>this.onExport())}async onExport(){if(this.selectedFormat===`png`)return this.exportPng();let e=this.selectedFormat,t={format:e,shapeIds:this.shapeIds};e===`step`?t.includeColors=this.includeColorsToggle.checked:(t.resolution=this.resolutionSelect.value,t.resolution===`custom`&&(t.customAngularDeflectionDeg=parseFloat(this.angularInput.value),t.customLinearDeflection=parseFloat(this.linearInput.value))),this.exportBtn.disabled=!0,this.statusEl.classList.remove(`hidden`),this.statusEl.innerHTML=`<span class="loading loading-spinner loading-xs"></span><span>Exporting...</span>`;try{let n=await nh(t),r=e===`step`?`.step`:`.stl`,i=URL.createObjectURL(n),a=document.createElement(`a`);a.href=i,a.download=`export${r}`,a.click(),URL.revokeObjectURL(i),this.hide()}catch(e){this.statusEl.innerHTML=`<span class="text-error text-xs">${e.message}</span>`}finally{this.exportBtn.disabled=!1}}async exportPng(){this.exportBtn.disabled=!0;try{let e=await Jg(this.sceneCtx,{width:Math.max(1,Math.min(8192,parseInt(this.widthInput.value)||800)),height:Math.max(1,Math.min(8192,parseInt(this.heightInput.value)||800)),showGrid:this.showGridToggle.checked,showAxes:this.showAxesToggle.checked,transparent:this.transparentToggle.checked,autoCrop:this.autoCropToggle.checked,margin:this.autoCropToggle.checked?Math.max(0,parseInt(this.marginInput.value)||0):0}),t=URL.createObjectURL(e),n=document.createElement(`a`);n.href=t,n.download=`export.png`,n.click(),URL.revokeObjectURL(t),this.hide()}catch(e){this.statusEl.classList.remove(`hidden`),this.statusEl.innerHTML=`<span class="text-error text-xs">${e.message}</span>`}finally{this.exportBtn.disabled=!1}}},r_=class{element;constructor(e,t){this.element=document.createElement(`div`),this.element.id=`fluidcad-breakpoint-indicator`,this.element.className=`absolute bottom-6 left-1/2 -translate-x-1/2 z-[999] pointer-events-auto hidden`,this.element.innerHTML=`
5347
5369
  <div class="flex items-center gap-3 panel-bg border border-warning/40 rounded-lg px-5 py-2.5 text-sm leading-none select-none">
5348
- <span class="text-warning [&>svg]:size-5">${Oh}</span>
5370
+ <span class="text-warning [&>svg]:size-5">${Hh}</span>
5349
5371
  <span class="text-base-content/80">Breakpoint Active</span>
5350
5372
  <div class="h-4 w-px bg-base-content/10"></div>
5351
5373
  <button class="text-base-content/60 hover:text-base-content transition-colors cursor-pointer fluidcad-breakpoint-continue">
5352
5374
  Continue
5353
5375
  </button>
5354
5376
  </div>
5355
- `,e.appendChild(this.element),this.element.querySelector(`.fluidcad-breakpoint-continue`).addEventListener(`click`,()=>{t?.(),Bm()})}setActive(e){this.element.classList.toggle(`hidden`,!e)}},Hg=class{element;messageEl;countEl;toggleEl;listEl;expanded=!1;primaryLoc=null;onGotoSource;constructor(e,t){this.onGotoSource=t,this.element=document.createElement(`div`),this.element.id=`fluidcad-error-banner`,this.element.className=`absolute top-4 left-1/2 -translate-x-1/2 z-[1001] pointer-events-auto hidden max-w-[600px]`,this.element.innerHTML=`
5377
+ `,e.appendChild(this.element),this.element.querySelector(`.fluidcad-breakpoint-continue`).addEventListener(`click`,()=>{t?.(),$m()})}setActive(e){this.element.classList.toggle(`hidden`,!e)}},i_=class{element;messageEl;countEl;toggleEl;listEl;expanded=!1;primaryLoc=null;onGotoSource;constructor(e,t){this.onGotoSource=t,this.element=document.createElement(`div`),this.element.id=`fluidcad-error-banner`,this.element.className=`absolute top-4 left-1/2 -translate-x-1/2 z-[1001] pointer-events-auto hidden max-w-[600px]`,this.element.innerHTML=`
5356
5378
  <div class="panel-bg border border-error/40 rounded-lg shadow-md overflow-hidden">
5357
5379
  <div class="flex items-start gap-3 px-5 py-2.5 text-sm select-none">
5358
- <span class="text-error shrink-0 mt-0.5 [&>svg]:size-5">${kh}</span>
5380
+ <span class="text-error shrink-0 mt-0.5 [&>svg]:size-5">${Uh}</span>
5359
5381
  <span data-ref="message" class="text-base-content/90 whitespace-pre-line break-words cursor-pointer hover:underline grow min-w-0"></span>
5360
5382
  <span data-ref="count" class="text-base-content/40 tabular-nums shrink-0 hidden mt-0.5"></span>
5361
5383
  <button data-ref="toggle" class="text-base-content/40 hover:text-base-content/70 shrink-0 hidden cursor-pointer transition-transform mt-0.5" aria-label="Toggle error list">
5362
- ${Wh}
5384
+ ${ag}
5363
5385
  </button>
5364
5386
  </div>
5365
5387
  <div data-ref="list" class="hidden border-t border-base-content/10 max-h-[40vh] overflow-y-auto"></div>
@@ -5372,33 +5394,33 @@ void main() {
5372
5394
  <div class="text-base-content/90 break-words whitespace-pre-line">${a}</div>
5373
5395
  </div>
5374
5396
  </div>
5375
- `}this.listEl.innerHTML=t,this.listEl.querySelectorAll(`[data-error-index]`).forEach(t=>{t.addEventListener(`click`,()=>{let n=e[parseInt(t.dataset.errorIndex,10)]?.sourceLocation;n&&this.onGotoSource(n)})})}},Ug=class{element;textEl;constructor(e){this.element=document.createElement(`div`),this.element.id=`fluidcad-loading`,this.element.className=`absolute top-4 left-1/2 -translate-x-1/2 z-[1000] pointer-events-none`,this.element.innerHTML=`
5397
+ `}this.listEl.innerHTML=t,this.listEl.querySelectorAll(`[data-error-index]`).forEach(t=>{t.addEventListener(`click`,()=>{let n=e[parseInt(t.dataset.errorIndex,10)]?.sourceLocation;n&&this.onGotoSource(n)})})}},a_=class{element;textEl;constructor(e){this.element=document.createElement(`div`),this.element.id=`fluidcad-loading`,this.element.className=`absolute top-4 left-1/2 -translate-x-1/2 z-[1000] pointer-events-none`,this.element.innerHTML=`
5376
5398
  <div class="flex items-center gap-3 panel-bg border border-base-content/10 rounded-lg px-6 py-3 text-base-content/70 text-sm leading-none select-none">
5377
5399
  <span class="loading loading-spinner loading-sm"></span>
5378
5400
  <span class="loading-text">Loading FluidCAD...</span>
5379
5401
  </div>
5380
- `,e.appendChild(this.element),this.textEl=this.element.querySelector(`.loading-text`)}show(e){this.textEl.textContent=e,this.element.classList.remove(`hidden`)}hide(){this.element.classList.add(`hidden`)}},Wg=class{importToast;fileInput;importToastTimer=null;showLoading;hideLoading;constructor(e,t){this.showLoading=t.showLoading,this.hideLoading=t.hideLoading,this.importToast=document.createElement(`div`),this.importToast.className=`absolute bottom-16 left-6 z-[100] panel-bg border border-base-content/10 rounded-lg px-4 py-3 text-sm text-base-content/80 hidden`,e.appendChild(this.importToast),this.fileInput=document.createElement(`input`),this.fileInput.type=`file`,this.fileInput.accept=`.step,.stp`,this.fileInput.style.display=`none`,e.appendChild(this.fileInput),this.fileInput.addEventListener(`change`,()=>this.handleFileChange())}openPicker(){this.fileInput.click()}showToast(e,t){t?(this.importToast.innerHTML=`
5402
+ `,e.appendChild(this.element),this.textEl=this.element.querySelector(`.loading-text`)}show(e){this.textEl.textContent=e,this.element.classList.remove(`hidden`)}hide(){this.element.classList.add(`hidden`)}},o_=class{importToast;fileInput;importToastTimer=null;showLoading;hideLoading;constructor(e,t){this.showLoading=t.showLoading,this.hideLoading=t.hideLoading,this.importToast=document.createElement(`div`),this.importToast.className=`absolute bottom-16 left-6 z-[100] panel-bg border border-base-content/10 rounded-lg px-4 py-3 text-sm text-base-content/80 hidden`,e.appendChild(this.importToast),this.fileInput=document.createElement(`input`),this.fileInput.type=`file`,this.fileInput.accept=`.step,.stp`,this.fileInput.style.display=`none`,e.appendChild(this.fileInput),this.fileInput.addEventListener(`change`,()=>this.handleFileChange())}openPicker(){this.fileInput.click()}showToast(e,t){t?(this.importToast.innerHTML=`
5381
5403
  <div class="flex items-center gap-2">
5382
5404
  <span>${e} <code class="bg-base-content/10 px-1.5 py-0.5 rounded text-base-content/90">${t}</code></span>
5383
5405
  <button class="btn btn-ghost btn-square btn-xs text-base-content/60 import-toast-copy" title="Copy">
5384
- <span class="[&>svg]:size-3.5">${yh}</span>
5406
+ <span class="[&>svg]:size-3.5">${Nh}</span>
5385
5407
  </button>
5386
5408
  </div>
5387
- `,this.importToast.querySelector(`.import-toast-copy`).addEventListener(`click`,()=>{navigator.clipboard.writeText(t);let e=this.importToast.querySelector(`.import-toast-copy`);e.setAttribute(`title`,`Copied!`),setTimeout(()=>e.setAttribute(`title`,`Copy`),1500)})):this.importToast.textContent=e,this.importToast.classList.remove(`hidden`),this.importToastTimer&&clearTimeout(this.importToastTimer),this.importToastTimer=setTimeout(()=>{this.importToast.classList.add(`hidden`),this.importToastTimer=null},6e3)}async handleFileChange(){let e=this.fileInput.files?.[0];if(e){this.fileInput.value=``,this.showLoading(`Importing file...`);try{let t=await e.arrayBuffer(),n=new Uint8Array(t),r=``;for(let e=0;e<n.length;e++)r+=String.fromCharCode(n[e]);let i=btoa(r),a=await Hm(e.name,i);a.success?this.showToast(`Imported! Use:`,`load('${a.fileName}')`):this.showToast(`Import failed: ${a.error||`Unknown error`}`)}catch{this.showToast(`Import failed: network error`)}finally{this.hideLoading()}}}},Gg=12,Kg=class{canvas;ctx;plane;snapManager;onPick;onHighlight;edges=[];highlightedShapeId=null;downX=0;downY=0;boundMouseDown;boundMouseUp;boundMouseMove;constructor(e,t,n,r,i,a,o){this.canvas=e.renderer.domElement,this.ctx=e,this.plane=t,this.snapManager=n,this.onPick=a,this.onHighlight=o,this.edges=dp(r,i,t),this.boundMouseDown=this.handleMouseDown.bind(this),this.boundMouseUp=this.handleMouseUp.bind(this),this.boundMouseMove=this.handleMouseMove.bind(this)}updateEdges(e,t){this.edges=dp(e,t,this.plane),this.highlightedShapeId&&(this.edges.some(e=>e.shapeId===this.highlightedShapeId)||(this.onHighlight(null),this.highlightedShapeId=null))}activate(){this.canvas.addEventListener(`mousedown`,this.boundMouseDown),this.canvas.addEventListener(`mouseup`,this.boundMouseUp),this.canvas.addEventListener(`mousemove`,this.boundMouseMove)}deactivate(){this.canvas.removeEventListener(`mousedown`,this.boundMouseDown),this.canvas.removeEventListener(`mouseup`,this.boundMouseUp),this.canvas.removeEventListener(`mousemove`,this.boundMouseMove),this.highlightedShapeId&&=(this.onHighlight(null),null)}getEdgeEntry(e){return this.edges.find(t=>t.shapeId===e)}handleMouseDown(e){this.downX=e.clientX,this.downY=e.clientY}handleMouseUp(e){let t=e.clientX-this.downX,n=e.clientY-this.downY;if(t*t+n*n>64||!this.highlightedShapeId)return;let r=this.projectToSketch(e.clientX,e.clientY);if(!r)return;let i=this.projectOntoEdge(r,this.highlightedShapeId)??r;this.onPick(J(i))}handleMouseMove(e){let t=this.projectToSketch(e.clientX,e.clientY);if(!t){this.highlightedShapeId&&=(this.onHighlight(null),null);return}let n=this.computeSketchThreshold(),r=this.findNearestEdge(t,n);if(r!==this.highlightedShapeId){if(r){let e=this.getEdgeEntry(r);this.onHighlight({shapeId:r,endpoints:e?.endpoints??[]})}else this.onHighlight(null);this.highlightedShapeId=r}}computeSketchThreshold(){return yp(this.ctx,Gg)}findNearestEdge(e,t){let n=1/0,r=null;for(let t of this.edges)for(let i of t.segments){let a=mp(e[0],e[1],i.ax,i.ay,i.bx,i.by);a<n&&(n=a,r=t.shapeId)}return n<=t?r:null}projectOntoEdge(e,t){let n=this.edges.find(e=>e.shapeId===t);if(!n)return null;let r=1/0,i=null;for(let t of n.segments){let n=hp(e[0],e[1],t.ax,t.ay,t.bx,t.by);n.dist<r&&(r=n.dist,i=[n.x,n.y])}return i}projectToSketch(e,t){return gp(this.ctx,this.plane,e,t)}},qg=1e-6,Jg=class{vertices2d=[];excluded=[];plane;constructor(e,t){this.vertices2d=e,this.plane=t}setExcluded(e){this.excluded=e}isExcluded(e){for(let t of this.excluded){let n=e[0]-t[0],r=e[1]-t[1];if(n*n+r*r<qg)return!0}return!1}snap(e,t){let n=1/0,r=null;for(let i of this.vertices2d){if(this.isExcluded(i))continue;let a=e[0]-i[0],o=e[1]-i[1],s=Math.sqrt(a*a+o*o);s<t&&s<n&&(n=s,r=i)}return r?{point2d:r,worldPoint:Yg(r,this.plane),snapType:`vertex`}:null}};function Yg(e,t){let n=t.origin,r=t.xDirection,i=t.yDirection;return new R(n.x+r.x*e[0]+i.x*e[1],n.y+r.y*e[0]+i.y*e[1],n.z+r.z*e[0]+i.z*e[1])}var Xg=.35,Zg=[1,2,5];function Qg(e,t=10,n=15){if(t/e>=n)return t;let r=t;for(;;){for(let t of Zg){let i=r*t;if(i/e>=n)return i}r*=10}}var $g=class{spacing;plane;constructor(e,t=10){this.plane=e,this.spacing=t}setSpacing(e){this.spacing=e}snap(e,t){let n=Math.round(e[0]/this.spacing)*this.spacing,r=Math.round(e[1]/this.spacing)*this.spacing,i=e[0]-n,a=e[1]-r;if(Math.sqrt(i*i+a*a)>Math.min(t,this.spacing*Xg))return null;let o=[n,r];return{point2d:o,worldPoint:e_(o,this.plane),snapType:`grid`}}};function e_(e,t){let n=t.origin,r=t.xDirection,i=t.yDirection;return new R(n.x+r.x*e[0]+i.x*e[1],n.y+r.y*e[0]+i.y*e[1],n.z+r.z*e[0]+i.z*e[1])}var t_=15,n_=class e{snappers=[];threshold;ctx;constructor(e,t=t_,n=null){this.snappers=e,this.threshold=t,this.ctx=n}setExcludedVertices(e){for(let t of this.snappers)t instanceof Jg&&t.setExcluded(e)}snap(e,t){this.ctx&&this.updateGridSpacing();for(let t of this.snappers){let n=t.snap(e,this.threshold);if(n)return n}let n=t.origin,r=t.xDirection,i=t.yDirection;return{point2d:e,worldPoint:new R(n.x+r.x*e[0]+i.x*e[1],n.y+r.y*e[0]+i.y*e[1],n.z+r.z*e[0]+i.z*e[1]),snapType:`none`}}updateGridSpacing(){let e=this.ctx.camera,t=this.ctx.renderer.domElement.getBoundingClientRect().height||1,n,r=e;if(r.isOrthographicCamera)n=(r.top-r.bottom)/(r.zoom||1);else{let t=new R;this.ctx.cameraControls.getTarget(t);let i=e.position.distanceTo(t),a=r.fov*Math.PI/180;n=2*i*Math.tan(a/2)}let i=Qg(n/t);for(let e of this.snappers)e instanceof $g&&e.setSpacing(i)}static fromSceneObjects(t,n,r,i){let a=[];for(let e of t)if(!(e.parentId!==n||!e.sceneShapes.length)){for(let t of e.sceneShapes)if(!(t.isMetaShape||t.isGuide))for(let e of t.meshes){if(!e.indices.length)continue;let t=new Map;for(let n of e.indices)t.set(n,(t.get(n)||0)+1);for(let[n,i]of t)if(i===1){let t=e.vertices[n*3],i=e.vertices[n*3+1],o=e.vertices[n*3+2],s=t-r.origin.x,c=i-r.origin.y,l=o-r.origin.z,u=s*r.xDirection.x+c*r.xDirection.y+l*r.xDirection.z,d=s*r.yDirection.x+c*r.yDirection.y+l*r.yDirection.z;a.some(e=>(e[0]-u)*(e[0]-u)+(e[1]-d)*(e[1]-d)<1e-6)||a.push([u,d])}}}return new e([new Jg(a,r),new $g(r)],t_,i??null)}};function r_(e,t){return e.parentId?t.find(t=>t.id===e.parentId)?.type===`part`:!0}var i_=16762232,a_=1e-4,o_=class{viewer;triggerBtn;activeBar;_state=`idle`;_lastPickInfo=null;lastSceneObjects=null;activePointPickMode=null;activePickSourceLine=null;_pendingActivation=!1;highlightedVertexDots=[];constructor(e,t){this.viewer=t,this.triggerBtn=document.createElement(`div`),this.triggerBtn.id=`fluidcad-trim-pick-trigger`,this.triggerBtn.className=`absolute top-4 left-1/2 -translate-x-1/2 z-[999] pointer-events-auto hidden`,this.triggerBtn.innerHTML=`
5409
+ `,this.importToast.querySelector(`.import-toast-copy`).addEventListener(`click`,()=>{navigator.clipboard.writeText(t);let e=this.importToast.querySelector(`.import-toast-copy`);e.setAttribute(`title`,`Copied!`),setTimeout(()=>e.setAttribute(`title`,`Copy`),1500)})):this.importToast.textContent=e,this.importToast.classList.remove(`hidden`),this.importToastTimer&&clearTimeout(this.importToastTimer),this.importToastTimer=setTimeout(()=>{this.importToast.classList.add(`hidden`),this.importToastTimer=null},6e3)}async handleFileChange(){let e=this.fileInput.files?.[0];if(e){this.fileInput.value=``,this.showLoading(`Importing file...`);try{let t=await e.arrayBuffer(),n=new Uint8Array(t),r=``;for(let e=0;e<n.length;e++)r+=String.fromCharCode(n[e]);let i=btoa(r),a=await th(e.name,i);a.success?this.showToast(`Imported! Use:`,`load('${a.fileName}')`):this.showToast(`Import failed: ${a.error||`Unknown error`}`)}catch{this.showToast(`Import failed: network error`)}finally{this.hideLoading()}}}},s_=12,c_=class{canvas;ctx;plane;snapManager;onPick;onHighlight;edges=[];highlightedShapeId=null;downX=0;downY=0;boundMouseDown;boundMouseUp;boundMouseMove;constructor(e,t,n,r,i,a,o){this.canvas=e.renderer.domElement,this.ctx=e,this.plane=t,this.snapManager=n,this.onPick=a,this.onHighlight=o,this.edges=bp(r,i,t),this.boundMouseDown=this.handleMouseDown.bind(this),this.boundMouseUp=this.handleMouseUp.bind(this),this.boundMouseMove=this.handleMouseMove.bind(this)}updateEdges(e,t){this.edges=bp(e,t,this.plane),this.highlightedShapeId&&(this.edges.some(e=>e.shapeId===this.highlightedShapeId)||(this.onHighlight(null),this.highlightedShapeId=null))}activate(){this.canvas.addEventListener(`mousedown`,this.boundMouseDown),this.canvas.addEventListener(`mouseup`,this.boundMouseUp),this.canvas.addEventListener(`mousemove`,this.boundMouseMove)}deactivate(){this.canvas.removeEventListener(`mousedown`,this.boundMouseDown),this.canvas.removeEventListener(`mouseup`,this.boundMouseUp),this.canvas.removeEventListener(`mousemove`,this.boundMouseMove),this.highlightedShapeId&&=(this.onHighlight(null),null)}getEdgeEntry(e){return this.edges.find(t=>t.shapeId===e)}handleMouseDown(e){this.downX=e.clientX,this.downY=e.clientY}handleMouseUp(e){let t=e.clientX-this.downX,n=e.clientY-this.downY;if(t*t+n*n>64||!this.highlightedShapeId)return;let r=this.projectToSketch(e.clientX,e.clientY);if(!r)return;let i=this.projectOntoEdge(r,this.highlightedShapeId)??r;this.onPick(Y(i))}handleMouseMove(e){let t=this.projectToSketch(e.clientX,e.clientY);if(!t){this.highlightedShapeId&&=(this.onHighlight(null),null);return}let n=this.computeSketchThreshold(),r=this.findNearestEdge(t,n);if(r!==this.highlightedShapeId){if(r){let e=this.getEdgeEntry(r);this.onHighlight({shapeId:r,endpoints:e?.endpoints??[]})}else this.onHighlight(null);this.highlightedShapeId=r}}computeSketchThreshold(){return kp(this.ctx,s_)}findNearestEdge(e,t){let n=1/0,r=null;for(let t of this.edges)for(let i of t.segments){let a=Cp(e[0],e[1],i.ax,i.ay,i.bx,i.by);a<n&&(n=a,r=t.shapeId)}return n<=t?r:null}projectOntoEdge(e,t){let n=this.edges.find(e=>e.shapeId===t);if(!n)return null;let r=1/0,i=null;for(let t of n.segments){let n=wp(e[0],e[1],t.ax,t.ay,t.bx,t.by);n.dist<r&&(r=n.dist,i=[n.x,n.y])}return i}projectToSketch(e,t){return Tp(this.ctx,this.plane,e,t)}},l_=1e-6,u_=class{vertices2d=[];excluded=[];plane;constructor(e,t){this.vertices2d=e,this.plane=t}setExcluded(e){this.excluded=e}isExcluded(e){for(let t of this.excluded){let n=e[0]-t[0],r=e[1]-t[1];if(n*n+r*r<l_)return!0}return!1}snap(e,t){let n=1/0,r=null;for(let i of this.vertices2d){if(this.isExcluded(i))continue;let a=e[0]-i[0],o=e[1]-i[1],s=Math.sqrt(a*a+o*o);s<t&&s<n&&(n=s,r=i)}return r?{point2d:r,worldPoint:d_(r,this.plane),snapType:`vertex`}:null}};function d_(e,t){let n=t.origin,r=t.xDirection,i=t.yDirection;return new R(n.x+r.x*e[0]+i.x*e[1],n.y+r.y*e[0]+i.y*e[1],n.z+r.z*e[0]+i.z*e[1])}var f_=.35,p_=[1,2,5];function m_(e,t=10,n=15){if(t/e>=n)return t;let r=t;for(;;){for(let t of p_){let i=r*t;if(i/e>=n)return i}r*=10}}var h_=class{spacing;plane;constructor(e,t=10){this.plane=e,this.spacing=t}setSpacing(e){this.spacing=e}snap(e,t){let n=Math.round(e[0]/this.spacing)*this.spacing,r=Math.round(e[1]/this.spacing)*this.spacing,i=e[0]-n,a=e[1]-r;if(Math.sqrt(i*i+a*a)>Math.min(t,this.spacing*f_))return null;let o=[n,r];return{point2d:o,worldPoint:g_(o,this.plane),snapType:`grid`}}};function g_(e,t){let n=t.origin,r=t.xDirection,i=t.yDirection;return new R(n.x+r.x*e[0]+i.x*e[1],n.y+r.y*e[0]+i.y*e[1],n.z+r.z*e[0]+i.z*e[1])}var __=15,v_=class e{snappers=[];threshold;ctx;constructor(e,t=__,n=null){this.snappers=e,this.threshold=t,this.ctx=n}setExcludedVertices(e){for(let t of this.snappers)t instanceof u_&&t.setExcluded(e)}snap(e,t){this.ctx&&this.updateGridSpacing();for(let t of this.snappers){let n=t.snap(e,this.threshold);if(n)return n}let n=t.origin,r=t.xDirection,i=t.yDirection;return{point2d:e,worldPoint:new R(n.x+r.x*e[0]+i.x*e[1],n.y+r.y*e[0]+i.y*e[1],n.z+r.z*e[0]+i.z*e[1]),snapType:`none`}}updateGridSpacing(){let e=this.ctx.camera,t=this.ctx.renderer.domElement.getBoundingClientRect().height||1,n,r=e;if(r.isOrthographicCamera)n=(r.top-r.bottom)/(r.zoom||1);else{let t=new R;this.ctx.cameraControls.getTarget(t);let i=e.position.distanceTo(t),a=r.fov*Math.PI/180;n=2*i*Math.tan(a/2)}let i=m_(n/t);for(let e of this.snappers)e instanceof h_&&e.setSpacing(i)}static fromSceneObjects(t,n,r,i){let a=[];for(let e of t)if(!(e.parentId!==n||!e.sceneShapes.length)){for(let t of e.sceneShapes)if(!(t.isMetaShape||t.isGuide))for(let e of t.meshes){if(!e.indices.length)continue;let t=new Map;for(let n of e.indices)t.set(n,(t.get(n)||0)+1);for(let[n,i]of t)if(i===1){let t=e.vertices[n*3],i=e.vertices[n*3+1],o=e.vertices[n*3+2],s=t-r.origin.x,c=i-r.origin.y,l=o-r.origin.z,u=s*r.xDirection.x+c*r.xDirection.y+l*r.xDirection.z,d=s*r.yDirection.x+c*r.yDirection.y+l*r.yDirection.z;a.some(e=>(e[0]-u)*(e[0]-u)+(e[1]-d)*(e[1]-d)<1e-6)||a.push([u,d])}}}return new e([new u_(a,r),new h_(r)],__,i??null)}};function y_(e,t){return e.parentId?t.find(t=>t.id===e.parentId)?.type===`part`:!0}var b_=16762232,x_=1e-4,S_=class{viewer;triggerBtn;activeBar;_state=`idle`;_lastPickInfo=null;lastSceneObjects=null;activePointPickMode=null;activePickSourceLine=null;_pendingActivation=!1;highlightedVertexDots=[];constructor(e,t){this.viewer=t,this.triggerBtn=document.createElement(`div`),this.triggerBtn.id=`fluidcad-trim-pick-trigger`,this.triggerBtn.className=`absolute top-4 left-1/2 -translate-x-1/2 z-[999] pointer-events-auto hidden`,this.triggerBtn.innerHTML=`
5388
5410
  <button class="flex items-center gap-3 panel-bg border border-base-content/10 rounded-lg px-6 py-3 text-base-content/70 text-sm leading-none select-none cursor-pointer hover:border-base-content/20 transition-colors">
5389
- <span class="[&>svg]:size-5">${vh}</span>
5411
+ <span class="[&>svg]:size-5">${Mh}</span>
5390
5412
  <span>Interactive Trimming</span>
5391
5413
  </button>
5392
5414
  `,e.appendChild(this.triggerBtn),this.activeBar=document.createElement(`div`),this.activeBar.id=`fluidcad-trim-pick-active`,this.activeBar.className=`absolute top-4 left-1/2 -translate-x-1/2 z-[999] pointer-events-auto hidden`,this.activeBar.innerHTML=`
5393
5415
  <div class="flex items-center gap-3 panel-bg border border-base-content/10 rounded-lg px-6 py-3 text-base-content/70 text-sm leading-none select-none">
5394
- <span class="[&>svg]:size-5">${vh}</span>
5416
+ <span class="[&>svg]:size-5">${Mh}</span>
5395
5417
  <span>Trimming Mode</span>
5396
5418
  <div class="h-4 w-px bg-base-content/10"></div>
5397
5419
  <button class="text-base-content/60 hover:text-base-content transition-colors cursor-pointer" id="exit-trim-pick">Exit</button>
5398
5420
  </div>
5399
- `,e.appendChild(this.activeBar),this.triggerBtn.querySelector(`button`).addEventListener(`click`,()=>{this.enter()}),this.activeBar.querySelector(`#exit-trim-pick`).addEventListener(`click`,()=>{this.exit()})}get state(){return this._state}get lastPickInfo(){return this._lastPickInfo}get pendingActivation(){return this._pendingActivation}set pendingActivation(e){this._pendingActivation=e}update(e){let t=this.hasTrimPickingTrigger(e);if(!t.hasTrigger){this._pendingActivation||this.reset();return}this._lastPickInfo={trimObj:t.trimObj,sketchObj:t.sketchObj},this.lastSceneObjects=e;let n=t.trimObj.object?.picking;if(this._pendingActivation){this._pendingActivation=!1,this.enter(),this.activeBar.classList.add(`hidden`),this.triggerBtn.classList.add(`hidden`);return}if(this._state===`picking-active`){if(n){let n=this._lastPickInfo.trimObj.sourceLocation.line;if(this.activePointPickMode&&this.activePickSourceLine===n){this.activePointPickMode.updateEdges(e,t.sketchObj.id);return}this.activateInteractive(this._lastPickInfo,e)}return}this._state=`icon-visible`,this.triggerBtn.classList.remove(`hidden`),this.activeBar.classList.add(`hidden`)}enter(){if(this._lastPickInfo){if(!this._lastPickInfo.trimObj.object?.picking){Cm(this._lastPickInfo.trimObj.sourceLocation),this._state=`picking-active`,this.triggerBtn.classList.add(`hidden`),this.activeBar.classList.remove(`hidden`),this.viewer.isTrimming=!0;return}this.lastSceneObjects&&this.activateInteractive(this._lastPickInfo,this.lastSceneObjects),this._state=`picking-active`,this.triggerBtn.classList.add(`hidden`),this.activeBar.classList.remove(`hidden`),this.viewer.isTrimming=!0}}exit(){this.deactivateHandler(),this.viewer.isTrimming=!1;let e=this._lastPickInfo?.trimObj,t=e?.object?.picking,n=e?.object?.pickPoints;t&&(!n||n.length===0)&&e?.sourceLocation&&wm(e.sourceLocation),this._lastPickInfo?(this._state=`icon-visible`,this.activeBar.classList.add(`hidden`),this.triggerBtn.classList.remove(`hidden`)):(this._state=`idle`,this.activeBar.classList.add(`hidden`),this.triggerBtn.classList.add(`hidden`))}reset(){this.deactivateHandler(),this._state=`idle`,this.triggerBtn.classList.add(`hidden`),this.activeBar.classList.add(`hidden`),this._lastPickInfo=null,this.lastSceneObjects=null,this.viewer.isTrimming=!1}hideBars(){this.activeBar.classList.add(`hidden`),this.triggerBtn.classList.add(`hidden`)}activateInteractive(e,t){this.deactivateHandler();let n=e.sketchObj.object.plane,r=e.trimObj.sourceLocation,i=e.sketchObj.id,a=n_.fromSceneObjects(t,i,n,this.viewer.sceneContext);this.activePointPickMode=new Kg(this.viewer.sceneContext,n,a,t,i,e=>{xm(e,r)},e=>{this.viewer.clearHighlight(),this.clearVertexHighlights(),e&&(this.viewer.highlightShape(e.shapeId),this.highlightVerticesAt(e.endpoints))}),this.activePickSourceLine=r.line,this.activePointPickMode.activate()}deactivateHandler(){this.activePointPickMode&&(this.activePointPickMode.deactivate(),this.activePointPickMode=null,this.activePickSourceLine=null),this.clearVertexHighlights()}highlightVerticesAt(e){this.clearVertexHighlights(),e.length!==0&&(this.viewer.sceneContext.scene.traverse(t=>{if(!t.userData.isVertexDot)return;let n=t.children[0];if(!n||!n.isMesh)return;let r=t.position;for(let t of e){let e=r.x-t[0],i=r.y-t[1],a=r.z-t[2];if(e*e+i*i+a*a<a_){let e=n.material,t=e.clone();t.color.setHex(i_),n.material=t,this.highlightedVertexDots.push({mesh:n,originalMaterial:e});break}}}),this.viewer.sceneContext.requestRender())}clearVertexHighlights(){for(let{mesh:e,originalMaterial:t}of this.highlightedVertexDots)e.material.dispose(),e.material=t;this.highlightedVertexDots.length>0&&(this.highlightedVertexDots.length=0,this.viewer.sceneContext.requestRender())}hasTrimPickingTrigger(e){let t=null;for(let n=e.length-1;n>=0;n--)if(r_(e[n],e)){t=e[n];break}if(!t||t.type!==`sketch`||!t.id||!t.object?.plane)return{hasTrigger:!1};let n=null;for(let r=e.length-1;r>=0;r--)if(e[r].parentId===t.id){n=e[r];break}let r=n;return!r||r.type!==`trim2d`||r.object?.trigger!==`trim-picking`||!r.sourceLocation?{hasTrigger:!1}:{hasTrigger:!0,trimObj:n,sketchObj:t}}},s_=`#64B5F6`,c_=.35,l_=class{canvas;ctx;plane;onPick;onRemove;onHighlight;highlightedMesh=null;highlightedOriginalColor=null;highlightedOriginalOpacity=null;downX=0;downY=0;boundMouseDown;boundMouseUp;boundMouseMove;constructor(e,t,n,r,i){this.canvas=e.renderer.domElement,this.ctx=e,this.plane=t,this.onPick=n,this.onRemove=r,this.onHighlight=i,this.boundMouseDown=this.handleMouseDown.bind(this),this.boundMouseUp=this.handleMouseUp.bind(this),this.boundMouseMove=this.handleMouseMove.bind(this)}activate(){this.canvas.addEventListener(`mousedown`,this.boundMouseDown),this.canvas.addEventListener(`mouseup`,this.boundMouseUp),this.canvas.addEventListener(`mousemove`,this.boundMouseMove)}deactivate(){this.canvas.removeEventListener(`mousedown`,this.boundMouseDown),this.canvas.removeEventListener(`mouseup`,this.boundMouseUp),this.canvas.removeEventListener(`mousemove`,this.boundMouseMove),this.restoreHighlight()}handleMouseDown(e){this.downX=e.clientX,this.downY=e.clientY}handleMouseUp(e){let t=e.clientX-this.downX,n=e.clientY-this.downY;if(t*t+n*n>64)return;let r=this.projectToSketch(e.clientX,e.clientY);if(!r)return;let i=this.raycastRegions(e.clientX,e.clientY);if(!i)return;let a=i.mesh.parent;if(a?.userData.isPickRegionSelected===!0){let e=this.collectSelectedPickPoints(a);this.onRemove(e)}else{let e=[Math.round(r[0]*100)/100,Math.round(r[1]*100)/100];this.onPick(e)}}collectSelectedPickPoints(e){let t=[];return this.ctx.scene.traverse(n=>{n!==e&&n.userData.isPickRegion&&n.userData.isPickRegionSelected&&n.userData.metaData?.pickPoint&&t.push(n.userData.metaData.pickPoint)}),t}handleMouseMove(e){let t=this.raycastRegions(e.clientX,e.clientY)?.mesh??null;if(t!==this.highlightedMesh)if(this.restoreHighlight(),t){let e=t.material;this.highlightedOriginalColor=e.color.getHex(),this.highlightedOriginalOpacity=e.opacity,e.color.set(s_),e.opacity=c_,this.highlightedMesh=t;let n=null,r=t;for(;r;){if(r.userData.shapeId){n=r.userData.shapeId;break}r=r.parent}this.onHighlight(n),this.ctx.requestRender()}else this.highlightedMesh=null,this.onHighlight(null),this.ctx.requestRender()}restoreHighlight(){if(this.highlightedMesh){let e=this.highlightedMesh.material;this.highlightedOriginalColor!==null&&e.color.setHex(this.highlightedOriginalColor),this.highlightedOriginalOpacity!==null&&(e.opacity=this.highlightedOriginalOpacity),this.highlightedMesh=null,this.highlightedOriginalColor=null,this.highlightedOriginalOpacity=null}}raycastRegions(e,t){let n=this.ctx.renderer.domElement.getBoundingClientRect(),r=(e-n.left)/n.width*2-1,i=-((t-n.top)/n.height)*2+1,a=this.ctx.createPickingRaycaster(r,i),o=[];if(this.ctx.scene.traverse(e=>{if(e.userData.isPickRegion&&e.children)for(let t of e.children)t.isMesh&&o.push(t)}),o.length===0)return null;let s=a.intersectObjects(o,!1);return s.length===0?null:{mesh:s[0].object,point:s[0].point}}projectToSketch(e,t){let n=this.ctx.renderer.domElement.getBoundingClientRect(),r=(e-n.left)/n.width*2-1,i=-((t-n.top)/n.height)*2+1,a=this.ctx.createPickingRaycaster(r,i),o=a.ray.origin,s=a.ray.direction,c=new R(this.plane.origin.x,this.plane.origin.y,this.plane.origin.z),l=new R(this.plane.normal.x,this.plane.normal.y,this.plane.normal.z),u=s.dot(l);if(Math.abs(u)<1e-6)return null;let d=c.clone().sub(o).dot(l)/u;if(d<0)return null;let f=o.clone().add(s.clone().multiplyScalar(d)).clone().sub(c),p=new R(this.plane.xDirection.x,this.plane.xDirection.y,this.plane.xDirection.z),m=new R(this.plane.yDirection.x,this.plane.yDirection.y,this.plane.yDirection.z);return[f.dot(p),f.dot(m)]}},u_=[`extrude`,`cut`,`cut-symmetric`,`revolve`,`sweep`],d_=class{viewer;triggerBtn;activeBar;_state=`idle`;lastInfo=null;activeMode=null;activeSourceLine=null;constructor(e,t){this.viewer=t,this.triggerBtn=document.createElement(`div`),this.triggerBtn.id=`fluidcad-region-pick-trigger`,this.triggerBtn.className=`absolute top-4 left-1/2 -translate-x-1/2 z-[999] pointer-events-auto hidden`,this.triggerBtn.innerHTML=`
5421
+ `,e.appendChild(this.activeBar),this.triggerBtn.querySelector(`button`).addEventListener(`click`,()=>{this.enter()}),this.activeBar.querySelector(`#exit-trim-pick`).addEventListener(`click`,()=>{this.exit()})}get state(){return this._state}get lastPickInfo(){return this._lastPickInfo}get pendingActivation(){return this._pendingActivation}set pendingActivation(e){this._pendingActivation=e}update(e){let t=this.hasTrimPickingTrigger(e);if(!t.hasTrigger){this._pendingActivation||this.reset();return}this._lastPickInfo={trimObj:t.trimObj,sketchObj:t.sketchObj},this.lastSceneObjects=e;let n=t.trimObj.object?.picking;if(this._pendingActivation){this._pendingActivation=!1,this.enter(),this.activeBar.classList.add(`hidden`),this.triggerBtn.classList.add(`hidden`);return}if(this._state===`picking-active`){if(n){let n=this._lastPickInfo.trimObj.sourceLocation.line;if(this.activePointPickMode&&this.activePickSourceLine===n){this.activePointPickMode.updateEdges(e,t.sketchObj.id);return}this.activateInteractive(this._lastPickInfo,e)}return}this._state=`icon-visible`,this.triggerBtn.classList.remove(`hidden`),this.activeBar.classList.add(`hidden`)}enter(){if(this._lastPickInfo){if(!this._lastPickInfo.trimObj.object?.picking){Fm(this._lastPickInfo.trimObj.sourceLocation),this._state=`picking-active`,this.triggerBtn.classList.add(`hidden`),this.activeBar.classList.remove(`hidden`),this.viewer.isTrimming=!0;return}this.lastSceneObjects&&this.activateInteractive(this._lastPickInfo,this.lastSceneObjects),this._state=`picking-active`,this.triggerBtn.classList.add(`hidden`),this.activeBar.classList.remove(`hidden`),this.viewer.isTrimming=!0}}exit(){this.deactivateHandler(),this.viewer.isTrimming=!1;let e=this._lastPickInfo?.trimObj,t=e?.object?.picking,n=e?.object?.pickPoints;t&&(!n||n.length===0)&&e?.sourceLocation&&Im(e.sourceLocation),this._lastPickInfo?(this._state=`icon-visible`,this.activeBar.classList.add(`hidden`),this.triggerBtn.classList.remove(`hidden`)):(this._state=`idle`,this.activeBar.classList.add(`hidden`),this.triggerBtn.classList.add(`hidden`))}reset(){this.deactivateHandler(),this._state=`idle`,this.triggerBtn.classList.add(`hidden`),this.activeBar.classList.add(`hidden`),this._lastPickInfo=null,this.lastSceneObjects=null,this.viewer.isTrimming=!1}hideBars(){this.activeBar.classList.add(`hidden`),this.triggerBtn.classList.add(`hidden`)}activateInteractive(e,t){this.deactivateHandler();let n=e.sketchObj.object.plane,r=e.trimObj.sourceLocation,i=e.sketchObj.id,a=v_.fromSceneObjects(t,i,n,this.viewer.sceneContext);this.activePointPickMode=new c_(this.viewer.sceneContext,n,a,t,i,e=>{Nm(e,r)},e=>{this.viewer.clearHighlight(),this.clearVertexHighlights(),e&&(this.viewer.highlightShape(e.shapeId),this.highlightVerticesAt(e.endpoints))}),this.activePickSourceLine=r.line,this.activePointPickMode.activate()}deactivateHandler(){this.activePointPickMode&&(this.activePointPickMode.deactivate(),this.activePointPickMode=null,this.activePickSourceLine=null),this.clearVertexHighlights()}highlightVerticesAt(e){this.clearVertexHighlights(),e.length!==0&&(this.viewer.sceneContext.scene.traverse(t=>{if(!t.userData.isVertexDot)return;let n=t.children[0];if(!n||!n.isMesh)return;let r=t.position;for(let t of e){let e=r.x-t[0],i=r.y-t[1],a=r.z-t[2];if(e*e+i*i+a*a<x_){let e=n.material,t=e.clone();t.color.setHex(b_),n.material=t,this.highlightedVertexDots.push({mesh:n,originalMaterial:e});break}}}),this.viewer.sceneContext.requestRender())}clearVertexHighlights(){for(let{mesh:e,originalMaterial:t}of this.highlightedVertexDots)e.material.dispose(),e.material=t;this.highlightedVertexDots.length>0&&(this.highlightedVertexDots.length=0,this.viewer.sceneContext.requestRender())}hasTrimPickingTrigger(e){let t=null;for(let n=e.length-1;n>=0;n--)if(y_(e[n],e)){t=e[n];break}if(!t||t.type!==`sketch`||!t.id||!t.object?.plane)return{hasTrigger:!1};let n=null;for(let r=e.length-1;r>=0;r--)if(e[r].parentId===t.id){n=e[r];break}let r=n;return!r||r.type!==`trim2d`||r.object?.trigger!==`trim-picking`||!r.sourceLocation?{hasTrigger:!1}:{hasTrigger:!0,trimObj:n,sketchObj:t}}},C_=`#64B5F6`,w_=.35,T_=class{canvas;ctx;plane;onPick;onRemove;onHighlight;highlightedMesh=null;highlightedOriginalColor=null;highlightedOriginalOpacity=null;downX=0;downY=0;boundMouseDown;boundMouseUp;boundMouseMove;constructor(e,t,n,r,i){this.canvas=e.renderer.domElement,this.ctx=e,this.plane=t,this.onPick=n,this.onRemove=r,this.onHighlight=i,this.boundMouseDown=this.handleMouseDown.bind(this),this.boundMouseUp=this.handleMouseUp.bind(this),this.boundMouseMove=this.handleMouseMove.bind(this)}activate(){this.canvas.addEventListener(`mousedown`,this.boundMouseDown),this.canvas.addEventListener(`mouseup`,this.boundMouseUp),this.canvas.addEventListener(`mousemove`,this.boundMouseMove)}deactivate(){this.canvas.removeEventListener(`mousedown`,this.boundMouseDown),this.canvas.removeEventListener(`mouseup`,this.boundMouseUp),this.canvas.removeEventListener(`mousemove`,this.boundMouseMove),this.restoreHighlight()}handleMouseDown(e){this.downX=e.clientX,this.downY=e.clientY}handleMouseUp(e){let t=e.clientX-this.downX,n=e.clientY-this.downY;if(t*t+n*n>64)return;let r=this.projectToSketch(e.clientX,e.clientY);if(!r)return;let i=this.raycastRegions(e.clientX,e.clientY);if(!i)return;let a=i.mesh.parent;if(a?.userData.isPickRegionSelected===!0){let e=this.collectSelectedPickPoints(a);this.onRemove(e)}else{let e=[Math.round(r[0]*100)/100,Math.round(r[1]*100)/100];this.onPick(e)}}collectSelectedPickPoints(e){let t=[];return this.ctx.scene.traverse(n=>{n!==e&&n.userData.isPickRegion&&n.userData.isPickRegionSelected&&n.userData.metaData?.pickPoint&&t.push(n.userData.metaData.pickPoint)}),t}handleMouseMove(e){let t=this.raycastRegions(e.clientX,e.clientY)?.mesh??null;if(t!==this.highlightedMesh)if(this.restoreHighlight(),t){let e=t.material;this.highlightedOriginalColor=e.color.getHex(),this.highlightedOriginalOpacity=e.opacity,e.color.set(C_),e.opacity=w_,this.highlightedMesh=t;let n=null,r=t;for(;r;){if(r.userData.shapeId){n=r.userData.shapeId;break}r=r.parent}this.onHighlight(n),this.ctx.requestRender()}else this.highlightedMesh=null,this.onHighlight(null),this.ctx.requestRender()}restoreHighlight(){if(this.highlightedMesh){let e=this.highlightedMesh.material;this.highlightedOriginalColor!==null&&e.color.setHex(this.highlightedOriginalColor),this.highlightedOriginalOpacity!==null&&(e.opacity=this.highlightedOriginalOpacity),this.highlightedMesh=null,this.highlightedOriginalColor=null,this.highlightedOriginalOpacity=null}}raycastRegions(e,t){let n=this.ctx.renderer.domElement.getBoundingClientRect(),r=(e-n.left)/n.width*2-1,i=-((t-n.top)/n.height)*2+1,a=this.ctx.createPickingRaycaster(r,i),o=[];if(this.ctx.scene.traverse(e=>{if(e.userData.isPickRegion&&e.children)for(let t of e.children)t.isMesh&&o.push(t)}),o.length===0)return null;let s=a.intersectObjects(o,!1);return s.length===0?null:{mesh:s[0].object,point:s[0].point}}projectToSketch(e,t){let n=this.ctx.renderer.domElement.getBoundingClientRect(),r=(e-n.left)/n.width*2-1,i=-((t-n.top)/n.height)*2+1,a=this.ctx.createPickingRaycaster(r,i),o=a.ray.origin,s=a.ray.direction,c=new R(this.plane.origin.x,this.plane.origin.y,this.plane.origin.z),l=new R(this.plane.normal.x,this.plane.normal.y,this.plane.normal.z),u=s.dot(l);if(Math.abs(u)<1e-6)return null;let d=c.clone().sub(o).dot(l)/u;if(d<0)return null;let f=o.clone().add(s.clone().multiplyScalar(d)).clone().sub(c),p=new R(this.plane.xDirection.x,this.plane.xDirection.y,this.plane.xDirection.z),m=new R(this.plane.yDirection.x,this.plane.yDirection.y,this.plane.yDirection.z);return[f.dot(p),f.dot(m)]}},E_=[`extrude`,`cut`,`cut-symmetric`,`revolve`,`sweep`,`wrap`],D_=class{viewer;triggerBtn;activeBar;_state=`idle`;lastInfo=null;activeMode=null;activeSourceLine=null;constructor(e,t){this.viewer=t,this.triggerBtn=document.createElement(`div`),this.triggerBtn.id=`fluidcad-region-pick-trigger`,this.triggerBtn.className=`absolute top-4 left-1/2 -translate-x-1/2 z-[999] pointer-events-auto hidden`,this.triggerBtn.innerHTML=`
5400
5422
  <button class="flex items-center gap-3 panel-bg border border-base-content/10 rounded-lg px-6 py-3 text-base-content/70 text-sm leading-none select-none cursor-pointer hover:border-base-content/20 transition-colors">
5401
- <span class="[&>svg]:size-5">${Sh}</span>
5423
+ <span class="[&>svg]:size-5">${Ih}</span>
5402
5424
  <span>Pick Regions</span>
5403
5425
  </button>
5404
5426
  `,e.appendChild(this.triggerBtn),this.activeBar=document.createElement(`div`),this.activeBar.id=`fluidcad-region-pick-active`,this.activeBar.className=`absolute top-4 left-1/2 -translate-x-1/2 z-[999] pointer-events-auto hidden`,this.activeBar.innerHTML=`
@@ -5407,11 +5429,36 @@ void main() {
5407
5429
  <div class="h-4 w-px bg-base-content/10"></div>
5408
5430
  <button class="text-base-content/60 hover:text-base-content transition-colors cursor-pointer" id="exit-region-pick">Exit</button>
5409
5431
  </div>
5410
- `,e.appendChild(this.activeBar),this.triggerBtn.querySelector(`button`).addEventListener(`click`,()=>{this.enter()}),this.activeBar.querySelector(`#exit-region-pick`).addEventListener(`click`,()=>{this.exit()})}get state(){return this._state}update(e){let t=this.hasRegionPickingTrigger(e),n=t.extrudeObj?.object?.pickPlane||t.sketchObj?.object?.plane;if(!t.hasTrigger||!t.extrudeObj?.sourceLocation||!n){this.reset();return}this.lastInfo={extrudeObj:t.extrudeObj,sketchObj:t.sketchObj};let r=t.extrudeObj.object?.picking;if(this._state===`picking-active`){if(r){let e=this.lastInfo.extrudeObj.sourceLocation.line;if(this.activeMode&&this.activeSourceLine===e)return;this.activateInteractive(this.lastInfo)}return}this._state=`icon-visible`,this.triggerBtn.classList.remove(`hidden`),this.activeBar.classList.add(`hidden`)}enter(){if(this.lastInfo){if(!this.lastInfo.extrudeObj.object?.picking){Cm(this.lastInfo.extrudeObj.sourceLocation),this._state=`picking-active`,this.triggerBtn.classList.add(`hidden`),this.activeBar.classList.remove(`hidden`),this.viewer.isRegionPicking=!0,this.viewer.toggleSketchMode(!1);return}this.activateInteractive(this.lastInfo),this._state=`picking-active`,this.triggerBtn.classList.add(`hidden`),this.activeBar.classList.remove(`hidden`),this.viewer.isRegionPicking=!0,this.viewer.toggleSketchMode(!1),this.viewer.rebuildSceneMesh()}}exit(){this.deactivateHandler(),this.viewer.isRegionPicking=!1,this.viewer.toggleSketchMode(!0),this.viewer.rebuildSceneMesh();let e=this.lastInfo?.extrudeObj,t=e?.object?.picking,n=e?.object?.pickPoints;t&&(!n||n.length===0)&&e?.sourceLocation&&wm(e.sourceLocation),this.lastInfo?(this._state=`icon-visible`,this.activeBar.classList.add(`hidden`),this.triggerBtn.classList.remove(`hidden`)):(this._state=`idle`,this.activeBar.classList.add(`hidden`),this.triggerBtn.classList.add(`hidden`))}reset(){this.deactivateHandler(),this._state=`idle`,this.triggerBtn.classList.add(`hidden`),this.activeBar.classList.add(`hidden`),this.lastInfo=null,this.viewer.isRegionPicking=!1,this.viewer.toggleSketchMode(!0)}activateInteractive(e){this.deactivateHandler();let t=e.extrudeObj.object?.pickPlane??e.sketchObj.object.plane,n=e.extrudeObj.sourceLocation;this.activeMode=new l_(this.viewer.sceneContext,t,e=>{xm(e,n)},e=>{Sm(e,n)},e=>{}),this.activeSourceLine=n.line,this.activeMode.activate()}deactivateHandler(){this.activeMode&&(this.activeMode.deactivate(),this.activeMode=null,this.activeSourceLine=null)}hasRegionPickingTrigger(e){let t=[`plane`,`axis`],n;for(let r=e.length-1;r>=0;r--){let i=e[r];if(!i.parentId&&!t.includes(i.type)){n=i;break}}if(!n)return{hasTrigger:!1};let r=n;if(!u_.includes(r.type)||r.object?.trigger!==`region-picking`||r.object?.thin)return{hasTrigger:!1};let i=e.indexOf(n),a;for(let t=i-1;t>=0;t--)if(e[t].type===`sketch`&&e[t].parentId===r.parentId){a=e[t];break}return{hasTrigger:!0,extrudeObj:n,sketchObj:a}}},f_=/^F([1-9]|1[0-9])$/;function p_(e){return!1}function m_(e){if(!(e instanceof Element))return!1;let t=e.tagName;return t===`INPUT`||t===`TEXTAREA`||t===`SELECT`?!0:e instanceof HTMLElement&&e.isContentEditable}function h_(e){return!(e.defaultPrevented||p_(e)||e.key===`Control`||e.key===`Alt`||e.key===`Meta`||e.key===`Shift`||m_(e.target)||!(e.ctrlKey||e.metaKey||e.altKey)&&!f_.test(e.key))}function g_(){window.parent!==window&&window.addEventListener(`keydown`,e=>{h_(e)&&window.parent.postMessage({type:`fluidcad-keydown`,key:e.key,code:e.code,ctrlKey:e.ctrlKey,shiftKey:e.shiftKey,altKey:e.altKey,metaKey:e.metaKey,repeat:e.repeat},`*`)},!1)}function __(){return{children:new Map,action:null}}var v_=class{root=__();buffer=``;timerId=null;pendingAction=null;enabled=!1;timeout;boundHandler;constructor(e){this.timeout=e?.timeout??300,this.boundHandler=this.handleKeyDown.bind(this)}register(e,t){let n=this.root;for(let t of e){let e=n.children.get(t);e||(e=__(),n.children.set(t,e)),n=e}n.action=t}enable(){this.enabled||(this.enabled=!0,this.resetState(),window.addEventListener(`keydown`,this.boundHandler))}disable(){if(this.enabled){if(this.enabled=!1,this.pendingAction){let e=this.pendingAction;this.resetState(),e()}else this.resetState();window.removeEventListener(`keydown`,this.boundHandler)}}destroy(){this.disable(),this.root=__()}handleKeyDown(e){if(e.repeat)return;if(e.ctrlKey||e.metaKey||e.altKey){this.firePendingAndReset();return}if(m_(e.target))return;let t=e.key.toLowerCase();if(t===`escape`){this.resetState();return}if(t.length!==1||t<`a`||t>`z`){this.firePendingAndReset();return}this.clearTimer();let n=this.buffer+t,{exactMatch:r,hasLongerPrefix:i}=this.lookupTrie(n);if(r&&!i){e.preventDefault();let t=r;this.resetState(),t()}else if(r&&i)e.preventDefault(),this.buffer=n,this.pendingAction=r,this.startTimer();else if(i)e.preventDefault(),this.buffer=n,this.startTimer();else if(this.pendingAction){e.preventDefault();let t=this.pendingAction;this.resetState(),t()}else this.resetState()}lookupTrie(e){let t=this.root;for(let n of e){let e=t.children.get(n);if(!e)return{exactMatch:null,hasLongerPrefix:!1};t=e}return{exactMatch:t.action,hasLongerPrefix:t.children.size>0}}firePendingAndReset(){if(this.pendingAction){let e=this.pendingAction;this.resetState(),e()}else this.resetState()}resetState(){this.clearTimer(),this.buffer=``,this.pendingAction=null}clearTimer(){this.timerId!==null&&(clearTimeout(this.timerId),this.timerId=null)}startTimer(){this.clearTimer(),this.timerId=setTimeout(()=>{this.timerId=null,this.firePendingAndReset()},this.timeout)}};function y_(e){return`tools`in e}var b_=[{tools:[{id:`line`,label:`Line`,icon:Nh},{id:`polyline`,label:`Polyline`,icon:Vh},{id:`bezier`,label:`Bezier`,icon:Hh}]},{tools:[{id:`circle`,label:`Circle`,icon:Ph},{id:`polygon`,label:`Polygon`,icon:Bh}]},{tools:[{id:`rect`,label:`Rectangle`,icon:Lh},{id:`rounded-rect`,label:`Rounded Rectangle`,icon:Rh}]},{tools:[{id:`arc3`,label:`3-Point Arc`,icon:Ih},{id:`arc2`,label:`Center Arc`,icon:Fh}]},{tools:[{id:`slot`,label:`Slot`,icon:zh}]},{tools:[{id:`trim`,label:`Trim`,icon:vh}]}],x_={circle:`c`,rect:`r`,"rounded-rect":`rr`,line:`l`,polygon:`p`,polyline:`ll`,arc3:`a`,arc2:`ca`,bezier:`b`,trim:`t`},S_=`btn btn-ghost btn-square btn-sm text-base-content/60`,C_=`btn btn-soft btn-primary btn-square btn-sm`,w_=class{el;inner;snapMenu=null;onToolSelect;activeToolId=null;buttons=new Map;shortcutManager;boundKeyDown;boundCloseSnapMenu;snapVertexCheckedState=!0;snapGridCheckedState=!0;onSnapVerticesChange=null;onSnapGridChange=null;constructor(e,t){this.onToolSelect=t,this.el=document.createElement(`div`),this.el.className=`absolute top-1/2 -translate-y-1/2 left-0 select-none pointer-events-auto flex flex-col items-center gap-1.5`,this.el.style.transition=`transform 0.25s ease, opacity 0.25s ease`,this.el.style.transform=`translateX(-100%)`,this.el.style.opacity=`0`,this.inner=document.createElement(`div`),this.inner.className=`flex flex-col gap-0.5 panel-bg border border-base-content/10 rounded-md p-1`,this.el.appendChild(this.inner),this.buildSnapButton(),this.renderTools(),e.appendChild(this.el),this.boundKeyDown=this.handleKeyDown.bind(this),this.boundCloseSnapMenu=this.handleCloseSnapMenu.bind(this),this.shortcutManager=new v_({timeout:200});for(let[e,t]of Object.entries(x_))this.shortcutManager.register(t,()=>this.handleToolClick(e))}show(){this.el.style.transform=``,this.el.style.opacity=``,window.addEventListener(`keydown`,this.boundKeyDown),this.shortcutManager.enable()}hide(){this.el.style.transform=`translateX(-100%)`,this.el.style.opacity=`0`,this.closeSnapMenu(),window.removeEventListener(`keydown`,this.boundKeyDown),this.shortcutManager.disable(),this.activeToolId&&this.setActiveTool(null)}get isVisible(){return this.el.style.transform===``}setActiveTool(e){this.activeToolId!==e&&(this.activeToolId=e,this.syncButtonStates())}get activeTool(){return this.activeToolId}get snapVerticesChecked(){return this.snapVertexCheckedState}get snapGridChecked(){return this.snapGridCheckedState}buildSnapButton(){let e=document.createElement(`div`);e.className=`relative`;let t=document.createElement(`button`);t.className=S_,t.innerHTML=`<span class="[&>svg]:size-5">${jh}</span>`,t.addEventListener(`click`,t=>{t.stopPropagation(),this.snapMenu?this.closeSnapMenu():this.openSnapMenu(e)}),e.appendChild(t),this.el.appendChild(e)}openSnapMenu(e){this.closeSnapMenu();let t=document.createElement(`div`);t.className=`absolute left-full top-1/2 -translate-y-1/2 ml-2 z-[200] panel-bg border border-base-content/10 rounded-md shadow-[0_4px_12px_rgba(0,0,0,0.4)] p-2 flex flex-col gap-2 whitespace-nowrap`;let n=document.createElement(`input`);n.type=`checkbox`,n.className=`checkbox checkbox-xs checkbox-primary`,n.checked=this.snapVertexCheckedState,n.addEventListener(`change`,()=>{this.snapVertexCheckedState=n.checked,this.onSnapVerticesChange?.(n.checked)});let r=document.createElement(`label`);r.className=`flex items-center gap-2 cursor-pointer`,r.appendChild(n);let i=document.createElement(`span`);i.className=`text-xs text-base-content/70`,i.textContent=`Snap to vertices`,r.appendChild(i);let a=document.createElement(`input`);a.type=`checkbox`,a.className=`checkbox checkbox-xs checkbox-primary`,a.checked=this.snapGridCheckedState,a.addEventListener(`change`,()=>{this.snapGridCheckedState=a.checked,this.onSnapGridChange?.(a.checked)});let o=document.createElement(`label`);o.className=`flex items-center gap-2 cursor-pointer`,o.appendChild(a);let s=document.createElement(`span`);s.className=`text-xs text-base-content/70`,s.textContent=`Snap to grid`,o.appendChild(s),t.appendChild(r),t.appendChild(o),e.appendChild(t),this.snapMenu=t,setTimeout(()=>document.addEventListener(`click`,this.boundCloseSnapMenu),0)}closeSnapMenu(){this.snapMenu&&(this.snapMenu.remove(),this.snapMenu=null,document.removeEventListener(`click`,this.boundCloseSnapMenu))}handleCloseSnapMenu(e){this.snapMenu&&!this.snapMenu.contains(e.target)&&!this.snapMenu.parentElement?.contains(e.target)&&this.closeSnapMenu()}renderTools(){this.inner.innerHTML=``,this.buttons.clear();for(let e=0;e<b_.length;e++){if(e>0){let e=document.createElement(`div`);e.className=`h-px bg-base-content/[0.08] my-0.5`,this.inner.appendChild(e)}let t=b_[e];y_(t)?this.renderGroup(t):this.inner.appendChild(this.createToolButton(t))}}renderGroup(e){if(e.tools.length===1){this.inner.appendChild(this.createToolButton(e.tools[0]));return}let t=document.createElement(`div`);t.className=`flex flex-col items-center`;for(let n of e.tools)t.appendChild(this.createToolButton(n));this.inner.appendChild(t)}createToolButton(e){let t=document.createElement(`div`);t.className=`relative group`;let n=document.createElement(`button`);n.className=e.id===this.activeToolId?C_:S_,n.innerHTML=`<span class="[&>svg]:size-5">${e.icon}</span>`,n.addEventListener(`click`,()=>this.handleToolClick(e.id));let r=x_[e.id],i=document.createElement(`div`);return i.className=`absolute left-full top-1/2 -translate-y-1/2 ml-2 px-2 py-1 rounded bg-base-300 text-base-content text-xs whitespace-nowrap opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity flex items-center gap-1.5`,i.innerHTML=r?`${e.label} <kbd class="kbd kbd-xs">${r}</kbd>`:e.label,t.appendChild(n),t.appendChild(i),this.buttons.set(e.id,n),t}syncButtonStates(){for(let[e,t]of this.buttons)t.className=e===this.activeToolId?C_:S_}handleToolClick(e){this.activeToolId===e?this.onToolSelect(null):this.onToolSelect(e)}handleKeyDown(e){e.key===`Escape`&&this.activeToolId&&(e.preventDefault(),e.stopPropagation(),this.onToolSelect(null))}},T_=class{ctx;plane;snapController;previewGroup;insertGeometry;canvas;currentPosition=null;constructor(e,t,n,r){this.ctx=e,this.plane=t,this.snapController=n,this.insertGeometry=r,this.canvas=e.renderer.domElement,this.previewGroup=new si,this.previewGroup.userData.isMetaShape=!0,this.previewGroup.renderOrder=3}updatePlane(e){this.plane=e}updateSnapManager(e){this.snapController.updateSnapManager(e)}updateCurrentPosition(e){e?this.currentPosition=vp(e,this.plane):this.currentPosition=null}isAtCurrentPosition(e){if(!this.currentPosition)return!1;let t=yp(this.ctx,15);return bp(e,this.currentPosition)<=t}disposePreview(){for(;this.previewGroup.children.length>0;){let e=this.previewGroup.children[0];this.previewGroup.remove(e);let t=e;t.geometry&&t.geometry.dispose(),t.material&&t.material.dispose()}}addPreviewToScene(){this.ctx.scene.add(this.previewGroup)}removePreviewFromScene(){this.ctx.scene.remove(this.previewGroup),this.disposePreview(),this.ctx.requestRender()}requestRender(){this.ctx.requestRender()}formatPoint(e){return`[${e[0]}, ${e[1]}]`}},E_=16,D_=-36,O_=/^[a-zA-Z_$][\w$]*$/,k_=/^([a-zA-Z_$][\w$]*)\s*=\s*(.+?)\s*;?\s*$/,A_=new Set(`const.let.var.if.else.for.while.do.return.function.class.new.this.true.false.null.undefined.typeof.instanceof.switch.case.break.continue.default.try.catch.finally.throw.in.of.delete.void.yield.async.await.import.export.from.as.extends.super.static.enum.interface.implements.package.private.protected.public`.split(`.`));function j_(e){return O_.test(e)&&!A_.has(e)}var M_=class{el;wrapperEl;input;label;dropdown;errorEl;onCommit=null;visible=!1;userIsTyping=!1;variables=[];filteredVars=[];selectedIndex=-1;seedValue=``;errorVisible=!1;numericOnly=!1;onSpaceOverride=null;constructor(e){this.el=document.createElement(`div`),this.el.className=`absolute z-[1000] pointer-events-auto hidden`,this.el.innerHTML=`
5432
+ `,e.appendChild(this.activeBar),this.triggerBtn.querySelector(`button`).addEventListener(`click`,()=>{this.enter()}),this.activeBar.querySelector(`#exit-region-pick`).addEventListener(`click`,()=>{this.exit()})}get state(){return this._state}update(e){let t=this.hasRegionPickingTrigger(e),n=t.extrudeObj?.object?.pickPlane||t.sketchObj?.object?.plane;if(!t.hasTrigger||!t.extrudeObj?.sourceLocation||!n){this.reset();return}this.lastInfo={extrudeObj:t.extrudeObj,sketchObj:t.sketchObj};let r=t.extrudeObj.object?.picking;if(this._state===`picking-active`){if(r){let e=this.lastInfo.extrudeObj.sourceLocation.line;if(this.activeMode&&this.activeSourceLine===e)return;this.activateInteractive(this.lastInfo)}return}this._state=`icon-visible`,this.triggerBtn.classList.remove(`hidden`),this.activeBar.classList.add(`hidden`)}enter(){if(this.lastInfo){if(!this.lastInfo.extrudeObj.object?.picking){Fm(this.lastInfo.extrudeObj.sourceLocation),this._state=`picking-active`,this.triggerBtn.classList.add(`hidden`),this.activeBar.classList.remove(`hidden`),this.viewer.isRegionPicking=!0,this.viewer.toggleSketchMode(!1);return}this.activateInteractive(this.lastInfo),this._state=`picking-active`,this.triggerBtn.classList.add(`hidden`),this.activeBar.classList.remove(`hidden`),this.viewer.isRegionPicking=!0,this.viewer.toggleSketchMode(!1),this.viewer.rebuildSceneMesh()}}exit(){this.deactivateHandler(),this.viewer.isRegionPicking=!1,this.viewer.toggleSketchMode(!0),this.viewer.rebuildSceneMesh();let e=this.lastInfo?.extrudeObj,t=e?.object?.picking,n=e?.object?.pickPoints;t&&(!n||n.length===0)&&e?.sourceLocation&&Im(e.sourceLocation),this.lastInfo?(this._state=`icon-visible`,this.activeBar.classList.add(`hidden`),this.triggerBtn.classList.remove(`hidden`)):(this._state=`idle`,this.activeBar.classList.add(`hidden`),this.triggerBtn.classList.add(`hidden`))}reset(){this.deactivateHandler(),this._state=`idle`,this.triggerBtn.classList.add(`hidden`),this.activeBar.classList.add(`hidden`),this.lastInfo=null,this.viewer.isRegionPicking=!1,this.viewer.toggleSketchMode(!0)}activateInteractive(e){this.deactivateHandler();let t=e.extrudeObj.object?.pickPlane??e.sketchObj.object.plane,n=e.extrudeObj.sourceLocation;this.activeMode=new T_(this.viewer.sceneContext,t,e=>{Nm(e,n)},e=>{Pm(e,n)},e=>{}),this.activeSourceLine=n.line,this.activeMode.activate()}deactivateHandler(){this.activeMode&&(this.activeMode.deactivate(),this.activeMode=null,this.activeSourceLine=null)}hasRegionPickingTrigger(e){let t=[`plane`,`axis`],n;for(let r=e.length-1;r>=0;r--){let i=e[r];if(!i.parentId&&!t.includes(i.type)){n=i;break}}if(!n)return{hasTrigger:!1};let r=n;if(!E_.includes(r.type)||r.object?.trigger!==`region-picking`||r.object?.thin)return{hasTrigger:!1};let i=e.indexOf(n),a;for(let t=i-1;t>=0;t--)if(e[t].type===`sketch`&&e[t].parentId===r.parentId){a=e[t];break}return{hasTrigger:!0,extrudeObj:n,sketchObj:a}}},O_=/^F([1-9]|1[0-9])$/;function k_(e){return!1}function A_(e){if(!(e instanceof Element))return!1;let t=e.tagName;return t===`INPUT`||t===`TEXTAREA`||t===`SELECT`?!0:e instanceof HTMLElement&&e.isContentEditable}function j_(e){return!(e.defaultPrevented||k_(e)||e.key===`Control`||e.key===`Alt`||e.key===`Meta`||e.key===`Shift`||A_(e.target)||!(e.ctrlKey||e.metaKey||e.altKey)&&!O_.test(e.key))}function M_(){window.parent!==window&&window.addEventListener(`keydown`,e=>{j_(e)&&window.parent.postMessage({type:`fluidcad-keydown`,key:e.key,code:e.code,ctrlKey:e.ctrlKey,shiftKey:e.shiftKey,altKey:e.altKey,metaKey:e.metaKey,repeat:e.repeat},`*`)},!1)}function N_(){return{children:new Map,action:null}}var P_=class{root=N_();buffer=``;timerId=null;pendingAction=null;enabled=!1;timeout;boundHandler;constructor(e){this.timeout=e?.timeout??300,this.boundHandler=this.handleKeyDown.bind(this)}register(e,t){let n=this.root;for(let t of e){let e=n.children.get(t);e||(e=N_(),n.children.set(t,e)),n=e}n.action=t}enable(){this.enabled||(this.enabled=!0,this.resetState(),window.addEventListener(`keydown`,this.boundHandler))}disable(){if(this.enabled){if(this.enabled=!1,this.pendingAction){let e=this.pendingAction;this.resetState(),e()}else this.resetState();window.removeEventListener(`keydown`,this.boundHandler)}}destroy(){this.disable(),this.root=N_()}handleKeyDown(e){if(e.repeat)return;if(e.ctrlKey||e.metaKey||e.altKey){this.firePendingAndReset();return}if(A_(e.target))return;let t=e.key.toLowerCase();if(t===`escape`){this.resetState();return}if(t.length!==1||t<`a`||t>`z`){this.firePendingAndReset();return}this.clearTimer();let n=this.buffer+t,{exactMatch:r,hasLongerPrefix:i}=this.lookupTrie(n);if(r&&!i){e.preventDefault();let t=r;this.resetState(),t()}else if(r&&i)e.preventDefault(),this.buffer=n,this.pendingAction=r,this.startTimer();else if(i)e.preventDefault(),this.buffer=n,this.startTimer();else if(this.pendingAction){e.preventDefault();let t=this.pendingAction;this.resetState(),t()}else this.resetState()}lookupTrie(e){let t=this.root;for(let n of e){let e=t.children.get(n);if(!e)return{exactMatch:null,hasLongerPrefix:!1};t=e}return{exactMatch:t.action,hasLongerPrefix:t.children.size>0}}firePendingAndReset(){if(this.pendingAction){let e=this.pendingAction;this.resetState(),e()}else this.resetState()}resetState(){this.clearTimer(),this.buffer=``,this.pendingAction=null}clearTimer(){this.timerId!==null&&(clearTimeout(this.timerId),this.timerId=null)}startTimer(){this.clearTimer(),this.timerId=setTimeout(()=>{this.timerId=null,this.firePendingAndReset()},this.timeout)}};function F_(e){return`tools`in e}var I_=[{tools:[{id:`line`,label:`Line`,icon:Jh},{id:`polyline`,label:`Polyline`,icon:ng},{id:`bezier`,label:`Bezier`,icon:rg}]},{tools:[{id:`circle`,label:`Circle`,icon:Yh},{id:`polygon`,label:`Polygon`,icon:tg}]},{tools:[{id:`rect`,label:`Rectangle`,icon:Qh},{id:`rounded-rect`,label:`Rounded Rectangle`,icon:$h}]},{tools:[{id:`arc3`,label:`3-Point Arc`,icon:Zh},{id:`arc2`,label:`Center Arc`,icon:Xh}]},{tools:[{id:`slot`,label:`Slot`,icon:eg}]},{tools:[{id:`trim`,label:`Trim`,icon:Mh}]}],L_={circle:`c`,rect:`r`,"rounded-rect":`rr`,line:`l`,polygon:`p`,polyline:`ll`,arc3:`a`,arc2:`ca`,bezier:`b`,trim:`t`},R_=`btn btn-ghost btn-square btn-sm text-base-content/60`,z_=`btn btn-soft btn-primary btn-square btn-sm`,B_=class{el;inner;snapMenu=null;onToolSelect;activeToolId=null;buttons=new Map;shortcutManager;boundKeyDown;boundCloseSnapMenu;snapVertexCheckedState=!0;snapGridCheckedState=!0;onSnapVerticesChange=null;onSnapGridChange=null;constructor(e,t){this.onToolSelect=t,this.el=document.createElement(`div`),this.el.className=`absolute top-1/2 -translate-y-1/2 left-0 select-none pointer-events-auto flex flex-col items-center gap-1.5`,this.el.style.transition=`transform 0.25s ease, opacity 0.25s ease`,this.el.style.transform=`translateX(-100%)`,this.el.style.opacity=`0`,this.inner=document.createElement(`div`),this.inner.className=`flex flex-col gap-0.5 panel-bg border border-base-content/10 rounded-md p-1`,this.el.appendChild(this.inner),this.buildSnapButton(),this.renderTools(),e.appendChild(this.el),this.boundKeyDown=this.handleKeyDown.bind(this),this.boundCloseSnapMenu=this.handleCloseSnapMenu.bind(this),this.shortcutManager=new P_({timeout:200});for(let[e,t]of Object.entries(L_))this.shortcutManager.register(t,()=>this.handleToolClick(e))}show(){this.el.style.transform=``,this.el.style.opacity=``,window.addEventListener(`keydown`,this.boundKeyDown),this.shortcutManager.enable()}hide(){this.el.style.transform=`translateX(-100%)`,this.el.style.opacity=`0`,this.closeSnapMenu(),window.removeEventListener(`keydown`,this.boundKeyDown),this.shortcutManager.disable(),this.activeToolId&&this.setActiveTool(null)}get isVisible(){return this.el.style.transform===``}setActiveTool(e){this.activeToolId!==e&&(this.activeToolId=e,this.syncButtonStates())}get activeTool(){return this.activeToolId}get snapVerticesChecked(){return this.snapVertexCheckedState}get snapGridChecked(){return this.snapGridCheckedState}buildSnapButton(){let e=document.createElement(`div`);e.className=`relative`;let t=document.createElement(`button`);t.className=R_,t.innerHTML=`<span class="[&>svg]:size-5">${Gh}</span>`,t.addEventListener(`click`,t=>{t.stopPropagation(),this.snapMenu?this.closeSnapMenu():this.openSnapMenu(e)}),e.appendChild(t),this.el.appendChild(e)}openSnapMenu(e){this.closeSnapMenu();let t=document.createElement(`div`);t.className=`absolute left-full top-1/2 -translate-y-1/2 ml-2 z-[200] panel-bg border border-base-content/10 rounded-md shadow-[0_4px_12px_rgba(0,0,0,0.4)] p-2 flex flex-col gap-2 whitespace-nowrap`;let n=document.createElement(`input`);n.type=`checkbox`,n.className=`checkbox checkbox-xs checkbox-primary`,n.checked=this.snapVertexCheckedState,n.addEventListener(`change`,()=>{this.snapVertexCheckedState=n.checked,this.onSnapVerticesChange?.(n.checked)});let r=document.createElement(`label`);r.className=`flex items-center gap-2 cursor-pointer`,r.appendChild(n);let i=document.createElement(`span`);i.className=`text-xs text-base-content/70`,i.textContent=`Snap to vertices`,r.appendChild(i);let a=document.createElement(`input`);a.type=`checkbox`,a.className=`checkbox checkbox-xs checkbox-primary`,a.checked=this.snapGridCheckedState,a.addEventListener(`change`,()=>{this.snapGridCheckedState=a.checked,this.onSnapGridChange?.(a.checked)});let o=document.createElement(`label`);o.className=`flex items-center gap-2 cursor-pointer`,o.appendChild(a);let s=document.createElement(`span`);s.className=`text-xs text-base-content/70`,s.textContent=`Snap to grid`,o.appendChild(s),t.appendChild(r),t.appendChild(o),e.appendChild(t),this.snapMenu=t,setTimeout(()=>document.addEventListener(`click`,this.boundCloseSnapMenu),0)}closeSnapMenu(){this.snapMenu&&(this.snapMenu.remove(),this.snapMenu=null,document.removeEventListener(`click`,this.boundCloseSnapMenu))}handleCloseSnapMenu(e){this.snapMenu&&!this.snapMenu.contains(e.target)&&!this.snapMenu.parentElement?.contains(e.target)&&this.closeSnapMenu()}renderTools(){this.inner.innerHTML=``,this.buttons.clear();for(let e=0;e<I_.length;e++){if(e>0){let e=document.createElement(`div`);e.className=`h-px bg-base-content/[0.08] my-0.5`,this.inner.appendChild(e)}let t=I_[e];F_(t)?this.renderGroup(t):this.inner.appendChild(this.createToolButton(t))}}renderGroup(e){if(e.tools.length===1){this.inner.appendChild(this.createToolButton(e.tools[0]));return}let t=document.createElement(`div`);t.className=`flex flex-col items-center`;for(let n of e.tools)t.appendChild(this.createToolButton(n));this.inner.appendChild(t)}createToolButton(e){let t=document.createElement(`div`);t.className=`relative group`;let n=document.createElement(`button`);n.className=e.id===this.activeToolId?z_:R_,n.innerHTML=`<span class="[&>svg]:size-5">${e.icon}</span>`,n.addEventListener(`click`,()=>this.handleToolClick(e.id));let r=L_[e.id],i=document.createElement(`div`);return i.className=`absolute left-full top-1/2 -translate-y-1/2 ml-2 px-2 py-1 rounded bg-base-300 text-base-content text-xs whitespace-nowrap opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity flex items-center gap-1.5`,i.innerHTML=r?`${e.label} <kbd class="kbd kbd-xs">${r}</kbd>`:e.label,t.appendChild(n),t.appendChild(i),this.buttons.set(e.id,n),t}syncButtonStates(){for(let[e,t]of this.buttons)t.className=e===this.activeToolId?z_:R_}handleToolClick(e){this.activeToolId===e?this.onToolSelect(null):this.onToolSelect(e)}handleKeyDown(e){e.key===`Escape`&&this.activeToolId&&(e.preventDefault(),e.stopPropagation(),this.onToolSelect(null))}},V_=class{ctx;plane;snapController;previewGroup;insertGeometry;canvas;currentPosition=null;constructor(e,t,n,r){this.ctx=e,this.plane=t,this.snapController=n,this.insertGeometry=r,this.canvas=e.renderer.domElement,this.previewGroup=new oi,this.previewGroup.userData.isMetaShape=!0,this.previewGroup.renderOrder=3}updatePlane(e){this.plane=e}updateSnapManager(e){this.snapController.updateSnapManager(e)}updateCurrentPosition(e){e?this.currentPosition=Op(e,this.plane):this.currentPosition=null}isAtCurrentPosition(e){if(!this.currentPosition)return!1;let t=kp(this.ctx,15);return Ap(e,this.currentPosition)<=t}disposePreview(){for(;this.previewGroup.children.length>0;){let e=this.previewGroup.children[0];this.previewGroup.remove(e);let t=e;t.geometry&&t.geometry.dispose(),t.material&&t.material.dispose()}}addPreviewToScene(){this.ctx.scene.add(this.previewGroup)}removePreviewFromScene(){this.ctx.scene.remove(this.previewGroup),this.disposePreview(),this.ctx.requestRender()}requestRender(){this.ctx.requestRender()}formatPoint(e){return`[${e[0]}, ${e[1]}]`}},H_=16,U_=-36,W_=/^[a-zA-Z_$][\w$]*$/,G_=/^([a-zA-Z_$][\w$]*)\s*=\s*(.+?)\s*;?\s*$/,K_=new Set(`const.let.var.if.else.for.while.do.return.function.class.new.this.true.false.null.undefined.typeof.instanceof.switch.case.break.continue.default.try.catch.finally.throw.in.of.delete.void.yield.async.await.import.export.from.as.extends.super.static.enum.interface.implements.package.private.protected.public`.split(`.`));function q_(e){return W_.test(e)&&!K_.has(e)}var J_=class{el;wrapperEl;input;label;dropdown;errorEl;onCommit=null;visible=!1;userIsTyping=!1;variables=[];filteredVars=[];selectedIndex=-1;seedValue=``;errorVisible=!1;numericOnly=!1;onSpaceOverride=null;constructor(e){this.el=document.createElement(`div`),this.el.className=`absolute z-[1000] pointer-events-auto hidden`,this.el.innerHTML=`
5411
5433
  <div class="expression-wrapper flex items-center gap-1.5 panel-bg border border-base-content/10 rounded-md px-2 py-1 shadow-lg">
5412
5434
  <span class="text-xs text-base-content/50 select-none expression-label"></span>
5413
5435
  <input type="text" class="bg-transparent border-none outline-none text-sm text-base-content w-24 font-mono expression-input" />
5414
5436
  </div>
5415
5437
  <div class="mt-1 panel-bg border border-base-content/10 rounded-md shadow-lg max-h-[150px] overflow-y-auto hidden expression-dropdown"></div>
5416
5438
  <div class="mt-1 bg-red-500/90 text-white text-xs rounded-md px-2 py-1 shadow-lg hidden expression-error"></div>
5417
- `,e.appendChild(this.el),this.wrapperEl=this.el.querySelector(`.expression-wrapper`),this.input=this.el.querySelector(`.expression-input`),this.label=this.el.querySelector(`.expression-label`),this.dropdown=this.el.querySelector(`.expression-dropdown`),this.errorEl=this.el.querySelector(`.expression-error`),this.input.addEventListener(`keydown`,e=>{if(e.key!==`Escape`&&e.stopPropagation(),e.key===`ArrowDown`){e.preventDefault(),this.moveSelection(1);return}if(e.key===`ArrowUp`){e.preventDefault(),this.moveSelection(-1);return}if(e.key===`Tab`){e.preventDefault(),this.fillSelected();return}if(e.key===`Enter`){e.preventDefault(),this.selectedIndex>=0&&this.selectedIndex<this.filteredVars.length&&(this.input.value=this.filteredVars[this.selectedIndex].name),this.commit();return}if(e.key===` `&&this.onSpaceOverride){e.preventDefault(),this.onSpaceOverride();return}if(e.key===`Escape`){e.preventDefault(),this.userIsTyping=!1,this.input.blur(),this.hide();return}}),this.input.addEventListener(`input`,()=>{this.userIsTyping=!0,this.errorVisible&&this.clearInlineError(),this.filterAndRender()}),this.input.addEventListener(`focus`,()=>{this.filterAndRender()}),this.input.addEventListener(`mousedown`,e=>e.stopPropagation()),this.input.addEventListener(`mouseup`,e=>e.stopPropagation()),this.input.addEventListener(`click`,e=>e.stopPropagation()),this.dropdown.addEventListener(`mousedown`,e=>e.stopPropagation())}show(e){this.label.textContent=e.label,this.onCommit=e.onCommit,this.variables=e.variables,this.numericOnly=e.numericOnly??!1,this.visible=!0,this.userIsTyping=!1,this.selectedIndex=-1,this.seedValue=e.value,this.el.classList.remove(`hidden`),this.updatePosition(e.clientX,e.clientY),this.input.value=e.value,this.input.focus(),this.input.select(),this.clearInlineError(),this.filterAndRender()}hide(){this.visible&&(this.visible=!1,this.userIsTyping=!1,this.el.classList.add(`hidden`),this.dropdown.classList.add(`hidden`),this.clearInlineError(),this.onCommit=null,this.input.blur())}get isVisible(){return this.visible}containsElement(e){return e instanceof Node&&this.el.contains(e)}updateValue(e){if(!this.visible||this.userIsTyping)return;let t=typeof e==`string`?e:String(Math.round(e*100)/100);this.input.value=t,this.seedValue=t,this.input.select()}updatePosition(e,t){if(!this.visible)return;let n=this.el.parentElement.getBoundingClientRect();this.el.style.left=`${e-n.left+E_}px`,this.el.style.top=`${t-n.top+D_}px`}commitCurrentValue(){let e=this.input.value.trim();return e?this.runCommit(e):!1}commit(){let e=this.input.value.trim();e?this.runCommit(e):this.hide()}runCommit(e){if(!this.onCommit)return!1;let t=this.classifyCommit(e);return t.kind===`error`?(this.showInlineError(t.message),!1):(t.kind===`declare`?this.onCommit({expression:t.name,newVariable:{name:t.name,initializer:t.initializer}}):this.onCommit({expression:t.expression}),this.hide(),!0)}classifyCommit(e){if(this.numericOnly)return isNaN(parseFloat(e))?{kind:`error`,message:`Enter a numeric value`}:{kind:`expression`,expression:e};let t=e.match(k_);if(t){let e=t[1],n=t[2].trim();return j_(e)?this.variables.some(t=>t.name===e)?{kind:`error`,message:`'${e}' is already defined`}:n?{kind:`declare`,name:e,initializer:n}:{kind:`error`,message:`Missing value`}:{kind:`error`,message:`'${e}' is not a valid name`}}if(O_.test(e)){if(this.variables.some(t=>t.name===e)||!j_(e))return{kind:`expression`,expression:e};let t=this.seedValue.trim();return t?{kind:`declare`,name:e,initializer:t}:{kind:`error`,message:`No value to assign`}}return{kind:`expression`,expression:e}}showInlineError(e){this.errorVisible=!0,this.errorEl.textContent=e,this.errorEl.classList.remove(`hidden`),this.wrapperEl.classList.add(`border-red-500/70`),this.wrapperEl.classList.remove(`border-base-content/10`)}clearInlineError(){if(!this.errorVisible){this.errorEl.classList.add(`hidden`);return}this.errorVisible=!1,this.errorEl.classList.add(`hidden`),this.errorEl.textContent=``,this.wrapperEl.classList.remove(`border-red-500/70`),this.wrapperEl.classList.add(`border-base-content/10`)}moveSelection(e){this.filteredVars.length!==0&&(this.selectedIndex+=e,this.selectedIndex<0?this.selectedIndex=this.filteredVars.length-1:this.selectedIndex>=this.filteredVars.length&&(this.selectedIndex=0),this.renderDropdown())}fillSelected(){this.selectedIndex>=0&&this.selectedIndex<this.filteredVars.length&&(this.input.value=this.filteredVars[this.selectedIndex].name,this.userIsTyping=!0,this.filterAndRender())}filterAndRender(){if(this.numericOnly){this.filteredVars=[],this.selectedIndex=-1,this.renderDropdown();return}if(!this.userIsTyping)this.filteredVars=[...this.variables];else{let e=this.input.value.trim().toLowerCase();e?this.filteredVars=this.variables.filter(t=>t.name.toLowerCase().includes(e)):this.filteredVars=[...this.variables]}this.selectedIndex=-1,this.renderDropdown()}renderDropdown(){if(this.filteredVars.length===0){this.dropdown.classList.add(`hidden`);return}if(this.dropdown.classList.remove(`hidden`),this.dropdown.innerHTML=this.filteredVars.map((e,t)=>{let n=t===this.selectedIndex?`bg-primary/10`:``,r=e.initializer?`<span class="text-base-content/40 ml-2">= ${this.escapeHtml(this.truncate(e.initializer,20))}</span>`:``;return`<div class="px-2 py-1 text-sm font-mono cursor-pointer hover:bg-primary/10 ${n}" data-idx="${t}">${this.escapeHtml(e.name)}${r}</div>`}).join(``),this.dropdown.querySelectorAll(`[data-idx]`).forEach(e=>{e.addEventListener(`mousedown`,t=>{t.preventDefault(),t.stopPropagation();let n=parseInt(e.dataset.idx,10);this.input.value=this.filteredVars[n].name,this.commit()})}),this.selectedIndex>=0){let e=this.dropdown.children[this.selectedIndex];e&&e.scrollIntoView({block:`nearest`})}}escapeHtml(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`)}truncate(e,t){return e.length>t?e.slice(0,t)+`...`:e}},Y=2280550,N_=11579568,X=16762232,P_=8947848,F_=2.5,I_=7.5;function L_(e){return e===`vertex`?X:P_}function Z(e,t,n,r,i,a,o=1,s=4,c=F_,l=I_){let u=new H(new ea(c,16),new mr({color:n,side:2,depthTest:!1,transparent:o<1,opacity:o}));u.renderOrder=s;let d=new si;d.renderOrder=s;let f=_p(t,a);d.position.copy(f),d.lookAt(f.clone().add(i)),Yf(u,d,f,l,c),d.add(u),e.add(d)}function R_(e,t,n,r,i=3){let a=_p(t,r),o=_p(n,r),s=new Float32Array(6);s[0]=a.x,s[1]=a.y,s[2]=a.z,s[3]=o.x,s[4]=o.y,s[5]=o.z;let c=new Or;c.setAttribute(`position`,new V(s,3));let l=new Ki(c,new ha({color:N_,dashSize:3,gapSize:2,depthTest:!1}));l.computeLineDistances(),l.renderOrder=i,e.add(l)}function z_(e,t,n,r,i=3){let a=new Float32Array(195);for(let e=0;e<=64;e++){let i=e/64*Math.PI*2,o=_p([t[0]+Math.cos(i)*n,t[1]+Math.sin(i)*n],r);a[e*3]=o.x,a[e*3+1]=o.y,a[e*3+2]=o.z}let o=new Or;o.setAttribute(`position`,new V(a,3));let s=new Ki(o,new ha({color:N_,dashSize:3,gapSize:2,depthTest:!1}));s.computeLineDistances(),s.renderOrder=i,e.add(s)}function B_(e,t,n,r,i=3){let a=t[0],o=t[1],s=n[0],c=n[1],l=[[a,o],[s,o],[s,c],[a,c],[a,o]],u=new Float32Array(l.length*3);for(let e=0;e<l.length;e++){let t=_p(l[e],r);u[e*3]=t.x,u[e*3+1]=t.y,u[e*3+2]=t.z}let d=new Or;d.setAttribute(`position`,new V(u,3));let f=new Ki(d,new ha({color:N_,dashSize:3,gapSize:2,depthTest:!1}));f.computeLineDistances(),f.renderOrder=i,e.add(f)}var V_=8;function H_(e,t,n,r,i,a=3){let o=Math.min(t[0],n[0]),s=Math.max(t[0],n[0]),c=Math.min(t[1],n[1]),l=Math.max(t[1],n[1]),u=s-o,d=l-c,f=Math.min(r,u/2,d/2);if(f<=0){B_(e,t,n,i,a);return}let p=[];p.push([o+f,c]),p.push([s-f,c]);for(let e=0;e<=V_;e++){let t=-Math.PI/2+e/V_*(Math.PI/2);p.push([s-f+f*Math.cos(t),c+f+f*Math.sin(t)])}p.push([s,c+f]),p.push([s,l-f]);for(let e=0;e<=V_;e++){let t=0+e/V_*(Math.PI/2);p.push([s-f+f*Math.cos(t),l-f+f*Math.sin(t)])}p.push([s-f,l]),p.push([o+f,l]);for(let e=0;e<=V_;e++){let t=Math.PI/2+e/V_*(Math.PI/2);p.push([o+f+f*Math.cos(t),l-f+f*Math.sin(t)])}p.push([o,l-f]),p.push([o,c+f]);for(let e=0;e<=V_;e++){let t=Math.PI+e/V_*(Math.PI/2);p.push([o+f+f*Math.cos(t),c+f+f*Math.sin(t)])}p.push([o+f,c]);let m=new Float32Array(p.length*3);for(let e=0;e<p.length;e++){let t=_p(p[e],i);m[e*3]=t.x,m[e*3+1]=t.y,m[e*3+2]=t.z}let h=new Or;h.setAttribute(`position`,new V(m,3));let g=new Ki(h,new ha({color:N_,dashSize:3,gapSize:2,depthTest:!1}));g.computeLineDistances(),g.renderOrder=a,e.add(g)}function U_(e,t,n,r,i,a=3){let o=new Float32Array((r+1)*3);for(let e=0;e<=r;e++){let a=e/r*Math.PI*2,s=_p([t[0]+Math.cos(a)*n,t[1]+Math.sin(a)*n],i);o[e*3]=s.x,o[e*3+1]=s.y,o[e*3+2]=s.z}let s=new Or;s.setAttribute(`position`,new V(o,3));let c=new Ki(s,new ha({color:N_,dashSize:3,gapSize:2,depthTest:!1}));c.computeLineDistances(),c.renderOrder=a,e.add(c)}function W_(e,t,n,r,i,a,o,s=3){let c=i-r;a?c<=0&&(c+=Math.PI*2):c>=0&&(c-=Math.PI*2);let l=Math.max(Math.round(Math.abs(c)/(Math.PI*2)*64),2),u=new Float32Array((l+1)*3);for(let e=0;e<=l;e++){let i=e/l,a=r+c*i,s=_p([t[0]+Math.cos(a)*n,t[1]+Math.sin(a)*n],o);u[e*3]=s.x,u[e*3+1]=s.y,u[e*3+2]=s.z}let d=new Or;d.setAttribute(`position`,new V(u,3));let f=new Ki(d,new ha({color:N_,dashSize:3,gapSize:2,depthTest:!1}));f.computeLineDistances(),f.renderOrder=s,e.add(f)}function G_(e,t){let n=e.slice();for(;n.length>1;){let e=[];for(let r=0;r<n.length-1;r++)e.push([(1-t)*n[r][0]+t*n[r+1][0],(1-t)*n[r][1]+t*n[r+1][1]]);n=e}return n[0]}function K_(e,t,n,r=3){if(t.length<2)return;let i=new Float32Array(195);for(let e=0;e<=64;e++){let r=_p(G_(t,e/64),n);i[e*3]=r.x,i[e*3+1]=r.y,i[e*3+2]=r.z}let a=new Or;a.setAttribute(`position`,new V(i,3));let o=new Ki(a,new ha({color:N_,dashSize:3,gapSize:2,depthTest:!1}));o.computeLineDistances(),o.renderOrder=r,e.add(o)}var q_=16;function J_(e,t,n,r,i,a=3){let o=n[0]-t[0],s=n[1]-t[1],c=Math.sqrt(o*o+s*s),l,u;c>1e-10?(l=o/c,u=s/c):(l=1,u=0);let d=-u,f=l,p=[],m=Math.atan2(f,d);for(let e=0;e<=q_;e++){let n=m+e/q_*Math.PI;p.push([t[0]+r*Math.cos(n),t[1]+r*Math.sin(n)])}p.push([n[0]-r*d,n[1]-r*f]);let h=Math.atan2(-f,-d);for(let e=0;e<=q_;e++){let t=h+e/q_*Math.PI;p.push([n[0]+r*Math.cos(t),n[1]+r*Math.sin(t)])}p.push([t[0]+r*d,t[1]+r*f]);let g=new Float32Array(p.length*3);for(let e=0;e<p.length;e++){let t=_p(p[e],i);g[e*3]=t.x,g[e*3+1]=t.y,g[e*3+2]=t.z}let _=new Or;_.setAttribute(`position`,new V(g,3));let v=new Ki(_,new ha({color:N_,dashSize:3,gapSize:2,depthTest:!1}));v.computeLineDistances(),v.renderOrder=a,e.add(v)}function Y_(e,t){return Math.atan2(t[1]-e[1],t[0]-e[0])}function X_(e,t,n){return[e[0]+t*Math.cos(n),e[1]+t*Math.sin(n)]}function Z_(e,t,n){let r=2*(e[0]*(t[1]-n[1])+t[0]*(n[1]-e[1])+n[0]*(e[1]-t[1]));if(Math.abs(r)<1e-10)return null;let i=e[0]*e[0]+e[1]*e[1],a=t[0]*t[0]+t[1]*t[1],o=n[0]*n[0]+n[1]*n[1];return[(i*(t[1]-n[1])+a*(n[1]-e[1])+o*(e[1]-t[1]))/r,(i*(n[0]-t[0])+a*(e[0]-n[0])+o*(t[0]-e[0]))/r]}function Q_(e,t,n){let r=Y_(e,t),i=Y_(e,n)-r;return i<0&&(i+=Math.PI*2),i<Math.PI}function $_(e,t,n,r){let i=(e[0]+t[0])/2,a=(e[1]+t[1])/2,o=t[0]-e[0],s=t[1]-e[1],c=Math.sqrt(o*o+s*s)/2;if(Math.abs(n)<c-1e-10)return null;let l=Math.sqrt(Math.max(n*n-c*c,0)),u=-s,d=o,f=Math.sqrt(u*u+d*d);if(f<1e-10)return null;let p=r?1:-1;return[i+p*l*u/f,a+p*l*d/f]}var ev=new Set([`line-two-points`,`hline`,`vline`,`arc`,`tarc-to-point`,`tarc-to-point-tangent`,`tarc-with-tangent`,`tline`]);function tv(e,t){let n=t.origin.x,r=t.origin.y,i=t.origin.z,a=t.xDirection.x,o=t.xDirection.y,s=t.xDirection.z,c=t.yDirection.x,l=t.yDirection.y,u=t.yDirection.z,d=[];for(let t=0;t<e.length;t+=3){let f=e[t]-n,p=e[t+1]-r,m=e[t+2]-i;d.push([f*a+p*o+m*s,f*c+p*l+m*u])}return d}function nv(e,t){let n,r;if(t===`end`){let t=e[e.length-2],i=e[e.length-1];n=i[0]-t[0],r=i[1]-t[1]}else{let t=e[0],i=e[1];n=t[0]-i[0],r=t[1]-i[1]}let i=Math.sqrt(n*n+r*r);return i<1e-10?null:[n/i,r/i]}var rv=class extends T_{id=`line`;label=`Line`;icon=Nh;startPoint=null;mousePoint=null;lastSnapType=`none`;shiftHeld=!1;ctrlHeld=!1;expressionInput;fetchVariables;cachedVariables=[];lastClientX=0;lastClientY=0;sceneObjects=[];sketchId=``;boundMouseDown;boundMouseUp;boundMouseMove;boundKeyDown;boundKeyUp;downX=0;downY=0;constructor(e,t,n,r,i,a){super(e,t,n,r),this.expressionInput=new M_(i),this.fetchVariables=a,this.boundMouseDown=this.handleMouseDown.bind(this),this.boundMouseUp=this.handleMouseUp.bind(this),this.boundMouseMove=this.handleMouseMove.bind(this),this.boundKeyDown=this.handleKeyDown.bind(this),this.boundKeyUp=this.handleKeyUp.bind(this)}activate(){this.addPreviewToScene(),this.canvas.addEventListener(`mousedown`,this.boundMouseDown),this.canvas.addEventListener(`mouseup`,this.boundMouseUp),this.canvas.addEventListener(`mousemove`,this.boundMouseMove),window.addEventListener(`keydown`,this.boundKeyDown),window.addEventListener(`keyup`,this.boundKeyUp),this.fetchVariables().then(e=>{this.cachedVariables=e})}deactivate(){this.canvas.removeEventListener(`mousedown`,this.boundMouseDown),this.canvas.removeEventListener(`mouseup`,this.boundMouseUp),this.canvas.removeEventListener(`mousemove`,this.boundMouseMove),window.removeEventListener(`keydown`,this.boundKeyDown),window.removeEventListener(`keyup`,this.boundKeyUp),this.startPoint=null,this.mousePoint=null,this.shiftHeld=!1,this.ctrlHeld=!1,this.expressionInput.hide(),this.removePreviewFromScene()}onSceneUpdate(e,t){this.sceneObjects=e,this.sketchId=t;let n=n_.fromSceneObjects(e,t,this.plane,this.ctx);this.updateSnapManager(n),this.fetchVariables().then(e=>{this.cachedVariables=e})}handleMouseDown(e){this.downX=e.clientX,this.downY=e.clientY,this.syncModifiers(e)}handleMouseUp(e){this.syncModifiers(e);let t=e.clientX-this.downX,n=e.clientY-this.downY;if(t*t+n*n>64)return;let r=gp(this.ctx,this.plane,e.clientX,e.clientY);if(!r)return;let i=J(this.snapController.snap(r).point2d);if(!this.startPoint){this.startPoint=i,this.rebuildPreview();return}this.isTLineMode()&&this.expressionInput.isVisible?this.expressionInput.commitCurrentValue():this.isTLineMode()?this.commitTLineDirect():this.shiftHeld&&this.expressionInput.isVisible?this.expressionInput.commitCurrentValue():this.commitLine(this.startPoint,i),this.expressionInput.hide(),this.startPoint=null,this.rebuildPreview()}handleMouseMove(e){this.lastClientX=e.clientX,this.lastClientY=e.clientY,this.syncModifiers(e);let t=gp(this.ctx,this.plane,e.clientX,e.clientY);if(!t){this.mousePoint=null,this.lastSnapType=`none`,this.rebuildPreview();return}let n=this.snapController.snap(t);this.mousePoint=n.point2d,this.lastSnapType=n.snapType,this.rebuildPreview(),this.updateDimensionInput()}syncModifiers(e){let t=this.isTLineMode();this.shiftHeld=e.shiftKey,this.ctrlHeld=e.ctrlKey||e.metaKey,this.isTLineMode()!==t&&this.expressionInput.hide()}handleKeyDown(e){this.syncModifiers(e),(e.key===`Shift`||e.key===`Control`||e.key===`Meta`)&&(this.rebuildPreview(),this.updateDimensionInput()),e.key===`Escape`&&this.startPoint&&(this.startPoint=null,this.expressionInput.hide(),this.rebuildPreview())}handleKeyUp(e){this.syncModifiers(e),(e.key===`Shift`||e.key===`Control`||e.key===`Meta`)&&(this.shiftHeld||this.expressionInput.hide(),this.rebuildPreview(),this.updateDimensionInput())}isTLineMode(){return this.shiftHeld&&this.ctrlHeld}findTangentAtStart(){if(!this.startPoint||!this.isAtCurrentPosition(J(this.startPoint)))return null;let e=null;for(let t of this.sceneObjects)t.parentId!==this.sketchId||!t.sourceLocation||ev.has(t.uniqueType??``)&&(e=t);if(!e)return null;for(let t of e.sceneShapes)if(!t.isMetaShape)for(let e of t.meshes){let t=tv(e.vertices,this.plane);if(!(t.length<2))return nv(t,`end`)}return null}getEffectiveEndPoint(){if(!this.startPoint||!this.mousePoint)return null;if(this.isTLineMode()){let e=this.findTangentAtStart();if(e){let t=this.mousePoint[0]-this.startPoint[0],n=this.mousePoint[1]-this.startPoint[1],r=t*e[0]+n*e[1];return[this.startPoint[0]+e[0]*r,this.startPoint[1]+e[1]*r]}return this.mousePoint}if(this.shiftHeld){let e=this.mousePoint[0]-this.startPoint[0],t=this.mousePoint[1]-this.startPoint[1];return Math.abs(e)>=Math.abs(t)?[this.mousePoint[0],this.startPoint[1]]:[this.startPoint[0],this.mousePoint[1]]}return this.mousePoint}updateDimensionInput(){if(!this.startPoint||!this.mousePoint||!this.shiftHeld){this.expressionInput.hide();return}if(this.isTLineMode()){this.updateTLineDimensionInput();return}let e=this.mousePoint[0]-this.startPoint[0],t=this.mousePoint[1]-this.startPoint[1],n=Math.abs(e)>=Math.abs(t),r=Math.abs(n?e:t);this.expressionInput.isVisible?(this.expressionInput.updateValue(r),this.expressionInput.updatePosition(this.lastClientX,this.lastClientY)):this.expressionInput.show({label:n?`H:`:`V:`,value:String(Math.round(r*100)/100),clientX:this.lastClientX,clientY:this.lastClientY,variables:this.cachedVariables,onCommit:e=>this.commitWithDimension(e)})}updateTLineDimensionInput(){let e=this.findTangentAtStart();if(!e){this.expressionInput.hide();return}let t=this.mousePoint[0]-this.startPoint[0],n=this.mousePoint[1]-this.startPoint[1],r=t*e[0]+n*e[1];this.expressionInput.isVisible?(this.expressionInput.updateValue(Math.abs(r)),this.expressionInput.updatePosition(this.lastClientX,this.lastClientY)):this.expressionInput.show({label:`T:`,value:String(Math.round(Math.abs(r)*100)/100),clientX:this.lastClientX,clientY:this.lastClientY,variables:this.cachedVariables,onCommit:e=>this.commitTLine(e,r)})}commitWithDimension(e){if(!this.startPoint||!this.mousePoint)return;let{expression:t,newVariable:n}=e,r=J(this.startPoint),i=this.isAtCurrentPosition(r),a=this.mousePoint[0]-this.startPoint[0],o=this.mousePoint[1]-this.startPoint[1],s=Math.abs(a)>=Math.abs(o),c=Math.sign(s?a:o),l=parseFloat(t),u=!isNaN(l)&&String(l)===t?String(Math.round(c*l*100)/100):t,d=s?`hLine`:`vLine`,f=i?`${d}(${u})`:`${d}(${this.formatPoint(r)}, ${u})`;this.insertGeometry(f,n),this.expressionInput.hide(),this.startPoint=null,this.rebuildPreview()}commitTLine(e,t){if(!this.startPoint)return;let{expression:n,newVariable:r}=e,i=Math.sign(t),a=parseFloat(n),o=!isNaN(a)&&String(a)===n?String(Math.round(i*a*100)/100):n;this.insertGeometry(`tLine(${o})`,r),this.expressionInput.hide(),this.startPoint=null,this.rebuildPreview()}commitTLineDirect(){if(!this.startPoint||!this.mousePoint)return;let e=this.findTangentAtStart();if(!e)return;let t=this.mousePoint[0]-this.startPoint[0],n=this.mousePoint[1]-this.startPoint[1],r=Math.round((t*e[0]+n*e[1])*100)/100;this.insertGeometry(`tLine(${r})`),this.expressionInput.hide(),this.startPoint=null,this.rebuildPreview()}commitLine(e,t){let n=J(e),r=J(t),i=this.isAtCurrentPosition(n);if(this.shiftHeld){let e=r[0]-n[0],t=r[1]-n[1],a=Math.abs(e)>=Math.abs(t),o=a?J([e,0])[0]:J([0,t])[1];a?i?this.insertGeometry(`hLine(${o})`):this.insertGeometry(`hLine(${this.formatPoint(n)}, ${o})`):i?this.insertGeometry(`vLine(${o})`):this.insertGeometry(`vLine(${this.formatPoint(n)}, ${o})`);return}i?this.insertGeometry(`line(${this.formatPoint(r)})`):this.insertGeometry(`line(${this.formatPoint(n)}, ${this.formatPoint(r)})`)}rebuildPreview(){this.disposePreview();let e=this.ctx.camera,t=new R(this.plane.normal.x,this.plane.normal.y,this.plane.normal.z);if(this.startPoint){Z(this.previewGroup,this.startPoint,Y,e,t,this.plane);let n=this.getEffectiveEndPoint();if(n&&(R_(this.previewGroup,this.startPoint,n,this.plane),this.lastSnapType!==`none`)){let r=this.lastSnapType===`vertex`?X:P_;Z(this.previewGroup,n,r,e,t,this.plane,.6)}}else if(this.mousePoint&&this.lastSnapType!==`none`){let n=this.lastSnapType===`vertex`?X:P_;Z(this.previewGroup,this.mousePoint,n,e,t,this.plane,.6)}this.requestRender()}},iv=class extends T_{id=`circle`;label=`Circle`;icon=Ph;centerPoint=null;mousePoint=null;lastSnapType=`none`;expressionInput;fetchVariables;cachedVariables=[];lastClientX=0;lastClientY=0;boundMouseDown;boundMouseUp;boundMouseMove;boundKeyDown;downX=0;downY=0;constructor(e,t,n,r,i,a){super(e,t,n,r),this.expressionInput=new M_(i),this.fetchVariables=a,this.boundMouseDown=this.handleMouseDown.bind(this),this.boundMouseUp=this.handleMouseUp.bind(this),this.boundMouseMove=this.handleMouseMove.bind(this),this.boundKeyDown=this.handleKeyDown.bind(this)}activate(){this.addPreviewToScene(),this.canvas.addEventListener(`mousedown`,this.boundMouseDown),this.canvas.addEventListener(`mouseup`,this.boundMouseUp),this.canvas.addEventListener(`mousemove`,this.boundMouseMove),window.addEventListener(`keydown`,this.boundKeyDown),this.fetchVariables().then(e=>{this.cachedVariables=e})}deactivate(){this.canvas.removeEventListener(`mousedown`,this.boundMouseDown),this.canvas.removeEventListener(`mouseup`,this.boundMouseUp),this.canvas.removeEventListener(`mousemove`,this.boundMouseMove),window.removeEventListener(`keydown`,this.boundKeyDown),this.centerPoint=null,this.mousePoint=null,this.expressionInput.hide(),this.removePreviewFromScene()}onSceneUpdate(e,t){let n=n_.fromSceneObjects(e,t,this.plane,this.ctx);this.updateSnapManager(n),this.fetchVariables().then(e=>{this.cachedVariables=e})}handleMouseDown(e){this.downX=e.clientX,this.downY=e.clientY}handleMouseUp(e){let t=e.clientX-this.downX,n=e.clientY-this.downY;if(t*t+n*n>64)return;let r=gp(this.ctx,this.plane,e.clientX,e.clientY);if(!r)return;let i=J(this.snapController.snap(r).point2d);if(!this.centerPoint){this.centerPoint=i,this.rebuildPreview();return}if(this.expressionInput.isVisible)this.expressionInput.commitCurrentValue();else{let e=Math.round(bp(this.centerPoint,i)*2*100)/100;if(e<=0)return;this.commitCircle(this.centerPoint,{expression:String(e)})}this.expressionInput.hide(),this.centerPoint=null,this.rebuildPreview()}handleMouseMove(e){this.lastClientX=e.clientX,this.lastClientY=e.clientY;let t=gp(this.ctx,this.plane,e.clientX,e.clientY);if(!t){this.mousePoint=null,this.lastSnapType=`none`,this.rebuildPreview();return}let n=this.snapController.snap(t);this.mousePoint=n.point2d,this.lastSnapType=n.snapType,this.rebuildPreview(),this.updateDimensionInput()}handleKeyDown(e){e.key===`Escape`&&this.centerPoint&&(this.centerPoint=null,this.expressionInput.hide(),this.rebuildPreview())}updateDimensionInput(){if(!this.centerPoint||!this.mousePoint)return;let e=Math.round(bp(this.centerPoint,this.mousePoint)*2*100)/100;e<=0||(this.expressionInput.isVisible?(this.expressionInput.updateValue(e),this.expressionInput.updatePosition(this.lastClientX,this.lastClientY)):this.expressionInput.show({label:`⌀`,value:String(e),clientX:this.lastClientX,clientY:this.lastClientY,variables:this.cachedVariables,onCommit:e=>{this.centerPoint&&(this.commitCircle(this.centerPoint,e),this.expressionInput.hide(),this.centerPoint=null,this.rebuildPreview())}}))}commitCircle(e,t){let{expression:n,newVariable:r}=t,i=this.isAtCurrentPosition(e)?`circle(${n})`:`circle(${this.formatPoint(e)}, ${n})`;this.insertGeometry(i,r)}rebuildPreview(){this.disposePreview();let e=this.ctx.camera,t=new R(this.plane.normal.x,this.plane.normal.y,this.plane.normal.z);if(this.centerPoint){if(Z(this.previewGroup,this.centerPoint,Y,e,t,this.plane),this.mousePoint){let e=bp(this.centerPoint,this.mousePoint);e>0&&z_(this.previewGroup,this.centerPoint,e,this.plane)}}else if(this.mousePoint&&this.lastSnapType!==`none`){let n=this.lastSnapType===`vertex`?X:P_;Z(this.previewGroup,this.mousePoint,n,e,t,this.plane,.6)}this.requestRender()}},av=function(e){return e[e.IDLE=0]=`IDLE`,e[e.CENTER_PLACED=1]=`CENTER_PLACED`,e[e.START_PLACED=2]=`START_PLACED`,e}(av||{}),ov=class extends T_{id=`arc2`;label=`Center Arc`;icon=Fh;state=av.IDLE;centerPoint=null;startPoint=null;mousePoint=null;lastSnapType=`none`;expressionInput;fetchVariables;cachedVariables=[];lastClientX=0;lastClientY=0;lastCCW=!0;boundMouseDown;boundMouseUp;boundMouseMove;boundKeyDown;downX=0;downY=0;constructor(e,t,n,r,i,a){super(e,t,n,r),this.expressionInput=new M_(i),this.fetchVariables=a,this.boundMouseDown=this.handleMouseDown.bind(this),this.boundMouseUp=this.handleMouseUp.bind(this),this.boundMouseMove=this.handleMouseMove.bind(this),this.boundKeyDown=this.handleKeyDown.bind(this)}activate(){this.addPreviewToScene(),this.canvas.addEventListener(`mousedown`,this.boundMouseDown),this.canvas.addEventListener(`mouseup`,this.boundMouseUp),this.canvas.addEventListener(`mousemove`,this.boundMouseMove),window.addEventListener(`keydown`,this.boundKeyDown),this.fetchVariables().then(e=>{this.cachedVariables=e})}deactivate(){this.canvas.removeEventListener(`mousedown`,this.boundMouseDown),this.canvas.removeEventListener(`mouseup`,this.boundMouseUp),this.canvas.removeEventListener(`mousemove`,this.boundMouseMove),window.removeEventListener(`keydown`,this.boundKeyDown),this.resetState(),this.expressionInput.hide(),this.removePreviewFromScene()}onSceneUpdate(e,t){let n=n_.fromSceneObjects(e,t,this.plane,this.ctx);this.updateSnapManager(n),this.fetchVariables().then(e=>{this.cachedVariables=e})}resetState(){this.state=av.IDLE,this.centerPoint=null,this.startPoint=null,this.mousePoint=null}handleMouseDown(e){this.downX=e.clientX,this.downY=e.clientY}handleMouseUp(e){let t=e.clientX-this.downX,n=e.clientY-this.downY;if(t*t+n*n>64)return;let r=gp(this.ctx,this.plane,e.clientX,e.clientY);if(!r)return;let i=J(this.snapController.snap(r).point2d);if(this.state===av.IDLE){this.centerPoint=i,this.state=av.CENTER_PLACED,this.rebuildPreview();return}if(this.state===av.CENTER_PLACED){if(bp(this.centerPoint,i)<=0)return;this.startPoint=i,this.state=av.START_PLACED,this.rebuildPreview();return}this.state===av.START_PLACED&&(this.expressionInput.isVisible?this.expressionInput.commitCurrentValue():this.commitFromMouse())}handleMouseMove(e){this.lastClientX=e.clientX,this.lastClientY=e.clientY;let t=gp(this.ctx,this.plane,e.clientX,e.clientY);if(!t){this.mousePoint=null,this.lastSnapType=`none`,this.rebuildPreview();return}let n=this.snapController.snap(t);this.mousePoint=n.point2d,this.lastSnapType=n.snapType,this.rebuildPreview(),this.state===av.START_PLACED&&this.updateDimensionInput()}handleKeyDown(e){e.key===`Escape`&&(this.state===av.START_PLACED?(this.startPoint=null,this.state=av.CENTER_PLACED,this.expressionInput.hide()):this.state===av.CENTER_PLACED&&(this.centerPoint=null,this.state=av.IDLE),this.rebuildPreview())}getSweepDeg(){if(!this.centerPoint||!this.startPoint||!this.mousePoint)return null;let e=Y_(this.centerPoint,this.startPoint),t=Y_(this.centerPoint,this.mousePoint);this.lastCCW=Q_(this.centerPoint,this.startPoint,this.mousePoint);let n;return this.lastCCW?(n=t-e,n<=0&&(n+=Math.PI*2)):(n=e-t,n<=0&&(n+=Math.PI*2)),n===0?null:Math.round(180/Math.PI*n*100)/100}updateDimensionInput(){let e=this.getSweepDeg();e===null||e<=0||(this.expressionInput.isVisible?(this.expressionInput.updateValue(e),this.expressionInput.updatePosition(this.lastClientX,this.lastClientY)):this.expressionInput.show({label:`∠`,value:String(e),clientX:this.lastClientX,clientY:this.lastClientY,variables:this.cachedVariables,numericOnly:!0,onCommit:e=>this.commitFromExpression(e)}))}commitFromMouse(){if(!this.centerPoint||!this.startPoint||!this.mousePoint)return;let e=Q_(this.centerPoint,this.startPoint,this.mousePoint),t=bp(this.centerPoint,this.startPoint),n=Y_(this.centerPoint,this.mousePoint),r=X_(this.centerPoint,t,n);this.emitArc(this.startPoint,r,this.centerPoint,e)}commitFromExpression(e){if(!this.centerPoint||!this.startPoint)return;let{expression:t,newVariable:n}=e,r=parseFloat(t);if(isNaN(r)||r<=0)return;let i=Math.PI/180*r,a=bp(this.centerPoint,this.startPoint),o=Y_(this.centerPoint,this.startPoint)+(this.lastCCW?1:-1)*i,s=X_(this.centerPoint,a,o);this.emitArc(this.startPoint,s,this.centerPoint,this.lastCCW,n)}emitArc(e,t,n,r,i){let a=J(e),o=J(t),s=J(n),c=r?``:`.cw()`,l=this.isAtCurrentPosition(a)?`arc(${this.formatPoint(o)}).center(${this.formatPoint(s)})${c}`:`arc(${this.formatPoint(a)}, ${this.formatPoint(o)}).center(${this.formatPoint(s)})${c}`;this.insertGeometry(l,i),this.expressionInput.hide(),this.resetState(),this.rebuildPreview()}rebuildPreview(){this.disposePreview();let e=this.ctx.camera,t=new R(this.plane.normal.x,this.plane.normal.y,this.plane.normal.z);if(this.state===av.IDLE){if(this.mousePoint&&this.lastSnapType!==`none`){let n=this.lastSnapType===`vertex`?X:P_;Z(this.previewGroup,this.mousePoint,n,e,t,this.plane,.6)}}else if(this.state===av.CENTER_PLACED){if(Z(this.previewGroup,this.centerPoint,Y,e,t,this.plane),this.mousePoint&&this.lastSnapType!==`none`){let n=this.lastSnapType===`vertex`?X:P_;Z(this.previewGroup,this.mousePoint,n,e,t,this.plane,.6)}}else if(this.state===av.START_PLACED&&this.centerPoint&&this.startPoint&&(Z(this.previewGroup,this.centerPoint,Y,e,t,this.plane),Z(this.previewGroup,this.startPoint,Y,e,t,this.plane),R_(this.previewGroup,this.centerPoint,this.startPoint,this.plane),this.mousePoint)){let n=bp(this.centerPoint,this.startPoint),r=Y_(this.centerPoint,this.startPoint),i=Y_(this.centerPoint,this.mousePoint),a=X_(this.centerPoint,n,i);R_(this.previewGroup,this.centerPoint,a,this.plane);let o=Q_(this.centerPoint,this.startPoint,this.mousePoint);if(W_(this.previewGroup,this.centerPoint,n,r,i,o,this.plane),this.lastSnapType!==`none`){let n=this.lastSnapType===`vertex`?X:P_;Z(this.previewGroup,this.mousePoint,n,e,t,this.plane,.6)}}this.requestRender()}},sv=function(e){return e[e.IDLE=0]=`IDLE`,e[e.START_PLACED=1]=`START_PLACED`,e[e.END_PLACED=2]=`END_PLACED`,e}(sv||{}),cv=class extends T_{id=`arc3`;label=`3-Point Arc`;icon=Ih;state=sv.IDLE;startPoint=null;endPoint=null;mousePoint=null;lastSnapType=`none`;expressionInput;fetchVariables;cachedVariables=[];lastClientX=0;lastClientY=0;lastCCW=!0;lastCenterOnLeft=!0;shiftHeld=!1;boundMouseDown;boundMouseUp;boundMouseMove;boundKeyDown;boundKeyUp;downX=0;downY=0;constructor(e,t,n,r,i,a){super(e,t,n,r),this.expressionInput=new M_(i),this.fetchVariables=a,this.boundMouseDown=this.handleMouseDown.bind(this),this.boundMouseUp=this.handleMouseUp.bind(this),this.boundMouseMove=this.handleMouseMove.bind(this),this.boundKeyDown=this.handleKeyDown.bind(this),this.boundKeyUp=this.handleKeyUp.bind(this)}activate(){this.addPreviewToScene(),this.canvas.addEventListener(`mousedown`,this.boundMouseDown),this.canvas.addEventListener(`mouseup`,this.boundMouseUp),this.canvas.addEventListener(`mousemove`,this.boundMouseMove),window.addEventListener(`keydown`,this.boundKeyDown),window.addEventListener(`keyup`,this.boundKeyUp),this.fetchVariables().then(e=>{this.cachedVariables=e})}deactivate(){this.canvas.removeEventListener(`mousedown`,this.boundMouseDown),this.canvas.removeEventListener(`mouseup`,this.boundMouseUp),this.canvas.removeEventListener(`mousemove`,this.boundMouseMove),window.removeEventListener(`keydown`,this.boundKeyDown),window.removeEventListener(`keyup`,this.boundKeyUp),this.resetState(),this.expressionInput.hide(),this.removePreviewFromScene()}onSceneUpdate(e,t){let n=n_.fromSceneObjects(e,t,this.plane,this.ctx);this.updateSnapManager(n),this.fetchVariables().then(e=>{this.cachedVariables=e})}resetState(){this.state=sv.IDLE,this.startPoint=null,this.endPoint=null,this.mousePoint=null}handleMouseDown(e){this.downX=e.clientX,this.downY=e.clientY}handleMouseUp(e){this.shiftHeld=e.shiftKey;let t=e.clientX-this.downX,n=e.clientY-this.downY;if(t*t+n*n>64)return;let r=gp(this.ctx,this.plane,e.clientX,e.clientY);if(!r)return;let i=J(this.snapController.snap(r).point2d);if(this.state===sv.IDLE){this.startPoint=i,this.state=sv.START_PLACED,this.rebuildPreview();return}if(this.state===sv.START_PLACED){if(bp(this.startPoint,i)<=0)return;this.endPoint=i,this.state=sv.END_PLACED,this.rebuildPreview();return}this.state===sv.END_PLACED&&(this.expressionInput.isVisible?this.expressionInput.commitCurrentValue():this.commitFromMouse())}handleMouseMove(e){this.shiftHeld=e.shiftKey,this.lastClientX=e.clientX,this.lastClientY=e.clientY;let t=gp(this.ctx,this.plane,e.clientX,e.clientY);if(!t){this.mousePoint=null,this.lastSnapType=`none`,this.rebuildPreview();return}let n=this.snapController.snap(t);this.mousePoint=n.point2d,this.lastSnapType=n.snapType,this.rebuildPreview(),this.state===sv.END_PLACED&&this.updateDimensionInput()}handleKeyDown(e){e.key===`Escape`&&(this.state===sv.END_PLACED?(this.endPoint=null,this.state=sv.START_PLACED,this.expressionInput.hide()):this.state===sv.START_PLACED&&(this.startPoint=null,this.state=sv.IDLE),this.rebuildPreview()),e.key===`Shift`&&!this.shiftHeld&&(this.shiftHeld=!0,this.rebuildPreview(),this.state===sv.END_PLACED&&this.updateDimensionInput())}handleKeyUp(e){e.key===`Shift`&&this.shiftHeld&&(this.shiftHeld=!1,this.rebuildPreview(),this.state===sv.END_PLACED&&this.updateDimensionInput())}snapCenterToCollinear(e){if(!this.startPoint||!this.endPoint)return null;let t=this.endPoint[0]-this.startPoint[0],n=this.endPoint[1]-this.startPoint[1],r=t*t+n*n;if(r<1e-10)return null;let i=e[0]-this.startPoint[0],a=e[1]-this.startPoint[1],o=Math.abs(i*n-a*t)/Math.sqrt(r),s=_p([(this.startPoint[0]+this.endPoint[0])/2,(this.startPoint[1]+this.endPoint[1])/2],this.plane);return o>=qf(this.ctx.renderer,this.ctx.camera,s,10)?null:[(this.startPoint[0]+this.endPoint[0])/2,(this.startPoint[1]+this.endPoint[1])/2]}computeCenter(){if(!this.startPoint||!this.endPoint||!this.mousePoint)return null;let e=Z_(this.startPoint,this.endPoint,this.mousePoint);return e?this.shiftHeld?e:this.snapCenterToCollinear(e)??e:null}isMouseCCW(){if(!this.startPoint||!this.endPoint||!this.mousePoint)return!0;let e=this.computeCenter();if(!e)return!0;let t=Y_(e,this.startPoint),n=Y_(e,this.endPoint),r=Y_(e,this.mousePoint)-t;r<0&&(r+=Math.PI*2);let i=n-t;return i<0&&(i+=Math.PI*2),r<i}updateDimensionInput(){let e=this.computeCenter();if(!e||!this.startPoint)return;let t=Math.round(bp(e,this.startPoint)*100)/100;if(t<=0)return;this.lastCCW=this.isMouseCCW();let n=this.endPoint[0]-this.startPoint[0],r=this.endPoint[1]-this.startPoint[1],i=e[0]-this.startPoint[0];this.lastCenterOnLeft=n*(e[1]-this.startPoint[1])-r*i>0,this.expressionInput.isVisible?(this.expressionInput.updateValue(t),this.expressionInput.updatePosition(this.lastClientX,this.lastClientY)):this.expressionInput.show({label:`R`,value:String(t),clientX:this.lastClientX,clientY:this.lastClientY,variables:this.cachedVariables,numericOnly:!0,onCommit:e=>this.commitFromExpression(e)})}commitFromMouse(){if(!this.startPoint||!this.endPoint)return;let e=this.computeCenter();e&&this.emitArc(this.startPoint,this.endPoint,e,this.isMouseCCW())}commitFromExpression(e){if(!this.startPoint||!this.endPoint)return;let{expression:t,newVariable:n}=e,r=parseFloat(t);if(isNaN(r)||r<=0)return;let i=$_(this.startPoint,this.endPoint,r,this.lastCenterOnLeft);i&&this.emitArc(this.startPoint,this.endPoint,i,this.lastCCW,n)}emitArc(e,t,n,r,i){let a=J(e),o=J(t),s=J(n),c=r?``:`.cw()`,l=this.isAtCurrentPosition(a)?`arc(${this.formatPoint(o)}).center(${this.formatPoint(s)})${c}`:`arc(${this.formatPoint(a)}, ${this.formatPoint(o)}).center(${this.formatPoint(s)})${c}`;this.insertGeometry(l,i),this.expressionInput.hide(),this.resetState(),this.rebuildPreview()}rebuildPreview(){this.disposePreview();let e=this.ctx.camera,t=new R(this.plane.normal.x,this.plane.normal.y,this.plane.normal.z);if(this.state===sv.IDLE){if(this.mousePoint&&this.lastSnapType!==`none`){let n=this.lastSnapType===`vertex`?X:P_;Z(this.previewGroup,this.mousePoint,n,e,t,this.plane,.6)}}else if(this.state===sv.START_PLACED){if(Z(this.previewGroup,this.startPoint,Y,e,t,this.plane),this.mousePoint&&this.lastSnapType!==`none`){let n=this.lastSnapType===`vertex`?X:P_;Z(this.previewGroup,this.mousePoint,n,e,t,this.plane,.6)}}else if(this.state===sv.END_PLACED&&this.startPoint&&this.endPoint&&(Z(this.previewGroup,this.startPoint,Y,e,t,this.plane),Z(this.previewGroup,this.endPoint,Y,e,t,this.plane),R_(this.previewGroup,this.startPoint,this.endPoint,this.plane),this.mousePoint)){let n=this.computeCenter();if(n){let r=bp(n,this.startPoint),i=Y_(n,this.startPoint),a=Y_(n,this.endPoint),o=this.isMouseCCW();W_(this.previewGroup,n,r,i,a,o,this.plane),Z(this.previewGroup,n,N_,e,t,this.plane,.7),R_(this.previewGroup,n,this.startPoint,this.plane),R_(this.previewGroup,n,this.endPoint,this.plane)}if(this.lastSnapType!==`none`){let n=this.lastSnapType===`vertex`?X:P_;Z(this.previewGroup,this.mousePoint,n,e,t,this.plane,.6)}}this.requestRender()}},lv=class extends T_{id=`rect`;label=`Rectangle`;icon=Lh;startPoint=null;mousePoint=null;lastSnapType=`none`;shiftHeld=!1;expressionInput;fetchVariables;cachedVariables=[];lastClientX=0;lastClientY=0;expressionPhase=`width`;widthExpression=null;lockedWidth=null;widthIsNumeric=!1;boundMouseDown;boundMouseUp;boundMouseMove;boundKeyDown;boundKeyUp;downX=0;downY=0;constructor(e,t,n,r,i,a){super(e,t,n,r),this.expressionInput=new M_(i),this.fetchVariables=a,this.boundMouseDown=this.handleMouseDown.bind(this),this.boundMouseUp=this.handleMouseUp.bind(this),this.boundMouseMove=this.handleMouseMove.bind(this),this.boundKeyDown=this.handleKeyDown.bind(this),this.boundKeyUp=this.handleKeyUp.bind(this)}activate(){this.addPreviewToScene(),this.canvas.addEventListener(`mousedown`,this.boundMouseDown),this.canvas.addEventListener(`mouseup`,this.boundMouseUp),this.canvas.addEventListener(`mousemove`,this.boundMouseMove),window.addEventListener(`keydown`,this.boundKeyDown),window.addEventListener(`keyup`,this.boundKeyUp),this.fetchVariables().then(e=>{this.cachedVariables=e})}deactivate(){this.canvas.removeEventListener(`mousedown`,this.boundMouseDown),this.canvas.removeEventListener(`mouseup`,this.boundMouseUp),this.canvas.removeEventListener(`mousemove`,this.boundMouseMove),window.removeEventListener(`keydown`,this.boundKeyDown),window.removeEventListener(`keyup`,this.boundKeyUp),this.resetState(),this.removePreviewFromScene()}onSceneUpdate(e,t){let n=n_.fromSceneObjects(e,t,this.plane,this.ctx);this.updateSnapManager(n),this.fetchVariables().then(e=>{this.cachedVariables=e})}resetState(){this.startPoint=null,this.mousePoint=null,this.expressionPhase=`width`,this.widthExpression=null,this.lockedWidth=null,this.widthIsNumeric=!1,this.shiftHeld=!1,this.expressionInput.hide()}handleMouseDown(e){this.downX=e.clientX,this.downY=e.clientY}handleMouseUp(e){let t=e.clientX-this.downX,n=e.clientY-this.downY;if(t*t+n*n>64)return;let r=gp(this.ctx,this.plane,e.clientX,e.clientY);if(!r)return;let i=J(this.snapController.snap(r).point2d);if(!this.startPoint){this.startPoint=i,this.syncModifiers(e),this.rebuildPreview();return}this.expressionInput.isVisible?this.expressionInput.commitCurrentValue():this.commitFromGeometry(i)}handleMouseMove(e){this.lastClientX=e.clientX,this.lastClientY=e.clientY,this.syncModifiers(e);let t=gp(this.ctx,this.plane,e.clientX,e.clientY);if(!t){this.mousePoint=null,this.lastSnapType=`none`,this.rebuildPreview();return}let n=this.snapController.snap(t);this.mousePoint=n.point2d,this.lastSnapType=n.snapType,this.rebuildPreview(),this.updateDimensionInput()}handleKeyDown(e){if(e.key===`Escape`){this.startPoint&&(this.resetState(),this.rebuildPreview());return}e.key===`Shift`&&(this.shiftHeld=!0,this.rebuildPreview())}handleKeyUp(e){e.key===`Shift`&&(this.shiftHeld=!1,this.rebuildPreview())}syncModifiers(e){this.shiftHeld=e.shiftKey}computeDimensions(e){let t=this.startPoint;if(this.shiftHeld){let n=e[0]-t[0],r=e[1]-t[1];return{width:Math.round(n*2*100)/100,height:Math.round(r*2*100)/100}}return{width:Math.round((e[0]-t[0])*100)/100,height:Math.round((e[1]-t[1])*100)/100}}computePreviewCorners(e){let t=this.startPoint;if(this.lockedWidth!==null){if(this.shiftHeld){let n=this.lockedWidth/2,r=e[1]-t[1];return{c1:[t[0]-n,t[1]-r],c2:[t[0]+n,t[1]+r]}}let n=e[0]>=t[0]?1:-1;return{c1:t,c2:[t[0]+n*this.lockedWidth,e[1]]}}if(this.shiftHeld){let n=e[0]-t[0],r=e[1]-t[1];return{c1:[t[0]-n,t[1]-r],c2:[t[0]+n,t[1]+r]}}return{c1:t,c2:e}}updateDimensionInput(){if(!this.startPoint||!this.mousePoint)return;let{width:e,height:t}=this.computeDimensions(this.mousePoint);if(this.expressionPhase===`width`){let t=Math.round(Math.abs(e)*100)/100;if(t<=0)return;this.expressionInput.isVisible?(this.expressionInput.updateValue(t),this.expressionInput.updatePosition(this.lastClientX,this.lastClientY)):this.expressionInput.show({label:`W`,value:String(t),clientX:this.lastClientX,clientY:this.lastClientY,variables:this.cachedVariables,onCommit:e=>this.onWidthCommit(e)})}else if(this.expressionPhase===`height`){let e=Math.round(Math.abs(t)*100)/100;this.expressionInput.isVisible?(this.expressionInput.updateValue(e),this.expressionInput.updatePosition(this.lastClientX,this.lastClientY)):this.expressionInput.show({label:`H`,value:String(e),clientX:this.lastClientX,clientY:this.lastClientY,variables:this.cachedVariables,onCommit:e=>this.onHeightCommit(e)})}}onWidthCommit(e){let t=parseFloat(e.expression),n=!isNaN(t)&&String(t)===e.expression;this.widthIsNumeric=n,n?(this.widthExpression=e,this.lockedWidth=t):(this.widthExpression=e,this.lockedWidth=null),this.expressionPhase=`height`,queueMicrotask(()=>{if(this.mousePoint&&this.startPoint){let{height:e}=this.computeDimensions(this.mousePoint),t=Math.round(Math.abs(e)*100)/100;this.expressionInput.show({label:`H`,value:String(t),clientX:this.lastClientX,clientY:this.lastClientY,variables:this.cachedVariables,onCommit:e=>this.onHeightCommit(e)})}this.rebuildPreview()})}onHeightCommit(e){if(!this.startPoint||!this.widthExpression)return;let t=parseFloat(e.expression),n=!isNaN(t)&&String(t)===e.expression,r=this.resolveSignedDim(this.widthExpression,this.widthIsNumeric,this.lockedWidth,0),i;if(n&&this.mousePoint&&!this.shiftHeld){let n=this.mousePoint[1]>=this.startPoint[1]?1:-1;i={expression:String(Math.round(n*t*100)/100),newVariable:e.newVariable}}else i=e;this.commitRect(this.startPoint,r,i),this.expressionInput.hide(),this.startPoint=null,this.expressionPhase=`width`,this.widthExpression=null,this.lockedWidth=null,this.widthIsNumeric=!1,this.rebuildPreview()}commitFromGeometry(e){if(!this.startPoint)return;let{width:t,height:n}=this.computeDimensions(e);t===0||n===0||(this.commitRect(this.startPoint,{expression:String(t)},{expression:String(n)}),this.expressionInput.hide(),this.startPoint=null,this.expressionPhase=`width`,this.widthExpression=null,this.lockedWidth=null,this.widthIsNumeric=!1,this.rebuildPreview())}resolveSignedDim(e,t,n,r){if(!t||n===null||!this.mousePoint||!this.startPoint||this.shiftHeld)return e;let i=r===0?this.mousePoint[0]>=this.startPoint[0]?1:-1:this.mousePoint[1]>=this.startPoint[1]?1:-1;return{expression:String(Math.round(i*n*100)/100),newVariable:e.newVariable}}commitRect(e,t,n){let r=this.isAtCurrentPosition(e),i;i=r?`rect(${t.expression}, ${n.expression})`:`rect(${this.formatPoint(e)}, ${t.expression}, ${n.expression})`,this.shiftHeld&&(i+=`.centered()`);let a=t.newVariable??n.newVariable;this.insertGeometry(i,a)}rebuildPreview(){this.disposePreview();let e=this.ctx.camera,t=new R(this.plane.normal.x,this.plane.normal.y,this.plane.normal.z);if(this.startPoint){if(Z(this.previewGroup,this.startPoint,Y,e,t,this.plane),this.mousePoint){let{c1:e,c2:t}=this.computePreviewCorners(this.mousePoint);B_(this.previewGroup,e,t,this.plane)}}else if(this.mousePoint&&this.lastSnapType!==`none`){let n=this.lastSnapType===`vertex`?X:P_;Z(this.previewGroup,this.mousePoint,n,e,t,this.plane,.6)}this.requestRender()}},uv=class extends T_{id=`rounded-rect`;label=`Rounded Rectangle`;icon=Rh;startPoint=null;mousePoint=null;lastSnapType=`none`;shiftHeld=!1;expressionInput;fetchVariables;cachedVariables=[];lastClientX=0;lastClientY=0;expressionPhase=`width`;widthExpression=null;heightExpression=null;lockedWidth=null;lockedHeight=null;widthIsNumeric=!1;heightIsNumeric=!1;boundMouseDown;boundMouseUp;boundMouseMove;boundKeyDown;boundKeyUp;downX=0;downY=0;constructor(e,t,n,r,i,a){super(e,t,n,r),this.expressionInput=new M_(i),this.fetchVariables=a,this.boundMouseDown=this.handleMouseDown.bind(this),this.boundMouseUp=this.handleMouseUp.bind(this),this.boundMouseMove=this.handleMouseMove.bind(this),this.boundKeyDown=this.handleKeyDown.bind(this),this.boundKeyUp=this.handleKeyUp.bind(this)}activate(){this.addPreviewToScene(),this.canvas.addEventListener(`mousedown`,this.boundMouseDown),this.canvas.addEventListener(`mouseup`,this.boundMouseUp),this.canvas.addEventListener(`mousemove`,this.boundMouseMove),window.addEventListener(`keydown`,this.boundKeyDown),window.addEventListener(`keyup`,this.boundKeyUp),this.fetchVariables().then(e=>{this.cachedVariables=e})}deactivate(){this.canvas.removeEventListener(`mousedown`,this.boundMouseDown),this.canvas.removeEventListener(`mouseup`,this.boundMouseUp),this.canvas.removeEventListener(`mousemove`,this.boundMouseMove),window.removeEventListener(`keydown`,this.boundKeyDown),window.removeEventListener(`keyup`,this.boundKeyUp),this.resetState(),this.removePreviewFromScene()}onSceneUpdate(e,t){let n=n_.fromSceneObjects(e,t,this.plane,this.ctx);this.updateSnapManager(n),this.fetchVariables().then(e=>{this.cachedVariables=e})}resetState(){this.startPoint=null,this.mousePoint=null,this.expressionPhase=`width`,this.widthExpression=null,this.heightExpression=null,this.lockedWidth=null,this.lockedHeight=null,this.widthIsNumeric=!1,this.heightIsNumeric=!1,this.shiftHeld=!1,this.expressionInput.hide()}handleMouseDown(e){this.downX=e.clientX,this.downY=e.clientY}handleMouseUp(e){let t=e.clientX-this.downX,n=e.clientY-this.downY;if(t*t+n*n>64)return;let r=gp(this.ctx,this.plane,e.clientX,e.clientY);if(!r)return;let i=J(this.snapController.snap(r).point2d);if(!this.startPoint){this.startPoint=i,this.syncModifiers(e),this.rebuildPreview();return}if(this.expressionInput.isVisible)this.expressionInput.commitCurrentValue();else if(this.expressionPhase===`width`||this.expressionPhase===`height`)this.commitDimensionsFromGeometry(i);else if(this.expressionPhase===`radius`){let e=this.computeRadiusFromMouse(i);this.commitRoundedRect(this.startPoint,this.widthExpression,this.heightExpression,{expression:String(e)}),this.resetState(),this.rebuildPreview()}}handleMouseMove(e){this.lastClientX=e.clientX,this.lastClientY=e.clientY,this.syncModifiers(e);let t=gp(this.ctx,this.plane,e.clientX,e.clientY);if(!t){this.mousePoint=null,this.lastSnapType=`none`,this.rebuildPreview();return}let n=this.snapController.snap(t);this.mousePoint=n.point2d,this.lastSnapType=n.snapType,this.rebuildPreview(),this.updateDimensionInput()}handleKeyDown(e){if(e.key===`Escape`){this.startPoint&&(this.resetState(),this.rebuildPreview());return}e.key===`Shift`&&(this.shiftHeld=!0,this.rebuildPreview())}handleKeyUp(e){e.key===`Shift`&&(this.shiftHeld=!1,this.rebuildPreview())}syncModifiers(e){this.shiftHeld=e.shiftKey}computeDimensions(e){let t=this.startPoint;if(this.shiftHeld){let n=e[0]-t[0],r=e[1]-t[1];return{width:Math.round(n*2*100)/100,height:Math.round(r*2*100)/100}}return{width:Math.round((e[0]-t[0])*100)/100,height:Math.round((e[1]-t[1])*100)/100}}computePreviewCorners(e){let t=this.startPoint,n=this.lockedWidth!==null,r=this.lockedHeight!==null;if(n&&r)return this.getLockedPreviewCorners();if(n){if(this.shiftHeld){let n=this.lockedWidth/2,r=e[1]-t[1];return{c1:[t[0]-n,t[1]-r],c2:[t[0]+n,t[1]+r]}}let n=e[0]>=t[0]?1:-1;return{c1:t,c2:[t[0]+n*this.lockedWidth,e[1]]}}if(this.shiftHeld){let n=e[0]-t[0],r=e[1]-t[1];return{c1:[t[0]-n,t[1]-r],c2:[t[0]+n,t[1]+r]}}return{c1:t,c2:e}}getLockedPreviewCorners(){if(!this.startPoint||this.lockedWidth===null||this.lockedHeight===null)return null;if(this.shiftHeld){let e=this.lockedWidth/2,t=this.lockedHeight/2;return{c1:[this.startPoint[0]-e,this.startPoint[1]-t],c2:[this.startPoint[0]+e,this.startPoint[1]+t]}}let e=this.mousePoint?this.mousePoint[0]>=this.startPoint[0]?1:-1:1,t=this.mousePoint?this.mousePoint[1]>=this.startPoint[1]?1:-1:1;return{c1:this.startPoint,c2:[this.startPoint[0]+e*this.lockedWidth,this.startPoint[1]+t*this.lockedHeight]}}computeRadiusFromMouse(e){let t=this.getLockedPreviewCorners();if(!t)return 0;let{c1:n,c2:r}=t,i=[[n[0],n[1]],[r[0],n[1]],[r[0],r[1]],[n[0],r[1]]],a=1/0;for(let t of i){let n=bp(e,t);n<a&&(a=n)}let o=Math.min(Math.abs(r[0]-n[0])/2,Math.abs(r[1]-n[1])/2);return Math.round(Math.min(a,o)*100)/100}updateDimensionInput(){if(!(!this.startPoint||!this.mousePoint)){if(this.expressionPhase===`width`){let{width:e}=this.computeDimensions(this.mousePoint),t=Math.round(Math.abs(e)*100)/100;if(t<=0)return;this.expressionInput.isVisible?(this.expressionInput.updateValue(t),this.expressionInput.updatePosition(this.lastClientX,this.lastClientY)):this.expressionInput.show({label:`W`,value:String(t),clientX:this.lastClientX,clientY:this.lastClientY,variables:this.cachedVariables,onCommit:e=>this.onWidthCommit(e)})}else if(this.expressionPhase===`height`){let{height:e}=this.computeDimensions(this.mousePoint),t=Math.round(Math.abs(e)*100)/100,n=e>=0?1:-1;this.expressionInput.isVisible?(this.expressionInput.updateValue(t),this.expressionInput.updatePosition(this.lastClientX,this.lastClientY)):this.expressionInput.show({label:`H`,value:String(t),clientX:this.lastClientX,clientY:this.lastClientY,variables:this.cachedVariables,onCommit:e=>this.onHeightCommit(e,n)})}else if(this.expressionPhase===`radius`){let e=this.computeRadiusFromMouse(this.mousePoint);this.expressionInput.isVisible?(this.expressionInput.updateValue(e),this.expressionInput.updatePosition(this.lastClientX,this.lastClientY)):this.expressionInput.show({label:`R`,value:String(e),clientX:this.lastClientX,clientY:this.lastClientY,variables:this.cachedVariables,onCommit:e=>this.onRadiusCommit(e)})}}}onWidthCommit(e){let t=parseFloat(e.expression),n=!isNaN(t)&&String(t)===e.expression;this.widthIsNumeric=n,n?(this.widthExpression=e,this.lockedWidth=t):(this.widthExpression=e,this.lockedWidth=null),this.expressionPhase=`height`,queueMicrotask(()=>{if(this.mousePoint&&this.startPoint){let{height:e}=this.computeDimensions(this.mousePoint),t=Math.round(Math.abs(e)*100)/100,n=e>=0?1:-1;this.expressionInput.show({label:`H`,value:String(t),clientX:this.lastClientX,clientY:this.lastClientY,variables:this.cachedVariables,onCommit:e=>this.onHeightCommit(e,n)})}this.rebuildPreview()})}onHeightCommit(e,t){if(!this.startPoint||!this.widthExpression)return;let n=parseFloat(e.expression),r=!isNaN(n)&&String(n)===e.expression;this.heightIsNumeric=r,r?(this.heightExpression=e,this.lockedHeight=n):(this.heightExpression=e,this.lockedHeight=null),this.expressionPhase=`radius`,queueMicrotask(()=>{if(this.mousePoint){let e=this.computeRadiusFromMouse(this.mousePoint);this.expressionInput.show({label:`R`,value:String(e),clientX:this.lastClientX,clientY:this.lastClientY,variables:this.cachedVariables,onCommit:e=>this.onRadiusCommit(e)})}this.rebuildPreview()})}onRadiusCommit(e){if(!this.startPoint||!this.widthExpression||!this.heightExpression)return;let t=this.resolveSignedExpression(this.widthExpression,this.widthIsNumeric,this.lockedWidth,0),n=this.resolveSignedExpression(this.heightExpression,this.heightIsNumeric,this.lockedHeight,1);this.commitRoundedRect(this.startPoint,t,n,e),this.resetState(),this.rebuildPreview()}resolveSignedExpression(e,t,n,r){if(!t||n===null||!this.mousePoint||!this.startPoint||this.shiftHeld)return e;let i=r===0?this.mousePoint[0]>=this.startPoint[0]?1:-1:this.mousePoint[1]>=this.startPoint[1]?1:-1,a=Math.round(i*n*100)/100;return{expression:String(a),newVariable:e.newVariable}}commitDimensionsFromGeometry(e){if(!this.startPoint)return;let{width:t,height:n}=this.computeDimensions(e);if(!(t===0||n===0)){if(this.widthExpression={expression:String(t)},this.lockedWidth=Math.abs(t),this.widthIsNumeric=!0,this.heightExpression={expression:String(n)},this.lockedHeight=Math.abs(n),this.heightIsNumeric=!0,this.expressionPhase=`radius`,this.expressionInput.hide(),this.mousePoint){let e=this.computeRadiusFromMouse(this.mousePoint);this.expressionInput.show({label:`R`,value:String(e),clientX:this.lastClientX,clientY:this.lastClientY,variables:this.cachedVariables,onCommit:e=>this.onRadiusCommit(e)})}this.rebuildPreview()}}commitRoundedRect(e,t,n,r){let i=this.isAtCurrentPosition(e),a;a=i?`rect(${t.expression}, ${n.expression})`:`rect(${this.formatPoint(e)}, ${t.expression}, ${n.expression})`,a+=`.radius(${r.expression})`,this.shiftHeld&&(a+=`.centered()`);let o=t.newVariable??n.newVariable??r.newVariable;this.insertGeometry(a,o)}rebuildPreview(){this.disposePreview();let e=this.ctx.camera,t=new R(this.plane.normal.x,this.plane.normal.y,this.plane.normal.z);if(this.startPoint){if(Z(this.previewGroup,this.startPoint,Y,e,t,this.plane),this.expressionPhase===`radius`){let e=this.getLockedPreviewCorners();if(e){let t=this.mousePoint?this.computeRadiusFromMouse(this.mousePoint):0;t>0?H_(this.previewGroup,e.c1,e.c2,t,this.plane):B_(this.previewGroup,e.c1,e.c2,this.plane)}}else if(this.mousePoint){let{c1:e,c2:t}=this.computePreviewCorners(this.mousePoint);B_(this.previewGroup,e,t,this.plane)}}else if(this.mousePoint&&this.lastSnapType!==`none`){let n=this.lastSnapType===`vertex`?X:P_;Z(this.previewGroup,this.mousePoint,n,e,t,this.plane,.6)}this.requestRender()}},dv=class extends T_{id=`slot`;label=`Slot`;icon=zh;startPoint=null;endPoint=null;mousePoint=null;lastSnapType=`none`;shiftHeld=!1;horizontalMode=!1;expressionInput;fetchVariables;cachedVariables=[];lastClientX=0;lastClientY=0;expressionPhase=`endpoint`;distanceExpression=null;lockedDistance=null;boundMouseDown;boundMouseUp;boundMouseMove;boundKeyDown;boundKeyUp;downX=0;downY=0;constructor(e,t,n,r,i,a){super(e,t,n,r),this.expressionInput=new M_(i),this.fetchVariables=a,this.boundMouseDown=this.handleMouseDown.bind(this),this.boundMouseUp=this.handleMouseUp.bind(this),this.boundMouseMove=this.handleMouseMove.bind(this),this.boundKeyDown=this.handleKeyDown.bind(this),this.boundKeyUp=this.handleKeyUp.bind(this)}activate(){this.addPreviewToScene(),this.canvas.addEventListener(`mousedown`,this.boundMouseDown),this.canvas.addEventListener(`mouseup`,this.boundMouseUp),this.canvas.addEventListener(`mousemove`,this.boundMouseMove),window.addEventListener(`keydown`,this.boundKeyDown),window.addEventListener(`keyup`,this.boundKeyUp),this.fetchVariables().then(e=>{this.cachedVariables=e})}deactivate(){this.canvas.removeEventListener(`mousedown`,this.boundMouseDown),this.canvas.removeEventListener(`mouseup`,this.boundMouseUp),this.canvas.removeEventListener(`mousemove`,this.boundMouseMove),window.removeEventListener(`keydown`,this.boundKeyDown),window.removeEventListener(`keyup`,this.boundKeyUp),this.resetState(),this.removePreviewFromScene()}onSceneUpdate(e,t){let n=n_.fromSceneObjects(e,t,this.plane,this.ctx);this.updateSnapManager(n),this.fetchVariables().then(e=>{this.cachedVariables=e})}handleEscape(){return this.startPoint?this.expressionPhase===`radius`?(this.expressionPhase=this.horizontalMode?`distance`:`endpoint`,this.endPoint=null,this.distanceExpression=null,this.lockedDistance=null,this.expressionInput.hide(),this.rebuildPreview(),!0):this.expressionPhase===`distance`?(this.expressionPhase=`endpoint`,this.horizontalMode=!1,this.expressionInput.hide(),this.rebuildPreview(),!0):(this.resetState(),this.rebuildPreview(),!0):!1}resetState(){this.startPoint=null,this.endPoint=null,this.mousePoint=null,this.expressionPhase=`endpoint`,this.horizontalMode=!1,this.distanceExpression=null,this.lockedDistance=null,this.expressionInput.hide()}handleMouseDown(e){this.downX=e.clientX,this.downY=e.clientY}handleMouseUp(e){let t=e.clientX-this.downX,n=e.clientY-this.downY;if(t*t+n*n>64)return;let r=gp(this.ctx,this.plane,e.clientX,e.clientY);if(!r)return;let i=J(this.snapController.snap(r).point2d);if(!this.startPoint){this.startPoint=i,this.syncModifiers(e),this.shiftHeld&&(this.horizontalMode=!0,this.expressionPhase=`distance`),this.rebuildPreview();return}if(this.expressionInput.isVisible){this.expressionInput.commitCurrentValue();return}if(this.expressionPhase===`endpoint`){if(bp(this.startPoint,i)<=0)return;this.endPoint=i,this.expressionPhase=`radius`,this.expressionInput.hide(),this.rebuildPreview(),this.updateDimensionInput();return}if(this.expressionPhase===`distance`){let e=Math.round((i[0]-this.startPoint[0])*100)/100;if(e===0)return;this.onDistanceCommit({expression:String(e)});return}if(this.expressionPhase===`radius`){let e=this.computeRadiusFromMouse(i);if(e<=0)return;this.onRadiusCommit({expression:String(e)})}}handleMouseMove(e){this.lastClientX=e.clientX,this.lastClientY=e.clientY,this.syncModifiers(e);let t=gp(this.ctx,this.plane,e.clientX,e.clientY);if(!t){this.mousePoint=null,this.lastSnapType=`none`,this.rebuildPreview();return}let n=this.snapController.snap(t);this.mousePoint=n.point2d,this.lastSnapType=n.snapType,this.rebuildPreview(),this.updateDimensionInput()}handleKeyDown(e){if(e.key===`Escape`){this.handleEscape()&&e.stopPropagation();return}e.key===`Shift`&&(this.shiftHeld=!0,this.startPoint&&this.expressionPhase===`endpoint`&&!this.horizontalMode&&(this.horizontalMode=!0,this.expressionPhase=`distance`,this.expressionInput.hide()),this.rebuildPreview(),this.updateDimensionInput())}handleKeyUp(e){e.key===`Shift`&&(this.shiftHeld=!1,this.expressionPhase===`distance`&&!this.distanceExpression&&(this.horizontalMode=!1,this.expressionPhase=`endpoint`,this.expressionInput.hide()),this.rebuildPreview(),this.updateDimensionInput())}syncModifiers(e){this.shiftHeld=e.shiftKey}getSlotAxis(){if(!this.startPoint)return null;if(this.horizontalMode){let e=this.lockedDistance??(this.mousePoint?this.mousePoint[0]-this.startPoint[0]:0);return{dir:e>=0?[1,0]:[-1,0],leftCenter:this.startPoint,rightCenter:[this.startPoint[0]+e,this.startPoint[1]]}}if(this.endPoint){let e=this.endPoint[0]-this.startPoint[0],t=this.endPoint[1]-this.startPoint[1],n=Math.sqrt(e*e+t*t);return n<1e-10?null:{dir:[e/n,t/n],leftCenter:this.startPoint,rightCenter:this.endPoint}}if(this.mousePoint){let e=this.mousePoint[0]-this.startPoint[0],t=this.mousePoint[1]-this.startPoint[1],n=Math.sqrt(e*e+t*t);return n<1e-10?null:{dir:[e/n,t/n],leftCenter:this.startPoint,rightCenter:this.mousePoint}}return null}computeRadiusFromMouse(e){let t=this.getSlotAxis();if(!t)return 0;let n=e[0]-t.leftCenter[0],r=e[1]-t.leftCenter[1],i=Math.abs(-t.dir[1]*n+t.dir[0]*r);return Math.round(i*100)/100}updateDimensionInput(){if(!(!this.startPoint||!this.mousePoint)){if(this.expressionPhase===`distance`){let e=Math.round((this.mousePoint[0]-this.startPoint[0])*100)/100;if(e===0)return;this.expressionInput.isVisible?(this.expressionInput.updateValue(e),this.expressionInput.updatePosition(this.lastClientX,this.lastClientY)):this.expressionInput.show({label:`D`,value:String(e),clientX:this.lastClientX,clientY:this.lastClientY,variables:this.cachedVariables,onCommit:e=>this.onDistanceCommit(e)});return}if(this.expressionPhase===`radius`){let e=this.computeRadiusFromMouse(this.mousePoint);if(e<=0)return;this.expressionInput.isVisible?(this.expressionInput.updateValue(e),this.expressionInput.updatePosition(this.lastClientX,this.lastClientY)):this.expressionInput.show({label:`R`,value:String(e),clientX:this.lastClientX,clientY:this.lastClientY,variables:this.cachedVariables,onCommit:e=>this.onRadiusCommit(e)})}}}onDistanceCommit(e){let t=parseFloat(e.expression),n=!isNaN(t)&&String(t)===e.expression;this.distanceExpression=e,this.lockedDistance=n?t:null,this.expressionPhase=`radius`,queueMicrotask(()=>{if(this.mousePoint){let e=this.computeRadiusFromMouse(this.mousePoint);this.expressionInput.show({label:`R`,value:String(e),clientX:this.lastClientX,clientY:this.lastClientY,variables:this.cachedVariables,onCommit:e=>this.onRadiusCommit(e)})}this.rebuildPreview()})}onRadiusCommit(e){this.startPoint&&(this.horizontalMode&&this.distanceExpression?this.commitHorizontalSlot(this.startPoint,this.distanceExpression,e):this.endPoint&&this.commitTwoPointSlot(this.startPoint,this.endPoint,e),this.resetState(),this.rebuildPreview())}commitTwoPointSlot(e,t,n){let r=`slot(${this.formatPoint(e)}, ${this.formatPoint(t)}, ${n.expression})`;this.insertGeometry(r,n.newVariable)}commitHorizontalSlot(e,t,n){let r=this.isAtCurrentPosition(e)?`slot(${t.expression}, ${n.expression})`:`slot(${this.formatPoint(e)}, ${t.expression}, ${n.expression})`,i=t.newVariable??n.newVariable;this.insertGeometry(r,i)}rebuildPreview(){this.disposePreview();let e=this.ctx.camera,t=new R(this.plane.normal.x,this.plane.normal.y,this.plane.normal.z);if(this.startPoint){Z(this.previewGroup,this.startPoint,Y,e,t,this.plane);let n=this.getSlotAxis();if(n){let r=bp(n.leftCenter,n.rightCenter);if(r>0)if(this.expressionPhase===`radius`&&this.mousePoint){let r=this.computeRadiusFromMouse(this.mousePoint);r>0?J_(this.previewGroup,n.leftCenter,n.rightCenter,r,this.plane):R_(this.previewGroup,n.leftCenter,n.rightCenter,this.plane),Z(this.previewGroup,n.rightCenter,Y,e,t,this.plane)}else J_(this.previewGroup,n.leftCenter,n.rightCenter,r/6,this.plane),Z(this.previewGroup,n.rightCenter,X,e,t,this.plane)}}else if(this.mousePoint&&this.lastSnapType!==`none`){let n=this.lastSnapType===`vertex`?X:P_;Z(this.previewGroup,this.mousePoint,n,e,t,this.plane,.6)}this.requestRender()}},fv={line:`Line`,hLine:`H-Line`,vLine:`V-Line`,arc:`Arc`,tArc:`T-Arc`,tLine:`T-Line`},pv=class{el;labelSpan;constructor(e){this.el=document.createElement(`div`),this.el.className=`absolute z-[999] pointer-events-none hidden`;let t=document.createElement(`div`);t.className=`panel-bg border border-base-content/10 rounded-md px-2 py-0.5 shadow-sm flex items-center gap-1.5`,this.labelSpan=document.createElement(`span`),this.labelSpan.className=`text-xs font-mono text-base-content/70`;let n=document.createElement(`span`);n.className=`text-[10px] text-base-content/30`,n.textContent=`Space`,t.appendChild(this.labelSpan),t.appendChild(n),this.el.appendChild(t),e.appendChild(this.el)}show(e){this.labelSpan.textContent=fv[e],this.el.classList.remove(`hidden`)}hide(){this.el.classList.add(`hidden`)}update(e){this.labelSpan.textContent=fv[e]}updatePosition(e,t){this.el.style.left=`${e+16}px`,this.el.style.top=`${t+16}px`}dispose(){this.el.remove()}},mv=class{id=`line`;label=`Line`;requiresTangent=!1;mousePoint=null;lastSnapType=`none`;enter(e){this.mousePoint=null,this.lastSnapType=`none`}exit(e){this.mousePoint=null}handleClick(e,t,n){let r=J(n.startPoint),i=J(e),a=n.isAtCurrentPosition(r)?`line(${n.formatPoint(i)})`:`line(${n.formatPoint(r)}, ${n.formatPoint(i)})`;n.insertGeometry(a);let o=i[0]-r[0],s=i[1]-r[1],c=Math.sqrt(o*o+s*s);return{kind:`committed`,result:{endpoint:i,exitTangent:c>1e-10?{direction:[o/c,s/c],point:i}:null}}}handleMouseMove(e,t,n,r,i){this.mousePoint=e,this.lastSnapType=t.snapType}handleEscape(e){return!1}rebuildPreview(e){if(Z(e.previewGroup,e.startPoint,Y,e.camera,e.planeNormal,e.plane),this.mousePoint&&(R_(e.previewGroup,e.startPoint,this.mousePoint,e.plane),this.lastSnapType!==`none`)){let t=this.lastSnapType===`vertex`?X:P_;Z(e.previewGroup,this.mousePoint,t,e.camera,e.planeNormal,e.plane,.6)}}},hv=class{id;label;requiresTangent=!1;axis;mousePoint=null;lastSnapType=`none`;constructor(e){this.axis=e,this.id=e===`h`?`hLine`:`vLine`,this.label=e===`h`?`H-Line`:`V-Line`}enter(e){this.mousePoint=null,this.lastSnapType=`none`}exit(e){this.mousePoint=null,e.hideExpressionInput()}getEffectiveEnd(e,t){return this.axis===`h`?[t[0],e[1]]:[e[0],t[1]]}getDistance(e,t){return this.axis===`h`?t[0]-e[0]:t[1]-e[1]}handleClick(e,t,n){if(n.isExpressionVisible())return n.commitExpressionValue(),{kind:`ignored`};let r=J(n.startPoint),i=this.getDistance(r,e),a=Math.round(i*100)/100;if(a===0)return{kind:`ignored`};let o=n.isAtCurrentPosition(r),s=this.axis===`h`?`hLine`:`vLine`,c=o?`${s}(${a})`:`${s}(${n.formatPoint(r)}, ${a})`;n.insertGeometry(c),n.hideExpressionInput();let l=J(this.axis===`h`?[r[0]+a,r[1]]:[r[0],r[1]+a]);return{kind:`committed`,result:{endpoint:l,exitTangent:{direction:this.axis===`h`?[Math.sign(a)||1,0]:[0,Math.sign(a)||1],point:l}}}}handleMouseMove(e,t,n,r,i){this.mousePoint=e,this.lastSnapType=t.snapType;let a=Math.abs(this.getDistance(i.startPoint,e)),o=this.axis===`h`?`H:`:`V:`;i.isExpressionVisible()?(i.updateExpressionValue(a),i.updateExpressionPosition(n,r)):i.showExpressionInput({label:o,value:String(Math.round(a*100)/100),clientX:n,clientY:r,onCommit:e=>this.commitWithDimension(e,i)})}handleEscape(e){return e.isExpressionVisible()?(e.hideExpressionInput(),!0):!1}commitWithDimension(e,t){let n=J(t.startPoint);if(!this.mousePoint)return;let{expression:r,newVariable:i}=e,a=this.getDistance(n,this.mousePoint),o=Math.sign(a),s=parseFloat(r),c=!isNaN(s)&&String(s)===r?String(Math.round(o*s*100)/100):r,l=t.isAtCurrentPosition(n),u=this.axis===`h`?`hLine`:`vLine`,d=l?`${u}(${c})`:`${u}(${t.formatPoint(n)}, ${c})`;t.insertGeometry(d,i),t.hideExpressionInput();let f=parseFloat(c),p=isNaN(f)?Math.round(o*Math.abs(this.getDistance(n,this.mousePoint))*100)/100:f,m=this.axis===`h`?[n[0]+p,n[1]]:[n[0],n[1]+p],h=this.axis===`h`?[Math.sign(p)||1,0]:[0,Math.sign(p)||1];t.onSegmentCommitted({endpoint:J(m),exitTangent:{direction:h,point:J(m)}})}rebuildPreview(e){if(Z(e.previewGroup,e.startPoint,Y,e.camera,e.planeNormal,e.plane),this.mousePoint){let t=this.getEffectiveEnd(e.startPoint,this.mousePoint);if(R_(e.previewGroup,e.startPoint,t,e.plane),this.lastSnapType!==`none`){let n=this.lastSnapType===`vertex`?X:P_;Z(e.previewGroup,t,n,e.camera,e.planeNormal,e.plane,.6)}}}},gv=function(e){return e[e.AWAITING_END=0]=`AWAITING_END`,e[e.AWAITING_THROUGH=1]=`AWAITING_THROUGH`,e}(gv||{}),_v=class{id=`arc`;label=`Arc`;requiresTangent=!1;subState=gv.AWAITING_END;endPoint=null;mousePoint=null;lastSnapType=`none`;enter(e){this.subState=gv.AWAITING_END,this.endPoint=null,this.mousePoint=null,this.lastSnapType=`none`}exit(e){this.subState=gv.AWAITING_END,this.endPoint=null,this.mousePoint=null}handleClick(e,t,n){if(this.subState===gv.AWAITING_END)return bp(n.startPoint,e)<1e-6?{kind:`ignored`}:(this.endPoint=e,this.subState=gv.AWAITING_THROUGH,{kind:`consumed`});if(!this.endPoint)return{kind:`ignored`};let r=Z_(n.startPoint,this.endPoint,e);if(!r)return{kind:`ignored`};let i=this.isMouseCCW(n.startPoint,this.endPoint,e,r),a=J(n.startPoint),o=J(this.endPoint),s=J(r),c=i?``:`.cw()`,l=n.isAtCurrentPosition(a)?`arc(${n.formatPoint(o)}).center(${n.formatPoint(s)})${c}`:`arc(${n.formatPoint(a)}, ${n.formatPoint(o)}).center(${n.formatPoint(s)})${c}`;return n.insertGeometry(l),{kind:`committed`,result:{endpoint:o,exitTangent:this.computeExitTangent(o,s,i)}}}handleMouseMove(e,t,n,r,i){this.mousePoint=e,this.lastSnapType=t.snapType}handleEscape(e){return this.subState===gv.AWAITING_THROUGH?(this.endPoint=null,this.subState=gv.AWAITING_END,!0):!1}isMouseCCW(e,t,n,r){let i=Y_(r,e),a=Y_(r,t),o=Y_(r,n)-i;o<0&&(o+=Math.PI*2);let s=a-i;return s<0&&(s+=Math.PI*2),o<s}semicirclePreview(e,t){let n=t[0]-e[0],r=t[1]-e[1],i=Math.sqrt(n*n+r*r);if(i<1e-6)return null;let a=[(e[0]+t[0])/2,(e[1]+t[1])/2];return{center:a,radius:i/2,startAngle:Y_(a,e),endAngle:Y_(a,t)}}computeExitTangent(e,t,n){let r=e[0]-t[0],i=e[1]-t[1],a=Math.sqrt(r*r+i*i);return a<1e-10?null:{direction:[n?-i/a:i/a,n?r/a:-r/a],point:e}}rebuildPreview(e){if(Z(e.previewGroup,e.startPoint,Y,e.camera,e.planeNormal,e.plane),this.subState===gv.AWAITING_END){if(this.mousePoint){let t=this.semicirclePreview(e.startPoint,this.mousePoint);if(t&&W_(e.previewGroup,t.center,t.radius,t.startAngle,t.endAngle,!0,e.plane),this.lastSnapType!==`none`){let t=this.lastSnapType===`vertex`?X:P_;Z(e.previewGroup,this.mousePoint,t,e.camera,e.planeNormal,e.plane,.6)}}}else if(this.endPoint&&(Z(e.previewGroup,this.endPoint,Y,e.camera,e.planeNormal,e.plane),R_(e.previewGroup,e.startPoint,this.endPoint,e.plane),this.mousePoint)){let t=Z_(e.startPoint,this.endPoint,this.mousePoint);if(t){let n=bp(t,e.startPoint),r=Y_(t,e.startPoint),i=Y_(t,this.endPoint),a=this.isMouseCCW(e.startPoint,this.endPoint,this.mousePoint,t);W_(e.previewGroup,t,n,r,i,a,e.plane)}if(this.lastSnapType!==`none`){let t=this.lastSnapType===`vertex`?X:P_;Z(e.previewGroup,this.mousePoint,t,e.camera,e.planeNormal,e.plane,.6)}}}},vv=class{id=`tArc`;label=`T-Arc`;requiresTangent=!0;mousePoint=null;lastSnapType=`none`;enter(e){this.mousePoint=null,this.lastSnapType=`none`}exit(e){this.mousePoint=null}handleClick(e,t,n){if(!n.tangent)return{kind:`ignored`};let r=J(e);n.insertGeometry(`tArc(${n.formatPoint(r)})`);let i=this.computeArcPreview(n.startPoint,e,n.tangent.direction),a=null;if(i){let e=r[0]-i.center[0],t=r[1]-i.center[1],n=Math.sqrt(e*e+t*t);n>1e-10&&(a={direction:[i.ccw?-t/n:t/n,i.ccw?e/n:-e/n],point:r})}return{kind:`committed`,result:{endpoint:r,exitTangent:a}}}handleMouseMove(e,t,n,r,i){this.mousePoint=e,this.lastSnapType=t.snapType}handleEscape(e){return!1}computeArcPreview(e,t,n){let r=-n[1],i=n[0],a=e[0]-t[0],o=e[1]-t[1],s=a*a+o*o,c=a*r+o*i;if(Math.abs(c)<1e-10)return null;let l=-s/(2*c),u=Math.abs(l),d=[e[0]+r*l,e[1]+i*l];return{center:d,radius:u,startAngle:Y_(d,e),endAngle:Y_(d,t),ccw:l>=0}}rebuildPreview(e){if(e.tangent&&(Z(e.previewGroup,e.startPoint,Y,e.camera,e.planeNormal,e.plane),this.mousePoint)){let t=this.computeArcPreview(e.startPoint,this.mousePoint,e.tangent.direction);if(t&&W_(e.previewGroup,t.center,t.radius,t.startAngle,t.endAngle,t.ccw,e.plane),this.lastSnapType!==`none`){let t=this.lastSnapType===`vertex`?X:P_;Z(e.previewGroup,this.mousePoint,t,e.camera,e.planeNormal,e.plane,.6)}}}},yv=class{id=`tLine`;label=`T-Line`;requiresTangent=!0;mousePoint=null;enter(e){this.mousePoint=null}exit(e){this.mousePoint=null,e.hideExpressionInput()}projectOnTangent(e,t,n){let r=t[0]-e[0],i=t[1]-e[1],a=r*n[0]+i*n[1];return{projected:[e[0]+n[0]*a,e[1]+n[1]*a],distance:a}}handleClick(e,t,n){if(!n.tangent)return{kind:`ignored`};if(n.isExpressionVisible())return n.commitExpressionValue(),{kind:`ignored`};if(!this.mousePoint)return{kind:`ignored`};let{distance:r}=this.projectOnTangent(n.startPoint,this.mousePoint,n.tangent.direction),i=Math.round(r*100)/100;if(i===0)return{kind:`ignored`};n.insertGeometry(`tLine(${i})`),n.hideExpressionInput();let a=J([n.startPoint[0]+n.tangent.direction[0]*r,n.startPoint[1]+n.tangent.direction[1]*r]);return{kind:`committed`,result:{endpoint:a,exitTangent:{direction:n.tangent.direction,point:a}}}}handleMouseMove(e,t,n,r,i){if(this.mousePoint=e,!i.tangent)return;let{distance:a}=this.projectOnTangent(i.startPoint,e,i.tangent.direction),o=Math.abs(a);i.isExpressionVisible()?(i.updateExpressionValue(o),i.updateExpressionPosition(n,r)):i.showExpressionInput({label:`T:`,value:String(Math.round(o*100)/100),clientX:n,clientY:r,onCommit:e=>this.commitWithDimension(e,i)})}handleEscape(e){return e.isExpressionVisible()?(e.hideExpressionInput(),!0):!1}commitWithDimension(e,t){if(!t.tangent||!this.mousePoint)return;let{expression:n,newVariable:r}=e,{distance:i}=this.projectOnTangent(t.startPoint,this.mousePoint,t.tangent.direction),a=Math.sign(i),o=parseFloat(n),s=!isNaN(o)&&String(o)===n?String(Math.round(a*o*100)/100):n;t.insertGeometry(`tLine(${s})`,r),t.hideExpressionInput();let c=J([t.startPoint[0]+t.tangent.direction[0]*i,t.startPoint[1]+t.tangent.direction[1]*i]);t.onSegmentCommitted({endpoint:c,exitTangent:{direction:t.tangent.direction,point:c}})}rebuildPreview(e){if(e.tangent&&(Z(e.previewGroup,e.startPoint,Y,e.camera,e.planeNormal,e.plane),this.mousePoint)){let{projected:t}=this.projectOnTangent(e.startPoint,this.mousePoint,e.tangent.direction);R_(e.previewGroup,e.startPoint,t,e.plane)}}},bv=function(e){return e[e.IDLE=0]=`IDLE`,e[e.DRAWING=1]=`DRAWING`,e}({}),xv=[`line`,`hLine`,`vLine`,`arc`,`tArc`,`tLine`],Sv=class extends T_{id=`polyline`;label=`Polyline`;icon=Vh;phase=bv.IDLE;startPoint=null;currentModeIndex=0;tangent=null;modes;expressionInput;fetchVariables;cachedVariables=[];modeIndicator;sceneObjects=[];sketchId=``;mousePoint=null;lastSnapType=`none`;lastSnapResult=null;lastClientX=0;lastClientY=0;boundMouseDown;boundMouseUp;boundMouseMove;boundKeyDown;downX=0;downY=0;constructor(e,t,n,r,i,a){super(e,t,n,r),this.expressionInput=new M_(i),this.fetchVariables=a,this.modeIndicator=new pv(i),this.modes=[new mv,new hv(`h`),new hv(`v`),new _v,new vv,new yv],this.boundMouseDown=this.handleMouseDown.bind(this),this.boundMouseUp=this.handleMouseUp.bind(this),this.boundMouseMove=this.handleMouseMove.bind(this),this.boundKeyDown=this.handleKeyDown.bind(this),this.expressionInput.onSpaceOverride=()=>{this.cycleMode(1)}}get currentMode(){return this.modes[this.currentModeIndex]}activate(){this.addPreviewToScene(),this.canvas.addEventListener(`mousedown`,this.boundMouseDown),this.canvas.addEventListener(`mouseup`,this.boundMouseUp),this.canvas.addEventListener(`mousemove`,this.boundMouseMove),window.addEventListener(`keydown`,this.boundKeyDown),this.fetchVariables().then(e=>{this.cachedVariables=e}),this.modeIndicator.show(this.currentMode.id)}deactivate(){this.canvas.removeEventListener(`mousedown`,this.boundMouseDown),this.canvas.removeEventListener(`mouseup`,this.boundMouseUp),this.canvas.removeEventListener(`mousemove`,this.boundMouseMove),window.removeEventListener(`keydown`,this.boundKeyDown),this.expressionInput.hide(),this.modeIndicator.dispose(),this.phase=bv.IDLE,this.startPoint=null,this.tangent=null,this.removePreviewFromScene()}onSceneUpdate(e,t){this.sceneObjects=e,this.sketchId=t;let n=n_.fromSceneObjects(e,t,this.plane,this.ctx);this.updateSnapManager(n),this.fetchVariables().then(e=>{this.cachedVariables=e}),this.phase===bv.DRAWING&&this.startPoint&&this.updateTangentFromScene()}handleEscape(){return!1}buildModeContext(){if(!this.startPoint)return null;let e=new R(this.plane.normal.x,this.plane.normal.y,this.plane.normal.z);return{plane:this.plane,previewGroup:this.previewGroup,camera:this.ctx.camera,planeNormal:e,tangent:this.tangent,sceneObjects:this.sceneObjects,sketchId:this.sketchId,startPoint:this.startPoint,isAtCurrentPosition:e=>this.isAtCurrentPosition(e),formatPoint:e=>this.formatPoint(e),insertGeometry:(e,t)=>this.insertGeometry(e,t),requestRender:()=>this.requestRender(),showExpressionInput:e=>{this.expressionInput.isVisible||this.expressionInput.show({...e,variables:this.cachedVariables})},updateExpressionValue:e=>this.expressionInput.updateValue(e),updateExpressionPosition:(e,t)=>this.expressionInput.updatePosition(e,t),hideExpressionInput:()=>this.expressionInput.hide(),isExpressionVisible:()=>this.expressionInput.isVisible,commitExpressionValue:()=>this.expressionInput.commitCurrentValue(),onSegmentCommitted:e=>this.handleModeCommit(e)}}handleModeCommit(e){let{endpoint:t,exitTangent:n}=e;this.startPoint=t,this.tangent=n,this.currentMode.requiresTangent&&!this.tangent&&(this.advanceToNextValidMode(),this.modeIndicator.update(this.currentMode.id));let r=this.buildModeContext();this.currentMode.enter(r),this.rebuildPreview()}handleMouseDown(e){this.downX=e.clientX,this.downY=e.clientY}handleMouseUp(e){let t=e.clientX-this.downX,n=e.clientY-this.downY;if(t*t+n*n>64)return;let r=gp(this.ctx,this.plane,e.clientX,e.clientY);if(!r)return;let i=this.snapController.snap(r),a=J(i.point2d);if(this.phase===bv.IDLE){this.startPoint=a,this.phase=bv.DRAWING,this.tangent=this.findTangentAtPoint(a),this.currentMode.requiresTangent&&!this.tangent&&this.advanceToNextValidMode();let e=this.buildModeContext();this.currentMode.enter(e),this.modeIndicator.update(this.currentMode.id),this.rebuildPreview();return}let o=this.buildModeContext();if(!o)return;let s=this.currentMode.handleClick(a,i,o);s.kind===`committed`?this.handleModeCommit(s.result):this.rebuildPreview()}handleMouseMove(e){this.lastClientX=e.clientX,this.lastClientY=e.clientY;let t=gp(this.ctx,this.plane,e.clientX,e.clientY);if(!t){this.mousePoint=null,this.lastSnapType=`none`,this.rebuildPreview();return}let n=this.snapController.snap(t);if(this.mousePoint=n.point2d,this.lastSnapType=n.snapType,this.lastSnapResult=n,this.modeIndicator.updatePosition(e.clientX,e.clientY),this.phase===bv.DRAWING){let t=this.buildModeContext();t&&this.currentMode.handleMouseMove(n.point2d,n,e.clientX,e.clientY,t)}this.rebuildPreview()}handleKeyDown(e){if(e.key===` `){e.preventDefault(),this.cycleMode(e.shiftKey?-1:1);return}}cycleMode(e){let t=this.buildModeContext();t&&(this.expressionInput.hide(),this.currentMode.exit(t));let n=this.currentModeIndex;for(let t=0;t<xv.length&&(this.currentModeIndex=(this.currentModeIndex+e+xv.length)%xv.length,!(!this.modes[this.currentModeIndex].requiresTangent||this.tangent||this.currentModeIndex===n));t++);if(this.modeIndicator.update(this.currentMode.id),this.phase===bv.DRAWING){let e=this.buildModeContext();e&&(this.currentMode.enter(e),this.mousePoint&&this.lastSnapResult&&this.currentMode.handleMouseMove(this.mousePoint,this.lastSnapResult,this.lastClientX,this.lastClientY,e))}this.rebuildPreview()}advanceToNextValidMode(){let e=this.currentModeIndex;for(let t=0;t<xv.length;t++)if(this.currentModeIndex=(this.currentModeIndex+1)%xv.length,!this.modes[this.currentModeIndex].requiresTangent||this.tangent||this.currentModeIndex===e)return}findTangentAtPoint(e){if(!this.isAtCurrentPosition(J(e)))return null;let t=null;for(let e of this.sceneObjects)e.parentId!==this.sketchId||!e.sourceLocation||ev.has(e.uniqueType??``)&&(t=e);if(!t)return null;for(let n of t.sceneShapes)if(!n.isMetaShape)for(let t of n.meshes){let n=tv(t.vertices,this.plane);if(n.length<2)continue;let r=nv(n,`end`);if(r)return{direction:r,point:e}}return null}updateTangentFromScene(){if(!this.startPoint||this.tangent)return;let e=this.findTangentAtPoint(this.startPoint);e&&(this.tangent=e)}rebuildPreview(){this.disposePreview();let e=new R(this.plane.normal.x,this.plane.normal.y,this.plane.normal.z);if(this.phase===bv.DRAWING){let e=this.buildModeContext();e&&this.currentMode.rebuildPreview(e)}else if(this.mousePoint&&this.lastSnapType!==`none`){let t=this.lastSnapType===`vertex`?X:P_;Z(this.previewGroup,this.mousePoint,t,this.ctx.camera,e,this.plane,.6)}this.requestRender()}},Cv=class extends T_{id=`bezier`;label=`Bezier`;icon=Hh;activeSourceLocation=null;existingPoles=[];mousePoint=null;lastSnapType=`none`;pendingFirstClick=!1;pendingStart=null;boundMouseDown;boundMouseUp;boundMouseMove;downX=0;downY=0;constructor(e,t,n,r,i,a){super(e,t,n,r),this.boundMouseDown=this.handleMouseDown.bind(this),this.boundMouseUp=this.handleMouseUp.bind(this),this.boundMouseMove=this.handleMouseMove.bind(this)}activate(){this.addPreviewToScene(),this.canvas.addEventListener(`mousedown`,this.boundMouseDown),this.canvas.addEventListener(`mouseup`,this.boundMouseUp),this.canvas.addEventListener(`mousemove`,this.boundMouseMove)}deactivate(){this.canvas.removeEventListener(`mousedown`,this.boundMouseDown),this.canvas.removeEventListener(`mouseup`,this.boundMouseUp),this.canvas.removeEventListener(`mousemove`,this.boundMouseMove),this.activeSourceLocation=null,this.existingPoles=[],this.mousePoint=null,this.lastSnapType=`none`,this.pendingFirstClick=!1,this.pendingStart=null,this.removePreviewFromScene()}handleEscape(){return!1}onSceneUpdate(e,t){let n=n_.fromSceneObjects(e,t,this.plane,this.ctx);if(this.updateSnapManager(n),!this.activeSourceLocation&&!this.pendingFirstClick){this.rebuildPreview();return}let r=null;for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.parentId===t&&i.type===`bezier`){r=i;break}}if(r&&r.sourceLocation){let e=r.object?.startPoint,t=r.object?.resolvedPoints;this.activeSourceLocation=r.sourceLocation,this.existingPoles=e?[e,...t??[]]:[],this.pendingFirstClick=!1,this.pendingStart=null}this.rebuildPreview()}handleMouseDown(e){this.downX=e.clientX,this.downY=e.clientY}handleMouseUp(e){let t=e.clientX-this.downX,n=e.clientY-this.downY;if(t*t+n*n>64||this.pendingFirstClick)return;let r=gp(this.ctx,this.plane,e.clientX,e.clientY);if(!r)return;let i=J(this.snapController.snap(r).point2d);if(!this.activeSourceLocation){this.insertGeometry(`bezier(${this.formatPoint(i)})`),this.pendingFirstClick=!0,this.pendingStart=i,this.rebuildPreview();return}xm(i,this.activeSourceLocation)}handleMouseMove(e){let t=gp(this.ctx,this.plane,e.clientX,e.clientY);if(!t){this.mousePoint=null,this.lastSnapType=`none`,this.rebuildPreview();return}let n=this.snapController.snap(t);this.mousePoint=n.point2d,this.lastSnapType=n.snapType,this.rebuildPreview()}rebuildPreview(){this.disposePreview();let e=this.ctx.camera,t=new R(this.plane.normal.x,this.plane.normal.y,this.plane.normal.z),n=[...this.existingPoles];if(n.length===0&&this.pendingStart&&n.push(this.pendingStart),this.mousePoint&&(this.activeSourceLocation||this.pendingStart)&&n.push(this.mousePoint),n.length>=2){for(let e=1;e<n.length;e++)R_(this.previewGroup,n[e-1],n[e],this.plane);K_(this.previewGroup,n,this.plane)}for(let r=0;r<n.length;r++){let i=r===0?Y:N_,a=r===0?1:.85;Z(this.previewGroup,n[r],i,e,t,this.plane,a)}this.mousePoint&&this.lastSnapType!==`none`&&Z(this.previewGroup,this.mousePoint,L_(this.lastSnapType),e,t,this.plane,.6),this.requestRender()}},wv=3,Tv=24,Ev=6,Dv=25,Ov=class extends T_{id=`polygon`;label=`Polygon`;icon=Bh;centerPoint=null;mousePoint=null;lastSnapType=`none`;expressionInput;fetchVariables;cachedVariables=[];lastClientX=0;lastClientY=0;expressionPhase=`diameter`;diameterExpression=null;lockedDiameter=null;currentSides=Ev;boundMouseDown;boundMouseUp;boundMouseMove;boundKeyDown;downX=0;downY=0;constructor(e,t,n,r,i,a){super(e,t,n,r),this.expressionInput=new M_(i),this.fetchVariables=a,this.boundMouseDown=this.handleMouseDown.bind(this),this.boundMouseUp=this.handleMouseUp.bind(this),this.boundMouseMove=this.handleMouseMove.bind(this),this.boundKeyDown=this.handleKeyDown.bind(this)}activate(){this.addPreviewToScene(),this.canvas.addEventListener(`mousedown`,this.boundMouseDown),this.canvas.addEventListener(`mouseup`,this.boundMouseUp),this.canvas.addEventListener(`mousemove`,this.boundMouseMove),window.addEventListener(`keydown`,this.boundKeyDown),this.fetchVariables().then(e=>{this.cachedVariables=e})}deactivate(){this.canvas.removeEventListener(`mousedown`,this.boundMouseDown),this.canvas.removeEventListener(`mouseup`,this.boundMouseUp),this.canvas.removeEventListener(`mousemove`,this.boundMouseMove),window.removeEventListener(`keydown`,this.boundKeyDown),this.resetState(),this.removePreviewFromScene()}onSceneUpdate(e,t){let n=n_.fromSceneObjects(e,t,this.plane,this.ctx);this.updateSnapManager(n),this.fetchVariables().then(e=>{this.cachedVariables=e})}resetState(){this.centerPoint=null,this.mousePoint=null,this.expressionPhase=`diameter`,this.diameterExpression=null,this.lockedDiameter=null,this.currentSides=Ev,this.expressionInput.hide()}sidesFromDistance(e){if(this.lockedDiameter!==null&&this.lockedDiameter>0){let t=e/(this.lockedDiameter/2);return Math.max(wv,Math.min(Tv,Math.round(t*Ev)))}let t=yp(this.ctx,Dv);return t<=0?Ev:Math.max(wv,Math.min(Tv,Math.round(e/t)))}handleMouseDown(e){this.downX=e.clientX,this.downY=e.clientY}handleMouseUp(e){let t=e.clientX-this.downX,n=e.clientY-this.downY;if(t*t+n*n>64)return;let r=gp(this.ctx,this.plane,e.clientX,e.clientY);if(!r)return;let i=J(this.snapController.snap(r).point2d);if(!this.centerPoint){this.centerPoint=i,this.rebuildPreview();return}if(this.expressionInput.isVisible){this.expressionInput.commitCurrentValue();return}if(this.expressionPhase===`diameter`){let e=Math.round(bp(this.centerPoint,i)*2*100)/100;if(e<=0)return;this.onDiameterCommit({expression:String(e)})}else this.onSidesCommit({expression:String(this.currentSides)})}handleMouseMove(e){this.lastClientX=e.clientX,this.lastClientY=e.clientY;let t=gp(this.ctx,this.plane,e.clientX,e.clientY);if(!t){this.mousePoint=null,this.lastSnapType=`none`,this.rebuildPreview();return}let n=this.snapController.snap(t);if(this.mousePoint=n.point2d,this.lastSnapType=n.snapType,this.centerPoint&&this.expressionPhase===`sides`){let e=bp(this.centerPoint,this.mousePoint);this.currentSides=this.sidesFromDistance(e)}this.rebuildPreview(),this.updateDimensionInput()}handleKeyDown(e){e.key===`Escape`&&this.centerPoint&&(this.resetState(),this.rebuildPreview())}updateDimensionInput(){if(!(!this.centerPoint||!this.mousePoint))if(this.expressionPhase===`diameter`){let e=Math.round(bp(this.centerPoint,this.mousePoint)*2*100)/100;if(e<=0)return;this.expressionInput.isVisible?(this.expressionInput.updateValue(e),this.expressionInput.updatePosition(this.lastClientX,this.lastClientY)):this.expressionInput.show({label:`⌀`,value:String(e),clientX:this.lastClientX,clientY:this.lastClientY,variables:this.cachedVariables,onCommit:e=>this.onDiameterCommit(e)})}else this.expressionInput.isVisible?(this.expressionInput.updateValue(this.currentSides),this.expressionInput.updatePosition(this.lastClientX,this.lastClientY)):this.expressionInput.show({label:`N`,value:String(this.currentSides),clientX:this.lastClientX,clientY:this.lastClientY,variables:this.cachedVariables,onCommit:e=>this.onSidesCommit(e)})}onDiameterCommit(e){let t=parseFloat(e.expression),n=!isNaN(t)&&String(t)===e.expression;this.diameterExpression=e,this.lockedDiameter=n?t:null,this.expressionPhase=`sides`,queueMicrotask(()=>{if(this.mousePoint&&this.centerPoint){let e=bp(this.centerPoint,this.mousePoint);this.currentSides=this.sidesFromDistance(e)}this.expressionInput.show({label:`N`,value:String(this.currentSides),clientX:this.lastClientX,clientY:this.lastClientY,variables:this.cachedVariables,onCommit:e=>this.onSidesCommit(e)}),this.rebuildPreview()})}onSidesCommit(e){!this.centerPoint||!this.diameterExpression||(this.commitPolygon(this.centerPoint,this.diameterExpression,e),this.resetState(),this.rebuildPreview())}commitPolygon(e,t,n){let r=this.isAtCurrentPosition(e)?`polygon(${n.expression}, ${t.expression})`:`polygon(${this.formatPoint(e)}, ${n.expression}, ${t.expression})`,i=n.newVariable??t.newVariable;this.insertGeometry(r,i)}rebuildPreview(){this.disposePreview();let e=this.ctx.camera,t=new R(this.plane.normal.x,this.plane.normal.y,this.plane.normal.z);if(this.centerPoint){if(Z(this.previewGroup,this.centerPoint,Y,e,t,this.plane),this.mousePoint)if(this.expressionPhase===`diameter`){let e=bp(this.centerPoint,this.mousePoint);e>0&&z_(this.previewGroup,this.centerPoint,e,this.plane)}else{let e=this.lockedDiameter===null?bp(this.centerPoint,this.mousePoint):this.lockedDiameter/2;if(e>0&&this.currentSides>=wv){let t=e/Math.cos(Math.PI/this.currentSides);U_(this.previewGroup,this.centerPoint,t,this.currentSides,this.plane)}}}else if(this.mousePoint&&this.lastSnapType!==`none`){let n=this.lastSnapType===`vertex`?X:P_;Z(this.previewGroup,this.mousePoint,n,e,t,this.plane,.6)}this.requestRender()}};function kv(e,t,n,r,i){let a=t.filter(e=>e.parentId===n),o=yp(i,12),s=o*o,c=null,l=1/0;for(let t of a){if(!t.sourceLocation||!up(t.uniqueType))continue;let n=t.uniqueType,i=t.sourceLocation;if(n&&n.startsWith(`bezier-`)){let r=Fv(e,t,i,n,s,l);r&&(c=r.hit,l=r.distSq);continue}if(n===`polygon`){let n=[];for(let e of t.sceneShapes)if(!e.isMetaShape)for(let t of e.meshes){let e=tv(t.vertices,r);for(let t of e)n.push(t)}if(n.length>0){let r=Lv(e,n,i,t,s,l);r&&(c=r.hit,l=r.distSq)}continue}if(n===`slot`){let n=[];for(let e of t.sceneShapes)if(e.isMetaShape){for(let t of e.meshes)if(t.vertices.length===3&&t.indices.length===0){let e=tv(t.vertices,r);e.length===1&&n.push(e[0])}}if(n.length===2){let a=Rv(e,n,i,t,r,s,l);a&&(c=a.hit,l=a.distSq)}continue}if(n===`rect`){let n=[];for(let e of t.sceneShapes)if(!e.isMetaShape)for(let t of e.meshes){let e=tv(t.vertices,r);for(let t of e)n.push(t)}if(n.length>0){let r=Iv(e,n,i,t,s,l);r&&(c=r.hit,l=r.distSq)}continue}for(let a of t.sceneShapes)if(!a.isMetaShape)for(let o of a.meshes){let a=tv(o.vertices,r);if(a.length!==0)if(n===`circle`){let t=Av(e,a,i,s,l);t&&(c=t.hit,l=t.distSq)}else if(n===`line-two-points`||n===`hline`||n===`vline`||n===`tline`){let r=jv(e,a,i,n,t,s,l);r&&(c=r.hit,l=r.distSq)}else if(n===`arc`&&a.length>=3){let n=Nv(e,a,i,t,r,s,l);n&&(c=n.hit,l=n.distSq)}else if((n===`tarc-to-point`||n===`tarc-to-point-tangent`)&&a.length>=2){let o=Pv(e,a,i,n,t,r,s,l);o&&(c=o.hit,l=o.distSq)}else for(let t of a){let r=t[0]-e[0],a=t[1]-e[1],o=r*r+a*a;o<s&&o<l&&(c={sourceLocation:i,uniqueType:n||``,hitZone:`body`},l=o)}}}return c}function Av(e,t,n,r,i){let a=[];for(let e of t){let t=!1;for(let n of a){let r=n[0]-e[0],i=n[1]-e[1];if(r*r+i*i<1e-6){t=!0;break}}t||a.push(e)}let o=0,s=0;for(let e of a)o+=e[0],s+=e[1];o/=a.length,s/=a.length;let c=a[0],l=c[0]-o,u=c[1]-s,d=Math.sqrt(l*l+u*u),f=Math.round(2*d*100)/100,p=null;for(let a of t){let t=a[0]-e[0],c=a[1]-e[1],l=t*t+c*c;l<r&&l<i&&(p={hit:{sourceLocation:n,uniqueType:`circle`,hitZone:`body`,anchorPoint:[o,s],initialValue:f},distSq:l},i=l)}return p}function jv(e,t,n,r,i,a,o){let s=t[0],c=t[t.length-1],l=s[0]-e[0],u=s[1]-e[1],d=l*l+u*u,f=c[0]-e[0],p=c[1]-e[1],m=f*f+p*p,h=r===`hline`||r===`vline`||r===`tline`,g,_;if(r===`tline`){let e=c[0]-s[0],n=c[1]-s[1],r=Math.sqrt(e*e+n*n);if(r>1e-10){if(_=[e/r,n/r],g=r,t.length>=2){let e=t[t.length-2],n=t[t.length-1],r=n[0]-e[0],i=n[1]-e[1],a=Math.sqrt(r*r+i*i);a>1e-10&&(_=[r/a,i/a])}let i=c[0]-s[0],a=c[1]-s[1];g=i*_[0]+a*_[1]}}else (r===`hline`||r===`vline`)&&(g=r===`hline`?c[0]-s[0]:c[1]-s[1]);let v=h?Math.round((g??0)*100)/100:void 0,y=d<a||m<a,b=null;if(m<a&&m<o&&(b={hit:{sourceLocation:n,uniqueType:r||``,hitZone:`end`,anchorPoint:s,fixedVertex:s,initialValue:v,draggedVertices:[c],tangentDir:_},distSq:m},o=m),r!==`tline`&&i.object?.hasExplicitStart===!0&&!(h&&i.object?.centered===!0)&&d<a&&d<o&&(b={hit:{sourceLocation:n,uniqueType:r||``,hitZone:`start`,anchorPoint:s,fixedVertex:c,originalDistance:g,draggedVertices:[s]},distSq:d},o=d),!y&&r===`line-two-points`){let t=mp(e[0],e[1],s[0],s[1],c[0],c[1]),i=t*t;i<a&&i<o&&(b={hit:{sourceLocation:n,uniqueType:r||``,hitZone:`body`,anchorPoint:s,fixedVertex:c,originalDistance:g,initialValue:v,draggedVertices:[s,c]},distSq:i})}return b}function Mv(e,t){for(let n of e.sceneShapes)if(n.isMetaShape){for(let e of n.meshes)if(e.vertices.length===3&&e.indices.length===0){let n=tv(e.vertices,t);if(n.length===1)return n[0]}}return null}function Nv(e,t,n,r,i,a,o){let s=t[0],c=t[t.length-1],l=r.object?.startPoint!==void 0,u=l?3:2,d=Mv(r,i);if(!d){let e=t[Math.floor(t.length/2)];d=Z_(s,e,c)}if(!d)return null;let f=t[Math.floor(t.length/2)],p=Q_(d,s,f),m=s[0]-e[0],h=s[1]-e[1],g=m*m+h*h,_=c[0]-e[0],v=c[1]-e[1],y=_*_+v*v,b=d[0]-e[0],x=d[1]-e[1],S=b*b+x*x,C=Math.min(g,y,S),w=null;return l&&g<a&&g<o&&g===C&&(w={hit:{sourceLocation:n,uniqueType:`arc`,hitZone:`start`,anchorPoint:d,fixedVertex:c,draggedVertices:[s],arcCCW:p,arcArgCount:u},distSq:g},o=g),y<a&&y<o&&y===C&&(w={hit:{sourceLocation:n,uniqueType:`arc`,hitZone:`end`,anchorPoint:d,fixedVertex:s,draggedVertices:[c],arcCCW:p,arcArgCount:u},distSq:y},o=y),S<a&&S<o&&S===C&&(w={hit:{sourceLocation:n,uniqueType:`arc`,hitZone:`center`,anchorPoint:d,fixedVertex:s,fixedVertex2:c,draggedVertices:[d],arcCCW:p,arcArgCount:u},distSq:S}),w}function Pv(e,t,n,r,i,a,o,s){let c=t[0],l=t[t.length-1],u=t[1][0]-c[0],d=t[1][1]-c[1],f=Math.sqrt(u*u+d*d),p=f>1e-10?[u/f,d/f]:[1,0],m=Mv(i,a);if(!m){let e=t[Math.floor(t.length/2)];m=Z_(c,e,l)}let h=t[Math.floor(t.length/2)],g=m?Q_(m,c,h):!0,_=l[0]-e[0],v=l[1]-e[1],y=_*_+v*v,b=null;if(y<o&&y<s&&(b={hit:{sourceLocation:n,uniqueType:r||``,hitZone:`end`,anchorPoint:c,fixedVertex:c,draggedVertices:[l],tangentDir:p,arcCCW:g},distSq:y},s=y),m){let t=m[0]-e[0],i=m[1]-e[1],a=t*t+i*i;a<o&&a<s&&(b={hit:{sourceLocation:n,uniqueType:r||``,hitZone:`center`,anchorPoint:c,fixedVertex:c,fixedVertex2:l,draggedVertices:[m],tangentDir:p,arcCCW:g},distSq:a})}return b}function Fv(e,t,n,r,i,a){let o=t.object?.startPoint,s=t.object?.resolvedPoints??[],c=o?[o,...s]:s;if(c.length===0)return null;let l=null;for(let t=0;t<c.length;t++){let o=c[t],s=o[0]-e[0],u=o[1]-e[1],d=s*s+u*u;d<i&&d<a&&(l={hit:{sourceLocation:n,uniqueType:r,hitZone:`end`,anchorPoint:o,draggedVertices:[o],bezierPoleIndex:t,bezierPoles:c},distSq:d},a=d)}return l}function Iv(e,t,n,r,i,a){if(r.object?.radius)return null;let o=[];for(let e of t){let t=!1;for(let n of o){let r=n[0]-e[0],i=n[1]-e[1];if(r*r+i*i<1e-6){t=!0;break}}t||o.push(e)}if(o.length<4)return null;let s=r.object?.centered===!0,c;if(s){let e=0,t=0;for(let n of o)e+=n[0],t+=n[1];c=[e/o.length,t/o.length]}let l=null;for(let t of o){let r=t[0]-e[0],u=t[1]-e[1],d=r*r+u*u;if(d<i&&d<a){let e;if(s&&c)e=c;else{let n=-1;e=o[0];for(let r of o){let i=r[0]-t[0],a=r[1]-t[1],o=i*i+a*a;o>n&&(n=o,e=r)}}l={hit:{sourceLocation:n,uniqueType:`rect`,hitZone:`end`,anchorPoint:e,fixedVertex:e,draggedVertices:[t],rectCentered:s},distSq:d},a=d}}return l}function Lv(e,t,n,r,i,a){let o=[];for(let e of t){let t=!1;for(let n of o){let r=n[0]-e[0],i=n[1]-e[1];if(r*r+i*i<1e-6){t=!0;break}}t||o.push(e)}let s=0,c=0;for(let e of o)s+=e[0],c+=e[1];s/=o.length,c/=o.length;let l=o[0],u=l[0]-s,d=l[1]-c,f=Math.sqrt(u*u+d*d),p=r.object?.numberOfSides??o.length,m=r.object?.diameter??Math.round(2*f*100)/100,h=null;for(let r of t){let t=r[0]-e[0],o=r[1]-e[1],l=t*t+o*o;l<i&&l<a&&(h={hit:{sourceLocation:n,uniqueType:`polygon`,hitZone:`body`,anchorPoint:[s,c],initialValue:m,originalDistance:f,polygonSides:p},distSq:l},a=l)}return h}function Rv(e,t,n,r,i,a,o){let s=t[0],c=t[1],l=r.object?.hasTwoPoints??!1,u=r.object?.radius??0,d=c[0]-s[0],f=c[1]-s[1],p=Math.sqrt(d*d+f*f),m;if(l)m=p>1e-10?[d/p,f/p]:[1,0];else{let e=(r.object?.angle??0)*Math.PI/180;m=[Math.cos(e),Math.sin(e)]}let h={sourceLocation:n,uniqueType:`slot`,initialValue:u,slotHasTwoPoints:l,slotAxisDir:m,slotRadius:u};function g(){return{...h,hitZone:`start`,anchorPoint:s,fixedVertex:c,slotOtherCenter:c,slotPointIndex:0,draggedVertices:[s]}}function _(){return{...h,hitZone:`end`,anchorPoint:c,fixedVertex:s,slotOtherCenter:s,slotPointIndex:1,draggedVertices:[c]}}let v=null,y=s[0]-e[0],b=s[1]-e[1],x=y*y+b*b,S=c[0]-e[0],C=c[1]-e[1],w=S*S+C*C;x<a&&x<o&&x<=w&&(v={hit:g(),distSq:x},o=x),w<a&&w<o&&(v={hit:_(),distSq:w},o=w);for(let t of r.sceneShapes)if(!t.isMetaShape)for(let n of t.meshes){let t=tv(n.vertices,i);for(let n of t){let t=n[0]-e[0],r=n[1]-e[1],i=t*t+r*r;i<a&&i<o&&(v={hit:{...h,hitZone:`body`,anchorPoint:s,fixedVertex:c,slotOtherCenter:c,slotRadius:u},distSq:i},o=i)}}return v}function zv(e,t,n){let r=(t[0]+n[0])/2,i=(t[1]+n[1])/2,a=n[0]-t[0],o=-(n[1]-t[1]),s=a,c=o*o+s*s;if(c<1e-10)return e;let l=((e[0]-r)*o+(e[1]-i)*s)/c;return[r+l*o,i+l*s]}function Bv(e,t,n){let r=-n[1],i=n[0],a=(e[0]-t[0])*r+(e[1]-t[1])*i;return[t[0]+a*r,t[1]+a*i]}function Vv(e,t,n){let r=-n[1],i=n[0],a=e[0]-t[0],o=e[1]-t[1],s=a*a+o*o,c=a*r+o*i;if(Math.abs(c)<1e-10)return null;let l=-s/(2*c),u=Math.abs(l),d=[e[0]+r*l,e[1]+i*l];return{center:d,radius:u,startAngle:Y_(d,e),endAngle:Y_(d,t),ccw:l>=0}}function Hv(e,t,n){let r=(t[0]+n[0])/2,i=(t[1]+n[1])/2,a=n[0]-t[0],o=-(n[1]-t[1]),s=a,c=o*o+s*s;if(c<1e-10)return e;let l=e[0]-r,u=e[1]-i,d=(l*o+u*s)/c;return[r+d*o,i+d*s]}var Q=5;function Uv(e,t,n,r,i,a){let o=new R(a.normal.x,a.normal.y,a.normal.z),{uniqueType:s,hitZone:c,anchorPoint:l,fixedVertex:u}=r;if(s===`polygon`&&l&&r.polygonSides){let n=l,s=t[0]-n[0],c=t[1]-n[1],u=Math.sqrt(s*s+c*c);Z(e,n,Y,i,o,a,1,Q),U_(e,n,u,r.polygonSides,a,Q),Z(e,t,X,i,o,a,1,Q)}else if(s===`circle`&&l){let n=l,r=t[0]-n[0],s=t[1]-n[1],c=Math.sqrt(r*r+s*s);Z(e,n,Y,i,o,a,1,Q),z_(e,n,c,a,Q)}else if(s===`tline`&&l&&r.tangentDir){let n=l,s=r.tangentDir,c=t[0]-n[0],u=t[1]-n[1],d=c*s[0]+u*s[1],f=[n[0]+s[0]*d,n[1]+s[1]*d];Z(e,n,Y,i,o,a,1,Q),R_(e,n,f,a,Q),Z(e,f,X,i,o,a,1,Q)}else if(s===`hline`||s===`vline`)if(c===`end`){let n=l,r=s===`hline`?[t[0],n[1]]:[n[0],t[1]];Z(e,n,Y,i,o,a,1,Q),R_(e,n,r,a,Q),Z(e,r,X,i,o,a,1,Q)}else{let n=r.originalDistance??0,c=s===`hline`?[t[0]+n,t[1]]:[t[0],t[1]+n];Z(e,t,Y,i,o,a,1,Q),R_(e,t,c,a,Q),Z(e,c,X,i,o,a,1,Q)}else if(s===`line-two-points`&&u&&l)if(c===`body`){let n=u[0]-l[0],r=u[1]-l[1],s=[t[0]+n,t[1]+r];Z(e,t,Y,i,o,a,1,Q),R_(e,t,s,a,Q),Z(e,s,X,i,o,a,1,Q)}else c===`start`?(Z(e,t,X,i,o,a,1,Q),R_(e,t,u,a,Q),Z(e,u,Y,i,o,a,1,Q)):(Z(e,u,Y,i,o,a,1,Q),R_(e,u,t,a,Q),Z(e,t,X,i,o,a,1,Q));else if(s===`arc`&&l&&u)Wv(e,t,r,i,o,a);else if(s===`rect`&&l)if(r.rectCentered){let n=[2*l[0]-t[0],2*l[1]-t[1]];Z(e,l,Y,i,o,a,1,Q),B_(e,n,t,a,Q),Z(e,t,X,i,o,a,1,Q)}else Z(e,l,Y,i,o,a,1,Q),B_(e,l,t,a,Q),Z(e,t,X,i,o,a,1,Q);else if(s===`slot`&&r.slotRadius!==void 0)if(c===`body`){let n=l,s=u,c=r.slotAxisDir?.[0]??1,d=r.slotAxisDir?.[1]??0,f=t[0]-n[0],p=t[1]-n[1],m=Math.abs(-d*f+c*p);Z(e,n,Y,i,o,a,1,Q),Z(e,s,Y,i,o,a,1,Q),m>0?J_(e,n,s,m,a,Q):R_(e,n,s,a,Q),Z(e,t,X,i,o,a,1,Q)}else{let n=r.slotOtherCenter,s=r.slotRadius,l=c===`start`?t:n,u=c===`start`?n:t;Z(e,n,Y,i,o,a,1,Q),s>0?J_(e,l,u,s,a,Q):R_(e,l,u,a,Q),Z(e,t,X,i,o,a,1,Q)}else if((s===`tarc-to-point`||s===`tarc-to-point-tangent`)&&u&&r.tangentDir)Gv(e,t,r,i,o,a);else if(s.startsWith(`bezier-`)&&r.bezierPoles&&r.bezierPoleIndex!==void 0){let n=r.bezierPoles.slice();n[r.bezierPoleIndex]=t;for(let t=1;t<n.length;t++)R_(e,n[t-1],n[t],a,Q);K_(e,n,a,Q);for(let t=0;t<n.length;t++)t!==r.bezierPoleIndex&&Z(e,n[t],N_,i,o,a,.85,Q);Z(e,t,X,i,o,a,1,Q)}else Z(e,t,X,i,o,a,1,Q),n&&R_(e,n,t,a,Q)}function Wv(e,t,n,r,i,a){let{hitZone:o,anchorPoint:s,fixedVertex:c}=n,l=n.arcCCW!==!1;if(o===`center`){let o=c,s=n.fixedVertex2,u=t,d=Math.sqrt((o[0]-u[0])**2+(o[1]-u[1])**2),f=Y_(u,o),p=Y_(u,s),m=[u[0]+d*Math.cos(p),u[1]+d*Math.sin(p)];Z(e,o,Y,r,i,a,1,Q),W_(e,u,d,f,p,l,a,Q),Z(e,m,Y,r,i,a,1,Q),Z(e,u,X,r,i,a,1,Q)}else{let n=Hv(s,c,t),u=Math.sqrt((t[0]-n[0])**2+(t[1]-n[1])**2);if(o===`start`){let o=Y_(n,t),s=Y_(n,c);Z(e,t,X,r,i,a,1,Q),W_(e,n,u,o,s,l,a,Q),Z(e,c,Y,r,i,a,1,Q)}else{let o=Y_(n,c),s=Y_(n,t);Z(e,c,Y,r,i,a,1,Q),W_(e,n,u,o,s,l,a,Q),Z(e,t,X,r,i,a,1,Q)}}}function Gv(e,t,n,r,i,a){let{hitZone:o,fixedVertex:s,tangentDir:c}=n,l=s,u=c;if(o===`center`){let o=t,s=n.fixedVertex2,c=Math.sqrt((l[0]-o[0])**2+(l[1]-o[1])**2),u=Y_(o,l),d=Y_(o,s),f=n.arcCCW!==!1,p=[o[0]+c*Math.cos(d),o[1]+c*Math.sin(d)];Z(e,l,Y,r,i,a,1,Q),W_(e,o,c,u,d,f,a,Q),Z(e,p,Y,r,i,a,1,Q),Z(e,o,X,r,i,a,1,Q)}else{let n=Vv(l,t,u);n?(Z(e,l,Y,r,i,a,1,Q),W_(e,n.center,n.radius,n.startAngle,n.endAngle,n.ccw,a,Q),Z(e,t,X,r,i,a,1,Q)):(Z(e,l,Y,r,i,a,1,Q),R_(e,l,t,a,Q),Z(e,t,X,r,i,a,1,Q))}}function Kv(e){for(;e.children.length>0;){let t=e.children[0];e.remove(t);let n=t;n.geometry&&n.geometry.dispose(),n.material&&n.material.dispose()}}function qv(e,t,n){let r=J(e),{sourceLocation:i,uniqueType:a,hitZone:o,anchorPoint:s,fixedVertex:c}=t;if(a===`line-two-points`&&o===`body`&&s&&c){let e=c[0]-s[0],t=c[1]-s[1];Em(r,J([r[0]+e,r[1]+t]),i);return}if(a===`line-two-points`)Dm(r,i,o===`start`?0:-1);else if(a===`arc`&&s&&c){let e=t.arcArgCount===2,n=+!e,a=e?1:2;if(o===`center`){let e=c,o=t.fixedVertex2,s=Math.sqrt((e[0]-r[0])**2+(e[1]-r[1])**2),l=Math.atan2(o[1]-r[1],o[0]-r[0]);Om([{pointIndex:n,position:J([r[0]+s*Math.cos(l),r[1]+s*Math.sin(l)])},{pointIndex:a,position:r}],i)}else{let e=J(Hv(s,c,r));Om([{pointIndex:o===`start`?0:n,position:r},{pointIndex:a,position:e}],i)}}else if((a===`hline`||a===`vline`)&&(o===`start`||o===`body`))Dm(r,i,0);else if(a===`tline`&&o===`end`&&s&&t.tangentDir){let e=t.tangentDir,a=r[0]-s[0],o=r[1]-s[1],c=Math.round((a*e[0]+o*e[1])*100)/100,l=n();Am(String(c),i,l)}else if(a===`polygon`&&s&&t.originalDistance&&t.initialValue){let e=r[0]-s[0],a=r[1]-s[1],o=Math.sqrt(e*e+a*a),c=Math.round(t.initialValue*o/t.originalDistance*100)/100,l=n();Am(String(c),i,l)}else if(a===`rect`&&s)if(t.rectCentered)km(Math.round(Math.abs(r[0]-s[0])*2*100)/100,Math.round(Math.abs(r[1]-s[1])*2*100)/100,i);else{let e=Math.min(s[0],r[0]),t=Math.min(s[1],r[1]);km(Math.round(Math.abs(r[0]-s[0])*100)/100,Math.round(Math.abs(r[1]-s[1])*100)/100,i,J([e,t]))}else if(a===`tarc-to-point`||a===`tarc-to-point-tangent`){let e=a===`tarc-to-point`?0:1;if(o===`center`&&c&&t.fixedVertex2){let n=c,a=t.fixedVertex2,o=Math.sqrt((n[0]-r[0])**2+(n[1]-r[1])**2),s=Math.atan2(a[1]-r[1],a[0]-r[0]);Dm(J([r[0]+o*Math.cos(s),r[1]+o*Math.sin(s)]),i,e)}else Dm(r,i,e)}else if(a===`slot`){if(o===`body`){let e=t.anchorPoint,a=t.slotAxisDir?.[0]??1,o=t.slotAxisDir?.[1]??0,s=r[0]-e[0],c=r[1]-e[1],l=Math.round(Math.abs(-o*s+a*c)*100)/100,u=n();Am(String(l),i,u)}else if(t.slotHasTwoPoints)Dm(r,i,t.slotPointIndex??0);else if(o===`start`)Dm(r,i,0);else if(t.slotOtherCenter&&t.slotAxisDir){let e=t.slotOtherCenter,a=t.slotAxisDir,o=r[0]-e[0],s=r[1]-e[1],c=Math.round((o*a[0]+s*a[1])*100)/100,l=n();Am(String(c),i,l,void 0,1)}}else a.startsWith(`bezier-`)&&t.bezierPoleIndex!==void 0?Dm(r,i,t.bezierPoleIndex):Dm(r,i)}var Jv=class{expressionInput;fetchVariables;getSketchSourceLine;cachedVariables=[];standaloneInputActive=!1;onRequestEndResize=null;onRequestCloseStandalone=null;constructor(e,t,n){this.expressionInput=new M_(e),this.fetchVariables=t,this.getSketchSourceLine=n}get isVisible(){return this.expressionInput.isVisible}containsElement(e){return this.expressionInput.containsElement(e)}refreshVariables(){return this.fetchVariables().then(e=>{this.cachedVariables=e})}showForDrag(e,t,n,r){let{uniqueType:i,hitZone:a}=e,o=null,s=0;if(i===`polygon`){o=`⌀`;let n=e.anchorPoint,r=t[0]-n[0],i=t[1]-n[1],a=Math.sqrt(r*r+i*i);s=e.originalDistance&&e.initialValue?Math.round(e.initialValue*a/e.originalDistance*100)/100:Math.round(2*a*100)/100}else if(i===`circle`){o=`⌀`;let n=e.anchorPoint,r=t[0]-n[0],i=t[1]-n[1];s=Math.round(2*Math.sqrt(r*r+i*i)*100)/100}else if((i===`hline`||i===`vline`)&&a===`end`){o=i===`hline`?`H:`:`V:`;let n=e.anchorPoint;s=i===`hline`?Math.round(Math.abs(t[0]-n[0])*100)/100:Math.round(Math.abs(t[1]-n[1])*100)/100}else if(i===`tline`&&a===`end`&&e.tangentDir){o=`T:`;let n=e.anchorPoint,r=e.tangentDir,i=t[0]-n[0],a=t[1]-n[1];s=Math.round(Math.abs(i*r[0]+a*r[1])*100)/100}else if(i===`slot`&&!e.slotHasTwoPoints&&e.slotOtherCenter&&e.slotAxisDir&&a===`end`){o=`D`;let n=e.slotOtherCenter,r=e.slotAxisDir,i=t[0]-n[0],a=t[1]-n[1];s=Math.round((i*r[0]+a*r[1])*100)/100}else if(i===`slot`&&a===`body`){o=`R`;let n=e.anchorPoint,r=t[0]-n[0],i=t[1]-n[1];s=Math.round(Math.sqrt(r*r+i*i)*100)/100}o!==null&&this.openInput(o,s,e,n,r,!0)}showForDoubleClick(e,t,n){let r,i;if(e.uniqueType===`polygon`||e.uniqueType===`circle`)r=`⌀`,i=e.initialValue??0;else if(e.uniqueType===`hline`||e.uniqueType===`vline`)r=e.uniqueType===`hline`?`H:`:`V:`,i=Math.abs(e.initialValue??0);else if(e.uniqueType===`tline`)r=`T:`,i=Math.abs(e.initialValue??0);else if(e.uniqueType===`slot`)if(e.hitZone===`start`||e.hitZone===`end`){if(e.slotHasTwoPoints)return!1;r=`D`;let t=e.anchorPoint,n=e.fixedVertex,a=e.slotAxisDir??[1,0];i=Math.round(((n[0]-t[0])*a[0]+(n[1]-t[1])*a[1])*100)/100}else r=`R`,i=e.slotRadius??0;else return!1;return this.standaloneInputActive=!0,this.openInput(r,i,e,t,n,!1),!0}updateValue(e,t){if(!this.expressionInput.isVisible)return;let{uniqueType:n,anchorPoint:r}=e,i;if(n===`polygon`){let n=r,a=t[0]-n[0],o=t[1]-n[1],s=Math.sqrt(a*a+o*o);i=e.originalDistance&&e.initialValue?Math.round(e.initialValue*s/e.originalDistance*100)/100:Math.round(2*s*100)/100}else if(n===`circle`){let e=r,n=t[0]-e[0],a=t[1]-e[1];i=Math.round(2*Math.sqrt(n*n+a*a)*100)/100}else if(n===`tline`&&e.tangentDir){let n=r,a=e.tangentDir,o=t[0]-n[0],s=t[1]-n[1];i=Math.round(Math.abs(o*a[0]+s*a[1])*100)/100}else if(n===`slot`&&e.hitZone===`body`){let n=r,a=e.slotAxisDir?.[0]??1,o=e.slotAxisDir?.[1]??0,s=t[0]-n[0],c=t[1]-n[1];i=Math.round(Math.abs(-o*s+a*c)*100)/100}else if(n===`slot`&&e.slotOtherCenter&&e.slotAxisDir){let n=e.slotOtherCenter,r=e.slotAxisDir,a=t[0]-n[0],o=t[1]-n[1];i=Math.round((a*r[0]+o*r[1])*100)/100}else{let e=r,a=n===`hline`?t[0]-e[0]:t[1]-e[1];i=Math.round(Math.abs(a)*100)/100}this.expressionInput.updateValue(i)}updatePosition(e,t){this.expressionInput.updatePosition(e,t)}updateValueIfUnmoved(e){this.expressionInput.updateValue(e)}commitIfVisible(e){this.expressionInput.isVisible&&e&&this.expressionInput.commitCurrentValue()}hide(){this.expressionInput.hide()}closeStandalone(){this.standaloneInputActive&&(this.standaloneInputActive=!1,this.expressionInput.hide())}openInput(e,t,n,r,i,a){let{sourceLocation:o}=n,s=String(t);this.expressionInput.show({label:e,value:s,clientX:r,clientY:i,variables:this.cachedVariables,onCommit:t=>{let{expression:r,newVariable:i}=t,s=parseFloat(r),c=!isNaN(s)&&String(s)===r,l=r;if(c&&n.uniqueType!==`circle`&&n.uniqueType!==`polygon`&&n.uniqueType!==`slot`){let e=this.computeDistanceSign(n,null);l=String(Math.round(e*s*100)/100)}else c&&(l=String(Math.round(s*100)/100));let u=this.getSketchSourceLine();Am(l,o,u,i,+(e===`D`)),a?this.onRequestEndResize?.():this.closeStandalone()}}),e!==`D`&&jm(o.line).then(({expression:e})=>{e&&(a||this.standaloneInputActive)&&this.updateValueIfUnmoved(e)})}computeDistanceSign(e,t){if(t){let n=e.anchorPoint;if(e.uniqueType===`tline`&&e.tangentDir){let r=e.tangentDir,i=t[0]-n[0],a=t[1]-n[1];return i*r[0]+a*r[1]>=0?1:-1}return e.uniqueType===`hline`?t[0]>=n[0]?1:-1:t[1]>=n[1]?1:-1}return(e.initialValue??e.originalDistance??0)>=0?1:-1}},Yv=class{ctx;plane;snapController;sceneObjects=[];sketchId=``;canvas;previewGroup;_isResizing=!1;hasMoved=!1;hitResult=null;startPoint=null;currentPoint=null;grabOffset=null;pendingHit=null;dimensionInput;getSketchSourceLine;boundCanvasPointerDown;boundPointerMove;boundPointerUp;boundKeyDown;boundCanvasDoubleClick;constructor(e,t,n,r,i,a){this.ctx=e,this.plane=t,this.snapController=n,this.canvas=e.renderer.domElement,this.getSketchSourceLine=a,this.previewGroup=new si,this.previewGroup.userData.isMetaShape=!0,this.previewGroup.renderOrder=5,this.dimensionInput=new Jv(r,i,a),this.dimensionInput.onRequestEndResize=()=>this.endResize(),this.dimensionInput.onRequestCloseStandalone=()=>{this.dimensionInput.closeStandalone(),this.hitResult=null},this.boundCanvasPointerDown=this.handleCanvasPointerDown.bind(this),this.boundPointerMove=this.handlePointerMove.bind(this),this.boundPointerUp=this.handlePointerUp.bind(this),this.boundKeyDown=this.handleKeyDown.bind(this),this.boundCanvasDoubleClick=this.handleCanvasDoubleClick.bind(this)}get isResizing(){return this._isResizing}activate(){this.ctx.scene.add(this.previewGroup),this.canvas.addEventListener(`pointerdown`,this.boundCanvasPointerDown,{capture:!0}),this.canvas.addEventListener(`dblclick`,this.boundCanvasDoubleClick),window.addEventListener(`pointermove`,this.boundPointerMove),window.addEventListener(`pointerup`,this.boundPointerUp,{capture:!0}),window.addEventListener(`keydown`,this.boundKeyDown)}deactivate(){this.canvas.removeEventListener(`pointerdown`,this.boundCanvasPointerDown,{capture:!0}),this.canvas.removeEventListener(`dblclick`,this.boundCanvasDoubleClick),window.removeEventListener(`pointermove`,this.boundPointerMove),window.removeEventListener(`pointerup`,this.boundPointerUp,{capture:!0}),window.removeEventListener(`keydown`,this.boundKeyDown),this.endResize(),this.dimensionInput.closeStandalone(),this.pendingHit=null,this.ctx.scene.remove(this.previewGroup),Kv(this.previewGroup)}updatePlane(e){this.plane=e}updateSnapController(e){this.snapController=e,this._isResizing&&this.hitResult?.draggedVertices&&this.snapController.setExcludedVertices(this.hitResult.draggedVertices)}updateSceneData(e,t){this.sceneObjects=e,this.sketchId=t,this.dimensionInput.refreshVariables()}handleCanvasPointerDown(e){if(e.button!==0||this._isResizing||this.dimensionInput.standaloneInputActive&&this.dimensionInput.containsElement(e.target))return;let t=gp(this.ctx,this.plane,e.clientX,e.clientY);if(!t)return;let n=kv(t,this.sceneObjects,this.sketchId,this.plane,this.ctx);n&&(this.pendingHit={hit:n,point2d:t,clientX:e.clientX,clientY:e.clientY},this.ctx.cameraControls.enabled=!1,e.stopPropagation())}handlePointerUp(e){if(e.button===0){if(this._isResizing){this.commitResize(),e.stopPropagation(),e.preventDefault();return}this.pendingHit&&(this.pendingHit=null,this.ctx.cameraControls.enabled=!0)}}startResize(e){this._isResizing=!0,this.hasMoved=!1,this.hitResult=e.hit,this.startPoint=e.point2d,this.currentPoint=e.point2d;let t=e.hit;t.hitZone===`body`&&t.anchorPoint&&(t.uniqueType===`hline`||t.uniqueType===`vline`||t.uniqueType===`line-two-points`)?this.grabOffset=[e.point2d[0]-t.anchorPoint[0],e.point2d[1]-t.anchorPoint[1]]:this.grabOffset=null,this.ctx.cameraControls.enabled=!1,this.canvas.style.cursor=`crosshair`,this.snapController.setExcludedVertices(t.draggedVertices??[]),this.dimensionInput.showForDrag(t,e.point2d,e.clientX,e.clientY)}commitResize(){this.dimensionInput.isVisible&&this.hasMoved?this.dimensionInput.commitIfVisible(this.hasMoved):this.currentPoint&&this.hitResult&&qv(this.currentPoint,this.hitResult,this.getSketchSourceLine),this.endResize()}handleKeyDown(e){e.key===`Escape`&&(this._isResizing?this.endResize():this.dimensionInput.standaloneInputActive&&(this.dimensionInput.closeStandalone(),this.hitResult=null))}handlePointerMove(e){if(this.pendingHit&&!this._isResizing){let t=e.clientX-this.pendingHit.clientX,n=e.clientY-this.pendingHit.clientY;if(t*t+n*n>=16){let e=this.pendingHit;this.pendingHit=null,this.startResize(e)}else return}if(!this._isResizing)return;let t=gp(this.ctx,this.plane,e.clientX,e.clientY);if(t){if(this.hasMoved=!0,this.grabOffset&&this.hitResult?.hitZone===`body`){let e=[t[0]-this.grabOffset[0],t[1]-this.grabOffset[1]];this.currentPoint=this.snapController.snap(e).point2d}else this.currentPoint=this.snapController.snap(t).point2d;if(this.hitResult?.hitZone===`start`&&this.hitResult.anchorPoint&&(this.hitResult.uniqueType===`hline`||this.hitResult.uniqueType===`vline`)&&(this.hitResult.uniqueType===`hline`?this.currentPoint=[this.currentPoint[0],this.hitResult.anchorPoint[1]]:this.currentPoint=[this.hitResult.anchorPoint[0],this.currentPoint[1]]),this.hitResult?.uniqueType===`tline`&&this.hitResult.hitZone===`end`&&this.hitResult.anchorPoint&&this.hitResult.tangentDir){let e=this.hitResult.anchorPoint,t=this.hitResult.tangentDir,n=this.currentPoint[0]-e[0],r=this.currentPoint[1]-e[1],i=n*t[0]+r*t[1];this.currentPoint=[e[0]+t[0]*i,e[1]+t[1]*i]}if(this.hitResult?.hitZone===`center`&&this.hitResult.uniqueType===`arc`&&this.hitResult.fixedVertex&&this.hitResult.fixedVertex2&&e.shiftKey&&(this.currentPoint=zv(this.currentPoint,this.hitResult.fixedVertex,this.hitResult.fixedVertex2)),this.hitResult?.hitZone===`center`&&this.hitResult.tangentDir&&this.hitResult.fixedVertex&&(this.currentPoint=Bv(this.currentPoint,this.hitResult.fixedVertex,this.hitResult.tangentDir)),this.hitResult?.uniqueType===`slot`&&!this.hitResult.slotHasTwoPoints&&(this.hitResult.hitZone===`start`||this.hitResult.hitZone===`end`)&&this.hitResult.slotAxisDir&&this.hitResult.slotOtherCenter){let e=this.hitResult.slotAxisDir,t=this.hitResult.slotOtherCenter,n=this.currentPoint[0]-t[0],r=this.currentPoint[1]-t[1],i=n*e[0]+r*e[1];this.currentPoint=[t[0]+e[0]*i,t[1]+e[1]*i]}Kv(this.previewGroup),this.currentPoint&&this.hitResult&&Uv(this.previewGroup,this.currentPoint,this.startPoint,this.hitResult,this.ctx.camera,this.plane),this.ctx.requestRender(),this.currentPoint&&this.hitResult&&this.dimensionInput.updateValue(this.hitResult,this.currentPoint),this.dimensionInput.updatePosition(e.clientX,e.clientY)}}handleCanvasDoubleClick(e){if(this._isResizing)return;let t=gp(this.ctx,this.plane,e.clientX,e.clientY);if(!t)return;let n=kv(t,this.sceneObjects,this.sketchId,this.plane,this.ctx);n&&n.uniqueType!==`line-two-points`&&(this.hitResult=n,this.startPoint=null,this.currentPoint=null,this.dimensionInput.showForDoubleClick(n,e.clientX,e.clientY)||(this.hitResult=null))}endResize(){this._isResizing=!1,this.hasMoved=!1,this.hitResult=null,this.startPoint=null,this.currentPoint=null,this.grabOffset=null,this.pendingHit=null,this.ctx.cameraControls.enabled=!0,this.canvas.style.cursor=``,this.snapController.setExcludedVertices([]),this.dimensionInput.hide(),Kv(this.previewGroup),this.ctx.requestRender()}},Xv=12,Zv=2,Qv=6,$v=class{ctx;plane;canvas;edges=[];centers=[];hoveredShapeId=null;hoveredCenterOverlay=null;hoveredCenterPoint=null;selectedShapeIds=new Set;isExternalResizing;boundMouseMove;boundMouseDown;boundMouseUp;downX=0;downY=0;constructor(e,t,n){this.ctx=e,this.plane=t,this.canvas=e.renderer.domElement,this.isExternalResizing=n,this.boundMouseMove=this.handleMouseMove.bind(this),this.boundMouseDown=this.handleMouseDown.bind(this),this.boundMouseUp=this.handleMouseUp.bind(this)}activate(){this.canvas.addEventListener(`mousemove`,this.boundMouseMove),this.canvas.addEventListener(`mousedown`,this.boundMouseDown),this.canvas.addEventListener(`mouseup`,this.boundMouseUp)}deactivate(){this.canvas.removeEventListener(`mousemove`,this.boundMouseMove),this.canvas.removeEventListener(`mousedown`,this.boundMouseDown),this.canvas.removeEventListener(`mouseup`,this.boundMouseUp),this.clearHover(),this.clearSelection(),this.removeCenterOverlay()}updatePlane(e){this.plane=e}updateSceneData(e,t){this.edges=dp(e,t,this.plane),this.centers=pp(e,t,this.plane);let n=new Set(this.edges.map(e=>e.shapeId));for(let e of this.centers)n.add(e.shapeId);this.hoveredShapeId&&!n.has(this.hoveredShapeId)&&this.clearHover();for(let e of this.selectedShapeIds)n.has(e)||(this.removeSelectionHighlight(e),this.selectedShapeIds.delete(e))}get selectedIds(){return this.selectedShapeIds}handleMouseDown(e){this.downX=e.clientX,this.downY=e.clientY}handleMouseMove(e){if(this.isExternalResizing()){this.hoveredShapeId&&this.clearHover();return}let t=gp(this.ctx,this.plane,e.clientX,e.clientY);if(!t){this.hoveredShapeId&&this.clearHover();return}let n=yp(this.ctx,Xv),r=this.findNearestEdge(t,n),i=r?.shapeId??null;i!==this.hoveredShapeId&&(this.hoveredShapeId&&this.removeHoverHighlight(this.hoveredShapeId),this.removeCenterOverlay(),i?(this.applyHoverHighlight(i),this.canvas.style.cursor=`pointer`):this.canvas.style.cursor=``,this.hoveredShapeId=i,this.ctx.requestRender()),r?.isCenter&&r.centerPoint?this.hoveredCenterPoint&&this.hoveredCenterPoint[0]===r.centerPoint[0]&&this.hoveredCenterPoint[1]===r.centerPoint[1]||(this.removeCenterOverlay(),this.addCenterOverlay(r.centerPoint),this.hoveredCenterPoint=r.centerPoint,this.ctx.requestRender()):this.hoveredCenterOverlay&&(this.removeCenterOverlay(),this.ctx.requestRender())}handleMouseUp(e){if(this.isExternalResizing())return;let t=e.clientX-this.downX,n=e.clientY-this.downY;if(t*t+n*n>64)return;let r=e.ctrlKey||e.metaKey;if(!this.hoveredShapeId){r||(this.clearSelection(),this.ctx.requestRender());return}r?this.selectedShapeIds.has(this.hoveredShapeId)?(this.removeSelectionHighlight(this.hoveredShapeId),this.selectedShapeIds.delete(this.hoveredShapeId),this.applyHoverHighlight(this.hoveredShapeId)):(this.selectedShapeIds.add(this.hoveredShapeId),this.applySelectionHighlight(this.hoveredShapeId)):(this.clearSelection(),this.selectedShapeIds.add(this.hoveredShapeId),this.applySelectionHighlight(this.hoveredShapeId)),this.ctx.requestRender()}findNearestEdge(e,t){let n=1/0,r=null,i=!1,a=null;for(let t of this.edges)for(let o of t.segments){let s=mp(e[0],e[1],o.ax,o.ay,o.bx,o.by);s<n&&(n=s,r=t.shapeId,i=!1,a=null)}for(let t of this.centers){let o=t.point2d[0]-e[0],s=t.point2d[1]-e[1],c=Math.sqrt(o*o+s*s);c<n&&(n=c,r=t.shapeId,i=!0,a=t.point2d)}return n>t||!r?null:a?{shapeId:r,isCenter:i,centerPoint:a}:{shapeId:r,isCenter:i}}applyHoverHighlight(e){this.selectedShapeIds.has(e)||this.traverseShapeEdges(e,e=>{e.userData.selectOriginalColor===void 0&&(e.userData.hoverOriginalColor=e.material.color.getHex(),e.material.color.set(Rd.highlightColor))})}removeHoverHighlight(e){this.traverseShapeEdges(e,e=>{e.userData.hoverOriginalColor!==void 0&&(e.material.color.setHex(e.userData.hoverOriginalColor),delete e.userData.hoverOriginalColor)})}applySelectionHighlight(e){this.traverseShapeEdges(e,e=>{e.userData.hoverOriginalColor===void 0?e.userData.selectOriginalColor=e.material.color.getHex():(e.userData.selectOriginalColor=e.userData.hoverOriginalColor,delete e.userData.hoverOriginalColor),e.material.color.set(Rd.highlightColor)})}removeSelectionHighlight(e){this.traverseShapeEdges(e,e=>{e.userData.selectOriginalColor!==void 0&&(e.material.color.setHex(e.userData.selectOriginalColor),delete e.userData.selectOriginalColor)})}clearHover(){this.hoveredShapeId&&(this.removeHoverHighlight(this.hoveredShapeId),this.hoveredShapeId=null,this.canvas.style.cursor=``,this.removeCenterOverlay(),this.ctx.requestRender())}clearSelection(){for(let e of this.selectedShapeIds)this.removeSelectionHighlight(e);this.selectedShapeIds.clear()}traverseShapeEdges(e,t){this.ctx.scene.traverse(n=>{n.userData.isMetaShape||(n.isLine||n.userData.isEdgeLine)&&this.findShapeId(n)===e&&t(n)})}findShapeId(e){let t=e;for(;t;){if(t.userData.shapeId&&!t.userData.isMetaShape)return t.userData.shapeId;t=t.parent}return null}addCenterOverlay(e){this.removeCenterOverlay();let t=_p(e,this.plane),n=this.plane.normal,r=new R(n.x,n.y,n.z),i=new H(new ea(Zv,16),new mr({color:Rd.highlightColor,side:2,depthTest:!1,transparent:!0,opacity:.9}));i.renderOrder=6;let a=new si;a.renderOrder=6,a.userData.isCenterOverlay=!0,a.add(i),a.position.copy(t),a.lookAt(t.clone().add(r)),Yf(i,a,t,Qv,Zv),this.ctx.scene.add(a),this.hoveredCenterOverlay=a}removeCenterOverlay(){if(this.hoveredCenterOverlay){this.ctx.scene.remove(this.hoveredCenterOverlay);let e=this.hoveredCenterOverlay.children[0];e.geometry.dispose(),e.material.dispose(),this.hoveredCenterOverlay=null,this.hoveredCenterPoint=null}}},ey=`#8899aa`,ty=1.5,ny=4.5,ry=.5,iy=2,ay=class{ctx;group;active=!1;constructor(e){this.ctx=e,this.group=new si,this.group.userData.isMetaShape=!0,this.group.renderOrder=3}activate(){this.active||=(this.ctx.scene.add(this.group),!0)}deactivate(){this.active&&(this.ctx.scene.remove(this.group),this.disposeGroup(),this.active=!1,this.ctx.requestRender())}update(e,t,n){if(!this.active)return;this.disposeGroup();let r=this.ctx.camera,i=new R(n.normal.x,n.normal.y,n.normal.z);for(let a of e){if(a.parentId!==t||a.type!==`bezier`)continue;let e=a.object?.startPoint,o=a.object?.resolvedPoints,s=[];e&&s.push(e),o&&s.push(...o);for(let e=1;e<s.length;e++)R_(this.group,s[e-1],s[e],n,iy);for(let e of s)Z(this.group,e,ey,r,i,n,ry,iy,ty,ny)}this.ctx.requestRender()}disposeGroup(){for(;this.group.children.length>0;){let e=this.group.children[0];this.group.remove(e);let t=e;t.geometry&&t.geometry.dispose(),t.material&&t.material.dispose();let n=e.children?.[0];n?.geometry&&n.geometry.dispose(),n?.material&&n.material.dispose()}}},oy=class{snapManager;plane;excludedVertices=[];snapToVertices=!0;snapToGrid=!0;constructor(e,t){this.snapManager=e,this.plane=t}updateSnapManager(e){this.snapManager=e,this.snapManager.setExcludedVertices(this.excludedVertices)}setExcludedVertices(e){this.excludedVertices=e,this.snapManager.setExcludedVertices(e)}snap(e){if(!this.snapToVertices&&!this.snapToGrid)return this.noSnapResult(e);let t=this.snapManager.snap(e,this.plane);return t.snapType===`vertex`&&!this.snapToVertices||t.snapType===`grid`&&!this.snapToGrid?this.noSnapResult(e):t}noSnapResult(e){let t=this.plane.origin,n=this.plane.xDirection,r=this.plane.yDirection;return{point2d:e,worldPoint:new R(t.x+n.x*e[0]+r.x*e[1],t.y+n.y*e[0]+r.y*e[1],t.z+n.z*e[0]+r.z*e[1]),snapType:`none`}}},sy=class{viewer;container;trimService;timelinePanel;toolbar;activeSketchInfo=null;activeDrawingTool=null;activeDragHandler=null;activeHoverSelectHandler=null;bezierHandles;shortcuts;constructor(e,t,n,r){this.viewer=t,this.container=e,this.trimService=n,this.timelinePanel=r,this.toolbar=new w_(r.toolbarHost,e=>{this.handleToolSelect(e)}),this.shortcuts=new v_,this.shortcuts.register(`n`,()=>this.lookAlongSketchNormal()),this.bezierHandles=new ay(t.sceneContext),this.toolbar.onSnapVerticesChange=e=>{this.activeDrawingTool&&(this.activeDrawingTool.snapController.snapToVertices=e),this.activeDragHandler&&(this.activeDragHandler.snapController.snapToVertices=e)},this.toolbar.onSnapGridChange=e=>{this.activeDrawingTool&&(this.activeDrawingTool.snapController.snapToGrid=e),this.activeDragHandler&&(this.activeDragHandler.snapController.snapToGrid=e)}}get hasActiveDrawingTool(){return this.activeDrawingTool!==null}update(e){let t=null;for(let n=e.length-1;n>=0;n--)if(r_(e[n],e)){t=e[n];break}if(t?.type===`sketch`&&t.id&&t.object?.plane&&t.sourceLocation){let n=t.object.plane,r=this.activeSketchInfo?.sketchObj.id;if(this.activeSketchInfo={sketchObj:t,plane:n,sourceLocation:t.sourceLocation},this.toolbar.isVisible||(this.toolbar.show(),this.shortcuts.enable(),this.timelinePanel.slideOut()),this.bezierHandles.activate(),this.bezierHandles.update(e,t.id,n),this.activeDrawingTool)r===t.id?(this.activeDrawingTool.updatePlane(n),this.activeDrawingTool.onSceneUpdate(e,t.id),t.object?.currentPosition&&this.activeDrawingTool.updateCurrentPosition(t.object.currentPosition)):this.handleToolSelect(this.toolbar.activeTool);else if(this.activeDragHandler){this.activeDragHandler.updatePlane(n);let r=new oy(n_.fromSceneObjects(e,t.id,n,this.viewer.sceneContext),n);r.snapToVertices=this.toolbar.snapVerticesChecked,r.snapToGrid=this.toolbar.snapGridChecked,this.activeDragHandler.updateSnapController(r),this.activeDragHandler.updateSceneData(e,t.id),this.activeHoverSelectHandler&&(this.activeHoverSelectHandler.updatePlane(n),this.activeHoverSelectHandler.updateSceneData(e,t.id))}else this.toolbar.activeTool||this.activateDragHandler()}else this.activeDrawingTool&&=(this.activeDrawingTool.deactivate(),null),this.deactivateDragHandler(),this.bezierHandles.deactivate(),this.activeSketchInfo=null,this.toolbar.hide(),this.shortcuts.disable(),this.timelinePanel.slideIn()}async fetchScopeVariables(){return this.activeSketchInfo?Mm(this.activeSketchInfo.sourceLocation.line):[]}createTool(e,t,n,r){let i=new oy(n_.fromSceneObjects(n,r,t,this.viewer.sceneContext),t);i.snapToVertices=this.toolbar.snapVerticesChecked,i.snapToGrid=this.toolbar.snapGridChecked;let a=(e,t)=>{this.activeSketchInfo&&Tm(e,this.activeSketchInfo.sourceLocation,t)},o=()=>this.fetchScopeVariables();switch(e){case`line`:{let e=new rv(this.viewer.sceneContext,t,i,a,this.container,o);return e.onSceneUpdate(n,r),e}case`circle`:return new iv(this.viewer.sceneContext,t,i,a,this.container,o);case`polygon`:return new Ov(this.viewer.sceneContext,t,i,a,this.container,o);case`arc2`:return new ov(this.viewer.sceneContext,t,i,a,this.container,o);case`arc3`:{let e=new cv(this.viewer.sceneContext,t,i,a,this.container,o);return e.onSceneUpdate(n,r),e}case`polyline`:{let e=new Sv(this.viewer.sceneContext,t,i,a,this.container,o);return e.onSceneUpdate(n,r),e}case`bezier`:{let e=new Cv(this.viewer.sceneContext,t,i,a,this.container,o);return e.onSceneUpdate(n,r),e}case`rect`:return new lv(this.viewer.sceneContext,t,i,a,this.container,o);case`rounded-rect`:return new uv(this.viewer.sceneContext,t,i,a,this.container,o);case`slot`:return new dv(this.viewer.sceneContext,t,i,a,this.container,o);default:return null}}activateDragHandler(){if(this.activeDragHandler||!this.activeSketchInfo)return;let e=new oy(n_.fromSceneObjects(this.viewer.currentSceneObjects,this.activeSketchInfo.sketchObj.id,this.activeSketchInfo.plane,this.viewer.sceneContext),this.activeSketchInfo.plane);e.snapToVertices=this.toolbar.snapVerticesChecked,e.snapToGrid=this.toolbar.snapGridChecked,this.activeDragHandler=new Yv(this.viewer.sceneContext,this.activeSketchInfo.plane,e,this.container,()=>this.fetchScopeVariables(),()=>this.activeSketchInfo?.sourceLocation.line??null),this.activeDragHandler.updateSceneData(this.viewer.currentSceneObjects,this.activeSketchInfo.sketchObj.id),this.activeDragHandler.activate(),this.activeHoverSelectHandler=new $v(this.viewer.sceneContext,this.activeSketchInfo.plane,()=>this.activeDragHandler?.isResizing??!1),this.activeHoverSelectHandler.updateSceneData(this.viewer.currentSceneObjects,this.activeSketchInfo.sketchObj.id),this.activeHoverSelectHandler.activate()}deactivateDragHandler(){this.activeHoverSelectHandler&&=(this.activeHoverSelectHandler.deactivate(),null),this.activeDragHandler&&=(this.activeDragHandler.deactivate(),null)}handleToolSelect(e){if(!e&&this.activeDrawingTool?.handleEscape?.())return;if(this.activeDrawingTool&&=(this.activeDrawingTool.deactivate(),null),this.toolbar.activeTool===`trim`&&e!==`trim`&&this.exitTrimFromToolbar(),this.toolbar.setActiveTool(e),!e||!this.activeSketchInfo){!e&&this.activeSketchInfo&&this.activateDragHandler();return}if(this.deactivateDragHandler(),e===`trim`){this.enterTrimFromToolbar();return}let t=this.createTool(e,this.activeSketchInfo.plane,this.viewer.currentSceneObjects,this.activeSketchInfo.sketchObj.id);t&&(this.activeSketchInfo.sketchObj.object?.currentPosition&&t.updateCurrentPosition(this.activeSketchInfo.sketchObj.object.currentPosition),t.activate(),this.activeDrawingTool=t)}enterTrimFromToolbar(){if(this.activeSketchInfo){if(this.trimService.lastPickInfo){this.trimService.enter(),this.trimService.hideBars();return}this.trimService.pendingActivation=!0,Tm(`trim()`,this.activeSketchInfo.sourceLocation)}}exitTrimFromToolbar(){if(this.trimService.pendingActivation=!1,this.trimService.state===`picking-active`&&this.trimService.exit(),this.trimService.lastPickInfo){let e=this.trimService.lastPickInfo.trimObj,t=e?.object?.picking,n=e?.object?.pickPoints;t&&(!n||n.length===0)&&e?.sourceLocation&&wm(e.sourceLocation)}this.trimService.reset()}lookAlongSketchNormal(){this.activeSketchInfo&&this.viewer.lookAlongSketchNormal(this.activeSketchInfo.plane)}};g_();var cy=document.getElementById(`fluidcad-viewer`)||document.body,ly=new Ug(cy),$=new og(`fluidcad-viewer`);zd(()=>$.rebuildSceneMesh()),Wm().then(e=>{e&&(document.documentElement.setAttribute(`data-theme`,e.theme),Jd(e),my.setShowBuildTimings(!!e.showBuildTimings))});var uy=new pg(cy),dy=new gg(cy),fy=new Bg(cy,$.sceneContext),py=new Wg(cy,{showLoading:e=>ly.show(e),hideLoading:()=>ly.hide()}),my=new Cg(cy,e=>$.highlightShape(e),e=>fy.show(e),(e,t)=>$.setShapeVisibility(e,t),e=>$.isShapeHidden(e),(e,t)=>$.setShapeTransparency(e,t),e=>$.getShapeTransparency(e),()=>$.resetAllTransparency(),()=>py.openPicker()),hy=new wg($.settingsPanelHost);$.setParamsToggleHandler(()=>{hy.toggle(),$.setParamsButtonActive(hy.isVisible)});var gy=new o_(cy,$),_y=new d_(cy,$),vy=new sy(cy,$,gy,my),yy=new Vg(cy,()=>{_y.state===`picking-active`&&_y.exit(),gy.state===`picking-active`&&gy.exit()}),by=new Hg(cy,e=>{Vm(e)});uy.setOpenHandler(()=>{$.clearHighlight(),dy.hide()}),uy.setCentroidHandler(e=>{e?$.showCentroid(e):$.clearCentroid()}),$.setSelectionHandler((e,t)=>{e?uy.isOpen?$.highlightShape(e):t?.type===`face`?$.highlightFace(e,t.index):t?.type===`edge`?$.highlightEdge(e,t.index):$.clearHighlight():$.clearHighlight(),uy.setSelectedShape(e),e!==null&&t!==null?t.type===`face`?dy.showForFace(e,t.index):dy.showForEdge(e,t.index):dy.hide()});async function xy(e,t,n){try{let r={...n||{}},i=!!r.multi;delete r.multi;let a=await(i?await Ng($.sceneContext,r):await Mg($.sceneContext,r)).arrayBuffer(),o=new Uint8Array(a),s=``;for(let e=0;e<o.length;e++)s+=String.fromCharCode(o[e]);e.send(JSON.stringify({type:`screenshot-result`,requestId:t,success:!0,data:btoa(s)}))}catch(n){e.send(JSON.stringify({type:`screenshot-result`,requestId:t,success:!1,error:n.message||String(n)}))}}var Sy=200,Cy=0,wy=!1,Ty=null;function Ey(){if(!Ty||Ty.readyState!==WebSocket.OPEN)return;let e=$.sceneContext,t=e.camera,n={x:0,y:0,z:0};e.cameraControls.getTarget(n),Ty.send(JSON.stringify({type:`camera-state`,position:[t.position.x,t.position.y,t.position.z],target:[n.x,n.y,n.z],up:[t.up.x,t.up.y,t.up.z],projection:t.isOrthographicCamera?`orthographic`:`perspective`}))}function Dy(){let e=Date.now();if(e-Cy>=Sy){Cy=e,Ey();return}if(wy)return;wy=!0;let t=Sy-(e-Cy);setTimeout(()=>{wy=!1,Cy=Date.now(),Ey()},Math.max(0,t))}$.sceneContext.cameraControls.addEventListener(`update`,Dy);function Oy(){let e=`ws://${window.location.host}`,t=new WebSocket(e);t.addEventListener(`open`,()=>{Ty=t,Ey()}),t.addEventListener(`message`,e=>{let n=JSON.parse(e.data);switch(n.type){case`init-complete`:ly.show(`Loading model...`);break;case`processing-file`:ly.show(`Loading model...`);break;case`scene-rendered`:{ly.hide();let e=n.rollbackStop!=null&&n.rollbackStop<n.result.length-1;$.isTrimming=!e&&gy.state===`picking-active`,$.isDrawing=!e&&vy.hasActiveDrawingTool,$.updateView(n.result,e,n.rollbackStop),n.absPath&&$.setFileName(n.absPath),e?(gy.reset(),_y.reset(),vy.update([])):(gy.update(n.result),_y.update(n.result),vy.update(n.result)),my.update(n.result,n.rollbackStop??n.result.length-1,n.absPath),n.params!==void 0&&(hy.update(n.params),$.setParamsButtonVisible(hy.hasAnyParams)),by.update(n.result,n.compileError??null),n.breakpointHit!==void 0&&yy.setActive(n.breakpointHit);break}case`highlight-shape`:$.highlightShape(n.shapeId),uy.setSelectedShape(n.shapeId);break;case`clear-highlight`:$.clearHighlight(),uy.setSelectedShape(null),dy.hide();break;case`show-shape-properties`:$.clearHighlight(),dy.hide(),uy.show(n.shapeId);break;case`take-screenshot`:xy(t,n.requestId,n.options);break}}),t.addEventListener(`close`,()=>{Ty===t&&(Ty=null),by.update([],null),setTimeout(Oy,1e3)})}Oy();
5439
+ `,e.appendChild(this.el),this.wrapperEl=this.el.querySelector(`.expression-wrapper`),this.input=this.el.querySelector(`.expression-input`),this.label=this.el.querySelector(`.expression-label`),this.dropdown=this.el.querySelector(`.expression-dropdown`),this.errorEl=this.el.querySelector(`.expression-error`),this.input.addEventListener(`keydown`,e=>{if(e.key!==`Escape`&&e.stopPropagation(),e.key===`ArrowDown`){e.preventDefault(),this.moveSelection(1);return}if(e.key===`ArrowUp`){e.preventDefault(),this.moveSelection(-1);return}if(e.key===`Tab`){e.preventDefault(),this.fillSelected();return}if(e.key===`Enter`){e.preventDefault(),this.selectedIndex>=0&&this.selectedIndex<this.filteredVars.length&&(this.input.value=this.filteredVars[this.selectedIndex].name),this.commit();return}if(e.key===` `&&this.onSpaceOverride){e.preventDefault(),this.onSpaceOverride();return}if(e.key===`Escape`){e.preventDefault(),this.userIsTyping=!1,this.input.blur(),this.hide();return}}),this.input.addEventListener(`input`,()=>{this.userIsTyping=!0,this.errorVisible&&this.clearInlineError(),this.filterAndRender()}),this.input.addEventListener(`focus`,()=>{this.filterAndRender()}),this.input.addEventListener(`mousedown`,e=>e.stopPropagation()),this.input.addEventListener(`mouseup`,e=>e.stopPropagation()),this.input.addEventListener(`click`,e=>e.stopPropagation()),this.dropdown.addEventListener(`mousedown`,e=>e.stopPropagation())}show(e){this.label.textContent=e.label,this.onCommit=e.onCommit,this.variables=e.variables,this.numericOnly=e.numericOnly??!1,this.visible=!0,this.userIsTyping=!1,this.selectedIndex=-1,this.seedValue=e.value,this.el.classList.remove(`hidden`),this.updatePosition(e.clientX,e.clientY),this.input.value=e.value,this.input.focus(),this.input.select(),this.clearInlineError(),this.filterAndRender()}hide(){this.visible&&(this.visible=!1,this.userIsTyping=!1,this.el.classList.add(`hidden`),this.dropdown.classList.add(`hidden`),this.clearInlineError(),this.onCommit=null,this.input.blur())}get isVisible(){return this.visible}containsElement(e){return e instanceof Node&&this.el.contains(e)}updateValue(e){if(!this.visible||this.userIsTyping)return;let t=typeof e==`string`?e:String(Math.round(e*100)/100);this.input.value=t,this.seedValue=t,this.input.select()}updatePosition(e,t){if(!this.visible)return;let n=this.el.parentElement.getBoundingClientRect();this.el.style.left=`${e-n.left+H_}px`,this.el.style.top=`${t-n.top+U_}px`}commitCurrentValue(){let e=this.input.value.trim();return e?this.runCommit(e):!1}commit(){let e=this.input.value.trim();e?this.runCommit(e):this.hide()}runCommit(e){if(!this.onCommit)return!1;let t=this.classifyCommit(e);return t.kind===`error`?(this.showInlineError(t.message),!1):(t.kind===`declare`?this.onCommit({expression:t.name,newVariable:{name:t.name,initializer:t.initializer}}):this.onCommit({expression:t.expression}),this.hide(),!0)}classifyCommit(e){if(this.numericOnly)return isNaN(parseFloat(e))?{kind:`error`,message:`Enter a numeric value`}:{kind:`expression`,expression:e};let t=e.match(G_);if(t){let e=t[1],n=t[2].trim();return q_(e)?this.variables.some(t=>t.name===e)?{kind:`error`,message:`'${e}' is already defined`}:n?{kind:`declare`,name:e,initializer:n}:{kind:`error`,message:`Missing value`}:{kind:`error`,message:`'${e}' is not a valid name`}}if(W_.test(e)){if(this.variables.some(t=>t.name===e)||!q_(e))return{kind:`expression`,expression:e};let t=this.seedValue.trim();return t?{kind:`declare`,name:e,initializer:t}:{kind:`error`,message:`No value to assign`}}return{kind:`expression`,expression:e}}showInlineError(e){this.errorVisible=!0,this.errorEl.textContent=e,this.errorEl.classList.remove(`hidden`),this.wrapperEl.classList.add(`border-red-500/70`),this.wrapperEl.classList.remove(`border-base-content/10`)}clearInlineError(){if(!this.errorVisible){this.errorEl.classList.add(`hidden`);return}this.errorVisible=!1,this.errorEl.classList.add(`hidden`),this.errorEl.textContent=``,this.wrapperEl.classList.remove(`border-red-500/70`),this.wrapperEl.classList.add(`border-base-content/10`)}moveSelection(e){this.filteredVars.length!==0&&(this.selectedIndex+=e,this.selectedIndex<0?this.selectedIndex=this.filteredVars.length-1:this.selectedIndex>=this.filteredVars.length&&(this.selectedIndex=0),this.renderDropdown())}fillSelected(){this.selectedIndex>=0&&this.selectedIndex<this.filteredVars.length&&(this.input.value=this.filteredVars[this.selectedIndex].name,this.userIsTyping=!0,this.filterAndRender())}filterAndRender(){if(this.numericOnly){this.filteredVars=[],this.selectedIndex=-1,this.renderDropdown();return}if(!this.userIsTyping)this.filteredVars=[...this.variables];else{let e=this.input.value.trim().toLowerCase();e?this.filteredVars=this.variables.filter(t=>t.name.toLowerCase().includes(e)):this.filteredVars=[...this.variables]}this.selectedIndex=-1,this.renderDropdown()}renderDropdown(){if(this.filteredVars.length===0){this.dropdown.classList.add(`hidden`);return}if(this.dropdown.classList.remove(`hidden`),this.dropdown.innerHTML=this.filteredVars.map((e,t)=>{let n=t===this.selectedIndex?`bg-primary/10`:``,r=e.initializer?`<span class="text-base-content/40 ml-2">= ${this.escapeHtml(this.truncate(e.initializer,20))}</span>`:``;return`<div class="px-2 py-1 text-sm font-mono cursor-pointer hover:bg-primary/10 ${n}" data-idx="${t}">${this.escapeHtml(e.name)}${r}</div>`}).join(``),this.dropdown.querySelectorAll(`[data-idx]`).forEach(e=>{e.addEventListener(`mousedown`,t=>{t.preventDefault(),t.stopPropagation();let n=parseInt(e.dataset.idx,10);this.input.value=this.filteredVars[n].name,this.commit()})}),this.selectedIndex>=0){let e=this.dropdown.children[this.selectedIndex];e&&e.scrollIntoView({block:`nearest`})}}escapeHtml(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`)}truncate(e,t){return e.length>t?e.slice(0,t)+`...`:e}},X=2280550,Y_=11579568,Z=16762232,X_=8947848,Z_=2.5,Q_=7.5;function $_(e){return e===`vertex`?Z:X_}function Q(e,t,n,r,i,a,o=1,s=4,c=Z_,l=Q_){let u=new U(new oa(c,16),new mr({color:n,side:2,depthTest:!1,transparent:o<1,opacity:o}));u.renderOrder=s;let d=new oi;d.renderOrder=s;let f=Ep(t,a);d.position.copy(f),d.lookAt(f.clone().add(i)),tf(u,d,f,l,c),d.add(u),e.add(d)}function ev(e,t,n,r,i=3){let a=Ep(t,r),o=Ep(n,r),s=new Float32Array(6);s[0]=a.x,s[1]=a.y,s[2]=a.z,s[3]=o.x,s[4]=o.y,s[5]=o.z;let c=new H;c.setAttribute(`position`,new V(s,3));let l=new Gi(c,new xa({color:Y_,dashSize:3,gapSize:2,depthTest:!1}));l.computeLineDistances(),l.renderOrder=i,e.add(l)}function tv(e,t,n,r,i=3){let a=new Float32Array(195);for(let e=0;e<=64;e++){let i=e/64*Math.PI*2,o=Ep([t[0]+Math.cos(i)*n,t[1]+Math.sin(i)*n],r);a[e*3]=o.x,a[e*3+1]=o.y,a[e*3+2]=o.z}let o=new H;o.setAttribute(`position`,new V(a,3));let s=new Gi(o,new xa({color:Y_,dashSize:3,gapSize:2,depthTest:!1}));s.computeLineDistances(),s.renderOrder=i,e.add(s)}function nv(e,t,n,r,i=3){let a=t[0],o=t[1],s=n[0],c=n[1],l=[[a,o],[s,o],[s,c],[a,c],[a,o]],u=new Float32Array(l.length*3);for(let e=0;e<l.length;e++){let t=Ep(l[e],r);u[e*3]=t.x,u[e*3+1]=t.y,u[e*3+2]=t.z}let d=new H;d.setAttribute(`position`,new V(u,3));let f=new Gi(d,new xa({color:Y_,dashSize:3,gapSize:2,depthTest:!1}));f.computeLineDistances(),f.renderOrder=i,e.add(f)}var rv=8;function iv(e,t,n,r,i,a=3){let o=Math.min(t[0],n[0]),s=Math.max(t[0],n[0]),c=Math.min(t[1],n[1]),l=Math.max(t[1],n[1]),u=s-o,d=l-c,f=Math.min(r,u/2,d/2);if(f<=0){nv(e,t,n,i,a);return}let p=[];p.push([o+f,c]),p.push([s-f,c]);for(let e=0;e<=rv;e++){let t=-Math.PI/2+e/rv*(Math.PI/2);p.push([s-f+f*Math.cos(t),c+f+f*Math.sin(t)])}p.push([s,c+f]),p.push([s,l-f]);for(let e=0;e<=rv;e++){let t=0+e/rv*(Math.PI/2);p.push([s-f+f*Math.cos(t),l-f+f*Math.sin(t)])}p.push([s-f,l]),p.push([o+f,l]);for(let e=0;e<=rv;e++){let t=Math.PI/2+e/rv*(Math.PI/2);p.push([o+f+f*Math.cos(t),l-f+f*Math.sin(t)])}p.push([o,l-f]),p.push([o,c+f]);for(let e=0;e<=rv;e++){let t=Math.PI+e/rv*(Math.PI/2);p.push([o+f+f*Math.cos(t),c+f+f*Math.sin(t)])}p.push([o+f,c]);let m=new Float32Array(p.length*3);for(let e=0;e<p.length;e++){let t=Ep(p[e],i);m[e*3]=t.x,m[e*3+1]=t.y,m[e*3+2]=t.z}let h=new H;h.setAttribute(`position`,new V(m,3));let g=new Gi(h,new xa({color:Y_,dashSize:3,gapSize:2,depthTest:!1}));g.computeLineDistances(),g.renderOrder=a,e.add(g)}function av(e,t,n,r,i,a=3){let o=new Float32Array((r+1)*3);for(let e=0;e<=r;e++){let a=e/r*Math.PI*2,s=Ep([t[0]+Math.cos(a)*n,t[1]+Math.sin(a)*n],i);o[e*3]=s.x,o[e*3+1]=s.y,o[e*3+2]=s.z}let s=new H;s.setAttribute(`position`,new V(o,3));let c=new Gi(s,new xa({color:Y_,dashSize:3,gapSize:2,depthTest:!1}));c.computeLineDistances(),c.renderOrder=a,e.add(c)}function ov(e,t,n,r,i,a,o,s=3){let c=i-r;a?c<=0&&(c+=Math.PI*2):c>=0&&(c-=Math.PI*2);let l=Math.max(Math.round(Math.abs(c)/(Math.PI*2)*64),2),u=new Float32Array((l+1)*3);for(let e=0;e<=l;e++){let i=e/l,a=r+c*i,s=Ep([t[0]+Math.cos(a)*n,t[1]+Math.sin(a)*n],o);u[e*3]=s.x,u[e*3+1]=s.y,u[e*3+2]=s.z}let d=new H;d.setAttribute(`position`,new V(u,3));let f=new Gi(d,new xa({color:Y_,dashSize:3,gapSize:2,depthTest:!1}));f.computeLineDistances(),f.renderOrder=s,e.add(f)}function sv(e,t){let n=e.slice();for(;n.length>1;){let e=[];for(let r=0;r<n.length-1;r++)e.push([(1-t)*n[r][0]+t*n[r+1][0],(1-t)*n[r][1]+t*n[r+1][1]]);n=e}return n[0]}function cv(e,t,n,r=3){if(t.length<2)return;let i=new Float32Array(195);for(let e=0;e<=64;e++){let r=Ep(sv(t,e/64),n);i[e*3]=r.x,i[e*3+1]=r.y,i[e*3+2]=r.z}let a=new H;a.setAttribute(`position`,new V(i,3));let o=new Gi(a,new xa({color:Y_,dashSize:3,gapSize:2,depthTest:!1}));o.computeLineDistances(),o.renderOrder=r,e.add(o)}var lv=16;function uv(e,t,n,r,i,a=3){let o=n[0]-t[0],s=n[1]-t[1],c=Math.sqrt(o*o+s*s),l,u;c>1e-10?(l=o/c,u=s/c):(l=1,u=0);let d=-u,f=l,p=[],m=Math.atan2(f,d);for(let e=0;e<=lv;e++){let n=m+e/lv*Math.PI;p.push([t[0]+r*Math.cos(n),t[1]+r*Math.sin(n)])}p.push([n[0]-r*d,n[1]-r*f]);let h=Math.atan2(-f,-d);for(let e=0;e<=lv;e++){let t=h+e/lv*Math.PI;p.push([n[0]+r*Math.cos(t),n[1]+r*Math.sin(t)])}p.push([t[0]+r*d,t[1]+r*f]);let g=new Float32Array(p.length*3);for(let e=0;e<p.length;e++){let t=Ep(p[e],i);g[e*3]=t.x,g[e*3+1]=t.y,g[e*3+2]=t.z}let _=new H;_.setAttribute(`position`,new V(g,3));let v=new Gi(_,new xa({color:Y_,dashSize:3,gapSize:2,depthTest:!1}));v.computeLineDistances(),v.renderOrder=a,e.add(v)}function dv(e,t){return Math.atan2(t[1]-e[1],t[0]-e[0])}function fv(e,t,n){return[e[0]+t*Math.cos(n),e[1]+t*Math.sin(n)]}function pv(e,t,n){let r=2*(e[0]*(t[1]-n[1])+t[0]*(n[1]-e[1])+n[0]*(e[1]-t[1]));if(Math.abs(r)<1e-10)return null;let i=e[0]*e[0]+e[1]*e[1],a=t[0]*t[0]+t[1]*t[1],o=n[0]*n[0]+n[1]*n[1];return[(i*(t[1]-n[1])+a*(n[1]-e[1])+o*(e[1]-t[1]))/r,(i*(n[0]-t[0])+a*(e[0]-n[0])+o*(t[0]-e[0]))/r]}function mv(e,t,n){let r=dv(e,t),i=dv(e,n)-r;return i<0&&(i+=Math.PI*2),i<Math.PI}function hv(e,t,n,r){let i=(e[0]+t[0])/2,a=(e[1]+t[1])/2,o=t[0]-e[0],s=t[1]-e[1],c=Math.sqrt(o*o+s*s)/2;if(Math.abs(n)<c-1e-10)return null;let l=Math.sqrt(Math.max(n*n-c*c,0)),u=-s,d=o,f=Math.sqrt(u*u+d*d);if(f<1e-10)return null;let p=r?1:-1;return[i+p*l*u/f,a+p*l*d/f]}var gv=new Set([`line-two-points`,`hline`,`vline`,`arc`,`tarc-to-point`,`tarc-to-point-tangent`,`tarc-with-tangent`,`tline`]);function _v(e,t){let n=t.origin.x,r=t.origin.y,i=t.origin.z,a=t.xDirection.x,o=t.xDirection.y,s=t.xDirection.z,c=t.yDirection.x,l=t.yDirection.y,u=t.yDirection.z,d=[];for(let t=0;t<e.length;t+=3){let f=e[t]-n,p=e[t+1]-r,m=e[t+2]-i;d.push([f*a+p*o+m*s,f*c+p*l+m*u])}return d}function vv(e,t){let n,r;if(t===`end`){let t=e[e.length-2],i=e[e.length-1];n=i[0]-t[0],r=i[1]-t[1]}else{let t=e[0],i=e[1];n=t[0]-i[0],r=t[1]-i[1]}let i=Math.sqrt(n*n+r*r);return i<1e-10?null:[n/i,r/i]}var yv=class extends V_{id=`line`;label=`Line`;icon=Jh;startPoint=null;mousePoint=null;lastSnapType=`none`;shiftHeld=!1;ctrlHeld=!1;expressionInput;fetchVariables;cachedVariables=[];lastClientX=0;lastClientY=0;sceneObjects=[];sketchId=``;boundMouseDown;boundMouseUp;boundMouseMove;boundKeyDown;boundKeyUp;downX=0;downY=0;constructor(e,t,n,r,i,a){super(e,t,n,r),this.expressionInput=new J_(i),this.fetchVariables=a,this.boundMouseDown=this.handleMouseDown.bind(this),this.boundMouseUp=this.handleMouseUp.bind(this),this.boundMouseMove=this.handleMouseMove.bind(this),this.boundKeyDown=this.handleKeyDown.bind(this),this.boundKeyUp=this.handleKeyUp.bind(this)}activate(){this.addPreviewToScene(),this.canvas.addEventListener(`mousedown`,this.boundMouseDown),this.canvas.addEventListener(`mouseup`,this.boundMouseUp),this.canvas.addEventListener(`mousemove`,this.boundMouseMove),window.addEventListener(`keydown`,this.boundKeyDown),window.addEventListener(`keyup`,this.boundKeyUp),this.fetchVariables().then(e=>{this.cachedVariables=e})}deactivate(){this.canvas.removeEventListener(`mousedown`,this.boundMouseDown),this.canvas.removeEventListener(`mouseup`,this.boundMouseUp),this.canvas.removeEventListener(`mousemove`,this.boundMouseMove),window.removeEventListener(`keydown`,this.boundKeyDown),window.removeEventListener(`keyup`,this.boundKeyUp),this.startPoint=null,this.mousePoint=null,this.shiftHeld=!1,this.ctrlHeld=!1,this.expressionInput.hide(),this.removePreviewFromScene()}onSceneUpdate(e,t){this.sceneObjects=e,this.sketchId=t;let n=v_.fromSceneObjects(e,t,this.plane,this.ctx);this.updateSnapManager(n),this.fetchVariables().then(e=>{this.cachedVariables=e})}handleMouseDown(e){this.downX=e.clientX,this.downY=e.clientY,this.syncModifiers(e)}handleMouseUp(e){this.syncModifiers(e);let t=e.clientX-this.downX,n=e.clientY-this.downY;if(t*t+n*n>64)return;let r=Tp(this.ctx,this.plane,e.clientX,e.clientY);if(!r)return;let i=Y(this.snapController.snap(r).point2d);if(!this.startPoint){this.startPoint=i,this.rebuildPreview();return}this.isTLineMode()&&this.expressionInput.isVisible?this.expressionInput.commitCurrentValue():this.isTLineMode()?this.commitTLineDirect():this.shiftHeld&&this.expressionInput.isVisible?this.expressionInput.commitCurrentValue():this.commitLine(this.startPoint,i),this.expressionInput.hide(),this.startPoint=null,this.rebuildPreview()}handleMouseMove(e){this.lastClientX=e.clientX,this.lastClientY=e.clientY,this.syncModifiers(e);let t=Tp(this.ctx,this.plane,e.clientX,e.clientY);if(!t){this.mousePoint=null,this.lastSnapType=`none`,this.rebuildPreview();return}let n=this.snapController.snap(t);this.mousePoint=n.point2d,this.lastSnapType=n.snapType,this.rebuildPreview(),this.updateDimensionInput()}syncModifiers(e){let t=this.isTLineMode();this.shiftHeld=e.shiftKey,this.ctrlHeld=e.ctrlKey||e.metaKey,this.isTLineMode()!==t&&this.expressionInput.hide()}handleKeyDown(e){this.syncModifiers(e),(e.key===`Shift`||e.key===`Control`||e.key===`Meta`)&&(this.rebuildPreview(),this.updateDimensionInput()),e.key===`Escape`&&this.startPoint&&(this.startPoint=null,this.expressionInput.hide(),this.rebuildPreview())}handleKeyUp(e){this.syncModifiers(e),(e.key===`Shift`||e.key===`Control`||e.key===`Meta`)&&(this.shiftHeld||this.expressionInput.hide(),this.rebuildPreview(),this.updateDimensionInput())}isTLineMode(){return this.shiftHeld&&this.ctrlHeld}findTangentAtStart(){if(!this.startPoint||!this.isAtCurrentPosition(Y(this.startPoint)))return null;let e=null;for(let t of this.sceneObjects)t.parentId!==this.sketchId||!t.sourceLocation||gv.has(t.uniqueType??``)&&(e=t);if(!e)return null;for(let t of e.sceneShapes)if(!t.isMetaShape)for(let e of t.meshes){let t=_v(e.vertices,this.plane);if(!(t.length<2))return vv(t,`end`)}return null}getEffectiveEndPoint(){if(!this.startPoint||!this.mousePoint)return null;if(this.isTLineMode()){let e=this.findTangentAtStart();if(e){let t=this.mousePoint[0]-this.startPoint[0],n=this.mousePoint[1]-this.startPoint[1],r=t*e[0]+n*e[1];return[this.startPoint[0]+e[0]*r,this.startPoint[1]+e[1]*r]}return this.mousePoint}if(this.shiftHeld){let e=this.mousePoint[0]-this.startPoint[0],t=this.mousePoint[1]-this.startPoint[1];return Math.abs(e)>=Math.abs(t)?[this.mousePoint[0],this.startPoint[1]]:[this.startPoint[0],this.mousePoint[1]]}return this.mousePoint}updateDimensionInput(){if(!this.startPoint||!this.mousePoint||!this.shiftHeld){this.expressionInput.hide();return}if(this.isTLineMode()){this.updateTLineDimensionInput();return}let e=this.mousePoint[0]-this.startPoint[0],t=this.mousePoint[1]-this.startPoint[1],n=Math.abs(e)>=Math.abs(t),r=Math.abs(n?e:t);this.expressionInput.isVisible?(this.expressionInput.updateValue(r),this.expressionInput.updatePosition(this.lastClientX,this.lastClientY)):this.expressionInput.show({label:n?`H:`:`V:`,value:String(Math.round(r*100)/100),clientX:this.lastClientX,clientY:this.lastClientY,variables:this.cachedVariables,onCommit:e=>this.commitWithDimension(e)})}updateTLineDimensionInput(){let e=this.findTangentAtStart();if(!e){this.expressionInput.hide();return}let t=this.mousePoint[0]-this.startPoint[0],n=this.mousePoint[1]-this.startPoint[1],r=t*e[0]+n*e[1];this.expressionInput.isVisible?(this.expressionInput.updateValue(Math.abs(r)),this.expressionInput.updatePosition(this.lastClientX,this.lastClientY)):this.expressionInput.show({label:`T:`,value:String(Math.round(Math.abs(r)*100)/100),clientX:this.lastClientX,clientY:this.lastClientY,variables:this.cachedVariables,onCommit:e=>this.commitTLine(e,r)})}commitWithDimension(e){if(!this.startPoint||!this.mousePoint)return;let{expression:t,newVariable:n}=e,r=Y(this.startPoint),i=this.isAtCurrentPosition(r),a=this.mousePoint[0]-this.startPoint[0],o=this.mousePoint[1]-this.startPoint[1],s=Math.abs(a)>=Math.abs(o),c=Math.sign(s?a:o),l=parseFloat(t),u=!isNaN(l)&&String(l)===t?String(Math.round(c*l*100)/100):t,d=s?`hLine`:`vLine`,f=i?`${d}(${u})`:`${d}(${this.formatPoint(r)}, ${u})`;this.insertGeometry(f,n),this.expressionInput.hide(),this.startPoint=null,this.rebuildPreview()}commitTLine(e,t){if(!this.startPoint)return;let{expression:n,newVariable:r}=e,i=Math.sign(t),a=parseFloat(n),o=!isNaN(a)&&String(a)===n?String(Math.round(i*a*100)/100):n;this.insertGeometry(`tLine(${o})`,r),this.expressionInput.hide(),this.startPoint=null,this.rebuildPreview()}commitTLineDirect(){if(!this.startPoint||!this.mousePoint)return;let e=this.findTangentAtStart();if(!e)return;let t=this.mousePoint[0]-this.startPoint[0],n=this.mousePoint[1]-this.startPoint[1],r=Math.round((t*e[0]+n*e[1])*100)/100;this.insertGeometry(`tLine(${r})`),this.expressionInput.hide(),this.startPoint=null,this.rebuildPreview()}commitLine(e,t){let n=Y(e),r=Y(t),i=this.isAtCurrentPosition(n);if(this.shiftHeld){let e=r[0]-n[0],t=r[1]-n[1],a=Math.abs(e)>=Math.abs(t),o=a?Y([e,0])[0]:Y([0,t])[1];a?i?this.insertGeometry(`hLine(${o})`):this.insertGeometry(`hLine(${this.formatPoint(n)}, ${o})`):i?this.insertGeometry(`vLine(${o})`):this.insertGeometry(`vLine(${this.formatPoint(n)}, ${o})`);return}i?this.insertGeometry(`line(${this.formatPoint(r)})`):this.insertGeometry(`line(${this.formatPoint(n)}, ${this.formatPoint(r)})`)}rebuildPreview(){this.disposePreview();let e=this.ctx.camera,t=new R(this.plane.normal.x,this.plane.normal.y,this.plane.normal.z);if(this.startPoint){Q(this.previewGroup,this.startPoint,X,e,t,this.plane);let n=this.getEffectiveEndPoint();if(n&&(ev(this.previewGroup,this.startPoint,n,this.plane),this.lastSnapType!==`none`)){let r=this.lastSnapType===`vertex`?Z:X_;Q(this.previewGroup,n,r,e,t,this.plane,.6)}}else if(this.mousePoint&&this.lastSnapType!==`none`){let n=this.lastSnapType===`vertex`?Z:X_;Q(this.previewGroup,this.mousePoint,n,e,t,this.plane,.6)}this.requestRender()}},bv=class extends V_{id=`circle`;label=`Circle`;icon=Yh;centerPoint=null;mousePoint=null;lastSnapType=`none`;expressionInput;fetchVariables;cachedVariables=[];lastClientX=0;lastClientY=0;boundMouseDown;boundMouseUp;boundMouseMove;boundKeyDown;downX=0;downY=0;constructor(e,t,n,r,i,a){super(e,t,n,r),this.expressionInput=new J_(i),this.fetchVariables=a,this.boundMouseDown=this.handleMouseDown.bind(this),this.boundMouseUp=this.handleMouseUp.bind(this),this.boundMouseMove=this.handleMouseMove.bind(this),this.boundKeyDown=this.handleKeyDown.bind(this)}activate(){this.addPreviewToScene(),this.canvas.addEventListener(`mousedown`,this.boundMouseDown),this.canvas.addEventListener(`mouseup`,this.boundMouseUp),this.canvas.addEventListener(`mousemove`,this.boundMouseMove),window.addEventListener(`keydown`,this.boundKeyDown),this.fetchVariables().then(e=>{this.cachedVariables=e})}deactivate(){this.canvas.removeEventListener(`mousedown`,this.boundMouseDown),this.canvas.removeEventListener(`mouseup`,this.boundMouseUp),this.canvas.removeEventListener(`mousemove`,this.boundMouseMove),window.removeEventListener(`keydown`,this.boundKeyDown),this.centerPoint=null,this.mousePoint=null,this.expressionInput.hide(),this.removePreviewFromScene()}onSceneUpdate(e,t){let n=v_.fromSceneObjects(e,t,this.plane,this.ctx);this.updateSnapManager(n),this.fetchVariables().then(e=>{this.cachedVariables=e})}handleMouseDown(e){this.downX=e.clientX,this.downY=e.clientY}handleMouseUp(e){let t=e.clientX-this.downX,n=e.clientY-this.downY;if(t*t+n*n>64)return;let r=Tp(this.ctx,this.plane,e.clientX,e.clientY);if(!r)return;let i=Y(this.snapController.snap(r).point2d);if(!this.centerPoint){this.centerPoint=i,this.rebuildPreview();return}if(this.expressionInput.isVisible)this.expressionInput.commitCurrentValue();else{let e=Math.round(Ap(this.centerPoint,i)*2*100)/100;if(e<=0)return;this.commitCircle(this.centerPoint,{expression:String(e)})}this.expressionInput.hide(),this.centerPoint=null,this.rebuildPreview()}handleMouseMove(e){this.lastClientX=e.clientX,this.lastClientY=e.clientY;let t=Tp(this.ctx,this.plane,e.clientX,e.clientY);if(!t){this.mousePoint=null,this.lastSnapType=`none`,this.rebuildPreview();return}let n=this.snapController.snap(t);this.mousePoint=n.point2d,this.lastSnapType=n.snapType,this.rebuildPreview(),this.updateDimensionInput()}handleKeyDown(e){e.key===`Escape`&&this.centerPoint&&(this.centerPoint=null,this.expressionInput.hide(),this.rebuildPreview())}updateDimensionInput(){if(!this.centerPoint||!this.mousePoint)return;let e=Math.round(Ap(this.centerPoint,this.mousePoint)*2*100)/100;e<=0||(this.expressionInput.isVisible?(this.expressionInput.updateValue(e),this.expressionInput.updatePosition(this.lastClientX,this.lastClientY)):this.expressionInput.show({label:`⌀`,value:String(e),clientX:this.lastClientX,clientY:this.lastClientY,variables:this.cachedVariables,onCommit:e=>{this.centerPoint&&(this.commitCircle(this.centerPoint,e),this.expressionInput.hide(),this.centerPoint=null,this.rebuildPreview())}}))}commitCircle(e,t){let{expression:n,newVariable:r}=t,i=this.isAtCurrentPosition(e)?`circle(${n})`:`circle(${this.formatPoint(e)}, ${n})`;this.insertGeometry(i,r)}rebuildPreview(){this.disposePreview();let e=this.ctx.camera,t=new R(this.plane.normal.x,this.plane.normal.y,this.plane.normal.z);if(this.centerPoint){if(Q(this.previewGroup,this.centerPoint,X,e,t,this.plane),this.mousePoint){let e=Ap(this.centerPoint,this.mousePoint);e>0&&tv(this.previewGroup,this.centerPoint,e,this.plane)}}else if(this.mousePoint&&this.lastSnapType!==`none`){let n=this.lastSnapType===`vertex`?Z:X_;Q(this.previewGroup,this.mousePoint,n,e,t,this.plane,.6)}this.requestRender()}},xv=function(e){return e[e.IDLE=0]=`IDLE`,e[e.CENTER_PLACED=1]=`CENTER_PLACED`,e[e.START_PLACED=2]=`START_PLACED`,e}(xv||{}),Sv=class extends V_{id=`arc2`;label=`Center Arc`;icon=Xh;state=xv.IDLE;centerPoint=null;startPoint=null;mousePoint=null;lastSnapType=`none`;expressionInput;fetchVariables;cachedVariables=[];lastClientX=0;lastClientY=0;lastCCW=!0;boundMouseDown;boundMouseUp;boundMouseMove;boundKeyDown;downX=0;downY=0;constructor(e,t,n,r,i,a){super(e,t,n,r),this.expressionInput=new J_(i),this.fetchVariables=a,this.boundMouseDown=this.handleMouseDown.bind(this),this.boundMouseUp=this.handleMouseUp.bind(this),this.boundMouseMove=this.handleMouseMove.bind(this),this.boundKeyDown=this.handleKeyDown.bind(this)}activate(){this.addPreviewToScene(),this.canvas.addEventListener(`mousedown`,this.boundMouseDown),this.canvas.addEventListener(`mouseup`,this.boundMouseUp),this.canvas.addEventListener(`mousemove`,this.boundMouseMove),window.addEventListener(`keydown`,this.boundKeyDown),this.fetchVariables().then(e=>{this.cachedVariables=e})}deactivate(){this.canvas.removeEventListener(`mousedown`,this.boundMouseDown),this.canvas.removeEventListener(`mouseup`,this.boundMouseUp),this.canvas.removeEventListener(`mousemove`,this.boundMouseMove),window.removeEventListener(`keydown`,this.boundKeyDown),this.resetState(),this.expressionInput.hide(),this.removePreviewFromScene()}onSceneUpdate(e,t){let n=v_.fromSceneObjects(e,t,this.plane,this.ctx);this.updateSnapManager(n),this.fetchVariables().then(e=>{this.cachedVariables=e})}resetState(){this.state=xv.IDLE,this.centerPoint=null,this.startPoint=null,this.mousePoint=null}handleMouseDown(e){this.downX=e.clientX,this.downY=e.clientY}handleMouseUp(e){let t=e.clientX-this.downX,n=e.clientY-this.downY;if(t*t+n*n>64)return;let r=Tp(this.ctx,this.plane,e.clientX,e.clientY);if(!r)return;let i=Y(this.snapController.snap(r).point2d);if(this.state===xv.IDLE){this.centerPoint=i,this.state=xv.CENTER_PLACED,this.rebuildPreview();return}if(this.state===xv.CENTER_PLACED){if(Ap(this.centerPoint,i)<=0)return;this.startPoint=i,this.state=xv.START_PLACED,this.rebuildPreview();return}this.state===xv.START_PLACED&&(this.expressionInput.isVisible?this.expressionInput.commitCurrentValue():this.commitFromMouse())}handleMouseMove(e){this.lastClientX=e.clientX,this.lastClientY=e.clientY;let t=Tp(this.ctx,this.plane,e.clientX,e.clientY);if(!t){this.mousePoint=null,this.lastSnapType=`none`,this.rebuildPreview();return}let n=this.snapController.snap(t);this.mousePoint=n.point2d,this.lastSnapType=n.snapType,this.rebuildPreview(),this.state===xv.START_PLACED&&this.updateDimensionInput()}handleKeyDown(e){e.key===`Escape`&&(this.state===xv.START_PLACED?(this.startPoint=null,this.state=xv.CENTER_PLACED,this.expressionInput.hide()):this.state===xv.CENTER_PLACED&&(this.centerPoint=null,this.state=xv.IDLE),this.rebuildPreview())}getSweepDeg(){if(!this.centerPoint||!this.startPoint||!this.mousePoint)return null;let e=dv(this.centerPoint,this.startPoint),t=dv(this.centerPoint,this.mousePoint);this.lastCCW=mv(this.centerPoint,this.startPoint,this.mousePoint);let n;return this.lastCCW?(n=t-e,n<=0&&(n+=Math.PI*2)):(n=e-t,n<=0&&(n+=Math.PI*2)),n===0?null:Math.round(180/Math.PI*n*100)/100}updateDimensionInput(){let e=this.getSweepDeg();e===null||e<=0||(this.expressionInput.isVisible?(this.expressionInput.updateValue(e),this.expressionInput.updatePosition(this.lastClientX,this.lastClientY)):this.expressionInput.show({label:`∠`,value:String(e),clientX:this.lastClientX,clientY:this.lastClientY,variables:this.cachedVariables,numericOnly:!0,onCommit:e=>this.commitFromExpression(e)}))}commitFromMouse(){if(!this.centerPoint||!this.startPoint||!this.mousePoint)return;let e=mv(this.centerPoint,this.startPoint,this.mousePoint),t=Ap(this.centerPoint,this.startPoint),n=dv(this.centerPoint,this.mousePoint),r=fv(this.centerPoint,t,n);this.emitArc(this.startPoint,r,this.centerPoint,e)}commitFromExpression(e){if(!this.centerPoint||!this.startPoint)return;let{expression:t,newVariable:n}=e,r=parseFloat(t);if(isNaN(r)||r<=0)return;let i=Math.PI/180*r,a=Ap(this.centerPoint,this.startPoint),o=dv(this.centerPoint,this.startPoint)+(this.lastCCW?1:-1)*i,s=fv(this.centerPoint,a,o);this.emitArc(this.startPoint,s,this.centerPoint,this.lastCCW,n)}emitArc(e,t,n,r,i){let a=Y(e),o=Y(t),s=Y(n),c=r?``:`.cw()`,l=this.isAtCurrentPosition(a)?`arc(${this.formatPoint(o)}).center(${this.formatPoint(s)})${c}`:`arc(${this.formatPoint(a)}, ${this.formatPoint(o)}).center(${this.formatPoint(s)})${c}`;this.insertGeometry(l,i),this.expressionInput.hide(),this.resetState(),this.rebuildPreview()}rebuildPreview(){this.disposePreview();let e=this.ctx.camera,t=new R(this.plane.normal.x,this.plane.normal.y,this.plane.normal.z);if(this.state===xv.IDLE){if(this.mousePoint&&this.lastSnapType!==`none`){let n=this.lastSnapType===`vertex`?Z:X_;Q(this.previewGroup,this.mousePoint,n,e,t,this.plane,.6)}}else if(this.state===xv.CENTER_PLACED){if(Q(this.previewGroup,this.centerPoint,X,e,t,this.plane),this.mousePoint&&this.lastSnapType!==`none`){let n=this.lastSnapType===`vertex`?Z:X_;Q(this.previewGroup,this.mousePoint,n,e,t,this.plane,.6)}}else if(this.state===xv.START_PLACED&&this.centerPoint&&this.startPoint&&(Q(this.previewGroup,this.centerPoint,X,e,t,this.plane),Q(this.previewGroup,this.startPoint,X,e,t,this.plane),ev(this.previewGroup,this.centerPoint,this.startPoint,this.plane),this.mousePoint)){let n=Ap(this.centerPoint,this.startPoint),r=dv(this.centerPoint,this.startPoint),i=dv(this.centerPoint,this.mousePoint),a=fv(this.centerPoint,n,i);ev(this.previewGroup,this.centerPoint,a,this.plane);let o=mv(this.centerPoint,this.startPoint,this.mousePoint);if(ov(this.previewGroup,this.centerPoint,n,r,i,o,this.plane),this.lastSnapType!==`none`){let n=this.lastSnapType===`vertex`?Z:X_;Q(this.previewGroup,this.mousePoint,n,e,t,this.plane,.6)}}this.requestRender()}},Cv=function(e){return e[e.IDLE=0]=`IDLE`,e[e.START_PLACED=1]=`START_PLACED`,e[e.END_PLACED=2]=`END_PLACED`,e}(Cv||{}),wv=class extends V_{id=`arc3`;label=`3-Point Arc`;icon=Zh;state=Cv.IDLE;startPoint=null;endPoint=null;mousePoint=null;lastSnapType=`none`;expressionInput;fetchVariables;cachedVariables=[];lastClientX=0;lastClientY=0;lastCCW=!0;lastCenterOnLeft=!0;shiftHeld=!1;boundMouseDown;boundMouseUp;boundMouseMove;boundKeyDown;boundKeyUp;downX=0;downY=0;constructor(e,t,n,r,i,a){super(e,t,n,r),this.expressionInput=new J_(i),this.fetchVariables=a,this.boundMouseDown=this.handleMouseDown.bind(this),this.boundMouseUp=this.handleMouseUp.bind(this),this.boundMouseMove=this.handleMouseMove.bind(this),this.boundKeyDown=this.handleKeyDown.bind(this),this.boundKeyUp=this.handleKeyUp.bind(this)}activate(){this.addPreviewToScene(),this.canvas.addEventListener(`mousedown`,this.boundMouseDown),this.canvas.addEventListener(`mouseup`,this.boundMouseUp),this.canvas.addEventListener(`mousemove`,this.boundMouseMove),window.addEventListener(`keydown`,this.boundKeyDown),window.addEventListener(`keyup`,this.boundKeyUp),this.fetchVariables().then(e=>{this.cachedVariables=e})}deactivate(){this.canvas.removeEventListener(`mousedown`,this.boundMouseDown),this.canvas.removeEventListener(`mouseup`,this.boundMouseUp),this.canvas.removeEventListener(`mousemove`,this.boundMouseMove),window.removeEventListener(`keydown`,this.boundKeyDown),window.removeEventListener(`keyup`,this.boundKeyUp),this.resetState(),this.expressionInput.hide(),this.removePreviewFromScene()}onSceneUpdate(e,t){let n=v_.fromSceneObjects(e,t,this.plane,this.ctx);this.updateSnapManager(n),this.fetchVariables().then(e=>{this.cachedVariables=e})}resetState(){this.state=Cv.IDLE,this.startPoint=null,this.endPoint=null,this.mousePoint=null}handleMouseDown(e){this.downX=e.clientX,this.downY=e.clientY}handleMouseUp(e){this.shiftHeld=e.shiftKey;let t=e.clientX-this.downX,n=e.clientY-this.downY;if(t*t+n*n>64)return;let r=Tp(this.ctx,this.plane,e.clientX,e.clientY);if(!r)return;let i=Y(this.snapController.snap(r).point2d);if(this.state===Cv.IDLE){this.startPoint=i,this.state=Cv.START_PLACED,this.rebuildPreview();return}if(this.state===Cv.START_PLACED){if(Ap(this.startPoint,i)<=0)return;this.endPoint=i,this.state=Cv.END_PLACED,this.rebuildPreview();return}this.state===Cv.END_PLACED&&(this.expressionInput.isVisible?this.expressionInput.commitCurrentValue():this.commitFromMouse())}handleMouseMove(e){this.shiftHeld=e.shiftKey,this.lastClientX=e.clientX,this.lastClientY=e.clientY;let t=Tp(this.ctx,this.plane,e.clientX,e.clientY);if(!t){this.mousePoint=null,this.lastSnapType=`none`,this.rebuildPreview();return}let n=this.snapController.snap(t);this.mousePoint=n.point2d,this.lastSnapType=n.snapType,this.rebuildPreview(),this.state===Cv.END_PLACED&&this.updateDimensionInput()}handleKeyDown(e){e.key===`Escape`&&(this.state===Cv.END_PLACED?(this.endPoint=null,this.state=Cv.START_PLACED,this.expressionInput.hide()):this.state===Cv.START_PLACED&&(this.startPoint=null,this.state=Cv.IDLE),this.rebuildPreview()),e.key===`Shift`&&!this.shiftHeld&&(this.shiftHeld=!0,this.rebuildPreview(),this.state===Cv.END_PLACED&&this.updateDimensionInput())}handleKeyUp(e){e.key===`Shift`&&this.shiftHeld&&(this.shiftHeld=!1,this.rebuildPreview(),this.state===Cv.END_PLACED&&this.updateDimensionInput())}snapCenterToCollinear(e){if(!this.startPoint||!this.endPoint)return null;let t=this.endPoint[0]-this.startPoint[0],n=this.endPoint[1]-this.startPoint[1],r=t*t+n*n;if(r<1e-10)return null;let i=e[0]-this.startPoint[0],a=e[1]-this.startPoint[1],o=Math.abs(i*n-a*t)/Math.sqrt(r),s=Ep([(this.startPoint[0]+this.endPoint[0])/2,(this.startPoint[1]+this.endPoint[1])/2],this.plane);return o>=Xd(this.ctx.renderer,this.ctx.camera,s,10)?null:[(this.startPoint[0]+this.endPoint[0])/2,(this.startPoint[1]+this.endPoint[1])/2]}computeCenter(){if(!this.startPoint||!this.endPoint||!this.mousePoint)return null;let e=pv(this.startPoint,this.endPoint,this.mousePoint);return e?this.shiftHeld?e:this.snapCenterToCollinear(e)??e:null}isMouseCCW(){if(!this.startPoint||!this.endPoint||!this.mousePoint)return!0;let e=this.computeCenter();if(!e)return!0;let t=dv(e,this.startPoint),n=dv(e,this.endPoint),r=dv(e,this.mousePoint)-t;r<0&&(r+=Math.PI*2);let i=n-t;return i<0&&(i+=Math.PI*2),r<i}updateDimensionInput(){let e=this.computeCenter();if(!e||!this.startPoint)return;let t=Math.round(Ap(e,this.startPoint)*100)/100;if(t<=0)return;this.lastCCW=this.isMouseCCW();let n=this.endPoint[0]-this.startPoint[0],r=this.endPoint[1]-this.startPoint[1],i=e[0]-this.startPoint[0];this.lastCenterOnLeft=n*(e[1]-this.startPoint[1])-r*i>0,this.expressionInput.isVisible?(this.expressionInput.updateValue(t),this.expressionInput.updatePosition(this.lastClientX,this.lastClientY)):this.expressionInput.show({label:`R`,value:String(t),clientX:this.lastClientX,clientY:this.lastClientY,variables:this.cachedVariables,numericOnly:!0,onCommit:e=>this.commitFromExpression(e)})}commitFromMouse(){if(!this.startPoint||!this.endPoint)return;let e=this.computeCenter();e&&this.emitArc(this.startPoint,this.endPoint,e,this.isMouseCCW())}commitFromExpression(e){if(!this.startPoint||!this.endPoint)return;let{expression:t,newVariable:n}=e,r=parseFloat(t);if(isNaN(r)||r<=0)return;let i=hv(this.startPoint,this.endPoint,r,this.lastCenterOnLeft);i&&this.emitArc(this.startPoint,this.endPoint,i,this.lastCCW,n)}emitArc(e,t,n,r,i){let a=Y(e),o=Y(t),s=Y(n),c=r?``:`.cw()`,l=this.isAtCurrentPosition(a)?`arc(${this.formatPoint(o)}).center(${this.formatPoint(s)})${c}`:`arc(${this.formatPoint(a)}, ${this.formatPoint(o)}).center(${this.formatPoint(s)})${c}`;this.insertGeometry(l,i),this.expressionInput.hide(),this.resetState(),this.rebuildPreview()}rebuildPreview(){this.disposePreview();let e=this.ctx.camera,t=new R(this.plane.normal.x,this.plane.normal.y,this.plane.normal.z);if(this.state===Cv.IDLE){if(this.mousePoint&&this.lastSnapType!==`none`){let n=this.lastSnapType===`vertex`?Z:X_;Q(this.previewGroup,this.mousePoint,n,e,t,this.plane,.6)}}else if(this.state===Cv.START_PLACED){if(Q(this.previewGroup,this.startPoint,X,e,t,this.plane),this.mousePoint&&this.lastSnapType!==`none`){let n=this.lastSnapType===`vertex`?Z:X_;Q(this.previewGroup,this.mousePoint,n,e,t,this.plane,.6)}}else if(this.state===Cv.END_PLACED&&this.startPoint&&this.endPoint&&(Q(this.previewGroup,this.startPoint,X,e,t,this.plane),Q(this.previewGroup,this.endPoint,X,e,t,this.plane),ev(this.previewGroup,this.startPoint,this.endPoint,this.plane),this.mousePoint)){let n=this.computeCenter();if(n){let r=Ap(n,this.startPoint),i=dv(n,this.startPoint),a=dv(n,this.endPoint),o=this.isMouseCCW();ov(this.previewGroup,n,r,i,a,o,this.plane),Q(this.previewGroup,n,Y_,e,t,this.plane,.7),ev(this.previewGroup,n,this.startPoint,this.plane),ev(this.previewGroup,n,this.endPoint,this.plane)}if(this.lastSnapType!==`none`){let n=this.lastSnapType===`vertex`?Z:X_;Q(this.previewGroup,this.mousePoint,n,e,t,this.plane,.6)}}this.requestRender()}},Tv=class extends V_{id=`rect`;label=`Rectangle`;icon=Qh;startPoint=null;mousePoint=null;lastSnapType=`none`;shiftHeld=!1;expressionInput;fetchVariables;cachedVariables=[];lastClientX=0;lastClientY=0;expressionPhase=`width`;widthExpression=null;lockedWidth=null;widthIsNumeric=!1;boundMouseDown;boundMouseUp;boundMouseMove;boundKeyDown;boundKeyUp;downX=0;downY=0;constructor(e,t,n,r,i,a){super(e,t,n,r),this.expressionInput=new J_(i),this.fetchVariables=a,this.boundMouseDown=this.handleMouseDown.bind(this),this.boundMouseUp=this.handleMouseUp.bind(this),this.boundMouseMove=this.handleMouseMove.bind(this),this.boundKeyDown=this.handleKeyDown.bind(this),this.boundKeyUp=this.handleKeyUp.bind(this)}activate(){this.addPreviewToScene(),this.canvas.addEventListener(`mousedown`,this.boundMouseDown),this.canvas.addEventListener(`mouseup`,this.boundMouseUp),this.canvas.addEventListener(`mousemove`,this.boundMouseMove),window.addEventListener(`keydown`,this.boundKeyDown),window.addEventListener(`keyup`,this.boundKeyUp),this.fetchVariables().then(e=>{this.cachedVariables=e})}deactivate(){this.canvas.removeEventListener(`mousedown`,this.boundMouseDown),this.canvas.removeEventListener(`mouseup`,this.boundMouseUp),this.canvas.removeEventListener(`mousemove`,this.boundMouseMove),window.removeEventListener(`keydown`,this.boundKeyDown),window.removeEventListener(`keyup`,this.boundKeyUp),this.resetState(),this.removePreviewFromScene()}onSceneUpdate(e,t){let n=v_.fromSceneObjects(e,t,this.plane,this.ctx);this.updateSnapManager(n),this.fetchVariables().then(e=>{this.cachedVariables=e})}resetState(){this.startPoint=null,this.mousePoint=null,this.expressionPhase=`width`,this.widthExpression=null,this.lockedWidth=null,this.widthIsNumeric=!1,this.shiftHeld=!1,this.expressionInput.hide()}handleMouseDown(e){this.downX=e.clientX,this.downY=e.clientY}handleMouseUp(e){let t=e.clientX-this.downX,n=e.clientY-this.downY;if(t*t+n*n>64)return;let r=Tp(this.ctx,this.plane,e.clientX,e.clientY);if(!r)return;let i=Y(this.snapController.snap(r).point2d);if(!this.startPoint){this.startPoint=i,this.syncModifiers(e),this.rebuildPreview();return}this.expressionInput.isVisible?this.expressionInput.commitCurrentValue():this.commitFromGeometry(i)}handleMouseMove(e){this.lastClientX=e.clientX,this.lastClientY=e.clientY,this.syncModifiers(e);let t=Tp(this.ctx,this.plane,e.clientX,e.clientY);if(!t){this.mousePoint=null,this.lastSnapType=`none`,this.rebuildPreview();return}let n=this.snapController.snap(t);this.mousePoint=n.point2d,this.lastSnapType=n.snapType,this.rebuildPreview(),this.updateDimensionInput()}handleKeyDown(e){if(e.key===`Escape`){this.startPoint&&(this.resetState(),this.rebuildPreview());return}e.key===`Shift`&&(this.shiftHeld=!0,this.rebuildPreview())}handleKeyUp(e){e.key===`Shift`&&(this.shiftHeld=!1,this.rebuildPreview())}syncModifiers(e){this.shiftHeld=e.shiftKey}computeDimensions(e){let t=this.startPoint;if(this.shiftHeld){let n=e[0]-t[0],r=e[1]-t[1];return{width:Math.round(n*2*100)/100,height:Math.round(r*2*100)/100}}return{width:Math.round((e[0]-t[0])*100)/100,height:Math.round((e[1]-t[1])*100)/100}}computePreviewCorners(e){let t=this.startPoint;if(this.lockedWidth!==null){if(this.shiftHeld){let n=this.lockedWidth/2,r=e[1]-t[1];return{c1:[t[0]-n,t[1]-r],c2:[t[0]+n,t[1]+r]}}let n=e[0]>=t[0]?1:-1;return{c1:t,c2:[t[0]+n*this.lockedWidth,e[1]]}}if(this.shiftHeld){let n=e[0]-t[0],r=e[1]-t[1];return{c1:[t[0]-n,t[1]-r],c2:[t[0]+n,t[1]+r]}}return{c1:t,c2:e}}dimensionInputAnchor(){if(!this.startPoint||!this.mousePoint)return{clientX:this.lastClientX,clientY:this.lastClientY};let{c1:e,c2:t}=this.computePreviewCorners(this.mousePoint),n=this.expressionPhase===`width`?[(e[0]+t[0])/2,e[1]]:[t[0],(e[1]+t[1])/2];return Dp(this.ctx,this.plane,n)}updateDimensionInput(){if(!this.startPoint||!this.mousePoint)return;let{width:e,height:t}=this.computeDimensions(this.mousePoint),n=this.dimensionInputAnchor();if(this.expressionPhase===`width`){let t=Math.round(Math.abs(e)*100)/100;if(t<=0)return;this.expressionInput.isVisible?(this.expressionInput.updateValue(t),this.expressionInput.updatePosition(n.clientX,n.clientY)):this.expressionInput.show({label:`W`,value:String(t),clientX:n.clientX,clientY:n.clientY,variables:this.cachedVariables,onCommit:e=>this.onWidthCommit(e)})}else if(this.expressionPhase===`height`){let e=Math.round(Math.abs(t)*100)/100;this.expressionInput.isVisible?(this.expressionInput.updateValue(e),this.expressionInput.updatePosition(n.clientX,n.clientY)):this.expressionInput.show({label:`H`,value:String(e),clientX:n.clientX,clientY:n.clientY,variables:this.cachedVariables,onCommit:e=>this.onHeightCommit(e)})}}onWidthCommit(e){let t=parseFloat(e.expression),n=!isNaN(t)&&String(t)===e.expression;this.widthIsNumeric=n,n?(this.widthExpression=e,this.lockedWidth=t):(this.widthExpression=e,this.lockedWidth=null),this.expressionPhase=`height`,queueMicrotask(()=>{if(this.mousePoint&&this.startPoint){let{height:e}=this.computeDimensions(this.mousePoint),t=Math.round(Math.abs(e)*100)/100,n=this.dimensionInputAnchor();this.expressionInput.show({label:`H`,value:String(t),clientX:n.clientX,clientY:n.clientY,variables:this.cachedVariables,onCommit:e=>this.onHeightCommit(e)})}this.rebuildPreview()})}onHeightCommit(e){if(!this.startPoint||!this.widthExpression)return;let t=parseFloat(e.expression),n=!isNaN(t)&&String(t)===e.expression,r=this.resolveSignedDim(this.widthExpression,this.widthIsNumeric,this.lockedWidth,0),i;if(n&&this.mousePoint&&!this.shiftHeld){let n=this.mousePoint[1]>=this.startPoint[1]?1:-1;i={expression:String(Math.round(n*t*100)/100),newVariable:e.newVariable}}else i=e;this.commitRect(this.startPoint,r,i),this.expressionInput.hide(),this.startPoint=null,this.expressionPhase=`width`,this.widthExpression=null,this.lockedWidth=null,this.widthIsNumeric=!1,this.rebuildPreview()}commitFromGeometry(e){if(!this.startPoint)return;let{width:t,height:n}=this.computeDimensions(e);t===0||n===0||(this.commitRect(this.startPoint,{expression:String(t)},{expression:String(n)}),this.expressionInput.hide(),this.startPoint=null,this.expressionPhase=`width`,this.widthExpression=null,this.lockedWidth=null,this.widthIsNumeric=!1,this.rebuildPreview())}resolveSignedDim(e,t,n,r){if(!t||n===null||!this.mousePoint||!this.startPoint||this.shiftHeld)return e;let i=r===0?this.mousePoint[0]>=this.startPoint[0]?1:-1:this.mousePoint[1]>=this.startPoint[1]?1:-1;return{expression:String(Math.round(i*n*100)/100),newVariable:e.newVariable}}commitRect(e,t,n){let r=this.isAtCurrentPosition(e),i;i=r?`rect(${t.expression}, ${n.expression})`:`rect(${this.formatPoint(e)}, ${t.expression}, ${n.expression})`,this.shiftHeld&&(i+=`.centered()`);let a=t.newVariable??n.newVariable;this.insertGeometry(i,a)}rebuildPreview(){this.disposePreview();let e=this.ctx.camera,t=new R(this.plane.normal.x,this.plane.normal.y,this.plane.normal.z);if(this.startPoint){if(Q(this.previewGroup,this.startPoint,X,e,t,this.plane),this.mousePoint){let{c1:e,c2:t}=this.computePreviewCorners(this.mousePoint);nv(this.previewGroup,e,t,this.plane)}}else if(this.mousePoint&&this.lastSnapType!==`none`){let n=this.lastSnapType===`vertex`?Z:X_;Q(this.previewGroup,this.mousePoint,n,e,t,this.plane,.6)}this.requestRender()}},Ev=class extends V_{id=`rounded-rect`;label=`Rounded Rectangle`;icon=$h;startPoint=null;mousePoint=null;lastSnapType=`none`;shiftHeld=!1;expressionInput;fetchVariables;cachedVariables=[];lastClientX=0;lastClientY=0;expressionPhase=`width`;widthExpression=null;heightExpression=null;lockedWidth=null;lockedHeight=null;widthIsNumeric=!1;heightIsNumeric=!1;boundMouseDown;boundMouseUp;boundMouseMove;boundKeyDown;boundKeyUp;downX=0;downY=0;constructor(e,t,n,r,i,a){super(e,t,n,r),this.expressionInput=new J_(i),this.fetchVariables=a,this.boundMouseDown=this.handleMouseDown.bind(this),this.boundMouseUp=this.handleMouseUp.bind(this),this.boundMouseMove=this.handleMouseMove.bind(this),this.boundKeyDown=this.handleKeyDown.bind(this),this.boundKeyUp=this.handleKeyUp.bind(this)}activate(){this.addPreviewToScene(),this.canvas.addEventListener(`mousedown`,this.boundMouseDown),this.canvas.addEventListener(`mouseup`,this.boundMouseUp),this.canvas.addEventListener(`mousemove`,this.boundMouseMove),window.addEventListener(`keydown`,this.boundKeyDown),window.addEventListener(`keyup`,this.boundKeyUp),this.fetchVariables().then(e=>{this.cachedVariables=e})}deactivate(){this.canvas.removeEventListener(`mousedown`,this.boundMouseDown),this.canvas.removeEventListener(`mouseup`,this.boundMouseUp),this.canvas.removeEventListener(`mousemove`,this.boundMouseMove),window.removeEventListener(`keydown`,this.boundKeyDown),window.removeEventListener(`keyup`,this.boundKeyUp),this.resetState(),this.removePreviewFromScene()}onSceneUpdate(e,t){let n=v_.fromSceneObjects(e,t,this.plane,this.ctx);this.updateSnapManager(n),this.fetchVariables().then(e=>{this.cachedVariables=e})}resetState(){this.startPoint=null,this.mousePoint=null,this.expressionPhase=`width`,this.widthExpression=null,this.heightExpression=null,this.lockedWidth=null,this.lockedHeight=null,this.widthIsNumeric=!1,this.heightIsNumeric=!1,this.shiftHeld=!1,this.expressionInput.hide()}handleMouseDown(e){this.downX=e.clientX,this.downY=e.clientY}handleMouseUp(e){let t=e.clientX-this.downX,n=e.clientY-this.downY;if(t*t+n*n>64)return;let r=Tp(this.ctx,this.plane,e.clientX,e.clientY);if(!r)return;let i=Y(this.snapController.snap(r).point2d);if(!this.startPoint){this.startPoint=i,this.syncModifiers(e),this.rebuildPreview();return}if(this.expressionInput.isVisible)this.expressionInput.commitCurrentValue();else if(this.expressionPhase===`width`||this.expressionPhase===`height`)this.commitDimensionsFromGeometry(i);else if(this.expressionPhase===`radius`){let e=this.computeRadiusFromMouse(i);this.commitRoundedRect(this.startPoint,this.widthExpression,this.heightExpression,{expression:String(e)}),this.resetState(),this.rebuildPreview()}}handleMouseMove(e){this.lastClientX=e.clientX,this.lastClientY=e.clientY,this.syncModifiers(e);let t=Tp(this.ctx,this.plane,e.clientX,e.clientY);if(!t){this.mousePoint=null,this.lastSnapType=`none`,this.rebuildPreview();return}let n=this.snapController.snap(t);this.mousePoint=n.point2d,this.lastSnapType=n.snapType,this.rebuildPreview(),this.updateDimensionInput()}handleKeyDown(e){if(e.key===`Escape`){this.startPoint&&(this.resetState(),this.rebuildPreview());return}e.key===`Shift`&&(this.shiftHeld=!0,this.rebuildPreview())}handleKeyUp(e){e.key===`Shift`&&(this.shiftHeld=!1,this.rebuildPreview())}syncModifiers(e){this.shiftHeld=e.shiftKey}computeDimensions(e){let t=this.startPoint;if(this.shiftHeld){let n=e[0]-t[0],r=e[1]-t[1];return{width:Math.round(n*2*100)/100,height:Math.round(r*2*100)/100}}return{width:Math.round((e[0]-t[0])*100)/100,height:Math.round((e[1]-t[1])*100)/100}}computePreviewCorners(e){let t=this.startPoint,n=this.lockedWidth!==null,r=this.lockedHeight!==null;if(n&&r)return this.getLockedPreviewCorners();if(n){if(this.shiftHeld){let n=this.lockedWidth/2,r=e[1]-t[1];return{c1:[t[0]-n,t[1]-r],c2:[t[0]+n,t[1]+r]}}let n=e[0]>=t[0]?1:-1;return{c1:t,c2:[t[0]+n*this.lockedWidth,e[1]]}}if(this.shiftHeld){let n=e[0]-t[0],r=e[1]-t[1];return{c1:[t[0]-n,t[1]-r],c2:[t[0]+n,t[1]+r]}}return{c1:t,c2:e}}getLockedPreviewCorners(){if(!this.startPoint||this.lockedWidth===null||this.lockedHeight===null)return null;if(this.shiftHeld){let e=this.lockedWidth/2,t=this.lockedHeight/2;return{c1:[this.startPoint[0]-e,this.startPoint[1]-t],c2:[this.startPoint[0]+e,this.startPoint[1]+t]}}let e=this.mousePoint?this.mousePoint[0]>=this.startPoint[0]?1:-1:1,t=this.mousePoint?this.mousePoint[1]>=this.startPoint[1]?1:-1:1;return{c1:this.startPoint,c2:[this.startPoint[0]+e*this.lockedWidth,this.startPoint[1]+t*this.lockedHeight]}}computeRadiusFromMouse(e){let t=this.getLockedPreviewCorners();if(!t)return 0;let{c1:n,c2:r}=t,i=[[n[0],n[1]],[r[0],n[1]],[r[0],r[1]],[n[0],r[1]]],a=1/0;for(let t of i){let n=Ap(e,t);n<a&&(a=n)}let o=Math.min(Math.abs(r[0]-n[0])/2,Math.abs(r[1]-n[1])/2);return Math.round(Math.min(a,o)*100)/100}dimensionInputAnchor(){let e={clientX:this.lastClientX,clientY:this.lastClientY};if(!this.startPoint||!this.mousePoint)return e;if(this.expressionPhase===`radius`){let t=this.getLockedPreviewCorners();if(!t)return e;let{c1:n,c2:r}=t;return Dp(this.ctx,this.plane,[(n[0]+r[0])/2,(n[1]+r[1])/2])}let{c1:t,c2:n}=this.computePreviewCorners(this.mousePoint),r=this.expressionPhase===`width`?[(t[0]+n[0])/2,t[1]]:[n[0],(t[1]+n[1])/2];return Dp(this.ctx,this.plane,r)}updateDimensionInput(){if(!this.startPoint||!this.mousePoint)return;let e=this.dimensionInputAnchor();if(this.expressionPhase===`width`){let{width:t}=this.computeDimensions(this.mousePoint),n=Math.round(Math.abs(t)*100)/100;if(n<=0)return;this.expressionInput.isVisible?(this.expressionInput.updateValue(n),this.expressionInput.updatePosition(e.clientX,e.clientY)):this.expressionInput.show({label:`W`,value:String(n),clientX:e.clientX,clientY:e.clientY,variables:this.cachedVariables,onCommit:e=>this.onWidthCommit(e)})}else if(this.expressionPhase===`height`){let{height:t}=this.computeDimensions(this.mousePoint),n=Math.round(Math.abs(t)*100)/100,r=t>=0?1:-1;this.expressionInput.isVisible?(this.expressionInput.updateValue(n),this.expressionInput.updatePosition(e.clientX,e.clientY)):this.expressionInput.show({label:`H`,value:String(n),clientX:e.clientX,clientY:e.clientY,variables:this.cachedVariables,onCommit:e=>this.onHeightCommit(e,r)})}else if(this.expressionPhase===`radius`){let t=this.computeRadiusFromMouse(this.mousePoint);this.expressionInput.isVisible?(this.expressionInput.updateValue(t),this.expressionInput.updatePosition(e.clientX,e.clientY)):this.expressionInput.show({label:`R`,value:String(t),clientX:e.clientX,clientY:e.clientY,variables:this.cachedVariables,onCommit:e=>this.onRadiusCommit(e)})}}onWidthCommit(e){let t=parseFloat(e.expression),n=!isNaN(t)&&String(t)===e.expression;this.widthIsNumeric=n,n?(this.widthExpression=e,this.lockedWidth=t):(this.widthExpression=e,this.lockedWidth=null),this.expressionPhase=`height`,queueMicrotask(()=>{if(this.mousePoint&&this.startPoint){let{height:e}=this.computeDimensions(this.mousePoint),t=Math.round(Math.abs(e)*100)/100,n=e>=0?1:-1,r=this.dimensionInputAnchor();this.expressionInput.show({label:`H`,value:String(t),clientX:r.clientX,clientY:r.clientY,variables:this.cachedVariables,onCommit:e=>this.onHeightCommit(e,n)})}this.rebuildPreview()})}onHeightCommit(e,t){if(!this.startPoint||!this.widthExpression)return;let n=parseFloat(e.expression),r=!isNaN(n)&&String(n)===e.expression;this.heightIsNumeric=r,r?(this.heightExpression=e,this.lockedHeight=n):(this.heightExpression=e,this.lockedHeight=null),this.expressionPhase=`radius`,queueMicrotask(()=>{if(this.mousePoint){let e=this.computeRadiusFromMouse(this.mousePoint),t=this.dimensionInputAnchor();this.expressionInput.show({label:`R`,value:String(e),clientX:t.clientX,clientY:t.clientY,variables:this.cachedVariables,onCommit:e=>this.onRadiusCommit(e)})}this.rebuildPreview()})}onRadiusCommit(e){if(!this.startPoint||!this.widthExpression||!this.heightExpression)return;let t=this.resolveSignedExpression(this.widthExpression,this.widthIsNumeric,this.lockedWidth,0),n=this.resolveSignedExpression(this.heightExpression,this.heightIsNumeric,this.lockedHeight,1);this.commitRoundedRect(this.startPoint,t,n,e),this.resetState(),this.rebuildPreview()}resolveSignedExpression(e,t,n,r){if(!t||n===null||!this.mousePoint||!this.startPoint||this.shiftHeld)return e;let i=r===0?this.mousePoint[0]>=this.startPoint[0]?1:-1:this.mousePoint[1]>=this.startPoint[1]?1:-1,a=Math.round(i*n*100)/100;return{expression:String(a),newVariable:e.newVariable}}commitDimensionsFromGeometry(e){if(!this.startPoint)return;let{width:t,height:n}=this.computeDimensions(e);if(!(t===0||n===0)){if(this.widthExpression={expression:String(t)},this.lockedWidth=Math.abs(t),this.widthIsNumeric=!0,this.heightExpression={expression:String(n)},this.lockedHeight=Math.abs(n),this.heightIsNumeric=!0,this.expressionPhase=`radius`,this.expressionInput.hide(),this.mousePoint){let e=this.computeRadiusFromMouse(this.mousePoint),t=this.dimensionInputAnchor();this.expressionInput.show({label:`R`,value:String(e),clientX:t.clientX,clientY:t.clientY,variables:this.cachedVariables,onCommit:e=>this.onRadiusCommit(e)})}this.rebuildPreview()}}commitRoundedRect(e,t,n,r){let i=this.isAtCurrentPosition(e),a;a=i?`rect(${t.expression}, ${n.expression})`:`rect(${this.formatPoint(e)}, ${t.expression}, ${n.expression})`,a+=`.radius(${r.expression})`,this.shiftHeld&&(a+=`.centered()`);let o=t.newVariable??n.newVariable??r.newVariable;this.insertGeometry(a,o)}rebuildPreview(){this.disposePreview();let e=this.ctx.camera,t=new R(this.plane.normal.x,this.plane.normal.y,this.plane.normal.z);if(this.startPoint){if(Q(this.previewGroup,this.startPoint,X,e,t,this.plane),this.expressionPhase===`radius`){let e=this.getLockedPreviewCorners();if(e){let t=this.mousePoint?this.computeRadiusFromMouse(this.mousePoint):0;t>0?iv(this.previewGroup,e.c1,e.c2,t,this.plane):nv(this.previewGroup,e.c1,e.c2,this.plane)}}else if(this.mousePoint){let{c1:e,c2:t}=this.computePreviewCorners(this.mousePoint);nv(this.previewGroup,e,t,this.plane)}}else if(this.mousePoint&&this.lastSnapType!==`none`){let n=this.lastSnapType===`vertex`?Z:X_;Q(this.previewGroup,this.mousePoint,n,e,t,this.plane,.6)}this.requestRender()}},Dv=class extends V_{id=`slot`;label=`Slot`;icon=eg;startPoint=null;endPoint=null;mousePoint=null;lastSnapType=`none`;shiftHeld=!1;horizontalMode=!1;expressionInput;fetchVariables;cachedVariables=[];lastClientX=0;lastClientY=0;expressionPhase=`endpoint`;distanceExpression=null;lockedDistance=null;boundMouseDown;boundMouseUp;boundMouseMove;boundKeyDown;boundKeyUp;downX=0;downY=0;constructor(e,t,n,r,i,a){super(e,t,n,r),this.expressionInput=new J_(i),this.fetchVariables=a,this.boundMouseDown=this.handleMouseDown.bind(this),this.boundMouseUp=this.handleMouseUp.bind(this),this.boundMouseMove=this.handleMouseMove.bind(this),this.boundKeyDown=this.handleKeyDown.bind(this),this.boundKeyUp=this.handleKeyUp.bind(this)}activate(){this.addPreviewToScene(),this.canvas.addEventListener(`mousedown`,this.boundMouseDown),this.canvas.addEventListener(`mouseup`,this.boundMouseUp),this.canvas.addEventListener(`mousemove`,this.boundMouseMove),window.addEventListener(`keydown`,this.boundKeyDown),window.addEventListener(`keyup`,this.boundKeyUp),this.fetchVariables().then(e=>{this.cachedVariables=e})}deactivate(){this.canvas.removeEventListener(`mousedown`,this.boundMouseDown),this.canvas.removeEventListener(`mouseup`,this.boundMouseUp),this.canvas.removeEventListener(`mousemove`,this.boundMouseMove),window.removeEventListener(`keydown`,this.boundKeyDown),window.removeEventListener(`keyup`,this.boundKeyUp),this.resetState(),this.removePreviewFromScene()}onSceneUpdate(e,t){let n=v_.fromSceneObjects(e,t,this.plane,this.ctx);this.updateSnapManager(n),this.fetchVariables().then(e=>{this.cachedVariables=e})}handleEscape(){return this.startPoint?this.expressionPhase===`radius`?(this.expressionPhase=this.horizontalMode?`distance`:`endpoint`,this.endPoint=null,this.distanceExpression=null,this.lockedDistance=null,this.expressionInput.hide(),this.rebuildPreview(),!0):this.expressionPhase===`distance`?(this.expressionPhase=`endpoint`,this.horizontalMode=!1,this.expressionInput.hide(),this.rebuildPreview(),!0):(this.resetState(),this.rebuildPreview(),!0):!1}resetState(){this.startPoint=null,this.endPoint=null,this.mousePoint=null,this.expressionPhase=`endpoint`,this.horizontalMode=!1,this.distanceExpression=null,this.lockedDistance=null,this.expressionInput.hide()}handleMouseDown(e){this.downX=e.clientX,this.downY=e.clientY}handleMouseUp(e){let t=e.clientX-this.downX,n=e.clientY-this.downY;if(t*t+n*n>64)return;let r=Tp(this.ctx,this.plane,e.clientX,e.clientY);if(!r)return;let i=Y(this.snapController.snap(r).point2d);if(!this.startPoint){this.startPoint=i,this.syncModifiers(e),this.shiftHeld&&(this.horizontalMode=!0,this.expressionPhase=`distance`),this.rebuildPreview();return}if(this.expressionInput.isVisible){this.expressionInput.commitCurrentValue();return}if(this.expressionPhase===`endpoint`){if(Ap(this.startPoint,i)<=0)return;this.endPoint=i,this.expressionPhase=`radius`,this.expressionInput.hide(),this.rebuildPreview(),this.updateDimensionInput();return}if(this.expressionPhase===`distance`){let e=Math.round((i[0]-this.startPoint[0])*100)/100;if(e===0)return;this.onDistanceCommit({expression:String(e)});return}if(this.expressionPhase===`radius`){let e=this.computeRadiusFromMouse(i);if(e<=0)return;this.onRadiusCommit({expression:String(e)})}}handleMouseMove(e){this.lastClientX=e.clientX,this.lastClientY=e.clientY,this.syncModifiers(e);let t=Tp(this.ctx,this.plane,e.clientX,e.clientY);if(!t){this.mousePoint=null,this.lastSnapType=`none`,this.rebuildPreview();return}let n=this.snapController.snap(t);this.mousePoint=n.point2d,this.lastSnapType=n.snapType,this.rebuildPreview(),this.updateDimensionInput()}handleKeyDown(e){if(e.key===`Escape`){this.handleEscape()&&e.stopPropagation();return}e.key===`Shift`&&(this.shiftHeld=!0,this.startPoint&&this.expressionPhase===`endpoint`&&!this.horizontalMode&&(this.horizontalMode=!0,this.expressionPhase=`distance`,this.expressionInput.hide()),this.rebuildPreview(),this.updateDimensionInput())}handleKeyUp(e){e.key===`Shift`&&(this.shiftHeld=!1,this.expressionPhase===`distance`&&!this.distanceExpression&&(this.horizontalMode=!1,this.expressionPhase=`endpoint`,this.expressionInput.hide()),this.rebuildPreview(),this.updateDimensionInput())}syncModifiers(e){this.shiftHeld=e.shiftKey}getSlotAxis(){if(!this.startPoint)return null;if(this.horizontalMode){let e=this.lockedDistance??(this.mousePoint?this.mousePoint[0]-this.startPoint[0]:0);return{dir:e>=0?[1,0]:[-1,0],leftCenter:this.startPoint,rightCenter:[this.startPoint[0]+e,this.startPoint[1]]}}if(this.endPoint){let e=this.endPoint[0]-this.startPoint[0],t=this.endPoint[1]-this.startPoint[1],n=Math.sqrt(e*e+t*t);return n<1e-10?null:{dir:[e/n,t/n],leftCenter:this.startPoint,rightCenter:this.endPoint}}if(this.mousePoint){let e=this.mousePoint[0]-this.startPoint[0],t=this.mousePoint[1]-this.startPoint[1],n=Math.sqrt(e*e+t*t);return n<1e-10?null:{dir:[e/n,t/n],leftCenter:this.startPoint,rightCenter:this.mousePoint}}return null}computeRadiusFromMouse(e){let t=this.getSlotAxis();if(!t)return 0;let n=e[0]-t.leftCenter[0],r=e[1]-t.leftCenter[1],i=Math.abs(-t.dir[1]*n+t.dir[0]*r);return Math.round(i*100)/100}updateDimensionInput(){if(!(!this.startPoint||!this.mousePoint)){if(this.expressionPhase===`distance`){let e=Math.round((this.mousePoint[0]-this.startPoint[0])*100)/100;if(e===0)return;this.expressionInput.isVisible?(this.expressionInput.updateValue(e),this.expressionInput.updatePosition(this.lastClientX,this.lastClientY)):this.expressionInput.show({label:`D`,value:String(e),clientX:this.lastClientX,clientY:this.lastClientY,variables:this.cachedVariables,onCommit:e=>this.onDistanceCommit(e)});return}if(this.expressionPhase===`radius`){let e=this.computeRadiusFromMouse(this.mousePoint);if(e<=0)return;this.expressionInput.isVisible?(this.expressionInput.updateValue(e),this.expressionInput.updatePosition(this.lastClientX,this.lastClientY)):this.expressionInput.show({label:`R`,value:String(e),clientX:this.lastClientX,clientY:this.lastClientY,variables:this.cachedVariables,onCommit:e=>this.onRadiusCommit(e)})}}}onDistanceCommit(e){let t=parseFloat(e.expression),n=!isNaN(t)&&String(t)===e.expression;this.distanceExpression=e,this.lockedDistance=n?t:null,this.expressionPhase=`radius`,queueMicrotask(()=>{if(this.mousePoint){let e=this.computeRadiusFromMouse(this.mousePoint);this.expressionInput.show({label:`R`,value:String(e),clientX:this.lastClientX,clientY:this.lastClientY,variables:this.cachedVariables,onCommit:e=>this.onRadiusCommit(e)})}this.rebuildPreview()})}onRadiusCommit(e){this.startPoint&&(this.horizontalMode&&this.distanceExpression?this.commitHorizontalSlot(this.startPoint,this.distanceExpression,e):this.endPoint&&this.commitTwoPointSlot(this.startPoint,this.endPoint,e),this.resetState(),this.rebuildPreview())}commitTwoPointSlot(e,t,n){let r=`slot(${this.formatPoint(e)}, ${this.formatPoint(t)}, ${n.expression})`;this.insertGeometry(r,n.newVariable)}commitHorizontalSlot(e,t,n){let r=this.isAtCurrentPosition(e)?`slot(${t.expression}, ${n.expression})`:`slot(${this.formatPoint(e)}, ${t.expression}, ${n.expression})`,i=t.newVariable??n.newVariable;this.insertGeometry(r,i)}rebuildPreview(){this.disposePreview();let e=this.ctx.camera,t=new R(this.plane.normal.x,this.plane.normal.y,this.plane.normal.z);if(this.startPoint){Q(this.previewGroup,this.startPoint,X,e,t,this.plane);let n=this.getSlotAxis();if(n){let r=Ap(n.leftCenter,n.rightCenter);if(r>0)if(this.expressionPhase===`radius`&&this.mousePoint){let r=this.computeRadiusFromMouse(this.mousePoint);r>0?uv(this.previewGroup,n.leftCenter,n.rightCenter,r,this.plane):ev(this.previewGroup,n.leftCenter,n.rightCenter,this.plane),Q(this.previewGroup,n.rightCenter,X,e,t,this.plane)}else uv(this.previewGroup,n.leftCenter,n.rightCenter,r/6,this.plane),Q(this.previewGroup,n.rightCenter,Z,e,t,this.plane)}}else if(this.mousePoint&&this.lastSnapType!==`none`){let n=this.lastSnapType===`vertex`?Z:X_;Q(this.previewGroup,this.mousePoint,n,e,t,this.plane,.6)}this.requestRender()}},Ov={line:`Line`,hLine:`H-Line`,vLine:`V-Line`,arc:`Arc`,tArc:`T-Arc`,tLine:`T-Line`},kv=class{el;labelSpan;constructor(e){this.el=document.createElement(`div`),this.el.className=`absolute z-[999] pointer-events-none hidden`;let t=document.createElement(`div`);t.className=`panel-bg border border-base-content/10 rounded-md px-2 py-0.5 shadow-sm flex items-center gap-1.5`,this.labelSpan=document.createElement(`span`),this.labelSpan.className=`text-xs font-mono text-base-content/70`;let n=document.createElement(`span`);n.className=`text-[10px] text-base-content/30`,n.textContent=`Space`,t.appendChild(this.labelSpan),t.appendChild(n),this.el.appendChild(t),e.appendChild(this.el)}show(e){this.labelSpan.textContent=Ov[e],this.el.classList.remove(`hidden`)}hide(){this.el.classList.add(`hidden`)}update(e){this.labelSpan.textContent=Ov[e]}updatePosition(e,t){this.el.style.left=`${e+16}px`,this.el.style.top=`${t+16}px`}dispose(){this.el.remove()}},Av=class{id=`line`;label=`Line`;requiresTangent=!1;mousePoint=null;lastSnapType=`none`;enter(e){this.mousePoint=null,this.lastSnapType=`none`}exit(e){this.mousePoint=null}handleClick(e,t,n){let r=Y(n.startPoint),i=Y(e),a=n.isAtCurrentPosition(r)?`line(${n.formatPoint(i)})`:`line(${n.formatPoint(r)}, ${n.formatPoint(i)})`;n.insertGeometry(a);let o=i[0]-r[0],s=i[1]-r[1],c=Math.sqrt(o*o+s*s);return{kind:`committed`,result:{endpoint:i,exitTangent:c>1e-10?{direction:[o/c,s/c],point:i}:null}}}handleMouseMove(e,t,n,r,i){this.mousePoint=e,this.lastSnapType=t.snapType}handleEscape(e){return!1}rebuildPreview(e){if(Q(e.previewGroup,e.startPoint,X,e.camera,e.planeNormal,e.plane),this.mousePoint&&(ev(e.previewGroup,e.startPoint,this.mousePoint,e.plane),this.lastSnapType!==`none`)){let t=this.lastSnapType===`vertex`?Z:X_;Q(e.previewGroup,this.mousePoint,t,e.camera,e.planeNormal,e.plane,.6)}}},jv=class{id;label;requiresTangent=!1;axis;mousePoint=null;lastSnapType=`none`;constructor(e){this.axis=e,this.id=e===`h`?`hLine`:`vLine`,this.label=e===`h`?`H-Line`:`V-Line`}enter(e){this.mousePoint=null,this.lastSnapType=`none`}exit(e){this.mousePoint=null,e.hideExpressionInput()}getEffectiveEnd(e,t){return this.axis===`h`?[t[0],e[1]]:[e[0],t[1]]}getDistance(e,t){return this.axis===`h`?t[0]-e[0]:t[1]-e[1]}handleClick(e,t,n){if(n.isExpressionVisible())return n.commitExpressionValue(),{kind:`ignored`};let r=Y(n.startPoint),i=this.getDistance(r,e),a=Math.round(i*100)/100;if(a===0)return{kind:`ignored`};let o=n.isAtCurrentPosition(r),s=this.axis===`h`?`hLine`:`vLine`,c=o?`${s}(${a})`:`${s}(${n.formatPoint(r)}, ${a})`;n.insertGeometry(c),n.hideExpressionInput();let l=Y(this.axis===`h`?[r[0]+a,r[1]]:[r[0],r[1]+a]);return{kind:`committed`,result:{endpoint:l,exitTangent:{direction:this.axis===`h`?[Math.sign(a)||1,0]:[0,Math.sign(a)||1],point:l}}}}handleMouseMove(e,t,n,r,i){this.mousePoint=e,this.lastSnapType=t.snapType;let a=Math.abs(this.getDistance(i.startPoint,e)),o=this.axis===`h`?`H:`:`V:`;i.isExpressionVisible()?(i.updateExpressionValue(a),i.updateExpressionPosition(n,r)):i.showExpressionInput({label:o,value:String(Math.round(a*100)/100),clientX:n,clientY:r,onCommit:e=>this.commitWithDimension(e,i)})}handleEscape(e){return e.isExpressionVisible()?(e.hideExpressionInput(),!0):!1}commitWithDimension(e,t){let n=Y(t.startPoint);if(!this.mousePoint)return;let{expression:r,newVariable:i}=e,a=this.getDistance(n,this.mousePoint),o=Math.sign(a),s=parseFloat(r),c=!isNaN(s)&&String(s)===r?String(Math.round(o*s*100)/100):r,l=t.isAtCurrentPosition(n),u=this.axis===`h`?`hLine`:`vLine`,d=l?`${u}(${c})`:`${u}(${t.formatPoint(n)}, ${c})`;t.insertGeometry(d,i),t.hideExpressionInput();let f=parseFloat(c),p=isNaN(f)?Math.round(o*Math.abs(this.getDistance(n,this.mousePoint))*100)/100:f,m=this.axis===`h`?[n[0]+p,n[1]]:[n[0],n[1]+p],h=this.axis===`h`?[Math.sign(p)||1,0]:[0,Math.sign(p)||1];t.onSegmentCommitted({endpoint:Y(m),exitTangent:{direction:h,point:Y(m)}})}rebuildPreview(e){if(Q(e.previewGroup,e.startPoint,X,e.camera,e.planeNormal,e.plane),this.mousePoint){let t=this.getEffectiveEnd(e.startPoint,this.mousePoint);if(ev(e.previewGroup,e.startPoint,t,e.plane),this.lastSnapType!==`none`){let n=this.lastSnapType===`vertex`?Z:X_;Q(e.previewGroup,t,n,e.camera,e.planeNormal,e.plane,.6)}}}},Mv=function(e){return e[e.AWAITING_END=0]=`AWAITING_END`,e[e.AWAITING_THROUGH=1]=`AWAITING_THROUGH`,e}(Mv||{}),Nv=class{id=`arc`;label=`Arc`;requiresTangent=!1;subState=Mv.AWAITING_END;endPoint=null;mousePoint=null;lastSnapType=`none`;enter(e){this.subState=Mv.AWAITING_END,this.endPoint=null,this.mousePoint=null,this.lastSnapType=`none`}exit(e){this.subState=Mv.AWAITING_END,this.endPoint=null,this.mousePoint=null}handleClick(e,t,n){if(this.subState===Mv.AWAITING_END)return Ap(n.startPoint,e)<1e-6?{kind:`ignored`}:(this.endPoint=e,this.subState=Mv.AWAITING_THROUGH,{kind:`consumed`});if(!this.endPoint)return{kind:`ignored`};let r=pv(n.startPoint,this.endPoint,e);if(!r)return{kind:`ignored`};let i=this.isMouseCCW(n.startPoint,this.endPoint,e,r),a=Y(n.startPoint),o=Y(this.endPoint),s=Y(r),c=i?``:`.cw()`,l=n.isAtCurrentPosition(a)?`arc(${n.formatPoint(o)}).center(${n.formatPoint(s)})${c}`:`arc(${n.formatPoint(a)}, ${n.formatPoint(o)}).center(${n.formatPoint(s)})${c}`;return n.insertGeometry(l),{kind:`committed`,result:{endpoint:o,exitTangent:this.computeExitTangent(o,s,i)}}}handleMouseMove(e,t,n,r,i){this.mousePoint=e,this.lastSnapType=t.snapType}handleEscape(e){return this.subState===Mv.AWAITING_THROUGH?(this.endPoint=null,this.subState=Mv.AWAITING_END,!0):!1}isMouseCCW(e,t,n,r){let i=dv(r,e),a=dv(r,t),o=dv(r,n)-i;o<0&&(o+=Math.PI*2);let s=a-i;return s<0&&(s+=Math.PI*2),o<s}semicirclePreview(e,t){let n=t[0]-e[0],r=t[1]-e[1],i=Math.sqrt(n*n+r*r);if(i<1e-6)return null;let a=[(e[0]+t[0])/2,(e[1]+t[1])/2];return{center:a,radius:i/2,startAngle:dv(a,e),endAngle:dv(a,t)}}computeExitTangent(e,t,n){let r=e[0]-t[0],i=e[1]-t[1],a=Math.sqrt(r*r+i*i);return a<1e-10?null:{direction:[n?-i/a:i/a,n?r/a:-r/a],point:e}}rebuildPreview(e){if(Q(e.previewGroup,e.startPoint,X,e.camera,e.planeNormal,e.plane),this.subState===Mv.AWAITING_END){if(this.mousePoint){let t=this.semicirclePreview(e.startPoint,this.mousePoint);if(t&&ov(e.previewGroup,t.center,t.radius,t.startAngle,t.endAngle,!0,e.plane),this.lastSnapType!==`none`){let t=this.lastSnapType===`vertex`?Z:X_;Q(e.previewGroup,this.mousePoint,t,e.camera,e.planeNormal,e.plane,.6)}}}else if(this.endPoint&&(Q(e.previewGroup,this.endPoint,X,e.camera,e.planeNormal,e.plane),ev(e.previewGroup,e.startPoint,this.endPoint,e.plane),this.mousePoint)){let t=pv(e.startPoint,this.endPoint,this.mousePoint);if(t){let n=Ap(t,e.startPoint),r=dv(t,e.startPoint),i=dv(t,this.endPoint),a=this.isMouseCCW(e.startPoint,this.endPoint,this.mousePoint,t);ov(e.previewGroup,t,n,r,i,a,e.plane)}if(this.lastSnapType!==`none`){let t=this.lastSnapType===`vertex`?Z:X_;Q(e.previewGroup,this.mousePoint,t,e.camera,e.planeNormal,e.plane,.6)}}}},Pv=class{id=`tArc`;label=`T-Arc`;requiresTangent=!0;mousePoint=null;lastSnapType=`none`;enter(e){this.mousePoint=null,this.lastSnapType=`none`}exit(e){this.mousePoint=null}handleClick(e,t,n){if(!n.tangent)return{kind:`ignored`};let r=Y(e);n.insertGeometry(`tArc(${n.formatPoint(r)})`);let i=this.computeArcPreview(n.startPoint,e,n.tangent.direction),a=null;if(i){let e=r[0]-i.center[0],t=r[1]-i.center[1],n=Math.sqrt(e*e+t*t);n>1e-10&&(a={direction:[i.ccw?-t/n:t/n,i.ccw?e/n:-e/n],point:r})}return{kind:`committed`,result:{endpoint:r,exitTangent:a}}}handleMouseMove(e,t,n,r,i){this.mousePoint=e,this.lastSnapType=t.snapType}handleEscape(e){return!1}computeArcPreview(e,t,n){let r=-n[1],i=n[0],a=e[0]-t[0],o=e[1]-t[1],s=a*a+o*o,c=a*r+o*i;if(Math.abs(c)<1e-10)return null;let l=-s/(2*c),u=Math.abs(l),d=[e[0]+r*l,e[1]+i*l];return{center:d,radius:u,startAngle:dv(d,e),endAngle:dv(d,t),ccw:l>=0}}rebuildPreview(e){if(e.tangent&&(Q(e.previewGroup,e.startPoint,X,e.camera,e.planeNormal,e.plane),this.mousePoint)){let t=this.computeArcPreview(e.startPoint,this.mousePoint,e.tangent.direction);if(t&&ov(e.previewGroup,t.center,t.radius,t.startAngle,t.endAngle,t.ccw,e.plane),this.lastSnapType!==`none`){let t=this.lastSnapType===`vertex`?Z:X_;Q(e.previewGroup,this.mousePoint,t,e.camera,e.planeNormal,e.plane,.6)}}}},Fv=class{id=`tLine`;label=`T-Line`;requiresTangent=!0;mousePoint=null;enter(e){this.mousePoint=null}exit(e){this.mousePoint=null,e.hideExpressionInput()}projectOnTangent(e,t,n){let r=t[0]-e[0],i=t[1]-e[1],a=r*n[0]+i*n[1];return{projected:[e[0]+n[0]*a,e[1]+n[1]*a],distance:a}}handleClick(e,t,n){if(!n.tangent)return{kind:`ignored`};if(n.isExpressionVisible())return n.commitExpressionValue(),{kind:`ignored`};if(!this.mousePoint)return{kind:`ignored`};let{distance:r}=this.projectOnTangent(n.startPoint,this.mousePoint,n.tangent.direction),i=Math.round(r*100)/100;if(i===0)return{kind:`ignored`};n.insertGeometry(`tLine(${i})`),n.hideExpressionInput();let a=Y([n.startPoint[0]+n.tangent.direction[0]*r,n.startPoint[1]+n.tangent.direction[1]*r]);return{kind:`committed`,result:{endpoint:a,exitTangent:{direction:n.tangent.direction,point:a}}}}handleMouseMove(e,t,n,r,i){if(this.mousePoint=e,!i.tangent)return;let{distance:a}=this.projectOnTangent(i.startPoint,e,i.tangent.direction),o=Math.abs(a);i.isExpressionVisible()?(i.updateExpressionValue(o),i.updateExpressionPosition(n,r)):i.showExpressionInput({label:`T:`,value:String(Math.round(o*100)/100),clientX:n,clientY:r,onCommit:e=>this.commitWithDimension(e,i)})}handleEscape(e){return e.isExpressionVisible()?(e.hideExpressionInput(),!0):!1}commitWithDimension(e,t){if(!t.tangent||!this.mousePoint)return;let{expression:n,newVariable:r}=e,{distance:i}=this.projectOnTangent(t.startPoint,this.mousePoint,t.tangent.direction),a=Math.sign(i),o=parseFloat(n),s=!isNaN(o)&&String(o)===n?String(Math.round(a*o*100)/100):n;t.insertGeometry(`tLine(${s})`,r),t.hideExpressionInput();let c=Y([t.startPoint[0]+t.tangent.direction[0]*i,t.startPoint[1]+t.tangent.direction[1]*i]);t.onSegmentCommitted({endpoint:c,exitTangent:{direction:t.tangent.direction,point:c}})}rebuildPreview(e){if(e.tangent&&(Q(e.previewGroup,e.startPoint,X,e.camera,e.planeNormal,e.plane),this.mousePoint)){let{projected:t}=this.projectOnTangent(e.startPoint,this.mousePoint,e.tangent.direction);ev(e.previewGroup,e.startPoint,t,e.plane)}}},Iv=function(e){return e[e.IDLE=0]=`IDLE`,e[e.DRAWING=1]=`DRAWING`,e}({}),Lv=[`line`,`hLine`,`vLine`,`arc`,`tArc`,`tLine`],Rv=class extends V_{id=`polyline`;label=`Polyline`;icon=ng;phase=Iv.IDLE;startPoint=null;currentModeIndex=0;tangent=null;modes;expressionInput;fetchVariables;cachedVariables=[];modeIndicator;sceneObjects=[];sketchId=``;mousePoint=null;lastSnapType=`none`;lastSnapResult=null;lastClientX=0;lastClientY=0;boundMouseDown;boundMouseUp;boundMouseMove;boundKeyDown;downX=0;downY=0;constructor(e,t,n,r,i,a){super(e,t,n,r),this.expressionInput=new J_(i),this.fetchVariables=a,this.modeIndicator=new kv(i),this.modes=[new Av,new jv(`h`),new jv(`v`),new Nv,new Pv,new Fv],this.boundMouseDown=this.handleMouseDown.bind(this),this.boundMouseUp=this.handleMouseUp.bind(this),this.boundMouseMove=this.handleMouseMove.bind(this),this.boundKeyDown=this.handleKeyDown.bind(this),this.expressionInput.onSpaceOverride=()=>{this.cycleMode(1)}}get currentMode(){return this.modes[this.currentModeIndex]}activate(){this.addPreviewToScene(),this.canvas.addEventListener(`mousedown`,this.boundMouseDown),this.canvas.addEventListener(`mouseup`,this.boundMouseUp),this.canvas.addEventListener(`mousemove`,this.boundMouseMove),window.addEventListener(`keydown`,this.boundKeyDown),this.fetchVariables().then(e=>{this.cachedVariables=e}),this.modeIndicator.show(this.currentMode.id)}deactivate(){this.canvas.removeEventListener(`mousedown`,this.boundMouseDown),this.canvas.removeEventListener(`mouseup`,this.boundMouseUp),this.canvas.removeEventListener(`mousemove`,this.boundMouseMove),window.removeEventListener(`keydown`,this.boundKeyDown),this.expressionInput.hide(),this.modeIndicator.dispose(),this.phase=Iv.IDLE,this.startPoint=null,this.tangent=null,this.removePreviewFromScene()}onSceneUpdate(e,t){this.sceneObjects=e,this.sketchId=t;let n=v_.fromSceneObjects(e,t,this.plane,this.ctx);this.updateSnapManager(n),this.fetchVariables().then(e=>{this.cachedVariables=e}),this.phase===Iv.DRAWING&&this.startPoint&&this.updateTangentFromScene()}handleEscape(){return!1}buildModeContext(){if(!this.startPoint)return null;let e=new R(this.plane.normal.x,this.plane.normal.y,this.plane.normal.z);return{plane:this.plane,previewGroup:this.previewGroup,camera:this.ctx.camera,planeNormal:e,tangent:this.tangent,sceneObjects:this.sceneObjects,sketchId:this.sketchId,startPoint:this.startPoint,isAtCurrentPosition:e=>this.isAtCurrentPosition(e),formatPoint:e=>this.formatPoint(e),insertGeometry:(e,t)=>this.insertGeometry(e,t),requestRender:()=>this.requestRender(),showExpressionInput:e=>{this.expressionInput.isVisible||this.expressionInput.show({...e,variables:this.cachedVariables})},updateExpressionValue:e=>this.expressionInput.updateValue(e),updateExpressionPosition:(e,t)=>this.expressionInput.updatePosition(e,t),hideExpressionInput:()=>this.expressionInput.hide(),isExpressionVisible:()=>this.expressionInput.isVisible,commitExpressionValue:()=>this.expressionInput.commitCurrentValue(),onSegmentCommitted:e=>this.handleModeCommit(e)}}handleModeCommit(e){let{endpoint:t,exitTangent:n}=e;this.startPoint=t,this.tangent=n,this.currentMode.requiresTangent&&!this.tangent&&(this.advanceToNextValidMode(),this.modeIndicator.update(this.currentMode.id));let r=this.buildModeContext();this.currentMode.enter(r),this.rebuildPreview()}handleMouseDown(e){this.downX=e.clientX,this.downY=e.clientY}handleMouseUp(e){let t=e.clientX-this.downX,n=e.clientY-this.downY;if(t*t+n*n>64)return;let r=Tp(this.ctx,this.plane,e.clientX,e.clientY);if(!r)return;let i=this.snapController.snap(r),a=Y(i.point2d);if(this.phase===Iv.IDLE){this.startPoint=a,this.phase=Iv.DRAWING,this.tangent=this.findTangentAtPoint(a),this.currentMode.requiresTangent&&!this.tangent&&this.advanceToNextValidMode();let e=this.buildModeContext();this.currentMode.enter(e),this.modeIndicator.update(this.currentMode.id),this.rebuildPreview();return}let o=this.buildModeContext();if(!o)return;let s=this.currentMode.handleClick(a,i,o);s.kind===`committed`?this.handleModeCommit(s.result):this.rebuildPreview()}handleMouseMove(e){this.lastClientX=e.clientX,this.lastClientY=e.clientY;let t=Tp(this.ctx,this.plane,e.clientX,e.clientY);if(!t){this.mousePoint=null,this.lastSnapType=`none`,this.rebuildPreview();return}let n=this.snapController.snap(t);if(this.mousePoint=n.point2d,this.lastSnapType=n.snapType,this.lastSnapResult=n,this.modeIndicator.updatePosition(e.clientX,e.clientY),this.phase===Iv.DRAWING){let t=this.buildModeContext();t&&this.currentMode.handleMouseMove(n.point2d,n,e.clientX,e.clientY,t)}this.rebuildPreview()}handleKeyDown(e){if(e.key===` `){e.preventDefault(),this.cycleMode(e.shiftKey?-1:1);return}}cycleMode(e){let t=this.buildModeContext();t&&(this.expressionInput.hide(),this.currentMode.exit(t));let n=this.currentModeIndex;for(let t=0;t<Lv.length&&(this.currentModeIndex=(this.currentModeIndex+e+Lv.length)%Lv.length,!(!this.modes[this.currentModeIndex].requiresTangent||this.tangent||this.currentModeIndex===n));t++);if(this.modeIndicator.update(this.currentMode.id),this.phase===Iv.DRAWING){let e=this.buildModeContext();e&&(this.currentMode.enter(e),this.mousePoint&&this.lastSnapResult&&this.currentMode.handleMouseMove(this.mousePoint,this.lastSnapResult,this.lastClientX,this.lastClientY,e))}this.rebuildPreview()}advanceToNextValidMode(){let e=this.currentModeIndex;for(let t=0;t<Lv.length;t++)if(this.currentModeIndex=(this.currentModeIndex+1)%Lv.length,!this.modes[this.currentModeIndex].requiresTangent||this.tangent||this.currentModeIndex===e)return}findTangentAtPoint(e){if(!this.isAtCurrentPosition(Y(e)))return null;let t=null;for(let e of this.sceneObjects)e.parentId!==this.sketchId||!e.sourceLocation||gv.has(e.uniqueType??``)&&(t=e);if(!t)return null;for(let n of t.sceneShapes)if(!n.isMetaShape)for(let t of n.meshes){let n=_v(t.vertices,this.plane);if(n.length<2)continue;let r=vv(n,`end`);if(r)return{direction:r,point:e}}return null}updateTangentFromScene(){if(!this.startPoint||this.tangent)return;let e=this.findTangentAtPoint(this.startPoint);e&&(this.tangent=e)}rebuildPreview(){this.disposePreview();let e=new R(this.plane.normal.x,this.plane.normal.y,this.plane.normal.z);if(this.phase===Iv.DRAWING){let e=this.buildModeContext();e&&this.currentMode.rebuildPreview(e)}else if(this.mousePoint&&this.lastSnapType!==`none`){let t=this.lastSnapType===`vertex`?Z:X_;Q(this.previewGroup,this.mousePoint,t,this.ctx.camera,e,this.plane,.6)}this.requestRender()}},zv=class extends V_{id=`bezier`;label=`Bezier`;icon=rg;activeSourceLocation=null;existingPoles=[];mousePoint=null;lastSnapType=`none`;pendingFirstClick=!1;pendingStart=null;boundMouseDown;boundMouseUp;boundMouseMove;downX=0;downY=0;constructor(e,t,n,r,i,a){super(e,t,n,r),this.boundMouseDown=this.handleMouseDown.bind(this),this.boundMouseUp=this.handleMouseUp.bind(this),this.boundMouseMove=this.handleMouseMove.bind(this)}activate(){this.addPreviewToScene(),this.canvas.addEventListener(`mousedown`,this.boundMouseDown),this.canvas.addEventListener(`mouseup`,this.boundMouseUp),this.canvas.addEventListener(`mousemove`,this.boundMouseMove)}deactivate(){this.canvas.removeEventListener(`mousedown`,this.boundMouseDown),this.canvas.removeEventListener(`mouseup`,this.boundMouseUp),this.canvas.removeEventListener(`mousemove`,this.boundMouseMove),this.activeSourceLocation=null,this.existingPoles=[],this.mousePoint=null,this.lastSnapType=`none`,this.pendingFirstClick=!1,this.pendingStart=null,this.removePreviewFromScene()}handleEscape(){return!1}onSceneUpdate(e,t){let n=v_.fromSceneObjects(e,t,this.plane,this.ctx);if(this.updateSnapManager(n),!this.activeSourceLocation&&!this.pendingFirstClick){this.rebuildPreview();return}let r=null;for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.parentId===t&&i.type===`bezier`){r=i;break}}if(r&&r.sourceLocation){let e=r.object?.startPoint,t=r.object?.resolvedPoints;this.activeSourceLocation=r.sourceLocation,this.existingPoles=e?[e,...t??[]]:[],this.pendingFirstClick=!1,this.pendingStart=null}this.rebuildPreview()}handleMouseDown(e){this.downX=e.clientX,this.downY=e.clientY}handleMouseUp(e){let t=e.clientX-this.downX,n=e.clientY-this.downY;if(t*t+n*n>64||this.pendingFirstClick)return;let r=Tp(this.ctx,this.plane,e.clientX,e.clientY);if(!r)return;let i=Y(this.snapController.snap(r).point2d);if(!this.activeSourceLocation){this.insertGeometry(`bezier(${this.formatPoint(i)})`),this.pendingFirstClick=!0,this.pendingStart=i,this.rebuildPreview();return}Nm(i,this.activeSourceLocation)}handleMouseMove(e){let t=Tp(this.ctx,this.plane,e.clientX,e.clientY);if(!t){this.mousePoint=null,this.lastSnapType=`none`,this.rebuildPreview();return}let n=this.snapController.snap(t);this.mousePoint=n.point2d,this.lastSnapType=n.snapType,this.rebuildPreview()}rebuildPreview(){this.disposePreview();let e=this.ctx.camera,t=new R(this.plane.normal.x,this.plane.normal.y,this.plane.normal.z),n=[...this.existingPoles];if(n.length===0&&this.pendingStart&&n.push(this.pendingStart),this.mousePoint&&(this.activeSourceLocation||this.pendingStart)&&n.push(this.mousePoint),n.length>=2){for(let e=1;e<n.length;e++)ev(this.previewGroup,n[e-1],n[e],this.plane);cv(this.previewGroup,n,this.plane)}for(let r=0;r<n.length;r++){let i=r===0?X:Y_,a=r===0?1:.85;Q(this.previewGroup,n[r],i,e,t,this.plane,a)}this.mousePoint&&this.lastSnapType!==`none`&&Q(this.previewGroup,this.mousePoint,$_(this.lastSnapType),e,t,this.plane,.6),this.requestRender()}},Bv=3,Vv=24,Hv=6,Uv=25,Wv=class extends V_{id=`polygon`;label=`Polygon`;icon=tg;centerPoint=null;mousePoint=null;lastSnapType=`none`;expressionInput;fetchVariables;cachedVariables=[];lastClientX=0;lastClientY=0;expressionPhase=`diameter`;diameterExpression=null;lockedDiameter=null;currentSides=Hv;boundMouseDown;boundMouseUp;boundMouseMove;boundKeyDown;downX=0;downY=0;constructor(e,t,n,r,i,a){super(e,t,n,r),this.expressionInput=new J_(i),this.fetchVariables=a,this.boundMouseDown=this.handleMouseDown.bind(this),this.boundMouseUp=this.handleMouseUp.bind(this),this.boundMouseMove=this.handleMouseMove.bind(this),this.boundKeyDown=this.handleKeyDown.bind(this)}activate(){this.addPreviewToScene(),this.canvas.addEventListener(`mousedown`,this.boundMouseDown),this.canvas.addEventListener(`mouseup`,this.boundMouseUp),this.canvas.addEventListener(`mousemove`,this.boundMouseMove),window.addEventListener(`keydown`,this.boundKeyDown),this.fetchVariables().then(e=>{this.cachedVariables=e})}deactivate(){this.canvas.removeEventListener(`mousedown`,this.boundMouseDown),this.canvas.removeEventListener(`mouseup`,this.boundMouseUp),this.canvas.removeEventListener(`mousemove`,this.boundMouseMove),window.removeEventListener(`keydown`,this.boundKeyDown),this.resetState(),this.removePreviewFromScene()}onSceneUpdate(e,t){let n=v_.fromSceneObjects(e,t,this.plane,this.ctx);this.updateSnapManager(n),this.fetchVariables().then(e=>{this.cachedVariables=e})}resetState(){this.centerPoint=null,this.mousePoint=null,this.expressionPhase=`diameter`,this.diameterExpression=null,this.lockedDiameter=null,this.currentSides=Hv,this.expressionInput.hide()}sidesFromDistance(e){if(this.lockedDiameter!==null&&this.lockedDiameter>0){let t=e/(this.lockedDiameter/2);return Math.max(Bv,Math.min(Vv,Math.round(t*Hv)))}let t=kp(this.ctx,Uv);return t<=0?Hv:Math.max(Bv,Math.min(Vv,Math.round(e/t)))}handleMouseDown(e){this.downX=e.clientX,this.downY=e.clientY}handleMouseUp(e){let t=e.clientX-this.downX,n=e.clientY-this.downY;if(t*t+n*n>64)return;let r=Tp(this.ctx,this.plane,e.clientX,e.clientY);if(!r)return;let i=Y(this.snapController.snap(r).point2d);if(!this.centerPoint){this.centerPoint=i,this.rebuildPreview();return}if(this.expressionInput.isVisible){this.expressionInput.commitCurrentValue();return}if(this.expressionPhase===`diameter`){let e=Math.round(Ap(this.centerPoint,i)*2*100)/100;if(e<=0)return;this.onDiameterCommit({expression:String(e)})}else this.onSidesCommit({expression:String(this.currentSides)})}handleMouseMove(e){this.lastClientX=e.clientX,this.lastClientY=e.clientY;let t=Tp(this.ctx,this.plane,e.clientX,e.clientY);if(!t){this.mousePoint=null,this.lastSnapType=`none`,this.rebuildPreview();return}let n=this.snapController.snap(t);if(this.mousePoint=n.point2d,this.lastSnapType=n.snapType,this.centerPoint&&this.expressionPhase===`sides`){let e=Ap(this.centerPoint,this.mousePoint);this.currentSides=this.sidesFromDistance(e)}this.rebuildPreview(),this.updateDimensionInput()}handleKeyDown(e){e.key===`Escape`&&this.centerPoint&&(this.resetState(),this.rebuildPreview())}updateDimensionInput(){if(!(!this.centerPoint||!this.mousePoint))if(this.expressionPhase===`diameter`){let e=Math.round(Ap(this.centerPoint,this.mousePoint)*2*100)/100;if(e<=0)return;this.expressionInput.isVisible?(this.expressionInput.updateValue(e),this.expressionInput.updatePosition(this.lastClientX,this.lastClientY)):this.expressionInput.show({label:`⌀`,value:String(e),clientX:this.lastClientX,clientY:this.lastClientY,variables:this.cachedVariables,onCommit:e=>this.onDiameterCommit(e)})}else this.expressionInput.isVisible?(this.expressionInput.updateValue(this.currentSides),this.expressionInput.updatePosition(this.lastClientX,this.lastClientY)):this.expressionInput.show({label:`N`,value:String(this.currentSides),clientX:this.lastClientX,clientY:this.lastClientY,variables:this.cachedVariables,onCommit:e=>this.onSidesCommit(e)})}onDiameterCommit(e){let t=parseFloat(e.expression),n=!isNaN(t)&&String(t)===e.expression;this.diameterExpression=e,this.lockedDiameter=n?t:null,this.expressionPhase=`sides`,queueMicrotask(()=>{if(this.mousePoint&&this.centerPoint){let e=Ap(this.centerPoint,this.mousePoint);this.currentSides=this.sidesFromDistance(e)}this.expressionInput.show({label:`N`,value:String(this.currentSides),clientX:this.lastClientX,clientY:this.lastClientY,variables:this.cachedVariables,onCommit:e=>this.onSidesCommit(e)}),this.rebuildPreview()})}onSidesCommit(e){!this.centerPoint||!this.diameterExpression||(this.commitPolygon(this.centerPoint,this.diameterExpression,e),this.resetState(),this.rebuildPreview())}commitPolygon(e,t,n){let r=this.isAtCurrentPosition(e)?`polygon(${n.expression}, ${t.expression})`:`polygon(${this.formatPoint(e)}, ${n.expression}, ${t.expression})`,i=n.newVariable??t.newVariable;this.insertGeometry(r,i)}rebuildPreview(){this.disposePreview();let e=this.ctx.camera,t=new R(this.plane.normal.x,this.plane.normal.y,this.plane.normal.z);if(this.centerPoint){if(Q(this.previewGroup,this.centerPoint,X,e,t,this.plane),this.mousePoint)if(this.expressionPhase===`diameter`){let e=Ap(this.centerPoint,this.mousePoint);e>0&&tv(this.previewGroup,this.centerPoint,e,this.plane)}else{let e=this.lockedDiameter===null?Ap(this.centerPoint,this.mousePoint):this.lockedDiameter/2;if(e>0&&this.currentSides>=Bv){let t=e/Math.cos(Math.PI/this.currentSides);av(this.previewGroup,this.centerPoint,t,this.currentSides,this.plane)}}}else if(this.mousePoint&&this.lastSnapType!==`none`){let n=this.lastSnapType===`vertex`?Z:X_;Q(this.previewGroup,this.mousePoint,n,e,t,this.plane,.6)}this.requestRender()}};function Gv(e,t,n,r,i){let a=t.filter(e=>e.parentId===n),o=kp(i,12),s=o*o,c=null,l=1/0;for(let t of a){if(!t.sourceLocation||!yp(t.uniqueType))continue;let n=t.uniqueType,i=t.sourceLocation;if(n&&n.startsWith(`bezier-`)){let r=Zv(e,t,i,n,s,l);r&&(c=r.hit,l=r.distSq);continue}if(n===`polygon`){let n=[];for(let e of t.sceneShapes)if(!e.isMetaShape)for(let t of e.meshes){let e=_v(t.vertices,r);for(let t of e)n.push(t)}if(n.length>0){let r=$v(e,n,i,t,s,l);r&&(c=r.hit,l=r.distSq)}continue}if(n===`slot`){let n=[];for(let e of t.sceneShapes)if(e.isMetaShape){for(let t of e.meshes)if(t.vertices.length===3&&t.indices.length===0){let e=_v(t.vertices,r);e.length===1&&n.push(e[0])}}if(n.length===2){let a=ey(e,n,i,t,r,s,l);a&&(c=a.hit,l=a.distSq)}continue}if(n===`rect`){let n=[];for(let e of t.sceneShapes)if(!e.isMetaShape)for(let t of e.meshes){let e=_v(t.vertices,r);for(let t of e)n.push(t)}if(n.length>0){let r=Qv(e,n,i,t,s,l);r&&(c=r.hit,l=r.distSq)}continue}for(let a of t.sceneShapes)if(!a.isMetaShape)for(let o of a.meshes){let a=_v(o.vertices,r);if(a.length!==0)if(n===`circle`){let t=Kv(e,a,i,s,l);t&&(c=t.hit,l=t.distSq)}else if(n===`line-two-points`||n===`hline`||n===`vline`||n===`tline`){let r=qv(e,a,i,n,t,s,l);r&&(c=r.hit,l=r.distSq)}else if(n===`arc`&&a.length>=3){let n=Yv(e,a,i,t,r,s,l);n&&(c=n.hit,l=n.distSq)}else if((n===`tarc-to-point`||n===`tarc-to-point-tangent`)&&a.length>=2){let o=Xv(e,a,i,n,t,r,s,l);o&&(c=o.hit,l=o.distSq)}else for(let t of a){let r=t[0]-e[0],a=t[1]-e[1],o=r*r+a*a;o<s&&o<l&&(c={sourceLocation:i,uniqueType:n||``,hitZone:`body`},l=o)}}}return c}function Kv(e,t,n,r,i){let a=[];for(let e of t){let t=!1;for(let n of a){let r=n[0]-e[0],i=n[1]-e[1];if(r*r+i*i<1e-6){t=!0;break}}t||a.push(e)}let o=0,s=0;for(let e of a)o+=e[0],s+=e[1];o/=a.length,s/=a.length;let c=a[0],l=c[0]-o,u=c[1]-s,d=Math.sqrt(l*l+u*u),f=Math.round(2*d*100)/100,p=null;for(let a of t){let t=a[0]-e[0],c=a[1]-e[1],l=t*t+c*c;l<r&&l<i&&(p={hit:{sourceLocation:n,uniqueType:`circle`,hitZone:`body`,anchorPoint:[o,s],initialValue:f},distSq:l},i=l)}return p}function qv(e,t,n,r,i,a,o){let s=t[0],c=t[t.length-1],l=s[0]-e[0],u=s[1]-e[1],d=l*l+u*u,f=c[0]-e[0],p=c[1]-e[1],m=f*f+p*p,h=r===`hline`||r===`vline`||r===`tline`,g,_;if(r===`tline`){let e=c[0]-s[0],n=c[1]-s[1],r=Math.sqrt(e*e+n*n);if(r>1e-10){if(_=[e/r,n/r],g=r,t.length>=2){let e=t[t.length-2],n=t[t.length-1],r=n[0]-e[0],i=n[1]-e[1],a=Math.sqrt(r*r+i*i);a>1e-10&&(_=[r/a,i/a])}let i=c[0]-s[0],a=c[1]-s[1];g=i*_[0]+a*_[1]}}else (r===`hline`||r===`vline`)&&(g=r===`hline`?c[0]-s[0]:c[1]-s[1]);let v=h?Math.round((g??0)*100)/100:void 0,y=d<a||m<a,b=null;if(m<a&&m<o&&(b={hit:{sourceLocation:n,uniqueType:r||``,hitZone:`end`,anchorPoint:s,fixedVertex:s,initialValue:v,draggedVertices:[c],tangentDir:_},distSq:m},o=m),r!==`tline`&&i.object?.hasExplicitStart===!0&&!(h&&i.object?.centered===!0)&&d<a&&d<o&&(b={hit:{sourceLocation:n,uniqueType:r||``,hitZone:`start`,anchorPoint:s,fixedVertex:c,originalDistance:g,draggedVertices:[s]},distSq:d},o=d),!y&&r===`line-two-points`){let t=Cp(e[0],e[1],s[0],s[1],c[0],c[1]),i=t*t;i<a&&i<o&&(b={hit:{sourceLocation:n,uniqueType:r||``,hitZone:`body`,anchorPoint:s,fixedVertex:c,originalDistance:g,initialValue:v,draggedVertices:[s,c]},distSq:i})}return b}function Jv(e,t){for(let n of e.sceneShapes)if(n.isMetaShape){for(let e of n.meshes)if(e.vertices.length===3&&e.indices.length===0){let n=_v(e.vertices,t);if(n.length===1)return n[0]}}return null}function Yv(e,t,n,r,i,a,o){let s=t[0],c=t[t.length-1],l=r.object?.startPoint!==void 0,u=l?3:2,d=Jv(r,i);if(!d){let e=t[Math.floor(t.length/2)];d=pv(s,e,c)}if(!d)return null;let f=t[Math.floor(t.length/2)],p=mv(d,s,f),m=s[0]-e[0],h=s[1]-e[1],g=m*m+h*h,_=c[0]-e[0],v=c[1]-e[1],y=_*_+v*v,b=d[0]-e[0],x=d[1]-e[1],S=b*b+x*x,C=Math.min(g,y,S),w=null;return l&&g<a&&g<o&&g===C&&(w={hit:{sourceLocation:n,uniqueType:`arc`,hitZone:`start`,anchorPoint:d,fixedVertex:c,draggedVertices:[s],arcCCW:p,arcArgCount:u},distSq:g},o=g),y<a&&y<o&&y===C&&(w={hit:{sourceLocation:n,uniqueType:`arc`,hitZone:`end`,anchorPoint:d,fixedVertex:s,draggedVertices:[c],arcCCW:p,arcArgCount:u},distSq:y},o=y),S<a&&S<o&&S===C&&(w={hit:{sourceLocation:n,uniqueType:`arc`,hitZone:`center`,anchorPoint:d,fixedVertex:s,fixedVertex2:c,draggedVertices:[d],arcCCW:p,arcArgCount:u},distSq:S}),w}function Xv(e,t,n,r,i,a,o,s){let c=t[0],l=t[t.length-1],u=t[1][0]-c[0],d=t[1][1]-c[1],f=Math.sqrt(u*u+d*d),p=f>1e-10?[u/f,d/f]:[1,0],m=Jv(i,a);if(!m){let e=t[Math.floor(t.length/2)];m=pv(c,e,l)}let h=t[Math.floor(t.length/2)],g=m?mv(m,c,h):!0,_=l[0]-e[0],v=l[1]-e[1],y=_*_+v*v,b=null;if(y<o&&y<s&&(b={hit:{sourceLocation:n,uniqueType:r||``,hitZone:`end`,anchorPoint:c,fixedVertex:c,draggedVertices:[l],tangentDir:p,arcCCW:g},distSq:y},s=y),m){let t=m[0]-e[0],i=m[1]-e[1],a=t*t+i*i;a<o&&a<s&&(b={hit:{sourceLocation:n,uniqueType:r||``,hitZone:`center`,anchorPoint:c,fixedVertex:c,fixedVertex2:l,draggedVertices:[m],tangentDir:p,arcCCW:g},distSq:a})}return b}function Zv(e,t,n,r,i,a){let o=t.object?.startPoint,s=t.object?.resolvedPoints??[],c=o?[o,...s]:s;if(c.length===0)return null;let l=null;for(let t=0;t<c.length;t++){let o=c[t],s=o[0]-e[0],u=o[1]-e[1],d=s*s+u*u;d<i&&d<a&&(l={hit:{sourceLocation:n,uniqueType:r,hitZone:`end`,anchorPoint:o,draggedVertices:[o],bezierPoleIndex:t,bezierPoles:c},distSq:d},a=d)}return l}function Qv(e,t,n,r,i,a){if(r.object?.radius)return null;let o=[];for(let e of t){let t=!1;for(let n of o){let r=n[0]-e[0],i=n[1]-e[1];if(r*r+i*i<1e-6){t=!0;break}}t||o.push(e)}if(o.length<4)return null;let s=r.object?.centered===!0,c;if(s){let e=0,t=0;for(let n of o)e+=n[0],t+=n[1];c=[e/o.length,t/o.length]}let l=null;for(let t of o){let r=t[0]-e[0],u=t[1]-e[1],d=r*r+u*u;if(d<i&&d<a){let e;if(s&&c)e=c;else{let n=-1;e=o[0];for(let r of o){let i=r[0]-t[0],a=r[1]-t[1],o=i*i+a*a;o>n&&(n=o,e=r)}}l={hit:{sourceLocation:n,uniqueType:`rect`,hitZone:`end`,anchorPoint:e,fixedVertex:e,draggedVertices:[t],rectCentered:s},distSq:d},a=d}}return l}function $v(e,t,n,r,i,a){let o=[];for(let e of t){let t=!1;for(let n of o){let r=n[0]-e[0],i=n[1]-e[1];if(r*r+i*i<1e-6){t=!0;break}}t||o.push(e)}let s=0,c=0;for(let e of o)s+=e[0],c+=e[1];s/=o.length,c/=o.length;let l=o[0],u=l[0]-s,d=l[1]-c,f=Math.sqrt(u*u+d*d),p=r.object?.numberOfSides??o.length,m=r.object?.diameter??Math.round(2*f*100)/100,h=null;for(let r of t){let t=r[0]-e[0],o=r[1]-e[1],l=t*t+o*o;l<i&&l<a&&(h={hit:{sourceLocation:n,uniqueType:`polygon`,hitZone:`body`,anchorPoint:[s,c],initialValue:m,originalDistance:f,polygonSides:p},distSq:l},a=l)}return h}function ey(e,t,n,r,i,a,o){let s=t[0],c=t[1],l=r.object?.hasTwoPoints??!1,u=r.object?.radius??0,d=c[0]-s[0],f=c[1]-s[1],p=Math.sqrt(d*d+f*f),m;if(l)m=p>1e-10?[d/p,f/p]:[1,0];else{let e=(r.object?.angle??0)*Math.PI/180;m=[Math.cos(e),Math.sin(e)]}let h={sourceLocation:n,uniqueType:`slot`,initialValue:u,slotHasTwoPoints:l,slotAxisDir:m,slotRadius:u};function g(){return{...h,hitZone:`start`,anchorPoint:s,fixedVertex:c,slotOtherCenter:c,slotPointIndex:0,draggedVertices:[s]}}function _(){return{...h,hitZone:`end`,anchorPoint:c,fixedVertex:s,slotOtherCenter:s,slotPointIndex:1,draggedVertices:[c]}}let v=null,y=s[0]-e[0],b=s[1]-e[1],x=y*y+b*b,S=c[0]-e[0],C=c[1]-e[1],w=S*S+C*C;x<a&&x<o&&x<=w&&(v={hit:g(),distSq:x},o=x),w<a&&w<o&&(v={hit:_(),distSq:w},o=w);for(let t of r.sceneShapes)if(!t.isMetaShape)for(let n of t.meshes){let t=_v(n.vertices,i);for(let n of t){let t=n[0]-e[0],r=n[1]-e[1],i=t*t+r*r;i<a&&i<o&&(v={hit:{...h,hitZone:`body`,anchorPoint:s,fixedVertex:c,slotOtherCenter:c,slotRadius:u},distSq:i},o=i)}}return v}function ty(e,t,n){let r=(t[0]+n[0])/2,i=(t[1]+n[1])/2,a=n[0]-t[0],o=-(n[1]-t[1]),s=a,c=o*o+s*s;if(c<1e-10)return e;let l=((e[0]-r)*o+(e[1]-i)*s)/c;return[r+l*o,i+l*s]}function ny(e,t,n){let r=-n[1],i=n[0],a=(e[0]-t[0])*r+(e[1]-t[1])*i;return[t[0]+a*r,t[1]+a*i]}function ry(e,t,n){let r=-n[1],i=n[0],a=e[0]-t[0],o=e[1]-t[1],s=a*a+o*o,c=a*r+o*i;if(Math.abs(c)<1e-10)return null;let l=-s/(2*c),u=Math.abs(l),d=[e[0]+r*l,e[1]+i*l];return{center:d,radius:u,startAngle:dv(d,e),endAngle:dv(d,t),ccw:l>=0}}function iy(e,t,n){let r=(t[0]+n[0])/2,i=(t[1]+n[1])/2,a=n[0]-t[0],o=-(n[1]-t[1]),s=a,c=o*o+s*s;if(c<1e-10)return e;let l=e[0]-r,u=e[1]-i,d=(l*o+u*s)/c;return[r+d*o,i+d*s]}var $=5;function ay(e,t,n,r,i,a){let o=new R(a.normal.x,a.normal.y,a.normal.z),{uniqueType:s,hitZone:c,anchorPoint:l,fixedVertex:u}=r;if(s===`polygon`&&l&&r.polygonSides){let n=l,s=t[0]-n[0],c=t[1]-n[1],u=Math.sqrt(s*s+c*c);Q(e,n,X,i,o,a,1,$),av(e,n,u,r.polygonSides,a,$),Q(e,t,Z,i,o,a,1,$)}else if(s===`circle`&&l){let n=l,r=t[0]-n[0],s=t[1]-n[1],c=Math.sqrt(r*r+s*s);Q(e,n,X,i,o,a,1,$),tv(e,n,c,a,$)}else if(s===`tline`&&l&&r.tangentDir){let n=l,s=r.tangentDir,c=t[0]-n[0],u=t[1]-n[1],d=c*s[0]+u*s[1],f=[n[0]+s[0]*d,n[1]+s[1]*d];Q(e,n,X,i,o,a,1,$),ev(e,n,f,a,$),Q(e,f,Z,i,o,a,1,$)}else if(s===`hline`||s===`vline`)if(c===`end`){let n=l,r=s===`hline`?[t[0],n[1]]:[n[0],t[1]];Q(e,n,X,i,o,a,1,$),ev(e,n,r,a,$),Q(e,r,Z,i,o,a,1,$)}else{let n=r.originalDistance??0,c=s===`hline`?[t[0]+n,t[1]]:[t[0],t[1]+n];Q(e,t,X,i,o,a,1,$),ev(e,t,c,a,$),Q(e,c,Z,i,o,a,1,$)}else if(s===`line-two-points`&&u&&l)if(c===`body`){let n=u[0]-l[0],r=u[1]-l[1],s=[t[0]+n,t[1]+r];Q(e,t,X,i,o,a,1,$),ev(e,t,s,a,$),Q(e,s,Z,i,o,a,1,$)}else c===`start`?(Q(e,t,Z,i,o,a,1,$),ev(e,t,u,a,$),Q(e,u,X,i,o,a,1,$)):(Q(e,u,X,i,o,a,1,$),ev(e,u,t,a,$),Q(e,t,Z,i,o,a,1,$));else if(s===`arc`&&l&&u)oy(e,t,r,i,o,a);else if(s===`rect`&&l)if(r.rectCentered){let n=[2*l[0]-t[0],2*l[1]-t[1]];Q(e,l,X,i,o,a,1,$),nv(e,n,t,a,$),Q(e,t,Z,i,o,a,1,$)}else Q(e,l,X,i,o,a,1,$),nv(e,l,t,a,$),Q(e,t,Z,i,o,a,1,$);else if(s===`slot`&&r.slotRadius!==void 0)if(c===`body`){let n=l,s=u,c=r.slotAxisDir?.[0]??1,d=r.slotAxisDir?.[1]??0,f=t[0]-n[0],p=t[1]-n[1],m=Math.abs(-d*f+c*p);Q(e,n,X,i,o,a,1,$),Q(e,s,X,i,o,a,1,$),m>0?uv(e,n,s,m,a,$):ev(e,n,s,a,$),Q(e,t,Z,i,o,a,1,$)}else{let n=r.slotOtherCenter,s=r.slotRadius,l=c===`start`?t:n,u=c===`start`?n:t;Q(e,n,X,i,o,a,1,$),s>0?uv(e,l,u,s,a,$):ev(e,l,u,a,$),Q(e,t,Z,i,o,a,1,$)}else if((s===`tarc-to-point`||s===`tarc-to-point-tangent`)&&u&&r.tangentDir)sy(e,t,r,i,o,a);else if(s.startsWith(`bezier-`)&&r.bezierPoles&&r.bezierPoleIndex!==void 0){let n=r.bezierPoles.slice();n[r.bezierPoleIndex]=t;for(let t=1;t<n.length;t++)ev(e,n[t-1],n[t],a,$);cv(e,n,a,$);for(let t=0;t<n.length;t++)t!==r.bezierPoleIndex&&Q(e,n[t],Y_,i,o,a,.85,$);Q(e,t,Z,i,o,a,1,$)}else Q(e,t,Z,i,o,a,1,$),n&&ev(e,n,t,a,$)}function oy(e,t,n,r,i,a){let{hitZone:o,anchorPoint:s,fixedVertex:c}=n,l=n.arcCCW!==!1;if(o===`center`){let o=c,s=n.fixedVertex2,u=t,d=Math.sqrt((o[0]-u[0])**2+(o[1]-u[1])**2),f=dv(u,o),p=dv(u,s),m=[u[0]+d*Math.cos(p),u[1]+d*Math.sin(p)];Q(e,o,X,r,i,a,1,$),ov(e,u,d,f,p,l,a,$),Q(e,m,X,r,i,a,1,$),Q(e,u,Z,r,i,a,1,$)}else{let n=iy(s,c,t),u=Math.sqrt((t[0]-n[0])**2+(t[1]-n[1])**2);if(o===`start`){let o=dv(n,t),s=dv(n,c);Q(e,t,Z,r,i,a,1,$),ov(e,n,u,o,s,l,a,$),Q(e,c,X,r,i,a,1,$)}else{let o=dv(n,c),s=dv(n,t);Q(e,c,X,r,i,a,1,$),ov(e,n,u,o,s,l,a,$),Q(e,t,Z,r,i,a,1,$)}}}function sy(e,t,n,r,i,a){let{hitZone:o,fixedVertex:s,tangentDir:c}=n,l=s,u=c;if(o===`center`){let o=t,s=n.fixedVertex2,c=Math.sqrt((l[0]-o[0])**2+(l[1]-o[1])**2),u=dv(o,l),d=dv(o,s),f=n.arcCCW!==!1,p=[o[0]+c*Math.cos(d),o[1]+c*Math.sin(d)];Q(e,l,X,r,i,a,1,$),ov(e,o,c,u,d,f,a,$),Q(e,p,X,r,i,a,1,$),Q(e,o,Z,r,i,a,1,$)}else{let n=ry(l,t,u);n?(Q(e,l,X,r,i,a,1,$),ov(e,n.center,n.radius,n.startAngle,n.endAngle,n.ccw,a,$),Q(e,t,Z,r,i,a,1,$)):(Q(e,l,X,r,i,a,1,$),ev(e,l,t,a,$),Q(e,t,Z,r,i,a,1,$))}}function cy(e){for(;e.children.length>0;){let t=e.children[0];e.remove(t);let n=t;n.geometry&&n.geometry.dispose(),n.material&&n.material.dispose()}}function ly(e,t,n){let r=Y(e),{sourceLocation:i,uniqueType:a,hitZone:o,anchorPoint:s,fixedVertex:c}=t;if(a===`line-two-points`&&o===`body`&&s&&c){let e=c[0]-s[0],t=c[1]-s[1];Rm(r,Y([r[0]+e,r[1]+t]),i);return}if(a===`line-two-points`)zm(r,i,o===`start`?0:-1);else if(a===`arc`&&s&&c){let e=t.arcArgCount===2,n=+!e,a=e?1:2;if(o===`center`){let e=c,o=t.fixedVertex2,s=Math.sqrt((e[0]-r[0])**2+(e[1]-r[1])**2),l=Math.atan2(o[1]-r[1],o[0]-r[0]);Bm([{pointIndex:n,position:Y([r[0]+s*Math.cos(l),r[1]+s*Math.sin(l)])},{pointIndex:a,position:r}],i)}else{let e=Y(iy(s,c,r));Bm([{pointIndex:o===`start`?0:n,position:r},{pointIndex:a,position:e}],i)}}else if((a===`hline`||a===`vline`)&&(o===`start`||o===`body`))zm(r,i,0);else if(a===`tline`&&o===`end`&&s&&t.tangentDir){let e=t.tangentDir,a=r[0]-s[0],o=r[1]-s[1],c=Math.round((a*e[0]+o*e[1])*100)/100,l=n();Hm(String(c),i,l)}else if(a===`polygon`&&s&&t.originalDistance&&t.initialValue){let e=r[0]-s[0],a=r[1]-s[1],o=Math.sqrt(e*e+a*a),c=Math.round(t.initialValue*o/t.originalDistance*100)/100,l=n();Hm(String(c),i,l)}else if(a===`rect`&&s)if(t.rectCentered)Vm(Math.round(Math.abs(r[0]-s[0])*2*100)/100,Math.round(Math.abs(r[1]-s[1])*2*100)/100,i);else{let e=Math.min(s[0],r[0]),t=Math.min(s[1],r[1]);Vm(Math.round(Math.abs(r[0]-s[0])*100)/100,Math.round(Math.abs(r[1]-s[1])*100)/100,i,Y([e,t]))}else if(a===`tarc-to-point`||a===`tarc-to-point-tangent`){let e=a===`tarc-to-point`?0:1;if(o===`center`&&c&&t.fixedVertex2){let n=c,a=t.fixedVertex2,o=Math.sqrt((n[0]-r[0])**2+(n[1]-r[1])**2),s=Math.atan2(a[1]-r[1],a[0]-r[0]);zm(Y([r[0]+o*Math.cos(s),r[1]+o*Math.sin(s)]),i,e)}else zm(r,i,e)}else if(a===`slot`){if(o===`body`){let e=t.anchorPoint,a=t.slotAxisDir?.[0]??1,o=t.slotAxisDir?.[1]??0,s=r[0]-e[0],c=r[1]-e[1],l=Math.round(Math.abs(-o*s+a*c)*100)/100,u=n();Hm(String(l),i,u)}else if(t.slotHasTwoPoints)zm(r,i,t.slotPointIndex??0);else if(o===`start`)zm(r,i,0);else if(t.slotOtherCenter&&t.slotAxisDir){let e=t.slotOtherCenter,a=t.slotAxisDir,o=r[0]-e[0],s=r[1]-e[1],c=Math.round((o*a[0]+s*a[1])*100)/100,l=n();Hm(String(c),i,l,void 0,1)}}else a.startsWith(`bezier-`)&&t.bezierPoleIndex!==void 0?zm(r,i,t.bezierPoleIndex):zm(r,i)}var uy=class{expressionInput;fetchVariables;getSketchSourceLine;cachedVariables=[];standaloneInputActive=!1;onRequestEndResize=null;onRequestCloseStandalone=null;constructor(e,t,n){this.expressionInput=new J_(e),this.fetchVariables=t,this.getSketchSourceLine=n}get isVisible(){return this.expressionInput.isVisible}containsElement(e){return this.expressionInput.containsElement(e)}refreshVariables(){return this.fetchVariables().then(e=>{this.cachedVariables=e})}showForDrag(e,t,n,r){let{uniqueType:i,hitZone:a}=e,o=null,s=0;if(i===`polygon`){o=`⌀`;let n=e.anchorPoint,r=t[0]-n[0],i=t[1]-n[1],a=Math.sqrt(r*r+i*i);s=e.originalDistance&&e.initialValue?Math.round(e.initialValue*a/e.originalDistance*100)/100:Math.round(2*a*100)/100}else if(i===`circle`){o=`⌀`;let n=e.anchorPoint,r=t[0]-n[0],i=t[1]-n[1];s=Math.round(2*Math.sqrt(r*r+i*i)*100)/100}else if((i===`hline`||i===`vline`)&&a===`end`){o=i===`hline`?`H:`:`V:`;let n=e.anchorPoint;s=i===`hline`?Math.round(Math.abs(t[0]-n[0])*100)/100:Math.round(Math.abs(t[1]-n[1])*100)/100}else if(i===`tline`&&a===`end`&&e.tangentDir){o=`T:`;let n=e.anchorPoint,r=e.tangentDir,i=t[0]-n[0],a=t[1]-n[1];s=Math.round(Math.abs(i*r[0]+a*r[1])*100)/100}else if(i===`slot`&&!e.slotHasTwoPoints&&e.slotOtherCenter&&e.slotAxisDir&&a===`end`){o=`D`;let n=e.slotOtherCenter,r=e.slotAxisDir,i=t[0]-n[0],a=t[1]-n[1];s=Math.round((i*r[0]+a*r[1])*100)/100}else if(i===`slot`&&a===`body`){o=`R`;let n=e.anchorPoint,r=t[0]-n[0],i=t[1]-n[1];s=Math.round(Math.sqrt(r*r+i*i)*100)/100}o!==null&&this.openInput(o,s,e,n,r,!0)}showForDoubleClick(e,t,n){let r,i;if(e.uniqueType===`polygon`||e.uniqueType===`circle`)r=`⌀`,i=e.initialValue??0;else if(e.uniqueType===`hline`||e.uniqueType===`vline`)r=e.uniqueType===`hline`?`H:`:`V:`,i=Math.abs(e.initialValue??0);else if(e.uniqueType===`tline`)r=`T:`,i=Math.abs(e.initialValue??0);else if(e.uniqueType===`slot`)if(e.hitZone===`start`||e.hitZone===`end`){if(e.slotHasTwoPoints)return!1;r=`D`;let t=e.anchorPoint,n=e.fixedVertex,a=e.slotAxisDir??[1,0];i=Math.round(((n[0]-t[0])*a[0]+(n[1]-t[1])*a[1])*100)/100}else r=`R`,i=e.slotRadius??0;else return!1;return this.standaloneInputActive=!0,this.openInput(r,i,e,t,n,!1),!0}updateValue(e,t){if(!this.expressionInput.isVisible)return;let{uniqueType:n,anchorPoint:r}=e,i;if(n===`polygon`){let n=r,a=t[0]-n[0],o=t[1]-n[1],s=Math.sqrt(a*a+o*o);i=e.originalDistance&&e.initialValue?Math.round(e.initialValue*s/e.originalDistance*100)/100:Math.round(2*s*100)/100}else if(n===`circle`){let e=r,n=t[0]-e[0],a=t[1]-e[1];i=Math.round(2*Math.sqrt(n*n+a*a)*100)/100}else if(n===`tline`&&e.tangentDir){let n=r,a=e.tangentDir,o=t[0]-n[0],s=t[1]-n[1];i=Math.round(Math.abs(o*a[0]+s*a[1])*100)/100}else if(n===`slot`&&e.hitZone===`body`){let n=r,a=e.slotAxisDir?.[0]??1,o=e.slotAxisDir?.[1]??0,s=t[0]-n[0],c=t[1]-n[1];i=Math.round(Math.abs(-o*s+a*c)*100)/100}else if(n===`slot`&&e.slotOtherCenter&&e.slotAxisDir){let n=e.slotOtherCenter,r=e.slotAxisDir,a=t[0]-n[0],o=t[1]-n[1];i=Math.round((a*r[0]+o*r[1])*100)/100}else{let e=r,a=n===`hline`?t[0]-e[0]:t[1]-e[1];i=Math.round(Math.abs(a)*100)/100}this.expressionInput.updateValue(i)}updatePosition(e,t){this.expressionInput.updatePosition(e,t)}updateValueIfUnmoved(e){this.expressionInput.updateValue(e)}commitIfVisible(e){this.expressionInput.isVisible&&e&&this.expressionInput.commitCurrentValue()}hide(){this.expressionInput.hide()}closeStandalone(){this.standaloneInputActive&&(this.standaloneInputActive=!1,this.expressionInput.hide())}openInput(e,t,n,r,i,a){let{sourceLocation:o}=n,s=String(t);this.expressionInput.show({label:e,value:s,clientX:r,clientY:i,variables:this.cachedVariables,onCommit:t=>{let{expression:r,newVariable:i}=t,s=parseFloat(r),c=!isNaN(s)&&String(s)===r,l=r;if(c&&n.uniqueType!==`circle`&&n.uniqueType!==`polygon`&&n.uniqueType!==`slot`){let e=this.computeDistanceSign(n,null);l=String(Math.round(e*s*100)/100)}else c&&(l=String(Math.round(s*100)/100));let u=this.getSketchSourceLine();Hm(l,o,u,i,+(e===`D`)),a?this.onRequestEndResize?.():this.closeStandalone()}}),e!==`D`&&Um(o.line).then(({expression:e})=>{e&&(a||this.standaloneInputActive)&&this.updateValueIfUnmoved(e)})}computeDistanceSign(e,t){if(t){let n=e.anchorPoint;if(e.uniqueType===`tline`&&e.tangentDir){let r=e.tangentDir,i=t[0]-n[0],a=t[1]-n[1];return i*r[0]+a*r[1]>=0?1:-1}return e.uniqueType===`hline`?t[0]>=n[0]?1:-1:t[1]>=n[1]?1:-1}return(e.initialValue??e.originalDistance??0)>=0?1:-1}},dy=class{ctx;plane;snapController;sceneObjects=[];sketchId=``;canvas;previewGroup;_isResizing=!1;hasMoved=!1;hitResult=null;startPoint=null;currentPoint=null;grabOffset=null;pendingHit=null;dimensionInput;getSketchSourceLine;boundCanvasPointerDown;boundPointerMove;boundPointerUp;boundKeyDown;boundCanvasDoubleClick;constructor(e,t,n,r,i,a){this.ctx=e,this.plane=t,this.snapController=n,this.canvas=e.renderer.domElement,this.getSketchSourceLine=a,this.previewGroup=new oi,this.previewGroup.userData.isMetaShape=!0,this.previewGroup.renderOrder=5,this.dimensionInput=new uy(r,i,a),this.dimensionInput.onRequestEndResize=()=>this.endResize(),this.dimensionInput.onRequestCloseStandalone=()=>{this.dimensionInput.closeStandalone(),this.hitResult=null},this.boundCanvasPointerDown=this.handleCanvasPointerDown.bind(this),this.boundPointerMove=this.handlePointerMove.bind(this),this.boundPointerUp=this.handlePointerUp.bind(this),this.boundKeyDown=this.handleKeyDown.bind(this),this.boundCanvasDoubleClick=this.handleCanvasDoubleClick.bind(this)}get isResizing(){return this._isResizing}activate(){this.ctx.scene.add(this.previewGroup),this.canvas.addEventListener(`pointerdown`,this.boundCanvasPointerDown,{capture:!0}),this.canvas.addEventListener(`dblclick`,this.boundCanvasDoubleClick),window.addEventListener(`pointermove`,this.boundPointerMove),window.addEventListener(`pointerup`,this.boundPointerUp,{capture:!0}),window.addEventListener(`keydown`,this.boundKeyDown)}deactivate(){this.canvas.removeEventListener(`pointerdown`,this.boundCanvasPointerDown,{capture:!0}),this.canvas.removeEventListener(`dblclick`,this.boundCanvasDoubleClick),window.removeEventListener(`pointermove`,this.boundPointerMove),window.removeEventListener(`pointerup`,this.boundPointerUp,{capture:!0}),window.removeEventListener(`keydown`,this.boundKeyDown),this.endResize(),this.dimensionInput.closeStandalone(),this.pendingHit=null,this.ctx.scene.remove(this.previewGroup),cy(this.previewGroup)}updatePlane(e){this.plane=e}updateSnapController(e){this.snapController=e,this._isResizing&&this.hitResult?.draggedVertices&&this.snapController.setExcludedVertices(this.hitResult.draggedVertices)}updateSceneData(e,t){this.sceneObjects=e,this.sketchId=t,this.dimensionInput.refreshVariables()}handleCanvasPointerDown(e){if(e.button!==0||this._isResizing||this.dimensionInput.standaloneInputActive&&this.dimensionInput.containsElement(e.target))return;let t=Tp(this.ctx,this.plane,e.clientX,e.clientY);if(!t)return;let n=Gv(t,this.sceneObjects,this.sketchId,this.plane,this.ctx);n&&(this.pendingHit={hit:n,point2d:t,clientX:e.clientX,clientY:e.clientY},this.ctx.cameraControls.enabled=!1,e.stopPropagation())}handlePointerUp(e){if(e.button===0){if(this._isResizing){this.commitResize(),e.stopPropagation(),e.preventDefault();return}this.pendingHit&&(this.pendingHit=null,this.ctx.cameraControls.enabled=!0)}}startResize(e){this._isResizing=!0,this.hasMoved=!1,this.hitResult=e.hit,this.startPoint=e.point2d,this.currentPoint=e.point2d;let t=e.hit;t.hitZone===`body`&&t.anchorPoint&&(t.uniqueType===`hline`||t.uniqueType===`vline`||t.uniqueType===`line-two-points`)?this.grabOffset=[e.point2d[0]-t.anchorPoint[0],e.point2d[1]-t.anchorPoint[1]]:this.grabOffset=null,this.ctx.cameraControls.enabled=!1,this.canvas.style.cursor=`crosshair`,this.snapController.setExcludedVertices(t.draggedVertices??[]),this.dimensionInput.showForDrag(t,e.point2d,e.clientX,e.clientY)}commitResize(){this.dimensionInput.isVisible&&this.hasMoved?this.dimensionInput.commitIfVisible(this.hasMoved):this.currentPoint&&this.hitResult&&ly(this.currentPoint,this.hitResult,this.getSketchSourceLine),this.endResize()}handleKeyDown(e){e.key===`Escape`&&(this._isResizing?this.endResize():this.dimensionInput.standaloneInputActive&&(this.dimensionInput.closeStandalone(),this.hitResult=null))}handlePointerMove(e){if(this.pendingHit&&!this._isResizing){let t=e.clientX-this.pendingHit.clientX,n=e.clientY-this.pendingHit.clientY;if(t*t+n*n>=16){let e=this.pendingHit;this.pendingHit=null,this.startResize(e)}else return}if(!this._isResizing)return;let t=Tp(this.ctx,this.plane,e.clientX,e.clientY);if(t){if(this.hasMoved=!0,this.grabOffset&&this.hitResult?.hitZone===`body`){let e=[t[0]-this.grabOffset[0],t[1]-this.grabOffset[1]];this.currentPoint=this.snapController.snap(e).point2d}else this.currentPoint=this.snapController.snap(t).point2d;if(this.hitResult?.hitZone===`start`&&this.hitResult.anchorPoint&&(this.hitResult.uniqueType===`hline`||this.hitResult.uniqueType===`vline`)&&(this.hitResult.uniqueType===`hline`?this.currentPoint=[this.currentPoint[0],this.hitResult.anchorPoint[1]]:this.currentPoint=[this.hitResult.anchorPoint[0],this.currentPoint[1]]),this.hitResult?.uniqueType===`tline`&&this.hitResult.hitZone===`end`&&this.hitResult.anchorPoint&&this.hitResult.tangentDir){let e=this.hitResult.anchorPoint,t=this.hitResult.tangentDir,n=this.currentPoint[0]-e[0],r=this.currentPoint[1]-e[1],i=n*t[0]+r*t[1];this.currentPoint=[e[0]+t[0]*i,e[1]+t[1]*i]}if(this.hitResult?.hitZone===`center`&&this.hitResult.uniqueType===`arc`&&this.hitResult.fixedVertex&&this.hitResult.fixedVertex2&&e.shiftKey&&(this.currentPoint=ty(this.currentPoint,this.hitResult.fixedVertex,this.hitResult.fixedVertex2)),this.hitResult?.hitZone===`center`&&this.hitResult.tangentDir&&this.hitResult.fixedVertex&&(this.currentPoint=ny(this.currentPoint,this.hitResult.fixedVertex,this.hitResult.tangentDir)),this.hitResult?.uniqueType===`slot`&&!this.hitResult.slotHasTwoPoints&&(this.hitResult.hitZone===`start`||this.hitResult.hitZone===`end`)&&this.hitResult.slotAxisDir&&this.hitResult.slotOtherCenter){let e=this.hitResult.slotAxisDir,t=this.hitResult.slotOtherCenter,n=this.currentPoint[0]-t[0],r=this.currentPoint[1]-t[1],i=n*e[0]+r*e[1];this.currentPoint=[t[0]+e[0]*i,t[1]+e[1]*i]}cy(this.previewGroup),this.currentPoint&&this.hitResult&&ay(this.previewGroup,this.currentPoint,this.startPoint,this.hitResult,this.ctx.camera,this.plane),this.ctx.requestRender(),this.currentPoint&&this.hitResult&&this.dimensionInput.updateValue(this.hitResult,this.currentPoint),this.dimensionInput.updatePosition(e.clientX,e.clientY)}}handleCanvasDoubleClick(e){if(this._isResizing)return;let t=Tp(this.ctx,this.plane,e.clientX,e.clientY);if(!t)return;let n=Gv(t,this.sceneObjects,this.sketchId,this.plane,this.ctx);n&&n.uniqueType!==`line-two-points`&&(this.hitResult=n,this.startPoint=null,this.currentPoint=null,this.dimensionInput.showForDoubleClick(n,e.clientX,e.clientY)||(this.hitResult=null))}endResize(){this._isResizing=!1,this.hasMoved=!1,this.hitResult=null,this.startPoint=null,this.currentPoint=null,this.grabOffset=null,this.pendingHit=null,this.ctx.cameraControls.enabled=!0,this.canvas.style.cursor=``,this.snapController.setExcludedVertices([]),this.dimensionInput.hide(),cy(this.previewGroup),this.ctx.requestRender()}},fy=12,py=2,my=6,hy=class{ctx;plane;canvas;edges=[];centers=[];hoveredShapeId=null;hoveredCenterOverlay=null;hoveredCenterPoint=null;selectedShapeIds=new Set;isExternalResizing;boundMouseMove;boundMouseDown;boundMouseUp;downX=0;downY=0;constructor(e,t,n){this.ctx=e,this.plane=t,this.canvas=e.renderer.domElement,this.isExternalResizing=n,this.boundMouseMove=this.handleMouseMove.bind(this),this.boundMouseDown=this.handleMouseDown.bind(this),this.boundMouseUp=this.handleMouseUp.bind(this)}activate(){this.canvas.addEventListener(`mousemove`,this.boundMouseMove),this.canvas.addEventListener(`mousedown`,this.boundMouseDown),this.canvas.addEventListener(`mouseup`,this.boundMouseUp)}deactivate(){this.canvas.removeEventListener(`mousemove`,this.boundMouseMove),this.canvas.removeEventListener(`mousedown`,this.boundMouseDown),this.canvas.removeEventListener(`mouseup`,this.boundMouseUp),this.clearHover(),this.clearSelection(),this.removeCenterOverlay()}updatePlane(e){this.plane=e}updateSceneData(e,t){this.edges=bp(e,t,this.plane),this.centers=Sp(e,t,this.plane);let n=new Set(this.edges.map(e=>e.shapeId));for(let e of this.centers)n.add(e.shapeId);this.hoveredShapeId&&!n.has(this.hoveredShapeId)&&this.clearHover();for(let e of this.selectedShapeIds)n.has(e)||(this.removeSelectionHighlight(e),this.selectedShapeIds.delete(e))}get selectedIds(){return this.selectedShapeIds}handleMouseDown(e){this.downX=e.clientX,this.downY=e.clientY}handleMouseMove(e){if(this.isExternalResizing()){this.hoveredShapeId&&this.clearHover();return}let t=Tp(this.ctx,this.plane,e.clientX,e.clientY);if(!t){this.hoveredShapeId&&this.clearHover();return}let n=kp(this.ctx,fy),r=this.findNearestEdge(t,n),i=r?.shapeId??null;i!==this.hoveredShapeId&&(this.hoveredShapeId&&this.removeHoverHighlight(this.hoveredShapeId),this.removeCenterOverlay(),i?(this.applyHoverHighlight(i),this.canvas.style.cursor=`pointer`):this.canvas.style.cursor=``,this.hoveredShapeId=i,this.ctx.requestRender()),r?.isCenter&&r.centerPoint?this.hoveredCenterPoint&&this.hoveredCenterPoint[0]===r.centerPoint[0]&&this.hoveredCenterPoint[1]===r.centerPoint[1]||(this.removeCenterOverlay(),this.addCenterOverlay(r.centerPoint),this.hoveredCenterPoint=r.centerPoint,this.ctx.requestRender()):this.hoveredCenterOverlay&&(this.removeCenterOverlay(),this.ctx.requestRender())}handleMouseUp(e){if(this.isExternalResizing())return;let t=e.clientX-this.downX,n=e.clientY-this.downY;if(t*t+n*n>64)return;let r=e.ctrlKey||e.metaKey;if(!this.hoveredShapeId){r||(this.clearSelection(),this.ctx.requestRender());return}r?this.selectedShapeIds.has(this.hoveredShapeId)?(this.removeSelectionHighlight(this.hoveredShapeId),this.selectedShapeIds.delete(this.hoveredShapeId),this.applyHoverHighlight(this.hoveredShapeId)):(this.selectedShapeIds.add(this.hoveredShapeId),this.applySelectionHighlight(this.hoveredShapeId)):(this.clearSelection(),this.selectedShapeIds.add(this.hoveredShapeId),this.applySelectionHighlight(this.hoveredShapeId)),this.ctx.requestRender()}findNearestEdge(e,t){let n=1/0,r=null,i=!1,a=null;for(let t of this.edges)for(let o of t.segments){let s=Cp(e[0],e[1],o.ax,o.ay,o.bx,o.by);s<n&&(n=s,r=t.shapeId,i=!1,a=null)}for(let t of this.centers){let o=t.point2d[0]-e[0],s=t.point2d[1]-e[1],c=Math.sqrt(o*o+s*s);c<n&&(n=c,r=t.shapeId,i=!0,a=t.point2d)}return n>t||!r?null:a?{shapeId:r,isCenter:i,centerPoint:a}:{shapeId:r,isCenter:i}}applyHoverHighlight(e){this.selectedShapeIds.has(e)||this.traverseShapeEdges(e,e=>{e.userData.selectOriginalColor===void 0&&(e.userData.hoverOriginalColor=e.material.color.getHex(),e.material.color.set(Wd.highlightColor))})}removeHoverHighlight(e){this.traverseShapeEdges(e,e=>{e.userData.hoverOriginalColor!==void 0&&(e.material.color.setHex(e.userData.hoverOriginalColor),delete e.userData.hoverOriginalColor)})}applySelectionHighlight(e){this.traverseShapeEdges(e,e=>{e.userData.hoverOriginalColor===void 0?e.userData.selectOriginalColor=e.material.color.getHex():(e.userData.selectOriginalColor=e.userData.hoverOriginalColor,delete e.userData.hoverOriginalColor),e.material.color.set(Wd.highlightColor)})}removeSelectionHighlight(e){this.traverseShapeEdges(e,e=>{e.userData.selectOriginalColor!==void 0&&(e.material.color.setHex(e.userData.selectOriginalColor),delete e.userData.selectOriginalColor)})}clearHover(){this.hoveredShapeId&&(this.removeHoverHighlight(this.hoveredShapeId),this.hoveredShapeId=null,this.canvas.style.cursor=``,this.removeCenterOverlay(),this.ctx.requestRender())}clearSelection(){for(let e of this.selectedShapeIds)this.removeSelectionHighlight(e);this.selectedShapeIds.clear()}traverseShapeEdges(e,t){this.ctx.scene.traverse(n=>{n.userData.isMetaShape||(n.isLine||n.userData.isEdgeLine)&&this.findShapeId(n)===e&&t(n)})}findShapeId(e){let t=e;for(;t;){if(t.userData.shapeId&&!t.userData.isMetaShape)return t.userData.shapeId;t=t.parent}return null}addCenterOverlay(e){this.removeCenterOverlay();let t=Ep(e,this.plane),n=this.plane.normal,r=new R(n.x,n.y,n.z),i=new U(new oa(py,16),new mr({color:Wd.highlightColor,side:2,depthTest:!1,transparent:!0,opacity:.9}));i.renderOrder=6;let a=new oi;a.renderOrder=6,a.userData.isCenterOverlay=!0,a.add(i),a.position.copy(t),a.lookAt(t.clone().add(r)),tf(i,a,t,my,py),this.ctx.scene.add(a),this.hoveredCenterOverlay=a}removeCenterOverlay(){if(this.hoveredCenterOverlay){this.ctx.scene.remove(this.hoveredCenterOverlay);let e=this.hoveredCenterOverlay.children[0];e.geometry.dispose(),e.material.dispose(),this.hoveredCenterOverlay=null,this.hoveredCenterPoint=null}}},gy=`#8899aa`,_y=1.5,vy=4.5,yy=.5,by=2,xy=class{ctx;group;active=!1;constructor(e){this.ctx=e,this.group=new oi,this.group.userData.isMetaShape=!0,this.group.renderOrder=3}activate(){this.active||=(this.ctx.scene.add(this.group),!0)}deactivate(){this.active&&(this.ctx.scene.remove(this.group),this.disposeGroup(),this.active=!1,this.ctx.requestRender())}update(e,t,n){if(!this.active)return;this.disposeGroup();let r=this.ctx.camera,i=new R(n.normal.x,n.normal.y,n.normal.z);for(let a of e){if(a.parentId!==t||a.type!==`bezier`)continue;let e=a.object?.startPoint,o=a.object?.resolvedPoints,s=[];e&&s.push(e),o&&s.push(...o);for(let e=1;e<s.length;e++)ev(this.group,s[e-1],s[e],n,by);for(let e of s)Q(this.group,e,gy,r,i,n,yy,by,_y,vy)}this.ctx.requestRender()}disposeGroup(){for(;this.group.children.length>0;){let e=this.group.children[0];this.group.remove(e);let t=e;t.geometry&&t.geometry.dispose(),t.material&&t.material.dispose();let n=e.children?.[0];n?.geometry&&n.geometry.dispose(),n?.material&&n.material.dispose()}}},Sy=class{snapManager;plane;excludedVertices=[];snapToVertices=!0;snapToGrid=!0;constructor(e,t){this.snapManager=e,this.plane=t}updateSnapManager(e){this.snapManager=e,this.snapManager.setExcludedVertices(this.excludedVertices)}setExcludedVertices(e){this.excludedVertices=e,this.snapManager.setExcludedVertices(e)}snap(e){if(!this.snapToVertices&&!this.snapToGrid)return this.noSnapResult(e);let t=this.snapManager.snap(e,this.plane);return t.snapType===`vertex`&&!this.snapToVertices||t.snapType===`grid`&&!this.snapToGrid?this.noSnapResult(e):t}noSnapResult(e){let t=this.plane.origin,n=this.plane.xDirection,r=this.plane.yDirection;return{point2d:e,worldPoint:new R(t.x+n.x*e[0]+r.x*e[1],t.y+n.y*e[0]+r.y*e[1],t.z+n.z*e[0]+r.z*e[1]),snapType:`none`}}},Cy=class{viewer;container;trimService;timelinePanel;toolbar;activeSketchInfo=null;activeDrawingTool=null;activeDragHandler=null;activeHoverSelectHandler=null;bezierHandles;shortcuts;constructor(e,t,n,r){this.viewer=t,this.container=e,this.trimService=n,this.timelinePanel=r,this.toolbar=new B_(r.toolbarHost,e=>{this.handleToolSelect(e)}),this.shortcuts=new P_,this.shortcuts.register(`n`,()=>this.lookAlongSketchNormal()),this.bezierHandles=new xy(t.sceneContext),this.toolbar.onSnapVerticesChange=e=>{this.activeDrawingTool&&(this.activeDrawingTool.snapController.snapToVertices=e),this.activeDragHandler&&(this.activeDragHandler.snapController.snapToVertices=e)},this.toolbar.onSnapGridChange=e=>{this.activeDrawingTool&&(this.activeDrawingTool.snapController.snapToGrid=e),this.activeDragHandler&&(this.activeDragHandler.snapController.snapToGrid=e)}}get hasActiveDrawingTool(){return this.activeDrawingTool!==null}update(e){let t=null;for(let n=e.length-1;n>=0;n--)if(y_(e[n],e)){t=e[n];break}if(t?.type===`sketch`&&t.id&&t.object?.plane&&t.sourceLocation){let n=t.object.plane,r=this.activeSketchInfo?.sketchObj.id;if(this.activeSketchInfo={sketchObj:t,plane:n,sourceLocation:t.sourceLocation},this.toolbar.isVisible||(this.toolbar.show(),this.shortcuts.enable(),this.timelinePanel.slideOut()),this.bezierHandles.activate(),this.bezierHandles.update(e,t.id,n),this.activeDrawingTool)r===t.id?(this.activeDrawingTool.updatePlane(n),this.activeDrawingTool.onSceneUpdate(e,t.id),t.object?.currentPosition&&this.activeDrawingTool.updateCurrentPosition(t.object.currentPosition)):this.handleToolSelect(this.toolbar.activeTool);else if(this.activeDragHandler){this.activeDragHandler.updatePlane(n);let r=new Sy(v_.fromSceneObjects(e,t.id,n,this.viewer.sceneContext),n);r.snapToVertices=this.toolbar.snapVerticesChecked,r.snapToGrid=this.toolbar.snapGridChecked,this.activeDragHandler.updateSnapController(r),this.activeDragHandler.updateSceneData(e,t.id),this.activeHoverSelectHandler&&(this.activeHoverSelectHandler.updatePlane(n),this.activeHoverSelectHandler.updateSceneData(e,t.id))}else this.toolbar.activeTool||this.activateDragHandler()}else this.activeDrawingTool&&=(this.activeDrawingTool.deactivate(),null),this.deactivateDragHandler(),this.bezierHandles.deactivate(),this.activeSketchInfo=null,this.toolbar.hide(),this.shortcuts.disable(),this.timelinePanel.slideIn()}async fetchScopeVariables(){return this.activeSketchInfo?Wm(this.activeSketchInfo.sourceLocation.line):[]}createTool(e,t,n,r){let i=new Sy(v_.fromSceneObjects(n,r,t,this.viewer.sceneContext),t);i.snapToVertices=this.toolbar.snapVerticesChecked,i.snapToGrid=this.toolbar.snapGridChecked;let a=(e,t)=>{this.activeSketchInfo&&Lm(e,this.activeSketchInfo.sourceLocation,t)},o=()=>this.fetchScopeVariables();switch(e){case`line`:{let e=new yv(this.viewer.sceneContext,t,i,a,this.container,o);return e.onSceneUpdate(n,r),e}case`circle`:return new bv(this.viewer.sceneContext,t,i,a,this.container,o);case`polygon`:return new Wv(this.viewer.sceneContext,t,i,a,this.container,o);case`arc2`:return new Sv(this.viewer.sceneContext,t,i,a,this.container,o);case`arc3`:{let e=new wv(this.viewer.sceneContext,t,i,a,this.container,o);return e.onSceneUpdate(n,r),e}case`polyline`:{let e=new Rv(this.viewer.sceneContext,t,i,a,this.container,o);return e.onSceneUpdate(n,r),e}case`bezier`:{let e=new zv(this.viewer.sceneContext,t,i,a,this.container,o);return e.onSceneUpdate(n,r),e}case`rect`:return new Tv(this.viewer.sceneContext,t,i,a,this.container,o);case`rounded-rect`:return new Ev(this.viewer.sceneContext,t,i,a,this.container,o);case`slot`:return new Dv(this.viewer.sceneContext,t,i,a,this.container,o);default:return null}}activateDragHandler(){if(this.activeDragHandler||!this.activeSketchInfo)return;let e=new Sy(v_.fromSceneObjects(this.viewer.currentSceneObjects,this.activeSketchInfo.sketchObj.id,this.activeSketchInfo.plane,this.viewer.sceneContext),this.activeSketchInfo.plane);e.snapToVertices=this.toolbar.snapVerticesChecked,e.snapToGrid=this.toolbar.snapGridChecked,this.activeDragHandler=new dy(this.viewer.sceneContext,this.activeSketchInfo.plane,e,this.container,()=>this.fetchScopeVariables(),()=>this.activeSketchInfo?.sourceLocation.line??null),this.activeDragHandler.updateSceneData(this.viewer.currentSceneObjects,this.activeSketchInfo.sketchObj.id),this.activeDragHandler.activate(),this.activeHoverSelectHandler=new hy(this.viewer.sceneContext,this.activeSketchInfo.plane,()=>this.activeDragHandler?.isResizing??!1),this.activeHoverSelectHandler.updateSceneData(this.viewer.currentSceneObjects,this.activeSketchInfo.sketchObj.id),this.activeHoverSelectHandler.activate()}deactivateDragHandler(){this.activeHoverSelectHandler&&=(this.activeHoverSelectHandler.deactivate(),null),this.activeDragHandler&&=(this.activeDragHandler.deactivate(),null)}handleToolSelect(e){if(!e&&this.activeDrawingTool?.handleEscape?.())return;if(this.activeDrawingTool&&=(this.activeDrawingTool.deactivate(),null),this.toolbar.activeTool===`trim`&&e!==`trim`&&this.exitTrimFromToolbar(),this.toolbar.setActiveTool(e),!e||!this.activeSketchInfo){!e&&this.activeSketchInfo&&this.activateDragHandler();return}if(this.deactivateDragHandler(),e===`trim`){this.enterTrimFromToolbar();return}let t=this.createTool(e,this.activeSketchInfo.plane,this.viewer.currentSceneObjects,this.activeSketchInfo.sketchObj.id);t&&(this.activeSketchInfo.sketchObj.object?.currentPosition&&t.updateCurrentPosition(this.activeSketchInfo.sketchObj.object.currentPosition),t.activate(),this.activeDrawingTool=t)}enterTrimFromToolbar(){if(this.activeSketchInfo){if(this.trimService.lastPickInfo){this.trimService.enter(),this.trimService.hideBars();return}this.trimService.pendingActivation=!0,Lm(`trim()`,this.activeSketchInfo.sourceLocation)}}exitTrimFromToolbar(){if(this.trimService.pendingActivation=!1,this.trimService.state===`picking-active`&&this.trimService.exit(),this.trimService.lastPickInfo){let e=this.trimService.lastPickInfo.trimObj,t=e?.object?.picking,n=e?.object?.pickPoints;t&&(!n||n.length===0)&&e?.sourceLocation&&Im(e.sourceLocation)}this.trimService.reset()}lookAlongSketchNormal(){this.activeSketchInfo&&this.viewer.lookAlongSketchNormal(this.activeSketchInfo.plane)}},wy=class extends vf{constructor(){super(),this.isLineGeometry=!0,this.type=`LineGeometry`}setPositions(e){let t=e.length-3,n=new Float32Array(2*t);for(let r=0;r<t;r+=3)n[2*r]=e[r],n[2*r+1]=e[r+1],n[2*r+2]=e[r+2],n[2*r+3]=e[r+3],n[2*r+4]=e[r+4],n[2*r+5]=e[r+5];return super.setPositions(n),this}setColors(e){let t=e.length-3,n=new Float32Array(2*t);for(let r=0;r<t;r+=3)n[2*r]=e[r],n[2*r+1]=e[r+1],n[2*r+2]=e[r+2],n[2*r+3]=e[r+3],n[2*r+4]=e[r+4],n[2*r+5]=e[r+5];return super.setColors(n),this}setFromPoints(e){let t=e.length-1,n=new Float32Array(6*t);for(let r=0;r<t;r++)n[6*r]=e[r].x,n[6*r+1]=e[r].y,n[6*r+2]=e[r].z||0,n[6*r+3]=e[r+1].x,n[6*r+4]=e[r+1].y,n[6*r+5]=e[r+1].z||0;return super.setPositions(n),this}fromLine(e){let t=e.geometry;return this.setPositions(t.attributes.position.array),this}},Ty=class extends Rf{constructor(e=new wy,t=new yf({color:Math.random()*16777215})){super(e,t),this.isLine2=!0,this.type=`Line2`}},Ey={x:15026253,y:3187820,z:4088797},Dy=999,Oy=class{group=null;constructor(e){this.ctx=e}show(e){this.clear();let{from:t,to:n,axis:r}=e;if(ky(t,n)<1e-12)return;let i=new oi;if(i.name=`measureOverlay`,i.userData.isMetaShape=!0,i.add(this.makeLine(t,n,Wd.highlightColor.getHex(),{width:2.5})),r){let e={x:r===`x`?n.x:t.x,y:r===`y`?n.y:t.y,z:r===`z`?n.z:t.z};ky(t,e)>1e-12&&i.add(this.makeLine(t,e,Ey[r],{width:3.5})),ky(e,n)>1e-12&&i.add(this.makeLine(e,n,Wd.metaEdgeColor.getHex(),{width:1.5,dashed:!0})),i.add(this.makePoints([t,n,e]))}else i.add(this.makePoints([t,n]));i.traverse(e=>{e.userData.isMetaShape=!0,e.renderOrder=Dy}),this.group=i,this.ctx.scene.add(i),this.ctx.requestRender()}clear(){this.group&&(this.group.traverse(e=>{e.geometry?.dispose(),e.material?.dispose()}),this.group.parent?.remove(this.group),this.group=null,this.ctx.requestRender())}makeLine(e,t,n,r){let i=new wy;i.setPositions([e.x,e.y,e.z,t.x,t.y,t.z]);let a=Math.sqrt(ky(e,t)),o=new yf({color:n,linewidth:r.width,transparent:!0,depthTest:!1,depthWrite:!1,dashed:!!r.dashed,dashSize:a/16,gapSize:a/24});Kd.register(o);let s=new Ty(i,o);return r.dashed&&s.computeLineDistances(),s}makePoints(e){let t=new H,n=e.flatMap(e=>[e.x,e.y,e.z]);return t.setAttribute(`position`,new br(n,3)),new ta(t,new Xi({color:Wd.highlightColor.getHex(),size:7,sizeAttenuation:!1,transparent:!0,depthTest:!1,depthWrite:!1}))}};function ky(e,t){let n=e.x-t.x,r=e.y-t.y,i=e.z-t.z;return n*n+r*r+i*i}var Ay=[{value:`mm`,label:`Millimeter`},{value:`cm`,label:`Centimeter`},{value:`m`,label:`Meter`},{value:`in`,label:`Inch`}],jy=[{value:`deg`,label:`Degree`},{value:`rad`,label:`Radian`}],My={mm:1,cm:.1,m:.001,in:1/25.4},Ny={mm:2,cm:3,m:5,in:3};function Py(e,t){return e*My[t]}function Fy(e,t){return`${Py(e,t).toFixed(Ny[t])} ${t}`}function Iy(e,t){let n=My[t];return`${(e*n*n).toFixed(Ny[t])} ${t}²`}function Ly(e,t){return t===`rad`?`${(Math.PI/180*e).toFixed(4)} rad`:`${e.toFixed(2)} deg`}var Ry={plane:`Plane face`,cylinder:`Cylindrical face`,cone:`Conical face`,sphere:`Spherical face`,torus:`Toroidal face`,surface:`Face`,line:`Line edge`,circle:`Circle edge`,arc:`Arc edge`,ellipse:`Ellipse edge`,curve:`Edge`},zy=[{key:`parallelDist`,label:`Parallel dist`},{key:`centerDist`,label:`Center dist`},{key:`axisDist`,label:`Axis dist`},{key:`minDist`,label:`Min dist`},{key:`maxDist`,label:`Max dist`}],By=[{axis:`x`,cls:`text-error`},{axis:`y`,cls:`text-success`},{axis:`z`,cls:`text-info`}];function Vy(e){let t=document.createElement(`div`);return t.textContent=e,t.innerHTML}var Hy=class{el;data={entities:[],result:null,lengthUnit:`mm`,angleUnit:`deg`};constructor(e,t){this.callbacks=t,this.el=document.createElement(`div`),this.el.className=`absolute bottom-[64px] right-[76px] z-[150] w-[290px] panel-bg border border-base-content/10 rounded-lg p-3 shadow-[0_4px_24px_rgba(0,0,0,0.5)] text-xs text-base-content select-none max-h-[70vh] overflow-y-auto hidden`,e.appendChild(this.el)}get isVisible(){return!this.el.classList.contains(`hidden`)}setVisible(e){this.el.classList.toggle(`hidden`,!e)}update(e){this.data=e,this.render()}render(){let{entities:e,result:t}=this.data,n=e.length?e.map((e,t)=>`<div class="flex items-center justify-between gap-1 px-2 py-1 border-b border-base-content/10 last:border-0">
5440
+ <span class="truncate">${Vy(e.label)}</span>
5441
+ <button data-remove="${t}" title="Remove" class="btn btn-ghost btn-xs btn-square shrink-0 opacity-60 hover:opacity-100 [&>svg]:w-3 [&>svg]:h-3">${ug}</button>
5442
+ </div>`).join(``):`<div class="px-2 py-2 text-base-content/50">Click faces or edges in the viewport to measure</div>`,r=Ay.map(e=>`<option value="${e.value}" ${e.value===this.data.lengthUnit?`selected`:``}>${e.label}</option>`).join(``),i=jy.map(e=>`<option value="${e.value}" ${e.value===this.data.angleUnit?`selected`:``}>${e.label}</option>`).join(``);this.el.innerHTML=`
5443
+ <div class="flex items-center justify-between mb-2">
5444
+ <span class="text-sm font-semibold">Measure</span>
5445
+ <button data-close title="Close" class="btn btn-ghost btn-xs btn-square opacity-60 hover:opacity-100 [&>svg]:w-4 [&>svg]:h-4">${ug}</button>
5446
+ </div>
5447
+ <div class="border border-base-content/15 rounded-md mb-2 max-h-28 overflow-y-auto">${n}</div>
5448
+ <div class="grid grid-cols-[auto_1fr] items-center gap-x-2 gap-y-1 mb-2">
5449
+ <span class="text-base-content/60">Length unit</span>
5450
+ <select data-length-unit class="select select-xs w-full bg-base-200 border-base-content/15">${r}</select>
5451
+ <span class="text-base-content/60">Angle unit</span>
5452
+ <select data-angle-unit class="select select-xs w-full bg-base-200 border-base-content/15">${i}</select>
5453
+ </div>
5454
+ ${t?`<div class="border-t border-base-content/10 pt-2">${this.renderRows(t)}</div>`:``}
5455
+ `,this.bindEvents()}renderRows(e){let t=[];this.data.entities.length===1&&e.entities.length===1&&t.push(this.renderEntityDetails(e.entities[0]));let n=e.entities.length===2;if(n)if(e.primary===`angle`&&e.angleDeg!==void 0)t.push(this.row(Vy(e.angleLabel??`Angle`),Ly(e.angleDeg,this.data.angleUnit)));else{let n=zy.find(t=>t.key===e.primary);n&&e[n.key]&&t.push(this.distanceRows(n.key,n.label,e[n.key])),e.angleDeg!==void 0&&t.push(this.row(Vy(e.angleLabel??`Angle`),Ly(e.angleDeg,this.data.angleUnit)))}let r=e.entities.filter(e=>e.ref.kind===`face`).length,i=e.entities.filter(e=>e.ref.kind===`edge`).length;if(e.totalArea!==void 0&&t.push(this.row(r>1?`Total area`:`Area`,Iy(e.totalArea,this.data.lengthUnit))),e.totalLength!==void 0&&t.push(this.row(i>1?`Total length`:`Length`,Fy(e.totalLength,this.data.lengthUnit))),n)for(let{key:n,label:r}of zy){if(n===e.primary)continue;let i=e[n];i&&t.push(this.distanceRows(n,r,i))}return t.join(``)}renderEntityDetails(e){let t=[this.row(`Type`,Ry[e.geomType]??e.geomType)];return e.area!==void 0&&t.push(this.row(`Area`,Iy(e.area,this.data.lengthUnit))),e.radius!==void 0&&(t.push(this.row(`Radius`,Fy(e.radius,this.data.lengthUnit))),t.push(this.row(`Diameter`,Fy(e.radius*2,this.data.lengthUnit)))),t.join(``)}row(e,t){return`<div class="flex justify-between items-baseline gap-2 px-1 py-0.5 rounded">
5456
+ <span class="text-base-content/60">${e}</span>
5457
+ <span class="font-medium tabular-nums">${t}</span>
5458
+ </div>`}distanceRows(e,t,n){return`<div data-viz="${e}" class="flex justify-between items-baseline gap-2 px-1 py-0.5 rounded hover:bg-base-content/10 cursor-default">
5459
+ <span class="text-base-content/60">${t}</span>
5460
+ <span class="font-medium tabular-nums">${Fy(n.value,this.data.lengthUnit)}</span>
5461
+ </div>`+By.map(({axis:t,cls:r})=>{let i=n.to[t]-n.from[t];return`<div data-viz="${e}:${t}" class="flex justify-between items-baseline gap-2 pl-5 pr-1 py-0.5 rounded hover:bg-base-content/10 cursor-default">
5462
+ <span class="${r} font-semibold">${t.toUpperCase()}</span>
5463
+ <span class="tabular-nums text-base-content/90">${Fy(i,this.data.lengthUnit)}</span>
5464
+ </div>`}).join(``)}bindEvents(){this.el.querySelector(`[data-close]`)?.addEventListener(`click`,()=>this.callbacks.onClose()),this.el.querySelectorAll(`[data-remove]`).forEach(e=>{e.addEventListener(`click`,()=>{let t=parseInt(e.dataset.remove,10),n=this.data.entities[t];n&&this.callbacks.onRemoveEntity(n.ref)})}),this.el.querySelector(`[data-length-unit]`)?.addEventListener(`change`,e=>{this.callbacks.onLengthUnitChange(e.target.value)}),this.el.querySelector(`[data-angle-unit]`)?.addEventListener(`change`,e=>{this.callbacks.onAngleUnitChange(e.target.value)}),this.el.querySelectorAll(`[data-viz]`).forEach(e=>{e.addEventListener(`mouseenter`,()=>{let t=this.resolveViz(e.dataset.viz);t&&this.callbacks.onHoverViz(t)}),e.addEventListener(`mouseleave`,()=>this.callbacks.onHoverViz(null))})}resolveViz(e){let[t,n]=e.split(`:`),r=this.data.result?.[t];return r?{from:r.from,to:r.to,axis:n}:null}},Uy=class{el;labelEl;valueEl;chevronEl;constructor(e,t){this.el=document.createElement(`div`),this.el.className=`absolute bottom-6 right-[76px] z-[150] panel-bg border border-base-content/10 rounded-lg h-8 px-3 text-xs text-base-content flex items-center gap-2 cursor-pointer select-none hover:border-base-content/30 hidden`,this.el.title=`Show all measurements`;let n=document.createElement(`span`);n.className=`opacity-60 [&>svg]:w-4 [&>svg]:h-4`,n.innerHTML=qh,this.labelEl=document.createElement(`span`),this.labelEl.className=`text-base-content/60 whitespace-nowrap`,this.valueEl=document.createElement(`span`),this.valueEl.className=`font-medium tabular-nums whitespace-nowrap`,this.chevronEl=document.createElement(`span`),this.chevronEl.className=`opacity-60 transition-transform rotate-180`,this.chevronEl.innerHTML=ag,this.el.append(n,this.labelEl,this.valueEl,this.chevronEl),this.el.addEventListener(`click`,t),e.appendChild(this.el)}show(e,t){this.labelEl.textContent=`${e}:`,this.valueEl.textContent=t,this.el.classList.remove(`hidden`)}hide(){this.el.classList.add(`hidden`)}setExpanded(e){this.chevronEl.classList.toggle(`rotate-180`,!e)}},Wy=8,Gy=[`parallelDist`,`centerDist`,`axisDist`,`minDist`,`maxDist`];function Ky(e,t){return e.shapeId===t.shapeId&&e.sub.type===t.sub.type&&e.sub.index===t.sub.index}function qy(e){return{shapeId:e.shapeId,kind:e.sub.type,index:e.sub.index}}var Jy=class{entities=[];result=null;panelOpen=!1;lengthUnit=`mm`;angleUnit=`deg`;abortController=null;statusBar;panel;overlay;constructor(e,t){this.viewer=t,this.statusBar=new Uy(e,()=>this.togglePanel()),this.panel=new Hy(e,{onClose:()=>this.togglePanel(!1),onRemoveEntity:e=>this.removeEntity(e),onLengthUnitChange:e=>{this.lengthUnit=e,ih(`measureLengthUnit`,e),this.updateUI()},onAngleUnitChange:e=>{this.angleUnit=e,ih(`measureAngleUnit`,e),this.updateUI()},onHoverViz:e=>{e?this.overlay.show(e):this.applyDefaultViz()}}),this.overlay=new Oy(t.sceneContext)}applyPreferences(e){e.measureLengthUnit&&(this.lengthUnit=e.measureLengthUnit),e.measureAngleUnit&&(this.angleUnit=e.measureAngleUnit),this.updateUI()}get selection(){return this.entities}handleClick(e,t,n){if(!e||!t)return n&&this.entities.length>0||this.setSelection([]),this.entities;let r={shapeId:e,sub:t},i=this.entities.findIndex(e=>Ky(e,r)),a;return n||this.panelOpen?(a=i>=0?this.entities.filter((e,t)=>t!==i):[...this.entities,r],a.length>Wy&&(a=a.slice(a.length-Wy))):a=[r],this.setSelection(a),this.entities}clearSelection(){this.setSelection([])}onSceneRendered(){this.abortController?.abort(),this.abortController=null,this.entities=[],this.result=null,this.updateUI()}setSelection(e){this.entities=e,e.length>0?this.viewer.highlightEntities(e):this.viewer.clearHighlight(),this.fetchMeasurement()}fetchMeasurement(){if(this.abortController?.abort(),this.abortController=null,this.entities.length===0){this.result=null,this.updateUI();return}let e=new AbortController;this.abortController=e;let t=this.entities.map(qy);this.result=null,this.updateUI(),Jm(t,e.signal).then(t=>{e.signal.aborted||this.abortController!==e||(this.result=t,this.updateUI())})}removeEntity(e){let t=this.entities.filter(t=>!(t.shapeId===e.shapeId&&t.sub.type===e.kind&&t.sub.index===e.index));this.setSelection(t)}togglePanel(e=!this.panelOpen){this.panelOpen=e,this.panel.setVisible(e),this.statusBar.setExpanded(e)}updateUI(){this.entities.length>=2&&this.result?(this.statusBar.show(this.result.primaryLabel,this.primaryValueText(this.result)),this.statusBar.setExpanded(this.panelOpen)):this.entities.length>=2?this.statusBar.show(`Measuring`,`…`):this.statusBar.hide(),this.panel.update({entities:this.entities.map((e,t)=>({ref:qy(e),label:`Selection ${t+1} [${e.sub.type===`face`?`Face`:`Edge`}]`})),result:this.result,lengthUnit:this.lengthUnit,angleUnit:this.angleUnit}),this.applyDefaultViz()}primaryValueText(e){if(e.primary===`angle`)return e.angleDeg===void 0?`—`:Ly(e.angleDeg,this.angleUnit);if(e.primary===`totalArea`)return e.totalArea===void 0?`—`:Iy(e.totalArea,this.lengthUnit);if(e.primary===`totalLength`)return e.totalLength===void 0?`—`:Fy(e.totalLength,this.lengthUnit);let t=e[e.primary];return t?Fy(t.value,this.lengthUnit):`—`}applyDefaultViz(){let e=this.result;if(!e||this.entities.length!==2||!Gy.includes(e.primary)){this.overlay.clear();return}let t=e[e.primary];t?this.overlay.show({from:t.from,to:t.to}):this.overlay.clear()}};M_();var Yy=document.getElementById(`fluidcad-viewer`)||document.body,Xy=new a_(Yy),Zy=new xg(`fluidcad-viewer`);Gd(()=>Zy.rebuildSceneMesh()),rh().then(e=>{e&&(document.documentElement.setAttribute(`data-theme`,e.theme),uf(e),rb.setShowBuildTimings(!!e.showBuildTimings),eb.applyPreferences(e))});var Qy=new Og(Yy),$y=new jg(Yy),eb=new Jy(Yy,Zy),tb=new n_(Yy,Zy.sceneContext),nb=new o_(Yy,{showLoading:e=>Xy.show(e),hideLoading:()=>Xy.hide()}),rb=new zg(Yy,e=>Zy.highlightShape(e),e=>tb.show(e),(e,t)=>Zy.setShapeVisibility(e,t),e=>Zy.isShapeHidden(e),(e,t)=>Zy.setShapeTransparency(e,t),e=>Zy.getShapeTransparency(e),()=>Zy.resetAllTransparency(),()=>nb.openPicker()),ib=new Bg(Zy.settingsPanelHost);Zy.setParamsToggleHandler(()=>{ib.toggle(),Zy.setParamsButtonActive(ib.isVisible)});var ab=new S_(Yy,Zy),ob=new D_(Yy,Zy),sb=new Cy(Yy,Zy,ab,rb),cb=new r_(Yy,()=>{ob.state===`picking-active`&&ob.exit(),ab.state===`picking-active`&&ab.exit()}),lb=new i_(Yy,e=>{eh(e)});Qy.setOpenHandler(()=>{eb.clearSelection(),Zy.clearHighlight(),$y.hide()}),Qy.setCentroidHandler(e=>{e?Zy.showCentroid(e):Zy.clearCentroid()}),Zy.setSelectionHandler((e,t,n)=>{if(Qy.isOpen){eb.clearSelection(),e?Zy.highlightShape(e):Zy.clearHighlight(),Qy.setSelectedShape(e),$y.hide();return}let r=eb.handleClick(e,t,n.additive);if(r.length===1){let e=r[0];Qy.setSelectedShape(e.shapeId),e.sub.type===`face`?$y.showForFace(e.shapeId,e.sub.index):$y.showForEdge(e.shapeId,e.sub.index)}else Qy.setSelectedShape(r.length>0?r[0].shapeId:null),$y.hide()});async function ub(e,t,n){try{let r={...n||{}},i=!!r.multi;delete r.multi;let a=await(i?await Yg(Zy.sceneContext,r):await Jg(Zy.sceneContext,r)).arrayBuffer(),o=new Uint8Array(a),s=``;for(let e=0;e<o.length;e++)s+=String.fromCharCode(o[e]);e.send(JSON.stringify({type:`screenshot-result`,requestId:t,success:!0,data:btoa(s)}))}catch(n){e.send(JSON.stringify({type:`screenshot-result`,requestId:t,success:!1,error:n.message||String(n)}))}}var db=200,fb=0,pb=!1,mb=null;function hb(){if(!mb||mb.readyState!==WebSocket.OPEN)return;let e=Zy.sceneContext,t=e.camera,n={x:0,y:0,z:0};e.cameraControls.getTarget(n),mb.send(JSON.stringify({type:`camera-state`,position:[t.position.x,t.position.y,t.position.z],target:[n.x,n.y,n.z],up:[t.up.x,t.up.y,t.up.z],projection:t.isOrthographicCamera?`orthographic`:`perspective`}))}function gb(){let e=Date.now();if(e-fb>=db){fb=e,hb();return}if(pb)return;pb=!0;let t=db-(e-fb);setTimeout(()=>{pb=!1,fb=Date.now(),hb()},Math.max(0,t))}Zy.sceneContext.cameraControls.addEventListener(`update`,gb);function _b(){let e=`ws://${window.location.host}`,t=new WebSocket(e);t.addEventListener(`open`,()=>{mb=t,hb()}),t.addEventListener(`message`,e=>{let n=JSON.parse(e.data);switch(n.type){case`init-complete`:Xy.show(`Loading model...`);break;case`processing-file`:Xy.show(`Loading model...`);break;case`scene-rendered`:{Xy.hide();let e=n.rollbackStop!=null&&n.rollbackStop<n.result.length-1;Zy.isTrimming=!e&&ab.state===`picking-active`,Zy.isDrawing=!e&&sb.hasActiveDrawingTool,Zy.updateView(n.result,e,n.rollbackStop),eb.onSceneRendered(),n.absPath&&Zy.setFileName(n.absPath),e?(ab.reset(),ob.reset(),sb.update([])):(ab.update(n.result),ob.update(n.result),sb.update(n.result)),rb.update(n.result,n.rollbackStop??n.result.length-1,n.absPath),n.params!==void 0&&(ib.update(n.params),Zy.setParamsButtonVisible(ib.hasAnyParams)),lb.update(n.result,n.compileError??null),n.breakpointHit!==void 0&&cb.setActive(n.breakpointHit);break}case`highlight-shape`:eb.clearSelection(),Zy.highlightShape(n.shapeId),Qy.setSelectedShape(n.shapeId);break;case`clear-highlight`:eb.clearSelection(),Zy.clearHighlight(),Qy.setSelectedShape(null),$y.hide();break;case`show-shape-properties`:eb.clearSelection(),Zy.clearHighlight(),$y.hide(),Qy.show(n.shapeId);break;case`take-screenshot`:ub(t,n.requestId,n.options);break}}),t.addEventListener(`close`,()=>{mb===t&&(mb=null),lb.update([],null),setTimeout(_b,1e3)})}_b();