@selvajs/compute 3.1.0-beta.9 → 3.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/dist/chunk-FQKQISPG.cjs +2 -0
- package/dist/chunk-FQKQISPG.cjs.map +1 -0
- package/dist/chunk-H3FZW6OX.cjs +4 -0
- package/dist/chunk-H3FZW6OX.cjs.map +1 -0
- package/dist/chunk-N2WCSETE.js +120 -0
- package/dist/chunk-N2WCSETE.js.map +1 -0
- package/dist/chunk-RFE763NG.cjs +120 -0
- package/dist/chunk-RFE763NG.cjs.map +1 -0
- package/dist/chunk-S3VUIIRE.js +2 -0
- package/dist/chunk-S3VUIIRE.js.map +1 -0
- package/dist/chunk-Y3M7P3BW.js +4 -0
- package/dist/chunk-Y3M7P3BW.js.map +1 -0
- package/dist/core.cjs +1 -1
- package/dist/core.cjs.map +1 -1
- package/dist/core.d.cts +22 -1
- package/dist/core.d.ts +22 -1
- package/dist/core.js +1 -1
- package/dist/grasshopper.cjs +1 -1
- package/dist/grasshopper.cjs.map +1 -1
- package/dist/grasshopper.d.cts +22 -2
- package/dist/grasshopper.d.ts +22 -2
- package/dist/grasshopper.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/{types-Dtok-mVq.d.ts → types-4FMvnx2j.d.ts} +14 -1
- package/dist/{types-C8XWc4Ab.d.cts → types-BpOl6U02.d.cts} +14 -1
- package/dist/visualization-E6BTQZCA.cjs +2 -0
- package/dist/visualization-E6BTQZCA.cjs.map +1 -0
- package/dist/visualization-HDBKPJGQ.js +2 -0
- package/dist/visualization.cjs +1 -1
- package/dist/visualization.cjs.map +1 -1
- package/dist/visualization.d.cts +331 -29
- package/dist/visualization.d.ts +331 -29
- package/dist/visualization.js +1 -1
- package/package.json +55 -34
- package/dist/chunk-CUQQ3ZBV.cjs +0 -4
- package/dist/chunk-CUQQ3ZBV.cjs.map +0 -1
- package/dist/chunk-GFY3L653.cjs +0 -62
- package/dist/chunk-GFY3L653.cjs.map +0 -1
- package/dist/chunk-MJOXUCDH.js +0 -62
- package/dist/chunk-MJOXUCDH.js.map +0 -1
- package/dist/chunk-WPB2LKCD.js +0 -4
- package/dist/chunk-WPB2LKCD.js.map +0 -1
- package/dist/chunk-WWD655BZ.cjs +0 -2
- package/dist/chunk-WWD655BZ.cjs.map +0 -1
- package/dist/chunk-YREXY7GT.js +0 -2
- package/dist/chunk-YREXY7GT.js.map +0 -1
- package/dist/visualization-4PVR5P7N.js +0 -2
- package/dist/visualization-LS3Z7Q3N.cjs +0 -2
- package/dist/visualization-LS3Z7Q3N.cjs.map +0 -1
- /package/dist/{visualization-4PVR5P7N.js.map → visualization-HDBKPJGQ.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/selva/selva/packages/compute/dist/chunk-RFE763NG.cjs","../src/features/visualization/threejs/three-materials.ts","../src/features/visualization/threejs/up-axis.ts","../src/features/visualization/threejs/three-helpers.ts","../src/features/visualization/threejs/grid.ts","../src/features/visualization/threejs/edge-extract.ts","../src/features/visualization/threejs/edges.ts","../src/features/visualization/threejs/edge-detection-pass.ts","../src/features/visualization/threejs/label-layer.ts","../src/features/visualization/threejs/three-initializer.ts","../src/features/visualization/webdisplay/batch-parser.ts","../src/features/visualization/webdisplay/webdisplay-parser.ts"],"names":["three_materials_exports","__export","CONCRETE_MATERIAL","EMISSIVE_MATERIAL","GLASS_MATERIAL","METAL_MATERIAL","PLASTIC_MATERIAL","RUBBER_MATERIAL","SHARED_MATERIALS","WOOD_MATERIAL","buildUpBasis","up","u","worldZ","worldY","seed","right","forward","isoOffset","distance","sunOffset","sideDistance","height","environmentRotationFor","mapZenith","quaternion","upToAxis","ax","ay","az","CAMERA_CONFIG","updateScene","scene","meshes","camera","controls","initialPositionSet","clearScene","mesh","unionBoundingBox","computeCombinedBoundingBox","center","size","maxDim","parseColor","colorString","getLogger","trimmed","hex","distanceFade"],"mappings":"AAAA,2/BAAgF,ICAhFA,EAAAA,CAAA,CAAA,CAAA,CAAAC,iCAAAA,EAAAD,CAAA,CAAA,iBAAA,CAAA,CAAA,CAAA,EAAAE,EAAAA,CAAA,iBAAA,CAAA,CAAA,CAAA,EAAAC,EAAAA,CAAA,cAAA,CAAA,CAAA,CAAA,EAAAC,EAAAA,CAAA,cAAA,CAAA,CAAA,CAAA,EAAAC,EAAAA,CAAA,gBAAA,CAAA,CAAA,CAAA,EAAAC,EAAAA,CAAA,eAAA,CAAA,CAAA,CAAA,EAAAC,EAAAA,CAAA,gBAAA,CAAA,CAAA,CAAA,EAAAC,EAAAA,CAAA,aAAA,CAAA,CAAA,CAAA,EAAAC,EAAAA,CAAAA,CAAAA,CAAA,0oBAAuB,IAEVN,EAAAA,CAAoB,IAAU,CAAA,CAAA,oBAAA,CAAqB,CAC/D,KAAA,CAAO,CAAA,CACP,QAAA,CAAU,IAAU,CAAA,CAAA,KAAA,CAAM,QAAQ,CAAA,CAClC,iBAAA,CAAmB,CAAA,CACnB,SAAA,CAAW,CAAA,CACX,SAAA,CAAW,EAAA,CACX,SAAA,CAAW,EAAA,CACX,kBAAA,CAAoB,EAAA,CACpB,UAAA,CAAY,CAAA,CAAA,CACZ,SAAA,CAAW,CAAA,CAAA,CACX,WAAA,CAAa,CAAA,CAAA,CACb,SAAA,CAAW,CAAA,CACX,aAAA,CAAe,CAAA,CAAA,CACf,mBAAA,CAAqB,CAAA,CACrB,kBAAA,CAAoB,CAAA,CACpB,IAAA,CAAY,CAAA,CAAA,SAAA,CACZ,SAAA,CAAW,CAAA,CACZ,CAAC,CAAA,CAEYE,EAAAA,CAAiB,IAAU,CAAA,CAAA,oBAAA,CAAqB,CAC5D,KAAA,CAAO,IAAU,CAAA,CAAA,KAAA,CAAM,CAAQ,CAAA,CAC/B,SAAA,CAAW,EAAA,CACX,SAAA,CAAW,EAAA,CACX,eAAA,CAAiB,GAAA,CACjB,SAAA,CAAW,EAAA,CACX,kBAAA,CAAoB,EAAA,CACpB,YAAA,CAAc,CAAA,CACd,GAAA,CAAK,GAAA,CACL,SAAA,CAAW,CAAA,CACX,UAAA,CAAY,CAAA,CAAA,CACZ,WAAA,CAAa,CAAA,CAAA,CACb,SAAA,CAAW,CAAA,CACX,SAAA,CAAW,CAAA,CAAA,CACX,aAAA,CAAe,CAAA,CAAA,CACf,mBAAA,CAAqB,CAAA,CACrB,kBAAA,CAAoB,CAAA,CACpB,IAAA,CAAY,CAAA,CAAA,SAAA,CACZ,SAAA,CAAW,CAAA,CACZ,CAAC,CAAA,CAEYH,EAAAA,CAAoB,IAAU,CAAA,CAAA,oBAAA,CAAqB,CAC/D,KAAA,CAAO,IAAU,CAAA,CAAA,KAAA,CAAM,QAAQ,CAAA,CAC/B,SAAA,CAAW,CAAA,CACX,SAAA,CAAW,GAAA,CACX,eAAA,CAAiB,GAAA,CACjB,SAAA,CAAW,GAAA,CACX,kBAAA,CAAoB,EAAA,CACpB,YAAA,CAAc,GAAA,CACd,YAAA,CAAc,CAAA,CACd,GAAA,CAAK,IAAA,CACL,SAAA,CAAW,CAAA,CACX,UAAA,CAAY,CAAA,CAAA,CACZ,WAAA,CAAa,CAAA,CAAA,CAGb,SAAA,CAAW,CAAA,CACX,SAAA,CAAW,CAAA,CAAA,CACX,aAAA,CAAe,CAAA,CAAA,CACf,mBAAA,CAAqB,CAAA,CACrB,kBAAA,CAAoB,CAAA,CACpB,IAAA,CAAY,CAAA,CAAA,SAAA,CACZ,SAAA,CAAW,CAAA,CACZ,CAAC,CAAA,CAEYI,EAAAA,CAAmB,IAAU,CAAA,CAAA,oBAAA,CAAqB,CAC9D,KAAA,CAAO,IAAU,CAAA,CAAA,KAAA,CAAM,QAAQ,CAAA,CAC/B,SAAA,CAAW,CAAA,CACX,SAAA,CAAW,EAAA,CACX,eAAA,CAAiB,EAAA,CACjB,SAAA,CAAW,EAAA,CACX,kBAAA,CAAoB,EAAA,CACpB,YAAA,CAAc,EAAA,CACd,GAAA,CAAK,GAAA,CACL,YAAA,CAAc,CAAA,CACd,WAAA,CAAa,CAAA,CAAA,CACb,UAAA,CAAY,CAAA,CAAA,CACZ,IAAA,CAAY,CAAA,CAAA,SAAA,CACZ,SAAA,CAAW,CAAA,CAAA,CACX,aAAA,CAAe,CAAA,CAAA,CACf,mBAAA,CAAqB,CAAA,CACrB,kBAAA,CAAoB,CACrB,CAAC,CAAA,CAEYF,EAAAA,CAAiB,IAAU,CAAA,CAAA,oBAAA,CAAqB,CAC5D,KAAA,CAAO,IAAU,CAAA,CAAA,KAAA,CAAM,QAAQ,CAAA,CAC/B,SAAA,CAAW,CAAA,CACX,SAAA,CAAW,CAAA,CAGX,YAAA,CAAc,GAAA,CACd,WAAA,CAAa,CAAA,CAAA,CAGb,UAAA,CAAY,CAAA,CAAA,CACZ,eAAA,CAAiB,CAAA,CACjB,SAAA,CAAW,CAAA,CACX,kBAAA,CAAoB,CAAA,CACpB,GAAA,CAAK,IAAA,CACL,YAAA,CAAc,EAAA,CACd,SAAA,CAAW,CAAA,CACX,IAAA,CAAY,CAAA,CAAA,UAAA,CACZ,aAAA,CAAe,CAAA,CAAA,CACf,mBAAA,CAAqB,CAAA,CACrB,kBAAA,CAAoB,CACrB,CAAC,CAAA,CAEYG,EAAAA,CAAkB,IAAU,CAAA,CAAA,oBAAA,CAAqB,CAC7D,KAAA,CAAO,IAAU,CAAA,CAAA,KAAA,CAAM,OAAQ,CAAA,CAC/B,SAAA,CAAW,CAAA,CACX,SAAA,CAAW,EAAA,CACX,eAAA,CAAiB,EAAA,CACjB,SAAA,CAAW,EAAA,CACX,kBAAA,CAAoB,EAAA,CACpB,YAAA,CAAc,EAAA,CACd,GAAA,CAAK,GAAA,CACL,YAAA,CAAc,CAAA,CACd,UAAA,CAAY,CAAA,CAAA,CACZ,IAAA,CAAY,CAAA,CAAA,SAAA,CACZ,aAAA,CAAe,CAAA,CAAA,CACf,mBAAA,CAAqB,CAAA,CACrB,kBAAA,CAAoB,CACrB,CAAC,CAAA,CAEYE,EAAAA,CAAgB,IAAU,CAAA,CAAA,oBAAA,CAAqB,CAC3D,KAAA,CAAO,IAAU,CAAA,CAAA,KAAA,CAAM,OAAQ,CAAA,CAC/B,SAAA,CAAW,CAAA,CACX,SAAA,CAAW,EAAA,CACX,eAAA,CAAiB,EAAA,CACjB,SAAA,CAAW,EAAA,CACX,kBAAA,CAAoB,EAAA,CACpB,YAAA,CAAc,EAAA,CACd,GAAA,CAAK,GAAA,CACL,YAAA,CAAc,CAAA,CACd,UAAA,CAAY,CAAA,CAAA,CACZ,IAAA,CAAY,CAAA,CAAA,SAAA,CACZ,SAAA,CAAW,CAAA,CAAA,CACX,aAAA,CAAe,CAAA,CAAA,CACf,mBAAA,CAAqB,CAAA,CACrB,kBAAA,CAAoB,CACrB,CAAC,CAAA,CAGYD,EAAAA,CAAgD,IAAI,GAAA,CAAoB,CACpFL,EAAAA,CACAE,EAAAA,CACAH,EAAAA,CACAI,EAAAA,CACAF,EAAAA,CACAG,EAAAA,CACAE,EACD,CAAC,CAAA,CCxJD,SAqCgBC,EAAAA,CAAaC,CAAAA,CAA4B,CACxD,IAAMC,CAAAA,CAAID,CAAAA,CAAG,KAAA,CAAM,CAAA,CAAE,SAAA,CAAU,CAAA,CAGzBE,CAAAA,CAAS,IAAU,EAAA,CAAA,OAAA,CAAQ,CAAA,CAAG,CAAA,CAAG,CAAC,CAAA,CAClCC,CAAAA,CAAS,IAAU,EAAA,CAAA,OAAA,CAAQ,CAAA,CAAG,CAAA,CAAG,CAAC,CAAA,CAClCC,CAAAA,CAAO,IAAA,CAAK,GAAA,CAAIH,CAAAA,CAAE,GAAA,CAAIC,CAAM,CAAC,CAAA,CAAI,EAAA,CAAMC,CAAAA,CAASD,CAAAA,CAGhDG,CAAAA,CAAQ,IAAU,EAAA,CAAA,OAAA,CAAQ,CAAA,CAAE,YAAA,CAAaD,CAAAA,CAAMH,CAAC,CAAA,CAAE,SAAA,CAAU,CAAA,CAE5DK,CAAAA,CAAU,IAAU,EAAA,CAAA,OAAA,CAAQ,CAAA,CAAE,YAAA,CAAaL,CAAAA,CAAGI,CAAK,CAAA,CAAE,SAAA,CAAU,CAAA,CAErE,MAAO,CAAE,EAAA,CAAIJ,CAAAA,CAAG,OAAA,CAAAK,CAAAA,CAAS,KAAA,CAAAD,CAAM,CAChC,CASO,SAASE,EAAAA,CAAUP,CAAAA,CAAmBQ,CAAAA,CAAiC,CAC7E,GAAM,CAAE,OAAA,CAAAF,CAAAA,CAAS,KAAA,CAAAD,CAAAA,CAAO,EAAA,CAAIJ,CAAE,CAAA,CAAIF,EAAAA,CAAaC,CAAE,CAAA,CAEjD,OAAOM,CAAAA,CACL,KAAA,CAAM,CAAA,CACN,cAAA,CAAe,CAAA,CAAE,CAAA,CACjB,GAAA,CAAID,CAAAA,CAAM,KAAA,CAAM,CAAA,CAAE,cAAA,CAAe,CAAA,CAAE,CAAC,CAAA,CACpC,GAAA,CAAIJ,CAAC,CAAA,CACL,SAAA,CAAU,CAAA,CACV,cAAA,CAAeO,CAAQ,CAC1B,CAOO,SAASC,EAAAA,CAAUT,CAAAA,CAAmBU,CAAAA,CAAsBC,CAAAA,CAA+B,CACjG,GAAM,CAAE,OAAA,CAAAL,CAAAA,CAAS,KAAA,CAAAD,CAAAA,CAAO,EAAA,CAAIJ,CAAE,CAAA,CAAIF,EAAAA,CAAaC,CAAE,CAAA,CACjD,OAAOK,CAAAA,CACL,KAAA,CAAM,CAAA,CACN,cAAA,CAAeK,CAAY,CAAA,CAC3B,GAAA,CAAIJ,CAAAA,CAAQ,KAAA,CAAM,CAAA,CAAE,cAAA,CAAeI,CAAY,CAAC,CAAA,CAChD,GAAA,CAAIT,CAAAA,CAAE,KAAA,CAAM,CAAA,CAAE,cAAA,CAAeU,CAAM,CAAC,CACvC,CAeO,SAASC,EAAAA,CAAuBZ,CAAAA,CAAgC,CACtE,IAAMC,CAAAA,CAAID,CAAAA,CAAG,KAAA,CAAM,CAAA,CAAE,SAAA,CAAU,CAAA,CACzBa,CAAAA,CAAY,IAAU,EAAA,CAAA,OAAA,CAAQ,CAAA,CAAG,CAAA,CAAG,CAAC,CAAA,CAG3C,EAAA,CAAIZ,CAAAA,CAAE,GAAA,CAAIY,CAAS,CAAA,CAAI,KAAA,CAAQ,OAAO,IAAU,EAAA,CAAA,KAAA,CAIhD,EAAA,CAAIZ,CAAAA,CAAE,GAAA,CAAIY,CAAS,CAAA,CAAI,CAAA,KAAA,CAAS,OAAO,IAAU,EAAA,CAAA,KAAA,CAAM,IAAA,CAAK,EAAA,CAAI,CAAA,CAAG,CAAC,CAAA,CAEpE,IAAMC,CAAAA,CAAa,IAAU,EAAA,CAAA,UAAA,CAAW,CAAA,CAAE,kBAAA,CAAmBD,CAAAA,CAAWZ,CAAC,CAAA,CACzE,OAAO,IAAU,EAAA,CAAA,KAAA,CAAM,CAAA,CAAE,iBAAA,CAAkBa,CAAU,CACtD,CAQO,SAASC,EAAAA,CAASf,CAAAA,CAAoC,CAC5D,IAAMgB,CAAAA,CAAK,IAAA,CAAK,GAAA,CAAIhB,CAAAA,CAAG,CAAC,CAAA,CAClBiB,CAAAA,CAAK,IAAA,CAAK,GAAA,CAAIjB,CAAAA,CAAG,CAAC,CAAA,CAClBkB,CAAAA,CAAK,IAAA,CAAK,GAAA,CAAIlB,CAAAA,CAAG,CAAC,CAAA,CACxB,OAAIgB,CAAAA,EAAMC,CAAAA,EAAMD,CAAAA,EAAME,CAAAA,CAAW,GAAA,CAC7BD,CAAAA,EAAMC,CAAAA,CAAW,GAAA,CACd,GACR,CC/HA,IAOMC,EAAAA,CAAgB,CACrB,cAAA,CAAgB,GAAA,CAChB,eAAA,CAAiB,GAAA,CACjB,qBAAA,CAAuB,GAAA,CACvB,iBAAA,CAAmB,CAClB,IAAA,CAAM,IAAA,CACN,KAAA,CAAO,IAAA,CACP,MAAA,CAAQ,GACT,CAAA,CACA,gBAAA,CAAkB,CACjB,IAAA,CAAM,GAAA,CACN,KAAA,CAAO,EAAA,CACP,MAAA,CAAQ,EACT,CAAA,CACA,2BAAA,CAA6B,CAC9B,CAAA,CAGO,SAASC,EAAAA,CACfC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACC,CAGD,EAAA,CAFAC,EAAAA,CAAWL,CAAK,CAAA,CAEZC,CAAAA,CAAO,MAAA,GAAW,CAAA,CAAG,MAAA,CAGzBA,CAAAA,CAAO,OAAA,CAASK,CAAAA,EAAS,CACxBN,CAAAA,CAAM,GAAA,CAAIM,CAAI,CACf,CAAC,CAAA,CAGD,IAAMC,CAAAA,CAAmBC,EAAAA,CAA2BP,CAAM,CAAA,CAGpDQ,CAAAA,CAASF,CAAAA,CAAiB,SAAA,CAAU,IAAU,CAAA,CAAA,OAAS,CAAA,CACvDG,CAAAA,CAAOH,CAAAA,CAAiB,OAAA,CAAQ,IAAU,CAAA,CAAA,OAAS,CAAA,CAGnDI,CAAAA,CAAS,IAAA,CAAK,GAAA,CAAID,CAAAA,CAAK,CAAA,CAAGA,CAAAA,CAAK,CAAA,CAAGA,CAAAA,CAAK,CAAC,CAAA,CA0B9C,EAAA,CAtBmBC,CAAAA,CAAS,IAAA,CAAK,GAAA,CAAID,CAAAA,CAAK,CAAA,EAAK,CAAA,CAAGA,CAAAA,CAAK,CAAA,EAAK,CAAA,CAAGA,CAAAA,CAAK,CAAA,EAAK,CAAC,CAAA,CAEzDZ,EAAAA,CAAc,qBAAA,EAAyBa,CAAAA,CAASb,EAAAA,CAAc,cAAA,CAAA,CAE9EI,CAAAA,CAAO,IAAA,CAAOS,CAAAA,CAASb,EAAAA,CAAc,iBAAA,CAAkB,IAAA,CACvDI,CAAAA,CAAO,GAAA,CAAMS,CAAAA,CAASb,EAAAA,CAAc,gBAAA,CAAiB,IAAA,CAAA,CAC3Ca,CAAAA,CAASb,EAAAA,CAAc,eAAA,CAAA,CAEjCI,CAAAA,CAAO,IAAA,CAAOS,CAAAA,CAASb,EAAAA,CAAc,iBAAA,CAAkB,KAAA,CACvDI,CAAAA,CAAO,GAAA,CAAMS,CAAAA,CAASb,EAAAA,CAAc,gBAAA,CAAiB,KAAA,CAAA,CAAA,CAGrDI,CAAAA,CAAO,IAAA,CAAO,IAAA,CAAK,GAAA,CAAI,GAAA,CAAMS,CAAAA,CAASb,EAAAA,CAAc,iBAAA,CAAkB,MAAM,CAAA,CAC5EI,CAAAA,CAAO,GAAA,CAAM,IAAA,CAAK,GAAA,CAAI,GAAA,CAAMS,CAAAA,CAASb,EAAAA,CAAc,gBAAA,CAAiB,MAAM,CAAA,CAAA,CAG3EI,CAAAA,CAAO,sBAAA,CAAuB,CAAA,CAM1B,CAACE,CAAAA,CAAoB,CACxB,IAAMjB,CAAAA,CAAWwB,CAAAA,CAASb,EAAAA,CAAc,2BAAA,CAMxCI,CAAAA,CAAO,QAAA,CAAS,IAAA,CAAKO,CAAM,CAAA,CAAE,GAAA,CAAIvB,EAAAA,CAAUgB,CAAAA,CAAO,EAAA,CAAIf,CAAQ,CAAC,CAAA,CAC/DgB,CAAAA,CAAS,MAAA,CAAO,IAAA,CAAKM,CAAM,CAAA,CAE3BN,CAAAA,CAAS,MAAA,CAAO,CACjB,CACD,CAGO,SAASS,EAAAA,CAAWC,CAAAA,CAAkC,CAC5D,EAAA,CAAI,CAACA,CAAAA,EAAe,OAAOA,CAAAA,EAAgB,QAAA,CAC1C,OAAAC,iCAAAA,CAAU,CAAE,IAAA,CAAK,CAAA,qBAAA,EAAwBD,CAAW,CAAA,aAAA,CAAe,CAAA,CAC5D,IAAU,CAAA,CAAA,KAAA,CAAM,QAAQ,CAAA,CAGhC,IAAME,CAAAA,CAAUF,CAAAA,CAAY,IAAA,CAAK,CAAA,CAGjC,EAAA,CAAI,oBAAA,CAAqB,IAAA,CAAKE,CAAO,CAAA,CACpC,GAAI,CACH,IAAMC,CAAAA,CAAMD,CAAAA,CAAQ,UAAA,CAAW,GAAG,CAAA,CAAIA,CAAAA,CAAU,CAAA,CAAA,EAAIA,CAAO,CAAA,CAAA;ACnC/B;AAAA;AAAA;AAAA;AAAA;AAAA;AASE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;ACyIkB;ACyZ9CE;ACzjBqB;AAAA;AAAA;AAAA;AAAA;AAOE,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;ACuDjB,CAAA;AClDT,QAAA;ACkaF;AAuRG;AAAA;AAAA;AAAA;AAAA;AAAA;AChcH,SAAA","file":"/home/runner/work/selva/selva/packages/compute/dist/chunk-RFE763NG.cjs","sourcesContent":[null,"import * as THREE from 'three';\n\nexport const EMISSIVE_MATERIAL = new THREE.MeshPhysicalMaterial({\n\tcolor: 0x000000,\n\temissive: new THREE.Color(0xffffff),\n\temissiveIntensity: 5,\n\tmetalness: 0.0,\n\troughness: 0.2,\n\tclearcoat: 0.3,\n\tclearcoatRoughness: 0.2,\n\tdepthWrite: true,\n\tdepthTest: true,\n\ttransparent: false,\n\talphaTest: 0.0,\n\tpolygonOffset: true,\n\tpolygonOffsetFactor: 1,\n\tpolygonOffsetUnits: 1,\n\tside: THREE.FrontSide,\n\tdithering: true\n});\n\nexport const METAL_MATERIAL = new THREE.MeshPhysicalMaterial({\n\tcolor: new THREE.Color(0x000000),\n\tmetalness: 0.9,\n\troughness: 0.3,\n\tenvMapIntensity: 1.2,\n\tclearcoat: 0.3,\n\tclearcoatRoughness: 0.2,\n\treflectivity: 1,\n\tior: 2.5,\n\tthickness: 1,\n\tdepthWrite: true,\n\ttransparent: false,\n\talphaTest: 0.0,\n\tdepthTest: true,\n\tpolygonOffset: true,\n\tpolygonOffsetFactor: 1,\n\tpolygonOffsetUnits: 1,\n\tside: THREE.FrontSide,\n\tdithering: true\n});\n\nexport const CONCRETE_MATERIAL = new THREE.MeshPhysicalMaterial({\n\tcolor: new THREE.Color(0xcccccc),\n\tmetalness: 0.0,\n\troughness: 0.92,\n\tenvMapIntensity: 0.15,\n\tclearcoat: 0.05,\n\tclearcoatRoughness: 0.9,\n\treflectivity: 0.15,\n\ttransmission: 0.0,\n\tior: 1.45,\n\tthickness: 0.0,\n\tdepthWrite: true,\n\ttransparent: false,\n\t// No alphaTest: concrete has no alpha map, and a nonzero alphaTest needlessly switches the\n\t// shader onto the alpha-test path.\n\talphaTest: 0.0,\n\tdepthTest: true,\n\tpolygonOffset: true,\n\tpolygonOffsetFactor: 1,\n\tpolygonOffsetUnits: 1,\n\tside: THREE.FrontSide,\n\tdithering: true\n});\n\nexport const PLASTIC_MATERIAL = new THREE.MeshPhysicalMaterial({\n\tcolor: new THREE.Color(0xffffff), // Default white plastic\n\tmetalness: 0.0,\n\troughness: 0.3,\n\tenvMapIntensity: 0.5,\n\tclearcoat: 0.5,\n\tclearcoatRoughness: 0.1,\n\treflectivity: 0.5,\n\tior: 1.4,\n\ttransmission: 0.0,\n\ttransparent: false,\n\tdepthWrite: true,\n\tside: THREE.FrontSide,\n\tdithering: true,\n\tpolygonOffset: true,\n\tpolygonOffsetFactor: 1,\n\tpolygonOffsetUnits: 1\n});\n\nexport const GLASS_MATERIAL = new THREE.MeshPhysicalMaterial({\n\tcolor: new THREE.Color(0xffffff),\n\tmetalness: 0.0,\n\troughness: 0.0,\n\t// Transmission alone models the see-through look; stacking a low `opacity` on top would\n\t// attenuate twice and render glass much darker than intended (opacity stays at its default 1).\n\ttransmission: 0.95,\n\ttransparent: true,\n\t// A depth-writing transparent DoubleSide surface culls whatever sorts behind it — objects\n\t// behind glass would intermittently vanish depending on draw order.\n\tdepthWrite: false,\n\tenvMapIntensity: 1.0,\n\tclearcoat: 1.0,\n\tclearcoatRoughness: 0.0,\n\tior: 1.52,\n\treflectivity: 0.9,\n\tthickness: 1.0,\n\tside: THREE.DoubleSide,\n\tpolygonOffset: true,\n\tpolygonOffsetFactor: 1,\n\tpolygonOffsetUnits: 1\n});\n\nexport const RUBBER_MATERIAL = new THREE.MeshPhysicalMaterial({\n\tcolor: new THREE.Color(0x1a1a1a),\n\tmetalness: 0.0,\n\troughness: 0.9,\n\tenvMapIntensity: 0.2,\n\tclearcoat: 0.1,\n\tclearcoatRoughness: 0.8,\n\treflectivity: 0.2,\n\tior: 1.3,\n\ttransmission: 0.0,\n\tdepthWrite: true,\n\tside: THREE.FrontSide,\n\tpolygonOffset: true,\n\tpolygonOffsetFactor: 1,\n\tpolygonOffsetUnits: 1\n});\n\nexport const WOOD_MATERIAL = new THREE.MeshPhysicalMaterial({\n\tcolor: new THREE.Color(0x885533),\n\tmetalness: 0.0,\n\troughness: 0.7,\n\tenvMapIntensity: 0.3,\n\tclearcoat: 0.3,\n\tclearcoatRoughness: 0.4,\n\treflectivity: 0.3,\n\tior: 1.3,\n\ttransmission: 0.0,\n\tdepthWrite: true,\n\tside: THREE.FrontSide,\n\tdithering: true,\n\tpolygonOffset: true,\n\tpolygonOffsetFactor: 1,\n\tpolygonOffsetUnits: 1\n});\n\n/** Shared singleton materials; must not be disposed (rebuilds shaders, frees textures). */\nexport const SHARED_MATERIALS: ReadonlySet<THREE.Material> = new Set<THREE.Material>([\n\tEMISSIVE_MATERIAL,\n\tMETAL_MATERIAL,\n\tCONCRETE_MATERIAL,\n\tPLASTIC_MATERIAL,\n\tGLASS_MATERIAL,\n\tRUBBER_MATERIAL,\n\tWOOD_MATERIAL\n]);\n","import * as THREE from 'three';\n\n/**\n * The single source of truth for \"which way is up, and what do front/right mean\" in the viewer.\n *\n * Every up-dependent default (camera framing, sun position, ground offset, view presets) derives\n * from {@link buildUpBasis} instead of hardcoding an axis. Before this module those defaults each\n * spelled out a Z-up vector inline, so a scene configured Y-up got a below-horizon camera and a\n * near-horizontal sun while the presets and floor correctly followed `sceneUp`.\n *\n * ## Why front is -forward\n *\n * The basis returns `forward` = the direction the camera LOOKS (from camera toward model), and the\n * preset positions are the opposite (from target toward camera). Rhino's convention fixes the signs:\n * its Front view looks along +Y, so the camera sits at -Y; its Right view looks along -X, so the\n * camera sits at +X. Deriving `right` as `seed x up` (rather than `up x seed`) is what makes the\n * handedness come out matching Rhino rather than mirrored.\n */\n\n/** An orthonormal frame derived from a scene up axis. All vectors are unit length. */\nexport interface UpBasis {\n\t/** The scene up axis, normalized. */\n\tup: THREE.Vector3;\n\t/** The direction a \"front\" view looks along (from camera toward the model). */\n\tforward: THREE.Vector3;\n\t/** Completes a right-handed frame with `up` and `forward`. */\n\tright: THREE.Vector3;\n}\n\n/**\n * Derive the ground-plane axes for a given up vector.\n *\n * The seed picks whichever world axis is least parallel to `up`, so the cross products stay\n * well-conditioned in any up convention. For Rhino's Z-up this yields forward = +Y and right = +X,\n * matching Rhino's own Front/Right views; for Three's native Y-up it yields forward = -Z and\n * right = +X, matching Three's convention that the default camera looks down -Z.\n */\nexport function buildUpBasis(up: THREE.Vector3): UpBasis {\n\tconst u = up.clone().normalize();\n\n\t// Seed with a world axis that isn't (nearly) parallel to up, so the cross product is stable.\n\tconst worldZ = new THREE.Vector3(0, 0, 1);\n\tconst worldY = new THREE.Vector3(0, 1, 0);\n\tconst seed = Math.abs(u.dot(worldZ)) > 0.9 ? worldY : worldZ;\n\n\t// `seed x up` (not `up x seed`) so the handedness matches Rhino: Z-up gives right = +X.\n\tconst right = new THREE.Vector3().crossVectors(seed, u).normalize();\n\t// Completes the frame. Z-up: forward = +Y (Rhino's Front looks along +Y). Y-up: forward = -Z.\n\tconst forward = new THREE.Vector3().crossVectors(u, right).normalize();\n\n\treturn { up: u, forward, right };\n}\n\n/**\n * The default 3/4 iso camera OFFSET from the target, scaled to `distance`.\n *\n * Placed behind-left and above the model (the conventional architectural 3/4), expressed in the\n * scene's own basis so it reads the same in any up convention. Callers add this to the framing\n * target to get a camera position.\n */\nexport function isoOffset(up: THREE.Vector3, distance: number): THREE.Vector3 {\n\tconst { forward, right, up: u } = buildUpBasis(up);\n\t// Behind (-forward), left (-right), above (+up) — normalized so `distance` is the true radius.\n\treturn forward\n\t\t.clone()\n\t\t.multiplyScalar(-1)\n\t\t.add(right.clone().multiplyScalar(-1))\n\t\t.add(u)\n\t\t.normalize()\n\t\t.multiplyScalar(distance);\n}\n\n/**\n * A default sun position: high above the model, offset to one side so surfaces get a directional\n * gradient instead of flat top-down light. Expressed in the scene basis rather than a literal\n * Z-up vector, so a Y-up scene still gets an overhead sun rather than a horizontal one.\n */\nexport function sunOffset(up: THREE.Vector3, sideDistance: number, height: number): THREE.Vector3 {\n\tconst { forward, right, up: u } = buildUpBasis(up);\n\treturn right\n\t\t.clone()\n\t\t.multiplyScalar(sideDistance)\n\t\t.add(forward.clone().multiplyScalar(sideDistance))\n\t\t.add(u.clone().multiplyScalar(height));\n}\n\n/**\n * The rotation that puts an equirectangular environment map's horizon on the scene's ground plane.\n *\n * Three's equirect mapping is hardcoded to Y-up: it assumes the HDR's horizon lies in the XZ plane\n * and its zenith points along +Y. In a Z-up scene that leaves the environment on its side — the\n * horizon runs vertically and image-based lighting arrives from +Y rather than from overhead. The\n * result is a subtly wrong key direction that a neutral studio HDR hides but any sky/ground HDR\n * makes obvious.\n *\n * Returns the Euler that rotates the map's native +Y zenith onto `up`. Identity for a Y-up scene.\n * Apply to BOTH `scene.environmentRotation` and `scene.backgroundRotation` — they are independent\n * properties, and setting only one makes the visible background disagree with the lighting.\n */\nexport function environmentRotationFor(up: THREE.Vector3): THREE.Euler {\n\tconst u = up.clone().normalize();\n\tconst mapZenith = new THREE.Vector3(0, 1, 0);\n\n\t// Already Y-up: the map is authored in this frame, so no correction is needed.\n\tif (u.dot(mapZenith) > 0.9999) return new THREE.Euler();\n\n\t// Upside-down (-Y): setFromUnitVectors picks an arbitrary perpendicular axis for a 180° flip,\n\t// which would also spin the horizon. Roll about X so the horizon stays put.\n\tif (u.dot(mapZenith) < -0.9999) return new THREE.Euler(Math.PI, 0, 0);\n\n\tconst quaternion = new THREE.Quaternion().setFromUnitVectors(mapZenith, u);\n\treturn new THREE.Euler().setFromQuaternion(quaternion);\n}\n\n/**\n * Which world axis (`'x' | 'y' | 'z'`) the up vector most closely aligns with.\n *\n * Used for the grid plane and for the ground-offset axis — both need a single component index\n * rather than a full vector. An off-axis up vector resolves to its dominant component.\n */\nexport function upToAxis(up: THREE.Vector3): 'x' | 'y' | 'z' {\n\tconst ax = Math.abs(up.x);\n\tconst ay = Math.abs(up.y);\n\tconst az = Math.abs(up.z);\n\tif (ax >= ay && ax >= az) return 'x';\n\tif (ay >= az) return 'y';\n\treturn 'z';\n}\n","import * as THREE from 'three';\nimport { OrbitControls } from 'three/addons/controls/OrbitControls.js';\nimport { getLogger } from '@/core';\n\nimport { SHARED_MATERIALS } from './three-materials';\nimport { isoOffset } from './up-axis';\n\nconst CAMERA_CONFIG = {\n\tHUGE_THRESHOLD: 10000,\n\tLARGE_THRESHOLD: 1000,\n\tSCALE_RATIO_THRESHOLD: 100,\n\tNEAR_PLANE_FACTOR: {\n\t\tTINY: 0.0001,\n\t\tSMALL: 0.001,\n\t\tNORMAL: 0.01\n\t},\n\tFAR_PLANE_FACTOR: {\n\t\tHUGE: 100,\n\t\tLARGE: 50,\n\t\tNORMAL: 20\n\t},\n\tINITIAL_DISTANCE_MULTIPLIER: 4\n};\n\n/** Updates scene with meshes and positions camera on first call. */\nexport function updateScene(\n\tscene: THREE.Scene,\n\tmeshes: THREE.Object3D[],\n\tcamera: THREE.PerspectiveCamera,\n\tcontrols: OrbitControls,\n\tinitialPositionSet: boolean\n) {\n\tclearScene(scene);\n\n\tif (meshes.length === 0) return;\n\n\t// Add new objects (meshes, lines, points) to scene\n\tmeshes.forEach((mesh) => {\n\t\tscene.add(mesh);\n\t});\n\n\t// Calculate bounds of the new content\n\tconst unionBoundingBox = computeCombinedBoundingBox(meshes);\n\n\t// Get the center of the union bounding box\n\tconst center = unionBoundingBox.getCenter(new THREE.Vector3());\n\tconst size = unionBoundingBox.getSize(new THREE.Vector3());\n\n\t// Calculate a distance that is slightly larger than the largest dimension of the union bounding box\n\tconst maxDim = Math.max(size.x, size.y, size.z);\n\n\t// Always update camera frustum to ensure geometry is visible\n\t// This prevents clipping when geometry size changes significantly\n\tconst scaleRatio = maxDim / Math.min(size.x || 1, size.y || 1, size.z || 1);\n\n\tif (scaleRatio > CAMERA_CONFIG.SCALE_RATIO_THRESHOLD || maxDim > CAMERA_CONFIG.HUGE_THRESHOLD) {\n\t\t// Large scale range detected - use logarithmic depth buffer approach\n\t\tcamera.near = maxDim * CAMERA_CONFIG.NEAR_PLANE_FACTOR.TINY;\n\t\tcamera.far = maxDim * CAMERA_CONFIG.FAR_PLANE_FACTOR.HUGE;\n\t} else if (maxDim > CAMERA_CONFIG.LARGE_THRESHOLD) {\n\t\t// Large scene\n\t\tcamera.near = maxDim * CAMERA_CONFIG.NEAR_PLANE_FACTOR.SMALL;\n\t\tcamera.far = maxDim * CAMERA_CONFIG.FAR_PLANE_FACTOR.LARGE;\n\t} else {\n\t\t// Normal scene\n\t\tcamera.near = Math.max(0.01, maxDim * CAMERA_CONFIG.NEAR_PLANE_FACTOR.NORMAL);\n\t\tcamera.far = Math.max(2000, maxDim * CAMERA_CONFIG.FAR_PLANE_FACTOR.NORMAL);\n\t}\n\n\tcamera.updateProjectionMatrix();\n\n\t// Only reposition camera and controls on first frame.\n\t// Zoom limits (min/maxDistance) are deliberately NOT touched here: they are owned by the\n\t// host via setupControls, and overwriting them per solve silently discarded user-supplied\n\t// configuration after the first geometry update.\n\tif (!initialPositionSet) {\n\t\tconst distance = maxDim * CAMERA_CONFIG.INITIAL_DISTANCE_MULTIPLIER;\n\n\t\t// Frame from the standard 3/4 iso, derived from the camera's own up axis (initThree sets it to\n\t\t// the configured sceneUp before this ever runs). Previously a hardcoded (0.8, 1.0, 1.2) offset\n\t\t// that both assumed Z-up and disagreed with the configured iso default, so the first solve\n\t\t// jumped to a different angle than the one the viewer opened at.\n\t\tcamera.position.copy(center).add(isoOffset(camera.up, distance));\n\t\tcontrols.target.copy(center);\n\n\t\tcontrols.update();\n\t}\n}\n\n/** Parses color strings (hex, RGB, CSS names). */\nexport function parseColor(colorString: string): THREE.Color {\n\tif (!colorString || typeof colorString !== 'string') {\n\t\tgetLogger().warn(`Invalid color input: ${colorString}, using white`);\n\t\treturn new THREE.Color(0xffffff);\n\t}\n\n\tconst trimmed = colorString.trim();\n\n\t// Try hex format (#C7A5A5 or C7A5A5) — require exactly 6 hex chars\n\tif (/^#?[0-9A-Fa-f]{6}$/.test(trimmed)) {\n\t\ttry {\n\t\t\tconst hex = trimmed.startsWith('#') ? trimmed : `#${trimmed}`;\n\t\t\treturn new THREE.Color(hex);\n\t\t} catch {\n\t\t\tgetLogger().warn(`Invalid hex color: ${colorString}, using white`);\n\t\t\treturn new THREE.Color(0xffffff);\n\t\t}\n\t}\n\n\t// Try RGB format (R, G, B)\n\tif (trimmed.includes(',')) {\n\t\tconst rgb = trimmed.split(',').map((c) => parseInt(c.trim(), 10));\n\t\tif (rgb.length === 3 && rgb.every((n) => !isNaN(n) && n >= 0 && n <= 255)) {\n\t\t\treturn new THREE.Color(rgb[0] / 255, rgb[1] / 255, rgb[2] / 255);\n\t\t}\n\t}\n\n\t// Try CSS named color. `new THREE.Color(name)` never throws on unknown names (it logs its own\n\t// warning and leaves the color white), so validate against three's CSS name table instead.\n\tconst named = trimmed.toLowerCase();\n\tif (named in THREE.Color.NAMES) {\n\t\treturn new THREE.Color(THREE.Color.NAMES[named as keyof typeof THREE.Color.NAMES]);\n\t}\n\n\tgetLogger().warn(`Invalid color string: ${colorString}, using white`);\n\treturn new THREE.Color(0xffffff);\n}\n\n/**\n * Shift objects along one world axis. Defaults to `z` — the up axis of the unified Z-up scene\n * frame (see `../coordinate-transform.ts`), so grounding subtracts the content's lowest z. Pass an\n * explicit axis when the scene is configured with a different `sceneUp`.\n */\nexport function applyOffset(\n\tmeshes: THREE.Object3D[],\n\toffset: number,\n\taxis: 'x' | 'y' | 'z' = 'z'\n): void {\n\tmeshes.forEach((mesh) => {\n\t\tmesh.position[axis] -= offset;\n\t});\n}\n\n/**\n * Computes the combined world-axis-aligned bounding box of a set of objects (meshes, lines, points).\n * Correctly accounts for transformations (rotation, position, scale).\n */\nexport function computeCombinedBoundingBox(meshes: THREE.Object3D[]): THREE.Box3 {\n\tconst combinedBoundingBox = new THREE.Box3();\n\tif (meshes.length === 0) return combinedBoundingBox;\n\tmeshes.forEach((mesh) => {\n\t\t// Ensure the world matrix is up to date before calculating the box\n\t\tmesh.updateMatrixWorld(true);\n\t\tconst bbox = new THREE.Box3().setFromObject(mesh);\n\t\tcombinedBoundingBox.union(bbox);\n\t});\n\treturn combinedBoundingBox;\n}\n\n/**\n * userData.id of objects that are viewer *aids*, not content — the grid, floor, CSS2D label layer and\n * measure markers. Excluded from every content-bounds query: the grid especially is a huge plane that\n * re-centers on the camera each frame, so including it would make fit-to-view frame the camera's\n * position instead of the geometry.\n */\nconst VIEWER_AID_IDS = new Set(['grid', 'floor', 'label-layer', 'measure']);\n\n/** True if the object or any ancestor is a viewer aid (grid/floor/labels/measure markers). */\nfunction isViewerAid(object: THREE.Object3D): boolean {\n\tlet current: THREE.Object3D | null = object;\n\twhile (current) {\n\t\tif (typeof current.userData.id === 'string' && VIEWER_AID_IDS.has(current.userData.id)) {\n\t\t\treturn true;\n\t\t}\n\t\tcurrent = current.parent;\n\t}\n\treturn false;\n}\n\n/**\n * Axis-aligned world bounds of the scene's renderable *content* — every visible mesh/line/points, with\n * viewer aids (grid/floor/labels/measure) excluded. The single content-bounds function: shared by\n * fit-to-view, pick-threshold scaling, camera framing (`setView`), and shadow-frustum fitting so they\n * all measure exactly the same box. Returns an empty Box3 when there is no content.\n *\n * Refreshes world matrices once up front (one traversal) so `expandByObject` reads current transforms\n * regardless of when the caller invokes this — cheaper and more correct than updating per object.\n */\nexport function computeContentBounds(scene: THREE.Scene): THREE.Box3 {\n\tscene.updateMatrixWorld(true);\n\tconst box = new THREE.Box3();\n\tscene.traverse((object) => {\n\t\tconst renderable = object as Partial<THREE.Mesh> & THREE.Object3D;\n\t\tif (object.visible && !isViewerAid(object) && renderable.geometry) {\n\t\t\tbox.expandByObject(object);\n\t\t}\n\t});\n\treturn box;\n}\n\n/** IDs of scene infrastructure that survives content updates (floor, grid, label layer). */\nconst PERSISTENT_SCENE_IDS = new Set(['floor', 'grid', 'label-layer']);\n\n/**\n * `geometry.userData` tag marking a geometry owned by the cross-solve geometry cache\n * (webdisplay/geometry-cache.ts). `clearScene` must NOT dispose these — the cache keeps them alive\n * (GPU buffers included) so the next solve can reuse them; the cache disposes on eviction instead.\n */\nexport const CACHED_GEOMETRY_USERDATA_FLAG = 'selvaGeometryCache';\n\n/** Removes all compute content except persistent infrastructure and shared materials. */\nexport function clearScene(scene: THREE.Scene): void {\n\t// Snapshot children — we mutate the array via removeFromParent during iteration\n\tconst topLevel = [...scene.children];\n\n\ttopLevel.forEach((object) => {\n\t\t// Persistent scene infrastructure (floor, grid, the CSS2D label layer) outlives content\n\t\t// updates — it's added once at init, not per solve. Removing the label-layer group here\n\t\t// orphans it, so labels created afterwards never render (the CSS2D renderer walks the live\n\t\t// scene and never finds them).\n\t\tif (PERSISTENT_SCENE_IDS.has(object.userData.id)) return;\n\n\t\t// User-drawn geometry (added via the viewer's addUserGeometry, tagged source==='user')\n\t\t// persists across solves so it isn't lost when compute content is replaced.\n\t\tif (object.userData.source === 'user') return;\n\n\t\t// Recursively dispose all renderable objects (meshes, lines, points) in this subtree.\n\t\tobject.traverse((child) => {\n\t\t\tconst renderable = child as Partial<THREE.Mesh> & THREE.Object3D;\n\t\t\tif (!renderable.geometry && !renderable.material) return;\n\n\t\t\t// Cache-owned geometries survive scene rebuilds — the cache disposes them on eviction.\n\t\t\tif (!renderable.geometry?.userData?.[CACHED_GEOMETRY_USERDATA_FLAG]) {\n\t\t\t\trenderable.geometry?.dispose();\n\t\t\t}\n\n\t\t\tconst material = renderable.material;\n\t\t\tif (!material) return;\n\t\t\tconst materials = Array.isArray(material) ? material : [material];\n\t\t\tmaterials.forEach((material) => {\n\t\t\t\t// Module-scope singletons (METAL_MATERIAL et al.) are shared across meshes and across\n\t\t\t\t// solves — disposing one here would force a shader rebuild on its next use and free\n\t\t\t\t// textures still referenced by surviving objects.\n\t\t\t\tif (SHARED_MATERIALS.has(material)) return;\n\n\t\t\t\t// Walk only own enumerable properties — `for...in` on a Three.js material\n\t\t\t\t// also iterates the prototype chain, which is needlessly expensive.\n\t\t\t\tfor (const value of Object.values(material)) {\n\t\t\t\t\tif (value instanceof THREE.Texture) {\n\t\t\t\t\t\tvalue.dispose();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tmaterial.dispose();\n\t\t\t});\n\t\t});\n\n\t\tobject.removeFromParent();\n\t});\n}\n","import * as THREE from 'three';\n\n/**\n * An \"infinite\", distance-fading reference grid — the single strongest visual cue that reads as CAD.\n *\n * Why not `GridHelper`: it's a fixed-size square of line segments that visibly ends and looks wrong\n * once you pan or zoom past it. Instead we draw one large screen-facing plane and compute the grid\n * in the fragment shader from world coordinates, fading lines out with distance so the edge is never\n * a hard cutoff. The plane is big enough to cover any reasonable view; the fade hides its bounds.\n *\n * Two line frequencies (minor + major every 10th) give the usual graph-paper depth read. Spacing is\n * in world units (meters — the scene's normalized unit), so a `cellSize` of 1 = 1m minor cells.\n */\n\nexport interface GridOptions {\n\t/** Minor cell size in world units (meters). Default 1. */\n\tcellSize?: number;\n\t/** How many minor cells per major line. Default 10. */\n\tmajorEvery?: number;\n\t/** Minor line color. */\n\tcellColor?: THREE.ColorRepresentation;\n\t/** Major line color. */\n\tmajorColor?: THREE.ColorRepresentation;\n\t/** World-space radius at which the grid has fully faded out. Default 100. */\n\tfadeDistance?: number;\n\t/**\n\t * Axis the grid is laid perpendicular to — i.e. the scene's up axis. `'z'` is the horizontal\n\t * ground in the Rhino Z-up frame the viewer uses; `'y'` is Three's native Y-up.\n\t *\n\t * This standalone default is `'y'`, but `initThree` always passes a plane derived from the\n\t * configured `sceneUp`, so a viewer-created grid defaults to `'z'`.\n\t */\n\tplane?: 'x' | 'y' | 'z';\n}\n\nexport interface Grid {\n\t/** The grid mesh; add to the scene. Tagged `userData.id = 'grid'` so pick/fit code skips it. */\n\treadonly object: THREE.Mesh;\n\t/** Keep the fade centered on the camera so the grid feels infinite as you move. Call per frame. */\n\tupdate(cameraPosition: THREE.Vector3): void;\n\t/**\n\t * Rescale the grid's cell spacing and fade radius to the loaded content's extent. Call after a\n\t * geometry change (e.g. right after `updateScene`) so a part that is 3 units or 3000 units wide\n\t * both get sensibly-sized cells and a fade that reaches past the model. No-op for empty/degenerate\n\t * bounds — the grid keeps its last (or default) scale. See {@link Grid.fitToContent}'s impl notes.\n\t */\n\tfitToContent(bounds: THREE.Box3): void;\n\tsetVisible(visible: boolean): void;\n\tdispose(): void;\n}\n\n/**\n * Round a value to a \"nice\" 1/2/5 × 10ⁿ step — the spacing conventions used by rulers and CAD grids,\n * so cells land on human-readable multiples (…, 0.5, 1, 2, 5, 10, 20, 50, …) rather than arbitrary\n * fractions like 1.37. Returns the largest nice step ≤ `value` (floored on the mantissa) so cells\n * never come out finer than the target and alias into a solid sheet.\n */\nfunction niceStep(value: number): number {\n\tif (!(value > 0) || !Number.isFinite(value)) return 1;\n\tconst exponent = Math.floor(Math.log10(value));\n\tconst power = Math.pow(10, exponent);\n\tconst mantissa = value / power; // in [1, 10)\n\tconst niceMantissa = mantissa >= 5 ? 5 : mantissa >= 2 ? 2 : 1;\n\treturn niceMantissa * power;\n}\n\nconst GRID_VERTEX = /* glsl */ `\n\tvarying vec3 vWorldPos;\n\tvoid main() {\n\t\tvec4 world = modelMatrix * vec4(position, 1.0);\n\t\tvWorldPos = world.xyz;\n\t\tgl_Position = projectionMatrix * viewMatrix * world;\n\t}\n`;\n\nconst GRID_FRAGMENT = /* glsl */ `\n\tprecision highp float;\n\tvarying vec3 vWorldPos;\n\n\tuniform vec2 uAxes; // indices (0=x,1=y,2=z) of the two in-plane world axes\n\tuniform float uCell;\n\tuniform float uMajor;\n\tuniform vec3 uCellColor;\n\tuniform vec3 uMajorColor;\n\tuniform vec3 uCenter; // fade center (camera position), projected onto plane\n\tuniform float uFade;\n\n\t// Antialiased grid line intensity for a given spacing, using screen-space derivatives so lines\n\t// stay ~1px regardless of zoom (the standard \"pristine grid\" technique).\n\tfloat gridLine(vec2 coord, float spacing) {\n\t\tvec2 c = coord / spacing;\n\t\tvec2 d = fwidth(c);\n\t\tvec2 g = abs(fract(c - 0.5) - 0.5) / max(d, 1e-6);\n\t\tfloat line = min(g.x, g.y);\n\t\treturn 1.0 - clamp(line, 0.0, 1.0);\n\t}\n\n\t// Index a vec3 by a float axis id (0/1/2) without dynamic indexing (WebGL1-safe).\n\tfloat axis(vec3 v, float i) {\n\t\treturn i < 0.5 ? v.x : (i < 1.5 ? v.y : v.z);\n\t}\n\n\tvoid main() {\n\t\t// Pick the two in-plane world coordinates.\n\t\tvec2 coord = vec2(axis(vWorldPos, uAxes.x), axis(vWorldPos, uAxes.y));\n\n\t\tfloat minor = gridLine(coord, uCell);\n\t\tfloat major = gridLine(coord, uCell * uMajor);\n\n\t\tvec3 color = mix(uCellColor, uMajorColor, major);\n\t\tfloat alpha = max(minor, major);\n\n\t\t// Radial fade from the camera-projected center.\n\t\tfloat dist = distance(vWorldPos, uCenter);\n\t\tfloat fade = 1.0 - clamp(dist / uFade, 0.0, 1.0);\n\t\talpha *= fade * fade;\n\n\t\tif (alpha < 0.001) discard;\n\t\tgl_FragColor = vec4(color, alpha);\n\t}\n`;\n\nexport function createGrid(options: GridOptions = {}): Grid {\n\tconst {\n\t\tcellSize = 1,\n\t\tmajorEvery = 10,\n\t\tcellColor = 0x888888,\n\t\tmajorColor = 0x444444,\n\t\tfadeDistance = 100,\n\t\tplane = 'y'\n\t} = options;\n\n\t// The two in-plane world axes (0=x,1=y,2=z): ground 'y' grids over x,z; 'z' over x,y; 'x' over y,z.\n\tconst axes =\n\t\tplane === 'y'\n\t\t\t? new THREE.Vector2(0, 2) // x, z\n\t\t\t: plane === 'z'\n\t\t\t\t? new THREE.Vector2(0, 1) // x, y\n\t\t\t\t: new THREE.Vector2(1, 2); // y, z\n\n\t// The plane must comfortably outreach the fade radius, else the grid ends before it has faded and\n\t// shows a hard rectangular edge. Built as a unit plane and sized purely by scale so fitToContent\n\t// can regrow it without recreating geometry — the same rotation onto the world plane still applies.\n\tconst PLANE_TO_FADE_RATIO = 2.5;\n\tconst geometry = new THREE.PlaneGeometry(1, 1);\n\n\t// PlaneGeometry is in the XY plane by default; rotate it onto the requested world plane.\n\tif (plane === 'y') geometry.rotateX(-Math.PI / 2);\n\telse if (plane === 'x') geometry.rotateY(Math.PI / 2);\n\n\tconst material = new THREE.ShaderMaterial({\n\t\tvertexShader: GRID_VERTEX,\n\t\tfragmentShader: GRID_FRAGMENT,\n\t\ttransparent: true,\n\t\tdepthWrite: false,\n\t\tside: THREE.DoubleSide,\n\t\tuniforms: {\n\t\t\tuAxes: { value: axes },\n\t\t\tuCell: { value: cellSize },\n\t\t\tuMajor: { value: majorEvery },\n\t\t\tuCellColor: { value: new THREE.Color(cellColor) },\n\t\t\tuMajorColor: { value: new THREE.Color(majorColor) },\n\t\t\tuCenter: { value: new THREE.Vector3() },\n\t\t\tuFade: { value: fadeDistance }\n\t\t}\n\t});\n\n\tconst mesh = new THREE.Mesh(geometry, material);\n\tmesh.name = 'grid';\n\tmesh.userData.id = 'grid'; // excluded from raycasting/fit-to-view, like the floor\n\tmesh.renderOrder = -1; // draw before content so transparent geometry blends over it\n\n\t// Live scale of the (unit) plane and current fade radius; fitToContent mutates both, `update`\n\t// reads planeScale each frame to size the camera-tracking plane. Seeded from the constructor's\n\t// fadeDistance so an un-fitted grid still covers its fade.\n\tlet fadeRadius = fadeDistance;\n\tlet planeScale = fadeDistance * PLANE_TO_FADE_RATIO;\n\n\tconst center = new THREE.Vector3();\n\n\treturn {\n\t\tobject: mesh,\n\t\tupdate: (cameraPosition) => {\n\t\t\t// Re-center the plane and the fade on the camera so the grid tracks the view \"infinitely\".\n\t\t\t// Keep the plane's own axis fixed (don't lift the ground grid up to the camera height).\n\t\t\tif (plane === 'y') {\n\t\t\t\tmesh.position.set(cameraPosition.x, 0, cameraPosition.z);\n\t\t\t\tcenter.set(cameraPosition.x, 0, cameraPosition.z);\n\t\t\t} else if (plane === 'z') {\n\t\t\t\tmesh.position.set(cameraPosition.x, cameraPosition.y, 0);\n\t\t\t\tcenter.set(cameraPosition.x, cameraPosition.y, 0);\n\t\t\t} else {\n\t\t\t\tmesh.position.set(0, cameraPosition.y, cameraPosition.z);\n\t\t\t\tcenter.set(0, cameraPosition.y, cameraPosition.z);\n\t\t\t}\n\t\t\tmaterial.uniforms.uCenter.value.copy(center);\n\t\t\t// Size the unit plane to the current scale. The rotation baked into the geometry means the\n\t\t\t// plane's local XY spans the two world in-plane axes, so a uniform scale is correct on any\n\t\t\t// plane orientation.\n\t\t\tmesh.scale.setScalar(planeScale);\n\t\t},\n\t\tfitToContent: (bounds) => {\n\t\t\tif (bounds.isEmpty()) return;\n\t\t\t// Use the two in-plane axes' extent (not the full 3D diagonal) as the \"how big is this on\n\t\t\t// the ground\" measure — a tall thin part shouldn't blow the cell size up by its height.\n\t\t\tconst sizeVec = bounds.getSize(new THREE.Vector3());\n\t\t\tconst axisComponent = (v: THREE.Vector3, i: number) => (i === 0 ? v.x : i === 1 ? v.y : v.z);\n\t\t\tconst inPlaneExtent = Math.max(\n\t\t\t\taxisComponent(sizeVec, axes.x),\n\t\t\t\taxisComponent(sizeVec, axes.y)\n\t\t\t);\n\t\t\tif (!(inPlaneExtent > 0) || !Number.isFinite(inPlaneExtent)) return;\n\n\t\t\t// Aim for ~20 minor cells across the part, snapped to a nice 1/2/5 step so labels stay\n\t\t\t// readable; majorEvery keeps the coarser reference lines. Fade reaches ~2× past the part so\n\t\t\t// the grid extends beyond it without a visible edge, and the plane outreaches the fade.\n\t\t\tconst TARGET_CELLS_ACROSS = 20;\n\t\t\tmaterial.uniforms.uCell.value = niceStep(inPlaneExtent / TARGET_CELLS_ACROSS);\n\t\t\tfadeRadius = inPlaneExtent * 2;\n\t\t\tmaterial.uniforms.uFade.value = fadeRadius;\n\t\t\tplaneScale = fadeRadius * PLANE_TO_FADE_RATIO;\n\t\t},\n\t\tsetVisible: (visible) => {\n\t\t\tmesh.visible = visible;\n\t\t},\n\t\tdispose: () => {\n\t\t\tmesh.removeFromParent(); // don't leave a dead mesh in the scene graph\n\t\t\tgeometry.dispose();\n\t\t\tmaterial.dispose();\n\t\t}\n\t};\n}\n","/**\n * Dependency-free crease/boundary edge extraction — the hot core behind `addEdges`.\n *\n * Semantically a drop-in for `THREE.EdgesGeometry(geometry, angle)` (same 1e-4 vertex welding,\n * same crease test, same boundary-edge handling, same quirks for 3+-face edges), but built for\n * speed and portability:\n *\n * - Operates on raw typed arrays, so extraction is O(triangles) with **numeric** hashing — no\n * per-vertex template strings, no string-keyed object maps. Phase 0 of\n * docs/plans/4.edge-overlay-performance.md measured three's string hashing at ~2.9 s per 1M\n * triangles; this path exists to remove exactly that.\n * - {@link extractEdgeSegments} is a single self-contained function with zero outer captures\n * (only `Math` and its own arguments), so `Function.prototype.toString` on it yields code that\n * runs unchanged inside a Worker — {@link edgeExtractWorkerSource} builds that script. Keep it\n * that way: importing anything into its body silently breaks the worker path.\n */\n\n/** Vertex ids are packed two-per-double in edge keys; above 2^26 vertices the packing overflows. */\nexport const MAX_EXTRACT_VERTICES = 0x4000000; // 2^26\n\n/**\n * Extract crease + boundary edge segments from raw triangle data.\n *\n * @param positions - Non-interleaved xyz triples (a plain `position` attribute array).\n * @param index - Triangle index array, or null for non-indexed soup.\n * @param thresholdAngleDeg - Keep edges whose adjacent face normals differ by more than this.\n * @returns Segment endpoint pairs `[x0,y0,z0, x1,y1,z1, ...]` — the exact format\n * `LineSegmentsGeometry.setPositions` (and `EdgesGeometry.attributes.position.array`) uses.\n * @throws When `positions` holds ≥ 2^26 vertices (see {@link MAX_EXTRACT_VERTICES}) — callers\n * fall back to `THREE.EdgesGeometry`.\n */\nexport function extractEdgeSegments(\n\tpositions: Float32Array,\n\tindex: Uint32Array | Uint16Array | null,\n\tthresholdAngleDeg: number\n): Float32Array {\n\t// NOTE: self-contained by design (worker stringification) — no outer references besides Math.\n\tconst PRECISION = 1e4; // same quantization grid as THREE.EdgesGeometry\n\tconst ID_BITS = 0x4000000; // 2^26 — two ids pack into one float64-exact integer key\n\tconst thresholdDot = Math.cos((Math.PI / 180) * thresholdAngleDeg);\n\n\tconst vertexCount = positions.length / 3;\n\tif (vertexCount >= ID_BITS) {\n\t\tthrow new Error(`extractEdgeSegments: ${vertexCount} vertices exceeds 2^26 limit`);\n\t}\n\n\t// --- Weld vertices on the quantization grid → canonical id per vertex -------------------\n\t// Rounded coords kept as float64 (huge coordinates stay exact where int32 would overflow);\n\t// the hash only needs int32 truncations — equality always compares the exact values.\n\tconst quantX = new Float64Array(vertexCount);\n\tconst quantY = new Float64Array(vertexCount);\n\tconst quantZ = new Float64Array(vertexCount);\n\tfor (let v = 0; v < vertexCount; v++) {\n\t\tquantX[v] = Math.round(positions[3 * v] * PRECISION);\n\t\tquantY[v] = Math.round(positions[3 * v + 1] * PRECISION);\n\t\tquantZ[v] = Math.round(positions[3 * v + 2] * PRECISION);\n\t}\n\n\t// Open-addressed table (linear probing): slot → first vertex id seen at that grid point.\n\tlet capacity = 16;\n\twhile (capacity < vertexCount * 2) capacity <<= 1;\n\tconst mask = capacity - 1;\n\tconst table = new Int32Array(capacity).fill(-1);\n\tconst canonical = new Int32Array(vertexCount);\n\tfor (let v = 0; v < vertexCount; v++) {\n\t\tlet slot =\n\t\t\t(Math.imul(quantX[v] | 0, 73856093) ^\n\t\t\t\tMath.imul(quantY[v] | 0, 19349663) ^\n\t\t\t\tMath.imul(quantZ[v] | 0, 83492791)) &\n\t\t\tmask;\n\t\tfor (;;) {\n\t\t\tconst existing = table[slot];\n\t\t\tif (existing === -1) {\n\t\t\t\ttable[slot] = v;\n\t\t\t\tcanonical[v] = v;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (\n\t\t\t\tquantX[existing] === quantX[v] &&\n\t\t\t\tquantY[existing] === quantY[v] &&\n\t\t\t\tquantZ[existing] === quantZ[v]\n\t\t\t) {\n\t\t\t\tcanonical[v] = existing;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tslot = (slot + 1) & mask;\n\t\t}\n\t}\n\n\t// --- Growable segment output ------------------------------------------------------------\n\tlet out = new Float32Array(4096);\n\tlet outLength = 0;\n\tconst emit = (i0: number, i1: number): void => {\n\t\tif (outLength + 6 > out.length) {\n\t\t\tconst grown = new Float32Array(out.length * 2);\n\t\t\tgrown.set(out);\n\t\t\tout = grown;\n\t\t}\n\t\tout[outLength++] = positions[3 * i0];\n\t\tout[outLength++] = positions[3 * i0 + 1];\n\t\tout[outLength++] = positions[3 * i0 + 2];\n\t\tout[outLength++] = positions[3 * i1];\n\t\tout[outLength++] = positions[3 * i1 + 1];\n\t\tout[outLength++] = positions[3 * i1 + 2];\n\t};\n\n\t// --- Walk triangles, pairing opposite-winding edges -------------------------------------\n\t// Mirrors EdgesGeometry: a directed edge a→b matches a pending b→a; on match the segment is\n\t// kept iff the face normals differ beyond the threshold, and the pending entry is tombstoned\n\t// (key kept, value -1) so a third face on the same edge re-registers it — quirk preserved.\n\t// Unmatched entries at the end are boundary edges and always emitted.\n\tconst edgeSlots = new Map<number, number>(); // directed key → pending-edge slot, -1 = matched\n\tconst pendingIndex0: number[] = []; // original vertex indices, for boundary emission\n\tconst pendingIndex1: number[] = [];\n\tconst pendingNormals: number[] = []; // xyz per pending edge\n\n\tconst triCount = (index ? index.length : vertexCount) / 3;\n\tfor (let t = 0; t < triCount; t++) {\n\t\tconst i0 = index ? index[3 * t] : 3 * t;\n\t\tconst i1 = index ? index[3 * t + 1] : 3 * t + 1;\n\t\tconst i2 = index ? index[3 * t + 2] : 3 * t + 2;\n\t\tconst a = canonical[i0];\n\t\tconst b = canonical[i1];\n\t\tconst c = canonical[i2];\n\n\t\t// Degenerate on the quantization grid — skip, as EdgesGeometry does.\n\t\tif (a === b || b === c || c === a) continue;\n\n\t\t// Face normal, computed exactly as Triangle.getNormal: normalize((c-b) × (a-b)).\n\t\tconst e0x = positions[3 * i2] - positions[3 * i1];\n\t\tconst e0y = positions[3 * i2 + 1] - positions[3 * i1 + 1];\n\t\tconst e0z = positions[3 * i2 + 2] - positions[3 * i1 + 2];\n\t\tconst e1x = positions[3 * i0] - positions[3 * i1];\n\t\tconst e1y = positions[3 * i0 + 1] - positions[3 * i1 + 1];\n\t\tconst e1z = positions[3 * i0 + 2] - positions[3 * i1 + 2];\n\t\tlet nx = e0y * e1z - e0z * e1y;\n\t\tlet ny = e0z * e1x - e0x * e1z;\n\t\tlet nz = e0x * e1y - e0y * e1x;\n\t\tconst lengthSq = nx * nx + ny * ny + nz * nz;\n\t\tif (lengthSq > 0) {\n\t\t\tconst inverseLength = 1 / Math.sqrt(lengthSq);\n\t\t\tnx *= inverseLength;\n\t\t\tny *= inverseLength;\n\t\t\tnz *= inverseLength;\n\t\t} else {\n\t\t\tnx = 0;\n\t\t\tny = 0;\n\t\t\tnz = 0;\n\t\t}\n\n\t\tfor (let j = 0; j < 3; j++) {\n\t\t\tlet from: number;\n\t\t\tlet to: number;\n\t\t\tlet fromCanonical: number;\n\t\t\tlet toCanonical: number;\n\t\t\tif (j === 0) {\n\t\t\t\tfrom = i0;\n\t\t\t\tto = i1;\n\t\t\t\tfromCanonical = a;\n\t\t\t\ttoCanonical = b;\n\t\t\t} else if (j === 1) {\n\t\t\t\tfrom = i1;\n\t\t\t\tto = i2;\n\t\t\t\tfromCanonical = b;\n\t\t\t\ttoCanonical = c;\n\t\t\t} else {\n\t\t\t\tfrom = i2;\n\t\t\t\tto = i0;\n\t\t\t\tfromCanonical = c;\n\t\t\t\ttoCanonical = a;\n\t\t\t}\n\n\t\t\tconst reverseKey = toCanonical * ID_BITS + fromCanonical;\n\t\t\tconst reverseSlot = edgeSlots.get(reverseKey);\n\t\t\tif (reverseSlot !== undefined && reverseSlot !== -1) {\n\t\t\t\tconst dot =\n\t\t\t\t\tnx * pendingNormals[3 * reverseSlot] +\n\t\t\t\t\tny * pendingNormals[3 * reverseSlot + 1] +\n\t\t\t\t\tnz * pendingNormals[3 * reverseSlot + 2];\n\t\t\t\tif (dot <= thresholdDot) emit(from, to);\n\t\t\t\tedgeSlots.set(reverseKey, -1);\n\t\t\t} else {\n\t\t\t\tconst forwardKey = fromCanonical * ID_BITS + toCanonical;\n\t\t\t\tif (!edgeSlots.has(forwardKey)) {\n\t\t\t\t\tconst slot = pendingIndex0.length;\n\t\t\t\t\tedgeSlots.set(forwardKey, slot);\n\t\t\t\t\tpendingIndex0.push(from);\n\t\t\t\t\tpendingIndex1.push(to);\n\t\t\t\t\tpendingNormals.push(nx, ny, nz);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// --- Unmatched edges are boundaries — always kept ---------------------------------------\n\tfor (const slot of edgeSlots.values()) {\n\t\tif (slot !== -1) emit(pendingIndex0[slot], pendingIndex1[slot]);\n\t}\n\n\treturn out.slice(0, outLength);\n}\n\n/**\n * Build the source of a Worker that runs {@link extractEdgeSegments} off the main thread.\n * Protocol: receives `{id, positions, index, thresholdAngle}`, replies `{id, segments}` with the\n * segment buffer transferred, or `{id, error}` on failure.\n *\n * Relies on `extractEdgeSegments` stringifying to standalone code — guarded by a unit test that\n * evals this source in isolation.\n */\nexport function edgeExtractWorkerSource(): string {\n\treturn [\n\t\t`const extract = ${extractEdgeSegments.toString()};`,\n\t\t`self.onmessage = (event) => {`,\n\t\t` const { id, positions, index, thresholdAngle } = event.data;`,\n\t\t` try {`,\n\t\t` const segments = extract(positions, index, thresholdAngle);`,\n\t\t` self.postMessage({ id, segments }, [segments.buffer]);`,\n\t\t` } catch (error) {`,\n\t\t` self.postMessage({ id, error: String((error && error.message) || error) });`,\n\t\t` }`,\n\t\t`};`\n\t].join('\\n');\n}\n","import * as THREE from 'three';\nimport { LineSegmentsGeometry } from 'three/addons/lines/LineSegmentsGeometry.js';\nimport { LineSegments2 } from 'three/addons/lines/LineSegments2.js';\nimport { LineMaterial } from 'three/addons/lines/LineMaterial.js';\n\nimport { MAX_EXTRACT_VERTICES, edgeExtractWorkerSource, extractEdgeSegments } from './edge-extract';\n\n/**\n * Crisp boundary/crease edges overlaid on meshes — the defining \"technical drawing\" look that makes\n * shaded geometry read as discrete objects rather than blobs.\n *\n * Edge segments are extracted by `extractEdgeSegments` (see edge-extract.ts — an\n * `EdgesGeometry`-equivalent that is ~an order of magnitude faster and worker-portable) and\n * rendered as fat `LineSegments2` using the same `LineMaterial` family as curves — so edges get\n * controllable thickness, not the 1px cap of `THREE.LineSegments`. The overlay is added as a\n * *child* of each mesh, so it inherits the mesh's transform and is disposed when the mesh subtree\n * is cleared.\n *\n * Performance model (docs/plans/4.edge-overlay-performance.md):\n * - Extraction results are cached at two levels: per source `BufferGeometry` (object identity,\n * helps instanced parts within one solve) and by *content fingerprint* in an LRU — the viewer\n * rebuilds all geometry objects every solve, so only a content key survives re-solves.\n * - {@link addEdgesAsync} runs extraction for large meshes in a Worker built from a blob URL\n * (bundler-agnostic; falls back to inline extraction when Workers are unavailable), keeping the\n * main thread free of the multi-second stalls extraction causes at millions of triangles.\n * - Caps bound the pathological cases: meshes above `maxTriangles` are skipped outright (tagged\n * `userData.edgesSkipped = 'triangle-cap'`), overlays above `maxSegments` lose the distance\n * fade so they render in the cheaper opaque pass.\n *\n * Depth strategy: surfaces render at TRUE depth, untouched; the LINES carry a small units-only\n * polygonOffset toward the camera (see EDGE_OFFSET_FACTOR/UNITS).\n *\n * This reverses an earlier strategy that instead pushed each mesh's *surface* back with a\n * slope-scaled offset (factor 1, units 2). That version bled badly: the slope term scales with\n * dZ/dpixel, which is enormous on a surface viewed near edge-on, so grazing faces receded by much\n * more than the millimetre gaps between stacked parts — geometry behind a wall then beat the wall's\n * own receded surface and drew through it. It also clobbered the polygonOffset that look presets\n * configure on their materials, and its \"restore\" path reset those to 0 rather than to the preset's\n * values.\n *\n * A units-only bias on the lines is bounded by construction: a fixed number of depth quantization\n * steps, independent of viewing angle, so it lifts an edge off its own coplanar surface without ever\n * reaching across to a neighbouring part.\n *\n * The caveat the old strategy correctly identified: a depth ULP grows ~quadratically with viewing\n * distance, so a constant bias is only safe while ULPs stay small. That is what the dynamic\n * near-plane fitter (near-plane.ts) buys — it keeps `camera.near` proportional to the camera↔content\n * gap, holding ULPs at micron scale even zoomed well out. The two mechanisms are load-bearing\n * together; weakening the near fit will make this bias start to bleed.\n */\nexport interface EdgeOptions {\n\t/**\n\t * Force a single edge color for every overlay. When omitted (the default), each overlay derives\n\t * its color from its own mesh's material — a darkened tint of the surface — so edges read as the\n\t * object's own outline rather than a uniform black frame. Meshes with no readable material color\n\t * fall back to {@link DEFAULT_EDGE_COLOR}.\n\t */\n\tcolor?: THREE.ColorRepresentation;\n\t/**\n\t * How far to darken the derived edge color toward black, 0–1 (default 0.75). Only applies when\n\t * `color` is omitted. Higher = darker edges; 0 leaves edges the surface color, 1 makes them black.\n\t */\n\tdarken?: number;\n\t/** Edge thickness in CSS px. Default 1.5. */\n\twidth?: number;\n\t/**\n\t * Crease angle in degrees: an edge is kept only where its two faces differ by more than this.\n\t * Default 44. Higher = fewer edges (only sharp creases); lower = more (catches gentle bends).\n\t */\n\tthresholdAngle?: number;\n\t/**\n\t * Fade an overlay out as its own edges crowd together on screen (default true). Edges draw at a\n\t * constant pixel width, so once neighbouring lines sit less than a pixel or two apart they stop\n\t * resolving and merge into a dark smear — worst on layered sheet goods, whose millimetre-pitch\n\t * laminations are sub-pixel at any normal zoom on a metre-scale part. Fading by edge density\n\t * (not by how large the mesh is) returns those parts to a clean shaded read while leaving\n\t * sparsely-edged geometry fully drawn at the same distance.\n\t */\n\tdistanceFade?: boolean;\n\t/**\n\t * Skip meshes above this triangle count entirely (default 4M) — extraction time is linear in\n\t * triangles, and past this bound even the worker path burns seconds for a look the screen-space\n\t * fallback approximates at constant cost. Skipped meshes are tagged\n\t * `userData.edgesSkipped = 'triangle-cap'` so hosts can react (e.g. enable the render-pipeline\n\t * edge pass).\n\t */\n\tmaxTriangles?: number;\n\t/**\n\t * Above this many extracted segments (default 2M), an overlay drops the distance fade so it\n\t * renders opaque — millions of blended fat-line quads are a fill-rate cliff; opaque ones aren't.\n\t */\n\tmaxSegments?: number;\n}\n\n/** Tag on edge overlays so pick/fit/clear logic can recognize and skip or dispose them. */\nexport const EDGE_USERDATA_KIND = 'edge-overlay';\n\n/** `userData.edgesSkipped` value on meshes whose triangle count exceeded {@link EdgeOptions.maxTriangles}. */\nexport const EDGES_SKIPPED_TRIANGLE_CAP = 'triangle-cap';\n\nconst DEFAULT_EDGE_COLOR = 0x222222;\nconst DEFAULT_EDGE_WIDTH = 1.5;\nconst DEFAULT_THRESHOLD_ANGLE = 44;\nconst DEFAULT_DARKEN = 0.75;\nconst DEFAULT_MAX_TRIANGLES = 4_000_000;\nconst DEFAULT_MAX_SEGMENTS = 2_000_000;\n\n/**\n * Below this triangle count extraction runs inline even on the async path — a worker round-trip\n * (copy + transfer + wake) costs more than the extraction itself. Phase 0 measured three's\n * extractor at ~200 ms per 100k triangles; the replacement extractor is ~an order faster, putting\n * 25k triangles well under a frame.\n */\nconst INLINE_TRIANGLE_BUDGET = 25_000;\n\n/** CPU byte budget for the cross-solve segment cache (Float32 segment arrays only). */\nconst SEGMENT_CACHE_BYTE_BUDGET = 128 * 1024 * 1024;\n\n// Edge-density fade band, as the mean on-screen gap between neighbouring edges in px: fully opaque\n// at/above FADE_START_PX, fully gone at/below FADE_END_PX, linear between.\n//\n// Density, not object size, is what breaks the technical look when zoomed out. A big part whose\n// edges have collapsed to sub-pixel spacing is precisely the failure case — every line still draws\n// at full width and full opacity, so they merge into a dark smear that reads as \"all the interior\n// edges showing through\". Fading on the *bounding sphere* instead (the previous rule) never fires\n// for that part at all, because the sphere still covers most of the viewport.\n//\n// The band sits just above 1 px: below ~2 px apart, constant-width lines visibly overlap, and by\n// 1 px they are a solid fill. Fading out across that range returns the part to its shaded read.\nconst FADE_START_PX = 4;\nconst FADE_END_PX = 1;\n\n// Edge pull-forward (see module doc). Units only — deliberately NO slope (factor) term.\n//\n// The slope term scales with the polygon's dZ/dpixel, which is small head-on but very large at\n// grazing angles: on a long surface viewed near edge-on, one pixel spans a lot of depth. Applying it\n// to the *surfaces* (the previous strategy) pushed grazing faces back by far more than the\n// millimetre-scale gaps between stacked parts, so geometry BEHIND a wall won the depth test against\n// the wall's own receded surface and its edges drew straight through — exactly the bleed-through\n// this offset exists to prevent.\n//\n// A units-only bias on the lines is bounded instead: it is a fixed number of depth quantization\n// steps regardless of viewing angle, so it can lift an edge off its own coplanar surface without\n// ever reaching across the gap to a neighbouring part. 1 unit is the minimum that reliably wins\n// z-fighting against the surface the edge was extracted from.\nconst EDGE_OFFSET_FACTOR = 0;\nconst EDGE_OFFSET_UNITS = -1; // negative = toward the camera\n\n// ============================================================================\n// Segment extraction — fast path, content cache, worker offload\n// ============================================================================\n\nfunction triangleCountOf(geometry: THREE.BufferGeometry): number {\n\tconst position = geometry.getAttribute('position');\n\tif (!position) return 0;\n\treturn (geometry.index ? geometry.index.count : position.count) / 3;\n}\n\ninterface FastPathData {\n\tpositions: Float32Array;\n\tindex: Uint32Array | Uint16Array | null;\n}\n\n/**\n * The fast extractor consumes plain non-interleaved float32 xyz + typed index arrays — which is\n * what every geometry in this pipeline has. Anything exotic (interleaved, float64, morphed) falls\n * back to `THREE.EdgesGeometry`, trading speed for guaranteed-identical semantics.\n */\nfunction fastPathData(geometry: THREE.BufferGeometry): FastPathData | null {\n\tconst position = geometry.getAttribute('position');\n\tif (\n\t\t!position ||\n\t\t(position as THREE.InterleavedBufferAttribute).isInterleavedBufferAttribute ||\n\t\tposition.itemSize !== 3 ||\n\t\t!(position.array instanceof Float32Array) ||\n\t\tposition.count >= MAX_EXTRACT_VERTICES\n\t) {\n\t\treturn null;\n\t}\n\tconst index = geometry.index;\n\tif (index && !(index.array instanceof Uint32Array) && !(index.array instanceof Uint16Array)) {\n\t\treturn null;\n\t}\n\treturn {\n\t\tpositions: position.array,\n\t\tindex: index ? (index.array as Uint32Array | Uint16Array) : null\n\t};\n}\n\n/**\n * Content fingerprint for the cross-solve cache: FNV-1a over sampled raw words of the position\n * (and index) arrays plus their lengths and the crease angle. Sampling (head + tail blocks) keeps\n * it ~free even at millions of vertices; two *different* solves colliding would need identical\n * lengths AND identical sampled regions — not a realistic geometry edit.\n */\nfunction contentKey(data: FastPathData, thresholdAngle: number): string {\n\tconst SAMPLE_WORDS = 4096;\n\tlet hash = 0x811c9dc5;\n\tconst mix = (word: number): void => {\n\t\thash ^= word;\n\t\thash = Math.imul(hash, 0x01000193);\n\t};\n\n\tconst words = new Uint32Array(\n\t\tdata.positions.buffer,\n\t\tdata.positions.byteOffset,\n\t\tdata.positions.length\n\t);\n\tconst head = Math.min(SAMPLE_WORDS, words.length);\n\tfor (let i = 0; i < head; i++) mix(words[i]);\n\tfor (let i = Math.max(head, words.length - SAMPLE_WORDS); i < words.length; i++) mix(words[i]);\n\n\tlet indexLength = 0;\n\tif (data.index) {\n\t\tindexLength = data.index.length;\n\t\tconst headIndex = Math.min(SAMPLE_WORDS, indexLength);\n\t\tfor (let i = 0; i < headIndex; i++) mix(data.index[i]);\n\t\tfor (let i = Math.max(headIndex, indexLength - SAMPLE_WORDS); i < indexLength; i++) {\n\t\t\tmix(data.index[i]);\n\t\t}\n\t}\n\n\treturn `${thresholdAngle}:${data.positions.length}:${indexLength}:${hash >>> 0}`;\n}\n\n/**\n * Cross-solve segment cache. The viewer rebuilds every `BufferGeometry` each solve, so identity\n * caches never hit across solves — this LRU keys on content instead, making \"same meshes again\"\n * (unchanged inputs, toggling edges, camera-only updates) free. Stores raw segment arrays (CPU\n * only); `LineSegmentsGeometry` uses the array as its backing store without copying, so entries\n * are safely shared across any number of overlays.\n */\nconst segmentCache = new Map<string, Float32Array>();\nlet segmentCacheBytes = 0;\n\nfunction segmentCacheGet(key: string): Float32Array | undefined {\n\tconst cached = segmentCache.get(key);\n\tif (cached) {\n\t\t// Refresh LRU order.\n\t\tsegmentCache.delete(key);\n\t\tsegmentCache.set(key, cached);\n\t}\n\treturn cached;\n}\n\nfunction segmentCachePut(key: string, segments: Float32Array): void {\n\tif (segments.byteLength > SEGMENT_CACHE_BYTE_BUDGET) return;\n\tconst existing = segmentCache.get(key);\n\tif (existing) {\n\t\tsegmentCacheBytes -= existing.byteLength;\n\t\tsegmentCache.delete(key);\n\t}\n\tsegmentCache.set(key, segments);\n\tsegmentCacheBytes += segments.byteLength;\n\twhile (segmentCacheBytes > SEGMENT_CACHE_BYTE_BUDGET) {\n\t\tconst oldestKey = segmentCache.keys().next().value as string;\n\t\tsegmentCacheBytes -= segmentCache.get(oldestKey)!.byteLength;\n\t\tsegmentCache.delete(oldestKey);\n\t}\n}\n\n/** Extract via `THREE.EdgesGeometry` — the slow but universally-correct fallback. */\nfunction extractViaThree(geometry: THREE.BufferGeometry, thresholdAngle: number): Float32Array {\n\tconst edges = new THREE.EdgesGeometry(geometry, thresholdAngle);\n\tconst positions = edges.attributes.position\n\t\t? (edges.attributes.position.array as Float32Array)\n\t\t: new Float32Array(0);\n\tedges.dispose(); // frees only GPU-side state; the CPU array is the return value\n\treturn positions;\n}\n\n/** Synchronous extraction: content cache → fast extractor → EdgesGeometry fallback. */\nfunction extractSegmentsSync(geometry: THREE.BufferGeometry, thresholdAngle: number): Float32Array {\n\tconst data = fastPathData(geometry);\n\tif (!data) return extractViaThree(geometry, thresholdAngle);\n\n\tconst key = contentKey(data, thresholdAngle);\n\tconst cached = segmentCacheGet(key);\n\tif (cached) return cached;\n\n\tconst segments = extractEdgeSegments(data.positions, data.index, thresholdAngle);\n\tsegmentCachePut(key, segments);\n\treturn segments;\n}\n\n// --- Worker offload -----------------------------------------------------------------------------\n\ninterface PendingRequest {\n\tresolve: (segments: Float32Array) => void;\n\treject: (error: Error) => void;\n}\n\nlet extractionWorker: Worker | null | undefined; // undefined = not yet tried, null = unavailable\nconst pendingRequests = new Map<number, PendingRequest>();\nlet nextRequestId = 1;\n\nfunction getExtractionWorker(): Worker | null {\n\tif (extractionWorker !== undefined) return extractionWorker;\n\tif (\n\t\ttypeof Worker === 'undefined' ||\n\t\ttypeof Blob === 'undefined' ||\n\t\ttypeof URL === 'undefined' ||\n\t\ttypeof URL.createObjectURL !== 'function'\n\t) {\n\t\textractionWorker = null;\n\t\treturn null;\n\t}\n\ttry {\n\t\t// Blob URL keeps the library bundler-agnostic (no `new Worker(new URL(...))` magic). The URL\n\t\t// is deliberately never revoked: revoking before the worker finishes fetching is\n\t\t// unspecified behavior, and one blob URL for a process-lifetime singleton is negligible.\n\t\tconst url = URL.createObjectURL(\n\t\t\tnew Blob([edgeExtractWorkerSource()], { type: 'text/javascript' })\n\t\t);\n\t\tconst worker = new Worker(url);\n\t\tworker.onmessage = (event: MessageEvent) => {\n\t\t\tconst { id, segments, error } = event.data as {\n\t\t\t\tid: number;\n\t\t\t\tsegments?: Float32Array;\n\t\t\t\terror?: string;\n\t\t\t};\n\t\t\tconst pending = pendingRequests.get(id);\n\t\t\tif (!pending) return;\n\t\t\tpendingRequests.delete(id);\n\t\t\tif (segments) pending.resolve(segments);\n\t\t\telse pending.reject(new Error(error ?? 'edge extraction failed in worker'));\n\t\t};\n\t\tworker.onerror = () => {\n\t\t\t// Worker died (CSP, OOM, script error): fail everything in flight — callers fall back to\n\t\t\t// inline extraction — and never try the worker again this session.\n\t\t\tfor (const pending of pendingRequests.values()) {\n\t\t\t\tpending.reject(new Error('edge extraction worker crashed'));\n\t\t\t}\n\t\t\tpendingRequests.clear();\n\t\t\tworker.terminate();\n\t\t\textractionWorker = null;\n\t\t};\n\t\textractionWorker = worker;\n\t} catch {\n\t\textractionWorker = null;\n\t}\n\treturn extractionWorker;\n}\n\nfunction extractInWorker(\n\tworker: Worker,\n\tdata: FastPathData,\n\tthresholdAngle: number\n): Promise<Float32Array> {\n\treturn new Promise<Float32Array>((resolve, reject) => {\n\t\tconst id = nextRequestId++;\n\t\tpendingRequests.set(id, { resolve, reject });\n\t\t// Copy before transfer — the originals back the render geometry.\n\t\tconst positions = data.positions.slice();\n\t\tconst index = data.index ? data.index.slice() : null;\n\t\tconst transfer: Transferable[] = [positions.buffer];\n\t\tif (index) transfer.push(index.buffer);\n\t\tworker.postMessage({ id, positions, index, thresholdAngle }, transfer);\n\t});\n}\n\n/**\n * In-flight dedupe: N meshes with identical content (or repeated applies during one extraction)\n * share one worker round-trip. Keyed by content key; cleared when the request settles (results\n * land in the segment cache, which takes over from there).\n */\nconst inFlightExtractions = new Map<string, Promise<Float32Array>>();\n\n/** Asynchronous extraction: cache → worker (large fast-path meshes) → inline fallback. */\nfunction extractSegmentsAsync(\n\tgeometry: THREE.BufferGeometry,\n\tthresholdAngle: number\n): Promise<Float32Array> {\n\tconst data = fastPathData(geometry);\n\tif (!data || triangleCountOf(geometry) < INLINE_TRIANGLE_BUDGET) {\n\t\treturn Promise.resolve(extractSegmentsSync(geometry, thresholdAngle));\n\t}\n\n\tconst key = contentKey(data, thresholdAngle);\n\tconst cached = segmentCacheGet(key);\n\tif (cached) return Promise.resolve(cached);\n\n\tconst inFlight = inFlightExtractions.get(key);\n\tif (inFlight) return inFlight;\n\n\tconst worker = getExtractionWorker();\n\tif (!worker) return Promise.resolve(extractSegmentsSync(geometry, thresholdAngle));\n\n\tconst request = extractInWorker(worker, data, thresholdAngle)\n\t\t.catch(() => extractEdgeSegments(data.positions, data.index, thresholdAngle))\n\t\t.then((segments) => {\n\t\t\tsegmentCachePut(key, segments);\n\t\t\treturn segments;\n\t\t})\n\t\t.finally(() => {\n\t\t\tinFlightExtractions.delete(key);\n\t\t});\n\tinFlightExtractions.set(key, request);\n\treturn request;\n}\n\n// ============================================================================\n// Per-geometry line-geometry cache (identity-keyed, refcounted)\n// ============================================================================\n\n/**\n * Extracted edge geometry, cached per source `BufferGeometry` (and per crease angle, since the\n * angle changes which edges survive). N meshes sharing one geometry — the common case for\n * instanced/repeated parts — get one extraction and one GPU buffer instead of N identical ones.\n *\n * Reference-counted so {@link removeEdges} only disposes a line geometry once its last overlay is\n * gone. The WeakMap keys on the source geometry, so entries vanish with the content they describe;\n * overlays disposed by whole-scene clears (which bypass removeEdges) just leave a refcount behind\n * on an entry that becomes unreachable together with its source geometry.\n */\ninterface EdgeGeometryEntry {\n\tgeometry: LineSegmentsGeometry;\n\trefCount: number;\n\tsegmentCount: number;\n\t/**\n\t * Mean world-space spacing between this overlay's edges: the characteristic distance at which\n\t * neighbouring lines sit. Drives the density fade (see {@link enableDistanceFade}) — an overlay\n\t * fades when *this* projects below a pixel, which is when its lines start merging, regardless of\n\t * how large the mesh itself is on screen.\n\t *\n\t * Estimated as area/length: total edge length L spread over the mesh's projected extent A behaves\n\t * like a set of parallel lines A/L apart. Infinity for degenerate cases (no length, no extent), so\n\t * they never fade.\n\t */\n\tedgeSpacing: number;\n}\n\n/**\n * Fraction of segments allowed to be shorter than the reported spacing. A low percentile tracks the\n * *fine* detail rather than the average: real parts mix a handful of long silhouette edges with many\n * short ones, and it is the short ones that merge first.\n */\nconst SPACING_PERCENTILE = 0.15;\n\n/** Cap on segments sampled for the percentile — a stride keeps this O(1) on millions of segments. */\nconst SPACING_SAMPLE_LIMIT = 4096;\n\n/**\n * Characteristic spacing between an overlay's edges, in world units: the\n * {@link SPACING_PERCENTILE} quantile of segment length.\n *\n * Segment length is the right proxy for spacing on the geometry this targets. Layered sheet goods —\n * plywood laminations, stacked panels — produce a ladder of short segments spanning each layer's\n * thickness, so the short-segment population *is* the layer pitch, which is exactly the distance\n * that collapses below a pixel and smears the lines together.\n *\n * A quantile rather than a mean because the two populations differ by orders of magnitude: a 10 m\n * part with 1 mm laminations mixes lengths at 1:10000, and any average of those sits far above the\n * pitch (so the laminations never fade) while still far below the outline (so the outline fades\n * early). Taking a low quantile lets the dense detail drive the fade without the silhouette edges\n * dragging it up. Infinity when there is nothing to measure, which never fades.\n */\nfunction edgeSpacingOf(segments: Float32Array): number {\n\tconst segmentCount = Math.floor(segments.length / 6);\n\tif (segmentCount === 0) return Infinity;\n\n\tconst stride = Math.max(1, Math.ceil(segmentCount / SPACING_SAMPLE_LIMIT));\n\tconst lengths: number[] = [];\n\tfor (let s = 0; s < segmentCount; s += stride) {\n\t\tconst i = s * 6;\n\t\tconst length = Math.hypot(\n\t\t\tsegments[i + 3] - segments[i],\n\t\t\tsegments[i + 4] - segments[i + 1],\n\t\t\tsegments[i + 5] - segments[i + 2]\n\t\t);\n\t\tif (length > 0) lengths.push(length);\n\t}\n\tif (lengths.length === 0) return Infinity;\n\n\tlengths.sort((a, b) => a - b);\n\treturn lengths[Math.min(lengths.length - 1, Math.floor(lengths.length * SPACING_PERCENTILE))];\n}\nconst edgeGeometryCache = new WeakMap<THREE.BufferGeometry, Map<number, EdgeGeometryEntry>>();\n\nfunction cachedEntry(\n\tgeometry: THREE.BufferGeometry,\n\tthresholdAngle: number\n): EdgeGeometryEntry | undefined {\n\treturn edgeGeometryCache.get(geometry)?.get(thresholdAngle);\n}\n\nfunction storeEntry(\n\tgeometry: THREE.BufferGeometry,\n\tthresholdAngle: number,\n\tsegments: Float32Array\n): EdgeGeometryEntry {\n\tlet byAngle = edgeGeometryCache.get(geometry);\n\tif (!byAngle) {\n\t\tbyAngle = new Map();\n\t\tedgeGeometryCache.set(geometry, byAngle);\n\t}\n\t// LineSegmentsGeometry adopts `segments` as its backing store without copying — sharing the\n\t// array with the segment cache and with other entries is safe (read-only from here on).\n\tconst lineGeometry = new LineSegmentsGeometry();\n\tlineGeometry.setPositions(segments);\n\tconst entry: EdgeGeometryEntry = {\n\t\tgeometry: lineGeometry,\n\t\trefCount: 0,\n\t\tsegmentCount: segments.length / 6,\n\t\tedgeSpacing: edgeSpacingOf(segments)\n\t};\n\tbyAngle.set(thresholdAngle, entry);\n\treturn entry;\n}\n\n/** Where an overlay's (possibly shared) line geometry came from, for refcounted disposal. */\ninterface EdgeOverlayUserData {\n\tkind: string;\n\tedgeSource?: THREE.BufferGeometry;\n\tedgeThresholdAngle?: number;\n}\n\n/** Refcounted disposal — only when the last overlay referencing an entry is gone. */\nfunction releaseEdgeGeometry(overlay: LineSegments2): void {\n\tconst userData = overlay.userData as EdgeOverlayUserData;\n\tconst byAngle = userData.edgeSource && edgeGeometryCache.get(userData.edgeSource);\n\tconst entry =\n\t\tuserData.edgeThresholdAngle != null ? byAngle?.get(userData.edgeThresholdAngle) : undefined;\n\n\tif (!entry || entry.geometry !== overlay.geometry) {\n\t\t// Not (or no longer) cache-managed — dispose directly.\n\t\toverlay.geometry.dispose();\n\t\treturn;\n\t}\n\n\tentry.refCount -= 1;\n\tif (entry.refCount <= 0) {\n\t\tentry.geometry.dispose();\n\t\tbyAngle!.delete(userData.edgeThresholdAngle!);\n\t}\n}\n\n// ============================================================================\n// Overlay construction\n// ============================================================================\n\ninterface ResolvedOptions {\n\tforcedColor: THREE.Color | null;\n\tdarken: number;\n\twidth: number;\n\tthresholdAngle: number;\n\tdistanceFade: boolean;\n\tmaxTriangles: number;\n\tmaxSegments: number;\n}\n\nfunction resolveOptions(options: EdgeOptions): ResolvedOptions {\n\treturn {\n\t\tforcedColor: options.color != null ? new THREE.Color(options.color) : null,\n\t\tdarken: THREE.MathUtils.clamp(options.darken ?? DEFAULT_DARKEN, 0, 1),\n\t\twidth: options.width ?? DEFAULT_EDGE_WIDTH,\n\t\tthresholdAngle: options.thresholdAngle ?? DEFAULT_THRESHOLD_ANGLE,\n\t\tdistanceFade: options.distanceFade ?? true,\n\t\tmaxTriangles: options.maxTriangles ?? DEFAULT_MAX_TRIANGLES,\n\t\tmaxSegments: options.maxSegments ?? DEFAULT_MAX_SEGMENTS\n\t};\n}\n\n/**\n * Edge color for a mesh when no color is forced: the mesh's own surface color darkened toward black\n * by `darken` (0 = surface color, 1 = black), so edges read as the object's darker outline. Falls\n * back to {@link DEFAULT_EDGE_COLOR} when no material color is readable. Multiplicative darkening\n * preserves hue and desaturates gently; a near-black surface just yields near-black edges.\n */\nfunction deriveEdgeColor(mesh: THREE.Mesh, darken: number): THREE.Color {\n\tconst material = Array.isArray(mesh.material) ? mesh.material[0] : mesh.material;\n\tconst source = (material as { color?: THREE.Color } | null)?.color;\n\tif (!source) return new THREE.Color(DEFAULT_EDGE_COLOR);\n\treturn source.clone().multiplyScalar(1 - darken);\n}\n\n/**\n * Overlays sharing a color and fade mode share a material: with a forced color that's one material\n * per `addEdges` call; when deriving per-mesh, meshes of the same surface color (instanced/repeated\n * parts) still collapse onto one. The fade bit is part of the key because fading needs\n * `transparent = true` while capped overlays must stay opaque.\n */\nclass MaterialPool {\n\tprivate readonly byKey = new Map<number, LineMaterial>();\n\tconstructor(private readonly options: ResolvedOptions) {}\n\n\tfor(mesh: THREE.Mesh, fade: boolean): LineMaterial {\n\t\tconst color = this.options.forcedColor ?? deriveEdgeColor(mesh, this.options.darken);\n\t\tconst key = color.getHex() * 2 + (fade ? 1 : 0);\n\t\tlet material = this.byKey.get(key);\n\t\tif (!material) {\n\t\t\tmaterial = createEdgeMaterial(color, this.options.width, fade);\n\t\t\tthis.byKey.set(key, material);\n\t\t}\n\t\treturn material;\n\t}\n\n\t/** Dispose any material no overlay adopted (e.g. every mesh was skipped or cancelled). */\n\tdisposeUnused(created: LineSegments2[]): void {\n\t\tconst used = new Set(created.map((overlay) => overlay.material));\n\t\tfor (const material of this.byKey.values()) {\n\t\t\tif (!used.has(material)) material.dispose();\n\t\t}\n\t}\n}\n\nfunction createEdgeMaterial(\n\tcolor: THREE.Color,\n\twidth: number,\n\tdistanceFade: boolean\n): LineMaterial {\n\t// LineMaterialParameters omits linewidth/opacity from its type though both exist at runtime.\n\tconst material = new LineMaterial({ color });\n\t(material as LineMaterial & { linewidth: number }).linewidth = width;\n\t// Lift the lines a fixed couple of quantization steps toward the camera so they win against the\n\t// surface they were extracted from, without touching the surfaces themselves (see the constants).\n\tmaterial.polygonOffset = true;\n\tmaterial.polygonOffsetFactor = EDGE_OFFSET_FACTOR;\n\tmaterial.polygonOffsetUnits = EDGE_OFFSET_UNITS;\n\t// Fading needs blending; set once here rather than per draw, since flipping `transparent` after\n\t// the render list is built wouldn't re-sort the object into the transparent pass.\n\tif (distanceFade) material.transparent = true;\n\treturn material;\n}\n\nfunction buildEdgeOverlay(\n\tsourceGeometry: THREE.BufferGeometry,\n\tentry: EdgeGeometryEntry,\n\tmaterial: LineMaterial,\n\tthresholdAngle: number,\n\tdistanceFade: boolean\n): LineSegments2 {\n\tentry.refCount += 1;\n\n\tconst overlay = new LineSegments2(entry.geometry, material);\n\toverlay.userData.kind = EDGE_USERDATA_KIND;\n\t// Remember which cache entry backs this overlay so removeEdges can refcount its disposal. The\n\t// strong reference is fine: the overlay is a child of the mesh that owns the source geometry,\n\t// so their lifetimes already coincide.\n\toverlay.userData.edgeSource = sourceGeometry;\n\toverlay.userData.edgeThresholdAngle = thresholdAngle;\n\toverlay.raycast = () => {}; // never pickable; clicks should hit the mesh, not its outline\n\tif (distanceFade) enableDistanceFade(overlay, entry.edgeSpacing);\n\treturn overlay;\n}\n\nconst _fadeCenter = new THREE.Vector3();\nconst _fadeCameraPos = new THREE.Vector3();\n\n/**\n * Pixels per world unit at the overlay's centre — the scale that converts a world-space edge spacing\n * into the on-screen gap driving the density fade. Returns Infinity (\"don't fade\") when the\n * projection is unknown or degenerate, and for a perspective camera sitting inside the mesh.\n */\nfunction pixelsPerWorldUnit(\n\toverlay: LineSegments2,\n\tcamera: THREE.Camera,\n\tviewportHeightPx: number\n): number {\n\tif (!overlay.geometry.boundingSphere) overlay.geometry.computeBoundingSphere();\n\tconst sphere = overlay.geometry.boundingSphere;\n\tif (!sphere) return Infinity;\n\n\tif ((camera as THREE.PerspectiveCamera).isPerspectiveCamera) {\n\t\tconst perspective = camera as THREE.PerspectiveCamera;\n\t\t_fadeCenter.copy(sphere.center).applyMatrix4(overlay.matrixWorld);\n\t\tconst distance = _fadeCameraPos\n\t\t\t.setFromMatrixPosition(camera.matrixWorld)\n\t\t\t.distanceTo(_fadeCenter);\n\t\tconst radius = sphere.radius * overlay.matrixWorld.getMaxScaleOnAxis();\n\t\tif (distance <= radius) return Infinity; // camera inside the mesh — no fade\n\t\tconst tanHalfFov = Math.tan(THREE.MathUtils.degToRad(perspective.fov) * 0.5);\n\t\tconst worldHeightAtCentre = 2 * distance * tanHalfFov;\n\t\treturn worldHeightAtCentre > 0 ? viewportHeightPx / worldHeightAtCentre : Infinity;\n\t}\n\tif ((camera as THREE.OrthographicCamera).isOrthographicCamera) {\n\t\tconst ortho = camera as THREE.OrthographicCamera;\n\t\tconst worldHeight = (ortho.top - ortho.bottom) / ortho.zoom;\n\t\treturn worldHeight > 0 ? viewportHeightPx / worldHeight : Infinity;\n\t}\n\treturn Infinity;\n}\n\n/**\n * Fade this overlay by its on-screen size (see FADE_START_PX/FADE_END_PX). Hooked into\n * onBeforeRender so the opacity is written immediately before *this* overlay's draw — uniforms\n * upload per draw call, so overlays sharing one material still fade independently. Chains\n * LineSegments2's own onBeforeRender, which keeps the material's resolution uniform in sync.\n */\nfunction enableDistanceFade(overlay: LineSegments2, edgeSpacing: number): void {\n\t// Assign via the Object3D base type: LineSegments2's typings narrow onBeforeRender to\n\t// (renderer) only, but the renderer actually calls it with (renderer, scene, camera, …).\n\t(overlay as THREE.Object3D).onBeforeRender = (renderer, _scene, camera) => {\n\t\tLineSegments2.prototype.onBeforeRender.call(overlay, renderer);\n\t\tconst material = overlay.material as LineMaterial;\n\t\tconst scale = pixelsPerWorldUnit(overlay, camera, material.resolution.y);\n\t\t// Mean gap between neighbouring edges, on screen. Infinity (unknown projection, camera inside\n\t\t// the mesh) yields Infinity here too, which clamps to fully opaque — never fade on a guess.\n\t\tconst gapPx = edgeSpacing * scale;\n\t\tmaterial.opacity = THREE.MathUtils.clamp(\n\t\t\t(gapPx - FADE_END_PX) / (FADE_START_PX - FADE_END_PX),\n\t\t\t0,\n\t\t\t1\n\t\t);\n\t};\n}\n\n// ============================================================================\n// Public API — add / remove / query\n// ============================================================================\n\n/** Whether an object is an edge overlay (for pick/fit filters elsewhere). */\nexport function isEdgeOverlay(object: THREE.Object3D): boolean {\n\treturn object.userData?.kind === EDGE_USERDATA_KIND;\n}\n\n/** Meshes under `root` that should get an overlay: content meshes without one, caps applied. */\nfunction collectTargets(root: THREE.Object3D, maxTriangles: number): THREE.Mesh[] {\n\tconst targets: THREE.Mesh[] = [];\n\troot.traverse((object) => {\n\t\tif (!(object instanceof THREE.Mesh)) return;\n\t\tif (object.userData.id === 'floor' || object.userData.id === 'grid') return;\n\t\tif (object.userData.kind === EDGE_USERDATA_KIND) return;\n\t\tif (object.children.some((c) => c.userData?.kind === EDGE_USERDATA_KIND)) return; // already done\n\t\tif (!object.geometry) return;\n\n\t\tif (triangleCountOf(object.geometry) > maxTriangles) {\n\t\t\tobject.userData.edgesSkipped = EDGES_SKIPPED_TRIANGLE_CAP;\n\t\t\t// eslint-disable-next-line no-console\n\t\t\tconsole.debug(\n\t\t\t\t`[edges] skipping mesh over triangle cap (${triangleCountOf(object.geometry)} > ${maxTriangles})`\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tdelete object.userData.edgesSkipped;\n\t\ttargets.push(object);\n\t});\n\treturn targets;\n}\n\nfunction attachOverlay(\n\tmesh: THREE.Mesh,\n\tentry: EdgeGeometryEntry,\n\tmaterials: MaterialPool,\n\tresolved: ResolvedOptions\n): LineSegments2 {\n\t// Distance fade needs the transparent pass; overlays over the segment cap stay opaque instead\n\t// of skipping outright — see EdgeOptions.maxSegments.\n\tconst fade = resolved.distanceFade && entry.segmentCount <= resolved.maxSegments;\n\tconst overlay = buildEdgeOverlay(\n\t\tmesh.geometry,\n\t\tentry,\n\t\tmaterials.for(mesh, fade),\n\t\tresolved.thresholdAngle,\n\t\tfade\n\t);\n\tmesh.add(overlay); // child → inherits transform, disposed with the parent subtree\n\treturn overlay;\n}\n\n/**\n * Walk an object subtree and attach an edge overlay to every `Mesh` found, returning the created\n * overlays (so callers can dispose them explicitly if they don't clear the whole subtree). Meshes\n * that already carry an overlay are skipped, so this is safe to call more than once.\n *\n * Skips the floor and the grid (they're aids, not content) and anything already tagged as an edge.\n *\n * Fully synchronous — extraction for every mesh runs on the calling thread. Interactive hosts with\n * potentially-large meshes should prefer {@link addEdgesAsync}, which offloads big extractions to\n * a worker.\n */\nexport function addEdges(root: THREE.Object3D, options: EdgeOptions = {}): LineSegments2[] {\n\tconst resolved = resolveOptions(options);\n\tconst materials = new MaterialPool(resolved);\n\tconst created: LineSegments2[] = [];\n\n\tfor (const mesh of collectTargets(root, resolved.maxTriangles)) {\n\t\tconst entry =\n\t\t\tcachedEntry(mesh.geometry, resolved.thresholdAngle) ??\n\t\t\tstoreEntry(\n\t\t\t\tmesh.geometry,\n\t\t\t\tresolved.thresholdAngle,\n\t\t\t\textractSegmentsSync(mesh.geometry, resolved.thresholdAngle)\n\t\t\t);\n\t\tcreated.push(attachOverlay(mesh, entry, materials, resolved));\n\t}\n\n\tmaterials.disposeUnused(created);\n\treturn created;\n}\n\n/**\n * Generation per root: {@link removeEdges} bumps it, and async attaches landing after a bump are\n * dropped — so \"toggle off while extracting\" can't resurrect overlays. Keyed on the root object,\n * which hosts keep stable across solves (the scene).\n */\nconst rootGenerations = new WeakMap<THREE.Object3D, number>();\n\nfunction generationOf(root: THREE.Object3D): number {\n\treturn rootGenerations.get(root) ?? 0;\n}\n\n/** Is `mesh` still reachable from `root`? Guards attaches racing scene clears. */\nfunction isConnected(mesh: THREE.Object3D, root: THREE.Object3D): boolean {\n\tfor (let node: THREE.Object3D | null = mesh; node; node = node.parent) {\n\t\tif (node === root) return true;\n\t}\n\treturn false;\n}\n\n/**\n * Like {@link addEdges}, but extraction for large meshes runs in a Worker so the main thread never\n * stalls. Small meshes (< ~25k triangles) still attach synchronously before this returns — only\n * heavy extractions arrive a beat later. Resolves with every overlay actually attached.\n *\n * Late results are dropped (never attached) when the mesh has left the root's subtree (scene was\n * cleared by a newer solve), the root's edges were removed via {@link removeEdges}, or another\n * apply already attached an overlay to that mesh.\n */\nexport async function addEdgesAsync(\n\troot: THREE.Object3D,\n\toptions: EdgeOptions = {}\n): Promise<LineSegments2[]> {\n\tconst resolved = resolveOptions(options);\n\tconst materials = new MaterialPool(resolved);\n\tconst generation = generationOf(root);\n\tconst created: LineSegments2[] = [];\n\n\tconst attaches = collectTargets(root, resolved.maxTriangles).map(async (mesh) => {\n\t\tlet entry = cachedEntry(mesh.geometry, resolved.thresholdAngle);\n\t\tif (!entry) {\n\t\t\tconst segments = await extractSegmentsAsync(mesh.geometry, resolved.thresholdAngle);\n\t\t\t// Things may have moved on while extracting — attach only if this apply is still wanted.\n\t\t\tif (generationOf(root) !== generation) return;\n\t\t\tif (!isConnected(mesh, root)) return;\n\t\t\tif (mesh.children.some((c) => c.userData?.kind === EDGE_USERDATA_KIND)) return;\n\t\t\tentry = cachedEntry(mesh.geometry, resolved.thresholdAngle);\n\t\t\tif (!entry) entry = storeEntry(mesh.geometry, resolved.thresholdAngle, segments);\n\t\t}\n\t\tcreated.push(attachOverlay(mesh, entry, materials, resolved));\n\t});\n\n\tawait Promise.all(attaches);\n\tmaterials.disposeUnused(created);\n\treturn created;\n}\n\n/**\n * Remove every edge overlay under `root`, disposing its geometry and material. The inverse of\n * {@link addEdges}/{@link addEdgesAsync}; together they make edges a live on/off toggle — this\n * also cancels any in-flight async attaches for `root`. Returns how many were removed.\n */\nexport function removeEdges(root: THREE.Object3D): number {\n\trootGenerations.set(root, generationOf(root) + 1);\n\n\tconst overlays: LineSegments2[] = [];\n\troot.traverse((object) => {\n\t\tif (object instanceof LineSegments2 && isEdgeOverlay(object)) overlays.push(object);\n\t});\n\n\t// One addEdges call shares one material across its overlays — dispose each distinct one once.\n\t// (If `root` covers only part of a call's overlays, survivors self-heal: three recompiles a\n\t// disposed-but-still-referenced material on its next use.)\n\tconst materials = new Set<LineMaterial>();\n\tfor (const overlay of overlays) {\n\t\treleaseEdgeGeometry(overlay); // geometry may be shared across overlays — refcounted dispose\n\t\tmaterials.add(overlay.material as LineMaterial);\n\t\t// Nothing to undo on the parent mesh: the depth bias lives entirely on the overlay's own\n\t\t// material, so surfaces keep whatever polygonOffset their look preset configured.\n\t\toverlay.removeFromParent();\n\t}\n\tmaterials.forEach((material) => material.dispose());\n\treturn overlays.length;\n}\n","import * as THREE from 'three';\nimport { Pass, FullScreenQuad } from 'three/addons/postprocessing/Pass.js';\n\n/**\n * Screen-space edge detection: draws crease/silhouette lines by finding depth and normal\n * discontinuities, as a fullscreen pass — cost is O(pixels), independent of triangle count.\n *\n * This is the fallback look for scenes too heavy for geometry edge overlays (see\n * docs/plans/4.edge-overlay-performance.md Phase 3): meshes over `EdgeOptions.maxTriangles` skip\n * extraction, and this pass approximates the technical-drawing read at constant cost. Trade-offs\n * vs geometry edges: uniform pixel width, one global color (no per-object tinting), view-dependent\n * response, and gentle creases below the normal threshold don't register.\n *\n * Works like GTAOPass internally: the scene is re-rendered with a `MeshNormalMaterial` override\n * into a normal target carrying a depth texture (a pattern this scene already tolerates for AO),\n * then a fullscreen shader Roberts-crosses depth (relative view-Z difference, so far scenes don't\n * dissolve into noise) and normals, and blends the edge color over the composed image.\n *\n * The render target is allocated lazily on first enabled render, so constructing the pass\n * disabled costs nothing but the material.\n */\nexport interface EdgeDetectionOptions {\n\t/** Edge line color. Default 0x222222 — matches the geometry overlays' default. */\n\tcolor?: THREE.ColorRepresentation;\n\t/** Edge blend strength 0–1. Default 1. */\n\topacity?: number;\n\t/**\n\t * Normal discontinuity threshold, in summed `1 - dot(n₁, n₂)` across the two diagonal pairs.\n\t * Lower catches gentler creases. Default 0.4 (≈ the 44° crease default of geometry edges).\n\t */\n\tnormalThreshold?: number;\n\t/** Relative view-depth discontinuity threshold. Default 0.02 (2% of the center depth). */\n\tdepthThreshold?: number;\n\t/** Sample offset in device px — line thickness. Default 1. */\n\tthickness?: number;\n}\n\nconst EDGE_SHADER = {\n\tuniforms: {\n\t\ttDiffuse: { value: null as THREE.Texture | null },\n\t\ttNormal: { value: null as THREE.Texture | null },\n\t\ttDepth: { value: null as THREE.Texture | null },\n\t\tuResolution: { value: new THREE.Vector2(1, 1) },\n\t\tuColor: { value: new THREE.Color(0x222222) },\n\t\tuOpacity: { value: 1 },\n\t\tuNormalThreshold: { value: 0.4 },\n\t\tuDepthThreshold: { value: 0.02 },\n\t\tuThickness: { value: 1 },\n\t\tuNear: { value: 0.1 },\n\t\tuFar: { value: 1000 },\n\t\tuPerspective: { value: 1 }\n\t},\n\tvertexShader: /* glsl */ `\n\t\tvarying vec2 vUv;\n\t\tvoid main() {\n\t\t\tvUv = uv;\n\t\t\tgl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n\t\t}\n\t`,\n\tfragmentShader: /* glsl */ `\n\t\tuniform sampler2D tDiffuse;\n\t\tuniform sampler2D tNormal;\n\t\tuniform sampler2D tDepth;\n\t\tuniform vec2 uResolution;\n\t\tuniform vec3 uColor;\n\t\tuniform float uOpacity;\n\t\tuniform float uNormalThreshold;\n\t\tuniform float uDepthThreshold;\n\t\tuniform float uThickness;\n\t\tuniform float uNear;\n\t\tuniform float uFar;\n\t\tuniform float uPerspective;\n\t\tvarying vec2 vUv;\n\n\t\tfloat viewZOf(const in float depth) {\n\t\t\tfloat perspective = (uNear * uFar) / ((uFar - uNear) * depth - uFar);\n\t\t\tfloat orthographic = -(depth * (uFar - uNear) + uNear);\n\t\t\treturn mix(orthographic, perspective, uPerspective);\n\t\t}\n\n\t\tvoid main() {\n\t\t\tvec4 color = texture2D(tDiffuse, vUv);\n\t\t\tvec2 texel = uThickness / uResolution;\n\n\t\t\t// Roberts cross over the two diagonal pairs.\n\t\t\tvec2 offsetA = vec2(texel.x, texel.y);\n\t\t\tvec2 offsetB = vec2(texel.x, -texel.y);\n\n\t\t\tfloat z0 = viewZOf(texture2D(tDepth, vUv + offsetA).x);\n\t\t\tfloat z1 = viewZOf(texture2D(tDepth, vUv - offsetA).x);\n\t\t\tfloat z2 = viewZOf(texture2D(tDepth, vUv + offsetB).x);\n\t\t\tfloat z3 = viewZOf(texture2D(tDepth, vUv - offsetB).x);\n\t\t\tfloat zCenter = viewZOf(texture2D(tDepth, vUv).x);\n\t\t\t// Relative difference: a constant threshold in absolute Z turns distant geometry into\n\t\t\t// noise (depth precision) and near geometry blind; normalizing by the center depth keeps\n\t\t\t// the response scale-invariant across the viewer's mm→m scenes.\n\t\t\tfloat depthDelta = (abs(z0 - z1) + abs(z2 - z3)) / max(abs(zCenter), 1e-6);\n\t\t\tfloat depthEdge = step(uDepthThreshold, depthDelta);\n\n\t\t\tvec3 n0 = texture2D(tNormal, vUv + offsetA).rgb * 2.0 - 1.0;\n\t\t\tvec3 n1 = texture2D(tNormal, vUv - offsetA).rgb * 2.0 - 1.0;\n\t\t\tvec3 n2 = texture2D(tNormal, vUv + offsetB).rgb * 2.0 - 1.0;\n\t\t\tvec3 n3 = texture2D(tNormal, vUv - offsetB).rgb * 2.0 - 1.0;\n\t\t\tfloat normalDelta = (1.0 - dot(n0, n1)) + (1.0 - dot(n2, n3));\n\t\t\tfloat normalEdge = step(uNormalThreshold, normalDelta);\n\n\t\t\tfloat edge = max(depthEdge, normalEdge) * uOpacity;\n\t\t\tgl_FragColor = vec4(mix(color.rgb, uColor, edge), color.a);\n\t\t}\n\t`\n};\n\nexport class EdgeDetectionPass extends Pass {\n\tcamera: THREE.Camera;\n\n\tprivate readonly scene: THREE.Scene;\n\tprivate readonly normalMaterial: THREE.MeshNormalMaterial;\n\tprivate readonly edgeMaterial: THREE.ShaderMaterial;\n\tprivate readonly fsQuad: FullScreenQuad;\n\tprivate normalTarget: THREE.WebGLRenderTarget | null = null;\n\tprivate width: number;\n\tprivate height: number;\n\n\tconstructor(\n\t\tscene: THREE.Scene,\n\t\tcamera: THREE.Camera,\n\t\twidth: number,\n\t\theight: number,\n\t\toptions: EdgeDetectionOptions = {}\n\t) {\n\t\tsuper();\n\t\tthis.scene = scene;\n\t\tthis.camera = camera;\n\t\tthis.width = Math.max(1, width);\n\t\tthis.height = Math.max(1, height);\n\n\t\tthis.normalMaterial = new THREE.MeshNormalMaterial();\n\t\tthis.normalMaterial.blending = THREE.NoBlending;\n\n\t\tthis.edgeMaterial = new THREE.ShaderMaterial({\n\t\t\tuniforms: THREE.UniformsUtils.clone(EDGE_SHADER.uniforms),\n\t\t\tvertexShader: EDGE_SHADER.vertexShader,\n\t\t\tfragmentShader: EDGE_SHADER.fragmentShader\n\t\t});\n\t\tconst uniforms = this.edgeMaterial.uniforms;\n\t\tuniforms.uColor.value = new THREE.Color(options.color ?? 0x222222);\n\t\tuniforms.uOpacity.value = options.opacity ?? 1;\n\t\tuniforms.uNormalThreshold.value = options.normalThreshold ?? 0.4;\n\t\tuniforms.uDepthThreshold.value = options.depthThreshold ?? 0.02;\n\t\tuniforms.uThickness.value = options.thickness ?? 1;\n\n\t\tthis.fsQuad = new FullScreenQuad(this.edgeMaterial);\n\t\tthis.needsSwap = true;\n\t}\n\n\tprivate acquireNormalTarget(): THREE.WebGLRenderTarget {\n\t\tif (!this.normalTarget) {\n\t\t\tconst depthTexture = new THREE.DepthTexture(this.width, this.height);\n\t\t\tthis.normalTarget = new THREE.WebGLRenderTarget(this.width, this.height, {\n\t\t\t\tminFilter: THREE.NearestFilter,\n\t\t\t\tmagFilter: THREE.NearestFilter,\n\t\t\t\tdepthTexture\n\t\t\t});\n\t\t}\n\t\treturn this.normalTarget;\n\t}\n\n\toverride setSize(width: number, height: number): void {\n\t\tthis.width = Math.max(1, width);\n\t\tthis.height = Math.max(1, height);\n\t\tthis.normalTarget?.setSize(this.width, this.height);\n\t}\n\n\toverride render(\n\t\trenderer: THREE.WebGLRenderer,\n\t\twriteBuffer: THREE.WebGLRenderTarget,\n\t\treadBuffer: THREE.WebGLRenderTarget\n\t): void {\n\t\tconst normalTarget = this.acquireNormalTarget();\n\n\t\t// --- Normals + depth prepass (override material, like GTAOPass's normal pass) ---\n\t\tconst previousTarget = renderer.getRenderTarget();\n\t\tconst previousAutoClear = renderer.autoClear;\n\t\tconst previousClearColor = renderer.getClearColor(new THREE.Color());\n\t\tconst previousClearAlpha = renderer.getClearAlpha();\n\t\tconst previousOverride = this.scene.overrideMaterial;\n\n\t\trenderer.setRenderTarget(normalTarget);\n\t\t// 0x7777ff ≈ packed +Z: background pixels get a uniform normal, so only depth silhouettes\n\t\t// (not normal noise) separate objects from empty space.\n\t\trenderer.setClearColor(0x7777ff, 1);\n\t\trenderer.autoClear = true;\n\t\tthis.scene.overrideMaterial = this.normalMaterial;\n\t\trenderer.render(this.scene, this.camera);\n\t\tthis.scene.overrideMaterial = previousOverride;\n\t\trenderer.setClearColor(previousClearColor, previousClearAlpha);\n\t\trenderer.autoClear = previousAutoClear;\n\n\t\t// --- Edge composite ---\n\t\tconst uniforms = this.edgeMaterial.uniforms;\n\t\tuniforms.tDiffuse.value = readBuffer.texture;\n\t\tuniforms.tNormal.value = normalTarget.texture;\n\t\tuniforms.tDepth.value = normalTarget.depthTexture;\n\t\tuniforms.uResolution.value.set(this.width, this.height);\n\t\tconst perspective = this.camera as Partial<THREE.PerspectiveCamera>;\n\t\tuniforms.uPerspective.value = perspective.isPerspectiveCamera ? 1 : 0;\n\t\tuniforms.uNear.value = (this.camera as THREE.PerspectiveCamera).near ?? 0.1;\n\t\tuniforms.uFar.value = (this.camera as THREE.PerspectiveCamera).far ?? 1000;\n\n\t\trenderer.setRenderTarget(this.renderToScreen ? null : writeBuffer);\n\t\tthis.fsQuad.render(renderer);\n\t\trenderer.setRenderTarget(previousTarget);\n\t}\n\n\toverride dispose(): void {\n\t\tthis.normalTarget?.dispose();\n\t\tthis.normalMaterial.dispose();\n\t\tthis.edgeMaterial.dispose();\n\t\tthis.fsQuad.dispose();\n\t}\n}\n","import * as THREE from 'three';\nimport { CSS2DRenderer, CSS2DObject } from 'three/addons/renderers/CSS2DRenderer.js';\n\n/**\n * An HTML label layer that tracks 3D positions, via three's {@link CSS2DRenderer}. Labels are real\n * DOM nodes (crisp text, CSS-stylable) positioned each frame to follow points in the scene — the\n * foundation for measurement readouts, dimension annotations, and point tags.\n *\n * The CSS2D renderer draws into its own absolutely-positioned DOM overlay stacked on top of the\n * WebGL canvas (pointer-events disabled so it never steals clicks from the viewer). The viewer owns\n * one of these; features like the measure tool add/remove labels through it.\n */\n\nexport interface LabelHandle {\n\t/** The CSS2DObject in the scene graph. */\n\treadonly object: CSS2DObject;\n\t/** Move the label to a new world position. */\n\tsetPosition(position: THREE.Vector3): void;\n\t/** Replace the label's text/HTML. */\n\tsetText(text: string): void;\n\t/** Remove the label from the scene and the DOM. */\n\tremove(): void;\n}\n\nexport interface LabelLayer {\n\t/** Create a label at a world position. `className` lets callers theme groups of labels. */\n\taddLabel(text: string, position: THREE.Vector3, className?: string): LabelHandle;\n\t/** Render the DOM overlay. Call each frame after the WebGL render, with the active camera. */\n\trender(scene: THREE.Scene, camera: THREE.Camera): void;\n\tsetSize(width: number, height: number): void;\n\tdispose(): void;\n}\n\n/**\n * @param container element to overlay labels onto — normally the canvas's parent, so the overlay and\n * canvas share a positioning context. The overlay is appended here and absolutely positioned.\n * @param scene labels are parented to a group added to this scene, so they render and follow the\n * camera without the caller wiring scene-graph parenting.\n */\nexport function createLabelLayer(container: HTMLElement, scene: THREE.Scene): LabelLayer {\n\tconst renderer = new CSS2DRenderer();\n\tconst dom = renderer.domElement;\n\tdom.style.position = 'absolute';\n\tdom.style.top = '0';\n\tdom.style.left = '0';\n\t// The overlay must never intercept viewer interaction. CSS2DRenderer sizes its root div to the\n\t// renderer size and stacks it above the canvas; without an explicit non-interactive, clipped box\n\t// it can cover the canvas and swallow orbit/clicks. Note the box is sized in PIXELS by\n\t// `setSize` (CSS2DRenderer overwrites width/height styles and bases its projection math on the\n\t// same values, so percentage sizing can't work here) — the host's resize handling must call\n\t// `setSize` whenever the container resizes, exactly as it does for the WebGL renderer.\n\tdom.style.overflow = 'hidden';\n\tdom.style.pointerEvents = 'none';\n\t// Stack above the canvas and any host overlays (e.g. blur/loading scrims) that share the\n\t// container's positioning context — without an explicit z-index the overlay sits at z-auto and\n\t// such scrims paint over the labels. Kept below typical menu/popover layers.\n\tdom.style.zIndex = '30';\n\t// The container is the canvas's positioning context; make sure it actually establishes one.\n\tif (getComputedStyle(container).position === 'static') {\n\t\tcontainer.style.position = 'relative';\n\t}\n\tcontainer.appendChild(dom);\n\n\tconst size = { width: container.clientWidth || 1, height: container.clientHeight || 1 };\n\trenderer.setSize(size.width, size.height);\n\n\t// Labels live under a dedicated group so they're easy to find/exclude and removed en masse on\n\t// dispose. Tagged so pick/fit logic ignores it.\n\tconst group = new THREE.Group();\n\tgroup.name = 'label-layer';\n\tgroup.userData.id = 'label-layer';\n\tscene.add(group);\n\n\tconst labels = new Set<CSS2DObject>();\n\n\tconst addLabel = (text: string, position: THREE.Vector3, className?: string): LabelHandle => {\n\t\tconst el = document.createElement('div');\n\t\tel.textContent = text;\n\t\tif (className) {\n\t\t\tel.className = className;\n\t\t} else {\n\t\t\t// Default styling that stays legible on any background (light or dark scene/page): a dark\n\t\t\t// translucent pill with light text. Callers wanting their own look pass a className, which\n\t\t\t// opts out of all of this. Kept inline so the layer needs no external stylesheet.\n\t\t\tObject.assign(el.style, {\n\t\t\t\tpadding: '2px 6px',\n\t\t\t\tborderRadius: '4px',\n\t\t\t\tbackground: 'rgba(20, 20, 20, 0.78)',\n\t\t\t\tcolor: '#fff',\n\t\t\t\tfont: '12px/1.3 system-ui, sans-serif',\n\t\t\t\t// `pre` so a multi-line readout (e.g. total + per-axis deltas) keeps its line breaks.\n\t\t\t\twhiteSpace: 'pre',\n\t\t\t\ttextAlign: 'center',\n\t\t\t\tuserSelect: 'none'\n\t\t\t} satisfies Partial<CSSStyleDeclaration>);\n\t\t}\n\t\t// Individual labels stay non-interactive by default (the overlay is too, but be explicit so a\n\t\t// caller that opts a label into pointer-events doesn't get surprised by inherited none).\n\t\tel.style.pointerEvents = 'none';\n\n\t\tconst object = new CSS2DObject(el);\n\t\tobject.position.copy(position);\n\t\tgroup.add(object);\n\t\tlabels.add(object);\n\n\t\treturn {\n\t\t\tobject,\n\t\t\tsetPosition: (p) => object.position.copy(p),\n\t\t\tsetText: (t) => {\n\t\t\t\tel.textContent = t;\n\t\t\t},\n\t\t\tremove: () => {\n\t\t\t\tobject.removeFromParent();\n\t\t\t\tel.remove();\n\t\t\t\tlabels.delete(object);\n\t\t\t}\n\t\t};\n\t};\n\n\treturn {\n\t\taddLabel,\n\t\trender: (scene, camera) => renderer.render(scene, camera),\n\t\tsetSize: (width, height) => renderer.setSize(width, height),\n\t\tdispose: () => {\n\t\t\tlabels.forEach((object) => {\n\t\t\t\tobject.removeFromParent();\n\t\t\t\t(object.element as HTMLElement).remove();\n\t\t\t});\n\t\t\tlabels.clear();\n\t\t\tgroup.removeFromParent();\n\t\t\tdom.remove();\n\t\t}\n\t};\n}\n","import * as THREE from 'three';\nimport { OrbitControls } from 'three/addons/controls/OrbitControls.js';\nimport { HDRLoader } from 'three/addons/loaders/HDRLoader.js';\n\nimport { getLogger } from '@/core';\nimport type { ThreeInitializerOptions, Look, LookPreset } from '../types';\nimport type { MaterialAppearanceOptions } from '../webdisplay/types';\nimport { createCameraController, type CameraController } from './camera-controller';\nimport { createGrid, type Grid } from './grid';\nimport { createViewGizmo, type ViewGizmo } from './view-gizmo';\nimport { EDGES_SKIPPED_TRIANGLE_CAP, addEdgesAsync, removeEdges } from './edges';\nimport { createNearPlaneFitter, type NearPlaneFitter } from './near-plane';\nimport { createRenderPipeline, type RenderPipeline } from './render-pipeline';\nimport { createLabelLayer, type LabelLayer } from './label-layer';\nimport { createMeasureTool, type MeasureTool } from './measure';\nimport { computeContentBounds } from './three-helpers';\nimport { environmentRotationFor, isoOffset, sunOffset, upToAxis } from './up-axis';\nimport { setTextureAnisotropy } from '../webdisplay/texture-cache';\n\n/** Rhino's convention, and the frame all geometry arrives in — see `coordinate-transform.ts`. */\nconst defaultUp = new THREE.Vector3(0, 0, 1);\n\n/** The look applied when the caller passes no `look` option. */\nconst DEFAULT_LOOK: Look = 'technical';\n\n/**\n * The ready-to-go looks, as concrete lighting/material dial values. Single source of truth: consumed\n * by `applyDefaults` to seed construction-time defaults AND by `setLook` to re-apply a look at\n * runtime, so the two paths can never drift. A look carries ONLY lighting/material — never edges or\n * grid (those are independent overlays). See {@link Look} for what each reads like.\n *\n * Every look ships with `ambientOcclusion: false`: GTAO is a heavy full-screen postprocessing path\n * that can dominate frame time, so it stays opt-in (via `render.ambientOcclusion` or the runtime\n * `setAmbientOcclusion(true)`) rather than costing every viewer 60fps by default.\n */\nexport const LOOK_PRESETS: Record<Look, LookPreset> = {\n\t// Soft, even product shot: ACES with generous, balanced fill (hemisphere + a little flat ambient)\n\t// so the whole object stays legible and shadows read open — the safe, neutral default. IBL and fill\n\t// are kept modest so their contributions don't triple-stack (env + hemisphere + ambient) and push\n\t// midtones toward white — ACES then desaturates that lift, which reads as \"washed out\". Distinct\n\t// from `showcase`: this fills the shadows in; showcase deliberately lets them fall off for drama.\n\tstudio: {\n\t\ttoneMapping: THREE.ACESFilmicToneMapping,\n\t\ttoneMappingExposure: 1,\n\t\tenvMapIntensity: 1.0,\n\t\tenvironmentIntensity: 1.0,\n\t\themisphereIntensity: 0.75,\n\t\tambientIntensity: 0.4,\n\t\tcullBackfaces: false,\n\t\tambientOcclusion: false\n\t},\n\t// Clean shaded CAD look: neutral tone mapping, IBL-led so the object keeps FORM. The old dial\n\t// (ambient 1 + IBL 0.5) was the classic PBR wash — a full flat ambient adds the same value to\n\t// every face regardless of orientation, flattening shading toward a milky grey, while the one\n\t// light that actually shapes the surface (the HDR env) was cut to half. Rebalanced per the\n\t// community rule \"let the env map carry the fill, keep flat ambient low\": IBL back up to near\n\t// full, a little direction-aware hemisphere fill to lift under-facing surfaces (what ambient was\n\t// really being used for), and flat ambient dropped to a thin floor so nothing goes pure black.\n\t// Still a flat, even, edge-friendly read — just with shape and a hint of material response back.\n\ttechnical: {\n\t\ttoneMapping: THREE.NeutralToneMapping,\n\t\ttoneMappingExposure: 1,\n\t\tenvMapIntensity: 0.9,\n\t\tenvironmentIntensity: 1,\n\t\themisphereIntensity: 0.35,\n\t\tambientIntensity: 0.25,\n\t\tcullBackfaces: false,\n\t\tambientOcclusion: false\n\t},\n\t// Dramatic hero shot: pushes exposure and reflective IBL for glossy pop, but deliberately pulls the\n\t// flat fill DOWN (low ambient, lean hemisphere) so light-to-shadow falloff stays strong and form\n\t// reads with contrast. Where `studio` fills the shadows in for even legibility, showcase lets them\n\t// fall off. Still trimmed below the old triple-stacked values so the punch doesn't tip into the\n\t// ACES wash — the drama comes from higher exposure + IBL against lower fill, not from stacking lift.\n\tshowcase: {\n\t\ttoneMapping: THREE.ACESFilmicToneMapping,\n\t\ttoneMappingExposure: 1.15,\n\t\tenvMapIntensity: 1.4,\n\t\tenvironmentIntensity: 1.25,\n\t\themisphereIntensity: 0.35,\n\t\tambientIntensity: 0.15,\n\t\tcullBackfaces: false,\n\t\tambientOcclusion: false\n\t}\n};\n\n/**\n * The material-parse options implied by a look — feed these into the batch parser's `material` option\n * so meshes are built to match it (backface culling, IBL strength). Kept out of the viewer's runtime\n * dials because they're baked at parse time, not toggleable in place.\n */\nexport function materialAppearanceForLook(look: Look): MaterialAppearanceOptions {\n\tconst preset = LOOK_PRESETS[look];\n\treturn {\n\t\tenvMapIntensity: preset.envMapIntensity,\n\t\tcullBackfaces: preset.cullBackfaces\n\t};\n}\n\n/**\n * Initializes a Three.js environment with scene, camera, renderer, and event handling.\n */\nexport const initThree = function (\n\tcanvas: HTMLCanvasElement,\n\toptions?: ThreeInitializerOptions\n): {\n\tscene: THREE.Scene;\n\tcamera: THREE.PerspectiveCamera;\n\tcontrols: OrbitControls;\n\trenderer: THREE.WebGLRenderer;\n\tcameraController: CameraController;\n\tgrid: Grid | null;\n\tgizmo: ViewGizmo | null;\n\t/** Two-click distance measurement tool. Null unless `measure.enabled`; `setEnabled(true)` to use. */\n\tmeasureTool: MeasureTool | null;\n\t/**\n\t * Attach edge overlays to the meshes under `root` (no-op unless `edges.enabled`). Call after\n\t * loading meshes via `updateScene`, since meshes arrive after init. Extraction for large meshes\n\t * runs off-thread — their overlays attach a beat later; meshes over `edges.maxTriangles` are\n\t * skipped and (by default) covered by the screen-space edge fallback instead.\n\t */\n\tapplyEdges: (root: THREE.Object3D) => void;\n\t/**\n\t * Remove edge overlays under `root` — the toggle-off counterpart of `applyEdges`. Prefer this\n\t * over calling `removeEdges` directly: it also cancels in-flight async attaches' fallout and\n\t * stands down the screen-space edge fallback if it was active.\n\t */\n\tclearEdges: (root: THREE.Object3D) => void;\n\t/**\n\t * Request a repaint from the on-demand render loop. Camera motion, resizes, pointer input, and\n\t * the built-in setters invalidate automatically; call this after mutating the scene externally\n\t * (e.g. `updateScene`, adding user geometry) so the change shows immediately rather than on the\n\t * next safety repaint. No-op (harmless) when `render.onDemand` is false.\n\t */\n\tinvalidate: () => void;\n\t/** Toggle ambient occlusion at runtime — builds or tears down the postprocessing pipeline. */\n\tsetAmbientOcclusion: (enabled: boolean) => void;\n\t/**\n\t * Apply a coherent look to the already-loaded scene: 'technical' (matte/CAD — edges, grid, low\n\t * IBL, neutral tone mapping) or 'rendered' (presentation — stronger IBL, ACES tone mapping, no\n\t * edges). Retunes viewer-owned dials only; per-material parse choices are set via the batch\n\t * parser's `material` option. Handy for comparing the two looks in a live viewer.\n\t */\n\t/**\n\t * Switch the viewer to a ready-to-go look at runtime ('studio' | 'technical' | 'showcase'). Retunes\n\t * lighting/material only (tone mapping, fill, IBL, AO) — never edges/grid. A straight preset apply:\n\t * overwrites any granular lighting dials you set earlier.\n\t */\n\tsetLook: (look: 'studio' | 'technical' | 'showcase') => void;\n\t/**\n\t * Retune the fill lights at runtime: the direction-aware hemisphere fill (sky/ground) and the flat\n\t * ambient. Raising `hemisphereIntensity` is the most effective way to lift shadowed / under-facing\n\t * surfaces a dark HDR leaves black. A positive `hemisphereIntensity` lazily creates the hemisphere\n\t * light if the viewer was built without one; `0` switches it off.\n\t */\n\tsetFillLights: (opts: {\n\t\themisphereIntensity?: number;\n\t\themisphereSkyColor?: THREE.Color | number;\n\t\themisphereGroundColor?: THREE.Color | number;\n\t\tambientIntensity?: number;\n\t}) => void;\n\t/**\n\t * Set the uniform multiplier on the HDR's image-based lighting (`scene.environmentIntensity`) at\n\t * runtime — normalizes brightness across HDRs of differing exposure so the scene isn't at the\n\t * mercy of whichever HDR is loaded. Applies immediately, even before the HDR finishes decoding.\n\t */\n\tsetEnvironmentIntensity: (intensity: number) => void;\n\t/** Set renderer tone-mapping exposure at runtime. Higher lifts shadows and overall brightness. */\n\tsetToneMappingExposure: (exposure: number) => void;\n\t/** Set GTAO strength at runtime (0–1). No-op when ambient occlusion isn't active. */\n\tsetAoIntensity: (intensity: number) => void;\n\t/**\n\t * The parse-time material options (backface culling, IBL strength) matching the active look — feed\n\t * into the batch parser's `material` option so freshly-loaded meshes are built to match it. See\n\t * `setLook`.\n\t */\n\tgetMaterialAppearance: () => MaterialAppearanceOptions;\n\t/**\n\t * Refit the sun's shadow frustum to the current scene content for crisp shadows. Call after\n\t * loading or replacing geometry (e.g. after `updateScene`). No-op when sunlight/shadows are off.\n\t */\n\tupdateShadowBounds: () => void;\n\t/**\n\t * Rescale the grid's cell spacing and fade radius to the current scene content, so parts of any\n\t * size get readable cells and a fade that reaches past the model. Call after loading or replacing\n\t * geometry (e.g. after `updateScene`). No-op when the grid is off or there's no content.\n\t */\n\tupdateGridScale: () => void;\n\tdispose: () => void;\n\tfitToView: () => void;\n\tclearSelection: () => void;\n\t/**\n\t * Add caller-owned geometry (lines, annotations, construction aids) to the scene. The object is\n\t * tagged `userData.source = 'user'` so it persists across `updateScene` solves instead of being\n\t * cleared with compute content. It is treated as normal content for fit-to-view framing.\n\t */\n\taddUserGeometry: (object: THREE.Object3D) => void;\n\t/** Remove a single user-added object and dispose its geometry/materials. */\n\tremoveUserGeometry: (object: THREE.Object3D) => void;\n\t/** Remove and dispose all user-added geometry (every object tagged `source === 'user'`). */\n\tclearUserGeometry: () => void;\n} {\n\tconst config = applyDefaults(options || {});\n\n\tconst sceneUp = config.environment?.sceneUp || defaultUp;\n\n\t// The configured pixel ratio is the single source of truth for every DPR consumer — renderer\n\t// setup, the per-frame resize check, and the AO pipeline. Resolving it once here means a\n\t// host-configured value (e.g. `pixelRatio: 1` for performance) is never silently overridden\n\t// after the first resize check. (applyDefaults always sets it; the fallback is type narrowing.)\n\tconst pixelRatio = config.render.pixelRatio ?? Math.min(window.devicePixelRatio, 2);\n\n\tconst scene = createScene(config);\n\tconst camera = createCamera(config, canvas);\n\t// Set the camera's up to the scene up BEFORE OrbitControls/the controller read it — OrbitControls\n\t// captures the orbit basis from camera.up at construction, and the controller derives its presets\n\t// and ortho camera from it. Without this, a Z-up scene would orbit and frame as if Y-up.\n\tcamera.up.copy(sceneUp);\n\tconst renderer = setupRenderer(canvas, config, pixelRatio);\n\t// Report the GPU's max anisotropy to the texture cache so color maps stay sharp at grazing angles.\n\t// One-time; retroactively upgrades any texture already decoded this session.\n\tsetTextureAnisotropy(renderer.capabilities.getMaxAnisotropy());\n\tconst controls = setupControls(camera, canvas, config);\n\n\t// Tracks whichever camera (perspective or orthographic) is live; the controller swaps it.\n\t// Render loop, resize, and raycasting all read through getActiveCamera so 2D/3D stays coherent.\n\tconst cameraController = createCameraController({\n\t\tscene,\n\t\tperspective: camera,\n\t\tcontrols,\n\t\tonActiveCameraChange: () => {},\n\t\tup: sceneUp\n\t});\n\tconst getActiveCamera = () => cameraController.getActiveCamera();\n\n\t// The HDR environment decodes asynchronously; if the viewer is disposed before it lands, the\n\t// load callback must drop (and dispose) the texture instead of attaching it to a swept scene.\n\tlet disposed = false;\n\tsetupEnvironment(scene, renderer, config, () => disposed);\n\t// Scene lights. The shadow-casting sun (null when sunlight or shadows are off) has its shadow\n\t// frustum fitted to the scene content below and again whenever the host calls updateShadowBounds\n\t// after a geometry change — keeping shadow-map texels packed onto the model for crisp shadows at\n\t// any scale. The ambient + optional hemisphere fill are retunable at runtime via the setters below.\n\tconst lights = setupLighting(scene, config);\n\tconst sunlight = lights.sun;\n\n\t/**\n\t * Refit the sun's shadow frustum to the current scene content. Call after loading or replacing\n\t * geometry (e.g. right after `updateScene`). No-op when there is no shadow-casting sun or no\n\t * content. Cheap: one bounds traversal, no per-frame cost.\n\t */\n\tconst updateShadowBounds = () => {\n\t\tif (sunlight) fitShadowToContent(sunlight, computeContentBounds(scene));\n\t};\n\n\tif (config.floor?.enabled) {\n\t\taddFloor(scene, config);\n\t}\n\t// Tagged by addFloor; grabbed here so the near-plane fitter can consult its live visibility.\n\tconst floorMesh = config.floor?.enabled\n\t\t? (scene.children.find((child) => child.userData.id === 'floor') ?? null)\n\t\t: null;\n\n\t// Optional CAD aids: an infinite fading grid and the corner nav-cube gizmo. Both opt-in.\n\tconst grid = config.grid.enabled\n\t\t? createGrid({\n\t\t\t\tcellSize: config.grid.cellSize,\n\t\t\t\tmajorEvery: config.grid.majorEvery,\n\t\t\t\tcellColor: config.grid.cellColor,\n\t\t\t\tmajorColor: config.grid.majorColor,\n\t\t\t\tfadeDistance: config.grid.fadeDistance,\n\t\t\t\tplane: config.grid.plane\n\t\t\t})\n\t\t: null;\n\tif (grid) scene.add(grid.object);\n\n\t/**\n\t * Rescale the grid's cell spacing and fade radius to the current scene content, so a part that is\n\t * a few units or a few thousand units wide both get sensibly-sized cells and a fade that reaches\n\t * past the model. Call after loading or replacing geometry (e.g. right after `updateScene`). No-op\n\t * when there's no grid or no content. Cheap: one bounds traversal, no per-frame cost.\n\t */\n\tconst updateGridScale = () => {\n\t\tif (grid) grid.fitToContent(computeContentBounds(scene));\n\t};\n\n\tconst gizmo = config.gizmo.enabled\n\t\t? createViewGizmo({ camera, domElement: canvas, controller: cameraController })\n\t\t: null;\n\n\t// Per-frame near-plane fitting: recovers depth precision when zoomed out (see near-plane.ts).\n\t// Ground-plane normals cap the fit where a ground aid (grid under the camera, floor) would\n\t// otherwise be clipped at grazing views.\n\t//\n\t// Resolved per frame, and only for aids actually VISIBLE: the grid is commonly built up-front so\n\t// hosts can toggle it, yet started hidden. Since this clamp is the camera's height above the\n\t// plane, letting a hidden grid contribute drives near→0 at grazing views and craters depth\n\t// precision (ULP ∝ 1/near) — which shows up as hidden edges punching through solid geometry.\n\t// applyDefaults always fills `plane` (from the scene up axis); the fallback derives from the same\n\t// source rather than assuming 'z', so the two can't disagree in a non-Z-up scene.\n\tconst gridPlane = config.grid.plane ?? upToAxis(sceneUp);\n\tconst gridNormal = new THREE.Vector3(\n\t\tgridPlane === 'x' ? 1 : 0,\n\t\tgridPlane === 'y' ? 1 : 0,\n\t\tgridPlane === 'z' ? 1 : 0\n\t);\n\tconst floorNormal = sceneUp.clone().normalize();\n\tconst groundNormals = (): THREE.Vector3[] => {\n\t\tconst normals: THREE.Vector3[] = [];\n\t\tif (grid?.object.visible) normals.push(gridNormal);\n\t\tif (config.floor.enabled && floorMesh?.visible) normals.push(floorNormal);\n\t\treturn normals;\n\t};\n\tconst nearFitter: NearPlaneFitter | null = config.camera.dynamicNear\n\t\t? createNearPlaneFitter({ camera, scene, groundNormals })\n\t\t: null;\n\n\t// HTML label overlay (CSS2D) and the measurement tool built on it. Both opt-in; the label layer\n\t// is only created when something needs it (currently the measure tool).\n\tconst labelContainer = canvas.parentElement ?? canvas;\n\tconst labelLayer: LabelLayer | null = config.measure.enabled\n\t\t? createLabelLayer(labelContainer, scene)\n\t\t: null;\n\tconst measureTool: MeasureTool | null =\n\t\tconfig.measure.enabled && labelLayer\n\t\t\t? createMeasureTool({\n\t\t\t\t\tcanvas,\n\t\t\t\t\tscene,\n\t\t\t\t\tgetActiveCamera,\n\t\t\t\t\tlabelLayer,\n\t\t\t\t\toptions: {\n\t\t\t\t\t\tsnapPixels: config.measure.snapPixels,\n\t\t\t\t\t\tcolor: config.measure.color,\n\t\t\t\t\t\tlabelClassName: config.measure.labelClassName,\n\t\t\t\t\t\tdisplayUnit: config.measure.displayUnit,\n\t\t\t\t\t\tformat: config.measure.format\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t: null;\n\n\tconst eventHandlers =\n\t\tconfig.events.enableEventHandlers !== false\n\t\t\t? setupEventHandlers(canvas, scene, cameraController, config)\n\t\t\t: { dispose: () => {}, fitToView: () => {}, clearSelection: () => {} };\n\n\t// A drag to orbit/pan ends with a `click` on mouseup. Without guarding, that release click would\n\t// be taken as a measurement point (placing a stray point or clearing a finished measurement when\n\t// the user only meant to rotate). Record where the press started and treat the release as a click\n\t// only if the pointer barely moved — a real click, not a drag.\n\tconst DRAG_SLOP_PX = 5;\n\tlet pressX = 0;\n\tlet pressY = 0;\n\tconst handlePointerDown = (event: MouseEvent) => {\n\t\tpressX = event.clientX;\n\t\tpressY = event.clientY;\n\t};\n\tconst wasDrag = (event: MouseEvent) =>\n\t\tMath.hypot(event.clientX - pressX, event.clientY - pressY) > DRAG_SLOP_PX;\n\n\t// Capture-phase interceptors that pre-empt scene selection. Order: an active measurement claims\n\t// the click first, then the gizmo. stopImmediatePropagation keeps the selection handler from\n\t// also firing. (Both run in capture so they see the event before the bubble-phase selection.)\n\tconst handleToolClick = (event: MouseEvent) => {\n\t\tif (wasDrag(event)) return; // an orbit/pan release, not a measurement click — leave it alone\n\t\tif (measureTool?.handleClick(event)) {\n\t\t\tevent.stopImmediatePropagation();\n\t\t\treturn;\n\t\t}\n\t\tif (gizmo?.handleClick(event)) {\n\t\t\tevent.stopImmediatePropagation();\n\t\t}\n\t};\n\tif (gizmo || measureTool) {\n\t\tcanvas.addEventListener('mousedown', handlePointerDown, { capture: true });\n\t\tcanvas.addEventListener('click', handleToolClick, { capture: true });\n\t}\n\t// Forward movement to the measure tool so it can preview the snap point under the cursor. Passive:\n\t// it only reads, never consumes, so it never interferes with orbit/pan.\n\tconst handleToolMove = (event: MouseEvent) => measureTool?.handleMove(event);\n\tif (measureTool) {\n\t\tcanvas.addEventListener('mousemove', handleToolMove, { passive: true });\n\t}\n\n\t// Repaint request for the on-demand render loop (audit P4). Forward-declared so setters defined\n\t// before the loop exists can call it; rebound to the loop's real invalidate once it's created.\n\tlet requestRender: () => void = () => {};\n\n\t// Edge overlays: bind the configured options into a closure the consumer calls after loading\n\t// meshes. Always applies when called explicitly (the `edges.enabled` flag governs whether the\n\t// host *intends* edges, but an explicit call should never be silently ignored).\n\t// Async path: extraction for large meshes runs in a worker, so a heavy solve never stalls the\n\t// main thread — their overlays pop in a beat later; small meshes still attach synchronously.\n\t// Cancellation (scene cleared by the next solve, clearEdges toggles) is handled inside.\n\t// Once attached, meshes skipped for exceeding the triangle cap switch the screen-space edge\n\t// fallback on (and a later solve without such meshes switches it back off).\n\tconst applyEdges = (root: THREE.Object3D) => {\n\t\tvoid addEdgesAsync(root, {\n\t\t\tcolor: config.edges.color, // undefined → derive from each mesh's surface color\n\t\t\tdarken: config.edges.darken,\n\t\t\twidth: config.edges.width,\n\t\t\tthresholdAngle: config.edges.thresholdAngle,\n\t\t\tdistanceFade: config.edges.distanceFade,\n\t\t\tmaxTriangles: config.edges.maxTriangles,\n\t\t\tmaxSegments: config.edges.maxSegments\n\t\t}).then(() => {\n\t\t\tupdateEdgeFallback(root);\n\t\t\trequestRender(); // overlays may have attached after the solve's own repaint\n\t\t});\n\t};\n\n\t/** Turn the screen-space fallback on/off to match whether capped-out meshes are present. */\n\tconst updateEdgeFallback = (root: THREE.Object3D) => {\n\t\tif (config.edges.screenSpaceFallback === false) return;\n\t\tlet hasSkippedMeshes = false;\n\t\troot.traverse((object) => {\n\t\t\tif (object.userData?.edgesSkipped === EDGES_SKIPPED_TRIANGLE_CAP) hasSkippedMeshes = true;\n\t\t});\n\t\tif (hasSkippedMeshes !== edgeFallbackActive) {\n\t\t\tedgeFallbackActive = hasSkippedMeshes;\n\t\t\tsyncPipeline();\n\t\t}\n\t};\n\n\t// The inverse of applyEdges: removes overlays (cancelling in-flight attaches) and stands down\n\t// the screen-space fallback. Hosts toggling edges off should call this rather than bare\n\t// removeEdges, or the fallback pass would keep drawing lines for capped meshes.\n\tconst clearEdges = (root: THREE.Object3D) => {\n\t\tremoveEdges(root);\n\t\tif (edgeFallbackActive) {\n\t\t\tedgeFallbackActive = false;\n\t\t\tsyncPipeline();\n\t\t}\n\t\trequestRender();\n\t};\n\n\tconst parent = canvas.parentElement;\n\tconst getCanvasSize = () =>\n\t\tparent\n\t\t\t? { width: parent.clientWidth, height: parent.clientHeight }\n\t\t\t: { width: window.innerWidth, height: window.innerHeight };\n\n\t// Optional postprocessing pipeline (AO and/or the screen-space edge fallback). Held in a mutable\n\t// so it can be toggled at runtime; the loop reads it through getRenderPipeline each frame. When\n\t// null, the loop uses the plain renderer.render path. Retargeted to the active camera every frame.\n\tlet renderPipeline: RenderPipeline | null = null;\n\tlet aoEnabled = !!config.render.ambientOcclusion;\n\t// True while meshes over the edge triangle cap are in the scene and the config wants the\n\t// screen-space approximation for them (see EdgesConfig.screenSpaceFallback).\n\tlet edgeFallbackActive = false;\n\tlet builtWithAo = false;\n\n\tconst buildPipeline = (withAo: boolean): RenderPipeline => {\n\t\tconst { width, height } = getCanvasSize();\n\t\tconst pipeline = createRenderPipeline(\n\t\t\trenderer,\n\t\t\tscene,\n\t\t\tgetActiveCamera(),\n\t\t\tMath.max(1, width),\n\t\t\tMath.max(1, height),\n\t\t\t{\n\t\t\t\ttoneMapping: config.render.toneMapping ?? THREE.NeutralToneMapping,\n\t\t\t\ttoneMappingExposure: config.render.toneMappingExposure ?? 1,\n\t\t\t\tambientOcclusion: withAo,\n\t\t\t\taoIntensity: config.render.aoIntensity,\n\t\t\t\taoPixelRatio: config.render.aoPixelRatio,\n\t\t\t\t// Constructed disabled (cheap until toggled); syncPipeline flips it via setEdgeDetection.\n\t\t\t\tedgeDetection: false\n\t\t\t}\n\t\t);\n\t\tpipeline.setSize(Math.max(1, width), Math.max(1, height), pixelRatio);\n\t\treturn pipeline;\n\t};\n\n\t/** Reconcile the pipeline with what's wanted: AO presence is baked at construction, edges toggle live. */\n\tconst syncPipeline = () => {\n\t\tconst wantPipeline = aoEnabled || edgeFallbackActive;\n\t\tif (!wantPipeline) {\n\t\t\trenderPipeline?.dispose();\n\t\t\trenderPipeline = null;\n\t\t\trequestRender();\n\t\t\treturn;\n\t\t}\n\t\tif (!renderPipeline || builtWithAo !== aoEnabled) {\n\t\t\trenderPipeline?.dispose();\n\t\t\trenderPipeline = buildPipeline(aoEnabled);\n\t\t\tbuiltWithAo = aoEnabled;\n\t\t}\n\t\trenderPipeline.setEdgeDetection(edgeFallbackActive);\n\t\trequestRender();\n\t};\n\n\t/** Dispose and rebuild the pipeline (if one is wanted) so construction-time options re-apply. */\n\tconst rebuildPipeline = () => {\n\t\trenderPipeline?.dispose();\n\t\trenderPipeline = null;\n\t\tsyncPipeline();\n\t};\n\n\tconst setAmbientOcclusion = (enabled: boolean) => {\n\t\taoEnabled = enabled;\n\t\tsyncPipeline();\n\t};\n\n\tsyncPipeline();\n\n\t/**\n\t * Retune the fill lights at runtime — the direction-aware hemisphere fill and the flat ambient.\n\t * Raising the hemisphere intensity is the most effective way to lift shadowed/under-facing\n\t * surfaces that a dark HDR leaves black, without washing the whole scene flat the way ambient does.\n\t * Pass `hemisphereIntensity: 0` to switch the fill off; a positive value creates the light lazily\n\t * if the viewer was built without one.\n\t */\n\tconst setFillLights = (opts: {\n\t\themisphereIntensity?: number;\n\t\themisphereSkyColor?: THREE.Color | number;\n\t\themisphereGroundColor?: THREE.Color | number;\n\t\tambientIntensity?: number;\n\t}) => {\n\t\tif (opts.ambientIntensity !== undefined) {\n\t\t\tlights.ambient.intensity = opts.ambientIntensity;\n\t\t}\n\t\tif (\n\t\t\topts.hemisphereIntensity !== undefined &&\n\t\t\t!lights.hemisphere &&\n\t\t\topts.hemisphereIntensity > 0\n\t\t) {\n\t\t\t// Built without a hemisphere light — create one on first positive intensity so hosts can\n\t\t\t// enable the fill purely at runtime.\n\t\t\tlights.hemisphere = new THREE.HemisphereLight(\n\t\t\t\topts.hemisphereSkyColor ?? config.lighting.hemisphereSkyColor,\n\t\t\t\topts.hemisphereGroundColor ?? config.lighting.hemisphereGroundColor,\n\t\t\t\topts.hemisphereIntensity\n\t\t\t);\n\t\t\tlights.hemisphere.position.copy(config.environment.sceneUp ?? defaultUp);\n\t\t\tscene.add(lights.hemisphere);\n\t\t}\n\t\tif (lights.hemisphere) {\n\t\t\tif (opts.hemisphereIntensity !== undefined)\n\t\t\t\tlights.hemisphere.intensity = opts.hemisphereIntensity;\n\t\t\tif (opts.hemisphereSkyColor !== undefined)\n\t\t\t\tlights.hemisphere.color.set(opts.hemisphereSkyColor);\n\t\t\tif (opts.hemisphereGroundColor !== undefined)\n\t\t\t\tlights.hemisphere.groundColor.set(opts.hemisphereGroundColor);\n\t\t}\n\t\trequestRender();\n\t};\n\n\t/**\n\t * Set the uniform multiplier on the HDR's image-based lighting (`scene.environmentIntensity`).\n\t * Normalizes brightness across HDRs of differing exposure — lift a dim HDR or tame a bright one —\n\t * so the scene isn't at the mercy of whichever HDR is loaded. Applies immediately, even before the\n\t * HDR has finished decoding.\n\t */\n\tconst setEnvironmentIntensity = (intensity: number) => {\n\t\tconfig.environment.environmentIntensity = intensity;\n\t\tscene.environmentIntensity = intensity;\n\t\trequestRender();\n\t};\n\n\t/** Set renderer tone-mapping exposure at runtime. Higher lifts shadows and overall brightness. */\n\tconst setToneMappingExposure = (exposure: number) => {\n\t\tconfig.render.toneMappingExposure = exposure;\n\t\trenderer.toneMappingExposure = exposure;\n\t\t// When the composer path is active, tone mapping is applied by its OutputPass — rebuild so it\n\t\t// adopts the new exposure.\n\t\tif (renderPipeline) rebuildPipeline();\n\t};\n\n\t/** Set GTAO strength at runtime (0 = off-looking, 1 = full). No-op when AO isn't active. */\n\tconst setAoIntensity = (intensity: number) => {\n\t\tconfig.render.aoIntensity = intensity;\n\t\tif (renderPipeline) rebuildPipeline();\n\t};\n\n\t/**\n\t * Apply a ready-to-go look to the *already-built* scene at runtime — a quick way to switch looks in\n\t * a live viewer. It retunes only LIGHTING/MATERIAL: tone mapping/exposure, hemisphere fill +\n\t * ambient, HDR environment intensity, AO on/off, and `envMapIntensity` on every compute material\n\t * currently in the scene. It deliberately does NOT touch edges or grid (those are independent\n\t * overlays — toggle them via `grid.setVisible()` / `applyEdges`). It does not rebuild geometry, so\n\t * parse-time material choices (backface culling, vertex-color decode) are unaffected — set those via\n\t * the batch parser's `material` option (see `getMaterialAppearance`).\n\t *\n\t * Note: this is a straight preset apply. Any dial you set earlier via a granular setter\n\t * (`setToneMappingExposure`, `setFillLights`, …) is overwritten to the new look's value.\n\t */\n\tconst setLook = (look: Look) => {\n\t\tconst preset = LOOK_PRESETS[look];\n\t\tactiveLook = look;\n\n\t\t// Tone mapping lives on the renderer (plain path) and is mirrored into the composer's OutputPass\n\t\t// when AO is active. Rebuild the pipeline so the composer picks up the new tone mapping.\n\t\trenderer.toneMapping = preset.toneMapping;\n\t\trenderer.toneMappingExposure = preset.toneMappingExposure;\n\t\tconfig.render.toneMapping = preset.toneMapping;\n\t\tconfig.render.toneMappingExposure = preset.toneMappingExposure;\n\n\t\t// Fill lighting + HDR normalization: studio/showcase add hemisphere fill and lift the environment\n\t\t// so shadowed surfaces read well regardless of the HDR; technical zeroes the fill back to a flat\n\t\t// CAD look. Applied through the same setters a host would call.\n\t\tsetFillLights({\n\t\t\themisphereIntensity: preset.hemisphereIntensity,\n\t\t\tambientIntensity: preset.ambientIntensity\n\t\t});\n\t\tsetEnvironmentIntensity(preset.environmentIntensity);\n\n\t\t// Rebuild (if a pipeline is active) so the composer's OutputPass adopts the new tone mapping,\n\t\t// honoring the look's AO choice.\n\t\taoEnabled = preset.ambientOcclusion;\n\t\tif (renderPipeline) rebuildPipeline();\n\t\telse syncPipeline();\n\n\t\t// Retune IBL reflection strength on every compute mesh material in the scene.\n\t\tscene.traverse((object) => {\n\t\t\tif (object.userData.source !== 'compute') return;\n\t\t\tconst mesh = object as Partial<THREE.Mesh> & THREE.Object3D;\n\t\t\tconst materials = Array.isArray(mesh.material)\n\t\t\t\t? mesh.material\n\t\t\t\t: mesh.material\n\t\t\t\t\t? [mesh.material]\n\t\t\t\t\t: [];\n\t\t\tfor (const material of materials) {\n\t\t\t\tif ('envMapIntensity' in material) {\n\t\t\t\t\t(material as THREE.MeshStandardMaterial).envMapIntensity = preset.envMapIntensity;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\trequestRender();\n\t};\n\n\t// The look currently applied. Always a real look (the default is 'studio'), seeded from the same\n\t// resolved value as the construction defaults. Drives `getMaterialAppearance()`.\n\tlet activeLook: Look = config.look;\n\n\t/**\n\t * The parse-time material options (backface culling, IBL strength) that match the active look —\n\t * pass into the batch parser's `material` option so newly-loaded meshes are built to match it.\n\t */\n\tconst getMaterialAppearance = (): MaterialAppearanceOptions =>\n\t\tmaterialAppearanceForLook(activeLook);\n\n\t// Resize checked every frame so buffer resize and render happen in the same frame,\n\t// preventing visible blank frames on resize\n\tconst {\n\t\tanimate,\n\t\tdispose: disposeAnimation,\n\t\tinvalidate\n\t} = createAnimationLoop(\n\t\trenderer,\n\t\tscene,\n\t\tcamera,\n\t\tgetActiveCamera,\n\t\tcameraController,\n\t\tcontrols,\n\t\tgetCanvasSize,\n\t\tpixelRatio,\n\t\tconfig.events.onFrame,\n\t\tgrid,\n\t\tgizmo,\n\t\t() => renderPipeline,\n\t\tlabelLayer,\n\t\tnearFitter,\n\t\tconfig.render.onDemand ?? true\n\t);\n\trequestRender = invalidate;\n\tanimate();\n\n\tscene.up.set(sceneUp.x, sceneUp.y, sceneUp.z);\n\n\t// Initial fit so any geometry already present at construction casts crisp shadows and the grid is\n\t// scaled to it. Hosts that add geometry later (via updateScene) should call updateShadowBounds and\n\t// updateGridScale again afterwards.\n\tupdateShadowBounds();\n\tupdateGridScale();\n\n\t// Dispose one object's renderable resources (geometry + materials + their textures), recursing\n\t// into children so Groups of lines/points clean up fully.\n\tconst disposeObjectTree = (root: THREE.Object3D) => {\n\t\troot.traverse((object) => {\n\t\t\tconst renderable = object as Partial<THREE.Mesh> & THREE.Object3D;\n\t\t\tif (!renderable.geometry && !renderable.material) return;\n\t\t\trenderable.geometry?.dispose();\n\t\t\tif (Array.isArray(renderable.material)) {\n\t\t\t\trenderable.material.forEach(disposeMaterialWithTextures);\n\t\t\t} else if (renderable.material) {\n\t\t\t\tdisposeMaterialWithTextures(renderable.material);\n\t\t\t}\n\t\t});\n\t};\n\n\tconst addUserGeometry = (object: THREE.Object3D) => {\n\t\tobject.userData.source = 'user';\n\t\tscene.add(object);\n\t};\n\n\tconst removeUserGeometry = (object: THREE.Object3D) => {\n\t\tobject.removeFromParent();\n\t\tdisposeObjectTree(object);\n\t};\n\n\tconst clearUserGeometry = () => {\n\t\t// Snapshot first — removeFromParent mutates scene.children during iteration.\n\t\tconst userObjects = scene.children.filter((child) => child.userData.source === 'user');\n\t\tuserObjects.forEach((object) => {\n\t\t\tobject.removeFromParent();\n\t\t\tdisposeObjectTree(object);\n\t\t});\n\t};\n\n\tconst dispose = () => {\n\t\t// Idempotent: a second call would re-run forceContextLoss() on an already-lost\n\t\t// context, throwing \"INVALID_OPERATION: loseContext: context already lost\".\n\t\t// Double-dispose happens naturally (React StrictMode effect double-invoke, hosts\n\t\t// that unmount twice), so guard on the flag we already track.\n\t\tif (disposed) return;\n\t\tdisposed = true;\n\t\tdisposeAnimation();\n\t\teventHandlers.dispose();\n\t\tif (gizmo || measureTool) {\n\t\t\tcanvas.removeEventListener('mousedown', handlePointerDown, { capture: true });\n\t\t\tcanvas.removeEventListener('click', handleToolClick, { capture: true });\n\t\t}\n\t\tif (measureTool) {\n\t\t\tcanvas.removeEventListener('mousemove', handleToolMove);\n\t\t}\n\t\tmeasureTool?.dispose();\n\t\tlabelLayer?.dispose();\n\t\tgizmo?.dispose();\n\t\tgrid?.dispose();\n\t\trenderPipeline?.dispose();\n\t\t// Stop any in-flight camera tween — its rAF ticks would otherwise keep touching the disposed\n\t\t// controls for up to the tween duration after teardown.\n\t\tcameraController.dispose();\n\t\tcontrols.dispose();\n\t\trenderer.dispose();\n\t\t// Free the GL context itself, not just its objects — browsers cap live WebGL contexts\n\t\t// (~16) and won't otherwise reclaim this one until GC, which can lag across rapid\n\t\t// mount/unmount cycles (e.g. navigating between definitions) and hit that cap.\n\t\trenderer.forceContextLoss();\n\n\t\tscene.traverse((object) => {\n\t\t\t// Dispose any renderable (mesh, line, points), not just meshes.\n\t\t\tconst renderable = object as Partial<THREE.Mesh> & THREE.Object3D;\n\t\t\tif (!renderable.geometry && !renderable.material) return;\n\n\t\t\trenderable.geometry?.dispose();\n\t\t\tif (Array.isArray(renderable.material)) {\n\t\t\t\trenderable.material.forEach(disposeMaterialWithTextures);\n\t\t\t} else if (renderable.material) {\n\t\t\t\tdisposeMaterialWithTextures(renderable.material);\n\t\t\t}\n\t\t});\n\n\t\t// Scene-level textures the traversal above can't reach.\n\t\tscene.environment?.dispose();\n\t\tif (scene.background instanceof THREE.Texture) {\n\t\t\tscene.background.dispose();\n\t\t}\n\t};\n\n\treturn {\n\t\tscene,\n\t\tcamera,\n\t\tcontrols,\n\t\trenderer,\n\t\tcameraController,\n\t\tgrid,\n\t\tgizmo,\n\t\tmeasureTool,\n\t\tapplyEdges,\n\t\tclearEdges,\n\t\tinvalidate,\n\t\tsetAmbientOcclusion,\n\t\tsetLook,\n\t\tsetFillLights,\n\t\tsetEnvironmentIntensity,\n\t\tsetToneMappingExposure,\n\t\tsetAoIntensity,\n\t\tgetMaterialAppearance,\n\t\tupdateShadowBounds,\n\t\tupdateGridScale,\n\t\tdispose,\n\t\tfitToView: eventHandlers.fitToView,\n\t\tclearSelection: eventHandlers.clearSelection,\n\t\taddUserGeometry,\n\t\tremoveUserGeometry,\n\t\tclearUserGeometry\n\t};\n};\n\n// Exported for unit testing the option-precedence logic (initThree itself needs a real WebGL canvas).\nexport function applyDefaults(options: ThreeInitializerOptions): Required<ThreeInitializerOptions> {\n\tconst scale = options.sceneScale || 'm';\n\n\t// All Rhino geometry is normalized to METERS (1 unit = 1 meter), sceneScale just changes the viewing perspective\n\tconst scaleDefaults = {\n\t\tmm: {\n\t\t\tcameraDistance: 20,\n\t\t\tnear: 0.1,\n\t\t\tfar: 2000,\n\t\t\tfloorSize: 100,\n\t\t\tlightDistance: 10,\n\t\t\tlightHeight: 20,\n\t\t\tminDistance: 0.1,\n\t\t\tshadowSize: 100,\n\t\t\tscaleFactor: 1000\n\t\t},\n\t\tcm: {\n\t\t\tcameraDistance: 20,\n\t\t\tnear: 0.1,\n\t\t\tfar: 2000,\n\t\t\tfloorSize: 100,\n\t\t\tlightDistance: 25,\n\t\t\tlightHeight: 50,\n\t\t\tminDistance: 0.1,\n\t\t\tshadowSize: 100,\n\t\t\tscaleFactor: 100\n\t\t},\n\t\tm: {\n\t\t\tcameraDistance: 10,\n\t\t\tnear: 0.01,\n\t\t\tfar: 2000,\n\t\t\tfloorSize: 50,\n\t\t\tlightDistance: 25,\n\t\t\tlightHeight: 50,\n\t\t\tminDistance: 0.001,\n\t\t\tshadowSize: 100,\n\t\t\tscaleFactor: 1\n\t\t},\n\t\tinches: {\n\t\t\tcameraDistance: 15,\n\t\t\tnear: 0.1,\n\t\t\tfar: 2000,\n\t\t\tfloorSize: 80,\n\t\t\tlightDistance: 20,\n\t\t\tlightHeight: 40,\n\t\t\tminDistance: 0.1,\n\t\t\tshadowSize: 80,\n\t\t\tscaleFactor: 39.37\n\t\t},\n\t\tfeet: {\n\t\t\tcameraDistance: 8,\n\t\t\tnear: 0.1,\n\t\t\tfar: 2000,\n\t\t\tfloorSize: 40,\n\t\t\tlightDistance: 15,\n\t\t\tlightHeight: 30,\n\t\t\tminDistance: 0.1,\n\t\t\tshadowSize: 60,\n\t\t\tscaleFactor: 3.28084\n\t\t}\n\t};\n\n\tconst defaults = scaleDefaults[scale];\n\n\t// The chosen look seeds the lighting/material defaults (tone mapping, AO, IBL, fill). It sits BELOW\n\t// explicit per-field options (those still win) and ABOVE the plain per-field defaults — so it only\n\t// fills what the caller left unspecified. Always a real preset: the default IS a look ('studio'),\n\t// so there's no \"no look\" state to represent. A look never touches edges/grid — those resolve from\n\t// their own configs below.\n\tconst look = options.look ?? DEFAULT_LOOK;\n\tconst preset = LOOK_PRESETS[look];\n\n\treturn {\n\t\tsceneScale: scale,\n\t\tlook,\n\t\tcamera: {\n\t\t\t// Default 3/4 iso: behind-left and ABOVE the model. Derived from the scene up axis rather\n\t\t\t// than a literal Z-up vector, so a Y-up scene gets an overhead iso instead of a\n\t\t\t// below-horizon view.\n\t\t\t// `cameraDistance` was historically a PER-COMPONENT magnitude on a (-d, -d, d) vector, so the\n\t\t\t// effective orbit radius is d*sqrt(3). Preserved exactly so this change reorients the default\n\t\t\t// view without also changing how zoomed-in every scene starts.\n\t\t\tposition:\n\t\t\t\toptions.camera?.position ||\n\t\t\t\tisoOffset(\n\t\t\t\t\toptions.environment?.sceneUp ?? defaultUp,\n\t\t\t\t\tdefaults.cameraDistance * Math.sqrt(3)\n\t\t\t\t),\n\t\t\tfov: options.camera?.fov || 20,\n\t\t\tnear: options.camera?.near || defaults.near,\n\t\t\tfar: options.camera?.far || defaults.far,\n\t\t\ttarget: options.camera?.target || new THREE.Vector3(0, 0, 0),\n\t\t\tdynamicNear: options.camera?.dynamicNear ?? true\n\t\t},\n\t\tlighting: {\n\t\t\tenableSunlight: options.lighting?.enableSunlight ?? true,\n\t\t\tsunlightIntensity: options.lighting?.sunlightIntensity ?? 1,\n\t\t\t// Sun overhead and offset to one side, expressed in the scene basis so it stays overhead in\n\t\t\t// any up convention (a hardcoded +Z height made the sun near-horizontal in a Y-up scene).\n\t\t\tsunlightPosition:\n\t\t\t\toptions.lighting?.sunlightPosition ||\n\t\t\t\tsunOffset(\n\t\t\t\t\toptions.environment?.sceneUp ?? defaultUp,\n\t\t\t\t\tdefaults.lightDistance,\n\t\t\t\t\tdefaults.lightHeight\n\t\t\t\t),\n\t\t\tambientLightColor: options.lighting?.ambientLightColor || new THREE.Color(0x404040),\n\t\t\t// The look sets ambient low across the board — the hemisphere fill + env carry the lift, so\n\t\t\t// flat ambient is only a thin floor keeping shadows off pure black. Explicit option still wins.\n\t\t\tambientLightIntensity: options.lighting?.ambientLightIntensity ?? preset.ambientIntensity,\n\t\t\tsunlightColor: options.lighting?.sunlightColor || 0xffffff, // Default to white sunlight\n\t\t\t// Direction-aware fill. The look decides whether it's on (a positive hemisphereIntensity is\n\t\t\t// what actually creates the light in setupLighting); an explicit option overrides.\n\t\t\tenableHemisphereLight:\n\t\t\t\toptions.lighting?.enableHemisphereLight ?? preset.hemisphereIntensity > 0,\n\t\t\themisphereSkyColor: options.lighting?.hemisphereSkyColor ?? 0xdfe6ff,\n\t\t\t// A slightly warm ground tint reads as bounced light and keeps fill from desaturating colour.\n\t\t\themisphereGroundColor: options.lighting?.hemisphereGroundColor ?? 0x6b5f52,\n\t\t\themisphereIntensity: options.lighting?.hemisphereIntensity ?? preset.hemisphereIntensity\n\t\t},\n\t\tenvironment: {\n\t\t\thdrPath: options.environment?.hdrPath || '/baseHDR.hdr',\n\t\t\tbackgroundColor: options.environment?.backgroundColor || new THREE.Color(0xf0f0f0),\n\t\t\tenableEnvironmentLighting: options.environment?.enableEnvironmentLighting ?? true,\n\t\t\tsceneUp: options.environment?.sceneUp || defaultUp,\n\t\t\tshowEnvironment: options.environment?.showEnvironment ?? false,\n\t\t\tenvironmentIntensity: options.environment?.environmentIntensity ?? preset.environmentIntensity\n\t\t},\n\t\tfloor: {\n\t\t\tenabled: options.floor?.enabled ?? false,\n\t\t\tsize: options.floor?.size || defaults.floorSize,\n\t\t\tcolor: options.floor?.color || new THREE.Color(0x808080),\n\t\t\troughness: options.floor?.roughness ?? 0.7,\n\t\t\tmetalness: options.floor?.metalness ?? 0.0,\n\t\t\treceiveShadow: options.floor?.receiveShadow ?? true\n\t\t},\n\t\trender: {\n\t\t\tenableShadows: options.render?.enableShadows ?? true,\n\t\t\tshadowMapSize: options.render?.shadowMapSize || 2048,\n\t\t\tantialias: options.render?.antialias ?? true,\n\t\t\tpixelRatio: options.render?.pixelRatio || Math.min(window.devicePixelRatio, 2),\n\t\t\t// ?? not || so an explicit NoToneMapping (=== 0) is honoured rather than falling through.\n\t\t\ttoneMapping: options.render?.toneMapping ?? preset.toneMapping,\n\t\t\ttoneMappingExposure: options.render?.toneMappingExposure ?? preset.toneMappingExposure,\n\t\t\tpreserveDrawingBuffer: options.render?.preserveDrawingBuffer ?? false,\n\t\t\tambientOcclusion: options.render?.ambientOcclusion ?? preset.ambientOcclusion,\n\t\t\taoIntensity: options.render?.aoIntensity ?? 1,\n\t\t\t// Cap AO buffers at 1× by default — the biggest lever on GTAO cost on high-DPI displays.\n\t\t\taoPixelRatio: options.render?.aoPixelRatio ?? 1,\n\t\t\t// On-demand rendering (audit P4): draw only when something changed. Opt-out flag.\n\t\t\tonDemand: options.render?.onDemand ?? true\n\t\t},\n\t\tcontrols: {\n\t\t\tenableDamping: options.controls?.enableDamping ?? false,\n\t\t\tdampingFactor: options.controls?.dampingFactor || 0.05,\n\t\t\tautoRotate: options.controls?.autoRotate ?? false,\n\t\t\tautoRotateSpeed: options.controls?.autoRotateSpeed || 0.5,\n\t\t\tenableZoom: options.controls?.enableZoom ?? true,\n\t\t\tenablePan: options.controls?.enablePan ?? true,\n\t\t\tminDistance: options.controls?.minDistance || defaults.minDistance,\n\t\t\tmaxDistance: options.controls?.maxDistance || Infinity\n\t\t},\n\t\tgrid: {\n\t\t\t// Defaults mirror createGrid's so the two never drift. Grid is an independent overlay — a\n\t\t\t// look never toggles it.\n\t\t\tenabled: options.grid?.enabled ?? false,\n\t\t\tcellSize: options.grid?.cellSize ?? 1,\n\t\t\tmajorEvery: options.grid?.majorEvery ?? 10,\n\t\t\tcellColor: options.grid?.cellColor ?? 0x888888,\n\t\t\tmajorColor: options.grid?.majorColor ?? 0x444444,\n\t\t\tfadeDistance: options.grid?.fadeDistance ?? 100,\n\t\t\t// The \"ground\" plane is the one orthogonal to the scene up axis, so the grid lies under the\n\t\t\t// model regardless of up convention (Z-up Rhino → 'z'; Y-up → 'y'). Explicit `plane` wins.\n\t\t\tplane: options.grid?.plane ?? upToAxis(options.environment?.sceneUp ?? defaultUp)\n\t\t},\n\t\tgizmo: {\n\t\t\tenabled: options.gizmo?.enabled ?? false\n\t\t},\n\t\tedges: {\n\t\t\t// Defaults mirror addEdges' so the two never drift. Edges are an independent overlay — a\n\t\t\t// look never toggles them.\n\t\t\tenabled: options.edges?.enabled ?? false,\n\t\t\t// No color default: leaving it undefined lets addEdges derive each mesh's edge color from\n\t\t\t// its own surface material (darkened). Set a color explicitly to force one uniform tint.\n\t\t\tcolor: options.edges?.color,\n\t\t\tdarken: options.edges?.darken,\n\t\t\twidth: options.edges?.width ?? 1.5,\n\t\t\tthresholdAngle: options.edges?.thresholdAngle ?? 44,\n\t\t\tdistanceFade: options.edges?.distanceFade ?? true\n\t\t},\n\t\tmeasure: {\n\t\t\t// Visual defaults live in createMeasureTool; only `enabled` needs a value here, the rest\n\t\t\t// pass through (undefined → the tool's own default).\n\t\t\tenabled: options.measure?.enabled ?? false,\n\t\t\tsnapPixels: options.measure?.snapPixels,\n\t\t\tcolor: options.measure?.color,\n\t\t\tlabelClassName: options.measure?.labelClassName,\n\t\t\tdisplayUnit: options.measure?.displayUnit,\n\t\t\tformat: options.measure?.format\n\t\t},\n\t\tevents: {\n\t\t\tonBackgroundClicked: options.events?.onBackgroundClicked,\n\t\t\tonObjectSelected: options.events?.onObjectSelected,\n\t\t\tonMeshMetadataClicked: options.events?.onMeshMetadataClicked,\n\t\t\tonMeshDoubleClicked: options.events?.onMeshDoubleClicked,\n\t\t\tselectionColor: options.events?.selectionColor || '#ff0000', // Default to red\n\t\t\tenableEventHandlers: options.events?.enableEventHandlers ?? true,\n\t\t\tenableKeyboardControls: options.events?.enableKeyboardControls ?? true,\n\t\t\tenableClickToFocus: options.events?.enableClickToFocus ?? true,\n\t\t\tenableDoubleClickZoom: options.events?.enableDoubleClickZoom ?? true,\n\t\t\tonReady: options.events?.onReady,\n\t\t\tonFrame: options.events?.onFrame\n\t\t}\n\t};\n}\n\n/**\n * Dispose a material together with any textures it references (`map`, `roughnessMap`, …), matching\n * `clearScene`'s texture sweep (three-helpers) so no teardown path leaks GPU textures across viewer\n * mount/unmount cycles. Walks own enumerable properties only — `for...in` would needlessly iterate\n * the prototype chain.\n */\nexport function disposeMaterialWithTextures(material: THREE.Material): void {\n\tfor (const value of Object.values(material)) {\n\t\tif (value instanceof THREE.Texture) {\n\t\t\tvalue.dispose();\n\t\t}\n\t}\n\tmaterial.dispose();\n}\n\n/**\n * Fit a directional light's shadow camera to the scene content. The orthographic shadow frustum is\n * sized to the content's bounding sphere (padded), so the fixed shadow-map texels cover only the\n * model rather than a generous constant area — the dominant lever on shadow crispness. Near/far are\n * derived from how far the light sits from the content centre, keeping depth precision tight.\n *\n * No-op when there is no content (an empty box would collapse the frustum to a point).\n */\nfunction fitShadowToContent(light: THREE.DirectionalLight, bounds: THREE.Box3): void {\n\tif (bounds.isEmpty()) return;\n\n\tconst center = bounds.getCenter(new THREE.Vector3());\n\t// Bounding-sphere radius makes the frustum rotation-invariant: the light can shine from any\n\t// angle and the model still fits, with no per-angle recompute. Pad so grazing-angle casters and\n\t// soft-shadow (VSM) blur near the edges don't clip.\n\tconst radius = bounds.getSize(new THREE.Vector3()).length() * 0.5 * 1.2;\n\n\tconst cam = light.shadow.camera;\n\tcam.left = -radius;\n\tcam.right = radius;\n\tcam.top = radius;\n\tcam.bottom = -radius;\n\n\t// Aim the shadow camera at the content centre. The light keeps its configured *position*; only\n\t// its target moves, so the lighting direction is preserved while the shadow frustum recentres.\n\tlight.target.position.copy(center);\n\tlight.target.updateMatrixWorld();\n\n\t// Near/far bracket the content along the light→centre axis. Clamp near to a small positive value\n\t// so a light sitting inside the bounds can't push near ≤ 0.\n\tconst lightDistance = light.position.distanceTo(center);\n\tcam.near = Math.max(radius * 0.01, lightDistance - radius);\n\tcam.far = lightDistance + radius;\n\tcam.updateProjectionMatrix();\n}\n\nfunction createScene(config: Required<ThreeInitializerOptions>): THREE.Scene {\n\tconst scene = new THREE.Scene();\n\n\tconst bgColor =\n\t\ttypeof config.environment.backgroundColor === 'string'\n\t\t\t? new THREE.Color(config.environment.backgroundColor)\n\t\t\t: config.environment.backgroundColor;\n\tscene.background = bgColor || null;\n\n\treturn scene;\n}\n\n// Resize applied before render so buffer clear and draw happen in the same frame,\n// preventing visible blank frames when the canvas is resized\nfunction createAnimationLoop(\n\trenderer: THREE.WebGLRenderer,\n\tscene: THREE.Scene,\n\tcamera: THREE.PerspectiveCamera,\n\tgetActiveCamera: () => THREE.Camera,\n\tcameraController: CameraController,\n\tcontrols: OrbitControls,\n\tgetCanvasSize: () => { width: number; height: number },\n\t// The resolved config.render.pixelRatio — the single source of truth for DPR (see initThree).\n\tpixelRatio: number,\n\tonFrame?: (delta: number) => void,\n\tgrid?: Grid | null,\n\tgizmo?: ViewGizmo | null,\n\tgetRenderPipeline?: () => RenderPipeline | null,\n\tlabelLayer?: LabelLayer | null,\n\tnearFitter?: NearPlaneFitter | null,\n\t// On-demand rendering (audit P4): render only when something changed. False = legacy every-frame.\n\tonDemand: boolean = true\n): { animate: () => void; dispose: () => void; invalidate: () => void } {\n\tlet animationId: number | null = null;\n\tlet lastTime = performance.now();\n\n\t// The loop always *ticks* (updates are cheap); it only *renders* when: invalidate() was called\n\t// (scene content, style toggles, async edge attach), the active camera moved — a matrix compare\n\t// catches every driver: damping, presets, gizmo snaps, near-plane refits — or the safety repaint\n\t// interval elapsed, which bounds the staleness of any mutation that forgot to invalidate.\n\tlet renderRequested = true; // first frame always renders\n\tlet lastRenderTime = 0;\n\tconst IDLE_REPAINT_INTERVAL_MS = 500;\n\tconst lastWorldMatrix = new THREE.Matrix4();\n\tconst lastProjectionMatrix = new THREE.Matrix4();\n\tlet lastCamera: THREE.Camera | null = null;\n\tconst invalidate = () => {\n\t\trenderRequested = true;\n\t};\n\n\tconst cameraMoved = (activeCamera: THREE.Camera): boolean => {\n\t\t// matrixWorld is normally refreshed by renderer.render — which we're deciding whether to\n\t\t// call — so refresh it here first (cheap: a camera has no deep subtree).\n\t\tactiveCamera.updateMatrixWorld();\n\t\tconst moved =\n\t\t\tlastCamera !== activeCamera ||\n\t\t\t!lastWorldMatrix.equals(activeCamera.matrixWorld) ||\n\t\t\t!lastProjectionMatrix.equals(activeCamera.projectionMatrix);\n\t\tif (moved) {\n\t\t\tlastCamera = activeCamera;\n\t\t\tlastWorldMatrix.copy(activeCamera.matrixWorld);\n\t\t\tlastProjectionMatrix.copy(activeCamera.projectionMatrix);\n\t\t}\n\t\treturn moved;\n\t};\n\n\t// Pointer/wheel activity is a catch-all for click-driven scene mutations (measure points,\n\t// selection highlights) whose code paths predate on-demand rendering.\n\tconst canvas = renderer.domElement;\n\tconst pointerEvents = ['pointerdown', 'pointerup', 'wheel'] as const;\n\tif (onDemand) {\n\t\tfor (const type of pointerEvents) {\n\t\t\tcanvas.addEventListener(type, invalidate, { passive: true });\n\t\t}\n\t}\n\n\tconst checkResize = () => {\n\t\tconst { width, height } = getCanvasSize();\n\t\tif (width === 0 || height === 0) return;\n\n\t\t// Must floor, not round: renderer.setSize floors the buffer size, and a mismatched rounding\n\t\t// here makes the comparison never settle — the resize branch would then run every frame.\n\t\tconst newW = Math.floor(width * pixelRatio);\n\t\tconst newH = Math.floor(height * pixelRatio);\n\n\t\tif (renderer.domElement.width !== newW || renderer.domElement.height !== newH) {\n\t\t\trenderer.setPixelRatio(pixelRatio);\n\t\t\trenderer.setSize(width, height, false);\n\t\t\tcamera.aspect = width / height;\n\t\t\tcamera.updateProjectionMatrix();\n\t\t\t// Reshape the orthographic frustum too, if it's the active projection.\n\t\t\tcameraController.updateAspect(width, height);\n\t\t\t// Keep the AO composer's render targets in step with the canvas.\n\t\t\tgetRenderPipeline?.()?.setSize(width, height, pixelRatio);\n\t\t\t// CSS2D overlay matches the canvas's CSS size (not the pixel-ratio buffer size).\n\t\t\tlabelLayer?.setSize(width, height);\n\t\t\tinvalidate();\n\t\t}\n\t};\n\n\tconst animate = function () {\n\t\tanimationId = requestAnimationFrame(animate);\n\n\t\tconst now = performance.now();\n\t\tconst delta = (now - lastTime) / 1000;\n\t\tlastTime = now;\n\n\t\tcheckResize();\n\n\t\tif (controls.enableDamping || controls.autoRotate) {\n\t\t\tcontrols.update();\n\t\t}\n\n\t\t// Keep the grid centered on the camera so it reads as infinite.\n\t\tif (grid) grid.update(getActiveCamera().position);\n\n\t\t// Advance the gizmo's fade/spin animation (no-op when idle).\n\t\tif (gizmo) gizmo.update(delta);\n\n\t\t// Refit the perspective near plane to the camera↔content gap (after controls moved the\n\t\t// camera, before anything renders) so depth precision tracks the viewing distance.\n\t\tif (nearFitter) nearFitter.update();\n\n\t\tonFrame?.(delta);\n\n\t\tconst activeCamera = getActiveCamera();\n\n\t\t// On-demand gate: skip the draw (the expensive part, especially with the AO composer) when\n\t\t// nothing changed. Ticking continues regardless, so damping/tweens re-trigger via the camera\n\t\t// compare on their next movement.\n\t\tif (onDemand) {\n\t\t\tconst shouldRender =\n\t\t\t\trenderRequested ||\n\t\t\t\tcameraMoved(activeCamera) ||\n\t\t\t\tnow - lastRenderTime >= IDLE_REPAINT_INTERVAL_MS;\n\t\t\tif (!shouldRender) return;\n\t\t\trenderRequested = false;\n\t\t\tlastRenderTime = now;\n\t\t}\n\n\t\tconst renderPipeline = getRenderPipeline?.();\n\t\tif (renderPipeline) {\n\t\t\t// AO path: composer owns the render. Retarget to the active camera in case 2D/3D swapped.\n\t\t\trenderPipeline.setCamera(activeCamera);\n\t\t\trenderPipeline.render(delta);\n\t\t} else {\n\t\t\trenderer.render(scene, activeCamera);\n\t\t}\n\n\t\t// HTML labels follow their 3D anchors — render the DOM overlay against the active camera.\n\t\tif (labelLayer) labelLayer.render(scene, activeCamera);\n\n\t\t// The gizmo draws as an overlay in a corner viewport with its own clear; render it last so it\n\t\t// sits on top of the scene.\n\t\tif (gizmo) gizmo.render(renderer);\n\t};\n\n\tconst dispose = () => {\n\t\tif (animationId !== null) {\n\t\t\tcancelAnimationFrame(animationId);\n\t\t\tanimationId = null;\n\t\t}\n\t\tif (onDemand) {\n\t\t\tfor (const type of pointerEvents) {\n\t\t\t\tcanvas.removeEventListener(type, invalidate);\n\t\t\t}\n\t\t}\n\t};\n\n\treturn { animate, dispose, invalidate };\n}\n\nfunction setupEnvironment(\n\tscene: THREE.Scene,\n\trenderer: THREE.WebGLRenderer,\n\tconfig: Required<ThreeInitializerOptions>,\n\tisDisposed: () => boolean\n) {\n\tif (config.environment.enableEnvironmentLighting) {\n\t\tnew HDRLoader().load(\n\t\t\tconfig.environment.hdrPath || '/baseHDR.hdr',\n\t\t\tfunction (envMap) {\n\t\t\t\t// The viewer can be torn down while the HDR is still fetching/decoding (fast\n\t\t\t\t// mount/unmount). dispose() has already swept the scene, so adopting the texture now\n\t\t\t\t// would leak it — and onReady must not fire on a dead viewer.\n\t\t\t\tif (isDisposed()) {\n\t\t\t\t\tenvMap.dispose();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (!envMap?.image) {\n\t\t\t\t\tgetLogger().warn('HDR loaded without image data; skipping environment map.');\n\t\t\t\t\t// The texture object still holds GPU/CPU resources even without usable image data —\n\t\t\t\t\t// dispose it, since it will never be attached to the scene.\n\t\t\t\t\tenvMap?.dispose();\n\t\t\t\t\tconfig.events.onReady?.();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tenvMap.mapping = THREE.EquirectangularReflectionMapping;\n\n\t\t\t\t// Prefilter the raw equirect HDR through PMREM: this builds the roughness-aware mip\n\t\t\t\t// chain a MeshStandardMaterial samples for image-based lighting. Without it, three\n\t\t\t\t// falls back to sampling the equirect map directly and a rough surface reads a near-\n\t\t\t\t// mirror level — reflections stay unnaturally sharp/busy and specular highlights\n\t\t\t\t// sparkle, which is a big part of the \"not quite right\" look. The prefiltered cube is\n\t\t\t\t// what drives IBL; the raw equirect is kept only if it's also shown as the background.\n\t\t\t\tconst pmrem = new THREE.PMREMGenerator(renderer);\n\t\t\t\tpmrem.compileEquirectangularShader();\n\t\t\t\tconst prefiltered = pmrem.fromEquirectangular(envMap).texture;\n\t\t\t\tpmrem.dispose();\n\n\t\t\t\tscene.environment = prefiltered;\n\t\t\t\t// Normalize the HDR's IBL contribution so brightness is consistent across HDRs of\n\t\t\t\t// differing exposure, instead of dim-HDR-looks-dim / bright-HDR-blows-out.\n\t\t\t\tscene.environmentIntensity = config.environment.environmentIntensity ?? 1;\n\t\t\t\t// Equirectangular mapping assumes the HDR's horizon lies in the XZ plane — i.e. Y-up.\n\t\t\t\t// This scene is Z-up, so without a rotation the environment sits on its side: the\n\t\t\t\t// horizon runs vertically and the sky lights the model from +Y instead of from above.\n\t\t\t\t// Invisible on a neutral studio HDR, obvious on any HDR with a sky/ground split.\n\t\t\t\tconst envRotation = environmentRotationFor(config.environment.sceneUp ?? defaultUp);\n\t\t\t\tscene.environmentRotation.copy(envRotation);\n\t\t\t\tif (config.environment.showEnvironment) {\n\t\t\t\t\t// Background wants the full-resolution equirect, not the low-res prefiltered probe —\n\t\t\t\t\t// so keep the raw map for that and let it dispose with the scene background sweep.\n\t\t\t\t\tscene.background = envMap;\n\t\t\t\t\t// Keep the visible background locked to the same orientation as the IBL probe;\n\t\t\t\t\t// they are separate properties and drift apart if only one is set.\n\t\t\t\t\tscene.backgroundRotation.copy(envRotation);\n\t\t\t\t} else {\n\t\t\t\t\t// The raw equirect was only an input to PMREM; the prefiltered probe has superseded\n\t\t\t\t\t// it for IBL and nothing else references it, so release it now.\n\t\t\t\t\tenvMap.dispose();\n\t\t\t\t}\n\t\t\t\tconfig.events.onReady?.();\n\t\t\t},\n\t\t\tundefined,\n\t\t\tfunction (error) {\n\t\t\t\tif (isDisposed()) return;\n\t\t\t\tgetLogger().warn('HDR texture could not be loaded, falling back to basic lighting:', error);\n\t\t\t\tconfig.events.onReady?.();\n\t\t\t}\n\t\t);\n\t} else {\n\t\tconfig.events.onReady?.();\n\t}\n}\n\n/** The lights created by {@link setupLighting}, handed back so runtime setters can retune them. */\ntype SceneLights = {\n\tambient: THREE.AmbientLight;\n\t/** Hemisphere fill light — null unless `lighting.enableHemisphereLight`. */\n\themisphere: THREE.HemisphereLight | null;\n\t/**\n\t * Shadow-casting sun. Null when sunlight is disabled or shadows are off — the caller uses it only\n\t * to refit the shadow frustum on geometry change (see `fitShadowToContent`), so null means nothing\n\t * to refit.\n\t */\n\tsun: THREE.DirectionalLight | null;\n};\n\n/**\n * Set up scene lighting. Returns handles to the created lights so the caller can refit the sun's\n * shadow frustum on geometry change and retune fill lights at runtime.\n */\nfunction setupLighting(scene: THREE.Scene, config: Required<ThreeInitializerOptions>): SceneLights {\n\tconst ambient = new THREE.AmbientLight(\n\t\tconfig.lighting.ambientLightColor,\n\t\tconfig.lighting.ambientLightIntensity\n\t);\n\tscene.add(ambient);\n\n\t// Hemisphere fill: soft sky-from-above / ground-from-below light that lifts occluded and\n\t// downward-facing surfaces the HDR may leave dark. Aligned to the scene up so \"sky\" is genuinely\n\t// up in a Z-up scene (a HemisphereLight defaults to +Y up).\n\tlet hemisphere: THREE.HemisphereLight | null = null;\n\tif (config.lighting.enableHemisphereLight) {\n\t\themisphere = new THREE.HemisphereLight(\n\t\t\tconfig.lighting.hemisphereSkyColor,\n\t\t\tconfig.lighting.hemisphereGroundColor,\n\t\t\tconfig.lighting.hemisphereIntensity\n\t\t);\n\t\tconst up = config.environment.sceneUp ?? defaultUp;\n\t\themisphere.position.copy(up);\n\t\tscene.add(hemisphere);\n\t}\n\n\tif (!config.lighting.enableSunlight) return { ambient, hemisphere, sun: null };\n\n\tconst sunlight = new THREE.DirectionalLight(\n\t\tconfig.lighting.sunlightColor ?? 0xffffff,\n\t\tconfig.lighting.sunlightIntensity\n\t);\n\tconst pos = config.lighting.sunlightPosition;\n\tif (pos) {\n\t\tsunlight.position.set(pos.x, pos.y, pos.z);\n\t}\n\n\tif (!config.render.enableShadows) {\n\t\tscene.add(sunlight);\n\t\treturn { ambient, hemisphere, sun: null };\n\t}\n\n\tsunlight.castShadow = true;\n\n\t// The frustum bounds (left/right/top/bottom/near/far) are not set here — they are fitted to the\n\t// scene content by fitShadowToContent, called at init and on every geometry change. Sizing them\n\t// to the model instead of a fixed constant is the dominant lever on shadow crispness.\n\tsunlight.shadow.mapSize.width = config.render.shadowMapSize || 2048;\n\tsunlight.shadow.mapSize.height = config.render.shadowMapSize || 2048;\n\n\tsunlight.shadow.bias = -0.0001;\n\tsunlight.shadow.normalBias = 0.02;\n\t// Soften VSM edges; cheap and only meaningful once the frustum is tight (see fitShadowToContent).\n\tsunlight.shadow.radius = 4;\n\n\tscene.add(sunlight);\n\t// A DirectionalLight aims at its target's world position; the target must be in the scene graph\n\t// for its matrix to update. fitShadowToContent moves this target to the content centre.\n\tscene.add(sunlight.target);\n\treturn { ambient, hemisphere, sun: sunlight };\n}\n\nfunction addFloor(scene: THREE.Scene, config: Required<ThreeInitializerOptions>) {\n\tconst floorSize = config.floor.size;\n\tconst floorGeometry = new THREE.PlaneGeometry(floorSize, floorSize);\n\n\tconst floorColor =\n\t\ttypeof config.floor.color === 'string'\n\t\t\t? new THREE.Color(config.floor.color)\n\t\t\t: config.floor.color;\n\n\tconst floorMaterial = new THREE.MeshStandardMaterial({\n\t\tcolor: floorColor,\n\t\troughness: config.floor.roughness,\n\t\tmetalness: config.floor.metalness,\n\t\tside: THREE.DoubleSide\n\t});\n\n\tconst floor = new THREE.Mesh(floorGeometry, floorMaterial);\n\tfloor.userData.id = 'floor';\n\tfloor.name = 'floor';\n\t// PlaneGeometry lies in XY with a +Z normal — already the ground for a Z-up scene. Orient its\n\t// normal to the scene up axis so the floor is the ground plane in any up convention.\n\tconst up = (config.environment?.sceneUp || defaultUp).clone().normalize();\n\tfloor.quaternion.setFromUnitVectors(new THREE.Vector3(0, 0, 1), up);\n\tfloor.position.set(0, 0, 0);\n\n\tif (config.floor.receiveShadow && config.render.enableShadows) {\n\t\tfloor.receiveShadow = true;\n\t}\n\n\tscene.add(floor);\n}\n\nfunction createCamera(\n\tconfig: Required<ThreeInitializerOptions>,\n\tcanvas: HTMLCanvasElement\n): THREE.PerspectiveCamera {\n\tconst parent = canvas.parentElement;\n\tconst width = parent ? parent.clientWidth : window.innerWidth;\n\tconst height = parent ? parent.clientHeight : window.innerHeight;\n\n\tconst camera = new THREE.PerspectiveCamera(\n\t\tconfig.camera.fov,\n\t\twidth / height,\n\t\tconfig.camera.near,\n\t\tconfig.camera.far\n\t);\n\n\tconst pos = config.camera.position;\n\tif (pos) {\n\t\tcamera.position.set(pos.x, pos.y, pos.z);\n\t}\n\n\treturn camera;\n}\n\nfunction setupRenderer(\n\tcanvas: HTMLCanvasElement,\n\tconfig: Required<ThreeInitializerOptions>,\n\tpixelRatio: number\n): THREE.WebGLRenderer {\n\tconst renderer = new THREE.WebGLRenderer({\n\t\tantialias: config.render.antialias,\n\t\tcanvas,\n\t\talpha: true,\n\t\tpowerPreference: 'high-performance',\n\t\tpreserveDrawingBuffer: config.render.preserveDrawingBuffer,\n\t\t// Deliberately NOT logarithmic: three's depth-based post passes (our GTAO pipeline) reconstruct\n\t\t// view-space positions assuming standard perspective depth and do not support log-encoded\n\t\t// depth — with it on, AO is computed from wrong depths (haloing, wrong-scale occlusion). The\n\t\t// per-scale near/far defaults (see applyDefaults) keep standard depth precision adequate for\n\t\t// the viewer's scene scales. If log depth is ever needed, AO must be disabled with it.\n\t\tlogarithmicDepthBuffer: false\n\t});\n\n\tconst parent = canvas.parentElement;\n\tconst width = parent ? parent.clientWidth : window.innerWidth;\n\tconst height = parent ? parent.clientHeight : window.innerHeight;\n\n\tif (parent) {\n\t\tcanvas.style.width = '100%';\n\t\tcanvas.style.height = '100%';\n\t\tcanvas.style.display = 'block';\n\t}\n\n\trenderer.setSize(width, height, false);\n\trenderer.setPixelRatio(pixelRatio);\n\n\tif (config.render.enableShadows) {\n\t\trenderer.shadowMap.enabled = true;\n\t\trenderer.shadowMap.type = THREE.VSMShadowMap;\n\t}\n\n\trenderer.toneMapping = config.render.toneMapping!;\n\trenderer.toneMappingExposure = config.render.toneMappingExposure ?? 1.0;\n\trenderer.outputColorSpace = THREE.SRGBColorSpace;\n\n\trenderer.sortObjects = true;\n\n\treturn renderer;\n}\n\nfunction setupEventHandlers(\n\tcanvas: HTMLCanvasElement,\n\tscene: THREE.Scene,\n\tcameraController: CameraController,\n\tconfig: Required<ThreeInitializerOptions>\n): {\n\tdispose: () => void;\n\tfitToView: () => void;\n\tclearSelection: () => void;\n} {\n\tconst selectedObjects = new Set<THREE.Object3D>();\n\tconst originalMaterials = new Map<THREE.Object3D, THREE.Material | THREE.Material[]>();\n\tconst raycaster = new THREE.Raycaster();\n\tconst mouse = new THREE.Vector2();\n\tconst mouseDownPosition = new THREE.Vector2();\n\tconst getActiveCamera = () => cameraController.getActiveCamera();\n\n\t// An object is hittable only if every ancestor is also visible. Three.js's\n\t// recursive intersect doesn't enforce that — it can hit a visible Mesh inside\n\t// a hidden Group.\n\tconst isFullyVisible = (object: THREE.Object3D): boolean => {\n\t\tlet current: THREE.Object3D | null = object;\n\t\twhile (current) {\n\t\t\tif (!current.visible) return false;\n\t\t\tcurrent = current.parent;\n\t\t}\n\t\treturn true;\n\t};\n\n\tconst fitToView = () => {\n\t\t// Frame the scene's renderable content; viewer aids (grid/floor/labels/measure) are excluded so\n\t\t// the camera-tracking grid plane can't dominate the bounds and blow up the fit distance.\n\t\tconst box = computeContentBounds(scene);\n\n\t\tif (box.isEmpty()) {\n\t\t\tgetLogger().warn('No objects to fit to view');\n\t\t\treturn;\n\t\t}\n\n\t\t// Delegate the move to the camera controller: it frames from the current view direction and\n\t\t// repositions whichever camera is LIVE, re-deriving the ortho frustum in 2D mode — whereas\n\t\t// moving the perspective camera directly would change nothing visible in 2D (and silently\n\t\t// drag the invisible perspective camera out of sync).\n\t\tcameraController.frameBounds(box, false);\n\t};\n\n\tconst selectionColorObj =\n\t\ttypeof config.events.selectionColor === 'string'\n\t\t\t? new THREE.Color(config.events.selectionColor)\n\t\t\t: config.events.selectionColor instanceof THREE.Color\n\t\t\t\t? config.events.selectionColor\n\t\t\t\t: new THREE.Color('#ff0000');\n\n\tconst clearSelection = () => {\n\t\tselectedObjects.forEach((obj) => {\n\t\t\tconst restorable = obj as THREE.Object3D & {\n\t\t\t\tmaterial?: THREE.Material | THREE.Material[];\n\t\t\t};\n\t\t\tif (originalMaterials.has(obj)) {\n\t\t\t\tconst original = originalMaterials.get(obj)!;\n\t\t\t\t// Dispose the clone we swapped in before restoring the original.\n\t\t\t\tconst clone = restorable.material;\n\t\t\t\tif (clone instanceof THREE.Material) clone.dispose();\n\t\t\t\telse if (Array.isArray(clone)) clone.forEach((m) => m.dispose());\n\t\t\t\trestorable.material = original;\n\t\t\t\toriginalMaterials.delete(obj);\n\n\t\t\t\t// If the object left the scene while selected (a solve's clearScene only saw — and\n\t\t\t\t// disposed — the highlight clone), no later scene traversal can reach the original we\n\t\t\t\t// just restored, so it must be disposed here. Compute content is cleared wholesale per\n\t\t\t\t// solve, so a detached object's material has no surviving sharers.\n\t\t\t\tlet root: THREE.Object3D = obj;\n\t\t\t\twhile (root.parent) root = root.parent;\n\t\t\t\tif (root !== scene) {\n\t\t\t\t\tif (original instanceof THREE.Material) original.dispose();\n\t\t\t\t\telse original.forEach((m) => m.dispose());\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tselectedObjects.clear();\n\t};\n\n\t// Highlight a selected object by cloning its material and recoloring. Meshes get an `emissive`\n\t// tint (so the surface keeps its base color); lines and points have no emissive channel, so we\n\t// recolor `color` directly. Returns true if a highlight was applied (a material was found).\n\tconst applyHighlight = (object: THREE.Object3D): boolean => {\n\t\tconst target = object as THREE.Object3D & { material?: THREE.Material | THREE.Material[] };\n\t\tif (!(target.material instanceof THREE.Material)) return false;\n\n\t\toriginalMaterials.set(object, target.material);\n\t\tconst clone = target.material.clone();\n\n\t\tif (object instanceof THREE.Mesh && 'emissive' in clone) {\n\t\t\t(clone as THREE.MeshStandardMaterial).emissive = selectionColorObj.clone();\n\t\t} else if ('color' in clone) {\n\t\t\t(clone as THREE.LineBasicMaterial).color = selectionColorObj.clone();\n\t\t}\n\n\t\ttarget.material = clone;\n\t\treturn true;\n\t};\n\n\t// Picking lines and points needs a ray-to-geometry tolerance, scaled to the scene so it holds at\n\t// any zoom. Plain THREE.Points use Raycaster.params.Points.threshold; fat Line2 uses its own\n\t// material linewidth, so only Points needs this. (THREE.Line would use params.Line.threshold, but\n\t// curves here are Line2.) Recomputed per pick from the current scene bounds.\n\tconst updatePickThresholds = () => {\n\t\tconst box = computeContentBounds(scene);\n\t\tconst diagonal = box.isEmpty() ? 1 : box.getSize(new THREE.Vector3()).length();\n\t\traycaster.params.Points.threshold = diagonal * 0.01;\n\t};\n\n\tconst handleMouseDown = (event: MouseEvent) => {\n\t\tmouseDownPosition.set(event.clientX, event.clientY);\n\t};\n\n\tconst handleCanvasClick = (event: MouseEvent) => {\n\t\t// Ignore if mouse has moved (drag)\n\t\tconst currentMousePosition = new THREE.Vector2(event.clientX, event.clientY);\n\t\tif (mouseDownPosition.distanceTo(currentMousePosition) > 5) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst rect = canvas.getBoundingClientRect();\n\t\tmouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;\n\t\tmouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;\n\n\t\tupdatePickThresholds();\n\t\traycaster.setFromCamera(mouse, getActiveCamera());\n\t\tconst intersects = raycaster\n\t\t\t.intersectObjects(scene.children, true)\n\t\t\t.filter((i) => isFullyVisible(i.object));\n\n\t\tif (intersects.length > 0) {\n\t\t\tconst clickedObject = intersects[0].object;\n\n\t\t\tif (!selectedObjects.has(clickedObject)) {\n\t\t\t\tclearSelection();\n\t\t\t\tselectedObjects.add(clickedObject);\n\n\t\t\t\t// Clone material (so siblings sharing it are untouched) and recolor to highlight.\n\t\t\t\t// Handles meshes, fat lines, and points alike.\n\t\t\t\tapplyHighlight(clickedObject);\n\n\t\t\t\tconfig.events?.onObjectSelected?.(clickedObject);\n\n\t\t\t\tif (clickedObject instanceof THREE.Mesh && Object.keys(clickedObject.userData).length > 0) {\n\t\t\t\t\tconfig.events?.onMeshMetadataClicked?.(clickedObject.userData);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tclearSelection();\n\t\t\tconfig.events?.onBackgroundClicked?.({ x: mouse.x, y: mouse.y });\n\t\t}\n\t};\n\n\tconst handleDoubleClick = (event: MouseEvent) => {\n\t\tconst rect = canvas.getBoundingClientRect();\n\t\tmouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;\n\t\tmouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;\n\n\t\tupdatePickThresholds();\n\t\traycaster.setFromCamera(mouse, getActiveCamera());\n\t\tconst intersects = raycaster\n\t\t\t.intersectObjects(scene.children, true)\n\t\t\t.filter((i) => isFullyVisible(i.object));\n\n\t\tif (intersects.length === 0) return;\n\n\t\tconst target = intersects[0].object;\n\t\tconfig.events?.onMeshDoubleClicked?.(target);\n\n\t\tif (!config.events?.enableDoubleClickZoom) return;\n\n\t\tconst box = new THREE.Box3().setFromObject(target);\n\t\tif (box.isEmpty()) return;\n\n\t\t// Frame the clicked object via the controller so the ACTIVE camera moves (ortho included —\n\t\t// its frustum is re-derived, since translating an ortho camera alone zooms nothing). The\n\t\t// controller's tween is cancellable: a rapid second double-click replaces the first tween\n\t\t// instead of running a competing loop, and dispose() stops it outright.\n\t\tcameraController.frameBounds(box, true);\n\t};\n\n\tconst handleKeydown = (event: KeyboardEvent) => {\n\t\tif (!config.events?.enableKeyboardControls) return;\n\n\t\tswitch (event.key.toLowerCase()) {\n\t\t\tcase 'f':\n\t\t\t\tevent.preventDefault();\n\t\t\t\tfitToView();\n\t\t\t\tbreak;\n\t\t\tcase 'escape':\n\t\t\t\tevent.preventDefault();\n\t\t\t\tclearSelection();\n\t\t\t\tbreak;\n\t\t\tcase ' ':\n\t\t\t\tevent.preventDefault();\n\t\t\t\tfitToView();\n\t\t\t\tbreak;\n\t\t}\n\t};\n\n\tif (config.events?.enableClickToFocus) {\n\t\tcanvas.addEventListener('mousedown', handleMouseDown);\n\t\tcanvas.addEventListener('click', handleCanvasClick);\n\t\tcanvas.addEventListener('dblclick', handleDoubleClick);\n\t}\n\n\tif (config.events?.enableKeyboardControls) {\n\t\tcanvas.setAttribute('tabindex', '0');\n\t\tcanvas.addEventListener('keydown', handleKeydown);\n\t}\n\n\tconst dispose = () => {\n\t\tcanvas.removeEventListener('mousedown', handleMouseDown);\n\t\tcanvas.removeEventListener('click', handleCanvasClick);\n\t\tcanvas.removeEventListener('dblclick', handleDoubleClick);\n\t\tcanvas.removeEventListener('keydown', handleKeydown);\n\t\tclearSelection();\n\t};\n\n\treturn { dispose, fitToView, clearSelection };\n}\n\nfunction setupControls(\n\tcamera: THREE.PerspectiveCamera,\n\tcanvas: HTMLCanvasElement,\n\tconfig: Required<ThreeInitializerOptions>\n): OrbitControls {\n\tconst controls = new OrbitControls(camera, canvas);\n\n\tconst target = config.camera.target;\n\tif (target) {\n\t\tcontrols.target.set(target.x, target.y, target.z);\n\t}\n\n\tcontrols.enableDamping = config.controls.enableDamping || false;\n\tcontrols.dampingFactor = config.controls.dampingFactor || 0.05;\n\n\tcontrols.autoRotate = config.controls.autoRotate || false;\n\tcontrols.autoRotateSpeed = config.controls.autoRotateSpeed || 0.5;\n\n\tcontrols.enableZoom = config.controls.enableZoom ?? true;\n\tcontrols.enablePan = config.controls.enablePan ?? true;\n\tcontrols.minDistance = config.controls.minDistance || 0.001;\n\tcontrols.maxDistance = config.controls.maxDistance || Infinity;\n\n\tcontrols.screenSpacePanning = false;\n\tcontrols.maxPolarAngle = Math.PI;\n\n\tcontrols.update();\n\treturn controls;\n}\n","import * as THREE from 'three';\n\nimport { parseColor } from '../threejs/three-helpers.js';\nimport { getLogger } from '@/core';\nimport { RhinoComputeError, ErrorCodes } from '@/core/errors';\n\nimport { FLAG_FLOAT32, parseBinaryMeshBatch, parseBinaryMeshBatchRaw } from './binary-parser.js';\nimport { fingerprintViews, geometryCacheGet, geometryCachePut } from './geometry-cache.js';\nimport { meshAssemblyWorkerSource } from './mesh-assembly.js';\nimport { applyTextureMap } from './texture-cache.js';\n\nimport type { AssembledGeometry, AssemblyJob, AssemblyWindow } from './mesh-assembly.js';\n\nimport type { ParsedBinaryMeshBatch } from './binary-parser.js';\nimport type {\n\tDisplayBatch,\n\tMaterialAppearanceOptions,\n\tMaterialGroup,\n\tMeshBatchParsingOptions,\n\tMeshMetadata,\n\tSerializableMaterial\n} from './types.js';\n\n/** Internal telemetry only (not exposed in public options). */\ninterface ParseTelemetry {\n\tparseTime?: number;\n\tperfStart?: number;\n}\n\n/**\n * Parses a batched mesh JSON and creates Three.js meshes.\n *\n * The geometry payload is the binary \"SLVA\" blob produced by the C# `BinaryGeometryWriter`,\n * base64-encoded into the outer JSON envelope. We `JSON.parse` the small envelope, then hand the\n * blob to `parseBinaryMeshBatch` which decodes the geometry without ever turning it into a string.\n *\n * An invalid JSON envelope (not a batch at all) logs and returns `[]` — that is the\n * \"genuinely absent data\" case. A batch whose *blob* is corrupt, truncated, or unsupported throws\n * instead of silently rendering an empty scene.\n *\n * @param batchJson - JSON string containing the batched mesh data\n * @param options - Rendering options\n * @returns Promise resolving to array of Three.js mesh objects\n * @throws {RhinoComputeError} On a corrupt/truncated/unsupported mesh blob or malformed group metadata.\n */\nexport async function parseMeshBatch(\n\tbatchJson: string,\n\toptions?: MeshBatchParsingOptions\n): Promise<THREE.Mesh[]> {\n\tconst { debug = false } = options ?? {};\n\n\tconst perfStart = debug ? performance.now() : 0;\n\n\t// Narrow catch: only the envelope JSON.parse is allowed to degrade to []. Blob parse errors\n\t// from parseMeshBatchObject propagate — see that entry point's contract.\n\tlet batch: DisplayBatch;\n\tconst parseStart = performance.now();\n\ttry {\n\t\tbatch = JSON.parse(batchJson);\n\t} catch (error) {\n\t\tgetLogger().error('Error parsing mesh batch envelope JSON:', error);\n\t\treturn [];\n\t}\n\tconst parseTime = performance.now() - parseStart;\n\n\treturn await parseMeshBatchObject(batch, options, { parseTime, perfStart });\n}\n\n/**\n * Parses a DisplayBatch object and creates Three.js meshes from its mesh blob.\n *\n * The path is synchronous internally — `parseBinaryMeshBatch` does no IO, just typed-array views\n * over the blob. The function stays `async` so callers don't have to change shape if we move\n * parsing into a worker later.\n *\n * A batch with no `compressedData` (genuinely empty/absent geometry) resolves to `[]`. A corrupt,\n * truncated, or unsupported blob throws so callers get a signal instead of a silent empty scene —\n * `getThreeMeshesFromComputeResponse` documents (and now delivers) exactly that rethrow.\n *\n * @param batch - DisplayBatch object\n * @param options - Rendering options\n * @returns Promise resolving to array of Three.js mesh objects\n * @throws {RhinoComputeError} On a corrupt/truncated/unsupported mesh blob or malformed group metadata.\n */\nexport async function parseMeshBatchObject(\n\tbatch: DisplayBatch,\n\toptions?: MeshBatchParsingOptions,\n\t/** @internal Timings threaded from an outer entry point; not a caller option. */\n\ttelemetry?: ParseTelemetry\n): Promise<THREE.Mesh[]> {\n\tconst { mergeByMaterial = true, applyTransforms = true, debug = false, material } = options ?? {};\n\tconst { parseTime = 0, perfStart = debug ? performance.now() : 0 } = telemetry ?? {};\n\n\tif (!batch.compressedData) {\n\t\t// No blob at all — an items-only or empty batch. This is the one entry-point path that\n\t\t// legitimately yields [] rather than throwing.\n\t\treturn [];\n\t}\n\n\t// Off-thread path (audit P2): heavy batches decode+assemble in a worker; null → do it here.\n\tconst workerMeshes = await tryBuildViaWorker(batch.compressedData, {\n\t\tmergeByMaterial,\n\t\tapplyTransforms,\n\t\tdebug,\n\t\tmaterial,\n\t\tfallback: {\n\t\t\tmaterials: batch.materials,\n\t\t\tgroups: batch.groups,\n\t\t\tsourceComponentId: batch.sourceComponentId\n\t\t}\n\t});\n\tif (workerMeshes) return workerMeshes;\n\n\tconst decodeStart = performance.now();\n\tconst parsed = parseBinaryMeshBatch(batch.compressedData);\n\tconst decodeTime = performance.now() - decodeStart;\n\n\tconst blobBytes = debug ? approximateBase64DecodedBytes(batch.compressedData) : 0;\n\n\treturn buildMeshesFromParsed(parsed, {\n\t\tmergeByMaterial,\n\t\tapplyTransforms,\n\t\tdebug,\n\t\tmaterial,\n\t\tparseTime,\n\t\tdecodeTime,\n\t\tperfStart,\n\t\tblobBytes,\n\t\tfallback: {\n\t\t\tmaterials: batch.materials,\n\t\t\tgroups: batch.groups,\n\t\t\tsourceComponentId: batch.sourceComponentId\n\t\t}\n\t});\n}\n\n/**\n * Parses a raw binary mesh batch blob (SLVA wire format) and creates Three.js meshes.\n *\n * Use this entry point when the blob arrives as a binary WebSocket frame (Phase 1b transport):\n * the JSON envelope no longer carries `displayData`, so there's nothing to `JSON.parse`. The blob\n * is self-describing — materials, groups, and `sourceComponentId` come from its embedded metadata\n * header.\n *\n * @param blob - Raw blob bytes from a binary WebSocket frame.\n * @param options - Rendering options.\n * @returns Promise resolving to array of Three.js mesh objects.\n * @throws {RhinoComputeError} On a corrupt/truncated/unsupported mesh blob or malformed group metadata.\n */\nexport async function parseMeshBatchBlob(\n\tblob: ArrayBuffer | Uint8Array,\n\toptions?: MeshBatchParsingOptions\n): Promise<THREE.Mesh[]> {\n\tconst { mergeByMaterial = true, applyTransforms = true, debug = false, material } = options ?? {};\n\n\tconst perfStart = debug ? performance.now() : 0;\n\n\t// Off-thread path (audit P2): heavy batches decode+assemble in a worker; null → do it here.\n\tconst workerMeshes = await tryBuildViaWorker(blob, {\n\t\tmergeByMaterial,\n\t\tapplyTransforms,\n\t\tdebug,\n\t\tmaterial\n\t});\n\tif (workerMeshes) return workerMeshes;\n\n\tconst decodeStart = performance.now();\n\tconst parsed = parseBinaryMeshBatch(blob);\n\tconst decodeTime = performance.now() - decodeStart;\n\n\tconst blobBytes = blob.byteLength;\n\n\treturn buildMeshesFromParsed(parsed, {\n\t\tmergeByMaterial,\n\t\tapplyTransforms,\n\t\tdebug,\n\t\tmaterial,\n\t\tparseTime: 0,\n\t\tdecodeTime,\n\t\tperfStart,\n\t\tblobBytes\n\t});\n}\n\ninterface BuildOptions {\n\tmergeByMaterial: boolean;\n\tapplyTransforms: boolean;\n\tdebug: boolean;\n\tmaterial?: MaterialAppearanceOptions;\n\tparseTime: number;\n\tdecodeTime: number;\n\tperfStart: number;\n\tblobBytes: number;\n\t/** Outer-envelope fallback when the blob's metadata is missing fields (defensive). */\n\tfallback?: {\n\t\tmaterials?: SerializableMaterial[];\n\t\tgroups?: MaterialGroup[];\n\t\tsourceComponentId?: string;\n\t};\n}\n\nfunction buildMeshesFromParsed(\n\tparsed: ParsedBinaryMeshBatch,\n\topts: BuildOptions\n): Promise<THREE.Mesh[]> {\n\tconst {\n\t\tmergeByMaterial,\n\t\tapplyTransforms,\n\t\tdebug,\n\t\tmaterial: materialAppearance,\n\t\tparseTime,\n\t\tdecodeTime,\n\t\tperfStart,\n\t\tblobBytes,\n\t\tfallback\n\t} = opts;\n\n\tconst materialsSrc = parsed.metadata.materials ?? fallback?.materials ?? [];\n\tconst groups = parsed.metadata.groups ?? fallback?.groups ?? [];\n\t// Prefer the outer envelope's sourceComponentId over the blob's embedded one. The blob bakes in\n\t// the id at encode time, but a reloaded part (e.g. from a .dmf instanced many times) re-stamps a\n\t// fresh id on the envelope to keep web pick identity distinct per placement. The blob value is\n\t// the fallback for the raw-blob transport, which has no envelope.\n\tconst sourceComponentId = fallback?.sourceComponentId ?? parsed.metadata.sourceComponentId;\n\n\tconst isFloat32 = (parsed.flags & FLAG_FLOAT32) !== 0;\n\n\t// Group metadata arrives as embedded (or envelope) JSON and is used arithmetically below —\n\t// unchecked, a bad vertexStart/indexStart wraps rebased indices into a Uint32Array, `subarray`\n\t// silently clamps, and an out-of-range materialId feeds `undefined` into `new THREE.Mesh`.\n\t// Fail the parse instead of silently corrupting the render.\n\tvalidateGroupMetadata(\n\t\tgroups,\n\t\tmaterialsSrc.length,\n\t\tparsed.vertices.length / 3,\n\t\tparsed.indices.length\n\t);\n\n\t// Dequantize once up-front into a single Float32Array. Downstream code (per-group merging,\n\t// computeVertexNormals, ground-offset) all expect world-unit floats, and a single\n\t// linear pass over the int16 buffer is far cheaper than the legacy gunzip + base64 path.\n\t// No rotation happens here: the scene uses Rhino's Z-up frame, so vertices pass through in the\n\t// frame they arrived in (see ../coordinate-transform.ts). `applyTransforms` is inert.\n\tconst worldVertices = isFloat32\n\t\t? maybeRotateFloat32Vertices(parsed.vertices as Float32Array, applyTransforms)\n\t\t: dequantizeInt16(parsed.vertices as Int16Array, parsed.origin, parsed.scale, applyTransforms);\n\n\tif (debug) {\n\t\tconst wireBytes = parsed.vertices.byteLength + parsed.indices.byteLength;\n\t\tgetLogger().debug('Mesh Batch Stats:');\n\t\tgetLogger().debug(` Materials: ${materialsSrc.length} | Groups: ${groups.length}`);\n\t\tgetLogger().debug(\n\t\t\t` Vertices: ${parsed.vertices.length / 3} | Indices: ${parsed.indices.length}`\n\t\t);\n\t\tgetLogger().debug(` Format: ${isFloat32 ? 'float32' : 'int16 quantized'}`);\n\t\tgetLogger().debug(\n\t\t\t` Blob: ${(blobBytes / 1024 / 1024).toFixed(2)} MB | Geometry on wire: ${(wireBytes / 1024 / 1024).toFixed(2)} MB`\n\t\t);\n\t}\n\n\tconst meshCreateStart = performance.now();\n\t// Vertex colors are batch-wide when present (meshes without real colors carry a white fill,\n\t// which multiplies to identity), so the material can enable vertexColors unconditionally.\n\tconst materials = materialsSrc.map((m) =>\n\t\tcreateMaterial(m, {\n\t\t\tvertexColors: parsed.colors != null,\n\t\t\tappearance: materialAppearance\n\t\t})\n\t);\n\n\tconst meshes: THREE.Mesh[] = [];\n\n\tfor (const group of groups) {\n\t\tif (mergeByMaterial && group.meshes.length > 1) {\n\t\t\tconst mergedMesh = createMergedMesh(\n\t\t\t\tgroup,\n\t\t\t\tworldVertices,\n\t\t\t\tparsed.indices,\n\t\t\t\tmaterials,\n\t\t\t\tparsed.uvs,\n\t\t\t\tparsed.colors\n\t\t\t);\n\t\t\tmergedMesh.userData.sourceComponentId = sourceComponentId ?? null;\n\t\t\tmeshes.push(mergedMesh);\n\t\t} else {\n\t\t\tconst individualMeshes = createIndividualMeshes(\n\t\t\t\tgroup,\n\t\t\t\tworldVertices,\n\t\t\t\tparsed.indices,\n\t\t\t\tmaterials,\n\t\t\t\tparsed.uvs,\n\t\t\t\tparsed.colors\n\t\t\t);\n\t\t\tfor (const mesh of individualMeshes) {\n\t\t\t\tmesh.userData.sourceComponentId = sourceComponentId ?? null;\n\t\t\t}\n\t\t\tmeshes.push(...individualMeshes);\n\t\t}\n\t}\n\n\tconst meshCreateTime = performance.now() - meshCreateStart;\n\n\tif (debug) {\n\t\tconst totalTime = performance.now() - perfStart;\n\t\tgetLogger().debug('Performance:');\n\t\tif (parseTime > 0) getLogger().debug(` Parse JSON: ${parseTime.toFixed(2)}ms`);\n\t\tgetLogger().debug(` Decode binary: ${decodeTime.toFixed(2)}ms`);\n\t\tgetLogger().debug(` Create Meshes: ${meshCreateTime.toFixed(2)}ms`);\n\t\tgetLogger().debug(` Total: ${totalTime.toFixed(2)}ms`);\n\t}\n\n\treturn Promise.resolve(meshes);\n}\n\nfunction metadataFail(message: string, context: Record<string, unknown>): RhinoComputeError {\n\treturn new RhinoComputeError(message, ErrorCodes.VALIDATION_ERROR, { context });\n}\n\n/**\n * Validates the batch's group/mesh metadata against the decoded geometry buffers before any of it\n * is used arithmetically. Throws a VALIDATION_ERROR on the first inconsistency (out-of-range\n * `materialId`, non-integer or negative offsets/counts, or vertex/index windows that overrun the\n * buffers) so malformed or version-skewed metadata fails the parse loudly.\n */\nfunction validateGroupMetadata(\n\tgroups: MaterialGroup[],\n\tmaterialCount: number,\n\ttotalVertexCount: number,\n\ttotalIndexCount: number\n): void {\n\tfor (const group of groups) {\n\t\tif (\n\t\t\t!Number.isInteger(group.materialId) ||\n\t\t\tgroup.materialId < 0 ||\n\t\t\tgroup.materialId >= materialCount\n\t\t) {\n\t\t\tthrow metadataFail('Group materialId out of range of the materials array.', {\n\t\t\t\tmaterialId: group.materialId,\n\t\t\t\tmaterialCount\n\t\t\t});\n\t\t}\n\n\t\tfor (const mesh of group.meshes) {\n\t\t\tconst fields = {\n\t\t\t\tvertexStart: mesh.vertexStart,\n\t\t\t\tvertexCount: mesh.vertexCount,\n\t\t\t\tindexStart: mesh.indexStart,\n\t\t\t\tindexCount: mesh.indexCount\n\t\t\t};\n\t\t\tfor (const [field, value] of Object.entries(fields)) {\n\t\t\t\tif (!Number.isInteger(value) || value < 0) {\n\t\t\t\t\tthrow metadataFail(`Mesh metadata field \"${field}\" must be a non-negative integer.`, {\n\t\t\t\t\t\tmeshName: mesh.name,\n\t\t\t\t\t\tfield,\n\t\t\t\t\t\tvalue\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (mesh.vertexStart + mesh.vertexCount > totalVertexCount) {\n\t\t\t\tthrow metadataFail('Mesh vertex window exceeds the batch vertex buffer.', {\n\t\t\t\t\tmeshName: mesh.name,\n\t\t\t\t\tvertexStart: mesh.vertexStart,\n\t\t\t\t\tvertexCount: mesh.vertexCount,\n\t\t\t\t\ttotalVertexCount\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (mesh.indexStart + mesh.indexCount > totalIndexCount) {\n\t\t\t\tthrow metadataFail('Mesh index window exceeds the batch index buffer.', {\n\t\t\t\t\tmeshName: mesh.name,\n\t\t\t\t\tindexStart: mesh.indexStart,\n\t\t\t\t\tindexCount: mesh.indexCount,\n\t\t\t\t\ttotalIndexCount\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Error for an index outside its mesh's declared vertex window\n * `[vertexStart, vertexStart + vertexCount)`. Rebasing (`index - vertexStart`) writes into an\n * unsigned array, so a violation would otherwise wrap to ~4 billion and corrupt the geometry.\n * The range checks themselves are inlined in the copy loops (audit P6 — a function call per index\n * was measurable at millions of indices); this only builds the failure.\n */\nfunction indexOutOfWindow(indexValue: number, meshMeta: MeshMetadata): RhinoComputeError {\n\treturn metadataFail(\"Index references a vertex outside its mesh's vertex window.\", {\n\t\tmeshName: meshMeta.name,\n\t\tindexValue,\n\t\tvertexStart: meshMeta.vertexStart,\n\t\tvertexCount: meshMeta.vertexCount\n\t});\n}\n\n/**\n * Content key for the cross-solve geometry cache: samples of every buffer window this geometry is\n * built from, plus the window layout as salt (identical bytes at a different offset rebase to\n * different geometry). See geometry-cache.ts for the safety model.\n */\nfunction geometryContentKey(\n\tkind: 'merged' | 'single',\n\tmeshes: MeshMetadata[],\n\tallVertices: Float32Array,\n\tallIndices: Uint16Array | Uint32Array,\n\tallUvs: Float32Array | null,\n\tallColors: Uint8Array | null\n): string {\n\tconst parts: (ArrayBufferView | null)[] = [];\n\tlet salt = kind;\n\tfor (const meshMeta of meshes) {\n\t\tsalt += `|${meshMeta.vertexStart},${meshMeta.vertexCount},${meshMeta.indexStart},${meshMeta.indexCount}`;\n\t\tconst componentStart = meshMeta.vertexStart * 3;\n\t\tconst componentEnd = componentStart + meshMeta.vertexCount * 3;\n\t\tparts.push(allVertices.subarray(componentStart, componentEnd));\n\t\tparts.push(allIndices.subarray(meshMeta.indexStart, meshMeta.indexStart + meshMeta.indexCount));\n\t\tparts.push(\n\t\t\tallUvs\n\t\t\t\t? allUvs.subarray(\n\t\t\t\t\t\tmeshMeta.vertexStart * 2,\n\t\t\t\t\t\t(meshMeta.vertexStart + meshMeta.vertexCount) * 2\n\t\t\t\t\t)\n\t\t\t\t: null\n\t\t);\n\t\tparts.push(allColors ? allColors.subarray(componentStart, componentEnd) : null);\n\t}\n\treturn fingerprintViews(parts, salt);\n}\n\n/**\n * Reconstructs world-unit float32 positions from int16 quantized values.\n *\n * Mirrors the encoder formula: `world = origin + (q + 32767) * scale`. Selva keeps one coordinate\n * frame end to end (the Three scene is Rhino's Z-up frame — see `../coordinate-transform.ts`), so\n * vertices pass through unrotated. `_applyCoordinateTransform` is retained for call-site\n * compatibility and no longer changes the output.\n */\nfunction dequantizeInt16(\n\tq: Int16Array,\n\torigin: [number, number, number],\n\tscale: [number, number, number],\n\t_applyCoordinateTransform: boolean\n): Float32Array {\n\tconst out = new Float32Array(q.length);\n\tconst ox = origin[0];\n\tconst oy = origin[1];\n\tconst oz = origin[2];\n\tconst sx = scale[0];\n\tconst sy = scale[1];\n\tconst sz = scale[2];\n\n\tfor (let i = 0; i < q.length; i += 3) {\n\t\tout[i] = ox + (q[i]! + 32767) * sx;\n\t\tout[i + 1] = oy + (q[i + 1]! + 32767) * sy;\n\t\tout[i + 2] = oz + (q[i + 2]! + 32767) * sz;\n\t}\n\n\treturn out;\n}\n\n/**\n * For float32 batches the parser's view is already in the scene frame (Rhino Z-up), so we pass it\n * through without copying. `_applyCoordinateTransform` is retained for call-site compatibility and\n * no longer rotates.\n */\nfunction maybeRotateFloat32Vertices(\n\tvertices: Float32Array,\n\t_applyCoordinateTransform: boolean\n): Float32Array {\n\treturn vertices;\n}\n\n// ============================================================================\n// OFF-THREAD ASSEMBLY (audit P2 — docs/plans/5.display-pipeline-performance-audit.md)\n// ============================================================================\n\n/**\n * Below this triangle count the synchronous path finishes in ~10 ms — a worker round-trip (two\n * buffer copies + wake) isn't worth it. Above it, delta-decode + dequantize + merge + normals run\n * in the worker and the main thread only wraps returned buffers (or reuses cached geometries).\n */\nconst ASSEMBLY_WORKER_MIN_TRIANGLES = 50_000;\n\ninterface PendingAssembly {\n\tresolve: (geometries: AssembledGeometry[]) => void;\n\treject: (error: Error) => void;\n}\n\nlet assemblyWorker: Worker | null | undefined; // undefined = not yet tried, null = unavailable\nconst pendingAssemblies = new Map<number, PendingAssembly>();\nlet nextAssemblyRequestId = 1;\n\nfunction getAssemblyWorker(): Worker | null {\n\tif (assemblyWorker !== undefined) return assemblyWorker;\n\tif (\n\t\ttypeof Worker === 'undefined' ||\n\t\ttypeof Blob === 'undefined' ||\n\t\ttypeof URL === 'undefined' ||\n\t\ttypeof URL.createObjectURL !== 'function'\n\t) {\n\t\tassemblyWorker = null;\n\t\treturn null;\n\t}\n\ttry {\n\t\t// Blob URL keeps the library bundler-agnostic; deliberately never revoked (see edges.ts).\n\t\tconst url = URL.createObjectURL(\n\t\t\tnew Blob([meshAssemblyWorkerSource()], { type: 'text/javascript' })\n\t\t);\n\t\tconst worker = new Worker(url);\n\t\tworker.onmessage = (event: MessageEvent) => {\n\t\t\tconst { id, geometries, error } = event.data as {\n\t\t\t\tid: number;\n\t\t\t\tgeometries?: AssembledGeometry[];\n\t\t\t\terror?: string;\n\t\t\t};\n\t\t\tconst pending = pendingAssemblies.get(id);\n\t\t\tif (!pending) return;\n\t\t\tpendingAssemblies.delete(id);\n\t\t\tif (geometries) pending.resolve(geometries);\n\t\t\telse pending.reject(new Error(error ?? 'mesh assembly failed in worker'));\n\t\t};\n\t\tworker.onerror = () => {\n\t\t\tfor (const pending of pendingAssemblies.values()) {\n\t\t\t\tpending.reject(new Error('mesh assembly worker crashed'));\n\t\t\t}\n\t\t\tpendingAssemblies.clear();\n\t\t\tworker.terminate();\n\t\t\tassemblyWorker = null; // don't retry this session — callers fall back to the sync path\n\t\t};\n\t\tassemblyWorker = worker;\n\t} catch {\n\t\tassemblyWorker = null;\n\t}\n\treturn assemblyWorker;\n}\n\nfunction requestAssembly(\n\tworker: Worker,\n\tinput: unknown,\n\ttransfer: Transferable[]\n): Promise<AssembledGeometry[]> {\n\treturn new Promise<AssembledGeometry[]>((resolve, reject) => {\n\t\tconst id = nextAssemblyRequestId++;\n\t\tpendingAssemblies.set(id, { resolve, reject });\n\t\tworker.postMessage({ id, input }, transfer);\n\t});\n}\n\ninterface WorkerPathOptions {\n\tmergeByMaterial: boolean;\n\tapplyTransforms: boolean;\n\tdebug: boolean;\n\tmaterial?: MaterialAppearanceOptions;\n\tfallback?: BuildOptions['fallback'];\n}\n\n/**\n * Attempt the off-thread build. Returns the finished meshes, or `null` when the worker path\n * doesn't apply (no Worker, small batch, worker crashed) — the caller then runs the synchronous\n * path. Malformed-blob/metadata errors throw, matching the entry points' contract either way.\n *\n * Cache interplay: the worker always assembles and fingerprints every geometry (decode is\n * whole-array work anyway), and the main thread prefers an existing cached geometry over the\n * returned buffers — so cache hits skip the GPU re-upload, and the wasted worker CPU for them is\n * off the critical path by definition.\n */\nasync function tryBuildViaWorker(\n\tinput: ArrayBuffer | Uint8Array | string,\n\topts: WorkerPathOptions\n): Promise<THREE.Mesh[] | null> {\n\tif (typeof Worker === 'undefined') return null;\n\n\tconst raw = parseBinaryMeshBatchRaw(input);\n\tif (raw.indexData.length / 3 < ASSEMBLY_WORKER_MIN_TRIANGLES) return null;\n\tconst worker = getAssemblyWorker();\n\tif (!worker) return null;\n\n\tconst materialsSrc = raw.metadata.materials ?? opts.fallback?.materials ?? [];\n\tconst groups = raw.metadata.groups ?? opts.fallback?.groups ?? [];\n\tconst sourceComponentId = opts.fallback?.sourceComponentId ?? raw.metadata.sourceComponentId;\n\tvalidateGroupMetadata(groups, materialsSrc.length, raw.vertexCount, raw.indexData.length);\n\n\t// Same job branching as buildMeshesFromParsed, with a parallel ref list to wrap results.\n\tinterface JobRef {\n\t\tkind: 'merged' | 'single';\n\t\tgroup: MaterialGroup;\n\t\tmeshMeta?: MeshMetadata;\n\t}\n\tconst windowOf = (m: MeshMetadata): AssemblyWindow => ({\n\t\tvertexStart: m.vertexStart,\n\t\tvertexCount: m.vertexCount,\n\t\tindexStart: m.indexStart,\n\t\tindexCount: m.indexCount\n\t});\n\tconst jobs: AssemblyJob[] = [];\n\tconst jobRefs: JobRef[] = [];\n\tfor (const group of groups) {\n\t\tif (opts.mergeByMaterial && group.meshes.length > 1) {\n\t\t\tjobs.push({ kind: 'merged', windows: group.meshes.map(windowOf) });\n\t\t\tjobRefs.push({ kind: 'merged', group });\n\t\t} else {\n\t\t\tfor (const meshMeta of group.meshes) {\n\t\t\t\tjobs.push({ kind: 'single', windows: [windowOf(meshMeta)] });\n\t\t\t\tjobRefs.push({ kind: 'single', group, meshMeta });\n\t\t\t}\n\t\t}\n\t}\n\n\t// The geometry views alias the caller's blob buffer — copy them so the transfer can't detach\n\t// it. UV/color arrays are parser-owned fresh copies and transfer directly.\n\tconst vertexData = raw.vertexData.slice();\n\tconst indexData = raw.indexData.slice();\n\tconst transfer: Transferable[] = [vertexData.buffer, indexData.buffer];\n\tif (raw.uvs) transfer.push(raw.uvs.buffer);\n\tif (raw.colors) transfer.push(raw.colors.buffer);\n\n\tlet assembled: AssembledGeometry[];\n\ttry {\n\t\tassembled = await requestAssembly(\n\t\t\tworker,\n\t\t\t{\n\t\t\t\tvertexData,\n\t\t\t\tisFloat32: raw.isFloat32,\n\t\t\t\tdeltaEncoded: raw.deltaEncoded,\n\t\t\t\torigin: raw.origin,\n\t\t\t\tscale: raw.scale,\n\t\t\t\tindexData,\n\t\t\t\tuvs: raw.uvs,\n\t\t\t\tcolors: raw.colors,\n\t\t\t\tjobs\n\t\t\t},\n\t\t\ttransfer\n\t\t);\n\t} catch (error) {\n\t\tgetLogger().warn('Mesh assembly worker failed; falling back to main-thread parse.', error);\n\t\treturn null;\n\t}\n\tif (assembled.length !== jobs.length) return null; // defensive: protocol mismatch → sync path\n\n\tconst materials = materialsSrc.map((m) =>\n\t\tcreateMaterial(m, { vertexColors: raw.colors != null, appearance: opts.material })\n\t);\n\n\tconst meshes: THREE.Mesh[] = [];\n\tfor (let i = 0; i < assembled.length; i++) {\n\t\tconst result = assembled[i]!;\n\t\tconst ref = jobRefs[i]!;\n\n\t\tlet geometry = geometryCacheGet(result.key);\n\t\tif (!geometry) {\n\t\t\tgeometry = new THREE.BufferGeometry();\n\t\t\tgeometry.setAttribute('position', new THREE.BufferAttribute(result.positions, 3));\n\t\t\tgeometry.setAttribute('normal', new THREE.BufferAttribute(result.normals, 3));\n\t\t\tgeometry.setIndex(new THREE.BufferAttribute(result.indices, 1));\n\t\t\tif (result.uvs) geometry.setAttribute('uv', new THREE.BufferAttribute(result.uvs, 2));\n\t\t\tif (result.colors) {\n\t\t\t\tgeometry.setAttribute('color', new THREE.BufferAttribute(result.colors, 3, true));\n\t\t\t}\n\t\t\tgeometryCachePut(result.key, geometry);\n\t\t}\n\n\t\tconst mesh =\n\t\t\tref.kind === 'merged'\n\t\t\t\t? finalizeMergedMesh(geometry, ref.group, materials)\n\t\t\t\t: finalizeSingleMesh(geometry, ref.meshMeta!, ref.group, materials);\n\t\tmesh.userData.sourceComponentId = sourceComponentId ?? null;\n\t\tmeshes.push(mesh);\n\t}\n\n\tif (opts.debug) {\n\t\tgetLogger().debug(\n\t\t\t`Mesh batch assembled off-thread: ${meshes.length} meshes, ${raw.indexData.length / 3} triangles`\n\t\t);\n\t}\n\treturn meshes;\n}\n\n// ============================================================================\n// MATERIAL CONSTRUCTION\n// ============================================================================\n\n// A near-pure metal has no diffuse response, so under the low-IBL 'technical' look it goes flat and\n// reads as painted card. Real architectural sheet metal is coated, not a bare mirror — so materials\n// that are meaningfully metallic get a thin satin clearcoat: a glossy dielectric layer whose\n// highlight and environment response are independent of the base metalness/envMap, so folds catch\n// light even when the IBL is dialed down. Below this metalness the material is treated as\n// plastic/matte and left untouched.\nconst METAL_CLEARCOAT_THRESHOLD = 0.5;\nconst METAL_CLEARCOAT = 0.5;\nconst METAL_CLEARCOAT_ROUGHNESS = 0.3;\n\nfunction createMaterial(\n\tmatData: SerializableMaterial,\n\toptions?: { vertexColors?: boolean; appearance?: MaterialAppearanceOptions }\n): THREE.MeshPhysicalMaterial {\n\tconst color = parseColor(matData.color);\n\tconst vertexColors = options?.vertexColors ?? false;\n\tconst appearance = options?.appearance;\n\n\tconst material = new THREE.MeshPhysicalMaterial({\n\t\tcolor,\n\t\tmetalness: matData.metalness,\n\t\troughness: matData.roughness,\n\t\topacity: matData.opacity,\n\t\ttransparent: matData.transparent,\n\t\tvertexColors,\n\t\t// Cull back faces for closed solids (crisper silhouette, less overdraw); keep both sides for\n\t\t// open surfaces. Caller-controlled since Rhino emits both — default DoubleSide is the safe read.\n\t\tside: appearance?.cullBackfaces ? THREE.FrontSide : THREE.DoubleSide,\n\t\t// Reduced polygon offset to minimize artifacts\n\t\t// Only use minimal offset to prevent z-fighting on coplanar faces\n\t\tpolygonOffset: true,\n\t\tpolygonOffsetFactor: 0.5,\n\t\tpolygonOffsetUnits: 0.5,\n\t\t// Improve depth rendering\n\t\tdepthWrite: true,\n\t\tdepthTest: true\n\t});\n\n\t// HDR image-based-lighting reflection strength. Left at three's default (1) unless the caller\n\t// dials it: <1 flattens reflections toward a matte/technical read, >1 pushes a glossier look.\n\tif (appearance?.envMapIntensity != null) {\n\t\tmaterial.envMapIntensity = appearance.envMapIntensity;\n\t}\n\n\t// Metals get a satin clearcoat so coated sheet metal reads as coated, not flat, under low IBL\n\t// (see the constants above). Plastics/matte fall below the threshold and stay bare.\n\tif (matData.metalness > METAL_CLEARCOAT_THRESHOLD) {\n\t\tmaterial.clearcoat = METAL_CLEARCOAT;\n\t\tmaterial.clearcoatRoughness = METAL_CLEARCOAT_ROUGHNESS;\n\t}\n\n\t// Vertex colors arrive as raw sRGB bytes, but three's vertex-color path multiplies them into the\n\t// (linear) working space with no decode — so they render washed out. Patch the vertex shader to\n\t// sRGB→linear decode `color` before use. Only meshes with real vertex colors take this path.\n\tif (vertexColors) {\n\t\tapplyVertexColorSRGBDecode(material);\n\t}\n\n\t// Texture loading is async (image decode); the cache assigns `material.map` when ready and\n\t// flags needsUpdate, so the mesh renders untextured for at most the first frames. Hash-keyed\n\t// asset URLs are immutable, so each texture is fetched and decoded once per session.\n\tif (matData.map) {\n\t\tapplyTextureMap(material, matData.map);\n\t}\n\n\treturn material;\n}\n\n/**\n * Patch a material's vertex shader to decode its per-vertex `color` attribute from sRGB to linear.\n * three.js uploads vertex colors verbatim and its `color_vertex` chunk multiplies them straight into\n * the linear working color space (unlike textures, which carry a `colorSpace` and get decoded) — so\n * sRGB-authored vertex colors render too bright without this. Done in the shader (not a CPU pass over\n * the buffer) to keep the hot per-solve parse cheap; the decode is a handful of GPU ops per vertex.\n */\nfunction applyVertexColorSRGBDecode(material: THREE.Material): void {\n\tmaterial.onBeforeCompile = (shader) => {\n\t\tshader.vertexShader = shader.vertexShader.replace(\n\t\t\t'#include <color_vertex>',\n\t\t\t`#include <color_vertex>\n\t\t\t#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )\n\t\t\t\tvColor.rgb = mix(\n\t\t\t\t\tvColor.rgb / 12.92,\n\t\t\t\t\tpow( ( vColor.rgb + 0.055 ) / 1.055, vec3( 2.4 ) ),\n\t\t\t\t\tstep( vec3( 0.04045 ), vColor.rgb )\n\t\t\t\t);\n\t\t\t#endif`\n\t\t);\n\t};\n}\n\n// ============================================================================\n// MESH CONSTRUCTION\n// ============================================================================\n\n/**\n * Creates a merged mesh from multiple meshes sharing the same material.\n *\n * Indices in the parser output already reference offsets into the combined vertex array (the C#\n * pipeline rebases per-mesh local indices into combined-array indices when assembling the batch).\n * For merged meshes we copy the relevant slices into a fresh contiguous buffer and shift indices\n * to match the new layout.\n */\nfunction createMergedMesh(\n\tgroup: MaterialGroup,\n\tallVertices: Float32Array,\n\tallIndices: Uint16Array | Uint32Array,\n\tmaterials: THREE.Material[],\n\tallUvs: Float32Array | null = null,\n\tallColors: Uint8Array | null = null\n): THREE.Mesh {\n\t// Cross-solve reuse (audit P1): identical content → same BufferGeometry object, skipping the\n\t// merge copies, computeVertexNormals, and the GPU re-upload entirely.\n\tconst cacheKey = geometryContentKey(\n\t\t'merged',\n\t\tgroup.meshes,\n\t\tallVertices,\n\t\tallIndices,\n\t\tallUvs,\n\t\tallColors\n\t);\n\tlet geometry = geometryCacheGet(cacheKey);\n\n\tif (!geometry) {\n\t\tlet totalVertexCount = 0;\n\t\tlet totalIndexCount = 0;\n\t\tfor (const meshMeta of group.meshes) {\n\t\t\ttotalVertexCount += meshMeta.vertexCount;\n\t\t\ttotalIndexCount += meshMeta.indexCount;\n\t\t}\n\n\t\tconst mergedVertices = new Float32Array(totalVertexCount * 3);\n\t\tconst mergedIndices = new Uint32Array(totalIndexCount);\n\t\tconst mergedUvs = allUvs ? new Float32Array(totalVertexCount * 2) : null;\n\t\tconst mergedColors = allColors ? new Uint8Array(totalVertexCount * 3) : null;\n\n\t\tlet vertexWriteCursor = 0;\n\t\tlet indexWriteCursor = 0;\n\n\t\tfor (const meshMeta of group.meshes) {\n\t\t\tconst componentStart = meshMeta.vertexStart * 3;\n\t\t\tconst componentLen = meshMeta.vertexCount * 3;\n\t\t\tmergedVertices.set(\n\t\t\t\tallVertices.subarray(componentStart, componentStart + componentLen),\n\t\t\t\tvertexWriteCursor * 3\n\t\t\t);\n\n\t\t\tif (mergedUvs && allUvs) {\n\t\t\t\tconst uvStart = meshMeta.vertexStart * 2;\n\t\t\t\tmergedUvs.set(\n\t\t\t\t\tallUvs.subarray(uvStart, uvStart + meshMeta.vertexCount * 2),\n\t\t\t\t\tvertexWriteCursor * 2\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (mergedColors && allColors) {\n\t\t\t\tmergedColors.set(\n\t\t\t\t\tallColors.subarray(componentStart, componentStart + componentLen),\n\t\t\t\t\tvertexWriteCursor * 3\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst indicesSlice = allIndices.subarray(\n\t\t\t\tmeshMeta.indexStart,\n\t\t\t\tmeshMeta.indexStart + meshMeta.indexCount\n\t\t\t);\n\t\t\tconst indexShift = vertexWriteCursor - meshMeta.vertexStart;\n\t\t\tconst windowStart = meshMeta.vertexStart;\n\t\t\tconst windowEnd = meshMeta.vertexStart + meshMeta.vertexCount;\n\t\t\tfor (let i = 0; i < indicesSlice.length; i++) {\n\t\t\t\tconst indexValue = indicesSlice[i]!;\n\t\t\t\tif (indexValue < windowStart || indexValue >= windowEnd) {\n\t\t\t\t\tthrow indexOutOfWindow(indexValue, meshMeta);\n\t\t\t\t}\n\t\t\t\tmergedIndices[indexWriteCursor + i] = indexValue + indexShift;\n\t\t\t}\n\n\t\t\tvertexWriteCursor += meshMeta.vertexCount;\n\t\t\tindexWriteCursor += meshMeta.indexCount;\n\t\t}\n\n\t\tgeometry = new THREE.BufferGeometry();\n\t\tgeometry.setAttribute('position', new THREE.BufferAttribute(mergedVertices, 3));\n\t\tgeometry.setIndex(new THREE.BufferAttribute(mergedIndices, 1));\n\t\tif (mergedUvs) {\n\t\t\tgeometry.setAttribute('uv', new THREE.BufferAttribute(mergedUvs, 2));\n\t\t}\n\t\tif (mergedColors) {\n\t\t\tgeometry.setAttribute('color', new THREE.BufferAttribute(mergedColors, 3, true));\n\t\t}\n\t\tgeometry.computeVertexNormals();\n\t\tgeometryCachePut(cacheKey, geometry);\n\t}\n\n\treturn finalizeMergedMesh(geometry, group, materials);\n}\n\n/** Wraps a merged group's geometry (built or cache-hit) in its THREE.Mesh with identity/userData. */\nfunction finalizeMergedMesh(\n\tgeometry: THREE.BufferGeometry,\n\tgroup: MaterialGroup,\n\tmaterials: THREE.Material[]\n): THREE.Mesh {\n\tconst threeMesh = new THREE.Mesh(geometry, materials[group.materialId]);\n\tconst firstMesh = group.meshes[0];\n\tconst meshNames = group.meshes.map((m) => m.name).filter((name) => name && name.length > 0);\n\tthreeMesh.name = meshNames.length > 0 ? meshNames[0]! : `merged_material_${group.materialId}`;\n\tthreeMesh.castShadow = true;\n\tthreeMesh.receiveShadow = true;\n\n\tthreeMesh.userData = {\n\t\tsource: 'compute',\n\t\tname: threeMesh.name,\n\t\tlayer: firstMesh?.layer ?? '',\n\t\toriginalIndex: firstMesh?.originalIndex ?? 0,\n\t\tmetadata: firstMesh?.metadata ?? {},\n\t\tmergedFrom: group.meshes.slice(1).map((m) => ({\n\t\t\tname: m.name,\n\t\t\tlayer: m.layer,\n\t\t\toriginalIndex: m.originalIndex\n\t\t}))\n\t};\n\n\treturn threeMesh;\n}\n\n/**\n * Creates individual meshes from a material group. Each mesh's indices are rebased so they\n * address its own local vertex slice starting from 0.\n */\nfunction createIndividualMeshes(\n\tgroup: MaterialGroup,\n\tallVertices: Float32Array,\n\tallIndices: Uint16Array | Uint32Array,\n\tmaterials: THREE.Material[],\n\tallUvs: Float32Array | null = null,\n\tallColors: Uint8Array | null = null\n): THREE.Mesh[] {\n\tconst meshes: THREE.Mesh[] = [];\n\n\tfor (const meshMeta of group.meshes) {\n\t\tconst componentStart = meshMeta.vertexStart * 3;\n\t\tconst componentLen = meshMeta.vertexCount * 3;\n\n\t\t// Cross-solve reuse (audit P1) — see createMergedMesh.\n\t\tconst cacheKey = geometryContentKey(\n\t\t\t'single',\n\t\t\t[meshMeta],\n\t\t\tallVertices,\n\t\t\tallIndices,\n\t\t\tallUvs,\n\t\t\tallColors\n\t\t);\n\t\tlet geometry = geometryCacheGet(cacheKey);\n\n\t\tif (!geometry) {\n\t\t\t// `subarray` returns a view; copy via `slice` so the BufferAttribute owns its memory and\n\t\t\t// downstream code (dispose/reuse) can't surprise us by sharing the parser's buffer.\n\t\t\tconst vertices = allVertices.slice(componentStart, componentStart + componentLen);\n\n\t\t\tconst indicesSlice = allIndices.subarray(\n\t\t\t\tmeshMeta.indexStart,\n\t\t\t\tmeshMeta.indexStart + meshMeta.indexCount\n\t\t\t);\n\t\t\tconst rebasedIndices = new Uint32Array(indicesSlice.length);\n\t\t\tconst baseIndex = meshMeta.vertexStart;\n\t\t\tconst windowEnd = meshMeta.vertexStart + meshMeta.vertexCount;\n\t\t\tfor (let i = 0; i < indicesSlice.length; i++) {\n\t\t\t\tconst indexValue = indicesSlice[i]!;\n\t\t\t\tif (indexValue < baseIndex || indexValue >= windowEnd) {\n\t\t\t\t\tthrow indexOutOfWindow(indexValue, meshMeta);\n\t\t\t\t}\n\t\t\t\trebasedIndices[i] = indexValue - baseIndex;\n\t\t\t}\n\n\t\t\tgeometry = new THREE.BufferGeometry();\n\t\t\tgeometry.setAttribute('position', new THREE.BufferAttribute(vertices, 3));\n\t\t\tgeometry.setIndex(new THREE.BufferAttribute(rebasedIndices, 1));\n\t\t\tif (allUvs) {\n\t\t\t\tconst uvStart = meshMeta.vertexStart * 2;\n\t\t\t\tconst uvs = allUvs.slice(uvStart, uvStart + meshMeta.vertexCount * 2);\n\t\t\t\tgeometry.setAttribute('uv', new THREE.BufferAttribute(uvs, 2));\n\t\t\t}\n\t\t\tif (allColors) {\n\t\t\t\tconst colors = allColors.slice(componentStart, componentStart + componentLen);\n\t\t\t\tgeometry.setAttribute('color', new THREE.BufferAttribute(colors, 3, true));\n\t\t\t}\n\t\t\tgeometry.computeVertexNormals();\n\t\t\tgeometryCachePut(cacheKey, geometry);\n\t\t}\n\n\t\tmeshes.push(finalizeSingleMesh(geometry, meshMeta, group, materials));\n\t}\n\n\treturn meshes;\n}\n\n/** Wraps a single mesh's geometry (built or cache-hit) in its THREE.Mesh with identity/userData. */\nfunction finalizeSingleMesh(\n\tgeometry: THREE.BufferGeometry,\n\tmeshMeta: MeshMetadata,\n\tgroup: MaterialGroup,\n\tmaterials: THREE.Material[]\n): THREE.Mesh {\n\tconst mesh = new THREE.Mesh(geometry, materials[group.materialId]);\n\tmesh.name = meshMeta.name;\n\tmesh.userData = {\n\t\tsource: 'compute',\n\t\tname: meshMeta.name,\n\t\tlayer: meshMeta.layer ?? '',\n\t\toriginalIndex: meshMeta.originalIndex,\n\t\tmetadata: meshMeta.metadata ?? {}\n\t};\n\tmesh.castShadow = true;\n\tmesh.receiveShadow = true;\n\treturn mesh;\n}\n\n// ============================================================================\n// DEBUG HELPERS\n// ============================================================================\n\nfunction approximateBase64DecodedBytes(base64: string): number {\n\treturn Math.floor((base64.length * 3) / 4);\n}\n","import * as THREE from 'three';\n\nimport { applyOffset, computeCombinedBoundingBox } from '../threejs/three-helpers.js';\nimport { getLogger } from '@/core';\n\nimport { parseDisplayItems } from '../display-items/display-items-parser.js';\n\nimport { parseMeshBatchObject } from './batch-parser.js';\n\nimport type { DataItem, GrasshopperComputeResponse } from '@/features/grasshopper/types';\nimport type { DisplayBatch, MeshExtractionOptions, MeshBatchParsingOptions } from './types.js';\nimport type { RhinoModule } from 'rhino3dm';\n\n// Constants\n\n/**\n * Metres per model unit, keyed by Rhino `UnitSystem` name (the `modelunits` string on the compute\n * response). Imperial factors are the exact international definitions (1 in = 0.0254 m,\n * 1 ft = 0.3048 m, 1 mi = 1609.344 m). Units not in this table scale 1 and log a one-time warning\n * — see {@link getScaleFactor}.\n */\nexport const SCALE_FACTORS: Record<string, number> = {\n\t// Metric\n\tAngstroms: 1e-10,\n\tNanometers: 1e-9,\n\tMicrons: 1e-6,\n\tMillimeters: 1e-3,\n\tCentimeters: 1e-2,\n\tDecimeters: 0.1,\n\tMeters: 1,\n\tDekameters: 10,\n\tHectometers: 100,\n\tKilometers: 1000,\n\tMegameters: 1e6,\n\tGigameters: 1e9,\n\t// Imperial (exact: 1 inch = 0.0254 m)\n\tMicroinches: 0.0254e-6,\n\tMils: 0.0254e-3,\n\tInches: 0.0254,\n\tFeet: 0.3048,\n\tYards: 0.9144,\n\tMiles: 1609.344,\n\tNauticalMiles: 1852\n};\n\n/**\n * Wire `type` token identifying a Selva Display payload. The real wire value is namespaced (e.g.\n * `Selva.GH.Features.Display.Services.DisplayBatch`), so dispatch matches exact dot-separated\n * tokens — never substrings, which would misroute any unrelated type merely containing \"Display\".\n */\nconst DISPLAY_COMPONENT_TYPE = 'Display';\nconst DISPLAY_BATCH_TYPE = 'DisplayBatch';\n\n/**\n * True when a wire `type` denotes a Display payload: one of its dot-separated tokens is exactly\n * `Display` or `DisplayBatch`. Matches the bare `Display` used by older servers and the namespaced\n * `Selva.GH.Features.Display.Services.DisplayBatch`, but not e.g. `System.DisplayText`.\n */\nfunction isDisplayItemType(type: string): boolean {\n\tconst tokens = type.split('.');\n\treturn tokens.includes(DISPLAY_COMPONENT_TYPE) || tokens.includes(DISPLAY_BATCH_TYPE);\n}\n\n/** Unknown-unit names already warned about, so a per-solve parse doesn't spam the log. */\nconst warnedUnknownUnits = new Set<string>();\n\n/**\n * Extracts and processes display meshes from a ComputePointerResponse using the Grasshopper WebDisplay component.\n *\n * This is the primary entry point for extracting mesh geometry from Grasshopper compute responses.\n * It handles all aspects of mesh processing: decompression, coordinate transformation, scaling, and positioning.\n *\n * **Note:** The entire pipeline (base64 decode, inflate, dequantization, mesh construction) runs\n * synchronously on the calling thread — large batches will block the UI for their duration. The\n * function is `async` only so its shape can stay stable if parsing moves off-thread later.\n *\n * @param data - The ComputePointerResponse containing Grasshopper output trees.\n * @param options - Configuration for mesh extraction and parsing behavior. All options are optional with sensible defaults.\n * @returns Promise resolving to array of THREE.Mesh objects (may be empty).\n * @throws Rethrows unexpected errors after attempting to dispose any created meshes.\n *\n * @remarks\n * - Only works with the WebDisplay component of GHHeadless.\n * - Requires changes to Rhino.Compute (see https://github.com/TheVessen/compute.rhino3d).\n * - Provides a performant way to display mesh data in Three.js.\n * - All decoding is synchronous on the main thread; there is no Web Worker offload today.\n * - Supports mesh metadata (names, user data) if provided in the compute response.\n *\n * @internal Internal helper: high-level extraction remains public via visualization module, but this\n * function is considered internal implementation detail for mesh extraction.\n *\n * @example\n * ```ts\n * // Simple usage with defaults (all processing enabled)\n * const meshes = await getThreeMeshesFromComputeResponse(response);\n *\n * // With debugging enabled\n * const meshes = await getThreeMeshesFromComputeResponse(response, { debug: true });\n *\n * // Opt in to seating the model on the grid instead of using its Rhino coordinates\n * const meshes = await getThreeMeshesFromComputeResponse(response, {\n * debug: true,\n * allowScaling: true,\n * allowAutoPosition: true,\n * parsing: {\n * mergeByMaterial: false,\n * applyTransforms: true,\n * debug: true,\n * },\n * });\n * ```\n */\nexport async function getThreeMeshesFromComputeResponse(\n\tdata: GrasshopperComputeResponse,\n\toptions?: MeshExtractionOptions\n): Promise<THREE.Object3D[]> {\n\tconst startTime = performance.now();\n\tconst objects: THREE.Object3D[] = [];\n\n\tconst {\n\t\tallowScaling = true,\n\t\t// Defaults to FALSE: geometry renders where Rhino puts it. Grounding used to be on by\n\t\t// default here but was never applied on the WebSocket preview path, so the same definition\n\t\t// sat at a different height depending on transport. Rhino coordinates are the honest frame —\n\t\t// the viewer agrees with the Grasshopper definition, and picked/measured coordinates match.\n\t\tallowAutoPosition = false,\n\t\tgroundAxis = 'z',\n\t\trhino,\n\t\tdebug = false,\n\t\tparsing: parsingOptions = {}\n\t} = options ?? {};\n\n\ttry {\n\t\tconst scaleFactor = allowScaling ? getScaleFactor(data.modelunits) : 1;\n\t\tawait extractDisplayFromData(data, objects, scaleFactor, parsingOptions, rhino, debug);\n\n\t\tif (allowAutoPosition) {\n\t\t\tapplyGroundOffset(objects, groundAxis);\n\t\t}\n\n\t\treturn objects;\n\t} catch (error) {\n\t\thandleError(error, objects);\n\t\tthrow error;\n\t} finally {\n\t\tif (debug) {\n\t\t\tlogProcessingTime(startTime);\n\t\t}\n\t}\n}\n\n/**\n * Gets the metres-per-unit scale factor for the given Rhino unit name. Unknown units fall back to\n * 1 (no scaling) with a one-time warning per unit name — a kilometers model rendering 1000× off\n * should at least say why.\n */\nfunction getScaleFactor(modelUnits: string): number {\n\tconst factor = SCALE_FACTORS[modelUnits];\n\tif (factor !== undefined) {\n\t\treturn factor;\n\t}\n\tif (!warnedUnknownUnits.has(modelUnits)) {\n\t\twarnedUnknownUnits.add(modelUnits);\n\t\tgetLogger().warn(\n\t\t\t`Unknown Rhino model unit \"${modelUnits}\" — geometry will not be scaled (factor 1). ` +\n\t\t\t\t`Known units: ${Object.keys(SCALE_FACTORS).join(', ')}.`\n\t\t);\n\t}\n\treturn 1;\n}\n\n/**\n * Extracts meshes and non-mesh display items (curves, points) from compute response data.\n */\nasync function extractDisplayFromData(\n\tdata: GrasshopperComputeResponse,\n\tobjects: THREE.Object3D[],\n\tscaleFactor: number,\n\tparsingOptions: MeshBatchParsingOptions,\n\trhino: RhinoModule | undefined,\n\tdebug: boolean\n): Promise<void> {\n\tfor (const value of data.values) {\n\t\tconst innerTree = value.InnerTree as { [key: string]: DataItem[] };\n\n\t\tfor (const path in innerTree) {\n\t\t\tconst branch = innerTree[path];\n\t\t\tif (!branch) continue;\n\n\t\t\tawait processDataBranch(branch, objects, scaleFactor, parsingOptions, rhino, debug);\n\t\t}\n\t}\n}\n\n/**\n * Processes a single data branch to extract a DisplayBatch's meshes (binary blob) and items\n * (curves/points JSON). Both get the same unit scale so they share one frame.\n */\nasync function processDataBranch(\n\tbranch: DataItem[],\n\tobjects: THREE.Object3D[],\n\tscaleFactor: number,\n\tparsingOptions: MeshBatchParsingOptions,\n\trhino: RhinoModule | undefined,\n\tdebug: boolean\n): Promise<void> {\n\tfor (const item of branch) {\n\t\tif (!isDisplayItemType(item.type)) continue;\n\n\t\tconst mergedParsingOptions = {\n\t\t\tmergeByMaterial: true,\n\t\t\tapplyTransforms: true,\n\t\t\tdebug: false,\n\t\t\t...parsingOptions\n\t\t};\n\n\t\t// Parse the JSON envelope once — it contains the full multi-MB base64 SLVA blob as a string,\n\t\t// so letting the mesh parser and the display-item extractor each parse it doubles both the\n\t\t// synchronous main-thread CPU and the transient string memory.\n\t\tconst batch = extractBatch(item.data);\n\t\tif (!batch) {\n\t\t\tgetLogger().error('Error parsing display batch envelope: invalid JSON');\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst batchMeshes = await parseMeshBatchObject(batch, mergedParsingOptions);\n\n\t\tconst batchItems = parseDisplayItems(batch.items, {\n\t\t\trhino,\n\t\t\tapplyTransforms: mergedParsingOptions.applyTransforms\n\t\t});\n\n\t\tconst batchObjects: THREE.Object3D[] = [...batchMeshes, ...batchItems];\n\n\t\tif (scaleFactor !== 1) {\n\t\t\tfor (const obj of batchObjects) {\n\t\t\t\tobj.scale.set(scaleFactor, scaleFactor, scaleFactor);\n\t\t\t}\n\t\t}\n\n\t\tobjects.push(...batchObjects);\n\n\t\tif (debug) {\n\t\t\tgetLogger().debug(\n\t\t\t\t`Extracted ${batchMeshes.length} meshes and ${batchItems.length} items from batch`\n\t\t\t);\n\t\t}\n\t}\n}\n\n/**\n * Resolves a raw DisplayBatch payload to a parsed object, tolerating either a parsed object or a\n * JSON string (the blob-bearing `item.data` is the same envelope the mesh parser reads).\n */\nfunction extractBatch(data: unknown): DisplayBatch | undefined {\n\treturn typeof data === 'string' ? safeParse(data) : (data as DisplayBatch | undefined);\n}\n\nfunction safeParse(s: string): DisplayBatch | undefined {\n\ttry {\n\t\treturn JSON.parse(s) as DisplayBatch;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Drops objects so their lowest point sits on the ground plane. `axis` is the scene's up axis —\n * `z` for the default Rhino frame geometry arrives in (see ../coordinate-transform.ts). Taking it\n * as a parameter rather than hardcoding `z` keeps grounding correct for a host that configures a\n * different `sceneUp`, where subtracting `min.z` would shove content sideways instead of down.\n */\nfunction applyGroundOffset(meshes: THREE.Object3D[], axis: 'x' | 'y' | 'z'): void {\n\tif (meshes.length === 0) return;\n\n\tconst combinedBoundingBox = computeCombinedBoundingBox(meshes);\n\tapplyOffset(meshes, combinedBoundingBox.min[axis], axis);\n}\n\n/**\n * Handles errors by disposing created objects and logging.\n */\nfunction handleError(error: unknown, meshes: THREE.Object3D[]): void {\n\tgetLogger().error('An unexpected error occurred:', error);\n\tdisposeMeshes(meshes);\n}\n\n/**\n * Disposes of all objects (meshes, lines, points) and their associated resources.\n */\nfunction disposeMeshes(meshes: THREE.Object3D[]): void {\n\tfor (const obj of meshes) {\n\t\tconst mesh = obj as Partial<THREE.Mesh> & THREE.Object3D;\n\t\tif (mesh.geometry) {\n\t\t\tmesh.geometry.dispose();\n\t\t}\n\n\t\tif (mesh.material) {\n\t\t\tif (Array.isArray(mesh.material)) {\n\t\t\t\tmesh.material.forEach((material) => material.dispose());\n\t\t\t} else {\n\t\t\t\tmesh.material.dispose();\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Logs the processing time for mesh extraction.\n */\nfunction logProcessingTime(startTime: number): void {\n\tconst elapsed = performance.now() - startTime;\n\tgetLogger().info('Time to process meshes:', `${elapsed.toFixed(2)}ms`);\n}\n"]}
|