From 5db271aeee26538b22704d3f275ef905d2858fe6 Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:26:21 +0300 Subject: [PATCH] Stream clustered BIM geometry with the full review viewer --- README.md | 1 + THIRD-PARTY-NOTICES.md | 3 + docs/viewer-performance-baseline.md | 284 ++++++++++ src/IOViewer.Cli/Program.cs | 24 +- src/IOViewer/Exporters/ClusterSourceWriter.cs | 222 ++++++++ src/IOViewer/Exporters/ViewerPayloadWriter.cs | 107 ++-- src/IOViewer/Exporters/ViewerProperties.cs | 51 ++ src/IOViewer/Viewer/build-mesh-pages.js | 326 +++++++++++ src/IOViewer/Viewer/dist/viewer.js | 360 ++++++------ src/IOViewer/Viewer/federate-mesh-pages.js | 76 +++ src/IOViewer/Viewer/pack-clusters.js | 116 ++++ src/IOViewer/Viewer/package-lock.json | 10 +- src/IOViewer/Viewer/package.json | 7 +- src/IOViewer/Viewer/serve-stream.js | 136 +++++ src/IOViewer/Viewer/src/data.js | 65 ++- src/IOViewer/Viewer/src/engine/chunks.js | 24 +- src/IOViewer/Viewer/src/model/clashTargets.js | 2 +- src/IOViewer/Viewer/src/model/schedule.js | 4 +- src/IOViewer/Viewer/src/nav/controls.js | 44 +- src/IOViewer/Viewer/src/stream/clusters.js | 53 ++ src/IOViewer/Viewer/src/stream/lod.js | 292 ++++++++++ src/IOViewer/Viewer/src/stream/lodShapes.js | 81 +++ src/IOViewer/Viewer/src/stream/main.js | 238 ++++++++ src/IOViewer/Viewer/src/stream/manifest.js | 32 ++ src/IOViewer/Viewer/src/stream/meshLod.js | 521 ++++++++++++++++++ src/IOViewer/Viewer/src/stream/meshPages.js | 106 ++++ src/IOViewer/Viewer/src/stream/meshScene.js | 153 +++++ src/IOViewer/Viewer/src/stream/meshSnap.js | 39 ++ src/IOViewer/Viewer/src/stream/meshTools.js | 254 +++++++++ src/IOViewer/Viewer/src/stream/pageFade.js | 9 + src/IOViewer/Viewer/src/stream/tile.js | 150 +++++ src/IOViewer/Viewer/src/stream/tileWorker.js | 11 + src/IOViewer/Viewer/src/tools/sectionCaps.js | 8 +- src/IOViewer/Viewer/src/ui/app.js | 17 +- src/IOViewer/Viewer/src/ui/properties.js | 38 +- src/IOViewer/Viewer/src/ui/tree.js | 6 +- src/IOViewer/Viewer/stream.html | 21 + .../Viewer/test/e2e/mesh-review.spec.js | 234 ++++++++ .../Viewer/test/e2e/navigation.spec.js | 57 ++ src/IOViewer/Viewer/test/perf/lod.perf.js | 128 +++++ .../Viewer/test/perf/mesh-approach.perf.js | 151 +++++ .../Viewer/test/perf/mesh-federation.perf.js | 85 +++ .../Viewer/test/perf/mesh-lod.perf.js | 103 ++++ .../Viewer/test/perf/mesh-profile.perf.js | 107 ++++ .../Viewer/test/perf/mesh-tools.perf.js | 208 +++++++ src/IOViewer/Viewer/test/perf/stream.perf.js | 99 ++++ src/IOViewer/Viewer/test/unit/lod.test.js | 35 ++ .../Viewer/test/unit/meshPages.test.js | 99 ++++ .../Viewer/test/unit/meshTools.test.js | 40 ++ src/IOViewer/Viewer/test/unit/stream.test.js | 99 ++++ tests/IOViewer.Tests/ClusterSourceTests.cs | 76 +++ .../TiledSyntheticModel.cs | 148 +++++ 52 files changed, 5265 insertions(+), 295 deletions(-) create mode 100644 src/IOViewer/Exporters/ClusterSourceWriter.cs create mode 100644 src/IOViewer/Exporters/ViewerProperties.cs create mode 100644 src/IOViewer/Viewer/build-mesh-pages.js create mode 100644 src/IOViewer/Viewer/federate-mesh-pages.js create mode 100644 src/IOViewer/Viewer/pack-clusters.js create mode 100644 src/IOViewer/Viewer/serve-stream.js create mode 100644 src/IOViewer/Viewer/src/stream/clusters.js create mode 100644 src/IOViewer/Viewer/src/stream/lod.js create mode 100644 src/IOViewer/Viewer/src/stream/lodShapes.js create mode 100644 src/IOViewer/Viewer/src/stream/main.js create mode 100644 src/IOViewer/Viewer/src/stream/manifest.js create mode 100644 src/IOViewer/Viewer/src/stream/meshLod.js create mode 100644 src/IOViewer/Viewer/src/stream/meshPages.js create mode 100644 src/IOViewer/Viewer/src/stream/meshScene.js create mode 100644 src/IOViewer/Viewer/src/stream/meshSnap.js create mode 100644 src/IOViewer/Viewer/src/stream/meshTools.js create mode 100644 src/IOViewer/Viewer/src/stream/pageFade.js create mode 100644 src/IOViewer/Viewer/src/stream/tile.js create mode 100644 src/IOViewer/Viewer/src/stream/tileWorker.js create mode 100644 src/IOViewer/Viewer/stream.html create mode 100644 src/IOViewer/Viewer/test/e2e/mesh-review.spec.js create mode 100644 src/IOViewer/Viewer/test/perf/lod.perf.js create mode 100644 src/IOViewer/Viewer/test/perf/mesh-approach.perf.js create mode 100644 src/IOViewer/Viewer/test/perf/mesh-federation.perf.js create mode 100644 src/IOViewer/Viewer/test/perf/mesh-lod.perf.js create mode 100644 src/IOViewer/Viewer/test/perf/mesh-profile.perf.js create mode 100644 src/IOViewer/Viewer/test/perf/mesh-tools.perf.js create mode 100644 src/IOViewer/Viewer/test/perf/stream.perf.js create mode 100644 src/IOViewer/Viewer/test/unit/lod.test.js create mode 100644 src/IOViewer/Viewer/test/unit/meshPages.test.js create mode 100644 src/IOViewer/Viewer/test/unit/meshTools.test.js create mode 100644 src/IOViewer/Viewer/test/unit/stream.test.js create mode 100644 tests/IOViewer.Tests/ClusterSourceTests.cs create mode 100644 tools/SyntheticModel/TiledSyntheticModel/TiledSyntheticModel.cs diff --git a/README.md b/README.md index 007c5f6..9c4e426 100644 --- a/README.md +++ b/README.md @@ -218,6 +218,7 @@ The documentation site with API references and guides is at diff --git a/docs/viewer-performance-baseline.md b/docs/viewer-performance-baseline.md index 11f4123..8d349cf 100644 --- a/docs/viewer-performance-baseline.md +++ b/docs/viewer-performance-baseline.md @@ -99,6 +99,290 @@ When evaluating instancing and picking, compare full-detail p95 with the same re p95 alongside its drawn share. The RTX full-detail range on the synthetic scene is too wide to establish a regression threshold from these runs. [Instancing and picking issue](https://github.com/IOExtend/IOViewer/issues/12) +## Multi-gigabyte synthetic model + +From the repository root, generate the spatially tiled industrial plant into an empty folder on a volume with more than +15 GB free. The generator uses a fixed seed to vary each vessel's geometry. It runs the standard HTML exporter on +one tile at a time and stops when the sum of the tile file sizes reaches 15,000,000,000 bytes. + +```powershell +dotnet run tools/SyntheticModel/TiledSyntheticModel/TiledSyntheticModel.cs -c Release -- D:/work/ioviewer-benchmarks/synthetic-industrial-15gb +``` + +Pass a byte target after the output folder for a smaller trial, for example `130000000` for two tiles. Each tile is also +a standalone HTML export with ordinary format-3 META, BIN and PROPS blocks. `manifest.json` lists the world-space +bounds and RTC offset of each tile in metres, together with global element ID ranges and file sizes. + +The reference generation contains 171 tiles, 1,094,148 elements and 1,186,056,432 triangles. The HTML tiles occupy +15,000,039,694 bytes in total, including base64 encoding and the viewer. Their decoded BIN blocks total 10,753,286,544 bytes. + +### Stream one scene + +#### Real IFC and RVT + +Export a native source with the regular CLI, using the `.ivmesh` extension for the offline builder. The same command +accepts an RVT path. Run from the repository root, then from `src/IOViewer/Viewer` for the Node.js commands. + +```powershell +dotnet run --project src/IOViewer.Cli -c Release -f net10.0 -- D:/models/model.ifc -o D:/models/model.ivmesh +Set-Location src/IOViewer/Viewer +npm ci +npm run pack-clusters -- D:/models/model.ivmesh D:/models/model-clusters +npm run stream -- D:/models/model-clusters +``` + +The CLI uses the same IFC and RVT adapters as standalone HTML. It writes rebased indexed mesh records to disk, so +the handoff does not need one HTML block for the scene. Import still constructs a `SceneDocument` in memory. Only +triangle meshes enter the cluster package. Triangle positions, material colors and opacity are carried over to the +full-resolution pages, including UVs when the source supplies them. Authored normals are transformed when present. +The builder derives missing normals from the triangles. The clustered and standalone viewers share the toolbar, +model tree, properties panel, context menu, navigation cube, perspective and orthographic controls. The section +tools clip drawing and picking and support filled cuts through closed meshes. Distance measurement snaps to +vertices, midpoints and edges on the original mesh. Display modes include materials, textures, white and +wireframe, with an opacity control. + +Current packages carry the original element IDs on leaf triangles and short names, categories, types, levels and +source IDs in the manifest when the importer supplies them. The tree can search and group these fields without +requesting any property blocks. The viewer traces the original geometry when selecting, so the displayed LOD +does not change the hit ID. It requests a property record once a single element is selected. Older annotated +packages still open with their existing tree fields. Re-export and repack them with the current CLI to carry +authored textures, grids, linked models, saved views, clashes, BCF and 4D. The `.ivmesh` export accepts the same +review inputs as HTML, including `--bcf`. Element visibility and isolation use exact page membership; when a +coarse page contains hidden elements the viewer draws its ready descendants instead. Linked model visibility, +BCF visibility and 4D playback use independent layers. `--geometry-only` builds omit element and review data +and retain navigation, clipping, measurement and geometry display modes. The streaming server limits the +manifest, including embedded review metadata and textures, to 64 MiB. + +The builder spatially partitions the input into leaves of at most 8,192 triangles while preserving the source triangles. +It uses meshoptimizer to construct simplified parent meshes bottom-up in groups of up to four. Parent pages carry +accumulated simplification errors in metres. The browser chooses a visible cut by projected error with hysteresis and +keeps drawing a parent until its visible children are resident. It switches the covered branch in a single frame +with one mesh per branch. A branch already refined stays split until its parent is within one pixel of error, +regardless of the adaptive threshold for admitting new detail. Parents +try simplification with locked borders first. Disconnected geometry may need relaxed or grid-based simplification to +fit a page, so borders at coarse levels need not be watertight. Full detail retains the original mesh. + +Initial framing uses triangle-weighted record centres around the core of the scene. **Fit all** uses the complete +model bounds. The 256 MiB budget accounts for resident and pending page buffers. The initial coarse pages are pinned. +The viewer requests the next detail level before it reaches the draw threshold and prefetches into a guard band +while moving. Speculative pages can use free space in the cache. A group blocking currently visible detail can evict +pages and takes precedence, with a bonus for groups near completion and for pages near the camera target. Upload work +is capped per frame. Each upload submits one triangle to initialize the page buffers before the full mesh becomes +eligible for display. Slow frames during movement or refinement can reduce framebuffer scale to 60% per axis. +The usual draw threshold returns when motion ends, and native resolution returns once the uploads finish. +Wheel zoom limits the apparent camera distance by the visible model radius in either projection. Perspective pan +and zoom use the depth of the picked point when it lies beyond the virtual camera target. A miss checks the viewport +centre to keep gestures responsive after the target has drifted close to the eye. +The benchmark holds detail responses to verify that the viewer continues to draw the selected region, then orbits the +model and follows a closer path through it. + +```powershell +$env:PERF_MESH_MODEL = 'D:/models/model-clusters' +$env:PERF_GPU = 'integrated' +npx playwright test --config playwright.perf.config.js mesh-lod.perf.js +``` + +The real-model check used Chromium 158 at 1920×1080 on the host described above. The camera orbited for 12 seconds +and moved through the core for 15 seconds. Results are one run per GPU and model. + +| Input | Triangles / total pages | GPU | Overview, s | Orbit p95 / max, ms | Close p95 / max, ms | Peak page buffers, MiB | +| --- | ---: | --- | ---: | ---: | ---: | ---: | +| 746 MB IFC | 21,380,864 / 5,424 | Radeon | 1.45 | 16.8 / 23.7 | 16.8 / 19.4 | 61.3 | +| 746 MB IFC | 21,380,864 / 5,424 | RTX 4080 | 1.09 | 16.8 / 21.2 | 16.8 / 19.5 | 61.1 | +| 931 MB RVT | 7,755,320 / 1,943 | Radeon | 1.18 | 16.8 / 33.3 | 50.0 / 116.7 | 256.0 | +| 931 MB RVT | 7,755,320 / 1,943 | RTX 4080 | 1.00 | 16.8 / 50.0 | 16.8 / 23.2 | 256.0 | + +Both hierarchies retained all triangles returned by their adapters. The RVT adapter reported 3,157 elements without +drawable geometry and 33 with potentially missing parts. Import and handoff took around 21 seconds for the IFC and +7 minutes 26 seconds for the RVT. The measurements in the table start at browser navigation to prepared data. + +#### Close RVT profile + +The second traversal can still request pages. The third traversal holds new requests after the pending pages finish +and checks that the browser neither downloads nor uploads pages during that route. The report includes GPU time +from WebGL disjoint timer queries, CPU staging and submission times, and physical framebuffer scale. + +~~~powershell +$env:PERF_MESH_PROFILE_MODEL = 'D:/models/rvt-clusters' +$env:PERF_GPU = 'integrated' +$env:PERF_MESH_NATIVE_PIXELS = '1' +$env:PERF_LABEL = 'rvt-native' +npx playwright test --config playwright.perf.config.js mesh-profile +Remove-Item Env:PERF_MESH_NATIVE_PIXELS +$env:PERF_LABEL = 'rvt-adaptive' +npx playwright test --config playwright.perf.config.js mesh-profile +~~~ + +The 931 MB RVT, Chromium at 1920×1080 on Radeon, one 15-second run per phase and mode. + +| Route | Frame p95, native / adaptive, ms | GPU p95, native / adaptive, ms | Frame p99, native / adaptive, ms | Adaptive scale p05 | +| --- | ---: | ---: | ---: | ---: | +| First traversal | 33.5 / 33.3 | 30.5 / 23.1 | 66.7 / 33.6 | 0.70 | +| Second traversal | 50.1 / 33.4 | 38.2 / 25.5 | 83.4 / 50.1 | 0.60 | +| Resident pages only | 50.0 / 33.4 | 44.0 / 28.7 | 66.7 / 50.1 | 0.70 | + +The resident-only case submitted a median of 1.19 million triangles at native resolution and 1.34 million with +adaptation. CPU submission was 2.5 and 2.4 ms p95. There were no detail requests or uploads during either resident-only route. + +#### Rapid approach to a cold area + +The camera travels 24× closer in 1.8 seconds, then stops. The harness records the first frame with original leaf +geometry and the last frame with a nearby parent above six pixels of estimated projected error. Nearby bounds +are within twice the camera's target distance. These are geometric estimates and include occluded clusters. + +| Package | First original leaf, before / after change | Last nearby coarse frame after arrival, with change | +| --- | ---: | ---: | +| 746 MB IFC | 383 ms after / 517 ms before arrival | 17 ms | +| 931 MB RVT | 67 ms after / 1,150 ms before arrival | 1,250 ms | +| 14.85 GB federation | 517 ms after / 1,150 ms before arrival | 2,050 ms | + +One run per version and package, with Chromium on Radeon at 1920×1080. The original implementation had a +parent above six pixels somewhere in view for the full three-second observation on each package. With the +change, the federation still had distant parents above that threshold at six seconds. Its geometric page +cache was at 256 MiB. The approach had no blank frames, and the frame interval p95 was 16.9 ms on IFC, +33.3 ms on RVT and 33.6 ms on the federation. + +On the separate five-route federation benchmark, the updated loader transferred 723 MiB of pages, up from +276 MiB with the previous review shell. Peak resident and pending pages stayed under 256 MiB. The close +routes ran at 16.8–33.4 ms p95 with no blank frames. + +The later single-cut change passed a pixel test with differently coloured LODs and all-or-nothing coverage. +Repeated cold approaches drew the first original leaf 583 ms before arrival on IFC and about 1.15–1.18 s before +arrival on RVT and the federation. Nearby coarse parents were gone at arrival on IFC, after 1.28 s on RVT, +and after 1.73 s on the federation. Frame interval p95 was 16.8, 33.3 and 33.4 ms respectively. + +~~~powershell +$env:PERF_MESH_MODEL = 'D:/models/federation' +$env:PERF_GPU = 'integrated' +npx playwright test --config playwright.perf.config.js mesh-approach +~~~ + +#### 14.85 GB federation of real geometry + +Build geometry-only packages from current `.ivmesh` exports before composing the benchmark. The script arranges copies +of the input packages in one scene. It writes each placement's mesh bytes to disk and coalesces the overview pages +into a separate file for one startup request. + +~~~powershell +npm run pack-clusters -- D:/models/model.ifc.ivmesh D:/models/ifc-geometry --geometry-only +npm run pack-clusters -- D:/models/model.rvt.ivmesh D:/models/rvt-geometry --geometry-only +node federate-mesh-pages.js D:/models/federation 14750000000 D:/models/ifc-geometry D:/models/rvt-geometry +npm run stream -- D:/models/federation 8790 +$env:PERF_FEDERATED_MODEL = 'D:/models/federation' +$env:PERF_GPU = 'integrated' +npx playwright test --config playwright.perf.config.js mesh-federation +~~~ + +The tested archive contains 14,850,100,406 mesh bytes, 115,929 pages and 458,423,624 source triangles in 31 repeated +placements from the two real models above. Chromium on Radeon drew the overview in 1.07 s from navigation. +The eight-second orbit around the whole scene ran at 16.8 ms p95. Across five six-second close routes, p95 ranged +from 16.8 to 33.3 ms and the worst interval was 66.7 ms. Every route reported zero blank frames. The viewer +evicted 493 pages and stayed under its 256 MiB page-buffer budget. A page was requested successfully at offset +14,848,148,992. The budget excludes the manifest, renderer and browser overhead. A single native model of that +size was unavailable. + +With the shared review shell, a repeat of the same benchmark drew its overview in 0.85 s. Orbit p95 was 16.8 ms +and the five close-route p95 intervals ranged from 16.7 to 33.3 ms. All routes still reported zero blank frames. +The cache evicted 540 pages without exceeding 256 MiB. + +With the review tools enabled in the streaming viewer, the same geometry-only federation drew its overview in +1.22 s. Orbit p95 was 16.8 ms and the five close-route p95 intervals ranged from 16.8 to 33.4 ms, with zero blank +frames. The maximum page-buffer charge was 268,435,360 bytes. The annotated IFC and RVT packages both loaded +original properties and passed the hide, restore and clipped picking checks. Their cold-approach p95 was 16.9 ms. + +The browser checks searched the tree, selected an original element and loaded its property groups in the 746 MB IFC +and a separate 139 MB RVT. A two-cluster fixture checked a distance measurement across the seam and both box clipping +modes in orthographic projection. The package for the 139 MB RVT contains 4,718,560 triangles. The repeat import of the 931 MB RVT +for annotation failed with an out-of-memory error inside RvtIO. Its pre-existing geometry package was used for the +performance checks. + +To check properties on a real annotated package and the section plane across a rendered cluster seam, set +`PERF_MESH_TOOLS_MODEL` to an IFC or RVT cluster directory packed with the default options and run +`npx playwright test --config playwright.perf.config.js mesh-tools`. + +#### Synthetic vessel reference + +From `src/IOViewer/Viewer`, pack the generated model once and run the local server. Open the printed address. + +```powershell +npm run pack-clusters -- D:/work/ioviewer-benchmarks/synthetic-industrial-15gb D:/work/ioviewer-benchmarks/industrial-clusters +npm run stream -- D:/work/ioviewer-benchmarks/industrial-clusters +``` + +The packer verifies the topology and quantized lattice of the synthetic vessels. It retains every source position and +triangle. The 17,100 leaves contain up to 64 vessels each. Full mesh pages contain up to 408 KiB of positions and normals +with indices reconstructed from the verified shared topology. The packed files contain a 30.6 MB resident instance table, +7.14 GB of fine geometry, and a manifest that indexes the byte ranges. The original HTML exports stay usable on their own. + +The viewer draws all vessels from the resident instance table at overview. It picks among three cached approximations +and the original mesh using frustum and projected-error tests over spatial roots and leaves. There is hysteresis between +levels, and the approximated surfaces morph toward the next resolution. The approximate meshes remain drawn while fine +pages are pending. Each arriving page replaces its approximation with a 140 ms complementary dither. The viewport admits +at most two new GPU pages per frame and issues at most four page requests at a time. The 256 MiB accounting reserves the +resident table, its possible GPU uploads and the fine mesh buffers, including in-flight pages. JavaScript object and +graphics-driver overhead are outside the accounting. + +The packer supports the synthetic vessel topology. The clustered view operates on geometry and material colors. The +standalone HTML exports also include selection, properties, and section tools. + +```powershell +$env:PERF_CLUSTER_MODEL = 'D:/work/ioviewer-benchmarks/industrial-clusters' +$env:PERF_GPU = 'integrated' +npx playwright test --config playwright.perf.config.js lod.perf.js +``` + +The benchmark holds fine page responses at a fixed camera and verifies that the same vessels are rendered before and +after refinement. It then flies 2.82 km at the original reference height in 30 seconds and flies 0.79 km close to the +vessels in 20 seconds. Additional camera jumps fill the cache and verify that eviction stays within the budget. + +One reference run per GPU used Chromium 158 at 1920×1080 on the host described above. + +| GPU | Overview, s | Flyover p95 / max, ms | Close route p95 / max, ms | Requested fine detail drawn, close route | +| --- | ---: | ---: | ---: | ---: | +| Radeon | 1.26 | 16.8 / 66.7 | 16.8 / 33.3 | 98.4% | +| RTX 4080 | 0.65 | 16.8 / 33.4 | 16.8 / 17.0 | 98.7% | + +At the fixed camera, 3,392 vessels were drawn before and after releasing the page responses. Both runs admitted +216 pages, evicted five and peaked at 255.9 MiB of accounted buffers during the cache pressure check. + +### Earlier whole-area reference + +Serve the unpacked HTML exports to reproduce the previous whole-area measurements. + +```powershell +npm run stream -- D:/work/ioviewer-benchmarks/synthetic-industrial-15gb +``` + +The initial view displays the bounds of every area. Zoom in or double-click an area's bounds to see the actual meshes. The viewer +prioritizes up to two nearby areas in the frustum, prepares one tile in a worker at a time, and submits up to two mesh +batches per frame. It frees geometry and material GPU resources on eviction. The 256 MiB cap covers prepared mesh +buffers including a reservation for the in-flight result. HTML input is limited to 96 MiB per tile and decoded BIN and +temporary worker allocations are separate from the mesh cap. + +This mode supports navigation and material colors for the tiled benchmark format. Element interaction, property panels, +texture rendering and section tools are available in the ordinary single-tile HTML exports. + +To reproduce the whole-model flyover, run from the viewer directory. The test opens the overview, flies 2.82 km across +12 areas in 30 seconds at a fixed height, then jumps to the opposite side. The report records the animation-frame +intervals and the share of route time when the priority area has finished uploading all its detail batches. + +```powershell +$env:PERF_STREAM_MODEL = 'D:/work/ioviewer-benchmarks/synthetic-industrial-15gb' +$env:PERF_GPU = 'integrated' +npx playwright test --config playwright.perf.config.js stream.perf.js +``` + +The reference run used Chromium 158 at 1920×1080 on the Windows host above. Results show one run per GPU. + +| GPU | Overview, s | Full detail after a jump, s | Frame interval p95 / max, ms | Priority area fully detailed | +| --- | ---: | ---: | ---: | ---: | +| Radeon | 0.95 | 1.55 | 33.3 / 33.5 | 92.1% | +| RTX 4080 | 0.83 | 1.48 | 16.9 / 17.6 | 95.4% | + +Both runs uploaded detail in all 12 route areas and the distant destination, evicted 12 areas, and submitted at most +7.88 million triangles in a frame during the route. The peak resident mesh size was 198.9 MiB. With the in-flight +reservation included, the peak budget charge was 227.5 MiB of 256 MiB on both GPUs. + ## Distance measurement hover On the same machine and Synthetic-400k workload, the harness records 60 paired pick and measurement samples per GPU. diff --git a/src/IOViewer.Cli/Program.cs b/src/IOViewer.Cli/Program.cs index 4e0fade..79add23 100644 --- a/src/IOViewer.Cli/Program.cs +++ b/src/IOViewer.Cli/Program.cs @@ -29,11 +29,11 @@ with NwcIO. Conversion diagnostics are reported as warnings or errors. Arguments: Path to input 3D model (.glb, .obj, .json, .ifc, .ifczip, .rvt or .nwc). - [output] Destination path for exported file (.html or .json). + [output] Destination path for exported file (.html, .json or .ivmesh for clustered LOD). Default: .html. Options: - -o, --output Destination path for exported HTML or JSON file. + -o, --output Destination path for exported HTML, JSON or .ivmesh file. --add --placement Add another model. Translation is in metres and yaw in degrees about +Z. Repeat the pair for each model. Use 0,0,0,0 for an already aligned source. @@ -237,6 +237,17 @@ public static int Main(string[] args) } outputPath ??= Path.ChangeExtension(inputPath, ".html"); + bool meshSource = outputPath.EndsWith(".ivmesh", StringComparison.OrdinalIgnoreCase); + if (meshSource && serve) + { + Console.Error.WriteLine("Error: --serve requires an HTML export. Build the cluster package before serving an .ivmesh source."); + return 1; + } + if (meshSource && File.Exists(outputPath)) + { + Console.Error.WriteLine($"Error: Cluster source already exists: '{Printable(outputPath)}'."); + return 3; + } var sw = Stopwatch.StartNew(); ViewerDocument doc; @@ -297,7 +308,14 @@ public static int Main(string[] args) try { EnsureParentDirectory(outputPath); - if (outputPath.EndsWith(".json", StringComparison.OrdinalIgnoreCase)) + if (meshSource) + { + long triangles = ClusterSourceWriter.Save(doc, outputPath, options); + Console.WriteLine($"Exported {triangles} source triangles for clustered LOD in {sw.ElapsedMilliseconds} ms."); + int undrawn = ViewerPayloadWriter.UndrawnInstances(doc.Scene); + if (undrawn > 0) Console.Error.WriteLine($"Warning: {undrawn} non-triangle meshes were skipped."); + } + else if (outputPath.EndsWith(".json", StringComparison.OrdinalIgnoreCase)) { JsonViewerExporter.Save(doc, outputPath); Console.WriteLine($"Exported JSON snapshot to '{outputPath}' ({doc.Scene.Instances.Count} meshes, {doc.Scene.Elements.Count} elements) in {sw.ElapsedMilliseconds} ms."); diff --git a/src/IOViewer/Exporters/ClusterSourceWriter.cs b/src/IOViewer/Exporters/ClusterSourceWriter.cs new file mode 100644 index 0000000..d72a1eb --- /dev/null +++ b/src/IOViewer/Exporters/ClusterSourceWriter.cs @@ -0,0 +1,222 @@ +using System.Buffers; +using System.Globalization; +using System.Text.Json; +using IOScene; +using IOViewer.Model; + +namespace IOViewer.Exporters; + +// Disk-backed handoff to the offline LOD builder. A record is at most 8,192 triangles. +internal static class ClusterSourceWriter +{ + private const int RecordIndices = 8192 * 3; + private const uint Signature = 0x33534d49; // IMS3 + + internal static long Save(ViewerDocument doc, string target, HtmlViewerOptions options) + { + string path = Path.GetFullPath(target); + string temporary = Path.Combine(Path.GetDirectoryName(path)!, $".ioviewer-{Guid.NewGuid():N}.tmp"); + try + { + long triangles; + using (var stream = new FileStream(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None, 65536)) + using (var writer = new BinaryWriter(stream)) + triangles = Write(doc, writer, options); + File.Move(temporary, path); + return triangles; + } + finally + { + File.Delete(temporary); + } + } + + private static long Write(ViewerDocument doc, BinaryWriter writer, HtmlViewerOptions options) + { + var scene = doc.Scene; + var geometries = scene.Geometries.ToDictionary(geometry => geometry.Id); + var materials = scene.Materials.ToDictionary(material => material.Id); + var textures = scene.Textures.Select((texture, index) => (texture.Id, index)).ToDictionary(texture => texture.Id, texture => texture.index); + var closed = new Dictionary(); + var bounds = scene.ComputeBounds(); + var origin = bounds.IsEmpty ? Vector3d.Zero : bounds.Center; + if (!double.IsFinite(origin.X) || !double.IsFinite(origin.Y) || !double.IsFinite(origin.Z)) + throw new InvalidDataException("Non-finite scene origin."); + writer.Write(Signature); + writer.Write(origin.X); + writer.Write(origin.Y); + writer.Write(origin.Z); + long directoryOffset = writer.BaseStream.Position; + writer.Write(0L); + var remap = new Dictionary(); + var vertices = new List(); + var normals = new List(); + var uvs = new List(); + var indices = new List(); + long triangles = 0; + foreach (var instance in scene.Instances) + { + if (!geometries.TryGetValue(instance.GeometryId, out var geometry)) + throw new InvalidDataException($"Missing geometry {instance.GeometryId}."); + if (geometry.Topology != SceneTopology.Triangles) continue; + var material = instance.MaterialId is int id ? materials.GetValueOrDefault(id) : null; + var color = instance.Color ?? material?.Color ?? new RgbaColor(200, 200, 200); + int texture = material?.TextureId is int textureId && geometry.UVs?.Count == geometry.Vertices.Count + ? textures.GetValueOrDefault(textureId, -1) : -1; + var transform = instance.Transform ?? Transform3d.Identity; + var rebased = transform with { Translation = transform.Translation - origin }; + var nx = Vector3d.Cross(transform.YAxis, transform.ZAxis); + var ny = Vector3d.Cross(transform.ZAxis, transform.XAxis); + var nz = Vector3d.Cross(transform.XAxis, transform.YAxis); + bool mirrored = Vector3d.Dot(transform.XAxis, nx) < 0; + bool hasIndices = geometry.Indices.Count != 0; + bool hasNormals = geometry.Normals?.Count == geometry.Vertices.Count; + int count = hasIndices ? geometry.Indices.Count : geometry.Vertices.Count / 3 * 3; + if (count % 3 != 0) throw new InvalidDataException($"Invalid triangle indices in geometry {geometry.Id}."); + if (!closed.TryGetValue(geometry.Id, out bool solid)) + closed.Add(geometry.Id, solid = IsClosed(geometry, count)); + for (int start = 0; start < count; ) + { + int length = Math.Min(RecordIndices, count - start); + var box = BoundingBox3d.Empty; + remap.Clear(); + vertices.Clear(); + normals.Clear(); + uvs.Clear(); + indices.Clear(); + for (int i = 0; i < length; i++) + { + int at = start + (mirrored && i % 3 != 0 ? i + (i % 3 == 1 ? 1 : -1) : i); + int index = hasIndices ? geometry.Indices[at] : at; + if ((uint)index >= (uint)geometry.Vertices.Count) + throw new InvalidDataException($"Invalid vertex index in geometry {geometry.Id}."); + if (!remap.TryGetValue(index, out int slot)) + { + slot = vertices.Count; + remap.Add(index, slot); + var p = rebased.Apply(geometry.Vertices[index]); + var point = new Vector3d((float)p.X, (float)p.Y, (float)p.Z); + if (!float.IsFinite((float)point.X) || !float.IsFinite((float)point.Y) || !float.IsFinite((float)point.Z)) + throw new InvalidDataException($"Non-finite vertex in geometry {geometry.Id}."); + vertices.Add(point); + box = box.Encapsulate(point); + if (hasNormals) + { + var n = geometry.Normals![index]; + normals.Add(((nx * n.X + ny * n.Y + nz * n.Z) * (mirrored ? -1 : 1)).Normalized()); + } + if (texture >= 0) uvs.Add(geometry.UVs![index]); + } + indices.Add(slot); + } + WriteVector(writer, box.Min); + WriteVector(writer, box.Max); + writer.Write(vertices.Count); + writer.Write(length); + writer.Write(color.R); + writer.Write(color.G); + writer.Write(color.B); + writer.Write(color.A); + writer.Write(hasNormals ? 1 : 0); + writer.Write(instance.ElementId); + writer.Write(texture); + writer.Write(solid ? 1 : 0); + foreach (var p in vertices) WriteVector(writer, p); + foreach (var n in normals) WriteVector(writer, n); + foreach (int i in indices) writer.Write(i); + foreach (var uv in uvs) + { + if (!float.IsFinite((float)uv.X) || !float.IsFinite((float)uv.Y)) + throw new InvalidDataException($"Non-finite UV in geometry {geometry.Id}."); + writer.Write((float)uv.X); + writer.Write((float)uv.Y); + } + triangles += length / 3; + start += length; + } + } + if (triangles == 0) throw new InvalidDataException("The source contains no triangle geometry."); + long geometryEnd = writer.BaseStream.Position; + writer.BaseStream.Position = directoryOffset; + writer.Write(geometryEnd); + writer.BaseStream.Position = geometryEnd; + writer.Write(0); + ViewerPayloadWriter.WriteClusterReview(doc, options, origin, writer.BaseStream); + long reviewEnd = writer.BaseStream.Position; + writer.BaseStream.Position = geometryEnd; + writer.Write(checked((int)(reviewEnd - geometryEnd - sizeof(int)))); + writer.BaseStream.Position = reviewEnd; + if (options.IncludeProperties) WriteElements(scene, writer); + return triangles; + } + + // Tessellation can duplicate vertices at normal and UV seams. + private static bool IsClosed(SceneGeometry geometry, int count) + { + if (count < 12) return false; + var welded = new Dictionary(); + var vertices = new int[geometry.Vertices.Count]; + for (int i = 0; i < vertices.Length; i++) + { + var p = geometry.Vertices[i]; + if (!welded.TryGetValue(p, out int id)) welded.Add(p, id = welded.Count); + vertices[i] = id; + } + if (welded.Count < 4) return false; + var edges = new Dictionary<(int, int), int>(); + int open = 0; + int Corner(int i) => geometry.Indices.Count == 0 ? i : geometry.Indices[i]; + bool AddEdge(int a, int b) + { + var key = a < b ? (a, b) : (b, a); + int direction = a < b ? 1 : -1; + if (edges.TryAdd(key, direction)) { open++; return true; } + if (edges[key] != -direction) return false; + edges[key] = 0; + open--; + return true; + } + for (int i = 0; i < count; i += 3) + { + int a = Corner(i), b = Corner(i + 1), c = Corner(i + 2); + if ((uint)a >= vertices.Length || (uint)b >= vertices.Length || (uint)c >= vertices.Length) return false; + (a, b, c) = (vertices[a], vertices[b], vertices[c]); + if (a != b && b != c && c != a && (!AddEdge(a, b) || !AddEdge(b, c) || !AddEdge(c, a))) return false; + } + return edges.Count != 0 && open == 0; + } + + private static void WriteElements(SceneDocument scene, BinaryWriter writer) + { + var levels = scene.Levels.ToDictionary(level => level.Id); + var properties = new ViewerProperties(scene); + var buffer = new ArrayBufferWriter(); + using var json = new Utf8JsonWriter(buffer); + foreach (var element in scene.Elements) + { + buffer.ResetWrittenCount(); + json.Reset(buffer); + json.WriteStartObject(); + json.WriteString("id", element.Id.ToString(CultureInfo.InvariantCulture)); + json.WriteString("name", element.Name); + json.WriteString("category", element.Category); + json.WriteString("type", element.TypeName); + json.WriteString("sourceId", element.SourceId); + if (element.LevelId is int level && levels.TryGetValue(level, out var levelData)) json.WriteString("level", levelData.Name); + json.WritePropertyName("properties"); + properties.Write(json, element); + json.WriteEndObject(); + json.Flush(); + writer.Write(element.Id); + writer.Write(buffer.WrittenCount); + writer.Write(buffer.WrittenSpan); + } + } + + private static void WriteVector(BinaryWriter writer, Vector3d value) + { + writer.Write((float)value.X); + writer.Write((float)value.Y); + writer.Write((float)value.Z); + } +} diff --git a/src/IOViewer/Exporters/ViewerPayloadWriter.cs b/src/IOViewer/Exporters/ViewerPayloadWriter.cs index fbd4172..b940ce9 100644 --- a/src/IOViewer/Exporters/ViewerPayloadWriter.cs +++ b/src/IOViewer/Exporters/ViewerPayloadWriter.cs @@ -76,6 +76,23 @@ public static ViewerPayloadWriter Create(ViewerDocument doc, HtmlViewerOptions o return writer; } + internal static void WriteClusterReview(ViewerDocument doc, HtmlViewerOptions options, Vector3d origin, Stream output) + { + var writer = new ViewerPayloadWriter(doc, options) { _rtcOffset = origin }; + var elementIndex = doc.Scene.Elements.Select((element, index) => (element.Id, index)) + .ToDictionary(element => element.Id, element => element.index); + writer._sections = writer.BuildSections(doc.SectionPlanes, doc.SectionBox); + writer.BuildViewpointStates(doc.ViewpointStates, elementIndex); + writer.ValidateMetadata(); + using var w = new Utf8JsonWriter(output); + w.WriteStartObject(); + w.WriteString("title", options.Title); + writer.WriteOptions(w); + writer.WriteTextures(w); + writer.WriteReview(w); + w.WriteEndObject(); + } + private SectionState BuildSections(List? planes, ViewerSectionBox? sectionBox) { var output = new List<(string Axis, Vector3d Normal, double Offset, bool Flipped)>(); @@ -589,51 +606,18 @@ public void WriteProps(Stream output) w.WriteStartObject(); if (_options.IncludeProperties) { - var sets = new Dictionary(); - foreach (var set in _scene.PropertySets) sets.TryAdd(set.Id, set); - var referenced = new HashSet(); - var names = new HashSet(); - var nextSuffix = new Dictionary(); + var properties = new ViewerProperties(_scene); foreach (var el in _scene.Elements) { if (el.PropertySetIds.Count == 0) continue; - w.WriteStartObject(el.Id.ToString(CultureInfo.InvariantCulture)); - // Sets with the same name are one group, in the order the element first references them; a property - // name used before in the group gets the first free suffix " (2)", " (3)", ... - referenced.Clear(); - var groups = el.PropertySetIds.Where(referenced.Add).Select(id => sets.GetValueOrDefault(id)).OfType().GroupBy(s => Written(s.Name)); - foreach (var group in groups) - { - w.WriteStartObject(group.Key); - names.Clear(); - nextSuffix.Clear(); - foreach (var prop in group.SelectMany(s => s.Properties)) - { - string written = Written(prop.Name), name = written; - if (!names.Add(name)) - { - // Every suffix below nextSuffix[written] is taken, so a name that repeats many times is not - // searched from " (2)" again each time. - int n = nextSuffix.GetValueOrDefault(written, 2); - while (!names.Add(name = string.Create(CultureInfo.InvariantCulture, $"{written} ({n})"))) n++; - nextSuffix[written] = n + 1; - } - // The display string: a value of a kind this version does not know is shown as text. - w.WriteString(name, prop.Value.Text); - } - w.WriteEndObject(); - } - w.WriteEndObject(); + w.WritePropertyName(el.Id.ToString(CultureInfo.InvariantCulture)); + properties.Write(w, el); FlushIfLarge(w); } } w.WriteEndObject(); } - // The writer writes each lone surrogate as U+FFFD, so names that differ only there are equal in the page. - private static string Written(string name) => - name.AsSpan().ContainsAnyInRange('\uD800', '\uDFFF') ? Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(name)) : name; - public void WriteMeta(Stream output) { using var w = new Utf8JsonWriter(output); @@ -646,10 +630,7 @@ public void WriteMeta(Stream output) WriteVector(w, "rtcOffset", _rtcOffset); WriteBox(w, "bbox", _bounds, _rtcOffset); - w.WriteStartObject("options"); - w.WriteBoolean("initialWireframe", _options.InitialWireframe); - w.WriteBoolean("initialWhiteMode", _options.InitialWhiteMode); - w.WriteEndObject(); + WriteOptions(w); if (_writtenMeshes < _drawable) { @@ -686,18 +667,7 @@ public void WriteMeta(Stream output) } w.WriteEndArray(); - w.WriteStartArray("textures"); - foreach (var tex in _scene.Textures) - { - w.WriteStartObject(); - w.WriteString("mime", tex.MimeType); - w.WriteString("data", Convert.ToBase64String(tex.Data)); - w.WriteNumber("sx", tex.ScaleX); - w.WriteNumber("sy", tex.ScaleY); - w.WriteEndObject(); - FlushIfLarge(w); - } - w.WriteEndArray(); + WriteTextures(w); w.WriteStartArray("geometries"); foreach (var g in _geometries) @@ -734,6 +704,37 @@ public void WriteMeta(Stream output) _instances.Matrix.WriteTo(w); w.WriteEndObject(); + WriteReview(w); + w.WriteEndObject(); + } + + private void WriteOptions(Utf8JsonWriter w) + { + w.WriteStartObject("options"); + w.WriteBoolean("initialWireframe", _options.InitialWireframe); + w.WriteBoolean("initialWhiteMode", _options.InitialWhiteMode); + w.WriteEndObject(); + } + + private void WriteTextures(Utf8JsonWriter w) + { + w.WriteStartArray("textures"); + foreach (var tex in _scene.Textures) + { + w.WriteStartObject(); + w.WriteString("mime", tex.MimeType); + w.WriteString("data", Convert.ToBase64String(tex.Data)); + w.WriteNumber("sx", tex.ScaleX); + w.WriteNumber("sy", tex.ScaleY); + w.WriteEndObject(); + FlushIfLarge(w); + } + w.WriteEndArray(); + } + + private void WriteReview(Utf8JsonWriter w) + { + var host = _scene.Models.Count > 0 ? _scene.Models[0] : null; // An element of a linked model carries the model's path, else its name, as the linked file list shows it. var links = new Dictionary(); for (int i = _firstListedModel; i < _scene.Models.Count; i++) @@ -783,8 +784,6 @@ public void WriteMeta(Stream output) WriteTimeLiner(w); WriteLinkedFiles(w); WriteClashTests(w); - - w.WriteEndObject(); } private static void WriteSections(Utf8JsonWriter w, SectionState sections) diff --git a/src/IOViewer/Exporters/ViewerProperties.cs b/src/IOViewer/Exporters/ViewerProperties.cs new file mode 100644 index 0000000..2c32330 --- /dev/null +++ b/src/IOViewer/Exporters/ViewerProperties.cs @@ -0,0 +1,51 @@ +using System.Globalization; +using System.Text; +using System.Text.Json; +using IOScene; + +namespace IOViewer.Exporters; + +internal sealed class ViewerProperties +{ + private readonly Dictionary _sets = []; + private readonly HashSet _referenced = []; + private readonly HashSet _names = []; + private readonly Dictionary _nextSuffix = []; + + public ViewerProperties(SceneDocument scene) + { + foreach (var set in scene.PropertySets) _sets.TryAdd(set.Id, set); + } + + public void Write(Utf8JsonWriter writer, SceneElement element) + { + writer.WriteStartObject(); + _referenced.Clear(); + var groups = element.PropertySetIds.Where(_referenced.Add).Select(id => _sets.GetValueOrDefault(id)) + .OfType().GroupBy(set => Written(set.Name)); + foreach (var group in groups) + { + writer.WriteStartObject(group.Key); + _names.Clear(); + _nextSuffix.Clear(); + foreach (var property in group.SelectMany(set => set.Properties)) + { + string name = Written(property.Name); + if (!_names.Add(name)) + { + string prefix = name; + int next = _nextSuffix.GetValueOrDefault(prefix, 2); + while (!_names.Add(name = string.Create(CultureInfo.InvariantCulture, $"{prefix} ({next})"))) next++; + _nextSuffix[prefix] = next + 1; + } + writer.WriteString(name, property.Value.Text); + } + writer.WriteEndObject(); + } + writer.WriteEndObject(); + } + + // JSON replaces unpaired surrogates, so names differing only in such a surrogate share a display key. + private static string Written(string name) => + name.AsSpan().ContainsAnyInRange('\uD800', '\uDFFF') ? Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(name)) : name; +} diff --git a/src/IOViewer/Viewer/build-mesh-pages.js b/src/IOViewer/Viewer/build-mesh-pages.js new file mode 100644 index 0000000..3f2a85e --- /dev/null +++ b/src/IOViewer/Viewer/build-mesh-pages.js @@ -0,0 +1,326 @@ +import { closeSync, fstatSync, mkdirSync, openSync, readSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { MeshoptSimplifier } from 'meshoptimizer/simplifier'; +import { splitCells, unitNormals } from './src/engine/chunks.js'; +import { ELEMENT_FIELDS, isBounds, isPoint, MAX_ELEMENT_BYTES, MESH_FORMAT, MESH_MANIFEST_BYTES, PAGE_TRIANGLES, ROOT_BYTES, pageBytes, sizeOfPage, validateMeshPages, viewsOfPage } from './src/stream/meshPages.js'; +import { validateReviewMeta } from './src/data.js'; + +const HEADER = 28, RECORD = 40; +const channel = Array.from({ length: 256 }, (_, i) => { + const x = i / 255; + return Math.round(255 * (x <= 0.04045 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4)); +}); + +function read(fd, bytes, offset) { + const buffer = new ArrayBuffer(bytes), data = new Uint8Array(buffer); + for (let at = 0; at < bytes;) { + const read = readSync(fd, data, at, bytes - at, offset + at); + if (!read) throw new Error('Truncated geometry source.'); + at += read; + } + return buffer; +} + +function recordsOf(fd, includeBim) { + const header = new DataView(read(fd, HEADER, 0)); + const version = header.getUint32(0, true); + const reviewFormat = version === 0x33534d49; + const annotated = reviewFormat || version === 0x32534d49; + if (!annotated && version !== 0x31534d49) throw new Error('Expected an IOViewer .ivmesh source.'); + const origin = [4, 12, 20].map((i) => header.getFloat64(i, true)); + if (!isPoint(origin)) throw new Error('Invalid source origin.'); + const records = []; + const size = fstatSync(fd).size; + const start = HEADER + (annotated ? 8 : 0), recordSize = RECORD + (reviewFormat ? 16 : annotated ? 8 : 0); + const end = annotated ? Number(new DataView(read(fd, 8, HEADER)).getBigInt64(0, true)) : size; + if (!Number.isSafeInteger(end) || end < start || end > size) throw new Error('Invalid geometry directory offset.'); + const meta = new Float32Array(recordSize / 4), data = new Uint8Array(meta.buffer), counts = new Uint32Array(meta.buffer); + const recordView = new DataView(meta.buffer); + const slots = new Map(), elements = []; + let review, propertiesStart = end, textureCount = 0; + if (reviewFormat) { + const length = new DataView(read(fd, 4, end)).getUint32(0, true); + propertiesStart += 4 + length; + if (!length || length > MESH_MANIFEST_BYTES || propertiesStart > size) throw new Error('Invalid cluster review size.'); + if (includeBim) { + const { elements: sourceElements, ...fields } = JSON.parse(Buffer.from(read(fd, length, end + 4)).toString('utf8')); + validateReviewMeta({ ...fields, elements: sourceElements }); + review = fields; + textureCount = fields.textures?.length ?? 0; + for (const input of sourceElements) { + const id = String(input.id); + if (!/^-?\d+$/.test(id) || slots.has(id)) throw new Error('Invalid review element ID.'); + slots.set(id, elements.length); + elements.push({ ...Object.fromEntries(Object.entries(input).filter(([, value]) => value != null)), id }); + } + } + } + for (let offset = start; offset < end;) { + if (offset + recordSize > end || readSync(fd, data, 0, recordSize, offset) !== recordSize) throw new Error('Truncated mesh record.'); + const min = [...meta.subarray(0, 3)], max = [...meta.subarray(3, 6)]; + const [vertices, indices, rgba, normals] = counts.subarray(6); + const texture = reviewFormat ? recordView.getInt32(RECORD + 8, true) : -1; + const solid = reviewFormat ? recordView.getUint32(RECORD + 12, true) : 0; + const bytes = vertices * (12 * (1 + normals) + (texture >= 0 ? 8 : 0)) + indices * 4; + offset += recordSize; + if (!isBounds({ min, max }) || !vertices || vertices > indices || !indices || indices % 3 || indices > PAGE_TRIANGLES * 3 + || normals > 1 || solid > 1 || texture < -1 || (includeBim && texture >= textureCount) || bytes > end - offset) throw new Error('Invalid mesh record.'); + let element; + if (annotated && includeBim) { + const id = recordView.getBigInt64(RECORD, true).toString(); + element = slots.get(id); + if (element === undefined) { + element = elements.length; + slots.set(id, element); + elements.push({ id }); + } + const bounds = elements[element]; + if (!bounds.min) Object.assign(bounds, { min: [...min], max: [...max] }); + else { + for (let i = 0; i < 3; i++) { + bounds.min[i] = Math.min(bounds.min[i], min[i]); + bounds.max[i] = Math.max(bounds.max[i], max[i]); + } + } + } + records.push({ min, max, vertices, indices, rgba, normals, offset, bytes, element, texture, solid: !!solid, includeBim }); + offset += bytes; + } + if (!records.length) throw new Error('The source contains no triangle geometry.'); + const metadata = new Map(); + for (let at = propertiesStart; includeBim && at < size;) { + const prefix = new DataView(read(fd, 12, at)); + const id = prefix.getBigInt64(0, true).toString(), length = prefix.getUint32(8, true); + at += 12; + if (!slots.has(id) || metadata.has(id) || !length || length > MAX_ELEMENT_BYTES || at + length > size) throw new Error('Invalid element property record.'); + metadata.set(id, { at, length }); + at += length; + } + return { origin, records, elements, metadata, review }; +} + +function aggregateBounds(children) { + const min = [Infinity, Infinity, Infinity], max = [-Infinity, -Infinity, -Infinity]; + for (const child of children) for (let i = 0; i < 3; i++) { + min[i] = Math.min(min[i], child.min[i]); + max[i] = Math.max(max[i], child.max[i]); + } + return { min, max }; +} + +// The initial camera fits the middle 98% of triangle-weighted record centres. The full bounds drive Fit All. +export function focusBounds(records, bounds) { + const total = records.reduce((sum, record) => sum + record.indices, 0); + const min = [], max = []; + for (let axis = 0; axis < 3; axis++) { + const centre = (entry) => (entry.min[axis] + entry.max[axis]) / 2; + const ordered = [...records].sort((a, b) => centre(a) - centre(b)); + let weight = 0, low, high; + for (const record of ordered) { + weight += record.indices; + if (low === undefined && weight >= total * 0.01) low = centre(record); + if (weight >= total * 0.99) { high = centre(record); break; } + } + min.push(low < high ? low : bounds.min[axis]); + max.push(low < high ? high : bounds.max[axis]); + } + return { min, max }; +} + +function assemble(parts, tagged = false, leaf = false) { + const vertices = parts.reduce((sum, part) => sum + part.position.length / 3, 0); + const position = new Float32Array(vertices * 3), normal = new Int16Array(vertices * 3), color = new Uint8Array(vertices * 4); + const uv = leaf && parts.some((part) => part.uv) ? new Float32Array(vertices * 2) : null; + const groups = leaf && parts.some((part) => part.solid || part.texture !== undefined); + const solidGroups = [], blendedGroups = []; + const opaque = [], blended = []; + const opaqueTags = [], blendedTags = []; + if (groups) parts.sort((a, b) => (a.texture ?? -1) - (b.texture ?? -1) || Number(a.solid) - Number(b.solid)); + let at = 0; + for (const part of parts) { + position.set(part.position, at * 3); + normal.set(part.normal, at * 3); + color.set(part.color, at * 4); + if (part.uv && uv) uv.set(part.uv, at * 2); + if (groups) { + const entries = part.opaque ? solidGroups : blendedGroups; + const previous = entries.at(-1); + const closed = part.solid || undefined, texture = part.texture; + if (previous && previous.closed === closed && previous.texture === texture) previous.count += part.index.length; + else entries.push({ count: part.index.length, closed, texture }); + } + for (let j = 0; j < part.index.length; j++) { + const solid = j < part.opaque; + (solid ? opaque : blended).push(at + part.index[j]); + if (tagged && j % 3 === 0) (solid ? opaqueTags : blendedTags).push(part.element); + } + at += part.position.length / 3; + } + return { position, normal, color, uv, groups: groups ? [...solidGroups, ...blendedGroups] : undefined, + opaque: Uint32Array.from(opaque), blended: Uint32Array.from(blended), + tags: tagged ? Uint32Array.from([...opaqueTags, ...blendedTags]) : null }; +} + +function partFromRecord(fd, record) { + const buffer = read(fd, record.bytes, record.offset), n = record.vertices * 3; + const position = new Float32Array(buffer, 0, n); + const index = new Uint32Array(buffer, n * 4 * (1 + record.normals), record.indices); + if (index.some((i) => i >= record.vertices) || position.some((n) => !Number.isFinite(n))) throw new Error('Invalid mesh positions or indices.'); + const normals = record.normals ? new Float32Array(buffer, n * 4, n) : unitNormals({ positions: position, indices: index }); + if (normals.some((n) => !Number.isFinite(n))) throw new Error('Invalid mesh normal.'); + const normal = Int16Array.from(normals, (x) => Math.round(Math.max(-1, Math.min(1, x)) * 32767)); + const color = new Uint8Array(record.vertices * 4), a = record.rgba >>> 24; + const rgba = [channel[record.rgba & 255], channel[(record.rgba >>> 8) & 255], channel[(record.rgba >>> 16) & 255], a]; + for (let i = 0; i < color.length; i += 4) color.set(rgba, i); + const texture = record.includeBim && record.texture >= 0 ? record.texture : undefined; + const uv = texture === undefined ? null : new Float32Array(buffer, index.byteOffset + index.byteLength, record.vertices * 2); + if (uv?.some((value) => !Number.isFinite(value))) throw new Error('Invalid mesh UV.'); + return { position, normal, color, index, uv, texture, solid: record.solid, + opaque: a === 255 ? index.length : 0, element: record.element }; +} + +function reducedIndices(mesh, target, bounds) { + const { position, normal, color } = mesh; + const scale = Math.max(...bounds.max.map((n, i) => n - bounds.min[i])); + const attributes = new Float32Array(position.length / 3 * 7); + for (let i = 0, j = 0; j < color.length; i += 7, j += 4) { + attributes[i] = color[j] / 255; + attributes[i + 1] = color[j + 1] / 255; + attributes[i + 2] = color[j + 2] / 255; + attributes[i + 3] = color[j + 3] / 255; + for (let a = 0; a < 3; a++) attributes[i + 4 + a] = normal[j / 4 * 3 + a] / 32767; + } + let error = 0; + const n = mesh.opaque.length + mesh.blended.length; + const output = ['opaque', 'blended'].map((kind) => { + const input = mesh[kind]; + if (!input.length) return input; + const limit = Math.max(3, Math.floor(target * input.length / n / 3) * 3); + if (input.length <= limit) return input; + let [indices, deviation] = MeshoptSimplifier.simplifyWithAttributes(input, position, 3, attributes, 7, + [0.25, 0.25, 0.25, 0.5, 0.1, 0.1, 0.1], null, limit, scale, ['ErrorAbsolute', 'LockBorder', 'Sparse']); + if (indices.length > limit) { + // shortcut: preserve cuts where simplification allows it; relax borders on a page that otherwise cannot fit. + [indices, deviation] = MeshoptSimplifier.simplifyWithAttributes(input, position, 3, attributes, 7, + [0.25, 0.25, 0.25, 0.5, 0.1, 0.1, 0.1], null, limit, scale, ['ErrorAbsolute', 'Permissive', 'Sparse']); + } + if (indices.length > limit) { + // shortcut: grid simplification handles disconnected triangle soup; revisit for continuous locked borders. + [indices, deviation] = MeshoptSimplifier.simplifySloppy(input, position, 3, null, limit, 1); + deviation *= scale; + } + if (!indices.length) { + // The cluster still has a surface and the full original remains available in its children. + indices = input.slice(0, 3); + deviation = scale; + } + if (indices.length > limit) { + indices = indices.slice(0, limit); + deviation = scale; + } + if (indices.length < input.length) deviation = Math.max(deviation, scale * 1e-5); + error = Math.max(error, deviation); + return indices; + }); + return { opaque: output[0], blended: output[1], error }; +} + +function pack(mesh, opaque, blended, tags = null) { + const index = new Uint32Array(opaque.length + blended.length); + index.set(opaque); + index.set(blended, opaque.length); + const [remap, vertices] = MeshoptSimplifier.compactMesh(index); + const pick = tags ? true : undefined; + const uv = mesh.uv ? true : undefined; + const buffer = new ArrayBuffer(pageBytes(vertices, index.length, pick, uv)); + const output = viewsOfPage(buffer, { vertices, indices: index.length, pick, uv }); + for (let old = 0; old < remap.length; old++) { + const next = remap[old]; + if (next >= vertices) continue; + for (let axis = 0; axis < 3; axis++) { + output.position[next * 3 + axis] = mesh.position[old * 3 + axis]; + output.normal[next * 3 + axis] = mesh.normal[old * 3 + axis]; + } + for (let c = 0; c < 4; c++) output.color[next * 4 + c] = mesh.color[old * 4 + c]; + if (uv) { + output.uv[next * 2] = mesh.uv[old * 2]; + output.uv[next * 2 + 1] = mesh.uv[old * 2 + 1]; + } + } + output.index.set(index); + if (tags) output.tags.set(tags); + return { buffer, vertices, indices: index.length, opaque: opaque.length, pick, uv, + members: tags ? [...new Set(tags)].sort((a, b) => a - b) : undefined, groups: mesh.groups }; +} + +export async function buildMeshPages(source, destination, includeBim = true) { + await MeshoptSimplifier.ready; + const input = openSync(source, 'r'); + let output; + try { + const { origin, records, elements, metadata, review } = recordsOf(input, includeBim); + mkdirSync(destination); + output = openSync(join(destination, 'meshes.bin'), 'wx+'); + const pages = []; + const weights = Uint32Array.from(records, ({ indices }) => indices / 3); + const centres = Float64Array.from(records.flatMap(({ min, max }) => min.map((n, i) => (n + max[i]) / 2))); + let bytes = 0; + function write({ buffer, ...sizes }, bounds, error, children) { + writeFileSync(output, new Uint8Array(buffer)); + pages.push({ ...bounds, ...sizes, error, children, offset: bytes }); + bytes += buffer.byteLength; + return pages.length - 1; + } + const leaves = splitCells(centres, weights, records.keys(), PAGE_TRIANGLES); + let roots = []; + for (const leaf of leaves) { + const parts = [...leaf].map((i) => records[i]); + const mesh = assemble(parts.map((part) => partFromRecord(input, part)), elements.length > 0, true); + roots.push(write(pack(mesh, mesh.opaque, mesh.blended, mesh.tags), aggregateBounds(parts), 0, [])); + } + console.log(`${roots.length} full-resolution mesh pages`); + const triangles = weights.reduce((sum, n) => sum + n, 0); + while (roots.length > 48 || roots.reduce((sum, id) => sum + sizeOfPage(pages[id]), 0) > ROOT_BYTES / 2) { + const next = []; + for (let i = 0; i < roots.length; i += 4) { + const children = roots.slice(i, i + 4); + if (children.length === 1) { next.push(children[0]); continue; } + const group = children.map((id) => pages[id]); + const bounds = aggregateBounds(group); + const mesh = assemble(group.map((page) => ({ ...viewsOfPage(read(output, sizeOfPage(page), page.offset), page), opaque: page.opaque }))); + const limit = Math.min(PAGE_TRIANGLES * 3 - 3, Math.max(6, (mesh.opaque.length + mesh.blended.length) / 5)); + const { opaque, blended, error } = reducedIndices(mesh, limit, bounds); + next.push(write(pack(mesh, opaque, blended), bounds, error + Math.max(...group.map((p) => p.error)), children)); + } + roots = next; + console.log(`${roots.length} pages at the next level`); + } + const bounds = aggregateBounds(records); + let propertyBytes = 0; + const props = metadata.size ? openSync(join(destination, 'elements.bin'), 'wx') : null; + try { + for (const element of elements) { + if (!element.min) Object.assign(element, { min: [0, 0, 0], max: [0, 0, 0], noGeometry: true }); + const record = metadata.get(element.id); + element.offset = propertyBytes; + element.size = record?.length ?? 0; + if (record) { + const encoded = new Uint8Array(read(input, record.length, record.at)); + const meta = JSON.parse(Buffer.from(encoded.buffer).toString('utf-8')); + if (meta?.id !== element.id) throw new Error('Mismatched element ID in properties.'); + for (const field of ELEMENT_FIELDS) if (typeof meta[field] === 'string' && meta[field]) element[field] = meta[field]; + writeFileSync(props, encoded); + } + propertyBytes += element.size; + } + } finally { if (props !== null) closeSync(props); } + const manifest = validateMeshPages({ format: MESH_FORMAT, origin, ...bounds, focus: focusBounds(records, bounds), pages, roots, bytes, triangles, + ...((elements.length || review) ? { elements, propertyBytes } : {}), ...(review ? { review } : {}) }); + writeFileSync(join(destination, 'manifest.json'), JSON.stringify(manifest), { flag: 'wx' }); + console.log(`${triangles} triangles, ${pages.length} total pages, ${bytes} bytes`); + return manifest; + } finally { + if (output !== undefined) closeSync(output); + closeSync(input); + } +} diff --git a/src/IOViewer/Viewer/dist/viewer.js b/src/IOViewer/Viewer/dist/viewer.js index ea7eb73..ce11c79 100644 --- a/src/IOViewer/Viewer/dist/viewer.js +++ b/src/IOViewer/Viewer/dist/viewer.js @@ -1,10 +1,10 @@ -(()=>{var Vh=i=>{throw TypeError(i)};var vl=(i,t,e)=>t.has(i)||Vh("Cannot "+e);var ii=(i,t,e)=>(vl(i,t,"read from private field"),e?e.call(i):t.get(i)),yl=(i,t,e)=>t.has(i)?Vh("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(i):t.set(i,e),Gh=(i,t,e,n)=>(vl(i,t,"write to private field"),n?n.call(i,e):t.set(i,e),e),zr=(i,t,e)=>(vl(i,t,"access private method"),e);var bu=0,Ql=1,Su=2;var lr=1,wu=2,vs=3,Bn=0,Ve=1,Ie=2,On=0,ys=1,tc=2,ec=3,nc=4,Eu=5;var Ni=100,Tu=101,Au=102,Ru=103,Cu=104,Iu=200,Pu=201,Lu=202,Du=203,ic=204,sc=205,Nu=206,Uu=207,Fu=208,Bu=209,Ou=210,zu=211,ku=212,Hu=213,Vu=214,go=0,_o=1,xo=2,rs=3,vo=4,yo=5,Mo=6,bo=7,Zo=0,Gu=1,Wu=2,Mn=0,rc=1,oc=2,ac=3,lc=4,cc=5,hc=6,uc=7;var dc=300,pi=301,Ui=302,Jo=303,Ko=304,cr=306,os=1e3,In=1001,So=1002,Ue=1003,Xu=1004;var hr=1005;var ze=1006,jo=1007;var mi=1008;var nn=1009,fc=1010,pc=1011,Ms=1012,Qo=1013,bn=1014,Ge=1015,Sn=1016,ta=1017,ea=1018,bs=1020,mc=35902,gc=35899,_c=1021,xc=1022,sn=1023,Pn=1026,gi=1027,Ss=1028,na=1029,_i=1030,ia=1031;var sa=1033,ur=33776,dr=33777,fr=33778,pr=33779,ra=35840,oa=35841,aa=35842,la=35843,ca=36196,ha=37492,ua=37496,da=37488,fa=37489,mr=37490,pa=37491,ma=37808,ga=37809,_a=37810,xa=37811,va=37812,ya=37813,Ma=37814,ba=37815,Sa=37816,wa=37817,Ea=37818,Ta=37819,Aa=37820,Ra=37821,Ca=36492,Ia=36494,Pa=36495,La=36283,Da=36284,gr=36285,Na=36286;var Gs=2300,wo=2301,po=2302,Wl=2303,Xl=2400,ql=2401,Yl=2402;var qu=3200;var Ua=0,Yu=1,jn="",Ae="srgb",Ws="srgb-linear",Xs="linear",te="srgb";var mo=7680;var vc=34055,yc=34056;var Mc=517;var $u=519,Zu=512,Ju=513,Ku=514,Fa=515,ju=516,Qu=517,Ba=518,td=519,bc=35044,Sc=35048;var wc="300 es",xn=2e3,as=2001;function bp(i){for(let t=i.length-1;t>=0;--t)if(i[t]>=65535)return!0;return!1}function Sp(i){return ArrayBuffer.isView(i)&&!(i instanceof DataView)}function qs(i){return document.createElementNS("http://www.w3.org/1999/xhtml",i)}function ed(){let i=qs("canvas");return i.style.display="block",i}var Wh={},ls=null;function Ys(...i){let t="THREE."+i.shift();ls?ls("log",t,...i):console.log(t,...i)}function nd(i){let t=i[0];if(typeof t=="string"&&t.startsWith("TSL:")){let e=i[1];e&&e.isStackTrace?i[0]+=" "+e.getLocation():i[1]='Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.'}return i}function Dt(...i){i=nd(i);let t="THREE."+i.shift();if(ls)ls("warn",t,...i);else{let e=i[0];e&&e.isStackTrace?console.warn(e.getError(t)):console.warn(t,...i)}}function Ut(...i){i=nd(i);let t="THREE."+i.shift();if(ls)ls("error",t,...i);else{let e=i[0];e&&e.isStackTrace?console.error(e.getError(t)):console.error(t,...i)}}function Ti(...i){let t=i.join(" ");t in Wh||(Wh[t]=!0,Dt(...i))}function id(i,t,e){return new Promise(function(n,s){function r(){switch(i.clientWaitSync(t,i.SYNC_FLUSH_COMMANDS_BIT,0)){case i.WAIT_FAILED:s();break;case i.TIMEOUT_EXPIRED:setTimeout(r,e);break;default:n()}}setTimeout(r,e)})}var sd={[go]:_o,[xo]:Mo,[vo]:bo,[rs]:yo,[_o]:go,[Mo]:xo,[bo]:vo,[yo]:rs},Ln=class{addEventListener(t,e){this._listeners===void 0&&(this._listeners={});let n=this._listeners;n[t]===void 0&&(n[t]=[]),n[t].indexOf(e)===-1&&n[t].push(e)}hasEventListener(t,e){let n=this._listeners;return n===void 0?!1:n[t]!==void 0&&n[t].indexOf(e)!==-1}removeEventListener(t,e){let n=this._listeners;if(n===void 0)return;let s=n[t];if(s!==void 0){let r=s.indexOf(e);r!==-1&&s.splice(r,1)}}dispatchEvent(t){let e=this._listeners;if(e===void 0)return;let n=e[t.type];if(n!==void 0){t.target=this;let s=n.slice(0);for(let r=0,o=s.length;r>8&255]+qe[i>>16&255]+qe[i>>24&255]+"-"+qe[t&255]+qe[t>>8&255]+"-"+qe[t>>16&15|64]+qe[t>>24&255]+"-"+qe[e&63|128]+qe[e>>8&255]+"-"+qe[e>>16&255]+qe[e>>24&255]+qe[n&255]+qe[n>>8&255]+qe[n>>16&255]+qe[n>>24&255]).toLowerCase()}function $t(i,t,e){return Math.max(t,Math.min(e,i))}function Ec(i,t){return(i%t+t)%t}function wp(i,t,e,n,s){return n+(i-t)*(s-n)/(e-t)}function Ep(i,t,e){return i!==t?(e-i)/(t-i):0}function Vs(i,t,e){return(1-e)*i+e*t}function Tp(i,t,e,n){return Vs(i,t,1-Math.exp(-e*n))}function Ap(i,t=1){return t-Math.abs(Ec(i,t*2)-t)}function Rp(i,t,e){return i<=t?0:i>=e?1:(i=(i-t)/(e-t),i*i*(3-2*i))}function Cp(i,t,e){return i<=t?0:i>=e?1:(i=(i-t)/(e-t),i*i*i*(i*(i*6-15)+10))}function Ip(i,t){return i+Math.floor(Math.random()*(t-i+1))}function Pp(i,t){return i+Math.random()*(t-i)}function Lp(i){return i*(.5-Math.random())}function Dp(i){i!==void 0&&(Xh=i);let t=Xh+=1831565813;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}function Np(i){return i*is}function Up(i){return i*cs}function Fp(i){return i>0&&Number.isInteger(i)&&2**Math.round(Math.log2(i))===i}function Bp(i){return Math.pow(2,Math.ceil(Math.log(i)/Math.LN2))}function Op(i){return Math.pow(2,Math.floor(Math.log(i)/Math.LN2))}function zp(i,t,e,n,s){let r=Math.cos,o=Math.sin,a=r(e/2),l=o(e/2),c=r((t+n)/2),h=o((t+n)/2),d=r((t-n)/2),u=o((t-n)/2),p=r((n-t)/2),g=o((n-t)/2);switch(s){case"XYX":i.set(a*h,l*d,l*u,a*c);break;case"YZY":i.set(l*u,a*h,l*d,a*c);break;case"ZXZ":i.set(l*d,l*u,a*h,a*c);break;case"XZX":i.set(a*h,l*g,l*p,a*c);break;case"YXY":i.set(l*p,a*h,l*g,a*c);break;case"ZYZ":i.set(l*g,l*p,a*h,a*c);break;default:Dt("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+s)}}function _n(i,t){switch(t.constructor){case Float32Array:return i;case Uint32Array:return i/4294967295;case Uint16Array:return i/65535;case Uint8Array:case Uint8ClampedArray:return i/255;case Int32Array:return Math.max(i/2147483647,-1);case Int16Array:return Math.max(i/32767,-1);case Int8Array:return Math.max(i/127,-1);default:throw new Error("THREE.MathUtils: Invalid component type.")}}function ne(i,t){switch(t.constructor){case Float32Array:return i;case Uint32Array:return Math.round(i*4294967295);case Uint16Array:return Math.round(i*65535);case Uint8Array:case Uint8ClampedArray:return Math.round(i*255);case Int32Array:return Math.round(i*2147483647);case Int16Array:return Math.round(i*32767);case Int8Array:return Math.round(i*127);default:throw new Error("THREE.MathUtils: Invalid component type.")}}var de={DEG2RAD:is,RAD2DEG:cs,generateUUID:$n,clamp:$t,euclideanModulo:Ec,mapLinear:wp,inverseLerp:Ep,lerp:Vs,damp:Tp,pingpong:Ap,smoothstep:Rp,smootherstep:Cp,randInt:Ip,randFloat:Pp,randFloatSpread:Lp,seededRandom:Dp,degToRad:Np,radToDeg:Up,isPowerOfTwo:Fp,ceilPowerOfTwo:Bp,floorPowerOfTwo:Op,setQuaternionFromProperEuler:zp,normalize:ne,denormalize:_n},Ic=class Ic{constructor(t=0,e=0){this.x=t,this.y=e}get width(){return this.x}set width(t){this.x=t}get height(){return this.y}set height(t){this.y=t}set(t,e){return this.x=t,this.y=e,this}setScalar(t){return this.x=t,this.y=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;default:throw new Error("THREE.Vector2: index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;default:throw new Error("THREE.Vector2: index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y)}copy(t){return this.x=t.x,this.y=t.y,this}add(t){return this.x+=t.x,this.y+=t.y,this}addScalar(t){return this.x+=t,this.y+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this}subScalar(t){return this.x-=t,this.y-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this}multiply(t){return this.x*=t.x,this.y*=t.y,this}multiplyScalar(t){return this.x*=t,this.y*=t,this}divide(t){return this.x/=t.x,this.y/=t.y,this}divideScalar(t){return this.multiplyScalar(1/t)}applyMatrix3(t){let e=this.x,n=this.y,s=t.elements;return this.x=s[0]*e+s[3]*n+s[6],this.y=s[1]*e+s[4]*n+s[7],this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this}clamp(t,e){return this.x=$t(this.x,t.x,e.x),this.y=$t(this.y,t.y,e.y),this}clampScalar(t,e){return this.x=$t(this.x,t,e),this.y=$t(this.y,t,e),this}clampLength(t,e){let n=this.length();return this.divideScalar(n||1).multiplyScalar($t(n,t,e))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(t){return this.x*t.x+this.y*t.y}cross(t){return this.x*t.y-this.y*t.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(t){let e=Math.sqrt(this.lengthSq()*t.lengthSq());if(e===0)return Math.PI/2;let n=this.dot(t)/e;return Math.acos($t(n,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){let e=this.x-t.x,n=this.y-t.y;return e*e+n*n}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this}lerpVectors(t,e,n){return this.x=t.x+(e.x-t.x)*n,this.y=t.y+(e.y-t.y)*n,this}equals(t){return t.x===this.x&&t.y===this.y}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this}rotateAround(t,e){let n=Math.cos(e),s=Math.sin(e),r=this.x-t.x,o=this.y-t.y;return this.x=r*n-o*s+t.x,this.y=r*s+o*n+t.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}};Ic.prototype.isVector2=!0;var Ht=Ic,Ce=class{constructor(t=0,e=0,n=0,s=1){this.isQuaternion=!0,this._x=t,this._y=e,this._z=n,this._w=s}static slerpFlat(t,e,n,s,r,o,a){let l=n[s+0],c=n[s+1],h=n[s+2],d=n[s+3],u=r[o+0],p=r[o+1],g=r[o+2],_=r[o+3];if(d!==_||l!==u||c!==p||h!==g){let m=l*u+c*p+h*g+d*_;m<0&&(u=-u,p=-p,g=-g,_=-_,m=-m);let f=1-a;if(m<.9995){let b=Math.acos(m),E=Math.sin(b);f=Math.sin(f*b)/E,a=Math.sin(a*b)/E,l=l*f+u*a,c=c*f+p*a,h=h*f+g*a,d=d*f+_*a}else{l=l*f+u*a,c=c*f+p*a,h=h*f+g*a,d=d*f+_*a;let b=1/Math.sqrt(l*l+c*c+h*h+d*d);l*=b,c*=b,h*=b,d*=b}}t[e]=l,t[e+1]=c,t[e+2]=h,t[e+3]=d}static multiplyQuaternionsFlat(t,e,n,s,r,o){let a=n[s],l=n[s+1],c=n[s+2],h=n[s+3],d=r[o],u=r[o+1],p=r[o+2],g=r[o+3];return t[e]=a*g+h*d+l*p-c*u,t[e+1]=l*g+h*u+c*d-a*p,t[e+2]=c*g+h*p+a*u-l*d,t[e+3]=h*g-a*d-l*u-c*p,t}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get w(){return this._w}set w(t){this._w=t,this._onChangeCallback()}set(t,e,n,s){return this._x=t,this._y=e,this._z=n,this._w=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(t){return this._x=t.x,this._y=t.y,this._z=t.z,this._w=t.w,this._onChangeCallback(),this}setFromEuler(t,e=!0){let n=t._x,s=t._y,r=t._z,o=t._order,a=Math.cos,l=Math.sin,c=a(n/2),h=a(s/2),d=a(r/2),u=l(n/2),p=l(s/2),g=l(r/2);switch(o){case"XYZ":this._x=u*h*d+c*p*g,this._y=c*p*d-u*h*g,this._z=c*h*g+u*p*d,this._w=c*h*d-u*p*g;break;case"YXZ":this._x=u*h*d+c*p*g,this._y=c*p*d-u*h*g,this._z=c*h*g-u*p*d,this._w=c*h*d+u*p*g;break;case"ZXY":this._x=u*h*d-c*p*g,this._y=c*p*d+u*h*g,this._z=c*h*g+u*p*d,this._w=c*h*d-u*p*g;break;case"ZYX":this._x=u*h*d-c*p*g,this._y=c*p*d+u*h*g,this._z=c*h*g-u*p*d,this._w=c*h*d+u*p*g;break;case"YZX":this._x=u*h*d+c*p*g,this._y=c*p*d+u*h*g,this._z=c*h*g-u*p*d,this._w=c*h*d-u*p*g;break;case"XZY":this._x=u*h*d-c*p*g,this._y=c*p*d-u*h*g,this._z=c*h*g+u*p*d,this._w=c*h*d+u*p*g;break;default:Dt("Quaternion: .setFromEuler() encountered an unknown order: "+o)}return e===!0&&this._onChangeCallback(),this}setFromAxisAngle(t,e){let n=e/2,s=Math.sin(n);return this._x=t.x*s,this._y=t.y*s,this._z=t.z*s,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(t){let e=t.elements,n=e[0],s=e[4],r=e[8],o=e[1],a=e[5],l=e[9],c=e[2],h=e[6],d=e[10],u=n+a+d;if(u>0){let p=.5/Math.sqrt(u+1);this._w=.25/p,this._x=(h-l)*p,this._y=(r-c)*p,this._z=(o-s)*p}else if(n>a&&n>d){let p=2*Math.sqrt(1+n-a-d);this._w=(h-l)/p,this._x=.25*p,this._y=(s+o)/p,this._z=(r+c)/p}else if(a>d){let p=2*Math.sqrt(1+a-n-d);this._w=(r-c)/p,this._x=(s+o)/p,this._y=.25*p,this._z=(l+h)/p}else{let p=2*Math.sqrt(1+d-n-a);this._w=(o-s)/p,this._x=(r+c)/p,this._y=(l+h)/p,this._z=.25*p}return this._onChangeCallback(),this}setFromUnitVectors(t,e){let n=t.dot(e)+1;return n<1e-8?(n=0,Math.abs(t.x)>Math.abs(t.z)?(this._x=-t.y,this._y=t.x,this._z=0,this._w=n):(this._x=0,this._y=-t.z,this._z=t.y,this._w=n)):(this._x=t.y*e.z-t.z*e.y,this._y=t.z*e.x-t.x*e.z,this._z=t.x*e.y-t.y*e.x,this._w=n),this.normalize()}angleTo(t){return 2*Math.acos(Math.abs($t(this.dot(t),-1,1)))}rotateTowards(t,e){let n=this.angleTo(t);if(n===0)return this;let s=Math.min(1,e/n);return this.slerp(t,s),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(t){return this._x*t._x+this._y*t._y+this._z*t._z+this._w*t._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let t=this.length();return t===0?(this._x=0,this._y=0,this._z=0,this._w=1):(t=1/t,this._x=this._x*t,this._y=this._y*t,this._z=this._z*t,this._w=this._w*t),this._onChangeCallback(),this}multiply(t){return this.multiplyQuaternions(this,t)}premultiply(t){return this.multiplyQuaternions(t,this)}multiplyQuaternions(t,e){let n=t._x,s=t._y,r=t._z,o=t._w,a=e._x,l=e._y,c=e._z,h=e._w;return this._x=n*h+o*a+s*c-r*l,this._y=s*h+o*l+r*a-n*c,this._z=r*h+o*c+n*l-s*a,this._w=o*h-n*a-s*l-r*c,this._onChangeCallback(),this}slerp(t,e){let n=t._x,s=t._y,r=t._z,o=t._w,a=this.dot(t);a<0&&(n=-n,s=-s,r=-r,o=-o,a=-a);let l=1-e;if(a<.9995){let c=Math.acos(a),h=Math.sin(c);l=Math.sin(l*c)/h,e=Math.sin(e*c)/h,this._x=this._x*l+n*e,this._y=this._y*l+s*e,this._z=this._z*l+r*e,this._w=this._w*l+o*e,this._onChangeCallback()}else this._x=this._x*l+n*e,this._y=this._y*l+s*e,this._z=this._z*l+r*e,this._w=this._w*l+o*e,this.normalize();return this}slerpQuaternions(t,e,n){return this.copy(t).slerp(e,n)}random(){let t=2*Math.PI*Math.random(),e=2*Math.PI*Math.random(),n=Math.random(),s=Math.sqrt(1-n),r=Math.sqrt(n);return this.set(s*Math.sin(t),s*Math.cos(t),r*Math.sin(e),r*Math.cos(e))}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._w===this._w}fromArray(t,e=0){return this._x=t[e],this._y=t[e+1],this._z=t[e+2],this._w=t[e+3],this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._w,t}fromBufferAttribute(t,e){return this._x=t.getX(e),this._y=t.getY(e),this._z=t.getZ(e),this._w=t.getW(e),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}},Pc=class Pc{constructor(t=0,e=0,n=0){this.x=t,this.y=e,this.z=n}set(t,e,n){return n===void 0&&(n=this.z),this.x=t,this.y=e,this.z=n,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;default:throw new Error("THREE.Vector3: index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("THREE.Vector3: index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this}multiplyVectors(t,e){return this.x=t.x*e.x,this.y=t.y*e.y,this.z=t.z*e.z,this}applyEuler(t){return this.applyQuaternion(qh.setFromEuler(t))}applyAxisAngle(t,e){return this.applyQuaternion(qh.setFromAxisAngle(t,e))}applyMatrix3(t){let e=this.x,n=this.y,s=this.z,r=t.elements;return this.x=r[0]*e+r[3]*n+r[6]*s,this.y=r[1]*e+r[4]*n+r[7]*s,this.z=r[2]*e+r[5]*n+r[8]*s,this}applyNormalMatrix(t){return this.applyMatrix3(t).normalize()}applyMatrix4(t){let e=this.x,n=this.y,s=this.z,r=t.elements,o=1/(r[3]*e+r[7]*n+r[11]*s+r[15]);return this.x=(r[0]*e+r[4]*n+r[8]*s+r[12])*o,this.y=(r[1]*e+r[5]*n+r[9]*s+r[13])*o,this.z=(r[2]*e+r[6]*n+r[10]*s+r[14])*o,this}applyQuaternion(t){let e=this.x,n=this.y,s=this.z,r=t.x,o=t.y,a=t.z,l=t.w,c=2*(o*s-a*n),h=2*(a*e-r*s),d=2*(r*n-o*e);return this.x=e+l*c+o*d-a*h,this.y=n+l*h+a*c-r*d,this.z=s+l*d+r*h-o*c,this}project(t){return this.applyMatrix4(t.matrixWorldInverse).applyMatrix4(t.projectionMatrix)}unproject(t){return this.applyMatrix4(t.projectionMatrixInverse).applyMatrix4(t.matrixWorld)}transformDirection(t){let e=this.x,n=this.y,s=this.z,r=t.elements;return this.x=r[0]*e+r[4]*n+r[8]*s,this.y=r[1]*e+r[5]*n+r[9]*s,this.z=r[2]*e+r[6]*n+r[10]*s,this.normalize()}divide(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this}divideScalar(t){return this.multiplyScalar(1/t)}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this}clamp(t,e){return this.x=$t(this.x,t.x,e.x),this.y=$t(this.y,t.y,e.y),this.z=$t(this.z,t.z,e.z),this}clampScalar(t,e){return this.x=$t(this.x,t,e),this.y=$t(this.y,t,e),this.z=$t(this.z,t,e),this}clampLength(t,e){let n=this.length();return this.divideScalar(n||1).multiplyScalar($t(n,t,e))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this}lerpVectors(t,e,n){return this.x=t.x+(e.x-t.x)*n,this.y=t.y+(e.y-t.y)*n,this.z=t.z+(e.z-t.z)*n,this}cross(t){return this.crossVectors(this,t)}crossVectors(t,e){let n=t.x,s=t.y,r=t.z,o=e.x,a=e.y,l=e.z;return this.x=s*l-r*a,this.y=r*o-n*l,this.z=n*a-s*o,this}projectOnVector(t){let e=t.lengthSq();if(e===0)return this.set(0,0,0);let n=t.dot(this)/e;return this.copy(t).multiplyScalar(n)}projectOnPlane(t){return Ml.copy(this).projectOnVector(t),this.sub(Ml)}reflect(t){return this.sub(Ml.copy(t).multiplyScalar(2*this.dot(t)))}angleTo(t){let e=Math.sqrt(this.lengthSq()*t.lengthSq());if(e===0)return Math.PI/2;let n=this.dot(t)/e;return Math.acos($t(n,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){let e=this.x-t.x,n=this.y-t.y,s=this.z-t.z;return e*e+n*n+s*s}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)+Math.abs(this.z-t.z)}setFromSpherical(t){return this.setFromSphericalCoords(t.radius,t.phi,t.theta)}setFromSphericalCoords(t,e,n){let s=Math.sin(e)*t;return this.x=s*Math.sin(n),this.y=Math.cos(e)*t,this.z=s*Math.cos(n),this}setFromCylindrical(t){return this.setFromCylindricalCoords(t.radius,t.theta,t.y)}setFromCylindricalCoords(t,e,n){return this.x=t*Math.sin(e),this.y=n,this.z=t*Math.cos(e),this}setFromMatrixPosition(t){let e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this}setFromMatrixScale(t){let e=this.setFromMatrixColumn(t,0).length(),n=this.setFromMatrixColumn(t,1).length(),s=this.setFromMatrixColumn(t,2).length();return this.x=e,this.y=n,this.z=s,this}setFromMatrixColumn(t,e){return this.fromArray(t.elements,e*4)}setFromMatrix3Column(t,e){return this.fromArray(t.elements,e*3)}setFromEuler(t){return this.x=t._x,this.y=t._y,this.z=t._z,this}setFromColor(t){return this.x=t.r,this.y=t.g,this.z=t.b,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this.z=t.getZ(e),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){let t=Math.random()*Math.PI*2,e=Math.random()*2-1,n=Math.sqrt(1-e*e);return this.x=n*Math.cos(t),this.y=e,this.z=n*Math.sin(t),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}};Pc.prototype.isVector3=!0;var I=Pc,Ml=new I,qh=new Ce,Lc=class Lc{constructor(t,e,n,s,r,o,a,l,c){this.elements=[1,0,0,0,1,0,0,0,1],t!==void 0&&this.set(t,e,n,s,r,o,a,l,c)}set(t,e,n,s,r,o,a,l,c){let h=this.elements;return h[0]=t,h[1]=s,h[2]=a,h[3]=e,h[4]=r,h[5]=l,h[6]=n,h[7]=o,h[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(t){let e=this.elements,n=t.elements;return e[0]=n[0],e[1]=n[1],e[2]=n[2],e[3]=n[3],e[4]=n[4],e[5]=n[5],e[6]=n[6],e[7]=n[7],e[8]=n[8],this}extractBasis(t,e,n){return t.setFromMatrix3Column(this,0),e.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(t){let e=t.elements;return this.set(e[0],e[4],e[8],e[1],e[5],e[9],e[2],e[6],e[10]),this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){let n=t.elements,s=e.elements,r=this.elements,o=n[0],a=n[3],l=n[6],c=n[1],h=n[4],d=n[7],u=n[2],p=n[5],g=n[8],_=s[0],m=s[3],f=s[6],b=s[1],E=s[4],M=s[7],v=s[2],S=s[5],A=s[8];return r[0]=o*_+a*b+l*v,r[3]=o*m+a*E+l*S,r[6]=o*f+a*M+l*A,r[1]=c*_+h*b+d*v,r[4]=c*m+h*E+d*S,r[7]=c*f+h*M+d*A,r[2]=u*_+p*b+g*v,r[5]=u*m+p*E+g*S,r[8]=u*f+p*M+g*A,this}multiplyScalar(t){let e=this.elements;return e[0]*=t,e[3]*=t,e[6]*=t,e[1]*=t,e[4]*=t,e[7]*=t,e[2]*=t,e[5]*=t,e[8]*=t,this}determinant(){let t=this.elements,e=t[0],n=t[1],s=t[2],r=t[3],o=t[4],a=t[5],l=t[6],c=t[7],h=t[8];return e*o*h-e*a*c-n*r*h+n*a*l+s*r*c-s*o*l}invert(){let t=this.elements,e=t[0],n=t[1],s=t[2],r=t[3],o=t[4],a=t[5],l=t[6],c=t[7],h=t[8],d=h*o-a*c,u=a*l-h*r,p=c*r-o*l,g=e*d+n*u+s*p;if(g===0)return this.set(0,0,0,0,0,0,0,0,0);let _=1/g;return t[0]=d*_,t[1]=(s*c-h*n)*_,t[2]=(a*n-s*o)*_,t[3]=u*_,t[4]=(h*e-s*l)*_,t[5]=(s*r-a*e)*_,t[6]=p*_,t[7]=(n*l-c*e)*_,t[8]=(o*e-n*r)*_,this}transpose(){let t,e=this.elements;return t=e[1],e[1]=e[3],e[3]=t,t=e[2],e[2]=e[6],e[6]=t,t=e[5],e[5]=e[7],e[7]=t,this}getNormalMatrix(t){return this.setFromMatrix4(t).invert().transpose()}transposeIntoArray(t){let e=this.elements;return t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8],this}setUvTransform(t,e,n,s,r,o,a){let l=Math.cos(r),c=Math.sin(r);return this.set(n*l,n*c,-n*(l*o+c*a)+o+t,-s*c,s*l,-s*(-c*o+l*a)+a+e,0,0,1),this}scale(t,e){return Ti("Matrix3: .scale() is deprecated. Use .makeScale() instead."),this.premultiply(bl.makeScale(t,e)),this}rotate(t){return Ti("Matrix3: .rotate() is deprecated. Use .makeRotation() instead."),this.premultiply(bl.makeRotation(-t)),this}translate(t,e){return Ti("Matrix3: .translate() is deprecated. Use .makeTranslation() instead."),this.premultiply(bl.makeTranslation(t,e)),this}makeTranslation(t,e){return t.isVector2?this.set(1,0,t.x,0,1,t.y,0,0,1):this.set(1,0,t,0,1,e,0,0,1),this}makeRotation(t){let e=Math.cos(t),n=Math.sin(t);return this.set(e,-n,0,n,e,0,0,0,1),this}makeScale(t,e){return this.set(t,0,0,0,e,0,0,0,1),this}equals(t){let e=this.elements,n=t.elements;for(let s=0;s<9;s++)if(e[s]!==n[s])return!1;return!0}fromArray(t,e=0){for(let n=0;n<9;n++)this.elements[n]=t[n+e];return this}toArray(t=[],e=0){let n=this.elements;return t[e]=n[0],t[e+1]=n[1],t[e+2]=n[2],t[e+3]=n[3],t[e+4]=n[4],t[e+5]=n[5],t[e+6]=n[6],t[e+7]=n[7],t[e+8]=n[8],t}clone(){return new this.constructor().fromArray(this.elements)}};Lc.prototype.isMatrix3=!0;var Ot=Lc,bl=new Ot,Yh=new Ot().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),$h=new Ot().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function kp(){let i={enabled:!0,workingColorSpace:Ws,spaces:{},convert:function(s,r,o){return this.enabled===!1||r===o||!r||!o||(this.spaces[r].transfer===te&&(s.r=Zn(s.r),s.g=Zn(s.g),s.b=Zn(s.b)),this.spaces[r].primaries!==this.spaces[o].primaries&&(s.applyMatrix3(this.spaces[r].toXYZ),s.applyMatrix3(this.spaces[o].fromXYZ)),this.spaces[o].transfer===te&&(s.r=ss(s.r),s.g=ss(s.g),s.b=ss(s.b))),s},workingToColorSpace:function(s,r){return this.convert(s,this.workingColorSpace,r)},colorSpaceToWorking:function(s,r){return this.convert(s,r,this.workingColorSpace)},getPrimaries:function(s){return this.spaces[s].primaries},getTransfer:function(s){return s===jn?Xs:this.spaces[s].transfer},getToneMappingMode:function(s){return this.spaces[s].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(s,r=this.workingColorSpace){return s.fromArray(this.spaces[r].luminanceCoefficients)},define:function(s){Object.assign(this.spaces,s)},_getMatrix:function(s,r,o){return s.copy(this.spaces[r].toXYZ).multiply(this.spaces[o].fromXYZ)},_getDrawingBufferColorSpace:function(s){return this.spaces[s].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(s=this.workingColorSpace){return this.spaces[s].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(s,r){return Ti("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),i.workingToColorSpace(s,r)},toWorkingColorSpace:function(s,r){return Ti("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),i.colorSpaceToWorking(s,r)}},t=[.64,.33,.3,.6,.15,.06],e=[.2126,.7152,.0722],n=[.3127,.329];return i.define({[Ws]:{primaries:t,whitePoint:n,transfer:Xs,toXYZ:Yh,fromXYZ:$h,luminanceCoefficients:e,workingColorSpaceConfig:{unpackColorSpace:Ae},outputColorSpaceConfig:{drawingBufferColorSpace:Ae}},[Ae]:{primaries:t,whitePoint:n,transfer:te,toXYZ:Yh,fromXYZ:$h,luminanceCoefficients:e,outputColorSpaceConfig:{drawingBufferColorSpace:Ae}}}),i}var Yt=kp();function Zn(i){return i<.04045?i*.0773993808:Math.pow(i*.9478672986+.0521327014,2.4)}function ss(i){return i<.0031308?i*12.92:1.055*Math.pow(i,.41666)-.055}var Gi,Eo=class{static getDataURL(t,e="image/png"){if(/^data:/i.test(t.src)||typeof HTMLCanvasElement>"u")return t.src;let n;if(t instanceof HTMLCanvasElement)n=t;else{Gi===void 0&&(Gi=qs("canvas")),Gi.width=t.width,Gi.height=t.height;let s=Gi.getContext("2d");t instanceof ImageData?s.putImageData(t,0,0):s.drawImage(t,0,0,t.width,t.height),n=Gi}return n.toDataURL(e)}static sRGBToLinear(t){if(typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&t instanceof ImageBitmap){let e=qs("canvas");e.width=t.width,e.height=t.height;let n=e.getContext("2d");n.drawImage(t,0,0,t.width,t.height);let s=n.getImageData(0,0,t.width,t.height),r=s.data;for(let o=0;o1),this.pmremVersion=0,this.normalized=!1}get width(){return this.source.getSize(wl).x}get height(){return this.source.getSize(wl).y}get depth(){return this.source.getSize(wl).z}get image(){return this.source.data}set image(t){this.source.data=t}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(t,e){this.updateRanges.push({start:t,count:e})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(t){return this.name=t.name,this.source=t.source,this.mipmaps=t.mipmaps.slice(0),this.mapping=t.mapping,this.channel=t.channel,this.wrapS=t.wrapS,this.wrapT=t.wrapT,this.magFilter=t.magFilter,this.minFilter=t.minFilter,this.anisotropy=t.anisotropy,this.format=t.format,this.internalFormat=t.internalFormat,this.type=t.type,this.normalized=t.normalized,this.offset.copy(t.offset),this.repeat.copy(t.repeat),this.center.copy(t.center),this.rotation=t.rotation,this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrix.copy(t.matrix),this.generateMipmaps=t.generateMipmaps,this.premultiplyAlpha=t.premultiplyAlpha,this.flipY=t.flipY,this.unpackAlignment=t.unpackAlignment,this.colorSpace=t.colorSpace,this.renderTarget=t.renderTarget,this.isRenderTargetTexture=t.isRenderTargetTexture,this.isArrayTexture=t.isArrayTexture,this.userData=JSON.parse(JSON.stringify(t.userData)),this.needsUpdate=!0,this}setValues(t){for(let e in t){let n=t[e];if(n===void 0){Dt(`Texture.setValues(): parameter '${e}' has value of undefined.`);continue}let s=this[e];if(s===void 0){Dt(`Texture.setValues(): property '${e}' does not exist.`);continue}s&&n&&s.isVector2&&n.isVector2||s&&n&&s.isVector3&&n.isVector3||s&&n&&s.isMatrix3&&n.isMatrix3?s.copy(n):this[e]=n}}toJSON(t){let e=t===void 0||typeof t=="string";if(!e&&t.textures[this.uuid]!==void 0)return t.textures[this.uuid];let n={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(t).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,normalized:this.normalized,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(n.userData=this.userData),e||(t.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(t){if(this.mapping!==dc)return t;if(t.applyMatrix3(this.matrix),t.x<0||t.x>1)switch(this.wrapS){case os:t.x=t.x-Math.floor(t.x);break;case In:t.x=t.x<0?0:1;break;case So:Math.abs(Math.floor(t.x)%2)===1?t.x=Math.ceil(t.x)-t.x:t.x=t.x-Math.floor(t.x);break}if(t.y<0||t.y>1)switch(this.wrapT){case os:t.y=t.y-Math.floor(t.y);break;case In:t.y=t.y<0?0:1;break;case So:Math.abs(Math.floor(t.y)%2)===1?t.y=Math.ceil(t.y)-t.y:t.y=t.y-Math.floor(t.y);break}return this.flipY&&(t.y=1-t.y),t}set needsUpdate(t){t===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(t){t===!0&&this.pmremVersion++}};ke.DEFAULT_IMAGE=null;ke.DEFAULT_MAPPING=dc;ke.DEFAULT_ANISOTROPY=1;var Dc=class Dc{constructor(t=0,e=0,n=0,s=1){this.x=t,this.y=e,this.z=n,this.w=s}get width(){return this.z}set width(t){this.z=t}get height(){return this.w}set height(t){this.w=t}set(t,e,n,s){return this.x=t,this.y=e,this.z=n,this.w=s,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this.w=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setW(t){return this.w=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;case 3:this.w=e;break;default:throw new Error("THREE.Vector4: index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("THREE.Vector4: index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w!==void 0?t.w:1,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this.w+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this.w=t.w+e.w,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this.w+=t.w*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this.w-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this.w=t.w-e.w,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this}applyMatrix4(t){let e=this.x,n=this.y,s=this.z,r=this.w,o=t.elements;return this.x=o[0]*e+o[4]*n+o[8]*s+o[12]*r,this.y=o[1]*e+o[5]*n+o[9]*s+o[13]*r,this.z=o[2]*e+o[6]*n+o[10]*s+o[14]*r,this.w=o[3]*e+o[7]*n+o[11]*s+o[15]*r,this}divide(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this.w/=t.w,this}divideScalar(t){return this.multiplyScalar(1/t)}setAxisAngleFromQuaternion(t){this.w=2*Math.acos(t.w);let e=Math.sqrt(1-t.w*t.w);return e<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=t.x/e,this.y=t.y/e,this.z=t.z/e),this}setAxisAngleFromRotationMatrix(t){let e,n,s,r,l=t.elements,c=l[0],h=l[4],d=l[8],u=l[1],p=l[5],g=l[9],_=l[2],m=l[6],f=l[10];if(Math.abs(h-u)<.01&&Math.abs(d-_)<.01&&Math.abs(g-m)<.01){if(Math.abs(h+u)<.1&&Math.abs(d+_)<.1&&Math.abs(g+m)<.1&&Math.abs(c+p+f-3)<.1)return this.set(1,0,0,0),this;e=Math.PI;let E=(c+1)/2,M=(p+1)/2,v=(f+1)/2,S=(h+u)/4,A=(d+_)/4,x=(g+m)/4;return E>M&&E>v?E<.01?(n=0,s=.707106781,r=.707106781):(n=Math.sqrt(E),s=S/n,r=A/n):M>v?M<.01?(n=.707106781,s=0,r=.707106781):(s=Math.sqrt(M),n=S/s,r=x/s):v<.01?(n=.707106781,s=.707106781,r=0):(r=Math.sqrt(v),n=A/r,s=x/r),this.set(n,s,r,e),this}let b=Math.sqrt((m-g)*(m-g)+(d-_)*(d-_)+(u-h)*(u-h));return Math.abs(b)<.001&&(b=1),this.x=(m-g)/b,this.y=(d-_)/b,this.z=(u-h)/b,this.w=Math.acos((c+p+f-1)/2),this}setFromMatrixPosition(t){let e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this.w=e[15],this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this.w=Math.min(this.w,t.w),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this.w=Math.max(this.w,t.w),this}clamp(t,e){return this.x=$t(this.x,t.x,e.x),this.y=$t(this.y,t.y,e.y),this.z=$t(this.z,t.z,e.z),this.w=$t(this.w,t.w,e.w),this}clampScalar(t,e){return this.x=$t(this.x,t,e),this.y=$t(this.y,t,e),this.z=$t(this.z,t,e),this.w=$t(this.w,t,e),this}clampLength(t,e){let n=this.length();return this.divideScalar(n||1).multiplyScalar($t(n,t,e))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z+this.w*t.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this.w+=(t.w-this.w)*e,this}lerpVectors(t,e,n){return this.x=t.x+(e.x-t.x)*n,this.y=t.y+(e.y-t.y)*n,this.z=t.z+(e.z-t.z)*n,this.w=t.w+(e.w-t.w)*n,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z&&t.w===this.w}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this.w=t[e+3],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t[e+3]=this.w,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this.z=t.getZ(e),this.w=t.getW(e),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}};Dc.prototype.isVector4=!0;var oe=Dc,To=class extends Ln{constructor(t=1,e=1,n={}){super(),n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:ze,depthBuffer:!0,stencilBuffer:!1,resolveColorBuffer:!0,resolveDepthBuffer:!0,resolveStencilBuffer:!0,storeMultisampledColorBuffer:!0,storeMultisampledDepthBuffer:!0,storeMultisampledStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1,useArrayDepthTexture:!1},n),this.isRenderTarget=!0,this.width=t,this.height=e,this.depth=n.depth,this.scissor=new oe(0,0,t,e),this.scissorTest=!1,this.viewport=new oe(0,0,t,e),this.textures=[];let s={width:t,height:e,depth:n.depth},r=new ke(s),o=n.count;for(let a=0;a1);this.dispose()}this.viewport.set(0,0,t,e),this.scissor.set(0,0,t,e)}clone(){return new this.constructor().copy(this)}copy(t){this.width=t.width,this.height=t.height,this.depth=t.depth,this.scissor.copy(t.scissor),this.scissorTest=t.scissorTest,this.viewport.copy(t.viewport),this.textures.length=0;for(let e=0,n=t.textures.length;e>>0}enable(t){this.mask|=1<1){for(let e=0;e1){for(let n=0;n0&&(s.userData=this.userData),s.layers=this.layers.mask,s.matrix=this.matrix.toArray(),s.up=this.up.toArray(),this.pivot!==null&&(s.pivot=this.pivot.toArray()),this.morphTargetDictionary!==void 0&&(s.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),this.morphTargetInfluences!==void 0&&(s.morphTargetInfluences=this.morphTargetInfluences.slice()),this.isInstancedMesh&&(s.type="InstancedMesh",s.count=this.count,s.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(s.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(s.type="BatchedMesh",s.perObjectFrustumCulled=this.perObjectFrustumCulled,s.sortObjects=this.sortObjects,s.drawRanges=this._drawRanges,s.reservedRanges=this._reservedRanges,s.geometryInfo=this._geometryInfo.map(a=>({...a,boundingBox:a.boundingBox?a.boundingBox.toJSON():void 0,boundingSphere:a.boundingSphere?a.boundingSphere.toJSON():void 0})),s.instanceInfo=this._instanceInfo.map(a=>({...a})),s.availableInstanceIds=this._availableInstanceIds.slice(),s.availableGeometryIds=this._availableGeometryIds.slice(),s.nextIndexStart=this._nextIndexStart,s.nextVertexStart=this._nextVertexStart,s.geometryCount=this._geometryCount,s.maxInstanceCount=this._maxInstanceCount,s.maxVertexCount=this._maxVertexCount,s.maxIndexCount=this._maxIndexCount,s.geometryInitialized=this._geometryInitialized,s.matricesTexture=this._matricesTexture.toJSON(t),s.indirectTexture=this._indirectTexture.toJSON(t),this._colorsTexture!==null&&(s.colorsTexture=this._colorsTexture.toJSON(t)),this.boundingSphere!==null&&(s.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(s.boundingBox=this.boundingBox.toJSON()));function r(a,l){return a[l.uuid]===void 0&&(a[l.uuid]=l.toJSON(t)),l.uuid}if(this.isScene)this.background&&(this.background.isColor?s.background=this.background.toJSON():this.background.isTexture&&(s.background=this.background.toJSON(t).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(s.environment=this.environment.toJSON(t).uuid);else if(this.isMesh||this.isLine||this.isPoints){s.geometry=r(t.geometries,this.geometry);let a=this.geometry.parameters;if(a!==void 0&&a.shapes!==void 0){let l=a.shapes;if(Array.isArray(l))for(let c=0,h=l.length;c0){s.children=[];for(let a=0;a0){s.animations=[];for(let a=0;a0&&(n.geometries=a),l.length>0&&(n.materials=l),c.length>0&&(n.textures=c),h.length>0&&(n.images=h),d.length>0&&(n.shapes=d),u.length>0&&(n.skeletons=u),p.length>0&&(n.animations=p),g.length>0&&(n.nodes=g)}return n.object=s,n;function o(a){let l=[];for(let c in a){let h=a[c];delete h.metadata,l.push(h)}return l}}clone(t){return new this.constructor().copy(this,t)}copy(t,e=!0){if(this.name=t.name,this.up.copy(t.up),this.position.copy(t.position),this.rotation.order=t.rotation.order,this.quaternion.copy(t.quaternion),this.scale.copy(t.scale),this.pivot=t.pivot!==null?t.pivot.clone():null,this.matrix.copy(t.matrix),this.matrixWorld.copy(t.matrixWorld),this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrixWorldAutoUpdate=t.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=t.matrixWorldNeedsUpdate,this.layers.mask=t.layers.mask,this.visible=t.visible,this.castShadow=t.castShadow,this.receiveShadow=t.receiveShadow,this.frustumCulled=t.frustumCulled,this.renderOrder=t.renderOrder,this.static=t.static,this.animations=t.animations.slice(),this.userData=JSON.parse(JSON.stringify(t.userData)),e===!0)for(let n=0;np+g?(c.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:t.handedness,target:this})):!c.inputState.pinching&&u<=p-g&&(c.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:t.handedness,target:this}))}else l!==null&&t.gripSpace&&(r=e.getPose(t.gripSpace,n),r!==null&&(l.matrix.fromArray(r.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),l.matrixWorldNeedsUpdate=!0,r.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(r.linearVelocity)):l.hasLinearVelocity=!1,r.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(r.angularVelocity)):l.hasAngularVelocity=!1,l.eventsEnabled&&l.dispatchEvent({type:"gripUpdated",data:t,target:this})));a!==null&&(s=e.getPose(t.targetRaySpace,n),s===null&&r!==null&&(s=r),s!==null&&(a.matrix.fromArray(s.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,s.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(s.linearVelocity)):a.hasLinearVelocity=!1,s.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(s.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(Zp)))}return a!==null&&(a.visible=s!==null),l!==null&&(l.visible=r!==null),c!==null&&(c.visible=o!==null),this}_getHandJoint(t,e){if(t.joints[e.jointName]===void 0){let n=new Re;n.matrixAutoUpdate=!1,n.visible=!1,t.joints[e.jointName]=n,t.add(n)}return t.joints[e.jointName]}},rd={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},ri={h:0,s:0,l:0},Vr={h:0,s:0,l:0};function Tl(i,t,e){return e<0&&(e+=1),e>1&&(e-=1),e<1/6?i+(t-i)*6*e:e<1/2?t:e<2/3?i+(t-i)*6*(2/3-e):i}var Ft=class{constructor(t,e,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(t,e,n)}set(t,e,n){if(e===void 0&&n===void 0){let s=t;s&&s.isColor?this.copy(s):typeof s=="number"?this.setHex(s):typeof s=="string"&&this.setStyle(s)}else this.setRGB(t,e,n);return this}setScalar(t){return this.r=t,this.g=t,this.b=t,this}setHex(t,e=Ae){return t=Math.floor(t),this.r=(t>>16&255)/255,this.g=(t>>8&255)/255,this.b=(t&255)/255,Yt.colorSpaceToWorking(this,e),this}setRGB(t,e,n,s=Yt.workingColorSpace){return this.r=t,this.g=e,this.b=n,Yt.colorSpaceToWorking(this,s),this}setHSL(t,e,n,s=Yt.workingColorSpace){if(t=Ec(t,1),e=$t(e,0,1),n=$t(n,0,1),e===0)this.r=this.g=this.b=n;else{let r=n<=.5?n*(1+e):n+e-n*e,o=2*n-r;this.r=Tl(o,r,t+1/3),this.g=Tl(o,r,t),this.b=Tl(o,r,t-1/3)}return Yt.colorSpaceToWorking(this,s),this}setStyle(t,e=Ae){function n(r){r!==void 0&&parseFloat(r)<1&&Dt("Color: Alpha component of "+t+" will be ignored.")}let s;if(s=/^(\w+)\(([^\)]*)\)/.exec(t)){let r,o=s[1],a=s[2];switch(o){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setRGB(Math.min(255,parseInt(r[1],10))/255,Math.min(255,parseInt(r[2],10))/255,Math.min(255,parseInt(r[3],10))/255,e);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setRGB(Math.min(100,parseInt(r[1],10))/100,Math.min(100,parseInt(r[2],10))/100,Math.min(100,parseInt(r[3],10))/100,e);break;case"hsl":case"hsla":if(r=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,e);break;default:Dt("Color: Unknown color model "+t)}}else if(s=/^\#([A-Fa-f\d]+)$/.exec(t)){let r=s[1],o=r.length;if(o===3)return this.setRGB(parseInt(r.charAt(0),16)/15,parseInt(r.charAt(1),16)/15,parseInt(r.charAt(2),16)/15,e);if(o===6)return this.setHex(parseInt(r,16),e);Dt("Color: Invalid hex color "+t)}else if(t&&t.length>0)return this.setColorName(t,e);return this}setColorName(t,e=Ae){let n=rd[t.toLowerCase()];return n!==void 0?this.setHex(n,e):Dt("Color: Unknown color "+t),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(t){return this.r=t.r,this.g=t.g,this.b=t.b,this}copySRGBToLinear(t){return this.r=Zn(t.r),this.g=Zn(t.g),this.b=Zn(t.b),this}copyLinearToSRGB(t){return this.r=ss(t.r),this.g=ss(t.g),this.b=ss(t.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(t=Ae){return Yt.workingToColorSpace(Ye.copy(this),t),Math.round($t(Ye.r*255,0,255))*65536+Math.round($t(Ye.g*255,0,255))*256+Math.round($t(Ye.b*255,0,255))}getHexString(t=Ae){return("000000"+this.getHex(t).toString(16)).slice(-6)}getHSL(t,e=Yt.workingColorSpace){Yt.workingToColorSpace(Ye.copy(this),e);let n=Ye.r,s=Ye.g,r=Ye.b,o=Math.max(n,s,r),a=Math.min(n,s,r),l,c,h=(a+o)/2;if(a===o)l=0,c=0;else{let d=o-a;switch(c=h<=.5?d/(o+a):d/(2-o-a),o){case n:l=(s-r)/d+(s0?s.multiplyScalar(1/Math.sqrt(r)):s.set(0,0,0)}static getBarycoord(t,e,n,s,r){mn.subVectors(s,e),Gn.subVectors(n,e),Al.subVectors(t,e);let o=mn.dot(mn),a=mn.dot(Gn),l=mn.dot(Al),c=Gn.dot(Gn),h=Gn.dot(Al),d=o*c-a*a;if(d===0)return r.set(0,0,0),null;let u=1/d,p=(c*l-a*h)*u,g=(o*h-a*l)*u;return r.set(1-p-g,g,p)}static containsPoint(t,e,n,s){return this.getBarycoord(t,e,n,s,Wn)===null?!1:Wn.x>=0&&Wn.y>=0&&Wn.x+Wn.y<=1}static getInterpolation(t,e,n,s,r,o,a,l){return this.getBarycoord(t,e,n,s,Wn)===null?(l.x=0,l.y=0,"z"in l&&(l.z=0),"w"in l&&(l.w=0),null):(l.setScalar(0),l.addScaledVector(r,Wn.x),l.addScaledVector(o,Wn.y),l.addScaledVector(a,Wn.z),l)}static getInterpolatedAttribute(t,e,n,s,r,o){return Pl.setScalar(0),Ll.setScalar(0),Dl.setScalar(0),Pl.fromBufferAttribute(t,e),Ll.fromBufferAttribute(t,n),Dl.fromBufferAttribute(t,s),o.setScalar(0),o.addScaledVector(Pl,r.x),o.addScaledVector(Ll,r.y),o.addScaledVector(Dl,r.z),o}static isFrontFacing(t,e,n,s){return mn.subVectors(n,e),Gn.subVectors(t,e),mn.cross(Gn).dot(s)<0}set(t,e,n){return this.a.copy(t),this.b.copy(e),this.c.copy(n),this}setFromPointsAndIndices(t,e,n,s){return this.a.copy(t[e]),this.b.copy(t[n]),this.c.copy(t[s]),this}setFromAttributeAndIndices(t,e,n,s){return this.a.fromBufferAttribute(t,e),this.b.fromBufferAttribute(t,n),this.c.fromBufferAttribute(t,s),this}clone(){return new this.constructor().copy(this)}copy(t){return this.a.copy(t.a),this.b.copy(t.b),this.c.copy(t.c),this}getArea(){return mn.subVectors(this.c,this.b),Gn.subVectors(this.a,this.b),mn.cross(Gn).length()*.5}getMidpoint(t){return t.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return i.getNormal(this.a,this.b,this.c,t)}getPlane(t){return t.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,e){return i.getBarycoord(t,this.a,this.b,this.c,e)}getInterpolation(t,e,n,s,r){return i.getInterpolation(t,this.a,this.b,this.c,e,n,s,r)}containsPoint(t){return i.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return i.isFrontFacing(this.a,this.b,this.c,t)}intersectsBox(t){return t.intersectsTriangle(this)}closestPointToPoint(t,e){let n=this.a,s=this.b,r=this.c,o,a;Yi.subVectors(s,n),$i.subVectors(r,n),Rl.subVectors(t,n);let l=Yi.dot(Rl),c=$i.dot(Rl);if(l<=0&&c<=0)return e.copy(n);Cl.subVectors(t,s);let h=Yi.dot(Cl),d=$i.dot(Cl);if(h>=0&&d<=h)return e.copy(s);let u=l*d-h*c;if(u<=0&&l>=0&&h<=0)return o=l/(l-h),e.copy(n).addScaledVector(Yi,o);Il.subVectors(t,r);let p=Yi.dot(Il),g=$i.dot(Il);if(g>=0&&p<=g)return e.copy(r);let _=p*c-l*g;if(_<=0&&c>=0&&g<=0)return a=c/(c-g),e.copy(n).addScaledVector($i,a);let m=h*g-p*d;if(m<=0&&d-h>=0&&p-g>=0)return nu.subVectors(r,s),a=(d-h)/(d-h+(p-g)),e.copy(s).addScaledVector(nu,a);let f=1/(m+_+u);return o=_*f,a=u*f,e.copy(n).addScaledVector(Yi,o).addScaledVector($i,a)}equals(t){return t.a.equals(this.a)&&t.b.equals(this.b)&&t.c.equals(this.c)}},ie=class{constructor(t=new I(1/0,1/0,1/0),e=new I(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=t,this.max=e}set(t,e){return this.min.copy(t),this.max.copy(e),this}setFromArray(t){this.makeEmpty();for(let e=0,n=t.length;e=this.min.x&&t.x<=this.max.x&&t.y>=this.min.y&&t.y<=this.max.y&&t.z>=this.min.z&&t.z<=this.max.z}containsBox(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y&&this.min.z<=t.min.z&&t.max.z<=this.max.z}getParameter(t,e){return e.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y),(t.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(t){return t.max.x>=this.min.x&&t.min.x<=this.max.x&&t.max.y>=this.min.y&&t.min.y<=this.max.y&&t.max.z>=this.min.z&&t.min.z<=this.max.z}intersectsSphere(t){return this.clampPoint(t.center,gn),gn.distanceToSquared(t.center)<=t.radius*t.radius}intersectsPlane(t){let e,n;return t.normal.x>0?(e=t.normal.x*this.min.x,n=t.normal.x*this.max.x):(e=t.normal.x*this.max.x,n=t.normal.x*this.min.x),t.normal.y>0?(e+=t.normal.y*this.min.y,n+=t.normal.y*this.max.y):(e+=t.normal.y*this.max.y,n+=t.normal.y*this.min.y),t.normal.z>0?(e+=t.normal.z*this.min.z,n+=t.normal.z*this.max.z):(e+=t.normal.z*this.max.z,n+=t.normal.z*this.min.z),e<=-t.constant&&n>=-t.constant}intersectsTriangle(t){if(this.isEmpty())return!1;this.getCenter(Fs),Wr.subVectors(this.max,Fs),Zi.subVectors(t.a,Fs),Ji.subVectors(t.b,Fs),Ki.subVectors(t.c,Fs),oi.subVectors(Ji,Zi),ai.subVectors(Ki,Ji),bi.subVectors(Zi,Ki);let e=[0,-oi.z,oi.y,0,-ai.z,ai.y,0,-bi.z,bi.y,oi.z,0,-oi.x,ai.z,0,-ai.x,bi.z,0,-bi.x,-oi.y,oi.x,0,-ai.y,ai.x,0,-bi.y,bi.x,0];return!Nl(e,Zi,Ji,Ki,Wr)||(e=[1,0,0,0,1,0,0,0,1],!Nl(e,Zi,Ji,Ki,Wr))?!1:(Xr.crossVectors(oi,ai),e=[Xr.x,Xr.y,Xr.z],Nl(e,Zi,Ji,Ki,Wr))}clampPoint(t,e){return e.copy(t).clamp(this.min,this.max)}distanceToPoint(t){return this.clampPoint(t,gn).distanceTo(t)}getBoundingSphere(t){return this.isEmpty()?t.makeEmpty():(this.getCenter(t.center),t.radius=this.getSize(gn).length()*.5),t}intersect(t){return this.min.max(t.min),this.max.min(t.max),this.isEmpty()&&this.makeEmpty(),this}union(t){return this.min.min(t.min),this.max.max(t.max),this}applyMatrix4(t){return this.isEmpty()?this:(Xn[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(t),Xn[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(t),Xn[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(t),Xn[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(t),Xn[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(t),Xn[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(t),Xn[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(t),Xn[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(t),this.setFromPoints(Xn),this)}translate(t){return this.min.add(t),this.max.add(t),this}equals(t){return t.min.equals(this.min)&&t.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(t){return this.min.fromArray(t.min),this.max.fromArray(t.max),this}},Xn=[new I,new I,new I,new I,new I,new I,new I,new I],gn=new I,Gr=new ie,Zi=new I,Ji=new I,Ki=new I,oi=new I,ai=new I,bi=new I,Fs=new I,Wr=new I,Xr=new I,Si=new I;function Nl(i,t,e,n,s){for(let r=0,o=i.length-3;r<=o;r+=3){Si.fromArray(i,r);let a=s.x*Math.abs(Si.x)+s.y*Math.abs(Si.y)+s.z*Math.abs(Si.z),l=t.dot(Si),c=e.dot(Si),h=n.dot(Si);if(Math.max(-Math.max(l,c,h),Math.min(l,c,h))>a)return!1}return!0}var Te=new I,qr=new Ht,Jp=0,Se=class extends Ln{constructor(t,e,n=!1){if(super(),Array.isArray(t))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:Jp++}),this.name="",this.array=t,this.itemSize=e,this.count=t!==void 0?t.length/e:0,this.normalized=n,this.usage=bc,this.updateRanges=[],this.gpuType=Ge,this.version=0}onUploadCallback(){}set needsUpdate(t){t===!0&&this.version++}setUsage(t){return this.usage=t,this}addUpdateRange(t,e){this.updateRanges.push({start:t,count:e})}clearUpdateRanges(){this.updateRanges.length=0}copy(t){return this.name=t.name,this.array=new t.array.constructor(t.array),this.itemSize=t.itemSize,this.count=t.count,this.normalized=t.normalized,this.usage=t.usage,this.gpuType=t.gpuType,this}copyAt(t,e,n){t*=this.itemSize,n*=e.itemSize;for(let s=0,r=this.itemSize;sthis.radius*this.radius&&(e.sub(this.center).normalize(),e.multiplyScalar(this.radius).add(this.center)),e}getBoundingBox(t){return this.isEmpty()?(t.makeEmpty(),t):(t.set(this.center,this.center),t.expandByScalar(this.radius),t)}applyMatrix4(t){return this.center.applyMatrix4(t),this.radius=this.radius*t.getMaxScaleOnAxis(),this}translate(t){return this.center.add(t),this}expandByPoint(t){if(this.isEmpty())return this.center.copy(t),this.radius=0,this;Bs.subVectors(t,this.center);let e=Bs.lengthSq();if(e>this.radius*this.radius){let n=Math.sqrt(e),s=(n-this.radius)*.5;this.center.addScaledVector(Bs,s/n),this.radius+=s}return this}union(t){return t.isEmpty()?this:this.isEmpty()?(this.copy(t),this):(this.center.equals(t.center)===!0?this.radius=Math.max(this.radius,t.radius):(Ul.subVectors(t.center,this.center).setLength(t.radius),this.expandByPoint(Bs.copy(t.center).add(Ul)),this.expandByPoint(Bs.copy(t.center).sub(Ul))),this)}equals(t){return t.center.equals(this.center)&&t.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(t){return this.radius=t.radius,this.center.fromArray(t.center),this}},jp=0,un=new kt,Fl=new Be,ji=new I,on=new ie,Os=new ie,Ne=new I,ae=class i extends Ln{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:jp++}),this.uuid=$n(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={},this._transformed=!1}getIndex(){return this.index}setIndex(t){return Array.isArray(t)?this.index=new(bp(t)?Js:Zs)(t,1):this.index=t,this}setIndirect(t,e=0){return this.indirect=t,this.indirectOffset=e,this}getIndirect(){return this.indirect}getAttribute(t){return this.attributes[t]}setAttribute(t,e){return this.attributes[t]=e,this}deleteAttribute(t){return delete this.attributes[t],this}hasAttribute(t){return this.attributes[t]!==void 0}addGroup(t,e,n=0){this.groups.push({start:t,count:e,materialIndex:n})}clearGroups(){this.groups=[]}setDrawRange(t,e){this.drawRange.start=t,this.drawRange.count=e}applyMatrix4(t){let e=this.attributes.position;e!==void 0&&(e.applyMatrix4(t),e.needsUpdate=!0);let n=this.attributes.normal;if(n!==void 0){let r=new Ot().getNormalMatrix(t);n.applyNormalMatrix(r),n.needsUpdate=!0}let s=this.attributes.tangent;return s!==void 0&&(s.transformDirection(t),s.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this._transformed=!0,this}applyQuaternion(t){return un.makeRotationFromQuaternion(t),this.applyMatrix4(un),this}rotateX(t){return un.makeRotationX(t),this.applyMatrix4(un),this}rotateY(t){return un.makeRotationY(t),this.applyMatrix4(un),this}rotateZ(t){return un.makeRotationZ(t),this.applyMatrix4(un),this}translate(t,e,n){return un.makeTranslation(t,e,n),this.applyMatrix4(un),this}scale(t,e,n){return un.makeScale(t,e,n),this.applyMatrix4(un),this}lookAt(t){return Fl.lookAt(t),Fl.updateMatrix(),this.applyMatrix4(Fl.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(ji).negate(),this.translate(ji.x,ji.y,ji.z),this}setFromPoints(t){let e=this.getAttribute("position");if(e===void 0){let n=[];for(let s=0,r=t.length;se.count&&Dt("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),e.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new ie);let t=this.attributes.position,e=this.morphAttributes.position;if(t&&t.isGLBufferAttribute){Ut("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new I(-1/0,-1/0,-1/0),new I(1/0,1/0,1/0));return}if(t!==void 0){if(this.boundingBox.setFromBufferAttribute(t),e)for(let n=0,s=e.length;n0&&(t.userData=this.userData),this.parameters!==void 0&&this._transformed!==!0){let l=this.parameters;for(let c in l)l[c]!==void 0&&(t[c]=l[c]);return t}t.data={attributes:{}};let e=this.index;e!==null&&(t.data.index={type:e.array.constructor.name,array:Array.prototype.slice.call(e.array)});let n=this.attributes;for(let l in n){let c=n[l];t.data.attributes[l]=c.toJSON(t.data)}let s={},r=!1;for(let l in this.morphAttributes){let c=this.morphAttributes[l],h=[];for(let d=0,u=c.length;d0&&(s[l]=h,r=!0)}r&&(t.data.morphAttributes=s,t.data.morphTargetsRelative=this.morphTargetsRelative);let o=this.groups;o.length>0&&(t.data.groups=JSON.parse(JSON.stringify(o)));let a=this.boundingSphere;return a!==null&&(t.data.boundingSphere=a.toJSON()),t}clone(){return new this.constructor().copy(this)}copy(t){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;let e={};this.name=t.name;let n=t.index;n!==null&&this.setIndex(n.clone());let s=t.attributes;for(let c in s){let h=s[c];this.setAttribute(c,h.clone(e))}let r=t.morphAttributes;for(let c in r){let h=[],d=r[c];for(let u=0,p=d.length;u1)?null:e.copy(t.start).addScaledVector(s,o)}intersectsLine(t){let e=this.distanceToPoint(t.start),n=this.distanceToPoint(t.end);return e<0&&n>0||n<0&&e>0}intersectsBox(t){return t.intersectsPlane(this)}intersectsSphere(t){return t.intersectsPlane(this)}coplanarPoint(t){return t.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(t,e){let n=e||tm.getNormalMatrix(t),s=this.coplanarPoint(Bl).applyMatrix4(t),r=this.normal.applyMatrix3(n).normalize();return this.constant=-s.dot(r),this}translate(t){return this.constant-=t.dot(this.normal),this}equals(t){return t.normal.equals(this.normal)&&t.constant===this.constant}clone(){return new this.constructor().copy(this)}toJSON(){return{normal:this.normal.toArray(),constant:this.constant}}fromJSON(t){return this.normal.fromArray(t.normal),this.constant=t.constant,this}},em=0,Dn=class extends Ln{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:em++}),this.uuid=$n(),this.name="",this.type="Material",this.blending=ys,this.side=Bn,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=ic,this.blendDst=sc,this.blendEquation=Ni,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new Ft(0,0,0),this.blendAlpha=0,this.depthFunc=rs,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=$u,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=mo,this.stencilZFail=mo,this.stencilZPass=mo,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(t){this._alphaTest>0!=t>0&&this.version++,this._alphaTest=t}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(t){if(t!==void 0)for(let e in t){let n=t[e];if(n===void 0){Dt(`Material: parameter '${e}' has value of undefined.`);continue}let s=this[e];if(s===void 0){Dt(`Material: '${e}' is not a property of THREE.${this.type}.`);continue}s&&s.isColor?s.set(n):s&&s.isVector2&&n&&n.isVector2||s&&s.isEuler&&n&&n.isEuler||s&&s.isVector3&&n&&n.isVector3?s.copy(n):this[e]=n}}toJSON(t){let e=t===void 0||typeof t=="string";e&&(t={textures:{},images:{}});let n={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};n.uuid=this.uuid,n.type=this.type,n.blending=this.blending,n.side=this.side,n.shadowSide=this.shadowSide,n.vertexColors=this.vertexColors,n.opacity=this.opacity,n.transparent=this.transparent,n.blendSrc=this.blendSrc,n.blendDst=this.blendDst,n.blendEquation=this.blendEquation,n.blendSrcAlpha=this.blendSrcAlpha,n.blendDstAlpha=this.blendDstAlpha,n.blendEquationAlpha=this.blendEquationAlpha,n.blendColor=this.blendColor.getHex(),n.blendAlpha=this.blendAlpha,n.depthFunc=this.depthFunc,n.depthTest=this.depthTest,n.depthWrite=this.depthWrite,n.colorWrite=this.colorWrite,n.clipIntersection=this.clipIntersection,n.clipShadows=this.clipShadows,n.stencilWriteMask=this.stencilWriteMask,n.stencilFunc=this.stencilFunc,n.stencilRef=this.stencilRef,n.stencilFuncMask=this.stencilFuncMask,n.stencilFail=this.stencilFail,n.stencilZFail=this.stencilZFail,n.stencilZPass=this.stencilZPass,n.stencilWrite=this.stencilWrite,n.polygonOffset=this.polygonOffset,n.polygonOffsetFactor=this.polygonOffsetFactor,n.polygonOffsetUnits=this.polygonOffsetUnits,n.dithering=this.dithering,n.alphaTest=this.alphaTest,n.alphaHash=this.alphaHash,n.alphaToCoverage=this.alphaToCoverage,n.premultipliedAlpha=this.premultipliedAlpha,n.forceSinglePass=this.forceSinglePass,n.allowOverride=this.allowOverride,n.visible=this.visible,n.toneMapped=this.toneMapped,n.name=this.name,this.color&&this.color.isColor&&(n.color=this.color.getHex()),this.roughness!==void 0&&(n.roughness=this.roughness),this.metalness!==void 0&&(n.metalness=this.metalness),this.sheen!==void 0&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(n.shininess=this.shininess),this.clearcoat!==void 0&&(n.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(t).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(t).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(t).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(n.sheenColorMap=this.sheenColorMap.toJSON(t).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(n.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(t).uuid),this.dispersion!==void 0&&(n.dispersion=this.dispersion),this.retroreflectivity!==void 0&&(n.retroreflectivity=this.retroreflectivity),this.iridescence!==void 0&&(n.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(n.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(t).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(t).uuid),this.anisotropy!==void 0&&(n.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(t).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(t).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(t).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(t).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(t).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(t).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(t).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(t).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(t).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(t).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(t).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(t).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(t).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(t).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(t).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(t).uuid,this.combine!==void 0&&(n.combine=this.combine)),this.envMapRotation!==void 0&&(n.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(n.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(n.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(t).uuid),this.transmission!==void 0&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(t).uuid),this.thickness!==void 0&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(t).uuid),this.attenuationDistance!==void 0&&(n.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(n.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(n.size=this.size),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),Array.isArray(this.clippingPlanes)&&this.clippingPlanes.length>0&&(n.clippingPlanes=this.clippingPlanes.map(r=>r.toJSON())),this.rotation!==void 0&&(n.rotation=this.rotation),this.depthPacking!==void 0&&(n.depthPacking=this.depthPacking),this.linewidth!==void 0&&(n.linewidth=this.linewidth),this.linecap!==void 0&&(n.linecap=this.linecap),this.linejoin!==void 0&&(n.linejoin=this.linejoin),this.dashSize!==void 0&&(n.dashSize=this.dashSize),this.gapSize!==void 0&&(n.gapSize=this.gapSize),this.scale!==void 0&&(n.scale=this.scale),this.wireframe!==void 0&&(n.wireframe=this.wireframe),this.wireframeLinewidth!==void 0&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!==void 0&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!==void 0&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading!==void 0&&(n.flatShading=this.flatShading),this.fog!==void 0&&(n.fog=this.fog),Object.keys(this.userData).length>0&&(n.userData=this.userData);function s(r){let o=[];for(let a in r){let l=r[a];delete l.metadata,o.push(l)}return o}if(e){let r=s(t.textures),o=s(t.images);r.length>0&&(n.textures=r),o.length>0&&(n.images=o)}return n}fromJSON(t,e){if(t.uuid!==void 0&&(this.uuid=t.uuid),t.name!==void 0&&(this.name=t.name),t.color!==void 0&&this.color!==void 0&&this.color.setHex(t.color),t.roughness!==void 0&&(this.roughness=t.roughness),t.metalness!==void 0&&(this.metalness=t.metalness),t.sheen!==void 0&&(this.sheen=t.sheen),t.sheenColor!==void 0&&(this.sheenColor=new Ft().setHex(t.sheenColor)),t.sheenRoughness!==void 0&&(this.sheenRoughness=t.sheenRoughness),t.emissive!==void 0&&this.emissive!==void 0&&this.emissive.setHex(t.emissive),t.specular!==void 0&&this.specular!==void 0&&this.specular.setHex(t.specular),t.specularIntensity!==void 0&&(this.specularIntensity=t.specularIntensity),t.specularColor!==void 0&&this.specularColor!==void 0&&this.specularColor.setHex(t.specularColor),t.shininess!==void 0&&(this.shininess=t.shininess),t.clearcoat!==void 0&&(this.clearcoat=t.clearcoat),t.clearcoatRoughness!==void 0&&(this.clearcoatRoughness=t.clearcoatRoughness),t.dispersion!==void 0&&(this.dispersion=t.dispersion),t.retroreflectivity!==void 0&&(this.retroreflectivity=t.retroreflectivity),t.iridescence!==void 0&&(this.iridescence=t.iridescence),t.iridescenceIOR!==void 0&&(this.iridescenceIOR=t.iridescenceIOR),t.iridescenceThicknessRange!==void 0&&(this.iridescenceThicknessRange=t.iridescenceThicknessRange),t.transmission!==void 0&&(this.transmission=t.transmission),t.thickness!==void 0&&(this.thickness=t.thickness),t.attenuationDistance!==void 0&&(this.attenuationDistance=t.attenuationDistance),t.attenuationColor!==void 0&&this.attenuationColor!==void 0&&this.attenuationColor.setHex(t.attenuationColor),t.anisotropy!==void 0&&(this.anisotropy=t.anisotropy),t.anisotropyRotation!==void 0&&(this.anisotropyRotation=t.anisotropyRotation),t.fog!==void 0&&(this.fog=t.fog),t.flatShading!==void 0&&(this.flatShading=t.flatShading),t.blending!==void 0&&(this.blending=t.blending),t.combine!==void 0&&(this.combine=t.combine),t.side!==void 0&&(this.side=t.side),t.shadowSide!==void 0&&(this.shadowSide=t.shadowSide),t.opacity!==void 0&&(this.opacity=t.opacity),t.transparent!==void 0&&(this.transparent=t.transparent),t.alphaTest!==void 0&&(this.alphaTest=t.alphaTest),t.alphaHash!==void 0&&(this.alphaHash=t.alphaHash),t.depthFunc!==void 0&&(this.depthFunc=t.depthFunc),t.depthTest!==void 0&&(this.depthTest=t.depthTest),t.depthWrite!==void 0&&(this.depthWrite=t.depthWrite),t.colorWrite!==void 0&&(this.colorWrite=t.colorWrite),t.clippingPlanes!==void 0&&(this.clippingPlanes=t.clippingPlanes.map(n=>new ge().fromJSON(n))),t.clipIntersection!==void 0&&(this.clipIntersection=t.clipIntersection),t.clipShadows!==void 0&&(this.clipShadows=t.clipShadows),t.depthPacking!==void 0&&(this.depthPacking=t.depthPacking),t.blendSrc!==void 0&&(this.blendSrc=t.blendSrc),t.blendDst!==void 0&&(this.blendDst=t.blendDst),t.blendEquation!==void 0&&(this.blendEquation=t.blendEquation),t.blendSrcAlpha!==void 0&&(this.blendSrcAlpha=t.blendSrcAlpha),t.blendDstAlpha!==void 0&&(this.blendDstAlpha=t.blendDstAlpha),t.blendEquationAlpha!==void 0&&(this.blendEquationAlpha=t.blendEquationAlpha),t.blendColor!==void 0&&this.blendColor!==void 0&&this.blendColor.setHex(t.blendColor),t.blendAlpha!==void 0&&(this.blendAlpha=t.blendAlpha),t.stencilWriteMask!==void 0&&(this.stencilWriteMask=t.stencilWriteMask),t.stencilFunc!==void 0&&(this.stencilFunc=t.stencilFunc),t.stencilRef!==void 0&&(this.stencilRef=t.stencilRef),t.stencilFuncMask!==void 0&&(this.stencilFuncMask=t.stencilFuncMask),t.stencilFail!==void 0&&(this.stencilFail=t.stencilFail),t.stencilZFail!==void 0&&(this.stencilZFail=t.stencilZFail),t.stencilZPass!==void 0&&(this.stencilZPass=t.stencilZPass),t.stencilWrite!==void 0&&(this.stencilWrite=t.stencilWrite),t.wireframe!==void 0&&(this.wireframe=t.wireframe),t.wireframeLinewidth!==void 0&&(this.wireframeLinewidth=t.wireframeLinewidth),t.wireframeLinecap!==void 0&&(this.wireframeLinecap=t.wireframeLinecap),t.wireframeLinejoin!==void 0&&(this.wireframeLinejoin=t.wireframeLinejoin),t.rotation!==void 0&&(this.rotation=t.rotation),t.linewidth!==void 0&&(this.linewidth=t.linewidth),t.linecap!==void 0&&(this.linecap=t.linecap),t.linejoin!==void 0&&(this.linejoin=t.linejoin),t.dashSize!==void 0&&(this.dashSize=t.dashSize),t.gapSize!==void 0&&(this.gapSize=t.gapSize),t.scale!==void 0&&(this.scale=t.scale),t.polygonOffset!==void 0&&(this.polygonOffset=t.polygonOffset),t.polygonOffsetFactor!==void 0&&(this.polygonOffsetFactor=t.polygonOffsetFactor),t.polygonOffsetUnits!==void 0&&(this.polygonOffsetUnits=t.polygonOffsetUnits),t.dithering!==void 0&&(this.dithering=t.dithering),t.alphaToCoverage!==void 0&&(this.alphaToCoverage=t.alphaToCoverage),t.premultipliedAlpha!==void 0&&(this.premultipliedAlpha=t.premultipliedAlpha),t.forceSinglePass!==void 0&&(this.forceSinglePass=t.forceSinglePass),t.allowOverride!==void 0&&(this.allowOverride=t.allowOverride),t.visible!==void 0&&(this.visible=t.visible),t.toneMapped!==void 0&&(this.toneMapped=t.toneMapped),t.userData!==void 0&&(this.userData=t.userData),t.vertexColors!==void 0&&(typeof t.vertexColors=="number"?this.vertexColors=t.vertexColors>0:this.vertexColors=t.vertexColors),t.size!==void 0&&(this.size=t.size),t.sizeAttenuation!==void 0&&(this.sizeAttenuation=t.sizeAttenuation),t.map!==void 0&&(this.map=e[t.map]||null),t.matcap!==void 0&&(this.matcap=e[t.matcap]||null),t.alphaMap!==void 0&&(this.alphaMap=e[t.alphaMap]||null),t.bumpMap!==void 0&&(this.bumpMap=e[t.bumpMap]||null),t.bumpScale!==void 0&&(this.bumpScale=t.bumpScale),t.normalMap!==void 0&&(this.normalMap=e[t.normalMap]||null),t.normalMapType!==void 0&&(this.normalMapType=t.normalMapType),t.normalScale!==void 0){let n=t.normalScale;Array.isArray(n)===!1&&(n=[n,n]),this.normalScale=new Ht().fromArray(n)}return t.displacementMap!==void 0&&(this.displacementMap=e[t.displacementMap]||null),t.displacementScale!==void 0&&(this.displacementScale=t.displacementScale),t.displacementBias!==void 0&&(this.displacementBias=t.displacementBias),t.roughnessMap!==void 0&&(this.roughnessMap=e[t.roughnessMap]||null),t.metalnessMap!==void 0&&(this.metalnessMap=e[t.metalnessMap]||null),t.emissiveMap!==void 0&&(this.emissiveMap=e[t.emissiveMap]||null),t.emissiveIntensity!==void 0&&(this.emissiveIntensity=t.emissiveIntensity),t.specularMap!==void 0&&(this.specularMap=e[t.specularMap]||null),t.specularIntensityMap!==void 0&&(this.specularIntensityMap=e[t.specularIntensityMap]||null),t.specularColorMap!==void 0&&(this.specularColorMap=e[t.specularColorMap]||null),t.envMap!==void 0&&(this.envMap=e[t.envMap]||null),t.envMapRotation!==void 0&&this.envMapRotation.fromArray(t.envMapRotation),t.envMapIntensity!==void 0&&(this.envMapIntensity=t.envMapIntensity),t.reflectivity!==void 0&&(this.reflectivity=t.reflectivity),t.refractionRatio!==void 0&&(this.refractionRatio=t.refractionRatio),t.lightMap!==void 0&&(this.lightMap=e[t.lightMap]||null),t.lightMapIntensity!==void 0&&(this.lightMapIntensity=t.lightMapIntensity),t.aoMap!==void 0&&(this.aoMap=e[t.aoMap]||null),t.aoMapIntensity!==void 0&&(this.aoMapIntensity=t.aoMapIntensity),t.gradientMap!==void 0&&(this.gradientMap=e[t.gradientMap]||null),t.clearcoatMap!==void 0&&(this.clearcoatMap=e[t.clearcoatMap]||null),t.clearcoatRoughnessMap!==void 0&&(this.clearcoatRoughnessMap=e[t.clearcoatRoughnessMap]||null),t.clearcoatNormalMap!==void 0&&(this.clearcoatNormalMap=e[t.clearcoatNormalMap]||null),t.clearcoatNormalScale!==void 0&&(this.clearcoatNormalScale=new Ht().fromArray(t.clearcoatNormalScale)),t.iridescenceMap!==void 0&&(this.iridescenceMap=e[t.iridescenceMap]||null),t.iridescenceThicknessMap!==void 0&&(this.iridescenceThicknessMap=e[t.iridescenceThicknessMap]||null),t.transmissionMap!==void 0&&(this.transmissionMap=e[t.transmissionMap]||null),t.thicknessMap!==void 0&&(this.thicknessMap=e[t.thicknessMap]||null),t.anisotropyMap!==void 0&&(this.anisotropyMap=e[t.anisotropyMap]||null),t.sheenColorMap!==void 0&&(this.sheenColorMap=e[t.sheenColorMap]||null),t.sheenRoughnessMap!==void 0&&(this.sheenRoughnessMap=e[t.sheenRoughnessMap]||null),this}clone(){return new this.constructor().copy(this)}copy(t){this.name=t.name,this.blending=t.blending,this.side=t.side,this.vertexColors=t.vertexColors,this.opacity=t.opacity,this.transparent=t.transparent,this.blendSrc=t.blendSrc,this.blendDst=t.blendDst,this.blendEquation=t.blendEquation,this.blendSrcAlpha=t.blendSrcAlpha,this.blendDstAlpha=t.blendDstAlpha,this.blendEquationAlpha=t.blendEquationAlpha,this.blendColor.copy(t.blendColor),this.blendAlpha=t.blendAlpha,this.depthFunc=t.depthFunc,this.depthTest=t.depthTest,this.depthWrite=t.depthWrite,this.stencilWriteMask=t.stencilWriteMask,this.stencilFunc=t.stencilFunc,this.stencilRef=t.stencilRef,this.stencilFuncMask=t.stencilFuncMask,this.stencilFail=t.stencilFail,this.stencilZFail=t.stencilZFail,this.stencilZPass=t.stencilZPass,this.stencilWrite=t.stencilWrite;let e=t.clippingPlanes,n=null;if(e!==null){let s=e.length;n=new Array(s);for(let r=0;r!==s;++r)n[r]=e[r].clone()}return this.clippingPlanes=n,this.clipIntersection=t.clipIntersection,this.clipShadows=t.clipShadows,this.shadowSide=t.shadowSide,this.colorWrite=t.colorWrite,this.precision=t.precision,this.polygonOffset=t.polygonOffset,this.polygonOffsetFactor=t.polygonOffsetFactor,this.polygonOffsetUnits=t.polygonOffsetUnits,this.dithering=t.dithering,this.alphaTest=t.alphaTest,this.alphaHash=t.alphaHash,this.alphaToCoverage=t.alphaToCoverage,this.premultipliedAlpha=t.premultipliedAlpha,this.forceSinglePass=t.forceSinglePass,this.allowOverride=t.allowOverride,this.visible=t.visible,this.toneMapped=t.toneMapped,this.userData=JSON.parse(JSON.stringify(t.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(t){t===!0&&this.version++}};var qn=new I,Ol=new I,Yr=new I,$r=new I,Ri=class{constructor(t=new I,e=new I(0,0,-1)){this.origin=t,this.direction=e}set(t,e){return this.origin.copy(t),this.direction.copy(e),this}copy(t){return this.origin.copy(t.origin),this.direction.copy(t.direction),this}at(t,e){return e.copy(this.origin).addScaledVector(this.direction,t)}lookAt(t){return this.direction.copy(t).sub(this.origin).normalize(),this}recast(t){return this.origin.copy(this.at(t,qn)),this}closestPointToPoint(t,e){e.subVectors(t,this.origin);let n=e.dot(this.direction);return n<0?e.copy(this.origin):e.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(t){return Math.sqrt(this.distanceSqToPoint(t))}distanceSqToPoint(t){let e=qn.subVectors(t,this.origin).dot(this.direction);return e<0?this.origin.distanceToSquared(t):(qn.copy(this.origin).addScaledVector(this.direction,e),qn.distanceToSquared(t))}distanceSqToSegment(t,e,n,s){Ol.copy(t).add(e).multiplyScalar(.5),Yr.copy(e).sub(t).normalize(),$r.copy(this.origin).sub(Ol);let r=t.distanceTo(e)*.5,o=-this.direction.dot(Yr),a=$r.dot(this.direction),l=-$r.dot(Yr),c=$r.lengthSq(),h=Math.abs(1-o*o),d,u,p,g;if(h>0)if(d=o*l-a,u=o*a-l,g=r*h,d>=0)if(u>=-g)if(u<=g){let _=1/h;d*=_,u*=_,p=d*(d+o*u+2*a)+u*(o*d+u+2*l)+c}else u=r,d=Math.max(0,-(o*u+a)),p=-d*d+u*(u+2*l)+c;else u=-r,d=Math.max(0,-(o*u+a)),p=-d*d+u*(u+2*l)+c;else u<=-g?(d=Math.max(0,-(-o*r+a)),u=d>0?-r:Math.min(Math.max(-r,-l),r),p=-d*d+u*(u+2*l)+c):u<=g?(d=0,u=Math.min(Math.max(-r,-l),r),p=u*(u+2*l)+c):(d=Math.max(0,-(o*r+a)),u=d>0?r:Math.min(Math.max(-r,-l),r),p=-d*d+u*(u+2*l)+c);else u=o>0?-r:r,d=Math.max(0,-(o*u+a)),p=-d*d+u*(u+2*l)+c;return n&&n.copy(this.origin).addScaledVector(this.direction,d),s&&s.copy(Ol).addScaledVector(Yr,u),p}intersectSphere(t,e){if(t.radius<0)return null;qn.subVectors(t.center,this.origin);let n=qn.dot(this.direction),s=qn.dot(qn)-n*n,r=t.radius*t.radius;if(s>r)return null;let o=Math.sqrt(r-s),a=n-o,l=n+o;return l<0?null:a<0?this.at(l,e):this.at(a,e)}intersectsSphere(t){return t.radius<0?!1:this.distanceSqToPoint(t.center)<=t.radius*t.radius}distanceToPlane(t){let e=t.normal.dot(this.direction);if(e===0)return t.distanceToPoint(this.origin)===0?0:null;let n=-(this.origin.dot(t.normal)+t.constant)/e;return n>=0?n:null}intersectPlane(t,e){let n=this.distanceToPlane(t);return n===null?null:this.at(n,e)}intersectsPlane(t){let e=t.distanceToPoint(this.origin);return e===0||t.normal.dot(this.direction)*e<0}intersectBox(t,e){let n,s,r,o,a,l,c=1/this.direction.x,h=1/this.direction.y,d=1/this.direction.z,u=this.origin;return c>=0?(n=(t.min.x-u.x)*c,s=(t.max.x-u.x)*c):(n=(t.max.x-u.x)*c,s=(t.min.x-u.x)*c),h>=0?(r=(t.min.y-u.y)*h,o=(t.max.y-u.y)*h):(r=(t.max.y-u.y)*h,o=(t.min.y-u.y)*h),n>o||r>s||((r>n||isNaN(n))&&(n=r),(o=0?(a=(t.min.z-u.z)*d,l=(t.max.z-u.z)*d):(a=(t.max.z-u.z)*d,l=(t.min.z-u.z)*d),n>l||a>s)||((a>n||n!==n)&&(n=a),(l=0?n:s,e)}intersectsBox(t){return this.intersectBox(t,qn)!==null}intersectTriangle(t,e,n,s,r){let o=this.origin,a=this.direction,l=a.x,c=a.y,h=a.z,d=t.x-o.x,u=t.y-o.y,p=t.z-o.z,g=e.x-o.x,_=e.y-o.y,m=e.z-o.z,f=n.x-o.x,b=n.y-o.y,E=n.z-o.z,M=Math.abs(l),v=Math.abs(c),S=Math.abs(h),A,x,T,R,L,N,U,C,B,z,W,F;if(M>=v&&M>=S?(T=l,N=d,B=g,F=f,l>=0?(A=c,x=h,R=u,L=p,U=_,C=m,z=b,W=E):(A=h,x=c,R=p,L=u,U=m,C=_,z=E,W=b)):v>=S?(T=c,N=u,B=_,F=b,c>=0?(A=h,x=l,R=p,L=d,U=m,C=g,z=E,W=f):(A=l,x=h,R=d,L=p,U=g,C=m,z=f,W=E)):(T=h,N=p,B=m,F=E,h>=0?(A=l,x=c,R=d,L=u,U=g,C=_,z=f,W=b):(A=c,x=l,R=u,L=d,U=_,C=g,z=b,W=f)),T===0)return null;let D=A/T,X=x/T,Z=1/T,G=R-D*N,Q=L-X*N,lt=U-D*B,ct=C-X*B,tt=z-D*F,V=W-X*F,j=tt*ct-V*lt,ut=G*V-Q*tt,Lt=lt*Q-ct*G;if(s){if(j<0||ut<0||Lt<0)return null}else if((j<0||ut<0||Lt<0)&&(j>0||ut>0||Lt>0))return null;let Mt=j+ut+Lt;if(Mt===0)return null;let Bt=Z*(j*N+ut*B+Lt*F);return(Mt>0?Bt<0:Bt>0)?null:this.at(Bt/Mt,r)}applyMatrix4(t){return this.origin.applyMatrix4(t),this.direction.transformDirection(t),this}equals(t){return t.origin.equals(this.origin)&&t.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}},en=class extends Dn{constructor(t){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Ft(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Jn,this.combine=Zo,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapRotation.copy(t.envMapRotation),this.combine=t.combine,this.reflectivity=t.reflectivity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.fog=t.fog,this}},iu=new kt,wi=new Ri,Zr=new Oe,su=new I,Jr=new I,Kr=new I,jr=new I,zl=new I,Qr=new I,ru=new I,to=new I,_e=class extends Be{constructor(t=new ae,e=new en){super(),this.isMesh=!0,this.type="Mesh",this.geometry=t,this.material=e,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(t,e){return super.copy(t,e),t.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=t.morphTargetInfluences.slice()),t.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},t.morphTargetDictionary)),this.material=Array.isArray(t.material)?t.material.slice():t.material,this.geometry=t.geometry,this}updateMorphTargets(){let e=this.geometry.morphAttributes,n=Object.keys(e);if(n.length>0){let s=e[n[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,o=s.length;r(t.far-t.near)**2))&&(iu.copy(r).invert(),wi.copy(t.ray).applyMatrix4(iu),!(n.boundingBox!==null&&wi.intersectsBox(n.boundingBox)===!1)&&this._computeIntersections(t,e,wi)))}_computeIntersections(t,e,n){let s,r=this.geometry,o=this.material,a=r.index,l=r.attributes.position,c=r.attributes.uv,h=r.attributes.uv1,d=r.attributes.normal,u=r.groups,p=r.drawRange;if(a!==null)if(Array.isArray(o))for(let g=0,_=u.length;g<_;g++){let m=u[g],f=o[m.materialIndex],b=Math.max(m.start,p.start),E=Math.min(a.count,Math.min(m.start+m.count,p.start+p.count));for(let M=b,v=E;Me.far?null:{distance:c,point:to.clone(),object:i}}function eo(i,t,e,n,s,r,o,a,l,c){i.getVertexPosition(a,Jr),i.getVertexPosition(l,Kr),i.getVertexPosition(c,jr);let h=nm(i,t,e,n,Jr,Kr,jr,ru);if(h){let d=new I;Yn.getBarycoord(ru,Jr,Kr,jr,d),s&&(h.uv=Yn.getInterpolatedAttribute(s,a,l,c,d,new Ht)),r&&(h.uv1=Yn.getInterpolatedAttribute(r,a,l,c,d,new Ht)),o&&(h.normal=Yn.getInterpolatedAttribute(o,a,l,c,d,new I),h.normal.dot(n.direction)>0&&h.normal.multiplyScalar(-1));let u={a,b:l,c,normal:new I,materialIndex:0};Yn.getNormal(Jr,Kr,jr,u.normal),h.face=u,h.barycoord=d}return h}var Nn=class extends ke{constructor(t=null,e=1,n=1,s,r,o,a,l,c=Ue,h=Ue,d,u){super(null,o,a,l,c,h,s,r,d,u),this.isDataTexture=!0,this.image={data:t,width:e,height:n},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}};var Kn=class extends Se{constructor(t,e,n,s=1){super(t,e,n),this.isInstancedBufferAttribute=!0,this.meshPerAttribute=s}copy(t){return super.copy(t),this.meshPerAttribute=t.meshPerAttribute,this}toJSON(){let t=super.toJSON();return t.meshPerAttribute=this.meshPerAttribute,t.isInstancedBufferAttribute=!0,t}},Qi=new kt,ou=new kt,no=[],au=new ie,im=new kt,zs=new _e,ks=new Oe,ps=class extends _e{constructor(t,e,n){super(t,e),this.isInstancedMesh=!0,this.instanceMatrix=new Kn(new Float32Array(n*16),16),this.instanceColor=null,this.morphTexture=null,this.count=n,this.boundingBox=null,this.boundingSphere=null;for(let s=0;s0?t.max.x:t.min.x,io.y=s.normal.y>0?t.max.y:t.min.y,io.z=s.normal.z>0?t.max.z:t.min.z,s.distanceToPoint(io)<0)return!1}return!0}containsPoint(t){let e=this.planes;for(let n=0;n<6;n++)if(e[n].distanceToPoint(t)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}};var an=class extends Dn{constructor(t){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new Ft(16777215),this.map=null,this.linewidth=1,this.linecap="round",this.linejoin="round",this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.linewidth=t.linewidth,this.linecap=t.linecap,this.linejoin=t.linejoin,this.fog=t.fog,this}},Co=new I,Io=new I,lu=new kt,Hs=new Ri,so=new Oe,kl=new I,cu=new I,Ci=class extends Be{constructor(t=new ae,e=new an){super(),this.isLine=!0,this.type="Line",this.geometry=t,this.material=e,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(t,e){return super.copy(t,e),this.material=Array.isArray(t.material)?t.material.slice():t.material,this.geometry=t.geometry,this}computeLineDistances(){let t=this.geometry;if(t.index===null){let e=t.attributes.position,n=[0];for(let s=1,r=e.count;s0){let s=e[n[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,o=s.length;rn)return;kl.applyMatrix4(i.matrixWorld);let c=t.ray.origin.distanceTo(kl);if(!(ct.far))return{distance:c,point:cu.clone().applyMatrix4(i.matrixWorld),index:o,face:null,faceIndex:null,barycoord:null,object:i}}var hu=new I,uu=new I,vn=class extends Ci{constructor(t,e){super(t,e),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){let t=this.geometry;if(t.index===null){let e=t.attributes.position,n=[];for(let s=0,r=e.count;s0){let s=e[n[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,o=s.length;rs.far)return;r.push({distance:c,distanceToRay:Math.sqrt(a),point:l,index:t,face:null,faceIndex:null,barycoord:null,object:o})}}var js=class extends ke{constructor(t=[],e=pi,n,s,r,o,a,l,c,h){super(t,e,n,s,r,o,a,l,c,h),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(t){this.image=t}},Qs=class extends ke{constructor(t,e,n,s,r,o,a,l,c){super(t,e,n,s,r,o,a,l,c),this.isCanvasTexture=!0,this.needsUpdate=!0}};var hi=class extends ke{constructor(t,e,n=bn,s,r,o,a=Ue,l=Ue,c,h=Pn,d=1){if(h!==Pn&&h!==gi)throw new Error("THREE.DepthTexture: format must be either THREE.DepthFormat or THREE.DepthStencilFormat");let u={width:t,height:e,depth:d};super(u,s,r,o,a,l,h,n,c),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(t){return super.copy(t),this.source=new hs(Object.assign({},t.image)),this.compareFunction=t.compareFunction,this}toJSON(t){let e=super.toJSON(t);return e.compareFunction=this.compareFunction,e}},Po=class extends hi{constructor(t,e=bn,n=pi,s,r,o=Ue,a=Ue,l,c=Pn){let h={width:t,height:t,depth:1},d=[h,h,h,h,h,h];super(t,t,e,n,s,r,o,a,l,c),this.image=d,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(t){this.image=t}},tr=class extends ke{constructor(t=null){super(),this.sourceTexture=t,this.isExternalTexture=!0}copy(t){return super.copy(t),this.sourceTexture=t.sourceTexture,this}},dn=class i extends ae{constructor(t=1,e=1,n=1,s=1,r=1,o=1){super(),this.type="BoxGeometry",this.parameters={width:t,height:e,depth:n,widthSegments:s,heightSegments:r,depthSegments:o};let a=this;s=Math.floor(s),r=Math.floor(r),o=Math.floor(o);let l=[],c=[],h=[],d=[],u=0,p=0;g("z","y","x",-1,-1,n,e,t,o,r,0),g("z","y","x",1,-1,n,e,-t,o,r,1),g("x","z","y",1,1,t,n,e,s,o,2),g("x","z","y",1,-1,t,n,-e,s,o,3),g("x","y","z",1,-1,t,e,n,s,r,4),g("x","y","z",-1,-1,t,e,-n,s,r,5),this.setIndex(l),this.setAttribute("position",new ue(c,3)),this.setAttribute("normal",new ue(h,3)),this.setAttribute("uv",new ue(d,2));function g(_,m,f,b,E,M,v,S,A,x,T){let R=M/A,L=v/x,N=M/2,U=v/2,C=S/2,B=A+1,z=x+1,W=0,F=0,D=new I;for(let X=0;X0?1:-1,h.push(D.x,D.y,D.z),d.push(G/A),d.push(1-X/x),W+=1}}for(let X=0;X0&&E(!0),e>0&&E(!1)),this.setIndex(h),this.setAttribute("position",new ue(d,3)),this.setAttribute("normal",new ue(u,3)),this.setAttribute("uv",new ue(p,2));function b(){let M=new I,v=new I,S=0,A=(e-t)/n;for(let x=0;x<=r;x++){let T=[],R=x/r,L=R*(e-t)+t;for(let N=0;N<=s;N++){let U=N/s,C=U*l+a,B=Math.sin(C),z=Math.cos(C);v.x=L*B,v.y=-R*n+m,v.z=L*z,d.push(v.x,v.y,v.z),M.set(B,A,z).normalize(),u.push(M.x,M.y,M.z),p.push(U,1-R),T.push(g++)}_.push(T)}for(let x=0;x0||T!==0)&&(h.push(R,L,U),S+=3),(e>0||T!==r-1)&&(h.push(L,N,U),S+=3)}c.addGroup(f,S,0),f+=S}function E(M){let v=g,S=new Ht,A=new I,x=0,T=M===!0?t:e,R=M===!0?1:-1;for(let N=1;N<=s;N++)d.push(0,m*R,0),u.push(0,R,0),p.push(.5,.5),g++;let L=g;for(let N=0;N<=s;N++){let C=N/s*l+a,B=Math.cos(C),z=Math.sin(C);A.x=T*z,A.y=m*R,A.z=T*B,d.push(A.x,A.y,A.z),u.push(0,R,0),S.x=B*.5+.5,S.y=z*.5*R+.5,p.push(S.x,S.y),g++}for(let N=0;N0)&&p.push(E,M,S),(f!==n-1||l{var Gh=i=>{throw TypeError(i)};var vl=(i,t,e)=>t.has(i)||Gh("Cannot "+e);var ii=(i,t,e)=>(vl(i,t,"read from private field"),e?e.call(i):t.get(i)),yl=(i,t,e)=>t.has(i)?Gh("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(i):t.set(i,e),Wh=(i,t,e,n)=>(vl(i,t,"write to private field"),n?n.call(i,e):t.set(i,e),e),zr=(i,t,e)=>(vl(i,t,"access private method"),e);var Su=0,Ql=1,wu=2;var cr=1,Eu=2,vs=3,Bn=0,Ve=1,Ie=2,On=0,ys=1,tc=2,ec=3,nc=4,Tu=5;var Ui=100,Au=101,Ru=102,Cu=103,Iu=104,Pu=200,Lu=201,Du=202,Nu=203,ic=204,sc=205,Uu=206,Fu=207,Bu=208,Ou=209,zu=210,ku=211,Hu=212,Vu=213,Gu=214,go=0,_o=1,xo=2,rs=3,vo=4,yo=5,Mo=6,bo=7,Zo=0,Wu=1,Xu=2,Mn=0,rc=1,oc=2,ac=3,lc=4,cc=5,hc=6,uc=7;var dc=300,pi=301,Fi=302,Jo=303,Ko=304,hr=306,os=1e3,In=1001,So=1002,Ue=1003,qu=1004;var ur=1005;var ze=1006,jo=1007;var mi=1008;var nn=1009,fc=1010,pc=1011,Ms=1012,Qo=1013,bn=1014,Ge=1015,Sn=1016,ta=1017,ea=1018,bs=1020,mc=35902,gc=35899,_c=1021,xc=1022,sn=1023,Pn=1026,gi=1027,Ss=1028,na=1029,_i=1030,ia=1031;var sa=1033,dr=33776,fr=33777,pr=33778,mr=33779,ra=35840,oa=35841,aa=35842,la=35843,ca=36196,ha=37492,ua=37496,da=37488,fa=37489,gr=37490,pa=37491,ma=37808,ga=37809,_a=37810,xa=37811,va=37812,ya=37813,Ma=37814,ba=37815,Sa=37816,wa=37817,Ea=37818,Ta=37819,Aa=37820,Ra=37821,Ca=36492,Ia=36494,Pa=36495,La=36283,Da=36284,_r=36285,Na=36286;var Ws=2300,wo=2301,po=2302,Wl=2303,Xl=2400,ql=2401,Yl=2402;var Yu=3200;var Ua=0,$u=1,jn="",Ae="srgb",Xs="srgb-linear",qs="linear",te="srgb";var mo=7680;var vc=34055,yc=34056;var Mc=517;var Zu=519,Ju=512,Ku=513,ju=514,Fa=515,Qu=516,td=517,Ba=518,ed=519,bc=35044,Sc=35048;var wc="300 es",xn=2e3,as=2001;function wp(i){for(let t=i.length-1;t>=0;--t)if(i[t]>=65535)return!0;return!1}function Ep(i){return ArrayBuffer.isView(i)&&!(i instanceof DataView)}function Ys(i){return document.createElementNS("http://www.w3.org/1999/xhtml",i)}function nd(){let i=Ys("canvas");return i.style.display="block",i}var Xh={},ls=null;function $s(...i){let t="THREE."+i.shift();ls?ls("log",t,...i):console.log(t,...i)}function id(i){let t=i[0];if(typeof t=="string"&&t.startsWith("TSL:")){let e=i[1];e&&e.isStackTrace?i[0]+=" "+e.getLocation():i[1]='Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.'}return i}function Dt(...i){i=id(i);let t="THREE."+i.shift();if(ls)ls("warn",t,...i);else{let e=i[0];e&&e.isStackTrace?console.warn(e.getError(t)):console.warn(t,...i)}}function Ut(...i){i=id(i);let t="THREE."+i.shift();if(ls)ls("error",t,...i);else{let e=i[0];e&&e.isStackTrace?console.error(e.getError(t)):console.error(t,...i)}}function Ai(...i){let t=i.join(" ");t in Xh||(Xh[t]=!0,Dt(...i))}function sd(i,t,e){return new Promise(function(n,s){function r(){switch(i.clientWaitSync(t,i.SYNC_FLUSH_COMMANDS_BIT,0)){case i.WAIT_FAILED:s();break;case i.TIMEOUT_EXPIRED:setTimeout(r,e);break;default:n()}}setTimeout(r,e)})}var rd={[go]:_o,[xo]:Mo,[vo]:bo,[rs]:yo,[_o]:go,[Mo]:xo,[bo]:vo,[yo]:rs},Ln=class{addEventListener(t,e){this._listeners===void 0&&(this._listeners={});let n=this._listeners;n[t]===void 0&&(n[t]=[]),n[t].indexOf(e)===-1&&n[t].push(e)}hasEventListener(t,e){let n=this._listeners;return n===void 0?!1:n[t]!==void 0&&n[t].indexOf(e)!==-1}removeEventListener(t,e){let n=this._listeners;if(n===void 0)return;let s=n[t];if(s!==void 0){let r=s.indexOf(e);r!==-1&&s.splice(r,1)}}dispatchEvent(t){let e=this._listeners;if(e===void 0)return;let n=e[t.type];if(n!==void 0){t.target=this;let s=n.slice(0);for(let r=0,o=s.length;r>8&255]+qe[i>>16&255]+qe[i>>24&255]+"-"+qe[t&255]+qe[t>>8&255]+"-"+qe[t>>16&15|64]+qe[t>>24&255]+"-"+qe[e&63|128]+qe[e>>8&255]+"-"+qe[e>>16&255]+qe[e>>24&255]+qe[n&255]+qe[n>>8&255]+qe[n>>16&255]+qe[n>>24&255]).toLowerCase()}function $t(i,t,e){return Math.max(t,Math.min(e,i))}function Ec(i,t){return(i%t+t)%t}function Tp(i,t,e,n,s){return n+(i-t)*(s-n)/(e-t)}function Ap(i,t,e){return i!==t?(e-i)/(t-i):0}function Gs(i,t,e){return(1-e)*i+e*t}function Rp(i,t,e,n){return Gs(i,t,1-Math.exp(-e*n))}function Cp(i,t=1){return t-Math.abs(Ec(i,t*2)-t)}function Ip(i,t,e){return i<=t?0:i>=e?1:(i=(i-t)/(e-t),i*i*(3-2*i))}function Pp(i,t,e){return i<=t?0:i>=e?1:(i=(i-t)/(e-t),i*i*i*(i*(i*6-15)+10))}function Lp(i,t){return i+Math.floor(Math.random()*(t-i+1))}function Dp(i,t){return i+Math.random()*(t-i)}function Np(i){return i*(.5-Math.random())}function Up(i){i!==void 0&&(qh=i);let t=qh+=1831565813;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}function Fp(i){return i*is}function Bp(i){return i*cs}function Op(i){return i>0&&Number.isInteger(i)&&2**Math.round(Math.log2(i))===i}function zp(i){return Math.pow(2,Math.ceil(Math.log(i)/Math.LN2))}function kp(i){return Math.pow(2,Math.floor(Math.log(i)/Math.LN2))}function Hp(i,t,e,n,s){let r=Math.cos,o=Math.sin,a=r(e/2),l=o(e/2),c=r((t+n)/2),h=o((t+n)/2),d=r((t-n)/2),u=o((t-n)/2),p=r((n-t)/2),g=o((n-t)/2);switch(s){case"XYX":i.set(a*h,l*d,l*u,a*c);break;case"YZY":i.set(l*u,a*h,l*d,a*c);break;case"ZXZ":i.set(l*d,l*u,a*h,a*c);break;case"XZX":i.set(a*h,l*g,l*p,a*c);break;case"YXY":i.set(l*p,a*h,l*g,a*c);break;case"ZYZ":i.set(l*g,l*p,a*h,a*c);break;default:Dt("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+s)}}function _n(i,t){switch(t.constructor){case Float32Array:return i;case Uint32Array:return i/4294967295;case Uint16Array:return i/65535;case Uint8Array:case Uint8ClampedArray:return i/255;case Int32Array:return Math.max(i/2147483647,-1);case Int16Array:return Math.max(i/32767,-1);case Int8Array:return Math.max(i/127,-1);default:throw new Error("THREE.MathUtils: Invalid component type.")}}function ne(i,t){switch(t.constructor){case Float32Array:return i;case Uint32Array:return Math.round(i*4294967295);case Uint16Array:return Math.round(i*65535);case Uint8Array:case Uint8ClampedArray:return Math.round(i*255);case Int32Array:return Math.round(i*2147483647);case Int16Array:return Math.round(i*32767);case Int8Array:return Math.round(i*127);default:throw new Error("THREE.MathUtils: Invalid component type.")}}var ce={DEG2RAD:is,RAD2DEG:cs,generateUUID:$n,clamp:$t,euclideanModulo:Ec,mapLinear:Tp,inverseLerp:Ap,lerp:Gs,damp:Rp,pingpong:Cp,smoothstep:Ip,smootherstep:Pp,randInt:Lp,randFloat:Dp,randFloatSpread:Np,seededRandom:Up,degToRad:Fp,radToDeg:Bp,isPowerOfTwo:Op,ceilPowerOfTwo:zp,floorPowerOfTwo:kp,setQuaternionFromProperEuler:Hp,normalize:ne,denormalize:_n},Ic=class Ic{constructor(t=0,e=0){this.x=t,this.y=e}get width(){return this.x}set width(t){this.x=t}get height(){return this.y}set height(t){this.y=t}set(t,e){return this.x=t,this.y=e,this}setScalar(t){return this.x=t,this.y=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;default:throw new Error("THREE.Vector2: index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;default:throw new Error("THREE.Vector2: index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y)}copy(t){return this.x=t.x,this.y=t.y,this}add(t){return this.x+=t.x,this.y+=t.y,this}addScalar(t){return this.x+=t,this.y+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this}subScalar(t){return this.x-=t,this.y-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this}multiply(t){return this.x*=t.x,this.y*=t.y,this}multiplyScalar(t){return this.x*=t,this.y*=t,this}divide(t){return this.x/=t.x,this.y/=t.y,this}divideScalar(t){return this.multiplyScalar(1/t)}applyMatrix3(t){let e=this.x,n=this.y,s=t.elements;return this.x=s[0]*e+s[3]*n+s[6],this.y=s[1]*e+s[4]*n+s[7],this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this}clamp(t,e){return this.x=$t(this.x,t.x,e.x),this.y=$t(this.y,t.y,e.y),this}clampScalar(t,e){return this.x=$t(this.x,t,e),this.y=$t(this.y,t,e),this}clampLength(t,e){let n=this.length();return this.divideScalar(n||1).multiplyScalar($t(n,t,e))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(t){return this.x*t.x+this.y*t.y}cross(t){return this.x*t.y-this.y*t.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(t){let e=Math.sqrt(this.lengthSq()*t.lengthSq());if(e===0)return Math.PI/2;let n=this.dot(t)/e;return Math.acos($t(n,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){let e=this.x-t.x,n=this.y-t.y;return e*e+n*n}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this}lerpVectors(t,e,n){return this.x=t.x+(e.x-t.x)*n,this.y=t.y+(e.y-t.y)*n,this}equals(t){return t.x===this.x&&t.y===this.y}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this}rotateAround(t,e){let n=Math.cos(e),s=Math.sin(e),r=this.x-t.x,o=this.y-t.y;return this.x=r*n-o*s+t.x,this.y=r*s+o*n+t.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}};Ic.prototype.isVector2=!0;var Ht=Ic,Ce=class{constructor(t=0,e=0,n=0,s=1){this.isQuaternion=!0,this._x=t,this._y=e,this._z=n,this._w=s}static slerpFlat(t,e,n,s,r,o,a){let l=n[s+0],c=n[s+1],h=n[s+2],d=n[s+3],u=r[o+0],p=r[o+1],g=r[o+2],_=r[o+3];if(d!==_||l!==u||c!==p||h!==g){let m=l*u+c*p+h*g+d*_;m<0&&(u=-u,p=-p,g=-g,_=-_,m=-m);let f=1-a;if(m<.9995){let b=Math.acos(m),E=Math.sin(b);f=Math.sin(f*b)/E,a=Math.sin(a*b)/E,l=l*f+u*a,c=c*f+p*a,h=h*f+g*a,d=d*f+_*a}else{l=l*f+u*a,c=c*f+p*a,h=h*f+g*a,d=d*f+_*a;let b=1/Math.sqrt(l*l+c*c+h*h+d*d);l*=b,c*=b,h*=b,d*=b}}t[e]=l,t[e+1]=c,t[e+2]=h,t[e+3]=d}static multiplyQuaternionsFlat(t,e,n,s,r,o){let a=n[s],l=n[s+1],c=n[s+2],h=n[s+3],d=r[o],u=r[o+1],p=r[o+2],g=r[o+3];return t[e]=a*g+h*d+l*p-c*u,t[e+1]=l*g+h*u+c*d-a*p,t[e+2]=c*g+h*p+a*u-l*d,t[e+3]=h*g-a*d-l*u-c*p,t}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get w(){return this._w}set w(t){this._w=t,this._onChangeCallback()}set(t,e,n,s){return this._x=t,this._y=e,this._z=n,this._w=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(t){return this._x=t.x,this._y=t.y,this._z=t.z,this._w=t.w,this._onChangeCallback(),this}setFromEuler(t,e=!0){let n=t._x,s=t._y,r=t._z,o=t._order,a=Math.cos,l=Math.sin,c=a(n/2),h=a(s/2),d=a(r/2),u=l(n/2),p=l(s/2),g=l(r/2);switch(o){case"XYZ":this._x=u*h*d+c*p*g,this._y=c*p*d-u*h*g,this._z=c*h*g+u*p*d,this._w=c*h*d-u*p*g;break;case"YXZ":this._x=u*h*d+c*p*g,this._y=c*p*d-u*h*g,this._z=c*h*g-u*p*d,this._w=c*h*d+u*p*g;break;case"ZXY":this._x=u*h*d-c*p*g,this._y=c*p*d+u*h*g,this._z=c*h*g+u*p*d,this._w=c*h*d-u*p*g;break;case"ZYX":this._x=u*h*d-c*p*g,this._y=c*p*d+u*h*g,this._z=c*h*g-u*p*d,this._w=c*h*d+u*p*g;break;case"YZX":this._x=u*h*d+c*p*g,this._y=c*p*d+u*h*g,this._z=c*h*g-u*p*d,this._w=c*h*d-u*p*g;break;case"XZY":this._x=u*h*d-c*p*g,this._y=c*p*d-u*h*g,this._z=c*h*g+u*p*d,this._w=c*h*d+u*p*g;break;default:Dt("Quaternion: .setFromEuler() encountered an unknown order: "+o)}return e===!0&&this._onChangeCallback(),this}setFromAxisAngle(t,e){let n=e/2,s=Math.sin(n);return this._x=t.x*s,this._y=t.y*s,this._z=t.z*s,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(t){let e=t.elements,n=e[0],s=e[4],r=e[8],o=e[1],a=e[5],l=e[9],c=e[2],h=e[6],d=e[10],u=n+a+d;if(u>0){let p=.5/Math.sqrt(u+1);this._w=.25/p,this._x=(h-l)*p,this._y=(r-c)*p,this._z=(o-s)*p}else if(n>a&&n>d){let p=2*Math.sqrt(1+n-a-d);this._w=(h-l)/p,this._x=.25*p,this._y=(s+o)/p,this._z=(r+c)/p}else if(a>d){let p=2*Math.sqrt(1+a-n-d);this._w=(r-c)/p,this._x=(s+o)/p,this._y=.25*p,this._z=(l+h)/p}else{let p=2*Math.sqrt(1+d-n-a);this._w=(o-s)/p,this._x=(r+c)/p,this._y=(l+h)/p,this._z=.25*p}return this._onChangeCallback(),this}setFromUnitVectors(t,e){let n=t.dot(e)+1;return n<1e-8?(n=0,Math.abs(t.x)>Math.abs(t.z)?(this._x=-t.y,this._y=t.x,this._z=0,this._w=n):(this._x=0,this._y=-t.z,this._z=t.y,this._w=n)):(this._x=t.y*e.z-t.z*e.y,this._y=t.z*e.x-t.x*e.z,this._z=t.x*e.y-t.y*e.x,this._w=n),this.normalize()}angleTo(t){return 2*Math.acos(Math.abs($t(this.dot(t),-1,1)))}rotateTowards(t,e){let n=this.angleTo(t);if(n===0)return this;let s=Math.min(1,e/n);return this.slerp(t,s),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(t){return this._x*t._x+this._y*t._y+this._z*t._z+this._w*t._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let t=this.length();return t===0?(this._x=0,this._y=0,this._z=0,this._w=1):(t=1/t,this._x=this._x*t,this._y=this._y*t,this._z=this._z*t,this._w=this._w*t),this._onChangeCallback(),this}multiply(t){return this.multiplyQuaternions(this,t)}premultiply(t){return this.multiplyQuaternions(t,this)}multiplyQuaternions(t,e){let n=t._x,s=t._y,r=t._z,o=t._w,a=e._x,l=e._y,c=e._z,h=e._w;return this._x=n*h+o*a+s*c-r*l,this._y=s*h+o*l+r*a-n*c,this._z=r*h+o*c+n*l-s*a,this._w=o*h-n*a-s*l-r*c,this._onChangeCallback(),this}slerp(t,e){let n=t._x,s=t._y,r=t._z,o=t._w,a=this.dot(t);a<0&&(n=-n,s=-s,r=-r,o=-o,a=-a);let l=1-e;if(a<.9995){let c=Math.acos(a),h=Math.sin(c);l=Math.sin(l*c)/h,e=Math.sin(e*c)/h,this._x=this._x*l+n*e,this._y=this._y*l+s*e,this._z=this._z*l+r*e,this._w=this._w*l+o*e,this._onChangeCallback()}else this._x=this._x*l+n*e,this._y=this._y*l+s*e,this._z=this._z*l+r*e,this._w=this._w*l+o*e,this.normalize();return this}slerpQuaternions(t,e,n){return this.copy(t).slerp(e,n)}random(){let t=2*Math.PI*Math.random(),e=2*Math.PI*Math.random(),n=Math.random(),s=Math.sqrt(1-n),r=Math.sqrt(n);return this.set(s*Math.sin(t),s*Math.cos(t),r*Math.sin(e),r*Math.cos(e))}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._w===this._w}fromArray(t,e=0){return this._x=t[e],this._y=t[e+1],this._z=t[e+2],this._w=t[e+3],this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._w,t}fromBufferAttribute(t,e){return this._x=t.getX(e),this._y=t.getY(e),this._z=t.getZ(e),this._w=t.getW(e),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}},Pc=class Pc{constructor(t=0,e=0,n=0){this.x=t,this.y=e,this.z=n}set(t,e,n){return n===void 0&&(n=this.z),this.x=t,this.y=e,this.z=n,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;default:throw new Error("THREE.Vector3: index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("THREE.Vector3: index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this}multiplyVectors(t,e){return this.x=t.x*e.x,this.y=t.y*e.y,this.z=t.z*e.z,this}applyEuler(t){return this.applyQuaternion(Yh.setFromEuler(t))}applyAxisAngle(t,e){return this.applyQuaternion(Yh.setFromAxisAngle(t,e))}applyMatrix3(t){let e=this.x,n=this.y,s=this.z,r=t.elements;return this.x=r[0]*e+r[3]*n+r[6]*s,this.y=r[1]*e+r[4]*n+r[7]*s,this.z=r[2]*e+r[5]*n+r[8]*s,this}applyNormalMatrix(t){return this.applyMatrix3(t).normalize()}applyMatrix4(t){let e=this.x,n=this.y,s=this.z,r=t.elements,o=1/(r[3]*e+r[7]*n+r[11]*s+r[15]);return this.x=(r[0]*e+r[4]*n+r[8]*s+r[12])*o,this.y=(r[1]*e+r[5]*n+r[9]*s+r[13])*o,this.z=(r[2]*e+r[6]*n+r[10]*s+r[14])*o,this}applyQuaternion(t){let e=this.x,n=this.y,s=this.z,r=t.x,o=t.y,a=t.z,l=t.w,c=2*(o*s-a*n),h=2*(a*e-r*s),d=2*(r*n-o*e);return this.x=e+l*c+o*d-a*h,this.y=n+l*h+a*c-r*d,this.z=s+l*d+r*h-o*c,this}project(t){return this.applyMatrix4(t.matrixWorldInverse).applyMatrix4(t.projectionMatrix)}unproject(t){return this.applyMatrix4(t.projectionMatrixInverse).applyMatrix4(t.matrixWorld)}transformDirection(t){let e=this.x,n=this.y,s=this.z,r=t.elements;return this.x=r[0]*e+r[4]*n+r[8]*s,this.y=r[1]*e+r[5]*n+r[9]*s,this.z=r[2]*e+r[6]*n+r[10]*s,this.normalize()}divide(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this}divideScalar(t){return this.multiplyScalar(1/t)}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this}clamp(t,e){return this.x=$t(this.x,t.x,e.x),this.y=$t(this.y,t.y,e.y),this.z=$t(this.z,t.z,e.z),this}clampScalar(t,e){return this.x=$t(this.x,t,e),this.y=$t(this.y,t,e),this.z=$t(this.z,t,e),this}clampLength(t,e){let n=this.length();return this.divideScalar(n||1).multiplyScalar($t(n,t,e))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this}lerpVectors(t,e,n){return this.x=t.x+(e.x-t.x)*n,this.y=t.y+(e.y-t.y)*n,this.z=t.z+(e.z-t.z)*n,this}cross(t){return this.crossVectors(this,t)}crossVectors(t,e){let n=t.x,s=t.y,r=t.z,o=e.x,a=e.y,l=e.z;return this.x=s*l-r*a,this.y=r*o-n*l,this.z=n*a-s*o,this}projectOnVector(t){let e=t.lengthSq();if(e===0)return this.set(0,0,0);let n=t.dot(this)/e;return this.copy(t).multiplyScalar(n)}projectOnPlane(t){return Ml.copy(this).projectOnVector(t),this.sub(Ml)}reflect(t){return this.sub(Ml.copy(t).multiplyScalar(2*this.dot(t)))}angleTo(t){let e=Math.sqrt(this.lengthSq()*t.lengthSq());if(e===0)return Math.PI/2;let n=this.dot(t)/e;return Math.acos($t(n,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){let e=this.x-t.x,n=this.y-t.y,s=this.z-t.z;return e*e+n*n+s*s}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)+Math.abs(this.z-t.z)}setFromSpherical(t){return this.setFromSphericalCoords(t.radius,t.phi,t.theta)}setFromSphericalCoords(t,e,n){let s=Math.sin(e)*t;return this.x=s*Math.sin(n),this.y=Math.cos(e)*t,this.z=s*Math.cos(n),this}setFromCylindrical(t){return this.setFromCylindricalCoords(t.radius,t.theta,t.y)}setFromCylindricalCoords(t,e,n){return this.x=t*Math.sin(e),this.y=n,this.z=t*Math.cos(e),this}setFromMatrixPosition(t){let e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this}setFromMatrixScale(t){let e=this.setFromMatrixColumn(t,0).length(),n=this.setFromMatrixColumn(t,1).length(),s=this.setFromMatrixColumn(t,2).length();return this.x=e,this.y=n,this.z=s,this}setFromMatrixColumn(t,e){return this.fromArray(t.elements,e*4)}setFromMatrix3Column(t,e){return this.fromArray(t.elements,e*3)}setFromEuler(t){return this.x=t._x,this.y=t._y,this.z=t._z,this}setFromColor(t){return this.x=t.r,this.y=t.g,this.z=t.b,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this.z=t.getZ(e),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){let t=Math.random()*Math.PI*2,e=Math.random()*2-1,n=Math.sqrt(1-e*e);return this.x=n*Math.cos(t),this.y=e,this.z=n*Math.sin(t),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}};Pc.prototype.isVector3=!0;var I=Pc,Ml=new I,Yh=new Ce,Lc=class Lc{constructor(t,e,n,s,r,o,a,l,c){this.elements=[1,0,0,0,1,0,0,0,1],t!==void 0&&this.set(t,e,n,s,r,o,a,l,c)}set(t,e,n,s,r,o,a,l,c){let h=this.elements;return h[0]=t,h[1]=s,h[2]=a,h[3]=e,h[4]=r,h[5]=l,h[6]=n,h[7]=o,h[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(t){let e=this.elements,n=t.elements;return e[0]=n[0],e[1]=n[1],e[2]=n[2],e[3]=n[3],e[4]=n[4],e[5]=n[5],e[6]=n[6],e[7]=n[7],e[8]=n[8],this}extractBasis(t,e,n){return t.setFromMatrix3Column(this,0),e.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(t){let e=t.elements;return this.set(e[0],e[4],e[8],e[1],e[5],e[9],e[2],e[6],e[10]),this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){let n=t.elements,s=e.elements,r=this.elements,o=n[0],a=n[3],l=n[6],c=n[1],h=n[4],d=n[7],u=n[2],p=n[5],g=n[8],_=s[0],m=s[3],f=s[6],b=s[1],E=s[4],M=s[7],v=s[2],S=s[5],A=s[8];return r[0]=o*_+a*b+l*v,r[3]=o*m+a*E+l*S,r[6]=o*f+a*M+l*A,r[1]=c*_+h*b+d*v,r[4]=c*m+h*E+d*S,r[7]=c*f+h*M+d*A,r[2]=u*_+p*b+g*v,r[5]=u*m+p*E+g*S,r[8]=u*f+p*M+g*A,this}multiplyScalar(t){let e=this.elements;return e[0]*=t,e[3]*=t,e[6]*=t,e[1]*=t,e[4]*=t,e[7]*=t,e[2]*=t,e[5]*=t,e[8]*=t,this}determinant(){let t=this.elements,e=t[0],n=t[1],s=t[2],r=t[3],o=t[4],a=t[5],l=t[6],c=t[7],h=t[8];return e*o*h-e*a*c-n*r*h+n*a*l+s*r*c-s*o*l}invert(){let t=this.elements,e=t[0],n=t[1],s=t[2],r=t[3],o=t[4],a=t[5],l=t[6],c=t[7],h=t[8],d=h*o-a*c,u=a*l-h*r,p=c*r-o*l,g=e*d+n*u+s*p;if(g===0)return this.set(0,0,0,0,0,0,0,0,0);let _=1/g;return t[0]=d*_,t[1]=(s*c-h*n)*_,t[2]=(a*n-s*o)*_,t[3]=u*_,t[4]=(h*e-s*l)*_,t[5]=(s*r-a*e)*_,t[6]=p*_,t[7]=(n*l-c*e)*_,t[8]=(o*e-n*r)*_,this}transpose(){let t,e=this.elements;return t=e[1],e[1]=e[3],e[3]=t,t=e[2],e[2]=e[6],e[6]=t,t=e[5],e[5]=e[7],e[7]=t,this}getNormalMatrix(t){return this.setFromMatrix4(t).invert().transpose()}transposeIntoArray(t){let e=this.elements;return t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8],this}setUvTransform(t,e,n,s,r,o,a){let l=Math.cos(r),c=Math.sin(r);return this.set(n*l,n*c,-n*(l*o+c*a)+o+t,-s*c,s*l,-s*(-c*o+l*a)+a+e,0,0,1),this}scale(t,e){return Ai("Matrix3: .scale() is deprecated. Use .makeScale() instead."),this.premultiply(bl.makeScale(t,e)),this}rotate(t){return Ai("Matrix3: .rotate() is deprecated. Use .makeRotation() instead."),this.premultiply(bl.makeRotation(-t)),this}translate(t,e){return Ai("Matrix3: .translate() is deprecated. Use .makeTranslation() instead."),this.premultiply(bl.makeTranslation(t,e)),this}makeTranslation(t,e){return t.isVector2?this.set(1,0,t.x,0,1,t.y,0,0,1):this.set(1,0,t,0,1,e,0,0,1),this}makeRotation(t){let e=Math.cos(t),n=Math.sin(t);return this.set(e,-n,0,n,e,0,0,0,1),this}makeScale(t,e){return this.set(t,0,0,0,e,0,0,0,1),this}equals(t){let e=this.elements,n=t.elements;for(let s=0;s<9;s++)if(e[s]!==n[s])return!1;return!0}fromArray(t,e=0){for(let n=0;n<9;n++)this.elements[n]=t[n+e];return this}toArray(t=[],e=0){let n=this.elements;return t[e]=n[0],t[e+1]=n[1],t[e+2]=n[2],t[e+3]=n[3],t[e+4]=n[4],t[e+5]=n[5],t[e+6]=n[6],t[e+7]=n[7],t[e+8]=n[8],t}clone(){return new this.constructor().fromArray(this.elements)}};Lc.prototype.isMatrix3=!0;var Ot=Lc,bl=new Ot,$h=new Ot().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),Zh=new Ot().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function Vp(){let i={enabled:!0,workingColorSpace:Xs,spaces:{},convert:function(s,r,o){return this.enabled===!1||r===o||!r||!o||(this.spaces[r].transfer===te&&(s.r=Zn(s.r),s.g=Zn(s.g),s.b=Zn(s.b)),this.spaces[r].primaries!==this.spaces[o].primaries&&(s.applyMatrix3(this.spaces[r].toXYZ),s.applyMatrix3(this.spaces[o].fromXYZ)),this.spaces[o].transfer===te&&(s.r=ss(s.r),s.g=ss(s.g),s.b=ss(s.b))),s},workingToColorSpace:function(s,r){return this.convert(s,this.workingColorSpace,r)},colorSpaceToWorking:function(s,r){return this.convert(s,r,this.workingColorSpace)},getPrimaries:function(s){return this.spaces[s].primaries},getTransfer:function(s){return s===jn?qs:this.spaces[s].transfer},getToneMappingMode:function(s){return this.spaces[s].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(s,r=this.workingColorSpace){return s.fromArray(this.spaces[r].luminanceCoefficients)},define:function(s){Object.assign(this.spaces,s)},_getMatrix:function(s,r,o){return s.copy(this.spaces[r].toXYZ).multiply(this.spaces[o].fromXYZ)},_getDrawingBufferColorSpace:function(s){return this.spaces[s].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(s=this.workingColorSpace){return this.spaces[s].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(s,r){return Ai("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),i.workingToColorSpace(s,r)},toWorkingColorSpace:function(s,r){return Ai("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),i.colorSpaceToWorking(s,r)}},t=[.64,.33,.3,.6,.15,.06],e=[.2126,.7152,.0722],n=[.3127,.329];return i.define({[Xs]:{primaries:t,whitePoint:n,transfer:qs,toXYZ:$h,fromXYZ:Zh,luminanceCoefficients:e,workingColorSpaceConfig:{unpackColorSpace:Ae},outputColorSpaceConfig:{drawingBufferColorSpace:Ae}},[Ae]:{primaries:t,whitePoint:n,transfer:te,toXYZ:$h,fromXYZ:Zh,luminanceCoefficients:e,outputColorSpaceConfig:{drawingBufferColorSpace:Ae}}}),i}var Yt=Vp();function Zn(i){return i<.04045?i*.0773993808:Math.pow(i*.9478672986+.0521327014,2.4)}function ss(i){return i<.0031308?i*12.92:1.055*Math.pow(i,.41666)-.055}var Gi,Eo=class{static getDataURL(t,e="image/png"){if(/^data:/i.test(t.src)||typeof HTMLCanvasElement>"u")return t.src;let n;if(t instanceof HTMLCanvasElement)n=t;else{Gi===void 0&&(Gi=Ys("canvas")),Gi.width=t.width,Gi.height=t.height;let s=Gi.getContext("2d");t instanceof ImageData?s.putImageData(t,0,0):s.drawImage(t,0,0,t.width,t.height),n=Gi}return n.toDataURL(e)}static sRGBToLinear(t){if(typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&t instanceof ImageBitmap){let e=Ys("canvas");e.width=t.width,e.height=t.height;let n=e.getContext("2d");n.drawImage(t,0,0,t.width,t.height);let s=n.getImageData(0,0,t.width,t.height),r=s.data;for(let o=0;o1),this.pmremVersion=0,this.normalized=!1}get width(){return this.source.getSize(wl).x}get height(){return this.source.getSize(wl).y}get depth(){return this.source.getSize(wl).z}get image(){return this.source.data}set image(t){this.source.data=t}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(t,e){this.updateRanges.push({start:t,count:e})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(t){return this.name=t.name,this.source=t.source,this.mipmaps=t.mipmaps.slice(0),this.mapping=t.mapping,this.channel=t.channel,this.wrapS=t.wrapS,this.wrapT=t.wrapT,this.magFilter=t.magFilter,this.minFilter=t.minFilter,this.anisotropy=t.anisotropy,this.format=t.format,this.internalFormat=t.internalFormat,this.type=t.type,this.normalized=t.normalized,this.offset.copy(t.offset),this.repeat.copy(t.repeat),this.center.copy(t.center),this.rotation=t.rotation,this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrix.copy(t.matrix),this.generateMipmaps=t.generateMipmaps,this.premultiplyAlpha=t.premultiplyAlpha,this.flipY=t.flipY,this.unpackAlignment=t.unpackAlignment,this.colorSpace=t.colorSpace,this.renderTarget=t.renderTarget,this.isRenderTargetTexture=t.isRenderTargetTexture,this.isArrayTexture=t.isArrayTexture,this.userData=JSON.parse(JSON.stringify(t.userData)),this.needsUpdate=!0,this}setValues(t){for(let e in t){let n=t[e];if(n===void 0){Dt(`Texture.setValues(): parameter '${e}' has value of undefined.`);continue}let s=this[e];if(s===void 0){Dt(`Texture.setValues(): property '${e}' does not exist.`);continue}s&&n&&s.isVector2&&n.isVector2||s&&n&&s.isVector3&&n.isVector3||s&&n&&s.isMatrix3&&n.isMatrix3?s.copy(n):this[e]=n}}toJSON(t){let e=t===void 0||typeof t=="string";if(!e&&t.textures[this.uuid]!==void 0)return t.textures[this.uuid];let n={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(t).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,normalized:this.normalized,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(n.userData=this.userData),e||(t.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(t){if(this.mapping!==dc)return t;if(t.applyMatrix3(this.matrix),t.x<0||t.x>1)switch(this.wrapS){case os:t.x=t.x-Math.floor(t.x);break;case In:t.x=t.x<0?0:1;break;case So:Math.abs(Math.floor(t.x)%2)===1?t.x=Math.ceil(t.x)-t.x:t.x=t.x-Math.floor(t.x);break}if(t.y<0||t.y>1)switch(this.wrapT){case os:t.y=t.y-Math.floor(t.y);break;case In:t.y=t.y<0?0:1;break;case So:Math.abs(Math.floor(t.y)%2)===1?t.y=Math.ceil(t.y)-t.y:t.y=t.y-Math.floor(t.y);break}return this.flipY&&(t.y=1-t.y),t}set needsUpdate(t){t===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(t){t===!0&&this.pmremVersion++}};ke.DEFAULT_IMAGE=null;ke.DEFAULT_MAPPING=dc;ke.DEFAULT_ANISOTROPY=1;var Dc=class Dc{constructor(t=0,e=0,n=0,s=1){this.x=t,this.y=e,this.z=n,this.w=s}get width(){return this.z}set width(t){this.z=t}get height(){return this.w}set height(t){this.w=t}set(t,e,n,s){return this.x=t,this.y=e,this.z=n,this.w=s,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this.w=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setW(t){return this.w=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;case 3:this.w=e;break;default:throw new Error("THREE.Vector4: index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("THREE.Vector4: index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w!==void 0?t.w:1,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this.w+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this.w=t.w+e.w,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this.w+=t.w*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this.w-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this.w=t.w-e.w,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this}applyMatrix4(t){let e=this.x,n=this.y,s=this.z,r=this.w,o=t.elements;return this.x=o[0]*e+o[4]*n+o[8]*s+o[12]*r,this.y=o[1]*e+o[5]*n+o[9]*s+o[13]*r,this.z=o[2]*e+o[6]*n+o[10]*s+o[14]*r,this.w=o[3]*e+o[7]*n+o[11]*s+o[15]*r,this}divide(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this.w/=t.w,this}divideScalar(t){return this.multiplyScalar(1/t)}setAxisAngleFromQuaternion(t){this.w=2*Math.acos(t.w);let e=Math.sqrt(1-t.w*t.w);return e<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=t.x/e,this.y=t.y/e,this.z=t.z/e),this}setAxisAngleFromRotationMatrix(t){let e,n,s,r,l=t.elements,c=l[0],h=l[4],d=l[8],u=l[1],p=l[5],g=l[9],_=l[2],m=l[6],f=l[10];if(Math.abs(h-u)<.01&&Math.abs(d-_)<.01&&Math.abs(g-m)<.01){if(Math.abs(h+u)<.1&&Math.abs(d+_)<.1&&Math.abs(g+m)<.1&&Math.abs(c+p+f-3)<.1)return this.set(1,0,0,0),this;e=Math.PI;let E=(c+1)/2,M=(p+1)/2,v=(f+1)/2,S=(h+u)/4,A=(d+_)/4,x=(g+m)/4;return E>M&&E>v?E<.01?(n=0,s=.707106781,r=.707106781):(n=Math.sqrt(E),s=S/n,r=A/n):M>v?M<.01?(n=.707106781,s=0,r=.707106781):(s=Math.sqrt(M),n=S/s,r=x/s):v<.01?(n=.707106781,s=.707106781,r=0):(r=Math.sqrt(v),n=A/r,s=x/r),this.set(n,s,r,e),this}let b=Math.sqrt((m-g)*(m-g)+(d-_)*(d-_)+(u-h)*(u-h));return Math.abs(b)<.001&&(b=1),this.x=(m-g)/b,this.y=(d-_)/b,this.z=(u-h)/b,this.w=Math.acos((c+p+f-1)/2),this}setFromMatrixPosition(t){let e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this.w=e[15],this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this.w=Math.min(this.w,t.w),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this.w=Math.max(this.w,t.w),this}clamp(t,e){return this.x=$t(this.x,t.x,e.x),this.y=$t(this.y,t.y,e.y),this.z=$t(this.z,t.z,e.z),this.w=$t(this.w,t.w,e.w),this}clampScalar(t,e){return this.x=$t(this.x,t,e),this.y=$t(this.y,t,e),this.z=$t(this.z,t,e),this.w=$t(this.w,t,e),this}clampLength(t,e){let n=this.length();return this.divideScalar(n||1).multiplyScalar($t(n,t,e))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z+this.w*t.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this.w+=(t.w-this.w)*e,this}lerpVectors(t,e,n){return this.x=t.x+(e.x-t.x)*n,this.y=t.y+(e.y-t.y)*n,this.z=t.z+(e.z-t.z)*n,this.w=t.w+(e.w-t.w)*n,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z&&t.w===this.w}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this.w=t[e+3],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t[e+3]=this.w,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this.z=t.getZ(e),this.w=t.getW(e),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}};Dc.prototype.isVector4=!0;var ae=Dc,To=class extends Ln{constructor(t=1,e=1,n={}){super(),n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:ze,depthBuffer:!0,stencilBuffer:!1,resolveColorBuffer:!0,resolveDepthBuffer:!0,resolveStencilBuffer:!0,storeMultisampledColorBuffer:!0,storeMultisampledDepthBuffer:!0,storeMultisampledStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1,useArrayDepthTexture:!1},n),this.isRenderTarget=!0,this.width=t,this.height=e,this.depth=n.depth,this.scissor=new ae(0,0,t,e),this.scissorTest=!1,this.viewport=new ae(0,0,t,e),this.textures=[];let s={width:t,height:e,depth:n.depth},r=new ke(s),o=n.count;for(let a=0;a1);this.dispose()}this.viewport.set(0,0,t,e),this.scissor.set(0,0,t,e)}clone(){return new this.constructor().copy(this)}copy(t){this.width=t.width,this.height=t.height,this.depth=t.depth,this.scissor.copy(t.scissor),this.scissorTest=t.scissorTest,this.viewport.copy(t.viewport),this.textures.length=0;for(let e=0,n=t.textures.length;e>>0}enable(t){this.mask|=1<1){for(let e=0;e1){for(let n=0;n0&&(s.userData=this.userData),s.layers=this.layers.mask,s.matrix=this.matrix.toArray(),s.up=this.up.toArray(),this.pivot!==null&&(s.pivot=this.pivot.toArray()),this.morphTargetDictionary!==void 0&&(s.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),this.morphTargetInfluences!==void 0&&(s.morphTargetInfluences=this.morphTargetInfluences.slice()),this.isInstancedMesh&&(s.type="InstancedMesh",s.count=this.count,s.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(s.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(s.type="BatchedMesh",s.perObjectFrustumCulled=this.perObjectFrustumCulled,s.sortObjects=this.sortObjects,s.drawRanges=this._drawRanges,s.reservedRanges=this._reservedRanges,s.geometryInfo=this._geometryInfo.map(a=>({...a,boundingBox:a.boundingBox?a.boundingBox.toJSON():void 0,boundingSphere:a.boundingSphere?a.boundingSphere.toJSON():void 0})),s.instanceInfo=this._instanceInfo.map(a=>({...a})),s.availableInstanceIds=this._availableInstanceIds.slice(),s.availableGeometryIds=this._availableGeometryIds.slice(),s.nextIndexStart=this._nextIndexStart,s.nextVertexStart=this._nextVertexStart,s.geometryCount=this._geometryCount,s.maxInstanceCount=this._maxInstanceCount,s.maxVertexCount=this._maxVertexCount,s.maxIndexCount=this._maxIndexCount,s.geometryInitialized=this._geometryInitialized,s.matricesTexture=this._matricesTexture.toJSON(t),s.indirectTexture=this._indirectTexture.toJSON(t),this._colorsTexture!==null&&(s.colorsTexture=this._colorsTexture.toJSON(t)),this.boundingSphere!==null&&(s.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(s.boundingBox=this.boundingBox.toJSON()));function r(a,l){return a[l.uuid]===void 0&&(a[l.uuid]=l.toJSON(t)),l.uuid}if(this.isScene)this.background&&(this.background.isColor?s.background=this.background.toJSON():this.background.isTexture&&(s.background=this.background.toJSON(t).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(s.environment=this.environment.toJSON(t).uuid);else if(this.isMesh||this.isLine||this.isPoints){s.geometry=r(t.geometries,this.geometry);let a=this.geometry.parameters;if(a!==void 0&&a.shapes!==void 0){let l=a.shapes;if(Array.isArray(l))for(let c=0,h=l.length;c0){s.children=[];for(let a=0;a0){s.animations=[];for(let a=0;a0&&(n.geometries=a),l.length>0&&(n.materials=l),c.length>0&&(n.textures=c),h.length>0&&(n.images=h),d.length>0&&(n.shapes=d),u.length>0&&(n.skeletons=u),p.length>0&&(n.animations=p),g.length>0&&(n.nodes=g)}return n.object=s,n;function o(a){let l=[];for(let c in a){let h=a[c];delete h.metadata,l.push(h)}return l}}clone(t){return new this.constructor().copy(this,t)}copy(t,e=!0){if(this.name=t.name,this.up.copy(t.up),this.position.copy(t.position),this.rotation.order=t.rotation.order,this.quaternion.copy(t.quaternion),this.scale.copy(t.scale),this.pivot=t.pivot!==null?t.pivot.clone():null,this.matrix.copy(t.matrix),this.matrixWorld.copy(t.matrixWorld),this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrixWorldAutoUpdate=t.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=t.matrixWorldNeedsUpdate,this.layers.mask=t.layers.mask,this.visible=t.visible,this.castShadow=t.castShadow,this.receiveShadow=t.receiveShadow,this.frustumCulled=t.frustumCulled,this.renderOrder=t.renderOrder,this.static=t.static,this.animations=t.animations.slice(),this.userData=JSON.parse(JSON.stringify(t.userData)),e===!0)for(let n=0;np+g?(c.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:t.handedness,target:this})):!c.inputState.pinching&&u<=p-g&&(c.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:t.handedness,target:this}))}else l!==null&&t.gripSpace&&(r=e.getPose(t.gripSpace,n),r!==null&&(l.matrix.fromArray(r.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),l.matrixWorldNeedsUpdate=!0,r.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(r.linearVelocity)):l.hasLinearVelocity=!1,r.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(r.angularVelocity)):l.hasAngularVelocity=!1,l.eventsEnabled&&l.dispatchEvent({type:"gripUpdated",data:t,target:this})));a!==null&&(s=e.getPose(t.targetRaySpace,n),s===null&&r!==null&&(s=r),s!==null&&(a.matrix.fromArray(s.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,s.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(s.linearVelocity)):a.hasLinearVelocity=!1,s.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(s.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(Kp)))}return a!==null&&(a.visible=s!==null),l!==null&&(l.visible=r!==null),c!==null&&(c.visible=o!==null),this}_getHandJoint(t,e){if(t.joints[e.jointName]===void 0){let n=new Re;n.matrixAutoUpdate=!1,n.visible=!1,t.joints[e.jointName]=n,t.add(n)}return t.joints[e.jointName]}},od={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},ri={h:0,s:0,l:0},Vr={h:0,s:0,l:0};function Tl(i,t,e){return e<0&&(e+=1),e>1&&(e-=1),e<1/6?i+(t-i)*6*e:e<1/2?t:e<2/3?i+(t-i)*6*(2/3-e):i}var Ft=class{constructor(t,e,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(t,e,n)}set(t,e,n){if(e===void 0&&n===void 0){let s=t;s&&s.isColor?this.copy(s):typeof s=="number"?this.setHex(s):typeof s=="string"&&this.setStyle(s)}else this.setRGB(t,e,n);return this}setScalar(t){return this.r=t,this.g=t,this.b=t,this}setHex(t,e=Ae){return t=Math.floor(t),this.r=(t>>16&255)/255,this.g=(t>>8&255)/255,this.b=(t&255)/255,Yt.colorSpaceToWorking(this,e),this}setRGB(t,e,n,s=Yt.workingColorSpace){return this.r=t,this.g=e,this.b=n,Yt.colorSpaceToWorking(this,s),this}setHSL(t,e,n,s=Yt.workingColorSpace){if(t=Ec(t,1),e=$t(e,0,1),n=$t(n,0,1),e===0)this.r=this.g=this.b=n;else{let r=n<=.5?n*(1+e):n+e-n*e,o=2*n-r;this.r=Tl(o,r,t+1/3),this.g=Tl(o,r,t),this.b=Tl(o,r,t-1/3)}return Yt.colorSpaceToWorking(this,s),this}setStyle(t,e=Ae){function n(r){r!==void 0&&parseFloat(r)<1&&Dt("Color: Alpha component of "+t+" will be ignored.")}let s;if(s=/^(\w+)\(([^\)]*)\)/.exec(t)){let r,o=s[1],a=s[2];switch(o){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setRGB(Math.min(255,parseInt(r[1],10))/255,Math.min(255,parseInt(r[2],10))/255,Math.min(255,parseInt(r[3],10))/255,e);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setRGB(Math.min(100,parseInt(r[1],10))/100,Math.min(100,parseInt(r[2],10))/100,Math.min(100,parseInt(r[3],10))/100,e);break;case"hsl":case"hsla":if(r=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,e);break;default:Dt("Color: Unknown color model "+t)}}else if(s=/^\#([A-Fa-f\d]+)$/.exec(t)){let r=s[1],o=r.length;if(o===3)return this.setRGB(parseInt(r.charAt(0),16)/15,parseInt(r.charAt(1),16)/15,parseInt(r.charAt(2),16)/15,e);if(o===6)return this.setHex(parseInt(r,16),e);Dt("Color: Invalid hex color "+t)}else if(t&&t.length>0)return this.setColorName(t,e);return this}setColorName(t,e=Ae){let n=od[t.toLowerCase()];return n!==void 0?this.setHex(n,e):Dt("Color: Unknown color "+t),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(t){return this.r=t.r,this.g=t.g,this.b=t.b,this}copySRGBToLinear(t){return this.r=Zn(t.r),this.g=Zn(t.g),this.b=Zn(t.b),this}copyLinearToSRGB(t){return this.r=ss(t.r),this.g=ss(t.g),this.b=ss(t.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(t=Ae){return Yt.workingToColorSpace(Ye.copy(this),t),Math.round($t(Ye.r*255,0,255))*65536+Math.round($t(Ye.g*255,0,255))*256+Math.round($t(Ye.b*255,0,255))}getHexString(t=Ae){return("000000"+this.getHex(t).toString(16)).slice(-6)}getHSL(t,e=Yt.workingColorSpace){Yt.workingToColorSpace(Ye.copy(this),e);let n=Ye.r,s=Ye.g,r=Ye.b,o=Math.max(n,s,r),a=Math.min(n,s,r),l,c,h=(a+o)/2;if(a===o)l=0,c=0;else{let d=o-a;switch(c=h<=.5?d/(o+a):d/(2-o-a),o){case n:l=(s-r)/d+(s0?s.multiplyScalar(1/Math.sqrt(r)):s.set(0,0,0)}static getBarycoord(t,e,n,s,r){mn.subVectors(s,e),Gn.subVectors(n,e),Al.subVectors(t,e);let o=mn.dot(mn),a=mn.dot(Gn),l=mn.dot(Al),c=Gn.dot(Gn),h=Gn.dot(Al),d=o*c-a*a;if(d===0)return r.set(0,0,0),null;let u=1/d,p=(c*l-a*h)*u,g=(o*h-a*l)*u;return r.set(1-p-g,g,p)}static containsPoint(t,e,n,s){return this.getBarycoord(t,e,n,s,Wn)===null?!1:Wn.x>=0&&Wn.y>=0&&Wn.x+Wn.y<=1}static getInterpolation(t,e,n,s,r,o,a,l){return this.getBarycoord(t,e,n,s,Wn)===null?(l.x=0,l.y=0,"z"in l&&(l.z=0),"w"in l&&(l.w=0),null):(l.setScalar(0),l.addScaledVector(r,Wn.x),l.addScaledVector(o,Wn.y),l.addScaledVector(a,Wn.z),l)}static getInterpolatedAttribute(t,e,n,s,r,o){return Pl.setScalar(0),Ll.setScalar(0),Dl.setScalar(0),Pl.fromBufferAttribute(t,e),Ll.fromBufferAttribute(t,n),Dl.fromBufferAttribute(t,s),o.setScalar(0),o.addScaledVector(Pl,r.x),o.addScaledVector(Ll,r.y),o.addScaledVector(Dl,r.z),o}static isFrontFacing(t,e,n,s){return mn.subVectors(n,e),Gn.subVectors(t,e),mn.cross(Gn).dot(s)<0}set(t,e,n){return this.a.copy(t),this.b.copy(e),this.c.copy(n),this}setFromPointsAndIndices(t,e,n,s){return this.a.copy(t[e]),this.b.copy(t[n]),this.c.copy(t[s]),this}setFromAttributeAndIndices(t,e,n,s){return this.a.fromBufferAttribute(t,e),this.b.fromBufferAttribute(t,n),this.c.fromBufferAttribute(t,s),this}clone(){return new this.constructor().copy(this)}copy(t){return this.a.copy(t.a),this.b.copy(t.b),this.c.copy(t.c),this}getArea(){return mn.subVectors(this.c,this.b),Gn.subVectors(this.a,this.b),mn.cross(Gn).length()*.5}getMidpoint(t){return t.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return i.getNormal(this.a,this.b,this.c,t)}getPlane(t){return t.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,e){return i.getBarycoord(t,this.a,this.b,this.c,e)}getInterpolation(t,e,n,s,r){return i.getInterpolation(t,this.a,this.b,this.c,e,n,s,r)}containsPoint(t){return i.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return i.isFrontFacing(this.a,this.b,this.c,t)}intersectsBox(t){return t.intersectsTriangle(this)}closestPointToPoint(t,e){let n=this.a,s=this.b,r=this.c,o,a;Yi.subVectors(s,n),$i.subVectors(r,n),Rl.subVectors(t,n);let l=Yi.dot(Rl),c=$i.dot(Rl);if(l<=0&&c<=0)return e.copy(n);Cl.subVectors(t,s);let h=Yi.dot(Cl),d=$i.dot(Cl);if(h>=0&&d<=h)return e.copy(s);let u=l*d-h*c;if(u<=0&&l>=0&&h<=0)return o=l/(l-h),e.copy(n).addScaledVector(Yi,o);Il.subVectors(t,r);let p=Yi.dot(Il),g=$i.dot(Il);if(g>=0&&p<=g)return e.copy(r);let _=p*c-l*g;if(_<=0&&c>=0&&g<=0)return a=c/(c-g),e.copy(n).addScaledVector($i,a);let m=h*g-p*d;if(m<=0&&d-h>=0&&p-g>=0)return iu.subVectors(r,s),a=(d-h)/(d-h+(p-g)),e.copy(s).addScaledVector(iu,a);let f=1/(m+_+u);return o=_*f,a=u*f,e.copy(n).addScaledVector(Yi,o).addScaledVector($i,a)}equals(t){return t.a.equals(this.a)&&t.b.equals(this.b)&&t.c.equals(this.c)}},ie=class{constructor(t=new I(1/0,1/0,1/0),e=new I(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=t,this.max=e}set(t,e){return this.min.copy(t),this.max.copy(e),this}setFromArray(t){this.makeEmpty();for(let e=0,n=t.length;e=this.min.x&&t.x<=this.max.x&&t.y>=this.min.y&&t.y<=this.max.y&&t.z>=this.min.z&&t.z<=this.max.z}containsBox(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y&&this.min.z<=t.min.z&&t.max.z<=this.max.z}getParameter(t,e){return e.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y),(t.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(t){return t.max.x>=this.min.x&&t.min.x<=this.max.x&&t.max.y>=this.min.y&&t.min.y<=this.max.y&&t.max.z>=this.min.z&&t.min.z<=this.max.z}intersectsSphere(t){return this.clampPoint(t.center,gn),gn.distanceToSquared(t.center)<=t.radius*t.radius}intersectsPlane(t){let e,n;return t.normal.x>0?(e=t.normal.x*this.min.x,n=t.normal.x*this.max.x):(e=t.normal.x*this.max.x,n=t.normal.x*this.min.x),t.normal.y>0?(e+=t.normal.y*this.min.y,n+=t.normal.y*this.max.y):(e+=t.normal.y*this.max.y,n+=t.normal.y*this.min.y),t.normal.z>0?(e+=t.normal.z*this.min.z,n+=t.normal.z*this.max.z):(e+=t.normal.z*this.max.z,n+=t.normal.z*this.min.z),e<=-t.constant&&n>=-t.constant}intersectsTriangle(t){if(this.isEmpty())return!1;this.getCenter(Bs),Wr.subVectors(this.max,Bs),Zi.subVectors(t.a,Bs),Ji.subVectors(t.b,Bs),Ki.subVectors(t.c,Bs),oi.subVectors(Ji,Zi),ai.subVectors(Ki,Ji),Si.subVectors(Zi,Ki);let e=[0,-oi.z,oi.y,0,-ai.z,ai.y,0,-Si.z,Si.y,oi.z,0,-oi.x,ai.z,0,-ai.x,Si.z,0,-Si.x,-oi.y,oi.x,0,-ai.y,ai.x,0,-Si.y,Si.x,0];return!Nl(e,Zi,Ji,Ki,Wr)||(e=[1,0,0,0,1,0,0,0,1],!Nl(e,Zi,Ji,Ki,Wr))?!1:(Xr.crossVectors(oi,ai),e=[Xr.x,Xr.y,Xr.z],Nl(e,Zi,Ji,Ki,Wr))}clampPoint(t,e){return e.copy(t).clamp(this.min,this.max)}distanceToPoint(t){return this.clampPoint(t,gn).distanceTo(t)}getBoundingSphere(t){return this.isEmpty()?t.makeEmpty():(this.getCenter(t.center),t.radius=this.getSize(gn).length()*.5),t}intersect(t){return this.min.max(t.min),this.max.min(t.max),this.isEmpty()&&this.makeEmpty(),this}union(t){return this.min.min(t.min),this.max.max(t.max),this}applyMatrix4(t){return this.isEmpty()?this:(Xn[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(t),Xn[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(t),Xn[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(t),Xn[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(t),Xn[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(t),Xn[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(t),Xn[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(t),Xn[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(t),this.setFromPoints(Xn),this)}translate(t){return this.min.add(t),this.max.add(t),this}equals(t){return t.min.equals(this.min)&&t.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(t){return this.min.fromArray(t.min),this.max.fromArray(t.max),this}},Xn=[new I,new I,new I,new I,new I,new I,new I,new I],gn=new I,Gr=new ie,Zi=new I,Ji=new I,Ki=new I,oi=new I,ai=new I,Si=new I,Bs=new I,Wr=new I,Xr=new I,wi=new I;function Nl(i,t,e,n,s){for(let r=0,o=i.length-3;r<=o;r+=3){wi.fromArray(i,r);let a=s.x*Math.abs(wi.x)+s.y*Math.abs(wi.y)+s.z*Math.abs(wi.z),l=t.dot(wi),c=e.dot(wi),h=n.dot(wi);if(Math.max(-Math.max(l,c,h),Math.min(l,c,h))>a)return!1}return!0}var Te=new I,qr=new Ht,jp=0,Se=class extends Ln{constructor(t,e,n=!1){if(super(),Array.isArray(t))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:jp++}),this.name="",this.array=t,this.itemSize=e,this.count=t!==void 0?t.length/e:0,this.normalized=n,this.usage=bc,this.updateRanges=[],this.gpuType=Ge,this.version=0}onUploadCallback(){}set needsUpdate(t){t===!0&&this.version++}setUsage(t){return this.usage=t,this}addUpdateRange(t,e){this.updateRanges.push({start:t,count:e})}clearUpdateRanges(){this.updateRanges.length=0}copy(t){return this.name=t.name,this.array=new t.array.constructor(t.array),this.itemSize=t.itemSize,this.count=t.count,this.normalized=t.normalized,this.usage=t.usage,this.gpuType=t.gpuType,this}copyAt(t,e,n){t*=this.itemSize,n*=e.itemSize;for(let s=0,r=this.itemSize;sthis.radius*this.radius&&(e.sub(this.center).normalize(),e.multiplyScalar(this.radius).add(this.center)),e}getBoundingBox(t){return this.isEmpty()?(t.makeEmpty(),t):(t.set(this.center,this.center),t.expandByScalar(this.radius),t)}applyMatrix4(t){return this.center.applyMatrix4(t),this.radius=this.radius*t.getMaxScaleOnAxis(),this}translate(t){return this.center.add(t),this}expandByPoint(t){if(this.isEmpty())return this.center.copy(t),this.radius=0,this;Os.subVectors(t,this.center);let e=Os.lengthSq();if(e>this.radius*this.radius){let n=Math.sqrt(e),s=(n-this.radius)*.5;this.center.addScaledVector(Os,s/n),this.radius+=s}return this}union(t){return t.isEmpty()?this:this.isEmpty()?(this.copy(t),this):(this.center.equals(t.center)===!0?this.radius=Math.max(this.radius,t.radius):(Ul.subVectors(t.center,this.center).setLength(t.radius),this.expandByPoint(Os.copy(t.center).add(Ul)),this.expandByPoint(Os.copy(t.center).sub(Ul))),this)}equals(t){return t.center.equals(this.center)&&t.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(t){return this.radius=t.radius,this.center.fromArray(t.center),this}},tm=0,un=new kt,Fl=new Be,ji=new I,on=new ie,zs=new ie,Ne=new I,le=class i extends Ln{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:tm++}),this.uuid=$n(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={},this._transformed=!1}getIndex(){return this.index}setIndex(t){return Array.isArray(t)?this.index=new(wp(t)?Ks:Js)(t,1):this.index=t,this}setIndirect(t,e=0){return this.indirect=t,this.indirectOffset=e,this}getIndirect(){return this.indirect}getAttribute(t){return this.attributes[t]}setAttribute(t,e){return this.attributes[t]=e,this}deleteAttribute(t){return delete this.attributes[t],this}hasAttribute(t){return this.attributes[t]!==void 0}addGroup(t,e,n=0){this.groups.push({start:t,count:e,materialIndex:n})}clearGroups(){this.groups=[]}setDrawRange(t,e){this.drawRange.start=t,this.drawRange.count=e}applyMatrix4(t){let e=this.attributes.position;e!==void 0&&(e.applyMatrix4(t),e.needsUpdate=!0);let n=this.attributes.normal;if(n!==void 0){let r=new Ot().getNormalMatrix(t);n.applyNormalMatrix(r),n.needsUpdate=!0}let s=this.attributes.tangent;return s!==void 0&&(s.transformDirection(t),s.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this._transformed=!0,this}applyQuaternion(t){return un.makeRotationFromQuaternion(t),this.applyMatrix4(un),this}rotateX(t){return un.makeRotationX(t),this.applyMatrix4(un),this}rotateY(t){return un.makeRotationY(t),this.applyMatrix4(un),this}rotateZ(t){return un.makeRotationZ(t),this.applyMatrix4(un),this}translate(t,e,n){return un.makeTranslation(t,e,n),this.applyMatrix4(un),this}scale(t,e,n){return un.makeScale(t,e,n),this.applyMatrix4(un),this}lookAt(t){return Fl.lookAt(t),Fl.updateMatrix(),this.applyMatrix4(Fl.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(ji).negate(),this.translate(ji.x,ji.y,ji.z),this}setFromPoints(t){let e=this.getAttribute("position");if(e===void 0){let n=[];for(let s=0,r=t.length;se.count&&Dt("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),e.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new ie);let t=this.attributes.position,e=this.morphAttributes.position;if(t&&t.isGLBufferAttribute){Ut("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new I(-1/0,-1/0,-1/0),new I(1/0,1/0,1/0));return}if(t!==void 0){if(this.boundingBox.setFromBufferAttribute(t),e)for(let n=0,s=e.length;n0&&(t.userData=this.userData),this.parameters!==void 0&&this._transformed!==!0){let l=this.parameters;for(let c in l)l[c]!==void 0&&(t[c]=l[c]);return t}t.data={attributes:{}};let e=this.index;e!==null&&(t.data.index={type:e.array.constructor.name,array:Array.prototype.slice.call(e.array)});let n=this.attributes;for(let l in n){let c=n[l];t.data.attributes[l]=c.toJSON(t.data)}let s={},r=!1;for(let l in this.morphAttributes){let c=this.morphAttributes[l],h=[];for(let d=0,u=c.length;d0&&(s[l]=h,r=!0)}r&&(t.data.morphAttributes=s,t.data.morphTargetsRelative=this.morphTargetsRelative);let o=this.groups;o.length>0&&(t.data.groups=JSON.parse(JSON.stringify(o)));let a=this.boundingSphere;return a!==null&&(t.data.boundingSphere=a.toJSON()),t}clone(){return new this.constructor().copy(this)}copy(t){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;let e={};this.name=t.name;let n=t.index;n!==null&&this.setIndex(n.clone());let s=t.attributes;for(let c in s){let h=s[c];this.setAttribute(c,h.clone(e))}let r=t.morphAttributes;for(let c in r){let h=[],d=r[c];for(let u=0,p=d.length;u1)?null:e.copy(t.start).addScaledVector(s,o)}intersectsLine(t){let e=this.distanceToPoint(t.start),n=this.distanceToPoint(t.end);return e<0&&n>0||n<0&&e>0}intersectsBox(t){return t.intersectsPlane(this)}intersectsSphere(t){return t.intersectsPlane(this)}coplanarPoint(t){return t.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(t,e){let n=e||nm.getNormalMatrix(t),s=this.coplanarPoint(Bl).applyMatrix4(t),r=this.normal.applyMatrix3(n).normalize();return this.constant=-s.dot(r),this}translate(t){return this.constant-=t.dot(this.normal),this}equals(t){return t.normal.equals(this.normal)&&t.constant===this.constant}clone(){return new this.constructor().copy(this)}toJSON(){return{normal:this.normal.toArray(),constant:this.constant}}fromJSON(t){return this.normal.fromArray(t.normal),this.constant=t.constant,this}},im=0,Dn=class extends Ln{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:im++}),this.uuid=$n(),this.name="",this.type="Material",this.blending=ys,this.side=Bn,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=ic,this.blendDst=sc,this.blendEquation=Ui,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new Ft(0,0,0),this.blendAlpha=0,this.depthFunc=rs,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=Zu,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=mo,this.stencilZFail=mo,this.stencilZPass=mo,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(t){this._alphaTest>0!=t>0&&this.version++,this._alphaTest=t}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(t){if(t!==void 0)for(let e in t){let n=t[e];if(n===void 0){Dt(`Material: parameter '${e}' has value of undefined.`);continue}let s=this[e];if(s===void 0){Dt(`Material: '${e}' is not a property of THREE.${this.type}.`);continue}s&&s.isColor?s.set(n):s&&s.isVector2&&n&&n.isVector2||s&&s.isEuler&&n&&n.isEuler||s&&s.isVector3&&n&&n.isVector3?s.copy(n):this[e]=n}}toJSON(t){let e=t===void 0||typeof t=="string";e&&(t={textures:{},images:{}});let n={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};n.uuid=this.uuid,n.type=this.type,n.blending=this.blending,n.side=this.side,n.shadowSide=this.shadowSide,n.vertexColors=this.vertexColors,n.opacity=this.opacity,n.transparent=this.transparent,n.blendSrc=this.blendSrc,n.blendDst=this.blendDst,n.blendEquation=this.blendEquation,n.blendSrcAlpha=this.blendSrcAlpha,n.blendDstAlpha=this.blendDstAlpha,n.blendEquationAlpha=this.blendEquationAlpha,n.blendColor=this.blendColor.getHex(),n.blendAlpha=this.blendAlpha,n.depthFunc=this.depthFunc,n.depthTest=this.depthTest,n.depthWrite=this.depthWrite,n.colorWrite=this.colorWrite,n.clipIntersection=this.clipIntersection,n.clipShadows=this.clipShadows,n.stencilWriteMask=this.stencilWriteMask,n.stencilFunc=this.stencilFunc,n.stencilRef=this.stencilRef,n.stencilFuncMask=this.stencilFuncMask,n.stencilFail=this.stencilFail,n.stencilZFail=this.stencilZFail,n.stencilZPass=this.stencilZPass,n.stencilWrite=this.stencilWrite,n.polygonOffset=this.polygonOffset,n.polygonOffsetFactor=this.polygonOffsetFactor,n.polygonOffsetUnits=this.polygonOffsetUnits,n.dithering=this.dithering,n.alphaTest=this.alphaTest,n.alphaHash=this.alphaHash,n.alphaToCoverage=this.alphaToCoverage,n.premultipliedAlpha=this.premultipliedAlpha,n.forceSinglePass=this.forceSinglePass,n.allowOverride=this.allowOverride,n.visible=this.visible,n.toneMapped=this.toneMapped,n.name=this.name,this.color&&this.color.isColor&&(n.color=this.color.getHex()),this.roughness!==void 0&&(n.roughness=this.roughness),this.metalness!==void 0&&(n.metalness=this.metalness),this.sheen!==void 0&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(n.shininess=this.shininess),this.clearcoat!==void 0&&(n.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(t).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(t).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(t).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(n.sheenColorMap=this.sheenColorMap.toJSON(t).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(n.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(t).uuid),this.dispersion!==void 0&&(n.dispersion=this.dispersion),this.retroreflectivity!==void 0&&(n.retroreflectivity=this.retroreflectivity),this.iridescence!==void 0&&(n.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(n.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(t).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(t).uuid),this.anisotropy!==void 0&&(n.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(t).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(t).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(t).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(t).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(t).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(t).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(t).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(t).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(t).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(t).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(t).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(t).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(t).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(t).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(t).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(t).uuid,this.combine!==void 0&&(n.combine=this.combine)),this.envMapRotation!==void 0&&(n.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(n.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(n.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(t).uuid),this.transmission!==void 0&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(t).uuid),this.thickness!==void 0&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(t).uuid),this.attenuationDistance!==void 0&&(n.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(n.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(n.size=this.size),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),Array.isArray(this.clippingPlanes)&&this.clippingPlanes.length>0&&(n.clippingPlanes=this.clippingPlanes.map(r=>r.toJSON())),this.rotation!==void 0&&(n.rotation=this.rotation),this.depthPacking!==void 0&&(n.depthPacking=this.depthPacking),this.linewidth!==void 0&&(n.linewidth=this.linewidth),this.linecap!==void 0&&(n.linecap=this.linecap),this.linejoin!==void 0&&(n.linejoin=this.linejoin),this.dashSize!==void 0&&(n.dashSize=this.dashSize),this.gapSize!==void 0&&(n.gapSize=this.gapSize),this.scale!==void 0&&(n.scale=this.scale),this.wireframe!==void 0&&(n.wireframe=this.wireframe),this.wireframeLinewidth!==void 0&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!==void 0&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!==void 0&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading!==void 0&&(n.flatShading=this.flatShading),this.fog!==void 0&&(n.fog=this.fog),Object.keys(this.userData).length>0&&(n.userData=this.userData);function s(r){let o=[];for(let a in r){let l=r[a];delete l.metadata,o.push(l)}return o}if(e){let r=s(t.textures),o=s(t.images);r.length>0&&(n.textures=r),o.length>0&&(n.images=o)}return n}fromJSON(t,e){if(t.uuid!==void 0&&(this.uuid=t.uuid),t.name!==void 0&&(this.name=t.name),t.color!==void 0&&this.color!==void 0&&this.color.setHex(t.color),t.roughness!==void 0&&(this.roughness=t.roughness),t.metalness!==void 0&&(this.metalness=t.metalness),t.sheen!==void 0&&(this.sheen=t.sheen),t.sheenColor!==void 0&&(this.sheenColor=new Ft().setHex(t.sheenColor)),t.sheenRoughness!==void 0&&(this.sheenRoughness=t.sheenRoughness),t.emissive!==void 0&&this.emissive!==void 0&&this.emissive.setHex(t.emissive),t.specular!==void 0&&this.specular!==void 0&&this.specular.setHex(t.specular),t.specularIntensity!==void 0&&(this.specularIntensity=t.specularIntensity),t.specularColor!==void 0&&this.specularColor!==void 0&&this.specularColor.setHex(t.specularColor),t.shininess!==void 0&&(this.shininess=t.shininess),t.clearcoat!==void 0&&(this.clearcoat=t.clearcoat),t.clearcoatRoughness!==void 0&&(this.clearcoatRoughness=t.clearcoatRoughness),t.dispersion!==void 0&&(this.dispersion=t.dispersion),t.retroreflectivity!==void 0&&(this.retroreflectivity=t.retroreflectivity),t.iridescence!==void 0&&(this.iridescence=t.iridescence),t.iridescenceIOR!==void 0&&(this.iridescenceIOR=t.iridescenceIOR),t.iridescenceThicknessRange!==void 0&&(this.iridescenceThicknessRange=t.iridescenceThicknessRange),t.transmission!==void 0&&(this.transmission=t.transmission),t.thickness!==void 0&&(this.thickness=t.thickness),t.attenuationDistance!==void 0&&(this.attenuationDistance=t.attenuationDistance),t.attenuationColor!==void 0&&this.attenuationColor!==void 0&&this.attenuationColor.setHex(t.attenuationColor),t.anisotropy!==void 0&&(this.anisotropy=t.anisotropy),t.anisotropyRotation!==void 0&&(this.anisotropyRotation=t.anisotropyRotation),t.fog!==void 0&&(this.fog=t.fog),t.flatShading!==void 0&&(this.flatShading=t.flatShading),t.blending!==void 0&&(this.blending=t.blending),t.combine!==void 0&&(this.combine=t.combine),t.side!==void 0&&(this.side=t.side),t.shadowSide!==void 0&&(this.shadowSide=t.shadowSide),t.opacity!==void 0&&(this.opacity=t.opacity),t.transparent!==void 0&&(this.transparent=t.transparent),t.alphaTest!==void 0&&(this.alphaTest=t.alphaTest),t.alphaHash!==void 0&&(this.alphaHash=t.alphaHash),t.depthFunc!==void 0&&(this.depthFunc=t.depthFunc),t.depthTest!==void 0&&(this.depthTest=t.depthTest),t.depthWrite!==void 0&&(this.depthWrite=t.depthWrite),t.colorWrite!==void 0&&(this.colorWrite=t.colorWrite),t.clippingPlanes!==void 0&&(this.clippingPlanes=t.clippingPlanes.map(n=>new _e().fromJSON(n))),t.clipIntersection!==void 0&&(this.clipIntersection=t.clipIntersection),t.clipShadows!==void 0&&(this.clipShadows=t.clipShadows),t.depthPacking!==void 0&&(this.depthPacking=t.depthPacking),t.blendSrc!==void 0&&(this.blendSrc=t.blendSrc),t.blendDst!==void 0&&(this.blendDst=t.blendDst),t.blendEquation!==void 0&&(this.blendEquation=t.blendEquation),t.blendSrcAlpha!==void 0&&(this.blendSrcAlpha=t.blendSrcAlpha),t.blendDstAlpha!==void 0&&(this.blendDstAlpha=t.blendDstAlpha),t.blendEquationAlpha!==void 0&&(this.blendEquationAlpha=t.blendEquationAlpha),t.blendColor!==void 0&&this.blendColor!==void 0&&this.blendColor.setHex(t.blendColor),t.blendAlpha!==void 0&&(this.blendAlpha=t.blendAlpha),t.stencilWriteMask!==void 0&&(this.stencilWriteMask=t.stencilWriteMask),t.stencilFunc!==void 0&&(this.stencilFunc=t.stencilFunc),t.stencilRef!==void 0&&(this.stencilRef=t.stencilRef),t.stencilFuncMask!==void 0&&(this.stencilFuncMask=t.stencilFuncMask),t.stencilFail!==void 0&&(this.stencilFail=t.stencilFail),t.stencilZFail!==void 0&&(this.stencilZFail=t.stencilZFail),t.stencilZPass!==void 0&&(this.stencilZPass=t.stencilZPass),t.stencilWrite!==void 0&&(this.stencilWrite=t.stencilWrite),t.wireframe!==void 0&&(this.wireframe=t.wireframe),t.wireframeLinewidth!==void 0&&(this.wireframeLinewidth=t.wireframeLinewidth),t.wireframeLinecap!==void 0&&(this.wireframeLinecap=t.wireframeLinecap),t.wireframeLinejoin!==void 0&&(this.wireframeLinejoin=t.wireframeLinejoin),t.rotation!==void 0&&(this.rotation=t.rotation),t.linewidth!==void 0&&(this.linewidth=t.linewidth),t.linecap!==void 0&&(this.linecap=t.linecap),t.linejoin!==void 0&&(this.linejoin=t.linejoin),t.dashSize!==void 0&&(this.dashSize=t.dashSize),t.gapSize!==void 0&&(this.gapSize=t.gapSize),t.scale!==void 0&&(this.scale=t.scale),t.polygonOffset!==void 0&&(this.polygonOffset=t.polygonOffset),t.polygonOffsetFactor!==void 0&&(this.polygonOffsetFactor=t.polygonOffsetFactor),t.polygonOffsetUnits!==void 0&&(this.polygonOffsetUnits=t.polygonOffsetUnits),t.dithering!==void 0&&(this.dithering=t.dithering),t.alphaToCoverage!==void 0&&(this.alphaToCoverage=t.alphaToCoverage),t.premultipliedAlpha!==void 0&&(this.premultipliedAlpha=t.premultipliedAlpha),t.forceSinglePass!==void 0&&(this.forceSinglePass=t.forceSinglePass),t.allowOverride!==void 0&&(this.allowOverride=t.allowOverride),t.visible!==void 0&&(this.visible=t.visible),t.toneMapped!==void 0&&(this.toneMapped=t.toneMapped),t.userData!==void 0&&(this.userData=t.userData),t.vertexColors!==void 0&&(typeof t.vertexColors=="number"?this.vertexColors=t.vertexColors>0:this.vertexColors=t.vertexColors),t.size!==void 0&&(this.size=t.size),t.sizeAttenuation!==void 0&&(this.sizeAttenuation=t.sizeAttenuation),t.map!==void 0&&(this.map=e[t.map]||null),t.matcap!==void 0&&(this.matcap=e[t.matcap]||null),t.alphaMap!==void 0&&(this.alphaMap=e[t.alphaMap]||null),t.bumpMap!==void 0&&(this.bumpMap=e[t.bumpMap]||null),t.bumpScale!==void 0&&(this.bumpScale=t.bumpScale),t.normalMap!==void 0&&(this.normalMap=e[t.normalMap]||null),t.normalMapType!==void 0&&(this.normalMapType=t.normalMapType),t.normalScale!==void 0){let n=t.normalScale;Array.isArray(n)===!1&&(n=[n,n]),this.normalScale=new Ht().fromArray(n)}return t.displacementMap!==void 0&&(this.displacementMap=e[t.displacementMap]||null),t.displacementScale!==void 0&&(this.displacementScale=t.displacementScale),t.displacementBias!==void 0&&(this.displacementBias=t.displacementBias),t.roughnessMap!==void 0&&(this.roughnessMap=e[t.roughnessMap]||null),t.metalnessMap!==void 0&&(this.metalnessMap=e[t.metalnessMap]||null),t.emissiveMap!==void 0&&(this.emissiveMap=e[t.emissiveMap]||null),t.emissiveIntensity!==void 0&&(this.emissiveIntensity=t.emissiveIntensity),t.specularMap!==void 0&&(this.specularMap=e[t.specularMap]||null),t.specularIntensityMap!==void 0&&(this.specularIntensityMap=e[t.specularIntensityMap]||null),t.specularColorMap!==void 0&&(this.specularColorMap=e[t.specularColorMap]||null),t.envMap!==void 0&&(this.envMap=e[t.envMap]||null),t.envMapRotation!==void 0&&this.envMapRotation.fromArray(t.envMapRotation),t.envMapIntensity!==void 0&&(this.envMapIntensity=t.envMapIntensity),t.reflectivity!==void 0&&(this.reflectivity=t.reflectivity),t.refractionRatio!==void 0&&(this.refractionRatio=t.refractionRatio),t.lightMap!==void 0&&(this.lightMap=e[t.lightMap]||null),t.lightMapIntensity!==void 0&&(this.lightMapIntensity=t.lightMapIntensity),t.aoMap!==void 0&&(this.aoMap=e[t.aoMap]||null),t.aoMapIntensity!==void 0&&(this.aoMapIntensity=t.aoMapIntensity),t.gradientMap!==void 0&&(this.gradientMap=e[t.gradientMap]||null),t.clearcoatMap!==void 0&&(this.clearcoatMap=e[t.clearcoatMap]||null),t.clearcoatRoughnessMap!==void 0&&(this.clearcoatRoughnessMap=e[t.clearcoatRoughnessMap]||null),t.clearcoatNormalMap!==void 0&&(this.clearcoatNormalMap=e[t.clearcoatNormalMap]||null),t.clearcoatNormalScale!==void 0&&(this.clearcoatNormalScale=new Ht().fromArray(t.clearcoatNormalScale)),t.iridescenceMap!==void 0&&(this.iridescenceMap=e[t.iridescenceMap]||null),t.iridescenceThicknessMap!==void 0&&(this.iridescenceThicknessMap=e[t.iridescenceThicknessMap]||null),t.transmissionMap!==void 0&&(this.transmissionMap=e[t.transmissionMap]||null),t.thicknessMap!==void 0&&(this.thicknessMap=e[t.thicknessMap]||null),t.anisotropyMap!==void 0&&(this.anisotropyMap=e[t.anisotropyMap]||null),t.sheenColorMap!==void 0&&(this.sheenColorMap=e[t.sheenColorMap]||null),t.sheenRoughnessMap!==void 0&&(this.sheenRoughnessMap=e[t.sheenRoughnessMap]||null),this}clone(){return new this.constructor().copy(this)}copy(t){this.name=t.name,this.blending=t.blending,this.side=t.side,this.vertexColors=t.vertexColors,this.opacity=t.opacity,this.transparent=t.transparent,this.blendSrc=t.blendSrc,this.blendDst=t.blendDst,this.blendEquation=t.blendEquation,this.blendSrcAlpha=t.blendSrcAlpha,this.blendDstAlpha=t.blendDstAlpha,this.blendEquationAlpha=t.blendEquationAlpha,this.blendColor.copy(t.blendColor),this.blendAlpha=t.blendAlpha,this.depthFunc=t.depthFunc,this.depthTest=t.depthTest,this.depthWrite=t.depthWrite,this.stencilWriteMask=t.stencilWriteMask,this.stencilFunc=t.stencilFunc,this.stencilRef=t.stencilRef,this.stencilFuncMask=t.stencilFuncMask,this.stencilFail=t.stencilFail,this.stencilZFail=t.stencilZFail,this.stencilZPass=t.stencilZPass,this.stencilWrite=t.stencilWrite;let e=t.clippingPlanes,n=null;if(e!==null){let s=e.length;n=new Array(s);for(let r=0;r!==s;++r)n[r]=e[r].clone()}return this.clippingPlanes=n,this.clipIntersection=t.clipIntersection,this.clipShadows=t.clipShadows,this.shadowSide=t.shadowSide,this.colorWrite=t.colorWrite,this.precision=t.precision,this.polygonOffset=t.polygonOffset,this.polygonOffsetFactor=t.polygonOffsetFactor,this.polygonOffsetUnits=t.polygonOffsetUnits,this.dithering=t.dithering,this.alphaTest=t.alphaTest,this.alphaHash=t.alphaHash,this.alphaToCoverage=t.alphaToCoverage,this.premultipliedAlpha=t.premultipliedAlpha,this.forceSinglePass=t.forceSinglePass,this.allowOverride=t.allowOverride,this.visible=t.visible,this.toneMapped=t.toneMapped,this.userData=JSON.parse(JSON.stringify(t.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(t){t===!0&&this.version++}};var qn=new I,Ol=new I,Yr=new I,$r=new I,Ci=class{constructor(t=new I,e=new I(0,0,-1)){this.origin=t,this.direction=e}set(t,e){return this.origin.copy(t),this.direction.copy(e),this}copy(t){return this.origin.copy(t.origin),this.direction.copy(t.direction),this}at(t,e){return e.copy(this.origin).addScaledVector(this.direction,t)}lookAt(t){return this.direction.copy(t).sub(this.origin).normalize(),this}recast(t){return this.origin.copy(this.at(t,qn)),this}closestPointToPoint(t,e){e.subVectors(t,this.origin);let n=e.dot(this.direction);return n<0?e.copy(this.origin):e.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(t){return Math.sqrt(this.distanceSqToPoint(t))}distanceSqToPoint(t){let e=qn.subVectors(t,this.origin).dot(this.direction);return e<0?this.origin.distanceToSquared(t):(qn.copy(this.origin).addScaledVector(this.direction,e),qn.distanceToSquared(t))}distanceSqToSegment(t,e,n,s){Ol.copy(t).add(e).multiplyScalar(.5),Yr.copy(e).sub(t).normalize(),$r.copy(this.origin).sub(Ol);let r=t.distanceTo(e)*.5,o=-this.direction.dot(Yr),a=$r.dot(this.direction),l=-$r.dot(Yr),c=$r.lengthSq(),h=Math.abs(1-o*o),d,u,p,g;if(h>0)if(d=o*l-a,u=o*a-l,g=r*h,d>=0)if(u>=-g)if(u<=g){let _=1/h;d*=_,u*=_,p=d*(d+o*u+2*a)+u*(o*d+u+2*l)+c}else u=r,d=Math.max(0,-(o*u+a)),p=-d*d+u*(u+2*l)+c;else u=-r,d=Math.max(0,-(o*u+a)),p=-d*d+u*(u+2*l)+c;else u<=-g?(d=Math.max(0,-(-o*r+a)),u=d>0?-r:Math.min(Math.max(-r,-l),r),p=-d*d+u*(u+2*l)+c):u<=g?(d=0,u=Math.min(Math.max(-r,-l),r),p=u*(u+2*l)+c):(d=Math.max(0,-(o*r+a)),u=d>0?r:Math.min(Math.max(-r,-l),r),p=-d*d+u*(u+2*l)+c);else u=o>0?-r:r,d=Math.max(0,-(o*u+a)),p=-d*d+u*(u+2*l)+c;return n&&n.copy(this.origin).addScaledVector(this.direction,d),s&&s.copy(Ol).addScaledVector(Yr,u),p}intersectSphere(t,e){if(t.radius<0)return null;qn.subVectors(t.center,this.origin);let n=qn.dot(this.direction),s=qn.dot(qn)-n*n,r=t.radius*t.radius;if(s>r)return null;let o=Math.sqrt(r-s),a=n-o,l=n+o;return l<0?null:a<0?this.at(l,e):this.at(a,e)}intersectsSphere(t){return t.radius<0?!1:this.distanceSqToPoint(t.center)<=t.radius*t.radius}distanceToPlane(t){let e=t.normal.dot(this.direction);if(e===0)return t.distanceToPoint(this.origin)===0?0:null;let n=-(this.origin.dot(t.normal)+t.constant)/e;return n>=0?n:null}intersectPlane(t,e){let n=this.distanceToPlane(t);return n===null?null:this.at(n,e)}intersectsPlane(t){let e=t.distanceToPoint(this.origin);return e===0||t.normal.dot(this.direction)*e<0}intersectBox(t,e){let n,s,r,o,a,l,c=1/this.direction.x,h=1/this.direction.y,d=1/this.direction.z,u=this.origin;return c>=0?(n=(t.min.x-u.x)*c,s=(t.max.x-u.x)*c):(n=(t.max.x-u.x)*c,s=(t.min.x-u.x)*c),h>=0?(r=(t.min.y-u.y)*h,o=(t.max.y-u.y)*h):(r=(t.max.y-u.y)*h,o=(t.min.y-u.y)*h),n>o||r>s||((r>n||isNaN(n))&&(n=r),(o=0?(a=(t.min.z-u.z)*d,l=(t.max.z-u.z)*d):(a=(t.max.z-u.z)*d,l=(t.min.z-u.z)*d),n>l||a>s)||((a>n||n!==n)&&(n=a),(l=0?n:s,e)}intersectsBox(t){return this.intersectBox(t,qn)!==null}intersectTriangle(t,e,n,s,r){let o=this.origin,a=this.direction,l=a.x,c=a.y,h=a.z,d=t.x-o.x,u=t.y-o.y,p=t.z-o.z,g=e.x-o.x,_=e.y-o.y,m=e.z-o.z,f=n.x-o.x,b=n.y-o.y,E=n.z-o.z,M=Math.abs(l),v=Math.abs(c),S=Math.abs(h),A,x,T,R,L,N,U,C,B,z,W,F;if(M>=v&&M>=S?(T=l,N=d,B=g,F=f,l>=0?(A=c,x=h,R=u,L=p,U=_,C=m,z=b,W=E):(A=h,x=c,R=p,L=u,U=m,C=_,z=E,W=b)):v>=S?(T=c,N=u,B=_,F=b,c>=0?(A=h,x=l,R=p,L=d,U=m,C=g,z=E,W=f):(A=l,x=h,R=d,L=p,U=g,C=m,z=f,W=E)):(T=h,N=p,B=m,F=E,h>=0?(A=l,x=c,R=d,L=u,U=g,C=_,z=f,W=b):(A=c,x=l,R=u,L=d,U=_,C=g,z=b,W=f)),T===0)return null;let D=A/T,X=x/T,Z=1/T,G=R-D*N,Q=L-X*N,lt=U-D*B,ct=C-X*B,et=z-D*F,V=W-X*F,j=et*ct-V*lt,ut=G*V-Q*et,Lt=lt*Q-ct*G;if(s){if(j<0||ut<0||Lt<0)return null}else if((j<0||ut<0||Lt<0)&&(j>0||ut>0||Lt>0))return null;let Mt=j+ut+Lt;if(Mt===0)return null;let Bt=Z*(j*N+ut*B+Lt*F);return(Mt>0?Bt<0:Bt>0)?null:this.at(Bt/Mt,r)}applyMatrix4(t){return this.origin.applyMatrix4(t),this.direction.transformDirection(t),this}equals(t){return t.origin.equals(this.origin)&&t.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}},en=class extends Dn{constructor(t){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Ft(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Jn,this.combine=Zo,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapRotation.copy(t.envMapRotation),this.combine=t.combine,this.reflectivity=t.reflectivity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.fog=t.fog,this}},su=new kt,Ei=new Ci,Zr=new Oe,ru=new I,Jr=new I,Kr=new I,jr=new I,zl=new I,Qr=new I,ou=new I,to=new I,xe=class extends Be{constructor(t=new le,e=new en){super(),this.isMesh=!0,this.type="Mesh",this.geometry=t,this.material=e,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(t,e){return super.copy(t,e),t.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=t.morphTargetInfluences.slice()),t.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},t.morphTargetDictionary)),this.material=Array.isArray(t.material)?t.material.slice():t.material,this.geometry=t.geometry,this}updateMorphTargets(){let e=this.geometry.morphAttributes,n=Object.keys(e);if(n.length>0){let s=e[n[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,o=s.length;r(t.far-t.near)**2))&&(su.copy(r).invert(),Ei.copy(t.ray).applyMatrix4(su),!(n.boundingBox!==null&&Ei.intersectsBox(n.boundingBox)===!1)&&this._computeIntersections(t,e,Ei)))}_computeIntersections(t,e,n){let s,r=this.geometry,o=this.material,a=r.index,l=r.attributes.position,c=r.attributes.uv,h=r.attributes.uv1,d=r.attributes.normal,u=r.groups,p=r.drawRange;if(a!==null)if(Array.isArray(o))for(let g=0,_=u.length;g<_;g++){let m=u[g],f=o[m.materialIndex],b=Math.max(m.start,p.start),E=Math.min(a.count,Math.min(m.start+m.count,p.start+p.count));for(let M=b,v=E;Me.far?null:{distance:c,point:to.clone(),object:i}}function eo(i,t,e,n,s,r,o,a,l,c){i.getVertexPosition(a,Jr),i.getVertexPosition(l,Kr),i.getVertexPosition(c,jr);let h=sm(i,t,e,n,Jr,Kr,jr,ou);if(h){let d=new I;Yn.getBarycoord(ou,Jr,Kr,jr,d),s&&(h.uv=Yn.getInterpolatedAttribute(s,a,l,c,d,new Ht)),r&&(h.uv1=Yn.getInterpolatedAttribute(r,a,l,c,d,new Ht)),o&&(h.normal=Yn.getInterpolatedAttribute(o,a,l,c,d,new I),h.normal.dot(n.direction)>0&&h.normal.multiplyScalar(-1));let u={a,b:l,c,normal:new I,materialIndex:0};Yn.getNormal(Jr,Kr,jr,u.normal),h.face=u,h.barycoord=d}return h}var Nn=class extends ke{constructor(t=null,e=1,n=1,s,r,o,a,l,c=Ue,h=Ue,d,u){super(null,o,a,l,c,h,s,r,d,u),this.isDataTexture=!0,this.image={data:t,width:e,height:n},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}};var Kn=class extends Se{constructor(t,e,n,s=1){super(t,e,n),this.isInstancedBufferAttribute=!0,this.meshPerAttribute=s}copy(t){return super.copy(t),this.meshPerAttribute=t.meshPerAttribute,this}toJSON(){let t=super.toJSON();return t.meshPerAttribute=this.meshPerAttribute,t.isInstancedBufferAttribute=!0,t}},Qi=new kt,au=new kt,no=[],lu=new ie,rm=new kt,ks=new xe,Hs=new Oe,ps=class extends xe{constructor(t,e,n){super(t,e),this.isInstancedMesh=!0,this.instanceMatrix=new Kn(new Float32Array(n*16),16),this.instanceColor=null,this.morphTexture=null,this.count=n,this.boundingBox=null,this.boundingSphere=null;for(let s=0;s0?t.max.x:t.min.x,io.y=s.normal.y>0?t.max.y:t.min.y,io.z=s.normal.z>0?t.max.z:t.min.z,s.distanceToPoint(io)<0)return!1}return!0}containsPoint(t){let e=this.planes;for(let n=0;n<6;n++)if(e[n].distanceToPoint(t)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}};var an=class extends Dn{constructor(t){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new Ft(16777215),this.map=null,this.linewidth=1,this.linecap="round",this.linejoin="round",this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.linewidth=t.linewidth,this.linecap=t.linecap,this.linejoin=t.linejoin,this.fog=t.fog,this}},Co=new I,Io=new I,cu=new kt,Vs=new Ci,so=new Oe,kl=new I,hu=new I,Ii=class extends Be{constructor(t=new le,e=new an){super(),this.isLine=!0,this.type="Line",this.geometry=t,this.material=e,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(t,e){return super.copy(t,e),this.material=Array.isArray(t.material)?t.material.slice():t.material,this.geometry=t.geometry,this}computeLineDistances(){let t=this.geometry;if(t.index===null){let e=t.attributes.position,n=[0];for(let s=1,r=e.count;s0){let s=e[n[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,o=s.length;rn)return;kl.applyMatrix4(i.matrixWorld);let c=t.ray.origin.distanceTo(kl);if(!(ct.far))return{distance:c,point:hu.clone().applyMatrix4(i.matrixWorld),index:o,face:null,faceIndex:null,barycoord:null,object:i}}var uu=new I,du=new I,vn=class extends Ii{constructor(t,e){super(t,e),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){let t=this.geometry;if(t.index===null){let e=t.attributes.position,n=[];for(let s=0,r=e.count;s0){let s=e[n[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,o=s.length;rs.far)return;r.push({distance:c,distanceToRay:Math.sqrt(a),point:l,index:t,face:null,faceIndex:null,barycoord:null,object:o})}}var Qs=class extends ke{constructor(t=[],e=pi,n,s,r,o,a,l,c,h){super(t,e,n,s,r,o,a,l,c,h),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(t){this.image=t}},tr=class extends ke{constructor(t,e,n,s,r,o,a,l,c){super(t,e,n,s,r,o,a,l,c),this.isCanvasTexture=!0,this.needsUpdate=!0}};var hi=class extends ke{constructor(t,e,n=bn,s,r,o,a=Ue,l=Ue,c,h=Pn,d=1){if(h!==Pn&&h!==gi)throw new Error("THREE.DepthTexture: format must be either THREE.DepthFormat or THREE.DepthStencilFormat");let u={width:t,height:e,depth:d};super(u,s,r,o,a,l,h,n,c),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(t){return super.copy(t),this.source=new hs(Object.assign({},t.image)),this.compareFunction=t.compareFunction,this}toJSON(t){let e=super.toJSON(t);return e.compareFunction=this.compareFunction,e}},Po=class extends hi{constructor(t,e=bn,n=pi,s,r,o=Ue,a=Ue,l,c=Pn){let h={width:t,height:t,depth:1},d=[h,h,h,h,h,h];super(t,t,e,n,s,r,o,a,l,c),this.image=d,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(t){this.image=t}},er=class extends ke{constructor(t=null){super(),this.sourceTexture=t,this.isExternalTexture=!0}copy(t){return super.copy(t),this.sourceTexture=t.sourceTexture,this}},dn=class i extends le{constructor(t=1,e=1,n=1,s=1,r=1,o=1){super(),this.type="BoxGeometry",this.parameters={width:t,height:e,depth:n,widthSegments:s,heightSegments:r,depthSegments:o};let a=this;s=Math.floor(s),r=Math.floor(r),o=Math.floor(o);let l=[],c=[],h=[],d=[],u=0,p=0;g("z","y","x",-1,-1,n,e,t,o,r,0),g("z","y","x",1,-1,n,e,-t,o,r,1),g("x","z","y",1,1,t,n,e,s,o,2),g("x","z","y",1,-1,t,n,-e,s,o,3),g("x","y","z",1,-1,t,e,n,s,r,4),g("x","y","z",-1,-1,t,e,-n,s,r,5),this.setIndex(l),this.setAttribute("position",new fe(c,3)),this.setAttribute("normal",new fe(h,3)),this.setAttribute("uv",new fe(d,2));function g(_,m,f,b,E,M,v,S,A,x,T){let R=M/A,L=v/x,N=M/2,U=v/2,C=S/2,B=A+1,z=x+1,W=0,F=0,D=new I;for(let X=0;X0?1:-1,h.push(D.x,D.y,D.z),d.push(G/A),d.push(1-X/x),W+=1}}for(let X=0;X0&&E(!0),e>0&&E(!1)),this.setIndex(h),this.setAttribute("position",new fe(d,3)),this.setAttribute("normal",new fe(u,3)),this.setAttribute("uv",new fe(p,2));function b(){let M=new I,v=new I,S=0,A=(e-t)/n;for(let x=0;x<=r;x++){let T=[],R=x/r,L=R*(e-t)+t;for(let N=0;N<=s;N++){let U=N/s,C=U*l+a,B=Math.sin(C),z=Math.cos(C);v.x=L*B,v.y=-R*n+m,v.z=L*z,d.push(v.x,v.y,v.z),M.set(B,A,z).normalize(),u.push(M.x,M.y,M.z),p.push(U,1-R),T.push(g++)}_.push(T)}for(let x=0;x0||T!==0)&&(h.push(R,L,U),S+=3),(e>0||T!==r-1)&&(h.push(L,N,U),S+=3)}c.addGroup(f,S,0),f+=S}function E(M){let v=g,S=new Ht,A=new I,x=0,T=M===!0?t:e,R=M===!0?1:-1;for(let N=1;N<=s;N++)d.push(0,m*R,0),u.push(0,R,0),p.push(.5,.5),g++;let L=g;for(let N=0;N<=s;N++){let C=N/s*l+a,B=Math.cos(C),z=Math.sin(C);A.x=T*z,A.y=m*R,A.z=T*B,d.push(A.x,A.y,A.z),u.push(0,R,0),S.x=B*.5+.5,S.y=z*.5*R+.5,p.push(S.x,S.y),g++}for(let N=0;N0)&&p.push(E,M,S),(f!==n-1||l0&&(e.defines=this.defines),e.vertexShader=this.vertexShader,e.fragmentShader=this.fragmentShader,e.lights=this.lights,e.clipping=this.clipping;let n={};for(let s in this.extensions)this.extensions[s]===!0&&(n[s]=!0);return Object.keys(n).length>0&&(e.extensions=n),e}fromJSON(t,e){if(super.fromJSON(t,e),t.uniforms!==void 0)for(let n in t.uniforms){let s=t.uniforms[n];switch(this.uniforms[n]={},s.type){case"t":this.uniforms[n].value=e[s.value]||null;break;case"c":this.uniforms[n].value=new Ft().setHex(s.value);break;case"v2":this.uniforms[n].value=new Ht().fromArray(s.value);break;case"v3":this.uniforms[n].value=new I().fromArray(s.value);break;case"v4":this.uniforms[n].value=new oe().fromArray(s.value);break;case"m3":this.uniforms[n].value=new Ot().fromArray(s.value);break;case"m4":this.uniforms[n].value=new kt().fromArray(s.value);break;default:this.uniforms[n].value=s.value}}if(t.defines!==void 0&&(this.defines=t.defines),t.vertexShader!==void 0&&(this.vertexShader=t.vertexShader),t.fragmentShader!==void 0&&(this.fragmentShader=t.fragmentShader),t.glslVersion!==void 0&&(this.glslVersion=t.glslVersion),t.extensions!==void 0)for(let n in t.extensions)this.extensions[n]=t.extensions[n];return t.lights!==void 0&&(this.lights=t.lights),t.clipping!==void 0&&(this.clipping=t.clipping),this}},Lo=class extends He{constructor(t){super(t),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}};var _s=class extends Dn{constructor(t){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new Ft(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Ft(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Ua,this.normalScale=new Ht(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Jn,this.combine=Zo,this.reflectivity=1,this.envMapIntensity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive.copy(t.emissive),this.emissiveMap=t.emissiveMap,this.emissiveIntensity=t.emissiveIntensity,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapRotation.copy(t.envMapRotation),this.combine=t.combine,this.reflectivity=t.reflectivity,this.envMapIntensity=t.envMapIntensity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.flatShading=t.flatShading,this.fog=t.fog,this}},Do=class extends Dn{constructor(t){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=qu,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(t)}copy(t){return super.copy(t),this.depthPacking=t.depthPacking,this.map=t.map,this.alphaMap=t.alphaMap,this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this}},No=class extends Dn{constructor(t){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(t)}copy(t){return super.copy(t),this.map=t.map,this.alphaMap=t.alphaMap,this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this}};function ts(i,t){return!i||i.constructor===t?i:typeof t.BYTES_PER_ELEMENT=="number"?new t(i):Array.prototype.slice.call(i)}function Vl(i){return i!==void 0&&i.inTangents!==void 0&&i.outTangents!==void 0}var ui=class{constructor(t,e,n,s){this.parameterPositions=t,this._cachedIndex=0,this.resultBuffer=s!==void 0?s:new e.constructor(n),this.sampleValues=e,this.valueSize=n,this.settings=null,this.DefaultSettings_={}}evaluate(t){let e=this.parameterPositions,n=this._cachedIndex,s=e[n],r=e[n-1];n:{t:{let o;e:{i:if(!(t=r)){let a=e[1];t=r)break t}o=n,n=0;break e}break n}for(;n>>1;te;)--o;if(++o,r!==0||o!==s){r>=o&&(o=Math.max(o,1),r=o-1);let a=this.getValueSize();this.times=n.slice(r,o),this.values=this.values.slice(r*a,o*a)}return this}validate(){let t=!0,e=this.getValueSize();e-Math.floor(e)!==0&&(Ut("KeyframeTrack: Invalid value size in track.",this),t=!1);let n=this.times,s=this.values,r=n.length;r===0&&(Ut("KeyframeTrack: Track is empty.",this),t=!1);let o=null;for(let a=0;a!==r;a++){let l=n[a];if(typeof l=="number"&&isNaN(l)){Ut("KeyframeTrack: Time is not a valid number.",this,a,l),t=!1;break}if(o!==null&&o>l){Ut("KeyframeTrack: Out of order keys.",this,a,l,o),t=!1;break}o=l}if(s!==void 0&&Sp(s))for(let a=0,l=s.length;a!==l;++a){let c=s[a];if(isNaN(c)){Ut("KeyframeTrack: Value is not a valid number.",this,a,c),t=!1;break}}return t}optimize(){let t=this.times.slice(),e=this.values.slice(),n=this.getValueSize(),s=this.getInterpolation()===po,r=t.length-1,o=1;for(let a=1;a0){t[o]=t[r];for(let a=r*n,l=o*n,c=0;c!==n;++c)e[l+c]=e[a+c];++o}return o!==t.length?(this.times=t.slice(0,o),this.values=e.slice(0,o*n)):(this.times=t,this.values=e),this}clone(){let t=this.times.slice(),e=this.values.slice(),n=this.constructor,s=new n(this.name,t,e);return s.createInterpolant=this.createInterpolant,Vl(this.settings)&&(s.settings={inTangents:this.settings.inTangents.slice(),outTangents:this.settings.outTangents.slice()}),s}};function mu(i,t){for(let e=0,n=i.length;e!==n;e+=2)i[e]*=t}ln.prototype.ValueTypeName="";ln.prototype.TimeBufferType=Float32Array;ln.prototype.ValueBufferType=Float32Array;ln.prototype.DefaultInterpolation=wo;var di=class extends ln{constructor(t,e,n){super(t,e,n)}};di.prototype.ValueTypeName="bool";di.prototype.ValueBufferType=Array;di.prototype.DefaultInterpolation=Gs;di.prototype.InterpolantFactoryMethodLinear=void 0;di.prototype.InterpolantFactoryMethodSmooth=void 0;var zo=class extends ln{constructor(t,e,n,s){super(t,e,n,s)}};zo.prototype.ValueTypeName="color";var ko=class extends ln{constructor(t,e,n,s){super(t,e,n,s)}};ko.prototype.ValueTypeName="number";var Ho=class extends ui{constructor(t,e,n,s){super(t,e,n,s)}interpolate_(t,e,n,s){let r=this.resultBuffer,o=this.sampleValues,a=this.valueSize,l=(n-e)/(s-e),c=t*a;for(let h=c+a;c!==h;c+=4)Ce.slerpFlat(r,0,o,c-a,o,c,l);return r}},nr=class extends ln{constructor(t,e,n,s){super(t,e,n,s)}InterpolantFactoryMethodLinear(t){return new Ho(this.times,this.values,this.getValueSize(),t)}};nr.prototype.ValueTypeName="quaternion";nr.prototype.InterpolantFactoryMethodSmooth=void 0;var fi=class extends ln{constructor(t,e,n){super(t,e,n)}};fi.prototype.ValueTypeName="string";fi.prototype.ValueBufferType=Array;fi.prototype.DefaultInterpolation=Gs;fi.prototype.InterpolantFactoryMethodLinear=void 0;fi.prototype.InterpolantFactoryMethodSmooth=void 0;var Vo=class extends ln{constructor(t,e,n,s){super(t,e,n,s)}};Vo.prototype.ValueTypeName="vector";var Go=class{constructor(t,e,n){let s=this,r=!1,o=0,a=0,l,c=[];this.onStart=void 0,this.onLoad=t,this.onProgress=e,this.onError=n,this._abortController=null,this.itemStart=function(h){a++,r===!1&&s.onStart!==void 0&&s.onStart(h,o,a),r=!0},this.itemEnd=function(h){o++,s.onProgress!==void 0&&s.onProgress(h,o,a),o===a&&(r=!1,s.onLoad!==void 0&&s.onLoad())},this.itemError=function(h){s.onError!==void 0&&s.onError(h)},this.resolveURL=function(h){return h=h.normalize("NFC"),l?l(h):h},this.setURLModifier=function(h){return l=h,this},this.addHandler=function(h,d){return c.push(h,d),this},this.removeHandler=function(h){let d=c.indexOf(h);return d!==-1&&c.splice(d,2),this},this.getHandler=function(h){for(let d=0,u=c.length;dp.start-g.start);let u=0;for(let p=1;p0&&(e.defines=this.defines),e.vertexShader=this.vertexShader,e.fragmentShader=this.fragmentShader,e.lights=this.lights,e.clipping=this.clipping;let n={};for(let s in this.extensions)this.extensions[s]===!0&&(n[s]=!0);return Object.keys(n).length>0&&(e.extensions=n),e}fromJSON(t,e){if(super.fromJSON(t,e),t.uniforms!==void 0)for(let n in t.uniforms){let s=t.uniforms[n];switch(this.uniforms[n]={},s.type){case"t":this.uniforms[n].value=e[s.value]||null;break;case"c":this.uniforms[n].value=new Ft().setHex(s.value);break;case"v2":this.uniforms[n].value=new Ht().fromArray(s.value);break;case"v3":this.uniforms[n].value=new I().fromArray(s.value);break;case"v4":this.uniforms[n].value=new ae().fromArray(s.value);break;case"m3":this.uniforms[n].value=new Ot().fromArray(s.value);break;case"m4":this.uniforms[n].value=new kt().fromArray(s.value);break;default:this.uniforms[n].value=s.value}}if(t.defines!==void 0&&(this.defines=t.defines),t.vertexShader!==void 0&&(this.vertexShader=t.vertexShader),t.fragmentShader!==void 0&&(this.fragmentShader=t.fragmentShader),t.glslVersion!==void 0&&(this.glslVersion=t.glslVersion),t.extensions!==void 0)for(let n in t.extensions)this.extensions[n]=t.extensions[n];return t.lights!==void 0&&(this.lights=t.lights),t.clipping!==void 0&&(this.clipping=t.clipping),this}},Lo=class extends He{constructor(t){super(t),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}};var _s=class extends Dn{constructor(t){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new Ft(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Ft(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Ua,this.normalScale=new Ht(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Jn,this.combine=Zo,this.reflectivity=1,this.envMapIntensity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive.copy(t.emissive),this.emissiveMap=t.emissiveMap,this.emissiveIntensity=t.emissiveIntensity,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapRotation.copy(t.envMapRotation),this.combine=t.combine,this.reflectivity=t.reflectivity,this.envMapIntensity=t.envMapIntensity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.flatShading=t.flatShading,this.fog=t.fog,this}},Do=class extends Dn{constructor(t){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=Yu,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(t)}copy(t){return super.copy(t),this.depthPacking=t.depthPacking,this.map=t.map,this.alphaMap=t.alphaMap,this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this}},No=class extends Dn{constructor(t){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(t)}copy(t){return super.copy(t),this.map=t.map,this.alphaMap=t.alphaMap,this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this}};function ts(i,t){return!i||i.constructor===t?i:typeof t.BYTES_PER_ELEMENT=="number"?new t(i):Array.prototype.slice.call(i)}function Vl(i){return i!==void 0&&i.inTangents!==void 0&&i.outTangents!==void 0}var ui=class{constructor(t,e,n,s){this.parameterPositions=t,this._cachedIndex=0,this.resultBuffer=s!==void 0?s:new e.constructor(n),this.sampleValues=e,this.valueSize=n,this.settings=null,this.DefaultSettings_={}}evaluate(t){let e=this.parameterPositions,n=this._cachedIndex,s=e[n],r=e[n-1];n:{t:{let o;e:{i:if(!(t=r)){let a=e[1];t=r)break t}o=n,n=0;break e}break n}for(;n>>1;te;)--o;if(++o,r!==0||o!==s){r>=o&&(o=Math.max(o,1),r=o-1);let a=this.getValueSize();this.times=n.slice(r,o),this.values=this.values.slice(r*a,o*a)}return this}validate(){let t=!0,e=this.getValueSize();e-Math.floor(e)!==0&&(Ut("KeyframeTrack: Invalid value size in track.",this),t=!1);let n=this.times,s=this.values,r=n.length;r===0&&(Ut("KeyframeTrack: Track is empty.",this),t=!1);let o=null;for(let a=0;a!==r;a++){let l=n[a];if(typeof l=="number"&&isNaN(l)){Ut("KeyframeTrack: Time is not a valid number.",this,a,l),t=!1;break}if(o!==null&&o>l){Ut("KeyframeTrack: Out of order keys.",this,a,l,o),t=!1;break}o=l}if(s!==void 0&&Ep(s))for(let a=0,l=s.length;a!==l;++a){let c=s[a];if(isNaN(c)){Ut("KeyframeTrack: Value is not a valid number.",this,a,c),t=!1;break}}return t}optimize(){let t=this.times.slice(),e=this.values.slice(),n=this.getValueSize(),s=this.getInterpolation()===po,r=t.length-1,o=1;for(let a=1;a0){t[o]=t[r];for(let a=r*n,l=o*n,c=0;c!==n;++c)e[l+c]=e[a+c];++o}return o!==t.length?(this.times=t.slice(0,o),this.values=e.slice(0,o*n)):(this.times=t,this.values=e),this}clone(){let t=this.times.slice(),e=this.values.slice(),n=this.constructor,s=new n(this.name,t,e);return s.createInterpolant=this.createInterpolant,Vl(this.settings)&&(s.settings={inTangents:this.settings.inTangents.slice(),outTangents:this.settings.outTangents.slice()}),s}};function gu(i,t){for(let e=0,n=i.length;e!==n;e+=2)i[e]*=t}ln.prototype.ValueTypeName="";ln.prototype.TimeBufferType=Float32Array;ln.prototype.ValueBufferType=Float32Array;ln.prototype.DefaultInterpolation=wo;var di=class extends ln{constructor(t,e,n){super(t,e,n)}};di.prototype.ValueTypeName="bool";di.prototype.ValueBufferType=Array;di.prototype.DefaultInterpolation=Ws;di.prototype.InterpolantFactoryMethodLinear=void 0;di.prototype.InterpolantFactoryMethodSmooth=void 0;var zo=class extends ln{constructor(t,e,n,s){super(t,e,n,s)}};zo.prototype.ValueTypeName="color";var ko=class extends ln{constructor(t,e,n,s){super(t,e,n,s)}};ko.prototype.ValueTypeName="number";var Ho=class extends ui{constructor(t,e,n,s){super(t,e,n,s)}interpolate_(t,e,n,s){let r=this.resultBuffer,o=this.sampleValues,a=this.valueSize,l=(n-e)/(s-e),c=t*a;for(let h=c+a;c!==h;c+=4)Ce.slerpFlat(r,0,o,c-a,o,c,l);return r}},ir=class extends ln{constructor(t,e,n,s){super(t,e,n,s)}InterpolantFactoryMethodLinear(t){return new Ho(this.times,this.values,this.getValueSize(),t)}};ir.prototype.ValueTypeName="quaternion";ir.prototype.InterpolantFactoryMethodSmooth=void 0;var fi=class extends ln{constructor(t,e,n){super(t,e,n)}};fi.prototype.ValueTypeName="string";fi.prototype.ValueBufferType=Array;fi.prototype.DefaultInterpolation=Ws;fi.prototype.InterpolantFactoryMethodLinear=void 0;fi.prototype.InterpolantFactoryMethodSmooth=void 0;var Vo=class extends ln{constructor(t,e,n,s){super(t,e,n,s)}};Vo.prototype.ValueTypeName="vector";var Go=class{constructor(t,e,n){let s=this,r=!1,o=0,a=0,l,c=[];this.onStart=void 0,this.onLoad=t,this.onProgress=e,this.onError=n,this._abortController=null,this.itemStart=function(h){a++,r===!1&&s.onStart!==void 0&&s.onStart(h,o,a),r=!0},this.itemEnd=function(h){o++,s.onProgress!==void 0&&s.onProgress(h,o,a),o===a&&(r=!1,s.onLoad!==void 0&&s.onLoad())},this.itemError=function(h){s.onError!==void 0&&s.onError(h)},this.resolveURL=function(h){return h=h.normalize("NFC"),l?l(h):h},this.setURLModifier=function(h){return l=h,this},this.addHandler=function(h,d){return c.push(h,d),this},this.removeHandler=function(h){let d=c.indexOf(h);return d!==-1&&c.splice(d,2),this},this.getHandler=function(h){for(let d=0,u=c.length;dp.start-g.start);let u=0;for(let p=1;p 0 +#endif`,Om=`#if NUM_CLIPPING_PLANES > 0 vec4 plane; #ifdef ALPHA_TO_COVERAGE float distanceToPlane, distanceGradient; @@ -254,20 +254,20 @@ vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in ve if ( clipped ) discard; #endif #endif -#endif`,Bm=`#if NUM_CLIPPING_PLANES > 0 +#endif`,zm=`#if NUM_CLIPPING_PLANES > 0 varying vec3 vClipPosition; uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; -#endif`,Om=`#if NUM_CLIPPING_PLANES > 0 +#endif`,km=`#if NUM_CLIPPING_PLANES > 0 varying vec3 vClipPosition; -#endif`,zm=`#if NUM_CLIPPING_PLANES > 0 +#endif`,Hm=`#if NUM_CLIPPING_PLANES > 0 vClipPosition = - mvPosition.xyz; -#endif`,km=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) +#endif`,Vm=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) diffuseColor *= vColor; -#endif`,Hm=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) +#endif`,Gm=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) varying vec4 vColor; -#endif`,Vm=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) +#endif`,Wm=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) varying vec4 vColor; -#endif`,Gm=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) +#endif`,Xm=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) vColor = vec4( 1.0 ); #endif #ifdef USE_COLOR_ALPHA @@ -280,7 +280,7 @@ vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in ve #endif #ifdef USE_BATCHING_COLOR vColor *= getBatchingColor( getIndirectIndex( gl_DrawID ) ); -#endif`,Wm=`#define PI 3.141592653589793 +#endif`,qm=`#define PI 3.141592653589793 #define PI2 6.283185307179586 #define PI_HALF 1.5707963267948966 #define RECIPROCAL_PI 0.3183098861837907 @@ -351,7 +351,7 @@ vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) { float F_Schlick( const in float f0, const in float f90, const in float dotVH ) { float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); -} // validated`,Xm=`#ifdef ENVMAP_TYPE_CUBE_UV +} // validated`,Ym=`#ifdef ENVMAP_TYPE_CUBE_UV #define cubeUV_minMipLevel 4.0 #define cubeUV_minTileSize 16.0 float getFace( vec3 direction ) { @@ -444,7 +444,7 @@ float F_Schlick( const in float f0, const in float f90, const in float dotVH ) { return vec4( mix( color0, color1, mipF ), 1.0 ); } } -#endif`,qm=`vec3 transformedNormal = objectNormal; +#endif`,$m=`vec3 transformedNormal = objectNormal; #ifdef USE_TANGENT vec3 transformedTangent = objectTangent; #endif @@ -470,21 +470,21 @@ transformedNormal = normalMatrix * transformedNormal; #endif #ifdef USE_TANGENT transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz; -#endif`,Ym=`#ifdef USE_DISPLACEMENTMAP +#endif`,Zm=`#ifdef USE_DISPLACEMENTMAP uniform sampler2D displacementMap; uniform float displacementScale; uniform float displacementBias; -#endif`,$m=`#ifdef USE_DISPLACEMENTMAP +#endif`,Jm=`#ifdef USE_DISPLACEMENTMAP transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias ); -#endif`,Zm=`#ifdef USE_EMISSIVEMAP +#endif`,Km=`#ifdef USE_EMISSIVEMAP vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE emissiveColor = sRGBTransferEOTF( emissiveColor ); #endif totalEmissiveRadiance *= emissiveColor.rgb; -#endif`,Jm=`#ifdef USE_EMISSIVEMAP +#endif`,jm=`#ifdef USE_EMISSIVEMAP uniform sampler2D emissiveMap; -#endif`,Km="gl_FragColor = linearToOutputTexel( gl_FragColor );",jm=`vec4 LinearTransferOETF( in vec4 value ) { +#endif`,Qm="gl_FragColor = linearToOutputTexel( gl_FragColor );",tg=`vec4 LinearTransferOETF( in vec4 value ) { return value; } vec4 sRGBTransferEOTF( in vec4 value ) { @@ -492,7 +492,7 @@ vec4 sRGBTransferEOTF( in vec4 value ) { } vec4 sRGBTransferOETF( in vec4 value ) { return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a ); -}`,Qm=`#ifdef USE_ENVMAP +}`,eg=`#ifdef USE_ENVMAP #ifdef ENV_WORLDPOS vec3 cameraToFrag; if ( isOrthographic ) { @@ -519,7 +519,7 @@ vec4 sRGBTransferOETF( in vec4 value ) { outgoingLight += envColor.xyz * specularStrength * reflectivity; #endif #endif -#endif`,tg=`#ifdef USE_ENVMAP +#endif`,ng=`#ifdef USE_ENVMAP uniform float envMapIntensity; uniform mat3 envMapRotation; #ifdef ENVMAP_TYPE_CUBE @@ -527,7 +527,7 @@ vec4 sRGBTransferOETF( in vec4 value ) { #else uniform sampler2D envMap; #endif -#endif`,eg=`#ifdef USE_ENVMAP +#endif`,ig=`#ifdef USE_ENVMAP uniform float reflectivity; #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) #define ENV_WORLDPOS @@ -538,7 +538,7 @@ vec4 sRGBTransferOETF( in vec4 value ) { #else varying vec3 vReflect; #endif -#endif`,ng=`#ifdef USE_ENVMAP +#endif`,sg=`#ifdef USE_ENVMAP #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) #define ENV_WORLDPOS #endif @@ -549,7 +549,7 @@ vec4 sRGBTransferOETF( in vec4 value ) { varying vec3 vReflect; uniform float refractionRatio; #endif -#endif`,ig=`#ifdef USE_ENVMAP +#endif`,rg=`#ifdef USE_ENVMAP #ifdef ENV_WORLDPOS vWorldPosition = worldPosition.xyz; #else @@ -566,18 +566,18 @@ vec4 sRGBTransferOETF( in vec4 value ) { vReflect = refract( cameraToVertex, worldNormal, refractionRatio ); #endif #endif -#endif`,sg=`#ifdef USE_FOG +#endif`,og=`#ifdef USE_FOG vFogDepth = - mvPosition.z; -#endif`,rg=`#ifdef USE_FOG +#endif`,ag=`#ifdef USE_FOG varying float vFogDepth; -#endif`,og=`#ifdef USE_FOG +#endif`,lg=`#ifdef USE_FOG #ifdef FOG_EXP2 float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth ); #else float fogFactor = smoothstep( fogNear, fogFar, vFogDepth ); #endif gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor ); -#endif`,ag=`#ifdef USE_FOG +#endif`,cg=`#ifdef USE_FOG uniform vec3 fogColor; varying float vFogDepth; #ifdef FOG_EXP2 @@ -586,7 +586,7 @@ vec4 sRGBTransferOETF( in vec4 value ) { uniform float fogNear; uniform float fogFar; #endif -#endif`,lg=`#ifdef USE_GRADIENTMAP +#endif`,hg=`#ifdef USE_GRADIENTMAP uniform sampler2D gradientMap; #endif vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { @@ -598,12 +598,12 @@ vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { vec2 fw = fwidth( coord ) * 0.5; return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) ); #endif -}`,cg=`#ifdef USE_LIGHTMAP +}`,ug=`#ifdef USE_LIGHTMAP uniform sampler2D lightMap; uniform float lightMapIntensity; -#endif`,hg=`LambertMaterial material; +#endif`,dg=`LambertMaterial material; material.diffuseColor = diffuseColor.rgb; -material.specularStrength = specularStrength;`,ug=`varying vec3 vViewPosition; +material.specularStrength = specularStrength;`,fg=`varying vec3 vViewPosition; struct LambertMaterial { vec3 diffuseColor; float specularStrength; @@ -617,7 +617,7 @@ void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometr reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } #define RE_Direct RE_Direct_Lambert -#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,dg=`uniform bool receiveShadow; +#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,pg=`uniform bool receiveShadow; uniform vec3 ambientLightColor; #if defined( USE_LIGHT_PROBES ) uniform vec3 lightProbe[ 9 ]; @@ -746,7 +746,7 @@ float getSpotAttenuation( const in float coneCosine, const in float penumbraCosi return irradiance; } #endif -#include `,fg=`#ifdef USE_ENVMAP +#include `,mg=`#ifdef USE_ENVMAP vec3 getIBLIrradiance( const in vec3 normal ) { #ifdef ENVMAP_TYPE_CUBE_UV vec3 worldNormal = transformNormalByInverseViewMatrix( normal, viewMatrix ); @@ -803,8 +803,8 @@ float getSpotAttenuation( const in float coneCosine, const in float penumbraCosi } #endif #endif -#endif`,pg=`ToonMaterial material; -material.diffuseColor = diffuseColor.rgb;`,mg=`varying vec3 vViewPosition; +#endif`,gg=`ToonMaterial material; +material.diffuseColor = diffuseColor.rgb;`,_g=`varying vec3 vViewPosition; struct ToonMaterial { vec3 diffuseColor; }; @@ -816,11 +816,11 @@ void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPo reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } #define RE_Direct RE_Direct_Toon -#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,gg=`BlinnPhongMaterial material; +#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,xg=`BlinnPhongMaterial material; material.diffuseColor = diffuseColor.rgb; material.specularColor = specular; material.specularShininess = shininess; -material.specularStrength = specularStrength;`,_g=`varying vec3 vViewPosition; +material.specularStrength = specularStrength;`,vg=`varying vec3 vViewPosition; struct BlinnPhongMaterial { vec3 diffuseColor; vec3 specularColor; @@ -837,7 +837,7 @@ void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geom reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } #define RE_Direct RE_Direct_BlinnPhong -#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,xg=`PhysicalMaterial material; +#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,yg=`PhysicalMaterial material; material.diffuseColor = diffuseColor.rgb; material.diffuseContribution = diffuseColor.rgb * ( 1.0 - metalnessFactor ); material.metalness = metalnessFactor; @@ -930,7 +930,7 @@ material.roughness = min( material.roughness, 1.0 ); material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) ); material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y; material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y; -#endif`,vg=`uniform sampler2D dfgLUT; +#endif`,Mg=`uniform sampler2D dfgLUT; struct PhysicalMaterial { vec3 diffuseColor; vec3 diffuseContribution; @@ -1297,7 +1297,7 @@ void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradia #define RE_IndirectSpecular RE_IndirectSpecular_Physical float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) { return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); -}`,yg=` +}`,bg=` vec3 geometryPosition = - vViewPosition; vec3 geometryNormal = normal; vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); @@ -1445,7 +1445,7 @@ IncidentLight directLight; #if defined( RE_IndirectSpecular ) vec3 radiance = vec3( 0.0 ); vec3 clearcoatRadiance = vec3( 0.0 ); -#endif`,Mg=`#if defined( RE_IndirectDiffuse ) +#endif`,Sg=`#if defined( RE_IndirectDiffuse ) #ifdef USE_LIGHTMAP vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; @@ -1475,7 +1475,7 @@ IncidentLight directLight; #ifdef USE_CLEARCOAT clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness ); #endif -#endif`,bg=`#if defined( RE_IndirectDiffuse ) +#endif`,wg=`#if defined( RE_IndirectDiffuse ) #if defined( LAMBERT ) || defined( PHONG ) irradiance += iblIrradiance; #endif @@ -1483,7 +1483,7 @@ IncidentLight directLight; #endif #if defined( RE_IndirectSpecular ) RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); -#endif`,Sg=`#ifdef USE_LIGHT_PROBES_GRID +#endif`,Eg=`#ifdef USE_LIGHT_PROBES_GRID uniform highp sampler3D probesSH; uniform vec3 probesMin; uniform vec3 probesMax; @@ -1528,27 +1528,27 @@ vec3 getLightProbeGridIrradiance( vec3 worldPos, vec3 worldNormal ) { result += c8 * 0.429043 * ( x * x - y * y ); return max( result, vec3( 0.0 ) ); } -#endif`,wg=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) +#endif`,Tg=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; -#endif`,Eg=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) +#endif`,Ag=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) uniform float logDepthBufFC; varying float vFragDepth; varying float vIsPerspective; -#endif`,Tg=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER +#endif`,Rg=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER varying float vFragDepth; varying float vIsPerspective; -#endif`,Ag=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER +#endif`,Cg=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER vFragDepth = 1.0 + gl_Position.w; vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); -#endif`,Rg=`#ifdef USE_MAP +#endif`,Ig=`#ifdef USE_MAP vec4 sampledDiffuseColor = texture2D( map, vMapUv ); #ifdef DECODE_VIDEO_TEXTURE sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor ); #endif diffuseColor *= sampledDiffuseColor; -#endif`,Cg=`#ifdef USE_MAP +#endif`,Pg=`#ifdef USE_MAP uniform sampler2D map; -#endif`,Ig=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) +#endif`,Lg=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) #if defined( USE_POINTS_UV ) vec2 uv = vUv; #else @@ -1560,7 +1560,7 @@ vec3 getLightProbeGridIrradiance( vec3 worldPos, vec3 worldNormal ) { #endif #ifdef USE_ALPHAMAP diffuseColor.a *= texture2D( alphaMap, uv ).g; -#endif`,Pg=`#if defined( USE_POINTS_UV ) +#endif`,Dg=`#if defined( USE_POINTS_UV ) varying vec2 vUv; #else #if defined( USE_MAP ) || defined( USE_ALPHAMAP ) @@ -1572,19 +1572,19 @@ vec3 getLightProbeGridIrradiance( vec3 worldPos, vec3 worldNormal ) { #endif #ifdef USE_ALPHAMAP uniform sampler2D alphaMap; -#endif`,Lg=`float metalnessFactor = metalness; +#endif`,Ng=`float metalnessFactor = metalness; #ifdef USE_METALNESSMAP vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); metalnessFactor *= texelMetalness.b; -#endif`,Dg=`#ifdef USE_METALNESSMAP +#endif`,Ug=`#ifdef USE_METALNESSMAP uniform sampler2D metalnessMap; -#endif`,Ng=`#ifdef USE_INSTANCING_MORPH +#endif`,Fg=`#ifdef USE_INSTANCING_MORPH float morphTargetInfluences[ MORPHTARGETS_COUNT ]; float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r; } -#endif`,Ug=`#if defined( USE_MORPHCOLORS ) +#endif`,Bg=`#if defined( USE_MORPHCOLORS ) vColor *= morphTargetBaseInfluence; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { #if defined( USE_COLOR_ALPHA ) @@ -1593,12 +1593,12 @@ vec3 getLightProbeGridIrradiance( vec3 worldPos, vec3 worldNormal ) { if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ]; #endif } -#endif`,Fg=`#ifdef USE_MORPHNORMALS +#endif`,Og=`#ifdef USE_MORPHNORMALS objectNormal *= morphTargetBaseInfluence; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ]; } -#endif`,Bg=`#ifdef USE_MORPHTARGETS +#endif`,zg=`#ifdef USE_MORPHTARGETS #ifndef USE_INSTANCING_MORPH uniform float morphTargetBaseInfluence; uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ]; @@ -1612,12 +1612,12 @@ vec3 getLightProbeGridIrradiance( vec3 worldPos, vec3 worldNormal ) { ivec3 morphUV = ivec3( x, y, morphTargetIndex ); return texelFetch( morphTargetsTexture, morphUV, 0 ); } -#endif`,Og=`#ifdef USE_MORPHTARGETS +#endif`,kg=`#ifdef USE_MORPHTARGETS transformed *= morphTargetBaseInfluence; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ]; } -#endif`,zg=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; +#endif`,Hg=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; #ifdef FLAT_SHADED vec3 fdx = dFdx( vViewPosition ); vec3 fdy = dFdy( vViewPosition ); @@ -1658,7 +1658,7 @@ vec3 getLightProbeGridIrradiance( vec3 worldPos, vec3 worldNormal ) { tbn2[1] *= faceDirection; #endif #endif -vec3 nonPerturbedNormal = normal;`,kg=`#ifdef USE_NORMALMAP_OBJECTSPACE +vec3 nonPerturbedNormal = normal;`,Vg=`#ifdef USE_NORMALMAP_OBJECTSPACE normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; #ifdef FLIP_SIDED normal = - normal; @@ -1676,19 +1676,19 @@ vec3 nonPerturbedNormal = normal;`,kg=`#ifdef USE_NORMALMAP_OBJECTSPACE normal = normalize( tbn * mapN ); #elif defined( USE_BUMPMAP ) normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection ); -#endif`,Hg=`#ifndef FLAT_SHADED +#endif`,Gg=`#ifndef FLAT_SHADED varying vec3 vNormal; #ifdef USE_TANGENT varying vec3 vTangent; varying vec3 vBitangent; #endif -#endif`,Vg=`#ifndef FLAT_SHADED +#endif`,Wg=`#ifndef FLAT_SHADED varying vec3 vNormal; #ifdef USE_TANGENT varying vec3 vTangent; varying vec3 vBitangent; #endif -#endif`,Gg=`#ifndef FLAT_SHADED +#endif`,Xg=`#ifndef FLAT_SHADED vNormal = normalize( transformedNormal ); #ifdef USE_TANGENT vTangent = normalize( transformedTangent ); @@ -1697,7 +1697,7 @@ vec3 nonPerturbedNormal = normal;`,kg=`#ifdef USE_NORMALMAP_OBJECTSPACE vBitangent = - vBitangent; #endif #endif -#endif`,Wg=`#ifdef USE_NORMALMAP +#endif`,qg=`#ifdef USE_NORMALMAP uniform sampler2D normalMap; uniform vec2 normalScale; #endif @@ -1719,13 +1719,13 @@ vec3 nonPerturbedNormal = normal;`,kg=`#ifdef USE_NORMALMAP_OBJECTSPACE float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det ); return mat3( T * scale, B * scale, N ); } -#endif`,Xg=`#ifdef USE_CLEARCOAT +#endif`,Yg=`#ifdef USE_CLEARCOAT vec3 clearcoatNormal = nonPerturbedNormal; -#endif`,qg=`#ifdef USE_CLEARCOAT_NORMALMAP +#endif`,$g=`#ifdef USE_CLEARCOAT_NORMALMAP vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; clearcoatMapN.xy *= clearcoatNormalScale; clearcoatNormal = normalize( tbn2 * clearcoatMapN ); -#endif`,Yg=`#ifdef USE_CLEARCOATMAP +#endif`,Zg=`#ifdef USE_CLEARCOATMAP uniform sampler2D clearcoatMap; #endif #ifdef USE_CLEARCOAT_NORMALMAP @@ -1734,18 +1734,18 @@ vec3 nonPerturbedNormal = normal;`,kg=`#ifdef USE_NORMALMAP_OBJECTSPACE #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP uniform sampler2D clearcoatRoughnessMap; -#endif`,$g=`#ifdef USE_IRIDESCENCEMAP +#endif`,Jg=`#ifdef USE_IRIDESCENCEMAP uniform sampler2D iridescenceMap; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP uniform sampler2D iridescenceThicknessMap; -#endif`,Zg=`#ifdef OPAQUE +#endif`,Kg=`#ifdef OPAQUE diffuseColor.a = 1.0; #endif #ifdef USE_TRANSMISSION diffuseColor.a *= material.transmissionAlpha; #endif -gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,Jg=`vec3 packNormalToRGB( const in vec3 normal ) { +gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,jg=`vec3 packNormalToRGB( const in vec3 normal ) { return normalize( normal ) * 0.5 + 0.5; } vec3 unpackRGBToNormal( const in vec3 rgb ) { @@ -1824,9 +1824,9 @@ float perspectiveDepthToViewZ( const in float depth, const in float near, const #else return ( near * far ) / ( ( far - near ) * depth - far ); #endif -}`,Kg=`#ifdef PREMULTIPLIED_ALPHA +}`,Qg=`#ifdef PREMULTIPLIED_ALPHA gl_FragColor.rgb *= gl_FragColor.a; -#endif`,jg=`vec4 mvPosition = vec4( transformed, 1.0 ); +#endif`,t_=`vec4 mvPosition = vec4( transformed, 1.0 ); #ifdef USE_BATCHING mvPosition = batchingMatrix * mvPosition; #endif @@ -1834,22 +1834,22 @@ float perspectiveDepthToViewZ( const in float depth, const in float near, const mvPosition = instanceMatrix * mvPosition; #endif mvPosition = modelViewMatrix * mvPosition; -gl_Position = projectionMatrix * mvPosition;`,Qg=`#ifdef DITHERING +gl_Position = projectionMatrix * mvPosition;`,e_=`#ifdef DITHERING gl_FragColor.rgb = dithering( gl_FragColor.rgb ); -#endif`,t_=`#ifdef DITHERING +#endif`,n_=`#ifdef DITHERING vec3 dithering( vec3 color ) { float grid_position = rand( gl_FragCoord.xy ); vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 ); dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position ); return color + dither_shift_RGB; } -#endif`,e_=`float roughnessFactor = roughness; +#endif`,i_=`float roughnessFactor = roughness; #ifdef USE_ROUGHNESSMAP vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); roughnessFactor *= texelRoughness.g; -#endif`,n_=`#ifdef USE_ROUGHNESSMAP +#endif`,s_=`#ifdef USE_ROUGHNESSMAP uniform sampler2D roughnessMap; -#endif`,i_=`#if NUM_SPOT_LIGHT_COORDS > 0 +#endif`,r_=`#if NUM_SPOT_LIGHT_COORDS > 0 varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; #endif #if NUM_SPOT_LIGHT_MAPS > 0 @@ -2100,7 +2100,7 @@ gl_Position = projectionMatrix * mvPosition;`,Qg=`#ifdef DITHERING } #endif #endif -#endif`,s_=`#if NUM_SPOT_LIGHT_COORDS > 0 +#endif`,o_=`#if NUM_SPOT_LIGHT_COORDS > 0 uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ]; varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; #endif @@ -2145,7 +2145,7 @@ gl_Position = projectionMatrix * mvPosition;`,Qg=`#ifdef DITHERING }; uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; #endif -#endif`,r_=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SUN_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) +#endif`,a_=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SUN_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) #ifdef HAS_NORMAL vec3 shadowWorldNormal = transformNormalByInverseViewMatrix( transformedNormal, viewMatrix ); #else @@ -2185,7 +2185,7 @@ gl_Position = projectionMatrix * mvPosition;`,Qg=`#ifdef DITHERING vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition; } #pragma unroll_loop_end -#endif`,o_=`float getShadowMask() { +#endif`,l_=`float getShadowMask() { float shadow = 1.0; #ifdef USE_SHADOWMAP #if NUM_SUN_LIGHT_SHADOWS > 0 @@ -2226,12 +2226,12 @@ gl_Position = projectionMatrix * mvPosition;`,Qg=`#ifdef DITHERING #endif #endif return shadow; -}`,a_=`#ifdef USE_SKINNING +}`,c_=`#ifdef USE_SKINNING mat4 boneMatX = getBoneMatrix( skinIndex.x ); mat4 boneMatY = getBoneMatrix( skinIndex.y ); mat4 boneMatZ = getBoneMatrix( skinIndex.z ); mat4 boneMatW = getBoneMatrix( skinIndex.w ); -#endif`,l_=`#ifdef USE_SKINNING +#endif`,h_=`#ifdef USE_SKINNING uniform mat4 bindMatrix; uniform mat4 bindMatrixInverse; uniform highp sampler2D boneTexture; @@ -2246,7 +2246,7 @@ gl_Position = projectionMatrix * mvPosition;`,Qg=`#ifdef DITHERING vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); return mat4( v1, v2, v3, v4 ); } -#endif`,c_=`#ifdef USE_SKINNING +#endif`,u_=`#ifdef USE_SKINNING vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); vec4 skinned = vec4( 0.0 ); skinned += boneMatX * skinVertex * skinWeight.x; @@ -2254,7 +2254,7 @@ gl_Position = projectionMatrix * mvPosition;`,Qg=`#ifdef DITHERING skinned += boneMatZ * skinVertex * skinWeight.z; skinned += boneMatW * skinVertex * skinWeight.w; transformed = ( bindMatrixInverse * skinned ).xyz; -#endif`,h_=`#ifdef USE_SKINNING +#endif`,d_=`#ifdef USE_SKINNING mat4 skinMatrix = mat4( 0.0 ); skinMatrix += skinWeight.x * boneMatX; skinMatrix += skinWeight.y * boneMatY; @@ -2265,17 +2265,17 @@ gl_Position = projectionMatrix * mvPosition;`,Qg=`#ifdef DITHERING #ifdef USE_TANGENT objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; #endif -#endif`,u_=`float specularStrength; +#endif`,f_=`float specularStrength; #ifdef USE_SPECULARMAP vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); specularStrength = texelSpecular.r; #else specularStrength = 1.0; -#endif`,d_=`#ifdef USE_SPECULARMAP +#endif`,p_=`#ifdef USE_SPECULARMAP uniform sampler2D specularMap; -#endif`,f_=`#if defined( TONE_MAPPING ) +#endif`,m_=`#if defined( TONE_MAPPING ) gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); -#endif`,p_=`#ifndef saturate +#endif`,g_=`#ifndef saturate #define saturate( a ) clamp( a, 0.0, 1.0 ) #endif uniform float toneMappingExposure; @@ -2372,7 +2372,7 @@ vec3 NeutralToneMapping( vec3 color ) { float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. ); return mix( color, vec3( newPeak ), g ); } -vec3 CustomToneMapping( vec3 color ) { return color; }`,m_=`#ifdef USE_TRANSMISSION +vec3 CustomToneMapping( vec3 color ) { return color; }`,__=`#ifdef USE_TRANSMISSION material.transmission = transmission; material.transmissionAlpha = 1.0; material.thickness = thickness; @@ -2393,7 +2393,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,m_=`#ifdef USE_TRANSMISS material.attenuationColor, material.attenuationDistance ); material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission ); totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission ); -#endif`,g_=`#ifdef USE_TRANSMISSION +#endif`,x_=`#ifdef USE_TRANSMISSION uniform float transmission; uniform float thickness; uniform float attenuationDistance; @@ -2519,7 +2519,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,m_=`#ifdef USE_TRANSMISS float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0; return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor ); } -#endif`,__=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) +#endif`,v_=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) varying vec2 vUv; #endif #ifdef USE_MAP @@ -2589,7 +2589,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,m_=`#ifdef USE_TRANSMISS #ifdef USE_THICKNESSMAP uniform mat3 thicknessMapTransform; varying vec2 vThicknessMapUv; -#endif`,x_=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) +#endif`,y_=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) varying vec2 vUv; #endif #ifdef USE_MAP @@ -2683,7 +2683,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,m_=`#ifdef USE_TRANSMISS #ifdef USE_THICKNESSMAP uniform mat3 thicknessMapTransform; varying vec2 vThicknessMapUv; -#endif`,v_=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) +#endif`,M_=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) vUv = vec3( uv, 1 ).xy; #endif #ifdef USE_MAP @@ -2754,7 +2754,7 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,m_=`#ifdef USE_TRANSMISS #endif #ifdef USE_THICKNESSMAP vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy; -#endif`,y_=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0 +#endif`,b_=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0 vec4 worldPosition = vec4( transformed, 1.0 ); #ifdef USE_BATCHING worldPosition = batchingMatrix * worldPosition; @@ -2763,12 +2763,12 @@ vec3 CustomToneMapping( vec3 color ) { return color; }`,m_=`#ifdef USE_TRANSMISS worldPosition = instanceMatrix * worldPosition; #endif worldPosition = modelMatrix * worldPosition; -#endif`,M_=`varying vec2 vUv; +#endif`,S_=`varying vec2 vUv; uniform mat3 uvTransform; void main() { vUv = ( uvTransform * vec3( uv, 1 ) ).xy; gl_Position = vec4( position.xy, 1.0, 1.0 ); -}`,b_=`uniform sampler2D t2D; +}`,w_=`uniform sampler2D t2D; uniform float backgroundIntensity; varying vec2 vUv; void main() { @@ -2780,14 +2780,14 @@ void main() { gl_FragColor = texColor; #include #include -}`,S_=`varying vec3 vWorldDirection; +}`,E_=`varying vec3 vWorldDirection; #include void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include gl_Position.z = gl_Position.w; -}`,w_=`#ifdef ENVMAP_TYPE_CUBE +}`,T_=`#ifdef ENVMAP_TYPE_CUBE uniform samplerCube envMap; #elif defined( ENVMAP_TYPE_CUBE_UV ) uniform sampler2D envMap; @@ -2809,14 +2809,14 @@ void main() { gl_FragColor = texColor; #include #include -}`,E_=`varying vec3 vWorldDirection; +}`,A_=`varying vec3 vWorldDirection; #include void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include gl_Position.z = gl_Position.w; -}`,T_=`uniform samplerCube tCube; +}`,R_=`uniform samplerCube tCube; uniform float tFlip; uniform float opacity; varying vec3 vWorldDirection; @@ -2826,7 +2826,7 @@ void main() { gl_FragColor.a *= opacity; #include #include -}`,A_=`#include +}`,C_=`#include #include #include #include @@ -2853,7 +2853,7 @@ void main() { #include #include vHighPrecisionZW = gl_Position.zw; -}`,R_=`#if DEPTH_PACKING == 3200 +}`,I_=`#if DEPTH_PACKING == 3200 uniform float opacity; #endif #include @@ -2891,7 +2891,7 @@ void main() { #elif DEPTH_PACKING == 3203 gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 ); #endif -}`,C_=`#define DISTANCE +}`,P_=`#define DISTANCE varying vec3 vWorldPosition; #include #include @@ -2918,7 +2918,7 @@ void main() { #include #include vWorldPosition = worldPosition.xyz; -}`,I_=`#define DISTANCE +}`,L_=`#define DISTANCE uniform vec3 referencePosition; uniform float nearDistance; uniform float farDistance; @@ -2941,13 +2941,13 @@ void main() { dist = ( dist - nearDistance ) / ( farDistance - nearDistance ); dist = saturate( dist ); gl_FragColor = vec4( dist, 0.0, 0.0, 1.0 ); -}`,P_=`varying vec3 vWorldDirection; +}`,D_=`varying vec3 vWorldDirection; #include void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include -}`,L_=`uniform sampler2D tEquirect; +}`,N_=`uniform sampler2D tEquirect; varying vec3 vWorldDirection; #include void main() { @@ -2956,7 +2956,7 @@ void main() { gl_FragColor = texture2D( tEquirect, sampleUV ); #include #include -}`,D_=`uniform float scale; +}`,U_=`uniform float scale; attribute float lineDistance; varying float vLineDistance; #include @@ -2978,7 +2978,7 @@ void main() { #include #include #include -}`,N_=`uniform vec3 diffuse; +}`,F_=`uniform vec3 diffuse; uniform float opacity; uniform float dashSize; uniform float totalSize; @@ -3006,7 +3006,7 @@ void main() { #include #include #include -}`,U_=`#include +}`,B_=`#include #include #include #include @@ -3038,7 +3038,7 @@ void main() { #include #include #include -}`,F_=`uniform vec3 diffuse; +}`,O_=`uniform vec3 diffuse; uniform float opacity; #ifndef FLAT_SHADED varying vec3 vNormal; @@ -3086,7 +3086,7 @@ void main() { #include #include #include -}`,B_=`#define LAMBERT +}`,z_=`#define LAMBERT varying vec3 vViewPosition; #include #include @@ -3125,7 +3125,7 @@ void main() { #include #include #include -}`,O_=`#define LAMBERT +}`,k_=`#define LAMBERT uniform vec3 diffuse; uniform vec3 emissive; uniform float opacity; @@ -3183,7 +3183,7 @@ void main() { #include #include #include -}`,z_=`#define MATCAP +}`,H_=`#define MATCAP varying vec3 vViewPosition; #include #include @@ -3217,7 +3217,7 @@ void main() { #include #include vViewPosition = - mvPosition.xyz; -}`,k_=`#define MATCAP +}`,V_=`#define MATCAP uniform vec3 diffuse; uniform float opacity; uniform sampler2D matcap; @@ -3263,7 +3263,7 @@ void main() { #include #include #include -}`,H_=`#define NORMAL +}`,G_=`#define NORMAL #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) varying vec3 vViewPosition; #endif @@ -3296,7 +3296,7 @@ void main() { #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) vViewPosition = - mvPosition.xyz; #endif -}`,V_=`#define NORMAL +}`,W_=`#define NORMAL uniform float opacity; #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) varying vec3 vViewPosition; @@ -3317,7 +3317,7 @@ void main() { #ifdef OPAQUE gl_FragColor.a = 1.0; #endif -}`,G_=`#define PHONG +}`,X_=`#define PHONG varying vec3 vViewPosition; #include #include @@ -3356,7 +3356,7 @@ void main() { #include #include #include -}`,W_=`#define PHONG +}`,q_=`#define PHONG uniform vec3 diffuse; uniform vec3 emissive; uniform vec3 specular; @@ -3416,7 +3416,7 @@ void main() { #include #include #include -}`,X_=`#define STANDARD +}`,Y_=`#define STANDARD varying vec3 vViewPosition; #ifdef USE_TRANSMISSION varying vec3 vWorldPosition; @@ -3459,7 +3459,7 @@ void main() { #ifdef USE_TRANSMISSION vWorldPosition = worldPosition.xyz; #endif -}`,q_=`#define STANDARD +}`,$_=`#define STANDARD #ifdef PHYSICAL #define IOR #define USE_SPECULAR @@ -3587,7 +3587,7 @@ void main() { #include #include #include -}`,Y_=`#define TOON +}`,Z_=`#define TOON varying vec3 vViewPosition; #include #include @@ -3624,7 +3624,7 @@ void main() { #include #include #include -}`,$_=`#define TOON +}`,J_=`#define TOON uniform vec3 diffuse; uniform vec3 emissive; uniform float opacity; @@ -3676,7 +3676,7 @@ void main() { #include #include #include -}`,Z_=`uniform float size; +}`,K_=`uniform float size; uniform float scale; #include #include @@ -3707,7 +3707,7 @@ void main() { #include #include #include -}`,J_=`uniform vec3 diffuse; +}`,j_=`uniform vec3 diffuse; uniform float opacity; #include #include @@ -3732,7 +3732,7 @@ void main() { #include #include #include -}`,K_=`#include +}`,Q_=`#include #include #include #include @@ -3755,7 +3755,7 @@ void main() { #include #include #include -}`,j_=`uniform vec3 color; +}`,t0=`uniform vec3 color; uniform float opacity; #include #include @@ -3771,7 +3771,7 @@ void main() { #include #include #include -}`,Q_=`uniform float rotation; +}`,e0=`uniform float rotation; uniform vec2 center; #include #include @@ -3795,7 +3795,7 @@ void main() { #include #include #include -}`,t0=`uniform vec3 diffuse; +}`,n0=`uniform vec3 diffuse; uniform float opacity; #include #include @@ -3820,7 +3820,7 @@ void main() { #include #include #include -}`,Wt={alphahash_fragment:Mm,alphahash_pars_fragment:bm,alphamap_fragment:Sm,alphamap_pars_fragment:wm,alphatest_fragment:Em,alphatest_pars_fragment:Tm,aomap_fragment:Am,aomap_pars_fragment:Rm,batching_pars_vertex:Cm,batching_vertex:Im,begin_vertex:Pm,beginnormal_vertex:Lm,bsdfs:Dm,iridescence_fragment:Nm,bumpmap_pars_fragment:Um,clipping_planes_fragment:Fm,clipping_planes_pars_fragment:Bm,clipping_planes_pars_vertex:Om,clipping_planes_vertex:zm,color_fragment:km,color_pars_fragment:Hm,color_pars_vertex:Vm,color_vertex:Gm,common:Wm,cube_uv_reflection_fragment:Xm,defaultnormal_vertex:qm,displacementmap_pars_vertex:Ym,displacementmap_vertex:$m,emissivemap_fragment:Zm,emissivemap_pars_fragment:Jm,colorspace_fragment:Km,colorspace_pars_fragment:jm,envmap_fragment:Qm,envmap_common_pars_fragment:tg,envmap_pars_fragment:eg,envmap_pars_vertex:ng,envmap_physical_pars_fragment:fg,envmap_vertex:ig,fog_vertex:sg,fog_pars_vertex:rg,fog_fragment:og,fog_pars_fragment:ag,gradientmap_pars_fragment:lg,lightmap_pars_fragment:cg,lights_lambert_fragment:hg,lights_lambert_pars_fragment:ug,lights_pars_begin:dg,lights_toon_fragment:pg,lights_toon_pars_fragment:mg,lights_phong_fragment:gg,lights_phong_pars_fragment:_g,lights_physical_fragment:xg,lights_physical_pars_fragment:vg,lights_fragment_begin:yg,lights_fragment_maps:Mg,lights_fragment_end:bg,lightprobes_pars_fragment:Sg,logdepthbuf_fragment:wg,logdepthbuf_pars_fragment:Eg,logdepthbuf_pars_vertex:Tg,logdepthbuf_vertex:Ag,map_fragment:Rg,map_pars_fragment:Cg,map_particle_fragment:Ig,map_particle_pars_fragment:Pg,metalnessmap_fragment:Lg,metalnessmap_pars_fragment:Dg,morphinstance_vertex:Ng,morphcolor_vertex:Ug,morphnormal_vertex:Fg,morphtarget_pars_vertex:Bg,morphtarget_vertex:Og,normal_fragment_begin:zg,normal_fragment_maps:kg,normal_pars_fragment:Hg,normal_pars_vertex:Vg,normal_vertex:Gg,normalmap_pars_fragment:Wg,clearcoat_normal_fragment_begin:Xg,clearcoat_normal_fragment_maps:qg,clearcoat_pars_fragment:Yg,iridescence_pars_fragment:$g,opaque_fragment:Zg,packing:Jg,premultiplied_alpha_fragment:Kg,project_vertex:jg,dithering_fragment:Qg,dithering_pars_fragment:t_,roughnessmap_fragment:e_,roughnessmap_pars_fragment:n_,shadowmap_pars_fragment:i_,shadowmap_pars_vertex:s_,shadowmap_vertex:r_,shadowmask_pars_fragment:o_,skinbase_vertex:a_,skinning_pars_vertex:l_,skinning_vertex:c_,skinnormal_vertex:h_,specularmap_fragment:u_,specularmap_pars_fragment:d_,tonemapping_fragment:f_,tonemapping_pars_fragment:p_,transmission_fragment:m_,transmission_pars_fragment:g_,uv_pars_fragment:__,uv_pars_vertex:x_,uv_vertex:v_,worldpos_vertex:y_,background_vert:M_,background_frag:b_,backgroundCube_vert:S_,backgroundCube_frag:w_,cube_vert:E_,cube_frag:T_,depth_vert:A_,depth_frag:R_,distance_vert:C_,distance_frag:I_,equirect_vert:P_,equirect_frag:L_,linedashed_vert:D_,linedashed_frag:N_,meshbasic_vert:U_,meshbasic_frag:F_,meshlambert_vert:B_,meshlambert_frag:O_,meshmatcap_vert:z_,meshmatcap_frag:k_,meshnormal_vert:H_,meshnormal_frag:V_,meshphong_vert:G_,meshphong_frag:W_,meshphysical_vert:X_,meshphysical_frag:q_,meshtoon_vert:Y_,meshtoon_frag:$_,points_vert:Z_,points_frag:J_,shadow_vert:K_,shadow_frag:j_,sprite_vert:Q_,sprite_frag:t0},xt={common:{diffuse:{value:new Ft(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new Ot},alphaMap:{value:null},alphaMapTransform:{value:new Ot},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new Ot}},envmap:{envMap:{value:null},envMapRotation:{value:new Ot},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new Ot}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new Ot}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new Ot},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new Ot},normalScale:{value:new Ht(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new Ot},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new Ot}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new Ot}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new Ot}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new Ft(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},sunLights:{value:[],properties:{direction:{},color:{}}},sunLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},sunShadowMatrix:{value:[]},sunShadowCascade:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null},probesSH:{value:null},probesMin:{value:new I},probesMax:{value:new I},probesResolution:{value:new I}},points:{diffuse:{value:new Ft(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new Ot},alphaTest:{value:0},uvTransform:{value:new Ot}},sprite:{diffuse:{value:new Ft(16777215)},opacity:{value:1},center:{value:new Ht(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new Ot},alphaMap:{value:null},alphaMapTransform:{value:new Ot},alphaTest:{value:0}}},kn={basic:{uniforms:Ze([xt.common,xt.specularmap,xt.envmap,xt.aomap,xt.lightmap,xt.fog]),vertexShader:Wt.meshbasic_vert,fragmentShader:Wt.meshbasic_frag},lambert:{uniforms:Ze([xt.common,xt.specularmap,xt.envmap,xt.aomap,xt.lightmap,xt.emissivemap,xt.bumpmap,xt.normalmap,xt.displacementmap,xt.fog,xt.lights,{emissive:{value:new Ft(0)},envMapIntensity:{value:1}}]),vertexShader:Wt.meshlambert_vert,fragmentShader:Wt.meshlambert_frag},phong:{uniforms:Ze([xt.common,xt.specularmap,xt.envmap,xt.aomap,xt.lightmap,xt.emissivemap,xt.bumpmap,xt.normalmap,xt.displacementmap,xt.fog,xt.lights,{emissive:{value:new Ft(0)},specular:{value:new Ft(1118481)},shininess:{value:30},envMapIntensity:{value:1}}]),vertexShader:Wt.meshphong_vert,fragmentShader:Wt.meshphong_frag},standard:{uniforms:Ze([xt.common,xt.envmap,xt.aomap,xt.lightmap,xt.emissivemap,xt.bumpmap,xt.normalmap,xt.displacementmap,xt.roughnessmap,xt.metalnessmap,xt.fog,xt.lights,{emissive:{value:new Ft(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Wt.meshphysical_vert,fragmentShader:Wt.meshphysical_frag},toon:{uniforms:Ze([xt.common,xt.aomap,xt.lightmap,xt.emissivemap,xt.bumpmap,xt.normalmap,xt.displacementmap,xt.gradientmap,xt.fog,xt.lights,{emissive:{value:new Ft(0)}}]),vertexShader:Wt.meshtoon_vert,fragmentShader:Wt.meshtoon_frag},matcap:{uniforms:Ze([xt.common,xt.bumpmap,xt.normalmap,xt.displacementmap,xt.fog,{matcap:{value:null}}]),vertexShader:Wt.meshmatcap_vert,fragmentShader:Wt.meshmatcap_frag},points:{uniforms:Ze([xt.points,xt.fog]),vertexShader:Wt.points_vert,fragmentShader:Wt.points_frag},dashed:{uniforms:Ze([xt.common,xt.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Wt.linedashed_vert,fragmentShader:Wt.linedashed_frag},depth:{uniforms:Ze([xt.common,xt.displacementmap]),vertexShader:Wt.depth_vert,fragmentShader:Wt.depth_frag},normal:{uniforms:Ze([xt.common,xt.bumpmap,xt.normalmap,xt.displacementmap,{opacity:{value:1}}]),vertexShader:Wt.meshnormal_vert,fragmentShader:Wt.meshnormal_frag},sprite:{uniforms:Ze([xt.sprite,xt.fog]),vertexShader:Wt.sprite_vert,fragmentShader:Wt.sprite_frag},background:{uniforms:{uvTransform:{value:new Ot},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:Wt.background_vert,fragmentShader:Wt.background_frag},backgroundCube:{uniforms:{envMap:{value:null},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new Ot}},vertexShader:Wt.backgroundCube_vert,fragmentShader:Wt.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Wt.cube_vert,fragmentShader:Wt.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Wt.equirect_vert,fragmentShader:Wt.equirect_frag},distance:{uniforms:Ze([xt.common,xt.displacementmap,{referencePosition:{value:new I},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Wt.distance_vert,fragmentShader:Wt.distance_frag},shadow:{uniforms:Ze([xt.lights,xt.fog,{color:{value:new Ft(0)},opacity:{value:1}}]),vertexShader:Wt.shadow_vert,fragmentShader:Wt.shadow_frag}};kn.physical={uniforms:Ze([kn.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new Ot},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new Ot},clearcoatNormalScale:{value:new Ht(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new Ot},dispersion:{value:0},retroreflectivity:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new Ot},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new Ot},sheen:{value:0},sheenColor:{value:new Ft(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new Ot},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new Ot},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new Ot},transmissionSamplerSize:{value:new Ht},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new Ot},attenuationDistance:{value:0},attenuationColor:{value:new Ft(0)},specularColor:{value:new Ft(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new Ot},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new Ot},anisotropyVector:{value:new Ht},anisotropyMap:{value:null},anisotropyMapTransform:{value:new Ot}}]),vertexShader:Wt.meshphysical_vert,fragmentShader:Wt.meshphysical_frag};var Oa={r:0,b:0,g:0},e0=new kt,Pd=new Ot;Pd.set(-1,0,0,0,1,0,0,0,1);function n0(i,t,e,n,s,r){let o=new Ft(0),a=s===!0?0:1,l,c,h=null,d=0,u=null;function p(b){let E=b.isScene===!0?b.background:null;if(E&&E.isTexture){let M=b.backgroundBlurriness>0;E=t.get(E,M)}return E}function g(b){let E=!1,M=p(b);M===null?m(o,a):M&&M.isColor&&(m(M,1),E=!0);let v=i.xr.getEnvironmentBlendMode();v==="additive"?e.buffers.color.setClear(0,0,0,1,r):v==="alpha-blend"&&e.buffers.color.setClear(0,0,0,0,r),(i.autoClear||E)&&(e.buffers.depth.setTest(!0),e.buffers.depth.setMask(!0),e.buffers.color.setMask(!0),i.clear(i.autoClearColor,i.autoClearDepth,i.autoClearStencil))}function _(b,E){let M=p(E);M&&(M.isCubeTexture||M.mapping===cr)?(c===void 0&&(c=new _e(new dn(1,1,1),new He({name:"BackgroundCubeMaterial",uniforms:Fi(kn.backgroundCube.uniforms),vertexShader:kn.backgroundCube.vertexShader,fragmentShader:kn.backgroundCube.fragmentShader,side:Ve,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),c.geometry.deleteAttribute("normal"),c.geometry.deleteAttribute("uv"),c.onBeforeRender=function(v,S,A){this.matrixWorld.copyPosition(A.matrixWorld)},Object.defineProperty(c.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),n.update(c)),c.material.uniforms.envMap.value=M,c.material.uniforms.backgroundBlurriness.value=E.backgroundBlurriness,c.material.uniforms.backgroundIntensity.value=E.backgroundIntensity,c.material.uniforms.backgroundRotation.value.setFromMatrix4(e0.makeRotationFromEuler(E.backgroundRotation)).transpose(),M.isCubeTexture&&M.isRenderTargetTexture===!1&&c.material.uniforms.backgroundRotation.value.premultiply(Pd),c.material.toneMapped=Yt.getTransfer(M.colorSpace)!==te,(h!==M||d!==M.version||u!==i.toneMapping)&&(c.material.needsUpdate=!0,h=M,d=M.version,u=i.toneMapping),c.layers.enableAll(),b.unshift(c,c.geometry,c.material,0,0,null)):M&&M.isTexture&&(l===void 0&&(l=new _e(new yn(2,2),new He({name:"BackgroundMaterial",uniforms:Fi(kn.background.uniforms),vertexShader:kn.background.vertexShader,fragmentShader:kn.background.fragmentShader,side:Bn,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute("normal"),Object.defineProperty(l.material,"map",{get:function(){return this.uniforms.t2D.value}}),n.update(l)),l.material.uniforms.t2D.value=M,l.material.uniforms.backgroundIntensity.value=E.backgroundIntensity,l.material.toneMapped=Yt.getTransfer(M.colorSpace)!==te,M.matrixAutoUpdate===!0&&M.updateMatrix(),l.material.uniforms.uvTransform.value.copy(M.matrix),(h!==M||d!==M.version||u!==i.toneMapping)&&(l.material.needsUpdate=!0,h=M,d=M.version,u=i.toneMapping),l.layers.enableAll(),b.unshift(l,l.geometry,l.material,0,0,null))}function m(b,E){b.getRGB(Oa,Tc(i)),e.buffers.color.setClear(Oa.r,Oa.g,Oa.b,E,r)}function f(){c!==void 0&&(c.geometry.dispose(),c.material.dispose(),c=void 0),l!==void 0&&(l.geometry.dispose(),l.material.dispose(),l=void 0)}return{getClearColor:function(){return o},setClearColor:function(b,E=1){o.set(b),a=E,m(o,a)},getClearAlpha:function(){return a},setClearAlpha:function(b){a=b,m(o,a)},render:g,addToRenderList:_,dispose:f}}function i0(i,t){let e=i.getParameter(i.MAX_VERTEX_ATTRIBS),n={},s=u(null),r=s,o=!1;function a(L,N,U,C,B){let z=!1,W=d(L,C,U,N);r!==W&&(r=W,c(r.object)),z=p(L,C,U,B),z&&g(L,C,U,B),B!==null&&t.update(B,i.ELEMENT_ARRAY_BUFFER),(z||o)&&(o=!1,M(L,N,U,C),B!==null&&i.bindBuffer(i.ELEMENT_ARRAY_BUFFER,t.get(B).buffer))}function l(){return i.createVertexArray()}function c(L){return i.bindVertexArray(L)}function h(L){return i.deleteVertexArray(L)}function d(L,N,U,C){let B=C.wireframe===!0,z=n[N.id];z===void 0&&(z={},n[N.id]=z);let W=L.isInstancedMesh===!0?L.id:0,F=z[W];F===void 0&&(F={},z[W]=F);let D=F[U.id];D===void 0&&(D={},F[U.id]=D);let X=D[B];return X===void 0&&(X=u(l()),D[B]=X),X}function u(L){let N=[],U=[],C=[];for(let B=0;B=0){let Z=B[D],G=z[D];if(G===void 0&&(D==="instanceMatrix"&&L.instanceMatrix&&(G=L.instanceMatrix),D==="instanceColor"&&L.instanceColor&&(G=L.instanceColor)),Z===void 0||Z.attribute!==G||G&&Z.data!==G.data)return!0;W++}return r.attributesNum!==W||r.index!==C}function g(L,N,U,C){let B={},z=N.attributes,W=0,F=U.getAttributes();for(let D in F)if(F[D].location>=0){let Z=z[D];Z===void 0&&(D==="instanceMatrix"&&L.instanceMatrix&&(Z=L.instanceMatrix),D==="instanceColor"&&L.instanceColor&&(Z=L.instanceColor));let G={};G.attribute=Z,Z&&Z.data&&(G.data=Z.data),B[D]=G,W++}r.attributes=B,r.attributesNum=W,r.index=C}function _(){let L=r.newAttributes;for(let N=0,U=L.length;N=0){let X=B[F];if(X===void 0&&(F==="instanceMatrix"&&L.instanceMatrix&&(X=L.instanceMatrix),F==="instanceColor"&&L.instanceColor&&(X=L.instanceColor)),X!==void 0){let Z=X.normalized,G=X.itemSize,Q=t.get(X);if(Q===void 0)continue;let lt=Q.buffer,ct=Q.type,tt=Q.bytesPerElement,V=ct===i.INT||ct===i.UNSIGNED_INT||X.gpuType===Qo;if(X.isInterleavedBufferAttribute){let j=X.data,ut=j.stride,Lt=X.offset;if(j.isInstancedInterleavedBuffer){for(let Mt=0;Mt0&&i.getShaderPrecisionFormat(i.FRAGMENT_SHADER,i.HIGH_FLOAT).precision>0)return"highp";A="mediump"}return A==="mediump"&&i.getShaderPrecisionFormat(i.VERTEX_SHADER,i.MEDIUM_FLOAT).precision>0&&i.getShaderPrecisionFormat(i.FRAGMENT_SHADER,i.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let c=e.precision!==void 0?e.precision:"highp",h=l(c);h!==c&&(Dt("WebGLRenderer:",c,"not supported, using",h,"instead."),c=h);let d=e.logarithmicDepthBuffer===!0,u=e.reversedDepthBuffer===!0&&t.has("EXT_clip_control");e.reversedDepthBuffer===!0&&u===!1&&Dt("WebGLRenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer.");let p=i.getParameter(i.MAX_TEXTURE_IMAGE_UNITS),g=i.getParameter(i.MAX_VERTEX_TEXTURE_IMAGE_UNITS),_=i.getParameter(i.MAX_TEXTURE_SIZE),m=i.getParameter(i.MAX_CUBE_MAP_TEXTURE_SIZE),f=i.getParameter(i.MAX_VERTEX_ATTRIBS),b=i.getParameter(i.MAX_VERTEX_UNIFORM_VECTORS),E=i.getParameter(i.MAX_VARYING_VECTORS),M=i.getParameter(i.MAX_FRAGMENT_UNIFORM_VECTORS),v=i.getParameter(i.MAX_SAMPLES),S=i.getParameter(i.SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:r,getMaxPrecision:l,textureFormatReadable:o,textureTypeReadable:a,precision:c,logarithmicDepthBuffer:d,reversedDepthBuffer:u,maxTextures:p,maxVertexTextures:g,maxTextureSize:_,maxCubemapSize:m,maxAttributes:f,maxVertexUniforms:b,maxVaryings:E,maxFragmentUniforms:M,maxSamples:v,samples:S}}function o0(i){let t=this,e=null,n=0,s=!1,r=!1,o=new ge,a=new Ot,l={value:null,needsUpdate:!1};this.uniform=l,this.numPlanes=0,this.numIntersection=0,this.init=function(d,u){let p=d.length!==0||u||n!==0||s;return s=u,n=d.length,p},this.beginShadows=function(){r=!0,h(null)},this.endShadows=function(){r=!1},this.setGlobalState=function(d,u){e=h(d,u,0)},this.setState=function(d,u,p){let g=d.clippingPlanes,_=d.clipIntersection,m=d.clipShadows,f=i.get(d);if(!s||g===null||g.length===0||r&&!m)r?h(null):c();else{let b=r?0:n,E=b*4,M=f.clippingState||null;l.value=M,M=h(g,u,E,p);for(let v=0;v!==E;++v)M[v]=e[v];f.clippingState=M,this.numIntersection=_?this.numPlanes:0,this.numPlanes+=b}};function c(){l.value!==e&&(l.value=e,l.needsUpdate=n>0),t.numPlanes=n,t.numIntersection=0}function h(d,u,p,g){let _=d!==null?d.length:0,m=null;if(_!==0){if(m=l.value,g!==!0||m===null){let f=p+_*4,b=u.matrixWorldInverse;a.getNormalMatrix(b),(m===null||m.length0&&this._blur(l,0,0,e),this._applyPMREM(l),this._cleanup(l),l}fromEquirectangular(t,e=null){return this._fromTexture(t,e)}fromCubemap(t,e=null){return this._fromTexture(t,e)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=dd(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=ud(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose(),this._backgroundBox!==null&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSize(t){this._lodMax=Math.floor(Math.log2(t)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._ggxMaterial!==null&&this._ggxMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let t=0;t2?v:0,v,v),d.setRenderTarget(s),f&&d.render(_,l),d.render(t,l)}d.toneMapping=p,d.autoClear=u,t.background=b}_textureToCubeUV(t,e){let n=this._renderer,s=t.mapping===pi||t.mapping===Ui;s?(this._cubemapMaterial===null&&(this._cubemapMaterial=dd()),this._cubemapMaterial.uniforms.flipEnvMap.value=t.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=ud());let r=s?this._cubemapMaterial:this._equirectMaterial,o=this._lodMeshes[0];o.material=r;let a=r.uniforms;a.envMap.value=t;let l=this._cubeSize;ws(e,0,0,3*l,2*l),n.setRenderTarget(e),n.render(o,_r)}_applyPMREM(t){let e=this._renderer,n=e.autoClear;e.autoClear=!1;let s=this._lodMeshes.length;for(let r=1;rg-Es?n-g+Es:0),f=4*(this._cubeSize-_);l.envMap.value=t.texture,l.roughness.value=p,l.mipInt.value=g-e,ws(r,m,f,3*_,2*_),s.setRenderTarget(r),s.render(a,_r),l.envMap.value=r.texture,l.roughness.value=0,l.mipInt.value=g-n,ws(t,m,f,3*_,2*_),s.setRenderTarget(t),s.render(a,_r)}_blur(t,e,n,s){let r=this._pingPongRenderTarget,o=Math.min(s,Math.PI)/Math.SQRT2;this._blurPass(t,r,e,n,o),this._blurPass(r,t,n,n,o)}_blurPass(t,e,n,s,r){let o=this._renderer,a=this._blurMaterial,l=this._lodMeshes[s];l.material=a;let c=a.uniforms;c.envMap.value=t.texture,c.sigma.value=r,c.mipInt.value=this._lodMax-n;let h=this._sizeLods[s],d=3*h*(s>this._lodMax-Es?s-this._lodMax+Es:0),u=4*(this._cubeSize-h);ws(e,d,u,3*h,2*h),o.setRenderTarget(e),o.render(l,_r)}};function u0(i){let t=[],e=[],n=i,s=i-Es+1+a0;for(let r=0;r2?0:-1,M=[b,E,0,b+2/3,E,0,b+2/3,E+1,0,b,E,0,b+2/3,E+1,0,b,E+1,0];g.set(M,p*u*f);for(let v=0;vEs&&n--}return{lodMeshes:e,sizeLods:t}}function hd(i,t,e){let n=new Fe(i,t,e);return n.texture.mapping=cr,n.texture.name="PMREM.cubeUv",n.scissorTest=!0,n}function ws(i,t,e,n,s){i.viewport.set(t,e,n,s),i.scissor.set(t,e,n,s)}function d0(i,t,e){return new He({name:"PMREMGGXConvolution",defines:{GGX_SAMPLES:c0,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/e,CUBEUV_MAX_MIP:`${i}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:Va(),fragmentShader:` +}`,Wt={alphahash_fragment:Sm,alphahash_pars_fragment:wm,alphamap_fragment:Em,alphamap_pars_fragment:Tm,alphatest_fragment:Am,alphatest_pars_fragment:Rm,aomap_fragment:Cm,aomap_pars_fragment:Im,batching_pars_vertex:Pm,batching_vertex:Lm,begin_vertex:Dm,beginnormal_vertex:Nm,bsdfs:Um,iridescence_fragment:Fm,bumpmap_pars_fragment:Bm,clipping_planes_fragment:Om,clipping_planes_pars_fragment:zm,clipping_planes_pars_vertex:km,clipping_planes_vertex:Hm,color_fragment:Vm,color_pars_fragment:Gm,color_pars_vertex:Wm,color_vertex:Xm,common:qm,cube_uv_reflection_fragment:Ym,defaultnormal_vertex:$m,displacementmap_pars_vertex:Zm,displacementmap_vertex:Jm,emissivemap_fragment:Km,emissivemap_pars_fragment:jm,colorspace_fragment:Qm,colorspace_pars_fragment:tg,envmap_fragment:eg,envmap_common_pars_fragment:ng,envmap_pars_fragment:ig,envmap_pars_vertex:sg,envmap_physical_pars_fragment:mg,envmap_vertex:rg,fog_vertex:og,fog_pars_vertex:ag,fog_fragment:lg,fog_pars_fragment:cg,gradientmap_pars_fragment:hg,lightmap_pars_fragment:ug,lights_lambert_fragment:dg,lights_lambert_pars_fragment:fg,lights_pars_begin:pg,lights_toon_fragment:gg,lights_toon_pars_fragment:_g,lights_phong_fragment:xg,lights_phong_pars_fragment:vg,lights_physical_fragment:yg,lights_physical_pars_fragment:Mg,lights_fragment_begin:bg,lights_fragment_maps:Sg,lights_fragment_end:wg,lightprobes_pars_fragment:Eg,logdepthbuf_fragment:Tg,logdepthbuf_pars_fragment:Ag,logdepthbuf_pars_vertex:Rg,logdepthbuf_vertex:Cg,map_fragment:Ig,map_pars_fragment:Pg,map_particle_fragment:Lg,map_particle_pars_fragment:Dg,metalnessmap_fragment:Ng,metalnessmap_pars_fragment:Ug,morphinstance_vertex:Fg,morphcolor_vertex:Bg,morphnormal_vertex:Og,morphtarget_pars_vertex:zg,morphtarget_vertex:kg,normal_fragment_begin:Hg,normal_fragment_maps:Vg,normal_pars_fragment:Gg,normal_pars_vertex:Wg,normal_vertex:Xg,normalmap_pars_fragment:qg,clearcoat_normal_fragment_begin:Yg,clearcoat_normal_fragment_maps:$g,clearcoat_pars_fragment:Zg,iridescence_pars_fragment:Jg,opaque_fragment:Kg,packing:jg,premultiplied_alpha_fragment:Qg,project_vertex:t_,dithering_fragment:e_,dithering_pars_fragment:n_,roughnessmap_fragment:i_,roughnessmap_pars_fragment:s_,shadowmap_pars_fragment:r_,shadowmap_pars_vertex:o_,shadowmap_vertex:a_,shadowmask_pars_fragment:l_,skinbase_vertex:c_,skinning_pars_vertex:h_,skinning_vertex:u_,skinnormal_vertex:d_,specularmap_fragment:f_,specularmap_pars_fragment:p_,tonemapping_fragment:m_,tonemapping_pars_fragment:g_,transmission_fragment:__,transmission_pars_fragment:x_,uv_pars_fragment:v_,uv_pars_vertex:y_,uv_vertex:M_,worldpos_vertex:b_,background_vert:S_,background_frag:w_,backgroundCube_vert:E_,backgroundCube_frag:T_,cube_vert:A_,cube_frag:R_,depth_vert:C_,depth_frag:I_,distance_vert:P_,distance_frag:L_,equirect_vert:D_,equirect_frag:N_,linedashed_vert:U_,linedashed_frag:F_,meshbasic_vert:B_,meshbasic_frag:O_,meshlambert_vert:z_,meshlambert_frag:k_,meshmatcap_vert:H_,meshmatcap_frag:V_,meshnormal_vert:G_,meshnormal_frag:W_,meshphong_vert:X_,meshphong_frag:q_,meshphysical_vert:Y_,meshphysical_frag:$_,meshtoon_vert:Z_,meshtoon_frag:J_,points_vert:K_,points_frag:j_,shadow_vert:Q_,shadow_frag:t0,sprite_vert:e0,sprite_frag:n0},xt={common:{diffuse:{value:new Ft(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new Ot},alphaMap:{value:null},alphaMapTransform:{value:new Ot},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new Ot}},envmap:{envMap:{value:null},envMapRotation:{value:new Ot},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new Ot}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new Ot}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new Ot},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new Ot},normalScale:{value:new Ht(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new Ot},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new Ot}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new Ot}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new Ot}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new Ft(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},sunLights:{value:[],properties:{direction:{},color:{}}},sunLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},sunShadowMatrix:{value:[]},sunShadowCascade:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null},probesSH:{value:null},probesMin:{value:new I},probesMax:{value:new I},probesResolution:{value:new I}},points:{diffuse:{value:new Ft(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new Ot},alphaTest:{value:0},uvTransform:{value:new Ot}},sprite:{diffuse:{value:new Ft(16777215)},opacity:{value:1},center:{value:new Ht(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new Ot},alphaMap:{value:null},alphaMapTransform:{value:new Ot},alphaTest:{value:0}}},kn={basic:{uniforms:Ze([xt.common,xt.specularmap,xt.envmap,xt.aomap,xt.lightmap,xt.fog]),vertexShader:Wt.meshbasic_vert,fragmentShader:Wt.meshbasic_frag},lambert:{uniforms:Ze([xt.common,xt.specularmap,xt.envmap,xt.aomap,xt.lightmap,xt.emissivemap,xt.bumpmap,xt.normalmap,xt.displacementmap,xt.fog,xt.lights,{emissive:{value:new Ft(0)},envMapIntensity:{value:1}}]),vertexShader:Wt.meshlambert_vert,fragmentShader:Wt.meshlambert_frag},phong:{uniforms:Ze([xt.common,xt.specularmap,xt.envmap,xt.aomap,xt.lightmap,xt.emissivemap,xt.bumpmap,xt.normalmap,xt.displacementmap,xt.fog,xt.lights,{emissive:{value:new Ft(0)},specular:{value:new Ft(1118481)},shininess:{value:30},envMapIntensity:{value:1}}]),vertexShader:Wt.meshphong_vert,fragmentShader:Wt.meshphong_frag},standard:{uniforms:Ze([xt.common,xt.envmap,xt.aomap,xt.lightmap,xt.emissivemap,xt.bumpmap,xt.normalmap,xt.displacementmap,xt.roughnessmap,xt.metalnessmap,xt.fog,xt.lights,{emissive:{value:new Ft(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Wt.meshphysical_vert,fragmentShader:Wt.meshphysical_frag},toon:{uniforms:Ze([xt.common,xt.aomap,xt.lightmap,xt.emissivemap,xt.bumpmap,xt.normalmap,xt.displacementmap,xt.gradientmap,xt.fog,xt.lights,{emissive:{value:new Ft(0)}}]),vertexShader:Wt.meshtoon_vert,fragmentShader:Wt.meshtoon_frag},matcap:{uniforms:Ze([xt.common,xt.bumpmap,xt.normalmap,xt.displacementmap,xt.fog,{matcap:{value:null}}]),vertexShader:Wt.meshmatcap_vert,fragmentShader:Wt.meshmatcap_frag},points:{uniforms:Ze([xt.points,xt.fog]),vertexShader:Wt.points_vert,fragmentShader:Wt.points_frag},dashed:{uniforms:Ze([xt.common,xt.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Wt.linedashed_vert,fragmentShader:Wt.linedashed_frag},depth:{uniforms:Ze([xt.common,xt.displacementmap]),vertexShader:Wt.depth_vert,fragmentShader:Wt.depth_frag},normal:{uniforms:Ze([xt.common,xt.bumpmap,xt.normalmap,xt.displacementmap,{opacity:{value:1}}]),vertexShader:Wt.meshnormal_vert,fragmentShader:Wt.meshnormal_frag},sprite:{uniforms:Ze([xt.sprite,xt.fog]),vertexShader:Wt.sprite_vert,fragmentShader:Wt.sprite_frag},background:{uniforms:{uvTransform:{value:new Ot},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:Wt.background_vert,fragmentShader:Wt.background_frag},backgroundCube:{uniforms:{envMap:{value:null},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new Ot}},vertexShader:Wt.backgroundCube_vert,fragmentShader:Wt.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Wt.cube_vert,fragmentShader:Wt.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Wt.equirect_vert,fragmentShader:Wt.equirect_frag},distance:{uniforms:Ze([xt.common,xt.displacementmap,{referencePosition:{value:new I},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Wt.distance_vert,fragmentShader:Wt.distance_frag},shadow:{uniforms:Ze([xt.lights,xt.fog,{color:{value:new Ft(0)},opacity:{value:1}}]),vertexShader:Wt.shadow_vert,fragmentShader:Wt.shadow_frag}};kn.physical={uniforms:Ze([kn.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new Ot},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new Ot},clearcoatNormalScale:{value:new Ht(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new Ot},dispersion:{value:0},retroreflectivity:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new Ot},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new Ot},sheen:{value:0},sheenColor:{value:new Ft(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new Ot},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new Ot},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new Ot},transmissionSamplerSize:{value:new Ht},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new Ot},attenuationDistance:{value:0},attenuationColor:{value:new Ft(0)},specularColor:{value:new Ft(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new Ot},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new Ot},anisotropyVector:{value:new Ht},anisotropyMap:{value:null},anisotropyMapTransform:{value:new Ot}}]),vertexShader:Wt.meshphysical_vert,fragmentShader:Wt.meshphysical_frag};var Oa={r:0,b:0,g:0},i0=new kt,Ld=new Ot;Ld.set(-1,0,0,0,1,0,0,0,1);function s0(i,t,e,n,s,r){let o=new Ft(0),a=s===!0?0:1,l,c,h=null,d=0,u=null;function p(b){let E=b.isScene===!0?b.background:null;if(E&&E.isTexture){let M=b.backgroundBlurriness>0;E=t.get(E,M)}return E}function g(b){let E=!1,M=p(b);M===null?m(o,a):M&&M.isColor&&(m(M,1),E=!0);let v=i.xr.getEnvironmentBlendMode();v==="additive"?e.buffers.color.setClear(0,0,0,1,r):v==="alpha-blend"&&e.buffers.color.setClear(0,0,0,0,r),(i.autoClear||E)&&(e.buffers.depth.setTest(!0),e.buffers.depth.setMask(!0),e.buffers.color.setMask(!0),i.clear(i.autoClearColor,i.autoClearDepth,i.autoClearStencil))}function _(b,E){let M=p(E);M&&(M.isCubeTexture||M.mapping===hr)?(c===void 0&&(c=new xe(new dn(1,1,1),new He({name:"BackgroundCubeMaterial",uniforms:Bi(kn.backgroundCube.uniforms),vertexShader:kn.backgroundCube.vertexShader,fragmentShader:kn.backgroundCube.fragmentShader,side:Ve,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),c.geometry.deleteAttribute("normal"),c.geometry.deleteAttribute("uv"),c.onBeforeRender=function(v,S,A){this.matrixWorld.copyPosition(A.matrixWorld)},Object.defineProperty(c.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),n.update(c)),c.material.uniforms.envMap.value=M,c.material.uniforms.backgroundBlurriness.value=E.backgroundBlurriness,c.material.uniforms.backgroundIntensity.value=E.backgroundIntensity,c.material.uniforms.backgroundRotation.value.setFromMatrix4(i0.makeRotationFromEuler(E.backgroundRotation)).transpose(),M.isCubeTexture&&M.isRenderTargetTexture===!1&&c.material.uniforms.backgroundRotation.value.premultiply(Ld),c.material.toneMapped=Yt.getTransfer(M.colorSpace)!==te,(h!==M||d!==M.version||u!==i.toneMapping)&&(c.material.needsUpdate=!0,h=M,d=M.version,u=i.toneMapping),c.layers.enableAll(),b.unshift(c,c.geometry,c.material,0,0,null)):M&&M.isTexture&&(l===void 0&&(l=new xe(new yn(2,2),new He({name:"BackgroundMaterial",uniforms:Bi(kn.background.uniforms),vertexShader:kn.background.vertexShader,fragmentShader:kn.background.fragmentShader,side:Bn,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute("normal"),Object.defineProperty(l.material,"map",{get:function(){return this.uniforms.t2D.value}}),n.update(l)),l.material.uniforms.t2D.value=M,l.material.uniforms.backgroundIntensity.value=E.backgroundIntensity,l.material.toneMapped=Yt.getTransfer(M.colorSpace)!==te,M.matrixAutoUpdate===!0&&M.updateMatrix(),l.material.uniforms.uvTransform.value.copy(M.matrix),(h!==M||d!==M.version||u!==i.toneMapping)&&(l.material.needsUpdate=!0,h=M,d=M.version,u=i.toneMapping),l.layers.enableAll(),b.unshift(l,l.geometry,l.material,0,0,null))}function m(b,E){b.getRGB(Oa,Tc(i)),e.buffers.color.setClear(Oa.r,Oa.g,Oa.b,E,r)}function f(){c!==void 0&&(c.geometry.dispose(),c.material.dispose(),c=void 0),l!==void 0&&(l.geometry.dispose(),l.material.dispose(),l=void 0)}return{getClearColor:function(){return o},setClearColor:function(b,E=1){o.set(b),a=E,m(o,a)},getClearAlpha:function(){return a},setClearAlpha:function(b){a=b,m(o,a)},render:g,addToRenderList:_,dispose:f}}function r0(i,t){let e=i.getParameter(i.MAX_VERTEX_ATTRIBS),n={},s=u(null),r=s,o=!1;function a(L,N,U,C,B){let z=!1,W=d(L,C,U,N);r!==W&&(r=W,c(r.object)),z=p(L,C,U,B),z&&g(L,C,U,B),B!==null&&t.update(B,i.ELEMENT_ARRAY_BUFFER),(z||o)&&(o=!1,M(L,N,U,C),B!==null&&i.bindBuffer(i.ELEMENT_ARRAY_BUFFER,t.get(B).buffer))}function l(){return i.createVertexArray()}function c(L){return i.bindVertexArray(L)}function h(L){return i.deleteVertexArray(L)}function d(L,N,U,C){let B=C.wireframe===!0,z=n[N.id];z===void 0&&(z={},n[N.id]=z);let W=L.isInstancedMesh===!0?L.id:0,F=z[W];F===void 0&&(F={},z[W]=F);let D=F[U.id];D===void 0&&(D={},F[U.id]=D);let X=D[B];return X===void 0&&(X=u(l()),D[B]=X),X}function u(L){let N=[],U=[],C=[];for(let B=0;B=0){let Z=B[D],G=z[D];if(G===void 0&&(D==="instanceMatrix"&&L.instanceMatrix&&(G=L.instanceMatrix),D==="instanceColor"&&L.instanceColor&&(G=L.instanceColor)),Z===void 0||Z.attribute!==G||G&&Z.data!==G.data)return!0;W++}return r.attributesNum!==W||r.index!==C}function g(L,N,U,C){let B={},z=N.attributes,W=0,F=U.getAttributes();for(let D in F)if(F[D].location>=0){let Z=z[D];Z===void 0&&(D==="instanceMatrix"&&L.instanceMatrix&&(Z=L.instanceMatrix),D==="instanceColor"&&L.instanceColor&&(Z=L.instanceColor));let G={};G.attribute=Z,Z&&Z.data&&(G.data=Z.data),B[D]=G,W++}r.attributes=B,r.attributesNum=W,r.index=C}function _(){let L=r.newAttributes;for(let N=0,U=L.length;N=0){let X=B[F];if(X===void 0&&(F==="instanceMatrix"&&L.instanceMatrix&&(X=L.instanceMatrix),F==="instanceColor"&&L.instanceColor&&(X=L.instanceColor)),X!==void 0){let Z=X.normalized,G=X.itemSize,Q=t.get(X);if(Q===void 0)continue;let lt=Q.buffer,ct=Q.type,et=Q.bytesPerElement,V=ct===i.INT||ct===i.UNSIGNED_INT||X.gpuType===Qo;if(X.isInterleavedBufferAttribute){let j=X.data,ut=j.stride,Lt=X.offset;if(j.isInstancedInterleavedBuffer){for(let Mt=0;Mt0&&i.getShaderPrecisionFormat(i.FRAGMENT_SHADER,i.HIGH_FLOAT).precision>0)return"highp";A="mediump"}return A==="mediump"&&i.getShaderPrecisionFormat(i.VERTEX_SHADER,i.MEDIUM_FLOAT).precision>0&&i.getShaderPrecisionFormat(i.FRAGMENT_SHADER,i.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let c=e.precision!==void 0?e.precision:"highp",h=l(c);h!==c&&(Dt("WebGLRenderer:",c,"not supported, using",h,"instead."),c=h);let d=e.logarithmicDepthBuffer===!0,u=e.reversedDepthBuffer===!0&&t.has("EXT_clip_control");e.reversedDepthBuffer===!0&&u===!1&&Dt("WebGLRenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer.");let p=i.getParameter(i.MAX_TEXTURE_IMAGE_UNITS),g=i.getParameter(i.MAX_VERTEX_TEXTURE_IMAGE_UNITS),_=i.getParameter(i.MAX_TEXTURE_SIZE),m=i.getParameter(i.MAX_CUBE_MAP_TEXTURE_SIZE),f=i.getParameter(i.MAX_VERTEX_ATTRIBS),b=i.getParameter(i.MAX_VERTEX_UNIFORM_VECTORS),E=i.getParameter(i.MAX_VARYING_VECTORS),M=i.getParameter(i.MAX_FRAGMENT_UNIFORM_VECTORS),v=i.getParameter(i.MAX_SAMPLES),S=i.getParameter(i.SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:r,getMaxPrecision:l,textureFormatReadable:o,textureTypeReadable:a,precision:c,logarithmicDepthBuffer:d,reversedDepthBuffer:u,maxTextures:p,maxVertexTextures:g,maxTextureSize:_,maxCubemapSize:m,maxAttributes:f,maxVertexUniforms:b,maxVaryings:E,maxFragmentUniforms:M,maxSamples:v,samples:S}}function l0(i){let t=this,e=null,n=0,s=!1,r=!1,o=new _e,a=new Ot,l={value:null,needsUpdate:!1};this.uniform=l,this.numPlanes=0,this.numIntersection=0,this.init=function(d,u){let p=d.length!==0||u||n!==0||s;return s=u,n=d.length,p},this.beginShadows=function(){r=!0,h(null)},this.endShadows=function(){r=!1},this.setGlobalState=function(d,u){e=h(d,u,0)},this.setState=function(d,u,p){let g=d.clippingPlanes,_=d.clipIntersection,m=d.clipShadows,f=i.get(d);if(!s||g===null||g.length===0||r&&!m)r?h(null):c();else{let b=r?0:n,E=b*4,M=f.clippingState||null;l.value=M,M=h(g,u,E,p);for(let v=0;v!==E;++v)M[v]=e[v];f.clippingState=M,this.numIntersection=_?this.numPlanes:0,this.numPlanes+=b}};function c(){l.value!==e&&(l.value=e,l.needsUpdate=n>0),t.numPlanes=n,t.numIntersection=0}function h(d,u,p,g){let _=d!==null?d.length:0,m=null;if(_!==0){if(m=l.value,g!==!0||m===null){let f=p+_*4,b=u.matrixWorldInverse;a.getNormalMatrix(b),(m===null||m.length0&&this._blur(l,0,0,e),this._applyPMREM(l),this._cleanup(l),l}fromEquirectangular(t,e=null){return this._fromTexture(t,e)}fromCubemap(t,e=null){return this._fromTexture(t,e)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=fd(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=dd(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose(),this._backgroundBox!==null&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSize(t){this._lodMax=Math.floor(Math.log2(t)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._ggxMaterial!==null&&this._ggxMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let t=0;t2?v:0,v,v),d.setRenderTarget(s),f&&d.render(_,l),d.render(t,l)}d.toneMapping=p,d.autoClear=u,t.background=b}_textureToCubeUV(t,e){let n=this._renderer,s=t.mapping===pi||t.mapping===Fi;s?(this._cubemapMaterial===null&&(this._cubemapMaterial=fd()),this._cubemapMaterial.uniforms.flipEnvMap.value=t.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=dd());let r=s?this._cubemapMaterial:this._equirectMaterial,o=this._lodMeshes[0];o.material=r;let a=r.uniforms;a.envMap.value=t;let l=this._cubeSize;ws(e,0,0,3*l,2*l),n.setRenderTarget(e),n.render(o,xr)}_applyPMREM(t){let e=this._renderer,n=e.autoClear;e.autoClear=!1;let s=this._lodMeshes.length;for(let r=1;rg-Es?n-g+Es:0),f=4*(this._cubeSize-_);l.envMap.value=t.texture,l.roughness.value=p,l.mipInt.value=g-e,ws(r,m,f,3*_,2*_),s.setRenderTarget(r),s.render(a,xr),l.envMap.value=r.texture,l.roughness.value=0,l.mipInt.value=g-n,ws(t,m,f,3*_,2*_),s.setRenderTarget(t),s.render(a,xr)}_blur(t,e,n,s){let r=this._pingPongRenderTarget,o=Math.min(s,Math.PI)/Math.SQRT2;this._blurPass(t,r,e,n,o),this._blurPass(r,t,n,n,o)}_blurPass(t,e,n,s,r){let o=this._renderer,a=this._blurMaterial,l=this._lodMeshes[s];l.material=a;let c=a.uniforms;c.envMap.value=t.texture,c.sigma.value=r,c.mipInt.value=this._lodMax-n;let h=this._sizeLods[s],d=3*h*(s>this._lodMax-Es?s-this._lodMax+Es:0),u=4*(this._cubeSize-h);ws(e,d,u,3*h,2*h),o.setRenderTarget(e),o.render(l,xr)}};function f0(i){let t=[],e=[],n=i,s=i-Es+1+c0;for(let r=0;r2?0:-1,M=[b,E,0,b+2/3,E,0,b+2/3,E+1,0,b,E,0,b+2/3,E+1,0,b,E+1,0];g.set(M,p*u*f);for(let v=0;vEs&&n--}return{lodMeshes:e,sizeLods:t}}function ud(i,t,e){let n=new Fe(i,t,e);return n.texture.mapping=hr,n.texture.name="PMREM.cubeUv",n.scissorTest=!0,n}function ws(i,t,e,n,s){i.viewport.set(t,e,n,s),i.scissor.set(t,e,n,s)}function p0(i,t,e){return new He({name:"PMREMGGXConvolution",defines:{GGX_SAMPLES:u0,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/e,CUBEUV_MAX_MIP:`${i}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:Va(),fragmentShader:` precision highp float; precision highp int; @@ -3924,7 +3924,7 @@ void main() { gl_FragColor = vec4(prefilteredColor, 1.0); } - `,blending:On,depthTest:!1,depthWrite:!1})}function f0(i,t,e){return new He({name:"SphericalGaussianBlur",defines:{SAMPLES:l0,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/e,CUBEUV_MAX_MIP:`${i}.0`},uniforms:{envMap:{value:null},sigma:{value:0},mipInt:{value:0}},vertexShader:Va(),fragmentShader:` + `,blending:On,depthTest:!1,depthWrite:!1})}function m0(i,t,e){return new He({name:"SphericalGaussianBlur",defines:{SAMPLES:h0,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/e,CUBEUV_MAX_MIP:`${i}.0`},uniforms:{envMap:{value:null},sigma:{value:0},mipInt:{value:0}},vertexShader:Va(),fragmentShader:` precision highp float; precision highp int; @@ -3984,7 +3984,7 @@ void main() { gl_FragColor = vec4( accumColor / accumWeight, 1.0 ); } - `,blending:On,depthTest:!1,depthWrite:!1})}function ud(){return new He({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:Va(),fragmentShader:` + `,blending:On,depthTest:!1,depthWrite:!1})}function dd(){return new He({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:Va(),fragmentShader:` precision mediump float; precision mediump int; @@ -4003,7 +4003,7 @@ void main() { gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); } - `,blending:On,depthTest:!1,depthWrite:!1})}function dd(){return new He({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:Va(),fragmentShader:` + `,blending:On,depthTest:!1,depthWrite:!1})}function fd(){return new He({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:Va(),fragmentShader:` precision mediump float; precision mediump int; @@ -4034,7 +4034,7 @@ void main() { gl_Position = vec4( position, 1.0 ); } - `}var Ha=class extends Fe{constructor(t=1,e={}){super(t,t,e),this.isWebGLCubeRenderTarget=!0;let n={width:t,height:t,depth:1},s=[n,n,n,n,n,n];this.texture=new js(s),this._setTextureOptions(e),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(t,e){this.texture.type=e.type,this.texture.colorSpace=e.colorSpace,this.texture.generateMipmaps=e.generateMipmaps,this.texture.minFilter=e.minFilter,this.texture.magFilter=e.magFilter;let n={uniforms:{tEquirect:{value:null}},vertexShader:` + `}var Ha=class extends Fe{constructor(t=1,e={}){super(t,t,e),this.isWebGLCubeRenderTarget=!0;let n={width:t,height:t,depth:1},s=[n,n,n,n,n,n];this.texture=new Qs(s),this._setTextureOptions(e),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(t,e){this.texture.type=e.type,this.texture.colorSpace=e.colorSpace,this.texture.generateMipmaps=e.generateMipmaps,this.texture.minFilter=e.minFilter,this.texture.magFilter=e.magFilter;let n={uniforms:{tEquirect:{value:null}},vertexShader:` varying vec3 vWorldDirection; @@ -4069,7 +4069,7 @@ void main() { gl_FragColor = texture2D( tEquirect, sampleUV ); } - `},s=new dn(5,5,5),r=new He({name:"CubemapFromEquirect",uniforms:Fi(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:Ve,blending:On});r.uniforms.tEquirect.value=e;let o=new _e(s,r),a=e.minFilter;return e.minFilter===mi&&(e.minFilter=ze),new qo(1,10,this).update(t,o),e.minFilter=a,o.geometry.dispose(),o.material.dispose(),this}clear(t,e=!0,n=!0,s=!0){let r=t.getRenderTarget();for(let o=0;o<6;o++)t.setRenderTarget(this,o),t.clear(e,n,s);t.setRenderTarget(r)}};function p0(i){let t=new WeakMap,e=new WeakMap,n=null;function s(u,p=!1){return u==null?null:p?o(u):r(u)}function r(u){if(u&&u.isTexture){let p=u.mapping;if(p===Jo||p===Ko)if(t.has(u)){let g=t.get(u).texture;return a(g,u.mapping)}else{let g=u.image;if(g&&g.height>0){let _=new Ha(g.height);return _.fromEquirectangularTexture(i,u),t.set(u,_),u.addEventListener("dispose",c),a(_.texture,u.mapping)}else return null}}return u}function o(u){if(u&&u.isTexture){let p=u.mapping,g=p===Jo||p===Ko,_=p===pi||p===Ui;if(g||_){let m=e.get(u),f=m!==void 0?m.texture.pmremVersion:0;if(u.isRenderTargetTexture&&u.pmremVersion!==f)return n===null&&(n=new ka(i)),m=g?n.fromEquirectangular(u,m):n.fromCubemap(u,m),m.texture.pmremVersion=u.pmremVersion,e.set(u,m),m.texture;if(m!==void 0)return m.texture;{let b=u.image;return g&&b&&b.height>0||_&&b&&l(b)?(n===null&&(n=new ka(i)),m=g?n.fromEquirectangular(u):n.fromCubemap(u),m.texture.pmremVersion=u.pmremVersion,e.set(u,m),u.addEventListener("dispose",h),m.texture):null}}}return u}function a(u,p){return p===Jo?u.mapping=pi:p===Ko&&(u.mapping=Ui),u}function l(u){let p=0,g=6;for(let _=0;_=65535?Js:Zs)(u,1);m.version=_;let f=r.get(d);f&&t.remove(f),r.set(d,m)}function h(d){let u=r.get(d);if(u){let p=d.index;p!==null&&u.versiont.maxTextureSize&&(v=Math.ceil(M/t.maxTextureSize),M=t.maxTextureSize);let S=new Float32Array(M*v*4*d),A=new $s(S,M,v,d);A.type=Ge,A.needsUpdate=!0;let x=E*4;for(let R=0;R0){let _=new Ha(g.height);return _.fromEquirectangularTexture(i,u),t.set(u,_),u.addEventListener("dispose",c),a(_.texture,u.mapping)}else return null}}return u}function o(u){if(u&&u.isTexture){let p=u.mapping,g=p===Jo||p===Ko,_=p===pi||p===Fi;if(g||_){let m=e.get(u),f=m!==void 0?m.texture.pmremVersion:0;if(u.isRenderTargetTexture&&u.pmremVersion!==f)return n===null&&(n=new ka(i)),m=g?n.fromEquirectangular(u,m):n.fromCubemap(u,m),m.texture.pmremVersion=u.pmremVersion,e.set(u,m),m.texture;if(m!==void 0)return m.texture;{let b=u.image;return g&&b&&b.height>0||_&&b&&l(b)?(n===null&&(n=new ka(i)),m=g?n.fromEquirectangular(u):n.fromCubemap(u),m.texture.pmremVersion=u.pmremVersion,e.set(u,m),u.addEventListener("dispose",h),m.texture):null}}}return u}function a(u,p){return p===Jo?u.mapping=pi:p===Ko&&(u.mapping=Fi),u}function l(u){let p=0,g=6;for(let _=0;_=65535?Ks:Js)(u,1);m.version=_;let f=r.get(d);f&&t.remove(f),r.set(d,m)}function h(d){let u=r.get(d);if(u){let p=d.index;p!==null&&u.versiont.maxTextureSize&&(v=Math.ceil(M/t.maxTextureSize),M=t.maxTextureSize);let S=new Float32Array(M*v*4*d),A=new Zs(S,M,v,d);A.type=Ge,A.needsUpdate=!0;let x=E*4;for(let R=0;R0&&b[0].isRenderPass===!0;let v=o.width,S=o.height;b.length>0&&a===null&&(a=new Fe(v,S,{type:Sn,depthBuffer:!1,stencilBuffer:!1}),l=new Fe(v,S,{type:Sn,depthBuffer:!1,stencilBuffer:!1}));for(let A=0;A0)return i;let s=t*e,r=fd[s];if(r===void 0&&(r=new Float32Array(s),fd[s]=r),t!==0){n.toArray(r,0);for(let o=1,a=0;o!==t;++o)a+=e,i[o].toArray(r,a)}return r}function Pe(i,t){if(i.length!==t.length)return!1;for(let e=0,n=i.length;e0&&(this.seq=s.concat(r))}setValue(t,e,n,s){let r=this.map[e];r!==void 0&&r.setValue(t,n,s)}setOptional(t,e,n){let s=e[n];s!==void 0&&this.setValue(t,n,s)}static upload(t,e,n,s){for(let r=0,o=e.length;r!==o;++r){let a=e[r],l=n[a.id];l.needsUpdate!==!1&&a.setValue(t,l.value,s)}}static seqWithValue(t,e){let n=[];for(let s=0,r=t.length;s!==r;++s){let o=t[s];o.id in e&&n.push(o)}return n}};function vd(i,t,e){let n=i.createShader(t);return i.shaderSource(n,e),i.compileShader(n),n}var hx=37297,ux=0;function dx(i,t){let e=i.split(` + }`,depthTest:!1,depthWrite:!1}),d=new xe(c,h),u=new Fn(-1,1,1,-1,0,1),p=null,g=null,_=!1,m,f=null,b=[],E=!1;this.setSize=function(M,v){o.setSize(M,v),a!==null&&a.setSize(M,v),l!==null&&l.setSize(M,v);for(let S=0;S0&&b[0].isRenderPass===!0;let v=o.width,S=o.height;b.length>0&&a===null&&(a=new Fe(v,S,{type:Sn,depthBuffer:!1,stencilBuffer:!1}),l=new Fe(v,S,{type:Sn,depthBuffer:!1,stencilBuffer:!1}));for(let A=0;A0)return i;let s=t*e,r=pd[s];if(r===void 0&&(r=new Float32Array(s),pd[s]=r),t!==0){n.toArray(r,0);for(let o=1,a=0;o!==t;++o)a+=e,i[o].toArray(r,a)}return r}function Pe(i,t){if(i.length!==t.length)return!1;for(let e=0,n=i.length;e0&&(this.seq=s.concat(r))}setValue(t,e,n,s){let r=this.map[e];r!==void 0&&r.setValue(t,n,s)}setOptional(t,e,n){let s=e[n];s!==void 0&&this.setValue(t,n,s)}static upload(t,e,n,s){for(let r=0,o=e.length;r!==o;++r){let a=e[r],l=n[a.id];l.needsUpdate!==!1&&a.setValue(t,l.value,s)}}static seqWithValue(t,e){let n=[];for(let s=0,r=t.length;s!==r;++s){let o=t[s];o.id in e&&n.push(o)}return n}};function yd(i,t,e){let n=i.createShader(t);return i.shaderSource(n,e),i.compileShader(n),n}var dx=37297,fx=0;function px(i,t){let e=i.split(` `),n=[],s=Math.max(t-6,0),r=Math.min(t+6,e.length);for(let o=s;o":" "} ${a}: ${e[o]}`)}return n.join(` -`)}var yd=new Ot;function fx(i){Yt._getMatrix(yd,Yt.workingColorSpace,i);let t=`mat3( ${yd.elements.map(e=>e.toFixed(4))} )`;switch(Yt.getTransfer(i)){case Xs:return[t,"LinearTransferOETF"];case te:return[t,"sRGBTransferOETF"];default:return Dt("WebGLProgram: Unsupported color space: ",i),[t,"LinearTransferOETF"]}}function Md(i,t,e){let n=i.getShaderParameter(t,i.COMPILE_STATUS),r=(i.getShaderInfoLog(t)||"").trim();if(n&&r==="")return"";let o=/ERROR: 0:(\d+)/.exec(r);if(o){let a=parseInt(o[1]);return e.toUpperCase()+` +`)}var Md=new Ot;function mx(i){Yt._getMatrix(Md,Yt.workingColorSpace,i);let t=`mat3( ${Md.elements.map(e=>e.toFixed(4))} )`;switch(Yt.getTransfer(i)){case qs:return[t,"LinearTransferOETF"];case te:return[t,"sRGBTransferOETF"];default:return Dt("WebGLProgram: Unsupported color space: ",i),[t,"LinearTransferOETF"]}}function bd(i,t,e){let n=i.getShaderParameter(t,i.COMPILE_STATUS),r=(i.getShaderInfoLog(t)||"").trim();if(n&&r==="")return"";let o=/ERROR: 0:(\d+)/.exec(r);if(o){let a=parseInt(o[1]);return e.toUpperCase()+` `+r+` -`+dx(i.getShaderSource(t),a)}else return r}function px(i,t){let e=fx(t);return[`vec4 ${i}( vec4 value ) {`,` return ${e[1]}( vec4( value.rgb * ${e[0]}, value.a ) );`,"}"].join(` -`)}var mx={[rc]:"Linear",[oc]:"Reinhard",[ac]:"Cineon",[lc]:"ACESFilmic",[hc]:"AgX",[uc]:"Neutral",[cc]:"Custom"};function gx(i,t){let e=mx[t];return e===void 0?(Dt("WebGLProgram: Unsupported toneMapping:",t),"vec3 "+i+"( vec3 color ) { return LinearToneMapping( color ); }"):"vec3 "+i+"( vec3 color ) { return "+e+"ToneMapping( color ); }"}var za=new I;function _x(){Yt.getLuminanceCoefficients(za);let i=za.x.toFixed(4),t=za.y.toFixed(4),e=za.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${i}, ${t}, ${e} );`," return dot( weights, rgb );","}"].join(` -`)}function xx(i){return[i.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",i.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(vr).join(` -`)}function vx(i){let t=[];for(let e in i){let n=i[e];n!==!1&&t.push("#define "+e+" "+n)}return t.join(` -`)}function yx(i,t){let e={},n=i.getProgramParameter(t,i.ACTIVE_ATTRIBUTES);for(let s=0;s/gm;function Xc(i){return i.replace(Mx,Sx)}var bx=new Map;function Sx(i,t){let e=Wt[t];if(e===void 0){let n=bx.get(t);if(n!==void 0)e=Wt[n],Dt('WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',t,n);else throw new Error("THREE.WebGLProgram: Can not resolve #include <"+t+">")}return Xc(e)}var wx=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function wd(i){return i.replace(wx,Ex)}function Ex(i,t,e,n){let s="";for(let r=parseInt(t);r/gm;function Xc(i){return i.replace(Sx,Ex)}var wx=new Map;function Ex(i,t){let e=Wt[t];if(e===void 0){let n=wx.get(t);if(n!==void 0)e=Wt[n],Dt('WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',t,n);else throw new Error("THREE.WebGLProgram: Can not resolve #include <"+t+">")}return Xc(e)}var Tx=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function Ed(i){return i.replace(Tx,Ax)}function Ax(i,t,e,n){let s="";for(let r=parseInt(t);r0&&(m+=` -`),f=["#define SHADER_TYPE "+e.shaderType,"#define SHADER_NAME "+e.shaderName,g].filter(vr).join(` +`),f=["#define SHADER_TYPE "+e.shaderType,"#define SHADER_NAME "+e.shaderName,g].filter(yr).join(` `),f.length>0&&(f+=` -`)):(m=[Ed(e),"#define SHADER_TYPE "+e.shaderType,"#define SHADER_NAME "+e.shaderName,g,e.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",e.batching?"#define USE_BATCHING":"",e.batchingColor?"#define USE_BATCHING_COLOR":"",e.instancing?"#define USE_INSTANCING":"",e.instancingColor?"#define USE_INSTANCING_COLOR":"",e.instancingMorph?"#define USE_INSTANCING_MORPH":"",e.useFog&&e.fog?"#define USE_FOG":"",e.useFog&&e.fogExp2?"#define FOG_EXP2":"",e.map?"#define USE_MAP":"",e.envMap?"#define USE_ENVMAP":"",e.envMap?"#define "+h:"",e.lightMap?"#define USE_LIGHTMAP":"",e.aoMap?"#define USE_AOMAP":"",e.bumpMap?"#define USE_BUMPMAP":"",e.normalMap?"#define USE_NORMALMAP":"",e.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",e.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",e.displacementMap?"#define USE_DISPLACEMENTMAP":"",e.emissiveMap?"#define USE_EMISSIVEMAP":"",e.anisotropy?"#define USE_ANISOTROPY":"",e.anisotropyMap?"#define USE_ANISOTROPYMAP":"",e.clearcoatMap?"#define USE_CLEARCOATMAP":"",e.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",e.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",e.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",e.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",e.specularMap?"#define USE_SPECULARMAP":"",e.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",e.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",e.roughnessMap?"#define USE_ROUGHNESSMAP":"",e.metalnessMap?"#define USE_METALNESSMAP":"",e.alphaMap?"#define USE_ALPHAMAP":"",e.alphaHash?"#define USE_ALPHAHASH":"",e.transmission?"#define USE_TRANSMISSION":"",e.transmissionMap?"#define USE_TRANSMISSIONMAP":"",e.thicknessMap?"#define USE_THICKNESSMAP":"",e.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",e.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",e.mapUv?"#define MAP_UV "+e.mapUv:"",e.alphaMapUv?"#define ALPHAMAP_UV "+e.alphaMapUv:"",e.lightMapUv?"#define LIGHTMAP_UV "+e.lightMapUv:"",e.aoMapUv?"#define AOMAP_UV "+e.aoMapUv:"",e.emissiveMapUv?"#define EMISSIVEMAP_UV "+e.emissiveMapUv:"",e.bumpMapUv?"#define BUMPMAP_UV "+e.bumpMapUv:"",e.normalMapUv?"#define NORMALMAP_UV "+e.normalMapUv:"",e.displacementMapUv?"#define DISPLACEMENTMAP_UV "+e.displacementMapUv:"",e.metalnessMapUv?"#define METALNESSMAP_UV "+e.metalnessMapUv:"",e.roughnessMapUv?"#define ROUGHNESSMAP_UV "+e.roughnessMapUv:"",e.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+e.anisotropyMapUv:"",e.clearcoatMapUv?"#define CLEARCOATMAP_UV "+e.clearcoatMapUv:"",e.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+e.clearcoatNormalMapUv:"",e.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+e.clearcoatRoughnessMapUv:"",e.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+e.iridescenceMapUv:"",e.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+e.iridescenceThicknessMapUv:"",e.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+e.sheenColorMapUv:"",e.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+e.sheenRoughnessMapUv:"",e.specularMapUv?"#define SPECULARMAP_UV "+e.specularMapUv:"",e.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+e.specularColorMapUv:"",e.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+e.specularIntensityMapUv:"",e.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+e.transmissionMapUv:"",e.thicknessMapUv?"#define THICKNESSMAP_UV "+e.thicknessMapUv:"",e.vertexTangents&&e.flatShading===!1?"#define USE_TANGENT":"",e.vertexNormals?"#define HAS_NORMAL":"",e.vertexColors?"#define USE_COLOR":"",e.vertexAlphas?"#define USE_COLOR_ALPHA":"",e.vertexUv1s?"#define USE_UV1":"",e.vertexUv2s?"#define USE_UV2":"",e.vertexUv3s?"#define USE_UV3":"",e.pointsUvs?"#define USE_POINTS_UV":"",e.flatShading?"#define FLAT_SHADED":"",e.skinning?"#define USE_SKINNING":"",e.morphTargets?"#define USE_MORPHTARGETS":"",e.morphNormals&&e.flatShading===!1?"#define USE_MORPHNORMALS":"",e.morphColors?"#define USE_MORPHCOLORS":"",e.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+e.morphTextureStride:"",e.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+e.morphTargetsCount:"",e.doubleSided?"#define DOUBLE_SIDED":"",e.flipSided?"#define FLIP_SIDED":"",e.shadowMapEnabled?"#define USE_SHADOWMAP":"",e.shadowMapEnabled?"#define "+l:"",e.sizeAttenuation?"#define USE_SIZEATTENUATION":"",e.numLightProbes>0?"#define USE_LIGHT_PROBES":"",e.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",e.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING"," attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR"," attribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH"," uniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1"," attribute vec2 uv1;","#endif","#ifdef USE_UV2"," attribute vec2 uv2;","#endif","#ifdef USE_UV3"," attribute vec2 uv3;","#endif","#ifdef USE_TANGENT"," attribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )"," attribute vec4 color;","#elif defined( USE_COLOR )"," attribute vec3 color;","#endif","#ifdef USE_SKINNING"," attribute vec4 skinIndex;"," attribute vec4 skinWeight;","#endif",` -`].filter(vr).join(` -`),f=[Ed(e),"#define SHADER_TYPE "+e.shaderType,"#define SHADER_NAME "+e.shaderName,g,e.useFog&&e.fog?"#define USE_FOG":"",e.useFog&&e.fogExp2?"#define FOG_EXP2":"",e.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",e.map?"#define USE_MAP":"",e.matcap?"#define USE_MATCAP":"",e.envMap?"#define USE_ENVMAP":"",e.envMap?"#define "+c:"",e.envMap?"#define "+h:"",e.envMap?"#define "+d:"",u?"#define CUBEUV_TEXEL_WIDTH "+u.texelWidth:"",u?"#define CUBEUV_TEXEL_HEIGHT "+u.texelHeight:"",u?"#define CUBEUV_MAX_MIP "+u.maxMip+".0":"",e.lightMap?"#define USE_LIGHTMAP":"",e.aoMap?"#define USE_AOMAP":"",e.bumpMap?"#define USE_BUMPMAP":"",e.normalMap?"#define USE_NORMALMAP":"",e.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",e.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",e.packedNormalMap?"#define USE_PACKED_NORMALMAP":"",e.emissiveMap?"#define USE_EMISSIVEMAP":"",e.anisotropy?"#define USE_ANISOTROPY":"",e.anisotropyMap?"#define USE_ANISOTROPYMAP":"",e.clearcoat?"#define USE_CLEARCOAT":"",e.clearcoatMap?"#define USE_CLEARCOATMAP":"",e.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",e.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",e.dispersion?"#define USE_DISPERSION":"",e.retroreflection?"#define USE_RETROREFLECTION":"",e.iridescence?"#define USE_IRIDESCENCE":"",e.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",e.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",e.specularMap?"#define USE_SPECULARMAP":"",e.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",e.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",e.roughnessMap?"#define USE_ROUGHNESSMAP":"",e.metalnessMap?"#define USE_METALNESSMAP":"",e.alphaMap?"#define USE_ALPHAMAP":"",e.alphaTest?"#define USE_ALPHATEST":"",e.alphaHash?"#define USE_ALPHAHASH":"",e.sheen?"#define USE_SHEEN":"",e.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",e.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",e.transmission?"#define USE_TRANSMISSION":"",e.transmissionMap?"#define USE_TRANSMISSIONMAP":"",e.thicknessMap?"#define USE_THICKNESSMAP":"",e.vertexTangents&&e.flatShading===!1?"#define USE_TANGENT":"",e.vertexColors||e.instancingColor?"#define USE_COLOR":"",e.vertexAlphas||e.batchingColor?"#define USE_COLOR_ALPHA":"",e.vertexUv1s?"#define USE_UV1":"",e.vertexUv2s?"#define USE_UV2":"",e.vertexUv3s?"#define USE_UV3":"",e.pointsUvs?"#define USE_POINTS_UV":"",e.gradientMap?"#define USE_GRADIENTMAP":"",e.flatShading?"#define FLAT_SHADED":"",e.doubleSided?"#define DOUBLE_SIDED":"",e.flipSided?"#define FLIP_SIDED":"",e.shadowMapEnabled?"#define USE_SHADOWMAP":"",e.shadowMapEnabled?"#define "+l:"",e.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",e.numLightProbes>0?"#define USE_LIGHT_PROBES":"",e.numLightProbeGrids>0?"#define USE_LIGHT_PROBES_GRID":"",e.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",e.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",e.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",e.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",e.toneMapping!==Mn?"#define TONE_MAPPING":"",e.toneMapping!==Mn?Wt.tonemapping_pars_fragment:"",e.toneMapping!==Mn?gx("toneMapping",e.toneMapping):"",e.dithering?"#define DITHERING":"",e.opaque?"#define OPAQUE":"",Wt.colorspace_pars_fragment,px("linearToOutputTexel",e.outputColorSpace),_x(),e.useDepthPacking?"#define DEPTH_PACKING "+e.depthPacking:"",` -`].filter(vr).join(` -`)),o=Xc(o),o=bd(o,e),o=Sd(o,e),a=Xc(a),a=bd(a,e),a=Sd(a,e),o=wd(o),a=wd(a),e.isRawShaderMaterial!==!0&&(b=`#version 300 es +`)):(m=[Td(e),"#define SHADER_TYPE "+e.shaderType,"#define SHADER_NAME "+e.shaderName,g,e.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",e.batching?"#define USE_BATCHING":"",e.batchingColor?"#define USE_BATCHING_COLOR":"",e.instancing?"#define USE_INSTANCING":"",e.instancingColor?"#define USE_INSTANCING_COLOR":"",e.instancingMorph?"#define USE_INSTANCING_MORPH":"",e.useFog&&e.fog?"#define USE_FOG":"",e.useFog&&e.fogExp2?"#define FOG_EXP2":"",e.map?"#define USE_MAP":"",e.envMap?"#define USE_ENVMAP":"",e.envMap?"#define "+h:"",e.lightMap?"#define USE_LIGHTMAP":"",e.aoMap?"#define USE_AOMAP":"",e.bumpMap?"#define USE_BUMPMAP":"",e.normalMap?"#define USE_NORMALMAP":"",e.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",e.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",e.displacementMap?"#define USE_DISPLACEMENTMAP":"",e.emissiveMap?"#define USE_EMISSIVEMAP":"",e.anisotropy?"#define USE_ANISOTROPY":"",e.anisotropyMap?"#define USE_ANISOTROPYMAP":"",e.clearcoatMap?"#define USE_CLEARCOATMAP":"",e.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",e.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",e.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",e.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",e.specularMap?"#define USE_SPECULARMAP":"",e.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",e.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",e.roughnessMap?"#define USE_ROUGHNESSMAP":"",e.metalnessMap?"#define USE_METALNESSMAP":"",e.alphaMap?"#define USE_ALPHAMAP":"",e.alphaHash?"#define USE_ALPHAHASH":"",e.transmission?"#define USE_TRANSMISSION":"",e.transmissionMap?"#define USE_TRANSMISSIONMAP":"",e.thicknessMap?"#define USE_THICKNESSMAP":"",e.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",e.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",e.mapUv?"#define MAP_UV "+e.mapUv:"",e.alphaMapUv?"#define ALPHAMAP_UV "+e.alphaMapUv:"",e.lightMapUv?"#define LIGHTMAP_UV "+e.lightMapUv:"",e.aoMapUv?"#define AOMAP_UV "+e.aoMapUv:"",e.emissiveMapUv?"#define EMISSIVEMAP_UV "+e.emissiveMapUv:"",e.bumpMapUv?"#define BUMPMAP_UV "+e.bumpMapUv:"",e.normalMapUv?"#define NORMALMAP_UV "+e.normalMapUv:"",e.displacementMapUv?"#define DISPLACEMENTMAP_UV "+e.displacementMapUv:"",e.metalnessMapUv?"#define METALNESSMAP_UV "+e.metalnessMapUv:"",e.roughnessMapUv?"#define ROUGHNESSMAP_UV "+e.roughnessMapUv:"",e.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+e.anisotropyMapUv:"",e.clearcoatMapUv?"#define CLEARCOATMAP_UV "+e.clearcoatMapUv:"",e.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+e.clearcoatNormalMapUv:"",e.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+e.clearcoatRoughnessMapUv:"",e.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+e.iridescenceMapUv:"",e.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+e.iridescenceThicknessMapUv:"",e.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+e.sheenColorMapUv:"",e.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+e.sheenRoughnessMapUv:"",e.specularMapUv?"#define SPECULARMAP_UV "+e.specularMapUv:"",e.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+e.specularColorMapUv:"",e.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+e.specularIntensityMapUv:"",e.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+e.transmissionMapUv:"",e.thicknessMapUv?"#define THICKNESSMAP_UV "+e.thicknessMapUv:"",e.vertexTangents&&e.flatShading===!1?"#define USE_TANGENT":"",e.vertexNormals?"#define HAS_NORMAL":"",e.vertexColors?"#define USE_COLOR":"",e.vertexAlphas?"#define USE_COLOR_ALPHA":"",e.vertexUv1s?"#define USE_UV1":"",e.vertexUv2s?"#define USE_UV2":"",e.vertexUv3s?"#define USE_UV3":"",e.pointsUvs?"#define USE_POINTS_UV":"",e.flatShading?"#define FLAT_SHADED":"",e.skinning?"#define USE_SKINNING":"",e.morphTargets?"#define USE_MORPHTARGETS":"",e.morphNormals&&e.flatShading===!1?"#define USE_MORPHNORMALS":"",e.morphColors?"#define USE_MORPHCOLORS":"",e.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+e.morphTextureStride:"",e.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+e.morphTargetsCount:"",e.doubleSided?"#define DOUBLE_SIDED":"",e.flipSided?"#define FLIP_SIDED":"",e.shadowMapEnabled?"#define USE_SHADOWMAP":"",e.shadowMapEnabled?"#define "+l:"",e.sizeAttenuation?"#define USE_SIZEATTENUATION":"",e.numLightProbes>0?"#define USE_LIGHT_PROBES":"",e.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",e.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING"," attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR"," attribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH"," uniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1"," attribute vec2 uv1;","#endif","#ifdef USE_UV2"," attribute vec2 uv2;","#endif","#ifdef USE_UV3"," attribute vec2 uv3;","#endif","#ifdef USE_TANGENT"," attribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )"," attribute vec4 color;","#elif defined( USE_COLOR )"," attribute vec3 color;","#endif","#ifdef USE_SKINNING"," attribute vec4 skinIndex;"," attribute vec4 skinWeight;","#endif",` +`].filter(yr).join(` +`),f=[Td(e),"#define SHADER_TYPE "+e.shaderType,"#define SHADER_NAME "+e.shaderName,g,e.useFog&&e.fog?"#define USE_FOG":"",e.useFog&&e.fogExp2?"#define FOG_EXP2":"",e.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",e.map?"#define USE_MAP":"",e.matcap?"#define USE_MATCAP":"",e.envMap?"#define USE_ENVMAP":"",e.envMap?"#define "+c:"",e.envMap?"#define "+h:"",e.envMap?"#define "+d:"",u?"#define CUBEUV_TEXEL_WIDTH "+u.texelWidth:"",u?"#define CUBEUV_TEXEL_HEIGHT "+u.texelHeight:"",u?"#define CUBEUV_MAX_MIP "+u.maxMip+".0":"",e.lightMap?"#define USE_LIGHTMAP":"",e.aoMap?"#define USE_AOMAP":"",e.bumpMap?"#define USE_BUMPMAP":"",e.normalMap?"#define USE_NORMALMAP":"",e.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",e.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",e.packedNormalMap?"#define USE_PACKED_NORMALMAP":"",e.emissiveMap?"#define USE_EMISSIVEMAP":"",e.anisotropy?"#define USE_ANISOTROPY":"",e.anisotropyMap?"#define USE_ANISOTROPYMAP":"",e.clearcoat?"#define USE_CLEARCOAT":"",e.clearcoatMap?"#define USE_CLEARCOATMAP":"",e.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",e.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",e.dispersion?"#define USE_DISPERSION":"",e.retroreflection?"#define USE_RETROREFLECTION":"",e.iridescence?"#define USE_IRIDESCENCE":"",e.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",e.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",e.specularMap?"#define USE_SPECULARMAP":"",e.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",e.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",e.roughnessMap?"#define USE_ROUGHNESSMAP":"",e.metalnessMap?"#define USE_METALNESSMAP":"",e.alphaMap?"#define USE_ALPHAMAP":"",e.alphaTest?"#define USE_ALPHATEST":"",e.alphaHash?"#define USE_ALPHAHASH":"",e.sheen?"#define USE_SHEEN":"",e.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",e.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",e.transmission?"#define USE_TRANSMISSION":"",e.transmissionMap?"#define USE_TRANSMISSIONMAP":"",e.thicknessMap?"#define USE_THICKNESSMAP":"",e.vertexTangents&&e.flatShading===!1?"#define USE_TANGENT":"",e.vertexColors||e.instancingColor?"#define USE_COLOR":"",e.vertexAlphas||e.batchingColor?"#define USE_COLOR_ALPHA":"",e.vertexUv1s?"#define USE_UV1":"",e.vertexUv2s?"#define USE_UV2":"",e.vertexUv3s?"#define USE_UV3":"",e.pointsUvs?"#define USE_POINTS_UV":"",e.gradientMap?"#define USE_GRADIENTMAP":"",e.flatShading?"#define FLAT_SHADED":"",e.doubleSided?"#define DOUBLE_SIDED":"",e.flipSided?"#define FLIP_SIDED":"",e.shadowMapEnabled?"#define USE_SHADOWMAP":"",e.shadowMapEnabled?"#define "+l:"",e.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",e.numLightProbes>0?"#define USE_LIGHT_PROBES":"",e.numLightProbeGrids>0?"#define USE_LIGHT_PROBES_GRID":"",e.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",e.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",e.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",e.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",e.toneMapping!==Mn?"#define TONE_MAPPING":"",e.toneMapping!==Mn?Wt.tonemapping_pars_fragment:"",e.toneMapping!==Mn?xx("toneMapping",e.toneMapping):"",e.dithering?"#define DITHERING":"",e.opaque?"#define OPAQUE":"",Wt.colorspace_pars_fragment,gx("linearToOutputTexel",e.outputColorSpace),vx(),e.useDepthPacking?"#define DEPTH_PACKING "+e.depthPacking:"",` +`].filter(yr).join(` +`)),o=Xc(o),o=Sd(o,e),o=wd(o,e),a=Xc(a),a=Sd(a,e),a=wd(a,e),o=Ed(o),a=Ed(a),e.isRawShaderMaterial!==!0&&(b=`#version 300 es `,m=[p,"#define attribute in","#define varying out","#define texture2D texture"].join(` `)+` `+m,f=["#define varying in",e.glslVersion===wc?"":"layout(location = 0) out highp vec4 pc_fragColor;",e.glslVersion===wc?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join(` `)+` -`+f);let E=b+m+o,M=b+f+a,v=vd(s,s.VERTEX_SHADER,E),S=vd(s,s.FRAGMENT_SHADER,M);s.attachShader(_,v),s.attachShader(_,S),e.index0AttributeName!==void 0?s.bindAttribLocation(_,0,e.index0AttributeName):e.hasPositionAttribute===!0&&s.bindAttribLocation(_,0,"position"),s.linkProgram(_);function A(L){if(i.debug.checkShaderErrors){let N=s.getProgramInfoLog(_)||"",U=s.getShaderInfoLog(v)||"",C=s.getShaderInfoLog(S)||"",B=N.trim(),z=U.trim(),W=C.trim(),F=!0,D=!0;if(s.getProgramParameter(_,s.LINK_STATUS)===!1)if(F=!1,typeof i.debug.onShaderError=="function")i.debug.onShaderError(s,_,v,S);else{let X=Md(s,v,"vertex"),Z=Md(s,S,"fragment");Ut("WebGLProgram: Shader Error "+s.getError()+" - VALIDATE_STATUS "+s.getProgramParameter(_,s.VALIDATE_STATUS)+` +`+f);let E=b+m+o,M=b+f+a,v=yd(s,s.VERTEX_SHADER,E),S=yd(s,s.FRAGMENT_SHADER,M);s.attachShader(_,v),s.attachShader(_,S),e.index0AttributeName!==void 0?s.bindAttribLocation(_,0,e.index0AttributeName):e.hasPositionAttribute===!0&&s.bindAttribLocation(_,0,"position"),s.linkProgram(_);function A(L){if(i.debug.checkShaderErrors){let N=s.getProgramInfoLog(_)||"",U=s.getShaderInfoLog(v)||"",C=s.getShaderInfoLog(S)||"",B=N.trim(),z=U.trim(),W=C.trim(),F=!0,D=!0;if(s.getProgramParameter(_,s.LINK_STATUS)===!1)if(F=!1,typeof i.debug.onShaderError=="function")i.debug.onShaderError(s,_,v,S);else{let X=bd(s,v,"vertex"),Z=bd(s,S,"fragment");Ut("WebGLProgram: Shader Error "+s.getError()+" - VALIDATE_STATUS "+s.getProgramParameter(_,s.VALIDATE_STATUS)+` Material Name: `+L.name+` Material Type: `+L.type+` Program Info Log: `+B+` `+X+` -`+Z)}else B!==""?Dt("WebGLProgram: Program Info Log:",B):(z===""||W==="")&&(D=!1);D&&(L.diagnostics={runnable:F,programLog:B,vertexShader:{log:z,prefix:m},fragmentShader:{log:W,prefix:f}})}s.deleteShader(v),s.deleteShader(S),x=new Ts(s,_),T=yx(s,_)}let x;this.getUniforms=function(){return x===void 0&&A(this),x};let T;this.getAttributes=function(){return T===void 0&&A(this),T};let R=e.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return R===!1&&(R=s.getProgramParameter(_,hx)),R},this.destroy=function(){n.releaseStatesOfProgram(this),s.deleteProgram(_),this.program=void 0},this.type=e.shaderType,this.name=e.shaderName,this.id=ux++,this.cacheKey=t,this.usedTimes=1,this.program=_,this.vertexShader=v,this.fragmentShader=S,this}var Fx=0,qc=class{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(t,e,n){let s=this._getShaderCacheForMaterial(t);return s.has(e)===!1&&(s.add(e),e.usedTimes++),s.has(n)===!1&&(s.add(n),n.usedTimes++),this}remove(t){let e=this.materialCache.get(t);for(let n of e)n.usedTimes--,n.usedTimes===0&&this.shaderCache.delete(n.code);return this.materialCache.delete(t),this}getVertexShaderStage(t){return this._getShaderStage(t.vertexShader)}getFragmentShaderStage(t){return this._getShaderStage(t.fragmentShader)}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(t){let e=this.materialCache,n=e.get(t);return n===void 0&&(n=new Set,e.set(t,n)),n}_getShaderStage(t){let e=this.shaderCache,n=e.get(t);return n===void 0&&(n=new Yc(t),e.set(t,n)),n}},Yc=class{constructor(t){this.id=Fx++,this.code=t,this.usedTimes=0}};function Bx(i){return i===_i||i===mr||i===gr}function Ox(i,t,e,n,s,r){let o=new us,a=new qc,l=new Set,c=[],h=new Map,d=n.logarithmicDepthBuffer,u=n.precision,p={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distance",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function g(x){return l.add(x),x===0?"uv":`uv${x}`}function _(x,T,R,L,N,U){let C=L.fog,B=N.geometry,z=x.isMeshStandardMaterial||x.isMeshLambertMaterial||x.isMeshPhongMaterial?L.environment:null,W=x.isMeshStandardMaterial||x.isMeshLambertMaterial&&!x.envMap||x.isMeshPhongMaterial&&!x.envMap,F=t.get(x.envMap||z,W),D=F&&F.mapping===cr?F.image.height:null,X=p[x.type];x.precision!==null&&(u=n.getMaxPrecision(x.precision),u!==x.precision&&Dt("WebGLProgram.getParameters:",x.precision,"not supported, using",u,"instead."));let Z=B.morphAttributes.position||B.morphAttributes.normal||B.morphAttributes.color,G=Z!==void 0?Z.length:0,Q=0;B.morphAttributes.position!==void 0&&(Q=1),B.morphAttributes.normal!==void 0&&(Q=2),B.morphAttributes.color!==void 0&&(Q=3);let lt,ct,tt,V;if(X){let ce=kn[X];lt=ce.vertexShader,ct=ce.fragmentShader}else{lt=x.vertexShader,ct=x.fragmentShader;let ce=a.getVertexShaderStage(x),jt=a.getFragmentShaderStage(x);a.update(x,ce,jt),tt=ce.id,V=jt.id}let j=i.getRenderTarget(),ut=i.state.buffers.depth.getReversed(),Lt=N.isInstancedMesh===!0,Mt=N.isBatchedMesh===!0,Bt=!!x.map,xe=!!x.matcap,Vt=!!F,Jt=!!x.aoMap,le=!!x.lightMap,qt=!!x.bumpMap&&x.wireframe===!1,ve=!!x.normalMap,De=!!x.displacementMap,tn=!!x.emissiveMap,Me=!!x.metalnessMap,we=!!x.roughnessMap,H=x.anisotropy>0,We=x.clearcoat>0,ee=x.dispersion>0,P=x.retroreflectivity>0,y=x.iridescence>0,q=x.sheen>0,J=x.transmission>0,nt=H&&!!x.anisotropyMap,ht=We&&!!x.clearcoatMap,dt=We&&!!x.clearcoatNormalMap,it=We&&!!x.clearcoatRoughnessMap,ot=y&&!!x.iridescenceMap,ft=y&&!!x.iridescenceThicknessMap,Ct=q&&!!x.sheenColorMap,_t=q&&!!x.sheenRoughnessMap,pt=!!x.specularMap,It=!!x.specularColorMap,Nt=!!x.specularIntensityMap,zt=J&&!!x.transmissionMap,k=J&&!!x.thicknessMap,mt=!!x.gradientMap,rt=!!x.alphaMap,gt=x.alphaTest>0,bt=!!x.alphaHash,at=!!x.extensions,Pt=Mn;x.toneMapped&&(j===null||j.isXRRenderTarget===!0)&&(Pt=i.toneMapping);let At={shaderID:X,shaderType:x.type,shaderName:x.name,vertexShader:lt,fragmentShader:ct,defines:x.defines,customVertexShaderID:tt,customFragmentShaderID:V,isRawShaderMaterial:x.isRawShaderMaterial===!0,glslVersion:x.glslVersion,precision:u,batching:Mt,batchingColor:Mt&&N._colorsTexture!==null,instancing:Lt,instancingColor:Lt&&N.instanceColor!==null,instancingMorph:Lt&&N.morphTexture!==null,outputColorSpace:j===null?i.outputColorSpace:j.isXRRenderTarget===!0?j.texture.colorSpace:Yt.workingColorSpace,alphaToCoverage:!!x.alphaToCoverage,map:Bt,matcap:xe,envMap:Vt,envMapMode:Vt&&F.mapping,envMapCubeUVHeight:D,aoMap:Jt,lightMap:le,bumpMap:qt,normalMap:ve,displacementMap:De,emissiveMap:tn,normalMapObjectSpace:ve&&x.normalMapType===Yu,normalMapTangentSpace:ve&&x.normalMapType===Ua,packedNormalMap:ve&&x.normalMapType===Ua&&Bx(x.normalMap.format),metalnessMap:Me,roughnessMap:we,anisotropy:H,anisotropyMap:nt,clearcoat:We,clearcoatMap:ht,clearcoatNormalMap:dt,clearcoatRoughnessMap:it,dispersion:ee,retroreflection:P,iridescence:y,iridescenceMap:ot,iridescenceThicknessMap:ft,sheen:q,sheenColorMap:Ct,sheenRoughnessMap:_t,specularMap:pt,specularColorMap:It,specularIntensityMap:Nt,transmission:J,transmissionMap:zt,thicknessMap:k,gradientMap:mt,opaque:x.transparent===!1&&x.blending===ys&&x.alphaToCoverage===!1,alphaMap:rt,alphaTest:gt,alphaHash:bt,combine:x.combine,mapUv:Bt&&g(x.map.channel),aoMapUv:Jt&&g(x.aoMap.channel),lightMapUv:le&&g(x.lightMap.channel),bumpMapUv:qt&&g(x.bumpMap.channel),normalMapUv:ve&&g(x.normalMap.channel),displacementMapUv:De&&g(x.displacementMap.channel),emissiveMapUv:tn&&g(x.emissiveMap.channel),metalnessMapUv:Me&&g(x.metalnessMap.channel),roughnessMapUv:we&&g(x.roughnessMap.channel),anisotropyMapUv:nt&&g(x.anisotropyMap.channel),clearcoatMapUv:ht&&g(x.clearcoatMap.channel),clearcoatNormalMapUv:dt&&g(x.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:it&&g(x.clearcoatRoughnessMap.channel),iridescenceMapUv:ot&&g(x.iridescenceMap.channel),iridescenceThicknessMapUv:ft&&g(x.iridescenceThicknessMap.channel),sheenColorMapUv:Ct&&g(x.sheenColorMap.channel),sheenRoughnessMapUv:_t&&g(x.sheenRoughnessMap.channel),specularMapUv:pt&&g(x.specularMap.channel),specularColorMapUv:It&&g(x.specularColorMap.channel),specularIntensityMapUv:Nt&&g(x.specularIntensityMap.channel),transmissionMapUv:zt&&g(x.transmissionMap.channel),thicknessMapUv:k&&g(x.thicknessMap.channel),alphaMapUv:rt&&g(x.alphaMap.channel),vertexTangents:!!B.attributes.tangent&&(ve||H),vertexNormals:!!B.attributes.normal,vertexColors:x.vertexColors,vertexAlphas:x.vertexColors===!0&&!!B.attributes.color&&B.attributes.color.itemSize===4,pointsUvs:N.isPoints===!0&&!!B.attributes.uv&&(Bt||rt),fog:!!C,useFog:x.fog===!0,fogExp2:!!C&&C.isFogExp2,flatShading:x.wireframe===!1&&(x.flatShading===!0||B.attributes.normal===void 0&&ve===!1&&(x.isMeshLambertMaterial||x.isMeshPhongMaterial||x.isMeshStandardMaterial||x.isMeshPhysicalMaterial)),sizeAttenuation:x.sizeAttenuation===!0,logarithmicDepthBuffer:d,reversedDepthBuffer:ut,skinning:N.isSkinnedMesh===!0,hasPositionAttribute:B.attributes.position!==void 0,morphTargets:B.morphAttributes.position!==void 0,morphNormals:B.morphAttributes.normal!==void 0,morphColors:B.morphAttributes.color!==void 0,morphTargetsCount:G,morphTextureStride:Q,numSunLights:T.sun.length,numDirLights:T.directional.length,numPointLights:T.point.length,numSpotLights:T.spot.length,numSpotLightMaps:T.spotLightMap.length,numRectAreaLights:T.rectArea.length,numHemiLights:T.hemi.length,numSunLightShadows:T.sunShadowMap.length,numDirLightShadows:T.directionalShadowMap.length,numPointLightShadows:T.pointShadowMap.length,numSpotLightShadows:T.spotShadowMap.length,numSpotLightShadowsWithMaps:T.numSpotLightShadowsWithMaps,numLightProbes:T.numLightProbes,numLightProbeGrids:U.length,numClippingPlanes:r.numPlanes,numClipIntersection:r.numIntersection,dithering:x.dithering,shadowMapEnabled:i.shadowMap.enabled&&R.length>0,shadowMapType:i.shadowMap.type,toneMapping:Pt,decodeVideoTexture:Bt&&x.map.isVideoTexture===!0&&Yt.getTransfer(x.map.colorSpace)===te,decodeVideoTextureEmissive:tn&&x.emissiveMap.isVideoTexture===!0&&Yt.getTransfer(x.emissiveMap.colorSpace)===te,premultipliedAlpha:x.premultipliedAlpha,doubleSided:x.side===Ie,flipSided:x.side===Ve,useDepthPacking:x.depthPacking>=0,depthPacking:x.depthPacking||0,index0AttributeName:x.index0AttributeName,extensionClipCullDistance:at&&x.extensions.clipCullDistance===!0&&e.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(at&&x.extensions.multiDraw===!0||Mt)&&e.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:e.has("KHR_parallel_shader_compile"),customProgramCacheKey:x.customProgramCacheKey()};return At.vertexUv1s=l.has(1),At.vertexUv2s=l.has(2),At.vertexUv3s=l.has(3),l.clear(),At}function m(x){let T=[];if(x.shaderID?T.push(x.shaderID):(T.push(x.customVertexShaderID),T.push(x.customFragmentShaderID)),x.defines!==void 0)for(let R in x.defines)T.push(R),T.push(x.defines[R]);return x.isRawShaderMaterial===!1&&(f(T,x),b(T,x),T.push(i.outputColorSpace)),T.push(x.customProgramCacheKey),T.join()}function f(x,T){x.push(T.precision),x.push(T.outputColorSpace),x.push(T.envMapMode),x.push(T.envMapCubeUVHeight),x.push(T.mapUv),x.push(T.alphaMapUv),x.push(T.lightMapUv),x.push(T.aoMapUv),x.push(T.bumpMapUv),x.push(T.normalMapUv),x.push(T.displacementMapUv),x.push(T.emissiveMapUv),x.push(T.metalnessMapUv),x.push(T.roughnessMapUv),x.push(T.anisotropyMapUv),x.push(T.clearcoatMapUv),x.push(T.clearcoatNormalMapUv),x.push(T.clearcoatRoughnessMapUv),x.push(T.iridescenceMapUv),x.push(T.iridescenceThicknessMapUv),x.push(T.sheenColorMapUv),x.push(T.sheenRoughnessMapUv),x.push(T.specularMapUv),x.push(T.specularColorMapUv),x.push(T.specularIntensityMapUv),x.push(T.transmissionMapUv),x.push(T.thicknessMapUv),x.push(T.combine),x.push(T.fogExp2),x.push(T.sizeAttenuation),x.push(T.morphTargetsCount),x.push(T.morphAttributeCount),x.push(T.numSunLights),x.push(T.numDirLights),x.push(T.numPointLights),x.push(T.numSpotLights),x.push(T.numSpotLightMaps),x.push(T.numHemiLights),x.push(T.numRectAreaLights),x.push(T.numSunLightShadows),x.push(T.numDirLightShadows),x.push(T.numPointLightShadows),x.push(T.numSpotLightShadows),x.push(T.numSpotLightShadowsWithMaps),x.push(T.numLightProbes),x.push(T.shadowMapType),x.push(T.toneMapping),x.push(T.numClippingPlanes),x.push(T.numClipIntersection),x.push(T.depthPacking)}function b(x,T){o.disableAll(),T.instancing&&o.enable(0),T.instancingColor&&o.enable(1),T.instancingMorph&&o.enable(2),T.matcap&&o.enable(3),T.envMap&&o.enable(4),T.normalMapObjectSpace&&o.enable(5),T.normalMapTangentSpace&&o.enable(6),T.clearcoat&&o.enable(7),T.iridescence&&o.enable(8),T.alphaTest&&o.enable(9),T.vertexColors&&o.enable(10),T.vertexAlphas&&o.enable(11),T.vertexUv1s&&o.enable(12),T.vertexUv2s&&o.enable(13),T.vertexUv3s&&o.enable(14),T.vertexTangents&&o.enable(15),T.anisotropy&&o.enable(16),T.alphaHash&&o.enable(17),T.batching&&o.enable(18),T.dispersion&&o.enable(19),T.retroreflection&&o.enable(24),T.batchingColor&&o.enable(20),T.gradientMap&&o.enable(21),T.packedNormalMap&&o.enable(22),T.vertexNormals&&o.enable(23),x.push(o.mask),o.disableAll(),T.fog&&o.enable(0),T.useFog&&o.enable(1),T.flatShading&&o.enable(2),T.logarithmicDepthBuffer&&o.enable(3),T.reversedDepthBuffer&&o.enable(4),T.skinning&&o.enable(5),T.morphTargets&&o.enable(6),T.morphNormals&&o.enable(7),T.morphColors&&o.enable(8),T.premultipliedAlpha&&o.enable(9),T.shadowMapEnabled&&o.enable(10),T.doubleSided&&o.enable(11),T.flipSided&&o.enable(12),T.useDepthPacking&&o.enable(13),T.dithering&&o.enable(14),T.transmission&&o.enable(15),T.sheen&&o.enable(16),T.opaque&&o.enable(17),T.pointsUvs&&o.enable(18),T.decodeVideoTexture&&o.enable(19),T.decodeVideoTextureEmissive&&o.enable(20),T.alphaToCoverage&&o.enable(21),T.numLightProbeGrids>0&&o.enable(22),T.hasPositionAttribute&&o.enable(23),x.push(o.mask)}function E(x){let T=p[x.type],R;if(T){let L=kn[T];R=od.clone(L.uniforms)}else R=x.uniforms;return R}function M(x,T){let R=h.get(T);return R!==void 0?++R.usedTimes:(R=new Ux(i,T,x,s),c.push(R),h.set(T,R)),R}function v(x){if(--x.usedTimes===0){let T=c.indexOf(x);c[T]=c[c.length-1],c.pop(),h.delete(x.cacheKey),x.destroy()}}function S(x){a.remove(x)}function A(){a.dispose()}return{getParameters:_,getProgramCacheKey:m,getUniforms:E,acquireProgram:M,releaseProgram:v,releaseShaderCache:S,programs:c,dispose:A}}function zx(){let i=new WeakMap;function t(o){return i.has(o)}function e(o){let a=i.get(o);return a===void 0&&(a={},i.set(o,a)),a}function n(o){i.delete(o)}function s(o,a,l){i.get(o)[a]=l}function r(){i=new WeakMap}return{has:t,get:e,remove:n,update:s,dispose:r}}function kx(i,t){return i.groupOrder!==t.groupOrder?i.groupOrder-t.groupOrder:i.renderOrder!==t.renderOrder?i.renderOrder-t.renderOrder:i.material.id!==t.material.id?i.material.id-t.material.id:i.materialVariant!==t.materialVariant?i.materialVariant-t.materialVariant:i.z!==t.z?i.z-t.z:i.id-t.id}function Td(i,t){return i.groupOrder!==t.groupOrder?i.groupOrder-t.groupOrder:i.renderOrder!==t.renderOrder?i.renderOrder-t.renderOrder:i.z!==t.z?t.z-i.z:i.id-t.id}function Ad(){let i=[],t=0,e=[],n=[],s=[];function r(){t=0,e.length=0,n.length=0,s.length=0}function o(u){let p=0;return u.isInstancedMesh&&(p+=2),u.isSkinnedMesh&&(p+=1),p}function a(u,p,g,_,m,f){let b=i[t];return b===void 0?(b={id:u.id,object:u,geometry:p,material:g,materialVariant:o(u),groupOrder:_,renderOrder:u.renderOrder,z:m,group:f},i[t]=b):(b.id=u.id,b.object=u,b.geometry=p,b.material=g,b.materialVariant=o(u),b.groupOrder=_,b.renderOrder=u.renderOrder,b.z=m,b.group=f),t++,b}function l(u,p,g,_,m,f,b){b.reversedDepth===!0&&(m=-m);let E=a(u,p,g,_,m,f);g.transmission>0?n.push(E):g.transparent===!0?s.push(E):e.push(E)}function c(u,p,g,_,m,f){let b=a(u,p,g,_,m,f);g.transmission>0?n.unshift(b):g.transparent===!0?s.unshift(b):e.unshift(b)}function h(u,p){e.length>1&&e.sort(u||kx),n.length>1&&n.sort(p||Td),s.length>1&&s.sort(p||Td)}function d(){for(let u=t,p=i.length;u=r.length?(o=new Ad,r.push(o)):o=r[s],o}function e(){i=new WeakMap}return{get:t,dispose:e}}function Vx(){let i={};return{get:function(t){if(i[t.id]!==void 0)return i[t.id];let e;switch(t.type){case"SunLight":case"DirectionalLight":e={direction:new I,color:new Ft};break;case"SpotLight":e={position:new I,direction:new I,color:new Ft,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":e={position:new I,color:new Ft,distance:0,decay:0};break;case"HemisphereLight":e={direction:new I,skyColor:new Ft,groundColor:new Ft};break;case"RectAreaLight":e={color:new Ft,position:new I,halfWidth:new I,halfHeight:new I};break}return i[t.id]=e,e}}}function Gx(){let i={};return{get:function(t){if(i[t.id]!==void 0)return i[t.id];let e;switch(t.type){case"SunLight":case"DirectionalLight":e={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Ht};break;case"SpotLight":e={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Ht};break;case"PointLight":e={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Ht,shadowCameraNear:1,shadowCameraFar:1e3};break}return i[t.id]=e,e}}}var Wx=0;function Xx(i,t){return(t.castShadow?2:0)-(i.castShadow?2:0)+(t.map?1:0)-(i.map?1:0)}function qx(i){let t=new Vx,e=Gx(),n={version:0,hash:{sunLength:-1,directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numSunShadows:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],sun:[],sunShadow:[],sunShadowMap:[],sunShadowMatrix:[],sunShadowCascade:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let c=0;c<9;c++)n.probe.push(new I);let s=new I,r=new kt,o=new kt;function a(c){let h=0,d=0,u=0;for(let N=0;N<9;N++)n.probe[N].set(0,0,0);let p=0,g=0,_=0,m=0,f=0,b=0,E=0,M=0,v=0,S=0,A=0,x=0,T=0,R=0;c.sort(Xx);for(let N=0,U=c.length;N0&&(i.has("OES_texture_float_linear")===!0?(n.rectAreaLTC1=xt.LTC_FLOAT_1,n.rectAreaLTC2=xt.LTC_FLOAT_2):(n.rectAreaLTC1=xt.LTC_HALF_1,n.rectAreaLTC2=xt.LTC_HALF_2)),n.ambient[0]=h,n.ambient[1]=d,n.ambient[2]=u;let L=n.hash;(L.sunLength!==p||L.directionalLength!==m||L.pointLength!==f||L.spotLength!==b||L.rectAreaLength!==E||L.hemiLength!==M||L.numSunShadows!==g||L.numDirectionalShadows!==v||L.numPointShadows!==S||L.numSpotShadows!==A||L.numSpotMaps!==x||L.numLightProbes!==R)&&(n.sun.length=p,n.directional.length=m,n.spot.length=b,n.rectArea.length=E,n.point.length=f,n.hemi.length=M,n.sunShadow.length=g,n.sunShadowMap.length=g,n.sunShadowMatrix.length=_,n.sunShadowCascade.length=_,n.directionalShadow.length=v,n.directionalShadowMap.length=v,n.directionalShadowMatrix.length=v,n.pointShadow.length=S,n.pointShadowMap.length=S,n.pointShadowMatrix.length=S,n.spotShadow.length=A,n.spotShadowMap.length=A,n.spotLightMatrix.length=A+x-T,n.spotLightMap.length=x,n.numSpotLightShadowsWithMaps=T,n.numLightProbes=R,L.sunLength=p,L.directionalLength=m,L.pointLength=f,L.spotLength=b,L.rectAreaLength=E,L.hemiLength=M,L.numSunShadows=g,L.numDirectionalShadows=v,L.numPointShadows=S,L.numSpotShadows=A,L.numSpotMaps=x,L.numLightProbes=R,n.version=Wx++)}function l(c,h){let d=0,u=0,p=0,g=0,_=0,m=0,f=h.matrixWorldInverse;for(let b=0,E=c.length;b=o.length?(a=new Rd(i),o.push(a)):a=o[r],a}function n(){t=new WeakMap}return{get:e,dispose:n}}var $x=`void main() { +`+Z)}else B!==""?Dt("WebGLProgram: Program Info Log:",B):(z===""||W==="")&&(D=!1);D&&(L.diagnostics={runnable:F,programLog:B,vertexShader:{log:z,prefix:m},fragmentShader:{log:W,prefix:f}})}s.deleteShader(v),s.deleteShader(S),x=new Ts(s,_),T=bx(s,_)}let x;this.getUniforms=function(){return x===void 0&&A(this),x};let T;this.getAttributes=function(){return T===void 0&&A(this),T};let R=e.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return R===!1&&(R=s.getProgramParameter(_,dx)),R},this.destroy=function(){n.releaseStatesOfProgram(this),s.deleteProgram(_),this.program=void 0},this.type=e.shaderType,this.name=e.shaderName,this.id=fx++,this.cacheKey=t,this.usedTimes=1,this.program=_,this.vertexShader=v,this.fragmentShader=S,this}var Ox=0,qc=class{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(t,e,n){let s=this._getShaderCacheForMaterial(t);return s.has(e)===!1&&(s.add(e),e.usedTimes++),s.has(n)===!1&&(s.add(n),n.usedTimes++),this}remove(t){let e=this.materialCache.get(t);for(let n of e)n.usedTimes--,n.usedTimes===0&&this.shaderCache.delete(n.code);return this.materialCache.delete(t),this}getVertexShaderStage(t){return this._getShaderStage(t.vertexShader)}getFragmentShaderStage(t){return this._getShaderStage(t.fragmentShader)}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(t){let e=this.materialCache,n=e.get(t);return n===void 0&&(n=new Set,e.set(t,n)),n}_getShaderStage(t){let e=this.shaderCache,n=e.get(t);return n===void 0&&(n=new Yc(t),e.set(t,n)),n}},Yc=class{constructor(t){this.id=Ox++,this.code=t,this.usedTimes=0}};function zx(i){return i===_i||i===gr||i===_r}function kx(i,t,e,n,s,r){let o=new us,a=new qc,l=new Set,c=[],h=new Map,d=n.logarithmicDepthBuffer,u=n.precision,p={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distance",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function g(x){return l.add(x),x===0?"uv":`uv${x}`}function _(x,T,R,L,N,U){let C=L.fog,B=N.geometry,z=x.isMeshStandardMaterial||x.isMeshLambertMaterial||x.isMeshPhongMaterial?L.environment:null,W=x.isMeshStandardMaterial||x.isMeshLambertMaterial&&!x.envMap||x.isMeshPhongMaterial&&!x.envMap,F=t.get(x.envMap||z,W),D=F&&F.mapping===hr?F.image.height:null,X=p[x.type];x.precision!==null&&(u=n.getMaxPrecision(x.precision),u!==x.precision&&Dt("WebGLProgram.getParameters:",x.precision,"not supported, using",u,"instead."));let Z=B.morphAttributes.position||B.morphAttributes.normal||B.morphAttributes.color,G=Z!==void 0?Z.length:0,Q=0;B.morphAttributes.position!==void 0&&(Q=1),B.morphAttributes.normal!==void 0&&(Q=2),B.morphAttributes.color!==void 0&&(Q=3);let lt,ct,et,V;if(X){let ue=kn[X];lt=ue.vertexShader,ct=ue.fragmentShader}else{lt=x.vertexShader,ct=x.fragmentShader;let ue=a.getVertexShaderStage(x),jt=a.getFragmentShaderStage(x);a.update(x,ue,jt),et=ue.id,V=jt.id}let j=i.getRenderTarget(),ut=i.state.buffers.depth.getReversed(),Lt=N.isInstancedMesh===!0,Mt=N.isBatchedMesh===!0,Bt=!!x.map,ve=!!x.matcap,Vt=!!F,Jt=!!x.aoMap,he=!!x.lightMap,qt=!!x.bumpMap&&x.wireframe===!1,ye=!!x.normalMap,De=!!x.displacementMap,tn=!!x.emissiveMap,Me=!!x.metalnessMap,we=!!x.roughnessMap,H=x.anisotropy>0,We=x.clearcoat>0,ee=x.dispersion>0,P=x.retroreflectivity>0,y=x.iridescence>0,q=x.sheen>0,J=x.transmission>0,nt=H&&!!x.anisotropyMap,ht=We&&!!x.clearcoatMap,dt=We&&!!x.clearcoatNormalMap,it=We&&!!x.clearcoatRoughnessMap,ot=y&&!!x.iridescenceMap,ft=y&&!!x.iridescenceThicknessMap,Ct=q&&!!x.sheenColorMap,_t=q&&!!x.sheenRoughnessMap,pt=!!x.specularMap,It=!!x.specularColorMap,Nt=!!x.specularIntensityMap,zt=J&&!!x.transmissionMap,k=J&&!!x.thicknessMap,mt=!!x.gradientMap,rt=!!x.alphaMap,gt=x.alphaTest>0,bt=!!x.alphaHash,at=!!x.extensions,Pt=Mn;x.toneMapped&&(j===null||j.isXRRenderTarget===!0)&&(Pt=i.toneMapping);let At={shaderID:X,shaderType:x.type,shaderName:x.name,vertexShader:lt,fragmentShader:ct,defines:x.defines,customVertexShaderID:et,customFragmentShaderID:V,isRawShaderMaterial:x.isRawShaderMaterial===!0,glslVersion:x.glslVersion,precision:u,batching:Mt,batchingColor:Mt&&N._colorsTexture!==null,instancing:Lt,instancingColor:Lt&&N.instanceColor!==null,instancingMorph:Lt&&N.morphTexture!==null,outputColorSpace:j===null?i.outputColorSpace:j.isXRRenderTarget===!0?j.texture.colorSpace:Yt.workingColorSpace,alphaToCoverage:!!x.alphaToCoverage,map:Bt,matcap:ve,envMap:Vt,envMapMode:Vt&&F.mapping,envMapCubeUVHeight:D,aoMap:Jt,lightMap:he,bumpMap:qt,normalMap:ye,displacementMap:De,emissiveMap:tn,normalMapObjectSpace:ye&&x.normalMapType===$u,normalMapTangentSpace:ye&&x.normalMapType===Ua,packedNormalMap:ye&&x.normalMapType===Ua&&zx(x.normalMap.format),metalnessMap:Me,roughnessMap:we,anisotropy:H,anisotropyMap:nt,clearcoat:We,clearcoatMap:ht,clearcoatNormalMap:dt,clearcoatRoughnessMap:it,dispersion:ee,retroreflection:P,iridescence:y,iridescenceMap:ot,iridescenceThicknessMap:ft,sheen:q,sheenColorMap:Ct,sheenRoughnessMap:_t,specularMap:pt,specularColorMap:It,specularIntensityMap:Nt,transmission:J,transmissionMap:zt,thicknessMap:k,gradientMap:mt,opaque:x.transparent===!1&&x.blending===ys&&x.alphaToCoverage===!1,alphaMap:rt,alphaTest:gt,alphaHash:bt,combine:x.combine,mapUv:Bt&&g(x.map.channel),aoMapUv:Jt&&g(x.aoMap.channel),lightMapUv:he&&g(x.lightMap.channel),bumpMapUv:qt&&g(x.bumpMap.channel),normalMapUv:ye&&g(x.normalMap.channel),displacementMapUv:De&&g(x.displacementMap.channel),emissiveMapUv:tn&&g(x.emissiveMap.channel),metalnessMapUv:Me&&g(x.metalnessMap.channel),roughnessMapUv:we&&g(x.roughnessMap.channel),anisotropyMapUv:nt&&g(x.anisotropyMap.channel),clearcoatMapUv:ht&&g(x.clearcoatMap.channel),clearcoatNormalMapUv:dt&&g(x.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:it&&g(x.clearcoatRoughnessMap.channel),iridescenceMapUv:ot&&g(x.iridescenceMap.channel),iridescenceThicknessMapUv:ft&&g(x.iridescenceThicknessMap.channel),sheenColorMapUv:Ct&&g(x.sheenColorMap.channel),sheenRoughnessMapUv:_t&&g(x.sheenRoughnessMap.channel),specularMapUv:pt&&g(x.specularMap.channel),specularColorMapUv:It&&g(x.specularColorMap.channel),specularIntensityMapUv:Nt&&g(x.specularIntensityMap.channel),transmissionMapUv:zt&&g(x.transmissionMap.channel),thicknessMapUv:k&&g(x.thicknessMap.channel),alphaMapUv:rt&&g(x.alphaMap.channel),vertexTangents:!!B.attributes.tangent&&(ye||H),vertexNormals:!!B.attributes.normal,vertexColors:x.vertexColors,vertexAlphas:x.vertexColors===!0&&!!B.attributes.color&&B.attributes.color.itemSize===4,pointsUvs:N.isPoints===!0&&!!B.attributes.uv&&(Bt||rt),fog:!!C,useFog:x.fog===!0,fogExp2:!!C&&C.isFogExp2,flatShading:x.wireframe===!1&&(x.flatShading===!0||B.attributes.normal===void 0&&ye===!1&&(x.isMeshLambertMaterial||x.isMeshPhongMaterial||x.isMeshStandardMaterial||x.isMeshPhysicalMaterial)),sizeAttenuation:x.sizeAttenuation===!0,logarithmicDepthBuffer:d,reversedDepthBuffer:ut,skinning:N.isSkinnedMesh===!0,hasPositionAttribute:B.attributes.position!==void 0,morphTargets:B.morphAttributes.position!==void 0,morphNormals:B.morphAttributes.normal!==void 0,morphColors:B.morphAttributes.color!==void 0,morphTargetsCount:G,morphTextureStride:Q,numSunLights:T.sun.length,numDirLights:T.directional.length,numPointLights:T.point.length,numSpotLights:T.spot.length,numSpotLightMaps:T.spotLightMap.length,numRectAreaLights:T.rectArea.length,numHemiLights:T.hemi.length,numSunLightShadows:T.sunShadowMap.length,numDirLightShadows:T.directionalShadowMap.length,numPointLightShadows:T.pointShadowMap.length,numSpotLightShadows:T.spotShadowMap.length,numSpotLightShadowsWithMaps:T.numSpotLightShadowsWithMaps,numLightProbes:T.numLightProbes,numLightProbeGrids:U.length,numClippingPlanes:r.numPlanes,numClipIntersection:r.numIntersection,dithering:x.dithering,shadowMapEnabled:i.shadowMap.enabled&&R.length>0,shadowMapType:i.shadowMap.type,toneMapping:Pt,decodeVideoTexture:Bt&&x.map.isVideoTexture===!0&&Yt.getTransfer(x.map.colorSpace)===te,decodeVideoTextureEmissive:tn&&x.emissiveMap.isVideoTexture===!0&&Yt.getTransfer(x.emissiveMap.colorSpace)===te,premultipliedAlpha:x.premultipliedAlpha,doubleSided:x.side===Ie,flipSided:x.side===Ve,useDepthPacking:x.depthPacking>=0,depthPacking:x.depthPacking||0,index0AttributeName:x.index0AttributeName,extensionClipCullDistance:at&&x.extensions.clipCullDistance===!0&&e.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(at&&x.extensions.multiDraw===!0||Mt)&&e.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:e.has("KHR_parallel_shader_compile"),customProgramCacheKey:x.customProgramCacheKey()};return At.vertexUv1s=l.has(1),At.vertexUv2s=l.has(2),At.vertexUv3s=l.has(3),l.clear(),At}function m(x){let T=[];if(x.shaderID?T.push(x.shaderID):(T.push(x.customVertexShaderID),T.push(x.customFragmentShaderID)),x.defines!==void 0)for(let R in x.defines)T.push(R),T.push(x.defines[R]);return x.isRawShaderMaterial===!1&&(f(T,x),b(T,x),T.push(i.outputColorSpace)),T.push(x.customProgramCacheKey),T.join()}function f(x,T){x.push(T.precision),x.push(T.outputColorSpace),x.push(T.envMapMode),x.push(T.envMapCubeUVHeight),x.push(T.mapUv),x.push(T.alphaMapUv),x.push(T.lightMapUv),x.push(T.aoMapUv),x.push(T.bumpMapUv),x.push(T.normalMapUv),x.push(T.displacementMapUv),x.push(T.emissiveMapUv),x.push(T.metalnessMapUv),x.push(T.roughnessMapUv),x.push(T.anisotropyMapUv),x.push(T.clearcoatMapUv),x.push(T.clearcoatNormalMapUv),x.push(T.clearcoatRoughnessMapUv),x.push(T.iridescenceMapUv),x.push(T.iridescenceThicknessMapUv),x.push(T.sheenColorMapUv),x.push(T.sheenRoughnessMapUv),x.push(T.specularMapUv),x.push(T.specularColorMapUv),x.push(T.specularIntensityMapUv),x.push(T.transmissionMapUv),x.push(T.thicknessMapUv),x.push(T.combine),x.push(T.fogExp2),x.push(T.sizeAttenuation),x.push(T.morphTargetsCount),x.push(T.morphAttributeCount),x.push(T.numSunLights),x.push(T.numDirLights),x.push(T.numPointLights),x.push(T.numSpotLights),x.push(T.numSpotLightMaps),x.push(T.numHemiLights),x.push(T.numRectAreaLights),x.push(T.numSunLightShadows),x.push(T.numDirLightShadows),x.push(T.numPointLightShadows),x.push(T.numSpotLightShadows),x.push(T.numSpotLightShadowsWithMaps),x.push(T.numLightProbes),x.push(T.shadowMapType),x.push(T.toneMapping),x.push(T.numClippingPlanes),x.push(T.numClipIntersection),x.push(T.depthPacking)}function b(x,T){o.disableAll(),T.instancing&&o.enable(0),T.instancingColor&&o.enable(1),T.instancingMorph&&o.enable(2),T.matcap&&o.enable(3),T.envMap&&o.enable(4),T.normalMapObjectSpace&&o.enable(5),T.normalMapTangentSpace&&o.enable(6),T.clearcoat&&o.enable(7),T.iridescence&&o.enable(8),T.alphaTest&&o.enable(9),T.vertexColors&&o.enable(10),T.vertexAlphas&&o.enable(11),T.vertexUv1s&&o.enable(12),T.vertexUv2s&&o.enable(13),T.vertexUv3s&&o.enable(14),T.vertexTangents&&o.enable(15),T.anisotropy&&o.enable(16),T.alphaHash&&o.enable(17),T.batching&&o.enable(18),T.dispersion&&o.enable(19),T.retroreflection&&o.enable(24),T.batchingColor&&o.enable(20),T.gradientMap&&o.enable(21),T.packedNormalMap&&o.enable(22),T.vertexNormals&&o.enable(23),x.push(o.mask),o.disableAll(),T.fog&&o.enable(0),T.useFog&&o.enable(1),T.flatShading&&o.enable(2),T.logarithmicDepthBuffer&&o.enable(3),T.reversedDepthBuffer&&o.enable(4),T.skinning&&o.enable(5),T.morphTargets&&o.enable(6),T.morphNormals&&o.enable(7),T.morphColors&&o.enable(8),T.premultipliedAlpha&&o.enable(9),T.shadowMapEnabled&&o.enable(10),T.doubleSided&&o.enable(11),T.flipSided&&o.enable(12),T.useDepthPacking&&o.enable(13),T.dithering&&o.enable(14),T.transmission&&o.enable(15),T.sheen&&o.enable(16),T.opaque&&o.enable(17),T.pointsUvs&&o.enable(18),T.decodeVideoTexture&&o.enable(19),T.decodeVideoTextureEmissive&&o.enable(20),T.alphaToCoverage&&o.enable(21),T.numLightProbeGrids>0&&o.enable(22),T.hasPositionAttribute&&o.enable(23),x.push(o.mask)}function E(x){let T=p[x.type],R;if(T){let L=kn[T];R=ad.clone(L.uniforms)}else R=x.uniforms;return R}function M(x,T){let R=h.get(T);return R!==void 0?++R.usedTimes:(R=new Bx(i,T,x,s),c.push(R),h.set(T,R)),R}function v(x){if(--x.usedTimes===0){let T=c.indexOf(x);c[T]=c[c.length-1],c.pop(),h.delete(x.cacheKey),x.destroy()}}function S(x){a.remove(x)}function A(){a.dispose()}return{getParameters:_,getProgramCacheKey:m,getUniforms:E,acquireProgram:M,releaseProgram:v,releaseShaderCache:S,programs:c,dispose:A}}function Hx(){let i=new WeakMap;function t(o){return i.has(o)}function e(o){let a=i.get(o);return a===void 0&&(a={},i.set(o,a)),a}function n(o){i.delete(o)}function s(o,a,l){i.get(o)[a]=l}function r(){i=new WeakMap}return{has:t,get:e,remove:n,update:s,dispose:r}}function Vx(i,t){return i.groupOrder!==t.groupOrder?i.groupOrder-t.groupOrder:i.renderOrder!==t.renderOrder?i.renderOrder-t.renderOrder:i.material.id!==t.material.id?i.material.id-t.material.id:i.materialVariant!==t.materialVariant?i.materialVariant-t.materialVariant:i.z!==t.z?i.z-t.z:i.id-t.id}function Ad(i,t){return i.groupOrder!==t.groupOrder?i.groupOrder-t.groupOrder:i.renderOrder!==t.renderOrder?i.renderOrder-t.renderOrder:i.z!==t.z?t.z-i.z:i.id-t.id}function Rd(){let i=[],t=0,e=[],n=[],s=[];function r(){t=0,e.length=0,n.length=0,s.length=0}function o(u){let p=0;return u.isInstancedMesh&&(p+=2),u.isSkinnedMesh&&(p+=1),p}function a(u,p,g,_,m,f){let b=i[t];return b===void 0?(b={id:u.id,object:u,geometry:p,material:g,materialVariant:o(u),groupOrder:_,renderOrder:u.renderOrder,z:m,group:f},i[t]=b):(b.id=u.id,b.object=u,b.geometry=p,b.material=g,b.materialVariant=o(u),b.groupOrder=_,b.renderOrder=u.renderOrder,b.z=m,b.group=f),t++,b}function l(u,p,g,_,m,f,b){b.reversedDepth===!0&&(m=-m);let E=a(u,p,g,_,m,f);g.transmission>0?n.push(E):g.transparent===!0?s.push(E):e.push(E)}function c(u,p,g,_,m,f){let b=a(u,p,g,_,m,f);g.transmission>0?n.unshift(b):g.transparent===!0?s.unshift(b):e.unshift(b)}function h(u,p){e.length>1&&e.sort(u||Vx),n.length>1&&n.sort(p||Ad),s.length>1&&s.sort(p||Ad)}function d(){for(let u=t,p=i.length;u=r.length?(o=new Rd,r.push(o)):o=r[s],o}function e(){i=new WeakMap}return{get:t,dispose:e}}function Wx(){let i={};return{get:function(t){if(i[t.id]!==void 0)return i[t.id];let e;switch(t.type){case"SunLight":case"DirectionalLight":e={direction:new I,color:new Ft};break;case"SpotLight":e={position:new I,direction:new I,color:new Ft,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":e={position:new I,color:new Ft,distance:0,decay:0};break;case"HemisphereLight":e={direction:new I,skyColor:new Ft,groundColor:new Ft};break;case"RectAreaLight":e={color:new Ft,position:new I,halfWidth:new I,halfHeight:new I};break}return i[t.id]=e,e}}}function Xx(){let i={};return{get:function(t){if(i[t.id]!==void 0)return i[t.id];let e;switch(t.type){case"SunLight":case"DirectionalLight":e={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Ht};break;case"SpotLight":e={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Ht};break;case"PointLight":e={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Ht,shadowCameraNear:1,shadowCameraFar:1e3};break}return i[t.id]=e,e}}}var qx=0;function Yx(i,t){return(t.castShadow?2:0)-(i.castShadow?2:0)+(t.map?1:0)-(i.map?1:0)}function $x(i){let t=new Wx,e=Xx(),n={version:0,hash:{sunLength:-1,directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numSunShadows:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],sun:[],sunShadow:[],sunShadowMap:[],sunShadowMatrix:[],sunShadowCascade:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let c=0;c<9;c++)n.probe.push(new I);let s=new I,r=new kt,o=new kt;function a(c){let h=0,d=0,u=0;for(let N=0;N<9;N++)n.probe[N].set(0,0,0);let p=0,g=0,_=0,m=0,f=0,b=0,E=0,M=0,v=0,S=0,A=0,x=0,T=0,R=0;c.sort(Yx);for(let N=0,U=c.length;N0&&(i.has("OES_texture_float_linear")===!0?(n.rectAreaLTC1=xt.LTC_FLOAT_1,n.rectAreaLTC2=xt.LTC_FLOAT_2):(n.rectAreaLTC1=xt.LTC_HALF_1,n.rectAreaLTC2=xt.LTC_HALF_2)),n.ambient[0]=h,n.ambient[1]=d,n.ambient[2]=u;let L=n.hash;(L.sunLength!==p||L.directionalLength!==m||L.pointLength!==f||L.spotLength!==b||L.rectAreaLength!==E||L.hemiLength!==M||L.numSunShadows!==g||L.numDirectionalShadows!==v||L.numPointShadows!==S||L.numSpotShadows!==A||L.numSpotMaps!==x||L.numLightProbes!==R)&&(n.sun.length=p,n.directional.length=m,n.spot.length=b,n.rectArea.length=E,n.point.length=f,n.hemi.length=M,n.sunShadow.length=g,n.sunShadowMap.length=g,n.sunShadowMatrix.length=_,n.sunShadowCascade.length=_,n.directionalShadow.length=v,n.directionalShadowMap.length=v,n.directionalShadowMatrix.length=v,n.pointShadow.length=S,n.pointShadowMap.length=S,n.pointShadowMatrix.length=S,n.spotShadow.length=A,n.spotShadowMap.length=A,n.spotLightMatrix.length=A+x-T,n.spotLightMap.length=x,n.numSpotLightShadowsWithMaps=T,n.numLightProbes=R,L.sunLength=p,L.directionalLength=m,L.pointLength=f,L.spotLength=b,L.rectAreaLength=E,L.hemiLength=M,L.numSunShadows=g,L.numDirectionalShadows=v,L.numPointShadows=S,L.numSpotShadows=A,L.numSpotMaps=x,L.numLightProbes=R,n.version=qx++)}function l(c,h){let d=0,u=0,p=0,g=0,_=0,m=0,f=h.matrixWorldInverse;for(let b=0,E=c.length;b=o.length?(a=new Cd(i),o.push(a)):a=o[r],a}function n(){t=new WeakMap}return{get:e,dispose:n}}var Jx=`void main() { gl_Position = vec4( position, 1.0 ); -}`,Zx=`uniform sampler2D shadow_pass; +}`,Kx=`uniform sampler2D shadow_pass; uniform vec2 resolution; uniform float radius; void main() { @@ -4193,12 +4193,12 @@ void main() { squared_mean = squared_mean / samples; float std_dev = sqrt( max( 0.0, squared_mean - mean * mean ) ); gl_FragColor = vec4( mean, std_dev, 0.0, 1.0 ); -}`,Jx=[new I(1,0,0),new I(-1,0,0),new I(0,1,0),new I(0,-1,0),new I(0,0,1),new I(0,0,-1)],Kx=[new I(0,-1,0),new I(0,-1,0),new I(0,0,1),new I(0,0,-1),new I(0,-1,0),new I(0,-1,0)],Cd=new kt,xr=new I,kc=new I;function jx(i,t,e){let n=new Un,s=new Ht,r=new Ht,o=new oe,a=new Do,l=new No,c={},h=e.maxTextureSize,d={[Bn]:Ve,[Ve]:Bn,[Ie]:Ie},u=new He({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new Ht},radius:{value:4}},vertexShader:$x,fragmentShader:Zx}),p=u.clone();p.defines.HORIZONTAL_PASS=1;let g=new ae;g.setAttribute("position",new Se(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));let _=new _e(g,u),m=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=lr;let f=this.type;this.render=function(S,A,x){if(m.enabled===!1||m.autoUpdate===!1&&m.needsUpdate===!1||S.length===0)return;this.type===wu&&(Dt("WebGLShadowMap: PCFSoftShadowMap has been removed. Using PCFShadowMap instead."),this.type=lr);let T=i.getRenderTarget(),R=i.getActiveCubeFace(),L=i.getActiveMipmapLevel(),N=i.state;N.setBlending(On),N.buffers.depth.getReversed()===!0?N.buffers.color.setClear(0,0,0,0):N.buffers.color.setClear(1,1,1,1),N.buffers.depth.setTest(!0),N.setScissorTest(!1);let U=f!==this.type;U&&A.traverse(function(C){C.material&&(Array.isArray(C.material)?C.material.forEach(B=>B.needsUpdate=!0):C.material.needsUpdate=!0)});for(let C=0,B=S.length;Ch||s.y>h)&&(s.x>h&&(r.x=Math.floor(h/F.x),s.x=r.x*F.x,W.mapSize.x=r.x),s.y>h&&(r.y=Math.floor(h/F.y),s.y=r.y*F.y,W.mapSize.y=r.y));let D=i.state.buffers.depth.getReversed();if(W.camera._reversedDepth=D,W.map===null||U===!0){if(W.map!==null&&(W.map.depthTexture!==null&&(W.map.depthTexture.dispose(),W.map.depthTexture=null),W.map.dispose()),this.type===vs){if(z.isPointLight){Dt("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}W.map=new Fe(s.x,s.y,{format:_i,type:Sn,minFilter:ze,magFilter:ze,generateMipmaps:!1}),W.map.texture.name=z.name+".shadowMap",W.map.depthTexture=new hi(s.x,s.y,Ge),W.map.depthTexture.name=z.name+".shadowMapDepth",W.map.depthTexture.format=Pn,W.map.depthTexture.compareFunction=null,W.map.depthTexture.minFilter=Ue,W.map.depthTexture.magFilter=Ue}else z.isPointLight?(W.map=new Ha(s.x),W.map.depthTexture=new Po(s.x,bn)):(W.map=new Fe(s.x,s.y),W.map.depthTexture=new hi(s.x,s.y,bn)),W.map.depthTexture.name=z.name+".shadowMap",W.map.depthTexture.format=Pn,this.type===lr?(W.map.depthTexture.compareFunction=D?Ba:Fa,W.map.depthTexture.minFilter=ze,W.map.depthTexture.magFilter=ze):(W.map.depthTexture.compareFunction=null,W.map.depthTexture.minFilter=Ue,W.map.depthTexture.magFilter=Ue);W.camera.updateProjectionMatrix()}W.map.isWebGLCubeRenderTarget!==!0&&(W.map.width!==s.x||W.map.height!==s.y)&&W.map.setSize(s.x,s.y);let X=W.map.isWebGLCubeRenderTarget?6:W.getViewportCount();z.isPointLight!==!0&&W.updateMatrices(z,x);for(let Z=0;Z0||A.map&&A.alphaTest>0||A.alphaToCoverage===!0){let N=R.uuid,U=A.uuid,C=c[N];C===void 0&&(C={},c[N]=C);let B=C[U];B===void 0&&(B=R.clone(),C[U]=B,A.addEventListener("dispose",v)),R=B}if(R.visible=A.visible,R.wireframe=A.wireframe,T===vs?R.side=A.shadowSide!==null?A.shadowSide:A.side:R.side=A.shadowSide!==null?A.shadowSide:d[A.side],R.alphaMap=A.alphaMap,R.alphaTest=A.alphaToCoverage===!0?.5:A.alphaTest,R.map=A.map,R.clipShadows=A.clipShadows,R.clippingPlanes=A.clippingPlanes,R.clipIntersection=A.clipIntersection,R.displacementMap=A.displacementMap,R.displacementScale=A.displacementScale,R.displacementBias=A.displacementBias,R.wireframeLinewidth=A.wireframeLinewidth,R.linewidth=A.linewidth,x.isPointLight===!0&&R.isMeshDistanceMaterial===!0){let N=i.properties.get(R);N.light=x}return R}function M(S,A,x,T,R){if(S.visible===!1)return;if(S.layers.test(A.layers)&&(S.isMesh||S.isLine||S.isPoints)&&(S.castShadow||S.receiveShadow&&R===vs)&&(!S.frustumCulled||S.intersectsFrustum(n))){S.modelViewMatrix.multiplyMatrices(x.matrixWorldInverse,S.matrixWorld);let U=t.update(S),C=S.material;if(Array.isArray(C)){let B=U.groups;for(let z=0,W=B.length;z=1):D.indexOf("OpenGL ES")!==-1&&(F=parseFloat(/^OpenGL ES (\d)/.exec(D)[1]),W=F>=2);let X=null,Z={},G=i.getParameter(i.SCISSOR_BOX),Q=i.getParameter(i.VIEWPORT),lt=new oe().fromArray(G),ct=new oe().fromArray(Q);function tt(k,mt,rt,gt){let bt=new Uint8Array(4),at=i.createTexture();i.bindTexture(k,at),i.texParameteri(k,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(k,i.TEXTURE_MAG_FILTER,i.NEAREST);for(let Pt=0;Pt"u"?!1:/OculusBrowser/g.test(navigator.userAgent),c=new Ht,h=new WeakMap,d=new Set,u,p=new WeakMap,g=!1;try{g=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function _(P,y){return g?new OffscreenCanvas(P,y):qs("canvas")}function m(P,y,q){let J=1,nt=ee(P);if((nt.width>q||nt.height>q)&&(J=q/Math.max(nt.width,nt.height)),J<1)if(typeof HTMLImageElement<"u"&&P instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&P instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&P instanceof ImageBitmap||typeof VideoFrame<"u"&&P instanceof VideoFrame){let ht=Math.floor(J*nt.width),dt=Math.floor(J*nt.height);u===void 0&&(u=_(ht,dt));let it=y?_(ht,dt):u;return it.width=ht,it.height=dt,it.getContext("2d").drawImage(P,0,0,ht,dt),Dt("WebGLRenderer: Texture has been resized from ("+nt.width+"x"+nt.height+") to ("+ht+"x"+dt+")."),it}else return"data"in P&&Dt("WebGLRenderer: Image in DataTexture is too big ("+nt.width+"x"+nt.height+")."),P;return P}function f(P){return P.generateMipmaps}function b(P){i.generateMipmap(P)}function E(P){return P.isWebGLCubeRenderTarget?i.TEXTURE_CUBE_MAP:P.isWebGL3DRenderTarget?i.TEXTURE_3D:P.isWebGLArrayRenderTarget||P.isCompressedArrayTexture?i.TEXTURE_2D_ARRAY:i.TEXTURE_2D}function M(P,y,q,J,nt,ht=!1){if(P!==null){if(i[P]!==void 0)return i[P];Dt("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+P+"'")}let dt;J&&(dt=t.get("EXT_texture_norm16"),dt||Dt("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension"));let it=y;if(y===i.RED&&(q===i.FLOAT&&(it=i.R32F),q===i.HALF_FLOAT&&(it=i.R16F),q===i.UNSIGNED_BYTE&&(it=i.R8),q===i.UNSIGNED_SHORT&&dt&&(it=dt.R16_EXT),q===i.SHORT&&dt&&(it=dt.R16_SNORM_EXT)),y===i.RED_INTEGER&&(q===i.UNSIGNED_BYTE&&(it=i.R8UI),q===i.UNSIGNED_SHORT&&(it=i.R16UI),q===i.UNSIGNED_INT&&(it=i.R32UI),q===i.BYTE&&(it=i.R8I),q===i.SHORT&&(it=i.R16I),q===i.INT&&(it=i.R32I)),y===i.RG&&(q===i.FLOAT&&(it=i.RG32F),q===i.HALF_FLOAT&&(it=i.RG16F),q===i.UNSIGNED_BYTE&&(it=i.RG8),q===i.UNSIGNED_SHORT&&dt&&(it=dt.RG16_EXT),q===i.SHORT&&dt&&(it=dt.RG16_SNORM_EXT)),y===i.RG_INTEGER&&(q===i.UNSIGNED_BYTE&&(it=i.RG8UI),q===i.UNSIGNED_SHORT&&(it=i.RG16UI),q===i.UNSIGNED_INT&&(it=i.RG32UI),q===i.BYTE&&(it=i.RG8I),q===i.SHORT&&(it=i.RG16I),q===i.INT&&(it=i.RG32I)),y===i.RGB_INTEGER&&(q===i.UNSIGNED_BYTE&&(it=i.RGB8UI),q===i.UNSIGNED_SHORT&&(it=i.RGB16UI),q===i.UNSIGNED_INT&&(it=i.RGB32UI),q===i.BYTE&&(it=i.RGB8I),q===i.SHORT&&(it=i.RGB16I),q===i.INT&&(it=i.RGB32I)),y===i.RGBA_INTEGER&&(q===i.UNSIGNED_BYTE&&(it=i.RGBA8UI),q===i.UNSIGNED_SHORT&&(it=i.RGBA16UI),q===i.UNSIGNED_INT&&(it=i.RGBA32UI),q===i.BYTE&&(it=i.RGBA8I),q===i.SHORT&&(it=i.RGBA16I),q===i.INT&&(it=i.RGBA32I)),y===i.RGB&&(q===i.UNSIGNED_SHORT&&dt&&(it=dt.RGB16_EXT),q===i.SHORT&&dt&&(it=dt.RGB16_SNORM_EXT),q===i.UNSIGNED_INT_5_9_9_9_REV&&(it=i.RGB9_E5),q===i.UNSIGNED_INT_10F_11F_11F_REV&&(it=i.R11F_G11F_B10F)),y===i.RGBA){let ot=ht?Xs:Yt.getTransfer(nt);q===i.FLOAT&&(it=i.RGBA32F),q===i.HALF_FLOAT&&(it=i.RGBA16F),q===i.UNSIGNED_BYTE&&(it=ot===te?i.SRGB8_ALPHA8:i.RGBA8),q===i.UNSIGNED_SHORT&&dt&&(it=dt.RGBA16_EXT),q===i.SHORT&&dt&&(it=dt.RGBA16_SNORM_EXT),q===i.UNSIGNED_SHORT_4_4_4_4&&(it=i.RGBA4),q===i.UNSIGNED_SHORT_5_5_5_1&&(it=i.RGB5_A1)}return(it===i.R16F||it===i.R32F||it===i.RG16F||it===i.RG32F||it===i.RGBA16F||it===i.RGBA32F)&&t.get("EXT_color_buffer_float"),it}function v(P,y){let q;return P?y===null||y===bn||y===bs?q=i.DEPTH24_STENCIL8:y===Ge?q=i.DEPTH32F_STENCIL8:y===Ms&&(q=i.DEPTH24_STENCIL8,Dt("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):y===null||y===bn||y===bs?q=i.DEPTH_COMPONENT24:y===Ge?q=i.DEPTH_COMPONENT32F:y===Ms&&(q=i.DEPTH_COMPONENT16),q}function S(P,y){return f(P)===!0||P.isFramebufferTexture&&P.minFilter!==Ue&&P.minFilter!==ze?Math.log2(Math.max(y.width,y.height))+1:P.mipmaps!==void 0&&P.mipmaps.length>0?P.mipmaps.length:P.isCompressedTexture&&Array.isArray(P.image)?y.mipmaps.length:1}function A(P){let y=P.target;y.removeEventListener("dispose",A),T(y),y.isVideoTexture&&h.delete(y),y.isHTMLTexture&&d.delete(y)}function x(P){let y=P.target;y.removeEventListener("dispose",x),L(y)}function T(P){let y=n.get(P);if(y.__webglInit===void 0)return;let q=P.source,J=p.get(q);if(J){let nt=J[y.__cacheKey];nt.usedTimes--,nt.usedTimes===0&&R(P),Object.keys(J).length===0&&p.delete(q)}n.remove(P)}function R(P){let y=n.get(P);i.deleteTexture(y.__webglTexture);let q=P.source,J=p.get(q);delete J[y.__cacheKey],o.memory.textures--}function L(P){let y=n.get(P);if(P.depthTexture&&(P.depthTexture.dispose(),n.remove(P.depthTexture)),P.isWebGLCubeRenderTarget)for(let J=0;J<6;J++){if(Array.isArray(y.__webglFramebuffer[J]))for(let nt=0;nt=s.maxTextures&&Dt("WebGLTextures: Trying to use "+(P+1)+" texture units while this GPU supports only "+s.maxTextures),N+=1,P}function W(P){let y=[];return y.push(P.wrapS),y.push(P.wrapT),y.push(P.wrapR||0),y.push(P.magFilter),y.push(P.minFilter),y.push(P.anisotropy),y.push(P.internalFormat),y.push(P.format),y.push(P.type),y.push(P.generateMipmaps),y.push(P.premultiplyAlpha),y.push(P.flipY),y.push(P.unpackAlignment),y.push(P.colorSpace),y.join()}function F(P,y){let q=n.get(P);if(P.isVideoTexture&&H(P),P.isRenderTargetTexture===!1&&P.isExternalTexture!==!0&&P.version>0&&q.__version!==P.version){let J=P.image;if(J===null)Dt("WebGLRenderer: Texture marked for update but no image data found.");else if(J.complete===!1)Dt("WebGLRenderer: Texture marked for update but image is incomplete");else{ut(q,P,y);return}}else P.isExternalTexture&&(q.__webglTexture=P.sourceTexture?P.sourceTexture:null);e.bindTexture(i.TEXTURE_2D,q.__webglTexture,i.TEXTURE0+y)}function D(P,y){let q=n.get(P);if(P.isRenderTargetTexture===!1&&P.version>0&&q.__version!==P.version){ut(q,P,y);return}else P.isExternalTexture&&(q.__webglTexture=P.sourceTexture?P.sourceTexture:null);e.bindTexture(i.TEXTURE_2D_ARRAY,q.__webglTexture,i.TEXTURE0+y)}function X(P,y){let q=n.get(P);if(P.isRenderTargetTexture===!1&&P.version>0&&q.__version!==P.version){ut(q,P,y);return}e.bindTexture(i.TEXTURE_3D,q.__webglTexture,i.TEXTURE0+y)}function Z(P,y){let q=n.get(P);if(P.isCubeDepthTexture!==!0&&P.version>0&&q.__version!==P.version){Lt(q,P,y);return}e.bindTexture(i.TEXTURE_CUBE_MAP,q.__webglTexture,i.TEXTURE0+y)}let G={[os]:i.REPEAT,[In]:i.CLAMP_TO_EDGE,[So]:i.MIRRORED_REPEAT},Q={[Ue]:i.NEAREST,[Xu]:i.NEAREST_MIPMAP_NEAREST,[hr]:i.NEAREST_MIPMAP_LINEAR,[ze]:i.LINEAR,[jo]:i.LINEAR_MIPMAP_NEAREST,[mi]:i.LINEAR_MIPMAP_LINEAR},lt={[Zu]:i.NEVER,[td]:i.ALWAYS,[Ju]:i.LESS,[Fa]:i.LEQUAL,[Ku]:i.EQUAL,[Ba]:i.GEQUAL,[ju]:i.GREATER,[Qu]:i.NOTEQUAL};function ct(P,y){if(y.type===Ge&&t.has("OES_texture_float_linear")===!1&&(y.magFilter===ze||y.magFilter===jo||y.magFilter===hr||y.magFilter===mi||y.minFilter===ze||y.minFilter===jo||y.minFilter===hr||y.minFilter===mi)&&Dt("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),i.texParameteri(P,i.TEXTURE_WRAP_S,G[y.wrapS]),i.texParameteri(P,i.TEXTURE_WRAP_T,G[y.wrapT]),(P===i.TEXTURE_3D||P===i.TEXTURE_2D_ARRAY)&&i.texParameteri(P,i.TEXTURE_WRAP_R,G[y.wrapR]),i.texParameteri(P,i.TEXTURE_MAG_FILTER,Q[y.magFilter]),i.texParameteri(P,i.TEXTURE_MIN_FILTER,Q[y.minFilter]),y.compareFunction&&(i.texParameteri(P,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE),i.texParameteri(P,i.TEXTURE_COMPARE_FUNC,lt[y.compareFunction])),t.has("EXT_texture_filter_anisotropic")===!0){if(y.magFilter===Ue||y.minFilter!==hr&&y.minFilter!==mi||y.type===Ge&&t.has("OES_texture_float_linear")===!1)return;if(y.anisotropy>1||n.get(y).__currentAnisotropy){let q=t.get("EXT_texture_filter_anisotropic");i.texParameterf(P,q.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(y.anisotropy,s.getMaxAnisotropy())),n.get(y).__currentAnisotropy=y.anisotropy}}}function tt(P,y){let q=!1;P.__webglInit===void 0&&(P.__webglInit=!0,y.addEventListener("dispose",A));let J=y.source,nt=p.get(J);nt===void 0&&(nt={},p.set(J,nt));let ht=W(y);if(ht!==P.__cacheKey){nt[ht]===void 0&&(nt[ht]={texture:i.createTexture(),usedTimes:0},o.memory.textures++,q=!0),nt[ht].usedTimes++;let dt=nt[P.__cacheKey];dt!==void 0&&(nt[P.__cacheKey].usedTimes--,dt.usedTimes===0&&R(y)),P.__cacheKey=ht,P.__webglTexture=nt[ht].texture}return q}function V(P,y,q){return Math.floor(Math.floor(P/q)/y)}function j(P,y,q,J){let ht=P.updateRanges;if(ht.length===0)e.texSubImage2D(i.TEXTURE_2D,0,0,0,y.width,y.height,q,J,y.data);else{ht.sort((Ct,_t)=>Ct.start-_t.start);let dt=0;for(let Ct=1;Ct0){Nt&&zt&&e.texStorage2D(i.TEXTURE_2D,mt,_t,It[0].width,It[0].height);for(let rt=0,gt=It.length;rt0){let bt=Cc(pt.width,pt.height,y.format,y.type);for(let at of y.layerUpdates){let Pt=pt.data.subarray(at*bt/pt.data.BYTES_PER_ELEMENT,(at+1)*bt/pt.data.BYTES_PER_ELEMENT);e.compressedTexSubImage3D(i.TEXTURE_2D_ARRAY,rt,0,0,at,pt.width,pt.height,1,ft,Pt)}}else e.compressedTexSubImage3D(i.TEXTURE_2D_ARRAY,rt,0,0,0,pt.width,pt.height,ot.depth,ft,pt.data)}else e.compressedTexImage3D(i.TEXTURE_2D_ARRAY,rt,_t,pt.width,pt.height,ot.depth,0,pt.data,0,0);else Dt("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else Nt?k&&e.texSubImage3D(i.TEXTURE_2D_ARRAY,rt,0,0,0,pt.width,pt.height,ot.depth,ft,Ct,pt.data):e.texImage3D(i.TEXTURE_2D_ARRAY,rt,_t,pt.width,pt.height,ot.depth,0,ft,Ct,pt.data);y.layerUpdates.size>0&&y.clearLayerUpdates()}else{Nt&&zt&&e.texStorage2D(i.TEXTURE_2D,mt,_t,It[0].width,It[0].height);for(let rt=0,gt=It.length;rt0){let rt=Cc(ot.width,ot.height,y.format,y.type);for(let gt of y.layerUpdates){let bt=ot.data.subarray(gt*rt/ot.data.BYTES_PER_ELEMENT,(gt+1)*rt/ot.data.BYTES_PER_ELEMENT);e.texSubImage3D(i.TEXTURE_2D_ARRAY,0,0,0,gt,ot.width,ot.height,1,ft,Ct,bt)}y.clearLayerUpdates()}else e.texSubImage3D(i.TEXTURE_2D_ARRAY,0,0,0,0,ot.width,ot.height,ot.depth,ft,Ct,ot.data)}else e.texImage3D(i.TEXTURE_2D_ARRAY,0,_t,ot.width,ot.height,ot.depth,0,ft,Ct,ot.data);else if(y.isData3DTexture)Nt?(zt&&e.texStorage3D(i.TEXTURE_3D,mt,_t,ot.width,ot.height,ot.depth),k&&e.texSubImage3D(i.TEXTURE_3D,0,0,0,0,ot.width,ot.height,ot.depth,ft,Ct,ot.data)):e.texImage3D(i.TEXTURE_3D,0,_t,ot.width,ot.height,ot.depth,0,ft,Ct,ot.data);else if(y.isFramebufferTexture){if(zt)if(Nt)e.texStorage2D(i.TEXTURE_2D,mt,_t,ot.width,ot.height);else{let rt=ot.width,gt=ot.height;for(let bt=0;bt>=1,gt>>=1}}else if(y.isHTMLTexture){if("texElementImage2D"in i){let rt=i.canvas;if(rt.hasAttribute("layoutsubtree")||rt.setAttribute("layoutsubtree","true"),ot.parentNode!==rt){rt.appendChild(ot),d.add(y),rt.onpaint=gt=>{let bt=gt.changedElements;for(let at of d)bt.includes(at.image)&&(at.needsUpdate=!0)},rt.requestPaint();return}if(i.texElementImage2D.length===3)i.texElementImage2D(i.TEXTURE_2D,i.RGBA8,ot);else{let bt=i.RGBA,at=i.RGBA,Pt=i.UNSIGNED_BYTE;i.texElementImage2D(i.TEXTURE_2D,0,bt,at,Pt,ot)}i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE)}}else if(It.length>0){if(Nt&&zt){let rt=ee(It[0]);e.texStorage2D(i.TEXTURE_2D,mt,_t,rt.width,rt.height)}for(let rt=0,gt=It.length;rt0&>++;let at=ee(_t[0]);e.texStorage2D(i.TEXTURE_CUBE_MAP,gt,zt,at.width,at.height)}for(let at=0;at<6;at++)if(Ct){k?rt&&e.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+at,0,0,0,_t[at].width,_t[at].height,It,Nt,_t[at].data):e.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+at,0,zt,_t[at].width,_t[at].height,0,It,Nt,_t[at].data);for(let Pt=0;Pt>ht),pt=Math.max(1,y.height>>ht);nt===i.TEXTURE_3D||nt===i.TEXTURE_2D_ARRAY?e.texImage3D(nt,ht,ot,_t,pt,y.depth,0,dt,it,null):e.texImage2D(nt,ht,ot,_t,pt,0,dt,it,null)}e.bindFramebuffer(i.FRAMEBUFFER,P),we(y)?a.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER,J,nt,Ct.__webglTexture,0,Me(y)):(nt===i.TEXTURE_2D||nt>=i.TEXTURE_CUBE_MAP_POSITIVE_X&&nt<=i.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&i.framebufferTexture2D(i.FRAMEBUFFER,J,nt,Ct.__webglTexture,ht),e.bindFramebuffer(i.FRAMEBUFFER,null)}function Bt(P,y,q){if(i.bindRenderbuffer(i.RENDERBUFFER,P),y.depthBuffer){let J=y.depthTexture,nt=J&&J.isDepthTexture?J.type:null,ht=v(y.stencilBuffer,nt),dt=y.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT;we(y)?a.renderbufferStorageMultisampleEXT(i.RENDERBUFFER,Me(y),ht,y.width,y.height):q?i.renderbufferStorageMultisample(i.RENDERBUFFER,Me(y),ht,y.width,y.height):i.renderbufferStorage(i.RENDERBUFFER,ht,y.width,y.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,dt,i.RENDERBUFFER,P)}else{let J=y.textures;for(let nt=0;nt{delete y.__boundDepthTexture,delete y.__depthDisposeCallback,J.removeEventListener("dispose",nt)};J.addEventListener("dispose",nt),y.__depthDisposeCallback=nt}y.__boundDepthTexture=J}if(P.depthTexture&&!y.__autoAllocateDepthBuffer)if(q)for(let J=0;J<6;J++)xe(y.__webglFramebuffer[J],P,J);else{let J=P.texture.mipmaps;J&&J.length>0?xe(y.__webglFramebuffer[0],P,0):xe(y.__webglFramebuffer,P,0)}else if(q){y.__webglDepthbuffer=[];for(let J=0;J<6;J++)if(e.bindFramebuffer(i.FRAMEBUFFER,y.__webglFramebuffer[J]),y.__webglDepthbuffer[J]===void 0)y.__webglDepthbuffer[J]=i.createRenderbuffer(),Bt(y.__webglDepthbuffer[J],P,!1);else{let nt=P.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,ht=y.__webglDepthbuffer[J];i.bindRenderbuffer(i.RENDERBUFFER,ht),i.framebufferRenderbuffer(i.FRAMEBUFFER,nt,i.RENDERBUFFER,ht)}}else{let J=P.texture.mipmaps;if(J&&J.length>0?e.bindFramebuffer(i.FRAMEBUFFER,y.__webglFramebuffer[0]):e.bindFramebuffer(i.FRAMEBUFFER,y.__webglFramebuffer),y.__webglDepthbuffer===void 0)y.__webglDepthbuffer=i.createRenderbuffer(),Bt(y.__webglDepthbuffer,P,!1);else{let nt=P.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,ht=y.__webglDepthbuffer;i.bindRenderbuffer(i.RENDERBUFFER,ht),i.framebufferRenderbuffer(i.FRAMEBUFFER,nt,i.RENDERBUFFER,ht)}}e.bindFramebuffer(i.FRAMEBUFFER,null)}function Jt(P,y,q){let J=n.get(P);y!==void 0&&Mt(J.__webglFramebuffer,P,P.texture,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,0),q!==void 0&&Vt(P)}function le(P){let y=P.texture,q=n.get(P),J=n.get(y);P.addEventListener("dispose",x);let nt=P.textures,ht=P.isWebGLCubeRenderTarget===!0,dt=nt.length>1;if(dt||(J.__webglTexture===void 0&&(J.__webglTexture=i.createTexture()),J.__version=y.version,o.memory.textures++),ht){q.__webglFramebuffer=[];for(let it=0;it<6;it++)if(y.mipmaps&&y.mipmaps.length>0){q.__webglFramebuffer[it]=[];for(let ot=0;ot0){q.__webglFramebuffer=[];for(let it=0;it0&&we(P)===!1){q.__webglMultisampledFramebuffer=i.createFramebuffer(),q.__webglColorRenderbuffer=[],e.bindFramebuffer(i.FRAMEBUFFER,q.__webglMultisampledFramebuffer);for(let it=0;it0)for(let ot=0;ot0)for(let ot=0;ot0){if(we(P)===!1){let y=P.textures,q=P.width,J=P.height,nt=i.COLOR_BUFFER_BIT,ht=P.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,dt=n.get(P),it=y.length>1;if(it)for(let ft=0;ft0?e.bindFramebuffer(i.DRAW_FRAMEBUFFER,dt.__webglFramebuffer[0]):e.bindFramebuffer(i.DRAW_FRAMEBUFFER,dt.__webglFramebuffer);for(let ft=0;ft0&&t.has("WEBGL_multisampled_render_to_texture")===!0&&y.__useRenderToTexture!==!1}function H(P){let y=o.render.frame;h.get(P)!==y&&(h.set(P,y),P.update())}function We(P,y){let q=P.colorSpace,J=P.format,nt=P.type;return P.isCompressedTexture===!0||P.isVideoTexture===!0||q!==Ws&&q!==jn&&(Yt.getTransfer(q)===te?(J!==sn||nt!==nn)&&Dt("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):Ut("WebGLTextures: Unsupported texture color space:",q)),y}function ee(P){return typeof HTMLImageElement<"u"&&P instanceof HTMLImageElement?(c.width=P.naturalWidth||P.width,c.height=P.naturalHeight||P.height):typeof VideoFrame<"u"&&P instanceof VideoFrame?(c.width=P.displayWidth,c.height=P.displayHeight):(c.width=P.width,c.height=P.height),c}this.allocateTextureUnit=z,this.resetTextureUnits=U,this.getTextureUnits=C,this.setTextureUnits=B,this.setTexture2D=F,this.setTexture2DArray=D,this.setTexture3D=X,this.setTextureCube=Z,this.rebindTextures=Jt,this.setupRenderTarget=le,this.updateRenderTargetMipmap=qt,this.updateMultisampleRenderTarget=tn,this.setupDepthRenderbuffer=Vt,this.setupFrameBufferTexture=Mt,this.useMultisampledRTT=we,this.isReversedDepthBuffer=function(){return e.buffers.depth.getReversed()}}function ev(i,t){function e(n,s=jn){let r,o=Yt.getTransfer(s);if(n===nn)return i.UNSIGNED_BYTE;if(n===ta)return i.UNSIGNED_SHORT_4_4_4_4;if(n===ea)return i.UNSIGNED_SHORT_5_5_5_1;if(n===mc)return i.UNSIGNED_INT_5_9_9_9_REV;if(n===gc)return i.UNSIGNED_INT_10F_11F_11F_REV;if(n===fc)return i.BYTE;if(n===pc)return i.SHORT;if(n===Ms)return i.UNSIGNED_SHORT;if(n===Qo)return i.INT;if(n===bn)return i.UNSIGNED_INT;if(n===Ge)return i.FLOAT;if(n===Sn)return i.HALF_FLOAT;if(n===_c)return i.ALPHA;if(n===xc)return i.RGB;if(n===sn)return i.RGBA;if(n===Pn)return i.DEPTH_COMPONENT;if(n===gi)return i.DEPTH_STENCIL;if(n===Ss)return i.RED;if(n===na)return i.RED_INTEGER;if(n===_i)return i.RG;if(n===ia)return i.RG_INTEGER;if(n===sa)return i.RGBA_INTEGER;if(n===ur||n===dr||n===fr||n===pr)if(o===te)if(r=t.get("WEBGL_compressed_texture_s3tc_srgb"),r!==null){if(n===ur)return r.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(n===dr)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(n===fr)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(n===pr)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(r=t.get("WEBGL_compressed_texture_s3tc"),r!==null){if(n===ur)return r.COMPRESSED_RGB_S3TC_DXT1_EXT;if(n===dr)return r.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(n===fr)return r.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(n===pr)return r.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(n===ra||n===oa||n===aa||n===la)if(r=t.get("WEBGL_compressed_texture_pvrtc"),r!==null){if(n===ra)return r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(n===oa)return r.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(n===aa)return r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(n===la)return r.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(n===ca||n===ha||n===ua||n===da||n===fa||n===mr||n===pa)if(r=t.get("WEBGL_compressed_texture_etc"),r!==null){if(n===ca||n===ha)return o===te?r.COMPRESSED_SRGB8_ETC2:r.COMPRESSED_RGB8_ETC2;if(n===ua)return o===te?r.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:r.COMPRESSED_RGBA8_ETC2_EAC;if(n===da)return r.COMPRESSED_R11_EAC;if(n===fa)return r.COMPRESSED_SIGNED_R11_EAC;if(n===mr)return r.COMPRESSED_RG11_EAC;if(n===pa)return r.COMPRESSED_SIGNED_RG11_EAC}else return null;if(n===ma||n===ga||n===_a||n===xa||n===va||n===ya||n===Ma||n===ba||n===Sa||n===wa||n===Ea||n===Ta||n===Aa||n===Ra)if(r=t.get("WEBGL_compressed_texture_astc"),r!==null){if(n===ma)return o===te?r.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:r.COMPRESSED_RGBA_ASTC_4x4_KHR;if(n===ga)return o===te?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:r.COMPRESSED_RGBA_ASTC_5x4_KHR;if(n===_a)return o===te?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:r.COMPRESSED_RGBA_ASTC_5x5_KHR;if(n===xa)return o===te?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:r.COMPRESSED_RGBA_ASTC_6x5_KHR;if(n===va)return o===te?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:r.COMPRESSED_RGBA_ASTC_6x6_KHR;if(n===ya)return o===te?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:r.COMPRESSED_RGBA_ASTC_8x5_KHR;if(n===Ma)return o===te?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:r.COMPRESSED_RGBA_ASTC_8x6_KHR;if(n===ba)return o===te?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:r.COMPRESSED_RGBA_ASTC_8x8_KHR;if(n===Sa)return o===te?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:r.COMPRESSED_RGBA_ASTC_10x5_KHR;if(n===wa)return o===te?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:r.COMPRESSED_RGBA_ASTC_10x6_KHR;if(n===Ea)return o===te?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:r.COMPRESSED_RGBA_ASTC_10x8_KHR;if(n===Ta)return o===te?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:r.COMPRESSED_RGBA_ASTC_10x10_KHR;if(n===Aa)return o===te?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:r.COMPRESSED_RGBA_ASTC_12x10_KHR;if(n===Ra)return o===te?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:r.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(n===Ca||n===Ia||n===Pa)if(r=t.get("EXT_texture_compression_bptc"),r!==null){if(n===Ca)return o===te?r.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:r.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(n===Ia)return r.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(n===Pa)return r.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(n===La||n===Da||n===gr||n===Na)if(r=t.get("EXT_texture_compression_rgtc"),r!==null){if(n===La)return r.COMPRESSED_RED_RGTC1_EXT;if(n===Da)return r.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(n===gr)return r.COMPRESSED_RED_GREEN_RGTC2_EXT;if(n===Na)return r.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return n===bs?i.UNSIGNED_INT_24_8:i[n]!==void 0?i[n]:null}return{convert:e}}var nv=` +}`,jx=[new I(1,0,0),new I(-1,0,0),new I(0,1,0),new I(0,-1,0),new I(0,0,1),new I(0,0,-1)],Qx=[new I(0,-1,0),new I(0,-1,0),new I(0,0,1),new I(0,0,-1),new I(0,-1,0),new I(0,-1,0)],Id=new kt,vr=new I,kc=new I;function tv(i,t,e){let n=new Un,s=new Ht,r=new Ht,o=new ae,a=new Do,l=new No,c={},h=e.maxTextureSize,d={[Bn]:Ve,[Ve]:Bn,[Ie]:Ie},u=new He({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new Ht},radius:{value:4}},vertexShader:Jx,fragmentShader:Kx}),p=u.clone();p.defines.HORIZONTAL_PASS=1;let g=new le;g.setAttribute("position",new Se(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));let _=new xe(g,u),m=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=cr;let f=this.type;this.render=function(S,A,x){if(m.enabled===!1||m.autoUpdate===!1&&m.needsUpdate===!1||S.length===0)return;this.type===Eu&&(Dt("WebGLShadowMap: PCFSoftShadowMap has been removed. Using PCFShadowMap instead."),this.type=cr);let T=i.getRenderTarget(),R=i.getActiveCubeFace(),L=i.getActiveMipmapLevel(),N=i.state;N.setBlending(On),N.buffers.depth.getReversed()===!0?N.buffers.color.setClear(0,0,0,0):N.buffers.color.setClear(1,1,1,1),N.buffers.depth.setTest(!0),N.setScissorTest(!1);let U=f!==this.type;U&&A.traverse(function(C){C.material&&(Array.isArray(C.material)?C.material.forEach(B=>B.needsUpdate=!0):C.material.needsUpdate=!0)});for(let C=0,B=S.length;Ch||s.y>h)&&(s.x>h&&(r.x=Math.floor(h/F.x),s.x=r.x*F.x,W.mapSize.x=r.x),s.y>h&&(r.y=Math.floor(h/F.y),s.y=r.y*F.y,W.mapSize.y=r.y));let D=i.state.buffers.depth.getReversed();if(W.camera._reversedDepth=D,W.map===null||U===!0){if(W.map!==null&&(W.map.depthTexture!==null&&(W.map.depthTexture.dispose(),W.map.depthTexture=null),W.map.dispose()),this.type===vs){if(z.isPointLight){Dt("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}W.map=new Fe(s.x,s.y,{format:_i,type:Sn,minFilter:ze,magFilter:ze,generateMipmaps:!1}),W.map.texture.name=z.name+".shadowMap",W.map.depthTexture=new hi(s.x,s.y,Ge),W.map.depthTexture.name=z.name+".shadowMapDepth",W.map.depthTexture.format=Pn,W.map.depthTexture.compareFunction=null,W.map.depthTexture.minFilter=Ue,W.map.depthTexture.magFilter=Ue}else z.isPointLight?(W.map=new Ha(s.x),W.map.depthTexture=new Po(s.x,bn)):(W.map=new Fe(s.x,s.y),W.map.depthTexture=new hi(s.x,s.y,bn)),W.map.depthTexture.name=z.name+".shadowMap",W.map.depthTexture.format=Pn,this.type===cr?(W.map.depthTexture.compareFunction=D?Ba:Fa,W.map.depthTexture.minFilter=ze,W.map.depthTexture.magFilter=ze):(W.map.depthTexture.compareFunction=null,W.map.depthTexture.minFilter=Ue,W.map.depthTexture.magFilter=Ue);W.camera.updateProjectionMatrix()}W.map.isWebGLCubeRenderTarget!==!0&&(W.map.width!==s.x||W.map.height!==s.y)&&W.map.setSize(s.x,s.y);let X=W.map.isWebGLCubeRenderTarget?6:W.getViewportCount();z.isPointLight!==!0&&W.updateMatrices(z,x);for(let Z=0;Z0||A.map&&A.alphaTest>0||A.alphaToCoverage===!0){let N=R.uuid,U=A.uuid,C=c[N];C===void 0&&(C={},c[N]=C);let B=C[U];B===void 0&&(B=R.clone(),C[U]=B,A.addEventListener("dispose",v)),R=B}if(R.visible=A.visible,R.wireframe=A.wireframe,T===vs?R.side=A.shadowSide!==null?A.shadowSide:A.side:R.side=A.shadowSide!==null?A.shadowSide:d[A.side],R.alphaMap=A.alphaMap,R.alphaTest=A.alphaToCoverage===!0?.5:A.alphaTest,R.map=A.map,R.clipShadows=A.clipShadows,R.clippingPlanes=A.clippingPlanes,R.clipIntersection=A.clipIntersection,R.displacementMap=A.displacementMap,R.displacementScale=A.displacementScale,R.displacementBias=A.displacementBias,R.wireframeLinewidth=A.wireframeLinewidth,R.linewidth=A.linewidth,x.isPointLight===!0&&R.isMeshDistanceMaterial===!0){let N=i.properties.get(R);N.light=x}return R}function M(S,A,x,T,R){if(S.visible===!1)return;if(S.layers.test(A.layers)&&(S.isMesh||S.isLine||S.isPoints)&&(S.castShadow||S.receiveShadow&&R===vs)&&(!S.frustumCulled||S.intersectsFrustum(n))){S.modelViewMatrix.multiplyMatrices(x.matrixWorldInverse,S.matrixWorld);let U=t.update(S),C=S.material;if(Array.isArray(C)){let B=U.groups;for(let z=0,W=B.length;z=1):D.indexOf("OpenGL ES")!==-1&&(F=parseFloat(/^OpenGL ES (\d)/.exec(D)[1]),W=F>=2);let X=null,Z={},G=i.getParameter(i.SCISSOR_BOX),Q=i.getParameter(i.VIEWPORT),lt=new ae().fromArray(G),ct=new ae().fromArray(Q);function et(k,mt,rt,gt){let bt=new Uint8Array(4),at=i.createTexture();i.bindTexture(k,at),i.texParameteri(k,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(k,i.TEXTURE_MAG_FILTER,i.NEAREST);for(let Pt=0;Pt"u"?!1:/OculusBrowser/g.test(navigator.userAgent),c=new Ht,h=new WeakMap,d=new Set,u,p=new WeakMap,g=!1;try{g=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function _(P,y){return g?new OffscreenCanvas(P,y):Ys("canvas")}function m(P,y,q){let J=1,nt=ee(P);if((nt.width>q||nt.height>q)&&(J=q/Math.max(nt.width,nt.height)),J<1)if(typeof HTMLImageElement<"u"&&P instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&P instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&P instanceof ImageBitmap||typeof VideoFrame<"u"&&P instanceof VideoFrame){let ht=Math.floor(J*nt.width),dt=Math.floor(J*nt.height);u===void 0&&(u=_(ht,dt));let it=y?_(ht,dt):u;return it.width=ht,it.height=dt,it.getContext("2d").drawImage(P,0,0,ht,dt),Dt("WebGLRenderer: Texture has been resized from ("+nt.width+"x"+nt.height+") to ("+ht+"x"+dt+")."),it}else return"data"in P&&Dt("WebGLRenderer: Image in DataTexture is too big ("+nt.width+"x"+nt.height+")."),P;return P}function f(P){return P.generateMipmaps}function b(P){i.generateMipmap(P)}function E(P){return P.isWebGLCubeRenderTarget?i.TEXTURE_CUBE_MAP:P.isWebGL3DRenderTarget?i.TEXTURE_3D:P.isWebGLArrayRenderTarget||P.isCompressedArrayTexture?i.TEXTURE_2D_ARRAY:i.TEXTURE_2D}function M(P,y,q,J,nt,ht=!1){if(P!==null){if(i[P]!==void 0)return i[P];Dt("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+P+"'")}let dt;J&&(dt=t.get("EXT_texture_norm16"),dt||Dt("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension"));let it=y;if(y===i.RED&&(q===i.FLOAT&&(it=i.R32F),q===i.HALF_FLOAT&&(it=i.R16F),q===i.UNSIGNED_BYTE&&(it=i.R8),q===i.UNSIGNED_SHORT&&dt&&(it=dt.R16_EXT),q===i.SHORT&&dt&&(it=dt.R16_SNORM_EXT)),y===i.RED_INTEGER&&(q===i.UNSIGNED_BYTE&&(it=i.R8UI),q===i.UNSIGNED_SHORT&&(it=i.R16UI),q===i.UNSIGNED_INT&&(it=i.R32UI),q===i.BYTE&&(it=i.R8I),q===i.SHORT&&(it=i.R16I),q===i.INT&&(it=i.R32I)),y===i.RG&&(q===i.FLOAT&&(it=i.RG32F),q===i.HALF_FLOAT&&(it=i.RG16F),q===i.UNSIGNED_BYTE&&(it=i.RG8),q===i.UNSIGNED_SHORT&&dt&&(it=dt.RG16_EXT),q===i.SHORT&&dt&&(it=dt.RG16_SNORM_EXT)),y===i.RG_INTEGER&&(q===i.UNSIGNED_BYTE&&(it=i.RG8UI),q===i.UNSIGNED_SHORT&&(it=i.RG16UI),q===i.UNSIGNED_INT&&(it=i.RG32UI),q===i.BYTE&&(it=i.RG8I),q===i.SHORT&&(it=i.RG16I),q===i.INT&&(it=i.RG32I)),y===i.RGB_INTEGER&&(q===i.UNSIGNED_BYTE&&(it=i.RGB8UI),q===i.UNSIGNED_SHORT&&(it=i.RGB16UI),q===i.UNSIGNED_INT&&(it=i.RGB32UI),q===i.BYTE&&(it=i.RGB8I),q===i.SHORT&&(it=i.RGB16I),q===i.INT&&(it=i.RGB32I)),y===i.RGBA_INTEGER&&(q===i.UNSIGNED_BYTE&&(it=i.RGBA8UI),q===i.UNSIGNED_SHORT&&(it=i.RGBA16UI),q===i.UNSIGNED_INT&&(it=i.RGBA32UI),q===i.BYTE&&(it=i.RGBA8I),q===i.SHORT&&(it=i.RGBA16I),q===i.INT&&(it=i.RGBA32I)),y===i.RGB&&(q===i.UNSIGNED_SHORT&&dt&&(it=dt.RGB16_EXT),q===i.SHORT&&dt&&(it=dt.RGB16_SNORM_EXT),q===i.UNSIGNED_INT_5_9_9_9_REV&&(it=i.RGB9_E5),q===i.UNSIGNED_INT_10F_11F_11F_REV&&(it=i.R11F_G11F_B10F)),y===i.RGBA){let ot=ht?qs:Yt.getTransfer(nt);q===i.FLOAT&&(it=i.RGBA32F),q===i.HALF_FLOAT&&(it=i.RGBA16F),q===i.UNSIGNED_BYTE&&(it=ot===te?i.SRGB8_ALPHA8:i.RGBA8),q===i.UNSIGNED_SHORT&&dt&&(it=dt.RGBA16_EXT),q===i.SHORT&&dt&&(it=dt.RGBA16_SNORM_EXT),q===i.UNSIGNED_SHORT_4_4_4_4&&(it=i.RGBA4),q===i.UNSIGNED_SHORT_5_5_5_1&&(it=i.RGB5_A1)}return(it===i.R16F||it===i.R32F||it===i.RG16F||it===i.RG32F||it===i.RGBA16F||it===i.RGBA32F)&&t.get("EXT_color_buffer_float"),it}function v(P,y){let q;return P?y===null||y===bn||y===bs?q=i.DEPTH24_STENCIL8:y===Ge?q=i.DEPTH32F_STENCIL8:y===Ms&&(q=i.DEPTH24_STENCIL8,Dt("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):y===null||y===bn||y===bs?q=i.DEPTH_COMPONENT24:y===Ge?q=i.DEPTH_COMPONENT32F:y===Ms&&(q=i.DEPTH_COMPONENT16),q}function S(P,y){return f(P)===!0||P.isFramebufferTexture&&P.minFilter!==Ue&&P.minFilter!==ze?Math.log2(Math.max(y.width,y.height))+1:P.mipmaps!==void 0&&P.mipmaps.length>0?P.mipmaps.length:P.isCompressedTexture&&Array.isArray(P.image)?y.mipmaps.length:1}function A(P){let y=P.target;y.removeEventListener("dispose",A),T(y),y.isVideoTexture&&h.delete(y),y.isHTMLTexture&&d.delete(y)}function x(P){let y=P.target;y.removeEventListener("dispose",x),L(y)}function T(P){let y=n.get(P);if(y.__webglInit===void 0)return;let q=P.source,J=p.get(q);if(J){let nt=J[y.__cacheKey];nt.usedTimes--,nt.usedTimes===0&&R(P),Object.keys(J).length===0&&p.delete(q)}n.remove(P)}function R(P){let y=n.get(P);i.deleteTexture(y.__webglTexture);let q=P.source,J=p.get(q);delete J[y.__cacheKey],o.memory.textures--}function L(P){let y=n.get(P);if(P.depthTexture&&(P.depthTexture.dispose(),n.remove(P.depthTexture)),P.isWebGLCubeRenderTarget)for(let J=0;J<6;J++){if(Array.isArray(y.__webglFramebuffer[J]))for(let nt=0;nt=s.maxTextures&&Dt("WebGLTextures: Trying to use "+(P+1)+" texture units while this GPU supports only "+s.maxTextures),N+=1,P}function W(P){let y=[];return y.push(P.wrapS),y.push(P.wrapT),y.push(P.wrapR||0),y.push(P.magFilter),y.push(P.minFilter),y.push(P.anisotropy),y.push(P.internalFormat),y.push(P.format),y.push(P.type),y.push(P.generateMipmaps),y.push(P.premultiplyAlpha),y.push(P.flipY),y.push(P.unpackAlignment),y.push(P.colorSpace),y.join()}function F(P,y){let q=n.get(P);if(P.isVideoTexture&&H(P),P.isRenderTargetTexture===!1&&P.isExternalTexture!==!0&&P.version>0&&q.__version!==P.version){let J=P.image;if(J===null)Dt("WebGLRenderer: Texture marked for update but no image data found.");else if(J.complete===!1)Dt("WebGLRenderer: Texture marked for update but image is incomplete");else{ut(q,P,y);return}}else P.isExternalTexture&&(q.__webglTexture=P.sourceTexture?P.sourceTexture:null);e.bindTexture(i.TEXTURE_2D,q.__webglTexture,i.TEXTURE0+y)}function D(P,y){let q=n.get(P);if(P.isRenderTargetTexture===!1&&P.version>0&&q.__version!==P.version){ut(q,P,y);return}else P.isExternalTexture&&(q.__webglTexture=P.sourceTexture?P.sourceTexture:null);e.bindTexture(i.TEXTURE_2D_ARRAY,q.__webglTexture,i.TEXTURE0+y)}function X(P,y){let q=n.get(P);if(P.isRenderTargetTexture===!1&&P.version>0&&q.__version!==P.version){ut(q,P,y);return}e.bindTexture(i.TEXTURE_3D,q.__webglTexture,i.TEXTURE0+y)}function Z(P,y){let q=n.get(P);if(P.isCubeDepthTexture!==!0&&P.version>0&&q.__version!==P.version){Lt(q,P,y);return}e.bindTexture(i.TEXTURE_CUBE_MAP,q.__webglTexture,i.TEXTURE0+y)}let G={[os]:i.REPEAT,[In]:i.CLAMP_TO_EDGE,[So]:i.MIRRORED_REPEAT},Q={[Ue]:i.NEAREST,[qu]:i.NEAREST_MIPMAP_NEAREST,[ur]:i.NEAREST_MIPMAP_LINEAR,[ze]:i.LINEAR,[jo]:i.LINEAR_MIPMAP_NEAREST,[mi]:i.LINEAR_MIPMAP_LINEAR},lt={[Ju]:i.NEVER,[ed]:i.ALWAYS,[Ku]:i.LESS,[Fa]:i.LEQUAL,[ju]:i.EQUAL,[Ba]:i.GEQUAL,[Qu]:i.GREATER,[td]:i.NOTEQUAL};function ct(P,y){if(y.type===Ge&&t.has("OES_texture_float_linear")===!1&&(y.magFilter===ze||y.magFilter===jo||y.magFilter===ur||y.magFilter===mi||y.minFilter===ze||y.minFilter===jo||y.minFilter===ur||y.minFilter===mi)&&Dt("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),i.texParameteri(P,i.TEXTURE_WRAP_S,G[y.wrapS]),i.texParameteri(P,i.TEXTURE_WRAP_T,G[y.wrapT]),(P===i.TEXTURE_3D||P===i.TEXTURE_2D_ARRAY)&&i.texParameteri(P,i.TEXTURE_WRAP_R,G[y.wrapR]),i.texParameteri(P,i.TEXTURE_MAG_FILTER,Q[y.magFilter]),i.texParameteri(P,i.TEXTURE_MIN_FILTER,Q[y.minFilter]),y.compareFunction&&(i.texParameteri(P,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE),i.texParameteri(P,i.TEXTURE_COMPARE_FUNC,lt[y.compareFunction])),t.has("EXT_texture_filter_anisotropic")===!0){if(y.magFilter===Ue||y.minFilter!==ur&&y.minFilter!==mi||y.type===Ge&&t.has("OES_texture_float_linear")===!1)return;if(y.anisotropy>1||n.get(y).__currentAnisotropy){let q=t.get("EXT_texture_filter_anisotropic");i.texParameterf(P,q.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(y.anisotropy,s.getMaxAnisotropy())),n.get(y).__currentAnisotropy=y.anisotropy}}}function et(P,y){let q=!1;P.__webglInit===void 0&&(P.__webglInit=!0,y.addEventListener("dispose",A));let J=y.source,nt=p.get(J);nt===void 0&&(nt={},p.set(J,nt));let ht=W(y);if(ht!==P.__cacheKey){nt[ht]===void 0&&(nt[ht]={texture:i.createTexture(),usedTimes:0},o.memory.textures++,q=!0),nt[ht].usedTimes++;let dt=nt[P.__cacheKey];dt!==void 0&&(nt[P.__cacheKey].usedTimes--,dt.usedTimes===0&&R(y)),P.__cacheKey=ht,P.__webglTexture=nt[ht].texture}return q}function V(P,y,q){return Math.floor(Math.floor(P/q)/y)}function j(P,y,q,J){let ht=P.updateRanges;if(ht.length===0)e.texSubImage2D(i.TEXTURE_2D,0,0,0,y.width,y.height,q,J,y.data);else{ht.sort((Ct,_t)=>Ct.start-_t.start);let dt=0;for(let Ct=1;Ct0){Nt&&zt&&e.texStorage2D(i.TEXTURE_2D,mt,_t,It[0].width,It[0].height);for(let rt=0,gt=It.length;rt0){let bt=Cc(pt.width,pt.height,y.format,y.type);for(let at of y.layerUpdates){let Pt=pt.data.subarray(at*bt/pt.data.BYTES_PER_ELEMENT,(at+1)*bt/pt.data.BYTES_PER_ELEMENT);e.compressedTexSubImage3D(i.TEXTURE_2D_ARRAY,rt,0,0,at,pt.width,pt.height,1,ft,Pt)}}else e.compressedTexSubImage3D(i.TEXTURE_2D_ARRAY,rt,0,0,0,pt.width,pt.height,ot.depth,ft,pt.data)}else e.compressedTexImage3D(i.TEXTURE_2D_ARRAY,rt,_t,pt.width,pt.height,ot.depth,0,pt.data,0,0);else Dt("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else Nt?k&&e.texSubImage3D(i.TEXTURE_2D_ARRAY,rt,0,0,0,pt.width,pt.height,ot.depth,ft,Ct,pt.data):e.texImage3D(i.TEXTURE_2D_ARRAY,rt,_t,pt.width,pt.height,ot.depth,0,ft,Ct,pt.data);y.layerUpdates.size>0&&y.clearLayerUpdates()}else{Nt&&zt&&e.texStorage2D(i.TEXTURE_2D,mt,_t,It[0].width,It[0].height);for(let rt=0,gt=It.length;rt0){let rt=Cc(ot.width,ot.height,y.format,y.type);for(let gt of y.layerUpdates){let bt=ot.data.subarray(gt*rt/ot.data.BYTES_PER_ELEMENT,(gt+1)*rt/ot.data.BYTES_PER_ELEMENT);e.texSubImage3D(i.TEXTURE_2D_ARRAY,0,0,0,gt,ot.width,ot.height,1,ft,Ct,bt)}y.clearLayerUpdates()}else e.texSubImage3D(i.TEXTURE_2D_ARRAY,0,0,0,0,ot.width,ot.height,ot.depth,ft,Ct,ot.data)}else e.texImage3D(i.TEXTURE_2D_ARRAY,0,_t,ot.width,ot.height,ot.depth,0,ft,Ct,ot.data);else if(y.isData3DTexture)Nt?(zt&&e.texStorage3D(i.TEXTURE_3D,mt,_t,ot.width,ot.height,ot.depth),k&&e.texSubImage3D(i.TEXTURE_3D,0,0,0,0,ot.width,ot.height,ot.depth,ft,Ct,ot.data)):e.texImage3D(i.TEXTURE_3D,0,_t,ot.width,ot.height,ot.depth,0,ft,Ct,ot.data);else if(y.isFramebufferTexture){if(zt)if(Nt)e.texStorage2D(i.TEXTURE_2D,mt,_t,ot.width,ot.height);else{let rt=ot.width,gt=ot.height;for(let bt=0;bt>=1,gt>>=1}}else if(y.isHTMLTexture){if("texElementImage2D"in i){let rt=i.canvas;if(rt.hasAttribute("layoutsubtree")||rt.setAttribute("layoutsubtree","true"),ot.parentNode!==rt){rt.appendChild(ot),d.add(y),rt.onpaint=gt=>{let bt=gt.changedElements;for(let at of d)bt.includes(at.image)&&(at.needsUpdate=!0)},rt.requestPaint();return}if(i.texElementImage2D.length===3)i.texElementImage2D(i.TEXTURE_2D,i.RGBA8,ot);else{let bt=i.RGBA,at=i.RGBA,Pt=i.UNSIGNED_BYTE;i.texElementImage2D(i.TEXTURE_2D,0,bt,at,Pt,ot)}i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE)}}else if(It.length>0){if(Nt&&zt){let rt=ee(It[0]);e.texStorage2D(i.TEXTURE_2D,mt,_t,rt.width,rt.height)}for(let rt=0,gt=It.length;rt0&>++;let at=ee(_t[0]);e.texStorage2D(i.TEXTURE_CUBE_MAP,gt,zt,at.width,at.height)}for(let at=0;at<6;at++)if(Ct){k?rt&&e.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+at,0,0,0,_t[at].width,_t[at].height,It,Nt,_t[at].data):e.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+at,0,zt,_t[at].width,_t[at].height,0,It,Nt,_t[at].data);for(let Pt=0;Pt>ht),pt=Math.max(1,y.height>>ht);nt===i.TEXTURE_3D||nt===i.TEXTURE_2D_ARRAY?e.texImage3D(nt,ht,ot,_t,pt,y.depth,0,dt,it,null):e.texImage2D(nt,ht,ot,_t,pt,0,dt,it,null)}e.bindFramebuffer(i.FRAMEBUFFER,P),we(y)?a.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER,J,nt,Ct.__webglTexture,0,Me(y)):(nt===i.TEXTURE_2D||nt>=i.TEXTURE_CUBE_MAP_POSITIVE_X&&nt<=i.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&i.framebufferTexture2D(i.FRAMEBUFFER,J,nt,Ct.__webglTexture,ht),e.bindFramebuffer(i.FRAMEBUFFER,null)}function Bt(P,y,q){if(i.bindRenderbuffer(i.RENDERBUFFER,P),y.depthBuffer){let J=y.depthTexture,nt=J&&J.isDepthTexture?J.type:null,ht=v(y.stencilBuffer,nt),dt=y.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT;we(y)?a.renderbufferStorageMultisampleEXT(i.RENDERBUFFER,Me(y),ht,y.width,y.height):q?i.renderbufferStorageMultisample(i.RENDERBUFFER,Me(y),ht,y.width,y.height):i.renderbufferStorage(i.RENDERBUFFER,ht,y.width,y.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,dt,i.RENDERBUFFER,P)}else{let J=y.textures;for(let nt=0;nt{delete y.__boundDepthTexture,delete y.__depthDisposeCallback,J.removeEventListener("dispose",nt)};J.addEventListener("dispose",nt),y.__depthDisposeCallback=nt}y.__boundDepthTexture=J}if(P.depthTexture&&!y.__autoAllocateDepthBuffer)if(q)for(let J=0;J<6;J++)ve(y.__webglFramebuffer[J],P,J);else{let J=P.texture.mipmaps;J&&J.length>0?ve(y.__webglFramebuffer[0],P,0):ve(y.__webglFramebuffer,P,0)}else if(q){y.__webglDepthbuffer=[];for(let J=0;J<6;J++)if(e.bindFramebuffer(i.FRAMEBUFFER,y.__webglFramebuffer[J]),y.__webglDepthbuffer[J]===void 0)y.__webglDepthbuffer[J]=i.createRenderbuffer(),Bt(y.__webglDepthbuffer[J],P,!1);else{let nt=P.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,ht=y.__webglDepthbuffer[J];i.bindRenderbuffer(i.RENDERBUFFER,ht),i.framebufferRenderbuffer(i.FRAMEBUFFER,nt,i.RENDERBUFFER,ht)}}else{let J=P.texture.mipmaps;if(J&&J.length>0?e.bindFramebuffer(i.FRAMEBUFFER,y.__webglFramebuffer[0]):e.bindFramebuffer(i.FRAMEBUFFER,y.__webglFramebuffer),y.__webglDepthbuffer===void 0)y.__webglDepthbuffer=i.createRenderbuffer(),Bt(y.__webglDepthbuffer,P,!1);else{let nt=P.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,ht=y.__webglDepthbuffer;i.bindRenderbuffer(i.RENDERBUFFER,ht),i.framebufferRenderbuffer(i.FRAMEBUFFER,nt,i.RENDERBUFFER,ht)}}e.bindFramebuffer(i.FRAMEBUFFER,null)}function Jt(P,y,q){let J=n.get(P);y!==void 0&&Mt(J.__webglFramebuffer,P,P.texture,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,0),q!==void 0&&Vt(P)}function he(P){let y=P.texture,q=n.get(P),J=n.get(y);P.addEventListener("dispose",x);let nt=P.textures,ht=P.isWebGLCubeRenderTarget===!0,dt=nt.length>1;if(dt||(J.__webglTexture===void 0&&(J.__webglTexture=i.createTexture()),J.__version=y.version,o.memory.textures++),ht){q.__webglFramebuffer=[];for(let it=0;it<6;it++)if(y.mipmaps&&y.mipmaps.length>0){q.__webglFramebuffer[it]=[];for(let ot=0;ot0){q.__webglFramebuffer=[];for(let it=0;it0&&we(P)===!1){q.__webglMultisampledFramebuffer=i.createFramebuffer(),q.__webglColorRenderbuffer=[],e.bindFramebuffer(i.FRAMEBUFFER,q.__webglMultisampledFramebuffer);for(let it=0;it0)for(let ot=0;ot0)for(let ot=0;ot0){if(we(P)===!1){let y=P.textures,q=P.width,J=P.height,nt=i.COLOR_BUFFER_BIT,ht=P.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,dt=n.get(P),it=y.length>1;if(it)for(let ft=0;ft0?e.bindFramebuffer(i.DRAW_FRAMEBUFFER,dt.__webglFramebuffer[0]):e.bindFramebuffer(i.DRAW_FRAMEBUFFER,dt.__webglFramebuffer);for(let ft=0;ft0&&t.has("WEBGL_multisampled_render_to_texture")===!0&&y.__useRenderToTexture!==!1}function H(P){let y=o.render.frame;h.get(P)!==y&&(h.set(P,y),P.update())}function We(P,y){let q=P.colorSpace,J=P.format,nt=P.type;return P.isCompressedTexture===!0||P.isVideoTexture===!0||q!==Xs&&q!==jn&&(Yt.getTransfer(q)===te?(J!==sn||nt!==nn)&&Dt("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):Ut("WebGLTextures: Unsupported texture color space:",q)),y}function ee(P){return typeof HTMLImageElement<"u"&&P instanceof HTMLImageElement?(c.width=P.naturalWidth||P.width,c.height=P.naturalHeight||P.height):typeof VideoFrame<"u"&&P instanceof VideoFrame?(c.width=P.displayWidth,c.height=P.displayHeight):(c.width=P.width,c.height=P.height),c}this.allocateTextureUnit=z,this.resetTextureUnits=U,this.getTextureUnits=C,this.setTextureUnits=B,this.setTexture2D=F,this.setTexture2DArray=D,this.setTexture3D=X,this.setTextureCube=Z,this.rebindTextures=Jt,this.setupRenderTarget=he,this.updateRenderTargetMipmap=qt,this.updateMultisampleRenderTarget=tn,this.setupDepthRenderbuffer=Vt,this.setupFrameBufferTexture=Mt,this.useMultisampledRTT=we,this.isReversedDepthBuffer=function(){return e.buffers.depth.getReversed()}}function iv(i,t){function e(n,s=jn){let r,o=Yt.getTransfer(s);if(n===nn)return i.UNSIGNED_BYTE;if(n===ta)return i.UNSIGNED_SHORT_4_4_4_4;if(n===ea)return i.UNSIGNED_SHORT_5_5_5_1;if(n===mc)return i.UNSIGNED_INT_5_9_9_9_REV;if(n===gc)return i.UNSIGNED_INT_10F_11F_11F_REV;if(n===fc)return i.BYTE;if(n===pc)return i.SHORT;if(n===Ms)return i.UNSIGNED_SHORT;if(n===Qo)return i.INT;if(n===bn)return i.UNSIGNED_INT;if(n===Ge)return i.FLOAT;if(n===Sn)return i.HALF_FLOAT;if(n===_c)return i.ALPHA;if(n===xc)return i.RGB;if(n===sn)return i.RGBA;if(n===Pn)return i.DEPTH_COMPONENT;if(n===gi)return i.DEPTH_STENCIL;if(n===Ss)return i.RED;if(n===na)return i.RED_INTEGER;if(n===_i)return i.RG;if(n===ia)return i.RG_INTEGER;if(n===sa)return i.RGBA_INTEGER;if(n===dr||n===fr||n===pr||n===mr)if(o===te)if(r=t.get("WEBGL_compressed_texture_s3tc_srgb"),r!==null){if(n===dr)return r.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(n===fr)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(n===pr)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(n===mr)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(r=t.get("WEBGL_compressed_texture_s3tc"),r!==null){if(n===dr)return r.COMPRESSED_RGB_S3TC_DXT1_EXT;if(n===fr)return r.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(n===pr)return r.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(n===mr)return r.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(n===ra||n===oa||n===aa||n===la)if(r=t.get("WEBGL_compressed_texture_pvrtc"),r!==null){if(n===ra)return r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(n===oa)return r.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(n===aa)return r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(n===la)return r.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(n===ca||n===ha||n===ua||n===da||n===fa||n===gr||n===pa)if(r=t.get("WEBGL_compressed_texture_etc"),r!==null){if(n===ca||n===ha)return o===te?r.COMPRESSED_SRGB8_ETC2:r.COMPRESSED_RGB8_ETC2;if(n===ua)return o===te?r.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:r.COMPRESSED_RGBA8_ETC2_EAC;if(n===da)return r.COMPRESSED_R11_EAC;if(n===fa)return r.COMPRESSED_SIGNED_R11_EAC;if(n===gr)return r.COMPRESSED_RG11_EAC;if(n===pa)return r.COMPRESSED_SIGNED_RG11_EAC}else return null;if(n===ma||n===ga||n===_a||n===xa||n===va||n===ya||n===Ma||n===ba||n===Sa||n===wa||n===Ea||n===Ta||n===Aa||n===Ra)if(r=t.get("WEBGL_compressed_texture_astc"),r!==null){if(n===ma)return o===te?r.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:r.COMPRESSED_RGBA_ASTC_4x4_KHR;if(n===ga)return o===te?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:r.COMPRESSED_RGBA_ASTC_5x4_KHR;if(n===_a)return o===te?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:r.COMPRESSED_RGBA_ASTC_5x5_KHR;if(n===xa)return o===te?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:r.COMPRESSED_RGBA_ASTC_6x5_KHR;if(n===va)return o===te?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:r.COMPRESSED_RGBA_ASTC_6x6_KHR;if(n===ya)return o===te?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:r.COMPRESSED_RGBA_ASTC_8x5_KHR;if(n===Ma)return o===te?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:r.COMPRESSED_RGBA_ASTC_8x6_KHR;if(n===ba)return o===te?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:r.COMPRESSED_RGBA_ASTC_8x8_KHR;if(n===Sa)return o===te?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:r.COMPRESSED_RGBA_ASTC_10x5_KHR;if(n===wa)return o===te?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:r.COMPRESSED_RGBA_ASTC_10x6_KHR;if(n===Ea)return o===te?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:r.COMPRESSED_RGBA_ASTC_10x8_KHR;if(n===Ta)return o===te?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:r.COMPRESSED_RGBA_ASTC_10x10_KHR;if(n===Aa)return o===te?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:r.COMPRESSED_RGBA_ASTC_12x10_KHR;if(n===Ra)return o===te?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:r.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(n===Ca||n===Ia||n===Pa)if(r=t.get("EXT_texture_compression_bptc"),r!==null){if(n===Ca)return o===te?r.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:r.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(n===Ia)return r.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(n===Pa)return r.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(n===La||n===Da||n===_r||n===Na)if(r=t.get("EXT_texture_compression_rgtc"),r!==null){if(n===La)return r.COMPRESSED_RED_RGTC1_EXT;if(n===Da)return r.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(n===_r)return r.COMPRESSED_RED_GREEN_RGTC2_EXT;if(n===Na)return r.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return n===bs?i.UNSIGNED_INT_24_8:i[n]!==void 0?i[n]:null}return{convert:e}}var sv=` void main() { gl_Position = vec4( position, 1.0 ); -}`,iv=` +}`,rv=` uniform sampler2DArray depthColor; uniform float depthWidth; uniform float depthHeight; @@ -4217,7 +4217,7 @@ void main() { } -}`,$c=class{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(t,e){if(this.texture===null){let n=new tr(t.texture);(t.depthNear!==e.depthNear||t.depthFar!==e.depthFar)&&(this.depthNear=t.depthNear,this.depthFar=t.depthFar),this.texture=n}}getMesh(t){if(this.texture!==null&&this.mesh===null){let e=t.cameras[0].viewport,n=new He({vertexShader:nv,fragmentShader:iv,uniforms:{depthColor:{value:this.texture},depthWidth:{value:e.z},depthHeight:{value:e.w}}});this.mesh=new _e(new yn(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}},Zc=class extends Ln{constructor(t,e){super();let n=this,s=null,r=1,o=null,a="local-floor",l=1,c=null,h=null,d=null,u=null,p=null,g=null,_=typeof XRWebGLBinding<"u",m=new $c,f={},b=e.getContextAttributes(),E=null,M=null,v=[],S=[],A=new Ht,x=null,T=null,R=new $e;R.viewport=new oe;let L=new $e;L.viewport=new oe;let N=[R,L],U=new Yo,C=null,B=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(V){let j=v[V];return j===void 0&&(j=new ds,v[V]=j),j.getTargetRaySpace()},this.getControllerGrip=function(V){let j=v[V];return j===void 0&&(j=new ds,v[V]=j),j.getGripSpace()},this.getHand=function(V){let j=v[V];return j===void 0&&(j=new ds,v[V]=j),j.getHandSpace()};function z(V){let j=S.indexOf(V.inputSource);if(j===-1)return;let ut=v[j];ut!==void 0&&(ut.update(V.inputSource,V.frame,c||o),ut.dispatchEvent({type:V.type,data:V.inputSource}))}function W(){s.removeEventListener("select",z),s.removeEventListener("selectstart",z),s.removeEventListener("selectend",z),s.removeEventListener("squeeze",z),s.removeEventListener("squeezestart",z),s.removeEventListener("squeezeend",z),s.removeEventListener("end",W),s.removeEventListener("inputsourceschange",F);for(let V=0;V=0&&(S[Lt]=null,v[Lt].disconnect(ut))}for(let j=0;j=S.length){S.push(ut),Lt=Bt;break}else if(S[Bt]===null){S[Bt]=ut,Lt=Bt;break}if(Lt===-1)break}let Mt=v[Lt];Mt&&Mt.connect(ut)}}let D=new I,X=new I;function Z(V,j,ut){D.setFromMatrixPosition(j.matrixWorld),X.setFromMatrixPosition(ut.matrixWorld);let Lt=D.distanceTo(X),Mt=j.projectionMatrix.elements,Bt=ut.projectionMatrix.elements,xe=Mt[14]/(Mt[10]-1),Vt=Mt[14]/(Mt[10]+1),Jt=(Mt[9]+1)/Mt[5],le=(Mt[9]-1)/Mt[5],qt=(Mt[8]-1)/Mt[0],ve=(Bt[8]+1)/Bt[0],De=xe*qt,tn=xe*ve,Me=Lt/(-qt+ve),we=Me*-qt;if(j.matrixWorld.decompose(V.position,V.quaternion,V.scale),V.translateX(we),V.translateZ(Me),V.matrixWorld.compose(V.position,V.quaternion,V.scale),V.matrixWorldInverse.copy(V.matrixWorld).invert(),Mt[10]===-1)V.projectionMatrix.copy(j.projectionMatrix),V.projectionMatrixInverse.copy(j.projectionMatrixInverse);else{let H=xe+Me,We=Vt+Me,ee=De-we,P=tn+(Lt-we),y=Jt*Vt/We*H,q=le*Vt/We*H;V.projectionMatrix.makePerspective(ee,P,y,q,H,We),V.projectionMatrixInverse.copy(V.projectionMatrix).invert()}}function G(V,j){j===null?V.matrixWorld.copy(V.matrix):V.matrixWorld.multiplyMatrices(j.matrixWorld,V.matrix),V.matrixWorldInverse.copy(V.matrixWorld).invert()}this.updateCamera=function(V){if(s===null)return;let j=V.near,ut=V.far;m.texture!==null&&(m.depthNear>0&&(j=m.depthNear),m.depthFar>0&&(ut=m.depthFar)),U.near=L.near=R.near=j,U.far=L.far=R.far=ut,(C!==U.near||B!==U.far)&&(s.updateRenderState({depthNear:U.near,depthFar:U.far}),C=U.near,B=U.far),U.layers.mask=V.layers.mask|6,R.layers.mask=U.layers.mask&-5,L.layers.mask=U.layers.mask&-3;let Lt=V.parent,Mt=U.cameras;G(U,Lt);for(let Bt=0;Bt0&&(m.alphaTest.value=f.alphaTest);let b=t.get(f),E=b.envMap,M=b.envMapRotation;E&&(m.envMap.value=E,m.envMapRotation.value.setFromMatrix4(sv.makeRotationFromEuler(M)).transpose(),E.isCubeTexture&&E.isRenderTargetTexture===!1&&m.envMapRotation.value.premultiply(Fd),m.reflectivity.value=f.reflectivity,m.ior.value=f.ior,m.refractionRatio.value=f.refractionRatio),f.lightMap&&(m.lightMap.value=f.lightMap,m.lightMapIntensity.value=f.lightMapIntensity,e(f.lightMap,m.lightMapTransform)),f.aoMap&&(m.aoMap.value=f.aoMap,m.aoMapIntensity.value=f.aoMapIntensity,e(f.aoMap,m.aoMapTransform))}function o(m,f){m.diffuse.value.copy(f.color),m.opacity.value=f.opacity,f.map&&(m.map.value=f.map,e(f.map,m.mapTransform))}function a(m,f){m.dashSize.value=f.dashSize,m.totalSize.value=f.dashSize+f.gapSize,m.scale.value=f.scale}function l(m,f,b,E){m.diffuse.value.copy(f.color),m.opacity.value=f.opacity,m.size.value=f.size*b,m.scale.value=E*.5,f.map&&(m.map.value=f.map,e(f.map,m.uvTransform)),f.alphaMap&&(m.alphaMap.value=f.alphaMap,e(f.alphaMap,m.alphaMapTransform)),f.alphaTest>0&&(m.alphaTest.value=f.alphaTest)}function c(m,f){m.diffuse.value.copy(f.color),m.opacity.value=f.opacity,m.rotation.value=f.rotation,f.map&&(m.map.value=f.map,e(f.map,m.mapTransform)),f.alphaMap&&(m.alphaMap.value=f.alphaMap,e(f.alphaMap,m.alphaMapTransform)),f.alphaTest>0&&(m.alphaTest.value=f.alphaTest)}function h(m,f){m.specular.value.copy(f.specular),m.shininess.value=Math.max(f.shininess,1e-4)}function d(m,f){f.gradientMap&&(m.gradientMap.value=f.gradientMap)}function u(m,f){m.metalness.value=f.metalness,f.metalnessMap&&(m.metalnessMap.value=f.metalnessMap,e(f.metalnessMap,m.metalnessMapTransform)),m.roughness.value=f.roughness,f.roughnessMap&&(m.roughnessMap.value=f.roughnessMap,e(f.roughnessMap,m.roughnessMapTransform)),f.envMap&&(m.envMapIntensity.value=f.envMapIntensity)}function p(m,f,b){m.ior.value=f.ior,f.sheen>0&&(m.sheenColor.value.copy(f.sheenColor).multiplyScalar(f.sheen),m.sheenRoughness.value=f.sheenRoughness,f.sheenColorMap&&(m.sheenColorMap.value=f.sheenColorMap,e(f.sheenColorMap,m.sheenColorMapTransform)),f.sheenRoughnessMap&&(m.sheenRoughnessMap.value=f.sheenRoughnessMap,e(f.sheenRoughnessMap,m.sheenRoughnessMapTransform))),f.clearcoat>0&&(m.clearcoat.value=f.clearcoat,m.clearcoatRoughness.value=f.clearcoatRoughness,f.clearcoatMap&&(m.clearcoatMap.value=f.clearcoatMap,e(f.clearcoatMap,m.clearcoatMapTransform)),f.clearcoatRoughnessMap&&(m.clearcoatRoughnessMap.value=f.clearcoatRoughnessMap,e(f.clearcoatRoughnessMap,m.clearcoatRoughnessMapTransform)),f.clearcoatNormalMap&&(m.clearcoatNormalMap.value=f.clearcoatNormalMap,e(f.clearcoatNormalMap,m.clearcoatNormalMapTransform),m.clearcoatNormalScale.value.copy(f.clearcoatNormalScale),f.side===Ve&&m.clearcoatNormalScale.value.negate())),f.dispersion>0&&(m.dispersion.value=f.dispersion),f.retroreflectivity>0&&(m.retroreflectivity.value=f.retroreflectivity),f.iridescence>0&&(m.iridescence.value=f.iridescence,m.iridescenceIOR.value=f.iridescenceIOR,m.iridescenceThicknessMinimum.value=f.iridescenceThicknessRange[0],m.iridescenceThicknessMaximum.value=f.iridescenceThicknessRange[1],f.iridescenceMap&&(m.iridescenceMap.value=f.iridescenceMap,e(f.iridescenceMap,m.iridescenceMapTransform)),f.iridescenceThicknessMap&&(m.iridescenceThicknessMap.value=f.iridescenceThicknessMap,e(f.iridescenceThicknessMap,m.iridescenceThicknessMapTransform))),f.transmission>0&&(m.transmission.value=f.transmission,m.transmissionSamplerMap.value=b.texture,m.transmissionSamplerSize.value.set(b.width,b.height),f.transmissionMap&&(m.transmissionMap.value=f.transmissionMap,e(f.transmissionMap,m.transmissionMapTransform)),m.thickness.value=f.thickness,f.thicknessMap&&(m.thicknessMap.value=f.thicknessMap,e(f.thicknessMap,m.thicknessMapTransform)),m.attenuationDistance.value=f.attenuationDistance,m.attenuationColor.value.copy(f.attenuationColor)),f.anisotropy>0&&(m.anisotropyVector.value.set(f.anisotropy*Math.cos(f.anisotropyRotation),f.anisotropy*Math.sin(f.anisotropyRotation)),f.anisotropyMap&&(m.anisotropyMap.value=f.anisotropyMap,e(f.anisotropyMap,m.anisotropyMapTransform))),m.specularIntensity.value=f.specularIntensity,m.specularColor.value.copy(f.specularColor),f.specularColorMap&&(m.specularColorMap.value=f.specularColorMap,e(f.specularColorMap,m.specularColorMapTransform)),f.specularIntensityMap&&(m.specularIntensityMap.value=f.specularIntensityMap,e(f.specularIntensityMap,m.specularIntensityMapTransform))}function g(m,f){f.matcap&&(m.matcap.value=f.matcap)}function _(m,f){let b=t.get(f).light;m.referencePosition.value.setFromMatrixPosition(b.matrixWorld),m.nearDistance.value=b.shadow.camera.near,m.farDistance.value=b.shadow.camera.far}return{refreshFogUniforms:n,refreshMaterialUniforms:s}}function ov(i,t,e,n){let s={},r={},o=[],a=i.getParameter(i.MAX_UNIFORM_BUFFER_BINDINGS);function l(M,v){let S=v.program;n.uniformBlockBinding(M,S)}function c(M,v){let S=s[M.id];S===void 0&&(m(M),S=h(M),s[M.id]=S,M.addEventListener("dispose",b));let A=v.program;n.updateUBOMapping(M,A);let x=t.render.frame;r[M.id]!==x&&(u(M),r[M.id]=x)}function h(M){let v=d();M.__bindingPointIndex=v;let S=i.createBuffer(),A=M.__size,x=M.usage;return i.bindBuffer(i.UNIFORM_BUFFER,S),i.bufferData(i.UNIFORM_BUFFER,A,x),i.bindBuffer(i.UNIFORM_BUFFER,null),i.bindBufferBase(i.UNIFORM_BUFFER,v,S),S}function d(){for(let M=0;M0&&(S+=A-x),M.__size=S,M.__cache={},this}function f(M){let v={boundary:0,storage:0};return typeof M=="number"||typeof M=="boolean"?(v.boundary=4,v.storage=4):M.isVector2?(v.boundary=8,v.storage=8):M.isVector3||M.isColor?(v.boundary=16,v.storage=12):M.isVector4?(v.boundary=16,v.storage=16):M.isMatrix3?(v.boundary=48,v.storage=48):M.isMatrix4?(v.boundary=64,v.storage=64):M.isTexture?Dt("WebGLRenderer: Texture samplers can not be part of an uniforms group."):ArrayBuffer.isView(M)?(v.boundary=16,v.storage=M.byteLength):Dt("WebGLRenderer: Unsupported uniform value type.",M),v}function b(M){let v=M.target;v.removeEventListener("dispose",b);let S=o.indexOf(v.__bindingPointIndex);o.splice(S,1),i.deleteBuffer(s[v.id]),delete s[v.id],delete r[v.id]}function E(){for(let M in s)i.deleteBuffer(s[M]);o=[],s={},r={}}return{bind:l,update:c,dispose:E}}var av=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]),zn=null;function lv(){return zn===null&&(zn=new Nn(av,16,16,_i,Sn),zn.name="DFG_LUT",zn.minFilter=ze,zn.magFilter=ze,zn.wrapS=In,zn.wrapT=In,zn.generateMipmaps=!1,zn.needsUpdate=!0),zn}var As=class{constructor(t={}){let{canvas:e=ed(),context:n=null,depth:s=!0,stencil:r=!1,alpha:o=!1,antialias:a=!1,premultipliedAlpha:l=!0,preserveDrawingBuffer:c=!1,powerPreference:h="default",failIfMajorPerformanceCaveat:d=!1,reversedDepthBuffer:u=!1,outputBufferType:p=nn}=t;this.isWebGLRenderer=!0;let g;if(n!==null){if(typeof WebGLRenderingContext<"u"&&n instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");g=n.getContextAttributes().alpha}else g=o;let _=p,m=new Set([sa,ia,na]),f=new Set([nn,bn,Ms,bs,ta,ea]),b=new Uint32Array(4),E=new Int32Array(4),M=new I,v=null,S=null,A=[],x=[],T=null;this.domElement=e,this.debug={checkShaderErrors:!0,diagnostics:{keywords:!1},onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=Mn,this.toneMappingExposure=1,this.transmissionResolutionScale=1;let R=this,L=!1,N=null,U=null,C=null,B=null;this._outputColorSpace=Ae;let z=0,W=0,F=null,D=-1,X=null,Z=new oe,G=new oe,Q=null,lt=new Ft(0),ct=0,tt=e.width,V=e.height,j=1,ut=null,Lt=null,Mt=new oe(0,0,tt,V),Bt=new oe(0,0,tt,V),xe=!1,Vt=new Un,Jt=!1,le=!1,qt=new kt,ve=new I,De=new oe,tn={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0},Me=!1;function we(){return F===null?j:1}let H=n;function We(w,O){return e.getContext(w,O)}let ee,P,y,q,J,nt,ht,dt,it,ot,ft,Ct,_t,pt,It,Nt,zt,k,mt,rt,gt,bt,at;try{let w={alpha:!0,depth:s,stencil:r,antialias:a,premultipliedAlpha:l,preserveDrawingBuffer:c,powerPreference:h,failIfMajorPerformanceCaveat:d};if("setAttribute"in e&&e.setAttribute("data-engine",`three.js r${"186"}`),e.addEventListener("webglcontextlost",ce,!1),e.addEventListener("webglcontextrestored",jt,!1),e.addEventListener("webglcontextcreationerror",fn,!1),H===null){let O="webgl2";if(H=We(O,w),H===null)throw We(O)?new Error("THREE.WebGLRenderer: Error creating WebGL context with your selected attributes."):new Error("THREE.WebGLRenderer: Error creating WebGL context.")}Pt()}catch(w){throw e.removeEventListener("webglcontextlost",ce,!1),e.removeEventListener("webglcontextrestored",jt,!1),e.removeEventListener("webglcontextcreationerror",fn,!1),Ut("WebGLRenderer: "+w.message),w}function Pt(){ee=new m0(H),ee.init(),gt=new ev(H,ee),P=new r0(H,ee,t,gt),y=new Qx(H,ee),P.reversedDepthBuffer&&u&&y.buffers.depth.setReversed(!0),U=H.createFramebuffer(),C=H.createFramebuffer(),B=H.createFramebuffer(),q=new x0(H),J=new zx,nt=new tv(H,ee,y,J,P,gt,q),ht=new p0(R),dt=new ym(H),bt=new i0(H,dt),it=new g0(H,dt,q,bt),ot=new y0(H,it,dt,bt,q),k=new v0(H,P,nt),It=new o0(J),ft=new Ox(R,ht,ee,P,bt,It),Ct=new rv(R,J),_t=new Hx,pt=new Yx(ee),zt=new n0(R,ht,y,ot,g,l),Nt=new jx(R,ot,P),at=new ov(H,q,P,y),mt=new s0(H,ee,q),rt=new _0(H,ee,q),q.programs=ft.programs,R.capabilities=P,R.extensions=ee,R.properties=J,R.renderLists=_t,R.shadowMap=Nt,R.state=y,R.info=q}_!==nn&&(T=new b0(_,e.width,e.height,a,s,r));let At=new Zc(R,H);this.xr=At,this.getContext=function(){return H},this.getContextAttributes=function(){return H.getContextAttributes()},this.forceContextLoss=function(){let w=ee.get("WEBGL_lose_context");w&&w.loseContext()},this.forceContextRestore=function(){let w=ee.get("WEBGL_lose_context");w&&w.restoreContext()},this.getPixelRatio=function(){return j},this.setPixelRatio=function(w){w!==void 0&&(j=w,this.setSize(tt,V,!1))},this.getSize=function(w){return w.set(tt,V)},this.setSize=function(w,O,K=!0){if(At.isPresenting){Dt("WebGLRenderer: Can't change size while VR device is presenting.");return}tt=w,V=O,e.width=Math.floor(w*j),e.height=Math.floor(O*j),K===!0&&(e.style.width=w+"px",e.style.height=O+"px"),T!==null&&T.setSize(e.width,e.height),this.setViewport(0,0,w,O)},this.getDrawingBufferSize=function(w){return w.set(tt*j,V*j).floor()},this.setDrawingBufferSize=function(w,O,K){tt=w,V=O,j=K,e.width=Math.floor(w*K),e.height=Math.floor(O*K),this.setViewport(0,0,w,O)},this.setEffects=function(w){if(_===nn){Ut("WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.");return}if(w){for(let O=0;O{function yt(){if(Y.forEach(function(wt){let Et=J.get(wt).currentProgram;(Et===void 0||Et.isReady())&&Y.delete(wt)}),Y.size===0){$(w);return}setTimeout(yt,10)}ee.get("KHR_parallel_shader_compile")!==null?yt():setTimeout(yt,10)})};let _l=null;function _p(w){_l&&_l(w)}function Dh(){Mi.stop()}function Nh(){Mi.start()}let Mi=new Id;Mi.setAnimationLoop(_p),typeof self<"u"&&Mi.setContext(self),this.setAnimationLoop=function(w){_l=w,At.setAnimationLoop(w),w===null?Mi.stop():Mi.start()},At.addEventListener("sessionstart",Dh),At.addEventListener("sessionend",Nh),this.render=function(w,O){if(O!==void 0&&O.isCamera!==!0){Ut("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(L===!0)return;N!==null&&N.renderStart(w,O);let K=At.enabled===!0&&At.isPresenting===!0,Y=T!==null&&(F===null||K)&&T.begin(R,F);if(w.matrixWorldAutoUpdate===!0&&w.updateMatrixWorld(),O.parent===null&&O.matrixWorldAutoUpdate===!0&&O.updateMatrixWorld(),At.enabled===!0&&At.isPresenting===!0&&(T===null||T.isCompositing()===!1)&&(At.cameraAutoUpdate===!0&&At.updateCamera(O),O=At.getCamera()),w.isScene===!0&&w.onBeforeRender(R,w,O,F),S=pt.get(w,x.length),S.init(O),S.state.textureUnits=nt.getTextureUnits(),x.push(S),qt.multiplyMatrices(O.projectionMatrix,O.matrixWorldInverse),Vt.setFromProjectionMatrix(qt,xn,O.reversedDepth),le=this.localClippingEnabled,Jt=It.init(this.clippingPlanes,le),v=_t.get(w,A.length),v.init(),A.push(v),At.enabled===!0&&At.isPresenting===!0){let wt=R.xr.getDepthSensingMesh();wt!==null&&xl(wt,O,-1/0,R.sortObjects)}xl(w,O,0,R.sortObjects),v.finish(),N!==null&&N.updateLights(S.state.lightsArray),R.sortObjects===!0&&v.sort(ut,Lt),Me=At.enabled===!1||At.isPresenting===!1||At.hasDepthSensing()===!1,Me&&zt.addToRenderList(v,w),this.info.render.frame++,this.info.autoReset===!0&&this.info.reset(),Jt===!0&&It.beginShadows();let $=S.state.shadowsArray;if(Nt.render($,w,O),Jt===!0&&It.endShadows(),(Y&&T.hasRenderPass())===!1){let wt=v.opaque,vt=v.transmissive;if(S.setupLights(),O.isArrayCamera){let Et=O.cameras;if(vt.length>0)for(let Rt=0,Gt=Et.length;Rt0&&Fh(wt,vt,w,O),Me&&zt.render(w),Uh(v,w,O)}F!==null&&W===0&&(nt.updateMultisampleRenderTarget(F),nt.updateRenderTargetMipmap(F)),Y&&T.end(R),w.isScene===!0&&w.onAfterRender(R,w,O),bt.resetDefaultState(),D=-1,X=null,x.pop(),x.length>0?(S=x[x.length-1],nt.setTextureUnits(S.state.textureUnits),Jt===!0&&It.setGlobalState(R.clippingPlanes,S.state.camera)):S=null,A.pop(),A.length>0?v=A[A.length-1]:v=null,N!==null&&N.renderEnd()};function xl(w,O,K,Y){if(w.visible===!1)return;if(w.layers.test(O.layers)){if(w.isGroup)K=w.renderOrder;else if(w.isLOD)w.autoUpdate===!0&&w.update(O);else if(w.isLightProbeGrid)S.pushLightProbeGrid(w);else if(w.isLight)S.pushLight(w),w.castShadow&&S.pushShadow(w);else if(w.isSprite){if(!w.frustumCulled||w.intersectsFrustum(Vt)){Y&&De.setFromMatrixPosition(w.matrixWorld).applyMatrix4(qt);let wt=ot.update(w),vt=w.material;vt.visible&&v.push(w,wt,vt,K,De.z,null,O)}}else if((w.isMesh||w.isLine||w.isPoints)&&(!w.frustumCulled||w.intersectsFrustum(Vt))){let wt=ot.update(w),vt=w.material;if(Y&&(w.boundingSphere!==void 0?(w.boundingSphere===null&&w.computeBoundingSphere(),De.copy(w.boundingSphere.center)):(wt.boundingSphere===null&&wt.computeBoundingSphere(),De.copy(wt.boundingSphere.center)),De.applyMatrix4(w.matrixWorld).applyMatrix4(qt)),Array.isArray(vt)){let Et=wt.groups;for(let Rt=0,Gt=Et.length;Rt0&&Br($,O,K),yt.length>0&&Br(yt,O,K),wt.length>0&&Br(wt,O,K),y.buffers.depth.setTest(!0),y.buffers.depth.setMask(!0),y.buffers.color.setMask(!0),y.setPolygonOffset(!1)}function Fh(w,O,K,Y){if((K.isScene===!0?K.overrideMaterial:null)!==null)return;if(S.state.transmissionRenderTarget[Y.id]===void 0){let Tt=ee.has("EXT_color_buffer_half_float")||ee.has("EXT_color_buffer_float");S.state.transmissionRenderTarget[Y.id]=new Fe(1,1,{generateMipmaps:!0,type:Tt?Sn:nn,minFilter:mi,samples:Math.max(4,P.samples),stencilBuffer:r,resolveDepthBuffer:!1,resolveStencilBuffer:!1,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1,colorSpace:Yt.workingColorSpace})}let yt=S.state.transmissionRenderTarget[Y.id],wt=Y.viewport||Z;yt.setSize(wt.z*R.transmissionResolutionScale,wt.w*R.transmissionResolutionScale);let vt=R.getRenderTarget(),Et=R.getActiveCubeFace(),Rt=R.getActiveMipmapLevel();R.setRenderTarget(yt),R.getClearColor(lt),ct=R.getClearAlpha(),ct<1&&R.setClearColor(16777215,.5),R.clear(),Me&&zt.render(K);let Gt=R.toneMapping;R.toneMapping=Mn;let Xt=Y.viewport;if(Y.viewport!==void 0&&(Y.viewport=void 0),S.setupLightsView(Y),Jt===!0&&It.setGlobalState(R.clippingPlanes,Y),Br(w,K,Y),nt.updateMultisampleRenderTarget(yt),nt.updateRenderTargetMipmap(yt),ee.has("WEBGL_multisampled_render_to_texture")===!1){let Tt=!1;for(let Qt=0,Ee=O.length;Qt0,Y.currentProgram=Xt,Y.uniformsList=null,Xt}function Oh(w){if(w.uniformsList===null){let O=w.currentProgram.getUniforms();w.uniformsList=Ts.seqWithValue(O.seq,w.uniforms)}return w.uniformsList}function zh(w,O){let K=J.get(w);K.outputColorSpace=O.outputColorSpace,K.batching=O.batching,K.batchingColor=O.batchingColor,K.instancing=O.instancing,K.instancingColor=O.instancingColor,K.instancingMorph=O.instancingMorph,K.skinning=O.skinning,K.morphTargets=O.morphTargets,K.morphNormals=O.morphNormals,K.morphColors=O.morphColors,K.morphTargetsCount=O.morphTargetsCount,K.numClippingPlanes=O.numClippingPlanes,K.numIntersection=O.numClipIntersection,K.vertexAlphas=O.vertexAlphas,K.vertexTangents=O.vertexTangents,K.toneMapping=O.toneMapping}function xp(w,O){if(w.length===0)return null;if(w.length===1)return w[0].texture!==null?w[0]:null;M.setFromMatrixPosition(O.matrixWorld);for(let K=0,Y=w.length;K0),Tt=!!K.morphAttributes.position,Qt=!!K.morphAttributes.normal,Ee=!!K.morphAttributes.color,pe=Mn;Y.toneMapped&&(F===null||F.isXRRenderTarget===!0)&&(pe=R.toneMapping);let re=K.morphAttributes.position||K.morphAttributes.normal||K.morphAttributes.color,Xe=re!==void 0?re.length:0,St=J.get(Y),je=S.state.lights;if(Jt===!0&&(le===!0||w!==X)){let he=w===X&&Y.id===D;It.setState(Y,w,he)}let Kt=!1;Y.version===St.__version?(St.needsLights&&St.lightsStateVersion!==je.state.version||St.outputColorSpace!==vt||$.isBatchedMesh&&St.batching===!1||!$.isBatchedMesh&&St.batching===!0||$.isBatchedMesh&&St.batchingColor===!0&&$._colorsTexture===null||$.isBatchedMesh&&St.batchingColor===!1&&$._colorsTexture!==null||$.isInstancedMesh&&St.instancing===!1||!$.isInstancedMesh&&St.instancing===!0||$.isSkinnedMesh&&St.skinning===!1||!$.isSkinnedMesh&&St.skinning===!0||$.isInstancedMesh&&St.instancingColor===!0&&$.instanceColor===null||$.isInstancedMesh&&St.instancingColor===!1&&$.instanceColor!==null||$.isInstancedMesh&&St.instancingMorph===!0&&$.morphTexture===null||$.isInstancedMesh&&St.instancingMorph===!1&&$.morphTexture!==null||St.envMap!==Rt||Y.fog===!0&&St.fog!==yt||St.numClippingPlanes!==void 0&&(St.numClippingPlanes!==It.numPlanes||St.numIntersection!==It.numIntersection)||St.vertexAlphas!==Gt||St.vertexTangents!==Xt||St.morphTargets!==Tt||St.morphNormals!==Qt||St.morphColors!==Ee||St.toneMapping!==pe||St.morphTargetsCount!==Xe||!!St.lightProbeGrid!=S.state.lightProbeGridArray.length>0)&&(Kt=!0):(Kt=!0,St.__version=Y.version);let hn=St.currentProgram;Kt===!0&&(hn=Or(Y,O,$),N&&Y.isNodeMaterial&&N.onUpdateProgram(Y,hn,St));let Rn=!1,ti=!1,Hi=!1,se=hn.getUniforms(),be=St.uniforms;if(y.useProgram(hn.program)&&(Rn=!0,ti=!0,Hi=!0),Y.id!==D&&(D=Y.id,ti=!0),St.needsLights){let he=xp(S.state.lightProbeGridArray,$);St.lightProbeGrid!==he&&(St.lightProbeGrid=he,ti=!0)}if(Rn||X!==w){y.buffers.depth.getReversed()&&w.reversedDepth!==!0&&(w._reversedDepth=!0,w.updateProjectionMatrix()),se.setValue(H,"projectionMatrix",w.projectionMatrix),se.setValue(H,"viewMatrix",w.matrixWorldInverse);let ni=se.map.cameraPosition;ni!==void 0&&ni.setValue(H,ve.setFromMatrixPosition(w.matrixWorld)),P.logarithmicDepthBuffer&&se.setValue(H,"logDepthBufFC",2/(Math.log(w.far+1)/Math.LN2)),(Y.isMeshPhongMaterial||Y.isMeshToonMaterial||Y.isMeshLambertMaterial||Y.isMeshBasicMaterial||Y.isMeshStandardMaterial||Y.isShaderMaterial)&&se.setValue(H,"isOrthographic",w.isOrthographicCamera===!0),X!==w&&(X=w,ti=!0,Hi=!0)}if(St.needsLights&&(je.state.sunShadowMap.length>0&&se.setValue(H,"sunShadowMap",je.state.sunShadowMap,nt),je.state.directionalShadowMap.length>0&&se.setValue(H,"directionalShadowMap",je.state.directionalShadowMap,nt),je.state.spotShadowMap.length>0&&se.setValue(H,"spotShadowMap",je.state.spotShadowMap,nt),je.state.pointShadowMap.length>0&&se.setValue(H,"pointShadowMap",je.state.pointShadowMap,nt)),$.isSkinnedMesh){se.setOptional(H,$,"bindMatrix"),se.setOptional(H,$,"bindMatrixInverse");let he=$.skeleton;he&&(he.boneTexture===null&&he.computeBoneTexture(),se.setValue(H,"boneTexture",he.boneTexture,nt))}$.isBatchedMesh&&(se.setOptional(H,$,"batchingTexture"),se.setValue(H,"batchingTexture",$._matricesTexture,nt),se.setOptional(H,$,"batchingIdTexture"),se.setValue(H,"batchingIdTexture",$._indirectTexture,nt),se.setOptional(H,$,"batchingColorTexture"),$._colorsTexture!==null&&se.setValue(H,"batchingColorTexture",$._colorsTexture,nt));let ei=K.morphAttributes;if((ei.position!==void 0||ei.normal!==void 0||ei.color!==void 0)&&k.update($,K,hn),(ti||St.receiveShadow!==$.receiveShadow)&&(St.receiveShadow=$.receiveShadow,se.setValue(H,"receiveShadow",$.receiveShadow)),(Y.isMeshStandardMaterial||Y.isMeshLambertMaterial||Y.isMeshPhongMaterial)&&Y.envMap===null&&O.environment!==null&&(be.envMapIntensity.value=O.environmentIntensity),be.dfgLUT!==void 0&&(be.dfgLUT.value=lv()),ti){if(se.setValue(H,"toneMappingExposure",R.toneMappingExposure),St.needsLights&&yp(be,Hi),yt&&Y.fog===!0&&Ct.refreshFogUniforms(be,yt),Ct.refreshMaterialUniforms(be,Y,j,V,S.state.transmissionRenderTarget[w.id]),St.needsLights&&St.lightProbeGrid){let he=St.lightProbeGrid;be.probesSH.value=he.texture,be.probesMin.value.copy(he.boundingBox.min),be.probesMax.value.copy(he.boundingBox.max),be.probesResolution.value.copy(he.resolution)}Ts.upload(H,Oh(St),be,nt)}if(Y.isShaderMaterial&&Y.uniformsNeedUpdate===!0&&(Ts.upload(H,Oh(St),be,nt),Y.uniformsNeedUpdate=!1),Y.isSpriteMaterial&&se.setValue(H,"center",$.center),se.setValue(H,"modelViewMatrix",$.modelViewMatrix),se.setValue(H,"normalMatrix",$.normalMatrix),se.setValue(H,"modelMatrix",$.matrixWorld),Y.uniformsGroups!==void 0){let he=Y.uniformsGroups;for(let ni=0,Vi=he.length;ni0&&nt.useMultisampledRTT(w)===!1?Y=J.get(w).__webglMultisampledFramebuffer:Array.isArray(Rt)?Y=Rt[K]:Y=Rt,Z.copy(w.viewport),G.copy(w.scissor),Q=w.scissorTest}else Z.copy(Mt).multiplyScalar(j).floor(),G.copy(Bt).multiplyScalar(j).floor(),Q=xe;if(K!==0&&(Y=U),y.bindFramebuffer(H.FRAMEBUFFER,Y)&&y.drawBuffers(w,Y),y.viewport(Z),y.scissor(G),y.setScissorTest(Q),$){let vt=J.get(w.texture);H.framebufferTexture2D(H.FRAMEBUFFER,H.COLOR_ATTACHMENT0,H.TEXTURE_CUBE_MAP_POSITIVE_X+O,vt.__webglTexture,K)}else if(yt){let vt=O;for(let Et=0;Et1&&H.readBuffer(H.COLOR_ATTACHMENT0+vt);let Tt=kh(Rt);if(Tt.__formatReadable===!1){Ut("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(Tt.__typeReadable===!1){Ut("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}O>=0&&O<=w.width-Y&&K>=0&&K<=w.height-$&&H.readPixels(O,K,Y,$,gt.convert(Gt),gt.convert(Xt),yt)}finally{let Rt=F!==null?J.get(F).__webglFramebuffer:null;y.bindFramebuffer(H.FRAMEBUFFER,Rt)}}},this.readRenderTargetPixelsAsync=async function(w,O,K,Y,$,yt,wt,vt=0){if(!(w&&w.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let Et=J.get(w).__webglFramebuffer;if(w.isWebGLCubeRenderTarget&&wt!==void 0&&(Et=Et[wt]),Et)if(O>=0&&O<=w.width-Y&&K>=0&&K<=w.height-$){y.bindFramebuffer(H.FRAMEBUFFER,Et);let Rt=w.textures[vt],Gt=Rt.format,Xt=Rt.type;w.textures.length>1&&H.readBuffer(H.COLOR_ATTACHMENT0+vt);let Tt=kh(Rt);if(Tt.__formatReadable===!1)throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(Tt.__typeReadable===!1)throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");let Qt=H.createBuffer();H.bindBuffer(H.PIXEL_PACK_BUFFER,Qt),H.bufferData(H.PIXEL_PACK_BUFFER,yt.byteLength,H.STREAM_READ),H.readPixels(O,K,Y,$,gt.convert(Gt),gt.convert(Xt),0),H.bindBuffer(H.PIXEL_PACK_BUFFER,null);let Ee=F!==null?J.get(F).__webglFramebuffer:null;y.bindFramebuffer(H.FRAMEBUFFER,Ee);let pe=H.fenceSync(H.SYNC_GPU_COMMANDS_COMPLETE,0);return H.flush(),await id(H,pe,4),H.bindBuffer(H.PIXEL_PACK_BUFFER,Qt),H.getBufferSubData(H.PIXEL_PACK_BUFFER,0,yt),H.bindBuffer(H.PIXEL_PACK_BUFFER,null),H.deleteBuffer(Qt),H.deleteSync(pe),yt}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(w,O=null,K=0){let Y=Math.pow(2,-K),$=Math.floor(w.image.width*Y),yt=Math.floor(w.image.height*Y),wt=O!==null?O.x:0,vt=O!==null?O.y:0;nt.setTexture2D(w,0),H.copyTexSubImage2D(H.TEXTURE_2D,K,0,0,wt,vt,$,yt),y.unbindTexture()},this.copyTextureToTexture=function(w,O,K=null,Y=null,$=0,yt=0){let wt,vt,Et,Rt,Gt,Xt,Tt,Qt,Ee,pe=w.isCompressedTexture?w.mipmaps[yt]:w.image;if(K!==null)wt=K.max.x-K.min.x,vt=K.max.y-K.min.y,Et=K.isBox3?K.max.z-K.min.z:1,Rt=K.min.x,Gt=K.min.y,Xt=K.isBox3?K.min.z:0;else{let be=Math.pow(2,-$);wt=Math.floor(pe.width*be),vt=Math.floor(pe.height*be),w.isDataArrayTexture?Et=pe.depth:w.isData3DTexture?Et=Math.floor(pe.depth*be):Et=1,Rt=0,Gt=0,Xt=0}Y!==null?(Tt=Y.x,Qt=Y.y,Ee=Y.z):(Tt=0,Qt=0,Ee=0);let re=gt.convert(O.format),Xe=gt.convert(O.type),St;O.isData3DTexture?(nt.setTexture3D(O,0),St=H.TEXTURE_3D):O.isDataArrayTexture||O.isCompressedArrayTexture?(nt.setTexture2DArray(O,0),St=H.TEXTURE_2D_ARRAY):(nt.setTexture2D(O,0),St=H.TEXTURE_2D),y.activeTexture(H.TEXTURE0),y.pixelStorei(H.UNPACK_FLIP_Y_WEBGL,O.flipY),y.pixelStorei(H.UNPACK_PREMULTIPLY_ALPHA_WEBGL,O.premultiplyAlpha),y.pixelStorei(H.UNPACK_ALIGNMENT,O.unpackAlignment);let je=y.getParameter(H.UNPACK_ROW_LENGTH),Kt=y.getParameter(H.UNPACK_IMAGE_HEIGHT),hn=y.getParameter(H.UNPACK_SKIP_PIXELS),Rn=y.getParameter(H.UNPACK_SKIP_ROWS),ti=y.getParameter(H.UNPACK_SKIP_IMAGES);y.pixelStorei(H.UNPACK_ROW_LENGTH,pe.width),y.pixelStorei(H.UNPACK_IMAGE_HEIGHT,pe.height),y.pixelStorei(H.UNPACK_SKIP_PIXELS,Rt),y.pixelStorei(H.UNPACK_SKIP_ROWS,Gt),y.pixelStorei(H.UNPACK_SKIP_IMAGES,Xt);let Hi=w.isDataArrayTexture||w.isData3DTexture,se=O.isDataArrayTexture||O.isData3DTexture;if(w.isDepthTexture){let be=J.get(w),ei=J.get(O),he=J.get(be.__renderTarget),ni=J.get(ei.__renderTarget);y.bindFramebuffer(H.READ_FRAMEBUFFER,he.__webglFramebuffer),y.bindFramebuffer(H.DRAW_FRAMEBUFFER,ni.__webglFramebuffer);for(let Vi=0;Vi=c.length){s-=c.length;continue}let h=Math.min(o,c.length-s);if(a.push(c.substringData(s,h)),o-=h,s=0,!o)break}let l=new Uint8Array(Math.ceil((r+e)/3)*3);if(Jc(l,0,a.join(""))i!==null&&typeof i=="object"&&!Array.isArray(i),Oi=i=>Array.isArray(i)&&i.every(yr),Qn=i=>Array.isArray(i)&&i.length===3&&i.every(t=>typeof t=="number"),Hd=i=>yr(i)&&Qn(i.min)&&Qn(i.max),zd=i=>i==null||yr(i)&&Oi(i.planes)&&i.planes.every(t=>Qn(t.normal)&&t.normal.every(Number.isFinite)&&t.normal.some(e=>e!==0)&&Number.isFinite(t.offset))&&(i.box==null||Hd(i.box)&&i.box.max.every(Number.isFinite)&&i.box.min.every((t,e)=>Number.isFinite(t)&&t<=i.box.max[e]));function uv(i){if(!yr(i)||!Oi(i.elements)||!Oi(i.geometries)||!Oi(i.materials)||!yr(i.instances))throw new ye("META must describe elements, geometries, materials and instances.");if(i.title!=null&&typeof i.title!="string")throw new ye("Invalid META title.");let{instances:t}=i;if(!Number.isSafeInteger(t.count)||t.count<0)throw new ye("Invalid META instance count.");for(let[l,c,h]of[["geometry","u32",t.count],["material","u32",t.count],["element","i32",t.count],["matrix","f32",t.count*12]])if(t[l]?.t!==c||t[l].n!==h)throw new ye(`Invalid META instance ${l} view.`);for(let l of i.geometries){let c=l.q;if(!Hd(l.bbox)||!["u16","u32"].includes(l.indices?.t)||l.positions?.t!==(c?"u16":"f32")||c&&(!Qn(c.o)||typeof c.s!="number")||l.normals!=null&&!["f32","i16"].includes(l.normals.t)||l.uvs!=null&&l.uvs.t!=="f32")throw new ye("Invalid META geometry.")}for(let l of["textures","grids","viewpoints","bcfTopics","clashTests","linkedFiles","models"])if(i[l]!=null&&!Oi(i[l]))throw new ye(`Invalid META ${l} list.`);if(i.models?.some(({id:l,name:c})=>!Number.isSafeInteger(l)||typeof c!="string")||i.elements.some(({modelId:l,levelId:c})=>l!=null&&!Number.isSafeInteger(l)||c!=null&&!Number.isSafeInteger(c)))throw new ye("Invalid META model or level identity.");for(let l of i.materials){let c=l.texture;if(!Qn(l.color)||typeof l.opacity!="number"||c!=null&&(!Number.isInteger(c)||c<0||c>=(i.textures?.length??0)))throw new ye("Invalid META material.")}let e=l=>l==null||Array.isArray(l)&&l.every(c=>Number.isInteger(c)&&c>=0&&cQn(l)&&l.every(Number.isFinite),s=l=>l==null||typeof l=="string",r=l=>n(l.camera?.position)&&n(l.camera?.target)&&zd(l.sections)&&e(l.hiddenElements)&&e(l.visibleElements)&&e(l.selectedElements)&&(l.hiddenElements==null||l.visibleElements==null)&&(l.hiddenModelKeys==null||Array.isArray(l.hiddenModelKeys)&&l.hiddenModelKeys.every(c=>typeof c=="string")),o=l=>Number.isSafeInteger(l)&&l>=0,a=l=>r(l)&&n(l.camera.up)&&l.camera.up.some(c=>c!==0)&&(l.camera.projection==="orthographic"?Number.isFinite(l.camera.orthographicHeight)&&l.camera.orthographicHeight>0:l.camera.projection==="perspective"&&Number.isFinite(l.camera.fov)&&l.camera.fov>0&&l.camera.fov<180)&&o(l.missingComponents)&&o(l.ambiguousComponents);if(i.grids?.some(l=>!Qn(l.start)||!Qn(l.end))||i.viewpoints?.some(l=>!r(l))||i.clashTests?.some(l=>!Oi(l.clashes)||l.clashes.some(c=>!Qn(c.point))))throw new ye("Invalid META grids, viewpoints or clashes.");if(i.bcfTopics?.some(l=>typeof l.title!="string"||!s(l.description)||!s(l.status)||!Oi(l.viewpoints)||l.viewpoints.some(c=>!a(c))))throw new ye("Invalid META BCF topics.");if(i.linkedFiles?.some(l=>!e(l.members)))throw new ye("Invalid META linked file members.");if(!zd(i.sections))throw new ye("Invalid META sections.")}function Kc(i=document,t){let e;t?.("metadataStart");try{e=JSON.parse(kd(i,"ioviewer-meta"))}catch(n){throw new ye(n.message,{cause:n})}return uv(e),t?.("metadataEnd"),e}function Vd(i=document,t,e=Kc(i,t)){let n,s,r,o;try{if(t?.("binaryStart"),s=i.getElementById("ioviewer-bin"),!s)throw new Error("Data block 'ioviewer-bin' is missing.");({bytes:n,canonical:r}=Od(s)),t?.("binaryEnd")}catch(h){throw new ye(h.message,{cause:h})}let a=n.length;function l(h){let d=cv[h?.t];if(!d)throw new ye(`Unknown view type '${h?.t}'.`);let u=d.BYTES_PER_ELEMENT;if(!(Number.isInteger(h.o)&&Number.isInteger(h.n)&&h.o>=0&&h.n>=0&&h.o%u===0&&h.o+h.n*u<=a))throw new ye(`View ${JSON.stringify(h)} is outside the ${a} bytes of binary data.`);return d}let c=null;return{meta:e,view(h){if(!n)throw new Error("The binary data has been released.");let d=l(h);return new d(n.buffer,h.o,h.n)},readView(h){let d=l(h);if(!h.n)return new d(0);!n&&!r&&(o??(o=Od(s).bytes));let u=n??o;return u?new d(u.buffer,h.o,h.n):new d(hv(s,h.o,h.n*d.BYTES_PER_ELEMENT))},releaseBinary(){n=null,o=null},props(h){return c??(c=JSON.parse(kd(i,"ioviewer-props"))),c[h]??null}}}var Gd=new kt,Wd=new Un,jc=32;function Qc(i,t=new Float64Array(24)){return Gd.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),Wd.setFromProjectionMatrix(Gd,i.coordinateSystem,i.reversedDepth),Wd.planes.forEach(({normal:e,constant:n},s)=>t.set([e.x,e.y,e.z,n],s*4)),t}function th(i,t,e,n,s){for(let r=0;r<24;r+=4)if(i[r]*t+i[r+1]*e+i[r+2]*n+i[r+3]<-s)return!0;return!1}function Xd(i,t,e,n,s){for(let r=0;r<24;r+=4)if(i[r]*t+i[r+1]*e+i[r+2]*n+i[r+3]=0;r--)if(i[r]!==0){if(n+=i[r],n>e)return s?r===0?0:2**(r/2-4):2**((r+1)/2-4);s=!1}return 0}var wn=.0009765625,nh=32767,Mr=i=>i<0?-1:1;function Yd(i){let t=Math.min(Math.max(i,-1),1)*nh;return Mr(t)*Math.round(Math.abs(t))}function br(i,t,e,n,s){let r=Math.abs(e)+Math.abs(n)+Math.abs(s);if(!(r>0)){i[t]=i[t+1]=0;return}let o=e/r,a=n/r;s<0&&([o,a]=[(1-Math.abs(a))*Mr(o),(1-Math.abs(o))*Mr(a)]),i[t]=Yd(o),i[t+1]=Yd(a)}function $d(i,t,e,n){let s=Math.max(e/nh,-1),r=Math.max(n/nh,-1),o=1-Math.abs(s)-Math.abs(r);o<0&&([s,r]=[(1-Math.abs(r))*Mr(s),(1-Math.abs(s))*Mr(r)]);let a=Math.sqrt(s*s+r*r+o*o);i[t]=s/a,i[t+1]=r/a,i[t+2]=o/a}function Sr(i,t){let e=i.view(t.positions);if(!t.q){if(!(e instanceof Float32Array))throw new Error(`Geometry positions of type '${t.positions.t}' need a "q" origin and step.`);return e}if(!(e instanceof Uint16Array))throw new Error(`Quantized geometry positions must be u16, got '${t.positions.t}'.`);return e}function Zd(i,t){let e=Sr(i,t);if(!t.q)return e;let[n,s,r]=t.q.o,o=t.q.s,a=new Float32Array(e.length);for(let l=0;ls[d]&&(s[d]=u))}let r=0;for(let h=1;h<3;h++)s[h]-n[h]>s[r]-n[r]&&(r=h);let o=s[r]-n[r],a=2**20-1,l=new Float64Array(i.length);for(let h=0;h0&&Number.isFinite(u)?Math.round((u-n[r])/o*a):0;l[h]=p*2**32+d}let c=0;e<0?l.sort():c=fv(l,e);for(let h=0;hr)return i.subarray(e,n+1).sort(),a+l*Math.ceil(Math.log2(l));a+=l,s=Math.imul(s,1664525)+1013904223>>>0;let c=i[e+s%(n-e+1)],h=e,d=n;for(;h<=d;){for(;i[h]c;)d--;if(h<=d){let u=i[h];i[h++]=i[d],i[d--]=u}}if(t<=d)n=d;else if(t>=h)e=h;else return a}return a}function nf(i,t,e,n=1/0){let s=[];s.scanned=0;let r=[Uint32Array.from(t)];for(;r.length;){let o=r.pop(),a=Math.ceil(o.length/e);if(o.length<=1||a<=1&&pv(o,i)<=n){o.length&&s.push(o);continue}let l=a>1?Math.ceil(o.length*Math.floor(a/2)/a):Math.ceil(o.length/2);s.scanned+=ef(o,i,l),r.push(o.subarray(l),o.subarray(0,l))}return s}function pv(i,t){let e=1/0,n=1/0,s=1/0,r=-1/0,o=-1/0,a=-1/0;for(let l of i){let c=t[l*3],h=t[l*3+1],d=t[l*3+2];cr&&(r=c),ho&&(o=h),da&&(a=d)}return Math.hypot(r-e,o-n,a-s)/2}function sf(i,t){let e=new Float64Array(6).fill(-1/0),n=new Float64Array(6).fill(-1/0),s=new Int32Array(6);for(let o=0;oe[a]?(n[a]=e[a],e[a]=c,s[a]=o):c>n[a]&&(n[a]=c)}if(e[0]===-1/0)return 0;let r=Math.hypot(e[0]+e[3],e[1]+e[4],e[2]+e[5]);if(n[0]===-1/0)return r;for(let o of s){let a=c=>s[c]===o?n[c]:e[c],l=Math.hypot(a(0)+a(3),a(1)+a(4),a(2)+a(5));r=Math.min(r,2*l)}return r}var sh=384*2**20;function rf(i,{cap:t=sh,minRepeats:e=16,perCell:n=1024,maxDraws:s=1024}={}){let r=new Uint8Array(i.length),o=0;for(let h of i)o+=h.k*h.bytes;if(o<=t)return r;let a=h=>(i[h].k-1)*i[h].bytes,l=[...i.keys()].filter(h=>i[h].k>=e);l.sort((h,d)=>a(d)-a(h)||i[d].k-i[h].k||h-d);let c=0;for(let h of l){let d=i[h].cells??Math.ceil(i[h].k/n);c+d>s||(r[h]=1,c+=d)}return r}function Wa(i,t){return i>65535?new Uint32Array(t):new Uint16Array(t)}function rh(i,t){return i.sort((e,n)=>t[n]-t[e]||e-n)}function of(i,t,e,n){for(;t>>1;i[s]>=n?t=s+1:e=s}return t}function af(i,t,e){let n=i[t];return[n,e>t?i[e]-n:0]}function lf(i,t,e,n){let s=i.subarray(t*12,t*12+12);if(s[0]===1&&s[1]===0&&s[2]===0&&s[3]===0&&s[4]===1&&s[5]===0&&s[6]===0&&s[7]===0&&s[8]===1&&e.q&&e.q.s===wn){for(let a=0;a<3;a++)n[a]=s[9+a]+e.q.o[a];return jd}let o=!0;for(let a=0;a<3;a++){let l=s[9+a],c=s[9+a];for(let h=0;h<3;h++){let d=s[h*3+a]*e.min[h],u=s[h*3+a]*e.max[h];l+=Math.min(d,u),c+=Math.max(d,u)}n[a]=Math.floor(l/wn)*wn,Math.ceil((c-n[a])/wn)<=Qd||(o=!1)}return o||n.fill(0),o?dv:Is}function cf(i,t){let e=i.length,n=0,s=0;for(let m of i){let f=t.source(t.geometryOf[m]);n+=f.vertices,s+=f.indices.length}let r=t.kind[i[0]]===Is,o=r?new Float32Array(n*4):new Uint16Array(n*4),a=new Int16Array(n*2),l=t.textured?new Float32Array(n*2):null,c=Wa(n,s),h=new Uint32Array(e+1),d=new Float32Array(e*3),u=new Float32Array(e),p=new Float64Array(3),g=0,_=0;for(let m=0;mMath.min(Math.max(Math.round(i/wn),0),Qd);function hf(i,t,e,n,s){let r=i.length/3,o=[1/0,1/0,1/0],a=[-1/0,-1/0,-1/0];for(let c=0;ca[h]&&(a[h]=d)}let l=e instanceof Int16Array?e:null;return{positions:i,q:t,oct:l,normals:l?null:e,indices:n,uvs:s,vertices:r,min:o,max:a}}function Xa(i){if(!i.normals&&i.oct){i.normals=new Float32Array(i.vertices*3);for(let t=0;tt?t.o[o]+i[r*3+o]*t.s:i[r*3+o],s=new Float32Array(i.length);for(let r=0;rn(a,u)-n(o,u)),h=[0,1,2].map(u=>n(l,u)-n(o,u)),d=[c[1]*h[2]-c[2]*h[1],c[2]*h[0]-c[0]*h[2],c[0]*h[1]-c[1]*h[0]];for(let u of[o,a,l])for(let p=0;p<3;p++)s[u*3+p]+=d[p]}for(let r=0;r=0&&(S[Lt]=null,v[Lt].disconnect(ut))}for(let j=0;j=S.length){S.push(ut),Lt=Bt;break}else if(S[Bt]===null){S[Bt]=ut,Lt=Bt;break}if(Lt===-1)break}let Mt=v[Lt];Mt&&Mt.connect(ut)}}let D=new I,X=new I;function Z(V,j,ut){D.setFromMatrixPosition(j.matrixWorld),X.setFromMatrixPosition(ut.matrixWorld);let Lt=D.distanceTo(X),Mt=j.projectionMatrix.elements,Bt=ut.projectionMatrix.elements,ve=Mt[14]/(Mt[10]-1),Vt=Mt[14]/(Mt[10]+1),Jt=(Mt[9]+1)/Mt[5],he=(Mt[9]-1)/Mt[5],qt=(Mt[8]-1)/Mt[0],ye=(Bt[8]+1)/Bt[0],De=ve*qt,tn=ve*ye,Me=Lt/(-qt+ye),we=Me*-qt;if(j.matrixWorld.decompose(V.position,V.quaternion,V.scale),V.translateX(we),V.translateZ(Me),V.matrixWorld.compose(V.position,V.quaternion,V.scale),V.matrixWorldInverse.copy(V.matrixWorld).invert(),Mt[10]===-1)V.projectionMatrix.copy(j.projectionMatrix),V.projectionMatrixInverse.copy(j.projectionMatrixInverse);else{let H=ve+Me,We=Vt+Me,ee=De-we,P=tn+(Lt-we),y=Jt*Vt/We*H,q=he*Vt/We*H;V.projectionMatrix.makePerspective(ee,P,y,q,H,We),V.projectionMatrixInverse.copy(V.projectionMatrix).invert()}}function G(V,j){j===null?V.matrixWorld.copy(V.matrix):V.matrixWorld.multiplyMatrices(j.matrixWorld,V.matrix),V.matrixWorldInverse.copy(V.matrixWorld).invert()}this.updateCamera=function(V){if(s===null)return;let j=V.near,ut=V.far;m.texture!==null&&(m.depthNear>0&&(j=m.depthNear),m.depthFar>0&&(ut=m.depthFar)),U.near=L.near=R.near=j,U.far=L.far=R.far=ut,(C!==U.near||B!==U.far)&&(s.updateRenderState({depthNear:U.near,depthFar:U.far}),C=U.near,B=U.far),U.layers.mask=V.layers.mask|6,R.layers.mask=U.layers.mask&-5,L.layers.mask=U.layers.mask&-3;let Lt=V.parent,Mt=U.cameras;G(U,Lt);for(let Bt=0;Bt0&&(m.alphaTest.value=f.alphaTest);let b=t.get(f),E=b.envMap,M=b.envMapRotation;E&&(m.envMap.value=E,m.envMapRotation.value.setFromMatrix4(ov.makeRotationFromEuler(M)).transpose(),E.isCubeTexture&&E.isRenderTargetTexture===!1&&m.envMapRotation.value.premultiply(Bd),m.reflectivity.value=f.reflectivity,m.ior.value=f.ior,m.refractionRatio.value=f.refractionRatio),f.lightMap&&(m.lightMap.value=f.lightMap,m.lightMapIntensity.value=f.lightMapIntensity,e(f.lightMap,m.lightMapTransform)),f.aoMap&&(m.aoMap.value=f.aoMap,m.aoMapIntensity.value=f.aoMapIntensity,e(f.aoMap,m.aoMapTransform))}function o(m,f){m.diffuse.value.copy(f.color),m.opacity.value=f.opacity,f.map&&(m.map.value=f.map,e(f.map,m.mapTransform))}function a(m,f){m.dashSize.value=f.dashSize,m.totalSize.value=f.dashSize+f.gapSize,m.scale.value=f.scale}function l(m,f,b,E){m.diffuse.value.copy(f.color),m.opacity.value=f.opacity,m.size.value=f.size*b,m.scale.value=E*.5,f.map&&(m.map.value=f.map,e(f.map,m.uvTransform)),f.alphaMap&&(m.alphaMap.value=f.alphaMap,e(f.alphaMap,m.alphaMapTransform)),f.alphaTest>0&&(m.alphaTest.value=f.alphaTest)}function c(m,f){m.diffuse.value.copy(f.color),m.opacity.value=f.opacity,m.rotation.value=f.rotation,f.map&&(m.map.value=f.map,e(f.map,m.mapTransform)),f.alphaMap&&(m.alphaMap.value=f.alphaMap,e(f.alphaMap,m.alphaMapTransform)),f.alphaTest>0&&(m.alphaTest.value=f.alphaTest)}function h(m,f){m.specular.value.copy(f.specular),m.shininess.value=Math.max(f.shininess,1e-4)}function d(m,f){f.gradientMap&&(m.gradientMap.value=f.gradientMap)}function u(m,f){m.metalness.value=f.metalness,f.metalnessMap&&(m.metalnessMap.value=f.metalnessMap,e(f.metalnessMap,m.metalnessMapTransform)),m.roughness.value=f.roughness,f.roughnessMap&&(m.roughnessMap.value=f.roughnessMap,e(f.roughnessMap,m.roughnessMapTransform)),f.envMap&&(m.envMapIntensity.value=f.envMapIntensity)}function p(m,f,b){m.ior.value=f.ior,f.sheen>0&&(m.sheenColor.value.copy(f.sheenColor).multiplyScalar(f.sheen),m.sheenRoughness.value=f.sheenRoughness,f.sheenColorMap&&(m.sheenColorMap.value=f.sheenColorMap,e(f.sheenColorMap,m.sheenColorMapTransform)),f.sheenRoughnessMap&&(m.sheenRoughnessMap.value=f.sheenRoughnessMap,e(f.sheenRoughnessMap,m.sheenRoughnessMapTransform))),f.clearcoat>0&&(m.clearcoat.value=f.clearcoat,m.clearcoatRoughness.value=f.clearcoatRoughness,f.clearcoatMap&&(m.clearcoatMap.value=f.clearcoatMap,e(f.clearcoatMap,m.clearcoatMapTransform)),f.clearcoatRoughnessMap&&(m.clearcoatRoughnessMap.value=f.clearcoatRoughnessMap,e(f.clearcoatRoughnessMap,m.clearcoatRoughnessMapTransform)),f.clearcoatNormalMap&&(m.clearcoatNormalMap.value=f.clearcoatNormalMap,e(f.clearcoatNormalMap,m.clearcoatNormalMapTransform),m.clearcoatNormalScale.value.copy(f.clearcoatNormalScale),f.side===Ve&&m.clearcoatNormalScale.value.negate())),f.dispersion>0&&(m.dispersion.value=f.dispersion),f.retroreflectivity>0&&(m.retroreflectivity.value=f.retroreflectivity),f.iridescence>0&&(m.iridescence.value=f.iridescence,m.iridescenceIOR.value=f.iridescenceIOR,m.iridescenceThicknessMinimum.value=f.iridescenceThicknessRange[0],m.iridescenceThicknessMaximum.value=f.iridescenceThicknessRange[1],f.iridescenceMap&&(m.iridescenceMap.value=f.iridescenceMap,e(f.iridescenceMap,m.iridescenceMapTransform)),f.iridescenceThicknessMap&&(m.iridescenceThicknessMap.value=f.iridescenceThicknessMap,e(f.iridescenceThicknessMap,m.iridescenceThicknessMapTransform))),f.transmission>0&&(m.transmission.value=f.transmission,m.transmissionSamplerMap.value=b.texture,m.transmissionSamplerSize.value.set(b.width,b.height),f.transmissionMap&&(m.transmissionMap.value=f.transmissionMap,e(f.transmissionMap,m.transmissionMapTransform)),m.thickness.value=f.thickness,f.thicknessMap&&(m.thicknessMap.value=f.thicknessMap,e(f.thicknessMap,m.thicknessMapTransform)),m.attenuationDistance.value=f.attenuationDistance,m.attenuationColor.value.copy(f.attenuationColor)),f.anisotropy>0&&(m.anisotropyVector.value.set(f.anisotropy*Math.cos(f.anisotropyRotation),f.anisotropy*Math.sin(f.anisotropyRotation)),f.anisotropyMap&&(m.anisotropyMap.value=f.anisotropyMap,e(f.anisotropyMap,m.anisotropyMapTransform))),m.specularIntensity.value=f.specularIntensity,m.specularColor.value.copy(f.specularColor),f.specularColorMap&&(m.specularColorMap.value=f.specularColorMap,e(f.specularColorMap,m.specularColorMapTransform)),f.specularIntensityMap&&(m.specularIntensityMap.value=f.specularIntensityMap,e(f.specularIntensityMap,m.specularIntensityMapTransform))}function g(m,f){f.matcap&&(m.matcap.value=f.matcap)}function _(m,f){let b=t.get(f).light;m.referencePosition.value.setFromMatrixPosition(b.matrixWorld),m.nearDistance.value=b.shadow.camera.near,m.farDistance.value=b.shadow.camera.far}return{refreshFogUniforms:n,refreshMaterialUniforms:s}}function lv(i,t,e,n){let s={},r={},o=[],a=i.getParameter(i.MAX_UNIFORM_BUFFER_BINDINGS);function l(M,v){let S=v.program;n.uniformBlockBinding(M,S)}function c(M,v){let S=s[M.id];S===void 0&&(m(M),S=h(M),s[M.id]=S,M.addEventListener("dispose",b));let A=v.program;n.updateUBOMapping(M,A);let x=t.render.frame;r[M.id]!==x&&(u(M),r[M.id]=x)}function h(M){let v=d();M.__bindingPointIndex=v;let S=i.createBuffer(),A=M.__size,x=M.usage;return i.bindBuffer(i.UNIFORM_BUFFER,S),i.bufferData(i.UNIFORM_BUFFER,A,x),i.bindBuffer(i.UNIFORM_BUFFER,null),i.bindBufferBase(i.UNIFORM_BUFFER,v,S),S}function d(){for(let M=0;M0&&(S+=A-x),M.__size=S,M.__cache={},this}function f(M){let v={boundary:0,storage:0};return typeof M=="number"||typeof M=="boolean"?(v.boundary=4,v.storage=4):M.isVector2?(v.boundary=8,v.storage=8):M.isVector3||M.isColor?(v.boundary=16,v.storage=12):M.isVector4?(v.boundary=16,v.storage=16):M.isMatrix3?(v.boundary=48,v.storage=48):M.isMatrix4?(v.boundary=64,v.storage=64):M.isTexture?Dt("WebGLRenderer: Texture samplers can not be part of an uniforms group."):ArrayBuffer.isView(M)?(v.boundary=16,v.storage=M.byteLength):Dt("WebGLRenderer: Unsupported uniform value type.",M),v}function b(M){let v=M.target;v.removeEventListener("dispose",b);let S=o.indexOf(v.__bindingPointIndex);o.splice(S,1),i.deleteBuffer(s[v.id]),delete s[v.id],delete r[v.id]}function E(){for(let M in s)i.deleteBuffer(s[M]);o=[],s={},r={}}return{bind:l,update:c,dispose:E}}var cv=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]),zn=null;function hv(){return zn===null&&(zn=new Nn(cv,16,16,_i,Sn),zn.name="DFG_LUT",zn.minFilter=ze,zn.magFilter=ze,zn.wrapS=In,zn.wrapT=In,zn.generateMipmaps=!1,zn.needsUpdate=!0),zn}var As=class{constructor(t={}){let{canvas:e=nd(),context:n=null,depth:s=!0,stencil:r=!1,alpha:o=!1,antialias:a=!1,premultipliedAlpha:l=!0,preserveDrawingBuffer:c=!1,powerPreference:h="default",failIfMajorPerformanceCaveat:d=!1,reversedDepthBuffer:u=!1,outputBufferType:p=nn}=t;this.isWebGLRenderer=!0;let g;if(n!==null){if(typeof WebGLRenderingContext<"u"&&n instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");g=n.getContextAttributes().alpha}else g=o;let _=p,m=new Set([sa,ia,na]),f=new Set([nn,bn,Ms,bs,ta,ea]),b=new Uint32Array(4),E=new Int32Array(4),M=new I,v=null,S=null,A=[],x=[],T=null;this.domElement=e,this.debug={checkShaderErrors:!0,diagnostics:{keywords:!1},onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=Mn,this.toneMappingExposure=1,this.transmissionResolutionScale=1;let R=this,L=!1,N=null,U=null,C=null,B=null;this._outputColorSpace=Ae;let z=0,W=0,F=null,D=-1,X=null,Z=new ae,G=new ae,Q=null,lt=new Ft(0),ct=0,et=e.width,V=e.height,j=1,ut=null,Lt=null,Mt=new ae(0,0,et,V),Bt=new ae(0,0,et,V),ve=!1,Vt=new Un,Jt=!1,he=!1,qt=new kt,ye=new I,De=new ae,tn={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0},Me=!1;function we(){return F===null?j:1}let H=n;function We(w,O){return e.getContext(w,O)}let ee,P,y,q,J,nt,ht,dt,it,ot,ft,Ct,_t,pt,It,Nt,zt,k,mt,rt,gt,bt,at;try{let w={alpha:!0,depth:s,stencil:r,antialias:a,premultipliedAlpha:l,preserveDrawingBuffer:c,powerPreference:h,failIfMajorPerformanceCaveat:d};if("setAttribute"in e&&e.setAttribute("data-engine",`three.js r${"186"}`),e.addEventListener("webglcontextlost",ue,!1),e.addEventListener("webglcontextrestored",jt,!1),e.addEventListener("webglcontextcreationerror",fn,!1),H===null){let O="webgl2";if(H=We(O,w),H===null)throw We(O)?new Error("THREE.WebGLRenderer: Error creating WebGL context with your selected attributes."):new Error("THREE.WebGLRenderer: Error creating WebGL context.")}Pt()}catch(w){throw e.removeEventListener("webglcontextlost",ue,!1),e.removeEventListener("webglcontextrestored",jt,!1),e.removeEventListener("webglcontextcreationerror",fn,!1),Ut("WebGLRenderer: "+w.message),w}function Pt(){ee=new _0(H),ee.init(),gt=new iv(H,ee),P=new a0(H,ee,t,gt),y=new ev(H,ee),P.reversedDepthBuffer&&u&&y.buffers.depth.setReversed(!0),U=H.createFramebuffer(),C=H.createFramebuffer(),B=H.createFramebuffer(),q=new y0(H),J=new Hx,nt=new nv(H,ee,y,J,P,gt,q),ht=new g0(R),dt=new bm(H),bt=new r0(H,dt),it=new x0(H,dt,q,bt),ot=new b0(H,it,dt,bt,q),k=new M0(H,P,nt),It=new l0(J),ft=new kx(R,ht,ee,P,bt,It),Ct=new av(R,J),_t=new Gx,pt=new Zx(ee),zt=new s0(R,ht,y,ot,g,l),Nt=new tv(R,ot,P),at=new lv(H,q,P,y),mt=new o0(H,ee,q),rt=new v0(H,ee,q),q.programs=ft.programs,R.capabilities=P,R.extensions=ee,R.properties=J,R.renderLists=_t,R.shadowMap=Nt,R.state=y,R.info=q}_!==nn&&(T=new w0(_,e.width,e.height,a,s,r));let At=new Zc(R,H);this.xr=At,this.getContext=function(){return H},this.getContextAttributes=function(){return H.getContextAttributes()},this.forceContextLoss=function(){let w=ee.get("WEBGL_lose_context");w&&w.loseContext()},this.forceContextRestore=function(){let w=ee.get("WEBGL_lose_context");w&&w.restoreContext()},this.getPixelRatio=function(){return j},this.setPixelRatio=function(w){w!==void 0&&(j=w,this.setSize(et,V,!1))},this.getSize=function(w){return w.set(et,V)},this.setSize=function(w,O,K=!0){if(At.isPresenting){Dt("WebGLRenderer: Can't change size while VR device is presenting.");return}et=w,V=O,e.width=Math.floor(w*j),e.height=Math.floor(O*j),K===!0&&(e.style.width=w+"px",e.style.height=O+"px"),T!==null&&T.setSize(e.width,e.height),this.setViewport(0,0,w,O)},this.getDrawingBufferSize=function(w){return w.set(et*j,V*j).floor()},this.setDrawingBufferSize=function(w,O,K){et=w,V=O,j=K,e.width=Math.floor(w*K),e.height=Math.floor(O*K),this.setViewport(0,0,w,O)},this.setEffects=function(w){if(_===nn){Ut("WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.");return}if(w){for(let O=0;O{function yt(){if(Y.forEach(function(wt){let Et=J.get(wt).currentProgram;(Et===void 0||Et.isReady())&&Y.delete(wt)}),Y.size===0){$(w);return}setTimeout(yt,10)}ee.get("KHR_parallel_shader_compile")!==null?yt():setTimeout(yt,10)})};let _l=null;function vp(w){_l&&_l(w)}function Nh(){bi.stop()}function Uh(){bi.start()}let bi=new Pd;bi.setAnimationLoop(vp),typeof self<"u"&&bi.setContext(self),this.setAnimationLoop=function(w){_l=w,At.setAnimationLoop(w),w===null?bi.stop():bi.start()},At.addEventListener("sessionstart",Nh),At.addEventListener("sessionend",Uh),this.render=function(w,O){if(O!==void 0&&O.isCamera!==!0){Ut("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(L===!0)return;N!==null&&N.renderStart(w,O);let K=At.enabled===!0&&At.isPresenting===!0,Y=T!==null&&(F===null||K)&&T.begin(R,F);if(w.matrixWorldAutoUpdate===!0&&w.updateMatrixWorld(),O.parent===null&&O.matrixWorldAutoUpdate===!0&&O.updateMatrixWorld(),At.enabled===!0&&At.isPresenting===!0&&(T===null||T.isCompositing()===!1)&&(At.cameraAutoUpdate===!0&&At.updateCamera(O),O=At.getCamera()),w.isScene===!0&&w.onBeforeRender(R,w,O,F),S=pt.get(w,x.length),S.init(O),S.state.textureUnits=nt.getTextureUnits(),x.push(S),qt.multiplyMatrices(O.projectionMatrix,O.matrixWorldInverse),Vt.setFromProjectionMatrix(qt,xn,O.reversedDepth),he=this.localClippingEnabled,Jt=It.init(this.clippingPlanes,he),v=_t.get(w,A.length),v.init(),A.push(v),At.enabled===!0&&At.isPresenting===!0){let wt=R.xr.getDepthSensingMesh();wt!==null&&xl(wt,O,-1/0,R.sortObjects)}xl(w,O,0,R.sortObjects),v.finish(),N!==null&&N.updateLights(S.state.lightsArray),R.sortObjects===!0&&v.sort(ut,Lt),Me=At.enabled===!1||At.isPresenting===!1||At.hasDepthSensing()===!1,Me&&zt.addToRenderList(v,w),this.info.render.frame++,this.info.autoReset===!0&&this.info.reset(),Jt===!0&&It.beginShadows();let $=S.state.shadowsArray;if(Nt.render($,w,O),Jt===!0&&It.endShadows(),(Y&&T.hasRenderPass())===!1){let wt=v.opaque,vt=v.transmissive;if(S.setupLights(),O.isArrayCamera){let Et=O.cameras;if(vt.length>0)for(let Rt=0,Gt=Et.length;Rt0&&Bh(wt,vt,w,O),Me&&zt.render(w),Fh(v,w,O)}F!==null&&W===0&&(nt.updateMultisampleRenderTarget(F),nt.updateRenderTargetMipmap(F)),Y&&T.end(R),w.isScene===!0&&w.onAfterRender(R,w,O),bt.resetDefaultState(),D=-1,X=null,x.pop(),x.length>0?(S=x[x.length-1],nt.setTextureUnits(S.state.textureUnits),Jt===!0&&It.setGlobalState(R.clippingPlanes,S.state.camera)):S=null,A.pop(),A.length>0?v=A[A.length-1]:v=null,N!==null&&N.renderEnd()};function xl(w,O,K,Y){if(w.visible===!1)return;if(w.layers.test(O.layers)){if(w.isGroup)K=w.renderOrder;else if(w.isLOD)w.autoUpdate===!0&&w.update(O);else if(w.isLightProbeGrid)S.pushLightProbeGrid(w);else if(w.isLight)S.pushLight(w),w.castShadow&&S.pushShadow(w);else if(w.isSprite){if(!w.frustumCulled||w.intersectsFrustum(Vt)){Y&&De.setFromMatrixPosition(w.matrixWorld).applyMatrix4(qt);let wt=ot.update(w),vt=w.material;vt.visible&&v.push(w,wt,vt,K,De.z,null,O)}}else if((w.isMesh||w.isLine||w.isPoints)&&(!w.frustumCulled||w.intersectsFrustum(Vt))){let wt=ot.update(w),vt=w.material;if(Y&&(w.boundingSphere!==void 0?(w.boundingSphere===null&&w.computeBoundingSphere(),De.copy(w.boundingSphere.center)):(wt.boundingSphere===null&&wt.computeBoundingSphere(),De.copy(wt.boundingSphere.center)),De.applyMatrix4(w.matrixWorld).applyMatrix4(qt)),Array.isArray(vt)){let Et=wt.groups;for(let Rt=0,Gt=Et.length;Rt0&&Br($,O,K),yt.length>0&&Br(yt,O,K),wt.length>0&&Br(wt,O,K),y.buffers.depth.setTest(!0),y.buffers.depth.setMask(!0),y.buffers.color.setMask(!0),y.setPolygonOffset(!1)}function Bh(w,O,K,Y){if((K.isScene===!0?K.overrideMaterial:null)!==null)return;if(S.state.transmissionRenderTarget[Y.id]===void 0){let Tt=ee.has("EXT_color_buffer_half_float")||ee.has("EXT_color_buffer_float");S.state.transmissionRenderTarget[Y.id]=new Fe(1,1,{generateMipmaps:!0,type:Tt?Sn:nn,minFilter:mi,samples:Math.max(4,P.samples),stencilBuffer:r,resolveDepthBuffer:!1,resolveStencilBuffer:!1,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1,colorSpace:Yt.workingColorSpace})}let yt=S.state.transmissionRenderTarget[Y.id],wt=Y.viewport||Z;yt.setSize(wt.z*R.transmissionResolutionScale,wt.w*R.transmissionResolutionScale);let vt=R.getRenderTarget(),Et=R.getActiveCubeFace(),Rt=R.getActiveMipmapLevel();R.setRenderTarget(yt),R.getClearColor(lt),ct=R.getClearAlpha(),ct<1&&R.setClearColor(16777215,.5),R.clear(),Me&&zt.render(K);let Gt=R.toneMapping;R.toneMapping=Mn;let Xt=Y.viewport;if(Y.viewport!==void 0&&(Y.viewport=void 0),S.setupLightsView(Y),Jt===!0&&It.setGlobalState(R.clippingPlanes,Y),Br(w,K,Y),nt.updateMultisampleRenderTarget(yt),nt.updateRenderTargetMipmap(yt),ee.has("WEBGL_multisampled_render_to_texture")===!1){let Tt=!1;for(let Qt=0,Ee=O.length;Qt0,Y.currentProgram=Xt,Y.uniformsList=null,Xt}function zh(w){if(w.uniformsList===null){let O=w.currentProgram.getUniforms();w.uniformsList=Ts.seqWithValue(O.seq,w.uniforms)}return w.uniformsList}function kh(w,O){let K=J.get(w);K.outputColorSpace=O.outputColorSpace,K.batching=O.batching,K.batchingColor=O.batchingColor,K.instancing=O.instancing,K.instancingColor=O.instancingColor,K.instancingMorph=O.instancingMorph,K.skinning=O.skinning,K.morphTargets=O.morphTargets,K.morphNormals=O.morphNormals,K.morphColors=O.morphColors,K.morphTargetsCount=O.morphTargetsCount,K.numClippingPlanes=O.numClippingPlanes,K.numIntersection=O.numClipIntersection,K.vertexAlphas=O.vertexAlphas,K.vertexTangents=O.vertexTangents,K.toneMapping=O.toneMapping}function yp(w,O){if(w.length===0)return null;if(w.length===1)return w[0].texture!==null?w[0]:null;M.setFromMatrixPosition(O.matrixWorld);for(let K=0,Y=w.length;K0),Tt=!!K.morphAttributes.position,Qt=!!K.morphAttributes.normal,Ee=!!K.morphAttributes.color,me=Mn;Y.toneMapped&&(F===null||F.isXRRenderTarget===!0)&&(me=R.toneMapping);let oe=K.morphAttributes.position||K.morphAttributes.normal||K.morphAttributes.color,Xe=oe!==void 0?oe.length:0,St=J.get(Y),je=S.state.lights;if(Jt===!0&&(he===!0||w!==X)){let de=w===X&&Y.id===D;It.setState(Y,w,de)}let Kt=!1;Y.version===St.__version?(St.needsLights&&St.lightsStateVersion!==je.state.version||St.outputColorSpace!==vt||$.isBatchedMesh&&St.batching===!1||!$.isBatchedMesh&&St.batching===!0||$.isBatchedMesh&&St.batchingColor===!0&&$._colorsTexture===null||$.isBatchedMesh&&St.batchingColor===!1&&$._colorsTexture!==null||$.isInstancedMesh&&St.instancing===!1||!$.isInstancedMesh&&St.instancing===!0||$.isSkinnedMesh&&St.skinning===!1||!$.isSkinnedMesh&&St.skinning===!0||$.isInstancedMesh&&St.instancingColor===!0&&$.instanceColor===null||$.isInstancedMesh&&St.instancingColor===!1&&$.instanceColor!==null||$.isInstancedMesh&&St.instancingMorph===!0&&$.morphTexture===null||$.isInstancedMesh&&St.instancingMorph===!1&&$.morphTexture!==null||St.envMap!==Rt||Y.fog===!0&&St.fog!==yt||St.numClippingPlanes!==void 0&&(St.numClippingPlanes!==It.numPlanes||St.numIntersection!==It.numIntersection)||St.vertexAlphas!==Gt||St.vertexTangents!==Xt||St.morphTargets!==Tt||St.morphNormals!==Qt||St.morphColors!==Ee||St.toneMapping!==me||St.morphTargetsCount!==Xe||!!St.lightProbeGrid!=S.state.lightProbeGridArray.length>0)&&(Kt=!0):(Kt=!0,St.__version=Y.version);let hn=St.currentProgram;Kt===!0&&(hn=Or(Y,O,$),N&&Y.isNodeMaterial&&N.onUpdateProgram(Y,hn,St));let Rn=!1,ti=!1,Hi=!1,se=hn.getUniforms(),be=St.uniforms;if(y.useProgram(hn.program)&&(Rn=!0,ti=!0,Hi=!0),Y.id!==D&&(D=Y.id,ti=!0),St.needsLights){let de=yp(S.state.lightProbeGridArray,$);St.lightProbeGrid!==de&&(St.lightProbeGrid=de,ti=!0)}if(Rn||X!==w){y.buffers.depth.getReversed()&&w.reversedDepth!==!0&&(w._reversedDepth=!0,w.updateProjectionMatrix()),se.setValue(H,"projectionMatrix",w.projectionMatrix),se.setValue(H,"viewMatrix",w.matrixWorldInverse);let ni=se.map.cameraPosition;ni!==void 0&&ni.setValue(H,ye.setFromMatrixPosition(w.matrixWorld)),P.logarithmicDepthBuffer&&se.setValue(H,"logDepthBufFC",2/(Math.log(w.far+1)/Math.LN2)),(Y.isMeshPhongMaterial||Y.isMeshToonMaterial||Y.isMeshLambertMaterial||Y.isMeshBasicMaterial||Y.isMeshStandardMaterial||Y.isShaderMaterial)&&se.setValue(H,"isOrthographic",w.isOrthographicCamera===!0),X!==w&&(X=w,ti=!0,Hi=!0)}if(St.needsLights&&(je.state.sunShadowMap.length>0&&se.setValue(H,"sunShadowMap",je.state.sunShadowMap,nt),je.state.directionalShadowMap.length>0&&se.setValue(H,"directionalShadowMap",je.state.directionalShadowMap,nt),je.state.spotShadowMap.length>0&&se.setValue(H,"spotShadowMap",je.state.spotShadowMap,nt),je.state.pointShadowMap.length>0&&se.setValue(H,"pointShadowMap",je.state.pointShadowMap,nt)),$.isSkinnedMesh){se.setOptional(H,$,"bindMatrix"),se.setOptional(H,$,"bindMatrixInverse");let de=$.skeleton;de&&(de.boneTexture===null&&de.computeBoneTexture(),se.setValue(H,"boneTexture",de.boneTexture,nt))}$.isBatchedMesh&&(se.setOptional(H,$,"batchingTexture"),se.setValue(H,"batchingTexture",$._matricesTexture,nt),se.setOptional(H,$,"batchingIdTexture"),se.setValue(H,"batchingIdTexture",$._indirectTexture,nt),se.setOptional(H,$,"batchingColorTexture"),$._colorsTexture!==null&&se.setValue(H,"batchingColorTexture",$._colorsTexture,nt));let ei=K.morphAttributes;if((ei.position!==void 0||ei.normal!==void 0||ei.color!==void 0)&&k.update($,K,hn),(ti||St.receiveShadow!==$.receiveShadow)&&(St.receiveShadow=$.receiveShadow,se.setValue(H,"receiveShadow",$.receiveShadow)),(Y.isMeshStandardMaterial||Y.isMeshLambertMaterial||Y.isMeshPhongMaterial)&&Y.envMap===null&&O.environment!==null&&(be.envMapIntensity.value=O.environmentIntensity),be.dfgLUT!==void 0&&(be.dfgLUT.value=hv()),ti){if(se.setValue(H,"toneMappingExposure",R.toneMappingExposure),St.needsLights&&bp(be,Hi),yt&&Y.fog===!0&&Ct.refreshFogUniforms(be,yt),Ct.refreshMaterialUniforms(be,Y,j,V,S.state.transmissionRenderTarget[w.id]),St.needsLights&&St.lightProbeGrid){let de=St.lightProbeGrid;be.probesSH.value=de.texture,be.probesMin.value.copy(de.boundingBox.min),be.probesMax.value.copy(de.boundingBox.max),be.probesResolution.value.copy(de.resolution)}Ts.upload(H,zh(St),be,nt)}if(Y.isShaderMaterial&&Y.uniformsNeedUpdate===!0&&(Ts.upload(H,zh(St),be,nt),Y.uniformsNeedUpdate=!1),Y.isSpriteMaterial&&se.setValue(H,"center",$.center),se.setValue(H,"modelViewMatrix",$.modelViewMatrix),se.setValue(H,"normalMatrix",$.normalMatrix),se.setValue(H,"modelMatrix",$.matrixWorld),Y.uniformsGroups!==void 0){let de=Y.uniformsGroups;for(let ni=0,Vi=de.length;ni0&&nt.useMultisampledRTT(w)===!1?Y=J.get(w).__webglMultisampledFramebuffer:Array.isArray(Rt)?Y=Rt[K]:Y=Rt,Z.copy(w.viewport),G.copy(w.scissor),Q=w.scissorTest}else Z.copy(Mt).multiplyScalar(j).floor(),G.copy(Bt).multiplyScalar(j).floor(),Q=ve;if(K!==0&&(Y=U),y.bindFramebuffer(H.FRAMEBUFFER,Y)&&y.drawBuffers(w,Y),y.viewport(Z),y.scissor(G),y.setScissorTest(Q),$){let vt=J.get(w.texture);H.framebufferTexture2D(H.FRAMEBUFFER,H.COLOR_ATTACHMENT0,H.TEXTURE_CUBE_MAP_POSITIVE_X+O,vt.__webglTexture,K)}else if(yt){let vt=O;for(let Et=0;Et1&&H.readBuffer(H.COLOR_ATTACHMENT0+vt);let Tt=Hh(Rt);if(Tt.__formatReadable===!1){Ut("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(Tt.__typeReadable===!1){Ut("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}O>=0&&O<=w.width-Y&&K>=0&&K<=w.height-$&&H.readPixels(O,K,Y,$,gt.convert(Gt),gt.convert(Xt),yt)}finally{let Rt=F!==null?J.get(F).__webglFramebuffer:null;y.bindFramebuffer(H.FRAMEBUFFER,Rt)}}},this.readRenderTargetPixelsAsync=async function(w,O,K,Y,$,yt,wt,vt=0){if(!(w&&w.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let Et=J.get(w).__webglFramebuffer;if(w.isWebGLCubeRenderTarget&&wt!==void 0&&(Et=Et[wt]),Et)if(O>=0&&O<=w.width-Y&&K>=0&&K<=w.height-$){y.bindFramebuffer(H.FRAMEBUFFER,Et);let Rt=w.textures[vt],Gt=Rt.format,Xt=Rt.type;w.textures.length>1&&H.readBuffer(H.COLOR_ATTACHMENT0+vt);let Tt=Hh(Rt);if(Tt.__formatReadable===!1)throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(Tt.__typeReadable===!1)throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");let Qt=H.createBuffer();H.bindBuffer(H.PIXEL_PACK_BUFFER,Qt),H.bufferData(H.PIXEL_PACK_BUFFER,yt.byteLength,H.STREAM_READ),H.readPixels(O,K,Y,$,gt.convert(Gt),gt.convert(Xt),0),H.bindBuffer(H.PIXEL_PACK_BUFFER,null);let Ee=F!==null?J.get(F).__webglFramebuffer:null;y.bindFramebuffer(H.FRAMEBUFFER,Ee);let me=H.fenceSync(H.SYNC_GPU_COMMANDS_COMPLETE,0);return H.flush(),await sd(H,me,4),H.bindBuffer(H.PIXEL_PACK_BUFFER,Qt),H.getBufferSubData(H.PIXEL_PACK_BUFFER,0,yt),H.bindBuffer(H.PIXEL_PACK_BUFFER,null),H.deleteBuffer(Qt),H.deleteSync(me),yt}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(w,O=null,K=0){let Y=Math.pow(2,-K),$=Math.floor(w.image.width*Y),yt=Math.floor(w.image.height*Y),wt=O!==null?O.x:0,vt=O!==null?O.y:0;nt.setTexture2D(w,0),H.copyTexSubImage2D(H.TEXTURE_2D,K,0,0,wt,vt,$,yt),y.unbindTexture()},this.copyTextureToTexture=function(w,O,K=null,Y=null,$=0,yt=0){let wt,vt,Et,Rt,Gt,Xt,Tt,Qt,Ee,me=w.isCompressedTexture?w.mipmaps[yt]:w.image;if(K!==null)wt=K.max.x-K.min.x,vt=K.max.y-K.min.y,Et=K.isBox3?K.max.z-K.min.z:1,Rt=K.min.x,Gt=K.min.y,Xt=K.isBox3?K.min.z:0;else{let be=Math.pow(2,-$);wt=Math.floor(me.width*be),vt=Math.floor(me.height*be),w.isDataArrayTexture?Et=me.depth:w.isData3DTexture?Et=Math.floor(me.depth*be):Et=1,Rt=0,Gt=0,Xt=0}Y!==null?(Tt=Y.x,Qt=Y.y,Ee=Y.z):(Tt=0,Qt=0,Ee=0);let oe=gt.convert(O.format),Xe=gt.convert(O.type),St;O.isData3DTexture?(nt.setTexture3D(O,0),St=H.TEXTURE_3D):O.isDataArrayTexture||O.isCompressedArrayTexture?(nt.setTexture2DArray(O,0),St=H.TEXTURE_2D_ARRAY):(nt.setTexture2D(O,0),St=H.TEXTURE_2D),y.activeTexture(H.TEXTURE0),y.pixelStorei(H.UNPACK_FLIP_Y_WEBGL,O.flipY),y.pixelStorei(H.UNPACK_PREMULTIPLY_ALPHA_WEBGL,O.premultiplyAlpha),y.pixelStorei(H.UNPACK_ALIGNMENT,O.unpackAlignment);let je=y.getParameter(H.UNPACK_ROW_LENGTH),Kt=y.getParameter(H.UNPACK_IMAGE_HEIGHT),hn=y.getParameter(H.UNPACK_SKIP_PIXELS),Rn=y.getParameter(H.UNPACK_SKIP_ROWS),ti=y.getParameter(H.UNPACK_SKIP_IMAGES);y.pixelStorei(H.UNPACK_ROW_LENGTH,me.width),y.pixelStorei(H.UNPACK_IMAGE_HEIGHT,me.height),y.pixelStorei(H.UNPACK_SKIP_PIXELS,Rt),y.pixelStorei(H.UNPACK_SKIP_ROWS,Gt),y.pixelStorei(H.UNPACK_SKIP_IMAGES,Xt);let Hi=w.isDataArrayTexture||w.isData3DTexture,se=O.isDataArrayTexture||O.isData3DTexture;if(w.isDepthTexture){let be=J.get(w),ei=J.get(O),de=J.get(be.__renderTarget),ni=J.get(ei.__renderTarget);y.bindFramebuffer(H.READ_FRAMEBUFFER,de.__webglFramebuffer),y.bindFramebuffer(H.DRAW_FRAMEBUFFER,ni.__webglFramebuffer);for(let Vi=0;Vi=c.length){s-=c.length;continue}let h=Math.min(o,c.length-s);if(a.push(c.substringData(s,h)),o-=h,s=0,!o)break}let l=new Uint8Array(Math.ceil((r+e)/3)*3);if(Jc(l,0,a.join(""))i!==null&&typeof i=="object"&&!Array.isArray(i),xi=i=>Array.isArray(i)&&i.every(Cs),Qn=i=>Array.isArray(i)&&i.length===3&&i.every(t=>typeof t=="number"),Gd=i=>Cs(i)&&Qn(i.min)&&Qn(i.max),kd=i=>i==null||Cs(i)&&xi(i.planes)&&i.planes.every(t=>Qn(t.normal)&&t.normal.every(Number.isFinite)&&t.normal.some(e=>e!==0)&&Number.isFinite(t.offset))&&(i.box==null||Gd(i.box)&&i.box.max.every(Number.isFinite)&&i.box.min.every((t,e)=>Number.isFinite(t)&&t<=i.box.max[e]));function fv(i){if(!Cs(i)||!xi(i.elements)||!xi(i.geometries)||!xi(i.materials)||!Cs(i.instances))throw new re("META must describe elements, geometries, materials and instances.");if(i.title!=null&&typeof i.title!="string")throw new re("Invalid META title.");let{instances:t}=i;if(!Number.isSafeInteger(t.count)||t.count<0)throw new re("Invalid META instance count.");for(let[e,n,s]of[["geometry","u32",t.count],["material","u32",t.count],["element","i32",t.count],["matrix","f32",t.count*12]])if(t[e]?.t!==n||t[e].n!==s)throw new re(`Invalid META instance ${e} view.`);for(let e of i.geometries){let n=e.q;if(!Gd(e.bbox)||!["u16","u32"].includes(e.indices?.t)||e.positions?.t!==(n?"u16":"f32")||n&&(!Qn(n.o)||typeof n.s!="number")||e.normals!=null&&!["f32","i16"].includes(e.normals.t)||e.uvs!=null&&e.uvs.t!=="f32")throw new re("Invalid META geometry.")}pv(i);for(let e of i.materials){let n=e.texture;if(!Qn(e.color)||typeof e.opacity!="number"||n!=null&&(!Number.isInteger(n)||n<0||n>=(i.textures?.length??0)))throw new re("Invalid META material.")}}function pv(i){if(!Cs(i)||!xi(i.elements)||i.title!=null&&typeof i.title!="string")throw new re("Invalid review metadata.");for(let a of["textures","grids","viewpoints","bcfTopics","clashTests","linkedFiles","models"])if(i[a]!=null&&!xi(i[a]))throw new re(`Invalid META ${a} list.`);if(i.models?.some(({id:a,name:l})=>!Number.isSafeInteger(a)||typeof l!="string")||i.elements.some(({modelId:a,levelId:l})=>a!=null&&!Number.isSafeInteger(a)||l!=null&&!Number.isSafeInteger(l)))throw new re("Invalid META model or level identity.");let t=a=>a==null||Array.isArray(a)&&a.every(l=>Number.isInteger(l)&&l>=0&&lQn(a)&&a.every(Number.isFinite),n=a=>a==null||typeof a=="string",s=a=>e(a.camera?.position)&&e(a.camera?.target)&&kd(a.sections)&&t(a.hiddenElements)&&t(a.visibleElements)&&t(a.selectedElements)&&(a.hiddenElements==null||a.visibleElements==null)&&(a.hiddenModelKeys==null||Array.isArray(a.hiddenModelKeys)&&a.hiddenModelKeys.every(l=>typeof l=="string")),r=a=>Number.isSafeInteger(a)&&a>=0,o=a=>s(a)&&e(a.camera.up)&&a.camera.up.some(l=>l!==0)&&(a.camera.projection==="orthographic"?Number.isFinite(a.camera.orthographicHeight)&&a.camera.orthographicHeight>0:a.camera.projection==="perspective"&&Number.isFinite(a.camera.fov)&&a.camera.fov>0&&a.camera.fov<180)&&r(a.missingComponents)&&r(a.ambiguousComponents);if(i.grids?.some(a=>!Qn(a.start)||!Qn(a.end))||i.viewpoints?.some(a=>!s(a))||i.clashTests?.some(a=>!xi(a.clashes)||a.clashes.some(l=>!Qn(l.point))))throw new re("Invalid META grids, viewpoints or clashes.");if(i.bcfTopics?.some(a=>typeof a.title!="string"||!n(a.description)||!n(a.status)||!xi(a.viewpoints)||a.viewpoints.some(l=>!o(l))))throw new re("Invalid META BCF topics.");if(i.linkedFiles?.some(a=>!t(a.members)))throw new re("Invalid META linked file members.");if(!kd(i.sections))throw new re("Invalid META sections.")}function mv(i){let t;try{t=JSON.parse(i)}catch(e){throw new re(e.message,{cause:e})}return fv(t),t}function Kc(i=document,t){t?.("metadataStart");let e;try{e=Vd(i,"ioviewer-meta")}catch(s){throw s instanceof re?s:new re(s.message,{cause:s})}let n=mv(e);return t?.("metadataEnd"),n}function Hd(i,t){let e=uv[i?.t];if(!e)throw new re(`Unknown view type '${i?.t}'.`);let n=e.BYTES_PER_ELEMENT;if(!(Number.isSafeInteger(i.o)&&Number.isSafeInteger(i.n)&&i.o>=0&&i.n>=0&&i.o%n===0&&i.o+i.n*n<=t))throw new re(`View ${JSON.stringify(i)} is outside the ${t} bytes of binary data.`);return e}function Wd(i=document,t,e=Kc(i,t)){let n,s,r,o;try{if(t?.("binaryStart"),s=i.getElementById("ioviewer-bin"),!s)throw new Error("Data block 'ioviewer-bin' is missing.");({bytes:n,canonical:r}=zd(s)),t?.("binaryEnd")}catch(c){throw new re(c.message,{cause:c})}let a=n.length,l=null;return{meta:e,view(c){if(!n)throw new Error("The binary data has been released.");let h=Hd(c,a);return new h(n.buffer,c.o,c.n)},readView(c){let h=Hd(c,a);if(!c.n)return new h(0);!n&&!r&&(o??(o=zd(s).bytes));let d=n??o;return d?new h(d.buffer,c.o,c.n):new h(dv(s,c.o,c.n*h.BYTES_PER_ELEMENT))},releaseBinary(){n=null,o=null},props(c){return l??(l=JSON.parse(Vd(i,"ioviewer-props"))),l[c]??null}}}var Xd=new kt,qd=new Un,jc=32;function Qc(i,t=new Float64Array(24)){return Xd.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),qd.setFromProjectionMatrix(Xd,i.coordinateSystem,i.reversedDepth),qd.planes.forEach(({normal:e,constant:n},s)=>t.set([e.x,e.y,e.z,n],s*4)),t}function th(i,t,e,n,s){for(let r=0;r<24;r+=4)if(i[r]*t+i[r+1]*e+i[r+2]*n+i[r+3]<-s)return!0;return!1}function Yd(i,t,e,n,s){for(let r=0;r<24;r+=4)if(i[r]*t+i[r+1]*e+i[r+2]*n+i[r+3]=0;r--)if(i[r]!==0){if(n+=i[r],n>e)return s?r===0?0:2**(r/2-4):2**((r+1)/2-4);s=!1}return 0}var wn=.0009765625,nh=32767,Mr=i=>i<0?-1:1;function Zd(i){let t=Math.min(Math.max(i,-1),1)*nh;return Mr(t)*Math.round(Math.abs(t))}function br(i,t,e,n,s){let r=Math.abs(e)+Math.abs(n)+Math.abs(s);if(!(r>0)){i[t]=i[t+1]=0;return}let o=e/r,a=n/r;s<0&&([o,a]=[(1-Math.abs(a))*Mr(o),(1-Math.abs(o))*Mr(a)]),i[t]=Zd(o),i[t+1]=Zd(a)}function Jd(i,t,e,n){let s=Math.max(e/nh,-1),r=Math.max(n/nh,-1),o=1-Math.abs(s)-Math.abs(r);o<0&&([s,r]=[(1-Math.abs(r))*Mr(s),(1-Math.abs(s))*Mr(r)]);let a=Math.sqrt(s*s+r*r+o*o);i[t]=s/a,i[t+1]=r/a,i[t+2]=o/a}function Sr(i,t){let e=i.view(t.positions);if(!t.q){if(!(e instanceof Float32Array))throw new Error(`Geometry positions of type '${t.positions.t}' need a "q" origin and step.`);return e}if(!(e instanceof Uint16Array))throw new Error(`Quantized geometry positions must be u16, got '${t.positions.t}'.`);return e}function Kd(i,t){let e=Sr(i,t);if(!t.q)return e;let[n,s,r]=t.q.o,o=t.q.s,a=new Float32Array(e.length);for(let l=0;ls[d]&&(s[d]=u))}let r=0;for(let h=1;h<3;h++)s[h]-n[h]>s[r]-n[r]&&(r=h);let o=s[r]-n[r],a=2**20-1,l=new Float64Array(i.length);for(let h=0;h0&&Number.isFinite(u)?Math.round((u-n[r])/o*a):0;l[h]=p*2**32+d}let c=0;e<0?l.sort():c=_v(l,e);for(let h=0;hr)return i.subarray(e,n+1).sort(),a+l*Math.ceil(Math.log2(l));a+=l,s=Math.imul(s,1664525)+1013904223>>>0;let c=i[e+s%(n-e+1)],h=e,d=n;for(;h<=d;){for(;i[h]c;)d--;if(h<=d){let u=i[h];i[h++]=i[d],i[d--]=u}}if(t<=d)n=d;else if(t>=h)e=h;else return a}return a}function rf(i,t,e,n=1/0){let s=[];s.scanned=0;let r=[Uint32Array.from(t)];for(;r.length;){let o=r.pop(),a=Math.ceil(o.length/e);if(o.length<=1||a<=1&&xv(o,i)<=n){o.length&&s.push(o);continue}let l=a>1?Math.ceil(o.length*Math.floor(a/2)/a):Math.ceil(o.length/2);s.scanned+=sf(o,i,l),r.push(o.subarray(l),o.subarray(0,l))}return s}function xv(i,t){let e=1/0,n=1/0,s=1/0,r=-1/0,o=-1/0,a=-1/0;for(let l of i){let c=t[l*3],h=t[l*3+1],d=t[l*3+2];cr&&(r=c),ho&&(o=h),da&&(a=d)}return Math.hypot(r-e,o-n,a-s)/2}function of(i,t){let e=new Float64Array(6).fill(-1/0),n=new Float64Array(6).fill(-1/0),s=new Int32Array(6);for(let o=0;oe[a]?(n[a]=e[a],e[a]=c,s[a]=o):c>n[a]&&(n[a]=c)}if(e[0]===-1/0)return 0;let r=Math.hypot(e[0]+e[3],e[1]+e[4],e[2]+e[5]);if(n[0]===-1/0)return r;for(let o of s){let a=c=>s[c]===o?n[c]:e[c],l=Math.hypot(a(0)+a(3),a(1)+a(4),a(2)+a(5));r=Math.min(r,2*l)}return r}var sh=384*2**20;function af(i,{cap:t=sh,minRepeats:e=16,perCell:n=1024,maxDraws:s=1024}={}){let r=new Uint8Array(i.length),o=0;for(let h of i)o+=h.k*h.bytes;if(o<=t)return r;let a=h=>(i[h].k-1)*i[h].bytes,l=[...i.keys()].filter(h=>i[h].k>=e);l.sort((h,d)=>a(d)-a(h)||i[d].k-i[h].k||h-d);let c=0;for(let h of l){let d=i[h].cells??Math.ceil(i[h].k/n);c+d>s||(r[h]=1,c+=d)}return r}function Wa(i,t){return i>65535?new Uint32Array(t):new Uint16Array(t)}function rh(i,t){return i.sort((e,n)=>t[n]-t[e]||e-n)}function lf(i,t,e,n){for(;t>>1;i[s]>=n?t=s+1:e=s}return t}function cf(i,t,e){let n=i[t];return[n,e>t?i[e]-n:0]}function hf(i,t,e,n){let s=i.subarray(t*12,t*12+12);if(s[0]===1&&s[1]===0&&s[2]===0&&s[3]===0&&s[4]===1&&s[5]===0&&s[6]===0&&s[7]===0&&s[8]===1&&e.q&&e.q.s===wn){for(let a=0;a<3;a++)n[a]=s[9+a]+e.q.o[a];return tf}let o=!0;for(let a=0;a<3;a++){let l=s[9+a],c=s[9+a];for(let h=0;h<3;h++){let d=s[h*3+a]*e.min[h],u=s[h*3+a]*e.max[h];l+=Math.min(d,u),c+=Math.max(d,u)}n[a]=Math.floor(l/wn)*wn,Math.ceil((c-n[a])/wn)<=ef||(o=!1)}return o||n.fill(0),o?gv:Ps}function uf(i,t){let e=i.length,n=0,s=0;for(let m of i){let f=t.source(t.geometryOf[m]);n+=f.vertices,s+=f.indices.length}let r=t.kind[i[0]]===Ps,o=r?new Float32Array(n*4):new Uint16Array(n*4),a=new Int16Array(n*2),l=t.textured?new Float32Array(n*2):null,c=Wa(n,s),h=new Uint32Array(e+1),d=new Float32Array(e*3),u=new Float32Array(e),p=new Float64Array(3),g=0,_=0;for(let m=0;mMath.min(Math.max(Math.round(i/wn),0),ef);function df(i,t,e,n,s){let r=i.length/3,o=[1/0,1/0,1/0],a=[-1/0,-1/0,-1/0];for(let c=0;ca[h]&&(a[h]=d)}let l=e instanceof Int16Array?e:null;return{positions:i,q:t,oct:l,normals:l?null:e,indices:n,uvs:s,vertices:r,min:o,max:a}}function Xa(i){if(!i.normals&&i.oct){i.normals=new Float32Array(i.vertices*3);for(let t=0;t=0)throw new Error(`The shader must contain '${t}' exactly once.`);return i.slice(0,n)+e+i.slice(n+t.length)}function vv(i){Object.assign(i.uniforms,this.userData.slotUniforms);let t=xi(i.vertexShader,"#include ",`#include -${wr}`);t=xi(t,"#include ",`${Er} -vTint = state.rgb;`),t=xi(t,"#include ","vec3 objectNormal = ioOct( normal.xy );"),t=xi(t,"#include ",xv),t=xi(t,"#include ","vec3 transformed = slotPosition;"),t=xi(t,"#include ",`#include -${oh}`),i.vertexShader=t;let e=xi(i.fragmentShader,"#include ",`#include -varying vec3 vTint;`);e=xi(e,"#include ","diffuseColor.rgb *= vTint;"),i.fragmentShader=e}function ah(i,t,e=!1){return i.userData.slotUniforms=t,i.onBeforeCompile=vv,i.index0AttributeName="q",e&&(i.defines={IO_NO_HIDE_BRANCH:""}),i}var uh=["materials","textures","white","wireframe"],yv=[245,158,11],Mv=[235,235,237],Tr=4294967295,zi=2048,lh=256,bv=16,ch=1024,Sv=.1,wv=8192,Ev=1.4,Ya=2**-20,qa=17;function Tv(i,t){let[e,n,s,r,o,a,l,c,h]=i.subarray(t*12,t*12+9);return e*(o*h-a*c)-r*(n*h-s*c)+l*(n*a-s*o)<0}function Av(){this.array=null}function En(i,t,e=!1,n=Se){return new n(i,t,e).onUpload(Av)}var Ar=class extends RangeError{constructor(t,e){super(`${t} drawable instances exceed the limit of ${e}.`),this.name="ModelTooLargeError",this.count=t,this.limit=e}},uf=(i,t)=>{for(let e=t*6;e=0?3:0)]+o*t[e+(o>=0?4:1)]+a*t[e+(a>=0?5:2)]+l<-(n+Ya*Math.abs(l)))return!0}return!1}function Cv(i,t,{min:e,max:n},s){let r=t*12,o=t*6;if(e[0]>n[0]||e[1]>n[1]||e[2]>n[2]){s.set(e,o),s.set(n,o+3);return}for(let a=0;a<3;a++){let l=i[r+a],c=i[r+a+3],h=i[r+a+6],d=i[r+a+9],u=l*e[0],p=l*n[0],g=c*e[1],_=c*n[1],m=h*e[2],f=h*n[2];s[o+a]=Math.min(u,p)+Math.min(g,_)+Math.min(m,f)+d,s[o+a+3]=Math.max(u,p)+Math.max(g,_)+Math.max(m,f)+d}}var Iv=i=>{let t=i.getHex(Ae);return[t>>16&255,t>>8&255,t&255]},Rr=class{constructor(t,e={}){let{meta:n}=t,s=n.instances,r=s.count,o=t.view(s.geometry),a=t.view(s.material),l=t.view(s.matrix);this.root=new Re,this.elementCount=n.elements.length,this._elements=n.elements,this._meta=n,this._mode="materials",this._opacity=1,this._picking=!1,this._pickBounds=!0,this._instanceDetail=!0,this._pickFrustum=null,this._textures=new Map,this._elementOf=t.view(s.element).slice(),this._bucketOf=new Uint32Array(r),this._visible=new Uint8Array(r).fill(1),this._layers=new Map,this._layerHides=new Uint8Array(r),this._highlight=new Uint8Array(r),this._highlighted=[],this._tint=new Map,this._boxes=new Float32Array(r*6),this._minPixels=0,this._viewHeight=1,this.visibleCost=0;let c=!!e.noHideBranch;this.slotUniforms={slotInfo:{value:null},slotState:{value:null}},this._buckets=this._createBuckets(n,a,c),this._indexElements();for(let d=0;dthis._shown(e)?1:0)}instancesOf(t){return this._checkElement(t),this._elementInstances.subarray(this._elementStart[t],this._elementStart[t+1])}isVisible(t){this._checkElement(t);for(let e=this._elementStart[t];ethis._chunkCount){this._pickFrustum=Qc(n,this._planes);let{x:r,y:o,z:a}=n.position;this._pickViewPadding=Ya*(Math.abs(r)+Math.abs(o)+Math.abs(a))}for(let r of this._units)r.mesh.material=t,s?(r.mesh.visible=(r.mesh.visible||!!r.lines?.visible)&&r.bucket.material.opacity>0,r.lines&&(r.lines.visible=!1)):this._showUnit(r);if(!s)for(let r of this._compactCells)this._cellAttributes(r,!1);try{return e()}finally{this._picking=!1,this._pickFrustum=null;for(let r of this._units)r.mesh.material=r.bucket.material,this._showUnit(r);for(let r of this._cut)r.mesh.visible=!1,r.lines&&(r.lines.visible=!1);if(!s)for(let r of this._compactCells)this._cellAttributes(r,!0)}}elementBox(t,e=new ie){this._checkElement(t),e.makeEmpty();for(let n=this._elementStart[t];n=0&&t<=1))throw new RangeError(`Opacity must be within 0..1, got ${t}.`);this._opacity=t;for(let e of this._buckets)this._applyOpacity(e);this._changed("appearance")}get opacity(){return this._opacity}setDetail(t,e=1){this._minPixels=t,this._viewHeight=e;for(let s of this._cut)this._showUnit(s);this._cut.length=0;for(let s of this._detailCells)s.detailCount=null;this._detailCells.length=0;for(let s of this._compactCells)this._cellAttributes(s,!1);this._compactCells.length=0;let n=this._unitScale;this._unitScale=null,!(!(t>0)||!n)&&(this._cutInView=0,this._cutFrame=null,this._units.forEach((s,r)=>{if(!(!(n[r]>=0)||s.shown===0)){if(s.dirty&&this._span(s),s.cell&&this._detailUsesInstances){if(s.detailHigh>=t&&this._detailCell(s,t))return}else if(this._slotRadius[s.slotBase+s.first]*n[r]>=t)return;s.mesh.visible=!1,s.lines&&(s.lines.visible=!1),this._cut.push(s),this._cutInView+=hh(s,s.first,s.last+1)}}))}_detailCell(t,e){if(t.detailLow>=e)return t.detailCount=Math.min(t.detailEnd,t.last+1),this._detailCells.push(t),!0;let{slotBase:n,last:s}=t,r=this._detailIndices,o=0,a=!1,l=!1;for(let u=0;u<=s;u++){let p=this._pixels[n+u];p<0||(pc.count;for(let u=0;u0?o[6]/m:1/0:o[6];d[p]=f;let b=g.cell&&this._detailUsesInstances,E=b&&!Xd(r,_[0],_[1],_[2],_[3]+g.pickPadding),M=g.slotBase+g.n,v=-1;if(b){let R=this._slotRadius[g.slotBase],L=this._slotRadius[M-1],N=m+_[3],U=Math.abs(o[3])*_[4]+Math.abs(o[4])*_[5]+Math.abs(o[5])*_[6],C=N-U-R,B=N+U-L,z=Math.fround(o[7]?C>0?R*o[6]/C:1/0:R*f),W=Math.fround(o[7]?B>0?L*o[6]/B:1/0:L*f);Cs(W)===Cs(z)&&(v=z)}if(v>=0&&!E){g.detailLow=g.detailHigh=v,g.detailEnd=g.n;let R=this._slotCost[g.slotBase]*g.shown;l[Cs(v)]+=R,u+=R;continue}let S=0,A=1/0,x=-1,T=0;for(let R=g.slotBase;R=0){S++;continue}let D=(z-o[0])*o[3]+(W-o[1])*o[4]+(F-o[2])*o[5]-L;N=o[7]?D>0?o[6]/D:1/0:o[6]}let U=N===1/0?1/0:Math.fround(L*N);b&&(a[R]=U,A=Math.min(A,U),x=Math.max(x,U));let C=this._slotCost[R];l[Cs(U)]+=C,u+=C}if(b){if(S){A=x=v;let R=S*this._slotCost[g.slotBase];l[Cs(v)]+=R,u+=R}g.detailLow=A,g.detailHigh=x,g.detailEnd=T}}return this.visibleCost=u,qd(l,u,n)}drawStats(){let t=-1/0;for(let r of this._units)t=Math.max(t,r.lastFrame);let e=0,n=this._cutFrame===t?this._cutInView:0,s=0;for(let r of this._units)r.lastFrame===t&&(n+=hh(r,r.first,Math.max(r.last+1,r.first)),e+=hh(r,r.first,Math.max(r.end,r.first)),s++);return{drawn:e,inView:n,draws:s}}drawnInstances(t){t.updateMatrixWorld();let e=new Un().setFromProjectionMatrix(new kt().multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse)),n={info:{render:{frame:-1}}},s=new Oe,r=[];for(let o of this._units){let a=this._mode==="wireframe"&&!this._picking?o.lines:o.mesh;if(!(!a?.visible||!e.intersectsSphere(s.set(s.center.fromArray(o.sphere),o.sphere[3])))){a.onBeforeRender(n,null,t,a.geometry,a.material,null);for(let l=o.first;lo-a)}memory(){let t=this._units[this._chunkCount]?.slotBase??this._slotInstance.length;return{gpuBytes:this._mergedBytes+this._instancedBytes+this._lineBytes+this._stateBytes+this._detailBytes,mergedBytes:this._mergedBytes,instancedBytes:this._instancedBytes,stateBytes:this._stateBytes,lineBytes:this._lineBytes,detailBytes:this._detailBytes,detailSourceBytes:(this._slotInstance.length-t)*48,chunks:this._chunkCount,cells:this._units.length-this._chunkCount,mergedInstances:t,instancedInstances:this._slotInstance.length-t,triangles:this._triangles}}setClipping(t,e){for(let n of this._buckets)for(let s of[n.material,n.wire])s.clippingPlanes=t.length>0?t:null,s.clipIntersection=e,s.needsUpdate=!0;this._changed("clipping")}_build(t,e,n,s,r){let o=e.length,a=this._meta,l=new Map,c=F=>{let D=l.get(F);if(!D){let X=a.geometries[F],Z=t.view(X.indices),G=X.uvs?t.view(X.uvs):null;D=hf(Sr(t,X),X.q??null,Jd(t,X),Z,G),D.drawable=D.indices.length>=3&&D.min.every(Number.isFinite)&&D.max.every(Number.isFinite),l.set(F,D)}return D},h=new Uint8Array(o),d=new Float64Array(o*3),u=new Float32Array(o*3),p=new Uint32Array(o),g=new Float32Array(o),_=new Uint8Array(o),m=new Map,f=this._boxes;for(let F=0;FF-D).map(F=>{let D=m.get(F),X=c(e[D[0]]),Z=this._buckets[this._bucketOf[D[0]]].texture!==null,G=[0,1,2].every(lt=>(X.max[lt]-X.min[lt])/wn<=65535),Q=X.vertices*((G?12:20)+(Z?8:0))+X.indices.length*(X.vertices>65535?4:2);return{k:D.length,bytes:Q,members:D,textured:Z}}),M=s.mergedCap??sh,v=s.minRepeats??bv;if(E.reduce((F,D)=>F+D.k*D.bytes,0)>M){let F=s.cellExtent==null?sf(f,p)*Sv:this.visibleBox().getSize(new I).length()*s.cellExtent;for(let D of E)D.k{if(S[D]){for(let X of F.leaves)T.push({shape:F,members:rh(X,g)});return}for(let X of F.members){x[e[X]]++;let Z=this._bucketOf[X]*2+(h[X]===Is?1:0),G=A.get(Z);G||A.set(Z,G=[]),G.push(X)}});let R=[];for(let F of[...A.keys()].sort((D,X)=>D-X))for(let D of tf(u,p,A.get(F),s.chunkVertices??Kd))R.push(rh(D,g));let L=[...R,...T.map(F=>F.members)].reduce((F,D)=>F+D.length,0);if(L>r)throw new Ar(L,r);let N=Math.max(1,Math.ceil(L/zi)),U=new Float32Array(zi*N*4);this._state=new Nn(new Uint8Array(zi*N*4),zi,N),this._state.colorSpace=Ae,this._state.onUpdate=()=>{this._fullPending=!1,this._pendingRanges=0},this._fullPending=!0,this._pendingRanges=0,this._dirty=new Uint32Array(lh),this._dirtyCount=0;let C=new Nn(U,zi,N,sn,Ge);C.needsUpdate=!0,C.onUpdate=()=>C.image.data=null,this.slotUniforms.slotInfo.value=C,this.slotUniforms.slotState.value=this._state,this._stateBytes=zi*N*20,this._slotOf=new Uint32Array(o).fill(Tr),this._slotInstance=new Uint32Array(L),this._slotUnit=new Uint32Array(L),this._slotRadius=new Float32Array(L),this._slotCost=new Float32Array(L),this._pixels=new Float32Array(L),this._planes=new Float64Array(24),this._detailView=new Float64Array(8),this._frameView=new Float64Array(8),this._frameViewAt=NaN,this._units=[],this._cut=[],this._detailCells=[],this._compactCells=[],this._detailIndices=new Uint16Array(ch),this._detailBins=new Float64Array(jc),this._detailBytes=0,this._unitScale=null,this._cutInView=0,this._cutFrame=-1,this._mergedBytes=0,this._instancedBytes=0,this._lineBytes=0;let B={matrices:n,geometryOf:e,mirrored:_,kind:h,origins:d,source:c,textured:!1};this._lineSources=new Map;let z=0;for(let F of R){let D=this._buckets[this._bucketOf[F[0]]];B.textured=D.texture!==null;let X=cf(F,B);for(let Z=0;ZF+D,0);let W=new Map;for(let{shape:F,members:D}of T){let X=D[0],Z=c(e[X]),G=W.get(F);if(!G){let Q=a.geometries[e[X]].bbox;G=this._shape(Z,_[X]===1,F.textured);let lt=tt=>Math.max(...tt.map(Math.abs)),ct=Math.max(lt(Z.min),lt(Z.max));G.pickExtent=ct,G.pickPadding=Math.max(0,...Z.min.map((tt,V)=>Q.min[V]-tt),...Z.max.map((tt,V)=>tt-Q.max[V]))+(Z.q?Ya*(lt(Z.q.o)+65535*Math.abs(Z.q.s)):0),W.set(F,G)}for(let Q=0;QF+D,0)}_shape(t,e,n){let s=t.vertices,r=t.q?new Uint16Array(s*4):new Float32Array(s*4);for(let h=0;hn+f),1,!1,Kn);a.setAttribute("slotBase",l),a.setIndex(s.index);let c=ff(this._boxes,e),h=new Oe(new I(c[0],c[1],c[2]),c[3]);a.boundingSphere=h;let d=new ps(a,t.material,0),u=new Float32Array(o*16),p=new Float32Array(o*12),g=0;for(let m=0;mthis._range(_,m,b,d),d.visible=!1,this.root.add(d),_}_chunk(t,e,n,s,r,o){let a=new xs;a.instanceCount=1,a.setAttribute("q",En(s.q,4)),a.setAttribute("normal",En(s.o,2,!0)),s.uv&&a.setAttribute("uv",En(s.uv,2)),a.setAttribute("slotBase",En(new Float32Array([n]),1,!1,Kn)),a.setIndex(En(s.index,1));let l=ff(this._boxes,e);a.boundingSphere=new Oe(new I(l[0],l[1],l[2]),l[3]),this._mergedBytes+=s.q.byteLength+s.o.byteLength+(s.uv?.byteLength??0)+s.index.byteLength;let c=new _e(a,t.material),h={bucket:t,mesh:c,lines:null,slotBase:n,n:e.length,sphere:l,shown:0,first:0,last:-1,end:0,dirty:!1,cell:!1,starts:s.indexStart,vertices:s.q.length/4,f32:s.q instanceof Float32Array,members:e.slice(),lastFrame:-1/0};return c.onBeforeRender=(d,u,p)=>this._range(h,d,p,c),c.visible=!1,this.root.add(c),h}_buildLines(){if(!this._lineSources)return;let{mirrored:t,geometryOf:e}=this._lineMembers;for(let n of this._units){if(n.cell){let h=n.mesh.geometry.index;n.lines=new ps(n.mesh.geometry,n.bucket.wire,0),n.lines.instanceMatrix=n.mesh.instanceMatrix,n.lines.boundingSphere=n.mesh.boundingSphere,n.lines.onBeforeRender=(d,u,p)=>this._range(n,d,p,n.lines),this._lineBytes+=h.count*2*h.array.BYTES_PER_ELEMENT,this.root.add(n.lines);continue}let s=n.starts[n.n],r=Wa(n.vertices,s*2),o=0,a=0;for(let h of n.members){let d=this._lineSources.get(e[h]),u=t[h]===1;for(let p=0;pthis._range(n,h,u,n.lines),this.root.add(n.lines),n.members=null}this._lineSources=null,this._lineMembers=null}_range(t,e,n,s){t.dirty&&this._span(t);let r=t.last+1;if(this._picking){if(t.cell&&this._pickFrustum){let o=this._state.image.data,a=t.pickPadding+this._pickViewPadding;for(;r>0;){let l=t.slotBase+r-1;if(o[l*4+3]&&!Rv(this._pickFrustum,this._boxes,this._slotInstance[l]*6,a))break;r--}}}else if(t.cell&&t.detailCount!==null)r=t.detailCount;else if(this._minPixels>0&&r>t.first){let o=e.info.render.frame;o!==this._frameViewAt&&(eh(n,this._viewHeight,this._frameView),this._frameViewAt=o);let a=this._frameView,l=df(a,t.sphere),c=a[7]?l>0?this._minPixels*l/a[6]:0:this._minPixels/a[6];r=Math.min(r,of(this._slotRadius,t.slotBase+t.first,t.slotBase+r,c)-t.slotBase)}if(t.cell)s.count=Math.max(r,0);else{let o=s.isLineSegments?2:1,[a,l]=af(t.starts,t.first,r);s.geometry.setDrawRange(a*o,l*o)}this._picking||(t.end=r,t.lastFrame=e.info.render.frame,this._cutFrame===null&&this._minPixels>0&&(this._cutFrame=t.lastFrame))}_span(t){let e=this._state.image.data,n=0;for(;n=n&&e[(t.slotBase+s)*4+3]===0;)s--;t.first=n0&&!e,t.lines&&(t.lines.visible=t.shown>0&&e)}_createBuckets(t,e,n){let s=new Map,r=[];for(let o=0;oMath.round(h*255)),opacity:c.opacity,texture:c.texture??null,material:ah(new _s({side:Ie}),this.slotUniforms,n),wire:ah(new _s({side:Ie,wireframe:!0}),this.slotUniforms,n)},this._applyOpacity(l),s.set(a,l),r.push(l)}this._bucketOf[o]=l.index}return r}_indexElements(){let t=new Uint32Array(this.elementCount+1);for(let s of this._elementOf)s>=0&&t[s+1]++;for(let s=0;s{s>=0&&(e[n[s]++]=r)}),this._elementStart=t,this._elementInstances=e}_texture(t){let e=this._textures.get(t);if(!e){let n=this._meta.textures[t],s=new Image;e=new ke(s),e.colorSpace=Ae,e.wrapS=e.wrapT=os,e.repeat.set(1/n.sx,1/n.sy),s.onload=()=>{e.needsUpdate=!0,this._changed("appearance")},s.src=`data:${n.mime};base64,${n.data}`,this._textures.set(t,e)}return e}_applyOpacity(t){let e=t.opacity*this._opacity,n=e<1;for(let s of[t.material,t.wire])s.transparent!==n&&(s.needsUpdate=!0),s.opacity=e,s.transparent=n,s.depthWrite=!n}_colorOf(t){return this._highlight[t]?yv:this._tint.get(t)??(this._mode==="white"?Mv:this._buckets[this._bucketOf[t]].bytes)}_applyColor(t){let e=this._slotOf[t];e!==Tr&&(this._state.image.data.set(this._colorOf(t),e*4),this._markDirty(e))}_setInstanceVisible(t,e){this._visible[t]=e?1:0,this._draw(t)}_setLayerFlag(t,e,n){t[e]!==(n?1:0)&&(t[e]=n?1:0,this._layerHides[e]+=n?1:-1,this._draw(e))}_shown(t){return this._visible[t]===1&&this._layerHides[t]===0}_draw(t){let e=this._slotOf[t];if(e===Tr)return;let n=this._shown(t)?255:0,s=this._state.image.data;if(s[e*4+3]===n)return;s[e*4+3]=n,this._markDirty(e);let r=this._units[this._slotUnit[e]];r.shown+=n?1:-1,r.dirty=!0,this._showUnit(r)}_markDirty(t){this._dirtyCountlh)e.clearUpdateRanges(),this._fullPending=!0;else{for(let n=0;n=this.elementCount)throw new RangeError(`Element index ${t} is out of range 0..${this.elementCount-1}.`)}_expandBox(t,e){if(!uf(this._boxes,e))return;let n=this._boxes,s=e*6;t.min.set(Math.min(t.min.x,n[s]),Math.min(t.min.y,n[s+1]),Math.min(t.min.z,n[s+2])),t.max.set(Math.max(t.max.x,n[s+3]),Math.max(t.max.y,n[s+4]),Math.max(t.max.z,n[s+5]))}_changed(t){this._flush(),this.root.dispatchEvent({type:"change",detail:{kind:t}})}};function hh(i,t,e){return e<=t?0:i.cell?(e-t)*i.triangles:(i.starts[e]-i.starts[t])/3}function df(i,t){return(t[0]-i[0])*i[3]+(t[1]-i[1])*i[4]+(t[2]-i[2])*i[5]-t[3]}function ff(i,t){let e=[1/0,1/0,1/0],n=[-1/0,-1/0,-1/0];for(let a of t)for(let l=0;l<3;l++)e[l]=Math.min(e[l],i[a*6+l]),n[l]=Math.max(n[l],i[a*6+3+l]);let s=(n[0]-e[0])/2,r=(n[1]-e[1])/2,o=(n[2]-e[2])/2;return Float64Array.of((e[0]+n[0])/2,(e[1]+n[1])/2,(e[2]+n[2])/2,Math.hypot(s,r,o),s,r,o)}var Pv={ru:{elements:"\u042D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432",noGeometry:"\u041D\u0435\u0442 \u0433\u0435\u043E\u043C\u0435\u0442\u0440\u0438\u0438",contextLost:"\u0412\u0438\u0434\u0435\u043E\u043A\u0430\u0440\u0442\u0430 \u0441\u0431\u0440\u043E\u0448\u0435\u043D\u0430 \u2014 \u043F\u0435\u0440\u0435\u0437\u0430\u0433\u0440\u0443\u0437\u0438\u0442\u0435 \u0441\u0442\u0440\u0430\u043D\u0438\u0446\u0443",noWebGL:"\u041D\u0443\u0436\u0435\u043D \u0431\u0440\u0430\u0443\u0437\u0435\u0440 \u0441 \u043F\u043E\u0434\u0434\u0435\u0440\u0436\u043A\u043E\u0439 WebGL 2",badData:"\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u043F\u0440\u043E\u0447\u0438\u0442\u0430\u0442\u044C \u0434\u0430\u043D\u043D\u044B\u0435 \u043C\u043E\u0434\u0435\u043B\u0438",tooLarge:"\u041C\u043E\u0434\u0435\u043B\u044C \u0441\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u0430\u044F \u0434\u043B\u044F \u044D\u0442\u043E\u0433\u043E \u043F\u0440\u043E\u0441\u043C\u043E\u0442\u0440\u0449\u0438\u043A\u0430: \u043E\u0431\u044A\u0435\u043A\u0442\u043E\u0432 \u0441 \u0433\u0435\u043E\u043C\u0435\u0442\u0440\u0438\u0435\u0439 \u2014 {count}, \u043F\u0440\u0435\u0434\u0435\u043B \u2014 {limit}",selected:"\u0412\u044B\u0431\u0440\u0430\u043D\u043E",close:"\u0417\u0430\u043A\u0440\u044B\u0442\u044C",elementGroup:"\u042D\u043B\u0435\u043C\u0435\u043D\u0442",id:"Id",category:"\u041A\u0430\u0442\u0435\u0433\u043E\u0440\u0438\u044F",type:"\u0422\u0438\u043F",level:"\u0423\u0440\u043E\u0432\u0435\u043D\u044C",sourceId:"ID \u0438\u0441\u0442\u043E\u0447\u043D\u0438\u043A\u0430",link:"\u0421\u0432\u044F\u0437\u0430\u043D\u043D\u044B\u0439 \u0444\u0430\u0439\u043B",panels:"\u041F\u0430\u043D\u0435\u043B\u0438","panel.model":"\u041C\u043E\u0434\u0435\u043B\u044C","panel.views":"\u0412\u0438\u0434\u044B","panel.sections":"\u0421\u0435\u0447\u0435\u043D\u0438\u044F","panel.clashes":"\u041A\u043E\u043B\u043B\u0438\u0437\u0438\u0438","panel.bcf":"\u0422\u0435\u043C\u044B BCF","bcf.noView":"\u041D\u0435\u0442 \u0434\u043E\u0441\u0442\u0443\u043F\u043D\u043E\u0433\u043E \u0432\u0438\u0434\u0430","bcf.viewpoint":"\u041E\u0442\u043A\u0440\u044B\u0442\u044C \u0432\u0438\u0434 {index}","bcf.components":"\u041D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D\u043E \u043A\u043E\u043C\u043F\u043E\u043D\u0435\u043D\u0442\u043E\u0432 \u2014 {missing}, \u043D\u0435\u043E\u0434\u043D\u043E\u0437\u043D\u0430\u0447\u043D\u044B\u0445 \u2014 {ambiguous}","panel.timeliner":"4D-\u0433\u0440\u0430\u0444\u0438\u043A","panel.links":"\u0421\u0432\u044F\u0437\u0430\u043D\u043D\u044B\u0435 \u0444\u0430\u0439\u043B\u044B","group.navigation":"\u041D\u0430\u0432\u0438\u0433\u0430\u0446\u0438\u044F","group.sections":"\u0421\u0435\u0447\u0435\u043D\u0438\u044F","group.measure":"\u0418\u0437\u043C\u0435\u0440\u0435\u043D\u0438\u044F","group.display":"\u041E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435","group.view":"\u0412\u0438\u0434","tool.orbit":"\u0412\u0440\u0430\u0449\u0435\u043D\u0438\u0435","tool.pan":"\u041F\u0430\u043D\u043E\u0440\u0430\u043C\u0430","tool.fit":"\u0412\u043F\u0438\u0441\u0430\u0442\u044C \u0432\u0441\u0451","tool.projection":"\u041F\u0435\u0440\u0441\u043F\u0435\u043A\u0442\u0438\u0432\u0430 / \u043E\u0440\u0442\u043E\u0433\u0440\u0430\u0444\u0438\u044F","tool.plane":"\u041F\u043B\u043E\u0441\u043A\u043E\u0441\u0442\u044C \u0441\u0435\u0447\u0435\u043D\u0438\u044F","tool.box":"\u0411\u043E\u043A\u0441 \u0441\u0435\u0447\u0435\u043D\u0438\u044F","tool.resetSections":"\u0421\u0431\u0440\u043E\u0441\u0438\u0442\u044C \u0441\u0435\u0447\u0435\u043D\u0438\u044F","tool.distance":"\u0420\u0430\u0441\u0441\u0442\u043E\u044F\u043D\u0438\u0435","tool.displayMode":"\u0420\u0435\u0436\u0438\u043C \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u044F","tool.grids":"\u041E\u0441\u0438","tool.opacity":"\u041F\u0440\u043E\u0437\u0440\u0430\u0447\u043D\u043E\u0441\u0442\u044C","tool.fullscreen":"\u041F\u043E\u043B\u043D\u044B\u0439 \u044D\u043A\u0440\u0430\u043D",contextMenu:"\u041A\u043E\u043D\u0442\u0435\u043A\u0441\u0442\u043D\u043E\u0435 \u043C\u0435\u043D\u044E","menu.properties":"\u0421\u0432\u043E\u0439\u0441\u0442\u0432\u0430","menu.hide":"\u0421\u043A\u0440\u044B\u0442\u044C","menu.isolate":"\u0418\u0437\u043E\u043B\u0438\u0440\u043E\u0432\u0430\u0442\u044C","menu.showAll":"\u041F\u043E\u043A\u0430\u0437\u0430\u0442\u044C \u0432\u0441\u0451","menu.zoomTo":"\u041F\u0440\u0438\u0431\u043B\u0438\u0437\u0438\u0442\u044C \u043A \u043E\u0431\u044A\u0435\u043A\u0442\u0443","menu.sectionBox":"\u0411\u043E\u043A\u0441 \u0441\u0435\u0447\u0435\u043D\u0438\u044F \u043F\u043E \u043E\u0431\u044A\u0435\u043A\u0442\u0443","menu.copyId":"\u041A\u043E\u043F\u0438\u0440\u043E\u0432\u0430\u0442\u044C Id","menu.fitAll":"\u0412\u043F\u0438\u0441\u0430\u0442\u044C \u0432\u0441\u0451","menu.resetSections":"\u0421\u0431\u0440\u043E\u0441\u0438\u0442\u044C \u0441\u0435\u0447\u0435\u043D\u0438\u044F","menu.unavailable":"\u041D\u0435\u0434\u043E\u0441\u0442\u0443\u043F\u043D\u043E \u0434\u043B\u044F \u044D\u0442\u043E\u0439 \u043C\u043E\u0434\u0435\u043B\u0438",searchPlaceholder:"\u041F\u043E\u0438\u0441\u043A \u043F\u043E \u0438\u043C\u0435\u043D\u0438, \u0442\u0438\u043F\u0443, Id\u2026",noCategory:"\u0411\u0435\u0437 \u043A\u0430\u0442\u0435\u0433\u043E\u0440\u0438\u0438",noMatches:"\u041D\u0438\u0447\u0435\u0433\u043E \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D\u043E","filters.title":"\u0424\u0438\u043B\u044C\u0442\u0440\u044B","filters.model":"\u041C\u043E\u0434\u0435\u043B\u044C-\u0438\u0441\u0442\u043E\u0447\u043D\u0438\u043A","filters.noLevel":"\u0411\u0435\u0437 \u0443\u0440\u043E\u0432\u043D\u044F","filters.all":"\u0412\u0441\u0435","filters.clear":"\u0421\u0431\u0440\u043E\u0441\u0438\u0442\u044C","filters.isolate":"\u0418\u0437\u043E\u043B\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0441\u043E\u0432\u043F\u0430\u0434\u0435\u043D\u0438\u044F",idCopied:"Id \u0441\u043A\u043E\u043F\u0438\u0440\u043E\u0432\u0430\u043D",copyFailed:"\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u0441\u043A\u043E\u043F\u0438\u0440\u043E\u0432\u0430\u0442\u044C Id",fullscreenUnavailable:"\u041F\u043E\u043B\u043D\u043E\u044D\u043A\u0440\u0430\u043D\u043D\u044B\u0439 \u0440\u0435\u0436\u0438\u043C \u043D\u0435\u0434\u043E\u0441\u0442\u0443\u043F\u0435\u043D","face.front":"\u0421\u043F\u0435\u0440\u0435\u0434\u0438","face.back":"\u0421\u0437\u0430\u0434\u0438","face.left":"\u0421\u043B\u0435\u0432\u0430","face.right":"\u0421\u043F\u0440\u0430\u0432\u0430","face.top":"\u0421\u0432\u0435\u0440\u0445\u0443","face.bottom":"\u0421\u043D\u0438\u0437\u0443","cube.title":"\u041A\u0443\u0431 \u0432\u0438\u0434\u0430","cube.up":"\u041F\u043E\u0432\u0435\u0440\u043D\u0443\u0442\u044C \u0432\u0432\u0435\u0440\u0445","cube.down":"\u041F\u043E\u0432\u0435\u0440\u043D\u0443\u0442\u044C \u0432\u043D\u0438\u0437","cube.left":"\u041F\u043E\u0432\u0435\u0440\u043D\u0443\u0442\u044C \u0432\u043B\u0435\u0432\u043E","cube.right":"\u041F\u043E\u0432\u0435\u0440\u043D\u0443\u0442\u044C \u0432\u043F\u0440\u0430\u0432\u043E","cube.home":"\u0418\u0441\u0445\u043E\u0434\u043D\u044B\u0439 \u0432\u0438\u0434","sections.mode":"\u0420\u0435\u0436\u0438\u043C \u0441\u0435\u0447\u0435\u043D\u0438\u044F","sections.planes":"\u041F\u043B\u043E\u0441\u043A\u043E\u0441\u0442\u0438","sections.box":"\u0411\u043E\u043A\u0441","sections.off":"\u0412\u044B\u043A\u043B","sections.axis":"\u041E\u0441\u044C","sections.addPlane":"\u0414\u043E\u0431\u0430\u0432\u0438\u0442\u044C \u043F\u043B\u043E\u0441\u043A\u043E\u0441\u0442\u044C","sections.noPlanes":"\u041F\u043B\u043E\u0441\u043A\u043E\u0441\u0442\u0435\u0439 \u043D\u0435\u0442","sections.rotated":"\u043F\u043E\u0432\u0451\u0440\u043D\u0443\u0442\u0430","sections.custom":"\u041F\u0440\u043E\u0438\u0437\u0432\u043E\u043B\u044C\u043D\u0430\u044F","sections.position":"\u041F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435 \u043F\u043B\u043E\u0441\u043A\u043E\u0441\u0442\u0438","sections.flip":"\u0421\u043C\u0435\u043D\u0438\u0442\u044C \u0441\u0442\u043E\u0440\u043E\u043D\u0443","sections.enabled":"\u0412\u043A\u043B","sections.delete":"\u0423\u0434\u0430\u043B\u0438\u0442\u044C \u043F\u043B\u043E\u0441\u043A\u043E\u0441\u0442\u044C","sections.keepInside":"\u041F\u043E\u043A\u0430\u0437\u0430\u0442\u044C \u0432\u043D\u0443\u0442\u0440\u0438","sections.cutInside":"\u0412\u044B\u0440\u0435\u0437\u0430\u0442\u044C \u0432\u043D\u0443\u0442\u0440\u0438","sections.fitSelection":"\u041F\u043E \u0432\u044B\u0434\u0435\u043B\u0435\u043D\u043D\u043E\u043C\u0443","sections.showGizmo":"\u041F\u043E\u043A\u0430\u0437\u044B\u0432\u0430\u0442\u044C \u043C\u0430\u043D\u0438\u043F\u0443\u043B\u044F\u0442\u043E\u0440","sections.boxYaw":"\u041F\u043E\u0432\u043E\u0440\u043E\u0442 \u0432\u043E\u043A\u0440\u0443\u0433 Z","sections.fill":"\u0417\u0430\u043B\u0438\u0432\u043A\u0430 \u0441\u0440\u0435\u0437\u043E\u0432","sections.fillUnavailable":"\u0417\u0430\u043B\u0438\u0432\u043A\u0430 \u043D\u0435\u0434\u043E\u0441\u0442\u0443\u043F\u043D\u0430 \u0431\u0435\u0437 \u0431\u0443\u0444\u0435\u0440\u0430 \u0442\u0440\u0430\u0444\u0430\u0440\u0435\u0442\u0430 WebGL","sections.maxPlanes":"\u041D\u0435 \u0431\u043E\u043B\u044C\u0448\u0435 6 \u043F\u043B\u043E\u0441\u043A\u043E\u0441\u0442\u0435\u0439","unit.m":"\u043C","display.materials":"\u041C\u0430\u0442\u0435\u0440\u0438\u0430\u043B\u044B","display.textures":"\u0422\u0435\u043A\u0441\u0442\u0443\u0440\u044B","display.white":"\u0411\u0435\u043B\u044B\u0439","display.wireframe":"\u041A\u0430\u0440\u043A\u0430\u0441","display.background":"\u0426\u0432\u0435\u0442 \u0444\u043E\u043D\u0430","display.backgroundReset":"\u0424\u043E\u043D \u043F\u043E \u0443\u043C\u043E\u043B\u0447\u0430\u043D\u0438\u044E","opacity.label":"\u041D\u0435\u043F\u0440\u043E\u0437\u0440\u0430\u0447\u043D\u043E\u0441\u0442\u044C","opacity.value":"{value} %","views.tour":"\u0422\u0443\u0440 \u043F\u043E \u0432\u0438\u0434\u0430\u043C","views.stop":"\u041E\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C \u0442\u0443\u0440","clash.New":"\u041D\u043E\u0432\u0430\u044F","clash.Active":"\u0410\u043A\u0442\u0438\u0432\u043D\u0430\u044F","clash.Reviewed":"\u041F\u0440\u043E\u0432\u0435\u0440\u0435\u043D\u0430","clash.Approved":"\u0423\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043D\u0430","clash.Resolved":"\u0423\u0441\u0442\u0440\u0430\u043D\u0435\u043D\u0430","task.construct":"\u0421\u0442\u0440\u043E\u0438\u0442\u0435\u043B\u044C\u0441\u0442\u0432\u043E","task.demolish":"\u0421\u043D\u043E\u0441","task.temporary":"\u0412\u0440\u0435\u043C\u0435\u043D\u043D\u043E\u0435","player.title":"4D-\u043F\u0440\u043E\u0438\u0433\u0440\u044B\u0432\u0430\u0442\u0435\u043B\u044C","player.play":"\u0412\u043E\u0441\u043F\u0440\u043E\u0438\u0437\u0432\u0435\u0441\u0442\u0438","player.pause":"\u041F\u0430\u0443\u0437\u0430","player.date":"\u0414\u0430\u0442\u0430 \u0433\u0440\u0430\u0444\u0438\u043A\u0430","player.speed":"\u0421\u043A\u043E\u0440\u043E\u0441\u0442\u044C",truncated:"\u041F\u043E\u043A\u0430\u0437\u0430\u043D\u043E {meshes} \u0438\u0437 {total} \u043C\u0435\u0448\u0435\u0439: \u043C\u043E\u0434\u0435\u043B\u044C \u043E\u0431\u0440\u0435\u0437\u0430\u043D\u0430 \u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u043E\u0439 MaxMeshVertices"},en:{elements:"Elements",noGeometry:"No geometry",contextLost:"The graphics context was lost \u2014 reload the page",noWebGL:"This page needs a browser with WebGL 2",badData:"The model data could not be read",tooLarge:"The model is too large for this viewer: {count} objects with geometry, the limit is {limit}",selected:"Selected",close:"Close",elementGroup:"Element",id:"Id",category:"Category",type:"Type",level:"Level",sourceId:"Source ID",link:"Link",panels:"Panels","panel.model":"Model","panel.views":"Views","panel.sections":"Sections","panel.clashes":"Clashes","panel.bcf":"BCF topics","bcf.noView":"No view available","bcf.viewpoint":"Open viewpoint {index}","bcf.components":"Components missing \u2014 {missing}, ambiguous \u2014 {ambiguous}","panel.timeliner":"4D schedule","panel.links":"Linked files","group.navigation":"Navigation","group.sections":"Sections","group.measure":"Measure","group.display":"Display","group.view":"View","tool.orbit":"Orbit","tool.pan":"Pan","tool.fit":"Fit all","tool.projection":"Perspective / orthographic","tool.plane":"Section plane","tool.box":"Section box","tool.resetSections":"Reset sections","tool.distance":"Distance","tool.displayMode":"Display mode","tool.grids":"Grids","tool.opacity":"Transparency","tool.fullscreen":"Full screen",contextMenu:"Context menu","menu.properties":"Properties","menu.hide":"Hide","menu.isolate":"Isolate","menu.showAll":"Show all","menu.zoomTo":"Zoom to object","menu.sectionBox":"Section box around object","menu.copyId":"Copy Id","menu.fitAll":"Fit all","menu.resetSections":"Reset sections","menu.unavailable":"Unavailable for this model",searchPlaceholder:"Search by name, type, Id\u2026",noCategory:"No category",noMatches:"No matches","filters.title":"Filters","filters.model":"Source model","filters.noLevel":"No level","filters.all":"All","filters.clear":"Clear","filters.isolate":"Isolate matches",idCopied:"Id copied",copyFailed:"Could not copy Id",fullscreenUnavailable:"Fullscreen is not available","face.front":"Front","face.back":"Back","face.left":"Left","face.right":"Right","face.top":"Top","face.bottom":"Bottom","cube.title":"View cube","cube.up":"Rotate up","cube.down":"Rotate down","cube.left":"Rotate left","cube.right":"Rotate right","cube.home":"Home view","sections.mode":"Section mode","sections.planes":"Planes","sections.box":"Box","sections.off":"Off","sections.axis":"Axis","sections.addPlane":"Add plane","sections.noPlanes":"No planes","sections.rotated":"rotated","sections.custom":"Custom","sections.position":"Plane position","sections.flip":"Flip side","sections.enabled":"On","sections.delete":"Delete plane","sections.keepInside":"Show inside","sections.cutInside":"Cut inside","sections.fitSelection":"Fit to selection","sections.showGizmo":"Show gizmo","sections.boxYaw":"Rotation around Z","sections.fill":"Fill cut faces","sections.fillUnavailable":"Section fill requires a WebGL stencil buffer","sections.maxPlanes":"At most 6 planes","unit.m":"m","display.materials":"Materials","display.textures":"Textures","display.white":"White","display.wireframe":"Wireframe","display.background":"Background color","display.backgroundReset":"Reset background","opacity.label":"Opacity","opacity.value":"{value}%","views.tour":"Play tour","views.stop":"Stop tour","clash.New":"New","clash.Active":"Active","clash.Reviewed":"Reviewed","clash.Approved":"Approved","clash.Resolved":"Resolved","task.construct":"Construct","task.demolish":"Demolish","task.temporary":"Temporary","player.title":"4D player","player.play":"Play","player.pause":"Pause","player.date":"Schedule date","player.speed":"Speed",truncated:"Showing {meshes} of {total} meshes: the model was truncated by the MaxMeshVertices setting"}},Ps=(globalThis.navigator?.language??"").toLowerCase().startsWith("ru")?"ru":"en",Cr=new Intl.NumberFormat(Ps).format;function st(i,t=Ps){let e=Pv[t][i];if(e===void 0)throw new Error(`Missing UI string '${i}'.`);return e}var pf=new I(0,0,1),$a=Math.PI/2-.01;function gf(i,t,e=4){return Math.hypot(t.x-i.x,t.y-i.y)<=e}function _f(i,t,e,n,s,r){let o=i.clone().sub(e),a=t.clone().sub(e),l=d=>(o.applyQuaternion(d),a.applyQuaternion(d));l(new Ce().setFromAxisAngle(pf,-n*r));let c=a.clone().sub(o).normalize(),h=c.clone().cross(pf);if(h.lengthSq()>1e-12){let d=Math.asin(de.clamp(c.z,-1,1)),u=de.clamp(s*r,d-$a,d+$a);l(new Ce().setFromAxisAngle(h.normalize(),-u))}return{position:o.add(e),target:a.add(e)}}function xf(i,t,e,n){let s=r=>r.clone().sub(e).multiplyScalar(n).add(e);return{position:s(i),target:s(t)}}var Lv=.85,Dv=100/3;function vf(i,t,e){let n=i*(t===1?Dv:t===2?e:1);return de.clamp(Lv**(-n/100),.5,2)}var dh=(i,t)=>t>=i?"window":"crossing";function yf(i,t,e){let n=mf(i.position,i.target),s=mf(t.position,t.target),r=n.azimuth??s.azimuth??0,o=s.azimuth??r,a=de.euclideanModulo(o-r+Math.PI,2*Math.PI)-Math.PI,l=(_,m)=>_+(m-_)*e,c=r+a*e,h=de.clamp(l(n.elevation,s.elevation),-$a,$a),d=l(n.distance,s.distance),u=i.target.clone().lerp(t.target,e),p=Math.cos(h)*d;return{position:u.clone().add(new I(p*Math.cos(c),p*Math.sin(c),Math.sin(h)*d)),target:u}}function Mf(i,t,e,n){let s=i.position.clone().sub(i.target),r=t.position.clone().sub(t.target),o=s.length(),a=r.length();s.normalize(),r.normalize();let l=new Ce().setFromUnitVectors(s,r),c=e.clone().applyQuaternion(l),h=new I().setFromMatrixColumn(new kt().lookAt(t.position,t.target,n),1),d=r.dot(new I().crossVectors(c,h)),u=Math.atan2(Math.abs(d)<1e-9?0:d,c.dot(h)),p=new Ce;return g=>{p.identity().slerp(l,g);let _=s.clone().applyQuaternion(p),m=i.target.clone().lerp(t.target,g),f=_.clone().multiplyScalar(de.lerp(o,a,g)).add(m),b=e.clone().applyQuaternion(p).applyAxisAngle(_,u*g);return{position:f,target:m,up:b}}}function mf(i,t){let e=i.clone().sub(t),n=e.length(),s=Math.hypot(e.x,e.y);return{distance:n,elevation:n>1e-12?Math.asin(de.clamp(e.z/n,-1,1)):0,azimuth:s>1e-9*Math.max(n,1e-12)?Math.atan2(e.y,e.x):null}}var Nv=.005,Uv=new I(1,-1,.8).normalize(),bf=.01,Sf=1.05,Fv=5e3,fh=(i,t)=>new CustomEvent(i,{detail:t});function wf({bbox:i,grids:t}){let e=r=>Array.isArray(r)&&r.length===3&&r.every(Number.isFinite);if(!e(i?.min)||!e(i?.max))return!0;let n=new ie(new I(...i.min),new I(...i.max));if(n.isEmpty())return!0;let s=new I;for(let r of t??[]){if(!e(r.start)||!e(r.end))return!0;n.expandByPoint(s.fromArray(r.start)),n.expandByPoint(s.fromArray(r.end))}return n.getSize(s).length()*Sf>bf*Fv}var Za=class extends EventTarget{constructor(t,e,{pick:n=()=>null,visibleBox:s=()=>new ie}={}){super(),this.dom=e,this.pick=n,this.visibleBox=s,this.target=new I,this.leftButtonMode="orbit",this._perspective=t,this._defaultFov=t.fov,this._orthographic=new Fn(-1,1,1,-1),this.camera=t,this._drag=null,this._wheelPick=null,this._animation=0,this._overlay=null,this._bounds=null,this._extraBounds=new Map,e.style.touchAction="none",e.addEventListener("pointerdown",r=>this._down(r)),e.addEventListener("pointermove",r=>this._move(r)),e.addEventListener("pointerup",r=>this._up(r)),e.addEventListener("pointercancel",()=>this._end()),e.addEventListener("lostpointercapture",r=>this._lostCapture(r)),window.addEventListener("blur",()=>this._end()),e.addEventListener("wheel",r=>this._wheel(r),{passive:!1}),e.addEventListener("contextmenu",r=>r.preventDefault())}setLeftButtonMode(t){if(t!=="orbit"&&t!=="pan")throw new RangeError(`Unknown left button mode: ${t}`);this.leftButtonMode=t}setProjection(t){if(t!=="perspective"&&t!=="orthographic")throw new RangeError(`Unknown projection: ${t}`);let e=t==="perspective"?this._perspective:this._orthographic,n=this.camera;if(e!==n){this._stopAnimation(),e.position.copy(n.position),n.isOrthographicCamera&&e.position.sub(this.target).divideScalar(n.zoom).add(this.target),e.zoom=1,e.quaternion.copy(n.quaternion),e.up.copy(n.up),n.parent?.add(e),n.parent?.remove(n);for(let s of[...n.children])e.add(s);this.camera=e,this.resize()}}resize(){let t=this.camera,e=this.dom.clientWidth/Math.max(this.dom.clientHeight,1),n=Math.max(t.position.distanceTo(this.target),1e-6);if(t.isPerspectiveCamera)t.aspect=e;else{let r=n*Math.tan(de.degToRad(this._perspective.fov/2));Object.assign(t,{top:r,bottom:-r,left:-r*e,right:r*e})}let s=this._rangeSphere();if(s){let r=s.center.clone().sub(t.position),o=new I(0,0,-1).applyQuaternion(t.quaternion);t.far=Math.max(1e-6,(r.length()+s.radius)*Sf);let a=r.dot(o)-s.radius;t.near=Math.max(a*.95,Math.min(bf,t.far/2))}t.updateProjectionMatrix(),this.dispatchEvent(new Event("change"))}setExtraBounds(t,e){e&&!e.isEmpty()?this._extraBounds.set(t,e.clone()):this._extraBounds.delete(t),this.resize()}_rangeSphere(){let t=this._visibleBounds()?.sphere??null;if(this._extraBounds.size===0)return t;let e=t?this._bounds.box.clone():new ie;for(let n of this._extraBounds.values())e.union(n);return e.getBoundingSphere(new Oe)}invalidateBounds(){this._bounds=null}_visibleBounds(){if(!this._bounds){let t=this.visibleBox();this._bounds={box:t,sphere:t.isEmpty()?null:t.getBoundingSphere(new Oe)}}return this._bounds.sphere&&this._bounds}fitBox(t,e=!0){if(t.isEmpty())return;let n=t.getBoundingSphere(new Oe),s=Math.max(n.radius,.001),r=de.degToRad(this._perspective.fov/2),o=this.dom.clientWidth/Math.max(this.dom.clientHeight,1),a=s/Math.sin(Math.min(r,Math.atan(Math.tan(r)*o))),l=this.camera.position.clone().sub(this.target);l.lengthSq()<1e-12&&l.copy(Uv);let c=l.normalize().multiplyScalar(a).add(n.center);e?this.animateTo({position:c,target:n.center}):(this.camera.zoom=1,this._set(c,n.center))}zoomToBox(t){this.fitBox(t,!0)}resetCameraStyle(){this._perspective.fov=this._defaultFov,this.camera.up.set(0,0,1)}restoreViewCamera({position:t,target:e,up:n,fov:s,orthographicHeight:r}){let o=new I(...t),a=new I(...e);if(this.resetCameraStyle(),!n){this.animateTo({position:o,target:a});return}this._stopAnimation(),this.camera.up.fromArray(n),this._perspective.fov=s??this._defaultFov;let l=Math.max(o.distanceTo(a),1e-6);this.camera.zoom=r==null?1:2*l*Math.tan(de.degToRad(this._perspective.fov/2))/r,this._set(o,a)}animateTo({position:t,target:e,zoom:n=1,overPole:s=!1},r=400){this._stopAnimation();let o={position:this.camera.position.clone(),target:this.target.clone()},a={position:t??o.position,target:e??o.target},l=this.camera.zoom,c=s?Mf(o,a,new I(0,1,0).applyQuaternion(this.camera.quaternion),this.camera.up):u=>yf(o,a,u),h=performance.now(),d=u=>{let p=Math.min((u-h)/r,1),g=p*p*(3-2*p),_=c(g);this.camera.isOrthographicCamera&&(this.camera.zoom=de.lerp(l,n,g)),this._set(_.position,_.target,_.up),this._animation=p<1?requestAnimationFrame(d):0};this._animation=requestAnimationFrame(d)}get animating(){return this._animation!==0}_stopAnimation(){cancelAnimationFrame(this._animation),this._animation=0}_set(t,e,n){if(this.camera.position.copy(t),this.target.copy(e),n){let s=this.camera.up.clone();this.camera.up.copy(n),this.camera.lookAt(e),this.camera.up.copy(s)}else this.camera.lookAt(e);this.resize()}_down(t){this._end(),this._stopAnimation(),this.dom.setPointerCapture(t.pointerId),t.preventDefault();let e=t.button===0&&t.shiftKey?"box":t.button===0&&this.leftButtonMode==="orbit"?"orbit":"pan",n={x:t.clientX,y:t.clientY},s=null;e==="orbit"&&(s=this.pick(n.x,n.y),s||(s=this._visibleBounds()?.sphere.center.clone()??this.target.clone())),this._drag={id:t.pointerId,button:t.button,mode:e,pivot:s,down:n,last:n,moved:!1}}_move(t){let e=this._drag;if(!e||t.pointerId!==e.id)return;if(t.buttons===0)return this._end();let n={x:t.clientX,y:t.clientY};if(!e.moved&&gf(e.down,n))return;e.moved=!0;let s=n.x-e.last.x,r=n.y-e.last.y;if(e.last=n,e.mode==="box")this._drawRect(e.down,n);else if(e.mode==="orbit"){let o=_f(this.camera.position,this.target,e.pivot,s,r,Nv);this._set(o.position,o.target)}else this._pan(s,r)}_pan(t,e){let n=this.camera,s=Math.max(this.dom.clientHeight,1),r=n.isPerspectiveCamera?2*n.position.distanceTo(this.target)*Math.tan(de.degToRad(n.fov/2))/s:(n.top-n.bottom)/n.zoom/s,o=new I(1,0,0).applyQuaternion(n.quaternion),a=new I(0,1,0).applyQuaternion(n.quaternion),l=o.multiplyScalar(-t*r).addScaledVector(a,e*r);this._set(n.position.clone().add(l),this.target.clone().add(l))}_up(t){let e=this._drag;if(!e||t.pointerId!==e.id||t.button!==e.button)return;let n={x:t.clientX,y:t.clientY};if(this._end(),e.mode==="box"&&e.moved){let s={x:Math.min(e.down.x,n.x),y:Math.min(e.down.y,n.y),width:Math.abs(n.x-e.down.x),height:Math.abs(n.y-e.down.y)},r=dh(e.down.x,n.x);this.dispatchEvent(fh("boxselect",{rect:s,mode:r,ctrl:t.ctrlKey,shift:t.shiftKey}))}else!e.moved&&e.button===0?this.dispatchEvent(fh("click",{x:n.x,y:n.y,button:0,ctrl:t.ctrlKey,shift:t.shiftKey})):!e.moved&&e.button===2&&this.dispatchEvent(fh("contextmenu",{x:n.x,y:n.y}))}_lostCapture(t){this._drag&&t.buttons?this.dom.setPointerCapture(this._drag.id):this._end()}_end(){this._drag=null,this._overlay?.remove(),this._overlay=null}_drawRect(t,e){this._overlay||(this._overlay=document.createElement("div"),Object.assign(this._overlay.style,{position:"fixed",pointerEvents:"none",border:"1px solid #2563eb",background:"rgba(37,99,235,0.12)"}),(this.dom.parentElement??document.body).appendChild(this._overlay)),Object.assign(this._overlay.style,{borderStyle:dh(t.x,e.x)==="window"?"solid":"dashed",left:`${Math.min(t.x,e.x)}px`,top:`${Math.min(t.y,e.y)}px`,width:`${Math.abs(e.x-t.x)}px`,height:`${Math.abs(e.y-t.y)}px`})}_wheel(t){if(t.preventDefault(),t.deltaY===0)return;this._stopAnimation();let e=vf(t.deltaY,t.deltaMode,this.dom.clientHeight),n=this.camera;if(n.isOrthographicCamera){let{left:o,top:a,width:l,height:c}=this.dom.getBoundingClientRect();if(!l||!c)return;let h=de.clamp(n.zoom/e,1e-6,1e6),d=new I((2*(t.clientX-o)/l-1)*n.right,(1-2*(t.clientY-a)/c)*n.top,0).multiplyScalar(1/n.zoom-1/h).applyQuaternion(n.quaternion);n.zoom=h,this._set(n.position.clone().add(d),this.target.clone().add(d));return}this._wheelPick||(this._wheelPick={point:this.pick(t.clientX,t.clientY)},requestAnimationFrame(()=>this._wheelPick=null));let s=this._wheelPick.point??this.target,r=xf(n.position,this.target,s,e);this._set(r.position,r.target)}};function et(i,t,e){let n=document.createElement(i);return t&&(n.className=t),e!==void 0&&(n.textContent=e),n}function Ke(i,t,e){let n=et("button",i);return n.type="button",n.innerHTML=t,n.title=e,n.setAttribute("aria-label",e),n}function Ls(i){i.preventDefault(),i.stopPropagation()}function Ja(i){Ls(i);let t=i.button===2,e=()=>{window.removeEventListener("pointerup",n,!0),setTimeout(()=>{window.removeEventListener("click",Ls,!0),t&&window.removeEventListener("contextmenu",Ls,!0)})},n=s=>{Ls(s),e()};window.addEventListener("pointerup",n,!0),window.addEventListener("click",Ls,!0),t&&window.addEventListener("contextmenu",Ls,!0)}function Ir(i,t,e,n){let s=t.clone().applyMatrix4(e.matrixWorldInverse).z<0,r=t.clone().project(e);i.hidden=!(s&&Math.abs(r.x)<=1&&Math.abs(r.y)<=1),!i.hidden&&(i.style.left=`${n.left+(r.x+1)/2*n.width}px`,i.style.top=`${n.top+(1-r.y)/2*n.height}px`)}var fe=i=>``,Ef='',Zt={model:fe(''),views:fe(''),sections:fe(''),clashes:fe(''),bcf:fe(''),timeliner:fe(''),links:fe(''),orbit:fe(''),pan:fe(''),fit:fe(''),projection:fe(Ef),plane:fe(''),box:fe(`${Ef}`),resetSections:fe(''),distance:fe(''),displayMode:fe(''),grids:fe(''),opacity:fe(''),fullscreen:fe(''),close:fe(''),chevron:fe(''),flip:fe(''),remove:fe(''),play:fe(''),pause:fe(''),home:fe('')};var Pr=new I(0,0,1),cn={right:new I(1,0,0),left:new I(-1,0,0),back:new I(0,1,0),front:new I(0,-1,0),top:new I(0,0,1),bottom:new I(0,0,-1)},Bv={right:Pr,left:Pr,back:Pr,front:Pr,top:cn.back,bottom:cn.front},ki=.7,Ov=de.degToRad(1),Tf=.01,Af=96,Ka=1.75;function Rf(i){let t=i.split("-"),e=new I;for(let n of t){if(!Object.hasOwn(cn,n))throw new RangeError(`Unknown view cube region: ${i}`);e.add(cn[n])}if(new Set(t).size!==t.length||e.lengthSq()!==t.length)throw new RangeError(`Unknown view cube region: ${i}`);return e.normalize()}function zv(i){let t=[];return Math.abs(i.z)>=ki&&t.push(i.z>0?"top":"bottom"),Math.abs(i.y)>=ki&&t.push(i.y>0?"back":"front"),Math.abs(i.x)>=ki&&t.push(i.x>0?"right":"left"),t.join("-")}function ph(i,t=Ov){let e=i.clone().normalize(),n=Math.cos(t);return Object.keys(cn).find(s=>e.dot(cn[s])>=n)??null}function Cf(i){let t=new I(i.x,i.y,0);if(t.lengthSq()<1e-24)return"front";t.normalize();let e=["front","right","back","left"],n=Math.max(...e.map(s=>t.dot(cn[s])));return e.find(s=>t.dot(cn[s])>=n-1e-9)}function mh(i,t){return cn[Cf(t)].clone().multiplyScalar(Math.sin(Tf)).addScaledVector(cn[i],Math.cos(Tf))}function kv(i,t){let e=ph(i);if(!e)return null;let n=e==="top"||e==="bottom";if(t==="left"||t==="right")return(n?mh(e,i):Rf(e)).applyAxisAngle(Pr,t==="right"?Math.PI/2:-Math.PI/2);if(t!=="up"&&t!=="down")throw new RangeError(`Unknown arrow: ${t}`);if(!n)return mh(t==="up"?"top":"bottom",i);let s=cn[Cf(i)];return t==="up"==(e==="top")?s.clone().negate():s.clone()}function Hv(i,t){let e=document.createElement("canvas");e.width=e.height=128;let n=e.getContext("2d");n.fillStyle="#2a2f38",n.fillRect(0,0,128,128),n.fillStyle="#cbd5e1",n.textAlign="center",n.textBaseline="middle",n.font=`600 26px ${t}`;let s=n.measureText(i).width;s>112&&(n.font=`600 ${Math.floor(2912/s)}px ${t}`),n.fillText(i,64,64);let r=new Qs(e);return r.colorSpace=Ae,r}var ja=class{constructor(t,e,n){this.controls=n,this.home={position:e.position.clone(),target:n.target.clone()},this.element=et("div","ioviewer-viewcube"),this.canvas=et("canvas","ioviewer-viewcube-canvas"),this.canvas.title=st("cube.title"),this.canvas.setAttribute("aria-label",st("cube.title")),this.element.append(this.canvas),this.error=null,this.renderer=this._createRenderer(),this.scene=new Ai,this.camera=new Fn(-Ka,Ka,Ka,-Ka,.1,10),this.faces=new Re;let s=getComputedStyle(t).fontFamily;for(let[l,c]of Object.entries(cn)){let h=st(`face.${l}`),d=new _e(new yn(2,2),new en({map:Hv(h,s)})),u=Bv[l];d.quaternion.setFromRotationMatrix(new kt().makeBasis(u.clone().cross(c),u,c)),d.position.copy(c),d.name=l,d.userData.label=h,this.faces.add(d)}let r=new vn(new Li(new dn(2,2,2)),new an({color:"#5b6575"}));this.highlight=new _e(new dn(1,1,1),new en({color:"#2563eb",transparent:!0,opacity:.6})),this.highlight.visible=!1,this.scene.add(this.faces,r,this.highlight),this._raycaster=new Di,this.hovered=null,this._pointer=null,this.element.addEventListener("contextmenu",l=>l.preventDefault());let o=l=>{this._pointer=[l.clientX,l.clientY],this._hover(this.regionAtClient(...this._pointer))&&this._render()};this.canvas.addEventListener("pointerenter",o),this.canvas.addEventListener("pointermove",o),this.canvas.addEventListener("pointerleave",()=>{this._pointer=null,this._hover(null)&&this._render()}),this.canvas.addEventListener("click",l=>{let c=this.regionAtClient(l.clientX,l.clientY);if(!c)return;let h=c==="top"||c==="bottom";this._look(h?mh(c,n.camera.position.clone().sub(n.target)):Rf(c))}),this.arrows=["up","down","left","right"].map(l=>{let c=Ke("ioviewer-viewcube-arrow",Zt.chevron,st(`cube.${l}`));return c.dataset.arrow=l,c.addEventListener("click",h=>{h.detail&&c.blur(),this._arrow(l)}),c});let a=Ke("ioviewer-viewcube-home",Zt.home,st("cube.home"));a.addEventListener("click",l=>{l.detail&&a.blur(),n.resetCameraStyle(),n.animateTo({position:this.home.position.clone(),target:this.home.target.clone()})}),this.element.append(...this.arrows,a),t.append(this.element),this.update()}_createRenderer(){this.canvas.addEventListener("webglcontextlost",e=>{e.stopImmediatePropagation(),this._fail(new Error("The view cube lost its WebGL context."))});let t=this.canvas.getContext("webgl2",{alpha:!0,antialias:!0});if(!t)return this._fail(new Error("WebGL 2 is not available for the view cube."));try{let e=new As({canvas:this.canvas,context:t,alpha:!0,antialias:!0});return e.setPixelRatio(window.devicePixelRatio),e.setSize(Af,Af),e}catch(e){return this._fail(e)}}_fail(t){return this.error=t,this.renderer=null,this.element.hidden=!0,null}_render(){if(this.renderer)try{this.renderer.render(this.scene,this.camera)}catch(t){this._fail(t)}}update(){if(!this.renderer)return;let t=this.controls.camera,e=!this.camera.quaternion.equals(t.quaternion);this.camera.quaternion.copy(t.quaternion),this.camera.position.set(0,0,5).applyQuaternion(t.quaternion),this.camera.updateMatrixWorld();let n=ph(t.position.clone().sub(this.controls.target))!==null;for(let s of this.arrows)s.hidden=!n;e&&this._pointer&&this._hover(this.regionAtClient(...this._pointer)),this._render()}regionAtClient(t,e){let n=this.canvas.getBoundingClientRect(),s=new Ht((t-n.left)/n.width*2-1,1-(e-n.top)/n.height*2);this._raycaster.setFromCamera(s,this.camera);let r=this._raycaster.intersectObjects(this.faces.children)[0];return r?zv(r.point):null}_hover(t){if(t===this.hovered)return!1;if(this.hovered=t,this.highlight.visible=!!t,t){let e=t.split("-").reduce((a,l)=>a.add(cn[l]),new I),n=a=>a===0?[-ki,ki]:a>0?[ki,1.02]:[-1.02,-ki],[s,r,o]=e.toArray().map(n);this.highlight.scale.set(s[1]-s[0],r[1]-r[0],o[1]-o[0]),this.highlight.position.set((s[0]+s[1])/2,(r[0]+r[1])/2,(o[0]+o[1])/2)}return!0}_arrow(t){let n=this.controls.camera.position.clone().sub(this.controls.target),s=kv(n,t);if(!s)return;let r=ph(n),o=r==="top"&&t==="up"||r==="bottom"&&t==="down";this._look(s,o)}_look(t,e=!1){let{controls:n}=this,s=n.camera.position.distanceTo(n.target);n.animateTo({position:t.clone().multiplyScalar(s).add(n.target),target:n.target.clone(),zoom:n.camera.zoom,overPole:e})}};var Vv=` +#endif`;function vi(i,t,e){let n=i.indexOf(t);if(n<0||i.indexOf(t,n+1)>=0)throw new Error(`The shader must contain '${t}' exactly once.`);return i.slice(0,n)+e+i.slice(n+t.length)}function Sv(i){Object.assign(i.uniforms,this.userData.slotUniforms);let t=vi(i.vertexShader,"#include ",`#include +${wr}`);t=vi(t,"#include ",`${Er} +vTint = state.rgb;`),t=vi(t,"#include ","vec3 objectNormal = ioOct( normal.xy );"),t=vi(t,"#include ",bv),t=vi(t,"#include ","vec3 transformed = slotPosition;"),t=vi(t,"#include ",`#include +${oh}`),i.vertexShader=t;let e=vi(i.fragmentShader,"#include ",`#include +varying vec3 vTint;`);e=vi(e,"#include ","diffuseColor.rgb *= vTint;"),i.fragmentShader=e}function ah(i,t,e=!1){return i.userData.slotUniforms=t,i.onBeforeCompile=Sv,i.index0AttributeName="q",e&&(i.defines={IO_NO_HIDE_BRANCH:""}),i}var uh=["materials","textures","white","wireframe"],wv=[245,158,11],Ev=[235,235,237],Tr=4294967295,zi=2048,lh=256,Tv=16,ch=1024,Av=.1,Rv=8192,Cv=1.4,Ya=2**-20,qa=17;function Iv(i,t){let[e,n,s,r,o,a,l,c,h]=i.subarray(t*12,t*12+9);return e*(o*h-a*c)-r*(n*h-s*c)+l*(n*a-s*o)<0}function Pv(){this.array=null}function En(i,t,e=!1,n=Se){return new n(i,t,e).onUpload(Pv)}var Ar=class extends RangeError{constructor(t,e){super(`${t} drawable instances exceed the limit of ${e}.`),this.name="ModelTooLargeError",this.count=t,this.limit=e}},ff=(i,t)=>{for(let e=t*6;e=0?3:0)]+o*t[e+(o>=0?4:1)]+a*t[e+(a>=0?5:2)]+l<-(n+Ya*Math.abs(l)))return!0}return!1}function Dv(i,t,{min:e,max:n},s){let r=t*12,o=t*6;if(e[0]>n[0]||e[1]>n[1]||e[2]>n[2]){s.set(e,o),s.set(n,o+3);return}for(let a=0;a<3;a++){let l=i[r+a],c=i[r+a+3],h=i[r+a+6],d=i[r+a+9],u=l*e[0],p=l*n[0],g=c*e[1],_=c*n[1],m=h*e[2],f=h*n[2];s[o+a]=Math.min(u,p)+Math.min(g,_)+Math.min(m,f)+d,s[o+a+3]=Math.max(u,p)+Math.max(g,_)+Math.max(m,f)+d}}var Nv=i=>{let t=i.getHex(Ae);return[t>>16&255,t>>8&255,t&255]},Rr=class{constructor(t,e={}){let{meta:n}=t,s=n.instances,r=s.count,o=t.view(s.geometry),a=t.view(s.material),l=t.view(s.matrix);this.root=new Re,this.elementCount=n.elements.length,this._elements=n.elements,this._meta=n,this._mode="materials",this._opacity=1,this._picking=!1,this._pickBounds=!0,this._instanceDetail=!0,this._pickFrustum=null,this._textures=new Map,this._elementOf=t.view(s.element).slice(),this._bucketOf=new Uint32Array(r),this._visible=new Uint8Array(r).fill(1),this._layers=new Map,this._layerHides=new Uint8Array(r),this._highlight=new Uint8Array(r),this._highlighted=[],this._tint=new Map,this._boxes=new Float32Array(r*6),this._minPixels=0,this._viewHeight=1,this.visibleCost=0;let c=!!e.noHideBranch;this.slotUniforms={slotInfo:{value:null},slotState:{value:null}},this._buckets=this._createBuckets(n,a,c),this._indexElements();for(let d=0;dthis._shown(e)?1:0)}instancesOf(t){return this._checkElement(t),this._elementInstances.subarray(this._elementStart[t],this._elementStart[t+1])}isVisible(t){this._checkElement(t);for(let e=this._elementStart[t];ethis._chunkCount){this._pickFrustum=Qc(n,this._planes);let{x:r,y:o,z:a}=n.position;this._pickViewPadding=Ya*(Math.abs(r)+Math.abs(o)+Math.abs(a))}for(let r of this._units)r.mesh.material=t,s?(r.mesh.visible=(r.mesh.visible||!!r.lines?.visible)&&r.bucket.material.opacity>0,r.lines&&(r.lines.visible=!1)):this._showUnit(r);if(!s)for(let r of this._compactCells)this._cellAttributes(r,!1);try{return e()}finally{this._picking=!1,this._pickFrustum=null;for(let r of this._units)r.mesh.material=r.bucket.material,this._showUnit(r);for(let r of this._cut)r.mesh.visible=!1,r.lines&&(r.lines.visible=!1);if(!s)for(let r of this._compactCells)this._cellAttributes(r,!0)}}elementBox(t,e=new ie){this._checkElement(t),e.makeEmpty();for(let n=this._elementStart[t];n=0&&t<=1))throw new RangeError(`Opacity must be within 0..1, got ${t}.`);this._opacity=t;for(let e of this._buckets)this._applyOpacity(e);this._changed("appearance")}get opacity(){return this._opacity}setDetail(t,e=1){this._minPixels=t,this._viewHeight=e;for(let s of this._cut)this._showUnit(s);this._cut.length=0;for(let s of this._detailCells)s.detailCount=null;this._detailCells.length=0;for(let s of this._compactCells)this._cellAttributes(s,!1);this._compactCells.length=0;let n=this._unitScale;this._unitScale=null,!(!(t>0)||!n)&&(this._cutInView=0,this._cutFrame=null,this._units.forEach((s,r)=>{if(!(!(n[r]>=0)||s.shown===0)){if(s.dirty&&this._span(s),s.cell&&this._detailUsesInstances){if(s.detailHigh>=t&&this._detailCell(s,t))return}else if(this._slotRadius[s.slotBase+s.first]*n[r]>=t)return;s.mesh.visible=!1,s.lines&&(s.lines.visible=!1),this._cut.push(s),this._cutInView+=hh(s,s.first,s.last+1)}}))}_detailCell(t,e){if(t.detailLow>=e)return t.detailCount=Math.min(t.detailEnd,t.last+1),this._detailCells.push(t),!0;let{slotBase:n,last:s}=t,r=this._detailIndices,o=0,a=!1,l=!1;for(let u=0;u<=s;u++){let p=this._pixels[n+u];p<0||(pc.count;for(let u=0;u0?o[6]/m:1/0:o[6];d[p]=f;let b=g.cell&&this._detailUsesInstances,E=b&&!Yd(r,_[0],_[1],_[2],_[3]+g.pickPadding),M=g.slotBase+g.n,v=-1;if(b){let R=this._slotRadius[g.slotBase],L=this._slotRadius[M-1],N=m+_[3],U=Math.abs(o[3])*_[4]+Math.abs(o[4])*_[5]+Math.abs(o[5])*_[6],C=N-U-R,B=N+U-L,z=Math.fround(o[7]?C>0?R*o[6]/C:1/0:R*f),W=Math.fround(o[7]?B>0?L*o[6]/B:1/0:L*f);Is(W)===Is(z)&&(v=z)}if(v>=0&&!E){g.detailLow=g.detailHigh=v,g.detailEnd=g.n;let R=this._slotCost[g.slotBase]*g.shown;l[Is(v)]+=R,u+=R;continue}let S=0,A=1/0,x=-1,T=0;for(let R=g.slotBase;R=0){S++;continue}let D=(z-o[0])*o[3]+(W-o[1])*o[4]+(F-o[2])*o[5]-L;N=o[7]?D>0?o[6]/D:1/0:o[6]}let U=N===1/0?1/0:Math.fround(L*N);b&&(a[R]=U,A=Math.min(A,U),x=Math.max(x,U));let C=this._slotCost[R];l[Is(U)]+=C,u+=C}if(b){if(S){A=x=v;let R=S*this._slotCost[g.slotBase];l[Is(v)]+=R,u+=R}g.detailLow=A,g.detailHigh=x,g.detailEnd=T}}return this.visibleCost=u,$d(l,u,n)}drawStats(){let t=-1/0;for(let r of this._units)t=Math.max(t,r.lastFrame);let e=0,n=this._cutFrame===t?this._cutInView:0,s=0;for(let r of this._units)r.lastFrame===t&&(n+=hh(r,r.first,Math.max(r.last+1,r.first)),e+=hh(r,r.first,Math.max(r.end,r.first)),s++);return{drawn:e,inView:n,draws:s}}drawnInstances(t){t.updateMatrixWorld();let e=new Un().setFromProjectionMatrix(new kt().multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse)),n={info:{render:{frame:-1}}},s=new Oe,r=[];for(let o of this._units){let a=this._mode==="wireframe"&&!this._picking?o.lines:o.mesh;if(!(!a?.visible||!e.intersectsSphere(s.set(s.center.fromArray(o.sphere),o.sphere[3])))){a.onBeforeRender(n,null,t,a.geometry,a.material,null);for(let l=o.first;lo-a)}memory(){let t=this._units[this._chunkCount]?.slotBase??this._slotInstance.length;return{gpuBytes:this._mergedBytes+this._instancedBytes+this._lineBytes+this._stateBytes+this._detailBytes,mergedBytes:this._mergedBytes,instancedBytes:this._instancedBytes,stateBytes:this._stateBytes,lineBytes:this._lineBytes,detailBytes:this._detailBytes,detailSourceBytes:(this._slotInstance.length-t)*48,chunks:this._chunkCount,cells:this._units.length-this._chunkCount,mergedInstances:t,instancedInstances:this._slotInstance.length-t,triangles:this._triangles}}setClipping(t,e){for(let n of this._buckets)for(let s of[n.material,n.wire])s.clippingPlanes=t.length>0?t:null,s.clipIntersection=e,s.needsUpdate=!0;this._changed("clipping")}_build(t,e,n,s,r){let o=e.length,a=this._meta,l=new Map,c=F=>{let D=l.get(F);if(!D){let X=a.geometries[F],Z=t.view(X.indices),G=X.uvs?t.view(X.uvs):null;D=df(Sr(t,X),X.q??null,jd(t,X),Z,G),D.drawable=D.indices.length>=3&&D.min.every(Number.isFinite)&&D.max.every(Number.isFinite),l.set(F,D)}return D},h=new Uint8Array(o),d=new Float64Array(o*3),u=new Float32Array(o*3),p=new Uint32Array(o),g=new Float32Array(o),_=new Uint8Array(o),m=new Map,f=this._boxes;for(let F=0;FF-D).map(F=>{let D=m.get(F),X=c(e[D[0]]),Z=this._buckets[this._bucketOf[D[0]]].texture!==null,G=[0,1,2].every(lt=>(X.max[lt]-X.min[lt])/wn<=65535),Q=X.vertices*((G?12:20)+(Z?8:0))+X.indices.length*(X.vertices>65535?4:2);return{k:D.length,bytes:Q,members:D,textured:Z}}),M=s.mergedCap??sh,v=s.minRepeats??Tv;if(E.reduce((F,D)=>F+D.k*D.bytes,0)>M){let F=s.cellExtent==null?of(f,p)*Av:this.visibleBox().getSize(new I).length()*s.cellExtent;for(let D of E)D.k{if(S[D]){for(let X of F.leaves)T.push({shape:F,members:rh(X,g)});return}for(let X of F.members){x[e[X]]++;let Z=this._bucketOf[X]*2+(h[X]===Ps?1:0),G=A.get(Z);G||A.set(Z,G=[]),G.push(X)}});let R=[];for(let F of[...A.keys()].sort((D,X)=>D-X))for(let D of nf(u,p,A.get(F),s.chunkVertices??Qd))R.push(rh(D,g));let L=[...R,...T.map(F=>F.members)].reduce((F,D)=>F+D.length,0);if(L>r)throw new Ar(L,r);let N=Math.max(1,Math.ceil(L/zi)),U=new Float32Array(zi*N*4);this._state=new Nn(new Uint8Array(zi*N*4),zi,N),this._state.colorSpace=Ae,this._state.onUpdate=()=>{this._fullPending=!1,this._pendingRanges=0},this._fullPending=!0,this._pendingRanges=0,this._dirty=new Uint32Array(lh),this._dirtyCount=0;let C=new Nn(U,zi,N,sn,Ge);C.needsUpdate=!0,C.onUpdate=()=>C.image.data=null,this.slotUniforms.slotInfo.value=C,this.slotUniforms.slotState.value=this._state,this._stateBytes=zi*N*20,this._slotOf=new Uint32Array(o).fill(Tr),this._slotInstance=new Uint32Array(L),this._slotUnit=new Uint32Array(L),this._slotRadius=new Float32Array(L),this._slotCost=new Float32Array(L),this._pixels=new Float32Array(L),this._planes=new Float64Array(24),this._detailView=new Float64Array(8),this._frameView=new Float64Array(8),this._frameViewAt=NaN,this._units=[],this._cut=[],this._detailCells=[],this._compactCells=[],this._detailIndices=new Uint16Array(ch),this._detailBins=new Float64Array(jc),this._detailBytes=0,this._unitScale=null,this._cutInView=0,this._cutFrame=-1,this._mergedBytes=0,this._instancedBytes=0,this._lineBytes=0;let B={matrices:n,geometryOf:e,mirrored:_,kind:h,origins:d,source:c,textured:!1};this._lineSources=new Map;let z=0;for(let F of R){let D=this._buckets[this._bucketOf[F[0]]];B.textured=D.texture!==null;let X=uf(F,B);for(let Z=0;ZF+D,0);let W=new Map;for(let{shape:F,members:D}of T){let X=D[0],Z=c(e[X]),G=W.get(F);if(!G){let Q=a.geometries[e[X]].bbox;G=this._shape(Z,_[X]===1,F.textured);let lt=et=>Math.max(...et.map(Math.abs)),ct=Math.max(lt(Z.min),lt(Z.max));G.pickExtent=ct,G.pickPadding=Math.max(0,...Z.min.map((et,V)=>Q.min[V]-et),...Z.max.map((et,V)=>et-Q.max[V]))+(Z.q?Ya*(lt(Z.q.o)+65535*Math.abs(Z.q.s)):0),W.set(F,G)}for(let Q=0;QF+D,0)}_shape(t,e,n){let s=t.vertices,r=t.q?new Uint16Array(s*4):new Float32Array(s*4);for(let h=0;hn+f),1,!1,Kn);a.setAttribute("slotBase",l),a.setIndex(s.index);let c=mf(this._boxes,e),h=new Oe(new I(c[0],c[1],c[2]),c[3]);a.boundingSphere=h;let d=new ps(a,t.material,0),u=new Float32Array(o*16),p=new Float32Array(o*12),g=0;for(let m=0;mthis._range(_,m,b,d),d.visible=!1,this.root.add(d),_}_chunk(t,e,n,s,r,o){let a=new xs;a.instanceCount=1,a.setAttribute("q",En(s.q,4)),a.setAttribute("normal",En(s.o,2,!0)),s.uv&&a.setAttribute("uv",En(s.uv,2)),a.setAttribute("slotBase",En(new Float32Array([n]),1,!1,Kn)),a.setIndex(En(s.index,1));let l=mf(this._boxes,e);a.boundingSphere=new Oe(new I(l[0],l[1],l[2]),l[3]),this._mergedBytes+=s.q.byteLength+s.o.byteLength+(s.uv?.byteLength??0)+s.index.byteLength;let c=new xe(a,t.material),h={bucket:t,mesh:c,lines:null,slotBase:n,n:e.length,sphere:l,shown:0,first:0,last:-1,end:0,dirty:!1,cell:!1,starts:s.indexStart,vertices:s.q.length/4,f32:s.q instanceof Float32Array,members:e.slice(),lastFrame:-1/0};return c.onBeforeRender=(d,u,p)=>this._range(h,d,p,c),c.visible=!1,this.root.add(c),h}_buildLines(){if(!this._lineSources)return;let{mirrored:t,geometryOf:e}=this._lineMembers;for(let n of this._units){if(n.cell){let h=n.mesh.geometry.index;n.lines=new ps(n.mesh.geometry,n.bucket.wire,0),n.lines.instanceMatrix=n.mesh.instanceMatrix,n.lines.boundingSphere=n.mesh.boundingSphere,n.lines.onBeforeRender=(d,u,p)=>this._range(n,d,p,n.lines),this._lineBytes+=h.count*2*h.array.BYTES_PER_ELEMENT,this.root.add(n.lines);continue}let s=n.starts[n.n],r=Wa(n.vertices,s*2),o=0,a=0;for(let h of n.members){let d=this._lineSources.get(e[h]),u=t[h]===1;for(let p=0;pthis._range(n,h,u,n.lines),this.root.add(n.lines),n.members=null}this._lineSources=null,this._lineMembers=null}_range(t,e,n,s){t.dirty&&this._span(t);let r=t.last+1;if(this._picking){if(t.cell&&this._pickFrustum){let o=this._state.image.data,a=t.pickPadding+this._pickViewPadding;for(;r>0;){let l=t.slotBase+r-1;if(o[l*4+3]&&!Lv(this._pickFrustum,this._boxes,this._slotInstance[l]*6,a))break;r--}}}else if(t.cell&&t.detailCount!==null)r=t.detailCount;else if(this._minPixels>0&&r>t.first){let o=e.info.render.frame;o!==this._frameViewAt&&(eh(n,this._viewHeight,this._frameView),this._frameViewAt=o);let a=this._frameView,l=pf(a,t.sphere),c=a[7]?l>0?this._minPixels*l/a[6]:0:this._minPixels/a[6];r=Math.min(r,lf(this._slotRadius,t.slotBase+t.first,t.slotBase+r,c)-t.slotBase)}if(t.cell)s.count=Math.max(r,0);else{let o=s.isLineSegments?2:1,[a,l]=cf(t.starts,t.first,r);s.geometry.setDrawRange(a*o,l*o)}this._picking||(t.end=r,t.lastFrame=e.info.render.frame,this._cutFrame===null&&this._minPixels>0&&(this._cutFrame=t.lastFrame))}_span(t){let e=this._state.image.data,n=0;for(;n=n&&e[(t.slotBase+s)*4+3]===0;)s--;t.first=n0&&!e,t.lines&&(t.lines.visible=t.shown>0&&e)}_createBuckets(t,e,n){let s=new Map,r=[];for(let o=0;oMath.round(h*255)),opacity:c.opacity,texture:c.texture??null,material:ah(new _s({side:Ie}),this.slotUniforms,n),wire:ah(new _s({side:Ie,wireframe:!0}),this.slotUniforms,n)},this._applyOpacity(l),s.set(a,l),r.push(l)}this._bucketOf[o]=l.index}return r}_indexElements(){let t=new Uint32Array(this.elementCount+1);for(let s of this._elementOf)s>=0&&t[s+1]++;for(let s=0;s{s>=0&&(e[n[s]++]=r)}),this._elementStart=t,this._elementInstances=e}_texture(t){let e=this._textures.get(t);if(!e){let n=this._meta.textures[t],s=new Image;e=new ke(s),e.colorSpace=Ae,e.wrapS=e.wrapT=os,e.repeat.set(1/n.sx,1/n.sy),s.onload=()=>{e.needsUpdate=!0,this._changed("appearance")},s.src=`data:${n.mime};base64,${n.data}`,this._textures.set(t,e)}return e}_applyOpacity(t){let e=t.opacity*this._opacity,n=e<1;for(let s of[t.material,t.wire])s.transparent!==n&&(s.needsUpdate=!0),s.opacity=e,s.transparent=n,s.depthWrite=!n}_colorOf(t){return this._highlight[t]?wv:this._tint.get(t)??(this._mode==="white"?Ev:this._buckets[this._bucketOf[t]].bytes)}_applyColor(t){let e=this._slotOf[t];e!==Tr&&(this._state.image.data.set(this._colorOf(t),e*4),this._markDirty(e))}_setInstanceVisible(t,e){this._visible[t]=e?1:0,this._draw(t)}_setLayerFlag(t,e,n){t[e]!==(n?1:0)&&(t[e]=n?1:0,this._layerHides[e]+=n?1:-1,this._draw(e))}_shown(t){return this._visible[t]===1&&this._layerHides[t]===0}_draw(t){let e=this._slotOf[t];if(e===Tr)return;let n=this._shown(t)?255:0,s=this._state.image.data;if(s[e*4+3]===n)return;s[e*4+3]=n,this._markDirty(e);let r=this._units[this._slotUnit[e]];r.shown+=n?1:-1,r.dirty=!0,this._showUnit(r)}_markDirty(t){this._dirtyCountlh)e.clearUpdateRanges(),this._fullPending=!0;else{for(let n=0;n=this.elementCount)throw new RangeError(`Element index ${t} is out of range 0..${this.elementCount-1}.`)}_expandBox(t,e){if(!ff(this._boxes,e))return;let n=this._boxes,s=e*6;t.min.set(Math.min(t.min.x,n[s]),Math.min(t.min.y,n[s+1]),Math.min(t.min.z,n[s+2])),t.max.set(Math.max(t.max.x,n[s+3]),Math.max(t.max.y,n[s+4]),Math.max(t.max.z,n[s+5]))}_changed(t){this._flush(),this.root.dispatchEvent({type:"change",detail:{kind:t}})}};function hh(i,t,e){return e<=t?0:i.cell?(e-t)*i.triangles:(i.starts[e]-i.starts[t])/3}function pf(i,t){return(t[0]-i[0])*i[3]+(t[1]-i[1])*i[4]+(t[2]-i[2])*i[5]-t[3]}function mf(i,t){let e=[1/0,1/0,1/0],n=[-1/0,-1/0,-1/0];for(let a of t)for(let l=0;l<3;l++)e[l]=Math.min(e[l],i[a*6+l]),n[l]=Math.max(n[l],i[a*6+3+l]);let s=(n[0]-e[0])/2,r=(n[1]-e[1])/2,o=(n[2]-e[2])/2;return Float64Array.of((e[0]+n[0])/2,(e[1]+n[1])/2,(e[2]+n[2])/2,Math.hypot(s,r,o),s,r,o)}var Uv={ru:{elements:"\u042D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432",noGeometry:"\u041D\u0435\u0442 \u0433\u0435\u043E\u043C\u0435\u0442\u0440\u0438\u0438",contextLost:"\u0412\u0438\u0434\u0435\u043E\u043A\u0430\u0440\u0442\u0430 \u0441\u0431\u0440\u043E\u0448\u0435\u043D\u0430 \u2014 \u043F\u0435\u0440\u0435\u0437\u0430\u0433\u0440\u0443\u0437\u0438\u0442\u0435 \u0441\u0442\u0440\u0430\u043D\u0438\u0446\u0443",noWebGL:"\u041D\u0443\u0436\u0435\u043D \u0431\u0440\u0430\u0443\u0437\u0435\u0440 \u0441 \u043F\u043E\u0434\u0434\u0435\u0440\u0436\u043A\u043E\u0439 WebGL 2",badData:"\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u043F\u0440\u043E\u0447\u0438\u0442\u0430\u0442\u044C \u0434\u0430\u043D\u043D\u044B\u0435 \u043C\u043E\u0434\u0435\u043B\u0438",tooLarge:"\u041C\u043E\u0434\u0435\u043B\u044C \u0441\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u0430\u044F \u0434\u043B\u044F \u044D\u0442\u043E\u0433\u043E \u043F\u0440\u043E\u0441\u043C\u043E\u0442\u0440\u0449\u0438\u043A\u0430: \u043E\u0431\u044A\u0435\u043A\u0442\u043E\u0432 \u0441 \u0433\u0435\u043E\u043C\u0435\u0442\u0440\u0438\u0435\u0439 \u2014 {count}, \u043F\u0440\u0435\u0434\u0435\u043B \u2014 {limit}",selected:"\u0412\u044B\u0431\u0440\u0430\u043D\u043E",close:"\u0417\u0430\u043A\u0440\u044B\u0442\u044C",elementGroup:"\u042D\u043B\u0435\u043C\u0435\u043D\u0442",id:"Id",category:"\u041A\u0430\u0442\u0435\u0433\u043E\u0440\u0438\u044F",type:"\u0422\u0438\u043F",level:"\u0423\u0440\u043E\u0432\u0435\u043D\u044C",sourceId:"ID \u0438\u0441\u0442\u043E\u0447\u043D\u0438\u043A\u0430",link:"\u0421\u0432\u044F\u0437\u0430\u043D\u043D\u044B\u0439 \u0444\u0430\u0439\u043B",panels:"\u041F\u0430\u043D\u0435\u043B\u0438","panel.model":"\u041C\u043E\u0434\u0435\u043B\u044C","panel.views":"\u0412\u0438\u0434\u044B","panel.sections":"\u0421\u0435\u0447\u0435\u043D\u0438\u044F","panel.clashes":"\u041A\u043E\u043B\u043B\u0438\u0437\u0438\u0438","panel.bcf":"\u0422\u0435\u043C\u044B BCF","bcf.noView":"\u041D\u0435\u0442 \u0434\u043E\u0441\u0442\u0443\u043F\u043D\u043E\u0433\u043E \u0432\u0438\u0434\u0430","bcf.viewpoint":"\u041E\u0442\u043A\u0440\u044B\u0442\u044C \u0432\u0438\u0434 {index}","bcf.components":"\u041D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D\u043E \u043A\u043E\u043C\u043F\u043E\u043D\u0435\u043D\u0442\u043E\u0432 \u2014 {missing}, \u043D\u0435\u043E\u0434\u043D\u043E\u0437\u043D\u0430\u0447\u043D\u044B\u0445 \u2014 {ambiguous}","panel.timeliner":"4D-\u0433\u0440\u0430\u0444\u0438\u043A","panel.links":"\u0421\u0432\u044F\u0437\u0430\u043D\u043D\u044B\u0435 \u0444\u0430\u0439\u043B\u044B","group.navigation":"\u041D\u0430\u0432\u0438\u0433\u0430\u0446\u0438\u044F","group.sections":"\u0421\u0435\u0447\u0435\u043D\u0438\u044F","group.measure":"\u0418\u0437\u043C\u0435\u0440\u0435\u043D\u0438\u044F","group.display":"\u041E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435","group.view":"\u0412\u0438\u0434","tool.orbit":"\u0412\u0440\u0430\u0449\u0435\u043D\u0438\u0435","tool.pan":"\u041F\u0430\u043D\u043E\u0440\u0430\u043C\u0430","tool.fit":"\u0412\u043F\u0438\u0441\u0430\u0442\u044C \u0432\u0441\u0451","tool.projection":"\u041F\u0435\u0440\u0441\u043F\u0435\u043A\u0442\u0438\u0432\u0430 / \u043E\u0440\u0442\u043E\u0433\u0440\u0430\u0444\u0438\u044F","tool.plane":"\u041F\u043B\u043E\u0441\u043A\u043E\u0441\u0442\u044C \u0441\u0435\u0447\u0435\u043D\u0438\u044F","tool.box":"\u0411\u043E\u043A\u0441 \u0441\u0435\u0447\u0435\u043D\u0438\u044F","tool.resetSections":"\u0421\u0431\u0440\u043E\u0441\u0438\u0442\u044C \u0441\u0435\u0447\u0435\u043D\u0438\u044F","tool.distance":"\u0420\u0430\u0441\u0441\u0442\u043E\u044F\u043D\u0438\u0435","tool.displayMode":"\u0420\u0435\u0436\u0438\u043C \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u044F","tool.grids":"\u041E\u0441\u0438","tool.opacity":"\u041F\u0440\u043E\u0437\u0440\u0430\u0447\u043D\u043E\u0441\u0442\u044C","tool.fullscreen":"\u041F\u043E\u043B\u043D\u044B\u0439 \u044D\u043A\u0440\u0430\u043D",contextMenu:"\u041A\u043E\u043D\u0442\u0435\u043A\u0441\u0442\u043D\u043E\u0435 \u043C\u0435\u043D\u044E","menu.properties":"\u0421\u0432\u043E\u0439\u0441\u0442\u0432\u0430","menu.hide":"\u0421\u043A\u0440\u044B\u0442\u044C","menu.isolate":"\u0418\u0437\u043E\u043B\u0438\u0440\u043E\u0432\u0430\u0442\u044C","menu.showAll":"\u041F\u043E\u043A\u0430\u0437\u0430\u0442\u044C \u0432\u0441\u0451","menu.zoomTo":"\u041F\u0440\u0438\u0431\u043B\u0438\u0437\u0438\u0442\u044C \u043A \u043E\u0431\u044A\u0435\u043A\u0442\u0443","menu.sectionBox":"\u0411\u043E\u043A\u0441 \u0441\u0435\u0447\u0435\u043D\u0438\u044F \u043F\u043E \u043E\u0431\u044A\u0435\u043A\u0442\u0443","menu.copyId":"\u041A\u043E\u043F\u0438\u0440\u043E\u0432\u0430\u0442\u044C Id","menu.fitAll":"\u0412\u043F\u0438\u0441\u0430\u0442\u044C \u0432\u0441\u0451","menu.resetSections":"\u0421\u0431\u0440\u043E\u0441\u0438\u0442\u044C \u0441\u0435\u0447\u0435\u043D\u0438\u044F","menu.unavailable":"\u041D\u0435\u0434\u043E\u0441\u0442\u0443\u043F\u043D\u043E \u0434\u043B\u044F \u044D\u0442\u043E\u0439 \u043C\u043E\u0434\u0435\u043B\u0438",searchPlaceholder:"\u041F\u043E\u0438\u0441\u043A \u043F\u043E \u0438\u043C\u0435\u043D\u0438, \u0442\u0438\u043F\u0443, Id\u2026",noCategory:"\u0411\u0435\u0437 \u043A\u0430\u0442\u0435\u0433\u043E\u0440\u0438\u0438",noMatches:"\u041D\u0438\u0447\u0435\u0433\u043E \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D\u043E","filters.title":"\u0424\u0438\u043B\u044C\u0442\u0440\u044B","filters.model":"\u041C\u043E\u0434\u0435\u043B\u044C-\u0438\u0441\u0442\u043E\u0447\u043D\u0438\u043A","filters.noLevel":"\u0411\u0435\u0437 \u0443\u0440\u043E\u0432\u043D\u044F","filters.all":"\u0412\u0441\u0435","filters.clear":"\u0421\u0431\u0440\u043E\u0441\u0438\u0442\u044C","filters.isolate":"\u0418\u0437\u043E\u043B\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0441\u043E\u0432\u043F\u0430\u0434\u0435\u043D\u0438\u044F",idCopied:"Id \u0441\u043A\u043E\u043F\u0438\u0440\u043E\u0432\u0430\u043D",copyFailed:"\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u0441\u043A\u043E\u043F\u0438\u0440\u043E\u0432\u0430\u0442\u044C Id",fullscreenUnavailable:"\u041F\u043E\u043B\u043D\u043E\u044D\u043A\u0440\u0430\u043D\u043D\u044B\u0439 \u0440\u0435\u0436\u0438\u043C \u043D\u0435\u0434\u043E\u0441\u0442\u0443\u043F\u0435\u043D","face.front":"\u0421\u043F\u0435\u0440\u0435\u0434\u0438","face.back":"\u0421\u0437\u0430\u0434\u0438","face.left":"\u0421\u043B\u0435\u0432\u0430","face.right":"\u0421\u043F\u0440\u0430\u0432\u0430","face.top":"\u0421\u0432\u0435\u0440\u0445\u0443","face.bottom":"\u0421\u043D\u0438\u0437\u0443","cube.title":"\u041A\u0443\u0431 \u0432\u0438\u0434\u0430","cube.up":"\u041F\u043E\u0432\u0435\u0440\u043D\u0443\u0442\u044C \u0432\u0432\u0435\u0440\u0445","cube.down":"\u041F\u043E\u0432\u0435\u0440\u043D\u0443\u0442\u044C \u0432\u043D\u0438\u0437","cube.left":"\u041F\u043E\u0432\u0435\u0440\u043D\u0443\u0442\u044C \u0432\u043B\u0435\u0432\u043E","cube.right":"\u041F\u043E\u0432\u0435\u0440\u043D\u0443\u0442\u044C \u0432\u043F\u0440\u0430\u0432\u043E","cube.home":"\u0418\u0441\u0445\u043E\u0434\u043D\u044B\u0439 \u0432\u0438\u0434","sections.mode":"\u0420\u0435\u0436\u0438\u043C \u0441\u0435\u0447\u0435\u043D\u0438\u044F","sections.planes":"\u041F\u043B\u043E\u0441\u043A\u043E\u0441\u0442\u0438","sections.box":"\u0411\u043E\u043A\u0441","sections.off":"\u0412\u044B\u043A\u043B","sections.axis":"\u041E\u0441\u044C","sections.addPlane":"\u0414\u043E\u0431\u0430\u0432\u0438\u0442\u044C \u043F\u043B\u043E\u0441\u043A\u043E\u0441\u0442\u044C","sections.noPlanes":"\u041F\u043B\u043E\u0441\u043A\u043E\u0441\u0442\u0435\u0439 \u043D\u0435\u0442","sections.rotated":"\u043F\u043E\u0432\u0451\u0440\u043D\u0443\u0442\u0430","sections.custom":"\u041F\u0440\u043E\u0438\u0437\u0432\u043E\u043B\u044C\u043D\u0430\u044F","sections.position":"\u041F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435 \u043F\u043B\u043E\u0441\u043A\u043E\u0441\u0442\u0438","sections.flip":"\u0421\u043C\u0435\u043D\u0438\u0442\u044C \u0441\u0442\u043E\u0440\u043E\u043D\u0443","sections.enabled":"\u0412\u043A\u043B","sections.delete":"\u0423\u0434\u0430\u043B\u0438\u0442\u044C \u043F\u043B\u043E\u0441\u043A\u043E\u0441\u0442\u044C","sections.keepInside":"\u041F\u043E\u043A\u0430\u0437\u0430\u0442\u044C \u0432\u043D\u0443\u0442\u0440\u0438","sections.cutInside":"\u0412\u044B\u0440\u0435\u0437\u0430\u0442\u044C \u0432\u043D\u0443\u0442\u0440\u0438","sections.fitSelection":"\u041F\u043E \u0432\u044B\u0434\u0435\u043B\u0435\u043D\u043D\u043E\u043C\u0443","sections.showGizmo":"\u041F\u043E\u043A\u0430\u0437\u044B\u0432\u0430\u0442\u044C \u043C\u0430\u043D\u0438\u043F\u0443\u043B\u044F\u0442\u043E\u0440","sections.boxYaw":"\u041F\u043E\u0432\u043E\u0440\u043E\u0442 \u0432\u043E\u043A\u0440\u0443\u0433 Z","sections.fill":"\u0417\u0430\u043B\u0438\u0432\u043A\u0430 \u0441\u0440\u0435\u0437\u043E\u0432","sections.fillUnavailable":"\u0417\u0430\u043B\u0438\u0432\u043A\u0430 \u043D\u0435\u0434\u043E\u0441\u0442\u0443\u043F\u043D\u0430 \u0431\u0435\u0437 \u0431\u0443\u0444\u0435\u0440\u0430 \u0442\u0440\u0430\u0444\u0430\u0440\u0435\u0442\u0430 WebGL","sections.maxPlanes":"\u041D\u0435 \u0431\u043E\u043B\u044C\u0448\u0435 6 \u043F\u043B\u043E\u0441\u043A\u043E\u0441\u0442\u0435\u0439","unit.m":"\u043C","display.materials":"\u041C\u0430\u0442\u0435\u0440\u0438\u0430\u043B\u044B","display.textures":"\u0422\u0435\u043A\u0441\u0442\u0443\u0440\u044B","display.white":"\u0411\u0435\u043B\u044B\u0439","display.wireframe":"\u041A\u0430\u0440\u043A\u0430\u0441","display.background":"\u0426\u0432\u0435\u0442 \u0444\u043E\u043D\u0430","display.backgroundReset":"\u0424\u043E\u043D \u043F\u043E \u0443\u043C\u043E\u043B\u0447\u0430\u043D\u0438\u044E","opacity.label":"\u041D\u0435\u043F\u0440\u043E\u0437\u0440\u0430\u0447\u043D\u043E\u0441\u0442\u044C","opacity.value":"{value} %","views.tour":"\u0422\u0443\u0440 \u043F\u043E \u0432\u0438\u0434\u0430\u043C","views.stop":"\u041E\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C \u0442\u0443\u0440","clash.New":"\u041D\u043E\u0432\u0430\u044F","clash.Active":"\u0410\u043A\u0442\u0438\u0432\u043D\u0430\u044F","clash.Reviewed":"\u041F\u0440\u043E\u0432\u0435\u0440\u0435\u043D\u0430","clash.Approved":"\u0423\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043D\u0430","clash.Resolved":"\u0423\u0441\u0442\u0440\u0430\u043D\u0435\u043D\u0430","task.construct":"\u0421\u0442\u0440\u043E\u0438\u0442\u0435\u043B\u044C\u0441\u0442\u0432\u043E","task.demolish":"\u0421\u043D\u043E\u0441","task.temporary":"\u0412\u0440\u0435\u043C\u0435\u043D\u043D\u043E\u0435","player.title":"4D-\u043F\u0440\u043E\u0438\u0433\u0440\u044B\u0432\u0430\u0442\u0435\u043B\u044C","player.play":"\u0412\u043E\u0441\u043F\u0440\u043E\u0438\u0437\u0432\u0435\u0441\u0442\u0438","player.pause":"\u041F\u0430\u0443\u0437\u0430","player.date":"\u0414\u0430\u0442\u0430 \u0433\u0440\u0430\u0444\u0438\u043A\u0430","player.speed":"\u0421\u043A\u043E\u0440\u043E\u0441\u0442\u044C",truncated:"\u041F\u043E\u043A\u0430\u0437\u0430\u043D\u043E {meshes} \u0438\u0437 {total} \u043C\u0435\u0448\u0435\u0439: \u043C\u043E\u0434\u0435\u043B\u044C \u043E\u0431\u0440\u0435\u0437\u0430\u043D\u0430 \u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u043E\u0439 MaxMeshVertices"},en:{elements:"Elements",noGeometry:"No geometry",contextLost:"The graphics context was lost \u2014 reload the page",noWebGL:"This page needs a browser with WebGL 2",badData:"The model data could not be read",tooLarge:"The model is too large for this viewer: {count} objects with geometry, the limit is {limit}",selected:"Selected",close:"Close",elementGroup:"Element",id:"Id",category:"Category",type:"Type",level:"Level",sourceId:"Source ID",link:"Link",panels:"Panels","panel.model":"Model","panel.views":"Views","panel.sections":"Sections","panel.clashes":"Clashes","panel.bcf":"BCF topics","bcf.noView":"No view available","bcf.viewpoint":"Open viewpoint {index}","bcf.components":"Components missing \u2014 {missing}, ambiguous \u2014 {ambiguous}","panel.timeliner":"4D schedule","panel.links":"Linked files","group.navigation":"Navigation","group.sections":"Sections","group.measure":"Measure","group.display":"Display","group.view":"View","tool.orbit":"Orbit","tool.pan":"Pan","tool.fit":"Fit all","tool.projection":"Perspective / orthographic","tool.plane":"Section plane","tool.box":"Section box","tool.resetSections":"Reset sections","tool.distance":"Distance","tool.displayMode":"Display mode","tool.grids":"Grids","tool.opacity":"Transparency","tool.fullscreen":"Full screen",contextMenu:"Context menu","menu.properties":"Properties","menu.hide":"Hide","menu.isolate":"Isolate","menu.showAll":"Show all","menu.zoomTo":"Zoom to object","menu.sectionBox":"Section box around object","menu.copyId":"Copy Id","menu.fitAll":"Fit all","menu.resetSections":"Reset sections","menu.unavailable":"Unavailable for this model",searchPlaceholder:"Search by name, type, Id\u2026",noCategory:"No category",noMatches:"No matches","filters.title":"Filters","filters.model":"Source model","filters.noLevel":"No level","filters.all":"All","filters.clear":"Clear","filters.isolate":"Isolate matches",idCopied:"Id copied",copyFailed:"Could not copy Id",fullscreenUnavailable:"Fullscreen is not available","face.front":"Front","face.back":"Back","face.left":"Left","face.right":"Right","face.top":"Top","face.bottom":"Bottom","cube.title":"View cube","cube.up":"Rotate up","cube.down":"Rotate down","cube.left":"Rotate left","cube.right":"Rotate right","cube.home":"Home view","sections.mode":"Section mode","sections.planes":"Planes","sections.box":"Box","sections.off":"Off","sections.axis":"Axis","sections.addPlane":"Add plane","sections.noPlanes":"No planes","sections.rotated":"rotated","sections.custom":"Custom","sections.position":"Plane position","sections.flip":"Flip side","sections.enabled":"On","sections.delete":"Delete plane","sections.keepInside":"Show inside","sections.cutInside":"Cut inside","sections.fitSelection":"Fit to selection","sections.showGizmo":"Show gizmo","sections.boxYaw":"Rotation around Z","sections.fill":"Fill cut faces","sections.fillUnavailable":"Section fill requires a WebGL stencil buffer","sections.maxPlanes":"At most 6 planes","unit.m":"m","display.materials":"Materials","display.textures":"Textures","display.white":"White","display.wireframe":"Wireframe","display.background":"Background color","display.backgroundReset":"Reset background","opacity.label":"Opacity","opacity.value":"{value}%","views.tour":"Play tour","views.stop":"Stop tour","clash.New":"New","clash.Active":"Active","clash.Reviewed":"Reviewed","clash.Approved":"Approved","clash.Resolved":"Resolved","task.construct":"Construct","task.demolish":"Demolish","task.temporary":"Temporary","player.title":"4D player","player.play":"Play","player.pause":"Pause","player.date":"Schedule date","player.speed":"Speed",truncated:"Showing {meshes} of {total} meshes: the model was truncated by the MaxMeshVertices setting"}},Ls=(globalThis.navigator?.language??"").toLowerCase().startsWith("ru")?"ru":"en",Cr=new Intl.NumberFormat(Ls).format;function st(i,t=Ls){let e=Uv[t][i];if(e===void 0)throw new Error(`Missing UI string '${i}'.`);return e}var gf=new I(0,0,1),$a=Math.PI/2-.01;function xf(i,t,e=4){return Math.hypot(t.x-i.x,t.y-i.y)<=e}function vf(i,t,e,n,s,r){let o=i.clone().sub(e),a=t.clone().sub(e),l=d=>(o.applyQuaternion(d),a.applyQuaternion(d));l(new Ce().setFromAxisAngle(gf,-n*r));let c=a.clone().sub(o).normalize(),h=c.clone().cross(gf);if(h.lengthSq()>1e-12){let d=Math.asin(ce.clamp(c.z,-1,1)),u=ce.clamp(s*r,d-$a,d+$a);l(new Ce().setFromAxisAngle(h.normalize(),-u))}return{position:o.add(e),target:a.add(e)}}function yf(i,t,e,n){let s=r=>r.clone().sub(e).multiplyScalar(n).add(e);return{position:s(i),target:s(t)}}var Fv=.85,Bv=100/3;function Mf(i,t,e){let n=i*(t===1?Bv:t===2?e:1);return ce.clamp(Fv**(-n/100),.5,2)}var dh=(i,t)=>t>=i?"window":"crossing";function bf(i,t,e){let n=_f(i.position,i.target),s=_f(t.position,t.target),r=n.azimuth??s.azimuth??0,o=s.azimuth??r,a=ce.euclideanModulo(o-r+Math.PI,2*Math.PI)-Math.PI,l=(_,m)=>_+(m-_)*e,c=r+a*e,h=ce.clamp(l(n.elevation,s.elevation),-$a,$a),d=l(n.distance,s.distance),u=i.target.clone().lerp(t.target,e),p=Math.cos(h)*d;return{position:u.clone().add(new I(p*Math.cos(c),p*Math.sin(c),Math.sin(h)*d)),target:u}}function Sf(i,t,e,n){let s=i.position.clone().sub(i.target),r=t.position.clone().sub(t.target),o=s.length(),a=r.length();s.normalize(),r.normalize();let l=new Ce().setFromUnitVectors(s,r),c=e.clone().applyQuaternion(l),h=new I().setFromMatrixColumn(new kt().lookAt(t.position,t.target,n),1),d=r.dot(new I().crossVectors(c,h)),u=Math.atan2(Math.abs(d)<1e-9?0:d,c.dot(h)),p=new Ce;return g=>{p.identity().slerp(l,g);let _=s.clone().applyQuaternion(p),m=i.target.clone().lerp(t.target,g),f=_.clone().multiplyScalar(ce.lerp(o,a,g)).add(m),b=e.clone().applyQuaternion(p).applyAxisAngle(_,u*g);return{position:f,target:m,up:b}}}function _f(i,t){let e=i.clone().sub(t),n=e.length(),s=Math.hypot(e.x,e.y);return{distance:n,elevation:n>1e-12?Math.asin(ce.clamp(e.z/n,-1,1)):0,azimuth:s>1e-9*Math.max(n,1e-12)?Math.atan2(e.y,e.x):null}}var Ov=.005,zv=new I(1,-1,.8).normalize(),ph=.01,wf=1e-6,kv=64,Ef=1.05,Hv=5e3,fh=(i,t)=>new CustomEvent(i,{detail:t});function Tf({bbox:i,grids:t}){let e=r=>Array.isArray(r)&&r.length===3&&r.every(Number.isFinite);if(!e(i?.min)||!e(i?.max))return!0;let n=new ie(new I(...i.min),new I(...i.max));if(n.isEmpty())return!0;let s=new I;for(let r of t??[]){if(!e(r.start)||!e(r.end))return!0;n.expandByPoint(s.fromArray(r.start)),n.expandByPoint(s.fromArray(r.end))}return n.getSize(s).length()*Ef>ph*Hv}var Za=class extends EventTarget{constructor(t,e,{pick:n=()=>null,visibleBox:s=()=>new ie}={}){super(),this.dom=e,this.pick=n,this.visibleBox=s,this.target=new I,this.leftButtonMode="orbit",this._perspective=t,this._defaultFov=t.fov,this._orthographic=new Fn(-1,1,1,-1),this.camera=t,this._drag=null,this._wheelPick=null,this._animation=0,this._overlay=null,this._bounds=null,this._extraBounds=new Map,e.style.touchAction="none",e.addEventListener("pointerdown",r=>this._down(r)),e.addEventListener("pointermove",r=>this._move(r)),e.addEventListener("pointerup",r=>this._up(r)),e.addEventListener("pointercancel",()=>this._end()),e.addEventListener("lostpointercapture",r=>this._lostCapture(r)),window.addEventListener("blur",()=>this._end()),e.addEventListener("wheel",r=>this._wheel(r),{passive:!1}),e.addEventListener("contextmenu",r=>r.preventDefault())}setLeftButtonMode(t){if(t!=="orbit"&&t!=="pan")throw new RangeError(`Unknown left button mode: ${t}`);this.leftButtonMode=t}setProjection(t){if(t!=="perspective"&&t!=="orthographic")throw new RangeError(`Unknown projection: ${t}`);let e=t==="perspective"?this._perspective:this._orthographic,n=this.camera;if(e!==n){this._stopAnimation(),e.position.copy(n.position),n.isOrthographicCamera&&e.position.sub(this.target).divideScalar(n.zoom).add(this.target),e.zoom=1,e.quaternion.copy(n.quaternion),e.up.copy(n.up),n.parent?.add(e),n.parent?.remove(n);for(let s of[...n.children])e.add(s);this.camera=e,this.resize()}}resize(){let t=this.camera,e=this.dom.clientWidth/Math.max(this.dom.clientHeight,1),n=Math.max(t.position.distanceTo(this.target),1e-6);if(t.isPerspectiveCamera)t.aspect=e;else{let r=n*Math.tan(ce.degToRad(this._perspective.fov/2));Object.assign(t,{top:r,bottom:-r,left:-r*e,right:r*e})}let s=this._rangeSphere();if(s){let r=s.center.clone().sub(t.position),o=new I(0,0,-1).applyQuaternion(t.quaternion);t.far=Math.max(1e-6,(r.length()+s.radius)*Ef);let a=r.dot(o)-s.radius;t.near=Math.max(a*.95,Math.min(ph,t.far/2))}t.updateProjectionMatrix(),this.dispatchEvent(new Event("change"))}setExtraBounds(t,e){e&&!e.isEmpty()?this._extraBounds.set(t,e.clone()):this._extraBounds.delete(t),this.resize()}_rangeSphere(){let t=this._visibleBounds()?.sphere??null;if(this._extraBounds.size===0)return t;let e=t?this._bounds.box.clone():new ie;for(let n of this._extraBounds.values())e.union(n);return e.getBoundingSphere(new Oe)}invalidateBounds(){this._bounds=null}_visibleBounds(){if(!this._bounds){let t=this.visibleBox();this._bounds={box:t,sphere:t.isEmpty()?null:t.getBoundingSphere(new Oe)}}return this._bounds.sphere&&this._bounds}fitBox(t,e=!0){if(t.isEmpty())return;let n=t.getBoundingSphere(new Oe),s=Math.max(n.radius,.001),r=ce.degToRad(this._perspective.fov/2),o=this.dom.clientWidth/Math.max(this.dom.clientHeight,1),a=s/Math.sin(Math.min(r,Math.atan(Math.tan(r)*o))),l=this.camera.position.clone().sub(this.target);l.lengthSq()<1e-12&&l.copy(zv);let c=l.normalize().multiplyScalar(a).add(n.center);e?this.animateTo({position:c,target:n.center}):(this.camera.zoom=1,this._set(c,n.center))}zoomToBox(t){this.fitBox(t,!0)}resetCameraStyle(){this._perspective.fov=this._defaultFov,this.camera.up.set(0,0,1)}restoreViewCamera({position:t,target:e,up:n,fov:s,orthographicHeight:r}){let o=new I(...t),a=new I(...e);if(this.resetCameraStyle(),!n){this.animateTo({position:o,target:a});return}this._stopAnimation(),this.camera.up.fromArray(n),this._perspective.fov=s??this._defaultFov;let l=Math.max(o.distanceTo(a),1e-6);this.camera.zoom=r==null?1:2*l*Math.tan(ce.degToRad(this._perspective.fov/2))/r,this._set(o,a)}animateTo({position:t,target:e,zoom:n=1,overPole:s=!1},r=400){this._stopAnimation();let o={position:this.camera.position.clone(),target:this.target.clone()},a={position:t??o.position,target:e??o.target},l=this.camera.zoom,c=s?Sf(o,a,new I(0,1,0).applyQuaternion(this.camera.quaternion),this.camera.up):u=>bf(o,a,u),h=performance.now(),d=u=>{let p=Math.min((u-h)/r,1),g=p*p*(3-2*p),_=c(g);this.camera.isOrthographicCamera&&(this.camera.zoom=ce.lerp(l,n,g)),this._set(_.position,_.target,_.up),this._animation=p<1?requestAnimationFrame(d):0};this._animation=requestAnimationFrame(d)}get animating(){return this._animation!==0}_stopAnimation(){cancelAnimationFrame(this._animation),this._animation=0}_set(t,e,n){if(this.camera.position.copy(t),this.target.copy(e),n){let s=this.camera.up.clone();this.camera.up.copy(n),this.camera.lookAt(e),this.camera.up.copy(s)}else this.camera.lookAt(e);this.resize()}_down(t){this._end(),this._stopAnimation(),this.dom.setPointerCapture(t.pointerId),t.preventDefault();let e=t.button===0&&t.shiftKey?"box":t.button===0&&this.leftButtonMode==="orbit"?"orbit":"pan",n={x:t.clientX,y:t.clientY},s=null;e==="orbit"&&(s=this.pick(n.x,n.y),s||(s=this._visibleBounds()?.sphere.center.clone()??this.target.clone())),this._drag={id:t.pointerId,button:t.button,mode:e,pivot:s,down:n,last:n,moved:!1}}_anchor(t,e){let n=this.pick(t,e);if(n)return n;let s=this.dom.getBoundingClientRect(),r=s.left+s.width/2,o=s.top+s.height/2;return t===r&&e===o?null:this.pick(r,o)}_gestureDepth(t,e){let n=this.camera,s=t?t.clone().sub(n.position).dot(e):0;return Math.max(wf,n.position.distanceTo(this.target),s)}_move(t){let e=this._drag;if(!e||t.pointerId!==e.id)return;if(t.buttons===0)return this._end();let n={x:t.clientX,y:t.clientY};if(!e.moved&&xf(e.down,n))return;e.moved=!0;let s=n.x-e.last.x,r=n.y-e.last.y;if(e.last=n,e.mode==="box")this._drawRect(e.down,n);else if(e.mode==="orbit"){let o=vf(this.camera.position,this.target,e.pivot,s,r,Ov);this._set(o.position,o.target)}else this._pan(s,r)}_pan(t,e){let n=this.camera,s=Math.max(this.dom.clientHeight,1);if(n.isPerspectiveCamera&&this._drag.depth===void 0){let{x:c,y:h}=this._drag.down;this._drag.depth=this._gestureDepth(this._anchor(c,h),n.getWorldDirection(new I))}let r=n.isPerspectiveCamera?2*this._drag.depth*Math.tan(ce.degToRad(n.fov/2))/(s*n.zoom):(n.top-n.bottom)/n.zoom/s,o=new I(1,0,0).applyQuaternion(n.quaternion),a=new I(0,1,0).applyQuaternion(n.quaternion),l=o.multiplyScalar(-t*r).addScaledVector(a,e*r);this._set(n.position.clone().add(l),this.target.clone().add(l))}_up(t){let e=this._drag;if(!e||t.pointerId!==e.id||t.button!==e.button)return;let n={x:t.clientX,y:t.clientY};if(this._end(),e.mode==="box"&&e.moved){let s={x:Math.min(e.down.x,n.x),y:Math.min(e.down.y,n.y),width:Math.abs(n.x-e.down.x),height:Math.abs(n.y-e.down.y)},r=dh(e.down.x,n.x);this.dispatchEvent(fh("boxselect",{rect:s,mode:r,ctrl:t.ctrlKey,shift:t.shiftKey}))}else!e.moved&&e.button===0?this.dispatchEvent(fh("click",{x:n.x,y:n.y,button:0,ctrl:t.ctrlKey,shift:t.shiftKey})):!e.moved&&e.button===2&&this.dispatchEvent(fh("contextmenu",{x:n.x,y:n.y}))}_lostCapture(t){this._drag&&t.buttons?this.dom.setPointerCapture(this._drag.id):this._end()}_end(){this._drag=null,this._overlay?.remove(),this._overlay=null}_drawRect(t,e){this._overlay||(this._overlay=document.createElement("div"),Object.assign(this._overlay.style,{position:"fixed",pointerEvents:"none",border:"1px solid #2563eb",background:"rgba(37,99,235,0.12)"}),(this.dom.parentElement??document.body).appendChild(this._overlay)),Object.assign(this._overlay.style,{borderStyle:dh(t.x,e.x)==="window"?"solid":"dashed",left:`${Math.min(t.x,e.x)}px`,top:`${Math.min(t.y,e.y)}px`,width:`${Math.abs(e.x-t.x)}px`,height:`${Math.abs(e.y-t.y)}px`})}_wheel(t){if(t.preventDefault(),t.deltaY===0)return;this._stopAnimation();let e=Mf(t.deltaY,t.deltaMode,this.dom.clientHeight),n=this.camera,s=n.position.distanceTo(this.target),r=this._visibleBounds()?.sphere.radius??0,o=kv*Math.max(r,.001);if(n.isOrthographicCamera){let{left:_,top:m,width:f,height:b}=this.dom.getBoundingClientRect();if(!f||!b)return;let E=ce.clamp(n.zoom/e,Math.max(1e-6,Math.min(n.zoom,s/o)),1e6);if(E===n.zoom)return;let M=new I((2*(t.clientX-_)/f-1)*n.right,(1-2*(t.clientY-m)/b)*n.top,0).multiplyScalar(1/n.zoom-1/E).applyQuaternion(n.quaternion);n.zoom=E,this._set(n.position.clone().add(M),this.target.clone().add(M));return}this._wheelPick||(this._wheelPick={point:this._anchor(t.clientX,t.clientY)},requestAnimationFrame(()=>this._wheelPick=null));let a=n.getWorldDirection(new I),l=this._gestureDepth(this._wheelPick.point,a);if(!Number.isFinite(l))return;let c=Math.min(ph,Math.max(wf,r)),h=ce.clamp(l*e,c,Math.max(l,o))/l;if(h===1)return;let d=n.position.clone().addScaledVector(a,l),u=this._wheelPick.point,p=u&&u.clone().sub(n.position).dot(a)>=c?u:d,g=yf(n.position,d,p,h);this._set(g.position,g.target)}};function tt(i,t,e){let n=document.createElement(i);return t&&(n.className=t),e!==void 0&&(n.textContent=e),n}function Ke(i,t,e){let n=tt("button",i);return n.type="button",n.innerHTML=t,n.title=e,n.setAttribute("aria-label",e),n}function Ds(i){i.preventDefault(),i.stopPropagation()}function Ja(i){Ds(i);let t=i.button===2,e=()=>{window.removeEventListener("pointerup",n,!0),setTimeout(()=>{window.removeEventListener("click",Ds,!0),t&&window.removeEventListener("contextmenu",Ds,!0)})},n=s=>{Ds(s),e()};window.addEventListener("pointerup",n,!0),window.addEventListener("click",Ds,!0),t&&window.addEventListener("contextmenu",Ds,!0)}function Ir(i,t,e,n){let s=t.clone().applyMatrix4(e.matrixWorldInverse).z<0,r=t.clone().project(e);i.hidden=!(s&&Math.abs(r.x)<=1&&Math.abs(r.y)<=1),!i.hidden&&(i.style.left=`${n.left+(r.x+1)/2*n.width}px`,i.style.top=`${n.top+(1-r.y)/2*n.height}px`)}var pe=i=>``,Af='',Zt={model:pe(''),views:pe(''),sections:pe(''),clashes:pe(''),bcf:pe(''),timeliner:pe(''),links:pe(''),orbit:pe(''),pan:pe(''),fit:pe(''),projection:pe(Af),plane:pe(''),box:pe(`${Af}`),resetSections:pe(''),distance:pe(''),displayMode:pe(''),grids:pe(''),opacity:pe(''),fullscreen:pe(''),close:pe(''),chevron:pe(''),flip:pe(''),remove:pe(''),play:pe(''),pause:pe(''),home:pe('')};var Pr=new I(0,0,1),cn={right:new I(1,0,0),left:new I(-1,0,0),back:new I(0,1,0),front:new I(0,-1,0),top:new I(0,0,1),bottom:new I(0,0,-1)},Vv={right:Pr,left:Pr,back:Pr,front:Pr,top:cn.back,bottom:cn.front},ki=.7,Gv=ce.degToRad(1),Rf=.01,Cf=96,Ka=1.75;function If(i){let t=i.split("-"),e=new I;for(let n of t){if(!Object.hasOwn(cn,n))throw new RangeError(`Unknown view cube region: ${i}`);e.add(cn[n])}if(new Set(t).size!==t.length||e.lengthSq()!==t.length)throw new RangeError(`Unknown view cube region: ${i}`);return e.normalize()}function Wv(i){let t=[];return Math.abs(i.z)>=ki&&t.push(i.z>0?"top":"bottom"),Math.abs(i.y)>=ki&&t.push(i.y>0?"back":"front"),Math.abs(i.x)>=ki&&t.push(i.x>0?"right":"left"),t.join("-")}function mh(i,t=Gv){let e=i.clone().normalize(),n=Math.cos(t);return Object.keys(cn).find(s=>e.dot(cn[s])>=n)??null}function Pf(i){let t=new I(i.x,i.y,0);if(t.lengthSq()<1e-24)return"front";t.normalize();let e=["front","right","back","left"],n=Math.max(...e.map(s=>t.dot(cn[s])));return e.find(s=>t.dot(cn[s])>=n-1e-9)}function gh(i,t){return cn[Pf(t)].clone().multiplyScalar(Math.sin(Rf)).addScaledVector(cn[i],Math.cos(Rf))}function Xv(i,t){let e=mh(i);if(!e)return null;let n=e==="top"||e==="bottom";if(t==="left"||t==="right")return(n?gh(e,i):If(e)).applyAxisAngle(Pr,t==="right"?Math.PI/2:-Math.PI/2);if(t!=="up"&&t!=="down")throw new RangeError(`Unknown arrow: ${t}`);if(!n)return gh(t==="up"?"top":"bottom",i);let s=cn[Pf(i)];return t==="up"==(e==="top")?s.clone().negate():s.clone()}function qv(i,t){let e=document.createElement("canvas");e.width=e.height=128;let n=e.getContext("2d");n.fillStyle="#2a2f38",n.fillRect(0,0,128,128),n.fillStyle="#cbd5e1",n.textAlign="center",n.textBaseline="middle",n.font=`600 26px ${t}`;let s=n.measureText(i).width;s>112&&(n.font=`600 ${Math.floor(2912/s)}px ${t}`),n.fillText(i,64,64);let r=new tr(e);return r.colorSpace=Ae,r}var ja=class{constructor(t,e,n){this.controls=n,this.home={position:e.position.clone(),target:n.target.clone()},this.element=tt("div","ioviewer-viewcube"),this.canvas=tt("canvas","ioviewer-viewcube-canvas"),this.canvas.title=st("cube.title"),this.canvas.setAttribute("aria-label",st("cube.title")),this.element.append(this.canvas),this.error=null,this.renderer=this._createRenderer(),this.scene=new Ri,this.camera=new Fn(-Ka,Ka,Ka,-Ka,.1,10),this.faces=new Re;let s=getComputedStyle(t).fontFamily;for(let[l,c]of Object.entries(cn)){let h=st(`face.${l}`),d=new xe(new yn(2,2),new en({map:qv(h,s)})),u=Vv[l];d.quaternion.setFromRotationMatrix(new kt().makeBasis(u.clone().cross(c),u,c)),d.position.copy(c),d.name=l,d.userData.label=h,this.faces.add(d)}let r=new vn(new Di(new dn(2,2,2)),new an({color:"#5b6575"}));this.highlight=new xe(new dn(1,1,1),new en({color:"#2563eb",transparent:!0,opacity:.6})),this.highlight.visible=!1,this.scene.add(this.faces,r,this.highlight),this._raycaster=new Ni,this.hovered=null,this._pointer=null,this.element.addEventListener("contextmenu",l=>l.preventDefault());let o=l=>{this._pointer=[l.clientX,l.clientY],this._hover(this.regionAtClient(...this._pointer))&&this._render()};this.canvas.addEventListener("pointerenter",o),this.canvas.addEventListener("pointermove",o),this.canvas.addEventListener("pointerleave",()=>{this._pointer=null,this._hover(null)&&this._render()}),this.canvas.addEventListener("click",l=>{let c=this.regionAtClient(l.clientX,l.clientY);if(!c)return;let h=c==="top"||c==="bottom";this._look(h?gh(c,n.camera.position.clone().sub(n.target)):If(c))}),this.arrows=["up","down","left","right"].map(l=>{let c=Ke("ioviewer-viewcube-arrow",Zt.chevron,st(`cube.${l}`));return c.dataset.arrow=l,c.addEventListener("click",h=>{h.detail&&c.blur(),this._arrow(l)}),c});let a=Ke("ioviewer-viewcube-home",Zt.home,st("cube.home"));a.addEventListener("click",l=>{l.detail&&a.blur(),n.resetCameraStyle(),n.animateTo({position:this.home.position.clone(),target:this.home.target.clone()})}),this.element.append(...this.arrows,a),t.append(this.element),this.update()}_createRenderer(){this.canvas.addEventListener("webglcontextlost",e=>{e.stopImmediatePropagation(),this._fail(new Error("The view cube lost its WebGL context."))});let t=this.canvas.getContext("webgl2",{alpha:!0,antialias:!0});if(!t)return this._fail(new Error("WebGL 2 is not available for the view cube."));try{let e=new As({canvas:this.canvas,context:t,alpha:!0,antialias:!0});return e.setPixelRatio(window.devicePixelRatio),e.setSize(Cf,Cf),e}catch(e){return this._fail(e)}}_fail(t){return this.error=t,this.renderer=null,this.element.hidden=!0,null}_render(){if(this.renderer)try{this.renderer.render(this.scene,this.camera)}catch(t){this._fail(t)}}update(){if(!this.renderer)return;let t=this.controls.camera,e=!this.camera.quaternion.equals(t.quaternion);this.camera.quaternion.copy(t.quaternion),this.camera.position.set(0,0,5).applyQuaternion(t.quaternion),this.camera.updateMatrixWorld();let n=mh(t.position.clone().sub(this.controls.target))!==null;for(let s of this.arrows)s.hidden=!n;e&&this._pointer&&this._hover(this.regionAtClient(...this._pointer)),this._render()}regionAtClient(t,e){let n=this.canvas.getBoundingClientRect(),s=new Ht((t-n.left)/n.width*2-1,1-(e-n.top)/n.height*2);this._raycaster.setFromCamera(s,this.camera);let r=this._raycaster.intersectObjects(this.faces.children)[0];return r?Wv(r.point):null}_hover(t){if(t===this.hovered)return!1;if(this.hovered=t,this.highlight.visible=!!t,t){let e=t.split("-").reduce((a,l)=>a.add(cn[l]),new I),n=a=>a===0?[-ki,ki]:a>0?[ki,1.02]:[-1.02,-ki],[s,r,o]=e.toArray().map(n);this.highlight.scale.set(s[1]-s[0],r[1]-r[0],o[1]-o[0]),this.highlight.position.set((s[0]+s[1])/2,(r[0]+r[1])/2,(o[0]+o[1])/2)}return!0}_arrow(t){let n=this.controls.camera.position.clone().sub(this.controls.target),s=Xv(n,t);if(!s)return;let r=mh(n),o=r==="top"&&t==="up"||r==="bottom"&&t==="down";this._look(s,o)}_look(t,e=!1){let{controls:n}=this,s=n.camera.position.distanceTo(n.target);n.animateTo({position:t.clone().multiplyScalar(s).add(n.target),target:n.target.clone(),zoom:n.camera.zoom,overPole:e})}};var Yv=` #include ${wr} #include @@ -4278,7 +4278,7 @@ void main() { vPos = ( modelMatrix * wp ).xyz; vSlot = vec2( float( slot >> 12 ), float( slot & 4095 ) ); if ( state.a < 0.5 ) gl_Position = vec4( 0.0, 0.0, 2.0, 1.0 ); -}`,Gv=` +}`,$v=` #include #include #include @@ -4300,10 +4300,10 @@ void main() { #else gl_FragColor = vec4( vPos, id ); #endif -}`,If=i=>i&&{element:i.element,point:i.point.clone()};function gh(i,t){let e=new He({vertexShader:Vv,fragmentShader:Gv,uniforms:i,defines:t?{[t]:""}:{},side:Ie,clipping:!0});return e.index0AttributeName="q",e}var Qa=class{constructor(t,e,n,s={}){this.renderer=t,this.scene=e,this.camera=n,this._lost=!1,t.domElement.addEventListener("webglcontextlost",()=>this._lost=!0),this._last=null,this._lastTile=null,this._key=new Float64Array(36),e.root.addEventListener("change",o=>{o.detail.kind!=="appearance"&&(this._last=this._lastTile=null)});let r=e.slotUniforms;this._float=s.pickFloat!==!1&&t.extensions.has("EXT_color_buffer_float"),this._float?(this._material=gh(r,null),this._target=new Fe(1,1,{type:Ge}),this._pixel=new Float32Array(4)):(this._material=gh(r,"IO_PICK_RGBA8"),this._depthMaterial=gh(r,"IO_PICK_DEPTH"),this._target=new Fe(1,1),this._pixel=new Uint8Array(4))}pick(t,e){let n=this.renderer.domElement.getBoundingClientRect(),s=Math.floor(t-n.left),r=Math.floor(e-n.top);if(this._lost||!(s>=0&&r>=0&&sh===o[d]))return If(l.hit);let c=this._pick(s,r,n);return this._last={camera:a,key:o.slice(),hit:c},If(c)}_sampleKey(t,e,n){this.camera.updateMatrixWorld();let s=this._key;return s.set([t,e,n.width,n.height]),s.set(this.camera.matrixWorld.elements,4),s.set(this.camera.projectionMatrix.elements,20),s}measureTile(t,e,n){let s=this.renderer.domElement.getBoundingClientRect(),r=Math.floor(t-s.left),o=Math.floor(e-s.top);if(this._lost||!(r>=0&&o>=0&&rv===a[S]))return c.tile;let h=n*2+1;(!this._measure||this._measure.target.width!==h)&&(this._measure?.target.dispose(),this._measure={target:new Fe(h,h,this._float?{type:Ge}:{}),ids:this._float?new Float32Array(h*h*4):new Uint8Array(h*h*4),depths:this._float?null:new Uint8Array(h*h*4)});let{target:d,ids:u,depths:p}=this._measure,g=r-n,_=o-n;this._render(this._material,g,_,s,d,u);let m=(v,S)=>{let A=Math.floor(v)-g,x=Math.floor(S)-_;return A>=0&&A=0&&x(this._float?Math.round(u[v*4+3]):f.getUint32(v*4,!0))-1,E=b(m(r,o)),M=null;if(E>=0){p&&this._render(this._depthMaterial,g,_,s,d,p);let v=p&&new DataView(p.buffer),S=l.matrixWorldInverse.elements.slice(),A=U=>{if(v)return v.getFloat32(U*4,!0);let C=U*4;return-(S[2]*u[C]+S[6]*u[C+1]+S[10]*u[C+2]+S[14])},x=m(r,o),T=this._float?new I().fromArray(u,x*4):this._depthPoint(r,o,s,A(x)),R=new Set([E]),L=this.scene.slotElement(E);if(L>=0)for(let U=0;U=0&&!R.has(C)&&this.scene.slotElement(C)===L&&R.add(C)}let N=l.isPerspectiveCamera;M={rect:s,point:T,element:L,slots:R,depthAt(U,C,B){let z=m(U,C),W=z<0?-1:b(z);if(W<0)return 1/0;if(W!==B)return A(z);let F=G=>N?1/A(G):A(G),D=F(z);function X(G,Q,lt){let ct=Math.sign(lt),tt=m(U+ct*G,C+ct*Q);if(tt>=0&&b(tt)===W)return(F(tt)-D)*Math.abs(lt);let V=m(U-ct*G,C-ct*Q);return V>=0&&b(V)===W?(D-F(V))*Math.abs(lt):0}let Z=D+X(1,0,U-Math.floor(U)-.5)+X(0,1,C-Math.floor(C)-.5);return Z>0?N?1/Z:Z:A(z)}}}return this._lastTile={camera:l,key:a.slice(),radius:n,tile:M},this._last={camera:l,key:this._lastTile.key,hit:M},M}_pick(t,e,n){let s=this._render(this._material,t,e,n),r=(this._float?Math.round(s[3]):new Uint32Array(s.buffer)[0])-1;if(r<0)return null;let o=this.scene.slotElement(r);if(this._float)return{element:o,point:new I(s[0],s[1],s[2])};let a=this._render(this._depthMaterial,t,e,n);return{element:o,point:this._depthPoint(t,e,n,new DataView(a.buffer).getFloat32(0,!0))}}_depthPoint(t,e,n,s){let r=this.camera,o=new I((t+.5)/n.width*2-1,1-(e+.5)/n.height*2,-1).applyMatrix4(r.projectionMatrixInverse);return r.isPerspectiveCamera?o.multiplyScalar(-s/o.z):o.z=-s,o.applyMatrix4(r.matrixWorld)}_render(t,e,n,s,r=this._target,o=this._pixel){let{renderer:a,camera:l}=this,c={target:a.getRenderTarget(),color:a.getClearColor(new Ft),alpha:a.getClearAlpha()},h=this.scene._buckets[0]?.material;t.clippingPlanes=h?.clippingPlanes??null,t.clipIntersection=h?.clipIntersection??!1,l.updateMatrixWorld(),l.setViewOffset(s.width,s.height,e,n,r.width,r.height);try{a.setRenderTarget(r),a.setClearColor(0,0),this.scene.withMaterial(t,()=>a.render(this.scene.root,l),{pickCamera:l}),a.readRenderTargetPixels(r,0,0,r.width,r.height,o)}finally{a.setRenderTarget(c.target),a.setClearColor(c.color,c.alpha),l.clearViewOffset()}return o}};var tl=33.333333333333336,Wv=200,Pf=1e6,Xv=20,el=class{constructor(t,e,n=1e7){this.scene=t,this.budget=n,this.minPixels=0,this._requestRender=e,this._last=new Float64Array(32),this._seen=!1,this._requestedAt=null,this._frame=null,this._cost=0,this._fastFrames=0,this._refine=!1,this._settle=0}requested(t){this._requestedAt??(this._requestedAt=t)}begin(t,e,n){t.updateMatrixWorld();let s=this._requestedAt===null?0:Math.max(n-this._requestedAt,0);this._requestedAt=null;let r=this._moved(t);this._frame=r?{start:n,waited:s}:null,this.minPixels=r?this.scene.detailThreshold(t,e,this.budget,this._refine):0,r||(this._fastFrames=0),this.scene.setDetail(this.minPixels,e),r&&(clearTimeout(this._settle),this.minPixels>0&&(this._settle=setTimeout(this._requestRender,Wv)))}end(t){this.scene.setDetail(0),this._frame&&this._adapt(this._frame.waited+(t-this._frame.start)),this._frame=null}_adapt(t){this._cost=this._cost?this._cost*.8+t*.2:t,t>tl*1.1?(this._refine=!1,this._fastFrames=0):this._refine||(this._fastFrames=this.minPixels>0&&t=Xv),this._cost>tl*1.1?this.budget=Math.max(this.budget*.9,Pf):this._cost0&&(this.budget=Math.max(Math.min(this.budget*1.05,this.scene.visibleCost),Pf))}_moved(t){let e=this._last,n=[...t.matrixWorld.elements,...t.projectionMatrix.elements],s=(o,a)=>a!==26&&a!==30&&Math.abs(o-e[a])>1e-9*Math.max(1,Math.abs(o)),r=this._seen&&n.some(s);return this._seen=!0,e.set(n),r}};var Tn,Ds,nl,il=class extends EventTarget{constructor(){super(...arguments);yl(this,Ds);yl(this,Tn,new Set)}get size(){return ii(this,Tn).size}has(e){return ii(this,Tn).has(e)}values(){return ii(this,Tn).values()}set(e){Gh(this,Tn,new Set(e)),zr(this,Ds,nl).call(this)}toggle(e){ii(this,Tn).delete(e)||ii(this,Tn).add(e),zr(this,Ds,nl).call(this)}clear(){ii(this,Tn).size!==0&&(ii(this,Tn).clear(),zr(this,Ds,nl).call(this))}};Tn=new WeakMap,Ds=new WeakSet,nl=function(){this.dispatchEvent(new Event("change"))};function Lf(i,t,e){if(t!=="window"&&t!=="crossing")throw new RangeError(`Unknown box select mode: ${t}`);let n=i.x+i.width,s=i.y+i.height,r=t==="window"?o=>o.minX>=i.x&&o.maxX<=n&&o.minY>=i.y&&o.maxY<=s:o=>o.maxX>=i.x&&o.minX<=n&&o.maxY>=i.y&&o.minY<=s;return e.filter(r).map(o=>o.index)}function Df(i,t,e){let n=new kt().multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse).elements,{left:s,top:r,width:o,height:a}=e,l=new ie,c=[];for(let h=0;hn===l?r(l):o(l));let m=[...t.children].find(v=>Nf.indexOf(v.dataset.panel)>g);t.insertBefore(_,m??null);let f=et("section","ioviewer-side-panel ioviewer-floating");f.dataset.panel=l,f.hidden=!0,f.setAttribute("aria-label",h);let b=Ke("ioviewer-panel-close",Zt.close,st("close"));b.addEventListener("click",()=>r(l));let E=et("header","ioviewer-panel-header");E.append(et("h2","",h),b);let M=et("div","ioviewer-panel-body");f.append(E,M),i.append(f),e.set(l,{button:_,panel:f,onClose:p}),d(M)}return{rail:t,openPanel:o,closePanel:r,registerPanel:a}}var Ff=[{id:"navigation",items:["orbit","pan","fit","projection"]},{id:"sections",items:["plane","box","resetSections"]},{id:"measure",items:["distance"]},{id:"display",items:["displayMode","grids","opacity"]},{id:"view",items:["fullscreen"]}];function Bf(i,t){let e=et("div","ioviewer-toolbar ioviewer-floating");e.setAttribute("role","toolbar");let n=new Map;for(let a of t){let l=et("div","ioviewer-toolbar-group");l.setAttribute("role","group"),l.setAttribute("aria-label",st(`group.${a.id}`));let c=et("div","ioviewer-toolbar-row");for(let h of a.items){let d=Ke("ioviewer-tool",Zt[h],st(`tool.${h}`));d.dataset.tool=h,d.setAttribute("aria-disabled","true");let u={button:d,handler:null};d.addEventListener("click",()=>{d.getAttribute("aria-disabled")!=="true"&&u.handler?.()}),n.set(h,u),c.append(d)}l.append(c,et("div","ioviewer-toolbar-label",st(`group.${a.id}`))),e.append(l)}i.append(e),new ResizeObserver(()=>i.style.setProperty("--toolbar-height",`${e.offsetHeight}px`)).observe(e);function r(a){let l=n.get(a);if(!l)throw new RangeError(`Unknown tool: ${a}`);return l}function o(a,l){r(a).button.setAttribute("aria-disabled",String(!l))}return{element:e,setHandler(a,l){r(a).handler=l,o(a,!0)},setEnabled:o,setActive(a,l){let{button:c}=r(a);c.classList.toggle("active",l),c.setAttribute("aria-pressed",String(l))}}}var qv="input, textarea, select, [contenteditable]";function _h(i){return i.key==="ContextMenu"||i.code==="ContextMenu"||i.shiftKey&&(i.key==="F10"||i.code==="F10")}function Of(i){if(i.ctrlKey||i.altKey||i.metaKey||i.repeat||i.target?.closest?.(qv))return null;if(_h(i))return"contextMenu";switch(i.code){case"KeyH":return i.shiftKey?"showAll":"hide";case"KeyI":return i.shiftKey?null:"isolate";case"KeyF":return i.shiftKey?null:"zoomTo";case"Escape":return"escape";default:return null}}function zf(i,t,e,n,s){let r=et("details","ioviewer-tree-filters");r.hidden=i.length===0;let o=et("summary","",st("filters.title")),a=et("div","ioviewer-filter-fields"),l=new Map(t.map(({id:v,name:S})=>[v,S||`#${v}`])),c=v=>v.modelId??t[0]?.id??null,h=v=>v.levelId??(v.level||null),d=v=>v.category??"",u=[{name:st("filters.model"),key:c,labels:new Map},{name:st("level"),key:h,labels:new Map},{name:st("category"),key:d,labels:new Map}],[p,g,_]=u,m=et("div","ioviewer-filter-actions"),f=et("button","ioviewer-text-button",st("filters.clear"));f.type="button",f.addEventListener("click",()=>{for(let v of u)v.select&&(v.select.selectedIndex=0);e.value="",n(),e.focus()});let b=et("button","ioviewer-text-button",st("filters.isolate"));b.type="button",b.addEventListener("click",s),m.append(f,b),r.append(o,a,m);function E(){if(r.open){r.removeEventListener("toggle",E);for(let v of i){let S=c(v),A=l.get(S)??(S==null?"":`#${S}`);S!=null&&p.labels.set(S,A);let x=h(v);if(!g.labels.has(x)){let R=v.level||(x==null?st("filters.noLevel"):`#${x}`);g.labels.set(x,x!=null&&t.length>1&&A?`${R} \xB7 ${A}`:R)}let T=d(v);_.labels.set(T,T||st("noCategory"))}for(let v of u){if(!v.labels.size)continue;let S=new Map;for(let R of v.labels.values())S.set(R,(S.get(R)??0)+1);let A=[...v.labels].map(([R,L])=>[R,S.get(L)>1?`${L} (#${R})`:L]);A.sort((R,L)=>R[1].localeCompare(L[1])),v.keys=A.map(([R])=>R);let x=v.select=et("select");x.append(new Option(st("filters.all"),""));for(let[R,[,L]]of A.entries())x.append(new Option(L,String(R+1)));x.addEventListener("change",n);let T=et("label","ioviewer-filter-field");T.append(et("span","",v.name),x),a.append(T)}}}r.addEventListener("toggle",E);function M(){return u.filter(v=>v.select?.selectedIndex>0)}return{element:r,predicate(){let v=M().map(({select:S,keys:A,key:x})=>({key:x,value:A[S.selectedIndex-1]}));return v.length?S=>v.every(({key:A,value:x})=>A(S)===x):null},update(v,S){let A=M().length;o.textContent=A?`${st("filters.title")} (${A})`:st("filters.title"),f.disabled=!A&&!v,b.disabled=!S}}}var vi=24,Yv=8;function xh(i,t,e,n,s){let r=Math.min(n,Math.max(0,Math.floor(i/t)-s)),o=Math.min(n,Math.ceil((i+e)/t)+s);return{start:r,end:Math.max(r,o)}}function $v(i){let t=null;return e=>{let n=e.trim().toLowerCase();t??(t=i.map(r=>`${r.name??""} +}`,Lf=i=>i&&{element:i.element,point:i.point.clone()};function _h(i,t){let e=new He({vertexShader:Yv,fragmentShader:$v,uniforms:i,defines:t?{[t]:""}:{},side:Ie,clipping:!0});return e.index0AttributeName="q",e}var Qa=class{constructor(t,e,n,s={}){this.renderer=t,this.scene=e,this.camera=n,this._lost=!1,t.domElement.addEventListener("webglcontextlost",()=>this._lost=!0),this._last=null,this._lastTile=null,this._key=new Float64Array(36),e.root.addEventListener("change",o=>{o.detail.kind!=="appearance"&&(this._last=this._lastTile=null)});let r=e.slotUniforms;this._float=s.pickFloat!==!1&&t.extensions.has("EXT_color_buffer_float"),this._float?(this._material=_h(r,null),this._target=new Fe(1,1,{type:Ge}),this._pixel=new Float32Array(4)):(this._material=_h(r,"IO_PICK_RGBA8"),this._depthMaterial=_h(r,"IO_PICK_DEPTH"),this._target=new Fe(1,1),this._pixel=new Uint8Array(4))}pick(t,e){let n=this.renderer.domElement.getBoundingClientRect(),s=Math.floor(t-n.left),r=Math.floor(e-n.top);if(this._lost||!(s>=0&&r>=0&&sh===o[d]))return Lf(l.hit);let c=this._pick(s,r,n);return this._last={camera:a,key:o.slice(),hit:c},Lf(c)}_sampleKey(t,e,n){this.camera.updateMatrixWorld();let s=this._key;return s.set([t,e,n.width,n.height]),s.set(this.camera.matrixWorld.elements,4),s.set(this.camera.projectionMatrix.elements,20),s}measureTile(t,e,n){let s=this.renderer.domElement.getBoundingClientRect(),r=Math.floor(t-s.left),o=Math.floor(e-s.top);if(this._lost||!(r>=0&&o>=0&&rv===a[S]))return c.tile;let h=n*2+1;(!this._measure||this._measure.target.width!==h)&&(this._measure?.target.dispose(),this._measure={target:new Fe(h,h,this._float?{type:Ge}:{}),ids:this._float?new Float32Array(h*h*4):new Uint8Array(h*h*4),depths:this._float?null:new Uint8Array(h*h*4)});let{target:d,ids:u,depths:p}=this._measure,g=r-n,_=o-n;this._render(this._material,g,_,s,d,u);let m=(v,S)=>{let A=Math.floor(v)-g,x=Math.floor(S)-_;return A>=0&&A=0&&x(this._float?Math.round(u[v*4+3]):f.getUint32(v*4,!0))-1,E=b(m(r,o)),M=null;if(E>=0){p&&this._render(this._depthMaterial,g,_,s,d,p);let v=p&&new DataView(p.buffer),S=l.matrixWorldInverse.elements.slice(),A=U=>{if(v)return v.getFloat32(U*4,!0);let C=U*4;return-(S[2]*u[C]+S[6]*u[C+1]+S[10]*u[C+2]+S[14])},x=m(r,o),T=this._float?new I().fromArray(u,x*4):this._depthPoint(r,o,s,A(x)),R=new Set([E]),L=this.scene.slotElement(E);if(L>=0)for(let U=0;U=0&&!R.has(C)&&this.scene.slotElement(C)===L&&R.add(C)}let N=l.isPerspectiveCamera;M={rect:s,point:T,element:L,slots:R,depthAt(U,C,B){let z=m(U,C),W=z<0?-1:b(z);if(W<0)return 1/0;if(W!==B)return A(z);let F=G=>N?1/A(G):A(G),D=F(z);function X(G,Q,lt){let ct=Math.sign(lt),et=m(U+ct*G,C+ct*Q);if(et>=0&&b(et)===W)return(F(et)-D)*Math.abs(lt);let V=m(U-ct*G,C-ct*Q);return V>=0&&b(V)===W?(D-F(V))*Math.abs(lt):0}let Z=D+X(1,0,U-Math.floor(U)-.5)+X(0,1,C-Math.floor(C)-.5);return Z>0?N?1/Z:Z:A(z)}}}return this._lastTile={camera:l,key:a.slice(),radius:n,tile:M},this._last={camera:l,key:this._lastTile.key,hit:M},M}_pick(t,e,n){let s=this._render(this._material,t,e,n),r=(this._float?Math.round(s[3]):new Uint32Array(s.buffer)[0])-1;if(r<0)return null;let o=this.scene.slotElement(r);if(this._float)return{element:o,point:new I(s[0],s[1],s[2])};let a=this._render(this._depthMaterial,t,e,n);return{element:o,point:this._depthPoint(t,e,n,new DataView(a.buffer).getFloat32(0,!0))}}_depthPoint(t,e,n,s){let r=this.camera,o=new I((t+.5)/n.width*2-1,1-(e+.5)/n.height*2,-1).applyMatrix4(r.projectionMatrixInverse);return r.isPerspectiveCamera?o.multiplyScalar(-s/o.z):o.z=-s,o.applyMatrix4(r.matrixWorld)}_render(t,e,n,s,r=this._target,o=this._pixel){let{renderer:a,camera:l}=this,c={target:a.getRenderTarget(),color:a.getClearColor(new Ft),alpha:a.getClearAlpha()},h=this.scene._buckets[0]?.material;t.clippingPlanes=h?.clippingPlanes??null,t.clipIntersection=h?.clipIntersection??!1,l.updateMatrixWorld(),l.setViewOffset(s.width,s.height,e,n,r.width,r.height);try{a.setRenderTarget(r),a.setClearColor(0,0),this.scene.withMaterial(t,()=>a.render(this.scene.root,l),{pickCamera:l}),a.readRenderTargetPixels(r,0,0,r.width,r.height,o)}finally{a.setRenderTarget(c.target),a.setClearColor(c.color,c.alpha),l.clearViewOffset()}return o}};var tl=33.333333333333336,Zv=200,Df=1e6,Jv=20,el=class{constructor(t,e,n=1e7){this.scene=t,this.budget=n,this.minPixels=0,this._requestRender=e,this._last=new Float64Array(32),this._seen=!1,this._requestedAt=null,this._frame=null,this._cost=0,this._fastFrames=0,this._refine=!1,this._settle=0}requested(t){this._requestedAt??(this._requestedAt=t)}begin(t,e,n){t.updateMatrixWorld();let s=this._requestedAt===null?0:Math.max(n-this._requestedAt,0);this._requestedAt=null;let r=this._moved(t);this._frame=r?{start:n,waited:s}:null,this.minPixels=r?this.scene.detailThreshold(t,e,this.budget,this._refine):0,r||(this._fastFrames=0),this.scene.setDetail(this.minPixels,e),r&&(clearTimeout(this._settle),this.minPixels>0&&(this._settle=setTimeout(this._requestRender,Zv)))}end(t){this.scene.setDetail(0),this._frame&&this._adapt(this._frame.waited+(t-this._frame.start)),this._frame=null}_adapt(t){this._cost=this._cost?this._cost*.8+t*.2:t,t>tl*1.1?(this._refine=!1,this._fastFrames=0):this._refine||(this._fastFrames=this.minPixels>0&&t=Jv),this._cost>tl*1.1?this.budget=Math.max(this.budget*.9,Df):this._cost0&&(this.budget=Math.max(Math.min(this.budget*1.05,this.scene.visibleCost),Df))}_moved(t){let e=this._last,n=[...t.matrixWorld.elements,...t.projectionMatrix.elements],s=(o,a)=>a!==26&&a!==30&&Math.abs(o-e[a])>1e-9*Math.max(1,Math.abs(o)),r=this._seen&&n.some(s);return this._seen=!0,e.set(n),r}};var Tn,Ns,nl,il=class extends EventTarget{constructor(){super(...arguments);yl(this,Ns);yl(this,Tn,new Set)}get size(){return ii(this,Tn).size}has(e){return ii(this,Tn).has(e)}values(){return ii(this,Tn).values()}set(e){Wh(this,Tn,new Set(e)),zr(this,Ns,nl).call(this)}toggle(e){ii(this,Tn).delete(e)||ii(this,Tn).add(e),zr(this,Ns,nl).call(this)}clear(){ii(this,Tn).size!==0&&(ii(this,Tn).clear(),zr(this,Ns,nl).call(this))}};Tn=new WeakMap,Ns=new WeakSet,nl=function(){this.dispatchEvent(new Event("change"))};function Nf(i,t,e){if(t!=="window"&&t!=="crossing")throw new RangeError(`Unknown box select mode: ${t}`);let n=i.x+i.width,s=i.y+i.height,r=t==="window"?o=>o.minX>=i.x&&o.maxX<=n&&o.minY>=i.y&&o.maxY<=s:o=>o.maxX>=i.x&&o.minX<=n&&o.maxY>=i.y&&o.minY<=s;return e.filter(r).map(o=>o.index)}function Uf(i,t,e){let n=new kt().multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse).elements,{left:s,top:r,width:o,height:a}=e,l=new ie,c=[];for(let h=0;hn===l?r(l):o(l));let m=[...t.children].find(v=>Ff.indexOf(v.dataset.panel)>g);t.insertBefore(_,m??null);let f=tt("section","ioviewer-side-panel ioviewer-floating");f.dataset.panel=l,f.hidden=!0,f.setAttribute("aria-label",h);let b=Ke("ioviewer-panel-close",Zt.close,st("close"));b.addEventListener("click",()=>r(l));let E=tt("header","ioviewer-panel-header");E.append(tt("h2","",h),b);let M=tt("div","ioviewer-panel-body");f.append(E,M),i.append(f),e.set(l,{button:_,panel:f,onClose:p}),d(M)}return{rail:t,openPanel:o,closePanel:r,registerPanel:a}}var Of=[{id:"navigation",items:["orbit","pan","fit","projection"]},{id:"sections",items:["plane","box","resetSections"]},{id:"measure",items:["distance"]},{id:"display",items:["displayMode","grids","opacity"]},{id:"view",items:["fullscreen"]}];function zf(i,t){let e=tt("div","ioviewer-toolbar ioviewer-floating");e.setAttribute("role","toolbar");let n=new Map;for(let a of t){let l=tt("div","ioviewer-toolbar-group");l.setAttribute("role","group"),l.setAttribute("aria-label",st(`group.${a.id}`));let c=tt("div","ioviewer-toolbar-row");for(let h of a.items){let d=Ke("ioviewer-tool",Zt[h],st(`tool.${h}`));d.dataset.tool=h,d.setAttribute("aria-disabled","true");let u={button:d,handler:null};d.addEventListener("click",()=>{d.getAttribute("aria-disabled")!=="true"&&u.handler?.()}),n.set(h,u),c.append(d)}l.append(c,tt("div","ioviewer-toolbar-label",st(`group.${a.id}`))),e.append(l)}i.append(e),new ResizeObserver(()=>i.style.setProperty("--toolbar-height",`${e.offsetHeight}px`)).observe(e);function r(a){let l=n.get(a);if(!l)throw new RangeError(`Unknown tool: ${a}`);return l}function o(a,l){r(a).button.setAttribute("aria-disabled",String(!l))}return{element:e,setHandler(a,l){r(a).handler=l,o(a,!0)},setEnabled:o,setActive(a,l){let{button:c}=r(a);c.classList.toggle("active",l),c.setAttribute("aria-pressed",String(l))}}}var Kv="input, textarea, select, [contenteditable]";function xh(i){return i.key==="ContextMenu"||i.code==="ContextMenu"||i.shiftKey&&(i.key==="F10"||i.code==="F10")}function kf(i){if(i.ctrlKey||i.altKey||i.metaKey||i.repeat||i.target?.closest?.(Kv))return null;if(xh(i))return"contextMenu";switch(i.code){case"KeyH":return i.shiftKey?"showAll":"hide";case"KeyI":return i.shiftKey?null:"isolate";case"KeyF":return i.shiftKey?null:"zoomTo";case"Escape":return"escape";default:return null}}function Hf(i,t,e,n,s){let r=tt("details","ioviewer-tree-filters");r.hidden=i.length===0;let o=tt("summary","",st("filters.title")),a=tt("div","ioviewer-filter-fields"),l=new Map(t.map(({id:v,name:S})=>[v,S||`#${v}`])),c=v=>v.modelId??t[0]?.id??null,h=v=>v.levelId??(v.level||null),d=v=>v.category??"",u=[{name:st("filters.model"),key:c,labels:new Map},{name:st("level"),key:h,labels:new Map},{name:st("category"),key:d,labels:new Map}],[p,g,_]=u,m=tt("div","ioviewer-filter-actions"),f=tt("button","ioviewer-text-button",st("filters.clear"));f.type="button",f.addEventListener("click",()=>{for(let v of u)v.select&&(v.select.selectedIndex=0);e.value="",n(),e.focus()});let b=tt("button","ioviewer-text-button",st("filters.isolate"));b.type="button",b.addEventListener("click",s),m.append(f,b),r.append(o,a,m);function E(){if(r.open){r.removeEventListener("toggle",E);for(let v of i){let S=c(v),A=l.get(S)??(S==null?"":`#${S}`);S!=null&&p.labels.set(S,A);let x=h(v);if(!g.labels.has(x)){let R=v.level||(x==null?st("filters.noLevel"):`#${x}`);g.labels.set(x,x!=null&&t.length>1&&A?`${R} \xB7 ${A}`:R)}let T=d(v);_.labels.set(T,T||st("noCategory"))}for(let v of u){if(!v.labels.size)continue;let S=new Map;for(let R of v.labels.values())S.set(R,(S.get(R)??0)+1);let A=[...v.labels].map(([R,L])=>[R,S.get(L)>1?`${L} (#${R})`:L]);A.sort((R,L)=>R[1].localeCompare(L[1])),v.keys=A.map(([R])=>R);let x=v.select=tt("select");x.append(new Option(st("filters.all"),""));for(let[R,[,L]]of A.entries())x.append(new Option(L,String(R+1)));x.addEventListener("change",n);let T=tt("label","ioviewer-filter-field");T.append(tt("span","",v.name),x),a.append(T)}}}r.addEventListener("toggle",E);function M(){return u.filter(v=>v.select?.selectedIndex>0)}return{element:r,predicate(){let v=M().map(({select:S,keys:A,key:x})=>({key:x,value:A[S.selectedIndex-1]}));return v.length?S=>v.every(({key:A,value:x})=>A(S)===x):null},update(v,S){let A=M().length;o.textContent=A?`${st("filters.title")} (${A})`:st("filters.title"),f.disabled=!A&&!v,b.disabled=!S}}}var yi=24,jv=8;function vh(i,t,e,n,s){let r=Math.min(n,Math.max(0,Math.floor(i/t)-s)),o=Math.min(n,Math.ceil((i+e)/t)+s);return{start:r,end:Math.max(r,o)}}function Qv(i){let t=null;return e=>{let n=e.trim().toLowerCase();t??(t=i.map(r=>`${r.name??""} ${r.type??""} ${r.id} -${r.sourceId??""}`.toLowerCase()));let s=[];for(let r=0;r{let s=e.category??"";t.has(s)||t.set(s,[]),t.get(s).push(n)}),[...t].map(([e,n])=>({name:e,indices:n})).sort((e,n)=>e.name.localeCompare(n.name))}function kf(i,{elements:t,models:e,selection:n,scene:s,zoomToElement:r,openContextMenu:o}){let a=Zv(t),l=new Int32Array(t.length);a.forEach((G,Q)=>G.indices.forEach(lt=>l[lt]=Q));let c=new Uint8Array(a.length),h=new Int32Array(a.length),d=new Uint32Array(a.length),u=$v(t),p="",g=!1,_=new Int32Array(0),m=0,f=-1,b=null,E=!1,M=et("input","ioviewer-tree-search");M.type="search",M.placeholder=st("searchPlaceholder"),M.setAttribute("aria-label",st("searchPlaceholder"));let v=et("div","ioviewer-tree");v.setAttribute("role","tree"),v.setAttribute("aria-label",st("panel.model")),v.setAttribute("aria-multiselectable","true"),v.tabIndex=-1;let S=et("div","ioviewer-tree-spacer");S.setAttribute("role","presentation"),v.append(S);let A=et("div","ioviewer-tree-empty",st("noMatches")),x=zf(t,e,M,D,()=>s.isolate(_));i.append(x.element,M,v,A);function T(){let G=_[m],Q=x.predicate();if(g=!!(p||Q),g){let ct=p?u(p):t.keys();if(Q){let tt=[];for(let V of ct)Q(t[V])&&tt.push(V);_=Int32Array.from(tt)}else _=Int32Array.from(ct)}else{let ct=a.length;a.forEach((V,j)=>c[j]&&(ct+=V.indices.length)),_=new Int32Array(ct);let tt=0;a.forEach((V,j)=>{if(h[j]=tt,_[tt++]=-(j+1),c[j])for(let ut of V.indices)_[tt++]=ut})}let lt=_.indexOf(G);m=lt>=0?lt:0,S.style.height=`${_.length*vi}px`,A.hidden=_.length>0||!g,x.update(p,g&&_.some(ct=>s.instancesOf(ct).length>0)),R()}function R(G=v.contains(document.activeElement)){let Q=v.clientHeight;if(Q===0||_.length===0){S.replaceChildren();return}let lt=v.scrollTop,{start:ct,end:tt}=xh(lt,vi,Q,_.length,Yv);!G&&(m=tt)&&(m=Math.min(_.length-1,Math.floor(lt/vi)));let V=[];m=tt&&V.push(L(m)),S.replaceChildren(...V),G&&S.querySelector('[tabindex="0"]')?.focus({preventScroll:!0})}function L(G){let Q=_[G],lt=Q<0?-Q-1:l[Q],ct=Q<0?d[lt]===a[lt].indices.length:n.has(Q),tt=et("div","tree-row");if(tt.style.top=`${G*vi}px`,tt.style.height=`${vi}px`,tt.dataset.row=G,tt.tabIndex=G===m?0:-1,tt.setAttribute("role","treeitem"),tt.classList.toggle("selected",ct),tt.setAttribute("aria-selected",String(ct)),Q<0){tt.classList.add("tree-category"),tt.setAttribute("aria-level","1"),tt.setAttribute("aria-posinset",String(lt+1)),tt.setAttribute("aria-setsize",String(a.length)),tt.setAttribute("aria-expanded",String(!!c[lt]));let V=et("span","tree-chevron");V.innerHTML=Zt.chevron;let{name:j,indices:ut}=a[lt];tt.append(V,et("span","tree-name",j||st("noCategory")),et("span","tree-count",Cr(ut.length)))}else{let V=t[Q];tt.classList.add("tree-element"),tt.setAttribute("aria-level",g?"1":"2"),tt.setAttribute("aria-posinset",String(g?G+1:G-h[lt])),tt.setAttribute("aria-setsize",String(g?_.length:a[lt].indices.length)),tt.classList.toggle("tree-child",!g),tt.classList.toggle("tree-hidden",!s.isVisible(Q)),tt.append(et("span","tree-name",V.name||`#${V.id}`),et("span","tree-type",V.type??""))}return tt}function N(G){let Q=v.clientHeight;if(Q===0){f=G;return}let lt=G*vi;ltv.scrollTop+Q&&(v.scrollTop=lt+vi-Q)}function U(G){m=G,N(G),R(!0)}function C(G){let Q=l[G];!g&&!c[Q]&&(c[Q]=1,T());let lt=_.indexOf(G);lt>=0&&(v.contains(document.activeElement)||(m=lt),N(lt)),R()}function B(G){E=!0;try{n.set(G)}finally{E=!1}}function z(G,Q){let lt=_.indexOf(b);lt<0&&(lt=G,b=_[G]);let ct=_.subarray(Math.min(lt,G),Math.max(lt,G)+1).filter(tt=>tt>=0);ct.length>0&&B(Q?[...n.values(),...ct]:ct)}function W(G){b=G;let Q=-G-1,lt=G<0?a[Q].indices:[G],ct=G<0?d[Q]===lt.length:n.has(G),tt=new Set(n.values());for(let V of lt)ct?tt.delete(V):tt.add(V);B(tt)}function F(G,Q,lt){G>=0&&!n.has(G)&&(b=G,B([G]));let ct=G>=0?G:n.values().next().value??null;o(Q,lt,ct,()=>{let tt=_.indexOf(G);tt>=0?U(tt):M.focus()})}M.addEventListener("focus",()=>{S.firstElementChild||Z()});function D(){p=M.value.trim(),v.scrollTop=0,f=-1,m=-1,T()}M.addEventListener("input",D),v.addEventListener("scroll",()=>R()),v.addEventListener("focusin",G=>{let Q=G.target.closest(".tree-row");!Q||Q.tabIndex===0||(S.querySelector('[tabindex="0"]')?.setAttribute("tabindex","-1"),m=Number(Q.dataset.row),Q.tabIndex=0)}),v.addEventListener("keydown",G=>{let Q=G.target.closest(".tree-row");if(!Q||G.ctrlKey||G.altKey||G.metaKey)return;let lt=Number(Q.dataset.row),ct=_[lt];if(_h(G)){if(G.preventDefault(),!G.repeat){let{left:V,bottom:j}=Q.getBoundingClientRect();F(ct,V,j)}return}if(G.key===" "){G.preventDefault(),G.repeat||(G.shiftKey?z(lt,!1):W(ct));return}if(G.shiftKey)return;let tt=lt;switch(G.key){case"ArrowUp":tt=Math.max(0,lt-1);break;case"ArrowDown":tt=Math.min(_.length-1,lt+1);break;case"Home":tt=0;break;case"End":tt=_.length-1;break;case"ArrowRight":ct<0&&(c[-ct-1]?tt=lt+1:(c[-ct-1]=1,T()));break;case"ArrowLeft":ct>=0&&!g?tt=h[l[ct]]:ct<0&&c[-ct-1]&&(c[-ct-1]=0,T());break;case"Enter":G.repeat||X(ct);break;default:return}G.preventDefault(),tt!==lt&&U(tt)});function X(G){if(G>=0){b=G,B([G]),r(G);return}c[-G-1]^=1,T()}v.addEventListener("click",G=>{let Q=G.target.closest(".tree-row");if(!Q)return;let lt=Number(Q.dataset.row),ct=G.ctrlKey||G.metaKey;G.shiftKey?z(lt,ct):ct?W(_[lt]):X(_[lt])}),v.addEventListener("contextmenu",G=>{let Q=G.target.closest(".tree-row");Q&&(G.preventDefault(),F(_[Number(Q.dataset.row)],G.clientX,G.clientY))});function Z(){f>=0&&v.clientHeight>0&&(N(f),f=-1),R()}new ResizeObserver(Z).observe(v),n.addEventListener("change",()=>{let G=-1;d.fill(0);for(let Q of n.values())d[l[Q]]++,G=Q;if(E){R();return}b=null,G>=0?C(G):R()}),s.root.addEventListener("change",G=>G.detail.kind==="visibility"&&R()),T()}var Hf={element:["properties","hide","isolate","showAll","-","zoomTo","sectionBox","-","copyId"],empty:["showAll","fitAll","resetSections"]},Jv={hide:"H",isolate:"I",showAll:"Shift+H",zoomTo:"F"},sl=4;function Vf(i){let t=et("div","ioviewer-context-menu");t.setAttribute("role","menu"),t.setAttribute("aria-label",st("contextMenu")),t.hidden=!0,i.append(t);let e=new Map(Object.values(Hf).flat().filter(c=>c!=="-").map(c=>[c,{enabled:!1,handler:null}])),n=null;function s(){if(t.hidden)return;let c=t.contains(document.activeElement)?n:null;n=null,t.hidden=!0,t.replaceChildren(),window.removeEventListener("pointerdown",o,!0),window.removeEventListener("wheel",s,!0),window.removeEventListener("scroll",r,!0),window.removeEventListener("resize",s),c?.()}function r(c){i.contains(c.target)||s()}function o(c){t.contains(c.target)||(s(),Ja(c))}function a(c,h,d,u,p=null){let g=Hf[c];if(!g)throw new RangeError(`Unknown menu: ${c}`);s(),n=p;for(let f of g){if(f==="-"){let M=et("div","ioviewer-menu-separator");M.setAttribute("role","separator"),t.append(M);continue}let b=e.get(f),E=et("button","ioviewer-menu-item");E.type="button",E.tabIndex=-1,E.dataset.item=f,E.setAttribute("role","menuitem"),E.setAttribute("aria-disabled",String(!b.enabled)),b.enabled||(E.title=st("menu.unavailable")),E.append(et("span","",st(`menu.${f}`)),et("kbd","",Jv[f]??"")),E.addEventListener("click",()=>{b.enabled&&(s(),b.handler(u))}),t.append(E)}t.hidden=!1;let{width:_,height:m}=t.getBoundingClientRect();t.style.left=`${Math.max(sl,Math.min(h,innerWidth-_-sl))}px`,t.style.top=`${Math.max(sl,Math.min(d,innerHeight-m-sl))}px`,window.addEventListener("pointerdown",o,!0),window.addEventListener("wheel",s,!0),window.addEventListener("scroll",r,!0),window.addEventListener("resize",s),p&&t.querySelector("button")?.focus({preventScroll:!0})}t.addEventListener("keydown",c=>{if(c.key==="Tab"){s();return}if(c.key==="Escape"){c.preventDefault(),s();return}let h=[...t.querySelectorAll("button")],d=h.indexOf(document.activeElement),u;switch(c.key){case"ArrowDown":u=(d+1)%h.length;break;case"ArrowUp":u=(d+h.length-1)%h.length;break;case"Home":u=0;break;case"End":u=h.length-1;break;default:return}c.preventDefault(),h[u]?.focus({preventScroll:!0})});function l(c,{enabled:h=!0,handler:d}){let u=e.get(c);if(!u)throw new RangeError(`Unknown menu item: ${c}`);d&&(u.handler=d),u.enabled=h&&!!u.handler}return{element:t,open:a,close:s,setItem:l,get isOpen(){return!t.hidden}}}var Kv=1600;function Gf(i,t,e){let n=()=>i.textContent=`${st("selected")}: ${Cr(t.size)} \xB7 ${st("elements")}: ${Cr(e)}`;t.addEventListener("change",n),n()}function Wf(i,t){if(!t)return;let e=et("div","ioviewer-banner ioviewer-floating");e.setAttribute("role","status");let n=st("truncated").replace("{meshes}",t.meshes).replace("{total}",t.totalMeshes),s=Ke("ioviewer-panel-close",Zt.close,st("close")),r=new ResizeObserver(()=>i.style.setProperty("--banner-height",`${e.offsetHeight}px`));s.addEventListener("click",()=>{r.disconnect(),i.style.removeProperty("--banner-height"),e.remove()}),e.append(et("span","",n),s),i.append(e),r.observe(e)}function Ns(i,t){let e=et("div","ioviewer-toast",t);e.setAttribute("role","status"),i.append(e),setTimeout(()=>e.remove(),Kv)}function Xf(i,t){let e=et("table");for(let[s,r]of t)e.insertRow().append(et("th","",s),et("td","",String(r??"")));let n=et("section");return n.append(et("h3","",i),e),n}function qf(i,t,e){let n=et("h2","ioviewer-properties-title"),s=et("button","ioviewer-properties-close","\xD7");s.type="button",s.title=st("close"),s.setAttribute("aria-label",st("close")),s.addEventListener("click",()=>t.clear());let r=et("header");r.append(n,s);let o=et("div","ioviewer-properties-body");i.replaceChildren(r,o),i.hidden=!0,t.addEventListener("change",()=>{if(i.hidden=t.size===0,o.replaceChildren(),t.size!==1){n.textContent=`${st("selected")}: ${t.size}`;return}let[a]=t.values(),l=e.meta.elements[a];n.textContent=l.name||`#${l.id}`;let c=[[st("id"),l.id],[st("category"),l.category],[st("type"),l.type],[st("level"),l.level]];l.sourceId&&c.push([st("sourceId"),l.sourceId]),l.link&&c.push([st("link"),l.link]),o.append(Xf(st("elementGroup"),c));for(let[h,d]of Object.entries(e.props(l.id)??{}))o.append(Xf(h,Object.entries(d)))})}async function jv(i){if(await navigator.clipboard?.writeText(i).then(()=>!0,()=>!1))return!0;let t=document.createElement("textarea");t.value=i,t.setAttribute("readonly",""),t.className="ioviewer-offscreen",document.body.append(t),t.select();try{return document.execCommand("copy")}finally{t.remove()}}function Yf({root:i,data:t,scene:e,controls:n,picker:s,selection:r,measure:o}){let{meta:a}=t,l=()=>n.fitBox(e.visibleBox()),c={hide:()=>r.size&&e.setVisible([...r.values()],!1),isolate:()=>r.size&&e.isolate([...r.values()]),showAll:()=>e.showAll(),zoomTo:()=>{if(!r.size)return l();let[b,...E]=r.values(),M=e.elementBox(b);for(let v of E)M.union(e.elementBox(v));n.zoomToBox(M)},fitAll:l},h=Uf(i);h.registerPanel("model",{icon:Zt.model,title:st("panel.model"),render:b=>kf(b,{elements:a.elements,models:a.models??[],selection:r,scene:e,openContextMenu:_,zoomToElement:E=>n.zoomToBox(e.elementBox(E))})});let d=document.createElement("aside");d.id="ioviewer-properties",d.className="ioviewer-floating",i.append(d),qf(d,r,t);let u=Bf(i,Ff),p=b=>{n.setLeftButtonMode(b),u.setActive("orbit",b==="orbit"),u.setActive("pan",b==="pan")};u.setHandler("orbit",()=>p("orbit")),u.setHandler("pan",()=>p("pan")),p(n.leftButtonMode),u.setHandler("fit",l),u.setHandler("projection",()=>{let b=!n.camera.isOrthographicCamera;n.setProjection(b?"orthographic":"perspective"),u.setActive("projection",b)}),u.setActive("projection",!1),document.fullscreenEnabled&&(u.setHandler("fullscreen",()=>{(document.fullscreenElement?document.exitFullscreen():document.documentElement.requestFullscreen()).catch(()=>{u.setActive("fullscreen",!!document.fullscreenElement),Ns(i,st("fullscreenUnavailable"))})}),document.addEventListener("fullscreenchange",()=>u.setActive("fullscreen",!!document.fullscreenElement)));let g=Vf(i);function _(b,E,M,v){g.open(M===null?"empty":"element",b,E,M,v)}function m(b){if(g.isOpen)return;let E=b===document.body,M=(E?n.dom:b).getBoundingClientRect(),v=E?M.left+M.width/2:M.left,S=E?M.top+M.height/2:M.bottom;_(v,S,r.values().next().value??null,()=>b.focus({preventScroll:!0}))}g.setItem("properties",{handler:b=>r.set([b])});for(let b of["hide","isolate","showAll","zoomTo","fitAll"])g.setItem(b,{handler:c[b]});g.setItem("copyId",{handler:b=>jv(String(a.elements[b].id)).then(E=>Ns(i,st(E?"idCopied":"copyFailed")),()=>Ns(i,st("copyFailed")))}),n.addEventListener("contextmenu",b=>{let{x:E,y:M}=b.detail;if(o.active)return _(E,M,r.values().next().value??null);let v=s.pick(E,M);if(!v||v.element<0)return _(E,M,null);r.has(v.element)||r.set([v.element]),_(E,M,v.element)});let f=[];return window.addEventListener("keydown",b=>{if(b.defaultPrevented)return;let E=Of(b);if(E){if(b.preventDefault(),E==="contextMenu")return m(document.activeElement??document.body);if(E==="escape"&&!g.isOpen){f.some(M=>M())||r.clear();return}g.close(),E!=="escape"&&c[E]()}}),Gf(document.getElementById("ioviewer-status"),r,e.elementCount),Wf(i,a.truncated),{shell:h,toolbar:u,contextMenu:g,onEscape:b=>f.push(b)}}var vh={x:new I(1,0,0),y:new I(0,1,0),z:new I(0,0,1)};function yh(i){let t=vh[i];if(!t)throw new RangeError(`Unknown axis: ${i}`);return t.clone()}function $f(i,t,e){if(t.length===0)return!1;let n=s=>s.distanceToPoint(i)<0;return e?t.every(n):t.some(n)}function Zf(i,t,e,n){let s=i.clone().normalize(),r=s.dot(t)+e;return n?new ge(s,-r):new ge(s.negate(),r)}function Jf(i,t,e=0){if(t!=="keepInside"&&t!=="cutInside")throw new RangeError(`Unknown box mode: ${t}`);let{min:n,max:s}=i,r=[new ge(new I(1,0,0),-n.x),new ge(new I(-1,0,0),s.x),new ge(new I(0,1,0),-n.y),new ge(new I(0,-1,0),s.y),new ge(new I(0,0,1),-n.z),new ge(new I(0,0,-1),s.z)];if(e!==0){let o=i.getCenter(new I);for(let a of r){let l=a.distanceToPoint(o);a.normal.applyAxisAngle(vh.z,e),a.constant=l-a.normal.dot(o)}}return t==="keepInside"?{planes:r,intersection:!1}:{planes:r.map(o=>o.negate()),intersection:!0}}function Kf(i,t,e,n,s,r){let o=i.clone();if(n>0?o.max[e]=Math.max(i.max[e]+s,i.min[e]+r):o.min[e]=Math.min(i.min[e]-s,i.max[e]-r),t!==0){let a=o.getCenter(new I).sub(i.getCenter(new I));o.translate(a.clone().applyAxisAngle(vh.z,t).sub(a))}return o}function jf(i){let{min:t,max:e}=i;return Array.from({length:8},(n,s)=>new I(s&1?e.x:t.x,s&2?e.y:t.y,s&4?e.z:t.z))}function Qf(i,t,e){if(t.length===0||i.isEmpty())return!1;let n=jf(i),s=r=>n.every(o=>r.distanceToPoint(o)<0);return e?t.every(s):t.some(s)}function rl(i,t){let e=i.getSize(new I).multiplyScalar(.5);return Math.abs(t.x)*e.x+Math.abs(t.y)*e.y+Math.abs(t.z)*e.z}function Lr(i,t,e){let n=t.clone().sub(i.origin),s=e.dot(i.direction),r=1-s*s;return r<.03?null:(s*i.direction.dot(n)-e.dot(n))/r}function ol(i,t,e){let n=new I(1,0,0).applyQuaternion(t),s=new I(0,1,0).applyQuaternion(t),[r,o,a,l]=[1/0,-1/0,1/0,-1/0];for(let h of jf(i)){h.sub(e);let d=h.dot(n),u=h.dot(s);[r,o,a,l]=[Math.min(r,d),Math.max(o,d),Math.min(a,u),Math.max(l,u)]}return{center:e.clone().addScaledVector(n,(r+o)/2).addScaledVector(s,(a+l)/2),width:(o-r)*1.1,height:(l-a)*1.1}}var Dr=6,Qv=["off","planes","box"],ty=.05,Mh=new I(0,0,1),al=class extends EventTarget{constructor(t,e,n){super(),this.scene=t,this.modelBox=e.clone(),this.center=e.getCenter(new I),this.planes=[],this.active=-1,this.box=null,this.boxYaw=0,this.boxMode="keepInside",this.fill=!1,this.gizmoVisible=!0,this._mode="off",n&&this.restore(n)}restore({planes:t,box:e,cutInside:n}){this.modelBox.isEmpty()||(this.planes=t.map(({axis:s,normal:r,offset:o,flipped:a})=>{let l=new I().fromArray(r),c=new Ce().setFromUnitVectors(Mh,l);return{axis:s,quaternion:c,offset:o-l.dot(this.center),flipped:a,enabled:!0,rotated:!1}}),this.active=this.planes.length?0:-1,this.box=e?new ie(new I().fromArray(e.min),new I().fromArray(e.max)):null,this.boxYaw=0,this.boxMode=n?"cutInside":"keepInside",this.gizmoVisible=!1,this.setMode(this.box?"box":this.planes.length?"planes":"off"))}get mode(){return this._mode}setMode(t){if(!Qv.includes(t))throw new RangeError(`Unknown section mode: ${t}`);t==="box"&&!this.box&&this.fitBoxToShown()||(this._mode=t,this._changed(!0))}addPlane(t){let e=yh(t);if(this.planes.length>=Dr||this.modelBox.isEmpty())return null;let n=new Ce().setFromUnitVectors(Mh,e);return this.planes.push({axis:t,quaternion:n,offset:0,flipped:!1,enabled:!0,rotated:!1}),this.active=this.planes.length-1,this._mode="planes",this._changed(!0),this.active}removePlane(t){this._plane(t),this.planes.splice(t,1),(this.active>=this.planes.length||this.active>t)&&this.active--,this._changed(!0)}updatePlane(t,{offset:e,flipped:n,enabled:s,quaternion:r}){let o=this._plane(t);if(e!==void 0){if(!Number.isFinite(e))throw new RangeError(`Offset must be a finite number, got ${e}.`);o.offset=e}n!==void 0&&(o.flipped=!!n),s!==void 0&&(o.enabled=!!s),r&&(o.quaternion.copy(r).normalize(),o.rotated=o.axis!=="custom"&&this.normal(t).angleTo(yh(o.axis))>1e-6),this._changed(!0)}setActivePlane(t){this._plane(t),this.active=t,this._changed(!1)}normal(t){return Mh.clone().applyQuaternion(this._plane(t).quaternion)}extent(t){return rl(this.modelBox,this.normal(t))}origin(t){return this.center.clone().addScaledVector(this.normal(t),this._plane(t).offset)}clipPlane(t){let e=this._plane(t);return Zf(this.normal(t),this.center,e.offset,e.flipped)}setBox(t,e=0){if(t.isEmpty())throw new RangeError("The section box is empty.");e=tp(e),this.box=t.clone(),this.boxYaw=e,this._mode="box",this._changed(!0)}setBoxYaw(t){this.box&&(this.boxYaw=tp(t),this._changed(this.mode==="box"))}setBoxMode(t){if(t!=="keepInside"&&t!=="cutInside")throw new RangeError(`Unknown box mode: ${t}`);this.boxMode=t,this._changed(!0)}fitBoxToElements(t){let e=new ie;for(let s of t)e.union(this.scene.elementBox(s));if(e.isEmpty())return!1;let n=e.getSize(new I);return this.setBox(e.expandByScalar(ty*Math.max(n.x,n.y,n.z))),!0}fitBoxToShown(){let t=this.scene.visibleBox();if(t.isEmpty())return!1;let e=t.getSize(new I);return this.setBox(t.expandByScalar(.001*Math.max(e.x,e.y,e.z))),!0}setGizmoVisible(t){this.gizmoVisible=!!t,this._changed(!1)}setFill(t){this.fill=!!t,this._changed(!1)}reset(){this.planes=[],this.active=-1,this.box=null,this.boxYaw=0,this._mode="off",this._changed(!0)}clipping(){if(this._mode==="planes")return{planes:this.planes.flatMap((e,n)=>e.enabled?[this.clipPlane(n)]:[]),intersection:!1};if(this._mode==="box"&&this.box){let t=Jf(this.box,this.boxMode,this.boxYaw);if(!t.intersection&&this.boxYaw!==0){let e=this.box.getCenter(new I),n=this.box.getSize(new I).multiplyScalar(.5),s=Math.abs(Math.cos(this.boxYaw)),r=Math.abs(Math.sin(this.boxYaw));n.set(s*n.x+r*n.y,r*n.x+s*n.y,n.z),t.bounds=new ie(e.clone().sub(n),e.add(n))}return t}return{planes:[],intersection:!1}}isCut(t,{planes:e,intersection:n,bounds:s}=this.clipping()){return s&&!t.isEmpty()&&!s.intersectsBox(t)||Qf(t,e,n)}_plane(t){let e=this.planes[t];if(!Number.isInteger(t)||!e)throw new RangeError(`Plane index ${t} is out of range 0..${this.planes.length-1}.`);return e}_changed(t){if(t){let{planes:e,intersection:n}=this.clipping();this.scene.setClipping(e,n)}this.dispatchEvent(new Event("change"))}};function tp(i){if(!Number.isFinite(i))throw new RangeError("The section box angle must be finite.");return i>=-Math.PI&&i<=Math.PI?i:de.euclideanModulo(i+Math.PI,2*Math.PI)-Math.PI}var bh=80,ey=8,Eh=.8,ny=Math.sin(de.degToRad(12)),yi={x:"#ef4444",y:"#22c55e",z:"#3b82f6",centre:"#e2e8f0",hover:"#facc15",frame:"#93c5fd",fill:"#60a5fa"},Sh=["x","y","z"],iy=Math.cos(de.degToRad(12)),ll=new I(0,0,1),sy=i=>new en({color:i,depthTest:!1,depthWrite:!1,transparent:!0,opacity:.9}),ry=new en({visible:!1});function cl(i,t,e,n){let s=new Re,r=sy(t);for(let a of e)s.add(new _e(a,r));let o=new _e(n,ry);return o.userData.handle=s,s.add(o),s.userData={kind:i,color:t,material:r,proxy:o},s.traverse(a=>a.renderOrder=1e3),s}function wh(i,t,e=n=>n){let n=cl("rotate",yi[t],[e(new gs(Eh,.018,8,64))],e(new gs(Eh,.09,8,48)));return n.name=i,n.userData.axis=t,n}var hl=class extends EventTarget{constructor(t,e){super(),this.sections=t,this.dom=e,this.camera=null,this.group=new Re,this.group.name="sections",this._raycaster=new Di,this._drag=null,this._hovered=null,this._buildPlanes(),this._buildPlaneGizmo(),this._buildBox(),t.addEventListener("change",()=>this._sync()),(e.parentElement??e).addEventListener("pointerdown",n=>this._down(n),!0),e.addEventListener("pointermove",n=>this._move(n)),e.addEventListener("pointerup",n=>this._up(n)),e.addEventListener("pointercancel",()=>this._end()),e.addEventListener("lostpointercapture",()=>this._end()),this._sync()}get dragging(){return this._drag!==null}update(t){this.camera=t;let e=this.planeGizmo;e.visible&&(e.scale.setScalar(this._worldPerPixel(e.position)*bh),this.arrow.visible=this._across(ll.clone().applyQuaternion(e.quaternion),e.position));for(let s of this.boxHandles){let{shown:r,normal:o}=s.userData;s.visible=r&&(!o||this._across(o,s.position)),s.visible&&s.scale.setScalar(this._worldPerPixel(s.position)*ey)}let n=this.boxRing;n.visible&&n.scale.setScalar(this._worldPerPixel(n.position)*bh)}_across(t,e){let n=this.camera,s=n.isOrthographicCamera?n.getWorldDirection(new I):e.clone().sub(n.position).normalize();return Math.abs(t.dot(s))new I(r/2,o/2,0))),n=new en({color:yi.fill,transparent:!0,opacity:.12,side:Ie,depthWrite:!1}),s=new an({color:yi.frame});this.planeVisuals=Array.from({length:Dr},()=>{let r=new Re;return r.add(new _e(t,n),new Ks(e,s)),this.group.add(r),r})}_buildPlaneGizmo(){let t=(n,s)=>n.rotateX(Math.PI/2).translate(0,0,s),e=cl("move",yi.z,[t(new Pi(.025,.025,1),.5),t(new er(.08,.25),1.125)],t(new Pi(.12,.12,1.25),.625));e.name="arrow",this.arrow=e,this.planeGizmo=new Re,this.planeGizmo.add(e,wh("ringX","x",n=>n.rotateY(Math.PI/2)),wh("ringY","y",n=>n.rotateX(Math.PI/2))),this.group.add(this.planeGizmo)}_buildBox(){this.boxWire=new vn(new Li(new dn(1,1,1)),new an({color:yi.frame})),this.group.add(this.boxWire);let t=new ms(1,16,12),e=new ms(1.6,8,6);this.boxHandles=[];for(let s of Sh)for(let r of[-1,1]){let o=cl("face",yi[s],[t],e);o.name=`face${r>0?"+":"-"}${s}`,Object.assign(o.userData,{axis:s,sign:r,normal:new I}),this.boxHandles.push(o)}let n=cl("centre",yi.centre,[new dn(1.4,1.4,1.4)],e);n.name="centre",this.boxHandles.push(n),this.boxRing=wh("boxRing","z"),this.group.add(...this.boxHandles,this.boxRing)}_sync(){let t=this.sections,e=t.mode==="planes";this.planeVisuals.forEach((r,o)=>{let a=t.planes[o];if(r.visible=e&&!!a?.enabled,!r.visible)return;r.children[0].visible=!t.fill;let l=ol(t.modelBox,a.quaternion,t.origin(o));r.position.copy(l.center),r.quaternion.copy(a.quaternion),r.scale.set(l.width,l.height,1)});let n=t.planes[t.active];this.planeGizmo.visible=e&&t.gizmoVisible&&!!n?.enabled,this.planeGizmo.visible&&(this.planeGizmo.position.copy(t.origin(t.active)),this.planeGizmo.quaternion.copy(n.quaternion));let s=t.mode==="box"?t.box:null;this.boxWire.visible=!!s,this.boxRing.visible=!!s&&t.gizmoVisible;for(let r of this.boxHandles)r.visible=r.userData.shown=!!s&&t.gizmoVisible;if(s){let r=s.getCenter(new I),o=s.getSize(new I);this.boxWire.position.copy(r),this.boxWire.scale.copy(o).max(new I(1e-6,1e-6,1e-6)),this.boxWire.rotation.z=t.boxYaw,this.boxRing.position.copy(r);for(let a of this.boxHandles){let{axis:l,sign:c,normal:h}=a.userData;h?(h.set(0,0,0).setComponent(Sh.indexOf(l),c).applyAxisAngle(ll,t.boxYaw),a.position.copy(r).addScaledVector(h,o[l]/2)):a.position.copy(r)}}}_worldPerPixel(t){let e=this.camera,n=Math.max(this.dom.clientHeight,1);if(e.isOrthographicCamera)return(e.top-e.bottom)/e.zoom/n;let s=t.clone().sub(e.position).dot(e.getWorldDirection(new I));return 2*Math.max(s,e.near)*Math.tan(de.degToRad(e.fov/2))/n}_ray(t){let e=this.dom.getBoundingClientRect(),n=new Ht((t.clientX-e.left)/e.width*2-1,1-(t.clientY-e.top)/e.height*2);return this.camera.updateMatrixWorld(),this._raycaster.setFromCamera(n,this.camera),this._raycaster.ray.clone()}_hit(t){if(!this.camera)return null;this.update(this.camera),this.group.updateMatrixWorld(!0);let e=r=>{for(;r&&r!==this.group;r=r.parent)if(!r.visible)return!1;return!0},n=[];this.group.traverse(r=>r.userData.handle&&e(r)&&n.push(r)),this._ray(t);let s=this._raycaster.intersectObjects(n,!1);return(this.sections.mode==="box"?s.find(r=>r.object.userData.handle!==this.boxRing):null)??s[0]??null}_down(t){if(t.target!==this.dom||t.button!==0)return;let e=this._hit(t);if(!e)return;let n=e.object.userData.handle,s=this._start(n,this._raycaster.ray,e.point,t);s&&(t.stopPropagation(),t.preventDefault(),this.dom.setPointerCapture(t.pointerId),this._drag={id:t.pointerId,handle:n,...s},this._highlight(n))}_start(t,e,n,s){let r=this.sections,{kind:o}=t.userData;if(o==="move"){let u=r.active,p=r.origin(u),g=r.normal(u),_=Lr(e,p,g);return _===null?null:{index:u,origin:p,normal:g,offset:r.planes[u].offset,s0:_}}if(o==="rotate"){let u=r.active,p=t===this.boxRing,g=p?t.position.clone():r.origin(u),_=p?null:r.planes[u].quaternion.clone(),m=p?ll:new I().setComponent(Sh.indexOf(t.userData.axis),1).applyQuaternion(_),f={index:u,origin:g,quaternion:_,axis:m,yaw:p?r.boxYaw:null};if(Math.abs(m.dot(e.direction))0&&r===0}function cy(i,t){let{instances:e,geometries:n}=t.meta,s=t.readView(e.geometry),{width:r,height:o}=i.slotUniforms.slotState.value.image,a=new Uint8Array(r*o),l=new Map;for(let h=0;h{let s=e.category??"";t.has(s)||t.set(s,[]),t.get(s).push(n)}),[...t].map(([e,n])=>({name:e,indices:n})).sort((e,n)=>e.name.localeCompare(n.name))}function Vf(i,{elements:t,models:e,selection:n,scene:s,zoomToElement:r,openContextMenu:o}){let a=ty(t),l=new Int32Array(t.length);a.forEach((G,Q)=>G.indices.forEach(lt=>l[lt]=Q));let c=new Uint8Array(a.length),h=new Int32Array(a.length),d=new Uint32Array(a.length),u=Qv(t),p="",g=!1,_=new Int32Array(0),m=0,f=-1,b=null,E=!1,M=tt("input","ioviewer-tree-search");M.type="search",M.placeholder=st("searchPlaceholder"),M.setAttribute("aria-label",st("searchPlaceholder"));let v=tt("div","ioviewer-tree");v.setAttribute("role","tree"),v.setAttribute("aria-label",st("panel.model")),v.setAttribute("aria-multiselectable","true"),v.tabIndex=-1;let S=tt("div","ioviewer-tree-spacer");S.setAttribute("role","presentation"),v.append(S);let A=tt("div","ioviewer-tree-empty",st("noMatches")),x=Hf(t,e,M,D,()=>s.isolate(_));i.append(x.element,M,v,A);function T(){let G=_[m],Q=x.predicate();if(g=!!(p||Q),g){let ct=p?u(p):t.keys();if(Q){let et=[];for(let V of ct)Q(t[V])&&et.push(V);_=Int32Array.from(et)}else _=Int32Array.from(ct)}else{let ct=a.length;a.forEach((V,j)=>c[j]&&(ct+=V.indices.length)),_=new Int32Array(ct);let et=0;a.forEach((V,j)=>{if(h[j]=et,_[et++]=-(j+1),c[j])for(let ut of V.indices)_[et++]=ut})}let lt=_.indexOf(G);m=lt>=0?lt:0,S.style.height=`${_.length*yi}px`,A.hidden=_.length>0||!g,x.update(p,!!s.isolate&&g&&_.some(ct=>s.instancesOf(ct).length>0)),R()}function R(G=v.contains(document.activeElement)){let Q=v.clientHeight;if(Q===0||_.length===0){S.replaceChildren();return}let lt=v.scrollTop,{start:ct,end:et}=vh(lt,yi,Q,_.length,jv);!G&&(m=et)&&(m=Math.min(_.length-1,Math.floor(lt/yi)));let V=[];m=et&&V.push(L(m)),S.replaceChildren(...V),G&&S.querySelector('[tabindex="0"]')?.focus({preventScroll:!0})}function L(G){let Q=_[G],lt=Q<0?-Q-1:l[Q],ct=Q<0?d[lt]===a[lt].indices.length:n.has(Q),et=tt("div","tree-row");if(et.style.top=`${G*yi}px`,et.style.height=`${yi}px`,et.dataset.row=G,et.tabIndex=G===m?0:-1,et.setAttribute("role","treeitem"),et.classList.toggle("selected",ct),et.setAttribute("aria-selected",String(ct)),Q<0){et.classList.add("tree-category"),et.setAttribute("aria-level","1"),et.setAttribute("aria-posinset",String(lt+1)),et.setAttribute("aria-setsize",String(a.length)),et.setAttribute("aria-expanded",String(!!c[lt]));let V=tt("span","tree-chevron");V.innerHTML=Zt.chevron;let{name:j,indices:ut}=a[lt];et.append(V,tt("span","tree-name",j||st("noCategory")),tt("span","tree-count",Cr(ut.length)))}else{let V=t[Q];et.classList.add("tree-element"),et.setAttribute("aria-level",g?"1":"2"),et.setAttribute("aria-posinset",String(g?G+1:G-h[lt])),et.setAttribute("aria-setsize",String(g?_.length:a[lt].indices.length)),et.classList.toggle("tree-child",!g),et.classList.toggle("tree-hidden",s.isVisible?.(Q)===!1),et.append(tt("span","tree-name",V.name||`#${V.id}`),tt("span","tree-type",V.type??""))}return et}function N(G){let Q=v.clientHeight;if(Q===0){f=G;return}let lt=G*yi;ltv.scrollTop+Q&&(v.scrollTop=lt+yi-Q)}function U(G){m=G,N(G),R(!0)}function C(G){let Q=l[G];!g&&!c[Q]&&(c[Q]=1,T());let lt=_.indexOf(G);lt>=0&&(v.contains(document.activeElement)||(m=lt),N(lt)),R()}function B(G){E=!0;try{n.set(G)}finally{E=!1}}function z(G,Q){let lt=_.indexOf(b);lt<0&&(lt=G,b=_[G]);let ct=_.subarray(Math.min(lt,G),Math.max(lt,G)+1).filter(et=>et>=0);ct.length>0&&B(Q?[...n.values(),...ct]:ct)}function W(G){b=G;let Q=-G-1,lt=G<0?a[Q].indices:[G],ct=G<0?d[Q]===lt.length:n.has(G),et=new Set(n.values());for(let V of lt)ct?et.delete(V):et.add(V);B(et)}function F(G,Q,lt){G>=0&&!n.has(G)&&(b=G,B([G]));let ct=G>=0?G:n.values().next().value??null;o(Q,lt,ct,()=>{let et=_.indexOf(G);et>=0?U(et):M.focus()})}M.addEventListener("focus",()=>{S.firstElementChild||Z()});function D(){p=M.value.trim(),v.scrollTop=0,f=-1,m=-1,T()}M.addEventListener("input",D),v.addEventListener("scroll",()=>R()),v.addEventListener("focusin",G=>{let Q=G.target.closest(".tree-row");!Q||Q.tabIndex===0||(S.querySelector('[tabindex="0"]')?.setAttribute("tabindex","-1"),m=Number(Q.dataset.row),Q.tabIndex=0)}),v.addEventListener("keydown",G=>{let Q=G.target.closest(".tree-row");if(!Q||G.ctrlKey||G.altKey||G.metaKey)return;let lt=Number(Q.dataset.row),ct=_[lt];if(xh(G)){if(G.preventDefault(),!G.repeat){let{left:V,bottom:j}=Q.getBoundingClientRect();F(ct,V,j)}return}if(G.key===" "){G.preventDefault(),G.repeat||(G.shiftKey?z(lt,!1):W(ct));return}if(G.shiftKey)return;let et=lt;switch(G.key){case"ArrowUp":et=Math.max(0,lt-1);break;case"ArrowDown":et=Math.min(_.length-1,lt+1);break;case"Home":et=0;break;case"End":et=_.length-1;break;case"ArrowRight":ct<0&&(c[-ct-1]?et=lt+1:(c[-ct-1]=1,T()));break;case"ArrowLeft":ct>=0&&!g?et=h[l[ct]]:ct<0&&c[-ct-1]&&(c[-ct-1]=0,T());break;case"Enter":G.repeat||X(ct);break;default:return}G.preventDefault(),et!==lt&&U(et)});function X(G){if(G>=0){b=G,B([G]),r(G);return}c[-G-1]^=1,T()}v.addEventListener("click",G=>{let Q=G.target.closest(".tree-row");if(!Q)return;let lt=Number(Q.dataset.row),ct=G.ctrlKey||G.metaKey;G.shiftKey?z(lt,ct):ct?W(_[lt]):X(_[lt])}),v.addEventListener("contextmenu",G=>{let Q=G.target.closest(".tree-row");Q&&(G.preventDefault(),F(_[Number(Q.dataset.row)],G.clientX,G.clientY))});function Z(){f>=0&&v.clientHeight>0&&(N(f),f=-1),R()}new ResizeObserver(Z).observe(v),n.addEventListener("change",()=>{let G=-1;d.fill(0);for(let Q of n.values())d[l[Q]]++,G=Q;if(E){R();return}b=null,G>=0?C(G):R()}),s.root?.addEventListener("change",G=>G.detail.kind==="visibility"&&R()),T()}var Gf={element:["properties","hide","isolate","showAll","-","zoomTo","sectionBox","-","copyId"],empty:["showAll","fitAll","resetSections"]},ey={hide:"H",isolate:"I",showAll:"Shift+H",zoomTo:"F"},sl=4;function Wf(i){let t=tt("div","ioviewer-context-menu");t.setAttribute("role","menu"),t.setAttribute("aria-label",st("contextMenu")),t.hidden=!0,i.append(t);let e=new Map(Object.values(Gf).flat().filter(c=>c!=="-").map(c=>[c,{enabled:!1,handler:null}])),n=null;function s(){if(t.hidden)return;let c=t.contains(document.activeElement)?n:null;n=null,t.hidden=!0,t.replaceChildren(),window.removeEventListener("pointerdown",o,!0),window.removeEventListener("wheel",s,!0),window.removeEventListener("scroll",r,!0),window.removeEventListener("resize",s),c?.()}function r(c){i.contains(c.target)||s()}function o(c){t.contains(c.target)||(s(),Ja(c))}function a(c,h,d,u,p=null){let g=Gf[c];if(!g)throw new RangeError(`Unknown menu: ${c}`);s(),n=p;for(let f of g){if(f==="-"){let M=tt("div","ioviewer-menu-separator");M.setAttribute("role","separator"),t.append(M);continue}let b=e.get(f),E=tt("button","ioviewer-menu-item");E.type="button",E.tabIndex=-1,E.dataset.item=f,E.setAttribute("role","menuitem"),E.setAttribute("aria-disabled",String(!b.enabled)),b.enabled||(E.title=st("menu.unavailable")),E.append(tt("span","",st(`menu.${f}`)),tt("kbd","",ey[f]??"")),E.addEventListener("click",()=>{b.enabled&&(s(),b.handler(u))}),t.append(E)}t.hidden=!1;let{width:_,height:m}=t.getBoundingClientRect();t.style.left=`${Math.max(sl,Math.min(h,innerWidth-_-sl))}px`,t.style.top=`${Math.max(sl,Math.min(d,innerHeight-m-sl))}px`,window.addEventListener("pointerdown",o,!0),window.addEventListener("wheel",s,!0),window.addEventListener("scroll",r,!0),window.addEventListener("resize",s),p&&t.querySelector("button")?.focus({preventScroll:!0})}t.addEventListener("keydown",c=>{if(c.key==="Tab"){s();return}if(c.key==="Escape"){c.preventDefault(),s();return}let h=[...t.querySelectorAll("button")],d=h.indexOf(document.activeElement),u;switch(c.key){case"ArrowDown":u=(d+1)%h.length;break;case"ArrowUp":u=(d+h.length-1)%h.length;break;case"Home":u=0;break;case"End":u=h.length-1;break;default:return}c.preventDefault(),h[u]?.focus({preventScroll:!0})});function l(c,{enabled:h=!0,handler:d}){let u=e.get(c);if(!u)throw new RangeError(`Unknown menu item: ${c}`);d&&(u.handler=d),u.enabled=h&&!!u.handler}return{element:t,open:a,close:s,setItem:l,get isOpen(){return!t.hidden}}}var ny=1600;function Xf(i,t,e){let n=()=>i.textContent=`${st("selected")}: ${Cr(t.size)} \xB7 ${st("elements")}: ${Cr(e)}`;t.addEventListener("change",n),n()}function qf(i,t){if(!t)return;let e=tt("div","ioviewer-banner ioviewer-floating");e.setAttribute("role","status");let n=st("truncated").replace("{meshes}",t.meshes).replace("{total}",t.totalMeshes),s=Ke("ioviewer-panel-close",Zt.close,st("close")),r=new ResizeObserver(()=>i.style.setProperty("--banner-height",`${e.offsetHeight}px`));s.addEventListener("click",()=>{r.disconnect(),i.style.removeProperty("--banner-height"),e.remove()}),e.append(tt("span","",n),s),i.append(e),r.observe(e)}function Us(i,t){let e=tt("div","ioviewer-toast",t);e.setAttribute("role","status"),i.append(e),setTimeout(()=>e.remove(),ny)}function Yf(i,t){let e=tt("table");for(let[s,r]of t)e.insertRow().append(tt("th","",s),tt("td","",String(r??"")));let n=tt("section");return n.append(tt("h3","",i),e),n}function $f(i,t,e){let n=tt("h2","ioviewer-properties-title"),s=tt("button","ioviewer-properties-close","\xD7");s.type="button",s.title=st("close"),s.setAttribute("aria-label",st("close")),s.addEventListener("click",()=>t.clear());let r=tt("header");r.append(n,s);let o=tt("div","ioviewer-properties-body");i.replaceChildren(r,o),i.hidden=!0;let a=h=>{let d=[[st("id"),h.id],[st("category"),h.category],[st("type"),h.type],[st("level"),h.level]];return h.sourceId&&d.push([st("sourceId"),h.sourceId]),h.link&&d.push([st("link"),h.link]),Yf(st("elementGroup"),d)},l=h=>{for(let[d,u]of Object.entries(h??{}))o.append(Yf(d,Object.entries(u)))},c;t.addEventListener("change",()=>{if(c?.abort(),c=void 0,o.removeAttribute("aria-busy"),i.hidden=t.size===0,o.replaceChildren(),t.size!==1){n.textContent=`${st("selected")}: ${t.size}`;return}let[h]=t.values(),d=e.meta.elements[h];if(n.textContent=d.name||`#${d.id}`,o.append(a(d)),!e.loadProperties){l(e.props(d.id));return}let u=new AbortController;c=u,o.setAttribute("aria-busy","true"),e.loadProperties(h,u.signal).then(p=>{u.signal.aborted||!p||(n.textContent=p.name||d.name||`#${d.id}`,o.replaceChildren(a({...d,...p})),l(p.properties))}).catch(()=>{u.signal.aborted||o.append(tt("p","",st("badData")))}).finally(()=>{c===u&&o.removeAttribute("aria-busy")})})}async function iy(i){if(await navigator.clipboard?.writeText(i).then(()=>!0,()=>!1))return!0;let t=document.createElement("textarea");t.value=i,t.setAttribute("readonly",""),t.className="ioviewer-offscreen",document.body.append(t),t.select();try{return document.execCommand("copy")}finally{t.remove()}}function Zf({root:i,data:t,scene:e,controls:n,picker:s,selection:r,measure:o}){let{meta:a}=t,l=()=>n.fitBox(e.visibleBox()),c={hide:e.setVisible&&(()=>r.size&&e.setVisible([...r.values()],!1)),isolate:e.isolate&&(()=>r.size&&e.isolate([...r.values()])),showAll:e.showAll&&(()=>e.showAll()),zoomTo:()=>{if(!r.size)return l();let[b,...E]=r.values(),M=e.elementBox(b);for(let v of E)M.union(e.elementBox(v));n.zoomToBox(M)},fitAll:l},h=Bf(i);h.registerPanel("model",{icon:Zt.model,title:st("panel.model"),visible:a.elements.length>0||!!e.setVisible,render:b=>Vf(b,{elements:a.elements,models:a.models??[],selection:r,scene:e,openContextMenu:_,zoomToElement:E=>n.zoomToBox(e.elementBox(E))})});let d=document.createElement("aside");d.id="ioviewer-properties",d.className="ioviewer-floating",i.append(d),$f(d,r,t);let u=zf(i,Of),p=b=>{n.setLeftButtonMode(b),u.setActive("orbit",b==="orbit"),u.setActive("pan",b==="pan")};u.setHandler("orbit",()=>p("orbit")),u.setHandler("pan",()=>p("pan")),p(n.leftButtonMode),u.setHandler("fit",l),u.setHandler("projection",()=>{let b=!n.camera.isOrthographicCamera;n.setProjection(b?"orthographic":"perspective"),u.setActive("projection",b)}),u.setActive("projection",!1),document.fullscreenEnabled&&(u.setHandler("fullscreen",()=>{(document.fullscreenElement?document.exitFullscreen():document.documentElement.requestFullscreen()).catch(()=>{u.setActive("fullscreen",!!document.fullscreenElement),Us(i,st("fullscreenUnavailable"))})}),document.addEventListener("fullscreenchange",()=>u.setActive("fullscreen",!!document.fullscreenElement)));let g=Wf(i);function _(b,E,M,v){g.open(M===null?"empty":"element",b,E,M,v)}function m(b){if(g.isOpen)return;let E=b===document.body,M=(E?n.dom:b).getBoundingClientRect(),v=E?M.left+M.width/2:M.left,S=E?M.top+M.height/2:M.bottom;_(v,S,r.values().next().value??null,()=>b.focus({preventScroll:!0}))}g.setItem("properties",{handler:b=>r.set([b])});for(let b of["hide","isolate","showAll","zoomTo","fitAll"])g.setItem(b,{handler:c[b]});g.setItem("copyId",{handler:b=>iy(String(a.elements[b].id)).then(E=>Us(i,st(E?"idCopied":"copyFailed")),()=>Us(i,st("copyFailed")))}),n.addEventListener("contextmenu",async b=>{let{x:E,y:M}=b.detail;if(o?.active)return _(E,M,r.values().next().value??null);let v=s.pick(E,M),S=v?.then?await v:v;if(S!==void 0){if(!S||S.element<0)return _(E,M,null);r.has(S.element)||r.set([S.element]),_(E,M,S.element)}});let f=[];return window.addEventListener("keydown",b=>{if(b.defaultPrevented)return;let E=kf(b);if(E){if(b.preventDefault(),E==="contextMenu")return m(document.activeElement??document.body);if(E==="escape"&&!g.isOpen){f.some(M=>M())||r.clear();return}g.close(),E!=="escape"&&c[E]?.()}}),Xf(document.getElementById("ioviewer-status"),r,e.elementCount),qf(i,a.truncated),{shell:h,toolbar:u,contextMenu:g,onEscape:b=>f.push(b)}}var yh={x:new I(1,0,0),y:new I(0,1,0),z:new I(0,0,1)};function Mh(i){let t=yh[i];if(!t)throw new RangeError(`Unknown axis: ${i}`);return t.clone()}function Jf(i,t,e){if(t.length===0)return!1;let n=s=>s.distanceToPoint(i)<0;return e?t.every(n):t.some(n)}function Kf(i,t,e,n){let s=i.clone().normalize(),r=s.dot(t)+e;return n?new _e(s,-r):new _e(s.negate(),r)}function jf(i,t,e=0){if(t!=="keepInside"&&t!=="cutInside")throw new RangeError(`Unknown box mode: ${t}`);let{min:n,max:s}=i,r=[new _e(new I(1,0,0),-n.x),new _e(new I(-1,0,0),s.x),new _e(new I(0,1,0),-n.y),new _e(new I(0,-1,0),s.y),new _e(new I(0,0,1),-n.z),new _e(new I(0,0,-1),s.z)];if(e!==0){let o=i.getCenter(new I);for(let a of r){let l=a.distanceToPoint(o);a.normal.applyAxisAngle(yh.z,e),a.constant=l-a.normal.dot(o)}}return t==="keepInside"?{planes:r,intersection:!1}:{planes:r.map(o=>o.negate()),intersection:!0}}function Qf(i,t,e,n,s,r){let o=i.clone();if(n>0?o.max[e]=Math.max(i.max[e]+s,i.min[e]+r):o.min[e]=Math.min(i.min[e]-s,i.max[e]-r),t!==0){let a=o.getCenter(new I).sub(i.getCenter(new I));o.translate(a.clone().applyAxisAngle(yh.z,t).sub(a))}return o}function tp(i){let{min:t,max:e}=i;return Array.from({length:8},(n,s)=>new I(s&1?e.x:t.x,s&2?e.y:t.y,s&4?e.z:t.z))}function ep(i,t,e){if(t.length===0||i.isEmpty())return!1;let n=tp(i),s=r=>n.every(o=>r.distanceToPoint(o)<0);return e?t.every(s):t.some(s)}function rl(i,t){let e=i.getSize(new I).multiplyScalar(.5);return Math.abs(t.x)*e.x+Math.abs(t.y)*e.y+Math.abs(t.z)*e.z}function Lr(i,t,e){let n=t.clone().sub(i.origin),s=e.dot(i.direction),r=1-s*s;return r<.03?null:(s*i.direction.dot(n)-e.dot(n))/r}function ol(i,t,e){let n=new I(1,0,0).applyQuaternion(t),s=new I(0,1,0).applyQuaternion(t),[r,o,a,l]=[1/0,-1/0,1/0,-1/0];for(let h of tp(i)){h.sub(e);let d=h.dot(n),u=h.dot(s);[r,o,a,l]=[Math.min(r,d),Math.max(o,d),Math.min(a,u),Math.max(l,u)]}return{center:e.clone().addScaledVector(n,(r+o)/2).addScaledVector(s,(a+l)/2),width:(o-r)*1.1,height:(l-a)*1.1}}var Dr=6,sy=["off","planes","box"],ry=.05,bh=new I(0,0,1),al=class extends EventTarget{constructor(t,e,n){super(),this.scene=t,this.modelBox=e.clone(),this.center=e.getCenter(new I),this.planes=[],this.active=-1,this.box=null,this.boxYaw=0,this.boxMode="keepInside",this.fill=!1,this.gizmoVisible=!0,this._mode="off",n&&this.restore(n)}restore({planes:t,box:e,cutInside:n}){this.modelBox.isEmpty()||(this.planes=t.map(({axis:s,normal:r,offset:o,flipped:a})=>{let l=new I().fromArray(r),c=new Ce().setFromUnitVectors(bh,l);return{axis:s,quaternion:c,offset:o-l.dot(this.center),flipped:a,enabled:!0,rotated:!1}}),this.active=this.planes.length?0:-1,this.box=e?new ie(new I().fromArray(e.min),new I().fromArray(e.max)):null,this.boxYaw=0,this.boxMode=n?"cutInside":"keepInside",this.gizmoVisible=!1,this.setMode(this.box?"box":this.planes.length?"planes":"off"))}get mode(){return this._mode}setMode(t){if(!sy.includes(t))throw new RangeError(`Unknown section mode: ${t}`);t==="box"&&!this.box&&this.fitBoxToShown()||(this._mode=t,this._changed(!0))}addPlane(t){let e=Mh(t);if(this.planes.length>=Dr||this.modelBox.isEmpty())return null;let n=new Ce().setFromUnitVectors(bh,e);return this.planes.push({axis:t,quaternion:n,offset:0,flipped:!1,enabled:!0,rotated:!1}),this.active=this.planes.length-1,this._mode="planes",this._changed(!0),this.active}removePlane(t){this._plane(t),this.planes.splice(t,1),(this.active>=this.planes.length||this.active>t)&&this.active--,this._changed(!0)}updatePlane(t,{offset:e,flipped:n,enabled:s,quaternion:r}){let o=this._plane(t);if(e!==void 0){if(!Number.isFinite(e))throw new RangeError(`Offset must be a finite number, got ${e}.`);o.offset=e}n!==void 0&&(o.flipped=!!n),s!==void 0&&(o.enabled=!!s),r&&(o.quaternion.copy(r).normalize(),o.rotated=o.axis!=="custom"&&this.normal(t).angleTo(Mh(o.axis))>1e-6),this._changed(!0)}setActivePlane(t){this._plane(t),this.active=t,this._changed(!1)}normal(t){return bh.clone().applyQuaternion(this._plane(t).quaternion)}extent(t){return rl(this.modelBox,this.normal(t))}origin(t){return this.center.clone().addScaledVector(this.normal(t),this._plane(t).offset)}clipPlane(t){let e=this._plane(t);return Kf(this.normal(t),this.center,e.offset,e.flipped)}setBox(t,e=0){if(t.isEmpty())throw new RangeError("The section box is empty.");e=np(e),this.box=t.clone(),this.boxYaw=e,this._mode="box",this._changed(!0)}setBoxYaw(t){this.box&&(this.boxYaw=np(t),this._changed(this.mode==="box"))}setBoxMode(t){if(t!=="keepInside"&&t!=="cutInside")throw new RangeError(`Unknown box mode: ${t}`);this.boxMode=t,this._changed(!0)}fitBoxToElements(t){let e=new ie;for(let s of t)e.union(this.scene.elementBox(s));if(e.isEmpty())return!1;let n=e.getSize(new I);return this.setBox(e.expandByScalar(ry*Math.max(n.x,n.y,n.z))),!0}fitBoxToShown(){let t=this.scene.visibleBox();if(t.isEmpty())return!1;let e=t.getSize(new I);return this.setBox(t.expandByScalar(.001*Math.max(e.x,e.y,e.z))),!0}setGizmoVisible(t){this.gizmoVisible=!!t,this._changed(!1)}setFill(t){this.fill=!!t,this._changed(!1)}reset(){this.planes=[],this.active=-1,this.box=null,this.boxYaw=0,this._mode="off",this._changed(!0)}clipping(){if(this._mode==="planes")return{planes:this.planes.flatMap((e,n)=>e.enabled?[this.clipPlane(n)]:[]),intersection:!1};if(this._mode==="box"&&this.box){let t=jf(this.box,this.boxMode,this.boxYaw);if(!t.intersection&&this.boxYaw!==0){let e=this.box.getCenter(new I),n=this.box.getSize(new I).multiplyScalar(.5),s=Math.abs(Math.cos(this.boxYaw)),r=Math.abs(Math.sin(this.boxYaw));n.set(s*n.x+r*n.y,r*n.x+s*n.y,n.z),t.bounds=new ie(e.clone().sub(n),e.add(n))}return t}return{planes:[],intersection:!1}}isCut(t,{planes:e,intersection:n,bounds:s}=this.clipping()){return s&&!t.isEmpty()&&!s.intersectsBox(t)||ep(t,e,n)}_plane(t){let e=this.planes[t];if(!Number.isInteger(t)||!e)throw new RangeError(`Plane index ${t} is out of range 0..${this.planes.length-1}.`);return e}_changed(t){if(t){let{planes:e,intersection:n}=this.clipping();this.scene.setClipping(e,n)}this.dispatchEvent(new Event("change"))}};function np(i){if(!Number.isFinite(i))throw new RangeError("The section box angle must be finite.");return i>=-Math.PI&&i<=Math.PI?i:ce.euclideanModulo(i+Math.PI,2*Math.PI)-Math.PI}var Sh=80,oy=8,Th=.8,ay=Math.sin(ce.degToRad(12)),Mi={x:"#ef4444",y:"#22c55e",z:"#3b82f6",centre:"#e2e8f0",hover:"#facc15",frame:"#93c5fd",fill:"#60a5fa"},wh=["x","y","z"],ly=Math.cos(ce.degToRad(12)),ll=new I(0,0,1),cy=i=>new en({color:i,depthTest:!1,depthWrite:!1,transparent:!0,opacity:.9}),hy=new en({visible:!1});function cl(i,t,e,n){let s=new Re,r=cy(t);for(let a of e)s.add(new xe(a,r));let o=new xe(n,hy);return o.userData.handle=s,s.add(o),s.userData={kind:i,color:t,material:r,proxy:o},s.traverse(a=>a.renderOrder=1e3),s}function Eh(i,t,e=n=>n){let n=cl("rotate",Mi[t],[e(new gs(Th,.018,8,64))],e(new gs(Th,.09,8,48)));return n.name=i,n.userData.axis=t,n}var hl=class extends EventTarget{constructor(t,e){super(),this.sections=t,this.dom=e,this.camera=null,this.group=new Re,this.group.name="sections",this._raycaster=new Ni,this._drag=null,this._hovered=null,this._buildPlanes(),this._buildPlaneGizmo(),this._buildBox(),t.addEventListener("change",()=>this._sync()),(e.parentElement??e).addEventListener("pointerdown",n=>this._down(n),!0),e.addEventListener("pointermove",n=>this._move(n)),e.addEventListener("pointerup",n=>this._up(n)),e.addEventListener("pointercancel",()=>this._end()),e.addEventListener("lostpointercapture",()=>this._end()),this._sync()}get dragging(){return this._drag!==null}update(t){this.camera=t;let e=this.planeGizmo;e.visible&&(e.scale.setScalar(this._worldPerPixel(e.position)*Sh),this.arrow.visible=this._across(ll.clone().applyQuaternion(e.quaternion),e.position));for(let s of this.boxHandles){let{shown:r,normal:o}=s.userData;s.visible=r&&(!o||this._across(o,s.position)),s.visible&&s.scale.setScalar(this._worldPerPixel(s.position)*oy)}let n=this.boxRing;n.visible&&n.scale.setScalar(this._worldPerPixel(n.position)*Sh)}_across(t,e){let n=this.camera,s=n.isOrthographicCamera?n.getWorldDirection(new I):e.clone().sub(n.position).normalize();return Math.abs(t.dot(s))new I(r/2,o/2,0))),n=new en({color:Mi.fill,transparent:!0,opacity:.12,side:Ie,depthWrite:!1}),s=new an({color:Mi.frame});this.planeVisuals=Array.from({length:Dr},()=>{let r=new Re;return r.add(new xe(t,n),new js(e,s)),this.group.add(r),r})}_buildPlaneGizmo(){let t=(n,s)=>n.rotateX(Math.PI/2).translate(0,0,s),e=cl("move",Mi.z,[t(new Li(.025,.025,1),.5),t(new nr(.08,.25),1.125)],t(new Li(.12,.12,1.25),.625));e.name="arrow",this.arrow=e,this.planeGizmo=new Re,this.planeGizmo.add(e,Eh("ringX","x",n=>n.rotateY(Math.PI/2)),Eh("ringY","y",n=>n.rotateX(Math.PI/2))),this.group.add(this.planeGizmo)}_buildBox(){this.boxWire=new vn(new Di(new dn(1,1,1)),new an({color:Mi.frame})),this.group.add(this.boxWire);let t=new ms(1,16,12),e=new ms(1.6,8,6);this.boxHandles=[];for(let s of wh)for(let r of[-1,1]){let o=cl("face",Mi[s],[t],e);o.name=`face${r>0?"+":"-"}${s}`,Object.assign(o.userData,{axis:s,sign:r,normal:new I}),this.boxHandles.push(o)}let n=cl("centre",Mi.centre,[new dn(1.4,1.4,1.4)],e);n.name="centre",this.boxHandles.push(n),this.boxRing=Eh("boxRing","z"),this.group.add(...this.boxHandles,this.boxRing)}_sync(){let t=this.sections,e=t.mode==="planes";this.planeVisuals.forEach((r,o)=>{let a=t.planes[o];if(r.visible=e&&!!a?.enabled,!r.visible)return;r.children[0].visible=!t.fill;let l=ol(t.modelBox,a.quaternion,t.origin(o));r.position.copy(l.center),r.quaternion.copy(a.quaternion),r.scale.set(l.width,l.height,1)});let n=t.planes[t.active];this.planeGizmo.visible=e&&t.gizmoVisible&&!!n?.enabled,this.planeGizmo.visible&&(this.planeGizmo.position.copy(t.origin(t.active)),this.planeGizmo.quaternion.copy(n.quaternion));let s=t.mode==="box"?t.box:null;this.boxWire.visible=!!s,this.boxRing.visible=!!s&&t.gizmoVisible;for(let r of this.boxHandles)r.visible=r.userData.shown=!!s&&t.gizmoVisible;if(s){let r=s.getCenter(new I),o=s.getSize(new I);this.boxWire.position.copy(r),this.boxWire.scale.copy(o).max(new I(1e-6,1e-6,1e-6)),this.boxWire.rotation.z=t.boxYaw,this.boxRing.position.copy(r);for(let a of this.boxHandles){let{axis:l,sign:c,normal:h}=a.userData;h?(h.set(0,0,0).setComponent(wh.indexOf(l),c).applyAxisAngle(ll,t.boxYaw),a.position.copy(r).addScaledVector(h,o[l]/2)):a.position.copy(r)}}}_worldPerPixel(t){let e=this.camera,n=Math.max(this.dom.clientHeight,1);if(e.isOrthographicCamera)return(e.top-e.bottom)/e.zoom/n;let s=t.clone().sub(e.position).dot(e.getWorldDirection(new I));return 2*Math.max(s,e.near)*Math.tan(ce.degToRad(e.fov/2))/n}_ray(t){let e=this.dom.getBoundingClientRect(),n=new Ht((t.clientX-e.left)/e.width*2-1,1-(t.clientY-e.top)/e.height*2);return this.camera.updateMatrixWorld(),this._raycaster.setFromCamera(n,this.camera),this._raycaster.ray.clone()}_hit(t){if(!this.camera)return null;this.update(this.camera),this.group.updateMatrixWorld(!0);let e=r=>{for(;r&&r!==this.group;r=r.parent)if(!r.visible)return!1;return!0},n=[];this.group.traverse(r=>r.userData.handle&&e(r)&&n.push(r)),this._ray(t);let s=this._raycaster.intersectObjects(n,!1);return(this.sections.mode==="box"?s.find(r=>r.object.userData.handle!==this.boxRing):null)??s[0]??null}_down(t){if(t.target!==this.dom||t.button!==0)return;let e=this._hit(t);if(!e)return;let n=e.object.userData.handle,s=this._start(n,this._raycaster.ray,e.point,t);s&&(t.stopPropagation(),t.preventDefault(),this.dom.setPointerCapture(t.pointerId),this._drag={id:t.pointerId,handle:n,...s},this._highlight(n))}_start(t,e,n,s){let r=this.sections,{kind:o}=t.userData;if(o==="move"){let u=r.active,p=r.origin(u),g=r.normal(u),_=Lr(e,p,g);return _===null?null:{index:u,origin:p,normal:g,offset:r.planes[u].offset,s0:_}}if(o==="rotate"){let u=r.active,p=t===this.boxRing,g=p?t.position.clone():r.origin(u),_=p?null:r.planes[u].quaternion.clone(),m=p?ll:new I().setComponent(wh.indexOf(t.userData.axis),1).applyQuaternion(_),f={index:u,origin:g,quaternion:_,axis:m,yaw:p?r.boxYaw:null};if(Math.abs(m.dot(e.direction))0&&r===0}function py(i,t){let{instances:e,geometries:n}=t.meta,s=t.readView(e.geometry),{width:r,height:o}=i.slotUniforms.slotState.value.image,a=new Uint8Array(r*o),l=new Map;for(let h=0;h ${wr} #include @@ -4320,7 +4320,7 @@ void main() { void main() { #include gl_FragColor = vec4( 0.0 ); -}`,side:e,stencilZPass:n,stencilWrite:!0,clipping:!0,clippingPlanes:[t],colorWrite:!1,depthTest:!1,depthWrite:!1});return s.index0AttributeName="q",s}var ul=class{constructor(t,e,n){this.model=t,this.sections=e,this.data=n,this._farSide=new ge,this._surface=new _e(new yn(1,1),new en({color:ay,side:Ie,forceSinglePass:!0,stencilWrite:!0,stencilFunc:Mc,stencilWriteMask:0}))}render(t,e,n){let{sections:s,model:r}=this,{planes:o,intersection:a}=s.clipping(),l=a?o.map(u=>u.clone().negate()):o,c=u=>Math.abs(u.distanceToPoint(s.center)){if(!c(p))return;let _=u?-p.normal.dot(u):p.distanceToPoint(n.position);if(_===0)return;this._farSide.copy(p),_>0&&this._farSide.negate(),t.clearStencil();for(let f of this._stencils)r.withMaterial(f,()=>t.render(r.root,n),{section:!0});this._surface.quaternion.setFromUnitVectors(oy,p.normal);let m=ol(s.modelBox,this._surface.quaternion,p.coplanarPoint(new I));this._surface.position.copy(m.center),this._surface.scale.set(m.width,m.height,1),h.clippingPlanes=l.filter((f,b)=>b!==g),t.render(this._surface,n)}),t.render(e,n)}finally{t.autoClear=d}}};function Nr(i,t,e){let n=et("div","ioviewer-segmented");n.setAttribute("role","group"),n.setAttribute("aria-label",i);let s=t.map(([o,a])=>{let l=et("button","",a);return l.type="button",l.dataset.value=o,l.addEventListener("click",()=>e(o)),n.append(l),l});return{element:n,update:o=>s.forEach(a=>a.setAttribute("aria-pressed",String(a.dataset.value===o)))}}function Th(i,t){let e=et("label","ioviewer-check"),n=et("input");return n.type="checkbox",n.addEventListener("change",()=>t(n.checked)),e.append(n,et("span","",i)),{element:e,input:n}}function hy(i,t){let e=et("li","ioviewer-section-plane");e.addEventListener("pointerdown",()=>i.active!==t&&i.setActivePlane(t));let n=et("span","ioviewer-section-name"),s=Ke("ioviewer-icon-button",Zt.flip,st("sections.flip"));s.addEventListener("click",()=>i.updatePlane(t,{flipped:!i.planes[t].flipped}));let r=Th(st("sections.enabled"),h=>i.updatePlane(t,{enabled:h})),o=Ke("ioviewer-icon-button",Zt.remove,st("sections.delete"));o.addEventListener("click",()=>i.removePlane(t));let a=et("input","ioviewer-section-slider");a.type="range",a.step="any",a.setAttribute("aria-label",st("sections.position")),a.addEventListener("input",()=>i.updatePlane(t,{offset:Number(a.value)}));let l=et("div","ioviewer-section-head");return l.append(n,s,r.element,o),e.append(l,a),{element:e,update:()=>{let h=i.planes[t],d=h.rotated?` (${st("sections.rotated")})`:"",u=h.axis==="custom"?st("sections.custom"):h.axis.toUpperCase();n.textContent=`${t+1}. ${u}${d}`,e.classList.toggle("active",i.active===t),s.setAttribute("aria-pressed",String(h.flipped)),r.input.checked=h.enabled;let p=i.extent(t);a.min=String(Math.min(-p,h.offset)),a.max=String(Math.max(p,h.offset)),a.value=String(h.offset)}}}function np({root:i,shell:t,toolbar:e,contextMenu:n,sections:s,selection:r,canFill:o}){let a="z",l=()=>{s.addPlane(a)===null&&(s.setMode("planes"),Ns(i,st("sections.maxPlanes")))},c=()=>[...r.values()],h=()=>s.fitBoxToElements(c()),d=Nr(st("sections.mode"),[["planes",st("sections.planes")],["box",st("sections.box")],["off",st("sections.off")]],C=>s.setMode(C)),u=Nr(st("sections.axis"),["x","y","z"].map(C=>[C,C.toUpperCase()]),C=>u.update(a=C));u.update(a);let p=et("button","ioviewer-text-button",st("sections.addPlane"));p.type="button",p.addEventListener("click",l);let g=et("ul","ioviewer-section-list"),_=et("div","ioviewer-section-empty",st("sections.noPlanes")),m=et("div","ioviewer-section-block"),f=et("div","ioviewer-section-row");f.append(et("span","",st("sections.axis")),u.element,p),m.append(f,g,_);let b=Nr(st("sections.box"),[["keepInside",st("sections.keepInside")],["cutInside",st("sections.cutInside")]],C=>s.setBoxMode(C)),E=et("button","ioviewer-text-button",st("sections.fitSelection"));E.type="button",E.addEventListener("click",h);let M=et("input","ioviewer-section-slider");Object.assign(M,{type:"range",min:"-180",max:"180",step:"1"}),M.addEventListener("input",()=>s.setBoxYaw(Number(M.value)*Math.PI/180));let v=et("span");v.setAttribute("aria-hidden","true");let S=et("label","ioviewer-section-row");S.append(et("span","",st("sections.boxYaw")),M,v);let A=et("div","ioviewer-section-block");A.append(b.element,S,E);let x=Th(st("sections.showGizmo"),C=>s.setGizmoVisible(C)),T=Th(st("sections.fill"),C=>s.setFill(C));o||(T.element.title=st("sections.fillUnavailable"));let R=[],L=()=>{d.update(s.mode),m.hidden=s.mode!=="planes",A.hidden=s.mode!=="box",p.disabled=s.planes.length>=Dr,R.length!==s.planes.length&&(R=s.planes.map((B,z)=>hy(s,z)),g.replaceChildren(...R.map(B=>B.element))),R.forEach(B=>B.update()),_.hidden=R.length>0,b.update(s.boxMode),M.value=String(Math.round(s.boxYaw*180/Math.PI)),v.textContent=`${M.value}\xB0`,M.setAttribute("aria-valuetext",v.textContent),x.input.checked=s.gizmoVisible,T.input.checked=s.fill;let C=s.mode==="box"||s.mode==="planes"&&s.planes.some(B=>B.enabled);T.input.disabled=!o||!C,e.setActive("plane",s.mode==="planes"),e.setActive("box",s.mode==="box")},N=()=>E.disabled=r.size===0;if(t.registerPanel("sections",{icon:Zt.sections,title:st("panel.sections"),visible:!s.modelBox.isEmpty(),render:C=>C.append(d.element,m,A,T.element,x.element)}),s.addEventListener("change",L),r.addEventListener("change",N),L(),N(),s.modelBox.isEmpty())return;let U=()=>t.openPanel("sections");e.setHandler("plane",()=>{l(),U()}),e.setHandler("box",()=>{(s.mode==="box"||r.size&&h()||s.fitBoxToShown())&&U()}),e.setHandler("resetSections",()=>s.reset()),n.setItem("sectionBox",{handler:C=>{s.fitBoxToElements(r.has(C)?c():[C]),U()}}),n.setItem("resetSections",{handler:()=>s.reset()})}var uy="#facc15",dy=9;function Ah(i,t=Ps){return`${new Intl.NumberFormat(t,{minimumFractionDigits:2,maximumFractionDigits:2,useGrouping:!1}).format(i)} ${st("unit.m",t)}`}var dl=class extends EventTarget{constructor(t){super(),this.active=!1,this.points=[],this.preview=null,this.group=new Re,this.group.name="measure";let e=new ae;e.setAttribute("position",new Se(new Float32Array(6),3));let n={color:uy,depthTest:!1,depthWrite:!1,transparent:!0};this._line=new Ci(e,new an(n)),this._markers=new Ii(e,new ci({...n,size:dy,sizeAttenuation:!1}));for(let s of[this._line,this._markers])s.frustumCulled=!1,s.renderOrder=1001,this.group.add(s);this.label=et("div","ioviewer-measure-label"),this.label.hidden=!0,this._previewMarker=et("div","ioviewer-measure-preview"),this._previewMarker.hidden=!0,this._previewMarker.setAttribute("aria-hidden","true"),t.prepend(this.label,this._previewMarker),this._sync()}get distance(){return this.points.length===2?this.points[0].distanceTo(this.points[1]):null}get box(){return new ie().setFromPoints(this.points)}setActive(t){this.active=!!t,this.active||(this.points=[],this.setPreview(null)),this._sync()}add(t){this.active&&(this.points=this.points.length===1?[this.points[0],t.clone()]:[t.clone()],this._sync())}clear(){return this.points.length===0?!1:(this.points=[],this._sync(),!0)}setPreview(t){!this.preview&&!t||(this.preview=t,this._previewMarker.hidden=!t,t&&(this._previewMarker.dataset.kind=t.kind),this.dispatchEvent(new Event("previewchange")))}update(t,e){this.preview&&Ir(this._previewMarker,this.preview.point,t,e),this.distance!==null&&Ir(this.label,this.points[0].clone().lerp(this.points[1],.5),t,e)}_sync(){let t=this._line.geometry.attributes.position;this.points.forEach((e,n)=>t.setXYZ(n,e.x,e.y,e.z)),t.needsUpdate=!0,this._line.geometry.setDrawRange(0,this.points.length),this._line.visible=this.points.length===2,this._markers.visible=this.points.length>0,this.label.hidden=this.distance===null,this.distance!==null&&(this.label.textContent=Ah(this.distance)),this.dispatchEvent(new Event("change"))}};var ip=8,fy=1-1e-6,py=8,sp={vertex:0,midpoint:1,edge:2},my=2e4;function gy(i,t){let e=new Map,n=new Uint32Array(i.length/3);for(let d=0;d0&&(_.normalize(),l(u,p,_),l(p,g,_),l(g,u,_))}let c=[],h=new Set;for(let{lo:d,hi:u,count:p,crease:g}of s.values())p!==1&&!g||(c.push(d,u),h.add(d),h.add(u));return{edges:c,vertices:h}}function fl(i,t,e){return t<0&&e<0?!1:(t<0&&(i[0]=Math.max(i[0],t/(t-e))),e<0&&(i[1]=Math.min(i[1],t/(t-e))),i[0]<=i[1])}function _y(i,t,e,n,s,r){let o=[0,1];if(!fl(o,e.w+e.z,n.w+n.z)||!fl(o,e.w-e.z,n.w-n.z))return[];if(!r||!s.length)return s.every(c=>fl(o,c.distanceToPoint(i),c.distanceToPoint(t)))?[o]:[];let a=o.slice();if(!s.every(c=>{let h=c.distanceToPoint(i),d=c.distanceToPoint(t);return(h<0||d<0)&&fl(a,-h,-d)}))return[o];let l=[];return o[0]0))return null;let m=de.clamp(((r-c)*p+(o-h)*g)/_,0,1);return e+(n-e)*(m*a.w/((1-m)*l.w+m*a.w))}var pl=class{constructor(t,e,n){this.picker=t,this.sections=e,this.data=n,this.cache=new Map}release(){this.data.releaseBinary(),this.cache.clear()}_geometry(t){let e=this.cache.get(t);if(e)this.cache.delete(t);else{let n=this.data.meta.geometries[t],s=Zd({view:this.data.readView},n);e={positions:s,...gy(s,this.data.readView(n.indices))}}return this.cache.set(t,e),this.cache.size>py&&this.cache.delete(this.cache.keys().next().value),e}target(t,e){let n=this.picker.measureTile(t,e,ip+1);if(!n)return null;let{rect:s}=n,r=t-s.left,o=e-s.top,{camera:a,scene:l}=this.picker,{planes:c,intersection:h}=this.sections.clipping(),d=new kt().multiplyMatrices(a.projectionMatrix,a.matrixWorldInverse),u=a.matrixWorldInverse.elements,p=null;function g(v,S,A,x){if(p&&sp[v]>sp[p.kind]||A.w<=0||A.z<-A.w||A.z>A.w)return;let[T,R]=Rh(A,s);if(!(T>=0&&R>=0&&Tip**2||p?.kind===v&&L>=p.distance||v!=="edge"&&$f(S,c,h))return;let N=-(u[2]*S.x+u[6]*S.y+u[10]*S.z+u[14]);N-n.depthAt(T,R,x)>2*wn+Math.abs(N)*2**-21||(p={kind:v,distance:L,point:S.clone()})}let _=my*3,m=new kt,f=new I,b=new oe,{geometry:E,matrix:M}=this.data.meta.instances;for(let v of n.slots){let S=l.slotInstance(v),[A]=this.data.readView({t:"u32",o:E.o+S*4,n:1}),x=this.data.meta.geometries[A],T=Math.max(x.indices.n,x.positions.n/3);if(T>_)continue;_-=T;let{positions:R,vertices:L,edges:N}=this._geometry(A),U=this.data.readView({t:"f32",o:M.o+S*48,n:12});m.set(U[0],U[3],U[6],U[9],U[1],U[4],U[7],U[10],U[2],U[5],U[8],U[11],0,0,0,1);let C=new Map;for(let B of L){let z=new I().fromArray(R,B*3).applyMatrix4(m),W=new oe(z.x,z.y,z.z,1).applyMatrix4(d);C.set(B,[z,W]),g("vertex",z,W,v)}if(p?.kind!=="vertex")for(let B=0;B[...s.start,...s.end]),3)),new an({color:"#93c5fd",transparent:!0,opacity:.55,depthTest:!1,depthWrite:!1})),this.group.name="grids",this.group.geometry.computeBoundingBox(),this.box=this.group.geometry.boundingBox,this.group.renderOrder=999,this._labels=e.flatMap(s=>[s.start,s.end].map(r=>({element:et("div","ioviewer-grid-label",s.name),point:new I(...r)})));let n=et("div","ioviewer-grid-labels");n.append(...this._labels.map(s=>s.element)),t.prepend(n),this._layer=n,this.setVisible(this.count>0)}get visible(){return this.group.visible}setVisible(t){this.group.visible=!!t,this._layer.hidden=!t,this.dispatchEvent(new Event("change"))}update(t,e){if(this.visible)for(let{element:n,point:s}of this._labels)Ir(n,s,t,e)}};var vy=8,rp=4;function Ch(i,t,e,n="dialog"){let s=et("div","ioviewer-popover ioviewer-floating");s.setAttribute("role",n),s.setAttribute("aria-label",e),s.hidden=!0,t.setAttribute("aria-haspopup",n),t.setAttribute("aria-expanded","false"),i.append(s);function r(l){s.contains(l.target)||(a(),Ja(l))}s.addEventListener("keydown",l=>{l.key==="Escape"&&(l.preventDefault(),l.stopPropagation(),a(),t.focus())});function o(){s.hidden=!1,t.setAttribute("aria-expanded","true");let l=t.getBoundingClientRect(),{width:c}=s.getBoundingClientRect();s.style.left=`${Math.max(rp,Math.min(l.left+l.width/2-c/2,innerWidth-c-rp))}px`,s.style.bottom=`${innerHeight-l.top+vy}px`,window.addEventListener("pointerdown",r,!0),window.addEventListener("resize",a)}function a(){return s.hidden?!1:(s.hidden=!0,t.setAttribute("aria-expanded","false"),window.removeEventListener("pointerdown",r,!0),window.removeEventListener("resize",a),!0)}return{element:s,close:a,toggle:()=>s.hidden?o():a(),get isOpen(){return!s.hidden}}}function yy(i){return i?.initialWireframe?"wireframe":i?.initialWhiteMode?"white":"materials"}function op({root:i,toolbar:t,scene:e,meta:n,grids:s,initialBackground:r,setBackground:o}){let a=x=>t.element.querySelector(`[data-tool="${x}"]`),l=a("displayMode"),c=Ch(i,l,st("group.display"));c.element.classList.add("ioviewer-display-modes");let h=et("div");h.setAttribute("role","menu"),h.setAttribute("aria-label",st("tool.displayMode")),c.element.append(h);let d=(n.textures??[]).length>0,u=uh.map(x=>{let T=et("button","ioviewer-menu-item",st(`display.${x}`));return T.type="button",T.dataset.mode=x,T.setAttribute("role","menuitemradio"),T.disabled=x==="textures"&&!d,T.addEventListener("click",()=>{p(x),c.close(),l.focus()}),h.append(T),T}),p=x=>{e.setDisplayMode(x);for(let T of u)T.setAttribute("aria-checked",String(T.dataset.mode===x))};p(yy(n.options)),t.setHandler("displayMode",()=>{c.toggle(),c.isOpen&&h.querySelector('[aria-checked="true"]')?.focus()});let g=et("div","ioviewer-background-setting"),_=et("label","",st("display.background")),m=et("input");Object.assign(m,{type:"color",value:r}),_.append(m);let f=et("button","ioviewer-text-button",st("display.backgroundReset"));f.type="button",f.disabled=!0;let b=()=>{o(m.value),f.disabled=m.value===r};m.addEventListener("input",b),f.addEventListener("click",()=>{m.value=r,m.focus(),b()}),g.append(_,f),c.element.append(g),t.setActive("grids",s.visible),s.count>0&&t.setHandler("grids",()=>{s.setVisible(!s.visible),t.setActive("grids",s.visible)});let E=Ch(i,a("opacity"),st("tool.opacity"));E.element.classList.add("ioviewer-opacity");let M=et("input","ioviewer-opacity-slider");Object.assign(M,{type:"range",min:"10",max:"100",step:"1",value:"100"}),M.setAttribute("aria-label",st("opacity.label"));let v=et("output","ioviewer-opacity-value"),S=()=>v.textContent=st("opacity.value").replace("{value}",M.value);M.addEventListener("input",()=>{e.setOpacity(Number(M.value)/100),S()}),S();let A=et("div","ioviewer-opacity-head");return A.append(et("span","",st("opacity.label")),v),E.element.append(A,M),t.setHandler("opacity",E.toggle),[c,E]}var My=3e3;function gl(i,t){let e=et("button",i);return e.type="button",e.setAttribute("title",t),e.append(et("span","ioviewer-row-name",t)),e}function ap({shell:i,toolbar:t,controls:e,scene:n,sections:s,selection:r,restoreLinkedModels:o,views:a,bcfTopics:l}){let c=null,h=et("button","ioviewer-text-button ioviewer-tour");h.type="button";function d(E){E.sections!=null&&s.restore(E.sections),E.hiddenElements!=null&&n.setHiddenElements(E.hiddenElements),E.visibleElements!=null&&n.isolate(E.visibleElements),E.hiddenModelKeys!=null&&o(E.hiddenModelKeys),E.selectedElements!=null&&r.set(E.selectedElements);let M=E.camera.projection==="orthographic";e.setProjection(M?"orthographic":"perspective"),t.setActive("projection",M),e.restoreViewCamera(E.camera)}function u(){d(a[c.next]),c.next=(c.next+1)%a.length;let E=()=>{e.animating?c.frame=requestAnimationFrame(E):c.timer=setTimeout(u,My)};c.frame=requestAnimationFrame(E)}let p=E=>h.contains(E.target),g=E=>!p(E)&&m(),_=E=>{p(E)&&(E.key==="Enter"||E.key===" ")||(E.key==="Escape"&&(E.preventDefault(),E.stopPropagation()),m())};function m(){c&&(cancelAnimationFrame(c.frame),clearTimeout(c.timer),c=null,window.removeEventListener("pointerdown",g,!0),window.removeEventListener("wheel",m,!0),window.removeEventListener("keydown",_,!0),b())}function f(){c={next:0,frame:0,timer:0},window.addEventListener("pointerdown",g,!0),window.addEventListener("wheel",m,!0),window.addEventListener("keydown",_,!0),b(),u()}function b(){let E=st(c?"views.stop":"views.tour");h.replaceChildren(),h.insertAdjacentHTML("afterbegin",c?Zt.pause:Zt.play),h.append(et("span","",E)),h.setAttribute("aria-pressed",String(!!c))}h.addEventListener("click",()=>c?m():f()),b(),i.registerPanel("views",{icon:Zt.views,title:st("panel.views"),visible:a.length>0,render:E=>{let M=et("div","ioviewer-row-list");for(let v of a){let S=gl("ioviewer-row ioviewer-view",String(v.name??""));S.addEventListener("click",()=>d(v)),M.append(S)}E.append(h,M)}}),i.registerPanel("bcf",{icon:Zt.bcf,title:st("panel.bcf"),visible:l.length>0,render:E=>{let M=et("div","ioviewer-row-list");for(let v of l){let S=et("details","ioviewer-bcf-topic");S.append(et("summary","",v.title)),v.status&&S.append(et("p","ioviewer-bcf-status",v.status)),v.description&&S.append(et("p","ioviewer-bcf-description",v.description)),v.viewpoints.length||S.append(et("p","ioviewer-bcf-status",st("bcf.noView"))),v.viewpoints.forEach((A,x)=>{let T=st("bcf.viewpoint").replace("{index}",String(x+1)),R=gl("ioviewer-row ioviewer-view",T);if(R.addEventListener("click",()=>d(A)),S.append(R),A.missingComponents||A.ambiguousComponents){let L=st("bcf.components").replace("{missing}",String(A.missingComponents)).replace("{ambiguous}",String(A.ambiguousComponents));S.append(et("p","ioviewer-bcf-status",L))}}),M.append(S)}E.append(M)}})}function lp(i,t){let e=[];for(let[n,s]of[[i.element1Id,i.element1Name],[i.element2Id,i.element2Name]]){let r=n!=null?t.findIndex(o=>o.id===n&&!o.mesh):by(t,s);r>=0&&!e.includes(r)&&e.push(r)}return e}function by(i,t){if(t==null)return-1;let e=i.findIndex(n=>n.name===t);return e>=0&&i.findIndex((n,s)=>s>e&&n.name===t)<0?e:-1}var Sy=["New","Active","Reviewed","Approved","Resolved"],Ih=27,wy=8,Ey=14,Ty=2,Ay=new I(1,-1,.8).normalize();function cp({shell:i,tests:t,elements:e,scene:n,controls:s,selection:r}){let o=new Re;o.name="clash-marker";let a=new ae;a.setAttribute("position",new Se(new Float32Array(3),3));let l={color:"#ef4444",depthTest:!1,depthWrite:!1,transparent:!0},c=new Ii(a,new ci({...l,size:Ey,sizeAttenuation:!1}));c.frustumCulled=!1,c.renderOrder=1002,o.add(c),o.visible=!1;let h=null,d=null;function u(){o.visible=!1,h?.removeAttribute("aria-current"),h=null,d=null,s.setExtraBounds("clash",null)}function p(b,E){let M=lp(b,e);M.length?r.set(M):r.clear();let v=new I(...b.point),S=0;for(let T of M){let R=n.elementBox(T);R.isEmpty()||(S=Math.max(S,...R.getSize(new I).toArray()))}let A=s.camera.position.clone().sub(s.target);A.lengthSq()<1e-12&&A.copy(Ay);let x=Math.max(3*S,Ty);s.animateTo({position:A.normalize().multiplyScalar(x).add(v),target:v}),a.attributes.position.setXYZ(0,v.x,v.y,v.z),a.attributes.position.needsUpdate=!0,o.visible=!0,h?.removeAttribute("aria-current"),h=E,d=b,E.setAttribute("aria-current","true"),s.setExtraBounds("clash",new ie(v.clone(),v.clone()))}function g(b){let E=gl("ioviewer-row ioviewer-clash",String(b.name??""));E.setAttribute("title",`${b.name??""}: ${b.element1Name??""} \u2014 ${b.element2Name??""}`);let M=Sy.includes(b.status),v=et("span","ioviewer-clash-status",M?st(`clash.${b.status}`):String(b.status??""));M&&(v.dataset.status=b.status);let S=typeof b.distance=="number"?Ah(b.distance):"";return E.append(v,et("span","ioviewer-clash-distance",S)),b===d&&(h=E,E.setAttribute("aria-current","true")),E.addEventListener("click",()=>p(b,E)),E}function _(b,E){let M=et("div","ioviewer-clash-test"),v=et("button","ioviewer-row ioviewer-clash-header");v.type="button",v.setAttribute("aria-expanded","true");let S=`${b.name??""} (${b.clashes.length})`;v.setAttribute("title",S),v.insertAdjacentHTML("afterbegin",Zt.chevron),v.append(et("span","ioviewer-row-name",S));let A=et("div","ioviewer-clash-list");return A.style.height=`${Math.max(0,b.clashes.length*Ih-1)}px`,v.addEventListener("click",()=>{A.hidden=!A.hidden,v.setAttribute("aria-expanded",String(!A.hidden)),E()}),M.append(v,A),{box:M,list:A,clashes:b.clashes,rows:new Map}}function m({list:b,clashes:E,rows:M},{start:v,end:S}){for(let[x,T]of M)(x=S)&&(T.remove(),M.delete(x));let A=null;for(let x=S-1;x>=v;x--){let T=M.get(x);T||(T=g(E[x]),T.style.top=`${x*Ih}px`,b.insertBefore(T,A),M.set(x,T)),A=T}}function f(b){if(!t.length)return;b.classList.add("ioviewer-clashes-body");let E=t.map(v=>_(v,M));for(let v of E)b.append(v.box);function M(){let v=b.scrollTop,S=b.clientHeight,A=E.map(({list:x,clashes:T})=>S&&!x.hidden?xh(v-x.offsetTop,Ih,S,T.length,wy):{start:0,end:0});E.forEach((x,T)=>m(x,A[T]))}b.addEventListener("scroll",M),b.addEventListener("focusin",M),new ResizeObserver(M).observe(b)}return i.registerPanel("clashes",{icon:Zt.clashes,title:st("panel.clashes"),visible:t.length>0,render:f,onClose:()=>o.visible&&u()}),{group:o}}var Ry=["construct","demolish","temporary"],Cy=Date.parse("0002-01-01T00:00:00Z");function hp(i){let t=typeof i=="string"?Date.parse(i):NaN;return t>=Cy?t:NaN}function up(i,t){let e=new Map(t.flatMap((o,a)=>o.mesh?[]:[[o.id,a]])),n=[];for(let o of Array.isArray(i?.tasks)?i.tasks:[]){let a=hp(o?.start),l=hp(o?.end);if(!(a<=l))continue;let c=Ry.includes(o.type)?o.type:"construct",h=Array.isArray(o.attachedElements)?o.attachedElements:[];n.push({name:o.name,type:c,start:a,end:l,elements:h.filter(d=>e.has(d)).map(d=>e.get(d))})}let s=n.reduce((o,a)=>Math.min(o,a.start),1/0),r=n.reduce((o,a)=>Math.max(o,a.end),-1/0);return{start:s,end:r,tasks:n}}function dp(i,t){let e=new Set,n=new Map;for(let s of i){let r=ts.end,a=s.type==="construct"?r:s.type==="demolish"?o:r||o;for(let l of s.elements)a?e.add(l):!r&&!o&&n.set(l,s.type)}for(let s of e)n.delete(s);return{hidden:e,active:n}}var Iy=864e5,Py=["1","5","15"],Ly={construct:"#22c55e",demolish:"#ef4444",temporary:"#a855f7"};function fp({root:i,shell:t,timeliner:e,elements:n,scene:s}){let r=up(e,n);if(r.tasks.length===0)return t.registerPanel("timeliner",{icon:Zt.timeliner,title:st("panel.timeliner"),visible:!1,render:()=>{}}),null;let o=new Intl.DateTimeFormat(void 0,{dateStyle:"short",timeZone:"UTC"}),a=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeZone:"UTC"}),l=r.start,c=1,h=0,d=0,u=!1,p=new Set,g=new Map,_=et("div","ioviewer-player ioviewer-floating");_.setAttribute("role","group"),_.setAttribute("aria-label",st("player.title")),_.hidden=!0;let m=Ke("ioviewer-icon-button ioviewer-player-play",Zt.play,st("player.play"));m.addEventListener("click",()=>h?N():L());let f=et("output","ioviewer-player-date"),b=et("input","ioviewer-player-slider");Object.assign(b,{type:"range",min:String(r.start),max:String(r.end),step:"any"}),b.setAttribute("aria-label",st("player.date")),b.addEventListener("input",()=>A(Number(b.value)));let E=Nr(st("player.speed"),Py.map(C=>[C,`${C}\xD7`]),C=>{c=Number(C),E.update(C)});E.update(String(c));let M=Ke("ioviewer-panel-close",Zt.close,st("close"));M.addEventListener("click",T),_.append(m,f,b,E.element,M),i.append(_),new ResizeObserver(()=>{let C=_.hidden?0:_.offsetHeight+8;i.style.setProperty("--player-space",`${C}px`)}).observe(_);function S(){let C=dp(r.tasks,l),B=[...p].filter(D=>!C.hidden.has(D)),z=[...C.hidden].filter(D=>!p.has(D));p=C.hidden;let W=[...g.keys()].filter(D=>C.active.get(D)!==g.get(D)),F=new Map;for(let[D,X]of C.active)g.get(D)!==X&&(F.has(X)||F.set(X,[]),F.get(X).push(D));g=C.active,B.length&&s.setLayerHidden("schedule",B,!1),z.length&&s.setLayerHidden("schedule",z,!0),W.length&&s.setTint(W,null);for(let[D,X]of F)s.setTint(X,Ly[D])}function A(C){l=Math.min(Math.max(C,r.start),r.end),b.value=String(l),f.textContent=a.format(l),u&&S()}function x(){u||(u=!0,_.hidden=!1,A(r.start))}function T(){u&&(N(),u=!1,s.setTint([...g.keys()],null),g=new Map,p=new Set,s.clearLayer("schedule"),_.hidden=!0)}function R(C){A(l+Math.max(C-d,0)/1e3*c*Iy),d=C,l>=r.end?N():h=requestAnimationFrame(R)}function L(){x(),!h&&(l>=r.end&&A(r.start),d=performance.now(),h=requestAnimationFrame(R),U())}function N(){cancelAnimationFrame(h),h=0,U()}function U(){let C=st(h?"player.pause":"player.play");m.innerHTML=h?Zt.pause:Zt.play,m.title=C,m.setAttribute("aria-label",C)}return t.registerPanel("timeliner",{icon:Zt.timeliner,title:st("panel.timeliner"),render:C=>{let B=et("button","ioviewer-text-button ioviewer-player-open");B.type="button",B.insertAdjacentHTML("afterbegin",Zt.play),B.append(et("span","",st("player.play"))),B.addEventListener("click",L);let z=et("div","ioviewer-row-list");for(let W of r.tasks){let F=String(W.name??""),D=et("div","ioviewer-row ioviewer-task");D.dataset.type=W.type,D.setAttribute("title",`${F} \xB7 ${st(`task.${W.type}`)}`);let X=`${o.format(W.start)} \u2013 ${o.format(W.end)}`;D.append(et("span","ioviewer-row-name",F),et("span","ioviewer-task-dates",X)),z.append(D)}C.append(B,z)}}),{open:x,close:T,play:L,pause:N,setDate:A,get date(){return l},get isOpen(){return u}}}function pp({shell:i,files:t,elements:e,scene:n}){let s=t.map(o=>({file:o,members:o.members??e.flatMap((a,l)=>a.link!=null&&(a.link===o.name||a.link===o.path)?[l]:[]),input:et("input")})),r=()=>n.replaceLayerHidden("links",s.flatMap(({input:o,members:a})=>o.checked?[]:a));return i.registerPanel("links",{icon:Zt.links,title:st("panel.links"),visible:s.length>0,render:o=>{let a=et("div","ioviewer-row-list");for(let l of s){let c=String(l.file.name??""),h=et("label","ioviewer-row ioviewer-check ioviewer-link");h.setAttribute("title",`${c} (${l.file.path??""})`);let{input:d}=l;d.type="checkbox",d.checked=l.members.length===0||l.file.visible!==!1,d.disabled=l.members.length===0,d.addEventListener("change",r),h.append(d,et("span","ioviewer-row-name",c),et("span","ioviewer-row-count",String(l.members.length))),a.append(h)}o.append(a),r()}}),o=>{let a=new Set(o);for(let{file:l,input:c}of s)c.checked=c.disabled||!a.has(l.key);r()}}document.documentElement.lang=Ps;var Hn=document.getElementById("ioviewer-canvas"),Ph=window.IOVIEWER_TEST??{},Ur=Ph.startup;function Fr(i){let t=document.getElementById("ioviewer-message");t.textContent=i,t.hidden=!1}try{let i=Kc(document,Ur);i.title&&(document.title=i.title);let t=Hn.getContext("webgl2",{antialias:!0,stencil:!0});t?Dy(Vd(document,Ur,i),t):Fr(st("noWebGL"))}catch(i){if(!(i instanceof ye))throw i;Fr(st("badData"))}function Dy(i,t){let e=new As({canvas:Hn,context:t,antialias:!0,stencil:!0,logarithmicDepthBuffer:wf(i.meta)});e.setPixelRatio(window.devicePixelRatio),e.autoClearStencil=!1,e.localClippingEnabled=!0;let n=new Ai,s="#1f2228",r=new Ft(s);e.setClearColor(r,1);let o=new sr("#ffffff","#8a8f99",1.6);o.position.set(0,0,1),n.add(o);let a=new $e(45,1,.1,1e3);a.up.set(0,0,1),a.position.set(1,-1,.8);let l=new or("#ffffff",1.4);l.position.set(.3,.6,0),a.add(l,l.target),l.target.position.set(0,0,-1),n.add(a),Ur?.("sceneStart");let c=b();Ur?.("sceneEnd"),i.releaseBinary();let h=new el(c,x,Math.min(c.totalCost,2e7));n.add(c.root);let d=new al(c,c.visibleBox(),i.meta.sections),u=t.getContextAttributes()?.stencil===!0,p,g=new hl(d,Hn);n.add(g.group);let _=document.getElementById("ioviewer-ui"),m=new dl(_),f=new ml(_,i.meta.grids??[]);n.add(m.group,f.group);function b(){try{let tt=new Rr(i,{...Ph,maxTextureSize:e.capabilities.maxTextureSize});return tt.totalCost===0&&Fr(st("noGeometry")),tt}catch(tt){if(!(tt instanceof Ar))throw tt;Fr(st("tooLarge").replace("{count}",tt.count).replace("{limit}",tt.limit));let V=ut=>({o:0,n:0,t:ut}),j={count:0,geometry:V("u32"),material:V("u32"),element:V("i32"),matrix:V("f32")};return new Rr({...i,meta:{...i.meta,instances:j}})}}let E=!1;Hn.addEventListener("webglcontextlost",()=>{E=!0,Fr(st("contextLost"))});let M,v=new Promise(tt=>M=tt),S=Ur,A=!1;function x(){A||E||(A=!0,h.requested(performance.now()),requestAnimationFrame(()=>{if(A=!1,E)return;let tt=Hn.getBoundingClientRect();z.camera.updateMatrixWorld(),g.update(z.camera),m.update(z.camera,tt),f.update(z.camera,tt),h.begin(z.camera,tt.height,performance.now()),S?.("renderStart"),d.fill&&u?(p??(p=new ul(c,d,i)),p.render(e,n,z.camera)):e.render(n,z.camera),S&&(S("renderEnd"),S=void 0),h.end(performance.now()),ct.update(),M()}))}c.root.addEventListener("change",x),d.addEventListener("change",x),g.addEventListener("change",x),m.addEventListener("change",x),m.addEventListener("previewchange",x),f.addEventListener("change",x);let T=new Qa(e,c,a,{pickFloat:Ph.pickFloat}),R=new pl(T,d,i),L=0,N=null;function U(){cancelAnimationFrame(L),L=0,N=null,m.setPreview(null)}function C(){L=0,N&&m.setPreview(R.target(...N))}function B(){N&&(m.setPreview(null),cancelAnimationFrame(L),L=requestAnimationFrame(()=>{L=requestAnimationFrame(C)}))}Hn.addEventListener("pointermove",tt=>{if(!m.active||tt.buttons)return U();N=[tt.clientX,tt.clientY],L||(L=requestAnimationFrame(C))});for(let tt of["pointerdown","pointerleave","pointercancel","webglcontextlost"])Hn.addEventListener(tt,U);c.root.addEventListener("change",tt=>{tt.detail.kind!=="appearance"&&B()});let z=new Za(a,Hn,{pick:(tt,V)=>T.pick(tt,V)?.point??null,visibleBox:()=>c.visibleBox()});z.addEventListener("change",()=>{T.camera=z.camera,B(),x()}),c.root.addEventListener("change",tt=>{tt.detail.kind==="visibility"&&(z.invalidateBounds(),z.resize())});let W=new il;W.addEventListener("change",()=>c.setHighlighted([...W.values()]));let F=Yf({root:_,data:i,scene:c,controls:z,picker:T,selection:W,measure:m});np({root:_,...F,sections:d,selection:W,canFill:u});let{meta:D}=i,X=pp({...F,files:D.linkedFiles??[],elements:D.elements,scene:c});ap({...F,controls:z,scene:c,sections:d,selection:W,restoreLinkedModels:X,views:D.viewpoints??[],bcfTopics:D.bcfTopics??[]});let Z=cp({...F,tests:D.clashTests??[],elements:D.elements,scene:c,controls:z,selection:W});n.add(Z.group);let G=fp({root:_,...F,timeliner:D.timeliner,elements:D.elements,scene:c}),Q=tt=>{e.setClearColor(r.set(tt),1);let{r:V,g:j,b:ut}=r,Mt=.2126*V+.7152*j+.0722*ut>Math.sqrt(.0525)-.05?"#000":"#fff";_.style.setProperty("--viewport-text",tt===s?"":Mt),x()};for(let tt of op({root:_,toolbar:F.toolbar,scene:c,meta:D,grids:f,initialBackground:s,setBackground:Q}))F.onEscape(tt.close);F.toolbar.setHandler("distance",()=>{U(),m.setActive(!m.active),m.active||R.release(),F.toolbar.setActive("distance",m.active)}),F.toolbar.setActive("distance",!1),F.onEscape(()=>(U(),m.clear()));let lt=()=>{z.setExtraBounds("grids",f.visible?f.box:null),z.setExtraBounds("measure",m.box)};f.addEventListener("change",lt),m.addEventListener("change",lt),lt(),z.addEventListener("click",tt=>{let{x:V,y:j,ctrl:ut,shift:Lt}=tt.detail;if(m.active){let xe=R.target(V,j);xe&&m.add(xe.point);return}let Bt=T.pick(V,j)?.element??-1;ut?Bt>=0&&W.toggle(Bt):Bt>=0?W.set([Bt]):Lt||W.clear()}),z.addEventListener("boxselect",tt=>{if(m.active)return;let{rect:V,mode:j,ctrl:ut,shift:Lt}=tt.detail;if(V.width<4||V.height<4){!ut&&!Lt&&W.clear();return}let Mt=new ie,Bt=Lf(V,j,Df(c,z.camera,Hn.getBoundingClientRect())),xe=d.clipping(),Vt=Bt.filter(Jt=>!d.isCut(c.elementBox(Jt,Mt),xe));W.set(ut?[...W.values(),...Vt]:Vt)}),window.addEventListener("resize",()=>{e.setSize(window.innerWidth,window.innerHeight,!1),z.resize()}),e.setSize(window.innerWidth,window.innerHeight,!1),z.resize(),z.fitBox(c.visibleBox(),!1);let ct=new ja(document.getElementById("ioviewer-ui"),a,z);window.addEventListener("pointerdown",tt=>{(tt.target===Hn||ct.element.contains(tt.target))&&document.activeElement?.blur()},!0),window.__ioviewer={scene:c,motionDetail:h,controls:z,picker:T,selection:W,ui:F,viewCube:ct,sections:d,sectionGizmo:g,measure:m,measureSnap:R,grids:f,clashes:Z,timeliner:G,ready:v,get camera(){return z.camera}}}})(); +}`,side:e,stencilZPass:n,stencilWrite:!0,clipping:!0,clippingPlanes:[t],colorWrite:!1,depthTest:!1,depthWrite:!1});return s.index0AttributeName="q",s}var ul=class{constructor(t,e,n,s){this.model=t,this.sections=e,this.data=n,this.drawStencils=s,this._farSide=new _e,this._surface=new xe(new yn(1,1),new en({color:dy,side:Ie,forceSinglePass:!0,stencilWrite:!0,stencilFunc:Mc,stencilWriteMask:0}))}render(t,e,n){let{sections:s,model:r}=this,{planes:o,intersection:a}=s.clipping(),l=a?o.map(u=>u.clone().negate()):o,c=u=>Math.abs(u.distanceToPoint(s.center)){if(!c(p))return;let _=u?-p.normal.dot(u):p.distanceToPoint(n.position);if(_===0)return;if(this._farSide.copy(p),_>0&&this._farSide.negate(),t.clearStencil(),this.drawStencils)this.drawStencils(t,n,this._farSide);else for(let f of this._stencils)r.withMaterial(f,()=>t.render(r.root,n),{section:!0});this._surface.quaternion.setFromUnitVectors(uy,p.normal);let m=ol(s.modelBox,this._surface.quaternion,p.coplanarPoint(new I));this._surface.position.copy(m.center),this._surface.scale.set(m.width,m.height,1),h.clippingPlanes=l.filter((f,b)=>b!==g),t.render(this._surface,n)}),t.render(e,n)}finally{t.autoClear=d}}};function Nr(i,t,e){let n=tt("div","ioviewer-segmented");n.setAttribute("role","group"),n.setAttribute("aria-label",i);let s=t.map(([o,a])=>{let l=tt("button","",a);return l.type="button",l.dataset.value=o,l.addEventListener("click",()=>e(o)),n.append(l),l});return{element:n,update:o=>s.forEach(a=>a.setAttribute("aria-pressed",String(a.dataset.value===o)))}}function Ah(i,t){let e=tt("label","ioviewer-check"),n=tt("input");return n.type="checkbox",n.addEventListener("change",()=>t(n.checked)),e.append(n,tt("span","",i)),{element:e,input:n}}function my(i,t){let e=tt("li","ioviewer-section-plane");e.addEventListener("pointerdown",()=>i.active!==t&&i.setActivePlane(t));let n=tt("span","ioviewer-section-name"),s=Ke("ioviewer-icon-button",Zt.flip,st("sections.flip"));s.addEventListener("click",()=>i.updatePlane(t,{flipped:!i.planes[t].flipped}));let r=Ah(st("sections.enabled"),h=>i.updatePlane(t,{enabled:h})),o=Ke("ioviewer-icon-button",Zt.remove,st("sections.delete"));o.addEventListener("click",()=>i.removePlane(t));let a=tt("input","ioviewer-section-slider");a.type="range",a.step="any",a.setAttribute("aria-label",st("sections.position")),a.addEventListener("input",()=>i.updatePlane(t,{offset:Number(a.value)}));let l=tt("div","ioviewer-section-head");return l.append(n,s,r.element,o),e.append(l,a),{element:e,update:()=>{let h=i.planes[t],d=h.rotated?` (${st("sections.rotated")})`:"",u=h.axis==="custom"?st("sections.custom"):h.axis.toUpperCase();n.textContent=`${t+1}. ${u}${d}`,e.classList.toggle("active",i.active===t),s.setAttribute("aria-pressed",String(h.flipped)),r.input.checked=h.enabled;let p=i.extent(t);a.min=String(Math.min(-p,h.offset)),a.max=String(Math.max(p,h.offset)),a.value=String(h.offset)}}}function sp({root:i,shell:t,toolbar:e,contextMenu:n,sections:s,selection:r,canFill:o}){let a="z",l=()=>{s.addPlane(a)===null&&(s.setMode("planes"),Us(i,st("sections.maxPlanes")))},c=()=>[...r.values()],h=()=>s.fitBoxToElements(c()),d=Nr(st("sections.mode"),[["planes",st("sections.planes")],["box",st("sections.box")],["off",st("sections.off")]],C=>s.setMode(C)),u=Nr(st("sections.axis"),["x","y","z"].map(C=>[C,C.toUpperCase()]),C=>u.update(a=C));u.update(a);let p=tt("button","ioviewer-text-button",st("sections.addPlane"));p.type="button",p.addEventListener("click",l);let g=tt("ul","ioviewer-section-list"),_=tt("div","ioviewer-section-empty",st("sections.noPlanes")),m=tt("div","ioviewer-section-block"),f=tt("div","ioviewer-section-row");f.append(tt("span","",st("sections.axis")),u.element,p),m.append(f,g,_);let b=Nr(st("sections.box"),[["keepInside",st("sections.keepInside")],["cutInside",st("sections.cutInside")]],C=>s.setBoxMode(C)),E=tt("button","ioviewer-text-button",st("sections.fitSelection"));E.type="button",E.addEventListener("click",h);let M=tt("input","ioviewer-section-slider");Object.assign(M,{type:"range",min:"-180",max:"180",step:"1"}),M.addEventListener("input",()=>s.setBoxYaw(Number(M.value)*Math.PI/180));let v=tt("span");v.setAttribute("aria-hidden","true");let S=tt("label","ioviewer-section-row");S.append(tt("span","",st("sections.boxYaw")),M,v);let A=tt("div","ioviewer-section-block");A.append(b.element,S,E);let x=Ah(st("sections.showGizmo"),C=>s.setGizmoVisible(C)),T=Ah(st("sections.fill"),C=>s.setFill(C));o||(T.element.title=st("sections.fillUnavailable"));let R=[],L=()=>{d.update(s.mode),m.hidden=s.mode!=="planes",A.hidden=s.mode!=="box",p.disabled=s.planes.length>=Dr,R.length!==s.planes.length&&(R=s.planes.map((B,z)=>my(s,z)),g.replaceChildren(...R.map(B=>B.element))),R.forEach(B=>B.update()),_.hidden=R.length>0,b.update(s.boxMode),M.value=String(Math.round(s.boxYaw*180/Math.PI)),v.textContent=`${M.value}\xB0`,M.setAttribute("aria-valuetext",v.textContent),x.input.checked=s.gizmoVisible,T.input.checked=s.fill;let C=s.mode==="box"||s.mode==="planes"&&s.planes.some(B=>B.enabled);T.input.disabled=!o||!C,e.setActive("plane",s.mode==="planes"),e.setActive("box",s.mode==="box")},N=()=>E.disabled=r.size===0;if(t.registerPanel("sections",{icon:Zt.sections,title:st("panel.sections"),visible:!s.modelBox.isEmpty(),render:C=>C.append(d.element,m,A,T.element,x.element)}),s.addEventListener("change",L),r.addEventListener("change",N),L(),N(),s.modelBox.isEmpty())return;let U=()=>t.openPanel("sections");e.setHandler("plane",()=>{l(),U()}),e.setHandler("box",()=>{(s.mode==="box"||r.size&&h()||s.fitBoxToShown())&&U()}),e.setHandler("resetSections",()=>s.reset()),n.setItem("sectionBox",{handler:C=>{s.fitBoxToElements(r.has(C)?c():[C]),U()}}),n.setItem("resetSections",{handler:()=>s.reset()})}var gy="#facc15",_y=9;function Rh(i,t=Ls){return`${new Intl.NumberFormat(t,{minimumFractionDigits:2,maximumFractionDigits:2,useGrouping:!1}).format(i)} ${st("unit.m",t)}`}var dl=class extends EventTarget{constructor(t){super(),this.active=!1,this.points=[],this.preview=null,this.group=new Re,this.group.name="measure";let e=new le;e.setAttribute("position",new Se(new Float32Array(6),3));let n={color:gy,depthTest:!1,depthWrite:!1,transparent:!0};this._line=new Ii(e,new an(n)),this._markers=new Pi(e,new ci({...n,size:_y,sizeAttenuation:!1}));for(let s of[this._line,this._markers])s.frustumCulled=!1,s.renderOrder=1001,this.group.add(s);this.label=tt("div","ioviewer-measure-label"),this.label.hidden=!0,this._previewMarker=tt("div","ioviewer-measure-preview"),this._previewMarker.hidden=!0,this._previewMarker.setAttribute("aria-hidden","true"),t.prepend(this.label,this._previewMarker),this._sync()}get distance(){return this.points.length===2?this.points[0].distanceTo(this.points[1]):null}get box(){return new ie().setFromPoints(this.points)}setActive(t){this.active=!!t,this.active||(this.points=[],this.setPreview(null)),this._sync()}add(t){this.active&&(this.points=this.points.length===1?[this.points[0],t.clone()]:[t.clone()],this._sync())}clear(){return this.points.length===0?!1:(this.points=[],this._sync(),!0)}setPreview(t){!this.preview&&!t||(this.preview=t,this._previewMarker.hidden=!t,t&&(this._previewMarker.dataset.kind=t.kind),this.dispatchEvent(new Event("previewchange")))}update(t,e){this.preview&&Ir(this._previewMarker,this.preview.point,t,e),this.distance!==null&&Ir(this.label,this.points[0].clone().lerp(this.points[1],.5),t,e)}_sync(){let t=this._line.geometry.attributes.position;this.points.forEach((e,n)=>t.setXYZ(n,e.x,e.y,e.z)),t.needsUpdate=!0,this._line.geometry.setDrawRange(0,this.points.length),this._line.visible=this.points.length===2,this._markers.visible=this.points.length>0,this.label.hidden=this.distance===null,this.distance!==null&&(this.label.textContent=Rh(this.distance)),this.dispatchEvent(new Event("change"))}};var rp=8,xy=1-1e-6,vy=8,op={vertex:0,midpoint:1,edge:2},yy=2e4;function My(i,t){let e=new Map,n=new Uint32Array(i.length/3);for(let d=0;d0&&(_.normalize(),l(u,p,_),l(p,g,_),l(g,u,_))}let c=[],h=new Set;for(let{lo:d,hi:u,count:p,crease:g}of s.values())p!==1&&!g||(c.push(d,u),h.add(d),h.add(u));return{edges:c,vertices:h}}function fl(i,t,e){return t<0&&e<0?!1:(t<0&&(i[0]=Math.max(i[0],t/(t-e))),e<0&&(i[1]=Math.min(i[1],t/(t-e))),i[0]<=i[1])}function by(i,t,e,n,s,r){let o=[0,1];if(!fl(o,e.w+e.z,n.w+n.z)||!fl(o,e.w-e.z,n.w-n.z))return[];if(!r||!s.length)return s.every(c=>fl(o,c.distanceToPoint(i),c.distanceToPoint(t)))?[o]:[];let a=o.slice();if(!s.every(c=>{let h=c.distanceToPoint(i),d=c.distanceToPoint(t);return(h<0||d<0)&&fl(a,-h,-d)}))return[o];let l=[];return o[0]0))return null;let m=ce.clamp(((r-c)*p+(o-h)*g)/_,0,1);return e+(n-e)*(m*a.w/((1-m)*l.w+m*a.w))}var pl=class{constructor(t,e,n){this.picker=t,this.sections=e,this.data=n,this.cache=new Map}release(){this.data.releaseBinary(),this.cache.clear()}_geometry(t){let e=this.cache.get(t);if(e)this.cache.delete(t);else{let n=this.data.meta.geometries[t],s=Kd({view:this.data.readView},n);e={positions:s,...My(s,this.data.readView(n.indices))}}return this.cache.set(t,e),this.cache.size>vy&&this.cache.delete(this.cache.keys().next().value),e}target(t,e){let n=this.picker.measureTile(t,e,rp+1);if(!n)return null;let{rect:s}=n,r=t-s.left,o=e-s.top,{camera:a,scene:l}=this.picker,{planes:c,intersection:h}=this.sections.clipping(),d=new kt().multiplyMatrices(a.projectionMatrix,a.matrixWorldInverse),u=a.matrixWorldInverse.elements,p=null;function g(v,S,A,x){if(p&&op[v]>op[p.kind]||A.w<=0||A.z<-A.w||A.z>A.w)return;let[T,R]=Ch(A,s);if(!(T>=0&&R>=0&&Trp**2||p?.kind===v&&L>=p.distance||v!=="edge"&&Jf(S,c,h))return;let N=-(u[2]*S.x+u[6]*S.y+u[10]*S.z+u[14]);N-n.depthAt(T,R,x)>2*wn+Math.abs(N)*2**-21||(p={kind:v,distance:L,point:S.clone()})}let _=yy*3,m=new kt,f=new I,b=new ae,{geometry:E,matrix:M}=this.data.meta.instances;for(let v of n.slots){let S=l.slotInstance(v),[A]=this.data.readView({t:"u32",o:E.o+S*4,n:1}),x=this.data.meta.geometries[A],T=Math.max(x.indices.n,x.positions.n/3);if(T>_)continue;_-=T;let{positions:R,vertices:L,edges:N}=this._geometry(A),U=this.data.readView({t:"f32",o:M.o+S*48,n:12});m.set(U[0],U[3],U[6],U[9],U[1],U[4],U[7],U[10],U[2],U[5],U[8],U[11],0,0,0,1);let C=new Map;for(let B of L){let z=new I().fromArray(R,B*3).applyMatrix4(m),W=new ae(z.x,z.y,z.z,1).applyMatrix4(d);C.set(B,[z,W]),g("vertex",z,W,v)}if(p?.kind!=="vertex")for(let B=0;B[...s.start,...s.end]),3)),new an({color:"#93c5fd",transparent:!0,opacity:.55,depthTest:!1,depthWrite:!1})),this.group.name="grids",this.group.geometry.computeBoundingBox(),this.box=this.group.geometry.boundingBox,this.group.renderOrder=999,this._labels=e.flatMap(s=>[s.start,s.end].map(r=>({element:tt("div","ioviewer-grid-label",s.name),point:new I(...r)})));let n=tt("div","ioviewer-grid-labels");n.append(...this._labels.map(s=>s.element)),t.prepend(n),this._layer=n,this.setVisible(this.count>0)}get visible(){return this.group.visible}setVisible(t){this.group.visible=!!t,this._layer.hidden=!t,this.dispatchEvent(new Event("change"))}update(t,e){if(this.visible)for(let{element:n,point:s}of this._labels)Ir(n,s,t,e)}};var wy=8,ap=4;function Ih(i,t,e,n="dialog"){let s=tt("div","ioviewer-popover ioviewer-floating");s.setAttribute("role",n),s.setAttribute("aria-label",e),s.hidden=!0,t.setAttribute("aria-haspopup",n),t.setAttribute("aria-expanded","false"),i.append(s);function r(l){s.contains(l.target)||(a(),Ja(l))}s.addEventListener("keydown",l=>{l.key==="Escape"&&(l.preventDefault(),l.stopPropagation(),a(),t.focus())});function o(){s.hidden=!1,t.setAttribute("aria-expanded","true");let l=t.getBoundingClientRect(),{width:c}=s.getBoundingClientRect();s.style.left=`${Math.max(ap,Math.min(l.left+l.width/2-c/2,innerWidth-c-ap))}px`,s.style.bottom=`${innerHeight-l.top+wy}px`,window.addEventListener("pointerdown",r,!0),window.addEventListener("resize",a)}function a(){return s.hidden?!1:(s.hidden=!0,t.setAttribute("aria-expanded","false"),window.removeEventListener("pointerdown",r,!0),window.removeEventListener("resize",a),!0)}return{element:s,close:a,toggle:()=>s.hidden?o():a(),get isOpen(){return!s.hidden}}}function Ey(i){return i?.initialWireframe?"wireframe":i?.initialWhiteMode?"white":"materials"}function lp({root:i,toolbar:t,scene:e,meta:n,grids:s,initialBackground:r,setBackground:o}){let a=x=>t.element.querySelector(`[data-tool="${x}"]`),l=a("displayMode"),c=Ih(i,l,st("group.display"));c.element.classList.add("ioviewer-display-modes");let h=tt("div");h.setAttribute("role","menu"),h.setAttribute("aria-label",st("tool.displayMode")),c.element.append(h);let d=(n.textures??[]).length>0,u=uh.map(x=>{let T=tt("button","ioviewer-menu-item",st(`display.${x}`));return T.type="button",T.dataset.mode=x,T.setAttribute("role","menuitemradio"),T.disabled=x==="textures"&&!d,T.addEventListener("click",()=>{p(x),c.close(),l.focus()}),h.append(T),T}),p=x=>{e.setDisplayMode(x);for(let T of u)T.setAttribute("aria-checked",String(T.dataset.mode===x))};p(Ey(n.options)),t.setHandler("displayMode",()=>{c.toggle(),c.isOpen&&h.querySelector('[aria-checked="true"]')?.focus()});let g=tt("div","ioviewer-background-setting"),_=tt("label","",st("display.background")),m=tt("input");Object.assign(m,{type:"color",value:r}),_.append(m);let f=tt("button","ioviewer-text-button",st("display.backgroundReset"));f.type="button",f.disabled=!0;let b=()=>{o(m.value),f.disabled=m.value===r};m.addEventListener("input",b),f.addEventListener("click",()=>{m.value=r,m.focus(),b()}),g.append(_,f),c.element.append(g),t.setActive("grids",s.visible),s.count>0&&t.setHandler("grids",()=>{s.setVisible(!s.visible),t.setActive("grids",s.visible)});let E=Ih(i,a("opacity"),st("tool.opacity"));E.element.classList.add("ioviewer-opacity");let M=tt("input","ioviewer-opacity-slider");Object.assign(M,{type:"range",min:"10",max:"100",step:"1",value:"100"}),M.setAttribute("aria-label",st("opacity.label"));let v=tt("output","ioviewer-opacity-value"),S=()=>v.textContent=st("opacity.value").replace("{value}",M.value);M.addEventListener("input",()=>{e.setOpacity(Number(M.value)/100),S()}),S();let A=tt("div","ioviewer-opacity-head");return A.append(tt("span","",st("opacity.label")),v),E.element.append(A,M),t.setHandler("opacity",E.toggle),[c,E]}var Ty=3e3;function gl(i,t){let e=tt("button",i);return e.type="button",e.setAttribute("title",t),e.append(tt("span","ioviewer-row-name",t)),e}function cp({shell:i,toolbar:t,controls:e,scene:n,sections:s,selection:r,restoreLinkedModels:o,views:a,bcfTopics:l}){let c=null,h=tt("button","ioviewer-text-button ioviewer-tour");h.type="button";function d(E){E.sections!=null&&s.restore(E.sections),E.hiddenElements!=null&&n.setHiddenElements(E.hiddenElements),E.visibleElements!=null&&n.isolate(E.visibleElements),E.hiddenModelKeys!=null&&o(E.hiddenModelKeys),E.selectedElements!=null&&r.set(E.selectedElements);let M=E.camera.projection==="orthographic";e.setProjection(M?"orthographic":"perspective"),t.setActive("projection",M),e.restoreViewCamera(E.camera)}function u(){d(a[c.next]),c.next=(c.next+1)%a.length;let E=()=>{e.animating?c.frame=requestAnimationFrame(E):c.timer=setTimeout(u,Ty)};c.frame=requestAnimationFrame(E)}let p=E=>h.contains(E.target),g=E=>!p(E)&&m(),_=E=>{p(E)&&(E.key==="Enter"||E.key===" ")||(E.key==="Escape"&&(E.preventDefault(),E.stopPropagation()),m())};function m(){c&&(cancelAnimationFrame(c.frame),clearTimeout(c.timer),c=null,window.removeEventListener("pointerdown",g,!0),window.removeEventListener("wheel",m,!0),window.removeEventListener("keydown",_,!0),b())}function f(){c={next:0,frame:0,timer:0},window.addEventListener("pointerdown",g,!0),window.addEventListener("wheel",m,!0),window.addEventListener("keydown",_,!0),b(),u()}function b(){let E=st(c?"views.stop":"views.tour");h.replaceChildren(),h.insertAdjacentHTML("afterbegin",c?Zt.pause:Zt.play),h.append(tt("span","",E)),h.setAttribute("aria-pressed",String(!!c))}h.addEventListener("click",()=>c?m():f()),b(),i.registerPanel("views",{icon:Zt.views,title:st("panel.views"),visible:a.length>0,render:E=>{let M=tt("div","ioviewer-row-list");for(let v of a){let S=gl("ioviewer-row ioviewer-view",String(v.name??""));S.addEventListener("click",()=>d(v)),M.append(S)}E.append(h,M)}}),i.registerPanel("bcf",{icon:Zt.bcf,title:st("panel.bcf"),visible:l.length>0,render:E=>{let M=tt("div","ioviewer-row-list");for(let v of l){let S=tt("details","ioviewer-bcf-topic");S.append(tt("summary","",v.title)),v.status&&S.append(tt("p","ioviewer-bcf-status",v.status)),v.description&&S.append(tt("p","ioviewer-bcf-description",v.description)),v.viewpoints.length||S.append(tt("p","ioviewer-bcf-status",st("bcf.noView"))),v.viewpoints.forEach((A,x)=>{let T=st("bcf.viewpoint").replace("{index}",String(x+1)),R=gl("ioviewer-row ioviewer-view",T);if(R.addEventListener("click",()=>d(A)),S.append(R),A.missingComponents||A.ambiguousComponents){let L=st("bcf.components").replace("{missing}",String(A.missingComponents)).replace("{ambiguous}",String(A.ambiguousComponents));S.append(tt("p","ioviewer-bcf-status",L))}}),M.append(S)}E.append(M)}})}function hp(i,t){let e=[];for(let[n,s]of[[i.element1Id,i.element1Name],[i.element2Id,i.element2Name]]){let r=n!=null?t.findIndex(o=>o.id!=null&&String(o.id)===String(n)&&!o.mesh):Ay(t,s);r>=0&&!e.includes(r)&&e.push(r)}return e}function Ay(i,t){if(t==null)return-1;let e=i.findIndex(n=>n.name===t);return e>=0&&i.findIndex((n,s)=>s>e&&n.name===t)<0?e:-1}var Ry=["New","Active","Reviewed","Approved","Resolved"],Ph=27,Cy=8,Iy=14,Py=2,Ly=new I(1,-1,.8).normalize();function up({shell:i,tests:t,elements:e,scene:n,controls:s,selection:r}){let o=new Re;o.name="clash-marker";let a=new le;a.setAttribute("position",new Se(new Float32Array(3),3));let l={color:"#ef4444",depthTest:!1,depthWrite:!1,transparent:!0},c=new Pi(a,new ci({...l,size:Iy,sizeAttenuation:!1}));c.frustumCulled=!1,c.renderOrder=1002,o.add(c),o.visible=!1;let h=null,d=null;function u(){o.visible=!1,h?.removeAttribute("aria-current"),h=null,d=null,s.setExtraBounds("clash",null)}function p(b,E){let M=hp(b,e);M.length?r.set(M):r.clear();let v=new I(...b.point),S=0;for(let T of M){let R=n.elementBox(T);R.isEmpty()||(S=Math.max(S,...R.getSize(new I).toArray()))}let A=s.camera.position.clone().sub(s.target);A.lengthSq()<1e-12&&A.copy(Ly);let x=Math.max(3*S,Py);s.animateTo({position:A.normalize().multiplyScalar(x).add(v),target:v}),a.attributes.position.setXYZ(0,v.x,v.y,v.z),a.attributes.position.needsUpdate=!0,o.visible=!0,h?.removeAttribute("aria-current"),h=E,d=b,E.setAttribute("aria-current","true"),s.setExtraBounds("clash",new ie(v.clone(),v.clone()))}function g(b){let E=gl("ioviewer-row ioviewer-clash",String(b.name??""));E.setAttribute("title",`${b.name??""}: ${b.element1Name??""} \u2014 ${b.element2Name??""}`);let M=Ry.includes(b.status),v=tt("span","ioviewer-clash-status",M?st(`clash.${b.status}`):String(b.status??""));M&&(v.dataset.status=b.status);let S=typeof b.distance=="number"?Rh(b.distance):"";return E.append(v,tt("span","ioviewer-clash-distance",S)),b===d&&(h=E,E.setAttribute("aria-current","true")),E.addEventListener("click",()=>p(b,E)),E}function _(b,E){let M=tt("div","ioviewer-clash-test"),v=tt("button","ioviewer-row ioviewer-clash-header");v.type="button",v.setAttribute("aria-expanded","true");let S=`${b.name??""} (${b.clashes.length})`;v.setAttribute("title",S),v.insertAdjacentHTML("afterbegin",Zt.chevron),v.append(tt("span","ioviewer-row-name",S));let A=tt("div","ioviewer-clash-list");return A.style.height=`${Math.max(0,b.clashes.length*Ph-1)}px`,v.addEventListener("click",()=>{A.hidden=!A.hidden,v.setAttribute("aria-expanded",String(!A.hidden)),E()}),M.append(v,A),{box:M,list:A,clashes:b.clashes,rows:new Map}}function m({list:b,clashes:E,rows:M},{start:v,end:S}){for(let[x,T]of M)(x=S)&&(T.remove(),M.delete(x));let A=null;for(let x=S-1;x>=v;x--){let T=M.get(x);T||(T=g(E[x]),T.style.top=`${x*Ph}px`,b.insertBefore(T,A),M.set(x,T)),A=T}}function f(b){if(!t.length)return;b.classList.add("ioviewer-clashes-body");let E=t.map(v=>_(v,M));for(let v of E)b.append(v.box);function M(){let v=b.scrollTop,S=b.clientHeight,A=E.map(({list:x,clashes:T})=>S&&!x.hidden?vh(v-x.offsetTop,Ph,S,T.length,Cy):{start:0,end:0});E.forEach((x,T)=>m(x,A[T]))}b.addEventListener("scroll",M),b.addEventListener("focusin",M),new ResizeObserver(M).observe(b)}return i.registerPanel("clashes",{icon:Zt.clashes,title:st("panel.clashes"),visible:t.length>0,render:f,onClose:()=>o.visible&&u()}),{group:o}}var Dy=["construct","demolish","temporary"],Ny=Date.parse("0002-01-01T00:00:00Z");function dp(i){let t=typeof i=="string"?Date.parse(i):NaN;return t>=Ny?t:NaN}function fp(i,t){let e=new Map(t.flatMap((o,a)=>o.mesh||o.id==null?[]:[[String(o.id),a]])),n=[];for(let o of Array.isArray(i?.tasks)?i.tasks:[]){let a=dp(o?.start),l=dp(o?.end);if(!(a<=l))continue;let c=Dy.includes(o.type)?o.type:"construct",h=Array.isArray(o.attachedElements)?o.attachedElements:[];n.push({name:o.name,type:c,start:a,end:l,elements:h.map(d=>e.get(String(d))).filter(d=>d!==void 0)})}let s=n.reduce((o,a)=>Math.min(o,a.start),1/0),r=n.reduce((o,a)=>Math.max(o,a.end),-1/0);return{start:s,end:r,tasks:n}}function pp(i,t){let e=new Set,n=new Map;for(let s of i){let r=ts.end,a=s.type==="construct"?r:s.type==="demolish"?o:r||o;for(let l of s.elements)a?e.add(l):!r&&!o&&n.set(l,s.type)}for(let s of e)n.delete(s);return{hidden:e,active:n}}var Uy=864e5,Fy=["1","5","15"],By={construct:"#22c55e",demolish:"#ef4444",temporary:"#a855f7"};function mp({root:i,shell:t,timeliner:e,elements:n,scene:s}){let r=fp(e,n);if(r.tasks.length===0)return t.registerPanel("timeliner",{icon:Zt.timeliner,title:st("panel.timeliner"),visible:!1,render:()=>{}}),null;let o=new Intl.DateTimeFormat(void 0,{dateStyle:"short",timeZone:"UTC"}),a=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeZone:"UTC"}),l=r.start,c=1,h=0,d=0,u=!1,p=new Set,g=new Map,_=tt("div","ioviewer-player ioviewer-floating");_.setAttribute("role","group"),_.setAttribute("aria-label",st("player.title")),_.hidden=!0;let m=Ke("ioviewer-icon-button ioviewer-player-play",Zt.play,st("player.play"));m.addEventListener("click",()=>h?N():L());let f=tt("output","ioviewer-player-date"),b=tt("input","ioviewer-player-slider");Object.assign(b,{type:"range",min:String(r.start),max:String(r.end),step:"any"}),b.setAttribute("aria-label",st("player.date")),b.addEventListener("input",()=>A(Number(b.value)));let E=Nr(st("player.speed"),Fy.map(C=>[C,`${C}\xD7`]),C=>{c=Number(C),E.update(C)});E.update(String(c));let M=Ke("ioviewer-panel-close",Zt.close,st("close"));M.addEventListener("click",T),_.append(m,f,b,E.element,M),i.append(_),new ResizeObserver(()=>{let C=_.hidden?0:_.offsetHeight+8;i.style.setProperty("--player-space",`${C}px`)}).observe(_);function S(){let C=pp(r.tasks,l),B=[...p].filter(D=>!C.hidden.has(D)),z=[...C.hidden].filter(D=>!p.has(D));p=C.hidden;let W=[...g.keys()].filter(D=>C.active.get(D)!==g.get(D)),F=new Map;for(let[D,X]of C.active)g.get(D)!==X&&(F.has(X)||F.set(X,[]),F.get(X).push(D));g=C.active,B.length&&s.setLayerHidden("schedule",B,!1),z.length&&s.setLayerHidden("schedule",z,!0),W.length&&s.setTint(W,null);for(let[D,X]of F)s.setTint(X,By[D])}function A(C){l=Math.min(Math.max(C,r.start),r.end),b.value=String(l),f.textContent=a.format(l),u&&S()}function x(){u||(u=!0,_.hidden=!1,A(r.start))}function T(){u&&(N(),u=!1,s.setTint([...g.keys()],null),g=new Map,p=new Set,s.clearLayer("schedule"),_.hidden=!0)}function R(C){A(l+Math.max(C-d,0)/1e3*c*Uy),d=C,l>=r.end?N():h=requestAnimationFrame(R)}function L(){x(),!h&&(l>=r.end&&A(r.start),d=performance.now(),h=requestAnimationFrame(R),U())}function N(){cancelAnimationFrame(h),h=0,U()}function U(){let C=st(h?"player.pause":"player.play");m.innerHTML=h?Zt.pause:Zt.play,m.title=C,m.setAttribute("aria-label",C)}return t.registerPanel("timeliner",{icon:Zt.timeliner,title:st("panel.timeliner"),render:C=>{let B=tt("button","ioviewer-text-button ioviewer-player-open");B.type="button",B.insertAdjacentHTML("afterbegin",Zt.play),B.append(tt("span","",st("player.play"))),B.addEventListener("click",L);let z=tt("div","ioviewer-row-list");for(let W of r.tasks){let F=String(W.name??""),D=tt("div","ioviewer-row ioviewer-task");D.dataset.type=W.type,D.setAttribute("title",`${F} \xB7 ${st(`task.${W.type}`)}`);let X=`${o.format(W.start)} \u2013 ${o.format(W.end)}`;D.append(tt("span","ioviewer-row-name",F),tt("span","ioviewer-task-dates",X)),z.append(D)}C.append(B,z)}}),{open:x,close:T,play:L,pause:N,setDate:A,get date(){return l},get isOpen(){return u}}}function gp({shell:i,files:t,elements:e,scene:n}){let s=t.map(o=>({file:o,members:o.members??e.flatMap((a,l)=>a.link!=null&&(a.link===o.name||a.link===o.path)?[l]:[]),input:tt("input")})),r=()=>n.replaceLayerHidden("links",s.flatMap(({input:o,members:a})=>o.checked?[]:a));return i.registerPanel("links",{icon:Zt.links,title:st("panel.links"),visible:s.length>0,render:o=>{let a=tt("div","ioviewer-row-list");for(let l of s){let c=String(l.file.name??""),h=tt("label","ioviewer-row ioviewer-check ioviewer-link");h.setAttribute("title",`${c} (${l.file.path??""})`);let{input:d}=l;d.type="checkbox",d.checked=l.members.length===0||l.file.visible!==!1,d.disabled=l.members.length===0,d.addEventListener("change",r),h.append(d,tt("span","ioviewer-row-name",c),tt("span","ioviewer-row-count",String(l.members.length))),a.append(h)}o.append(a),r()}}),o=>{let a=new Set(o);for(let{file:l,input:c}of s)c.checked=c.disabled||!a.has(l.key);r()}}document.documentElement.lang=Ls;var Hn=document.getElementById("ioviewer-canvas"),Lh=window.IOVIEWER_TEST??{},Ur=Lh.startup;function Fr(i){let t=document.getElementById("ioviewer-message");t.textContent=i,t.hidden=!1}try{let i=Kc(document,Ur);i.title&&(document.title=i.title);let t=Hn.getContext("webgl2",{antialias:!0,stencil:!0});t?Oy(Wd(document,Ur,i),t):Fr(st("noWebGL"))}catch(i){if(!(i instanceof re))throw i;Fr(st("badData"))}function Oy(i,t){let e=new As({canvas:Hn,context:t,antialias:!0,stencil:!0,logarithmicDepthBuffer:Tf(i.meta)});e.setPixelRatio(window.devicePixelRatio),e.autoClearStencil=!1,e.localClippingEnabled=!0;let n=new Ri,s="#1f2228",r=new Ft(s);e.setClearColor(r,1);let o=new rr("#ffffff","#8a8f99",1.6);o.position.set(0,0,1),n.add(o);let a=new $e(45,1,.1,1e3);a.up.set(0,0,1),a.position.set(1,-1,.8);let l=new ar("#ffffff",1.4);l.position.set(.3,.6,0),a.add(l,l.target),l.target.position.set(0,0,-1),n.add(a),Ur?.("sceneStart");let c=b();Ur?.("sceneEnd"),i.releaseBinary();let h=new el(c,x,Math.min(c.totalCost,2e7));n.add(c.root);let d=new al(c,c.visibleBox(),i.meta.sections),u=t.getContextAttributes()?.stencil===!0,p,g=new hl(d,Hn);n.add(g.group);let _=document.getElementById("ioviewer-ui"),m=new dl(_),f=new ml(_,i.meta.grids??[]);n.add(m.group,f.group);function b(){try{let et=new Rr(i,{...Lh,maxTextureSize:e.capabilities.maxTextureSize});return et.totalCost===0&&Fr(st("noGeometry")),et}catch(et){if(!(et instanceof Ar))throw et;Fr(st("tooLarge").replace("{count}",et.count).replace("{limit}",et.limit));let V=ut=>({o:0,n:0,t:ut}),j={count:0,geometry:V("u32"),material:V("u32"),element:V("i32"),matrix:V("f32")};return new Rr({...i,meta:{...i.meta,instances:j}})}}let E=!1;Hn.addEventListener("webglcontextlost",()=>{E=!0,Fr(st("contextLost"))});let M,v=new Promise(et=>M=et),S=Ur,A=!1;function x(){A||E||(A=!0,h.requested(performance.now()),requestAnimationFrame(()=>{if(A=!1,E)return;let et=Hn.getBoundingClientRect();z.camera.updateMatrixWorld(),g.update(z.camera),m.update(z.camera,et),f.update(z.camera,et),h.begin(z.camera,et.height,performance.now()),S?.("renderStart"),d.fill&&u?(p??(p=new ul(c,d,i)),p.render(e,n,z.camera)):e.render(n,z.camera),S&&(S("renderEnd"),S=void 0),h.end(performance.now()),ct.update(),M()}))}c.root.addEventListener("change",x),d.addEventListener("change",x),g.addEventListener("change",x),m.addEventListener("change",x),m.addEventListener("previewchange",x),f.addEventListener("change",x);let T=new Qa(e,c,a,{pickFloat:Lh.pickFloat}),R=new pl(T,d,i),L=0,N=null;function U(){cancelAnimationFrame(L),L=0,N=null,m.setPreview(null)}function C(){L=0,N&&m.setPreview(R.target(...N))}function B(){N&&(m.setPreview(null),cancelAnimationFrame(L),L=requestAnimationFrame(()=>{L=requestAnimationFrame(C)}))}Hn.addEventListener("pointermove",et=>{if(!m.active||et.buttons)return U();N=[et.clientX,et.clientY],L||(L=requestAnimationFrame(C))});for(let et of["pointerdown","pointerleave","pointercancel","webglcontextlost"])Hn.addEventListener(et,U);c.root.addEventListener("change",et=>{et.detail.kind!=="appearance"&&B()});let z=new Za(a,Hn,{pick:(et,V)=>T.pick(et,V)?.point??null,visibleBox:()=>c.visibleBox()});z.addEventListener("change",()=>{T.camera=z.camera,B(),x()}),c.root.addEventListener("change",et=>{et.detail.kind==="visibility"&&(z.invalidateBounds(),z.resize())});let W=new il;W.addEventListener("change",()=>c.setHighlighted([...W.values()]));let F=Zf({root:_,data:i,scene:c,controls:z,picker:T,selection:W,measure:m});sp({root:_,...F,sections:d,selection:W,canFill:u});let{meta:D}=i,X=gp({...F,files:D.linkedFiles??[],elements:D.elements,scene:c});cp({...F,controls:z,scene:c,sections:d,selection:W,restoreLinkedModels:X,views:D.viewpoints??[],bcfTopics:D.bcfTopics??[]});let Z=up({...F,tests:D.clashTests??[],elements:D.elements,scene:c,controls:z,selection:W});n.add(Z.group);let G=mp({root:_,...F,timeliner:D.timeliner,elements:D.elements,scene:c}),Q=et=>{e.setClearColor(r.set(et),1);let{r:V,g:j,b:ut}=r,Mt=.2126*V+.7152*j+.0722*ut>Math.sqrt(.0525)-.05?"#000":"#fff";_.style.setProperty("--viewport-text",et===s?"":Mt),x()};for(let et of lp({root:_,toolbar:F.toolbar,scene:c,meta:D,grids:f,initialBackground:s,setBackground:Q}))F.onEscape(et.close);F.toolbar.setHandler("distance",()=>{U(),m.setActive(!m.active),m.active||R.release(),F.toolbar.setActive("distance",m.active)}),F.toolbar.setActive("distance",!1),F.onEscape(()=>(U(),m.clear()));let lt=()=>{z.setExtraBounds("grids",f.visible?f.box:null),z.setExtraBounds("measure",m.box)};f.addEventListener("change",lt),m.addEventListener("change",lt),lt(),z.addEventListener("click",et=>{let{x:V,y:j,ctrl:ut,shift:Lt}=et.detail;if(m.active){let ve=R.target(V,j);ve&&m.add(ve.point);return}let Bt=T.pick(V,j)?.element??-1;ut?Bt>=0&&W.toggle(Bt):Bt>=0?W.set([Bt]):Lt||W.clear()}),z.addEventListener("boxselect",et=>{if(m.active)return;let{rect:V,mode:j,ctrl:ut,shift:Lt}=et.detail;if(V.width<4||V.height<4){!ut&&!Lt&&W.clear();return}let Mt=new ie,Bt=Nf(V,j,Uf(c,z.camera,Hn.getBoundingClientRect())),ve=d.clipping(),Vt=Bt.filter(Jt=>!d.isCut(c.elementBox(Jt,Mt),ve));W.set(ut?[...W.values(),...Vt]:Vt)}),window.addEventListener("resize",()=>{e.setSize(window.innerWidth,window.innerHeight,!1),z.resize()}),e.setSize(window.innerWidth,window.innerHeight,!1),z.resize(),z.fitBox(c.visibleBox(),!1);let ct=new ja(document.getElementById("ioviewer-ui"),a,z);window.addEventListener("pointerdown",et=>{(et.target===Hn||ct.element.contains(et.target))&&document.activeElement?.blur()},!0),window.__ioviewer={scene:c,motionDetail:h,controls:z,picker:T,selection:W,ui:F,viewCube:ct,sections:d,sectionGizmo:g,measure:m,measureSnap:R,grids:f,clashes:Z,timeliner:G,ready:v,get camera(){return z.camera}}}})(); /*! Bundled license information: three/build/three.core.js: diff --git a/src/IOViewer/Viewer/federate-mesh-pages.js b/src/IOViewer/Viewer/federate-mesh-pages.js new file mode 100644 index 0000000..4a4b8cf --- /dev/null +++ b/src/IOViewer/Viewer/federate-mesh-pages.js @@ -0,0 +1,76 @@ +import { createReadStream, createWriteStream } from 'node:fs'; +import { mkdir, open, readFile, stat, writeFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import { pipeline } from 'node:stream/promises'; +import { MESH_FORMAT, sizeOfPage, validateMeshPages } from './src/stream/meshPages.js'; + +const [destination, targetText, ...folders] = process.argv.slice(2); +const target = Number(targetText); +if (!destination || !Number.isSafeInteger(target) || target <= 0 || folders.length < 2) { + throw new Error('Usage: node federate-mesh-pages.js ...'); +} +const sources = await Promise.all(folders.map(async (folder) => { + const manifest = validateMeshPages(JSON.parse(await readFile(join(folder, 'manifest.json')))); + const file = join(folder, 'meshes.bin'); + // shortcut: benchmark placements carry geometry only, add namespaced element IDs if federated BIM review is needed. + if ((await stat(file)).size !== manifest.bytes || manifest.elements || manifest.pages.some((page) => page.shift)) { + throw new Error('Expected a geometry-only package made directly from an input model.'); + } + return { manifest, file }; +})); +const plan = []; +for (let bytes = 0; bytes < target;) { + const source = sources[plan.length % sources.length]; + plan.push(source); + bytes += source.manifest.bytes; +} +const columns = Math.ceil(Math.sqrt(plan.length)); +const pitch = [0, 1].map((axis) => 20 + Math.max(...sources.map(({ manifest }) => manifest.max[axis] - manifest.min[axis]))); +const min = [Infinity, Infinity, Infinity], max = [-Infinity, -Infinity, -Infinity]; +const pages = [], roots = [], placements = []; +let bytes = 0, overview = 0, triangles = 0; +for (const [i, { manifest }] of plan.entries()) { + const shift = [i % columns * pitch[0] - manifest.min[0], Math.floor(i / columns) * pitch[1] - manifest.min[1], -manifest.min[2]]; + const point = (p) => p.map((n, axis) => n + shift[axis]); + const transformed = (bounds) => ({ min: point(bounds.min), max: point(bounds.max) }); + const first = pages.length; + for (const page of manifest.pages) pages.push({ ...page, ...transformed(page), shift, + offset: bytes + page.offset, children: page.children.map((id) => first + id) }); + for (const id of manifest.roots) { + roots.push(first + id); + overview += sizeOfPage(manifest.pages[id]); + } + placements.push(transformed(manifest.focus ?? manifest)); + const bounds = transformed(manifest); + for (let axis = 0; axis < 3; axis++) { + min[axis] = Math.min(min[axis], bounds.min[axis]); + max[axis] = Math.max(max[axis], bounds.max[axis]); + } + bytes += manifest.bytes; + triangles += manifest.triangles; +} +const manifest = validateMeshPages({ format: MESH_FORMAT, origin: [0, 0, 0], min, max, pages, roots, placements, bytes, triangles, overview }); +await mkdir(destination); +const packed = join(destination, 'meshes.bin'); +await (await open(packed, 'wx')).close(); +for (const [i, { file }] of plan.entries()) { + await pipeline(createReadStream(file), createWriteStream(packed, { flags: 'a' })); + console.log(`Copied ${i + 1}/${plan.length} placements`); +} +if ((await stat(join(destination, 'meshes.bin'))).size !== bytes) throw new Error('Incomplete federation archive.'); +const rootFile = await open(join(destination, 'overview.bin'), 'wx'); +try { + for (const { manifest: source, file } of plan) { + const handle = await open(file, 'r'); + try { + for (const id of source.roots) { + const page = source.pages[id], length = sizeOfPage(page), buffer = Buffer.alloc(length); + const { bytesRead } = await handle.read(buffer, 0, length, page.offset); + if (bytesRead !== length) throw new Error('Truncated overview page.'); + await rootFile.writeFile(buffer); + } + } finally { await handle.close(); } + } +} finally { await rootFile.close(); } +await writeFile(join(destination, 'manifest.json'), JSON.stringify(manifest), { flag: 'wx' }); +console.log(`${plan.length} placements, ${pages.length} pages, ${triangles} triangles, ${bytes} bytes`); diff --git a/src/IOViewer/Viewer/pack-clusters.js b/src/IOViewer/Viewer/pack-clusters.js new file mode 100644 index 0000000..813b374 --- /dev/null +++ b/src/IOViewer/Viewer/pack-clusters.js @@ -0,0 +1,116 @@ +import { closeSync, mkdirSync, openSync, readFileSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { validateManifest } from './src/stream/manifest.js'; +import { CLUSTER_FORMAT, detailInputBytes, FACES, INSTANCE_FLOATS, STEP, VERTICES } from './src/stream/clusters.js'; +import { readTile } from './src/stream/tile.js'; +import { unitNormals } from './src/engine/chunks.js'; +import { buildMeshPages } from './build-mesh-pages.js'; + +const [source, destination, mode, ...extras] = process.argv.slice(2); +const native = source?.toLowerCase().endsWith('.ivmesh'); +if (!source || !destination || extras.length || (mode && (!native || mode !== '--geometry-only'))) { + throw new Error('Usage: npm run pack-clusters -- [--geometry-only]'); +} +if (native) { + await buildMeshPages(source, destination, mode !== '--geometry-only'); + process.exit(0); +} +const manifest = validateManifest(JSON.parse(readFileSync(join(source, 'manifest.json')))); +const origin = manifest.min.map((n, i) => (n + manifest.max[i]) / 2); +const palette = [], roots = []; +let first = 0, offset = 0, id = 0; +mkdirSync(destination); +const coarse = openSync(join(destination, 'coarse.bin'), 'wx'); +const detail = openSync(join(destination, 'detail.bin'), 'wx'); +try { + for (const tile of manifest.tiles) { + const data = readTile(readFileSync(join(source, tile.file)), tile); + const { meta } = data; + const instances = meta.instances; + const shapes = data.view(instances.geometry), material = data.view(instances.material), matrices = data.view(instances.matrix); + if (instances.count !== tile.elements || instances.count > 6400 || tile.triangles !== instances.count * FACES.length / 3) { + throw new Error(`${tile.file}: unsupported vessel topology.`); + } + const colors = meta.materials.map(({ color, opacity, texture }) => { + if (opacity !== 1 || texture != null) throw new Error('Expected an opaque vessel material.'); + let index = palette.findIndex((entry) => entry.every((n, i) => n === color[i])); + if (index < 0) { index = palette.length; palette.push(color); } + if (index >= 3) throw new Error('Expected at most three vessel materials.'); + return index; + }); + const children = []; + const root = { x: tile.x, y: tile.y, min: tile.min, max: tile.max, first, count: instances.count, children }; + const cells = Array.from({ length: 100 }, () => []); + for (let i = 0; i < instances.count; i++) { + const x = Math.floor((i % 40) / 4), y = Math.floor((Math.floor(i / 40) % 40) / 4); + cells[y * 10 + x].push(i); + } + for (const members of cells) { + if (!members.length) continue; + members.sort((a, b) => colors[material[a]] - colors[material[b]]); + const min = [Infinity, Infinity, Infinity], max = [-Infinity, -Infinity, -Infinity]; + for (const i of members) { + const shape = meta.geometries[shapes[i]]; + for (let axis = 0; axis < 3; axis++) { + const place = matrices[i * 12 + 9 + axis] + tile.rtcOffset[axis]; + min[axis] = Math.min(min[axis], shape.bbox.min[axis] + place); + max[axis] = Math.max(max[axis], shape.bbox.max[axis] + place); + } + } + const anchor = min.map((n, axis) => Math.floor((n - tile.rtcOffset[axis]) / STEP) * STEP); + const boxes = new Float32Array(members.length * INSTANCE_FLOATS); + const page = new ArrayBuffer(detailInputBytes(members.length)); + const positions = new Uint16Array(page, 0, members.length * VERTICES * 3); + const normals = new Int16Array(page, positions.byteLength); + const counts = [0, 0, 0]; + for (let j = 0; j < members.length; j++) { + const i = members[j], shape = meta.geometries[shapes[i]]; + const src = data.view(shape.positions), indices = data.view(shape.indices); + const matrix = matrices.subarray(i * 12, i * 12 + 12); + if (!(src instanceof Uint16Array) || src.length !== VERTICES * 3 || shape.q?.s !== STEP || !shape.q.o.every((n) => n === 0) + || shape.normals || indices.length !== FACES.length || indices.some((n, t) => n !== FACES[t]) + || matrix.subarray(0, 9).some((n, k) => n !== +(k % 4 === 0))) throw new Error('Expected the authored vessel mesh.'); + const color = colors[material[i]]; + counts[color]++; + const { min: low, max: high } = shape.bbox; + const start = j * VERTICES * 3, at = j * INSTANCE_FLOATS; + const shifts = []; + for (let axis = 0; axis < 3; axis++) { + const place = matrix[9 + axis]; + const shift = (place - anchor[axis]) / STEP; + if (!Number.isInteger(shift)) throw new Error('Position would lose precision.'); + shifts.push(shift); + const center = axis < 2 ? (low[axis] + high[axis]) / 2 : low[axis]; + boxes[at + axis] = center + place + tile.rtcOffset[axis] - origin[axis]; + boxes[at + 3 + axis] = (high[axis] - low[axis]) / (axis < 2 ? 2.14 : 1); + } + boxes[at + 6] = color; + const normal = unitNormals({ positions: src, q: shape.q, indices }); + for (let k = 0; k < src.length; k++) { + const value = src[k] + shifts[k % 3]; + if (value < 0 || value > 65535) throw new Error('Cluster exceeds its quantization range.'); + positions[start + k] = value; + normals[start + k] = Math.round(normal[k] * 32767); + } + } + writeFileSync(coarse, boxes); + writeFileSync(detail, new Uint8Array(page)); + children.push({ id: id++, min, max, anchor: anchor.map((n, axis) => n + tile.rtcOffset[axis] - origin[axis]), + first, count: members.length, counts, offset }); + first += members.length; + offset += page.byteLength; + } + roots.push(root); + if (roots.length % 10 === 0) console.log(`${roots.length}/${manifest.tiles.length} areas, ${id} clusters`); + } + if (first !== manifest.elements || !palette.length) throw new Error('Unexpected cluster totals.'); + while (palette.length < 3) palette.push(palette[0]); + writeFileSync(join(destination, 'manifest.json'), JSON.stringify({ + format: CLUSTER_FORMAT, sourceBytes: manifest.totalBytes, elements: first, triangles: manifest.triangles, + min: manifest.min, max: manifest.max, origin, palette, roots, detailBytes: offset, + }), { flag: 'wx' }); + console.log(`${first} vessels, ${id} clusters, ${offset} bytes of fine geometry`); +} finally { + closeSync(detail); + closeSync(coarse); +} diff --git a/src/IOViewer/Viewer/package-lock.json b/src/IOViewer/Viewer/package-lock.json index 916a3a8..531c6fe 100644 --- a/src/IOViewer/Viewer/package-lock.json +++ b/src/IOViewer/Viewer/package-lock.json @@ -10,7 +10,8 @@ }, "devDependencies": { "@playwright/test": "1.65.0", - "esbuild": "0.28.2" + "esbuild": "0.28.2", + "meshoptimizer": "1.3.0" } }, "node_modules/@esbuild/aix-ppc64": { @@ -513,6 +514,13 @@ "@esbuild/win32-x64": "0.28.2" } }, + "node_modules/meshoptimizer": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/meshoptimizer/-/meshoptimizer-1.3.0.tgz", + "integrity": "sha512-2oZqMAcEEiCtXWUjIGtZ71oPx1B0ZxYGTqIKsXB1wzWFhleNsCFxQuUJzgCV706bRcwPWtMGf1odmQvAcqKkIw==", + "dev": true, + "license": "MIT" + }, "node_modules/playwright": { "version": "1.65.0", "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.65.0.tgz", diff --git a/src/IOViewer/Viewer/package.json b/src/IOViewer/Viewer/package.json index 9dee57f..2f502a5 100644 --- a/src/IOViewer/Viewer/package.json +++ b/src/IOViewer/Viewer/package.json @@ -6,13 +6,16 @@ "build": "esbuild src/main.js --bundle --minify --format=iife --target=es2020 --outfile=dist/viewer.js", "test": "node --test test/unit/*.test.js", "e2e": "npm run build && playwright test --project=chromium", - "perf": "npm run build && playwright test --config playwright.perf.config.js" + "perf": "npm run build && playwright test --config playwright.perf.config.js", + "stream": "node serve-stream.js", + "pack-clusters": "node pack-clusters.js" }, "dependencies": { "three": "0.186.1" }, "devDependencies": { "@playwright/test": "1.65.0", - "esbuild": "0.28.2" + "esbuild": "0.28.2", + "meshoptimizer": "1.3.0" } } diff --git a/src/IOViewer/Viewer/serve-stream.js b/src/IOViewer/Viewer/serve-stream.js new file mode 100644 index 0000000..098ada1 --- /dev/null +++ b/src/IOViewer/Viewer/serve-stream.js @@ -0,0 +1,136 @@ +import { build } from 'esbuild'; +import { createReadStream } from 'node:fs'; +import { readFile, realpath, stat } from 'node:fs/promises'; +import { createServer } from 'node:http'; +import { dirname, join } from 'node:path'; +import { pipeline } from 'node:stream/promises'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { MAX_MANIFEST, validateManifest } from './src/stream/manifest.js'; +import { CLUSTER_FORMAT, detailInputBytes, INSTANCE_FLOATS, validateClusters } from './src/stream/clusters.js'; +import { MESH_FORMAT, MESH_MANIFEST_BYTES, sizeOfPage, validateMeshPages } from './src/stream/meshPages.js'; + +const root = dirname(fileURLToPath(import.meta.url)); + +export async function startStreamServer(folder, port = 0) { + const directory = await realpath(folder); + const manifestPath = await localFile(directory, 'manifest.json'); + const manifestLimit = MESH_MANIFEST_BYTES; + if ((await stat(manifestPath)).size > manifestLimit) throw new Error('Manifest exceeds its size limit.'); + const json = await readFile(manifestPath); + if (json.length > manifestLimit) throw new Error('Manifest exceeds its size limit.'); + const manifest = JSON.parse(json); + const clustered = manifest?.format === CLUSTER_FORMAT; + const meshes = manifest?.format === MESH_FORMAT; + const files = new Map(); + async function fileInfo(name, length) { + const path = await localFile(directory, name); + if ((await stat(path)).size !== length) throw new Error(`${name} differs from the manifest.`); + return { name, length }; + } + if (meshes) { + validateMeshPages(manifest); + const info = await fileInfo('meshes.bin', manifest.bytes); + for (const [id, page] of manifest.pages.entries()) { + files.set(`/pages/${id}`, { ...info, start: page.offset, size: sizeOfPage(page) }); + } + if (manifest.overview) { + files.set('/overview.bin', { ...await fileInfo('overview.bin', manifest.overview), start: 0, size: manifest.overview }); + } + if (manifest.propertyBytes) { + const properties = await fileInfo('elements.bin', manifest.propertyBytes); + for (const [id, element] of manifest.elements.entries()) if (element.size) { + files.set(`/elements/${id}`, { ...properties, start: element.offset, size: element.size }); + } + } + } else if (clustered) { + if (json.length > 6 * MAX_MANIFEST) throw new Error('Manifest exceeds its size limit.'); + validateClusters(manifest); + const coarse = await fileInfo('coarse.bin', manifest.elements * INSTANCE_FLOATS * 4); + const detail = await fileInfo('detail.bin', manifest.detailBytes); + files.set('/coarse.bin', { ...coarse, start: 0, size: coarse.length }); + for (const root of manifest.roots) for (const page of root.children) { + files.set(`/pages/${page.id}`, { ...detail, start: page.offset, size: detailInputBytes(page.count) }); + } + } else { + if (json.length > MAX_MANIFEST) throw new Error('Manifest exceeds its size limit.'); + validateManifest(manifest); + for (const tile of manifest.tiles) { + files.set(`/tiles/${tile.file}`, { ...await fileInfo(tile.file, tile.bytes), start: 0, size: tile.bytes }); + } + } + + const bundle = async (entry) => (await build({ + entryPoints: [join(root, 'src', 'stream', entry)], bundle: true, write: false, format: 'esm', minify: true, target: 'es2022', + })).outputFiles[0].contents; + const [html, css, viewer, worker] = await Promise.all([ + readFile(join(root, 'stream.html')), readFile(join(root, 'styles', 'viewer.css')), + bundle(meshes ? 'meshLod.js' : clustered ? 'lod.js' : 'main.js'), + meshes || clustered ? null : bundle('tileWorker.js'), + ]); + const assets = new Map([ + ['/', [html, 'text/html; charset=utf-8']], ['/manifest.json', [json, 'application/json']], + ['/viewer.css', [css, 'text/css']], ['/stream.js', [viewer, 'text/javascript']], + ]); + if (worker) assets.set('/tile-worker.js', [worker, 'text/javascript']); + const server = createServer(async (request, response) => { + if (request.headers.host !== `127.0.0.1:${server.address().port}`) { + response.writeHead(403).end(); + return; + } + if (request.method !== 'GET' && request.method !== 'HEAD') { + response.writeHead(405, { Allow: 'GET, HEAD' }).end(); + return; + } + const send = (body, length, type) => { + response.writeHead(200, { 'Content-Type': type, 'Content-Length': length, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' }); + if (request.method === 'HEAD' || body) response.end(request.method === 'HEAD' ? undefined : body); + }; + const asset = assets.get(request.url); + if (asset) { + send(asset[0], asset[0].byteLength, asset[1]); + return; + } + const tile = files.get(request.url); + if (!tile) { + response.writeHead(404).end(); + return; + } + try { + const file = await localFile(directory, tile.name); + if ((await stat(file)).size !== tile.length) throw new Error('Geometry file size changed.'); + send(null, tile.size, 'application/octet-stream'); + if (request.method === 'GET') await pipeline(createReadStream(file, { start: tile.start, end: tile.start + tile.size - 1 }), response); + } catch (error) { + // Panning away can close a response while the file is being read. + if (!response.headersSent && !response.destroyed) response.writeHead(500).end(); + else if (!response.destroyed) response.destroy(error); + } + }); + await new Promise((resolve, reject) => { + server.once('error', reject); + server.listen(port, '127.0.0.1', () => { server.off('error', reject); resolve(); }); + }); + return { server, url: `http://127.0.0.1:${server.address().port}/` }; +} + +async function localFile(directory, name) { + const path = join(directory, name); + if (await realpath(path) !== path || !(await stat(path)).isFile()) throw new Error(`Expected a regular file: ${name}`); + return path; +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + const folder = process.argv[2]; + if (!folder) { + process.stderr.write('Usage: npm run stream -- [port]\n'); + process.exitCode = 2; + } else { + try { + const { url } = await startStreamServer(folder, process.argv[3] === undefined ? 8787 : Number(process.argv[3])); + process.stdout.write(`IOViewer ${url}\n`); + } catch (error) { + process.stderr.write(`${error.message}\n`); + process.exitCode = 1; + } + } +} diff --git a/src/IOViewer/Viewer/src/data.js b/src/IOViewer/Viewer/src/data.js index a19bcb3..e2201cc 100644 --- a/src/IOViewer/Viewer/src/data.js +++ b/src/IOViewer/Viewer/src/data.js @@ -5,7 +5,7 @@ const CHUNK_CHARS = 4 * 1024 * 1024; // multiple of 4, so every chunk decodes on function block(doc, id) { const element = doc.getElementById(id); - if (!element) throw new Error(`Data block '${id}' is missing.`); + if (!element) throw new ModelDataError(`Data block '${id}' is missing.`); return element.textContent; } @@ -108,6 +108,20 @@ function validateMeta(meta) { throw new ModelDataError('Invalid META geometry.'); } } + validateReviewMeta(meta); + for (const material of meta.materials) { + const index = material.texture; + if (!vector(material.color) || typeof material.opacity !== 'number' + || (index != null && (!Number.isInteger(index) || index < 0 || index >= (meta.textures?.length ?? 0)))) { + throw new ModelDataError('Invalid META material.'); + } + } +} + +export function validateReviewMeta(meta) { + if (!object(meta) || !records(meta.elements) || (meta.title != null && typeof meta.title !== 'string')) { + throw new ModelDataError('Invalid review metadata.'); + } for (const name of ['textures', 'grids', 'viewpoints', 'bcfTopics', 'clashTests', 'linkedFiles', 'models']) { if (meta[name] != null && !records(meta[name])) throw new ModelDataError(`Invalid META ${name} list.`); } @@ -116,13 +130,6 @@ function validateMeta(meta) { || (levelId != null && !Number.isSafeInteger(levelId)))) { throw new ModelDataError('Invalid META model or level identity.'); } - for (const material of meta.materials) { - const index = material.texture; - if (!vector(material.color) || typeof material.opacity !== 'number' - || (index != null && (!Number.isInteger(index) || index < 0 || index >= (meta.textures?.length ?? 0)))) { - throw new ModelDataError('Invalid META material.'); - } - } const elementIndices = (values) => values == null || (Array.isArray(values) && values.every((i) => Number.isInteger(i) && i >= 0 && i < meta.elements.length)); const finiteVector = (v) => vector(v) && v.every(Number.isFinite); @@ -151,19 +158,42 @@ function validateMeta(meta) { if (!sectionState(meta.sections)) throw new ModelDataError('Invalid META sections.'); } -export function readModelMeta(doc = document, startup) { +export function parseModelMeta(text) { let meta; - startup?.('metadataStart'); try { - meta = JSON.parse(block(doc, 'ioviewer-meta')); + meta = JSON.parse(text); } catch (error) { throw new ModelDataError(error.message, { cause: error }); } validateMeta(meta); + return meta; +} + +export function readModelMeta(doc = document, startup) { + startup?.('metadataStart'); + let text; + try { + text = block(doc, 'ioviewer-meta'); + } catch (error) { + if (error instanceof ModelDataError) throw error; + throw new ModelDataError(error.message, { cause: error }); + } + const meta = parseModelMeta(text); startup?.('metadataEnd'); return meta; } +export function binaryViewType(v, binaryLength) { + const Type = VIEW_TYPES[v?.t]; + if (!Type) throw new ModelDataError(`Unknown view type '${v?.t}'.`); + const size = Type.BYTES_PER_ELEMENT; + if (!(Number.isSafeInteger(v.o) && Number.isSafeInteger(v.n) && v.o >= 0 && v.n >= 0 && v.o % size === 0 + && v.o + v.n * size <= binaryLength)) { + throw new ModelDataError(`View ${JSON.stringify(v)} is outside the ${binaryLength} bytes of binary data.`); + } + return Type; +} + export function loadModelData(doc = document, startup, meta = readModelMeta(doc, startup)) { let bin, binElement, canonical, legacyBin; try { @@ -176,25 +206,16 @@ export function loadModelData(doc = document, startup, meta = readModelMeta(doc, throw new ModelDataError(error.message, { cause: error }); } const binaryLength = bin.length; - function viewType(v) { - const Type = VIEW_TYPES[v?.t]; - if (!Type) throw new ModelDataError(`Unknown view type '${v?.t}'.`); - const size = Type.BYTES_PER_ELEMENT; - if (!(Number.isInteger(v.o) && Number.isInteger(v.n) && v.o >= 0 && v.n >= 0 && v.o % size === 0 && v.o + v.n * size <= binaryLength)) { - throw new ModelDataError(`View ${JSON.stringify(v)} is outside the ${binaryLength} bytes of binary data.`); - } - return Type; - } let props = null; return { meta, view(v) { if (!bin) throw new Error('The binary data has been released.'); - const Type = viewType(v); + const Type = binaryViewType(v, binaryLength); return new Type(bin.buffer, v.o, v.n); }, readView(v) { - const Type = viewType(v); + const Type = binaryViewType(v, binaryLength); if (!v.n) return new Type(0); if (!bin && !canonical) legacyBin ??= decodeBase64(binElement).bytes; const bytes = bin ?? legacyBin; diff --git a/src/IOViewer/Viewer/src/engine/chunks.js b/src/IOViewer/Viewer/src/engine/chunks.js index d9abe00..f081151 100644 --- a/src/IOViewer/Viewer/src/engine/chunks.js +++ b/src/IOViewer/Viewer/src/engine/chunks.js @@ -411,14 +411,26 @@ export function unitNormals(s) { // Area-weighted vertex normals from the faces, as three's computeVertexNormals. function vertexNormals(positions, q, indices) { - const p = (v, a) => (q ? q.o[a] + positions[v * 3 + a] * q.s : positions[v * 3 + a]); const out = new Float32Array(positions.length); + const scale = q?.s ?? 1; for (let t = 0; t < indices.length; t += 3) { - const [a, b, c] = [indices[t], indices[t + 1], indices[t + 2]]; - const e1 = [0, 1, 2].map((k) => p(b, k) - p(a, k)); - const e2 = [0, 1, 2].map((k) => p(c, k) - p(a, k)); - const n = [e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0]]; - for (const v of [a, b, c]) for (let k = 0; k < 3; k++) out[v * 3 + k] += n[k]; + const a = indices[t] * 3, b = indices[t + 1] * 3, c = indices[t + 2] * 3; + const bx = (positions[b] - positions[a]) * scale; + const by = (positions[b + 1] - positions[a + 1]) * scale; + const bz = (positions[b + 2] - positions[a + 2]) * scale; + const cx = (positions[c] - positions[a]) * scale; + const cy = (positions[c + 1] - positions[a + 1]) * scale; + const cz = (positions[c + 2] - positions[a + 2]) * scale; + const x = by * cz - bz * cy, y = bz * cx - bx * cz, z = bx * cy - by * cx; + out[a] += x; + out[a + 1] += y; + out[a + 2] += z; + out[b] += x; + out[b + 1] += y; + out[b + 2] += z; + out[c] += x; + out[c + 1] += y; + out[c + 2] += z; } for (let v = 0; v < out.length; v += 3) { const l = Math.hypot(out[v], out[v + 1], out[v + 2]) || 1; diff --git a/src/IOViewer/Viewer/src/model/clashTargets.js b/src/IOViewer/Viewer/src/model/clashTargets.js index 030144e..9c6fc20 100644 --- a/src/IOViewer/Viewer/src/model/clashTargets.js +++ b/src/IOViewer/Viewer/src/model/clashTargets.js @@ -6,7 +6,7 @@ export function resolveClashElements(clash, elements) { const found = []; for (const [id, name] of [[clash.element1Id, clash.element1Name], [clash.element2Id, clash.element2Name]]) { - const index = id != null ? elements.findIndex((e) => e.id === id && !e.mesh) : uniqueName(elements, name); + const index = id != null ? elements.findIndex((e) => e.id != null && String(e.id) === String(id) && !e.mesh) : uniqueName(elements, name); if (index >= 0 && !found.includes(index)) found.push(index); } return found; diff --git a/src/IOViewer/Viewer/src/model/schedule.js b/src/IOViewer/Viewer/src/model/schedule.js index d668c1f..33e7616 100644 --- a/src/IOViewer/Viewer/src/model/schedule.js +++ b/src/IOViewer/Viewer/src/model/schedule.js @@ -18,7 +18,7 @@ function time(text) { */ export function prepareSchedule(timeliner, elements) { // A per-mesh stand-in element (`mesh: true`) carries a mesh id, which no task refers to. - const indexOf = new Map(elements.flatMap((e, i) => (e.mesh ? [] : [[e.id, i]]))); + const indexOf = new Map(elements.flatMap((e, i) => e.mesh || e.id == null ? [] : [[String(e.id), i]])); const tasks = []; for (const task of Array.isArray(timeliner?.tasks) ? timeliner.tasks : []) { const start = time(task?.start); @@ -26,7 +26,7 @@ export function prepareSchedule(timeliner, elements) { if (!(start <= end)) continue; const type = TASK_TYPES.includes(task.type) ? task.type : 'construct'; const ids = Array.isArray(task.attachedElements) ? task.attachedElements : []; - tasks.push({ name: task.name, type, start, end, elements: ids.filter((id) => indexOf.has(id)).map((id) => indexOf.get(id)) }); + tasks.push({ name: task.name, type, start, end, elements: ids.map((id) => indexOf.get(String(id))).filter((i) => i !== undefined) }); } const start = tasks.reduce((min, task) => Math.min(min, task.start), Infinity); const end = tasks.reduce((max, task) => Math.max(max, task.end), -Infinity); diff --git a/src/IOViewer/Viewer/src/nav/controls.js b/src/IOViewer/Viewer/src/nav/controls.js index 12b77a5..94ebddc 100644 --- a/src/IOViewer/Viewer/src/nav/controls.js +++ b/src/IOViewer/Viewer/src/nav/controls.js @@ -4,6 +4,8 @@ import { isClick, orbit, zoomTowards, wheelZoomFactor, boxSelectMode, interpolat const ORBIT_SPEED = 0.005; // radians per pixel const DEFAULT_DIRECTION = new THREE.Vector3(1, -1, 0.8).normalize(); const NEAR_MIN = 0.01; // metres +const MIN_VIEW_DISTANCE = 1e-6; +const MAX_VIEW_RADII = 64; const FAR_MARGIN = 1.05; const LINEAR_DEPTH_RATIO = 5000; @@ -239,6 +241,20 @@ export class NavigationControls extends EventTarget { this._drag = { id: e.pointerId, button: e.button, mode, pivot, down: point, last: point, moved: false }; } + _anchor(x, y) { + const point = this.pick(x, y); + if (point) return point; + const rect = this.dom.getBoundingClientRect(); + const cx = rect.left + rect.width / 2, cy = rect.top + rect.height / 2; + return x === cx && y === cy ? null : this.pick(cx, cy); + } + + _gestureDepth(point, forward) { + const cam = this.camera; + const hitDepth = point ? point.clone().sub(cam.position).dot(forward) : 0; + return Math.max(MIN_VIEW_DISTANCE, cam.position.distanceTo(this.target), hitDepth); + } + _move(e) { const d = this._drag; if (!d || e.pointerId !== d.id) return; @@ -259,8 +275,12 @@ export class NavigationControls extends EventTarget { _pan(dx, dy) { const cam = this.camera; const height = Math.max(this.dom.clientHeight, 1); + if (cam.isPerspectiveCamera && this._drag.depth === undefined) { + const { x, y } = this._drag.down; + this._drag.depth = this._gestureDepth(this._anchor(x, y), cam.getWorldDirection(new THREE.Vector3())); + } const worldPerPixel = cam.isPerspectiveCamera - ? (2 * cam.position.distanceTo(this.target) * Math.tan(THREE.MathUtils.degToRad(cam.fov / 2))) / height + ? (2 * this._drag.depth * Math.tan(THREE.MathUtils.degToRad(cam.fov / 2))) / (height * cam.zoom) : (cam.top - cam.bottom) / cam.zoom / height; const right = new THREE.Vector3(1, 0, 0).applyQuaternion(cam.quaternion); const up = new THREE.Vector3(0, 1, 0).applyQuaternion(cam.quaternion); @@ -322,10 +342,15 @@ export class NavigationControls extends EventTarget { this._stopAnimation(); const factor = wheelZoomFactor(e.deltaY, e.deltaMode, this.dom.clientHeight); const cam = this.camera; + const distance = cam.position.distanceTo(this.target); + // Beyond this scale the model is only a few pixels wide and pan/zoom stop being useful. + const radius = this._visibleBounds()?.sphere.radius ?? 0; + const maxDistance = MAX_VIEW_RADII * Math.max(radius, 1e-3); if (cam.isOrthographicCamera) { const { left, top, width, height } = this.dom.getBoundingClientRect(); if (!width || !height) return; - const zoom = THREE.MathUtils.clamp(cam.zoom / factor, 1e-6, 1e6); + const zoom = THREE.MathUtils.clamp(cam.zoom / factor, Math.max(1e-6, Math.min(cam.zoom, distance / maxDistance)), 1e6); + if (zoom === cam.zoom) return; // Translate in the view plane by the change in the cursor offset. Depth and the pivot distance stay fixed. const shift = new THREE.Vector3( (2 * (e.clientX - left) / width - 1) * cam.right, @@ -338,11 +363,20 @@ export class NavigationControls extends EventTarget { } // One pick per animation frame: notches arriving within a frame zoom towards the same point. if (!this._wheelPick) { - this._wheelPick = { point: this.pick(e.clientX, e.clientY) }; + this._wheelPick = { point: this._anchor(e.clientX, e.clientY) }; requestAnimationFrame(() => (this._wheelPick = null)); } - const point = this._wheelPick.point ?? this.target; - const r = zoomTowards(cam.position, this.target, point, factor); + const forward = cam.getWorldDirection(new THREE.Vector3()); + const depth = this._gestureDepth(this._wheelPick.point, forward); + if (!Number.isFinite(depth)) return; + const minimum = Math.min(NEAR_MIN, Math.max(MIN_VIEW_DISTANCE, radius)); + const boundedFactor = THREE.MathUtils.clamp(depth * factor, minimum, Math.max(depth, maxDistance)) / depth; + if (boundedFactor === 1) return; + // Keep the cursor anchor while moving a stale target back to the depth of the model. + const target = cam.position.clone().addScaledVector(forward, depth); + const point = this._wheelPick.point; + const anchor = point && point.clone().sub(cam.position).dot(forward) >= minimum ? point : target; + const r = zoomTowards(cam.position, target, anchor, boundedFactor); this._set(r.position, r.target); } } diff --git a/src/IOViewer/Viewer/src/stream/clusters.js b/src/IOViewer/Viewer/src/stream/clusters.js new file mode 100644 index 0000000..8a9e517 --- /dev/null +++ b/src/IOViewer/Viewer/src/stream/clusters.js @@ -0,0 +1,53 @@ +export const SIDES = 32; +export const PROFILE = [0.68, 0.91, 1, 1.07, 1, 1, 1, 1, 1.05, 1, 1, 1, 1, 1.07, 1, 0.91, 0.68]; +export const VERTICES = SIDES * PROFILE.length; +export const STEP = 1 / 1024; +export const INSTANCE_FLOATS = 7; +export const MAX_CLUSTER_OBJECTS = 64; +export const CLUSTER_FORMAT = 'ioviewer-vessel-clusters-1'; + +export function vesselIndices(sides, rings) { + const indices = []; + for (let ring = 0; ring < rings - 1; ring++) { + for (let side = 0; side < sides; side++) { + const a = ring * sides + side, b = ring * sides + (side + 1) % sides; + indices.push(a, b, a + sides, b, b + sides, a + sides); + } + } + const top = (rings - 1) * sides; + for (let side = 1; side < sides - 1; side++) indices.push(0, side + 1, side, top, top + side, top + side + 1); + return Uint16Array.from(indices); +} + +export const FACES = vesselIndices(SIDES, PROFILE.length); +export const detailInputBytes = (count) => count * VERTICES * 12; +export const detailMeshBytes = (count) => detailInputBytes(count) + count * FACES.length * 2; + +const point = (v) => Array.isArray(v) && v.length === 3 && v.every(Number.isFinite); +const box = (v) => point(v?.min) && point(v?.max) && v.min.every((x, i) => x <= v.max[i]); +const whole = (n) => Number.isSafeInteger(n) && n >= 0; + +export function validateClusters(manifest) { + if (manifest?.format !== CLUSTER_FORMAT || !box(manifest) || !point(manifest.origin) + || !Array.isArray(manifest.palette) || manifest.palette.length !== 3 + || !manifest.palette.every((p) => point(p) && p.every((n) => n >= 0 && n <= 1)) + || !Array.isArray(manifest.roots) || !manifest.roots.length) throw new Error('Invalid cluster manifest.'); + let objects = 0, id = 0, offset = 0; + for (const root of manifest.roots) { + if (!box(root) || !whole(root.x) || !whole(root.y) || root.first !== objects + || !Array.isArray(root.children) || !root.children.length) throw new Error('Invalid cluster root.'); + const first = objects; + for (const node of root.children) { + if (!box(node) || !point(node.anchor) || node.id !== id++ || node.first !== objects || node.offset !== offset + || !Array.isArray(node.counts) || node.counts.length !== 3 || !node.counts.every(whole)) throw new Error('Invalid cluster page.'); + const count = node.counts.reduce((sum, n) => sum + n, 0); + if (count !== node.count || count < 1 || count > MAX_CLUSTER_OBJECTS) throw new Error('Invalid cluster size.'); + objects += count; + offset += detailInputBytes(count); + } + if (root.count !== objects - first) throw new Error('Invalid cluster root size.'); + } + if (objects !== manifest.elements || offset !== manifest.detailBytes || !Number.isSafeInteger(offset) + || manifest.triangles !== objects * FACES.length / 3) throw new Error('Invalid cluster totals.'); + return manifest; +} diff --git a/src/IOViewer/Viewer/src/stream/lod.js b/src/IOViewer/Viewer/src/stream/lod.js new file mode 100644 index 0000000..06e2d8d --- /dev/null +++ b/src/IOViewer/Viewer/src/stream/lod.js @@ -0,0 +1,292 @@ +import * as THREE from 'three'; +import { lang, t } from '../i18n.js'; +import { NavigationControls } from '../nav/controls.js'; +import { MESH_BUDGET, MIB } from './manifest.js'; +import { detailInputBytes, detailMeshBytes, FACES, INSTANCE_FLOATS, STEP, VERTICES, validateClusters } from './clusters.js'; +import { chooseLevel, clusterMaterial, makeTemplates } from './lodShapes.js'; + +const canvas = document.querySelector('canvas'); +const status = document.querySelector('#ioviewer-status'); +const message = document.querySelector('#ioviewer-message'); +const fit = document.querySelector('#fit'); +const retry = document.querySelector('#retry'); +const ru = lang === 'ru'; +document.documentElement.lang = lang; +fit.textContent = t('tool.fit'); +retry.textContent = ru ? 'Повторить загрузку' : 'Retry downloads'; + +function show(text) { + message.textContent = text; + message.hidden = false; +} + +async function loadBytes(url, expected) { + const response = await fetch(url, { cache: 'no-store' }); + if (!response.ok || Number(response.headers.get('content-length')) !== expected) throw new Error(`Invalid geometry response ${url} (${response.status}).`); + const buffer = await response.arrayBuffer(); + if (buffer.byteLength !== expected) throw new Error(`Truncated geometry response ${url}.`); + return buffer; +} + +try { + const response = await fetch('/manifest.json'); + if (!response.ok) throw new Error(`Manifest: HTTP ${response.status}.`); + const manifest = validateClusters(await response.json()); + const expected = manifest.elements * INSTANCE_FLOATS * 4; + if (3 * expected >= MESH_BUDGET) throw new Error('The resident LOD exceeds the memory budget.'); + const context = canvas.getContext('webgl2', { antialias: true }); + if (context) start(manifest, new Float32Array(await loadBytes('/coarse.bin', expected)), context); + else show(t('noWebGL')); +} catch (error) { + show(`${t('badData')}. ${error.message}`); +} + +function start(manifest, instances, context) { + const renderer = new THREE.WebGLRenderer({ canvas, context, antialias: true, logarithmicDepthBuffer: true }); + renderer.setClearColor(0x1f2228); + renderer.setPixelRatio(window.devicePixelRatio); + const world = new THREE.Scene(); + const camera = new THREE.PerspectiveCamera(45, 1, 0.1, 1000); + camera.up.set(0, 0, 1); + camera.position.set(1, -1, 0.8); + const sun = new THREE.DirectionalLight(0xfff6e9, 1.6); + sun.position.set(2, -3, 5); + world.add(sun, new THREE.HemisphereLight(0xffffff, 0x8897a8, 1.35)); + + const origin = new THREE.Vector3(...manifest.origin); + const local = ({ min, max }) => new THREE.Box3(new THREE.Vector3(...min).sub(origin), new THREE.Vector3(...max).sub(origin)); + const bounds = local(manifest); + const palette = manifest.palette.map((rgb) => new THREE.Color().setRGB(...rgb, THREE.SRGBColorSpace)); + const focal = { value: 1 }; + const templates = makeTemplates(); + const levels = templates.map((_, level) => clusterMaterial({ palette, focal, level })); + const fineMaterials = palette.map((color) => clusterMaterial({ color })); + const roots = manifest.roots.map((root) => ({ ...root, box: local(root), + children: root.children.map((node) => ({ ...node, box: local(node), level: 0 })) })); + const fullIndices = new Uint16Array(64 * FACES.length); + for (let i = 0; i < 64; i++) for (let k = 0; k < FACES.length; k++) fullIndices[i * FACES.length + k] = FACES[k] + i * VERTICES; + + function approximate(node, level) { + if (!node.mesh) { + const g = new THREE.InstancedBufferGeometry(); + const view = instances.subarray(node.first * INSTANCE_FLOATS, (node.first + node.count) * INSTANCE_FLOATS); + const buffer = new THREE.InstancedInterleavedBuffer(view, INSTANCE_FLOATS); + g.setAttribute('shift', new THREE.InterleavedBufferAttribute(buffer, 3, 0)); + g.setAttribute('extent', new THREE.InterleavedBufferAttribute(buffer, 3, 3)); + g.setAttribute('styleIndex', new THREE.InterleavedBufferAttribute(buffer, 1, 6)); + g.instanceCount = node.count; + g.boundingSphere = node.box.getBoundingSphere(new THREE.Sphere()); + node.mesh = new THREE.Mesh(g, levels[level]); + } + if (node.drawLevel !== level) { + const { geometry } = node.mesh; + for (const [name, attribute] of Object.entries(templates[level].attributes)) geometry.setAttribute(name, attribute); + geometry.setIndex(templates[level].index); + node.drawLevel = level; + } + node.mesh.material = levels[level]; + return node.mesh; + } + + const ndc = new THREE.Vector2(), ray = new THREE.Raycaster(); + const point = new THREE.Vector3(), closest = new THREE.Vector3(); + const frustum = new THREE.Frustum(), matrix = new THREE.Matrix4(); + let pointed = null; + const controls = new NavigationControls(camera, canvas, { pick, visibleBox: () => bounds }); + function pick(x, y) { + const rect = canvas.getBoundingClientRect(); + ndc.set(2 * (x - rect.left) / rect.width - 1, 1 - 2 * (y - rect.top) / rect.height); + camera.updateMatrixWorld(); + ray.setFromCamera(ndc, camera); + let best = Infinity; + pointed = null; + for (const root of roots) { + if (!ray.ray.intersectBox(root.box, point)) continue; + const distance = point.distanceToSquared(ray.ray.origin); + if (distance < best) { best = distance; closest.copy(point); pointed = root; } + } + return pointed ? closest.clone() : null; + } + + const resident = new Map(), pending = new Map(), failed = new Map(), transferred = []; + const pinned = 3 * instances.byteLength + fullIndices.byteLength; + let bytes = pinned, peak = bytes, frame = 0, lost = false, requests = 0, evictions = 0, downloaded = 0; + let drawn = new Set(), candidates = [], shown = [0, 0, 0, 0], renderedObjects = 0; + let resolveReady; + const ready = new Promise((resolve) => (resolveReady = resolve)); + window.__ioviewerLod = { + controls, manifest, ready, + stats: () => ({ bytes, pinned, peak, budget: MESH_BUDGET, requests, evictions, downloaded, pages: resident.size, + pending: pending.size, detailDemand: candidates.length, shown: [...shown], renderedObjects, failures: [...failed.values()], + triangles: renderer.info.render.triangles, draws: renderer.info.render.calls }), + }; + + function requestFrame() { + if (!frame && !lost) frame = requestAnimationFrame(render); + } + + function stopFade(item) { + if (!item.fade) return; + for (const material of item.fade.fine) material.dispose(); + item.fade.coarse.dispose(); + item.mesh.material = fineMaterials; + item.fade = null; + } + + function nextDownloads() { + const chosen = new Set(candidates.map(({ node }) => node)); + for (const { node } of candidates) { + if (pending.size >= 4) break; + if (resident.has(node) || pending.has(node) || failed.has(node)) continue; + const required = detailMeshBytes(node.count); + for (const [old, item] of resident) { + if (bytes + required <= MESH_BUDGET) break; + if (chosen.has(old) || drawn.has(item.mesh)) continue; + stopFade(item); + world.remove(item.mesh); + item.mesh.geometry.dispose(); + resident.delete(old); + bytes -= detailMeshBytes(old.count); + evictions++; + } + if (bytes + required > MESH_BUDGET) break; + bytes += required; + peak = Math.max(peak, bytes); + requests++; + pending.set(node, required); + loadBytes(`/pages/${node.id}`, detailInputBytes(node.count)).then((data) => { + downloaded += data.byteLength; + transferred.push({ node, data }); + requestFrame(); + }, (error) => { + pending.delete(node); + bytes -= required; + failed.set(node, error.message); + requestFrame(); + }); + } + } + + function stage({ node, data }) { + const length = node.count * VERTICES * 3; + const size = Uint16Array.BYTES_PER_ELEMENT * length; + const geometry = new THREE.BufferGeometry(); + const attribute = (array, itemSize, normalized = false) => new THREE.BufferAttribute(array, itemSize, normalized) + .onUpload(function () { this.array = null; }); + geometry.setAttribute('position', attribute(new Uint16Array(data, 0, length), 3)); + geometry.setAttribute('normal', attribute(new Int16Array(data, size, length), 3, true)); + geometry.setIndex(attribute(fullIndices.slice(0, node.count * FACES.length), 1)); + let start = 0; + for (const [index, count] of node.counts.entries()) { + if (count) geometry.addGroup(start, count * FACES.length, index); + start += count * FACES.length; + } + geometry.boundingSphere = node.box.clone().expandByScalar(STEP).translate(new THREE.Vector3(...node.anchor).negate()) + .getBoundingSphere(new THREE.Sphere()); + geometry.boundingSphere.center.divideScalar(STEP); + geometry.boundingSphere.radius /= STEP; + const mesh = new THREE.Mesh(geometry, fineMaterials); + mesh.scale.setScalar(STEP); + mesh.position.fromArray(node.anchor); + resident.set(node, { mesh, seen: false, fade: null }); + pending.delete(node); + } + + function render(now) { + frame = 0; + camera.updateMatrixWorld(); + frustum.setFromProjectionMatrix(matrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse)); + // Each queued page is at most 408 KiB of compressed coordinates and normals before building its index. + for (const page of transferred.splice(0, 2)) stage(page); + candidates = []; + shown = [0, 0, 0, 0]; + renderedObjects = 0; + const active = new Set(); + let animating = false, uploads = 0; + const pixels = (node) => focal.value / Math.max(0.01, node.box.distanceToPoint(camera.position)); + const draw = (node, level) => { + shown[level]++; + renderedObjects += node.count; + }; + for (const root of roots) { + if (!frustum.intersectsBox(root.box)) continue; + root.split = chooseLevel(pixels(root), root.split ? 1 : 0) > 0; + if (!root.split) { + active.add(approximate(root, 0)); + draw(root, 0); + continue; + } + for (const node of root.children) { + if (!frustum.intersectsBox(node.box)) continue; + const scale = pixels(node); + node.level = chooseLevel(scale, node.level); + const level = Math.min(node.level, 2); + if (node.level === 3) candidates.push({ node, scale }); + const item = node.level === 3 ? resident.get(node) : null; + if (!item || (!item.seen && uploads >= 2)) { + active.add(approximate(node, level)); + draw(node, level); + if (item) animating = true; + continue; + } + active.add(item.mesh); + draw(node, 3); + if (!item.seen) { + uploads++; + const fade = { value: 0 }; + item.fade = { value: fade, start: now, + coarse: clusterMaterial({ palette, focal, level: 2, fade, inverse: true }), + fine: palette.map((color) => clusterMaterial({ color, fade })) }; + item.mesh.material = item.fade.fine; + item.seen = true; + } + if (item.fade && now - item.fade.start < 140) { + item.fade.value.value = (now - item.fade.start) / 140; + const lower = approximate(node, 2); + lower.material = item.fade.coarse; + active.add(lower); + animating = true; + } else stopFade(item); + } + } + for (const item of resident.values()) if (item.fade && !active.has(item.mesh)) stopFade(item); + for (const mesh of drawn) if (!active.has(mesh)) world.remove(mesh); + for (const mesh of active) if (!drawn.has(mesh)) world.add(mesh); + drawn = active; + candidates.sort((a, b) => b.scale - a.scale); + candidates = candidates.slice(0, Math.floor((MESH_BUDGET - pinned) / detailMeshBytes(64))); + nextDownloads(); + renderer.render(world, camera); + resolveReady(performance.now()); + if (animating || transferred.length) requestFrame(); + status.textContent = ru ? `${Math.ceil(bytes / MIB)} МиБ · точная геометрия ${shown[3]}/${candidates.length}` + : `${Math.ceil(bytes / MIB)} MiB · full detail ${shown[3]}/${candidates.length}`; + retry.hidden = failed.size === 0; + if (failed.size) retry.title = [...failed.values()].join('\n'); + } + + function resize() { + renderer.setSize(window.innerWidth, window.innerHeight, false); + focal.value = canvas.clientHeight * renderer.getPixelRatio() / (2 * Math.tan(camera.fov * Math.PI / 360)); + controls.resize(); + } + controls.addEventListener('change', requestFrame); + window.addEventListener('resize', resize); + fit.addEventListener('click', () => controls.fitBox(bounds)); + retry.addEventListener('click', () => { failed.clear(); requestFrame(); }); + window.addEventListener('keydown', (event) => { + if (event.code === 'KeyF' && !event.ctrlKey && !event.metaKey && !event.altKey && event.target === document.body) fit.click(); + }); + canvas.addEventListener('pointerdown', () => document.activeElement?.blur(), true); + canvas.addEventListener('dblclick', ({ clientX, clientY }) => { + pick(clientX, clientY); + if (pointed) controls.fitBox(pointed.box); + }); + canvas.addEventListener('webglcontextlost', () => { + lost = true; + cancelAnimationFrame(frame); + show(t('contextLost')); + }); + resize(); + controls.fitBox(bounds, false); +} diff --git a/src/IOViewer/Viewer/src/stream/lodShapes.js b/src/IOViewer/Viewer/src/stream/lodShapes.js new file mode 100644 index 0000000..95c9038 --- /dev/null +++ b/src/IOViewer/Viewer/src/stream/lodShapes.js @@ -0,0 +1,81 @@ +import * as THREE from 'three'; +import { PROFILE, vesselIndices } from './clusters.js'; +import { applyPageFade } from './pageFade.js'; + +const levels = [ + { sides: 4, rings: [0, 16] }, + { sides: 8, rings: [0, 3, 8, 13, 16] }, + { sides: 16, rings: PROFILE.map((_, i) => i) }, +]; + +// Conservative world-space displacement of each simplified vessel surface from its source mesh, in metres. +export const LOD_ERROR = [1.55, 0.66, 0.047]; +export const ENTER_PX = 1.25; +const EXIT_PX = 0.95; + +export function chooseLevel(pixelScale, previous) { + let level = 0; + while (level < LOD_ERROR.length && pixelScale * LOD_ERROR[level] > (level < previous ? EXIT_PX : ENTER_PX)) level++; + return level; +} + +function radial(sides, side) { + return [Math.cos(side * Math.PI * 2 / sides), Math.sin(side * Math.PI * 2 / sides)]; +} + +export function makeTemplates() { + return levels.map(({ sides, rings }, level) => { + const position = [], from = []; + const old = levels[Math.max(0, level - 1)]; + for (const ring of rings) { + const hi = old.rings.findIndex((value) => value >= ring); + const a = old.rings[Math.max(0, hi - 1)], b = old.rings[hi]; + const r = a === b ? PROFILE[a] : THREE.MathUtils.lerp(PROFILE[a], PROFILE[b], (ring - a) / (b - a)); + for (let side = 0; side < sides; side++) { + const [x, y] = radial(sides, side); + position.push(x * PROFILE[ring], y * PROFILE[ring], ring / 16); + const at = side * old.sides / sides; + const [x0, y0] = radial(old.sides, Math.floor(at)), [x1, y1] = radial(old.sides, Math.ceil(at)); + const k = at % 1; + from.push(r * THREE.MathUtils.lerp(x0, x1, k), r * THREE.MathUtils.lerp(y0, y1, k), ring / 16); + } + } + const geometry = new THREE.BufferGeometry(); + geometry.setAttribute('position', new THREE.Float32BufferAttribute(position, 3)); + geometry.setAttribute('previousPosition', new THREE.Float32BufferAttribute(from, 3)); + geometry.setAttribute('color', new THREE.Float32BufferAttribute(new Float32Array(position.length).fill(1), 3)); + geometry.setIndex(new THREE.BufferAttribute(vesselIndices(sides, rings.length), 1)); + geometry.computeVertexNormals(); + return geometry; + }); +} + +export function clusterMaterial({ palette, focal, level, color, fade, inverse = false }) { + const coarse = level !== undefined; + const material = new THREE.MeshLambertMaterial(coarse ? { vertexColors: true } : { color }); + material.customProgramCacheKey = () => `clusters-${coarse}-${Boolean(fade)}-${inverse}`; + material.onBeforeCompile = (shader) => { + if (coarse) { + Object.assign(shader.uniforms, { palette: { value: palette }, focal, oldError: { value: LOD_ERROR[level - 1] ?? 0 } }); + shader.vertexShader = shader.vertexShader + .replace('#include ', `#include + attribute vec3 shift; + attribute vec3 extent; + attribute float styleIndex; + attribute vec3 previousPosition; + uniform vec3 palette[3]; + uniform float focal; + uniform float oldError;`) + .replace('#include ', `#include + vColor.rgb = palette[int(styleIndex + 0.5)];`) + .replace('#include ', `#include + objectNormal /= max(extent, vec3(0.000001));`) + .replace('#include ', `#include + float errorPx = oldError * focal / max(distance(cameraPosition, shift + vec3(0.0, 0.0, extent.z * 0.5)), 0.01); + vec3 local = mix(previousPosition, position, smoothstep(1.25, 2.25, errorPx)); + transformed = shift + extent * local;`); + } + applyPageFade(shader, fade, inverse); + }; + return material; +} diff --git a/src/IOViewer/Viewer/src/stream/main.js b/src/IOViewer/Viewer/src/stream/main.js new file mode 100644 index 0000000..8a5b7dd --- /dev/null +++ b/src/IOViewer/Viewer/src/stream/main.js @@ -0,0 +1,238 @@ +import * as THREE from 'three'; +import { lang, t } from '../i18n.js'; +import { NavigationControls } from '../nav/controls.js'; +import { MAX_TILE_MESH, MESH_BUDGET, MIB, validateManifest } from './manifest.js'; + +const canvas = document.querySelector('canvas'); +const status = document.querySelector('#ioviewer-status'); +const message = document.querySelector('#ioviewer-message'); +const fit = document.querySelector('#fit'); +const retry = document.querySelector('#retry'); +const ru = lang === 'ru'; +document.documentElement.lang = lang; +fit.textContent = t('tool.fit'); +retry.textContent = ru ? 'Повторить загрузку' : 'Retry downloads'; + +function show(text) { + message.textContent = text; + message.hidden = false; +} + +try { + const response = await fetch('/manifest.json'); + if (!response.ok) throw new Error(`Manifest: HTTP ${response.status}.`); + const manifest = validateManifest(await response.json()); + const context = canvas.getContext('webgl2', { antialias: true }); + if (context) start(manifest, context); + else show(t('noWebGL')); +} catch (error) { + show(`${t('badData')}. ${error.message}`); +} + +function start(manifest, context) { + const renderer = new THREE.WebGLRenderer({ canvas, context, antialias: true, logarithmicDepthBuffer: true }); + renderer.setClearColor(0x1f2228); + renderer.setPixelRatio(window.devicePixelRatio); + const world = new THREE.Scene(); + const camera = new THREE.PerspectiveCamera(45, 1, 0.1, 1000); + camera.up.set(0, 0, 1); + camera.position.set(1, -1, 0.8); + const sun = new THREE.DirectionalLight(0xfff6e9, 1.6); + sun.position.set(2, -3, 5); + world.add(sun, new THREE.HemisphereLight(0xffffff, 0x8897a8, 1.35)); + + const asBox = ({ min, max }) => new THREE.Box3(new THREE.Vector3(...min), new THREE.Vector3(...max)); + const bounds = asBox(manifest); + const origin = bounds.getCenter(new THREE.Vector3()); + bounds.translate(origin.clone().negate()); + const proxyGeometry = new THREE.BoxGeometry(); + const proxyMaterial = new THREE.MeshLambertMaterial({ color: 0x63788b }); + const tiles = manifest.tiles.map((tile) => { + const box = asBox(tile).translate(origin.clone().negate()); + const proxy = new THREE.Mesh(proxyGeometry, proxyMaterial); + box.getCenter(proxy.position); + box.getSize(proxy.scale); + world.add(proxy); + return { tile, box, proxy, range: 2.5 * Math.max(proxy.scale.x, proxy.scale.y, proxy.scale.z) }; + }); + + const ndc = new THREE.Vector2(), ray = new THREE.Raycaster(); + const testPoint = new THREE.Vector3(), closest = new THREE.Vector3(); + const matrix = new THREE.Matrix4(), frustum = new THREE.Frustum(); + let pointed = null; + const controls = new NavigationControls(camera, canvas, { pick, visibleBox: () => bounds }); + // shortcut: navigation pivots on area bounds, use per-tile picking when element tools are added. + function pick(x, y) { + const rect = canvas.getBoundingClientRect(); + ndc.set(2 * (x - rect.left) / rect.width - 1, 1 - 2 * (y - rect.top) / rect.height); + controls.camera.updateMatrixWorld(); + ray.setFromCamera(ndc, controls.camera); + let distance = Infinity; + pointed = null; + for (const entry of tiles) { + if (!ray.ray.intersectBox(entry.box, testPoint)) continue; + const squared = testPoint.distanceToSquared(ray.ray.origin); + if (squared >= distance) continue; + distance = squared; + closest.copy(testPoint); + pointed = entry; + } + return pointed ? closest.clone() : null; + } + + const resident = new Map(), failed = new Map(), visited = new Set(); + let wanted = [], pending = null, bytes = 0, peak = 0, requested = 0, cancelled = 0, evicted = 0; + let frame = 0, lost = false, cameraDirty = true; + let firstFrame; + const ready = new Promise((resolve) => (firstFrame = resolve)); + const stats = () => ({ + tiles: tiles.length, requested, cancelled, evicted, visited: visited.size, resident: resident.size, + readyTiles: [...resident].filter(([, entry]) => entry.next === entry.batches.length).map(([key]) => key.tile.file), + wanted: wanted.map(({ tile }) => tile.file), pending: pending?.key.tile.file ?? null, + bytes, reserved: pending ? MAX_TILE_MESH : 0, peak, budget: MESH_BUDGET, + failures: [...failed].map(([key, error]) => ({ file: key.tile.file, error })), + triangles: renderer.info.render.triangles, + }); + window.__ioviewerStream = { controls, manifest, ready, stats, origin: origin.toArray() }; + + function discard(key) { + const item = resident.get(key); + bytes -= item.bytes; + resident.delete(key); + world.remove(item.group); + for (const mesh of item.group.children) mesh.geometry.dispose(); + for (const material of item.materials) material.dispose(); + key.proxy.visible = true; + evicted++; + } + + function load(key) { + // Reserve the worst-case result before sending a job. The same reservation covers transfer and upload. + for (const old of resident.keys()) { + if (bytes + MAX_TILE_MESH <= MESH_BUDGET) break; + if (!wanted.includes(old)) discard(old); + } + if (bytes + MAX_TILE_MESH > MESH_BUDGET) return; + const worker = new Worker('/tile-worker.js'); + pending = { key, worker }; + requested++; + peak = Math.max(peak, bytes + MAX_TILE_MESH); + const complete = (result) => { + if (pending?.worker !== worker) return; + worker.terminate(); + pending = null; + if (result.error) failed.set(key, result.error); + else { + const group = new THREE.Group(); + group.position.fromArray(key.tile.rtcOffset).sub(origin); + world.add(group); + const materials = result.materials.map(({ color, opacity }) => new THREE.MeshLambertMaterial({ + color: new THREE.Color().setRGB(...color, THREE.SRGBColorSpace), opacity, transparent: opacity < 1, + })); + resident.set(key, { ...result, materials, group, next: 0 }); + bytes += result.bytes; + } + requestFrame(); + }; + worker.onmessage = ({ data }) => complete(data); + worker.onerror = ({ message: error }) => complete({ error: error || 'Tile worker failed.' }); + worker.postMessage(key.tile); + } + + function updateWanted() { + const cam = controls.camera; + cam.updateMatrixWorld(); + frustum.setFromProjectionMatrix(matrix.multiplyMatrices(cam.projectionMatrix, cam.matrixWorldInverse)); + wanted = tiles.filter((entry) => entry.box.distanceToPoint(cam.position) <= entry.range + && frustum.intersectsBox(entry.box)) + .sort((a, b) => a.box.distanceToPoint(controls.target) - b.box.distanceToPoint(controls.target) + || a.box.distanceToPoint(cam.position) - b.box.distanceToPoint(cam.position)).slice(0, 2); + // A pan can leave a requested tile behind. Keep cache entries available for a return trip. + if (pending && !wanted.includes(pending.key)) { + pending.worker.terminate(); + pending = null; + cancelled++; + } + for (const [key, item] of resident) { + item.group.visible = wanted.includes(key); + key.proxy.visible = !item.group.visible || item.next === 0; + } + } + + function requestFrame() { + if (!frame && !lost) frame = requestAnimationFrame(render); + } + + function render() { + frame = 0; + if (cameraDirty) { + cameraDirty = false; + updateWanted(); + } + const uploaded = []; + for (const key of wanted) { + const item = resident.get(key); + if (!item) continue; + // Limit per-frame GPU uploads to two spatial batches (normally under 4 MiB together). + while (item.next < item.batches.length && uploaded.length < 2) { + const batch = item.batches[item.next]; + const geometry = new THREE.BufferGeometry(); + const attr = (array, size, normalized = false) => new THREE.BufferAttribute(array, size, normalized) + .onUpload(function () { this.array = null; }); + geometry.setAttribute('position', attr(batch.position, 3)); + geometry.setAttribute('normal', attr(batch.normal, 3, true)); + geometry.setIndex(attr(batch.index, 1)); + geometry.boundingSphere = asBox(batch).getBoundingSphere(new THREE.Sphere()); + const mesh = new THREE.Mesh(geometry, item.materials[batch.material]); + // Upload this batch now, even if out of the frustum; later camera changes cannot upload a whole tile at once. + mesh.frustumCulled = false; + item.group.visible = true; + item.group.add(mesh); + uploaded.push(mesh); + item.batches[item.next++] = null; + key.proxy.visible = false; + } + if (item.next === item.batches.length) visited.add(key); + } + renderer.render(world, controls.camera); + for (const mesh of uploaded) mesh.frustumCulled = true; + firstFrame(performance.now()); + if (!pending) { + const next = wanted.find((key) => !resident.has(key) && !failed.has(key)); + if (next) load(next); + } + if (uploaded.length) requestFrame(); + const shown = wanted.filter((key) => resident.get(key)?.next > 0).length; + status.textContent = ru + ? `Участков ${tiles.length} · Детализация ${shown}/${wanted.length} · ${Math.ceil(bytes / MIB)} МиБ / ${MESH_BUDGET / MIB} МиБ` + : `${tiles.length} areas · Detail ${shown}/${wanted.length} · ${Math.ceil(bytes / MIB)} MiB / ${MESH_BUDGET / MIB} MiB`; + retry.hidden = failed.size === 0; + if (failed.size) retry.title = [...failed].map(([key, error]) => `${key.tile.file}: ${error}`).join('\n'); + } + + controls.addEventListener('change', () => { cameraDirty = true; requestFrame(); }); + function resize() { + renderer.setSize(window.innerWidth, window.innerHeight, false); + controls.resize(); + } + window.addEventListener('resize', resize); + fit.addEventListener('click', () => controls.fitBox(bounds)); + window.addEventListener('keydown', (event) => { + if (event.code === 'KeyF' && !event.ctrlKey && !event.metaKey && !event.altKey && event.target === document.body) fit.click(); + }); + retry.addEventListener('click', () => { failed.clear(); requestFrame(); }); + canvas.addEventListener('pointerdown', () => document.activeElement?.blur(), true); + canvas.addEventListener('dblclick', ({ clientX, clientY }) => { + pick(clientX, clientY); + if (pointed) controls.fitBox(pointed.box); + }); + canvas.addEventListener('webglcontextlost', () => { + lost = true; + pending?.worker.terminate(); + pending = null; + cancelAnimationFrame(frame); + show(t('contextLost')); + }); + resize(); + controls.fitBox(bounds, false); +} diff --git a/src/IOViewer/Viewer/src/stream/manifest.js b/src/IOViewer/Viewer/src/stream/manifest.js new file mode 100644 index 0000000..0d53c7a --- /dev/null +++ b/src/IOViewer/Viewer/src/stream/manifest.js @@ -0,0 +1,32 @@ +export const MIB = 1024 ** 2; +export const MAX_TILE_INPUT = 96 * MIB; +export const MAX_TILE_MESH = 128 * MIB; +export const MESH_BUDGET = 2 * MAX_TILE_MESH; +export const MAX_MANIFEST = 2 * MIB; + +const point = (value) => Array.isArray(value) && value.length === 3 && value.every(Number.isFinite); +const box = (value) => point(value?.min) && point(value?.max) && value.min.every((n, i) => n <= value.max[i]); +const count = (value) => Number.isSafeInteger(value) && value > 0; + +export function validateManifest(manifest) { + if (manifest?.format !== 'ioviewer-synthetic-tiles-1' || manifest.upAxis !== 'Z' || manifest.unit !== 'metre' + || !box(manifest) || !Array.isArray(manifest.tiles) || !manifest.tiles.length) throw new Error('Invalid tile manifest.'); + const names = new Set(); + let bytes = 0, elements = 0, triangles = 0; + for (const tile of manifest.tiles) { + if (typeof tile?.file !== 'string' || !/^tile-\d+\.html$/.test(tile.file) || names.has(tile.file) + || !Number.isSafeInteger(tile.x) || !Number.isSafeInteger(tile.y) || tile.x < 0 || tile.y < 0 + || !count(tile.bytes) || tile.bytes > MAX_TILE_INPUT || !count(tile.elements) || !count(tile.triangles) + || tile.firstElementId !== elements + 1 || !box(tile) || !point(tile.rtcOffset) + || tile.min.some((n, i) => n < manifest.min[i] || tile.max[i] > manifest.max[i])) { + throw new Error('Invalid or oversized tile in manifest.'); + } + names.add(tile.file); + bytes += tile.bytes; + elements += tile.elements; + triangles += tile.triangles; + } + if (![bytes, elements, triangles].every(count) || bytes !== manifest.totalBytes || elements !== manifest.elements + || triangles !== manifest.triangles) throw new Error('Invalid tile manifest totals.'); + return manifest; +} diff --git a/src/IOViewer/Viewer/src/stream/meshLod.js b/src/IOViewer/Viewer/src/stream/meshLod.js new file mode 100644 index 0000000..af1889d --- /dev/null +++ b/src/IOViewer/Viewer/src/stream/meshLod.js @@ -0,0 +1,521 @@ +import * as THREE from 'three'; +import { lang, t } from '../i18n.js'; +import { NavigationControls } from '../nav/controls.js'; +import { ViewCube } from '../nav/viewCube.js'; +import { el } from '../ui/dom.js'; +import { MESH_BUDGET, MIB } from './manifest.js'; +import { sizeOfPage, validateMeshPages, viewsOfPage } from './meshPages.js'; +import { mountMeshTools } from './meshTools.js'; +import { meshScene } from './meshScene.js'; +import { SectionCaps } from '../tools/sectionCaps.js'; + +const canvas = document.querySelector('canvas'); +const message = document.querySelector('#ioviewer-message'); +const retry = document.querySelector('#retry'); +const status = el('span'); +document.querySelector('#stream-controls').append(status); +document.querySelector('#fit').remove(); +const ru = lang === 'ru'; +const profile = window.IOVIEWER_MESH_PROFILE; +document.documentElement.lang = lang; +retry.textContent = ru ? 'Повторить загрузку' : 'Retry downloads'; + +function show(text) { + message.textContent = text; + message.hidden = false; +} + +async function fetchPage(node, signal) { + const start = profile && performance.now(); + const response = await fetch(`/pages/${node.id}`, { cache: 'no-store', signal }); + if (!response.ok || Number(response.headers.get('content-length')) !== node.bytes) throw new Error(`Page ${node.id} failed (${response.status}).`); + const data = await response.arrayBuffer(); + if (profile) profile.fetch(performance.now() - start, data.byteLength); + return viewsOfPage(data, node); +} + +const box = ({ min, max }) => new THREE.Box3(new THREE.Vector3(...min), new THREE.Vector3(...max)); +const BASE_ERROR = 1.5, MERGE_ERROR = 1, MOVE_SETTLE = 180; + +try { + const response = await fetch('/manifest.json'); + if (!response.ok) throw new Error(`Manifest: HTTP ${response.status}.`); + const manifest = validateMeshPages(await response.json()); + if (manifest.review?.title) document.title = manifest.review.title; + const context = canvas.getContext('webgl2', { antialias: true, stencil: true }); + if (context) await start(manifest, context); + else show(t('noWebGL')); +} catch (error) { + show(`${t('badData')}. ${error.message}`); +} + +async function start(manifest, context) { + const bounds = box(manifest); + const nodes = manifest.pages.map((page, id) => { + const bytes = sizeOfPage(page); + return { ...page, id, box: box(page), bytes, memory: bytes + page.indices * 2 + (page.pick ? page.vertices * 4 : 0) }; + }); + const roots = manifest.roots.map((id) => nodes[id]); + const pinned = new Set(roots); + const resident = new Map(), pending = new Set(), failed = new Map(), transferred = []; + const appearances = new Map(), textures = new Map(); + let clip = { planes: [], intersection: false }; + const scene = meshScene(manifest.elements ?? [], nodes, bounds, context, (planes, intersection) => { + clip = { planes, intersection }; + updateMaterials(); + }, requestFrame); + const warming = new THREE.MeshBasicMaterial({ colorWrite: false, depthWrite: false }); + let bytes = roots.reduce((n, node) => n + node.memory, 0), peak = bytes; + let wireBudget = false; + const pageMemory = (node) => node.memory + (wireBudget ? node.indices * 8 : 0); + let requested = 0, downloaded = 0, evictions = 0, fallback = 0, exact = 0, visible = 0; + let coarsePixels = 0, nearbyCoarsePixels = 0; + let frame = 0, lost = false; + let lastMove = -Infinity, settleTimer = 0, lastFrame = 0, fastFrames = 0, movingError = BASE_ERROR, threshold = BASE_ERROR; + let rasterScale = 1, lastScaleChange = -Infinity; + let drawn = new Set(); + if (manifest.overview) { + const response = await fetch('/overview.bin', { cache: 'no-store' }); + if (!response.ok || Number(response.headers.get('content-length')) !== manifest.overview) throw new Error('Invalid overview size.'); + const overview = await response.arrayBuffer(); + if (overview.byteLength !== manifest.overview) throw new Error('Truncated overview.'); + let at = 0; + for (const node of roots) { + stage(node, viewsOfPage(overview.slice(at, at + node.bytes), node), true); + at += node.bytes; + } + } else { + for (let at = 0; at < roots.length; at += 4) { + await Promise.all(roots.slice(at, at + 4).map(async (node) => stage(node, await fetchPage(node), true))); + } + } + + const renderer = new THREE.WebGLRenderer({ canvas, context, antialias: true, stencil: true, logarithmicDepthBuffer: true }); + renderer.localClippingEnabled = true; + renderer.autoClearStencil = false; + renderer.setClearColor(0x1f2228); + renderer.setPixelRatio(window.devicePixelRatio); + const world = new THREE.Scene(); + const camera = new THREE.PerspectiveCamera(45, 1, 0.1, 1000); + camera.up.set(0, 0, 1); + camera.position.set(1, -1, 0.8); + const sun = new THREE.DirectionalLight(0xfff6e9, 1.7); + sun.position.set(2, -3, 5); + world.add(sun, new THREE.HemisphereLight(0xffffff, 0x8897a8, 1.35)); + + const ndc = new THREE.Vector2(), ray = new THREE.Raycaster(); + const point = new THREE.Vector3(), closest = new THREE.Vector3(), forward = new THREE.Vector3(); + const frustum = new THREE.Frustum(), guard = new THREE.Frustum(), matrix = new THREE.Matrix4(); + const guardScale = new THREE.Matrix4().makeScale(0.8, 0.8, 1); + let pointed = null; + const controls = new NavigationControls(camera, canvas, { pick, visibleBox: scene.visibleBox }); + function pick(x, y) { + const rect = canvas.getBoundingClientRect(); + ndc.set(2 * (x - rect.left) / rect.width - 1, 1 - 2 * (y - rect.top) / rect.height); + const camera = controls.camera; + camera.updateMatrixWorld(); + ray.setFromCamera(ndc, camera); + camera.getWorldDirection(forward); + const eyeDepth = forward.dot(camera.position); + let best = Infinity; + pointed = null; + for (const node of drawn) { + if (!ray.ray.intersectBox(node.box, point)) continue; + const depth = forward.dot(point) - eyeDepth; + if (depth < camera.near || depth > camera.far) continue; + const distance = point.distanceToSquared(ray.ray.origin); + if (distance < best) { best = distance; closest.copy(point); pointed = node; } + } + return pointed ? closest.clone() : null; + } + + function configureMaterial(material) { + material.clippingPlanes = clip.planes; + material.clipIntersection = clip.intersection; + material.opacity = scene.opacity; + const transparent = material.userData.blended || scene.opacity < 1; + if (material.transparent !== transparent) { + material.transparent = transparent; + material.needsUpdate = true; + } + material.depthWrite = !material.transparent; + } + function updateMaterials() { + for (const material of appearances.values()) configureMaterial(material); + requestFrame(); + } + function materialFor(tagged, blended, textureId) { + const key = `${scene.mode}-${tagged}-${blended}-${textureId}`; + let material = appearances.get(key); + if (material) return material; + const white = scene.mode === 'white'; + let map = null; + if (scene.mode === 'textures' && textureId !== undefined) { + if (!textures.has(textureId)) { + const { mime, data, sx, sy } = manifest.review.textures[textureId]; + const loaded = new THREE.TextureLoader().load(`data:${mime};base64,${data}`, requestFrame, + undefined, () => show(t('badData'))); + loaded.colorSpace = THREE.SRGBColorSpace; + loaded.wrapS = loaded.wrapT = THREE.RepeatWrapping; + loaded.repeat.set(1 / sx, 1 / sy); + textures.set(textureId, loaded); + } + map = textures.get(textureId); + } + material = new THREE.MeshLambertMaterial({ vertexColors: tagged || !white, color: white && !tagged ? 0xfafafa : 0xffffff, + wireframe: scene.mode === 'wireframe', map }); + material.userData.blended = blended; + if (tagged) scene.patchMaterial(material, { white }); + configureMaterial(material); + appearances.set(key, material); + return material; + } + function style(node, item) { + if (item.mode === scene.mode) return; + let start = 0; + item.mesh.material = item.groups.map((group) => { + const blended = start >= node.opaque; + start += group.count; + return materialFor(!!node.pick, blended, group.texture); + }); + item.mode = scene.mode; + } + scene.root.addEventListener('change', (event) => { + if (event.detail.kind === 'visibility') { + controls.invalidateBounds(); + controls.resize(); + } + if (!wireBudget && scene.mode === 'wireframe') { + wireBudget = true; + const reserved = new Set([...resident.keys(), ...pending]); + for (const node of reserved) bytes += node.indices * 8; + // Three retains generated edge indices until the source geometry is disposed. + const candidates = [...resident].filter(([node, item]) => item.ready && !pinned.has(node)).sort((a, b) => a[1].used - b[1].used); + for (const [node] of candidates) { + if (bytes <= MESH_BUDGET) break; + discard(node); + } + peak = Math.max(peak, bytes); + } + updateMaterials(); + }); + const tools = mountMeshTools({ manifest, roots, nodes, bounds, world, controls, canvas, scene, + fetchPage, ru, render: requestFrame, canFill: context.getContextAttributes()?.stencil === true && roots.some((node) => node.hasClosed), + setBackground: (color) => renderer.setClearColor(color) }); + let caps, capWorld, capMaterials; + function renderStencils(renderer, camera, plane) { + if (!capWorld) { + capWorld = new THREE.Scene(); + capMaterials = [false, true].map((tagged) => [ + [THREE.BackSide, THREE.IncrementWrapStencilOp], [THREE.FrontSide, THREE.DecrementWrapStencilOp], + ].map(([side, stencilZPass]) => { + const material = new THREE.MeshBasicMaterial({ side, stencilZPass, stencilWrite: true, clippingPlanes: [plane], + colorWrite: false, depthWrite: false, depthTest: false }); + if (tagged) scene.patchMaterial(material, { stencil: true }); + return material; + })); + } + for (let pass = 0; pass < 2; pass++) { + capWorld.clear(); + for (const node of drawn) { + if (node.children.length || !node.hasClosed) continue; + const item = resident.get(node); + if (!item.stencil) { + const invisible = new THREE.MeshBasicMaterial({ visible: false }); + item.stencil = new THREE.Mesh(item.mesh.geometry); + item.stencil.position.copy(item.mesh.position); + item.stencilMaterials = capMaterials[Number(!!node.pick)].map((material) => + item.groups.map(({ closed }) => closed ? material : invisible)); + } + item.stencil.material = item.stencilMaterials[pass]; + capWorld.add(item.stencil); + } + renderer.render(capWorld, camera); + } + capWorld.clear(); + } + let viewCube, cubeDirty = true; + let resolveReady; + const ready = new Promise((resolve) => (resolveReady = resolve)); + window.__ioviewerMeshLod = { controls, manifest, ready, ...tools, + stats: () => ({ bytes, peak, budget: MESH_BUDGET, requested, evictions, downloaded, visible, exact, fallback, + coarsePixels, nearbyCoarsePixels, threshold, rasterScale, pending: pending.size, + resident: resident.size, triangles: renderer.info.render.triangles, draws: renderer.info.render.calls, failures: [...failed.values()] }) }; + + function stage(node, view, ready = false) { + if (view.index.some((i) => i >= node.vertices) || view.position.some((value) => !Number.isFinite(value))) { + throw new Error(`Invalid geometry in page ${node.id}.`); + } + const geometry = new THREE.BufferGeometry(); + const attribute = (array, size, normalized = false) => new THREE.BufferAttribute(array, size, normalized) + .onUpload(function () { this.array = null; }); + geometry.setAttribute('position', attribute(view.position, 3)); + geometry.setAttribute('normal', attribute(view.normal, 3, true)); + geometry.setAttribute('color', attribute(view.color, 4, true)); + if (view.uv) geometry.setAttribute('uv', attribute(view.uv, 2)); + if (view.tags) { + const elements = new Float32Array(node.vertices); + for (let i = 0; i < view.index.length; i++) { + const element = view.tags[Math.floor(i / 3)]; + if (element >= scene.elementCount) throw new Error(`Invalid element in page ${node.id}.`); + elements[view.index[i]] = element; + } + geometry.setAttribute('elementIndex', attribute(elements, 1)); + } + geometry.setIndex(new THREE.BufferAttribute(new Uint16Array(view.index), 1)); + const groups = node.groups ?? [node.opaque, node.indices - node.opaque].filter(Boolean).map((count) => ({ count })); + let at = 0; + groups.forEach(({ count }, index) => { geometry.addGroup(at, count, index); at += count; }); + const item = { mesh: new THREE.Mesh(geometry, warming), groups, used: performance.now(), ready }; + geometry.boundingSphere = node.box.getBoundingSphere(new THREE.Sphere()); + if (node.shift) { + item.mesh.position.fromArray(node.shift); + geometry.boundingSphere.center.sub(item.mesh.position); + } + resident.set(node, item); + return item; + } + + function requestFrame() { + if (!frame && !lost) frame = requestAnimationFrame(render); + } + + function fail(node, error) { + pending.delete(node); + bytes -= pageMemory(node); + failed.set(node, error.message); + } + + function discard(node) { + const item = resident.get(node); + drawn.delete(node); + world.remove(item.mesh); + item.mesh.geometry.dispose(); + resident.delete(node); + bytes -= pageMemory(node); + evictions++; + } + + function load(needs, protectedNodes, concurrency) { + if (profile?.holdPages) return; + for (const [node, request] of [...needs].sort((a, b) => b[1].priority - a[1].priority)) { + if (pending.size >= concurrency) break; + if (resident.has(node) || pending.has(node) || failed.has(node)) continue; + const cost = pageMemory(node); + if (!request.blocking && bytes + cost > MESH_BUDGET) continue; + while (bytes + cost > MESH_BUDGET) { + let old = null, age = Infinity; + for (const [candidate, value] of resident) { + if (!value.ready || value.used >= age || pinned.has(candidate) || protectedNodes.has(candidate) || drawn.has(candidate)) continue; + old = candidate; + age = value.used; + } + if (!old) break; + discard(old); + } + if (bytes + cost > MESH_BUDGET) continue; + bytes += cost; + peak = Math.max(peak, bytes); + pending.add(node); + requested++; + fetchPage(node).then((view) => { + downloaded += node.bytes; + transferred.push({ node, view }); + requestFrame(); + }, (error) => { fail(node, error); requestFrame(); }); + } + } + + function render(now) { + frame = 0; + const interval = now - lastFrame; + lastFrame = now; + const moving = now - lastMove < MOVE_SETTLE; + if (moving && interval < MOVE_SETTLE) { + if (interval > 38) { + movingError = Math.min(4.5, movingError * 1.18); + fastFrames = 0; + } else if (interval < 23 && ++fastFrames >= 12) { + movingError = Math.max(BASE_ERROR, movingError / 1.08); + fastFrames = 0; + } + } else if (!moving) { + movingError = BASE_ERROR; + fastFrames = 0; + } + threshold = moving ? movingError : BASE_ERROR; + let scale = rasterScale; + if ((!moving && !pending.size) || profile?.nativePixels) { + scale = 1; + } else if (interval > 38 && interval < MOVE_SETTLE && now - lastScaleChange >= 220) { + scale = Math.max(0.6, scale - 0.15); + } + if (scale !== rasterScale) { + rasterScale = scale; + lastScaleChange = now; + renderer.setPixelRatio(window.devicePixelRatio * rasterScale); + } + const camera = controls.camera; + const height = canvas.clientHeight * window.devicePixelRatio; + const focal = camera.zoom * (camera.isOrthographicCamera ? height / (camera.top - camera.bottom) + : height / (2 * Math.tan(camera.fov * Math.PI / 360))); + camera.updateMatrixWorld(); + tools.sectionGizmo.update(camera); + if (tools.grids.visible || tools.measure.preview || tools.measure.distance !== null) { + const rect = canvas.getBoundingClientRect(); + tools.grids.update(camera, rect); + tools.measure.update(camera, rect); + } + frustum.setFromProjectionMatrix(matrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse)); + guard.setFromProjectionMatrix(matrix.premultiply(guardScale)); + const warm = []; + const uploads = moving ? (interval < 23 ? 3 : interval < 38 ? 2 : 1) : (interval < 38 ? 6 : 3); + for (const { node, view } of transferred.splice(0, uploads)) { + try { + const prepareAt = profile && performance.now(); + const item = stage(node, view); + if (profile) profile.prepare(performance.now() - prepareAt); + item.mesh.material = warming; + item.mesh.frustumCulled = false; + // Three uploads the full vertex and index buffers on the first draw. + item.mesh.geometry.setDrawRange(0, 3); + world.add(item.mesh); + warm.push(node); + } catch (error) { fail(node, error); } + } + const cut = new Set(), needs = new Map(), protectedNodes = new Set(); + const fill = tools.canFill && tools.sections.fill && clip.planes.length > 0; + let capPending = false; + const projectedError = (node) => node.error * focal / (camera.isOrthographicCamera ? 1 : Math.max(0.01, node.box.distanceToPoint(camera.position))); + const inView = (node, volume) => !scene.fullyHidden(node) && volume.intersectsBox(node.box) + && (!clip.planes.length || (fill && node.hasClosed) || !tools.sections.isCut(node.box, clip)); + const childrenIn = (node, volume) => node.children.map((id) => nodes[id]).filter((child) => inView(child, volume)); + const viewDistance = camera.position.distanceTo(controls.target); + const focusRange = Math.max(1, viewDistance / camera.zoom) * 0.3; + const nearby = viewDistance * 2; + function queue(children, projected, blocking = false) { + const ready = children.filter((child) => resident.get(child)?.ready).length; + for (const child of children) { + if (blocking) protectedNodes.add(child); + if (resident.has(child)) continue; + const focus = 1 / (1 + child.box.distanceToPoint(controls.target) / focusRange); + const near = child.box.distanceToPoint(camera.position) < nearby; + const priority = Math.min(projected, 20) + (blocking ? 48 + (near ? 64 : 0) + focus * 40 + ready * 4 : focus * 16); + if (priority > (needs.get(child)?.priority ?? 0)) needs.set(child, { priority, blocking }); + } + } + function prefetch(node) { + if (!node.children.length) return; + const projected = projectedError(node); + if (projected > BASE_ERROR / 2) queue(childrenIn(node, moving ? guard : frustum), projected); + } + fallback = exact = coarsePixels = nearbyCoarsePixels = 0; + function draw(node) { + cut.add(node); + style(node, resident.get(node)); + if (!node.children.length) exact++; + if (profile?.coarseMetrics && node.children.length) { + const error = projectedError(node); + coarsePixels = Math.max(coarsePixels, error); + if (node.box.distanceToPoint(camera.position) < nearby) nearbyCoarsePixels = Math.max(nearbyCoarsePixels, error); + } + } + function visit(node, knownVisible = false) { + if (!knownVisible && !inView(node, frustum)) { + if (moving && inView(node, guard)) prefetch(node); + return; + } + protectedNodes.add(node); + const projected = projectedError(node); + const forced = scene.affected(node) || (scene.mode === 'textures' && node.hasTexture) || (fill && node.hasClosed); + if (!node.children.length || (!forced && projected <= (node.split ? MERGE_ERROR : threshold))) { + if (moving) prefetch(node); + node.split = false; + draw(node); + return; + } + const children = childrenIn(node, frustum); + if (!children.length) return; + if (moving) queue(childrenIn(node, guard), projected); + queue(children, projected, true); + if (children.some((child) => !resident.get(child)?.ready)) { + children.forEach(prefetch); + fallback++; + if (fill && node.hasClosed) capPending = true; + if (scene.visibilityAffects(node)) { + for (const child of children) if (resident.get(child)?.ready) visit(child, true); + } else draw(node); + return; + } + // Commit only a covered cut. Keeping one mesh per branch avoids depth fighting and stipple. + node.split = true; + for (const child of children) visit(child, true); + } + for (const root of roots) visit(root); + for (const node of drawn) if (!cut.has(node)) world.remove(resident.get(node).mesh); + for (const node of cut) if (!drawn.has(node)) world.add(resident.get(node).mesh); + drawn = cut; + for (const node of protectedNodes) if (resident.has(node)) resident.get(node).used = now; + visible = cut.size; + load(needs, protectedNodes, moving ? 6 : 12); + const drawWorld = () => { + if (fill && !capPending) { + caps ??= new SectionCaps(scene, tools.sections, null, renderStencils); + caps.render(renderer, world, camera); + } else renderer.render(world, camera); + }; + if (profile) profile.draw(context, drawWorld); + else drawWorld(); + if (cubeDirty) { + cubeDirty = false; + viewCube?.update(); + } + // Upload at a bounded rate before a sibling group can replace its visible parent. + for (const node of warm) { + const item = resident.get(node); + world.remove(item.mesh); + item.mode = undefined; + item.mesh.frustumCulled = true; + item.mesh.geometry.setDrawRange(0, Infinity); + item.ready = true; + pending.delete(node); + } + resolveReady(performance.now()); + if (transferred.length || warm.length) requestFrame(); + status.textContent = ru ? `${Math.ceil(bytes / MIB)} МиБ · Кластеров ${visible} · Уточняется ${fallback}` + : `${Math.ceil(bytes / MIB)} MiB · ${visible} clusters · ${fallback} refining`; + retry.hidden = failed.size === 0; + if (failed.size) retry.title = [...failed.values()].join('\n'); + } + + function resize() { + renderer.setSize(window.innerWidth, window.innerHeight, false); + controls.resize(); + } + controls.addEventListener('change', () => { + cubeDirty = true; + lastMove = performance.now(); + clearTimeout(settleTimer); + settleTimer = setTimeout(requestFrame, MOVE_SETTLE); + requestFrame(); + }); + window.addEventListener('resize', resize); + retry.addEventListener('click', () => { failed.clear(); requestFrame(); }); + window.addEventListener('pointerdown', (event) => { + if (event.target === canvas || viewCube?.element.contains(event.target)) document.activeElement?.blur(); + }, true); + canvas.addEventListener('dblclick', ({ clientX, clientY }) => { + pick(clientX, clientY); + if (pointed) controls.fitBox(pointed.box); + }); + canvas.addEventListener('webglcontextlost', () => { + lost = true; + cancelAnimationFrame(frame); + clearTimeout(settleTimer); + show(t('contextLost')); + }); + resize(); + controls.fitBox(manifest.focus ? box(manifest.focus) : bounds, false); + viewCube = new ViewCube(document.querySelector('#ioviewer-ui'), camera, controls); + window.__ioviewerMeshLod.viewCube = viewCube; +} diff --git a/src/IOViewer/Viewer/src/stream/meshPages.js b/src/IOViewer/Viewer/src/stream/meshPages.js new file mode 100644 index 0000000..568826f --- /dev/null +++ b/src/IOViewer/Viewer/src/stream/meshPages.js @@ -0,0 +1,106 @@ +import { MIB } from './manifest.js'; +import { validateReviewMeta } from '../data.js'; + +export const MESH_FORMAT = 'ioviewer-mesh-clusters-1'; +export const PAGE_TRIANGLES = 8192; +export const ROOT_BYTES = 48 * MIB; +export const MESH_MANIFEST_BYTES = 64 * MIB; +export const align4 = (bytes) => (bytes + 3) & ~3; +export const pageBytes = (vertices, indices, pick = false, uv = false) => { + const mesh = vertices * 22 + indices * 2; + const end = pick ? align4(mesh) + (indices / 3) * 4 : mesh; + return uv ? align4(end) + vertices * 8 : end; +}; +export const sizeOfPage = ({ vertices, indices, pick, uv }) => pageBytes(vertices, indices, pick, uv); +export const MAX_PAGE_BYTES = pageBytes(PAGE_TRIANGLES * 3, PAGE_TRIANGLES * 3); +export const isPoint = (p) => Array.isArray(p) && p.length === 3 && p.every(Number.isFinite); +export const isBounds = (value) => isPoint(value?.min) && isPoint(value?.max) && value.min.every((v, i) => v <= value.max[i]); +const contains = (outer, inner) => inner.min.every((n, i) => n >= outer.min[i] && inner.max[i] <= outer.max[i]); +const count = (n) => Number.isSafeInteger(n) && n > 0; +export const MAX_ELEMENT_BYTES = 16 * MIB; +export const ELEMENT_FIELDS = ['name', 'category', 'type', 'level', 'sourceId']; + +export function validateMeshPages(manifest) { + if (manifest?.format !== MESH_FORMAT || !isBounds(manifest) || !isPoint(manifest.origin) + || (manifest.focus !== undefined && (!isBounds(manifest.focus) || !contains(manifest, manifest.focus))) + || (manifest.placements !== undefined && (!Array.isArray(manifest.placements) || !manifest.placements.length + || !manifest.placements.every((placement) => isBounds(placement) && contains(manifest, placement)))) + || !Array.isArray(manifest.pages) || !manifest.pages.length || !Array.isArray(manifest.roots) || !manifest.roots.length + || (manifest.elements !== undefined && !Array.isArray(manifest.elements))) { + throw new Error('Invalid mesh cluster manifest.'); + } + const parent = new Uint8Array(manifest.pages.length); + if (manifest.review !== undefined) { + if (!manifest.review || typeof manifest.review !== 'object' || Array.isArray(manifest.review)) throw new Error('Invalid mesh review.'); + validateReviewMeta({ ...manifest.review, elements: manifest.elements ?? [] }); + if (manifest.review.textures?.some(({ mime, data, sx, sy }) => !/^image\/(?:png|jpeg|webp|gif|bmp|avif)$/.test(mime) + || typeof data !== 'string' || !Number.isFinite(sx) || !Number.isFinite(sy))) throw new Error('Invalid review texture.'); + } + let length = 0, triangles = 0; + for (const [id, page] of manifest.pages.entries()) { + if (!page || !isBounds(page) || !count(page.vertices) || !count(page.indices) || page.indices > PAGE_TRIANGLES * 3 + || page.vertices > page.indices || page.indices % 3 || !Number.isSafeInteger(page.opaque) + || page.opaque < 0 || page.opaque > page.indices || page.opaque % 3 || !Number.isFinite(page.error) || page.error < 0 + || page.offset !== length || !Array.isArray(page.children) || page.children.length > 4 + || (page.shift !== undefined && !isPoint(page.shift)) || (page.pick !== undefined && typeof page.pick !== 'boolean') + || (page.pick && (!manifest.elements?.length || page.children.length)) + || (page.uv !== undefined && typeof page.uv !== 'boolean') + || (page.members !== undefined && (!page.pick || !Array.isArray(page.members) || !page.members.length + || page.members.some((member, i) => !Number.isInteger(member) || member < 0 || member >= manifest.elements.length + || (i > 0 && member <= page.members[i - 1])))) + || (page.children.length === 0 && page.error !== 0)) throw new Error(`Invalid mesh cluster page ${id}.`); + if (page.groups !== undefined) { + let at = 0; + if (page.children.length || !Array.isArray(page.groups) || !page.groups.length || page.groups.some((group) => { + if (!group || !count(group.count) || group.count % 3 || (group.closed !== undefined && typeof group.closed !== 'boolean') + || (group.texture !== undefined && (!page.uv || !Number.isInteger(group.texture) || group.texture < 0 + || group.texture >= (manifest.review?.textures?.length ?? 0)))) return true; + const start = at; + at += group.count; + return start < page.opaque && at > page.opaque; + }) || at !== page.indices) throw new Error(`Invalid mesh groups at page ${id}.`); + } + length += sizeOfPage(page); + if (!page.children.length) triangles += page.indices / 3; + for (const child of page.children) { + if (!Number.isSafeInteger(child) || child < 0 || child >= id || parent[child] || manifest.pages[child].error > page.error) { + throw new Error(`Invalid cluster hierarchy at page ${id}.`); + } + if (!contains(page, manifest.pages[child])) throw new Error(`A child exceeds the bounds of page ${id}.`); + parent[child] = 1; + } + } + let pinned = 0; + for (const root of manifest.roots) { + if (!Number.isSafeInteger(root) || root < 0 || root >= parent.length || parent[root]) throw new Error('Invalid mesh cluster root.'); + if (!contains(manifest, manifest.pages[root])) throw new Error('A root exceeds the scene bounds.'); + parent[root] = 1; + pinned += sizeOfPage(manifest.pages[root]); + } + let propertyBytes = 0; + for (const element of manifest.elements ?? []) { + if (!isBounds(element) || typeof element.id !== 'string' || !/^-?\d+$/.test(element.id) || !Number.isSafeInteger(element.size) + || element.size < 0 || element.size > MAX_ELEMENT_BYTES || element.offset !== propertyBytes + || ELEMENT_FIELDS.some((field) => element[field] !== undefined && typeof element[field] !== 'string')) { + throw new Error('Invalid mesh element record.'); + } + propertyBytes += element.size; + } + if (!parent.every(Boolean) || !count(length) || length !== manifest.bytes || triangles !== manifest.triangles || pinned > ROOT_BYTES + || (manifest.overview !== undefined && manifest.overview !== pinned) || propertyBytes !== (manifest.propertyBytes ?? 0)) { + throw new Error('Invalid cluster coverage or byte totals.'); + } + return manifest; +} + +export function viewsOfPage(buffer, { vertices, indices, pick, uv }) { + if (buffer.byteLength !== pageBytes(vertices, indices, pick, uv)) throw new Error('Truncated mesh page.'); + return { + position: new Float32Array(buffer, 0, vertices * 3), + normal: new Int16Array(buffer, vertices * 12, vertices * 3), + color: new Uint8Array(buffer, vertices * 18, vertices * 4), + index: new Uint16Array(buffer, vertices * 22, indices), + tags: pick ? new Uint32Array(buffer, align4(vertices * 22 + indices * 2), indices / 3) : null, + uv: uv ? new Float32Array(buffer, align4(pageBytes(vertices, indices, pick)), vertices * 2) : null, + }; +} diff --git a/src/IOViewer/Viewer/src/stream/meshScene.js b/src/IOViewer/Viewer/src/stream/meshScene.js new file mode 100644 index 0000000..3a43d92 --- /dev/null +++ b/src/IOViewer/Viewer/src/stream/meshScene.js @@ -0,0 +1,153 @@ +import * as THREE from 'three'; + +const HIGHLIGHT = new THREE.Color('#f59e0b'); + +export function meshScene(elements, nodes, bounds, context, setClipping, render) { + const root = new EventTarget(); + const parents = new Int32Array(nodes.length).fill(-1); + const leaves = Array.from({ length: elements.length }, () => []); + const limit = context.getParameter(context.MAX_TEXTURE_SIZE); + const width = Math.min(Math.max(elements.length, 1), limit); + const height = Math.max(1, Math.ceil(elements.length / width)); + if (height > limit) throw new Error('Model exceeds the element state texture limit.'); + const rgba = new Uint8Array(width * height * 4); + const texture = new THREE.DataTexture(rgba, width, height); + const hidden = new Set(), layers = new Map(), tinted = new Map(); + let highlighted = new Set(), changedElements = 0, hiddenElements = 0, visibleBounds; + let mode = 'materials', opacity = 1; + const indexed = nodes.every((node) => !node.pick || node.members); + const legacy = [0]; + for (const node of nodes) { + node.affected = node.hidden = 0; + node.total = node.members?.length ?? 0; + node.hasTexture = !!node.uv; + node.hasClosed = node.groups?.some((group) => group.closed) ?? false; + for (const child of node.children) { + parents[child] = node.id; + node.total += nodes[child].total; + node.hasTexture ||= nodes[child].hasTexture; + node.hasClosed ||= nodes[child].hasClosed; + } + for (const index of node.members ?? []) leaves[index].push(node.id); + } + texture.needsUpdate = true; + + const event = (kind) => { + if (kind === 'visibility') visibleBounds = undefined; + root.dispatchEvent(new CustomEvent('change', { detail: { kind } })); + render(); + }; + const state = (i) => rgba[i * 4 + 3]; + const isVisible = (i) => !!elements[i] && state(i) !== 255 && !elements[i].noGeometry; + function update(indices, kind) { + for (const i of indices) { + if (!elements[i]) continue; + const previous = state(i); + const color = highlighted.has(i) ? HIGHLIGHT : tinted.get(i); + const next = hidden.has(i) || [...layers.values()].some((items) => items.has(i)) ? 255 : color ? 128 : 0; + if (color) rgba.set([color.r * 255, color.g * 255, color.b * 255], i * 4); + rgba[i * 4 + 3] = next; + const appearanceDelta = Number(next !== 0) - Number(previous !== 0); + const hiddenDelta = Number(next === 255) - Number(previous === 255); + changedElements += appearanceDelta; + hiddenElements += hiddenDelta; + if (!appearanceDelta && !hiddenDelta) continue; + for (const leaf of leaves[i]) for (let node = leaf; node >= 0; node = parents[node]) { + nodes[node].affected += appearanceDelta; + nodes[node].hidden += hiddenDelta; + } + } + texture.needsUpdate = true; + event(kind); + } + const replace = (set, indices, kind) => { + const previous = [...set]; + set.clear(); + for (const i of indices) set.add(i); + update(new Set([...previous, ...set]), kind); + }; + const selectionComplement = (selection) => { + const keep = new Set(selection); + return elements.flatMap((_, i) => keep.has(i) ? [] : [i]); + }; + + const scene = { + root, elementCount: elements.length, setClipping, isVisible, + elementBox(i, box = new THREE.Box3()) { + const element = elements[i]; + if (!element || element.noGeometry) return box.makeEmpty(); + return box.set(box.min.fromArray(element.min), box.max.fromArray(element.max)); + }, + visibleBox() { + if (!hiddenElements) return bounds.clone(); + if (!visibleBounds) { + visibleBounds = new THREE.Box3(); + const box = new THREE.Box3(); + for (let i = 0; i < elements.length; i++) if (isVisible(i)) visibleBounds.union(scene.elementBox(i, box)); + } + return visibleBounds.clone(); + }, + instancesOf(i) { return indexed ? leaves[i] : elements[i]?.noGeometry ? [] : legacy; }, + showAll() { replace(hidden, [], 'visibility'); }, + isolate(indices) { replace(hidden, selectionComplement(indices), 'visibility'); }, + setHiddenElements(indices) { replace(hidden, indices, 'visibility'); }, + setVisible(indices, visible) { + for (const i of indices) visible ? hidden.delete(i) : hidden.add(i); + update(indices, 'visibility'); + }, + setLayerHidden(layer, indices, hide) { + if (!layers.has(layer)) layers.set(layer, new Set()); + const items = layers.get(layer); + for (const i of indices) hide ? items.add(i) : items.delete(i); + update(indices, 'visibility'); + }, + replaceLayerHidden(layer, indices) { + const before = layers.get(layer) ?? []; + layers.set(layer, new Set(indices)); + update(new Set([...before, ...indices]), 'visibility'); + }, + clearLayer(layer) { scene.replaceLayerHidden(layer, []); }, + setHighlighted(indices) { + const before = highlighted; + highlighted = new Set(indices); + update(new Set([...before, ...highlighted]), 'appearance'); + }, + setTint(indices, color) { + const tint = color == null ? null : new THREE.Color(color); + for (const i of indices) tint ? tinted.set(i, tint) : tinted.delete(i); + update(indices, 'appearance'); + }, + get mode() { return mode; }, + get opacity() { return opacity; }, + setDisplayMode(value) { mode = value; event('appearance'); }, + setOpacity(value) { opacity = value; event('appearance'); }, + affected(node) { return indexed ? node.affected > 0 : changedElements > 0; }, + visibilityAffects(node) { return indexed ? node.hidden > 0 : hiddenElements > 0; }, + fullyHidden(node) { return node.total > 0 && node.total === node.hidden; }, + patchMaterial(material, { stencil = false, white = false } = {}) { + const key = material.customProgramCacheKey(); + material.customProgramCacheKey = () => `${key}-element-${stencil}-${white}`; + material.onBeforeCompile = (shader) => { + shader.uniforms.elementState = { value: texture }; + shader.uniforms.elementWidth = { value: width }; + shader.vertexShader = shader.vertexShader.replace('#include ', `#include + attribute float elementIndex; + uniform highp sampler2D elementState; + uniform int elementWidth;`); + shader.vertexShader = shader.vertexShader.replace('#include ', ` + int iovElement = int(elementIndex); + vec4 iovState = texelFetch(elementState, ivec2(iovElement % elementWidth, iovElement / elementWidth), 0); + #include + if (iovState.a > 0.9) gl_Position = vec4(0.0, 0.0, 2.0, 1.0); + ${stencil ? '' : `${white ? 'vColor.rgb = vec3(0.95);' : ''} if (iovState.a > 0.25) vColor.rgb = iovState.rgb;`}`); + }; + }, + }; + // Geometry-only packages have no element visibility actions. + if (!elements.length) { + delete scene.setVisible; + delete scene.showAll; + delete scene.isolate; + } + return scene; +} diff --git a/src/IOViewer/Viewer/src/stream/meshSnap.js b/src/IOViewer/Viewer/src/stream/meshSnap.js new file mode 100644 index 0000000..16a07b8 --- /dev/null +++ b/src/IOViewer/Viewer/src/stream/meshSnap.js @@ -0,0 +1,39 @@ +import * as THREE from 'three'; +import { edgeParameter, featureEdges, SNAP_RADIUS, visibleEdgeRanges } from '../tools/measureSnap.js'; +import { isClipped } from '../tools/sectionMath.js'; + +export function meshSnapCandidates(hit, camera, rect, clientX, clientY, sections) { + const { view, node, element } = hit; + const { position, index, tags } = view; + const triangles = tags ? index.filter((_, i) => tags[Math.floor(i / 3)] === element) : index; + const { vertices, edges } = featureEdges(position, triangles); + const matrix = new THREE.Matrix4().multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse); + const shift = new THREE.Vector3().fromArray(node.shift ?? [0, 0, 0]); + const { planes, intersection } = sections.clipping(); + const x = clientX - rect.left, y = clientY - rect.top; + const points = new Map(); + const rank = { vertex: 0, midpoint: 1, edge: 2 }; + const best = []; + const offer = (kind, point, p) => { + if (p.w <= 0 || Math.abs(p.z) > p.w || (kind !== 'edge' && isClipped(point, planes, intersection))) return; + const sx = (p.x / p.w + 1) * rect.width / 2, sy = (1 - p.y / p.w) * rect.height / 2; + const distance = (sx - x) ** 2 + (sy - y) ** 2; + if (distance > SNAP_RADIUS ** 2 || distance >= (best[rank[kind]]?.distance ?? Infinity)) return; + best[rank[kind]] = { kind, point, distance }; + }; + for (const i of vertices) { + const point = new THREE.Vector3().fromArray(position, i * 3).add(shift); + const p = new THREE.Vector4(point.x, point.y, point.z, 1).applyMatrix4(matrix); + points.set(i, [point, p]); + offer('vertex', point, p); + } + for (let i = 0; i < edges.length; i += 2) { + const [a, pa] = points.get(edges[i]), [b, pb] = points.get(edges[i + 1]); + offer('midpoint', a.clone().lerp(b, 0.5), pa.clone().lerp(pb, 0.5)); + for (const range of visibleEdgeRanges(a, b, pa, pb, planes, intersection)) { + const t = edgeParameter(pa, pb, range, rect, x, y); + if (t !== null) offer('edge', a.clone().lerp(b, t), pa.clone().lerp(pb, t)); + } + } + return best.filter(Boolean); +} diff --git a/src/IOViewer/Viewer/src/stream/meshTools.js b/src/IOViewer/Viewer/src/stream/meshTools.js new file mode 100644 index 0000000..623a73b --- /dev/null +++ b/src/IOViewer/Viewer/src/stream/meshTools.js @@ -0,0 +1,254 @@ +import * as THREE from 'three'; +import { t } from '../i18n.js'; +import { screenBoxes, selectInRect } from '../select/boxSelect.js'; +import { Selection } from '../select/selection.js'; +import { Measure } from '../tools/measure.js'; +import { SNAP_RADIUS } from '../tools/measureSnap.js'; +import { GridAxes } from '../tools/grids.js'; +import { mountDisplay } from '../tools/display.js'; +import { SectionGizmo } from '../tools/sectionGizmo.js'; +import { isClipped } from '../tools/sectionMath.js'; +import { Sections } from '../tools/sections.js'; +import { mountUI } from '../ui/app.js'; +import { el } from '../ui/dom.js'; +import { mountSections } from '../ui/sectionsPanel.js'; +import { mountViews } from '../ui/viewsPanel.js'; +import { mountClashes } from '../ui/clashesPanel.js'; +import { mountLinks } from '../ui/linksPanel.js'; +import { mountTimeliner } from '../ui/timeliner.js'; +import { meshSnapCandidates } from './meshSnap.js'; + +// Trace the original leaves independently of the cut on screen. The nearest hit gives the same element at every LOD. +export async function pickMeshSurface(ray, roots, nodes, getPage, sections, signal, visible = () => true) { + const queue = [], p = new THREE.Vector3(), a = p.clone(), b = p.clone(), c = p.clone(); + const localRay = ray.clone(), shift = new THREE.Vector3(); + const clip = sections.clipping(); + const enqueue = (node) => { + if (sections.isCut(node.box, clip)) return; + if (node.box.containsPoint(ray.origin)) queue.push({ node, distance: 0 }); + else if (ray.intersectBox(node.box, p)) queue.push({ node, distance: p.distanceToSquared(ray.origin) }); + }; + for (const root of roots) enqueue(root); + let hit = null, best = Infinity; + while (queue.length) { + signal?.throwIfAborted(); + queue.sort((u, v) => v.distance - u.distance); + const { node, distance } = queue.pop(); + if (distance > best) break; + if (node.children.length) { + for (const id of node.children) enqueue(nodes[id]); + continue; + } + const view = await getPage(node, signal); + const { position, index, color, tags } = view; + if (index.some((i) => i >= position.length / 3) || position.some((value) => !Number.isFinite(value))) { + throw new Error('Invalid pick page geometry.'); + } + shift.fromArray(node.shift ?? [0, 0, 0]); + localRay.origin.copy(ray.origin).sub(shift); + for (let i = 0; i < index.length; i += 3) { + const element = tags?.[i / 3] ?? null; + if (element !== null && !visible(element)) continue; + const x = index[i], y = index[i + 1], z = index[i + 2]; + if (!color[x * 4 + 3] && !color[y * 4 + 3] && !color[z * 4 + 3]) continue; + a.fromArray(position, x * 3); + b.fromArray(position, y * 3); + c.fromArray(position, z * 3); + if (!localRay.intersectTriangle(a, b, c, true, p)) continue; + p.add(shift); + const d = p.distanceToSquared(ray.origin); + if (d >= best || isClipped(p, clip.planes, clip.intersection)) continue; + best = d; + hit = { element, point: p.clone(), view, node }; + } + } + return hit; +} + +export function mountMeshTools({ manifest, roots, nodes, bounds, world, controls, canvas, scene, fetchPage, setBackground, canFill, render, ru }) { + const selection = new Selection(); + const root = document.querySelector('#ioviewer-ui'); + const elements = manifest.elements ?? []; + const meta = { ...manifest.review, elements }; + const sections = new Sections(scene, bounds, meta.sections); + const sectionGizmo = new SectionGizmo(sections, canvas); + const measure = new Measure(root); + const grids = new GridAxes(root, meta.grids ?? []); + world.add(sectionGizmo.group, measure.group, grids.group); + sectionGizmo.addEventListener('change', render); + measure.addEventListener('change', render); + const note = el('span'); + note.id = 'stream-pick-status'; + note.setAttribute('role', 'status'); + note.hidden = true; + document.querySelector('#stream-controls').append(note); + const data = { meta, async loadProperties(index, signal) { + const entry = elements[index]; + if (!entry.size) return null; + const response = await fetch(`/elements/${index}`, { signal }); + if (!response.ok || Number(response.headers.get('content-length')) !== entry.size) throw new Error('Invalid element response.'); + const loaded = await response.json(); + if (loaded?.id !== entry.id || !loaded.properties || typeof loaded.properties !== 'object' || Array.isArray(loaded.properties) + || Object.values(loaded.properties).some((group) => !group || typeof group !== 'object' || Array.isArray(group))) { + throw new Error('Invalid element data.'); + } + return loaded; + } }; + const outline = new THREE.Box3Helper(new THREE.Box3(), 0xf59e0b); + outline.visible = false; + world.add(outline); + const updateOutline = () => { + outline.box.makeEmpty(); + const clip = sections.clipping(); + const bounds = new THREE.Box3(); + for (const i of selection.values()) { + if (scene.isVisible(i) && !sections.isCut(scene.elementBox(i, bounds), clip)) outline.box.union(bounds); + } + outline.visible = !outline.box.isEmpty(); + outline.material.clippingPlanes = clip.planes; + outline.material.clipIntersection = clip.intersection; + render(); + }; + selection.addEventListener('change', () => { + scene.setHighlighted(selection.values()); + updateOutline(); + }); + let controller, previewTimer; + const cancel = () => { + controller?.abort(); + clearTimeout(previewTimer); + measure.setPreview(null); + }; + const measurePages = new Map(); + async function getPage(node, signal) { + if (!measure.active) return fetchPage(node, signal); + if (measurePages.has(node.id)) return measurePages.get(node.id); + const view = await fetchPage(node, signal); + signal.throwIfAborted(); + if (measurePages.size === 4) measurePages.delete(measurePages.keys().next().value); + measurePages.set(node.id, view); + return view; + } + async function pick(x, y, preview = false) { + if (!elements.length && !measure.active) return null; + controller?.abort(); + const current = new AbortController(); + controller = current; + let failed = false; + if (!preview) { + note.hidden = false; + note.textContent = ru ? 'Поиск элемента…' : 'Finding element…'; + } + try { + const rect = canvas.getBoundingClientRect(); + const cursor = new THREE.Vector2(); + const picker = new THREE.Raycaster(); + const camera = controls.camera; + camera.updateMatrixWorld(); + const trace = (ndc) => { + picker.setFromCamera(ndc, camera); + return pickMeshSurface(picker.ray, roots, nodes, getPage, sections, current.signal, scene.isVisible); + }; + const at = (cx, cy) => trace(cursor.set((cx - rect.left) / rect.width * 2 - 1, 1 - (cy - rect.top) / rect.height * 2)); + const hit = await at(x, y); + current.signal.throwIfAborted(); + if (hit?.element != null && !elements[hit.element]) throw new Error('Invalid mesh element index.'); + if (measure.active) { + let near = hit; + for (let direction = 0; !near && direction < 8; direction++) { + const angle = direction * Math.PI / 4; + near = await at(x + Math.cos(angle) * SNAP_RADIUS, y + Math.sin(angle) * SNAP_RADIUS); + current.signal.throwIfAborted(); + } + if (!near) return null; + for (const target of meshSnapCandidates(near, camera, rect, x, y, sections)) { + const obstruction = await trace(target.point.clone().project(camera)); + current.signal.throwIfAborted(); + if (!obstruction || obstruction.point.distanceTo(picker.ray.origin) + 0.002 >= target.point.distanceTo(picker.ray.origin)) return target; + } + return hit ? { kind: 'surface', point: hit.point } : null; + } + return hit?.element != null ? hit : null; + } catch (error) { + if (!current.signal.aborted) { + failed = true; + note.textContent = `${t('badData')}. ${error.message}`; + note.hidden = false; + } + } finally { + if (controller === current) { + controller = undefined; + note.hidden = !failed; + } + } + } + const ui = mountUI({ root, data, scene, controls, picker: { pick }, selection, measure }); + mountSections({ root, ...ui, sections, selection, canFill }); + const restoreLinkedModels = mountLinks({ ...ui, files: meta.linkedFiles ?? [], elements, scene }); + mountViews({ ...ui, controls, scene, sections, selection, restoreLinkedModels, + views: meta.viewpoints ?? [], bcfTopics: meta.bcfTopics ?? [] }); + const clashes = mountClashes({ ...ui, tests: meta.clashTests ?? [], elements, scene, controls, selection }); + world.add(clashes.group); + const timeliner = mountTimeliner({ root, ...ui, timeliner: meta.timeliner, elements, scene }); + const initialBackground = '#1f2228'; + const background = new THREE.Color(initialBackground); + for (const popover of mountDisplay({ root, toolbar: ui.toolbar, scene, meta, grids, initialBackground, setBackground(color) { + setBackground(background.set(color)); + const { r, g, b } = background; + const light = 0.2126 * r + 0.7152 * g + 0.0722 * b > Math.sqrt(0.0525) - 0.05; + root.style.setProperty('--viewport-text', color === initialBackground ? '' : light ? '#000' : '#fff'); + render(); + } })) ui.onEscape(popover.close); + grids.addEventListener('change', () => controls.setExtraBounds('grids', grids.visible ? grids.box : null)); + if (grids.visible) controls.setExtraBounds('grids', grids.box); + measure.addEventListener('change', () => controls.setExtraBounds('measure', measure.box)); + measure.addEventListener('previewchange', render); + sections.addEventListener('change', () => { cancel(); updateOutline(); }); + scene.root.addEventListener('change', (event) => { + if (event.detail.kind === 'visibility') { cancel(); updateOutline(); } + }); + controls.addEventListener('change', cancel); + window.addEventListener('pointerdown', cancel, true); + canvas.addEventListener('pointerleave', cancel); + canvas.addEventListener('pointermove', (event) => { + if (!measure.active || event.buttons) return; + cancel(); + previewTimer = setTimeout(async () => { + const target = await pick(event.clientX, event.clientY, true); + if (target !== undefined && measure.active) measure.setPreview(target); + }, 80); + }); + ui.toolbar.setHandler('distance', () => { + cancel(); + measure.setActive(!measure.active); + if (!measure.active) measurePages.clear(); + ui.toolbar.setActive('distance', measure.active); + }); + ui.toolbar.setActive('distance', false); + ui.onEscape(() => { cancel(); note.hidden = true; return measure.clear(); }); + controls.addEventListener('click', async ({ detail: { x, y, ctrl, shift } }) => { + const hit = await pick(x, y); + if (hit === undefined) return; + if (measure.active) { + if (hit) measure.add(hit.point); + return; + } + if (ctrl) { + if (hit) selection.toggle(hit.element); + } else if (hit) selection.set([hit.element]); + else if (!shift) selection.clear(); + }); + controls.addEventListener('boxselect', ({ detail: { rect, mode, ctrl, shift } }) => { + if (measure.active || !elements.length) return; + if (rect.width < 4 || rect.height < 4) { + if (!ctrl && !shift) selection.clear(); + return; + } + controls.camera.updateMatrixWorld(); + const found = selectInRect(rect, mode, screenBoxes(scene, controls.camera, canvas.getBoundingClientRect())); + const clip = sections.clipping(), bounds = new THREE.Box3(); + const shown = found.filter((i) => !sections.isCut(scene.elementBox(i, bounds), clip)); + selection.set(ctrl ? [...selection.values(), ...shown] : shown); + }); + return { sections, selection, ui, sectionGizmo, measure, grids, canFill, scene, clashes, timeliner }; +} diff --git a/src/IOViewer/Viewer/src/stream/pageFade.js b/src/IOViewer/Viewer/src/stream/pageFade.js new file mode 100644 index 0000000..1e0050a --- /dev/null +++ b/src/IOViewer/Viewer/src/stream/pageFade.js @@ -0,0 +1,9 @@ +export function applyPageFade(shader, fade, inverse) { + if (!fade) return; + shader.uniforms.pageFade = fade; + shader.fragmentShader = shader.fragmentShader + .replace('#include ', '#include \nuniform float pageFade;') + .replace('#include ', `#include + float pattern = fract(52.9829189 * fract(dot(floor(gl_FragCoord.xy), vec2(0.06711056, 0.00583715)))); + if (pattern ${inverse ? '<' : '>='} pageFade) discard;`); +} diff --git a/src/IOViewer/Viewer/src/stream/tile.js b/src/IOViewer/Viewer/src/stream/tile.js new file mode 100644 index 0000000..bd855fb --- /dev/null +++ b/src/IOViewer/Viewer/src/stream/tile.js @@ -0,0 +1,150 @@ +import { Matrix3, Matrix4, Vector3 } from 'three'; +import { binaryViewType, parseModelMeta } from '../data.js'; +import { bakeSource, indexArray, splitCells, unitNormals } from '../engine/chunks.js'; +import { normalsView, positionsView } from '../engine/quantize.js'; +import { MAX_TILE_INPUT, MAX_TILE_MESH } from './manifest.js'; + +const decoder = new TextDecoder('utf-8', { fatal: true }); +const encoder = new TextEncoder(); +const CHARS = 4 * 1024 ** 2; + +function block(html, opening) { + const marker = encoder.encode(opening); + // Find the opening tag without decoding the HTML or keeping two copies of the embedded BIN string. + for (let i = html.indexOf(60); i >= 0; i = html.indexOf(60, i + 1)) { + if (!marker.every((value, j) => value === html[i + j])) continue; + const start = i + marker.length; + const end = html.indexOf(60, start); + if (end >= start && decoder.decode(html.subarray(end, end + 9)) === '') return html.subarray(start, end); + break; + } + throw new Error('Missing or malformed tile data block.'); +} + +export function readTile(html, tile) { + if (html.length !== tile.bytes || html.length > MAX_TILE_INPUT) throw new Error('Tile length changed.'); + const meta = parseModelMeta(decoder.decode(block(html, ' + diff --git a/src/IOViewer/Viewer/test/e2e/mesh-review.spec.js b/src/IOViewer/Viewer/test/e2e/mesh-review.spec.js new file mode 100644 index 0000000..f2d384a --- /dev/null +++ b/src/IOViewer/Viewer/test/e2e/mesh-review.spec.js @@ -0,0 +1,234 @@ +import { expect, test } from '@playwright/test'; +import { execFileSync } from 'node:child_process'; +import { mkdtemp, rm, rmdir } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { buildMeshPages } from '../../build-mesh-pages.js'; +import { startStreamServer } from '../../serve-stream.js'; +import { fixturesDir, viewerDir } from './global-setup.js'; + +const generated = join(viewerDir, 'test-results'); +const cli = join(viewerDir, '../../IOViewer.Cli/bin/Release/net10.0/IOViewer.Cli.dll'); +const rail = (page, name) => page.locator(`.ioviewer-rail-button[data-panel="${name}"]`); +const panel = (page, name) => page.locator(`.ioviewer-side-panel[data-panel="${name}"]`); +const tool = (page, name) => page.locator(`[data-tool="${name}"]`); +const frame = (page) => page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)))); +let folder; + +test.beforeAll(async () => { + folder = await mkdtemp(join(tmpdir(), 'ioviewer-mesh-review-')); + for (const [name, input, ...args] of [ + ['review', join(generated, 'bcf-model.json'), '--bcf', join(fixturesDir, '../bcf/review.bcfzip')], + ['textures', join(fixturesDir, 'textured.json')], + ['measure', join(generated, 'measure-snap.json')], + ]) { + const source = join(folder, `${name}.ivmesh`); + execFileSync('dotnet', [cli, input, '-o', source, ...args], { stdio: 'pipe' }); + await buildMeshPages(source, join(folder, name)); + } +}); + +test.afterAll(async () => { + if (!folder) return; + for (const name of ['review', 'textures', 'measure']) { + await rm(join(folder, `${name}.ivmesh`), { force: true }); + for (const file of ['meshes.bin', 'manifest.json', 'elements.bin']) await rm(join(folder, name, file), { force: true }); + await rmdir(join(folder, name)).catch((error) => { if (error.code !== 'ENOENT') throw error; }); + } + await rmdir(folder); +}); + +async function withViewer(page, name, run) { + const { server, url } = await startStreamServer(join(folder, name)); + const errors = []; + page.on('pageerror', (e) => errors.push(e.message)); + page.on('console', (event) => { if (event.type() === 'error') errors.push(event.text()); }); + try { + await page.goto(url); + await page.waitForFunction(() => Boolean(window.__ioviewerMeshLod), null, { timeout: 7000 }); + await page.evaluate(() => window.__ioviewerMeshLod.ready); + await run(); + expect(errors).toEqual([]); + } finally { + await new Promise((resolve) => { + server.close(resolve); + server.closeAllConnections(); + }); + } +} + +function shown(page, name) { + return page.evaluate((name) => { + const { scene, manifest } = window.__ioviewerMeshLod; + return scene.isVisible(manifest.elements.findIndex((e) => e.name === name)); + }, name); +} + +async function sample(page, [x, y]) { + const png = await page.screenshot({ clip: { x: Math.round(x), y: Math.round(y), width: 1, height: 1 }, timeout: 4000 }); + return page.evaluate(async (bytes) => { + const image = new Image(); + image.src = `data:image/png;base64,${bytes}`; + await image.decode(); + const context = document.createElement('canvas').getContext('2d'); + context.drawImage(image, 0, 0); + return [...context.getImageData(0, 0, 1, 1).data].slice(0, 3); + }, png.toString('base64')); +} + +test('stream BIM panels share saved views, independent visibility layers, clashes and BCF', async ({ page }) => { + await withViewer(page, 'review', async () => { + await expect(page.locator('#stream-controls select')).toHaveCount(0); + await expect(page.locator('.ioviewer-grid-label').first()).toBeAttached(); + await tool(page, 'grids').click(); + await expect(page.locator('.ioviewer-grid-labels')).toBeHidden(); + await rail(page, 'views').click(); + await panel(page, 'views').locator('button.ioviewer-row').first().click(); + await page.waitForFunction(() => !window.__ioviewerMeshLod.controls.animating); + const saved = await page.evaluate(() => { + const { manifest, controls } = window.__ioviewerMeshLod; + return controls.target.toArray().map((n, i) => n - manifest.review.viewpoints[0].camera.target[i]); + }); + saved.forEach((value) => expect(value).toBeCloseTo(0, 6)); + + await rail(page, 'clashes').click(); + const clash = panel(page, 'clashes').locator('.ioviewer-clash').first(); + await clash.click(); + expect(await page.evaluate(() => window.__ioviewerMeshLod.clashes.group.visible)).toBe(true); + expect(await page.evaluate(() => window.__ioviewerMeshLod.selection.size)).toBeGreaterThan(0); + + await rail(page, 'links').click(); + const link = panel(page, 'links').getByRole('checkbox').first(); + const member = await page.evaluate(() => { + const { manifest } = window.__ioviewerMeshLod; + return manifest.elements[manifest.review.linkedFiles[0].members[0]].name; + }); + await link.uncheck(); + expect(await shown(page, member)).toBe(false); + await page.keyboard.press('Shift+H'); + expect(await shown(page, member)).toBe(false); + await link.check(); + expect(await shown(page, member)).toBe(true); + + await rail(page, 'timeliner').click(); + await expect(panel(page, 'timeliner').locator('.ioviewer-task')).toHaveCount(7); + await panel(page, 'timeliner').locator('.ioviewer-player-open').click(); + const player = page.locator('.ioviewer-player'); + await player.getByRole('button', { name: 'Пауза' }).click(); + expect(await shown(page, 'Ground Slab')).toBe(true); + expect(await shown(page, 'Supply Duct SA-1')).toBe(false); + await player.getByRole('button', { name: 'Закрыть' }).click(); + expect(await shown(page, 'Supply Duct SA-1')).toBe(true); + + await rail(page, 'bcf').click(); + const bcf = panel(page, 'bcf'); + await bcf.getByText('Inspect supply duct ', { exact: true }).click(); + await bcf.getByRole('button', { name: /1$/ }).first().click(); + expect(await shown(page, 'Ground Slab')).toBe(false); + expect(await page.evaluate(() => window.__ioviewerMeshLod.sections.planes.length)).toBe(1); + expect(await page.evaluate(() => window.__ioviewerMeshLod.selection.size)).toBe(2); + await bcf.getByRole('button', { name: /2$/ }).first().click(); + expect(await page.evaluate(() => window.__ioviewerMeshLod.controls.camera.isOrthographicCamera)).toBe(true); + expect(await shown(page, 'Supply Duct SA-1')).toBe(true); + }); +}); + +test('stream selection isolation and stencil cap render only the shown closed solid', async ({ page }) => { + await withViewer(page, 'review', async () => { + const item = await page.evaluate(() => { + const { scene, sections, controls, manifest, grids } = window.__ioviewerMeshLod; + grids.setVisible(false); + const index = manifest.elements.findIndex((element) => element.name === 'Column D2 Level 1'); + scene.isolate([index]); + const box = scene.elementBox(index); + const center = box.getCenter(box.min.clone()); + controls.setProjection('orthographic'); + controls.restoreViewCamera({ position: [center.x, center.y - 0.1, center.z + 10], target: center.toArray(), up: [0, 1, 0] }); + const plane = sections.addPlane('z'); + sections.updatePlane(plane, { offset: center.z - sections.center.z }); + sections.setGizmoVisible(false); + return index; + }); + await rail(page, 'sections').click(); + const fill = panel(page, 'sections').getByRole('checkbox', { name: 'Заливка срезов' }); + await frame(page); + const capDistance = async () => { + const rgb = await sample(page, [640, 400]); + return Math.hypot(...rgb.map((n, i) => n - [233, 173, 104][i])); + }; + expect(await capDistance()).toBeGreaterThan(40); + await fill.check(); + await expect.poll(capDistance).toBeLessThan(10); + await page.evaluate((i) => window.__ioviewerMeshLod.scene.setVisible([i], false), item); + await expect.poll(capDistance).toBeGreaterThan(40); + expect(await page.evaluate(() => window.__ioviewerMeshLod.stats().visible)).toBe(0); + }); +}); + +test('stream textures retain UVs and the standard display toolbar controls their appearance', async ({ page }) => { + await withViewer(page, 'textures', async () => { + const points = await page.evaluate(() => { + const { manifest, controls } = window.__ioviewerMeshLod; + const rtc = controls.target.clone().fromArray(manifest.origin); + const center = controls.target.clone().set(0, -2, 1.5).sub(rtc); + controls.restoreViewCamera({ position: center.clone().add(controls.target.clone().set(0, -3, 0)).toArray(), + target: center.toArray(), up: [0, 0, 1] }); + controls.camera.updateMatrixWorld(); + const a = 3 * Math.PI / 2, b = a + Math.PI / 24; + const first = center.clone().set(2 * Math.cos(a), 2 * Math.sin(a), 0); + const last = center.clone().set(2 * Math.cos(b), 2 * Math.sin(b), 0); + return [[9.53125, 1.53125], [9.59375, 1.53125], [9.65625, 1.53125], [9.53125, 1.59375]].map(([u, z]) => { + const p = first.clone().lerp(last, (u / 2 - a) / (b - a)).setZ(z).sub(rtc).project(controls.camera); + return [(p.x + 1) * innerWidth / 2, (1 - p.y) * innerHeight / 2]; + }); + }); + const mode = async (value) => { + await tool(page, 'displayMode').click(); + await page.locator(`[role=menuitemradio][data-mode=${value}]`).click(); + await frame(page); + }; + await mode('textures'); + await expect.poll(async () => { + const brightness = []; + for (const point of points) brightness.push((await sample(page, point)).reduce((a, b) => a + b) / 3); + return Math.min(brightness[0], brightness[2]) - Math.max(brightness[1], brightness[3]); + }).toBeGreaterThan(30); + await mode('white'); + const white = await sample(page, [640, 400]); + await mode('wireframe'); + expect(await sample(page, [640, 400])).not.toEqual(white); + await mode('materials'); + const opaque = await sample(page, [640, 400]); + await tool(page, 'opacity').click(); + await page.locator('.ioviewer-opacity-slider').fill('40'); + await frame(page); + expect(await sample(page, [640, 400])).not.toEqual(opaque); + }); +}); + +test('stream measurement snaps to a vertex, midpoint and edge on a fetched mesh', async ({ page }) => { + await withViewer(page, 'measure', async () => { + const coords = await page.evaluate(() => { + const { controls, scene } = window.__ioviewerMeshLod; + scene.setVisible([1], false); + controls.setProjection('orthographic'); + const box = scene.elementBox(0), center = box.getCenter(box.max.clone()); + controls.restoreViewCamera({ position: [center.x, center.y, center.z + 9], target: center.toArray(), up: [0, 1, 0] }); + controls.camera.updateMatrixWorld(); + return [[0, 0], [2, 0], [1, 0], [2, 2]].map(([x, y]) => { + const p = box.min.clone().set(box.min.x + x, box.min.y + y, box.min.z).project(controls.camera); + return [(p.x + 1) * innerWidth / 2, (1 - p.y) * innerHeight / 2]; + }); + }); + await tool(page, 'distance').click(); + const canvas = page.locator('#ioviewer-canvas'); + const marker = page.locator('.ioviewer-measure-preview'); + for (const [i, kind, dx, dy] of [[0, 'vertex', 5, -3], [1, 'midpoint', 0, -3], [2, 'edge', 0, -3], [3, 'surface', 0, 0]]) { + const x = coords[i][0] + dx, y = coords[i][1] + dy; + await canvas.dispatchEvent('pointermove', { clientX: x, clientY: y, pointerType: 'mouse' }); + await expect(marker).toHaveAttribute('data-kind', kind); + if (i < 2) await page.mouse.click(x, y); + } + expect(await page.evaluate(() => window.__ioviewerMeshLod.measure.distance)).toBeCloseTo(2, 5); + }); +}); diff --git a/src/IOViewer/Viewer/test/e2e/navigation.spec.js b/src/IOViewer/Viewer/test/e2e/navigation.spec.js index f9c1a69..746313c 100644 --- a/src/IOViewer/Viewer/test/e2e/navigation.spec.js +++ b/src/IOViewer/Viewer/test/e2e/navigation.spec.js @@ -100,6 +100,63 @@ test('wheel zooms by 0.85 per notch and the model stays inside near/far', async expect(covered).toBe(true); }); +for (const projection of ['perspective', 'orthographic']) { + test(`extreme ${projection} zoom out still permits pan and a quick return`, async ({ page }) => { + const errors = await open(page); + await page.evaluate((kind) => window.__ioviewer.controls.setProjection(kind), projection); + const scale = () => page.evaluate(() => { + const { camera, controls } = window.__ioviewer; + return camera.position.distanceTo(controls.target) / camera.zoom; + }); + const wheel = (count, deltaY) => page.evaluate(({ count, deltaY }) => { + const { dom } = window.__ioviewer.controls; + for (let i = 0; i < count; i++) { + dom.dispatchEvent(new WheelEvent('wheel', { deltaY, clientX: 640, clientY: 400, bubbles: true, cancelable: true })); + } + }, { count, deltaY }); + const fit = await scale(); + await wheel(120, 600); + await frame(page); + const far = await scale(); + expect(far / fit).toBeGreaterThan(5); + expect(far / fit).toBeLessThan(30); + + const target = () => page.evaluate(() => window.__ioviewer.controls.target.toArray()); + const before = await target(); + await drag(page, 'right', [640, 400], [655, 404]); + expect(await target()).not.toEqual(before); + expect((await scale()) / far).toBeCloseTo(1, 5); + await drag(page, 'right', [655, 404], [640, 400]); + await wheel(5, -600); + await frame(page); + expect((await scale()) / fit).toBeLessThan(1); + expect(await page.evaluate(() => { + const { camera } = window.__ioviewer; + return camera.near > 0 && camera.far > camera.near && camera.projectionMatrix.elements.every(Number.isFinite); + })).toBe(true); + expect(errors).toEqual([]); + }); +} + +test('pan and wheel recover when the target is a centimetre away but the geometry is farther', async ({ page }) => { + await open(page); + const depth = 1; + await page.evaluate((depth) => { + const { controls, camera } = window.__ioviewer; + controls.restoreViewCamera({ position: [0, -5, 1], target: [0, -4.99, 1], up: [0, 0, 1] }); + controls.pick = (x) => x === 640 ? camera.position.clone().set(0, -5 + depth, 1) : null; + }, depth); + await drag(page, 'right', [640, 400], [740, 400]); + const eye = () => page.evaluate(() => window.__ioviewer.controls.camera.position.toArray()); + expect((await eye())[0]).toBeCloseTo(-2 * depth * Math.tan(Math.PI / 8) * 100 / 800, 6); + + await page.mouse.move(660, 400); // miss under the cursor, with geometry at the centre of the viewport + await page.mouse.wheel(0, 100); + await frame(page); + expect((await eye())[1]).toBeCloseTo(-5 - (1 / 0.85 - 1) * depth, 6); + expect(await distance(page)).toBeCloseTo(depth / 0.85, 6); +}); + test('shift drag emits boxselect: dashed overlay for crossing, solid for window', async ({ page }) => { await open(page); await page.keyboard.down('Shift'); diff --git a/src/IOViewer/Viewer/test/perf/lod.perf.js b/src/IOViewer/Viewer/test/perf/lod.perf.js new file mode 100644 index 0000000..eb118c8 --- /dev/null +++ b/src/IOViewer/Viewer/test/perf/lod.perf.js @@ -0,0 +1,128 @@ +import { expect, test } from '@playwright/test'; +import { mkdir, writeFile } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { startStreamServer } from '../../serve-stream.js'; + +const folder = process.env.PERF_CLUSTER_MODEL; + +test('continuous mesh coverage and frame pacing across the clustered 15 GB source', async ({ page }) => { + test.skip(!folder, 'Set PERF_CLUSTER_MODEL to the packed fixture directory.'); + const { server, url } = await startStreamServer(folder); + const errors = []; + page.on('pageerror', (error) => errors.push(error.message)); + page.on('console', (message) => { + if (message.type() === 'error' && /shader error|WebGL:/.test(message.text())) errors.push(message.text()); + }); + let open; + const gate = new Promise((resolve) => (open = resolve)); + try { + await page.route('**/pages/*', async (route) => { await gate; await route.continue(); }); + await page.goto(url); + await page.waitForFunction(() => Boolean(window.__ioviewerLod)); + const overview = await page.evaluate(async () => { + const api = window.__ioviewerLod; + const gl = document.querySelector('canvas').getContext('webgl2'); + const debug = gl.getExtension('WEBGL_debug_renderer_info'); + return { readyMs: await api.ready, renderer: gl.getParameter(debug?.UNMASKED_RENDERER_WEBGL ?? gl.RENDERER), ...api.stats() }; + }); + expect(overview.renderedObjects).toBe(1_094_148); + expect(overview.requests).toBe(0); + await page.evaluate(() => { + const api = window.__ioviewerLod; + const node = api.manifest.roots[74].children[44]; + const target = node.min.map((n, i) => (n + node.max[i]) / 2 - api.manifest.origin[i]); + target[2] += 20; + api.controls.restoreViewCamera({ position: target.map((n, i) => n + [-12, -17, 20][i]), target, up: [0, 0, 1] }); + }); + await page.waitForFunction(() => window.__ioviewerLod.stats().pending > 0); + const waiting = await page.evaluate(() => window.__ioviewerLod.stats()); + expect(waiting.shown[3]).toBe(0); + expect(waiting.renderedObjects).toBeGreaterThan(100); + expect(waiting.triangles).toBeGreaterThan(10_000); + open(); + await page.waitForFunction(() => { + const s = window.__ioviewerLod.stats(); + return s.shown[3] > 0 && s.pending === 0; + }); + const refined = await page.evaluate(() => window.__ioviewerLod.stats()); + expect(refined.renderedObjects).toBe(waiting.renderedObjects); + expect(refined.shown[3]).toBe(refined.detailDemand); + + const route = await page.evaluate(async () => { + const api = window.__ioviewerLod; + const next = () => new Promise((resolve) => requestAnimationFrame(resolve)); + const row = api.manifest.roots.filter((r) => r.y === 6); + const mid = (r) => r.min.map((n, i) => (n + r.max[i]) / 2 - api.manifest.origin[i]); + const a = mid(row[0]), b = mid(row.at(-1)); + const set = (target, offset) => api.controls.restoreViewCamera({ position: target.map((n, i) => n + offset[i]), target, up: [0, 0, 1] }); + const sample = async (ms, step) => { + const start = await next(); + let prev = start, uncoveredFrames = 0, fine = 0, demand = 0, maxTriangles = 0, maxDraws = 0; + const durations = []; + while (prev - start < ms) { + const now = await next(), elapsed = now - prev; + const s = api.stats(); + if (s.renderedObjects === 0) uncoveredFrames++; + if (s.detailDemand) { + fine += s.shown[3] / s.detailDemand * elapsed; + demand += elapsed; + } + maxTriangles = Math.max(maxTriangles, s.triangles); + maxDraws = Math.max(maxDraws, s.draws); + step(Math.min(1, (now - start) / ms)); + durations.push(elapsed); + prev = now; + } + durations.sort((x, y) => x - y); + return { ms, samples: durations.length, p50: durations[Math.ceil(0.5 * durations.length) - 1], + p95: durations[Math.ceil(0.95 * durations.length) - 1], p99: durations[Math.ceil(0.99 * durations.length) - 1], + max: durations.at(-1), uncoveredFrames, fineCoverage: demand ? fine / demand : null, maxTriangles, maxDraws }; + }; + const fly = (fraction) => { + const target = a.map((n, i) => n + (b[i] - n) * fraction); + set(target, [-45, -55 + Math.sin(fraction * 4 * Math.PI) * 10, 100]); + }; + fly(0); + await next(); + await next(); + const flyover = await sample(30_000, fly); + const near = (fraction) => { + const target = a.map((n, i) => n + (b[i] - n) * (0.25 + fraction * 0.28)); + target[2] += 20; + set(target, [-12, -17, 20]); + }; + near(0); + await next(); + await next(); + const close = await sample(20_000, near); + for (const root of api.manifest.roots.filter((root) => root.y % 2 === 0 && [4, 8, 11].includes(root.x))) { + if (api.stats().evictions > 0) break; + const target = mid(root.children[55]); + target[2] += 20; + set(target, [-12, -17, 20]); + const deadline = performance.now() + 2500; + do { await next(); } + while (performance.now() < deadline && (api.stats().pending || api.stats().shown[3] < api.stats().detailDemand)); + } + return { flyover, close, end: api.stats() }; + }); + const out = process.env.PERF_OUT ?? path.join(os.tmpdir(), 'ioviewer-perf'); + await mkdir(out, { recursive: true }); + const report = { overview, waiting, refined, ...route }; + await writeFile(path.join(out, `lod-${process.env.PERF_LABEL || process.env.PERF_GPU || 'default'}.json`), JSON.stringify(report, null, 2)); + console.log(JSON.stringify(report)); + expect(route.flyover.uncoveredFrames).toBe(0); + expect(route.close.uncoveredFrames).toBe(0); + expect(route.close.fineCoverage).toBeGreaterThan(0.5); + expect(route.end.peak).toBeLessThanOrEqual(route.end.budget); + expect(route.end.requests).toBeGreaterThan(50); + expect(route.end.evictions).toBeGreaterThan(0); + expect(route.end.failures).toEqual([]); + expect(errors).toEqual([]); + } finally { + open(); + await page.close(); + await new Promise((resolve) => server.close(resolve)); + } +}); diff --git a/src/IOViewer/Viewer/test/perf/mesh-approach.perf.js b/src/IOViewer/Viewer/test/perf/mesh-approach.perf.js new file mode 100644 index 0000000..a8d6a08 --- /dev/null +++ b/src/IOViewer/Viewer/test/perf/mesh-approach.perf.js @@ -0,0 +1,151 @@ +import { expect, test } from '@playwright/test'; +import { mkdtemp, rm, rmdir, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { startStreamServer } from '../../serve-stream.js'; +import { MESH_FORMAT, sizeOfPage, viewsOfPage } from '../../src/stream/meshPages.js'; + +test('a covered mesh cut switches without mixed pixels and holds its detail', async ({ page }) => { + const folder = await mkdtemp(join(tmpdir(), 'ioviewer-refine-')); + const manifestPath = join(folder, 'manifest.json'), geometryPath = join(folder, 'meshes.bin'); + const nodes = [0, 400, 0].map((x) => ({ + min: [x, 0, 0], max: [x + 1, 1, 0], offset: 0, vertices: 4, indices: 6, opaque: 6, error: 0, children: [], + })); + const root = nodes[2]; + Object.assign(root, { children: [0, 1], max: nodes[1].max, error: 0.1 }); + const size = sizeOfPage(root); + const data = nodes.map((node, i) => { + const x = node.min[0], buffer = new ArrayBuffer(size); + node.offset = i * size; + const view = viewsOfPage(buffer, node); + view.position.set([x, 0, 0, x + 1, 0, 0, x, 1, 0, x + 1, 1, 0]); + view.normal.set([0, 0, 32767, 0, 0, 32767, 0, 0, 32767, 0, 0, 32767]); + view.index.set([0, 1, 2, 1, 3, 2]); + for (let at = 0; at < view.color.length; at += 4) view.color.set(i === 2 ? [255, 0, 0, 255] : [0, 255, 0, 255], at); + return Buffer.from(buffer); + }); + let server, release, readyLeaf; + const hold = new Promise((resolve) => (release = resolve)); + const leaf = new Promise((resolve) => (readyLeaf = resolve)); + try { + await writeFile(geometryPath, Buffer.concat(data)); + await writeFile(manifestPath, JSON.stringify({ + format: MESH_FORMAT, min: root.min, max: root.max, origin: [0, 0, 0], triangles: 4, bytes: size * 3, pages: nodes, roots: [2], + })); + const streaming = await startStreamServer(folder); + server = streaming.server; + await page.route('**/pages/1', async (route) => { await hold; await route.abort(); }); + await page.route('**/pages/0', async (route) => { await leaf; await route.continue(); }); + await page.addInitScript(() => { + window.cutFrames = []; + const pixels = new Uint8Array(36); + window.IOVIEWER_MESH_PROFILE = { nativePixels: true, fetch() {}, prepare() {}, draw(gl, draw) { + draw(); + if (!window.captureCut) return; + gl.readPixels((gl.drawingBufferWidth >> 1) - 1, (gl.drawingBufferHeight >> 1) - 1, 3, 3, gl.RGBA, gl.UNSIGNED_BYTE, pixels); + let red = 0, green = 0; + for (let at = 0; at < pixels.length; at += 4) { + if (pixels[at] > pixels[at + 1] + 30) red++; + if (pixels[at + 1] > pixels[at] + 30) green++; + } + window.cutFrames.push([red, green]); + } }; + }); + await page.goto(streaming.url); + await page.waitForFunction(() => Boolean(window.__ioviewerMeshLod)); + await page.evaluate(async () => { + const api = window.__ioviewerMeshLod; + await api.ready; + window.captureCut = true; + api.controls.restoreViewCamera({ position: [0.5, 0.5, 30], target: [0.5, 0.5, 0], up: [0, 1, 0] }); + }); + await expect.poll(() => page.evaluate(() => window.cutFrames), { timeout: 5000 }).toContainEqual([9, 0]); + readyLeaf(); + await page.waitForFunction(() => window.__ioviewerMeshLod.stats().exact === 1, null, { timeout: 5000 }); + const stats = await page.evaluate(() => window.__ioviewerMeshLod.stats()); + expect(stats.triangles).toBe(2); + expect(stats.fallback).toBe(0); + expect(stats.failures).toEqual([]); + const frames = await page.evaluate(() => { + window.captureCut = false; + const { controls } = window.__ioviewerMeshLod; + const z = 0.1 * controls.dom.clientHeight / (2 * Math.tan(Math.PI / 8) * 1.2); + controls.restoreViewCamera({ position: [0.5, 0.5, z], target: [0.5, 0.5, 0], up: [0, 1, 0] }); + return window.cutFrames; + }); + expect(frames).toContainEqual([9, 0]); + expect(frames).toContainEqual([0, 9]); + expect(frames.every(([red, green]) => red === 9 || green === 9)).toBe(true); + await page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)))); + expect(await page.evaluate(() => window.__ioviewerMeshLod.stats().exact)).toBe(1); + } finally { + readyLeaf(); + release(); + await page.close(); + if (server) await new Promise((resolve) => server.close(resolve)); + await Promise.all([manifestPath, geometryPath].map((file) => rm(file, { force: true }))); + await rmdir(folder); + } +}); + +test('measure refinement while approaching a cold area and after arriving', async ({ page }) => { + const folder = process.env.PERF_MESH_MODEL; + test.skip(!folder, 'Set PERF_MESH_MODEL to a prepared cluster package.'); + const { server, url } = await startStreamServer(folder); + const errors = []; + page.on('pageerror', (error) => errors.push(error.message)); + try { + await page.addInitScript(() => { + window.IOVIEWER_MESH_PROFILE = { coarseMetrics: true, fetch() {}, prepare() {}, draw: (_, draw) => draw() }; + }); + await page.goto(url); + await page.waitForFunction(() => Boolean(window.__ioviewerMeshLod)); + const report = await page.evaluate(async () => { + const api = window.__ioviewerMeshLod; + const { controls, manifest } = api; + await api.ready; + const region = manifest.placements?.[1] ?? manifest.focus ?? manifest; + const target = region.min.map((n, i) => (n + region.max[i]) / 2); + const near = [8, -11, 5]; + const next = () => new Promise(requestAnimationFrame); + const move = (scale) => controls.restoreViewCamera({ position: target.map((n, i) => n + near[i] * scale), target, up: [0, 0, 1] }); + move(24); + const start = await next(); + const approach = 1800, hold = 6000; + let now = start, arrival = null, lastCoarse = null, lastNearbyCoarse = null, firstExact = null, blank = 0, coarseFrames = 0; + let atThreeSeconds; + const intervals = []; + do { + const previous = now; + now = await next(); + const stats = api.stats(); + if (firstExact === null && stats.exact) firstExact = now - start - approach; + if (now - start >= approach) { + arrival ??= stats.coarsePixels; + if (now - start >= approach + 3000) atThreeSeconds ??= { exact: stats.exact, fallback: stats.fallback }; + if (stats.coarsePixels > 6) { + lastCoarse = now - start - approach; + coarseFrames++; + } + if (stats.nearbyCoarsePixels > 6) lastNearbyCoarse = now - start - approach; + } + if (!stats.visible) blank++; + intervals.push(now - previous); + if (previous - start < approach) move(24 ** (1 - Math.min(1, (now - start) / approach))); + } while (now - start < approach + hold); + intervals.sort((a, b) => a - b); + return { arrivalErrorPx: arrival, lastCoarseMs: lastCoarse, lastNearbyCoarseMs: lastNearbyCoarse, firstExactMs: firstExact, atThreeSeconds, + coarseFrames, blank, p95: intervals[Math.ceil(intervals.length * 0.95) - 1], max: intervals.at(-1), end: api.stats() }; + }); + console.log(JSON.stringify(report)); + if (process.env.PERF_OUT) await writeFile(join(process.env.PERF_OUT, `mesh-approach-${process.env.PERF_LABEL}.json`), JSON.stringify(report, null, 2)); + expect(report.blank).toBe(0); + expect(report.firstExactMs).not.toBeNull(); + expect(report.end.peak).toBeLessThanOrEqual(report.end.budget); + expect(report.end.failures).toEqual([]); + expect(errors).toEqual([]); + } finally { + await page.close(); + await new Promise((resolve) => server.close(resolve)); + } +}); diff --git a/src/IOViewer/Viewer/test/perf/mesh-federation.perf.js b/src/IOViewer/Viewer/test/perf/mesh-federation.perf.js new file mode 100644 index 0000000..87d7c14 --- /dev/null +++ b/src/IOViewer/Viewer/test/perf/mesh-federation.perf.js @@ -0,0 +1,85 @@ +import { expect, test } from '@playwright/test'; +import { readFile, stat, writeFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import { startStreamServer } from '../../serve-stream.js'; + +test('browse a federation wider than a 32-bit file offset under the page budget', async ({ page }) => { + const folder = process.env.PERF_FEDERATED_MODEL; + test.skip(!folder, 'Set PERF_FEDERATED_MODEL to a prepared large federation.'); + const manifest = JSON.parse(await readFile(join(folder, 'manifest.json'))); + expect((await stat(join(folder, 'meshes.bin'))).size).toBe(manifest.bytes); + expect(manifest.bytes).toBeGreaterThanOrEqual(10_000_000_000); + const { server, url } = await startStreamServer(folder); + let highOffset = 0; + const errors = []; + page.on('pageerror', (error) => errors.push(error.message)); + page.on('response', (response) => { + const match = new URL(response.url()).pathname.match(/^\/pages\/(\d+)$/); + if (match && response.ok()) highOffset = Math.max(highOffset, manifest.pages[Number(match[1])].offset); + }); + try { + await page.goto(url); + await page.waitForFunction(() => Boolean(window.__ioviewerMeshLod)); + const report = await page.evaluate(async () => { + const api = window.__ioviewerMeshLod; + const readyMs = await api.ready; + const overview = api.stats().triangles; + const next = () => new Promise(requestAnimationFrame); + const { placements } = api.manifest; + const set = (target, offset) => api.controls.restoreViewCamera({ + position: target.map((n, axis) => n + offset[axis]), target, up: [0, 0, 1], + }); + const run = async (duration, apply) => { + apply(0); + await next(); + const times = []; + let blank = 0, exact = 0, previous = await next(); + const start = previous; + while (previous - start < duration) { + const now = await next(); + times.push(now - previous); + const stats = api.stats(); + if (!stats.triangles || !stats.visible) blank++; + if (stats.exact) exact++; + apply(Math.min(1, (now - start) / duration)); + previous = now; + } + times.sort((a, b) => a - b); + return { frames: times.length, blank, exact, p95Ms: times[Math.ceil(times.length * 0.95) - 1], maxMs: times.at(-1) }; + }; + const centre = api.controls.target.toArray(); + const [x, y, z] = api.controls.camera.position.clone().sub(api.controls.target).toArray(); + const orbit = await run(8000, (k) => { + const a = Math.PI * k; + set(centre, [x * Math.cos(a) - y * Math.sin(a), x * Math.sin(a) + y * Math.cos(a), z]); + }); + const routes = []; + for (const i of [0, 1, Math.floor(placements.length / 2), placements.length - 2, placements.length - 1]) { + const { min, max } = placements[i]; + const route = await run(6000, (k) => { + const target = min.map((n, axis) => (n + max[axis]) / 2); + target[2] = min[2] + (max[2] - min[2]) * (0.24 + k * 0.52); + set(target, [8, -11, 5]); + }); + routes.push({ placement: i, ...route }); + } + return { readyMs, overview, orbit, routes, ...api.stats() }; + }); + const result = { archiveBytes: manifest.bytes, pages: manifest.pages.length, sourceTriangles: manifest.triangles, highOffset, ...report }; + console.log(JSON.stringify(result)); + await writeFile(join(process.env.PERF_OUT ?? folder, `mesh-federation-${process.env.PERF_LABEL ?? 'default'}.json`), JSON.stringify(result, null, 2)); + expect(report.overview).toBeGreaterThan(0); + expect(report.orbit.blank).toBe(0); + for (const route of report.routes) { + expect(route.blank).toBe(0); + expect(route.exact).toBeGreaterThan(0); + } + expect(highOffset).toBeGreaterThan(2 ** 32); + expect(report.peak).toBeLessThanOrEqual(report.budget); + expect(report.failures).toEqual([]); + expect(errors).toEqual([]); + } finally { + await page.close(); + await new Promise((resolve) => server.close(resolve)); + } +}); diff --git a/src/IOViewer/Viewer/test/perf/mesh-lod.perf.js b/src/IOViewer/Viewer/test/perf/mesh-lod.perf.js new file mode 100644 index 0000000..74d2708 --- /dev/null +++ b/src/IOViewer/Viewer/test/perf/mesh-lod.perf.js @@ -0,0 +1,103 @@ +import { expect, test } from '@playwright/test'; +import { mkdir, readFile, writeFile } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { startStreamServer } from '../../serve-stream.js'; + +const folder = process.env.PERF_MESH_MODEL; + +test('walk a real model with progressive mesh coverage', async ({ page }) => { + test.skip(!folder, 'Set PERF_MESH_MODEL to the prepared real model folder.'); + const manifest = JSON.parse(await readFile(path.join(folder, 'manifest.json'))); + const initial = new Set(manifest.roots.map((id) => `/pages/${id}`)); + const { server, url } = await startStreamServer(folder); + const errors = []; + page.on('pageerror', (error) => errors.push(error.message)); + page.on('console', (event) => { if (/shader error|WebGL:/.test(event.text())) errors.push(event.text()); }); + let release; + const gate = new Promise((resolve) => (release = resolve)); + try { + await page.route('**/pages/*', async (route) => { + if (!initial.has(new URL(route.request().url()).pathname)) await gate; + await route.continue(); + }); + await page.goto(url); + await page.waitForFunction(() => Boolean(window.__ioviewerMeshLod)); + const overview = await page.evaluate(async () => { + const api = window.__ioviewerMeshLod; + const gl = document.querySelector('canvas').getContext('webgl2'); + const debug = gl.getExtension('WEBGL_debug_renderer_info'); + return { readyMs: await api.ready, renderer: gl.getParameter(debug?.UNMASKED_RENDERER_WEBGL ?? gl.RENDERER), ...api.stats() }; + }); + await page.evaluate(() => { + const { controls, manifest } = window.__ioviewerMeshLod; + const { min, max } = manifest.focus ?? manifest; + const target = min.map((n, i) => (n + max[i]) / 2); + controls.restoreViewCamera({ position: target.map((n, i) => n + [8, -11, 5][i]), target, up: [0, 0, 1] }); + }); + await page.waitForFunction(() => window.__ioviewerMeshLod.stats().fallback > 0); + const waiting = await page.evaluate(() => window.__ioviewerMeshLod.stats()); + const delayStart = Date.now(); + release(); + await page.waitForFunction(() => window.__ioviewerMeshLod.stats().exact > 0, null, { timeout: 30_000 }); + const firstExactMs = Date.now() - delayStart; + const result = await page.evaluate(async () => { + const api = window.__ioviewerMeshLod; + const next = () => new Promise((resolve) => requestAnimationFrame(resolve)); + const { min, max } = api.manifest.focus ?? api.manifest; + const centre = min.map((n, i) => (n + max[i]) / 2); + const extent = Math.hypot(...max.map((n, i) => n - min[i])); + const set = (target, shift) => api.controls.restoreViewCamera({ position: target.map((n, i) => n + shift[i]), target, up: [0, 0, 1] }); + const run = async (duration, step) => { + step(0); + await next(); + const start = await next(); + let previous = start, blank = 0, framesWithExact = 0, peakTriangles = 0, peakErrorPx = 0; + const times = []; + do { + const now = await next(); + const stats = api.stats(); + if (!stats.visible || !stats.triangles) blank++; + if (stats.exact) framesWithExact++; + peakTriangles = Math.max(peakTriangles, stats.triangles); + peakErrorPx = Math.max(peakErrorPx, stats.threshold); + times.push(now - previous); + previous = now; + step(Math.min(1, (now - start) / duration)); + } while (previous - start < duration); + times.sort((a, b) => a - b); + const percentile = (p) => times[Math.ceil(p * times.length) - 1]; + return { samples: times.length, p50Ms: percentile(0.5), p95Ms: percentile(0.95), p99Ms: percentile(0.99), + maxMs: times.at(-1), blank, framesWithExact, peakTriangles, peakErrorPx }; + }; + const orbit = await run(12_000, (fraction) => { + const theta = -Math.PI / 2 + 0.9 * Math.PI * fraction; + set(centre, [extent * Math.cos(theta), extent * Math.sin(theta), extent * 0.6]); + }); + const close = await run(15_000, (fraction) => { + const target = [...centre]; + target[2] = min[2] + (max[2] - min[2]) * (0.12 + fraction * 0.76); + set(target, [8, -11, 5]); + }); + return { orbit, close, end: api.stats() }; + }); + const out = process.env.PERF_OUT ?? path.join(os.tmpdir(), 'ioviewer-perf'); + await mkdir(out, { recursive: true }); + const report = { triangles: manifest.triangles, overview, waiting, firstExactMs, ...result }; + await writeFile(path.join(out, `mesh-lod-${process.env.PERF_LABEL || process.env.PERF_GPU || 'default'}.json`), JSON.stringify(report, null, 2)); + console.log(JSON.stringify(report)); + expect(overview.triangles).toBeGreaterThan(0); + expect(waiting.triangles).toBeGreaterThan(0); + expect(waiting.exact).toBe(0); + expect(result.orbit.blank).toBe(0); + expect(result.close.blank).toBe(0); + expect(result.close.framesWithExact).toBeGreaterThan(0); + expect(result.end.peak).toBeLessThanOrEqual(result.end.budget); + expect(result.end.failures).toEqual([]); + expect(errors).toEqual([]); + } finally { + release(); + await page.close(); + await new Promise((resolve) => server.close(resolve)); + } +}); diff --git a/src/IOViewer/Viewer/test/perf/mesh-profile.perf.js b/src/IOViewer/Viewer/test/perf/mesh-profile.perf.js new file mode 100644 index 0000000..b3e6a99 --- /dev/null +++ b/src/IOViewer/Viewer/test/perf/mesh-profile.perf.js @@ -0,0 +1,107 @@ +import { expect, test } from '@playwright/test'; +import { mkdir, writeFile } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { startStreamServer } from '../../serve-stream.js'; + +test('measure the same close route with cold and warm page caches', async ({ page }) => { + const folder = process.env.PERF_MESH_PROFILE_MODEL; + test.skip(!folder, 'Set PERF_MESH_PROFILE_MODEL to a prepared RVT package.'); + const { server, url } = await startStreamServer(folder); + try { + await page.addInitScript((nativePixels) => { + let samples, queries = [], extension; + const reset = () => (samples = { fetch: [], networkBytes: 0, prepare: [], draw: [], upload: [], uploadBytes: 0, gpu: [] }); + reset(); + const original = WebGL2RenderingContext.prototype.bufferData; + WebGL2RenderingContext.prototype.bufferData = function (...args) { + const now = performance.now(); + original.apply(this, args); + samples.upload.push(performance.now() - now); + samples.uploadBytes += typeof args[1] === 'number' ? args[1] : (args[1]?.byteLength ?? 0); + }; + window.IOVIEWER_MESH_PROFILE = { + nativePixels, + reset, read: () => ({ ...samples, gpuTimer: !!extension }), + fetch: (ms, bytes) => { samples.fetch.push(ms); samples.networkBytes += bytes; }, + prepare: (ms) => samples.prepare.push(ms), + draw: (gl, draw) => { + extension ??= gl.getExtension('EXT_disjoint_timer_query_webgl2') ?? false; + if (extension) { + const disjoint = gl.getParameter(extension.GPU_DISJOINT_EXT); + queries = queries.filter(([query, output]) => { + if (!disjoint && !gl.getQueryParameter(query, gl.QUERY_RESULT_AVAILABLE)) return true; + if (!disjoint) output.push(gl.getQueryParameter(query, gl.QUERY_RESULT) / 1e6); + gl.deleteQuery(query); + return false; + }); + } + const query = extension && queries.length < 8 ? gl.createQuery() : null; + if (query) gl.beginQuery(extension.TIME_ELAPSED_EXT, query); + const now = performance.now(); + draw(); + samples.draw.push(performance.now() - now); + if (query) { gl.endQuery(extension.TIME_ELAPSED_EXT); queries.push([query, samples.gpu]); } + }, + }; + }, process.env.PERF_MESH_NATIVE_PIXELS === '1'); + await page.goto(url); + await page.waitForFunction(() => Boolean(window.__ioviewerMeshLod)); + const report = await page.evaluate(async () => { + const api = window.__ioviewerMeshLod; + const prof = window.IOVIEWER_MESH_PROFILE; + await api.ready; + const { min, max } = api.manifest.focus ?? api.manifest; + const next = () => new Promise(requestAnimationFrame); + const pct = (values, p) => values.length ? [...values].sort((a, b) => a - b)[Math.ceil(p * values.length) - 1] : null; + const route = (k) => { + const target = min.map((n, i) => (n + max[i]) / 2); + target[2] = min[2] + (max[2] - min[2]) * (0.12 + k * 0.76); + api.controls.restoreViewCamera({ position: target.map((n, i) => n + [8, -11, 5][i]), target, up: [0, 0, 1] }); + }; + const run = async () => { + prof.reset(); + const before = api.stats(); + const times = [], triangles = [], threshold = [], raster = []; + const start = await next(); + let last = start; + route(0); + while (last - start < 15_000) { + const t = await next(); + times.push(t - last); + const stats = api.stats(); + triangles.push(stats.triangles); + threshold.push(stats.threshold); + raster.push(stats.rasterScale); + route(Math.min(1, (t - start) / 15_000)); + last = t; + } + const trace = prof.read(), after = api.stats(); + return { p95: pct(times, 0.95), p99: pct(times, 0.99), max: Math.max(...times), trianglesP50: pct(triangles, 0.5), + thresholdP95: pct(threshold, 0.95), rasterP05: pct(raster, 0.05), requests: after.requested - before.requested, evictions: after.evictions - before.evictions, + networkMiB: trace.networkBytes / 1048576, fetchP95: pct(trace.fetch, 0.95), prepareP95: pct(trace.prepare, 0.95), + submissionP95: pct(trace.draw, 0.95), uploadCalls: trace.upload.length, uploadMiB: trace.uploadBytes / 1048576, + uploadCallP95: pct(trace.upload, 0.95), gpuP95: pct(trace.gpu, 0.95), gpuSamples: trace.gpu.length, gpuTimer: trace.gpuTimer }; + }; + const cold = await run(); + await new Promise((resolve) => setTimeout(resolve, 400)); + const warm = await run(); + prof.holdPages = true; + const deadline = performance.now() + 10_000; + while (api.stats().pending && performance.now() < deadline) await next(); + if (api.stats().pending) throw new Error('Page requests did not finish.'); + return { cold, warm, residentOnly: await run(), end: api.stats() }; + }); + const out = process.env.PERF_OUT ?? path.join(os.tmpdir(), 'ioviewer-perf'); + await mkdir(out, { recursive: true }); + await writeFile(path.join(out, `mesh-profile-${process.env.PERF_LABEL ?? 'default'}.json`), JSON.stringify(report, null, 2)); + console.log(JSON.stringify(report)); + expect(report.end.failures).toEqual([]); + expect(report.cold.networkMiB).toBeGreaterThan(0); + expect(report.residentOnly.requests).toBe(0); + expect(report.residentOnly.uploadMiB).toBe(0); + } finally { + await page.close(); + await new Promise((resolve) => server.close(resolve)); + } +}); diff --git a/src/IOViewer/Viewer/test/perf/mesh-tools.perf.js b/src/IOViewer/Viewer/test/perf/mesh-tools.perf.js new file mode 100644 index 0000000..a921447 --- /dev/null +++ b/src/IOViewer/Viewer/test/perf/mesh-tools.perf.js @@ -0,0 +1,208 @@ +import { expect, test } from '@playwright/test'; +import { mkdtemp, open, readFile, rm, rmdir, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { Vector3 } from 'three'; +import { startStreamServer } from '../../serve-stream.js'; +import { MESH_FORMAT, sizeOfPage, viewsOfPage } from '../../src/stream/meshPages.js'; + +test('the section plane cuts both sides of a rendered cluster seam', async ({ page }) => { + const folder = await mkdtemp(join(tmpdir(), 'ioviewer-section-')); + const manifestPath = join(folder, 'manifest.json'), dataPath = join(folder, 'meshes.bin'); + let server; + try { + const nodes = [0, 1].map((x) => ({ + min: [x, 0, 0], max: [x + 1, 1, 0], offset: 0, vertices: 4, indices: 6, opaque: 6, error: 0, children: [], + })); + const size = sizeOfPage(nodes[0]); + nodes[1].offset = size; + const pages = nodes.map((node, x) => { + const buffer = new ArrayBuffer(size); + const view = viewsOfPage(buffer, node); + view.position.set([x, 0, 0, x + 1, 0, 0, x, 1, 0, x + 1, 1, 0]); + view.normal.set([0, 0, 32767, 0, 0, 32767, 0, 0, 32767, 0, 0, 32767]); + view.index.set([0, 1, 2, 1, 3, 2]); + view.color.fill(255); + return Buffer.from(buffer); + }); + await writeFile(dataPath, Buffer.concat(pages)); + await writeFile(manifestPath, JSON.stringify({ + format: MESH_FORMAT, min: [0, 0, 0], max: [2, 1, 0], origin: [0, 0, 0], triangles: 4, bytes: size * 2, pages: nodes, roots: [0, 1], + })); + const io = await startStreamServer(folder); + server = io.server; + await page.addInitScript(() => { + window.IOVIEWER_MESH_PROFILE = { + fetch() {}, prepare() {}, + draw(gl, draw) { + draw(); + if (!window.readSectionPixels) return; + const camera = window.__ioviewerMeshLod.controls.camera; + const pixel = new Uint8Array(4); + const samples = [0.75, 1.25].flatMap((x) => [0.3, 0.7].map((y) => { + const p = camera.position.clone().set(x, y, 0).project(camera); + gl.readPixels(Math.floor((p.x + 1) * gl.drawingBufferWidth / 2), Math.floor((p.y + 1) * gl.drawingBufferHeight / 2), + 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel); + return pixel[0] > 128; + })); + window.readSectionPixels(samples); + window.readSectionPixels = null; + }, + }; + }); + await page.goto(io.url); + await page.waitForFunction(() => Boolean(window.__ioviewerMeshLod)); + const colors = () => page.evaluate(() => new Promise((resolve) => { + window.readSectionPixels = resolve; + window.__ioviewerMeshLod.controls.restoreViewCamera({ position: [1, 0.5, 2], target: [1, 0.5, 0], up: [0, 1, 0] }); + })); + expect(await colors()).toEqual([true, true, true, true]); + await page.locator('[data-tool=distance]').click(); + const points = await page.evaluate(() => { + const camera = window.__ioviewerMeshLod.controls.camera; + const rect = document.querySelector('#ioviewer-canvas').getBoundingClientRect(); + return [0.75, 1.25].map((x) => { + const p = camera.position.clone().set(x, 0.3, 0).project(camera); + return [rect.left + (p.x + 1) * rect.width / 2, rect.top + (1 - p.y) * rect.height / 2]; + }); + }); + await page.mouse.click(...points[0]); + await expect.poll(() => page.evaluate(() => window.__ioviewerMeshLod.measure.points.length)).toBe(1); + await page.mouse.click(...points[1]); + await expect(page.locator('.ioviewer-measure-label')).toHaveText(/0[.,]50\s/); + await page.locator('[data-tool=distance]').click(); + await page.locator('.ioviewer-rail-button[data-panel=sections]').click(); + const sections = page.locator('.ioviewer-side-panel[data-panel=sections]'); + await sections.getByRole('button', { name: /плоскости|planes/i, exact: true }).click(); + await sections.getByRole('button', { name: 'Y', exact: true }).click(); + await sections.locator('.ioviewer-section-row > .ioviewer-text-button').click(); + await page.evaluate(() => window.__ioviewerMeshLod.sections.setGizmoVisible(false)); + expect(await colors()).toEqual([true, false, true, false]); + await sections.locator('.ioviewer-section-head button[aria-pressed]').click(); + expect(await colors()).toEqual([false, true, false, true]); + + await page.locator('[data-tool=projection]').click(); + expect(await page.evaluate(() => window.__ioviewerMeshLod.controls.camera.isOrthographicCamera)).toBe(true); + await page.evaluate(() => { + const { sections } = window.__ioviewerMeshLod; + const box = sections.modelBox.clone(); + box.min.set(0.5, 0.5, -0.1); + box.max.set(1.5, 1, 0.1); + sections.setBox(box, Math.PI / 12); + }); + expect(await colors()).toEqual([false, true, false, true]); + await sections.locator('[data-value=cutInside]').click(); + expect(await colors()).toEqual([true, false, true, false]); + } finally { + await page.close(); + if (server) await new Promise((resolve) => server.close(resolve)); + await Promise.all([dataPath, manifestPath].map((file) => rm(file, { force: true }))); + await rmdir(folder); + } +}); + +test('select a real original element and keep its properties while changing detail', async ({ page }) => { + const folder = process.env.PERF_MESH_TOOLS_MODEL; + test.skip(!folder, 'Set PERF_MESH_TOOLS_MODEL to an annotated IFC or RVT package.'); + const manifest = JSON.parse(await readFile(join(folder, 'manifest.json'))); + const leaves = manifest.pages.filter((node) => node.pick); + expect(leaves.length).toBeGreaterThan(1); + const candidates = []; + const file = await open(join(folder, 'meshes.bin')); + try { + for (let sample = 1; sample <= 12; sample++) { + const node = leaves[Math.floor(leaves.length * sample / 13)]; + const size = sizeOfPage(node); + const buffer = new ArrayBuffer(size); + expect((await file.read(new Uint8Array(buffer), 0, size, node.offset)).bytesRead).toBe(size); + const { position, index, color, tags } = viewsOfPage(buffer, node); + for (let i = 0; i < index.length; i += 3) { + const element = manifest.elements[tags[i / 3]]; + const [x, y, z] = index.slice(i, i + 3); + if (!element.size || [x, y, z].some((v) => color[v * 4 + 3] !== 255)) continue; + const a = new Vector3().fromArray(position, x * 3); + const b = new Vector3().fromArray(position, y * 3); + const c = new Vector3().fromArray(position, z * 3); + const normal = b.clone().sub(a).cross(c.clone().sub(a)); + if (normal.lengthSq() < 1e-5) continue; + normal.normalize(); + const target = a.add(b).add(c).divideScalar(3); + if (target.z <= (manifest.focus ?? manifest).min[2]) continue; + const camera = { target: target.toArray(), position: target.addScaledVector(normal, 0.2).toArray(), + up: Math.abs(normal.z) > 0.9 ? [0, 1, 0] : [0, 0, 1] }; + candidates.push({ camera, id: element.id, index: tags[i / 3] }); + break; + } + } + } finally { + await file.close(); + } + expect(candidates.length).toBeGreaterThan(0); + const { server, url } = await startStreamServer(folder); + const errors = []; + page.on('pageerror', (error) => errors.push(error.message)); + try { + await page.goto(url); + await page.waitForFunction(() => Boolean(window.__ioviewerMeshLod)); + await page.evaluate(() => window.__ioviewerMeshLod.ready); + const canvas = await page.locator('#ioviewer-canvas').boundingBox(); + const click = (button = 'left') => page.mouse.click(canvas.x + canvas.width / 2, canvas.y + canvas.height / 2, { button }); + const selected = () => page.evaluate(() => [...window.__ioviewerMeshLod.selection.values()][0] ?? null); + const panel = page.locator('#ioviewer-properties'); + const note = page.locator('#stream-pick-status'); + let hit; + for (const candidate of candidates) { + await page.keyboard.press('Escape'); + await page.evaluate((camera) => window.__ioviewerMeshLod.controls.restoreViewCamera(camera), candidate.camera); + await click(); + await expect(note).toBeHidden({ timeout: 15_000 }); + if (await selected() === candidate.index) { hit = candidate; break; } + } + expect(hit).toBeDefined(); + await expect(panel).toBeVisible(); + await expect(panel.getByText(hit.id, { exact: true })).toBeVisible(); + await expect.poll(() => panel.locator('section').count()).toBeGreaterThan(1); + const propertyGroups = await panel.locator('section').count(); + await click('right'); + await expect(page.getByRole('menu').locator('[data-item=copyId]')).toBeVisible(); + await page.keyboard.press('Escape'); + await page.locator('[data-tool=fit]').click(); + expect(await selected()).toBe(hit.index); + await page.locator('.ioviewer-rail-button[data-panel=model]').click(); + const model = page.locator('.ioviewer-side-panel[data-panel=model]'); + await model.getByRole('searchbox').fill(hit.id); + const row = model.locator('.tree-element[aria-selected=true]'); + await expect(row).toBeVisible(); + if (manifest.elements[hit.index].name) await expect(row).toContainText(manifest.elements[hit.index].name); + const rowNumber = await row.getAttribute('data-row'); + await page.locator('#ioviewer-properties .ioviewer-properties-close').click(); + const propertyResponse = page.waitForResponse((response) => new URL(response.url()).pathname === `/elements/${hit.index}`); + await model.locator(`.tree-element[data-row="${rowNumber}"]`).click(); + expect(await selected()).toBe(hit.index); + expect((await propertyResponse).ok()).toBe(true); + await page.evaluate((camera) => window.__ioviewerMeshLod.controls.restoreViewCamera(camera), hit.camera); + await click('right'); + await page.getByRole('menu').locator('[data-item=hide]').click(); + await click(); + await expect(note).toBeHidden({ timeout: 15_000 }); + expect(await selected()).not.toBe(hit.index); + await page.keyboard.press('Shift+H'); + await click(); + await expect(note).toBeHidden({ timeout: 15_000 }); + expect(await selected()).toBe(hit.index); + await page.locator('[data-tool=plane]').click(); + await page.locator('.ioviewer-section-plane input[type=range]').evaluate((input) => { + input.value = input.min; + input.dispatchEvent(new Event('input')); + }); + await click(); + await expect(note).toBeHidden({ timeout: 15_000 }); + expect(await selected()).toBeNull(); + await expect(panel).toBeHidden(); + expect(errors).toEqual([]); + console.log(JSON.stringify({ elements: manifest.elements.length, propertyGroups })); + } finally { + await page.close(); + await new Promise((resolve) => server.close(resolve)); + } +}); diff --git a/src/IOViewer/Viewer/test/perf/stream.perf.js b/src/IOViewer/Viewer/test/perf/stream.perf.js new file mode 100644 index 0000000..65f0943 --- /dev/null +++ b/src/IOViewer/Viewer/test/perf/stream.perf.js @@ -0,0 +1,99 @@ +import { expect, test } from '@playwright/test'; +import { mkdir, writeFile } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { startStreamServer } from '../../serve-stream.js'; + +const folder = process.env.PERF_STREAM_MODEL; + +test('stream route across the 15 GB model', async ({ page }) => { + test.skip(!folder, 'Set PERF_STREAM_MODEL to the prepared fixture directory.'); + const { server, url } = await startStreamServer(folder); + const pageErrors = []; + page.on('pageerror', (error) => pageErrors.push(error.message)); + try { + await page.goto(url); + await page.waitForFunction(() => Boolean(window.__ioviewerStream)); + const overview = await page.evaluate(async () => { + const api = window.__ioviewerStream; + const gl = document.querySelector('canvas').getContext('webgl2'); + const extension = gl.getExtension('WEBGL_debug_renderer_info'); + const readyMs = await api.ready; + return { readyMs, renderer: gl.getParameter(extension?.UNMASKED_RENDERER_WEBGL ?? gl.RENDERER), ...api.stats() }; + }); + expect(overview.tiles).toBe(171); + expect(overview.requested).toBe(0); + expect(overview.triangles).toBe(171 * 12); + + const result = await page.evaluate(async () => { + const api = window.__ioviewerStream; + const nextFrame = () => new Promise((resolve) => requestAnimationFrame(resolve)); + const row = api.manifest.tiles.filter((tile) => tile.y === 6); + const position = (tile) => tile.rtcOffset.map((n, i) => n - api.origin[i]); + const cameraAt = (target, angle = 0) => { + const offset = [-45 * Math.cos(angle) - 55 * Math.sin(angle), -55 * Math.cos(angle) + 45 * Math.sin(angle), 100]; + api.controls.restoreViewCamera({ position: target.map((n, i) => n + offset[i]), target, up: [0, 0, 1] }); + }; + const waitDetail = async (tile) => { + const start = performance.now(); + let now = start; + while (now - start < 15_000) { + const state = api.stats(); + if (state.failures.length) throw new Error(JSON.stringify(state.failures)); + if (state.readyTiles.includes(tile.file)) return now - start; + now = await nextFrame(); + } + throw new Error(`Timed out waiting for ${tile.file}.`); + }; + const a = position(row[0]), b = position(row.at(-1)); + cameraAt(a); + const firstDetailMs = await waitDetail(row[0]); + const routeMs = 30_000; + const start = await nextFrame(); + let last = start, coverage = 0, peakVisibleTriangles = 0, maxMeshBytes = 0, maxV8Heap = 0; + const intervals = []; + const detailedDuringRoute = new Set(); + while (last - start < routeMs) { + const now = await nextFrame(); + const fraction = Math.min(1, (now - start) / routeMs); + const target = a.map((n, i) => n + fraction * (b[i] - n)); + cameraAt(target, 0.22 * Math.sin(4 * Math.PI * fraction)); + const state = api.stats(); + const elapsed = now - last; + if (state.readyTiles.includes(state.wanted[0])) { + coverage += elapsed; + detailedDuringRoute.add(state.wanted[0]); + } + peakVisibleTriangles = Math.max(peakVisibleTriangles, state.triangles); + maxMeshBytes = Math.max(maxMeshBytes, state.bytes); + maxV8Heap = Math.max(maxV8Heap, performance.memory?.usedJSHeapSize ?? 0); + intervals.push(elapsed); + last = now; + } + intervals.sort((a, b) => a - b); + const percentile = (p) => intervals[Math.ceil(p * intervals.length) - 1]; + const far = api.manifest.tiles.at(-1); + cameraAt(position(far)); + const farDetailMs = await waitDetail(far); + return { + firstDetailMs, farDetailMs, routeMetres: Math.hypot(...a.map((n, i) => b[i] - n)), routeMs, + samples: intervals.length, p50Ms: percentile(0.5), p95Ms: percentile(0.95), p99Ms: percentile(0.99), maxMs: intervals.at(-1), + detailedShare: coverage / (last - start), detailedDuringRoute: [...detailedDuringRoute], peakVisibleTriangles, + maxMeshBytes, maxV8Heap, end: api.stats(), + }; + }); + expect(result.end.failures).toEqual([]); + expect(pageErrors).toEqual([]); + expect(result.end.evicted).toBeGreaterThan(0); + expect(result.detailedDuringRoute.length).toBeGreaterThan(5); + expect(result.end.peak).toBeLessThanOrEqual(result.end.budget); + const out = process.env.PERF_OUT ?? path.join(os.tmpdir(), 'ioviewer-perf'); + await mkdir(out, { recursive: true }); + const report = { overview, ...result }; + await writeFile(path.join(out, `stream-${process.env.PERF_LABEL || process.env.PERF_GPU || 'default'}.json`), JSON.stringify(report, null, 2)); + console.log(JSON.stringify(report)); + } finally { + await page.close(); + await new Promise((resolve) => server.close(resolve)); + } +}); diff --git a/src/IOViewer/Viewer/test/unit/lod.test.js b/src/IOViewer/Viewer/test/unit/lod.test.js new file mode 100644 index 0000000..b44e913 --- /dev/null +++ b/src/IOViewer/Viewer/test/unit/lod.test.js @@ -0,0 +1,35 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { CLUSTER_FORMAT, detailInputBytes, detailMeshBytes, FACES, validateClusters, VERTICES } from '../../src/stream/clusters.js'; +import { chooseLevel, LOD_ERROR, makeTemplates } from '../../src/stream/lodShapes.js'; + +test('nested levels keep every vessel and apply hysteresis at each screen-error threshold', () => { + const meshes = makeTemplates(); + assert.deepEqual(meshes.map((g) => g.index.count / 3), [12, 76, 540]); + for (const [level, error] of LOD_ERROR.entries()) { + assert.equal(chooseLevel(1.24 / error, level), level); + assert.equal(chooseLevel(1.26 / error, level), level + 1); + assert.equal(chooseLevel(0.96 / error, level + 1), level + 1); + assert.equal(chooseLevel(0.94 / error, level + 1), level); + } + // An intermediate point along the first edge starts at the coarse edge midpoint during geomorphing. + const from = meshes[1].getAttribute('previousPosition'); + assert(Math.abs(from.getX(1) - 0.34) < 1e-6); + assert(Math.abs(from.getY(1) - 0.34) < 1e-6); +}); + +test('fine pages reconstruct the original index template and enforce contiguous byte ranges', () => { + assert.equal(FACES.length / 3, 1084); + assert(FACES.every((n) => n < VERTICES)); + assert(detailInputBytes(64) <= 408 * 1024); + assert.equal(detailMeshBytes(64), 834_048); + const box = { min: [0, 0, 0], max: [2, 2, 2] }; + const node = { ...box, anchor: box.min, id: 0, first: 0, offset: 0, count: 1, counts: [1, 0, 0] }; + const root = { ...box, x: 0, y: 0, first: 0, count: 1, children: [node] }; + const manifest = { ...box, format: CLUSTER_FORMAT, palette: [box.min, [1, 0, 0], [0, 1, 0]], origin: box.min, + elements: 1, triangles: 1084, detailBytes: detailInputBytes(1), roots: [root] }; + assert.equal(validateClusters(manifest), manifest); + for (const patch of [{ offset: 1 }, { count: 0 }, { id: 2 }, { counts: [65, 0, 0] }]) { + assert.throws(() => validateClusters({ ...manifest, roots: [{ ...root, children: [{ ...node, ...patch }] }] }), /Invalid cluster/); + } +}); diff --git a/src/IOViewer/Viewer/test/unit/meshPages.test.js b/src/IOViewer/Viewer/test/unit/meshPages.test.js new file mode 100644 index 0000000..eac8c95 --- /dev/null +++ b/src/IOViewer/Viewer/test/unit/meshPages.test.js @@ -0,0 +1,99 @@ +import assert from 'node:assert/strict'; +import { mkdtemp, readFile, rm, rmdir, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import test from 'node:test'; +import { buildMeshPages, focusBounds } from '../../build-mesh-pages.js'; +import { MESH_FORMAT, pageBytes, validateMeshPages, viewsOfPage } from '../../src/stream/meshPages.js'; + +const bounds = { min: [0, 0, 0], max: [1, 1, 0] }; + +test('a cluster tree covers every leaf exactly once and bounds its error and byte ranges', () => { + const page = { ...bounds, offset: 0, vertices: 3, indices: 3, opaque: 3, error: 0, children: [] }; + const step = pageBytes(3, 3); + const manifest = { ...bounds, format: MESH_FORMAT, origin: [0, 0, 0], triangles: 2, bytes: 3 * step, + pages: [page, { ...page, offset: step }, { ...page, offset: 2 * step, children: [0, 1], error: 0.01 }], roots: [2] }; + assert.equal(validateMeshPages(manifest), manifest); + for (const patch of [{ children: [1, 1] }, { offset: 1 }, { children: [2] }, { max: [0.5, 0.5, 0] }]) { + assert.throws(() => validateMeshPages({ ...manifest, pages: [...manifest.pages.slice(0, 2), { ...manifest.pages[2], ...patch }] })); + } + assert.throws(() => validateMeshPages({ ...manifest, roots: [0, 2] })); +}); + +test('the initial focus ignores a remote record with less than one percent of the triangles', () => { + const outer = { min: [0, 0, 0], max: [1000, 3, 0] }; + const focus = focusBounds([{ ...bounds, indices: 1000 }, { min: [1, 1, 0], max: [2, 2, 0], indices: 1000 }, + { min: [999, 0, 0], max: [1000, 3, 0], indices: 3 }], outer); + assert.deepEqual(focus, { min: [0.5, 0.5, 0], max: [1.5, 1.5, 0] }); +}); + +test('a native geometry record produces the same indexed triangle and preserves alpha', async () => { + const folder = await mkdtemp(join(tmpdir(), 'ioviewer-mesh-pages-')); + const output = join(folder, 'output'), source = join(folder, 'one.ivmesh'); + try { + const bytes = Buffer.alloc(116); + bytes.write('IMS1'); + bytes.writeFloatLE(1, 40); + bytes.writeFloatLE(1, 44); + bytes.writeUInt32LE(3, 52); + bytes.writeUInt32LE(3, 56); + bytes.set([255, 0, 0, 128], 60); + [0, 0, 0, 1, 0, 0, 0, 1, 0].forEach((n, i) => bytes.writeFloatLE(n, 68 + i * 4)); + [0, 1, 2].forEach((n, i) => bytes.writeUInt32LE(n, 104 + i * 4)); + await writeFile(source, bytes); + const manifest = await buildMeshPages(source, output); + const [page] = manifest.pages; + assert.equal(manifest.triangles, 1); + assert.equal(page.opaque, 0); + const packed = await readFile(join(output, 'meshes.bin')); + const mesh = viewsOfPage(new Uint8Array(packed).buffer, page); + assert.deepEqual([...mesh.index], [0, 1, 2]); + assert.deepEqual([...mesh.position], [0, 0, 0, 1, 0, 0, 0, 1, 0]); + assert.deepEqual([...mesh.normal], [0, 0, 32767, 0, 0, 32767, 0, 0, 32767]); + assert.deepEqual([...mesh.color], [255, 0, 0, 128, 255, 0, 0, 128, 255, 0, 0, 128]); + } finally { + await Promise.all([source, join(output, 'manifest.json'), join(output, 'meshes.bin')].map((file) => rm(file, { force: true }))); + await rmdir(output).catch((error) => { if (error.code !== 'ENOENT') throw error; }); + await rmdir(folder); + } +}); + +test('IMS2 preserves exact IDs and property ranges and also packs geometry alone', async () => { + const folder = await mkdtemp(join(tmpdir(), 'ioviewer-bim-pages-')); + const source = join(folder, 'one.ivmesh'), review = join(folder, 'review'), geometry = join(folder, 'geometry'); + const property = Buffer.from('{"id":"9007199254740993","name":"Slab","category":"Floors","properties":{"Identity":{"Type":"Slab"}}}'); + try { + const end = 132; + const input = Buffer.alloc(end + 12 + property.length); + input.write('IMS2'); + input.writeBigInt64LE(BigInt(end), 28); + input.writeFloatLE(1, 48); + input.writeFloatLE(1, 52); + input.writeUInt32LE(3, 60); + input.writeUInt32LE(3, 64); + input.set([255, 255, 255, 255], 68); + input.writeBigInt64LE(9007199254740993n, 76); + [0, 0, 0, 1, 0, 0, 0, 1, 0].forEach((n, i) => input.writeFloatLE(n, 84 + i * 4)); + [0, 1, 2].forEach((n, i) => input.writeUInt32LE(n, 120 + i * 4)); + input.writeBigInt64LE(9007199254740993n, end); + input.writeUInt32LE(property.length, end + 8); + property.copy(input, end + 12); + await writeFile(source, input); + const annotated = await buildMeshPages(source, review); + assert.deepEqual(annotated.elements, [{ ...bounds, id: '9007199254740993', name: 'Slab', category: 'Floors', offset: 0, size: property.length }]); + assert.deepEqual(await readFile(join(review, 'elements.bin')), property); + const shape = await buildMeshPages(source, geometry, false); + assert.equal(shape.elements, undefined); + const detailed = viewsOfPage(Uint8Array.from(await readFile(join(review, 'meshes.bin'))).buffer, annotated.pages[0]); + const bare = viewsOfPage(Uint8Array.from(await readFile(join(geometry, 'meshes.bin'))).buffer, shape.pages[0]); + assert.deepEqual([...detailed.tags], [0]); + assert.deepEqual(detailed.position, bare.position); + assert.deepEqual(detailed.index, bare.index); + } finally { + await Promise.all([source, join(review, 'elements.bin'), ...[review, geometry].flatMap((dir) => [ + join(dir, 'manifest.json'), join(dir, 'meshes.bin'), + ])].map((file) => rm(file, { force: true }))); + for (const dir of [review, geometry]) await rmdir(dir).catch((error) => { if (error.code !== 'ENOENT') throw error; }); + await rmdir(folder); + } +}); diff --git a/src/IOViewer/Viewer/test/unit/meshTools.test.js b/src/IOViewer/Viewer/test/unit/meshTools.test.js new file mode 100644 index 0000000..c98b7e8 --- /dev/null +++ b/src/IOViewer/Viewer/test/unit/meshTools.test.js @@ -0,0 +1,40 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import * as THREE from 'three'; +import { pickMeshSurface } from '../../src/stream/meshTools.js'; +import { Sections } from '../../src/tools/sections.js'; + +test('exact selection traverses both leaves and clips them with one world-space plane', async () => { + const vec = (x, y, z) => new THREE.Vector3(x, y, z); + const bounds = new THREE.Box3(vec(0, 0, 0), vec(2, 1, 0)); + const nodes = [ + { id: 0, box: new THREE.Box3(vec(0, 0, 0), vec(1, 1, 0)), children: [], pick: true }, + { id: 1, box: new THREE.Box3(vec(1, 0, 0), vec(2, 1, 0)), shift: [1, 0, 0], children: [], pick: true }, + { id: 2, box: bounds, children: [0, 1] }, + ]; + const sections = new Sections({ setClipping() {} }, bounds); + const page = async (node) => ({ + position: [0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0], + color: new Uint8Array(16).fill(255), + index: [0, 1, 2, 1, 3, 2], + tags: [node.id, node.id], + }); + const surface = (x, y, signal) => pickMeshSurface(new THREE.Ray(vec(x, y, 1), vec(0, 0, -1)), + [nodes[2]], nodes, page, sections, signal); + const pick = async (...args) => (await surface(...args))?.element ?? null; + assert.deepEqual((await surface(1.01, 0.25)).point, vec(1.01, 0.25, 0)); + assert.equal(await pick(0.99, 0.25), 0); + assert.equal(await pick(1.01, 0.25), 1); + sections.addPlane('y'); + assert.equal(await pick(0.99, 0.25), 0); + assert.equal(await pick(1.01, 0.25), 1); + assert.equal(await pick(0.99, 0.75), null); + assert.equal(await pick(1.01, 0.75), null); + sections.setBox(new THREE.Box3(vec(0.9, 0.1, -0.1), vec(1.1, 0.4, 0.1))); + assert.equal(await pick(1.01, 0.25), 1); + assert.equal(await pick(1.01, 0.75), null); + sections.setBoxMode('cutInside'); + assert.equal(await pick(1.01, 0.25), null); + assert.equal(await pick(1.01, 0.75), 1); + await assert.rejects(pick(0.99, 0.25, AbortSignal.abort()), { name: 'AbortError' }); +}); diff --git a/src/IOViewer/Viewer/test/unit/stream.test.js b/src/IOViewer/Viewer/test/unit/stream.test.js new file mode 100644 index 0000000..5d5f813 --- /dev/null +++ b/src/IOViewer/Viewer/test/unit/stream.test.js @@ -0,0 +1,99 @@ +import assert from 'node:assert/strict'; +import { mkdtemp, rm, rmdir, writeFile } from 'node:fs/promises'; +import { request } from 'node:http'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import test from 'node:test'; +import { startStreamServer } from '../../serve-stream.js'; +import { MAX_TILE_INPUT, validateManifest } from '../../src/stream/manifest.js'; +import { prepareTile, readTile } from '../../src/stream/tile.js'; + +const tile = { + file: 'tile-0001.html', x: 0, y: 0, bytes: 1, firstElementId: 1, elements: 1, triangles: 1, + rtcOffset: [1, 2, 3], min: [0, 0, 0], max: [2, 4, 6], +}; + +test('stream manifest fixes file names, world bounds, per-tile size and aggregate totals', () => { + const manifest = { + format: 'ioviewer-synthetic-tiles-1', unit: 'metre', upAxis: 'Z', min: tile.min, max: tile.max, + tiles: [tile], totalBytes: 1, elements: 1, triangles: 1, + }; + assert.equal(validateManifest(manifest), manifest); + for (const patch of [{ file: '../tile-0001.html' }, { bytes: MAX_TILE_INPUT + 1 }, { firstElementId: 2 }, { max: [3, 4, 6] }]) { + assert.throws(() => validateManifest({ ...manifest, tiles: [{ ...tile, ...patch }] }), /Invalid or oversized tile/); + } + assert.throws(() => validateManifest({ ...manifest, totalBytes: 2 }), /Invalid tile manifest totals/); +}); + +function triangle({ badIndex = false } = {}) { + const bytes = Buffer.alloc(88); + new Uint16Array(bytes.buffer, 0, 9).set([0, 0, 0, 2, 0, 0, 0, 2, 0]); + new Uint16Array(bytes.buffer, 20, 3).set([0, 1, badIndex ? 3 : 2]); + new Float32Array(bytes.buffer, 40, 12).set([-1, 0, 0, 0, 1, 0, 0, 0, 1, 2, 3, 4]); + const view = (o, n, t) => ({ o, n, t }); + const meta = { + format: 3, rtcOffset: tile.rtcOffset, elements: [{ id: 1 }], materials: [{ color: [1, 0, 0], opacity: 1 }], + geometries: [{ bbox: { min: [0, 0, 0], max: [1, 1, 0] }, positions: view(0, 9, 'u16'), + q: { o: [0, 0, 0], s: 0.5 }, indices: view(20, 3, 'u16') }], + instances: { count: 1, geometry: view(28, 1, 'u32'), material: view(32, 1, 'u32'), element: view(36, 1, 'i32'), matrix: view(40, 12, 'f32') }, + }; + const html = Buffer.from(` +`); + return [html, { ...tile, bytes: html.length }]; +} + +test('tile preparation preserves quantized positions, mirrored winding and derived normals', () => { + const [html, entry] = triangle(); + const result = prepareTile(readTile(html, entry), entry); + assert.equal(result.bytes, 60); + assert.equal(result.batches.length, 1); + const batch = result.batches[0]; + assert.deepEqual([...batch.position], [2, 3, 4, 1, 3, 4, 2, 4, 4]); + assert.deepEqual([...batch.index], [0, 2, 1]); + assert.deepEqual([...batch.normal], [0, 0, 32767, 0, 0, 32767, 0, 0, 32767]); + assert.deepEqual(batch.min, [1, 3, 4]); + assert.deepEqual(batch.max, [2, 4, 4]); +}); + +test('tile preparation rejects truncated files, stale manifests and invalid indices', () => { + const [html, entry] = triangle({ badIndex: true }); + assert.throws(() => readTile(html.subarray(0, -1), entry), /Tile length changed/); + assert.throws(() => readTile(html, { ...entry, rtcOffset: [0, 0, 0] }), /metadata differs/); + assert.throws(() => prepareTile(readTile(html, entry), entry), /index is out of bounds/); +}); + +test('loopback server streams only declared tiles and reports a missing file', async () => { + const directory = await mkdtemp(join(tmpdir(), 'ioviewer-stream-test-')); + const [html, entry] = triangle(); + const file = join(directory, entry.file), manifest = join(directory, 'manifest.json'); + const hidden = join(directory, 'other.html'); + let server; + try { + await Promise.all([ + writeFile(file, html), writeFile(hidden, html), writeFile(manifest, JSON.stringify({ + format: 'ioviewer-synthetic-tiles-1', unit: 'metre', upAxis: 'Z', min: tile.min, max: tile.max, + tiles: [entry], totalBytes: html.length, elements: 1, triangles: 1, + })), + ]); + const running = await startStreamServer(directory); + server = running.server; + const url = `${running.url}tiles/${entry.file}`; + const response = await fetch(url); + assert.equal(response.headers.get('content-type'), 'application/octet-stream'); + assert.deepEqual(Buffer.from(await response.arrayBuffer()), html); + assert.equal((await fetch(`${running.url}tiles/other.html`)).status, 404); + const denied = await new Promise((resolve, reject) => { + request(url, { method: 'HEAD', headers: { Host: 'example.com' } }, (response) => { + response.resume(); + resolve(response.statusCode); + }).on('error', reject).end(); + }); + assert.equal(denied, 403); + await rm(file); + assert.equal((await fetch(url)).status, 500); + } finally { + if (server) await new Promise((resolve) => server.close(resolve)); + await Promise.all([file, manifest, hidden].map((p) => rm(p, { force: true }))); + await rmdir(directory); + } +}); diff --git a/tests/IOViewer.Tests/ClusterSourceTests.cs b/tests/IOViewer.Tests/ClusterSourceTests.cs new file mode 100644 index 0000000..0f1c5c8 --- /dev/null +++ b/tests/IOViewer.Tests/ClusterSourceTests.cs @@ -0,0 +1,76 @@ +using System.Text.Json; +using IOScene; +using IOViewer.Exporters; +using IOViewer.Model; +using Xunit; + +namespace IOViewer.Tests; + +public class ClusterSourceTests +{ + [Fact] + public void WritesRebasedMirroredGeometryAndPreservesMaterialAlpha() + { + const long elementId = 9_007_199_254_740_993; + var scene = new SceneDocument(); + scene.PropertySets.Add(new ScenePropertySet + { + Id = 1, Name = "Dimensions", + Properties = [new SceneProperty { Name = "Thickness", Value = SceneValue.FromText("300 mm") }], + }); + scene.Elements.Add(new SceneElement { Id = elementId, ModelId = 1, Name = "Slab", PropertySetIds = [1] }); + scene.Geometries.Add(new SceneGeometry + { + Id = 1, Vertices = [Vector3d.Zero, Vector3d.UnitX, Vector3d.UnitY], Indices = [0, 1, 2], + Normals = [Vector3d.UnitZ, Vector3d.UnitZ, Vector3d.UnitZ], + }); + scene.Instances.Add(new SceneInstance + { + GeometryId = 1, ElementId = elementId, Color = new RgbaColor(40, 80, 120, 160), + Transform = new(-Vector3d.UnitX, Vector3d.UnitY, Vector3d.UnitZ, new Vector3d(1_000_000, 0, 0)), + }); + var directory = Directory.CreateTempSubdirectory(); + var path = Path.Combine(directory.FullName, "model.ivmesh"); + try + { + var doc = new ViewerDocument(scene); + var options = new HtmlViewerOptions { Title = "Cluster review" }; + Assert.Equal(1, ClusterSourceWriter.Save(doc, path, options)); + Assert.Throws(() => ClusterSourceWriter.Save(doc, path, options)); + using var reader = new BinaryReader(File.OpenRead(path)); + Assert.Equal("IMS3"u8.ToArray(), reader.ReadBytes(4)); + Assert.Equal(999_999.5, reader.ReadDouble()); + Assert.Equal(0.5, reader.ReadDouble()); + Assert.Equal(0, reader.ReadDouble()); + long geometryEnd = reader.ReadInt64(); + Assert.Equal(new float[] { -0.5f, -0.5f, 0, 0.5f, 0.5f, 0 }, Enumerable.Range(0, 6).Select(_ => reader.ReadSingle())); + Assert.Equal(3, reader.ReadInt32()); + Assert.Equal(3, reader.ReadInt32()); + Assert.Equal(new byte[] { 40, 80, 120, 160 }, reader.ReadBytes(4)); + Assert.Equal(1, reader.ReadInt32()); + Assert.Equal(elementId, reader.ReadInt64()); + Assert.Equal(-1, reader.ReadInt32()); + Assert.Equal(0, reader.ReadInt32()); + Assert.Equal(new float[] { 0.5f, -0.5f, 0, 0.5f, 0.5f, 0, -0.5f, -0.5f, 0 }, Enumerable.Range(0, 9).Select(_ => reader.ReadSingle())); + Assert.Equal(new float[] { 0, 0, 1, 0, 0, 1, 0, 0, 1 }, Enumerable.Range(0, 9).Select(_ => reader.ReadSingle())); + Assert.Equal(0, reader.ReadInt32()); + Assert.Equal(1, reader.ReadInt32()); + Assert.Equal(2, reader.ReadInt32()); + Assert.Equal(geometryEnd, reader.BaseStream.Position); + using var review = JsonDocument.Parse(reader.ReadBytes(reader.ReadInt32())); + Assert.Equal("Cluster review", review.RootElement.GetProperty("title").GetString()); + Assert.Equal("9007199254740993", review.RootElement.GetProperty("elements")[0].GetProperty("id").GetString()); + Assert.Equal(elementId, reader.ReadInt64()); + using var element = JsonDocument.Parse(reader.ReadBytes(reader.ReadInt32())); + Assert.Equal("9007199254740993", element.RootElement.GetProperty("id").GetString()); + Assert.Equal("Slab", element.RootElement.GetProperty("name").GetString()); + Assert.Equal("300 mm", element.RootElement.GetProperty("properties").GetProperty("Dimensions").GetProperty("Thickness").GetString()); + Assert.Equal(reader.BaseStream.Length, reader.BaseStream.Position); + } + finally + { + File.Delete(path); + directory.Delete(); + } + } +} diff --git a/tools/SyntheticModel/TiledSyntheticModel/TiledSyntheticModel.cs b/tools/SyntheticModel/TiledSyntheticModel/TiledSyntheticModel.cs new file mode 100644 index 0000000..1eced0a --- /dev/null +++ b/tools/SyntheticModel/TiledSyntheticModel/TiledSyntheticModel.cs @@ -0,0 +1,148 @@ +#:project ../../../src/IOViewer/IOViewer.csproj +#:property TargetFramework=net10.0 +#:property PublishAot=false + +using System.Globalization; +using System.Text.Json; +using IOScene; +using IOViewer.Exporters; + +const long defaultBytes = 15_000_000_000; +const int columns = 40, levels = 4, tilesPerRow = 12; +const int elementsPerTile = columns * columns * levels; +const int rings = 17, sides = 32; +const int seed = 20261120; +const double tilePitch = 256, spacing = 6, levelPitch = 12; + +long target = defaultBytes; +if (args.Length is < 1 or > 2 || (args.Length == 2 && + (!long.TryParse(args[1], NumberStyles.None, CultureInfo.InvariantCulture, out target) || target < 1))) +{ + Console.Error.WriteLine("Usage: TiledSyntheticModel [target-bytes]"); + return 2; +} + +var output = Directory.CreateDirectory(args[0]); +if (output.EnumerateFileSystemInfos().Any()) +{ + Console.Error.WriteLine("The output directory must be empty."); + return 2; +} + +var indices = MakeIndices(); +double[] angles = Enumerable.Range(0, sides).Select(i => i * Math.Tau / sides).ToArray(); +double[] cos = angles.Select(Math.Cos).ToArray(), sin = angles.Select(Math.Sin).ToArray(); +double[] profile = [0.68, 0.91, 1.0, 1.07, 1.0, 1.0, 1.0, 1.0, 1.05, 1.0, 1.0, 1.0, 1.0, 1.07, 1.0, 0.91, 0.68]; +var random = new Random(seed); +var tiles = new List(); +long totalBytes = 0, elements = 0, triangles = 0; +var bounds = BoundingBox3d.Empty; +// Estimate the first tile and use its actual bytes per element to size the final tile. +double bytesPerElement = 14_000; +while (totalBytes < target) +{ + int count = (int)Math.Clamp(Math.Ceiling((target - totalBytes) / bytesPerElement), 1, elementsPerTile); + int tile = tiles.Count; + int x = tile % tilesPerRow, y = tile / tilesPerRow; + string file = FormattableString.Invariant($"tile-{tile + 1:D4}.html"); + string title = FormattableString.Invariant($"Synthetic industrial plant ({x + 1}, {y + 1})"); + var scene = Build(count, x, y, elements + 1, title); + var box = scene.ComputeBounds(); + long bytes; + using (var stream = new FileStream(Path.Combine(output.FullName, file), FileMode.CreateNew, FileAccess.Write)) + { + HtmlViewerExporter.Export(scene, stream, new HtmlViewerOptions { Title = title }); + bytes = stream.Length; + } + + long tileTriangles = (long)count * (indices.Length / 3); + tiles.Add(new Tile(file, x, y, bytes, elements + 1, count, tileTriangles, Point(box.Center), Point(box.Min), Point(box.Max))); + bounds = bounds.Encapsulate(box); + totalBytes += bytes; + triangles += tileTriangles; + elements += count; + bytesPerElement = (double)bytes / count; + Console.WriteLine(FormattableString.Invariant($"{file} {bytes} bytes; total {totalBytes} / {target}")); +} + +using (var index = new FileStream(Path.Combine(output.FullName, "index.html"), FileMode.CreateNew, FileAccess.Write)) +using (var html = new StreamWriter(index)) +{ + html.WriteLine("Synthetic industrial plant"); + html.WriteLine("

Synthetic industrial plant

Open an area in IOViewer. Model manifest

    "); + foreach (var tile in tiles) + html.WriteLine(FormattableString.Invariant($"
  1. Area {tile.X + 1}, {tile.Y + 1} ({tile.Elements} elements)
  2. ")); + html.WriteLine("
"); +} + +using (var manifest = new FileStream(Path.Combine(output.FullName, "manifest.json"), FileMode.CreateNew, FileAccess.Write)) +{ + JsonSerializer.Serialize(manifest, new + { + format = "ioviewer-synthetic-tiles-1", seed, targetBytes = target, totalBytes, elements, triangles, + unit = "metre", upAxis = "Z", min = Point(bounds.Min), max = Point(bounds.Max), tiles, + }, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, WriteIndented = true }); +} +return 0; + +SceneDocument Build(int count, int x, int y, long firstId, string title) +{ + var scene = new SceneDocument { Title = title }; + scene.Models.Add(new SceneModel { Id = 1, Key = "synthetic-plant", Name = title, CreatedAt = "2026-11-20T00:00:00Z" }); + scene.Materials.Add(new SceneMaterial { Id = 1, Color = new RgbaColor(112, 150, 167) }); + scene.Materials.Add(new SceneMaterial { Id = 2, Color = new RgbaColor(190, 140, 82) }); + scene.Materials.Add(new SceneMaterial { Id = 3, Color = new RgbaColor(132, 150, 116) }); + for (int level = 1; level <= levels; level++) + scene.Levels.Add(new SceneLevel { Id = level, ModelId = 1, Name = $"Level {level}" }); + + for (int i = 0; i < count; i++) + { + int level = i / (columns * columns); + double radius = 0.75 + 1.45 * random.NextDouble(); + double height = 3 + 6 * random.NextDouble(); + double oval = 0.8 + 0.2 * random.NextDouble(); + var vertices = new Vector3d[rings * sides]; + for (int ring = 0; ring < rings; ring++) + { + double r = radius * profile[ring]; + double z = height * ring / (rings - 1); + for (int side = 0; side < sides; side++) + vertices[ring * sides + side] = new Vector3d(r * cos[side], r * oval * sin[side], z); + } + + long id = firstId + i; + var origin = new Vector3d(x * tilePitch + i % columns * spacing, y * tilePitch + i / columns % columns * spacing, level * levelPitch); + scene.Geometries.Add(new SceneGeometry { Id = i, Vertices = vertices, Indices = indices }); + scene.Instances.Add(new SceneInstance { ElementId = id, GeometryId = i, MaterialId = i % 3 + 1, Transform = Transform3d.Translate(origin) }); + var element = new SceneElement { Id = id, ModelId = 1, Category = "Process equipment", TypeName = "Vessel", Name = $"Vessel {id}", LevelId = level + 1 }; + var dimensions = new ScenePropertySet { Id = i + 1, Name = "Dimensions" }; + dimensions.Properties.Add(new SceneProperty { Name = "Height", Value = SceneValue.FromText(FormattableString.Invariant($"{height:F3} m")) }); + dimensions.Properties.Add(new SceneProperty { Name = "Diameter", Value = SceneValue.FromText(FormattableString.Invariant($"{2 * radius:F3} m")) }); + element.PropertySetIds.Add(dimensions.Id); + scene.PropertySets.Add(dimensions); + scene.Elements.Add(element); + } + return scene; +} + +static int[] MakeIndices() +{ + var indices = new List(); + for (int ring = 0; ring < rings - 1; ring++) + { + for (int side = 0; side < sides; side++) + { + int a = ring * sides + side, b = ring * sides + (side + 1) % sides; + indices.AddRange([a, b, a + sides, b, b + sides, a + sides]); + } + } + int top = (rings - 1) * sides; + for (int side = 1; side < sides - 1; side++) + indices.AddRange([0, side + 1, side, top, top + side, top + side + 1]); + return [.. indices]; +} + +static double[] Point(Vector3d p) => [p.X, p.Y, p.Z]; + +internal sealed record Tile(string File, int X, int Y, long Bytes, long FirstElementId, int Elements, long Triangles, + double[] RtcOffset, double[] Min, double[] Max);