You can now generate creatures directly within your project. Drop the open-source into your Agent, and start prompting what you want.
JavaScript
anyCreature 1.2.0
Ariescarab5b1ce5c13e
diff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..e03878a--- /dev/null+++ b/.gitignore@@ -0,0 +1,39 @@+# deps+node_modules/+package-lock.json+package.json+__pycache__/+*.pyc+.venv/+venv/++# harness working output — every run writes here, none of it belongs in git+out/+delivery/+*_viewer.html+hero.png+hero.jpg+gate.json++# ...but the README's own images ARE committed. Without these two exceptions the+# bare `hero.png` rule above silently swallows the front page's main picture.+!/assets/hero.png+!/assets/silhouettes.png++# the operator's saved signature (personal data — never commit)+.anyCreature.json++# scratch / editor / OS+*.log+*.bak+*.tmp+*~+*.swp+.DS_Store+Thumbs.db+.idea/+.vscode/++# large archives: ship these as GitHub Release attachments, not repo objects.+# Once a big blob is pushed it stays in history even after deletion.+*.zipdiff --git a/CHANGELOG.md b/CHANGELOG.mdnew file mode 100644index 0000000..9e5e62b--- /dev/null+++ b/CHANGELOG.md@@ -0,0 +1,214 @@+# CHANGELOG++> **Version renumber (at 1.2.0).** 1.2.0 is the FIRST PUBLIC RELEASE. All+> earlier development versions were renumbered to 0.3.0–0.12.0 in release order+> (old 0.1.0→0.3.0 … old 1.7.0→0.12.0); the full mapping lives in the+> version-library README. Entries below keep their original content; their old+> numbers are shown with the new number in front.++## 1.2.0 — smooth bodies, one shading pass, saturation measured++Stage cards+- **HIGH gains a fifth colour norm — `saturation_area`, band 10%–34%**: the share of the view whose colour carries HSV saturation ≥ 0.50, measured on the UNLIT baked vertex colour so brightness, AO and lighting cannot skew it. Below the floor the creature reads as a grey mass; above the ceiling saturation stops working as a spotlight. It rules AMOUNT, never LOCATION — the designer picks which surfaces carry the colour. The reshipped wolf measures 26.0%; the previous wolf measured 0.2% and would fail. The accent norm now reads as a cap on the ACCENT alone (<5%), not on total saturated area.+- **MID's fold-and-carve vocabulary no longer offers `faceted` for masses**: concave sections, `sharp` profile rows and a lower per-volume `smooth_angle` instead; parts may still be faceted freely.+- SYNTAX.md gains `shading`, `smooth_angle` and `build`, marks `faceted` parts-only, and drops `colors.gradient`/`colors.noise` from the volume example. 04_SHIP's gate.json example lists `faceted_body` and `saturation_area`.++Engine+- **Vertex normals are ANGLE-weighted and carry a smoothing angle** — `smooth_angle`, spec-level default 50, overridable per volume and per part. Faces meeting at a vertex average when their normals sit within the angle; the vertex is duplicated only where it genuinely carries two smoothing groups, so creases cost a handful of vertices instead of tripling the mesh. `"faceted": true` is now exactly `smooth_angle: 0`. Area weighting let one big skinny triangle drag a normal off by tens of degrees — and AO bakes from those normals.+- **`faceted: true` on a VOLUME now BLOCKs (`faceted_body`)**: two real runs came back 89% and 93% hard-edged because the model set `faceted` on the big masses; an 800-triangle torso became 800 shards, and since AO bakes from those normals the mess ships inside COLOR_0 where relighting cannot reach it. The right tools for a hard break on a body are `"sharp": true` on the profile row or a lower `smooth_angle` on that volume. Escape hatch for robots, constructs, golems and vehicles: `"build": "rigid"` at spec level. Parts (fin/spike/curve/paw/membrane) may still be faceted freely.+- **Shading moved from per-volume to spec-level**: `"shading": {"gradient":{"top":0.30,"bottom":-0.88}, "noise":{"size":0.018,"amount":0.26}}` (the defaults). The ramp is measured over the WHOLE body's Y range and applied to EVERY mesh — volumes, paws, ears, eyes, horns. Each volume used to ramp over its own bbox, so the same numbers meant different things on an upright leg and a horizontal torso (the old wolf wrote bottom -0.16 on legs and -0.04 on the torso to fake one consistent light), and parts received no shading at all, so paws read as stickers. `noise.size` is a FRACTION OF THE MODEL DIAGONAL, not an absolute distance: an absolute cell keeps its world size as the creature scales, so the same spec on a 5x larger creature produced grain finer than the vertex spacing and aliased into banding. `colors.arcs` stays per volume; `colors.gradient`/`colors.noise` are ignored and emit an `info:` line.+- **Gamma bug fixed**: `hex2lin` in compile.js applies the sRGB transfer function, as ao.js and glb.js always did. Before, any volume with a `colors` block shipped about 1.5x too bright with its value steps collapsed — the wolf's spine-band-to-base contrast fell from 5.3x to 2.1x, so the arc bands were effectively invisible.+- **AO defaults retuned**: samples 14 → 16, strength 0.75 → 0.59, radius 0.35 → 0.60 of the model diagonal. One AO pass only; there is no second crevice pass and none is planned.++Harness & fixes+- **`saturation_area` claim** in judge.mjs — `{"type":"saturation_area","view":"tq","min":0.14,"max":0.34}` — added at stage HIGH to all three role presets (minion/npc/boss) and to `specs/_TEMPLATE.json`.+- `setup.sh` installs scipy: harness/maskmetrics.py imports `scipy.ndimage`, and setup used to print "calibrate OK" then blow up mid-LOW.+- `proportion` decides limb exemption from `spec.mirror` instead of the chain name's first letter — renaming a chain "axis" to "Laxis" used to bypass the 50:50 ruler entirely.+- example/README.md rewritten accurate: the wolf is the reference example (high-saturation area 26.0%), not a copy of the `templates/` anchor removed in 1.2.0, and it ships with UV off.++## 1.2.0 — first public release: MID/HIGH doctrine + Gobkit delivery++Stage cards+- **MID = whitelist part blind-reads, identity only**: face (always) + signature part + order-named parts are rendered ALONE (`qa_isolate` builds) and shown 4-view to a context-free reader with one question — "what is this?" A face that reads as "a ball" fails. Edit vocabulary: swap local shapes / fold-carve / bend the pose (elbows are MID); no naked sphere/cube/cone on whitelisted parts. Silhouette share demoted to a budget check.+- **HIGH = free colour under four norms** (one high-sat main on the signature, one secondary, accent <5%, brightness floor measured on the render) + three animations always (idle/move/attack).+- **04_SHIP (new card)**: gate stamp (real results only) → name + signature questions (ownership first; signature remembered in ~/.anyCreature.json) → scripted delivery → the share ask LAST, CC0 in one sentence → publish only on an explicit yes. Never auto-upload, never background, ask every time.++Engine+- **Per-vertex AO bakes at compile** into COLOR_0 (hemisphere rays, grid-accelerated, deterministic) — the "solid" look ships in the file; `"ao":false` is debug-only.+- **`attack_reach` check**: attack clips must drive some part ≥ half the body span past the bind front or the build BLOCKs — kills the in-place-wave class.+- **`touch` declarations**: chains declared connected must overlap or BLOCK (the floating-snake-body class).+- **`part_overlap` warn**: measures gross part-into-part interpenetration (the self-intersecting-fist class) — a measure, not a law.+- **`joints_R` pose overrides**: mirrored pairs grow symmetric, bind pose staggers; the mirrored skin follows its joints.+- **Public bone naming**: exported limb bones follow `^[LR][A-Z][A-Za-z]*\d+[A-Z][a-z]$` (LArm1Sh, RFrontLeg1Kn) natively — no `.l/.r` suffixes, no rename pass; mesh `creature`, skin `creature_rig`; internal spec names never leak.+- **Primitive merge**: one primitive + one material per palette entry (kills the 67-material class from mirrored parts) — semantic part names survive as material names.+- **UV atlas now opt-in** (`keep_uv`): without textures TEXCOORD_0 was dead weight; AO no longer needs it.+- Language cleanup: part types settled on `curve` and `membrane`, and the surface-snapping switch on anchored parts settled on `conform`.+- Harness stamp in `asset`: generator `anyCreature v1.2.0`, `extras.harness/.harness_version/.spec`; delivery adds `extras.monster` + `asset.copyright` (user's name + signature travel INSIDE the file); publish adds `extras.license: CC0-1.0` at consent time.++Engine correctness — the "invisible until a human looks" class+- **`part_attachment` (new BLOCK): parts were never checked for being attached to+ anything.** `root_containment` walks `spec.attach`, whose candidates must carry+ both `_rings` and `chain` — curve / fin / eye / paw / spike / membrane have+ neither, so no part ever entered the loop. Real runs shipped a tusk whose whole+ root ring stood 0.031 clear of the skull, a trunk 6/15 outside, a forehead plate+ 0.050 above the surface, all reported all green and all caught by eye in the most+ expensive repair round. A part must now come within 1.5% of model height of its+ host's surface. Deliberately generous: eyes and conformed plates sit ON the+ surface and pass; something hanging in the air does not. Mirrored twins are+ skipped — the source carries the verdict for both.+- **`mirror_distortion` (new BLOCK + warn): `joints_R` shears the twin instead of+ posing it.** The mirrored mesh is grown along the LEFT bone path and then dragged+ onto the right joints by weighted TRANSLATION, so a large offset squashes the+ volume. Measured on the wolf: offsets up to 10% of limb length are clean, 16%+ costs 12% of a dimension, 24% costs 19%, 39% costs 31% and blocks. A reported+ case had a right thigh 0.152 deep against 0.381 on the left with its width intact+ — invisible from the left, invisible in the log. Warn past 12% deviation, BLOCK+ past 30%. Doctrine added to SYNTAX and MID: `joints_R` is for a few centimetres+ of stagger; a genuinely different pose belongs in its own chain outside `mirror`.+- **`attack_reach` no longer demands a whole-body lunge.** It required half a body+ span PAST the bind front, which rejected every stand-and-swing design. Now either+ route passes: REACH (≥15% of span past the front) or SWING (a part travels forward+ ≥45% of ITS OWN length — the limb's travel is bounded by the limb, not the body;+ the old rule was a dimensional error). Verified: ±20° twitch blocked, ±35° foreleg+ swing passes, forward tail slam passes, sideways sweep blocked, full lunge passes.+- **`anim_integrity` says WHERE.** It is ~83% of all blocks in practice and used to+ report only `"move" @0.5 folds mesh (10 flipped tris)`, forcing a binary search.+ It now names the worst mesh for folds, and the mesh plus the driving joint for+ stretches, with the three fixes that actually apply.+- **Profile-slope warning at compile.** Scaling a volume without scaling `ring_step`+ crowds rings relative to how fast the radius changes; past a slope of ~0.8 the+ next bend flips triangles. The engine now warns with the number and the location,+ instead of letting it surface later as flipped tris during an animation.+- **Anchored parts narrate the world direction they actually face.** `around` is+ read in the host section's frame; the documented 0=spine / 90=side / 180=belly is+ the BODY chain's frame. Measured on a leg: 0=inner, 90=FRONT, 180=OUTER, 270=back+ — so a plate aimed at the outside of a thigh with 90 silently lands on its front.+- **`deliver.py` refuses a self-contradicting gate stamp.** A delivered model was+ found carrying `"passed": true` with `mid_face_blindread` failed in the same+ object, and it had already been published. The stamp travels inside the GLB+ forever; delivery now stops unless the aggregate matches the checks.++Security & open-sourcing+- **Arbitrary file read in `judge.mjs` closed (the one real vulnerability).** The+ static handler did `path.join(base, urlPath)` with no containment check, and the+ listener bound to `0.0.0.0`. A raw request line carrying `/../../../../etc/passwd`+ (a socket does not normalise it the way `fetch` does) escaped every base and the+ file was served — `/proc/self/environ` included, which is where credentials live.+ Any host on the same network could read any file, for as long as a judge run+ lasted. Now: resolve then require containment, serve only `.js .mjs .map .json+ .wasm`, and listen on `127.0.0.1`.+- **`silmetrics.mjs` and `hero.mjs` bind to `127.0.0.1` on an OS-assigned port**+ instead of `0.0.0.0:8961` / `0.0.0.0:8963`. Their handlers were already+ whitelisted so nothing leaked beyond the model, but the pages and models were+ network-visible during a run, and two concurrent runs collided on the port.+- **Creature names and signatures are HTML-escaped** before they go into the+ delivered viewer (`deliver.py`). A creature named `</h1><script>…` executed in+ the page; the same string also rides in the GLB to the community wall, so+ SECURITY.md states plainly that the server must escape it independently too.+- **Chromium keeps its OS sandbox.** `--no-sandbox` was unconditional in+ `judge.mjs`; it is now opt-in via `PW_NO_SANDBOX=1`. The hardcoded+ `/opt/pw-browsers/chromium` path is gone from all three render tools — Playwright+ locates its own browser, `PW_CHROMIUM_PATH` pins one. That path made every clone+ fail on macOS and Windows.+- **Licensing corrected.** MANUAL claimed "no third-party code is bundled"; it does+ bundle three.js (MIT) as `harness/assets/three-bundle.js`. The upstream notice was+ always preserved in the file, so nothing was ever out of compliance — the sentence+ was simply wrong. Added `THIRD-PARTY-NOTICES.md` with the full MIT text plus the+ licences of everything `setup.sh` installs.+- **Added `LICENSE` (MIT, © 2026 Alsomind Tech Co., Ltd.), `README.md`, `SECURITY.md` and `.gitignore`**; `gobkit.json`'s `_key_label` now says+ the key is public by design and that rotation cannot retract what is already in+ git history.++Delivery & publish+- **Showroom viewer redesigned and moved out of the Python** into+ `harness/assets/showroom.html` (placeholders `__TITLE__` `__BYLINE__`+ `__BUNDLE__` `__B64__`), so the room can be restyled without touching+ `deliver.py`. Gallery room: radial backdrop, floor wash, vignette, a+ small-caps name plate reading `<signature> · anyCreature <version>`, and three+ tool buttons — cycle the file's own animation clips, turntable, hard-edge clay+ with a wireframe overlay. Shadow-casting key light over a ShadowMaterial+ ground; camera auto-framed to the bounding sphere and the model rested on the+ floor. Fully offline: three.js inlined, model base64'd, no CDN and no webfont+ (system serif stack) — double-click and it runs.+- **`publish.mjs`: try the upload, always.** New doctrine written into the+ script header and card 04 — never pre-judge the environment as offline.+ Cloud sandboxes and Cowork sessions frequently do have egress; run the command+ and answer from what it prints. Saying "in a sandbox you can only upload by+ hand" without attempting is now explicitly wrong.+- **`offline` renamed to `blocked`, and 403 is classified as network filtering,+ not a key problem.** The submit endpoint always answers in JSON, so an HTTP+ 403 or any non-JSON body means an intermediary replied — a proxy, captive+ portal or corporate filter. `blocked` is a normal outcome, reported as the+ next step ("the pack is ready, drag it into the page") rather than an error.+ Nothing tells the user to fetch or change a key.+- **hero.png is now required in practice**: a submission without a thumbnail is+ accepted but never lists automatically — it waits for a human reviewer, and+ that is the one common post-upload stall. `publish.mjs` warns loudly when the+ file is missing and reports `thumb` in its JSON line.++- `deliver.py` v2: stamped GLB + showroom viewer (studio backdrop, title card, animation pills) + `hero.mjs` auto-framed hero.png (1024² transparent 45°, ≥8% margins, idle mid-frame) / hero.jpg + backup upload pack.+- `publish.mjs`: multipart POST to gobkit.com/api/community (fields model/thumb/title/creator_name/channel/key) with three scripted outcomes — published (echo the SERVER's title/creator + share link), pending_review (one calm line), offline (backup path: drag delivery/upload/creature.glb into gobkit.com/community/upload).++## 0.12.0 (was 1.7.0) — clean painter, strict inspector (validated by 7 head-to-head experiments)++Architecture (from the harness-vs-native duels and the 2x2/gryphon experiments)+- **Creation side stripped to a pit-map**: no design doctrine upfront — free design won or tied every duel where part character mattered; doctrine text taxed boldness. Design knowledge now lives in gates and rulers only.+- **Two gates, four views each, read by context-free agents** (self-grading shipped the worst failure in project history): Gate 1 RECOGNISED — any stick/slab view kills; Gate 2 PUNCHIER — after identity passes, rounds may only exaggerate, judged prev-vs-curr; compliance-only edits forbidden. LOW's deliverable is an exaggerated silhouette.+- **Stop-loss**: same symptom failed twice → concept restart, never a third tweak (verdict-driven micro-repair oscillated: human→bell, trousers→rooster).+- **Signature parts get real geometry at LOW** (a fist is fingers and knuckles, not a sphere); 6:3:1 governs geometry budget, not just screen share.+- Scale calibration: 24px = feel, 48px = identity (control reads on the approved standard proved single-scale gates miscalibrated). Front view alone may be symmetric; paired features still stagger.+- Templates removed entirely (anchor became a topology prison — a giant order produced a wolf skeleton).++Engine wave-1 (~+250 lines; required reading stays ~1 page)+- `curve`: curved horns/tusks/trunks — per-segment steering that accumulates down the chain (`rise`/`fall`/`ahead`/`behind`/`coil`); the mammoth-tusk class of failure was a vocabulary gap, not a design gap.+- `membrane`: skin between rib chains with blend skinning, a scooped trailing edge, and the root-gap warning — the bat-wing failure class, where a shape that never encloses reads as spread fingers.+- Named sections incl. CONCAVE outlines (`"sections"`): bark flutes, crescents — relief is geometry.+- `faceted` hard-edge shading; anchored parts snap onto the host surface normal by default (`conform:false` opts out).+- Compiler narration: `info:` lines report the accumulated bend of a curve and how far a plate was rotated to meet its surface.+- Membranes exempt from the closed-surface fold check (saddle regions are legitimate).+- maskmetrics dullness flags: `sq_fill` (1:1-frame volume), `mirror_sym`, `straight_max` (plank detector) — measures only, judgment stays with the reader/LLM.++## 0.11.0 (was 1.6.0) — method over conclusions (cards + silmetrics)++Constitutional rule added: **cards carry method and rulers, never instance conclusions** — a specific creature's ratio numbers or 24px phrases are per-order products; baking them in anchors every future creature to one answer and pollutes context. Accordingly:+- Ratio table (design 2c) rewritten method-only: the session decomposes the order's creature-noun itself — picks WHICH 3–5 ratios carry the identity, justifies each against the temperament. The giant's worked numbers are gone.+- New general art direction: **ratios checked in all three orthographic views** (one-view drama = cardboard); **per-axis decomposition** (a mass's elongation axis is identity information); **colour philosophy** in HIGH (value-first 70/25/5, saturation as spotlight, one temperature story, pattern follows form).+- silmetrics now renders **side + front + top** and reports per-view aspect/fill.+- Instance residue swept from 1.5.0's cards (giant example lines, magic numbers).++## 0.10.0 (was 1.5.0) — doctrine patch: the giant lessons (cards only; engine unchanged from 1.4.0)++Distilled from an approved no-harness mountain-giant build — the reasoning that made it work, sedimented into the cards:+- **Ratio table** (design 2c): the identity noun translates DIRECTLY into a mass-allocation table vs a baseline; scaling up ≠ giant, changed ratios = giant. The exaggeration vector is the table's extreme rows.+- **Three contour layers** (LOWRES): primary masses (3–5, = 80% of silhouette, verified FIRST) → breakers (straight lines & sharp angles on the contour) → details. Order never reverses.+- **Blob-pile trap + the glue**: elongate ~1.7×, overlap seams, and the decisive fix — a hard plate spanning ≥2 masses fuses them into one structure (why pauldrons span shoulder+arm).+- **Negative space, pose, curve-vs-hard coexistence** added to the silhouette declarations; **≥3 read points** and a ~15° asymmetry nudge added to the stage-1 human checklist.++## 0.9.0 (was 1.4.0) — the big-form release (core competence: silhouette tension)++Engine+- **Relational joints**: `{"from":X,"fwd/up/side":d}`, `{"from":X,"dir":[..],"len":d}`, `"ground":y` for feet — specs think in proportions again; absolute coords stay legal. Verified bit-identical against the absolute wolf spec.+- **Game-ready UVs**: automatic unwrap (cylindrical tubes + planar caps, box unwrap for parts), seam-vertex duplication, one non-overlapping world-density atlas (`TEXCOORD_0`); overlap audit 0.2% (corner texels only) → AO/lightmap bakeable.+- Fixed inverted normals in `paw` (winding) and `fin` (outline now canonicalised CCW, rim rewound).+- Fixed floating surface anchors (eyes/ears): lookup by true arc-length `ringT` instead of ring index (bevel-skip had shifted indices).+- `proportion` gate aligned to the styling rule: 0.96 → **0.923** (the 0.92–0.96 blind band caught nothing); minor-segment filter now relative to mean segment length (checks 6–7 pairs on a 9-joint spine, was 1).+- `limb_clearance` exposed-test gets a 5% seam tolerance (groin-seam verts are host geometry, not exposed limbs).+- Wolf: head split into its own volume (rooted inside the neck), slab thighs (`exp` 2.2–2.6), eyes moved to the head's side (`around` 62).++Harness+- **silmetrics.mjs**: side+front silhouettes, 24px thumbnail, and the numbers — `W_over_H, fill, mass_thirds, torso_depth, mass_contrast, leg_fraction, turn_count, zigzag_alignment, iou_vs_prev`.+- Calibration: green = the bred wolf; red = legacy broken wolf **plus** `red_5050.json`, which violates ONLY the 50:50 rule — proving that specific ruler bites.++Doctrine (cards, all-English rewrite)+- 24px contract (identity phrase / per-part features / signature survival) + blind-read gate with recall scoring and signature veto.+- Exaggeration vector + character axes: declared tension, verified by the loop; floors-are-not-goals iron law.+- Knob table (symptom → spec knob) distilled from the wolf's measured convergence.+- `templates/` library with breeding pipeline: in-house references only, human sign-off mandatory; ships `quadruped_light`.+- Docs/cards no longer reference the retired pre-0.8 spec language or its tooling; syntax quick-refs show the real JSON.++## 0.8.0 (was 1.2.0) — engine swap: original ACS engine v2 (author Ariescar, zero foreign code), six built-in checks, JSON spec, wolf example.+## 0.7.0 (was 1.2.0) — one-shot pipeline for non-designers: 2-question interview, 3/2/1 rounds, five stage cards, staged judging, scripted delivery.+## 0.6.0 (was 1.1.0) — engine renamed ACS; two quantified claims added; 10-round budget.+## 0.5.0 (was 1.0.0) — generic engine + styling rules + embedded compiler + example + manual.+## 0.4.0 (was 0.2.0) — engine/spec split, generic harness.+## 0.3.0 (was 0.1.0) — first two gates, dragon-specific thresholds.diff --git a/LICENSE b/LICENSEnew file mode 100644index 0000000..f750c2e--- /dev/null+++ b/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Alsomind Tech Co., Ltd.++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/MANUAL.md b/MANUAL.mdnew file mode 100644index 0000000..cd7ef79--- /dev/null+++ b/MANUAL.md@@ -0,0 +1,107 @@+# anyCreature 1.2.0 — text → game-ready 3D creature, one shot++Author: **Ariescar**. The engine and the harness scripts are original work. One third-party component IS bundled: `harness/assets/three-bundle.js` is a build of three.js (MIT, © 2010-2025 Three.js Authors) used by the render tools and the delivered showroom — its licence notice travels in the file and in `THIRD-PARTY-NOTICES.md`. Everything else npm installs at setup time. Licence: MIT (`LICENSE`); third-party attributions in `THIRD-PARTY-NOTICES.md`.++A session receives an order like "make me a menacing mountain giant", asks at most+2 questions, and delivers a skinned, animated, vertex-coloured, **AO-baked GLB**+plus an offline showroom viewer — and, with the user's explicit yes, publishes it+to the Gobkit community under CC0.++## Quickstart for the executing session++```bash+bash setup.sh # deps + red/green ruler calibration (must print "calibrate OK")+# then read cards/ in order: 00_START → 01_LOW → 02_MID → 03_HIGH → 04_SHIP (SYNTAX.md when building)+```++Pipeline: interview (≤2Q) → silhouette brief → **LOW: design free + two gates** →+MID (2 rounds, whitelist part blind-reads) → HIGH (1 round, colour + 3 animations)+→ SHIP (scripted delivery, closing dialogue, optional publish).++## The doctrine in one paragraph++Head-to-head experiments showed the model designs BOLDLY when left free, and every+attempt to teach it design upfront made the output tamer — so this harness ships a+**clean painter and a strict inspector**: the creation side gets only the order, the+engine syntax, and a short pit-map of engine-local traps; ALL quality control lives+in gates read by context-free reader agents (never self-graded). Gate 1: all four+views RECOGNISED. Gate 2: rounds may only make the silhouette BOLDER — LOW's+deliverable is an exaggerated silhouette, not a correct one. MID blind-reads the+whitelisted parts (face, signature, order-named) with one question: what is this?+Same symptom failed twice = concept restart, never a third tweak. Form beats+obedience, everywhere.++## Folder map (accurate — trust this over memory)++```+MANUAL.md this file+README.md repository front page (humans)+LICENSE MIT+THIRD-PARTY-NOTICES.md bundled + installed dependency licences+SECURITY.md local servers, the public key, untrusted input+VERSION 1.2.0+setup.sh deps + calibration self-check+cards/ 00_START · 01_LOW · 02_MID · 03_HIGH · 04_SHIP · SYNTAX.md+engine/ cli.js + core/ — the ACS engine v2+ core/normals.js angle-weighted normals + `smooth_angle` creases (bodies stay smooth)+harness/+ silmetrics.mjs 4-view silhouettes (front/side/top/hero45) + numbers + 24/48px thumbs+ maskmetrics.py per-view measures + dullness flags (sq_fill / mirror_sym / straight_max)+ judge.mjs claims judge (part shares, focal contrast, styles, saturated area, rig/anim/tri)+ deliver.py stamped GLB + showroom viewer + hero shots + backup upload pack+ hero.mjs hero.png (1024² transparent 45°) + hero.jpg (studio grey)+ publish.mjs Gobkit publisher — ONLY after the user's explicit yes (card 04).+ ALWAYS attempt the upload; the drag-and-drop page is the+ fallback for a `blocked` result, never the opening move+ gobkit.json endpoint + release key for publish.mjs+ presets/ role QC presets (minion/npc/boss)+ assets/ three-bundle.js for the render tools+calibration/ wolf_green (must build) · wolf_red + red_5050 (must be blocked)+example/ wolf.json + wolf.glb — a bred, approved light quadruped+```++## The engine in seven lines++- ONE JSON spec: relational joints, chains, mirrored twins (+`joints_R` staggered+ pose), tube volumes with profile rows (superellipse / **named concave sections**),+ `sharp` breaks, per-volume colour arcs, keyframe animations, `touch` connection+ declarations.+- Parts: `curve` (bending horns/tusks/trunks), `membrane` (wings, frills, sails —+ close the outline back to the body or the compiler warns), `fin` (plates,+ conforming onto surfaces by default), `eye`, `paw`, `spike`.+- Normals carry a smoothing angle (`core/normals.js`, default `smooth_angle` 50,+ per volume/part): faces within the angle average, vertices split only at real+ creases. `faceted` on a VOLUME is a BLOCK (`faceted_body`) — bodies break with+ `sharp` rows; `"build":"rigid"` is the escape hatch for machines.+- ONE spec-level `shading` pass — value ramp over the whole body's Y range plus+ grain sized as a fraction of the model diagonal, on every mesh, parts included —+ then **per-vertex AO bakes at compile** into COLOR_0: the solid look ships in+ the file.+- Blocking checks incl. `attack_reach` (an attack must lunge half a body span);+ `warn:` measures (part overlap) are yours to judge; refused builds cost no+ round. The compiler also NARRATES (`info:` lines) — where a curve really bent,+ how far a plate conformed. Free QC; read it.+- Shipped GLBs: primitives merged per material, public bone names (`LArm1Sh`+ convention), mesh `creature` / skin `creature_rig`, harness stamp in `asset`.+- `node engine/cli.js spec.json out.glb` — that's the whole interface.++## Scale discipline++24px reads FEEL (heavy/fast/sharp); 48px reads IDENTITY (what creature). Judge each+at its own scale. Only the FRONT view may be left-right symmetric — and paired+features (four wings) still stagger. Model-level looks are the final judge.++## Delivery & publish++Card 04 is the whole flow: gate stamp → name + signature questions (once;+`~/.anyCreature.json` remembers the signature) → `deliver.py` (stamped GLB,+offline showroom viewer, hero shots, backup upload pack) → the share ask LAST →+`publish.mjs` only on an explicit yes — and then RUN it, never assume the+environment is offline. hero.png must be attached or the listing waits for a+human reviewer. CC0 is stamped at consent time, not before.++## Versioning++Semver; old zips never change; every release adds a CHANGELOG entry and a README+row. (1.2.0 is the first public release — earlier development history was+renumbered 0.3.0–0.12.0; the mapping lives in the version-library README.)diff --git a/README.md b/README.mdnew file mode 100644index 0000000..9f533be--- /dev/null+++ b/README.md@@ -0,0 +1,183 @@+<div align="center">++# anyCreature++**Text → a game-ready 3D creature, in one session.**++An AI session takes an order like *"make me a menacing mountain giant"*, asks at most+two questions, and delivers a skinned, animated, vertex-coloured, AO-baked GLB plus an+offline showroom viewer.++[](LICENSE)+[](CHANGELOG.md)+[](engine)+[](https://www.khronos.org/gltf/)+[](setup.sh)++<img src="assets/hero.png" width="560" alt="anyCreature — a winged creature compiled from a one-line order">+++</div>++*Every creature is compiled from one JSON spec. No mesh files, no downloaded art+packs, no photogrammetry. The worked example that ships with this repo,+[`example/wolf.json`](example/wolf.json), is 2,211 vertices and 31 joints written+out by the engine from plain text.*++---++## Quick start++```bash+bash setup.sh # deps + red/green ruler calibration+node engine/cli.js example/wolf.json out/wolf.glb+```++`setup.sh` must print **`calibrate OK`** before you trust anything else: it builds one+spec that has to pass and two that have to be blocked, so you know the rulers separate+good from bad on your machine.++To run the full text-to-creature session, point an agent at+[`MANUAL.md`](MANUAL.md) and let it read `cards/` in order —+`00_START → 01_LOW → 02_MID → 03_HIGH → 04_SHIP`.++### Driving it harder++| Knob | Where | What it changes |+|---|---|---|+| `smooth_angle` | spec root, or per volume/part | Crease threshold in degrees, default `50`. Higher = smoother body, lower = more facets. |+| `shading` | spec root | Whole-body vertical colour ramp and grain — `{gradient:{top,bottom}, noise:{size,amount}}`. |+| `build: "rigid"` | spec root | The only way to get a fully faceted body past the checker. For robots and crystals, not for animals. |+| `ao` | spec root | Per-vertex ambient occlusion; `false` to skip the bake. |+| `harness/presets/` | QC | Role presets — `minion.json`, `npc.json`, `boss.json` — different budgets and thresholds per role. |++## What is actually in here++| Folder | What it holds |+|---|---|+| `engine/` | The ACS engine. One JSON spec in, one skinned GLB out. Zero runtime dependencies — `node engine/cli.js spec.json out.glb` is the whole interface. |+| `cards/` | The five stage cards the executing session reads, plus the spec syntax on one page. |+| `harness/` | Measuring tools (silhouettes, mask metrics, claims judge), the delivery packer and the publisher. |+| `example/` | A bred, approved light quadruped to read and copy from. |+| `calibration/` | One sample that must build and two that must be blocked — proof the rulers separate good from bad. |++## How it works++```mermaid+flowchart LR+ A[Order<br/>one sentence] --> B[Interview<br/>≤ 2 questions] --> C[Silhouette<br/>brief] --> D[LOW<br/>design free]+ D --> E{Gate 1<br/>RECOGNISED}+ E -->|fail| D+ E -->|pass| F{Gate 2<br/>PUNCHIER}+ F -->|reverted| D+ F -->|pass| G[MID<br/>all parts] --> H[HIGH<br/>colour + anims] --> I[SHIP<br/>stamp · deliver]+```++### The two gates++Neither gate is self-graded. The session that designed the creature is the worst+possible judge of whether it reads, because it already knows what it drew. So the+silhouettes go to a **context-free reader agent** that has never seen the order, and+the only question is *"what is this?"*++Gate 1 is **RECOGNISED**: all four views have to land. Gate 2 is **PUNCHIER**: a new+round may only make the silhouette bolder than the last one — a round that tames the+shape is reverted, even if it is "more correct". LOW's deliverable is an exaggerated+silhouette, not an accurate one.++### The engine floors++The compiler talks in three registers, and they mean different things:++| Prefix | Meaning |+|---|---|+| `BLOCK:` | The build stops. A hard floor was crossed — faceted body, part floating off its host, a mirrored twin distorted past 30%, an attack that never reaches. |+| `warn:` | It built, but something is probably wrong. Read it. |+| `info:` | A number you asked for, or an assumption the compiler made on your behalf — like which way an anchored fin ended up facing. |++Floors are not style opinions. They are the failures that survive review and ship+broken: a body that renders in hard facets, a horn that hovers a centimetre off the+skull, a right thigh collapsed to 40% depth by mirrored skinning.++### What gets measured++++Every round renders these four views, reduces them to masks, and computes the numbers+the design card declared a target for — width over height, mass thirds, torso depth+contrast, leg fraction, silhouette turn count, zigzag alignment, and IoU against the+previous round as a regression guard. The 24px thumbnail is what the blind reader+actually sees; if it does not read at 24px, it does not read.++## The doctrine in one paragraph++Head-to-head experiments showed the model designs BOLDLY when left free, and+every attempt to teach it design upfront made the output tamer — so this harness+ships a **clean painter and a strict inspector**. The creation side gets only the+order, the engine syntax, and a short pit-map of engine-local traps; ALL quality+control lives in gates read by context-free reader agents, never self-graded.+Form beats obedience, everywhere.++## Honesty about limits++- **Isolated-part blind reads misfire on dome-plus-hanging-tube heads.** Elephants and+ birds get read as something else when the head is shown alone; put the same head back+ on the body and it reads fine. Trust the whole-body read when the two disagree.+- **Cost is only measured on two bosses**, at roughly 4.4M tokens each. Minions and NPCs+ should be cheaper, but nobody has measured them, so treat the preset budgets in+ `harness/presets/` as estimates rather than data.+- **`part_attachment` and `mirror_distortion` are new in 1.2.0.** Specs authored against+ an older version may now be blocked. That is usually the checker being right, but it+ is a breaking change, not a silent improvement.+- **The example wolf ships two animations, not three.** Card 03 asks for idle, move and+ attack; `example/wolf.json` has idle and move. Copy it for structure, not for+ animation coverage.+- **The engine has zero dependencies; the tooling does not.** Every render and measure+ tool drives headless Chromium through playwright. If playwright will not install, you+ can still compile creatures — you just cannot measure them, and the gates are the+ point.++## Scripts++| Script | Role |+|---|---|+| `engine/cli.js` | Spec → GLB. The whole engine interface. |+| `harness/silmetrics.mjs` | Renders the four silhouettes and the 24px thumbnail; emits the layout metrics. |+| `harness/maskmetrics.py` | Per-view mask measures and dullness flags (`sq_fill`, `mirror_sym`, `straight_max`). |+| `harness/judge.mjs` | Claims judge — part shares, focal contrast, saturated area, rig/anim/triangle budgets. |+| `harness/hero.mjs` | `hero.png` (1024² transparent, 45°) and `hero.jpg` over studio grey. |+| `harness/deliver.py` | Stamps identity into the GLB, writes the offline showroom viewer, builds the upload pack. |+| `harness/publish.mjs` | Gobkit publisher. Only runs after an explicit yes, and always tries the upload before offering the manual page. |+| `harness/calibrate.py` | The red/green self-check `setup.sh` runs. |++## Requirements++Node 18+ and Python 3.9+. `setup.sh` installs `three`, `playwright`, `numpy`, `pillow`+and `scipy`, then runs the calibration self-check. The engine alone needs nothing but+Node; the dependencies are for the measuring and render tools.++## Security++Short-lived local servers used by the render tools bind to `127.0.0.1` only, and+Chromium runs with its OS sandbox enabled. The Gobkit submission key in+`harness/gobkit.json` is **public by design** — it authorises posting to the community+wall and nothing else. Details and reporting: [`SECURITY.md`](SECURITY.md).++## Licence++MIT — see [`LICENSE`](LICENSE). One third-party component is bundled+(`harness/assets/three-bundle.js`, three.js, MIT); attributions for it and for+everything `setup.sh` installs are in+[`THIRD-PARTY-NOTICES.md`](THIRD-PARTY-NOTICES.md).++---++## About++**Gobkit: AI-native 3D infrastructure for agents and vibe coders.** Stream+game-ready 3D assets straight into your workflows via API. Agent-friendly.+Studio-quality. Built by a team of artists and engineers.++**Author:** Ariescar | Alsomindtech++👹 [gobkit.com](https://gobkit.com) · 📖 [Devlog](https://gobkit.com/harness/anycreature)diff --git a/SECURITY.md b/SECURITY.mdnew file mode 100644index 0000000..ef8d940--- /dev/null+++ b/SECURITY.md@@ -0,0 +1,53 @@+# Security notes++## What this package runs on your machine++`silmetrics.mjs`, `hero.mjs` and `judge.mjs` each start a short-lived local HTTP+server so a headless Chromium can load the model, then shut it down. All three+**bind to `127.0.0.1` on an OS-assigned port** — they are not reachable from the+network, and two runs cannot collide on a port.++`judge.mjs` also serves the JavaScript its measuring page imports. Paths are+resolved and then checked for containment inside the allowed roots, and only+`.js .mjs .map .json .wasm` are served. Before 1.2.0 this used `path.join` with+no containment check and listened on `0.0.0.0`, which allowed any host on the+same network to read arbitrary files — `/etc/passwd` and `/proc/self/environ`+among them — for as long as a judge run lasted. If you are on an older copy,+update or do not run it on an untrusted network.++Chromium is launched **with the OS sandbox enabled**. Set `PW_NO_SANDBOX=1` only+where the sandbox genuinely cannot work (a container without the required+privileges). `PW_CHROMIUM_PATH` pins a browser binary if you need to; otherwise+Playwright picks its own.++## The Gobkit key in `harness/gobkit.json`++Public by design. It is an anonymous submission key for the community wall — it+authorises posting, nothing else, and abuse is bounded server-side by rate+limiting and review. Finding it in this repository is not a leak.++It does mean two things:++- **Rotation does not retract.** A key committed to git stays readable in the+ history forever. Retiring one has to happen server-side.+- The endpoint is effectively open to anyone who clones this repo, so the+ server's rate limiting and moderation are the only real controls.++## Untrusted input++Creature names and signatures come from a human and are written into three+places: the delivered `_viewer.html`, the GLB's `asset.copyright` /+`extras.monster`, and the community listing. `deliver.py` HTML-escapes them+before substitution — a creature named `</h1><script>…` used to execute in the+viewer. **Any service rendering `extras.monster` must escape it independently.**+Do not rely on this package having done it.++Spec JSON is executed as data, not code — there is no `eval`, no dynamic+`require`, and the only subprocess calls are fixed argument lists to `node`.+Nothing in the pipeline fetches a URL except `publish.mjs`, and only after+explicit consent.++## Reporting++Open a GitHub issue for anything non-sensitive. For something exploitable,+please report privately first.diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.mdnew file mode 100644index 0000000..cc33baa--- /dev/null+++ b/THIRD-PARTY-NOTICES.md@@ -0,0 +1,59 @@+# Third-party notices++The anyCreature engine (`engine/`) and harness scripts (`harness/*.mjs`,+`harness/*.py`) are original work by Ariescar. The components below are not, and+their licences are reproduced here as those licences require. anyCreature+itself is MIT — see `LICENSE`.++## Bundled in this repository++### three.js — `harness/assets/three-bundle.js`++A prebuilt bundle of three.js (core + `GLTFLoader` + `OrbitControls`), used by+`silmetrics.mjs`, `hero.mjs` and by the offline showroom that `deliver.py`+writes. The upstream licence banner is preserved at the end of the bundle.++```+Copyright © 2010-2025 Three.js Authors+SPDX-License-Identifier: MIT++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.+```++## Installed at setup time, not bundled++`setup.sh` fetches these from their registries; they are not redistributed here.++| Package | Licence |+|---|---|+| three (npm, pinned 0.180.0) | MIT |+| playwright | Apache-2.0 |+| numpy | BSD-3-Clause |+| pillow | MIT-CMU |+| scipy | BSD-3-Clause |++Playwright downloads a Chromium build on install; Chromium carries its own+licences (BSD-3-Clause and others), shown at `chrome://credits` in that build.++## Output files++Models produced by this harness are the work of whoever ran it. `deliver.py`+stamps the operator's chosen signature into `asset.copyright`. No licence is+applied at that point — `publish.mjs` writes `extras.license = CC0-1.0` only+after the user has explicitly consented to publishing.diff --git a/VERSION b/VERSIONnew file mode 100644index 0000000..26aaba0--- /dev/null+++ b/VERSION@@ -0,0 +1 @@+1.2.0diff --git a/assets/hero.png b/assets/hero.pngnew file mode 100644index 0000000..29127aeBinary files /dev/null and b/assets/hero.png differdiff --git a/assets/silhouettes.png b/assets/silhouettes.pngnew file mode 100644index 0000000..ddf0e0dBinary files /dev/null and b/assets/silhouettes.png differdiff --git a/calibration/red_5050.json b/calibration/red_5050.jsonnew file mode 100644index 0000000..f7c21da--- /dev/null+++ b/calibration/red_5050.json@@ -0,0 +1,20 @@+{+ "name": "red_5050",+ "_purpose": "calibration sample that violates ONLY the 50:50 proportion rule (segments 0.50 vs 0.48, ratio 0.96). Everything else is clean. The build MUST fail with reason 'proportion'.",+ "palette": { "skin": { "color": "#a08060", "rough": 0.9 } },+ "joints": {+ "A": [0, 0.5, -0.5],+ "B": [0, 0.5, 0.0],+ "C": [0, 0.5, 0.48]+ },+ "chains": { "axis": ["A", "B", "C"] },+ "volumes": [+ {+ "chain": "axis",+ "material": "skin",+ "sides": 12,+ "profile": [[0, 0.14, 0.14], [0.5, 0.15, 0.15], [1, 0.1, 0.1]],+ "caps": ["dome", "dome"]+ }+ ]+}diff --git a/calibration/wolf_green.json b/calibration/wolf_green.jsonnew file mode 100644index 0000000..a2c5a0c--- /dev/null+++ b/calibration/wolf_green.json@@ -0,0 +1,842 @@+{+ "name": "quadruped_light",+ "_template": "ANCHOR, not target. A validated light quadruped (wolf lineage, bred against the approved 1.2 reference over 3 measured rounds). Start here, then DEVIATE: declare your exaggeration vector (which 1-2 numbers you push past this anchor, and how far) in the design card. Converging back to these numbers means you designed nothing.",+ "_anchor_numbers": {+ "W_over_H": 1.41,+ "fill": 0.39,+ "leg_fraction": 0.35,+ "mass_thirds_rear_mid_front": [+ 0.3,+ 0.42,+ 0.28+ ],+ "head_share_of_length": 0.26,+ "belly_y_over_H": 0.34+ },+ "palette": {+ "fur_body": {+ "color": "#b9ae99",+ "rough": 0.95+ },+ "fur_head": {+ "color": "#b9ae99",+ "rough": 0.95+ },+ "fur_tail": {+ "color": "#b9ae99",+ "rough": 0.95+ },+ "fur_leg": {+ "color": "#b9ae99",+ "rough": 0.95+ },+ "fur_paw": {+ "color": "#a89d88",+ "rough": 0.95+ },+ "nose": {+ "color": "#16161a",+ "rough": 0.6+ },+ "ear": {+ "color": "#57513f",+ "rough": 0.95+ },+ "eye": {+ "color": "#c08a2a",+ "rough": 0.25+ }+ },+ "joints": {+ "Hips": [+ 0,+ 0.87,+ -0.42+ ],+ "Rump": {+ "from": "Hips",+ "up": -0.11,+ "fwd": -0.18+ },+ "Spine": {+ "from": "Hips",+ "up": 0.01,+ "fwd": 0.47+ },+ "Chest": {+ "from": "Spine",+ "up": -0.04,+ "fwd": 0.29+ },+ "NeckB": {+ "from": "Chest",+ "up": 0.11,+ "fwd": 0.21+ },+ "Neck2": {+ "from": "NeckB",+ "up": 0.13,+ "fwd": 0.06+ },+ "HeadRoot": {+ "from": "Neck2",+ "up": -0.02,+ "fwd": -0.035+ },+ "Skull": {+ "from": "HeadRoot",+ "up": 0.08,+ "fwd": 0.085+ },+ "Brow": {+ "from": "Skull",+ "up": 0.01,+ "fwd": 0.14+ },+ "Muzzle": {+ "from": "Brow",+ "up": -0.06,+ "fwd": 0.18+ },+ "Nose": {+ "from": "Muzzle",+ "up": -0.02,+ "fwd": 0.14+ },+ "TailRoot": {+ "from": "Hips",+ "up": 0.01,+ "fwd": -0.1+ },+ "Tail1": {+ "from": "TailRoot",+ "up": -0.02,+ "fwd": -0.16+ },+ "Tail2": {+ "from": "Tail1",+ "up": -0.24,+ "fwd": -0.18+ },+ "TailTip": {+ "from": "Tail2",+ "up": -0.32,+ "fwd": -0.1+ },+ "LFrontRoot": {+ "from": "Chest",+ "side": 0.1,+ "up": 0.02,+ "fwd": -0.04+ },+ "LFrontElbow": {+ "from": "LFrontRoot",+ "side": 0.09,+ "up": -0.34,+ "fwd": -0.05+ },+ "LFrontWrist": {+ "from": "LFrontElbow",+ "side": 0.005,+ "up": -0.34,+ "fwd": 0.05+ },+ "LFrontToe": {+ "from": "LFrontWrist",+ "side": 0.005,+ "fwd": 0.14,+ "ground": 0.035+ },+ "LBackRoot": {+ "from": "Hips",+ "side": 0.09,+ "fwd": 0.04+ },+ "LBackKnee": {+ "from": "LBackRoot",+ "side": 0.135,+ "up": -0.37,+ "fwd": 0.12+ },+ "LBackHock": {+ "from": "LBackKnee",+ "side": 0.01,+ "up": -0.28,+ "fwd": -0.18+ },+ "LBackToe": {+ "from": "LBackHock",+ "side": 0.005,+ "fwd": 0.17,+ "ground": 0.035+ }+ },+ "chains": {+ "body": [+ "Rump",+ "Hips",+ "Spine",+ "Chest",+ "NeckB",+ "Neck2"+ ],+ "head": [+ "HeadRoot",+ "Skull",+ "Brow",+ "Muzzle",+ "Nose"+ ],+ "tail": [+ "TailRoot",+ "Tail1",+ "Tail2",+ "TailTip"+ ],+ "LFront": [+ "LFrontRoot",+ "LFrontElbow",+ "LFrontWrist",+ "LFrontToe"+ ],+ "LBack": [+ "LBackRoot",+ "LBackKnee",+ "LBackHock",+ "LBackToe"+ ]+ },+ "attach": {+ "head": "Neck2",+ "tail": "Hips",+ "LFront": "Chest",+ "LBack": "Hips"+ },+ "mirror": [+ "LFront",+ "LBack"+ ],+ "volumes": [+ {+ "chain": "body",+ "material": "fur_body",+ "frame": "up",+ "sides": 16,+ "profile": [+ [+ 0.0,+ 0.14,+ 0.16+ ],+ [+ 0.109,+ 0.185,+ 0.235,+ {+ "bias": -0.1+ }+ ],+ [+ 0.357,+ 0.205,+ 0.31,+ {+ "bias": -0.14+ }+ ],+ [+ 0.62,+ 0.21,+ 0.34,+ {+ "bias": -0.2,+ "sharp": true+ }+ ],+ [+ 0.775,+ 0.18,+ 0.25,+ {+ "sharp": true+ }+ ],+ [+ 0.946,+ 0.163,+ 0.19+ ],+ [+ 1.0,+ 0.175,+ 0.2+ ]+ ],+ "caps": [+ "dome",+ "dome"+ ],+ "colors": {+ "arcs": [+ {+ "from": 0,+ "to": 52,+ "color": "#57513f"+ },+ {+ "from": 128,+ "to": 180,+ "color": "#f2ead7"+ }+ ]+ }+ },+ {+ "chain": "head",+ "material": "fur_head",+ "frame": "up",+ "sides": 14,+ "profile": [+ [+ 0.0,+ 0.155,+ 0.17+ ],+ [+ 0.16,+ 0.22,+ 0.23,+ {+ "sharp": true+ }+ ],+ [+ 0.3,+ 0.22,+ 0.21+ ],+ [+ 0.43,+ 0.212,+ 0.198,+ {+ "sharp": true+ }+ ],+ [+ 0.62,+ 0.148,+ 0.138+ ],+ [+ 0.84,+ 0.085,+ 0.072+ ],+ [+ 1.0,+ 0.06,+ 0.052+ ]+ ],+ "caps": [+ "none",+ "dome"+ ],+ "colors": {+ "arcs": [+ {+ "from": 0,+ "to": 52,+ "color": "#57513f"+ },+ {+ "from": 128,+ "to": 180,+ "color": "#f2ead7"+ }+ ]+ }+ },+ {+ "chain": "tail",+ "material": "fur_tail",+ "sides": 10,+ "profile": [+ [+ 0,+ 0.11,+ 0.11+ ],+ [+ 0.35,+ 0.135,+ 0.14+ ],+ [+ 0.7,+ 0.1,+ 0.105+ ],+ [+ 1,+ 0.04,+ 0.04+ ]+ ],+ "caps": [+ "none",+ "dome"+ ],+ "colors": {+ "arcs": [+ {+ "from": 0,+ "to": 52,+ "color": "#57513f"+ }+ ]+ }+ },+ {+ "chain": "LFront",+ "material": "fur_leg",+ "sides": 9,+ "profile": [+ [+ 0,+ 0.132,+ 0.15+ ],+ [+ 0.42,+ 0.101,+ 0.109+ ],+ [+ 0.85,+ 0.078,+ 0.08+ ],+ [+ 1,+ 0.074,+ 0.048+ ]+ ],+ "caps": [+ "none",+ "dome"+ ],+ "ring_step": 0.055+ },+ {+ "chain": "LBack",+ "material": "fur_leg",+ "sides": 9,+ "profile": [+ [+ 0,+ 0.112,+ 0.142+ ],+ [+ 0.25,+ 0.106,+ 0.148,+ {+ "exp": 2.5+ }+ ],+ [+ 0.45,+ 0.096,+ 0.115,+ {+ "exp": 2.2+ }+ ],+ [+ 0.82,+ 0.081,+ 0.083+ ],+ [+ 1,+ 0.076,+ 0.048+ ]+ ],+ "caps": [+ "none",+ "dome"+ ],+ "ring_step": 0.055+ }+ ],+ "parts": [+ {+ "type": "fin",+ "host": "Skull",+ "material": "ear",+ "thickness": 0.02,+ "conform": false,+ "anchor": {+ "chain": "head",+ "t": 0.22,+ "around": 38+ },+ "udir": [+ 0.25,+ 0.1,+ -0.95+ ],+ "vdir": [+ 0.15,+ 1,+ 0.05+ ],+ "points": [+ [+ -0.025,+ 0+ ],+ [+ 0.12,+ 0.025+ ],+ [+ 0.055,+ 0.18+ ],+ [+ -0.055,+ 0.055+ ]+ ],+ "mirrored": true+ },+ {+ "type": "eye",+ "host": "Brow",+ "material": "eye",+ "size": 0.028,+ "anchor": {+ "chain": "head",+ "t": 0.4,+ "around": 62+ }+ },+ {+ "type": "spike",+ "host": "Nose",+ "offset": [+ 0,+ 0.005,+ 0.0+ ],+ "dir": [+ 0,+ -0.08,+ 1+ ],+ "segments": [+ {+ "len": 0.045,+ "r": 0.04+ }+ ],+ "sides": 8,+ "material": "nose"+ },+ {+ "type": "paw",+ "host": "LFrontToe",+ "material": "fur_paw",+ "size": [+ 0.206,+ 0.151,+ 0.076+ ],+ "mirrored": true+ },+ {+ "type": "paw",+ "host": "LBackToe",+ "material": "fur_paw",+ "size": [+ 0.22,+ 0.158,+ 0.076+ ],+ "mirrored": true+ }+ ],+ "animations": {+ "idle": {+ "duration": 2.2,+ "loop": true,+ "tracks": {+ "NeckB": {+ "rx": [+ [+ 0,+ -2+ ],+ [+ 0.5,+ 3+ ],+ [+ 1,+ -2+ ]+ ]+ },+ "Skull": {+ "rx": [+ [+ 0,+ 2+ ],+ [+ 0.5,+ -2+ ],+ [+ 1,+ 2+ ]+ ]+ },+ "Tail1": {+ "ry": [+ [+ 0,+ 8+ ],+ [+ 0.5,+ -8+ ],+ [+ 1,+ 8+ ]+ ]+ },+ "Tail2": {+ "ry": [+ [+ 0,+ -6+ ],+ [+ 0.25,+ 6+ ],+ [+ 0.75,+ -9+ ],+ [+ 1,+ -6+ ]+ ]+ },+ "Hips": {+ "ty": [+ [+ 0,+ 0+ ],+ [+ 0.5,+ 0.012+ ],+ [+ 1,+ 0+ ]+ ]+ }+ }+ },+ "move": {+ "duration": 0.95,+ "loop": true,+ "mirror_phase": 0.5,+ "tracks": {+ "LFrontRoot": {+ "rx": [+ [+ 0,+ -26+ ],+ [+ 0.5,+ 28+ ],+ [+ 1,+ -26+ ]+ ]+ },+ "LFrontElbow": {+ "rx": [+ [+ 0,+ 12+ ],+ [+ 0.25,+ 30+ ],+ [+ 0.5,+ -6+ ],+ [+ 1,+ 12+ ]+ ]+ },+ "LFrontWrist": {+ "rx": [+ [+ 0,+ -12+ ],+ [+ 0.35,+ -30+ ],+ [+ 0.6,+ 8+ ],+ [+ 1,+ -12+ ]+ ]+ },+ "LBackRoot": {+ "rx": [+ [+ 0,+ 24+ ],+ [+ 0.5,+ -22+ ],+ [+ 1,+ 24+ ]+ ]+ },+ "LBackKnee": {+ "rx": [+ [+ 0,+ -10+ ],+ [+ 0.3,+ -32+ ],+ [+ 0.6,+ 10+ ],+ [+ 1,+ -10+ ]+ ]+ },+ "LBackHock": {+ "rx": [+ [+ 0,+ 8+ ],+ [+ 0.4,+ 26+ ],+ [+ 0.7,+ -6+ ],+ [+ 1,+ 8+ ]+ ]+ },+ "Hips": {+ "ty": [+ [+ 0,+ 0+ ],+ [+ 0.25,+ 0.024+ ],+ [+ 0.5,+ 0+ ],+ [+ 0.75,+ 0.024+ ],+ [+ 1,+ 0+ ]+ ]+ },+ "NeckB": {+ "rx": [+ [+ 0,+ 3+ ],+ [+ 0.5,+ -3+ ],+ [+ 1,+ 3+ ]+ ]+ },+ "Tail1": {+ "ry": [+ [+ 0,+ 9+ ],+ [+ 0.5,+ -9+ ],+ [+ 1,+ 9+ ]+ ]+ }+ }+ }+ }+}\ No newline at end of filediff --git a/calibration/wolf_red.json b/calibration/wolf_red.jsonnew file mode 100644index 0000000..f8eaabe--- /dev/null+++ b/calibration/wolf_red.json@@ -0,0 +1,734 @@+{+ "name": "wolf_red (known-bad sample)",+ "palette": {+ "fur": {+ "color": "#b9ae99",+ "rough": 0.95+ },+ "nose": {+ "color": "#16161a",+ "rough": 0.6+ },+ "ear": {+ "color": "#57513f",+ "rough": 0.95+ },+ "eye": {+ "color": "#c08a2a",+ "rough": 0.25+ }+ },+ "joints": {+ "TailTip": [+ 0,+ 0.6,+ -1.47+ ],+ "Tail2": [+ 0,+ 0.73,+ -1.07+ ],+ "Tail1": [+ 0,+ 0.83,+ -0.76+ ],+ "Hips": [+ 0,+ 0.8,+ -0.4+ ],+ "Spine": [+ 0,+ 0.835,+ -0.02+ ],+ "Chest": [+ 0,+ 0.81,+ 0.34+ ],+ "NeckB": [+ 0,+ 0.9,+ 0.52+ ],+ "Skull": [+ 0,+ 1.07,+ 0.68+ ],+ "Brow": [+ 0,+ 1.09,+ 0.86+ ],+ "Muzzle": [+ 0,+ 1.03,+ 1.1+ ],+ "Nose": [+ 0,+ 1.0,+ 1.28+ ],+ "LFrontRoot": [+ 0.01,+ 0.6,+ 0.3+ ],+ "LFrontElbow": [+ 0.15,+ 0.46,+ 0.25+ ],+ "LFrontWrist": [+ 0.155,+ 0.16,+ 0.3+ ],+ "LFrontToe": [+ 0.16,+ 0.035,+ 0.44+ ],+ "LBackRoot": [+ 0.01,+ 0.62,+ -0.38+ ],+ "LBackKnee": [+ 0.155,+ 0.44,+ -0.26+ ],+ "LBackHock": [+ 0.165,+ 0.2,+ -0.44+ ],+ "LBackToe": [+ 0.17,+ 0.035,+ -0.27+ ],+ "Rump": [+ 0,+ 0.78,+ -0.56+ ],+ "TailRoot": [+ 0,+ 0.815,+ -0.5+ ]+ },+ "chains": {+ "axis": [+ "Rump",+ "Hips",+ "Spine",+ "Chest",+ "NeckB",+ "Skull",+ "Brow",+ "Muzzle",+ "Nose"+ ],+ "tail": [+ "TailRoot",+ "Tail1",+ "Tail2",+ "TailTip"+ ],+ "LFront": [+ "LFrontRoot",+ "LFrontElbow",+ "LFrontWrist",+ "LFrontToe"+ ],+ "LBack": [+ "LBackRoot",+ "LBackKnee",+ "LBackHock",+ "LBackToe"+ ]+ },+ "attach": {+ "tail": "Hips",+ "LFront": "Chest",+ "LBack": "Hips"+ },+ "mirror": [+ "LFront",+ "LBack"+ ],+ "volumes": [+ {+ "chain": "axis",+ "material": "fur",+ "frame": "up",+ "sides": 16,+ "profile": [+ [+ 0.0,+ 0.12,+ 0.135+ ],+ [+ 0.07,+ 0.16,+ 0.185,+ {+ "bias": -0.06+ }+ ],+ [+ 0.23,+ 0.185,+ 0.22,+ {+ "bias": -0.1+ }+ ],+ [+ 0.4,+ 0.195,+ 0.225,+ {+ "bias": -0.12+ }+ ],+ [+ 0.52,+ 0.16,+ 0.185,+ {+ "bias": -0.06+ }+ ],+ [+ 0.61,+ 0.142,+ 0.156+ ],+ [+ 0.66,+ 0.14,+ 0.148+ ],+ [+ 0.72,+ 0.152,+ 0.15+ ],+ [+ 0.78,+ 0.155,+ 0.146+ ],+ [+ 0.85,+ 0.104,+ 0.094+ ],+ [+ 0.925,+ 0.072,+ 0.062+ ],+ [+ 1.0,+ 0.054,+ 0.048+ ]+ ],+ "caps": [+ "dome",+ "dome"+ ],+ "colors": {+ "arcs": [+ {+ "from": 0,+ "to": 52,+ "color": "#57513f"+ },+ {+ "from": 128,+ "to": 180,+ "color": "#f2ead7"+ }+ ]+ }+ },+ {+ "chain": "tail",+ "material": "fur",+ "sides": 10,+ "profile": [+ [+ 0,+ 0.095,+ 0.095+ ],+ [+ 0.35,+ 0.095,+ 0.098+ ],+ [+ 0.7,+ 0.075,+ 0.077+ ],+ [+ 1,+ 0.03,+ 0.03+ ]+ ],+ "caps": [+ "none",+ "dome"+ ],+ "colors": {+ "arcs": [+ {+ "from": 0,+ "to": 52,+ "color": "#57513f"+ }+ ]+ }+ },+ {+ "chain": "LFront",+ "material": "fur",+ "sides": 9,+ "profile": [+ [+ 0,+ 0.088,+ 0.118+ ],+ [+ 0.42,+ 0.058,+ 0.068+ ],+ [+ 0.85,+ 0.046,+ 0.048+ ],+ [+ 1,+ 0.042,+ 0.03+ ]+ ],+ "caps": [+ "none",+ "dome"+ ]+ },+ {+ "chain": "LBack",+ "material": "fur",+ "sides": 9,+ "profile": [+ [+ 0,+ 0.1,+ 0.132+ ],+ [+ 0.4,+ 0.062,+ 0.075+ ],+ [+ 0.82,+ 0.048,+ 0.05+ ],+ [+ 1,+ 0.044,+ 0.03+ ]+ ],+ "caps": [+ "none",+ "dome"+ ]+ }+ ],+ "parts": [+ {+ "type": "fin",+ "host": "Skull",+ "material": "ear",+ "thickness": 0.02,+ "anchor": {+ "chain": "axis",+ "t": 0.7,+ "around": 38+ },+ "udir": [+ 0.25,+ 0.1,+ -0.95+ ],+ "vdir": [+ 0.15,+ 1,+ 0.05+ ],+ "points": [+ [+ -0.025,+ 0+ ],+ [+ 0.12,+ 0.025+ ],+ [+ 0.055,+ 0.18+ ],+ [+ -0.055,+ 0.055+ ]+ ],+ "mirrored": true+ },+ {+ "type": "eye",+ "host": "Brow",+ "material": "eye",+ "size": 0.028,+ "anchor": {+ "chain": "axis",+ "t": 0.795,+ "around": 42+ }+ },+ {+ "type": "spike",+ "host": "Nose",+ "offset": [+ 0,+ 0.005,+ 0.0+ ],+ "dir": [+ 0,+ -0.08,+ 1+ ],+ "segments": [+ {+ "len": 0.045,+ "r": 0.04+ }+ ],+ "sides": 8,+ "material": "nose"+ },+ {+ "type": "paw",+ "host": "LFrontToe",+ "material": "fur",+ "size": [+ 0.165,+ 0.12100000000000001,+ 0.060500000000000005+ ],+ "mirrored": true+ },+ {+ "type": "paw",+ "host": "LBackToe",+ "material": "fur",+ "size": [+ 0.17600000000000002,+ 0.12650000000000003,+ 0.060500000000000005+ ],+ "mirrored": true+ }+ ],+ "animations": {+ "idle": {+ "duration": 2.2,+ "loop": true,+ "tracks": {+ "NeckB": {+ "rx": [+ [+ 0,+ -2+ ],+ [+ 0.5,+ 3+ ],+ [+ 1,+ -2+ ]+ ]+ },+ "Skull": {+ "rx": [+ [+ 0,+ 2+ ],+ [+ 0.5,+ -2+ ],+ [+ 1,+ 2+ ]+ ]+ },+ "Tail1": {+ "ry": [+ [+ 0,+ 8+ ],+ [+ 0.5,+ -8+ ],+ [+ 1,+ 8+ ]+ ]+ },+ "Tail2": {+ "ry": [+ [+ 0,+ -6+ ],+ [+ 0.25,+ 6+ ],+ [+ 0.75,+ -9+ ],+ [+ 1,+ -6+ ]+ ]+ },+ "Hips": {+ "ty": [+ [+ 0,+ 0+ ],+ [+ 0.5,+ 0.012+ ],+ [+ 1,+ 0+ ]+ ]+ }+ }+ },+ "move": {+ "duration": 0.95,+ "loop": true,+ "mirror_phase": 0.5,+ "tracks": {+ "LFrontRoot": {+ "rx": [+ [+ 0,+ -26+ ],+ [+ 0.5,+ 28+ ],+ [+ 1,+ -26+ ]+ ]+ },+ "LFrontElbow": {+ "rx": [+ [+ 0,+ 12+ ],+ [+ 0.25,+ 30+ ],+ [+ 0.5,+ -6+ ],+ [+ 1,+ 12+ ]+ ]+ },+ "LFrontWrist": {+ "rx": [+ [+ 0,+ -12+ ],+ [+ 0.35,+ -30+ ],+ [+ 0.6,+ 8+ ],+ [+ 1,+ -12+ ]+ ]+ },+ "LBackRoot": {+ "rx": [+ [+ 0,+ 24+ ],+ [+ 0.5,+ -22+ ],+ [+ 1,+ 24+ ]+ ]+ },+ "LBackKnee": {+ "rx": [+ [+ 0,+ -10+ ],+ [+ 0.3,+ -32+ ],+ [+ 0.6,+ 10+ ],+ [+ 1,+ -10+ ]+ ]+ },+ "LBackHock": {+ "rx": [+ [+ 0,+ 8+ ],+ [+ 0.4,+ 26+ ],+ [+ 0.7,+ -6+ ],+ [+ 1,+ 8+ ]+ ]+ },+ "Hips": {+ "ty": [+ [+ 0,+ 0+ ],+ [+ 0.25,+ 0.024+ ],+ [+ 0.5,+ 0+ ],+ [+ 0.75,+ 0.024+ ],+ [+ 1,+ 0+ ]+ ]+ },+ "NeckB": {+ "rx": [+ [+ 0,+ 3+ ],+ [+ 0.5,+ -3+ ],+ [+ 1,+ 3+ ]+ ]+ },+ "Tail1": {+ "ry": [+ [+ 0,+ 9+ ],+ [+ 0.5,+ -9+ ],+ [+ 1,+ 9+ ]+ ]+ }+ }+ }+ }+}\ No newline at end of filediff --git a/cards/00_START.md b/cards/00_START.mdnew file mode 100644index 0000000..828f450--- /dev/null+++ b/cards/00_START.md@@ -0,0 +1,28 @@+# 00 START (read first after unzip — the only always-on rules)++## The pipeline in one line++```+order → interview (≤2 questions) → silhouette brief → LOW: design FREE + two gates → MID (2 rounds) → HIGH (1 round) → SHIP (scripted delivery + closing dialogue)+```++## Iron laws++1. **Form beats obedience.** Every rule below exists to protect form quality; if following a rule would make the creature tamer, the rule loses. Edits whose only purpose is to make a number match a declaration are forbidden.+2. **You never grade your own thumbnails.** Every gate is read by a context-free agent you spawn who knows nothing about the order. Its verbatim answer is the verdict.+3. **Same symptom failed twice = no third tweak.** Restart that view/element from a DIFFERENT concept. If the restart also fails, ship your best version and write one honest DEVLOG line about what didn't land.+4. **The signature part gets real geometry at LOW.** A giant whose identity is its fists gets fingers, knuckles and a planted pose in the silhouette round — not a placeholder sphere. Budget follows 6:3:1: the 6-level element gets 6-level geometry.+5. **Materials are named per PART** (`skin_torso`, `fur_leg`, `eye`, `tusk`…) — the area rulers identify parts by material name.+6. **Engine floors block builds** — mechanical checks refuse broken geometry and fake attacks (`BLOCK:` lines say exactly what; `warn:` lines are measures for YOUR judgment; `info:` lines narrate what the compiler actually did). Fix and rebuild; a refused build costs no round.+7. **The customer is a non-designer.** After the interview, never ask them anything until the closing dialogue (card 04).+8. **Nothing is ever uploaded without the user's explicit yes, this session.** No background uploads, no test uploads, ask for every creature — card 04 has the flow.++## Environment self-check (run verbatim)++```bash+bash setup.sh # deps + red/green ruler calibration; must print "calibrate OK"+```++## Closing ledger (one DEVLOG line at delivery)++`gates: ID pass@r? PUNCH pass@r? | restarts: none-or-what | unresolved: none-or-what`diff --git a/cards/01_LOW.md b/cards/01_LOW.mdnew file mode 100644index 0000000..30273b7--- /dev/null+++ b/cards/01_LOW.md@@ -0,0 +1,50 @@+# 01 LOW — design free, then two gates (the big-form stage)++## 1. Interview (≤2 questions; skip any already answered)++Q1 Temperament: "What's the first feeling this creature should give?" (cute / solid / scary / free text)+Q2 Role: minion / NPC / boss → loads `harness/presets/<role>.json` (tri budget + animation list).++## 2. Silhouette brief (a few lines, then freeze)++Translate the order into the brief the gates will test against — identity ("reads as: tree + giant-proportioned humanoid"), feel ("heavy, crushing"), the ONE signature that must survive shrinking, and which view carries the identity. No method, no numbers you can't check.++## 3. Design FREE++Build the creature with the engine (syntax: `cards/SYNTAX.md`) exactly as you see fit — your own judgment, your own process. Only the pit-map applies (engine-local facts, not design rules):++- Anatomically independent masses get their OWN volumes, overlapping their neighbours (mane, shoulder, chest slab, head). Radius wiggle inside one tube reads as soft sausage, not as blocks.+- Wings spread flat in one plane vanish from the side — give them sweep-back. Every view needs a designed silhouette; a straight-line view is a dead view.+- The bind pose IS the pose. Creatures never stand bolt upright in a T-pose; plant the weight.+- Curved things (tusks, trunks, horns) are `curve`; membranes (wings, frills, sails) are `membrane` — don't fake either with straight spikes or flat plates.+- **Bends belong to JOINTS.** An arm that must flex needs its elbow joint placed where the bend lives; radius wiggle inside a straight tube gives you a bent sausage, not an elbow. Place the skeleton for the pose you want.++Measure every build:+```bash+node engine/cli.js spec.json out/creature.glb+node harness/silmetrics.mjs out/creature.glb out/rN+python3 harness/maskmetrics.py out/rN out/rN/sil_front.png out/rN/sil_side.png out/rN/sil_top.png out/rN/sil_hero.png+```+The report measures; YOU judge. Flags worth eyes: `sq_fill` (silhouette volume in a 1:1 frame), `mirror_sym` (only the FRONT view may be symmetric; wing pairs stagger even there), `straight_max` (plank-limb detector).++## 4. Gate 1 — RECOGNISED (all four views)++Spawn a context-free reader agent (a fresh subagent given NOTHING but the images) with exactly this task:++> Look at these images one at a time, answering only from what you SEE.+> 1) [thumb24 of the identity view] What FEELING does this shape give — heavy/stable, fast/agile, sharp/menacing, floating? One phrase.+> 2-5) [thumb48 of front / side / top / hero] What is this? What parts can you make out? Does this view read as a real creature, or as an abstract shape/nothing?++Judge the verbatim answers against the brief: identity wrong → repair (biggest shapes first). **Any view read as "abstract/nothing/a stick" fails the whole gate.** Feel mismatch → repair. The verdict IS the work order. Budget: 2 repair rounds, then iron law 3 (concept restart).++## 5. Gate 2 — PUNCHIER (after Gate 1; all four views must stay readable)++LOW is not done when it's recognisable — it's done when it's EXAGGERATED. Up to 2 rounds; each round may ONLY make the silhouette bolder: push the extreme proportion further, harden breaks, deepen negative space, exaggerate the signature. Spawn a fresh reader; show the PREVIOUS round's identity-view silhouette and the CURRENT one:++> Two silhouettes of a creature. Which is punchier — more striking, more tension? One sentence why.++Reader picks the old one = the round is reverted; try a different push or stop. Reader picks the new one and all four views still read = LOW passes. Skeleton and main volumes lock.++## 6. Outputs++`spec.json`, `creature.glb`, `out/rN/` per round (sils, thumbs, metrics, archived spec), reader verdicts verbatim in `log.md`.diff --git a/cards/02_MID.md b/cards/02_MID.mdnew file mode 100644index 0000000..bd69c31--- /dev/null+++ b/cards/02_MID.md@@ -0,0 +1,98 @@+# 02 MID (budget 2 rounds | build: all parts, flat colour, ZERO new bones)++Output: every part — ears, horns, claws, eyes, fins, shell spikes, paws — riding+bones LOW already placed, or anchored to volume surfaces. No material detail, no+animation. MID's question is: **do the key parts READ as what they are?**++## The part gate — whitelist blind-reads, identity only++Not every part gets examined. The whitelist:++1. **the face — always** (if the creature has one),+2. **the signature part** (from the brief),+3. **any part the order names** ("scissor hands" → the hands).++For each whitelisted part, render it ALONE and blind-read it:++```bash+# temp spec: copy the real spec, keep only this part (+ its host chain volume+# if the part is meaningless without it), add "qa_isolate": true+node engine/cli.js out/qa_face.json out/qa_face.glb+node harness/silmetrics.mjs out/qa_face.glb out/qa_face+```++Show the four thumb48s to a context-free reader with EXACTLY this and no more:++> What is this? Answer with the name of the thing or body part you see.++Judge the verbatim answer: the part's name (or an unmistakable synonym) = pass.+**"a ball", "a blob", "an egg", "nothing" = fail** — a siren's face that reads+as a sphere has no face. Identity is the only question at MID; feel and beauty+were LOW's business, colour is HIGH's.++Two repair rounds per failed part, then iron law 3 (different concept for that+part, not a third tweak).++## Edit vocabulary (what a MID repair is allowed to be)++- **swap the local shape**: replace the primitive-ish mass with structured+ geometry — brow + muzzle + jaw instead of a head-sphere; knuckles + fingers+ instead of a fist-ball. **No naked sphere / cube / cone may remain visible+ on a whitelisted part.**+- **fold and carve**: concave sections, `sharp` profile breaks on the profile+ rows, a lower `smooth_angle` on that volume (spec default 50°), plates and+ spikes that cut the outline. **`faceted` on a VOLUME is a BLOCK**+ (`faceted_body`): it shatters an 800-triangle torso into 800 shards, and AO+ bakes that mess into COLOR_0 where no relighting can reach it. Parts — fins,+ spikes, claws, crystal, armour — may still be faceted freely.+- **bend the pose**: elbows/knees bend at MID — place the bend at its JOINT+ (`joints` positions form the bind pose). Straight arms read as dead arms.+ Mirrored pairs may stagger via `joints_R` (grow symmetric, pose asymmetric) —+ **but only by a few centimetres.** The twin's mesh is grown on the LEFT bone+ path and then translated onto the right joints, so a large offset shears the+ volume rather than posing it (a right thigh at 40% of the left's depth, width+ untouched — invisible from the left, invisible in the build log). Past ~10% of+ the limb's length it starts squashing and `mirror_distortion` warns; past ~35%+ it BLOCKs. For a genuinely different pose, take that limb OUT of `mirror` and+ author it as its own chain.++## Do (layout)++1. **Signature presence**: silhouette share is a BUDGET check — the signature+ part hits its declared share (judge measures by material name); nothing else+ needs a share test.+2. **6:3:1 lands**: geometry budget follows the hierarchy; the 6-part gets+ 6-level structure.+3. **Busy-vs-calm**: on one part, one edge detailed, the other long and clean.+4. **Declared connections touch**: masses that must read as one body declare+ `"touch": [["torso","tail"]]` — the engine BLOCKS if they don't overlap.+5. **Read the warns**: `part_overlap` lines flag parts sitting inside other+ parts (the self-intersecting-fist class). A warn is a measure, not a law —+ look at the render and decide.++## Don't (blood of previous runs)++- **Mirrored inward-tilted parts cross at the midline**: length × sin(tilt) vs+ the left-right gap — do the arithmetic BEFORE placing horns/fins.+- **Parts must not cover focals**: a horn base once covered the eye. After+ placing anything big, re-check the focal view.+- **Ride the right bone**: jaw/tongue ride the skull, or they detach in motion.+- **Every part must TOUCH its host** — `part_attachment` BLOCKs a part whose+ nearest point still stands clear of the host surface. Tusks, trunks and plates+ used to float with the build reporting all green, and only a human eye caught+ them. The first third of a root is meant to be buried; that is what hides the+ seam. A part that cannot name what it touches is not attached.+- Eyes/ears anchor to the HEAD volume surface: `"anchor":+ {"chain":"head","t":0.40,"around":62}` — `around` in degrees from the top of+ the section (0=spine, 90=side, 180=belly). Wolf-class eyes sit at 55–70.+- On an anchored plate the host surface wins by default: the plate is snapped+ onto the surface normal and the direction you wrote survives as a reported+ difference. `"conform": false` when that written direction was deliberate.++## Stage-end gate++- Machine: build green + MID-stage claims (`part_exists` / `part_visible` /+ `part_signature` / `share_hierarchy` / `focal_contrast`).+- Whitelist blind-reads all passed.+- Human look #2: focal distribution right? part-to-body seams clean?+- Pass = part layout locks.diff --git a/cards/03_HIGH.md b/cards/03_HIGH.mdnew file mode 100644index 0000000..627f853--- /dev/null+++ b/cards/03_HIGH.md@@ -0,0 +1,78 @@+# 03 HIGH (budget 1 round | build: colour + three animations)++## Colour — you choose freely; five norms bound the choice++Pick the palette yourself, from the creature's story. The norms:++1. **One high-saturation MAIN colour, spent on the signature part.** Saturation+ is a spotlight; if everything is saturated, nothing is.+2. **One secondary colour** for the big masses — quieter than the main.+3. **The ACCENT stays under 5%** of the surface (eye glow, claw tips, markings)+ — the memory spark. One accent temperature, not two. The 5% caps the ACCENT+ alone; it is not a cap on how much of the creature carries saturated colour —+ norm 4 sets that, and its floor sits well above 5%.+4. **Saturated area: 10%–34% — measured, not judged by eye.** The+ `saturation_area` claim counts the share of the view carrying HSV saturation+ ≥ 0.50, read on the UNLIT baked vertex colour, so brightness, AO and lighting+ cannot skew it. Below the floor the creature reads as a grey mass; above the+ ceiling saturation stops working as a spotlight. The band rules HOW MUCH,+ never WHERE — which surfaces carry the loud colour is your call. It agrees+ with norm 1: one main colour on the signature plus its supporting bands lands+ mid-band (the wolf example measures 26.0%). Out of band, raise or drop+ saturation on a mass that deserves the attention; do not tint everything.+5. **Brightness floor — do not crush to black.** The judge measures the beauty+ render's median luminance; a "dark" creature reads by VALUE STEPS between+ its masses, not by making everything dark. If the render medians below the+ floor, lift the mid masses, keep the darks only where a step needs them.++The engine bakes **per-vertex AO at compile** (crevices, pits, undersides+darken automatically — that's the "solid" look). The floor is measured AFTER+AO; never fight AO by flattening your colours, and never disable it to pass+(`"ao": false` exists only for debug builds).++Vertex colours come from two places. Per volume, `colors.arcs` bands the+section over that material's base colour (0°=spine, 180°=belly) — bands must+follow the form, spine band darkening the top plane, belly band lifting the+underside. Spec-level, ONE `shading` block ramps value over the WHOLE body's Y+range and lays one grain, on EVERY mesh — volumes, paws, ears, eyes, horns —+so the same numbers mean the same thing on an upright leg and a horizontal+torso, and no part reads as a sticker. Defaults: `gradient {top 0.30, bottom+-0.88}`, `noise {size 0.018, amount 0.26}`; `noise.size` is a fraction of the+model diagonal, so the grain scales with the creature. `colors.gradient` and+`colors.noise` are ignored now — the compiler says so in an `info:` line.+UV atlas is opt-in (`"keep_uv": true`) for downstream texture bakes; by default+the shipped file carries colour in vertices and stays lean.++## Animation — three, always: `idle`, `move`, `attack`++- The bar for idle/move: skinned, actually moving, no clipping, no explosions.+- **`attack` must COMMIT FORWARD — but it does not have to lunge.** The engine+ CPU-skins the clip and BLOCKS (`attack_reach`) only when nothing commits at the+ space in front of the body. Two ways to satisfy it, either is enough:+ **REACH** — something ends up ≥15% of the body span past the bind-pose front;+ **SWING** — some part travels forward ≥45% of its own length. So a creature+ planted on the spot, winding a foreleg, a tail or a weapon BACK and sweeping it+ FORWARD, passes. A ±20° twitch does not, and neither does a sideways sweep that+ never crosses toward the front. Wind up BACK first, then strike FORWARD.+- Channels stack: several tracks bending one segment = keep total bend modest,+ or `anim_integrity` blocks (folds / >3× edge stretch). Reduce bend or add a+ joint; don't fight the check.++```jsonc+"animations": {+ "move": { "duration":0.95, "loop":true, "mirror_phase":0.5,+ "tracks": { "LFrontRoot": {"rx":[[0,-26],[0.5,28],[1,-26]]} } },+ "attack": { "duration":0.7, "loop":false, "tracks": {+ "Chest": {"rx":[[0,0],[0.25,-14],[0.5,22],[1,0]]}, // wind up, strike+ "Root": {"tz":[[0,0],[0.25,-0.1],[0.5,0.9],[1,0]]} } } // …and LUNGE+}+```++## Stage-end gate++- Machine: full claims re-run (styles, `rig_skinned`, `anim_named` incl.+ attack, motion amplitude, tri budget) — save the claims output, 04 ships it+ as the gate stamp.+- Human look #3 (final): value readability + play all three animations once.++Then read `cards/04_SHIP.md` — delivery and closing are scripted.diff --git a/cards/04_SHIP.md b/cards/04_SHIP.mdnew file mode 100644index 0000000..2896e6c--- /dev/null+++ b/cards/04_SHIP.md@@ -0,0 +1,93 @@+# 04 SHIP (scripted delivery + closing dialogue + optional community publish)++## Red lines (absolute)++- **Never upload anything without the user's explicit YES, this session.**+ Not to test, not in the background, not because a card says the flow exists.+- **Ask about sharing for every creature**, even if the user shared the last one.+- **Once they say yes, RUN the upload. Always try it first.** Do not decide in+ advance that this environment cannot reach the network — cloud sandboxes,+ Cowork sessions and CI runners frequently can. Run `publish.mjs`, then answer+ from what it printed. ❌ "in a sandbox you can only upload manually" — never+ say this. ✅ "try the upload, fall back to the link if it fails."+- The web page `gobkit.com/community/upload` is the BACKUP path only, and it is+ offered ONLY after a real attempt came back `blocked`.++## 1. Gate stamp (real results only)++Serialize the checks you actually ran into `delivery/gate.json`:++```json+{ "passed": true, "checks": [ {"name":"anim_integrity","passed":true},+ {"name":"attack_reach","passed":true}, {"name":"faceted_body","passed":true},+ {"name":"saturation_area","passed":true}, {"name":"gate1_recognised","passed":true},+ {"name":"gate2_punchier","passed":true} ] }+```++Never invent a line. If a check didn't run, it isn't in the file.++## 2. Names, then delivery++Ask in the USER'S language, exactly two questions, in this order (they name it+and sign it BEFORE any talk of sharing — ownership first):++> Give your monster a name? (Enter = <working name>)+> Your signature? Asked once — auto-filled from now on. (Enter = anonymous)++The signature question is skipped when `~/.anyCreature.json` exists — read+`{"author": "..."}` from it; on first answer, write it there.++```bash+python3 harness/deliver.py out/<name>.glb delivery/ <name> \+ --title "<their name>" --author "<signature>" --gate delivery/gate.json+```++This stamps name + signature + gate INTO the GLB (`asset.copyright`,+`extras.monster` — they travel with the file forever), then packs: stamped+`.glb`, offline showroom `_viewer.html`, `hero.png`/`hero.jpg` (auto-framed,+no label card in shot), and `upload/` (the backup pack). Confirm the viewer+opens. Echo one line:++> "<Name>" by <signature> — written into the model.++## 3. The share ask (LAST, after they've seen their name on it)++> Share it to the Gobkit community? Uploading releases it under CC0, permanently —+> anyone can download, use and remix it. [yes / no]++That one sentence IS the licence consent — no legal recital. On **no**: reply+"All files are in delivery/ — say the word if you ever want to share it." and+STOP. On **yes**:++```bash+node harness/publish.mjs delivery/<name>.glb delivery/hero.png \+ --title "<their name>" --creator "<signature>"+```++**`hero.png` is not optional.** A submission without an image is not rejected,+but it will not list automatically — it sits waiting for a human reviewer. That+is the one common reason a creature stalls after a successful upload. Pass it+every time.++It re-stamps `extras.license = CC0-1.0` (consent just given) and POSTs to the+endpoint in `harness/gobkit.json`. One JSON line comes back — answer from it,+using the SERVER's title/creator (what the wall actually shows):++| result | tell the user (their language, one line) |+|---|---|+| `published` | ✅ Published: "<title>" by <creator> → <share_url> |+| `pending_review` | ⚠ Uploaded — a reviewer is checking it; it will appear shortly. (no further explanation) |+| `blocked` | The upload pack is ready in `delivery/upload/` — open https://gobkit.com/community/upload and drag `creature.glb` in. No account, no key needed. (state it as the next step, NOT as an error — nothing is broken and nothing was lost) |+| `error` | The server answered and refused — read its message out verbatim, then offer the same backup page. |++**Reading a `blocked` result.** The submit endpoint always answers in JSON, so+an **HTTP 403 is a filtered network, never a key problem** — 403 is not one of+the endpoint's own answers. A non-JSON body means a proxy or captive portal+replied instead of the server. `publish.mjs` already classifies all of these as+`blocked`; do not re-diagnose them as authentication failures, and never tell+the user to fetch or change a key.++## 4. Closing ledger++One DEVLOG line (format in card 00) + the delivery checklist: glb, viewer,+heroes, spec JSON, gate.json, DEVLOG.diff --git a/cards/SYNTAX.md b/cards/SYNTAX.mdnew file mode 100644index 0000000..f702145--- /dev/null+++ b/cards/SYNTAX.md@@ -0,0 +1,109 @@+# Spec JSON — the whole language on one page++```jsonc+{+ "palette": { "skin_torso": {"color":"#8a8a80","rough":0.95}, ... }, // one material PER PART+ "sections": { "flute": [[1,0],[0.6,0.4],...] }, // named 2D outlines, CONCAVE allowed (bark, crescents)++ "smooth_angle": 50, // default: faces meeting at a vertex average when their normals sit within+ // this many degrees; the vertex splits only at a REAL crease. Override per+ // volume and per part. "faceted":true == smooth_angle 0.+ "shading": { "gradient":{"top":0.30,"bottom":-0.88}, // THE DEFAULTS. ONE value ramp over the+ "noise":{"size":0.018,"amount":0.26} }, // WHOLE body's Y range, on EVERY mesh,+ // parts included; noise.size = FRACTION OF THE MODEL DIAGONAL, not metres.+ "build": "rigid", // robots/constructs/golems/vehicles ONLY — lifts the faceted_body BLOCK++ "joints": {+ "Hips": [0, 0.9, 0], // absolute [x,y,z], y up, z forward+ "Chest": {"from":"Hips","fwd":0.1,"up":0.5}, // relational: fwd=+z up=+y side=+x+ "TailTip": {"from":"Tail2","dir":[0,-1,-0.4],"len":0.3},+ "LToe": {"from":"LKnee","fwd":0.1,"ground":0.03} // ground = absolute Y (feet)+ },+ "joints_R": { "RElbow": {"from":"Chest","side":-0.3,"up":0.25} },+ // optional: reposition auto-mirrored R* joints — pairs GROW symmetric but the+ // bind POSE staggers (raised right arm); the mirrored skin follows its joints.+ // A FEW CENTIMETRES ONLY. The twin's mesh is grown on the LEFT bone path and+ // then dragged onto the right joints by translation, so a large offset shears+ // the volume instead of posing it: past ~10% of the limb's length it starts+ // squashing, past ~35% the right thigh comes out 40% of the left's depth with+ // its width untouched. mirror_distortion BLOCKs that. For a genuinely+ // different pose, take the limb OUT of "mirror" and author it as its own chain.+ "chains": { "torso":["Hips","Spine","Chest"], "LArm":[...], ... },+ "attach": { "LArm":"Chest", "head":"Neck" }, // every non-root chain → its host joint+ "mirror": ["LArm","LLeg"], // auto right-side twins (joints, meshes, anims)+ "touch": [["torso","tail"]], // declared connections MUST overlap or BLOCK++ "volumes": [{+ "chain":"torso", "material":"skin_torso", "sides":14, "frame":"up",+ "profile":[[0,0.3,0.35], [0.6,0.42,0.5,{"bias":-0.1,"sharp":true}], [1,0.2,0.22]],+ // rows [t, half-width, half-height, opts]; exp 2.5-4=boxy slab; bias<0 belly-full;+ // sharp = hard silhouette break; "section":"flute" = use a named outline+ "smooth_angle": 30, // optional per-volume override, crisper creases+ // "faceted":true on a VOLUME is a BLOCK (faceted_body) — an 800-tri torso becomes 800 shards+ // and AO bakes the mess into COLOR_0. Break a body with "sharp" rows or a lower smooth_angle.+ "caps":["dome","dome"], "ring_step":0.05,+ "colors": { "arcs":[{"from":0,"to":52,"color":"#57513f"}] } // 0°=spine 180°=belly+ // arcs ONLY — colors.gradient / colors.noise are ignored (info: line); see "shading" above+ }],++ "parts": [+ { "type":"curve", "host":"Head", "material":"tusk", "mirrored":true, // CURVED horn/tusk/trunk+ "offset":[0.06,0,0.1], "dir":[0.3,-0.6,0.7], "sides":8,+ "segments":[ {"len":0.1,"r":0.035,"ahead":20}, {"len":0.1,"r":0.028,"rise":35},+ {"len":0.08,"r":0.015,"rise":30,"taper":true} ] },+ // steering is per-segment and ADDS UP down the chain. rise/fall/ahead/behind+ // pull the heading that many degrees toward that world axis; coil swings it in+ // the carried plane (rings, spirals); taper pinches the far end.+ // Four mild segments can finish somewhere you did not predict — the compiler+ // reports the accumulated total (info: ... accumulated to 123°). Read that line.++ { "type":"membrane", "name":"wing", "material":"wing_skin", "mirrored":true, // skin between rib chains+ "cusp":0.25, "along":8, "across":3,+ "ribs":[ {"chain":"LArm"}, {"chain":"LFing2"}, {"chain":"LFing3"}, {"chain":"LTrail"} ] },+ // along = samples down each rib · across = columns between neighbouring ribs+ // cusp = how deeply the trailing edge scoops · per-rib "shorten":0.2 pulls one rib in+ // Ribs run leading→trailing and the LAST one has to come back to the body.+ // Leave it out at the far end and the silhouette never encloses — it reads as+ // spread fingers, not one sheet. The compiler measures the root gap and warns.++ { "type":"fin", "host":"Skull", "material":"plate", "thickness":0.02, "mirrored":true,+ "anchor":{"chain":"head","t":0.4,"around":60}, // around: 0=spine 90=side 180=belly+ // ⚠ that mapping is the BODY chain's frame. `around` is read in the host+ // SECTION's frame, so on a chain running vertically (a leg) the same numbers+ // point elsewhere: 0=inner, 90=FRONT, 180=OUTER, 270=back. Aiming a plate at+ // the outside of a thigh with 90 lands it on the front. The compiler prints+ // the world direction each anchored part actually faces — read that line,+ // do not reason from this comment.+ "udir":[0,0,1], "vdir":[0,1,0], "points":[[0,0],[0.1,0.02],[0.05,0.15]],+ "faceted":true }, // PARTS may face freely (or set "smooth_angle") — only VOLUMES are blocked+ // by default the host surface wins: an anchored part is snapped flat onto the+ // surface normal, and the direction you wrote survives only as a reported+ // difference. Set "conform":false when that written direction was the point.++ { "type":"eye", "host":"Brow", "material":"eye", "size":0.028,+ "anchor":{"chain":"head","t":0.4,"around":62} }, // both eyes from one entry; side of head ≈55-70++ { "type":"paw", "host":"LToe", "material":"skin_fist", "size":[0.3,0.25,0.2], "mirrored":true }+ ],++ "animations": {+ "move": { "duration":0.95, "loop":true, "mirror_phase":0.5,+ "tracks": { "LFrontRoot": {"rx":[[0,-26],[0.5,28],[1,-26]]} } }, // rx..tz keys [fraction,deg|m]+ "attack": { "duration":0.7, "loop":false, "tracks": { ... } }+ // attack must COMMIT FORWARD — either route passes (attack_reach):+ // REACH: something ends ≥15% of the body span past the bind front, or+ // SWING: some part travels forward ≥45% of ITS OWN length.+ // You do NOT have to lunge. Planted on the spot, winding a limb, tail or+ // weapon BACK and sweeping it FORWARD counts. A sideways sweep does not —+ // the strike has to commit at the space in front of the body.+ },+ "style": "heavy", // ONLY if 1:1 segment rhythm is the design (relaxes the 50:50 gate)+ "ao": false, // debug only — vertex AO bakes automatically otherwise+ "keep_uv": true, // opt-in UV atlas (TEXCOORD_0) for downstream texture bakes+ "qa_isolate": true // MID part-isolation builds only: skips whole-body checks+}+```+`BLOCK:` = build refused (fix, costs no round) · `warn:` = a measure, you judge ·+`info:` = the compiler telling you what actually happened — always read them.+Shipped GLBs auto-merge primitives per material and export public bone names+(`LArm1Sh` convention) — internal spec names never leak.diff --git a/engine/cli.js b/engine/cli.jsnew file mode 100644index 0000000..66c696d--- /dev/null+++ b/engine/cli.js@@ -0,0 +1,57 @@+#!/usr/bin/env node+// ACS engine CLI. Author: Ariescar.+// usage: node cli.js <spec.json> <out.glb>+// Compiles the spec, runs all mechanical checks (any failure = exit 1, build+// blocked), then writes a skinned+animated GLB. Errors are structured and+// agent-readable: one line each, prefixed BLOCK:.+'use strict';+const fs = require('fs');+const { compile } = require('./core/compile.js');+const { buildSkeleton, inverseBindMatrices } = require('./core/skeleton.js');+const { compileAnims } = require('./core/anim.js');+const { runChecks } = require('./core/checks.js');+const { writeGLB } = require('./core/glb.js');++const [specPath, outPath] = process.argv.slice(2);+if (!specPath || !outPath) { console.error('usage: node cli.js <spec.json> <out.glb>'); process.exit(2); }++const spec = JSON.parse(fs.readFileSync(specPath, 'utf8'));+require('./core/relative.js').resolveJoints(spec); // relational joints → coordinates+const sk = buildSkeleton(spec); // also registers mirrored chains+const meshes = compile(spec);+for (const line of require('./core/compile.js').drainInfo())+ console.error('info: ' + line); // the compiler narrates what happened+const { fails, warns } = runChecks(spec, sk, meshes, null);+for (const w of warns) console.error('warn: ' + w); // measures, not laws — you judge+if (fails.length) {+ console.error('='.repeat(68));+ for (const f of fails) console.error('BLOCK: ' + f);+ console.error('='.repeat(68));+ console.error(`${fails.length} blocking issue(s) — build refused.`);+ process.exit(1);+}+const anims = compileAnims(spec, sk);+// UV atlas is opt-in ("keep_uv": true): without textures TEXCOORD_0 is dead+// weight in the shipped file, and AO now bakes into vertex colours instead+const uvInfo = spec.keep_uv ? require('./core/uv.js').applyUVs(meshes) : null;+const aoInfo = require('./core/ao.js').bakeAO(meshes, spec.ao); // vertex AO → COLOR_0 (ao:false skips)+// public identity: harness stamp + convention bone names (internal names stay authoring-side)+let hv = '0.0.0';+for (const vp of ['..', '.']) {+ try { hv = fs.readFileSync(require('path').join(__dirname, vp, 'VERSION'), 'utf8').trim(); break; } catch {}+}+const specName = require('path').basename(specPath).replace(/\.json$/, '');+const asset = {+ generator: `anyCreature v${hv}`,+ extras: { harness: 'anyCreature', harness_version: hv, spec: specName },+};+const names = require('./core/skeleton.js').exportNames(spec, sk);+const bytes = writeGLB({ meshes, skeleton: sk, ibm: inverseBindMatrices(sk), anims }, outPath,+ { asset, names });+const tv = meshes.reduce((a, m) => a + m.V.length, 0);+const tf = meshes.reduce((a, m) => a + m.F.length, 0);+console.log(JSON.stringify({ ok: true, out: outPath, bytes,+ verts: tv, faces: tf, joints: sk.joints.length,+ anims: anims.map(a => a.name), checks: 'all green',+ uv: uvInfo ? { islands: uvInfo.islands, atlasUtil: +uvInfo.atlasUtil.toFixed(2) } : 'off',+ ao: aoInfo.baked ? { meanOcc: +aoInfo.meanOcc.toFixed(3) } : 'off' }));diff --git a/engine/core/anim.js b/engine/core/anim.jsnew file mode 100644index 0000000..74f8a5f--- /dev/null+++ b/engine/core/anim.js@@ -0,0 +1,97 @@+// ACS engine — animation compiler. Author: Ariescar.+// Agent-first keyframes: degrees + fractions, engine turns them into+// glTF rotation/translation samplers. Mirrored chains get phase-shifted,+// axis-flipped copies of the L tracks automatically.+//+// spec.animations = {+// move: { duration: 1.0, loop: true, mirror_phase: 0.5,+// tracks: { LLegRoot: { rx: [[0,-25],[0.5,25],[1,-25]] },+// Hips: { ty: [[0,0],[0.25,0.04],[0.5,0]] } } }+// }+// rx/ry/rz = rotation degrees around local X/Y/Z; tx/ty/tz = translation offset.+'use strict';+const { mirrorName } = require('./skeleton.js');++function eulerToQuat(rx, ry, rz) { // XYZ order, degrees+ const d = Math.PI / 180;+ const [x, y, z] = [rx * d / 2, ry * d / 2, rz * d / 2];+ const [cx, sx, cy, sy, cz, sz] = [Math.cos(x), Math.sin(x), Math.cos(y), Math.sin(y), Math.cos(z), Math.sin(z)];+ return [+ sx * cy * cz + cx * sy * sz,+ cx * sy * cz - sx * cy * sz,+ cx * cy * sz + sx * sy * cz,+ cx * cy * cz - sx * sy * sz,+ ];+}++function sampleKeys(keys, t) { // keys [[frac, val]...] sorted; linear interp, t in [0,1]+ if (t <= keys[0][0]) return keys[0][1];+ for (let i = 0; i < keys.length - 1; i++) {+ const [t0, v0] = keys[i], [t1, v1] = keys[i + 1];+ if (t <= t1) { const f = (t - t0) / (t1 - t0 || 1); return v0 + (v1 - v0) * f; }+ }+ return keys[keys.length - 1][1];+}++// Expand one animation into per-joint uniform samplers (N samples across duration).+// Returns { name, duration, channels: [{joint, path:'rotation'|'translation', times:[], values:[]}] }+function compileAnim(name, a, spec, sk, samples = 24) {+ const tracks = { ...a.tracks };+ // auto-mirror: for each track on a joint belonging to a mirrored chain,+ // add the R-side twin with phase shift + axis flip (ry, rz, tx negate).+ const phase = a.mirror_phase ?? 0;+ for (const cn of spec.mirror || []) {+ for (const jn of spec.chains[cn]) {+ if (!tracks[jn]) continue;+ const rj = mirrorName(jn);+ if (tracks[rj]) continue; // author overrode+ const src = tracks[jn]; const dst = {};+ for (const [axis, keys] of Object.entries(src)) {+ const flip = (axis === 'ry' || axis === 'rz' || axis === 'tx') ? -1 : 1;+ dst[axis] = keys.map(([t, v]) => [(t + phase) % 1, v * flip])+ .sort((p, q) => p[0] - q[0]);+ // re-close the loop+ if (dst[axis][0][0] !== 0) dst[axis].unshift([0, sampleKeys(src[axis].map(([t,v])=>[(t+phase)%1, v*flip]).sort((p,q)=>p[0]-q[0]), 0)]);+ if (dst[axis][dst[axis].length-1][0] !== 1) dst[axis].push([1, dst[axis][0][1]]);+ }+ tracks[rj] = dst;+ }+ }+ const channels = [];+ const times = Array.from({ length: samples + 1 }, (_, i) => (i / samples) * a.duration);+ for (const [jn, tr] of Object.entries(tracks)) {+ if (!(jn in sk.index)) throw new Error(`animation "${name}" targets unknown joint "${jn}"`);+ const hasRot = tr.rx || tr.ry || tr.rz;+ const hasTrn = tr.tx || tr.ty || tr.tz;+ if (hasRot) {+ const values = [];+ for (let i = 0; i <= samples; i++) {+ const t = i / samples;+ values.push(...eulerToQuat(+ tr.rx ? sampleKeys(tr.rx, t) : 0,+ tr.ry ? sampleKeys(tr.ry, t) : 0,+ tr.rz ? sampleKeys(tr.rz, t) : 0));+ }+ channels.push({ joint: jn, path: 'rotation', times, values });+ }+ if (hasTrn) {+ const base = require('./skeleton.js').localTranslations(sk)[sk.index[jn]];+ const values = [];+ for (let i = 0; i <= samples; i++) {+ const t = i / samples;+ values.push(+ base[0] + (tr.tx ? sampleKeys(tr.tx, t) : 0),+ base[1] + (tr.ty ? sampleKeys(tr.ty, t) : 0),+ base[2] + (tr.tz ? sampleKeys(tr.tz, t) : 0));+ }+ channels.push({ joint: jn, path: 'translation', times, values });+ }+ }+ return { name, duration: a.duration, channels };+}++function compileAnims(spec, sk) {+ return Object.entries(spec.animations || {}).map(([n, a]) => compileAnim(n, a, spec, sk));+}++module.exports = { compileAnims, eulerToQuat, sampleKeys };diff --git a/engine/core/ao.js b/engine/core/ao.jsnew file mode 100644index 0000000..ea64890--- /dev/null+++ b/engine/core/ao.js@@ -0,0 +1,138 @@+// ACS engine — per-vertex ambient occlusion bake. Author: Ariescar.+// Casts short hemisphere rays from every vertex against the whole creature+// (uniform-grid accelerated Möller–Trumbore) and multiplies the occlusion into+// COLOR_0. Meshes without vertex colours get their flat material colour+// expanded into COLOR_0 first, so AO always lands in the same attribute.+// Runs at compile time in the bind pose; skinned deformation inherits it.+'use strict';++function hex2lin(h) {+ const x = parseInt(String(h).replace('#', ''), 16);+ const s = c => Math.pow(c / 255, 2.2);+ return [s((x >> 16) & 255), s((x >> 8) & 255), s(x & 255)];+}+function triangulate(F) {+ const out = [];+ for (const f of F) {+ if (f.length === 3) out.push(f);+ else if (f.length === 4) out.push([f[0], f[1], f[2]], [f[0], f[2], f[3]]);+ }+ return out;+}++function bakeAO(meshes, cfg) {+ if (cfg === false) return { baked: false };+ const opt = typeof cfg === 'object' && cfg ? cfg : {};+ const SAMPLES = opt.samples ?? 16;+ const STRENGTH = opt.strength ?? 0.59;++ // ── triangle soup + bounds ──+ const tris = []; // [a,b,c] as vec3s+ const lo = [1e9, 1e9, 1e9], hi = [-1e9, -1e9, -1e9];+ for (const m of meshes) {+ for (const v of m.V) for (let k = 0; k < 3; k++) {+ if (v[k] < lo[k]) lo[k] = v[k];+ if (v[k] > hi[k]) hi[k] = v[k];+ }+ for (const [a, b, c] of triangulate(m.F)) tris.push([m.V[a], m.V[b], m.V[c]]);+ }+ if (!tris.length) return { baked: false };+ const diag = Math.hypot(hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2]);+ const RADIUS = opt.radius ?? diag * 0.60;+ const EPS = diag * 1e-4;++ // ── uniform grid over the soup ──+ const RES = 24;+ const cs = [0, 1, 2].map(k => (hi[k] - lo[k]) / RES || 1e-6);+ const cellOf = (p, k) => Math.max(0, Math.min(RES - 1, Math.floor((p[k] - lo[k]) / cs[k])));+ const grid = new Map();+ tris.forEach((t, ti) => {+ const tl = [0, 1, 2].map(k => Math.min(t[0][k], t[1][k], t[2][k]));+ const th = [0, 1, 2].map(k => Math.max(t[0][k], t[1][k], t[2][k]));+ for (let x = cellOf(tl, 0); x <= cellOf(th, 0); x++)+ for (let y = cellOf(tl, 1); y <= cellOf(th, 1); y++)+ for (let z = cellOf(tl, 2); z <= cellOf(th, 2); z++) {+ const key = (x * RES + y) * RES + z;+ let b = grid.get(key); if (!b) grid.set(key, b = []);+ b.push(ti);+ }+ });++ const rayTri = (o, d, t, tmax) => { // Möller–Trumbore, returns hit distance or 0+ const [p0, p1, p2] = t;+ const e1 = [p1[0]-p0[0], p1[1]-p0[1], p1[2]-p0[2]];+ const e2 = [p2[0]-p0[0], p2[1]-p0[1], p2[2]-p0[2]];+ const pv = [d[1]*e2[2]-d[2]*e2[1], d[2]*e2[0]-d[0]*e2[2], d[0]*e2[1]-d[1]*e2[0]];+ const det = e1[0]*pv[0] + e1[1]*pv[1] + e1[2]*pv[2];+ if (Math.abs(det) < 1e-12) return 0;+ const inv = 1 / det;+ const tv = [o[0]-p0[0], o[1]-p0[1], o[2]-p0[2]];+ const u = (tv[0]*pv[0] + tv[1]*pv[1] + tv[2]*pv[2]) * inv;+ if (u < 0 || u > 1) return 0;+ const qv = [tv[1]*e1[2]-tv[2]*e1[1], tv[2]*e1[0]-tv[0]*e1[2], tv[0]*e1[1]-tv[1]*e1[0]];+ const v = (d[0]*qv[0] + d[1]*qv[1] + d[2]*qv[2]) * inv;+ if (v < 0 || u + v > 1) return 0;+ const dist = (e2[0]*qv[0] + e2[1]*qv[1] + e2[2]*qv[2]) * inv;+ return (dist > EPS && dist < tmax) ? dist : 0;+ };+ const occluded = (o, d) => { // walk the grid cells along the ray+ const steps = Math.ceil(RADIUS / Math.min(cs[0], cs[1], cs[2]));+ const seen = new Set(); let last = -1;+ for (let s = 0; s <= steps; s++) {+ const t = (s / steps) * RADIUS;+ const p = [o[0] + d[0]*t, o[1] + d[1]*t, o[2] + d[2]*t];+ const key = (cellOf(p, 0) * RES + cellOf(p, 1)) * RES + cellOf(p, 2);+ if (key === last) continue; last = key;+ const bucket = grid.get(key); if (!bucket) continue;+ for (const ti of bucket) {+ if (seen.has(ti)) continue; seen.add(ti);+ if (rayTri(o, d, tris[ti], RADIUS)) return true;+ }+ }+ return false;+ };++ // ── fixed cosine-weighted hemisphere kernel (deterministic, no RNG) ──+ const kernel = [];+ const GA = Math.PI * (3 - Math.sqrt(5)); // golden angle+ for (let i = 0; i < SAMPLES; i++) {+ const z = Math.sqrt((i + 0.5) / SAMPLES); // bias toward the normal+ const r = Math.sqrt(1 - z * z), a = GA * i;+ kernel.push([Math.cos(a) * r, Math.sin(a) * r, z]);+ }++ // ── bake per mesh ──+ let vcount = 0, occSum = 0;+ const { vertexNormals } = require('./normals.js');+ for (const m of meshes) {+ // ANGLE-weighted vertex normals — the hemisphere axis for every ray. Area+ // weighting used to let one long skinny triangle tilt the axis by tens of+ // degrees, and that error bakes straight into COLOR_0.+ const N = vertexNormals(m.V, triangulate(m.F));+ if (!m.C) m.C = m.V.map(() => hex2lin(m.color || '#888888'));+ m.V.forEach((v, vi) => {+ const n = N[vi];+ // tangent frame+ const ax = Math.abs(n[0]) < 0.9 ? [1, 0, 0] : [0, 0, 1];+ let tx = [n[1]*ax[2]-n[2]*ax[1], n[2]*ax[0]-n[0]*ax[2], n[0]*ax[1]-n[1]*ax[0]];+ const tl = Math.hypot(...tx); tx = [tx[0]/tl, tx[1]/tl, tx[2]/tl];+ const ty = [n[1]*tx[2]-n[2]*tx[1], n[2]*tx[0]-n[0]*tx[2], n[0]*tx[1]-n[1]*tx[0]];+ const o = [v[0] + n[0]*EPS*4, v[1] + n[1]*EPS*4, v[2] + n[2]*EPS*4];+ let hits = 0;+ for (const [kx, ky, kz] of kernel) {+ const d = [tx[0]*kx + ty[0]*ky + n[0]*kz,+ tx[1]*kx + ty[1]*ky + n[1]*kz,+ tx[2]*kx + ty[2]*ky + n[2]*kz];+ if (occluded(o, d)) hits++;+ }+ const occ = hits / SAMPLES;+ const ao = 1 - STRENGTH * occ;+ const c = m.C[vi];+ m.C[vi] = [c[0] * ao, c[1] * ao, c[2] * ao];+ vcount++; occSum += occ;+ });+ }+ return { baked: true, verts: vcount, meanOcc: vcount ? occSum / vcount : 0 };+}++module.exports = { bakeAO };diff --git a/engine/core/checks.js b/engine/core/checks.jsnew file mode 100644index 0000000..0aaf3da--- /dev/null+++ b/engine/core/checks.js@@ -0,0 +1,493 @@+// ACS engine — mechanical checks (compile-time gate). Author: Ariescar.+// Warnings here are ERRORS: a failing check blocks the build (exit 1 in cli).+// 1. anim_integrity — CPU-skin the mesh at sampled anim times; folded tris = 0,+// edge stretch ≤ 3×. (kills twist/breakage like the wolf case)+// 2. proportion — adjacent axis segments must not be 50:50 (dead rhythm),+// unless spec.style === 'heavy'.+// 3. balance — mass centroid must project inside the support polygon.+'use strict';+const G = require('./geometry.js');+const { sampleKeys, eulerToQuat } = require('./anim.js');++// ── mat helpers (column-major mat4) ──+function quatMat(q) {+ const [x, y, z, w] = q;+ return [+ 1-2*(y*y+z*z), 2*(x*y+z*w), 2*(x*z-y*w), 0,+ 2*(x*y-z*w), 1-2*(x*x+z*z), 2*(y*z+x*w), 0,+ 2*(x*z+y*w), 2*(y*z-x*w), 1-2*(x*x+y*y), 0,+ 0, 0, 0, 1];+}+function matMul(a, b) {+ const o = new Array(16).fill(0);+ for (let c = 0; c < 4; c++) for (let r = 0; r < 4; r++)+ for (let k = 0; k < 4; k++) o[c*4+r] += a[k*4+r] * b[c*4+k];+ return o;+}+function matVec(m, v) {+ return [+ m[0]*v[0]+m[4]*v[1]+m[8]*v[2]+m[12],+ m[1]*v[0]+m[5]*v[1]+m[9]*v[2]+m[13],+ m[2]*v[0]+m[6]*v[1]+m[10]*v[2]+m[14]];+}+function transMat(t) { return [1,0,0,0, 0,1,0,0, 0,0,1,0, t[0],t[1],t[2],1]; }++// world matrices for all joints at time-fraction t of an anim (or bind pose if anim null)+function jointWorlds(sk, locals, anim, t) {+ const rot = {}, trn = {};+ if (anim) for (const ch of anim._tracks || []) { /* unused */ }+ // build per-joint local TRS from compiled tracks+ const trackOf = {};+ if (anim) for (const [jn, tr] of Object.entries(anim.tracksResolved)) trackOf[jn] = tr;+ const world = new Array(sk.joints.length);+ sk.joints.forEach((j, i) => {+ let local = transMat(locals[i]);+ const tr = trackOf[j.name];+ if (tr) {+ const T = [+ locals[i][0] + (tr.tx ? sampleKeys(tr.tx, t) : 0),+ locals[i][1] + (tr.ty ? sampleKeys(tr.ty, t) : 0),+ locals[i][2] + (tr.tz ? sampleKeys(tr.tz, t) : 0)];+ const q = eulerToQuat(+ tr.rx ? sampleKeys(tr.rx, t) : 0,+ tr.ry ? sampleKeys(tr.ry, t) : 0,+ tr.rz ? sampleKeys(tr.rz, t) : 0);+ local = matMul(transMat(T), quatMat(q));+ }+ world[i] = j.parent < 0 ? local : matMul(world[j.parent], local);+ });+ return world;+}++function skinVerts(mesh, sk, world) {+ // v' = Σ w * world[j] * (v - bind[j]) (IBM is translate(-bind))+ return mesh.V.map((v, vi) => {+ const out = [0, 0, 0];+ for (const [jn, w] of mesh.skin[vi]) {+ const ji = sk.index[jn];+ const bind = sk.joints[ji].pos;+ const p = matVec(world[ji], G.sub(v, bind));+ out[0] += w * p[0]; out[1] += w * p[1]; out[2] += w * p[2];+ }+ return out;+ });+}++function foldCount(V, F, minArea2 = 0) {+ const tris = [];+ for (const f of F) { if (f.length === 3) tris.push(f); else tris.push([f[0],f[1],f[2]],[f[0],f[2],f[3]]); }+ const VN = V.map(() => [0, 0, 0]);+ const FN = tris.map(([a, b, c]) => {+ const n = G.cross(G.sub(V[b], V[a]), G.sub(V[c], V[a]));+ for (const i of [a, b, c]) { VN[i][0]+=n[0]; VN[i][1]+=n[1]; VN[i][2]+=n[2]; }+ return n;+ });+ let folds = 0;+ tris.forEach(([a, b, c], i) => {+ if (G.dot(FN[i], FN[i]) < minArea2) return; // degenerate slivers don't vote+ const s = G.add(G.add(VN[a], VN[b]), VN[c]);+ if (G.dot(FN[i], s) < 0) folds++;+ });+ return folds;+}++function runChecks(spec, sk, meshes, animsCompiled) {+ const fails = [];+ const warns = []; // hoisted: checks above the part_overlap block also report measures+ const locals = require('./skeleton.js').localTranslations(sk);++ // ── faceted bodies are banned ─────────────────────────────────────────────+ // `faceted: true` on a VOLUME shatters the mass into one independent facet per+ // triangle — an 800-triangle torso becomes 800 shards — and because AO bakes+ // from those normals the mess ships inside COLOR_0, where no relighting can+ // reach it. Two real runs (gryphon, mammoth) came back 89% and 93% hard-edged+ // this way. Bodies are smooth-shaded. Parts — plates, spikes, claws, crystal,+ // armour — may still face freely; only volumes are covered.+ if (spec.build !== 'rigid') {+ const bad = (spec.volumes || []).filter(v => v.faceted).map(v => `"${v.chain}"`);+ if (bad.length)+ fails.push('faceted_body: volume(s) ' + bad.join(', ') + ' set "faceted": true — bodies are '+ + 'smooth-shaded. Put "sharp": true on the profile rows where the silhouette should break, '+ + 'or lower "smooth_angle" on that volume. If the creature really is a machine, declare '+ + '"build": "rigid" at spec level.');+ }++ // QA isolation builds ("qa_isolate": true): a lone part rendered for the MID+ // blind-read is not a creature — whole-body laws (balance, containment,+ // proportion…) don't apply. Geometry must still be sound.+ if (spec.qa_isolate) {+ let qaFolds = 0;+ for (const m of meshes) if (!m.doubleSided) qaFolds += foldCount(m.V, m.F);+ return { fails: qaFolds > 0 ? [`mesh_integrity: bind pose has ${qaFolds} flipped tris`] : [], warns: [] };+ }++ // resolve raw tracks (with mirrored twins) once per anim for CPU skinning+ const { mirrorName } = require('./skeleton.js');+ const animsResolved = Object.entries(spec.animations || {}).map(([name, a]) => {+ const tracks = { ...a.tracks };+ const phase = a.mirror_phase ?? 0;+ for (const cn of spec.mirror || []) {+ for (const jn of spec.chains[cn] || []) {+ if (!tracks[jn] || tracks[mirrorName(jn)]) continue;+ const dst = {};+ for (const [axis, keys] of Object.entries(tracks[jn])) {+ const flip = (axis === 'ry' || axis === 'rz' || axis === 'tx') ? -1 : 1;+ dst[axis] = keys.map(([t, v]) => [(t + phase) % 1, v * flip]).sort((p, q) => p[0] - q[0]);+ }+ tracks[mirrorName(jn)] = dst;+ }+ }+ return { name, tracksResolved: tracks };+ });++ // scale floors: ignore sub-centimetre noise relative to model size+ const allV0 = meshes.flatMap(m => m.V);+ const ys0 = allV0.map(v => v[1]);+ const modelH = Math.max(...ys0) - Math.min(...ys0) || 1;+ const edgeFloor = 0.015 * modelH; // edges shorter than 1.5% of height don't vote+ const areaFloor2 = Math.pow(0.0004 * modelH * modelH, 2); // ~sliver faces don't vote++ // 1. anim_integrity+ const bindEdges = [];+ for (const m of meshes) {+ const edges = [];+ for (const f of m.F) for (let k = 0; k < f.length; k++) {+ const a = f[k], b = f[(k + 1) % f.length];+ const L = G.len(G.sub(m.V[a], m.V[b]));+ if (L >= edgeFloor) edges.push([a, b, L]);+ }+ bindEdges.push(edges);+ }+ for (const anim of animsResolved) {+ for (const t of [0, 0.2, 0.4, 0.6, 0.8]) {+ const world = jointWorlds(sk, locals, anim, t);+ // WHERE, not just how many. This check is ~83% of all blocks in practice,+ // and "10 flipped tris" with no location forces a binary search through+ // the spec. Name the mesh, and for a stretch name the joint driving it.+ let folds = 0, maxStretch = 0, worstFoldMesh = '', worstFolds = 0;+ let stretchMesh = '', stretchJoint = '';+ const nameOf = (m) => m.chain || m.part || m.material;+ const heaviestJoint = (m, vi) => {+ const infl = (m.skin && m.skin[vi]) || [];+ let best = '', bw = -1;+ for (const [jn, w] of infl) if (w > bw) { bw = w; best = jn; }+ return best;+ };+ meshes.forEach((m, mi) => {+ const V2 = skinVerts(m, sk, world);+ if (!m.doubleSided) { // open membranes have saddle regions; fold test assumes a closed surface+ const f = foldCount(V2, m.F, areaFloor2);+ folds += f;+ if (f > worstFolds) { worstFolds = f; worstFoldMesh = nameOf(m); }+ }+ for (const [a, b, L] of bindEdges[mi]) {+ const s = G.len(G.sub(V2[a], V2[b])) / L;+ if (s > maxStretch) {+ maxStretch = s; stretchMesh = nameOf(m);+ stretchJoint = heaviestJoint(m, a) || heaviestJoint(m, b);+ }+ }+ });+ if (folds > 0) fails.push(`anim_integrity: "${anim.name}" @${t.toFixed(1)} folds mesh — `+ + `${folds} flipped tris, worst in "${worstFoldMesh}" (${worstFolds}). A bend there is sharper `+ + `than the volume can absorb: reduce the rotation on the joint driving "${worstFoldMesh}", `+ + `raise "ring_step" on that volume so rings are not crowded through the bend, or add a joint `+ + `to split the bend across two segments.`);+ if (maxStretch > 3) fails.push(`anim_integrity: "${anim.name}" @${t.toFixed(1)} stretches an edge `+ + `${maxStretch.toFixed(1)}× in "${stretchMesh}", pulled by joint "${stretchJoint}" — that joint `+ + `is tearing the skin. Reduce its travel, or spread the same motion over more joints in the chain.`);+ }+ }++ // 2. proportion — axis chain, 50:50 ban on significant adjacent segments+ const mset = new Set(spec.mirror || []);+ const mirroredChains = new Set([...mset, ...[...mset].map(c => 'R' + c.slice(1))]);+ if (spec.style !== 'heavy') {+ for (const [cn, names] of Object.entries(spec.chains)) {+ // limbs are exempt (legs are naturally even) — but membership is decided by+ // spec.mirror, NOT by the chain's first letter. Testing the letter meant a+ // dead-rhythm chain slipped through by renaming "axis" to "Laxis".+ if (mirroredChains.has(cn)) continue;+ const segs = [];+ for (let i = 1; i < names.length; i++)+ segs.push(G.len(G.sub(spec.joints[names[i]] ?? [0,0,0], spec.joints[names[i-1]] ?? [0,0,0])));+ const total = segs.reduce((a, b) => a + b, 0);+ const mean = total / (segs.length || 1);+ for (let i = 0; i < segs.length - 1; i++) {+ // minor-segment filter is RELATIVE TO MEAN segment length (a fixed %-of-total+ // filter silently exempted almost every pair on long chains)+ if (segs[i] < 0.5 * mean || segs[i+1] < 0.5 * mean) continue;+ const r = Math.min(segs[i], segs[i+1]) / (Math.max(segs[i], segs[i+1]) || 1);+ // 0.923 aligns with the styling rule ("no 50:50 rhythm"); the old 0.96 left+ // a 0.92–0.96 blind band that let a 0.946 split through+ if (r > 0.923) fails.push(`proportion: chain "${cn}" segments ${names[i]}→${names[i+1]}→${names[i+2]} are 50:50 (${r.toFixed(2)}) — dead rhythm; aim for ~0.62–0.85 (declare "style":"heavy" to allow)`);+ }+ }+ }++ // 3. balance — centroid over support polygon (XZ convex hull of lowest verts)+ const allV = meshes.flatMap(m => m.V);+ const cen = allV.reduce((a, v) => G.add(a, v), [0,0,0]).map(x => x / allV.length);+ const ys = allV.map(v => v[1]); const ymin = Math.min(...ys), ymax = Math.max(...ys);+ const feet = allV.filter(v => v[1] < ymin + 0.08 * (ymax - ymin));+ if (feet.length >= 3) {+ const xs = feet.map(v => v[0]), zs = feet.map(v => v[2]);+ const inX = cen[0] >= Math.min(...xs) - 1e-6 && cen[0] <= Math.max(...xs) + 1e-6;+ const inZ = cen[2] >= Math.min(...zs) && cen[2] <= Math.max(...zs);+ if (!inX || !inZ) fails.push(`balance: mass centre (${cen[0].toFixed(2)},${cen[2].toFixed(2)}) falls outside the support footprint x[${Math.min(...xs).toFixed(2)},${Math.max(...xs).toFixed(2)}] z[${Math.min(...zs).toFixed(2)},${Math.max(...zs).toFixed(2)}] — it would tip over`);+ }++ // 4. root containment — attached volumes (legs/tail) must bury their root+ // ring inside the host tube, or the open ring shows on the surface.+ const volsByChain = {};+ for (const m of meshes) if (m._rings && m.chain) volsByChain[m.chain] = m;+ for (const [cn, hostJoint] of Object.entries(spec.attach || {})) {+ const v = volsByChain[cn]; if (!v) continue;+ // host volume = the one whose chain contains the host joint+ const hostChain = Object.keys(spec.chains).find(c => volsByChain[c] && spec.chains[c].includes(hostJoint) && c !== cn);+ if (!hostChain) continue;+ const host = volsByChain[hostChain];+ const rootRing = v._rings[0];+ let inside = 0;+ for (const p of rootRing) {+ let best = Infinity, bs = 0;+ host._pts.forEach((c2, si) => { const d = G.len(G.sub(p, c2)); if (d < best) { best = d; bs = si; } });+ const ring = host._rings[bs]; const c2 = host._pts[bs];+ const rad = Math.max(...ring.map(q => G.len(G.sub(q, c2))));+ if (best < rad * 0.98) inside++;+ }+ if (inside < rootRing.length * 0.8)+ fails.push(`root_containment: chain "${cn}" root ring is ${Math.round(100 * (1 - inside / rootRing.length))}% outside its host "${hostChain}" — the open ring will show on the surface; bury the root joint deeper`);+ }++ // 5. limb clearance — mirrored volumes must not touch across the centreline+ // (measured only on exposed verts below the torso)+ {+ const hostOf = cn => {+ const hj = (spec.attach || {})[cn]; if (!hj) return null;+ const hc = Object.keys(spec.chains).find(c => volsByChain[c] && spec.chains[c].includes(hj) && c !== cn);+ return hc ? volsByChain[hc] : null;+ };+ const containedInHost = (p, host) => {+ if (!host) return false;+ let best = Infinity, bs = 0;+ host._pts.forEach((c2, si) => { const d = G.len(G.sub(p, c2)); if (d < best) { best = d; bs = si; } });+ const rad = Math.max(...host._rings[bs].map(q => G.len(G.sub(q, host._pts[bs]))));+ // 1.05: verts within 5% of the host surface are thigh-belly SEAM geometry,+ // covered by the host silhouette — not a visible limb at the centreline.+ // (a zero-margin binary test flags every quadruped groin seam as "exposed")+ return best < rad * 1.05;+ };+ for (const cn of spec.mirror || []) {+ const v = volsByChain[cn]; if (!v) continue;+ const host = hostOf(cn);+ const exposed = v.V.filter(p => !containedInHost(p, host));+ if (!exposed.length) continue;+ const minX = Math.min(...exposed.map(p => Math.abs(p[0])));+ const clearance = 2 * minX;+ if (clearance < 0.03 * modelH)+ fails.push(`limb_clearance: "${cn}" and its mirror are ${clearance.toFixed(3)} apart at the centreline (need ≥ ${(0.03 * modelH).toFixed(3)}) — legs will interpenetrate in motion`);+ }+ }++ // 4b. part_attachment — root_containment above only walks `spec.attach`, whose+ // candidates are meshes carrying BOTH `_rings` and `chain`. Parts (curve /+ // fin / eye / paw / spike / membrane) have neither, so until now no part was+ // ever checked for being attached to anything: tusks whose entire root ring+ // floated 0.031 clear of the skull, a trunk 6/15 outside, a forehead plate+ // 0.050 above the surface at its nearest point — all shipped "all green"+ // and were caught by eye, in the most expensive repair round of the run.+ // The test is deliberately generous: a part only has to TOUCH its host.+ // Eyes and conformed plates sit ON the surface (nearest ≈ 0) and pass; a+ // part hanging in the air does not.+ {+ const gap = 0.015 * modelH; // a part nearer than this counts as meeting the host+ for (const m of meshes) {+ if (!m.part || !m.hostChain) continue;+ // A mirrored twin is the source reflected across X, and its host volume is+ // the source's host reflected the same way — testing it against the LEFT+ // host would measure the width of the creature. The source carries the+ // verdict for both; any twin-only deformation is mirror_distortion's job.+ if (m._mirrorSrc) continue;+ const host = volsByChain[m.hostChain];+ if (!host || !host._rings) continue;+ let nearest = Infinity;+ for (const p of m.V) {+ let best = Infinity, bs = 0;+ host._pts.forEach((c2, si) => { const d = G.len(G.sub(p, c2)); if (d < best) { best = d; bs = si; } });+ const rad = Math.max(...host._rings[bs].map(q => G.len(G.sub(q, host._pts[bs]))));+ const outside = best - rad; // <0 inside the host, >0 clear of it+ if (outside < nearest) nearest = outside;+ }+ if (nearest > gap)+ fails.push(`part_attachment: "${m.part}" never meets its host "${m.hostChain}" — its closest `+ + `point still stands ${nearest.toFixed(3)} clear of the surface (tolerance ${gap.toFixed(3)}). `+ + `It is floating: it will read as a detached sticker and drift the moment the host animates. `+ + `Bury the root inside the host (the first third of a root is meant to be embedded — that is `+ + `what hides the seam), or move its anchor onto the surface.`);+ }+ }++ // 5b. mirror_distortion — `joints_R` staggers a mirrored twin by TRANSLATING+ // its vertices with skin weights: the mesh was grown along the LEFT bone+ // path and is then linearly dragged onto the right joints. Small offsets+ // read as a pose; large ones shear the volume — a thigh that measures+ // 0.38 deep on the left comes out 0.15 deep on the right while its width+ // stays correct, which looks like the limb lost its volume. Nothing else+ // catches this: the build is green, the silhouette from the left is fine,+ // and only a look from the other side shows it.+ // Without joints_R every axis ratio is exactly 1.00, so any deviation is+ // distortion the skinning introduced, in either direction.+ {+ const extents = (V) => {+ const lo = [Infinity, Infinity, Infinity], hi = [-Infinity, -Infinity, -Infinity];+ for (const v of V) for (let k = 0; k < 3; k++) {+ if (v[k] < lo[k]) lo[k] = v[k];+ if (v[k] > hi[k]) hi[k] = v[k];+ }+ return [hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2]];+ };+ const AXIS = ['width', 'height', 'depth'];+ for (const m of meshes) {+ if (!m._mirrorSrc) continue;+ const a = extents(m._mirrorSrc.V), b = extents(m.V);+ for (let k = 0; k < 3; k++) {+ if (a[k] < 1e-6) continue;+ const r = b[k] / a[k];+ const who = m._mirrorSrc.chain || m._mirrorSrc.part || m._mirrorSrc.material;+ const how = r < 1 ? 'collapsed' : 'stretched';+ if (r < 0.70 || r > 1.30)+ fails.push(`mirror_distortion: the mirrored twin of "${who}" has ${how} — ${AXIS[k]} `+ + `${b[k].toFixed(3)} against ${a[k].toFixed(3)} on the source (${(r * 100).toFixed(0)}%). `+ + `"joints_R" drags a mesh grown on the LEFT bone path onto the right joints by translation, `+ + `so a large offset shears the volume instead of posing it. Keep "joints_R" to a few `+ + `centimetres of stagger; for a genuinely different pose take the limb OUT of "mirror" `+ + `and author it as its own chain.`);+ else if (r < 0.88 || r > 1.12)+ warns.push(`mirror_distortion: mirrored twin of "${who}" is ${(r * 100).toFixed(0)}% of the `+ + `source's ${AXIS[k]} — "joints_R" is starting to shear the volume rather than pose it.`);+ }+ }+ }++ // 6. bind-pose integrity+ let bindFolds = 0;+ for (const m of meshes) if (!m.doubleSided) bindFolds += foldCount(m.V, m.F, areaFloor2);+ if (bindFolds > 0) fails.push(`mesh_integrity: bind pose has ${bindFolds} flipped tris — geometry folds into itself`);++ // 7. attack_reach — an attack must COMMIT FORWARD. Two ways to satisfy it,+ // because a strike does not have to be a whole-body lunge:+ // REACH — something ends up in the space in front of the body, i.e. past+ // the bind-pose front. Enough to touch a target standing there.+ // SWING — something travels forward far enough relative to ITS OWN bind+ // position. A creature planted on the spot swinging an arm, a+ // weapon or a tail is a legitimate attack; the root never moves+ // and the hand still crosses a lot of ground.+ // Either route passes. The old rule demanded half a body span PAST the+ // nose, which forced every creature to fly forward and rejected every+ // stand-and-swing design.+ {+ const atk = animsResolved.find(a => a.name === 'attack');+ if (atk) {+ const zs0 = allV0.map(v => v[2]);+ const maxZ0 = Math.max(...zs0);+ const span = Math.max(maxZ0 - Math.min(...zs0), modelH);+ const REACH_MIN = 0.15 * span;+ // A limb's travel is bounded by the LIMB, not by the body. Measuring the+ // swing against the body span is a dimensional error: it asks a wolf's+ // foreleg to cover most of the wolf. Each mesh is judged against its own+ // longest bind axis instead, so the same rule fits a claw, a tail and a+ // greatsword. Meshes too small to carry a strike (eyes, nostrils) do not+ // vote. Calibration: a foreleg swung ±20° travels 0.32 of its own length,+ // ±35° travels 0.51, ±55° travels 0.70 — 0.45 keeps the real swings.+ const SWING_FRAC = 0.45, MIN_PART = 0.10 * span;+ let reach = 0, swing = 0, swingName = '', swingRatio = 0;+ const extentOf = (m) => {+ let lo = [Infinity, Infinity, Infinity], hi = [-Infinity, -Infinity, -Infinity];+ for (const v of m.V) for (let k = 0; k < 3; k++) {+ if (v[k] < lo[k]) lo[k] = v[k];+ if (v[k] > hi[k]) hi[k] = v[k];+ }+ return Math.max(hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2]);+ };+ for (let s = 0; s <= 20; s++) {+ const world = jointWorlds(sk, locals, atk, s / 20);+ for (const m of meshes) {+ const ext = extentOf(m);+ const V2 = skinVerts(m, sk, world);+ for (let i = 0; i < V2.length; i++) {+ const dz = V2[i][2] - maxZ0; if (dz > reach) reach = dz;+ if (ext < MIN_PART) continue;+ const tr = V2[i][2] - m.V[i][2];+ if (tr > swing) swing = tr;+ const ratio = tr / ext;+ if (ratio > swingRatio) { swingRatio = ratio; swingName = m.chain || m.part || m.material; }+ }+ }+ }+ if (reach < REACH_MIN && swingRatio < SWING_FRAC)+ fails.push(`attack_reach: "attack" neither reaches nor swings. Forward of the bind front: `+ + `${reach.toFixed(2)} (a reach needs ≥ ${REACH_MIN.toFixed(2)}). Best swing: "${swingName || 'none'}" `+ + `travels ${swing.toFixed(2)} forward = ${(swingRatio * 100).toFixed(0)}% of its own length `+ + `(a swing needs ≥ ${(SWING_FRAC * 100).toFixed(0)}%). Nothing commits at a target. `+ + `You do NOT have to lunge — standing on the spot and sweeping a limb, tail or weapon `+ + `counts, as long as it winds BACK and crosses FORWARD. Otherwise drive the root with tz keys.`);+ }+ }++ // 8. declared adjacency — "touch": [["chainA","chainB"], ...]. Declared-+ // connected chains must actually meet; a gap reads as floating bodyparts.+ {+ const insideVol = (p, vol) => {+ let best = Infinity, bs = 0;+ vol._pts.forEach((c2, si) => { const d = G.len(G.sub(p, c2)); if (d < best) { best = d; bs = si; } });+ const c2 = vol._pts[bs];+ const rad = Math.max(...vol._rings[bs].map(q => G.len(G.sub(q, c2))));+ return best < rad * 0.98;+ };+ for (const [ca, cb] of spec.touch || []) {+ const A = volsByChain[ca], B = volsByChain[cb];+ if (!A || !B) { fails.push(`touch: pair ["${ca}","${cb}"] names a chain with no volume`); continue; }+ const eps = 0.01 * modelH;+ let met = false, best = Infinity;+ for (const p of A.V) { if (insideVol(p, B)) { met = true; break; } }+ if (!met) for (const p of B.V) { if (insideVol(p, A)) { met = true; break; } }+ if (!met) outer: for (const p of A.V) for (const q of B.V) {+ const d = G.len(G.sub(p, q)); if (d < best) best = d;+ if (d < eps) { met = true; break outer; }+ }+ if (!met)+ fails.push(`touch: "${ca}" and "${cb}" are declared connected but their surfaces stay ${best.toFixed(3)} apart — overlap the volumes so the join is buried`);+ }+ }++ // 9. part_overlap — a MEASURE, not a law: gross part-into-part interpenetration+ // (the self-intersecting fist class). Reported as warn; you judge.+ {+ const parts = meshes.filter(m => m.part);+ for (let i = 0; i < parts.length; i++) for (let k = 0; k < parts.length; k++) {+ if (i === k) continue;+ const A = parts[i], B = parts[k];+ if (A.part.replace(/\.R$/, '') === B.part.replace(/\.R$/, '')) continue; // own mirror twin+ if (B.doubleSided) continue; // a zero-thickness membrane has a huge hollow box — it contains nothing+ const lo = [1e9, 1e9, 1e9], hi = [-1e9, -1e9, -1e9];+ for (const v of B.V) for (let a = 0; a < 3; a++) {+ if (v[a] < lo[a]) lo[a] = v[a];+ if (v[a] > hi[a]) hi[a] = v[a];+ }+ const c = [0, 1, 2].map(a => (lo[a] + hi[a]) / 2);+ const h = [0, 1, 2].map(a => (hi[a] - lo[a]) / 2);+ if (Math.min(...h) <= 0) continue;+ let inside = 0;+ for (const v of A.V)+ if (Math.abs(v[0] - c[0]) < h[0] && Math.abs(v[1] - c[1]) < h[1] && Math.abs(v[2] - c[2]) < h[2]) inside++;+ const frac = inside / A.V.length;+ if (frac > 0.45)+ warns.push(`part_overlap: '${A.part}' sits ${Math.round(frac * 100)}% inside '${B.part}' — check for interpenetration`);+ }+ }++ return { fails, warns };+}++module.exports = { runChecks, foldCount, skinVerts, jointWorlds };diff --git a/engine/core/compile.js b/engine/core/compile.jsnew file mode 100644index 0000000..b0422f2--- /dev/null+++ b/engine/core/compile.js@@ -0,0 +1,642 @@+// ACS engine — spec compiler (M1: static geometry). Author: Ariescar.+// Agent-first: input is plain JSON. Joints are explicit 3D points (the agent+// does the proportional reasoning; the engine does the meshing).+//+// spec = {+// name, height?,+// palette: { material: {color:'#rrggbb', rough?, metal?} },+// joints: { JointName: [x,y,z], ... },+// chains: { chainName: [JointName, ...], ... },+// volumes: [ { chain, material, profile: [[t, w, h], ...], frame?: 'auto'|'up'|'ground',+// caps?: [start,end] // 'fan'|'ngon'|'none' } ],+// parts: [+// { type:'spike', host:JointName, offset:[x,y,z], dir:[x,y,z],+// segments:[{len, r}...], material },+// { type:'eye', host:JointName, forward:[x,y,z], spread, up?, size, material }+// // eyes are first-class: ALWAYS placed on the forward hemisphere of the host.+// ],+// mirror?: [chainName...] // chains to duplicate across X (names prefixed L/R)+// }+'use strict';+const G = require('./geometry.js');++// compiler narration. A spec declares intent; the geometry that comes out is+// the resolved result, and the two diverge quietly. Every place the engine+// resolves something the author did not state exactly — the realized bend of a+// curve, the angle a plate was turned to meet its surface — it says so here.+const INFO = [];+function drainInfo() { const out = INFO.slice(); INFO.length = 0; return out; }+function dirName(v) {+ const p = [];+ if (v[1] > 0.4) p.push('up'); if (v[1] < -0.4) p.push('down');+ if (v[2] > 0.4) p.push('fwd'); if (v[2] < -0.4) p.push('back');+ if (Math.abs(v[0]) > 0.4) p.push('side');+ return p.join('-') || 'level';+}++// value noise (deterministic, no Date/random)+function hash3(x, y, z) {+ let h = Math.sin(x * 127.1 + y * 311.7 + z * 74.7) * 43758.5453;+ return h - Math.floor(h);+}+function vnoise(p, scale) {+ const q = p.map(v => v / scale);+ const f = q.map(v => v - Math.floor(v)), i = q.map(Math.floor);+ const sm = f.map(v => v * v * (3 - 2 * v));+ let acc = 0;+ for (let dx = 0; dx <= 1; dx++) for (let dy = 0; dy <= 1; dy++) for (let dz = 0; dz <= 1; dz++) {+ const w = (dx ? sm[0] : 1 - sm[0]) * (dy ? sm[1] : 1 - sm[1]) * (dz ? sm[2] : 1 - sm[2]);+ acc += w * hash3(i[0] + dx, i[1] + dy, i[2] + dz);+ }+ return acc; // 0..1+}+// sRGB hex → LINEAR. COLOR_0 is defined as linear by glTF, and ao.js / glb.js+// have always linearised; this one used to skip the transfer function, so any+// volume carrying a `colors` block shipped ~1.5x too bright and its value steps+// collapsed (wolf's spine-vs-base contrast fell from 5.3x to 2.1x).+function hex2lin(h) {+ const x = parseInt(h.replace('#', ''), 16);+ const s = c => Math.pow(c / 255, 2.2);+ return [s((x >> 16) & 255), s((x >> 8) & 255), s(x & 255)];+}++function lerpProfile(profile, t) { // rows [t, w, h, {exp,bias,roll}?]+ const row = (r) => [r[1], r[2], r[3] || null];+ if (t <= profile[0][0]) return row(profile[0]);+ for (let i = 0; i < profile.length - 1; i++) {+ const [t0, w0, h0] = profile[i], [t1, w1, h1] = profile[i + 1];+ if (t <= t1) {+ const f = (t - t0) / (t1 - t0 || 1);+ const s0 = profile[i][3] || {}, s1 = profile[i + 1][3] || {};+ const mix = (a, b, d) => (a ?? d) + ((b ?? d) - (a ?? d)) * f;+ return [w0 + (w1 - w0) * f, h0 + (h1 - h0) * f,+ { exp: mix(s0.exp, s1.exp, 2), bias: mix(s0.bias, s1.bias, 0), roll: mix(s0.roll, s1.roll, 0),+ section: f < 0.5 ? s0.section : s1.section }];+ }+ }+ const last = profile[profile.length - 1]; return row(last);+}++function chainPoints(spec, chainName) {+ const names = spec.chains[chainName];+ if (!names) throw new Error(`unknown chain "${chainName}"`);+ return names.map(n => {+ const p = spec.joints[n];+ if (!p) throw new Error(`chain "${chainName}" references missing joint "${n}"`);+ return p.slice();+ });+}++// Catmull-Rom through profile rows: fat, ROUND masses instead of straight frustums+function crProfile(profile, t) {+ const n = profile.length;+ if (t <= profile[0][0]) return lerpProfile(profile, t);+ if (t >= profile[n - 1][0]) return lerpProfile(profile, t);+ let i = 0; while (i < n - 2 && t > profile[i + 1][0]) i++;+ const P = k => profile[Math.min(n - 1, Math.max(0, k))];+ const [p0, p1, p2, p3] = [P(i - 1), P(i), P(i + 1), P(i + 2)];+ const sharpAt = r => r[3] && r[3].sharp;+ if (sharpAt(p1) || sharpAt(p2)) return lerpProfile(profile, t); // hard silhouette break+ const f = (t - p1[0]) / (p2[0] - p1[0] || 1);+ const cr = (a, b, c, d) => {+ const f2 = f * f, f3 = f2 * f;+ return 0.5 * ((2 * b) + (-a + c) * f + (2 * a - 5 * b + 4 * c - d) * f2 + (-a + 3 * b - 3 * c + d) * f3);+ };+ const sec = lerpProfile(profile, t)[2]; // sections stay linear+ return [Math.max(0.004, cr(p0[1], p1[1], p2[1], p3[1])),+ Math.max(0.004, cr(p0[2], p1[2], p2[2], p3[2])), sec];+}++function buildVolume(spec, vol) {+ const sides = vol.sides || 12;+ const joints = chainPoints(spec, vol.chain);+ // arc-length table over the joint polyline+ const jArc = [0];+ for (let i = 1; i < joints.length; i++) jArc.push(jArc[i - 1] + G.len(G.sub(joints[i], joints[i - 1])));+ const total = jArc[jArc.length - 1] || 1;+ // DENSE resample: ring every ~step of arc, joints no longer dictate density+ const step = vol.ring_step || Math.max(0.035, total / 36);+ const M = Math.max(joints.length, Math.min(48, Math.round(total / step)));+ const pts = []; const ringT = []; const ringSkin = [];+ const names = spec.chains[vol.chain];+ for (let m = 0; m <= M; m++) {+ const a = (m / M) * total;+ let i = 0; while (i < jArc.length - 2 && a > jArc[i + 1]) i++;+ const f = (a - jArc[i]) / (jArc[i + 1] - jArc[i] || 1);+ pts.push(G.add(G.mul(joints[i], 1 - f), G.mul(joints[i + 1], f)));+ ringT.push(a / total);+ // snap-style skinning: blend the two bracketing joints, smoothstep for soft bends+ const sf = f * f * (3 - 2 * f);+ ringSkin.push(sf < 0.001 ? [[names[i], 1]] : sf > 0.999 ? [[names[i + 1], 1]]+ : [[names[i], 1 - sf], [names[i + 1], sf]]);+ }+ let prof = ringT.map(t => crProfile(vol.profile, t));+ // corner bevel-skip: at sharp path corners, rings inside the compression+ // zone (r·tan(θ/2)) would interpenetrate on the inner side — drop them and+ // let one span bridge the corner. Kills the fold class at any bend.+ {+ const keep = pts.map(() => true);+ for (let m = 1; m < pts.length - 1; m++) {+ const d0 = G.nrm(G.sub(pts[m], pts[m - 1])), d1 = G.nrm(G.sub(pts[m + 1], pts[m]));+ const cosA = Math.max(-1, Math.min(1, G.dot(d0, d1)));+ const th = Math.acos(cosA);+ if (th < 0.17) continue; // <10°: harmless+ const r = Math.max(prof[m][0], prof[m][1]);+ const ex = r * Math.tan(th / 2) * 1.2;+ for (let k = 1; k < pts.length - 1; k++) {+ if (k === m || !keep[k]) continue;+ const d = G.len(G.sub(pts[k], pts[m]));+ if (d < ex) keep[k] = false;+ }+ }+ const f = (arr) => arr.filter((_, i) => keep[i]);+ const pts2 = f(pts), prof2 = f(prof), rt2 = f(ringT), rs2 = f(ringSkin);+ pts.length = 0; pts.push(...pts2);+ prof = prof2; ringT.length = 0; ringT.push(...rt2);+ ringSkin.length = 0; ringSkin.push(...rs2);+ }+ // profile slope warning — the precursor to the fold class. `ring_step` sets how+ // far apart rings sit; the profile sets how fast the radius changes. When the+ // radius moves further between two rings than the rings are apart, the surface+ // turns more than 45° in one span and the next bend flips triangles. Scaling a+ // volume up without scaling `ring_step` with it is the usual way in — and the+ // failure surfaces much later, as "N flipped tris" during an animation.+ {+ let worst = 0, at = 0;+ for (let m = 1; m < pts.length; m++) {+ const ds = G.len(G.sub(pts[m], pts[m - 1]));+ if (ds < 1e-6) continue;+ const dr = Math.max(Math.abs(prof[m][0] - prof[m - 1][0]), Math.abs(prof[m][1] - prof[m - 1][1]));+ const slope = dr / ds;+ if (slope > worst) { worst = slope; at = ringT[m]; }+ }+ if (worst > 0.8) {+ const r = Math.max(prof[0][0], prof[0][1]);+ INFO.push(`WARN volume "${vol.chain}": profile slope ${worst.toFixed(2)} at t=${at.toFixed(2)} `+ + `(ring spacing ${(vol.ring_step || Math.max(0.035, total / 36)).toFixed(3)} vs radius ~${r.toFixed(3)}) `+ + `— rings are crowded relative to how fast the radius changes; this is the shape that flips `+ + `triangles once it bends. Raise "ring_step" on this volume, or soften the profile row there.`);+ }+ }++ const frame = vol.frame === 'up' ? true : vol.frame === 'ground' ? 'ground' : false;+ const resolveSec = (s) => {+ if (!s) return {};+ if (typeof s === 'string') s = { section: s };+ if (s.section) {+ const pp = (spec.sections || {})[s.section];+ if (!pp) throw new Error(`unknown named section "${s.section}"`);+ return { ...s, pts: pp };+ }+ return s;+ };+ const secs = prof.map(r => resolveSec(r[2] || vol.section));+ const rr = prof.map(r => [r[0], r[1]]);+ const rings = require('./section.js').chainRingsRich(pts, rr, sides, frame, secs);+ const capMap = c => c === 'dome' ? 'fanx' : c;+ const caps = (vol.caps || ['ngon', 'ngon']).map(capMap);+ const part = G.partFromRings(rings, sides, caps[0], caps[1], pts);+ // snap skinning: each ring blends its two bracketing joints+ const vIndex = new Map(); part.v.forEach((p, i) => vIndex.set(p, i));+ const skin = part.v.map(() => null);+ part.rings.forEach((ring, s) => {+ for (const p of ring) skin[vIndex.get(p)] = ringSkin[s].map(x => x.slice());+ });+ part.v.forEach((p, i) => {+ if (skin[i]) return;+ const d0 = G.len(G.sub(p, pts[0])), d1 = G.len(G.sub(p, pts[pts.length - 1]));+ skin[i] = [[d0 < d1 ? names[0] : names[names.length - 1], 1]];+ });+ // ── vertex colours: arc bands (0°=spine, 180°=belly) + gradient + noise ──+ const colSpec = vol.colors || {};+ const base = hex2lin((spec.palette[vol.material] || {}).color || '#888888');+ const arcs = (colSpec.arcs || []).map(a => ({ from: a.from, to: a.to, c: hex2lin(a.color) }));+ const C = part.v.map(() => null);+ const rollOf = s2 => (secs[s2] && secs[s2].roll) || 0;+ part.rings.forEach((ring, s2) => {+ ring.forEach((pnt, k) => {+ const vi = vIndex.get(pnt);+ const aDeg = (360 * k / sides + rollOf(s2) * 180 / Math.PI) % 360;+ const fromTop = (450 - aDeg) % 360; // 0=top(+W), 180=bottom+ const sym = fromTop > 180 ? 360 - fromTop : fromTop; // symmetric 0..180+ let c = base;+ for (const a of arcs) if (sym >= a.from && sym <= a.to) c = a.c;+ C[vi] = c.slice();+ });+ });+ for (let i = 0; i < C.length; i++) if (!C[i]) C[i] = base.slice();+ // gradient and noise are NOT applied here any more — they are one whole-body+ // pass in applyShading() below, so every mesh (paws, ears, eyes included)+ // shares one top-to-bottom ramp and one grain size. Arc bands stay local.+ if (colSpec.gradient || colSpec.noise)+ INFO.push(`volume "${vol.chain}": colors.gradient/noise are ignored — shading is one spec-level pass now (see "shading")`);+ return { material: vol.material, V: part.v, F: part.fq, skin, C, chain: vol.chain,+ faceted: vol.faceted,+ _rings: part.rings, _pts: pts, _sides: sides, _ringT: ringT.slice(),+ _ringIdx: part.rings.map(ring => ring.map(p => vIndex.get(p))) };+}++// surface point of a built volume at (t along chain, angle from top in degrees).+// Rings are indexed by their true arc-length t (_ringT), NOT by array position —+// bevel-skip drops rings, so index-proportional lookup lands on the wrong ring.+function surfacePoint(builtVols, anchor) {+ const bv = builtVols[anchor.chain];+ if (!bv) throw new Error(`anchor chain "${anchor.chain}" has no built volume`);+ const rt = bv._ringT; const n = rt.length;+ let s1 = 0; while (s1 < n - 1 && rt[s1] < anchor.t) s1++;+ const s0 = Math.max(0, s1 - 1);+ const span = rt[s1] - rt[s0];+ const f0 = span > 1e-9 ? Math.min(1, Math.max(0, (anchor.t - rt[s0]) / span)) : 0;+ const N = bv._sides;+ const fromTop = ((anchor.around % 360) + 360) % 360;+ const aDeg = (450 - fromTop) % 360;+ const kf = (aDeg / 360) * N;+ const k0 = Math.floor(kf) % N, k1 = (k0 + 1) % N, f = kf - Math.floor(kf);+ const at = s => G.add(G.mul(bv._rings[s][k0], 1 - f), G.mul(bv._rings[s][k1], f));+ const p = G.add(G.mul(at(s0), 1 - f0), G.mul(at(s1), f0));+ const c = G.add(G.mul(bv._pts[s0], 1 - f0), G.mul(bv._pts[s1], f0));+ const out = G.nrm(G.sub(p, c));+ return { p, out, center: c };+}++function buildSpike(spec, p) {+ const host = spec.joints[p.host];+ if (!host) throw new Error(`spike host joint "${p.host}" missing`);+ const dir = G.nrm(p.dir); const pts = [G.add(host, p.offset || [0, 0, 0])];+ const radii = [p.segments[0].r];+ for (const s of p.segments) { pts.push(G.add(pts[pts.length - 1], G.mul(dir, s.len))); radii.push(Math.max(s.r * 0.35, 0.004)); }+ const rings = G.chainRings(pts, radii, p.sides || 6, false);+ const part = G.partFromRings(rings, p.sides || 6, 'ngon', 'fan', pts);+ return { material: p.material, V: part.v, F: part.fq,+ skin: part.v.map(() => [[p.host, 1]]) };+}++function buildEye(spec, p, builtVols) {+ // First-class eyes: placed on the FORWARD hemisphere of the host joint,+ // spread apart on ±X, always looking along `forward` (default +Z).+ const host = spec.joints[p.host];+ if (!host) throw new Error(`eye host joint "${p.host}" missing`);+ const fwd = G.nrm(p.forward || [0, 0, 1]);+ const up = G.nrm(p.up || [0, 1, 0]);+ const side = G.nrm(G.cross(up, fwd));+ const out = [];+ for (const sx of [1, -1]) {+ let c;+ if (p.anchor) { // ride ON the volume surface, bulging out+ const sp = surfacePoint(builtVols, { ...p.anchor, around: p.anchor.around * sx });+ c = G.add(sp.p, G.mul(sp.out, -(p.size ?? 0.05) * 0.35));+ } else {+ c = G.add(G.add(G.add(host, G.mul(fwd, p.face ?? 0.9 * (p.dist ?? 0.3))),+ G.mul(side, sx * (p.spread ?? 0.15))), G.mul(up, p.height ?? 0));+ }+ // small icosphere-ish octahedron subdivided once is enough at these sizes+ const r = p.size ?? 0.05; const V = []; const F = [];+ const oct = [[0,r,0],[0,-r,0],[r,0,0],[-r,0,0],[0,0,r],[0,0,-r]];+ const faces = [[0,4,2],[0,2,5],[0,5,3],[0,3,4],[1,2,4],[1,5,2],[1,3,5],[1,4,3]];+ // subdivide once + project to sphere+ const cache = new Map(); const mid = (a,b) => {+ const k = a < b ? a + '_' + b : b + '_' + a;+ if (cache.has(k)) return cache.get(k);+ const m = G.mul(G.nrm(G.add(oct[a] ?? V[a], oct[b] ?? V[b])), r);+ V.push(m); cache.set(k, oct.length + V.length - 1); return oct.length + V.length - 1;+ };+ const allV = oct.slice();+ const tris = [];+ for (const [a,b,c] of faces) {+ const ab = mid(a,b), bc = mid(b,c), ca = mid(c,a);+ tris.push([a,ab,ca],[ab,b,bc],[ca,bc,c],[ab,bc,ca]);+ }+ for (const v of V) allV.push(v);+ const Vw = allV.map(v => G.add(c, G.mul(G.nrm(v), r)));+ out.push({ material: p.material || 'eye', V: Vw, F: tris,+ skin: Vw.map(() => [[p.host, 1]]) });+ }+ return out;+}++function buildCurve(spec, p) {+ // Curved tapering tube — horns, tusks, trunks, tentacles. Each segment's+ // steering is applied on top of the heading it inherits, so bends ADD UP+ // down the chain: `rise`/`fall`/`ahead`/`behind` pull the heading that many+ // degrees toward the matching world axis, and `coil` swings it in the plane+ // carried along with the tube, which is what produces rings and spirals.+ // Because they accumulate, four mild segments can end up pointing somewhere+ // nobody predicted, so the realized path is reported as one info line rather+ // than discovered in the render.+ const host = spec.joints[p.host];+ if (!host) throw new Error(`curve host joint "${p.host}" missing`);+ let t = G.nrm(p.dir || [0, 0, 1]);+ let side = Math.abs(t[1]) < 0.9 ? G.nrm(G.cross([0, 1, 0], t)) : [1, 0, 0];+ const rad = d => d * Math.PI / 180;+ const pts = [G.add(host, p.offset || [0, 0, 0])];+ const radii = [p.segments[0].r];+ const AX = { rise: [0, 1, 0], fall: [0, -1, 0], ahead: [0, 0, 1], behind: [0, 0, -1] };+ for (const seg of p.segments) {+ for (const [k, dv] of Object.entries(AX)) {+ if (!seg[k]) continue;+ const ax = G.cross(t, dv), l = G.len(ax);+ if (l < 1e-6) continue;+ const axn = G.mul(ax, 1 / l);+ t = G.nrm(G.rod(t, axn, rad(seg[k])));+ side = G.nrm(G.rod(side, axn, rad(seg[k])));+ }+ if (seg.coil) t = G.nrm(G.rod(t, side, rad(seg.coil)));+ pts.push(G.add(pts[pts.length - 1], G.mul(t, seg.len)));+ radii.push(seg.taper ? Math.max(seg.r * 0.3, 0.004) : seg.r);+ }+ const sides = p.sides || 8;+ const rings = G.chainRings(pts, radii, sides, false);+ const part = G.partFromRings(rings, sides, 'ngon', 'fan', pts);+ const d0 = G.nrm(p.dir || [0, 0, 1]);+ const bend = Math.acos(Math.max(-1, Math.min(1, G.dot(d0, t)))) * 180 / Math.PI;+ const dy = pts[pts.length - 1][1] - pts[0][1];+ if (bend > 15) INFO.push(`curve '${p.name || p.host}': steering accumulated to ${bend.toFixed(0)}° — starts ${dirName(d0)}, finishes ${dirName(t)}, far end ${dy >= 0 ? '+' : ''}${dy.toFixed(2)} in y`);+ return { material: p.material, V: part.v, F: part.fq, faceted: p.faceted,+ skin: part.v.map(() => [[p.host, 1]]) };+}++function buildMembrane(spec, p) {+ // Membrane stretched between rib joint-chains — wings, frills, sails, webbed feet.+ // What the viewer reads is the enclosed silhouette, not the ribs inside it, so+ // ribs are listed leading edge → trailing edge and the last one has to come back+ // to the body. A last rib left out at the far end leaves the shape unenclosed:+ // it reads as spread fingers rather than one sheet. The compiler measures the+ // root gap and says so.+ const ribs = p.ribs.map(r => {+ const names = r.chain ? spec.chains[r.chain] : r.joints;+ if (!names) throw new Error(`membrane rib references unknown chain "${r.chain}"`);+ return names.map(n => {+ const q = spec.joints[n];+ if (!q) throw new Error(`membrane rib joint "${n}" missing`);+ return { n, p: q };+ });+ });+ const S = p.along || 8, U = p.across || 3;+ const sampled = ribs.map((rib, ri) => {+ const pl = rib.map(x => x.p);+ const arc = [0];+ for (let i = 1; i < pl.length; i++) arc.push(arc[i - 1] + G.len(G.sub(pl[i], pl[i - 1])));+ const L = arc[arc.length - 1] || 1;+ const t1 = 1 - (p.ribs[ri].shorten || 0);+ const out = [];+ for (let sI = 0; sI <= S; sI++) {+ const tt = (t1 * sI / S) * L;+ let i = 0; while (i < arc.length - 2 && tt > arc[i + 1]) i++;+ const f = (tt - arc[i]) / (arc[i + 1] - arc[i] || 1);+ out.push({+ p: G.add(G.mul(pl[i], 1 - f), G.mul(pl[i + 1], f)),+ skin: f < 0.01 ? [[rib[i].n, 1]] : f > 0.99 ? [[rib[i + 1].n, 1]]+ : [[rib[i].n, 1 - f], [rib[i + 1].n, f]],+ });+ }+ return out;+ });+ const C = (ribs.length - 1) * U + 1; // grid columns+ const V = [], skin = [], F = [];+ const colPt = (j, sI) => {+ const r = Math.min(ribs.length - 2, Math.floor(j / U));+ const u = (j - r * U) / U;+ const a = sampled[r][sI], b = sampled[r + 1][sI];+ let pnt = G.add(G.mul(a.p, 1 - u), G.mul(b.p, u));+ if (sI === S && u > 0 && u < 1 && (p.trailing || 'cusp') === 'cusp') {+ const rootMid = G.mul(G.add(sampled[r][0].p, sampled[r + 1][0].p), 0.5);+ const tipMid = G.mul(G.add(sampled[r][S].p, sampled[r + 1][S].p), 0.5);+ const outDir = G.nrm(G.sub(tipMid, rootMid));+ const span = G.len(G.sub(sampled[r + 1][S].p, sampled[r][S].p));+ pnt = G.sub(pnt, G.mul(outDir, (p.cusp ?? 0.25) * span * Math.sin(Math.PI * u)));+ }+ const w = [];+ for (const [jn, ww] of a.skin) w.push([jn, ww * (1 - u)]);+ for (const [jn, ww] of b.skin) w.push([jn, ww * u]);+ return { pnt, w: w.filter(x => x[1] > 0.001) };+ };+ for (let j = 0; j < C; j++) for (let sI = 0; sI <= S; sI++) {+ const { pnt, w } = colPt(j, sI);+ V.push(pnt); skin.push(w);+ }+ const idx = (j, sI) => j * (S + 1) + sI;+ for (let j = 0; j < C - 1; j++) for (let sI = 0; sI < S; sI++)+ F.push([idx(j, sI), idx(j + 1, sI), idx(j + 1, sI + 1), idx(j, sI + 1)]);+ if (ribs.length >= 3) {+ const gap = G.len(G.sub(sampled[0][0].p, sampled[sampled.length - 1][0].p));+ let reach = 0;+ for (const col of sampled) for (const q of col) reach = Math.max(reach, G.len(G.sub(q.p, sampled[0][0].p)));+ if (gap > 0.35 * reach)+ INFO.push(`WARN membrane '${p.name || 'membrane'}': root gap ${gap.toFixed(2)} between the leading and trailing ribs, ${Math.round(100 * gap / reach)}% of this membrane's own reach. Nothing brings the trailing rib home, so the silhouette stays unenclosed and reads as spread fingers instead of one sheet — end the rib list back at the body.`);+ }+ return { material: p.material, V, F, skin, doubleSided: true, faceted: p.faceted };+}++function buildPaw(spec, p) {+ // Independent paw object: flattened ellipsoid pad with a FLAT sole,+ // snapped under the leg-end joint. size = [length(fwd), width, height].+ const host = spec.joints[p.host];+ if (!host) throw new Error(`paw host joint "${p.host}" missing`);+ const [L, W2, H] = p.size || [0.14, 0.10, 0.07];+ const c = G.add(host, p.offset || [0, H * 0.45 - host[1], L * 0.18]); // sole on ground+ const V = []; const F = [];+ const N1 = p.sides || 10, N2 = 5; // longitude × latitude+ for (let j = 0; j <= N2; j++) {+ const phi = (j / N2) * Math.PI / 2; // upper hemisphere only+ for (let k = 0; k < N1; k++) {+ const th = 2 * Math.PI * k / N1;+ V.push([c[0] + Math.cos(th) * Math.cos(phi) * W2 / 2 * (1 + 0.15 * Math.sin(th)),+ c[1] + Math.sin(phi) * H,+ c[2] + Math.sin(th) * Math.cos(phi) * L / 2]);+ }+ }+ for (let j = 0; j < N2; j++) for (let k = 0; k < N1; k++)+ F.push([j * N1 + k, (j + 1) * N1 + k, (j + 1) * N1 + (k + 1) % N1, j * N1 + (k + 1) % N1]);+ // flat sole: ngon fan on bottom ring (faces down)+ const ci = V.length; V.push([c[0], c[1], c[2]]);+ for (let k = 0; k < N1; k++) F.push([k, (k + 1) % N1, ci]);+ return { material: p.material, V, F, skin: V.map(() => [[p.host, 1]]) };+}++const { mirrorName } = require('./skeleton.js');+function buildFin(spec, p, builtVols) {+ // Flat plate with thickness: outline points [[u,v],...] in a plane at host,+ // plane axes given by udir/vdir (world), extruded ±thickness/2 along normal.+ const host = spec.joints[p.host];+ if (!host) throw new Error(`fin host joint "${p.host}" missing`);+ let U = G.nrm(p.udir || [0, 0, 1]), Vv = G.nrm(p.vdir || [0, 1, 0]);+ let Nn = G.nrm(G.cross(U, Vv));+ let o = G.add(host, p.offset || [0, 0, 0]);+ if (p.anchor) {+ const sp = surfacePoint(builtVols, p.anchor);+ o = sp.p;+ // `around` is measured in the host section's own frame. On a body chain that+ // frame gives the documented 0=spine / 90=side / 180=belly. On a chain that+ // runs vertically (a leg) the same numbers point somewhere else entirely —+ // 90 comes out FRONT, 180 comes out OUTER — so a plate aimed at the outside+ // of a thigh silently lands on its front. Say where it actually went.+ INFO.push(`fin '${p.name || p.host}' anchored on "${p.anchor.chain}" at around=${p.anchor.around ?? 0}`+ + ` faces ${dirName(sp.out)} (world normal ${sp.out.map(x => x.toFixed(2)).join(',')})`+ + ` — "around" is read in the host section's frame, NOT in world space; verify this is the side you meant`);+ if (p.conform !== false) {+ // Default behaviour: the host surface wins. The plate's normal is snapped+ // onto the surface normal at the landing point, and whatever direction the+ // spec asked for is kept only as a measured difference. Opt out per part.+ const dev = Math.acos(Math.max(-1, Math.min(1, G.dot(Nn, sp.out)))) * 180 / Math.PI;+ const U2 = G.sub(U, G.mul(sp.out, G.dot(U, sp.out)));+ if (G.len(U2) > 1e-4) {+ Nn = sp.out.slice();+ U = G.nrm(U2);+ Vv = G.nrm(G.cross(Nn, U));+ if (dev > 25) INFO.push(`fin '${p.name || p.host}': the host surface rotated this plate ${dev.toFixed(0)}° off the direction the spec asked for. If that written direction was the point, set "conform": false on this part.`);+ }+ }+ }+ const th = (p.thickness ?? 0.03) / 2;+ const pOutline = p.points; if (!pOutline || pOutline.length < 3) throw new Error('fin needs >=3 outline points');+ // canonicalise outline to CCW in (u,v) — makes every winding below deterministic+ let area2 = 0;+ for (let i = 0; i < pOutline.length; i++) {+ const [u0, v0] = pOutline[i], [u1, v1] = pOutline[(i + 1) % pOutline.length];+ area2 += u0 * v1 - u1 * v0;+ }+ const poly = area2 < 0 ? pOutline.slice().reverse() : pOutline;+ const ring = poly.map(([u, v]) => G.add(o, G.add(G.mul(U, u), G.mul(Vv, v))));+ const V = [];+ for (const q of ring) V.push(G.add(q, G.mul(Nn, th)));+ for (const q of ring) V.push(G.sub(q, G.mul(Nn, th)));+ const n = ring.length; const F = [];+ for (let i = 1; i < n - 1; i++) F.push([0, i, i + 1]); // front fan (+N)+ for (let i = 1; i < n - 1; i++) F.push([n, n + i + 1, n + i]); // back fan (−N)+ for (let i = 0; i < n; i++) F.push([n + i, n + (i + 1) % n, (i + 1) % n, i]); // rim (outward)+ return { material: p.material, V, F, skin: V.map(() => [[p.host, 1]]) };+}++function mirrorMesh(m, rDelta) { // duplicate across X with flipped winding + L→R joints+ // rDelta: per-R-joint translation from "joints_R" pose overrides — verts follow+ // their joints by skin weight, so a staggered right side carries its skin along+ const shift = (v, infl) => {+ if (!rDelta || !infl) return v;+ let dx = 0, dy = 0, dz = 0;+ for (const [j, w] of infl) {+ const d = rDelta[mirrorName(j)];+ if (d) { dx += w * d[0]; dy += w * d[1]; dz += w * d[2]; }+ }+ return [v[0] + dx, v[1] + dy, v[2] + dz];+ };+ return { material: m.material, faceted: m.faceted, smoothAngle: m.smoothAngle,+ doubleSided: m.doubleSided,+ V: m.V.map((v, i) => shift([-v[0], v[1], v[2]], m.skin && m.skin[i])),+ F: m.F.map(f => f.slice().reverse()),+ C: m.C ? m.C.map(c => c.slice()) : undefined,+ skin: m.skin ? m.skin.map(infl => infl.map(([j, w]) => [mirrorName(j), w])) : undefined,+ // index-based ring topology survives mirroring → mirrored volumes still get+ // proper cylindrical UVs (their own atlas island, required for AO bakes)+ _ringIdx: m._ringIdx, _ringT: m._ringT, _sides: m._sides,+ _pts: m._pts ? m._pts.map(p => [-p[0], p[1], p[2]]) : undefined };+}++function rPoseDeltas(spec) { // joints_R override − default mirror = per-joint shift+ if (!spec.joints_R) return null;+ const d = {};+ for (const [rn, pos] of Object.entries(spec.joints_R)) {+ const lp = spec.joints['L' + rn.slice(1)];+ if (!lp) continue;+ d[rn] = [pos[0] + lp[0], pos[1] - lp[1], pos[2] - lp[2]]; // default was [-lx, ly, lz]+ }+ return d;+}++function compile(spec) {+ const meshes = []; const builtVols = {}; const rd = rPoseDeltas(spec);+ // smoothing angle: spec-level default (50°), overridable per volume/part.+ // mirrorMesh copies it along with everything else it carries.+ const defSmooth = spec.smooth_angle ?? 50;+ for (const vol of spec.volumes || []) {+ const m = buildVolume(spec, vol);+ m.smoothAngle = vol.smooth_angle ?? defSmooth;+ builtVols[vol.chain] = m;+ meshes.push(m);+ if ((spec.mirror || []).includes(vol.chain)) {+ const t = mirrorMesh(m, rd);+ t._mirrorSrc = m; // lets checks compare the twin's shape against the original+ meshes.push(t);+ }+ }+ const BUILDERS = { spike: buildSpike, curve: buildCurve, membrane: buildMembrane,+ paw: buildPaw, fin: (s2, p2) => buildFin(s2, p2, builtVols) };+ for (const p of spec.parts || []) {+ const label = p.name || `${p.type}@${p.host || 'ribs'}`;+ const sa = p.smooth_angle ?? defSmooth;+ // which volume is this part supposed to be growing out of? Either declared+ // via anchor.chain, or the chain that owns its host joint. checks.js needs+ // it to tell "buried in the host" from "floating next to the host".+ const hostChain = (p.anchor && p.anchor.chain)+ || (p.host && Object.keys(spec.chains || {}).find(c => (spec.chains[c] || []).includes(p.host)))+ || null;+ if (p.type === 'eye') {+ for (const m of buildEye(spec, p, builtVols)) {+ m.part = label; m.smoothAngle = sa; m.partType = p.type; m.hostChain = hostChain; meshes.push(m); }+ } else if (BUILDERS[p.type]) {+ const m = BUILDERS[p.type](spec, p);+ m.part = label; m.smoothAngle = sa; m.partType = p.type; m.hostChain = hostChain; meshes.push(m);+ if (p.mirrored) { const t = mirrorMesh(m, rd); t.part = label + '.R'; t._mirrorSrc = m;+ t.partType = p.type; t.hostChain = hostChain; meshes.push(t); }+ } else throw new Error(`unknown part type "${p.type}"`);+ }+ // attach material colors+ for (const m of meshes) {+ const pal = (spec.palette || {})[m.material];+ if (!pal) throw new Error(`material "${m.material}" not in palette`);+ m.color = pal.color; m.rough = pal.rough; m.metal = pal.metal;+ }+ applyShading(spec, meshes);+ return meshes;+}++// ── whole-body shading pass ────────────────────────────────────────────────+// ONE top-to-bottom value ramp and ONE grain size across the entire creature,+// applied to EVERY mesh — volumes, paws, ears, eyes, horns alike. Two reasons+// it lives here instead of inside each volume:+// · the ramp is measured over the WHOLE body's Y range, so the same numbers+// mean the same thing on an upright leg and a horizontal torso (per-volume+// ranges forced the wolf to write bottom -0.16 on legs and -0.04 on the+// torso to fake one consistent light);+// · parts have no `colors` block at all, so under the old scheme paws, ears+// and claws never received any shading and read as stickers on the body.+// Noise size is a FRACTION OF THE MODEL DIAGONAL, not an absolute distance:+// an absolute cell keeps its world size as the creature scales, so the same+// spec on a giant produced grain finer than the vertex spacing and aliased.+function applyShading(spec, meshes) {+ const sh = spec.shading || {};+ const grad = sh.gradient === undefined ? { top: 0.30, bottom: -0.88 } : sh.gradient;+ const nz = sh.noise === undefined ? { size: 0.018, amount: 0.26 } : sh.noise;+ if (!meshes.length) return;++ const lo = [Infinity, Infinity, Infinity], hi = [-Infinity, -Infinity, -Infinity];+ for (const m of meshes) for (const v of m.V) for (let k = 0; k < 3; k++) {+ if (v[k] < lo[k]) lo[k] = v[k];+ if (v[k] > hi[k]) hi[k] = v[k];+ }+ const y0 = lo[1], y1 = hi[1] > lo[1] ? hi[1] : lo[1] + 1e-6;+ const diag = Math.hypot(hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2]) || 1;+ const cell = nz && nz.amount ? (nz.size ?? 0.018) * diag : 0;+ const cl = x => Math.min(1, Math.max(0, x));++ for (const m of meshes) {+ if (!m.C) m.C = m.V.map(() => hex2lin(m.color || '#888888'));+ m.V.forEach((v, i) => {+ let c = m.C[i];+ if (grad) {+ const f = (v[1] - y0) / (y1 - y0);+ const k = 1 + (grad.top ?? 0) * f + (grad.bottom ?? 0) * (1 - f);+ c = [cl(c[0] * k), cl(c[1] * k), cl(c[2] * k)];+ }+ if (cell) {+ const k = 1 + (vnoise(v, cell) - 0.5) * 2 * nz.amount;+ c = [cl(c[0] * k), cl(c[1] * k), cl(c[2] * k)];+ }+ m.C[i] = c;+ });+ }+ INFO.push(`shading: body-Y ramp top ${(grad && grad.top) ?? 0} / bottom ${(grad && grad.bottom) ?? 0}`+ + (cell ? `, grain ${(cell).toFixed(4)} (${((nz.size ?? 0.018) * 100).toFixed(1)}% of the ${diag.toFixed(2)} diagonal)` : ', no grain')+ + ` — applied to all ${meshes.length} meshes`);+}++module.exports = { compile, drainInfo };diff --git a/engine/core/geometry.js b/engine/core/geometry.jsnew file mode 100644index 0000000..40ef0f0--- /dev/null+++ b/engine/core/geometry.js@@ -0,0 +1,110 @@+// ACS engine — geometry core.+// Lineage: Ariescar's Creature project (animal_gen.js) — rotation-minimizing frames,+// miter ring normals, ground-anchored frames, bone-centered rings. Author: Ariescar.+const sub=(a,b)=>[a[0]-b[0],a[1]-b[1],a[2]-b[2]],add=(a,b)=>[a[0]+b[0],a[1]+b[1],a[2]+b[2]],mul=(a,s)=>[a[0]*s,a[1]*s,a[2]*s];+const cross=(a,b)=>[a[1]*b[2]-a[2]*b[1],a[2]*b[0]-a[0]*b[2],a[0]*b[1]-a[1]*b[0]],dot=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2];+const len=a=>Math.hypot(a[0],a[1],a[2]),nrm=a=>{const l=len(a)||1;return[a[0]/l,a[1]/l,a[2]/l];};+function rod(v,ax,ang){const c=Math.cos(ang),s=Math.sin(ang),cr=cross(ax,v),d=dot(ax,v);return[v[0]*c+cr[0]*s+ax[0]*d*(1-c),v[1]*c+cr[1]*s+ax[1]*d*(1-c),v[2]*c+cr[2]*s+ax[2]*d*(1-c)];}+// Parallel-transport frame (rotation-minimizing, no twist) · one ring per point · ring centre = that bone point.+// ★ Ring normal = bone-chain angle bisector (central-difference miter, iron law 18): ring tilt follows the bone bend; no arbitrary tilt.+// radii[s] may be a scalar r (circle) or [rw,rh] (ellipse; rw = horizontal width radius, rh = vertical height radius).+// upFrame=true: use the world-up frame (width→horizontal, height→vertical) → allows flat bodies (fish/salamander); adjacent rings stay aligned, no twist.+// (near-horizontal axial bodies: up-frame is stable; vertical legs → use the default parallel-transport circular frame). Ring normal is still the bone-angle miter (iron law 18).+// ★ Single source of truth: per-point orthogonal frame {tan (tangent, angle-bisector miter), fr:[U (width), W (height)]}. Generation and [fit inverse/rebuild] share one function → invertible.+function framesOf(pts,upFrame){+ const n=pts.length,tan=[];+ for(let s=0;s<n;s++){let t;+ if(n===1)t=[0,0,1];+ else if(s===0)t=nrm(sub(pts[1],pts[0]));+ else if(s===n-1)t=nrm(sub(pts[n-1],pts[n-2]));+ else t=nrm(add(nrm(sub(pts[s+1],pts[s])),nrm(sub(pts[s],pts[s-1])))); // angle-bisector miter+ tan.push(t);}+ let fr=[];+ if(upFrame&&upFrame!=='ground'){ // ★ 'ground' is a string and would make if(upFrame) misread it as up-frame — exclude it first+ // ★ The ring coordinate system must be a pure function of the tangent WITH a fixed sign, or it is not comparable across species (2026-08-03).+ // Old code: "if the tangent is near vertical, swap the reference axis from +Y to +Z" — at the instant of the swap cross(up,t) flips sign entirely and U rotates 180°.+ // Measured: duck neck end tangent ≈(0,1,0.01) yielded U=(-1,0,0); deer neck at the same station, tangent (0,0.59,0.81), yielded U=(+1,0,0),+ // so the two parents' first harmonics were EXACTLY 180° out of phase → blending cancelled them, ring radii 4.89/3.95 collapsed to 0.42, and the neck snapped down to a thread.+ // Fix: fix the sign after computing U — U always points toward world +X (creatures are bilaterally symmetric, so an axial part's width axis already lies along ±X);+ // when U is near-perpendicular to X, fall back to +Y then +Z. On a flip, negate U and W together to keep the frame right-handed (equivalent to a 180° rotation about the tangent).+ // Encoding and rebuilding both call the same framesOf, so this change is an identity for a SINGLE species' round-trip reproduction.+ for(let s=0;s<n;s++){const t=tan[s];const up=Math.abs(dot(t,[0,1,0]))>0.99?[0,0,1]:[0,1,0];+ let U=nrm(cross(up,t)),W=nrm(cross(t,U));+ for(const a of [[1,0,0],[0,1,0],[0,0,1]]){ const dd=dot(U,a);+ if(Math.abs(dd)>0.1){ if(dd<0){U=mul(U,-1);W=mul(W,-1);} break; } }+ fr.push([U,W]);} // U = horizontal width axis, W = vertical height axis+ } else if(upFrame==='ground'){+ // ★ Ground-anchored frame (2026-07-29): U = world DOWN projected onto the ring plane. When the ring plane is near horizontal, fall back to world -Z.+ // Why it is needed: a parallel-transport frame's absolute roll is decided by its own bone chain, so it is not comparable across species — measured, the same+ // "lowest point of the end ring" sits at -119° in the horse's frame, +90° in the giraffe's, +137° in the theropod's. Blending by index therefore averages+ // vectors pointing in different world directions: two flat foot soles blend into a non-flat one (0.482~1.454).+ // With down-anchoring, the bottom edge always lands at local angle ~0°; pure blending (zero post-processing) gives sole deviation 0.0002~0.055.+ // Equivalent to the old studio line's "strip pitch/roll from ring orientation, keep only yaw → soles flat by construction".+ for(let s=0;s<n;s++){const t=tan[s];+ let d=[0,-1,0],U=sub(d,mul(t,dot(d,t)));+ if(len(U)<0.15){d=[0,0,-1];U=sub(d,mul(t,dot(d,t)));}+ U=nrm(U);fr.push([U,nrm(cross(t,U))]);}+ } else {+ const ref=Math.abs(tan[0][1])<0.9?[0,1,0]:[1,0,0];let U=nrm(cross(tan[0],ref));fr.push([U,nrm(cross(tan[0],U))]);+ for(let s=1;s<n;s++){const t0=tan[s-1],t1=tan[s];let Un=fr[s-1][0];const ax=cross(t0,t1);if(len(ax)>1e-6){const a=nrm(ax),ang=Math.acos(Math.max(-1,Math.min(1,dot(t0,t1))));Un=rod(Un,a,ang);}Un=nrm(sub(Un,mul(t1,dot(Un,t1))));fr.push([Un,nrm(cross(t1,Un))]);}+ }+ return {tan,fr};+}+function chainRings(pts,radii,N,upFrame){+ const n=pts.length, {fr}=framesOf(pts,upFrame);+ const rad=s=>Array.isArray(radii[s])?radii[s]:[radii[s],radii[s]]; // [rw,rh]+ const rings=[];for(let s=0;s<n;s++){const U2=fr[s][0],W2=fr[s][1],[rw,rh]=rad(s),r=[];for(let k=0;k<N;k++){const a=2*Math.PI*k/N;r.push(add(pts[s],add(mul(U2,Math.cos(a)*rw),mul(W2,Math.sin(a)*rh))));}rings.push(r);}+ return rings;+}+// rings→mesh. ★ centers = the bone point at each ring's centre (used by the bone-centre gate).+// ★ Cap STYLE is a topological property of the part, not a constant (2026-07-31).+// Real failure: hybrids always emitted (...,true,true) = FAN caps at both ends (one extra centre vertex + N triangles),+// but the canonical ear is actually an NGON cap (12 verts / 10 all-quad faces, no centre vertex) → hybrid ears went from 12v/10f to 14v/18f,+// and the root, which should stay OPEN (buried in the head), got sealed = the "ear topology error" the user pointed out in the viewport.+// capS/capE stay backward compatible: true→'fan' (bit-for-bit unchanged), false→'none'; 'ngon' (centre-less polygon cap) is new.+function partFromRings(rings,N,capS,capE,centers){+ const V=[],F=[],idx=[];+ for(const r of rings){const ri=[];for(const p of r){ri.push(V.length);V.push(p.slice());}idx.push(ri);}+ for(let s=0;s<idx.length-1;s++)for(let k=0;k<N;k++)F.push([idx[s][k],idx[s][(k+1)%N],idx[s+1][(k+1)%N],idx[s+1][k]]);+ const styleOf=x=>x===true?'fan':(x===false||x==null?'none':x); // 'fanx' = slightly convex (synthesis path only)+ // ★ Convex caps (2026-07-31, CAP switch): once the sole is flattened the end ring is no longer planar, and a flat fan cap FOLDS BACK INTO the tube+ // — measured, 563 of the leg's self-intersection points involve the end cap and only 38 the root cap. Push the cap centre slightly outward along the tube axis+ // and the cap becomes a shallow cone, structurally incapable of caving back into the tube. The push scales with that ring's radius (no absolute constant).+ // ★ 'fanx' = convex fan cap: synthesis path (hybrids) ONLY. The fit path must reproduce the user's REF bit-for-bit — do not touch it.+ const CONVEX_K=+(process.env.CAPK||0.15);+ const capFan=(ri,fl,nb,cvx)=>{let c=[0,0,0];for(const i of ri)c=add(c,V[i]);c=mul(c,1/N);+ // ★ Push the cap centre outward along THE RING'S OWN NORMAL by that ring's non-planarity (2026-08-01).+ // Measured: self-intersecting legs have end-ring non-planarity median 0.178 / max 0.780; non-intersecting ones only 0.020 / max 0.506+ // — sole flattening straightens the lower half of the ring while the upper half stays round, so the end ring is non-planar and the fan cap's triangles bend out into the side wall.+ // Push amount = that ring's max distance from its best-fit plane (measured from data, not a constant); a planar ring pushes 0 = bit-for-bit unchanged.+ if(process.env.CAPLIFT==='on'){ /* Off by default: measured zero effect on pass rate (786/786); non-planarity and self-intersection are correlated, not causal */+ let nn=[0,0,0];+ for(let i=0;i<ri.length;i++){const p=V[ri[i]],q=V[ri[(i+1)%ri.length]];+ nn=[nn[0]+(p[1]-q[1])*(p[2]+q[2]), nn[1]+(p[2]-q[2])*(p[0]+q[0]), nn[2]+(p[0]-q[0])*(p[1]+q[1])];}+ const ln=len(nn);+ if(ln>1e-9){ const u=[nn[0]/ln,nn[1]/ln,nn[2]/ln];+ let dev=0; for(const i of ri){const d=Math.abs(dot(sub(V[i],c),u)); if(d>dev)dev=d;}+ if(dev>1e-9){ const sgn=fl?-1:1; c=[c[0]+u[0]*dev*sgn, c[1]+u[1]*dev*sgn, c[2]+u[2]*dev*sgn]; } }+ }+ if(cvx&&nb&&nb.length){ let nc=[0,0,0];for(const i of nb)nc=add(nc,V[i]);nc=mul(nc,1/nb.length);+ const ax=sub(c,nc), L=len(ax);+ if(L>1e-9){ const rr=ri.reduce((t,i)=>t+len(sub(V[i],c)),0)/ri.length;+ c=add(c,mul(ax,CONVEX_K*rr/L)); } }+ const ci=V.length;V.push(c);for(let k=0;k<N;k++)F.push(fl?[ri[(k+1)%N],ri[k],ci]:[ri[k],ri[(k+1)%N],ci]);};+ // Ngon cap: no centre vertex; the ring's own points form the faces (even edge count → quad strip; odd → one triangle at the end)+ const capNgon=(ri,fl)=>{const o=fl?ri.slice().reverse():ri.slice(), m=o.length;+ // Fan quads out from o[0]; an even edge count covers exactly (hexagon = 2 quads), an odd count needs one closing triangle.+ // ★ The old code's closing-triangle condition was wrong: hexagons got two extra triangles (ear 12 faces vs canonical 10).+ let last=0;+ for(let k=0;k+3<m;k+=2){F.push([o[0],o[k+1],o[k+2],o[k+3]]); last=k+3;}+ if(last<m-1)F.push([o[0],o[m-2],o[m-1]]);};+ const doCap=(ri,fl,st,nb)=>{ if(st==='fan'||st==='fanx')capFan(ri,fl,nb,st==='fanx'); else if(st==='ngon')capNgon(ri,fl); };+ doCap(idx[idx.length-1],false,styleOf(capE),idx.length>1?idx[idx.length-2]:null);+ doCap(idx[0],true,styleOf(capS),idx.length>1?idx[1]:null);+ // ★★★ Single source of truth (same fix as buildPartFromFit): v was rounded while rings kept raw values → the two sides round differently at the .0005 boundary.+ // Rings must always POINT AT the vertex object inside v; never keep a separate copy.+ const Vr=V.map(q=>q.map(x=>+x.toFixed(3)));+ let _o=0; const Rr=rings.map(r=>r.map(()=>Vr[_o++]));+ return {v:Vr,fq:F,rings:Rr,centers:(centers||[]).slice()};+}+module.exports = { sub, add, mul, cross, dot, len, nrm, rod, framesOf, chainRings, partFromRings };diff --git a/engine/core/glb.js b/engine/core/glb.jsnew file mode 100644index 0000000..2f25a35--- /dev/null+++ b/engine/core/glb.js@@ -0,0 +1,176 @@+// ACS engine — GLB writer (skinned + animated). Author: Ariescar.+// glTF 2.0 binary: joint node tree, skin (IBM), per-vertex JOINTS_0/WEIGHTS_0,+// LINEAR-sampled animations, per-material primitives, flat PBR materials.+'use strict';+const fs = require('fs');++const { smoothSplit } = require('./normals.js');++function triangulate(faces) {+ const out = [];+ for (const f of faces) {+ if (f.length === 3) out.push(f);+ else if (f.length === 4) out.push([f[0], f[1], f[2]], [f[0], f[2], f[3]]);+ }+ return out;+}+function hex2rgb(h) {+ const x = parseInt(h.replace('#', ''), 16);+ const s = c => Math.pow(c / 255, 2.2);+ return [s((x >> 16) & 255), s((x >> 8) & 255), s(x & 255)];+}++// build = { meshes, skeleton?, ibm?, anims? }+// meshes: [{material,color,rough,metal,V,F, skin?: [ [[jointName,w],...] per vertex ]}]+// skeleton: { joints:[{name,pos,parent}], index:{} } ibm: Float32Array(16*n)+// anims: [{name,duration,channels:[{joint,path,times,values}]}]+function writeGLB(build, outPath, opts = {}) {+ const { meshes, skeleton, ibm, anims } = build;+ const names = opts.names || {}; // internal joint name → public export name+ const bufs = []; let byteLen = 0;+ const pushBuf = (ab) => {+ const pad = (4 - (ab.byteLength % 4)) % 4;+ const view = { byteOffset: byteLen, byteLength: ab.byteLength };+ bufs.push(Buffer.from(ab.buffer ? ab.buffer.slice(ab.byteOffset, ab.byteOffset + ab.byteLength) : ab));+ if (pad) bufs.push(Buffer.alloc(pad));+ byteLen += ab.byteLength + pad;+ return view;+ };+ const gltf = {+ asset: Object.assign({ version: '2.0', generator: 'acs-engine' }, opts.asset || {}),+ scenes: [{ nodes: [] }], scene: 0,+ nodes: [], meshes: [{ name: 'creature', primitives: [] }],+ materials: [], accessors: [], bufferViews: [], buffers: [],+ };+ const addAccessor = (arr, ctype, type, target, minmax) => {+ const bv = pushBuf(arr);+ gltf.bufferViews.push(target ? { buffer: 0, ...bv, target } : { buffer: 0, ...bv });+ const acc = { bufferView: gltf.bufferViews.length - 1, componentType: ctype,+ count: arr.length / ({ SCALAR: 1, VEC2: 2, VEC3: 3, VEC4: 4, MAT4: 16 }[type]), type };+ if (minmax) { acc.min = minmax[0]; acc.max = minmax[1]; }+ gltf.accessors.push(acc);+ return gltf.accessors.length - 1;+ };++ // ── joint nodes ──+ let jointNodeBase = 0; let skinIndex;+ if (skeleton) {+ const { localTranslations } = require('./skeleton.js');+ const locals = localTranslations(skeleton);+ jointNodeBase = gltf.nodes.length;+ skeleton.joints.forEach((j, i) => {+ gltf.nodes.push({ name: names[j.name] || j.name, translation: locals[i] });+ });+ skeleton.joints.forEach((j, i) => {+ if (j.parent >= 0) {+ const pn = gltf.nodes[jointNodeBase + j.parent];+ (pn.children = pn.children || []).push(jointNodeBase + i);+ } else gltf.scenes[0].nodes.push(jointNodeBase + i);+ });+ const ibmAcc = addAccessor(ibm, 5126, 'MAT4');+ gltf.skins = [{ name: 'creature_rig', joints: skeleton.joints.map((_, i) => jointNodeBase + i),+ inverseBindMatrices: ibmAcc }];+ skinIndex = 0;+ }++ // ── mesh node ──+ const meshNode = { name: 'creature', mesh: 0 };+ if (skinIndex !== undefined) meshNode.skin = skinIndex;+ gltf.nodes.push(meshNode);+ gltf.scenes[0].nodes.push(gltf.nodes.length - 1);++ // ── primitives (merged: one primitive + one material per distinct material) ──+ // Mirrored twins and repeated parts share a palette entry; without merging+ // every mesh ships its own primitive+material copy (the 67-material class).+ // Semantic part names are the palette keys, so merging by material signature+ // loses nothing the judge needs.+ const groups = new Map();+ for (const m of meshes) {+ let tris = triangulate(m.F);+ // Smoothing angle: faces meeting at a vertex are averaged when they sit+ // within `smoothAngle` of each other, and the vertex is duplicated only+ // where it really carries two smoothing groups. `faceted: true` is just+ // smoothAngle 0 (every face its own group). Default lives in cli.js.+ const deg = m.faceted ? 0 : (m.smoothAngle ?? 50);+ const r = smoothSplit(m.V, tris, deg, { C: m.C, skin: m.skin, UV: m.UV });+ m.V = r.V; if (m.C) m.C = r.C; if (m.skin) m.skin = r.skin; if (m.UV) m.UV = r.UV;+ tris = r.tris;+ const N = r.N;+ const key = [m.material, m.color, m.rough ?? 0.9, m.metal ?? 0, !!m.doubleSided, !!m.C, !!m.UV].join('|');+ let g = groups.get(key);+ if (!g) groups.set(key, g = { m, V: [], N: [], C: m.C ? [] : null, UV: m.UV ? [] : null,+ skin: m.skin ? [] : null, tris: [] });+ const off = g.V.length;+ g.V.push(...m.V); g.N.push(...N);+ if (g.C && m.C) g.C.push(...m.C);+ if (g.UV && m.UV) g.UV.push(...m.UV);+ if (g.skin && m.skin) g.skin.push(...m.skin);+ for (const t of tris) g.tris.push([t[0] + off, t[1] + off, t[2] + off]);+ }+ for (const g of groups.values()) {+ const { m } = g;+ const mins = [0,1,2].map(k => Math.min(...g.V.map(v => v[k])));+ const maxs = [0,1,2].map(k => Math.max(...g.V.map(v => v[k])));+ const attrs = {+ POSITION: addAccessor(new Float32Array(g.V.flat()), 5126, 'VEC3', 34962, [mins, maxs]),+ NORMAL: addAccessor(new Float32Array(g.N.flat()), 5126, 'VEC3', 34962),+ };+ if (g.C) attrs.COLOR_0 = addAccessor(new Float32Array(g.C.flat()), 5126, 'VEC3', 34962);+ if (g.UV) attrs.TEXCOORD_0 = addAccessor(new Float32Array(g.UV.flat()), 5126, 'VEC2', 34962);+ if (skeleton && g.skin) {+ const J = new Uint16Array(g.V.length * 4); const W = new Float32Array(g.V.length * 4);+ g.skin.forEach((infl, vi) => {+ let tot = 0; infl.slice(0, 4).forEach(([, w]) => tot += w);+ infl.slice(0, 4).forEach(([jn, w], k) => {+ const ji = skeleton.index[jn];+ if (ji === undefined) throw new Error(`skin references unknown joint "${jn}"`);+ J[vi * 4 + k] = ji; W[vi * 4 + k] = w / (tot || 1);+ });+ });+ attrs.JOINTS_0 = addAccessor(J, 5123, 'VEC4', 34962);+ attrs.WEIGHTS_0 = addAccessor(W, 5126, 'VEC4', 34962);+ }+ const idxAcc = addAccessor(new Uint32Array(g.tris.flat()), 5125, 'SCALAR', 34963);+ const mi = gltf.materials.length;+ const mat = { name: m.material, pbrMetallicRoughness: {+ baseColorFactor: g.C ? [1, 1, 1, 1] : [...hex2rgb(m.color), 1],+ metallicFactor: m.metal ?? 0, roughnessFactor: m.rough ?? 0.9 } };+ if (m.doubleSided) mat.doubleSided = true; // zero-thickness membranes+ gltf.materials.push(mat);+ gltf.meshes[0].primitives.push({ attributes: attrs, indices: idxAcc, material: mi });+ }++ // ── animations ──+ if (anims && anims.length && skeleton) {+ gltf.animations = anims.map(a => {+ const samplers = []; const channels = [];+ for (const ch of a.channels) {+ const tAcc = addAccessor(new Float32Array(ch.times), 5126, 'SCALAR', null,+ [[Math.min(...ch.times)], [Math.max(...ch.times)]]);+ const vAcc = addAccessor(new Float32Array(ch.values), 5126, ch.path === 'rotation' ? 'VEC4' : 'VEC3');+ samplers.push({ input: tAcc, output: vAcc, interpolation: 'LINEAR' });+ channels.push({ sampler: samplers.length - 1,+ target: { node: jointNodeBase + skeleton.index[ch.joint], path: ch.path } });+ }+ return { name: a.name, samplers, channels };+ });+ }++ gltf.buffers.push({ byteLength: byteLen });+ const bin = Buffer.concat(bufs);+ let js = Buffer.from(JSON.stringify(gltf)); const jpad = (4 - (js.length % 4)) % 4;+ if (jpad) js = Buffer.concat([js, Buffer.alloc(jpad, 0x20)]);+ const total = 12 + 8 + js.length + 8 + bin.length;+ const head = Buffer.alloc(12); head.write('glTF'); head.writeUInt32LE(2, 4); head.writeUInt32LE(total, 8);+ const jh = Buffer.alloc(8); jh.writeUInt32LE(js.length, 0); jh.writeUInt32LE(0x4E4F534A, 4);+ const bh = Buffer.alloc(8); bh.writeUInt32LE(bin.length, 0); bh.writeUInt32LE(0x004E4942, 4);+ // The README's own first command writes to out/wolf.glb, and a fresh clone has+ // no out/ — without this the very first build a newcomer runs dies on ENOENT+ // after doing all the work.+ const dir = require('path').dirname(outPath);+ if (dir && dir !== '.') fs.mkdirSync(dir, { recursive: true });+ fs.writeFileSync(outPath, Buffer.concat([head, jh, js, bh, bin]));+ return total;+}++module.exports = { writeGLB, triangulate };diff --git a/engine/core/normals.js b/engine/core/normals.jsnew file mode 100644index 0000000..3f2f5bd--- /dev/null+++ b/engine/core/normals.js@@ -0,0 +1,131 @@+// ACS engine — vertex normals with a smoothing angle. Author: Ariescar.+//+// Two entry points, both ANGLE-weighted (each face contributes in proportion to+// the corner angle it subtends at the vertex, not to its area). Area weighting+// lets one big skinny triangle drag a normal off by tens of degrees, and because+// AO bakes from these normals the error lands in the shipped vertex colours.+//+// vertexNormals(V, tris) → one normal per vertex, fully smooth.+// Used by the AO bake (it only needs a+// hemisphere axis, never a crease).+// smoothSplit(V, tris, deg, attrs) → normals WITH creases: faces meeting at+// a vertex are grouped by dihedral angle,+// and the vertex is duplicated only when+// it genuinely carries more than one+// smoothing group. deg <= 0 = every face+// its own group (the old `faceted`).+//+// Splitting only at real creases is the point: a 50° default leaves an organic+// mass fully smooth while keeping `sharp` profile breaks and plate rims crisp,+// and it costs a handful of extra vertices instead of tripling the mesh.+'use strict';++function faceData(V, tris) {+ const fn = [], ang = [];+ for (const [a, b, c] of tris) {+ const A = V[a], B = V[b], C = V[c];+ const u = [B[0]-A[0], B[1]-A[1], B[2]-A[2]];+ const w = [C[0]-A[0], C[1]-A[1], C[2]-A[2]];+ const n = [u[1]*w[2]-u[2]*w[1], u[2]*w[0]-u[0]*w[2], u[0]*w[1]-u[1]*w[0]];+ const l = Math.hypot(n[0], n[1], n[2]);+ fn.push(l > 1e-12 ? [n[0]/l, n[1]/l, n[2]/l] : null); // null = degenerate+ const corner = (p, q, r) => {+ const e1 = [q[0]-p[0], q[1]-p[1], q[2]-p[2]];+ const e2 = [r[0]-p[0], r[1]-p[1], r[2]-p[2]];+ const l1 = Math.hypot(e1[0], e1[1], e1[2]), l2 = Math.hypot(e2[0], e2[1], e2[2]);+ if (l1 < 1e-12 || l2 < 1e-12) return 0;+ const d = (e1[0]*e2[0] + e1[1]*e2[1] + e1[2]*e2[2]) / (l1 * l2);+ return Math.acos(Math.max(-1, Math.min(1, d)));+ };+ ang.push([corner(A, B, C), corner(B, C, A), corner(C, A, B)]);+ }+ return { fn, ang };+}++function incidence(vcount, tris) {+ const inc = Array.from({ length: vcount }, () => []);+ tris.forEach((t, ti) => t.forEach((v, k) => inc[v].push([ti, k])));+ return inc;+}++function vertexNormals(V, tris) {+ const { fn, ang } = faceData(V, tris);+ const N = V.map(() => [0, 0, 0]);+ tris.forEach((t, ti) => {+ const n = fn[ti]; if (!n) return;+ t.forEach((v, k) => {+ const w = ang[ti][k];+ N[v][0] += n[0]*w; N[v][1] += n[1]*w; N[v][2] += n[2]*w;+ });+ });+ return N.map(n => { const l = Math.hypot(n[0], n[1], n[2]); return l > 1e-12 ? [n[0]/l, n[1]/l, n[2]/l] : [0, 1, 0]; });+}++// group a vertex's incident faces: two faces join when their normals sit within+// `deg` of each other (transitively — a fan that turns gradually stays one group,+// a `sharp` break with no face bridging it does not).+function groupFaces(list, fn, cosT) {+ const p = list.map((_, i) => i);+ const find = i => { while (p[i] !== i) { p[i] = p[p[i]]; i = p[i]; } return i; };+ for (let i = 0; i < list.length; i++) {+ const a = fn[list[i][0]]; if (!a) continue;+ for (let j = i + 1; j < list.length; j++) {+ const b = fn[list[j][0]]; if (!b) continue;+ if (a[0]*b[0] + a[1]*b[1] + a[2]*b[2] >= cosT) {+ const ra = find(i), rb = find(j); if (ra !== rb) p[ra] = rb;+ }+ }+ }+ const byRoot = new Map();+ list.forEach((_, i) => {+ const r = find(i);+ if (!byRoot.has(r)) byRoot.set(r, []);+ byRoot.get(r).push(i);+ });+ return [...byRoot.values()];+}++// attrs: { C?, skin?, UV? } parallel arrays that must follow any vertex split.+// Returns { V, tris, N, C, skin, UV, split } — arrays are NEW, inputs untouched.+function smoothSplit(V, tris, deg, attrs = {}) {+ const { fn, ang } = faceData(V, tris);+ const inc = incidence(V.length, tris);+ const cosT = Math.cos(Math.max(0, Math.min(180, deg)) * Math.PI / 180);+ const hard = !(deg > 0);++ const outV = V.map(v => v);+ const outC = attrs.C ? attrs.C.map(c => c) : null;+ const outS = attrs.skin ? attrs.skin.map(s => s) : null;+ const outU = attrs.UV ? attrs.UV.map(u => u) : null;+ const outT = tris.map(t => t.slice());+ const N = V.map(() => null);+ let split = 0;++ for (let v = 0; v < V.length; v++) {+ const list = inc[v];+ if (!list.length) { N[v] = [0, 1, 0]; continue; }+ const groups = hard ? list.map(x => [list.indexOf(x)]) : groupFaces(list, fn, cosT);+ groups.forEach((gi, gidx) => {+ let acc = [0, 0, 0];+ for (const i of gi) {+ const [ti, k] = list[i]; const n = fn[ti]; if (!n) continue;+ const w = ang[ti][k];+ acc = [acc[0] + n[0]*w, acc[1] + n[1]*w, acc[2] + n[2]*w];+ }+ const l = Math.hypot(acc[0], acc[1], acc[2]);+ const nn = l > 1e-12 ? [acc[0]/l, acc[1]/l, acc[2]/l]+ : (fn[list[gi[0]][0]] || [0, 1, 0]);+ if (gidx === 0) { N[v] = nn; return; }+ // second and later smoothing groups get their own copy of the vertex+ const nv = outV.length;+ outV.push(V[v]); N.push(nn); split++;+ if (outC) outC.push(attrs.C[v]);+ if (outS) outS.push(attrs.skin[v]);+ if (outU) outU.push(attrs.UV[v]);+ for (const i of gi) { const [ti, k] = list[i]; outT[ti][k] = nv; }+ });+ }+ return { V: outV, tris: outT, N, C: outC, skin: outS, UV: outU, split };+}++module.exports = { vertexNormals, smoothSplit };diff --git a/engine/core/relative.js b/engine/core/relative.jsnew file mode 100644index 0000000..d4a294a--- /dev/null+++ b/engine/core/relative.js@@ -0,0 +1,67 @@+// ACS engine — relational joint resolver. Author: Ariescar.+// Lets specs express the skeleton in PROPORTIONS (segment offsets) instead of+// raw world coordinates. Absolute [x,y,z] stays legal everywhere.+//+// "Spine": {"from": "Hips", "fwd": 0.47, "up": 0.01} offset form+// "TailTip":{"from": "Tail2", "dir": [0,-0.9,-0.35], "len": 0.34} dir+len form+// "LToe": {"from": "LWrist","fwd": 0.14, "ground": 0.035} ground = absolute Y+//+// fwd = +z, up = +y, side = +x. "ground" overrides Y after the offset (for feet).+// Resolution is order-independent (iterates until fixed point); cycles throw.+// Idempotent: already-resolved arrays pass through untouched.+'use strict';+const G = require('./geometry.js');++function resolveJoints(spec) {+ const J = spec.joints;+ let pending = Object.keys(J).filter(n => !Array.isArray(J[n]));+ let guard = pending.length + 1;+ while (pending.length && guard-- > 0) {+ const next = [];+ for (const name of pending) {+ const d = J[name];+ const base = J[d.from];+ if (!base) throw new Error(`joint "${name}": "from" references unknown joint "${d.from}"`);+ if (!Array.isArray(base)) { next.push(name); continue; } // dependency not ready yet+ let p;+ if (d.dir && d.len !== undefined) p = G.add(base, G.mul(G.nrm(d.dir), d.len));+ else p = [base[0] + (d.side || 0), base[1] + (d.up || 0), base[2] + (d.fwd || 0)];+ if (d.ground !== undefined) p[1] = d.ground;+ J[name] = p;+ }+ if (next.length === pending.length)+ throw new Error(`joint dependency cycle: ${next.join(', ')}`);+ pending = next;+ }+ if (pending.length) throw new Error(`unresolvable joints: ${pending.join(', ')}`);++ // Optional right-side pose overrides: "joints_R" repositions auto-mirrored+ // R* joints AFTER the default mirror, so paired parts grow symmetric but the+ // bind pose can stagger (raised right arm, turned right wing). Same forms as+ // "joints"; "from" may reference any resolved joint or another joints_R entry.+ if (spec.joints_R) {+ const R = spec.joints_R;+ const look = n => Array.isArray(R[n]) ? R[n] : (Array.isArray(J[n]) ? J[n] : null);+ let pend = Object.keys(R).filter(n => !Array.isArray(R[n]));+ let g2 = pend.length + 1;+ while (pend.length && g2-- > 0) {+ const next = [];+ for (const name of pend) {+ const d = R[name];+ const base = look(d.from);+ if (!base) { next.push(name); continue; }+ let p;+ if (d.dir && d.len !== undefined) p = G.add(base, G.mul(G.nrm(d.dir), d.len));+ else p = [base[0] + (d.side || 0), base[1] + (d.up || 0), base[2] + (d.fwd || 0)];+ if (d.ground !== undefined) p[1] = d.ground;+ R[name] = p;+ }+ if (next.length === pend.length) throw new Error(`joints_R dependency cycle: ${next.join(', ')}`);+ pend = next;+ }+ if (pend.length) throw new Error(`unresolvable joints_R: ${pend.join(', ')}`);+ }+ return spec;+}++module.exports = { resolveJoints };diff --git a/engine/core/section.js b/engine/core/section.jsnew file mode 100644index 0000000..b9e77c3--- /dev/null+++ b/engine/core/section.js@@ -0,0 +1,53 @@+// ACS engine — cross-section vocabulary. Author: Ariescar.+// Rich ring generation on top of the frame math (framesOf lineage):+// exp — superellipse exponent: 2 = ellipse, 3-6 = boxy slab, 1.2-1.6 = diamond-ish+// bias — vertical asymmetry: +0.3 = egg (fuller on top), -0.3 = keel (fuller below)+// roll — rotate the section in its plane (radians)+// Per-ring overrides allowed via the profile row: [t, w, h, {exp,bias,roll}]+'use strict';+const G = require('./geometry.js');++function sectionPoint(a, rw, rh, exp, bias) {+ const c = Math.cos(a), s = Math.sin(a);+ const e = 2 / (exp || 2);+ let x = Math.sign(c) * Math.pow(Math.abs(c), e) * rw;+ let y = Math.sign(s) * Math.pow(Math.abs(s), e) * rh;+ if (bias) y *= s > 0 ? (1 + bias) : (1 - bias);+ return [x, y];+}++// named custom section: closed 2D polygon [[x,y]...] in ~unit space, sampled+// by angle position around the list. Concave relief — bark flutes, crescents,+// star sections — has to be built as real geometry: a texture can darken a+// groove but never moves the silhouette, and the silhouette is what gets read.+function polyPoint(pts, a, rw, rh) {+ const n = pts.length;+ const f = (((a / (2 * Math.PI)) % 1) + 1) % 1 * n;+ const i = Math.floor(f) % n, j = (i + 1) % n, t = f - Math.floor(f);+ return [(pts[i][0] + (pts[j][0] - pts[i][0]) * t) * rw,+ (pts[i][1] + (pts[j][1] - pts[i][1]) * t) * rh];+}++// pts: chain joints; radii: [[rw,rh],...] per joint; secs: [{exp,bias,roll}] per joint+function chainRingsRich(pts, radii, N, frame, secs) {+ const { fr } = require('./geometry.js').framesOf+ ? require('./geometry.js').framesOf(pts, frame)+ : (() => { throw new Error('framesOf missing'); })();+ const rings = [];+ for (let s = 0; s < pts.length; s++) {+ const [U, W] = fr[s];+ const [rw, rh] = Array.isArray(radii[s]) ? radii[s] : [radii[s], radii[s]];+ const sec = secs[s] || {};+ const ring = [];+ for (let k = 0; k < N; k++) {+ const a = 2 * Math.PI * k / N + (sec.roll || 0);+ const [x, y] = sec.pts ? polyPoint(sec.pts, a, rw, rh)+ : sectionPoint(a, rw, rh, sec.exp, sec.bias);+ ring.push(G.add(pts[s], G.add(G.mul(U, x), G.mul(W, y))));+ }+ rings.push(ring);+ }+ return rings;+}++module.exports = { chainRingsRich, sectionPoint, polyPoint };diff --git a/engine/core/skeleton.js b/engine/core/skeleton.jsnew file mode 100644index 0000000..574307b--- /dev/null+++ b/engine/core/skeleton.js@@ -0,0 +1,160 @@+// ACS engine — skeleton builder. Author: Ariescar.+// Builds the joint tree from spec (chains + attach + mirror), computes local+// bind transforms and inverse bind matrices for GLB skinning.+'use strict';+const G = require('./geometry.js');++function mirrorName(n) { return n.startsWith('L') ? 'R' + n.slice(1) : n; }++// Returns { joints: [{name, pos, parent(index|-1)}], index: {name->i}, mirroredChains: {Lname->Rname} }+function buildSkeleton(spec) {+ const joints = []; const index = {};+ const addJoint = (name, pos, parentName) => {+ if (name in index) return index[name];+ const pi = parentName == null ? -1 : index[parentName];+ if (parentName != null && pi === undefined) throw new Error(`joint "${name}" parent "${parentName}" not yet defined`);+ index[name] = joints.length;+ joints.push({ name, pos: pos.slice(), parent: pi === undefined ? -1 : pi });+ return index[name];+ };++ const attach = spec.attach || {};+ // 1) axis-like chains first (those not attached to anything), in spec order+ const chainNames = Object.keys(spec.chains);+ const rootChains = chainNames.filter(c => !(c in attach));+ const subChains = chainNames.filter(c => c in attach);+ if (rootChains.length === 0) throw new Error('need at least one root chain (not listed in "attach")');+ for (const cn of rootChains) {+ const names = spec.chains[cn];+ // root chain: middle-out parenting is overkill; parent sequentially from first+ addJoint(names[0], spec.joints[names[0]], null);+ for (let i = 1; i < names.length; i++) addJoint(names[i], spec.joints[names[i]], names[i - 1]);+ }+ // 2) attached chains (legs etc.): root parents to the attach joint+ for (const cn of subChains) {+ const names = spec.chains[cn];+ const host = attach[cn];+ if (!(host in index)) throw new Error(`chain "${cn}" attaches to unknown joint "${host}"`);+ addJoint(names[0], spec.joints[names[0]], host);+ for (let i = 1; i < names.length; i++) addJoint(names[i], spec.joints[names[i]], names[i - 1]);+ }+ // 3) mirrored chains: create R* joints mirrored across X+ const mirroredChains = {};+ for (const cn of spec.mirror || []) {+ const names = spec.chains[cn];+ const rn = mirrorName(cn);+ mirroredChains[cn] = rn;+ const host = attach[cn]; // same host (axis joints sit on X=0)+ const rnames = names.map(mirrorName);+ const ov = spec.joints_R || {}; // optional per-joint right-side pose override+ const mpos = n => {+ const rn = mirrorName(n);+ if (ov[rn]) return ov[rn].slice();+ const p = spec.joints[n]; return [-p[0], p[1], p[2]];+ };+ addJoint(rnames[0], mpos(names[0]), host ?? null);+ for (let i = 1; i < rnames.length; i++) addJoint(rnames[i], mpos(names[i]), rnames[i - 1]);+ spec.chains[rn] = rnames; // register for animation mirroring+ }+ // 4) loose joints (hosts for parts, e.g. ears): not in any chain.+ // Must have an "attach" entry. L* loose joints get auto-mirrored R twins.+ const inChains = new Set(chainNames.flatMap(c => spec.chains[c]));+ for (const [name, pos] of Object.entries(spec.joints)) {+ if (index[name] !== undefined || inChains.has(name)) continue;+ const host = attach[name];+ if (!host) throw new Error(`loose joint "${name}" needs an "attach" entry (which joint it rides on)`);+ addJoint(name, pos, host);+ if (name.startsWith('L')) {+ const rn = 'R' + name.slice(1);+ addJoint(rn, (spec.joints_R || {})[rn]?.slice() || [-pos[0], pos[1], pos[2]], host);+ }+ }+ return { joints, index, mirroredChains };+}++// local translation = world - parentWorld (bind rotations are identity)+function localTranslations(sk) {+ return sk.joints.map(j => {+ if (j.parent < 0) return j.pos.slice();+ const p = sk.joints[j.parent].pos;+ return G.sub(j.pos, p);+ });+}++// inverse bind matrix = translate(-worldPos), column-major mat4+function inverseBindMatrices(sk) {+ const out = new Float32Array(sk.joints.length * 16);+ sk.joints.forEach((j, i) => {+ const m = [1,0,0,0, 0,1,0,0, 0,0,1,0, -j.pos[0], -j.pos[1], -j.pos[2], 1];+ out.set(m, i * 16);+ });+ return out;+}++// ── public bone names for export ──+// Side-limb joints ship under the convention <L|R><ChainBase><instance><Tg>+// (LArm1Sh, RFrontLeg1Kn): side prefix, chain base, instance digit(s), then a+// two-letter joint tag. Internal spec names stay authoring-side; this map is+// applied only when writing the GLB, so animations/skins (index-based) are+// untouched. Every exported bone starting with L/R conforms to+// ^[LR][A-Z][A-Za-z]*\d+[A-Z][a-z]$ — a structural pattern, not a word list.+const JOINT_TAGS = [+ ['shoulder', 'Sh'], ['elbow', 'El'], ['wrist', 'Wr'], ['hand', 'Ha'], ['finger', 'Fg'],+ ['thumb', 'Tb'], ['hip', 'Hp'], ['knee', 'Kn'], ['ankle', 'An'], ['toe', 'To'],+ ['foot', 'Ft'], ['paw', 'Pw'], ['thigh', 'Th'], ['shin', 'Sn'], ['claw', 'Cl'],+ ['root', 'Rt'], ['mid', 'Md'], ['tip', 'Tp'], ['base', 'Bs'], ['end', 'En'],+];+function jointTag(raw, used) {+ const low = raw.toLowerCase();+ let tag = null;+ for (const [k, t] of JOINT_TAGS) if (low.includes(k)) { tag = t; break; }+ if (!tag || used.has(tag)) {+ const s = raw.replace(/^[LR]/, '').replace(/[^A-Za-z]/g, '') || 'Jt';+ tag = s[0].toUpperCase() + (s[1] || 'x').toLowerCase();+ }+ if (used.has(tag)) // positional fallback: Ja, Jb, ...+ for (let c = 97; c <= 122; c++) {+ const t2 = 'J' + String.fromCharCode(c);+ if (!used.has(t2)) { tag = t2; break; }+ }+ used.add(tag);+ return tag;+}+function exportNames(spec, sk) {+ const map = {}; const taken = new Set();+ const claim = (name) => { // guarantee global uniqueness+ let n = name, bump = 2;+ while (taken.has(n)) n = name.replace(/(\d+)(?=[A-Z][a-z]$)/, () => String(bump++));+ taken.add(n);+ return n;+ };+ const baseCount = {};+ for (const cn of spec.mirror || []) {+ const m = cn.match(/^L([A-Za-z]*?)(\d*)$/);+ const rawBase = (m && m[1]) ? m[1] : 'Limb';+ const base = rawBase[0].toUpperCase() + rawBase.slice(1);+ let inst = (m && m[2]) ? m[2] : null;+ if (inst === null) { baseCount[base] = (baseCount[base] || 0) + 1; inst = String(baseCount[base]); }+ const used = new Set();+ for (const n of spec.chains[cn]) {+ const tag = jointTag(n, used);+ map[n] = claim(`L${base}${inst}${tag}`);+ map[mirrorName(n)] = claim(`R${base}${inst}${tag}`);+ }+ }+ // loose L*/R* joints (ears, eyes' hosts) and any stray side-prefixed name:+ // give them the same mechanical form so no exported bone breaks the pattern+ for (const j of sk.joints) {+ // only names in the side convention (L/R + capital) are limbs; axis bones+ // like "Rump" (lowercase second letter) pass through untouched+ if (map[j.name] || !/^[LR][A-Z]/.test(j.name)) continue;+ if (/^[LR][A-Z][A-Za-z]*\d+[A-Z][a-z]$/.test(j.name)) { map[j.name] = claim(j.name); continue; }+ const side = j.name[0];+ const rest = j.name.slice(1).replace(/[^A-Za-z]/g, '') || 'Part';+ const base = rest[0].toUpperCase() + rest.slice(1);+ map[j.name] = claim(`${side}${base}1${jointTag(rest, new Set())}`);+ }+ return map;+}++module.exports = { buildSkeleton, localTranslations, inverseBindMatrices, mirrorName, exportNames };diff --git a/engine/core/uv.js b/engine/core/uv.jsnew file mode 100644index 0000000..5d70aa5--- /dev/null+++ b/engine/core/uv.js@@ -0,0 +1,165 @@+// ACS engine — UV unwrap + global atlas. Author: Ariescar.+// Game-ready TEXCOORD_0: every primitive unwrapped into non-overlapping+// islands, all islands shelf-packed into ONE 0..1 atlas at uniform world+// texel density → a single AO/lightmap bake covers the whole creature.+//+// tube volumes → cylindrical (u = around-angle × circumference, v = arc length)+// + each end cap as its own planar island; wrap seam gets+// duplicated vertices (no smeared triangle across the seam)+// everything else (paw/fin/eye/spike…) → box unwrap: faces grouped by the+// dominant axis of their normal (6 islands), planar projected+//+// Runs AFTER checks, BEFORE the GLB writer. Mutates meshes: vertices are+// duplicated along island borders/seams (V, C, skin, F rebuilt; UV added).+'use strict';+const G = require('./geometry.js');++function faceNormal(V, f) {+ const n = [0, 0, 0];+ for (let i = 1; i < f.length - 1; i++) {+ const x = G.cross(G.sub(V[f[i]], V[f[0]]), G.sub(V[f[i + 1]], V[f[0]]));+ n[0] += x[0]; n[1] += x[1]; n[2] += x[2];+ }+ return n;+}++// Rebuild one mesh from a list of islands; each island = {faces, proj(vi)->[u,v], wrap?}+// proj returns WORLD-scaled uv so texel density is uniform everywhere.+function rebuild(m, islands) {+ const newV = [], newUV = [], newF = [];+ const newC = m.C ? [] : null, newS = m.skin ? [] : null;+ const rects = [];+ for (const isl of islands) {+ if (!isl.faces.length) continue;+ const start = newV.length;+ const map = new Map();+ const emit = (vi, shifted) => {+ const key = shifted ? vi + 0.5 : vi;+ if (!map.has(key)) {+ map.set(key, newV.length);+ newV.push(m.V[vi]);+ if (newC) newC.push(m.C[vi]);+ if (newS) newS.push(m.skin[vi]);+ const [u, v] = isl.proj(vi);+ newUV.push([u + (shifted ? isl.wrap : 0), v]);+ }+ return map.get(key);+ };+ for (const f of isl.faces) {+ let shifts = f.map(() => false);+ if (isl.wrap) {+ const us = f.map(vi => isl.proj(vi)[0]);+ if (Math.max(...us) - Math.min(...us) > isl.wrap / 2)+ shifts = us.map(u => u < isl.wrap / 2);+ }+ newF.push(f.map((vi, i) => emit(vi, shifts[i])));+ }+ rects.push({ start, end: newV.length });+ }+ m.V = newV; m.F = newF; m.UV = newUV;+ if (newC) m.C = newC; if (newS) m.skin = newS;+ return rects.map(r => ({ mesh: m, ...r }));+}++function volumeIslands(m) {+ const ringOf = new Map();+ m._ringIdx.forEach((idx, s) => idx.forEach((vi, k) => ringOf.set(vi, [s, k])));+ const N = m._sides;+ // world scale: circumference of the mean ring, and total path length+ let rbar = 0, cnt = 0;+ m._ringIdx.forEach((idx, s) => {+ const c = m._pts[s];+ for (const vi of idx) { rbar += G.len(G.sub(m.V[vi], c)); cnt++; }+ });+ rbar /= cnt || 1;+ const circ = 2 * Math.PI * rbar;+ let L = 0;+ for (let i = 1; i < m._pts.length; i++) L += G.len(G.sub(m._pts[i], m._pts[i - 1]));+ const tube = [], cap0 = [], cap1 = [];+ for (const f of m.F) {+ if (f.every(vi => ringOf.has(vi))) { tube.push(f); continue; }+ const touches0 = f.some(vi => ringOf.has(vi) && ringOf.get(vi)[0] === 0);+ (touches0 ? cap0 : cap1).push(f);+ }+ const tubeProj = vi => {+ const [s, k] = ringOf.get(vi);+ return [(k / N) * circ, m._ringT[s] * L];+ };+ const capProj = (endS) => {+ const c = m._pts[endS];+ const other = m._pts[endS === 0 ? Math.min(1, m._pts.length - 1) : endS - 1];+ const nrm = G.nrm(G.sub(c, other));+ let e1 = Math.abs(nrm[1]) < 0.9 ? G.nrm(G.cross(nrm, [0, 1, 0])) : [1, 0, 0];+ const e2 = G.nrm(G.cross(nrm, e1));+ return vi => {+ const d = G.sub(m.V[vi], c);+ return [G.dot(d, e1), G.dot(d, e2)];+ };+ };+ return [+ { faces: tube, proj: tubeProj, wrap: circ },+ { faces: cap0, proj: capProj(0) },+ { faces: cap1, proj: capProj(m._pts.length - 1) },+ ];+}++function boxIslands(m) {+ const groups = [[], [], [], [], [], []]; // +x -x +y -y +z -z+ for (const f of m.F) {+ const n = faceNormal(m.V, f);+ const a = [Math.abs(n[0]), Math.abs(n[1]), Math.abs(n[2])];+ const ax = a[0] >= a[1] && a[0] >= a[2] ? 0 : a[1] >= a[2] ? 1 : 2;+ groups[ax * 2 + (n[ax] >= 0 ? 0 : 1)].push(f);+ }+ const projFor = gi => {+ const ax = Math.floor(gi / 2), sign = gi % 2 === 0 ? 1 : -1;+ const u = (ax + 1) % 3, v = (ax + 2) % 3;+ return vi => [m.V[vi][u] * sign, m.V[vi][v]];+ };+ return groups.map((faces, gi) => ({ faces, proj: projFor(gi) }));+}++function applyUVs(meshes) {+ const rects = [];+ for (const m of meshes) {+ const islands = (m._ringIdx && m._pts) ? volumeIslands(m) : boxIslands(m);+ rects.push(...rebuild(m, islands));+ }+ // measure islands in world units+ let totalArea = 0;+ for (const r of rects) {+ const uv = r.mesh.UV;+ let u0 = Infinity, u1 = -Infinity, v0 = Infinity, v1 = -Infinity;+ for (let i = r.start; i < r.end; i++) {+ const [u, v] = uv[i];+ if (u < u0) u0 = u; if (u > u1) u1 = u;+ if (v < v0) v0 = v; if (v > v1) v1 = v;+ }+ r.u0 = u0; r.v0 = v0; r.w = Math.max(u1 - u0, 1e-6); r.h = Math.max(v1 - v0, 1e-6);+ totalArea += r.w * r.h;+ }+ // shelf pack (height-sorted) with padding, into a roughly square atlas+ const pad = 0.015 * Math.sqrt(totalArea);+ const targetW = Math.sqrt(totalArea) * 1.25;+ const sorted = rects.slice().sort((a, b) => b.h - a.h);+ let x = pad, y = pad, rowH = 0, atlasW = 0;+ for (const r of sorted) {+ if (x + r.w + pad > targetW && x > pad) { y += rowH + pad; x = pad; rowH = 0; }+ r.px = x; r.py = y;+ x += r.w + pad;+ if (r.h > rowH) rowH = r.h;+ if (x > atlasW) atlasW = x;+ }+ const atlasH = y + rowH + pad;+ const S = Math.max(atlasW, atlasH);+ // write back normalised 0..1 uv+ for (const r of rects) {+ const uv = r.mesh.UV;+ for (let i = r.start; i < r.end; i++) {+ uv[i] = [(uv[i][0] - r.u0 + r.px) / S, (uv[i][1] - r.v0 + r.py) / S];+ }+ }+ return { islands: rects.length, atlasUtil: totalArea / (S * S) };+}++module.exports = { applyUVs };diff --git a/example/README.md b/example/README.mdnew file mode 100644index 0000000..a28718d--- /dev/null+++ b/example/README.md@@ -0,0 +1,27 @@+# Example: the reference light quadruped (wolf)++`wolf.json` is the reference example — a light quadruped bred over 3 measured+rounds and kept in step with the engine: spec-level `shading`, `smooth_angle`+50, `colors.arcs` per volume, no faceted masses. Its `_template` and+`_anchor_numbers` fields are an ANCHOR to deviate from, not a target to+converge on; there is no `templates/` library any more (removed in 1.2.0).++Files: `wolf.glb` — skinned, animated, vertex-coloured, AO baked into COLOR_0,+UV off (`"keep_uv": true` is opt-in, and this spec does not set it) —+`wolf_beauty.png`, `wolf_silhouette.png`, `wolf_thumb24.png` (the blind-read+image).++Measured: high-saturation area **26.0%** of the tq view, mid-band for the+`saturation_area` claim (14%-34%).++```bash+# rebuild+node engine/cli.js example/wolf.json example/wolf.glb+# silhouettes (front/side/top/hero45) + numbers + 24/48px thumbs+node harness/silmetrics.mjs example/wolf.glb out/r1+# per-view measures + dullness flags+python3 harness/maskmetrics.py out/r1 out/r1/sil_front.png out/r1/sil_side.png \+ out/r1/sil_top.png out/r1/sil_hero.png+# metrics incl. hi_sat_share per view (add --spec <claims.json> to check claims)+node harness/judge.mjs example/wolf.glb out/j wolf+```diff --git a/example/wolf.glb b/example/wolf.glbnew file mode 100644index 0000000..afca652Binary files /dev/null and b/example/wolf.glb differdiff --git a/example/wolf.json b/example/wolf.jsonnew file mode 100644index 0000000..58d41fd--- /dev/null+++ b/example/wolf.json@@ -0,0 +1,853 @@+{+ "name": "quadruped_light",+ "_template": "ANCHOR, not target. A validated light quadruped (wolf lineage, bred against the approved 1.2 reference over 3 measured rounds). Start here, then DEVIATE: declare your exaggeration vector (which 1-2 numbers you push past this anchor, and how far) in the design card. Converging back to these numbers means you designed nothing.",+ "_anchor_numbers": {+ "W_over_H": 1.41,+ "fill": 0.39,+ "leg_fraction": 0.35,+ "mass_thirds_rear_mid_front": [+ 0.3,+ 0.42,+ 0.28+ ],+ "head_share_of_length": 0.26,+ "belly_y_over_H": 0.34+ },+ "palette": {+ "fur_body": {+ "color": "#77705f",+ "rough": 0.95+ },+ "fur_head": {+ "color": "#b5561f",+ "rough": 0.95+ },+ "fur_tail": {+ "color": "#b5561f",+ "rough": 0.95+ },+ "fur_leg": {+ "color": "#5f594b",+ "rough": 0.95+ },+ "fur_paw": {+ "color": "#6b6455",+ "rough": 0.95+ },+ "nose": {+ "color": "#191a1d",+ "rough": 0.6+ },+ "ear": {+ "color": "#8c3c14",+ "rough": 0.95+ },+ "eye": {+ "color": "#f0a51e",+ "rough": 0.25+ }+ },+ "shading": {+ "gradient": {+ "top": 0.3,+ "bottom": -0.88+ },+ "noise": {+ "size": 0.018,+ "amount": 0.26+ }+ },+ "smooth_angle": 50,+ "joints": {+ "Hips": [+ 0,+ 0.87,+ -0.42+ ],+ "Rump": {+ "from": "Hips",+ "up": -0.11,+ "fwd": -0.18+ },+ "Spine": {+ "from": "Hips",+ "up": 0.01,+ "fwd": 0.47+ },+ "Chest": {+ "from": "Spine",+ "up": -0.04,+ "fwd": 0.29+ },+ "NeckB": {+ "from": "Chest",+ "up": 0.11,+ "fwd": 0.21+ },+ "Neck2": {+ "from": "NeckB",+ "up": 0.13,+ "fwd": 0.06+ },+ "HeadRoot": {+ "from": "Neck2",+ "up": -0.02,+ "fwd": -0.035+ },+ "Skull": {+ "from": "HeadRoot",+ "up": 0.08,+ "fwd": 0.085+ },+ "Brow": {+ "from": "Skull",+ "up": 0.01,+ "fwd": 0.14+ },+ "Muzzle": {+ "from": "Brow",+ "up": -0.06,+ "fwd": 0.18+ },+ "Nose": {+ "from": "Muzzle",+ "up": -0.02,+ "fwd": 0.14+ },+ "TailRoot": {+ "from": "Hips",+ "up": 0.01,+ "fwd": -0.1+ },+ "Tail1": {+ "from": "TailRoot",+ "up": -0.02,+ "fwd": -0.16+ },+ "Tail2": {+ "from": "Tail1",+ "up": -0.24,+ "fwd": -0.18+ },+ "TailTip": {+ "from": "Tail2",+ "up": -0.32,+ "fwd": -0.1+ },+ "LFrontRoot": {+ "from": "Chest",+ "side": 0.1,+ "up": 0.02,+ "fwd": -0.04+ },+ "LFrontElbow": {+ "from": "LFrontRoot",+ "side": 0.09,+ "up": -0.34,+ "fwd": -0.05+ },+ "LFrontWrist": {+ "from": "LFrontElbow",+ "side": 0.005,+ "up": -0.34,+ "fwd": 0.05+ },+ "LFrontToe": {+ "from": "LFrontWrist",+ "side": 0.005,+ "fwd": 0.14,+ "ground": 0.035+ },+ "LBackRoot": {+ "from": "Hips",+ "side": 0.09,+ "fwd": 0.04+ },+ "LBackKnee": {+ "from": "LBackRoot",+ "side": 0.135,+ "up": -0.37,+ "fwd": 0.12+ },+ "LBackHock": {+ "from": "LBackKnee",+ "side": 0.01,+ "up": -0.28,+ "fwd": -0.18+ },+ "LBackToe": {+ "from": "LBackHock",+ "side": 0.005,+ "fwd": 0.17,+ "ground": 0.035+ }+ },+ "chains": {+ "body": [+ "Rump",+ "Hips",+ "Spine",+ "Chest",+ "NeckB",+ "Neck2"+ ],+ "head": [+ "HeadRoot",+ "Skull",+ "Brow",+ "Muzzle",+ "Nose"+ ],+ "tail": [+ "TailRoot",+ "Tail1",+ "Tail2",+ "TailTip"+ ],+ "LFront": [+ "LFrontRoot",+ "LFrontElbow",+ "LFrontWrist",+ "LFrontToe"+ ],+ "LBack": [+ "LBackRoot",+ "LBackKnee",+ "LBackHock",+ "LBackToe"+ ]+ },+ "attach": {+ "head": "Neck2",+ "tail": "Hips",+ "LFront": "Chest",+ "LBack": "Hips"+ },+ "mirror": [+ "LFront",+ "LBack"+ ],+ "volumes": [+ {+ "chain": "body",+ "material": "fur_body",+ "frame": "up",+ "sides": 16,+ "profile": [+ [+ 0.0,+ 0.14,+ 0.16+ ],+ [+ 0.109,+ 0.185,+ 0.235,+ {+ "bias": -0.1+ }+ ],+ [+ 0.357,+ 0.205,+ 0.31,+ {+ "bias": -0.14+ }+ ],+ [+ 0.62,+ 0.21,+ 0.34,+ {+ "bias": -0.2,+ "sharp": true+ }+ ],+ [+ 0.775,+ 0.18,+ 0.25,+ {+ "sharp": true+ }+ ],+ [+ 0.946,+ 0.163,+ 0.19+ ],+ [+ 1.0,+ 0.175,+ 0.2+ ]+ ],+ "caps": [+ "dome",+ "dome"+ ],+ "colors": {+ "arcs": [+ {+ "from": 0,+ "to": 52,+ "color": "#3d382d"+ },+ {+ "from": 128,+ "to": 180,+ "color": "#c9c1ae"+ }+ ]+ }+ },+ {+ "chain": "head",+ "material": "fur_head",+ "frame": "up",+ "sides": 14,+ "profile": [+ [+ 0.0,+ 0.155,+ 0.17+ ],+ [+ 0.16,+ 0.22,+ 0.23,+ {+ "sharp": true+ }+ ],+ [+ 0.3,+ 0.22,+ 0.21+ ],+ [+ 0.43,+ 0.212,+ 0.198,+ {+ "sharp": true+ }+ ],+ [+ 0.62,+ 0.148,+ 0.138+ ],+ [+ 0.84,+ 0.085,+ 0.072+ ],+ [+ 1.0,+ 0.06,+ 0.052+ ]+ ],+ "caps": [+ "none",+ "dome"+ ],+ "colors": {+ "arcs": [+ {+ "from": 0,+ "to": 52,+ "color": "#8a3d14"+ },+ {+ "from": 128,+ "to": 180,+ "color": "#e08a3c"+ }+ ]+ }+ },+ {+ "chain": "tail",+ "material": "fur_tail",+ "sides": 10,+ "profile": [+ [+ 0,+ 0.11,+ 0.11+ ],+ [+ 0.35,+ 0.135,+ 0.14+ ],+ [+ 0.7,+ 0.1,+ 0.105+ ],+ [+ 1,+ 0.04,+ 0.04+ ]+ ],+ "caps": [+ "none",+ "dome"+ ],+ "colors": {+ "arcs": [+ {+ "from": 0,+ "to": 52,+ "color": "#8a3d14"+ }+ ]+ }+ },+ {+ "chain": "LFront",+ "material": "fur_leg",+ "sides": 9,+ "profile": [+ [+ 0,+ 0.132,+ 0.15+ ],+ [+ 0.42,+ 0.101,+ 0.109+ ],+ [+ 0.85,+ 0.078,+ 0.08+ ],+ [+ 1,+ 0.074,+ 0.048+ ]+ ],+ "caps": [+ "none",+ "dome"+ ],+ "ring_step": 0.055+ },+ {+ "chain": "LBack",+ "material": "fur_leg",+ "sides": 9,+ "profile": [+ [+ 0,+ 0.112,+ 0.142+ ],+ [+ 0.25,+ 0.106,+ 0.148,+ {+ "exp": 2.5+ }+ ],+ [+ 0.45,+ 0.096,+ 0.115,+ {+ "exp": 2.2+ }+ ],+ [+ 0.82,+ 0.081,+ 0.083+ ],+ [+ 1,+ 0.076,+ 0.048+ ]+ ],+ "caps": [+ "none",+ "dome"+ ],+ "ring_step": 0.055+ }+ ],+ "parts": [+ {+ "type": "fin",+ "host": "Skull",+ "material": "ear",+ "thickness": 0.02,+ "conform": false,+ "anchor": {+ "chain": "head",+ "t": 0.22,+ "around": 38+ },+ "udir": [+ 0.25,+ 0.1,+ -0.95+ ],+ "vdir": [+ 0.15,+ 1,+ 0.05+ ],+ "points": [+ [+ -0.025,+ 0+ ],+ [+ 0.12,+ 0.025+ ],+ [+ 0.055,+ 0.18+ ],+ [+ -0.055,+ 0.055+ ]+ ],+ "mirrored": true+ },+ {+ "type": "eye",+ "host": "Brow",+ "material": "eye",+ "size": 0.028,+ "anchor": {+ "chain": "head",+ "t": 0.4,+ "around": 62+ }+ },+ {+ "type": "spike",+ "host": "Nose",+ "offset": [+ 0,+ 0.005,+ 0.0+ ],+ "dir": [+ 0,+ -0.08,+ 1+ ],+ "segments": [+ {+ "len": 0.045,+ "r": 0.04+ }+ ],+ "sides": 8,+ "material": "nose"+ },+ {+ "type": "paw",+ "host": "LFrontToe",+ "material": "fur_paw",+ "size": [+ 0.206,+ 0.151,+ 0.076+ ],+ "mirrored": true+ },+ {+ "type": "paw",+ "host": "LBackToe",+ "material": "fur_paw",+ "size": [+ 0.22,+ 0.158,+ 0.076+ ],+ "mirrored": true+ }+ ],+ "animations": {+ "idle": {+ "duration": 2.2,+ "loop": true,+ "tracks": {+ "NeckB": {+ "rx": [+ [+ 0,+ -2+ ],+ [+ 0.5,+ 3+ ],+ [+ 1,+ -2+ ]+ ]+ },+ "Skull": {+ "rx": [+ [+ 0,+ 2+ ],+ [+ 0.5,+ -2+ ],+ [+ 1,+ 2+ ]+ ]+ },+ "Tail1": {+ "ry": [+ [+ 0,+ 8+ ],+ [+ 0.5,+ -8+ ],+ [+ 1,+ 8+ ]+ ]+ },+ "Tail2": {+ "ry": [+ [+ 0,+ -6+ ],+ [+ 0.25,+ 6+ ],+ [+ 0.75,+ -9+ ],+ [+ 1,+ -6+ ]+ ]+ },+ "Hips": {+ "ty": [+ [+ 0,+ 0+ ],+ [+ 0.5,+ 0.012+ ],+ [+ 1,+ 0+ ]+ ]+ }+ }+ },+ "move": {+ "duration": 0.95,+ "loop": true,+ "mirror_phase": 0.5,+ "tracks": {+ "LFrontRoot": {+ "rx": [+ [+ 0,+ -26+ ],+ [+ 0.5,+ 28+ ],+ [+ 1,+ -26+ ]+ ]+ },+ "LFrontElbow": {+ "rx": [+ [+ 0,+ 12+ ],+ [+ 0.25,+ 30+ ],+ [+ 0.5,+ -6+ ],+ [+ 1,+ 12+ ]+ ]+ },+ "LFrontWrist": {+ "rx": [+ [+ 0,+ -12+ ],+ [+ 0.35,+ -30+ ],+ [+ 0.6,+ 8+ ],+ [+ 1,+ -12+ ]+ ]+ },+ "LBackRoot": {+ "rx": [+ [+ 0,+ 24+ ],+ [+ 0.5,+ -22+ ],+ [+ 1,+ 24+ ]+ ]+ },+ "LBackKnee": {+ "rx": [+ [+ 0,+ -10+ ],+ [+ 0.3,+ -32+ ],+ [+ 0.6,+ 10+ ],+ [+ 1,+ -10+ ]+ ]+ },+ "LBackHock": {+ "rx": [+ [+ 0,+ 8+ ],+ [+ 0.4,+ 26+ ],+ [+ 0.7,+ -6+ ],+ [+ 1,+ 8+ ]+ ]+ },+ "Hips": {+ "ty": [+ [+ 0,+ 0+ ],+ [+ 0.25,+ 0.024+ ],+ [+ 0.5,+ 0+ ],+ [+ 0.75,+ 0.024+ ],+ [+ 1,+ 0+ ]+ ]+ },+ "NeckB": {+ "rx": [+ [+ 0,+ 3+ ],+ [+ 0.5,+ -3+ ],+ [+ 1,+ 3+ ]+ ]+ },+ "Tail1": {+ "ry": [+ [+ 0,+ 9+ ],+ [+ 0.5,+ -9+ ],+ [+ 1,+ 9+ ]+ ]+ }+ }+ }+ }+}\ No newline at end of filediff --git a/example/wolf_beauty.png b/example/wolf_beauty.pngnew file mode 100644index 0000000..a5453c0Binary files /dev/null and b/example/wolf_beauty.png differdiff --git a/example/wolf_silhouette.png b/example/wolf_silhouette.pngnew file mode 100644index 0000000..88f66a2Binary files /dev/null and b/example/wolf_silhouette.png differdiff --git a/example/wolf_thumb24.png b/example/wolf_thumb24.pngnew file mode 100644index 0000000..0d704c0Binary files /dev/null and b/example/wolf_thumb24.png differdiff --git a/harness/assets/showroom.html b/harness/assets/showroom.htmlnew file mode 100644index 0000000..790c26c--- /dev/null+++ b/harness/assets/showroom.html@@ -0,0 +1,213 @@+<!DOCTYPE html>+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<title>__TITLE__ · 3D Showroom</title>+<!-- Offline showroom: three.js is inlined and the model is embedded as base64.+ No CDN, no webfont, no server — double-click the file and it runs. -->+<style>+ *{box-sizing:border-box}+ html,body{margin:0;height:100%}+ body{+ color:#1b1b1d;+ font-family:Georgia,"Iowan Old Style","Palatino Linotype",Palatino,"Songti TC","Noto Serif CJK TC",serif;+ overflow:hidden;+ background:radial-gradient(75% 55% at 50% 30%, #6e6e73 0%, #4c4c51 55%, #3a3a3f 100%);+ }+ .room{position:relative;height:100vh;display:grid;grid-template-rows:1fr auto}+ #stage{display:block;width:100%;height:100%}+ #stage canvas{display:block;width:100%;height:100%}+ .floor{+ position:fixed;left:0;right:0;bottom:0;height:60vh;z-index:1;pointer-events:none;+ background:linear-gradient(180deg, rgba(150,150,156,0) 0%, rgba(158,158,164,.28) 26%,+ rgba(184,184,190,.62) 52%, rgba(200,200,205,.86) 78%, rgba(188,188,194,.9) 100%);+ }+ .vignette{+ position:fixed;inset:0;z-index:2;pointer-events:none;+ background:radial-gradient(115% 88% at 50% 34%, rgba(0,0,0,0) 40%, rgba(20,20,24,.5) 100%);+ }+ .plate{position:relative;z-index:3;display:flex;justify-content:center;padding:0 32px 16vh}+ .card{+ text-align:center;padding:16px 40px 14px;+ background:rgba(233,231,226,.82);+ border:1px solid rgba(27,27,29,.4);border-radius:2px;+ box-shadow:0 12px 28px rgba(15,15,18,.28);backdrop-filter:blur(2px);+ }+ .name{+ margin:0;font-weight:500;font-size:clamp(24px,2.9vw,36px);+ font-variant:small-caps;letter-spacing:.24em;text-indent:.24em;white-space:nowrap;color:#17171a;+ }+ .version{+ margin:8px 0 0;padding-top:9px;border-top:1px solid rgba(27,27,29,.22);+ font-size:12.5px;letter-spacing:.14em;color:rgba(27,27,29,.62);+ }+ .tools{position:fixed;right:22px;bottom:22px;z-index:4;display:flex;flex-direction:column;gap:10px}+ .tools button{+ width:42px;height:42px;display:grid;place-items:center;+ background:rgba(233,231,226,.8);border:1px solid rgba(27,27,29,.38);+ border-radius:2px;color:#17171a;cursor:pointer;+ box-shadow:0 6px 16px rgba(15,15,18,.22);transition:background .15s,color .15s;+ }+ .tools button:hover{background:#f2f1ed}+ .tools button[aria-pressed="true"]{background:#17171a;color:#eceae5;border-color:#17171a}+ .tools button svg{width:20px;height:20px;display:block}+ .tag{+ position:fixed;left:50%;top:50%;transform:translate(-50%,-50%);z-index:5;+ padding:9px 20px;background:rgba(23,23,26,.86);color:#f0eee9;+ border:1px solid rgba(240,238,233,.35);border-radius:2px;+ font-size:13px;letter-spacing:.3em;text-indent:.3em;text-transform:uppercase;+ white-space:nowrap;opacity:0;transition:opacity .18s;pointer-events:none;+ }+ .tag[data-on="1"]{opacity:1}+ .hint{position:fixed;left:22px;bottom:22px;z-index:4;font-size:11.5px;letter-spacing:.08em;+ color:rgba(240,238,233,.5);pointer-events:none}+</style>+</head>+<body>+ <div class="floor"></div>+ <div class="vignette"></div>+ <div class="room">+ <div style="position:relative"><div id="stage"></div></div>+ <div class="plate">+ <div class="card">+ <h1 class="name">__TITLE__</h1>+ <p class="version">__BYLINE__</p>+ </div>+ </div>+ </div>++ <div class="tools">+ <button id="btn-anim" type="button" title="Animation">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">+ <path d="M4 19V9.5"></path>+ <path d="M4 12.5c3-4.5 6-4.5 9 0s6 4.5 8-0.5"></path>+ <circle cx="4" cy="6.4" r="1.6"></circle>+ </svg>+ </button>+ <button id="btn-turntable" type="button" aria-pressed="true" title="Turntable">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round">+ <path d="M19 12a7 7 0 1 1-2.6-5.45"></path>+ <path d="M16.1 3.1v3.7h-3.7"></path>+ </svg>+ </button>+ <button id="btn-clay" type="button" aria-pressed="false" title="Hard-edge clay">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round">+ <path d="M12 3.2 20 7.6v8.8L12 20.8 4 16.4V7.6z"></path>+ <path d="M4 7.6 12 12l8-4.4M12 12v8.8"></path>+ </svg>+ </button>+ </div>++ <div id="anim-tag" class="tag"></div>+ <div class="hint">drag to orbit · wheel to zoom</div>++<script>__BUNDLE__</script>+<script>const B64="__B64__";</script>+<script>+const {Scene,Color,PerspectiveCamera,WebGLRenderer,SRGBColorSpace,PCFSoftShadowMap,+ HemisphereLight,DirectionalLight,PlaneGeometry,ShadowMaterial,MeshStandardMaterial,+ LineBasicMaterial,LineSegments,WireframeGeometry,Mesh,AnimationMixer,Box3,Sphere,+ Vector3,Clock,DoubleSide}=THREE;++const host=document.getElementById('stage');+const scene=new Scene(); // transparent — the CSS room shows through+const camera=new PerspectiveCamera(45,1,0.01,500);+camera.position.set(3,2.2,4);+const renderer=new WebGLRenderer({antialias:true,alpha:true,preserveDrawingBuffer:true});+renderer.setPixelRatio(Math.min(window.devicePixelRatio||1,2));+renderer.outputColorSpace=SRGBColorSpace;+renderer.shadowMap.enabled=true; renderer.shadowMap.type=PCFSoftShadowMap;+host.appendChild(renderer.domElement);++// Neutral studio: sky/ground wash, a shadow-casting key, a dim warm fill from+// behind so the silhouette never goes black.+scene.add(new HemisphereLight(0xffffff,0xd8d2c4,1.0));+const key=new DirectionalLight(0xffffff,2.2);+key.position.set(4,7,5); key.castShadow=true;+key.shadow.mapSize.set(2048,2048); key.shadow.bias=-0.0002;+scene.add(key);+const fill=new DirectionalLight(0xfff4e6,0.5); fill.position.set(-5,3,-4); scene.add(fill);+const ground=new Mesh(new PlaneGeometry(200,200),new ShadowMaterial({opacity:0.18}));+ground.rotation.x=-Math.PI/2; ground.receiveShadow=true; scene.add(ground);++const controls=new OrbitControls(camera,renderer.domElement);+controls.enableDamping=true; controls.dampingFactor=0.08;+controls.autoRotate=true; controls.autoRotateSpeed=1.2;+controls.addEventListener('start',()=>{ controls.autoRotate=false;+ document.getElementById('btn-turntable').setAttribute('aria-pressed','false'); });++const tag=document.getElementById('anim-tag'); let tagTimer=null;+const showTag=t=>{ tag.textContent=t; tag.dataset.on='1';+ clearTimeout(tagTimer); tagTimer=setTimeout(()=>{tag.dataset.on='0';},1000); };++function b2a(b){const s=atob(b),u=new Uint8Array(s.length);+ for(let i=0;i<s.length;i++)u[i]=s.charCodeAt(i);return u.buffer}++let mixer=null; const clock=new Clock();+new GLTFLoader().parse(b2a(B64),'',g=>{+ const model=g.scene; scene.add(model);+ model.traverse(o=>{ o.frustumCulled=false;+ if(o.isMesh){ o.castShadow=true; o.receiveShadow=true; } });++ // rest the model on the ground, then frame the camera to its bounds+ const box=new Box3().setFromObject(model);+ model.position.y-=box.min.y;+ box.setFromObject(model);+ const sphere=box.getBoundingSphere(new Sphere());+ const dist=(sphere.radius/Math.tan((camera.fov*Math.PI)/360))*1.35;+ camera.position.copy(sphere.center).add(new Vector3(0.62,0.42,0.86).normalize().multiplyScalar(dist));+ camera.near=Math.max(dist/100,0.01); camera.far=dist*100; camera.updateProjectionMatrix();+ controls.target.copy(sphere.center); controls.update();+ const span=sphere.radius*2.2;+ key.shadow.camera.left=-span; key.shadow.camera.right=span;+ key.shadow.camera.top=span; key.shadow.camera.bottom=-span;+ key.shadow.camera.updateProjectionMatrix();++ // ── animation: cycle the clips the file actually carries, plus the bind pose+ mixer=new AnimationMixer(model);+ const clips=g.animations||[];+ const order=['pose',...clips.map(c=>c.name)];+ let ix=clips.length?1:0;+ const play=()=>{ mixer.stopAllAction();+ if(ix>0) mixer.clipAction(clips[ix-1]).reset().play();+ showTag(order[ix]); };+ document.getElementById('btn-anim').addEventListener('click',()=>{+ ix=(ix+1)%order.length; play(); });+ if(clips.length){ mixer.clipAction(clips[0]).play(); }++ // ── hard-edge clay: flat neutral material + wireframe overlay, no colour+ const clay=new MeshStandardMaterial({name:'clay',color:0xb9b6b0,roughness:0.85,metalness:0,+ flatShading:true,side:DoubleSide,polygonOffset:true,polygonOffsetFactor:1.6,polygonOffsetUnits:1.6});+ const edgeMat=new LineBasicMaterial({color:0x0a0a0c,transparent:true,opacity:0.55,depthWrite:false});+ const original=new Map(); const edges=[];+ model.traverse(o=>{ if(o.isMesh){ original.set(o,o.material);+ const l=new LineSegments(new WireframeGeometry(o.geometry),edgeMat);+ l.visible=false; o.add(l); edges.push(l); } });+ const clayBtn=document.getElementById('btn-clay');+ clayBtn.addEventListener('click',()=>{+ const on=clayBtn.getAttribute('aria-pressed')!=='true';+ clayBtn.setAttribute('aria-pressed',String(on));+ edges.forEach(l=>{l.visible=on;});+ original.forEach((mat,mesh)=>{ mesh.material=on?clay:mat; });+ showTag(on?'clay on':'clay off');+ });+});++const turntable=document.getElementById('btn-turntable');+turntable.addEventListener('click',()=>{+ const on=turntable.getAttribute('aria-pressed')!=='true';+ turntable.setAttribute('aria-pressed',String(on));+ controls.autoRotate=on;+ showTag(on?'turntable on':'turntable off');+});++function fit(){ const w=host.clientWidth||1,h=host.clientHeight||1;+ renderer.setSize(w,h); camera.aspect=w/h; camera.updateProjectionMatrix(); }+addEventListener('resize',fit); fit();+new ResizeObserver(fit).observe(host);+renderer.setAnimationLoop(()=>{ if(mixer) mixer.update(clock.getDelta());+ controls.update(); renderer.render(scene,camera); });+</script>+</body>+</html>diff --git a/harness/assets/three-bundle.js b/harness/assets/three-bundle.jsnew file mode 100644index 0000000..b19c1d9--- /dev/null+++ b/harness/assets/three-bundle.js@@ -0,0 +1,3842 @@+(()=>{var Ig=Object.defineProperty;var Pg=(r,e)=>{for(var t in e)Ig(r,t,{get:e[t],enumerable:!0})};var sf={};Pg(sf,{ACESFilmicToneMapping:()=>fd,AddEquation:()=>gi,AddOperation:()=>ld,AdditiveAnimationBlendMode:()=>Ch,AdditiveBlending:()=>yh,AgXToneMapping:()=>md,AlphaFormat:()=>Ah,AlwaysCompare:()=>Id,AlwaysDepth:()=>La,AlwaysStencilFunc:()=>pl,AmbientLight:()=>ya,AnimationAction:()=>Ia,AnimationClip:()=>ei,AnimationLoader:()=>Dl,AnimationMixer:()=>Wl,AnimationObjectGroup:()=>Gl,AnimationUtils:()=>Ll,ArcCurve:()=>Ho,ArrayCamera:()=>Aa,ArrowHelper:()=>fh,AttachedBindMode:()=>fl,Audio:()=>Ra,AudioAnalyser:()=>Hl,AudioContext:()=>Vr,AudioListener:()=>kl,AudioLoader:()=>Bl,AxesHelper:()=>ph,BackSide:()=>Wt,BasicDepthPacking:()=>Md,BasicShadowMap:()=>$p,BatchedMesh:()=>Fo,Bone:()=>Gi,BooleanKeyframeTrack:()=>jn,Box2:()=>eh,Box3:()=>Rt,Box3Helper:()=>uh,BoxGeometry:()=>Vi,BoxHelper:()=>hh,BufferAttribute:()=>je,BufferGeometry:()=>ze,BufferGeometryLoader:()=>Ea,ByteType:()=>Sh,Cache:()=>Fn,Camera:()=>gs,CameraHelper:()=>lh,CanvasTexture:()=>Il,CapsuleGeometry:()=>Bo,CatmullRomCurve3:()=>Go,CineonToneMapping:()=>dd,CircleGeometry:()=>zo,ClampToEdgeWrapping:()=>Kt,Clock:()=>wa,Color:()=>ue,ColorKeyframeTrack:()=>Or,ColorManagement:()=>Ze,CompressedArrayTexture:()=>Rl,CompressedCubeTexture:()=>Cl,CompressedTexture:()=>bs,CompressedTextureLoader:()=>Nl,ConeGeometry:()=>Er,ConstantAlphaFactor:()=>od,ConstantColorFactor:()=>sd,Controls:()=>Hr,CubeCamera:()=>Ro,CubeReflectionMapping:()=>ii,CubeRefractionMapping:()=>bi,CubeTexture:()=>Hi,CubeTextureLoader:()=>Ul,CubeUVReflectionMapping:()=>Ls,CubicBezierCurve:()=>Ar,CubicBezierCurve3:()=>Wo,CubicInterpolant:()=>pa,CullFaceBack:()=>_h,CullFaceFront:()=>Hu,CullFaceFrontBack:()=>Jp,CullFaceNone:()=>Vu,Curve:()=>an,CurvePath:()=>qo,CustomBlending:()=>Wu,CustomToneMapping:()=>pd,CylinderGeometry:()=>Tr,Cylindrical:()=>jl,Data3DTexture:()=>ps,DataArrayTexture:()=>fs,DataTexture:()=>_n,DataTextureLoader:()=>Fl,DataUtils:()=>_l,DecrementStencilOp:()=>cm,DecrementWrapStencilOp:()=>hm,DefaultLoadingManager:()=>Bd,DepthFormat:()=>hs,DepthStencilFormat:()=>Fs,DepthTexture:()=>Sr,DetachedBindMode:()=>_d,DirectionalLight:()=>Is,DirectionalLightHelper:()=>ch,DiscreteInterpolant:()=>ma,DodecahedronGeometry:()=>ko,DoubleSide:()=>Mn,DstAlphaFactor:()=>Qu,DstColorFactor:()=>td,DynamicCopyUsage:()=>Em,DynamicDrawUsage:()=>ym,DynamicReadUsage:()=>Sm,EdgesGeometry:()=>Vo,EllipseCurve:()=>Ts,EqualCompare:()=>Ad,EqualDepth:()=>Na,EqualStencilFunc:()=>pm,EquirectangularReflectionMapping:()=>Wr,EquirectangularRefractionMapping:()=>Xr,Euler:()=>rn,EventDispatcher:()=>xn,ExternalTexture:()=>br,ExtrudeGeometry:()=>Jo,FileLoader:()=>Qt,Float16BufferAttribute:()=>bl,Float32BufferAttribute:()=>ye,FloatType:()=>Jt,Fog:()=>Po,FogExp2:()=>Io,FramebufferTexture:()=>wl,FrontSide:()=>An,Frustum:()=>_i,FrustumArray:()=>Uo,GLBufferAttribute:()=>Kl,GLSL1:()=>wm,GLSL3:()=>Lh,GreaterCompare:()=>wd,GreaterDepth:()=>Fa,GreaterEqualCompare:()=>Cd,GreaterEqualDepth:()=>Ua,GreaterEqualStencilFunc:()=>xm,GreaterStencilFunc:()=>gm,GridHelper:()=>oh,Group:()=>mn,HalfFloatType:()=>Ns,HemisphereLight:()=>_a,HemisphereLightHelper:()=>rh,IcosahedronGeometry:()=>$o,ImageBitmapLoader:()=>kr,ImageLoader:()=>Xi,ImageUtils:()=>wo,IncrementStencilOp:()=>am,IncrementWrapStencilOp:()=>lm,InstancedBufferAttribute:()=>wn,InstancedBufferGeometry:()=>Ta,InstancedInterleavedBuffer:()=>Zl,InstancedMesh:()=>vs,Int16BufferAttribute:()=>Ml,Int32BufferAttribute:()=>Sl,Int8BufferAttribute:()=>xl,IntType:()=>za,InterleavedBuffer:()=>Jn,InterleavedBufferAttribute:()=>Bn,Interpolant:()=>$n,InterpolateDiscrete:()=>zi,InterpolateLinear:()=>ki,InterpolateSmooth:()=>Mo,InterpolationSamplingMode:()=>Im,InterpolationSamplingType:()=>Cm,InvertStencilOp:()=>um,KeepStencilOp:()=>Di,KeyframeTrack:()=>jt,LOD:()=>No,LatheGeometry:()=>jo,Layers:()=>ms,LessCompare:()=>Ed,LessDepth:()=>Da,LessEqualCompare:()=>Ph,LessEqualDepth:()=>Oi,LessEqualStencilFunc:()=>mm,LessStencilFunc:()=>fm,Light:()=>Hn,LightProbe:()=>Sa,Line:()=>vn,Line3:()=>th,LineBasicMaterial:()=>Pt,LineCurve:()=>wr,LineCurve3:()=>Xo,LineDashedMaterial:()=>fa,LineLoop:()=>Ms,LineSegments:()=>$t,LinearFilter:()=>mt,LinearInterpolant:()=>Fr,LinearMipMapLinearFilter:()=>tm,LinearMipMapNearestFilter:()=>em,LinearMipmapLinearFilter:()=>cn,LinearMipmapNearestFilter:()=>qi,LinearSRGBColorSpace:()=>Ot,LinearToneMapping:()=>hd,LinearTransfer:()=>pr,Loader:()=>Lt,LoaderUtils:()=>Rn,LoadingManager:()=>Br,LoopOnce:()=>xd,LoopPingPong:()=>vd,LoopRepeat:()=>yd,MOUSE:()=>Mi,Material:()=>Mt,MaterialLoader:()=>ba,MathUtils:()=>Qr,Matrix2:()=>Ql,Matrix3:()=>Ve,Matrix4:()=>De,MaxEquation:()=>Zu,Mesh:()=>pt,MeshBasicMaterial:()=>Bt,MeshDepthMaterial:()=>Nr,MeshDistanceMaterial:()=>Ur,MeshLambertMaterial:()=>ua,MeshMatcapMaterial:()=>da,MeshNormalMaterial:()=>ha,MeshPhongMaterial:()=>ca,MeshPhysicalMaterial:()=>Gt,MeshStandardMaterial:()=>yi,MeshToonMaterial:()=>la,MinEquation:()=>Yu,MirroredRepeatWrapping:()=>Bi,MixOperation:()=>cd,MultiplyBlending:()=>Mh,MultiplyOperation:()=>Gr,NearestFilter:()=>Ct,NearestMipMapLinearFilter:()=>Qp,NearestMipMapNearestFilter:()=>jp,NearestMipmapLinearFilter:()=>Ti,NearestMipmapNearestFilter:()=>qr,NeutralToneMapping:()=>gd,NeverCompare:()=>Td,NeverDepth:()=>Pa,NeverStencilFunc:()=>dm,NoBlending:()=>ti,NoColorSpace:()=>ri,NoToneMapping:()=>ni,NormalAnimationBlendMode:()=>yc,NormalBlending:()=>Fi,NotEqualCompare:()=>Rd,NotEqualDepth:()=>Oa,NotEqualStencilFunc:()=>_m,NumberKeyframeTrack:()=>zn,Object3D:()=>Qe,ObjectLoader:()=>Ol,ObjectSpaceNormalMap:()=>bd,OctahedronGeometry:()=>Lr,OneFactor:()=>Ju,OneMinusConstantAlphaFactor:()=>ad,OneMinusConstantColorFactor:()=>rd,OneMinusDstAlphaFactor:()=>ed,OneMinusDstColorFactor:()=>nd,OneMinusSrcAlphaFactor:()=>Ao,OneMinusSrcColorFactor:()=>ju,OrthographicCamera:()=>vi,PCFShadowMap:()=>xh,PCFSoftShadowMap:()=>Gu,PMREMGenerator:()=>Mc,Path:()=>Es,PerspectiveCamera:()=>Tt,Plane:()=>pn,PlaneGeometry:()=>ws,PlaneHelper:()=>dh,PointLight:()=>Cs,PointLightHelper:()=>sh,Points:()=>Ss,PointsMaterial:()=>Wi,PolarGridHelper:()=>ah,PolyhedronGeometry:()=>xi,PositionalAudio:()=>Vl,PropertyBinding:()=>st,PropertyMixer:()=>Ca,QuadraticBezierCurve:()=>Rr,QuadraticBezierCurve3:()=>Cr,Quaternion:()=>vt,QuaternionKeyframeTrack:()=>kn,QuaternionLinearInterpolant:()=>ga,RED_GREEN_RGTC2_Format:()=>_c,RED_RGTC1_Format:()=>mc,REVISION:()=>ku,RGBADepthPacking:()=>Sd,RGBAFormat:()=>Ht,RGBAIntegerFormat:()=>Wa,RGBA_ASTC_10x10_Format:()=>lc,RGBA_ASTC_10x5_Format:()=>oc,RGBA_ASTC_10x6_Format:()=>ac,RGBA_ASTC_10x8_Format:()=>cc,RGBA_ASTC_12x10_Format:()=>hc,RGBA_ASTC_12x12_Format:()=>uc,RGBA_ASTC_4x4_Format:()=>ja,RGBA_ASTC_5x4_Format:()=>Qa,RGBA_ASTC_5x5_Format:()=>ec,RGBA_ASTC_6x5_Format:()=>tc,RGBA_ASTC_6x6_Format:()=>nc,RGBA_ASTC_8x5_Format:()=>ic,RGBA_ASTC_8x6_Format:()=>sc,RGBA_ASTC_8x8_Format:()=>rc,RGBA_BPTC_Format:()=>dc,RGBA_ETC2_EAC_Format:()=>$a,RGBA_PVRTC_2BPPV1_Format:()=>Za,RGBA_PVRTC_4BPPV1_Format:()=>Ya,RGBA_S3TC_DXT1_Format:()=>Kr,RGBA_S3TC_DXT3_Format:()=>Jr,RGBA_S3TC_DXT5_Format:()=>$r,RGBDepthPacking:()=>im,RGBFormat:()=>wh,RGBIntegerFormat:()=>nm,RGB_BPTC_SIGNED_Format:()=>fc,RGB_BPTC_UNSIGNED_Format:()=>pc,RGB_ETC1_Format:()=>Ka,RGB_ETC2_Format:()=>Ja,RGB_PVRTC_2BPPV1_Format:()=>qa,RGB_PVRTC_4BPPV1_Format:()=>Xa,RGB_S3TC_DXT1_Format:()=>Zr,RGDepthPacking:()=>sm,RGFormat:()=>Rh,RGIntegerFormat:()=>Ga,RawShaderMaterial:()=>aa,Ray:()=>On,Raycaster:()=>Jl,RectAreaLight:()=>va,RedFormat:()=>Ha,RedIntegerFormat:()=>Yr,ReinhardToneMapping:()=>ud,RenderTarget:()=>xr,RenderTarget3D:()=>Xl,RepeatWrapping:()=>Kn,ReplaceStencilOp:()=>om,ReverseSubtractEquation:()=>qu,RingGeometry:()=>Qo,SIGNED_RED_GREEN_RGTC2_Format:()=>xc,SIGNED_RED_RGTC1_Format:()=>gc,SRGBColorSpace:()=>wt,SRGBTransfer:()=>ot,Scene:()=>Lo,ShaderChunk:()=>Ye,ShaderLib:()=>Wn,ShaderMaterial:()=>on,ShadowMaterial:()=>oa,Shape:()=>Zn,ShapeGeometry:()=>ea,ShapePath:()=>mh,ShapeUtils:()=>En,ShortType:()=>bh,Skeleton:()=>ys,SkeletonHelper:()=>ih,SkinnedMesh:()=>xs,Source:()=>Un,Sphere:()=>Et,SphereGeometry:()=>Dr,Spherical:()=>Ps,SphericalHarmonics3:()=>Ma,SplineCurve:()=>Ir,SpotLight:()=>Rs,SpotLightHelper:()=>nh,Sprite:()=>Do,SpriteMaterial:()=>Mr,SrcAlphaFactor:()=>Eo,SrcAlphaSaturateFactor:()=>id,SrcColorFactor:()=>$u,StaticCopyUsage:()=>Tm,StaticDrawUsage:()=>mr,StaticReadUsage:()=>Mm,StereoCamera:()=>zl,StreamCopyUsage:()=>Am,StreamDrawUsage:()=>vm,StreamReadUsage:()=>bm,StringKeyframeTrack:()=>Qn,SubtractEquation:()=>Xu,SubtractiveBlending:()=>vh,TOUCH:()=>Si,TangentSpaceNormalMap:()=>Ei,TetrahedronGeometry:()=>ta,Texture:()=>gt,TextureLoader:()=>zr,TextureUtils:()=>gh,Timer:()=>$l,TimestampQuery:()=>Rm,TorusGeometry:()=>na,TorusKnotGeometry:()=>ia,Triangle:()=>Nn,TriangleFanDrawMode:()=>Os,TriangleStripDrawMode:()=>jr,TrianglesDrawMode:()=>Ih,TubeGeometry:()=>sa,UVMapping:()=>Ba,Uint16BufferAttribute:()=>yr,Uint32BufferAttribute:()=>vr,Uint8BufferAttribute:()=>yl,Uint8ClampedBufferAttribute:()=>vl,Uniform:()=>ql,UniformsGroup:()=>Yl,UniformsLib:()=>pe,UniformsUtils:()=>Ud,UnsignedByteType:()=>Cn,UnsignedInt101111Type:()=>Eh,UnsignedInt248Type:()=>Us,UnsignedInt5999Type:()=>Th,UnsignedIntType:()=>si,UnsignedShort4444Type:()=>ka,UnsignedShort5551Type:()=>Va,UnsignedShortType:()=>Ds,VSMShadowMap:()=>Gn,Vector2:()=>Y,Vector3:()=>w,Vector4:()=>tt,VectorKeyframeTrack:()=>Vn,VideoFrameTexture:()=>Al,VideoTexture:()=>Oo,WebGL3DRenderTarget:()=>gl,WebGLArrayRenderTarget:()=>ml,WebGLCoordinateSystem:()=>sn,WebGLCubeRenderTarget:()=>Co,WebGLRenderTarget:()=>yn,WebGLRenderer:()=>tf,WebGLUtils:()=>mg,WebGPUCoordinateSystem:()=>us,WebXRController:()=>_s,WireframeGeometry:()=>ra,WrapAroundEnding:()=>fr,ZeroCurvatureEnding:()=>Ni,ZeroFactor:()=>Ku,ZeroSlopeEnding:()=>Ui,ZeroStencilOp:()=>rm,createCanvasElement:()=>Dd});var ku="180",Mi={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},Si={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},Vu=0,_h=1,Hu=2,Jp=3,$p=0,xh=1,Gu=2,Gn=3,An=0,Wt=1,Mn=2,ti=0,Fi=1,yh=2,vh=3,Mh=4,Wu=5,gi=100,Xu=101,qu=102,Yu=103,Zu=104,Ku=200,Ju=201,$u=202,ju=203,Eo=204,Ao=205,Qu=206,ed=207,td=208,nd=209,id=210,sd=211,rd=212,od=213,ad=214,Pa=0,La=1,Da=2,Oi=3,Na=4,Ua=5,Fa=6,Oa=7,Gr=0,cd=1,ld=2,ni=0,hd=1,ud=2,dd=3,fd=4,pd=5,md=6,gd=7,fl="attached",_d="detached",Ba=300,ii=301,bi=302,Wr=303,Xr=304,Ls=306,Kn=1e3,Kt=1001,Bi=1002,Ct=1003,qr=1004,jp=1004,Ti=1005,Qp=1005,mt=1006,qi=1007,em=1007,cn=1008,tm=1008,Cn=1009,Sh=1010,bh=1011,Ds=1012,za=1013,si=1014,Jt=1015,Ns=1016,ka=1017,Va=1018,Us=1020,Th=35902,Eh=35899,Ah=1021,wh=1022,Ht=1023,hs=1026,Fs=1027,Ha=1028,Yr=1029,Rh=1030,Ga=1031,nm=1032,Wa=1033,Zr=33776,Kr=33777,Jr=33778,$r=33779,Xa=35840,qa=35841,Ya=35842,Za=35843,Ka=36196,Ja=37492,$a=37496,ja=37808,Qa=37809,ec=37810,tc=37811,nc=37812,ic=37813,sc=37814,rc=37815,oc=37816,ac=37817,cc=37818,lc=37819,hc=37820,uc=37821,dc=36492,fc=36494,pc=36495,mc=36283,gc=36284,_c=36285,xc=36286,xd=2200,yd=2201,vd=2202,zi=2300,ki=2301,Mo=2302,Ni=2400,Ui=2401,fr=2402,yc=2500,Ch=2501,Ih=0,jr=1,Os=2,Md=3200,Sd=3201,im=3202,sm=3203,Ei=0,bd=1,ri="",wt="srgb",Ot="srgb-linear",pr="linear",ot="srgb",rm=0,Di=7680,om=7681,am=7682,cm=7683,lm=34055,hm=34056,um=5386,dm=512,fm=513,pm=514,mm=515,gm=516,_m=517,xm=518,pl=519,Td=512,Ed=513,Ad=514,Ph=515,wd=516,Rd=517,Cd=518,Id=519,mr=35044,ym=35048,vm=35040,Mm=35045,Sm=35049,bm=35041,Tm=35046,Em=35050,Am=35042,wm="100",Lh="300 es",sn=2e3,us=2001,Rm={COMPUTE:"compute",RENDER:"render"},Cm={PERSPECTIVE:"perspective",LINEAR:"linear",FLAT:"flat"},Im={NORMAL:"normal",CENTROID:"centroid",SAMPLE:"sample",FIRST:"first",EITHER:"either"},xn=class{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});let n=this._listeners;n[e]===void 0&&(n[e]=[]),n[e].indexOf(t)===-1&&n[e].push(t)}hasEventListener(e,t){let n=this._listeners;return n===void 0?!1:n[e]!==void 0&&n[e].indexOf(t)!==-1}removeEventListener(e,t){let n=this._listeners;if(n===void 0)return;let i=n[e];if(i!==void 0){let s=i.indexOf(t);s!==-1&&i.splice(s,1)}}dispatchEvent(e){let t=this._listeners;if(t===void 0)return;let n=t[e.type];if(n!==void 0){e.target=this;let i=n.slice(0);for(let s=0,o=i.length;s<o;s++)i[s].call(this,e);e.target=null}}},zt=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"],Gf=1234567,ls=Math.PI/180,ds=180/Math.PI;function gn(){let r=Math.random()*4294967295|0,e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,n=Math.random()*4294967295|0;return(zt[r&255]+zt[r>>8&255]+zt[r>>16&255]+zt[r>>24&255]+"-"+zt[e&255]+zt[e>>8&255]+"-"+zt[e>>16&15|64]+zt[e>>24&255]+"-"+zt[t&63|128]+zt[t>>8&255]+"-"+zt[t>>16&255]+zt[t>>24&255]+zt[n&255]+zt[n>>8&255]+zt[n>>16&255]+zt[n>>24&255]).toLowerCase()}function Fe(r,e,t){return Math.max(e,Math.min(t,r))}function Pd(r,e){return(r%e+e)%e}function Lg(r,e,t,n,i){return n+(r-e)*(i-n)/(t-e)}function Dg(r,e,t){return r!==e?(t-r)/(e-r):0}function So(r,e,t){return(1-t)*r+t*e}function Ng(r,e,t,n){return So(r,e,1-Math.exp(-t*n))}function Ug(r,e=1){return e-Math.abs(Pd(r,e*2)-e)}function Fg(r,e,t){return r<=e?0:r>=t?1:(r=(r-e)/(t-e),r*r*(3-2*r))}function Og(r,e,t){return r<=e?0:r>=t?1:(r=(r-e)/(t-e),r*r*r*(r*(r*6-15)+10))}function Bg(r,e){return r+Math.floor(Math.random()*(e-r+1))}function zg(r,e){return r+Math.random()*(e-r)}function kg(r){return r*(.5-Math.random())}function Vg(r){r!==void 0&&(Gf=r);let e=Gf+=1831565813;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}function Hg(r){return r*ls}function Gg(r){return r*ds}function Wg(r){return(r&r-1)===0&&r!==0}function Xg(r){return Math.pow(2,Math.ceil(Math.log(r)/Math.LN2))}function qg(r){return Math.pow(2,Math.floor(Math.log(r)/Math.LN2))}function Yg(r,e,t,n,i){let s=Math.cos,o=Math.sin,a=s(t/2),c=o(t/2),l=s((e+n)/2),h=o((e+n)/2),u=s((e-n)/2),d=o((e-n)/2),f=s((n-e)/2),m=o((n-e)/2);switch(i){case"XYX":r.set(a*h,c*u,c*d,a*l);break;case"YZY":r.set(c*d,a*h,c*u,a*l);break;case"ZXZ":r.set(c*u,c*d,a*h,a*l);break;case"XZX":r.set(a*h,c*m,c*f,a*l);break;case"YXY":r.set(c*f,a*h,c*m,a*l);break;case"ZYZ":r.set(c*m,c*f,a*h,a*l);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+i)}}function Zt(r,e){switch(e.constructor){case Float32Array:return r;case Uint32Array:return r/4294967295;case Uint16Array:return r/65535;case Uint8Array:return r/255;case Int32Array:return Math.max(r/2147483647,-1);case Int16Array:return Math.max(r/32767,-1);case Int8Array:return Math.max(r/127,-1);default:throw new Error("Invalid component type.")}}function Xe(r,e){switch(e.constructor){case Float32Array:return r;case Uint32Array:return Math.round(r*4294967295);case Uint16Array:return Math.round(r*65535);case Uint8Array:return Math.round(r*255);case Int32Array:return Math.round(r*2147483647);case Int16Array:return Math.round(r*32767);case Int8Array:return Math.round(r*127);default:throw new Error("Invalid component type.")}}var Qr={DEG2RAD:ls,RAD2DEG:ds,generateUUID:gn,clamp:Fe,euclideanModulo:Pd,mapLinear:Lg,inverseLerp:Dg,lerp:So,damp:Ng,pingpong:Ug,smoothstep:Fg,smootherstep:Og,randInt:Bg,randFloat:zg,randFloatSpread:kg,seededRandom:Vg,degToRad:Hg,radToDeg:Gg,isPowerOfTwo:Wg,ceilPowerOfTwo:Xg,floorPowerOfTwo:qg,setQuaternionFromProperEuler:Yg,normalize:Xe,denormalize:Zt},Y=class r{constructor(e=0,t=0){r.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){let t=this.x,n=this.y,i=e.elements;return this.x=i[0]*t+i[3]*n+i[6],this.y=i[1]*t+i[4]*n+i[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Fe(this.x,e.x,t.x),this.y=Fe(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=Fe(this.x,e,t),this.y=Fe(this.y,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(Fe(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(Fe(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y;return t*t+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){let n=Math.cos(t),i=Math.sin(t),s=this.x-e.x,o=this.y-e.y;return this.x=s*n-o*i+e.x,this.y=s*i+o*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}},vt=class{constructor(e=0,t=0,n=0,i=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=n,this._w=i}static slerpFlat(e,t,n,i,s,o,a){let c=n[i+0],l=n[i+1],h=n[i+2],u=n[i+3],d=s[o+0],f=s[o+1],m=s[o+2],_=s[o+3];if(a===0){e[t+0]=c,e[t+1]=l,e[t+2]=h,e[t+3]=u;return}if(a===1){e[t+0]=d,e[t+1]=f,e[t+2]=m,e[t+3]=_;return}if(u!==_||c!==d||l!==f||h!==m){let g=1-a,p=c*d+l*f+h*m+u*_,v=p>=0?1:-1,y=1-p*p;if(y>Number.EPSILON){let A=Math.sqrt(y),E=Math.atan2(A,p*v);g=Math.sin(g*E)/A,a=Math.sin(a*E)/A}let x=a*v;if(c=c*g+d*x,l=l*g+f*x,h=h*g+m*x,u=u*g+_*x,g===1-a){let A=1/Math.sqrt(c*c+l*l+h*h+u*u);c*=A,l*=A,h*=A,u*=A}}e[t]=c,e[t+1]=l,e[t+2]=h,e[t+3]=u}static multiplyQuaternionsFlat(e,t,n,i,s,o){let a=n[i],c=n[i+1],l=n[i+2],h=n[i+3],u=s[o],d=s[o+1],f=s[o+2],m=s[o+3];return e[t]=a*m+h*u+c*f-l*d,e[t+1]=c*m+h*d+l*u-a*f,e[t+2]=l*m+h*f+a*d-c*u,e[t+3]=h*m-a*u-c*d-l*f,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,n,i){return this._x=e,this._y=t,this._z=n,this._w=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){let n=e._x,i=e._y,s=e._z,o=e._order,a=Math.cos,c=Math.sin,l=a(n/2),h=a(i/2),u=a(s/2),d=c(n/2),f=c(i/2),m=c(s/2);switch(o){case"XYZ":this._x=d*h*u+l*f*m,this._y=l*f*u-d*h*m,this._z=l*h*m+d*f*u,this._w=l*h*u-d*f*m;break;case"YXZ":this._x=d*h*u+l*f*m,this._y=l*f*u-d*h*m,this._z=l*h*m-d*f*u,this._w=l*h*u+d*f*m;break;case"ZXY":this._x=d*h*u-l*f*m,this._y=l*f*u+d*h*m,this._z=l*h*m+d*f*u,this._w=l*h*u-d*f*m;break;case"ZYX":this._x=d*h*u-l*f*m,this._y=l*f*u+d*h*m,this._z=l*h*m-d*f*u,this._w=l*h*u+d*f*m;break;case"YZX":this._x=d*h*u+l*f*m,this._y=l*f*u+d*h*m,this._z=l*h*m-d*f*u,this._w=l*h*u-d*f*m;break;case"XZY":this._x=d*h*u-l*f*m,this._y=l*f*u-d*h*m,this._z=l*h*m+d*f*u,this._w=l*h*u+d*f*m;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+o)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){let n=t/2,i=Math.sin(n);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){let t=e.elements,n=t[0],i=t[4],s=t[8],o=t[1],a=t[5],c=t[9],l=t[2],h=t[6],u=t[10],d=n+a+u;if(d>0){let f=.5/Math.sqrt(d+1);this._w=.25/f,this._x=(h-c)*f,this._y=(s-l)*f,this._z=(o-i)*f}else if(n>a&&n>u){let f=2*Math.sqrt(1+n-a-u);this._w=(h-c)/f,this._x=.25*f,this._y=(i+o)/f,this._z=(s+l)/f}else if(a>u){let f=2*Math.sqrt(1+a-n-u);this._w=(s-l)/f,this._x=(i+o)/f,this._y=.25*f,this._z=(c+h)/f}else{let f=2*Math.sqrt(1+u-n-a);this._w=(o-i)/f,this._x=(s+l)/f,this._y=(c+h)/f,this._z=.25*f}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return n<1e-8?(n=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(Fe(this.dot(e),-1,1)))}rotateTowards(e,t){let n=this.angleTo(e);if(n===0)return this;let i=Math.min(1,t/n);return this.slerp(e,i),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){let n=e._x,i=e._y,s=e._z,o=e._w,a=t._x,c=t._y,l=t._z,h=t._w;return this._x=n*h+o*a+i*l-s*c,this._y=i*h+o*c+s*a-n*l,this._z=s*h+o*l+n*c-i*a,this._w=o*h-n*a-i*c-s*l,this._onChangeCallback(),this}slerp(e,t){if(t===0)return this;if(t===1)return this.copy(e);let n=this._x,i=this._y,s=this._z,o=this._w,a=o*e._w+n*e._x+i*e._y+s*e._z;if(a<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,a=-a):this.copy(e),a>=1)return this._w=o,this._x=n,this._y=i,this._z=s,this;let c=1-a*a;if(c<=Number.EPSILON){let f=1-t;return this._w=f*o+t*this._w,this._x=f*n+t*this._x,this._y=f*i+t*this._y,this._z=f*s+t*this._z,this.normalize(),this}let l=Math.sqrt(c),h=Math.atan2(l,a),u=Math.sin((1-t)*h)/l,d=Math.sin(t*h)/l;return this._w=o*u+this._w*d,this._x=n*u+this._x*d,this._y=i*u+this._y*d,this._z=s*u+this._z*d,this._onChangeCallback(),this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){let e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),n=Math.random(),i=Math.sqrt(1-n),s=Math.sqrt(n);return this.set(i*Math.sin(e),i*Math.cos(e),s*Math.sin(t),s*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}},w=class r{constructor(e=0,t=0,n=0){r.prototype.isVector3=!0,this.x=e,this.y=t,this.z=n}set(e,t,n){return n===void 0&&(n=this.z),this.x=e,this.y=t,this.z=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(Wf.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(Wf.setFromAxisAngle(e,t))}applyMatrix3(e){let t=this.x,n=this.y,i=this.z,s=e.elements;return this.x=s[0]*t+s[3]*n+s[6]*i,this.y=s[1]*t+s[4]*n+s[7]*i,this.z=s[2]*t+s[5]*n+s[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){let t=this.x,n=this.y,i=this.z,s=e.elements,o=1/(s[3]*t+s[7]*n+s[11]*i+s[15]);return this.x=(s[0]*t+s[4]*n+s[8]*i+s[12])*o,this.y=(s[1]*t+s[5]*n+s[9]*i+s[13])*o,this.z=(s[2]*t+s[6]*n+s[10]*i+s[14])*o,this}applyQuaternion(e){let t=this.x,n=this.y,i=this.z,s=e.x,o=e.y,a=e.z,c=e.w,l=2*(o*i-a*n),h=2*(a*t-s*i),u=2*(s*n-o*t);return this.x=t+c*l+o*u-a*h,this.y=n+c*h+a*l-s*u,this.z=i+c*u+s*h-o*l,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){let t=this.x,n=this.y,i=this.z,s=e.elements;return this.x=s[0]*t+s[4]*n+s[8]*i,this.y=s[1]*t+s[5]*n+s[9]*i,this.z=s[2]*t+s[6]*n+s[10]*i,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Fe(this.x,e.x,t.x),this.y=Fe(this.y,e.y,t.y),this.z=Fe(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=Fe(this.x,e,t),this.y=Fe(this.y,e,t),this.z=Fe(this.z,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(Fe(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){let n=e.x,i=e.y,s=e.z,o=t.x,a=t.y,c=t.z;return this.x=i*c-s*a,this.y=s*o-n*c,this.z=n*a-i*o,this}projectOnVector(e){let t=e.lengthSq();if(t===0)return this.set(0,0,0);let n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return Wh.copy(this).projectOnVector(e),this.sub(Wh)}reflect(e){return this.sub(Wh.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(Fe(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y,i=this.z-e.z;return t*t+n*n+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,n){let i=Math.sin(t)*e;return this.x=i*Math.sin(n),this.y=Math.cos(t)*e,this.z=i*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){let t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),i=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=i,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){let e=Math.random()*Math.PI*2,t=Math.random()*2-1,n=Math.sqrt(1-t*t);return this.x=n*Math.cos(e),this.y=t,this.z=n*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}},Wh=new w,Wf=new vt,Ve=class r{constructor(e,t,n,i,s,o,a,c,l){r.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,n,i,s,o,a,c,l)}set(e,t,n,i,s,o,a,c,l){let h=this.elements;return h[0]=e,h[1]=i,h[2]=a,h[3]=t,h[4]=s,h[5]=c,h[6]=n,h[7]=o,h[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){let t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(e){let t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let n=e.elements,i=t.elements,s=this.elements,o=n[0],a=n[3],c=n[6],l=n[1],h=n[4],u=n[7],d=n[2],f=n[5],m=n[8],_=i[0],g=i[3],p=i[6],v=i[1],y=i[4],x=i[7],A=i[2],E=i[5],C=i[8];return s[0]=o*_+a*v+c*A,s[3]=o*g+a*y+c*E,s[6]=o*p+a*x+c*C,s[1]=l*_+h*v+u*A,s[4]=l*g+h*y+u*E,s[7]=l*p+h*x+u*C,s[2]=d*_+f*v+m*A,s[5]=d*g+f*y+m*E,s[8]=d*p+f*x+m*C,this}multiplyScalar(e){let t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){let e=this.elements,t=e[0],n=e[1],i=e[2],s=e[3],o=e[4],a=e[5],c=e[6],l=e[7],h=e[8];return t*o*h-t*a*l-n*s*h+n*a*c+i*s*l-i*o*c}invert(){let e=this.elements,t=e[0],n=e[1],i=e[2],s=e[3],o=e[4],a=e[5],c=e[6],l=e[7],h=e[8],u=h*o-a*l,d=a*c-h*s,f=l*s-o*c,m=t*u+n*d+i*f;if(m===0)return this.set(0,0,0,0,0,0,0,0,0);let _=1/m;return e[0]=u*_,e[1]=(i*l-h*n)*_,e[2]=(a*n-i*o)*_,e[3]=d*_,e[4]=(h*t-i*c)*_,e[5]=(i*s-a*t)*_,e[6]=f*_,e[7]=(n*c-l*t)*_,e[8]=(o*t-n*s)*_,this}transpose(){let e,t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){let t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,n,i,s,o,a){let c=Math.cos(s),l=Math.sin(s);return this.set(n*c,n*l,-n*(c*o+l*a)+o+e,-i*l,i*c,-i*(-l*o+c*a)+a+t,0,0,1),this}scale(e,t){return this.premultiply(Xh.makeScale(e,t)),this}rotate(e){return this.premultiply(Xh.makeRotation(-e)),this}translate(e,t){return this.premultiply(Xh.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,n,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){let t=this.elements,n=e.elements;for(let i=0;i<9;i++)if(t[i]!==n[i])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){let n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return new this.constructor().fromArray(this.elements)}},Xh=new Ve;function Ld(r){for(let e=r.length-1;e>=0;--e)if(r[e]>=65535)return!0;return!1}var Zg={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array};function ur(r,e){return new Zg[r](e)}function gr(r){return document.createElementNS("http://www.w3.org/1999/xhtml",r)}function Dd(){let r=gr("canvas");return r.style.display="block",r}var Xf={};function _r(r){r in Xf||(Xf[r]=!0,console.warn(r))}function Pm(r,e,t){return new Promise(function(n,i){function s(){switch(r.clientWaitSync(e,r.SYNC_FLUSH_COMMANDS_BIT,0)){case r.WAIT_FAILED:i();break;case r.TIMEOUT_EXPIRED:setTimeout(s,t);break;default:n()}}setTimeout(s,t)})}var qf=new Ve().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),Yf=new Ve().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function Kg(){let r={enabled:!0,workingColorSpace:Ot,spaces:{},convert:function(i,s,o){return this.enabled===!1||s===o||!s||!o||(this.spaces[s].transfer===ot&&(i.r=mi(i.r),i.g=mi(i.g),i.b=mi(i.b)),this.spaces[s].primaries!==this.spaces[o].primaries&&(i.applyMatrix3(this.spaces[s].toXYZ),i.applyMatrix3(this.spaces[o].fromXYZ)),this.spaces[o].transfer===ot&&(i.r=dr(i.r),i.g=dr(i.g),i.b=dr(i.b))),i},workingToColorSpace:function(i,s){return this.convert(i,this.workingColorSpace,s)},colorSpaceToWorking:function(i,s){return this.convert(i,s,this.workingColorSpace)},getPrimaries:function(i){return this.spaces[i].primaries},getTransfer:function(i){return i===ri?pr:this.spaces[i].transfer},getToneMappingMode:function(i){return this.spaces[i].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(i,s=this.workingColorSpace){return i.fromArray(this.spaces[s].luminanceCoefficients)},define:function(i){Object.assign(this.spaces,i)},_getMatrix:function(i,s,o){return i.copy(this.spaces[s].toXYZ).multiply(this.spaces[o].fromXYZ)},_getDrawingBufferColorSpace:function(i){return this.spaces[i].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(i=this.workingColorSpace){return this.spaces[i].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(i,s){return _r("THREE.ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),r.workingToColorSpace(i,s)},toWorkingColorSpace:function(i,s){return _r("THREE.ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),r.colorSpaceToWorking(i,s)}},e=[.64,.33,.3,.6,.15,.06],t=[.2126,.7152,.0722],n=[.3127,.329];return r.define({[Ot]:{primaries:e,whitePoint:n,transfer:pr,toXYZ:qf,fromXYZ:Yf,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:wt},outputColorSpaceConfig:{drawingBufferColorSpace:wt}},[wt]:{primaries:e,whitePoint:n,transfer:ot,toXYZ:qf,fromXYZ:Yf,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:wt}}}),r}var Ze=Kg();function mi(r){return r<.04045?r*.0773993808:Math.pow(r*.9478672986+.0521327014,2.4)}function dr(r){return r<.0031308?r*12.92:1.055*Math.pow(r,.41666)-.055}var Xs,wo=class{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{Xs===void 0&&(Xs=gr("canvas")),Xs.width=e.width,Xs.height=e.height;let i=Xs.getContext("2d");e instanceof ImageData?i.putImageData(e,0,0):i.drawImage(e,0,0,e.width,e.height),n=Xs}return n.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){let t=gr("canvas");t.width=e.width,t.height=e.height;let n=t.getContext("2d");n.drawImage(e,0,0,e.width,e.height);let i=n.getImageData(0,0,e.width,e.height),s=i.data;for(let o=0;o<s.length;o++)s[o]=mi(s[o]/255)*255;return n.putImageData(i,0,0),t}else if(e.data){let t=e.data.slice(0);for(let n=0;n<t.length;n++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[n]=Math.floor(mi(t[n]/255)*255):t[n]=mi(t[n]);return{data:t,width:e.width,height:e.height}}else return console.warn("THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}},Jg=0,Un=class{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:Jg++}),this.uuid=gn(),this.data=e,this.dataReady=!0,this.version=0}getSize(e){let t=this.data;return typeof HTMLVideoElement<"u"&&t instanceof HTMLVideoElement?e.set(t.videoWidth,t.videoHeight,0):t instanceof VideoFrame?e.set(t.displayHeight,t.displayWidth,0):t!==null?e.set(t.width,t.height,t.depth||0):e.set(0,0,0),e}set needsUpdate(e){e===!0&&this.version++}toJSON(e){let t=e===void 0||typeof e=="string";if(!t&&e.images[this.uuid]!==void 0)return e.images[this.uuid];let n={uuid:this.uuid,url:""},i=this.data;if(i!==null){let s;if(Array.isArray(i)){s=[];for(let o=0,a=i.length;o<a;o++)i[o].isDataTexture?s.push(qh(i[o].image)):s.push(qh(i[o]))}else s=qh(i);n.url=s}return t||(e.images[this.uuid]=n),n}};function qh(r){return typeof HTMLImageElement<"u"&&r instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&r instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&r instanceof ImageBitmap?wo.getDataURL(r):r.data?{data:Array.from(r.data),width:r.width,height:r.height,type:r.data.constructor.name}:(console.warn("THREE.Texture: Unable to serialize Texture."),{})}var $g=0,Yh=new w,gt=class r extends xn{constructor(e=r.DEFAULT_IMAGE,t=r.DEFAULT_MAPPING,n=Kt,i=Kt,s=mt,o=cn,a=Ht,c=Cn,l=r.DEFAULT_ANISOTROPY,h=ri){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:$g++}),this.uuid=gn(),this.name="",this.source=new Un(e),this.mipmaps=[],this.mapping=t,this.channel=0,this.wrapS=n,this.wrapT=i,this.magFilter=s,this.minFilter=o,this.anisotropy=l,this.format=a,this.internalFormat=null,this.type=c,this.offset=new Y(0,0),this.repeat=new Y(1,1),this.center=new Y(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new Ve,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=h,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(e&&e.depth&&e.depth>1),this.pmremVersion=0}get width(){return this.source.getSize(Yh).x}get height(){return this.source.getSize(Yh).y}get depth(){return this.source.getSize(Yh).z}get image(){return this.source.data}set image(e=null){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(let t in e){let n=e[t];if(n===void 0){console.warn(`THREE.Texture.setValues(): parameter '${t}' has value of undefined.`);continue}let i=this[t];if(i===void 0){console.warn(`THREE.Texture.setValues(): property '${t}' does not exist.`);continue}i&&n&&i.isVector2&&n.isVector2||i&&n&&i.isVector3&&n.isVector3||i&&n&&i.isMatrix3&&n.isMatrix3?i.copy(n):this[t]=n}}toJSON(e){let t=e===void 0||typeof e=="string";if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];let n={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(n.userData=this.userData),t||(e.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==Ba)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case Kn:e.x=e.x-Math.floor(e.x);break;case Kt:e.x=e.x<0?0:1;break;case Bi:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case Kn:e.y=e.y-Math.floor(e.y);break;case Kt:e.y=e.y<0?0:1;break;case Bi:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}};gt.DEFAULT_IMAGE=null;gt.DEFAULT_MAPPING=Ba;gt.DEFAULT_ANISOTROPY=1;var tt=class r{constructor(e=0,t=0,n=0,i=1){r.prototype.isVector4=!0,this.x=e,this.y=t,this.z=n,this.w=i}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,n,i){return this.x=e,this.y=t,this.z=n,this.w=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){let t=this.x,n=this.y,i=this.z,s=this.w,o=e.elements;return this.x=o[0]*t+o[4]*n+o[8]*i+o[12]*s,this.y=o[1]*t+o[5]*n+o[9]*i+o[13]*s,this.z=o[2]*t+o[6]*n+o[10]*i+o[14]*s,this.w=o[3]*t+o[7]*n+o[11]*i+o[15]*s,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);let t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,n,i,s,c=e.elements,l=c[0],h=c[4],u=c[8],d=c[1],f=c[5],m=c[9],_=c[2],g=c[6],p=c[10];if(Math.abs(h-d)<.01&&Math.abs(u-_)<.01&&Math.abs(m-g)<.01){if(Math.abs(h+d)<.1&&Math.abs(u+_)<.1&&Math.abs(m+g)<.1&&Math.abs(l+f+p-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;let y=(l+1)/2,x=(f+1)/2,A=(p+1)/2,E=(h+d)/4,C=(u+_)/4,I=(m+g)/4;return y>x&&y>A?y<.01?(n=0,i=.707106781,s=.707106781):(n=Math.sqrt(y),i=E/n,s=C/n):x>A?x<.01?(n=.707106781,i=0,s=.707106781):(i=Math.sqrt(x),n=E/i,s=I/i):A<.01?(n=.707106781,i=.707106781,s=0):(s=Math.sqrt(A),n=C/s,i=I/s),this.set(n,i,s,t),this}let v=Math.sqrt((g-m)*(g-m)+(u-_)*(u-_)+(d-h)*(d-h));return Math.abs(v)<.001&&(v=1),this.x=(g-m)/v,this.y=(u-_)/v,this.z=(d-h)/v,this.w=Math.acos((l+f+p-1)/2),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=Fe(this.x,e.x,t.x),this.y=Fe(this.y,e.y,t.y),this.z=Fe(this.z,e.z,t.z),this.w=Fe(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=Fe(this.x,e,t),this.y=Fe(this.y,e,t),this.z=Fe(this.z,e,t),this.w=Fe(this.w,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(Fe(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this.w=e.w+(t.w-e.w)*n,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}},xr=class extends xn{constructor(e=1,t=1,n={}){super(),n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:mt,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},n),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=n.depth,this.scissor=new tt(0,0,e,t),this.scissorTest=!1,this.viewport=new tt(0,0,e,t);let i={width:e,height:t,depth:n.depth},s=new gt(i);this.textures=[];let o=n.count;for(let a=0;a<o;a++)this.textures[a]=s.clone(),this.textures[a].isRenderTargetTexture=!0,this.textures[a].renderTarget=this;this._setTextureOptions(n),this.depthBuffer=n.depthBuffer,this.stencilBuffer=n.stencilBuffer,this.resolveDepthBuffer=n.resolveDepthBuffer,this.resolveStencilBuffer=n.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=n.depthTexture,this.samples=n.samples,this.multiview=n.multiview}_setTextureOptions(e={}){let t={minFilter:mt,generateMipmaps:!1,flipY:!1,internalFormat:null};e.mapping!==void 0&&(t.mapping=e.mapping),e.wrapS!==void 0&&(t.wrapS=e.wrapS),e.wrapT!==void 0&&(t.wrapT=e.wrapT),e.wrapR!==void 0&&(t.wrapR=e.wrapR),e.magFilter!==void 0&&(t.magFilter=e.magFilter),e.minFilter!==void 0&&(t.minFilter=e.minFilter),e.format!==void 0&&(t.format=e.format),e.type!==void 0&&(t.type=e.type),e.anisotropy!==void 0&&(t.anisotropy=e.anisotropy),e.colorSpace!==void 0&&(t.colorSpace=e.colorSpace),e.flipY!==void 0&&(t.flipY=e.flipY),e.generateMipmaps!==void 0&&(t.generateMipmaps=e.generateMipmaps),e.internalFormat!==void 0&&(t.internalFormat=e.internalFormat);for(let n=0;n<this.textures.length;n++)this.textures[n].setValues(t)}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}set depthTexture(e){this._depthTexture!==null&&(this._depthTexture.renderTarget=null),e!==null&&(e.renderTarget=this),this._depthTexture=e}get depthTexture(){return this._depthTexture}setSize(e,t,n=1){if(this.width!==e||this.height!==t||this.depth!==n){this.width=e,this.height=t,this.depth=n;for(let i=0,s=this.textures.length;i<s;i++)this.textures[i].image.width=e,this.textures[i].image.height=t,this.textures[i].image.depth=n,this.textures[i].isArrayTexture=this.textures[i].image.depth>1;this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,n=e.textures.length;t<n;t++){this.textures[t]=e.textures[t].clone(),this.textures[t].isRenderTargetTexture=!0,this.textures[t].renderTarget=this;let i=Object.assign({},e.textures[t].image);this.textures[t].source=new Un(i)}return this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,e.depthTexture!==null&&(this.depthTexture=e.depthTexture.clone()),this.samples=e.samples,this}dispose(){this.dispatchEvent({type:"dispose"})}},yn=class extends xr{constructor(e=1,t=1,n={}){super(e,t,n),this.isWebGLRenderTarget=!0}},fs=class extends gt{constructor(e=null,t=1,n=1,i=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:n,depth:i},this.magFilter=Ct,this.minFilter=Ct,this.wrapR=Kt,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}},ml=class extends yn{constructor(e=1,t=1,n=1,i={}){super(e,t,i),this.isWebGLArrayRenderTarget=!0,this.depth=n,this.texture=new fs(null,e,t,n),this._setTextureOptions(i),this.texture.isRenderTargetTexture=!0}},ps=class extends gt{constructor(e=null,t=1,n=1,i=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:n,depth:i},this.magFilter=Ct,this.minFilter=Ct,this.wrapR=Kt,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}},gl=class extends yn{constructor(e=1,t=1,n=1,i={}){super(e,t,i),this.isWebGL3DRenderTarget=!0,this.depth=n,this.texture=new ps(null,e,t,n),this._setTextureOptions(i),this.texture.isRenderTargetTexture=!0}},Rt=class{constructor(e=new w(1/0,1/0,1/0),t=new w(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t+=3)this.expandByPoint(Pn.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,n=e.count;t<n;t++)this.expandByPoint(Pn.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){let n=Pn.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(n),this.max.copy(e).add(n),this}setFromObject(e,t=!1){return this.makeEmpty(),this.expandByObject(e,t)}clone(){return new this.constructor().copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,t=!1){e.updateWorldMatrix(!1,!1);let n=e.geometry;if(n!==void 0){let s=n.getAttribute("position");if(t===!0&&s!==void 0&&e.isInstancedMesh!==!0)for(let o=0,a=s.count;o<a;o++)e.isMesh===!0?e.getVertexPosition(o,Pn):Pn.fromBufferAttribute(s,o),Pn.applyMatrix4(e.matrixWorld),this.expandByPoint(Pn);else e.boundingBox!==void 0?(e.boundingBox===null&&e.computeBoundingBox(),Ec.copy(e.boundingBox)):(n.boundingBox===null&&n.computeBoundingBox(),Ec.copy(n.boundingBox)),Ec.applyMatrix4(e.matrixWorld),this.union(Ec)}let i=e.children;for(let s=0,o=i.length;s<o;s++)this.expandByObject(i[s],t);return this}containsPoint(e){return e.x>=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,Pn),Pn.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(oo),Ac.subVectors(this.max,oo),qs.subVectors(e.a,oo),Ys.subVectors(e.b,oo),Zs.subVectors(e.c,oo),Ai.subVectors(Ys,qs),wi.subVectors(Zs,Ys),Ji.subVectors(qs,Zs);let t=[0,-Ai.z,Ai.y,0,-wi.z,wi.y,0,-Ji.z,Ji.y,Ai.z,0,-Ai.x,wi.z,0,-wi.x,Ji.z,0,-Ji.x,-Ai.y,Ai.x,0,-wi.y,wi.x,0,-Ji.y,Ji.x,0];return!Zh(t,qs,Ys,Zs,Ac)||(t=[1,0,0,0,1,0,0,0,1],!Zh(t,qs,Ys,Zs,Ac))?!1:(wc.crossVectors(Ai,wi),t=[wc.x,wc.y,wc.z],Zh(t,qs,Ys,Zs,Ac))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Pn).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(Pn).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(ci[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),ci[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),ci[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),ci[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),ci[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),ci[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),ci[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),ci[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(ci),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}},ci=[new w,new w,new w,new w,new w,new w,new w,new w],Pn=new w,Ec=new Rt,qs=new w,Ys=new w,Zs=new w,Ai=new w,wi=new w,Ji=new w,oo=new w,Ac=new w,wc=new w,$i=new w;function Zh(r,e,t,n,i){for(let s=0,o=r.length-3;s<=o;s+=3){$i.fromArray(r,s);let a=i.x*Math.abs($i.x)+i.y*Math.abs($i.y)+i.z*Math.abs($i.z),c=e.dot($i),l=t.dot($i),h=n.dot($i);if(Math.max(-Math.max(c,l,h),Math.min(c,l,h))>a)return!1}return!0}var jg=new Rt,ao=new w,Kh=new w,Et=class{constructor(e=new w,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){let n=this.center;t!==void 0?n.copy(t):jg.setFromPoints(e).getCenter(n);let i=0;for(let s=0,o=e.length;s<o;s++)i=Math.max(i,n.distanceToSquared(e[s]));return this.radius=Math.sqrt(i),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){let t=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=t*t}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,t){let n=this.center.distanceToSquared(e);return t.copy(e),n>this.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;ao.subVectors(e,this.center);let t=ao.lengthSq();if(t>this.radius*this.radius){let n=Math.sqrt(t),i=(n-this.radius)*.5;this.center.addScaledVector(ao,i/n),this.radius+=i}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(Kh.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(ao.copy(e.center).add(Kh)),this.expandByPoint(ao.copy(e.center).sub(Kh))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}},li=new w,Jh=new w,Rc=new w,Ri=new w,$h=new w,Cc=new w,jh=new w,On=class{constructor(e=new w,t=new w(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,li)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);let n=t.dot(this.direction);return n<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){let t=li.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(li.copy(this.origin).addScaledVector(this.direction,t),li.distanceToSquared(e))}distanceSqToSegment(e,t,n,i){Jh.copy(e).add(t).multiplyScalar(.5),Rc.copy(t).sub(e).normalize(),Ri.copy(this.origin).sub(Jh);let s=e.distanceTo(t)*.5,o=-this.direction.dot(Rc),a=Ri.dot(this.direction),c=-Ri.dot(Rc),l=Ri.lengthSq(),h=Math.abs(1-o*o),u,d,f,m;if(h>0)if(u=o*c-a,d=o*a-c,m=s*h,u>=0)if(d>=-m)if(d<=m){let _=1/h;u*=_,d*=_,f=u*(u+o*d+2*a)+d*(o*u+d+2*c)+l}else d=s,u=Math.max(0,-(o*d+a)),f=-u*u+d*(d+2*c)+l;else d=-s,u=Math.max(0,-(o*d+a)),f=-u*u+d*(d+2*c)+l;else d<=-m?(u=Math.max(0,-(-o*s+a)),d=u>0?-s:Math.min(Math.max(-s,-c),s),f=-u*u+d*(d+2*c)+l):d<=m?(u=0,d=Math.min(Math.max(-s,-c),s),f=d*(d+2*c)+l):(u=Math.max(0,-(o*s+a)),d=u>0?s:Math.min(Math.max(-s,-c),s),f=-u*u+d*(d+2*c)+l);else d=o>0?-s:s,u=Math.max(0,-(o*d+a)),f=-u*u+d*(d+2*c)+l;return n&&n.copy(this.origin).addScaledVector(this.direction,u),i&&i.copy(Jh).addScaledVector(Rc,d),f}intersectSphere(e,t){li.subVectors(e.center,this.origin);let n=li.dot(this.direction),i=li.dot(li)-n*n,s=e.radius*e.radius;if(i>s)return null;let o=Math.sqrt(s-i),a=n-o,c=n+o;return c<0?null:a<0?this.at(c,t):this.at(a,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){let t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;let n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){let n=this.distanceToPlane(e);return n===null?null:this.at(n,t)}intersectsPlane(e){let t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,i,s,o,a,c,l=1/this.direction.x,h=1/this.direction.y,u=1/this.direction.z,d=this.origin;return l>=0?(n=(e.min.x-d.x)*l,i=(e.max.x-d.x)*l):(n=(e.max.x-d.x)*l,i=(e.min.x-d.x)*l),h>=0?(s=(e.min.y-d.y)*h,o=(e.max.y-d.y)*h):(s=(e.max.y-d.y)*h,o=(e.min.y-d.y)*h),n>o||s>i||((s>n||isNaN(n))&&(n=s),(o<i||isNaN(i))&&(i=o),u>=0?(a=(e.min.z-d.z)*u,c=(e.max.z-d.z)*u):(a=(e.max.z-d.z)*u,c=(e.min.z-d.z)*u),n>c||a>i)||((a>n||n!==n)&&(n=a),(c<i||i!==i)&&(i=c),i<0)?null:this.at(n>=0?n:i,t)}intersectsBox(e){return this.intersectBox(e,li)!==null}intersectTriangle(e,t,n,i,s){$h.subVectors(t,e),Cc.subVectors(n,e),jh.crossVectors($h,Cc);let o=this.direction.dot(jh),a;if(o>0){if(i)return null;a=1}else if(o<0)a=-1,o=-o;else return null;Ri.subVectors(this.origin,e);let c=a*this.direction.dot(Cc.crossVectors(Ri,Cc));if(c<0)return null;let l=a*this.direction.dot($h.cross(Ri));if(l<0||c+l>o)return null;let h=-a*Ri.dot(jh);return h<0?null:this.at(h/o,s)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}},De=class r{constructor(e,t,n,i,s,o,a,c,l,h,u,d,f,m,_,g){r.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,n,i,s,o,a,c,l,h,u,d,f,m,_,g)}set(e,t,n,i,s,o,a,c,l,h,u,d,f,m,_,g){let p=this.elements;return p[0]=e,p[4]=t,p[8]=n,p[12]=i,p[1]=s,p[5]=o,p[9]=a,p[13]=c,p[2]=l,p[6]=h,p[10]=u,p[14]=d,p[3]=f,p[7]=m,p[11]=_,p[15]=g,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new r().fromArray(this.elements)}copy(e){let t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],t[9]=n[9],t[10]=n[10],t[11]=n[11],t[12]=n[12],t[13]=n[13],t[14]=n[14],t[15]=n[15],this}copyPosition(e){let t=this.elements,n=e.elements;return t[12]=n[12],t[13]=n[13],t[14]=n[14],this}setFromMatrix3(e){let t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,n){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this}makeBasis(e,t,n){return this.set(e.x,t.x,n.x,0,e.y,t.y,n.y,0,e.z,t.z,n.z,0,0,0,0,1),this}extractRotation(e){let t=this.elements,n=e.elements,i=1/Ks.setFromMatrixColumn(e,0).length(),s=1/Ks.setFromMatrixColumn(e,1).length(),o=1/Ks.setFromMatrixColumn(e,2).length();return t[0]=n[0]*i,t[1]=n[1]*i,t[2]=n[2]*i,t[3]=0,t[4]=n[4]*s,t[5]=n[5]*s,t[6]=n[6]*s,t[7]=0,t[8]=n[8]*o,t[9]=n[9]*o,t[10]=n[10]*o,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){let t=this.elements,n=e.x,i=e.y,s=e.z,o=Math.cos(n),a=Math.sin(n),c=Math.cos(i),l=Math.sin(i),h=Math.cos(s),u=Math.sin(s);if(e.order==="XYZ"){let d=o*h,f=o*u,m=a*h,_=a*u;t[0]=c*h,t[4]=-c*u,t[8]=l,t[1]=f+m*l,t[5]=d-_*l,t[9]=-a*c,t[2]=_-d*l,t[6]=m+f*l,t[10]=o*c}else if(e.order==="YXZ"){let d=c*h,f=c*u,m=l*h,_=l*u;t[0]=d+_*a,t[4]=m*a-f,t[8]=o*l,t[1]=o*u,t[5]=o*h,t[9]=-a,t[2]=f*a-m,t[6]=_+d*a,t[10]=o*c}else if(e.order==="ZXY"){let d=c*h,f=c*u,m=l*h,_=l*u;t[0]=d-_*a,t[4]=-o*u,t[8]=m+f*a,t[1]=f+m*a,t[5]=o*h,t[9]=_-d*a,t[2]=-o*l,t[6]=a,t[10]=o*c}else if(e.order==="ZYX"){let d=o*h,f=o*u,m=a*h,_=a*u;t[0]=c*h,t[4]=m*l-f,t[8]=d*l+_,t[1]=c*u,t[5]=_*l+d,t[9]=f*l-m,t[2]=-l,t[6]=a*c,t[10]=o*c}else if(e.order==="YZX"){let d=o*c,f=o*l,m=a*c,_=a*l;t[0]=c*h,t[4]=_-d*u,t[8]=m*u+f,t[1]=u,t[5]=o*h,t[9]=-a*h,t[2]=-l*h,t[6]=f*u+m,t[10]=d-_*u}else if(e.order==="XZY"){let d=o*c,f=o*l,m=a*c,_=a*l;t[0]=c*h,t[4]=-u,t[8]=l*h,t[1]=d*u+_,t[5]=o*h,t[9]=f*u-m,t[2]=m*u-f,t[6]=a*h,t[10]=_*u+d}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(Qg,e,e_)}lookAt(e,t,n){let i=this.elements;return dn.subVectors(e,t),dn.lengthSq()===0&&(dn.z=1),dn.normalize(),Ci.crossVectors(n,dn),Ci.lengthSq()===0&&(Math.abs(n.z)===1?dn.x+=1e-4:dn.z+=1e-4,dn.normalize(),Ci.crossVectors(n,dn)),Ci.normalize(),Ic.crossVectors(dn,Ci),i[0]=Ci.x,i[4]=Ic.x,i[8]=dn.x,i[1]=Ci.y,i[5]=Ic.y,i[9]=dn.y,i[2]=Ci.z,i[6]=Ic.z,i[10]=dn.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let n=e.elements,i=t.elements,s=this.elements,o=n[0],a=n[4],c=n[8],l=n[12],h=n[1],u=n[5],d=n[9],f=n[13],m=n[2],_=n[6],g=n[10],p=n[14],v=n[3],y=n[7],x=n[11],A=n[15],E=i[0],C=i[4],I=i[8],b=i[12],S=i[1],L=i[5],F=i[9],z=i[13],G=i[2],q=i[6],W=i[10],ne=i[14],H=i[3],de=i[7],xe=i[11],Se=i[15];return s[0]=o*E+a*S+c*G+l*H,s[4]=o*C+a*L+c*q+l*de,s[8]=o*I+a*F+c*W+l*xe,s[12]=o*b+a*z+c*ne+l*Se,s[1]=h*E+u*S+d*G+f*H,s[5]=h*C+u*L+d*q+f*de,s[9]=h*I+u*F+d*W+f*xe,s[13]=h*b+u*z+d*ne+f*Se,s[2]=m*E+_*S+g*G+p*H,s[6]=m*C+_*L+g*q+p*de,s[10]=m*I+_*F+g*W+p*xe,s[14]=m*b+_*z+g*ne+p*Se,s[3]=v*E+y*S+x*G+A*H,s[7]=v*C+y*L+x*q+A*de,s[11]=v*I+y*F+x*W+A*xe,s[15]=v*b+y*z+x*ne+A*Se,this}multiplyScalar(e){let t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){let e=this.elements,t=e[0],n=e[4],i=e[8],s=e[12],o=e[1],a=e[5],c=e[9],l=e[13],h=e[2],u=e[6],d=e[10],f=e[14],m=e[3],_=e[7],g=e[11],p=e[15];return m*(+s*c*u-i*l*u-s*a*d+n*l*d+i*a*f-n*c*f)+_*(+t*c*f-t*l*d+s*o*d-i*o*f+i*l*h-s*c*h)+g*(+t*l*u-t*a*f-s*o*u+n*o*f+s*a*h-n*l*h)+p*(-i*a*h-t*c*u+t*a*d+i*o*u-n*o*d+n*c*h)}transpose(){let e=this.elements,t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,n){let i=this.elements;return e.isVector3?(i[12]=e.x,i[13]=e.y,i[14]=e.z):(i[12]=e,i[13]=t,i[14]=n),this}invert(){let e=this.elements,t=e[0],n=e[1],i=e[2],s=e[3],o=e[4],a=e[5],c=e[6],l=e[7],h=e[8],u=e[9],d=e[10],f=e[11],m=e[12],_=e[13],g=e[14],p=e[15],v=u*g*l-_*d*l+_*c*f-a*g*f-u*c*p+a*d*p,y=m*d*l-h*g*l-m*c*f+o*g*f+h*c*p-o*d*p,x=h*_*l-m*u*l+m*a*f-o*_*f-h*a*p+o*u*p,A=m*u*c-h*_*c-m*a*d+o*_*d+h*a*g-o*u*g,E=t*v+n*y+i*x+s*A;if(E===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);let C=1/E;return e[0]=v*C,e[1]=(_*d*s-u*g*s-_*i*f+n*g*f+u*i*p-n*d*p)*C,e[2]=(a*g*s-_*c*s+_*i*l-n*g*l-a*i*p+n*c*p)*C,e[3]=(u*c*s-a*d*s-u*i*l+n*d*l+a*i*f-n*c*f)*C,e[4]=y*C,e[5]=(h*g*s-m*d*s+m*i*f-t*g*f-h*i*p+t*d*p)*C,e[6]=(m*c*s-o*g*s-m*i*l+t*g*l+o*i*p-t*c*p)*C,e[7]=(o*d*s-h*c*s+h*i*l-t*d*l-o*i*f+t*c*f)*C,e[8]=x*C,e[9]=(m*u*s-h*_*s-m*n*f+t*_*f+h*n*p-t*u*p)*C,e[10]=(o*_*s-m*a*s+m*n*l-t*_*l-o*n*p+t*a*p)*C,e[11]=(h*a*s-o*u*s-h*n*l+t*u*l+o*n*f-t*a*f)*C,e[12]=A*C,e[13]=(h*_*i-m*u*i+m*n*d-t*_*d-h*n*g+t*u*g)*C,e[14]=(m*a*i-o*_*i-m*n*c+t*_*c+o*n*g-t*a*g)*C,e[15]=(o*u*i-h*a*i+h*n*c-t*u*c-o*n*d+t*a*d)*C,this}scale(e){let t=this.elements,n=e.x,i=e.y,s=e.z;return t[0]*=n,t[4]*=i,t[8]*=s,t[1]*=n,t[5]*=i,t[9]*=s,t[2]*=n,t[6]*=i,t[10]*=s,t[3]*=n,t[7]*=i,t[11]*=s,this}getMaxScaleOnAxis(){let e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],n=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],i=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,i))}makeTranslation(e,t,n){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,n,0,0,0,1),this}makeRotationX(e){let t=Math.cos(e),n=Math.sin(e);return this.set(1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1),this}makeRotationY(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1),this}makeRotationZ(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){let n=Math.cos(t),i=Math.sin(t),s=1-n,o=e.x,a=e.y,c=e.z,l=s*o,h=s*a;return this.set(l*o+n,l*a-i*c,l*c+i*a,0,l*a+i*c,h*a+n,h*c-i*o,0,l*c-i*a,h*c+i*o,s*c*c+n,0,0,0,0,1),this}makeScale(e,t,n){return this.set(e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1),this}makeShear(e,t,n,i,s,o){return this.set(1,n,s,0,e,1,o,0,t,i,1,0,0,0,0,1),this}compose(e,t,n){let i=this.elements,s=t._x,o=t._y,a=t._z,c=t._w,l=s+s,h=o+o,u=a+a,d=s*l,f=s*h,m=s*u,_=o*h,g=o*u,p=a*u,v=c*l,y=c*h,x=c*u,A=n.x,E=n.y,C=n.z;return i[0]=(1-(_+p))*A,i[1]=(f+x)*A,i[2]=(m-y)*A,i[3]=0,i[4]=(f-x)*E,i[5]=(1-(d+p))*E,i[6]=(g+v)*E,i[7]=0,i[8]=(m+y)*C,i[9]=(g-v)*C,i[10]=(1-(d+_))*C,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this}decompose(e,t,n){let i=this.elements,s=Ks.set(i[0],i[1],i[2]).length(),o=Ks.set(i[4],i[5],i[6]).length(),a=Ks.set(i[8],i[9],i[10]).length();this.determinant()<0&&(s=-s),e.x=i[12],e.y=i[13],e.z=i[14],Ln.copy(this);let l=1/s,h=1/o,u=1/a;return Ln.elements[0]*=l,Ln.elements[1]*=l,Ln.elements[2]*=l,Ln.elements[4]*=h,Ln.elements[5]*=h,Ln.elements[6]*=h,Ln.elements[8]*=u,Ln.elements[9]*=u,Ln.elements[10]*=u,t.setFromRotationMatrix(Ln),n.x=s,n.y=o,n.z=a,this}makePerspective(e,t,n,i,s,o,a=sn,c=!1){let l=this.elements,h=2*s/(t-e),u=2*s/(n-i),d=(t+e)/(t-e),f=(n+i)/(n-i),m,_;if(c)m=s/(o-s),_=o*s/(o-s);else if(a===sn)m=-(o+s)/(o-s),_=-2*o*s/(o-s);else if(a===us)m=-o/(o-s),_=-o*s/(o-s);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);return l[0]=h,l[4]=0,l[8]=d,l[12]=0,l[1]=0,l[5]=u,l[9]=f,l[13]=0,l[2]=0,l[6]=0,l[10]=m,l[14]=_,l[3]=0,l[7]=0,l[11]=-1,l[15]=0,this}makeOrthographic(e,t,n,i,s,o,a=sn,c=!1){let l=this.elements,h=2/(t-e),u=2/(n-i),d=-(t+e)/(t-e),f=-(n+i)/(n-i),m,_;if(c)m=1/(o-s),_=o/(o-s);else if(a===sn)m=-2/(o-s),_=-(o+s)/(o-s);else if(a===us)m=-1/(o-s),_=-s/(o-s);else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);return l[0]=h,l[4]=0,l[8]=0,l[12]=d,l[1]=0,l[5]=u,l[9]=0,l[13]=f,l[2]=0,l[6]=0,l[10]=m,l[14]=_,l[3]=0,l[7]=0,l[11]=0,l[15]=1,this}equals(e){let t=this.elements,n=e.elements;for(let i=0;i<16;i++)if(t[i]!==n[i])return!1;return!0}fromArray(e,t=0){for(let n=0;n<16;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){let n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e[t+9]=n[9],e[t+10]=n[10],e[t+11]=n[11],e[t+12]=n[12],e[t+13]=n[13],e[t+14]=n[14],e[t+15]=n[15],e}},Ks=new w,Ln=new De,Qg=new w(0,0,0),e_=new w(1,1,1),Ci=new w,Ic=new w,dn=new w,Zf=new De,Kf=new vt,rn=class r{constructor(e=0,t=0,n=0,i=r.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=n,this._order=i}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,n,i=this._order){return this._x=e,this._y=t,this._z=n,this._order=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,n=!0){let i=e.elements,s=i[0],o=i[4],a=i[8],c=i[1],l=i[5],h=i[9],u=i[2],d=i[6],f=i[10];switch(t){case"XYZ":this._y=Math.asin(Fe(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-h,f),this._z=Math.atan2(-o,s)):(this._x=Math.atan2(d,l),this._z=0);break;case"YXZ":this._x=Math.asin(-Fe(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(a,f),this._z=Math.atan2(c,l)):(this._y=Math.atan2(-u,s),this._z=0);break;case"ZXY":this._x=Math.asin(Fe(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-u,f),this._z=Math.atan2(-o,l)):(this._y=0,this._z=Math.atan2(c,s));break;case"ZYX":this._y=Math.asin(-Fe(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(d,f),this._z=Math.atan2(c,s)):(this._x=0,this._z=Math.atan2(-o,l));break;case"YZX":this._z=Math.asin(Fe(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(-h,l),this._y=Math.atan2(-u,s)):(this._x=0,this._y=Math.atan2(a,f));break;case"XZY":this._z=Math.asin(-Fe(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(d,l),this._y=Math.atan2(a,s)):(this._x=Math.atan2(-h,f),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,n===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return Zf.makeRotationFromQuaternion(e),this.setFromRotationMatrix(Zf,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return Kf.setFromEuler(this),this.setFromQuaternion(Kf,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}};rn.DEFAULT_ORDER="XYZ";var ms=class{constructor(){this.mask=1}set(e){this.mask=(1<<e|0)>>>0}enable(e){this.mask|=1<<e|0}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e|0}disable(e){this.mask&=~(1<<e|0)}disableAll(){this.mask=0}test(e){return(this.mask&e.mask)!==0}isEnabled(e){return(this.mask&(1<<e|0))!==0}},t_=0,Jf=new w,Js=new vt,hi=new De,Pc=new w,co=new w,n_=new w,i_=new vt,$f=new w(1,0,0),jf=new w(0,1,0),Qf=new w(0,0,1),ep={type:"added"},s_={type:"removed"},$s={type:"childadded",child:null},Qh={type:"childremoved",child:null},Qe=class r extends xn{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:t_++}),this.uuid=gn(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=r.DEFAULT_UP.clone();let e=new w,t=new rn,n=new vt,i=new w(1,1,1);function s(){n.setFromEuler(t,!1)}function o(){t.setFromQuaternion(n,void 0,!1)}t._onChange(s),n._onChange(o),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:e},rotation:{configurable:!0,enumerable:!0,value:t},quaternion:{configurable:!0,enumerable:!0,value:n},scale:{configurable:!0,enumerable:!0,value:i},modelViewMatrix:{value:new De},normalMatrix:{value:new Ve}}),this.matrix=new De,this.matrixWorld=new De,this.matrixAutoUpdate=r.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=r.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new ms,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.userData={}}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,t){this.quaternion.setFromAxisAngle(e,t)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,t){return Js.setFromAxisAngle(e,t),this.quaternion.multiply(Js),this}rotateOnWorldAxis(e,t){return Js.setFromAxisAngle(e,t),this.quaternion.premultiply(Js),this}rotateX(e){return this.rotateOnAxis($f,e)}rotateY(e){return this.rotateOnAxis(jf,e)}rotateZ(e){return this.rotateOnAxis(Qf,e)}translateOnAxis(e,t){return Jf.copy(e).applyQuaternion(this.quaternion),this.position.add(Jf.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis($f,e)}translateY(e){return this.translateOnAxis(jf,e)}translateZ(e){return this.translateOnAxis(Qf,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(hi.copy(this.matrixWorld).invert())}lookAt(e,t,n){e.isVector3?Pc.copy(e):Pc.set(e,t,n);let i=this.parent;this.updateWorldMatrix(!0,!1),co.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?hi.lookAt(co,Pc,this.up):hi.lookAt(Pc,co,this.up),this.quaternion.setFromRotationMatrix(hi),i&&(hi.extractRotation(i.matrixWorld),Js.setFromRotationMatrix(hi),this.quaternion.premultiply(Js.invert()))}add(e){if(arguments.length>1){for(let t=0;t<arguments.length;t++)this.add(arguments[t]);return this}return e===this?(console.error("THREE.Object3D.add: object can't be added as a child of itself.",e),this):(e&&e.isObject3D?(e.removeFromParent(),e.parent=this,this.children.push(e),e.dispatchEvent(ep),$s.child=e,this.dispatchEvent($s),$s.child=null):console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.",e),this)}remove(e){if(arguments.length>1){for(let n=0;n<arguments.length;n++)this.remove(arguments[n]);return this}let t=this.children.indexOf(e);return t!==-1&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent(s_),Qh.child=e,this.dispatchEvent(Qh),Qh.child=null),this}removeFromParent(){let e=this.parent;return e!==null&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),hi.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),hi.multiply(e.parent.matrixWorld)),e.applyMatrix4(hi),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(ep),$s.child=e,this.dispatchEvent($s),$s.child=null,this}getObjectById(e){return this.getObjectByProperty("id",e)}getObjectByName(e){return this.getObjectByProperty("name",e)}getObjectByProperty(e,t){if(this[e]===t)return this;for(let n=0,i=this.children.length;n<i;n++){let o=this.children[n].getObjectByProperty(e,t);if(o!==void 0)return o}}getObjectsByProperty(e,t,n=[]){this[e]===t&&n.push(this);let i=this.children;for(let s=0,o=i.length;s<o;s++)i[s].getObjectsByProperty(e,t,n);return n}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(co,e,n_),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(co,i_,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);let t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}traverse(e){e(this);let t=this.children;for(let n=0,i=t.length;n<i;n++)t[n].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);let t=this.children;for(let n=0,i=t.length;n<i;n++)t[n].traverseVisible(e)}traverseAncestors(e){let t=this.parent;t!==null&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale),this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,e=!0);let t=this.children;for(let n=0,i=t.length;n<i;n++)t[n].updateMatrixWorld(e)}updateWorldMatrix(e,t){let n=this.parent;if(e===!0&&n!==null&&n.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),t===!0){let i=this.children;for(let s=0,o=i.length;s<o;s++)i[s].updateWorldMatrix(!1,!0)}}toJSON(e){let t=e===void 0||typeof e=="string",n={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},n.metadata={version:4.7,type:"Object",generator:"Object3D.toJSON"});let i={};i.uuid=this.uuid,i.type=this.type,this.name!==""&&(i.name=this.name),this.castShadow===!0&&(i.castShadow=!0),this.receiveShadow===!0&&(i.receiveShadow=!0),this.visible===!1&&(i.visible=!1),this.frustumCulled===!1&&(i.frustumCulled=!1),this.renderOrder!==0&&(i.renderOrder=this.renderOrder),Object.keys(this.userData).length>0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(i.matrixAutoUpdate=!1),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(i.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.geometryInfo=this._geometryInfo.map(a=>({...a,boundingBox:a.boundingBox?a.boundingBox.toJSON():void 0,boundingSphere:a.boundingSphere?a.boundingSphere.toJSON():void 0})),i.instanceInfo=this._instanceInfo.map(a=>({...a})),i.availableInstanceIds=this._availableInstanceIds.slice(),i.availableGeometryIds=this._availableGeometryIds.slice(),i.nextIndexStart=this._nextIndexStart,i.nextVertexStart=this._nextVertexStart,i.geometryCount=this._geometryCount,i.maxInstanceCount=this._maxInstanceCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.matricesTexture=this._matricesTexture.toJSON(e),i.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(i.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(i.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(i.boundingBox=this.boundingBox.toJSON()));function s(a,c){return a[c.uuid]===void 0&&(a[c.uuid]=c.toJSON(e)),c.uuid}if(this.isScene)this.background&&(this.background.isColor?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(i.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=s(e.geometries,this.geometry);let a=this.geometry.parameters;if(a!==void 0&&a.shapes!==void 0){let c=a.shapes;if(Array.isArray(c))for(let l=0,h=c.length;l<h;l++){let u=c[l];s(e.shapes,u)}else s(e.shapes,c)}}if(this.isSkinnedMesh&&(i.bindMode=this.bindMode,i.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(s(e.skeletons,this.skeleton),i.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){let a=[];for(let c=0,l=this.material.length;c<l;c++)a.push(s(e.materials,this.material[c]));i.material=a}else i.material=s(e.materials,this.material);if(this.children.length>0){i.children=[];for(let a=0;a<this.children.length;a++)i.children.push(this.children[a].toJSON(e).object)}if(this.animations.length>0){i.animations=[];for(let a=0;a<this.animations.length;a++){let c=this.animations[a];i.animations.push(s(e.animations,c))}}if(t){let a=o(e.geometries),c=o(e.materials),l=o(e.textures),h=o(e.images),u=o(e.shapes),d=o(e.skeletons),f=o(e.animations),m=o(e.nodes);a.length>0&&(n.geometries=a),c.length>0&&(n.materials=c),l.length>0&&(n.textures=l),h.length>0&&(n.images=h),u.length>0&&(n.shapes=u),d.length>0&&(n.skeletons=d),f.length>0&&(n.animations=f),m.length>0&&(n.nodes=m)}return n.object=i,n;function o(a){let c=[];for(let l in a){let h=a[l];delete h.metadata,c.push(h)}return c}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let n=0;n<e.children.length;n++){let i=e.children[n];this.add(i.clone())}return this}};Qe.DEFAULT_UP=new w(0,1,0);Qe.DEFAULT_MATRIX_AUTO_UPDATE=!0;Qe.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;var Dn=new w,ui=new w,eu=new w,di=new w,js=new w,Qs=new w,tp=new w,tu=new w,nu=new w,iu=new w,su=new tt,ru=new tt,ou=new tt,Nn=class r{constructor(e=new w,t=new w,n=new w){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,i){i.subVectors(n,t),Dn.subVectors(e,t),i.cross(Dn);let s=i.lengthSq();return s>0?i.multiplyScalar(1/Math.sqrt(s)):i.set(0,0,0)}static getBarycoord(e,t,n,i,s){Dn.subVectors(i,t),ui.subVectors(n,t),eu.subVectors(e,t);let o=Dn.dot(Dn),a=Dn.dot(ui),c=Dn.dot(eu),l=ui.dot(ui),h=ui.dot(eu),u=o*l-a*a;if(u===0)return s.set(0,0,0),null;let d=1/u,f=(l*c-a*h)*d,m=(o*h-a*c)*d;return s.set(1-f-m,m,f)}static containsPoint(e,t,n,i){return this.getBarycoord(e,t,n,i,di)===null?!1:di.x>=0&&di.y>=0&&di.x+di.y<=1}static getInterpolation(e,t,n,i,s,o,a,c){return this.getBarycoord(e,t,n,i,di)===null?(c.x=0,c.y=0,"z"in c&&(c.z=0),"w"in c&&(c.w=0),null):(c.setScalar(0),c.addScaledVector(s,di.x),c.addScaledVector(o,di.y),c.addScaledVector(a,di.z),c)}static getInterpolatedAttribute(e,t,n,i,s,o){return su.setScalar(0),ru.setScalar(0),ou.setScalar(0),su.fromBufferAttribute(e,t),ru.fromBufferAttribute(e,n),ou.fromBufferAttribute(e,i),o.setScalar(0),o.addScaledVector(su,s.x),o.addScaledVector(ru,s.y),o.addScaledVector(ou,s.z),o}static isFrontFacing(e,t,n,i){return Dn.subVectors(n,t),ui.subVectors(e,t),Dn.cross(ui).dot(i)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,i){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[i]),this}setFromAttributeAndIndices(e,t,n,i){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,i),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Dn.subVectors(this.c,this.b),ui.subVectors(this.a,this.b),Dn.cross(ui).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return r.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return r.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,n,i,s){return r.getInterpolation(e,this.a,this.b,this.c,t,n,i,s)}containsPoint(e){return r.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return r.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){let n=this.a,i=this.b,s=this.c,o,a;js.subVectors(i,n),Qs.subVectors(s,n),tu.subVectors(e,n);let c=js.dot(tu),l=Qs.dot(tu);if(c<=0&&l<=0)return t.copy(n);nu.subVectors(e,i);let h=js.dot(nu),u=Qs.dot(nu);if(h>=0&&u<=h)return t.copy(i);let d=c*u-h*l;if(d<=0&&c>=0&&h<=0)return o=c/(c-h),t.copy(n).addScaledVector(js,o);iu.subVectors(e,s);let f=js.dot(iu),m=Qs.dot(iu);if(m>=0&&f<=m)return t.copy(s);let _=f*l-c*m;if(_<=0&&l>=0&&m<=0)return a=l/(l-m),t.copy(n).addScaledVector(Qs,a);let g=h*m-f*u;if(g<=0&&u-h>=0&&f-m>=0)return tp.subVectors(s,i),a=(u-h)/(u-h+(f-m)),t.copy(i).addScaledVector(tp,a);let p=1/(g+_+d);return o=_*p,a=d*p,t.copy(n).addScaledVector(js,o).addScaledVector(Qs,a)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}},Lm={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},Ii={h:0,s:0,l:0},Lc={h:0,s:0,l:0};function au(r,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?r+(e-r)*6*t:t<1/2?e:t<2/3?r+(e-r)*6*(2/3-t):r}var ue=class{constructor(e,t,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,n)}set(e,t,n){if(t===void 0&&n===void 0){let i=e;i&&i.isColor?this.copy(i):typeof i=="number"?this.setHex(i):typeof i=="string"&&this.setStyle(i)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=wt){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,Ze.colorSpaceToWorking(this,t),this}setRGB(e,t,n,i=Ze.workingColorSpace){return this.r=e,this.g=t,this.b=n,Ze.colorSpaceToWorking(this,i),this}setHSL(e,t,n,i=Ze.workingColorSpace){if(e=Pd(e,1),t=Fe(t,0,1),n=Fe(n,0,1),t===0)this.r=this.g=this.b=n;else{let s=n<=.5?n*(1+t):n+t-n*t,o=2*n-s;this.r=au(o,s,e+1/3),this.g=au(o,s,e),this.b=au(o,s,e-1/3)}return Ze.colorSpaceToWorking(this,i),this}setStyle(e,t=wt){function n(s){s!==void 0&&parseFloat(s)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let s,o=i[1],a=i[2];switch(o){case"rgb":case"rgba":if(s=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(s[4]),this.setRGB(Math.min(255,parseInt(s[1],10))/255,Math.min(255,parseInt(s[2],10))/255,Math.min(255,parseInt(s[3],10))/255,t);if(s=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(s[4]),this.setRGB(Math.min(100,parseInt(s[1],10))/100,Math.min(100,parseInt(s[2],10))/100,Math.min(100,parseInt(s[3],10))/100,t);break;case"hsl":case"hsla":if(s=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(s[4]),this.setHSL(parseFloat(s[1])/360,parseFloat(s[2])/100,parseFloat(s[3])/100,t);break;default:console.warn("THREE.Color: Unknown color model "+e)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(e)){let s=i[1],o=s.length;if(o===3)return this.setRGB(parseInt(s.charAt(0),16)/15,parseInt(s.charAt(1),16)/15,parseInt(s.charAt(2),16)/15,t);if(o===6)return this.setHex(parseInt(s,16),t);console.warn("THREE.Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=wt){let n=Lm[e.toLowerCase()];return n!==void 0?this.setHex(n,t):console.warn("THREE.Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=mi(e.r),this.g=mi(e.g),this.b=mi(e.b),this}copyLinearToSRGB(e){return this.r=dr(e.r),this.g=dr(e.g),this.b=dr(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=wt){return Ze.workingToColorSpace(kt.copy(this),e),Math.round(Fe(kt.r*255,0,255))*65536+Math.round(Fe(kt.g*255,0,255))*256+Math.round(Fe(kt.b*255,0,255))}getHexString(e=wt){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=Ze.workingColorSpace){Ze.workingToColorSpace(kt.copy(this),t);let n=kt.r,i=kt.g,s=kt.b,o=Math.max(n,i,s),a=Math.min(n,i,s),c,l,h=(a+o)/2;if(a===o)c=0,l=0;else{let u=o-a;switch(l=h<=.5?u/(o+a):u/(2-o-a),o){case n:c=(i-s)/u+(i<s?6:0);break;case i:c=(s-n)/u+2;break;case s:c=(n-i)/u+4;break}c/=6}return e.h=c,e.s=l,e.l=h,e}getRGB(e,t=Ze.workingColorSpace){return Ze.workingToColorSpace(kt.copy(this),t),e.r=kt.r,e.g=kt.g,e.b=kt.b,e}getStyle(e=wt){Ze.workingToColorSpace(kt.copy(this),e);let t=kt.r,n=kt.g,i=kt.b;return e!==wt?`color(${e} ${t.toFixed(3)} ${n.toFixed(3)} ${i.toFixed(3)})`:`rgb(${Math.round(t*255)},${Math.round(n*255)},${Math.round(i*255)})`}offsetHSL(e,t,n){return this.getHSL(Ii),this.setHSL(Ii.h+e,Ii.s+t,Ii.l+n)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,t){return this.r=e.r+t.r,this.g=e.g+t.g,this.b=e.b+t.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,t){return this.r+=(e.r-this.r)*t,this.g+=(e.g-this.g)*t,this.b+=(e.b-this.b)*t,this}lerpColors(e,t,n){return this.r=e.r+(t.r-e.r)*n,this.g=e.g+(t.g-e.g)*n,this.b=e.b+(t.b-e.b)*n,this}lerpHSL(e,t){this.getHSL(Ii),e.getHSL(Lc);let n=So(Ii.h,Lc.h,t),i=So(Ii.s,Lc.s,t),s=So(Ii.l,Lc.l,t);return this.setHSL(n,i,s),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){let t=this.r,n=this.g,i=this.b,s=e.elements;return this.r=s[0]*t+s[3]*n+s[6]*i,this.g=s[1]*t+s[4]*n+s[7]*i,this.b=s[2]*t+s[5]*n+s[8]*i,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}},kt=new ue;ue.NAMES=Lm;var r_=0,Mt=class extends xn{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:r_++}),this.uuid=gn(),this.name="",this.type="Material",this.blending=Fi,this.side=An,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=Eo,this.blendDst=Ao,this.blendEquation=gi,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new ue(0,0,0),this.blendAlpha=0,this.depthFunc=Oi,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=pl,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=Di,this.stencilZFail=Di,this.stencilZPass=Di,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(let t in e){let n=e[t];if(n===void 0){console.warn(`THREE.Material: parameter '${t}' has value of undefined.`);continue}let i=this[t];if(i===void 0){console.warn(`THREE.Material: '${t}' is not a property of THREE.${this.type}.`);continue}i&&i.isColor?i.set(n):i&&i.isVector3&&n&&n.isVector3?i.copy(n):this[t]=n}}toJSON(e){let t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});let n={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};n.uuid=this.uuid,n.type=this.type,this.name!==""&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),this.roughness!==void 0&&(n.roughness=this.roughness),this.metalness!==void 0&&(n.metalness=this.metalness),this.sheen!==void 0&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(n.shininess=this.shininess),this.clearcoat!==void 0&&(n.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(n.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(n.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(n.dispersion=this.dispersion),this.iridescence!==void 0&&(n.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(n.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(n.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(n.combine=this.combine)),this.envMapRotation!==void 0&&(n.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(n.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(n.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(n.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(n.size=this.size),this.shadowSide!==null&&(n.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),this.blending!==Fi&&(n.blending=this.blending),this.side!==An&&(n.side=this.side),this.vertexColors===!0&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),this.transparent===!0&&(n.transparent=!0),this.blendSrc!==Eo&&(n.blendSrc=this.blendSrc),this.blendDst!==Ao&&(n.blendDst=this.blendDst),this.blendEquation!==gi&&(n.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(n.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(n.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(n.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(n.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(n.blendAlpha=this.blendAlpha),this.depthFunc!==Oi&&(n.depthFunc=this.depthFunc),this.depthTest===!1&&(n.depthTest=this.depthTest),this.depthWrite===!1&&(n.depthWrite=this.depthWrite),this.colorWrite===!1&&(n.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(n.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==pl&&(n.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(n.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==Di&&(n.stencilFail=this.stencilFail),this.stencilZFail!==Di&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==Di&&(n.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(n.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(n.rotation=this.rotation),this.polygonOffset===!0&&(n.polygonOffset=!0),this.polygonOffsetFactor!==0&&(n.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(n.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(n.linewidth=this.linewidth),this.dashSize!==void 0&&(n.dashSize=this.dashSize),this.gapSize!==void 0&&(n.gapSize=this.gapSize),this.scale!==void 0&&(n.scale=this.scale),this.dithering===!0&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),this.alphaHash===!0&&(n.alphaHash=!0),this.alphaToCoverage===!0&&(n.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(n.premultipliedAlpha=!0),this.forceSinglePass===!0&&(n.forceSinglePass=!0),this.wireframe===!0&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(n.flatShading=!0),this.visible===!1&&(n.visible=!1),this.toneMapped===!1&&(n.toneMapped=!1),this.fog===!1&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData);function i(s){let o=[];for(let a in s){let c=s[a];delete c.metadata,o.push(c)}return o}if(t){let s=i(e.textures),o=i(e.images);s.length>0&&(n.textures=s),o.length>0&&(n.images=o)}return n}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;let t=e.clippingPlanes,n=null;if(t!==null){let i=t.length;n=new Array(i);for(let s=0;s!==i;++s)n[s]=t[s].clone()}return this.clippingPlanes=n,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}},Bt=class extends Mt{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new ue(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 rn,this.combine=Gr,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}},pi=o_();function o_(){let r=new ArrayBuffer(4),e=new Float32Array(r),t=new Uint32Array(r),n=new Uint32Array(512),i=new Uint32Array(512);for(let c=0;c<256;++c){let l=c-127;l<-27?(n[c]=0,n[c|256]=32768,i[c]=24,i[c|256]=24):l<-14?(n[c]=1024>>-l-14,n[c|256]=1024>>-l-14|32768,i[c]=-l-1,i[c|256]=-l-1):l<=15?(n[c]=l+15<<10,n[c|256]=l+15<<10|32768,i[c]=13,i[c|256]=13):l<128?(n[c]=31744,n[c|256]=64512,i[c]=24,i[c|256]=24):(n[c]=31744,n[c|256]=64512,i[c]=13,i[c|256]=13)}let s=new Uint32Array(2048),o=new Uint32Array(64),a=new Uint32Array(64);for(let c=1;c<1024;++c){let l=c<<13,h=0;for(;(l&8388608)===0;)l<<=1,h-=8388608;l&=-8388609,h+=947912704,s[c]=l|h}for(let c=1024;c<2048;++c)s[c]=939524096+(c-1024<<13);for(let c=1;c<31;++c)o[c]=c<<23;o[31]=1199570944,o[32]=2147483648;for(let c=33;c<63;++c)o[c]=2147483648+(c-32<<23);o[63]=3347054592;for(let c=1;c<64;++c)c!==32&&(a[c]=1024);return{floatView:e,uint32View:t,baseTable:n,shiftTable:i,mantissaTable:s,exponentTable:o,offsetTable:a}}function nn(r){Math.abs(r)>65504&&console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."),r=Fe(r,-65504,65504),pi.floatView[0]=r;let e=pi.uint32View[0],t=e>>23&511;return pi.baseTable[t]+((e&8388607)>>pi.shiftTable[t])}function yo(r){let e=r>>10;return pi.uint32View[0]=pi.mantissaTable[pi.offsetTable[e]+(r&1023)]+pi.exponentTable[e],pi.floatView[0]}var _l=class{static toHalfFloat(e){return nn(e)}static fromHalfFloat(e){return yo(e)}},It=new w,Dc=new Y,a_=0,je=class{constructor(e,t,n=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:a_++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=n,this.usage=mr,this.updateRanges=[],this.gpuType=Jt,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,n){e*=this.itemSize,n*=t.itemSize;for(let i=0,s=this.itemSize;i<s;i++)this.array[e+i]=t.array[n+i];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let t=0,n=this.count;t<n;t++)Dc.fromBufferAttribute(this,t),Dc.applyMatrix3(e),this.setXY(t,Dc.x,Dc.y);else if(this.itemSize===3)for(let t=0,n=this.count;t<n;t++)It.fromBufferAttribute(this,t),It.applyMatrix3(e),this.setXYZ(t,It.x,It.y,It.z);return this}applyMatrix4(e){for(let t=0,n=this.count;t<n;t++)It.fromBufferAttribute(this,t),It.applyMatrix4(e),this.setXYZ(t,It.x,It.y,It.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)It.fromBufferAttribute(this,t),It.applyNormalMatrix(e),this.setXYZ(t,It.x,It.y,It.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)It.fromBufferAttribute(this,t),It.transformDirection(e),this.setXYZ(t,It.x,It.y,It.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let n=this.array[e*this.itemSize+t];return this.normalized&&(n=Zt(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=Xe(n,this.array)),this.array[e*this.itemSize+t]=n,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=Zt(t,this.array)),t}setX(e,t){return this.normalized&&(t=Xe(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=Zt(t,this.array)),t}setY(e,t){return this.normalized&&(t=Xe(t,this.array)),this.array[e*this.itemSize+1]=t,this}getZ(e){let t=this.array[e*this.itemSize+2];return this.normalized&&(t=Zt(t,this.array)),t}setZ(e,t){return this.normalized&&(t=Xe(t,this.array)),this.array[e*this.itemSize+2]=t,this}getW(e){let t=this.array[e*this.itemSize+3];return this.normalized&&(t=Zt(t,this.array)),t}setW(e,t){return this.normalized&&(t=Xe(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=Xe(t,this.array),n=Xe(n,this.array)),this.array[e+0]=t,this.array[e+1]=n,this}setXYZ(e,t,n,i){return e*=this.itemSize,this.normalized&&(t=Xe(t,this.array),n=Xe(n,this.array),i=Xe(i,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=i,this}setXYZW(e,t,n,i,s){return e*=this.itemSize,this.normalized&&(t=Xe(t,this.array),n=Xe(n,this.array),i=Xe(i,this.array),s=Xe(s,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=i,this.array[e+3]=s,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){let e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return this.name!==""&&(e.name=this.name),this.usage!==mr&&(e.usage=this.usage),e}},xl=class extends je{constructor(e,t,n){super(new Int8Array(e),t,n)}},yl=class extends je{constructor(e,t,n){super(new Uint8Array(e),t,n)}},vl=class extends je{constructor(e,t,n){super(new Uint8ClampedArray(e),t,n)}},Ml=class extends je{constructor(e,t,n){super(new Int16Array(e),t,n)}},yr=class extends je{constructor(e,t,n){super(new Uint16Array(e),t,n)}},Sl=class extends je{constructor(e,t,n){super(new Int32Array(e),t,n)}},vr=class extends je{constructor(e,t,n){super(new Uint32Array(e),t,n)}},bl=class extends je{constructor(e,t,n){super(new Uint16Array(e),t,n),this.isFloat16BufferAttribute=!0}getX(e){let t=yo(this.array[e*this.itemSize]);return this.normalized&&(t=Zt(t,this.array)),t}setX(e,t){return this.normalized&&(t=Xe(t,this.array)),this.array[e*this.itemSize]=nn(t),this}getY(e){let t=yo(this.array[e*this.itemSize+1]);return this.normalized&&(t=Zt(t,this.array)),t}setY(e,t){return this.normalized&&(t=Xe(t,this.array)),this.array[e*this.itemSize+1]=nn(t),this}getZ(e){let t=yo(this.array[e*this.itemSize+2]);return this.normalized&&(t=Zt(t,this.array)),t}setZ(e,t){return this.normalized&&(t=Xe(t,this.array)),this.array[e*this.itemSize+2]=nn(t),this}getW(e){let t=yo(this.array[e*this.itemSize+3]);return this.normalized&&(t=Zt(t,this.array)),t}setW(e,t){return this.normalized&&(t=Xe(t,this.array)),this.array[e*this.itemSize+3]=nn(t),this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=Xe(t,this.array),n=Xe(n,this.array)),this.array[e+0]=nn(t),this.array[e+1]=nn(n),this}setXYZ(e,t,n,i){return e*=this.itemSize,this.normalized&&(t=Xe(t,this.array),n=Xe(n,this.array),i=Xe(i,this.array)),this.array[e+0]=nn(t),this.array[e+1]=nn(n),this.array[e+2]=nn(i),this}setXYZW(e,t,n,i,s){return e*=this.itemSize,this.normalized&&(t=Xe(t,this.array),n=Xe(n,this.array),i=Xe(i,this.array),s=Xe(s,this.array)),this.array[e+0]=nn(t),this.array[e+1]=nn(n),this.array[e+2]=nn(i),this.array[e+3]=nn(s),this}},ye=class extends je{constructor(e,t,n){super(new Float32Array(e),t,n)}},c_=0,Tn=new De,cu=new Qe,er=new w,fn=new Rt,lo=new Rt,Ft=new w,ze=class r extends xn{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:c_++}),this.uuid=gn(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(Ld(e)?vr:yr)(e,1):this.index=e,this}setIndirect(e){return this.indirect=e,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,t,n=0){this.groups.push({start:e,count:t,materialIndex:n})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){let t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);let n=this.attributes.normal;if(n!==void 0){let s=new Ve().getNormalMatrix(e);n.applyNormalMatrix(s),n.needsUpdate=!0}let i=this.attributes.tangent;return i!==void 0&&(i.transformDirection(e),i.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(e){return Tn.makeRotationFromQuaternion(e),this.applyMatrix4(Tn),this}rotateX(e){return Tn.makeRotationX(e),this.applyMatrix4(Tn),this}rotateY(e){return Tn.makeRotationY(e),this.applyMatrix4(Tn),this}rotateZ(e){return Tn.makeRotationZ(e),this.applyMatrix4(Tn),this}translate(e,t,n){return Tn.makeTranslation(e,t,n),this.applyMatrix4(Tn),this}scale(e,t,n){return Tn.makeScale(e,t,n),this.applyMatrix4(Tn),this}lookAt(e){return cu.lookAt(e),cu.updateMatrix(),this.applyMatrix4(cu.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(er).negate(),this.translate(er.x,er.y,er.z),this}setFromPoints(e){let t=this.getAttribute("position");if(t===void 0){let n=[];for(let i=0,s=e.length;i<s;i++){let o=e[i];n.push(o.x,o.y,o.z||0)}this.setAttribute("position",new ye(n,3))}else{let n=Math.min(e.length,t.count);for(let i=0;i<n;i++){let s=e[i];t.setXYZ(i,s.x,s.y,s.z||0)}e.length>t.count&&console.warn("THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Rt);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new w(-1/0,-1/0,-1/0),new w(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let n=0,i=t.length;n<i;n++){let s=t[n];fn.setFromBufferAttribute(s),this.morphTargetsRelative?(Ft.addVectors(this.boundingBox.min,fn.min),this.boundingBox.expandByPoint(Ft),Ft.addVectors(this.boundingBox.max,fn.max),this.boundingBox.expandByPoint(Ft)):(this.boundingBox.expandByPoint(fn.min),this.boundingBox.expandByPoint(fn.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new Et);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error("THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new w,1/0);return}if(e){let n=this.boundingSphere.center;if(fn.setFromBufferAttribute(e),t)for(let s=0,o=t.length;s<o;s++){let a=t[s];lo.setFromBufferAttribute(a),this.morphTargetsRelative?(Ft.addVectors(fn.min,lo.min),fn.expandByPoint(Ft),Ft.addVectors(fn.max,lo.max),fn.expandByPoint(Ft)):(fn.expandByPoint(lo.min),fn.expandByPoint(lo.max))}fn.getCenter(n);let i=0;for(let s=0,o=e.count;s<o;s++)Ft.fromBufferAttribute(e,s),i=Math.max(i,n.distanceToSquared(Ft));if(t)for(let s=0,o=t.length;s<o;s++){let a=t[s],c=this.morphTargetsRelative;for(let l=0,h=a.count;l<h;l++)Ft.fromBufferAttribute(a,l),c&&(er.fromBufferAttribute(e,l),Ft.add(er)),i=Math.max(i,n.distanceToSquared(Ft))}this.boundingSphere.radius=Math.sqrt(i),isNaN(this.boundingSphere.radius)&&console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){let e=this.index,t=this.attributes;if(e===null||t.position===void 0||t.normal===void 0||t.uv===void 0){console.error("THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}let n=t.position,i=t.normal,s=t.uv;this.hasAttribute("tangent")===!1&&this.setAttribute("tangent",new je(new Float32Array(4*n.count),4));let o=this.getAttribute("tangent"),a=[],c=[];for(let I=0;I<n.count;I++)a[I]=new w,c[I]=new w;let l=new w,h=new w,u=new w,d=new Y,f=new Y,m=new Y,_=new w,g=new w;function p(I,b,S){l.fromBufferAttribute(n,I),h.fromBufferAttribute(n,b),u.fromBufferAttribute(n,S),d.fromBufferAttribute(s,I),f.fromBufferAttribute(s,b),m.fromBufferAttribute(s,S),h.sub(l),u.sub(l),f.sub(d),m.sub(d);let L=1/(f.x*m.y-m.x*f.y);isFinite(L)&&(_.copy(h).multiplyScalar(m.y).addScaledVector(u,-f.y).multiplyScalar(L),g.copy(u).multiplyScalar(f.x).addScaledVector(h,-m.x).multiplyScalar(L),a[I].add(_),a[b].add(_),a[S].add(_),c[I].add(g),c[b].add(g),c[S].add(g))}let v=this.groups;v.length===0&&(v=[{start:0,count:e.count}]);for(let I=0,b=v.length;I<b;++I){let S=v[I],L=S.start,F=S.count;for(let z=L,G=L+F;z<G;z+=3)p(e.getX(z+0),e.getX(z+1),e.getX(z+2))}let y=new w,x=new w,A=new w,E=new w;function C(I){A.fromBufferAttribute(i,I),E.copy(A);let b=a[I];y.copy(b),y.sub(A.multiplyScalar(A.dot(b))).normalize(),x.crossVectors(E,b);let L=x.dot(c[I])<0?-1:1;o.setXYZW(I,y.x,y.y,y.z,L)}for(let I=0,b=v.length;I<b;++I){let S=v[I],L=S.start,F=S.count;for(let z=L,G=L+F;z<G;z+=3)C(e.getX(z+0)),C(e.getX(z+1)),C(e.getX(z+2))}}computeVertexNormals(){let e=this.index,t=this.getAttribute("position");if(t!==void 0){let n=this.getAttribute("normal");if(n===void 0)n=new je(new Float32Array(t.count*3),3),this.setAttribute("normal",n);else for(let d=0,f=n.count;d<f;d++)n.setXYZ(d,0,0,0);let i=new w,s=new w,o=new w,a=new w,c=new w,l=new w,h=new w,u=new w;if(e)for(let d=0,f=e.count;d<f;d+=3){let m=e.getX(d+0),_=e.getX(d+1),g=e.getX(d+2);i.fromBufferAttribute(t,m),s.fromBufferAttribute(t,_),o.fromBufferAttribute(t,g),h.subVectors(o,s),u.subVectors(i,s),h.cross(u),a.fromBufferAttribute(n,m),c.fromBufferAttribute(n,_),l.fromBufferAttribute(n,g),a.add(h),c.add(h),l.add(h),n.setXYZ(m,a.x,a.y,a.z),n.setXYZ(_,c.x,c.y,c.z),n.setXYZ(g,l.x,l.y,l.z)}else for(let d=0,f=t.count;d<f;d+=3)i.fromBufferAttribute(t,d+0),s.fromBufferAttribute(t,d+1),o.fromBufferAttribute(t,d+2),h.subVectors(o,s),u.subVectors(i,s),h.cross(u),n.setXYZ(d+0,h.x,h.y,h.z),n.setXYZ(d+1,h.x,h.y,h.z),n.setXYZ(d+2,h.x,h.y,h.z);this.normalizeNormals(),n.needsUpdate=!0}}normalizeNormals(){let e=this.attributes.normal;for(let t=0,n=e.count;t<n;t++)Ft.fromBufferAttribute(e,t),Ft.normalize(),e.setXYZ(t,Ft.x,Ft.y,Ft.z)}toNonIndexed(){function e(a,c){let l=a.array,h=a.itemSize,u=a.normalized,d=new l.constructor(c.length*h),f=0,m=0;for(let _=0,g=c.length;_<g;_++){a.isInterleavedBufferAttribute?f=c[_]*a.data.stride+a.offset:f=c[_]*h;for(let p=0;p<h;p++)d[m++]=l[f++]}return new je(d,h,u)}if(this.index===null)return console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;let t=new r,n=this.index.array,i=this.attributes;for(let a in i){let c=i[a],l=e(c,n);t.setAttribute(a,l)}let s=this.morphAttributes;for(let a in s){let c=[],l=s[a];for(let h=0,u=l.length;h<u;h++){let d=l[h],f=e(d,n);c.push(f)}t.morphAttributes[a]=c}t.morphTargetsRelative=this.morphTargetsRelative;let o=this.groups;for(let a=0,c=o.length;a<c;a++){let l=o[a];t.addGroup(l.start,l.count,l.materialIndex)}return t}toJSON(){let e={metadata:{version:4.7,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(e.uuid=this.uuid,e.type=this.type,this.name!==""&&(e.name=this.name),Object.keys(this.userData).length>0&&(e.userData=this.userData),this.parameters!==void 0){let c=this.parameters;for(let l in c)c[l]!==void 0&&(e[l]=c[l]);return e}e.data={attributes:{}};let t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});let n=this.attributes;for(let c in n){let l=n[c];e.data.attributes[c]=l.toJSON(e.data)}let i={},s=!1;for(let c in this.morphAttributes){let l=this.morphAttributes[c],h=[];for(let u=0,d=l.length;u<d;u++){let f=l[u];h.push(f.toJSON(e.data))}h.length>0&&(i[c]=h,s=!0)}s&&(e.data.morphAttributes=i,e.data.morphTargetsRelative=this.morphTargetsRelative);let o=this.groups;o.length>0&&(e.data.groups=JSON.parse(JSON.stringify(o)));let a=this.boundingSphere;return a!==null&&(e.data.boundingSphere=a.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;let t={};this.name=e.name;let n=e.index;n!==null&&this.setIndex(n.clone());let i=e.attributes;for(let l in i){let h=i[l];this.setAttribute(l,h.clone(t))}let s=e.morphAttributes;for(let l in s){let h=[],u=s[l];for(let d=0,f=u.length;d<f;d++)h.push(u[d].clone(t));this.morphAttributes[l]=h}this.morphTargetsRelative=e.morphTargetsRelative;let o=e.groups;for(let l=0,h=o.length;l<h;l++){let u=o[l];this.addGroup(u.start,u.count,u.materialIndex)}let a=e.boundingBox;a!==null&&(this.boundingBox=a.clone());let c=e.boundingSphere;return c!==null&&(this.boundingSphere=c.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this}dispose(){this.dispatchEvent({type:"dispose"})}},np=new De,ji=new On,Nc=new Et,ip=new w,Uc=new w,Fc=new w,Oc=new w,lu=new w,Bc=new w,sp=new w,zc=new w,pt=class extends Qe{constructor(e=new ze,t=new Bt){super(),this.isMesh=!0,this.type="Mesh",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),e.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),e.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){let t=this.geometry.morphAttributes,n=Object.keys(t);if(n.length>0){let i=t[n[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,o=i.length;s<o;s++){let a=i[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=s}}}}getVertexPosition(e,t){let n=this.geometry,i=n.attributes.position,s=n.morphAttributes.position,o=n.morphTargetsRelative;t.fromBufferAttribute(i,e);let a=this.morphTargetInfluences;if(s&&a){Bc.set(0,0,0);for(let c=0,l=s.length;c<l;c++){let h=a[c],u=s[c];h!==0&&(lu.fromBufferAttribute(u,e),o?Bc.addScaledVector(lu,h):Bc.addScaledVector(lu.sub(t),h))}t.add(Bc)}return t}raycast(e,t){let n=this.geometry,i=this.material,s=this.matrixWorld;i!==void 0&&(n.boundingSphere===null&&n.computeBoundingSphere(),Nc.copy(n.boundingSphere),Nc.applyMatrix4(s),ji.copy(e.ray).recast(e.near),!(Nc.containsPoint(ji.origin)===!1&&(ji.intersectSphere(Nc,ip)===null||ji.origin.distanceToSquared(ip)>(e.far-e.near)**2))&&(np.copy(s).invert(),ji.copy(e.ray).applyMatrix4(np),!(n.boundingBox!==null&&ji.intersectsBox(n.boundingBox)===!1)&&this._computeIntersections(e,t,ji)))}_computeIntersections(e,t,n){let i,s=this.geometry,o=this.material,a=s.index,c=s.attributes.position,l=s.attributes.uv,h=s.attributes.uv1,u=s.attributes.normal,d=s.groups,f=s.drawRange;if(a!==null)if(Array.isArray(o))for(let m=0,_=d.length;m<_;m++){let g=d[m],p=o[g.materialIndex],v=Math.max(g.start,f.start),y=Math.min(a.count,Math.min(g.start+g.count,f.start+f.count));for(let x=v,A=y;x<A;x+=3){let E=a.getX(x),C=a.getX(x+1),I=a.getX(x+2);i=kc(this,p,e,n,l,h,u,E,C,I),i&&(i.faceIndex=Math.floor(x/3),i.face.materialIndex=g.materialIndex,t.push(i))}}else{let m=Math.max(0,f.start),_=Math.min(a.count,f.start+f.count);for(let g=m,p=_;g<p;g+=3){let v=a.getX(g),y=a.getX(g+1),x=a.getX(g+2);i=kc(this,o,e,n,l,h,u,v,y,x),i&&(i.faceIndex=Math.floor(g/3),t.push(i))}}else if(c!==void 0)if(Array.isArray(o))for(let m=0,_=d.length;m<_;m++){let g=d[m],p=o[g.materialIndex],v=Math.max(g.start,f.start),y=Math.min(c.count,Math.min(g.start+g.count,f.start+f.count));for(let x=v,A=y;x<A;x+=3){let E=x,C=x+1,I=x+2;i=kc(this,p,e,n,l,h,u,E,C,I),i&&(i.faceIndex=Math.floor(x/3),i.face.materialIndex=g.materialIndex,t.push(i))}}else{let m=Math.max(0,f.start),_=Math.min(c.count,f.start+f.count);for(let g=m,p=_;g<p;g+=3){let v=g,y=g+1,x=g+2;i=kc(this,o,e,n,l,h,u,v,y,x),i&&(i.faceIndex=Math.floor(g/3),t.push(i))}}}};function l_(r,e,t,n,i,s,o,a){let c;if(e.side===Wt?c=n.intersectTriangle(o,s,i,!0,a):c=n.intersectTriangle(i,s,o,e.side===An,a),c===null)return null;zc.copy(a),zc.applyMatrix4(r.matrixWorld);let l=t.ray.origin.distanceTo(zc);return l<t.near||l>t.far?null:{distance:l,point:zc.clone(),object:r}}function kc(r,e,t,n,i,s,o,a,c,l){r.getVertexPosition(a,Uc),r.getVertexPosition(c,Fc),r.getVertexPosition(l,Oc);let h=l_(r,e,t,n,Uc,Fc,Oc,sp);if(h){let u=new w;Nn.getBarycoord(sp,Uc,Fc,Oc,u),i&&(h.uv=Nn.getInterpolatedAttribute(i,a,c,l,u,new Y)),s&&(h.uv1=Nn.getInterpolatedAttribute(s,a,c,l,u,new Y)),o&&(h.normal=Nn.getInterpolatedAttribute(o,a,c,l,u,new w),h.normal.dot(n.direction)>0&&h.normal.multiplyScalar(-1));let d={a,b:c,c:l,normal:new w,materialIndex:0};Nn.getNormal(Uc,Fc,Oc,d.normal),h.face=d,h.barycoord=u}return h}var Vi=class r extends ze{constructor(e=1,t=1,n=1,i=1,s=1,o=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:n,widthSegments:i,heightSegments:s,depthSegments:o};let a=this;i=Math.floor(i),s=Math.floor(s),o=Math.floor(o);let c=[],l=[],h=[],u=[],d=0,f=0;m("z","y","x",-1,-1,n,t,e,o,s,0),m("z","y","x",1,-1,n,t,-e,o,s,1),m("x","z","y",1,1,e,n,t,i,o,2),m("x","z","y",1,-1,e,n,-t,i,o,3),m("x","y","z",1,-1,e,t,n,i,s,4),m("x","y","z",-1,-1,e,t,-n,i,s,5),this.setIndex(c),this.setAttribute("position",new ye(l,3)),this.setAttribute("normal",new ye(h,3)),this.setAttribute("uv",new ye(u,2));function m(_,g,p,v,y,x,A,E,C,I,b){let S=x/C,L=A/I,F=x/2,z=A/2,G=E/2,q=C+1,W=I+1,ne=0,H=0,de=new w;for(let xe=0;xe<W;xe++){let Se=xe*L-z;for(let We=0;We<q;We++){let et=We*S-F;de[_]=et*v,de[g]=Se*y,de[p]=G,l.push(de.x,de.y,de.z),de[_]=0,de[g]=0,de[p]=E>0?1:-1,h.push(de.x,de.y,de.z),u.push(We/C),u.push(1-xe/I),ne+=1}}for(let xe=0;xe<I;xe++)for(let Se=0;Se<C;Se++){let We=d+Se+q*xe,et=d+Se+q*(xe+1),at=d+(Se+1)+q*(xe+1),nt=d+(Se+1)+q*xe;c.push(We,et,nt),c.push(et,at,nt),H+=6}a.addGroup(f,H,b),f+=H,d+=ne}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new r(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}};function Bs(r){let e={};for(let t in r){e[t]={};for(let n in r[t]){let i=r[t][n];i&&(i.isColor||i.isMatrix3||i.isMatrix4||i.isVector2||i.isVector3||i.isVector4||i.isTexture||i.isQuaternion)?i.isRenderTargetTexture?(console.warn("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),e[t][n]=null):e[t][n]=i.clone():Array.isArray(i)?e[t][n]=i.slice():e[t][n]=i}}return e}function Xt(r){let e={};for(let t=0;t<r.length;t++){let n=Bs(r[t]);for(let i in n)e[i]=n[i]}return e}function h_(r){let e=[];for(let t=0;t<r.length;t++)e.push(r[t].clone());return e}function Nd(r){let e=r.getRenderTarget();return e===null?r.outputColorSpace:e.isXRRenderTarget===!0?e.texture.colorSpace:Ze.workingColorSpace}var Ud={clone:Bs,merge:Xt},u_=`void main() {+ gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );+}`,d_=`void main() {+ gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );+}`,on=class extends Mt{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=u_,this.fragmentShader=d_,this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,e!==void 0&&this.setValues(e)}copy(e){return super.copy(e),this.fragmentShader=e.fragmentShader,this.vertexShader=e.vertexShader,this.uniforms=Bs(e.uniforms),this.uniformsGroups=h_(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this}toJSON(e){let t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(let i in this.uniforms){let o=this.uniforms[i].value;o&&o.isTexture?t.uniforms[i]={type:"t",value:o.toJSON(e).uuid}:o&&o.isColor?t.uniforms[i]={type:"c",value:o.getHex()}:o&&o.isVector2?t.uniforms[i]={type:"v2",value:o.toArray()}:o&&o.isVector3?t.uniforms[i]={type:"v3",value:o.toArray()}:o&&o.isVector4?t.uniforms[i]={type:"v4",value:o.toArray()}:o&&o.isMatrix3?t.uniforms[i]={type:"m3",value:o.toArray()}:o&&o.isMatrix4?t.uniforms[i]={type:"m4",value:o.toArray()}:t.uniforms[i]={value:o}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;let n={};for(let i in this.extensions)this.extensions[i]===!0&&(n[i]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}},gs=class extends Qe{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new De,this.projectionMatrix=new De,this.projectionMatrixInverse=new De,this.coordinateSystem=sn,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}},Pi=new w,rp=new Y,op=new Y,Tt=class extends gs{constructor(e=50,t=1,n=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=n,this.far=i,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){let t=.5*this.getFilmHeight()/e;this.fov=ds*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){let e=Math.tan(ls*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return ds*2*Math.atan(Math.tan(ls*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,n){Pi.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(Pi.x,Pi.y).multiplyScalar(-e/Pi.z),Pi.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(Pi.x,Pi.y).multiplyScalar(-e/Pi.z)}getViewSize(e,t){return this.getViewBounds(e,rp,op),t.subVectors(op,rp)}setViewOffset(e,t,n,i,s,o){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=i,this.view.width=s,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let e=this.near,t=e*Math.tan(ls*.5*this.fov)/this.zoom,n=2*t,i=this.aspect*n,s=-.5*i,o=this.view;if(this.view!==null&&this.view.enabled){let c=o.fullWidth,l=o.fullHeight;s+=o.offsetX*i/c,t-=o.offsetY*n/l,i*=o.width/c,n*=o.height/l}let a=this.filmOffset;a!==0&&(s+=e*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(s,s+i,t,t-n,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}},tr=-90,nr=1,Ro=class extends Qe{constructor(e,t,n){super(),this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;let i=new Tt(tr,nr,e,t);i.layers=this.layers,this.add(i);let s=new Tt(tr,nr,e,t);s.layers=this.layers,this.add(s);let o=new Tt(tr,nr,e,t);o.layers=this.layers,this.add(o);let a=new Tt(tr,nr,e,t);a.layers=this.layers,this.add(a);let c=new Tt(tr,nr,e,t);c.layers=this.layers,this.add(c);let l=new Tt(tr,nr,e,t);l.layers=this.layers,this.add(l)}updateCoordinateSystem(){let e=this.coordinateSystem,t=this.children.concat(),[n,i,s,o,a,c]=t;for(let l of t)this.remove(l);if(e===sn)n.up.set(0,1,0),n.lookAt(1,0,0),i.up.set(0,1,0),i.lookAt(-1,0,0),s.up.set(0,0,-1),s.lookAt(0,1,0),o.up.set(0,0,1),o.lookAt(0,-1,0),a.up.set(0,1,0),a.lookAt(0,0,1),c.up.set(0,1,0),c.lookAt(0,0,-1);else if(e===us)n.up.set(0,-1,0),n.lookAt(-1,0,0),i.up.set(0,-1,0),i.lookAt(1,0,0),s.up.set(0,0,1),s.lookAt(0,1,0),o.up.set(0,0,-1),o.lookAt(0,-1,0),a.up.set(0,-1,0),a.lookAt(0,0,1),c.up.set(0,-1,0),c.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(let l of t)this.add(l),l.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();let{renderTarget:n,activeMipmapLevel:i}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());let[s,o,a,c,l,h]=this.children,u=e.getRenderTarget(),d=e.getActiveCubeFace(),f=e.getActiveMipmapLevel(),m=e.xr.enabled;e.xr.enabled=!1;let _=n.texture.generateMipmaps;n.texture.generateMipmaps=!1,e.setRenderTarget(n,0,i),e.render(t,s),e.setRenderTarget(n,1,i),e.render(t,o),e.setRenderTarget(n,2,i),e.render(t,a),e.setRenderTarget(n,3,i),e.render(t,c),e.setRenderTarget(n,4,i),e.render(t,l),n.texture.generateMipmaps=_,e.setRenderTarget(n,5,i),e.render(t,h),e.setRenderTarget(u,d,f),e.xr.enabled=m,n.texture.needsPMREMUpdate=!0}},Hi=class extends gt{constructor(e=[],t=ii,n,i,s,o,a,c,l,h){super(e,t,n,i,s,o,a,c,l,h),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}},Co=class extends yn{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;let n={width:e,height:e,depth:1},i=[n,n,n,n,n,n];this.texture=new Hi(i),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;let n={uniforms:{tEquirect:{value:null}},vertexShader:`++ varying vec3 vWorldDirection;++ vec3 transformDirection( in vec3 dir, in mat4 matrix ) {++ return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );++ }++ void main() {++ vWorldDirection = transformDirection( position, modelMatrix );++ #include <begin_vertex>+ #include <project_vertex>++ }+ `,fragmentShader:`++ uniform sampler2D tEquirect;++ varying vec3 vWorldDirection;++ #include <common>++ void main() {++ vec3 direction = normalize( vWorldDirection );++ vec2 sampleUV = equirectUv( direction );++ gl_FragColor = texture2D( tEquirect, sampleUV );++ }+ `},i=new Vi(5,5,5),s=new on({name:"CubemapFromEquirect",uniforms:Bs(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:Wt,blending:ti});s.uniforms.tEquirect.value=t;let o=new pt(i,s),a=t.minFilter;return t.minFilter===cn&&(t.minFilter=mt),new Ro(1,10,this).update(e,o),t.minFilter=a,o.geometry.dispose(),o.material.dispose(),this}clear(e,t=!0,n=!0,i=!0){let s=e.getRenderTarget();for(let o=0;o<6;o++)e.setRenderTarget(this,o),e.clear(t,n,i);e.setRenderTarget(s)}},mn=class extends Qe{constructor(){super(),this.isGroup=!0,this.type="Group"}},f_={type:"move"},_s=class{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new mn,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new mn,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new w,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new w),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new mn,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new w,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new w),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){let t=this._hand;if(t)for(let n of e.hand.values())this._getHandJoint(t,n)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,n){let i=null,s=null,o=null,a=this._targetRay,c=this._grip,l=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(l&&e.hand){o=!0;for(let _ of e.hand.values()){let g=t.getJointPose(_,n),p=this._getHandJoint(l,_);g!==null&&(p.matrix.fromArray(g.transform.matrix),p.matrix.decompose(p.position,p.rotation,p.scale),p.matrixWorldNeedsUpdate=!0,p.jointRadius=g.radius),p.visible=g!==null}let h=l.joints["index-finger-tip"],u=l.joints["thumb-tip"],d=h.position.distanceTo(u.position),f=.02,m=.005;l.inputState.pinching&&d>f+m?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!l.inputState.pinching&&d<=f-m&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else c!==null&&e.gripSpace&&(s=t.getPose(e.gripSpace,n),s!==null&&(c.matrix.fromArray(s.transform.matrix),c.matrix.decompose(c.position,c.rotation,c.scale),c.matrixWorldNeedsUpdate=!0,s.linearVelocity?(c.hasLinearVelocity=!0,c.linearVelocity.copy(s.linearVelocity)):c.hasLinearVelocity=!1,s.angularVelocity?(c.hasAngularVelocity=!0,c.angularVelocity.copy(s.angularVelocity)):c.hasAngularVelocity=!1));a!==null&&(i=t.getPose(e.targetRaySpace,n),i===null&&s!==null&&(i=s),i!==null&&(a.matrix.fromArray(i.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,i.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(i.linearVelocity)):a.hasLinearVelocity=!1,i.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(i.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(f_)))}return a!==null&&(a.visible=i!==null),c!==null&&(c.visible=s!==null),l!==null&&(l.visible=o!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){let n=new mn;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}},Io=class r{constructor(e,t=25e-5){this.isFogExp2=!0,this.name="",this.color=new ue(e),this.density=t}clone(){return new r(this.color,this.density)}toJSON(){return{type:"FogExp2",name:this.name,color:this.color.getHex(),density:this.density}}},Po=class r{constructor(e,t=1,n=1e3){this.isFog=!0,this.name="",this.color=new ue(e),this.near=t,this.far=n}clone(){return new r(this.color,this.near,this.far)}toJSON(){return{type:"Fog",name:this.name,color:this.color.getHex(),near:this.near,far:this.far}}},Lo=class extends Qe{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new rn,this.environmentIntensity=1,this.environmentRotation=new rn,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){let t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}},Jn=class{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=e!==void 0?e.length/t:0,this.usage=mr,this.updateRanges=[],this.version=0,this.uuid=gn()}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,t,n){e*=this.stride,n*=t.stride;for(let i=0,s=this.stride;i<s;i++)this.array[e+i]=t.array[n+i];return this}set(e,t=0){return this.array.set(e,t),this}clone(e){e.arrayBuffers===void 0&&(e.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=gn()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=this.array.slice(0).buffer);let t=new this.array.constructor(e.arrayBuffers[this.array.buffer._uuid]),n=new this.constructor(t,this.stride);return n.setUsage(this.usage),n}onUpload(e){return this.onUploadCallback=e,this}toJSON(e){return e.arrayBuffers===void 0&&(e.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=gn()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=Array.from(new Uint32Array(this.array.buffer))),{uuid:this.uuid,buffer:this.array.buffer._uuid,type:this.array.constructor.name,stride:this.stride}}},Yt=new w,Bn=class r{constructor(e,t,n,i=!1){this.isInterleavedBufferAttribute=!0,this.name="",this.data=e,this.itemSize=t,this.offset=n,this.normalized=i}get count(){return this.data.count}get array(){return this.data.array}set needsUpdate(e){this.data.needsUpdate=e}applyMatrix4(e){for(let t=0,n=this.data.count;t<n;t++)Yt.fromBufferAttribute(this,t),Yt.applyMatrix4(e),this.setXYZ(t,Yt.x,Yt.y,Yt.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)Yt.fromBufferAttribute(this,t),Yt.applyNormalMatrix(e),this.setXYZ(t,Yt.x,Yt.y,Yt.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)Yt.fromBufferAttribute(this,t),Yt.transformDirection(e),this.setXYZ(t,Yt.x,Yt.y,Yt.z);return this}getComponent(e,t){let n=this.array[e*this.data.stride+this.offset+t];return this.normalized&&(n=Zt(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=Xe(n,this.array)),this.data.array[e*this.data.stride+this.offset+t]=n,this}setX(e,t){return this.normalized&&(t=Xe(t,this.array)),this.data.array[e*this.data.stride+this.offset]=t,this}setY(e,t){return this.normalized&&(t=Xe(t,this.array)),this.data.array[e*this.data.stride+this.offset+1]=t,this}setZ(e,t){return this.normalized&&(t=Xe(t,this.array)),this.data.array[e*this.data.stride+this.offset+2]=t,this}setW(e,t){return this.normalized&&(t=Xe(t,this.array)),this.data.array[e*this.data.stride+this.offset+3]=t,this}getX(e){let t=this.data.array[e*this.data.stride+this.offset];return this.normalized&&(t=Zt(t,this.array)),t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(t=Zt(t,this.array)),t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(t=Zt(t,this.array)),t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(t=Zt(t,this.array)),t}setXY(e,t,n){return e=e*this.data.stride+this.offset,this.normalized&&(t=Xe(t,this.array),n=Xe(n,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this}setXYZ(e,t,n,i){return e=e*this.data.stride+this.offset,this.normalized&&(t=Xe(t,this.array),n=Xe(n,this.array),i=Xe(i,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this.data.array[e+2]=i,this}setXYZW(e,t,n,i,s){return e=e*this.data.stride+this.offset,this.normalized&&(t=Xe(t,this.array),n=Xe(n,this.array),i=Xe(i,this.array),s=Xe(s,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this.data.array[e+2]=i,this.data.array[e+3]=s,this}clone(e){if(e===void 0){console.log("THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.");let t=[];for(let n=0;n<this.count;n++){let i=n*this.data.stride+this.offset;for(let s=0;s<this.itemSize;s++)t.push(this.data.array[i+s])}return new je(new this.array.constructor(t),this.itemSize,this.normalized)}else return e.interleavedBuffers===void 0&&(e.interleavedBuffers={}),e.interleavedBuffers[this.data.uuid]===void 0&&(e.interleavedBuffers[this.data.uuid]=this.data.clone(e)),new r(e.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(e){if(e===void 0){console.log("THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.");let t=[];for(let n=0;n<this.count;n++){let i=n*this.data.stride+this.offset;for(let s=0;s<this.itemSize;s++)t.push(this.data.array[i+s])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:t,normalized:this.normalized}}else return e.interleavedBuffers===void 0&&(e.interleavedBuffers={}),e.interleavedBuffers[this.data.uuid]===void 0&&(e.interleavedBuffers[this.data.uuid]=this.data.toJSON(e)),{isInterleavedBufferAttribute:!0,itemSize:this.itemSize,data:this.data.uuid,offset:this.offset,normalized:this.normalized}}},Mr=class extends Mt{constructor(e){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new ue(16777215),this.map=null,this.alphaMap=null,this.rotation=0,this.sizeAttenuation=!0,this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.rotation=e.rotation,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}},ir,ho=new w,sr=new w,rr=new w,or=new Y,uo=new Y,Dm=new De,Vc=new w,fo=new w,Hc=new w,ap=new Y,hu=new Y,cp=new Y,Do=class extends Qe{constructor(e=new Mr){if(super(),this.isSprite=!0,this.type="Sprite",ir===void 0){ir=new ze;let t=new Float32Array([-.5,-.5,0,0,0,.5,-.5,0,1,0,.5,.5,0,1,1,-.5,.5,0,0,1]),n=new Jn(t,5);ir.setIndex([0,1,2,0,2,3]),ir.setAttribute("position",new Bn(n,3,0,!1)),ir.setAttribute("uv",new Bn(n,2,3,!1))}this.geometry=ir,this.material=e,this.center=new Y(.5,.5),this.count=1}raycast(e,t){e.camera===null&&console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.'),sr.setFromMatrixScale(this.matrixWorld),Dm.copy(e.camera.matrixWorld),this.modelViewMatrix.multiplyMatrices(e.camera.matrixWorldInverse,this.matrixWorld),rr.setFromMatrixPosition(this.modelViewMatrix),e.camera.isPerspectiveCamera&&this.material.sizeAttenuation===!1&&sr.multiplyScalar(-rr.z);let n=this.material.rotation,i,s;n!==0&&(s=Math.cos(n),i=Math.sin(n));let o=this.center;Gc(Vc.set(-.5,-.5,0),rr,o,sr,i,s),Gc(fo.set(.5,-.5,0),rr,o,sr,i,s),Gc(Hc.set(.5,.5,0),rr,o,sr,i,s),ap.set(0,0),hu.set(1,0),cp.set(1,1);let a=e.ray.intersectTriangle(Vc,fo,Hc,!1,ho);if(a===null&&(Gc(fo.set(-.5,.5,0),rr,o,sr,i,s),hu.set(0,1),a=e.ray.intersectTriangle(Vc,Hc,fo,!1,ho),a===null))return;let c=e.ray.origin.distanceTo(ho);c<e.near||c>e.far||t.push({distance:c,point:ho.clone(),uv:Nn.getInterpolation(ho,Vc,fo,Hc,ap,hu,cp,new Y),face:null,object:this})}copy(e,t){return super.copy(e,t),e.center!==void 0&&this.center.copy(e.center),this.material=e.material,this}};function Gc(r,e,t,n,i,s){or.subVectors(r,t).addScalar(.5).multiply(n),i!==void 0?(uo.x=s*or.x-i*or.y,uo.y=i*or.x+s*or.y):uo.copy(or),r.copy(e),r.x+=uo.x,r.y+=uo.y,r.applyMatrix4(Dm)}var Wc=new w,lp=new w,No=class extends Qe{constructor(){super(),this.isLOD=!0,this._currentLevel=0,this.type="LOD",Object.defineProperties(this,{levels:{enumerable:!0,value:[]}}),this.autoUpdate=!0}copy(e){super.copy(e,!1);let t=e.levels;for(let n=0,i=t.length;n<i;n++){let s=t[n];this.addLevel(s.object.clone(),s.distance,s.hysteresis)}return this.autoUpdate=e.autoUpdate,this}addLevel(e,t=0,n=0){t=Math.abs(t);let i=this.levels,s;for(s=0;s<i.length&&!(t<i[s].distance);s++);return i.splice(s,0,{distance:t,hysteresis:n,object:e}),this.add(e),this}removeLevel(e){let t=this.levels;for(let n=0;n<t.length;n++)if(t[n].distance===e){let i=t.splice(n,1);return this.remove(i[0].object),!0}return!1}getCurrentLevel(){return this._currentLevel}getObjectForDistance(e){let t=this.levels;if(t.length>0){let n,i;for(n=1,i=t.length;n<i;n++){let s=t[n].distance;if(t[n].object.visible&&(s-=s*t[n].hysteresis),e<s)break}return t[n-1].object}return null}raycast(e,t){if(this.levels.length>0){Wc.setFromMatrixPosition(this.matrixWorld);let i=e.ray.origin.distanceTo(Wc);this.getObjectForDistance(i).raycast(e,t)}}update(e){let t=this.levels;if(t.length>1){Wc.setFromMatrixPosition(e.matrixWorld),lp.setFromMatrixPosition(this.matrixWorld);let n=Wc.distanceTo(lp)/e.zoom;t[0].object.visible=!0;let i,s;for(i=1,s=t.length;i<s;i++){let o=t[i].distance;if(t[i].object.visible&&(o-=o*t[i].hysteresis),n>=o)t[i-1].object.visible=!1,t[i].object.visible=!0;else break}for(this._currentLevel=i-1;i<s;i++)t[i].object.visible=!1}}toJSON(e){let t=super.toJSON(e);this.autoUpdate===!1&&(t.object.autoUpdate=!1),t.object.levels=[];let n=this.levels;for(let i=0,s=n.length;i<s;i++){let o=n[i];t.object.levels.push({object:o.object.uuid,distance:o.distance,hysteresis:o.hysteresis})}return t}},hp=new w,up=new tt,dp=new tt,p_=new w,fp=new De,Xc=new w,uu=new Et,pp=new De,du=new On,xs=class extends pt{constructor(e,t){super(e,t),this.isSkinnedMesh=!0,this.type="SkinnedMesh",this.bindMode=fl,this.bindMatrix=new De,this.bindMatrixInverse=new De,this.boundingBox=null,this.boundingSphere=null}computeBoundingBox(){let e=this.geometry;this.boundingBox===null&&(this.boundingBox=new Rt),this.boundingBox.makeEmpty();let t=e.getAttribute("position");for(let n=0;n<t.count;n++)this.getVertexPosition(n,Xc),this.boundingBox.expandByPoint(Xc)}computeBoundingSphere(){let e=this.geometry;this.boundingSphere===null&&(this.boundingSphere=new Et),this.boundingSphere.makeEmpty();let t=e.getAttribute("position");for(let n=0;n<t.count;n++)this.getVertexPosition(n,Xc),this.boundingSphere.expandByPoint(Xc)}copy(e,t){return super.copy(e,t),this.bindMode=e.bindMode,this.bindMatrix.copy(e.bindMatrix),this.bindMatrixInverse.copy(e.bindMatrixInverse),this.skeleton=e.skeleton,e.boundingBox!==null&&(this.boundingBox=e.boundingBox.clone()),e.boundingSphere!==null&&(this.boundingSphere=e.boundingSphere.clone()),this}raycast(e,t){let n=this.material,i=this.matrixWorld;n!==void 0&&(this.boundingSphere===null&&this.computeBoundingSphere(),uu.copy(this.boundingSphere),uu.applyMatrix4(i),e.ray.intersectsSphere(uu)!==!1&&(pp.copy(i).invert(),du.copy(e.ray).applyMatrix4(pp),!(this.boundingBox!==null&&du.intersectsBox(this.boundingBox)===!1)&&this._computeIntersections(e,t,du)))}getVertexPosition(e,t){return super.getVertexPosition(e,t),this.applyBoneTransform(e,t),t}bind(e,t){this.skeleton=e,t===void 0&&(this.updateMatrixWorld(!0),this.skeleton.calculateInverses(),t=this.matrixWorld),this.bindMatrix.copy(t),this.bindMatrixInverse.copy(t).invert()}pose(){this.skeleton.pose()}normalizeSkinWeights(){let e=new tt,t=this.geometry.attributes.skinWeight;for(let n=0,i=t.count;n<i;n++){e.fromBufferAttribute(t,n);let s=1/e.manhattanLength();s!==1/0?e.multiplyScalar(s):e.set(1,0,0,0),t.setXYZW(n,e.x,e.y,e.z,e.w)}}updateMatrixWorld(e){super.updateMatrixWorld(e),this.bindMode===fl?this.bindMatrixInverse.copy(this.matrixWorld).invert():this.bindMode===_d?this.bindMatrixInverse.copy(this.bindMatrix).invert():console.warn("THREE.SkinnedMesh: Unrecognized bindMode: "+this.bindMode)}applyBoneTransform(e,t){let n=this.skeleton,i=this.geometry;up.fromBufferAttribute(i.attributes.skinIndex,e),dp.fromBufferAttribute(i.attributes.skinWeight,e),hp.copy(t).applyMatrix4(this.bindMatrix),t.set(0,0,0);for(let s=0;s<4;s++){let o=dp.getComponent(s);if(o!==0){let a=up.getComponent(s);fp.multiplyMatrices(n.bones[a].matrixWorld,n.boneInverses[a]),t.addScaledVector(p_.copy(hp).applyMatrix4(fp),o)}}return t.applyMatrix4(this.bindMatrixInverse)}},Gi=class extends Qe{constructor(){super(),this.isBone=!0,this.type="Bone"}},_n=class extends gt{constructor(e=null,t=1,n=1,i,s,o,a,c,l=Ct,h=Ct,u,d){super(null,o,a,c,l,h,i,s,u,d),this.isDataTexture=!0,this.image={data:e,width:t,height:n},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}},mp=new De,m_=new De,ys=class r{constructor(e=[],t=[]){this.uuid=gn(),this.bones=e.slice(0),this.boneInverses=t,this.boneMatrices=null,this.boneTexture=null,this.init()}init(){let e=this.bones,t=this.boneInverses;if(this.boneMatrices=new Float32Array(e.length*16),t.length===0)this.calculateInverses();else if(e.length!==t.length){console.warn("THREE.Skeleton: Number of inverse bone matrices does not match amount of bones."),this.boneInverses=[];for(let n=0,i=this.bones.length;n<i;n++)this.boneInverses.push(new De)}}calculateInverses(){this.boneInverses.length=0;for(let e=0,t=this.bones.length;e<t;e++){let n=new De;this.bones[e]&&n.copy(this.bones[e].matrixWorld).invert(),this.boneInverses.push(n)}}pose(){for(let e=0,t=this.bones.length;e<t;e++){let n=this.bones[e];n&&n.matrixWorld.copy(this.boneInverses[e]).invert()}for(let e=0,t=this.bones.length;e<t;e++){let n=this.bones[e];n&&(n.parent&&n.parent.isBone?(n.matrix.copy(n.parent.matrixWorld).invert(),n.matrix.multiply(n.matrixWorld)):n.matrix.copy(n.matrixWorld),n.matrix.decompose(n.position,n.quaternion,n.scale))}}update(){let e=this.bones,t=this.boneInverses,n=this.boneMatrices,i=this.boneTexture;for(let s=0,o=e.length;s<o;s++){let a=e[s]?e[s].matrixWorld:m_;mp.multiplyMatrices(a,t[s]),mp.toArray(n,s*16)}i!==null&&(i.needsUpdate=!0)}clone(){return new r(this.bones,this.boneInverses)}computeBoneTexture(){let e=Math.sqrt(this.bones.length*4);e=Math.ceil(e/4)*4,e=Math.max(e,4);let t=new Float32Array(e*e*4);t.set(this.boneMatrices);let n=new _n(t,e,e,Ht,Jt);return n.needsUpdate=!0,this.boneMatrices=t,this.boneTexture=n,this}getBoneByName(e){for(let t=0,n=this.bones.length;t<n;t++){let i=this.bones[t];if(i.name===e)return i}}dispose(){this.boneTexture!==null&&(this.boneTexture.dispose(),this.boneTexture=null)}fromJSON(e,t){this.uuid=e.uuid;for(let n=0,i=e.bones.length;n<i;n++){let s=e.bones[n],o=t[s];o===void 0&&(console.warn("THREE.Skeleton: No bone found with UUID:",s),o=new Gi),this.bones.push(o),this.boneInverses.push(new De().fromArray(e.boneInverses[n]))}return this.init(),this}toJSON(){let e={metadata:{version:4.7,type:"Skeleton",generator:"Skeleton.toJSON"},bones:[],boneInverses:[]};e.uuid=this.uuid;let t=this.bones,n=this.boneInverses;for(let i=0,s=t.length;i<s;i++){let o=t[i];e.bones.push(o.uuid);let a=n[i];e.boneInverses.push(a.toArray())}return e}},wn=class extends je{constructor(e,t,n,i=1){super(e,t,n),this.isInstancedBufferAttribute=!0,this.meshPerAttribute=i}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}toJSON(){let e=super.toJSON();return e.meshPerAttribute=this.meshPerAttribute,e.isInstancedBufferAttribute=!0,e}},ar=new De,gp=new De,qc=[],_p=new Rt,g_=new De,po=new pt,mo=new Et,vs=class extends pt{constructor(e,t,n){super(e,t),this.isInstancedMesh=!0,this.instanceMatrix=new wn(new Float32Array(n*16),16),this.instanceColor=null,this.morphTexture=null,this.count=n,this.boundingBox=null,this.boundingSphere=null;for(let i=0;i<n;i++)this.setMatrixAt(i,g_)}computeBoundingBox(){let e=this.geometry,t=this.count;this.boundingBox===null&&(this.boundingBox=new Rt),e.boundingBox===null&&e.computeBoundingBox(),this.boundingBox.makeEmpty();for(let n=0;n<t;n++)this.getMatrixAt(n,ar),_p.copy(e.boundingBox).applyMatrix4(ar),this.boundingBox.union(_p)}computeBoundingSphere(){let e=this.geometry,t=this.count;this.boundingSphere===null&&(this.boundingSphere=new Et),e.boundingSphere===null&&e.computeBoundingSphere(),this.boundingSphere.makeEmpty();for(let n=0;n<t;n++)this.getMatrixAt(n,ar),mo.copy(e.boundingSphere).applyMatrix4(ar),this.boundingSphere.union(mo)}copy(e,t){return super.copy(e,t),this.instanceMatrix.copy(e.instanceMatrix),e.morphTexture!==null&&(this.morphTexture=e.morphTexture.clone()),e.instanceColor!==null&&(this.instanceColor=e.instanceColor.clone()),this.count=e.count,e.boundingBox!==null&&(this.boundingBox=e.boundingBox.clone()),e.boundingSphere!==null&&(this.boundingSphere=e.boundingSphere.clone()),this}getColorAt(e,t){t.fromArray(this.instanceColor.array,e*3)}getMatrixAt(e,t){t.fromArray(this.instanceMatrix.array,e*16)}getMorphAt(e,t){let n=t.morphTargetInfluences,i=this.morphTexture.source.data.data,s=n.length+1,o=e*s+1;for(let a=0;a<n.length;a++)n[a]=i[o+a]}raycast(e,t){let n=this.matrixWorld,i=this.count;if(po.geometry=this.geometry,po.material=this.material,po.material!==void 0&&(this.boundingSphere===null&&this.computeBoundingSphere(),mo.copy(this.boundingSphere),mo.applyMatrix4(n),e.ray.intersectsSphere(mo)!==!1))for(let s=0;s<i;s++){this.getMatrixAt(s,ar),gp.multiplyMatrices(n,ar),po.matrixWorld=gp,po.raycast(e,qc);for(let o=0,a=qc.length;o<a;o++){let c=qc[o];c.instanceId=s,c.object=this,t.push(c)}qc.length=0}}setColorAt(e,t){this.instanceColor===null&&(this.instanceColor=new wn(new Float32Array(this.instanceMatrix.count*3).fill(1),3)),t.toArray(this.instanceColor.array,e*3)}setMatrixAt(e,t){t.toArray(this.instanceMatrix.array,e*16)}setMorphAt(e,t){let n=t.morphTargetInfluences,i=n.length+1;this.morphTexture===null&&(this.morphTexture=new _n(new Float32Array(i*this.count),i,this.count,Ha,Jt));let s=this.morphTexture.source.data.data,o=0;for(let l=0;l<n.length;l++)o+=n[l];let a=this.geometry.morphTargetsRelative?1:1-o,c=i*e;s[c]=a,s.set(n,c+1)}updateMorphTargets(){}dispose(){this.dispatchEvent({type:"dispose"}),this.morphTexture!==null&&(this.morphTexture.dispose(),this.morphTexture=null)}},fu=new w,__=new w,x_=new Ve,pn=class{constructor(e=new w(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,n,i){return this.normal.set(e,t,n),this.constant=i,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,n){let i=fu.subVectors(n,t).cross(__.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(i,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){let e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t){let n=e.delta(fu),i=this.normal.dot(n);if(i===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;let s=-(e.start.dot(this.normal)+this.constant)/i;return s<0||s>1?null:t.copy(e.start).addScaledVector(n,s)}intersectsLine(e){let t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){let n=t||x_.getNormalMatrix(e),i=this.coplanarPoint(fu).applyMatrix4(e),s=this.normal.applyMatrix3(n).normalize();return this.constant=-i.dot(s),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}},Qi=new Et,y_=new Y(.5,.5),Yc=new w,_i=class{constructor(e=new pn,t=new pn,n=new pn,i=new pn,s=new pn,o=new pn){this.planes=[e,t,n,i,s,o]}set(e,t,n,i,s,o){let a=this.planes;return a[0].copy(e),a[1].copy(t),a[2].copy(n),a[3].copy(i),a[4].copy(s),a[5].copy(o),this}copy(e){let t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=sn,n=!1){let i=this.planes,s=e.elements,o=s[0],a=s[1],c=s[2],l=s[3],h=s[4],u=s[5],d=s[6],f=s[7],m=s[8],_=s[9],g=s[10],p=s[11],v=s[12],y=s[13],x=s[14],A=s[15];if(i[0].setComponents(l-o,f-h,p-m,A-v).normalize(),i[1].setComponents(l+o,f+h,p+m,A+v).normalize(),i[2].setComponents(l+a,f+u,p+_,A+y).normalize(),i[3].setComponents(l-a,f-u,p-_,A-y).normalize(),n)i[4].setComponents(c,d,g,x).normalize(),i[5].setComponents(l-c,f-d,p-g,A-x).normalize();else if(i[4].setComponents(l-c,f-d,p-g,A-x).normalize(),t===sn)i[5].setComponents(l+c,f+d,p+g,A+x).normalize();else if(t===us)i[5].setComponents(c,d,g,x).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),Qi.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{let t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),Qi.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Qi)}intersectsSprite(e){Qi.center.set(0,0,0);let t=y_.distanceTo(e.center);return Qi.radius=.7071067811865476+t,Qi.applyMatrix4(e.matrixWorld),this.intersectsSphere(Qi)}intersectsSphere(e){let t=this.planes,n=e.center,i=-e.radius;for(let s=0;s<6;s++)if(t[s].distanceToPoint(n)<i)return!1;return!0}intersectsBox(e){let t=this.planes;for(let n=0;n<6;n++){let i=t[n];if(Yc.x=i.normal.x>0?e.max.x:e.min.x,Yc.y=i.normal.y>0?e.max.y:e.min.y,Yc.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(Yc)<0)return!1}return!0}containsPoint(e){let t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}},qn=new De,Yn=new _i,Uo=class r{constructor(){this.coordinateSystem=sn}intersectsObject(e,t){if(!t.isArrayCamera||t.cameras.length===0)return!1;for(let n=0;n<t.cameras.length;n++){let i=t.cameras[n];if(qn.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),Yn.setFromProjectionMatrix(qn,i.coordinateSystem,i.reversedDepth),Yn.intersectsObject(e))return!0}return!1}intersectsSprite(e,t){if(!t||!t.cameras||t.cameras.length===0)return!1;for(let n=0;n<t.cameras.length;n++){let i=t.cameras[n];if(qn.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),Yn.setFromProjectionMatrix(qn,i.coordinateSystem,i.reversedDepth),Yn.intersectsSprite(e))return!0}return!1}intersectsSphere(e,t){if(!t||!t.cameras||t.cameras.length===0)return!1;for(let n=0;n<t.cameras.length;n++){let i=t.cameras[n];if(qn.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),Yn.setFromProjectionMatrix(qn,i.coordinateSystem,i.reversedDepth),Yn.intersectsSphere(e))return!0}return!1}intersectsBox(e,t){if(!t||!t.cameras||t.cameras.length===0)return!1;for(let n=0;n<t.cameras.length;n++){let i=t.cameras[n];if(qn.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),Yn.setFromProjectionMatrix(qn,i.coordinateSystem,i.reversedDepth),Yn.intersectsBox(e))return!0}return!1}containsPoint(e,t){if(!t||!t.cameras||t.cameras.length===0)return!1;for(let n=0;n<t.cameras.length;n++){let i=t.cameras[n];if(qn.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),Yn.setFromProjectionMatrix(qn,i.coordinateSystem,i.reversedDepth),Yn.containsPoint(e))return!0}return!1}clone(){return new r}};function pu(r,e){return r-e}function v_(r,e){return r.z-e.z}function M_(r,e){return e.z-r.z}var Ru=class{constructor(){this.index=0,this.pool=[],this.list=[]}push(e,t,n,i){let s=this.pool,o=this.list;this.index>=s.length&&s.push({start:-1,count:-1,z:-1,index:-1});let a=s[this.index];o.push(a),this.index++,a.start=e,a.count=t,a.z=n,a.index=i}reset(){this.list.length=0,this.index=0}},tn=new De,S_=new ue(1,1,1),xp=new _i,b_=new Uo,Zc=new Rt,es=new Et,go=new w,yp=new w,T_=new w,mu=new Ru,Vt=new pt,Kc=[];function E_(r,e,t=0){let n=e.itemSize;if(r.isInterleavedBufferAttribute||r.array.constructor!==e.array.constructor){let i=r.count;for(let s=0;s<i;s++)for(let o=0;o<n;o++)e.setComponent(s+t,o,r.getComponent(s,o))}else e.array.set(r.array,t*n);e.needsUpdate=!0}function ts(r,e){if(r.constructor!==e.constructor){let t=Math.min(r.length,e.length);for(let n=0;n<t;n++)e[n]=r[n]}else{let t=Math.min(r.length,e.length);e.set(new r.constructor(r.buffer,0,t))}}var Fo=class extends pt{constructor(e,t,n=t*2,i){super(new ze,i),this.isBatchedMesh=!0,this.perObjectFrustumCulled=!0,this.sortObjects=!0,this.boundingBox=null,this.boundingSphere=null,this.customSort=null,this._instanceInfo=[],this._geometryInfo=[],this._availableInstanceIds=[],this._availableGeometryIds=[],this._nextIndexStart=0,this._nextVertexStart=0,this._geometryCount=0,this._visibilityChanged=!0,this._geometryInitialized=!1,this._maxInstanceCount=e,this._maxVertexCount=t,this._maxIndexCount=n,this._multiDrawCounts=new Int32Array(e),this._multiDrawStarts=new Int32Array(e),this._multiDrawCount=0,this._multiDrawInstances=null,this._matricesTexture=null,this._indirectTexture=null,this._colorsTexture=null,this._initMatricesTexture(),this._initIndirectTexture()}get maxInstanceCount(){return this._maxInstanceCount}get instanceCount(){return this._instanceInfo.length-this._availableInstanceIds.length}get unusedVertexCount(){return this._maxVertexCount-this._nextVertexStart}get unusedIndexCount(){return this._maxIndexCount-this._nextIndexStart}_initMatricesTexture(){let e=Math.sqrt(this._maxInstanceCount*4);e=Math.ceil(e/4)*4,e=Math.max(e,4);let t=new Float32Array(e*e*4),n=new _n(t,e,e,Ht,Jt);this._matricesTexture=n}_initIndirectTexture(){let e=Math.sqrt(this._maxInstanceCount);e=Math.ceil(e);let t=new Uint32Array(e*e),n=new _n(t,e,e,Yr,si);this._indirectTexture=n}_initColorsTexture(){let e=Math.sqrt(this._maxInstanceCount);e=Math.ceil(e);let t=new Float32Array(e*e*4).fill(1),n=new _n(t,e,e,Ht,Jt);n.colorSpace=Ze.workingColorSpace,this._colorsTexture=n}_initializeGeometry(e){let t=this.geometry,n=this._maxVertexCount,i=this._maxIndexCount;if(this._geometryInitialized===!1){for(let s in e.attributes){let o=e.getAttribute(s),{array:a,itemSize:c,normalized:l}=o,h=new a.constructor(n*c),u=new je(h,c,l);t.setAttribute(s,u)}if(e.getIndex()!==null){let s=n>65535?new Uint32Array(i):new Uint16Array(i);t.setIndex(new je(s,1))}this._geometryInitialized=!0}}_validateGeometry(e){let t=this.geometry;if(!!e.getIndex()!=!!t.getIndex())throw new Error('THREE.BatchedMesh: All geometries must consistently have "index".');for(let n in t.attributes){if(!e.hasAttribute(n))throw new Error(`THREE.BatchedMesh: Added geometry missing "${n}". All geometries must have consistent attributes.`);let i=e.getAttribute(n),s=t.getAttribute(n);if(i.itemSize!==s.itemSize||i.normalized!==s.normalized)throw new Error("THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.")}}validateInstanceId(e){let t=this._instanceInfo;if(e<0||e>=t.length||t[e].active===!1)throw new Error(`THREE.BatchedMesh: Invalid instanceId ${e}. Instance is either out of range or has been deleted.`)}validateGeometryId(e){let t=this._geometryInfo;if(e<0||e>=t.length||t[e].active===!1)throw new Error(`THREE.BatchedMesh: Invalid geometryId ${e}. Geometry is either out of range or has been deleted.`)}setCustomSort(e){return this.customSort=e,this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Rt);let e=this.boundingBox,t=this._instanceInfo;e.makeEmpty();for(let n=0,i=t.length;n<i;n++){if(t[n].active===!1)continue;let s=t[n].geometryIndex;this.getMatrixAt(n,tn),this.getBoundingBoxAt(s,Zc).applyMatrix4(tn),e.union(Zc)}}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new Et);let e=this.boundingSphere,t=this._instanceInfo;e.makeEmpty();for(let n=0,i=t.length;n<i;n++){if(t[n].active===!1)continue;let s=t[n].geometryIndex;this.getMatrixAt(n,tn),this.getBoundingSphereAt(s,es).applyMatrix4(tn),e.union(es)}}addInstance(e){if(this._instanceInfo.length>=this.maxInstanceCount&&this._availableInstanceIds.length===0)throw new Error("THREE.BatchedMesh: Maximum item count reached.");let n={visible:!0,active:!0,geometryIndex:e},i=null;this._availableInstanceIds.length>0?(this._availableInstanceIds.sort(pu),i=this._availableInstanceIds.shift(),this._instanceInfo[i]=n):(i=this._instanceInfo.length,this._instanceInfo.push(n));let s=this._matricesTexture;tn.identity().toArray(s.image.data,i*16),s.needsUpdate=!0;let o=this._colorsTexture;return o&&(S_.toArray(o.image.data,i*4),o.needsUpdate=!0),this._visibilityChanged=!0,i}addGeometry(e,t=-1,n=-1){this._initializeGeometry(e),this._validateGeometry(e);let i={vertexStart:-1,vertexCount:-1,reservedVertexCount:-1,indexStart:-1,indexCount:-1,reservedIndexCount:-1,start:-1,count:-1,boundingBox:null,boundingSphere:null,active:!0},s=this._geometryInfo;i.vertexStart=this._nextVertexStart,i.reservedVertexCount=t===-1?e.getAttribute("position").count:t;let o=e.getIndex();if(o!==null&&(i.indexStart=this._nextIndexStart,i.reservedIndexCount=n===-1?o.count:n),i.indexStart!==-1&&i.indexStart+i.reservedIndexCount>this._maxIndexCount||i.vertexStart+i.reservedVertexCount>this._maxVertexCount)throw new Error("THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.");let c;return this._availableGeometryIds.length>0?(this._availableGeometryIds.sort(pu),c=this._availableGeometryIds.shift(),s[c]=i):(c=this._geometryCount,this._geometryCount++,s.push(i)),this.setGeometryAt(c,e),this._nextIndexStart=i.indexStart+i.reservedIndexCount,this._nextVertexStart=i.vertexStart+i.reservedVertexCount,c}setGeometryAt(e,t){if(e>=this._geometryCount)throw new Error("THREE.BatchedMesh: Maximum geometry count reached.");this._validateGeometry(t);let n=this.geometry,i=n.getIndex()!==null,s=n.getIndex(),o=t.getIndex(),a=this._geometryInfo[e];if(i&&o.count>a.reservedIndexCount||t.attributes.position.count>a.reservedVertexCount)throw new Error("THREE.BatchedMesh: Reserved space not large enough for provided geometry.");let c=a.vertexStart,l=a.reservedVertexCount;a.vertexCount=t.getAttribute("position").count;for(let h in n.attributes){let u=t.getAttribute(h),d=n.getAttribute(h);E_(u,d,c);let f=u.itemSize;for(let m=u.count,_=l;m<_;m++){let g=c+m;for(let p=0;p<f;p++)d.setComponent(g,p,0)}d.needsUpdate=!0,d.addUpdateRange(c*f,l*f)}if(i){let h=a.indexStart,u=a.reservedIndexCount;a.indexCount=t.getIndex().count;for(let d=0;d<o.count;d++)s.setX(h+d,c+o.getX(d));for(let d=o.count,f=u;d<f;d++)s.setX(h+d,c);s.needsUpdate=!0,s.addUpdateRange(h,a.reservedIndexCount)}return a.start=i?a.indexStart:a.vertexStart,a.count=i?a.indexCount:a.vertexCount,a.boundingBox=null,t.boundingBox!==null&&(a.boundingBox=t.boundingBox.clone()),a.boundingSphere=null,t.boundingSphere!==null&&(a.boundingSphere=t.boundingSphere.clone()),this._visibilityChanged=!0,e}deleteGeometry(e){let t=this._geometryInfo;if(e>=t.length||t[e].active===!1)return this;let n=this._instanceInfo;for(let i=0,s=n.length;i<s;i++)n[i].active&&n[i].geometryIndex===e&&this.deleteInstance(i);return t[e].active=!1,this._availableGeometryIds.push(e),this._visibilityChanged=!0,this}deleteInstance(e){return this.validateInstanceId(e),this._instanceInfo[e].active=!1,this._availableInstanceIds.push(e),this._visibilityChanged=!0,this}optimize(){let e=0,t=0,n=this._geometryInfo,i=n.map((o,a)=>a).sort((o,a)=>n[o].vertexStart-n[a].vertexStart),s=this.geometry;for(let o=0,a=n.length;o<a;o++){let c=i[o],l=n[c];if(l.active!==!1){if(s.index!==null){if(l.indexStart!==t){let{indexStart:h,vertexStart:u,reservedIndexCount:d}=l,f=s.index,m=f.array,_=e-u;for(let g=h;g<h+d;g++)m[g]=m[g]+_;f.array.copyWithin(t,h,h+d),f.addUpdateRange(t,d),l.indexStart=t}t+=l.reservedIndexCount}if(l.vertexStart!==e){let{vertexStart:h,reservedVertexCount:u}=l,d=s.attributes;for(let f in d){let m=d[f],{array:_,itemSize:g}=m;_.copyWithin(e*g,h*g,(h+u)*g),m.addUpdateRange(e*g,u*g)}l.vertexStart=e}e+=l.reservedVertexCount,l.start=s.index?l.indexStart:l.vertexStart,this._nextIndexStart=s.index?l.indexStart+l.reservedIndexCount:0,this._nextVertexStart=l.vertexStart+l.reservedVertexCount}}return this}getBoundingBoxAt(e,t){if(e>=this._geometryCount)return null;let n=this.geometry,i=this._geometryInfo[e];if(i.boundingBox===null){let s=new Rt,o=n.index,a=n.attributes.position;for(let c=i.start,l=i.start+i.count;c<l;c++){let h=c;o&&(h=o.getX(h)),s.expandByPoint(go.fromBufferAttribute(a,h))}i.boundingBox=s}return t.copy(i.boundingBox),t}getBoundingSphereAt(e,t){if(e>=this._geometryCount)return null;let n=this.geometry,i=this._geometryInfo[e];if(i.boundingSphere===null){let s=new Et;this.getBoundingBoxAt(e,Zc),Zc.getCenter(s.center);let o=n.index,a=n.attributes.position,c=0;for(let l=i.start,h=i.start+i.count;l<h;l++){let u=l;o&&(u=o.getX(u)),go.fromBufferAttribute(a,u),c=Math.max(c,s.center.distanceToSquared(go))}s.radius=Math.sqrt(c),i.boundingSphere=s}return t.copy(i.boundingSphere),t}setMatrixAt(e,t){this.validateInstanceId(e);let n=this._matricesTexture,i=this._matricesTexture.image.data;return t.toArray(i,e*16),n.needsUpdate=!0,this}getMatrixAt(e,t){return this.validateInstanceId(e),t.fromArray(this._matricesTexture.image.data,e*16)}setColorAt(e,t){return this.validateInstanceId(e),this._colorsTexture===null&&this._initColorsTexture(),t.toArray(this._colorsTexture.image.data,e*4),this._colorsTexture.needsUpdate=!0,this}getColorAt(e,t){return this.validateInstanceId(e),t.fromArray(this._colorsTexture.image.data,e*4)}setVisibleAt(e,t){return this.validateInstanceId(e),this._instanceInfo[e].visible===t?this:(this._instanceInfo[e].visible=t,this._visibilityChanged=!0,this)}getVisibleAt(e){return this.validateInstanceId(e),this._instanceInfo[e].visible}setGeometryIdAt(e,t){return this.validateInstanceId(e),this.validateGeometryId(t),this._instanceInfo[e].geometryIndex=t,this}getGeometryIdAt(e){return this.validateInstanceId(e),this._instanceInfo[e].geometryIndex}getGeometryRangeAt(e,t={}){this.validateGeometryId(e);let n=this._geometryInfo[e];return t.vertexStart=n.vertexStart,t.vertexCount=n.vertexCount,t.reservedVertexCount=n.reservedVertexCount,t.indexStart=n.indexStart,t.indexCount=n.indexCount,t.reservedIndexCount=n.reservedIndexCount,t.start=n.start,t.count=n.count,t}setInstanceCount(e){let t=this._availableInstanceIds,n=this._instanceInfo;for(t.sort(pu);t[t.length-1]===n.length-1;)n.pop(),t.pop();if(e<n.length)throw new Error(`BatchedMesh: Instance ids outside the range ${e} are being used. Cannot shrink instance count.`);let i=new Int32Array(e),s=new Int32Array(e);ts(this._multiDrawCounts,i),ts(this._multiDrawStarts,s),this._multiDrawCounts=i,this._multiDrawStarts=s,this._maxInstanceCount=e;let o=this._indirectTexture,a=this._matricesTexture,c=this._colorsTexture;o.dispose(),this._initIndirectTexture(),ts(o.image.data,this._indirectTexture.image.data),a.dispose(),this._initMatricesTexture(),ts(a.image.data,this._matricesTexture.image.data),c&&(c.dispose(),this._initColorsTexture(),ts(c.image.data,this._colorsTexture.image.data))}setGeometrySize(e,t){let n=[...this._geometryInfo].filter(a=>a.active);if(Math.max(...n.map(a=>a.vertexStart+a.reservedVertexCount))>e)throw new Error(`BatchedMesh: Geometry vertex values are being used outside the range ${t}. Cannot shrink further.`);if(this.geometry.index&&Math.max(...n.map(c=>c.indexStart+c.reservedIndexCount))>t)throw new Error(`BatchedMesh: Geometry index values are being used outside the range ${t}. Cannot shrink further.`);let s=this.geometry;s.dispose(),this._maxVertexCount=e,this._maxIndexCount=t,this._geometryInitialized&&(this._geometryInitialized=!1,this.geometry=new ze,this._initializeGeometry(s));let o=this.geometry;s.index&&ts(s.index.array,o.index.array);for(let a in s.attributes)ts(s.attributes[a].array,o.attributes[a].array)}raycast(e,t){let n=this._instanceInfo,i=this._geometryInfo,s=this.matrixWorld,o=this.geometry;Vt.material=this.material,Vt.geometry.index=o.index,Vt.geometry.attributes=o.attributes,Vt.geometry.boundingBox===null&&(Vt.geometry.boundingBox=new Rt),Vt.geometry.boundingSphere===null&&(Vt.geometry.boundingSphere=new Et);for(let a=0,c=n.length;a<c;a++){if(!n[a].visible||!n[a].active)continue;let l=n[a].geometryIndex,h=i[l];Vt.geometry.setDrawRange(h.start,h.count),this.getMatrixAt(a,Vt.matrixWorld).premultiply(s),this.getBoundingBoxAt(l,Vt.geometry.boundingBox),this.getBoundingSphereAt(l,Vt.geometry.boundingSphere),Vt.raycast(e,Kc);for(let u=0,d=Kc.length;u<d;u++){let f=Kc[u];f.object=this,f.batchId=a,t.push(f)}Kc.length=0}Vt.material=null,Vt.geometry.index=null,Vt.geometry.attributes={},Vt.geometry.setDrawRange(0,1/0)}copy(e){return super.copy(e),this.geometry=e.geometry.clone(),this.perObjectFrustumCulled=e.perObjectFrustumCulled,this.sortObjects=e.sortObjects,this.boundingBox=e.boundingBox!==null?e.boundingBox.clone():null,this.boundingSphere=e.boundingSphere!==null?e.boundingSphere.clone():null,this._geometryInfo=e._geometryInfo.map(t=>({...t,boundingBox:t.boundingBox!==null?t.boundingBox.clone():null,boundingSphere:t.boundingSphere!==null?t.boundingSphere.clone():null})),this._instanceInfo=e._instanceInfo.map(t=>({...t})),this._availableInstanceIds=e._availableInstanceIds.slice(),this._availableGeometryIds=e._availableGeometryIds.slice(),this._nextIndexStart=e._nextIndexStart,this._nextVertexStart=e._nextVertexStart,this._geometryCount=e._geometryCount,this._maxInstanceCount=e._maxInstanceCount,this._maxVertexCount=e._maxVertexCount,this._maxIndexCount=e._maxIndexCount,this._geometryInitialized=e._geometryInitialized,this._multiDrawCounts=e._multiDrawCounts.slice(),this._multiDrawStarts=e._multiDrawStarts.slice(),this._indirectTexture=e._indirectTexture.clone(),this._indirectTexture.image.data=this._indirectTexture.image.data.slice(),this._matricesTexture=e._matricesTexture.clone(),this._matricesTexture.image.data=this._matricesTexture.image.data.slice(),this._colorsTexture!==null&&(this._colorsTexture=e._colorsTexture.clone(),this._colorsTexture.image.data=this._colorsTexture.image.data.slice()),this}dispose(){this.geometry.dispose(),this._matricesTexture.dispose(),this._matricesTexture=null,this._indirectTexture.dispose(),this._indirectTexture=null,this._colorsTexture!==null&&(this._colorsTexture.dispose(),this._colorsTexture=null)}onBeforeRender(e,t,n,i,s){if(!this._visibilityChanged&&!this.perObjectFrustumCulled&&!this.sortObjects)return;let o=i.getIndex(),a=o===null?1:o.array.BYTES_PER_ELEMENT,c=this._instanceInfo,l=this._multiDrawStarts,h=this._multiDrawCounts,u=this._geometryInfo,d=this.perObjectFrustumCulled,f=this._indirectTexture,m=f.image.data,_=n.isArrayCamera?b_:xp;d&&!n.isArrayCamera&&(tn.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse).multiply(this.matrixWorld),xp.setFromProjectionMatrix(tn,n.coordinateSystem,n.reversedDepth));let g=0;if(this.sortObjects){tn.copy(this.matrixWorld).invert(),go.setFromMatrixPosition(n.matrixWorld).applyMatrix4(tn),yp.set(0,0,-1).transformDirection(n.matrixWorld).transformDirection(tn);for(let y=0,x=c.length;y<x;y++)if(c[y].visible&&c[y].active){let A=c[y].geometryIndex;this.getMatrixAt(y,tn),this.getBoundingSphereAt(A,es).applyMatrix4(tn);let E=!1;if(d&&(E=!_.intersectsSphere(es,n)),!E){let C=u[A],I=T_.subVectors(es.center,go).dot(yp);mu.push(C.start,C.count,I,y)}}let p=mu.list,v=this.customSort;v===null?p.sort(s.transparent?M_:v_):v.call(this,p,n);for(let y=0,x=p.length;y<x;y++){let A=p[y];l[g]=A.start*a,h[g]=A.count,m[g]=A.index,g++}mu.reset()}else for(let p=0,v=c.length;p<v;p++)if(c[p].visible&&c[p].active){let y=c[p].geometryIndex,x=!1;if(d&&(this.getMatrixAt(p,tn),this.getBoundingSphereAt(y,es).applyMatrix4(tn),x=!_.intersectsSphere(es,n)),!x){let A=u[y];l[g]=A.start*a,h[g]=A.count,m[g]=p,g++}}f.needsUpdate=!0,this._multiDrawCount=g,this._visibilityChanged=!1}onBeforeShadow(e,t,n,i,s,o){this.onBeforeRender(e,null,i,s,o)}},Pt=class extends Mt{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new ue(16777215),this.map=null,this.linewidth=1,this.linecap="round",this.linejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.linewidth=e.linewidth,this.linecap=e.linecap,this.linejoin=e.linejoin,this.fog=e.fog,this}},Tl=new w,El=new w,vp=new De,_o=new On,Jc=new Et,gu=new w,Mp=new w,vn=class extends Qe{constructor(e=new ze,t=new Pt){super(),this.isLine=!0,this.type="Line",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}computeLineDistances(){let e=this.geometry;if(e.index===null){let t=e.attributes.position,n=[0];for(let i=1,s=t.count;i<s;i++)Tl.fromBufferAttribute(t,i-1),El.fromBufferAttribute(t,i),n[i]=n[i-1],n[i]+=Tl.distanceTo(El);e.setAttribute("lineDistance",new ye(n,1))}else console.warn("THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}raycast(e,t){let n=this.geometry,i=this.matrixWorld,s=e.params.Line.threshold,o=n.drawRange;if(n.boundingSphere===null&&n.computeBoundingSphere(),Jc.copy(n.boundingSphere),Jc.applyMatrix4(i),Jc.radius+=s,e.ray.intersectsSphere(Jc)===!1)return;vp.copy(i).invert(),_o.copy(e.ray).applyMatrix4(vp);let a=s/((this.scale.x+this.scale.y+this.scale.z)/3),c=a*a,l=this.isLineSegments?2:1,h=n.index,d=n.attributes.position;if(h!==null){let f=Math.max(0,o.start),m=Math.min(h.count,o.start+o.count);for(let _=f,g=m-1;_<g;_+=l){let p=h.getX(_),v=h.getX(_+1),y=$c(this,e,_o,c,p,v,_);y&&t.push(y)}if(this.isLineLoop){let _=h.getX(m-1),g=h.getX(f),p=$c(this,e,_o,c,_,g,m-1);p&&t.push(p)}}else{let f=Math.max(0,o.start),m=Math.min(d.count,o.start+o.count);for(let _=f,g=m-1;_<g;_+=l){let p=$c(this,e,_o,c,_,_+1,_);p&&t.push(p)}if(this.isLineLoop){let _=$c(this,e,_o,c,m-1,f,m-1);_&&t.push(_)}}}updateMorphTargets(){let t=this.geometry.morphAttributes,n=Object.keys(t);if(n.length>0){let i=t[n[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,o=i.length;s<o;s++){let a=i[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=s}}}}};function $c(r,e,t,n,i,s,o){let a=r.geometry.attributes.position;if(Tl.fromBufferAttribute(a,i),El.fromBufferAttribute(a,s),t.distanceSqToSegment(Tl,El,gu,Mp)>n)return;gu.applyMatrix4(r.matrixWorld);let l=e.ray.origin.distanceTo(gu);if(!(l<e.near||l>e.far))return{distance:l,point:Mp.clone().applyMatrix4(r.matrixWorld),index:o,face:null,faceIndex:null,barycoord:null,object:r}}var Sp=new w,bp=new w,$t=class extends vn{constructor(e,t){super(e,t),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){let e=this.geometry;if(e.index===null){let t=e.attributes.position,n=[];for(let i=0,s=t.count;i<s;i+=2)Sp.fromBufferAttribute(t,i),bp.fromBufferAttribute(t,i+1),n[i]=i===0?0:n[i-1],n[i+1]=n[i]+Sp.distanceTo(bp);e.setAttribute("lineDistance",new ye(n,1))}else console.warn("THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}},Ms=class extends vn{constructor(e,t){super(e,t),this.isLineLoop=!0,this.type="LineLoop"}},Wi=class extends Mt{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new ue(16777215),this.map=null,this.alphaMap=null,this.size=1,this.sizeAttenuation=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.size=e.size,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}},Tp=new De,Cu=new On,jc=new Et,Qc=new w,Ss=class extends Qe{constructor(e=new ze,t=new Wi){super(),this.isPoints=!0,this.type="Points",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}raycast(e,t){let n=this.geometry,i=this.matrixWorld,s=e.params.Points.threshold,o=n.drawRange;if(n.boundingSphere===null&&n.computeBoundingSphere(),jc.copy(n.boundingSphere),jc.applyMatrix4(i),jc.radius+=s,e.ray.intersectsSphere(jc)===!1)return;Tp.copy(i).invert(),Cu.copy(e.ray).applyMatrix4(Tp);let a=s/((this.scale.x+this.scale.y+this.scale.z)/3),c=a*a,l=n.index,u=n.attributes.position;if(l!==null){let d=Math.max(0,o.start),f=Math.min(l.count,o.start+o.count);for(let m=d,_=f;m<_;m++){let g=l.getX(m);Qc.fromBufferAttribute(u,g),Ep(Qc,g,c,i,e,t,this)}}else{let d=Math.max(0,o.start),f=Math.min(u.count,o.start+o.count);for(let m=d,_=f;m<_;m++)Qc.fromBufferAttribute(u,m),Ep(Qc,m,c,i,e,t,this)}}updateMorphTargets(){let t=this.geometry.morphAttributes,n=Object.keys(t);if(n.length>0){let i=t[n[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,o=i.length;s<o;s++){let a=i[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=s}}}}};function Ep(r,e,t,n,i,s,o){let a=Cu.distanceSqToPoint(r);if(a<t){let c=new w;Cu.closestPointToPoint(r,c),c.applyMatrix4(n);let l=i.ray.origin.distanceTo(c);if(l<i.near||l>i.far)return;s.push({distance:l,distanceToRay:Math.sqrt(a),point:c,index:e,face:null,faceIndex:null,barycoord:null,object:o})}}var Oo=class extends gt{constructor(e,t,n,i,s=mt,o=mt,a,c,l){super(e,t,n,i,s,o,a,c,l),this.isVideoTexture=!0,this.generateMipmaps=!1,this._requestVideoFrameCallbackId=0;let h=this;function u(){h.needsUpdate=!0,h._requestVideoFrameCallbackId=e.requestVideoFrameCallback(u)}"requestVideoFrameCallback"in e&&(this._requestVideoFrameCallbackId=e.requestVideoFrameCallback(u))}clone(){return new this.constructor(this.image).copy(this)}update(){let e=this.image;"requestVideoFrameCallback"in e===!1&&e.readyState>=e.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}dispose(){this._requestVideoFrameCallbackId!==0&&this.source.data.cancelVideoFrameCallback(this._requestVideoFrameCallbackId),super.dispose()}},Al=class extends Oo{constructor(e,t,n,i,s,o,a,c){super({},e,t,n,i,s,o,a,c),this.isVideoFrameTexture=!0}update(){}clone(){return new this.constructor().copy(this)}setFrame(e){this.image=e,this.needsUpdate=!0}},wl=class extends gt{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=Ct,this.minFilter=Ct,this.generateMipmaps=!1,this.needsUpdate=!0}},bs=class extends gt{constructor(e,t,n,i,s,o,a,c,l,h,u,d){super(null,o,a,c,l,h,i,s,u,d),this.isCompressedTexture=!0,this.image={width:t,height:n},this.mipmaps=e,this.flipY=!1,this.generateMipmaps=!1}},Rl=class extends bs{constructor(e,t,n,i,s,o){super(e,t,n,s,o),this.isCompressedArrayTexture=!0,this.image.depth=i,this.wrapR=Kt,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}},Cl=class extends bs{constructor(e,t,n){super(void 0,e[0].width,e[0].height,t,n,ii),this.isCompressedCubeTexture=!0,this.isCubeTexture=!0,this.image=e}},Il=class extends gt{constructor(e,t,n,i,s,o,a,c,l){super(e,t,n,i,s,o,a,c,l),this.isCanvasTexture=!0,this.needsUpdate=!0}},Sr=class extends gt{constructor(e,t,n=si,i,s,o,a=Ct,c=Ct,l,h=hs,u=1){if(h!==hs&&h!==Fs)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");let d={width:e,height:t,depth:u};super(d,i,s,o,a,c,h,n,l),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new Un(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){let t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}},br=class extends gt{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}},Bo=class r extends ze{constructor(e=1,t=1,n=4,i=8,s=1){super(),this.type="CapsuleGeometry",this.parameters={radius:e,height:t,capSegments:n,radialSegments:i,heightSegments:s},t=Math.max(0,t),n=Math.max(1,Math.floor(n)),i=Math.max(3,Math.floor(i)),s=Math.max(1,Math.floor(s));let o=[],a=[],c=[],l=[],h=t/2,u=Math.PI/2*e,d=t,f=2*u+d,m=n*2+s,_=i+1,g=new w,p=new w;for(let v=0;v<=m;v++){let y=0,x=0,A=0,E=0;if(v<=n){let b=v/n,S=b*Math.PI/2;x=-h-e*Math.cos(S),A=e*Math.sin(S),E=-e*Math.cos(S),y=b*u}else if(v<=n+s){let b=(v-n)/s;x=-h+b*t,A=e,E=0,y=u+b*d}else{let b=(v-n-s)/n,S=b*Math.PI/2;x=h+e*Math.sin(S),A=e*Math.cos(S),E=e*Math.sin(S),y=u+d+b*u}let C=Math.max(0,Math.min(1,y/f)),I=0;v===0?I=.5/i:v===m&&(I=-.5/i);for(let b=0;b<=i;b++){let S=b/i,L=S*Math.PI*2,F=Math.sin(L),z=Math.cos(L);p.x=-A*z,p.y=x,p.z=A*F,a.push(p.x,p.y,p.z),g.set(-A*z,E,A*F),g.normalize(),c.push(g.x,g.y,g.z),l.push(S+I,C)}if(v>0){let b=(v-1)*_;for(let S=0;S<i;S++){let L=b+S,F=b+S+1,z=v*_+S,G=v*_+S+1;o.push(L,F,z),o.push(F,G,z)}}}this.setIndex(o),this.setAttribute("position",new ye(a,3)),this.setAttribute("normal",new ye(c,3)),this.setAttribute("uv",new ye(l,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new r(e.radius,e.height,e.capSegments,e.radialSegments,e.heightSegments)}},zo=class r extends ze{constructor(e=1,t=32,n=0,i=Math.PI*2){super(),this.type="CircleGeometry",this.parameters={radius:e,segments:t,thetaStart:n,thetaLength:i},t=Math.max(3,t);let s=[],o=[],a=[],c=[],l=new w,h=new Y;o.push(0,0,0),a.push(0,0,1),c.push(.5,.5);for(let u=0,d=3;u<=t;u++,d+=3){let f=n+u/t*i;l.x=e*Math.cos(f),l.y=e*Math.sin(f),o.push(l.x,l.y,l.z),a.push(0,0,1),h.x=(o[d]/e+1)/2,h.y=(o[d+1]/e+1)/2,c.push(h.x,h.y)}for(let u=1;u<=t;u++)s.push(u,u+1,0);this.setIndex(s),this.setAttribute("position",new ye(o,3)),this.setAttribute("normal",new ye(a,3)),this.setAttribute("uv",new ye(c,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new r(e.radius,e.segments,e.thetaStart,e.thetaLength)}},Tr=class r extends ze{constructor(e=1,t=1,n=1,i=32,s=1,o=!1,a=0,c=Math.PI*2){super(),this.type="CylinderGeometry",this.parameters={radiusTop:e,radiusBottom:t,height:n,radialSegments:i,heightSegments:s,openEnded:o,thetaStart:a,thetaLength:c};let l=this;i=Math.floor(i),s=Math.floor(s);let h=[],u=[],d=[],f=[],m=0,_=[],g=n/2,p=0;v(),o===!1&&(e>0&&y(!0),t>0&&y(!1)),this.setIndex(h),this.setAttribute("position",new ye(u,3)),this.setAttribute("normal",new ye(d,3)),this.setAttribute("uv",new ye(f,2));function v(){let x=new w,A=new w,E=0,C=(t-e)/n;for(let I=0;I<=s;I++){let b=[],S=I/s,L=S*(t-e)+e;for(let F=0;F<=i;F++){let z=F/i,G=z*c+a,q=Math.sin(G),W=Math.cos(G);A.x=L*q,A.y=-S*n+g,A.z=L*W,u.push(A.x,A.y,A.z),x.set(q,C,W).normalize(),d.push(x.x,x.y,x.z),f.push(z,1-S),b.push(m++)}_.push(b)}for(let I=0;I<i;I++)for(let b=0;b<s;b++){let S=_[b][I],L=_[b+1][I],F=_[b+1][I+1],z=_[b][I+1];(e>0||b!==0)&&(h.push(S,L,z),E+=3),(t>0||b!==s-1)&&(h.push(L,F,z),E+=3)}l.addGroup(p,E,0),p+=E}function y(x){let A=m,E=new Y,C=new w,I=0,b=x===!0?e:t,S=x===!0?1:-1;for(let F=1;F<=i;F++)u.push(0,g*S,0),d.push(0,S,0),f.push(.5,.5),m++;let L=m;for(let F=0;F<=i;F++){let G=F/i*c+a,q=Math.cos(G),W=Math.sin(G);C.x=b*W,C.y=g*S,C.z=b*q,u.push(C.x,C.y,C.z),d.push(0,S,0),E.x=q*.5+.5,E.y=W*.5*S+.5,f.push(E.x,E.y),m++}for(let F=0;F<i;F++){let z=A+F,G=L+F;x===!0?h.push(G,G+1,z):h.push(G+1,G,z),I+=3}l.addGroup(p,I,x===!0?1:2),p+=I}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new r(e.radiusTop,e.radiusBottom,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}},Er=class r extends Tr{constructor(e=1,t=1,n=32,i=1,s=!1,o=0,a=Math.PI*2){super(0,e,t,n,i,s,o,a),this.type="ConeGeometry",this.parameters={radius:e,height:t,radialSegments:n,heightSegments:i,openEnded:s,thetaStart:o,thetaLength:a}}static fromJSON(e){return new r(e.radius,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}},xi=class r extends ze{constructor(e=[],t=[],n=1,i=0){super(),this.type="PolyhedronGeometry",this.parameters={vertices:e,indices:t,radius:n,detail:i};let s=[],o=[];a(i),l(n),h(),this.setAttribute("position",new ye(s,3)),this.setAttribute("normal",new ye(s.slice(),3)),this.setAttribute("uv",new ye(o,2)),i===0?this.computeVertexNormals():this.normalizeNormals();function a(v){let y=new w,x=new w,A=new w;for(let E=0;E<t.length;E+=3)f(t[E+0],y),f(t[E+1],x),f(t[E+2],A),c(y,x,A,v)}function c(v,y,x,A){let E=A+1,C=[];for(let I=0;I<=E;I++){C[I]=[];let b=v.clone().lerp(x,I/E),S=y.clone().lerp(x,I/E),L=E-I;for(let F=0;F<=L;F++)F===0&&I===E?C[I][F]=b:C[I][F]=b.clone().lerp(S,F/L)}for(let I=0;I<E;I++)for(let b=0;b<2*(E-I)-1;b++){let S=Math.floor(b/2);b%2===0?(d(C[I][S+1]),d(C[I+1][S]),d(C[I][S])):(d(C[I][S+1]),d(C[I+1][S+1]),d(C[I+1][S]))}}function l(v){let y=new w;for(let x=0;x<s.length;x+=3)y.x=s[x+0],y.y=s[x+1],y.z=s[x+2],y.normalize().multiplyScalar(v),s[x+0]=y.x,s[x+1]=y.y,s[x+2]=y.z}function h(){let v=new w;for(let y=0;y<s.length;y+=3){v.x=s[y+0],v.y=s[y+1],v.z=s[y+2];let x=g(v)/2/Math.PI+.5,A=p(v)/Math.PI+.5;o.push(x,1-A)}m(),u()}function u(){for(let v=0;v<o.length;v+=6){let y=o[v+0],x=o[v+2],A=o[v+4],E=Math.max(y,x,A),C=Math.min(y,x,A);E>.9&&C<.1&&(y<.2&&(o[v+0]+=1),x<.2&&(o[v+2]+=1),A<.2&&(o[v+4]+=1))}}function d(v){s.push(v.x,v.y,v.z)}function f(v,y){let x=v*3;y.x=e[x+0],y.y=e[x+1],y.z=e[x+2]}function m(){let v=new w,y=new w,x=new w,A=new w,E=new Y,C=new Y,I=new Y;for(let b=0,S=0;b<s.length;b+=9,S+=6){v.set(s[b+0],s[b+1],s[b+2]),y.set(s[b+3],s[b+4],s[b+5]),x.set(s[b+6],s[b+7],s[b+8]),E.set(o[S+0],o[S+1]),C.set(o[S+2],o[S+3]),I.set(o[S+4],o[S+5]),A.copy(v).add(y).add(x).divideScalar(3);let L=g(A);_(E,S+0,v,L),_(C,S+2,y,L),_(I,S+4,x,L)}}function _(v,y,x,A){A<0&&v.x===1&&(o[y]=v.x-1),x.x===0&&x.z===0&&(o[y]=A/2/Math.PI+.5)}function g(v){return Math.atan2(v.z,-v.x)}function p(v){return Math.atan2(-v.y,Math.sqrt(v.x*v.x+v.z*v.z))}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new r(e.vertices,e.indices,e.radius,e.details)}},ko=class r extends xi{constructor(e=1,t=0){let n=(1+Math.sqrt(5))/2,i=1/n,s=[-1,-1,-1,-1,-1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,1,1,1,-1,1,1,1,0,-i,-n,0,-i,n,0,i,-n,0,i,n,-i,-n,0,-i,n,0,i,-n,0,i,n,0,-n,0,-i,n,0,-i,-n,0,i,n,0,i],o=[3,11,7,3,7,15,3,15,13,7,19,17,7,17,6,7,6,15,17,4,8,17,8,10,17,10,6,8,0,16,8,16,2,8,2,10,0,12,1,0,1,18,0,18,16,6,10,2,6,2,13,6,13,15,2,16,18,2,18,3,2,3,13,18,1,9,18,9,11,18,11,3,4,14,12,4,12,0,4,0,8,11,9,5,11,5,19,11,19,7,19,5,14,19,14,4,19,4,17,1,12,14,1,14,5,1,5,9];super(s,o,e,t),this.type="DodecahedronGeometry",this.parameters={radius:e,detail:t}}static fromJSON(e){return new r(e.radius,e.detail)}},el=new w,tl=new w,_u=new w,nl=new Nn,Vo=class extends ze{constructor(e=null,t=1){if(super(),this.type="EdgesGeometry",this.parameters={geometry:e,thresholdAngle:t},e!==null){let i=Math.pow(10,4),s=Math.cos(ls*t),o=e.getIndex(),a=e.getAttribute("position"),c=o?o.count:a.count,l=[0,0,0],h=["a","b","c"],u=new Array(3),d={},f=[];for(let m=0;m<c;m+=3){o?(l[0]=o.getX(m),l[1]=o.getX(m+1),l[2]=o.getX(m+2)):(l[0]=m,l[1]=m+1,l[2]=m+2);let{a:_,b:g,c:p}=nl;if(_.fromBufferAttribute(a,l[0]),g.fromBufferAttribute(a,l[1]),p.fromBufferAttribute(a,l[2]),nl.getNormal(_u),u[0]=`${Math.round(_.x*i)},${Math.round(_.y*i)},${Math.round(_.z*i)}`,u[1]=`${Math.round(g.x*i)},${Math.round(g.y*i)},${Math.round(g.z*i)}`,u[2]=`${Math.round(p.x*i)},${Math.round(p.y*i)},${Math.round(p.z*i)}`,!(u[0]===u[1]||u[1]===u[2]||u[2]===u[0]))for(let v=0;v<3;v++){let y=(v+1)%3,x=u[v],A=u[y],E=nl[h[v]],C=nl[h[y]],I=`${x}_${A}`,b=`${A}_${x}`;b in d&&d[b]?(_u.dot(d[b].normal)<=s&&(f.push(E.x,E.y,E.z),f.push(C.x,C.y,C.z)),d[b]=null):I in d||(d[I]={index0:l[v],index1:l[y],normal:_u.clone()})}}for(let m in d)if(d[m]){let{index0:_,index1:g}=d[m];el.fromBufferAttribute(a,_),tl.fromBufferAttribute(a,g),f.push(el.x,el.y,el.z),f.push(tl.x,tl.y,tl.z)}this.setAttribute("position",new ye(f,3))}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}},an=class{constructor(){this.type="Curve",this.arcLengthDivisions=200,this.needsUpdate=!1,this.cacheArcLengths=null}getPoint(){console.warn("THREE.Curve: .getPoint() not implemented.")}getPointAt(e,t){let n=this.getUtoTmapping(e);return this.getPoint(n,t)}getPoints(e=5){let t=[];for(let n=0;n<=e;n++)t.push(this.getPoint(n/e));return t}getSpacedPoints(e=5){let t=[];for(let n=0;n<=e;n++)t.push(this.getPointAt(n/e));return t}getLength(){let e=this.getLengths();return e[e.length-1]}getLengths(e=this.arcLengthDivisions){if(this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;let t=[],n,i=this.getPoint(0),s=0;t.push(0);for(let o=1;o<=e;o++)n=this.getPoint(o/e),s+=n.distanceTo(i),t.push(s),i=n;return this.cacheArcLengths=t,t}updateArcLengths(){this.needsUpdate=!0,this.getLengths()}getUtoTmapping(e,t=null){let n=this.getLengths(),i=0,s=n.length,o;t?o=t:o=e*n[s-1];let a=0,c=s-1,l;for(;a<=c;)if(i=Math.floor(a+(c-a)/2),l=n[i]-o,l<0)a=i+1;else if(l>0)c=i-1;else{c=i;break}if(i=c,n[i]===o)return i/(s-1);let h=n[i],d=n[i+1]-h,f=(o-h)/d;return(i+f)/(s-1)}getTangent(e,t){let i=e-1e-4,s=e+1e-4;i<0&&(i=0),s>1&&(s=1);let o=this.getPoint(i),a=this.getPoint(s),c=t||(o.isVector2?new Y:new w);return c.copy(a).sub(o).normalize(),c}getTangentAt(e,t){let n=this.getUtoTmapping(e);return this.getTangent(n,t)}computeFrenetFrames(e,t=!1){let n=new w,i=[],s=[],o=[],a=new w,c=new De;for(let f=0;f<=e;f++){let m=f/e;i[f]=this.getTangentAt(m,new w)}s[0]=new w,o[0]=new w;let l=Number.MAX_VALUE,h=Math.abs(i[0].x),u=Math.abs(i[0].y),d=Math.abs(i[0].z);h<=l&&(l=h,n.set(1,0,0)),u<=l&&(l=u,n.set(0,1,0)),d<=l&&n.set(0,0,1),a.crossVectors(i[0],n).normalize(),s[0].crossVectors(i[0],a),o[0].crossVectors(i[0],s[0]);for(let f=1;f<=e;f++){if(s[f]=s[f-1].clone(),o[f]=o[f-1].clone(),a.crossVectors(i[f-1],i[f]),a.length()>Number.EPSILON){a.normalize();let m=Math.acos(Fe(i[f-1].dot(i[f]),-1,1));s[f].applyMatrix4(c.makeRotationAxis(a,m))}o[f].crossVectors(i[f],s[f])}if(t===!0){let f=Math.acos(Fe(s[0].dot(s[e]),-1,1));f/=e,i[0].dot(a.crossVectors(s[0],s[e]))>0&&(f=-f);for(let m=1;m<=e;m++)s[m].applyMatrix4(c.makeRotationAxis(i[m],f*m)),o[m].crossVectors(i[m],s[m])}return{tangents:i,normals:s,binormals:o}}clone(){return new this.constructor().copy(this)}copy(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}toJSON(){let e={metadata:{version:4.7,type:"Curve",generator:"Curve.toJSON"}};return e.arcLengthDivisions=this.arcLengthDivisions,e.type=this.type,e}fromJSON(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}},Ts=class extends an{constructor(e=0,t=0,n=1,i=1,s=0,o=Math.PI*2,a=!1,c=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=e,this.aY=t,this.xRadius=n,this.yRadius=i,this.aStartAngle=s,this.aEndAngle=o,this.aClockwise=a,this.aRotation=c}getPoint(e,t=new Y){let n=t,i=Math.PI*2,s=this.aEndAngle-this.aStartAngle,o=Math.abs(s)<Number.EPSILON;for(;s<0;)s+=i;for(;s>i;)s-=i;s<Number.EPSILON&&(o?s=0:s=i),this.aClockwise===!0&&!o&&(s===i?s=-i:s=s-i);let a=this.aStartAngle+e*s,c=this.aX+this.xRadius*Math.cos(a),l=this.aY+this.yRadius*Math.sin(a);if(this.aRotation!==0){let h=Math.cos(this.aRotation),u=Math.sin(this.aRotation),d=c-this.aX,f=l-this.aY;c=d*h-f*u+this.aX,l=d*u+f*h+this.aY}return n.set(c,l)}copy(e){return super.copy(e),this.aX=e.aX,this.aY=e.aY,this.xRadius=e.xRadius,this.yRadius=e.yRadius,this.aStartAngle=e.aStartAngle,this.aEndAngle=e.aEndAngle,this.aClockwise=e.aClockwise,this.aRotation=e.aRotation,this}toJSON(){let e=super.toJSON();return e.aX=this.aX,e.aY=this.aY,e.xRadius=this.xRadius,e.yRadius=this.yRadius,e.aStartAngle=this.aStartAngle,e.aEndAngle=this.aEndAngle,e.aClockwise=this.aClockwise,e.aRotation=this.aRotation,e}fromJSON(e){return super.fromJSON(e),this.aX=e.aX,this.aY=e.aY,this.xRadius=e.xRadius,this.yRadius=e.yRadius,this.aStartAngle=e.aStartAngle,this.aEndAngle=e.aEndAngle,this.aClockwise=e.aClockwise,this.aRotation=e.aRotation,this}},Ho=class extends Ts{constructor(e,t,n,i,s,o){super(e,t,n,n,i,s,o),this.isArcCurve=!0,this.type="ArcCurve"}};function Fd(){let r=0,e=0,t=0,n=0;function i(s,o,a,c){r=s,e=a,t=-3*s+3*o-2*a-c,n=2*s-2*o+a+c}return{initCatmullRom:function(s,o,a,c,l){i(o,a,l*(a-s),l*(c-o))},initNonuniformCatmullRom:function(s,o,a,c,l,h,u){let d=(o-s)/l-(a-s)/(l+h)+(a-o)/h,f=(a-o)/h-(c-o)/(h+u)+(c-a)/u;d*=h,f*=h,i(o,a,d,f)},calc:function(s){let o=s*s,a=o*s;return r+e*s+t*o+n*a}}}var il=new w,xu=new Fd,yu=new Fd,vu=new Fd,Go=class extends an{constructor(e=[],t=!1,n="centripetal",i=.5){super(),this.isCatmullRomCurve3=!0,this.type="CatmullRomCurve3",this.points=e,this.closed=t,this.curveType=n,this.tension=i}getPoint(e,t=new w){let n=t,i=this.points,s=i.length,o=(s-(this.closed?0:1))*e,a=Math.floor(o),c=o-a;this.closed?a+=a>0?0:(Math.floor(Math.abs(a)/s)+1)*s:c===0&&a===s-1&&(a=s-2,c=1);let l,h;this.closed||a>0?l=i[(a-1)%s]:(il.subVectors(i[0],i[1]).add(i[0]),l=il);let u=i[a%s],d=i[(a+1)%s];if(this.closed||a+2<s?h=i[(a+2)%s]:(il.subVectors(i[s-1],i[s-2]).add(i[s-1]),h=il),this.curveType==="centripetal"||this.curveType==="chordal"){let f=this.curveType==="chordal"?.5:.25,m=Math.pow(l.distanceToSquared(u),f),_=Math.pow(u.distanceToSquared(d),f),g=Math.pow(d.distanceToSquared(h),f);_<1e-4&&(_=1),m<1e-4&&(m=_),g<1e-4&&(g=_),xu.initNonuniformCatmullRom(l.x,u.x,d.x,h.x,m,_,g),yu.initNonuniformCatmullRom(l.y,u.y,d.y,h.y,m,_,g),vu.initNonuniformCatmullRom(l.z,u.z,d.z,h.z,m,_,g)}else this.curveType==="catmullrom"&&(xu.initCatmullRom(l.x,u.x,d.x,h.x,this.tension),yu.initCatmullRom(l.y,u.y,d.y,h.y,this.tension),vu.initCatmullRom(l.z,u.z,d.z,h.z,this.tension));return n.set(xu.calc(c),yu.calc(c),vu.calc(c)),n}copy(e){super.copy(e),this.points=[];for(let t=0,n=e.points.length;t<n;t++){let i=e.points[t];this.points.push(i.clone())}return this.closed=e.closed,this.curveType=e.curveType,this.tension=e.tension,this}toJSON(){let e=super.toJSON();e.points=[];for(let t=0,n=this.points.length;t<n;t++){let i=this.points[t];e.points.push(i.toArray())}return e.closed=this.closed,e.curveType=this.curveType,e.tension=this.tension,e}fromJSON(e){super.fromJSON(e),this.points=[];for(let t=0,n=e.points.length;t<n;t++){let i=e.points[t];this.points.push(new w().fromArray(i))}return this.closed=e.closed,this.curveType=e.curveType,this.tension=e.tension,this}};function Ap(r,e,t,n,i){let s=(n-e)*.5,o=(i-t)*.5,a=r*r,c=r*a;return(2*t-2*n+s+o)*c+(-3*t+3*n-2*s-o)*a+s*r+t}function A_(r,e){let t=1-r;return t*t*e}function w_(r,e){return 2*(1-r)*r*e}function R_(r,e){return r*r*e}function bo(r,e,t,n){return A_(r,e)+w_(r,t)+R_(r,n)}function C_(r,e){let t=1-r;return t*t*t*e}function I_(r,e){let t=1-r;return 3*t*t*r*e}function P_(r,e){return 3*(1-r)*r*r*e}function L_(r,e){return r*r*r*e}function To(r,e,t,n,i){return C_(r,e)+I_(r,t)+P_(r,n)+L_(r,i)}var Ar=class extends an{constructor(e=new Y,t=new Y,n=new Y,i=new Y){super(),this.isCubicBezierCurve=!0,this.type="CubicBezierCurve",this.v0=e,this.v1=t,this.v2=n,this.v3=i}getPoint(e,t=new Y){let n=t,i=this.v0,s=this.v1,o=this.v2,a=this.v3;return n.set(To(e,i.x,s.x,o.x,a.x),To(e,i.y,s.y,o.y,a.y)),n}copy(e){return super.copy(e),this.v0.copy(e.v0),this.v1.copy(e.v1),this.v2.copy(e.v2),this.v3.copy(e.v3),this}toJSON(){let e=super.toJSON();return e.v0=this.v0.toArray(),e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e.v3=this.v3.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v0.fromArray(e.v0),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this.v3.fromArray(e.v3),this}},Wo=class extends an{constructor(e=new w,t=new w,n=new w,i=new w){super(),this.isCubicBezierCurve3=!0,this.type="CubicBezierCurve3",this.v0=e,this.v1=t,this.v2=n,this.v3=i}getPoint(e,t=new w){let n=t,i=this.v0,s=this.v1,o=this.v2,a=this.v3;return n.set(To(e,i.x,s.x,o.x,a.x),To(e,i.y,s.y,o.y,a.y),To(e,i.z,s.z,o.z,a.z)),n}copy(e){return super.copy(e),this.v0.copy(e.v0),this.v1.copy(e.v1),this.v2.copy(e.v2),this.v3.copy(e.v3),this}toJSON(){let e=super.toJSON();return e.v0=this.v0.toArray(),e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e.v3=this.v3.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v0.fromArray(e.v0),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this.v3.fromArray(e.v3),this}},wr=class extends an{constructor(e=new Y,t=new Y){super(),this.isLineCurve=!0,this.type="LineCurve",this.v1=e,this.v2=t}getPoint(e,t=new Y){let n=t;return e===1?n.copy(this.v2):(n.copy(this.v2).sub(this.v1),n.multiplyScalar(e).add(this.v1)),n}getPointAt(e,t){return this.getPoint(e,t)}getTangent(e,t=new Y){return t.subVectors(this.v2,this.v1).normalize()}getTangentAt(e,t){return this.getTangent(e,t)}copy(e){return super.copy(e),this.v1.copy(e.v1),this.v2.copy(e.v2),this}toJSON(){let e=super.toJSON();return e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this}},Xo=class extends an{constructor(e=new w,t=new w){super(),this.isLineCurve3=!0,this.type="LineCurve3",this.v1=e,this.v2=t}getPoint(e,t=new w){let n=t;return e===1?n.copy(this.v2):(n.copy(this.v2).sub(this.v1),n.multiplyScalar(e).add(this.v1)),n}getPointAt(e,t){return this.getPoint(e,t)}getTangent(e,t=new w){return t.subVectors(this.v2,this.v1).normalize()}getTangentAt(e,t){return this.getTangent(e,t)}copy(e){return super.copy(e),this.v1.copy(e.v1),this.v2.copy(e.v2),this}toJSON(){let e=super.toJSON();return e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this}},Rr=class extends an{constructor(e=new Y,t=new Y,n=new Y){super(),this.isQuadraticBezierCurve=!0,this.type="QuadraticBezierCurve",this.v0=e,this.v1=t,this.v2=n}getPoint(e,t=new Y){let n=t,i=this.v0,s=this.v1,o=this.v2;return n.set(bo(e,i.x,s.x,o.x),bo(e,i.y,s.y,o.y)),n}copy(e){return super.copy(e),this.v0.copy(e.v0),this.v1.copy(e.v1),this.v2.copy(e.v2),this}toJSON(){let e=super.toJSON();return e.v0=this.v0.toArray(),e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v0.fromArray(e.v0),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this}},Cr=class extends an{constructor(e=new w,t=new w,n=new w){super(),this.isQuadraticBezierCurve3=!0,this.type="QuadraticBezierCurve3",this.v0=e,this.v1=t,this.v2=n}getPoint(e,t=new w){let n=t,i=this.v0,s=this.v1,o=this.v2;return n.set(bo(e,i.x,s.x,o.x),bo(e,i.y,s.y,o.y),bo(e,i.z,s.z,o.z)),n}copy(e){return super.copy(e),this.v0.copy(e.v0),this.v1.copy(e.v1),this.v2.copy(e.v2),this}toJSON(){let e=super.toJSON();return e.v0=this.v0.toArray(),e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v0.fromArray(e.v0),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this}},Ir=class extends an{constructor(e=[]){super(),this.isSplineCurve=!0,this.type="SplineCurve",this.points=e}getPoint(e,t=new Y){let n=t,i=this.points,s=(i.length-1)*e,o=Math.floor(s),a=s-o,c=i[o===0?o:o-1],l=i[o],h=i[o>i.length-2?i.length-1:o+1],u=i[o>i.length-3?i.length-1:o+2];return n.set(Ap(a,c.x,l.x,h.x,u.x),Ap(a,c.y,l.y,h.y,u.y)),n}copy(e){super.copy(e),this.points=[];for(let t=0,n=e.points.length;t<n;t++){let i=e.points[t];this.points.push(i.clone())}return this}toJSON(){let e=super.toJSON();e.points=[];for(let t=0,n=this.points.length;t<n;t++){let i=this.points[t];e.points.push(i.toArray())}return e}fromJSON(e){super.fromJSON(e),this.points=[];for(let t=0,n=e.points.length;t<n;t++){let i=e.points[t];this.points.push(new Y().fromArray(i))}return this}},Pl=Object.freeze({__proto__:null,ArcCurve:Ho,CatmullRomCurve3:Go,CubicBezierCurve:Ar,CubicBezierCurve3:Wo,EllipseCurve:Ts,LineCurve:wr,LineCurve3:Xo,QuadraticBezierCurve:Rr,QuadraticBezierCurve3:Cr,SplineCurve:Ir}),qo=class extends an{constructor(){super(),this.type="CurvePath",this.curves=[],this.autoClose=!1}add(e){this.curves.push(e)}closePath(){let e=this.curves[0].getPoint(0),t=this.curves[this.curves.length-1].getPoint(1);if(!e.equals(t)){let n=e.isVector2===!0?"LineCurve":"LineCurve3";this.curves.push(new Pl[n](t,e))}return this}getPoint(e,t){let n=e*this.getLength(),i=this.getCurveLengths(),s=0;for(;s<i.length;){if(i[s]>=n){let o=i[s]-n,a=this.curves[s],c=a.getLength(),l=c===0?0:1-o/c;return a.getPointAt(l,t)}s++}return null}getLength(){let e=this.getCurveLengths();return e[e.length-1]}updateArcLengths(){this.needsUpdate=!0,this.cacheLengths=null,this.getCurveLengths()}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;let e=[],t=0;for(let n=0,i=this.curves.length;n<i;n++)t+=this.curves[n].getLength(),e.push(t);return this.cacheLengths=e,e}getSpacedPoints(e=40){let t=[];for(let n=0;n<=e;n++)t.push(this.getPoint(n/e));return this.autoClose&&t.push(t[0]),t}getPoints(e=12){let t=[],n;for(let i=0,s=this.curves;i<s.length;i++){let o=s[i],a=o.isEllipseCurve?e*2:o.isLineCurve||o.isLineCurve3?1:o.isSplineCurve?e*o.points.length:e,c=o.getPoints(a);for(let l=0;l<c.length;l++){let h=c[l];n&&n.equals(h)||(t.push(h),n=h)}}return this.autoClose&&t.length>1&&!t[t.length-1].equals(t[0])&&t.push(t[0]),t}copy(e){super.copy(e),this.curves=[];for(let t=0,n=e.curves.length;t<n;t++){let i=e.curves[t];this.curves.push(i.clone())}return this.autoClose=e.autoClose,this}toJSON(){let e=super.toJSON();e.autoClose=this.autoClose,e.curves=[];for(let t=0,n=this.curves.length;t<n;t++){let i=this.curves[t];e.curves.push(i.toJSON())}return e}fromJSON(e){super.fromJSON(e),this.autoClose=e.autoClose,this.curves=[];for(let t=0,n=e.curves.length;t<n;t++){let i=e.curves[t];this.curves.push(new Pl[i.type]().fromJSON(i))}return this}},Es=class extends qo{constructor(e){super(),this.type="Path",this.currentPoint=new Y,e&&this.setFromPoints(e)}setFromPoints(e){this.moveTo(e[0].x,e[0].y);for(let t=1,n=e.length;t<n;t++)this.lineTo(e[t].x,e[t].y);return this}moveTo(e,t){return this.currentPoint.set(e,t),this}lineTo(e,t){let n=new wr(this.currentPoint.clone(),new Y(e,t));return this.curves.push(n),this.currentPoint.set(e,t),this}quadraticCurveTo(e,t,n,i){let s=new Rr(this.currentPoint.clone(),new Y(e,t),new Y(n,i));return this.curves.push(s),this.currentPoint.set(n,i),this}bezierCurveTo(e,t,n,i,s,o){let a=new Ar(this.currentPoint.clone(),new Y(e,t),new Y(n,i),new Y(s,o));return this.curves.push(a),this.currentPoint.set(s,o),this}splineThru(e){let t=[this.currentPoint.clone()].concat(e),n=new Ir(t);return this.curves.push(n),this.currentPoint.copy(e[e.length-1]),this}arc(e,t,n,i,s,o){let a=this.currentPoint.x,c=this.currentPoint.y;return this.absarc(e+a,t+c,n,i,s,o),this}absarc(e,t,n,i,s,o){return this.absellipse(e,t,n,n,i,s,o),this}ellipse(e,t,n,i,s,o,a,c){let l=this.currentPoint.x,h=this.currentPoint.y;return this.absellipse(e+l,t+h,n,i,s,o,a,c),this}absellipse(e,t,n,i,s,o,a,c){let l=new Ts(e,t,n,i,s,o,a,c);if(this.curves.length>0){let u=l.getPoint(0);u.equals(this.currentPoint)||this.lineTo(u.x,u.y)}this.curves.push(l);let h=l.getPoint(1);return this.currentPoint.copy(h),this}copy(e){return super.copy(e),this.currentPoint.copy(e.currentPoint),this}toJSON(){let e=super.toJSON();return e.currentPoint=this.currentPoint.toArray(),e}fromJSON(e){return super.fromJSON(e),this.currentPoint.fromArray(e.currentPoint),this}},Zn=class extends Es{constructor(e){super(e),this.uuid=gn(),this.type="Shape",this.holes=[]}getPointsHoles(e){let t=[];for(let n=0,i=this.holes.length;n<i;n++)t[n]=this.holes[n].getPoints(e);return t}extractPoints(e){return{shape:this.getPoints(e),holes:this.getPointsHoles(e)}}copy(e){super.copy(e),this.holes=[];for(let t=0,n=e.holes.length;t<n;t++){let i=e.holes[t];this.holes.push(i.clone())}return this}toJSON(){let e=super.toJSON();e.uuid=this.uuid,e.holes=[];for(let t=0,n=this.holes.length;t<n;t++){let i=this.holes[t];e.holes.push(i.toJSON())}return e}fromJSON(e){super.fromJSON(e),this.uuid=e.uuid,this.holes=[];for(let t=0,n=e.holes.length;t<n;t++){let i=e.holes[t];this.holes.push(new Es().fromJSON(i))}return this}};function D_(r,e,t=2){let n=e&&e.length,i=n?e[0]*t:r.length,s=Nm(r,0,i,t,!0),o=[];if(!s||s.next===s.prev)return o;let a,c,l;if(n&&(s=B_(r,e,s,t)),r.length>80*t){a=1/0,c=1/0;let h=-1/0,u=-1/0;for(let d=t;d<i;d+=t){let f=r[d],m=r[d+1];f<a&&(a=f),m<c&&(c=m),f>h&&(h=f),m>u&&(u=m)}l=Math.max(h-a,u-c),l=l!==0?32767/l:0}return Yo(s,o,t,a,c,l,0),o}function Nm(r,e,t,n,i){let s;if(i===K_(r,e,t,n)>0)for(let o=e;o<t;o+=n)s=wp(o/n|0,r[o],r[o+1],s);else for(let o=t-n;o>=e;o-=n)s=wp(o/n|0,r[o],r[o+1],s);return s&&Pr(s,s.next)&&(Ko(s),s=s.next),s}function As(r,e){if(!r)return r;e||(e=r);let t=r,n;do if(n=!1,!t.steiner&&(Pr(t,t.next)||yt(t.prev,t,t.next)===0)){if(Ko(t),t=e=t.prev,t===t.next)break;n=!0}else t=t.next;while(n||t!==e);return e}function Yo(r,e,t,n,i,s,o){if(!r)return;!o&&s&&G_(r,n,i,s);let a=r;for(;r.prev!==r.next;){let c=r.prev,l=r.next;if(s?U_(r,n,i,s):N_(r)){e.push(c.i,r.i,l.i),Ko(r),r=l.next,a=l.next;continue}if(r=l,r===a){o?o===1?(r=F_(As(r),e),Yo(r,e,t,n,i,s,2)):o===2&&O_(r,e,t,n,i,s):Yo(As(r),e,t,n,i,s,1);break}}}function N_(r){let e=r.prev,t=r,n=r.next;if(yt(e,t,n)>=0)return!1;let i=e.x,s=t.x,o=n.x,a=e.y,c=t.y,l=n.y,h=Math.min(i,s,o),u=Math.min(a,c,l),d=Math.max(i,s,o),f=Math.max(a,c,l),m=n.next;for(;m!==e;){if(m.x>=h&&m.x<=d&&m.y>=u&&m.y<=f&&vo(i,a,s,c,o,l,m.x,m.y)&&yt(m.prev,m,m.next)>=0)return!1;m=m.next}return!0}function U_(r,e,t,n){let i=r.prev,s=r,o=r.next;if(yt(i,s,o)>=0)return!1;let a=i.x,c=s.x,l=o.x,h=i.y,u=s.y,d=o.y,f=Math.min(a,c,l),m=Math.min(h,u,d),_=Math.max(a,c,l),g=Math.max(h,u,d),p=Iu(f,m,e,t,n),v=Iu(_,g,e,t,n),y=r.prevZ,x=r.nextZ;for(;y&&y.z>=p&&x&&x.z<=v;){if(y.x>=f&&y.x<=_&&y.y>=m&&y.y<=g&&y!==i&&y!==o&&vo(a,h,c,u,l,d,y.x,y.y)&&yt(y.prev,y,y.next)>=0||(y=y.prevZ,x.x>=f&&x.x<=_&&x.y>=m&&x.y<=g&&x!==i&&x!==o&&vo(a,h,c,u,l,d,x.x,x.y)&&yt(x.prev,x,x.next)>=0))return!1;x=x.nextZ}for(;y&&y.z>=p;){if(y.x>=f&&y.x<=_&&y.y>=m&&y.y<=g&&y!==i&&y!==o&&vo(a,h,c,u,l,d,y.x,y.y)&&yt(y.prev,y,y.next)>=0)return!1;y=y.prevZ}for(;x&&x.z<=v;){if(x.x>=f&&x.x<=_&&x.y>=m&&x.y<=g&&x!==i&&x!==o&&vo(a,h,c,u,l,d,x.x,x.y)&&yt(x.prev,x,x.next)>=0)return!1;x=x.nextZ}return!0}function F_(r,e){let t=r;do{let n=t.prev,i=t.next.next;!Pr(n,i)&&Fm(n,t,t.next,i)&&Zo(n,i)&&Zo(i,n)&&(e.push(n.i,t.i,i.i),Ko(t),Ko(t.next),t=r=i),t=t.next}while(t!==r);return As(t)}function O_(r,e,t,n,i,s){let o=r;do{let a=o.next.next;for(;a!==o.prev;){if(o.i!==a.i&&q_(o,a)){let c=Om(o,a);o=As(o,o.next),c=As(c,c.next),Yo(o,e,t,n,i,s,0),Yo(c,e,t,n,i,s,0);return}a=a.next}o=o.next}while(o!==r)}function B_(r,e,t,n){let i=[];for(let s=0,o=e.length;s<o;s++){let a=e[s]*n,c=s<o-1?e[s+1]*n:r.length,l=Nm(r,a,c,n,!1);l===l.next&&(l.steiner=!0),i.push(X_(l))}i.sort(z_);for(let s=0;s<i.length;s++)t=k_(i[s],t);return t}function z_(r,e){let t=r.x-e.x;if(t===0&&(t=r.y-e.y,t===0)){let n=(r.next.y-r.y)/(r.next.x-r.x),i=(e.next.y-e.y)/(e.next.x-e.x);t=n-i}return t}function k_(r,e){let t=V_(r,e);if(!t)return e;let n=Om(t,r);return As(n,n.next),As(t,t.next)}function V_(r,e){let t=e,n=r.x,i=r.y,s=-1/0,o;if(Pr(r,t))return t;do{if(Pr(r,t.next))return t.next;if(i<=t.y&&i>=t.next.y&&t.next.y!==t.y){let u=t.x+(i-t.y)*(t.next.x-t.x)/(t.next.y-t.y);if(u<=n&&u>s&&(s=u,o=t.x<t.next.x?t:t.next,u===n))return o}t=t.next}while(t!==e);if(!o)return null;let a=o,c=o.x,l=o.y,h=1/0;t=o;do{if(n>=t.x&&t.x>=c&&n!==t.x&&Um(i<l?n:s,i,c,l,i<l?s:n,i,t.x,t.y)){let u=Math.abs(i-t.y)/(n-t.x);Zo(t,r)&&(u<h||u===h&&(t.x>o.x||t.x===o.x&&H_(o,t)))&&(o=t,h=u)}t=t.next}while(t!==a);return o}function H_(r,e){return yt(r.prev,r,e.prev)<0&&yt(e.next,r,r.next)<0}function G_(r,e,t,n){let i=r;do i.z===0&&(i.z=Iu(i.x,i.y,e,t,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next;while(i!==r);i.prevZ.nextZ=null,i.prevZ=null,W_(i)}function W_(r){let e,t=1;do{let n=r,i;r=null;let s=null;for(e=0;n;){e++;let o=n,a=0;for(let l=0;l<t&&(a++,o=o.nextZ,!!o);l++);let c=t;for(;a>0||c>0&&o;)a!==0&&(c===0||!o||n.z<=o.z)?(i=n,n=n.nextZ,a--):(i=o,o=o.nextZ,c--),s?s.nextZ=i:r=i,i.prevZ=s,s=i;n=o}s.nextZ=null,t*=2}while(e>1);return r}function Iu(r,e,t,n,i){return r=(r-t)*i|0,e=(e-n)*i|0,r=(r|r<<8)&16711935,r=(r|r<<4)&252645135,r=(r|r<<2)&858993459,r=(r|r<<1)&1431655765,e=(e|e<<8)&16711935,e=(e|e<<4)&252645135,e=(e|e<<2)&858993459,e=(e|e<<1)&1431655765,r|e<<1}function X_(r){let e=r,t=r;do(e.x<t.x||e.x===t.x&&e.y<t.y)&&(t=e),e=e.next;while(e!==r);return t}function Um(r,e,t,n,i,s,o,a){return(i-o)*(e-a)>=(r-o)*(s-a)&&(r-o)*(n-a)>=(t-o)*(e-a)&&(t-o)*(s-a)>=(i-o)*(n-a)}function vo(r,e,t,n,i,s,o,a){return!(r===o&&e===a)&&Um(r,e,t,n,i,s,o,a)}function q_(r,e){return r.next.i!==e.i&&r.prev.i!==e.i&&!Y_(r,e)&&(Zo(r,e)&&Zo(e,r)&&Z_(r,e)&&(yt(r.prev,r,e.prev)||yt(r,e.prev,e))||Pr(r,e)&&yt(r.prev,r,r.next)>0&&yt(e.prev,e,e.next)>0)}function yt(r,e,t){return(e.y-r.y)*(t.x-e.x)-(e.x-r.x)*(t.y-e.y)}function Pr(r,e){return r.x===e.x&&r.y===e.y}function Fm(r,e,t,n){let i=rl(yt(r,e,t)),s=rl(yt(r,e,n)),o=rl(yt(t,n,r)),a=rl(yt(t,n,e));return!!(i!==s&&o!==a||i===0&&sl(r,t,e)||s===0&&sl(r,n,e)||o===0&&sl(t,r,n)||a===0&&sl(t,e,n))}function sl(r,e,t){return e.x<=Math.max(r.x,t.x)&&e.x>=Math.min(r.x,t.x)&&e.y<=Math.max(r.y,t.y)&&e.y>=Math.min(r.y,t.y)}function rl(r){return r>0?1:r<0?-1:0}function Y_(r,e){let t=r;do{if(t.i!==r.i&&t.next.i!==r.i&&t.i!==e.i&&t.next.i!==e.i&&Fm(t,t.next,r,e))return!0;t=t.next}while(t!==r);return!1}function Zo(r,e){return yt(r.prev,r,r.next)<0?yt(r,e,r.next)>=0&&yt(r,r.prev,e)>=0:yt(r,e,r.prev)<0||yt(r,r.next,e)<0}function Z_(r,e){let t=r,n=!1,i=(r.x+e.x)/2,s=(r.y+e.y)/2;do t.y>s!=t.next.y>s&&t.next.y!==t.y&&i<(t.next.x-t.x)*(s-t.y)/(t.next.y-t.y)+t.x&&(n=!n),t=t.next;while(t!==r);return n}function Om(r,e){let t=Pu(r.i,r.x,r.y),n=Pu(e.i,e.x,e.y),i=r.next,s=e.prev;return r.next=e,e.prev=r,t.next=i,i.prev=t,n.next=t,t.prev=n,s.next=n,n.prev=s,n}function wp(r,e,t,n){let i=Pu(r,e,t);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function Ko(r){r.next.prev=r.prev,r.prev.next=r.next,r.prevZ&&(r.prevZ.nextZ=r.nextZ),r.nextZ&&(r.nextZ.prevZ=r.prevZ)}function Pu(r,e,t){return{i:r,x:e,y:t,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function K_(r,e,t,n){let i=0;for(let s=e,o=t-n;s<t;s+=n)i+=(r[o]-r[s])*(r[s+1]+r[o+1]),o=s;return i}var Lu=class{static triangulate(e,t,n=2){return D_(e,t,n)}},En=class r{static area(e){let t=e.length,n=0;for(let i=t-1,s=0;s<t;i=s++)n+=e[i].x*e[s].y-e[s].x*e[i].y;return n*.5}static isClockWise(e){return r.area(e)<0}static triangulateShape(e,t){let n=[],i=[],s=[];Rp(e),Cp(n,e);let o=e.length;t.forEach(Rp);for(let c=0;c<t.length;c++)i.push(o),o+=t[c].length,Cp(n,t[c]);let a=Lu.triangulate(n,i);for(let c=0;c<a.length;c+=3)s.push(a.slice(c,c+3));return s}};function Rp(r){let e=r.length;e>2&&r[e-1].equals(r[0])&&r.pop()}function Cp(r,e){for(let t=0;t<e.length;t++)r.push(e[t].x),r.push(e[t].y)}var Jo=class r extends ze{constructor(e=new Zn([new Y(.5,.5),new Y(-.5,.5),new Y(-.5,-.5),new Y(.5,-.5)]),t={}){super(),this.type="ExtrudeGeometry",this.parameters={shapes:e,options:t},e=Array.isArray(e)?e:[e];let n=this,i=[],s=[];for(let a=0,c=e.length;a<c;a++){let l=e[a];o(l)}this.setAttribute("position",new ye(i,3)),this.setAttribute("uv",new ye(s,2)),this.computeVertexNormals();function o(a){let c=[],l=t.curveSegments!==void 0?t.curveSegments:12,h=t.steps!==void 0?t.steps:1,u=t.depth!==void 0?t.depth:1,d=t.bevelEnabled!==void 0?t.bevelEnabled:!0,f=t.bevelThickness!==void 0?t.bevelThickness:.2,m=t.bevelSize!==void 0?t.bevelSize:f-.1,_=t.bevelOffset!==void 0?t.bevelOffset:0,g=t.bevelSegments!==void 0?t.bevelSegments:3,p=t.extrudePath,v=t.UVGenerator!==void 0?t.UVGenerator:J_,y,x=!1,A,E,C,I;p&&(y=p.getSpacedPoints(h),x=!0,d=!1,A=p.computeFrenetFrames(h,!1),E=new w,C=new w,I=new w),d||(g=0,f=0,m=0,_=0);let b=a.extractPoints(l),S=b.shape,L=b.holes;if(!En.isClockWise(S)){S=S.reverse();for(let ee=0,$=L.length;ee<$;ee++){let J=L[ee];En.isClockWise(J)&&(L[ee]=J.reverse())}}function z(ee){let J=10000000000000001e-36,K=ee[0];for(let le=1;le<=ee.length;le++){let ie=le%ee.length,he=ee[ie],He=he.x-K.x,ke=he.y-K.y,R=He*He+ke*ke,M=Math.max(Math.abs(he.x),Math.abs(he.y),Math.abs(K.x),Math.abs(K.y)),O=J*M*M;if(R<=O){ee.splice(ie,1),le--;continue}K=he}}z(S),L.forEach(z);let G=L.length,q=S;for(let ee=0;ee<G;ee++){let $=L[ee];S=S.concat($)}function W(ee,$,J){return $||console.error("THREE.ExtrudeGeometry: vec does not exist"),ee.clone().addScaledVector($,J)}let ne=S.length;function H(ee,$,J){let K,le,ie,he=ee.x-$.x,He=ee.y-$.y,ke=J.x-ee.x,R=J.y-ee.y,M=he*he+He*He,O=he*R-He*ke;if(Math.abs(O)>Number.EPSILON){let V=Math.sqrt(M),Q=Math.sqrt(ke*ke+R*R),X=$.x-He/V,Ce=$.y+he/V,ce=J.x-R/Q,Ae=J.y+ke/Q,we=((ce-X)*R-(Ae-Ce)*ke)/(he*R-He*ke);K=X+he*we-ee.x,le=Ce+He*we-ee.y;let se=K*K+le*le;if(se<=2)return new Y(K,le);ie=Math.sqrt(se/2)}else{let V=!1;he>Number.EPSILON?ke>Number.EPSILON&&(V=!0):he<-Number.EPSILON?ke<-Number.EPSILON&&(V=!0):Math.sign(He)===Math.sign(R)&&(V=!0),V?(K=-He,le=he,ie=Math.sqrt(M)):(K=he,le=He,ie=Math.sqrt(M/2))}return new Y(K/ie,le/ie)}let de=[];for(let ee=0,$=q.length,J=$-1,K=ee+1;ee<$;ee++,J++,K++)J===$&&(J=0),K===$&&(K=0),de[ee]=H(q[ee],q[J],q[K]);let xe=[],Se,We=de.concat();for(let ee=0,$=G;ee<$;ee++){let J=L[ee];Se=[];for(let K=0,le=J.length,ie=le-1,he=K+1;K<le;K++,ie++,he++)ie===le&&(ie=0),he===le&&(he=0),Se[K]=H(J[K],J[ie],J[he]);xe.push(Se),We=We.concat(Se)}let et;if(g===0)et=En.triangulateShape(q,L);else{let ee=[],$=[];for(let J=0;J<g;J++){let K=J/g,le=f*Math.cos(K*Math.PI/2),ie=m*Math.sin(K*Math.PI/2)+_;for(let he=0,He=q.length;he<He;he++){let ke=W(q[he],de[he],ie);Pe(ke.x,ke.y,-le),K===0&&ee.push(ke)}for(let he=0,He=G;he<He;he++){let ke=L[he];Se=xe[he];let R=[];for(let M=0,O=ke.length;M<O;M++){let V=W(ke[M],Se[M],ie);Pe(V.x,V.y,-le),K===0&&R.push(V)}K===0&&$.push(R)}}et=En.triangulateShape(ee,$)}let at=et.length,nt=m+_;for(let ee=0;ee<ne;ee++){let $=d?W(S[ee],We[ee],nt):S[ee];x?(C.copy(A.normals[0]).multiplyScalar($.x),E.copy(A.binormals[0]).multiplyScalar($.y),I.copy(y[0]).add(C).add(E),Pe(I.x,I.y,I.z)):Pe($.x,$.y,0)}for(let ee=1;ee<=h;ee++)for(let $=0;$<ne;$++){let J=d?W(S[$],We[$],nt):S[$];x?(C.copy(A.normals[ee]).multiplyScalar(J.x),E.copy(A.binormals[ee]).multiplyScalar(J.y),I.copy(y[ee]).add(C).add(E),Pe(I.x,I.y,I.z)):Pe(J.x,J.y,u/h*ee)}for(let ee=g-1;ee>=0;ee--){let $=ee/g,J=f*Math.cos($*Math.PI/2),K=m*Math.sin($*Math.PI/2)+_;for(let le=0,ie=q.length;le<ie;le++){let he=W(q[le],de[le],K);Pe(he.x,he.y,u+J)}for(let le=0,ie=L.length;le<ie;le++){let he=L[le];Se=xe[le];for(let He=0,ke=he.length;He<ke;He++){let R=W(he[He],Se[He],K);x?Pe(R.x,R.y+y[h-1].y,y[h-1].x+J):Pe(R.x,R.y,u+J)}}}Z(),te();function Z(){let ee=i.length/3;if(d){let $=0,J=ne*$;for(let K=0;K<at;K++){let le=et[K];Ee(le[2]+J,le[1]+J,le[0]+J)}$=h+g*2,J=ne*$;for(let K=0;K<at;K++){let le=et[K];Ee(le[0]+J,le[1]+J,le[2]+J)}}else{for(let $=0;$<at;$++){let J=et[$];Ee(J[2],J[1],J[0])}for(let $=0;$<at;$++){let J=et[$];Ee(J[0]+ne*h,J[1]+ne*h,J[2]+ne*h)}}n.addGroup(ee,i.length/3-ee,0)}function te(){let ee=i.length/3,$=0;Me(q,$),$+=q.length;for(let J=0,K=L.length;J<K;J++){let le=L[J];Me(le,$),$+=le.length}n.addGroup(ee,i.length/3-ee,1)}function Me(ee,$){let J=ee.length;for(;--J>=0;){let K=J,le=J-1;le<0&&(le=ee.length-1);for(let ie=0,he=h+g*2;ie<he;ie++){let He=ne*ie,ke=ne*(ie+1),R=$+K+He,M=$+le+He,O=$+le+ke,V=$+K+ke;Je(R,M,O,V)}}}function Pe(ee,$,J){c.push(ee),c.push($),c.push(J)}function Ee(ee,$,J){ut(ee),ut($),ut(J);let K=i.length/3,le=v.generateTopUV(n,i,K-3,K-2,K-1);P(le[0]),P(le[1]),P(le[2])}function Je(ee,$,J,K){ut(ee),ut($),ut(K),ut($),ut(J),ut(K);let le=i.length/3,ie=v.generateSideWallUV(n,i,le-6,le-3,le-2,le-1);P(ie[0]),P(ie[1]),P(ie[3]),P(ie[1]),P(ie[2]),P(ie[3])}function ut(ee){i.push(c[ee*3+0]),i.push(c[ee*3+1]),i.push(c[ee*3+2])}function P(ee){s.push(ee.x),s.push(ee.y)}}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}toJSON(){let e=super.toJSON(),t=this.parameters.shapes,n=this.parameters.options;return $_(t,n,e)}static fromJSON(e,t){let n=[];for(let s=0,o=e.shapes.length;s<o;s++){let a=t[e.shapes[s]];n.push(a)}let i=e.options.extrudePath;return i!==void 0&&(e.options.extrudePath=new Pl[i.type]().fromJSON(i)),new r(n,e.options)}},J_={generateTopUV:function(r,e,t,n,i){let s=e[t*3],o=e[t*3+1],a=e[n*3],c=e[n*3+1],l=e[i*3],h=e[i*3+1];return[new Y(s,o),new Y(a,c),new Y(l,h)]},generateSideWallUV:function(r,e,t,n,i,s){let o=e[t*3],a=e[t*3+1],c=e[t*3+2],l=e[n*3],h=e[n*3+1],u=e[n*3+2],d=e[i*3],f=e[i*3+1],m=e[i*3+2],_=e[s*3],g=e[s*3+1],p=e[s*3+2];return Math.abs(a-h)<Math.abs(o-l)?[new Y(o,1-c),new Y(l,1-u),new Y(d,1-m),new Y(_,1-p)]:[new Y(a,1-c),new Y(h,1-u),new Y(f,1-m),new Y(g,1-p)]}};function $_(r,e,t){if(t.shapes=[],Array.isArray(r))for(let n=0,i=r.length;n<i;n++){let s=r[n];t.shapes.push(s.uuid)}else t.shapes.push(r.uuid);return t.options=Object.assign({},e),e.extrudePath!==void 0&&(t.options.extrudePath=e.extrudePath.toJSON()),t}var $o=class r extends xi{constructor(e=1,t=0){let n=(1+Math.sqrt(5))/2,i=[-1,n,0,1,n,0,-1,-n,0,1,-n,0,0,-1,n,0,1,n,0,-1,-n,0,1,-n,n,0,-1,n,0,1,-n,0,-1,-n,0,1],s=[0,11,5,0,5,1,0,1,7,0,7,10,0,10,11,1,5,9,5,11,4,11,10,2,10,7,6,7,1,8,3,9,4,3,4,2,3,2,6,3,6,8,3,8,9,4,9,5,2,4,11,6,2,10,8,6,7,9,8,1];super(i,s,e,t),this.type="IcosahedronGeometry",this.parameters={radius:e,detail:t}}static fromJSON(e){return new r(e.radius,e.detail)}},jo=class r extends ze{constructor(e=[new Y(0,-.5),new Y(.5,0),new Y(0,.5)],t=12,n=0,i=Math.PI*2){super(),this.type="LatheGeometry",this.parameters={points:e,segments:t,phiStart:n,phiLength:i},t=Math.floor(t),i=Fe(i,0,Math.PI*2);let s=[],o=[],a=[],c=[],l=[],h=1/t,u=new w,d=new Y,f=new w,m=new w,_=new w,g=0,p=0;for(let v=0;v<=e.length-1;v++)switch(v){case 0:g=e[v+1].x-e[v].x,p=e[v+1].y-e[v].y,f.x=p*1,f.y=-g,f.z=p*0,_.copy(f),f.normalize(),c.push(f.x,f.y,f.z);break;case e.length-1:c.push(_.x,_.y,_.z);break;default:g=e[v+1].x-e[v].x,p=e[v+1].y-e[v].y,f.x=p*1,f.y=-g,f.z=p*0,m.copy(f),f.x+=_.x,f.y+=_.y,f.z+=_.z,f.normalize(),c.push(f.x,f.y,f.z),_.copy(m)}for(let v=0;v<=t;v++){let y=n+v*h*i,x=Math.sin(y),A=Math.cos(y);for(let E=0;E<=e.length-1;E++){u.x=e[E].x*x,u.y=e[E].y,u.z=e[E].x*A,o.push(u.x,u.y,u.z),d.x=v/t,d.y=E/(e.length-1),a.push(d.x,d.y);let C=c[3*E+0]*x,I=c[3*E+1],b=c[3*E+0]*A;l.push(C,I,b)}}for(let v=0;v<t;v++)for(let y=0;y<e.length-1;y++){let x=y+v*e.length,A=x,E=x+e.length,C=x+e.length+1,I=x+1;s.push(A,E,I),s.push(C,I,E)}this.setIndex(s),this.setAttribute("position",new ye(o,3)),this.setAttribute("uv",new ye(a,2)),this.setAttribute("normal",new ye(l,3))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new r(e.points,e.segments,e.phiStart,e.phiLength)}},Lr=class r extends xi{constructor(e=1,t=0){let n=[1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1],i=[0,2,4,0,4,3,0,3,5,0,5,2,1,2,5,1,5,3,1,3,4,1,4,2];super(n,i,e,t),this.type="OctahedronGeometry",this.parameters={radius:e,detail:t}}static fromJSON(e){return new r(e.radius,e.detail)}},ws=class r extends ze{constructor(e=1,t=1,n=1,i=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:t,widthSegments:n,heightSegments:i};let s=e/2,o=t/2,a=Math.floor(n),c=Math.floor(i),l=a+1,h=c+1,u=e/a,d=t/c,f=[],m=[],_=[],g=[];for(let p=0;p<h;p++){let v=p*d-o;for(let y=0;y<l;y++){let x=y*u-s;m.push(x,-v,0),_.push(0,0,1),g.push(y/a),g.push(1-p/c)}}for(let p=0;p<c;p++)for(let v=0;v<a;v++){let y=v+l*p,x=v+l*(p+1),A=v+1+l*(p+1),E=v+1+l*p;f.push(y,x,E),f.push(x,A,E)}this.setIndex(f),this.setAttribute("position",new ye(m,3)),this.setAttribute("normal",new ye(_,3)),this.setAttribute("uv",new ye(g,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new r(e.width,e.height,e.widthSegments,e.heightSegments)}},Qo=class r extends ze{constructor(e=.5,t=1,n=32,i=1,s=0,o=Math.PI*2){super(),this.type="RingGeometry",this.parameters={innerRadius:e,outerRadius:t,thetaSegments:n,phiSegments:i,thetaStart:s,thetaLength:o},n=Math.max(3,n),i=Math.max(1,i);let a=[],c=[],l=[],h=[],u=e,d=(t-e)/i,f=new w,m=new Y;for(let _=0;_<=i;_++){for(let g=0;g<=n;g++){let p=s+g/n*o;f.x=u*Math.cos(p),f.y=u*Math.sin(p),c.push(f.x,f.y,f.z),l.push(0,0,1),m.x=(f.x/t+1)/2,m.y=(f.y/t+1)/2,h.push(m.x,m.y)}u+=d}for(let _=0;_<i;_++){let g=_*(n+1);for(let p=0;p<n;p++){let v=p+g,y=v,x=v+n+1,A=v+n+2,E=v+1;a.push(y,x,E),a.push(x,A,E)}}this.setIndex(a),this.setAttribute("position",new ye(c,3)),this.setAttribute("normal",new ye(l,3)),this.setAttribute("uv",new ye(h,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new r(e.innerRadius,e.outerRadius,e.thetaSegments,e.phiSegments,e.thetaStart,e.thetaLength)}},ea=class r extends ze{constructor(e=new Zn([new Y(0,.5),new Y(-.5,-.5),new Y(.5,-.5)]),t=12){super(),this.type="ShapeGeometry",this.parameters={shapes:e,curveSegments:t};let n=[],i=[],s=[],o=[],a=0,c=0;if(Array.isArray(e)===!1)l(e);else for(let h=0;h<e.length;h++)l(e[h]),this.addGroup(a,c,h),a+=c,c=0;this.setIndex(n),this.setAttribute("position",new ye(i,3)),this.setAttribute("normal",new ye(s,3)),this.setAttribute("uv",new ye(o,2));function l(h){let u=i.length/3,d=h.extractPoints(t),f=d.shape,m=d.holes;En.isClockWise(f)===!1&&(f=f.reverse());for(let g=0,p=m.length;g<p;g++){let v=m[g];En.isClockWise(v)===!0&&(m[g]=v.reverse())}let _=En.triangulateShape(f,m);for(let g=0,p=m.length;g<p;g++){let v=m[g];f=f.concat(v)}for(let g=0,p=f.length;g<p;g++){let v=f[g];i.push(v.x,v.y,0),s.push(0,0,1),o.push(v.x,v.y)}for(let g=0,p=_.length;g<p;g++){let v=_[g],y=v[0]+u,x=v[1]+u,A=v[2]+u;n.push(y,x,A),c+=3}}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}toJSON(){let e=super.toJSON(),t=this.parameters.shapes;return j_(t,e)}static fromJSON(e,t){let n=[];for(let i=0,s=e.shapes.length;i<s;i++){let o=t[e.shapes[i]];n.push(o)}return new r(n,e.curveSegments)}};function j_(r,e){if(e.shapes=[],Array.isArray(r))for(let t=0,n=r.length;t<n;t++){let i=r[t];e.shapes.push(i.uuid)}else e.shapes.push(r.uuid);return e}var Dr=class r extends ze{constructor(e=1,t=32,n=16,i=0,s=Math.PI*2,o=0,a=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:e,widthSegments:t,heightSegments:n,phiStart:i,phiLength:s,thetaStart:o,thetaLength:a},t=Math.max(3,Math.floor(t)),n=Math.max(2,Math.floor(n));let c=Math.min(o+a,Math.PI),l=0,h=[],u=new w,d=new w,f=[],m=[],_=[],g=[];for(let p=0;p<=n;p++){let v=[],y=p/n,x=0;p===0&&o===0?x=.5/t:p===n&&c===Math.PI&&(x=-.5/t);for(let A=0;A<=t;A++){let E=A/t;u.x=-e*Math.cos(i+E*s)*Math.sin(o+y*a),u.y=e*Math.cos(o+y*a),u.z=e*Math.sin(i+E*s)*Math.sin(o+y*a),m.push(u.x,u.y,u.z),d.copy(u).normalize(),_.push(d.x,d.y,d.z),g.push(E+x,1-y),v.push(l++)}h.push(v)}for(let p=0;p<n;p++)for(let v=0;v<t;v++){let y=h[p][v+1],x=h[p][v],A=h[p+1][v],E=h[p+1][v+1];(p!==0||o>0)&&f.push(y,x,E),(p!==n-1||c<Math.PI)&&f.push(x,A,E)}this.setIndex(f),this.setAttribute("position",new ye(m,3)),this.setAttribute("normal",new ye(_,3)),this.setAttribute("uv",new ye(g,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new r(e.radius,e.widthSegments,e.heightSegments,e.phiStart,e.phiLength,e.thetaStart,e.thetaLength)}},ta=class r extends xi{constructor(e=1,t=0){let n=[1,1,1,-1,-1,1,-1,1,-1,1,-1,-1],i=[2,1,0,0,3,2,1,3,0,2,3,1];super(n,i,e,t),this.type="TetrahedronGeometry",this.parameters={radius:e,detail:t}}static fromJSON(e){return new r(e.radius,e.detail)}},na=class r extends ze{constructor(e=1,t=.4,n=12,i=48,s=Math.PI*2){super(),this.type="TorusGeometry",this.parameters={radius:e,tube:t,radialSegments:n,tubularSegments:i,arc:s},n=Math.floor(n),i=Math.floor(i);let o=[],a=[],c=[],l=[],h=new w,u=new w,d=new w;for(let f=0;f<=n;f++)for(let m=0;m<=i;m++){let _=m/i*s,g=f/n*Math.PI*2;u.x=(e+t*Math.cos(g))*Math.cos(_),u.y=(e+t*Math.cos(g))*Math.sin(_),u.z=t*Math.sin(g),a.push(u.x,u.y,u.z),h.x=e*Math.cos(_),h.y=e*Math.sin(_),d.subVectors(u,h).normalize(),c.push(d.x,d.y,d.z),l.push(m/i),l.push(f/n)}for(let f=1;f<=n;f++)for(let m=1;m<=i;m++){let _=(i+1)*f+m-1,g=(i+1)*(f-1)+m-1,p=(i+1)*(f-1)+m,v=(i+1)*f+m;o.push(_,g,v),o.push(g,p,v)}this.setIndex(o),this.setAttribute("position",new ye(a,3)),this.setAttribute("normal",new ye(c,3)),this.setAttribute("uv",new ye(l,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new r(e.radius,e.tube,e.radialSegments,e.tubularSegments,e.arc)}},ia=class r extends ze{constructor(e=1,t=.4,n=64,i=8,s=2,o=3){super(),this.type="TorusKnotGeometry",this.parameters={radius:e,tube:t,tubularSegments:n,radialSegments:i,p:s,q:o},n=Math.floor(n),i=Math.floor(i);let a=[],c=[],l=[],h=[],u=new w,d=new w,f=new w,m=new w,_=new w,g=new w,p=new w;for(let y=0;y<=n;++y){let x=y/n*s*Math.PI*2;v(x,s,o,e,f),v(x+.01,s,o,e,m),g.subVectors(m,f),p.addVectors(m,f),_.crossVectors(g,p),p.crossVectors(_,g),_.normalize(),p.normalize();for(let A=0;A<=i;++A){let E=A/i*Math.PI*2,C=-t*Math.cos(E),I=t*Math.sin(E);u.x=f.x+(C*p.x+I*_.x),u.y=f.y+(C*p.y+I*_.y),u.z=f.z+(C*p.z+I*_.z),c.push(u.x,u.y,u.z),d.subVectors(u,f).normalize(),l.push(d.x,d.y,d.z),h.push(y/n),h.push(A/i)}}for(let y=1;y<=n;y++)for(let x=1;x<=i;x++){let A=(i+1)*(y-1)+(x-1),E=(i+1)*y+(x-1),C=(i+1)*y+x,I=(i+1)*(y-1)+x;a.push(A,E,I),a.push(E,C,I)}this.setIndex(a),this.setAttribute("position",new ye(c,3)),this.setAttribute("normal",new ye(l,3)),this.setAttribute("uv",new ye(h,2));function v(y,x,A,E,C){let I=Math.cos(y),b=Math.sin(y),S=A/x*y,L=Math.cos(S);C.x=E*(2+L)*.5*I,C.y=E*(2+L)*b*.5,C.z=E*Math.sin(S)*.5}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new r(e.radius,e.tube,e.tubularSegments,e.radialSegments,e.p,e.q)}},sa=class r extends ze{constructor(e=new Cr(new w(-1,-1,0),new w(-1,1,0),new w(1,1,0)),t=64,n=1,i=8,s=!1){super(),this.type="TubeGeometry",this.parameters={path:e,tubularSegments:t,radius:n,radialSegments:i,closed:s};let o=e.computeFrenetFrames(t,s);this.tangents=o.tangents,this.normals=o.normals,this.binormals=o.binormals;let a=new w,c=new w,l=new Y,h=new w,u=[],d=[],f=[],m=[];_(),this.setIndex(m),this.setAttribute("position",new ye(u,3)),this.setAttribute("normal",new ye(d,3)),this.setAttribute("uv",new ye(f,2));function _(){for(let y=0;y<t;y++)g(y);g(s===!1?t:0),v(),p()}function g(y){h=e.getPointAt(y/t,h);let x=o.normals[y],A=o.binormals[y];for(let E=0;E<=i;E++){let C=E/i*Math.PI*2,I=Math.sin(C),b=-Math.cos(C);c.x=b*x.x+I*A.x,c.y=b*x.y+I*A.y,c.z=b*x.z+I*A.z,c.normalize(),d.push(c.x,c.y,c.z),a.x=h.x+n*c.x,a.y=h.y+n*c.y,a.z=h.z+n*c.z,u.push(a.x,a.y,a.z)}}function p(){for(let y=1;y<=t;y++)for(let x=1;x<=i;x++){let A=(i+1)*(y-1)+(x-1),E=(i+1)*y+(x-1),C=(i+1)*y+x,I=(i+1)*(y-1)+x;m.push(A,E,I),m.push(E,C,I)}}function v(){for(let y=0;y<=t;y++)for(let x=0;x<=i;x++)l.x=y/t,l.y=x/i,f.push(l.x,l.y)}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}toJSON(){let e=super.toJSON();return e.path=this.parameters.path.toJSON(),e}static fromJSON(e){return new r(new Pl[e.path.type]().fromJSON(e.path),e.tubularSegments,e.radius,e.radialSegments,e.closed)}},ra=class extends ze{constructor(e=null){if(super(),this.type="WireframeGeometry",this.parameters={geometry:e},e!==null){let t=[],n=new Set,i=new w,s=new w;if(e.index!==null){let o=e.attributes.position,a=e.index,c=e.groups;c.length===0&&(c=[{start:0,count:a.count,materialIndex:0}]);for(let l=0,h=c.length;l<h;++l){let u=c[l],d=u.start,f=u.count;for(let m=d,_=d+f;m<_;m+=3)for(let g=0;g<3;g++){let p=a.getX(m+g),v=a.getX(m+(g+1)%3);i.fromBufferAttribute(o,p),s.fromBufferAttribute(o,v),Ip(i,s,n)===!0&&(t.push(i.x,i.y,i.z),t.push(s.x,s.y,s.z))}}}else{let o=e.attributes.position;for(let a=0,c=o.count/3;a<c;a++)for(let l=0;l<3;l++){let h=3*a+l,u=3*a+(l+1)%3;i.fromBufferAttribute(o,h),s.fromBufferAttribute(o,u),Ip(i,s,n)===!0&&(t.push(i.x,i.y,i.z),t.push(s.x,s.y,s.z))}}this.setAttribute("position",new ye(t,3))}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}};function Ip(r,e,t){let n=`${r.x},${r.y},${r.z}-${e.x},${e.y},${e.z}`,i=`${e.x},${e.y},${e.z}-${r.x},${r.y},${r.z}`;return t.has(n)===!0||t.has(i)===!0?!1:(t.add(n),t.add(i),!0)}var Pp=Object.freeze({__proto__:null,BoxGeometry:Vi,CapsuleGeometry:Bo,CircleGeometry:zo,ConeGeometry:Er,CylinderGeometry:Tr,DodecahedronGeometry:ko,EdgesGeometry:Vo,ExtrudeGeometry:Jo,IcosahedronGeometry:$o,LatheGeometry:jo,OctahedronGeometry:Lr,PlaneGeometry:ws,PolyhedronGeometry:xi,RingGeometry:Qo,ShapeGeometry:ea,SphereGeometry:Dr,TetrahedronGeometry:ta,TorusGeometry:na,TorusKnotGeometry:ia,TubeGeometry:sa,WireframeGeometry:ra}),oa=class extends Mt{constructor(e){super(),this.isShadowMaterial=!0,this.type="ShadowMaterial",this.color=new ue(0),this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.fog=e.fog,this}},aa=class extends on{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}},yi=class extends Mt{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new ue(16777215),this.roughness=1,this.metalness=0,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new ue(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Ei,this.normalScale=new Y(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new rn,this.envMapIntensity=1,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={STANDARD:""},this.color.copy(e.color),this.roughness=e.roughness,this.metalness=e.metalness,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.roughnessMap=e.roughnessMap,this.metalnessMap=e.metalnessMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.envMapIntensity=e.envMapIntensity,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}},Gt=class extends yi{constructor(e){super(),this.isMeshPhysicalMaterial=!0,this.defines={STANDARD:"",PHYSICAL:""},this.type="MeshPhysicalMaterial",this.anisotropyRotation=0,this.anisotropyMap=null,this.clearcoatMap=null,this.clearcoatRoughness=0,this.clearcoatRoughnessMap=null,this.clearcoatNormalScale=new Y(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return Fe(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(t){this.ior=(1+.4*t)/(1-.4*t)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new ue(0),this.sheenColorMap=null,this.sheenRoughness=1,this.sheenRoughnessMap=null,this.transmissionMap=null,this.thickness=0,this.thicknessMap=null,this.attenuationDistance=1/0,this.attenuationColor=new ue(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new ue(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._dispersion=0,this._iridescence=0,this._sheen=0,this._transmission=0,this.setValues(e)}get anisotropy(){return this._anisotropy}set anisotropy(e){this._anisotropy>0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}},ca=class extends Mt{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new ue(16777215),this.specular=new ue(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new ue(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Ei,this.normalScale=new Y(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new rn,this.combine=Gr,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}},la=class extends Mt{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new ue(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new ue(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Ei,this.normalScale=new Y(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.gradientMap=e.gradientMap,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}},ha=class extends Mt{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Ei,this.normalScale=new Y(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(e)}copy(e){return super.copy(e),this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this}},ua=class extends Mt{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new ue(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new ue(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Ei,this.normalScale=new Y(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new rn,this.combine=Gr,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}},Nr=class extends Mt{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=Md,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}},Ur=class extends Mt{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}},da=class extends Mt{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new ue(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Ei,this.normalScale=new Y(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={MATCAP:""},this.color.copy(e.color),this.matcap=e.matcap,this.map=e.map,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.flatShading=e.flatShading,this.fog=e.fog,this}},fa=class extends Pt{constructor(e){super(),this.isLineDashedMaterial=!0,this.type="LineDashedMaterial",this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(e)}copy(e){return super.copy(e),this.scale=e.scale,this.dashSize=e.dashSize,this.gapSize=e.gapSize,this}};function cs(r,e){return!r||r.constructor===e?r:typeof e.BYTES_PER_ELEMENT=="number"?new e(r):Array.prototype.slice.call(r)}function Bm(r){return ArrayBuffer.isView(r)&&!(r instanceof DataView)}function zm(r){function e(i,s){return r[i]-r[s]}let t=r.length,n=new Array(t);for(let i=0;i!==t;++i)n[i]=i;return n.sort(e),n}function Du(r,e,t){let n=r.length,i=new r.constructor(n);for(let s=0,o=0;o!==n;++s){let a=t[s]*e;for(let c=0;c!==e;++c)i[o++]=r[a+c]}return i}function Od(r,e,t,n){let i=1,s=r[0];for(;s!==void 0&&s[n]===void 0;)s=r[i++];if(s===void 0)return;let o=s[n];if(o!==void 0)if(Array.isArray(o))do o=s[n],o!==void 0&&(e.push(s.time),t.push(...o)),s=r[i++];while(s!==void 0);else if(o.toArray!==void 0)do o=s[n],o!==void 0&&(e.push(s.time),o.toArray(t,t.length)),s=r[i++];while(s!==void 0);else do o=s[n],o!==void 0&&(e.push(s.time),t.push(o)),s=r[i++];while(s!==void 0)}function Q_(r,e,t,n,i=30){let s=r.clone();s.name=e;let o=[];for(let c=0;c<s.tracks.length;++c){let l=s.tracks[c],h=l.getValueSize(),u=[],d=[];for(let f=0;f<l.times.length;++f){let m=l.times[f]*i;if(!(m<t||m>=n)){u.push(l.times[f]);for(let _=0;_<h;++_)d.push(l.values[f*h+_])}}u.length!==0&&(l.times=cs(u,l.times.constructor),l.values=cs(d,l.values.constructor),o.push(l))}s.tracks=o;let a=1/0;for(let c=0;c<s.tracks.length;++c)a>s.tracks[c].times[0]&&(a=s.tracks[c].times[0]);for(let c=0;c<s.tracks.length;++c)s.tracks[c].shift(-1*a);return s.resetDuration(),s}function ex(r,e=0,t=r,n=30){n<=0&&(n=30);let i=t.tracks.length,s=e/n;for(let o=0;o<i;++o){let a=t.tracks[o],c=a.ValueTypeName;if(c==="bool"||c==="string")continue;let l=r.tracks.find(function(p){return p.name===a.name&&p.ValueTypeName===c});if(l===void 0)continue;let h=0,u=a.getValueSize();a.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline&&(h=u/3);let d=0,f=l.getValueSize();l.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline&&(d=f/3);let m=a.times.length-1,_;if(s<=a.times[0]){let p=h,v=u-h;_=a.values.slice(p,v)}else if(s>=a.times[m]){let p=m*u+h,v=p+u-h;_=a.values.slice(p,v)}else{let p=a.createInterpolant(),v=h,y=u-h;p.evaluate(s),_=p.resultBuffer.slice(v,y)}c==="quaternion"&&new vt().fromArray(_).normalize().conjugate().toArray(_);let g=l.times.length;for(let p=0;p<g;++p){let v=p*f+d;if(c==="quaternion")vt.multiplyQuaternionsFlat(l.values,v,_,0,l.values,v);else{let y=f-d*2;for(let x=0;x<y;++x)l.values[v+x]-=_[x]}}}return r.blendMode=Ch,r}var Ll=class{static convertArray(e,t){return cs(e,t)}static isTypedArray(e){return Bm(e)}static getKeyframeOrder(e){return zm(e)}static sortedArray(e,t,n){return Du(e,t,n)}static flattenJSON(e,t,n,i){Od(e,t,n,i)}static subclip(e,t,n,i,s=30){return Q_(e,t,n,i,s)}static makeClipAdditive(e,t=0,n=e,i=30){return ex(e,t,n,i)}},$n=class{constructor(e,t,n,i){this.parameterPositions=e,this._cachedIndex=0,this.resultBuffer=i!==void 0?i:new t.constructor(n),this.sampleValues=t,this.valueSize=n,this.settings=null,this.DefaultSettings_={}}evaluate(e){let t=this.parameterPositions,n=this._cachedIndex,i=t[n],s=t[n-1];e:{t:{let o;n:{i:if(!(e<i)){for(let a=n+2;;){if(i===void 0){if(e<s)break i;return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}if(n===a)break;if(s=i,i=t[++n],e<i)break t}o=t.length;break n}if(!(e>=s)){let a=t[1];e<a&&(n=2,s=a);for(let c=n-2;;){if(s===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(n===c)break;if(i=s,s=t[--n-1],e>=s)break t}o=n,n=0;break n}break e}for(;n<o;){let a=n+o>>>1;e<t[a]?o=a:n=a+1}if(i=t[n],s=t[n-1],s===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(i===void 0)return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}this._cachedIndex=n,this.intervalChanged_(n,s,i)}return this.interpolate_(n,s,e,i)}getSettings_(){return this.settings||this.DefaultSettings_}copySampleValue_(e){let t=this.resultBuffer,n=this.sampleValues,i=this.valueSize,s=e*i;for(let o=0;o!==i;++o)t[o]=n[s+o];return t}interpolate_(){throw new Error("call to abstract method")}intervalChanged_(){}},pa=class extends $n{constructor(e,t,n,i){super(e,t,n,i),this._weightPrev=-0,this._offsetPrev=-0,this._weightNext=-0,this._offsetNext=-0,this.DefaultSettings_={endingStart:Ni,endingEnd:Ni}}intervalChanged_(e,t,n){let i=this.parameterPositions,s=e-2,o=e+1,a=i[s],c=i[o];if(a===void 0)switch(this.getSettings_().endingStart){case Ui:s=e,a=2*t-n;break;case fr:s=i.length-2,a=t+i[s]-i[s+1];break;default:s=e,a=n}if(c===void 0)switch(this.getSettings_().endingEnd){case Ui:o=e,c=2*n-t;break;case fr:o=1,c=n+i[1]-i[0];break;default:o=e-1,c=t}let l=(n-t)*.5,h=this.valueSize;this._weightPrev=l/(t-a),this._weightNext=l/(c-n),this._offsetPrev=s*h,this._offsetNext=o*h}interpolate_(e,t,n,i){let s=this.resultBuffer,o=this.sampleValues,a=this.valueSize,c=e*a,l=c-a,h=this._offsetPrev,u=this._offsetNext,d=this._weightPrev,f=this._weightNext,m=(n-t)/(i-t),_=m*m,g=_*m,p=-d*g+2*d*_-d*m,v=(1+d)*g+(-1.5-2*d)*_+(-.5+d)*m+1,y=(-1-f)*g+(1.5+f)*_+.5*m,x=f*g-f*_;for(let A=0;A!==a;++A)s[A]=p*o[h+A]+v*o[l+A]+y*o[c+A]+x*o[u+A];return s}},Fr=class extends $n{constructor(e,t,n,i){super(e,t,n,i)}interpolate_(e,t,n,i){let s=this.resultBuffer,o=this.sampleValues,a=this.valueSize,c=e*a,l=c-a,h=(n-t)/(i-t),u=1-h;for(let d=0;d!==a;++d)s[d]=o[l+d]*u+o[c+d]*h;return s}},ma=class extends $n{constructor(e,t,n,i){super(e,t,n,i)}interpolate_(e){return this.copySampleValue_(e-1)}},jt=class{constructor(e,t,n,i){if(e===void 0)throw new Error("THREE.KeyframeTrack: track name is undefined");if(t===void 0||t.length===0)throw new Error("THREE.KeyframeTrack: no keyframes in track named "+e);this.name=e,this.times=cs(t,this.TimeBufferType),this.values=cs(n,this.ValueBufferType),this.setInterpolation(i||this.DefaultInterpolation)}static toJSON(e){let t=e.constructor,n;if(t.toJSON!==this.toJSON)n=t.toJSON(e);else{n={name:e.name,times:cs(e.times,Array),values:cs(e.values,Array)};let i=e.getInterpolation();i!==e.DefaultInterpolation&&(n.interpolation=i)}return n.type=e.ValueTypeName,n}InterpolantFactoryMethodDiscrete(e){return new ma(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodLinear(e){return new Fr(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodSmooth(e){return new pa(this.times,this.values,this.getValueSize(),e)}setInterpolation(e){let t;switch(e){case zi:t=this.InterpolantFactoryMethodDiscrete;break;case ki:t=this.InterpolantFactoryMethodLinear;break;case Mo:t=this.InterpolantFactoryMethodSmooth;break}if(t===void 0){let n="unsupported interpolation for "+this.ValueTypeName+" keyframe track named "+this.name;if(this.createInterpolant===void 0)if(e!==this.DefaultInterpolation)this.setInterpolation(this.DefaultInterpolation);else throw new Error(n);return console.warn("THREE.KeyframeTrack:",n),this}return this.createInterpolant=t,this}getInterpolation(){switch(this.createInterpolant){case this.InterpolantFactoryMethodDiscrete:return zi;case this.InterpolantFactoryMethodLinear:return ki;case this.InterpolantFactoryMethodSmooth:return Mo}}getValueSize(){return this.values.length/this.times.length}shift(e){if(e!==0){let t=this.times;for(let n=0,i=t.length;n!==i;++n)t[n]+=e}return this}scale(e){if(e!==1){let t=this.times;for(let n=0,i=t.length;n!==i;++n)t[n]*=e}return this}trim(e,t){let n=this.times,i=n.length,s=0,o=i-1;for(;s!==i&&n[s]<e;)++s;for(;o!==-1&&n[o]>t;)--o;if(++o,s!==0||o!==i){s>=o&&(o=Math.max(o,1),s=o-1);let a=this.getValueSize();this.times=n.slice(s,o),this.values=this.values.slice(s*a,o*a)}return this}validate(){let e=!0,t=this.getValueSize();t-Math.floor(t)!==0&&(console.error("THREE.KeyframeTrack: Invalid value size in track.",this),e=!1);let n=this.times,i=this.values,s=n.length;s===0&&(console.error("THREE.KeyframeTrack: Track is empty.",this),e=!1);let o=null;for(let a=0;a!==s;a++){let c=n[a];if(typeof c=="number"&&isNaN(c)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,a,c),e=!1;break}if(o!==null&&o>c){console.error("THREE.KeyframeTrack: Out of order keys.",this,a,c,o),e=!1;break}o=c}if(i!==void 0&&Bm(i))for(let a=0,c=i.length;a!==c;++a){let l=i[a];if(isNaN(l)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,a,l),e=!1;break}}return e}optimize(){let e=this.times.slice(),t=this.values.slice(),n=this.getValueSize(),i=this.getInterpolation()===Mo,s=e.length-1,o=1;for(let a=1;a<s;++a){let c=!1,l=e[a],h=e[a+1];if(l!==h&&(a!==1||l!==e[0]))if(i)c=!0;else{let u=a*n,d=u-n,f=u+n;for(let m=0;m!==n;++m){let _=t[u+m];if(_!==t[d+m]||_!==t[f+m]){c=!0;break}}}if(c){if(a!==o){e[o]=e[a];let u=a*n,d=o*n;for(let f=0;f!==n;++f)t[d+f]=t[u+f]}++o}}if(s>0){e[o]=e[s];for(let a=s*n,c=o*n,l=0;l!==n;++l)t[c+l]=t[a+l];++o}return o!==e.length?(this.times=e.slice(0,o),this.values=t.slice(0,o*n)):(this.times=e,this.values=t),this}clone(){let e=this.times.slice(),t=this.values.slice(),n=this.constructor,i=new n(this.name,e,t);return i.createInterpolant=this.createInterpolant,i}};jt.prototype.ValueTypeName="";jt.prototype.TimeBufferType=Float32Array;jt.prototype.ValueBufferType=Float32Array;jt.prototype.DefaultInterpolation=ki;var jn=class extends jt{constructor(e,t,n){super(e,t,n)}};jn.prototype.ValueTypeName="bool";jn.prototype.ValueBufferType=Array;jn.prototype.DefaultInterpolation=zi;jn.prototype.InterpolantFactoryMethodLinear=void 0;jn.prototype.InterpolantFactoryMethodSmooth=void 0;var Or=class extends jt{constructor(e,t,n,i){super(e,t,n,i)}};Or.prototype.ValueTypeName="color";var zn=class extends jt{constructor(e,t,n,i){super(e,t,n,i)}};zn.prototype.ValueTypeName="number";var ga=class extends $n{constructor(e,t,n,i){super(e,t,n,i)}interpolate_(e,t,n,i){let s=this.resultBuffer,o=this.sampleValues,a=this.valueSize,c=(n-t)/(i-t),l=e*a;for(let h=l+a;l!==h;l+=4)vt.slerpFlat(s,0,o,l-a,o,l,c);return s}},kn=class extends jt{constructor(e,t,n,i){super(e,t,n,i)}InterpolantFactoryMethodLinear(e){return new ga(this.times,this.values,this.getValueSize(),e)}};kn.prototype.ValueTypeName="quaternion";kn.prototype.InterpolantFactoryMethodSmooth=void 0;var Qn=class extends jt{constructor(e,t,n){super(e,t,n)}};Qn.prototype.ValueTypeName="string";Qn.prototype.ValueBufferType=Array;Qn.prototype.DefaultInterpolation=zi;Qn.prototype.InterpolantFactoryMethodLinear=void 0;Qn.prototype.InterpolantFactoryMethodSmooth=void 0;var Vn=class extends jt{constructor(e,t,n,i){super(e,t,n,i)}};Vn.prototype.ValueTypeName="vector";var ei=class{constructor(e="",t=-1,n=[],i=yc){this.name=e,this.tracks=n,this.duration=t,this.blendMode=i,this.uuid=gn(),this.userData={},this.duration<0&&this.resetDuration()}static parse(e){let t=[],n=e.tracks,i=1/(e.fps||1);for(let o=0,a=n.length;o!==a;++o)t.push(nx(n[o]).scale(i));let s=new this(e.name,e.duration,t,e.blendMode);return s.uuid=e.uuid,s.userData=JSON.parse(e.userData||"{}"),s}static toJSON(e){let t=[],n=e.tracks,i={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode,userData:JSON.stringify(e.userData)};for(let s=0,o=n.length;s!==o;++s)t.push(jt.toJSON(n[s]));return i}static CreateFromMorphTargetSequence(e,t,n,i){let s=t.length,o=[];for(let a=0;a<s;a++){let c=[],l=[];c.push((a+s-1)%s,a,(a+1)%s),l.push(0,1,0);let h=zm(c);c=Du(c,1,h),l=Du(l,1,h),!i&&c[0]===0&&(c.push(s),l.push(l[0])),o.push(new zn(".morphTargetInfluences["+t[a].name+"]",c,l).scale(1/n))}return new this(e,-1,o)}static findByName(e,t){let n=e;if(!Array.isArray(e)){let i=e;n=i.geometry&&i.geometry.animations||i.animations}for(let i=0;i<n.length;i++)if(n[i].name===t)return n[i];return null}static CreateClipsFromMorphTargetSequences(e,t,n){let i={},s=/^([\w-]*?)([\d]+)$/;for(let a=0,c=e.length;a<c;a++){let l=e[a],h=l.name.match(s);if(h&&h.length>1){let u=h[1],d=i[u];d||(i[u]=d=[]),d.push(l)}}let o=[];for(let a in i)o.push(this.CreateFromMorphTargetSequence(a,i[a],t,n));return o}static parseAnimation(e,t){if(console.warn("THREE.AnimationClip: parseAnimation() is deprecated and will be removed with r185"),!e)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;let n=function(u,d,f,m,_){if(f.length!==0){let g=[],p=[];Od(f,g,p,m),g.length!==0&&_.push(new u(d,g,p))}},i=[],s=e.name||"default",o=e.fps||30,a=e.blendMode,c=e.length||-1,l=e.hierarchy||[];for(let u=0;u<l.length;u++){let d=l[u].keys;if(!(!d||d.length===0))if(d[0].morphTargets){let f={},m;for(m=0;m<d.length;m++)if(d[m].morphTargets)for(let _=0;_<d[m].morphTargets.length;_++)f[d[m].morphTargets[_]]=-1;for(let _ in f){let g=[],p=[];for(let v=0;v!==d[m].morphTargets.length;++v){let y=d[m];g.push(y.time),p.push(y.morphTarget===_?1:0)}i.push(new zn(".morphTargetInfluence["+_+"]",g,p))}c=f.length*o}else{let f=".bones["+t[u].name+"]";n(Vn,f+".position",d,"pos",i),n(kn,f+".quaternion",d,"rot",i),n(Vn,f+".scale",d,"scl",i)}}return i.length===0?null:new this(s,c,i,a)}resetDuration(){let e=this.tracks,t=0;for(let n=0,i=e.length;n!==i;++n){let s=this.tracks[n];t=Math.max(t,s.times[s.times.length-1])}return this.duration=t,this}trim(){for(let e=0;e<this.tracks.length;e++)this.tracks[e].trim(0,this.duration);return this}validate(){let e=!0;for(let t=0;t<this.tracks.length;t++)e=e&&this.tracks[t].validate();return e}optimize(){for(let e=0;e<this.tracks.length;e++)this.tracks[e].optimize();return this}clone(){let e=[];for(let n=0;n<this.tracks.length;n++)e.push(this.tracks[n].clone());let t=new this.constructor(this.name,this.duration,e,this.blendMode);return t.userData=JSON.parse(JSON.stringify(this.userData)),t}toJSON(){return this.constructor.toJSON(this)}};function tx(r){switch(r.toLowerCase()){case"scalar":case"double":case"float":case"number":case"integer":return zn;case"vector":case"vector2":case"vector3":case"vector4":return Vn;case"color":return Or;case"quaternion":return kn;case"bool":case"boolean":return jn;case"string":return Qn}throw new Error("THREE.KeyframeTrack: Unsupported typeName: "+r)}function nx(r){if(r.type===void 0)throw new Error("THREE.KeyframeTrack: track type undefined, can not parse");let e=tx(r.type);if(r.times===void 0){let t=[],n=[];Od(r.keys,t,n,"value"),r.times=t,r.values=n}return e.parse!==void 0?e.parse(r):new e(r.name,r.times,r.values,r.interpolation)}var Fn={enabled:!1,files:{},add:function(r,e){this.enabled!==!1&&(this.files[r]=e)},get:function(r){if(this.enabled!==!1)return this.files[r]},remove:function(r){delete this.files[r]},clear:function(){this.files={}}},Br=class{constructor(e,t,n){let i=this,s=!1,o=0,a=0,c,l=[];this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=n,this.abortController=new AbortController,this.itemStart=function(h){a++,s===!1&&i.onStart!==void 0&&i.onStart(h,o,a),s=!0},this.itemEnd=function(h){o++,i.onProgress!==void 0&&i.onProgress(h,o,a),o===a&&(s=!1,i.onLoad!==void 0&&i.onLoad())},this.itemError=function(h){i.onError!==void 0&&i.onError(h)},this.resolveURL=function(h){return c?c(h):h},this.setURLModifier=function(h){return c=h,this},this.addHandler=function(h,u){return l.push(h,u),this},this.removeHandler=function(h){let u=l.indexOf(h);return u!==-1&&l.splice(u,2),this},this.getHandler=function(h){for(let u=0,d=l.length;u<d;u+=2){let f=l[u],m=l[u+1];if(f.global&&(f.lastIndex=0),f.test(h))return m}return null},this.abort=function(){return this.abortController.abort(),this.abortController=new AbortController,this}}},Bd=new Br,Lt=class{constructor(e){this.manager=e!==void 0?e:Bd,this.crossOrigin="anonymous",this.withCredentials=!1,this.path="",this.resourcePath="",this.requestHeader={}}load(){}loadAsync(e,t){let n=this;return new Promise(function(i,s){n.load(e,i,t,s)})}parse(){}setCrossOrigin(e){return this.crossOrigin=e,this}setWithCredentials(e){return this.withCredentials=e,this}setPath(e){return this.path=e,this}setResourcePath(e){return this.resourcePath=e,this}setRequestHeader(e){return this.requestHeader=e,this}abort(){return this}};Lt.DEFAULT_MATERIAL_NAME="__DEFAULT";var fi={},Nu=class extends Error{constructor(e,t){super(e),this.response=t}},Qt=class extends Lt{constructor(e){super(e),this.mimeType="",this.responseType="",this._abortController=new AbortController}load(e,t,n,i){e===void 0&&(e=""),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let s=Fn.get(`file:${e}`);if(s!==void 0)return this.manager.itemStart(e),setTimeout(()=>{t&&t(s),this.manager.itemEnd(e)},0),s;if(fi[e]!==void 0){fi[e].push({onLoad:t,onProgress:n,onError:i});return}fi[e]=[],fi[e].push({onLoad:t,onProgress:n,onError:i});let o=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin",signal:typeof AbortSignal.any=="function"?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal}),a=this.mimeType,c=this.responseType;fetch(o).then(l=>{if(l.status===200||l.status===0){if(l.status===0&&console.warn("THREE.FileLoader: HTTP Status 0 received."),typeof ReadableStream>"u"||l.body===void 0||l.body.getReader===void 0)return l;let h=fi[e],u=l.body.getReader(),d=l.headers.get("X-File-Size")||l.headers.get("Content-Length"),f=d?parseInt(d):0,m=f!==0,_=0,g=new ReadableStream({start(p){v();function v(){u.read().then(({done:y,value:x})=>{if(y)p.close();else{_+=x.byteLength;let A=new ProgressEvent("progress",{lengthComputable:m,loaded:_,total:f});for(let E=0,C=h.length;E<C;E++){let I=h[E];I.onProgress&&I.onProgress(A)}p.enqueue(x),v()}},y=>{p.error(y)})}}});return new Response(g)}else throw new Nu(`fetch for "${l.url}" responded with ${l.status}: ${l.statusText}`,l)}).then(l=>{switch(c){case"arraybuffer":return l.arrayBuffer();case"blob":return l.blob();case"document":return l.text().then(h=>new DOMParser().parseFromString(h,a));case"json":return l.json();default:if(a==="")return l.text();{let u=/charset="?([^;"\s]*)"?/i.exec(a),d=u&&u[1]?u[1].toLowerCase():void 0,f=new TextDecoder(d);return l.arrayBuffer().then(m=>f.decode(m))}}}).then(l=>{Fn.add(`file:${e}`,l);let h=fi[e];delete fi[e];for(let u=0,d=h.length;u<d;u++){let f=h[u];f.onLoad&&f.onLoad(l)}}).catch(l=>{let h=fi[e];if(h===void 0)throw this.manager.itemError(e),l;delete fi[e];for(let u=0,d=h.length;u<d;u++){let f=h[u];f.onError&&f.onError(l)}this.manager.itemError(e)}).finally(()=>{this.manager.itemEnd(e)}),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}},Dl=class extends Lt{constructor(e){super(e)}load(e,t,n,i){let s=this,o=new Qt(this.manager);o.setPath(this.path),o.setRequestHeader(this.requestHeader),o.setWithCredentials(this.withCredentials),o.load(e,function(a){try{t(s.parse(JSON.parse(a)))}catch(c){i?i(c):console.error(c),s.manager.itemError(e)}},n,i)}parse(e){let t=[];for(let n=0;n<e.length;n++){let i=ei.parse(e[n]);t.push(i)}return t}},Nl=class extends Lt{constructor(e){super(e)}load(e,t,n,i){let s=this,o=[],a=new bs,c=new Qt(this.manager);c.setPath(this.path),c.setResponseType("arraybuffer"),c.setRequestHeader(this.requestHeader),c.setWithCredentials(s.withCredentials);let l=0;function h(u){c.load(e[u],function(d){let f=s.parse(d,!0);o[u]={width:f.width,height:f.height,format:f.format,mipmaps:f.mipmaps},l+=1,l===6&&(f.mipmapCount===1&&(a.minFilter=mt),a.image=o,a.format=f.format,a.needsUpdate=!0,t&&t(a))},n,i)}if(Array.isArray(e))for(let u=0,d=e.length;u<d;++u)h(u);else c.load(e,function(u){let d=s.parse(u,!0);if(d.isCubemap){let f=d.mipmaps.length/d.mipmapCount;for(let m=0;m<f;m++){o[m]={mipmaps:[]};for(let _=0;_<d.mipmapCount;_++)o[m].mipmaps.push(d.mipmaps[m*d.mipmapCount+_]),o[m].format=d.format,o[m].width=d.width,o[m].height=d.height}a.image=o}else a.image.width=d.width,a.image.height=d.height,a.mipmaps=d.mipmaps;d.mipmapCount===1&&(a.minFilter=mt),a.format=d.format,a.needsUpdate=!0,t&&t(a)},n,i);return a}},cr=new WeakMap,Xi=class extends Lt{constructor(e){super(e)}load(e,t,n,i){this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let s=this,o=Fn.get(`image:${e}`);if(o!==void 0){if(o.complete===!0)s.manager.itemStart(e),setTimeout(function(){t&&t(o),s.manager.itemEnd(e)},0);else{let u=cr.get(o);u===void 0&&(u=[],cr.set(o,u)),u.push({onLoad:t,onError:i})}return o}let a=gr("img");function c(){h(),t&&t(this);let u=cr.get(this)||[];for(let d=0;d<u.length;d++){let f=u[d];f.onLoad&&f.onLoad(this)}cr.delete(this),s.manager.itemEnd(e)}function l(u){h(),i&&i(u),Fn.remove(`image:${e}`);let d=cr.get(this)||[];for(let f=0;f<d.length;f++){let m=d[f];m.onError&&m.onError(u)}cr.delete(this),s.manager.itemError(e),s.manager.itemEnd(e)}function h(){a.removeEventListener("load",c,!1),a.removeEventListener("error",l,!1)}return a.addEventListener("load",c,!1),a.addEventListener("error",l,!1),e.slice(0,5)!=="data:"&&this.crossOrigin!==void 0&&(a.crossOrigin=this.crossOrigin),Fn.add(`image:${e}`,a),s.manager.itemStart(e),a.src=e,a}},Ul=class extends Lt{constructor(e){super(e)}load(e,t,n,i){let s=new Hi;s.colorSpace=wt;let o=new Xi(this.manager);o.setCrossOrigin(this.crossOrigin),o.setPath(this.path);let a=0;function c(l){o.load(e[l],function(h){s.images[l]=h,a++,a===6&&(s.needsUpdate=!0,t&&t(s))},void 0,i)}for(let l=0;l<e.length;++l)c(l);return s}},Fl=class extends Lt{constructor(e){super(e)}load(e,t,n,i){let s=this,o=new _n,a=new Qt(this.manager);return a.setResponseType("arraybuffer"),a.setRequestHeader(this.requestHeader),a.setPath(this.path),a.setWithCredentials(s.withCredentials),a.load(e,function(c){let l;try{l=s.parse(c)}catch(h){if(i!==void 0)i(h);else{console.error(h);return}}l.image!==void 0?o.image=l.image:l.data!==void 0&&(o.image.width=l.width,o.image.height=l.height,o.image.data=l.data),o.wrapS=l.wrapS!==void 0?l.wrapS:Kt,o.wrapT=l.wrapT!==void 0?l.wrapT:Kt,o.magFilter=l.magFilter!==void 0?l.magFilter:mt,o.minFilter=l.minFilter!==void 0?l.minFilter:mt,o.anisotropy=l.anisotropy!==void 0?l.anisotropy:1,l.colorSpace!==void 0&&(o.colorSpace=l.colorSpace),l.flipY!==void 0&&(o.flipY=l.flipY),l.format!==void 0&&(o.format=l.format),l.type!==void 0&&(o.type=l.type),l.mipmaps!==void 0&&(o.mipmaps=l.mipmaps,o.minFilter=cn),l.mipmapCount===1&&(o.minFilter=mt),l.generateMipmaps!==void 0&&(o.generateMipmaps=l.generateMipmaps),o.needsUpdate=!0,t&&t(o,l)},n,i),o}},zr=class extends Lt{constructor(e){super(e)}load(e,t,n,i){let s=new gt,o=new Xi(this.manager);return o.setCrossOrigin(this.crossOrigin),o.setPath(this.path),o.load(e,function(a){s.image=a,s.needsUpdate=!0,t!==void 0&&t(s)},n,i),s}},Hn=class extends Qe{constructor(e,t=1){super(),this.isLight=!0,this.type="Light",this.color=new ue(e),this.intensity=t}dispose(){}copy(e,t){return super.copy(e,t),this.color.copy(e.color),this.intensity=e.intensity,this}toJSON(e){let t=super.toJSON(e);return t.object.color=this.color.getHex(),t.object.intensity=this.intensity,this.groundColor!==void 0&&(t.object.groundColor=this.groundColor.getHex()),this.distance!==void 0&&(t.object.distance=this.distance),this.angle!==void 0&&(t.object.angle=this.angle),this.decay!==void 0&&(t.object.decay=this.decay),this.penumbra!==void 0&&(t.object.penumbra=this.penumbra),this.shadow!==void 0&&(t.object.shadow=this.shadow.toJSON()),this.target!==void 0&&(t.object.target=this.target.uuid),t}},_a=class extends Hn{constructor(e,t,n){super(e,n),this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(Qe.DEFAULT_UP),this.updateMatrix(),this.groundColor=new ue(t)}copy(e,t){return super.copy(e,t),this.groundColor.copy(e.groundColor),this}},Mu=new De,Lp=new w,Dp=new w,xa=class{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new Y(512,512),this.mapType=Cn,this.map=null,this.mapPass=null,this.matrix=new De,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new _i,this._frameExtents=new Y(1,1),this._viewportCount=1,this._viewports=[new tt(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){let t=this.camera,n=this.matrix;Lp.setFromMatrixPosition(e.matrixWorld),t.position.copy(Lp),Dp.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(Dp),t.updateMatrixWorld(),Mu.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(Mu,t.coordinateSystem,t.reversedDepth),t.reversedDepth?n.set(.5,0,0,.5,0,.5,0,.5,0,0,1,0,0,0,0,1):n.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),n.multiply(Mu)}getViewport(e){return this._viewports[e]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(e){return this.camera=e.camera.clone(),this.intensity=e.intensity,this.bias=e.bias,this.radius=e.radius,this.autoUpdate=e.autoUpdate,this.needsUpdate=e.needsUpdate,this.normalBias=e.normalBias,this.blurSamples=e.blurSamples,this.mapSize.copy(e.mapSize),this}clone(){return new this.constructor().copy(this)}toJSON(){let e={};return this.intensity!==1&&(e.intensity=this.intensity),this.bias!==0&&(e.bias=this.bias),this.normalBias!==0&&(e.normalBias=this.normalBias),this.radius!==1&&(e.radius=this.radius),(this.mapSize.x!==512||this.mapSize.y!==512)&&(e.mapSize=this.mapSize.toArray()),e.camera=this.camera.toJSON(!1).object,delete e.camera.matrix,e}},Uu=class extends xa{constructor(){super(new Tt(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1,this.aspect=1}updateMatrices(e){let t=this.camera,n=ds*2*e.angle*this.focus,i=this.mapSize.width/this.mapSize.height*this.aspect,s=e.distance||t.far;(n!==t.fov||i!==t.aspect||s!==t.far)&&(t.fov=n,t.aspect=i,t.far=s,t.updateProjectionMatrix()),super.updateMatrices(e)}copy(e){return super.copy(e),this.focus=e.focus,this}},Rs=class extends Hn{constructor(e,t,n=0,i=Math.PI/3,s=0,o=2){super(e,t),this.isSpotLight=!0,this.type="SpotLight",this.position.copy(Qe.DEFAULT_UP),this.updateMatrix(),this.target=new Qe,this.distance=n,this.angle=i,this.penumbra=s,this.decay=o,this.map=null,this.shadow=new Uu}get power(){return this.intensity*Math.PI}set power(e){this.intensity=e/Math.PI}dispose(){this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.angle=e.angle,this.penumbra=e.penumbra,this.decay=e.decay,this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}},Np=new De,xo=new w,Su=new w,Fu=class extends xa{constructor(){super(new Tt(90,1,.5,500)),this.isPointLightShadow=!0,this._frameExtents=new Y(4,2),this._viewportCount=6,this._viewports=[new tt(2,1,1,1),new tt(0,1,1,1),new tt(3,1,1,1),new tt(1,1,1,1),new tt(3,0,1,1),new tt(1,0,1,1)],this._cubeDirections=[new w(1,0,0),new w(-1,0,0),new w(0,0,1),new w(0,0,-1),new w(0,1,0),new w(0,-1,0)],this._cubeUps=[new w(0,1,0),new w(0,1,0),new w(0,1,0),new w(0,1,0),new w(0,0,1),new w(0,0,-1)]}updateMatrices(e,t=0){let n=this.camera,i=this.matrix,s=e.distance||n.far;s!==n.far&&(n.far=s,n.updateProjectionMatrix()),xo.setFromMatrixPosition(e.matrixWorld),n.position.copy(xo),Su.copy(n.position),Su.add(this._cubeDirections[t]),n.up.copy(this._cubeUps[t]),n.lookAt(Su),n.updateMatrixWorld(),i.makeTranslation(-xo.x,-xo.y,-xo.z),Np.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse),this._frustum.setFromProjectionMatrix(Np,n.coordinateSystem,n.reversedDepth)}},Cs=class extends Hn{constructor(e,t,n=0,i=2){super(e,t),this.isPointLight=!0,this.type="PointLight",this.distance=n,this.decay=i,this.shadow=new Fu}get power(){return this.intensity*4*Math.PI}set power(e){this.intensity=e/(4*Math.PI)}dispose(){this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.decay=e.decay,this.shadow=e.shadow.clone(),this}},vi=class extends gs{constructor(e=-1,t=1,n=1,i=-1,s=.1,o=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=n,this.bottom=i,this.near=s,this.far=o,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,t,n,i,s,o){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=i,this.view.width=s,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),n=(this.right+this.left)/2,i=(this.top+this.bottom)/2,s=n-e,o=n+e,a=i+t,c=i-t;if(this.view!==null&&this.view.enabled){let l=(this.right-this.left)/this.view.fullWidth/this.zoom,h=(this.top-this.bottom)/this.view.fullHeight/this.zoom;s+=l*this.view.offsetX,o=s+l*this.view.width,a-=h*this.view.offsetY,c=a-h*this.view.height}this.projectionMatrix.makeOrthographic(s,o,a,c,this.near,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,this.view!==null&&(t.object.view=Object.assign({},this.view)),t}},Ou=class extends xa{constructor(){super(new vi(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}},Is=class extends Hn{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(Qe.DEFAULT_UP),this.updateMatrix(),this.target=new Qe,this.shadow=new Ou}dispose(){this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}},ya=class extends Hn{constructor(e,t){super(e,t),this.isAmbientLight=!0,this.type="AmbientLight"}},va=class extends Hn{constructor(e,t,n=10,i=10){super(e,t),this.isRectAreaLight=!0,this.type="RectAreaLight",this.width=n,this.height=i}get power(){return this.intensity*this.width*this.height*Math.PI}set power(e){this.intensity=e/(this.width*this.height*Math.PI)}copy(e){return super.copy(e),this.width=e.width,this.height=e.height,this}toJSON(e){let t=super.toJSON(e);return t.object.width=this.width,t.object.height=this.height,t}},Ma=class{constructor(){this.isSphericalHarmonics3=!0,this.coefficients=[];for(let e=0;e<9;e++)this.coefficients.push(new w)}set(e){for(let t=0;t<9;t++)this.coefficients[t].copy(e[t]);return this}zero(){for(let e=0;e<9;e++)this.coefficients[e].set(0,0,0);return this}getAt(e,t){let n=e.x,i=e.y,s=e.z,o=this.coefficients;return t.copy(o[0]).multiplyScalar(.282095),t.addScaledVector(o[1],.488603*i),t.addScaledVector(o[2],.488603*s),t.addScaledVector(o[3],.488603*n),t.addScaledVector(o[4],1.092548*(n*i)),t.addScaledVector(o[5],1.092548*(i*s)),t.addScaledVector(o[6],.315392*(3*s*s-1)),t.addScaledVector(o[7],1.092548*(n*s)),t.addScaledVector(o[8],.546274*(n*n-i*i)),t}getIrradianceAt(e,t){let n=e.x,i=e.y,s=e.z,o=this.coefficients;return t.copy(o[0]).multiplyScalar(.886227),t.addScaledVector(o[1],2*.511664*i),t.addScaledVector(o[2],2*.511664*s),t.addScaledVector(o[3],2*.511664*n),t.addScaledVector(o[4],2*.429043*n*i),t.addScaledVector(o[5],2*.429043*i*s),t.addScaledVector(o[6],.743125*s*s-.247708),t.addScaledVector(o[7],2*.429043*n*s),t.addScaledVector(o[8],.429043*(n*n-i*i)),t}add(e){for(let t=0;t<9;t++)this.coefficients[t].add(e.coefficients[t]);return this}addScaledSH(e,t){for(let n=0;n<9;n++)this.coefficients[n].addScaledVector(e.coefficients[n],t);return this}scale(e){for(let t=0;t<9;t++)this.coefficients[t].multiplyScalar(e);return this}lerp(e,t){for(let n=0;n<9;n++)this.coefficients[n].lerp(e.coefficients[n],t);return this}equals(e){for(let t=0;t<9;t++)if(!this.coefficients[t].equals(e.coefficients[t]))return!1;return!0}copy(e){return this.set(e.coefficients)}clone(){return new this.constructor().copy(this)}fromArray(e,t=0){let n=this.coefficients;for(let i=0;i<9;i++)n[i].fromArray(e,t+i*3);return this}toArray(e=[],t=0){let n=this.coefficients;for(let i=0;i<9;i++)n[i].toArray(e,t+i*3);return e}static getBasisAt(e,t){let n=e.x,i=e.y,s=e.z;t[0]=.282095,t[1]=.488603*i,t[2]=.488603*s,t[3]=.488603*n,t[4]=1.092548*n*i,t[5]=1.092548*i*s,t[6]=.315392*(3*s*s-1),t[7]=1.092548*n*s,t[8]=.546274*(n*n-i*i)}},Sa=class extends Hn{constructor(e=new Ma,t=1){super(void 0,t),this.isLightProbe=!0,this.sh=e}copy(e){return super.copy(e),this.sh.copy(e.sh),this}fromJSON(e){return this.intensity=e.intensity,this.sh.fromArray(e.sh),this}toJSON(e){let t=super.toJSON(e);return t.object.sh=this.sh.toArray(),t}},ba=class r extends Lt{constructor(e){super(e),this.textures={}}load(e,t,n,i){let s=this,o=new Qt(s.manager);o.setPath(s.path),o.setRequestHeader(s.requestHeader),o.setWithCredentials(s.withCredentials),o.load(e,function(a){try{t(s.parse(JSON.parse(a)))}catch(c){i?i(c):console.error(c),s.manager.itemError(e)}},n,i)}parse(e){let t=this.textures;function n(s){return t[s]===void 0&&console.warn("THREE.MaterialLoader: Undefined texture",s),t[s]}let i=this.createMaterialFromType(e.type);if(e.uuid!==void 0&&(i.uuid=e.uuid),e.name!==void 0&&(i.name=e.name),e.color!==void 0&&i.color!==void 0&&i.color.setHex(e.color),e.roughness!==void 0&&(i.roughness=e.roughness),e.metalness!==void 0&&(i.metalness=e.metalness),e.sheen!==void 0&&(i.sheen=e.sheen),e.sheenColor!==void 0&&(i.sheenColor=new ue().setHex(e.sheenColor)),e.sheenRoughness!==void 0&&(i.sheenRoughness=e.sheenRoughness),e.emissive!==void 0&&i.emissive!==void 0&&i.emissive.setHex(e.emissive),e.specular!==void 0&&i.specular!==void 0&&i.specular.setHex(e.specular),e.specularIntensity!==void 0&&(i.specularIntensity=e.specularIntensity),e.specularColor!==void 0&&i.specularColor!==void 0&&i.specularColor.setHex(e.specularColor),e.shininess!==void 0&&(i.shininess=e.shininess),e.clearcoat!==void 0&&(i.clearcoat=e.clearcoat),e.clearcoatRoughness!==void 0&&(i.clearcoatRoughness=e.clearcoatRoughness),e.dispersion!==void 0&&(i.dispersion=e.dispersion),e.iridescence!==void 0&&(i.iridescence=e.iridescence),e.iridescenceIOR!==void 0&&(i.iridescenceIOR=e.iridescenceIOR),e.iridescenceThicknessRange!==void 0&&(i.iridescenceThicknessRange=e.iridescenceThicknessRange),e.transmission!==void 0&&(i.transmission=e.transmission),e.thickness!==void 0&&(i.thickness=e.thickness),e.attenuationDistance!==void 0&&(i.attenuationDistance=e.attenuationDistance),e.attenuationColor!==void 0&&i.attenuationColor!==void 0&&i.attenuationColor.setHex(e.attenuationColor),e.anisotropy!==void 0&&(i.anisotropy=e.anisotropy),e.anisotropyRotation!==void 0&&(i.anisotropyRotation=e.anisotropyRotation),e.fog!==void 0&&(i.fog=e.fog),e.flatShading!==void 0&&(i.flatShading=e.flatShading),e.blending!==void 0&&(i.blending=e.blending),e.combine!==void 0&&(i.combine=e.combine),e.side!==void 0&&(i.side=e.side),e.shadowSide!==void 0&&(i.shadowSide=e.shadowSide),e.opacity!==void 0&&(i.opacity=e.opacity),e.transparent!==void 0&&(i.transparent=e.transparent),e.alphaTest!==void 0&&(i.alphaTest=e.alphaTest),e.alphaHash!==void 0&&(i.alphaHash=e.alphaHash),e.depthFunc!==void 0&&(i.depthFunc=e.depthFunc),e.depthTest!==void 0&&(i.depthTest=e.depthTest),e.depthWrite!==void 0&&(i.depthWrite=e.depthWrite),e.colorWrite!==void 0&&(i.colorWrite=e.colorWrite),e.blendSrc!==void 0&&(i.blendSrc=e.blendSrc),e.blendDst!==void 0&&(i.blendDst=e.blendDst),e.blendEquation!==void 0&&(i.blendEquation=e.blendEquation),e.blendSrcAlpha!==void 0&&(i.blendSrcAlpha=e.blendSrcAlpha),e.blendDstAlpha!==void 0&&(i.blendDstAlpha=e.blendDstAlpha),e.blendEquationAlpha!==void 0&&(i.blendEquationAlpha=e.blendEquationAlpha),e.blendColor!==void 0&&i.blendColor!==void 0&&i.blendColor.setHex(e.blendColor),e.blendAlpha!==void 0&&(i.blendAlpha=e.blendAlpha),e.stencilWriteMask!==void 0&&(i.stencilWriteMask=e.stencilWriteMask),e.stencilFunc!==void 0&&(i.stencilFunc=e.stencilFunc),e.stencilRef!==void 0&&(i.stencilRef=e.stencilRef),e.stencilFuncMask!==void 0&&(i.stencilFuncMask=e.stencilFuncMask),e.stencilFail!==void 0&&(i.stencilFail=e.stencilFail),e.stencilZFail!==void 0&&(i.stencilZFail=e.stencilZFail),e.stencilZPass!==void 0&&(i.stencilZPass=e.stencilZPass),e.stencilWrite!==void 0&&(i.stencilWrite=e.stencilWrite),e.wireframe!==void 0&&(i.wireframe=e.wireframe),e.wireframeLinewidth!==void 0&&(i.wireframeLinewidth=e.wireframeLinewidth),e.wireframeLinecap!==void 0&&(i.wireframeLinecap=e.wireframeLinecap),e.wireframeLinejoin!==void 0&&(i.wireframeLinejoin=e.wireframeLinejoin),e.rotation!==void 0&&(i.rotation=e.rotation),e.linewidth!==void 0&&(i.linewidth=e.linewidth),e.dashSize!==void 0&&(i.dashSize=e.dashSize),e.gapSize!==void 0&&(i.gapSize=e.gapSize),e.scale!==void 0&&(i.scale=e.scale),e.polygonOffset!==void 0&&(i.polygonOffset=e.polygonOffset),e.polygonOffsetFactor!==void 0&&(i.polygonOffsetFactor=e.polygonOffsetFactor),e.polygonOffsetUnits!==void 0&&(i.polygonOffsetUnits=e.polygonOffsetUnits),e.dithering!==void 0&&(i.dithering=e.dithering),e.alphaToCoverage!==void 0&&(i.alphaToCoverage=e.alphaToCoverage),e.premultipliedAlpha!==void 0&&(i.premultipliedAlpha=e.premultipliedAlpha),e.forceSinglePass!==void 0&&(i.forceSinglePass=e.forceSinglePass),e.visible!==void 0&&(i.visible=e.visible),e.toneMapped!==void 0&&(i.toneMapped=e.toneMapped),e.userData!==void 0&&(i.userData=e.userData),e.vertexColors!==void 0&&(typeof e.vertexColors=="number"?i.vertexColors=e.vertexColors>0:i.vertexColors=e.vertexColors),e.uniforms!==void 0)for(let s in e.uniforms){let o=e.uniforms[s];switch(i.uniforms[s]={},o.type){case"t":i.uniforms[s].value=n(o.value);break;case"c":i.uniforms[s].value=new ue().setHex(o.value);break;case"v2":i.uniforms[s].value=new Y().fromArray(o.value);break;case"v3":i.uniforms[s].value=new w().fromArray(o.value);break;case"v4":i.uniforms[s].value=new tt().fromArray(o.value);break;case"m3":i.uniforms[s].value=new Ve().fromArray(o.value);break;case"m4":i.uniforms[s].value=new De().fromArray(o.value);break;default:i.uniforms[s].value=o.value}}if(e.defines!==void 0&&(i.defines=e.defines),e.vertexShader!==void 0&&(i.vertexShader=e.vertexShader),e.fragmentShader!==void 0&&(i.fragmentShader=e.fragmentShader),e.glslVersion!==void 0&&(i.glslVersion=e.glslVersion),e.extensions!==void 0)for(let s in e.extensions)i.extensions[s]=e.extensions[s];if(e.lights!==void 0&&(i.lights=e.lights),e.clipping!==void 0&&(i.clipping=e.clipping),e.size!==void 0&&(i.size=e.size),e.sizeAttenuation!==void 0&&(i.sizeAttenuation=e.sizeAttenuation),e.map!==void 0&&(i.map=n(e.map)),e.matcap!==void 0&&(i.matcap=n(e.matcap)),e.alphaMap!==void 0&&(i.alphaMap=n(e.alphaMap)),e.bumpMap!==void 0&&(i.bumpMap=n(e.bumpMap)),e.bumpScale!==void 0&&(i.bumpScale=e.bumpScale),e.normalMap!==void 0&&(i.normalMap=n(e.normalMap)),e.normalMapType!==void 0&&(i.normalMapType=e.normalMapType),e.normalScale!==void 0){let s=e.normalScale;Array.isArray(s)===!1&&(s=[s,s]),i.normalScale=new Y().fromArray(s)}return e.displacementMap!==void 0&&(i.displacementMap=n(e.displacementMap)),e.displacementScale!==void 0&&(i.displacementScale=e.displacementScale),e.displacementBias!==void 0&&(i.displacementBias=e.displacementBias),e.roughnessMap!==void 0&&(i.roughnessMap=n(e.roughnessMap)),e.metalnessMap!==void 0&&(i.metalnessMap=n(e.metalnessMap)),e.emissiveMap!==void 0&&(i.emissiveMap=n(e.emissiveMap)),e.emissiveIntensity!==void 0&&(i.emissiveIntensity=e.emissiveIntensity),e.specularMap!==void 0&&(i.specularMap=n(e.specularMap)),e.specularIntensityMap!==void 0&&(i.specularIntensityMap=n(e.specularIntensityMap)),e.specularColorMap!==void 0&&(i.specularColorMap=n(e.specularColorMap)),e.envMap!==void 0&&(i.envMap=n(e.envMap)),e.envMapRotation!==void 0&&i.envMapRotation.fromArray(e.envMapRotation),e.envMapIntensity!==void 0&&(i.envMapIntensity=e.envMapIntensity),e.reflectivity!==void 0&&(i.reflectivity=e.reflectivity),e.refractionRatio!==void 0&&(i.refractionRatio=e.refractionRatio),e.lightMap!==void 0&&(i.lightMap=n(e.lightMap)),e.lightMapIntensity!==void 0&&(i.lightMapIntensity=e.lightMapIntensity),e.aoMap!==void 0&&(i.aoMap=n(e.aoMap)),e.aoMapIntensity!==void 0&&(i.aoMapIntensity=e.aoMapIntensity),e.gradientMap!==void 0&&(i.gradientMap=n(e.gradientMap)),e.clearcoatMap!==void 0&&(i.clearcoatMap=n(e.clearcoatMap)),e.clearcoatRoughnessMap!==void 0&&(i.clearcoatRoughnessMap=n(e.clearcoatRoughnessMap)),e.clearcoatNormalMap!==void 0&&(i.clearcoatNormalMap=n(e.clearcoatNormalMap)),e.clearcoatNormalScale!==void 0&&(i.clearcoatNormalScale=new Y().fromArray(e.clearcoatNormalScale)),e.iridescenceMap!==void 0&&(i.iridescenceMap=n(e.iridescenceMap)),e.iridescenceThicknessMap!==void 0&&(i.iridescenceThicknessMap=n(e.iridescenceThicknessMap)),e.transmissionMap!==void 0&&(i.transmissionMap=n(e.transmissionMap)),e.thicknessMap!==void 0&&(i.thicknessMap=n(e.thicknessMap)),e.anisotropyMap!==void 0&&(i.anisotropyMap=n(e.anisotropyMap)),e.sheenColorMap!==void 0&&(i.sheenColorMap=n(e.sheenColorMap)),e.sheenRoughnessMap!==void 0&&(i.sheenRoughnessMap=n(e.sheenRoughnessMap)),i}setTextures(e){return this.textures=e,this}createMaterialFromType(e){return r.createMaterialFromType(e)}static createMaterialFromType(e){let t={ShadowMaterial:oa,SpriteMaterial:Mr,RawShaderMaterial:aa,ShaderMaterial:on,PointsMaterial:Wi,MeshPhysicalMaterial:Gt,MeshStandardMaterial:yi,MeshPhongMaterial:ca,MeshToonMaterial:la,MeshNormalMaterial:ha,MeshLambertMaterial:ua,MeshDepthMaterial:Nr,MeshDistanceMaterial:Ur,MeshBasicMaterial:Bt,MeshMatcapMaterial:da,LineDashedMaterial:fa,LineBasicMaterial:Pt,Material:Mt};return new t[e]}},Rn=class{static extractUrlBase(e){let t=e.lastIndexOf("/");return t===-1?"./":e.slice(0,t+1)}static resolveURL(e,t){return typeof e!="string"||e===""?"":(/^https?:\/\//i.test(t)&&/^\//.test(e)&&(t=t.replace(/(^https?:\/\/[^\/]+).*/i,"$1")),/^(https?:)?\/\//i.test(e)||/^data:.*,.*$/i.test(e)||/^blob:.*$/i.test(e)?e:t+e)}},Ta=class extends ze{constructor(){super(),this.isInstancedBufferGeometry=!0,this.type="InstancedBufferGeometry",this.instanceCount=1/0}copy(e){return super.copy(e),this.instanceCount=e.instanceCount,this}toJSON(){let e=super.toJSON();return e.instanceCount=this.instanceCount,e.isInstancedBufferGeometry=!0,e}},Ea=class extends Lt{constructor(e){super(e)}load(e,t,n,i){let s=this,o=new Qt(s.manager);o.setPath(s.path),o.setRequestHeader(s.requestHeader),o.setWithCredentials(s.withCredentials),o.load(e,function(a){try{t(s.parse(JSON.parse(a)))}catch(c){i?i(c):console.error(c),s.manager.itemError(e)}},n,i)}parse(e){let t={},n={};function i(f,m){if(t[m]!==void 0)return t[m];let g=f.interleavedBuffers[m],p=s(f,g.buffer),v=ur(g.type,p),y=new Jn(v,g.stride);return y.uuid=g.uuid,t[m]=y,y}function s(f,m){if(n[m]!==void 0)return n[m];let g=f.arrayBuffers[m],p=new Uint32Array(g).buffer;return n[m]=p,p}let o=e.isInstancedBufferGeometry?new Ta:new ze,a=e.data.index;if(a!==void 0){let f=ur(a.type,a.array);o.setIndex(new je(f,1))}let c=e.data.attributes;for(let f in c){let m=c[f],_;if(m.isInterleavedBufferAttribute){let g=i(e.data,m.data);_=new Bn(g,m.itemSize,m.offset,m.normalized)}else{let g=ur(m.type,m.array),p=m.isInstancedBufferAttribute?wn:je;_=new p(g,m.itemSize,m.normalized)}m.name!==void 0&&(_.name=m.name),m.usage!==void 0&&_.setUsage(m.usage),o.setAttribute(f,_)}let l=e.data.morphAttributes;if(l)for(let f in l){let m=l[f],_=[];for(let g=0,p=m.length;g<p;g++){let v=m[g],y;if(v.isInterleavedBufferAttribute){let x=i(e.data,v.data);y=new Bn(x,v.itemSize,v.offset,v.normalized)}else{let x=ur(v.type,v.array);y=new je(x,v.itemSize,v.normalized)}v.name!==void 0&&(y.name=v.name),_.push(y)}o.morphAttributes[f]=_}e.data.morphTargetsRelative&&(o.morphTargetsRelative=!0);let u=e.data.groups||e.data.drawcalls||e.data.offsets;if(u!==void 0)for(let f=0,m=u.length;f!==m;++f){let _=u[f];o.addGroup(_.start,_.count,_.materialIndex)}let d=e.data.boundingSphere;return d!==void 0&&(o.boundingSphere=new Et().fromJSON(d)),e.name&&(o.name=e.name),e.userData&&(o.userData=e.userData),o}},Ol=class extends Lt{constructor(e){super(e)}load(e,t,n,i){let s=this,o=this.path===""?Rn.extractUrlBase(e):this.path;this.resourcePath=this.resourcePath||o;let a=new Qt(this.manager);a.setPath(this.path),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(e,function(c){let l=null;try{l=JSON.parse(c)}catch(u){i!==void 0&&i(u),console.error("THREE:ObjectLoader: Can't parse "+e+".",u.message);return}let h=l.metadata;if(h===void 0||h.type===void 0||h.type.toLowerCase()==="geometry"){i!==void 0&&i(new Error("THREE.ObjectLoader: Can't load "+e)),console.error("THREE.ObjectLoader: Can't load "+e);return}s.parse(l,t)},n,i)}async loadAsync(e,t){let n=this,i=this.path===""?Rn.extractUrlBase(e):this.path;this.resourcePath=this.resourcePath||i;let s=new Qt(this.manager);s.setPath(this.path),s.setRequestHeader(this.requestHeader),s.setWithCredentials(this.withCredentials);let o=await s.loadAsync(e,t),a=JSON.parse(o),c=a.metadata;if(c===void 0||c.type===void 0||c.type.toLowerCase()==="geometry")throw new Error("THREE.ObjectLoader: Can't load "+e);return await n.parseAsync(a)}parse(e,t){let n=this.parseAnimations(e.animations),i=this.parseShapes(e.shapes),s=this.parseGeometries(e.geometries,i),o=this.parseImages(e.images,function(){t!==void 0&&t(l)}),a=this.parseTextures(e.textures,o),c=this.parseMaterials(e.materials,a),l=this.parseObject(e.object,s,c,a,n),h=this.parseSkeletons(e.skeletons,l);if(this.bindSkeletons(l,h),this.bindLightTargets(l),t!==void 0){let u=!1;for(let d in o)if(o[d].data instanceof HTMLImageElement){u=!0;break}u===!1&&t(l)}return l}async parseAsync(e){let t=this.parseAnimations(e.animations),n=this.parseShapes(e.shapes),i=this.parseGeometries(e.geometries,n),s=await this.parseImagesAsync(e.images),o=this.parseTextures(e.textures,s),a=this.parseMaterials(e.materials,o),c=this.parseObject(e.object,i,a,o,t),l=this.parseSkeletons(e.skeletons,c);return this.bindSkeletons(c,l),this.bindLightTargets(c),c}parseShapes(e){let t={};if(e!==void 0)for(let n=0,i=e.length;n<i;n++){let s=new Zn().fromJSON(e[n]);t[s.uuid]=s}return t}parseSkeletons(e,t){let n={},i={};if(t.traverse(function(s){s.isBone&&(i[s.uuid]=s)}),e!==void 0)for(let s=0,o=e.length;s<o;s++){let a=new ys().fromJSON(e[s],i);n[a.uuid]=a}return n}parseGeometries(e,t){let n={};if(e!==void 0){let i=new Ea;for(let s=0,o=e.length;s<o;s++){let a,c=e[s];switch(c.type){case"BufferGeometry":case"InstancedBufferGeometry":a=i.parse(c);break;default:c.type in Pp?a=Pp[c.type].fromJSON(c,t):console.warn(`THREE.ObjectLoader: Unsupported geometry type "${c.type}"`)}a.uuid=c.uuid,c.name!==void 0&&(a.name=c.name),c.userData!==void 0&&(a.userData=c.userData),n[c.uuid]=a}}return n}parseMaterials(e,t){let n={},i={};if(e!==void 0){let s=new ba;s.setTextures(t);for(let o=0,a=e.length;o<a;o++){let c=e[o];n[c.uuid]===void 0&&(n[c.uuid]=s.parse(c)),i[c.uuid]=n[c.uuid]}}return i}parseAnimations(e){let t={};if(e!==void 0)for(let n=0;n<e.length;n++){let i=e[n],s=ei.parse(i);t[s.uuid]=s}return t}parseImages(e,t){let n=this,i={},s;function o(c){return n.manager.itemStart(c),s.load(c,function(){n.manager.itemEnd(c)},void 0,function(){n.manager.itemError(c),n.manager.itemEnd(c)})}function a(c){if(typeof c=="string"){let l=c,h=/^(\/\/)|([a-z]+:(\/\/)?)/i.test(l)?l:n.resourcePath+l;return o(h)}else return c.data?{data:ur(c.type,c.data),width:c.width,height:c.height}:null}if(e!==void 0&&e.length>0){let c=new Br(t);s=new Xi(c),s.setCrossOrigin(this.crossOrigin);for(let l=0,h=e.length;l<h;l++){let u=e[l],d=u.url;if(Array.isArray(d)){let f=[];for(let m=0,_=d.length;m<_;m++){let g=d[m],p=a(g);p!==null&&(p instanceof HTMLImageElement?f.push(p):f.push(new _n(p.data,p.width,p.height)))}i[u.uuid]=new Un(f)}else{let f=a(u.url);i[u.uuid]=new Un(f)}}}return i}async parseImagesAsync(e){let t=this,n={},i;async function s(o){if(typeof o=="string"){let a=o,c=/^(\/\/)|([a-z]+:(\/\/)?)/i.test(a)?a:t.resourcePath+a;return await i.loadAsync(c)}else return o.data?{data:ur(o.type,o.data),width:o.width,height:o.height}:null}if(e!==void 0&&e.length>0){i=new Xi(this.manager),i.setCrossOrigin(this.crossOrigin);for(let o=0,a=e.length;o<a;o++){let c=e[o],l=c.url;if(Array.isArray(l)){let h=[];for(let u=0,d=l.length;u<d;u++){let f=l[u],m=await s(f);m!==null&&(m instanceof HTMLImageElement?h.push(m):h.push(new _n(m.data,m.width,m.height)))}n[c.uuid]=new Un(h)}else{let h=await s(c.url);n[c.uuid]=new Un(h)}}}return n}parseTextures(e,t){function n(s,o){return typeof s=="number"?s:(console.warn("THREE.ObjectLoader.parseTexture: Constant should be in numeric form.",s),o[s])}let i={};if(e!==void 0)for(let s=0,o=e.length;s<o;s++){let a=e[s];a.image===void 0&&console.warn('THREE.ObjectLoader: No "image" specified for',a.uuid),t[a.image]===void 0&&console.warn("THREE.ObjectLoader: Undefined image",a.image);let c=t[a.image],l=c.data,h;Array.isArray(l)?(h=new Hi,l.length===6&&(h.needsUpdate=!0)):(l&&l.data?h=new _n:h=new gt,l&&(h.needsUpdate=!0)),h.source=c,h.uuid=a.uuid,a.name!==void 0&&(h.name=a.name),a.mapping!==void 0&&(h.mapping=n(a.mapping,ix)),a.channel!==void 0&&(h.channel=a.channel),a.offset!==void 0&&h.offset.fromArray(a.offset),a.repeat!==void 0&&h.repeat.fromArray(a.repeat),a.center!==void 0&&h.center.fromArray(a.center),a.rotation!==void 0&&(h.rotation=a.rotation),a.wrap!==void 0&&(h.wrapS=n(a.wrap[0],Up),h.wrapT=n(a.wrap[1],Up)),a.format!==void 0&&(h.format=a.format),a.internalFormat!==void 0&&(h.internalFormat=a.internalFormat),a.type!==void 0&&(h.type=a.type),a.colorSpace!==void 0&&(h.colorSpace=a.colorSpace),a.minFilter!==void 0&&(h.minFilter=n(a.minFilter,Fp)),a.magFilter!==void 0&&(h.magFilter=n(a.magFilter,Fp)),a.anisotropy!==void 0&&(h.anisotropy=a.anisotropy),a.flipY!==void 0&&(h.flipY=a.flipY),a.generateMipmaps!==void 0&&(h.generateMipmaps=a.generateMipmaps),a.premultiplyAlpha!==void 0&&(h.premultiplyAlpha=a.premultiplyAlpha),a.unpackAlignment!==void 0&&(h.unpackAlignment=a.unpackAlignment),a.compareFunction!==void 0&&(h.compareFunction=a.compareFunction),a.userData!==void 0&&(h.userData=a.userData),i[a.uuid]=h}return i}parseObject(e,t,n,i,s){let o;function a(d){return t[d]===void 0&&console.warn("THREE.ObjectLoader: Undefined geometry",d),t[d]}function c(d){if(d!==void 0){if(Array.isArray(d)){let f=[];for(let m=0,_=d.length;m<_;m++){let g=d[m];n[g]===void 0&&console.warn("THREE.ObjectLoader: Undefined material",g),f.push(n[g])}return f}return n[d]===void 0&&console.warn("THREE.ObjectLoader: Undefined material",d),n[d]}}function l(d){return i[d]===void 0&&console.warn("THREE.ObjectLoader: Undefined texture",d),i[d]}let h,u;switch(e.type){case"Scene":o=new Lo,e.background!==void 0&&(Number.isInteger(e.background)?o.background=new ue(e.background):o.background=l(e.background)),e.environment!==void 0&&(o.environment=l(e.environment)),e.fog!==void 0&&(e.fog.type==="Fog"?o.fog=new Po(e.fog.color,e.fog.near,e.fog.far):e.fog.type==="FogExp2"&&(o.fog=new Io(e.fog.color,e.fog.density)),e.fog.name!==""&&(o.fog.name=e.fog.name)),e.backgroundBlurriness!==void 0&&(o.backgroundBlurriness=e.backgroundBlurriness),e.backgroundIntensity!==void 0&&(o.backgroundIntensity=e.backgroundIntensity),e.backgroundRotation!==void 0&&o.backgroundRotation.fromArray(e.backgroundRotation),e.environmentIntensity!==void 0&&(o.environmentIntensity=e.environmentIntensity),e.environmentRotation!==void 0&&o.environmentRotation.fromArray(e.environmentRotation);break;case"PerspectiveCamera":o=new Tt(e.fov,e.aspect,e.near,e.far),e.focus!==void 0&&(o.focus=e.focus),e.zoom!==void 0&&(o.zoom=e.zoom),e.filmGauge!==void 0&&(o.filmGauge=e.filmGauge),e.filmOffset!==void 0&&(o.filmOffset=e.filmOffset),e.view!==void 0&&(o.view=Object.assign({},e.view));break;case"OrthographicCamera":o=new vi(e.left,e.right,e.top,e.bottom,e.near,e.far),e.zoom!==void 0&&(o.zoom=e.zoom),e.view!==void 0&&(o.view=Object.assign({},e.view));break;case"AmbientLight":o=new ya(e.color,e.intensity);break;case"DirectionalLight":o=new Is(e.color,e.intensity),o.target=e.target||"";break;case"PointLight":o=new Cs(e.color,e.intensity,e.distance,e.decay);break;case"RectAreaLight":o=new va(e.color,e.intensity,e.width,e.height);break;case"SpotLight":o=new Rs(e.color,e.intensity,e.distance,e.angle,e.penumbra,e.decay),o.target=e.target||"";break;case"HemisphereLight":o=new _a(e.color,e.groundColor,e.intensity);break;case"LightProbe":o=new Sa().fromJSON(e);break;case"SkinnedMesh":h=a(e.geometry),u=c(e.material),o=new xs(h,u),e.bindMode!==void 0&&(o.bindMode=e.bindMode),e.bindMatrix!==void 0&&o.bindMatrix.fromArray(e.bindMatrix),e.skeleton!==void 0&&(o.skeleton=e.skeleton);break;case"Mesh":h=a(e.geometry),u=c(e.material),o=new pt(h,u);break;case"InstancedMesh":h=a(e.geometry),u=c(e.material);let d=e.count,f=e.instanceMatrix,m=e.instanceColor;o=new vs(h,u,d),o.instanceMatrix=new wn(new Float32Array(f.array),16),m!==void 0&&(o.instanceColor=new wn(new Float32Array(m.array),m.itemSize));break;case"BatchedMesh":h=a(e.geometry),u=c(e.material),o=new Fo(e.maxInstanceCount,e.maxVertexCount,e.maxIndexCount,u),o.geometry=h,o.perObjectFrustumCulled=e.perObjectFrustumCulled,o.sortObjects=e.sortObjects,o._drawRanges=e.drawRanges,o._reservedRanges=e.reservedRanges,o._geometryInfo=e.geometryInfo.map(_=>{let g=null,p=null;return _.boundingBox!==void 0&&(g=new Rt().fromJSON(_.boundingBox)),_.boundingSphere!==void 0&&(p=new Et().fromJSON(_.boundingSphere)),{..._,boundingBox:g,boundingSphere:p}}),o._instanceInfo=e.instanceInfo,o._availableInstanceIds=e._availableInstanceIds,o._availableGeometryIds=e._availableGeometryIds,o._nextIndexStart=e.nextIndexStart,o._nextVertexStart=e.nextVertexStart,o._geometryCount=e.geometryCount,o._maxInstanceCount=e.maxInstanceCount,o._maxVertexCount=e.maxVertexCount,o._maxIndexCount=e.maxIndexCount,o._geometryInitialized=e.geometryInitialized,o._matricesTexture=l(e.matricesTexture.uuid),o._indirectTexture=l(e.indirectTexture.uuid),e.colorsTexture!==void 0&&(o._colorsTexture=l(e.colorsTexture.uuid)),e.boundingSphere!==void 0&&(o.boundingSphere=new Et().fromJSON(e.boundingSphere)),e.boundingBox!==void 0&&(o.boundingBox=new Rt().fromJSON(e.boundingBox));break;case"LOD":o=new No;break;case"Line":o=new vn(a(e.geometry),c(e.material));break;case"LineLoop":o=new Ms(a(e.geometry),c(e.material));break;case"LineSegments":o=new $t(a(e.geometry),c(e.material));break;case"PointCloud":case"Points":o=new Ss(a(e.geometry),c(e.material));break;case"Sprite":o=new Do(c(e.material));break;case"Group":o=new mn;break;case"Bone":o=new Gi;break;default:o=new Qe}if(o.uuid=e.uuid,e.name!==void 0&&(o.name=e.name),e.matrix!==void 0?(o.matrix.fromArray(e.matrix),e.matrixAutoUpdate!==void 0&&(o.matrixAutoUpdate=e.matrixAutoUpdate),o.matrixAutoUpdate&&o.matrix.decompose(o.position,o.quaternion,o.scale)):(e.position!==void 0&&o.position.fromArray(e.position),e.rotation!==void 0&&o.rotation.fromArray(e.rotation),e.quaternion!==void 0&&o.quaternion.fromArray(e.quaternion),e.scale!==void 0&&o.scale.fromArray(e.scale)),e.up!==void 0&&o.up.fromArray(e.up),e.castShadow!==void 0&&(o.castShadow=e.castShadow),e.receiveShadow!==void 0&&(o.receiveShadow=e.receiveShadow),e.shadow&&(e.shadow.intensity!==void 0&&(o.shadow.intensity=e.shadow.intensity),e.shadow.bias!==void 0&&(o.shadow.bias=e.shadow.bias),e.shadow.normalBias!==void 0&&(o.shadow.normalBias=e.shadow.normalBias),e.shadow.radius!==void 0&&(o.shadow.radius=e.shadow.radius),e.shadow.mapSize!==void 0&&o.shadow.mapSize.fromArray(e.shadow.mapSize),e.shadow.camera!==void 0&&(o.shadow.camera=this.parseObject(e.shadow.camera))),e.visible!==void 0&&(o.visible=e.visible),e.frustumCulled!==void 0&&(o.frustumCulled=e.frustumCulled),e.renderOrder!==void 0&&(o.renderOrder=e.renderOrder),e.userData!==void 0&&(o.userData=e.userData),e.layers!==void 0&&(o.layers.mask=e.layers),e.children!==void 0){let d=e.children;for(let f=0;f<d.length;f++)o.add(this.parseObject(d[f],t,n,i,s))}if(e.animations!==void 0){let d=e.animations;for(let f=0;f<d.length;f++){let m=d[f];o.animations.push(s[m])}}if(e.type==="LOD"){e.autoUpdate!==void 0&&(o.autoUpdate=e.autoUpdate);let d=e.levels;for(let f=0;f<d.length;f++){let m=d[f],_=o.getObjectByProperty("uuid",m.object);_!==void 0&&o.addLevel(_,m.distance,m.hysteresis)}}return o}bindSkeletons(e,t){Object.keys(t).length!==0&&e.traverse(function(n){if(n.isSkinnedMesh===!0&&n.skeleton!==void 0){let i=t[n.skeleton];i===void 0?console.warn("THREE.ObjectLoader: No skeleton found with UUID:",n.skeleton):n.bind(i,n.bindMatrix)}})}bindLightTargets(e){e.traverse(function(t){if(t.isDirectionalLight||t.isSpotLight){let n=t.target,i=e.getObjectByProperty("uuid",n);i!==void 0?t.target=i:t.target=new Qe}})}},ix={UVMapping:Ba,CubeReflectionMapping:ii,CubeRefractionMapping:bi,EquirectangularReflectionMapping:Wr,EquirectangularRefractionMapping:Xr,CubeUVReflectionMapping:Ls},Up={RepeatWrapping:Kn,ClampToEdgeWrapping:Kt,MirroredRepeatWrapping:Bi},Fp={NearestFilter:Ct,NearestMipmapNearestFilter:qr,NearestMipmapLinearFilter:Ti,LinearFilter:mt,LinearMipmapNearestFilter:qi,LinearMipmapLinearFilter:cn},bu=new WeakMap,kr=class extends Lt{constructor(e){super(e),this.isImageBitmapLoader=!0,typeof createImageBitmap>"u"&&console.warn("THREE.ImageBitmapLoader: createImageBitmap() not supported."),typeof fetch>"u"&&console.warn("THREE.ImageBitmapLoader: fetch() not supported."),this.options={premultiplyAlpha:"none"},this._abortController=new AbortController}setOptions(e){return this.options=e,this}load(e,t,n,i){e===void 0&&(e=""),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let s=this,o=Fn.get(`image-bitmap:${e}`);if(o!==void 0){if(s.manager.itemStart(e),o.then){o.then(l=>{if(bu.has(o)===!0)i&&i(bu.get(o)),s.manager.itemError(e),s.manager.itemEnd(e);else return t&&t(l),s.manager.itemEnd(e),l});return}return setTimeout(function(){t&&t(o),s.manager.itemEnd(e)},0),o}let a={};a.credentials=this.crossOrigin==="anonymous"?"same-origin":"include",a.headers=this.requestHeader,a.signal=typeof AbortSignal.any=="function"?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal;let c=fetch(e,a).then(function(l){return l.blob()}).then(function(l){return createImageBitmap(l,Object.assign(s.options,{colorSpaceConversion:"none"}))}).then(function(l){return Fn.add(`image-bitmap:${e}`,l),t&&t(l),s.manager.itemEnd(e),l}).catch(function(l){i&&i(l),bu.set(c,l),Fn.remove(`image-bitmap:${e}`),s.manager.itemError(e),s.manager.itemEnd(e)});Fn.add(`image-bitmap:${e}`,c),s.manager.itemStart(e)}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}},ol,Vr=class{static getContext(){return ol===void 0&&(ol=new(window.AudioContext||window.webkitAudioContext)),ol}static setContext(e){ol=e}},Bl=class extends Lt{constructor(e){super(e)}load(e,t,n,i){let s=this,o=new Qt(this.manager);o.setResponseType("arraybuffer"),o.setPath(this.path),o.setRequestHeader(this.requestHeader),o.setWithCredentials(this.withCredentials),o.load(e,function(c){try{let l=c.slice(0);Vr.getContext().decodeAudioData(l,function(u){t(u)}).catch(a)}catch(l){a(l)}},n,i);function a(c){i?i(c):console.error(c),s.manager.itemError(e)}}},Op=new De,Bp=new De,ns=new De,zl=class{constructor(){this.type="StereoCamera",this.aspect=1,this.eyeSep=.064,this.cameraL=new Tt,this.cameraL.layers.enable(1),this.cameraL.matrixAutoUpdate=!1,this.cameraR=new Tt,this.cameraR.layers.enable(2),this.cameraR.matrixAutoUpdate=!1,this._cache={focus:null,fov:null,aspect:null,near:null,far:null,zoom:null,eyeSep:null}}update(e){let t=this._cache;if(t.focus!==e.focus||t.fov!==e.fov||t.aspect!==e.aspect*this.aspect||t.near!==e.near||t.far!==e.far||t.zoom!==e.zoom||t.eyeSep!==this.eyeSep){t.focus=e.focus,t.fov=e.fov,t.aspect=e.aspect*this.aspect,t.near=e.near,t.far=e.far,t.zoom=e.zoom,t.eyeSep=this.eyeSep,ns.copy(e.projectionMatrix);let i=t.eyeSep/2,s=i*t.near/t.focus,o=t.near*Math.tan(ls*t.fov*.5)/t.zoom,a,c;Bp.elements[12]=-i,Op.elements[12]=i,a=-o*t.aspect+s,c=o*t.aspect+s,ns.elements[0]=2*t.near/(c-a),ns.elements[8]=(c+a)/(c-a),this.cameraL.projectionMatrix.copy(ns),a=-o*t.aspect-s,c=o*t.aspect-s,ns.elements[0]=2*t.near/(c-a),ns.elements[8]=(c+a)/(c-a),this.cameraR.projectionMatrix.copy(ns)}this.cameraL.matrixWorld.copy(e.matrixWorld).multiply(Bp),this.cameraR.matrixWorld.copy(e.matrixWorld).multiply(Op)}},Aa=class extends Tt{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}},wa=class{constructor(e=!0){this.autoStart=e,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=performance.now(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let e=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){let t=performance.now();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}},is=new w,Tu=new vt,sx=new w,ss=new w,rs=new w,kl=class extends Qe{constructor(){super(),this.type="AudioListener",this.context=Vr.getContext(),this.gain=this.context.createGain(),this.gain.connect(this.context.destination),this.filter=null,this.timeDelta=0,this._clock=new wa}getInput(){return this.gain}removeFilter(){return this.filter!==null&&(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination),this.gain.connect(this.context.destination),this.filter=null),this}getFilter(){return this.filter}setFilter(e){return this.filter!==null?(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination)):this.gain.disconnect(this.context.destination),this.filter=e,this.gain.connect(this.filter),this.filter.connect(this.context.destination),this}getMasterVolume(){return this.gain.gain.value}setMasterVolume(e){return this.gain.gain.setTargetAtTime(e,this.context.currentTime,.01),this}updateMatrixWorld(e){super.updateMatrixWorld(e);let t=this.context.listener;if(this.timeDelta=this._clock.getDelta(),this.matrixWorld.decompose(is,Tu,sx),ss.set(0,0,-1).applyQuaternion(Tu),rs.set(0,1,0).applyQuaternion(Tu),t.positionX){let n=this.context.currentTime+this.timeDelta;t.positionX.linearRampToValueAtTime(is.x,n),t.positionY.linearRampToValueAtTime(is.y,n),t.positionZ.linearRampToValueAtTime(is.z,n),t.forwardX.linearRampToValueAtTime(ss.x,n),t.forwardY.linearRampToValueAtTime(ss.y,n),t.forwardZ.linearRampToValueAtTime(ss.z,n),t.upX.linearRampToValueAtTime(rs.x,n),t.upY.linearRampToValueAtTime(rs.y,n),t.upZ.linearRampToValueAtTime(rs.z,n)}else t.setPosition(is.x,is.y,is.z),t.setOrientation(ss.x,ss.y,ss.z,rs.x,rs.y,rs.z)}},Ra=class extends Qe{constructor(e){super(),this.type="Audio",this.listener=e,this.context=e.context,this.gain=this.context.createGain(),this.gain.connect(e.getInput()),this.autoplay=!1,this.buffer=null,this.detune=0,this.loop=!1,this.loopStart=0,this.loopEnd=0,this.offset=0,this.duration=void 0,this.playbackRate=1,this.isPlaying=!1,this.hasPlaybackControl=!0,this.source=null,this.sourceType="empty",this._startedAt=0,this._progress=0,this._connected=!1,this.filters=[]}getOutput(){return this.gain}setNodeSource(e){return this.hasPlaybackControl=!1,this.sourceType="audioNode",this.source=e,this.connect(),this}setMediaElementSource(e){return this.hasPlaybackControl=!1,this.sourceType="mediaNode",this.source=this.context.createMediaElementSource(e),this.connect(),this}setMediaStreamSource(e){return this.hasPlaybackControl=!1,this.sourceType="mediaStreamNode",this.source=this.context.createMediaStreamSource(e),this.connect(),this}setBuffer(e){return this.buffer=e,this.sourceType="buffer",this.autoplay&&this.play(),this}play(e=0){if(this.isPlaying===!0){console.warn("THREE.Audio: Audio is already playing.");return}if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}this._startedAt=this.context.currentTime+e;let t=this.context.createBufferSource();return t.buffer=this.buffer,t.loop=this.loop,t.loopStart=this.loopStart,t.loopEnd=this.loopEnd,t.onended=this.onEnded.bind(this),t.start(this._startedAt,this._progress+this.offset,this.duration),this.isPlaying=!0,this.source=t,this.setDetune(this.detune),this.setPlaybackRate(this.playbackRate),this.connect()}pause(){if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}return this.isPlaying===!0&&(this._progress+=Math.max(this.context.currentTime-this._startedAt,0)*this.playbackRate,this.loop===!0&&(this._progress=this._progress%(this.duration||this.buffer.duration)),this.source.stop(),this.source.onended=null,this.isPlaying=!1),this}stop(e=0){if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}return this._progress=0,this.source!==null&&(this.source.stop(this.context.currentTime+e),this.source.onended=null),this.isPlaying=!1,this}connect(){if(this.filters.length>0){this.source.connect(this.filters[0]);for(let e=1,t=this.filters.length;e<t;e++)this.filters[e-1].connect(this.filters[e]);this.filters[this.filters.length-1].connect(this.getOutput())}else this.source.connect(this.getOutput());return this._connected=!0,this}disconnect(){if(this._connected!==!1){if(this.filters.length>0){this.source.disconnect(this.filters[0]);for(let e=1,t=this.filters.length;e<t;e++)this.filters[e-1].disconnect(this.filters[e]);this.filters[this.filters.length-1].disconnect(this.getOutput())}else this.source.disconnect(this.getOutput());return this._connected=!1,this}}getFilters(){return this.filters}setFilters(e){return e||(e=[]),this._connected===!0?(this.disconnect(),this.filters=e.slice(),this.connect()):this.filters=e.slice(),this}setDetune(e){return this.detune=e,this.isPlaying===!0&&this.source.detune!==void 0&&this.source.detune.setTargetAtTime(this.detune,this.context.currentTime,.01),this}getDetune(){return this.detune}getFilter(){return this.getFilters()[0]}setFilter(e){return this.setFilters(e?[e]:[])}setPlaybackRate(e){if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}return this.playbackRate=e,this.isPlaying===!0&&this.source.playbackRate.setTargetAtTime(this.playbackRate,this.context.currentTime,.01),this}getPlaybackRate(){return this.playbackRate}onEnded(){this.isPlaying=!1,this._progress=0}getLoop(){return this.hasPlaybackControl===!1?(console.warn("THREE.Audio: this Audio has no playback control."),!1):this.loop}setLoop(e){if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}return this.loop=e,this.isPlaying===!0&&(this.source.loop=this.loop),this}setLoopStart(e){return this.loopStart=e,this}setLoopEnd(e){return this.loopEnd=e,this}getVolume(){return this.gain.gain.value}setVolume(e){return this.gain.gain.setTargetAtTime(e,this.context.currentTime,.01),this}copy(e,t){return super.copy(e,t),e.sourceType!=="buffer"?(console.warn("THREE.Audio: Audio source type cannot be copied."),this):(this.autoplay=e.autoplay,this.buffer=e.buffer,this.detune=e.detune,this.loop=e.loop,this.loopStart=e.loopStart,this.loopEnd=e.loopEnd,this.offset=e.offset,this.duration=e.duration,this.playbackRate=e.playbackRate,this.hasPlaybackControl=e.hasPlaybackControl,this.sourceType=e.sourceType,this.filters=e.filters.slice(),this)}clone(e){return new this.constructor(this.listener).copy(this,e)}},os=new w,zp=new vt,rx=new w,as=new w,Vl=class extends Ra{constructor(e){super(e),this.panner=this.context.createPanner(),this.panner.panningModel="HRTF",this.panner.connect(this.gain)}connect(){return super.connect(),this.panner.connect(this.gain),this}disconnect(){return super.disconnect(),this.panner.disconnect(this.gain),this}getOutput(){return this.panner}getRefDistance(){return this.panner.refDistance}setRefDistance(e){return this.panner.refDistance=e,this}getRolloffFactor(){return this.panner.rolloffFactor}setRolloffFactor(e){return this.panner.rolloffFactor=e,this}getDistanceModel(){return this.panner.distanceModel}setDistanceModel(e){return this.panner.distanceModel=e,this}getMaxDistance(){return this.panner.maxDistance}setMaxDistance(e){return this.panner.maxDistance=e,this}setDirectionalCone(e,t,n){return this.panner.coneInnerAngle=e,this.panner.coneOuterAngle=t,this.panner.coneOuterGain=n,this}updateMatrixWorld(e){if(super.updateMatrixWorld(e),this.hasPlaybackControl===!0&&this.isPlaying===!1)return;this.matrixWorld.decompose(os,zp,rx),as.set(0,0,1).applyQuaternion(zp);let t=this.panner;if(t.positionX){let n=this.context.currentTime+this.listener.timeDelta;t.positionX.linearRampToValueAtTime(os.x,n),t.positionY.linearRampToValueAtTime(os.y,n),t.positionZ.linearRampToValueAtTime(os.z,n),t.orientationX.linearRampToValueAtTime(as.x,n),t.orientationY.linearRampToValueAtTime(as.y,n),t.orientationZ.linearRampToValueAtTime(as.z,n)}else t.setPosition(os.x,os.y,os.z),t.setOrientation(as.x,as.y,as.z)}},Hl=class{constructor(e,t=2048){this.analyser=e.context.createAnalyser(),this.analyser.fftSize=t,this.data=new Uint8Array(this.analyser.frequencyBinCount),e.getOutput().connect(this.analyser)}getFrequencyData(){return this.analyser.getByteFrequencyData(this.data),this.data}getAverageFrequency(){let e=0,t=this.getFrequencyData();for(let n=0;n<t.length;n++)e+=t[n];return e/t.length}},Ca=class{constructor(e,t,n){this.binding=e,this.valueSize=n;let i,s,o;switch(t){case"quaternion":i=this._slerp,s=this._slerpAdditive,o=this._setAdditiveIdentityQuaternion,this.buffer=new Float64Array(n*6),this._workIndex=5;break;case"string":case"bool":i=this._select,s=this._select,o=this._setAdditiveIdentityOther,this.buffer=new Array(n*5);break;default:i=this._lerp,s=this._lerpAdditive,o=this._setAdditiveIdentityNumeric,this.buffer=new Float64Array(n*5)}this._mixBufferRegion=i,this._mixBufferRegionAdditive=s,this._setIdentity=o,this._origIndex=3,this._addIndex=4,this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,this.useCount=0,this.referenceCount=0}accumulate(e,t){let n=this.buffer,i=this.valueSize,s=e*i+i,o=this.cumulativeWeight;if(o===0){for(let a=0;a!==i;++a)n[s+a]=n[a];o=t}else{o+=t;let a=t/o;this._mixBufferRegion(n,s,0,a,i)}this.cumulativeWeight=o}accumulateAdditive(e){let t=this.buffer,n=this.valueSize,i=n*this._addIndex;this.cumulativeWeightAdditive===0&&this._setIdentity(),this._mixBufferRegionAdditive(t,i,0,e,n),this.cumulativeWeightAdditive+=e}apply(e){let t=this.valueSize,n=this.buffer,i=e*t+t,s=this.cumulativeWeight,o=this.cumulativeWeightAdditive,a=this.binding;if(this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,s<1){let c=t*this._origIndex;this._mixBufferRegion(n,i,c,1-s,t)}o>0&&this._mixBufferRegionAdditive(n,i,this._addIndex*t,1,t);for(let c=t,l=t+t;c!==l;++c)if(n[c]!==n[c+t]){a.setValue(n,i);break}}saveOriginalState(){let e=this.binding,t=this.buffer,n=this.valueSize,i=n*this._origIndex;e.getValue(t,i);for(let s=n,o=i;s!==o;++s)t[s]=t[i+s%n];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){let e=this.valueSize*3;this.binding.setValue(this.buffer,e)}_setAdditiveIdentityNumeric(){let e=this._addIndex*this.valueSize,t=e+this.valueSize;for(let n=e;n<t;n++)this.buffer[n]=0}_setAdditiveIdentityQuaternion(){this._setAdditiveIdentityNumeric(),this.buffer[this._addIndex*this.valueSize+3]=1}_setAdditiveIdentityOther(){let e=this._origIndex*this.valueSize,t=this._addIndex*this.valueSize;for(let n=0;n<this.valueSize;n++)this.buffer[t+n]=this.buffer[e+n]}_select(e,t,n,i,s){if(i>=.5)for(let o=0;o!==s;++o)e[t+o]=e[n+o]}_slerp(e,t,n,i){vt.slerpFlat(e,t,e,t,e,n,i)}_slerpAdditive(e,t,n,i,s){let o=this._workIndex*s;vt.multiplyQuaternionsFlat(e,o,e,t,e,n),vt.slerpFlat(e,t,e,t,e,o,i)}_lerp(e,t,n,i,s){let o=1-i;for(let a=0;a!==s;++a){let c=t+a;e[c]=e[c]*o+e[n+a]*i}}_lerpAdditive(e,t,n,i,s){for(let o=0;o!==s;++o){let a=t+o;e[a]=e[a]+e[n+o]*i}}},zd="\\[\\]\\.:\\/",ox=new RegExp("["+zd+"]","g"),kd="[^"+zd+"]",ax="[^"+zd.replace("\\.","")+"]",cx=/((?:WC+[\/:])*)/.source.replace("WC",kd),lx=/(WCOD+)?/.source.replace("WCOD",ax),hx=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",kd),ux=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",kd),dx=new RegExp("^"+cx+lx+hx+ux+"$"),fx=["material","materials","bones","map"],Bu=class{constructor(e,t,n){let i=n||st.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,i)}getValue(e,t){this.bind();let n=this._targetGroup.nCachedObjects_,i=this._bindings[n];i!==void 0&&i.getValue(e,t)}setValue(e,t){let n=this._bindings;for(let i=this._targetGroup.nCachedObjects_,s=n.length;i!==s;++i)n[i].setValue(e,t)}bind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].bind()}unbind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].unbind()}},st=class r{constructor(e,t,n){this.path=t,this.parsedPath=n||r.parseTrackName(t),this.node=r.findNode(e,this.parsedPath.nodeName),this.rootNode=e,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(e,t,n){return e&&e.isAnimationObjectGroup?new r.Composite(e,t,n):new r(e,t,n)}static sanitizeNodeName(e){return e.replace(/\s/g,"_").replace(ox,"")}static parseTrackName(e){let t=dx.exec(e);if(t===null)throw new Error("PropertyBinding: Cannot parse trackName: "+e);let n={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},i=n.nodeName&&n.nodeName.lastIndexOf(".");if(i!==void 0&&i!==-1){let s=n.nodeName.substring(i+1);fx.indexOf(s)!==-1&&(n.nodeName=n.nodeName.substring(0,i),n.objectName=s)}if(n.propertyName===null||n.propertyName.length===0)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+e);return n}static findNode(e,t){if(t===void 0||t===""||t==="."||t===-1||t===e.name||t===e.uuid)return e;if(e.skeleton){let n=e.skeleton.getBoneByName(t);if(n!==void 0)return n}if(e.children){let n=function(s){for(let o=0;o<s.length;o++){let a=s[o];if(a.name===t||a.uuid===t)return a;let c=n(a.children);if(c)return c}return null},i=n(e.children);if(i)return i}return null}_getValue_unavailable(){}_setValue_unavailable(){}_getValue_direct(e,t){e[t]=this.targetObject[this.propertyName]}_getValue_array(e,t){let n=this.resolvedProperty;for(let i=0,s=n.length;i!==s;++i)e[t++]=n[i]}_getValue_arrayElement(e,t){e[t]=this.resolvedProperty[this.propertyIndex]}_getValue_toArray(e,t){this.resolvedProperty.toArray(e,t)}_setValue_direct(e,t){this.targetObject[this.propertyName]=e[t]}_setValue_direct_setNeedsUpdate(e,t){this.targetObject[this.propertyName]=e[t],this.targetObject.needsUpdate=!0}_setValue_direct_setMatrixWorldNeedsUpdate(e,t){this.targetObject[this.propertyName]=e[t],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_array(e,t){let n=this.resolvedProperty;for(let i=0,s=n.length;i!==s;++i)n[i]=e[t++]}_setValue_array_setNeedsUpdate(e,t){let n=this.resolvedProperty;for(let i=0,s=n.length;i!==s;++i)n[i]=e[t++];this.targetObject.needsUpdate=!0}_setValue_array_setMatrixWorldNeedsUpdate(e,t){let n=this.resolvedProperty;for(let i=0,s=n.length;i!==s;++i)n[i]=e[t++];this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_arrayElement(e,t){this.resolvedProperty[this.propertyIndex]=e[t]}_setValue_arrayElement_setNeedsUpdate(e,t){this.resolvedProperty[this.propertyIndex]=e[t],this.targetObject.needsUpdate=!0}_setValue_arrayElement_setMatrixWorldNeedsUpdate(e,t){this.resolvedProperty[this.propertyIndex]=e[t],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_fromArray(e,t){this.resolvedProperty.fromArray(e,t)}_setValue_fromArray_setNeedsUpdate(e,t){this.resolvedProperty.fromArray(e,t),this.targetObject.needsUpdate=!0}_setValue_fromArray_setMatrixWorldNeedsUpdate(e,t){this.resolvedProperty.fromArray(e,t),this.targetObject.matrixWorldNeedsUpdate=!0}_getValue_unbound(e,t){this.bind(),this.getValue(e,t)}_setValue_unbound(e,t){this.bind(),this.setValue(e,t)}bind(){let e=this.node,t=this.parsedPath,n=t.objectName,i=t.propertyName,s=t.propertyIndex;if(e||(e=r.findNode(this.rootNode,t.nodeName),this.node=e),this.getValue=this._getValue_unavailable,this.setValue=this._setValue_unavailable,!e){console.warn("THREE.PropertyBinding: No target node found for track: "+this.path+".");return}if(n){let l=t.objectIndex;switch(n){case"materials":if(!e.material){console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.",this);return}if(!e.material.materials){console.error("THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.",this);return}e=e.material.materials;break;case"bones":if(!e.skeleton){console.error("THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.",this);return}e=e.skeleton.bones;for(let h=0;h<e.length;h++)if(e[h].name===l){l=h;break}break;case"map":if("map"in e){e=e.map;break}if(!e.material){console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.",this);return}if(!e.material.map){console.error("THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.",this);return}e=e.material.map;break;default:if(e[n]===void 0){console.error("THREE.PropertyBinding: Can not bind to objectName of node undefined.",this);return}e=e[n]}if(l!==void 0){if(e[l]===void 0){console.error("THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.",this,e);return}e=e[l]}}let o=e[i];if(o===void 0){let l=t.nodeName;console.error("THREE.PropertyBinding: Trying to update property for track: "+l+"."+i+" but it wasn't found.",e);return}let a=this.Versioning.None;this.targetObject=e,e.isMaterial===!0?a=this.Versioning.NeedsUpdate:e.isObject3D===!0&&(a=this.Versioning.MatrixWorldNeedsUpdate);let c=this.BindingType.Direct;if(s!==void 0){if(i==="morphTargetInfluences"){if(!e.geometry){console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.",this);return}if(!e.geometry.morphAttributes){console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.",this);return}e.morphTargetDictionary[s]!==void 0&&(s=e.morphTargetDictionary[s])}c=this.BindingType.ArrayElement,this.resolvedProperty=o,this.propertyIndex=s}else o.fromArray!==void 0&&o.toArray!==void 0?(c=this.BindingType.HasFromToArray,this.resolvedProperty=o):Array.isArray(o)?(c=this.BindingType.EntireArray,this.resolvedProperty=o):this.propertyName=i;this.getValue=this.GetterByBindingType[c],this.setValue=this.SetterByBindingTypeAndVersioning[c][a]}unbind(){this.node=null,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}};st.Composite=Bu;st.prototype.BindingType={Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3};st.prototype.Versioning={None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2};st.prototype.GetterByBindingType=[st.prototype._getValue_direct,st.prototype._getValue_array,st.prototype._getValue_arrayElement,st.prototype._getValue_toArray];st.prototype.SetterByBindingTypeAndVersioning=[[st.prototype._setValue_direct,st.prototype._setValue_direct_setNeedsUpdate,st.prototype._setValue_direct_setMatrixWorldNeedsUpdate],[st.prototype._setValue_array,st.prototype._setValue_array_setNeedsUpdate,st.prototype._setValue_array_setMatrixWorldNeedsUpdate],[st.prototype._setValue_arrayElement,st.prototype._setValue_arrayElement_setNeedsUpdate,st.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate],[st.prototype._setValue_fromArray,st.prototype._setValue_fromArray_setNeedsUpdate,st.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];var Gl=class{constructor(){this.isAnimationObjectGroup=!0,this.uuid=gn(),this._objects=Array.prototype.slice.call(arguments),this.nCachedObjects_=0;let e={};this._indicesByUUID=e;for(let n=0,i=arguments.length;n!==i;++n)e[arguments[n].uuid]=n;this._paths=[],this._parsedPaths=[],this._bindings=[],this._bindingsIndicesByPath={};let t=this;this.stats={objects:{get total(){return t._objects.length},get inUse(){return this.total-t.nCachedObjects_}},get bindingsPerObject(){return t._bindings.length}}}add(){let e=this._objects,t=this._indicesByUUID,n=this._paths,i=this._parsedPaths,s=this._bindings,o=s.length,a,c=e.length,l=this.nCachedObjects_;for(let h=0,u=arguments.length;h!==u;++h){let d=arguments[h],f=d.uuid,m=t[f];if(m===void 0){m=c++,t[f]=m,e.push(d);for(let _=0,g=o;_!==g;++_)s[_].push(new st(d,n[_],i[_]))}else if(m<l){a=e[m];let _=--l,g=e[_];t[g.uuid]=m,e[m]=g,t[f]=_,e[_]=d;for(let p=0,v=o;p!==v;++p){let y=s[p],x=y[_],A=y[m];y[m]=x,A===void 0&&(A=new st(d,n[p],i[p])),y[_]=A}}else e[m]!==a&&console.error("THREE.AnimationObjectGroup: Different objects with the same UUID detected. Clean the caches or recreate your infrastructure when reloading scenes.")}this.nCachedObjects_=l}remove(){let e=this._objects,t=this._indicesByUUID,n=this._bindings,i=n.length,s=this.nCachedObjects_;for(let o=0,a=arguments.length;o!==a;++o){let c=arguments[o],l=c.uuid,h=t[l];if(h!==void 0&&h>=s){let u=s++,d=e[u];t[d.uuid]=h,e[h]=d,t[l]=u,e[u]=c;for(let f=0,m=i;f!==m;++f){let _=n[f],g=_[u],p=_[h];_[h]=g,_[u]=p}}}this.nCachedObjects_=s}uncache(){let e=this._objects,t=this._indicesByUUID,n=this._bindings,i=n.length,s=this.nCachedObjects_,o=e.length;for(let a=0,c=arguments.length;a!==c;++a){let l=arguments[a],h=l.uuid,u=t[h];if(u!==void 0)if(delete t[h],u<s){let d=--s,f=e[d],m=--o,_=e[m];t[f.uuid]=u,e[u]=f,t[_.uuid]=d,e[d]=_,e.pop();for(let g=0,p=i;g!==p;++g){let v=n[g],y=v[d],x=v[m];v[u]=y,v[d]=x,v.pop()}}else{let d=--o,f=e[d];d>0&&(t[f.uuid]=u),e[u]=f,e.pop();for(let m=0,_=i;m!==_;++m){let g=n[m];g[u]=g[d],g.pop()}}}this.nCachedObjects_=s}subscribe_(e,t){let n=this._bindingsIndicesByPath,i=n[e],s=this._bindings;if(i!==void 0)return s[i];let o=this._paths,a=this._parsedPaths,c=this._objects,l=c.length,h=this.nCachedObjects_,u=new Array(l);i=s.length,n[e]=i,o.push(e),a.push(t),s.push(u);for(let d=h,f=c.length;d!==f;++d){let m=c[d];u[d]=new st(m,e,t)}return u}unsubscribe_(e){let t=this._bindingsIndicesByPath,n=t[e];if(n!==void 0){let i=this._paths,s=this._parsedPaths,o=this._bindings,a=o.length-1,c=o[a],l=e[a];t[l]=n,o[n]=c,o.pop(),s[n]=s[a],s.pop(),i[n]=i[a],i.pop()}}},Ia=class{constructor(e,t,n=null,i=t.blendMode){this._mixer=e,this._clip=t,this._localRoot=n,this.blendMode=i;let s=t.tracks,o=s.length,a=new Array(o),c={endingStart:Ni,endingEnd:Ni};for(let l=0;l!==o;++l){let h=s[l].createInterpolant(null);a[l]=h,h.settings=c}this._interpolantSettings=c,this._interpolants=a,this._propertyBindings=new Array(o),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=yd,this._loopCount=-1,this._startTime=null,this.time=0,this.timeScale=1,this._effectiveTimeScale=1,this.weight=1,this._effectiveWeight=1,this.repetitions=1/0,this.paused=!1,this.enabled=!0,this.clampWhenFinished=!1,this.zeroSlopeAtStart=!0,this.zeroSlopeAtEnd=!0}play(){return this._mixer._activateAction(this),this}stop(){return this._mixer._deactivateAction(this),this.reset()}reset(){return this.paused=!1,this.enabled=!0,this.time=0,this._loopCount=-1,this._startTime=null,this.stopFading().stopWarping()}isRunning(){return this.enabled&&!this.paused&&this.timeScale!==0&&this._startTime===null&&this._mixer._isActiveAction(this)}isScheduled(){return this._mixer._isActiveAction(this)}startAt(e){return this._startTime=e,this}setLoop(e,t){return this.loop=e,this.repetitions=t,this}setEffectiveWeight(e){return this.weight=e,this._effectiveWeight=this.enabled?e:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(e){return this._scheduleFading(e,0,1)}fadeOut(e){return this._scheduleFading(e,1,0)}crossFadeFrom(e,t,n=!1){if(e.fadeOut(t),this.fadeIn(t),n===!0){let i=this._clip.duration,s=e._clip.duration,o=s/i,a=i/s;e.warp(1,o,t),this.warp(a,1,t)}return this}crossFadeTo(e,t,n=!1){return e.crossFadeFrom(this,t,n)}stopFading(){let e=this._weightInterpolant;return e!==null&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}setEffectiveTimeScale(e){return this.timeScale=e,this._effectiveTimeScale=this.paused?0:e,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(e){return this.timeScale=this._clip.duration/e,this.stopWarping()}syncWith(e){return this.time=e.time,this.timeScale=e.timeScale,this.stopWarping()}halt(e){return this.warp(this._effectiveTimeScale,0,e)}warp(e,t,n){let i=this._mixer,s=i.time,o=this.timeScale,a=this._timeScaleInterpolant;a===null&&(a=i._lendControlInterpolant(),this._timeScaleInterpolant=a);let c=a.parameterPositions,l=a.sampleValues;return c[0]=s,c[1]=s+n,l[0]=e/o,l[1]=t/o,this}stopWarping(){let e=this._timeScaleInterpolant;return e!==null&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(e,t,n,i){if(!this.enabled){this._updateWeight(e);return}let s=this._startTime;if(s!==null){let c=(e-s)*n;c<0||n===0?t=0:(this._startTime=null,t=n*c)}t*=this._updateTimeScale(e);let o=this._updateTime(t),a=this._updateWeight(e);if(a>0){let c=this._interpolants,l=this._propertyBindings;switch(this.blendMode){case Ch:for(let h=0,u=c.length;h!==u;++h)c[h].evaluate(o),l[h].accumulateAdditive(a);break;case yc:default:for(let h=0,u=c.length;h!==u;++h)c[h].evaluate(o),l[h].accumulate(i,a)}}}_updateWeight(e){let t=0;if(this.enabled){t=this.weight;let n=this._weightInterpolant;if(n!==null){let i=n.evaluate(e)[0];t*=i,e>n.parameterPositions[1]&&(this.stopFading(),i===0&&(this.enabled=!1))}}return this._effectiveWeight=t,t}_updateTimeScale(e){let t=0;if(!this.paused){t=this.timeScale;let n=this._timeScaleInterpolant;if(n!==null){let i=n.evaluate(e)[0];t*=i,e>n.parameterPositions[1]&&(this.stopWarping(),t===0?this.paused=!0:this.timeScale=t)}}return this._effectiveTimeScale=t,t}_updateTime(e){let t=this._clip.duration,n=this.loop,i=this.time+e,s=this._loopCount,o=n===vd;if(e===0)return s===-1?i:o&&(s&1)===1?t-i:i;if(n===xd){s===-1&&(this._loopCount=0,this._setEndings(!0,!0,!1));e:{if(i>=t)i=t;else if(i<0)i=0;else{this.time=i;break e}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=i,this._mixer.dispatchEvent({type:"finished",action:this,direction:e<0?-1:1})}}else{if(s===-1&&(e>=0?(s=0,this._setEndings(!0,this.repetitions===0,o)):this._setEndings(this.repetitions===0,!0,o)),i>=t||i<0){let a=Math.floor(i/t);i-=t*a,s+=Math.abs(a);let c=this.repetitions-s;if(c<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,i=e>0?t:0,this.time=i,this._mixer.dispatchEvent({type:"finished",action:this,direction:e>0?1:-1});else{if(c===1){let l=e<0;this._setEndings(l,!l,o)}else this._setEndings(!1,!1,o);this._loopCount=s,this.time=i,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:a})}}else this.time=i;if(o&&(s&1)===1)return t-i}return i}_setEndings(e,t,n){let i=this._interpolantSettings;n?(i.endingStart=Ui,i.endingEnd=Ui):(e?i.endingStart=this.zeroSlopeAtStart?Ui:Ni:i.endingStart=fr,t?i.endingEnd=this.zeroSlopeAtEnd?Ui:Ni:i.endingEnd=fr)}_scheduleFading(e,t,n){let i=this._mixer,s=i.time,o=this._weightInterpolant;o===null&&(o=i._lendControlInterpolant(),this._weightInterpolant=o);let a=o.parameterPositions,c=o.sampleValues;return a[0]=s,c[0]=t,a[1]=s+e,c[1]=n,this}},px=new Float32Array(1),Wl=class extends xn{constructor(e){super(),this._root=e,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1}_bindAction(e,t){let n=e._localRoot||this._root,i=e._clip.tracks,s=i.length,o=e._propertyBindings,a=e._interpolants,c=n.uuid,l=this._bindingsByRootAndName,h=l[c];h===void 0&&(h={},l[c]=h);for(let u=0;u!==s;++u){let d=i[u],f=d.name,m=h[f];if(m!==void 0)++m.referenceCount,o[u]=m;else{if(m=o[u],m!==void 0){m._cacheIndex===null&&(++m.referenceCount,this._addInactiveBinding(m,c,f));continue}let _=t&&t._propertyBindings[u].binding.parsedPath;m=new Ca(st.create(n,f,_),d.ValueTypeName,d.getValueSize()),++m.referenceCount,this._addInactiveBinding(m,c,f),o[u]=m}a[u].resultBuffer=m.buffer}}_activateAction(e){if(!this._isActiveAction(e)){if(e._cacheIndex===null){let n=(e._localRoot||this._root).uuid,i=e._clip.uuid,s=this._actionsByClip[i];this._bindAction(e,s&&s.knownActions[0]),this._addInactiveAction(e,i,n)}let t=e._propertyBindings;for(let n=0,i=t.length;n!==i;++n){let s=t[n];s.useCount++===0&&(this._lendBinding(s),s.saveOriginalState())}this._lendAction(e)}}_deactivateAction(e){if(this._isActiveAction(e)){let t=e._propertyBindings;for(let n=0,i=t.length;n!==i;++n){let s=t[n];--s.useCount===0&&(s.restoreOriginalState(),this._takeBackBinding(s))}this._takeBackAction(e)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;let e=this;this.stats={actions:{get total(){return e._actions.length},get inUse(){return e._nActiveActions}},bindings:{get total(){return e._bindings.length},get inUse(){return e._nActiveBindings}},controlInterpolants:{get total(){return e._controlInterpolants.length},get inUse(){return e._nActiveControlInterpolants}}}}_isActiveAction(e){let t=e._cacheIndex;return t!==null&&t<this._nActiveActions}_addInactiveAction(e,t,n){let i=this._actions,s=this._actionsByClip,o=s[t];if(o===void 0)o={knownActions:[e],actionByRoot:{}},e._byClipCacheIndex=0,s[t]=o;else{let a=o.knownActions;e._byClipCacheIndex=a.length,a.push(e)}e._cacheIndex=i.length,i.push(e),o.actionByRoot[n]=e}_removeInactiveAction(e){let t=this._actions,n=t[t.length-1],i=e._cacheIndex;n._cacheIndex=i,t[i]=n,t.pop(),e._cacheIndex=null;let s=e._clip.uuid,o=this._actionsByClip,a=o[s],c=a.knownActions,l=c[c.length-1],h=e._byClipCacheIndex;l._byClipCacheIndex=h,c[h]=l,c.pop(),e._byClipCacheIndex=null;let u=a.actionByRoot,d=(e._localRoot||this._root).uuid;delete u[d],c.length===0&&delete o[s],this._removeInactiveBindingsForAction(e)}_removeInactiveBindingsForAction(e){let t=e._propertyBindings;for(let n=0,i=t.length;n!==i;++n){let s=t[n];--s.referenceCount===0&&this._removeInactiveBinding(s)}}_lendAction(e){let t=this._actions,n=e._cacheIndex,i=this._nActiveActions++,s=t[i];e._cacheIndex=i,t[i]=e,s._cacheIndex=n,t[n]=s}_takeBackAction(e){let t=this._actions,n=e._cacheIndex,i=--this._nActiveActions,s=t[i];e._cacheIndex=i,t[i]=e,s._cacheIndex=n,t[n]=s}_addInactiveBinding(e,t,n){let i=this._bindingsByRootAndName,s=this._bindings,o=i[t];o===void 0&&(o={},i[t]=o),o[n]=e,e._cacheIndex=s.length,s.push(e)}_removeInactiveBinding(e){let t=this._bindings,n=e.binding,i=n.rootNode.uuid,s=n.path,o=this._bindingsByRootAndName,a=o[i],c=t[t.length-1],l=e._cacheIndex;c._cacheIndex=l,t[l]=c,t.pop(),delete a[s],Object.keys(a).length===0&&delete o[i]}_lendBinding(e){let t=this._bindings,n=e._cacheIndex,i=this._nActiveBindings++,s=t[i];e._cacheIndex=i,t[i]=e,s._cacheIndex=n,t[n]=s}_takeBackBinding(e){let t=this._bindings,n=e._cacheIndex,i=--this._nActiveBindings,s=t[i];e._cacheIndex=i,t[i]=e,s._cacheIndex=n,t[n]=s}_lendControlInterpolant(){let e=this._controlInterpolants,t=this._nActiveControlInterpolants++,n=e[t];return n===void 0&&(n=new Fr(new Float32Array(2),new Float32Array(2),1,px),n.__cacheIndex=t,e[t]=n),n}_takeBackControlInterpolant(e){let t=this._controlInterpolants,n=e.__cacheIndex,i=--this._nActiveControlInterpolants,s=t[i];e.__cacheIndex=i,t[i]=e,s.__cacheIndex=n,t[n]=s}clipAction(e,t,n){let i=t||this._root,s=i.uuid,o=typeof e=="string"?ei.findByName(i,e):e,a=o!==null?o.uuid:e,c=this._actionsByClip[a],l=null;if(n===void 0&&(o!==null?n=o.blendMode:n=yc),c!==void 0){let u=c.actionByRoot[s];if(u!==void 0&&u.blendMode===n)return u;l=c.knownActions[0],o===null&&(o=l._clip)}if(o===null)return null;let h=new Ia(this,o,t,n);return this._bindAction(h,l),this._addInactiveAction(h,a,s),h}existingAction(e,t){let n=t||this._root,i=n.uuid,s=typeof e=="string"?ei.findByName(n,e):e,o=s?s.uuid:e,a=this._actionsByClip[o];return a!==void 0&&a.actionByRoot[i]||null}stopAllAction(){let e=this._actions,t=this._nActiveActions;for(let n=t-1;n>=0;--n)e[n].stop();return this}update(e){e*=this.timeScale;let t=this._actions,n=this._nActiveActions,i=this.time+=e,s=Math.sign(e),o=this._accuIndex^=1;for(let l=0;l!==n;++l)t[l]._update(i,e,s,o);let a=this._bindings,c=this._nActiveBindings;for(let l=0;l!==c;++l)a[l].apply(o);return this}setTime(e){this.time=0;for(let t=0;t<this._actions.length;t++)this._actions[t].time=0;return this.update(e)}getRoot(){return this._root}uncacheClip(e){let t=this._actions,n=e.uuid,i=this._actionsByClip,s=i[n];if(s!==void 0){let o=s.knownActions;for(let a=0,c=o.length;a!==c;++a){let l=o[a];this._deactivateAction(l);let h=l._cacheIndex,u=t[t.length-1];l._cacheIndex=null,l._byClipCacheIndex=null,u._cacheIndex=h,t[h]=u,t.pop(),this._removeInactiveBindingsForAction(l)}delete i[n]}}uncacheRoot(e){let t=e.uuid,n=this._actionsByClip;for(let o in n){let a=n[o].actionByRoot,c=a[t];c!==void 0&&(this._deactivateAction(c),this._removeInactiveAction(c))}let i=this._bindingsByRootAndName,s=i[t];if(s!==void 0)for(let o in s){let a=s[o];a.restoreOriginalState(),this._removeInactiveBinding(a)}}uncacheAction(e,t){let n=this.existingAction(e,t);n!==null&&(this._deactivateAction(n),this._removeInactiveAction(n))}},Xl=class extends xr{constructor(e=1,t=1,n=1,i={}){super(e,t,i),this.isRenderTarget3D=!0,this.depth=n,this.texture=new ps(null,e,t,n),this._setTextureOptions(i),this.texture.isRenderTargetTexture=!0}},ql=class r{constructor(e){this.value=e}clone(){return new r(this.value.clone===void 0?this.value:this.value.clone())}},mx=0,Yl=class extends xn{constructor(){super(),this.isUniformsGroup=!0,Object.defineProperty(this,"id",{value:mx++}),this.name="",this.usage=mr,this.uniforms=[]}add(e){return this.uniforms.push(e),this}remove(e){let t=this.uniforms.indexOf(e);return t!==-1&&this.uniforms.splice(t,1),this}setName(e){return this.name=e,this}setUsage(e){return this.usage=e,this}dispose(){this.dispatchEvent({type:"dispose"})}copy(e){this.name=e.name,this.usage=e.usage;let t=e.uniforms;this.uniforms.length=0;for(let n=0,i=t.length;n<i;n++){let s=Array.isArray(t[n])?t[n]:[t[n]];for(let o=0;o<s.length;o++)this.uniforms.push(s[o].clone())}return this}clone(){return new this.constructor().copy(this)}},Zl=class extends Jn{constructor(e,t,n=1){super(e,t),this.isInstancedInterleavedBuffer=!0,this.meshPerAttribute=n}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}clone(e){let t=super.clone(e);return t.meshPerAttribute=this.meshPerAttribute,t}toJSON(e){let t=super.toJSON(e);return t.isInstancedInterleavedBuffer=!0,t.meshPerAttribute=this.meshPerAttribute,t}},Kl=class{constructor(e,t,n,i,s,o=!1){this.isGLBufferAttribute=!0,this.name="",this.buffer=e,this.type=t,this.itemSize=n,this.elementSize=i,this.count=s,this.normalized=o,this.version=0}set needsUpdate(e){e===!0&&this.version++}setBuffer(e){return this.buffer=e,this}setType(e,t){return this.type=e,this.elementSize=t,this}setItemSize(e){return this.itemSize=e,this}setCount(e){return this.count=e,this}},kp=new De,Jl=class{constructor(e,t,n=0,i=1/0){this.ray=new On(e,t),this.near=n,this.far=i,this.camera=null,this.layers=new ms,this.params={Mesh:{},Line:{threshold:1},LOD:{},Points:{threshold:1},Sprite:{}}}set(e,t){this.ray.set(e,t)}setFromCamera(e,t){t.isPerspectiveCamera?(this.ray.origin.setFromMatrixPosition(t.matrixWorld),this.ray.direction.set(e.x,e.y,.5).unproject(t).sub(this.ray.origin).normalize(),this.camera=t):t.isOrthographicCamera?(this.ray.origin.set(e.x,e.y,(t.near+t.far)/(t.near-t.far)).unproject(t),this.ray.direction.set(0,0,-1).transformDirection(t.matrixWorld),this.camera=t):console.error("THREE.Raycaster: Unsupported camera type: "+t.type)}setFromXRController(e){return kp.identity().extractRotation(e.matrixWorld),this.ray.origin.setFromMatrixPosition(e.matrixWorld),this.ray.direction.set(0,0,-1).applyMatrix4(kp),this}intersectObject(e,t=!0,n=[]){return zu(e,this,n,t),n.sort(Vp),n}intersectObjects(e,t=!0,n=[]){for(let i=0,s=e.length;i<s;i++)zu(e[i],this,n,t);return n.sort(Vp),n}};function Vp(r,e){return r.distance-e.distance}function zu(r,e,t,n){let i=!0;if(r.layers.test(e.layers)&&r.raycast(e,t)===!1&&(i=!1),i===!0&&n===!0){let s=r.children;for(let o=0,a=s.length;o<a;o++)zu(s[o],e,t,!0)}}var $l=class{constructor(){this._previousTime=0,this._currentTime=0,this._startTime=performance.now(),this._delta=0,this._elapsed=0,this._timescale=1,this._document=null,this._pageVisibilityHandler=null}connect(e){this._document=e,e.hidden!==void 0&&(this._pageVisibilityHandler=gx.bind(this),e.addEventListener("visibilitychange",this._pageVisibilityHandler,!1))}disconnect(){this._pageVisibilityHandler!==null&&(this._document.removeEventListener("visibilitychange",this._pageVisibilityHandler),this._pageVisibilityHandler=null),this._document=null}getDelta(){return this._delta/1e3}getElapsed(){return this._elapsed/1e3}getTimescale(){return this._timescale}setTimescale(e){return this._timescale=e,this}reset(){return this._currentTime=performance.now()-this._startTime,this}dispose(){this.disconnect()}update(e){return this._pageVisibilityHandler!==null&&this._document.hidden===!0?this._delta=0:(this._previousTime=this._currentTime,this._currentTime=(e!==void 0?e:performance.now())-this._startTime,this._delta=(this._currentTime-this._previousTime)*this._timescale,this._elapsed+=this._delta),this}};function gx(){this._document.hidden===!1&&this.reset()}var Ps=class{constructor(e=1,t=0,n=0){this.radius=e,this.phi=t,this.theta=n}set(e,t,n){return this.radius=e,this.phi=t,this.theta=n,this}copy(e){return this.radius=e.radius,this.phi=e.phi,this.theta=e.theta,this}makeSafe(){return this.phi=Fe(this.phi,1e-6,Math.PI-1e-6),this}setFromVector3(e){return this.setFromCartesianCoords(e.x,e.y,e.z)}setFromCartesianCoords(e,t,n){return this.radius=Math.sqrt(e*e+t*t+n*n),this.radius===0?(this.theta=0,this.phi=0):(this.theta=Math.atan2(e,n),this.phi=Math.acos(Fe(t/this.radius,-1,1))),this}clone(){return new this.constructor().copy(this)}},jl=class{constructor(e=1,t=0,n=0){this.radius=e,this.theta=t,this.y=n}set(e,t,n){return this.radius=e,this.theta=t,this.y=n,this}copy(e){return this.radius=e.radius,this.theta=e.theta,this.y=e.y,this}setFromVector3(e){return this.setFromCartesianCoords(e.x,e.y,e.z)}setFromCartesianCoords(e,t,n){return this.radius=Math.sqrt(e*e+n*n),this.theta=Math.atan2(e,n),this.y=t,this}clone(){return new this.constructor().copy(this)}},Ql=class r{constructor(e,t,n,i){r.prototype.isMatrix2=!0,this.elements=[1,0,0,1],e!==void 0&&this.set(e,t,n,i)}identity(){return this.set(1,0,0,1),this}fromArray(e,t=0){for(let n=0;n<4;n++)this.elements[n]=e[n+t];return this}set(e,t,n,i){let s=this.elements;return s[0]=e,s[2]=t,s[1]=n,s[3]=i,this}},Hp=new Y,eh=class{constructor(e=new Y(1/0,1/0),t=new Y(-1/0,-1/0)){this.isBox2=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromPoints(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){let n=Hp.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(n),this.max.copy(e).add(n),this}clone(){return new this.constructor().copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=1/0,this.max.x=this.max.y=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y}getCenter(e){return this.isEmpty()?e.set(0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}containsPoint(e){return e.x>=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Hp).distanceTo(e)}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}},Gp=new w,al=new w,lr=new w,hr=new w,Eu=new w,_x=new w,xx=new w,th=class{constructor(e=new w,t=new w){this.start=e,this.end=t}set(e,t){return this.start.copy(e),this.end.copy(t),this}copy(e){return this.start.copy(e.start),this.end.copy(e.end),this}getCenter(e){return e.addVectors(this.start,this.end).multiplyScalar(.5)}delta(e){return e.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(e,t){return this.delta(t).multiplyScalar(e).add(this.start)}closestPointToPointParameter(e,t){Gp.subVectors(e,this.start),al.subVectors(this.end,this.start);let n=al.dot(al),s=al.dot(Gp)/n;return t&&(s=Fe(s,0,1)),s}closestPointToPoint(e,t,n){let i=this.closestPointToPointParameter(e,t);return this.delta(n).multiplyScalar(i).add(this.start)}distanceSqToLine3(e,t=_x,n=xx){let i=10000000000000001e-32,s,o,a=this.start,c=e.start,l=this.end,h=e.end;lr.subVectors(l,a),hr.subVectors(h,c),Eu.subVectors(a,c);let u=lr.dot(lr),d=hr.dot(hr),f=hr.dot(Eu);if(u<=i&&d<=i)return t.copy(a),n.copy(c),t.sub(n),t.dot(t);if(u<=i)s=0,o=f/d,o=Fe(o,0,1);else{let m=lr.dot(Eu);if(d<=i)o=0,s=Fe(-m/u,0,1);else{let _=lr.dot(hr),g=u*d-_*_;g!==0?s=Fe((_*f-m*d)/g,0,1):s=0,o=(_*s+f)/d,o<0?(o=0,s=Fe(-m/u,0,1)):o>1&&(o=1,s=Fe((_-m)/u,0,1))}}return t.copy(a).add(lr.multiplyScalar(s)),n.copy(c).add(hr.multiplyScalar(o)),t.sub(n),t.dot(t)}applyMatrix4(e){return this.start.applyMatrix4(e),this.end.applyMatrix4(e),this}equals(e){return e.start.equals(this.start)&&e.end.equals(this.end)}clone(){return new this.constructor().copy(this)}},Wp=new w,nh=class extends Qe{constructor(e,t){super(),this.light=e,this.matrixAutoUpdate=!1,this.color=t,this.type="SpotLightHelper";let n=new ze,i=[0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,-1,0,1,0,0,0,0,1,1,0,0,0,0,-1,1];for(let o=0,a=1,c=32;o<c;o++,a++){let l=o/c*Math.PI*2,h=a/c*Math.PI*2;i.push(Math.cos(l),Math.sin(l),1,Math.cos(h),Math.sin(h),1)}n.setAttribute("position",new ye(i,3));let s=new Pt({fog:!1,toneMapped:!1});this.cone=new $t(n,s),this.add(this.cone),this.update()}dispose(){this.cone.geometry.dispose(),this.cone.material.dispose()}update(){this.light.updateWorldMatrix(!0,!1),this.light.target.updateWorldMatrix(!0,!1),this.parent?(this.parent.updateWorldMatrix(!0),this.matrix.copy(this.parent.matrixWorld).invert().multiply(this.light.matrixWorld)):this.matrix.copy(this.light.matrixWorld),this.matrixWorld.copy(this.light.matrixWorld);let e=this.light.distance?this.light.distance:1e3,t=e*Math.tan(this.light.angle);this.cone.scale.set(t,t,e),Wp.setFromMatrixPosition(this.light.target.matrixWorld),this.cone.lookAt(Wp),this.color!==void 0?this.cone.material.color.set(this.color):this.cone.material.color.copy(this.light.color)}},Li=new w,cl=new De,Au=new De,ih=class extends $t{constructor(e){let t=km(e),n=new ze,i=[],s=[];for(let l=0;l<t.length;l++){let h=t[l];h.parent&&h.parent.isBone&&(i.push(0,0,0),i.push(0,0,0),s.push(0,0,0),s.push(0,0,0))}n.setAttribute("position",new ye(i,3)),n.setAttribute("color",new ye(s,3));let o=new Pt({vertexColors:!0,depthTest:!1,depthWrite:!1,toneMapped:!1,transparent:!0});super(n,o),this.isSkeletonHelper=!0,this.type="SkeletonHelper",this.root=e,this.bones=t,this.matrix=e.matrixWorld,this.matrixAutoUpdate=!1;let a=new ue(255),c=new ue(65280);this.setColors(a,c)}updateMatrixWorld(e){let t=this.bones,n=this.geometry,i=n.getAttribute("position");Au.copy(this.root.matrixWorld).invert();for(let s=0,o=0;s<t.length;s++){let a=t[s];a.parent&&a.parent.isBone&&(cl.multiplyMatrices(Au,a.matrixWorld),Li.setFromMatrixPosition(cl),i.setXYZ(o,Li.x,Li.y,Li.z),cl.multiplyMatrices(Au,a.parent.matrixWorld),Li.setFromMatrixPosition(cl),i.setXYZ(o+1,Li.x,Li.y,Li.z),o+=2)}n.getAttribute("position").needsUpdate=!0,super.updateMatrixWorld(e)}setColors(e,t){let i=this.geometry.getAttribute("color");for(let s=0;s<i.count;s+=2)i.setXYZ(s,e.r,e.g,e.b),i.setXYZ(s+1,t.r,t.g,t.b);return i.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}};function km(r){let e=[];r.isBone===!0&&e.push(r);for(let t=0;t<r.children.length;t++)e.push(...km(r.children[t]));return e}var sh=class extends pt{constructor(e,t,n){let i=new Dr(t,4,2),s=new Bt({wireframe:!0,fog:!1,toneMapped:!1});super(i,s),this.light=e,this.color=n,this.type="PointLightHelper",this.matrix=this.light.matrixWorld,this.matrixAutoUpdate=!1,this.update()}dispose(){this.geometry.dispose(),this.material.dispose()}update(){this.light.updateWorldMatrix(!0,!1),this.color!==void 0?this.material.color.set(this.color):this.material.color.copy(this.light.color)}},yx=new w,Xp=new ue,qp=new ue,rh=class extends Qe{constructor(e,t,n){super(),this.light=e,this.matrix=e.matrixWorld,this.matrixAutoUpdate=!1,this.color=n,this.type="HemisphereLightHelper";let i=new Lr(t);i.rotateY(Math.PI*.5),this.material=new Bt({wireframe:!0,fog:!1,toneMapped:!1}),this.color===void 0&&(this.material.vertexColors=!0);let s=i.getAttribute("position"),o=new Float32Array(s.count*3);i.setAttribute("color",new je(o,3)),this.add(new pt(i,this.material)),this.update()}dispose(){this.children[0].geometry.dispose(),this.children[0].material.dispose()}update(){let e=this.children[0];if(this.color!==void 0)this.material.color.set(this.color);else{let t=e.geometry.getAttribute("color");Xp.copy(this.light.color),qp.copy(this.light.groundColor);for(let n=0,i=t.count;n<i;n++){let s=n<i/2?Xp:qp;t.setXYZ(n,s.r,s.g,s.b)}t.needsUpdate=!0}this.light.updateWorldMatrix(!0,!1),e.lookAt(yx.setFromMatrixPosition(this.light.matrixWorld).negate())}},oh=class extends $t{constructor(e=10,t=10,n=4473924,i=8947848){n=new ue(n),i=new ue(i);let s=t/2,o=e/t,a=e/2,c=[],l=[];for(let d=0,f=0,m=-a;d<=t;d++,m+=o){c.push(-a,0,m,a,0,m),c.push(m,0,-a,m,0,a);let _=d===s?n:i;_.toArray(l,f),f+=3,_.toArray(l,f),f+=3,_.toArray(l,f),f+=3,_.toArray(l,f),f+=3}let h=new ze;h.setAttribute("position",new ye(c,3)),h.setAttribute("color",new ye(l,3));let u=new Pt({vertexColors:!0,toneMapped:!1});super(h,u),this.type="GridHelper"}dispose(){this.geometry.dispose(),this.material.dispose()}},ah=class extends $t{constructor(e=10,t=16,n=8,i=64,s=4473924,o=8947848){s=new ue(s),o=new ue(o);let a=[],c=[];if(t>1)for(let u=0;u<t;u++){let d=u/t*(Math.PI*2),f=Math.sin(d)*e,m=Math.cos(d)*e;a.push(0,0,0),a.push(f,0,m);let _=u&1?s:o;c.push(_.r,_.g,_.b),c.push(_.r,_.g,_.b)}for(let u=0;u<n;u++){let d=u&1?s:o,f=e-e/n*u;for(let m=0;m<i;m++){let _=m/i*(Math.PI*2),g=Math.sin(_)*f,p=Math.cos(_)*f;a.push(g,0,p),c.push(d.r,d.g,d.b),_=(m+1)/i*(Math.PI*2),g=Math.sin(_)*f,p=Math.cos(_)*f,a.push(g,0,p),c.push(d.r,d.g,d.b)}}let l=new ze;l.setAttribute("position",new ye(a,3)),l.setAttribute("color",new ye(c,3));let h=new Pt({vertexColors:!0,toneMapped:!1});super(l,h),this.type="PolarGridHelper"}dispose(){this.geometry.dispose(),this.material.dispose()}},Yp=new w,ll=new w,Zp=new w,ch=class extends Qe{constructor(e,t,n){super(),this.light=e,this.matrix=e.matrixWorld,this.matrixAutoUpdate=!1,this.color=n,this.type="DirectionalLightHelper",t===void 0&&(t=1);let i=new ze;i.setAttribute("position",new ye([-t,t,0,t,t,0,t,-t,0,-t,-t,0,-t,t,0],3));let s=new Pt({fog:!1,toneMapped:!1});this.lightPlane=new vn(i,s),this.add(this.lightPlane),i=new ze,i.setAttribute("position",new ye([0,0,0,0,0,1],3)),this.targetLine=new vn(i,s),this.add(this.targetLine),this.update()}dispose(){this.lightPlane.geometry.dispose(),this.lightPlane.material.dispose(),this.targetLine.geometry.dispose(),this.targetLine.material.dispose()}update(){this.light.updateWorldMatrix(!0,!1),this.light.target.updateWorldMatrix(!0,!1),Yp.setFromMatrixPosition(this.light.matrixWorld),ll.setFromMatrixPosition(this.light.target.matrixWorld),Zp.subVectors(ll,Yp),this.lightPlane.lookAt(ll),this.color!==void 0?(this.lightPlane.material.color.set(this.color),this.targetLine.material.color.set(this.color)):(this.lightPlane.material.color.copy(this.light.color),this.targetLine.material.color.copy(this.light.color)),this.targetLine.lookAt(ll),this.targetLine.scale.z=Zp.length()}},hl=new w,bt=new gs,lh=class extends $t{constructor(e){let t=new ze,n=new Pt({color:16777215,vertexColors:!0,toneMapped:!1}),i=[],s=[],o={};a("n1","n2"),a("n2","n4"),a("n4","n3"),a("n3","n1"),a("f1","f2"),a("f2","f4"),a("f4","f3"),a("f3","f1"),a("n1","f1"),a("n2","f2"),a("n3","f3"),a("n4","f4"),a("p","n1"),a("p","n2"),a("p","n3"),a("p","n4"),a("u1","u2"),a("u2","u3"),a("u3","u1"),a("c","t"),a("p","c"),a("cn1","cn2"),a("cn3","cn4"),a("cf1","cf2"),a("cf3","cf4");function a(m,_){c(m),c(_)}function c(m){i.push(0,0,0),s.push(0,0,0),o[m]===void 0&&(o[m]=[]),o[m].push(i.length/3-1)}t.setAttribute("position",new ye(i,3)),t.setAttribute("color",new ye(s,3)),super(t,n),this.type="CameraHelper",this.camera=e,this.camera.updateProjectionMatrix&&this.camera.updateProjectionMatrix(),this.matrix=e.matrixWorld,this.matrixAutoUpdate=!1,this.pointMap=o,this.update();let l=new ue(16755200),h=new ue(16711680),u=new ue(43775),d=new ue(16777215),f=new ue(3355443);this.setColors(l,h,u,d,f)}setColors(e,t,n,i,s){let a=this.geometry.getAttribute("color");return a.setXYZ(0,e.r,e.g,e.b),a.setXYZ(1,e.r,e.g,e.b),a.setXYZ(2,e.r,e.g,e.b),a.setXYZ(3,e.r,e.g,e.b),a.setXYZ(4,e.r,e.g,e.b),a.setXYZ(5,e.r,e.g,e.b),a.setXYZ(6,e.r,e.g,e.b),a.setXYZ(7,e.r,e.g,e.b),a.setXYZ(8,e.r,e.g,e.b),a.setXYZ(9,e.r,e.g,e.b),a.setXYZ(10,e.r,e.g,e.b),a.setXYZ(11,e.r,e.g,e.b),a.setXYZ(12,e.r,e.g,e.b),a.setXYZ(13,e.r,e.g,e.b),a.setXYZ(14,e.r,e.g,e.b),a.setXYZ(15,e.r,e.g,e.b),a.setXYZ(16,e.r,e.g,e.b),a.setXYZ(17,e.r,e.g,e.b),a.setXYZ(18,e.r,e.g,e.b),a.setXYZ(19,e.r,e.g,e.b),a.setXYZ(20,e.r,e.g,e.b),a.setXYZ(21,e.r,e.g,e.b),a.setXYZ(22,e.r,e.g,e.b),a.setXYZ(23,e.r,e.g,e.b),a.setXYZ(24,t.r,t.g,t.b),a.setXYZ(25,t.r,t.g,t.b),a.setXYZ(26,t.r,t.g,t.b),a.setXYZ(27,t.r,t.g,t.b),a.setXYZ(28,t.r,t.g,t.b),a.setXYZ(29,t.r,t.g,t.b),a.setXYZ(30,t.r,t.g,t.b),a.setXYZ(31,t.r,t.g,t.b),a.setXYZ(32,n.r,n.g,n.b),a.setXYZ(33,n.r,n.g,n.b),a.setXYZ(34,n.r,n.g,n.b),a.setXYZ(35,n.r,n.g,n.b),a.setXYZ(36,n.r,n.g,n.b),a.setXYZ(37,n.r,n.g,n.b),a.setXYZ(38,i.r,i.g,i.b),a.setXYZ(39,i.r,i.g,i.b),a.setXYZ(40,s.r,s.g,s.b),a.setXYZ(41,s.r,s.g,s.b),a.setXYZ(42,s.r,s.g,s.b),a.setXYZ(43,s.r,s.g,s.b),a.setXYZ(44,s.r,s.g,s.b),a.setXYZ(45,s.r,s.g,s.b),a.setXYZ(46,s.r,s.g,s.b),a.setXYZ(47,s.r,s.g,s.b),a.setXYZ(48,s.r,s.g,s.b),a.setXYZ(49,s.r,s.g,s.b),a.needsUpdate=!0,this}update(){let e=this.geometry,t=this.pointMap,n=1,i=1,s,o;if(bt.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse),this.camera.reversedDepth===!0)s=1,o=0;else if(this.camera.coordinateSystem===sn)s=-1,o=1;else if(this.camera.coordinateSystem===us)s=0,o=1;else throw new Error("THREE.CameraHelper.update(): Invalid coordinate system: "+this.camera.coordinateSystem);At("c",t,e,bt,0,0,s),At("t",t,e,bt,0,0,o),At("n1",t,e,bt,-n,-i,s),At("n2",t,e,bt,n,-i,s),At("n3",t,e,bt,-n,i,s),At("n4",t,e,bt,n,i,s),At("f1",t,e,bt,-n,-i,o),At("f2",t,e,bt,n,-i,o),At("f3",t,e,bt,-n,i,o),At("f4",t,e,bt,n,i,o),At("u1",t,e,bt,n*.7,i*1.1,s),At("u2",t,e,bt,-n*.7,i*1.1,s),At("u3",t,e,bt,0,i*2,s),At("cf1",t,e,bt,-n,0,o),At("cf2",t,e,bt,n,0,o),At("cf3",t,e,bt,0,-i,o),At("cf4",t,e,bt,0,i,o),At("cn1",t,e,bt,-n,0,s),At("cn2",t,e,bt,n,0,s),At("cn3",t,e,bt,0,-i,s),At("cn4",t,e,bt,0,i,s),e.getAttribute("position").needsUpdate=!0}dispose(){this.geometry.dispose(),this.material.dispose()}};function At(r,e,t,n,i,s,o){hl.set(i,s,o).unproject(n);let a=e[r];if(a!==void 0){let c=t.getAttribute("position");for(let l=0,h=a.length;l<h;l++)c.setXYZ(a[l],hl.x,hl.y,hl.z)}}var ul=new Rt,hh=class extends $t{constructor(e,t=16776960){let n=new Uint16Array([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,4,1,5,2,6,3,7]),i=new Float32Array(24),s=new ze;s.setIndex(new je(n,1)),s.setAttribute("position",new je(i,3)),super(s,new Pt({color:t,toneMapped:!1})),this.object=e,this.type="BoxHelper",this.matrixAutoUpdate=!1,this.update()}update(){if(this.object!==void 0&&ul.setFromObject(this.object),ul.isEmpty())return;let e=ul.min,t=ul.max,n=this.geometry.attributes.position,i=n.array;i[0]=t.x,i[1]=t.y,i[2]=t.z,i[3]=e.x,i[4]=t.y,i[5]=t.z,i[6]=e.x,i[7]=e.y,i[8]=t.z,i[9]=t.x,i[10]=e.y,i[11]=t.z,i[12]=t.x,i[13]=t.y,i[14]=e.z,i[15]=e.x,i[16]=t.y,i[17]=e.z,i[18]=e.x,i[19]=e.y,i[20]=e.z,i[21]=t.x,i[22]=e.y,i[23]=e.z,n.needsUpdate=!0,this.geometry.computeBoundingSphere()}setFromObject(e){return this.object=e,this.update(),this}copy(e,t){return super.copy(e,t),this.object=e.object,this}dispose(){this.geometry.dispose(),this.material.dispose()}},uh=class extends $t{constructor(e,t=16776960){let n=new Uint16Array([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,4,1,5,2,6,3,7]),i=[1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1],s=new ze;s.setIndex(new je(n,1)),s.setAttribute("position",new ye(i,3)),super(s,new Pt({color:t,toneMapped:!1})),this.box=e,this.type="Box3Helper",this.geometry.computeBoundingSphere()}updateMatrixWorld(e){let t=this.box;t.isEmpty()||(t.getCenter(this.position),t.getSize(this.scale),this.scale.multiplyScalar(.5),super.updateMatrixWorld(e))}dispose(){this.geometry.dispose(),this.material.dispose()}},dh=class extends vn{constructor(e,t=1,n=16776960){let i=n,s=[1,-1,0,-1,1,0,-1,-1,0,1,1,0,-1,1,0,-1,-1,0,1,-1,0,1,1,0],o=new ze;o.setAttribute("position",new ye(s,3)),o.computeBoundingSphere(),super(o,new Pt({color:i,toneMapped:!1})),this.type="PlaneHelper",this.plane=e,this.size=t;let a=[1,1,0,-1,1,0,-1,-1,0,1,1,0,-1,-1,0,1,-1,0],c=new ze;c.setAttribute("position",new ye(a,3)),c.computeBoundingSphere(),this.add(new pt(c,new Bt({color:i,opacity:.2,transparent:!0,depthWrite:!1,toneMapped:!1})))}updateMatrixWorld(e){this.position.set(0,0,0),this.scale.set(.5*this.size,.5*this.size,1),this.lookAt(this.plane.normal),this.translateZ(-this.plane.constant),super.updateMatrixWorld(e)}dispose(){this.geometry.dispose(),this.material.dispose(),this.children[0].geometry.dispose(),this.children[0].material.dispose()}},Kp=new w,dl,wu,fh=class extends Qe{constructor(e=new w(0,0,1),t=new w(0,0,0),n=1,i=16776960,s=n*.2,o=s*.2){super(),this.type="ArrowHelper",dl===void 0&&(dl=new ze,dl.setAttribute("position",new ye([0,0,0,0,1,0],3)),wu=new Er(.5,1,5,1),wu.translate(0,-.5,0)),this.position.copy(t),this.line=new vn(dl,new Pt({color:i,toneMapped:!1})),this.line.matrixAutoUpdate=!1,this.add(this.line),this.cone=new pt(wu,new Bt({color:i,toneMapped:!1})),this.cone.matrixAutoUpdate=!1,this.add(this.cone),this.setDirection(e),this.setLength(n,s,o)}setDirection(e){if(e.y>.99999)this.quaternion.set(0,0,0,1);else if(e.y<-.99999)this.quaternion.set(1,0,0,0);else{Kp.set(e.z,0,-e.x).normalize();let t=Math.acos(e.y);this.quaternion.setFromAxisAngle(Kp,t)}}setLength(e,t=e*.2,n=t*.2){this.line.scale.set(1,Math.max(1e-4,e-t),1),this.line.updateMatrix(),this.cone.scale.set(n,t,n),this.cone.position.y=e,this.cone.updateMatrix()}setColor(e){this.line.material.color.set(e),this.cone.material.color.set(e)}copy(e){return super.copy(e,!1),this.line.copy(e.line),this.cone.copy(e.cone),this}dispose(){this.line.geometry.dispose(),this.line.material.dispose(),this.cone.geometry.dispose(),this.cone.material.dispose()}},ph=class extends $t{constructor(e=1){let t=[0,0,0,e,0,0,0,0,0,0,e,0,0,0,0,0,0,e],n=[1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],i=new ze;i.setAttribute("position",new ye(t,3)),i.setAttribute("color",new ye(n,3));let s=new Pt({vertexColors:!0,toneMapped:!1});super(i,s),this.type="AxesHelper"}setColors(e,t,n){let i=new ue,s=this.geometry.attributes.color.array;return i.set(e),i.toArray(s,0),i.toArray(s,3),i.set(t),i.toArray(s,6),i.toArray(s,9),i.set(n),i.toArray(s,12),i.toArray(s,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}},mh=class{constructor(){this.type="ShapePath",this.color=new ue,this.subPaths=[],this.currentPath=null}moveTo(e,t){return this.currentPath=new Es,this.subPaths.push(this.currentPath),this.currentPath.moveTo(e,t),this}lineTo(e,t){return this.currentPath.lineTo(e,t),this}quadraticCurveTo(e,t,n,i){return this.currentPath.quadraticCurveTo(e,t,n,i),this}bezierCurveTo(e,t,n,i,s,o){return this.currentPath.bezierCurveTo(e,t,n,i,s,o),this}splineThru(e){return this.currentPath.splineThru(e),this}toShapes(e){function t(p){let v=[];for(let y=0,x=p.length;y<x;y++){let A=p[y],E=new Zn;E.curves=A.curves,v.push(E)}return v}function n(p,v){let y=v.length,x=!1;for(let A=y-1,E=0;E<y;A=E++){let C=v[A],I=v[E],b=I.x-C.x,S=I.y-C.y;if(Math.abs(S)>Number.EPSILON){if(S<0&&(C=v[E],b=-b,I=v[A],S=-S),p.y<C.y||p.y>I.y)continue;if(p.y===C.y){if(p.x===C.x)return!0}else{let L=S*(p.x-C.x)-b*(p.y-C.y);if(L===0)return!0;if(L<0)continue;x=!x}}else{if(p.y!==C.y)continue;if(I.x<=p.x&&p.x<=C.x||C.x<=p.x&&p.x<=I.x)return!0}}return x}let i=En.isClockWise,s=this.subPaths;if(s.length===0)return[];let o,a,c,l=[];if(s.length===1)return a=s[0],c=new Zn,c.curves=a.curves,l.push(c),l;let h=!i(s[0].getPoints());h=e?!h:h;let u=[],d=[],f=[],m=0,_;d[m]=void 0,f[m]=[];for(let p=0,v=s.length;p<v;p++)a=s[p],_=a.getPoints(),o=i(_),o=e?!o:o,o?(!h&&d[m]&&m++,d[m]={s:new Zn,p:_},d[m].s.curves=a.curves,h&&m++,f[m]=[]):f[m].push({h:a,p:_[0]});if(!d[0])return t(s);if(d.length>1){let p=!1,v=0;for(let y=0,x=d.length;y<x;y++)u[y]=[];for(let y=0,x=d.length;y<x;y++){let A=f[y];for(let E=0;E<A.length;E++){let C=A[E],I=!0;for(let b=0;b<d.length;b++)n(C.p,d[b].p)&&(y!==b&&v++,I?(I=!1,u[b].push(C)):p=!0);I&&u[y].push(C)}}v>0&&p===!1&&(f=u)}let g;for(let p=0,v=d.length;p<v;p++){c=d[p].s,l.push(c),g=f[p];for(let y=0,x=g.length;y<x;y++)c.holes.push(g[y].h)}return l}},Hr=class extends xn{constructor(e,t=null){super(),this.object=e,this.domElement=t,this.enabled=!0,this.state=-1,this.keys={},this.mouseButtons={LEFT:null,MIDDLE:null,RIGHT:null},this.touches={ONE:null,TWO:null}}connect(e){if(e===void 0){console.warn("THREE.Controls: connect() now requires an element.");return}this.domElement!==null&&this.disconnect(),this.domElement=e}disconnect(){}dispose(){}update(){}};function vx(r,e){let t=r.image&&r.image.width?r.image.width/r.image.height:1;return t>e?(r.repeat.x=1,r.repeat.y=t/e,r.offset.x=0,r.offset.y=(1-r.repeat.y)/2):(r.repeat.x=e/t,r.repeat.y=1,r.offset.x=(1-r.repeat.x)/2,r.offset.y=0),r}function Mx(r,e){let t=r.image&&r.image.width?r.image.width/r.image.height:1;return t>e?(r.repeat.x=e/t,r.repeat.y=1,r.offset.x=(1-r.repeat.x)/2,r.offset.y=0):(r.repeat.x=1,r.repeat.y=t/e,r.offset.x=0,r.offset.y=(1-r.repeat.y)/2),r}function Sx(r){return r.repeat.x=1,r.repeat.y=1,r.offset.x=0,r.offset.y=0,r}function Dh(r,e,t,n){let i=bx(n);switch(t){case Ah:return r*e;case Ha:return r*e/i.components*i.byteLength;case Yr:return r*e/i.components*i.byteLength;case Rh:return r*e*2/i.components*i.byteLength;case Ga:return r*e*2/i.components*i.byteLength;case wh:return r*e*3/i.components*i.byteLength;case Ht:return r*e*4/i.components*i.byteLength;case Wa:return r*e*4/i.components*i.byteLength;case Zr:case Kr:return Math.floor((r+3)/4)*Math.floor((e+3)/4)*8;case Jr:case $r:return Math.floor((r+3)/4)*Math.floor((e+3)/4)*16;case qa:case Za:return Math.max(r,16)*Math.max(e,8)/4;case Xa:case Ya:return Math.max(r,8)*Math.max(e,8)/2;case Ka:case Ja:return Math.floor((r+3)/4)*Math.floor((e+3)/4)*8;case $a:return Math.floor((r+3)/4)*Math.floor((e+3)/4)*16;case ja:return Math.floor((r+3)/4)*Math.floor((e+3)/4)*16;case Qa:return Math.floor((r+4)/5)*Math.floor((e+3)/4)*16;case ec:return Math.floor((r+4)/5)*Math.floor((e+4)/5)*16;case tc:return Math.floor((r+5)/6)*Math.floor((e+4)/5)*16;case nc:return Math.floor((r+5)/6)*Math.floor((e+5)/6)*16;case ic:return Math.floor((r+7)/8)*Math.floor((e+4)/5)*16;case sc:return Math.floor((r+7)/8)*Math.floor((e+5)/6)*16;case rc:return Math.floor((r+7)/8)*Math.floor((e+7)/8)*16;case oc:return Math.floor((r+9)/10)*Math.floor((e+4)/5)*16;case ac:return Math.floor((r+9)/10)*Math.floor((e+5)/6)*16;case cc:return Math.floor((r+9)/10)*Math.floor((e+7)/8)*16;case lc:return Math.floor((r+9)/10)*Math.floor((e+9)/10)*16;case hc:return Math.floor((r+11)/12)*Math.floor((e+9)/10)*16;case uc:return Math.floor((r+11)/12)*Math.floor((e+11)/12)*16;case dc:case fc:case pc:return Math.ceil(r/4)*Math.ceil(e/4)*16;case mc:case gc:return Math.ceil(r/4)*Math.ceil(e/4)*8;case _c:case xc:return Math.ceil(r/4)*Math.ceil(e/4)*16}throw new Error(`Unable to determine texture byte length for ${t} format.`)}function bx(r){switch(r){case Cn:case Sh:return{byteLength:1,components:1};case Ds:case bh:case Ns:return{byteLength:2,components:1};case ka:case Va:return{byteLength:2,components:4};case si:case za:case Jt:return{byteLength:4,components:1};case Th:case Eh:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${r}.`)}var gh=class{static contain(e,t){return vx(e,t)}static cover(e,t){return Mx(e,t)}static fill(e){return Sx(e)}static getByteLength(e,t,n,i){return Dh(e,t,n,i)}};typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:"180"}}));typeof window<"u"&&(window.__THREE__?console.warn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__="180");function hg(){let r=null,e=!1,t=null,n=null;function i(s,o){t(s,o),n=r.requestAnimationFrame(i)}return{start:function(){e!==!0&&t!==null&&(n=r.requestAnimationFrame(i),e=!0)},stop:function(){r.cancelAnimationFrame(n),e=!1},setAnimationLoop:function(s){t=s},setContext:function(s){r=s}}}function Tx(r){let e=new WeakMap;function t(a,c){let l=a.array,h=a.usage,u=l.byteLength,d=r.createBuffer();r.bindBuffer(c,d),r.bufferData(c,l,h),a.onUploadCallback();let f;if(l instanceof Float32Array)f=r.FLOAT;else if(typeof Float16Array<"u"&&l instanceof Float16Array)f=r.HALF_FLOAT;else if(l instanceof Uint16Array)a.isFloat16BufferAttribute?f=r.HALF_FLOAT:f=r.UNSIGNED_SHORT;else if(l instanceof Int16Array)f=r.SHORT;else if(l instanceof Uint32Array)f=r.UNSIGNED_INT;else if(l instanceof Int32Array)f=r.INT;else if(l instanceof Int8Array)f=r.BYTE;else if(l instanceof Uint8Array)f=r.UNSIGNED_BYTE;else if(l instanceof Uint8ClampedArray)f=r.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+l);return{buffer:d,type:f,bytesPerElement:l.BYTES_PER_ELEMENT,version:a.version,size:u}}function n(a,c,l){let h=c.array,u=c.updateRanges;if(r.bindBuffer(l,a),u.length===0)r.bufferSubData(l,0,h);else{u.sort((f,m)=>f.start-m.start);let d=0;for(let f=1;f<u.length;f++){let m=u[d],_=u[f];_.start<=m.start+m.count+1?m.count=Math.max(m.count,_.start+_.count-m.start):(++d,u[d]=_)}u.length=d+1;for(let f=0,m=u.length;f<m;f++){let _=u[f];r.bufferSubData(l,_.start*h.BYTES_PER_ELEMENT,h,_.start,_.count)}c.clearUpdateRanges()}c.onUploadCallback()}function i(a){return a.isInterleavedBufferAttribute&&(a=a.data),e.get(a)}function s(a){a.isInterleavedBufferAttribute&&(a=a.data);let c=e.get(a);c&&(r.deleteBuffer(c.buffer),e.delete(a))}function o(a,c){if(a.isInterleavedBufferAttribute&&(a=a.data),a.isGLBufferAttribute){let h=e.get(a);(!h||h.version<a.version)&&e.set(a,{buffer:a.buffer,type:a.type,bytesPerElement:a.elementSize,version:a.version});return}let l=e.get(a);if(l===void 0)e.set(a,t(a,c));else if(l.version<a.version){if(l.size!==a.array.byteLength)throw new Error("THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported.");n(l.buffer,a,c),l.version=a.version}}return{get:i,remove:s,update:o}}var Ex=`#ifdef USE_ALPHAHASH+ if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;+#endif`,Ax=`#ifdef USE_ALPHAHASH+ const float ALPHA_HASH_SCALE = 0.05;+ float hash2D( vec2 value ) {+ return fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );+ }+ float hash3D( vec3 value ) {+ return hash2D( vec2( hash2D( value.xy ), value.z ) );+ }+ float getAlphaHashThreshold( vec3 position ) {+ float maxDeriv = max(+ length( dFdx( position.xyz ) ),+ length( dFdy( position.xyz ) )+ );+ float pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );+ vec2 pixScales = vec2(+ exp2( floor( log2( pixScale ) ) ),+ exp2( ceil( log2( pixScale ) ) )+ );+ vec2 alpha = vec2(+ hash3D( floor( pixScales.x * position.xyz ) ),+ hash3D( floor( pixScales.y * position.xyz ) )+ );+ float lerpFactor = fract( log2( pixScale ) );+ float x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;+ float a = min( lerpFactor, 1.0 - lerpFactor );+ vec3 cases = vec3(+ x * x / ( 2.0 * a * ( 1.0 - a ) ),+ ( x - 0.5 * a ) / ( 1.0 - a ),+ 1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )+ );+ float threshold = ( x < ( 1.0 - a ) )+ ? ( ( x < a ) ? cases.x : cases.y )+ : cases.z;+ return clamp( threshold , 1.0e-6, 1.0 );+ }+#endif`,wx=`#ifdef USE_ALPHAMAP+ diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;+#endif`,Rx=`#ifdef USE_ALPHAMAP+ uniform sampler2D alphaMap;+#endif`,Cx=`#ifdef USE_ALPHATEST+ #ifdef ALPHA_TO_COVERAGE+ diffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );+ if ( diffuseColor.a == 0.0 ) discard;+ #else+ if ( diffuseColor.a < alphaTest ) discard;+ #endif+#endif`,Ix=`#ifdef USE_ALPHATEST+ uniform float alphaTest;+#endif`,Px=`#ifdef USE_AOMAP+ float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;+ reflectedLight.indirectDiffuse *= ambientOcclusion;+ #if defined( USE_CLEARCOAT )+ clearcoatSpecularIndirect *= ambientOcclusion;+ #endif+ #if defined( USE_SHEEN )+ sheenSpecularIndirect *= ambientOcclusion;+ #endif+ #if defined( USE_ENVMAP ) && defined( STANDARD )+ float dotNV = saturate( dot( geometryNormal, geometryViewDir ) );+ reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );+ #endif+#endif`,Lx=`#ifdef USE_AOMAP+ uniform sampler2D aoMap;+ uniform float aoMapIntensity;+#endif`,Dx=`#ifdef USE_BATCHING+ #if ! defined( GL_ANGLE_multi_draw )+ #define gl_DrawID _gl_DrawID+ uniform int _gl_DrawID;+ #endif+ uniform highp sampler2D batchingTexture;+ uniform highp usampler2D batchingIdTexture;+ mat4 getBatchingMatrix( const in float i ) {+ int size = textureSize( batchingTexture, 0 ).x;+ int j = int( i ) * 4;+ int x = j % size;+ int y = j / size;+ vec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 );+ vec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );+ vec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );+ vec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );+ return mat4( v1, v2, v3, v4 );+ }+ float getIndirectIndex( const in int i ) {+ int size = textureSize( batchingIdTexture, 0 ).x;+ int x = i % size;+ int y = i / size;+ return float( texelFetch( batchingIdTexture, ivec2( x, y ), 0 ).r );+ }+#endif+#ifdef USE_BATCHING_COLOR+ uniform sampler2D batchingColorTexture;+ vec3 getBatchingColor( const in float i ) {+ int size = textureSize( batchingColorTexture, 0 ).x;+ int j = int( i );+ int x = j % size;+ int y = j / size;+ return texelFetch( batchingColorTexture, ivec2( x, y ), 0 ).rgb;+ }+#endif`,Nx=`#ifdef USE_BATCHING+ mat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );+#endif`,Ux=`vec3 transformed = vec3( position );+#ifdef USE_ALPHAHASH+ vPosition = vec3( position );+#endif`,Fx=`vec3 objectNormal = vec3( normal );+#ifdef USE_TANGENT+ vec3 objectTangent = vec3( tangent.xyz );+#endif`,Ox=`float G_BlinnPhong_Implicit( ) {+ return 0.25;+}+float D_BlinnPhong( const in float shininess, const in float dotNH ) {+ return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );+}+vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {+ vec3 halfDir = normalize( lightDir + viewDir );+ float dotNH = saturate( dot( normal, halfDir ) );+ float dotVH = saturate( dot( viewDir, halfDir ) );+ vec3 F = F_Schlick( specularColor, 1.0, dotVH );+ float G = G_BlinnPhong_Implicit( );+ float D = D_BlinnPhong( shininess, dotNH );+ return F * ( G * D );+} // validated`,Bx=`#ifdef USE_IRIDESCENCE+ const mat3 XYZ_TO_REC709 = mat3(+ 3.2404542, -0.9692660, 0.0556434,+ -1.5371385, 1.8760108, -0.2040259,+ -0.4985314, 0.0415560, 1.0572252+ );+ vec3 Fresnel0ToIor( vec3 fresnel0 ) {+ vec3 sqrtF0 = sqrt( fresnel0 );+ return ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );+ }+ vec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {+ return pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );+ }+ float IorToFresnel0( float transmittedIor, float incidentIor ) {+ return pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));+ }+ vec3 evalSensitivity( float OPD, vec3 shift ) {+ float phase = 2.0 * PI * OPD * 1.0e-9;+ vec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );+ vec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );+ vec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );+ vec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );+ xyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );+ xyz /= 1.0685e-7;+ vec3 rgb = XYZ_TO_REC709 * xyz;+ return rgb;+ }+ vec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {+ vec3 I;+ float iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );+ float sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );+ float cosTheta2Sq = 1.0 - sinTheta2Sq;+ if ( cosTheta2Sq < 0.0 ) {+ return vec3( 1.0 );+ }+ float cosTheta2 = sqrt( cosTheta2Sq );+ float R0 = IorToFresnel0( iridescenceIOR, outsideIOR );+ float R12 = F_Schlick( R0, 1.0, cosTheta1 );+ float T121 = 1.0 - R12;+ float phi12 = 0.0;+ if ( iridescenceIOR < outsideIOR ) phi12 = PI;+ float phi21 = PI - phi12;+ vec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) ); vec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );+ vec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );+ vec3 phi23 = vec3( 0.0 );+ if ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;+ if ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;+ if ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;+ float OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;+ vec3 phi = vec3( phi21 ) + phi23;+ vec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );+ vec3 r123 = sqrt( R123 );+ vec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );+ vec3 C0 = R12 + Rs;+ I = C0;+ vec3 Cm = Rs - T121;+ for ( int m = 1; m <= 2; ++ m ) {+ Cm *= r123;+ vec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );+ I += Cm * Sm;+ }+ return max( I, vec3( 0.0 ) );+ }+#endif`,zx=`#ifdef USE_BUMPMAP+ uniform sampler2D bumpMap;+ uniform float bumpScale;+ vec2 dHdxy_fwd() {+ vec2 dSTdx = dFdx( vBumpMapUv );+ vec2 dSTdy = dFdy( vBumpMapUv );+ float Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;+ float dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;+ float dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;+ return vec2( dBx, dBy );+ }+ vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {+ vec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );+ vec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );+ vec3 vN = surf_norm;+ vec3 R1 = cross( vSigmaY, vN );+ vec3 R2 = cross( vN, vSigmaX );+ float fDet = dot( vSigmaX, R1 ) * faceDirection;+ vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );+ return normalize( abs( fDet ) * surf_norm - vGrad );+ }+#endif`,kx=`#if NUM_CLIPPING_PLANES > 0+ vec4 plane;+ #ifdef ALPHA_TO_COVERAGE+ float distanceToPlane, distanceGradient;+ float clipOpacity = 1.0;+ #pragma unroll_loop_start+ for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {+ plane = clippingPlanes[ i ];+ distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;+ distanceGradient = fwidth( distanceToPlane ) / 2.0;+ clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );+ if ( clipOpacity == 0.0 ) discard;+ }+ #pragma unroll_loop_end+ #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES+ float unionClipOpacity = 1.0;+ #pragma unroll_loop_start+ for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {+ plane = clippingPlanes[ i ];+ distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;+ distanceGradient = fwidth( distanceToPlane ) / 2.0;+ unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );+ }+ #pragma unroll_loop_end+ clipOpacity *= 1.0 - unionClipOpacity;+ #endif+ diffuseColor.a *= clipOpacity;+ if ( diffuseColor.a == 0.0 ) discard;+ #else+ #pragma unroll_loop_start+ for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {+ plane = clippingPlanes[ i ];+ if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;+ }+ #pragma unroll_loop_end+ #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES+ bool clipped = true;+ #pragma unroll_loop_start+ for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {+ plane = clippingPlanes[ i ];+ clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;+ }+ #pragma unroll_loop_end+ if ( clipped ) discard;+ #endif+ #endif+#endif`,Vx=`#if NUM_CLIPPING_PLANES > 0+ varying vec3 vClipPosition;+ uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];+#endif`,Hx=`#if NUM_CLIPPING_PLANES > 0+ varying vec3 vClipPosition;+#endif`,Gx=`#if NUM_CLIPPING_PLANES > 0+ vClipPosition = - mvPosition.xyz;+#endif`,Wx=`#if defined( USE_COLOR_ALPHA )+ diffuseColor *= vColor;+#elif defined( USE_COLOR )+ diffuseColor.rgb *= vColor;+#endif`,Xx=`#if defined( USE_COLOR_ALPHA )+ varying vec4 vColor;+#elif defined( USE_COLOR )+ varying vec3 vColor;+#endif`,qx=`#if defined( USE_COLOR_ALPHA )+ varying vec4 vColor;+#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )+ varying vec3 vColor;+#endif`,Yx=`#if defined( USE_COLOR_ALPHA )+ vColor = vec4( 1.0 );+#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )+ vColor = vec3( 1.0 );+#endif+#ifdef USE_COLOR+ vColor *= color;+#endif+#ifdef USE_INSTANCING_COLOR+ vColor.xyz *= instanceColor.xyz;+#endif+#ifdef USE_BATCHING_COLOR+ vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) );+ vColor.xyz *= batchingColor.xyz;+#endif`,Zx=`#define PI 3.141592653589793+#define PI2 6.283185307179586+#define PI_HALF 1.5707963267948966+#define RECIPROCAL_PI 0.3183098861837907+#define RECIPROCAL_PI2 0.15915494309189535+#define EPSILON 1e-6+#ifndef saturate+#define saturate( a ) clamp( a, 0.0, 1.0 )+#endif+#define whiteComplement( a ) ( 1.0 - saturate( a ) )+float pow2( const in float x ) { return x*x; }+vec3 pow2( const in vec3 x ) { return x*x; }+float pow3( const in float x ) { return x*x*x; }+float pow4( const in float x ) { float x2 = x*x; return x2*x2; }+float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }+float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }+highp float rand( const in vec2 uv ) {+ const highp float a = 12.9898, b = 78.233, c = 43758.5453;+ highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );+ return fract( sin( sn ) * c );+}+#ifdef HIGH_PRECISION+ float precisionSafeLength( vec3 v ) { return length( v ); }+#else+ float precisionSafeLength( vec3 v ) {+ float maxComponent = max3( abs( v ) );+ return length( v / maxComponent ) * maxComponent;+ }+#endif+struct IncidentLight {+ vec3 color;+ vec3 direction;+ bool visible;+};+struct ReflectedLight {+ vec3 directDiffuse;+ vec3 directSpecular;+ vec3 indirectDiffuse;+ vec3 indirectSpecular;+};+#ifdef USE_ALPHAHASH+ varying vec3 vPosition;+#endif+vec3 transformDirection( in vec3 dir, in mat4 matrix ) {+ return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );+}+vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {+ return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );+}+mat3 transposeMat3( const in mat3 m ) {+ mat3 tmp;+ tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );+ tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );+ tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );+ return tmp;+}+bool isPerspectiveMatrix( mat4 m ) {+ return m[ 2 ][ 3 ] == - 1.0;+}+vec2 equirectUv( in vec3 dir ) {+ float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;+ float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;+ return vec2( u, v );+}+vec3 BRDF_Lambert( const in vec3 diffuseColor ) {+ return RECIPROCAL_PI * diffuseColor;+}+vec3 F_Schlick( const in vec3 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 );+}+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`,Kx=`#ifdef ENVMAP_TYPE_CUBE_UV+ #define cubeUV_minMipLevel 4.0+ #define cubeUV_minTileSize 16.0+ float getFace( vec3 direction ) {+ vec3 absDirection = abs( direction );+ float face = - 1.0;+ if ( absDirection.x > absDirection.z ) {+ if ( absDirection.x > absDirection.y )+ face = direction.x > 0.0 ? 0.0 : 3.0;+ else+ face = direction.y > 0.0 ? 1.0 : 4.0;+ } else {+ if ( absDirection.z > absDirection.y )+ face = direction.z > 0.0 ? 2.0 : 5.0;+ else+ face = direction.y > 0.0 ? 1.0 : 4.0;+ }+ return face;+ }+ vec2 getUV( vec3 direction, float face ) {+ vec2 uv;+ if ( face == 0.0 ) {+ uv = vec2( direction.z, direction.y ) / abs( direction.x );+ } else if ( face == 1.0 ) {+ uv = vec2( - direction.x, - direction.z ) / abs( direction.y );+ } else if ( face == 2.0 ) {+ uv = vec2( - direction.x, direction.y ) / abs( direction.z );+ } else if ( face == 3.0 ) {+ uv = vec2( - direction.z, direction.y ) / abs( direction.x );+ } else if ( face == 4.0 ) {+ uv = vec2( - direction.x, direction.z ) / abs( direction.y );+ } else {+ uv = vec2( direction.x, direction.y ) / abs( direction.z );+ }+ return 0.5 * ( uv + 1.0 );+ }+ vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {+ float face = getFace( direction );+ float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );+ mipInt = max( mipInt, cubeUV_minMipLevel );+ float faceSize = exp2( mipInt );+ highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;+ if ( face > 2.0 ) {+ uv.y += faceSize;+ face -= 3.0;+ }+ uv.x += face * faceSize;+ uv.x += filterInt * 3.0 * cubeUV_minTileSize;+ uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );+ uv.x *= CUBEUV_TEXEL_WIDTH;+ uv.y *= CUBEUV_TEXEL_HEIGHT;+ #ifdef texture2DGradEXT+ return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;+ #else+ return texture2D( envMap, uv ).rgb;+ #endif+ }+ #define cubeUV_r0 1.0+ #define cubeUV_m0 - 2.0+ #define cubeUV_r1 0.8+ #define cubeUV_m1 - 1.0+ #define cubeUV_r4 0.4+ #define cubeUV_m4 2.0+ #define cubeUV_r5 0.305+ #define cubeUV_m5 3.0+ #define cubeUV_r6 0.21+ #define cubeUV_m6 4.0+ float roughnessToMip( float roughness ) {+ float mip = 0.0;+ if ( roughness >= cubeUV_r1 ) {+ mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;+ } else if ( roughness >= cubeUV_r4 ) {+ mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;+ } else if ( roughness >= cubeUV_r5 ) {+ mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;+ } else if ( roughness >= cubeUV_r6 ) {+ mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;+ } else {+ mip = - 2.0 * log2( 1.16 * roughness ); }+ return mip;+ }+ vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {+ float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );+ float mipF = fract( mip );+ float mipInt = floor( mip );+ vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );+ if ( mipF == 0.0 ) {+ return vec4( color0, 1.0 );+ } else {+ vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );+ return vec4( mix( color0, color1, mipF ), 1.0 );+ }+ }+#endif`,Jx=`vec3 transformedNormal = objectNormal;+#ifdef USE_TANGENT+ vec3 transformedTangent = objectTangent;+#endif+#ifdef USE_BATCHING+ mat3 bm = mat3( batchingMatrix );+ transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );+ transformedNormal = bm * transformedNormal;+ #ifdef USE_TANGENT+ transformedTangent = bm * transformedTangent;+ #endif+#endif+#ifdef USE_INSTANCING+ mat3 im = mat3( instanceMatrix );+ transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );+ transformedNormal = im * transformedNormal;+ #ifdef USE_TANGENT+ transformedTangent = im * transformedTangent;+ #endif+#endif+transformedNormal = normalMatrix * transformedNormal;+#ifdef FLIP_SIDED+ transformedNormal = - transformedNormal;+#endif+#ifdef USE_TANGENT+ transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;+ #ifdef FLIP_SIDED+ transformedTangent = - transformedTangent;+ #endif+#endif`,$x=`#ifdef USE_DISPLACEMENTMAP+ uniform sampler2D displacementMap;+ uniform float displacementScale;+ uniform float displacementBias;+#endif`,jx=`#ifdef USE_DISPLACEMENTMAP+ transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );+#endif`,Qx=`#ifdef USE_EMISSIVEMAP+ vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );+ #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE+ emissiveColor = sRGBTransferEOTF( emissiveColor );+ #endif+ totalEmissiveRadiance *= emissiveColor.rgb;+#endif`,e0=`#ifdef USE_EMISSIVEMAP+ uniform sampler2D emissiveMap;+#endif`,t0="gl_FragColor = linearToOutputTexel( gl_FragColor );",n0=`vec4 LinearTransferOETF( in vec4 value ) {+ return value;+}+vec4 sRGBTransferEOTF( in vec4 value ) {+ return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );+}+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 );+}`,i0=`#ifdef USE_ENVMAP+ #ifdef ENV_WORLDPOS+ vec3 cameraToFrag;+ if ( isOrthographic ) {+ cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );+ } else {+ cameraToFrag = normalize( vWorldPosition - cameraPosition );+ }+ vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );+ #ifdef ENVMAP_MODE_REFLECTION+ vec3 reflectVec = reflect( cameraToFrag, worldNormal );+ #else+ vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );+ #endif+ #else+ vec3 reflectVec = vReflect;+ #endif+ #ifdef ENVMAP_TYPE_CUBE+ vec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );+ #else+ vec4 envColor = vec4( 0.0 );+ #endif+ #ifdef ENVMAP_BLENDING_MULTIPLY+ outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );+ #elif defined( ENVMAP_BLENDING_MIX )+ outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );+ #elif defined( ENVMAP_BLENDING_ADD )+ outgoingLight += envColor.xyz * specularStrength * reflectivity;+ #endif+#endif`,s0=`#ifdef USE_ENVMAP+ uniform float envMapIntensity;+ uniform float flipEnvMap;+ uniform mat3 envMapRotation;+ #ifdef ENVMAP_TYPE_CUBE+ uniform samplerCube envMap;+ #else+ uniform sampler2D envMap;+ #endif++#endif`,r0=`#ifdef USE_ENVMAP+ uniform float reflectivity;+ #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )+ #define ENV_WORLDPOS+ #endif+ #ifdef ENV_WORLDPOS+ varying vec3 vWorldPosition;+ uniform float refractionRatio;+ #else+ varying vec3 vReflect;+ #endif+#endif`,o0=`#ifdef USE_ENVMAP+ #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )+ #define ENV_WORLDPOS+ #endif+ #ifdef ENV_WORLDPOS++ varying vec3 vWorldPosition;+ #else+ varying vec3 vReflect;+ uniform float refractionRatio;+ #endif+#endif`,a0=`#ifdef USE_ENVMAP+ #ifdef ENV_WORLDPOS+ vWorldPosition = worldPosition.xyz;+ #else+ vec3 cameraToVertex;+ if ( isOrthographic ) {+ cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );+ } else {+ cameraToVertex = normalize( worldPosition.xyz - cameraPosition );+ }+ vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );+ #ifdef ENVMAP_MODE_REFLECTION+ vReflect = reflect( cameraToVertex, worldNormal );+ #else+ vReflect = refract( cameraToVertex, worldNormal, refractionRatio );+ #endif+ #endif+#endif`,c0=`#ifdef USE_FOG+ vFogDepth = - mvPosition.z;+#endif`,l0=`#ifdef USE_FOG+ varying float vFogDepth;+#endif`,h0=`#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`,u0=`#ifdef USE_FOG+ uniform vec3 fogColor;+ varying float vFogDepth;+ #ifdef FOG_EXP2+ uniform float fogDensity;+ #else+ uniform float fogNear;+ uniform float fogFar;+ #endif+#endif`,d0=`#ifdef USE_GRADIENTMAP+ uniform sampler2D gradientMap;+#endif+vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {+ float dotNL = dot( normal, lightDirection );+ vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );+ #ifdef USE_GRADIENTMAP+ return vec3( texture2D( gradientMap, coord ).r );+ #else+ 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+}`,f0=`#ifdef USE_LIGHTMAP+ uniform sampler2D lightMap;+ uniform float lightMapIntensity;+#endif`,p0=`LambertMaterial material;+material.diffuseColor = diffuseColor.rgb;+material.specularStrength = specularStrength;`,m0=`varying vec3 vViewPosition;+struct LambertMaterial {+ vec3 diffuseColor;+ float specularStrength;+};+void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {+ float dotNL = saturate( dot( geometryNormal, directLight.direction ) );+ vec3 irradiance = dotNL * directLight.color;+ reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );+}+void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {+ reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );+}+#define RE_Direct RE_Direct_Lambert+#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,g0=`uniform bool receiveShadow;+uniform vec3 ambientLightColor;+#if defined( USE_LIGHT_PROBES )+ uniform vec3 lightProbe[ 9 ];+#endif+vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {+ float x = normal.x, y = normal.y, z = normal.z;+ vec3 result = shCoefficients[ 0 ] * 0.886227;+ result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;+ result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;+ result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;+ result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;+ result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;+ result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );+ result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;+ result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );+ return result;+}+vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {+ vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );+ vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );+ return irradiance;+}+vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {+ vec3 irradiance = ambientLightColor;+ return irradiance;+}+float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {+ float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );+ if ( cutoffDistance > 0.0 ) {+ distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );+ }+ return distanceFalloff;+}+float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {+ return smoothstep( coneCosine, penumbraCosine, angleCosine );+}+#if NUM_DIR_LIGHTS > 0+ struct DirectionalLight {+ vec3 direction;+ vec3 color;+ };+ uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];+ void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {+ light.color = directionalLight.color;+ light.direction = directionalLight.direction;+ light.visible = true;+ }+#endif+#if NUM_POINT_LIGHTS > 0+ struct PointLight {+ vec3 position;+ vec3 color;+ float distance;+ float decay;+ };+ uniform PointLight pointLights[ NUM_POINT_LIGHTS ];+ void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {+ vec3 lVector = pointLight.position - geometryPosition;+ light.direction = normalize( lVector );+ float lightDistance = length( lVector );+ light.color = pointLight.color;+ light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );+ light.visible = ( light.color != vec3( 0.0 ) );+ }+#endif+#if NUM_SPOT_LIGHTS > 0+ struct SpotLight {+ vec3 position;+ vec3 direction;+ vec3 color;+ float distance;+ float decay;+ float coneCos;+ float penumbraCos;+ };+ uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];+ void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {+ vec3 lVector = spotLight.position - geometryPosition;+ light.direction = normalize( lVector );+ float angleCos = dot( light.direction, spotLight.direction );+ float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );+ if ( spotAttenuation > 0.0 ) {+ float lightDistance = length( lVector );+ light.color = spotLight.color * spotAttenuation;+ light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );+ light.visible = ( light.color != vec3( 0.0 ) );+ } else {+ light.color = vec3( 0.0 );+ light.visible = false;+ }+ }+#endif+#if NUM_RECT_AREA_LIGHTS > 0+ struct RectAreaLight {+ vec3 color;+ vec3 position;+ vec3 halfWidth;+ vec3 halfHeight;+ };+ uniform sampler2D ltc_1; uniform sampler2D ltc_2;+ uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];+#endif+#if NUM_HEMI_LIGHTS > 0+ struct HemisphereLight {+ vec3 direction;+ vec3 skyColor;+ vec3 groundColor;+ };+ uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];+ vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {+ float dotNL = dot( normal, hemiLight.direction );+ float hemiDiffuseWeight = 0.5 * dotNL + 0.5;+ vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );+ return irradiance;+ }+#endif`,_0=`#ifdef USE_ENVMAP+ vec3 getIBLIrradiance( const in vec3 normal ) {+ #ifdef ENVMAP_TYPE_CUBE_UV+ vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );+ vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 );+ return PI * envMapColor.rgb * envMapIntensity;+ #else+ return vec3( 0.0 );+ #endif+ }+ vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {+ #ifdef ENVMAP_TYPE_CUBE_UV+ vec3 reflectVec = reflect( - viewDir, normal );+ reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );+ reflectVec = inverseTransformDirection( reflectVec, viewMatrix );+ vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );+ return envMapColor.rgb * envMapIntensity;+ #else+ return vec3( 0.0 );+ #endif+ }+ #ifdef USE_ANISOTROPY+ vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {+ #ifdef ENVMAP_TYPE_CUBE_UV+ vec3 bentNormal = cross( bitangent, viewDir );+ bentNormal = normalize( cross( bentNormal, bitangent ) );+ bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );+ return getIBLRadiance( viewDir, bentNormal, roughness );+ #else+ return vec3( 0.0 );+ #endif+ }+ #endif+#endif`,x0=`ToonMaterial material;+material.diffuseColor = diffuseColor.rgb;`,y0=`varying vec3 vViewPosition;+struct ToonMaterial {+ vec3 diffuseColor;+};+void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {+ vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;+ reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );+}+void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {+ reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );+}+#define RE_Direct RE_Direct_Toon+#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,v0=`BlinnPhongMaterial material;+material.diffuseColor = diffuseColor.rgb;+material.specularColor = specular;+material.specularShininess = shininess;+material.specularStrength = specularStrength;`,M0=`varying vec3 vViewPosition;+struct BlinnPhongMaterial {+ vec3 diffuseColor;+ vec3 specularColor;+ float specularShininess;+ float specularStrength;+};+void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {+ float dotNL = saturate( dot( geometryNormal, directLight.direction ) );+ vec3 irradiance = dotNL * directLight.color;+ reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );+ reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;+}+void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {+ reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );+}+#define RE_Direct RE_Direct_BlinnPhong+#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,S0=`PhysicalMaterial material;+material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );+vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );+float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );+material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;+material.roughness = min( material.roughness, 1.0 );+#ifdef IOR+ material.ior = ior;+ #ifdef USE_SPECULAR+ float specularIntensityFactor = specularIntensity;+ vec3 specularColorFactor = specularColor;+ #ifdef USE_SPECULAR_COLORMAP+ specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;+ #endif+ #ifdef USE_SPECULAR_INTENSITYMAP+ specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;+ #endif+ material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );+ #else+ float specularIntensityFactor = 1.0;+ vec3 specularColorFactor = vec3( 1.0 );+ material.specularF90 = 1.0;+ #endif+ material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );+#else+ material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );+ material.specularF90 = 1.0;+#endif+#ifdef USE_CLEARCOAT+ material.clearcoat = clearcoat;+ material.clearcoatRoughness = clearcoatRoughness;+ material.clearcoatF0 = vec3( 0.04 );+ material.clearcoatF90 = 1.0;+ #ifdef USE_CLEARCOATMAP+ material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;+ #endif+ #ifdef USE_CLEARCOAT_ROUGHNESSMAP+ material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;+ #endif+ material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );+ material.clearcoatRoughness += geometryRoughness;+ material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );+#endif+#ifdef USE_DISPERSION+ material.dispersion = dispersion;+#endif+#ifdef USE_IRIDESCENCE+ material.iridescence = iridescence;+ material.iridescenceIOR = iridescenceIOR;+ #ifdef USE_IRIDESCENCEMAP+ material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;+ #endif+ #ifdef USE_IRIDESCENCE_THICKNESSMAP+ material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;+ #else+ material.iridescenceThickness = iridescenceThicknessMaximum;+ #endif+#endif+#ifdef USE_SHEEN+ material.sheenColor = sheenColor;+ #ifdef USE_SHEEN_COLORMAP+ material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;+ #endif+ material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );+ #ifdef USE_SHEEN_ROUGHNESSMAP+ material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;+ #endif+#endif+#ifdef USE_ANISOTROPY+ #ifdef USE_ANISOTROPYMAP+ mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );+ vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;+ vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;+ #else+ vec2 anisotropyV = anisotropyVector;+ #endif+ material.anisotropy = length( anisotropyV );+ if( material.anisotropy == 0.0 ) {+ anisotropyV = vec2( 1.0, 0.0 );+ } else {+ anisotropyV /= material.anisotropy;+ material.anisotropy = saturate( material.anisotropy );+ }+ 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`,b0=`struct PhysicalMaterial {+ vec3 diffuseColor;+ float roughness;+ vec3 specularColor;+ float specularF90;+ float dispersion;+ #ifdef USE_CLEARCOAT+ float clearcoat;+ float clearcoatRoughness;+ vec3 clearcoatF0;+ float clearcoatF90;+ #endif+ #ifdef USE_IRIDESCENCE+ float iridescence;+ float iridescenceIOR;+ float iridescenceThickness;+ vec3 iridescenceFresnel;+ vec3 iridescenceF0;+ #endif+ #ifdef USE_SHEEN+ vec3 sheenColor;+ float sheenRoughness;+ #endif+ #ifdef IOR+ float ior;+ #endif+ #ifdef USE_TRANSMISSION+ float transmission;+ float transmissionAlpha;+ float thickness;+ float attenuationDistance;+ vec3 attenuationColor;+ #endif+ #ifdef USE_ANISOTROPY+ float anisotropy;+ float alphaT;+ vec3 anisotropyT;+ vec3 anisotropyB;+ #endif+};+vec3 clearcoatSpecularDirect = vec3( 0.0 );+vec3 clearcoatSpecularIndirect = vec3( 0.0 );+vec3 sheenSpecularDirect = vec3( 0.0 );+vec3 sheenSpecularIndirect = vec3(0.0 );+vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {+ float x = clamp( 1.0 - dotVH, 0.0, 1.0 );+ float x2 = x * x;+ float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );+ return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );+}+float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {+ float a2 = pow2( alpha );+ float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );+ float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );+ return 0.5 / max( gv + gl, EPSILON );+}+float D_GGX( const in float alpha, const in float dotNH ) {+ float a2 = pow2( alpha );+ float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;+ return RECIPROCAL_PI * a2 / pow2( denom );+}+#ifdef USE_ANISOTROPY+ float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {+ float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );+ float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );+ float v = 0.5 / ( gv + gl );+ return saturate(v);+ }+ float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {+ float a2 = alphaT * alphaB;+ highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );+ highp float v2 = dot( v, v );+ float w2 = a2 / v2;+ return RECIPROCAL_PI * a2 * pow2 ( w2 );+ }+#endif+#ifdef USE_CLEARCOAT+ vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {+ vec3 f0 = material.clearcoatF0;+ float f90 = material.clearcoatF90;+ float roughness = material.clearcoatRoughness;+ float alpha = pow2( roughness );+ vec3 halfDir = normalize( lightDir + viewDir );+ float dotNL = saturate( dot( normal, lightDir ) );+ float dotNV = saturate( dot( normal, viewDir ) );+ float dotNH = saturate( dot( normal, halfDir ) );+ float dotVH = saturate( dot( viewDir, halfDir ) );+ vec3 F = F_Schlick( f0, f90, dotVH );+ float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );+ float D = D_GGX( alpha, dotNH );+ return F * ( V * D );+ }+#endif+vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {+ vec3 f0 = material.specularColor;+ float f90 = material.specularF90;+ float roughness = material.roughness;+ float alpha = pow2( roughness );+ vec3 halfDir = normalize( lightDir + viewDir );+ float dotNL = saturate( dot( normal, lightDir ) );+ float dotNV = saturate( dot( normal, viewDir ) );+ float dotNH = saturate( dot( normal, halfDir ) );+ float dotVH = saturate( dot( viewDir, halfDir ) );+ vec3 F = F_Schlick( f0, f90, dotVH );+ #ifdef USE_IRIDESCENCE+ F = mix( F, material.iridescenceFresnel, material.iridescence );+ #endif+ #ifdef USE_ANISOTROPY+ float dotTL = dot( material.anisotropyT, lightDir );+ float dotTV = dot( material.anisotropyT, viewDir );+ float dotTH = dot( material.anisotropyT, halfDir );+ float dotBL = dot( material.anisotropyB, lightDir );+ float dotBV = dot( material.anisotropyB, viewDir );+ float dotBH = dot( material.anisotropyB, halfDir );+ float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );+ float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );+ #else+ float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );+ float D = D_GGX( alpha, dotNH );+ #endif+ return F * ( V * D );+}+vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {+ const float LUT_SIZE = 64.0;+ const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;+ const float LUT_BIAS = 0.5 / LUT_SIZE;+ float dotNV = saturate( dot( N, V ) );+ vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );+ uv = uv * LUT_SCALE + LUT_BIAS;+ return uv;+}+float LTC_ClippedSphereFormFactor( const in vec3 f ) {+ float l = length( f );+ return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );+}+vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {+ float x = dot( v1, v2 );+ float y = abs( x );+ float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;+ float b = 3.4175940 + ( 4.1616724 + y ) * y;+ float v = a / b;+ float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;+ return cross( v1, v2 ) * theta_sintheta;+}+vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {+ vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];+ vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];+ vec3 lightNormal = cross( v1, v2 );+ if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );+ vec3 T1, T2;+ T1 = normalize( V - N * dot( V, N ) );+ T2 = - cross( N, T1 );+ mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );+ vec3 coords[ 4 ];+ coords[ 0 ] = mat * ( rectCoords[ 0 ] - P );+ coords[ 1 ] = mat * ( rectCoords[ 1 ] - P );+ coords[ 2 ] = mat * ( rectCoords[ 2 ] - P );+ coords[ 3 ] = mat * ( rectCoords[ 3 ] - P );+ coords[ 0 ] = normalize( coords[ 0 ] );+ coords[ 1 ] = normalize( coords[ 1 ] );+ coords[ 2 ] = normalize( coords[ 2 ] );+ coords[ 3 ] = normalize( coords[ 3 ] );+ vec3 vectorFormFactor = vec3( 0.0 );+ vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );+ vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );+ vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );+ vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );+ float result = LTC_ClippedSphereFormFactor( vectorFormFactor );+ return vec3( result );+}+#if defined( USE_SHEEN )+float D_Charlie( float roughness, float dotNH ) {+ float alpha = pow2( roughness );+ float invAlpha = 1.0 / alpha;+ float cos2h = dotNH * dotNH;+ float sin2h = max( 1.0 - cos2h, 0.0078125 );+ return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );+}+float V_Neubelt( float dotNV, float dotNL ) {+ return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );+}+vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {+ vec3 halfDir = normalize( lightDir + viewDir );+ float dotNL = saturate( dot( normal, lightDir ) );+ float dotNV = saturate( dot( normal, viewDir ) );+ float dotNH = saturate( dot( normal, halfDir ) );+ float D = D_Charlie( sheenRoughness, dotNH );+ float V = V_Neubelt( dotNV, dotNL );+ return sheenColor * ( D * V );+}+#endif+float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {+ float dotNV = saturate( dot( normal, viewDir ) );+ float r2 = roughness * roughness;+ float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;+ float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;+ float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );+ return saturate( DG * RECIPROCAL_PI );+}+vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {+ float dotNV = saturate( dot( normal, viewDir ) );+ const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );+ const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );+ vec4 r = roughness * c0 + c1;+ float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;+ vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;+ return fab;+}+vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {+ vec2 fab = DFGApprox( normal, viewDir, roughness );+ return specularColor * fab.x + specularF90 * fab.y;+}+#ifdef USE_IRIDESCENCE+void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {+#else+void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {+#endif+ vec2 fab = DFGApprox( normal, viewDir, roughness );+ #ifdef USE_IRIDESCENCE+ vec3 Fr = mix( specularColor, iridescenceF0, iridescence );+ #else+ vec3 Fr = specularColor;+ #endif+ vec3 FssEss = Fr * fab.x + specularF90 * fab.y;+ float Ess = fab.x + fab.y;+ float Ems = 1.0 - Ess;+ vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );+ singleScatter += FssEss;+ multiScatter += Fms * Ems;+}+#if NUM_RECT_AREA_LIGHTS > 0+ void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {+ vec3 normal = geometryNormal;+ vec3 viewDir = geometryViewDir;+ vec3 position = geometryPosition;+ vec3 lightPos = rectAreaLight.position;+ vec3 halfWidth = rectAreaLight.halfWidth;+ vec3 halfHeight = rectAreaLight.halfHeight;+ vec3 lightColor = rectAreaLight.color;+ float roughness = material.roughness;+ vec3 rectCoords[ 4 ];+ rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight;+ rectCoords[ 2 ] = lightPos - halfWidth + halfHeight;+ rectCoords[ 3 ] = lightPos + halfWidth + halfHeight;+ vec2 uv = LTC_Uv( normal, viewDir, roughness );+ vec4 t1 = texture2D( ltc_1, uv );+ vec4 t2 = texture2D( ltc_2, uv );+ mat3 mInv = mat3(+ vec3( t1.x, 0, t1.y ),+ vec3( 0, 1, 0 ),+ vec3( t1.z, 0, t1.w )+ );+ vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );+ reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );+ reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );+ }+#endif+void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {+ float dotNL = saturate( dot( geometryNormal, directLight.direction ) );+ vec3 irradiance = dotNL * directLight.color;+ #ifdef USE_CLEARCOAT+ float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );+ vec3 ccIrradiance = dotNLcc * directLight.color;+ clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );+ #endif+ #ifdef USE_SHEEN+ sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );+ #endif+ reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );+ reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );+}+void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {+ reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );+}+void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {+ #ifdef USE_CLEARCOAT+ clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );+ #endif+ #ifdef USE_SHEEN+ sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );+ #endif+ vec3 singleScattering = vec3( 0.0 );+ vec3 multiScattering = vec3( 0.0 );+ vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;+ #ifdef USE_IRIDESCENCE+ computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );+ #else+ computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );+ #endif+ vec3 totalScattering = singleScattering + multiScattering;+ vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );+ reflectedLight.indirectSpecular += radiance * singleScattering;+ reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;+ reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;+}+#define RE_Direct RE_Direct_Physical+#define RE_Direct_RectArea RE_Direct_RectArea_Physical+#define RE_IndirectDiffuse RE_IndirectDiffuse_Physical+#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 );+}`,T0=`+vec3 geometryPosition = - vViewPosition;+vec3 geometryNormal = normal;+vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );+vec3 geometryClearcoatNormal = vec3( 0.0 );+#ifdef USE_CLEARCOAT+ geometryClearcoatNormal = clearcoatNormal;+#endif+#ifdef USE_IRIDESCENCE+ float dotNVi = saturate( dot( normal, geometryViewDir ) );+ if ( material.iridescenceThickness == 0.0 ) {+ material.iridescence = 0.0;+ } else {+ material.iridescence = saturate( material.iridescence );+ }+ if ( material.iridescence > 0.0 ) {+ material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );+ material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );+ }+#endif+IncidentLight directLight;+#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )+ PointLight pointLight;+ #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0+ PointLightShadow pointLightShadow;+ #endif+ #pragma unroll_loop_start+ for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {+ pointLight = pointLights[ i ];+ getPointLightInfo( pointLight, geometryPosition, directLight );+ #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )+ pointLightShadow = pointLightShadows[ i ];+ directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;+ #endif+ RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );+ }+ #pragma unroll_loop_end+#endif+#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )+ SpotLight spotLight;+ vec4 spotColor;+ vec3 spotLightCoord;+ bool inSpotLightMap;+ #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0+ SpotLightShadow spotLightShadow;+ #endif+ #pragma unroll_loop_start+ for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {+ spotLight = spotLights[ i ];+ getSpotLightInfo( spotLight, geometryPosition, directLight );+ #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )+ #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX+ #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )+ #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS+ #else+ #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )+ #endif+ #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )+ spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;+ inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );+ spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );+ directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;+ #endif+ #undef SPOT_LIGHT_MAP_INDEX+ #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )+ spotLightShadow = spotLightShadows[ i ];+ directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;+ #endif+ RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );+ }+ #pragma unroll_loop_end+#endif+#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )+ DirectionalLight directionalLight;+ #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0+ DirectionalLightShadow directionalLightShadow;+ #endif+ #pragma unroll_loop_start+ for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {+ directionalLight = directionalLights[ i ];+ getDirectionalLightInfo( directionalLight, directLight );+ #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )+ directionalLightShadow = directionalLightShadows[ i ];+ directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;+ #endif+ RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );+ }+ #pragma unroll_loop_end+#endif+#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )+ RectAreaLight rectAreaLight;+ #pragma unroll_loop_start+ for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {+ rectAreaLight = rectAreaLights[ i ];+ RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );+ }+ #pragma unroll_loop_end+#endif+#if defined( RE_IndirectDiffuse )+ vec3 iblIrradiance = vec3( 0.0 );+ vec3 irradiance = getAmbientLightIrradiance( ambientLightColor );+ #if defined( USE_LIGHT_PROBES )+ irradiance += getLightProbeIrradiance( lightProbe, geometryNormal );+ #endif+ #if ( NUM_HEMI_LIGHTS > 0 )+ #pragma unroll_loop_start+ for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {+ irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );+ }+ #pragma unroll_loop_end+ #endif+#endif+#if defined( RE_IndirectSpecular )+ vec3 radiance = vec3( 0.0 );+ vec3 clearcoatRadiance = vec3( 0.0 );+#endif`,E0=`#if defined( RE_IndirectDiffuse )+ #ifdef USE_LIGHTMAP+ vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );+ vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;+ irradiance += lightMapIrradiance;+ #endif+ #if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )+ iblIrradiance += getIBLIrradiance( geometryNormal );+ #endif+#endif+#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )+ #ifdef USE_ANISOTROPY+ radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );+ #else+ radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );+ #endif+ #ifdef USE_CLEARCOAT+ clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );+ #endif+#endif`,A0=`#if defined( RE_IndirectDiffuse )+ RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );+#endif+#if defined( RE_IndirectSpecular )+ RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );+#endif`,w0=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )+ gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;+#endif`,R0=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )+ uniform float logDepthBufFC;+ varying float vFragDepth;+ varying float vIsPerspective;+#endif`,C0=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER+ varying float vFragDepth;+ varying float vIsPerspective;+#endif`,I0=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER+ vFragDepth = 1.0 + gl_Position.w;+ vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );+#endif`,P0=`#ifdef USE_MAP+ vec4 sampledDiffuseColor = texture2D( map, vMapUv );+ #ifdef DECODE_VIDEO_TEXTURE+ sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );+ #endif+ diffuseColor *= sampledDiffuseColor;+#endif`,L0=`#ifdef USE_MAP+ uniform sampler2D map;+#endif`,D0=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP )+ #if defined( USE_POINTS_UV )+ vec2 uv = vUv;+ #else+ vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;+ #endif+#endif+#ifdef USE_MAP+ diffuseColor *= texture2D( map, uv );+#endif+#ifdef USE_ALPHAMAP+ diffuseColor.a *= texture2D( alphaMap, uv ).g;+#endif`,N0=`#if defined( USE_POINTS_UV )+ varying vec2 vUv;+#else+ #if defined( USE_MAP ) || defined( USE_ALPHAMAP )+ uniform mat3 uvTransform;+ #endif+#endif+#ifdef USE_MAP+ uniform sampler2D map;+#endif+#ifdef USE_ALPHAMAP+ uniform sampler2D alphaMap;+#endif`,U0=`float metalnessFactor = metalness;+#ifdef USE_METALNESSMAP+ vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );+ metalnessFactor *= texelMetalness.b;+#endif`,F0=`#ifdef USE_METALNESSMAP+ uniform sampler2D metalnessMap;+#endif`,O0=`#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`,B0=`#if defined( USE_MORPHCOLORS )+ vColor *= morphTargetBaseInfluence;+ for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {+ #if defined( USE_COLOR_ALPHA )+ if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];+ #elif defined( USE_COLOR )+ if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];+ #endif+ }+#endif`,z0=`#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`,k0=`#ifdef USE_MORPHTARGETS+ #ifndef USE_INSTANCING_MORPH+ uniform float morphTargetBaseInfluence;+ uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];+ #endif+ uniform sampler2DArray morphTargetsTexture;+ uniform ivec2 morphTargetsTextureSize;+ vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {+ int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;+ int y = texelIndex / morphTargetsTextureSize.x;+ int x = texelIndex - y * morphTargetsTextureSize.x;+ ivec3 morphUV = ivec3( x, y, morphTargetIndex );+ return texelFetch( morphTargetsTexture, morphUV, 0 );+ }+#endif`,V0=`#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`,H0=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;+#ifdef FLAT_SHADED+ vec3 fdx = dFdx( vViewPosition );+ vec3 fdy = dFdy( vViewPosition );+ vec3 normal = normalize( cross( fdx, fdy ) );+#else+ vec3 normal = normalize( vNormal );+ #ifdef DOUBLE_SIDED+ normal *= faceDirection;+ #endif+#endif+#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )+ #ifdef USE_TANGENT+ mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );+ #else+ mat3 tbn = getTangentFrame( - vViewPosition, normal,+ #if defined( USE_NORMALMAP )+ vNormalMapUv+ #elif defined( USE_CLEARCOAT_NORMALMAP )+ vClearcoatNormalMapUv+ #else+ vUv+ #endif+ );+ #endif+ #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )+ tbn[0] *= faceDirection;+ tbn[1] *= faceDirection;+ #endif+#endif+#ifdef USE_CLEARCOAT_NORMALMAP+ #ifdef USE_TANGENT+ mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );+ #else+ mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );+ #endif+ #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )+ tbn2[0] *= faceDirection;+ tbn2[1] *= faceDirection;+ #endif+#endif+vec3 nonPerturbedNormal = normal;`,G0=`#ifdef USE_NORMALMAP_OBJECTSPACE+ normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;+ #ifdef FLIP_SIDED+ normal = - normal;+ #endif+ #ifdef DOUBLE_SIDED+ normal = normal * faceDirection;+ #endif+ normal = normalize( normalMatrix * normal );+#elif defined( USE_NORMALMAP_TANGENTSPACE )+ vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;+ mapN.xy *= normalScale;+ normal = normalize( tbn * mapN );+#elif defined( USE_BUMPMAP )+ normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );+#endif`,W0=`#ifndef FLAT_SHADED+ varying vec3 vNormal;+ #ifdef USE_TANGENT+ varying vec3 vTangent;+ varying vec3 vBitangent;+ #endif+#endif`,X0=`#ifndef FLAT_SHADED+ varying vec3 vNormal;+ #ifdef USE_TANGENT+ varying vec3 vTangent;+ varying vec3 vBitangent;+ #endif+#endif`,q0=`#ifndef FLAT_SHADED+ vNormal = normalize( transformedNormal );+ #ifdef USE_TANGENT+ vTangent = normalize( transformedTangent );+ vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );+ #endif+#endif`,Y0=`#ifdef USE_NORMALMAP+ uniform sampler2D normalMap;+ uniform vec2 normalScale;+#endif+#ifdef USE_NORMALMAP_OBJECTSPACE+ uniform mat3 normalMatrix;+#endif+#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )+ mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {+ vec3 q0 = dFdx( eye_pos.xyz );+ vec3 q1 = dFdy( eye_pos.xyz );+ vec2 st0 = dFdx( uv.st );+ vec2 st1 = dFdy( uv.st );+ vec3 N = surf_norm;+ vec3 q1perp = cross( q1, N );+ vec3 q0perp = cross( N, q0 );+ vec3 T = q1perp * st0.x + q0perp * st1.x;+ vec3 B = q1perp * st0.y + q0perp * st1.y;+ float det = max( dot( T, T ), dot( B, B ) );+ float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );+ return mat3( T * scale, B * scale, N );+ }+#endif`,Z0=`#ifdef USE_CLEARCOAT+ vec3 clearcoatNormal = nonPerturbedNormal;+#endif`,K0=`#ifdef USE_CLEARCOAT_NORMALMAP+ vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;+ clearcoatMapN.xy *= clearcoatNormalScale;+ clearcoatNormal = normalize( tbn2 * clearcoatMapN );+#endif`,J0=`#ifdef USE_CLEARCOATMAP+ uniform sampler2D clearcoatMap;+#endif+#ifdef USE_CLEARCOAT_NORMALMAP+ uniform sampler2D clearcoatNormalMap;+ uniform vec2 clearcoatNormalScale;+#endif+#ifdef USE_CLEARCOAT_ROUGHNESSMAP+ uniform sampler2D clearcoatRoughnessMap;+#endif`,$0=`#ifdef USE_IRIDESCENCEMAP+ uniform sampler2D iridescenceMap;+#endif+#ifdef USE_IRIDESCENCE_THICKNESSMAP+ uniform sampler2D iridescenceThicknessMap;+#endif`,j0=`#ifdef OPAQUE+diffuseColor.a = 1.0;+#endif+#ifdef USE_TRANSMISSION+diffuseColor.a *= material.transmissionAlpha;+#endif+gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,Q0=`vec3 packNormalToRGB( const in vec3 normal ) {+ return normalize( normal ) * 0.5 + 0.5;+}+vec3 unpackRGBToNormal( const in vec3 rgb ) {+ return 2.0 * rgb.xyz - 1.0;+}+const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.;+const float Inv255 = 1. / 255.;+const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 );+const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g );+const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b );+const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a );+vec4 packDepthToRGBA( const in float v ) {+ if( v <= 0.0 )+ return vec4( 0., 0., 0., 0. );+ if( v >= 1.0 )+ return vec4( 1., 1., 1., 1. );+ float vuf;+ float af = modf( v * PackFactors.a, vuf );+ float bf = modf( vuf * ShiftRight8, vuf );+ float gf = modf( vuf * ShiftRight8, vuf );+ return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af );+}+vec3 packDepthToRGB( const in float v ) {+ if( v <= 0.0 )+ return vec3( 0., 0., 0. );+ if( v >= 1.0 )+ return vec3( 1., 1., 1. );+ float vuf;+ float bf = modf( v * PackFactors.b, vuf );+ float gf = modf( vuf * ShiftRight8, vuf );+ return vec3( vuf * Inv255, gf * PackUpscale, bf );+}+vec2 packDepthToRG( const in float v ) {+ if( v <= 0.0 )+ return vec2( 0., 0. );+ if( v >= 1.0 )+ return vec2( 1., 1. );+ float vuf;+ float gf = modf( v * 256., vuf );+ return vec2( vuf * Inv255, gf );+}+float unpackRGBAToDepth( const in vec4 v ) {+ return dot( v, UnpackFactors4 );+}+float unpackRGBToDepth( const in vec3 v ) {+ return dot( v, UnpackFactors3 );+}+float unpackRGToDepth( const in vec2 v ) {+ return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g;+}+vec4 pack2HalfToRGBA( const in vec2 v ) {+ vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );+ return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );+}+vec2 unpackRGBATo2Half( const in vec4 v ) {+ return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );+}+float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {+ return ( viewZ + near ) / ( near - far );+}+float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {+ return depth * ( near - far ) - near;+}+float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {+ return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );+}+float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {+ return ( near * far ) / ( ( far - near ) * depth - far );+}`,ey=`#ifdef PREMULTIPLIED_ALPHA+ gl_FragColor.rgb *= gl_FragColor.a;+#endif`,ty=`vec4 mvPosition = vec4( transformed, 1.0 );+#ifdef USE_BATCHING+ mvPosition = batchingMatrix * mvPosition;+#endif+#ifdef USE_INSTANCING+ mvPosition = instanceMatrix * mvPosition;+#endif+mvPosition = modelViewMatrix * mvPosition;+gl_Position = projectionMatrix * mvPosition;`,ny=`#ifdef DITHERING+ gl_FragColor.rgb = dithering( gl_FragColor.rgb );+#endif`,iy=`#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`,sy=`float roughnessFactor = roughness;+#ifdef USE_ROUGHNESSMAP+ vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );+ roughnessFactor *= texelRoughness.g;+#endif`,ry=`#ifdef USE_ROUGHNESSMAP+ uniform sampler2D roughnessMap;+#endif`,oy=`#if NUM_SPOT_LIGHT_COORDS > 0+ varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];+#endif+#if NUM_SPOT_LIGHT_MAPS > 0+ uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];+#endif+#ifdef USE_SHADOWMAP+ #if NUM_DIR_LIGHT_SHADOWS > 0+ uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];+ varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];+ struct DirectionalLightShadow {+ float shadowIntensity;+ float shadowBias;+ float shadowNormalBias;+ float shadowRadius;+ vec2 shadowMapSize;+ };+ uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];+ #endif+ #if NUM_SPOT_LIGHT_SHADOWS > 0+ uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];+ struct SpotLightShadow {+ float shadowIntensity;+ float shadowBias;+ float shadowNormalBias;+ float shadowRadius;+ vec2 shadowMapSize;+ };+ uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];+ #endif+ #if NUM_POINT_LIGHT_SHADOWS > 0+ uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];+ varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];+ struct PointLightShadow {+ float shadowIntensity;+ float shadowBias;+ float shadowNormalBias;+ float shadowRadius;+ vec2 shadowMapSize;+ float shadowCameraNear;+ float shadowCameraFar;+ };+ uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];+ #endif+ float texture2DCompare( sampler2D depths, vec2 uv, float compare ) {+ float depth = unpackRGBAToDepth( texture2D( depths, uv ) );+ #ifdef USE_REVERSED_DEPTH_BUFFER+ return step( depth, compare );+ #else+ return step( compare, depth );+ #endif+ }+ vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {+ return unpackRGBATo2Half( texture2D( shadow, uv ) );+ }+ float VSMShadow( sampler2D shadow, vec2 uv, float compare ) {+ float occlusion = 1.0;+ vec2 distribution = texture2DDistribution( shadow, uv );+ #ifdef USE_REVERSED_DEPTH_BUFFER+ float hard_shadow = step( distribution.x, compare );+ #else+ float hard_shadow = step( compare, distribution.x );+ #endif+ if ( hard_shadow != 1.0 ) {+ float distance = compare - distribution.x;+ float variance = max( 0.00000, distribution.y * distribution.y );+ float softness_probability = variance / (variance + distance * distance ); softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 ); occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );+ }+ return occlusion;+ }+ float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {+ float shadow = 1.0;+ shadowCoord.xyz /= shadowCoord.w;+ shadowCoord.z += shadowBias;+ bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;+ bool frustumTest = inFrustum && shadowCoord.z <= 1.0;+ if ( frustumTest ) {+ #if defined( SHADOWMAP_TYPE_PCF )+ vec2 texelSize = vec2( 1.0 ) / shadowMapSize;+ float dx0 = - texelSize.x * shadowRadius;+ float dy0 = - texelSize.y * shadowRadius;+ float dx1 = + texelSize.x * shadowRadius;+ float dy1 = + texelSize.y * shadowRadius;+ float dx2 = dx0 / 2.0;+ float dy2 = dy0 / 2.0;+ float dx3 = dx1 / 2.0;+ float dy3 = dy1 / 2.0;+ shadow = (+ texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) ++ texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) ++ texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) ++ texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) ++ texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) ++ texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) ++ texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) ++ texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) ++ texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) ++ texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) ++ texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) ++ texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) ++ texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) ++ texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) ++ texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) ++ texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) ++ texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )+ ) * ( 1.0 / 17.0 );+ #elif defined( SHADOWMAP_TYPE_PCF_SOFT )+ vec2 texelSize = vec2( 1.0 ) / shadowMapSize;+ float dx = texelSize.x;+ float dy = texelSize.y;+ vec2 uv = shadowCoord.xy;+ vec2 f = fract( uv * shadowMapSize + 0.5 );+ uv -= f * texelSize;+ shadow = (+ texture2DCompare( shadowMap, uv, shadowCoord.z ) ++ texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) ++ texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) ++ texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) ++ mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),+ texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),+ f.x ) ++ mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),+ texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),+ f.x ) ++ mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),+ texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),+ f.y ) ++ mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),+ texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),+ f.y ) ++ mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),+ texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),+ f.x ),+ mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),+ texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),+ f.x ),+ f.y )+ ) * ( 1.0 / 9.0 );+ #elif defined( SHADOWMAP_TYPE_VSM )+ shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );+ #else+ shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );+ #endif+ }+ return mix( 1.0, shadow, shadowIntensity );+ }+ vec2 cubeToUV( vec3 v, float texelSizeY ) {+ vec3 absV = abs( v );+ float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );+ absV *= scaleToCube;+ v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );+ vec2 planar = v.xy;+ float almostATexel = 1.5 * texelSizeY;+ float almostOne = 1.0 - almostATexel;+ if ( absV.z >= almostOne ) {+ if ( v.z > 0.0 )+ planar.x = 4.0 - v.x;+ } else if ( absV.x >= almostOne ) {+ float signX = sign( v.x );+ planar.x = v.z * signX + 2.0 * signX;+ } else if ( absV.y >= almostOne ) {+ float signY = sign( v.y );+ planar.x = v.x + 2.0 * signY + 2.0;+ planar.y = v.z * signY - 2.0;+ }+ return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );+ }+ float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {+ float shadow = 1.0;+ vec3 lightToPosition = shadowCoord.xyz;++ float lightToPositionLength = length( lightToPosition );+ if ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) {+ float dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); dp += shadowBias;+ vec3 bd3D = normalize( lightToPosition );+ vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );+ #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )+ vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;+ shadow = (+ texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) ++ texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) ++ texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) ++ texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) ++ texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) ++ texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) ++ texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) ++ texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) ++ texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )+ ) * ( 1.0 / 9.0 );+ #else+ shadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );+ #endif+ }+ return mix( 1.0, shadow, shadowIntensity );+ }+#endif`,ay=`#if NUM_SPOT_LIGHT_COORDS > 0+ uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];+ varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];+#endif+#ifdef USE_SHADOWMAP+ #if NUM_DIR_LIGHT_SHADOWS > 0+ uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];+ varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];+ struct DirectionalLightShadow {+ float shadowIntensity;+ float shadowBias;+ float shadowNormalBias;+ float shadowRadius;+ vec2 shadowMapSize;+ };+ uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];+ #endif+ #if NUM_SPOT_LIGHT_SHADOWS > 0+ struct SpotLightShadow {+ float shadowIntensity;+ float shadowBias;+ float shadowNormalBias;+ float shadowRadius;+ vec2 shadowMapSize;+ };+ uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];+ #endif+ #if NUM_POINT_LIGHT_SHADOWS > 0+ uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];+ varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];+ struct PointLightShadow {+ float shadowIntensity;+ float shadowBias;+ float shadowNormalBias;+ float shadowRadius;+ vec2 shadowMapSize;+ float shadowCameraNear;+ float shadowCameraFar;+ };+ uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];+ #endif+#endif`,cy=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )+ vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );+ vec4 shadowWorldPosition;+#endif+#if defined( USE_SHADOWMAP )+ #if NUM_DIR_LIGHT_SHADOWS > 0+ #pragma unroll_loop_start+ for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {+ shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );+ vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;+ }+ #pragma unroll_loop_end+ #endif+ #if NUM_POINT_LIGHT_SHADOWS > 0+ #pragma unroll_loop_start+ for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {+ shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );+ vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;+ }+ #pragma unroll_loop_end+ #endif+#endif+#if NUM_SPOT_LIGHT_COORDS > 0+ #pragma unroll_loop_start+ for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {+ shadowWorldPosition = worldPosition;+ #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )+ shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;+ #endif+ vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;+ }+ #pragma unroll_loop_end+#endif`,ly=`float getShadowMask() {+ float shadow = 1.0;+ #ifdef USE_SHADOWMAP+ #if NUM_DIR_LIGHT_SHADOWS > 0+ DirectionalLightShadow directionalLight;+ #pragma unroll_loop_start+ for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {+ directionalLight = directionalLightShadows[ i ];+ shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;+ }+ #pragma unroll_loop_end+ #endif+ #if NUM_SPOT_LIGHT_SHADOWS > 0+ SpotLightShadow spotLight;+ #pragma unroll_loop_start+ for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {+ spotLight = spotLightShadows[ i ];+ shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;+ }+ #pragma unroll_loop_end+ #endif+ #if NUM_POINT_LIGHT_SHADOWS > 0+ PointLightShadow pointLight;+ #pragma unroll_loop_start+ for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {+ pointLight = pointLightShadows[ i ];+ shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;+ }+ #pragma unroll_loop_end+ #endif+ #endif+ return shadow;+}`,hy=`#ifdef USE_SKINNING+ mat4 boneMatX = getBoneMatrix( skinIndex.x );+ mat4 boneMatY = getBoneMatrix( skinIndex.y );+ mat4 boneMatZ = getBoneMatrix( skinIndex.z );+ mat4 boneMatW = getBoneMatrix( skinIndex.w );+#endif`,uy=`#ifdef USE_SKINNING+ uniform mat4 bindMatrix;+ uniform mat4 bindMatrixInverse;+ uniform highp sampler2D boneTexture;+ mat4 getBoneMatrix( const in float i ) {+ int size = textureSize( boneTexture, 0 ).x;+ int j = int( i ) * 4;+ int x = j % size;+ int y = j / size;+ vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );+ vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );+ vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );+ vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );+ return mat4( v1, v2, v3, v4 );+ }+#endif`,dy=`#ifdef USE_SKINNING+ vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );+ vec4 skinned = vec4( 0.0 );+ skinned += boneMatX * skinVertex * skinWeight.x;+ skinned += boneMatY * skinVertex * skinWeight.y;+ skinned += boneMatZ * skinVertex * skinWeight.z;+ skinned += boneMatW * skinVertex * skinWeight.w;+ transformed = ( bindMatrixInverse * skinned ).xyz;+#endif`,fy=`#ifdef USE_SKINNING+ mat4 skinMatrix = mat4( 0.0 );+ skinMatrix += skinWeight.x * boneMatX;+ skinMatrix += skinWeight.y * boneMatY;+ skinMatrix += skinWeight.z * boneMatZ;+ skinMatrix += skinWeight.w * boneMatW;+ skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;+ objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;+ #ifdef USE_TANGENT+ objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;+ #endif+#endif`,py=`float specularStrength;+#ifdef USE_SPECULARMAP+ vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );+ specularStrength = texelSpecular.r;+#else+ specularStrength = 1.0;+#endif`,my=`#ifdef USE_SPECULARMAP+ uniform sampler2D specularMap;+#endif`,gy=`#if defined( TONE_MAPPING )+ gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );+#endif`,_y=`#ifndef saturate+#define saturate( a ) clamp( a, 0.0, 1.0 )+#endif+uniform float toneMappingExposure;+vec3 LinearToneMapping( vec3 color ) {+ return saturate( toneMappingExposure * color );+}+vec3 ReinhardToneMapping( vec3 color ) {+ color *= toneMappingExposure;+ return saturate( color / ( vec3( 1.0 ) + color ) );+}+vec3 CineonToneMapping( vec3 color ) {+ color *= toneMappingExposure;+ color = max( vec3( 0.0 ), color - 0.004 );+ return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );+}+vec3 RRTAndODTFit( vec3 v ) {+ vec3 a = v * ( v + 0.0245786 ) - 0.000090537;+ vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;+ return a / b;+}+vec3 ACESFilmicToneMapping( vec3 color ) {+ const mat3 ACESInputMat = mat3(+ vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ),+ vec3( 0.04823, 0.01566, 0.83777 )+ );+ const mat3 ACESOutputMat = mat3(+ vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ),+ vec3( -0.07367, -0.00605, 1.07602 )+ );+ color *= toneMappingExposure / 0.6;+ color = ACESInputMat * color;+ color = RRTAndODTFit( color );+ color = ACESOutputMat * color;+ return saturate( color );+}+const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(+ vec3( 1.6605, - 0.1246, - 0.0182 ),+ vec3( - 0.5876, 1.1329, - 0.1006 ),+ vec3( - 0.0728, - 0.0083, 1.1187 )+);+const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(+ vec3( 0.6274, 0.0691, 0.0164 ),+ vec3( 0.3293, 0.9195, 0.0880 ),+ vec3( 0.0433, 0.0113, 0.8956 )+);+vec3 agxDefaultContrastApprox( vec3 x ) {+ vec3 x2 = x * x;+ vec3 x4 = x2 * x2;+ return + 15.5 * x4 * x2+ - 40.14 * x4 * x+ + 31.96 * x4+ - 6.868 * x2 * x+ + 0.4298 * x2+ + 0.1191 * x+ - 0.00232;+}+vec3 AgXToneMapping( vec3 color ) {+ const mat3 AgXInsetMatrix = mat3(+ vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),+ vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),+ vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )+ );+ const mat3 AgXOutsetMatrix = mat3(+ vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),+ vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),+ vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )+ );+ const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069;+ color *= toneMappingExposure;+ color = LINEAR_SRGB_TO_LINEAR_REC2020 * color;+ color = AgXInsetMatrix * color;+ color = max( color, 1e-10 ); color = log2( color );+ color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );+ color = clamp( color, 0.0, 1.0 );+ color = agxDefaultContrastApprox( color );+ color = AgXOutsetMatrix * color;+ color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );+ color = LINEAR_REC2020_TO_LINEAR_SRGB * color;+ color = clamp( color, 0.0, 1.0 );+ return color;+}+vec3 NeutralToneMapping( vec3 color ) {+ const float StartCompression = 0.8 - 0.04;+ const float Desaturation = 0.15;+ color *= toneMappingExposure;+ float x = min( color.r, min( color.g, color.b ) );+ float offset = x < 0.08 ? x - 6.25 * x * x : 0.04;+ color -= offset;+ float peak = max( color.r, max( color.g, color.b ) );+ if ( peak < StartCompression ) return color;+ float d = 1. - StartCompression;+ float newPeak = 1. - d * d / ( peak + d - StartCompression );+ color *= newPeak / peak;+ float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );+ return mix( color, vec3( newPeak ), g );+}+vec3 CustomToneMapping( vec3 color ) { return color; }`,xy=`#ifdef USE_TRANSMISSION+ material.transmission = transmission;+ material.transmissionAlpha = 1.0;+ material.thickness = thickness;+ material.attenuationDistance = attenuationDistance;+ material.attenuationColor = attenuationColor;+ #ifdef USE_TRANSMISSIONMAP+ material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;+ #endif+ #ifdef USE_THICKNESSMAP+ material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;+ #endif+ vec3 pos = vWorldPosition;+ vec3 v = normalize( cameraPosition - pos );+ vec3 n = inverseTransformDirection( normal, viewMatrix );+ vec4 transmitted = getIBLVolumeRefraction(+ n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,+ pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness,+ material.attenuationColor, material.attenuationDistance );+ material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );+ totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );+#endif`,yy=`#ifdef USE_TRANSMISSION+ uniform float transmission;+ uniform float thickness;+ uniform float attenuationDistance;+ uniform vec3 attenuationColor;+ #ifdef USE_TRANSMISSIONMAP+ uniform sampler2D transmissionMap;+ #endif+ #ifdef USE_THICKNESSMAP+ uniform sampler2D thicknessMap;+ #endif+ uniform vec2 transmissionSamplerSize;+ uniform sampler2D transmissionSamplerMap;+ uniform mat4 modelMatrix;+ uniform mat4 projectionMatrix;+ varying vec3 vWorldPosition;+ float w0( float a ) {+ return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );+ }+ float w1( float a ) {+ return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );+ }+ float w2( float a ){+ return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );+ }+ float w3( float a ) {+ return ( 1.0 / 6.0 ) * ( a * a * a );+ }+ float g0( float a ) {+ return w0( a ) + w1( a );+ }+ float g1( float a ) {+ return w2( a ) + w3( a );+ }+ float h0( float a ) {+ return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );+ }+ float h1( float a ) {+ return 1.0 + w3( a ) / ( w2( a ) + w3( a ) );+ }+ vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {+ uv = uv * texelSize.zw + 0.5;+ vec2 iuv = floor( uv );+ vec2 fuv = fract( uv );+ float g0x = g0( fuv.x );+ float g1x = g1( fuv.x );+ float h0x = h0( fuv.x );+ float h1x = h1( fuv.x );+ float h0y = h0( fuv.y );+ float h1y = h1( fuv.y );+ vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;+ vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;+ vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;+ vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;+ return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) ++ g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );+ }+ vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {+ vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );+ vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );+ vec2 fLodSizeInv = 1.0 / fLodSize;+ vec2 cLodSizeInv = 1.0 / cLodSize;+ vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );+ vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );+ return mix( fSample, cSample, fract( lod ) );+ }+ vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {+ vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );+ vec3 modelScale;+ modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );+ modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );+ modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );+ return normalize( refractionVector ) * thickness * modelScale;+ }+ float applyIorToRoughness( const in float roughness, const in float ior ) {+ return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );+ }+ vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {+ float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );+ return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );+ }+ vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {+ if ( isinf( attenuationDistance ) ) {+ return vec3( 1.0 );+ } else {+ vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;+ vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance;+ }+ }+ vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,+ const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,+ const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness,+ const in vec3 attenuationColor, const in float attenuationDistance ) {+ vec4 transmittedLight;+ vec3 transmittance;+ #ifdef USE_DISPERSION+ float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion;+ vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread );+ for ( int i = 0; i < 3; i ++ ) {+ vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix );+ vec3 refractedRayExit = position + transmissionRay;+ vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );+ vec2 refractionCoords = ndcPos.xy / ndcPos.w;+ refractionCoords += 1.0;+ refractionCoords /= 2.0;+ vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );+ transmittedLight[ i ] = transmissionSample[ i ];+ transmittedLight.a += transmissionSample.a;+ transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ];+ }+ transmittedLight.a /= 3.0;+ #else+ vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );+ vec3 refractedRayExit = position + transmissionRay;+ vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );+ vec2 refractionCoords = ndcPos.xy / ndcPos.w;+ refractionCoords += 1.0;+ refractionCoords /= 2.0;+ transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );+ transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );+ #endif+ vec3 attenuatedColor = transmittance * transmittedLight.rgb;+ vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );+ float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;+ return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );+ }+#endif`,vy=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )+ varying vec2 vUv;+#endif+#ifdef USE_MAP+ varying vec2 vMapUv;+#endif+#ifdef USE_ALPHAMAP+ varying vec2 vAlphaMapUv;+#endif+#ifdef USE_LIGHTMAP+ varying vec2 vLightMapUv;+#endif+#ifdef USE_AOMAP+ varying vec2 vAoMapUv;+#endif+#ifdef USE_BUMPMAP+ varying vec2 vBumpMapUv;+#endif+#ifdef USE_NORMALMAP+ varying vec2 vNormalMapUv;+#endif+#ifdef USE_EMISSIVEMAP+ varying vec2 vEmissiveMapUv;+#endif+#ifdef USE_METALNESSMAP+ varying vec2 vMetalnessMapUv;+#endif+#ifdef USE_ROUGHNESSMAP+ varying vec2 vRoughnessMapUv;+#endif+#ifdef USE_ANISOTROPYMAP+ varying vec2 vAnisotropyMapUv;+#endif+#ifdef USE_CLEARCOATMAP+ varying vec2 vClearcoatMapUv;+#endif+#ifdef USE_CLEARCOAT_NORMALMAP+ varying vec2 vClearcoatNormalMapUv;+#endif+#ifdef USE_CLEARCOAT_ROUGHNESSMAP+ varying vec2 vClearcoatRoughnessMapUv;+#endif+#ifdef USE_IRIDESCENCEMAP+ varying vec2 vIridescenceMapUv;+#endif+#ifdef USE_IRIDESCENCE_THICKNESSMAP+ varying vec2 vIridescenceThicknessMapUv;+#endif+#ifdef USE_SHEEN_COLORMAP+ varying vec2 vSheenColorMapUv;+#endif+#ifdef USE_SHEEN_ROUGHNESSMAP+ varying vec2 vSheenRoughnessMapUv;+#endif+#ifdef USE_SPECULARMAP+ varying vec2 vSpecularMapUv;+#endif+#ifdef USE_SPECULAR_COLORMAP+ varying vec2 vSpecularColorMapUv;+#endif+#ifdef USE_SPECULAR_INTENSITYMAP+ varying vec2 vSpecularIntensityMapUv;+#endif+#ifdef USE_TRANSMISSIONMAP+ uniform mat3 transmissionMapTransform;+ varying vec2 vTransmissionMapUv;+#endif+#ifdef USE_THICKNESSMAP+ uniform mat3 thicknessMapTransform;+ varying vec2 vThicknessMapUv;+#endif`,My=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )+ varying vec2 vUv;+#endif+#ifdef USE_MAP+ uniform mat3 mapTransform;+ varying vec2 vMapUv;+#endif+#ifdef USE_ALPHAMAP+ uniform mat3 alphaMapTransform;+ varying vec2 vAlphaMapUv;+#endif+#ifdef USE_LIGHTMAP+ uniform mat3 lightMapTransform;+ varying vec2 vLightMapUv;+#endif+#ifdef USE_AOMAP+ uniform mat3 aoMapTransform;+ varying vec2 vAoMapUv;+#endif+#ifdef USE_BUMPMAP+ uniform mat3 bumpMapTransform;+ varying vec2 vBumpMapUv;+#endif+#ifdef USE_NORMALMAP+ uniform mat3 normalMapTransform;+ varying vec2 vNormalMapUv;+#endif+#ifdef USE_DISPLACEMENTMAP+ uniform mat3 displacementMapTransform;+ varying vec2 vDisplacementMapUv;+#endif+#ifdef USE_EMISSIVEMAP+ uniform mat3 emissiveMapTransform;+ varying vec2 vEmissiveMapUv;+#endif+#ifdef USE_METALNESSMAP+ uniform mat3 metalnessMapTransform;+ varying vec2 vMetalnessMapUv;+#endif+#ifdef USE_ROUGHNESSMAP+ uniform mat3 roughnessMapTransform;+ varying vec2 vRoughnessMapUv;+#endif+#ifdef USE_ANISOTROPYMAP+ uniform mat3 anisotropyMapTransform;+ varying vec2 vAnisotropyMapUv;+#endif+#ifdef USE_CLEARCOATMAP+ uniform mat3 clearcoatMapTransform;+ varying vec2 vClearcoatMapUv;+#endif+#ifdef USE_CLEARCOAT_NORMALMAP+ uniform mat3 clearcoatNormalMapTransform;+ varying vec2 vClearcoatNormalMapUv;+#endif+#ifdef USE_CLEARCOAT_ROUGHNESSMAP+ uniform mat3 clearcoatRoughnessMapTransform;+ varying vec2 vClearcoatRoughnessMapUv;+#endif+#ifdef USE_SHEEN_COLORMAP+ uniform mat3 sheenColorMapTransform;+ varying vec2 vSheenColorMapUv;+#endif+#ifdef USE_SHEEN_ROUGHNESSMAP+ uniform mat3 sheenRoughnessMapTransform;+ varying vec2 vSheenRoughnessMapUv;+#endif+#ifdef USE_IRIDESCENCEMAP+ uniform mat3 iridescenceMapTransform;+ varying vec2 vIridescenceMapUv;+#endif+#ifdef USE_IRIDESCENCE_THICKNESSMAP+ uniform mat3 iridescenceThicknessMapTransform;+ varying vec2 vIridescenceThicknessMapUv;+#endif+#ifdef USE_SPECULARMAP+ uniform mat3 specularMapTransform;+ varying vec2 vSpecularMapUv;+#endif+#ifdef USE_SPECULAR_COLORMAP+ uniform mat3 specularColorMapTransform;+ varying vec2 vSpecularColorMapUv;+#endif+#ifdef USE_SPECULAR_INTENSITYMAP+ uniform mat3 specularIntensityMapTransform;+ varying vec2 vSpecularIntensityMapUv;+#endif+#ifdef USE_TRANSMISSIONMAP+ uniform mat3 transmissionMapTransform;+ varying vec2 vTransmissionMapUv;+#endif+#ifdef USE_THICKNESSMAP+ uniform mat3 thicknessMapTransform;+ varying vec2 vThicknessMapUv;+#endif`,Sy=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )+ vUv = vec3( uv, 1 ).xy;+#endif+#ifdef USE_MAP+ vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;+#endif+#ifdef USE_ALPHAMAP+ vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;+#endif+#ifdef USE_LIGHTMAP+ vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;+#endif+#ifdef USE_AOMAP+ vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;+#endif+#ifdef USE_BUMPMAP+ vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;+#endif+#ifdef USE_NORMALMAP+ vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;+#endif+#ifdef USE_DISPLACEMENTMAP+ vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;+#endif+#ifdef USE_EMISSIVEMAP+ vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;+#endif+#ifdef USE_METALNESSMAP+ vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;+#endif+#ifdef USE_ROUGHNESSMAP+ vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;+#endif+#ifdef USE_ANISOTROPYMAP+ vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;+#endif+#ifdef USE_CLEARCOATMAP+ vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;+#endif+#ifdef USE_CLEARCOAT_NORMALMAP+ vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;+#endif+#ifdef USE_CLEARCOAT_ROUGHNESSMAP+ vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;+#endif+#ifdef USE_IRIDESCENCEMAP+ vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;+#endif+#ifdef USE_IRIDESCENCE_THICKNESSMAP+ vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;+#endif+#ifdef USE_SHEEN_COLORMAP+ vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;+#endif+#ifdef USE_SHEEN_ROUGHNESSMAP+ vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;+#endif+#ifdef USE_SPECULARMAP+ vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;+#endif+#ifdef USE_SPECULAR_COLORMAP+ vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;+#endif+#ifdef USE_SPECULAR_INTENSITYMAP+ vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;+#endif+#ifdef USE_TRANSMISSIONMAP+ vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;+#endif+#ifdef USE_THICKNESSMAP+ vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;+#endif`,by=`#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;+ #endif+ #ifdef USE_INSTANCING+ worldPosition = instanceMatrix * worldPosition;+ #endif+ worldPosition = modelMatrix * worldPosition;+#endif`,Ty=`varying vec2 vUv;+uniform mat3 uvTransform;+void main() {+ vUv = ( uvTransform * vec3( uv, 1 ) ).xy;+ gl_Position = vec4( position.xy, 1.0, 1.0 );+}`,Ey=`uniform sampler2D t2D;+uniform float backgroundIntensity;+varying vec2 vUv;+void main() {+ vec4 texColor = texture2D( t2D, vUv );+ #ifdef DECODE_VIDEO_TEXTURE+ texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );+ #endif+ texColor.rgb *= backgroundIntensity;+ gl_FragColor = texColor;+ #include <tonemapping_fragment>+ #include <colorspace_fragment>+}`,Ay=`varying vec3 vWorldDirection;+#include <common>+void main() {+ vWorldDirection = transformDirection( position, modelMatrix );+ #include <begin_vertex>+ #include <project_vertex>+ gl_Position.z = gl_Position.w;+}`,wy=`#ifdef ENVMAP_TYPE_CUBE+ uniform samplerCube envMap;+#elif defined( ENVMAP_TYPE_CUBE_UV )+ uniform sampler2D envMap;+#endif+uniform float flipEnvMap;+uniform float backgroundBlurriness;+uniform float backgroundIntensity;+uniform mat3 backgroundRotation;+varying vec3 vWorldDirection;+#include <cube_uv_reflection_fragment>+void main() {+ #ifdef ENVMAP_TYPE_CUBE+ vec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );+ #elif defined( ENVMAP_TYPE_CUBE_UV )+ vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness );+ #else+ vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );+ #endif+ texColor.rgb *= backgroundIntensity;+ gl_FragColor = texColor;+ #include <tonemapping_fragment>+ #include <colorspace_fragment>+}`,Ry=`varying vec3 vWorldDirection;+#include <common>+void main() {+ vWorldDirection = transformDirection( position, modelMatrix );+ #include <begin_vertex>+ #include <project_vertex>+ gl_Position.z = gl_Position.w;+}`,Cy=`uniform samplerCube tCube;+uniform float tFlip;+uniform float opacity;+varying vec3 vWorldDirection;+void main() {+ vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );+ gl_FragColor = texColor;+ gl_FragColor.a *= opacity;+ #include <tonemapping_fragment>+ #include <colorspace_fragment>+}`,Iy=`#include <common>+#include <batching_pars_vertex>+#include <uv_pars_vertex>+#include <displacementmap_pars_vertex>+#include <morphtarget_pars_vertex>+#include <skinning_pars_vertex>+#include <logdepthbuf_pars_vertex>+#include <clipping_planes_pars_vertex>+varying vec2 vHighPrecisionZW;+void main() {+ #include <uv_vertex>+ #include <batching_vertex>+ #include <skinbase_vertex>+ #include <morphinstance_vertex>+ #ifdef USE_DISPLACEMENTMAP+ #include <beginnormal_vertex>+ #include <morphnormal_vertex>+ #include <skinnormal_vertex>+ #endif+ #include <begin_vertex>+ #include <morphtarget_vertex>+ #include <skinning_vertex>+ #include <displacementmap_vertex>+ #include <project_vertex>+ #include <logdepthbuf_vertex>+ #include <clipping_planes_vertex>+ vHighPrecisionZW = gl_Position.zw;+}`,Py=`#if DEPTH_PACKING == 3200+ uniform float opacity;+#endif+#include <common>+#include <packing>+#include <uv_pars_fragment>+#include <map_pars_fragment>+#include <alphamap_pars_fragment>+#include <alphatest_pars_fragment>+#include <alphahash_pars_fragment>+#include <logdepthbuf_pars_fragment>+#include <clipping_planes_pars_fragment>+varying vec2 vHighPrecisionZW;+void main() {+ vec4 diffuseColor = vec4( 1.0 );+ #include <clipping_planes_fragment>+ #if DEPTH_PACKING == 3200+ diffuseColor.a = opacity;+ #endif+ #include <map_fragment>+ #include <alphamap_fragment>+ #include <alphatest_fragment>+ #include <alphahash_fragment>+ #include <logdepthbuf_fragment>+ #ifdef USE_REVERSED_DEPTH_BUFFER+ float fragCoordZ = vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ];+ #else+ float fragCoordZ = 0.5 * vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ] + 0.5;+ #endif+ #if DEPTH_PACKING == 3200+ gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );+ #elif DEPTH_PACKING == 3201+ gl_FragColor = packDepthToRGBA( fragCoordZ );+ #elif DEPTH_PACKING == 3202+ gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );+ #elif DEPTH_PACKING == 3203+ gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );+ #endif+}`,Ly=`#define DISTANCE+varying vec3 vWorldPosition;+#include <common>+#include <batching_pars_vertex>+#include <uv_pars_vertex>+#include <displacementmap_pars_vertex>+#include <morphtarget_pars_vertex>+#include <skinning_pars_vertex>+#include <clipping_planes_pars_vertex>+void main() {+ #include <uv_vertex>+ #include <batching_vertex>+ #include <skinbase_vertex>+ #include <morphinstance_vertex>+ #ifdef USE_DISPLACEMENTMAP+ #include <beginnormal_vertex>+ #include <morphnormal_vertex>+ #include <skinnormal_vertex>+ #endif+ #include <begin_vertex>+ #include <morphtarget_vertex>+ #include <skinning_vertex>+ #include <displacementmap_vertex>+ #include <project_vertex>+ #include <worldpos_vertex>+ #include <clipping_planes_vertex>+ vWorldPosition = worldPosition.xyz;+}`,Dy=`#define DISTANCE+uniform vec3 referencePosition;+uniform float nearDistance;+uniform float farDistance;+varying vec3 vWorldPosition;+#include <common>+#include <packing>+#include <uv_pars_fragment>+#include <map_pars_fragment>+#include <alphamap_pars_fragment>+#include <alphatest_pars_fragment>+#include <alphahash_pars_fragment>+#include <clipping_planes_pars_fragment>+void main () {+ vec4 diffuseColor = vec4( 1.0 );+ #include <clipping_planes_fragment>+ #include <map_fragment>+ #include <alphamap_fragment>+ #include <alphatest_fragment>+ #include <alphahash_fragment>+ float dist = length( vWorldPosition - referencePosition );+ dist = ( dist - nearDistance ) / ( farDistance - nearDistance );+ dist = saturate( dist );+ gl_FragColor = packDepthToRGBA( dist );+}`,Ny=`varying vec3 vWorldDirection;+#include <common>+void main() {+ vWorldDirection = transformDirection( position, modelMatrix );+ #include <begin_vertex>+ #include <project_vertex>+}`,Uy=`uniform sampler2D tEquirect;+varying vec3 vWorldDirection;+#include <common>+void main() {+ vec3 direction = normalize( vWorldDirection );+ vec2 sampleUV = equirectUv( direction );+ gl_FragColor = texture2D( tEquirect, sampleUV );+ #include <tonemapping_fragment>+ #include <colorspace_fragment>+}`,Fy=`uniform float scale;+attribute float lineDistance;+varying float vLineDistance;+#include <common>+#include <uv_pars_vertex>+#include <color_pars_vertex>+#include <fog_pars_vertex>+#include <morphtarget_pars_vertex>+#include <logdepthbuf_pars_vertex>+#include <clipping_planes_pars_vertex>+void main() {+ vLineDistance = scale * lineDistance;+ #include <uv_vertex>+ #include <color_vertex>+ #include <morphinstance_vertex>+ #include <morphcolor_vertex>+ #include <begin_vertex>+ #include <morphtarget_vertex>+ #include <project_vertex>+ #include <logdepthbuf_vertex>+ #include <clipping_planes_vertex>+ #include <fog_vertex>+}`,Oy=`uniform vec3 diffuse;+uniform float opacity;+uniform float dashSize;+uniform float totalSize;+varying float vLineDistance;+#include <common>+#include <color_pars_fragment>+#include <uv_pars_fragment>+#include <map_pars_fragment>+#include <fog_pars_fragment>+#include <logdepthbuf_pars_fragment>+#include <clipping_planes_pars_fragment>+void main() {+ vec4 diffuseColor = vec4( diffuse, opacity );+ #include <clipping_planes_fragment>+ if ( mod( vLineDistance, totalSize ) > dashSize ) {+ discard;+ }+ vec3 outgoingLight = vec3( 0.0 );+ #include <logdepthbuf_fragment>+ #include <map_fragment>+ #include <color_fragment>+ outgoingLight = diffuseColor.rgb;+ #include <opaque_fragment>+ #include <tonemapping_fragment>+ #include <colorspace_fragment>+ #include <fog_fragment>+ #include <premultiplied_alpha_fragment>+}`,By=`#include <common>+#include <batching_pars_vertex>+#include <uv_pars_vertex>+#include <envmap_pars_vertex>+#include <color_pars_vertex>+#include <fog_pars_vertex>+#include <morphtarget_pars_vertex>+#include <skinning_pars_vertex>+#include <logdepthbuf_pars_vertex>+#include <clipping_planes_pars_vertex>+void main() {+ #include <uv_vertex>+ #include <color_vertex>+ #include <morphinstance_vertex>+ #include <morphcolor_vertex>+ #include <batching_vertex>+ #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )+ #include <beginnormal_vertex>+ #include <morphnormal_vertex>+ #include <skinbase_vertex>+ #include <skinnormal_vertex>+ #include <defaultnormal_vertex>+ #endif+ #include <begin_vertex>+ #include <morphtarget_vertex>+ #include <skinning_vertex>+ #include <project_vertex>+ #include <logdepthbuf_vertex>+ #include <clipping_planes_vertex>+ #include <worldpos_vertex>+ #include <envmap_vertex>+ #include <fog_vertex>+}`,zy=`uniform vec3 diffuse;+uniform float opacity;+#ifndef FLAT_SHADED+ varying vec3 vNormal;+#endif+#include <common>+#include <dithering_pars_fragment>+#include <color_pars_fragment>+#include <uv_pars_fragment>+#include <map_pars_fragment>+#include <alphamap_pars_fragment>+#include <alphatest_pars_fragment>+#include <alphahash_pars_fragment>+#include <aomap_pars_fragment>+#include <lightmap_pars_fragment>+#include <envmap_common_pars_fragment>+#include <envmap_pars_fragment>+#include <fog_pars_fragment>+#include <specularmap_pars_fragment>+#include <logdepthbuf_pars_fragment>+#include <clipping_planes_pars_fragment>+void main() {+ vec4 diffuseColor = vec4( diffuse, opacity );+ #include <clipping_planes_fragment>+ #include <logdepthbuf_fragment>+ #include <map_fragment>+ #include <color_fragment>+ #include <alphamap_fragment>+ #include <alphatest_fragment>+ #include <alphahash_fragment>+ #include <specularmap_fragment>+ ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );+ #ifdef USE_LIGHTMAP+ vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );+ reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;+ #else+ reflectedLight.indirectDiffuse += vec3( 1.0 );+ #endif+ #include <aomap_fragment>+ reflectedLight.indirectDiffuse *= diffuseColor.rgb;+ vec3 outgoingLight = reflectedLight.indirectDiffuse;+ #include <envmap_fragment>+ #include <opaque_fragment>+ #include <tonemapping_fragment>+ #include <colorspace_fragment>+ #include <fog_fragment>+ #include <premultiplied_alpha_fragment>+ #include <dithering_fragment>+}`,ky=`#define LAMBERT+varying vec3 vViewPosition;+#include <common>+#include <batching_pars_vertex>+#include <uv_pars_vertex>+#include <displacementmap_pars_vertex>+#include <envmap_pars_vertex>+#include <color_pars_vertex>+#include <fog_pars_vertex>+#include <normal_pars_vertex>+#include <morphtarget_pars_vertex>+#include <skinning_pars_vertex>+#include <shadowmap_pars_vertex>+#include <logdepthbuf_pars_vertex>+#include <clipping_planes_pars_vertex>+void main() {+ #include <uv_vertex>+ #include <color_vertex>+ #include <morphinstance_vertex>+ #include <morphcolor_vertex>+ #include <batching_vertex>+ #include <beginnormal_vertex>+ #include <morphnormal_vertex>+ #include <skinbase_vertex>+ #include <skinnormal_vertex>+ #include <defaultnormal_vertex>+ #include <normal_vertex>+ #include <begin_vertex>+ #include <morphtarget_vertex>+ #include <skinning_vertex>+ #include <displacementmap_vertex>+ #include <project_vertex>+ #include <logdepthbuf_vertex>+ #include <clipping_planes_vertex>+ vViewPosition = - mvPosition.xyz;+ #include <worldpos_vertex>+ #include <envmap_vertex>+ #include <shadowmap_vertex>+ #include <fog_vertex>+}`,Vy=`#define LAMBERT+uniform vec3 diffuse;+uniform vec3 emissive;+uniform float opacity;+#include <common>+#include <packing>+#include <dithering_pars_fragment>+#include <color_pars_fragment>+#include <uv_pars_fragment>+#include <map_pars_fragment>+#include <alphamap_pars_fragment>+#include <alphatest_pars_fragment>+#include <alphahash_pars_fragment>+#include <aomap_pars_fragment>+#include <lightmap_pars_fragment>+#include <emissivemap_pars_fragment>+#include <envmap_common_pars_fragment>+#include <envmap_pars_fragment>+#include <fog_pars_fragment>+#include <bsdfs>+#include <lights_pars_begin>+#include <normal_pars_fragment>+#include <lights_lambert_pars_fragment>+#include <shadowmap_pars_fragment>+#include <bumpmap_pars_fragment>+#include <normalmap_pars_fragment>+#include <specularmap_pars_fragment>+#include <logdepthbuf_pars_fragment>+#include <clipping_planes_pars_fragment>+void main() {+ vec4 diffuseColor = vec4( diffuse, opacity );+ #include <clipping_planes_fragment>+ ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );+ vec3 totalEmissiveRadiance = emissive;+ #include <logdepthbuf_fragment>+ #include <map_fragment>+ #include <color_fragment>+ #include <alphamap_fragment>+ #include <alphatest_fragment>+ #include <alphahash_fragment>+ #include <specularmap_fragment>+ #include <normal_fragment_begin>+ #include <normal_fragment_maps>+ #include <emissivemap_fragment>+ #include <lights_lambert_fragment>+ #include <lights_fragment_begin>+ #include <lights_fragment_maps>+ #include <lights_fragment_end>+ #include <aomap_fragment>+ vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;+ #include <envmap_fragment>+ #include <opaque_fragment>+ #include <tonemapping_fragment>+ #include <colorspace_fragment>+ #include <fog_fragment>+ #include <premultiplied_alpha_fragment>+ #include <dithering_fragment>+}`,Hy=`#define MATCAP+varying vec3 vViewPosition;+#include <common>+#include <batching_pars_vertex>+#include <uv_pars_vertex>+#include <color_pars_vertex>+#include <displacementmap_pars_vertex>+#include <fog_pars_vertex>+#include <normal_pars_vertex>+#include <morphtarget_pars_vertex>+#include <skinning_pars_vertex>+#include <logdepthbuf_pars_vertex>+#include <clipping_planes_pars_vertex>+void main() {+ #include <uv_vertex>+ #include <color_vertex>+ #include <morphinstance_vertex>+ #include <morphcolor_vertex>+ #include <batching_vertex>+ #include <beginnormal_vertex>+ #include <morphnormal_vertex>+ #include <skinbase_vertex>+ #include <skinnormal_vertex>+ #include <defaultnormal_vertex>+ #include <normal_vertex>+ #include <begin_vertex>+ #include <morphtarget_vertex>+ #include <skinning_vertex>+ #include <displacementmap_vertex>+ #include <project_vertex>+ #include <logdepthbuf_vertex>+ #include <clipping_planes_vertex>+ #include <fog_vertex>+ vViewPosition = - mvPosition.xyz;+}`,Gy=`#define MATCAP+uniform vec3 diffuse;+uniform float opacity;+uniform sampler2D matcap;+varying vec3 vViewPosition;+#include <common>+#include <dithering_pars_fragment>+#include <color_pars_fragment>+#include <uv_pars_fragment>+#include <map_pars_fragment>+#include <alphamap_pars_fragment>+#include <alphatest_pars_fragment>+#include <alphahash_pars_fragment>+#include <fog_pars_fragment>+#include <normal_pars_fragment>+#include <bumpmap_pars_fragment>+#include <normalmap_pars_fragment>+#include <logdepthbuf_pars_fragment>+#include <clipping_planes_pars_fragment>+void main() {+ vec4 diffuseColor = vec4( diffuse, opacity );+ #include <clipping_planes_fragment>+ #include <logdepthbuf_fragment>+ #include <map_fragment>+ #include <color_fragment>+ #include <alphamap_fragment>+ #include <alphatest_fragment>+ #include <alphahash_fragment>+ #include <normal_fragment_begin>+ #include <normal_fragment_maps>+ vec3 viewDir = normalize( vViewPosition );+ vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );+ vec3 y = cross( viewDir, x );+ vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;+ #ifdef USE_MATCAP+ vec4 matcapColor = texture2D( matcap, uv );+ #else+ vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );+ #endif+ vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;+ #include <opaque_fragment>+ #include <tonemapping_fragment>+ #include <colorspace_fragment>+ #include <fog_fragment>+ #include <premultiplied_alpha_fragment>+ #include <dithering_fragment>+}`,Wy=`#define NORMAL+#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )+ varying vec3 vViewPosition;+#endif+#include <common>+#include <batching_pars_vertex>+#include <uv_pars_vertex>+#include <displacementmap_pars_vertex>+#include <normal_pars_vertex>+#include <morphtarget_pars_vertex>+#include <skinning_pars_vertex>+#include <logdepthbuf_pars_vertex>+#include <clipping_planes_pars_vertex>+void main() {+ #include <uv_vertex>+ #include <batching_vertex>+ #include <beginnormal_vertex>+ #include <morphinstance_vertex>+ #include <morphnormal_vertex>+ #include <skinbase_vertex>+ #include <skinnormal_vertex>+ #include <defaultnormal_vertex>+ #include <normal_vertex>+ #include <begin_vertex>+ #include <morphtarget_vertex>+ #include <skinning_vertex>+ #include <displacementmap_vertex>+ #include <project_vertex>+ #include <logdepthbuf_vertex>+ #include <clipping_planes_vertex>+#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )+ vViewPosition = - mvPosition.xyz;+#endif+}`,Xy=`#define NORMAL+uniform float opacity;+#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )+ varying vec3 vViewPosition;+#endif+#include <packing>+#include <uv_pars_fragment>+#include <normal_pars_fragment>+#include <bumpmap_pars_fragment>+#include <normalmap_pars_fragment>+#include <logdepthbuf_pars_fragment>+#include <clipping_planes_pars_fragment>+void main() {+ vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );+ #include <clipping_planes_fragment>+ #include <logdepthbuf_fragment>+ #include <normal_fragment_begin>+ #include <normal_fragment_maps>+ gl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a );+ #ifdef OPAQUE+ gl_FragColor.a = 1.0;+ #endif+}`,qy=`#define PHONG+varying vec3 vViewPosition;+#include <common>+#include <batching_pars_vertex>+#include <uv_pars_vertex>+#include <displacementmap_pars_vertex>+#include <envmap_pars_vertex>+#include <color_pars_vertex>+#include <fog_pars_vertex>+#include <normal_pars_vertex>+#include <morphtarget_pars_vertex>+#include <skinning_pars_vertex>+#include <shadowmap_pars_vertex>+#include <logdepthbuf_pars_vertex>+#include <clipping_planes_pars_vertex>+void main() {+ #include <uv_vertex>+ #include <color_vertex>+ #include <morphcolor_vertex>+ #include <batching_vertex>+ #include <beginnormal_vertex>+ #include <morphinstance_vertex>+ #include <morphnormal_vertex>+ #include <skinbase_vertex>+ #include <skinnormal_vertex>+ #include <defaultnormal_vertex>+ #include <normal_vertex>+ #include <begin_vertex>+ #include <morphtarget_vertex>+ #include <skinning_vertex>+ #include <displacementmap_vertex>+ #include <project_vertex>+ #include <logdepthbuf_vertex>+ #include <clipping_planes_vertex>+ vViewPosition = - mvPosition.xyz;+ #include <worldpos_vertex>+ #include <envmap_vertex>+ #include <shadowmap_vertex>+ #include <fog_vertex>+}`,Yy=`#define PHONG+uniform vec3 diffuse;+uniform vec3 emissive;+uniform vec3 specular;+uniform float shininess;+uniform float opacity;+#include <common>+#include <packing>+#include <dithering_pars_fragment>+#include <color_pars_fragment>+#include <uv_pars_fragment>+#include <map_pars_fragment>+#include <alphamap_pars_fragment>+#include <alphatest_pars_fragment>+#include <alphahash_pars_fragment>+#include <aomap_pars_fragment>+#include <lightmap_pars_fragment>+#include <emissivemap_pars_fragment>+#include <envmap_common_pars_fragment>+#include <envmap_pars_fragment>+#include <fog_pars_fragment>+#include <bsdfs>+#include <lights_pars_begin>+#include <normal_pars_fragment>+#include <lights_phong_pars_fragment>+#include <shadowmap_pars_fragment>+#include <bumpmap_pars_fragment>+#include <normalmap_pars_fragment>+#include <specularmap_pars_fragment>+#include <logdepthbuf_pars_fragment>+#include <clipping_planes_pars_fragment>+void main() {+ vec4 diffuseColor = vec4( diffuse, opacity );+ #include <clipping_planes_fragment>+ ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );+ vec3 totalEmissiveRadiance = emissive;+ #include <logdepthbuf_fragment>+ #include <map_fragment>+ #include <color_fragment>+ #include <alphamap_fragment>+ #include <alphatest_fragment>+ #include <alphahash_fragment>+ #include <specularmap_fragment>+ #include <normal_fragment_begin>+ #include <normal_fragment_maps>+ #include <emissivemap_fragment>+ #include <lights_phong_fragment>+ #include <lights_fragment_begin>+ #include <lights_fragment_maps>+ #include <lights_fragment_end>+ #include <aomap_fragment>+ vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;+ #include <envmap_fragment>+ #include <opaque_fragment>+ #include <tonemapping_fragment>+ #include <colorspace_fragment>+ #include <fog_fragment>+ #include <premultiplied_alpha_fragment>+ #include <dithering_fragment>+}`,Zy=`#define STANDARD+varying vec3 vViewPosition;+#ifdef USE_TRANSMISSION+ varying vec3 vWorldPosition;+#endif+#include <common>+#include <batching_pars_vertex>+#include <uv_pars_vertex>+#include <displacementmap_pars_vertex>+#include <color_pars_vertex>+#include <fog_pars_vertex>+#include <normal_pars_vertex>+#include <morphtarget_pars_vertex>+#include <skinning_pars_vertex>+#include <shadowmap_pars_vertex>+#include <logdepthbuf_pars_vertex>+#include <clipping_planes_pars_vertex>+void main() {+ #include <uv_vertex>+ #include <color_vertex>+ #include <morphinstance_vertex>+ #include <morphcolor_vertex>+ #include <batching_vertex>+ #include <beginnormal_vertex>+ #include <morphnormal_vertex>+ #include <skinbase_vertex>+ #include <skinnormal_vertex>+ #include <defaultnormal_vertex>+ #include <normal_vertex>+ #include <begin_vertex>+ #include <morphtarget_vertex>+ #include <skinning_vertex>+ #include <displacementmap_vertex>+ #include <project_vertex>+ #include <logdepthbuf_vertex>+ #include <clipping_planes_vertex>+ vViewPosition = - mvPosition.xyz;+ #include <worldpos_vertex>+ #include <shadowmap_vertex>+ #include <fog_vertex>+#ifdef USE_TRANSMISSION+ vWorldPosition = worldPosition.xyz;+#endif+}`,Ky=`#define STANDARD+#ifdef PHYSICAL+ #define IOR+ #define USE_SPECULAR+#endif+uniform vec3 diffuse;+uniform vec3 emissive;+uniform float roughness;+uniform float metalness;+uniform float opacity;+#ifdef IOR+ uniform float ior;+#endif+#ifdef USE_SPECULAR+ uniform float specularIntensity;+ uniform vec3 specularColor;+ #ifdef USE_SPECULAR_COLORMAP+ uniform sampler2D specularColorMap;+ #endif+ #ifdef USE_SPECULAR_INTENSITYMAP+ uniform sampler2D specularIntensityMap;+ #endif+#endif+#ifdef USE_CLEARCOAT+ uniform float clearcoat;+ uniform float clearcoatRoughness;+#endif+#ifdef USE_DISPERSION+ uniform float dispersion;+#endif+#ifdef USE_IRIDESCENCE+ uniform float iridescence;+ uniform float iridescenceIOR;+ uniform float iridescenceThicknessMinimum;+ uniform float iridescenceThicknessMaximum;+#endif+#ifdef USE_SHEEN+ uniform vec3 sheenColor;+ uniform float sheenRoughness;+ #ifdef USE_SHEEN_COLORMAP+ uniform sampler2D sheenColorMap;+ #endif+ #ifdef USE_SHEEN_ROUGHNESSMAP+ uniform sampler2D sheenRoughnessMap;+ #endif+#endif+#ifdef USE_ANISOTROPY+ uniform vec2 anisotropyVector;+ #ifdef USE_ANISOTROPYMAP+ uniform sampler2D anisotropyMap;+ #endif+#endif+varying vec3 vViewPosition;+#include <common>+#include <packing>+#include <dithering_pars_fragment>+#include <color_pars_fragment>+#include <uv_pars_fragment>+#include <map_pars_fragment>+#include <alphamap_pars_fragment>+#include <alphatest_pars_fragment>+#include <alphahash_pars_fragment>+#include <aomap_pars_fragment>+#include <lightmap_pars_fragment>+#include <emissivemap_pars_fragment>+#include <iridescence_fragment>+#include <cube_uv_reflection_fragment>+#include <envmap_common_pars_fragment>+#include <envmap_physical_pars_fragment>+#include <fog_pars_fragment>+#include <lights_pars_begin>+#include <normal_pars_fragment>+#include <lights_physical_pars_fragment>+#include <transmission_pars_fragment>+#include <shadowmap_pars_fragment>+#include <bumpmap_pars_fragment>+#include <normalmap_pars_fragment>+#include <clearcoat_pars_fragment>+#include <iridescence_pars_fragment>+#include <roughnessmap_pars_fragment>+#include <metalnessmap_pars_fragment>+#include <logdepthbuf_pars_fragment>+#include <clipping_planes_pars_fragment>+void main() {+ vec4 diffuseColor = vec4( diffuse, opacity );+ #include <clipping_planes_fragment>+ ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );+ vec3 totalEmissiveRadiance = emissive;+ #include <logdepthbuf_fragment>+ #include <map_fragment>+ #include <color_fragment>+ #include <alphamap_fragment>+ #include <alphatest_fragment>+ #include <alphahash_fragment>+ #include <roughnessmap_fragment>+ #include <metalnessmap_fragment>+ #include <normal_fragment_begin>+ #include <normal_fragment_maps>+ #include <clearcoat_normal_fragment_begin>+ #include <clearcoat_normal_fragment_maps>+ #include <emissivemap_fragment>+ #include <lights_physical_fragment>+ #include <lights_fragment_begin>+ #include <lights_fragment_maps>+ #include <lights_fragment_end>+ #include <aomap_fragment>+ vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;+ vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;+ #include <transmission_fragment>+ vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;+ #ifdef USE_SHEEN+ float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );+ outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect;+ #endif+ #ifdef USE_CLEARCOAT+ float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );+ vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );+ outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;+ #endif+ #include <opaque_fragment>+ #include <tonemapping_fragment>+ #include <colorspace_fragment>+ #include <fog_fragment>+ #include <premultiplied_alpha_fragment>+ #include <dithering_fragment>+}`,Jy=`#define TOON+varying vec3 vViewPosition;+#include <common>+#include <batching_pars_vertex>+#include <uv_pars_vertex>+#include <displacementmap_pars_vertex>+#include <color_pars_vertex>+#include <fog_pars_vertex>+#include <normal_pars_vertex>+#include <morphtarget_pars_vertex>+#include <skinning_pars_vertex>+#include <shadowmap_pars_vertex>+#include <logdepthbuf_pars_vertex>+#include <clipping_planes_pars_vertex>+void main() {+ #include <uv_vertex>+ #include <color_vertex>+ #include <morphinstance_vertex>+ #include <morphcolor_vertex>+ #include <batching_vertex>+ #include <beginnormal_vertex>+ #include <morphnormal_vertex>+ #include <skinbase_vertex>+ #include <skinnormal_vertex>+ #include <defaultnormal_vertex>+ #include <normal_vertex>+ #include <begin_vertex>+ #include <morphtarget_vertex>+ #include <skinning_vertex>+ #include <displacementmap_vertex>+ #include <project_vertex>+ #include <logdepthbuf_vertex>+ #include <clipping_planes_vertex>+ vViewPosition = - mvPosition.xyz;+ #include <worldpos_vertex>+ #include <shadowmap_vertex>+ #include <fog_vertex>+}`,$y=`#define TOON+uniform vec3 diffuse;+uniform vec3 emissive;+uniform float opacity;+#include <common>+#include <packing>+#include <dithering_pars_fragment>+#include <color_pars_fragment>+#include <uv_pars_fragment>+#include <map_pars_fragment>+#include <alphamap_pars_fragment>+#include <alphatest_pars_fragment>+#include <alphahash_pars_fragment>+#include <aomap_pars_fragment>+#include <lightmap_pars_fragment>+#include <emissivemap_pars_fragment>+#include <gradientmap_pars_fragment>+#include <fog_pars_fragment>+#include <bsdfs>+#include <lights_pars_begin>+#include <normal_pars_fragment>+#include <lights_toon_pars_fragment>+#include <shadowmap_pars_fragment>+#include <bumpmap_pars_fragment>+#include <normalmap_pars_fragment>+#include <logdepthbuf_pars_fragment>+#include <clipping_planes_pars_fragment>+void main() {+ vec4 diffuseColor = vec4( diffuse, opacity );+ #include <clipping_planes_fragment>+ ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );+ vec3 totalEmissiveRadiance = emissive;+ #include <logdepthbuf_fragment>+ #include <map_fragment>+ #include <color_fragment>+ #include <alphamap_fragment>+ #include <alphatest_fragment>+ #include <alphahash_fragment>+ #include <normal_fragment_begin>+ #include <normal_fragment_maps>+ #include <emissivemap_fragment>+ #include <lights_toon_fragment>+ #include <lights_fragment_begin>+ #include <lights_fragment_maps>+ #include <lights_fragment_end>+ #include <aomap_fragment>+ vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;+ #include <opaque_fragment>+ #include <tonemapping_fragment>+ #include <colorspace_fragment>+ #include <fog_fragment>+ #include <premultiplied_alpha_fragment>+ #include <dithering_fragment>+}`,jy=`uniform float size;+uniform float scale;+#include <common>+#include <color_pars_vertex>+#include <fog_pars_vertex>+#include <morphtarget_pars_vertex>+#include <logdepthbuf_pars_vertex>+#include <clipping_planes_pars_vertex>+#ifdef USE_POINTS_UV+ varying vec2 vUv;+ uniform mat3 uvTransform;+#endif+void main() {+ #ifdef USE_POINTS_UV+ vUv = ( uvTransform * vec3( uv, 1 ) ).xy;+ #endif+ #include <color_vertex>+ #include <morphinstance_vertex>+ #include <morphcolor_vertex>+ #include <begin_vertex>+ #include <morphtarget_vertex>+ #include <project_vertex>+ gl_PointSize = size;+ #ifdef USE_SIZEATTENUATION+ bool isPerspective = isPerspectiveMatrix( projectionMatrix );+ if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );+ #endif+ #include <logdepthbuf_vertex>+ #include <clipping_planes_vertex>+ #include <worldpos_vertex>+ #include <fog_vertex>+}`,Qy=`uniform vec3 diffuse;+uniform float opacity;+#include <common>+#include <color_pars_fragment>+#include <map_particle_pars_fragment>+#include <alphatest_pars_fragment>+#include <alphahash_pars_fragment>+#include <fog_pars_fragment>+#include <logdepthbuf_pars_fragment>+#include <clipping_planes_pars_fragment>+void main() {+ vec4 diffuseColor = vec4( diffuse, opacity );+ #include <clipping_planes_fragment>+ vec3 outgoingLight = vec3( 0.0 );+ #include <logdepthbuf_fragment>+ #include <map_particle_fragment>+ #include <color_fragment>+ #include <alphatest_fragment>+ #include <alphahash_fragment>+ outgoingLight = diffuseColor.rgb;+ #include <opaque_fragment>+ #include <tonemapping_fragment>+ #include <colorspace_fragment>+ #include <fog_fragment>+ #include <premultiplied_alpha_fragment>+}`,ev=`#include <common>+#include <batching_pars_vertex>+#include <fog_pars_vertex>+#include <morphtarget_pars_vertex>+#include <skinning_pars_vertex>+#include <logdepthbuf_pars_vertex>+#include <shadowmap_pars_vertex>+void main() {+ #include <batching_vertex>+ #include <beginnormal_vertex>+ #include <morphinstance_vertex>+ #include <morphnormal_vertex>+ #include <skinbase_vertex>+ #include <skinnormal_vertex>+ #include <defaultnormal_vertex>+ #include <begin_vertex>+ #include <morphtarget_vertex>+ #include <skinning_vertex>+ #include <project_vertex>+ #include <logdepthbuf_vertex>+ #include <worldpos_vertex>+ #include <shadowmap_vertex>+ #include <fog_vertex>+}`,tv=`uniform vec3 color;+uniform float opacity;+#include <common>+#include <packing>+#include <fog_pars_fragment>+#include <bsdfs>+#include <lights_pars_begin>+#include <logdepthbuf_pars_fragment>+#include <shadowmap_pars_fragment>+#include <shadowmask_pars_fragment>+void main() {+ #include <logdepthbuf_fragment>+ gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );+ #include <tonemapping_fragment>+ #include <colorspace_fragment>+ #include <fog_fragment>+}`,nv=`uniform float rotation;+uniform vec2 center;+#include <common>+#include <uv_pars_vertex>+#include <fog_pars_vertex>+#include <logdepthbuf_pars_vertex>+#include <clipping_planes_pars_vertex>+void main() {+ #include <uv_vertex>+ vec4 mvPosition = modelViewMatrix[ 3 ];+ vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) );+ #ifndef USE_SIZEATTENUATION+ bool isPerspective = isPerspectiveMatrix( projectionMatrix );+ if ( isPerspective ) scale *= - mvPosition.z;+ #endif+ vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;+ vec2 rotatedPosition;+ rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;+ rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;+ mvPosition.xy += rotatedPosition;+ gl_Position = projectionMatrix * mvPosition;+ #include <logdepthbuf_vertex>+ #include <clipping_planes_vertex>+ #include <fog_vertex>+}`,iv=`uniform vec3 diffuse;+uniform float opacity;+#include <common>+#include <uv_pars_fragment>+#include <map_pars_fragment>+#include <alphamap_pars_fragment>+#include <alphatest_pars_fragment>+#include <alphahash_pars_fragment>+#include <fog_pars_fragment>+#include <logdepthbuf_pars_fragment>+#include <clipping_planes_pars_fragment>+void main() {+ vec4 diffuseColor = vec4( diffuse, opacity );+ #include <clipping_planes_fragment>+ vec3 outgoingLight = vec3( 0.0 );+ #include <logdepthbuf_fragment>+ #include <map_fragment>+ #include <alphamap_fragment>+ #include <alphatest_fragment>+ #include <alphahash_fragment>+ outgoingLight = diffuseColor.rgb;+ #include <opaque_fragment>+ #include <tonemapping_fragment>+ #include <colorspace_fragment>+ #include <fog_fragment>+}`,Ye={alphahash_fragment:Ex,alphahash_pars_fragment:Ax,alphamap_fragment:wx,alphamap_pars_fragment:Rx,alphatest_fragment:Cx,alphatest_pars_fragment:Ix,aomap_fragment:Px,aomap_pars_fragment:Lx,batching_pars_vertex:Dx,batching_vertex:Nx,begin_vertex:Ux,beginnormal_vertex:Fx,bsdfs:Ox,iridescence_fragment:Bx,bumpmap_pars_fragment:zx,clipping_planes_fragment:kx,clipping_planes_pars_fragment:Vx,clipping_planes_pars_vertex:Hx,clipping_planes_vertex:Gx,color_fragment:Wx,color_pars_fragment:Xx,color_pars_vertex:qx,color_vertex:Yx,common:Zx,cube_uv_reflection_fragment:Kx,defaultnormal_vertex:Jx,displacementmap_pars_vertex:$x,displacementmap_vertex:jx,emissivemap_fragment:Qx,emissivemap_pars_fragment:e0,colorspace_fragment:t0,colorspace_pars_fragment:n0,envmap_fragment:i0,envmap_common_pars_fragment:s0,envmap_pars_fragment:r0,envmap_pars_vertex:o0,envmap_physical_pars_fragment:_0,envmap_vertex:a0,fog_vertex:c0,fog_pars_vertex:l0,fog_fragment:h0,fog_pars_fragment:u0,gradientmap_pars_fragment:d0,lightmap_pars_fragment:f0,lights_lambert_fragment:p0,lights_lambert_pars_fragment:m0,lights_pars_begin:g0,lights_toon_fragment:x0,lights_toon_pars_fragment:y0,lights_phong_fragment:v0,lights_phong_pars_fragment:M0,lights_physical_fragment:S0,lights_physical_pars_fragment:b0,lights_fragment_begin:T0,lights_fragment_maps:E0,lights_fragment_end:A0,logdepthbuf_fragment:w0,logdepthbuf_pars_fragment:R0,logdepthbuf_pars_vertex:C0,logdepthbuf_vertex:I0,map_fragment:P0,map_pars_fragment:L0,map_particle_fragment:D0,map_particle_pars_fragment:N0,metalnessmap_fragment:U0,metalnessmap_pars_fragment:F0,morphinstance_vertex:O0,morphcolor_vertex:B0,morphnormal_vertex:z0,morphtarget_pars_vertex:k0,morphtarget_vertex:V0,normal_fragment_begin:H0,normal_fragment_maps:G0,normal_pars_fragment:W0,normal_pars_vertex:X0,normal_vertex:q0,normalmap_pars_fragment:Y0,clearcoat_normal_fragment_begin:Z0,clearcoat_normal_fragment_maps:K0,clearcoat_pars_fragment:J0,iridescence_pars_fragment:$0,opaque_fragment:j0,packing:Q0,premultiplied_alpha_fragment:ey,project_vertex:ty,dithering_fragment:ny,dithering_pars_fragment:iy,roughnessmap_fragment:sy,roughnessmap_pars_fragment:ry,shadowmap_pars_fragment:oy,shadowmap_pars_vertex:ay,shadowmap_vertex:cy,shadowmask_pars_fragment:ly,skinbase_vertex:hy,skinning_pars_vertex:uy,skinning_vertex:dy,skinnormal_vertex:fy,specularmap_fragment:py,specularmap_pars_fragment:my,tonemapping_fragment:gy,tonemapping_pars_fragment:_y,transmission_fragment:xy,transmission_pars_fragment:yy,uv_pars_fragment:vy,uv_pars_vertex:My,uv_vertex:Sy,worldpos_vertex:by,background_vert:Ty,background_frag:Ey,backgroundCube_vert:Ay,backgroundCube_frag:wy,cube_vert:Ry,cube_frag:Cy,depth_vert:Iy,depth_frag:Py,distanceRGBA_vert:Ly,distanceRGBA_frag:Dy,equirect_vert:Ny,equirect_frag:Uy,linedashed_vert:Fy,linedashed_frag:Oy,meshbasic_vert:By,meshbasic_frag:zy,meshlambert_vert:ky,meshlambert_frag:Vy,meshmatcap_vert:Hy,meshmatcap_frag:Gy,meshnormal_vert:Wy,meshnormal_frag:Xy,meshphong_vert:qy,meshphong_frag:Yy,meshphysical_vert:Zy,meshphysical_frag:Ky,meshtoon_vert:Jy,meshtoon_frag:$y,points_vert:jy,points_frag:Qy,shadow_vert:ev,shadow_frag:tv,sprite_vert:nv,sprite_frag:iv},pe={common:{diffuse:{value:new ue(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new Ve},alphaMap:{value:null},alphaMapTransform:{value:new Ve},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new Ve}},envmap:{envMap:{value:null},envMapRotation:{value:new Ve},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new Ve}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new Ve}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new Ve},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new Ve},normalScale:{value:new Y(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new Ve},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new Ve}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new Ve}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new Ve}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new ue(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new ue(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new Ve},alphaTest:{value:0},uvTransform:{value:new Ve}},sprite:{diffuse:{value:new ue(16777215)},opacity:{value:1},center:{value:new Y(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new Ve},alphaMap:{value:null},alphaMapTransform:{value:new Ve},alphaTest:{value:0}}},Wn={basic:{uniforms:Xt([pe.common,pe.specularmap,pe.envmap,pe.aomap,pe.lightmap,pe.fog]),vertexShader:Ye.meshbasic_vert,fragmentShader:Ye.meshbasic_frag},lambert:{uniforms:Xt([pe.common,pe.specularmap,pe.envmap,pe.aomap,pe.lightmap,pe.emissivemap,pe.bumpmap,pe.normalmap,pe.displacementmap,pe.fog,pe.lights,{emissive:{value:new ue(0)}}]),vertexShader:Ye.meshlambert_vert,fragmentShader:Ye.meshlambert_frag},phong:{uniforms:Xt([pe.common,pe.specularmap,pe.envmap,pe.aomap,pe.lightmap,pe.emissivemap,pe.bumpmap,pe.normalmap,pe.displacementmap,pe.fog,pe.lights,{emissive:{value:new ue(0)},specular:{value:new ue(1118481)},shininess:{value:30}}]),vertexShader:Ye.meshphong_vert,fragmentShader:Ye.meshphong_frag},standard:{uniforms:Xt([pe.common,pe.envmap,pe.aomap,pe.lightmap,pe.emissivemap,pe.bumpmap,pe.normalmap,pe.displacementmap,pe.roughnessmap,pe.metalnessmap,pe.fog,pe.lights,{emissive:{value:new ue(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Ye.meshphysical_vert,fragmentShader:Ye.meshphysical_frag},toon:{uniforms:Xt([pe.common,pe.aomap,pe.lightmap,pe.emissivemap,pe.bumpmap,pe.normalmap,pe.displacementmap,pe.gradientmap,pe.fog,pe.lights,{emissive:{value:new ue(0)}}]),vertexShader:Ye.meshtoon_vert,fragmentShader:Ye.meshtoon_frag},matcap:{uniforms:Xt([pe.common,pe.bumpmap,pe.normalmap,pe.displacementmap,pe.fog,{matcap:{value:null}}]),vertexShader:Ye.meshmatcap_vert,fragmentShader:Ye.meshmatcap_frag},points:{uniforms:Xt([pe.points,pe.fog]),vertexShader:Ye.points_vert,fragmentShader:Ye.points_frag},dashed:{uniforms:Xt([pe.common,pe.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Ye.linedashed_vert,fragmentShader:Ye.linedashed_frag},depth:{uniforms:Xt([pe.common,pe.displacementmap]),vertexShader:Ye.depth_vert,fragmentShader:Ye.depth_frag},normal:{uniforms:Xt([pe.common,pe.bumpmap,pe.normalmap,pe.displacementmap,{opacity:{value:1}}]),vertexShader:Ye.meshnormal_vert,fragmentShader:Ye.meshnormal_frag},sprite:{uniforms:Xt([pe.sprite,pe.fog]),vertexShader:Ye.sprite_vert,fragmentShader:Ye.sprite_frag},background:{uniforms:{uvTransform:{value:new Ve},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:Ye.background_vert,fragmentShader:Ye.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new Ve}},vertexShader:Ye.backgroundCube_vert,fragmentShader:Ye.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Ye.cube_vert,fragmentShader:Ye.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Ye.equirect_vert,fragmentShader:Ye.equirect_frag},distanceRGBA:{uniforms:Xt([pe.common,pe.displacementmap,{referencePosition:{value:new w},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Ye.distanceRGBA_vert,fragmentShader:Ye.distanceRGBA_frag},shadow:{uniforms:Xt([pe.lights,pe.fog,{color:{value:new ue(0)},opacity:{value:1}}]),vertexShader:Ye.shadow_vert,fragmentShader:Ye.shadow_frag}};Wn.physical={uniforms:Xt([Wn.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new Ve},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new Ve},clearcoatNormalScale:{value:new Y(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new Ve},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new Ve},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new Ve},sheen:{value:0},sheenColor:{value:new ue(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new Ve},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new Ve},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new Ve},transmissionSamplerSize:{value:new Y},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new Ve},attenuationDistance:{value:0},attenuationColor:{value:new ue(0)},specularColor:{value:new ue(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new Ve},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new Ve},anisotropyVector:{value:new Y},anisotropyMap:{value:null},anisotropyMapTransform:{value:new Ve}}]),vertexShader:Ye.meshphysical_vert,fragmentShader:Ye.meshphysical_frag};var Nh={r:0,b:0,g:0},zs=new rn,sv=new De;function rv(r,e,t,n,i,s,o){let a=new ue(0),c=s===!0?0:1,l,h,u=null,d=0,f=null;function m(y){let x=y.isScene===!0?y.background:null;return x&&x.isTexture&&(x=(y.backgroundBlurriness>0?t:e).get(x)),x}function _(y){let x=!1,A=m(y);A===null?p(a,c):A&&A.isColor&&(p(A,1),x=!0);let E=r.xr.getEnvironmentBlendMode();E==="additive"?n.buffers.color.setClear(0,0,0,1,o):E==="alpha-blend"&&n.buffers.color.setClear(0,0,0,0,o),(r.autoClear||x)&&(n.buffers.depth.setTest(!0),n.buffers.depth.setMask(!0),n.buffers.color.setMask(!0),r.clear(r.autoClearColor,r.autoClearDepth,r.autoClearStencil))}function g(y,x){let A=m(x);A&&(A.isCubeTexture||A.mapping===Ls)?(h===void 0&&(h=new pt(new Vi(1,1,1),new on({name:"BackgroundCubeMaterial",uniforms:Bs(Wn.backgroundCube.uniforms),vertexShader:Wn.backgroundCube.vertexShader,fragmentShader:Wn.backgroundCube.fragmentShader,side:Wt,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),h.geometry.deleteAttribute("normal"),h.geometry.deleteAttribute("uv"),h.onBeforeRender=function(E,C,I){this.matrixWorld.copyPosition(I.matrixWorld)},Object.defineProperty(h.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),i.update(h)),zs.copy(x.backgroundRotation),zs.x*=-1,zs.y*=-1,zs.z*=-1,A.isCubeTexture&&A.isRenderTargetTexture===!1&&(zs.y*=-1,zs.z*=-1),h.material.uniforms.envMap.value=A,h.material.uniforms.flipEnvMap.value=A.isCubeTexture&&A.isRenderTargetTexture===!1?-1:1,h.material.uniforms.backgroundBlurriness.value=x.backgroundBlurriness,h.material.uniforms.backgroundIntensity.value=x.backgroundIntensity,h.material.uniforms.backgroundRotation.value.setFromMatrix4(sv.makeRotationFromEuler(zs)),h.material.toneMapped=Ze.getTransfer(A.colorSpace)!==ot,(u!==A||d!==A.version||f!==r.toneMapping)&&(h.material.needsUpdate=!0,u=A,d=A.version,f=r.toneMapping),h.layers.enableAll(),y.unshift(h,h.geometry,h.material,0,0,null)):A&&A.isTexture&&(l===void 0&&(l=new pt(new ws(2,2),new on({name:"BackgroundMaterial",uniforms:Bs(Wn.background.uniforms),vertexShader:Wn.background.vertexShader,fragmentShader:Wn.background.fragmentShader,side:An,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute("normal"),Object.defineProperty(l.material,"map",{get:function(){return this.uniforms.t2D.value}}),i.update(l)),l.material.uniforms.t2D.value=A,l.material.uniforms.backgroundIntensity.value=x.backgroundIntensity,l.material.toneMapped=Ze.getTransfer(A.colorSpace)!==ot,A.matrixAutoUpdate===!0&&A.updateMatrix(),l.material.uniforms.uvTransform.value.copy(A.matrix),(u!==A||d!==A.version||f!==r.toneMapping)&&(l.material.needsUpdate=!0,u=A,d=A.version,f=r.toneMapping),l.layers.enableAll(),y.unshift(l,l.geometry,l.material,0,0,null))}function p(y,x){y.getRGB(Nh,Nd(r)),n.buffers.color.setClear(Nh.r,Nh.g,Nh.b,x,o)}function v(){h!==void 0&&(h.geometry.dispose(),h.material.dispose(),h=void 0),l!==void 0&&(l.geometry.dispose(),l.material.dispose(),l=void 0)}return{getClearColor:function(){return a},setClearColor:function(y,x=1){a.set(y),c=x,p(a,c)},getClearAlpha:function(){return c},setClearAlpha:function(y){c=y,p(a,c)},render:_,addToRenderList:g,dispose:v}}function ov(r,e){let t=r.getParameter(r.MAX_VERTEX_ATTRIBS),n={},i=d(null),s=i,o=!1;function a(S,L,F,z,G){let q=!1,W=u(z,F,L);s!==W&&(s=W,l(s.object)),q=f(S,z,F,G),q&&m(S,z,F,G),G!==null&&e.update(G,r.ELEMENT_ARRAY_BUFFER),(q||o)&&(o=!1,x(S,L,F,z),G!==null&&r.bindBuffer(r.ELEMENT_ARRAY_BUFFER,e.get(G).buffer))}function c(){return r.createVertexArray()}function l(S){return r.bindVertexArray(S)}function h(S){return r.deleteVertexArray(S)}function u(S,L,F){let z=F.wireframe===!0,G=n[S.id];G===void 0&&(G={},n[S.id]=G);let q=G[L.id];q===void 0&&(q={},G[L.id]=q);let W=q[z];return W===void 0&&(W=d(c()),q[z]=W),W}function d(S){let L=[],F=[],z=[];for(let G=0;G<t;G++)L[G]=0,F[G]=0,z[G]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:L,enabledAttributes:F,attributeDivisors:z,object:S,attributes:{},index:null}}function f(S,L,F,z){let G=s.attributes,q=L.attributes,W=0,ne=F.getAttributes();for(let H in ne)if(ne[H].location>=0){let xe=G[H],Se=q[H];if(Se===void 0&&(H==="instanceMatrix"&&S.instanceMatrix&&(Se=S.instanceMatrix),H==="instanceColor"&&S.instanceColor&&(Se=S.instanceColor)),xe===void 0||xe.attribute!==Se||Se&&xe.data!==Se.data)return!0;W++}return s.attributesNum!==W||s.index!==z}function m(S,L,F,z){let G={},q=L.attributes,W=0,ne=F.getAttributes();for(let H in ne)if(ne[H].location>=0){let xe=q[H];xe===void 0&&(H==="instanceMatrix"&&S.instanceMatrix&&(xe=S.instanceMatrix),H==="instanceColor"&&S.instanceColor&&(xe=S.instanceColor));let Se={};Se.attribute=xe,xe&&xe.data&&(Se.data=xe.data),G[H]=Se,W++}s.attributes=G,s.attributesNum=W,s.index=z}function _(){let S=s.newAttributes;for(let L=0,F=S.length;L<F;L++)S[L]=0}function g(S){p(S,0)}function p(S,L){let F=s.newAttributes,z=s.enabledAttributes,G=s.attributeDivisors;F[S]=1,z[S]===0&&(r.enableVertexAttribArray(S),z[S]=1),G[S]!==L&&(r.vertexAttribDivisor(S,L),G[S]=L)}function v(){let S=s.newAttributes,L=s.enabledAttributes;for(let F=0,z=L.length;F<z;F++)L[F]!==S[F]&&(r.disableVertexAttribArray(F),L[F]=0)}function y(S,L,F,z,G,q,W){W===!0?r.vertexAttribIPointer(S,L,F,G,q):r.vertexAttribPointer(S,L,F,z,G,q)}function x(S,L,F,z){_();let G=z.attributes,q=F.getAttributes(),W=L.defaultAttributeValues;for(let ne in q){let H=q[ne];if(H.location>=0){let de=G[ne];if(de===void 0&&(ne==="instanceMatrix"&&S.instanceMatrix&&(de=S.instanceMatrix),ne==="instanceColor"&&S.instanceColor&&(de=S.instanceColor)),de!==void 0){let xe=de.normalized,Se=de.itemSize,We=e.get(de);if(We===void 0)continue;let et=We.buffer,at=We.type,nt=We.bytesPerElement,Z=at===r.INT||at===r.UNSIGNED_INT||de.gpuType===za;if(de.isInterleavedBufferAttribute){let te=de.data,Me=te.stride,Pe=de.offset;if(te.isInstancedInterleavedBuffer){for(let Ee=0;Ee<H.locationSize;Ee++)p(H.location+Ee,te.meshPerAttribute);S.isInstancedMesh!==!0&&z._maxInstanceCount===void 0&&(z._maxInstanceCount=te.meshPerAttribute*te.count)}else for(let Ee=0;Ee<H.locationSize;Ee++)g(H.location+Ee);r.bindBuffer(r.ARRAY_BUFFER,et);for(let Ee=0;Ee<H.locationSize;Ee++)y(H.location+Ee,Se/H.locationSize,at,xe,Me*nt,(Pe+Se/H.locationSize*Ee)*nt,Z)}else{if(de.isInstancedBufferAttribute){for(let te=0;te<H.locationSize;te++)p(H.location+te,de.meshPerAttribute);S.isInstancedMesh!==!0&&z._maxInstanceCount===void 0&&(z._maxInstanceCount=de.meshPerAttribute*de.count)}else for(let te=0;te<H.locationSize;te++)g(H.location+te);r.bindBuffer(r.ARRAY_BUFFER,et);for(let te=0;te<H.locationSize;te++)y(H.location+te,Se/H.locationSize,at,xe,Se*nt,Se/H.locationSize*te*nt,Z)}}else if(W!==void 0){let xe=W[ne];if(xe!==void 0)switch(xe.length){case 2:r.vertexAttrib2fv(H.location,xe);break;case 3:r.vertexAttrib3fv(H.location,xe);break;case 4:r.vertexAttrib4fv(H.location,xe);break;default:r.vertexAttrib1fv(H.location,xe)}}}}v()}function A(){I();for(let S in n){let L=n[S];for(let F in L){let z=L[F];for(let G in z)h(z[G].object),delete z[G];delete L[F]}delete n[S]}}function E(S){if(n[S.id]===void 0)return;let L=n[S.id];for(let F in L){let z=L[F];for(let G in z)h(z[G].object),delete z[G];delete L[F]}delete n[S.id]}function C(S){for(let L in n){let F=n[L];if(F[S.id]===void 0)continue;let z=F[S.id];for(let G in z)h(z[G].object),delete z[G];delete F[S.id]}}function I(){b(),o=!0,s!==i&&(s=i,l(s.object))}function b(){i.geometry=null,i.program=null,i.wireframe=!1}return{setup:a,reset:I,resetDefaultState:b,dispose:A,releaseStatesOfGeometry:E,releaseStatesOfProgram:C,initAttributes:_,enableAttribute:g,disableUnusedAttributes:v}}function av(r,e,t){let n;function i(l){n=l}function s(l,h){r.drawArrays(n,l,h),t.update(h,n,1)}function o(l,h,u){u!==0&&(r.drawArraysInstanced(n,l,h,u),t.update(h,n,u))}function a(l,h,u){if(u===0)return;e.get("WEBGL_multi_draw").multiDrawArraysWEBGL(n,l,0,h,0,u);let f=0;for(let m=0;m<u;m++)f+=h[m];t.update(f,n,1)}function c(l,h,u,d){if(u===0)return;let f=e.get("WEBGL_multi_draw");if(f===null)for(let m=0;m<l.length;m++)o(l[m],h[m],d[m]);else{f.multiDrawArraysInstancedWEBGL(n,l,0,h,0,d,0,u);let m=0;for(let _=0;_<u;_++)m+=h[_]*d[_];t.update(m,n,1)}}this.setMode=i,this.render=s,this.renderInstances=o,this.renderMultiDraw=a,this.renderMultiDrawInstances=c}function cv(r,e,t,n){let i;function s(){if(i!==void 0)return i;if(e.has("EXT_texture_filter_anisotropic")===!0){let C=e.get("EXT_texture_filter_anisotropic");i=r.getParameter(C.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else i=0;return i}function o(C){return!(C!==Ht&&n.convert(C)!==r.getParameter(r.IMPLEMENTATION_COLOR_READ_FORMAT))}function a(C){let I=C===Ns&&(e.has("EXT_color_buffer_half_float")||e.has("EXT_color_buffer_float"));return!(C!==Cn&&n.convert(C)!==r.getParameter(r.IMPLEMENTATION_COLOR_READ_TYPE)&&C!==Jt&&!I)}function c(C){if(C==="highp"){if(r.getShaderPrecisionFormat(r.VERTEX_SHADER,r.HIGH_FLOAT).precision>0&&r.getShaderPrecisionFormat(r.FRAGMENT_SHADER,r.HIGH_FLOAT).precision>0)return"highp";C="mediump"}return C==="mediump"&&r.getShaderPrecisionFormat(r.VERTEX_SHADER,r.MEDIUM_FLOAT).precision>0&&r.getShaderPrecisionFormat(r.FRAGMENT_SHADER,r.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let l=t.precision!==void 0?t.precision:"highp",h=c(l);h!==l&&(console.warn("THREE.WebGLRenderer:",l,"not supported, using",h,"instead."),l=h);let u=t.logarithmicDepthBuffer===!0,d=t.reversedDepthBuffer===!0&&e.has("EXT_clip_control"),f=r.getParameter(r.MAX_TEXTURE_IMAGE_UNITS),m=r.getParameter(r.MAX_VERTEX_TEXTURE_IMAGE_UNITS),_=r.getParameter(r.MAX_TEXTURE_SIZE),g=r.getParameter(r.MAX_CUBE_MAP_TEXTURE_SIZE),p=r.getParameter(r.MAX_VERTEX_ATTRIBS),v=r.getParameter(r.MAX_VERTEX_UNIFORM_VECTORS),y=r.getParameter(r.MAX_VARYING_VECTORS),x=r.getParameter(r.MAX_FRAGMENT_UNIFORM_VECTORS),A=m>0,E=r.getParameter(r.MAX_SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:s,getMaxPrecision:c,textureFormatReadable:o,textureTypeReadable:a,precision:l,logarithmicDepthBuffer:u,reversedDepthBuffer:d,maxTextures:f,maxVertexTextures:m,maxTextureSize:_,maxCubemapSize:g,maxAttributes:p,maxVertexUniforms:v,maxVaryings:y,maxFragmentUniforms:x,vertexTextures:A,maxSamples:E}}function lv(r){let e=this,t=null,n=0,i=!1,s=!1,o=new pn,a=new Ve,c={value:null,needsUpdate:!1};this.uniform=c,this.numPlanes=0,this.numIntersection=0,this.init=function(u,d){let f=u.length!==0||d||n!==0||i;return i=d,n=u.length,f},this.beginShadows=function(){s=!0,h(null)},this.endShadows=function(){s=!1},this.setGlobalState=function(u,d){t=h(u,d,0)},this.setState=function(u,d,f){let m=u.clippingPlanes,_=u.clipIntersection,g=u.clipShadows,p=r.get(u);if(!i||m===null||m.length===0||s&&!g)s?h(null):l();else{let v=s?0:n,y=v*4,x=p.clippingState||null;c.value=x,x=h(m,d,y,f);for(let A=0;A!==y;++A)x[A]=t[A];p.clippingState=x,this.numIntersection=_?this.numPlanes:0,this.numPlanes+=v}};function l(){c.value!==t&&(c.value=t,c.needsUpdate=n>0),e.numPlanes=n,e.numIntersection=0}function h(u,d,f,m){let _=u!==null?u.length:0,g=null;if(_!==0){if(g=c.value,m!==!0||g===null){let p=f+_*4,v=d.matrixWorldInverse;a.getNormalMatrix(v),(g===null||g.length<p)&&(g=new Float32Array(p));for(let y=0,x=f;y!==_;++y,x+=4)o.copy(u[y]).applyMatrix4(v,a),o.normal.toArray(g,x),g[x+3]=o.constant}c.value=g,c.needsUpdate=!0}return e.numPlanes=_,e.numIntersection=0,g}}function hv(r){let e=new WeakMap;function t(o,a){return a===Wr?o.mapping=ii:a===Xr&&(o.mapping=bi),o}function n(o){if(o&&o.isTexture){let a=o.mapping;if(a===Wr||a===Xr)if(e.has(o)){let c=e.get(o).texture;return t(c,o.mapping)}else{let c=o.image;if(c&&c.height>0){let l=new Co(c.height);return l.fromEquirectangularTexture(r,o),e.set(o,l),o.addEventListener("dispose",i),t(l.texture,o.mapping)}else return null}}return o}function i(o){let a=o.target;a.removeEventListener("dispose",i);let c=e.get(a);c!==void 0&&(e.delete(a),c.dispose())}function s(){e=new WeakMap}return{get:n,dispose:s}}var to=4,Vm=[.125,.215,.35,.446,.526,.582],Hs=20,Vd=new vi,Hm=new ue,Hd=null,Gd=0,Wd=0,Xd=!1,Vs=(1+Math.sqrt(5))/2,eo=1/Vs,Gm=[new w(-Vs,eo,0),new w(Vs,eo,0),new w(-eo,0,Vs),new w(eo,0,Vs),new w(0,Vs,-eo),new w(0,Vs,eo),new w(-1,1,-1),new w(1,1,-1),new w(-1,1,1),new w(1,1,1)],uv=new w,Mc=class{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(e,t=0,n=.1,i=100,s={}){let{size:o=256,position:a=uv}=s;Hd=this._renderer.getRenderTarget(),Gd=this._renderer.getActiveCubeFace(),Wd=this._renderer.getActiveMipmapLevel(),Xd=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(o);let c=this._allocateTargets();return c.depthBuffer=!0,this._sceneToCubeUV(e,n,i,c,a),t>0&&this._blur(c,0,0,t),this._applyPMREM(c),this._cleanup(c),c}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=qm(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=Xm(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose()}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodPlanes.length;e++)this._lodPlanes[e].dispose()}_cleanup(e){this._renderer.setRenderTarget(Hd,Gd,Wd),this._renderer.xr.enabled=Xd,e.scissorTest=!1,Uh(e,0,0,e.width,e.height)}_fromTexture(e,t){e.mapping===ii||e.mapping===bi?this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4),Hd=this._renderer.getRenderTarget(),Gd=this._renderer.getActiveCubeFace(),Wd=this._renderer.getActiveMipmapLevel(),Xd=this._renderer.xr.enabled,this._renderer.xr.enabled=!1;let n=t||this._allocateTargets();return this._textureToCubeUV(e,n),this._applyPMREM(n),this._cleanup(n),n}_allocateTargets(){let e=3*Math.max(this._cubeSize,112),t=4*this._cubeSize,n={magFilter:mt,minFilter:mt,generateMipmaps:!1,type:Ns,format:Ht,colorSpace:Ot,depthBuffer:!1},i=Wm(e,t,n);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=Wm(e,t,n);let{_lodMax:s}=this;({sizeLods:this._sizeLods,lodPlanes:this._lodPlanes,sigmas:this._sigmas}=dv(s)),this._blurMaterial=fv(s,e,t)}return i}_compileMaterial(e){let t=new pt(this._lodPlanes[0],e);this._renderer.compile(t,Vd)}_sceneToCubeUV(e,t,n,i,s){let c=new Tt(90,1,t,n),l=[1,-1,1,1,1,1],h=[1,1,1,-1,-1,-1],u=this._renderer,d=u.autoClear,f=u.toneMapping;u.getClearColor(Hm),u.toneMapping=ni,u.autoClear=!1,u.state.buffers.depth.getReversed()&&(u.setRenderTarget(i),u.clearDepth(),u.setRenderTarget(null));let _=new Bt({name:"PMREM.Background",side:Wt,depthWrite:!1,depthTest:!1}),g=new pt(new Vi,_),p=!1,v=e.background;v?v.isColor&&(_.color.copy(v),e.background=null,p=!0):(_.color.copy(Hm),p=!0);for(let y=0;y<6;y++){let x=y%3;x===0?(c.up.set(0,l[y],0),c.position.set(s.x,s.y,s.z),c.lookAt(s.x+h[y],s.y,s.z)):x===1?(c.up.set(0,0,l[y]),c.position.set(s.x,s.y,s.z),c.lookAt(s.x,s.y+h[y],s.z)):(c.up.set(0,l[y],0),c.position.set(s.x,s.y,s.z),c.lookAt(s.x,s.y,s.z+h[y]));let A=this._cubeSize;Uh(i,x*A,y>2?A:0,A,A),u.setRenderTarget(i),p&&u.render(g,c),u.render(e,c)}g.geometry.dispose(),g.material.dispose(),u.toneMapping=f,u.autoClear=d,e.background=v}_textureToCubeUV(e,t){let n=this._renderer,i=e.mapping===ii||e.mapping===bi;i?(this._cubemapMaterial===null&&(this._cubemapMaterial=qm()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=Xm());let s=i?this._cubemapMaterial:this._equirectMaterial,o=new pt(this._lodPlanes[0],s),a=s.uniforms;a.envMap.value=e;let c=this._cubeSize;Uh(t,0,0,3*c,2*c),n.setRenderTarget(t),n.render(o,Vd)}_applyPMREM(e){let t=this._renderer,n=t.autoClear;t.autoClear=!1;let i=this._lodPlanes.length;for(let s=1;s<i;s++){let o=Math.sqrt(this._sigmas[s]*this._sigmas[s]-this._sigmas[s-1]*this._sigmas[s-1]),a=Gm[(i-s-1)%Gm.length];this._blur(e,s-1,s,o,a)}t.autoClear=n}_blur(e,t,n,i,s){let o=this._pingPongRenderTarget;this._halfBlur(e,o,t,n,i,"latitudinal",s),this._halfBlur(o,e,n,n,i,"longitudinal",s)}_halfBlur(e,t,n,i,s,o,a){let c=this._renderer,l=this._blurMaterial;o!=="latitudinal"&&o!=="longitudinal"&&console.error("blur direction must be either latitudinal or longitudinal!");let h=3,u=new pt(this._lodPlanes[i],l),d=l.uniforms,f=this._sizeLods[n]-1,m=isFinite(s)?Math.PI/(2*f):2*Math.PI/(2*Hs-1),_=s/m,g=isFinite(s)?1+Math.floor(h*_):Hs;g>Hs&&console.warn(`sigmaRadians, ${s}, is too large and will clip, as it requested ${g} samples when the maximum is set to ${Hs}`);let p=[],v=0;for(let C=0;C<Hs;++C){let I=C/_,b=Math.exp(-I*I/2);p.push(b),C===0?v+=b:C<g&&(v+=2*b)}for(let C=0;C<p.length;C++)p[C]=p[C]/v;d.envMap.value=e.texture,d.samples.value=g,d.weights.value=p,d.latitudinal.value=o==="latitudinal",a&&(d.poleAxis.value=a);let{_lodMax:y}=this;d.dTheta.value=m,d.mipInt.value=y-n;let x=this._sizeLods[i],A=3*x*(i>y-to?i-y+to:0),E=4*(this._cubeSize-x);Uh(t,A,E,3*x,2*x),c.setRenderTarget(t),c.render(u,Vd)}};function dv(r){let e=[],t=[],n=[],i=r,s=r-to+1+Vm.length;for(let o=0;o<s;o++){let a=Math.pow(2,i);t.push(a);let c=1/a;o>r-to?c=Vm[o-r+to-1]:o===0&&(c=0),n.push(c);let l=1/(a-2),h=-l,u=1+l,d=[h,h,u,h,u,u,h,h,u,u,h,u],f=6,m=6,_=3,g=2,p=1,v=new Float32Array(_*m*f),y=new Float32Array(g*m*f),x=new Float32Array(p*m*f);for(let E=0;E<f;E++){let C=E%3*2/3-1,I=E>2?0:-1,b=[C,I,0,C+2/3,I,0,C+2/3,I+1,0,C,I,0,C+2/3,I+1,0,C,I+1,0];v.set(b,_*m*E),y.set(d,g*m*E);let S=[E,E,E,E,E,E];x.set(S,p*m*E)}let A=new ze;A.setAttribute("position",new je(v,_)),A.setAttribute("uv",new je(y,g)),A.setAttribute("faceIndex",new je(x,p)),e.push(A),i>to&&i--}return{lodPlanes:e,sizeLods:t,sigmas:n}}function Wm(r,e,t){let n=new yn(r,e,t);return n.texture.mapping=Ls,n.texture.name="PMREM.cubeUv",n.scissorTest=!0,n}function Uh(r,e,t,n,i){r.viewport.set(e,t,n,i),r.scissor.set(e,t,n,i)}function fv(r,e,t){let n=new Float32Array(Hs),i=new w(0,1,0);return new on({name:"SphericalGaussianBlur",defines:{n:Hs,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${r}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:n},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:i}},vertexShader:nf(),fragmentShader:`++ precision mediump float;+ precision mediump int;++ varying vec3 vOutputDirection;++ uniform sampler2D envMap;+ uniform int samples;+ uniform float weights[ n ];+ uniform bool latitudinal;+ uniform float dTheta;+ uniform float mipInt;+ uniform vec3 poleAxis;++ #define ENVMAP_TYPE_CUBE_UV+ #include <cube_uv_reflection_fragment>++ vec3 getSample( float theta, vec3 axis ) {++ float cosTheta = cos( theta );+ // Rodrigues' axis-angle rotation+ vec3 sampleDirection = vOutputDirection * cosTheta+ + cross( axis, vOutputDirection ) * sin( theta )+ + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );++ return bilinearCubeUV( envMap, sampleDirection, mipInt );++ }++ void main() {++ vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );++ if ( all( equal( axis, vec3( 0.0 ) ) ) ) {++ axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );++ }++ axis = normalize( axis );++ gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );+ gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );++ for ( int i = 1; i < n; i++ ) {++ if ( i >= samples ) {++ break;++ }++ float theta = dTheta * float( i );+ gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );+ gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );++ }++ }+ `,blending:ti,depthTest:!1,depthWrite:!1})}function Xm(){return new on({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:nf(),fragmentShader:`++ precision mediump float;+ precision mediump int;++ varying vec3 vOutputDirection;++ uniform sampler2D envMap;++ #include <common>++ void main() {++ vec3 outputDirection = normalize( vOutputDirection );+ vec2 uv = equirectUv( outputDirection );++ gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );++ }+ `,blending:ti,depthTest:!1,depthWrite:!1})}function qm(){return new on({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:nf(),fragmentShader:`++ precision mediump float;+ precision mediump int;++ uniform float flipEnvMap;++ varying vec3 vOutputDirection;++ uniform samplerCube envMap;++ void main() {++ gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );++ }+ `,blending:ti,depthTest:!1,depthWrite:!1})}function nf(){return`++ precision mediump float;+ precision mediump int;++ attribute float faceIndex;++ varying vec3 vOutputDirection;++ // RH coordinate system; PMREM face-indexing convention+ vec3 getDirection( vec2 uv, float face ) {++ uv = 2.0 * uv - 1.0;++ vec3 direction = vec3( uv, 1.0 );++ if ( face == 0.0 ) {++ direction = direction.zyx; // ( 1, v, u ) pos x++ } else if ( face == 1.0 ) {++ direction = direction.xzy;+ direction.xz *= -1.0; // ( -u, 1, -v ) pos y++ } else if ( face == 2.0 ) {++ direction.x *= -1.0; // ( -u, v, 1 ) pos z++ } else if ( face == 3.0 ) {++ direction = direction.zyx;+ direction.xz *= -1.0; // ( -1, v, -u ) neg x++ } else if ( face == 4.0 ) {++ direction = direction.xzy;+ direction.xy *= -1.0; // ( -u, -1, v ) neg y++ } else if ( face == 5.0 ) {++ direction.z *= -1.0; // ( u, v, -1 ) neg z++ }++ return direction;++ }++ void main() {++ vOutputDirection = getDirection( uv, faceIndex );+ gl_Position = vec4( position, 1.0 );++ }+ `}function pv(r){let e=new WeakMap,t=null;function n(a){if(a&&a.isTexture){let c=a.mapping,l=c===Wr||c===Xr,h=c===ii||c===bi;if(l||h){let u=e.get(a),d=u!==void 0?u.texture.pmremVersion:0;if(a.isRenderTargetTexture&&a.pmremVersion!==d)return t===null&&(t=new Mc(r)),u=l?t.fromEquirectangular(a,u):t.fromCubemap(a,u),u.texture.pmremVersion=a.pmremVersion,e.set(a,u),u.texture;if(u!==void 0)return u.texture;{let f=a.image;return l&&f&&f.height>0||h&&f&&i(f)?(t===null&&(t=new Mc(r)),u=l?t.fromEquirectangular(a):t.fromCubemap(a),u.texture.pmremVersion=a.pmremVersion,e.set(a,u),a.addEventListener("dispose",s),u.texture):null}}}return a}function i(a){let c=0,l=6;for(let h=0;h<l;h++)a[h]!==void 0&&c++;return c===l}function s(a){let c=a.target;c.removeEventListener("dispose",s);let l=e.get(c);l!==void 0&&(e.delete(c),l.dispose())}function o(){e=new WeakMap,t!==null&&(t.dispose(),t=null)}return{get:n,dispose:o}}function mv(r){let e={};function t(n){if(e[n]!==void 0)return e[n];let i;switch(n){case"WEBGL_depth_texture":i=r.getExtension("WEBGL_depth_texture")||r.getExtension("MOZ_WEBGL_depth_texture")||r.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":i=r.getExtension("EXT_texture_filter_anisotropic")||r.getExtension("MOZ_EXT_texture_filter_anisotropic")||r.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":i=r.getExtension("WEBGL_compressed_texture_s3tc")||r.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||r.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":i=r.getExtension("WEBGL_compressed_texture_pvrtc")||r.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:i=r.getExtension(n)}return e[n]=i,i}return{has:function(n){return t(n)!==null},init:function(){t("EXT_color_buffer_float"),t("WEBGL_clip_cull_distance"),t("OES_texture_float_linear"),t("EXT_color_buffer_half_float"),t("WEBGL_multisampled_render_to_texture"),t("WEBGL_render_shared_exponent")},get:function(n){let i=t(n);return i===null&&_r("THREE.WebGLRenderer: "+n+" extension not supported."),i}}}function gv(r,e,t,n){let i={},s=new WeakMap;function o(u){let d=u.target;d.index!==null&&e.remove(d.index);for(let m in d.attributes)e.remove(d.attributes[m]);d.removeEventListener("dispose",o),delete i[d.id];let f=s.get(d);f&&(e.remove(f),s.delete(d)),n.releaseStatesOfGeometry(d),d.isInstancedBufferGeometry===!0&&delete d._maxInstanceCount,t.memory.geometries--}function a(u,d){return i[d.id]===!0||(d.addEventListener("dispose",o),i[d.id]=!0,t.memory.geometries++),d}function c(u){let d=u.attributes;for(let f in d)e.update(d[f],r.ARRAY_BUFFER)}function l(u){let d=[],f=u.index,m=u.attributes.position,_=0;if(f!==null){let v=f.array;_=f.version;for(let y=0,x=v.length;y<x;y+=3){let A=v[y+0],E=v[y+1],C=v[y+2];d.push(A,E,E,C,C,A)}}else if(m!==void 0){let v=m.array;_=m.version;for(let y=0,x=v.length/3-1;y<x;y+=3){let A=y+0,E=y+1,C=y+2;d.push(A,E,E,C,C,A)}}else return;let g=new(Ld(d)?vr:yr)(d,1);g.version=_;let p=s.get(u);p&&e.remove(p),s.set(u,g)}function h(u){let d=s.get(u);if(d){let f=u.index;f!==null&&d.version<f.version&&l(u)}else l(u);return s.get(u)}return{get:a,update:c,getWireframeAttribute:h}}function _v(r,e,t){let n;function i(d){n=d}let s,o;function a(d){s=d.type,o=d.bytesPerElement}function c(d,f){r.drawElements(n,f,s,d*o),t.update(f,n,1)}function l(d,f,m){m!==0&&(r.drawElementsInstanced(n,f,s,d*o,m),t.update(f,n,m))}function h(d,f,m){if(m===0)return;e.get("WEBGL_multi_draw").multiDrawElementsWEBGL(n,f,0,s,d,0,m);let g=0;for(let p=0;p<m;p++)g+=f[p];t.update(g,n,1)}function u(d,f,m,_){if(m===0)return;let g=e.get("WEBGL_multi_draw");if(g===null)for(let p=0;p<d.length;p++)l(d[p]/o,f[p],_[p]);else{g.multiDrawElementsInstancedWEBGL(n,f,0,s,d,0,_,0,m);let p=0;for(let v=0;v<m;v++)p+=f[v]*_[v];t.update(p,n,1)}}this.setMode=i,this.setIndex=a,this.render=c,this.renderInstances=l,this.renderMultiDraw=h,this.renderMultiDrawInstances=u}function xv(r){let e={geometries:0,textures:0},t={frame:0,calls:0,triangles:0,points:0,lines:0};function n(s,o,a){switch(t.calls++,o){case r.TRIANGLES:t.triangles+=a*(s/3);break;case r.LINES:t.lines+=a*(s/2);break;case r.LINE_STRIP:t.lines+=a*(s-1);break;case r.LINE_LOOP:t.lines+=a*s;break;case r.POINTS:t.points+=a*s;break;default:console.error("THREE.WebGLInfo: Unknown draw mode:",o);break}}function i(){t.calls=0,t.triangles=0,t.points=0,t.lines=0}return{memory:e,render:t,programs:null,autoReset:!0,reset:i,update:n}}function yv(r,e,t){let n=new WeakMap,i=new tt;function s(o,a,c){let l=o.morphTargetInfluences,h=a.morphAttributes.position||a.morphAttributes.normal||a.morphAttributes.color,u=h!==void 0?h.length:0,d=n.get(a);if(d===void 0||d.count!==u){let b=function(){C.dispose(),n.delete(a),a.removeEventListener("dispose",b)};d!==void 0&&d.texture.dispose();let f=a.morphAttributes.position!==void 0,m=a.morphAttributes.normal!==void 0,_=a.morphAttributes.color!==void 0,g=a.morphAttributes.position||[],p=a.morphAttributes.normal||[],v=a.morphAttributes.color||[],y=0;f===!0&&(y=1),m===!0&&(y=2),_===!0&&(y=3);let x=a.attributes.position.count*y,A=1;x>e.maxTextureSize&&(A=Math.ceil(x/e.maxTextureSize),x=e.maxTextureSize);let E=new Float32Array(x*A*4*u),C=new fs(E,x,A,u);C.type=Jt,C.needsUpdate=!0;let I=y*4;for(let S=0;S<u;S++){let L=g[S],F=p[S],z=v[S],G=x*A*4*S;for(let q=0;q<L.count;q++){let W=q*I;f===!0&&(i.fromBufferAttribute(L,q),E[G+W+0]=i.x,E[G+W+1]=i.y,E[G+W+2]=i.z,E[G+W+3]=0),m===!0&&(i.fromBufferAttribute(F,q),E[G+W+4]=i.x,E[G+W+5]=i.y,E[G+W+6]=i.z,E[G+W+7]=0),_===!0&&(i.fromBufferAttribute(z,q),E[G+W+8]=i.x,E[G+W+9]=i.y,E[G+W+10]=i.z,E[G+W+11]=z.itemSize===4?i.w:1)}}d={count:u,texture:C,size:new Y(x,A)},n.set(a,d),a.addEventListener("dispose",b)}if(o.isInstancedMesh===!0&&o.morphTexture!==null)c.getUniforms().setValue(r,"morphTexture",o.morphTexture,t);else{let f=0;for(let _=0;_<l.length;_++)f+=l[_];let m=a.morphTargetsRelative?1:1-f;c.getUniforms().setValue(r,"morphTargetBaseInfluence",m),c.getUniforms().setValue(r,"morphTargetInfluences",l)}c.getUniforms().setValue(r,"morphTargetsTexture",d.texture,t),c.getUniforms().setValue(r,"morphTargetsTextureSize",d.size)}return{update:s}}function vv(r,e,t,n){let i=new WeakMap;function s(c){let l=n.render.frame,h=c.geometry,u=e.get(c,h);if(i.get(u)!==l&&(e.update(u),i.set(u,l)),c.isInstancedMesh&&(c.hasEventListener("dispose",a)===!1&&c.addEventListener("dispose",a),i.get(c)!==l&&(t.update(c.instanceMatrix,r.ARRAY_BUFFER),c.instanceColor!==null&&t.update(c.instanceColor,r.ARRAY_BUFFER),i.set(c,l))),c.isSkinnedMesh){let d=c.skeleton;i.get(d)!==l&&(d.update(),i.set(d,l))}return u}function o(){i=new WeakMap}function a(c){let l=c.target;l.removeEventListener("dispose",a),t.remove(l.instanceMatrix),l.instanceColor!==null&&t.remove(l.instanceColor)}return{update:s,dispose:o}}var ug=new gt,Ym=new Sr(1,1),dg=new fs,fg=new ps,pg=new Hi,Zm=[],Km=[],Jm=new Float32Array(16),$m=new Float32Array(9),jm=new Float32Array(4);function io(r,e,t){let n=r[0];if(n<=0||n>0)return r;let i=e*t,s=Zm[i];if(s===void 0&&(s=new Float32Array(i),Zm[i]=s),e!==0){n.toArray(s,0);for(let o=1,a=0;o!==e;++o)a+=t,r[o].toArray(s,a)}return s}function Dt(r,e){if(r.length!==e.length)return!1;for(let t=0,n=r.length;t<n;t++)if(r[t]!==e[t])return!1;return!0}function Nt(r,e){for(let t=0,n=e.length;t<n;t++)r[t]=e[t]}function Oh(r,e){let t=Km[e];t===void 0&&(t=new Int32Array(e),Km[e]=t);for(let n=0;n!==e;++n)t[n]=r.allocateTextureUnit();return t}function Mv(r,e){let t=this.cache;t[0]!==e&&(r.uniform1f(this.addr,e),t[0]=e)}function Sv(r,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(r.uniform2f(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(Dt(t,e))return;r.uniform2fv(this.addr,e),Nt(t,e)}}function bv(r,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(r.uniform3f(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else if(e.r!==void 0)(t[0]!==e.r||t[1]!==e.g||t[2]!==e.b)&&(r.uniform3f(this.addr,e.r,e.g,e.b),t[0]=e.r,t[1]=e.g,t[2]=e.b);else{if(Dt(t,e))return;r.uniform3fv(this.addr,e),Nt(t,e)}}function Tv(r,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(r.uniform4f(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(Dt(t,e))return;r.uniform4fv(this.addr,e),Nt(t,e)}}function Ev(r,e){let t=this.cache,n=e.elements;if(n===void 0){if(Dt(t,e))return;r.uniformMatrix2fv(this.addr,!1,e),Nt(t,e)}else{if(Dt(t,n))return;jm.set(n),r.uniformMatrix2fv(this.addr,!1,jm),Nt(t,n)}}function Av(r,e){let t=this.cache,n=e.elements;if(n===void 0){if(Dt(t,e))return;r.uniformMatrix3fv(this.addr,!1,e),Nt(t,e)}else{if(Dt(t,n))return;$m.set(n),r.uniformMatrix3fv(this.addr,!1,$m),Nt(t,n)}}function wv(r,e){let t=this.cache,n=e.elements;if(n===void 0){if(Dt(t,e))return;r.uniformMatrix4fv(this.addr,!1,e),Nt(t,e)}else{if(Dt(t,n))return;Jm.set(n),r.uniformMatrix4fv(this.addr,!1,Jm),Nt(t,n)}}function Rv(r,e){let t=this.cache;t[0]!==e&&(r.uniform1i(this.addr,e),t[0]=e)}function Cv(r,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(r.uniform2i(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(Dt(t,e))return;r.uniform2iv(this.addr,e),Nt(t,e)}}function Iv(r,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(r.uniform3i(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else{if(Dt(t,e))return;r.uniform3iv(this.addr,e),Nt(t,e)}}function Pv(r,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(r.uniform4i(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(Dt(t,e))return;r.uniform4iv(this.addr,e),Nt(t,e)}}function Lv(r,e){let t=this.cache;t[0]!==e&&(r.uniform1ui(this.addr,e),t[0]=e)}function Dv(r,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(r.uniform2ui(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(Dt(t,e))return;r.uniform2uiv(this.addr,e),Nt(t,e)}}function Nv(r,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(r.uniform3ui(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else{if(Dt(t,e))return;r.uniform3uiv(this.addr,e),Nt(t,e)}}function Uv(r,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(r.uniform4ui(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(Dt(t,e))return;r.uniform4uiv(this.addr,e),Nt(t,e)}}function Fv(r,e,t){let n=this.cache,i=t.allocateTextureUnit();n[0]!==i&&(r.uniform1i(this.addr,i),n[0]=i);let s;this.type===r.SAMPLER_2D_SHADOW?(Ym.compareFunction=Ph,s=Ym):s=ug,t.setTexture2D(e||s,i)}function Ov(r,e,t){let n=this.cache,i=t.allocateTextureUnit();n[0]!==i&&(r.uniform1i(this.addr,i),n[0]=i),t.setTexture3D(e||fg,i)}function Bv(r,e,t){let n=this.cache,i=t.allocateTextureUnit();n[0]!==i&&(r.uniform1i(this.addr,i),n[0]=i),t.setTextureCube(e||pg,i)}function zv(r,e,t){let n=this.cache,i=t.allocateTextureUnit();n[0]!==i&&(r.uniform1i(this.addr,i),n[0]=i),t.setTexture2DArray(e||dg,i)}function kv(r){switch(r){case 5126:return Mv;case 35664:return Sv;case 35665:return bv;case 35666:return Tv;case 35674:return Ev;case 35675:return Av;case 35676:return wv;case 5124:case 35670:return Rv;case 35667:case 35671:return Cv;case 35668:case 35672:return Iv;case 35669:case 35673:return Pv;case 5125:return Lv;case 36294:return Dv;case 36295:return Nv;case 36296:return Uv;case 35678:case 36198:case 36298:case 36306:case 35682:return Fv;case 35679:case 36299:case 36307:return Ov;case 35680:case 36300:case 36308:case 36293:return Bv;case 36289:case 36303:case 36311:case 36292:return zv}}function Vv(r,e){r.uniform1fv(this.addr,e)}function Hv(r,e){let t=io(e,this.size,2);r.uniform2fv(this.addr,t)}function Gv(r,e){let t=io(e,this.size,3);r.uniform3fv(this.addr,t)}function Wv(r,e){let t=io(e,this.size,4);r.uniform4fv(this.addr,t)}function Xv(r,e){let t=io(e,this.size,4);r.uniformMatrix2fv(this.addr,!1,t)}function qv(r,e){let t=io(e,this.size,9);r.uniformMatrix3fv(this.addr,!1,t)}function Yv(r,e){let t=io(e,this.size,16);r.uniformMatrix4fv(this.addr,!1,t)}function Zv(r,e){r.uniform1iv(this.addr,e)}function Kv(r,e){r.uniform2iv(this.addr,e)}function Jv(r,e){r.uniform3iv(this.addr,e)}function $v(r,e){r.uniform4iv(this.addr,e)}function jv(r,e){r.uniform1uiv(this.addr,e)}function Qv(r,e){r.uniform2uiv(this.addr,e)}function eM(r,e){r.uniform3uiv(this.addr,e)}function tM(r,e){r.uniform4uiv(this.addr,e)}function nM(r,e,t){let n=this.cache,i=e.length,s=Oh(t,i);Dt(n,s)||(r.uniform1iv(this.addr,s),Nt(n,s));for(let o=0;o!==i;++o)t.setTexture2D(e[o]||ug,s[o])}function iM(r,e,t){let n=this.cache,i=e.length,s=Oh(t,i);Dt(n,s)||(r.uniform1iv(this.addr,s),Nt(n,s));for(let o=0;o!==i;++o)t.setTexture3D(e[o]||fg,s[o])}function sM(r,e,t){let n=this.cache,i=e.length,s=Oh(t,i);Dt(n,s)||(r.uniform1iv(this.addr,s),Nt(n,s));for(let o=0;o!==i;++o)t.setTextureCube(e[o]||pg,s[o])}function rM(r,e,t){let n=this.cache,i=e.length,s=Oh(t,i);Dt(n,s)||(r.uniform1iv(this.addr,s),Nt(n,s));for(let o=0;o!==i;++o)t.setTexture2DArray(e[o]||dg,s[o])}function oM(r){switch(r){case 5126:return Vv;case 35664:return Hv;case 35665:return Gv;case 35666:return Wv;case 35674:return Xv;case 35675:return qv;case 35676:return Yv;case 5124:case 35670:return Zv;case 35667:case 35671:return Kv;case 35668:case 35672:return Jv;case 35669:case 35673:return $v;case 5125:return jv;case 36294:return Qv;case 36295:return eM;case 36296:return tM;case 35678:case 36198:case 36298:case 36306:case 35682:return nM;case 35679:case 36299:case 36307:return iM;case 35680:case 36300:case 36308:case 36293:return sM;case 36289:case 36303:case 36311:case 36292:return rM}}var Yd=class{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.setValue=kv(t.type)}},Zd=class{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.size=t.size,this.setValue=oM(t.type)}},Kd=class{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,t,n){let i=this.seq;for(let s=0,o=i.length;s!==o;++s){let a=i[s];a.setValue(e,t[a.id],n)}}},qd=/(\w+)(\])?(\[|\.)?/g;function Qm(r,e){r.seq.push(e),r.map[e.id]=e}function aM(r,e,t){let n=r.name,i=n.length;for(qd.lastIndex=0;;){let s=qd.exec(n),o=qd.lastIndex,a=s[1],c=s[2]==="]",l=s[3];if(c&&(a=a|0),l===void 0||l==="["&&o+2===i){Qm(t,l===void 0?new Yd(a,r,e):new Zd(a,r,e));break}else{let u=t.map[a];u===void 0&&(u=new Kd(a),Qm(t,u)),t=u}}}var no=class{constructor(e,t){this.seq=[],this.map={};let n=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let i=0;i<n;++i){let s=e.getActiveUniform(t,i),o=e.getUniformLocation(t,s.name);aM(s,o,this)}}setValue(e,t,n,i){let s=this.map[t];s!==void 0&&s.setValue(e,n,i)}setOptional(e,t,n){let i=t[n];i!==void 0&&this.setValue(e,n,i)}static upload(e,t,n,i){for(let s=0,o=t.length;s!==o;++s){let a=t[s],c=n[a.id];c.needsUpdate!==!1&&a.setValue(e,c.value,i)}}static seqWithValue(e,t){let n=[];for(let i=0,s=e.length;i!==s;++i){let o=e[i];o.id in t&&n.push(o)}return n}};function eg(r,e,t){let n=r.createShader(e);return r.shaderSource(n,t),r.compileShader(n),n}var cM=37297,lM=0;function hM(r,e){let t=r.split(`+`),n=[],i=Math.max(e-6,0),s=Math.min(e+6,t.length);for(let o=i;o<s;o++){let a=o+1;n.push(`${a===e?">":" "} ${a}: ${t[o]}`)}return n.join(`+`)}var tg=new Ve;function uM(r){Ze._getMatrix(tg,Ze.workingColorSpace,r);let e=`mat3( ${tg.elements.map(t=>t.toFixed(4))} )`;switch(Ze.getTransfer(r)){case pr:return[e,"LinearTransferOETF"];case ot:return[e,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space: ",r),[e,"LinearTransferOETF"]}}function ng(r,e,t){let n=r.getShaderParameter(e,r.COMPILE_STATUS),s=(r.getShaderInfoLog(e)||"").trim();if(n&&s==="")return"";let o=/ERROR: 0:(\d+)/.exec(s);if(o){let a=parseInt(o[1]);return t.toUpperCase()+`++`+s+`++`+hM(r.getShaderSource(e),a)}else return s}function dM(r,e){let t=uM(e);return[`vec4 ${r}( vec4 value ) {`,` return ${t[1]}( vec4( value.rgb * ${t[0]}, value.a ) );`,"}"].join(`+`)}function fM(r,e){let t;switch(e){case hd:t="Linear";break;case ud:t="Reinhard";break;case dd:t="Cineon";break;case fd:t="ACESFilmic";break;case md:t="AgX";break;case gd:t="Neutral";break;case pd:t="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",e),t="Linear"}return"vec3 "+r+"( vec3 color ) { return "+t+"ToneMapping( color ); }"}var Fh=new w;function pM(){Ze.getLuminanceCoefficients(Fh);let r=Fh.x.toFixed(4),e=Fh.y.toFixed(4),t=Fh.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${r}, ${e}, ${t} );`," return dot( weights, rgb );","}"].join(`+`)}function mM(r){return[r.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",r.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(vc).join(`+`)}function gM(r){let e=[];for(let t in r){let n=r[t];n!==!1&&e.push("#define "+t+" "+n)}return e.join(`+`)}function _M(r,e){let t={},n=r.getProgramParameter(e,r.ACTIVE_ATTRIBUTES);for(let i=0;i<n;i++){let s=r.getActiveAttrib(e,i),o=s.name,a=1;s.type===r.FLOAT_MAT2&&(a=2),s.type===r.FLOAT_MAT3&&(a=3),s.type===r.FLOAT_MAT4&&(a=4),t[o]={type:s.type,location:r.getAttribLocation(e,o),locationSize:a}}return t}function vc(r){return r!==""}function ig(r,e){let t=e.numSpotLightShadows+e.numSpotLightMaps-e.numSpotLightShadowsWithMaps;return r.replace(/NUM_DIR_LIGHTS/g,e.numDirLights).replace(/NUM_SPOT_LIGHTS/g,e.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,e.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,t).replace(/NUM_RECT_AREA_LIGHTS/g,e.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,e.numPointLights).replace(/NUM_HEMI_LIGHTS/g,e.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g,e.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,e.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,e.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,e.numPointLightShadows)}function sg(r,e){return r.replace(/NUM_CLIPPING_PLANES/g,e.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,e.numClippingPlanes-e.numClipIntersection)}var xM=/^[ \t]*#include +<([\w\d./]+)>/gm;function Jd(r){return r.replace(xM,vM)}var yM=new Map;function vM(r,e){let t=Ye[e];if(t===void 0){let n=yM.get(e);if(n!==void 0)t=Ye[n],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,n);else throw new Error("Can not resolve #include <"+e+">")}return Jd(t)}var MM=/#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 rg(r){return r.replace(MM,SM)}function SM(r,e,t,n){let i="";for(let s=parseInt(e);s<parseInt(t);s++)i+=n.replace(/\[\s*i\s*\]/g,"[ "+s+" ]").replace(/UNROLLED_LOOP_INDEX/g,s);return i}function og(r){let e=`precision ${r.precision} float;+ precision ${r.precision} int;+ precision ${r.precision} sampler2D;+ precision ${r.precision} samplerCube;+ precision ${r.precision} sampler3D;+ precision ${r.precision} sampler2DArray;+ precision ${r.precision} sampler2DShadow;+ precision ${r.precision} samplerCubeShadow;+ precision ${r.precision} sampler2DArrayShadow;+ precision ${r.precision} isampler2D;+ precision ${r.precision} isampler3D;+ precision ${r.precision} isamplerCube;+ precision ${r.precision} isampler2DArray;+ precision ${r.precision} usampler2D;+ precision ${r.precision} usampler3D;+ precision ${r.precision} usamplerCube;+ precision ${r.precision} usampler2DArray;+ `;return r.precision==="highp"?e+=`+#define HIGH_PRECISION`:r.precision==="mediump"?e+=`+#define MEDIUM_PRECISION`:r.precision==="lowp"&&(e+=`+#define LOW_PRECISION`),e}function bM(r){let e="SHADOWMAP_TYPE_BASIC";return r.shadowMapType===xh?e="SHADOWMAP_TYPE_PCF":r.shadowMapType===Gu?e="SHADOWMAP_TYPE_PCF_SOFT":r.shadowMapType===Gn&&(e="SHADOWMAP_TYPE_VSM"),e}function TM(r){let e="ENVMAP_TYPE_CUBE";if(r.envMap)switch(r.envMapMode){case ii:case bi:e="ENVMAP_TYPE_CUBE";break;case Ls:e="ENVMAP_TYPE_CUBE_UV";break}return e}function EM(r){let e="ENVMAP_MODE_REFLECTION";return r.envMap&&r.envMapMode===bi&&(e="ENVMAP_MODE_REFRACTION"),e}function AM(r){let e="ENVMAP_BLENDING_NONE";if(r.envMap)switch(r.combine){case Gr:e="ENVMAP_BLENDING_MULTIPLY";break;case cd:e="ENVMAP_BLENDING_MIX";break;case ld:e="ENVMAP_BLENDING_ADD";break}return e}function wM(r){let e=r.envMapCubeUVHeight;if(e===null)return null;let t=Math.log2(e)-2,n=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,t),112)),texelHeight:n,maxMip:t}}function RM(r,e,t,n){let i=r.getContext(),s=t.defines,o=t.vertexShader,a=t.fragmentShader,c=bM(t),l=TM(t),h=EM(t),u=AM(t),d=wM(t),f=mM(t),m=gM(s),_=i.createProgram(),g,p,v=t.glslVersion?"#version "+t.glslVersion+`+`:"";t.isRawShaderMaterial?(g=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,m].filter(vc).join(`+`),g.length>0&&(g+=`+`),p=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,m].filter(vc).join(`+`),p.length>0&&(p+=`+`)):(g=[og(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,m,t.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",t.batching?"#define USE_BATCHING":"",t.batchingColor?"#define USE_BATCHING_COLOR":"",t.instancing?"#define USE_INSTANCING":"",t.instancingColor?"#define USE_INSTANCING_COLOR":"",t.instancingMorph?"#define USE_INSTANCING_MORPH":"",t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.map?"#define USE_MAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+h:"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.displacementMap?"#define USE_DISPLACEMENTMAP":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.mapUv?"#define MAP_UV "+t.mapUv:"",t.alphaMapUv?"#define ALPHAMAP_UV "+t.alphaMapUv:"",t.lightMapUv?"#define LIGHTMAP_UV "+t.lightMapUv:"",t.aoMapUv?"#define AOMAP_UV "+t.aoMapUv:"",t.emissiveMapUv?"#define EMISSIVEMAP_UV "+t.emissiveMapUv:"",t.bumpMapUv?"#define BUMPMAP_UV "+t.bumpMapUv:"",t.normalMapUv?"#define NORMALMAP_UV "+t.normalMapUv:"",t.displacementMapUv?"#define DISPLACEMENTMAP_UV "+t.displacementMapUv:"",t.metalnessMapUv?"#define METALNESSMAP_UV "+t.metalnessMapUv:"",t.roughnessMapUv?"#define ROUGHNESSMAP_UV "+t.roughnessMapUv:"",t.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+t.anisotropyMapUv:"",t.clearcoatMapUv?"#define CLEARCOATMAP_UV "+t.clearcoatMapUv:"",t.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+t.clearcoatNormalMapUv:"",t.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+t.clearcoatRoughnessMapUv:"",t.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+t.iridescenceMapUv:"",t.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+t.iridescenceThicknessMapUv:"",t.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+t.sheenColorMapUv:"",t.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+t.sheenRoughnessMapUv:"",t.specularMapUv?"#define SPECULARMAP_UV "+t.specularMapUv:"",t.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+t.specularColorMapUv:"",t.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+t.specularIntensityMapUv:"",t.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+t.transmissionMapUv:"",t.thicknessMapUv?"#define THICKNESSMAP_UV "+t.thicknessMapUv:"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.flatShading?"#define FLAT_SHADED":"",t.skinning?"#define USE_SKINNING":"",t.morphTargets?"#define USE_MORPHTARGETS":"",t.morphNormals&&t.flatShading===!1?"#define USE_MORPHNORMALS":"",t.morphColors?"#define USE_MORPHCOLORS":"",t.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+t.morphTextureStride:"",t.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+t.morphTargetsCount:"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+c:"",t.sizeAttenuation?"#define USE_SIZEATTENUATION":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.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(vc).join(`+`),p=[og(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,m,t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",t.map?"#define USE_MAP":"",t.matcap?"#define USE_MATCAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+l:"",t.envMap?"#define "+h:"",t.envMap?"#define "+u:"",d?"#define CUBEUV_TEXEL_WIDTH "+d.texelWidth:"",d?"#define CUBEUV_TEXEL_HEIGHT "+d.texelHeight:"",d?"#define CUBEUV_MAX_MIP "+d.maxMip+".0":"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoat?"#define USE_CLEARCOAT":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.dispersion?"#define USE_DISPERSION":"",t.iridescence?"#define USE_IRIDESCENCE":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaTest?"#define USE_ALPHATEST":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.sheen?"#define USE_SHEEN":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors||t.instancingColor||t.batchingColor?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.gradientMap?"#define USE_GRADIENTMAP":"",t.flatShading?"#define FLAT_SHADED":"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+c:"",t.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",t.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",t.toneMapping!==ni?"#define TONE_MAPPING":"",t.toneMapping!==ni?Ye.tonemapping_pars_fragment:"",t.toneMapping!==ni?fM("toneMapping",t.toneMapping):"",t.dithering?"#define DITHERING":"",t.opaque?"#define OPAQUE":"",Ye.colorspace_pars_fragment,dM("linearToOutputTexel",t.outputColorSpace),pM(),t.useDepthPacking?"#define DEPTH_PACKING "+t.depthPacking:"",`+`].filter(vc).join(`+`)),o=Jd(o),o=ig(o,t),o=sg(o,t),a=Jd(a),a=ig(a,t),a=sg(a,t),o=rg(o),a=rg(a),t.isRawShaderMaterial!==!0&&(v=`#version 300 es+`,g=[f,"#define attribute in","#define varying out","#define texture2D texture"].join(`+`)+`+`+g,p=["#define varying in",t.glslVersion===Lh?"":"layout(location = 0) out highp vec4 pc_fragColor;",t.glslVersion===Lh?"":"#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(`+`)+`+`+p);let y=v+g+o,x=v+p+a,A=eg(i,i.VERTEX_SHADER,y),E=eg(i,i.FRAGMENT_SHADER,x);i.attachShader(_,A),i.attachShader(_,E),t.index0AttributeName!==void 0?i.bindAttribLocation(_,0,t.index0AttributeName):t.morphTargets===!0&&i.bindAttribLocation(_,0,"position"),i.linkProgram(_);function C(L){if(r.debug.checkShaderErrors){let F=i.getProgramInfoLog(_)||"",z=i.getShaderInfoLog(A)||"",G=i.getShaderInfoLog(E)||"",q=F.trim(),W=z.trim(),ne=G.trim(),H=!0,de=!0;if(i.getProgramParameter(_,i.LINK_STATUS)===!1)if(H=!1,typeof r.debug.onShaderError=="function")r.debug.onShaderError(i,_,A,E);else{let xe=ng(i,A,"vertex"),Se=ng(i,E,"fragment");console.error("THREE.WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(_,i.VALIDATE_STATUS)+`++Material Name: `+L.name+`+Material Type: `+L.type+`++Program Info Log: `+q+`+`+xe+`+`+Se)}else q!==""?console.warn("THREE.WebGLProgram: Program Info Log:",q):(W===""||ne==="")&&(de=!1);de&&(L.diagnostics={runnable:H,programLog:q,vertexShader:{log:W,prefix:g},fragmentShader:{log:ne,prefix:p}})}i.deleteShader(A),i.deleteShader(E),I=new no(i,_),b=_M(i,_)}let I;this.getUniforms=function(){return I===void 0&&C(this),I};let b;this.getAttributes=function(){return b===void 0&&C(this),b};let S=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return S===!1&&(S=i.getProgramParameter(_,cM)),S},this.destroy=function(){n.releaseStatesOfProgram(this),i.deleteProgram(_),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=lM++,this.cacheKey=e,this.usedTimes=1,this.program=_,this.vertexShader=A,this.fragmentShader=E,this}var CM=0,$d=class{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){let t=e.vertexShader,n=e.fragmentShader,i=this._getShaderStage(t),s=this._getShaderStage(n),o=this._getShaderCacheForMaterial(e);return o.has(i)===!1&&(o.add(i),i.usedTimes++),o.has(s)===!1&&(o.add(s),s.usedTimes++),this}remove(e){let t=this.materialCache.get(e);for(let n of t)n.usedTimes--,n.usedTimes===0&&this.shaderCache.delete(n.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){let t=this.materialCache,n=t.get(e);return n===void 0&&(n=new Set,t.set(e,n)),n}_getShaderStage(e){let t=this.shaderCache,n=t.get(e);return n===void 0&&(n=new jd(e),t.set(e,n)),n}},jd=class{constructor(e){this.id=CM++,this.code=e,this.usedTimes=0}};function IM(r,e,t,n,i,s,o){let a=new ms,c=new $d,l=new Set,h=[],u=i.logarithmicDepthBuffer,d=i.vertexTextures,f=i.precision,m={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function _(b){return l.add(b),b===0?"uv":`uv${b}`}function g(b,S,L,F,z){let G=F.fog,q=z.geometry,W=b.isMeshStandardMaterial?F.environment:null,ne=(b.isMeshStandardMaterial?t:e).get(b.envMap||W),H=ne&&ne.mapping===Ls?ne.image.height:null,de=m[b.type];b.precision!==null&&(f=i.getMaxPrecision(b.precision),f!==b.precision&&console.warn("THREE.WebGLProgram.getParameters:",b.precision,"not supported, using",f,"instead."));let xe=q.morphAttributes.position||q.morphAttributes.normal||q.morphAttributes.color,Se=xe!==void 0?xe.length:0,We=0;q.morphAttributes.position!==void 0&&(We=1),q.morphAttributes.normal!==void 0&&(We=2),q.morphAttributes.color!==void 0&&(We=3);let et,at,nt,Z;if(de){let rt=Wn[de];et=rt.vertexShader,at=rt.fragmentShader}else et=b.vertexShader,at=b.fragmentShader,c.update(b),nt=c.getVertexShaderID(b),Z=c.getFragmentShaderID(b);let te=r.getRenderTarget(),Me=r.state.buffers.depth.getReversed(),Pe=z.isInstancedMesh===!0,Ee=z.isBatchedMesh===!0,Je=!!b.map,ut=!!b.matcap,P=!!ne,ee=!!b.aoMap,$=!!b.lightMap,J=!!b.bumpMap,K=!!b.normalMap,le=!!b.displacementMap,ie=!!b.emissiveMap,he=!!b.metalnessMap,He=!!b.roughnessMap,ke=b.anisotropy>0,R=b.clearcoat>0,M=b.dispersion>0,O=b.iridescence>0,V=b.sheen>0,Q=b.transmission>0,X=ke&&!!b.anisotropyMap,Ce=R&&!!b.clearcoatMap,ce=R&&!!b.clearcoatNormalMap,Ae=R&&!!b.clearcoatRoughnessMap,we=O&&!!b.iridescenceMap,se=O&&!!b.iridescenceThicknessMap,_e=V&&!!b.sheenColorMap,Oe=V&&!!b.sheenRoughnessMap,Ie=!!b.specularMap,me=!!b.specularColorMap,qe=!!b.specularIntensityMap,D=Q&&!!b.transmissionMap,ae=Q&&!!b.thicknessMap,fe=!!b.gradientMap,be=!!b.alphaMap,re=b.alphaTest>0,j=!!b.alphaHash,Re=!!b.extensions,Ge=ni;b.toneMapped&&(te===null||te.isXRRenderTarget===!0)&&(Ge=r.toneMapping);let dt={shaderID:de,shaderType:b.type,shaderName:b.name,vertexShader:et,fragmentShader:at,defines:b.defines,customVertexShaderID:nt,customFragmentShaderID:Z,isRawShaderMaterial:b.isRawShaderMaterial===!0,glslVersion:b.glslVersion,precision:f,batching:Ee,batchingColor:Ee&&z._colorsTexture!==null,instancing:Pe,instancingColor:Pe&&z.instanceColor!==null,instancingMorph:Pe&&z.morphTexture!==null,supportsVertexTextures:d,outputColorSpace:te===null?r.outputColorSpace:te.isXRRenderTarget===!0?te.texture.colorSpace:Ot,alphaToCoverage:!!b.alphaToCoverage,map:Je,matcap:ut,envMap:P,envMapMode:P&&ne.mapping,envMapCubeUVHeight:H,aoMap:ee,lightMap:$,bumpMap:J,normalMap:K,displacementMap:d&&le,emissiveMap:ie,normalMapObjectSpace:K&&b.normalMapType===bd,normalMapTangentSpace:K&&b.normalMapType===Ei,metalnessMap:he,roughnessMap:He,anisotropy:ke,anisotropyMap:X,clearcoat:R,clearcoatMap:Ce,clearcoatNormalMap:ce,clearcoatRoughnessMap:Ae,dispersion:M,iridescence:O,iridescenceMap:we,iridescenceThicknessMap:se,sheen:V,sheenColorMap:_e,sheenRoughnessMap:Oe,specularMap:Ie,specularColorMap:me,specularIntensityMap:qe,transmission:Q,transmissionMap:D,thicknessMap:ae,gradientMap:fe,opaque:b.transparent===!1&&b.blending===Fi&&b.alphaToCoverage===!1,alphaMap:be,alphaTest:re,alphaHash:j,combine:b.combine,mapUv:Je&&_(b.map.channel),aoMapUv:ee&&_(b.aoMap.channel),lightMapUv:$&&_(b.lightMap.channel),bumpMapUv:J&&_(b.bumpMap.channel),normalMapUv:K&&_(b.normalMap.channel),displacementMapUv:le&&_(b.displacementMap.channel),emissiveMapUv:ie&&_(b.emissiveMap.channel),metalnessMapUv:he&&_(b.metalnessMap.channel),roughnessMapUv:He&&_(b.roughnessMap.channel),anisotropyMapUv:X&&_(b.anisotropyMap.channel),clearcoatMapUv:Ce&&_(b.clearcoatMap.channel),clearcoatNormalMapUv:ce&&_(b.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Ae&&_(b.clearcoatRoughnessMap.channel),iridescenceMapUv:we&&_(b.iridescenceMap.channel),iridescenceThicknessMapUv:se&&_(b.iridescenceThicknessMap.channel),sheenColorMapUv:_e&&_(b.sheenColorMap.channel),sheenRoughnessMapUv:Oe&&_(b.sheenRoughnessMap.channel),specularMapUv:Ie&&_(b.specularMap.channel),specularColorMapUv:me&&_(b.specularColorMap.channel),specularIntensityMapUv:qe&&_(b.specularIntensityMap.channel),transmissionMapUv:D&&_(b.transmissionMap.channel),thicknessMapUv:ae&&_(b.thicknessMap.channel),alphaMapUv:be&&_(b.alphaMap.channel),vertexTangents:!!q.attributes.tangent&&(K||ke),vertexColors:b.vertexColors,vertexAlphas:b.vertexColors===!0&&!!q.attributes.color&&q.attributes.color.itemSize===4,pointsUvs:z.isPoints===!0&&!!q.attributes.uv&&(Je||be),fog:!!G,useFog:b.fog===!0,fogExp2:!!G&&G.isFogExp2,flatShading:b.flatShading===!0&&b.wireframe===!1,sizeAttenuation:b.sizeAttenuation===!0,logarithmicDepthBuffer:u,reversedDepthBuffer:Me,skinning:z.isSkinnedMesh===!0,morphTargets:q.morphAttributes.position!==void 0,morphNormals:q.morphAttributes.normal!==void 0,morphColors:q.morphAttributes.color!==void 0,morphTargetsCount:Se,morphTextureStride:We,numDirLights:S.directional.length,numPointLights:S.point.length,numSpotLights:S.spot.length,numSpotLightMaps:S.spotLightMap.length,numRectAreaLights:S.rectArea.length,numHemiLights:S.hemi.length,numDirLightShadows:S.directionalShadowMap.length,numPointLightShadows:S.pointShadowMap.length,numSpotLightShadows:S.spotShadowMap.length,numSpotLightShadowsWithMaps:S.numSpotLightShadowsWithMaps,numLightProbes:S.numLightProbes,numClippingPlanes:o.numPlanes,numClipIntersection:o.numIntersection,dithering:b.dithering,shadowMapEnabled:r.shadowMap.enabled&&L.length>0,shadowMapType:r.shadowMap.type,toneMapping:Ge,decodeVideoTexture:Je&&b.map.isVideoTexture===!0&&Ze.getTransfer(b.map.colorSpace)===ot,decodeVideoTextureEmissive:ie&&b.emissiveMap.isVideoTexture===!0&&Ze.getTransfer(b.emissiveMap.colorSpace)===ot,premultipliedAlpha:b.premultipliedAlpha,doubleSided:b.side===Mn,flipSided:b.side===Wt,useDepthPacking:b.depthPacking>=0,depthPacking:b.depthPacking||0,index0AttributeName:b.index0AttributeName,extensionClipCullDistance:Re&&b.extensions.clipCullDistance===!0&&n.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(Re&&b.extensions.multiDraw===!0||Ee)&&n.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:n.has("KHR_parallel_shader_compile"),customProgramCacheKey:b.customProgramCacheKey()};return dt.vertexUv1s=l.has(1),dt.vertexUv2s=l.has(2),dt.vertexUv3s=l.has(3),l.clear(),dt}function p(b){let S=[];if(b.shaderID?S.push(b.shaderID):(S.push(b.customVertexShaderID),S.push(b.customFragmentShaderID)),b.defines!==void 0)for(let L in b.defines)S.push(L),S.push(b.defines[L]);return b.isRawShaderMaterial===!1&&(v(S,b),y(S,b),S.push(r.outputColorSpace)),S.push(b.customProgramCacheKey),S.join()}function v(b,S){b.push(S.precision),b.push(S.outputColorSpace),b.push(S.envMapMode),b.push(S.envMapCubeUVHeight),b.push(S.mapUv),b.push(S.alphaMapUv),b.push(S.lightMapUv),b.push(S.aoMapUv),b.push(S.bumpMapUv),b.push(S.normalMapUv),b.push(S.displacementMapUv),b.push(S.emissiveMapUv),b.push(S.metalnessMapUv),b.push(S.roughnessMapUv),b.push(S.anisotropyMapUv),b.push(S.clearcoatMapUv),b.push(S.clearcoatNormalMapUv),b.push(S.clearcoatRoughnessMapUv),b.push(S.iridescenceMapUv),b.push(S.iridescenceThicknessMapUv),b.push(S.sheenColorMapUv),b.push(S.sheenRoughnessMapUv),b.push(S.specularMapUv),b.push(S.specularColorMapUv),b.push(S.specularIntensityMapUv),b.push(S.transmissionMapUv),b.push(S.thicknessMapUv),b.push(S.combine),b.push(S.fogExp2),b.push(S.sizeAttenuation),b.push(S.morphTargetsCount),b.push(S.morphAttributeCount),b.push(S.numDirLights),b.push(S.numPointLights),b.push(S.numSpotLights),b.push(S.numSpotLightMaps),b.push(S.numHemiLights),b.push(S.numRectAreaLights),b.push(S.numDirLightShadows),b.push(S.numPointLightShadows),b.push(S.numSpotLightShadows),b.push(S.numSpotLightShadowsWithMaps),b.push(S.numLightProbes),b.push(S.shadowMapType),b.push(S.toneMapping),b.push(S.numClippingPlanes),b.push(S.numClipIntersection),b.push(S.depthPacking)}function y(b,S){a.disableAll(),S.supportsVertexTextures&&a.enable(0),S.instancing&&a.enable(1),S.instancingColor&&a.enable(2),S.instancingMorph&&a.enable(3),S.matcap&&a.enable(4),S.envMap&&a.enable(5),S.normalMapObjectSpace&&a.enable(6),S.normalMapTangentSpace&&a.enable(7),S.clearcoat&&a.enable(8),S.iridescence&&a.enable(9),S.alphaTest&&a.enable(10),S.vertexColors&&a.enable(11),S.vertexAlphas&&a.enable(12),S.vertexUv1s&&a.enable(13),S.vertexUv2s&&a.enable(14),S.vertexUv3s&&a.enable(15),S.vertexTangents&&a.enable(16),S.anisotropy&&a.enable(17),S.alphaHash&&a.enable(18),S.batching&&a.enable(19),S.dispersion&&a.enable(20),S.batchingColor&&a.enable(21),S.gradientMap&&a.enable(22),b.push(a.mask),a.disableAll(),S.fog&&a.enable(0),S.useFog&&a.enable(1),S.flatShading&&a.enable(2),S.logarithmicDepthBuffer&&a.enable(3),S.reversedDepthBuffer&&a.enable(4),S.skinning&&a.enable(5),S.morphTargets&&a.enable(6),S.morphNormals&&a.enable(7),S.morphColors&&a.enable(8),S.premultipliedAlpha&&a.enable(9),S.shadowMapEnabled&&a.enable(10),S.doubleSided&&a.enable(11),S.flipSided&&a.enable(12),S.useDepthPacking&&a.enable(13),S.dithering&&a.enable(14),S.transmission&&a.enable(15),S.sheen&&a.enable(16),S.opaque&&a.enable(17),S.pointsUvs&&a.enable(18),S.decodeVideoTexture&&a.enable(19),S.decodeVideoTextureEmissive&&a.enable(20),S.alphaToCoverage&&a.enable(21),b.push(a.mask)}function x(b){let S=m[b.type],L;if(S){let F=Wn[S];L=Ud.clone(F.uniforms)}else L=b.uniforms;return L}function A(b,S){let L;for(let F=0,z=h.length;F<z;F++){let G=h[F];if(G.cacheKey===S){L=G,++L.usedTimes;break}}return L===void 0&&(L=new RM(r,S,b,s),h.push(L)),L}function E(b){if(--b.usedTimes===0){let S=h.indexOf(b);h[S]=h[h.length-1],h.pop(),b.destroy()}}function C(b){c.remove(b)}function I(){c.dispose()}return{getParameters:g,getProgramCacheKey:p,getUniforms:x,acquireProgram:A,releaseProgram:E,releaseShaderCache:C,programs:h,dispose:I}}function PM(){let r=new WeakMap;function e(o){return r.has(o)}function t(o){let a=r.get(o);return a===void 0&&(a={},r.set(o,a)),a}function n(o){r.delete(o)}function i(o,a,c){r.get(o)[a]=c}function s(){r=new WeakMap}return{has:e,get:t,remove:n,update:i,dispose:s}}function LM(r,e){return r.groupOrder!==e.groupOrder?r.groupOrder-e.groupOrder:r.renderOrder!==e.renderOrder?r.renderOrder-e.renderOrder:r.material.id!==e.material.id?r.material.id-e.material.id:r.z!==e.z?r.z-e.z:r.id-e.id}function ag(r,e){return r.groupOrder!==e.groupOrder?r.groupOrder-e.groupOrder:r.renderOrder!==e.renderOrder?r.renderOrder-e.renderOrder:r.z!==e.z?e.z-r.z:r.id-e.id}function cg(){let r=[],e=0,t=[],n=[],i=[];function s(){e=0,t.length=0,n.length=0,i.length=0}function o(u,d,f,m,_,g){let p=r[e];return p===void 0?(p={id:u.id,object:u,geometry:d,material:f,groupOrder:m,renderOrder:u.renderOrder,z:_,group:g},r[e]=p):(p.id=u.id,p.object=u,p.geometry=d,p.material=f,p.groupOrder=m,p.renderOrder=u.renderOrder,p.z=_,p.group=g),e++,p}function a(u,d,f,m,_,g){let p=o(u,d,f,m,_,g);f.transmission>0?n.push(p):f.transparent===!0?i.push(p):t.push(p)}function c(u,d,f,m,_,g){let p=o(u,d,f,m,_,g);f.transmission>0?n.unshift(p):f.transparent===!0?i.unshift(p):t.unshift(p)}function l(u,d){t.length>1&&t.sort(u||LM),n.length>1&&n.sort(d||ag),i.length>1&&i.sort(d||ag)}function h(){for(let u=e,d=r.length;u<d;u++){let f=r[u];if(f.id===null)break;f.id=null,f.object=null,f.geometry=null,f.material=null,f.group=null}}return{opaque:t,transmissive:n,transparent:i,init:s,push:a,unshift:c,finish:h,sort:l}}function DM(){let r=new WeakMap;function e(n,i){let s=r.get(n),o;return s===void 0?(o=new cg,r.set(n,[o])):i>=s.length?(o=new cg,s.push(o)):o=s[i],o}function t(){r=new WeakMap}return{get:e,dispose:t}}function NM(){let r={};return{get:function(e){if(r[e.id]!==void 0)return r[e.id];let t;switch(e.type){case"DirectionalLight":t={direction:new w,color:new ue};break;case"SpotLight":t={position:new w,direction:new w,color:new ue,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new w,color:new ue,distance:0,decay:0};break;case"HemisphereLight":t={direction:new w,skyColor:new ue,groundColor:new ue};break;case"RectAreaLight":t={color:new ue,position:new w,halfWidth:new w,halfHeight:new w};break}return r[e.id]=t,t}}}function UM(){let r={};return{get:function(e){if(r[e.id]!==void 0)return r[e.id];let t;switch(e.type){case"DirectionalLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Y};break;case"SpotLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Y};break;case"PointLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Y,shadowCameraNear:1,shadowCameraFar:1e3};break}return r[e.id]=t,t}}}var FM=0;function OM(r,e){return(e.castShadow?2:0)-(r.castShadow?2:0)+(e.map?1:0)-(r.map?1:0)}function BM(r){let e=new NM,t=UM(),n={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let l=0;l<9;l++)n.probe.push(new w);let i=new w,s=new De,o=new De;function a(l){let h=0,u=0,d=0;for(let b=0;b<9;b++)n.probe[b].set(0,0,0);let f=0,m=0,_=0,g=0,p=0,v=0,y=0,x=0,A=0,E=0,C=0;l.sort(OM);for(let b=0,S=l.length;b<S;b++){let L=l[b],F=L.color,z=L.intensity,G=L.distance,q=L.shadow&&L.shadow.map?L.shadow.map.texture:null;if(L.isAmbientLight)h+=F.r*z,u+=F.g*z,d+=F.b*z;else if(L.isLightProbe){for(let W=0;W<9;W++)n.probe[W].addScaledVector(L.sh.coefficients[W],z);C++}else if(L.isDirectionalLight){let W=e.get(L);if(W.color.copy(L.color).multiplyScalar(L.intensity),L.castShadow){let ne=L.shadow,H=t.get(L);H.shadowIntensity=ne.intensity,H.shadowBias=ne.bias,H.shadowNormalBias=ne.normalBias,H.shadowRadius=ne.radius,H.shadowMapSize=ne.mapSize,n.directionalShadow[f]=H,n.directionalShadowMap[f]=q,n.directionalShadowMatrix[f]=L.shadow.matrix,v++}n.directional[f]=W,f++}else if(L.isSpotLight){let W=e.get(L);W.position.setFromMatrixPosition(L.matrixWorld),W.color.copy(F).multiplyScalar(z),W.distance=G,W.coneCos=Math.cos(L.angle),W.penumbraCos=Math.cos(L.angle*(1-L.penumbra)),W.decay=L.decay,n.spot[_]=W;let ne=L.shadow;if(L.map&&(n.spotLightMap[A]=L.map,A++,ne.updateMatrices(L),L.castShadow&&E++),n.spotLightMatrix[_]=ne.matrix,L.castShadow){let H=t.get(L);H.shadowIntensity=ne.intensity,H.shadowBias=ne.bias,H.shadowNormalBias=ne.normalBias,H.shadowRadius=ne.radius,H.shadowMapSize=ne.mapSize,n.spotShadow[_]=H,n.spotShadowMap[_]=q,x++}_++}else if(L.isRectAreaLight){let W=e.get(L);W.color.copy(F).multiplyScalar(z),W.halfWidth.set(L.width*.5,0,0),W.halfHeight.set(0,L.height*.5,0),n.rectArea[g]=W,g++}else if(L.isPointLight){let W=e.get(L);if(W.color.copy(L.color).multiplyScalar(L.intensity),W.distance=L.distance,W.decay=L.decay,L.castShadow){let ne=L.shadow,H=t.get(L);H.shadowIntensity=ne.intensity,H.shadowBias=ne.bias,H.shadowNormalBias=ne.normalBias,H.shadowRadius=ne.radius,H.shadowMapSize=ne.mapSize,H.shadowCameraNear=ne.camera.near,H.shadowCameraFar=ne.camera.far,n.pointShadow[m]=H,n.pointShadowMap[m]=q,n.pointShadowMatrix[m]=L.shadow.matrix,y++}n.point[m]=W,m++}else if(L.isHemisphereLight){let W=e.get(L);W.skyColor.copy(L.color).multiplyScalar(z),W.groundColor.copy(L.groundColor).multiplyScalar(z),n.hemi[p]=W,p++}}g>0&&(r.has("OES_texture_float_linear")===!0?(n.rectAreaLTC1=pe.LTC_FLOAT_1,n.rectAreaLTC2=pe.LTC_FLOAT_2):(n.rectAreaLTC1=pe.LTC_HALF_1,n.rectAreaLTC2=pe.LTC_HALF_2)),n.ambient[0]=h,n.ambient[1]=u,n.ambient[2]=d;let I=n.hash;(I.directionalLength!==f||I.pointLength!==m||I.spotLength!==_||I.rectAreaLength!==g||I.hemiLength!==p||I.numDirectionalShadows!==v||I.numPointShadows!==y||I.numSpotShadows!==x||I.numSpotMaps!==A||I.numLightProbes!==C)&&(n.directional.length=f,n.spot.length=_,n.rectArea.length=g,n.point.length=m,n.hemi.length=p,n.directionalShadow.length=v,n.directionalShadowMap.length=v,n.pointShadow.length=y,n.pointShadowMap.length=y,n.spotShadow.length=x,n.spotShadowMap.length=x,n.directionalShadowMatrix.length=v,n.pointShadowMatrix.length=y,n.spotLightMatrix.length=x+A-E,n.spotLightMap.length=A,n.numSpotLightShadowsWithMaps=E,n.numLightProbes=C,I.directionalLength=f,I.pointLength=m,I.spotLength=_,I.rectAreaLength=g,I.hemiLength=p,I.numDirectionalShadows=v,I.numPointShadows=y,I.numSpotShadows=x,I.numSpotMaps=A,I.numLightProbes=C,n.version=FM++)}function c(l,h){let u=0,d=0,f=0,m=0,_=0,g=h.matrixWorldInverse;for(let p=0,v=l.length;p<v;p++){let y=l[p];if(y.isDirectionalLight){let x=n.directional[u];x.direction.setFromMatrixPosition(y.matrixWorld),i.setFromMatrixPosition(y.target.matrixWorld),x.direction.sub(i),x.direction.transformDirection(g),u++}else if(y.isSpotLight){let x=n.spot[f];x.position.setFromMatrixPosition(y.matrixWorld),x.position.applyMatrix4(g),x.direction.setFromMatrixPosition(y.matrixWorld),i.setFromMatrixPosition(y.target.matrixWorld),x.direction.sub(i),x.direction.transformDirection(g),f++}else if(y.isRectAreaLight){let x=n.rectArea[m];x.position.setFromMatrixPosition(y.matrixWorld),x.position.applyMatrix4(g),o.identity(),s.copy(y.matrixWorld),s.premultiply(g),o.extractRotation(s),x.halfWidth.set(y.width*.5,0,0),x.halfHeight.set(0,y.height*.5,0),x.halfWidth.applyMatrix4(o),x.halfHeight.applyMatrix4(o),m++}else if(y.isPointLight){let x=n.point[d];x.position.setFromMatrixPosition(y.matrixWorld),x.position.applyMatrix4(g),d++}else if(y.isHemisphereLight){let x=n.hemi[_];x.direction.setFromMatrixPosition(y.matrixWorld),x.direction.transformDirection(g),_++}}}return{setup:a,setupView:c,state:n}}function lg(r){let e=new BM(r),t=[],n=[];function i(h){l.camera=h,t.length=0,n.length=0}function s(h){t.push(h)}function o(h){n.push(h)}function a(){e.setup(t)}function c(h){e.setupView(t,h)}let l={lightsArray:t,shadowsArray:n,camera:null,lights:e,transmissionRenderTarget:{}};return{init:i,state:l,setupLights:a,setupLightsView:c,pushLight:s,pushShadow:o}}function zM(r){let e=new WeakMap;function t(i,s=0){let o=e.get(i),a;return o===void 0?(a=new lg(r),e.set(i,[a])):s>=o.length?(a=new lg(r),o.push(a)):a=o[s],a}function n(){e=new WeakMap}return{get:t,dispose:n}}var kM=`void main() {+ gl_Position = vec4( position, 1.0 );+}`,VM=`uniform sampler2D shadow_pass;+uniform vec2 resolution;+uniform float radius;+#include <packing>+void main() {+ const float samples = float( VSM_SAMPLES );+ float mean = 0.0;+ float squared_mean = 0.0;+ float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );+ float uvStart = samples <= 1.0 ? 0.0 : - 1.0;+ for ( float i = 0.0; i < samples; i ++ ) {+ float uvOffset = uvStart + i * uvStride;+ #ifdef HORIZONTAL_PASS+ vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );+ mean += distribution.x;+ squared_mean += distribution.y * distribution.y + distribution.x * distribution.x;+ #else+ float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );+ mean += depth;+ squared_mean += depth * depth;+ #endif+ }+ mean = mean / samples;+ squared_mean = squared_mean / samples;+ float std_dev = sqrt( squared_mean - mean * mean );+ gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );+}`;function HM(r,e,t){let n=new _i,i=new Y,s=new Y,o=new tt,a=new Nr({depthPacking:Sd}),c=new Ur,l={},h=t.maxTextureSize,u={[An]:Wt,[Wt]:An,[Mn]:Mn},d=new on({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new Y},radius:{value:4}},vertexShader:kM,fragmentShader:VM}),f=d.clone();f.defines.HORIZONTAL_PASS=1;let m=new ze;m.setAttribute("position",new je(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));let _=new pt(m,d),g=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=xh;let p=this.type;this.render=function(E,C,I){if(g.enabled===!1||g.autoUpdate===!1&&g.needsUpdate===!1||E.length===0)return;let b=r.getRenderTarget(),S=r.getActiveCubeFace(),L=r.getActiveMipmapLevel(),F=r.state;F.setBlending(ti),F.buffers.depth.getReversed()===!0?F.buffers.color.setClear(0,0,0,0):F.buffers.color.setClear(1,1,1,1),F.buffers.depth.setTest(!0),F.setScissorTest(!1);let z=p!==Gn&&this.type===Gn,G=p===Gn&&this.type!==Gn;for(let q=0,W=E.length;q<W;q++){let ne=E[q],H=ne.shadow;if(H===void 0){console.warn("THREE.WebGLShadowMap:",ne,"has no shadow.");continue}if(H.autoUpdate===!1&&H.needsUpdate===!1)continue;i.copy(H.mapSize);let de=H.getFrameExtents();if(i.multiply(de),s.copy(H.mapSize),(i.x>h||i.y>h)&&(i.x>h&&(s.x=Math.floor(h/de.x),i.x=s.x*de.x,H.mapSize.x=s.x),i.y>h&&(s.y=Math.floor(h/de.y),i.y=s.y*de.y,H.mapSize.y=s.y)),H.map===null||z===!0||G===!0){let Se=this.type!==Gn?{minFilter:Ct,magFilter:Ct}:{};H.map!==null&&H.map.dispose(),H.map=new yn(i.x,i.y,Se),H.map.texture.name=ne.name+".shadowMap",H.camera.updateProjectionMatrix()}r.setRenderTarget(H.map),r.clear();let xe=H.getViewportCount();for(let Se=0;Se<xe;Se++){let We=H.getViewport(Se);o.set(s.x*We.x,s.y*We.y,s.x*We.z,s.y*We.w),F.viewport(o),H.updateMatrices(ne,Se),n=H.getFrustum(),x(C,I,H.camera,ne,this.type)}H.isPointLightShadow!==!0&&this.type===Gn&&v(H,I),H.needsUpdate=!1}p=this.type,g.needsUpdate=!1,r.setRenderTarget(b,S,L)};function v(E,C){let I=e.update(_);d.defines.VSM_SAMPLES!==E.blurSamples&&(d.defines.VSM_SAMPLES=E.blurSamples,f.defines.VSM_SAMPLES=E.blurSamples,d.needsUpdate=!0,f.needsUpdate=!0),E.mapPass===null&&(E.mapPass=new yn(i.x,i.y)),d.uniforms.shadow_pass.value=E.map.texture,d.uniforms.resolution.value=E.mapSize,d.uniforms.radius.value=E.radius,r.setRenderTarget(E.mapPass),r.clear(),r.renderBufferDirect(C,null,I,d,_,null),f.uniforms.shadow_pass.value=E.mapPass.texture,f.uniforms.resolution.value=E.mapSize,f.uniforms.radius.value=E.radius,r.setRenderTarget(E.map),r.clear(),r.renderBufferDirect(C,null,I,f,_,null)}function y(E,C,I,b){let S=null,L=I.isPointLight===!0?E.customDistanceMaterial:E.customDepthMaterial;if(L!==void 0)S=L;else if(S=I.isPointLight===!0?c:a,r.localClippingEnabled&&C.clipShadows===!0&&Array.isArray(C.clippingPlanes)&&C.clippingPlanes.length!==0||C.displacementMap&&C.displacementScale!==0||C.alphaMap&&C.alphaTest>0||C.map&&C.alphaTest>0||C.alphaToCoverage===!0){let F=S.uuid,z=C.uuid,G=l[F];G===void 0&&(G={},l[F]=G);let q=G[z];q===void 0&&(q=S.clone(),G[z]=q,C.addEventListener("dispose",A)),S=q}if(S.visible=C.visible,S.wireframe=C.wireframe,b===Gn?S.side=C.shadowSide!==null?C.shadowSide:C.side:S.side=C.shadowSide!==null?C.shadowSide:u[C.side],S.alphaMap=C.alphaMap,S.alphaTest=C.alphaToCoverage===!0?.5:C.alphaTest,S.map=C.map,S.clipShadows=C.clipShadows,S.clippingPlanes=C.clippingPlanes,S.clipIntersection=C.clipIntersection,S.displacementMap=C.displacementMap,S.displacementScale=C.displacementScale,S.displacementBias=C.displacementBias,S.wireframeLinewidth=C.wireframeLinewidth,S.linewidth=C.linewidth,I.isPointLight===!0&&S.isMeshDistanceMaterial===!0){let F=r.properties.get(S);F.light=I}return S}function x(E,C,I,b,S){if(E.visible===!1)return;if(E.layers.test(C.layers)&&(E.isMesh||E.isLine||E.isPoints)&&(E.castShadow||E.receiveShadow&&S===Gn)&&(!E.frustumCulled||n.intersectsObject(E))){E.modelViewMatrix.multiplyMatrices(I.matrixWorldInverse,E.matrixWorld);let z=e.update(E),G=E.material;if(Array.isArray(G)){let q=z.groups;for(let W=0,ne=q.length;W<ne;W++){let H=q[W],de=G[H.materialIndex];if(de&&de.visible){let xe=y(E,de,b,S);E.onBeforeShadow(r,E,C,I,z,xe,H),r.renderBufferDirect(I,null,z,xe,E,H),E.onAfterShadow(r,E,C,I,z,xe,H)}}}else if(G.visible){let q=y(E,G,b,S);E.onBeforeShadow(r,E,C,I,z,q,null),r.renderBufferDirect(I,null,z,q,E,null),E.onAfterShadow(r,E,C,I,z,q,null)}}let F=E.children;for(let z=0,G=F.length;z<G;z++)x(F[z],C,I,b,S)}function A(E){E.target.removeEventListener("dispose",A);for(let I in l){let b=l[I],S=E.target.uuid;S in b&&(b[S].dispose(),delete b[S])}}}var GM={[Pa]:La,[Da]:Fa,[Na]:Oa,[Oi]:Ua,[La]:Pa,[Fa]:Da,[Oa]:Na,[Ua]:Oi};function WM(r,e){function t(){let D=!1,ae=new tt,fe=null,be=new tt(0,0,0,0);return{setMask:function(re){fe!==re&&!D&&(r.colorMask(re,re,re,re),fe=re)},setLocked:function(re){D=re},setClear:function(re,j,Re,Ge,dt){dt===!0&&(re*=Ge,j*=Ge,Re*=Ge),ae.set(re,j,Re,Ge),be.equals(ae)===!1&&(r.clearColor(re,j,Re,Ge),be.copy(ae))},reset:function(){D=!1,fe=null,be.set(-1,0,0,0)}}}function n(){let D=!1,ae=!1,fe=null,be=null,re=null;return{setReversed:function(j){if(ae!==j){let Re=e.get("EXT_clip_control");j?Re.clipControlEXT(Re.LOWER_LEFT_EXT,Re.ZERO_TO_ONE_EXT):Re.clipControlEXT(Re.LOWER_LEFT_EXT,Re.NEGATIVE_ONE_TO_ONE_EXT),ae=j;let Ge=re;re=null,this.setClear(Ge)}},getReversed:function(){return ae},setTest:function(j){j?te(r.DEPTH_TEST):Me(r.DEPTH_TEST)},setMask:function(j){fe!==j&&!D&&(r.depthMask(j),fe=j)},setFunc:function(j){if(ae&&(j=GM[j]),be!==j){switch(j){case Pa:r.depthFunc(r.NEVER);break;case La:r.depthFunc(r.ALWAYS);break;case Da:r.depthFunc(r.LESS);break;case Oi:r.depthFunc(r.LEQUAL);break;case Na:r.depthFunc(r.EQUAL);break;case Ua:r.depthFunc(r.GEQUAL);break;case Fa:r.depthFunc(r.GREATER);break;case Oa:r.depthFunc(r.NOTEQUAL);break;default:r.depthFunc(r.LEQUAL)}be=j}},setLocked:function(j){D=j},setClear:function(j){re!==j&&(ae&&(j=1-j),r.clearDepth(j),re=j)},reset:function(){D=!1,fe=null,be=null,re=null,ae=!1}}}function i(){let D=!1,ae=null,fe=null,be=null,re=null,j=null,Re=null,Ge=null,dt=null;return{setTest:function(rt){D||(rt?te(r.STENCIL_TEST):Me(r.STENCIL_TEST))},setMask:function(rt){ae!==rt&&!D&&(r.stencilMask(rt),ae=rt)},setFunc:function(rt,ai,Xn){(fe!==rt||be!==ai||re!==Xn)&&(r.stencilFunc(rt,ai,Xn),fe=rt,be=ai,re=Xn)},setOp:function(rt,ai,Xn){(j!==rt||Re!==ai||Ge!==Xn)&&(r.stencilOp(rt,ai,Xn),j=rt,Re=ai,Ge=Xn)},setLocked:function(rt){D=rt},setClear:function(rt){dt!==rt&&(r.clearStencil(rt),dt=rt)},reset:function(){D=!1,ae=null,fe=null,be=null,re=null,j=null,Re=null,Ge=null,dt=null}}}let s=new t,o=new n,a=new i,c=new WeakMap,l=new WeakMap,h={},u={},d=new WeakMap,f=[],m=null,_=!1,g=null,p=null,v=null,y=null,x=null,A=null,E=null,C=new ue(0,0,0),I=0,b=!1,S=null,L=null,F=null,z=null,G=null,q=r.getParameter(r.MAX_COMBINED_TEXTURE_IMAGE_UNITS),W=!1,ne=0,H=r.getParameter(r.VERSION);H.indexOf("WebGL")!==-1?(ne=parseFloat(/^WebGL (\d)/.exec(H)[1]),W=ne>=1):H.indexOf("OpenGL ES")!==-1&&(ne=parseFloat(/^OpenGL ES (\d)/.exec(H)[1]),W=ne>=2);let de=null,xe={},Se=r.getParameter(r.SCISSOR_BOX),We=r.getParameter(r.VIEWPORT),et=new tt().fromArray(Se),at=new tt().fromArray(We);function nt(D,ae,fe,be){let re=new Uint8Array(4),j=r.createTexture();r.bindTexture(D,j),r.texParameteri(D,r.TEXTURE_MIN_FILTER,r.NEAREST),r.texParameteri(D,r.TEXTURE_MAG_FILTER,r.NEAREST);for(let Re=0;Re<fe;Re++)D===r.TEXTURE_3D||D===r.TEXTURE_2D_ARRAY?r.texImage3D(ae,0,r.RGBA,1,1,be,0,r.RGBA,r.UNSIGNED_BYTE,re):r.texImage2D(ae+Re,0,r.RGBA,1,1,0,r.RGBA,r.UNSIGNED_BYTE,re);return j}let Z={};Z[r.TEXTURE_2D]=nt(r.TEXTURE_2D,r.TEXTURE_2D,1),Z[r.TEXTURE_CUBE_MAP]=nt(r.TEXTURE_CUBE_MAP,r.TEXTURE_CUBE_MAP_POSITIVE_X,6),Z[r.TEXTURE_2D_ARRAY]=nt(r.TEXTURE_2D_ARRAY,r.TEXTURE_2D_ARRAY,1,1),Z[r.TEXTURE_3D]=nt(r.TEXTURE_3D,r.TEXTURE_3D,1,1),s.setClear(0,0,0,1),o.setClear(1),a.setClear(0),te(r.DEPTH_TEST),o.setFunc(Oi),J(!1),K(_h),te(r.CULL_FACE),ee(ti);function te(D){h[D]!==!0&&(r.enable(D),h[D]=!0)}function Me(D){h[D]!==!1&&(r.disable(D),h[D]=!1)}function Pe(D,ae){return u[D]!==ae?(r.bindFramebuffer(D,ae),u[D]=ae,D===r.DRAW_FRAMEBUFFER&&(u[r.FRAMEBUFFER]=ae),D===r.FRAMEBUFFER&&(u[r.DRAW_FRAMEBUFFER]=ae),!0):!1}function Ee(D,ae){let fe=f,be=!1;if(D){fe=d.get(ae),fe===void 0&&(fe=[],d.set(ae,fe));let re=D.textures;if(fe.length!==re.length||fe[0]!==r.COLOR_ATTACHMENT0){for(let j=0,Re=re.length;j<Re;j++)fe[j]=r.COLOR_ATTACHMENT0+j;fe.length=re.length,be=!0}}else fe[0]!==r.BACK&&(fe[0]=r.BACK,be=!0);be&&r.drawBuffers(fe)}function Je(D){return m!==D?(r.useProgram(D),m=D,!0):!1}let ut={[gi]:r.FUNC_ADD,[Xu]:r.FUNC_SUBTRACT,[qu]:r.FUNC_REVERSE_SUBTRACT};ut[Yu]=r.MIN,ut[Zu]=r.MAX;let P={[Ku]:r.ZERO,[Ju]:r.ONE,[$u]:r.SRC_COLOR,[Eo]:r.SRC_ALPHA,[id]:r.SRC_ALPHA_SATURATE,[td]:r.DST_COLOR,[Qu]:r.DST_ALPHA,[ju]:r.ONE_MINUS_SRC_COLOR,[Ao]:r.ONE_MINUS_SRC_ALPHA,[nd]:r.ONE_MINUS_DST_COLOR,[ed]:r.ONE_MINUS_DST_ALPHA,[sd]:r.CONSTANT_COLOR,[rd]:r.ONE_MINUS_CONSTANT_COLOR,[od]:r.CONSTANT_ALPHA,[ad]:r.ONE_MINUS_CONSTANT_ALPHA};function ee(D,ae,fe,be,re,j,Re,Ge,dt,rt){if(D===ti){_===!0&&(Me(r.BLEND),_=!1);return}if(_===!1&&(te(r.BLEND),_=!0),D!==Wu){if(D!==g||rt!==b){if((p!==gi||x!==gi)&&(r.blendEquation(r.FUNC_ADD),p=gi,x=gi),rt)switch(D){case Fi:r.blendFuncSeparate(r.ONE,r.ONE_MINUS_SRC_ALPHA,r.ONE,r.ONE_MINUS_SRC_ALPHA);break;case yh:r.blendFunc(r.ONE,r.ONE);break;case vh:r.blendFuncSeparate(r.ZERO,r.ONE_MINUS_SRC_COLOR,r.ZERO,r.ONE);break;case Mh:r.blendFuncSeparate(r.DST_COLOR,r.ONE_MINUS_SRC_ALPHA,r.ZERO,r.ONE);break;default:console.error("THREE.WebGLState: Invalid blending: ",D);break}else switch(D){case Fi:r.blendFuncSeparate(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA,r.ONE,r.ONE_MINUS_SRC_ALPHA);break;case yh:r.blendFuncSeparate(r.SRC_ALPHA,r.ONE,r.ONE,r.ONE);break;case vh:console.error("THREE.WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case Mh:console.error("THREE.WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:console.error("THREE.WebGLState: Invalid blending: ",D);break}v=null,y=null,A=null,E=null,C.set(0,0,0),I=0,g=D,b=rt}return}re=re||ae,j=j||fe,Re=Re||be,(ae!==p||re!==x)&&(r.blendEquationSeparate(ut[ae],ut[re]),p=ae,x=re),(fe!==v||be!==y||j!==A||Re!==E)&&(r.blendFuncSeparate(P[fe],P[be],P[j],P[Re]),v=fe,y=be,A=j,E=Re),(Ge.equals(C)===!1||dt!==I)&&(r.blendColor(Ge.r,Ge.g,Ge.b,dt),C.copy(Ge),I=dt),g=D,b=!1}function $(D,ae){D.side===Mn?Me(r.CULL_FACE):te(r.CULL_FACE);let fe=D.side===Wt;ae&&(fe=!fe),J(fe),D.blending===Fi&&D.transparent===!1?ee(ti):ee(D.blending,D.blendEquation,D.blendSrc,D.blendDst,D.blendEquationAlpha,D.blendSrcAlpha,D.blendDstAlpha,D.blendColor,D.blendAlpha,D.premultipliedAlpha),o.setFunc(D.depthFunc),o.setTest(D.depthTest),o.setMask(D.depthWrite),s.setMask(D.colorWrite);let be=D.stencilWrite;a.setTest(be),be&&(a.setMask(D.stencilWriteMask),a.setFunc(D.stencilFunc,D.stencilRef,D.stencilFuncMask),a.setOp(D.stencilFail,D.stencilZFail,D.stencilZPass)),ie(D.polygonOffset,D.polygonOffsetFactor,D.polygonOffsetUnits),D.alphaToCoverage===!0?te(r.SAMPLE_ALPHA_TO_COVERAGE):Me(r.SAMPLE_ALPHA_TO_COVERAGE)}function J(D){S!==D&&(D?r.frontFace(r.CW):r.frontFace(r.CCW),S=D)}function K(D){D!==Vu?(te(r.CULL_FACE),D!==L&&(D===_h?r.cullFace(r.BACK):D===Hu?r.cullFace(r.FRONT):r.cullFace(r.FRONT_AND_BACK))):Me(r.CULL_FACE),L=D}function le(D){D!==F&&(W&&r.lineWidth(D),F=D)}function ie(D,ae,fe){D?(te(r.POLYGON_OFFSET_FILL),(z!==ae||G!==fe)&&(r.polygonOffset(ae,fe),z=ae,G=fe)):Me(r.POLYGON_OFFSET_FILL)}function he(D){D?te(r.SCISSOR_TEST):Me(r.SCISSOR_TEST)}function He(D){D===void 0&&(D=r.TEXTURE0+q-1),de!==D&&(r.activeTexture(D),de=D)}function ke(D,ae,fe){fe===void 0&&(de===null?fe=r.TEXTURE0+q-1:fe=de);let be=xe[fe];be===void 0&&(be={type:void 0,texture:void 0},xe[fe]=be),(be.type!==D||be.texture!==ae)&&(de!==fe&&(r.activeTexture(fe),de=fe),r.bindTexture(D,ae||Z[D]),be.type=D,be.texture=ae)}function R(){let D=xe[de];D!==void 0&&D.type!==void 0&&(r.bindTexture(D.type,null),D.type=void 0,D.texture=void 0)}function M(){try{r.compressedTexImage2D(...arguments)}catch(D){console.error("THREE.WebGLState:",D)}}function O(){try{r.compressedTexImage3D(...arguments)}catch(D){console.error("THREE.WebGLState:",D)}}function V(){try{r.texSubImage2D(...arguments)}catch(D){console.error("THREE.WebGLState:",D)}}function Q(){try{r.texSubImage3D(...arguments)}catch(D){console.error("THREE.WebGLState:",D)}}function X(){try{r.compressedTexSubImage2D(...arguments)}catch(D){console.error("THREE.WebGLState:",D)}}function Ce(){try{r.compressedTexSubImage3D(...arguments)}catch(D){console.error("THREE.WebGLState:",D)}}function ce(){try{r.texStorage2D(...arguments)}catch(D){console.error("THREE.WebGLState:",D)}}function Ae(){try{r.texStorage3D(...arguments)}catch(D){console.error("THREE.WebGLState:",D)}}function we(){try{r.texImage2D(...arguments)}catch(D){console.error("THREE.WebGLState:",D)}}function se(){try{r.texImage3D(...arguments)}catch(D){console.error("THREE.WebGLState:",D)}}function _e(D){et.equals(D)===!1&&(r.scissor(D.x,D.y,D.z,D.w),et.copy(D))}function Oe(D){at.equals(D)===!1&&(r.viewport(D.x,D.y,D.z,D.w),at.copy(D))}function Ie(D,ae){let fe=l.get(ae);fe===void 0&&(fe=new WeakMap,l.set(ae,fe));let be=fe.get(D);be===void 0&&(be=r.getUniformBlockIndex(ae,D.name),fe.set(D,be))}function me(D,ae){let be=l.get(ae).get(D);c.get(ae)!==be&&(r.uniformBlockBinding(ae,be,D.__bindingPointIndex),c.set(ae,be))}function qe(){r.disable(r.BLEND),r.disable(r.CULL_FACE),r.disable(r.DEPTH_TEST),r.disable(r.POLYGON_OFFSET_FILL),r.disable(r.SCISSOR_TEST),r.disable(r.STENCIL_TEST),r.disable(r.SAMPLE_ALPHA_TO_COVERAGE),r.blendEquation(r.FUNC_ADD),r.blendFunc(r.ONE,r.ZERO),r.blendFuncSeparate(r.ONE,r.ZERO,r.ONE,r.ZERO),r.blendColor(0,0,0,0),r.colorMask(!0,!0,!0,!0),r.clearColor(0,0,0,0),r.depthMask(!0),r.depthFunc(r.LESS),o.setReversed(!1),r.clearDepth(1),r.stencilMask(4294967295),r.stencilFunc(r.ALWAYS,0,4294967295),r.stencilOp(r.KEEP,r.KEEP,r.KEEP),r.clearStencil(0),r.cullFace(r.BACK),r.frontFace(r.CCW),r.polygonOffset(0,0),r.activeTexture(r.TEXTURE0),r.bindFramebuffer(r.FRAMEBUFFER,null),r.bindFramebuffer(r.DRAW_FRAMEBUFFER,null),r.bindFramebuffer(r.READ_FRAMEBUFFER,null),r.useProgram(null),r.lineWidth(1),r.scissor(0,0,r.canvas.width,r.canvas.height),r.viewport(0,0,r.canvas.width,r.canvas.height),h={},de=null,xe={},u={},d=new WeakMap,f=[],m=null,_=!1,g=null,p=null,v=null,y=null,x=null,A=null,E=null,C=new ue(0,0,0),I=0,b=!1,S=null,L=null,F=null,z=null,G=null,et.set(0,0,r.canvas.width,r.canvas.height),at.set(0,0,r.canvas.width,r.canvas.height),s.reset(),o.reset(),a.reset()}return{buffers:{color:s,depth:o,stencil:a},enable:te,disable:Me,bindFramebuffer:Pe,drawBuffers:Ee,useProgram:Je,setBlending:ee,setMaterial:$,setFlipSided:J,setCullFace:K,setLineWidth:le,setPolygonOffset:ie,setScissorTest:he,activeTexture:He,bindTexture:ke,unbindTexture:R,compressedTexImage2D:M,compressedTexImage3D:O,texImage2D:we,texImage3D:se,updateUBOMapping:Ie,uniformBlockBinding:me,texStorage2D:ce,texStorage3D:Ae,texSubImage2D:V,texSubImage3D:Q,compressedTexSubImage2D:X,compressedTexSubImage3D:Ce,scissor:_e,viewport:Oe,reset:qe}}function XM(r,e,t,n,i,s,o){let a=e.has("WEBGL_multisampled_render_to_texture")?e.get("WEBGL_multisampled_render_to_texture"):null,c=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),l=new Y,h=new WeakMap,u,d=new WeakMap,f=!1;try{f=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function m(R,M){return f?new OffscreenCanvas(R,M):gr("canvas")}function _(R,M,O){let V=1,Q=ke(R);if((Q.width>O||Q.height>O)&&(V=O/Math.max(Q.width,Q.height)),V<1)if(typeof HTMLImageElement<"u"&&R instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&R instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&R instanceof ImageBitmap||typeof VideoFrame<"u"&&R instanceof VideoFrame){let X=Math.floor(V*Q.width),Ce=Math.floor(V*Q.height);u===void 0&&(u=m(X,Ce));let ce=M?m(X,Ce):u;return ce.width=X,ce.height=Ce,ce.getContext("2d").drawImage(R,0,0,X,Ce),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+Q.width+"x"+Q.height+") to ("+X+"x"+Ce+")."),ce}else return"data"in R&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+Q.width+"x"+Q.height+")."),R;return R}function g(R){return R.generateMipmaps}function p(R){r.generateMipmap(R)}function v(R){return R.isWebGLCubeRenderTarget?r.TEXTURE_CUBE_MAP:R.isWebGL3DRenderTarget?r.TEXTURE_3D:R.isWebGLArrayRenderTarget||R.isCompressedArrayTexture?r.TEXTURE_2D_ARRAY:r.TEXTURE_2D}function y(R,M,O,V,Q=!1){if(R!==null){if(r[R]!==void 0)return r[R];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+R+"'")}let X=M;if(M===r.RED&&(O===r.FLOAT&&(X=r.R32F),O===r.HALF_FLOAT&&(X=r.R16F),O===r.UNSIGNED_BYTE&&(X=r.R8)),M===r.RED_INTEGER&&(O===r.UNSIGNED_BYTE&&(X=r.R8UI),O===r.UNSIGNED_SHORT&&(X=r.R16UI),O===r.UNSIGNED_INT&&(X=r.R32UI),O===r.BYTE&&(X=r.R8I),O===r.SHORT&&(X=r.R16I),O===r.INT&&(X=r.R32I)),M===r.RG&&(O===r.FLOAT&&(X=r.RG32F),O===r.HALF_FLOAT&&(X=r.RG16F),O===r.UNSIGNED_BYTE&&(X=r.RG8)),M===r.RG_INTEGER&&(O===r.UNSIGNED_BYTE&&(X=r.RG8UI),O===r.UNSIGNED_SHORT&&(X=r.RG16UI),O===r.UNSIGNED_INT&&(X=r.RG32UI),O===r.BYTE&&(X=r.RG8I),O===r.SHORT&&(X=r.RG16I),O===r.INT&&(X=r.RG32I)),M===r.RGB_INTEGER&&(O===r.UNSIGNED_BYTE&&(X=r.RGB8UI),O===r.UNSIGNED_SHORT&&(X=r.RGB16UI),O===r.UNSIGNED_INT&&(X=r.RGB32UI),O===r.BYTE&&(X=r.RGB8I),O===r.SHORT&&(X=r.RGB16I),O===r.INT&&(X=r.RGB32I)),M===r.RGBA_INTEGER&&(O===r.UNSIGNED_BYTE&&(X=r.RGBA8UI),O===r.UNSIGNED_SHORT&&(X=r.RGBA16UI),O===r.UNSIGNED_INT&&(X=r.RGBA32UI),O===r.BYTE&&(X=r.RGBA8I),O===r.SHORT&&(X=r.RGBA16I),O===r.INT&&(X=r.RGBA32I)),M===r.RGB&&(O===r.UNSIGNED_INT_5_9_9_9_REV&&(X=r.RGB9_E5),O===r.UNSIGNED_INT_10F_11F_11F_REV&&(X=r.R11F_G11F_B10F)),M===r.RGBA){let Ce=Q?pr:Ze.getTransfer(V);O===r.FLOAT&&(X=r.RGBA32F),O===r.HALF_FLOAT&&(X=r.RGBA16F),O===r.UNSIGNED_BYTE&&(X=Ce===ot?r.SRGB8_ALPHA8:r.RGBA8),O===r.UNSIGNED_SHORT_4_4_4_4&&(X=r.RGBA4),O===r.UNSIGNED_SHORT_5_5_5_1&&(X=r.RGB5_A1)}return(X===r.R16F||X===r.R32F||X===r.RG16F||X===r.RG32F||X===r.RGBA16F||X===r.RGBA32F)&&e.get("EXT_color_buffer_float"),X}function x(R,M){let O;return R?M===null||M===si||M===Us?O=r.DEPTH24_STENCIL8:M===Jt?O=r.DEPTH32F_STENCIL8:M===Ds&&(O=r.DEPTH24_STENCIL8,console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):M===null||M===si||M===Us?O=r.DEPTH_COMPONENT24:M===Jt?O=r.DEPTH_COMPONENT32F:M===Ds&&(O=r.DEPTH_COMPONENT16),O}function A(R,M){return g(R)===!0||R.isFramebufferTexture&&R.minFilter!==Ct&&R.minFilter!==mt?Math.log2(Math.max(M.width,M.height))+1:R.mipmaps!==void 0&&R.mipmaps.length>0?R.mipmaps.length:R.isCompressedTexture&&Array.isArray(R.image)?M.mipmaps.length:1}function E(R){let M=R.target;M.removeEventListener("dispose",E),I(M),M.isVideoTexture&&h.delete(M)}function C(R){let M=R.target;M.removeEventListener("dispose",C),S(M)}function I(R){let M=n.get(R);if(M.__webglInit===void 0)return;let O=R.source,V=d.get(O);if(V){let Q=V[M.__cacheKey];Q.usedTimes--,Q.usedTimes===0&&b(R),Object.keys(V).length===0&&d.delete(O)}n.remove(R)}function b(R){let M=n.get(R);r.deleteTexture(M.__webglTexture);let O=R.source,V=d.get(O);delete V[M.__cacheKey],o.memory.textures--}function S(R){let M=n.get(R);if(R.depthTexture&&(R.depthTexture.dispose(),n.remove(R.depthTexture)),R.isWebGLCubeRenderTarget)for(let V=0;V<6;V++){if(Array.isArray(M.__webglFramebuffer[V]))for(let Q=0;Q<M.__webglFramebuffer[V].length;Q++)r.deleteFramebuffer(M.__webglFramebuffer[V][Q]);else r.deleteFramebuffer(M.__webglFramebuffer[V]);M.__webglDepthbuffer&&r.deleteRenderbuffer(M.__webglDepthbuffer[V])}else{if(Array.isArray(M.__webglFramebuffer))for(let V=0;V<M.__webglFramebuffer.length;V++)r.deleteFramebuffer(M.__webglFramebuffer[V]);else r.deleteFramebuffer(M.__webglFramebuffer);if(M.__webglDepthbuffer&&r.deleteRenderbuffer(M.__webglDepthbuffer),M.__webglMultisampledFramebuffer&&r.deleteFramebuffer(M.__webglMultisampledFramebuffer),M.__webglColorRenderbuffer)for(let V=0;V<M.__webglColorRenderbuffer.length;V++)M.__webglColorRenderbuffer[V]&&r.deleteRenderbuffer(M.__webglColorRenderbuffer[V]);M.__webglDepthRenderbuffer&&r.deleteRenderbuffer(M.__webglDepthRenderbuffer)}let O=R.textures;for(let V=0,Q=O.length;V<Q;V++){let X=n.get(O[V]);X.__webglTexture&&(r.deleteTexture(X.__webglTexture),o.memory.textures--),n.remove(O[V])}n.remove(R)}let L=0;function F(){L=0}function z(){let R=L;return R>=i.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+R+" texture units while this GPU supports only "+i.maxTextures),L+=1,R}function G(R){let M=[];return M.push(R.wrapS),M.push(R.wrapT),M.push(R.wrapR||0),M.push(R.magFilter),M.push(R.minFilter),M.push(R.anisotropy),M.push(R.internalFormat),M.push(R.format),M.push(R.type),M.push(R.generateMipmaps),M.push(R.premultiplyAlpha),M.push(R.flipY),M.push(R.unpackAlignment),M.push(R.colorSpace),M.join()}function q(R,M){let O=n.get(R);if(R.isVideoTexture&&he(R),R.isRenderTargetTexture===!1&&R.isExternalTexture!==!0&&R.version>0&&O.__version!==R.version){let V=R.image;if(V===null)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else if(V.complete===!1)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");else{Z(O,R,M);return}}else R.isExternalTexture&&(O.__webglTexture=R.sourceTexture?R.sourceTexture:null);t.bindTexture(r.TEXTURE_2D,O.__webglTexture,r.TEXTURE0+M)}function W(R,M){let O=n.get(R);if(R.isRenderTargetTexture===!1&&R.version>0&&O.__version!==R.version){Z(O,R,M);return}t.bindTexture(r.TEXTURE_2D_ARRAY,O.__webglTexture,r.TEXTURE0+M)}function ne(R,M){let O=n.get(R);if(R.isRenderTargetTexture===!1&&R.version>0&&O.__version!==R.version){Z(O,R,M);return}t.bindTexture(r.TEXTURE_3D,O.__webglTexture,r.TEXTURE0+M)}function H(R,M){let O=n.get(R);if(R.version>0&&O.__version!==R.version){te(O,R,M);return}t.bindTexture(r.TEXTURE_CUBE_MAP,O.__webglTexture,r.TEXTURE0+M)}let de={[Kn]:r.REPEAT,[Kt]:r.CLAMP_TO_EDGE,[Bi]:r.MIRRORED_REPEAT},xe={[Ct]:r.NEAREST,[qr]:r.NEAREST_MIPMAP_NEAREST,[Ti]:r.NEAREST_MIPMAP_LINEAR,[mt]:r.LINEAR,[qi]:r.LINEAR_MIPMAP_NEAREST,[cn]:r.LINEAR_MIPMAP_LINEAR},Se={[Td]:r.NEVER,[Id]:r.ALWAYS,[Ed]:r.LESS,[Ph]:r.LEQUAL,[Ad]:r.EQUAL,[Cd]:r.GEQUAL,[wd]:r.GREATER,[Rd]:r.NOTEQUAL};function We(R,M){if(M.type===Jt&&e.has("OES_texture_float_linear")===!1&&(M.magFilter===mt||M.magFilter===qi||M.magFilter===Ti||M.magFilter===cn||M.minFilter===mt||M.minFilter===qi||M.minFilter===Ti||M.minFilter===cn)&&console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),r.texParameteri(R,r.TEXTURE_WRAP_S,de[M.wrapS]),r.texParameteri(R,r.TEXTURE_WRAP_T,de[M.wrapT]),(R===r.TEXTURE_3D||R===r.TEXTURE_2D_ARRAY)&&r.texParameteri(R,r.TEXTURE_WRAP_R,de[M.wrapR]),r.texParameteri(R,r.TEXTURE_MAG_FILTER,xe[M.magFilter]),r.texParameteri(R,r.TEXTURE_MIN_FILTER,xe[M.minFilter]),M.compareFunction&&(r.texParameteri(R,r.TEXTURE_COMPARE_MODE,r.COMPARE_REF_TO_TEXTURE),r.texParameteri(R,r.TEXTURE_COMPARE_FUNC,Se[M.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(M.magFilter===Ct||M.minFilter!==Ti&&M.minFilter!==cn||M.type===Jt&&e.has("OES_texture_float_linear")===!1)return;if(M.anisotropy>1||n.get(M).__currentAnisotropy){let O=e.get("EXT_texture_filter_anisotropic");r.texParameterf(R,O.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(M.anisotropy,i.getMaxAnisotropy())),n.get(M).__currentAnisotropy=M.anisotropy}}}function et(R,M){let O=!1;R.__webglInit===void 0&&(R.__webglInit=!0,M.addEventListener("dispose",E));let V=M.source,Q=d.get(V);Q===void 0&&(Q={},d.set(V,Q));let X=G(M);if(X!==R.__cacheKey){Q[X]===void 0&&(Q[X]={texture:r.createTexture(),usedTimes:0},o.memory.textures++,O=!0),Q[X].usedTimes++;let Ce=Q[R.__cacheKey];Ce!==void 0&&(Q[R.__cacheKey].usedTimes--,Ce.usedTimes===0&&b(M)),R.__cacheKey=X,R.__webglTexture=Q[X].texture}return O}function at(R,M,O){return Math.floor(Math.floor(R/O)/M)}function nt(R,M,O,V){let X=R.updateRanges;if(X.length===0)t.texSubImage2D(r.TEXTURE_2D,0,0,0,M.width,M.height,O,V,M.data);else{X.sort((se,_e)=>se.start-_e.start);let Ce=0;for(let se=1;se<X.length;se++){let _e=X[Ce],Oe=X[se],Ie=_e.start+_e.count,me=at(Oe.start,M.width,4),qe=at(_e.start,M.width,4);Oe.start<=Ie+1&&me===qe&&at(Oe.start+Oe.count-1,M.width,4)===me?_e.count=Math.max(_e.count,Oe.start+Oe.count-_e.start):(++Ce,X[Ce]=Oe)}X.length=Ce+1;let ce=r.getParameter(r.UNPACK_ROW_LENGTH),Ae=r.getParameter(r.UNPACK_SKIP_PIXELS),we=r.getParameter(r.UNPACK_SKIP_ROWS);r.pixelStorei(r.UNPACK_ROW_LENGTH,M.width);for(let se=0,_e=X.length;se<_e;se++){let Oe=X[se],Ie=Math.floor(Oe.start/4),me=Math.ceil(Oe.count/4),qe=Ie%M.width,D=Math.floor(Ie/M.width),ae=me,fe=1;r.pixelStorei(r.UNPACK_SKIP_PIXELS,qe),r.pixelStorei(r.UNPACK_SKIP_ROWS,D),t.texSubImage2D(r.TEXTURE_2D,0,qe,D,ae,fe,O,V,M.data)}R.clearUpdateRanges(),r.pixelStorei(r.UNPACK_ROW_LENGTH,ce),r.pixelStorei(r.UNPACK_SKIP_PIXELS,Ae),r.pixelStorei(r.UNPACK_SKIP_ROWS,we)}}function Z(R,M,O){let V=r.TEXTURE_2D;(M.isDataArrayTexture||M.isCompressedArrayTexture)&&(V=r.TEXTURE_2D_ARRAY),M.isData3DTexture&&(V=r.TEXTURE_3D);let Q=et(R,M),X=M.source;t.bindTexture(V,R.__webglTexture,r.TEXTURE0+O);let Ce=n.get(X);if(X.version!==Ce.__version||Q===!0){t.activeTexture(r.TEXTURE0+O);let ce=Ze.getPrimaries(Ze.workingColorSpace),Ae=M.colorSpace===ri?null:Ze.getPrimaries(M.colorSpace),we=M.colorSpace===ri||ce===Ae?r.NONE:r.BROWSER_DEFAULT_WEBGL;r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,M.flipY),r.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,M.premultiplyAlpha),r.pixelStorei(r.UNPACK_ALIGNMENT,M.unpackAlignment),r.pixelStorei(r.UNPACK_COLORSPACE_CONVERSION_WEBGL,we);let se=_(M.image,!1,i.maxTextureSize);se=He(M,se);let _e=s.convert(M.format,M.colorSpace),Oe=s.convert(M.type),Ie=y(M.internalFormat,_e,Oe,M.colorSpace,M.isVideoTexture);We(V,M);let me,qe=M.mipmaps,D=M.isVideoTexture!==!0,ae=Ce.__version===void 0||Q===!0,fe=X.dataReady,be=A(M,se);if(M.isDepthTexture)Ie=x(M.format===Fs,M.type),ae&&(D?t.texStorage2D(r.TEXTURE_2D,1,Ie,se.width,se.height):t.texImage2D(r.TEXTURE_2D,0,Ie,se.width,se.height,0,_e,Oe,null));else if(M.isDataTexture)if(qe.length>0){D&&ae&&t.texStorage2D(r.TEXTURE_2D,be,Ie,qe[0].width,qe[0].height);for(let re=0,j=qe.length;re<j;re++)me=qe[re],D?fe&&t.texSubImage2D(r.TEXTURE_2D,re,0,0,me.width,me.height,_e,Oe,me.data):t.texImage2D(r.TEXTURE_2D,re,Ie,me.width,me.height,0,_e,Oe,me.data);M.generateMipmaps=!1}else D?(ae&&t.texStorage2D(r.TEXTURE_2D,be,Ie,se.width,se.height),fe&&nt(M,se,_e,Oe)):t.texImage2D(r.TEXTURE_2D,0,Ie,se.width,se.height,0,_e,Oe,se.data);else if(M.isCompressedTexture)if(M.isCompressedArrayTexture){D&&ae&&t.texStorage3D(r.TEXTURE_2D_ARRAY,be,Ie,qe[0].width,qe[0].height,se.depth);for(let re=0,j=qe.length;re<j;re++)if(me=qe[re],M.format!==Ht)if(_e!==null)if(D){if(fe)if(M.layerUpdates.size>0){let Re=Dh(me.width,me.height,M.format,M.type);for(let Ge of M.layerUpdates){let dt=me.data.subarray(Ge*Re/me.data.BYTES_PER_ELEMENT,(Ge+1)*Re/me.data.BYTES_PER_ELEMENT);t.compressedTexSubImage3D(r.TEXTURE_2D_ARRAY,re,0,0,Ge,me.width,me.height,1,_e,dt)}M.clearLayerUpdates()}else t.compressedTexSubImage3D(r.TEXTURE_2D_ARRAY,re,0,0,0,me.width,me.height,se.depth,_e,me.data)}else t.compressedTexImage3D(r.TEXTURE_2D_ARRAY,re,Ie,me.width,me.height,se.depth,0,me.data,0,0);else console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else D?fe&&t.texSubImage3D(r.TEXTURE_2D_ARRAY,re,0,0,0,me.width,me.height,se.depth,_e,Oe,me.data):t.texImage3D(r.TEXTURE_2D_ARRAY,re,Ie,me.width,me.height,se.depth,0,_e,Oe,me.data)}else{D&&ae&&t.texStorage2D(r.TEXTURE_2D,be,Ie,qe[0].width,qe[0].height);for(let re=0,j=qe.length;re<j;re++)me=qe[re],M.format!==Ht?_e!==null?D?fe&&t.compressedTexSubImage2D(r.TEXTURE_2D,re,0,0,me.width,me.height,_e,me.data):t.compressedTexImage2D(r.TEXTURE_2D,re,Ie,me.width,me.height,0,me.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):D?fe&&t.texSubImage2D(r.TEXTURE_2D,re,0,0,me.width,me.height,_e,Oe,me.data):t.texImage2D(r.TEXTURE_2D,re,Ie,me.width,me.height,0,_e,Oe,me.data)}else if(M.isDataArrayTexture)if(D){if(ae&&t.texStorage3D(r.TEXTURE_2D_ARRAY,be,Ie,se.width,se.height,se.depth),fe)if(M.layerUpdates.size>0){let re=Dh(se.width,se.height,M.format,M.type);for(let j of M.layerUpdates){let Re=se.data.subarray(j*re/se.data.BYTES_PER_ELEMENT,(j+1)*re/se.data.BYTES_PER_ELEMENT);t.texSubImage3D(r.TEXTURE_2D_ARRAY,0,0,0,j,se.width,se.height,1,_e,Oe,Re)}M.clearLayerUpdates()}else t.texSubImage3D(r.TEXTURE_2D_ARRAY,0,0,0,0,se.width,se.height,se.depth,_e,Oe,se.data)}else t.texImage3D(r.TEXTURE_2D_ARRAY,0,Ie,se.width,se.height,se.depth,0,_e,Oe,se.data);else if(M.isData3DTexture)D?(ae&&t.texStorage3D(r.TEXTURE_3D,be,Ie,se.width,se.height,se.depth),fe&&t.texSubImage3D(r.TEXTURE_3D,0,0,0,0,se.width,se.height,se.depth,_e,Oe,se.data)):t.texImage3D(r.TEXTURE_3D,0,Ie,se.width,se.height,se.depth,0,_e,Oe,se.data);else if(M.isFramebufferTexture){if(ae)if(D)t.texStorage2D(r.TEXTURE_2D,be,Ie,se.width,se.height);else{let re=se.width,j=se.height;for(let Re=0;Re<be;Re++)t.texImage2D(r.TEXTURE_2D,Re,Ie,re,j,0,_e,Oe,null),re>>=1,j>>=1}}else if(qe.length>0){if(D&&ae){let re=ke(qe[0]);t.texStorage2D(r.TEXTURE_2D,be,Ie,re.width,re.height)}for(let re=0,j=qe.length;re<j;re++)me=qe[re],D?fe&&t.texSubImage2D(r.TEXTURE_2D,re,0,0,_e,Oe,me):t.texImage2D(r.TEXTURE_2D,re,Ie,_e,Oe,me);M.generateMipmaps=!1}else if(D){if(ae){let re=ke(se);t.texStorage2D(r.TEXTURE_2D,be,Ie,re.width,re.height)}fe&&t.texSubImage2D(r.TEXTURE_2D,0,0,0,_e,Oe,se)}else t.texImage2D(r.TEXTURE_2D,0,Ie,_e,Oe,se);g(M)&&p(V),Ce.__version=X.version,M.onUpdate&&M.onUpdate(M)}R.__version=M.version}function te(R,M,O){if(M.image.length!==6)return;let V=et(R,M),Q=M.source;t.bindTexture(r.TEXTURE_CUBE_MAP,R.__webglTexture,r.TEXTURE0+O);let X=n.get(Q);if(Q.version!==X.__version||V===!0){t.activeTexture(r.TEXTURE0+O);let Ce=Ze.getPrimaries(Ze.workingColorSpace),ce=M.colorSpace===ri?null:Ze.getPrimaries(M.colorSpace),Ae=M.colorSpace===ri||Ce===ce?r.NONE:r.BROWSER_DEFAULT_WEBGL;r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,M.flipY),r.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,M.premultiplyAlpha),r.pixelStorei(r.UNPACK_ALIGNMENT,M.unpackAlignment),r.pixelStorei(r.UNPACK_COLORSPACE_CONVERSION_WEBGL,Ae);let we=M.isCompressedTexture||M.image[0].isCompressedTexture,se=M.image[0]&&M.image[0].isDataTexture,_e=[];for(let j=0;j<6;j++)!we&&!se?_e[j]=_(M.image[j],!0,i.maxCubemapSize):_e[j]=se?M.image[j].image:M.image[j],_e[j]=He(M,_e[j]);let Oe=_e[0],Ie=s.convert(M.format,M.colorSpace),me=s.convert(M.type),qe=y(M.internalFormat,Ie,me,M.colorSpace),D=M.isVideoTexture!==!0,ae=X.__version===void 0||V===!0,fe=Q.dataReady,be=A(M,Oe);We(r.TEXTURE_CUBE_MAP,M);let re;if(we){D&&ae&&t.texStorage2D(r.TEXTURE_CUBE_MAP,be,qe,Oe.width,Oe.height);for(let j=0;j<6;j++){re=_e[j].mipmaps;for(let Re=0;Re<re.length;Re++){let Ge=re[Re];M.format!==Ht?Ie!==null?D?fe&&t.compressedTexSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+j,Re,0,0,Ge.width,Ge.height,Ie,Ge.data):t.compressedTexImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+j,Re,qe,Ge.width,Ge.height,0,Ge.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):D?fe&&t.texSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+j,Re,0,0,Ge.width,Ge.height,Ie,me,Ge.data):t.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+j,Re,qe,Ge.width,Ge.height,0,Ie,me,Ge.data)}}}else{if(re=M.mipmaps,D&&ae){re.length>0&&be++;let j=ke(_e[0]);t.texStorage2D(r.TEXTURE_CUBE_MAP,be,qe,j.width,j.height)}for(let j=0;j<6;j++)if(se){D?fe&&t.texSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+j,0,0,0,_e[j].width,_e[j].height,Ie,me,_e[j].data):t.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+j,0,qe,_e[j].width,_e[j].height,0,Ie,me,_e[j].data);for(let Re=0;Re<re.length;Re++){let dt=re[Re].image[j].image;D?fe&&t.texSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+j,Re+1,0,0,dt.width,dt.height,Ie,me,dt.data):t.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+j,Re+1,qe,dt.width,dt.height,0,Ie,me,dt.data)}}else{D?fe&&t.texSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+j,0,0,0,Ie,me,_e[j]):t.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+j,0,qe,Ie,me,_e[j]);for(let Re=0;Re<re.length;Re++){let Ge=re[Re];D?fe&&t.texSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+j,Re+1,0,0,Ie,me,Ge.image[j]):t.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+j,Re+1,qe,Ie,me,Ge.image[j])}}}g(M)&&p(r.TEXTURE_CUBE_MAP),X.__version=Q.version,M.onUpdate&&M.onUpdate(M)}R.__version=M.version}function Me(R,M,O,V,Q,X){let Ce=s.convert(O.format,O.colorSpace),ce=s.convert(O.type),Ae=y(O.internalFormat,Ce,ce,O.colorSpace),we=n.get(M),se=n.get(O);if(se.__renderTarget=M,!we.__hasExternalTextures){let _e=Math.max(1,M.width>>X),Oe=Math.max(1,M.height>>X);Q===r.TEXTURE_3D||Q===r.TEXTURE_2D_ARRAY?t.texImage3D(Q,X,Ae,_e,Oe,M.depth,0,Ce,ce,null):t.texImage2D(Q,X,Ae,_e,Oe,0,Ce,ce,null)}t.bindFramebuffer(r.FRAMEBUFFER,R),ie(M)?a.framebufferTexture2DMultisampleEXT(r.FRAMEBUFFER,V,Q,se.__webglTexture,0,le(M)):(Q===r.TEXTURE_2D||Q>=r.TEXTURE_CUBE_MAP_POSITIVE_X&&Q<=r.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&r.framebufferTexture2D(r.FRAMEBUFFER,V,Q,se.__webglTexture,X),t.bindFramebuffer(r.FRAMEBUFFER,null)}function Pe(R,M,O){if(r.bindRenderbuffer(r.RENDERBUFFER,R),M.depthBuffer){let V=M.depthTexture,Q=V&&V.isDepthTexture?V.type:null,X=x(M.stencilBuffer,Q),Ce=M.stencilBuffer?r.DEPTH_STENCIL_ATTACHMENT:r.DEPTH_ATTACHMENT,ce=le(M);ie(M)?a.renderbufferStorageMultisampleEXT(r.RENDERBUFFER,ce,X,M.width,M.height):O?r.renderbufferStorageMultisample(r.RENDERBUFFER,ce,X,M.width,M.height):r.renderbufferStorage(r.RENDERBUFFER,X,M.width,M.height),r.framebufferRenderbuffer(r.FRAMEBUFFER,Ce,r.RENDERBUFFER,R)}else{let V=M.textures;for(let Q=0;Q<V.length;Q++){let X=V[Q],Ce=s.convert(X.format,X.colorSpace),ce=s.convert(X.type),Ae=y(X.internalFormat,Ce,ce,X.colorSpace),we=le(M);O&&ie(M)===!1?r.renderbufferStorageMultisample(r.RENDERBUFFER,we,Ae,M.width,M.height):ie(M)?a.renderbufferStorageMultisampleEXT(r.RENDERBUFFER,we,Ae,M.width,M.height):r.renderbufferStorage(r.RENDERBUFFER,Ae,M.width,M.height)}}r.bindRenderbuffer(r.RENDERBUFFER,null)}function Ee(R,M){if(M&&M.isWebGLCubeRenderTarget)throw new Error("Depth Texture with cube render targets is not supported");if(t.bindFramebuffer(r.FRAMEBUFFER,R),!(M.depthTexture&&M.depthTexture.isDepthTexture))throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");let V=n.get(M.depthTexture);V.__renderTarget=M,(!V.__webglTexture||M.depthTexture.image.width!==M.width||M.depthTexture.image.height!==M.height)&&(M.depthTexture.image.width=M.width,M.depthTexture.image.height=M.height,M.depthTexture.needsUpdate=!0),q(M.depthTexture,0);let Q=V.__webglTexture,X=le(M);if(M.depthTexture.format===hs)ie(M)?a.framebufferTexture2DMultisampleEXT(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.TEXTURE_2D,Q,0,X):r.framebufferTexture2D(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.TEXTURE_2D,Q,0);else if(M.depthTexture.format===Fs)ie(M)?a.framebufferTexture2DMultisampleEXT(r.FRAMEBUFFER,r.DEPTH_STENCIL_ATTACHMENT,r.TEXTURE_2D,Q,0,X):r.framebufferTexture2D(r.FRAMEBUFFER,r.DEPTH_STENCIL_ATTACHMENT,r.TEXTURE_2D,Q,0);else throw new Error("Unknown depthTexture format")}function Je(R){let M=n.get(R),O=R.isWebGLCubeRenderTarget===!0;if(M.__boundDepthTexture!==R.depthTexture){let V=R.depthTexture;if(M.__depthDisposeCallback&&M.__depthDisposeCallback(),V){let Q=()=>{delete M.__boundDepthTexture,delete M.__depthDisposeCallback,V.removeEventListener("dispose",Q)};V.addEventListener("dispose",Q),M.__depthDisposeCallback=Q}M.__boundDepthTexture=V}if(R.depthTexture&&!M.__autoAllocateDepthBuffer){if(O)throw new Error("target.depthTexture not supported in Cube render targets");let V=R.texture.mipmaps;V&&V.length>0?Ee(M.__webglFramebuffer[0],R):Ee(M.__webglFramebuffer,R)}else if(O){M.__webglDepthbuffer=[];for(let V=0;V<6;V++)if(t.bindFramebuffer(r.FRAMEBUFFER,M.__webglFramebuffer[V]),M.__webglDepthbuffer[V]===void 0)M.__webglDepthbuffer[V]=r.createRenderbuffer(),Pe(M.__webglDepthbuffer[V],R,!1);else{let Q=R.stencilBuffer?r.DEPTH_STENCIL_ATTACHMENT:r.DEPTH_ATTACHMENT,X=M.__webglDepthbuffer[V];r.bindRenderbuffer(r.RENDERBUFFER,X),r.framebufferRenderbuffer(r.FRAMEBUFFER,Q,r.RENDERBUFFER,X)}}else{let V=R.texture.mipmaps;if(V&&V.length>0?t.bindFramebuffer(r.FRAMEBUFFER,M.__webglFramebuffer[0]):t.bindFramebuffer(r.FRAMEBUFFER,M.__webglFramebuffer),M.__webglDepthbuffer===void 0)M.__webglDepthbuffer=r.createRenderbuffer(),Pe(M.__webglDepthbuffer,R,!1);else{let Q=R.stencilBuffer?r.DEPTH_STENCIL_ATTACHMENT:r.DEPTH_ATTACHMENT,X=M.__webglDepthbuffer;r.bindRenderbuffer(r.RENDERBUFFER,X),r.framebufferRenderbuffer(r.FRAMEBUFFER,Q,r.RENDERBUFFER,X)}}t.bindFramebuffer(r.FRAMEBUFFER,null)}function ut(R,M,O){let V=n.get(R);M!==void 0&&Me(V.__webglFramebuffer,R,R.texture,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,0),O!==void 0&&Je(R)}function P(R){let M=R.texture,O=n.get(R),V=n.get(M);R.addEventListener("dispose",C);let Q=R.textures,X=R.isWebGLCubeRenderTarget===!0,Ce=Q.length>1;if(Ce||(V.__webglTexture===void 0&&(V.__webglTexture=r.createTexture()),V.__version=M.version,o.memory.textures++),X){O.__webglFramebuffer=[];for(let ce=0;ce<6;ce++)if(M.mipmaps&&M.mipmaps.length>0){O.__webglFramebuffer[ce]=[];for(let Ae=0;Ae<M.mipmaps.length;Ae++)O.__webglFramebuffer[ce][Ae]=r.createFramebuffer()}else O.__webglFramebuffer[ce]=r.createFramebuffer()}else{if(M.mipmaps&&M.mipmaps.length>0){O.__webglFramebuffer=[];for(let ce=0;ce<M.mipmaps.length;ce++)O.__webglFramebuffer[ce]=r.createFramebuffer()}else O.__webglFramebuffer=r.createFramebuffer();if(Ce)for(let ce=0,Ae=Q.length;ce<Ae;ce++){let we=n.get(Q[ce]);we.__webglTexture===void 0&&(we.__webglTexture=r.createTexture(),o.memory.textures++)}if(R.samples>0&&ie(R)===!1){O.__webglMultisampledFramebuffer=r.createFramebuffer(),O.__webglColorRenderbuffer=[],t.bindFramebuffer(r.FRAMEBUFFER,O.__webglMultisampledFramebuffer);for(let ce=0;ce<Q.length;ce++){let Ae=Q[ce];O.__webglColorRenderbuffer[ce]=r.createRenderbuffer(),r.bindRenderbuffer(r.RENDERBUFFER,O.__webglColorRenderbuffer[ce]);let we=s.convert(Ae.format,Ae.colorSpace),se=s.convert(Ae.type),_e=y(Ae.internalFormat,we,se,Ae.colorSpace,R.isXRRenderTarget===!0),Oe=le(R);r.renderbufferStorageMultisample(r.RENDERBUFFER,Oe,_e,R.width,R.height),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0+ce,r.RENDERBUFFER,O.__webglColorRenderbuffer[ce])}r.bindRenderbuffer(r.RENDERBUFFER,null),R.depthBuffer&&(O.__webglDepthRenderbuffer=r.createRenderbuffer(),Pe(O.__webglDepthRenderbuffer,R,!0)),t.bindFramebuffer(r.FRAMEBUFFER,null)}}if(X){t.bindTexture(r.TEXTURE_CUBE_MAP,V.__webglTexture),We(r.TEXTURE_CUBE_MAP,M);for(let ce=0;ce<6;ce++)if(M.mipmaps&&M.mipmaps.length>0)for(let Ae=0;Ae<M.mipmaps.length;Ae++)Me(O.__webglFramebuffer[ce][Ae],R,M,r.COLOR_ATTACHMENT0,r.TEXTURE_CUBE_MAP_POSITIVE_X+ce,Ae);else Me(O.__webglFramebuffer[ce],R,M,r.COLOR_ATTACHMENT0,r.TEXTURE_CUBE_MAP_POSITIVE_X+ce,0);g(M)&&p(r.TEXTURE_CUBE_MAP),t.unbindTexture()}else if(Ce){for(let ce=0,Ae=Q.length;ce<Ae;ce++){let we=Q[ce],se=n.get(we),_e=r.TEXTURE_2D;(R.isWebGL3DRenderTarget||R.isWebGLArrayRenderTarget)&&(_e=R.isWebGL3DRenderTarget?r.TEXTURE_3D:r.TEXTURE_2D_ARRAY),t.bindTexture(_e,se.__webglTexture),We(_e,we),Me(O.__webglFramebuffer,R,we,r.COLOR_ATTACHMENT0+ce,_e,0),g(we)&&p(_e)}t.unbindTexture()}else{let ce=r.TEXTURE_2D;if((R.isWebGL3DRenderTarget||R.isWebGLArrayRenderTarget)&&(ce=R.isWebGL3DRenderTarget?r.TEXTURE_3D:r.TEXTURE_2D_ARRAY),t.bindTexture(ce,V.__webglTexture),We(ce,M),M.mipmaps&&M.mipmaps.length>0)for(let Ae=0;Ae<M.mipmaps.length;Ae++)Me(O.__webglFramebuffer[Ae],R,M,r.COLOR_ATTACHMENT0,ce,Ae);else Me(O.__webglFramebuffer,R,M,r.COLOR_ATTACHMENT0,ce,0);g(M)&&p(ce),t.unbindTexture()}R.depthBuffer&&Je(R)}function ee(R){let M=R.textures;for(let O=0,V=M.length;O<V;O++){let Q=M[O];if(g(Q)){let X=v(R),Ce=n.get(Q).__webglTexture;t.bindTexture(X,Ce),p(X),t.unbindTexture()}}}let $=[],J=[];function K(R){if(R.samples>0){if(ie(R)===!1){let M=R.textures,O=R.width,V=R.height,Q=r.COLOR_BUFFER_BIT,X=R.stencilBuffer?r.DEPTH_STENCIL_ATTACHMENT:r.DEPTH_ATTACHMENT,Ce=n.get(R),ce=M.length>1;if(ce)for(let we=0;we<M.length;we++)t.bindFramebuffer(r.FRAMEBUFFER,Ce.__webglMultisampledFramebuffer),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0+we,r.RENDERBUFFER,null),t.bindFramebuffer(r.FRAMEBUFFER,Ce.__webglFramebuffer),r.framebufferTexture2D(r.DRAW_FRAMEBUFFER,r.COLOR_ATTACHMENT0+we,r.TEXTURE_2D,null,0);t.bindFramebuffer(r.READ_FRAMEBUFFER,Ce.__webglMultisampledFramebuffer);let Ae=R.texture.mipmaps;Ae&&Ae.length>0?t.bindFramebuffer(r.DRAW_FRAMEBUFFER,Ce.__webglFramebuffer[0]):t.bindFramebuffer(r.DRAW_FRAMEBUFFER,Ce.__webglFramebuffer);for(let we=0;we<M.length;we++){if(R.resolveDepthBuffer&&(R.depthBuffer&&(Q|=r.DEPTH_BUFFER_BIT),R.stencilBuffer&&R.resolveStencilBuffer&&(Q|=r.STENCIL_BUFFER_BIT)),ce){r.framebufferRenderbuffer(r.READ_FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.RENDERBUFFER,Ce.__webglColorRenderbuffer[we]);let se=n.get(M[we]).__webglTexture;r.framebufferTexture2D(r.DRAW_FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,se,0)}r.blitFramebuffer(0,0,O,V,0,0,O,V,Q,r.NEAREST),c===!0&&($.length=0,J.length=0,$.push(r.COLOR_ATTACHMENT0+we),R.depthBuffer&&R.resolveDepthBuffer===!1&&($.push(X),J.push(X),r.invalidateFramebuffer(r.DRAW_FRAMEBUFFER,J)),r.invalidateFramebuffer(r.READ_FRAMEBUFFER,$))}if(t.bindFramebuffer(r.READ_FRAMEBUFFER,null),t.bindFramebuffer(r.DRAW_FRAMEBUFFER,null),ce)for(let we=0;we<M.length;we++){t.bindFramebuffer(r.FRAMEBUFFER,Ce.__webglMultisampledFramebuffer),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0+we,r.RENDERBUFFER,Ce.__webglColorRenderbuffer[we]);let se=n.get(M[we]).__webglTexture;t.bindFramebuffer(r.FRAMEBUFFER,Ce.__webglFramebuffer),r.framebufferTexture2D(r.DRAW_FRAMEBUFFER,r.COLOR_ATTACHMENT0+we,r.TEXTURE_2D,se,0)}t.bindFramebuffer(r.DRAW_FRAMEBUFFER,Ce.__webglMultisampledFramebuffer)}else if(R.depthBuffer&&R.resolveDepthBuffer===!1&&c){let M=R.stencilBuffer?r.DEPTH_STENCIL_ATTACHMENT:r.DEPTH_ATTACHMENT;r.invalidateFramebuffer(r.DRAW_FRAMEBUFFER,[M])}}}function le(R){return Math.min(i.maxSamples,R.samples)}function ie(R){let M=n.get(R);return R.samples>0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&M.__useRenderToTexture!==!1}function he(R){let M=o.render.frame;h.get(R)!==M&&(h.set(R,M),R.update())}function He(R,M){let O=R.colorSpace,V=R.format,Q=R.type;return R.isCompressedTexture===!0||R.isVideoTexture===!0||O!==Ot&&O!==ri&&(Ze.getTransfer(O)===ot?(V!==Ht||Q!==Cn)&&console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",O)),M}function ke(R){return typeof HTMLImageElement<"u"&&R instanceof HTMLImageElement?(l.width=R.naturalWidth||R.width,l.height=R.naturalHeight||R.height):typeof VideoFrame<"u"&&R instanceof VideoFrame?(l.width=R.displayWidth,l.height=R.displayHeight):(l.width=R.width,l.height=R.height),l}this.allocateTextureUnit=z,this.resetTextureUnits=F,this.setTexture2D=q,this.setTexture2DArray=W,this.setTexture3D=ne,this.setTextureCube=H,this.rebindTextures=ut,this.setupRenderTarget=P,this.updateRenderTargetMipmap=ee,this.updateMultisampleRenderTarget=K,this.setupDepthRenderbuffer=Je,this.setupFrameBufferTexture=Me,this.useMultisampledRTT=ie}function mg(r,e){function t(n,i=ri){let s,o=Ze.getTransfer(i);if(n===Cn)return r.UNSIGNED_BYTE;if(n===ka)return r.UNSIGNED_SHORT_4_4_4_4;if(n===Va)return r.UNSIGNED_SHORT_5_5_5_1;if(n===Th)return r.UNSIGNED_INT_5_9_9_9_REV;if(n===Eh)return r.UNSIGNED_INT_10F_11F_11F_REV;if(n===Sh)return r.BYTE;if(n===bh)return r.SHORT;if(n===Ds)return r.UNSIGNED_SHORT;if(n===za)return r.INT;if(n===si)return r.UNSIGNED_INT;if(n===Jt)return r.FLOAT;if(n===Ns)return r.HALF_FLOAT;if(n===Ah)return r.ALPHA;if(n===wh)return r.RGB;if(n===Ht)return r.RGBA;if(n===hs)return r.DEPTH_COMPONENT;if(n===Fs)return r.DEPTH_STENCIL;if(n===Ha)return r.RED;if(n===Yr)return r.RED_INTEGER;if(n===Rh)return r.RG;if(n===Ga)return r.RG_INTEGER;if(n===Wa)return r.RGBA_INTEGER;if(n===Zr||n===Kr||n===Jr||n===$r)if(o===ot)if(s=e.get("WEBGL_compressed_texture_s3tc_srgb"),s!==null){if(n===Zr)return s.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(n===Kr)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(n===Jr)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(n===$r)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(s=e.get("WEBGL_compressed_texture_s3tc"),s!==null){if(n===Zr)return s.COMPRESSED_RGB_S3TC_DXT1_EXT;if(n===Kr)return s.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(n===Jr)return s.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(n===$r)return s.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(n===Xa||n===qa||n===Ya||n===Za)if(s=e.get("WEBGL_compressed_texture_pvrtc"),s!==null){if(n===Xa)return s.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(n===qa)return s.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(n===Ya)return s.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(n===Za)return s.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(n===Ka||n===Ja||n===$a)if(s=e.get("WEBGL_compressed_texture_etc"),s!==null){if(n===Ka||n===Ja)return o===ot?s.COMPRESSED_SRGB8_ETC2:s.COMPRESSED_RGB8_ETC2;if(n===$a)return o===ot?s.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:s.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(n===ja||n===Qa||n===ec||n===tc||n===nc||n===ic||n===sc||n===rc||n===oc||n===ac||n===cc||n===lc||n===hc||n===uc)if(s=e.get("WEBGL_compressed_texture_astc"),s!==null){if(n===ja)return o===ot?s.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:s.COMPRESSED_RGBA_ASTC_4x4_KHR;if(n===Qa)return o===ot?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:s.COMPRESSED_RGBA_ASTC_5x4_KHR;if(n===ec)return o===ot?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:s.COMPRESSED_RGBA_ASTC_5x5_KHR;if(n===tc)return o===ot?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:s.COMPRESSED_RGBA_ASTC_6x5_KHR;if(n===nc)return o===ot?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:s.COMPRESSED_RGBA_ASTC_6x6_KHR;if(n===ic)return o===ot?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:s.COMPRESSED_RGBA_ASTC_8x5_KHR;if(n===sc)return o===ot?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:s.COMPRESSED_RGBA_ASTC_8x6_KHR;if(n===rc)return o===ot?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:s.COMPRESSED_RGBA_ASTC_8x8_KHR;if(n===oc)return o===ot?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:s.COMPRESSED_RGBA_ASTC_10x5_KHR;if(n===ac)return o===ot?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:s.COMPRESSED_RGBA_ASTC_10x6_KHR;if(n===cc)return o===ot?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:s.COMPRESSED_RGBA_ASTC_10x8_KHR;if(n===lc)return o===ot?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:s.COMPRESSED_RGBA_ASTC_10x10_KHR;if(n===hc)return o===ot?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:s.COMPRESSED_RGBA_ASTC_12x10_KHR;if(n===uc)return o===ot?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:s.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(n===dc||n===fc||n===pc)if(s=e.get("EXT_texture_compression_bptc"),s!==null){if(n===dc)return o===ot?s.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:s.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(n===fc)return s.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(n===pc)return s.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(n===mc||n===gc||n===_c||n===xc)if(s=e.get("EXT_texture_compression_rgtc"),s!==null){if(n===mc)return s.COMPRESSED_RED_RGTC1_EXT;if(n===gc)return s.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(n===_c)return s.COMPRESSED_RED_GREEN_RGTC2_EXT;if(n===xc)return s.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return n===Us?r.UNSIGNED_INT_24_8:r[n]!==void 0?r[n]:null}return{convert:t}}var qM=`+void main() {++ gl_Position = vec4( position, 1.0 );++}`,YM=`+uniform sampler2DArray depthColor;+uniform float depthWidth;+uniform float depthHeight;++void main() {++ vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );++ if ( coord.x >= 1.0 ) {++ gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;++ } else {++ gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;++ }++}`,Qd=class{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){let n=new br(e.texture);(e.depthNear!==t.depthNear||e.depthFar!==t.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=n}}getMesh(e){if(this.texture!==null&&this.mesh===null){let t=e.cameras[0].viewport,n=new on({vertexShader:qM,fragmentShader:YM,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new pt(new ws(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}},ef=class extends xn{constructor(e,t){super();let n=this,i=null,s=1,o=null,a="local-floor",c=1,l=null,h=null,u=null,d=null,f=null,m=null,_=typeof XRWebGLBinding<"u",g=new Qd,p={},v=t.getContextAttributes(),y=null,x=null,A=[],E=[],C=new Y,I=null,b=new Tt;b.viewport=new tt;let S=new Tt;S.viewport=new tt;let L=[b,S],F=new Aa,z=null,G=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(Z){let te=A[Z];return te===void 0&&(te=new _s,A[Z]=te),te.getTargetRaySpace()},this.getControllerGrip=function(Z){let te=A[Z];return te===void 0&&(te=new _s,A[Z]=te),te.getGripSpace()},this.getHand=function(Z){let te=A[Z];return te===void 0&&(te=new _s,A[Z]=te),te.getHandSpace()};function q(Z){let te=E.indexOf(Z.inputSource);if(te===-1)return;let Me=A[te];Me!==void 0&&(Me.update(Z.inputSource,Z.frame,l||o),Me.dispatchEvent({type:Z.type,data:Z.inputSource}))}function W(){i.removeEventListener("select",q),i.removeEventListener("selectstart",q),i.removeEventListener("selectend",q),i.removeEventListener("squeeze",q),i.removeEventListener("squeezestart",q),i.removeEventListener("squeezeend",q),i.removeEventListener("end",W),i.removeEventListener("inputsourceschange",ne);for(let Z=0;Z<A.length;Z++){let te=E[Z];te!==null&&(E[Z]=null,A[Z].disconnect(te))}z=null,G=null,g.reset();for(let Z in p)delete p[Z];e.setRenderTarget(y),f=null,d=null,u=null,i=null,x=null,nt.stop(),n.isPresenting=!1,e.setPixelRatio(I),e.setSize(C.width,C.height,!1),n.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(Z){s=Z,n.isPresenting===!0&&console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(Z){a=Z,n.isPresenting===!0&&console.warn("THREE.WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return l||o},this.setReferenceSpace=function(Z){l=Z},this.getBaseLayer=function(){return d!==null?d:f},this.getBinding=function(){return u===null&&_&&(u=new XRWebGLBinding(i,t)),u},this.getFrame=function(){return m},this.getSession=function(){return i},this.setSession=async function(Z){if(i=Z,i!==null){if(y=e.getRenderTarget(),i.addEventListener("select",q),i.addEventListener("selectstart",q),i.addEventListener("selectend",q),i.addEventListener("squeeze",q),i.addEventListener("squeezestart",q),i.addEventListener("squeezeend",q),i.addEventListener("end",W),i.addEventListener("inputsourceschange",ne),v.xrCompatible!==!0&&await t.makeXRCompatible(),I=e.getPixelRatio(),e.getSize(C),_&&"createProjectionLayer"in XRWebGLBinding.prototype){let Me=null,Pe=null,Ee=null;v.depth&&(Ee=v.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,Me=v.stencil?Fs:hs,Pe=v.stencil?Us:si);let Je={colorFormat:t.RGBA8,depthFormat:Ee,scaleFactor:s};u=this.getBinding(),d=u.createProjectionLayer(Je),i.updateRenderState({layers:[d]}),e.setPixelRatio(1),e.setSize(d.textureWidth,d.textureHeight,!1),x=new yn(d.textureWidth,d.textureHeight,{format:Ht,type:Cn,depthTexture:new Sr(d.textureWidth,d.textureHeight,Pe,void 0,void 0,void 0,void 0,void 0,void 0,Me),stencilBuffer:v.stencil,colorSpace:e.outputColorSpace,samples:v.antialias?4:0,resolveDepthBuffer:d.ignoreDepthValues===!1,resolveStencilBuffer:d.ignoreDepthValues===!1})}else{let Me={antialias:v.antialias,alpha:!0,depth:v.depth,stencil:v.stencil,framebufferScaleFactor:s};f=new XRWebGLLayer(i,t,Me),i.updateRenderState({baseLayer:f}),e.setPixelRatio(1),e.setSize(f.framebufferWidth,f.framebufferHeight,!1),x=new yn(f.framebufferWidth,f.framebufferHeight,{format:Ht,type:Cn,colorSpace:e.outputColorSpace,stencilBuffer:v.stencil,resolveDepthBuffer:f.ignoreDepthValues===!1,resolveStencilBuffer:f.ignoreDepthValues===!1})}x.isXRRenderTarget=!0,this.setFoveation(c),l=null,o=await i.requestReferenceSpace(a),nt.setContext(i),nt.start(),n.isPresenting=!0,n.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(i!==null)return i.environmentBlendMode},this.getDepthTexture=function(){return g.getDepthTexture()};function ne(Z){for(let te=0;te<Z.removed.length;te++){let Me=Z.removed[te],Pe=E.indexOf(Me);Pe>=0&&(E[Pe]=null,A[Pe].disconnect(Me))}for(let te=0;te<Z.added.length;te++){let Me=Z.added[te],Pe=E.indexOf(Me);if(Pe===-1){for(let Je=0;Je<A.length;Je++)if(Je>=E.length){E.push(Me),Pe=Je;break}else if(E[Je]===null){E[Je]=Me,Pe=Je;break}if(Pe===-1)break}let Ee=A[Pe];Ee&&Ee.connect(Me)}}let H=new w,de=new w;function xe(Z,te,Me){H.setFromMatrixPosition(te.matrixWorld),de.setFromMatrixPosition(Me.matrixWorld);let Pe=H.distanceTo(de),Ee=te.projectionMatrix.elements,Je=Me.projectionMatrix.elements,ut=Ee[14]/(Ee[10]-1),P=Ee[14]/(Ee[10]+1),ee=(Ee[9]+1)/Ee[5],$=(Ee[9]-1)/Ee[5],J=(Ee[8]-1)/Ee[0],K=(Je[8]+1)/Je[0],le=ut*J,ie=ut*K,he=Pe/(-J+K),He=he*-J;if(te.matrixWorld.decompose(Z.position,Z.quaternion,Z.scale),Z.translateX(He),Z.translateZ(he),Z.matrixWorld.compose(Z.position,Z.quaternion,Z.scale),Z.matrixWorldInverse.copy(Z.matrixWorld).invert(),Ee[10]===-1)Z.projectionMatrix.copy(te.projectionMatrix),Z.projectionMatrixInverse.copy(te.projectionMatrixInverse);else{let ke=ut+he,R=P+he,M=le-He,O=ie+(Pe-He),V=ee*P/R*ke,Q=$*P/R*ke;Z.projectionMatrix.makePerspective(M,O,V,Q,ke,R),Z.projectionMatrixInverse.copy(Z.projectionMatrix).invert()}}function Se(Z,te){te===null?Z.matrixWorld.copy(Z.matrix):Z.matrixWorld.multiplyMatrices(te.matrixWorld,Z.matrix),Z.matrixWorldInverse.copy(Z.matrixWorld).invert()}this.updateCamera=function(Z){if(i===null)return;let te=Z.near,Me=Z.far;g.texture!==null&&(g.depthNear>0&&(te=g.depthNear),g.depthFar>0&&(Me=g.depthFar)),F.near=S.near=b.near=te,F.far=S.far=b.far=Me,(z!==F.near||G!==F.far)&&(i.updateRenderState({depthNear:F.near,depthFar:F.far}),z=F.near,G=F.far),F.layers.mask=Z.layers.mask|6,b.layers.mask=F.layers.mask&3,S.layers.mask=F.layers.mask&5;let Pe=Z.parent,Ee=F.cameras;Se(F,Pe);for(let Je=0;Je<Ee.length;Je++)Se(Ee[Je],Pe);Ee.length===2?xe(F,b,S):F.projectionMatrix.copy(b.projectionMatrix),We(Z,F,Pe)};function We(Z,te,Me){Me===null?Z.matrix.copy(te.matrixWorld):(Z.matrix.copy(Me.matrixWorld),Z.matrix.invert(),Z.matrix.multiply(te.matrixWorld)),Z.matrix.decompose(Z.position,Z.quaternion,Z.scale),Z.updateMatrixWorld(!0),Z.projectionMatrix.copy(te.projectionMatrix),Z.projectionMatrixInverse.copy(te.projectionMatrixInverse),Z.isPerspectiveCamera&&(Z.fov=ds*2*Math.atan(1/Z.projectionMatrix.elements[5]),Z.zoom=1)}this.getCamera=function(){return F},this.getFoveation=function(){if(!(d===null&&f===null))return c},this.setFoveation=function(Z){c=Z,d!==null&&(d.fixedFoveation=Z),f!==null&&f.fixedFoveation!==void 0&&(f.fixedFoveation=Z)},this.hasDepthSensing=function(){return g.texture!==null},this.getDepthSensingMesh=function(){return g.getMesh(F)},this.getCameraTexture=function(Z){return p[Z]};let et=null;function at(Z,te){if(h=te.getViewerPose(l||o),m=te,h!==null){let Me=h.views;f!==null&&(e.setRenderTargetFramebuffer(x,f.framebuffer),e.setRenderTarget(x));let Pe=!1;Me.length!==F.cameras.length&&(F.cameras.length=0,Pe=!0);for(let P=0;P<Me.length;P++){let ee=Me[P],$=null;if(f!==null)$=f.getViewport(ee);else{let K=u.getViewSubImage(d,ee);$=K.viewport,P===0&&(e.setRenderTargetTextures(x,K.colorTexture,K.depthStencilTexture),e.setRenderTarget(x))}let J=L[P];J===void 0&&(J=new Tt,J.layers.enable(P),J.viewport=new tt,L[P]=J),J.matrix.fromArray(ee.transform.matrix),J.matrix.decompose(J.position,J.quaternion,J.scale),J.projectionMatrix.fromArray(ee.projectionMatrix),J.projectionMatrixInverse.copy(J.projectionMatrix).invert(),J.viewport.set($.x,$.y,$.width,$.height),P===0&&(F.matrix.copy(J.matrix),F.matrix.decompose(F.position,F.quaternion,F.scale)),Pe===!0&&F.cameras.push(J)}let Ee=i.enabledFeatures;if(Ee&&Ee.includes("depth-sensing")&&i.depthUsage=="gpu-optimized"&&_){u=n.getBinding();let P=u.getDepthInformation(Me[0]);P&&P.isValid&&P.texture&&g.init(P,i.renderState)}if(Ee&&Ee.includes("camera-access")&&_){e.state.unbindTexture(),u=n.getBinding();for(let P=0;P<Me.length;P++){let ee=Me[P].camera;if(ee){let $=p[ee];$||($=new br,p[ee]=$);let J=u.getCameraImage(ee);$.sourceTexture=J}}}}for(let Me=0;Me<A.length;Me++){let Pe=E[Me],Ee=A[Me];Pe!==null&&Ee!==void 0&&Ee.update(Pe,te,l||o)}et&&et(Z,te),te.detectedPlanes&&n.dispatchEvent({type:"planesdetected",data:te}),m=null}let nt=new hg;nt.setAnimationLoop(at),this.setAnimationLoop=function(Z){et=Z},this.dispose=function(){}}},ks=new rn,ZM=new De;function KM(r,e){function t(g,p){g.matrixAutoUpdate===!0&&g.updateMatrix(),p.value.copy(g.matrix)}function n(g,p){p.color.getRGB(g.fogColor.value,Nd(r)),p.isFog?(g.fogNear.value=p.near,g.fogFar.value=p.far):p.isFogExp2&&(g.fogDensity.value=p.density)}function i(g,p,v,y,x){p.isMeshBasicMaterial||p.isMeshLambertMaterial?s(g,p):p.isMeshToonMaterial?(s(g,p),u(g,p)):p.isMeshPhongMaterial?(s(g,p),h(g,p)):p.isMeshStandardMaterial?(s(g,p),d(g,p),p.isMeshPhysicalMaterial&&f(g,p,x)):p.isMeshMatcapMaterial?(s(g,p),m(g,p)):p.isMeshDepthMaterial?s(g,p):p.isMeshDistanceMaterial?(s(g,p),_(g,p)):p.isMeshNormalMaterial?s(g,p):p.isLineBasicMaterial?(o(g,p),p.isLineDashedMaterial&&a(g,p)):p.isPointsMaterial?c(g,p,v,y):p.isSpriteMaterial?l(g,p):p.isShadowMaterial?(g.color.value.copy(p.color),g.opacity.value=p.opacity):p.isShaderMaterial&&(p.uniformsNeedUpdate=!1)}function s(g,p){g.opacity.value=p.opacity,p.color&&g.diffuse.value.copy(p.color),p.emissive&&g.emissive.value.copy(p.emissive).multiplyScalar(p.emissiveIntensity),p.map&&(g.map.value=p.map,t(p.map,g.mapTransform)),p.alphaMap&&(g.alphaMap.value=p.alphaMap,t(p.alphaMap,g.alphaMapTransform)),p.bumpMap&&(g.bumpMap.value=p.bumpMap,t(p.bumpMap,g.bumpMapTransform),g.bumpScale.value=p.bumpScale,p.side===Wt&&(g.bumpScale.value*=-1)),p.normalMap&&(g.normalMap.value=p.normalMap,t(p.normalMap,g.normalMapTransform),g.normalScale.value.copy(p.normalScale),p.side===Wt&&g.normalScale.value.negate()),p.displacementMap&&(g.displacementMap.value=p.displacementMap,t(p.displacementMap,g.displacementMapTransform),g.displacementScale.value=p.displacementScale,g.displacementBias.value=p.displacementBias),p.emissiveMap&&(g.emissiveMap.value=p.emissiveMap,t(p.emissiveMap,g.emissiveMapTransform)),p.specularMap&&(g.specularMap.value=p.specularMap,t(p.specularMap,g.specularMapTransform)),p.alphaTest>0&&(g.alphaTest.value=p.alphaTest);let v=e.get(p),y=v.envMap,x=v.envMapRotation;y&&(g.envMap.value=y,ks.copy(x),ks.x*=-1,ks.y*=-1,ks.z*=-1,y.isCubeTexture&&y.isRenderTargetTexture===!1&&(ks.y*=-1,ks.z*=-1),g.envMapRotation.value.setFromMatrix4(ZM.makeRotationFromEuler(ks)),g.flipEnvMap.value=y.isCubeTexture&&y.isRenderTargetTexture===!1?-1:1,g.reflectivity.value=p.reflectivity,g.ior.value=p.ior,g.refractionRatio.value=p.refractionRatio),p.lightMap&&(g.lightMap.value=p.lightMap,g.lightMapIntensity.value=p.lightMapIntensity,t(p.lightMap,g.lightMapTransform)),p.aoMap&&(g.aoMap.value=p.aoMap,g.aoMapIntensity.value=p.aoMapIntensity,t(p.aoMap,g.aoMapTransform))}function o(g,p){g.diffuse.value.copy(p.color),g.opacity.value=p.opacity,p.map&&(g.map.value=p.map,t(p.map,g.mapTransform))}function a(g,p){g.dashSize.value=p.dashSize,g.totalSize.value=p.dashSize+p.gapSize,g.scale.value=p.scale}function c(g,p,v,y){g.diffuse.value.copy(p.color),g.opacity.value=p.opacity,g.size.value=p.size*v,g.scale.value=y*.5,p.map&&(g.map.value=p.map,t(p.map,g.uvTransform)),p.alphaMap&&(g.alphaMap.value=p.alphaMap,t(p.alphaMap,g.alphaMapTransform)),p.alphaTest>0&&(g.alphaTest.value=p.alphaTest)}function l(g,p){g.diffuse.value.copy(p.color),g.opacity.value=p.opacity,g.rotation.value=p.rotation,p.map&&(g.map.value=p.map,t(p.map,g.mapTransform)),p.alphaMap&&(g.alphaMap.value=p.alphaMap,t(p.alphaMap,g.alphaMapTransform)),p.alphaTest>0&&(g.alphaTest.value=p.alphaTest)}function h(g,p){g.specular.value.copy(p.specular),g.shininess.value=Math.max(p.shininess,1e-4)}function u(g,p){p.gradientMap&&(g.gradientMap.value=p.gradientMap)}function d(g,p){g.metalness.value=p.metalness,p.metalnessMap&&(g.metalnessMap.value=p.metalnessMap,t(p.metalnessMap,g.metalnessMapTransform)),g.roughness.value=p.roughness,p.roughnessMap&&(g.roughnessMap.value=p.roughnessMap,t(p.roughnessMap,g.roughnessMapTransform)),p.envMap&&(g.envMapIntensity.value=p.envMapIntensity)}function f(g,p,v){g.ior.value=p.ior,p.sheen>0&&(g.sheenColor.value.copy(p.sheenColor).multiplyScalar(p.sheen),g.sheenRoughness.value=p.sheenRoughness,p.sheenColorMap&&(g.sheenColorMap.value=p.sheenColorMap,t(p.sheenColorMap,g.sheenColorMapTransform)),p.sheenRoughnessMap&&(g.sheenRoughnessMap.value=p.sheenRoughnessMap,t(p.sheenRoughnessMap,g.sheenRoughnessMapTransform))),p.clearcoat>0&&(g.clearcoat.value=p.clearcoat,g.clearcoatRoughness.value=p.clearcoatRoughness,p.clearcoatMap&&(g.clearcoatMap.value=p.clearcoatMap,t(p.clearcoatMap,g.clearcoatMapTransform)),p.clearcoatRoughnessMap&&(g.clearcoatRoughnessMap.value=p.clearcoatRoughnessMap,t(p.clearcoatRoughnessMap,g.clearcoatRoughnessMapTransform)),p.clearcoatNormalMap&&(g.clearcoatNormalMap.value=p.clearcoatNormalMap,t(p.clearcoatNormalMap,g.clearcoatNormalMapTransform),g.clearcoatNormalScale.value.copy(p.clearcoatNormalScale),p.side===Wt&&g.clearcoatNormalScale.value.negate())),p.dispersion>0&&(g.dispersion.value=p.dispersion),p.iridescence>0&&(g.iridescence.value=p.iridescence,g.iridescenceIOR.value=p.iridescenceIOR,g.iridescenceThicknessMinimum.value=p.iridescenceThicknessRange[0],g.iridescenceThicknessMaximum.value=p.iridescenceThicknessRange[1],p.iridescenceMap&&(g.iridescenceMap.value=p.iridescenceMap,t(p.iridescenceMap,g.iridescenceMapTransform)),p.iridescenceThicknessMap&&(g.iridescenceThicknessMap.value=p.iridescenceThicknessMap,t(p.iridescenceThicknessMap,g.iridescenceThicknessMapTransform))),p.transmission>0&&(g.transmission.value=p.transmission,g.transmissionSamplerMap.value=v.texture,g.transmissionSamplerSize.value.set(v.width,v.height),p.transmissionMap&&(g.transmissionMap.value=p.transmissionMap,t(p.transmissionMap,g.transmissionMapTransform)),g.thickness.value=p.thickness,p.thicknessMap&&(g.thicknessMap.value=p.thicknessMap,t(p.thicknessMap,g.thicknessMapTransform)),g.attenuationDistance.value=p.attenuationDistance,g.attenuationColor.value.copy(p.attenuationColor)),p.anisotropy>0&&(g.anisotropyVector.value.set(p.anisotropy*Math.cos(p.anisotropyRotation),p.anisotropy*Math.sin(p.anisotropyRotation)),p.anisotropyMap&&(g.anisotropyMap.value=p.anisotropyMap,t(p.anisotropyMap,g.anisotropyMapTransform))),g.specularIntensity.value=p.specularIntensity,g.specularColor.value.copy(p.specularColor),p.specularColorMap&&(g.specularColorMap.value=p.specularColorMap,t(p.specularColorMap,g.specularColorMapTransform)),p.specularIntensityMap&&(g.specularIntensityMap.value=p.specularIntensityMap,t(p.specularIntensityMap,g.specularIntensityMapTransform))}function m(g,p){p.matcap&&(g.matcap.value=p.matcap)}function _(g,p){let v=e.get(p).light;g.referencePosition.value.setFromMatrixPosition(v.matrixWorld),g.nearDistance.value=v.shadow.camera.near,g.farDistance.value=v.shadow.camera.far}return{refreshFogUniforms:n,refreshMaterialUniforms:i}}function JM(r,e,t,n){let i={},s={},o=[],a=r.getParameter(r.MAX_UNIFORM_BUFFER_BINDINGS);function c(v,y){let x=y.program;n.uniformBlockBinding(v,x)}function l(v,y){let x=i[v.id];x===void 0&&(m(v),x=h(v),i[v.id]=x,v.addEventListener("dispose",g));let A=y.program;n.updateUBOMapping(v,A);let E=e.render.frame;s[v.id]!==E&&(d(v),s[v.id]=E)}function h(v){let y=u();v.__bindingPointIndex=y;let x=r.createBuffer(),A=v.__size,E=v.usage;return r.bindBuffer(r.UNIFORM_BUFFER,x),r.bufferData(r.UNIFORM_BUFFER,A,E),r.bindBuffer(r.UNIFORM_BUFFER,null),r.bindBufferBase(r.UNIFORM_BUFFER,y,x),x}function u(){for(let v=0;v<a;v++)if(o.indexOf(v)===-1)return o.push(v),v;return console.error("THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function d(v){let y=i[v.id],x=v.uniforms,A=v.__cache;r.bindBuffer(r.UNIFORM_BUFFER,y);for(let E=0,C=x.length;E<C;E++){let I=Array.isArray(x[E])?x[E]:[x[E]];for(let b=0,S=I.length;b<S;b++){let L=I[b];if(f(L,E,b,A)===!0){let F=L.__offset,z=Array.isArray(L.value)?L.value:[L.value],G=0;for(let q=0;q<z.length;q++){let W=z[q],ne=_(W);typeof W=="number"||typeof W=="boolean"?(L.__data[0]=W,r.bufferSubData(r.UNIFORM_BUFFER,F+G,L.__data)):W.isMatrix3?(L.__data[0]=W.elements[0],L.__data[1]=W.elements[1],L.__data[2]=W.elements[2],L.__data[3]=0,L.__data[4]=W.elements[3],L.__data[5]=W.elements[4],L.__data[6]=W.elements[5],L.__data[7]=0,L.__data[8]=W.elements[6],L.__data[9]=W.elements[7],L.__data[10]=W.elements[8],L.__data[11]=0):(W.toArray(L.__data,G),G+=ne.storage/Float32Array.BYTES_PER_ELEMENT)}r.bufferSubData(r.UNIFORM_BUFFER,F,L.__data)}}}r.bindBuffer(r.UNIFORM_BUFFER,null)}function f(v,y,x,A){let E=v.value,C=y+"_"+x;if(A[C]===void 0)return typeof E=="number"||typeof E=="boolean"?A[C]=E:A[C]=E.clone(),!0;{let I=A[C];if(typeof E=="number"||typeof E=="boolean"){if(I!==E)return A[C]=E,!0}else if(I.equals(E)===!1)return I.copy(E),!0}return!1}function m(v){let y=v.uniforms,x=0,A=16;for(let C=0,I=y.length;C<I;C++){let b=Array.isArray(y[C])?y[C]:[y[C]];for(let S=0,L=b.length;S<L;S++){let F=b[S],z=Array.isArray(F.value)?F.value:[F.value];for(let G=0,q=z.length;G<q;G++){let W=z[G],ne=_(W),H=x%A,de=H%ne.boundary,xe=H+de;x+=de,xe!==0&&A-xe<ne.storage&&(x+=A-xe),F.__data=new Float32Array(ne.storage/Float32Array.BYTES_PER_ELEMENT),F.__offset=x,x+=ne.storage}}}let E=x%A;return E>0&&(x+=A-E),v.__size=x,v.__cache={},this}function _(v){let y={boundary:0,storage:0};return typeof v=="number"||typeof v=="boolean"?(y.boundary=4,y.storage=4):v.isVector2?(y.boundary=8,y.storage=8):v.isVector3||v.isColor?(y.boundary=16,y.storage=12):v.isVector4?(y.boundary=16,y.storage=16):v.isMatrix3?(y.boundary=48,y.storage=48):v.isMatrix4?(y.boundary=64,y.storage=64):v.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",v),y}function g(v){let y=v.target;y.removeEventListener("dispose",g);let x=o.indexOf(y.__bindingPointIndex);o.splice(x,1),r.deleteBuffer(i[y.id]),delete i[y.id],delete s[y.id]}function p(){for(let v in i)r.deleteBuffer(i[v]);o=[],i={},s={}}return{bind:c,update:l,dispose:p}}var tf=class{constructor(e={}){let{canvas:t=Dd(),context:n=null,depth:i=!0,stencil:s=!1,alpha:o=!1,antialias:a=!1,premultipliedAlpha:c=!0,preserveDrawingBuffer:l=!1,powerPreference:h="default",failIfMajorPerformanceCaveat:u=!1,reversedDepthBuffer:d=!1}=e;this.isWebGLRenderer=!0;let f;if(n!==null){if(typeof WebGLRenderingContext<"u"&&n instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");f=n.getContextAttributes().alpha}else f=o;let m=new Uint32Array(4),_=new Int32Array(4),g=null,p=null,v=[],y=[];this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=ni,this.toneMappingExposure=1,this.transmissionResolutionScale=1;let x=this,A=!1;this._outputColorSpace=wt;let E=0,C=0,I=null,b=-1,S=null,L=new tt,F=new tt,z=null,G=new ue(0),q=0,W=t.width,ne=t.height,H=1,de=null,xe=null,Se=new tt(0,0,W,ne),We=new tt(0,0,W,ne),et=!1,at=new _i,nt=!1,Z=!1,te=new De,Me=new w,Pe=new tt,Ee={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0},Je=!1;function ut(){return I===null?H:1}let P=n;function ee(T,N){return t.getContext(T,N)}try{let T={alpha:!0,depth:i,stencil:s,antialias:a,premultipliedAlpha:c,preserveDrawingBuffer:l,powerPreference:h,failIfMajorPerformanceCaveat:u};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${"180"}`),t.addEventListener("webglcontextlost",fe,!1),t.addEventListener("webglcontextrestored",be,!1),t.addEventListener("webglcontextcreationerror",re,!1),P===null){let N="webgl2";if(P=ee(N,T),P===null)throw ee(N)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(T){throw console.error("THREE.WebGLRenderer: "+T.message),T}let $,J,K,le,ie,he,He,ke,R,M,O,V,Q,X,Ce,ce,Ae,we,se,_e,Oe,Ie,me,qe;function D(){$=new mv(P),$.init(),Ie=new mg(P,$),J=new cv(P,$,e,Ie),K=new WM(P,$),J.reversedDepthBuffer&&d&&K.buffers.depth.setReversed(!0),le=new xv(P),ie=new PM,he=new XM(P,$,K,ie,J,Ie,le),He=new hv(x),ke=new pv(x),R=new Tx(P),me=new ov(P,R),M=new gv(P,R,le,me),O=new vv(P,M,R,le),se=new yv(P,J,he),ce=new lv(ie),V=new IM(x,He,ke,$,J,me,ce),Q=new KM(x,ie),X=new DM,Ce=new zM($),we=new rv(x,He,ke,K,O,f,c),Ae=new HM(x,O,J),qe=new JM(P,le,J,K),_e=new av(P,$,le),Oe=new _v(P,$,le),le.programs=V.programs,x.capabilities=J,x.extensions=$,x.properties=ie,x.renderLists=X,x.shadowMap=Ae,x.state=K,x.info=le}D();let ae=new ef(x,P);this.xr=ae,this.getContext=function(){return P},this.getContextAttributes=function(){return P.getContextAttributes()},this.forceContextLoss=function(){let T=$.get("WEBGL_lose_context");T&&T.loseContext()},this.forceContextRestore=function(){let T=$.get("WEBGL_lose_context");T&&T.restoreContext()},this.getPixelRatio=function(){return H},this.setPixelRatio=function(T){T!==void 0&&(H=T,this.setSize(W,ne,!1))},this.getSize=function(T){return T.set(W,ne)},this.setSize=function(T,N,B=!0){if(ae.isPresenting){console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting.");return}W=T,ne=N,t.width=Math.floor(T*H),t.height=Math.floor(N*H),B===!0&&(t.style.width=T+"px",t.style.height=N+"px"),this.setViewport(0,0,T,N)},this.getDrawingBufferSize=function(T){return T.set(W*H,ne*H).floor()},this.setDrawingBufferSize=function(T,N,B){W=T,ne=N,H=B,t.width=Math.floor(T*B),t.height=Math.floor(N*B),this.setViewport(0,0,T,N)},this.getCurrentViewport=function(T){return T.copy(L)},this.getViewport=function(T){return T.copy(Se)},this.setViewport=function(T,N,B,k){T.isVector4?Se.set(T.x,T.y,T.z,T.w):Se.set(T,N,B,k),K.viewport(L.copy(Se).multiplyScalar(H).round())},this.getScissor=function(T){return T.copy(We)},this.setScissor=function(T,N,B,k){T.isVector4?We.set(T.x,T.y,T.z,T.w):We.set(T,N,B,k),K.scissor(F.copy(We).multiplyScalar(H).round())},this.getScissorTest=function(){return et},this.setScissorTest=function(T){K.setScissorTest(et=T)},this.setOpaqueSort=function(T){de=T},this.setTransparentSort=function(T){xe=T},this.getClearColor=function(T){return T.copy(we.getClearColor())},this.setClearColor=function(){we.setClearColor(...arguments)},this.getClearAlpha=function(){return we.getClearAlpha()},this.setClearAlpha=function(){we.setClearAlpha(...arguments)},this.clear=function(T=!0,N=!0,B=!0){let k=0;if(T){let U=!1;if(I!==null){let oe=I.texture.format;U=oe===Wa||oe===Ga||oe===Yr}if(U){let oe=I.texture.type,ge=oe===Cn||oe===si||oe===Ds||oe===Us||oe===ka||oe===Va,Te=we.getClearColor(),ve=we.getClearAlpha(),Ue=Te.r,Be=Te.g,Le=Te.b;ge?(m[0]=Ue,m[1]=Be,m[2]=Le,m[3]=ve,P.clearBufferuiv(P.COLOR,0,m)):(_[0]=Ue,_[1]=Be,_[2]=Le,_[3]=ve,P.clearBufferiv(P.COLOR,0,_))}else k|=P.COLOR_BUFFER_BIT}N&&(k|=P.DEPTH_BUFFER_BIT),B&&(k|=P.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),P.clear(k)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){t.removeEventListener("webglcontextlost",fe,!1),t.removeEventListener("webglcontextrestored",be,!1),t.removeEventListener("webglcontextcreationerror",re,!1),we.dispose(),X.dispose(),Ce.dispose(),ie.dispose(),He.dispose(),ke.dispose(),O.dispose(),me.dispose(),qe.dispose(),V.dispose(),ae.dispose(),ae.removeEventListener("sessionstart",Xn),ae.removeEventListener("sessionend",Of),Zi.stop()};function fe(T){T.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),A=!0}function be(){console.log("THREE.WebGLRenderer: Context Restored."),A=!1;let T=le.autoReset,N=Ae.enabled,B=Ae.autoUpdate,k=Ae.needsUpdate,U=Ae.type;D(),le.autoReset=T,Ae.enabled=N,Ae.autoUpdate=B,Ae.needsUpdate=k,Ae.type=U}function re(T){console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ",T.statusMessage)}function j(T){let N=T.target;N.removeEventListener("dispose",j),Re(N)}function Re(T){Ge(T),ie.remove(T)}function Ge(T){let N=ie.get(T).programs;N!==void 0&&(N.forEach(function(B){V.releaseProgram(B)}),T.isShaderMaterial&&V.releaseShaderCache(T))}this.renderBufferDirect=function(T,N,B,k,U,oe){N===null&&(N=Ee);let ge=U.isMesh&&U.matrixWorld.determinant()<0,Te=Tg(T,N,B,k,U);K.setMaterial(k,ge);let ve=B.index,Ue=1;if(k.wireframe===!0){if(ve=M.getWireframeAttribute(B),ve===void 0)return;Ue=2}let Be=B.drawRange,Le=B.attributes.position,$e=Be.start*Ue,ct=(Be.start+Be.count)*Ue;oe!==null&&($e=Math.max($e,oe.start*Ue),ct=Math.min(ct,(oe.start+oe.count)*Ue)),ve!==null?($e=Math.max($e,0),ct=Math.min(ct,ve.count)):Le!=null&&($e=Math.max($e,0),ct=Math.min(ct,Le.count));let St=ct-$e;if(St<0||St===1/0)return;me.setup(U,k,Te,B,ve);let ft,ht=_e;if(ve!==null&&(ft=R.get(ve),ht=Oe,ht.setIndex(ft)),U.isMesh)k.wireframe===!0?(K.setLineWidth(k.wireframeLinewidth*ut()),ht.setMode(P.LINES)):ht.setMode(P.TRIANGLES);else if(U.isLine){let Ne=k.linewidth;Ne===void 0&&(Ne=1),K.setLineWidth(Ne*ut()),U.isLineSegments?ht.setMode(P.LINES):U.isLineLoop?ht.setMode(P.LINE_LOOP):ht.setMode(P.LINE_STRIP)}else U.isPoints?ht.setMode(P.POINTS):U.isSprite&&ht.setMode(P.TRIANGLES);if(U.isBatchedMesh)if(U._multiDrawInstances!==null)_r("THREE.WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),ht.renderMultiDrawInstances(U._multiDrawStarts,U._multiDrawCounts,U._multiDrawCount,U._multiDrawInstances);else if($.get("WEBGL_multi_draw"))ht.renderMultiDraw(U._multiDrawStarts,U._multiDrawCounts,U._multiDrawCount);else{let Ne=U._multiDrawStarts,_t=U._multiDrawCounts,it=U._multiDrawCount,hn=ve?R.get(ve).bytesPerElement:1,Ws=ie.get(k).currentProgram.getUniforms();for(let un=0;un<it;un++)Ws.setValue(P,"_gl_DrawID",un),ht.render(Ne[un]/hn,_t[un])}else if(U.isInstancedMesh)ht.renderInstances($e,St,U.count);else if(B.isInstancedBufferGeometry){let Ne=B._maxInstanceCount!==void 0?B._maxInstanceCount:1/0,_t=Math.min(B.instanceCount,Ne);ht.renderInstances($e,St,_t)}else ht.render($e,St)};function dt(T,N,B){T.transparent===!0&&T.side===Mn&&T.forceSinglePass===!1?(T.side=Wt,T.needsUpdate=!0,Tc(T,N,B),T.side=An,T.needsUpdate=!0,Tc(T,N,B),T.side=Mn):Tc(T,N,B)}this.compile=function(T,N,B=null){B===null&&(B=T),p=Ce.get(B),p.init(N),y.push(p),B.traverseVisible(function(U){U.isLight&&U.layers.test(N.layers)&&(p.pushLight(U),U.castShadow&&p.pushShadow(U))}),T!==B&&T.traverseVisible(function(U){U.isLight&&U.layers.test(N.layers)&&(p.pushLight(U),U.castShadow&&p.pushShadow(U))}),p.setupLights();let k=new Set;return T.traverse(function(U){if(!(U.isMesh||U.isPoints||U.isLine||U.isSprite))return;let oe=U.material;if(oe)if(Array.isArray(oe))for(let ge=0;ge<oe.length;ge++){let Te=oe[ge];dt(Te,B,U),k.add(Te)}else dt(oe,B,U),k.add(oe)}),p=y.pop(),k},this.compileAsync=function(T,N,B=null){let k=this.compile(T,N,B);return new Promise(U=>{function oe(){if(k.forEach(function(ge){ie.get(ge).currentProgram.isReady()&&k.delete(ge)}),k.size===0){U(T);return}setTimeout(oe,10)}$.get("KHR_parallel_shader_compile")!==null?oe():setTimeout(oe,10)})};let rt=null;function ai(T){rt&&rt(T)}function Xn(){Zi.stop()}function Of(){Zi.start()}let Zi=new hg;Zi.setAnimationLoop(ai),typeof self<"u"&&Zi.setContext(self),this.setAnimationLoop=function(T){rt=T,ae.setAnimationLoop(T),T===null?Zi.stop():Zi.start()},ae.addEventListener("sessionstart",Xn),ae.addEventListener("sessionend",Of),this.render=function(T,N){if(N!==void 0&&N.isCamera!==!0){console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(A===!0)return;if(T.matrixWorldAutoUpdate===!0&&T.updateMatrixWorld(),N.parent===null&&N.matrixWorldAutoUpdate===!0&&N.updateMatrixWorld(),ae.enabled===!0&&ae.isPresenting===!0&&(ae.cameraAutoUpdate===!0&&ae.updateCamera(N),N=ae.getCamera()),T.isScene===!0&&T.onBeforeRender(x,T,N,I),p=Ce.get(T,y.length),p.init(N),y.push(p),te.multiplyMatrices(N.projectionMatrix,N.matrixWorldInverse),at.setFromProjectionMatrix(te,sn,N.reversedDepth),Z=this.localClippingEnabled,nt=ce.init(this.clippingPlanes,Z),g=X.get(T,v.length),g.init(),v.push(g),ae.enabled===!0&&ae.isPresenting===!0){let oe=x.xr.getDepthSensingMesh();oe!==null&&Hh(oe,N,-1/0,x.sortObjects)}Hh(T,N,0,x.sortObjects),g.finish(),x.sortObjects===!0&&g.sort(de,xe),Je=ae.enabled===!1||ae.isPresenting===!1||ae.hasDepthSensing()===!1,Je&&we.addToRenderList(g,T),this.info.render.frame++,nt===!0&&ce.beginShadows();let B=p.state.shadowsArray;Ae.render(B,T,N),nt===!0&&ce.endShadows(),this.info.autoReset===!0&&this.info.reset();let k=g.opaque,U=g.transmissive;if(p.setupLights(),N.isArrayCamera){let oe=N.cameras;if(U.length>0)for(let ge=0,Te=oe.length;ge<Te;ge++){let ve=oe[ge];zf(k,U,T,ve)}Je&&we.render(T);for(let ge=0,Te=oe.length;ge<Te;ge++){let ve=oe[ge];Bf(g,T,ve,ve.viewport)}}else U.length>0&&zf(k,U,T,N),Je&&we.render(T),Bf(g,T,N);I!==null&&C===0&&(he.updateMultisampleRenderTarget(I),he.updateRenderTargetMipmap(I)),T.isScene===!0&&T.onAfterRender(x,T,N),me.resetDefaultState(),b=-1,S=null,y.pop(),y.length>0?(p=y[y.length-1],nt===!0&&ce.setGlobalState(x.clippingPlanes,p.state.camera)):p=null,v.pop(),v.length>0?g=v[v.length-1]:g=null};function Hh(T,N,B,k){if(T.visible===!1)return;if(T.layers.test(N.layers)){if(T.isGroup)B=T.renderOrder;else if(T.isLOD)T.autoUpdate===!0&&T.update(N);else if(T.isLight)p.pushLight(T),T.castShadow&&p.pushShadow(T);else if(T.isSprite){if(!T.frustumCulled||at.intersectsSprite(T)){k&&Pe.setFromMatrixPosition(T.matrixWorld).applyMatrix4(te);let ge=O.update(T),Te=T.material;Te.visible&&g.push(T,ge,Te,B,Pe.z,null)}}else if((T.isMesh||T.isLine||T.isPoints)&&(!T.frustumCulled||at.intersectsObject(T))){let ge=O.update(T),Te=T.material;if(k&&(T.boundingSphere!==void 0?(T.boundingSphere===null&&T.computeBoundingSphere(),Pe.copy(T.boundingSphere.center)):(ge.boundingSphere===null&&ge.computeBoundingSphere(),Pe.copy(ge.boundingSphere.center)),Pe.applyMatrix4(T.matrixWorld).applyMatrix4(te)),Array.isArray(Te)){let ve=ge.groups;for(let Ue=0,Be=ve.length;Ue<Be;Ue++){let Le=ve[Ue],$e=Te[Le.materialIndex];$e&&$e.visible&&g.push(T,ge,$e,B,Pe.z,Le)}}else Te.visible&&g.push(T,ge,Te,B,Pe.z,null)}}let oe=T.children;for(let ge=0,Te=oe.length;ge<Te;ge++)Hh(oe[ge],N,B,k)}function Bf(T,N,B,k){let U=T.opaque,oe=T.transmissive,ge=T.transparent;p.setupLightsView(B),nt===!0&&ce.setGlobalState(x.clippingPlanes,B),k&&K.viewport(L.copy(k)),U.length>0&&bc(U,N,B),oe.length>0&&bc(oe,N,B),ge.length>0&&bc(ge,N,B),K.buffers.depth.setTest(!0),K.buffers.depth.setMask(!0),K.buffers.color.setMask(!0),K.setPolygonOffset(!1)}function zf(T,N,B,k){if((B.isScene===!0?B.overrideMaterial:null)!==null)return;p.state.transmissionRenderTarget[k.id]===void 0&&(p.state.transmissionRenderTarget[k.id]=new yn(1,1,{generateMipmaps:!0,type:$.has("EXT_color_buffer_half_float")||$.has("EXT_color_buffer_float")?Ns:Cn,minFilter:cn,samples:4,stencilBuffer:s,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:Ze.workingColorSpace}));let oe=p.state.transmissionRenderTarget[k.id],ge=k.viewport||L;oe.setSize(ge.z*x.transmissionResolutionScale,ge.w*x.transmissionResolutionScale);let Te=x.getRenderTarget(),ve=x.getActiveCubeFace(),Ue=x.getActiveMipmapLevel();x.setRenderTarget(oe),x.getClearColor(G),q=x.getClearAlpha(),q<1&&x.setClearColor(16777215,.5),x.clear(),Je&&we.render(B);let Be=x.toneMapping;x.toneMapping=ni;let Le=k.viewport;if(k.viewport!==void 0&&(k.viewport=void 0),p.setupLightsView(k),nt===!0&&ce.setGlobalState(x.clippingPlanes,k),bc(T,B,k),he.updateMultisampleRenderTarget(oe),he.updateRenderTargetMipmap(oe),$.has("WEBGL_multisampled_render_to_texture")===!1){let $e=!1;for(let ct=0,St=N.length;ct<St;ct++){let ft=N[ct],ht=ft.object,Ne=ft.geometry,_t=ft.material,it=ft.group;if(_t.side===Mn&&ht.layers.test(k.layers)){let hn=_t.side;_t.side=Wt,_t.needsUpdate=!0,kf(ht,B,k,Ne,_t,it),_t.side=hn,_t.needsUpdate=!0,$e=!0}}$e===!0&&(he.updateMultisampleRenderTarget(oe),he.updateRenderTargetMipmap(oe))}x.setRenderTarget(Te,ve,Ue),x.setClearColor(G,q),Le!==void 0&&(k.viewport=Le),x.toneMapping=Be}function bc(T,N,B){let k=N.isScene===!0?N.overrideMaterial:null;for(let U=0,oe=T.length;U<oe;U++){let ge=T[U],Te=ge.object,ve=ge.geometry,Ue=ge.group,Be=ge.material;Be.allowOverride===!0&&k!==null&&(Be=k),Te.layers.test(B.layers)&&kf(Te,N,B,ve,Be,Ue)}}function kf(T,N,B,k,U,oe){T.onBeforeRender(x,N,B,k,U,oe),T.modelViewMatrix.multiplyMatrices(B.matrixWorldInverse,T.matrixWorld),T.normalMatrix.getNormalMatrix(T.modelViewMatrix),U.onBeforeRender(x,N,B,k,T,oe),U.transparent===!0&&U.side===Mn&&U.forceSinglePass===!1?(U.side=Wt,U.needsUpdate=!0,x.renderBufferDirect(B,N,k,U,T,oe),U.side=An,U.needsUpdate=!0,x.renderBufferDirect(B,N,k,U,T,oe),U.side=Mn):x.renderBufferDirect(B,N,k,U,T,oe),T.onAfterRender(x,N,B,k,U,oe)}function Tc(T,N,B){N.isScene!==!0&&(N=Ee);let k=ie.get(T),U=p.state.lights,oe=p.state.shadowsArray,ge=U.state.version,Te=V.getParameters(T,U.state,oe,N,B),ve=V.getProgramCacheKey(Te),Ue=k.programs;k.environment=T.isMeshStandardMaterial?N.environment:null,k.fog=N.fog,k.envMap=(T.isMeshStandardMaterial?ke:He).get(T.envMap||k.environment),k.envMapRotation=k.environment!==null&&T.envMap===null?N.environmentRotation:T.envMapRotation,Ue===void 0&&(T.addEventListener("dispose",j),Ue=new Map,k.programs=Ue);let Be=Ue.get(ve);if(Be!==void 0){if(k.currentProgram===Be&&k.lightsStateVersion===ge)return Hf(T,Te),Be}else Te.uniforms=V.getUniforms(T),T.onBeforeCompile(Te,x),Be=V.acquireProgram(Te,ve),Ue.set(ve,Be),k.uniforms=Te.uniforms;let Le=k.uniforms;return(!T.isShaderMaterial&&!T.isRawShaderMaterial||T.clipping===!0)&&(Le.clippingPlanes=ce.uniform),Hf(T,Te),k.needsLights=Ag(T),k.lightsStateVersion=ge,k.needsLights&&(Le.ambientLightColor.value=U.state.ambient,Le.lightProbe.value=U.state.probe,Le.directionalLights.value=U.state.directional,Le.directionalLightShadows.value=U.state.directionalShadow,Le.spotLights.value=U.state.spot,Le.spotLightShadows.value=U.state.spotShadow,Le.rectAreaLights.value=U.state.rectArea,Le.ltc_1.value=U.state.rectAreaLTC1,Le.ltc_2.value=U.state.rectAreaLTC2,Le.pointLights.value=U.state.point,Le.pointLightShadows.value=U.state.pointShadow,Le.hemisphereLights.value=U.state.hemi,Le.directionalShadowMap.value=U.state.directionalShadowMap,Le.directionalShadowMatrix.value=U.state.directionalShadowMatrix,Le.spotShadowMap.value=U.state.spotShadowMap,Le.spotLightMatrix.value=U.state.spotLightMatrix,Le.spotLightMap.value=U.state.spotLightMap,Le.pointShadowMap.value=U.state.pointShadowMap,Le.pointShadowMatrix.value=U.state.pointShadowMatrix),k.currentProgram=Be,k.uniformsList=null,Be}function Vf(T){if(T.uniformsList===null){let N=T.currentProgram.getUniforms();T.uniformsList=no.seqWithValue(N.seq,T.uniforms)}return T.uniformsList}function Hf(T,N){let B=ie.get(T);B.outputColorSpace=N.outputColorSpace,B.batching=N.batching,B.batchingColor=N.batchingColor,B.instancing=N.instancing,B.instancingColor=N.instancingColor,B.instancingMorph=N.instancingMorph,B.skinning=N.skinning,B.morphTargets=N.morphTargets,B.morphNormals=N.morphNormals,B.morphColors=N.morphColors,B.morphTargetsCount=N.morphTargetsCount,B.numClippingPlanes=N.numClippingPlanes,B.numIntersection=N.numClipIntersection,B.vertexAlphas=N.vertexAlphas,B.vertexTangents=N.vertexTangents,B.toneMapping=N.toneMapping}function Tg(T,N,B,k,U){N.isScene!==!0&&(N=Ee),he.resetTextureUnits();let oe=N.fog,ge=k.isMeshStandardMaterial?N.environment:null,Te=I===null?x.outputColorSpace:I.isXRRenderTarget===!0?I.texture.colorSpace:Ot,ve=(k.isMeshStandardMaterial?ke:He).get(k.envMap||ge),Ue=k.vertexColors===!0&&!!B.attributes.color&&B.attributes.color.itemSize===4,Be=!!B.attributes.tangent&&(!!k.normalMap||k.anisotropy>0),Le=!!B.morphAttributes.position,$e=!!B.morphAttributes.normal,ct=!!B.morphAttributes.color,St=ni;k.toneMapped&&(I===null||I.isXRRenderTarget===!0)&&(St=x.toneMapping);let ft=B.morphAttributes.position||B.morphAttributes.normal||B.morphAttributes.color,ht=ft!==void 0?ft.length:0,Ne=ie.get(k),_t=p.state.lights;if(nt===!0&&(Z===!0||T!==S)){let qt=T===S&&k.id===b;ce.setState(k,T,qt)}let it=!1;k.version===Ne.__version?(Ne.needsLights&&Ne.lightsStateVersion!==_t.state.version||Ne.outputColorSpace!==Te||U.isBatchedMesh&&Ne.batching===!1||!U.isBatchedMesh&&Ne.batching===!0||U.isBatchedMesh&&Ne.batchingColor===!0&&U.colorTexture===null||U.isBatchedMesh&&Ne.batchingColor===!1&&U.colorTexture!==null||U.isInstancedMesh&&Ne.instancing===!1||!U.isInstancedMesh&&Ne.instancing===!0||U.isSkinnedMesh&&Ne.skinning===!1||!U.isSkinnedMesh&&Ne.skinning===!0||U.isInstancedMesh&&Ne.instancingColor===!0&&U.instanceColor===null||U.isInstancedMesh&&Ne.instancingColor===!1&&U.instanceColor!==null||U.isInstancedMesh&&Ne.instancingMorph===!0&&U.morphTexture===null||U.isInstancedMesh&&Ne.instancingMorph===!1&&U.morphTexture!==null||Ne.envMap!==ve||k.fog===!0&&Ne.fog!==oe||Ne.numClippingPlanes!==void 0&&(Ne.numClippingPlanes!==ce.numPlanes||Ne.numIntersection!==ce.numIntersection)||Ne.vertexAlphas!==Ue||Ne.vertexTangents!==Be||Ne.morphTargets!==Le||Ne.morphNormals!==$e||Ne.morphColors!==ct||Ne.toneMapping!==St||Ne.morphTargetsCount!==ht)&&(it=!0):(it=!0,Ne.__version=k.version);let hn=Ne.currentProgram;it===!0&&(hn=Tc(k,N,U));let Ws=!1,un=!1,ro=!1,xt=hn.getUniforms(),Sn=Ne.uniforms;if(K.useProgram(hn.program)&&(Ws=!0,un=!0,ro=!0),k.id!==b&&(b=k.id,un=!0),Ws||S!==T){K.buffers.depth.getReversed()&&T.reversedDepth!==!0&&(T._reversedDepth=!0,T.updateProjectionMatrix()),xt.setValue(P,"projectionMatrix",T.projectionMatrix),xt.setValue(P,"viewMatrix",T.matrixWorldInverse);let en=xt.map.cameraPosition;en!==void 0&&en.setValue(P,Me.setFromMatrixPosition(T.matrixWorld)),J.logarithmicDepthBuffer&&xt.setValue(P,"logDepthBufFC",2/(Math.log(T.far+1)/Math.LN2)),(k.isMeshPhongMaterial||k.isMeshToonMaterial||k.isMeshLambertMaterial||k.isMeshBasicMaterial||k.isMeshStandardMaterial||k.isShaderMaterial)&&xt.setValue(P,"isOrthographic",T.isOrthographicCamera===!0),S!==T&&(S=T,un=!0,ro=!0)}if(U.isSkinnedMesh){xt.setOptional(P,U,"bindMatrix"),xt.setOptional(P,U,"bindMatrixInverse");let qt=U.skeleton;qt&&(qt.boneTexture===null&&qt.computeBoneTexture(),xt.setValue(P,"boneTexture",qt.boneTexture,he))}U.isBatchedMesh&&(xt.setOptional(P,U,"batchingTexture"),xt.setValue(P,"batchingTexture",U._matricesTexture,he),xt.setOptional(P,U,"batchingIdTexture"),xt.setValue(P,"batchingIdTexture",U._indirectTexture,he),xt.setOptional(P,U,"batchingColorTexture"),U._colorsTexture!==null&&xt.setValue(P,"batchingColorTexture",U._colorsTexture,he));let bn=B.morphAttributes;if((bn.position!==void 0||bn.normal!==void 0||bn.color!==void 0)&&se.update(U,B,hn),(un||Ne.receiveShadow!==U.receiveShadow)&&(Ne.receiveShadow=U.receiveShadow,xt.setValue(P,"receiveShadow",U.receiveShadow)),k.isMeshGouraudMaterial&&k.envMap!==null&&(Sn.envMap.value=ve,Sn.flipEnvMap.value=ve.isCubeTexture&&ve.isRenderTargetTexture===!1?-1:1),k.isMeshStandardMaterial&&k.envMap===null&&N.environment!==null&&(Sn.envMapIntensity.value=N.environmentIntensity),un&&(xt.setValue(P,"toneMappingExposure",x.toneMappingExposure),Ne.needsLights&&Eg(Sn,ro),oe&&k.fog===!0&&Q.refreshFogUniforms(Sn,oe),Q.refreshMaterialUniforms(Sn,k,H,ne,p.state.transmissionRenderTarget[T.id]),no.upload(P,Vf(Ne),Sn,he)),k.isShaderMaterial&&k.uniformsNeedUpdate===!0&&(no.upload(P,Vf(Ne),Sn,he),k.uniformsNeedUpdate=!1),k.isSpriteMaterial&&xt.setValue(P,"center",U.center),xt.setValue(P,"modelViewMatrix",U.modelViewMatrix),xt.setValue(P,"normalMatrix",U.normalMatrix),xt.setValue(P,"modelMatrix",U.matrixWorld),k.isShaderMaterial||k.isRawShaderMaterial){let qt=k.uniformsGroups;for(let en=0,Gh=qt.length;en<Gh;en++){let Ki=qt[en];qe.update(Ki,hn),qe.bind(Ki,hn)}}return hn}function Eg(T,N){T.ambientLightColor.needsUpdate=N,T.lightProbe.needsUpdate=N,T.directionalLights.needsUpdate=N,T.directionalLightShadows.needsUpdate=N,T.pointLights.needsUpdate=N,T.pointLightShadows.needsUpdate=N,T.spotLights.needsUpdate=N,T.spotLightShadows.needsUpdate=N,T.rectAreaLights.needsUpdate=N,T.hemisphereLights.needsUpdate=N}function Ag(T){return T.isMeshLambertMaterial||T.isMeshToonMaterial||T.isMeshPhongMaterial||T.isMeshStandardMaterial||T.isShadowMaterial||T.isShaderMaterial&&T.lights===!0}this.getActiveCubeFace=function(){return E},this.getActiveMipmapLevel=function(){return C},this.getRenderTarget=function(){return I},this.setRenderTargetTextures=function(T,N,B){let k=ie.get(T);k.__autoAllocateDepthBuffer=T.resolveDepthBuffer===!1,k.__autoAllocateDepthBuffer===!1&&(k.__useRenderToTexture=!1),ie.get(T.texture).__webglTexture=N,ie.get(T.depthTexture).__webglTexture=k.__autoAllocateDepthBuffer?void 0:B,k.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(T,N){let B=ie.get(T);B.__webglFramebuffer=N,B.__useDefaultFramebuffer=N===void 0};let wg=P.createFramebuffer();this.setRenderTarget=function(T,N=0,B=0){I=T,E=N,C=B;let k=!0,U=null,oe=!1,ge=!1;if(T){let ve=ie.get(T);if(ve.__useDefaultFramebuffer!==void 0)K.bindFramebuffer(P.FRAMEBUFFER,null),k=!1;else if(ve.__webglFramebuffer===void 0)he.setupRenderTarget(T);else if(ve.__hasExternalTextures)he.rebindTextures(T,ie.get(T.texture).__webglTexture,ie.get(T.depthTexture).__webglTexture);else if(T.depthBuffer){let Le=T.depthTexture;if(ve.__boundDepthTexture!==Le){if(Le!==null&&ie.has(Le)&&(T.width!==Le.image.width||T.height!==Le.image.height))throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");he.setupDepthRenderbuffer(T)}}let Ue=T.texture;(Ue.isData3DTexture||Ue.isDataArrayTexture||Ue.isCompressedArrayTexture)&&(ge=!0);let Be=ie.get(T).__webglFramebuffer;T.isWebGLCubeRenderTarget?(Array.isArray(Be[N])?U=Be[N][B]:U=Be[N],oe=!0):T.samples>0&&he.useMultisampledRTT(T)===!1?U=ie.get(T).__webglMultisampledFramebuffer:Array.isArray(Be)?U=Be[B]:U=Be,L.copy(T.viewport),F.copy(T.scissor),z=T.scissorTest}else L.copy(Se).multiplyScalar(H).floor(),F.copy(We).multiplyScalar(H).floor(),z=et;if(B!==0&&(U=wg),K.bindFramebuffer(P.FRAMEBUFFER,U)&&k&&K.drawBuffers(T,U),K.viewport(L),K.scissor(F),K.setScissorTest(z),oe){let ve=ie.get(T.texture);P.framebufferTexture2D(P.FRAMEBUFFER,P.COLOR_ATTACHMENT0,P.TEXTURE_CUBE_MAP_POSITIVE_X+N,ve.__webglTexture,B)}else if(ge){let ve=N;for(let Ue=0;Ue<T.textures.length;Ue++){let Be=ie.get(T.textures[Ue]);P.framebufferTextureLayer(P.FRAMEBUFFER,P.COLOR_ATTACHMENT0+Ue,Be.__webglTexture,B,ve)}}else if(T!==null&&B!==0){let ve=ie.get(T.texture);P.framebufferTexture2D(P.FRAMEBUFFER,P.COLOR_ATTACHMENT0,P.TEXTURE_2D,ve.__webglTexture,B)}b=-1},this.readRenderTargetPixels=function(T,N,B,k,U,oe,ge,Te=0){if(!(T&&T.isWebGLRenderTarget)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let ve=ie.get(T).__webglFramebuffer;if(T.isWebGLCubeRenderTarget&&ge!==void 0&&(ve=ve[ge]),ve){K.bindFramebuffer(P.FRAMEBUFFER,ve);try{let Ue=T.textures[Te],Be=Ue.format,Le=Ue.type;if(!J.textureFormatReadable(Be)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!J.textureTypeReadable(Le)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}N>=0&&N<=T.width-k&&B>=0&&B<=T.height-U&&(T.textures.length>1&&P.readBuffer(P.COLOR_ATTACHMENT0+Te),P.readPixels(N,B,k,U,Ie.convert(Be),Ie.convert(Le),oe))}finally{let Ue=I!==null?ie.get(I).__webglFramebuffer:null;K.bindFramebuffer(P.FRAMEBUFFER,Ue)}}},this.readRenderTargetPixelsAsync=async function(T,N,B,k,U,oe,ge,Te=0){if(!(T&&T.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let ve=ie.get(T).__webglFramebuffer;if(T.isWebGLCubeRenderTarget&&ge!==void 0&&(ve=ve[ge]),ve)if(N>=0&&N<=T.width-k&&B>=0&&B<=T.height-U){K.bindFramebuffer(P.FRAMEBUFFER,ve);let Ue=T.textures[Te],Be=Ue.format,Le=Ue.type;if(!J.textureFormatReadable(Be))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!J.textureTypeReadable(Le))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");let $e=P.createBuffer();P.bindBuffer(P.PIXEL_PACK_BUFFER,$e),P.bufferData(P.PIXEL_PACK_BUFFER,oe.byteLength,P.STREAM_READ),T.textures.length>1&&P.readBuffer(P.COLOR_ATTACHMENT0+Te),P.readPixels(N,B,k,U,Ie.convert(Be),Ie.convert(Le),0);let ct=I!==null?ie.get(I).__webglFramebuffer:null;K.bindFramebuffer(P.FRAMEBUFFER,ct);let St=P.fenceSync(P.SYNC_GPU_COMMANDS_COMPLETE,0);return P.flush(),await Pm(P,St,4),P.bindBuffer(P.PIXEL_PACK_BUFFER,$e),P.getBufferSubData(P.PIXEL_PACK_BUFFER,0,oe),P.deleteBuffer($e),P.deleteSync(St),oe}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(T,N=null,B=0){let k=Math.pow(2,-B),U=Math.floor(T.image.width*k),oe=Math.floor(T.image.height*k),ge=N!==null?N.x:0,Te=N!==null?N.y:0;he.setTexture2D(T,0),P.copyTexSubImage2D(P.TEXTURE_2D,B,0,0,ge,Te,U,oe),K.unbindTexture()};let Rg=P.createFramebuffer(),Cg=P.createFramebuffer();this.copyTextureToTexture=function(T,N,B=null,k=null,U=0,oe=null){oe===null&&(U!==0?(_r("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),oe=U,U=0):oe=0);let ge,Te,ve,Ue,Be,Le,$e,ct,St,ft=T.isCompressedTexture?T.mipmaps[oe]:T.image;if(B!==null)ge=B.max.x-B.min.x,Te=B.max.y-B.min.y,ve=B.isBox3?B.max.z-B.min.z:1,Ue=B.min.x,Be=B.min.y,Le=B.isBox3?B.min.z:0;else{let bn=Math.pow(2,-U);ge=Math.floor(ft.width*bn),Te=Math.floor(ft.height*bn),T.isDataArrayTexture?ve=ft.depth:T.isData3DTexture?ve=Math.floor(ft.depth*bn):ve=1,Ue=0,Be=0,Le=0}k!==null?($e=k.x,ct=k.y,St=k.z):($e=0,ct=0,St=0);let ht=Ie.convert(N.format),Ne=Ie.convert(N.type),_t;N.isData3DTexture?(he.setTexture3D(N,0),_t=P.TEXTURE_3D):N.isDataArrayTexture||N.isCompressedArrayTexture?(he.setTexture2DArray(N,0),_t=P.TEXTURE_2D_ARRAY):(he.setTexture2D(N,0),_t=P.TEXTURE_2D),P.pixelStorei(P.UNPACK_FLIP_Y_WEBGL,N.flipY),P.pixelStorei(P.UNPACK_PREMULTIPLY_ALPHA_WEBGL,N.premultiplyAlpha),P.pixelStorei(P.UNPACK_ALIGNMENT,N.unpackAlignment);let it=P.getParameter(P.UNPACK_ROW_LENGTH),hn=P.getParameter(P.UNPACK_IMAGE_HEIGHT),Ws=P.getParameter(P.UNPACK_SKIP_PIXELS),un=P.getParameter(P.UNPACK_SKIP_ROWS),ro=P.getParameter(P.UNPACK_SKIP_IMAGES);P.pixelStorei(P.UNPACK_ROW_LENGTH,ft.width),P.pixelStorei(P.UNPACK_IMAGE_HEIGHT,ft.height),P.pixelStorei(P.UNPACK_SKIP_PIXELS,Ue),P.pixelStorei(P.UNPACK_SKIP_ROWS,Be),P.pixelStorei(P.UNPACK_SKIP_IMAGES,Le);let xt=T.isDataArrayTexture||T.isData3DTexture,Sn=N.isDataArrayTexture||N.isData3DTexture;if(T.isDepthTexture){let bn=ie.get(T),qt=ie.get(N),en=ie.get(bn.__renderTarget),Gh=ie.get(qt.__renderTarget);K.bindFramebuffer(P.READ_FRAMEBUFFER,en.__webglFramebuffer),K.bindFramebuffer(P.DRAW_FRAMEBUFFER,Gh.__webglFramebuffer);for(let Ki=0;Ki<ve;Ki++)xt&&(P.framebufferTextureLayer(P.READ_FRAMEBUFFER,P.COLOR_ATTACHMENT0,ie.get(T).__webglTexture,U,Le+Ki),P.framebufferTextureLayer(P.DRAW_FRAMEBUFFER,P.COLOR_ATTACHMENT0,ie.get(N).__webglTexture,oe,St+Ki)),P.blitFramebuffer(Ue,Be,ge,Te,$e,ct,ge,Te,P.DEPTH_BUFFER_BIT,P.NEAREST);K.bindFramebuffer(P.READ_FRAMEBUFFER,null),K.bindFramebuffer(P.DRAW_FRAMEBUFFER,null)}else if(U!==0||T.isRenderTargetTexture||ie.has(T)){let bn=ie.get(T),qt=ie.get(N);K.bindFramebuffer(P.READ_FRAMEBUFFER,Rg),K.bindFramebuffer(P.DRAW_FRAMEBUFFER,Cg);for(let en=0;en<ve;en++)xt?P.framebufferTextureLayer(P.READ_FRAMEBUFFER,P.COLOR_ATTACHMENT0,bn.__webglTexture,U,Le+en):P.framebufferTexture2D(P.READ_FRAMEBUFFER,P.COLOR_ATTACHMENT0,P.TEXTURE_2D,bn.__webglTexture,U),Sn?P.framebufferTextureLayer(P.DRAW_FRAMEBUFFER,P.COLOR_ATTACHMENT0,qt.__webglTexture,oe,St+en):P.framebufferTexture2D(P.DRAW_FRAMEBUFFER,P.COLOR_ATTACHMENT0,P.TEXTURE_2D,qt.__webglTexture,oe),U!==0?P.blitFramebuffer(Ue,Be,ge,Te,$e,ct,ge,Te,P.COLOR_BUFFER_BIT,P.NEAREST):Sn?P.copyTexSubImage3D(_t,oe,$e,ct,St+en,Ue,Be,ge,Te):P.copyTexSubImage2D(_t,oe,$e,ct,Ue,Be,ge,Te);K.bindFramebuffer(P.READ_FRAMEBUFFER,null),K.bindFramebuffer(P.DRAW_FRAMEBUFFER,null)}else Sn?T.isDataTexture||T.isData3DTexture?P.texSubImage3D(_t,oe,$e,ct,St,ge,Te,ve,ht,Ne,ft.data):N.isCompressedArrayTexture?P.compressedTexSubImage3D(_t,oe,$e,ct,St,ge,Te,ve,ht,ft.data):P.texSubImage3D(_t,oe,$e,ct,St,ge,Te,ve,ht,Ne,ft):T.isDataTexture?P.texSubImage2D(P.TEXTURE_2D,oe,$e,ct,ge,Te,ht,Ne,ft.data):T.isCompressedTexture?P.compressedTexSubImage2D(P.TEXTURE_2D,oe,$e,ct,ft.width,ft.height,ht,ft.data):P.texSubImage2D(P.TEXTURE_2D,oe,$e,ct,ge,Te,ht,Ne,ft);P.pixelStorei(P.UNPACK_ROW_LENGTH,it),P.pixelStorei(P.UNPACK_IMAGE_HEIGHT,hn),P.pixelStorei(P.UNPACK_SKIP_PIXELS,Ws),P.pixelStorei(P.UNPACK_SKIP_ROWS,un),P.pixelStorei(P.UNPACK_SKIP_IMAGES,ro),oe===0&&N.generateMipmaps&&P.generateMipmap(_t),K.unbindTexture()},this.initRenderTarget=function(T){ie.get(T).__webglFramebuffer===void 0&&he.setupRenderTarget(T)},this.initTexture=function(T){T.isCubeTexture?he.setTextureCube(T,0):T.isData3DTexture?he.setTexture3D(T,0):T.isDataArrayTexture||T.isCompressedArrayTexture?he.setTexture2DArray(T,0):he.setTexture2D(T,0),K.unbindTexture()},this.resetState=function(){E=0,C=0,I=null,K.reset(),me.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return sn}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;let t=this.getContext();t.drawingBufferColorSpace=Ze._getDrawingBufferColorSpace(e),t.unpackColorSpace=Ze._getUnpackColorSpace()}};function rf(r,e){if(e===Ih)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),r;if(e===Os||e===jr){let t=r.getIndex();if(t===null){let o=[],a=r.getAttribute("position");if(a!==void 0){for(let c=0;c<a.count;c++)o.push(c);r.setIndex(o),t=r.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),r}let n=t.count-2,i=[];if(e===Os)for(let o=1;o<=n;o++)i.push(t.getX(0)),i.push(t.getX(o)),i.push(t.getX(o+1));else for(let o=0;o<n;o++)o%2===0?(i.push(t.getX(o)),i.push(t.getX(o+1)),i.push(t.getX(o+2))):(i.push(t.getX(o+2)),i.push(t.getX(o+1)),i.push(t.getX(o)));i.length/3!==n&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");let s=r.clone();return s.setIndex(i),s.clearGroups(),s}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",e),r}var Bh=class extends Lt{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new df(t)}),this.register(function(t){return new ff(t)}),this.register(function(t){return new Sf(t)}),this.register(function(t){return new bf(t)}),this.register(function(t){return new Tf(t)}),this.register(function(t){return new mf(t)}),this.register(function(t){return new gf(t)}),this.register(function(t){return new _f(t)}),this.register(function(t){return new xf(t)}),this.register(function(t){return new uf(t)}),this.register(function(t){return new yf(t)}),this.register(function(t){return new pf(t)}),this.register(function(t){return new Mf(t)}),this.register(function(t){return new vf(t)}),this.register(function(t){return new lf(t)}),this.register(function(t){return new Ef(t)}),this.register(function(t){return new Af(t)})}load(e,t,n,i){let s=this,o;if(this.resourcePath!=="")o=this.resourcePath;else if(this.path!==""){let l=Rn.extractUrlBase(e);o=Rn.resolveURL(l,this.path)}else o=Rn.extractUrlBase(e);this.manager.itemStart(e);let a=function(l){i?i(l):console.error(l),s.manager.itemError(e),s.manager.itemEnd(e)},c=new Qt(this.manager);c.setPath(this.path),c.setResponseType("arraybuffer"),c.setRequestHeader(this.requestHeader),c.setWithCredentials(this.withCredentials),c.load(e,function(l){try{s.parse(l,o,function(h){t(h),s.manager.itemEnd(e)},a)}catch(h){a(h)}},n,a)}setDRACOLoader(e){return this.dracoLoader=e,this}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,n,i){let s,o={},a={},c=new TextDecoder;if(typeof e=="string")s=JSON.parse(e);else if(e instanceof ArrayBuffer)if(c.decode(new Uint8Array(e,0,4))===vg){try{o[Ke.KHR_BINARY_GLTF]=new wf(e)}catch(u){i&&i(u);return}s=JSON.parse(o[Ke.KHR_BINARY_GLTF].content)}else s=JSON.parse(c.decode(e));else s=e;if(s.asset===void 0||s.asset.version[0]<2){i&&i(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}let l=new Nf(s,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});l.fileLoader.setRequestHeader(this.requestHeader);for(let h=0;h<this.pluginCallbacks.length;h++){let u=this.pluginCallbacks[h](l);u.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),a[u.name]=u,o[u.name]=!0}if(s.extensionsUsed)for(let h=0;h<s.extensionsUsed.length;++h){let u=s.extensionsUsed[h],d=s.extensionsRequired||[];switch(u){case Ke.KHR_MATERIALS_UNLIT:o[u]=new hf;break;case Ke.KHR_DRACO_MESH_COMPRESSION:o[u]=new Rf(s,this.dracoLoader);break;case Ke.KHR_TEXTURE_TRANSFORM:o[u]=new Cf;break;case Ke.KHR_MESH_QUANTIZATION:o[u]=new If;break;default:d.indexOf(u)>=0&&a[u]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+u+'".')}}l.setExtensions(o),l.setPlugins(a),l.parse(n,i)}parseAsync(e,t){let n=this;return new Promise(function(i,s){n.parse(e,t,i,s)})}};function $M(){let r={};return{get:function(e){return r[e]},add:function(e,t){r[e]=t},remove:function(e){delete r[e]},removeAll:function(){r={}}}}var Ke={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"},lf=class{constructor(e){this.parser=e,this.name=Ke.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){let e=this.parser,t=this.parser.json.nodes||[];for(let n=0,i=t.length;n<i;n++){let s=t[n];s.extensions&&s.extensions[this.name]&&s.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,s.extensions[this.name].light)}}_loadLight(e){let t=this.parser,n="light:"+e,i=t.cache.get(n);if(i)return i;let s=t.json,c=((s.extensions&&s.extensions[this.name]||{}).lights||[])[e],l,h=new ue(16777215);c.color!==void 0&&h.setRGB(c.color[0],c.color[1],c.color[2],Ot);let u=c.range!==void 0?c.range:0;switch(c.type){case"directional":l=new Is(h),l.target.position.set(0,0,-1),l.add(l.target);break;case"point":l=new Cs(h),l.distance=u;break;case"spot":l=new Rs(h),l.distance=u,c.spot=c.spot||{},c.spot.innerConeAngle=c.spot.innerConeAngle!==void 0?c.spot.innerConeAngle:0,c.spot.outerConeAngle=c.spot.outerConeAngle!==void 0?c.spot.outerConeAngle:Math.PI/4,l.angle=c.spot.outerConeAngle,l.penumbra=1-c.spot.innerConeAngle/c.spot.outerConeAngle,l.target.position.set(0,0,-1),l.add(l.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+c.type)}return l.position.set(0,0,0),oi(l,c),c.intensity!==void 0&&(l.intensity=c.intensity),l.name=t.createUniqueName(c.name||"light_"+e),i=Promise.resolve(l),t.cache.add(n,i),i}getDependency(e,t){if(e==="light")return this._loadLight(t)}createNodeAttachment(e){let t=this,n=this.parser,s=n.json.nodes[e],a=(s.extensions&&s.extensions[this.name]||{}).light;return a===void 0?null:this._loadLight(a).then(function(c){return n._getNodeRef(t.cache,a,c)})}},hf=class{constructor(){this.name=Ke.KHR_MATERIALS_UNLIT}getMaterialType(){return Bt}extendParams(e,t,n){let i=[];e.color=new ue(1,1,1),e.opacity=1;let s=t.pbrMetallicRoughness;if(s){if(Array.isArray(s.baseColorFactor)){let o=s.baseColorFactor;e.color.setRGB(o[0],o[1],o[2],Ot),e.opacity=o[3]}s.baseColorTexture!==void 0&&i.push(n.assignTexture(e,"map",s.baseColorTexture,wt))}return Promise.all(i)}},uf=class{constructor(e){this.parser=e,this.name=Ke.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){let i=this.parser.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();let s=i.extensions[this.name].emissiveStrength;return s!==void 0&&(t.emissiveIntensity=s),Promise.resolve()}},df=class{constructor(e){this.parser=e,this.name=Ke.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){let n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Gt}extendMaterialParams(e,t){let n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();let s=[],o=i.extensions[this.name];if(o.clearcoatFactor!==void 0&&(t.clearcoat=o.clearcoatFactor),o.clearcoatTexture!==void 0&&s.push(n.assignTexture(t,"clearcoatMap",o.clearcoatTexture)),o.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=o.clearcoatRoughnessFactor),o.clearcoatRoughnessTexture!==void 0&&s.push(n.assignTexture(t,"clearcoatRoughnessMap",o.clearcoatRoughnessTexture)),o.clearcoatNormalTexture!==void 0&&(s.push(n.assignTexture(t,"clearcoatNormalMap",o.clearcoatNormalTexture)),o.clearcoatNormalTexture.scale!==void 0)){let a=o.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new Y(a,a)}return Promise.all(s)}},ff=class{constructor(e){this.parser=e,this.name=Ke.KHR_MATERIALS_DISPERSION}getMaterialType(e){let n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Gt}extendMaterialParams(e,t){let i=this.parser.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();let s=i.extensions[this.name];return t.dispersion=s.dispersion!==void 0?s.dispersion:0,Promise.resolve()}},pf=class{constructor(e){this.parser=e,this.name=Ke.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){let n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Gt}extendMaterialParams(e,t){let n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();let s=[],o=i.extensions[this.name];return o.iridescenceFactor!==void 0&&(t.iridescence=o.iridescenceFactor),o.iridescenceTexture!==void 0&&s.push(n.assignTexture(t,"iridescenceMap",o.iridescenceTexture)),o.iridescenceIor!==void 0&&(t.iridescenceIOR=o.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),o.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=o.iridescenceThicknessMinimum),o.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=o.iridescenceThicknessMaximum),o.iridescenceThicknessTexture!==void 0&&s.push(n.assignTexture(t,"iridescenceThicknessMap",o.iridescenceThicknessTexture)),Promise.all(s)}},mf=class{constructor(e){this.parser=e,this.name=Ke.KHR_MATERIALS_SHEEN}getMaterialType(e){let n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Gt}extendMaterialParams(e,t){let n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();let s=[];t.sheenColor=new ue(0,0,0),t.sheenRoughness=0,t.sheen=1;let o=i.extensions[this.name];if(o.sheenColorFactor!==void 0){let a=o.sheenColorFactor;t.sheenColor.setRGB(a[0],a[1],a[2],Ot)}return o.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=o.sheenRoughnessFactor),o.sheenColorTexture!==void 0&&s.push(n.assignTexture(t,"sheenColorMap",o.sheenColorTexture,wt)),o.sheenRoughnessTexture!==void 0&&s.push(n.assignTexture(t,"sheenRoughnessMap",o.sheenRoughnessTexture)),Promise.all(s)}},gf=class{constructor(e){this.parser=e,this.name=Ke.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){let n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Gt}extendMaterialParams(e,t){let n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();let s=[],o=i.extensions[this.name];return o.transmissionFactor!==void 0&&(t.transmission=o.transmissionFactor),o.transmissionTexture!==void 0&&s.push(n.assignTexture(t,"transmissionMap",o.transmissionTexture)),Promise.all(s)}},_f=class{constructor(e){this.parser=e,this.name=Ke.KHR_MATERIALS_VOLUME}getMaterialType(e){let n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Gt}extendMaterialParams(e,t){let n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();let s=[],o=i.extensions[this.name];t.thickness=o.thicknessFactor!==void 0?o.thicknessFactor:0,o.thicknessTexture!==void 0&&s.push(n.assignTexture(t,"thicknessMap",o.thicknessTexture)),t.attenuationDistance=o.attenuationDistance||1/0;let a=o.attenuationColor||[1,1,1];return t.attenuationColor=new ue().setRGB(a[0],a[1],a[2],Ot),Promise.all(s)}},xf=class{constructor(e){this.parser=e,this.name=Ke.KHR_MATERIALS_IOR}getMaterialType(e){let n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Gt}extendMaterialParams(e,t){let i=this.parser.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();let s=i.extensions[this.name];return t.ior=s.ior!==void 0?s.ior:1.5,Promise.resolve()}},yf=class{constructor(e){this.parser=e,this.name=Ke.KHR_MATERIALS_SPECULAR}getMaterialType(e){let n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Gt}extendMaterialParams(e,t){let n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();let s=[],o=i.extensions[this.name];t.specularIntensity=o.specularFactor!==void 0?o.specularFactor:1,o.specularTexture!==void 0&&s.push(n.assignTexture(t,"specularIntensityMap",o.specularTexture));let a=o.specularColorFactor||[1,1,1];return t.specularColor=new ue().setRGB(a[0],a[1],a[2],Ot),o.specularColorTexture!==void 0&&s.push(n.assignTexture(t,"specularColorMap",o.specularColorTexture,wt)),Promise.all(s)}},vf=class{constructor(e){this.parser=e,this.name=Ke.EXT_MATERIALS_BUMP}getMaterialType(e){let n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Gt}extendMaterialParams(e,t){let n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();let s=[],o=i.extensions[this.name];return t.bumpScale=o.bumpFactor!==void 0?o.bumpFactor:1,o.bumpTexture!==void 0&&s.push(n.assignTexture(t,"bumpMap",o.bumpTexture)),Promise.all(s)}},Mf=class{constructor(e){this.parser=e,this.name=Ke.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){let n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:Gt}extendMaterialParams(e,t){let n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();let s=[],o=i.extensions[this.name];return o.anisotropyStrength!==void 0&&(t.anisotropy=o.anisotropyStrength),o.anisotropyRotation!==void 0&&(t.anisotropyRotation=o.anisotropyRotation),o.anisotropyTexture!==void 0&&s.push(n.assignTexture(t,"anisotropyMap",o.anisotropyTexture)),Promise.all(s)}},Sf=class{constructor(e){this.parser=e,this.name=Ke.KHR_TEXTURE_BASISU}loadTexture(e){let t=this.parser,n=t.json,i=n.textures[e];if(!i.extensions||!i.extensions[this.name])return null;let s=i.extensions[this.name],o=t.options.ktx2Loader;if(!o){if(n.extensionsRequired&&n.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,s.source,o)}},bf=class{constructor(e){this.parser=e,this.name=Ke.EXT_TEXTURE_WEBP}loadTexture(e){let t=this.name,n=this.parser,i=n.json,s=i.textures[e];if(!s.extensions||!s.extensions[t])return null;let o=s.extensions[t],a=i.images[o.source],c=n.textureLoader;if(a.uri){let l=n.options.manager.getHandler(a.uri);l!==null&&(c=l)}return n.loadTextureImage(e,o.source,c)}},Tf=class{constructor(e){this.parser=e,this.name=Ke.EXT_TEXTURE_AVIF}loadTexture(e){let t=this.name,n=this.parser,i=n.json,s=i.textures[e];if(!s.extensions||!s.extensions[t])return null;let o=s.extensions[t],a=i.images[o.source],c=n.textureLoader;if(a.uri){let l=n.options.manager.getHandler(a.uri);l!==null&&(c=l)}return n.loadTextureImage(e,o.source,c)}},Ef=class{constructor(e){this.name=Ke.EXT_MESHOPT_COMPRESSION,this.parser=e}loadBufferView(e){let t=this.parser.json,n=t.bufferViews[e];if(n.extensions&&n.extensions[this.name]){let i=n.extensions[this.name],s=this.parser.getDependency("buffer",i.buffer),o=this.parser.options.meshoptDecoder;if(!o||!o.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return s.then(function(a){let c=i.byteOffset||0,l=i.byteLength||0,h=i.count,u=i.byteStride,d=new Uint8Array(a,c,l);return o.decodeGltfBufferAsync?o.decodeGltfBufferAsync(h,u,d,i.mode,i.filter).then(function(f){return f.buffer}):o.ready.then(function(){let f=new ArrayBuffer(h*u);return o.decodeGltfBuffer(new Uint8Array(f),h,u,d,i.mode,i.filter),f})})}else return null}},Af=class{constructor(e){this.name=Ke.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){let t=this.parser.json,n=t.nodes[e];if(!n.extensions||!n.extensions[this.name]||n.mesh===void 0)return null;let i=t.meshes[n.mesh];for(let l of i.primitives)if(l.mode!==In.TRIANGLES&&l.mode!==In.TRIANGLE_STRIP&&l.mode!==In.TRIANGLE_FAN&&l.mode!==void 0)return null;let o=n.extensions[this.name].attributes,a=[],c={};for(let l in o)a.push(this.parser.getDependency("accessor",o[l]).then(h=>(c[l]=h,c[l])));return a.length<1?null:(a.push(this.parser.createNodeMesh(e)),Promise.all(a).then(l=>{let h=l.pop(),u=h.isGroup?h.children:[h],d=l[0].count,f=[];for(let m of u){let _=new De,g=new w,p=new vt,v=new w(1,1,1),y=new vs(m.geometry,m.material,d);for(let x=0;x<d;x++)c.TRANSLATION&&g.fromBufferAttribute(c.TRANSLATION,x),c.ROTATION&&p.fromBufferAttribute(c.ROTATION,x),c.SCALE&&v.fromBufferAttribute(c.SCALE,x),y.setMatrixAt(x,_.compose(g,p,v));for(let x in c)if(x==="_COLOR_0"){let A=c[x];y.instanceColor=new wn(A.array,A.itemSize,A.normalized)}else x!=="TRANSLATION"&&x!=="ROTATION"&&x!=="SCALE"&&m.geometry.setAttribute(x,c[x]);Qe.prototype.copy.call(y,m),this.parser.assignFinalMaterial(y),f.push(y)}return h.isGroup?(h.clear(),h.add(...f),h):f[0]}))}},vg="glTF",Sc=12,gg={JSON:1313821514,BIN:5130562},wf=class{constructor(e){this.name=Ke.KHR_BINARY_GLTF,this.content=null,this.body=null;let t=new DataView(e,0,Sc),n=new TextDecoder;if(this.header={magic:n.decode(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==vg)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");let i=this.header.length-Sc,s=new DataView(e,Sc),o=0;for(;o<i;){let a=s.getUint32(o,!0);o+=4;let c=s.getUint32(o,!0);if(o+=4,c===gg.JSON){let l=new Uint8Array(e,Sc+o,a);this.content=n.decode(l)}else if(c===gg.BIN){let l=Sc+o;this.body=e.slice(l,l+a)}o+=a}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}},Rf=class{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=Ke.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){let n=this.json,i=this.dracoLoader,s=e.extensions[this.name].bufferView,o=e.extensions[this.name].attributes,a={},c={},l={};for(let h in o){let u=Lf[h]||h.toLowerCase();a[u]=o[h]}for(let h in e.attributes){let u=Lf[h]||h.toLowerCase();if(o[h]!==void 0){let d=n.accessors[e.attributes[h]],f=so[d.componentType];l[u]=f.name,c[u]=d.normalized===!0}}return t.getDependency("bufferView",s).then(function(h){return new Promise(function(u,d){i.decodeDracoFile(h,function(f){for(let m in f.attributes){let _=f.attributes[m],g=c[m];g!==void 0&&(_.normalized=g)}u(f)},a,l,Ot,d)})})}},Cf=class{constructor(){this.name=Ke.KHR_TEXTURE_TRANSFORM}extendTexture(e,t){return(t.texCoord===void 0||t.texCoord===e.channel)&&t.offset===void 0&&t.rotation===void 0&&t.scale===void 0||(e=e.clone(),t.texCoord!==void 0&&(e.channel=t.texCoord),t.offset!==void 0&&e.offset.fromArray(t.offset),t.rotation!==void 0&&(e.rotation=t.rotation),t.scale!==void 0&&e.repeat.fromArray(t.scale),e.needsUpdate=!0),e}},If=class{constructor(){this.name=Ke.KHR_MESH_QUANTIZATION}},zh=class extends $n{constructor(e,t,n,i){super(e,t,n,i)}copySampleValue_(e){let t=this.resultBuffer,n=this.sampleValues,i=this.valueSize,s=e*i*3+i;for(let o=0;o!==i;o++)t[o]=n[s+o];return t}interpolate_(e,t,n,i){let s=this.resultBuffer,o=this.sampleValues,a=this.valueSize,c=a*2,l=a*3,h=i-t,u=(n-t)/h,d=u*u,f=d*u,m=e*l,_=m-l,g=-2*f+3*d,p=f-d,v=1-g,y=p-d+u;for(let x=0;x!==a;x++){let A=o[_+x+a],E=o[_+x+c]*h,C=o[m+x+a],I=o[m+x]*h;s[x]=v*A+y*E+g*C+p*I}return s}},jM=new vt,Pf=class extends zh{interpolate_(e,t,n,i){let s=super.interpolate_(e,t,n,i);return jM.fromArray(s).normalize().toArray(s),s}},In={FLOAT:5126,FLOAT_MAT3:35675,FLOAT_MAT4:35676,FLOAT_VEC2:35664,FLOAT_VEC3:35665,FLOAT_VEC4:35666,LINEAR:9729,REPEAT:10497,SAMPLER_2D:35678,POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6,UNSIGNED_BYTE:5121,UNSIGNED_SHORT:5123},so={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},_g={9728:Ct,9729:mt,9984:qr,9985:qi,9986:Ti,9987:cn},xg={33071:Kt,33648:Bi,10497:Kn},of={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},Lf={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",TEXCOORD_0:"uv",TEXCOORD_1:"uv1",TEXCOORD_2:"uv2",TEXCOORD_3:"uv3",COLOR_0:"color",WEIGHTS_0:"skinWeight",JOINTS_0:"skinIndex"},Yi={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},QM={CUBICSPLINE:void 0,LINEAR:ki,STEP:zi},af={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function eS(r){return r.DefaultMaterial===void 0&&(r.DefaultMaterial=new yi({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:An})),r.DefaultMaterial}function Gs(r,e,t){for(let n in t.extensions)r[n]===void 0&&(e.userData.gltfExtensions=e.userData.gltfExtensions||{},e.userData.gltfExtensions[n]=t.extensions[n])}function oi(r,e){e.extras!==void 0&&(typeof e.extras=="object"?Object.assign(r.userData,e.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+e.extras))}function tS(r,e,t){let n=!1,i=!1,s=!1;for(let l=0,h=e.length;l<h;l++){let u=e[l];if(u.POSITION!==void 0&&(n=!0),u.NORMAL!==void 0&&(i=!0),u.COLOR_0!==void 0&&(s=!0),n&&i&&s)break}if(!n&&!i&&!s)return Promise.resolve(r);let o=[],a=[],c=[];for(let l=0,h=e.length;l<h;l++){let u=e[l];if(n){let d=u.POSITION!==void 0?t.getDependency("accessor",u.POSITION):r.attributes.position;o.push(d)}if(i){let d=u.NORMAL!==void 0?t.getDependency("accessor",u.NORMAL):r.attributes.normal;a.push(d)}if(s){let d=u.COLOR_0!==void 0?t.getDependency("accessor",u.COLOR_0):r.attributes.color;c.push(d)}}return Promise.all([Promise.all(o),Promise.all(a),Promise.all(c)]).then(function(l){let h=l[0],u=l[1],d=l[2];return n&&(r.morphAttributes.position=h),i&&(r.morphAttributes.normal=u),s&&(r.morphAttributes.color=d),r.morphTargetsRelative=!0,r})}function nS(r,e){if(r.updateMorphTargets(),e.weights!==void 0)for(let t=0,n=e.weights.length;t<n;t++)r.morphTargetInfluences[t]=e.weights[t];if(e.extras&&Array.isArray(e.extras.targetNames)){let t=e.extras.targetNames;if(r.morphTargetInfluences.length===t.length){r.morphTargetDictionary={};for(let n=0,i=t.length;n<i;n++)r.morphTargetDictionary[t[n]]=n}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function iS(r){let e,t=r.extensions&&r.extensions[Ke.KHR_DRACO_MESH_COMPRESSION];if(t?e="draco:"+t.bufferView+":"+t.indices+":"+cf(t.attributes):e=r.indices+":"+cf(r.attributes)+":"+r.mode,r.targets!==void 0)for(let n=0,i=r.targets.length;n<i;n++)e+=":"+cf(r.targets[n]);return e}function cf(r){let e="",t=Object.keys(r).sort();for(let n=0,i=t.length;n<i;n++)e+=t[n]+":"+r[t[n]]+";";return e}function Df(r){switch(r){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}function sS(r){return r.search(/\.jpe?g($|\?)/i)>0||r.search(/^data\:image\/jpeg/)===0?"image/jpeg":r.search(/\.webp($|\?)/i)>0||r.search(/^data\:image\/webp/)===0?"image/webp":r.search(/\.ktx2($|\?)/i)>0||r.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}var rS=new De,Nf=class{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new $M,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let n=!1,i=-1,s=!1,o=-1;if(typeof navigator<"u"){let a=navigator.userAgent;n=/^((?!chrome|android).)*safari/i.test(a)===!0;let c=a.match(/Version\/(\d+)/);i=n&&c?parseInt(c[1],10):-1,s=a.indexOf("Firefox")>-1,o=s?a.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||n&&i<17||s&&o<98?this.textureLoader=new zr(this.options.manager):this.textureLoader=new kr(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new Qt(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){let n=this,i=this.json,s=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(o){return o._markDefs&&o._markDefs()}),Promise.all(this._invokeAll(function(o){return o.beforeRoot&&o.beforeRoot()})).then(function(){return Promise.all([n.getDependencies("scene"),n.getDependencies("animation"),n.getDependencies("camera")])}).then(function(o){let a={scene:o[0][i.scene||0],scenes:o[0],animations:o[1],cameras:o[2],asset:i.asset,parser:n,userData:{}};return Gs(s,a,i),oi(a,i),Promise.all(n._invokeAll(function(c){return c.afterRoot&&c.afterRoot(a)})).then(function(){for(let c of a.scenes)c.updateMatrixWorld();e(a)})}).catch(t)}_markDefs(){let e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let i=0,s=t.length;i<s;i++){let o=t[i].joints;for(let a=0,c=o.length;a<c;a++)e[o[a]].isBone=!0}for(let i=0,s=e.length;i<s;i++){let o=e[i];o.mesh!==void 0&&(this._addNodeRef(this.meshCache,o.mesh),o.skin!==void 0&&(n[o.mesh].isSkinnedMesh=!0)),o.camera!==void 0&&this._addNodeRef(this.cameraCache,o.camera)}}_addNodeRef(e,t){t!==void 0&&(e.refs[t]===void 0&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,n){if(e.refs[t]<=1)return n;let i=n.clone(),s=(o,a)=>{let c=this.associations.get(o);c!=null&&this.associations.set(a,c);for(let[l,h]of o.children.entries())s(h,a.children[l])};return s(n,i),i.name+="_instance_"+e.uses[t]++,i}_invokeOne(e){let t=Object.values(this.plugins);t.push(this);for(let n=0;n<t.length;n++){let i=e(t[n]);if(i)return i}return null}_invokeAll(e){let t=Object.values(this.plugins);t.unshift(this);let n=[];for(let i=0;i<t.length;i++){let s=e(t[i]);s&&n.push(s)}return n}getDependency(e,t){let n=e+":"+t,i=this.cache.get(n);if(!i){switch(e){case"scene":i=this.loadScene(t);break;case"node":i=this._invokeOne(function(s){return s.loadNode&&s.loadNode(t)});break;case"mesh":i=this._invokeOne(function(s){return s.loadMesh&&s.loadMesh(t)});break;case"accessor":i=this.loadAccessor(t);break;case"bufferView":i=this._invokeOne(function(s){return s.loadBufferView&&s.loadBufferView(t)});break;case"buffer":i=this.loadBuffer(t);break;case"material":i=this._invokeOne(function(s){return s.loadMaterial&&s.loadMaterial(t)});break;case"texture":i=this._invokeOne(function(s){return s.loadTexture&&s.loadTexture(t)});break;case"skin":i=this.loadSkin(t);break;case"animation":i=this._invokeOne(function(s){return s.loadAnimation&&s.loadAnimation(t)});break;case"camera":i=this.loadCamera(t);break;default:if(i=this._invokeOne(function(s){return s!=this&&s.getDependency&&s.getDependency(e,t)}),!i)throw new Error("Unknown type: "+e);break}this.cache.add(n,i)}return i}getDependencies(e){let t=this.cache.get(e);if(!t){let n=this,i=this.json[e+(e==="mesh"?"es":"s")]||[];t=Promise.all(i.map(function(s,o){return n.getDependency(e,o)})),this.cache.add(e,t)}return t}loadBuffer(e){let t=this.json.buffers[e],n=this.fileLoader;if(t.type&&t.type!=="arraybuffer")throw new Error("THREE.GLTFLoader: "+t.type+" buffer type is not supported.");if(t.uri===void 0&&e===0)return Promise.resolve(this.extensions[Ke.KHR_BINARY_GLTF].body);let i=this.options;return new Promise(function(s,o){n.load(Rn.resolveURL(t.uri,i.path),s,void 0,function(){o(new Error('THREE.GLTFLoader: Failed to load buffer "'+t.uri+'".'))})})}loadBufferView(e){let t=this.json.bufferViews[e];return this.getDependency("buffer",t.buffer).then(function(n){let i=t.byteLength||0,s=t.byteOffset||0;return n.slice(s,s+i)})}loadAccessor(e){let t=this,n=this.json,i=this.json.accessors[e];if(i.bufferView===void 0&&i.sparse===void 0){let o=of[i.type],a=so[i.componentType],c=i.normalized===!0,l=new a(i.count*o);return Promise.resolve(new je(l,o,c))}let s=[];return i.bufferView!==void 0?s.push(this.getDependency("bufferView",i.bufferView)):s.push(null),i.sparse!==void 0&&(s.push(this.getDependency("bufferView",i.sparse.indices.bufferView)),s.push(this.getDependency("bufferView",i.sparse.values.bufferView))),Promise.all(s).then(function(o){let a=o[0],c=of[i.type],l=so[i.componentType],h=l.BYTES_PER_ELEMENT,u=h*c,d=i.byteOffset||0,f=i.bufferView!==void 0?n.bufferViews[i.bufferView].byteStride:void 0,m=i.normalized===!0,_,g;if(f&&f!==u){let p=Math.floor(d/f),v="InterleavedBuffer:"+i.bufferView+":"+i.componentType+":"+p+":"+i.count,y=t.cache.get(v);y||(_=new l(a,p*f,i.count*f/h),y=new Jn(_,f/h),t.cache.add(v,y)),g=new Bn(y,c,d%f/h,m)}else a===null?_=new l(i.count*c):_=new l(a,d,i.count*c),g=new je(_,c,m);if(i.sparse!==void 0){let p=of.SCALAR,v=so[i.sparse.indices.componentType],y=i.sparse.indices.byteOffset||0,x=i.sparse.values.byteOffset||0,A=new v(o[1],y,i.sparse.count*p),E=new l(o[2],x,i.sparse.count*c);a!==null&&(g=new je(g.array.slice(),g.itemSize,g.normalized)),g.normalized=!1;for(let C=0,I=A.length;C<I;C++){let b=A[C];if(g.setX(b,E[C*c]),c>=2&&g.setY(b,E[C*c+1]),c>=3&&g.setZ(b,E[C*c+2]),c>=4&&g.setW(b,E[C*c+3]),c>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}g.normalized=m}return g})}loadTexture(e){let t=this.json,n=this.options,s=t.textures[e].source,o=t.images[s],a=this.textureLoader;if(o.uri){let c=n.manager.getHandler(o.uri);c!==null&&(a=c)}return this.loadTextureImage(e,s,a)}loadTextureImage(e,t,n){let i=this,s=this.json,o=s.textures[e],a=s.images[t],c=(a.uri||a.bufferView)+":"+o.sampler;if(this.textureCache[c])return this.textureCache[c];let l=this.loadImageSource(t,n).then(function(h){h.flipY=!1,h.name=o.name||a.name||"",h.name===""&&typeof a.uri=="string"&&a.uri.startsWith("data:image/")===!1&&(h.name=a.uri);let d=(s.samplers||{})[o.sampler]||{};return h.magFilter=_g[d.magFilter]||mt,h.minFilter=_g[d.minFilter]||cn,h.wrapS=xg[d.wrapS]||Kn,h.wrapT=xg[d.wrapT]||Kn,h.generateMipmaps=!h.isCompressedTexture&&h.minFilter!==Ct&&h.minFilter!==mt,i.associations.set(h,{textures:e}),h}).catch(function(){return null});return this.textureCache[c]=l,l}loadImageSource(e,t){let n=this,i=this.json,s=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(u=>u.clone());let o=i.images[e],a=self.URL||self.webkitURL,c=o.uri||"",l=!1;if(o.bufferView!==void 0)c=n.getDependency("bufferView",o.bufferView).then(function(u){l=!0;let d=new Blob([u],{type:o.mimeType});return c=a.createObjectURL(d),c});else if(o.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");let h=Promise.resolve(c).then(function(u){return new Promise(function(d,f){let m=d;t.isImageBitmapLoader===!0&&(m=function(_){let g=new gt(_);g.needsUpdate=!0,d(g)}),t.load(Rn.resolveURL(u,s.path),m,void 0,f)})}).then(function(u){return l===!0&&a.revokeObjectURL(c),oi(u,o),u.userData.mimeType=o.mimeType||sS(o.uri),u}).catch(function(u){throw console.error("THREE.GLTFLoader: Couldn't load texture",c),u});return this.sourceCache[e]=h,h}assignTexture(e,t,n,i){let s=this;return this.getDependency("texture",n.index).then(function(o){if(!o)return null;if(n.texCoord!==void 0&&n.texCoord>0&&(o=o.clone(),o.channel=n.texCoord),s.extensions[Ke.KHR_TEXTURE_TRANSFORM]){let a=n.extensions!==void 0?n.extensions[Ke.KHR_TEXTURE_TRANSFORM]:void 0;if(a){let c=s.associations.get(o);o=s.extensions[Ke.KHR_TEXTURE_TRANSFORM].extendTexture(o,a),s.associations.set(o,c)}}return i!==void 0&&(o.colorSpace=i),e[t]=o,o})}assignFinalMaterial(e){let t=e.geometry,n=e.material,i=t.attributes.tangent===void 0,s=t.attributes.color!==void 0,o=t.attributes.normal===void 0;if(e.isPoints){let a="PointsMaterial:"+n.uuid,c=this.cache.get(a);c||(c=new Wi,Mt.prototype.copy.call(c,n),c.color.copy(n.color),c.map=n.map,c.sizeAttenuation=!1,this.cache.add(a,c)),n=c}else if(e.isLine){let a="LineBasicMaterial:"+n.uuid,c=this.cache.get(a);c||(c=new Pt,Mt.prototype.copy.call(c,n),c.color.copy(n.color),c.map=n.map,this.cache.add(a,c)),n=c}if(i||s||o){let a="ClonedMaterial:"+n.uuid+":";i&&(a+="derivative-tangents:"),s&&(a+="vertex-colors:"),o&&(a+="flat-shading:");let c=this.cache.get(a);c||(c=n.clone(),s&&(c.vertexColors=!0),o&&(c.flatShading=!0),i&&(c.normalScale&&(c.normalScale.y*=-1),c.clearcoatNormalScale&&(c.clearcoatNormalScale.y*=-1)),this.cache.add(a,c),this.associations.set(c,this.associations.get(n))),n=c}e.material=n}getMaterialType(){return yi}loadMaterial(e){let t=this,n=this.json,i=this.extensions,s=n.materials[e],o,a={},c=s.extensions||{},l=[];if(c[Ke.KHR_MATERIALS_UNLIT]){let u=i[Ke.KHR_MATERIALS_UNLIT];o=u.getMaterialType(),l.push(u.extendParams(a,s,t))}else{let u=s.pbrMetallicRoughness||{};if(a.color=new ue(1,1,1),a.opacity=1,Array.isArray(u.baseColorFactor)){let d=u.baseColorFactor;a.color.setRGB(d[0],d[1],d[2],Ot),a.opacity=d[3]}u.baseColorTexture!==void 0&&l.push(t.assignTexture(a,"map",u.baseColorTexture,wt)),a.metalness=u.metallicFactor!==void 0?u.metallicFactor:1,a.roughness=u.roughnessFactor!==void 0?u.roughnessFactor:1,u.metallicRoughnessTexture!==void 0&&(l.push(t.assignTexture(a,"metalnessMap",u.metallicRoughnessTexture)),l.push(t.assignTexture(a,"roughnessMap",u.metallicRoughnessTexture))),o=this._invokeOne(function(d){return d.getMaterialType&&d.getMaterialType(e)}),l.push(Promise.all(this._invokeAll(function(d){return d.extendMaterialParams&&d.extendMaterialParams(e,a)})))}s.doubleSided===!0&&(a.side=Mn);let h=s.alphaMode||af.OPAQUE;if(h===af.BLEND?(a.transparent=!0,a.depthWrite=!1):(a.transparent=!1,h===af.MASK&&(a.alphaTest=s.alphaCutoff!==void 0?s.alphaCutoff:.5)),s.normalTexture!==void 0&&o!==Bt&&(l.push(t.assignTexture(a,"normalMap",s.normalTexture)),a.normalScale=new Y(1,1),s.normalTexture.scale!==void 0)){let u=s.normalTexture.scale;a.normalScale.set(u,u)}if(s.occlusionTexture!==void 0&&o!==Bt&&(l.push(t.assignTexture(a,"aoMap",s.occlusionTexture)),s.occlusionTexture.strength!==void 0&&(a.aoMapIntensity=s.occlusionTexture.strength)),s.emissiveFactor!==void 0&&o!==Bt){let u=s.emissiveFactor;a.emissive=new ue().setRGB(u[0],u[1],u[2],Ot)}return s.emissiveTexture!==void 0&&o!==Bt&&l.push(t.assignTexture(a,"emissiveMap",s.emissiveTexture,wt)),Promise.all(l).then(function(){let u=new o(a);return s.name&&(u.name=s.name),oi(u,s),t.associations.set(u,{materials:e}),s.extensions&&Gs(i,u,s),u})}createUniqueName(e){let t=st.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){let t=this,n=this.extensions,i=this.primitiveCache;function s(a){return n[Ke.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(a,t).then(function(c){return yg(c,a,t)})}let o=[];for(let a=0,c=e.length;a<c;a++){let l=e[a],h=iS(l),u=i[h];if(u)o.push(u.promise);else{let d;l.extensions&&l.extensions[Ke.KHR_DRACO_MESH_COMPRESSION]?d=s(l):d=yg(new ze,l,t),i[h]={primitive:l,promise:d},o.push(d)}}return Promise.all(o)}loadMesh(e){let t=this,n=this.json,i=this.extensions,s=n.meshes[e],o=s.primitives,a=[];for(let c=0,l=o.length;c<l;c++){let h=o[c].material===void 0?eS(this.cache):this.getDependency("material",o[c].material);a.push(h)}return a.push(t.loadGeometries(o)),Promise.all(a).then(function(c){let l=c.slice(0,c.length-1),h=c[c.length-1],u=[];for(let f=0,m=h.length;f<m;f++){let _=h[f],g=o[f],p,v=l[f];if(g.mode===In.TRIANGLES||g.mode===In.TRIANGLE_STRIP||g.mode===In.TRIANGLE_FAN||g.mode===void 0)p=s.isSkinnedMesh===!0?new xs(_,v):new pt(_,v),p.isSkinnedMesh===!0&&p.normalizeSkinWeights(),g.mode===In.TRIANGLE_STRIP?p.geometry=rf(p.geometry,jr):g.mode===In.TRIANGLE_FAN&&(p.geometry=rf(p.geometry,Os));else if(g.mode===In.LINES)p=new $t(_,v);else if(g.mode===In.LINE_STRIP)p=new vn(_,v);else if(g.mode===In.LINE_LOOP)p=new Ms(_,v);else if(g.mode===In.POINTS)p=new Ss(_,v);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+g.mode);Object.keys(p.geometry.morphAttributes).length>0&&nS(p,s),p.name=t.createUniqueName(s.name||"mesh_"+e),oi(p,s),g.extensions&&Gs(i,p,g),t.assignFinalMaterial(p),u.push(p)}for(let f=0,m=u.length;f<m;f++)t.associations.set(u[f],{meshes:e,primitives:f});if(u.length===1)return s.extensions&&Gs(i,u[0],s),u[0];let d=new mn;s.extensions&&Gs(i,d,s),t.associations.set(d,{meshes:e});for(let f=0,m=u.length;f<m;f++)d.add(u[f]);return d})}loadCamera(e){let t,n=this.json.cameras[e],i=n[n.type];if(!i){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return n.type==="perspective"?t=new Tt(Qr.radToDeg(i.yfov),i.aspectRatio||1,i.znear||1,i.zfar||2e6):n.type==="orthographic"&&(t=new vi(-i.xmag,i.xmag,i.ymag,-i.ymag,i.znear,i.zfar)),n.name&&(t.name=this.createUniqueName(n.name)),oi(t,n),Promise.resolve(t)}loadSkin(e){let t=this.json.skins[e],n=[];for(let i=0,s=t.joints.length;i<s;i++)n.push(this._loadNodeShallow(t.joints[i]));return t.inverseBindMatrices!==void 0?n.push(this.getDependency("accessor",t.inverseBindMatrices)):n.push(null),Promise.all(n).then(function(i){let s=i.pop(),o=i,a=[],c=[];for(let l=0,h=o.length;l<h;l++){let u=o[l];if(u){a.push(u);let d=new De;s!==null&&d.fromArray(s.array,l*16),c.push(d)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[l])}return new ys(a,c)})}loadAnimation(e){let t=this.json,n=this,i=t.animations[e],s=i.name?i.name:"animation_"+e,o=[],a=[],c=[],l=[],h=[];for(let u=0,d=i.channels.length;u<d;u++){let f=i.channels[u],m=i.samplers[f.sampler],_=f.target,g=_.node,p=i.parameters!==void 0?i.parameters[m.input]:m.input,v=i.parameters!==void 0?i.parameters[m.output]:m.output;_.node!==void 0&&(o.push(this.getDependency("node",g)),a.push(this.getDependency("accessor",p)),c.push(this.getDependency("accessor",v)),l.push(m),h.push(_))}return Promise.all([Promise.all(o),Promise.all(a),Promise.all(c),Promise.all(l),Promise.all(h)]).then(function(u){let d=u[0],f=u[1],m=u[2],_=u[3],g=u[4],p=[];for(let y=0,x=d.length;y<x;y++){let A=d[y],E=f[y],C=m[y],I=_[y],b=g[y];if(A===void 0)continue;A.updateMatrix&&A.updateMatrix();let S=n._createAnimationTracks(A,E,C,I,b);if(S)for(let L=0;L<S.length;L++)p.push(S[L])}let v=new ei(s,void 0,p);return oi(v,i),v})}createNodeMesh(e){let t=this.json,n=this,i=t.nodes[e];return i.mesh===void 0?null:n.getDependency("mesh",i.mesh).then(function(s){let o=n._getNodeRef(n.meshCache,i.mesh,s);return i.weights!==void 0&&o.traverse(function(a){if(a.isMesh)for(let c=0,l=i.weights.length;c<l;c++)a.morphTargetInfluences[c]=i.weights[c]}),o})}loadNode(e){let t=this.json,n=this,i=t.nodes[e],s=n._loadNodeShallow(e),o=[],a=i.children||[];for(let l=0,h=a.length;l<h;l++)o.push(n.getDependency("node",a[l]));let c=i.skin===void 0?Promise.resolve(null):n.getDependency("skin",i.skin);return Promise.all([s,Promise.all(o),c]).then(function(l){let h=l[0],u=l[1],d=l[2];d!==null&&h.traverse(function(f){f.isSkinnedMesh&&f.bind(d,rS)});for(let f=0,m=u.length;f<m;f++)h.add(u[f]);return h})}_loadNodeShallow(e){let t=this.json,n=this.extensions,i=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];let s=t.nodes[e],o=s.name?i.createUniqueName(s.name):"",a=[],c=i._invokeOne(function(l){return l.createNodeMesh&&l.createNodeMesh(e)});return c&&a.push(c),s.camera!==void 0&&a.push(i.getDependency("camera",s.camera).then(function(l){return i._getNodeRef(i.cameraCache,s.camera,l)})),i._invokeAll(function(l){return l.createNodeAttachment&&l.createNodeAttachment(e)}).forEach(function(l){a.push(l)}),this.nodeCache[e]=Promise.all(a).then(function(l){let h;if(s.isBone===!0?h=new Gi:l.length>1?h=new mn:l.length===1?h=l[0]:h=new Qe,h!==l[0])for(let u=0,d=l.length;u<d;u++)h.add(l[u]);if(s.name&&(h.userData.name=s.name,h.name=o),oi(h,s),s.extensions&&Gs(n,h,s),s.matrix!==void 0){let u=new De;u.fromArray(s.matrix),h.applyMatrix4(u)}else s.translation!==void 0&&h.position.fromArray(s.translation),s.rotation!==void 0&&h.quaternion.fromArray(s.rotation),s.scale!==void 0&&h.scale.fromArray(s.scale);if(!i.associations.has(h))i.associations.set(h,{});else if(s.mesh!==void 0&&i.meshCache.refs[s.mesh]>1){let u=i.associations.get(h);i.associations.set(h,{...u})}return i.associations.get(h).nodes=e,h}),this.nodeCache[e]}loadScene(e){let t=this.extensions,n=this.json.scenes[e],i=this,s=new mn;n.name&&(s.name=i.createUniqueName(n.name)),oi(s,n),n.extensions&&Gs(t,s,n);let o=n.nodes||[],a=[];for(let c=0,l=o.length;c<l;c++)a.push(i.getDependency("node",o[c]));return Promise.all(a).then(function(c){for(let h=0,u=c.length;h<u;h++)s.add(c[h]);let l=h=>{let u=new Map;for(let[d,f]of i.associations)(d instanceof Mt||d instanceof gt)&&u.set(d,f);return h.traverse(d=>{let f=i.associations.get(d);f!=null&&u.set(d,f)}),u};return i.associations=l(s),s})}_createAnimationTracks(e,t,n,i,s){let o=[],a=e.name?e.name:e.uuid,c=[];Yi[s.path]===Yi.weights?e.traverse(function(d){d.morphTargetInfluences&&c.push(d.name?d.name:d.uuid)}):c.push(a);let l;switch(Yi[s.path]){case Yi.weights:l=zn;break;case Yi.rotation:l=kn;break;case Yi.translation:case Yi.scale:l=Vn;break;default:n.itemSize===1?l=zn:l=Vn;break}let h=i.interpolation!==void 0?QM[i.interpolation]:ki,u=this._getArrayFromAccessor(n);for(let d=0,f=c.length;d<f;d++){let m=new l(c[d]+"."+Yi[s.path],t.array,u,h);i.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(m),o.push(m)}return o}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){let n=Df(t.constructor),i=new Float32Array(t.length);for(let s=0,o=t.length;s<o;s++)i[s]=t[s]*n;t=i}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(n){let i=this instanceof kn?Pf:zh;return new i(this.times,this.values,this.getValueSize()/3,n)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}};function oS(r,e,t){let n=e.attributes,i=new Rt;if(n.POSITION!==void 0){let a=t.json.accessors[n.POSITION],c=a.min,l=a.max;if(c!==void 0&&l!==void 0){if(i.set(new w(c[0],c[1],c[2]),new w(l[0],l[1],l[2])),a.normalized){let h=Df(so[a.componentType]);i.min.multiplyScalar(h),i.max.multiplyScalar(h)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;let s=e.targets;if(s!==void 0){let a=new w,c=new w;for(let l=0,h=s.length;l<h;l++){let u=s[l];if(u.POSITION!==void 0){let d=t.json.accessors[u.POSITION],f=d.min,m=d.max;if(f!==void 0&&m!==void 0){if(c.setX(Math.max(Math.abs(f[0]),Math.abs(m[0]))),c.setY(Math.max(Math.abs(f[1]),Math.abs(m[1]))),c.setZ(Math.max(Math.abs(f[2]),Math.abs(m[2]))),d.normalized){let _=Df(so[d.componentType]);c.multiplyScalar(_)}a.max(c)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}i.expandByVector(a)}r.boundingBox=i;let o=new Et;i.getCenter(o.center),o.radius=i.min.distanceTo(i.max)/2,r.boundingSphere=o}function yg(r,e,t){let n=e.attributes,i=[];function s(o,a){return t.getDependency("accessor",o).then(function(c){r.setAttribute(a,c)})}for(let o in n){let a=Lf[o]||o.toLowerCase();a in r.attributes||i.push(s(n[o],a))}if(e.indices!==void 0&&!r.index){let o=t.getDependency("accessor",e.indices).then(function(a){r.setIndex(a)});i.push(o)}return Ze.workingColorSpace!==Ot&&"COLOR_0"in n&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${Ze.workingColorSpace}" not supported.`),oi(r,e),oS(r,e,t),Promise.all(i).then(function(){return e.targets!==void 0?tS(r,e.targets,t):r})}var Mg={type:"change"},Ff={type:"start"},bg={type:"end"},kh=new On,Sg=new pn,aS=Math.cos(70*Qr.DEG2RAD),Ut=new w,ln=2*Math.PI,lt={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},Uf=1e-6,Vh=class extends Hr{constructor(e,t=null){super(e,t),this.state=lt.NONE,this.target=new w,this.cursor=new w,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.keyRotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:Mi.ROTATE,MIDDLE:Mi.DOLLY,RIGHT:Mi.PAN},this.touches={ONE:Si.ROTATE,TWO:Si.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this._lastPosition=new w,this._lastQuaternion=new vt,this._lastTargetPosition=new w,this._quat=new vt().setFromUnitVectors(e.up,new w(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new Ps,this._sphericalDelta=new Ps,this._scale=1,this._panOffset=new w,this._rotateStart=new Y,this._rotateEnd=new Y,this._rotateDelta=new Y,this._panStart=new Y,this._panEnd=new Y,this._panDelta=new Y,this._dollyStart=new Y,this._dollyEnd=new Y,this._dollyDelta=new Y,this._dollyDirection=new w,this._mouse=new Y,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=lS.bind(this),this._onPointerDown=cS.bind(this),this._onPointerUp=hS.bind(this),this._onContextMenu=_S.bind(this),this._onMouseWheel=fS.bind(this),this._onKeyDown=pS.bind(this),this._onTouchStart=mS.bind(this),this._onTouchMove=gS.bind(this),this._onMouseDown=uS.bind(this),this._onMouseMove=dS.bind(this),this._interceptControlDown=xS.bind(this),this._interceptControlUp=yS.bind(this),this.domElement!==null&&this.connect(this.domElement),this.update()}connect(e){super.connect(e),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerUp),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.getRootNode().addEventListener("keydown",this._interceptControlDown,{passive:!0,capture:!0}),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerUp),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.stopListenToKeyEvents(),this.domElement.getRootNode().removeEventListener("keydown",this._interceptControlDown,{capture:!0}),this.domElement.style.touchAction="auto"}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents(e){e.addEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=e}stopListenToKeyEvents(){this._domElementKeyEvents!==null&&(this._domElementKeyEvents.removeEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=null)}saveState(){this.target0.copy(this.target),this.position0.copy(this.object.position),this.zoom0=this.object.zoom}reset(){this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.zoom=this.zoom0,this.object.updateProjectionMatrix(),this.dispatchEvent(Mg),this.update(),this.state=lt.NONE}update(e=null){let t=this.object.position;Ut.copy(t).sub(this.target),Ut.applyQuaternion(this._quat),this._spherical.setFromVector3(Ut),this.autoRotate&&this.state===lt.NONE&&this._rotateLeft(this._getAutoRotationAngle(e)),this.enableDamping?(this._spherical.theta+=this._sphericalDelta.theta*this.dampingFactor,this._spherical.phi+=this._sphericalDelta.phi*this.dampingFactor):(this._spherical.theta+=this._sphericalDelta.theta,this._spherical.phi+=this._sphericalDelta.phi);let n=this.minAzimuthAngle,i=this.maxAzimuthAngle;isFinite(n)&&isFinite(i)&&(n<-Math.PI?n+=ln:n>Math.PI&&(n-=ln),i<-Math.PI?i+=ln:i>Math.PI&&(i-=ln),n<=i?this._spherical.theta=Math.max(n,Math.min(i,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(n+i)/2?Math.max(n,this._spherical.theta):Math.min(i,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let s=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{let o=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),s=o!=this._spherical.radius}if(Ut.setFromSpherical(this._spherical),Ut.applyQuaternion(this._quatInverse),t.copy(this.target).add(Ut),this.object.lookAt(this.target),this.enableDamping===!0?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let o=null;if(this.object.isPerspectiveCamera){let a=Ut.length();o=this._clampDistance(a*this._scale);let c=a-o;this.object.position.addScaledVector(this._dollyDirection,c),this.object.updateMatrixWorld(),s=!!c}else if(this.object.isOrthographicCamera){let a=new w(this._mouse.x,this._mouse.y,0);a.unproject(this.object);let c=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),s=c!==this.object.zoom;let l=new w(this._mouse.x,this._mouse.y,0);l.unproject(this.object),this.object.position.sub(l).add(a),this.object.updateMatrixWorld(),o=Ut.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;o!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(o).add(this.object.position):(kh.origin.copy(this.object.position),kh.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(kh.direction))<aS?this.object.lookAt(this.target):(Sg.setFromNormalAndCoplanarPoint(this.object.up,this.target),kh.intersectPlane(Sg,this.target))))}else if(this.object.isOrthographicCamera){let o=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),o!==this.object.zoom&&(this.object.updateProjectionMatrix(),s=!0)}return this._scale=1,this._performCursorZoom=!1,s||this._lastPosition.distanceToSquared(this.object.position)>Uf||8*(1-this._lastQuaternion.dot(this.object.quaternion))>Uf||this._lastTargetPosition.distanceToSquared(this.target)>Uf?(this.dispatchEvent(Mg),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?ln/60*this.autoRotateSpeed*e:ln/60/60*this.autoRotateSpeed}_getZoomScale(e){let t=Math.abs(e*.01);return Math.pow(.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){Ut.setFromMatrixColumn(t,0),Ut.multiplyScalar(-e),this._panOffset.add(Ut)}_panUp(e,t){this.screenSpacePanning===!0?Ut.setFromMatrixColumn(t,1):(Ut.setFromMatrixColumn(t,0),Ut.crossVectors(this.object.up,Ut)),Ut.multiplyScalar(e),this._panOffset.add(Ut)}_pan(e,t){let n=this.domElement;if(this.object.isPerspectiveCamera){let i=this.object.position;Ut.copy(i).sub(this.target);let s=Ut.length();s*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*s/n.clientHeight,this.object.matrix),this._panUp(2*t*s/n.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/n.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/n.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(e,t){if(!this.zoomToCursor)return;this._performCursorZoom=!0;let n=this.domElement.getBoundingClientRect(),i=e-n.left,s=t-n.top,o=n.width,a=n.height;this._mouse.x=i/o*2-1,this._mouse.y=-(s/a)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);let t=this.domElement;this._rotateLeft(ln*this._rotateDelta.x/t.clientHeight),this._rotateUp(ln*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){this._updateZoomParameters(e.clientX,e.clientY),e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY>0&&this._dollyOut(this._getZoomScale(e.deltaY)),this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(ln*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),t=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(-ln*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),t=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(ln*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),t=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(-ln*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),t=!0;break}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(this._pointers.length===1)this._rotateStart.set(e.pageX,e.pageY);else{let t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._rotateStart.set(n,i)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{let t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._panStart.set(n,i)}}_handleTouchStartDolly(e){let t=this._getSecondPointerPosition(e),n=e.pageX-t.x,i=e.pageY-t.y,s=Math.sqrt(n*n+i*i);this._dollyStart.set(0,s)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{let n=this._getSecondPointerPosition(e),i=.5*(e.pageX+n.x),s=.5*(e.pageY+n.y);this._rotateEnd.set(i,s)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);let t=this.domElement;this._rotateLeft(ln*this._rotateDelta.x/t.clientHeight),this._rotateUp(ln*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(this._pointers.length===1)this._panEnd.set(e.pageX,e.pageY);else{let t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._panEnd.set(n,i)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){let t=this._getSecondPointerPosition(e),n=e.pageX-t.x,i=e.pageY-t.y,s=Math.sqrt(n*n+i*i);this._dollyEnd.set(0,s),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);let o=(e.pageX+t.x)*.5,a=(e.pageY+t.y)*.5;this._updateZoomParameters(o,a)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId){this._pointers.splice(t,1);return}}_isTrackingPointer(e){for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId)return!0;return!1}_trackPointer(e){let t=this._pointerPositions[e.pointerId];t===void 0&&(t=new Y,this._pointerPositions[e.pointerId]=t),t.set(e.pageX,e.pageY)}_getSecondPointerPosition(e){let t=e.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[t]}_customWheelEvent(e){let t=e.deltaMode,n={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:n.deltaY*=16;break;case 2:n.deltaY*=100;break}return e.ctrlKey&&!this._controlActive&&(n.deltaY*=10),n}};function cS(r){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(r.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(r)&&(this._addPointer(r),r.pointerType==="touch"?this._onTouchStart(r):this._onMouseDown(r)))}function lS(r){this.enabled!==!1&&(r.pointerType==="touch"?this._onTouchMove(r):this._onMouseMove(r))}function hS(r){switch(this._removePointer(r),this._pointers.length){case 0:this.domElement.releasePointerCapture(r.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(bg),this.state=lt.NONE;break;case 1:let e=this._pointers[0],t=this._pointerPositions[e];this._onTouchStart({pointerId:e,pageX:t.x,pageY:t.y});break}}function uS(r){let e;switch(r.button){case 0:e=this.mouseButtons.LEFT;break;case 1:e=this.mouseButtons.MIDDLE;break;case 2:e=this.mouseButtons.RIGHT;break;default:e=-1}switch(e){case Mi.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(r),this.state=lt.DOLLY;break;case Mi.ROTATE:if(r.ctrlKey||r.metaKey||r.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(r),this.state=lt.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(r),this.state=lt.ROTATE}break;case Mi.PAN:if(r.ctrlKey||r.metaKey||r.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(r),this.state=lt.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(r),this.state=lt.PAN}break;default:this.state=lt.NONE}this.state!==lt.NONE&&this.dispatchEvent(Ff)}function dS(r){switch(this.state){case lt.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(r);break;case lt.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(r);break;case lt.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(r);break}}function fS(r){this.enabled===!1||this.enableZoom===!1||this.state!==lt.NONE||(r.preventDefault(),this.dispatchEvent(Ff),this._handleMouseWheel(this._customWheelEvent(r)),this.dispatchEvent(bg))}function pS(r){this.enabled!==!1&&this._handleKeyDown(r)}function mS(r){switch(this._trackPointer(r),this._pointers.length){case 1:switch(this.touches.ONE){case Si.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(r),this.state=lt.TOUCH_ROTATE;break;case Si.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(r),this.state=lt.TOUCH_PAN;break;default:this.state=lt.NONE}break;case 2:switch(this.touches.TWO){case Si.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(r),this.state=lt.TOUCH_DOLLY_PAN;break;case Si.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(r),this.state=lt.TOUCH_DOLLY_ROTATE;break;default:this.state=lt.NONE}break;default:this.state=lt.NONE}this.state!==lt.NONE&&this.dispatchEvent(Ff)}function gS(r){switch(this._trackPointer(r),this.state){case lt.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(r),this.update();break;case lt.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(r),this.update();break;case lt.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(r),this.update();break;case lt.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(r),this.update();break;default:this.state=lt.NONE}}function _S(r){this.enabled!==!1&&r.preventDefault()}function xS(r){r.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function yS(r){r.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}window.THREE=sf;window.GLTFLoader=Bh;window.OrbitControls=Vh;})();+/*! Bundled license information:++three/build/three.core.js:+three/build/three.module.js:+ (**+ * @license+ * Copyright 2010-2025 Three.js Authors+ * SPDX-License-Identifier: MIT+ *)+*/diff --git a/harness/calibrate.py b/harness/calibrate.pynew file mode 100644index 0000000..76bfa0a--- /dev/null+++ b/harness/calibrate.py@@ -0,0 +1,34 @@+#!/usr/bin/env python3+"""Calibration (L1): prove the ruler tells good from bad, per ruler.+green = the bred example wolf (must build clean)+red = legacy multi-fault wolf (must be blocked)+red_5050 = violates ONLY the 50:50 proportion rule — must be blocked AND the+ block reason must actually be 'proportion' (a red sample that fails+ for other reasons proves nothing about this ruler)."""+import subprocess, os, sys, tempfile+H = os.path.dirname(os.path.abspath(__file__))+R = os.path.join(H, '..')+tmp = tempfile.mkdtemp(prefix='calib_')++def build(spec):+ p = subprocess.run(['node', os.path.join(R, 'engine', 'cli.js'),+ os.path.join(R, 'calibration', spec),+ os.path.join(tmp, spec + '.glb')],+ capture_output=True, text=True)+ return p.returncode, p.stderr++rc_g, _ = build('wolf_green.json')+rc_r, _ = build('wolf_red.json')+rc_5, err5 = build('red_5050.json')+ok_g = rc_g == 0+ok_r = rc_r != 0+ok_5 = rc_5 != 0 and 'proportion' in err5++print(f"green (known-good) -> {'PASS ✓' if ok_g else 'blocked ✗ (ruler too strict)'}")+print(f"red (multi-fault) -> {'blocked ✓' if ok_r else 'PASSED ✗ (ruler too loose)'}")+print(f"red_5050 (only 50:50) -> {'blocked by proportion ✓' if ok_5 else 'NOT blocked by proportion ✗'}")+if ok_g and ok_r and ok_5:+ print('[calibrate] OK: the rulers separate good from bad.')+else:+ print('[calibrate] FAILED — do not start work; report this.')+ sys.exit(1)diff --git a/harness/deliver.py b/harness/deliver.pynew file mode 100644index 0000000..5b5f013--- /dev/null+++ b/harness/deliver.py@@ -0,0 +1,144 @@+#!/usr/bin/env python3+"""Delivery packer (L1, zero handwork): stamped GLB + showroom viewer + hero shots + upload pack.++usage: python3 deliver.py <model.glb> <delivery_dir> <name>+ [--title "Monster Name"] [--author "Signature"] [--gate gate.json]++outputs in <delivery_dir>:+ <name>.glb final stamped model (identity written INTO the file)+ <name>_viewer.html offline showroom (open by double-click, no server)+ hero.png / hero.jpg 1024² hero shots (transparent / studio grey)+ upload/ ready-to-drag backup pack for gobkit.com/community/upload++stamping (asset block):+ generator anyCreature v<VERSION>+ copyright --author (the creature's human, not the tool)+ extras.harness/.harness_version/.spec tool identity+ extras.monster --title (display name)+ extras.gate --gate JSON, ONLY if it holds really-run check results+CC0 licence is NOT stamped here — publish.mjs adds it at upload, after consent.+"""+import sys, os, json, base64, struct, shutil, subprocess, html++HERE = os.path.dirname(os.path.abspath(__file__))++def read_version():+ for p in (os.path.join(HERE, '..', 'VERSION'), os.path.join(HERE, 'VERSION')):+ try:+ return open(p).read().strip()+ except OSError:+ pass+ return '0.0.0'++def parse_glb(raw):+ assert raw[:4] == b'glTF', 'need a binary .glb (compiler output)'+ jlen, jtype = struct.unpack('<II', raw[12:20])+ g = json.loads(raw[20:20 + jlen])+ bin_chunk = b''+ off = 20 + jlen+ if off < len(raw):+ blen, btype = struct.unpack('<II', raw[off:off + 8])+ bin_chunk = raw[off + 8: off + 8 + blen]+ return g, bin_chunk++def pack_glb(g, bin_chunk):+ js = json.dumps(g, separators=(',', ':')).encode()+ while len(js) % 4: js += b' '+ body = bytearray(bin_chunk)+ while len(body) % 4: body.append(0)+ total = 12 + 8 + len(js) + 8 + len(body)+ return (struct.pack('<4sII', b'glTF', 2, total)+ + struct.pack('<II', len(js), 0x4E4F534A) + js+ + struct.pack('<II', len(body), 0x004E4942) + bytes(body))++def stamp(g, name, title, author, gate):+ a = g.setdefault('asset', {})+ a['version'] = '2.0'+ a['generator'] = f'anyCreature v{read_version()}'+ if author: a['copyright'] = author+ x = a.setdefault('extras', {})+ x['harness'] = 'anyCreature'+ x['harness_version'] = read_version()+ x['spec'] = x.get('spec') or name+ if title: x['monster'] = title+ if gate: x['gate'] = gate+ return g++# The showroom layout lives in harness/assets/showroom.html so it can be+# redesigned without touching this file. Placeholders: __TITLE__ __BYLINE__+# __BUNDLE__ __B64__.+def read_showroom():+ return open(os.path.join(HERE, 'assets', 'showroom.html'), encoding='utf-8').read()+++UPLOAD_README = """Backup upload path (no key, no account needed):+ 1. open https://gobkit.com/community/upload+ 2. drag creature.glb into the page+Your monster's name and signature are already written inside the file, so the+listing will show them automatically. Uploads via this page go through a short+review before appearing. Uploading releases the model under CC0.+"""++def main():+ args = sys.argv[1:]+ def opt(flag):+ if flag in args:+ i = args.index(flag); v = args[i + 1]; del args[i:i + 2]; return v+ return None+ title, author, gatep = opt('--title'), opt('--author'), opt('--gate')+ if len(args) < 3:+ sys.exit('usage: python3 deliver.py <model.glb> <delivery_dir> <name> [--title T] [--author A] [--gate g.json]')+ src, outdir, name = args[0], args[1], args[2]+ os.makedirs(outdir, exist_ok=True)++ gate = None+ if gatep:+ gate = json.load(open(gatep))+ assert isinstance(gate, dict) and 'checks' in gate, 'gate.json must hold REAL check results ({passed, checks:[...]})'+ # A stamp claiming "passed" while listing a failure is worse than no stamp:+ # it is written into the GLB and travels onto the community wall. Seen in+ # the wild — a delivered model carried passed:true with mid_face_blindread+ # failed in the same object. Either fix the check or say it failed.+ failed = [c.get('name', '?') for c in gate['checks'] if not c.get('passed')]+ if failed and gate.get('passed'):+ raise SystemExit(+ '[deliver] REFUSED: gate.json says "passed": true but these checks failed: '+ + ', '.join(failed) + '.\n'+ ' The gate stamp is written into the model and travels with it forever.\n'+ ' Fix the check and re-run, or set "passed": false and deliver it honestly.')++ g, bin_chunk = parse_glb(open(src, 'rb').read())+ g = stamp(g, name, title, author, gate)+ glb = pack_glb(g, bin_chunk)+ glb_path = os.path.join(outdir, f'{name}.glb')+ open(glb_path, 'wb').write(glb)++ # showroom viewer+ bundle = open(os.path.join(HERE, 'assets', 'three-bundle.js'), encoding='utf-8').read()+ disp = title or name.replace('_', ' ').title()+ byline = (f'{author} · ' if author else '') + f'anyCreature {read_version()}'+ # The name and the signature come from a human and land inside markup, so+ # they are escaped before substitution. Unescaped, a creature called+ # `</h1><script>…` executed in the delivered viewer — and the same string+ # travels in the GLB to the community wall.+ page = (read_showroom().replace('__TITLE__', html.escape(disp, quote=True))+ .replace('__BYLINE__', html.escape(byline, quote=True))+ .replace('__BUNDLE__', bundle)+ .replace('__B64__', base64.b64encode(glb).decode()))+ open(os.path.join(outdir, f'{name}_viewer.html'), 'w', encoding='utf-8').write(page)++ # hero shots (transparent + studio) — the hero NEVER shows the label card+ subprocess.run(['node', os.path.join(HERE, 'hero.mjs'), glb_path, outdir], check=True)++ # backup upload pack (web drag path)+ up = os.path.join(outdir, 'upload'); os.makedirs(up, exist_ok=True)+ shutil.copy(glb_path, os.path.join(up, 'creature.glb'))+ shutil.copy(os.path.join(outdir, 'hero.png'), os.path.join(up, 'hero.png'))+ open(os.path.join(up, 'README.txt'), 'w').write(UPLOAD_README)++ print(f'[deliver] done: {name}.glb · {name}_viewer.html · hero.png/jpg · upload/'+ f'\n[deliver] stamped: {disp}{" " + byline if byline else ""} · gate={"yes" if gate else "no"}'+ f'\n[deliver] checklist: glb, viewer, heroes, spec JSON, DEVLOG one-liner')++if __name__ == '__main__':+ main()diff --git a/harness/gobkit.json b/harness/gobkit.jsonnew file mode 100644index 0000000..b4088bb--- /dev/null+++ b/harness/gobkit.json@@ -0,0 +1,6 @@+{+ "endpoint": "https://gobkit.com/api/community",+ "channel": "harness",+ "key": "gk_ugc_pub_8521725c13a6904bc70334af17f9e7ed76f16a9458f5d779",+ "_key_label": "anyCreature 1.2.0 — PUBLIC BY DESIGN. This is an anonymous UGC submission key, meant to ship inside the package; it grants nothing but the right to post to the community wall, and abuse is bounded server-side by rate limiting and review. It is not a secret and finding it in the repo is not a leak. Note that rotating it does not retract it — old keys stay readable in git history, so retirement has to happen server-side."+}\ No newline at end of filediff --git a/harness/hero.mjs b/harness/hero.mjsnew file mode 100644index 0000000..a79d370--- /dev/null+++ b/harness/hero.mjs@@ -0,0 +1,98 @@+// anyCreature — hero shot renderer. Author: Ariescar.+// Renders the delivery hero images from the final GLB:+// hero.png 1024×1024, TRANSPARENT background, 45° three-quarter view,+// idle mid-frame, ≥8% margin on every side (nothing cropped)+// hero.jpg same shot over the studio grey backdrop+// usage: node harness/hero.mjs <model.glb> <outdir>+import { chromium } from 'playwright';+import fs from 'fs'; import path from 'path'; import http from 'http';+import { fileURLToPath } from 'url';++const here = path.dirname(fileURLToPath(import.meta.url));+const [modelPath, outDir] = process.argv.slice(2);+if (!modelPath || !outDir) { console.error('usage: node hero.mjs <model.glb> <outdir>'); process.exit(2); }+fs.mkdirSync(outDir, { recursive: true });++const html = `<!doctype html><body style="margin:0;background:transparent"><script src="/bundle.js"></script><script>+const S=1024;+const scene=new THREE.Scene(); scene.background=null;+const cam=new THREE.PerspectiveCamera(32,1,0.01,500);+const r=new THREE.WebGLRenderer({antialias:true,alpha:true,preserveDrawingBuffer:true});+r.setSize(S,S); r.outputColorSpace=THREE.SRGBColorSpace; document.body.appendChild(r.domElement);+scene.add(new THREE.HemisphereLight(0xffffff,0x8a8578,1.5));+const key=new THREE.DirectionalLight(0xffffff,2.4); key.position.set(3,4,2.5); scene.add(key);+const fill=new THREE.DirectionalLight(0xcfd8ff,1.0); fill.position.set(-4,1.5,2); scene.add(fill);+const rim=new THREE.DirectionalLight(0xaac4ff,1.6); rim.position.set(-2.5,2.5,-4); scene.add(rim);+let cur=null,mixer=null,anims=[];+window.load=(url)=>new Promise((res,rej)=>{ fetch(url).then(x=>x.arrayBuffer()).then(buf=>{+ new GLTFLoader().parse(buf,'',g=>{ cur=g.scene; scene.add(cur);+ cur.traverse(o=>{o.frustumCulled=false});+ anims=g.animations||[];+ const idle=anims.find(a=>a.name==='idle');+ if(idle){ mixer=new THREE.AnimationMixer(cur);+ mixer.clipAction(idle).play(); mixer.update(idle.duration*0.3); }+ res(1);},e=>rej(String(e))); }); });+window.shoot=(dist,panX,panY)=>{ const box=new THREE.Box3().setFromObject(cur),+ c=box.getCenter(new THREE.Vector3()), sz=box.getSize(new THREE.Vector3());+ const rad=Math.max(sz.x,sz.y,sz.z);+ cam.position.copy(c).add(new THREE.Vector3(1,0.5,1).normalize().multiplyScalar(rad*dist));+ cam.lookAt(c);+ if(panX||panY){ // recentre: shift camera AND target along camera right/up+ const right=new THREE.Vector3().setFromMatrixColumn(cam.matrix,0);+ const up=new THREE.Vector3().setFromMatrixColumn(cam.matrix,1);+ const off=right.multiplyScalar(panX).add(up.multiplyScalar(panY));+ cam.position.add(off); c.add(off); cam.lookAt(c);+ }+ r.render(scene,cam);+ const g2=r.domElement.getContext('webgl2')||r.domElement.getContext('webgl');+ const px=new Uint8Array(S*S*4); g2.readPixels(0,0,S,S,g2.RGBA,g2.UNSIGNED_BYTE,px);+ let x0=S,x1=-1,y0=S,y1=-1;+ for(let y=0;y<S;y++)for(let x=0;x<S;x++) if(px[(y*S+x)*4+3]>8){+ if(x<x0)x0=x; if(x>x1)x1=x; if(y<y0)y0=y; if(y>y1)y1=y; }+ const camDist=rad*dist, half=camDist*Math.tan(cam.fov/2*Math.PI/180);+ return { png:r.domElement.toDataURL('image/png'),+ frac: x1<0?0:Math.max(x1-x0+1,y1-y0+1)/S,+ // gl reads y-up, matching NDC — world offset of the alpha centre+ ndcX:((x0+x1)/2-S/2)/(S/2)*half, ndcY:((y0+y1)/2-S/2)/(S/2)*half };+};+window.jpg=()=>{ const cv=document.createElement('canvas'); cv.width=cv.height=S;+ const ctx=cv.getContext('2d'); ctx.fillStyle='#4c4c51'; ctx.fillRect(0,0,S,S);+ ctx.drawImage(r.domElement,0,0); return cv.toDataURL('image/jpeg',0.92); };+</script></body>`;++const srv = http.createServer((q, res) => {+ if (q.url === '/') { res.writeHead(200, { 'content-type': 'text/html' }); return res.end(html); }+ if (q.url === '/bundle.js') { res.writeHead(200, { 'content-type': 'text/javascript' }); return res.end(fs.readFileSync(path.join(here, 'assets/three-bundle.js'))); }+ if (q.url === '/model.glb') { res.writeHead(200); return res.end(fs.readFileSync(modelPath)); }+ res.writeHead(404); res.end();+});+// loopback only, and let the OS pick the port — a fixed port on 0.0.0.0+// exposed the page and the model to the whole network, and collided+// whenever two runs overlapped.+await new Promise(r => srv.listen(0, '127.0.0.1', r));+const port = srv.address().port;+// Let Playwright locate its own browser; PW_CHROMIUM_PATH pins it if needed.+const br = await chromium.launch({ executablePath: process.env.PW_CHROMIUM_PATH || undefined,+ args: ['--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader']+ .concat(process.env.PW_NO_SANDBOX === '1' ? ['--no-sandbox'] : []) });+const pg = await br.newPage({ viewport: { width: 1044, height: 1044 } });+await pg.goto(`http://127.0.0.1:${port}/`);+await pg.evaluate(() => window.load('/model.glb'));+await pg.waitForTimeout(500);++// iterative fit: rescale so the long side is 84%, then pan the camera so the+// alpha bbox centres — both re-measured, so margins land ≥8% on every side+let dist = 2.6, panX = 0, panY = 0;+let shot = await pg.evaluate(a => window.shoot(a.d, a.x, a.y), { d: dist, x: 0, y: 0 });+for (let i = 0; i < 3 && shot.frac > 0.01; i++) {+ dist = dist * shot.frac / 0.83;+ panX += shot.ndcX; panY += shot.ndcY;+ shot = await pg.evaluate(a => window.shoot(a.d, a.x, a.y), { d: dist, x: panX, y: panY });+ if (Math.abs(shot.frac - 0.83) < 0.02 && Math.hypot(shot.ndcX, shot.ndcY) < 0.01) break;+}+const jpg = await pg.evaluate(() => window.jpg());+await br.close(); srv.close();++fs.writeFileSync(path.join(outDir, 'hero.png'), Buffer.from(shot.png.split(',')[1], 'base64'));+fs.writeFileSync(path.join(outDir, 'hero.jpg'), Buffer.from(jpg.split(',')[1], 'base64'));+console.log(JSON.stringify({ ok: true, margin: +((1 - shot.frac) / 2 * 100).toFixed(1) + 0 }));diff --git a/harness/judge.mjs b/harness/judge.mjsnew file mode 100644index 0000000..0de74e0--- /dev/null+++ b/harness/judge.mjs@@ -0,0 +1,285 @@+// Generic creature mechanical judge (engine layer, L1) — renders (silhouette / ID / beauty) + pure numeric measurement, zero LLM.+// The engine contains no creature-specific vocabulary; all identity claims live in the spec JSON.+//+// usage: node judge.mjs <model.gltf|glb> <outDir> <name> [--spec creature.json] [--stage LOW|MID|HIGH]+// no --spec = measure only, emit metrics JSON (for humans or for scoring)+// with --spec = check every claim in the spec; any failure exits 1 (symptom-first messages)+//+// spec JSON = { "name": "...", "claims": [ {type, ...params, "label": "plain-language description"} ] }+// Supported claim types (add a new one in CHECKS; keep the engine creature-agnostic):+// part_exists {part} — a material/part with this name must exist+// part_visible {part, view?, min_share} — minimum share of body pixels the part holds in a given view+// part_signature {part, view?, min_share, or_min_span} — signature part: share OR span ratio must clear its bar+// style_dark {view?, max_median_lum} — dark styling: body median luminance must not exceed the cap+// style_light {view?, min_median_lum} — light styling: must not fall below the floor+// rig_skinned {} — must be skinned (bones move nothing without skin weights)+// anim_named {names:[...]} — these named animations must be present+// tri_budget {min, max} — triangle budget band+// share_hierarchy {primary:[..],secondary:[..],tertiary:[..],view?,tolerance?} — primary/secondary/tertiary shares ≈6:3:1+// focal_contrast {a, b, view?, min_ratio?} — the two focal parts' shares must differ by ≥N× (default 2)+// saturation_area {view?, min?, max?} — share of the view carrying a highly saturated colour+// (HSV S ≥ 0.50 on the UNLIT baked colour). Default band+// 0.10–0.34. Says how much, never where.+import { chromium } from 'playwright';+import path from 'path'; import fs from 'fs'; import http from 'http';+import { fileURLToPath } from 'url';++const args = process.argv.slice(2);+const si = args.indexOf('--spec');+const specFile = si >= 0 ? args.splice(si, 2)[1] : null;+const sti = args.indexOf('--stage');+const stageFilter = sti >= 0 ? args.splice(sti, 2)[1].toUpperCase() : null; // LOW/MID/HIGH; none = check all+const [src, outDir, name] = args;+if (!src || !outDir || !name) { console.error('usage: node judge.mjs <model> <outDir> <name> [--spec spec.json]'); process.exit(2); }+const root = path.dirname(fileURLToPath(import.meta.url));+const abs = path.resolve(src);+fs.mkdirSync(outDir, { recursive: true });++const PAGE = `<!doctype html><html><head><meta charset="utf-8">+<script type="importmap">{"imports":{"three":"/node_modules/three/build/three.module.js",+"three/addons/":"/node_modules/three/examples/jsm/"}}</script></head><body style="margin:0">+<script type="module">+import * as THREE from 'three';+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+const W=512,H=512;+const r=new THREE.WebGLRenderer({antialias:false,preserveDrawingBuffer:true});+r.setSize(W,H); r.setPixelRatio(1); document.body.appendChild(r.domElement);+const scene=new THREE.Scene(); scene.background=new THREE.Color(0xffffff);+const gltf=await new GLTFLoader().loadAsync('/__model');+const model=gltf.scene; scene.add(model);+const anims=(gltf.animations||[]).map(a=>a.name);+let skins=0; model.traverse(o=>{ if(o.isSkinnedMesh) skins++; });++const groups=new Map();+model.traverse(o=>{ if(!o.isMesh) return;+ const mats=Array.isArray(o.material)?o.material:[o.material];+ const n=(mats[0]?.name||'unnamed').toLowerCase();+ if(!groups.has(n)) groups.set(n,[]);+ groups.get(n).push(o); });+const names=[...groups.keys()];+const idMat=new Map();+names.forEach((n,i)=>{ const id=i+1;+ idMat.set(n,new THREE.MeshBasicMaterial({color:new THREE.Color((id&3)/3,((id>>2)&3)/3,((id>>4)&3)/3),side:THREE.DoubleSide})); });+const idRGB=names.map((n,i)=>{const id=i+1;return [Math.round((id&3)/3*255),Math.round(((id>>2)&3)/3*255),Math.round(((id>>4)&3)/3*255)];});++// per-group world bbox (skinned parts use undeformed vertices ≈ rest pose)+const gb={};+for(const [n,ms] of groups){ const b=new THREE.Box3();+ for(const m of ms){ m.updateWorldMatrix(true,false);+ const pos=m.geometry.attributes.position; const idx=m.geometry.index; const v=new THREE.Vector3();+ // ★ Measure only the vertices the index actually references — glTF primitives often share one POSITION accessor;+ // scanning attributes directly measures every group's bbox as the whole body.+ if(idx){ const seen=new Set();+ for(let i=0;i<idx.count;i++){ const k=idx.getX(i); if(seen.has(k))continue; seen.add(k);+ v.fromBufferAttribute(pos,k).applyMatrix4(m.matrixWorld); b.expandByPoint(v); } }+ else for(let i=0;i<pos.count;i++){ v.fromBufferAttribute(pos,i).applyMatrix4(m.matrixWorld); b.expandByPoint(v); } }+ gb[n]={min:b.min.toArray(),max:b.max.toArray()}; }+const box=new THREE.Box3().setFromObject(model);+const size=box.getSize(new THREE.Vector3()), c=box.getCenter(new THREE.Vector3());+const rad=Math.max(size.x,size.y,size.z);+const cam=new THREE.PerspectiveCamera(35,1,rad*0.01,rad*100);+const VIEWS={front:[0,0.12,1],side:[1,0.12,0],tq:[0.8,0.3,0.8],reartq:[-0.8,0.3,-0.8],top:[0.02,1,0.02]};++const cv=document.createElement('canvas'); cv.width=W; cv.height=H;+const cx=cv.getContext('2d',{willReadFrequently:true});+function grab(){ cx.drawImage(r.domElement,0,0); return cx.getImageData(0,0,W,H).data; }+function shoot(analyze){ const out={},px={};+ for(const [vn,v] of Object.entries(VIEWS)){+ const d=new THREE.Vector3(...v).normalize().multiplyScalar(rad*2.5);+ cam.position.copy(c).add(d); cam.lookAt(c); cam.updateProjectionMatrix();+ r.render(scene,cam); out[vn]=r.domElement.toDataURL('image/png');+ if(analyze) px[vn]=analyze(grab()); }+ return {out,px}; }++// 1) beauty (original materials + lights, sRGB = what the display actually shows) → measure luminance+r.outputColorSpace=THREE.SRGBColorSpace;+const hemi=new THREE.HemisphereLight(0xffffff,0x888877,0.9);+const key=new THREE.DirectionalLight(0xffffff,1.6); key.position.set(2,3,2);+const fill=new THREE.DirectionalLight(0xffffff,0.5); fill.position.set(-2,1,-1);+scene.add(hemi,key,fill);+const beauty=shoot(d=>{ const lums=[];+ for(let i=0;i<d.length;i+=4){ const R=d[i],G=d[i+1],B=d[i+2];+ if(R>248&&G>248&&B>248) continue; // white background+ lums.push(0.2126*R+0.7152*G+0.0722*B); }+ lums.sort((a,b)=>a-b);+ return {bodyPx:lums.length, medianLum:lums.length?lums[Math.floor(lums.length/2)]:255}; });+scene.remove(hemi,key,fill);+r.outputColorSpace=THREE.LinearSRGBColorSpace;++// 1b) albedo — the baked vertex colours with NO lighting, so saturation can be+// measured independently of brightness. gradient, grain and AO are all uniform+// multiplies, so they move a pixel's value but never its HSV saturation; lights+// do move it (a white key washes colour out, a blue rim invents it). Measuring+// here is the only way "how much of this creature is highly saturated" comes out+// as an honest area rather than a lighting artefact.+r.outputColorSpace=THREE.SRGBColorSpace;+const albedoMat=new Map();+model.traverse(o=>{ if(o.isMesh){ albedoMat.set(o,o.material);+ o.material=new THREE.MeshBasicMaterial({vertexColors:!!o.geometry.attributes.color,+ color:o.geometry.attributes.color?0xffffff:(o.material.color?o.material.color.clone():0xffffff),+ side:THREE.DoubleSide}); }});+const albedo=shoot(d=>{ let body=0,hi=0;+ for(let i=0;i<d.length;i+=4){ const R=d[i],G=d[i+1],B=d[i+2];+ if(R>248&&G>248&&B>248) continue; // white background+ body++;+ const mx=Math.max(R,G,B), mn=Math.min(R,G,B);+ if(mx>0 && (mx-mn)/mx>=0.50) hi++; } // HSV saturation ≥ 0.50+ return {bodyPx:body, hiSatPx:hi, hiSatShare: body? hi/body : 0}; });+model.traverse(o=>{ if(o.isMesh) o.material=albedoMat.get(o); });+r.outputColorSpace=THREE.LinearSRGBColorSpace;++// 2) silhouette+const orig=new Map();+model.traverse(o=>{ if(o.isMesh){ orig.set(o,o.material);+ o.material=new THREE.MeshBasicMaterial({color:0x000000,side:THREE.DoubleSide}); }});+const sil=shoot(null);+// 3) ID buffer → per-material pixel counts per view+for(const [n,ms] of groups) for(const m of ms) m.material=idMat.get(n);+const ids=shoot(d=>{ const cnt={}; let body=0;+ for(let i=0;i<d.length;i+=4){ const R=d[i],G=d[i+1],B=d[i+2];+ if(R>248&&G>248&&B>248) continue; body++;+ for(let k=0;k<idRGB.length;k++){ const t=idRGB[k];+ if(Math.abs(R-t[0])<28&&Math.abs(G-t[1])<28&&Math.abs(B-t[2])<28){ cnt[names[k]]=(cnt[names[k]]||0)+1; break; } } }+ return {bodyPx:body,counts:cnt}; });+model.traverse(o=>{ if(o.isMesh) o.material=orig.get(o); });++let tris=0; model.traverse(o=>{ if(o.isMesh){ const g=o.geometry.index;+ tris += g? g.count/3 : o.geometry.attributes.position.count/3; }});+window.__r={ beauty:beauty.out, sil:sil.out, ids:ids.out, albedo:albedo.out,+ lum:beauty.px, idpx:ids.px, sat:albedo.px,+ names, gbox:gb, wbox:{min:box.min.toArray(),max:box.max.toArray()},+ stats:{triangles:Math.round(tris), skinnedMeshes:skins, animations:anims} };+window.__done=true;+</script></body></html>`;++// Static file serving is CONFINED. `path.join(base, urlPath)` is not safe:+// a raw request line carrying "/../../../../etc/passwd" (fetch normalises it,+// a socket does not) escaped every base and served the file, and the listener+// was bound to 0.0.0.0 — arbitrary file read from anywhere on the network,+// /proc/self/environ included. Resolve, then require containment, then allow+// only the extensions the page actually imports.+const OK_EXT = new Set(['.js', '.mjs', '.map', '.json', '.wasm']);+const BASES = [path.dirname(abs), root, path.join(root, '..')].map(b => path.resolve(b));+function safeResolve(urlPath) {+ for (const base of BASES) {+ const f = path.resolve(base, '.' + urlPath);+ if (f !== base && !f.startsWith(base + path.sep)) continue; // escaped the base+ if (!OK_EXT.has(path.extname(f))) continue;+ try { if (fs.statSync(f).isFile()) return f; } catch {}+ }+ return null;+}+const server = http.createServer((req,res)=>{+ let p; try { p = decodeURIComponent(req.url.split('?')[0]); } catch { res.writeHead(400); return res.end(); }+ if(p==='/'){res.writeHead(200,{'Content-Type':'text/html'});return res.end(PAGE);}+ if(p==='/__model'){res.writeHead(200,{'Content-Type':'model/gltf+json'});return res.end(fs.readFileSync(abs));}+ const f = safeResolve(p);+ if(f){res.writeHead(200,{'Content-Type':'text/javascript'});return res.end(fs.readFileSync(f));}+ res.writeHead(404);res.end();+});+// loopback only — nothing here is meant to be reachable from the network+await new Promise(r=>server.listen(0,'127.0.0.1',r));+const port=server.address().port;+// Let Playwright find its own browser. A hardcoded container path breaks every+// clone on macOS/Windows; PW_CHROMIUM_PATH stays available for pinned setups.+const exe = process.env.PW_CHROMIUM_PATH || undefined;+// --no-sandbox drops a real defence and is only needed where the OS sandbox is+// unavailable (docker without SYS_ADMIN, CI images). Opt in, never by default.+const launchArgs=['--use-gl=angle','--use-angle=swiftshader','--enable-unsafe-swiftshader'];+if(process.env.PW_NO_SANDBOX==='1') launchArgs.push('--no-sandbox');+const browser=await chromium.launch({executablePath:exe,args:launchArgs});+const page=await browser.newPage({viewport:{width:560,height:560}});+const errs=[]; page.on('pageerror',e=>errs.push(String(e)));+await page.goto(`http://127.0.0.1:${port}/`);+try{ await page.waitForFunction('window.__done===true',{timeout:120000}); }+catch(e){ console.error('FAILED\n'+errs.join('\n')); await browser.close(); server.close(); process.exit(2); }+const R=await page.evaluate('window.__r');+for(const [vn,d] of Object.entries(R.sil)) fs.writeFileSync(path.join(outDir,`${name}_sil_${vn}.png`),Buffer.from(d.split(',')[1],'base64'));+for(const [vn,d] of Object.entries(R.ids)) fs.writeFileSync(path.join(outDir,`${name}_id_${vn}.png`),Buffer.from(d.split(',')[1],'base64'));+for(const [vn,d] of Object.entries(R.beauty)) fs.writeFileSync(path.join(outDir,`${name}_beauty_${vn}.png`),Buffer.from(d.split(',')[1],'base64'));++// ── Export measurements (every part measured; no name filtering) ──+const sz=b=>[b.max[0]-b.min[0],b.max[1]-b.min[1],b.max[2]-b.min[2]];+const diagXZ=s=>Math.hypot(s[0],s[2]);+const whole=sz(R.wbox);+const share=(vn,mat)=>{ const p=R.idpx[vn]; return p.bodyPx? (p.counts[mat]||0)/p.bodyPx : 0; };+const parts={};+for(const n of R.names){ const b=R.gbox[n]; if(!b) continue; const s=sz(b);+ parts[n]={ size:s,+ share:Object.fromEntries(Object.keys(R.idpx).map(vn=>[vn,+share(vn,n).toFixed(5)])),+ span_ratio:+(diagXZ(s)/(diagXZ(whole)||1)).toFixed(4),+ height_ratio:+(s[1]/(whole[1]||1)).toFixed(4) }; }+const m={ name, stats:R.stats, names:R.names,+ lum:Object.fromEntries(Object.entries(R.lum).map(([vn,x])=>[vn,+x.medianLum.toFixed(1)])),+ hi_sat_share:Object.fromEntries(Object.entries(R.sat).map(([vn,x])=>[vn,+x.hiSatShare.toFixed(4)])),+ parts, whole:{size:whole} };+fs.writeFileSync(path.join(outDir,`${name}_metrics.json`),JSON.stringify(m,null,1));+console.log(JSON.stringify(m));++// ── Spec mode: check every claim, symptom first ──+if(specFile){+ const S=JSON.parse(fs.readFileSync(specFile,'utf8'));+ const bad=[];+ const pct=x=>(x*100).toFixed(2)+'%';+ const CHECKS={+ part_exists(c){ if(!R.names.includes(c.part))+ bad.push(`Part "${c.part}" not measurable: no material by that name in the model (part missing, or naming convention not followed)`); },+ part_visible(c){ if(!R.names.includes(c.part)) return CHECKS.part_exists(c);+ const v=c.view||'side'; const s=share(v,c.part);+ if(s<c.min_share) bad.push(`Part "${c.part}" is nearly invisible in the ${v} view (share ${pct(s)} < ${pct(c.min_share)}) — occluded, too small, or in the wrong place`); },+ part_signature(c){ if(!R.names.includes(c.part)) return CHECKS.part_exists(c);+ const v=c.view||'side'; const s=share(v,c.part); const sp=parts[c.part].span_ratio;+ if(!(s>=c.min_share||sp>=c.or_min_span))+ bad.push(`Signature part \"${c.part}\" is not exaggerated enough: ${v}-view share ${pct(s)} (need ≥${pct(c.min_share)}) and span ratio ${sp} (need ≥${c.or_min_span}) — right now it is just another part; it cannot carry this creature's identity`); },+ style_dark(c){ const v=c.view||'side'; const L=R.lum[v].medianLum;+ if(L>c.max_median_lum) bad.push(`Declared dark but does not read dark on screen: ${v}-view body median luminance ${L.toFixed(0)}/255 (need ≤${c.max_median_lum}) — push the material colour values darker`); },+ style_light(c){ const v=c.view||'side'; const L=R.lum[v].medianLum;+ if(L<c.min_median_lum) bad.push(`Declared light but reads too dark on screen: ${v}-view body median luminance ${L.toFixed(0)}/255 (need ≥${c.min_median_lum})`); },+ // High-saturation AREA, measured on the unlit baked colour (HSV S ≥ 0.50).+ // Too little and the creature is a grey lump; too much and saturation stops+ // being a spotlight and the whole thing screams. Do NOT name which surfaces+ // carry it — where the colour goes is the designer's call, only how much.+ saturation_area(c){ const v=c.view||'tq';+ const s=R.sat[v]; if(!s) return;+ const pct=s.hiSatShare*100, lo=(c.min??0.10)*100, hi=(c.max??0.34)*100;+ if(pct<lo) bad.push(`Too little colour: only ${pct.toFixed(1)}% of the ${v} view is highly saturated (need ≥${lo.toFixed(0)}%) — the creature reads as a grey mass. Raise the saturation of a mass that deserves the attention, do not tint everything.`);+ if(pct>hi) bad.push(`Too much colour: ${pct.toFixed(1)}% of the ${v} view is highly saturated (need ≤${hi.toFixed(0)}%) — saturation stops reading as a spotlight when it covers this much. Desaturate the supporting masses and keep the loud colour on the signature.`); },+ rig_skinned(){ if(R.stats.skinnedMeshes<1)+ bad.push('Model is not skinned: the rig is not bound to the mesh, so animating the bones moves nothing'); },+ anim_named(c){ for(const a of c.names) if(!R.stats.animations.includes(a))+ bad.push(`Missing named animation ${a} (present: ${R.stats.animations.join(',')||'none'})`); },+ tri_budget(c){ const t=R.stats.triangles;+ if(t<c.min||t>c.max) bad.push(`Triangle count ${t} is outside the budget band ${c.min}–${c.max}`); },+ // 6:3:1 hierarchy: the primary / secondary / tertiary part groups must hold roughly+ // 6:3:1 of the frame. An even spread reads as no hierarchy at all — a silhouette needs+ // one mass that clearly leads, one that supports, and detail that stays detail.+ share_hierarchy(c){ const v=c.view||'side';+ const grp=g=>g.reduce((a,p)=>a+(R.names.includes(p)?share(v,p):0),0);+ const [P,S,T]=[grp(c.primary||[]),grp(c.secondary||[]),grp(c.tertiary||[])];+ const tot=P+S+T; if(!tot){ bad.push(`631 hierarchy not measurable: primary/secondary/tertiary parts are all 0 in the ${v} view`); return; }+ const tol=c.tolerance??0.15, want=[0.6,0.3,0.1], got=[P/tot,S/tot,T/tot];+ const off=got.map((g,i)=>Math.abs(g-want[i]));+ if(Math.max(...off)>tol) bad.push(`Hierarchy ratio off: primary/secondary/tertiary = ${got.map(x=>(x*100).toFixed(0)).join(':')} (target 60:30:10, tolerance ±${tol*100}%) — no dominance; the frame is split evenly`); },+ // No equal-weight focal points: two focal parts of the same size make the eye ping-pong+ // between them and neither one wins. The declared pair's shares must differ by ≥ratio×.+ focal_contrast(c){ const v=c.view||'side';+ for(const p of [c.a,c.b]) if(!R.names.includes(p)) return CHECKS.part_exists({part:p});+ const A=share(v,c.a), B=share(v,c.b); const hi=Math.max(A,B), lo=Math.min(A,B);+ const ratio=c.min_ratio??2;+ if(lo>0 && hi/lo<ratio) bad.push(`Two focal points of equal weight compete: "${c.a}" ${(A*100).toFixed(1)}% vs "${c.b}" ${(B*100).toFixed(1)}% (need ≥${ratio}× apart) — the eye ping-pongs between them; open up the dominance gap`); },+ };+ const claims=(S.claims||[]).filter(c=>!stageFilter || !c.stage || c.stage.toUpperCase()===stageFilter);+ for(const c of claims){+ const fn=CHECKS[c.type];+ if(!fn){ bad.push(`Spec contains a claim type the engine does not recognise: "${c.type}"`); continue; }+ const before=bad.length; fn(c);+ if(bad.length>before && c.label) bad[bad.length-1] += ` [${c.label}]`;+ }+ if(bad.length){ console.log('\n'+'='.repeat(68));+ console.log(`BLOCKING — against spec "${S.name||path.basename(specFile)}", the following fail and must be fixed:`);+ for(const b of bad) console.log(' ✗ '+b);+ console.log('='.repeat(68)+`\n${bad.length} blocking item(s). exit 1 — cannot ship.`);+ await browser.close(); server.close(); process.exit(1); }+ console.log(`[judge] Spec \"${S.name||''}\" — all claims pass.`);+}+await browser.close(); server.close();diff --git a/harness/maskmetrics.py b/harness/maskmetrics.pynew file mode 100644index 0000000..21b899e--- /dev/null+++ b/harness/maskmetrics.py@@ -0,0 +1,113 @@+#!/usr/bin/env python3+"""Silhouette measurement report (MEASURES ONLY — judgment belongs to the LLM).+usage: python3 maskmetrics.py <outdir> <img1.png> [img2.png ...]+Per image: crops to content, writes <stem>_thumb24.png / _thumb48.png and+metrics to <outdir>/metrics.json. Also writes sheet.png (all views side by side).+Descriptors: W_over_H, fill, thirds_cols, thirds_rows, compactness+(perimeter^2/4πA: 1=disc, higher=spikier/branchier), neg_pockets (enclosed+whitespace count+sizes), protrusions (direction & sharpness of major limbs/spikes),+com (centre of mass position in bbox, 0..1)."""+import sys, os, json+import numpy as np+from PIL import Image++outdir = sys.argv[1]; os.makedirs(outdir, exist_ok=True)+report = {}+sheets = []+for p in sys.argv[2:]:+ name = os.path.splitext(os.path.basename(p))[0]+ im = np.array(Image.open(p).convert('L'))+ m = im < 128+ if not m.any():+ report[name] = None; continue+ ys, xs = np.where(m)+ m = m[ys.min():ys.max()+1, xs.min():xs.max()+1]+ H, W = m.shape; area = int(m.sum())+ # perimeter: count edge transitions+ per = int((m[:, 1:] != m[:, :-1]).sum() + (m[1:] != m[:-1]).sum()+ + m[0].sum() + m[-1].sum() + m[:, 0].sum() + m[:, -1].sum())+ from scipy import ndimage+ inv = ~m+ lab, n = ndimage.label(inv)+ border = set(lab[0]) | set(lab[-1]) | set(lab[:, 0]) | set(lab[:, -1])+ pockets = sorted([int((lab == i).sum()) for i in range(1, n+1)+ if i not in border and (lab == i).sum() > area*0.002], reverse=True)+ # protrusions: erode heavily -> core; subtract -> appendages; report each blob's+ # direction from core centroid and aspect (long/thin = sharp)+ core = ndimage.binary_erosion(m, iterations=max(2, int(min(H, W)*0.06)))+ app = m & ~ndimage.binary_dilation(core, iterations=max(2, int(min(H, W)*0.06)))+ la, na = ndimage.label(app)+ cy, cx = ndimage.center_of_mass(m)+ protr = []+ for i in range(1, na+1):+ blob = la == i+ s = int(blob.sum())+ if s < area*0.01: continue+ by, bx = ndimage.center_of_mass(blob)+ import math+ ang = math.degrees(math.atan2(-(by-cy), bx-cx)) # 0=right, 90=up+ ys2, xs2 = np.where(blob)+ ext = max(ys2.max()-ys2.min(), xs2.max()-xs2.min()) + 1+ thin = ext*ext / max(s, 1) # higher = longer/thinner = sharper read+ protr.append({'dir_deg': round(ang), 'size': round(s/area, 3), 'thinness': round(thin, 1)})+ protr.sort(key=lambda x: -x['size'])+ # ── dullness flags (MEASURES ONLY, the reader/LLM judges) ──+ # 1:1-frame fill: the silhouette in a square frame must carry real volume+ Ssq = max(H, W)+ sq_fill = area / (Ssq * Ssq)+ # mirror symmetry: IoU with own horizontal flip (front views of bilateral+ # creatures are EXEMPT from judgment on this — measure everywhere, judge per view)+ mf = np.fliplr(m)+ mirror_sym = float((m & mf).sum() / max((m | mf).sum(), 1))+ # straight-line runs: longest constant-slope run on any boundary, as a+ # fraction of that boundary's length (stiff legs / plank wings light this up)+ def longest_const_slope(arr):+ best, cur, slope = 0, 1, None+ for i in range(1, len(arr)):+ if arr[i] < 0 or arr[i-1] < 0:+ cur, slope = 1, None; continue+ s = arr[i] - arr[i-1]+ if slope is not None and s == slope: cur += 1+ else: slope, cur = s, 2+ best = max(best, cur)+ return best+ topB = [-1]*W; botB = [-1]*W; lefB = [-1]*H; rigB = [-1]*H+ for x in range(W):+ col = np.where(m[:, x])[0]+ if len(col): topB[x] = int(col.min()); botB[x] = int(col.max())+ for y in range(H):+ row = np.where(m[y])[0]+ if len(row): lefB[y] = int(row.min()); rigB[y] = int(row.max())+ straight = max(longest_const_slope(topB)/max(W,1), longest_const_slope(botB)/max(W,1),+ longest_const_slope(lefB)/max(H,1), longest_const_slope(rigB)/max(H,1))+ report[name] = {+ 'W_over_H': round(W/H, 2), 'fill': round(area/(H*W), 3),+ 'thirds_cols': [round(float(m[:, i*W//3:(i+1)*W//3].sum()/area), 2) for i in range(3)],+ 'thirds_rows': [round(float(m[i*H//3:(i+1)*H//3].sum()/area), 2) for i in range(3)],+ 'compactness': round(per*per/(4*np.pi*area), 1),+ 'neg_pockets': pockets[:6],+ 'com': [round(float(cx)/W, 2), round(float(cy)/H, 2)],+ 'protrusions': protr[:8],+ 'sq_fill': round(sq_fill, 3),+ 'mirror_sym': round(mirror_sym, 2),+ 'straight_max': round(float(straight), 2),+ }+ sil = Image.fromarray((~m*255).astype(np.uint8))+ for px in (24, 48):+ sil.resize((px, px), Image.LANCZOS).resize((240, 240), Image.NEAREST)\+ .save(os.path.join(outdir, f'{name}_thumb{px}.png'))+ sheets.append((name, sil))+if sheets:+ hmax = 300+ tiles = [(n, s.resize((int(s.width*hmax/s.height), hmax))) for n, s in sheets]+ Wt = sum(t.width for _, t in tiles) + 10*(len(tiles)+1)+ sheet = Image.new('L', (Wt, hmax+40), 255)+ x = 10+ from PIL import ImageDraw+ d = ImageDraw.Draw(sheet)+ for n, t in tiles:+ sheet.paste(t, (x, 30)); d.text((x, 8), n, fill=0); x += t.width + 10+ sheet.save(os.path.join(outdir, 'sheet.png'))+with open(os.path.join(outdir, 'metrics.json'), 'w') as f:+ json.dump(report, f, indent=1)+print(json.dumps(report))diff --git a/harness/presets/boss.json b/harness/presets/boss.jsonnew file mode 100644index 0000000..aeca32e--- /dev/null+++ b/harness/presets/boss.json@@ -0,0 +1,71 @@+{+ "name": "<creature name> (BOSS)",+ "_role": "Viewed close up + exaggerated; signature thresholds raised.",+ "claims": [+ {+ "type": "part_exists",+ "part": "<signature part>",+ "stage": "MID",+ "label": "signature part must exist"+ },+ {+ "type": "part_signature",+ "part": "<signature part>",+ "view": "side",+ "min_share": 0.16,+ "or_min_span": 0.12,+ "stage": "MID",+ "label": "signature presence"+ },+ {+ "type": "focal_contrast",+ "a": "<primary focal>",+ "b": "<secondary focal>",+ "min_ratio": 2,+ "stage": "MID",+ "label": "focal points must not be equal weight"+ },+ {+ "type": "share_hierarchy",+ "primary": [+ "<primary mass…>"+ ],+ "secondary": [+ "<secondary mass…>"+ ],+ "tertiary": [+ "<detail part…>"+ ],+ "stage": "MID",+ "label": "631 hierarchy"+ },+ {+ "type": "rig_skinned",+ "stage": "HIGH"+ },+ {+ "type": "anim_named",+ "names": [+ "idle",+ "move",+ "attack"+ ],+ "stage": "HIGH"+ },+ {+ "type": "saturation_area",+ "view": "tq",+ "min": 0.1,+ "max": 0.34,+ "stage": "HIGH",+ "label": "high-saturation area must sit in the 10%-34% band: amount of colour, not where it goes"+ },+ {+ "type": "tri_budget",+ "min": 4000,+ "max": 9000,+ "stage": "LOW",+ "label": "triangle budget band"+ }+ ]+}\ No newline at end of filediff --git a/harness/presets/minion.json b/harness/presets/minion.jsonnew file mode 100644index 0000000..bddfff6--- /dev/null+++ b/harness/presets/minion.json@@ -0,0 +1,71 @@+{+ "name": "<creature name> (minion)",+ "_role": "Must read at distance; silhouette judged strictly; triangle count kept lean.",+ "claims": [+ {+ "type": "part_exists",+ "part": "<signature part>",+ "stage": "MID",+ "label": "signature part must exist"+ },+ {+ "type": "part_signature",+ "part": "<signature part>",+ "view": "side",+ "min_share": 0.12,+ "or_min_span": 0.12,+ "stage": "MID",+ "label": "signature presence"+ },+ {+ "type": "focal_contrast",+ "a": "<primary focal>",+ "b": "<secondary focal>",+ "min_ratio": 2,+ "stage": "MID",+ "label": "focal points must not be equal weight"+ },+ {+ "type": "share_hierarchy",+ "primary": [+ "<primary mass…>"+ ],+ "secondary": [+ "<secondary mass…>"+ ],+ "tertiary": [+ "<detail part…>"+ ],+ "stage": "MID",+ "label": "631 hierarchy"+ },+ {+ "type": "rig_skinned",+ "stage": "HIGH"+ },+ {+ "type": "anim_named",+ "names": [+ "idle",+ "move",+ "attack"+ ],+ "stage": "HIGH"+ },+ {+ "type": "saturation_area",+ "view": "tq",+ "min": 0.1,+ "max": 0.34,+ "stage": "HIGH",+ "label": "high-saturation area must sit in the 10%-34% band: amount of colour, not where it goes"+ },+ {+ "type": "tri_budget",+ "min": 800,+ "max": 3000,+ "stage": "LOW",+ "label": "triangle budget band"+ }+ ]+}\ No newline at end of filediff --git a/harness/presets/npc.json b/harness/presets/npc.jsonnew file mode 100644index 0000000..cde9259--- /dev/null+++ b/harness/presets/npc.json@@ -0,0 +1,71 @@+{+ "name": "<creature name> (NPC)",+ "_role": "Viewed at mid distance; balanced.",+ "claims": [+ {+ "type": "part_exists",+ "part": "<signature part>",+ "stage": "MID",+ "label": "signature part must exist"+ },+ {+ "type": "part_signature",+ "part": "<signature part>",+ "view": "side",+ "min_share": 0.12,+ "or_min_span": 0.12,+ "stage": "MID",+ "label": "signature presence"+ },+ {+ "type": "focal_contrast",+ "a": "<primary focal>",+ "b": "<secondary focal>",+ "min_ratio": 2,+ "stage": "MID",+ "label": "focal points must not be equal weight"+ },+ {+ "type": "share_hierarchy",+ "primary": [+ "<primary mass…>"+ ],+ "secondary": [+ "<secondary mass…>"+ ],+ "tertiary": [+ "<detail part…>"+ ],+ "stage": "MID",+ "label": "631 hierarchy"+ },+ {+ "type": "rig_skinned",+ "stage": "HIGH"+ },+ {+ "type": "anim_named",+ "names": [+ "idle",+ "move",+ "attack"+ ],+ "stage": "HIGH"+ },+ {+ "type": "saturation_area",+ "view": "tq",+ "min": 0.1,+ "max": 0.34,+ "stage": "HIGH",+ "label": "high-saturation area must sit in the 10%-34% band: amount of colour, not where it goes"+ },+ {+ "type": "tri_budget",+ "min": 1500,+ "max": 5000,+ "stage": "LOW",+ "label": "triangle budget band"+ }+ ]+}\ No newline at end of filediff --git a/harness/publish.mjs b/harness/publish.mjsnew file mode 100644index 0000000..ef88c42--- /dev/null+++ b/harness/publish.mjs@@ -0,0 +1,120 @@+// anyCreature — Gobkit community publisher. Author: Ariescar.+//+// IRON RULE: run this ONLY after the user has explicitly said yes to sharing.+// Never on your own initiative, never in the background, never "to test".+//+// node harness/publish.mjs <model.glb> <hero.png> --title "Name" --creator "Signature"+//+// ── ALWAYS TRY THE UPLOAD FIRST ───────────────────────────────────────────────+// Never decide in advance that the environment cannot reach the network. Cloud+// sandboxes, Cowork sessions and CI runners frequently CAN. Run this command,+// then answer from what it prints. Telling the user "in this environment you+// have to upload by hand" WITHOUT having tried is wrong, and it is the most+// common way a finished creature never reaches the wall.+//+// ── THE THUMBNAIL IS NOT OPTIONAL ─────────────────────────────────────────────+// Always pass hero.png. A submission without an image is NOT rejected, but it+// will not list automatically — it waits for a human reviewer. A missing image+// is the one common reason a creature stalls after a successful upload.+//+// What it does, in order:+// 1. re-stamps the GLB: extras.license = CC0-1.0 (consent just given),+// extras.monster / asset.copyright refreshed from --title / --creator+// 2. POSTs multipart to the endpoint in harness/gobkit.json+// fields: model, thumb, title, creator_name, channel, key+// 3. prints ONE machine-readable JSON line:+// {"status":"published","share_url":"https://gobkit.com/s/…","title":…,"creator":…}+// {"status":"pending_review"} → uploaded; a reviewer lists it shortly+// {"status":"blocked","reason":…} → could not reach the server. NOT an error,+// NOT a key problem — offer the backup path.+// {"status":"error",…} → the server answered and refused; read it out.+//+// ── HOW TO READ A FAILURE ─────────────────────────────────────────────────────+// The submit endpoint ALWAYS answers in JSON. Therefore:+// · HTTP 403 → something between you and the server refused the+// request. It is a filtered network, NOT a bad key;+// 403 is not one of the endpoint's own answers.+// · a non-JSON body → a proxy, captive portal or corporate filter replied+// instead of the server. Blocked.+// · a transport exception → blocked.+// "blocked" is a normal outcome, not a failed run. Tell the user the upload pack+// is ready and give them the drag-and-drop page — no account, no key needed.+import fs from 'fs'; import path from 'path';+import { fileURLToPath } from 'url';++const here = path.dirname(fileURLToPath(import.meta.url));+const args = process.argv.slice(2);+const opt = (f) => { const i = args.indexOf(f); if (i < 0) return null; const v = args[i + 1]; args.splice(i, 2); return v; };+const title = opt('--title'), creator = opt('--creator');+const [glbPath, heroPath] = args;+if (!glbPath) {+ console.error('usage: node publish.mjs <model.glb> <hero.png> --title "Name" --creator "Signature"');+ process.exit(2);+}++const cfg = JSON.parse(fs.readFileSync(path.join(here, 'gobkit.json'), 'utf8'));+const endpoint = process.env.GOBKIT_ENDPOINT || cfg.endpoint;++// ── 1. consent stamp: licence + final naming into the file itself ──+const raw = fs.readFileSync(glbPath);+const jlen = raw.readUInt32LE(12);+const g = JSON.parse(raw.slice(20, 20 + jlen).toString());+const rest = raw.slice(20 + jlen);+const a = g.asset = g.asset || { version: '2.0' };+if (creator) a.copyright = creator;+const x = a.extras = a.extras || {};+if (title) x.monster = title;+x.license = 'CC0-1.0';+let js = Buffer.from(JSON.stringify(g)); while (js.length % 4) js = Buffer.concat([js, Buffer.from(' ')]);+const head = Buffer.alloc(12); head.write('glTF'); head.writeUInt32LE(2, 4);+const jh = Buffer.alloc(8); jh.writeUInt32LE(js.length, 0); jh.writeUInt32LE(0x4E4F534A, 4);+const out = Buffer.concat([head, jh, js, rest]);+out.writeUInt32LE(out.length, 8);+fs.writeFileSync(glbPath, out);++// ── 2. multipart POST ──+const form = new FormData();+form.append('model', new Blob([out], { type: 'model/gltf-binary' }), path.basename(glbPath));+let hasThumb = false;+if (heroPath && fs.existsSync(heroPath)) {+ form.append('thumb', new Blob([fs.readFileSync(heroPath)], { type: 'image/png' }), 'hero.png');+ hasThumb = true;+} else {+ console.error('warn: no hero.png attached — the upload will be accepted but waits for a human '+ + 'reviewer instead of listing automatically. Pass delivery/hero.png.');+}+if (title) form.append('title', title);+if (creator) form.append('creator_name', creator);+form.append('channel', cfg.channel || 'harness');+form.append('key', cfg.key || '');++const blocked = (reason) => {+ console.log(JSON.stringify({ status: 'blocked', reason, thumb: hasThumb }));+ process.exit(0);+};++let res, body;+try {+ res = await fetch(endpoint, { method: 'POST', body: form, signal: AbortSignal.timeout(60000) });+} catch (e) {+ blocked('cannot reach the server: ' + String((e && e.message) || e));+}+// 403 is never one of this endpoint's answers — an intermediary produced it.+// Same for any body that is not JSON.+if (res.status === 403) blocked('HTTP 403 from an intermediary — the network is filtered, not the key');+try {+ body = await res.json();+} catch {+ blocked(`HTTP ${res.status} with a non-JSON body — a proxy or filter answered instead of the server`);+}++// ── 3. one JSON line for the closing dialogue ──+if ((res.status === 200 || res.status === 201) && body.ok && body.status === 'published') {+ const share = body.share_url?.startsWith('http') ? body.share_url : 'https://gobkit.com' + (body.share_url || '');+ console.log(JSON.stringify({ status: 'published', share_url: share,+ title: body.title ?? title, creator: body.creator ?? creator, thumb: hasThumb }));+} else if (body.ok && body.status === 'pending_review') {+ console.log(JSON.stringify({ status: 'pending_review', thumb: hasThumb }));+} else {+ console.log(JSON.stringify({ status: 'error', http: res.status, error: body.error || 'unexpected response' }));+}diff --git a/harness/silmetrics.mjs b/harness/silmetrics.mjsnew file mode 100644index 0000000..4998ea9--- /dev/null+++ b/harness/silmetrics.mjs@@ -0,0 +1,268 @@+// anyCreature — silhouette metrics tool. Author: Ariescar.+// The measuring half of the LOWRES loop. Renders the model as a pure-black+// silhouette (side + front), then computes the FLOOR numbers and the+// CHARACTER-AXIS numbers, plus the 24px thumbnail used by the blind-read gate.+//+// node harness/silmetrics.mjs <model.glb> <outdir> [--prev <outdir_of_previous_round>]+//+// outputs in <outdir>:+// sil_side.png / sil_front.png 640px silhouettes (human review)+// thumb24.png 24px silhouette, nearest-upscaled to 240px+// → show ONLY this image to a context-free+// blind reader; ask (1) "what is this?"+// (2) "which part grabs the eye most?"+// (3) "list the parts/features you can read"+// sil_side.mask.json packed mask (input for next round's --prev)+// metrics.json all numbers, see below+//+// metrics.json:+// W_over_H, fill, mass_thirds — global mass layout+// torso_depth_{min,max}, mass_contrast (max/min torso depth over mid-band)+// leg_fraction — ground→belly gap at mid-body / H+// turn_count — hard silhouette corners (>35°); LOW+// turn_count = the "too round" disease+// zigzag_alignment — fraction of top-contour bumps sitting+// directly above a bottom-contour bump+// (0 = staggered/good, 1 = stacked/stiff)+// iou_vs_prev — regression guard (needs --prev)+//+// These are not pass/fail thresholds. The design card DECLARES a position per+// axis (tension targets); this tool verifies the declared position was reached.+import { chromium } from 'playwright';+import fs from 'fs'; import path from 'path'; import http from 'http';+import { fileURLToPath } from 'url';++const here = path.dirname(fileURLToPath(import.meta.url));+const [modelPath, outDir] = process.argv.slice(2);+const prevIx = process.argv.indexOf('--prev');+const prevDir = prevIx > 0 ? process.argv[prevIx + 1] : null;+if (!modelPath || !outDir) { console.error('usage: node silmetrics.mjs <model.glb> <outdir> [--prev <prev outdir>]'); process.exit(2); }+fs.mkdirSync(outDir, { recursive: true });++const html = `<!doctype html><body style="margin:0"><script src="/bundle.js"></script><script>+const scene=new THREE.Scene(); scene.background=new THREE.Color(0xffffff);+const cam=new THREE.PerspectiveCamera(30,1,0.01,100);+const r=new THREE.WebGLRenderer({antialias:false,preserveDrawingBuffer:true}); r.setSize(640,640);+document.body.appendChild(r.domElement);+let cur=null;+window.load=(url)=>new Promise((res,rej)=>{ fetch(url).then(x=>x.arrayBuffer()).then(buf=>{+ new GLTFLoader().parse(buf,'',g=>{ cur=g.scene; scene.add(cur);+ cur.traverse(o=>{o.frustumCulled=false; if(o.isMesh)o.material=new THREE.MeshBasicMaterial({color:0,side:THREE.DoubleSide});});+ res(1);},e=>rej(String(e))); }); });+window.shoot=(view)=>{ const box=new THREE.Box3().setFromObject(cur),c=box.getCenter(new THREE.Vector3()),s=box.getSize(new THREE.Vector3());+ const long = s.x>s.z ? 'x':'z';+ let dir;+ if(view==='top'){ dir=[0,1,0]; cam.up.set(long==='x'?1:0, 0, long==='x'?0:1); }+ else if(view==='hero'){ cam.up.set(0,1,0); dir=[1,0.5,1]; }+ else { cam.up.set(0,1,0); dir = view==='side' ? (long==='x'?[0,0,1]:[1,0,0]) : (long==='x'?[1,0,0]:[0,0,1]); }+ const rad=Math.max(s.x,s.y,s.z);+ cam.position.copy(c).add(new THREE.Vector3(...dir).multiplyScalar(rad*2.4)); cam.lookAt(c);+ r.render(scene,cam);+ const g2=r.domElement.getContext('webgl2')||r.domElement.getContext('webgl');+ const px=new Uint8Array(640*640*4); g2.readPixels(0,0,640,640,g2.RGBA,g2.UNSIGNED_BYTE,px);+ let bits='';+ for(let y=639;y>=0;y--){ let acc=0,n=0;+ for(let x=0;x<640;x++){ acc=(acc<<1)|(px[(y*640+x)*4]<128?1:0); if(++n===6){bits+=String.fromCharCode(48+acc);acc=0;n=0;} }+ if(n)bits+=String.fromCharCode(48+(acc<<(6-n))); // row-aligned: flush per row+ }+ return { bits, png: r.domElement.toDataURL('image/png') }; };+</script></body>`;++const srv = http.createServer((q, res) => {+ if (q.url === '/') { res.writeHead(200, { 'content-type': 'text/html' }); return res.end(html); }+ if (q.url === '/bundle.js') { res.writeHead(200, { 'content-type': 'text/javascript' }); return res.end(fs.readFileSync(path.join(here, 'assets/three-bundle.js'))); }+ if (q.url === '/model.glb') { res.writeHead(200); return res.end(fs.readFileSync(modelPath)); }+ res.writeHead(404); res.end();+});+// loopback only, and let the OS pick the port — a fixed port on 0.0.0.0+// exposed the page and the model to the whole network, and collided+// whenever two runs overlapped.+await new Promise(r => srv.listen(0, '127.0.0.1', r));+const port = srv.address().port;+// Let Playwright locate its own browser; PW_CHROMIUM_PATH pins it if needed.+const br = await chromium.launch({ executablePath: process.env.PW_CHROMIUM_PATH || undefined,+ args: ['--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader']+ .concat(process.env.PW_NO_SANDBOX === '1' ? ['--no-sandbox'] : []) });+const pg = await br.newPage({ viewport: { width: 660, height: 660 } });+await pg.goto(`http://127.0.0.1:${port}/`);+await pg.evaluate(() => window.load('/model.glb'));+await pg.waitForTimeout(600);++function unpack(bits) {+ const m = Array.from({ length: 640 }, () => new Uint8Array(640));+ let i = 0;+ for (let y = 0; y < 640; y++) for (let x = 0; x < 640; x += 6) {+ const c = bits.charCodeAt(i++) - 48;+ for (let b = 0; b < 6 && x + b < 640; b++) m[y][x + b] = (c >> (5 - b)) & 1;+ }+ return m;+}+function bbox(m) {+ let y0 = 640, y1 = -1, x0 = 640, x1 = -1;+ for (let y = 0; y < 640; y++) for (let x = 0; x < 640; x++) if (m[y][x]) {+ if (y < y0) y0 = y; if (y > y1) y1 = y; if (x < x0) x0 = x; if (x > x1) x1 = x;+ }+ return { y0, y1, x0, x1 };+}+const shots = {};+for (const view of ['side', 'front', 'top', 'hero']) {+ const { bits, png } = await pg.evaluate(v => window.shoot(v), view);+ fs.writeFileSync(path.join(outDir, `sil_${view}.png`), Buffer.from(png.split(',')[1], 'base64'));+ shots[view] = unpack(bits);+}+await br.close(); srv.close();++// ── 24px thumbnail (nearest ×10) from the side mask ──+{+ const m = shots.side, b = bbox(m);+ const W = b.x1 - b.x0 + 1, H = b.y1 - b.y0 + 1, S = Math.max(W, H);+ const canvasPng = await (async () => {+ // tiny hand-rolled PNG: 240x240 grayscale via zlib store — use playwright page instead? keep simple: write PGM then let humans open PNGs; blind reader gets a PNG rendered from mask+ const px = 240; const img = Buffer.alloc(px * px, 255);+ for (let y = 0; y < px; y++) for (let x = 0; x < px; x++) {+ const sx = b.x0 + Math.floor((Math.floor(x / 10) + 0.5) / 24 * S) - Math.floor((S - W) / 2);+ const sy = b.y0 + Math.floor((Math.floor(y / 10) + 0.5) / 24 * S) - Math.floor((S - H) / 2);+ let on = 0;+ if (sx >= 0 && sy >= 0 && sx < 640 && sy < 640) {+ // 24px cell = majority vote over the source block+ const cell = S / 24; let cnt = 0, tot = 0;+ for (let dy = 0; dy < cell; dy += 2) for (let dx = 0; dx < cell; dx += 2) {+ const yy = sy + Math.floor(dy - cell / 2), xx = sx + Math.floor(dx - cell / 2);+ if (yy >= 0 && xx >= 0 && yy < 640 && xx < 640) { tot++; cnt += m[yy][xx]; }+ }+ on = tot && cnt / tot > 0.35 ? 1 : 0;+ }+ if (on) img[y * px + x] = 0;+ }+ const zlib = await import('zlib');+ const raw = Buffer.alloc(px * (px + 1));+ for (let y = 0; y < px; y++) { raw[y * (px + 1)] = 0; img.copy(raw, y * (px + 1) + 1, y * px, (y + 1) * px); }+ const idat = zlib.deflateSync(raw);+ const crc = (buf) => { let c = ~0; for (const b2 of buf) { c ^= b2; for (let k = 0; k < 8; k++) c = (c >>> 1) ^ (0xEDB88320 & -(c & 1)); } return ~c >>> 0; };+ const chunk = (type, data) => { const len = Buffer.alloc(4); len.writeUInt32BE(data.length); const td = Buffer.concat([Buffer.from(type), data]); const cc = Buffer.alloc(4); cc.writeUInt32BE(crc(td)); return Buffer.concat([len, td, cc]); };+ const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(px, 0); ihdr.writeUInt32BE(px, 4); ihdr[8] = 8; ihdr[9] = 0;+ return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk('IHDR', ihdr), chunk('IDAT', idat), chunk('IEND', Buffer.alloc(0))]);+ })();+ fs.writeFileSync(path.join(outDir, 'thumb24.png'), canvasPng);+}++// ── metrics on the side mask ──+const m = shots.side, b = bbox(m);+const H = b.y1 - b.y0 + 1, W = b.x1 - b.x0 + 1;+const at = (y, x) => m[b.y0 + y] ? (m[b.y0 + y][b.x0 + x] || 0) : 0;+let area = 0; for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) area += at(y, x);+const thirds = [0, 1, 2].map(i => {+ let s = 0;+ for (let y = 0; y < H; y++) for (let x = Math.floor(i * W / 3); x < Math.floor((i + 1) * W / 3); x++) s += at(y, x);+ return +(s / area).toFixed(3);+});+// largest contiguous run per column = torso(+merged limb) depth+const runTop = new Array(W).fill(-1), runBot = new Array(W).fill(-1), runLen = new Array(W).fill(0);+for (let x = 0; x < W; x++) {+ let best = 0, bt = -1, bb = -1, s = -1;+ for (let y = 0; y <= H; y++) {+ const v = y < H ? at(y, x) : 0;+ if (v && s < 0) s = y;+ if (!v && s >= 0) { if (y - s > best) { best = y - s; bt = s; bb = y - 1; } s = -1; }+ }+ runTop[x] = bt; runBot[x] = bb; runLen[x] = best;+}+const band = runLen.slice(Math.floor(0.18 * W), Math.floor(0.82 * W)).filter(v => v > 0);+const dMax = Math.max(...band) / H, dMin = Math.min(...band) / H;+// leg fraction: columns whose run touches the bottom 3% are feet; take the gap+// between front and back foot groups, measure belly→ground there+const footCols = [];+for (let x = 0; x < W; x++) if (runBot[x] >= 0 && runBot[x] > H * 0.94 - 1) footCols.push(x);+let legFrac = null;+if (footCols.length) {+ // largest gap between consecutive foot columns = under-belly span+ let g0 = -1, g1 = -1, best = 0;+ for (let i = 1; i < footCols.length; i++) {+ const gap = footCols[i] - footCols[i - 1];+ if (gap > best) { best = gap; g0 = footCols[i - 1]; g1 = footCols[i]; }+ }+ if (best > 3) {+ const mid = Math.floor((g0 + g1) / 2);+ legFrac = +((H - 1 - runBot[mid]) / H).toFixed(3);+ }+}+// contour turn count (top + bottom boundary polylines)+function turnCount(boundary) {+ const ys = boundary.filter(v => v >= 0);+ if (ys.length < 20) return 0;+ const sm = ys.map((_, i) => {+ let s = 0, n = 0;+ for (let k = -2; k <= 2; k++) if (ys[i + k] !== undefined) { s += ys[i + k]; n++; }+ return s / n;+ });+ let count = 0, last = -10;+ const step = 4;+ for (let i = step; i < sm.length - step; i++) {+ const a = Math.atan2(sm[i] - sm[i - step], step), c = Math.atan2(sm[i + step] - sm[i], step);+ const d = Math.abs(c - a) * 180 / Math.PI;+ if (d > 35 && i - last > 8) { count++; last = i; }+ }+ return count;+}+const topB = new Array(W).fill(-1), botB = new Array(W).fill(-1);+for (let x = 0; x < W; x++) for (let y = 0; y < H; y++) if (at(y, x)) { topB[x] = y; break; }+for (let x = 0; x < W; x++) for (let y = H - 1; y >= 0; y--) if (at(y, x)) { botB[x] = y; break; }+const turns = turnCount(topB) + turnCount(botB);+// zigzag alignment: top-contour extrema stacked over bottom-contour extrema?+function extrema(bd) {+ const out = [];+ for (let x = 6; x < W - 6; x++) {+ if (bd[x] < 0) continue;+ let isMin = true, isMax = true;+ for (let k = -6; k <= 6; k++) { if (bd[x + k] < 0) { isMin = isMax = false; break; }+ if (bd[x + k] < bd[x]) isMin = false; if (bd[x + k] > bd[x]) isMax = false; }+ if ((isMin || isMax) && (!out.length || x - out[out.length - 1] > 10)) out.push(x);+ }+ return out;+}+const te = extrema(topB), be = extrema(botB);+let stacked = 0;+for (const x of te) if (be.some(x2 => Math.abs(x2 - x) < 0.04 * W)) stacked++;+const zigzag = te.length ? +(stacked / te.length).toFixed(2) : 0;++// iou vs previous round+let iou = null;+if (prevDir) {+ const prev = unpack(JSON.parse(fs.readFileSync(path.join(prevDir, 'sil_side.mask.json'))).bits);+ const pb = bbox(prev);+ let inter = 0, uni = 0;+ for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) {+ const a = at(y, x);+ const py = pb.y0 + Math.floor(y * (pb.y1 - pb.y0 + 1) / H);+ const px2 = pb.x0 + Math.floor(x * (pb.x1 - pb.x0 + 1) / W);+ const p = prev[py] ? (prev[py][px2] || 0) : 0;+ if (a & p) inter++; if (a | p) uni++;+ }+ iou = +(inter / (uni || 1)).toFixed(3);+}++let repack = '';+for (let y = 0; y < 640; y++) for (let x = 0; x < 640; x += 6) {+ let c = 0; for (let bq = 0; bq < 6; bq++) c = (c << 1) | (x + bq < 640 ? m[y][x + bq] : 0);+ repack += String.fromCharCode(48 + c);+}+fs.writeFileSync(path.join(outDir, 'sil_side.mask.json'), JSON.stringify({ bits: repack }));+// per-view basics: identity must hold from every orthographic view, not one+const viewStats = {};+for (const view of ['front', 'top', 'hero']) {+ const mv = shots[view], bv = bbox(mv);+ if (bv.y1 < 0) { viewStats[view] = null; continue; }+ const Hv = bv.y1 - bv.y0 + 1, Wv = bv.x1 - bv.x0 + 1;+ let av = 0;+ for (let y = bv.y0; y <= bv.y1; y++) for (let x = bv.x0; x <= bv.x1; x++) av += mv[y][x];+ viewStats[view] = { W_over_H: +(Wv / Hv).toFixed(2), fill: +(av / (Wv * Hv)).toFixed(3) };+}+const metrics = {+ W_over_H: +(W / H).toFixed(2), fill: +(area / (W * H)).toFixed(3),+ mass_thirds: thirds, torso_depth_max: +dMax.toFixed(2), torso_depth_min: +dMin.toFixed(2),+ mass_contrast: +(dMax / (dMin || 1)).toFixed(2), leg_fraction: legFrac,+ turn_count: turns, zigzag_alignment: zigzag, iou_vs_prev: iou,+ front: viewStats.front, top: viewStats.top, hero: viewStats.hero,+};+fs.writeFileSync(path.join(outDir, 'metrics.json'), JSON.stringify(metrics, null, 1));+console.log(JSON.stringify(metrics));diff --git a/harness/specs/_TEMPLATE.json b/harness/specs/_TEMPLATE.jsonnew file mode 100644index 0000000..e18e621--- /dev/null+++ b/harness/specs/_TEMPLATE.json@@ -0,0 +1,56 @@+{+ "name": "<creature name (one-line identity)>",+ "_how_to_write": "Translate this creature's design claims into measurable claims. Each may carry a label (plain-language description; failure messages quote it). Parts are identified by MATERIAL NAME — the material name IS the part name, naming must match the spec JSON palette (material name = part name).",+ "_claim_types": {+ "part_exists": "{part} a material/part with this name must exist",+ "part_visible": "{part, view?, min_share} minimum share of body pixels the part holds in a given view (view: front/side/tq/reartq/top, default side)",+ "part_signature": "{part, view?, min_share, or_min_span} signature part: frame share OR span ratio must clear its bar",+ "style_dark": "{view?, max_median_lum} dark styling: cap on body median luminance (0-255)",+ "style_light": "{view?, min_median_lum} light styling: the floor",+ "saturation_area": "{view?, min?, max?} share of the view carrying a highly saturated colour (HSV S ≥ 0.50 on the UNLIT baked colour, default view tq, default band 0.10-0.34): under the floor the creature reads as a grey mass, over the ceiling saturation stops working as a spotlight. Says HOW MUCH, never WHERE",+ "rig_skinned": "{} must be skinned",+ "anim_named": "{names:[...]} these named animations must be present",+ "tri_budget": "{min, max} triangle budget band",+ "share_hierarchy": "{primary:[..],secondary:[..],tertiary:[..],tolerance?} primary/secondary/tertiary frame shares ≈6:3:1",+ "focal_contrast": "{a, b, min_ratio?} the two focal parts' shares must differ by ≥N× (default 2); equal-weight competition is forbidden"+ },+ "claims": [+ {+ "type": "part_exists",+ "part": "<signature part material name>",+ "label": "signature part must exist"+ },+ {+ "type": "part_signature",+ "part": "<signature part material name>",+ "view": "side",+ "min_share": 0.12,+ "or_min_span": 0.12,+ "label": "the signature must be exaggerated: share or span must clear its bar"+ },+ {+ "type": "rig_skinned"+ },+ {+ "type": "anim_named",+ "names": [+ "<anim1>",+ "<anim2>"+ ]+ },+ {+ "type": "saturation_area",+ "view": "tq",+ "min": 0.1,+ "max": 0.34,+ "stage": "HIGH",+ "label": "high-saturation area must sit in the 10%-34% band: amount of colour, not where it goes"+ },+ {+ "type": "tri_budget",+ "min": 1200,+ "max": 9000+ }+ ],+ "_stage": "Each claim may declare a stage: LOW/MID/HIGH. judge --stage LOW checks only that stage (plus unstaged claims); with no --stage, everything is checked."+}\ No newline at end of filediff --git a/setup.sh b/setup.shnew file mode 100644index 0000000..2fb2f60--- /dev/null+++ b/setup.sh@@ -0,0 +1,11 @@+#!/bin/bash+# anyCreature one-command start: install deps → red/green ruler calibration+set -e+cd "$(dirname "$0")"+npm install [email protected] playwright --no-fund --no-audit+# scipy is NOT optional: harness/maskmetrics.py imports scipy.ndimage. Leaving it+# out let setup print "calibrate OK" and then blow up mid-LOW on the first measure.+pip install numpy pillow scipy --break-system-packages -q 2>/dev/null || pip install numpy pillow scipy -q+python3 -c "import numpy, PIL, scipy.ndimage" || { echo "python deps missing"; exit 1; }+python3 harness/calibrate.py+echo "calibrate OK"