diff --git a/.gitignore b/.gitignore index 0a6775b2a..9fbcce91d 100644 --- a/.gitignore +++ b/.gitignore @@ -8,6 +8,7 @@ __pycache__/ dist/ build/ .pytest_cache/ +.hypothesis/ .mypy_cache/ .ruff_cache/ *.so diff --git a/CHANGELOG.md b/CHANGELOG.md index 145dce7d6..fbe047b0e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ Full release notes with details on each version: [GitHub Releases](https://github.com/safishamsi/graphify/releases) +## Unreleased + +- Feature: `--viz 3d` renders `graph.html` as a navigable, fully offline WebGL + view with search, community filters, hop-focused inspection, bounded labels, + and community aggregation above the visualization node limit. The exact + 3d-force-graph browser bundle is packaged and embedded with its license and + integrity digest; the default 2D renderer remains unchanged. + ## 0.9.31 (2026-07-30) - Feature: the MCP server is dual-compatible with SDK 1.x AND 2.x (#2308, thanks @NiSHoW), lifting the `mcp<2` cap 0.9.30 introduced to `mcp>=1,<3`. The 2.0 SDK removed the low-level decorator API (`Server.list_tools`/`call_tool`/...); `_build_server` now binds the same handlers via the 1.x decorators or the 2.x `on_*` constructor callbacks, picked at runtime, and adapts `Tool.inputSchema`, `Resource.uri` (plain `str` in 2.x), and the dropped `AnyUrl` re-export. Verified with full stdio handshakes under both mcp 1.29 and 2.0. @@ -33,7 +41,6 @@ Full release notes with details on each version: [GitHub Releases](https://githu - Fix: committed `.env.example` / `.env.sample` / `.env.template` templates are indexed instead of dropped by the sensitive-file filter, while real `.env` files (and templates under a secrets directory) stay excluded (#2184, thanks @SyedFahad7). - Fix: Obsidian export no longer hides notes whose label starts with a dot (`.env` -> `dot-env`); an all-dot label falls back to `unnamed` (#2205, thanks @SyedFahad7). - Fix: Scala `self`-type annotations (`self: A with B =>`) now emit `requires` edges to the required traits (#2052, thanks @Yyunozor). - ## 0.9.28 (2026-07-27) - Fix: incremental extraction no longer drops cross-file edges whose target file wasn't in the batch (#2211, #2213). Python relative imports and markdown reference links emitted absolute-path-derived target ids without the `target_file` stamp the incremental canonicalization needs, so a re-extracted file's imports/references dangled or vanished; both now stamp the resolved target and canonicalize to the root-relative node. diff --git a/README.md b/README.md index e171cd0a1..d34c46bc7 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,7 @@ That's it. You get **three files**: ``` graphify-out/ -├── graph.html open in any browser — click nodes, filter, search +├── graph.html open in any browser — click nodes, filter, search (`--viz 3d` for the WebGL 3D view) ├── GRAPH_REPORT.md the highlights: key concepts, surprising connections, suggested questions └── graph.json the full graph — query it anytime without re-reading your files ``` @@ -371,6 +371,7 @@ You can also set `GRAPHIFY_GOOGLE_WORKSPACE=1`. Graphify exports shortcuts into /graphify . --cluster-only --resolution 1.5 # more granular communities /graphify . --cluster-only --exclude-hubs 99 # suppress utility super-hubs from god-node rankings /graphify . --no-viz # skip the HTML, just the report + JSON +/graphify . --viz 3d # render graph.html as a navigable WebGL 3D view /graphify . --wiki # build a markdown wiki from the graph graphify export callflow-html # Mermaid architecture/call-flow HTML (auto-regenerates on every git commit if hook is installed) @@ -392,6 +393,28 @@ graphify prs --conflicts # PRs sharing graph communities — merge-ord See the [full command reference](#full-command-reference) below. +### Offline 3D HTML export + +Use the opt-in WebGL renderer when a dense graph is easier to inspect in three +dimensions: + +```bash +graphify export html --viz 3d +# or build and render in one step +/graphify . --viz 3d +``` + +The generated `graphify-out/graph.html` embeds the graph data and the pinned +3D rendering engine. It can be copied to another machine and opened without a +server or network connection. Community names come from +`.graphify_labels.json`; node colors identify communities and node size +reflects degree (or member count in an aggregated view). + +The 2D renderer remains the default. Use `--viz 2d` explicitly when WebGL or +hardware acceleration is unavailable. Graphs above the visualization node +limit retain the existing safe behavior: Graphify exports a community-level +aggregate instead of attempting an unbounded browser layout. + --- ## Ignoring files @@ -594,8 +617,9 @@ graphify extract . --mode deep --token-budget 4000 # smaller inpu ``` With a cloud gateway like OpenRouter, prefer `--backend openai` (set `OPENAI_BASE_URL`) over the Ollama shim — it's a cleaner OpenAI-compatible path. If the model has its own max-output ceiling, lowering `--token-budget` is the reliable lever. -**Graph HTML is too large to open in a browser (>5000 nodes)** -Skip HTML generation and use the JSON directly: +**Graph HTML has more than 5000 nodes** +Graphify automatically exports a community-level aggregate at the default +visualization limit. To skip HTML and query the full graph directly: ```bash graphify cluster-only ./my-project --no-viz graphify query "..." diff --git a/graphify/cli.py b/graphify/cli.py index 56c32140a..023cca37c 100644 --- a/graphify/cli.py +++ b/graphify/cli.py @@ -14,6 +14,11 @@ from graphify.paths import GRAPHIFY_OUT as _GRAPHIFY_OUT from pathlib import Path +# Accepted `--viz` values. Kept as a literal so `graphify --help` and the arg +# validation below don't drag the exporter (and networkx) into every startup; +# the tuple is asserted against exporters.html.VIZ_MODES in the test suite. +_VIZ_MODES = ("2d", "3d") + _SEARCH_NUDGE = json.dumps({ "hookSpecificOutput": { @@ -1591,6 +1596,7 @@ def dispatch_command(cmd: str) -> None: label_model = _model_arg.split("=", 1)[1] if _model_arg else None _min_cs_arg = next((a for a in sys.argv if a.startswith("--min-community-size=")), None) min_community_size = int(_min_cs_arg.split("=")[1]) if _min_cs_arg else 3 + viz_mode: str | None = None args = sys.argv[2:] watch_path: Path | None = None graph_override: Path | None = None @@ -1627,6 +1633,16 @@ def dispatch_command(cmd: str) -> None: label_batch_size = int(args[i_arg + 1]); i_arg += 2 elif a.startswith("--batch-size="): label_batch_size = int(a.split("=", 1)[1]); i_arg += 1 + # Must precede the `--`-prefixed catch-all: without an explicit arm + # the flag is skipped and its value falls through to the positional + # path slot, so `--viz 3d` would try to cluster a directory "3d". + elif a == "--viz" and i_arg + 1 < len(args): + viz_mode = args[i_arg + 1]; i_arg += 2 + elif a == "--viz": + print("error: --viz requires a value (2d or 3d)", file=sys.stderr) + sys.exit(1) + elif a.startswith("--viz="): + viz_mode = a.split("=", 1)[1]; i_arg += 1 elif a in ("--no-viz", "--missing-only") or a.startswith("--min-community-size="): i_arg += 1 elif a.startswith("--"): @@ -1637,6 +1653,10 @@ def dispatch_command(cmd: str) -> None: i_arg += 1 if watch_path is None: watch_path = Path(".") + if viz_mode is not None and viz_mode.strip().lower() not in _VIZ_MODES: + print(f"error: --viz must be one of {', '.join(_VIZ_MODES)} (got {viz_mode!r})", + file=sys.stderr) + sys.exit(1) graph_json = graph_override if graph_override is not None else watch_path / _GRAPHIFY_OUT / "graph.json" if not graph_json.exists(): print( @@ -1889,7 +1909,7 @@ def dispatch_command(cmd: str) -> None: # path so an oversized graph still renders a usable graph.html. _node_limit = 5000 if _over_cap else None to_html(G, communities, str(html_target), community_labels=labels or None, - node_limit=_node_limit) + node_limit=_node_limit, mode=viz_mode) stages.mark("export"); stages.total() print(f"Done - {len(communities)} communities. GRAPH_REPORT.md, graph.json and graph.html updated.") except ValueError as viz_err: @@ -2218,7 +2238,7 @@ def _to_simple(g: "_nx.Graph") -> "_nx.Graph": subcmd = sys.argv[2] if len(sys.argv) > 2 else "" if subcmd not in ("html", "callflow-html", "obsidian", "wiki", "svg", "graphml", "neo4j", "falkordb"): print("Usage: graphify export ", file=sys.stderr) - print(" html [--graph PATH] [--labels PATH] [--node-limit N] [--no-viz]", file=sys.stderr) + print(" html [--graph PATH] [--labels PATH] [--node-limit N] [--no-viz] [--viz 2d|3d]", file=sys.stderr) print(" callflow-html [GRAPH|DIR] [--graph PATH] [--labels PATH] [--report PATH] [--sections PATH] [--output HTML]", file=sys.stderr) print(" [--lang auto|zh-CN|en] [--max-sections N] [--diagram-scale N]", file=sys.stderr) print(" obsidian [--graph PATH] [--labels PATH] [--dir PATH]", file=sys.stderr) @@ -2249,6 +2269,7 @@ def _to_simple(g: "_nx.Graph") -> "_nx.Graph": analysis_path = Path(_GRAPHIFY_OUT) / ".graphify_analysis.json" node_limit = 5000 no_viz = False + export_viz_mode: str | None = None obsidian_dir = Path(_GRAPHIFY_OUT) / "obsidian" # Shared push-connection settings for the graph-database sinks (neo4j, # falkordb), parsed from the generic --push/--user/--password flags below. @@ -2309,6 +2330,13 @@ def _to_simple(g: "_nx.Graph") -> "_nx.Graph": node_limit = int(args[i + 1]); i += 2 elif a == "--no-viz": no_viz = True; i += 1 + elif a == "--viz" and i + 1 < len(args): + export_viz_mode = args[i + 1]; i += 2 + elif a == "--viz": + print("error: --viz requires a value (2d or 3d)", file=sys.stderr) + sys.exit(1) + elif a.startswith("--viz="): + export_viz_mode = a.split("=", 1)[1]; i += 1 elif a == "--dir" and i + 1 < len(args): obsidian_dir = Path(args[i + 1]); i += 2 elif a == "--push" and i + 1 < len(args): @@ -2438,6 +2466,10 @@ def _to_simple(g: "_nx.Graph") -> "_nx.Graph": if subcmd == "html": from graphify.export import to_html as _to_html + if export_viz_mode is not None and export_viz_mode.strip().lower() not in _VIZ_MODES: + print(f"error: --viz must be one of {', '.join(_VIZ_MODES)} (got {export_viz_mode!r})", + file=sys.stderr) + sys.exit(1) if no_viz: html_target = out_dir / "graph.html" if html_target.exists(): @@ -2448,7 +2480,8 @@ def _to_simple(g: "_nx.Graph") -> "_nx.Graph": # path so the oversized graph still renders a usable artifact. _effective_node_limit = 5000 if _over_cap else node_limit _to_html(G, communities, str(out_dir / "graph.html"), - community_labels=labels or None, node_limit=_effective_node_limit) + community_labels=labels or None, node_limit=_effective_node_limit, + mode=export_viz_mode) if G.number_of_nodes() <= _effective_node_limit: print(f"graph.html written - open in any browser, no server needed") if _over_cap: diff --git a/graphify/exporters/html.py b/graphify/exporters/html.py index 59c0e52e3..43fae6643 100644 --- a/graphify/exporters/html.py +++ b/graphify/exporters/html.py @@ -12,6 +12,22 @@ MAX_NODES_FOR_VIZ = 5_000 +#: Renderers `to_html` can dispatch to. "2d" is the long-standing vis.js canvas +#: view; "3d" is the WebGL view in graphify.exporters.html3d. +VIZ_MODES = ("2d", "3d") + +def _resolve_viz_mode(mode: str | None) -> str: + """Pick the renderer: explicit argument > GRAPHIFY_VIZ_MODE > "2d". + + Defaults to 2d so existing callers keep their byte-identical output; an + unknown value falls back to 2d rather than raising, matching how + _viz_node_limit() treats a malformed env var. + """ + import os + raw = mode if mode is not None else os.environ.get("GRAPHIFY_VIZ_MODE", "") + candidate = (raw or "").strip().lower() + return candidate if candidate in VIZ_MODES else "2d" + def _viz_node_limit() -> int: """Return the effective viz node limit, honoring GRAPHIFY_VIZ_NODE_LIMIT env var. @@ -330,19 +346,25 @@ def to_html( member_counts: dict[int, int] | None = None, node_limit: int | None = None, learning_overlay: dict | None = None, + mode: str | None = None, ) -> None: - """Generate an interactive vis.js HTML visualization of the graph. + """Generate an interactive HTML visualization of the graph. Features: node size by degree, click-to-inspect panel, search box, community filter, physics clustering by community, confidence-styled edges. Raises ValueError if graph exceeds MAX_NODES_FOR_VIZ. + `mode` selects the renderer — "2d" (vis.js canvas, the default) or "3d" + (WebGL via 3d-force-graph). Both are fed the identical node/edge/legend + model built below, so the two views always describe the same graph. + If member_counts is provided (aggregated community view), node sizes are based on community member counts rather than graph degree. If node_limit is set and the graph exceeds it, automatically builds an aggregated community-level meta-graph instead of raising ValueError. """ + mode = _resolve_viz_mode(mode) limit = node_limit if node_limit is not None else _viz_node_limit() if G.number_of_nodes() > limit: if node_limit is not None: @@ -392,7 +414,7 @@ def to_html( }) meta.graph["hyperedges"] = remapped to_html(meta, meta_communities, output_path, - community_labels=community_labels, member_counts=mc) + community_labels=community_labels, member_counts=mc, mode=mode) print(f"graph.html written (aggregated: {meta.number_of_nodes()} community nodes, {meta.number_of_edges()} cross-community edges)") print("Tip: run with --obsidian for full node-level detail.") return @@ -511,18 +533,46 @@ def to_html( n = member_counts.get(cid, len(communities.get(cid, []))) if member_counts else len(communities.get(cid, [])) legend_data.append({"cid": cid, "color": color, "label": lbl, "count": n}) - # Escape sequences so embedded JSON cannot break out of the script tag - def _js_safe(obj) -> str: - return json.dumps(obj).replace(" +def js_safe(obj) -> str: + """Serialize `obj` for embedding in a ` from + closing the tag early and turning graph data into markup. + """ + return json.dumps(obj).replace(" str: + """Render the view model as the vis.js 2D canvas viewer.""" + nodes_json = js_safe(model["nodes"]) + edges_json = js_safe(model["edges"]) + legend_json = js_safe(model["legend"]) + hyperedges_json = js_safe(model["hyperedges"]) + title = model["title"] + stats = model["stats"] + + return f""" @@ -556,5 +606,3 @@ def _js_safe(obj) -> str: {_hyperedge_script(hyperedges_json)} """ - - Path(output_path).write_text(html, encoding="utf-8") # nosec diff --git a/graphify/exporters/html3d.py b/graphify/exporters/html3d.py new file mode 100644 index 000000000..55a44c8f9 --- /dev/null +++ b/graphify/exporters/html3d.py @@ -0,0 +1,785 @@ +"""html3d — WebGL renderer for the graph viewer (`--viz 3d`). + +Consumes the same view model as the vis.js renderer in graphify.exporters.html +(nodes, edges, legend, hyperedges) and draws it with 3d-force-graph, a UMD +bundle of three.js + d3-force-3d. WebGL keeps drawing and camera interaction +responsive while the extra dimension gives dense communities more room to +separate. The existing node limit and community aggregation remain the safety +boundary for expensive force layouts. + +Two deliberate differences from the 2D view, both downstream of one constraint: +the bundle keeps its three.js instance private, so we cannot build custom +geometry without shipping a second copy of three. + + * Learning-overlay status is painted onto the node itself (green/amber/grey) + instead of ringing it. A sphere has no border to tint, and the community + colour stays legible in the legend, the search list and the info panel. + * Hyperedges become a synthetic hub node wired to every member (the standard + star expansion) rather than a shaded hull. Same information, and the hub is + clickable, which the hull never was. + +Labels are DOM elements projected onto the canvas each frame rather than +sprites, which keeps text crisp, keeps it escapable, and costs no extra +dependency. Only the highest-degree visible nodes plus the current selection +get one — a label per node is unreadable in 3D long before it is slow. +""" +from __future__ import annotations + +from functools import lru_cache +from importlib.resources import files + +from graphify.exporters.html import _html_styles, js_safe + +# The exact reviewed UMD release is packaged with Graphify and embedded into +# each 3D export. This keeps the generated page usable without a network and +# avoids executing mutable CDN content. Bumping the version requires replacing +# the asset, its license/notices, and this digest together. +FORCE_GRAPH_VERSION = "1.80.0" +FORCE_GRAPH_ASSET = ( + f"vendor/3d-force-graph-{FORCE_GRAPH_VERSION}.min.js" +) +FORCE_GRAPH_ASSET_SHA384 = ( + "63b6c2d8f04abbcba3c6dbe8e7e67ad4e786752551cc5b185812b88b97672ff5" + "3a6850d3a1d93ad6a3949137c89dac52" +) + + +@lru_cache(maxsize=1) +def _force_graph_source() -> str: + """Read the packaged 3d-force-graph UMD bundle.""" + return files("graphify").joinpath(FORCE_GRAPH_ASSET).read_text(encoding="utf-8") + + +def _styles_3d() -> str: + """Styles layered on top of the shared sidebar CSS from the 2D renderer.""" + return """""" + + +# The viewer script. Kept as a plain (non-f) string so the JS can use `${...}` +# template literals and object literals without brace-doubling; the four data +# placeholders are substituted by render() below. +_SCRIPT_3D = r"""""" + + +def render(model: dict) -> str: + """Render the shared view model as the 3d-force-graph WebGL viewer.""" + # A literal closing script tag in either graph data or a future dependency + # release must not be able to terminate this inline block. + force_graph_source = _force_graph_source().replace("Hyperedges' + if model["hyperedges"] else "" + ) + return f""" + + + +graphify 3D - {model["title"]} + +{_html_styles()} +{_styles_3d()} + + +
+ +{script} + +""" diff --git a/graphify/skill-agents.md b/graphify/skill-agents.md index afb4ecc12..35e6079fb 100644 --- a/graphify/skill-agents.md +++ b/graphify/skill-agents.md @@ -21,6 +21,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti /graphify --whisper-model medium # use a larger Whisper model for better transcription accuracy /graphify --cluster-only # rerun clustering on existing graph /graphify --no-viz # skip visualization, just report + JSON +/graphify --viz 3d # render graph.html as an interactive 3D WebGL view /graphify --html # (HTML is generated by default - this flag is a no-op) /graphify --svg # also export graph.svg (embeds in Notion, GitHub) /graphify --graphml # export graph.graphml (Gephi, yEd) @@ -532,6 +533,7 @@ Generate the HTML graph (always, unless `--no-viz`): ```bash graphify export html # auto-aggregates to community view if graph > 5000 nodes # or: graphify export html --no-viz +# or: graphify export html --viz 3d # only when the user asked for --viz 3d ``` ### Steps 6b-8 - Wiki, Neo4j, FalkorDB, SVG, GraphML, MCP, benchmark (only on their flags) diff --git a/graphify/skill-amp.md b/graphify/skill-amp.md index afb4ecc12..35e6079fb 100644 --- a/graphify/skill-amp.md +++ b/graphify/skill-amp.md @@ -21,6 +21,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti /graphify --whisper-model medium # use a larger Whisper model for better transcription accuracy /graphify --cluster-only # rerun clustering on existing graph /graphify --no-viz # skip visualization, just report + JSON +/graphify --viz 3d # render graph.html as an interactive 3D WebGL view /graphify --html # (HTML is generated by default - this flag is a no-op) /graphify --svg # also export graph.svg (embeds in Notion, GitHub) /graphify --graphml # export graph.graphml (Gephi, yEd) @@ -532,6 +533,7 @@ Generate the HTML graph (always, unless `--no-viz`): ```bash graphify export html # auto-aggregates to community view if graph > 5000 nodes # or: graphify export html --no-viz +# or: graphify export html --viz 3d # only when the user asked for --viz 3d ``` ### Steps 6b-8 - Wiki, Neo4j, FalkorDB, SVG, GraphML, MCP, benchmark (only on their flags) diff --git a/graphify/skill-claw.md b/graphify/skill-claw.md index d98865cc8..149f68207 100644 --- a/graphify/skill-claw.md +++ b/graphify/skill-claw.md @@ -21,6 +21,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti /graphify --whisper-model medium # use a larger Whisper model for better transcription accuracy /graphify --cluster-only # rerun clustering on existing graph /graphify --no-viz # skip visualization, just report + JSON +/graphify --viz 3d # render graph.html as an interactive 3D WebGL view /graphify --html # (HTML is generated by default - this flag is a no-op) /graphify --svg # also export graph.svg (embeds in Notion, GitHub) /graphify --graphml # export graph.graphml (Gephi, yEd) @@ -535,6 +536,7 @@ Generate the HTML graph (always, unless `--no-viz`): ```bash graphify export html # auto-aggregates to community view if graph > 5000 nodes # or: graphify export html --no-viz +# or: graphify export html --viz 3d # only when the user asked for --viz 3d ``` ### Steps 6b-8 - Wiki, Neo4j, FalkorDB, SVG, GraphML, MCP, benchmark (only on their flags) diff --git a/graphify/skill-codex.md b/graphify/skill-codex.md index 0c821a278..49c3bcc01 100644 --- a/graphify/skill-codex.md +++ b/graphify/skill-codex.md @@ -21,6 +21,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti /graphify --whisper-model medium # use a larger Whisper model for better transcription accuracy /graphify --cluster-only # rerun clustering on existing graph /graphify --no-viz # skip visualization, just report + JSON +/graphify --viz 3d # render graph.html as an interactive 3D WebGL view /graphify --html # (HTML is generated by default - this flag is a no-op) /graphify --svg # also export graph.svg (embeds in Notion, GitHub) /graphify --graphml # export graph.graphml (Gephi, yEd) @@ -532,6 +533,7 @@ Generate the HTML graph (always, unless `--no-viz`): ```bash graphify export html # auto-aggregates to community view if graph > 5000 nodes # or: graphify export html --no-viz +# or: graphify export html --viz 3d # only when the user asked for --viz 3d ``` ### Steps 6b-8 - Wiki, Neo4j, FalkorDB, SVG, GraphML, MCP, benchmark (only on their flags) diff --git a/graphify/skill-copilot.md b/graphify/skill-copilot.md index d98865cc8..149f68207 100644 --- a/graphify/skill-copilot.md +++ b/graphify/skill-copilot.md @@ -21,6 +21,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti /graphify --whisper-model medium # use a larger Whisper model for better transcription accuracy /graphify --cluster-only # rerun clustering on existing graph /graphify --no-viz # skip visualization, just report + JSON +/graphify --viz 3d # render graph.html as an interactive 3D WebGL view /graphify --html # (HTML is generated by default - this flag is a no-op) /graphify --svg # also export graph.svg (embeds in Notion, GitHub) /graphify --graphml # export graph.graphml (Gephi, yEd) @@ -535,6 +536,7 @@ Generate the HTML graph (always, unless `--no-viz`): ```bash graphify export html # auto-aggregates to community view if graph > 5000 nodes # or: graphify export html --no-viz +# or: graphify export html --viz 3d # only when the user asked for --viz 3d ``` ### Steps 6b-8 - Wiki, Neo4j, FalkorDB, SVG, GraphML, MCP, benchmark (only on their flags) diff --git a/graphify/skill-droid.md b/graphify/skill-droid.md index c3815d556..1f464bb8a 100644 --- a/graphify/skill-droid.md +++ b/graphify/skill-droid.md @@ -21,6 +21,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti /graphify --whisper-model medium # use a larger Whisper model for better transcription accuracy /graphify --cluster-only # rerun clustering on existing graph /graphify --no-viz # skip visualization, just report + JSON +/graphify --viz 3d # render graph.html as an interactive 3D WebGL view /graphify --html # (HTML is generated by default - this flag is a no-op) /graphify --svg # also export graph.svg (embeds in Notion, GitHub) /graphify --graphml # export graph.graphml (Gephi, yEd) @@ -532,6 +533,7 @@ Generate the HTML graph (always, unless `--no-viz`): ```bash graphify export html # auto-aggregates to community view if graph > 5000 nodes # or: graphify export html --no-viz +# or: graphify export html --viz 3d # only when the user asked for --viz 3d ``` ### Steps 6b-8 - Wiki, Neo4j, FalkorDB, SVG, GraphML, MCP, benchmark (only on their flags) diff --git a/graphify/skill-kilo.md b/graphify/skill-kilo.md index dbb4658ca..ebc336896 100644 --- a/graphify/skill-kilo.md +++ b/graphify/skill-kilo.md @@ -21,6 +21,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti /graphify --whisper-model medium # use a larger Whisper model for better transcription accuracy /graphify --cluster-only # rerun clustering on existing graph /graphify --no-viz # skip visualization, just report + JSON +/graphify --viz 3d # render graph.html as an interactive 3D WebGL view /graphify --html # (HTML is generated by default - this flag is a no-op) /graphify --svg # also export graph.svg (embeds in Notion, GitHub) /graphify --graphml # export graph.graphml (Gephi, yEd) @@ -535,6 +536,7 @@ Generate the HTML graph (always, unless `--no-viz`): ```bash graphify export html # auto-aggregates to community view if graph > 5000 nodes # or: graphify export html --no-viz +# or: graphify export html --viz 3d # only when the user asked for --viz 3d ``` ### Steps 6b-8 - Wiki, Neo4j, FalkorDB, SVG, GraphML, MCP, benchmark (only on their flags) diff --git a/graphify/skill-kiro.md b/graphify/skill-kiro.md index d98865cc8..149f68207 100644 --- a/graphify/skill-kiro.md +++ b/graphify/skill-kiro.md @@ -21,6 +21,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti /graphify --whisper-model medium # use a larger Whisper model for better transcription accuracy /graphify --cluster-only # rerun clustering on existing graph /graphify --no-viz # skip visualization, just report + JSON +/graphify --viz 3d # render graph.html as an interactive 3D WebGL view /graphify --html # (HTML is generated by default - this flag is a no-op) /graphify --svg # also export graph.svg (embeds in Notion, GitHub) /graphify --graphml # export graph.graphml (Gephi, yEd) @@ -535,6 +536,7 @@ Generate the HTML graph (always, unless `--no-viz`): ```bash graphify export html # auto-aggregates to community view if graph > 5000 nodes # or: graphify export html --no-viz +# or: graphify export html --viz 3d # only when the user asked for --viz 3d ``` ### Steps 6b-8 - Wiki, Neo4j, FalkorDB, SVG, GraphML, MCP, benchmark (only on their flags) diff --git a/graphify/skill-opencode.md b/graphify/skill-opencode.md index cf5dae440..fc4055b00 100644 --- a/graphify/skill-opencode.md +++ b/graphify/skill-opencode.md @@ -21,6 +21,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti /graphify --whisper-model medium # use a larger Whisper model for better transcription accuracy /graphify --cluster-only # rerun clustering on existing graph /graphify --no-viz # skip visualization, just report + JSON +/graphify --viz 3d # render graph.html as an interactive 3D WebGL view /graphify --html # (HTML is generated by default - this flag is a no-op) /graphify --svg # also export graph.svg (embeds in Notion, GitHub) /graphify --graphml # export graph.graphml (Gephi, yEd) @@ -527,6 +528,7 @@ Generate the HTML graph (always, unless `--no-viz`): ```bash graphify export html # auto-aggregates to community view if graph > 5000 nodes # or: graphify export html --no-viz +# or: graphify export html --viz 3d # only when the user asked for --viz 3d ``` ### Steps 6b-8 - Wiki, Neo4j, FalkorDB, SVG, GraphML, MCP, benchmark (only on their flags) diff --git a/graphify/skill-pi.md b/graphify/skill-pi.md index d98865cc8..149f68207 100644 --- a/graphify/skill-pi.md +++ b/graphify/skill-pi.md @@ -21,6 +21,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti /graphify --whisper-model medium # use a larger Whisper model for better transcription accuracy /graphify --cluster-only # rerun clustering on existing graph /graphify --no-viz # skip visualization, just report + JSON +/graphify --viz 3d # render graph.html as an interactive 3D WebGL view /graphify --html # (HTML is generated by default - this flag is a no-op) /graphify --svg # also export graph.svg (embeds in Notion, GitHub) /graphify --graphml # export graph.graphml (Gephi, yEd) @@ -535,6 +536,7 @@ Generate the HTML graph (always, unless `--no-viz`): ```bash graphify export html # auto-aggregates to community view if graph > 5000 nodes # or: graphify export html --no-viz +# or: graphify export html --viz 3d # only when the user asked for --viz 3d ``` ### Steps 6b-8 - Wiki, Neo4j, FalkorDB, SVG, GraphML, MCP, benchmark (only on their flags) diff --git a/graphify/skill-trae.md b/graphify/skill-trae.md index b0cbeb122..c3746b44b 100644 --- a/graphify/skill-trae.md +++ b/graphify/skill-trae.md @@ -21,6 +21,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti /graphify --whisper-model medium # use a larger Whisper model for better transcription accuracy /graphify --cluster-only # rerun clustering on existing graph /graphify --no-viz # skip visualization, just report + JSON +/graphify --viz 3d # render graph.html as an interactive 3D WebGL view /graphify --html # (HTML is generated by default - this flag is a no-op) /graphify --svg # also export graph.svg (embeds in Notion, GitHub) /graphify --graphml # export graph.graphml (Gephi, yEd) @@ -533,6 +534,7 @@ Generate the HTML graph (always, unless `--no-viz`): ```bash graphify export html # auto-aggregates to community view if graph > 5000 nodes # or: graphify export html --no-viz +# or: graphify export html --viz 3d # only when the user asked for --viz 3d ``` ### Steps 6b-8 - Wiki, Neo4j, FalkorDB, SVG, GraphML, MCP, benchmark (only on their flags) diff --git a/graphify/skill-vscode.md b/graphify/skill-vscode.md index 3e6bc6b7b..cebe01559 100644 --- a/graphify/skill-vscode.md +++ b/graphify/skill-vscode.md @@ -21,6 +21,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti /graphify --whisper-model medium # use a larger Whisper model for better transcription accuracy /graphify --cluster-only # rerun clustering on existing graph /graphify --no-viz # skip visualization, just report + JSON +/graphify --viz 3d # render graph.html as an interactive 3D WebGL view /graphify --html # (HTML is generated by default - this flag is a no-op) /graphify --svg # also export graph.svg (embeds in Notion, GitHub) /graphify --graphml # export graph.graphml (Gephi, yEd) @@ -531,6 +532,7 @@ Generate the HTML graph (always, unless `--no-viz`): ```bash graphify export html # auto-aggregates to community view if graph > 5000 nodes # or: graphify export html --no-viz +# or: graphify export html --viz 3d # only when the user asked for --viz 3d ``` ### Steps 6b-8 - Wiki, Neo4j, FalkorDB, SVG, GraphML, MCP, benchmark (only on their flags) diff --git a/graphify/skill-windows.md b/graphify/skill-windows.md index 574384576..452bb1275 100644 --- a/graphify/skill-windows.md +++ b/graphify/skill-windows.md @@ -21,6 +21,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti /graphify --whisper-model medium # use a larger Whisper model for better transcription accuracy /graphify --cluster-only # rerun clustering on existing graph /graphify --no-viz # skip visualization, just report + JSON +/graphify --viz 3d # render graph.html as an interactive 3D WebGL view /graphify --html # (HTML is generated by default - this flag is a no-op) /graphify --svg # also export graph.svg (embeds in Notion, GitHub) /graphify --graphml # export graph.graphml (Gephi, yEd) @@ -557,6 +558,7 @@ Generate the HTML graph (always, unless `--no-viz`): ```bash graphify export html # auto-aggregates to community view if graph > 5000 nodes # or: graphify export html --no-viz +# or: graphify export html --viz 3d # only when the user asked for --viz 3d ``` ### Steps 6b-8 - Wiki, Neo4j, FalkorDB, SVG, GraphML, MCP, benchmark (only on their flags) diff --git a/graphify/skill.md b/graphify/skill.md index d98865cc8..149f68207 100644 --- a/graphify/skill.md +++ b/graphify/skill.md @@ -21,6 +21,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti /graphify --whisper-model medium # use a larger Whisper model for better transcription accuracy /graphify --cluster-only # rerun clustering on existing graph /graphify --no-viz # skip visualization, just report + JSON +/graphify --viz 3d # render graph.html as an interactive 3D WebGL view /graphify --html # (HTML is generated by default - this flag is a no-op) /graphify --svg # also export graph.svg (embeds in Notion, GitHub) /graphify --graphml # export graph.graphml (Gephi, yEd) @@ -535,6 +536,7 @@ Generate the HTML graph (always, unless `--no-viz`): ```bash graphify export html # auto-aggregates to community view if graph > 5000 nodes # or: graphify export html --no-viz +# or: graphify export html --viz 3d # only when the user asked for --viz 3d ``` ### Steps 6b-8 - Wiki, Neo4j, FalkorDB, SVG, GraphML, MCP, benchmark (only on their flags) diff --git a/graphify/vendor/3d-force-graph-1.80.0.min.js b/graphify/vendor/3d-force-graph-1.80.0.min.js new file mode 100644 index 000000000..30da1058d --- /dev/null +++ b/graphify/vendor/3d-force-graph-1.80.0.min.js @@ -0,0 +1,5 @@ +// Version 1.80.0 3d-force-graph - https://github.com/vasturiano/3d-force-graph +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).ForceGraph3D=t()}(this,function(){"use strict";function e(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n>8&255]+Qt[e>>16&255]+Qt[e>>24&255]+"-"+Qt[255&t]+Qt[t>>8&255]+"-"+Qt[t>>16&15|64]+Qt[t>>24&255]+"-"+Qt[63&n|128]+Qt[n>>8&255]+"-"+Qt[n>>16&255]+Qt[n>>24&255]+Qt[255&i]+Qt[i>>8&255]+Qt[i>>16&255]+Qt[i>>24&255]).toLowerCase()}function rn(e,t,n){return Math.max(t,Math.min(n,e))}function sn(e,t){return(e%t+t)%t}function an(e,t,n){return(1-n)*e+n*t}function on(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return e/4294967295;case Uint16Array:return e/65535;case Uint8Array:return e/255;case Int32Array:return Math.max(e/2147483647,-1);case Int16Array:return Math.max(e/32767,-1);case Int8Array:return Math.max(e/127,-1);default:throw new Error("Invalid component type.")}}function ln(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return Math.round(4294967295*e);case Uint16Array:return Math.round(65535*e);case Uint8Array:return Math.round(255*e);case Int32Array:return Math.round(2147483647*e);case Int16Array:return Math.round(32767*e);case Int8Array:return Math.round(127*e);default:throw new Error("Invalid component type.")}}const un={DEG2RAD:en,RAD2DEG:tn,generateUUID:nn,clamp:rn,euclideanModulo:sn,mapLinear:function(e,t,n,i,r){return i+(e-t)*(r-i)/(n-t)},inverseLerp:function(e,t,n){return e!==t?(n-e)/(t-e):0},lerp:an,damp:function(e,t,n,i){return an(e,t,1-Math.exp(-n*i))},pingpong:function(e,t=1){return t-Math.abs(sn(e,2*t)-t)},smoothstep:function(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t))*e*(3-2*e)},smootherstep:function(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t))*e*e*(e*(6*e-15)+10)},randInt:function(e,t){return e+Math.floor(Math.random()*(t-e+1))},randFloat:function(e,t){return e+Math.random()*(t-e)},randFloatSpread:function(e){return e*(.5-Math.random())},seededRandom:function(e){void 0!==e&&(Jt=e);let t=Jt+=1831565813;return t=Math.imul(t^t>>>15,1|t),t^=t+Math.imul(t^t>>>7,61|t),((t^t>>>14)>>>0)/4294967296},degToRad:function(e){return e*en},radToDeg:function(e){return e*tn},isPowerOfTwo:function(e){return!(e&e-1)&&0!==e},ceilPowerOfTwo:function(e){return Math.pow(2,Math.ceil(Math.log(e)/Math.LN2))},floorPowerOfTwo:function(e){return Math.pow(2,Math.floor(Math.log(e)/Math.LN2))},setQuaternionFromProperEuler:function(e,t,n,i,r){const s=Math.cos,a=Math.sin,o=s(n/2),l=a(n/2),u=s((t+i)/2),c=a((t+i)/2),h=s((t-i)/2),d=a((t-i)/2),p=s((i-t)/2),f=a((i-t)/2);switch(r){case"XYX":e.set(o*c,l*h,l*d,o*u);break;case"YZY":e.set(l*d,o*c,l*h,o*u);break;case"ZXZ":e.set(l*h,l*d,o*c,o*u);break;case"XZX":e.set(o*c,l*f,l*p,o*u);break;case"YXY":e.set(l*p,o*c,l*f,o*u);break;case"ZYZ":e.set(l*f,l*p,o*c,o*u);break;default:Xt("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}},normalize:ln,denormalize:on};class cn{constructor(e=0,t=0){cn.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){const 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=rn(this.x,e.x,t.x),this.y=rn(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=rn(this.x,e,t),this.y=rn(this.y,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(rn(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){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(0===t)return Math.PI/2;const n=this.dot(e)/t;return Math.acos(rn(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const 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){const n=Math.cos(t),i=Math.sin(t),r=this.x-e.x,s=this.y-e.y;return this.x=r*n-s*i+e.x,this.y=r*i+s*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class hn{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,r,s,a){let o=n[i+0],l=n[i+1],u=n[i+2],c=n[i+3],h=r[s+0],d=r[s+1],p=r[s+2],f=r[s+3];if(c!==f||o!==h||l!==d||u!==p){let e=o*h+l*d+u*p+c*f;e<0&&(h=-h,d=-d,p=-p,f=-f,e=-e);let t=1-a;if(e<.9995){const n=Math.acos(e),i=Math.sin(n);t=Math.sin(t*n)/i,o=o*t+h*(a=Math.sin(a*n)/i),l=l*t+d*a,u=u*t+p*a,c=c*t+f*a}else{o=o*t+h*a,l=l*t+d*a,u=u*t+p*a,c=c*t+f*a;const e=1/Math.sqrt(o*o+l*l+u*u+c*c);o*=e,l*=e,u*=e,c*=e}}e[t]=o,e[t+1]=l,e[t+2]=u,e[t+3]=c}static multiplyQuaternionsFlat(e,t,n,i,r,s){const a=n[i],o=n[i+1],l=n[i+2],u=n[i+3],c=r[s],h=r[s+1],d=r[s+2],p=r[s+3];return e[t]=a*p+u*c+o*d-l*h,e[t+1]=o*p+u*h+l*c-a*d,e[t+2]=l*p+u*d+a*h-o*c,e[t+3]=u*p-a*c-o*h-l*d,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){const n=e._x,i=e._y,r=e._z,s=e._order,a=Math.cos,o=Math.sin,l=a(n/2),u=a(i/2),c=a(r/2),h=o(n/2),d=o(i/2),p=o(r/2);switch(s){case"XYZ":this._x=h*u*c+l*d*p,this._y=l*d*c-h*u*p,this._z=l*u*p+h*d*c,this._w=l*u*c-h*d*p;break;case"YXZ":this._x=h*u*c+l*d*p,this._y=l*d*c-h*u*p,this._z=l*u*p-h*d*c,this._w=l*u*c+h*d*p;break;case"ZXY":this._x=h*u*c-l*d*p,this._y=l*d*c+h*u*p,this._z=l*u*p+h*d*c,this._w=l*u*c-h*d*p;break;case"ZYX":this._x=h*u*c-l*d*p,this._y=l*d*c+h*u*p,this._z=l*u*p-h*d*c,this._w=l*u*c+h*d*p;break;case"YZX":this._x=h*u*c+l*d*p,this._y=l*d*c+h*u*p,this._z=l*u*p-h*d*c,this._w=l*u*c-h*d*p;break;case"XZY":this._x=h*u*c-l*d*p,this._y=l*d*c-h*u*p,this._z=l*u*p+h*d*c,this._w=l*u*c+h*d*p;break;default:Xt("Quaternion: .setFromEuler() encountered an unknown order: "+s)}return!0===t&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const 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){const t=e.elements,n=t[0],i=t[4],r=t[8],s=t[1],a=t[5],o=t[9],l=t[2],u=t[6],c=t[10],h=n+a+c;if(h>0){const e=.5/Math.sqrt(h+1);this._w=.25/e,this._x=(u-o)*e,this._y=(r-l)*e,this._z=(s-i)*e}else if(n>a&&n>c){const e=2*Math.sqrt(1+n-a-c);this._w=(u-o)/e,this._x=.25*e,this._y=(i+s)/e,this._z=(r+l)/e}else if(a>c){const e=2*Math.sqrt(1+a-n-c);this._w=(r-l)/e,this._x=(i+s)/e,this._y=.25*e,this._z=(o+u)/e}else{const e=2*Math.sqrt(1+c-n-a);this._w=(s-i)/e,this._x=(r+l)/e,this._y=(o+u)/e,this._z=.25*e}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return n<1e-8?(n=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(rn(this.dot(e),-1,1)))}rotateTowards(e,t){const n=this.angleTo(e);if(0===n)return this;const 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 0===e?(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){const n=e._x,i=e._y,r=e._z,s=e._w,a=t._x,o=t._y,l=t._z,u=t._w;return this._x=n*u+s*a+i*l-r*o,this._y=i*u+s*o+r*a-n*l,this._z=r*u+s*l+n*o-i*a,this._w=s*u-n*a-i*o-r*l,this._onChangeCallback(),this}slerp(e,t){let n=e._x,i=e._y,r=e._z,s=e._w,a=this.dot(e);a<0&&(n=-n,i=-i,r=-r,s=-s,a=-a);let o=1-t;if(a<.9995){const e=Math.acos(a),l=Math.sin(e);o=Math.sin(o*e)/l,t=Math.sin(t*e)/l,this._x=this._x*o+n*t,this._y=this._y*o+i*t,this._z=this._z*o+r*t,this._w=this._w*o+s*t,this._onChangeCallback()}else this._x=this._x*o+n*t,this._y=this._y*o+i*t,this._z=this._z*o+r*t,this._w=this._w*o+s*t,this.normalize();return this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),n=Math.random(),i=Math.sqrt(1-n),r=Math.sqrt(n);return this.set(i*Math.sin(e),i*Math.cos(e),r*Math.sin(t),r*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}}class dn{constructor(e=0,t=0,n=0){dn.prototype.isVector3=!0,this.x=e,this.y=t,this.z=n}set(e,t,n){return void 0===n&&(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(fn.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(fn.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,n=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6]*i,this.y=r[1]*t+r[4]*n+r[7]*i,this.z=r[2]*t+r[5]*n+r[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,n=this.y,i=this.z,r=e.elements,s=1/(r[3]*t+r[7]*n+r[11]*i+r[15]);return this.x=(r[0]*t+r[4]*n+r[8]*i+r[12])*s,this.y=(r[1]*t+r[5]*n+r[9]*i+r[13])*s,this.z=(r[2]*t+r[6]*n+r[10]*i+r[14])*s,this}applyQuaternion(e){const t=this.x,n=this.y,i=this.z,r=e.x,s=e.y,a=e.z,o=e.w,l=2*(s*i-a*n),u=2*(a*t-r*i),c=2*(r*n-s*t);return this.x=t+o*l+s*c-a*u,this.y=n+o*u+a*l-r*c,this.z=i+o*c+r*u-s*l,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,n=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[4]*n+r[8]*i,this.y=r[1]*t+r[5]*n+r[9]*i,this.z=r[2]*t+r[6]*n+r[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=rn(this.x,e.x,t.x),this.y=rn(this.y,e.y,t.y),this.z=rn(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=rn(this.x,e,t),this.y=rn(this.y,e,t),this.z=rn(this.z,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(rn(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){const n=e.x,i=e.y,r=e.z,s=t.x,a=t.y,o=t.z;return this.x=i*o-r*a,this.y=r*s-n*o,this.z=n*a-i*s,this}projectOnVector(e){const t=e.lengthSq();if(0===t)return this.set(0,0,0);const n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return pn.copy(this).projectOnVector(e),this.sub(pn)}reflect(e){return this.sub(pn.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(0===t)return Math.PI/2;const n=this.dot(e)/t;return Math.acos(rn(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const 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){const 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){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const 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,4*t)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,3*t)}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(){const e=Math.random()*Math.PI*2,t=2*Math.random()-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}}const pn=new dn,fn=new hn;class mn{constructor(e,t,n,i,r,s,a,o,l){mn.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],void 0!==e&&this.set(e,t,n,i,r,s,a,o,l)}set(e,t,n,i,r,s,a,o,l){const u=this.elements;return u[0]=e,u[1]=i,u[2]=a,u[3]=t,u[4]=r,u[5]=o,u[6]=n,u[7]=s,u[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const 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){const 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){const n=e.elements,i=t.elements,r=this.elements,s=n[0],a=n[3],o=n[6],l=n[1],u=n[4],c=n[7],h=n[2],d=n[5],p=n[8],f=i[0],m=i[3],g=i[6],_=i[1],v=i[4],y=i[7],b=i[2],x=i[5],T=i[8];return r[0]=s*f+a*_+o*b,r[3]=s*m+a*v+o*x,r[6]=s*g+a*y+o*T,r[1]=l*f+u*_+c*b,r[4]=l*m+u*v+c*x,r[7]=l*g+u*y+c*T,r[2]=h*f+d*_+p*b,r[5]=h*m+d*v+p*x,r[8]=h*g+d*y+p*T,this}multiplyScalar(e){const 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(){const e=this.elements,t=e[0],n=e[1],i=e[2],r=e[3],s=e[4],a=e[5],o=e[6],l=e[7],u=e[8];return t*s*u-t*a*l-n*r*u+n*a*o+i*r*l-i*s*o}invert(){const e=this.elements,t=e[0],n=e[1],i=e[2],r=e[3],s=e[4],a=e[5],o=e[6],l=e[7],u=e[8],c=u*s-a*l,h=a*o-u*r,d=l*r-s*o,p=t*c+n*h+i*d;if(0===p)return this.set(0,0,0,0,0,0,0,0,0);const f=1/p;return e[0]=c*f,e[1]=(i*l-u*n)*f,e[2]=(a*n-i*s)*f,e[3]=h*f,e[4]=(u*t-i*o)*f,e[5]=(i*r-a*t)*f,e[6]=d*f,e[7]=(n*o-l*t)*f,e[8]=(s*t-n*r)*f,this}transpose(){let e;const 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){const 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,r,s,a){const o=Math.cos(r),l=Math.sin(r);return this.set(n*o,n*l,-n*(o*s+l*a)+s+e,-i*l,i*o,-i*(-l*s+o*a)+a+t,0,0,1),this}scale(e,t){return this.premultiply(gn.makeScale(e,t)),this}rotate(e){return this.premultiply(gn.makeRotation(-e)),this}translate(e,t){return this.premultiply(gn.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){const 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){const t=this.elements,n=e.elements;for(let e=0;e<9;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const 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)}}const gn=new mn,_n=(new mn).set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),vn=(new mn).set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function yn(){const e={enabled:!0,workingColorSpace:xt,spaces:{},convert:function(e,t,n){return!1!==this.enabled&&t!==n&&t&&n?(this.spaces[t].transfer===St&&(e.r=xn(e.r),e.g=xn(e.g),e.b=xn(e.b)),this.spaces[t].primaries!==this.spaces[n].primaries&&(e.applyMatrix3(this.spaces[t].toXYZ),e.applyMatrix3(this.spaces[n].fromXYZ)),this.spaces[n].transfer===St&&(e.r=Tn(e.r),e.g=Tn(e.g),e.b=Tn(e.b)),e):e},workingToColorSpace:function(e,t){return this.convert(e,this.workingColorSpace,t)},colorSpaceToWorking:function(e,t){return this.convert(e,t,this.workingColorSpace)},getPrimaries:function(e){return this.spaces[e].primaries},getTransfer:function(e){return e===yt?Tt:this.spaces[e].transfer},getToneMappingMode:function(e){return this.spaces[e].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(e,t=this.workingColorSpace){return e.fromArray(this.spaces[t].luminanceCoefficients)},define:function(e){Object.assign(this.spaces,e)},_getMatrix:function(e,t,n){return e.copy(this.spaces[t].toXYZ).multiply(this.spaces[n].fromXYZ)},_getDrawingBufferColorSpace:function(e){return this.spaces[e].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(e=this.workingColorSpace){return this.spaces[e].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(t,n){return Yt("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),e.workingToColorSpace(t,n)},toWorkingColorSpace:function(t,n){return Yt("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),e.colorSpaceToWorking(t,n)}},t=[.64,.33,.3,.6,.15,.06],n=[.2126,.7152,.0722],i=[.3127,.329];return e.define({[xt]:{primaries:t,whitePoint:i,transfer:Tt,toXYZ:_n,fromXYZ:vn,luminanceCoefficients:n,workingColorSpaceConfig:{unpackColorSpace:bt},outputColorSpaceConfig:{drawingBufferColorSpace:bt}},[bt]:{primaries:t,whitePoint:i,transfer:St,toXYZ:_n,fromXYZ:vn,luminanceCoefficients:n,outputColorSpaceConfig:{drawingBufferColorSpace:bt}}}),e}const bn=yn();function xn(e){return e<.04045?.0773993808*e:Math.pow(.9478672986*e+.0521327014,2.4)}function Tn(e){return e<.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}let Sn;class Mn{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src))return e.src;if("undefined"==typeof HTMLCanvasElement)return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{void 0===Sn&&(Sn=Gt("canvas")),Sn.width=e.width,Sn.height=e.height;const t=Sn.getContext("2d");e instanceof ImageData?t.putImageData(e,0,0):t.drawImage(e,0,0,e.width,e.height),n=Sn}return n.toDataURL(t)}static sRGBToLinear(e){if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap){const t=Gt("canvas");t.width=e.width,t.height=e.height;const n=t.getContext("2d");n.drawImage(e,0,0,e.width,e.height);const i=n.getImageData(0,0,e.width,e.height),r=i.data;for(let e=0;e1),this.pmremVersion=0}get width(){return this.source.getSize(Cn).x}get height(){return this.source.getSize(Cn).y}get depth(){return this.source.getSize(Cn).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(const t in e){const n=e[t];if(void 0===n){Xt(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}const i=this[t];void 0!==i?i&&n&&i.isVector2&&n.isVector2||i&&n&&i.isVector3&&n.isVector3||i&&n&&i.isMatrix3&&n.isMatrix3?i.copy(n):this[t]=n:Xt(`Texture.setValues(): property '${t}' does not exist.`)}}toJSON(e){const t=void 0===e||"string"==typeof e;if(!t&&void 0!==e.textures[this.uuid])return e.textures[this.uuid];const 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(300!==this.mapping)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case se:e.x=e.x-Math.floor(e.x);break;case ae:e.x=e.x<0?0:1;break;case oe:1===Math.abs(Math.floor(e.x)%2)?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x)}if(e.y<0||e.y>1)switch(this.wrapT){case se:e.y=e.y-Math.floor(e.y);break;case ae:e.y=e.y<0?0:1;break;case oe:1===Math.abs(Math.floor(e.y)%2)?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y)}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){!0===e&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){!0===e&&this.pmremVersion++}}Nn.DEFAULT_IMAGE=null,Nn.DEFAULT_MAPPING=300,Nn.DEFAULT_ANISOTROPY=1;class Pn{constructor(e=0,t=0,n=0,i=1){Pn.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=void 0!==e.w?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){const t=this.x,n=this.y,i=this.z,r=this.w,s=e.elements;return this.x=s[0]*t+s[4]*n+s[8]*i+s[12]*r,this.y=s[1]*t+s[5]*n+s[9]*i+s[13]*r,this.z=s[2]*t+s[6]*n+s[10]*i+s[14]*r,this.w=s[3]*t+s[7]*n+s[11]*i+s[15]*r,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);const 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,r;const s=.01,a=.1,o=e.elements,l=o[0],u=o[4],c=o[8],h=o[1],d=o[5],p=o[9],f=o[2],m=o[6],g=o[10];if(Math.abs(u-h)o&&e>_?e_?o1);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>>0}enable(e){this.mask|=1<1){for(let e=0;e1){for(let e=0;e0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),null!==this.pivot&&(i.pivot=this.pivot.toArray()),!1===this.matrixAutoUpdate&&(i.matrixAutoUpdate=!1),void 0!==this.morphTargetDictionary&&(i.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),void 0!==this.morphTargetInfluences&&(i.morphTargetInfluences=this.morphTargetInfluences.slice()),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),null!==this.instanceColor&&(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(e=>({...e,boundingBox:e.boundingBox?e.boundingBox.toJSON():void 0,boundingSphere:e.boundingSphere?e.boundingSphere.toJSON():void 0})),i.instanceInfo=this._instanceInfo.map(e=>({...e})),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),null!==this._colorsTexture&&(i.colorsTexture=this._colorsTexture.toJSON(e)),null!==this.boundingSphere&&(i.boundingSphere=this.boundingSphere.toJSON()),null!==this.boundingBox&&(i.boundingBox=this.boundingBox.toJSON())),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&&!0!==this.environment.isRenderTargetTexture&&(i.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=r(e.geometries,this.geometry);const t=this.geometry.parameters;if(void 0!==t&&void 0!==t.shapes){const n=t.shapes;if(Array.isArray(n))for(let t=0,i=n.length;t0){i.children=[];for(let t=0;t0){i.animations=[];for(let t=0;t0&&(n.geometries=t),i.length>0&&(n.materials=i),r.length>0&&(n.textures=r),a.length>0&&(n.images=a),o.length>0&&(n.shapes=o),l.length>0&&(n.skeletons=l),u.length>0&&(n.animations=u),c.length>0&&(n.nodes=c)}return n.object=i,n;function s(e){const t=[];for(const n in e){const i=e[n];delete i.metadata,t.push(i)}return t}}clone(e){return(new this.constructor).copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),null!==e.pivot&&(this.pivot=e.pivot.clone()),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.static=e.static,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),!0===t)for(let t=0;to+u?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!l.inputState.pinching&&a<=o-u&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else null!==o&&e.gripSpace&&(r=t.getPose(e.gripSpace,n),null!==r&&(o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,r.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(r.linearVelocity)):o.hasLinearVelocity=!1,r.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(r.angularVelocity)):o.hasAngularVelocity=!1));null!==a&&(i=t.getPose(e.targetRaySpace,n),null===i&&null!==r&&(i=r),null!==i&&(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(hi)))}return null!==a&&(a.visible=null!==i),null!==o&&(o.visible=null!==r),null!==l&&(l.visible=null!==s),this}_getHandJoint(e,t){if(void 0===e.joints[t.jointName]){const n=new ci;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}}const pi={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},fi={h:0,s:0,l:0},mi={h:0,s:0,l:0};function gi(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+6*(t-e)*n:n<.5?t:n<2/3?e+6*(t-e)*(2/3-n):e}class _i{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(void 0===t&&void 0===n){const t=e;t&&t.isColor?this.copy(t):"number"==typeof t?this.setHex(t):"string"==typeof t&&this.setStyle(t)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=bt){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(255&e)/255,bn.colorSpaceToWorking(this,t),this}setRGB(e,t,n,i=bn.workingColorSpace){return this.r=e,this.g=t,this.b=n,bn.colorSpaceToWorking(this,i),this}setHSL(e,t,n,i=bn.workingColorSpace){if(e=sn(e,1),t=rn(t,0,1),n=rn(n,0,1),0===t)this.r=this.g=this.b=n;else{const i=n<=.5?n*(1+t):n+t-n*t,r=2*n-i;this.r=gi(r,i,e+1/3),this.g=gi(r,i,e),this.b=gi(r,i,e-1/3)}return bn.colorSpaceToWorking(this,i),this}setStyle(e,t=bt){function n(t){void 0!==t&&parseFloat(t)<1&&Xt("Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let r;const s=i[1],a=i[2];switch(s){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setRGB(Math.min(255,parseInt(r[1],10))/255,Math.min(255,parseInt(r[2],10))/255,Math.min(255,parseInt(r[3],10))/255,t);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setRGB(Math.min(100,parseInt(r[1],10))/100,Math.min(100,parseInt(r[2],10))/100,Math.min(100,parseInt(r[3],10))/100,t);break;case"hsl":case"hsla":if(r=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,t);break;default:Xt("Color: Unknown color model "+e)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(e)){const n=i[1],r=n.length;if(3===r)return this.setRGB(parseInt(n.charAt(0),16)/15,parseInt(n.charAt(1),16)/15,parseInt(n.charAt(2),16)/15,t);if(6===r)return this.setHex(parseInt(n,16),t);Xt("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=bt){const n=pi[e.toLowerCase()];return void 0!==n?this.setHex(n,t):Xt("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=xn(e.r),this.g=xn(e.g),this.b=xn(e.b),this}copyLinearToSRGB(e){return this.r=Tn(e.r),this.g=Tn(e.g),this.b=Tn(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=bt){return bn.workingToColorSpace(vi.copy(this),e),65536*Math.round(rn(255*vi.r,0,255))+256*Math.round(rn(255*vi.g,0,255))+Math.round(rn(255*vi.b,0,255))}getHexString(e=bt){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=bn.workingColorSpace){bn.workingToColorSpace(vi.copy(this),t);const n=vi.r,i=vi.g,r=vi.b,s=Math.max(n,i,r),a=Math.min(n,i,r);let o,l;const u=(a+s)/2;if(a===s)o=0,l=0;else{const e=s-a;switch(l=u<=.5?e/(s+a):e/(2-s-a),s){case n:o=(i-r)/e+(i0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),1!==this.backgroundIntensity&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),1!==this.environmentIntensity&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}}const bi=new dn,xi=new dn,Ti=new dn,Si=new dn,Mi=new dn,Ei=new dn,wi=new dn,Ai=new dn,Ri=new dn,Ci=new dn,Ni=new Pn,Pi=new Pn,Li=new Pn;class Di{constructor(e=new dn,t=new dn,n=new dn){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,i){i.subVectors(n,t),bi.subVectors(e,t),i.cross(bi);const r=i.lengthSq();return r>0?i.multiplyScalar(1/Math.sqrt(r)):i.set(0,0,0)}static getBarycoord(e,t,n,i,r){bi.subVectors(i,t),xi.subVectors(n,t),Ti.subVectors(e,t);const s=bi.dot(bi),a=bi.dot(xi),o=bi.dot(Ti),l=xi.dot(xi),u=xi.dot(Ti),c=s*l-a*a;if(0===c)return r.set(0,0,0),null;const h=1/c,d=(l*o-a*u)*h,p=(s*u-a*o)*h;return r.set(1-d-p,p,d)}static containsPoint(e,t,n,i){return null!==this.getBarycoord(e,t,n,i,Si)&&(Si.x>=0&&Si.y>=0&&Si.x+Si.y<=1)}static getInterpolation(e,t,n,i,r,s,a,o){return null===this.getBarycoord(e,t,n,i,Si)?(o.x=0,o.y=0,"z"in o&&(o.z=0),"w"in o&&(o.w=0),null):(o.setScalar(0),o.addScaledVector(r,Si.x),o.addScaledVector(s,Si.y),o.addScaledVector(a,Si.z),o)}static getInterpolatedAttribute(e,t,n,i,r,s){return Ni.setScalar(0),Pi.setScalar(0),Li.setScalar(0),Ni.fromBufferAttribute(e,t),Pi.fromBufferAttribute(e,n),Li.fromBufferAttribute(e,i),s.setScalar(0),s.addScaledVector(Ni,r.x),s.addScaledVector(Pi,r.y),s.addScaledVector(Li,r.z),s}static isFrontFacing(e,t,n,i){return bi.subVectors(n,t),xi.subVectors(e,t),bi.cross(xi).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 bi.subVectors(this.c,this.b),xi.subVectors(this.a,this.b),.5*bi.cross(xi).length()}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Di.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Di.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,n,i,r){return Di.getInterpolation(e,this.a,this.b,this.c,t,n,i,r)}containsPoint(e){return Di.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Di.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const n=this.a,i=this.b,r=this.c;let s,a;Mi.subVectors(i,n),Ei.subVectors(r,n),Ai.subVectors(e,n);const o=Mi.dot(Ai),l=Ei.dot(Ai);if(o<=0&&l<=0)return t.copy(n);Ri.subVectors(e,i);const u=Mi.dot(Ri),c=Ei.dot(Ri);if(u>=0&&c<=u)return t.copy(i);const h=o*c-u*l;if(h<=0&&o>=0&&u<=0)return s=o/(o-u),t.copy(n).addScaledVector(Mi,s);Ci.subVectors(e,r);const d=Mi.dot(Ci),p=Ei.dot(Ci);if(p>=0&&d<=p)return t.copy(r);const f=d*l-o*p;if(f<=0&&l>=0&&p<=0)return a=l/(l-p),t.copy(n).addScaledVector(Ei,a);const m=u*p-d*c;if(m<=0&&c-u>=0&&d-p>=0)return wi.subVectors(r,i),a=(c-u)/(c-u+(d-p)),t.copy(i).addScaledVector(wi,a);const g=1/(m+f+h);return s=f*g,a=h*g,t.copy(n).addScaledVector(Mi,s).addScaledVector(Ei,a)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}class Ii{constructor(e=new dn(1/0,1/0,1/0),t=new dn(-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=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,Fi),Fi.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(ji),Wi.subVectors(this.max,ji),Bi.subVectors(e.a,ji),ki.subVectors(e.b,ji),zi.subVectors(e.c,ji),Vi.subVectors(ki,Bi),Gi.subVectors(zi,ki),Hi.subVectors(Bi,zi);let t=[0,-Vi.z,Vi.y,0,-Gi.z,Gi.y,0,-Hi.z,Hi.y,Vi.z,0,-Vi.x,Gi.z,0,-Gi.x,Hi.z,0,-Hi.x,-Vi.y,Vi.x,0,-Gi.y,Gi.x,0,-Hi.y,Hi.x,0];return!!qi(t,Bi,ki,zi,Wi)&&(t=[1,0,0,0,1,0,0,0,1],!!qi(t,Bi,ki,zi,Wi)&&($i.crossVectors(Vi,Gi),t=[$i.x,$i.y,$i.z],qi(t,Bi,ki,zi,Wi)))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Fi).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=.5*this.getSize(Fi).length()),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()||(Ui[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Ui[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Ui[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Ui[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Ui[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Ui[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Ui[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Ui[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Ui)),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}}const Ui=[new dn,new dn,new dn,new dn,new dn,new dn,new dn,new dn],Fi=new dn,Oi=new Ii,Bi=new dn,ki=new dn,zi=new dn,Vi=new dn,Gi=new dn,Hi=new dn,ji=new dn,Wi=new dn,$i=new dn,Xi=new dn;function qi(e,t,n,i,r){for(let s=0,a=e.length-3;s<=a;s+=3){Xi.fromArray(e,s);const a=r.x*Math.abs(Xi.x)+r.y*Math.abs(Xi.y)+r.z*Math.abs(Xi.z),o=t.dot(Xi),l=n.dot(Xi),u=i.dot(Xi);if(Math.max(-Math.max(o,l,u),Math.min(o,l,u))>a)return!1}return!0}const Yi=Ki();function Ki(){const e=new ArrayBuffer(4),t=new Float32Array(e),n=new Uint32Array(e),i=new Uint32Array(512),r=new Uint32Array(512);for(let e=0;e<256;++e){const t=e-127;t<-27?(i[e]=0,i[256|e]=32768,r[e]=24,r[256|e]=24):t<-14?(i[e]=1024>>-t-14,i[256|e]=1024>>-t-14|32768,r[e]=-t-1,r[256|e]=-t-1):t<=15?(i[e]=t+15<<10,i[256|e]=t+15<<10|32768,r[e]=13,r[256|e]=13):t<128?(i[e]=31744,i[256|e]=64512,r[e]=24,r[256|e]=24):(i[e]=31744,i[256|e]=64512,r[e]=13,r[256|e]=13)}const s=new Uint32Array(2048),a=new Uint32Array(64),o=new Uint32Array(64);for(let e=1;e<1024;++e){let t=e<<13,n=0;for(;!(8388608&t);)t<<=1,n-=8388608;t&=-8388609,n+=947912704,s[e]=t|n}for(let e=1024;e<2048;++e)s[e]=939524096+(e-1024<<13);for(let e=1;e<31;++e)a[e]=e<<23;a[31]=1199570944,a[32]=2147483648;for(let e=33;e<63;++e)a[e]=2147483648+(e-32<<23);a[63]=3347054592;for(let e=1;e<64;++e)32!==e&&(o[e]=1024);return{floatView:t,uint32View:n,baseTable:i,shiftTable:r,mantissaTable:s,exponentTable:a,offsetTable:o}}function Zi(e){Math.abs(e)>65504&&Xt("DataUtils.toHalfFloat(): Value out of range."),e=rn(e,-65504,65504),Yi.floatView[0]=e;const t=Yi.uint32View[0],n=t>>23&511;return Yi.baseTable[n]+((8388607&t)>>Yi.shiftTable[n])}function Qi(e){const t=e>>10;return Yi.uint32View[0]=Yi.mantissaTable[Yi.offsetTable[t]+(1023&e)]+Yi.exponentTable[t],Yi.floatView[0]}const Ji=new dn,er=new cn;let tr=0;class nr{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:tr++}),this.name="",this.array=e,this.itemSize=t,this.count=void 0!==e?e.length/t:0,this.normalized=n,this.usage=Dt,this.updateRanges=[],this.gpuType=be,this.version=0}onUploadCallback(){}set needsUpdate(e){!0===e&&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,r=this.itemSize;ithis.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;lr.subVectors(e,this.center);const t=lr.lengthSq();if(t>this.radius*this.radius){const e=Math.sqrt(t),n=.5*(e-this.radius);this.center.addScaledVector(lr,n/e),this.radius+=n}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(!0===this.center.equals(e.center)?this.radius=Math.max(this.radius,e.radius):(ur.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(lr.copy(e.center).add(ur)),this.expandByPoint(lr.copy(e.center).sub(ur))),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}}let hr=0;const dr=new Fn,pr=new ui,fr=new dn,mr=new Ii,gr=new Ii,_r=new dn;class vr extends Zt{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:hr++}),this.uuid=nn(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(function(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}(e)?rr:ir)(e,1):this.index=e,this}setIndirect(e,t=0){return this.indirect=e,this.indirectOffset=t,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 void 0!==this.attributes[e]}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){const t=this.attributes.position;void 0!==t&&(t.applyMatrix4(e),t.needsUpdate=!0);const n=this.attributes.normal;if(void 0!==n){const t=(new mn).getNormalMatrix(e);n.applyNormalMatrix(t),n.needsUpdate=!0}const i=this.attributes.tangent;return void 0!==i&&(i.transformDirection(e),i.needsUpdate=!0),null!==this.boundingBox&&this.computeBoundingBox(),null!==this.boundingSphere&&this.computeBoundingSphere(),this}applyQuaternion(e){return dr.makeRotationFromQuaternion(e),this.applyMatrix4(dr),this}rotateX(e){return dr.makeRotationX(e),this.applyMatrix4(dr),this}rotateY(e){return dr.makeRotationY(e),this.applyMatrix4(dr),this}rotateZ(e){return dr.makeRotationZ(e),this.applyMatrix4(dr),this}translate(e,t,n){return dr.makeTranslation(e,t,n),this.applyMatrix4(dr),this}scale(e,t,n){return dr.makeScale(e,t,n),this.applyMatrix4(dr),this}lookAt(e){return pr.lookAt(e),pr.updateMatrix(),this.applyMatrix4(pr.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(fr).negate(),this.translate(fr.x,fr.y,fr.z),this}setFromPoints(e){const t=this.getAttribute("position");if(void 0===t){const t=[];for(let n=0,i=e.length;nt.count&&Xt("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){null===this.boundingBox&&(this.boundingBox=new Ii);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute)return qt("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),void this.boundingBox.set(new dn(-1/0,-1/0,-1/0),new dn(1/0,1/0,1/0));if(void 0!==e){if(this.boundingBox.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e0&&(e.userData=this.userData),void 0!==this.parameters){const t=this.parameters;for(const n in t)void 0!==t[n]&&(e[n]=t[n]);return e}e.data={attributes:{}};const t=this.index;null!==t&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const n=this.attributes;for(const t in n){const i=n[t];e.data.attributes[t]=i.toJSON(e.data)}const i={};let r=!1;for(const t in this.morphAttributes){const n=this.morphAttributes[t],s=[];for(let t=0,i=n.length;t0&&(i[t]=s,r=!0)}r&&(e.data.morphAttributes=i,e.data.morphTargetsRelative=this.morphTargetsRelative);const s=this.groups;s.length>0&&(e.data.groups=JSON.parse(JSON.stringify(s)));const a=this.boundingSphere;return null!==a&&(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;const t={};this.name=e.name;const n=e.index;null!==n&&this.setIndex(n.clone());const i=e.attributes;for(const e in i){const n=i[e];this.setAttribute(e,n.clone(t))}const r=e.morphAttributes;for(const e in r){const n=[],i=r[e];for(let e=0,r=i.length;e0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(void 0!==e)for(const t in e){const n=e[t];if(void 0===n){Xt(`Material: parameter '${t}' has value of undefined.`);continue}const i=this[t];void 0!==i?i&&i.isColor?i.set(n):i&&i.isVector3&&n&&n.isVector3?i.copy(n):this[t]=n:Xt(`Material: '${t}' is not a property of THREE.${this.type}.`)}}toJSON(e){const t=void 0===e||"string"==typeof e;t&&(e={textures:{},images:{}});const n={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};function i(e){const t=[];for(const n in e){const i=e[n];delete i.metadata,t.push(i)}return t}if(n.uuid=this.uuid,n.type=this.type,""!==this.name&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),void 0!==this.roughness&&(n.roughness=this.roughness),void 0!==this.metalness&&(n.metalness=this.metalness),void 0!==this.sheen&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),void 0!==this.sheenRoughness&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),void 0!==this.emissiveIntensity&&1!==this.emissiveIntensity&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),void 0!==this.specularIntensity&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),void 0!==this.shininess&&(n.shininess=this.shininess),void 0!==this.clearcoat&&(n.clearcoat=this.clearcoat),void 0!==this.clearcoatRoughness&&(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),void 0!==this.dispersion&&(n.dispersion=this.dispersion),void 0!==this.iridescence&&(n.iridescence=this.iridescence),void 0!==this.iridescenceIOR&&(n.iridescenceIOR=this.iridescenceIOR),void 0!==this.iridescenceThicknessRange&&(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),void 0!==this.anisotropy&&(n.anisotropy=this.anisotropy),void 0!==this.anisotropyRotation&&(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,void 0!==this.combine&&(n.combine=this.combine)),void 0!==this.envMapRotation&&(n.envMapRotation=this.envMapRotation.toArray()),void 0!==this.envMapIntensity&&(n.envMapIntensity=this.envMapIntensity),void 0!==this.reflectivity&&(n.reflectivity=this.reflectivity),void 0!==this.refractionRatio&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),void 0!==this.transmission&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),void 0!==this.thickness&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),void 0!==this.attenuationDistance&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),void 0!==this.attenuationColor&&(n.attenuationColor=this.attenuationColor.getHex()),void 0!==this.size&&(n.size=this.size),null!==this.shadowSide&&(n.shadowSide=this.shadowSide),void 0!==this.sizeAttenuation&&(n.sizeAttenuation=this.sizeAttenuation),1!==this.blending&&(n.blending=this.blending),0!==this.side&&(n.side=this.side),!0===this.vertexColors&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),!0===this.transparent&&(n.transparent=!0),this.blendSrc!==E&&(n.blendSrc=this.blendSrc),this.blendDst!==w&&(n.blendDst=this.blendDst),this.blendEquation!==v&&(n.blendEquation=this.blendEquation),null!==this.blendSrcAlpha&&(n.blendSrcAlpha=this.blendSrcAlpha),null!==this.blendDstAlpha&&(n.blendDstAlpha=this.blendDstAlpha),null!==this.blendEquationAlpha&&(n.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(n.blendColor=this.blendColor.getHex()),0!==this.blendAlpha&&(n.blendAlpha=this.blendAlpha),3!==this.depthFunc&&(n.depthFunc=this.depthFunc),!1===this.depthTest&&(n.depthTest=this.depthTest),!1===this.depthWrite&&(n.depthWrite=this.depthWrite),!1===this.colorWrite&&(n.colorWrite=this.colorWrite),255!==this.stencilWriteMask&&(n.stencilWriteMask=this.stencilWriteMask),519!==this.stencilFunc&&(n.stencilFunc=this.stencilFunc),0!==this.stencilRef&&(n.stencilRef=this.stencilRef),255!==this.stencilFuncMask&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==Mt&&(n.stencilFail=this.stencilFail),this.stencilZFail!==Mt&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==Mt&&(n.stencilZPass=this.stencilZPass),!0===this.stencilWrite&&(n.stencilWrite=this.stencilWrite),void 0!==this.rotation&&0!==this.rotation&&(n.rotation=this.rotation),!0===this.polygonOffset&&(n.polygonOffset=!0),0!==this.polygonOffsetFactor&&(n.polygonOffsetFactor=this.polygonOffsetFactor),0!==this.polygonOffsetUnits&&(n.polygonOffsetUnits=this.polygonOffsetUnits),void 0!==this.linewidth&&1!==this.linewidth&&(n.linewidth=this.linewidth),void 0!==this.dashSize&&(n.dashSize=this.dashSize),void 0!==this.gapSize&&(n.gapSize=this.gapSize),void 0!==this.scale&&(n.scale=this.scale),!0===this.dithering&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),!0===this.alphaHash&&(n.alphaHash=!0),!0===this.alphaToCoverage&&(n.alphaToCoverage=!0),!0===this.premultipliedAlpha&&(n.premultipliedAlpha=!0),!0===this.forceSinglePass&&(n.forceSinglePass=!0),!1===this.allowOverride&&(n.allowOverride=!1),!0===this.wireframe&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),"round"!==this.wireframeLinecap&&(n.wireframeLinecap=this.wireframeLinecap),"round"!==this.wireframeLinejoin&&(n.wireframeLinejoin=this.wireframeLinejoin),!0===this.flatShading&&(n.flatShading=!0),!1===this.visible&&(n.visible=!1),!1===this.toneMapped&&(n.toneMapped=!1),!1===this.fog&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData),t){const t=i(e.textures),r=i(e.images);t.length>0&&(n.textures=t),r.length>0&&(n.images=r)}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;const t=e.clippingPlanes;let n=null;if(null!==t){const e=t.length;n=new Array(e);for(let i=0;i!==e;++i)n[i]=t[i].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.allowOverride=e.allowOverride,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){!0===e&&this.version++}}class Mr extends Sr{constructor(e){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new _i(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}}const Er=new dn,wr=new dn,Ar=new dn,Rr=new dn,Cr=new dn,Nr=new dn,Pr=new dn;class Lr{constructor(e=new dn,t=new dn(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,Er)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const 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){const t=Er.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Er.copy(this.origin).addScaledVector(this.direction,t),Er.distanceToSquared(e))}distanceSqToSegment(e,t,n,i){wr.copy(e).add(t).multiplyScalar(.5),Ar.copy(t).sub(e).normalize(),Rr.copy(this.origin).sub(wr);const r=.5*e.distanceTo(t),s=-this.direction.dot(Ar),a=Rr.dot(this.direction),o=-Rr.dot(Ar),l=Rr.lengthSq(),u=Math.abs(1-s*s);let c,h,d,p;if(u>0)if(c=s*o-a,h=s*a-o,p=r*u,c>=0)if(h>=-p)if(h<=p){const e=1/u;c*=e,h*=e,d=c*(c+s*h+2*a)+h*(s*c+h+2*o)+l}else h=r,c=Math.max(0,-(s*h+a)),d=-c*c+h*(h+2*o)+l;else h=-r,c=Math.max(0,-(s*h+a)),d=-c*c+h*(h+2*o)+l;else h<=-p?(c=Math.max(0,-(-s*r+a)),h=c>0?-r:Math.min(Math.max(-r,-o),r),d=-c*c+h*(h+2*o)+l):h<=p?(c=0,h=Math.min(Math.max(-r,-o),r),d=h*(h+2*o)+l):(c=Math.max(0,-(s*r+a)),h=c>0?r:Math.min(Math.max(-r,-o),r),d=-c*c+h*(h+2*o)+l);else h=s>0?-r:r,c=Math.max(0,-(s*h+a)),d=-c*c+h*(h+2*o)+l;return n&&n.copy(this.origin).addScaledVector(this.direction,c),i&&i.copy(wr).addScaledVector(Ar,h),d}intersectSphere(e,t){Er.subVectors(e.center,this.origin);const n=Er.dot(this.direction),i=Er.dot(Er)-n*n,r=e.radius*e.radius;if(i>r)return null;const s=Math.sqrt(r-i),a=n-s,o=n+s;return o<0?null:a<0?this.at(o,t):this.at(a,t)}intersectsSphere(e){return!(e.radius<0)&&this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(0===t)return 0===e.distanceToPoint(this.origin)?0:null;const n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){const n=this.distanceToPlane(e);return null===n?null:this.at(n,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);if(0===t)return!0;return e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,i,r,s,a,o;const l=1/this.direction.x,u=1/this.direction.y,c=1/this.direction.z,h=this.origin;return l>=0?(n=(e.min.x-h.x)*l,i=(e.max.x-h.x)*l):(n=(e.max.x-h.x)*l,i=(e.min.x-h.x)*l),u>=0?(r=(e.min.y-h.y)*u,s=(e.max.y-h.y)*u):(r=(e.max.y-h.y)*u,s=(e.min.y-h.y)*u),n>s||r>i?null:((r>n||isNaN(n))&&(n=r),(s=0?(a=(e.min.z-h.z)*c,o=(e.max.z-h.z)*c):(a=(e.max.z-h.z)*c,o=(e.min.z-h.z)*c),n>o||a>i?null:((a>n||n!=n)&&(n=a),(o=0?n:i,t)))}intersectsBox(e){return null!==this.intersectBox(e,Er)}intersectTriangle(e,t,n,i,r){Cr.subVectors(t,e),Nr.subVectors(n,e),Pr.crossVectors(Cr,Nr);let s,a=this.direction.dot(Pr);if(a>0){if(i)return null;s=1}else{if(!(a<0))return null;s=-1,a=-a}Rr.subVectors(this.origin,e);const o=s*this.direction.dot(Nr.crossVectors(Rr,Nr));if(o<0)return null;const l=s*this.direction.dot(Cr.cross(Rr));if(l<0)return null;if(o+l>a)return null;const u=-s*Rr.dot(Pr);return u<0?null:this.at(u/a,r)}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)}}class Dr extends Sr{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new _i(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 $n,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const Ir=new Fn,Ur=new Lr,Fr=new cr,Or=new dn,Br=new dn,kr=new dn,zr=new dn,Vr=new dn,Gr=new dn,Hr=new dn,jr=new dn;class Wr extends ui{constructor(e=new vr,t=new Dr){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),void 0!==e.morphTargetInfluences&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),void 0!==e.morphTargetDictionary&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){const e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){const n=e[t[0]];if(void 0!==n){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e(e.far-e.near)**2)return}Ir.copy(r).invert(),Ur.copy(e.ray).applyMatrix4(Ir),null!==n.boundingBox&&!1===Ur.intersectsBox(n.boundingBox)||this._computeIntersections(e,t,Ur)}}_computeIntersections(e,t,n){let i;const r=this.geometry,s=this.material,a=r.index,o=r.attributes.position,l=r.attributes.uv,u=r.attributes.uv1,c=r.attributes.normal,h=r.groups,d=r.drawRange;if(null!==a)if(Array.isArray(s))for(let r=0,o=h.length;rn.far?null:{distance:u,point:jr.clone(),object:e}}(e,t,n,i,Br,kr,zr,Hr);if(c){const e=new dn;Di.getBarycoord(Hr,Br,kr,zr,e),r&&(c.uv=Di.getInterpolatedAttribute(r,o,l,u,e,new cn)),s&&(c.uv1=Di.getInterpolatedAttribute(s,o,l,u,e,new cn)),a&&(c.normal=Di.getInterpolatedAttribute(a,o,l,u,e,new dn),c.normal.dot(i.direction)>0&&c.normal.multiplyScalar(-1));const t={a:o,b:l,c:u,normal:new dn,materialIndex:0};Di.getNormal(Br,kr,zr,t.normal),c.face=t,c.barycoord=e}return c}class Xr extends Nn{constructor(e=null,t=1,n=1,i,r,s,a,o,l=1003,u=1003,c,h){super(null,s,a,o,l,u,i,r,c,h),this.isDataTexture=!0,this.image={data:e,width:t,height:n},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class qr extends nr{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(){const e=super.toJSON();return e.meshPerAttribute=this.meshPerAttribute,e.isInstancedBufferAttribute=!0,e}}const Yr=new dn,Kr=new dn,Zr=new mn;class Qr{constructor(e=new dn(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){const i=Yr.subVectors(n,t).cross(Kr.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(i,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const 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){const n=e.delta(Yr),i=this.normal.dot(n);if(0===i)return 0===this.distanceToPoint(e.start)?t.copy(e.start):null;const r=-(e.start.dot(this.normal)+this.constant)/i;return r<0||r>1?null:t.copy(e.start).addScaledVector(n,r)}intersectsLine(e){const 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){const n=t||Zr.getNormalMatrix(e),i=this.coplanarPoint(Yr).applyMatrix4(e),r=this.normal.applyMatrix3(n).normalize();return this.constant=-i.dot(r),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)}}const Jr=new cr,es=new cn(.5,.5),ts=new dn;class ns{constructor(e=new Qr,t=new Qr,n=new Qr,i=new Qr,r=new Qr,s=new Qr){this.planes=[e,t,n,i,r,s]}set(e,t,n,i,r,s){const a=this.planes;return a[0].copy(e),a[1].copy(t),a[2].copy(n),a[3].copy(i),a[4].copy(r),a[5].copy(s),this}copy(e){const t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=2e3,n=!1){const i=this.planes,r=e.elements,s=r[0],a=r[1],o=r[2],l=r[3],u=r[4],c=r[5],h=r[6],d=r[7],p=r[8],f=r[9],m=r[10],g=r[11],_=r[12],v=r[13],y=r[14],b=r[15];if(i[0].setComponents(l-s,d-u,g-p,b-_).normalize(),i[1].setComponents(l+s,d+u,g+p,b+_).normalize(),i[2].setComponents(l+a,d+c,g+f,b+v).normalize(),i[3].setComponents(l-a,d-c,g-f,b-v).normalize(),n)i[4].setComponents(o,h,m,y).normalize(),i[5].setComponents(l-o,d-h,g-m,b-y).normalize();else if(i[4].setComponents(l-o,d-h,g-m,b-y).normalize(),t===Ft)i[5].setComponents(l+o,d+h,g+m,b+y).normalize();else{if(t!==Ot)throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);i[5].setComponents(o,h,m,y).normalize()}return this}intersectsObject(e){if(void 0!==e.boundingSphere)null===e.boundingSphere&&e.computeBoundingSphere(),Jr.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;null===t.boundingSphere&&t.computeBoundingSphere(),Jr.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Jr)}intersectsSprite(e){Jr.center.set(0,0,0);const t=es.distanceTo(e.center);return Jr.radius=.7071067811865476+t,Jr.applyMatrix4(e.matrixWorld),this.intersectsSphere(Jr)}intersectsSphere(e){const t=this.planes,n=e.center,i=-e.radius;for(let e=0;e<6;e++){if(t[e].distanceToPoint(n)0?e.max.x:e.min.x,ts.y=i.normal.y>0?e.max.y:e.min.y,ts.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(ts)<0)return!1}return!0}containsPoint(e){const 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)}}const is=new Fn,rs=new ns;class ss{constructor(){this.coordinateSystem=Ft}intersectsObject(e,t){if(!t.isArrayCamera||0===t.cameras.length)return!1;for(let n=0;ni)return;ds.applyMatrix4(e.matrixWorld);const l=t.ray.origin.distanceTo(ds);return lt.far?void 0:{distance:l,point:ps.clone().applyMatrix4(e.matrixWorld),index:a,face:null,faceIndex:null,barycoord:null,object:e}}class ms extends Sr{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new _i(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}}class gs extends Nn{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=le,this.minFilter=le,this.generateMipmaps=!1,this.needsUpdate=!0}}class _s extends Nn{constructor(e=[],t=301,n,i,r,s,a,o,l,u){super(e,t,n,i,r,s,a,o,l,u),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class vs extends Nn{constructor(e,t,n=1014,i,r,s,a=1003,o=1003,l,u=1026,c=1){if(u!==Ne&&u!==Pe)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");super({width:e,height:t,depth:c},i,r,s,a,o,u,n,l),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new wn(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return null!==this.compareFunction&&(t.compareFunction=this.compareFunction),t}}class ys extends vs{constructor(e,t=1014,n=301,i,r,s=1003,a=1003,o,l=1026){const u={width:e,height:e,depth:1},c=[u,u,u,u,u,u];super(e,e,t,n,i,r,s,a,o,l),this.image=c,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}}class bs extends Nn{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}}class xs extends vr{constructor(e=1,t=1,n=1,i=1,r=1,s=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:n,widthSegments:i,heightSegments:r,depthSegments:s};const a=this;i=Math.floor(i),r=Math.floor(r),s=Math.floor(s);const o=[],l=[],u=[],c=[];let h=0,d=0;function p(e,t,n,i,r,s,p,f,m,g,_){const v=s/m,y=p/g,b=s/2,x=p/2,T=f/2,S=m+1,M=g+1;let E=0,w=0;const A=new dn;for(let s=0;s0?1:-1,u.push(A.x,A.y,A.z),c.push(o/m),c.push(1-s/g),E+=1}}for(let e=0;e0||0!==i)&&(u.push(s,a,l),v+=3),(t>0||i!==r-1)&&(u.push(a,o,l),v+=3)}l.addGroup(g,v,0),g+=v}(),!1===s&&(e>0&&_(!0),t>0&&_(!1)),this.setIndex(u),this.setAttribute("position",new ar(c,3)),this.setAttribute("normal",new ar(h,3)),this.setAttribute("uv",new ar(d,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Ts(e.radiusTop,e.radiusBottom,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class Ss extends Ts{constructor(e=1,t=1,n=32,i=1,r=!1,s=0,a=2*Math.PI){super(0,e,t,n,i,r,s,a),this.type="ConeGeometry",this.parameters={radius:e,height:t,radialSegments:n,heightSegments:i,openEnded:r,thetaStart:s,thetaLength:a}}static fromJSON(e){return new Ss(e.radius,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class Ms{constructor(){this.type="Curve",this.arcLengthDivisions=200,this.needsUpdate=!1,this.cacheArcLengths=null}getPoint(){Xt("Curve: .getPoint() not implemented.")}getPointAt(e,t){const n=this.getUtoTmapping(e);return this.getPoint(n,t)}getPoints(e=5){const t=[];for(let n=0;n<=e;n++)t.push(this.getPoint(n/e));return t}getSpacedPoints(e=5){const t=[];for(let n=0;n<=e;n++)t.push(this.getPointAt(n/e));return t}getLength(){const 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;const t=[];let n,i=this.getPoint(0),r=0;t.push(0);for(let s=1;s<=e;s++)n=this.getPoint(s/e),r+=n.distanceTo(i),t.push(r),i=n;return this.cacheArcLengths=t,t}updateArcLengths(){this.needsUpdate=!0,this.getLengths()}getUtoTmapping(e,t=null){const n=this.getLengths();let i=0;const r=n.length;let s;s=t||e*n[r-1];let a,o=0,l=r-1;for(;o<=l;)if(i=Math.floor(o+(l-o)/2),a=n[i]-s,a<0)o=i+1;else{if(!(a>0)){l=i;break}l=i-1}if(i=l,n[i]===s)return i/(r-1);const u=n[i];return(i+(s-u)/(n[i+1]-u))/(r-1)}getTangent(e,t){const n=1e-4;let i=e-n,r=e+n;i<0&&(i=0),r>1&&(r=1);const s=this.getPoint(i),a=this.getPoint(r),o=t||(s.isVector2?new cn:new dn);return o.copy(a).sub(s).normalize(),o}getTangentAt(e,t){const n=this.getUtoTmapping(e);return this.getTangent(n,t)}computeFrenetFrames(e,t=!1){const n=new dn,i=[],r=[],s=[],a=new dn,o=new Fn;for(let t=0;t<=e;t++){const n=t/e;i[t]=this.getTangentAt(n,new dn)}r[0]=new dn,s[0]=new dn;let l=Number.MAX_VALUE;const u=Math.abs(i[0].x),c=Math.abs(i[0].y),h=Math.abs(i[0].z);u<=l&&(l=u,n.set(1,0,0)),c<=l&&(l=c,n.set(0,1,0)),h<=l&&n.set(0,0,1),a.crossVectors(i[0],n).normalize(),r[0].crossVectors(i[0],a),s[0].crossVectors(i[0],r[0]);for(let t=1;t<=e;t++){if(r[t]=r[t-1].clone(),s[t]=s[t-1].clone(),a.crossVectors(i[t-1],i[t]),a.length()>Number.EPSILON){a.normalize();const e=Math.acos(rn(i[t-1].dot(i[t]),-1,1));r[t].applyMatrix4(o.makeRotationAxis(a,e))}s[t].crossVectors(i[t],r[t])}if(!0===t){let t=Math.acos(rn(r[0].dot(r[e]),-1,1));t/=e,i[0].dot(a.crossVectors(r[0],r[e]))>0&&(t=-t);for(let n=1;n<=e;n++)r[n].applyMatrix4(o.makeRotationAxis(i[n],t*n)),s[n].crossVectors(i[n],r[n])}return{tangents:i,normals:r,binormals:s}}clone(){return(new this.constructor).copy(this)}copy(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}toJSON(){const 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}}class Es extends Ms{constructor(e=0,t=0,n=1,i=1,r=0,s=2*Math.PI,a=!1,o=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=e,this.aY=t,this.xRadius=n,this.yRadius=i,this.aStartAngle=r,this.aEndAngle=s,this.aClockwise=a,this.aRotation=o}getPoint(e,t=new cn){const n=t,i=2*Math.PI;let r=this.aEndAngle-this.aStartAngle;const s=Math.abs(r)i;)r-=i;r0?0:(Math.floor(Math.abs(l)/r)+1)*r:0===u&&l===r-1&&(l=r-2,u=1),this.closed||l>0?a=i[(l-1)%r]:(As.subVectors(i[0],i[1]).add(i[0]),a=As);const c=i[l%r],h=i[(l+1)%r];if(this.closed||l+2i.length-2?i.length-1:s+1],c=i[s>i.length-3?i.length-1:s+2];return n.set(Ps(a,o.x,l.x,u.x,c.x),Ps(a,o.y,l.y,u.y,c.y)),n}copy(e){super.copy(e),this.points=[];for(let t=0,n=e.points.length;t0)&&d.push(t,r,l),(e!==n-1||o0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const n={};for(const e in this.extensions)!0===this.extensions[e]&&(n[e]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}}class $s extends Ws{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}}class Xs extends Sr{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new _i(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 _i(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new cn(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 $n,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}}class qs extends Xs{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 cn(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return rn(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(e){this.ior=(1+.4*e)/(1-.4*e)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new _i(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 _i(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new _i(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}}class Ys extends Sr{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new _i(16777215),this.specular=new _i(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new _i(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new cn(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new $n,this.combine=0,this.reflectivity=1,this.envMapIntensity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(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.envMapIntensity=e.envMapIntensity,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}}class Ks extends Sr{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new _i(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new _i(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new cn(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}}class Zs extends Sr{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new cn(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}}class Qs extends Sr{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new _i(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new _i(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new cn(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new $n,this.combine=0,this.reflectivity=1,this.envMapIntensity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(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.envMapIntensity=e.envMapIntensity,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}}class Js extends Sr{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=3200,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}}class ea extends Sr{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}}class ta extends Sr{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new _i(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new cn(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,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.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this.fog=e.fog,this}}class na extends as{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}}const ia={enabled:!1,files:{},add:function(e,t){!1!==this.enabled&&(ra(e)||(this.files[e]=t))},get:function(e){if(!1!==this.enabled&&!ra(e))return this.files[e]},remove:function(e){delete this.files[e]},clear:function(){this.files={}}};function ra(e){try{const t=e.slice(e.indexOf(":")+1);return"blob:"===new URL(t).protocol}catch(e){return!1}}class sa{constructor(e,t,n){const i=this;let r,s=!1,a=0,o=0;const l=[];this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=n,this._abortController=null,this.itemStart=function(e){o++,!1===s&&void 0!==i.onStart&&i.onStart(e,a,o),s=!0},this.itemEnd=function(e){a++,void 0!==i.onProgress&&i.onProgress(e,a,o),a===o&&(s=!1,void 0!==i.onLoad&&i.onLoad())},this.itemError=function(e){void 0!==i.onError&&i.onError(e)},this.resolveURL=function(e){return r?r(e):e},this.setURLModifier=function(e){return r=e,this},this.addHandler=function(e,t){return l.push(e,t),this},this.removeHandler=function(e){const t=l.indexOf(e);return-1!==t&&l.splice(t,2),this},this.getHandler=function(e){for(let t=0,n=l.length;te.start-t.start);let t=0;for(let e=1;e 0\n\tvec4 plane;\n\t#ifdef ALPHA_TO_COVERAGE\n\t\tfloat distanceToPlane, distanceGradient;\n\t\tfloat clipOpacity = 1.0;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\tclipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\tif ( clipOpacity == 0.0 ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tfloat unionClipOpacity = 1.0;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\t\tunionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tclipOpacity *= 1.0 - unionClipOpacity;\n\t\t#endif\n\t\tdiffuseColor.a *= clipOpacity;\n\t\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tbool clipped = true;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tif ( clipped ) discard;\n\t\t#endif\n\t#endif\n#endif",clipping_planes_pars_fragment:"#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif",clipping_planes_pars_vertex:"#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif",clipping_planes_vertex:"#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif",color_fragment:"#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#endif",color_pars_fragment:"#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#endif",color_pars_vertex:"#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvarying vec4 vColor;\n#endif",color_vertex:"#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvColor = vec4( 1.0 );\n#endif\n#ifdef USE_COLOR_ALPHA\n\tvColor *= color;\n#elif defined( USE_COLOR )\n\tvColor.rgb *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.rgb *= instanceColor.rgb;\n#endif\n#ifdef USE_BATCHING_COLOR\n\tvColor *= getBatchingColor( getIndirectIndex( gl_DrawID ) );\n#endif",common:"#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nvec3 pow2( const in vec3 x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\n#ifdef USE_ALPHAHASH\n\tvarying vec3 vPosition;\n#endif\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}\nvec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n} // validated",cube_uv_reflection_fragment:"#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\thighp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tuv.x += filterInt * 3.0 * cubeUV_minTileSize;\n\t\tuv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n\t\tuv.x *= CUBEUV_TEXEL_WIDTH;\n\t\tuv.y *= CUBEUV_TEXEL_HEIGHT;\n\t\t#ifdef texture2DGradEXT\n\t\t\treturn texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n\t\t#else\n\t\t\treturn texture2D( envMap, uv ).rgb;\n\t\t#endif\n\t}\n\t#define cubeUV_r0 1.0\n\t#define cubeUV_m0 - 2.0\n\t#define cubeUV_r1 0.8\n\t#define cubeUV_m1 - 1.0\n\t#define cubeUV_r4 0.4\n\t#define cubeUV_m4 2.0\n\t#define cubeUV_r5 0.305\n\t#define cubeUV_m5 3.0\n\t#define cubeUV_r6 0.21\n\t#define cubeUV_m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= cubeUV_r1 ) {\n\t\t\tmip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;\n\t\t} else if ( roughness >= cubeUV_r4 ) {\n\t\t\tmip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;\n\t\t} else if ( roughness >= cubeUV_r5 ) {\n\t\t\tmip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;\n\t\t} else if ( roughness >= cubeUV_r6 ) {\n\t\t\tmip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif",defaultnormal_vertex:"vec3 transformedNormal = objectNormal;\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = objectTangent;\n#endif\n#ifdef USE_BATCHING\n\tmat3 bm = mat3( batchingMatrix );\n\ttransformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );\n\ttransformedNormal = bm * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = bm * transformedTangent;\n\t#endif\n#endif\n#ifdef USE_INSTANCING\n\tmat3 im = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );\n\ttransformedNormal = im * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = im * transformedTangent;\n\t#endif\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\ttransformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif",displacementmap_pars_vertex:"#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif",displacementmap_vertex:"#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif",emissivemap_fragment:"#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );\n\t#ifdef DECODE_VIDEO_TEXTURE_EMISSIVE\n\t\temissiveColor = sRGBTransferEOTF( emissiveColor );\n\t#endif\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif",emissivemap_pars_fragment:"#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif",colorspace_fragment:"gl_FragColor = linearToOutputTexel( gl_FragColor );",colorspace_pars_fragment:"vec4 LinearTransferOETF( in vec4 value ) {\n\treturn value;\n}\nvec4 sRGBTransferEOTF( in vec4 value ) {\n\treturn 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 );\n}\nvec4 sRGBTransferOETF( in vec4 value ) {\n\treturn 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 );\n}",envmap_fragment:"#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t\t#endif\n\t#endif\n#endif",envmap_common_pars_fragment:"#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform mat3 envMapRotation;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n#endif",envmap_pars_fragment:"#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif",envmap_pars_vertex:"#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif",envmap_physical_pars_fragment:"#ifdef USE_ENVMAP\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 reflectVec = reflect( - viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, pow4( roughness ) ) );\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\t#ifdef USE_ANISOTROPY\n\t\tvec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {\n\t\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\t\tvec3 bentNormal = cross( bitangent, viewDir );\n\t\t\t\tbentNormal = normalize( cross( bentNormal, bitangent ) );\n\t\t\t\tbentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );\n\t\t\t\treturn getIBLRadiance( viewDir, bentNormal, roughness );\n\t\t\t#else\n\t\t\t\treturn vec3( 0.0 );\n\t\t\t#endif\n\t\t}\n\t#endif\n#endif",envmap_vertex:"#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif",fog_vertex:"#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif",fog_pars_vertex:"#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif",fog_fragment:"#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif",fog_pars_fragment:"#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif",gradientmap_pars_fragment:"#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn vec3( texture2D( gradientMap, coord ).r );\n\t#else\n\t\tvec2 fw = fwidth( coord ) * 0.5;\n\t\treturn mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );\n\t#endif\n}",lightmap_pars_fragment:"#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif",lights_lambert_fragment:"LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;",lights_lambert_pars_fragment:"varying vec3 vViewPosition;\nstruct LambertMaterial {\n\tvec3 diffuseColor;\n\tfloat specularStrength;\n};\nvoid 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 ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid 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 ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Lambert\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Lambert",lights_pars_begin:"uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\n#if defined( USE_LIGHT_PROBES )\n\tuniform vec3 lightProbe[ 9 ];\n#endif\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif ( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif",lights_toon_fragment:"ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;",lights_toon_pars_fragment:"varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid 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 ) {\n\tvec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid 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 ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon",lights_phong_fragment:"BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;",lights_phong_pars_fragment:"varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid 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 ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid 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 ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong",lights_physical_fragment:"PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.diffuseContribution = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.metalness = metalnessFactor;\nvec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\tmaterial.ior = ior;\n\t#ifdef USE_SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULAR_COLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;\n\t\t#endif\n\t\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor;\n\tmaterial.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = vec3( 0.04 );\n\tmaterial.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_DISPERSION\n\tmaterial.dispersion = dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n\tmaterial.iridescence = iridescence;\n\tmaterial.iridescenceIOR = iridescenceIOR;\n\t#ifdef USE_IRIDESCENCEMAP\n\t\tmaterial.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;\n\t#else\n\t\tmaterial.iridescenceThickness = iridescenceThicknessMaximum;\n\t#endif\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.0001, 1.0 );\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\t#ifdef USE_ANISOTROPYMAP\n\t\tmat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );\n\t\tvec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;\n\t\tvec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;\n\t#else\n\t\tvec2 anisotropyV = anisotropyVector;\n\t#endif\n\tmaterial.anisotropy = length( anisotropyV );\n\tif( material.anisotropy == 0.0 ) {\n\t\tanisotropyV = vec2( 1.0, 0.0 );\n\t} else {\n\t\tanisotropyV /= material.anisotropy;\n\t\tmaterial.anisotropy = saturate( material.anisotropy );\n\t}\n\tmaterial.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );\n\tmaterial.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;\n\tmaterial.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;\n#endif",lights_physical_pars_fragment:"uniform sampler2D dfgLUT;\nstruct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tvec3 diffuseContribution;\n\tvec3 specularColor;\n\tvec3 specularColorBlended;\n\tfloat roughness;\n\tfloat metalness;\n\tfloat specularF90;\n\tfloat dispersion;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tfloat iridescence;\n\t\tfloat iridescenceIOR;\n\t\tfloat iridescenceThickness;\n\t\tvec3 iridescenceFresnel;\n\t\tvec3 iridescenceF0;\n\t\tvec3 iridescenceFresnelDielectric;\n\t\tvec3 iridescenceFresnelMetallic;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n\t#ifdef IOR\n\t\tfloat ior;\n\t#endif\n\t#ifdef USE_TRANSMISSION\n\t\tfloat transmission;\n\t\tfloat transmissionAlpha;\n\t\tfloat thickness;\n\t\tfloat attenuationDistance;\n\t\tvec3 attenuationColor;\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat anisotropy;\n\t\tfloat alphaT;\n\t\tvec3 anisotropyT;\n\t\tvec3 anisotropyB;\n\t#endif\n};\nvec3 clearcoatSpecularDirect = vec3( 0.0 );\nvec3 clearcoatSpecularIndirect = vec3( 0.0 );\nvec3 sheenSpecularDirect = vec3( 0.0 );\nvec3 sheenSpecularIndirect = vec3(0.0 );\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n float x2 = x * x;\n float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\n#ifdef USE_ANISOTROPY\n\tfloat 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 ) {\n\t\tfloat gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );\n\t\tfloat gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );\n\t\tfloat v = 0.5 / ( gv + gl );\n\t\treturn v;\n\t}\n\tfloat D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {\n\t\tfloat a2 = alphaT * alphaB;\n\t\thighp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );\n\t\thighp float v2 = dot( v, v );\n\t\tfloat w2 = a2 / v2;\n\t\treturn RECIPROCAL_PI * a2 * pow2 ( w2 );\n\t}\n#endif\n#ifdef USE_CLEARCOAT\n\tvec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {\n\t\tvec3 f0 = material.clearcoatF0;\n\t\tfloat f90 = material.clearcoatF90;\n\t\tfloat roughness = material.clearcoatRoughness;\n\t\tfloat alpha = pow2( roughness );\n\t\tvec3 halfDir = normalize( lightDir + viewDir );\n\t\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\t\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\t\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\t\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\t\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t\treturn F * ( V * D );\n\t}\n#endif\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n\tvec3 f0 = material.specularColorBlended;\n\tfloat f90 = material.specularF90;\n\tfloat roughness = material.roughness;\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t#ifdef USE_IRIDESCENCE\n\t\tF = mix( F, material.iridescenceFresnel, material.iridescence );\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat dotTL = dot( material.anisotropyT, lightDir );\n\t\tfloat dotTV = dot( material.anisotropyT, viewDir );\n\t\tfloat dotTH = dot( material.anisotropyT, halfDir );\n\t\tfloat dotBL = dot( material.anisotropyB, lightDir );\n\t\tfloat dotBV = dot( material.anisotropyB, viewDir );\n\t\tfloat dotBH = dot( material.anisotropyB, halfDir );\n\t\tfloat V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );\n\t\tfloat D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );\n\t#else\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t#endif\n\treturn F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transpose( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat rInv = 1.0 / ( roughness + 0.1 );\n\tfloat a = -1.9362 + 1.0678 * roughness + 0.4573 * r2 - 0.8469 * rInv;\n\tfloat b = -0.6014 + 0.5538 * roughness - 0.4670 * r2 - 0.1255 * rInv;\n\tfloat DG = exp( a * dotNV + b );\n\treturn saturate( DG );\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg;\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid 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 ) {\n#else\nvoid 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 ) {\n#endif\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg;\n\t#ifdef USE_IRIDESCENCE\n\t\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n\t#else\n\t\tvec3 Fr = specularColor;\n\t#endif\n\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\nvec3 BRDF_GGX_Multiscatter( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n\tvec3 singleScatter = BRDF_GGX( lightDir, viewDir, normal, material );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 dfgV = texture2D( dfgLUT, vec2( material.roughness, dotNV ) ).rg;\n\tvec2 dfgL = texture2D( dfgLUT, vec2( material.roughness, dotNL ) ).rg;\n\tvec3 FssEss_V = material.specularColorBlended * dfgV.x + material.specularF90 * dfgV.y;\n\tvec3 FssEss_L = material.specularColorBlended * dfgL.x + material.specularF90 * dfgL.y;\n\tfloat Ess_V = dfgV.x + dfgV.y;\n\tfloat Ess_L = dfgL.x + dfgL.y;\n\tfloat Ems_V = 1.0 - Ess_V;\n\tfloat Ems_L = 1.0 - Ess_L;\n\tvec3 Favg = material.specularColorBlended + ( 1.0 - material.specularColorBlended ) * 0.047619;\n\tvec3 Fms = FssEss_V * FssEss_L * Favg / ( 1.0 - Ems_V * Ems_L * Favg + EPSILON );\n\tfloat compensationFactor = Ems_V * Ems_L;\n\tvec3 multiScatter = Fms * compensationFactor;\n\treturn singleScatter + multiScatter;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid 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 ) {\n\t\tvec3 normal = geometryNormal;\n\t\tvec3 viewDir = geometryViewDir;\n\t\tvec3 position = geometryPosition;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColorBlended * t2.x + ( material.specularF90 - material.specularColorBlended ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseContribution * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t\t#ifdef USE_CLEARCOAT\n\t\t\tvec3 Ncc = geometryClearcoatNormal;\n\t\t\tvec2 uvClearcoat = LTC_Uv( Ncc, viewDir, material.clearcoatRoughness );\n\t\t\tvec4 t1Clearcoat = texture2D( ltc_1, uvClearcoat );\n\t\t\tvec4 t2Clearcoat = texture2D( ltc_2, uvClearcoat );\n\t\t\tmat3 mInvClearcoat = mat3(\n\t\t\t\tvec3( t1Clearcoat.x, 0, t1Clearcoat.y ),\n\t\t\t\tvec3( 0, 1, 0 ),\n\t\t\t\tvec3( t1Clearcoat.z, 0, t1Clearcoat.w )\n\t\t\t);\n\t\t\tvec3 fresnelClearcoat = material.clearcoatF0 * t2Clearcoat.x + ( material.clearcoatF90 - material.clearcoatF0 ) * t2Clearcoat.y;\n\t\t\tclearcoatSpecularDirect += lightColor * fresnelClearcoat * LTC_Evaluate( Ncc, viewDir, position, mInvClearcoat, rectCoords );\n\t\t#endif\n\t}\n#endif\nvoid 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 ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );\n\t#endif\n\t#ifdef USE_SHEEN\n \n \t\tsheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );\n \n \t\tfloat sheenAlbedoV = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n \t\tfloat sheenAlbedoL = IBLSheenBRDF( geometryNormal, directLight.direction, material.sheenRoughness );\n \n \t\tfloat sheenEnergyComp = 1.0 - max3( material.sheenColor ) * max( sheenAlbedoV, sheenAlbedoL );\n \n \t\tirradiance *= sheenEnergyComp;\n \n \t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX_Multiscatter( directLight.direction, geometryViewDir, geometryNormal, material );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseContribution );\n}\nvoid 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 ) {\n\tvec3 diffuse = irradiance * BRDF_Lambert( material.diffuseContribution );\n\t#ifdef USE_SHEEN\n\t\tfloat sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n\t\tfloat sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo;\n\t\tdiffuse *= sheenEnergyComp;\n\t#endif\n\treflectedLight.indirectDiffuse += diffuse;\n}\nvoid 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) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ) * RECIPROCAL_PI;\n \t#endif\n\tvec3 singleScatteringDielectric = vec3( 0.0 );\n\tvec3 multiScatteringDielectric = vec3( 0.0 );\n\tvec3 singleScatteringMetallic = vec3( 0.0 );\n\tvec3 multiScatteringMetallic = vec3( 0.0 );\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnelDielectric, material.roughness, singleScatteringDielectric, multiScatteringDielectric );\n\t\tcomputeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.iridescence, material.iridescenceFresnelMetallic, material.roughness, singleScatteringMetallic, multiScatteringMetallic );\n\t#else\n\t\tcomputeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScatteringDielectric, multiScatteringDielectric );\n\t\tcomputeMultiscattering( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.roughness, singleScatteringMetallic, multiScatteringMetallic );\n\t#endif\n\tvec3 singleScattering = mix( singleScatteringDielectric, singleScatteringMetallic, material.metalness );\n\tvec3 multiScattering = mix( multiScatteringDielectric, multiScatteringMetallic, material.metalness );\n\tvec3 totalScatteringDielectric = singleScatteringDielectric + multiScatteringDielectric;\n\tvec3 diffuse = material.diffuseContribution * ( 1.0 - totalScatteringDielectric );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tvec3 indirectSpecular = radiance * singleScattering;\n\tindirectSpecular += multiScattering * cosineWeightedIrradiance;\n\tvec3 indirectDiffuse = diffuse * cosineWeightedIrradiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n\t\tfloat sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo;\n\t\tindirectSpecular *= sheenEnergyComp;\n\t\tindirectDiffuse *= sheenEnergyComp;\n\t#endif\n\treflectedLight.indirectSpecular += indirectSpecular;\n\treflectedLight.indirectDiffuse += indirectDiffuse;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}",lights_fragment_begin:"\nvec3 geometryPosition = - vViewPosition;\nvec3 geometryNormal = normal;\nvec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\nvec3 geometryClearcoatNormal = vec3( 0.0 );\n#ifdef USE_CLEARCOAT\n\tgeometryClearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometryViewDir ) );\n\tif ( material.iridescenceThickness == 0.0 ) {\n\t\tmaterial.iridescence = 0.0;\n\t} else {\n\t\tmaterial.iridescence = saturate( material.iridescence );\n\t}\n\tif ( material.iridescence > 0.0 ) {\n\t\tmaterial.iridescenceFresnelDielectric = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tmaterial.iridescenceFresnelMetallic = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.diffuseColor );\n\t\tmaterial.iridescenceFresnel = mix( material.iridescenceFresnelDielectric, material.iridescenceFresnelMetallic, material.metalness );\n\t\tmaterial.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n\t}\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometryPosition, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tvec4 spotColor;\n\tvec3 spotLightCoord;\n\tbool inSpotLightMap;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometryPosition, directLight );\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n\t\t#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n\t\t#else\n\t\t#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#endif\n\t\t#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n\t\t\tspotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n\t\t\tinSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n\t\t\tspotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n\t\t\tdirectLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n\t\t#endif\n\t\t#undef SPOT_LIGHT_MAP_INDEX\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#if defined( USE_LIGHT_PROBES )\n\t\tirradiance += getLightProbeIrradiance( lightProbe, geometryNormal );\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif",lights_fragment_maps:"#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\t#if defined( STANDARD ) || defined( LAMBERT ) || defined( PHONG )\n\t\t\tiblIrradiance += getIBLIrradiance( geometryNormal );\n\t\t#endif\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\t#ifdef USE_ANISOTROPY\n\t\tradiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );\n\t#else\n\t\tradiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif",lights_fragment_end:"#if defined( RE_IndirectDiffuse )\n\t#if defined( LAMBERT ) || defined( PHONG )\n\t\tirradiance += iblIrradiance;\n\t#endif\n\tRE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif",logdepthbuf_fragment:"#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )\n\tgl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif",logdepthbuf_pars_fragment:"#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif",logdepthbuf_pars_vertex:"#ifdef USE_LOGARITHMIC_DEPTH_BUFFER\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif",logdepthbuf_vertex:"#ifdef USE_LOGARITHMIC_DEPTH_BUFFER\n\tvFragDepth = 1.0 + gl_Position.w;\n\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n#endif",map_fragment:"#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vMapUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif",map_pars_fragment:"#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif",map_particle_fragment:"#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t#if defined( USE_POINTS_UV )\n\t\tvec2 uv = vUv;\n\t#else\n\t\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif",map_particle_pars_fragment:"#if defined( USE_POINTS_UV )\n\tvarying vec2 vUv;\n#else\n\t#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t\tuniform mat3 uvTransform;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif",metalnessmap_fragment:"float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif",metalnessmap_pars_fragment:"#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif",morphinstance_vertex:"#ifdef USE_INSTANCING_MORPH\n\tfloat morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\tfloat morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tmorphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;\n\t}\n#endif",morphcolor_vertex:"#if defined( USE_MORPHCOLORS )\n\tvColor *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t#if defined( USE_COLOR_ALPHA )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\n\t\t#elif defined( USE_COLOR )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\n\t\t#endif\n\t}\n#endif",morphnormal_vertex:"#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif",morphtarget_pars_vertex:"#ifdef USE_MORPHTARGETS\n\t#ifndef USE_INSTANCING_MORPH\n\t\tuniform float morphTargetBaseInfluence;\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t#endif\n\tuniform sampler2DArray morphTargetsTexture;\n\tuniform ivec2 morphTargetsTextureSize;\n\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t}\n#endif",morphtarget_vertex:"#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif",normal_fragment_begin:"float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = dFdx( vViewPosition );\n\tvec3 fdy = dFdy( vViewPosition );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal *= faceDirection;\n\t#endif\n#endif\n#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn = getTangentFrame( - vViewPosition, normal,\n\t\t#if defined( USE_NORMALMAP )\n\t\t\tvNormalMapUv\n\t\t#elif defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tvClearcoatNormalMapUv\n\t\t#else\n\t\t\tvUv\n\t\t#endif\n\t\t);\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn[0] *= faceDirection;\n\t\ttbn[1] *= faceDirection;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn2[0] *= faceDirection;\n\t\ttbn2[1] *= faceDirection;\n\t#endif\n#endif\nvec3 nonPerturbedNormal = normal;",normal_fragment_maps:"#ifdef USE_NORMALMAP_OBJECTSPACE\n\tnormal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( USE_NORMALMAP_TANGENTSPACE )\n\tvec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\tnormal = normalize( tbn * mapN );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif",normal_pars_fragment:"#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif",normal_pars_vertex:"#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif",normal_vertex:"#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif",normalmap_pars_fragment:"#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef USE_NORMALMAP_OBJECTSPACE\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )\n\tmat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( uv.st );\n\t\tvec2 st1 = dFdy( uv.st );\n\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );\n\t\treturn mat3( T * scale, B * scale, N );\n\t}\n#endif",clearcoat_normal_fragment_begin:"#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif",clearcoat_normal_fragment_maps:"#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\tclearcoatNormal = normalize( tbn2 * clearcoatMapN );\n#endif",clearcoat_pars_fragment:"#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif",iridescence_pars_fragment:"#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif",opaque_fragment:"#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );",packing:"vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.;\nconst float Inv255 = 1. / 255.;\nconst vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 );\nconst vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g );\nconst vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b );\nconst vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a );\nvec4 packDepthToRGBA( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec4( 0., 0., 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec4( 1., 1., 1., 1. );\n\tfloat vuf;\n\tfloat af = modf( v * PackFactors.a, vuf );\n\tfloat bf = modf( vuf * ShiftRight8, vuf );\n\tfloat gf = modf( vuf * ShiftRight8, vuf );\n\treturn vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af );\n}\nvec3 packDepthToRGB( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec3( 0., 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec3( 1., 1., 1. );\n\tfloat vuf;\n\tfloat bf = modf( v * PackFactors.b, vuf );\n\tfloat gf = modf( vuf * ShiftRight8, vuf );\n\treturn vec3( vuf * Inv255, gf * PackUpscale, bf );\n}\nvec2 packDepthToRG( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec2( 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec2( 1., 1. );\n\tfloat vuf;\n\tfloat gf = modf( v * 256., vuf );\n\treturn vec2( vuf * Inv255, gf );\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors4 );\n}\nfloat unpackRGBToDepth( const in vec3 v ) {\n\treturn dot( v, UnpackFactors3 );\n}\nfloat unpackRGToDepth( const in vec2 v ) {\n\treturn v.r * UnpackFactors2.r + v.g * UnpackFactors2.g;\n}\nvec4 pack2HalfToRGBA( const in vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( const in vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\n\t\treturn depth * ( far - near ) - far;\n\t#else\n\t\treturn depth * ( near - far ) - near;\n\t#endif\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\t\n\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\treturn ( near * far ) / ( ( near - far ) * depth - near );\n\t#else\n\t\treturn ( near * far ) / ( ( far - near ) * depth - far );\n\t#endif\n}",premultiplied_alpha_fragment:"#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif",project_vertex:"vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_BATCHING\n\tmvPosition = batchingMatrix * mvPosition;\n#endif\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;",dithering_fragment:"#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif",dithering_pars_fragment:"#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif",roughnessmap_fragment:"float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif",roughnessmap_pars_fragment:"#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif",shadowmap_pars_fragment:"#if NUM_SPOT_LIGHT_COORDS > 0\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n\tuniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform sampler2DShadow directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\t#else\n\t\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\t#endif\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform sampler2DShadow spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\t#else\n\t\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\t#endif\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform samplerCubeShadow pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\t#elif defined( SHADOWMAP_TYPE_BASIC )\n\t\t\tuniform samplerCube pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\t#endif\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\tfloat interleavedGradientNoise( vec2 position ) {\n\t\t\treturn fract( 52.9829189 * fract( dot( position, vec2( 0.06711056, 0.00583715 ) ) ) );\n\t\t}\n\t\tvec2 vogelDiskSample( int sampleIndex, int samplesCount, float phi ) {\n\t\t\tconst float goldenAngle = 2.399963229728653;\n\t\t\tfloat r = sqrt( ( float( sampleIndex ) + 0.5 ) / float( samplesCount ) );\n\t\t\tfloat theta = float( sampleIndex ) * goldenAngle + phi;\n\t\t\treturn vec2( cos( theta ), sin( theta ) ) * r;\n\t\t}\n\t#endif\n\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\tfloat getShadow( sampler2DShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\t\tfloat shadow = 1.0;\n\t\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\t\tshadowCoord.z += shadowBias;\n\t\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\t\tif ( frustumTest ) {\n\t\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\t\tfloat radius = shadowRadius * texelSize.x;\n\t\t\t\tfloat phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2;\n\t\t\t\tshadow = (\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 0, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 1, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 2, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 3, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 4, 5, phi ) * radius, shadowCoord.z ) )\n\t\t\t\t) * 0.2;\n\t\t\t}\n\t\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t\t}\n\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\t\tfloat shadow = 1.0;\n\t\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tshadowCoord.z -= shadowBias;\n\t\t\t#else\n\t\t\t\tshadowCoord.z += shadowBias;\n\t\t\t#endif\n\t\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\t\tif ( frustumTest ) {\n\t\t\t\tvec2 distribution = texture2D( shadowMap, shadowCoord.xy ).rg;\n\t\t\t\tfloat mean = distribution.x;\n\t\t\t\tfloat variance = distribution.y * distribution.y;\n\t\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\t\tfloat hard_shadow = step( mean, shadowCoord.z );\n\t\t\t\t#else\n\t\t\t\t\tfloat hard_shadow = step( shadowCoord.z, mean );\n\t\t\t\t#endif\n\t\t\t\t\n\t\t\t\tif ( hard_shadow == 1.0 ) {\n\t\t\t\t\tshadow = 1.0;\n\t\t\t\t} else {\n\t\t\t\t\tvariance = max( variance, 0.0000001 );\n\t\t\t\t\tfloat d = shadowCoord.z - mean;\n\t\t\t\t\tfloat p_max = variance / ( variance + d * d );\n\t\t\t\t\tp_max = clamp( ( p_max - 0.3 ) / 0.65, 0.0, 1.0 );\n\t\t\t\t\tshadow = max( hard_shadow, p_max );\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t\t}\n\t#else\n\t\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\t\tfloat shadow = 1.0;\n\t\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tshadowCoord.z -= shadowBias;\n\t\t\t#else\n\t\t\t\tshadowCoord.z += shadowBias;\n\t\t\t#endif\n\t\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\t\tif ( frustumTest ) {\n\t\t\t\tfloat depth = texture2D( shadowMap, shadowCoord.xy ).r;\n\t\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\t\tshadow = step( depth, shadowCoord.z );\n\t\t\t\t#else\n\t\t\t\t\tshadow = step( shadowCoord.z, depth );\n\t\t\t\t#endif\n\t\t\t}\n\t\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t\t}\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#if defined( SHADOWMAP_TYPE_PCF )\n\tfloat getPointShadow( samplerCubeShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tfloat shadow = 1.0;\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\tvec3 absVec = abs( lightToPosition );\n\t\tfloat viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z );\n\t\tif ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) {\n\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tfloat dp = ( shadowCameraNear * ( shadowCameraFar - viewSpaceZ ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );\n\t\t\t\tdp -= shadowBias;\n\t\t\t#else\n\t\t\t\tfloat dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );\n\t\t\t\tdp += shadowBias;\n\t\t\t#endif\n\t\t\tfloat texelSize = shadowRadius / shadowMapSize.x;\n\t\t\tvec3 absDir = abs( bd3D );\n\t\t\tvec3 tangent = absDir.x > absDir.z ? vec3( 0.0, 1.0, 0.0 ) : vec3( 1.0, 0.0, 0.0 );\n\t\t\ttangent = normalize( cross( bd3D, tangent ) );\n\t\t\tvec3 bitangent = cross( bd3D, tangent );\n\t\t\tfloat phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2;\n\t\t\tvec2 sample0 = vogelDiskSample( 0, 5, phi );\n\t\t\tvec2 sample1 = vogelDiskSample( 1, 5, phi );\n\t\t\tvec2 sample2 = vogelDiskSample( 2, 5, phi );\n\t\t\tvec2 sample3 = vogelDiskSample( 3, 5, phi );\n\t\t\tvec2 sample4 = vogelDiskSample( 4, 5, phi );\n\t\t\tshadow = (\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample0.x + bitangent * sample0.y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample1.x + bitangent * sample1.y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample2.x + bitangent * sample2.y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample3.x + bitangent * sample3.y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample4.x + bitangent * sample4.y ) * texelSize, dp ) )\n\t\t\t) * 0.2;\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n\t#elif defined( SHADOWMAP_TYPE_BASIC )\n\tfloat getPointShadow( samplerCube shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tfloat shadow = 1.0;\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 absVec = abs( lightToPosition );\n\t\tfloat viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z );\n\t\tif ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) {\n\t\t\tfloat dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );\n\t\t\tdp += shadowBias;\n\t\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t\tfloat depth = textureCube( shadowMap, bd3D ).r;\n\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tdepth = 1.0 - depth;\n\t\t\t#endif\n\t\t\tshadow = step( dp, depth );\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n\t#endif\n\t#endif\n#endif",shadowmap_pars_vertex:"#if NUM_SPOT_LIGHT_COORDS > 0\n\tuniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif",shadowmap_vertex:"#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\tvec4 shadowWorldPosition;\n#endif\n#if defined( USE_SHADOWMAP )\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if NUM_SPOT_LIGHT_COORDS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition;\n\t\t#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t\tshadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\n\t\t#endif\n\t\tvSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n#endif",shadowmask_pars_fragment:"float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0 && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) )\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}",skinbase_vertex:"#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif",skinning_pars_vertex:"#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tint size = textureSize( boneTexture, 0 ).x;\n\t\tint j = int( i ) * 4;\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\tvec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );\n\t\tvec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );\n\t\tvec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );\n\t\tvec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );\n\t\treturn mat4( v1, v2, v3, v4 );\n\t}\n#endif",skinning_vertex:"#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif",skinnormal_vertex:"#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif",specularmap_fragment:"float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif",specularmap_pars_fragment:"#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif",tonemapping_fragment:"#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif",tonemapping_pars_fragment:"#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn saturate( toneMappingExposure * color );\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 CineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nconst mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(\n\tvec3( 1.6605, - 0.1246, - 0.0182 ),\n\tvec3( - 0.5876, 1.1329, - 0.1006 ),\n\tvec3( - 0.0728, - 0.0083, 1.1187 )\n);\nconst mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(\n\tvec3( 0.6274, 0.0691, 0.0164 ),\n\tvec3( 0.3293, 0.9195, 0.0880 ),\n\tvec3( 0.0433, 0.0113, 0.8956 )\n);\nvec3 agxDefaultContrastApprox( vec3 x ) {\n\tvec3 x2 = x * x;\n\tvec3 x4 = x2 * x2;\n\treturn + 15.5 * x4 * x2\n\t\t- 40.14 * x4 * x\n\t\t+ 31.96 * x4\n\t\t- 6.868 * x2 * x\n\t\t+ 0.4298 * x2\n\t\t+ 0.1191 * x\n\t\t- 0.00232;\n}\nvec3 AgXToneMapping( vec3 color ) {\n\tconst mat3 AgXInsetMatrix = mat3(\n\t\tvec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),\n\t\tvec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),\n\t\tvec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )\n\t);\n\tconst mat3 AgXOutsetMatrix = mat3(\n\t\tvec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),\n\t\tvec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),\n\t\tvec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )\n\t);\n\tconst float AgxMinEv = - 12.47393;\tconst float AgxMaxEv = 4.026069;\n\tcolor *= toneMappingExposure;\n\tcolor = LINEAR_SRGB_TO_LINEAR_REC2020 * color;\n\tcolor = AgXInsetMatrix * color;\n\tcolor = max( color, 1e-10 );\tcolor = log2( color );\n\tcolor = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );\n\tcolor = clamp( color, 0.0, 1.0 );\n\tcolor = agxDefaultContrastApprox( color );\n\tcolor = AgXOutsetMatrix * color;\n\tcolor = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );\n\tcolor = LINEAR_REC2020_TO_LINEAR_SRGB * color;\n\tcolor = clamp( color, 0.0, 1.0 );\n\treturn color;\n}\nvec3 NeutralToneMapping( vec3 color ) {\n\tconst float StartCompression = 0.8 - 0.04;\n\tconst float Desaturation = 0.15;\n\tcolor *= toneMappingExposure;\n\tfloat x = min( color.r, min( color.g, color.b ) );\n\tfloat offset = x < 0.08 ? x - 6.25 * x * x : 0.04;\n\tcolor -= offset;\n\tfloat peak = max( color.r, max( color.g, color.b ) );\n\tif ( peak < StartCompression ) return color;\n\tfloat d = 1. - StartCompression;\n\tfloat newPeak = 1. - d * d / ( peak + d - StartCompression );\n\tcolor *= newPeak / peak;\n\tfloat g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );\n\treturn mix( color, vec3( newPeak ), g );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }",transmission_fragment:"#ifdef USE_TRANSMISSION\n\tmaterial.transmission = transmission;\n\tmaterial.transmissionAlpha = 1.0;\n\tmaterial.thickness = thickness;\n\tmaterial.attenuationDistance = attenuationDistance;\n\tmaterial.attenuationColor = attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tmaterial.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tmaterial.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmitted = getIBLVolumeRefraction(\n\t\tn, v, material.roughness, material.diffuseContribution, material.specularColorBlended, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness,\n\t\tmaterial.attenuationColor, material.attenuationDistance );\n\tmaterial.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );\n\ttotalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );\n#endif",transmission_pars_fragment:"#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tfloat w0( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );\n\t}\n\tfloat w1( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );\n\t}\n\tfloat w2( float a ){\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );\n\t}\n\tfloat w3( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * a );\n\t}\n\tfloat g0( float a ) {\n\t\treturn w0( a ) + w1( a );\n\t}\n\tfloat g1( float a ) {\n\t\treturn w2( a ) + w3( a );\n\t}\n\tfloat h0( float a ) {\n\t\treturn - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );\n\t}\n\tfloat h1( float a ) {\n\t\treturn 1.0 + w3( a ) / ( w2( a ) + w3( a ) );\n\t}\n\tvec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {\n\t\tuv = uv * texelSize.zw + 0.5;\n\t\tvec2 iuv = floor( uv );\n\t\tvec2 fuv = fract( uv );\n\t\tfloat g0x = g0( fuv.x );\n\t\tfloat g1x = g1( fuv.x );\n\t\tfloat h0x = h0( fuv.x );\n\t\tfloat h1x = h1( fuv.x );\n\t\tfloat h0y = h0( fuv.y );\n\t\tfloat h1y = h1( fuv.y );\n\t\tvec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\treturn g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +\n\t\t\tg1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );\n\t}\n\tvec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {\n\t\tvec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );\n\t\tvec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );\n\t\tvec2 fLodSizeInv = 1.0 / fLodSize;\n\t\tvec2 cLodSizeInv = 1.0 / cLodSize;\n\t\tvec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );\n\t\tvec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );\n\t\treturn mix( fSample, cSample, fract( lod ) );\n\t}\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\treturn textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );\n\t}\n\tvec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( isinf( attenuationDistance ) ) {\n\t\t\treturn vec3( 1.0 );\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec4 transmittedLight;\n\t\tvec3 transmittance;\n\t\t#ifdef USE_DISPERSION\n\t\t\tfloat halfSpread = ( ior - 1.0 ) * 0.025 * dispersion;\n\t\t\tvec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread );\n\t\t\tfor ( int i = 0; i < 3; i ++ ) {\n\t\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix );\n\t\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\t\trefractionCoords += 1.0;\n\t\t\t\trefractionCoords /= 2.0;\n\t\t\t\tvec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );\n\t\t\t\ttransmittedLight[ i ] = transmissionSample[ i ];\n\t\t\t\ttransmittedLight.a += transmissionSample.a;\n\t\t\t\ttransmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ];\n\t\t\t}\n\t\t\ttransmittedLight.a /= 3.0;\n\t\t#else\n\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\trefractionCoords += 1.0;\n\t\t\trefractionCoords /= 2.0;\n\t\t\ttransmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\t\ttransmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\t#endif\n\t\tvec3 attenuatedColor = transmittance * transmittedLight.rgb;\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\tfloat transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );\n\t}\n#endif",uv_pars_fragment:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif",uv_pars_vertex:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tuniform mat3 mapTransform;\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform mat3 alphaMapTransform;\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tuniform mat3 lightMapTransform;\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tuniform mat3 aoMapTransform;\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tuniform mat3 bumpMapTransform;\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tuniform mat3 normalMapTransform;\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tuniform mat3 displacementMapTransform;\n\tvarying vec2 vDisplacementMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tuniform mat3 emissiveMapTransform;\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tuniform mat3 metalnessMapTransform;\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tuniform mat3 roughnessMapTransform;\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tuniform mat3 anisotropyMapTransform;\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tuniform mat3 clearcoatMapTransform;\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform mat3 clearcoatNormalMapTransform;\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform mat3 clearcoatRoughnessMapTransform;\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tuniform mat3 sheenColorMapTransform;\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tuniform mat3 sheenRoughnessMapTransform;\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tuniform mat3 iridescenceMapTransform;\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform mat3 iridescenceThicknessMapTransform;\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tuniform mat3 specularMapTransform;\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tuniform mat3 specularColorMapTransform;\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tuniform mat3 specularIntensityMapTransform;\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif",uv_vertex:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvUv = vec3( uv, 1 ).xy;\n#endif\n#ifdef USE_MAP\n\tvMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ALPHAMAP\n\tvAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_LIGHTMAP\n\tvLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_AOMAP\n\tvAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_BUMPMAP\n\tvBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_NORMALMAP\n\tvNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tvDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_METALNESSMAP\n\tvMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULARMAP\n\tvSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tvTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_THICKNESSMAP\n\tvThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;\n#endif",worldpos_vertex:"#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_BATCHING\n\t\tworldPosition = batchingMatrix * worldPosition;\n\t#endif\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif",background_vert:"varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}",background_frag:"uniform sampler2D t2D;\nuniform float backgroundIntensity;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\ttexColor = 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 );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include \n\t#include \n}",backgroundCube_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}",backgroundCube_frag:"#ifdef ENVMAP_TYPE_CUBE\n\tuniform samplerCube envMap;\n#elif defined( ENVMAP_TYPE_CUBE_UV )\n\tuniform sampler2D envMap;\n#endif\nuniform float flipEnvMap;\nuniform float backgroundBlurriness;\nuniform float backgroundIntensity;\nuniform mat3 backgroundRotation;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness );\n\t#else\n\t\tvec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include \n\t#include \n}",cube_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}",cube_frag:"uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n\tgl_FragColor = texColor;\n\tgl_FragColor.a *= opacity;\n\t#include \n\t#include \n}",depth_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvHighPrecisionZW = gl_Position.zw;\n}",depth_frag:"#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\tfloat fragCoordZ = vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ];\n\t#else\n\t\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ] + 0.5;\n\t#endif\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#elif DEPTH_PACKING == 3202\n\t\tgl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );\n\t#elif DEPTH_PACKING == 3203\n\t\tgl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );\n\t#endif\n}",distance_vert:"#define DISTANCE\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvWorldPosition = worldPosition.xyz;\n}",distance_frag:"#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main () {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = vec4( dist, 0.0, 0.0, 1.0 );\n}",equirect_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}",equirect_frag:"uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include \n\t#include \n}",linedashed_vert:"uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",linedashed_frag:"uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshbasic_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshbasic_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include \n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshlambert_vert:"#define LAMBERT\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}",meshlambert_frag:"#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshmatcap_vert:"#define MATCAP\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n}",meshmatcap_frag:"#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t#else\n\t\tvec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshnormal_vert:"#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}",meshnormal_frag:"#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_FragColor = vec4( normalize( normal ) * 0.5 + 0.5, diffuseColor.a );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}",meshphong_vert:"#define PHONG\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}",meshphong_frag:"#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshphysical_vert:"#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}",meshphysical_frag:"#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define USE_SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef USE_SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULAR_COLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_DISPERSION\n\tuniform float dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n\tuniform float iridescence;\n\tuniform float iridescenceIOR;\n\tuniform float iridescenceThicknessMinimum;\n\tuniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\tuniform vec2 anisotropyVector;\n\t#ifdef USE_ANISOTROPYMAP\n\t\tuniform sampler2D anisotropyMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include \n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n \n\t\toutgoingLight = outgoingLight + sheenSpecularDirect + sheenSpecularIndirect;\n \n \t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshtoon_vert:"#define TOON\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n}",meshtoon_frag:"#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",points_vert:"uniform float size;\nuniform float scale;\n#include \n#include \n#include \n#include \n#include \n#include \n#ifdef USE_POINTS_UV\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif\nvoid main() {\n\t#ifdef USE_POINTS_UV\n\t\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n}",points_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",shadow_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",shadow_frag:"uniform vec3 color;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include \n\t#include \n\t#include \n\t#include \n}",sprite_vert:"uniform float rotation;\nuniform vec2 center;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 mvPosition = modelViewMatrix[ 3 ];\n\tvec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include \n\t#include \n\t#include \n}",sprite_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n}"},Qa={common:{diffuse:{value:new _i(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new mn},alphaMap:{value:null},alphaMapTransform:{value:new mn},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new mn}},envmap:{envMap:{value:null},envMapRotation:{value:new mn},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new mn}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new mn}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new mn},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new mn},normalScale:{value:new cn(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new mn},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new mn}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new mn}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new mn}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new _i(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new _i(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new mn},alphaTest:{value:0},uvTransform:{value:new mn}},sprite:{diffuse:{value:new _i(16777215)},opacity:{value:1},center:{value:new cn(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new mn},alphaMap:{value:null},alphaMapTransform:{value:new mn},alphaTest:{value:0}}},Ja={basic:{uniforms:Gs([Qa.common,Qa.specularmap,Qa.envmap,Qa.aomap,Qa.lightmap,Qa.fog]),vertexShader:Za.meshbasic_vert,fragmentShader:Za.meshbasic_frag},lambert:{uniforms:Gs([Qa.common,Qa.specularmap,Qa.envmap,Qa.aomap,Qa.lightmap,Qa.emissivemap,Qa.bumpmap,Qa.normalmap,Qa.displacementmap,Qa.fog,Qa.lights,{emissive:{value:new _i(0)},envMapIntensity:{value:1}}]),vertexShader:Za.meshlambert_vert,fragmentShader:Za.meshlambert_frag},phong:{uniforms:Gs([Qa.common,Qa.specularmap,Qa.envmap,Qa.aomap,Qa.lightmap,Qa.emissivemap,Qa.bumpmap,Qa.normalmap,Qa.displacementmap,Qa.fog,Qa.lights,{emissive:{value:new _i(0)},specular:{value:new _i(1118481)},shininess:{value:30},envMapIntensity:{value:1}}]),vertexShader:Za.meshphong_vert,fragmentShader:Za.meshphong_frag},standard:{uniforms:Gs([Qa.common,Qa.envmap,Qa.aomap,Qa.lightmap,Qa.emissivemap,Qa.bumpmap,Qa.normalmap,Qa.displacementmap,Qa.roughnessmap,Qa.metalnessmap,Qa.fog,Qa.lights,{emissive:{value:new _i(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Za.meshphysical_vert,fragmentShader:Za.meshphysical_frag},toon:{uniforms:Gs([Qa.common,Qa.aomap,Qa.lightmap,Qa.emissivemap,Qa.bumpmap,Qa.normalmap,Qa.displacementmap,Qa.gradientmap,Qa.fog,Qa.lights,{emissive:{value:new _i(0)}}]),vertexShader:Za.meshtoon_vert,fragmentShader:Za.meshtoon_frag},matcap:{uniforms:Gs([Qa.common,Qa.bumpmap,Qa.normalmap,Qa.displacementmap,Qa.fog,{matcap:{value:null}}]),vertexShader:Za.meshmatcap_vert,fragmentShader:Za.meshmatcap_frag},points:{uniforms:Gs([Qa.points,Qa.fog]),vertexShader:Za.points_vert,fragmentShader:Za.points_frag},dashed:{uniforms:Gs([Qa.common,Qa.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Za.linedashed_vert,fragmentShader:Za.linedashed_frag},depth:{uniforms:Gs([Qa.common,Qa.displacementmap]),vertexShader:Za.depth_vert,fragmentShader:Za.depth_frag},normal:{uniforms:Gs([Qa.common,Qa.bumpmap,Qa.normalmap,Qa.displacementmap,{opacity:{value:1}}]),vertexShader:Za.meshnormal_vert,fragmentShader:Za.meshnormal_frag},sprite:{uniforms:Gs([Qa.sprite,Qa.fog]),vertexShader:Za.sprite_vert,fragmentShader:Za.sprite_frag},background:{uniforms:{uvTransform:{value:new mn},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:Za.background_vert,fragmentShader:Za.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new mn}},vertexShader:Za.backgroundCube_vert,fragmentShader:Za.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Za.cube_vert,fragmentShader:Za.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Za.equirect_vert,fragmentShader:Za.equirect_frag},distance:{uniforms:Gs([Qa.common,Qa.displacementmap,{referencePosition:{value:new dn},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Za.distance_vert,fragmentShader:Za.distance_frag},shadow:{uniforms:Gs([Qa.lights,Qa.fog,{color:{value:new _i(0)},opacity:{value:1}}]),vertexShader:Za.shadow_vert,fragmentShader:Za.shadow_frag}};Ja.physical={uniforms:Gs([Ja.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new mn},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new mn},clearcoatNormalScale:{value:new cn(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new mn},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new mn},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new mn},sheen:{value:0},sheenColor:{value:new _i(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new mn},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new mn},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new mn},transmissionSamplerSize:{value:new cn},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new mn},attenuationDistance:{value:0},attenuationColor:{value:new _i(0)},specularColor:{value:new _i(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new mn},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new mn},anisotropyVector:{value:new cn},anisotropyMap:{value:null},anisotropyMapTransform:{value:new mn}}]),vertexShader:Za.meshphysical_vert,fragmentShader:Za.meshphysical_frag};const eo={r:0,b:0,g:0},to=new $n,no=new Fn;function io(e,t,n,i,r,s){const a=new _i(0);let o,l,u=!0===r?0:1,c=null,h=0,d=null;function p(e){let n=!0===e.isScene?e.background:null;if(n&&n.isTexture){const i=e.backgroundBlurriness>0;n=t.get(n,i)}return n}function f(t,i){t.getRGB(eo,Hs(e)),n.buffers.color.setClear(eo.r,eo.g,eo.b,i,s)}return{getClearColor:function(){return a},setClearColor:function(e,t=1){a.set(e),u=t,f(a,u)},getClearAlpha:function(){return u},setClearAlpha:function(e){u=e,f(a,u)},render:function(t){let i=!1;const r=p(t);null===r?f(a,u):r&&r.isColor&&(f(r,1),i=!0);const o=e.xr.getEnvironmentBlendMode();"additive"===o?n.buffers.color.setClear(0,0,0,1,s):"alpha-blend"===o&&n.buffers.color.setClear(0,0,0,0,s),(e.autoClear||i)&&(n.buffers.depth.setTest(!0),n.buffers.depth.setMask(!0),n.buffers.color.setMask(!0),e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil))},addToRenderList:function(t,n){const r=p(n);r&&(r.isCubeTexture||r.mapping===re)?(void 0===l&&(l=new Wr(new xs(1,1,1),new Ws({name:"BackgroundCubeMaterial",uniforms:Vs(Ja.backgroundCube.uniforms),vertexShader:Ja.backgroundCube.vertexShader,fragmentShader:Ja.backgroundCube.fragmentShader,side:1,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute("normal"),l.geometry.deleteAttribute("uv"),l.onBeforeRender=function(e,t,n){this.matrixWorld.copyPosition(n.matrixWorld)},Object.defineProperty(l.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),i.update(l)),to.copy(n.backgroundRotation),to.x*=-1,to.y*=-1,to.z*=-1,r.isCubeTexture&&!1===r.isRenderTargetTexture&&(to.y*=-1,to.z*=-1),l.material.uniforms.envMap.value=r,l.material.uniforms.flipEnvMap.value=r.isCubeTexture&&!1===r.isRenderTargetTexture?-1:1,l.material.uniforms.backgroundBlurriness.value=n.backgroundBlurriness,l.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,l.material.uniforms.backgroundRotation.value.setFromMatrix4(no.makeRotationFromEuler(to)),l.material.toneMapped=bn.getTransfer(r.colorSpace)!==St,c===r&&h===r.version&&d===e.toneMapping||(l.material.needsUpdate=!0,c=r,h=r.version,d=e.toneMapping),l.layers.enableAll(),t.unshift(l,l.geometry,l.material,0,0,null)):r&&r.isTexture&&(void 0===o&&(o=new Wr(new Os(2,2),new Ws({name:"BackgroundMaterial",uniforms:Vs(Ja.background.uniforms),vertexShader:Ja.background.vertexShader,fragmentShader:Ja.background.fragmentShader,side:0,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),o.geometry.deleteAttribute("normal"),Object.defineProperty(o.material,"map",{get:function(){return this.uniforms.t2D.value}}),i.update(o)),o.material.uniforms.t2D.value=r,o.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,o.material.toneMapped=bn.getTransfer(r.colorSpace)!==St,!0===r.matrixAutoUpdate&&r.updateMatrix(),o.material.uniforms.uvTransform.value.copy(r.matrix),c===r&&h===r.version&&d===e.toneMapping||(o.material.needsUpdate=!0,c=r,h=r.version,d=e.toneMapping),o.layers.enableAll(),t.unshift(o,o.geometry,o.material,0,0,null))},dispose:function(){void 0!==l&&(l.geometry.dispose(),l.material.dispose(),l=void 0),void 0!==o&&(o.geometry.dispose(),o.material.dispose(),o=void 0)}}}function ro(e,t){const n=e.getParameter(e.MAX_VERTEX_ATTRIBS),i={},r=u(null);let s=r,a=!1;function o(t){return e.bindVertexArray(t)}function l(t){return e.deleteVertexArray(t)}function u(e){const t=[],i=[],r=[];for(let e=0;e=0){const n=r[t];let i=a[t];if(void 0===i&&("instanceMatrix"===t&&e.instanceMatrix&&(i=e.instanceMatrix),"instanceColor"===t&&e.instanceColor&&(i=e.instanceColor)),void 0===n)return!0;if(n.attribute!==i)return!0;if(i&&n.data!==i.data)return!0;o++}}return s.attributesNum!==o||s.index!==i}(n,m,l,g),_&&function(e,t,n,i){const r={},a=t.attributes;let o=0;const l=n.getAttributes();for(const t in l){if(l[t].location>=0){let n=a[t];void 0===n&&("instanceMatrix"===t&&e.instanceMatrix&&(n=e.instanceMatrix),"instanceColor"===t&&e.instanceColor&&(n=e.instanceColor));const i={};i.attribute=n,n&&n.data&&(i.data=n.data),r[t]=i,o++}}s.attributes=r,s.attributesNum=o,s.index=i}(n,m,l,g),null!==g&&t.update(g,e.ELEMENT_ARRAY_BUFFER),(_||a)&&(a=!1,function(n,i,r,s){c();const a=s.attributes,o=r.getAttributes(),l=i.defaultAttributeValues;for(const i in o){const r=o[i];if(r.location>=0){let o=a[i];if(void 0===o&&("instanceMatrix"===i&&n.instanceMatrix&&(o=n.instanceMatrix),"instanceColor"===i&&n.instanceColor&&(o=n.instanceColor)),void 0!==o){const i=o.normalized,a=o.itemSize,l=t.get(o);if(void 0===l)continue;const u=l.buffer,c=l.type,p=l.bytesPerElement,m=c===e.INT||c===e.UNSIGNED_INT||o.gpuType===ve;if(o.isInterleavedBufferAttribute){const t=o.data,l=t.stride,g=o.offset;if(t.isInstancedInterleavedBuffer){for(let e=0;e0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0)return"highp";t="mediump"}return"mediump"===t&&e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.MEDIUM_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let a=void 0!==n.precision?n.precision:"highp";const o=s(a);o!==a&&(Xt("WebGLRenderer:",a,"not supported, using",o,"instead."),a=o);return{isWebGL2:!0,getMaxAnisotropy:function(){if(void 0!==r)return r;if(!0===t.has("EXT_texture_filter_anisotropic")){const n=t.get("EXT_texture_filter_anisotropic");r=e.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else r=0;return r},getMaxPrecision:s,textureFormatReadable:function(t){return t===Ce||i.convert(t)===e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)},textureTypeReadable:function(n){const r=n===xe&&(t.has("EXT_color_buffer_half_float")||t.has("EXT_color_buffer_float"));return!(n!==fe&&i.convert(n)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)&&n!==be&&!r)},precision:a,logarithmicDepthBuffer:!0===n.logarithmicDepthBuffer,reversedDepthBuffer:!0===n.reversedDepthBuffer&&t.has("EXT_clip_control"),maxTextures:e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),maxVertexTextures:e.getParameter(e.MAX_VERTEX_TEXTURE_IMAGE_UNITS),maxTextureSize:e.getParameter(e.MAX_TEXTURE_SIZE),maxCubemapSize:e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),maxAttributes:e.getParameter(e.MAX_VERTEX_ATTRIBS),maxVertexUniforms:e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),maxVaryings:e.getParameter(e.MAX_VARYING_VECTORS),maxFragmentUniforms:e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),maxSamples:e.getParameter(e.MAX_SAMPLES),samples:e.getParameter(e.SAMPLES)}}function oo(e){const t=this;let n=null,i=0,r=!1,s=!1;const a=new Qr,o=new mn,l={value:null,needsUpdate:!1};function u(e,n,i,r){const s=null!==e?e.length:0;let u=null;if(0!==s){if(u=l.value,!0!==r||null===u){const t=i+4*s,r=n.matrixWorldInverse;o.getNormalMatrix(r),(null===u||u.length0);t.numPlanes=i,t.numIntersection=0}();else{const e=s?0:i,t=4*e;let r=f.clippingState||null;l.value=r,r=u(h,o,t,c);for(let e=0;e!==t;++e)r[e]=n[e];f.clippingState=r,this.numIntersection=d?this.numPlanes:0,this.numPlanes+=e}}}const lo=[.125,.215,.35,.446,.526,.582],uo=20,co=new Ra,ho=new _i;let po=null,fo=0,mo=0,go=!1;const _o=new dn;let vo=class{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._backgroundBox=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._blurMaterial=null,this._ggxMaterial=null}fromScene(e,t=0,n=.1,i=100,r={}){const{size:s=256,position:a=_o}=r;po=this._renderer.getRenderTarget(),fo=this._renderer.getActiveCubeFace(),mo=this._renderer.getActiveMipmapLevel(),go=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(s);const o=this._allocateTargets();return o.depthBuffer=!0,this._sceneToCubeUV(e,n,i,o,a),t>0&&this._blur(o,0,0,t),this._applyPMREM(o),this._cleanup(o),o}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=To(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=xo(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),null!==this._cubemapMaterial&&this._cubemapMaterial.dispose(),null!==this._equirectMaterial&&this._equirectMaterial.dispose(),null!==this._backgroundBox&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){null!==this._blurMaterial&&this._blurMaterial.dispose(),null!==this._ggxMaterial&&this._ggxMaterial.dispose(),null!==this._pingPongRenderTarget&&this._pingPongRenderTarget.dispose();for(let e=0;ee-4?o=lo[a-e+4-1]:0===a&&(o=0),n.push(o);const l=1/(s-2),u=-l,c=1+l,h=[u,u,c,u,c,c,u,u,c,c,u,c],d=6,p=6,f=3,m=2,g=1,_=new Float32Array(f*p*d),v=new Float32Array(m*p*d),y=new Float32Array(g*p*d);for(let e=0;e2?0:-1,i=[t,n,0,t+2/3,n,0,t+2/3,n+1,0,t,n,0,t+2/3,n+1,0,t,n+1,0];_.set(i,f*p*e),v.set(h,m*p*e);const r=[e,e,e,e,e,e];y.set(r,g*p*e)}const b=new vr;b.setAttribute("position",new nr(_,f)),b.setAttribute("uv",new nr(v,m)),b.setAttribute("faceIndex",new nr(y,g)),i.push(new Wr(b,null)),r>4&&r--}return{lodMeshes:i,sizeLods:t,sigmas:n}}(i)),this._blurMaterial=function(e,t,n){const i=new Float32Array(uo),r=new dn(0,1,0),s=new Ws({name:"SphericalGaussianBlur",defines:{n:uo,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:i},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:r}},vertexShader:So(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\t\t\tuniform int samples;\n\t\t\tuniform float weights[ n ];\n\t\t\tuniform bool latitudinal;\n\t\t\tuniform float dTheta;\n\t\t\tuniform float mipInt;\n\t\t\tuniform vec3 poleAxis;\n\n\t\t\t#define ENVMAP_TYPE_CUBE_UV\n\t\t\t#include \n\n\t\t\tvec3 getSample( float theta, vec3 axis ) {\n\n\t\t\t\tfloat cosTheta = cos( theta );\n\t\t\t\t// Rodrigues' axis-angle rotation\n\t\t\t\tvec3 sampleDirection = vOutputDirection * cosTheta\n\t\t\t\t\t+ cross( axis, vOutputDirection ) * sin( theta )\n\t\t\t\t\t+ axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );\n\n\t\t\t\treturn bilinearCubeUV( envMap, sampleDirection, mipInt );\n\n\t\t\t}\n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );\n\n\t\t\t\tif ( all( equal( axis, vec3( 0.0 ) ) ) ) {\n\n\t\t\t\t\taxis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );\n\n\t\t\t\t}\n\n\t\t\t\taxis = normalize( axis );\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t\t\t\tgl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );\n\n\t\t\t\tfor ( int i = 1; i < n; i++ ) {\n\n\t\t\t\t\tif ( i >= samples ) {\n\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tfloat theta = dTheta * float( i );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( theta, axis );\n\n\t\t\t\t}\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1});return s}(i,e,t),this._ggxMaterial=function(e,t,n){const i=new Ws({name:"PMREMGGXConvolution",defines:{GGX_SAMPLES:256,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:So(),fragmentShader:'\n\n\t\t\tprecision highp float;\n\t\t\tprecision highp int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\t\t\tuniform float roughness;\n\t\t\tuniform float mipInt;\n\n\t\t\t#define ENVMAP_TYPE_CUBE_UV\n\t\t\t#include \n\n\t\t\t#define PI 3.14159265359\n\n\t\t\t// Van der Corput radical inverse\n\t\t\tfloat radicalInverse_VdC(uint bits) {\n\t\t\t\tbits = (bits << 16u) | (bits >> 16u);\n\t\t\t\tbits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);\n\t\t\t\tbits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);\n\t\t\t\tbits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);\n\t\t\t\tbits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);\n\t\t\t\treturn float(bits) * 2.3283064365386963e-10; // / 0x100000000\n\t\t\t}\n\n\t\t\t// Hammersley sequence\n\t\t\tvec2 hammersley(uint i, uint N) {\n\t\t\t\treturn vec2(float(i) / float(N), radicalInverse_VdC(i));\n\t\t\t}\n\n\t\t\t// GGX VNDF importance sampling (Eric Heitz 2018)\n\t\t\t// "Sampling the GGX Distribution of Visible Normals"\n\t\t\t// https://jcgt.org/published/0007/04/01/\n\t\t\tvec3 importanceSampleGGX_VNDF(vec2 Xi, vec3 V, float roughness) {\n\t\t\t\tfloat alpha = roughness * roughness;\n\n\t\t\t\t// Section 4.1: Orthonormal basis\n\t\t\t\tvec3 T1 = vec3(1.0, 0.0, 0.0);\n\t\t\t\tvec3 T2 = cross(V, T1);\n\n\t\t\t\t// Section 4.2: Parameterization of projected area\n\t\t\t\tfloat r = sqrt(Xi.x);\n\t\t\t\tfloat phi = 2.0 * PI * Xi.y;\n\t\t\t\tfloat t1 = r * cos(phi);\n\t\t\t\tfloat t2 = r * sin(phi);\n\t\t\t\tfloat s = 0.5 * (1.0 + V.z);\n\t\t\t\tt2 = (1.0 - s) * sqrt(1.0 - t1 * t1) + s * t2;\n\n\t\t\t\t// Section 4.3: Reprojection onto hemisphere\n\t\t\t\tvec3 Nh = t1 * T1 + t2 * T2 + sqrt(max(0.0, 1.0 - t1 * t1 - t2 * t2)) * V;\n\n\t\t\t\t// Section 3.4: Transform back to ellipsoid configuration\n\t\t\t\treturn normalize(vec3(alpha * Nh.x, alpha * Nh.y, max(0.0, Nh.z)));\n\t\t\t}\n\n\t\t\tvoid main() {\n\t\t\t\tvec3 N = normalize(vOutputDirection);\n\t\t\t\tvec3 V = N; // Assume view direction equals normal for pre-filtering\n\n\t\t\t\tvec3 prefilteredColor = vec3(0.0);\n\t\t\t\tfloat totalWeight = 0.0;\n\n\t\t\t\t// For very low roughness, just sample the environment directly\n\t\t\t\tif (roughness < 0.001) {\n\t\t\t\t\tgl_FragColor = vec4(bilinearCubeUV(envMap, N, mipInt), 1.0);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// Tangent space basis for VNDF sampling\n\t\t\t\tvec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);\n\t\t\t\tvec3 tangent = normalize(cross(up, N));\n\t\t\t\tvec3 bitangent = cross(N, tangent);\n\n\t\t\t\tfor(uint i = 0u; i < uint(GGX_SAMPLES); i++) {\n\t\t\t\t\tvec2 Xi = hammersley(i, uint(GGX_SAMPLES));\n\n\t\t\t\t\t// For PMREM, V = N, so in tangent space V is always (0, 0, 1)\n\t\t\t\t\tvec3 H_tangent = importanceSampleGGX_VNDF(Xi, vec3(0.0, 0.0, 1.0), roughness);\n\n\t\t\t\t\t// Transform H back to world space\n\t\t\t\t\tvec3 H = normalize(tangent * H_tangent.x + bitangent * H_tangent.y + N * H_tangent.z);\n\t\t\t\t\tvec3 L = normalize(2.0 * dot(V, H) * H - V);\n\n\t\t\t\t\tfloat NdotL = max(dot(N, L), 0.0);\n\n\t\t\t\t\tif(NdotL > 0.0) {\n\t\t\t\t\t\t// Sample environment at fixed mip level\n\t\t\t\t\t\t// VNDF importance sampling handles the distribution filtering\n\t\t\t\t\t\tvec3 sampleColor = bilinearCubeUV(envMap, L, mipInt);\n\n\t\t\t\t\t\t// Weight by NdotL for the split-sum approximation\n\t\t\t\t\t\t// VNDF PDF naturally accounts for the visible microfacet distribution\n\t\t\t\t\t\tprefilteredColor += sampleColor * NdotL;\n\t\t\t\t\t\ttotalWeight += NdotL;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (totalWeight > 0.0) {\n\t\t\t\t\tprefilteredColor = prefilteredColor / totalWeight;\n\t\t\t\t}\n\n\t\t\t\tgl_FragColor = vec4(prefilteredColor, 1.0);\n\t\t\t}\n\t\t',blending:0,depthTest:!1,depthWrite:!1});return i}(i,e,t)}return i}_compileMaterial(e){const t=new Wr(new vr,e);this._renderer.compile(t,co)}_sceneToCubeUV(e,t,n,i,r){const s=new Sa(90,1,t,n),a=[1,-1,1,1,1,1],o=[1,1,1,-1,-1,-1],l=this._renderer,u=l.autoClear,c=l.toneMapping;l.getClearColor(ho),l.toneMapping=0,l.autoClear=!1;l.state.buffers.depth.getReversed()&&(l.setRenderTarget(i),l.clearDepth(),l.setRenderTarget(null)),null===this._backgroundBox&&(this._backgroundBox=new Wr(new xs,new Dr({name:"PMREM.Background",side:1,depthWrite:!1,depthTest:!1})));const h=this._backgroundBox,d=h.material;let p=!1;const f=e.background;f?f.isColor&&(d.color.copy(f),e.background=null,p=!0):(d.color.copy(ho),p=!0);for(let t=0;t<6;t++){const n=t%3;0===n?(s.up.set(0,a[t],0),s.position.set(r.x,r.y,r.z),s.lookAt(r.x+o[t],r.y,r.z)):1===n?(s.up.set(0,0,a[t]),s.position.set(r.x,r.y,r.z),s.lookAt(r.x,r.y+o[t],r.z)):(s.up.set(0,a[t],0),s.position.set(r.x,r.y,r.z),s.lookAt(r.x,r.y,r.z+o[t]));const u=this._cubeSize;bo(i,n*u,t>2?u:0,u,u),l.setRenderTarget(i),p&&l.render(h,s),l.render(e,s)}l.toneMapping=c,l.autoClear=u,e.background=f}_textureToCubeUV(e,t){const n=this._renderer,i=e.mapping===ee||e.mapping===te;i?(null===this._cubemapMaterial&&(this._cubemapMaterial=To()),this._cubemapMaterial.uniforms.flipEnvMap.value=!1===e.isRenderTargetTexture?-1:1):null===this._equirectMaterial&&(this._equirectMaterial=xo());const r=i?this._cubemapMaterial:this._equirectMaterial,s=this._lodMeshes[0];s.material=r;r.uniforms.envMap.value=e;const a=this._cubeSize;bo(t,0,0,3*a,2*a),n.setRenderTarget(t),n.render(s,co)}_applyPMREM(e){const t=this._renderer,n=t.autoClear;t.autoClear=!1;const i=this._lodMeshes.length;for(let t=1;th-4?n-h+4:0),f=4*(this._cubeSize-d);o.envMap.value=e.texture,o.roughness.value=c,o.mipInt.value=h-t,bo(r,p,f,3*d,2*d),i.setRenderTarget(r),i.render(a,co),o.envMap.value=r.texture,o.roughness.value=0,o.mipInt.value=h-n,bo(e,p,f,3*d,2*d),i.setRenderTarget(e),i.render(a,co)}_blur(e,t,n,i,r){const s=this._pingPongRenderTarget;this._halfBlur(e,s,t,n,i,"latitudinal",r),this._halfBlur(s,e,n,n,i,"longitudinal",r)}_halfBlur(e,t,n,i,r,s,a){const o=this._renderer,l=this._blurMaterial;"latitudinal"!==s&&"longitudinal"!==s&&qt("blur direction must be either latitudinal or longitudinal!");const u=this._lodMeshes[i];u.material=l;const c=l.uniforms,h=this._sizeLods[n]-1,d=isFinite(r)?Math.PI/(2*h):2*Math.PI/39,p=r/d,f=isFinite(r)?1+Math.floor(3*p):uo;f>uo&&Xt(`sigmaRadians, ${r}, is too large and will clip, as it requested ${f} samples when the maximum is set to 20`);const m=[];let g=0;for(let e=0;e_-4?i-_+4:0),4*(this._cubeSize-v),3*v,2*v),o.setRenderTarget(t),o.render(u,co)}};function yo(e,t,n){const i=new Dn(e,t,n);return i.texture.mapping=re,i.texture.name="PMREM.cubeUv",i.scissorTest=!0,i}function bo(e,t,n,i,r){e.viewport.set(t,n,i,r),e.scissor.set(t,n,i,r)}function xo(){return new Ws({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:So(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\n\t\t\t#include \n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 outputDirection = normalize( vOutputDirection );\n\t\t\t\tvec2 uv = equirectUv( outputDirection );\n\n\t\t\t\tgl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1})}function To(){return new Ws({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:So(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tuniform float flipEnvMap;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform samplerCube envMap;\n\n\t\t\tvoid main() {\n\n\t\t\t\tgl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1})}function So(){return"\n\n\t\tprecision mediump float;\n\t\tprecision mediump int;\n\n\t\tattribute float faceIndex;\n\n\t\tvarying vec3 vOutputDirection;\n\n\t\t// RH coordinate system; PMREM face-indexing convention\n\t\tvec3 getDirection( vec2 uv, float face ) {\n\n\t\t\tuv = 2.0 * uv - 1.0;\n\n\t\t\tvec3 direction = vec3( uv, 1.0 );\n\n\t\t\tif ( face == 0.0 ) {\n\n\t\t\t\tdirection = direction.zyx; // ( 1, v, u ) pos x\n\n\t\t\t} else if ( face == 1.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xz *= -1.0; // ( -u, 1, -v ) pos y\n\n\t\t\t} else if ( face == 2.0 ) {\n\n\t\t\t\tdirection.x *= -1.0; // ( -u, v, 1 ) pos z\n\n\t\t\t} else if ( face == 3.0 ) {\n\n\t\t\t\tdirection = direction.zyx;\n\t\t\t\tdirection.xz *= -1.0; // ( -1, v, -u ) neg x\n\n\t\t\t} else if ( face == 4.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xy *= -1.0; // ( -u, -1, v ) neg y\n\n\t\t\t} else if ( face == 5.0 ) {\n\n\t\t\t\tdirection.z *= -1.0; // ( u, v, -1 ) neg z\n\n\t\t\t}\n\n\t\t\treturn direction;\n\n\t\t}\n\n\t\tvoid main() {\n\n\t\t\tvOutputDirection = getDirection( uv, faceIndex );\n\t\t\tgl_Position = vec4( position, 1.0 );\n\n\t\t}\n\t"}class Mo extends Dn{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const n={width:e,height:e,depth:1},i=[n,n,n,n,n,n];this.texture=new _s(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;const n={uniforms:{tEquirect:{value:null}},vertexShader:"\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\tvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\t\t\t\t\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n\t\t\t\t}\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t\t\t\t\t#include \n\t\t\t\t\t#include \n\n\t\t\t\t}\n\t\t\t",fragmentShader:"\n\n\t\t\t\tuniform sampler2D tEquirect;\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\t#include \n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvec3 direction = normalize( vWorldDirection );\n\n\t\t\t\t\tvec2 sampleUV = equirectUv( direction );\n\n\t\t\t\t\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n\t\t\t\t}\n\t\t\t"},i=new xs(5,5,5),r=new Ws({name:"CubemapFromEquirect",uniforms:Vs(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:1,blending:0});r.uniforms.tEquirect.value=t;const s=new Wr(i,r),a=t.minFilter;t.minFilter===pe&&(t.minFilter=he);return new Fa(1,10,this).update(e,s),t.minFilter=a,s.geometry.dispose(),s.material.dispose(),this}clear(e,t=!0,n=!0,i=!0){const r=e.getRenderTarget();for(let r=0;r<6;r++)e.setRenderTarget(this,r),e.clear(t,n,i);e.setRenderTarget(r)}}function Eo(e){let t=new WeakMap,n=new WeakMap,i=null;function r(e,t){return t===ne?e.mapping=ee:t===ie&&(e.mapping=te),e}function s(e){const n=e.target;n.removeEventListener("dispose",s);const i=t.get(n);void 0!==i&&(t.delete(n),i.dispose())}function a(e){const t=e.target;t.removeEventListener("dispose",a);const i=n.get(t);void 0!==i&&(n.delete(t),i.dispose())}return{get:function(o,l=!1){return null==o?null:l?function(t){if(t&&t.isTexture){const r=t.mapping,s=r===ne||r===ie,o=r===ee||r===te;if(s||o){let r=n.get(t);const l=void 0!==r?r.texture.pmremVersion:0;if(t.isRenderTargetTexture&&t.pmremVersion!==l)return null===i&&(i=new vo(e)),r=s?i.fromEquirectangular(t,r):i.fromCubemap(t,r),r.texture.pmremVersion=t.pmremVersion,n.set(t,r),r.texture;if(void 0!==r)return r.texture;{const l=t.image;return s&&l&&l.height>0||o&&l&&function(e){let t=0;const n=6;for(let i=0;i0){const a=new Mo(i.height);return a.fromEquirectangularTexture(e,n),t.set(n,a),n.addEventListener("dispose",s),r(a.texture,n.mapping)}return null}}}return n}(o)},dispose:function(){t=new WeakMap,n=new WeakMap,null!==i&&(i.dispose(),i=null)}}}function wo(e){const t={};function n(n){if(void 0!==t[n])return t[n];const i=e.getExtension(n);return t[n]=i,i}return{has:function(e){return null!==n(e)},init:function(){n("EXT_color_buffer_float"),n("WEBGL_clip_cull_distance"),n("OES_texture_float_linear"),n("EXT_color_buffer_half_float"),n("WEBGL_multisampled_render_to_texture"),n("WEBGL_render_shared_exponent")},get:function(e){const t=n(e);return null===t&&Yt("WebGLRenderer: "+e+" extension not supported."),t}}}function Ao(e,t,n,i){const r={},s=new WeakMap;function a(e){const o=e.target;null!==o.index&&t.remove(o.index);for(const e in o.attributes)t.remove(o.attributes[e]);o.removeEventListener("dispose",a),delete r[o.id];const l=s.get(o);l&&(t.remove(l),s.delete(o)),i.releaseStatesOfGeometry(o),!0===o.isInstancedBufferGeometry&&delete o._maxInstanceCount,n.memory.geometries--}function o(e){const n=[],i=e.index,r=e.attributes.position;let a=0;if(void 0===r)return;if(null!==i){const e=i.array;a=i.version;for(let t=0,i=e.length;t=65535?rr:ir)(n,1);o.version=a;const l=s.get(e);l&&t.remove(l),s.set(e,o)}return{get:function(e,t){return!0===r[t.id]||(t.addEventListener("dispose",a),r[t.id]=!0,n.memory.geometries++),t},update:function(n){const i=n.attributes;for(const n in i)t.update(i[n],e.ARRAY_BUFFER)},getWireframeAttribute:function(e){const t=s.get(e);if(t){const n=e.index;null!==n&&t.versiont.maxTextureSize&&(b=Math.ceil(y/t.maxTextureSize),y=t.maxTextureSize);const x=new Float32Array(y*b*4*c),T=new In(x,y,b,c);T.type=be,T.needsUpdate=!0;const S=4*v;for(let E=0;E\n\t\t\t#include \n\n\t\t\tvoid main() {\n\t\t\t\tgl_FragColor = texture2D( tDiffuse, vUv );\n\n\t\t\t\t#ifdef LINEAR_TONE_MAPPING\n\t\t\t\t\tgl_FragColor.rgb = LinearToneMapping( gl_FragColor.rgb );\n\t\t\t\t#elif defined( REINHARD_TONE_MAPPING )\n\t\t\t\t\tgl_FragColor.rgb = ReinhardToneMapping( gl_FragColor.rgb );\n\t\t\t\t#elif defined( CINEON_TONE_MAPPING )\n\t\t\t\t\tgl_FragColor.rgb = CineonToneMapping( gl_FragColor.rgb );\n\t\t\t\t#elif defined( ACES_FILMIC_TONE_MAPPING )\n\t\t\t\t\tgl_FragColor.rgb = ACESFilmicToneMapping( gl_FragColor.rgb );\n\t\t\t\t#elif defined( AGX_TONE_MAPPING )\n\t\t\t\t\tgl_FragColor.rgb = AgXToneMapping( gl_FragColor.rgb );\n\t\t\t\t#elif defined( NEUTRAL_TONE_MAPPING )\n\t\t\t\t\tgl_FragColor.rgb = NeutralToneMapping( gl_FragColor.rgb );\n\t\t\t\t#elif defined( CUSTOM_TONE_MAPPING )\n\t\t\t\t\tgl_FragColor.rgb = CustomToneMapping( gl_FragColor.rgb );\n\t\t\t\t#endif\n\n\t\t\t\t#ifdef SRGB_TRANSFER\n\t\t\t\t\tgl_FragColor = sRGBTransferOETF( gl_FragColor );\n\t\t\t\t#endif\n\t\t\t}",depthTest:!1,depthWrite:!1}),u=new Wr(o,l),c=new Ra(-1,1,1,-1,0,1);let h,d=null,p=null,f=!1,m=null,g=[],_=!1;this.setSize=function(e,t){s.setSize(e,t),a.setSize(e,t);for(let n=0;n0&&!0===g[0].isRenderPass;const t=s.width,n=s.height;for(let e=0;e0)return e;const r=t*n;let s=ko[r];if(void 0===s&&(s=new Float32Array(r),ko[r]=s),0!==t){i.toArray(s,0);for(let i=1,r=0;i!==t;++i)r+=n,e[i].toArray(s,r)}return s}function Wo(e,t){if(e.length!==t.length)return!1;for(let n=0,i=e.length;n0&&(this.seq=i.concat(r))}setValue(e,t,n,i){const r=this.map[t];void 0!==r&&r.setValue(e,n,i)}setOptional(e,t,n){const i=t[n];void 0!==i&&this.setValue(e,n,i)}static upload(e,t,n,i){for(let r=0,s=t.length;r!==s;++r){const s=t[r],a=n[s.id];!1!==a.needsUpdate&&s.setValue(e,a.value,i)}}static seqWithValue(e,t){const n=[];for(let i=0,r=e.length;i!==r;++i){const r=e[i];r.id in t&&n.push(r)}return n}}function kl(e,t,n){const i=e.createShader(t);return e.shaderSource(i,n),e.compileShader(i),i}let zl=0;const Vl=new mn;function Gl(e,t,n){const i=e.getShaderParameter(t,e.COMPILE_STATUS),r=(e.getShaderInfoLog(t)||"").trim();if(i&&""===r)return"";const s=/ERROR: 0:(\d+)/.exec(r);if(s){const i=parseInt(s[1]);return n.toUpperCase()+"\n\n"+r+"\n\n"+function(e,t){const n=e.split("\n"),i=[],r=Math.max(t-6,0),s=Math.min(t+6,n.length);for(let e=r;e":" "} ${r}: ${n[e]}`)}return i.join("\n")}(e.getShaderSource(t),i)}return r}function Hl(e,t){const n=function(e){bn._getMatrix(Vl,bn.workingColorSpace,e);const t=`mat3( ${Vl.elements.map(e=>e.toFixed(4))} )`;switch(bn.getTransfer(e)){case Tt:return[t,"LinearTransferOETF"];case St:return[t,"sRGBTransferOETF"];default:return Xt("WebGLProgram: Unsupported color space: ",e),[t,"LinearTransferOETF"]}}(t);return[`vec4 ${e}( vec4 value ) {`,`\treturn ${n[1]}( vec4( value.rgb * ${n[0]}, value.a ) );`,"}"].join("\n")}const jl={[X]:"Linear",[q]:"Reinhard",[Y]:"Cineon",[K]:"ACESFilmic",[Q]:"AgX",[J]:"Neutral",[Z]:"Custom"};function Wl(e,t){const n=jl[t];return void 0===n?(Xt("WebGLProgram: Unsupported toneMapping:",t),"vec3 "+e+"( vec3 color ) { return LinearToneMapping( color ); }"):"vec3 "+e+"( vec3 color ) { return "+n+"ToneMapping( color ); }"}const $l=new dn;function Xl(){bn.getLuminanceCoefficients($l);return["float luminance( const in vec3 rgb ) {",`\tconst vec3 weights = vec3( ${$l.x.toFixed(4)}, ${$l.y.toFixed(4)}, ${$l.z.toFixed(4)} );`,"\treturn dot( weights, rgb );","}"].join("\n")}function ql(e){return""!==e}function Yl(e,t){const n=t.numSpotLightShadows+t.numSpotLightMaps-t.numSpotLightShadowsWithMaps;return e.replace(/NUM_DIR_LIGHTS/g,t.numDirLights).replace(/NUM_SPOT_LIGHTS/g,t.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,t.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,n).replace(/NUM_RECT_AREA_LIGHTS/g,t.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,t.numPointLights).replace(/NUM_HEMI_LIGHTS/g,t.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g,t.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,t.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,t.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,t.numPointLightShadows)}function Kl(e,t){return e.replace(/NUM_CLIPPING_PLANES/g,t.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,t.numClippingPlanes-t.numClipIntersection)}const Zl=/^[ \t]*#include +<([\w\d./]+)>/gm;function Ql(e){return e.replace(Zl,eu)}const Jl=new Map;function eu(e,t){let n=Za[t];if(void 0===n){const e=Jl.get(t);if(void 0===e)throw new Error("Can not resolve #include <"+t+">");n=Za[e],Xt('WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',t,e)}return Ql(n)}const tu=/#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 nu(e){return e.replace(tu,iu)}function iu(e,t,n,i){let r="";for(let e=parseInt(t);e0&&(g+="\n"),_=["#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,f].filter(ql).join("\n"),_.length>0&&(_+="\n")):(g=[ru(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,f,n.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",n.batching?"#define USE_BATCHING":"",n.batchingColor?"#define USE_BATCHING_COLOR":"",n.instancing?"#define USE_INSTANCING":"",n.instancingColor?"#define USE_INSTANCING_COLOR":"",n.instancingMorph?"#define USE_INSTANCING_MORPH":"",n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.map?"#define USE_MAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+c:"",n.lightMap?"#define USE_LIGHTMAP":"",n.aoMap?"#define USE_AOMAP":"",n.bumpMap?"#define USE_BUMPMAP":"",n.normalMap?"#define USE_NORMALMAP":"",n.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",n.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",n.displacementMap?"#define USE_DISPLACEMENTMAP":"",n.emissiveMap?"#define USE_EMISSIVEMAP":"",n.anisotropy?"#define USE_ANISOTROPY":"",n.anisotropyMap?"#define USE_ANISOTROPYMAP":"",n.clearcoatMap?"#define USE_CLEARCOATMAP":"",n.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",n.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",n.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",n.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",n.specularMap?"#define USE_SPECULARMAP":"",n.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",n.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",n.roughnessMap?"#define USE_ROUGHNESSMAP":"",n.metalnessMap?"#define USE_METALNESSMAP":"",n.alphaMap?"#define USE_ALPHAMAP":"",n.alphaHash?"#define USE_ALPHAHASH":"",n.transmission?"#define USE_TRANSMISSION":"",n.transmissionMap?"#define USE_TRANSMISSIONMAP":"",n.thicknessMap?"#define USE_THICKNESSMAP":"",n.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",n.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",n.mapUv?"#define MAP_UV "+n.mapUv:"",n.alphaMapUv?"#define ALPHAMAP_UV "+n.alphaMapUv:"",n.lightMapUv?"#define LIGHTMAP_UV "+n.lightMapUv:"",n.aoMapUv?"#define AOMAP_UV "+n.aoMapUv:"",n.emissiveMapUv?"#define EMISSIVEMAP_UV "+n.emissiveMapUv:"",n.bumpMapUv?"#define BUMPMAP_UV "+n.bumpMapUv:"",n.normalMapUv?"#define NORMALMAP_UV "+n.normalMapUv:"",n.displacementMapUv?"#define DISPLACEMENTMAP_UV "+n.displacementMapUv:"",n.metalnessMapUv?"#define METALNESSMAP_UV "+n.metalnessMapUv:"",n.roughnessMapUv?"#define ROUGHNESSMAP_UV "+n.roughnessMapUv:"",n.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+n.anisotropyMapUv:"",n.clearcoatMapUv?"#define CLEARCOATMAP_UV "+n.clearcoatMapUv:"",n.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+n.clearcoatNormalMapUv:"",n.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+n.clearcoatRoughnessMapUv:"",n.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+n.iridescenceMapUv:"",n.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+n.iridescenceThicknessMapUv:"",n.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+n.sheenColorMapUv:"",n.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+n.sheenRoughnessMapUv:"",n.specularMapUv?"#define SPECULARMAP_UV "+n.specularMapUv:"",n.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+n.specularColorMapUv:"",n.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+n.specularIntensityMapUv:"",n.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+n.transmissionMapUv:"",n.thicknessMapUv?"#define THICKNESSMAP_UV "+n.thicknessMapUv:"",n.vertexTangents&&!1===n.flatShading?"#define USE_TANGENT":"",n.vertexColors?"#define USE_COLOR":"",n.vertexAlphas?"#define USE_COLOR_ALPHA":"",n.vertexUv1s?"#define USE_UV1":"",n.vertexUv2s?"#define USE_UV2":"",n.vertexUv3s?"#define USE_UV3":"",n.pointsUvs?"#define USE_POINTS_UV":"",n.flatShading?"#define FLAT_SHADED":"",n.skinning?"#define USE_SKINNING":"",n.morphTargets?"#define USE_MORPHTARGETS":"",n.morphNormals&&!1===n.flatShading?"#define USE_MORPHNORMALS":"",n.morphColors?"#define USE_MORPHCOLORS":"",n.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+n.morphTextureStride:"",n.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+n.morphTargetsCount:"",n.doubleSided?"#define DOUBLE_SIDED":"",n.flipSided?"#define FLIP_SIDED":"",n.shadowMapEnabled?"#define USE_SHADOWMAP":"",n.shadowMapEnabled?"#define "+l:"",n.sizeAttenuation?"#define USE_SIZEATTENUATION":"",n.numLightProbes>0?"#define USE_LIGHT_PROBES":"",n.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",n.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING","\tattribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR","\tattribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH","\tuniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1","\tattribute vec2 uv1;","#endif","#ifdef USE_UV2","\tattribute vec2 uv2;","#endif","#ifdef USE_UV3","\tattribute vec2 uv3;","#endif","#ifdef USE_TANGENT","\tattribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )","\tattribute vec4 color;","#elif defined( USE_COLOR )","\tattribute vec3 color;","#endif","#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif","\n"].filter(ql).join("\n"),_=[ru(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,f,n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",n.map?"#define USE_MAP":"",n.matcap?"#define USE_MATCAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+u:"",n.envMap?"#define "+c:"",n.envMap?"#define "+h:"",d?"#define CUBEUV_TEXEL_WIDTH "+d.texelWidth:"",d?"#define CUBEUV_TEXEL_HEIGHT "+d.texelHeight:"",d?"#define CUBEUV_MAX_MIP "+d.maxMip+".0":"",n.lightMap?"#define USE_LIGHTMAP":"",n.aoMap?"#define USE_AOMAP":"",n.bumpMap?"#define USE_BUMPMAP":"",n.normalMap?"#define USE_NORMALMAP":"",n.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",n.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",n.emissiveMap?"#define USE_EMISSIVEMAP":"",n.anisotropy?"#define USE_ANISOTROPY":"",n.anisotropyMap?"#define USE_ANISOTROPYMAP":"",n.clearcoat?"#define USE_CLEARCOAT":"",n.clearcoatMap?"#define USE_CLEARCOATMAP":"",n.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",n.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",n.dispersion?"#define USE_DISPERSION":"",n.iridescence?"#define USE_IRIDESCENCE":"",n.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",n.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",n.specularMap?"#define USE_SPECULARMAP":"",n.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",n.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",n.roughnessMap?"#define USE_ROUGHNESSMAP":"",n.metalnessMap?"#define USE_METALNESSMAP":"",n.alphaMap?"#define USE_ALPHAMAP":"",n.alphaTest?"#define USE_ALPHATEST":"",n.alphaHash?"#define USE_ALPHAHASH":"",n.sheen?"#define USE_SHEEN":"",n.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",n.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",n.transmission?"#define USE_TRANSMISSION":"",n.transmissionMap?"#define USE_TRANSMISSIONMAP":"",n.thicknessMap?"#define USE_THICKNESSMAP":"",n.vertexTangents&&!1===n.flatShading?"#define USE_TANGENT":"",n.vertexColors||n.instancingColor?"#define USE_COLOR":"",n.vertexAlphas||n.batchingColor?"#define USE_COLOR_ALPHA":"",n.vertexUv1s?"#define USE_UV1":"",n.vertexUv2s?"#define USE_UV2":"",n.vertexUv3s?"#define USE_UV3":"",n.pointsUvs?"#define USE_POINTS_UV":"",n.gradientMap?"#define USE_GRADIENTMAP":"",n.flatShading?"#define FLAT_SHADED":"",n.doubleSided?"#define DOUBLE_SIDED":"",n.flipSided?"#define FLIP_SIDED":"",n.shadowMapEnabled?"#define USE_SHADOWMAP":"",n.shadowMapEnabled?"#define "+l:"",n.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",n.numLightProbes>0?"#define USE_LIGHT_PROBES":"",n.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",n.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",n.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",n.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",0!==n.toneMapping?"#define TONE_MAPPING":"",0!==n.toneMapping?Za.tonemapping_pars_fragment:"",0!==n.toneMapping?Wl("toneMapping",n.toneMapping):"",n.dithering?"#define DITHERING":"",n.opaque?"#define OPAQUE":"",Za.colorspace_pars_fragment,Hl("linearToOutputTexel",n.outputColorSpace),Xl(),n.useDepthPacking?"#define DEPTH_PACKING "+n.depthPacking:"","\n"].filter(ql).join("\n")),a=Ql(a),a=Yl(a,n),a=Kl(a,n),o=Ql(o),o=Yl(o,n),o=Kl(o,n),a=nu(a),o=nu(o),!0!==n.isRawShaderMaterial&&(v="#version 300 es\n",g=[p,"#define attribute in","#define varying out","#define texture2D texture"].join("\n")+"\n"+g,_=["#define varying in",n.glslVersion===Ut?"":"layout(location = 0) out highp vec4 pc_fragColor;",n.glslVersion===Ut?"":"#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("\n")+"\n"+_);const y=v+g+a,b=v+_+o,x=kl(r,r.VERTEX_SHADER,y),T=kl(r,r.FRAGMENT_SHADER,b);function S(t){if(e.debug.checkShaderErrors){const n=r.getProgramInfoLog(m)||"",i=r.getShaderInfoLog(x)||"",s=r.getShaderInfoLog(T)||"",a=n.trim(),o=i.trim(),l=s.trim();let u=!0,c=!0;if(!1===r.getProgramParameter(m,r.LINK_STATUS))if(u=!1,"function"==typeof e.debug.onShaderError)e.debug.onShaderError(r,m,x,T);else{const e=Gl(r,x,"vertex"),n=Gl(r,T,"fragment");qt("THREE.WebGLProgram: Shader Error "+r.getError()+" - VALIDATE_STATUS "+r.getProgramParameter(m,r.VALIDATE_STATUS)+"\n\nMaterial Name: "+t.name+"\nMaterial Type: "+t.type+"\n\nProgram Info Log: "+a+"\n"+e+"\n"+n)}else""!==a?Xt("WebGLProgram: Program Info Log:",a):""!==o&&""!==l||(c=!1);c&&(t.diagnostics={runnable:u,programLog:a,vertexShader:{log:o,prefix:g},fragmentShader:{log:l,prefix:_}})}r.deleteShader(x),r.deleteShader(T),M=new Bl(r,m),E=function(e,t){const n={},i=e.getProgramParameter(t,e.ACTIVE_ATTRIBUTES);for(let r=0;r0,$=r.clearcoat>0,X=r.dispersion>0,q=r.iridescence>0,Y=r.sheen>0,K=r.transmission>0,Z=W&&!!r.anisotropyMap,Q=$&&!!r.clearcoatMap,J=$&&!!r.clearcoatNormalMap,ee=$&&!!r.clearcoatRoughnessMap,te=q&&!!r.iridescenceMap,ne=q&&!!r.iridescenceThicknessMap,ie=Y&&!!r.sheenColorMap,se=Y&&!!r.sheenRoughnessMap,ae=!!r.specularMap,oe=!!r.specularColorMap,le=!!r.specularIntensityMap,ue=K&&!!r.transmissionMap,ce=K&&!!r.thicknessMap,he=!!r.gradientMap,de=!!r.alphaMap,pe=r.alphaTest>0,fe=!!r.alphaHash,me=!!r.extensions;let ge=0;r.toneMapped&&(null!==N&&!0!==N.isXRRenderTarget||(ge=e.toneMapping));const _e={shaderID:T,shaderType:r.type,shaderName:r.name,vertexShader:E,fragmentShader:w,defines:r.defines,customVertexShaderID:A,customFragmentShaderID:R,isRawShaderMaterial:!0===r.isRawShaderMaterial,glslVersion:r.glslVersion,precision:d,batching:D,batchingColor:D&&null!==m._colorsTexture,instancing:L,instancingColor:L&&null!==m.instanceColor,instancingMorph:L&&null!==m.morphTexture,outputColorSpace:null===N?e.outputColorSpace:!0===N.isXRRenderTarget?N.texture.colorSpace:xt,alphaToCoverage:!!r.alphaToCoverage,map:I,matcap:U,envMap:F,envMapMode:F&&b.mapping,envMapCubeUVHeight:x,aoMap:O,lightMap:B,bumpMap:k,normalMap:z,displacementMap:V,emissiveMap:G,normalMapObjectSpace:z&&1===r.normalMapType,normalMapTangentSpace:z&&0===r.normalMapType,metalnessMap:H,roughnessMap:j,anisotropy:W,anisotropyMap:Z,clearcoat:$,clearcoatMap:Q,clearcoatNormalMap:J,clearcoatRoughnessMap:ee,dispersion:X,iridescence:q,iridescenceMap:te,iridescenceThicknessMap:ne,sheen:Y,sheenColorMap:ie,sheenRoughnessMap:se,specularMap:ae,specularColorMap:oe,specularIntensityMap:le,transmission:K,transmissionMap:ue,thicknessMap:ce,gradientMap:he,opaque:!1===r.transparent&&1===r.blending&&!1===r.alphaToCoverage,alphaMap:de,alphaTest:pe,alphaHash:fe,combine:r.combine,mapUv:I&&f(r.map.channel),aoMapUv:O&&f(r.aoMap.channel),lightMapUv:B&&f(r.lightMap.channel),bumpMapUv:k&&f(r.bumpMap.channel),normalMapUv:z&&f(r.normalMap.channel),displacementMapUv:V&&f(r.displacementMap.channel),emissiveMapUv:G&&f(r.emissiveMap.channel),metalnessMapUv:H&&f(r.metalnessMap.channel),roughnessMapUv:j&&f(r.roughnessMap.channel),anisotropyMapUv:Z&&f(r.anisotropyMap.channel),clearcoatMapUv:Q&&f(r.clearcoatMap.channel),clearcoatNormalMapUv:J&&f(r.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:ee&&f(r.clearcoatRoughnessMap.channel),iridescenceMapUv:te&&f(r.iridescenceMap.channel),iridescenceThicknessMapUv:ne&&f(r.iridescenceThicknessMap.channel),sheenColorMapUv:ie&&f(r.sheenColorMap.channel),sheenRoughnessMapUv:se&&f(r.sheenRoughnessMap.channel),specularMapUv:ae&&f(r.specularMap.channel),specularColorMapUv:oe&&f(r.specularColorMap.channel),specularIntensityMapUv:le&&f(r.specularIntensityMap.channel),transmissionMapUv:ue&&f(r.transmissionMap.channel),thicknessMapUv:ce&&f(r.thicknessMap.channel),alphaMapUv:de&&f(r.alphaMap.channel),vertexTangents:!!_.attributes.tangent&&(z||W),vertexColors:r.vertexColors,vertexAlphas:!0===r.vertexColors&&!!_.attributes.color&&4===_.attributes.color.itemSize,pointsUvs:!0===m.isPoints&&!!_.attributes.uv&&(I||de),fog:!!g,useFog:!0===r.fog,fogExp2:!!g&&g.isFogExp2,flatShading:!1===r.wireframe&&(!0===r.flatShading||void 0===_.attributes.normal&&!1===z&&(r.isMeshLambertMaterial||r.isMeshPhongMaterial||r.isMeshStandardMaterial||r.isMeshPhysicalMaterial)),sizeAttenuation:!0===r.sizeAttenuation,logarithmicDepthBuffer:h,reversedDepthBuffer:P,skinning:!0===m.isSkinnedMesh,morphTargets:void 0!==_.morphAttributes.position,morphNormals:void 0!==_.morphAttributes.normal,morphColors:void 0!==_.morphAttributes.color,morphTargetsCount:M,morphTextureStride:C,numDirLights:a.directional.length,numPointLights:a.point.length,numSpotLights:a.spot.length,numSpotLightMaps:a.spotLightMap.length,numRectAreaLights:a.rectArea.length,numHemiLights:a.hemi.length,numDirLightShadows:a.directionalShadowMap.length,numPointLightShadows:a.pointShadowMap.length,numSpotLightShadows:a.spotShadowMap.length,numSpotLightShadowsWithMaps:a.numSpotLightShadowsWithMaps,numLightProbes:a.numLightProbes,numClippingPlanes:s.numPlanes,numClipIntersection:s.numIntersection,dithering:r.dithering,shadowMapEnabled:e.shadowMap.enabled&&u.length>0,shadowMapType:e.shadowMap.type,toneMapping:ge,decodeVideoTexture:I&&!0===r.map.isVideoTexture&&bn.getTransfer(r.map.colorSpace)===St,decodeVideoTextureEmissive:G&&!0===r.emissiveMap.isVideoTexture&&bn.getTransfer(r.emissiveMap.colorSpace)===St,premultipliedAlpha:r.premultipliedAlpha,doubleSided:2===r.side,flipSided:1===r.side,useDepthPacking:r.depthPacking>=0,depthPacking:r.depthPacking||0,index0AttributeName:r.index0AttributeName,extensionClipCullDistance:me&&!0===r.extensions.clipCullDistance&&n.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(me&&!0===r.extensions.multiDraw||D)&&n.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:n.has("KHR_parallel_shader_compile"),customProgramCacheKey:r.customProgramCacheKey()};return _e.vertexUv1s=l.has(1),_e.vertexUv2s=l.has(2),_e.vertexUv3s=l.has(3),l.clear(),_e},getProgramCacheKey:function(t){const n=[];if(t.shaderID?n.push(t.shaderID):(n.push(t.customVertexShaderID),n.push(t.customFragmentShaderID)),void 0!==t.defines)for(const e in t.defines)n.push(e),n.push(t.defines[e]);return!1===t.isRawShaderMaterial&&(!function(e,t){e.push(t.precision),e.push(t.outputColorSpace),e.push(t.envMapMode),e.push(t.envMapCubeUVHeight),e.push(t.mapUv),e.push(t.alphaMapUv),e.push(t.lightMapUv),e.push(t.aoMapUv),e.push(t.bumpMapUv),e.push(t.normalMapUv),e.push(t.displacementMapUv),e.push(t.emissiveMapUv),e.push(t.metalnessMapUv),e.push(t.roughnessMapUv),e.push(t.anisotropyMapUv),e.push(t.clearcoatMapUv),e.push(t.clearcoatNormalMapUv),e.push(t.clearcoatRoughnessMapUv),e.push(t.iridescenceMapUv),e.push(t.iridescenceThicknessMapUv),e.push(t.sheenColorMapUv),e.push(t.sheenRoughnessMapUv),e.push(t.specularMapUv),e.push(t.specularColorMapUv),e.push(t.specularIntensityMapUv),e.push(t.transmissionMapUv),e.push(t.thicknessMapUv),e.push(t.combine),e.push(t.fogExp2),e.push(t.sizeAttenuation),e.push(t.morphTargetsCount),e.push(t.morphAttributeCount),e.push(t.numDirLights),e.push(t.numPointLights),e.push(t.numSpotLights),e.push(t.numSpotLightMaps),e.push(t.numHemiLights),e.push(t.numRectAreaLights),e.push(t.numDirLightShadows),e.push(t.numPointLightShadows),e.push(t.numSpotLightShadows),e.push(t.numSpotLightShadowsWithMaps),e.push(t.numLightProbes),e.push(t.shadowMapType),e.push(t.toneMapping),e.push(t.numClippingPlanes),e.push(t.numClipIntersection),e.push(t.depthPacking)}(n,t),function(e,t){a.disableAll(),t.instancing&&a.enable(0);t.instancingColor&&a.enable(1);t.instancingMorph&&a.enable(2);t.matcap&&a.enable(3);t.envMap&&a.enable(4);t.normalMapObjectSpace&&a.enable(5);t.normalMapTangentSpace&&a.enable(6);t.clearcoat&&a.enable(7);t.iridescence&&a.enable(8);t.alphaTest&&a.enable(9);t.vertexColors&&a.enable(10);t.vertexAlphas&&a.enable(11);t.vertexUv1s&&a.enable(12);t.vertexUv2s&&a.enable(13);t.vertexUv3s&&a.enable(14);t.vertexTangents&&a.enable(15);t.anisotropy&&a.enable(16);t.alphaHash&&a.enable(17);t.batching&&a.enable(18);t.dispersion&&a.enable(19);t.batchingColor&&a.enable(20);t.gradientMap&&a.enable(21);e.push(a.mask),a.disableAll(),t.fog&&a.enable(0);t.useFog&&a.enable(1);t.flatShading&&a.enable(2);t.logarithmicDepthBuffer&&a.enable(3);t.reversedDepthBuffer&&a.enable(4);t.skinning&&a.enable(5);t.morphTargets&&a.enable(6);t.morphNormals&&a.enable(7);t.morphColors&&a.enable(8);t.premultipliedAlpha&&a.enable(9);t.shadowMapEnabled&&a.enable(10);t.doubleSided&&a.enable(11);t.flipSided&&a.enable(12);t.useDepthPacking&&a.enable(13);t.dithering&&a.enable(14);t.transmission&&a.enable(15);t.sheen&&a.enable(16);t.opaque&&a.enable(17);t.pointsUvs&&a.enable(18);t.decodeVideoTexture&&a.enable(19);t.decodeVideoTextureEmissive&&a.enable(20);t.alphaToCoverage&&a.enable(21);e.push(a.mask)}(n,t),n.push(e.outputColorSpace)),n.push(t.customProgramCacheKey),n.join()},getUniforms:function(e){const t=p[e.type];let n;if(t){const e=Ja[t];n=js.clone(e.uniforms)}else n=e.uniforms;return n},acquireProgram:function(t,n){let i=c.get(n);return void 0!==i?++i.usedTimes:(i=new uu(e,n,t,r),u.push(i),c.set(n,i)),i},releaseProgram:function(e){if(0===--e.usedTimes){const t=u.indexOf(e);u[t]=u[u.length-1],u.pop(),c.delete(e.cacheKey),e.destroy()}},releaseShaderCache:function(e){o.remove(e)},programs:u,dispose:function(){o.dispose()}}}function fu(){let e=new WeakMap;return{has:function(t){return e.has(t)},get:function(t){let n=e.get(t);return void 0===n&&(n={},e.set(t,n)),n},remove:function(t){e.delete(t)},update:function(t,n,i){e.get(t)[n]=i},dispose:function(){e=new WeakMap}}}function mu(e,t){return e.groupOrder!==t.groupOrder?e.groupOrder-t.groupOrder:e.renderOrder!==t.renderOrder?e.renderOrder-t.renderOrder:e.material.id!==t.material.id?e.material.id-t.material.id:e.materialVariant!==t.materialVariant?e.materialVariant-t.materialVariant:e.z!==t.z?e.z-t.z:e.id-t.id}function gu(e,t){return e.groupOrder!==t.groupOrder?e.groupOrder-t.groupOrder:e.renderOrder!==t.renderOrder?e.renderOrder-t.renderOrder:e.z!==t.z?t.z-e.z:e.id-t.id}function _u(){const e=[];let t=0;const n=[],i=[],r=[];function s(e){let t=0;return e.isInstancedMesh&&(t+=2),e.isSkinnedMesh&&(t+=1),t}function a(n,i,r,a,o,l){let u=e[t];return void 0===u?(u={id:n.id,object:n,geometry:i,material:r,materialVariant:s(n),groupOrder:a,renderOrder:n.renderOrder,z:o,group:l},e[t]=u):(u.id=n.id,u.object=n,u.geometry=i,u.material=r,u.materialVariant=s(n),u.groupOrder=a,u.renderOrder=n.renderOrder,u.z=o,u.group=l),t++,u}return{opaque:n,transmissive:i,transparent:r,init:function(){t=0,n.length=0,i.length=0,r.length=0},push:function(e,t,s,o,l,u){const c=a(e,t,s,o,l,u);s.transmission>0?i.push(c):!0===s.transparent?r.push(c):n.push(c)},unshift:function(e,t,s,o,l,u){const c=a(e,t,s,o,l,u);s.transmission>0?i.unshift(c):!0===s.transparent?r.unshift(c):n.unshift(c)},finish:function(){for(let n=t,i=e.length;n1&&n.sort(e||mu),i.length>1&&i.sort(t||gu),r.length>1&&r.sort(t||gu)}}}function vu(){let e=new WeakMap;return{get:function(t,n){const i=e.get(t);let r;return void 0===i?(r=new _u,e.set(t,[r])):n>=i.length?(r=new _u,i.push(r)):r=i[n],r},dispose:function(){e=new WeakMap}}}function yu(){const e={};return{get:function(t){if(void 0!==e[t.id])return e[t.id];let n;switch(t.type){case"DirectionalLight":n={direction:new dn,color:new _i};break;case"SpotLight":n={position:new dn,direction:new dn,color:new _i,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":n={position:new dn,color:new _i,distance:0,decay:0};break;case"HemisphereLight":n={direction:new dn,skyColor:new _i,groundColor:new _i};break;case"RectAreaLight":n={color:new _i,position:new dn,halfWidth:new dn,halfHeight:new dn}}return e[t.id]=n,n}}}let bu=0;function xu(e,t){return(t.castShadow?2:0)-(e.castShadow?2:0)+(t.map?1:0)-(e.map?1:0)}function Tu(e){const t=new yu,n=function(){const e={};return{get:function(t){if(void 0!==e[t.id])return e[t.id];let n;switch(t.type){case"DirectionalLight":case"SpotLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new cn};break;case"PointLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new cn,shadowCameraNear:1,shadowCameraFar:1e3}}return e[t.id]=n,n}}}(),i={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let e=0;e<9;e++)i.probe.push(new dn);const r=new dn,s=new Fn,a=new Fn;return{setup:function(r){let s=0,a=0,o=0;for(let e=0;e<9;e++)i.probe[e].set(0,0,0);let l=0,u=0,c=0,h=0,d=0,p=0,f=0,m=0,g=0,_=0,v=0;r.sort(xu);for(let e=0,y=r.length;e0&&(!0===e.has("OES_texture_float_linear")?(i.rectAreaLTC1=Qa.LTC_FLOAT_1,i.rectAreaLTC2=Qa.LTC_FLOAT_2):(i.rectAreaLTC1=Qa.LTC_HALF_1,i.rectAreaLTC2=Qa.LTC_HALF_2)),i.ambient[0]=s,i.ambient[1]=a,i.ambient[2]=o;const y=i.hash;y.directionalLength===l&&y.pointLength===u&&y.spotLength===c&&y.rectAreaLength===h&&y.hemiLength===d&&y.numDirectionalShadows===p&&y.numPointShadows===f&&y.numSpotShadows===m&&y.numSpotMaps===g&&y.numLightProbes===v||(i.directional.length=l,i.spot.length=c,i.rectArea.length=h,i.point.length=u,i.hemi.length=d,i.directionalShadow.length=p,i.directionalShadowMap.length=p,i.pointShadow.length=f,i.pointShadowMap.length=f,i.spotShadow.length=m,i.spotShadowMap.length=m,i.directionalShadowMatrix.length=p,i.pointShadowMatrix.length=f,i.spotLightMatrix.length=m+g-_,i.spotLightMap.length=g,i.numSpotLightShadowsWithMaps=_,i.numLightProbes=v,y.directionalLength=l,y.pointLength=u,y.spotLength=c,y.rectAreaLength=h,y.hemiLength=d,y.numDirectionalShadows=p,y.numPointShadows=f,y.numSpotShadows=m,y.numSpotMaps=g,y.numLightProbes=v,i.version=bu++)},setupView:function(e,t){let n=0,o=0,l=0,u=0,c=0;const h=t.matrixWorldInverse;for(let t=0,d=e.length;t=r.length?(s=new Su(e),r.push(s)):s=r[i],s},dispose:function(){t=new WeakMap}}}const Eu=[new dn(1,0,0),new dn(-1,0,0),new dn(0,1,0),new dn(0,-1,0),new dn(0,0,1),new dn(0,0,-1)],wu=[new dn(0,-1,0),new dn(0,-1,0),new dn(0,0,1),new dn(0,0,-1),new dn(0,-1,0),new dn(0,-1,0)],Au=new Fn,Ru=new dn,Cu=new dn;function Nu(e,t,n){let i=new ns;const r=new cn,s=new cn,a=new Pn,o=new Js,l=new ea,u={},c=n.maxTextureSize,h={[m]:1,[g]:0,[_]:2},d=new Ws({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new cn},radius:{value:4}},vertexShader:"void main() {\n\tgl_Position = vec4( position, 1.0 );\n}",fragmentShader:"uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\nvoid main() {\n\tconst float samples = float( VSM_SAMPLES );\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ).rg;\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ).r;\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( max( 0.0, squared_mean - mean * mean ) );\n\tgl_FragColor = vec4( mean, std_dev, 0.0, 1.0 );\n}"}),p=d.clone();p.defines.HORIZONTAL_PASS=1;const f=new vr;f.setAttribute("position",new nr(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const v=new Wr(f,d),y=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=1;let b=this.type;function x(n,i){const s=t.update(v);d.defines.VSM_SAMPLES!==n.blurSamples&&(d.defines.VSM_SAMPLES=n.blurSamples,p.defines.VSM_SAMPLES=n.blurSamples,d.needsUpdate=!0,p.needsUpdate=!0),null===n.mapPass&&(n.mapPass=new Dn(r.x,r.y,{format:Ie,type:xe})),d.uniforms.shadow_pass.value=n.map.depthTexture,d.uniforms.resolution.value=n.mapSize,d.uniforms.radius.value=n.radius,e.setRenderTarget(n.mapPass),e.clear(),e.renderBufferDirect(i,null,s,d,v,null),p.uniforms.shadow_pass.value=n.mapPass.texture,p.uniforms.resolution.value=n.mapSize,p.uniforms.radius.value=n.radius,e.setRenderTarget(n.map),e.clear(),e.renderBufferDirect(i,null,s,p,v,null)}function T(t,n,i,r){let s=null;const a=!0===i.isPointLight?t.customDistanceMaterial:t.customDepthMaterial;if(void 0!==a)s=a;else if(s=!0===i.isPointLight?l:o,e.localClippingEnabled&&!0===n.clipShadows&&Array.isArray(n.clippingPlanes)&&0!==n.clippingPlanes.length||n.displacementMap&&0!==n.displacementScale||n.alphaMap&&n.alphaTest>0||n.map&&n.alphaTest>0||!0===n.alphaToCoverage){const e=s.uuid,t=n.uuid;let i=u[e];void 0===i&&(i={},u[e]=i);let r=i[t];void 0===r&&(r=s.clone(),i[t]=r,n.addEventListener("dispose",M)),s=r}if(s.visible=n.visible,s.wireframe=n.wireframe,s.side=3===r?null!==n.shadowSide?n.shadowSide:n.side:null!==n.shadowSide?n.shadowSide:h[n.side],s.alphaMap=n.alphaMap,s.alphaTest=!0===n.alphaToCoverage?.5:n.alphaTest,s.map=n.map,s.clipShadows=n.clipShadows,s.clippingPlanes=n.clippingPlanes,s.clipIntersection=n.clipIntersection,s.displacementMap=n.displacementMap,s.displacementScale=n.displacementScale,s.displacementBias=n.displacementBias,s.wireframeLinewidth=n.wireframeLinewidth,s.linewidth=n.linewidth,!0===i.isPointLight&&!0===s.isMeshDistanceMaterial){e.properties.get(s).light=i}return s}function S(n,r,s,a,o){if(!1===n.visible)return;if(n.layers.test(r.layers)&&(n.isMesh||n.isLine||n.isPoints)&&(n.castShadow||n.receiveShadow&&3===o)&&(!n.frustumCulled||i.intersectsObject(n))){n.modelViewMatrix.multiplyMatrices(s.matrixWorldInverse,n.matrixWorld);const i=t.update(n),l=n.material;if(Array.isArray(l)){const t=i.groups;for(let u=0,c=t.length;ue.needsUpdate=!0):e.material.needsUpdate=!0)});for(let l=0,u=t.length;lc||r.y>c)&&(r.x>c&&(s.x=Math.floor(c/f.x),r.x=s.x*f.x,h.mapSize.x=s.x),r.y>c&&(s.y=Math.floor(c/f.y),r.y=s.y*f.y,h.mapSize.y=s.y));const m=e.state.buffers.depth.getReversed();if(h.camera._reversedDepth=m,null===h.map||!0===p){if(null!==h.map&&(null!==h.map.depthTexture&&(h.map.depthTexture.dispose(),h.map.depthTexture=null),h.map.dispose()),3===this.type){if(u.isPointLight){Xt("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}h.map=new Dn(r.x,r.y,{format:Ie,type:xe,minFilter:he,magFilter:he,generateMipmaps:!1}),h.map.texture.name=u.name+".shadowMap",h.map.depthTexture=new vs(r.x,r.y,be),h.map.depthTexture.name=u.name+".shadowMapDepth",h.map.depthTexture.format=Ne,h.map.depthTexture.compareFunction=null,h.map.depthTexture.minFilter=le,h.map.depthTexture.magFilter=le}else u.isPointLight?(h.map=new Mo(r.x),h.map.depthTexture=new ys(r.x,ye)):(h.map=new Dn(r.x,r.y),h.map.depthTexture=new vs(r.x,r.y,ye)),h.map.depthTexture.name=u.name+".shadowMap",h.map.depthTexture.format=Ne,1===this.type?(h.map.depthTexture.compareFunction=m?Pt:Rt,h.map.depthTexture.minFilter=he,h.map.depthTexture.magFilter=he):(h.map.depthTexture.compareFunction=null,h.map.depthTexture.minFilter=le,h.map.depthTexture.magFilter=le);h.camera.updateProjectionMatrix()}const g=h.map.isWebGLCubeRenderTarget?6:1;for(let t=0;t=1):-1!==Y.indexOf("OpenGL ES")&&(q=parseFloat(/^OpenGL ES (\d)/.exec(Y)[1]),X=q>=2);let K=null,Z={};const Q=e.getParameter(e.SCISSOR_BOX),J=e.getParameter(e.VIEWPORT),ee=(new Pn).fromArray(Q),te=(new Pn).fromArray(J);function ne(t,n,i,r){const s=new Uint8Array(4),a=e.createTexture();e.bindTexture(t,a),e.texParameteri(t,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(t,e.TEXTURE_MAG_FILTER,e.NEAREST);for(let a=0;an||r.height>n)&&(i=n/Math.max(r.width,r.height)),i<1){if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof VideoFrame&&e instanceof VideoFrame){const n=Math.floor(i*r.width),s=Math.floor(i*r.height);void 0===h&&(h=f(n,s));const a=t?f(n,s):h;a.width=n,a.height=s;return a.getContext("2d").drawImage(e,0,0,n,s),Xt("WebGLRenderer: Texture has been resized from ("+r.width+"x"+r.height+") to ("+n+"x"+s+")."),a}return"data"in e&&Xt("WebGLRenderer: Image in DataTexture is too big ("+r.width+"x"+r.height+")."),e}return e}function g(e){return e.generateMipmaps}function _(t){e.generateMipmap(t)}function v(t){return t.isWebGLCubeRenderTarget?e.TEXTURE_CUBE_MAP:t.isWebGL3DRenderTarget?e.TEXTURE_3D:t.isWebGLArrayRenderTarget||t.isCompressedArrayTexture?e.TEXTURE_2D_ARRAY:e.TEXTURE_2D}function y(n,i,r,s,a=!1){if(null!==n){if(void 0!==e[n])return e[n];Xt("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+n+"'")}let o=i;if(i===e.RED&&(r===e.FLOAT&&(o=e.R32F),r===e.HALF_FLOAT&&(o=e.R16F),r===e.UNSIGNED_BYTE&&(o=e.R8)),i===e.RED_INTEGER&&(r===e.UNSIGNED_BYTE&&(o=e.R8UI),r===e.UNSIGNED_SHORT&&(o=e.R16UI),r===e.UNSIGNED_INT&&(o=e.R32UI),r===e.BYTE&&(o=e.R8I),r===e.SHORT&&(o=e.R16I),r===e.INT&&(o=e.R32I)),i===e.RG&&(r===e.FLOAT&&(o=e.RG32F),r===e.HALF_FLOAT&&(o=e.RG16F),r===e.UNSIGNED_BYTE&&(o=e.RG8)),i===e.RG_INTEGER&&(r===e.UNSIGNED_BYTE&&(o=e.RG8UI),r===e.UNSIGNED_SHORT&&(o=e.RG16UI),r===e.UNSIGNED_INT&&(o=e.RG32UI),r===e.BYTE&&(o=e.RG8I),r===e.SHORT&&(o=e.RG16I),r===e.INT&&(o=e.RG32I)),i===e.RGB_INTEGER&&(r===e.UNSIGNED_BYTE&&(o=e.RGB8UI),r===e.UNSIGNED_SHORT&&(o=e.RGB16UI),r===e.UNSIGNED_INT&&(o=e.RGB32UI),r===e.BYTE&&(o=e.RGB8I),r===e.SHORT&&(o=e.RGB16I),r===e.INT&&(o=e.RGB32I)),i===e.RGBA_INTEGER&&(r===e.UNSIGNED_BYTE&&(o=e.RGBA8UI),r===e.UNSIGNED_SHORT&&(o=e.RGBA16UI),r===e.UNSIGNED_INT&&(o=e.RGBA32UI),r===e.BYTE&&(o=e.RGBA8I),r===e.SHORT&&(o=e.RGBA16I),r===e.INT&&(o=e.RGBA32I)),i===e.RGB&&(r===e.UNSIGNED_INT_5_9_9_9_REV&&(o=e.RGB9_E5),r===e.UNSIGNED_INT_10F_11F_11F_REV&&(o=e.R11F_G11F_B10F)),i===e.RGBA){const t=a?Tt:bn.getTransfer(s);r===e.FLOAT&&(o=e.RGBA32F),r===e.HALF_FLOAT&&(o=e.RGBA16F),r===e.UNSIGNED_BYTE&&(o=t===St?e.SRGB8_ALPHA8:e.RGBA8),r===e.UNSIGNED_SHORT_4_4_4_4&&(o=e.RGBA4),r===e.UNSIGNED_SHORT_5_5_5_1&&(o=e.RGB5_A1)}return o!==e.R16F&&o!==e.R32F&&o!==e.RG16F&&o!==e.RG32F&&o!==e.RGBA16F&&o!==e.RGBA32F||t.get("EXT_color_buffer_float"),o}function b(t,n){let i;return t?null===n||n===ye||n===Me?i=e.DEPTH24_STENCIL8:n===be?i=e.DEPTH32F_STENCIL8:n===_e&&(i=e.DEPTH24_STENCIL8,Xt("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):null===n||n===ye||n===Me?i=e.DEPTH_COMPONENT24:n===be?i=e.DEPTH_COMPONENT32F:n===_e&&(i=e.DEPTH_COMPONENT16),i}function x(e,t){return!0===g(e)||e.isFramebufferTexture&&e.minFilter!==le&&e.minFilter!==he?Math.log2(Math.max(t.width,t.height))+1:void 0!==e.mipmaps&&e.mipmaps.length>0?e.mipmaps.length:e.isCompressedTexture&&Array.isArray(e.image)?t.mipmaps.length:1}function T(e){const t=e.target;t.removeEventListener("dispose",T),function(e){const t=i.get(e);if(void 0===t.__webglInit)return;const n=e.source,r=d.get(n);if(r){const i=r[t.__cacheKey];i.usedTimes--,0===i.usedTimes&&M(e),0===Object.keys(r).length&&d.delete(n)}i.remove(e)}(t),t.isVideoTexture&&c.delete(t)}function S(t){const n=t.target;n.removeEventListener("dispose",S),function(t){const n=i.get(t);t.depthTexture&&(t.depthTexture.dispose(),i.remove(t.depthTexture));if(t.isWebGLCubeRenderTarget)for(let t=0;t<6;t++){if(Array.isArray(n.__webglFramebuffer[t]))for(let i=0;i0&&s.__version!==t.version){const e=t.image;if(null===e)Xt("WebGLRenderer: Texture marked for update but no image data found.");else{if(!1!==e.complete)return void D(s,t,r);Xt("WebGLRenderer: Texture marked for update but image is incomplete")}}else t.isExternalTexture&&(s.__webglTexture=t.sourceTexture?t.sourceTexture:null);n.bindTexture(e.TEXTURE_2D,s.__webglTexture,e.TEXTURE0+r)}const A={[se]:e.REPEAT,[ae]:e.CLAMP_TO_EDGE,[oe]:e.MIRRORED_REPEAT},R={[le]:e.NEAREST,[ue]:e.NEAREST_MIPMAP_NEAREST,[ce]:e.NEAREST_MIPMAP_LINEAR,[he]:e.LINEAR,[de]:e.LINEAR_MIPMAP_NEAREST,[pe]:e.LINEAR_MIPMAP_LINEAR},C={[Et]:e.NEVER,[Lt]:e.ALWAYS,[wt]:e.LESS,[Rt]:e.LEQUAL,[At]:e.EQUAL,[Pt]:e.GEQUAL,[Ct]:e.GREATER,[Nt]:e.NOTEQUAL};function N(n,s){if(s.type!==be||!1!==t.has("OES_texture_float_linear")||s.magFilter!==he&&s.magFilter!==de&&s.magFilter!==ce&&s.magFilter!==pe&&s.minFilter!==he&&s.minFilter!==de&&s.minFilter!==ce&&s.minFilter!==pe||Xt("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),e.texParameteri(n,e.TEXTURE_WRAP_S,A[s.wrapS]),e.texParameteri(n,e.TEXTURE_WRAP_T,A[s.wrapT]),n!==e.TEXTURE_3D&&n!==e.TEXTURE_2D_ARRAY||e.texParameteri(n,e.TEXTURE_WRAP_R,A[s.wrapR]),e.texParameteri(n,e.TEXTURE_MAG_FILTER,R[s.magFilter]),e.texParameteri(n,e.TEXTURE_MIN_FILTER,R[s.minFilter]),s.compareFunction&&(e.texParameteri(n,e.TEXTURE_COMPARE_MODE,e.COMPARE_REF_TO_TEXTURE),e.texParameteri(n,e.TEXTURE_COMPARE_FUNC,C[s.compareFunction])),!0===t.has("EXT_texture_filter_anisotropic")){if(s.magFilter===le)return;if(s.minFilter!==ce&&s.minFilter!==pe)return;if(s.type===be&&!1===t.has("OES_texture_float_linear"))return;if(s.anisotropy>1||i.get(s).__currentAnisotropy){const a=t.get("EXT_texture_filter_anisotropic");e.texParameterf(n,a.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(s.anisotropy,r.getMaxAnisotropy())),i.get(s).__currentAnisotropy=s.anisotropy}}}function P(t,n){let i=!1;void 0===t.__webglInit&&(t.__webglInit=!0,n.addEventListener("dispose",T));const r=n.source;let s=d.get(r);void 0===s&&(s={},d.set(r,s));const o=function(e){const t=[];return t.push(e.wrapS),t.push(e.wrapT),t.push(e.wrapR||0),t.push(e.magFilter),t.push(e.minFilter),t.push(e.anisotropy),t.push(e.internalFormat),t.push(e.format),t.push(e.type),t.push(e.generateMipmaps),t.push(e.premultiplyAlpha),t.push(e.flipY),t.push(e.unpackAlignment),t.push(e.colorSpace),t.join()}(n);if(o!==t.__cacheKey){void 0===s[o]&&(s[o]={texture:e.createTexture(),usedTimes:0},a.memory.textures++,i=!0),s[o].usedTimes++;const r=s[t.__cacheKey];void 0!==r&&(s[t.__cacheKey].usedTimes--,0===r.usedTimes&&M(n)),t.__cacheKey=o,t.__webglTexture=s[o].texture}return i}function L(e,t,n){return Math.floor(Math.floor(e/n)/t)}function D(t,a,o){let l=e.TEXTURE_2D;(a.isDataArrayTexture||a.isCompressedArrayTexture)&&(l=e.TEXTURE_2D_ARRAY),a.isData3DTexture&&(l=e.TEXTURE_3D);const u=P(t,a),c=a.source;n.bindTexture(l,t.__webglTexture,e.TEXTURE0+o);const h=i.get(c);if(c.version!==h.__version||!0===u){n.activeTexture(e.TEXTURE0+o);const t=bn.getPrimaries(bn.workingColorSpace),i=a.colorSpace===yt?null:bn.getPrimaries(a.colorSpace),d=a.colorSpace===yt||t===i?e.NONE:e.BROWSER_DEFAULT_WEBGL;e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,a.flipY),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,a.premultiplyAlpha),e.pixelStorei(e.UNPACK_ALIGNMENT,a.unpackAlignment),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,d);let p=m(a.image,!1,r.maxTextureSize);p=G(a,p);const f=s.convert(a.format,a.colorSpace),v=s.convert(a.type);let T,S=y(a.internalFormat,f,v,a.colorSpace,a.isVideoTexture);N(l,a);const M=a.mipmaps,E=!0!==a.isVideoTexture,w=void 0===h.__version||!0===u,A=c.dataReady,R=x(a,p);if(a.isDepthTexture)S=b(a.format===Pe,a.type),w&&(E?n.texStorage2D(e.TEXTURE_2D,1,S,p.width,p.height):n.texImage2D(e.TEXTURE_2D,0,S,p.width,p.height,0,f,v,null));else if(a.isDataTexture)if(M.length>0){E&&w&&n.texStorage2D(e.TEXTURE_2D,R,S,M[0].width,M[0].height);for(let t=0,i=M.length;te.start-t.start);let o=0;for(let e=1;e0){const i=qa(T.width,T.height,a.format,a.type);for(const r of a.layerUpdates){const s=T.data.subarray(r*i/T.data.BYTES_PER_ELEMENT,(r+1)*i/T.data.BYTES_PER_ELEMENT);n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,t,0,0,r,T.width,T.height,1,f,s)}a.clearLayerUpdates()}else n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,t,0,0,0,T.width,T.height,p.depth,f,T.data)}else n.compressedTexImage3D(e.TEXTURE_2D_ARRAY,t,S,T.width,T.height,p.depth,0,T.data,0,0);else Xt("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else E?A&&n.texSubImage3D(e.TEXTURE_2D_ARRAY,t,0,0,0,T.width,T.height,p.depth,f,v,T.data):n.texImage3D(e.TEXTURE_2D_ARRAY,t,S,T.width,T.height,p.depth,0,f,v,T.data)}else{E&&w&&n.texStorage2D(e.TEXTURE_2D,R,S,M[0].width,M[0].height);for(let t=0,i=M.length;t0){const t=qa(p.width,p.height,a.format,a.type);for(const i of a.layerUpdates){const r=p.data.subarray(i*t/p.data.BYTES_PER_ELEMENT,(i+1)*t/p.data.BYTES_PER_ELEMENT);n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,i,p.width,p.height,1,f,v,r)}a.clearLayerUpdates()}else n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,0,p.width,p.height,p.depth,f,v,p.data)}else n.texImage3D(e.TEXTURE_2D_ARRAY,0,S,p.width,p.height,p.depth,0,f,v,p.data);else if(a.isData3DTexture)E?(w&&n.texStorage3D(e.TEXTURE_3D,R,S,p.width,p.height,p.depth),A&&n.texSubImage3D(e.TEXTURE_3D,0,0,0,0,p.width,p.height,p.depth,f,v,p.data)):n.texImage3D(e.TEXTURE_3D,0,S,p.width,p.height,p.depth,0,f,v,p.data);else if(a.isFramebufferTexture){if(w)if(E)n.texStorage2D(e.TEXTURE_2D,R,S,p.width,p.height);else{let t=p.width,i=p.height;for(let r=0;r>=1,i>>=1}}else if(M.length>0){if(E&&w){const t=H(M[0]);n.texStorage2D(e.TEXTURE_2D,R,S,t.width,t.height)}for(let t=0,i=M.length;t>c),i=Math.max(1,r.height>>c);u===e.TEXTURE_3D||u===e.TEXTURE_2D_ARRAY?n.texImage3D(u,c,p,t,i,r.depth,0,h,d,null):n.texImage2D(u,c,p,t,i,0,h,d,null)}n.bindFramebuffer(e.FRAMEBUFFER,t),V(r)?o.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,l,u,m.__webglTexture,0,z(r)):(u===e.TEXTURE_2D||u>=e.TEXTURE_CUBE_MAP_POSITIVE_X&&u<=e.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&e.framebufferTexture2D(e.FRAMEBUFFER,l,u,m.__webglTexture,c),n.bindFramebuffer(e.FRAMEBUFFER,null)}function U(t,n,i){if(e.bindRenderbuffer(e.RENDERBUFFER,t),n.depthBuffer){const r=n.depthTexture,s=r&&r.isDepthTexture?r.type:null,a=b(n.stencilBuffer,s),l=n.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;V(n)?o.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,z(n),a,n.width,n.height):i?e.renderbufferStorageMultisample(e.RENDERBUFFER,z(n),a,n.width,n.height):e.renderbufferStorage(e.RENDERBUFFER,a,n.width,n.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,l,e.RENDERBUFFER,t)}else{const t=n.textures;for(let r=0;r{delete r.__boundDepthTexture,delete r.__depthDisposeCallback,e.removeEventListener("dispose",t)};e.addEventListener("dispose",t),r.__depthDisposeCallback=t}r.__boundDepthTexture=e}if(t.depthTexture&&!r.__autoAllocateDepthBuffer)if(s)for(let e=0;e<6;e++)F(r.__webglFramebuffer[e],t,e);else{const e=t.texture.mipmaps;e&&e.length>0?F(r.__webglFramebuffer[0],t,0):F(r.__webglFramebuffer,t,0)}else if(s){r.__webglDepthbuffer=[];for(let i=0;i<6;i++)if(n.bindFramebuffer(e.FRAMEBUFFER,r.__webglFramebuffer[i]),void 0===r.__webglDepthbuffer[i])r.__webglDepthbuffer[i]=e.createRenderbuffer(),U(r.__webglDepthbuffer[i],t,!1);else{const n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,s=r.__webglDepthbuffer[i];e.bindRenderbuffer(e.RENDERBUFFER,s),e.framebufferRenderbuffer(e.FRAMEBUFFER,n,e.RENDERBUFFER,s)}}else{const i=t.texture.mipmaps;if(i&&i.length>0?n.bindFramebuffer(e.FRAMEBUFFER,r.__webglFramebuffer[0]):n.bindFramebuffer(e.FRAMEBUFFER,r.__webglFramebuffer),void 0===r.__webglDepthbuffer)r.__webglDepthbuffer=e.createRenderbuffer(),U(r.__webglDepthbuffer,t,!1);else{const n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,i=r.__webglDepthbuffer;e.bindRenderbuffer(e.RENDERBUFFER,i),e.framebufferRenderbuffer(e.FRAMEBUFFER,n,e.RENDERBUFFER,i)}}n.bindFramebuffer(e.FRAMEBUFFER,null)}const B=[],k=[];function z(e){return Math.min(r.maxSamples,e.samples)}function V(e){const n=i.get(e);return e.samples>0&&!0===t.has("WEBGL_multisampled_render_to_texture")&&!1!==n.__useRenderToTexture}function G(e,t){const n=e.colorSpace,i=e.format,r=e.type;return!0===e.isCompressedTexture||!0===e.isVideoTexture||n!==xt&&n!==yt&&(bn.getTransfer(n)===St?i===Ce&&r===fe||Xt("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):qt("WebGLTextures: Unsupported texture color space:",n)),t}function H(e){return"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement?(u.width=e.naturalWidth||e.width,u.height=e.naturalHeight||e.height):"undefined"!=typeof VideoFrame&&e instanceof VideoFrame?(u.width=e.displayWidth,u.height=e.displayHeight):(u.width=e.width,u.height=e.height),u}this.allocateTextureUnit=function(){const e=E;return e>=r.maxTextures&&Xt("WebGLTextures: Trying to use "+e+" texture units while this GPU supports only "+r.maxTextures),E+=1,e},this.resetTextureUnits=function(){E=0},this.setTexture2D=w,this.setTexture2DArray=function(t,r){const s=i.get(t);!1===t.isRenderTargetTexture&&t.version>0&&s.__version!==t.version?D(s,t,r):(t.isExternalTexture&&(s.__webglTexture=t.sourceTexture?t.sourceTexture:null),n.bindTexture(e.TEXTURE_2D_ARRAY,s.__webglTexture,e.TEXTURE0+r))},this.setTexture3D=function(t,r){const s=i.get(t);!1===t.isRenderTargetTexture&&t.version>0&&s.__version!==t.version?D(s,t,r):n.bindTexture(e.TEXTURE_3D,s.__webglTexture,e.TEXTURE0+r)},this.setTextureCube=function(t,a){const o=i.get(t);!0!==t.isCubeDepthTexture&&t.version>0&&o.__version!==t.version?function(t,a,o){if(6!==a.image.length)return;const l=P(t,a),u=a.source;n.bindTexture(e.TEXTURE_CUBE_MAP,t.__webglTexture,e.TEXTURE0+o);const c=i.get(u);if(u.version!==c.__version||!0===l){n.activeTexture(e.TEXTURE0+o);const t=bn.getPrimaries(bn.workingColorSpace),i=a.colorSpace===yt?null:bn.getPrimaries(a.colorSpace),h=a.colorSpace===yt||t===i?e.NONE:e.BROWSER_DEFAULT_WEBGL;e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,a.flipY),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,a.premultiplyAlpha),e.pixelStorei(e.UNPACK_ALIGNMENT,a.unpackAlignment),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,h);const d=a.isCompressedTexture||a.image[0].isCompressedTexture,p=a.image[0]&&a.image[0].isDataTexture,f=[];for(let e=0;e<6;e++)f[e]=d||p?p?a.image[e].image:a.image[e]:m(a.image[e],!0,r.maxCubemapSize),f[e]=G(a,f[e]);const v=f[0],b=s.convert(a.format,a.colorSpace),T=s.convert(a.type),S=y(a.internalFormat,b,T,a.colorSpace),M=!0!==a.isVideoTexture,E=void 0===c.__version||!0===l,w=u.dataReady;let A,R=x(a,v);if(N(e.TEXTURE_CUBE_MAP,a),d){M&&E&&n.texStorage2D(e.TEXTURE_CUBE_MAP,R,S,v.width,v.height);for(let t=0;t<6;t++){A=f[t].mipmaps;for(let i=0;i0&&R++;const t=H(f[0]);n.texStorage2D(e.TEXTURE_CUBE_MAP,R,S,t.width,t.height)}for(let t=0;t<6;t++)if(p){M?w&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,f[t].width,f[t].height,b,T,f[t].data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,S,f[t].width,f[t].height,0,b,T,f[t].data);for(let i=0;i1;if(h||(void 0===l.__webglTexture&&(l.__webglTexture=e.createTexture()),l.__version=r.version,a.memory.textures++),c){o.__webglFramebuffer=[];for(let t=0;t<6;t++)if(r.mipmaps&&r.mipmaps.length>0){o.__webglFramebuffer[t]=[];for(let n=0;n0){o.__webglFramebuffer=[];for(let t=0;t0&&!1===V(t)){o.__webglMultisampledFramebuffer=e.createFramebuffer(),o.__webglColorRenderbuffer=[],n.bindFramebuffer(e.FRAMEBUFFER,o.__webglMultisampledFramebuffer);for(let n=0;n0)for(let i=0;i0)for(let n=0;n0)if(!1===V(t)){const r=t.textures,s=t.width,a=t.height;let o=e.COLOR_BUFFER_BIT;const u=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,c=i.get(t),h=r.length>1;if(h)for(let t=0;t0?n.bindFramebuffer(e.DRAW_FRAMEBUFFER,c.__webglFramebuffer[0]):n.bindFramebuffer(e.DRAW_FRAMEBUFFER,c.__webglFramebuffer);for(let n=0;n= 1.0 ) {\n\n\t\tgl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;\n\n\t} else {\n\n\t\tgl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;\n\n\t}\n\n}",uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new Wr(new Os(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class Uu extends Zt{constructor(e,t){super();const n=this;let i=null,r=1,s=null,a="local-floor",o=1,l=null,u=null,c=null,h=null,d=null,p=null;const f="undefined"!=typeof XRWebGLBinding,m=new Iu,g={},_=t.getContextAttributes();let v=null,y=null;const b=[],x=[],T=new cn;let S=null;const M=new Sa;M.viewport=new Pn;const E=new Sa;E.viewport=new Pn;const w=[M,E],A=new Oa;let R=null,C=null;function N(e){const t=x.indexOf(e.inputSource);if(-1===t)return;const n=b[t];void 0!==n&&(n.update(e.inputSource,e.frame,l||s),n.dispatchEvent({type:e.type,data:e.inputSource}))}function P(){i.removeEventListener("select",N),i.removeEventListener("selectstart",N),i.removeEventListener("selectend",N),i.removeEventListener("squeeze",N),i.removeEventListener("squeezestart",N),i.removeEventListener("squeezeend",N),i.removeEventListener("end",P),i.removeEventListener("inputsourceschange",L);for(let e=0;e=0&&(x[i]=null,b[i].disconnect(n))}for(let t=0;t=x.length){x.push(n),i=e;break}if(null===x[e]){x[e]=n,i=e;break}}if(-1===i)break}const r=b[i];r&&r.connect(n)}}this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(e){let t=b[e];return void 0===t&&(t=new di,b[e]=t),t.getTargetRaySpace()},this.getControllerGrip=function(e){let t=b[e];return void 0===t&&(t=new di,b[e]=t),t.getGripSpace()},this.getHand=function(e){let t=b[e];return void 0===t&&(t=new di,b[e]=t),t.getHandSpace()},this.setFramebufferScaleFactor=function(e){r=e,!0===n.isPresenting&&Xt("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(e){a=e,!0===n.isPresenting&&Xt("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return l||s},this.setReferenceSpace=function(e){l=e},this.getBaseLayer=function(){return null!==h?h:d},this.getBinding=function(){return null===c&&f&&(c=new XRWebGLBinding(i,t)),c},this.getFrame=function(){return p},this.getSession=function(){return i},this.setSession=async function(u){if(i=u,null!==i){v=e.getRenderTarget(),i.addEventListener("select",N),i.addEventListener("selectstart",N),i.addEventListener("selectend",N),i.addEventListener("squeeze",N),i.addEventListener("squeezestart",N),i.addEventListener("squeezeend",N),i.addEventListener("end",P),i.addEventListener("inputsourceschange",L),!0!==_.xrCompatible&&await t.makeXRCompatible(),S=e.getPixelRatio(),e.getSize(T);if(f&&"createProjectionLayer"in XRWebGLBinding.prototype){let n=null,s=null,a=null;_.depth&&(a=_.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,n=_.stencil?Pe:Ne,s=_.stencil?Me:ye);const o={colorFormat:t.RGBA8,depthFormat:a,scaleFactor:r};c=this.getBinding(),h=c.createProjectionLayer(o),i.updateRenderState({layers:[h]}),e.setPixelRatio(1),e.setSize(h.textureWidth,h.textureHeight,!1),y=new Dn(h.textureWidth,h.textureHeight,{format:Ce,type:fe,depthTexture:new vs(h.textureWidth,h.textureHeight,s,void 0,void 0,void 0,void 0,void 0,void 0,n),stencilBuffer:_.stencil,colorSpace:e.outputColorSpace,samples:_.antialias?4:0,resolveDepthBuffer:!1===h.ignoreDepthValues,resolveStencilBuffer:!1===h.ignoreDepthValues})}else{const n={antialias:_.antialias,alpha:!0,depth:_.depth,stencil:_.stencil,framebufferScaleFactor:r};d=new XRWebGLLayer(i,t,n),i.updateRenderState({baseLayer:d}),e.setPixelRatio(1),e.setSize(d.framebufferWidth,d.framebufferHeight,!1),y=new Dn(d.framebufferWidth,d.framebufferHeight,{format:Ce,type:fe,colorSpace:e.outputColorSpace,stencilBuffer:_.stencil,resolveDepthBuffer:!1===d.ignoreDepthValues,resolveStencilBuffer:!1===d.ignoreDepthValues})}y.isXRRenderTarget=!0,this.setFoveation(o),l=null,s=await i.requestReferenceSpace(a),O.setContext(i),O.start(),n.isPresenting=!0,n.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(null!==i)return i.environmentBlendMode},this.getDepthTexture=function(){return m.getDepthTexture()};const D=new dn,I=new dn;function U(e,t){null===t?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}this.updateCamera=function(e){if(null===i)return;let t=e.near,n=e.far;null!==m.texture&&(m.depthNear>0&&(t=m.depthNear),m.depthFar>0&&(n=m.depthFar)),A.near=E.near=M.near=t,A.far=E.far=M.far=n,R===A.near&&C===A.far||(i.updateRenderState({depthNear:A.near,depthFar:A.far}),R=A.near,C=A.far),A.layers.mask=6|e.layers.mask,M.layers.mask=-5&A.layers.mask,E.layers.mask=-3&A.layers.mask;const r=e.parent,s=A.cameras;U(A,r);for(let e=0;e0&&(e.alphaTest.value=i.alphaTest);const r=t.get(i),s=r.envMap,a=r.envMapRotation;s&&(e.envMap.value=s,Fu.copy(a),Fu.x*=-1,Fu.y*=-1,Fu.z*=-1,s.isCubeTexture&&!1===s.isRenderTargetTexture&&(Fu.y*=-1,Fu.z*=-1),e.envMapRotation.value.setFromMatrix4(Ou.makeRotationFromEuler(Fu)),e.flipEnvMap.value=s.isCubeTexture&&!1===s.isRenderTargetTexture?-1:1,e.reflectivity.value=i.reflectivity,e.ior.value=i.ior,e.refractionRatio.value=i.refractionRatio),i.lightMap&&(e.lightMap.value=i.lightMap,e.lightMapIntensity.value=i.lightMapIntensity,n(i.lightMap,e.lightMapTransform)),i.aoMap&&(e.aoMap.value=i.aoMap,e.aoMapIntensity.value=i.aoMapIntensity,n(i.aoMap,e.aoMapTransform))}return{refreshFogUniforms:function(t,n){n.color.getRGB(t.fogColor.value,Hs(e)),n.isFog?(t.fogNear.value=n.near,t.fogFar.value=n.far):n.isFogExp2&&(t.fogDensity.value=n.density)},refreshMaterialUniforms:function(e,r,s,a,o){r.isMeshBasicMaterial?i(e,r):r.isMeshLambertMaterial?(i(e,r),r.envMap&&(e.envMapIntensity.value=r.envMapIntensity)):r.isMeshToonMaterial?(i(e,r),function(e,t){t.gradientMap&&(e.gradientMap.value=t.gradientMap)}(e,r)):r.isMeshPhongMaterial?(i(e,r),function(e,t){e.specular.value.copy(t.specular),e.shininess.value=Math.max(t.shininess,1e-4)}(e,r),r.envMap&&(e.envMapIntensity.value=r.envMapIntensity)):r.isMeshStandardMaterial?(i(e,r),function(e,t){e.metalness.value=t.metalness,t.metalnessMap&&(e.metalnessMap.value=t.metalnessMap,n(t.metalnessMap,e.metalnessMapTransform));e.roughness.value=t.roughness,t.roughnessMap&&(e.roughnessMap.value=t.roughnessMap,n(t.roughnessMap,e.roughnessMapTransform));t.envMap&&(e.envMapIntensity.value=t.envMapIntensity)}(e,r),r.isMeshPhysicalMaterial&&function(e,t,i){e.ior.value=t.ior,t.sheen>0&&(e.sheenColor.value.copy(t.sheenColor).multiplyScalar(t.sheen),e.sheenRoughness.value=t.sheenRoughness,t.sheenColorMap&&(e.sheenColorMap.value=t.sheenColorMap,n(t.sheenColorMap,e.sheenColorMapTransform)),t.sheenRoughnessMap&&(e.sheenRoughnessMap.value=t.sheenRoughnessMap,n(t.sheenRoughnessMap,e.sheenRoughnessMapTransform)));t.clearcoat>0&&(e.clearcoat.value=t.clearcoat,e.clearcoatRoughness.value=t.clearcoatRoughness,t.clearcoatMap&&(e.clearcoatMap.value=t.clearcoatMap,n(t.clearcoatMap,e.clearcoatMapTransform)),t.clearcoatRoughnessMap&&(e.clearcoatRoughnessMap.value=t.clearcoatRoughnessMap,n(t.clearcoatRoughnessMap,e.clearcoatRoughnessMapTransform)),t.clearcoatNormalMap&&(e.clearcoatNormalMap.value=t.clearcoatNormalMap,n(t.clearcoatNormalMap,e.clearcoatNormalMapTransform),e.clearcoatNormalScale.value.copy(t.clearcoatNormalScale),1===t.side&&e.clearcoatNormalScale.value.negate()));t.dispersion>0&&(e.dispersion.value=t.dispersion);t.iridescence>0&&(e.iridescence.value=t.iridescence,e.iridescenceIOR.value=t.iridescenceIOR,e.iridescenceThicknessMinimum.value=t.iridescenceThicknessRange[0],e.iridescenceThicknessMaximum.value=t.iridescenceThicknessRange[1],t.iridescenceMap&&(e.iridescenceMap.value=t.iridescenceMap,n(t.iridescenceMap,e.iridescenceMapTransform)),t.iridescenceThicknessMap&&(e.iridescenceThicknessMap.value=t.iridescenceThicknessMap,n(t.iridescenceThicknessMap,e.iridescenceThicknessMapTransform)));t.transmission>0&&(e.transmission.value=t.transmission,e.transmissionSamplerMap.value=i.texture,e.transmissionSamplerSize.value.set(i.width,i.height),t.transmissionMap&&(e.transmissionMap.value=t.transmissionMap,n(t.transmissionMap,e.transmissionMapTransform)),e.thickness.value=t.thickness,t.thicknessMap&&(e.thicknessMap.value=t.thicknessMap,n(t.thicknessMap,e.thicknessMapTransform)),e.attenuationDistance.value=t.attenuationDistance,e.attenuationColor.value.copy(t.attenuationColor));t.anisotropy>0&&(e.anisotropyVector.value.set(t.anisotropy*Math.cos(t.anisotropyRotation),t.anisotropy*Math.sin(t.anisotropyRotation)),t.anisotropyMap&&(e.anisotropyMap.value=t.anisotropyMap,n(t.anisotropyMap,e.anisotropyMapTransform)));e.specularIntensity.value=t.specularIntensity,e.specularColor.value.copy(t.specularColor),t.specularColorMap&&(e.specularColorMap.value=t.specularColorMap,n(t.specularColorMap,e.specularColorMapTransform));t.specularIntensityMap&&(e.specularIntensityMap.value=t.specularIntensityMap,n(t.specularIntensityMap,e.specularIntensityMapTransform))}(e,r,o)):r.isMeshMatcapMaterial?(i(e,r),function(e,t){t.matcap&&(e.matcap.value=t.matcap)}(e,r)):r.isMeshDepthMaterial?i(e,r):r.isMeshDistanceMaterial?(i(e,r),function(e,n){const i=t.get(n).light;e.referencePosition.value.setFromMatrixPosition(i.matrixWorld),e.nearDistance.value=i.shadow.camera.near,e.farDistance.value=i.shadow.camera.far}(e,r)):r.isMeshNormalMaterial?i(e,r):r.isLineBasicMaterial?(function(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform))}(e,r),r.isLineDashedMaterial&&function(e,t){e.dashSize.value=t.dashSize,e.totalSize.value=t.dashSize+t.gapSize,e.scale.value=t.scale}(e,r)):r.isPointsMaterial?function(e,t,i,r){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.size.value=t.size*i,e.scale.value=.5*r,t.map&&(e.map.value=t.map,n(t.map,e.uvTransform));t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform));t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}(e,r,s,a):r.isSpriteMaterial?function(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.rotation.value=t.rotation,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform));t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform));t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}(e,r):r.isShadowMaterial?(e.color.value.copy(r.color),e.opacity.value=r.opacity):r.isShaderMaterial&&(r.uniformsNeedUpdate=!1)}}}function ku(e,t,n,i){let r={},s={},a=[];const o=e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS);function l(e,t,n,i){const r=e.value,s=t+"_"+n;if(void 0===i[s])return i[s]="number"==typeof r||"boolean"==typeof r?r:r.clone(),!0;{const e=i[s];if("number"==typeof r||"boolean"==typeof r){if(e!==r)return i[s]=r,!0}else if(!1===e.equals(r))return e.copy(r),!0}return!1}function u(e){const t={boundary:0,storage:0};return"number"==typeof e||"boolean"==typeof e?(t.boundary=4,t.storage=4):e.isVector2?(t.boundary=8,t.storage=8):e.isVector3||e.isColor?(t.boundary=16,t.storage=12):e.isVector4?(t.boundary=16,t.storage=16):e.isMatrix3?(t.boundary=48,t.storage=48):e.isMatrix4?(t.boundary=64,t.storage=64):e.isTexture?Xt("WebGLRenderer: Texture samplers can not be part of an uniforms group."):Xt("WebGLRenderer: Unsupported uniform value type.",e),t}function c(t){const n=t.target;n.removeEventListener("dispose",c);const i=a.indexOf(n.__bindingPointIndex);a.splice(i,1),e.deleteBuffer(r[n.id]),delete r[n.id],delete s[n.id]}return{bind:function(e,t){const n=t.program;i.uniformBlockBinding(e,n)},update:function(n,h){let d=r[n.id];void 0===d&&(!function(e){const t=e.uniforms;let n=0;const i=16;for(let e=0,r=t.length;e0&&(n+=i-r);e.__size=n,e.__cache={}}(n),d=function(t){const n=function(){for(let e=0;e0){const e=ec[0].object;Gu.setFromNormalAndCoplanarPoint(t.getWorldDirection(Gu.normal),qu.setFromMatrixPosition(e.matrixWorld)),Ju!==e&&null!==Ju&&(this.dispatchEvent({type:"hoveroff",object:Ju}),n.style.cursor="auto",Ju=null),Ju!==e&&(this.dispatchEvent({type:"hoveron",object:e}),n.style.cursor="pointer",Ju=e)}else null!==Ju&&(this.dispatchEvent({type:"hoveroff",object:Ju}),n.style.cursor="auto",Ju=null);$u.copy(Hu)}}function ac(e){const t=this.object,n=this.domElement,i=this.raycaster;!1!==this.enabled&&(this._updatePointer(e),this._updateState(e),ec.length=0,i.setFromCamera(Hu,t),i.intersectObjects(this.objects,this.recursive,ec),ec.length>0&&(Qu=!0===this.transformGroup?uc(ec[0].object):ec[0].object,Gu.setFromNormalAndCoplanarPoint(t.getWorldDirection(Gu.normal),qu.setFromMatrixPosition(Qu.matrixWorld)),i.ray.intersectPlane(Gu,Xu)&&(this.state===nc?(Yu.copy(Qu.parent.matrixWorld).invert(),ju.copy(Xu).sub(qu.setFromMatrixPosition(Qu.matrixWorld)),n.style.cursor="move",this.dispatchEvent({type:"dragstart",object:Qu})):this.state===ic&&(Ku.set(0,1,0).applyQuaternion(t.quaternion).normalize(),Zu.set(1,0,0).applyQuaternion(t.quaternion).normalize(),n.style.cursor="move",this.dispatchEvent({type:"dragstart",object:Qu})))),$u.copy(Hu))}function oc(){!1!==this.enabled&&(Qu&&(this.dispatchEvent({type:"dragend",object:Qu}),Qu=null),this.domElement.style.cursor=Ju?"pointer":"auto",this.state=tc)}function lc(e){!1!==this.enabled&&e.preventDefault()}function uc(e,t=null){return e.isGroup&&(t=e),null===e.parent?t:uc(e.parent,t)}function cc(e,t,n){var i,r=1;function s(){var s,a,o=i.length,l=0,u=0,c=0;for(s=0;s=(r=(h+d)/2))?h=r:d=r,i=u,!(u=u[o=+a]))return i[o]=c,e;if(t===(s=+e._x.call(null,u.data)))return c.next=u,i?i[o]=c:e._root=c,e;do{i=i?i[o]=new Array(2):e._root=new Array(2),(a=t>=(r=(h+d)/2))?h=r:d=r}while((o=+a)===(l=+(s>=r)));return i[l]=u,i[o]=c,e}function dc(e,t,n){this.node=e,this.x0=t,this.x1=n}function pc(e){return e[0]}function fc(e,t){var n=new mc(null==t?pc:t,NaN,NaN);return null==e?n:n.addAll(e)}function mc(e,t,n){this._x=e,this._x0=t,this._x1=n,this._root=void 0}function gc(e){for(var t={data:e.data},n=t;e=e.next;)n=n.next={data:e.data};return t}var _c=fc.prototype=mc.prototype;function vc(e,t,n,i){if(isNaN(t)||isNaN(n))return e;var r,s,a,o,l,u,c,h,d,p=e._root,f={data:i},m=e._x0,g=e._y0,_=e._x1,v=e._y1;if(!p)return e._root=f,e;for(;p.length;)if((u=t>=(s=(m+_)/2))?m=s:_=s,(c=n>=(a=(g+v)/2))?g=a:v=a,r=p,!(p=p[h=c<<1|u]))return r[h]=f,e;if(o=+e._x.call(null,p.data),l=+e._y.call(null,p.data),t===o&&n===l)return f.next=p,r?r[h]=f:e._root=f,e;do{r=r?r[h]=new Array(4):e._root=new Array(4),(u=t>=(s=(m+_)/2))?m=s:_=s,(c=n>=(a=(g+v)/2))?g=a:v=a}while((h=c<<1|u)==(d=(l>=a)<<1|o>=s));return r[d]=p,r[h]=f,e}function yc(e,t,n,i,r){this.node=e,this.x0=t,this.y0=n,this.x1=i,this.y1=r}function bc(e){return e[0]}function xc(e){return e[1]}function Tc(e,t,n){var i=new Sc(null==t?bc:t,null==n?xc:n,NaN,NaN,NaN,NaN);return null==e?i:i.addAll(e)}function Sc(e,t,n,i,r,s){this._x=e,this._y=t,this._x0=n,this._y0=i,this._x1=r,this._y1=s,this._root=void 0}function Mc(e){for(var t={data:e.data},n=t;e=e.next;)n=n.next={data:e.data};return t}_c.copy=function(){var e,t,n=new mc(this._x,this._x0,this._x1),i=this._root;if(!i)return n;if(!i.length)return n._root=gc(i),n;for(e=[{source:i,target:n._root=new Array(2)}];i=e.pop();)for(var r=0;r<2;++r)(t=i.source[r])&&(t.length?e.push({source:t,target:i.target[r]=new Array(2)}):i.target[r]=gc(t));return n},_c.add=function(e){const t=+this._x.call(null,e);return hc(this.cover(t),t,e)},_c.addAll=function(e){Array.isArray(e)||(e=Array.from(e));const t=e.length,n=new Float64Array(t);let i=1/0,r=-1/0;for(let s,a=0;ar&&(r=s));if(i>r)return this;this.cover(i).cover(r);for(let i=0;ie||e>=n;)switch(r=+(el||(r=s.x1)=h))&&(s=u[u.length-1],u[u.length-1]=u[u.length-1-a],u[u.length-1-a]=s)}else{var d=Math.abs(e-+this._x.call(null,c.data));d=(a=(h+d)/2))?h=a:d=a,t=c,!(c=c[l=+o]))return this;if(!c.length)break;t[l+1&1]&&(n=t,u=l)}for(;c.data!==e;)if(i=c,!(c=c.next))return this;return(r=c.next)&&delete c.next,i?(r?i.next=r:delete i.next,this):t?(r?t[l]=r:delete t[l],(c=t[0]||t[1])&&c===(t[1]||t[0])&&!c.length&&(n?n[u]=c:this._root=c),this):(this._root=r,this)},_c.removeAll=function(e){for(var t=0,n=e.length;t=(a=(y+T)/2))?y=a:T=a,(p=n>=(o=(b+S)/2))?b=o:S=o,(f=i>=(l=(x+M)/2))?x=l:M=l,s=_,!(_=_[m=f<<2|p<<1|d]))return s[m]=v,e;if(u=+e._x.call(null,_.data),c=+e._y.call(null,_.data),h=+e._z.call(null,_.data),t===u&&n===c&&i===h)return v.next=_,s?s[m]=v:e._root=v,e;do{s=s?s[m]=new Array(8):e._root=new Array(8),(d=t>=(a=(y+T)/2))?y=a:T=a,(p=n>=(o=(b+S)/2))?b=o:S=o,(f=i>=(l=(x+M)/2))?x=l:M=l}while((m=f<<2|p<<1|d)==(g=(h>=l)<<2|(c>=o)<<1|u>=a));return s[g]=_,s[m]=v,e}function Ac(e,t,n,i,r,s,a){this.node=e,this.x0=t,this.y0=n,this.z0=i,this.x1=r,this.y1=s,this.z1=a}Ec.copy=function(){var e,t,n=new Sc(this._x,this._y,this._x0,this._y0,this._x1,this._y1),i=this._root;if(!i)return n;if(!i.length)return n._root=Mc(i),n;for(e=[{source:i,target:n._root=new Array(4)}];i=e.pop();)for(var r=0;r<4;++r)(t=i.source[r])&&(t.length?e.push({source:t,target:i.target[r]=new Array(4)}):i.target[r]=Mc(t));return n},Ec.add=function(e){const t=+this._x.call(null,e),n=+this._y.call(null,e);return vc(this.cover(t,n),t,n,e)},Ec.addAll=function(e){var t,n,i,r,s=e.length,a=new Array(s),o=new Array(s),l=1/0,u=1/0,c=-1/0,h=-1/0;for(n=0;nc&&(c=i),rh&&(h=r));if(l>c||u>h)return this;for(this.cover(l,u).cover(c,h),n=0;ne||e>=r||i>t||t>=s;)switch(o=(td||(s=l.y0)>p||(a=l.x1)=_)<<1|e>=g)&&(l=f[f.length-1],f[f.length-1]=f[f.length-1-u],f[f.length-1-u]=l)}else{var v=e-+this._x.call(null,m.data),y=t-+this._y.call(null,m.data),b=v*v+y*y;if(b=(o=(f+g)/2))?f=o:g=o,(c=a>=(l=(m+_)/2))?m=l:_=l,t=p,!(p=p[h=c<<1|u]))return this;if(!p.length)break;(t[h+1&3]||t[h+2&3]||t[h+3&3])&&(n=t,d=h)}for(;p.data!==e;)if(i=p,!(p=p.next))return this;return(r=p.next)&&delete p.next,i?(r?i.next=r:delete i.next,this):t?(r?t[h]=r:delete t[h],(p=t[0]||t[1]||t[2]||t[3])&&p===(t[3]||t[2]||t[1]||t[0])&&!p.length&&(n?n[d]=p:this._root=p),this):(this._root=r,this)},Ec.removeAll=function(e){for(var t=0,n=e.length;tMath.sqrt((e-i)**2+(t-r)**2+(n-s)**2);function Cc(e){return e[0]}function Nc(e){return e[1]}function Pc(e){return e[2]}function Lc(e,t,n,i){var r=new Dc(null==t?Cc:t,null==n?Nc:n,null==i?Pc:i,NaN,NaN,NaN,NaN,NaN,NaN);return null==e?r:r.addAll(e)}function Dc(e,t,n,i,r,s,a,o,l){this._x=e,this._y=t,this._z=n,this._x0=i,this._y0=r,this._z0=s,this._x1=a,this._y1=o,this._z1=l,this._root=void 0}function Ic(e){for(var t={data:e.data},n=t;e=e.next;)n=n.next={data:e.data};return t}var Uc=Lc.prototype=Dc.prototype;function Fc(e){return function(){return e}}function Oc(e){return 1e-6*(e()-.5)}function Bc(e){return e.index}function kc(e,t){var n=e.get(t);if(!n)throw new Error("node not found: "+t);return n}function zc(e){var t,n,i,r,s,a,o,l=Bc,u=function(e){return 1/Math.min(s[e.source.index],s[e.target.index])},c=Fc(30),h=1;function d(i){for(var s=0,l=e.length;s1&&(_=d.y+d.vy-c.y-c.vy||Oc(o)),r>2&&(v=d.z+d.vz-c.z-c.vz||Oc(o)),g*=p=((p=Math.sqrt(g*g+_*_+v*v))-n[m])/p*i*t[m],_*=p,v*=p,d.vx-=g*(f=a[m]),r>1&&(d.vy-=_*f),r>2&&(d.vz-=v*f),c.vx+=g*(f=1-f),r>1&&(c.vy+=_*f),r>2&&(c.vz+=v*f)}function p(){if(i){var r,o,u=i.length,c=e.length,h=new Map(i.map((e,t)=>[l(e,t,i),e]));for(r=0,s=new Array(u);r"function"==typeof e)||Math.random,r=t.find(e=>[1,2,3].includes(e))||2,p()},d.links=function(t){return arguments.length?(e=t,p(),d):e},d.id=function(e){return arguments.length?(l=e,d):l},d.iterations=function(e){return arguments.length?(h=+e,d):h},d.strength=function(e){return arguments.length?(u="function"==typeof e?e:Fc(+e),f(),d):u},d.distance=function(e){return arguments.length?(c="function"==typeof e?e:Fc(+e),m(),d):c},d}Uc.copy=function(){var e,t,n=new Dc(this._x,this._y,this._z,this._x0,this._y0,this._z0,this._x1,this._y1,this._z1),i=this._root;if(!i)return n;if(!i.length)return n._root=Ic(i),n;for(e=[{source:i,target:n._root=new Array(8)}];i=e.pop();)for(var r=0;r<8;++r)(t=i.source[r])&&(t.length?e.push({source:t,target:i.target[r]=new Array(8)}):i.target[r]=Ic(t));return n},Uc.add=function(e){const t=+this._x.call(null,e),n=+this._y.call(null,e),i=+this._z.call(null,e);return wc(this.cover(t,n,i),t,n,i,e)},Uc.addAll=function(e){Array.isArray(e)||(e=Array.from(e));const t=e.length,n=new Float64Array(t),i=new Float64Array(t),r=new Float64Array(t);let s=1/0,a=1/0,o=1/0,l=-1/0,u=-1/0,c=-1/0;for(let h,d,p,f,m=0;ml&&(l=d),pu&&(u=p),fc&&(c=f));if(s>l||a>u||o>c)return this;this.cover(s,a,o).cover(l,u,c);for(let s=0;se||e>=a||r>t||t>=o||s>n||n>=l;)switch(c=(ng||(a=h.y0)>_||(o=h.z0)>v||(l=h.x1)=S)<<2|(t>=T)<<1|e>=x)&&(h=y[y.length-1],y[y.length-1]=y[y.length-1-d],y[y.length-1-d]=h)}else{var M=e-+this._x.call(null,b.data),E=t-+this._y.call(null,b.data),w=n-+this._z.call(null,b.data),A=M*M+E*E+w*w;if(A{if(!h.length)do{const s=h.data;Rc(e,t,n,this._x(s),this._y(s),this._z(s))<=i&&r.push(s)}while(h=h.next);return d>l||p>u||f>c||m=(l=(_+b)/2))?_=l:b=l,(d=a>=(u=(v+x)/2))?v=u:x=u,(p=o>=(c=(y+T)/2))?y=c:T=c,t=g,!(g=g[f=p<<2|d<<1|h]))return this;if(!g.length)break;(t[f+1&7]||t[f+2&7]||t[f+3&7]||t[f+4&7]||t[f+5&7]||t[f+6&7]||t[f+7&7])&&(n=t,m=f)}for(;g.data!==e;)if(i=g,!(g=g.next))return this;return(r=g.next)&&delete g.next,i?(r?i.next=r:delete i.next,this):t?(r?t[f]=r:delete t[f],(g=t[0]||t[1]||t[2]||t[3]||t[4]||t[5]||t[6]||t[7])&&g===(t[7]||t[6]||t[5]||t[4]||t[3]||t[2]||t[1]||t[0])&&!g.length&&(n?n[m]=g:this._root=g),this):(this._root=r,this)},Uc.removeAll=function(e){for(var t=0,n=e.length;t{}};function Gc(){for(var e,t=0,n=arguments.length,i={};t=0&&(t=e.slice(n+1),e=e.slice(0,n)),e&&!i.hasOwnProperty(e))throw new Error("unknown type: "+e);return{type:e,name:t}})),a=-1,o=s.length;if(!(arguments.length<2)){if(null!=t&&"function"!=typeof t)throw new Error("invalid callback: "+t);for(;++a0)for(var n,i,r=new Array(n),s=0;s=0&&t._call.call(void 0,e),t=t._next;--qc}()}finally{qc=0,function(){var e,t,n=$c,i=1/0;for(;n;)n._call?(i>n._time&&(i=n._time),e=n,n=n._next):(t=n._next,n._next=null,n=e?e._next=t:$c=t);Xc=e,lh(i)}(),Qc=0}}function oh(){var e=eh.now(),t=e-Zc;t>1e3&&(Jc-=t,Zc=e)}function lh(e){qc||(Yc&&(Yc=clearTimeout(Yc)),e-Qc>24?(e<1/0&&(Yc=setTimeout(ah,e-eh.now()-Jc)),Kc&&(Kc=clearInterval(Kc))):(Kc||(Zc=eh.now(),Kc=setInterval(oh,1e3)),qc=1,th(ah)))}rh.prototype=sh.prototype={constructor:rh,restart:function(e,t,n){if("function"!=typeof e)throw new TypeError("callback is not a function");n=(null==n?nh():+n)+(null==t?0:+t),this._next||Xc===this||(Xc?Xc._next=this:$c=this,Xc=this),this._call=e,this._time=n,lh()},stop:function(){this._call&&(this._call=null,this._time=1/0,lh())}};const uh=4294967296;function ch(e){return e.x}function hh(e){return e.y}function dh(e){return e.z}var ph=Math.PI*(3-Math.sqrt(5)),fh=20*Math.PI/(9+Math.sqrt(221));function mh(e,t){t=t||2;var n,i=Math.min(3,Math.max(1,Math.round(t))),r=1,s=.001,a=1-Math.pow(s,1/300),o=0,l=.6,u=new Map,c=sh(p),h=Gc("tick","end"),d=function(){let e=1;return()=>(e=(1664525*e+1013904223)%uh)/uh}();function p(){f(),h.call("tick",n),r1&&(null==c.fy?c.y+=c.vy*=l:(c.y=c.fy,c.vy=0)),i>2&&(null==c.fz?c.z+=c.vz*=l:(c.z=c.fz,c.vz=0));return n}function m(){for(var t,n=0,r=e.length;n1&&isNaN(t.y)||i>2&&isNaN(t.z)){var s=10*(i>2?Math.cbrt(.5+n):i>1?Math.sqrt(.5+n):n),a=n*ph,o=n*fh;1===i?t.x=s:2===i?(t.x=s*Math.cos(a),t.y=s*Math.sin(a)):(t.x=s*Math.sin(a)*Math.cos(o),t.y=s*Math.cos(a),t.z=s*Math.sin(a)*Math.sin(o))}(isNaN(t.vx)||i>1&&isNaN(t.vy)||i>2&&isNaN(t.vz))&&(t.vx=0,i>1&&(t.vy=0),i>2&&(t.vz=0))}}function g(t){return t.initialize&&t.initialize(e,d,i),t}return null==e&&(e=[]),m(),n={tick:f,restart:function(){return c.restart(p),n},stop:function(){return c.stop(),n},numDimensions:function(e){return arguments.length?(i=Math.min(3,Math.max(1,Math.round(e))),u.forEach(g),n):i},nodes:function(t){return arguments.length?(e=t,m(),u.forEach(g),n):e},alpha:function(e){return arguments.length?(r=+e,n):r},alphaMin:function(e){return arguments.length?(s=+e,n):s},alphaDecay:function(e){return arguments.length?(a=+e,n):+a},alphaTarget:function(e){return arguments.length?(o=+e,n):o},velocityDecay:function(e){return arguments.length?(l=1-e,n):1-l},randomSource:function(e){return arguments.length?(d=e,u.forEach(g),n):d},force:function(e,t){return arguments.length>1?(null==t?u.delete(e):u.set(e,g(t)),n):u.get(e)},find:function(){var t,n,r,s,a,o,l=Array.prototype.slice.call(arguments),u=l.shift()||0,c=(i>1?l.shift():null)||0,h=(i>2?l.shift():null)||0,d=l.shift()||1/0,p=0,f=e.length;for(d*=d,p=0;p1?(h.on(e,t),n):h.on(e)}}}function gh(){var e,t,n,i,r,s,a=Fc(-30),o=1,l=1/0,u=.81;function c(i){var s,a=e.length,o=(1===t?fc(e,ch):2===t?Tc(e,ch,hh):3===t?Lc(e,ch,hh,dh):null).visitAfter(d);for(r=i,s=0;s1&&(e.y=a/c),t>2&&(e.z=o/c)}else{(n=e).x=n.data.x,t>1&&(n.y=n.data.y),t>2&&(n.z=n.data.z);do{u+=s[n.data.index]}while(n=n.next)}e.value=u}function p(e,a,c,h,d){if(!e.value)return!0;var p=[c,h,d][t-1],f=e.x-n.x,m=t>1?e.y-n.y:0,g=t>2?e.z-n.z:0,_=p-a,v=f*f+m*m+g*g;if(_*_/u1&&0===m&&(v+=(m=Oc(i))*m),t>2&&0===g&&(v+=(g=Oc(i))*g),v1&&(n.vy+=m*e.value*r/v),t>2&&(n.vz+=g*e.value*r/v)),!0;if(!(e.length||v>=l)){(e.data!==n||e.next)&&(0===f&&(v+=(f=Oc(i))*f),t>1&&0===m&&(v+=(m=Oc(i))*m),t>2&&0===g&&(v+=(g=Oc(i))*g),v1&&(n.vy+=m*_),t>2&&(n.vz+=g*_))}while(e=e.next)}}return c.initialize=function(n,...r){e=n,i=r.find(e=>"function"==typeof e)||Math.random,t=r.find(e=>[1,2,3].includes(e))||2,h()},c.strength=function(e){return arguments.length?(a="function"==typeof e?e:Fc(+e),h(),c):a},c.distanceMin=function(e){return arguments.length?(o=e*e,c):Math.sqrt(o)},c.distanceMax=function(e){return arguments.length?(l=e*e,c):Math.sqrt(l)},c.theta=function(e){return arguments.length?(u=e*e,c):Math.sqrt(u)},c}function _h(e){!function(e){if(!e)throw new Error("Eventify cannot use falsy object as events subject");const t=["on","fire","off"];for(let n=0;n1&&(r=Array.prototype.slice.call(arguments,1));for(let e=0;e"u")return t=Object.create(null),e;if(t[n])if("function"!=typeof i)delete t[n];else{const e=t[n];for(let t=0;t1&&(r=Array.prototype.slice.call(arguments,1));for(let e=0;e>>19))+(e<<5)&4294967295)^e<<9))+(e<<3)&4294967295)^e>>>16),this.seed=e,(268435455&e)/268435456}return Yh=1,Jh.exports=e,Jh.exports.random=e,Jh.exports.randomIterator=function(t,n){var i=n||e();if("function"!=typeof i.next)throw new Error("customRandom does not match expected API: next() function is missing");return{forEach:function(e){var n,r,s;for(n=t.length-1;n>0;--n)r=i.next(n+1),s=t[r],t[r]=t[n],t[n]=s,e(s);t.length&&e(t[0])},shuffle:function(){var e,n,r;for(e=t.length-1;e>0;--e)n=i.next(e+1),r=t[n],t[n]=t[e],t[e]=r;return t}}},t.prototype.next=function(e){return Math.floor(this.nextDouble()*e)},t.prototype.nextDouble=i,t.prototype.uniform=i,t.prototype.gaussian=function(){var e,t,n;do{e=(t=2*this.nextDouble()-1)*t+(n=2*this.nextDouble()-1)*n}while(e>=1||0===e);return t*Math.sqrt(-2*Math.log(e)/e)},t.prototype.random=i,t.prototype.levy=function(){var e=1.5,t=Math.pow(n(2.5)*Math.sin(Math.PI*e/2)/(n(1.25)*e*Math.pow(2,.25)),1/e);return this.gaussian()*t/Math.pow(Math.abs(this.gaussian()),1/e)},Jh.exports}().random(42),x=[],T=[],S=m(l,b),M=g(x,l,b),E=v(l,b),w=_(l),A=[],R=new Map,C=0;L("nbody",function(){if(0===x.length)return;S.insertBodies(x);var e=x.length;for(;e--;){var t=x[e];t.isPinned||(t.reset(),S.updateBodyForce(t),w.update(t))}}),L("spring",function(){var e=T.length;for(;e--;)E.update(T[e])});var N={bodies:x,quadTree:S,springs:T,settings:l,addForce:L,removeForce:function(e){var t=A.indexOf(R.get(e));if(t<0)return;A.splice(t,1),R.delete(e)},getForces:function(){return R},step:function(){for(var e=0;enew f(e))(e);return x.push(t),t},removeBody:function(e){if(e){var t=x.indexOf(e);if(!(t<0))return x.splice(t,1),0===x.length&&M.reset(),!0}},addSpring:function(e,t,n,i){if(!e||!t)throw new Error("Cannot add null spring to force simulator");"number"!=typeof n&&(n=-1);var r=new u(e,t,n,i>=0?i:-1);return T.push(r),r},getTotalMovement:function(){return 0},removeSpring:function(e){if(e){var t=T.indexOf(e);return t>-1?(T.splice(t,1),!0):void 0}},getBestNewBodyPosition:function(e){return M.getBestNewPosition(e)},getBBox:P,getBoundingBox:P,invalidateBBox:function(){console.warn("invalidateBBox() is deprecated, bounds always recomputed on `getBBox()` call")},gravity:function(e){return void 0!==e?(l.gravity=e,S.options({gravity:e}),this):l.gravity},theta:function(e){return void 0!==e?(l.theta=e,S.options({theta:e}),this):l.theta},random:b};return function(e,t){for(var n in e)o(e,t,n)}(l,N),h(N),N;function P(){return M.update(),M.box}function L(e,t){if(R.has(e))throw new Error("Force "+e+" is already added");R.set(e,t),A.push(t)}};var e=function(){if(Ah)return Ch.exports;Ah=1;const e=Ph();function t(e,t){return`\n${i(e,t)}\n${n(e)}\nreturn {Body: Body, Vector: Vector};\n`}function n(t){let n=e(t),i=n("{var}",{join:", "});return`\nfunction Body(${i}) {\n this.isPinned = false;\n this.pos = new Vector(${i});\n this.force = new Vector();\n this.velocity = new Vector();\n this.mass = 1;\n\n this.springCount = 0;\n this.springLength = 0;\n}\n\nBody.prototype.reset = function() {\n this.force.reset();\n this.springCount = 0;\n this.springLength = 0;\n}\n\nBody.prototype.setPosition = function (${i}) {\n ${n("this.pos.{var} = {var} || 0;",{indent:2})}\n};`}function i(t,n){let i=e(t),r="";return n&&(r=`${i("\n\t var v{var};\n\tObject.defineProperty(this, '{var}', {\n\t set: function(v) { \n\t if (!Number.isFinite(v)) throw new Error('Cannot set non-numbers to {var}');\n\t v{var} = v; \n\t },\n\t get: function() { return v{var}; }\n\t});")}`),`function Vector(${i("{var}",{join:", "})}) {\n ${r}\n if (typeof arguments[0] === 'object') {\n // could be another vector\n let v = arguments[0];\n ${i('if (!Number.isFinite(v.{var})) throw new Error("Expected value is not a finite number at Vector constructor ({var})");',{indent:4})}\n ${i("this.{var} = v.{var};",{indent:4})}\n } else {\n ${i('this.{var} = typeof {var} === "number" ? {var} : 0;',{indent:4})}\n }\n }\n \n Vector.prototype.reset = function () {\n ${i("this.{var} = ",{join:""})}0;\n };`}return Ch.exports=function(e,n){let i=t(e,n),{Body:r}=new Function(i)();return r},Ch.exports.generateCreateBodyFunctionBody=t,Ch.exports.getVectorCode=i,Ch.exports.getBodyCode=n,Ch.exports}(),t=function(){if(Lh)return Dh.exports;Lh=1;const e=Ph(),t=Nh();function n(n){let l=e(n),u=Math.pow(2,n),c=`\n${o()}\n${a(n)}\n${i(n)}\n${s(n)}\n${r(n)}\n\nfunction createQuadTree(options, random) {\n options = options || {};\n options.gravity = typeof options.gravity === 'number' ? options.gravity : -1;\n options.theta = typeof options.theta === 'number' ? options.theta : 0.8;\n\n var gravity = options.gravity;\n var updateQueue = [];\n var insertStack = new InsertStack();\n var theta = options.theta;\n\n var nodesCache = [];\n var currentInCache = 0;\n var root = newNode();\n\n return {\n insertBodies: insertBodies,\n\n /**\n * Gets root node if it is present\n */\n getRoot: function() {\n return root;\n },\n\n updateBodyForce: update,\n\n options: function(newOptions) {\n if (newOptions) {\n if (typeof newOptions.gravity === 'number') {\n gravity = newOptions.gravity;\n }\n if (typeof newOptions.theta === 'number') {\n theta = newOptions.theta;\n }\n\n return this;\n }\n\n return {\n gravity: gravity,\n theta: theta\n };\n }\n };\n\n function newNode() {\n // To avoid pressure on GC we reuse nodes.\n var node = nodesCache[currentInCache];\n if (node) {\n${function(e){let t=[];for(let n=0;n {var}max) {var}max = pos.{var};",{indent:6})}\n }\n\n // Makes the bounds square.\n var maxSideLength = -Infinity;\n ${l("if ({var}max - {var}min > maxSideLength) maxSideLength = {var}max - {var}min ;",{indent:4})}\n\n currentInCache = 0;\n root = newNode();\n ${l("root.min_{var} = {var}min;",{indent:4})}\n ${l("root.max_{var} = {var}min + maxSideLength;",{indent:4})}\n\n i = bodies.length - 1;\n if (i >= 0) {\n root.body = bodies[i];\n }\n while (i--) {\n insert(bodies[i], root);\n }\n }\n\n function insert(newBody) {\n insertStack.reset();\n insertStack.push(root, newBody);\n\n while (!insertStack.isEmpty()) {\n var stackItem = insertStack.pop();\n var node = stackItem.node;\n var body = stackItem.body;\n\n if (!node.body) {\n // This is internal node. Update the total mass of the node and center-of-mass.\n ${l("var {var} = body.pos.{var};",{indent:8})}\n node.mass += body.mass;\n ${l("node.mass_{var} += body.mass * {var};",{indent:8})}\n\n // Recursively insert the body in the appropriate quadrant.\n // But first find the appropriate quadrant.\n var quadIdx = 0; // Assume we are in the 0's quad.\n ${l("var min_{var} = node.min_{var};",{indent:8})}\n ${l("var max_{var} = (min_{var} + node.max_{var}) / 2;",{indent:8})}\n\n${function(){let e=[],i=Array(8+1).join(" ");for(let r=0;r max_${t(r)}) {`),e.push(i+` quadIdx = quadIdx + ${Math.pow(2,r)};`),e.push(i+` min_${t(r)} = max_${t(r)};`),e.push(i+` max_${t(r)} = node.max_${t(r)};`),e.push(i+"}");return e.join("\n")}()}\n\n var child = getChild(node, quadIdx);\n\n if (!child) {\n // The node is internal but this quadrant is not taken. Add\n // subnode to it.\n child = newNode();\n ${l("child.min_{var} = min_{var};",{indent:10})}\n ${l("child.max_{var} = max_{var};",{indent:10})}\n child.body = body;\n\n setChild(node, quadIdx, child);\n } else {\n // continue searching in this quadrant.\n insertStack.push(child, body);\n }\n } else {\n // We are trying to add to the leaf node.\n // We have to convert current leaf into internal node\n // and continue adding two nodes.\n var oldBody = node.body;\n node.body = null; // internal nodes do not cary bodies\n\n if (isSamePosition(oldBody.pos, body.pos)) {\n // Prevent infinite subdivision by bumping one node\n // anywhere in this quadrant\n var retriesCount = 3;\n do {\n var offset = random.nextDouble();\n ${l("var d{var} = (node.max_{var} - node.min_{var}) * offset;",{indent:12})}\n\n ${l("oldBody.pos.{var} = node.min_{var} + d{var};",{indent:12})}\n retriesCount -= 1;\n // Make sure we don't bump it out of the box. If we do, next iteration should fix it\n } while (retriesCount > 0 && isSamePosition(oldBody.pos, body.pos));\n\n if (retriesCount === 0 && isSamePosition(oldBody.pos, body.pos)) {\n // This is very bad, we ran out of precision.\n // if we do not return from the method we'll get into\n // infinite loop here. So we sacrifice correctness of layout, and keep the app running\n // Next layout iteration should get larger bounding box in the first step and fix this\n return;\n }\n }\n // Next iteration should subdivide node further.\n insertStack.push(node, oldBody);\n insertStack.push(node, body);\n }\n }\n }\n}\nreturn createQuadTree;\n\n`;return c}function i(t){let n=e(t);return`\n function isSamePosition(point1, point2) {\n ${n("var d{var} = Math.abs(point1.{var} - point2.{var});",{indent:2})}\n \n return ${n("d{var} < 1e-8",{join:" && "})};\n } \n`}function r(e){var t=Math.pow(2,e);return`\nfunction setChild(node, idx, child) {\n ${function(){let e=[];for(let n=0;n 0) {\n return this.stack[--this.popIdx];\n }\n },\n reset: function () {\n this.popIdx = 0;\n }\n};\n\nfunction InsertStackElement(node, body) {\n this.node = node; // QuadTree node\n this.body = body; // physical body which needs to be inserted to node\n}\n"}return Dh.exports=function(e){let t=n(e);return new Function(t)()},Dh.exports.generateQuadTreeFunctionBody=n,Dh.exports.getInsertStackCode=o,Dh.exports.getQuadNodeCode=a,Dh.exports.isSamePosition=i,Dh.exports.getChildBodyCode=s,Dh.exports.setChildBodyCode=r,Dh.exports}(),n=function(){if(Ih)return Uh.exports;Ih=1,Uh.exports=function(e){let n=t(e);return new Function("bodies","settings","random",n)},Uh.exports.generateFunctionBody=t;const e=Ph();function t(t){let n=e(t);return`\n var boundingBox = {\n ${n("min_{var}: 0, max_{var}: 0,",{indent:4})}\n };\n\n return {\n box: boundingBox,\n\n update: updateBoundingBox,\n\n reset: resetBoundingBox,\n\n getBestNewPosition: function (neighbors) {\n var ${n("base_{var} = 0",{join:", "})};\n\n if (neighbors.length) {\n for (var i = 0; i < neighbors.length; ++i) {\n let neighborPos = neighbors[i].pos;\n ${n("base_{var} += neighborPos.{var};",{indent:10})}\n }\n\n ${n("base_{var} /= neighbors.length;",{indent:8})}\n } else {\n ${n("base_{var} = (boundingBox.min_{var} + boundingBox.max_{var}) / 2;",{indent:8})}\n }\n\n var springLength = settings.springLength;\n return {\n ${n("{var}: base_{var} + (random.nextDouble() - 0.5) * springLength,",{indent:8})}\n };\n }\n };\n\n function updateBoundingBox() {\n var i = bodies.length;\n if (i === 0) return; // No bodies - no borders.\n\n ${n("var max_{var} = -Infinity;",{indent:4})}\n ${n("var min_{var} = Infinity;",{indent:4})}\n\n while(i--) {\n // this is O(n), it could be done faster with quadtree, if we check the root node bounds\n var bodyPos = bodies[i].pos;\n ${n("if (bodyPos.{var} < min_{var}) min_{var} = bodyPos.{var};",{indent:6})}\n ${n("if (bodyPos.{var} > max_{var}) max_{var} = bodyPos.{var};",{indent:6})}\n }\n\n ${n("boundingBox.min_{var} = min_{var};",{indent:4})}\n ${n("boundingBox.max_{var} = max_{var};",{indent:4})}\n }\n\n function resetBoundingBox() {\n ${n("boundingBox.min_{var} = boundingBox.max_{var} = 0;",{indent:4})}\n }\n`}return Uh.exports}(),i=function(){if(Fh)return Oh.exports;Fh=1;const e=Ph();function t(t){return`\n if (!Number.isFinite(options.dragCoefficient)) throw new Error('dragCoefficient is not a finite number');\n\n return {\n update: function(body) {\n ${e(t)("body.force.{var} -= options.dragCoefficient * body.velocity.{var};",{indent:6})}\n }\n };\n`}return Oh.exports=function(e){let n=t(e);return new Function("options",n)},Oh.exports.generateCreateDragForceFunctionBody=t,Oh.exports}(),r=function(){if(Bh)return kh.exports;Bh=1;const e=Ph();function t(t){let n=e(t);return`\n if (!Number.isFinite(options.springCoefficient)) throw new Error('Spring coefficient is not a number');\n if (!Number.isFinite(options.springLength)) throw new Error('Spring length is not a number');\n\n return {\n /**\n * Updates forces acting on a spring\n */\n update: function (spring) {\n var body1 = spring.from;\n var body2 = spring.to;\n var length = spring.length < 0 ? options.springLength : spring.length;\n ${n("var d{var} = body2.pos.{var} - body1.pos.{var};",{indent:6})}\n var r = Math.sqrt(${n("d{var} * d{var}",{join:" + "})});\n\n if (r === 0) {\n ${n("d{var} = (random.nextDouble() - 0.5) / 50;",{indent:8})}\n r = Math.sqrt(${n("d{var} * d{var}",{join:" + "})});\n }\n\n var d = r - length;\n var coefficient = ((spring.coefficient > 0) ? spring.coefficient : options.springCoefficient) * d / r;\n\n ${n("body1.force.{var} += coefficient * d{var}",{indent:6})};\n body1.springCount += 1;\n body1.springLength += r;\n\n ${n("body2.force.{var} -= coefficient * d{var}",{indent:6})};\n body2.springCount += 1;\n body2.springLength += r;\n }\n };\n`}return kh.exports=function(e){let n=t(e);return new Function("options","random",n)},kh.exports.generateCreateSpringForceFunctionBody=t,kh.exports}(),s=function(){if(zh)return Xh.exports;zh=1;const e=Ph();function t(t){let n=e(t);return`\n var length = bodies.length;\n if (length === 0) return 0;\n\n ${n("var d{var} = 0, t{var} = 0;",{indent:2})}\n\n for (var i = 0; i < length; ++i) {\n var body = bodies[i];\n if (body.isPinned) continue;\n\n if (adaptiveTimeStepWeight && body.springCount) {\n timeStep = (adaptiveTimeStepWeight * body.springLength/body.springCount);\n }\n\n var coeff = timeStep / body.mass;\n\n ${n("body.velocity.{var} += coeff * body.force.{var};",{indent:4})}\n ${n("var v{var} = body.velocity.{var};",{indent:4})}\n var v = Math.sqrt(${n("v{var} * v{var}",{join:" + "})});\n\n if (v > 1) {\n // We normalize it so that we move within timeStep range. \n // for the case when v <= 1 - we let velocity to fade out.\n ${n("body.velocity.{var} = v{var} / v;",{indent:6})}\n }\n\n ${n("d{var} = timeStep * body.velocity.{var};",{indent:4})}\n\n ${n("body.pos.{var} += d{var};",{indent:4})}\n\n ${n("t{var} += Math.abs(d{var});",{indent:4})}\n }\n\n return (${n("t{var} * t{var}",{join:" + "})})/length;\n`}return Xh.exports=function(e){let n=t(e);return new Function("bodies","timeStep","adaptiveTimeStepWeight",n)},Xh.exports.generateIntegratorFunctionBody=t,Xh.exports}(),a={};function o(e,t,n){if(e.hasOwnProperty(n)&&"function"!=typeof t[n]){var i=Number.isFinite(e[n]);t[n]=i?function(i){if(void 0!==i){if(!Number.isFinite(i))throw new Error("Value of "+n+" should be a valid number.");return e[n]=i,t}return e[n]}:function(i){return void 0!==i?(e[n]=i,t):e[n]}}}return Kh}var td=function(){if(Qh)return Rh.exports;Qh=1,Rh.exports=function(n,i){if(!n)throw new Error("Graph structure cannot be undefined");var r=(i&&i.createSimulator||ed())(i);if(Array.isArray(i))throw new Error("Physics settings is expected to be an object");var s=n.version>19?function(e){var t=n.getLinks(e);return t?1+t.size/3:1}:function(e){var t=n.getLinks(e);return t?1+t.length/3:1};i&&"function"==typeof i.nodeMass&&(s=i.nodeMass);var a=new Map,o={},l=0,u=r.settings.springTransform||t;l=0,n.forEachNode(function(e){m(e.id),l+=1}),n.forEachLink(_),n.on("changed",f);var c=!1,h={step:function(){if(0===l)return d(!0),!0;var e=r.step();h.lastMove=e,h.fire("step");var t=e/l<=.01;return d(t),t},getNodePosition:function(e){return b(e).pos},setNodePosition:function(e){var t=b(e);t.setPosition.apply(t,Array.prototype.slice.call(arguments,1))},getLinkPosition:function(e){var t=o[e];if(t)return{from:t.from.pos,to:t.to.pos}},getGraphRect:function(){return r.getBBox()},forEachBody:p,pinNode:function(e,t){b(e.id).isPinned=!!t},isNodePinned:function(e){return b(e.id).isPinned},dispose:function(){n.off("changed",f),h.fire("disposed")},getBody:function(e){return a.get(e)},getSpring:function(e,t){var i;if(void 0===t)i="object"!=typeof e?e:e.id;else{var r=n.hasLink(e,t);if(!r)return;i=r.id}return o[i]},getForceVectorLength:function(){var e=0,t=0;return p(function(n){e+=Math.abs(n.force.x),t+=Math.abs(n.force.y)}),Math.sqrt(e*e+t*t)},simulator:r,graph:n,lastMove:0};return e(h),h;function d(e){var t;c!==e&&(c=e,t=e,h.fire("stable",t))}function p(e){a.forEach(e)}function f(e){for(var t=0;t=t||n<0||h&&e-u>=s}function m(){var e=od();if(f(e))return g(e);o=setTimeout(m,function(e){var n=t-(e-l);return h?Ed(n,s-(e-u)):n}(e))}function g(e){return o=void 0,d&&i?p(e):(i=r=void 0,a)}function _(){var e=od(),n=f(e);if(i=arguments,r=this,l=e,n){if(void 0===o)return function(e){return u=e,o=setTimeout(m,t),c?p(e):a}(l);if(h)return clearTimeout(o),o=setTimeout(m,t),p(l)}return void 0===o&&(o=setTimeout(m,t)),a}return t=Sd(t)||0,id(n)&&(c=!!n.leading,s=(h="maxWait"in n)?Md(Sd(n.maxWait)||0,t):s,d="trailing"in n?!!n.trailing:d),_.cancel=function(){void 0!==o&&clearTimeout(o),u=0,i=l=r=o=void 0},_.flush=function(){return void 0===o?a:g(od())},_}function Ad(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n=t)&&(n=t);else{let i=-1;for(let r of e)null!=(r=t(r,++i,e))&&(n=r)&&(n=r)}return n}function Od(e,t){let n;if(void 0===t)for(const t of e)null!=t&&(n>t||void 0===n&&t>=t)&&(n=t);else{let i=-1;for(let r of e)null!=(r=t(r,++i,e))&&(n>r||void 0===n&&r>=r)&&(n=r)}return n}function Bd(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n1&&(n-=1),n<1/6?e+6*(t-e)*n:n<.5?t:n<2/3?e+(t-e)*(2/3-n)*6:e}if(e=Ap(e,360),t=Ap(t,100),n=Ap(n,100),0===t)i=r=s=n;else{var o=n<.5?n*(1+t):n+t-n*t,l=2*n-o;i=a(l,o,e+1/3),r=a(l,o,e),s=a(l,o,e-1/3)}return{r:255*i,g:255*r,b:255*s}}(e.h,i,s),a=!0,o="hsl"),e.hasOwnProperty("a")&&(n=e.a));return n=wp(n),{ok:a,format:e.format||o,r:Math.min(255,Math.max(t.r,0)),g:Math.min(255,Math.max(t.g,0)),b:Math.min(255,Math.max(t.b,0)),a:n}}(e);this._originalInput=e,this._r=n.r,this._g=n.g,this._b=n.b,this._a=n.a,this._roundA=Math.round(100*this._a)/100,this._format=t.format||n.format,this._gradientType=t.gradientType,this._r<1&&(this._r=Math.round(this._r)),this._g<1&&(this._g=Math.round(this._g)),this._b<1&&(this._b=Math.round(this._b)),this._ok=n.ok}function lp(e,t,n){e=Ap(e,255),t=Ap(t,255),n=Ap(n,255);var i,r,s=Math.max(e,t,n),a=Math.min(e,t,n),o=(s+a)/2;if(s==a)i=r=0;else{var l=s-a;switch(r=o>.5?l/(2-s-a):l/(s+a),s){case e:i=(t-n)/l+(t>1)+720)%360;--t;)i.h=(i.h+r)%360,s.push(op(i));return s}function Sp(e,t){t=t||6;for(var n=op(e).toHsv(),i=n.h,r=n.s,s=n.v,a=[],o=1/t;t--;)a.push(op({h:i,s:r,v:s})),s=(s+o)%1;return a}op.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var e=this.toRgb();return(299*e.r+587*e.g+114*e.b)/1e3},getLuminance:function(){var e,t,n,i=this.toRgb();return e=i.r/255,t=i.g/255,n=i.b/255,.2126*(e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4))+.7152*(t<=.03928?t/12.92:Math.pow((t+.055)/1.055,2.4))+.0722*(n<=.03928?n/12.92:Math.pow((n+.055)/1.055,2.4))},setAlpha:function(e){return this._a=wp(e),this._roundA=Math.round(100*this._a)/100,this},toHsv:function(){var e=up(this._r,this._g,this._b);return{h:360*e.h,s:e.s,v:e.v,a:this._a}},toHsvString:function(){var e=up(this._r,this._g,this._b),t=Math.round(360*e.h),n=Math.round(100*e.s),i=Math.round(100*e.v);return 1==this._a?"hsv("+t+", "+n+"%, "+i+"%)":"hsva("+t+", "+n+"%, "+i+"%, "+this._roundA+")"},toHsl:function(){var e=lp(this._r,this._g,this._b);return{h:360*e.h,s:e.s,l:e.l,a:this._a}},toHslString:function(){var e=lp(this._r,this._g,this._b),t=Math.round(360*e.h),n=Math.round(100*e.s),i=Math.round(100*e.l);return 1==this._a?"hsl("+t+", "+n+"%, "+i+"%)":"hsla("+t+", "+n+"%, "+i+"%, "+this._roundA+")"},toHex:function(e){return cp(this._r,this._g,this._b,e)},toHexString:function(e){return"#"+this.toHex(e)},toHex8:function(e){return function(e,t,n,i,r){var s=[Np(Math.round(e).toString(16)),Np(Math.round(t).toString(16)),Np(Math.round(n).toString(16)),Np(Lp(i))];if(r&&s[0].charAt(0)==s[0].charAt(1)&&s[1].charAt(0)==s[1].charAt(1)&&s[2].charAt(0)==s[2].charAt(1)&&s[3].charAt(0)==s[3].charAt(1))return s[0].charAt(0)+s[1].charAt(0)+s[2].charAt(0)+s[3].charAt(0);return s.join("")}(this._r,this._g,this._b,this._a,e)},toHex8String:function(e){return"#"+this.toHex8(e)},toRgb:function(){return{r:Math.round(this._r),g:Math.round(this._g),b:Math.round(this._b),a:this._a}},toRgbString:function(){return 1==this._a?"rgb("+Math.round(this._r)+", "+Math.round(this._g)+", "+Math.round(this._b)+")":"rgba("+Math.round(this._r)+", "+Math.round(this._g)+", "+Math.round(this._b)+", "+this._roundA+")"},toPercentageRgb:function(){return{r:Math.round(100*Ap(this._r,255))+"%",g:Math.round(100*Ap(this._g,255))+"%",b:Math.round(100*Ap(this._b,255))+"%",a:this._a}},toPercentageRgbString:function(){return 1==this._a?"rgb("+Math.round(100*Ap(this._r,255))+"%, "+Math.round(100*Ap(this._g,255))+"%, "+Math.round(100*Ap(this._b,255))+"%)":"rgba("+Math.round(100*Ap(this._r,255))+"%, "+Math.round(100*Ap(this._g,255))+"%, "+Math.round(100*Ap(this._b,255))+"%, "+this._roundA+")"},toName:function(){return 0===this._a?"transparent":!(this._a<1)&&(Ep[cp(this._r,this._g,this._b,!0)]||!1)},toFilter:function(e){var t="#"+hp(this._r,this._g,this._b,this._a),n=t,i=this._gradientType?"GradientType = 1, ":"";if(e){var r=op(e);n="#"+hp(r._r,r._g,r._b,r._a)}return"progid:DXImageTransform.Microsoft.gradient("+i+"startColorstr="+t+",endColorstr="+n+")"},toString:function(e){var t=!!e;e=e||this._format;var n=!1,i=this._a<1&&this._a>=0;return t||!i||"hex"!==e&&"hex6"!==e&&"hex3"!==e&&"hex4"!==e&&"hex8"!==e&&"name"!==e?("rgb"===e&&(n=this.toRgbString()),"prgb"===e&&(n=this.toPercentageRgbString()),"hex"!==e&&"hex6"!==e||(n=this.toHexString()),"hex3"===e&&(n=this.toHexString(!0)),"hex4"===e&&(n=this.toHex8String(!0)),"hex8"===e&&(n=this.toHex8String()),"name"===e&&(n=this.toName()),"hsl"===e&&(n=this.toHslString()),"hsv"===e&&(n=this.toHsvString()),n||this.toHexString()):"name"===e&&0===this._a?this.toName():this.toRgbString()},clone:function(){return op(this.toString())},_applyModification:function(e,t){var n=e.apply(null,[this].concat([].slice.call(t)));return this._r=n._r,this._g=n._g,this._b=n._b,this.setAlpha(n._a),this},lighten:function(){return this._applyModification(mp,arguments)},brighten:function(){return this._applyModification(gp,arguments)},darken:function(){return this._applyModification(_p,arguments)},desaturate:function(){return this._applyModification(dp,arguments)},saturate:function(){return this._applyModification(pp,arguments)},greyscale:function(){return this._applyModification(fp,arguments)},spin:function(){return this._applyModification(vp,arguments)},_applyCombination:function(e,t){return e.apply(null,[this].concat([].slice.call(t)))},analogous:function(){return this._applyCombination(Tp,arguments)},complement:function(){return this._applyCombination(yp,arguments)},monochromatic:function(){return this._applyCombination(Sp,arguments)},splitcomplement:function(){return this._applyCombination(xp,arguments)},triad:function(){return this._applyCombination(bp,[3])},tetrad:function(){return this._applyCombination(bp,[4])}},op.fromRatio=function(e,t){if("object"==rp(e)){var n={};for(var i in e)e.hasOwnProperty(i)&&(n[i]="a"===i?e[i]:Pp(e[i]));e=n}return op(e,t)},op.equals=function(e,t){return!(!e||!t)&&op(e).toRgbString()==op(t).toRgbString()},op.random=function(){return op.fromRatio({r:Math.random(),g:Math.random(),b:Math.random()})},op.mix=function(e,t,n){n=0===n?0:n||50;var i=op(e).toRgb(),r=op(t).toRgb(),s=n/100;return op({r:(r.r-i.r)*s+i.r,g:(r.g-i.g)*s+i.g,b:(r.b-i.b)*s+i.b,a:(r.a-i.a)*s+i.a})}, +// =4.5;break;case"AAlarge":r=s>=3;break;case"AAAsmall":r=s>=7}return r},op.mostReadable=function(e,t,n){var i,r,s,a,o=null,l=0;r=(n=n||{}).includeFallbackColors,s=n.level,a=n.size;for(var u=0;ul&&(l=i,o=op(t[u]));return op.isReadable(e,o,{level:s,size:a})||!r?o:(n.includeFallbackColors=!1,op.mostReadable(e,["#fff","#000"],n))};var Mp=op.names={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"0ff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"00f",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",burntsienna:"ea7e5d",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"0ff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"f0f",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"789",lightslategrey:"789",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"0f0",limegreen:"32cd32",linen:"faf0e6",magenta:"f0f",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"663399",red:"f00",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"fff",whitesmoke:"f5f5f5",yellow:"ff0",yellowgreen:"9acd32"},Ep=op.hexNames=function(e){var t={};for(var n in e)e.hasOwnProperty(n)&&(t[e[n]]=n);return t}(Mp);function wp(e){return e=parseFloat(e),(isNaN(e)||e<0||e>1)&&(e=1),e}function Ap(e,t){(function(e){return"string"==typeof e&&-1!=e.indexOf(".")&&1===parseFloat(e)})(e)&&(e="100%");var n=function(e){return"string"==typeof e&&-1!=e.indexOf("%")}(e);return e=Math.min(t,Math.max(0,parseFloat(e))),n&&(e=parseInt(e*t,10)/100),Math.abs(e-t)<1e-6?1:e%t/parseFloat(t)}function Rp(e){return Math.min(1,Math.max(0,e))}function Cp(e){return parseInt(e,16)}function Np(e){return 1==e.length?"0"+e:""+e}function Pp(e){return e<=1&&(e=100*e+"%"),e}function Lp(e){return Math.round(255*parseFloat(e)).toString(16)}function Dp(e){return Cp(e)/255}var Ip,Up,Fp,Op=(Up="[\\s|\\(]+("+(Ip="(?:[-\\+]?\\d*\\.\\d+%?)|(?:[-\\+]?\\d+%?)")+")[,|\\s]+("+Ip+")[,|\\s]+("+Ip+")\\s*\\)?",Fp="[\\s|\\(]+("+Ip+")[,|\\s]+("+Ip+")[,|\\s]+("+Ip+")[,|\\s]+("+Ip+")\\s*\\)?",{CSS_UNIT:new RegExp(Ip),rgb:new RegExp("rgb"+Up),rgba:new RegExp("rgba"+Fp),hsl:new RegExp("hsl"+Up),hsla:new RegExp("hsla"+Fp),hsv:new RegExp("hsv"+Up),hsva:new RegExp("hsva"+Fp),hex3:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex6:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,hex4:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex8:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/});function Bp(e){return!!Op.CSS_UNIT.exec(e)}function kp(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n1&&void 0!==arguments[1]?arguments[1]:{},r=i.dataBindAttr,s=void 0===r?"__data":r,a=i.objBindAttr,o=void 0===a?"__threeObj":a;return Gp(this,t),qp(n=Vp(this,t),"scene",void 0),jp(n,hf,void 0),jp(n,df,void 0),n.scene=e,Wp(hf,n,s),Wp(df,n,o),n.onRemoveObj(function(){}),n}return Zp(t,e),Xp(t,[{key:"onCreateObj",value:function(e){var n=this;return nf(t,"onCreateObj",this)([function(t){var i=e(t);return t[Hp(df,n)]=i,i[Hp(hf,n)]=t,n.scene.add(i),i}]),this}},{key:"onRemoveObj",value:function(e){var n=this;return nf(t,"onRemoveObj",this)([function(i,r){var s=nf(t,"getData",n)([i]);e(i,r),n.scene.remove(i),uf(i),delete s[Hp(df,n)]}]),this}}])}(ep),ff=function(e){return isNaN(e)?parseInt(op(e).toHex(),16):e},mf=function(e){return isNaN(e)?op(e).getAlpha():1},gf=function e(){var t=new Dd,n=[],i=[],r=np;function s(e){let s=t.get(e);if(void 0===s){if(r!==np)return r;t.set(e,s=n.push(e)-1)}return i[s%i.length]}return s.domain=function(e){if(!arguments.length)return n.slice();n=[],t=new Dd;for(const i of e)t.has(i)||t.set(i,n.push(i)-1);return s},s.range=function(e){return arguments.length?(i=Array.from(e),s):i.slice()},s.unknown=function(e){return arguments.length?(r=e,s):r},s.copy=function(){return e(n,i).unknown(r)},tp.apply(s,arguments),s}(ip);function _f(e,t,n){t&&"string"==typeof n&&e.filter(function(e){return!e[n]}).forEach(function(e){e[n]=gf(t(e))})}var vf=window.THREE?window.THREE:{Group:ci,Mesh:Wr,MeshLambertMaterial:Qs,Color:_i,BufferGeometry:vr,BufferAttribute:nr,Matrix4:Fn,Vector3:dn,SphereGeometry:Bs,CylinderGeometry:Ts,TubeGeometry:ks,ConeGeometry:Ss,Line:class extends ui{constructor(e=new vr,t=new as){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(){const e=this.geometry;if(null===e.index){const t=e.attributes.position,n=[0];for(let e=1,i=t.count;e0){const n=e[t[0]];if(void 0!==n){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e0&&(d.fire("changed",o),o.length=0)}function E(e){if("function"!=typeof e)throw new Error("Function is expected to iterate over graph nodes. You passed "+e);for(var t=n.values(),i=t.next();!i.done;){if(e(i.value))return!0;i=t.next()}}},forcelayout:nd},bf=(new vf.BufferGeometry).setAttribute?"setAttribute":"addAttribute",xf=(new vf.BufferGeometry).applyMatrix4?"applyMatrix4":"applyMatrix",Tf=Pd({props:{jsonUrl:{onChange:function(e,t){var n=this;e&&!t.fetchingJson&&(t.fetchingJson=!0,t.onLoading(),fetch(e).then(function(e){return e.json()}).then(function(e){t.fetchingJson=!1,t.onFinishLoading(e),n.graphData(e)}))},triggerUpdate:!1},graphData:{default:{nodes:[],links:[]},onChange:function(e,t){t.engineRunning=!1}},numDimensions:{default:3,onChange:function(e,t){var n=t.d3ForceLayout.force("charge");function i(e,t){e.forEach(function(e){delete e[t],delete e["v".concat(t)]})}n&&n.strength(e>2?-60:-30),e<3&&i(t.graphData.nodes,"z"),e<2&&i(t.graphData.nodes,"y")}},dagMode:{onChange:function(e,t){!e&&"d3"===t.forceEngine&&(t.graphData.nodes||[]).forEach(function(e){return e.fx=e.fy=e.fz=void 0})}},dagLevelDistance:{},dagNodeFilter:{default:function(e){return!0}},onDagError:{triggerUpdate:!1},nodeRelSize:{default:4},nodeId:{default:"id"},nodeVal:{default:"val"},nodeResolution:{default:8},nodeColor:{default:"color"},nodeAutoColorBy:{},nodeOpacity:{default:.75},nodeVisibility:{default:!0},nodeThreeObject:{},nodeThreeObjectExtend:{default:!1},nodePositionUpdate:{triggerUpdate:!1},linkSource:{default:"source"},linkTarget:{default:"target"},linkVisibility:{default:!0},linkColor:{default:"color"},linkAutoColorBy:{},linkOpacity:{default:.2},linkWidth:{},linkResolution:{default:6},linkCurvature:{default:0,triggerUpdate:!1},linkCurveRotation:{default:0,triggerUpdate:!1},linkMaterial:{},linkThreeObject:{},linkThreeObjectExtend:{default:!1},linkPositionUpdate:{triggerUpdate:!1},linkDirectionalArrowLength:{default:0},linkDirectionalArrowColor:{},linkDirectionalArrowRelPos:{default:.5,triggerUpdate:!1},linkDirectionalArrowResolution:{default:8},linkDirectionalParticles:{default:0},linkDirectionalParticleSpeed:{default:.01,triggerUpdate:!1},linkDirectionalParticleOffset:{default:0,triggerUpdate:!1},linkDirectionalParticleWidth:{default:.5},linkDirectionalParticleColor:{},linkDirectionalParticleResolution:{default:4},linkDirectionalParticleThreeObject:{},forceEngine:{default:"d3"},d3AlphaMin:{default:0},d3AlphaDecay:{default:.0228,triggerUpdate:!1,onChange:function(e,t){t.d3ForceLayout.alphaDecay(e)}},d3AlphaTarget:{default:0,triggerUpdate:!1,onChange:function(e,t){t.d3ForceLayout.alphaTarget(e)}},d3VelocityDecay:{default:.4,triggerUpdate:!1,onChange:function(e,t){t.d3ForceLayout.velocityDecay(e)}},ngraphPhysics:{default:{timeStep:20,gravity:-1.2,theta:.8,springLength:30,springCoefficient:8e-4,dragCoefficient:.02}},warmupTicks:{default:0,triggerUpdate:!1},cooldownTicks:{default:1/0,triggerUpdate:!1},cooldownTime:{default:15e3,triggerUpdate:!1},onLoading:{default:function(){},triggerUpdate:!1},onFinishLoading:{default:function(){},triggerUpdate:!1},onUpdate:{default:function(){},triggerUpdate:!1},onFinishUpdate:{default:function(){},triggerUpdate:!1},onEngineTick:{default:function(){},triggerUpdate:!1},onEngineStop:{default:function(){},triggerUpdate:!1}},methods:{refresh:function(e){return e._flushObjects=!0,e._rerender(),this},d3Force:function(e,t,n){return void 0===n?e.d3ForceLayout.force(t):(e.d3ForceLayout.force(t,n),this)},d3ReheatSimulation:function(e){return e.d3ForceLayout.alpha(1),this.resetCountdown(),this},resetCountdown:function(e){return e.cntTicks=0,e.startTickTime=new Date,e.engineRunning=!0,this},tickFrame:function(e){var t,n,i,r,s,a="ngraph"!==e.forceEngine;return e.engineRunning&&function(){++e.cntTicks>e.cooldownTicks||new Date-e.startTickTime>e.cooldownTime||a&&e.d3AlphaMin>0&&e.d3ForceLayout.alpha()0){var f=o.x-s.x,m=o.y-s.y||0,g=(new vf.Vector3).subVectors(h,c),_=g.clone().multiplyScalar(l).cross(0!==f||0!==m?new vf.Vector3(0,0,1):new vf.Vector3(0,1,0)).applyAxisAngle(g.normalize(),p).add((new vf.Vector3).addVectors(c,h).divideScalar(2));u=new vf.QuadraticBezierCurve3(c,_,h)}else{var v=70*l,y=-p,b=y+Math.PI/2;u=new vf.CubicBezierCurve3(c,new vf.Vector3(v*Math.cos(b),v*Math.sin(b),0).add(c),new vf.Vector3(v*Math.cos(y),v*Math.sin(y),0).add(c),h)}t.__curve=u}else t.__curve=null}}e.linkDataMapper.entries().forEach(function(t){var i=tf(t,2),r=i[0],l=i[1];if(l){var u=a?r:e.layout.getLinkPosition(e.layout.graph.getLink(r.source,r.target).id),c=u[a?"source":"from"],h=u[a?"target":"to"];if(c&&h&&c.hasOwnProperty("x")&&h.hasOwnProperty("x")){o(r);var d=s(r);if(!e.linkPositionUpdate||!e.linkPositionUpdate(d?l.children[1]:l,{start:{x:c.x,y:c.y,z:c.z},end:{x:h.x,y:h.y,z:h.z}},r)||d){var p=30,f=r.__curve,m=l.children.length?l.children[0]:l;if("Line"===m.type){if(f){var g=f.getPoints(p);m.geometry.getAttribute("position").array.length!==3*g.length&&m.geometry[bf]("position",new vf.BufferAttribute(new Float32Array(3*g.length),3)),m.geometry.setFromPoints(g)}else{var _=m.geometry.getAttribute("position");_&&_.array&&6===_.array.length||m.geometry[bf]("position",_=new vf.BufferAttribute(new Float32Array(6),3)),_.array[0]=c.x,_.array[1]=c.y||0,_.array[2]=c.z||0,_.array[3]=h.x,_.array[4]=h.y||0,_.array[5]=h.z||0,_.needsUpdate=!0}m.geometry.computeBoundingSphere()}else if("Mesh"===m.type)if(f){m.geometry.type.match(/^Tube(Buffer)?Geometry$/)||(m.position.set(0,0,0),m.rotation.set(0,0,0),m.scale.set(1,1,1));var v=Math.ceil(10*n(r))/10/2,y=new vf.TubeGeometry(f,p,v,e.linkResolution,!1);m.geometry.dispose(),m.geometry=y}else{if(!m.geometry.type.match(/^Cylinder(Buffer)?Geometry$/)){var b=Math.ceil(10*n(r))/10/2,x=new vf.CylinderGeometry(b,b,1,e.linkResolution,1,!1);x[xf]((new vf.Matrix4).makeTranslation(0,.5,0)),x[xf]((new vf.Matrix4).makeRotationX(Math.PI/2)),m.geometry.dispose(),m.geometry=x}var T=new vf.Vector3(c.x,c.y||0,c.z||0),S=new vf.Vector3(h.x,h.y||0,h.z||0),M=T.distanceTo(S);m.position.x=T.x,m.position.y=T.y,m.position.z=T.z,m.scale.z=M,m.parent.localToWorld(S),m.lookAt(S)}}}}})}(),t=Ld(e.linkDirectionalArrowRelPos),n=Ld(e.linkDirectionalArrowLength),i=Ld(e.nodeVal),e.arrowDataMapper.entries().forEach(function(r){var s=tf(r,2),o=s[0],l=s[1];if(l){var u=a?o:e.layout.getLinkPosition(e.layout.graph.getLink(o.source,o.target).id),c=u[a?"source":"from"],h=u[a?"target":"to"];if(c&&h&&c.hasOwnProperty("x")&&h.hasOwnProperty("x")){var d=Math.cbrt(Math.max(0,i(c)||1))*e.nodeRelSize,p=Math.cbrt(Math.max(0,i(h)||1))*e.nodeRelSize,f=n(o),m=t(o),g=o.__curve?function(e){return o.__curve.getPoint(e)}:function(e){var t=function(e,t,n,i){return t[e]+(n[e]-t[e])*i||0};return{x:t("x",c,h,e),y:t("y",c,h,e),z:t("z",c,h,e)}},_=o.__curve?o.__curve.getLength():Math.sqrt(["x","y","z"].map(function(e){return Math.pow((h[e]||0)-(c[e]||0),2)}).reduce(function(e,t){return e+t},0)),v=d+f+(_-d-p-f)*m,y=g(v/_),b=g((v-f)/_);["x","y","z"].forEach(function(e){return l.position[e]=b[e]});var x=$p(vf.Vector3,rf(["x","y","z"].map(function(e){return y[e]})));l.parent.localToWorld(x),l.lookAt(x)}}}),r=Ld(e.linkDirectionalParticleSpeed),s=Ld(e.linkDirectionalParticleOffset),e.graphData.links.forEach(function(t){var n=e.particlesDataMapper.getObj(t),i=n&&n.children,o=t.__singleHopPhotonsObj&&t.__singleHopPhotonsObj.children;if(o&&o.length||i&&i.length){var l=a?t:e.layout.getLinkPosition(e.layout.graph.getLink(t.source,t.target).id),u=l[a?"source":"from"],c=l[a?"target":"to"];if(u&&c&&u.hasOwnProperty("x")&&c.hasOwnProperty("x")){var h=r(t),d=Math.abs(s(t)),p=t.__curve?function(e){return t.__curve.getPoint(e)}:function(e){var t=function(e,t,n,i){return t[e]+(n[e]-t[e])*i||0};return{x:t("x",u,c,e),y:t("y",u,c,e),z:t("z",u,c,e)}};[].concat(rf(i||[]),rf(o||[])).forEach(function(e,t){var n="singleHopPhotons"===e.parent.__linkThreeObjType;if(e.hasOwnProperty("__progressRatio")||(e.__progressRatio=n?0:(t+d)/i.length),e.__progressRatio+=h,e.__progressRatio>=1){if(n)return e.parent.remove(e),void cf(e);e.__progressRatio=e.__progressRatio%1}var r=e.__progressRatio,s=p(r);"SphereGeometry"!==e.geometry.type&&e.lookAt(s.x,s.y,s.z),["x","y","z"].forEach(function(t){return e.position[t]=s[t]})})}}}),this},emitParticle:function(e,t){if(t&&e.graphData.links.includes(t)){if(!t.__singleHopPhotonsObj){var n=new vf.Group;n.__linkThreeObjType="singleHopPhotons",t.__singleHopPhotonsObj=n,e.graphScene.add(n)}var i=Ld(e.linkDirectionalParticleThreeObject)(t);if(i&&e.linkDirectionalParticleThreeObject===i&&(i=i.clone()),!i){var r=Ld(e.linkDirectionalParticleWidth),s=Math.ceil(10*r(t))/10/2,a=e.linkDirectionalParticleResolution,o=new vf.SphereGeometry(s,a,a),l=Ld(e.linkColor),u=Ld(e.linkDirectionalParticleColor)(t)||l(t)||"#f0f0f0",c=new vf.Color(ff(u)),h=3*e.linkOpacity,d=new vf.MeshLambertMaterial({color:c,transparent:!0,opacity:h});i=new vf.Mesh(o,d)}t.__singleHopPhotonsObj.add(i)}return this},getGraphBbox:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(){return!0};if(!e.initialised)return null;var n=function e(n){var i=[];if(n.geometry){n.geometry.computeBoundingBox();var r=new vf.Box3;r.copy(n.geometry.boundingBox).applyMatrix4(n.matrixWorld),i.push(r)}return i.concat.apply(i,rf((n.children||[]).filter(function(e){return!e.hasOwnProperty("__graphObjType")||"node"===e.__graphObjType&&t(e.__data)}).map(e)))}(e.graphScene);return n.length?Object.assign.apply(Object,rf(["x","y","z"].map(function(e){return qp({},e,[Od(n,function(t){return t.min[e]}),Fd(n,function(t){return t.max[e]})])}))):null}},stateInit:function(){return{d3ForceLayout:mh().force("link",zc()).force("charge",gh()).force("center",cc()).force("dagRadial",null).stop(),engineRunning:!1}},init:function(e,t){t.graphScene=e,t.nodeDataMapper=new pf(e,{objBindAttr:"__threeObj"}),t.linkDataMapper=new pf(e,{objBindAttr:"__lineObj"}),t.arrowDataMapper=new pf(e,{objBindAttr:"__arrowObj"}),t.particlesDataMapper=new pf(e,{objBindAttr:"__photonsObj"})},update:function(e,t){var n=function(e){return e.some(function(e){return t.hasOwnProperty(e)})};if(e.engineRunning=!1,"function"==typeof e.onUpdate&&e.onUpdate(),null!==e.nodeAutoColorBy&&n(["nodeAutoColorBy","graphData","nodeColor"])&&_f(e.graphData.nodes,Ld(e.nodeAutoColorBy),e.nodeColor),null!==e.linkAutoColorBy&&n(["linkAutoColorBy","graphData","linkColor"])&&_f(e.graphData.links,Ld(e.linkAutoColorBy),e.linkColor),e._flushObjects||n(["graphData","nodeThreeObject","nodeThreeObjectExtend","nodeVal","nodeColor","nodeVisibility","nodeRelSize","nodeResolution","nodeOpacity"])){var i=Ld(e.nodeThreeObject),r=Ld(e.nodeThreeObjectExtend),s=Ld(e.nodeVal),a=Ld(e.nodeColor),o=Ld(e.nodeVisibility),l={},u={};(e._flushObjects||n(["nodeThreeObject","nodeThreeObjectExtend"]))&&e.nodeDataMapper.clear(),e.nodeDataMapper.onCreateObj(function(t){var n,s=i(t),a=r(t);return s&&e.nodeThreeObject===s&&(s=s.clone()),s&&!a?n=s:((n=new vf.Mesh).__graphDefaultObj=!0,s&&a&&n.add(s)),n.__graphObjType="node",n}).onUpdateObj(function(t,n){if(t.__graphDefaultObj){var i=s(n)||1,r=Math.cbrt(i)*e.nodeRelSize,o=e.nodeResolution;t.geometry.type.match(/^Sphere(Buffer)?Geometry$/)&&t.geometry.parameters.radius===r&&t.geometry.parameters.widthSegments===o||(l.hasOwnProperty(i)||(l[i]=new vf.SphereGeometry(r,o,o)),t.geometry.dispose(),t.geometry=l[i]);var c=a(n),h=new vf.Color(ff(c||"#ffffaa")),d=e.nodeOpacity*mf(c);"MeshLambertMaterial"===t.material.type&&t.material.color.equals(h)&&t.material.opacity===d||(u.hasOwnProperty(c)||(u[c]=new vf.MeshLambertMaterial({color:h,transparent:!0,opacity:d})),t.material.dispose(),t.material=u[c])}}).digest(e.graphData.nodes.filter(o))}if(e._flushObjects||n(["graphData","linkThreeObject","linkThreeObjectExtend","linkMaterial","linkColor","linkWidth","linkVisibility","linkResolution","linkOpacity","linkDirectionalArrowLength","linkDirectionalArrowColor","linkDirectionalArrowResolution","linkDirectionalParticles","linkDirectionalParticleWidth","linkDirectionalParticleColor","linkDirectionalParticleResolution","linkDirectionalParticleThreeObject"])){var c=Ld(e.linkThreeObject),h=Ld(e.linkThreeObjectExtend),d=Ld(e.linkMaterial),p=Ld(e.linkVisibility),f=Ld(e.linkColor),m=Ld(e.linkWidth),g={},_={},v={},y=e.graphData.links.filter(p);if((e._flushObjects||n(["linkThreeObject","linkThreeObjectExtend","linkWidth"]))&&e.linkDataMapper.clear(),e.linkDataMapper.onRemoveObj(function(e){var t=e.__data&&e.__data.__singleHopPhotonsObj;t&&(t.parent.remove(t),cf(t),delete e.__data.__singleHopPhotonsObj)}).onCreateObj(function(t){var n,i,r=c(t),s=h(t);if(r&&e.linkThreeObject===r&&(r=r.clone()),!r||s)if(!!m(t))n=new vf.Mesh;else{var a=new vf.BufferGeometry;a[bf]("position",new vf.BufferAttribute(new Float32Array(6),3)),n=new vf.Line(a)}return r?s?((i=new vf.Group).__graphDefaultObj=!0,i.add(n),i.add(r)):i=r:(i=n).__graphDefaultObj=!0,i.renderOrder=10,i.__graphObjType="link",i}).onUpdateObj(function(t,n){if(t.__graphDefaultObj){var i=t.children.length?t.children[0]:t,r=Math.ceil(10*m(n))/10,s=!!r;if(s){var a=r/2,o=e.linkResolution;if(!i.geometry.type.match(/^Cylinder(Buffer)?Geometry$/)||i.geometry.parameters.radiusTop!==a||i.geometry.parameters.radialSegments!==o){if(!g.hasOwnProperty(r)){var l=new vf.CylinderGeometry(a,a,1,o,1,!1);l[xf]((new vf.Matrix4).makeTranslation(0,.5,0)),l[xf]((new vf.Matrix4).makeRotationX(Math.PI/2)),g[r]=l}i.geometry.dispose(),i.geometry=g[r]}}var u=d(n);if(u)i.material=u;else{var c=f(n),h=new vf.Color(ff(c||"#f0f0f0")),p=e.linkOpacity*mf(c),y=s?"MeshLambertMaterial":"LineBasicMaterial";if(i.material.type!==y||!i.material.color.equals(h)||i.material.opacity!==p){var b=s?_:v;b.hasOwnProperty(c)||(b[c]=new vf[y]({color:h,transparent:p<1,opacity:p,depthWrite:p>=1})),i.material.dispose(),i.material=b[c]}}}}).digest(y),e.linkDirectionalArrowLength||t.hasOwnProperty("linkDirectionalArrowLength")){var b=Ld(e.linkDirectionalArrowLength),x=Ld(e.linkDirectionalArrowColor);e.arrowDataMapper.onCreateObj(function(){var e=new vf.Mesh(void 0,new vf.MeshLambertMaterial({transparent:!0}));return e.__linkThreeObjType="arrow",e}).onUpdateObj(function(t,n){var i=b(n),r=e.linkDirectionalArrowResolution;if(!t.geometry.type.match(/^Cone(Buffer)?Geometry$/)||t.geometry.parameters.height!==i||t.geometry.parameters.radialSegments!==r){var s=new vf.ConeGeometry(.25*i,i,r);s.translate(0,i/2,0),s.rotateX(Math.PI/2),t.geometry.dispose(),t.geometry=s}var a=x(n)||f(n)||"#f0f0f0";t.material.color=new vf.Color(ff(a)),t.material.opacity=3*e.linkOpacity*mf(a)}).digest(y.filter(b))}if(e.linkDirectionalParticles||t.hasOwnProperty("linkDirectionalParticles")){var T=Ld(e.linkDirectionalParticles),S=Ld(e.linkDirectionalParticleWidth),M=Ld(e.linkDirectionalParticleColor),E=Ld(e.linkDirectionalParticleThreeObject),w={},A={};e.particlesDataMapper.onCreateObj(function(){var e=new vf.Group;return e.__linkThreeObjType="photons",e.__photonDataMapper=new pf(e),e}).onUpdateObj(function(t,n){var i,r,s=!!t.children.length&&t.children[0],a=E(n);if(a)i=a.geometry,r=a.material;else{var o=Math.ceil(10*S(n))/10/2,l=e.linkDirectionalParticleResolution;s&&s.geometry.parameters.radius===o&&s.geometry.parameters.widthSegments===l?i=s.geometry:(A.hasOwnProperty(o)||(A[o]=new vf.SphereGeometry(o,l,l)),i=A[o]);var u=M(n)||f(n)||"#f0f0f0",c=new vf.Color(ff(u)),h=3*e.linkOpacity;s&&s.material.color.equals(c)&&s.material.opacity===h?r=s.material:(w.hasOwnProperty(u)||(w[u]=new vf.MeshLambertMaterial({color:c,transparent:!0,opacity:h})),r=w[u])}s&&(s.geometry!==i&&s.geometry.dispose(),s.material!==r&&s.material.dispose());var d=Math.round(Math.abs(T(n)));t.__photonDataMapper.id(function(e){return e.idx}).onCreateObj(function(){return new vf.Mesh(i,r)}).onUpdateObj(function(e){e.geometry=i,e.material=r}).digest(rf(new Array(d)).map(function(e,t){return{idx:t}}))}).digest(y.filter(T))}}if(e._flushObjects=!1,n(["graphData","nodeId","linkSource","linkTarget","numDimensions","forceEngine","dagMode","dagNodeFilter","dagLevelDistance"])){e.engineRunning=!1,e.graphData.links.forEach(function(t){t.source=t[e.linkSource],t.target=t[e.linkTarget]});var R,C="ngraph"!==e.forceEngine;if(C){(R=e.d3ForceLayout).stop().alpha(1).numDimensions(e.numDimensions).nodes(e.graphData.nodes);var N=e.d3ForceLayout.force("link");N&&N.id(function(t){return t[e.nodeId]}).links(e.graphData.links);var P=e.dagMode&&function(e,t){var n=e.nodes,i=e.links,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},s=r.nodeFilter,a=void 0===s?function(){return!0}:s,o=r.onLoopError,l=void 0===o?function(e){throw"Invalid DAG structure! Found cycle in node path: ".concat(e.join(" -> "),".")}:o,u={};n.forEach(function(e){return u[t(e)]={data:e,out:[],depth:-1,skip:!a(e)}}),i.forEach(function(e){var n=e.source,i=e.target,r=l(n),s=l(i);if(!u.hasOwnProperty(r))throw"Missing source node with id: ".concat(r);if(!u.hasOwnProperty(s))throw"Missing target node with id: ".concat(s);var a=u[r],o=u[s];function l(e){return"object"===af(e)?t(e):e}a.out.push(o)});var c=[];return function e(n){for(var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,s=function(){var s=n[a];if(-1!==i.indexOf(s)){var o=[].concat(rf(i.slice(i.indexOf(s))),[s]).map(function(e){return t(e.data)});return c.some(function(e){return e.length===o.length&&e.every(function(e,t){return e===o[t]})})||(c.push(o),l(o)),1}r>s.depth&&(s.depth=r,e(s.out,[].concat(rf(i),[s]),r+(s.skip?0:1)))},a=0,o=n.length;a1&&(c.vy+=d*m),s>2&&(c.vz+=p*m)}}function c(){if(r){var t,n=r.length;for(a=new Array(n),o=new Array(n),t=0;t[1,2,3].includes(e))||2,c()},u.strength=function(e){return arguments.length?(l="function"==typeof e?e:Fc(+e),c(),u):l},u.radius=function(t){return arguments.length?(e="function"==typeof t?t:Fc(+t),c(),u):e},u.x=function(e){return arguments.length?(t=+e,u):t},u.y=function(e){return arguments.length?(n=+e,u):n},u.z=function(e){return arguments.length?(i=+e,u):i},u}(function(t){var n=P[t[e.nodeId]]||-1;return("radialin"===e.dagMode?L-n:n)*D}).strength(function(t){return e.dagNodeFilter(t)?1:0}):null)}else{var O=yf.graph();e.graphData.nodes.forEach(function(t){O.addNode(t[e.nodeId])}),e.graphData.links.forEach(function(e){O.addLink(e.source,e.target)}),R=yf.forcelayout(O,function(e){for(var t=1;t0&&e.d3ForceLayout.alpha()2&&void 0!==arguments[2]&&arguments[2],n=function(n){function i(){var n;Gp(this,i);for(var r=arguments.length,s=new Array(r),a=0;a1&&void 0!==arguments[1]?arguments[1]:Object);return Object.keys(e()).forEach(function(e){return n.prototype[e]=function(){var t,n=(t=this.__kapsuleInstance)[e].apply(t,arguments);return n===this.__kapsuleInstance?this:n}}),n}(Tf,(window.THREE?window.THREE:{Group:ci}).Group,!0);const Mf=["alphaMap","alphaTest","anisotropy","anisotropyMap","anisotropyRotation","aoMap","aoMapIntensity","attenuationColor","attenuationDistance","bumpMap","clearcoat","clearcoatMap","clearcoatNormalMap","clearcoatNormalScale","clearcoatRoughness","color","dispersion","displacementMap","emissive","emissiveIntensity","emissiveMap","envMap","envMapIntensity","gradientMap","ior","iridescence","iridescenceIOR","iridescenceMap","iridescenceThicknessMap","lightMap","lightMapIntensity","map","matcap","metalness","metalnessMap","normalMap","normalScale","opacity","roughness","roughnessMap","sheen","sheenColor","sheenColorMap","sheenRoughnessMap","shininess","specular","specularColor","specularColorMap","specularIntensity","specularIntensityMap","specularMap","thickness","transmission","transmissionMap"],Ef=new WeakMap;class wf{constructor(e){this.renderObjects=new WeakMap,this.hasNode=this.containsNode(e),this.hasAnimation=!0===e.object.isSkinnedMesh,this.refreshUniforms=Mf,this.renderId=0}firstInitialization(e){return!1===this.renderObjects.has(e)&&(this.getRenderObjectData(e),!0)}needsVelocity(e){const t=e.getMRT();return null!==t&&t.has("velocity")}getRenderObjectData(e){let t=this.renderObjects.get(e);if(void 0===t){const{geometry:n,material:i,object:r}=e;if(t={material:this.getMaterialData(i),geometry:{id:n.id,attributes:this.getAttributesData(n.attributes),indexId:n.index?n.index.id:null,indexVersion:n.index?n.index.version:null,drawRange:{start:n.drawRange.start,count:n.drawRange.count}},worldMatrix:r.matrixWorld.clone()},r.center&&(t.center=r.center.clone()),r.morphTargetInfluences&&(t.morphTargetInfluences=r.morphTargetInfluences.slice()),null!==e.bundle&&(t.version=e.bundle.version),t.material.transmission>0){const{width:n,height:i}=e.context;t.bufferWidth=n,t.bufferHeight=i}t.lights=this.getLightsData(e.lightsNode.getLights()),this.renderObjects.set(e,t)}return t}getAttributesData(e){const t={};for(const n in e){const i=e[n];t[n]={id:i.id,version:i.version}}return t}containsNode(e){const t=e.material;for(const e in t)if(t[e]&&t[e].isNode)return!0;return!!(e.context.modelViewMatrix||e.context.modelNormalViewMatrix||e.context.getAO||e.context.getShadow)}getMaterialData(e){const t={};for(const n of this.refreshUniforms){const i=e[n];null!=i&&("object"==typeof i&&void 0!==i.clone?!0===i.isTexture?t[n]={id:i.id,version:i.version}:t[n]=i.clone():t[n]=i)}return t}equals(e,t){const{object:n,material:i,geometry:r}=e,s=this.getRenderObjectData(e);if(!0!==s.worldMatrix.equals(n.matrixWorld))return s.worldMatrix.copy(n.matrixWorld),!1;const a=s.material;for(const e in a){const t=a[e],n=i[e];if(void 0!==t.equals){if(!1===t.equals(n))return t.copy(n),!1}else if(!0===n.isTexture){if(t.id!==n.id||t.version!==n.version)return t.id=n.id,t.version=n.version,!1}else if(t!==n)return a[e]=n,!1}if(a.transmission>0){const{width:t,height:n}=e.context;if(s.bufferWidth!==t||s.bufferHeight!==n)return s.bufferWidth=t,s.bufferHeight=n,!1}const o=s.geometry,l=r.attributes,u=o.attributes,c=Object.keys(u),h=Object.keys(l);if(o.id!==r.id)return o.id=r.id,!1;if(c.length!==h.length)return s.geometry.attributes=this.getAttributesData(l),!1;for(const e of c){const t=u[e],n=l[e];if(void 0===n)return delete u[e],!1;if(t.id!==n.id||t.version!==n.version)return t.id=n.id,t.version=n.version,!1}const d=r.index,p=o.indexId,f=o.indexVersion,m=d?d.id:null,g=d?d.version:null;if(p!==m||f!==g)return o.indexId=m,o.indexVersion=g,!1;if(o.drawRange.start!==r.drawRange.start||o.drawRange.count!==r.drawRange.count)return o.drawRange.start=r.drawRange.start,o.drawRange.count=r.drawRange.count,!1;if(s.morphTargetInfluences){let e=!1;for(let t=0;t{const n=e.match(t);if(!n)return null;const i=n[1]||n[2]||"",r=n[3].split("?")[0],s=parseInt(n[4],10),a=parseInt(n[5],10);return{fn:i,file:r.split("/").pop(),line:s,column:a}}).filter(e=>e&&!Af.some(t=>t.test(e.file)))}(e||(new Error).stack)}getLocation(){if(0===this.stack.length)return"[Unknown location]";const e=this.stack[0],t=e.fn;return`${t?`"${t}()" at `:""}"${e.file}:${e.line}"`}getError(e){if(0===this.stack.length)return e;const t=this.stack.map(e=>{const t=`${e.file}:${e.line}:${e.column}`;return e.fn?` at ${e.fn} (${t})`:` at ${t}`}).join("\n");return`${e}\n${t}`}}function Cf(e,t=0){let n=3735928559^t,i=1103547991^t;if(e instanceof Array)for(let t,r=0;r>>16,2246822507),n^=Math.imul(i^i>>>13,3266489909),i=Math.imul(i^i>>>16,2246822507),i^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&i)+(n>>>0)}const Nf=e=>Cf(e),Pf=e=>Cf(e),Lf=(...e)=>Cf(e),Df=new Map([[1,"float"],[2,"vec2"],[3,"vec3"],[4,"vec4"],[9,"mat3"],[16,"mat4"]]),If=new WeakMap;function Uf(e){return Df.get(e)}function Ff(e){if(null==e)return null;const t=typeof e;return!0===e.isNode?"node":"number"===t?"float":"boolean"===t?"bool":"string"===t?"string":"function"===t?"shader":!0===e.isVector2?"vec2":!0===e.isVector3?"vec3":!0===e.isVector4?"vec4":!0===e.isMatrix2?"mat2":!0===e.isMatrix3?"mat3":!0===e.isMatrix4?"mat4":!0===e.isColor?"color":e instanceof ArrayBuffer?"ArrayBuffer":null}function Of(e,...t){const n=e?e.slice(-4):void 0;return 1===t.length&&("vec2"===n?t=[t[0],t[0]]:"vec3"===n?t=[t[0],t[0],t[0]]:"vec4"===n&&(t=[t[0],t[0],t[0],t[0]])),"color"===e?new _i(...t):"vec2"===n?new cn(...t):"vec3"===n?new dn(...t):"vec4"===n?new Pn(...t):"mat2"===n?new $a(...t):"mat3"===n?new mn(...t):"mat4"===n?new Fn(...t):"bool"===e?t[0]||!1:"float"===e||"int"===e||"uint"===e?t[0]||0:"string"===e?t[0]||"":"ArrayBuffer"===e?(i=t[0],Uint8Array.from(atob(i),e=>e.charCodeAt(0)).buffer):null;var i}function Bf(e){let t=If.get(e);return void 0===t&&(t={},If.set(e,t)),t}const kf="vertex",zf="none",Vf="frame",Gf="render",Hf="object",jf="readOnly",Wf="writeOnly",$f="readWrite",Xf=["setup","analyze","generate"],qf=["fragment","vertex","compute"],Yf=["x","y","z","w"],Kf={analyze:"setup",generate:"analyze"};let Zf=0;class Qf extends Zt{static get type(){return"Node"}constructor(e=null){super(),this.nodeType=e,this.updateType=zf,this.updateBeforeType=zf,this.updateAfterType=zf,this.uuid=un.generateUUID(),this.version=0,this.name="",this.global=!1,this.parents=!1,this.isNode=!0,this._beforeNodes=null,this._cacheKey=null,this._cacheKeyVersion=0,Object.defineProperty(this,"id",{value:Zf++}),this.stackTrace=null,!0===Qf.captureStackTrace&&(this.stackTrace=new Rf)}set needsUpdate(e){!0===e&&this.version++}get type(){return this.constructor.type}onUpdate(e,t){return this.updateType=t,this.update=e.bind(this),this}onFrameUpdate(e){return this.onUpdate(e,Vf)}onRenderUpdate(e){return this.onUpdate(e,Gf)}onObjectUpdate(e){return this.onUpdate(e,Hf)}onReference(e){return this.updateReference=e.bind(this),this}updateReference(){return this}isGlobal(){return this.global}*getChildren(){for(const{childNode:e}of this._getChildren())yield e}dispose(){this.dispatchEvent({type:"dispose"})}traverse(e){e(this);for(const t of this.getChildren())t.traverse(e)}_getChildren(e=new Set){const t=[];e.add(this);for(const n of Object.getOwnPropertyNames(this)){const i=this[n];if(!0!==n.startsWith("_")&&!e.has(i))if(!0===Array.isArray(i))for(let e=0;e0&&(e.inputNodes=n)}deserialize(e){if(void 0!==e.inputNodes){const t=e.meta.nodes;for(const n in e.inputNodes)if(Array.isArray(e.inputNodes[n])){const i=[];for(const r of e.inputNodes[n])i.push(t[r]);this[n]=i}else if("object"==typeof e.inputNodes[n]){const i={};for(const r in e.inputNodes[n]){const s=e.inputNodes[n][r];i[r]=t[s]}this[n]=i}else{const i=e.inputNodes[n];this[n]=t[i]}}}toJSON(e){const{uuid:t,type:n}=this,i=void 0===e||"string"==typeof e;i&&(e={textures:{},images:{},nodes:{}});let r=e.nodes[t];function s(e){const t=[];for(const n in e){const i=e[n];delete i.metadata,t.push(i)}return t}if(void 0===r&&(r={uuid:t,type:n,meta:e,metadata:{version:4.7,type:"Node",generator:"Node.toJSON"}},!0!==i&&(e.nodes[r.uuid]=r),this.serialize(r),delete r.meta),i){const t=s(e.textures),n=s(e.images),i=s(e.nodes);t.length>0&&(r.textures=t),n.length>0&&(r.images=n),i.length>0&&(r.nodes=i)}return r}}Qf.captureStackTrace=!1;class Jf extends Qf{static get type(){return"ArrayElementNode"}constructor(e,t){super(),this.node=e,this.indexNode=t,this.isArrayElementNode=!0}getNodeType(e){return this.node.getElementType(e)}getMemberType(e,t){return this.node.getMemberType(e,t)}generate(e){const t=this.indexNode.getNodeType(e);return`${this.node.build(e)}[ ${this.indexNode.build(e,!e.isVector(t)&&e.isInteger(t)?t:"uint")} ]`}}class em extends Qf{static get type(){return"ConvertNode"}constructor(e,t){super(),this.node=e,this.convertTo=t}getNodeType(e){const t=this.node.getNodeType(e);let n=null;for(const i of this.convertTo.split("|"))null!==n&&e.getTypeLength(t)!==e.getTypeLength(i)||(n=i);return n}serialize(e){super.serialize(e),e.convertTo=this.convertTo}deserialize(e){super.deserialize(e),this.convertTo=e.convertTo}generate(e,t){const n=this.node,i=this.getNodeType(e),r=n.build(e,i);return e.format(r,i,t)}}class tm extends Qf{static get type(){return"TempNode"}constructor(e=null){super(e),this.isTempNode=!0}hasDependencies(e){return e.getDataFromNode(this).usageCount>1}build(e,t){if("generate"===e.getBuildStage()){const n=e.getVectorType(this.getNodeType(e,t)),i=e.getDataFromNode(this);if(void 0!==i.propertyName)return e.format(i.propertyName,n,t);if("void"!==n&&"void"!==t&&this.hasDependencies(e)){const r=super.build(e,n),s=e.getVarFromNode(this,null,n),a=e.getPropertyName(s);return e.addLineFlowCode(`${a} = ${r}`,this),i.snippet=r,i.propertyName=a,e.format(i.propertyName,n,t)}}return super.build(e,t)}}class nm extends tm{static get type(){return"JoinNode"}constructor(e=[],t=null){super(t),this.nodes=e}getNodeType(e){return null!==this.nodeType?e.getVectorType(this.nodeType):e.getTypeFromLength(this.nodes.reduce((t,n)=>t+e.getTypeLength(n.getNodeType(e)),0))}generate(e,t){const n=this.getNodeType(e),i=e.getTypeLength(n),r=this.nodes,s=e.getComponentType(n),a=[];let o=0;for(const t of r){if(o>=i){qt(`TSL: Length of parameters exceeds maximum length of function '${n}()' type.`,this.stackTrace);break}let r,l=t.getNodeType(e),u=e.getTypeLength(l);o+u>i&&(qt(`TSL: Length of '${n}()' data exceeds maximum length of output type.`,this.stackTrace),u=i-o,l=e.getTypeFromLength(u)),o+=u,r=t.build(e,l);if(e.getComponentType(l)!==s){const t=e.getTypeFromLength(u,s);r=e.format(r,l,t)}a.push(r)}const l=`${e.getType(n)}( ${a.join(", ")} )`;return e.format(l,n,t)}}const im=Yf.join("");class rm extends Qf{static get type(){return"SplitNode"}constructor(e,t="x"){super(),this.node=e,this.components=t,this.isSplitNode=!0}getVectorLength(){let e=this.components.length;for(const t of this.components)e=Math.max(Yf.indexOf(t)+1,e);return e}getComponentType(e){return e.getComponentType(this.node.getNodeType(e))}getNodeType(e){return e.getTypeFromLength(this.components.length,this.getComponentType(e))}getScope(){return this.node.getScope()}generate(e,t){const n=this.node,i=e.getTypeLength(n.getNodeType(e));let r=null;if(i>1){let s=null;this.getVectorLength()>=i&&(s=e.getTypeFromLength(this.getVectorLength(),this.getComponentType(e)));const a=n.build(e,s);r=this.components.length===i&&this.components===im.slice(0,this.components.length)?e.format(a,s,t):e.format(`${a}.${this.components}`,this.getNodeType(e),t)}else r=n.build(e,t);return r}serialize(e){super.serialize(e),e.components=this.components}deserialize(e){super.deserialize(e),this.components=e.components}}class sm extends tm{static get type(){return"SetNode"}constructor(e,t,n){super(),this.sourceNode=e,this.components=t,this.targetNode=n}getNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{sourceNode:t,components:n,targetNode:i}=this,r=this.getNodeType(e),s=e.getComponentType(i.getNodeType(e)),a=e.getTypeFromLength(n.length,s),o=i.build(e,a),l=t.build(e,r),u=e.getTypeLength(r),c=[];for(let e=0;e(e=>e.replace(/r|s/g,"x").replace(/g|t/g,"y").replace(/b|p/g,"z").replace(/a|q/g,"w"))(e).split("").sort().join("");Qf.prototype.assign=function(...e){if(!0!==this.isStackNode)return null!==hm?hm.assign(this,...e):qt("TSL: No stack defined for assign operation. Make sure the assign is inside a Fn().",new Rf),this;{const t=dm.get("assign");return this.addToStack(t(...e))}},Qf.prototype.toVarIntent=function(){return this},Qf.prototype.get=function(e){return new cm(this,e)};const mm={};function gm(e,t,n){mm[e]=mm[t]=mm[n]={get(){this._cache=this._cache||{};let t=this._cache[e];return void 0===t&&(t=new rm(this,e),this._cache[e]=t),t},set(t){this[e].assign(Vm(t))}};const i=e.toUpperCase(),r=t.toUpperCase(),s=n.toUpperCase();Qf.prototype["set"+i]=Qf.prototype["set"+r]=Qf.prototype["set"+s]=function(t){const n=fm(e);return new sm(this,n,Vm(t))},Qf.prototype["flip"+i]=Qf.prototype["flip"+r]=Qf.prototype["flip"+s]=function(){const t=fm(e);return new am(this,t)}}const _m=["x","y","z","w"],vm=["r","g","b","a"],ym=["s","t","p","q"];for(let e=0;e<4;e++){let t=_m[e],n=vm[e],i=ym[e];gm(t,n,i);for(let r=0;r<4;r++){t=_m[e]+_m[r],n=vm[e]+vm[r],i=ym[e]+ym[r],gm(t,n,i);for(let s=0;s<4;s++){t=_m[e]+_m[r]+_m[s],n=vm[e]+vm[r]+vm[s],i=ym[e]+ym[r]+ym[s],gm(t,n,i);for(let a=0;a<4;a++)t=_m[e]+_m[r]+_m[s]+_m[a],n=vm[e]+vm[r]+vm[s]+vm[a],i=ym[e]+ym[r]+ym[s]+ym[a],gm(t,n,i)}}}for(let e=0;e<32;e++)mm[e]={get(){this._cache=this._cache||{};let t=this._cache[e];return void 0===t&&(t=new Jf(this,new um(e,"uint")),this._cache[e]=t),t},set(t){this[e].assign(Vm(t))}};Object.defineProperties(Qf.prototype,mm);const bm=new WeakMap,xm=function(e,t=null){for(const n in e)e[n]=Vm(e[n],t);return e},Tm=function(e,t=null){const n=e.length;for(let i=0;io?(qt(`TSL: "${n}" parameter length exceeds limit.`,new Rf),t.slice(0,o)):t}return null===t?s=(...t)=>r(new e(...jm(u(t)))):null!==n?(n=Vm(n),s=(...i)=>r(new e(t,...jm(u(i)),n))):s=(...n)=>r(new e(t,...jm(u(n)))),s.setParameterLength=(...e)=>(1===e.length?a=o=e[0]:2===e.length&&([a,o]=e),s),s.setName=e=>(l=e,s),s},Mm=function(e,...t){return new e(...jm(t))};class Em extends Qf{constructor(e,t){super(),this.shaderNode=e,this.rawInputs=t,this.isShaderCallNodeInternal=!0}getNodeType(e){return this.shaderNode.nodeType||this.getOutputNode(e).getNodeType(e)}getElementType(e){return this.getOutputNode(e).getElementType(e)}getMemberType(e,t){return this.getOutputNode(e).getMemberType(e,t)}call(e){const{shaderNode:t,rawInputs:n}=this,i=e.getNodeProperties(t),r=e.getClosestSubBuild(t.subBuilds)||"",s=r||"default";if(i[s])return i[s];const a=e.subBuildFn,o=e.fnCall;e.subBuildFn=r,e.fnCall=this;let l=null;if(t.layout){let i=bm.get(e.constructor);void 0===i&&(i=new WeakMap,bm.set(e.constructor,i));let r=i.get(t);void 0===r&&(r=Vm(e.buildFunctionNode(t)),i.set(t,r)),e.addInclude(r);const s=n?function(e){let t;Hm(e);t=e[0]&&(e[0].isNode||Object.getPrototypeOf(e[0])!==Object.prototype)?[...e]:e[0];return t}(n):null;l=Vm(r.call(s))}else{const i=new Proxy(e,{get:(e,t,n)=>{let i;return i=Symbol.iterator===t?function*(){yield}:Reflect.get(e,t,n),i}}),r=n?function(e){let t=0;return Hm(e),new Proxy(e,{get:(n,i,r)=>{let s;if("length"===i)return s=e.length,s;if(Symbol.iterator===i)s=function*(){for(const t of e)yield Vm(t)};else{if(e.length>0)if(Object.getPrototypeOf(e[0])===Object.prototype){const n=e[0];s=void 0===n[i]?n[t++]:Reflect.get(n,i,r)}else e[0]instanceof Qf&&(s=void 0===e[i]?e[t++]:Reflect.get(e,i,r));else s=Reflect.get(n,i,r);s=Vm(s)}return s}})}(n):null,s=Array.isArray(n)?n.length>0:null!==n,a=t.jsFunc,o=s||a.length>1?a(r,i):a(i);l=Vm(o)}return e.subBuildFn=a,e.fnCall=o,t.once&&(i[s]=l),l}setupOutput(e){return e.addStack(),e.stack.outputNode=this.call(e),e.removeStack()}getOutputNode(e){const t=e.getNodeProperties(this),n=e.getSubBuildOutput(this);return t[n]=t[n]||this.setupOutput(e),t[n].subBuild=e.getClosestSubBuild(this),t[n]}build(e,t=null){let n=null;const i=e.getBuildStage(),r=e.getNodeProperties(this),s=e.getSubBuildOutput(this),a=this.getOutputNode(e),o=e.fnCall;if(e.fnCall=this,"setup"===i){const t=e.getSubBuildProperty("initialized",this);if(!0!==r[t]&&(r[t]=!0,r[s]=this.getOutputNode(e),r[s].build(e),this.shaderNode.subBuilds))for(const t of e.chaining){const n=e.getDataFromNode(t,"any");n.subBuilds=n.subBuilds||new Set;for(const e of this.shaderNode.subBuilds)n.subBuilds.add(e)}n=r[s]}else"analyze"===i?a.build(e,t):"generate"===i&&(n=a.build(e,t)||"");return e.fnCall=o,n}}class wm extends Qf{constructor(e,t){super(t),this.jsFunc=e,this.layout=null,this.global=!0,this.once=!1}setLayout(e){return this.layout=e,this}getLayout(){return this.layout}call(e=null){return new Em(this,e)}setup(){return this.call()}}const Am=[!1,!0],Rm=[0,1,2,3],Cm=[-1,-2],Nm=[.5,1.5,1/3,1e-6,1e6,Math.PI,2*Math.PI,1/Math.PI,2/Math.PI,1/(2*Math.PI),Math.PI/2],Pm=new Map;for(const e of Am)Pm.set(e,new um(e));const Lm=new Map;for(const e of Rm)Lm.set(e,new um(e,"uint"));const Dm=new Map([...Lm].map(e=>new um(e.value,"int")));for(const e of Cm)Dm.set(e,new um(e,"int"));const Im=new Map([...Dm].map(e=>new um(e.value)));for(const e of Nm)Im.set(e,new um(e));for(const e of Nm)Im.set(-e,new um(-e));const Um={bool:Pm,uint:Lm,ints:Dm,float:Im},Fm=new Map([...Pm,...Im]),Om=(e,t)=>Fm.has(e)?Fm.get(e):!0===e.isNode?e:new um(e,t),Bm=function(e,t=null){return(...n)=>{for(const t of n)if(void 0===t)return qt(`TSL: Invalid parameter for the type "${e}".`,new Rf),new um(0,e);if((0===n.length||!["bool","float","int","uint"].includes(e)&&n.every(e=>{const t=typeof e;return"object"!==t&&"function"!==t}))&&(n=[Of(e,...n)]),1===n.length&&null!==t&&t.has(n[0]))return Gm(t.get(n[0]));if(1===n.length){const t=Om(n[0],e);return t.nodeType===e?Gm(t):Gm(new em(t,e))}const i=n.map(e=>Om(e));return Gm(new nm(i,e))}},km=e=>"object"==typeof e&&null!==e?e.value:e;function zm(e,t){return new wm(e,t)}const Vm=(e,t=null)=>function(e,t=null){const n=Ff(e);return"node"===n?e:null===t&&("float"===n||"boolean"===n)||n&&"shader"!==n&&"string"!==n?Vm(Om(e,t)):"shader"===n?e.isFn?e:Km(e):e}(e,t),Gm=(e,t=null)=>Vm(e,t).toVarIntent(),Hm=(e,t=null)=>new xm(e,t),jm=(e,t=null)=>new Tm(e,t),Wm=(e,t=null,n=null,i=null)=>new Sm(e,t,n,i),$m=(e,...t)=>new Mm(e,...t),Xm=(e,t=null,n=null,i={})=>new Sm(e,t,n,{...i,intent:!0});let qm=0;class Ym extends Qf{constructor(e,t=null){super();let n=null;null!==t&&("object"==typeof t?n=t.return:("string"==typeof t?n=t:qt("TSL: Invalid layout type.",new Rf),t=null)),this.shaderNode=new zm(e,n),null!==t&&this.setLayout(t),this.isFn=!0}setLayout(e){const t=this.shaderNode.nodeType;if("object"!=typeof e.inputs){const n={name:"fn"+qm++,type:t,inputs:[]};for(const t in e)"return"!==t&&n.inputs.push({name:t,type:e[t]});e=n}return this.shaderNode.setLayout(e),this}getNodeType(e){return this.shaderNode.getNodeType(e)||"float"}call(...e){const t=this.shaderNode.call(e);return"void"===this.shaderNode.nodeType&&t.toStack(),t.toVarIntent()}once(e=null){return this.shaderNode.once=!0,this.shaderNode.subBuilds=e,this}generate(e){const t=this.getNodeType(e);return qt('TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".',this.stackTrace),e.generateConst(t)}}function Km(e,t=null){const n=new Ym(e,t);return new Proxy(()=>{},{apply:(e,t,i)=>n.call(...i),get:(e,t,i)=>Reflect.get(n,t,i),set:(e,t,i,r)=>Reflect.set(n,t,i,r)})}const Zm=e=>{hm=e},Qm=()=>hm,Jm=(...e)=>hm.If(...e);function eg(e){return hm&&hm.addToStack(e),e}pm("toStack",eg);const tg=new Bm("color"),ng=new Bm("float",Um.float),ig=new Bm("int",Um.ints),rg=new Bm("uint",Um.uint),sg=new Bm("bool",Um.bool),ag=new Bm("vec2"),og=new Bm("ivec2"),lg=new Bm("uvec2"),ug=new Bm("bvec2"),cg=new Bm("vec3"),hg=new Bm("ivec3"),dg=new Bm("uvec3"),pg=new Bm("bvec3"),fg=new Bm("vec4"),mg=new Bm("ivec4"),gg=new Bm("uvec4"),_g=new Bm("bvec4"),vg=new Bm("mat2"),yg=new Bm("mat3"),bg=new Bm("mat4");pm("toColor",tg),pm("toFloat",ng),pm("toInt",ig),pm("toUint",rg),pm("toBool",sg),pm("toVec2",ag),pm("toIVec2",og),pm("toUVec2",lg),pm("toBVec2",ug),pm("toVec3",cg),pm("toIVec3",hg),pm("toUVec3",dg),pm("toBVec3",pg),pm("toVec4",fg),pm("toIVec4",mg),pm("toUVec4",gg),pm("toBVec4",_g),pm("toMat2",vg),pm("toMat3",yg),pm("toMat4",bg);pm("element",Wm(Jf).setParameterLength(2)),pm("convert",(e,t)=>new em(Vm(e),t)),pm("append",e=>(Xt("TSL: .append() has been renamed to .toStack().",new Rf),eg(e)));class xg extends Qf{static get type(){return"PropertyNode"}constructor(e,t=null,n=!1){super(e),this.name=t,this.varying=n,this.isPropertyNode=!0,this.global=!0}customCacheKey(){return Nf(this.type+":"+(this.name||"")+":"+(this.varying?"1":"0"))}getHash(e){return this.name||super.getHash(e)}generate(e){let t;return!0===this.varying?(t=e.getVaryingFromNode(this,this.name),t.needsInterpolation=!0):t=e.getVarFromNode(this,this.name),e.getPropertyName(t)}}const Tg=(e,t)=>new xg(e,t),Sg=(e,t)=>new xg(e,t,!0),Mg=$m(xg,"vec4","DiffuseColor"),Eg=$m(xg,"vec3","DiffuseContribution"),wg=$m(xg,"vec3","EmissiveColor"),Ag=$m(xg,"float","Roughness"),Rg=$m(xg,"float","Metalness"),Cg=$m(xg,"float","Clearcoat"),Ng=$m(xg,"float","ClearcoatRoughness"),Pg=$m(xg,"vec3","Sheen"),Lg=$m(xg,"float","SheenRoughness"),Dg=$m(xg,"float","Iridescence"),Ig=$m(xg,"float","IridescenceIOR"),Ug=$m(xg,"float","IridescenceThickness"),Fg=$m(xg,"float","AlphaT"),Og=$m(xg,"float","Anisotropy"),Bg=$m(xg,"vec3","AnisotropyT"),kg=$m(xg,"vec3","AnisotropyB"),zg=$m(xg,"color","SpecularColor"),Vg=$m(xg,"color","SpecularColorBlended"),Gg=$m(xg,"float","SpecularF90"),Hg=$m(xg,"float","Shininess"),jg=$m(xg,"vec4","Output"),Wg=$m(xg,"float","dashSize"),$g=$m(xg,"float","gapSize"),Xg=$m(xg,"float","IOR"),qg=$m(xg,"float","Transmission"),Yg=$m(xg,"float","Thickness"),Kg=$m(xg,"float","AttenuationDistance"),Zg=$m(xg,"color","AttenuationColor"),Qg=$m(xg,"float","Dispersion");class Jg extends Qf{static get type(){return"UniformGroupNode"}constructor(e,t=!1,n=1){super("string"),this.name=e,this.shared=t,this.order=n,this.isUniformGroup=!0}serialize(e){super.serialize(e),e.name=this.name,e.version=this.version,e.shared=this.shared}deserialize(e){super.deserialize(e),this.name=e.name,this.version=e.version,this.shared=e.shared}}const e_=e=>new Jg(e),t_=(e,t=0)=>new Jg(e,!0,t),n_=t_("frame"),i_=t_("render"),r_=e_("object");class s_ extends om{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=r_}setName(e){return this.name=e,this}label(e){return Xt('TSL: "label()" has been deprecated. Use "setName()" instead.',new Rf),this.setName(e)}setGroup(e){return this.groupNode=e,this}getGroup(){return this.groupNode}getUniformHash(e){return this.getHash(e)}onUpdate(e,t){return e=e.bind(this),super.onUpdate(t=>{const n=e(t,this);void 0!==n&&(this.value=n)},t)}getInputType(e){let t=super.getInputType(e);return"bool"===t&&(t="uint"),t}generate(e,t){const n=this.getNodeType(e),i=this.getUniformHash(e);let r=e.getNodeFromHash(i);void 0===r&&(e.setHashNode(this,i),r=this);const s=r.getInputType(e),a=e.getUniformFromNode(r,s,e.shaderStage,this.name||e.context.nodeName),o=e.getPropertyName(a);void 0!==e.context.nodeName&&delete e.context.nodeName;let l=o;if("bool"===n){const t=e.getDataFromNode(this);let i=t.propertyName;if(void 0===i){const r=e.getVarFromNode(this,null,"bool");i=e.getPropertyName(r),t.propertyName=i,l=e.format(o,s,n),e.addLineFlowCode(`${i} = ${l}`,this)}l=i}return e.format(l,n,t)}}const a_=(e,t)=>{const n=(e=>null!=e?e.nodeType||e.convertTo||("string"==typeof e?e:null):null)(t||e);if(n===e&&(e=Of(n)),e&&!0===e.isNode){let t=e.value;e.traverse(e=>{!0===e.isConstNode&&(t=e.value)}),e=t}return new s_(e,n)};class o_ extends tm{static get type(){return"ArrayNode"}constructor(e,t,n=null){super(e),this.count=t,this.values=n,this.isArrayNode=!0}getArrayCount(){return this.count}getNodeType(e){return null===this.nodeType?this.values[0].getNodeType(e):this.nodeType}getElementType(e){return this.getNodeType(e)}getMemberType(e,t){return null===this.nodeType?this.values[0].getMemberType(e,t):super.getMemberType(e,t)}generate(e){const t=this.getNodeType(e);return e.generateArray(t,this.count,this.values)}}pm("toArray",(e,t)=>((...e)=>{let t;if(1===e.length){const n=e[0];t=new o_(null,n.length,n)}else{const n=e[0],i=e[1];t=new o_(n,i)}return Vm(t)})(Array(t).fill(e)));class l_ extends tm{static get type(){return"AssignNode"}constructor(e,t){super(),this.targetNode=e,this.sourceNode=t,this.isAssignNode=!0}hasDependencies(){return!1}getNodeType(e,t){return"void"!==t?this.targetNode.getNodeType(e):"void"}needsSplitAssign(e){const{targetNode:t}=this;if(!1===e.isAvailable("swizzleAssign")&&t.isSplitNode&&t.components.length>1){const n=e.getTypeLength(t.node.getNodeType(e));return Yf.join("").slice(0,n)!==t.components}return!1}setup(e){const{targetNode:t,sourceNode:n}=this,i=t.getScope();e.getDataFromNode(i).assign=!0;const r=e.getNodeProperties(this);r.sourceNode=n,r.targetNode=t.context({assign:!0})}generate(e,t){const{targetNode:n,sourceNode:i}=e.getNodeProperties(this),r=this.needsSplitAssign(e),s=n.build(e),a=n.getNodeType(e),o=i.build(e,a),l=i.getNodeType(e),u=e.getDataFromNode(this);let c;if(!0===u.initialized)"void"!==t&&(c=s);else if(r){const i=e.getVarFromNode(this,null,a),r=e.getPropertyName(i);e.addLineFlowCode(`${r} = ${o}`,this);const l=n.node,u=l.node.context({assign:!0}).build(e);for(let t=0;t{const i=n.type;let r;return r="pointer"===i?"&"+t.build(e):t.build(e,i),r};if(Array.isArray(r)){if(r.length>i.length)qt("TSL: The number of provided parameters exceeds the expected number of inputs in 'Fn()'."),r.length=i.length;else if(r.length(t=t.length>1||t[0]&&!0===t[0].isNode?jm(t):Hm(t[0]),new u_(Vm(e),t)));const c_={"==":"equal","!=":"notEqual","<":"lessThan",">":"greaterThan","<=":"lessThanEqual",">=":"greaterThanEqual","%":"mod"};class h_ extends tm{static get type(){return"OperatorNode"}constructor(e,t,n,...i){if(super(),i.length>0){let r=new h_(e,t,n);for(let t=0;t>"===n||"<<"===n)return e.getIntegerType(s);if("!"===n||"&&"===n||"||"===n||"^^"===n)return"bool";if("=="===n||"!="===n||"<"===n||">"===n||"<="===n||">="===n){const t=Math.max(e.getTypeLength(s),e.getTypeLength(a));return t>1?`bvec${t}`:"bool"}if(e.isMatrix(s)){if("float"===a)return s;if(e.isVector(a))return e.getVectorFromMatrix(s);if(e.isMatrix(a))return s}else if(e.isMatrix(a)){if("float"===s)return a;if(e.isVector(s))return e.getVectorFromMatrix(a)}return e.getTypeLength(a)>e.getTypeLength(s)?a:s}generate(e,t){const n=this.op,{aNode:i,bNode:r}=this,s=this.getNodeType(e,t);let a=null,o=null;"void"!==s?(a=i.getNodeType(e),o=r?r.getNodeType(e):null,"<"===n||">"===n||"<="===n||">="===n||"=="===n||"!="===n?e.isVector(a)?o=a:e.isVector(o)?a=o:a!==o&&(a=o="float"):">>"===n||"<<"===n?(a=s,o=e.changeComponentType(o,"uint")):"%"===n?(a=s,o=e.isInteger(a)&&e.isInteger(o)?o:a):e.isMatrix(a)?"float"===o?o="float":e.isVector(o)?o=e.getVectorFromMatrix(a):e.isMatrix(o)||(a=o=s):a=e.isMatrix(o)?"float"===a?"float":e.isVector(a)?e.getVectorFromMatrix(o):o=s:o=s):a=o=s;const l=i.build(e,a),u=r?r.build(e,o):null,c=e.getFunctionOperator(n);if("void"!==t){const i=e.renderer.coordinateSystem===Ft;if("=="===n||"!="===n||"<"===n||">"===n||"<="===n||">="===n)return i&&e.isVector(a)?e.format(`${this.getOperatorMethod(e,t)}( ${l}, ${u} )`,s,t):e.format(`( ${l} ${n} ${u} )`,s,t);if("%"===n)return e.isInteger(o)?e.format(`( ${l} % ${u} )`,s,t):e.format(`${this.getOperatorMethod(e,s)}( ${l}, ${u} )`,s,t);if("!"===n||"~"===n)return e.format(`(${n}${l})`,a,t);if(c)return e.format(`${c}( ${l}, ${u} )`,s,t);if(e.isMatrix(a)&&"float"===o)return e.format(`( ${u} ${n} ${l} )`,s,t);if("float"===a&&e.isMatrix(o))return e.format(`${l} ${n} ${u}`,s,t);{let r=`( ${l} ${n} ${u} )`;return!i&&"bool"===s&&e.isVector(a)&&e.isVector(o)&&(r=`all${r}`),e.format(r,s,t)}}if("void"!==a)return c?e.format(`${c}( ${l}, ${u} )`,s,t):e.isMatrix(a)&&"float"===o?e.format(`${u} ${n} ${l}`,s,t):e.format(`${l} ${n} ${u}`,s,t)}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}}const d_=Xm(h_,"+").setParameterLength(2,1/0).setName("add"),p_=Xm(h_,"-").setParameterLength(2,1/0).setName("sub"),f_=Xm(h_,"*").setParameterLength(2,1/0).setName("mul"),m_=Xm(h_,"/").setParameterLength(2,1/0).setName("div"),g_=Xm(h_,"%").setParameterLength(2).setName("mod"),__=Xm(h_,"==").setParameterLength(2).setName("equal"),v_=Xm(h_,"!=").setParameterLength(2).setName("notEqual"),y_=Xm(h_,"<").setParameterLength(2).setName("lessThan"),b_=Xm(h_,">").setParameterLength(2).setName("greaterThan"),x_=Xm(h_,"<=").setParameterLength(2).setName("lessThanEqual"),T_=Xm(h_,">=").setParameterLength(2).setName("greaterThanEqual"),S_=Xm(h_,"&&").setParameterLength(2,1/0).setName("and"),M_=Xm(h_,"||").setParameterLength(2,1/0).setName("or"),E_=Xm(h_,"!").setParameterLength(1).setName("not"),w_=Xm(h_,"^^").setParameterLength(2).setName("xor"),A_=Xm(h_,"&").setParameterLength(2).setName("bitAnd"),R_=Xm(h_,"~").setParameterLength(1).setName("bitNot"),C_=Xm(h_,"|").setParameterLength(2).setName("bitOr"),N_=Xm(h_,"^").setParameterLength(2).setName("bitXor"),P_=Xm(h_,"<<").setParameterLength(2).setName("shiftLeft"),L_=Xm(h_,">>").setParameterLength(2).setName("shiftRight"),D_=Km(([e])=>(e.addAssign(1),e)),I_=Km(([e])=>(e.subAssign(1),e)),U_=Km(([e])=>{const t=ig(e).toConst();return e.addAssign(1),t}),F_=Km(([e])=>{const t=ig(e).toConst();return e.subAssign(1),t});pm("add",d_),pm("sub",p_),pm("mul",f_),pm("div",m_),pm("mod",g_),pm("equal",__),pm("notEqual",v_),pm("lessThan",y_),pm("greaterThan",b_),pm("lessThanEqual",x_),pm("greaterThanEqual",T_),pm("and",S_),pm("or",M_),pm("not",E_),pm("xor",w_),pm("bitAnd",A_),pm("bitNot",R_),pm("bitOr",C_),pm("bitXor",N_),pm("shiftLeft",P_),pm("shiftRight",L_),pm("incrementBefore",D_),pm("decrementBefore",I_),pm("increment",U_),pm("decrement",F_);pm("modInt",(e,t)=>(Xt('TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.',new Rf),g_(ig(e),ig(t))));class O_ extends tm{static get type(){return"MathNode"}constructor(e,t,n=null,i=null){if(super(),(e===O_.MAX||e===O_.MIN)&&arguments.length>3){let r=new O_(e,t,n);for(let t=2;ts&&r>a?t:s>a?n:a>r?i:t}getNodeType(e){const t=this.method;return t===O_.LENGTH||t===O_.DISTANCE||t===O_.DOT?"float":t===O_.CROSS?"vec3":t===O_.ALL||t===O_.ANY?"bool":t===O_.EQUALS?e.changeComponentType(this.aNode.getNodeType(e),"bool"):this.getInputType(e)}setup(e){const{aNode:t,bNode:n,method:i}=this;let r=null;if(i===O_.ONE_MINUS)r=p_(1,t);else if(i===O_.RECIPROCAL)r=m_(1,t);else if(i===O_.DIFFERENCE)r=av(p_(t,n));else if(i===O_.TRANSFORM_DIRECTION){let i=t,s=n;e.isMatrix(i.getNodeType(e))?s=fg(cg(s),0):i=fg(cg(i),0);const a=f_(i,s).xyz;r=Q_(a)}return null!==r?r:super.setup(e)}generate(e,t){if(e.getNodeProperties(this).outputNode)return super.generate(e,t);let n=this.method;const i=this.getNodeType(e),r=this.getInputType(e),s=this.aNode,a=this.bNode,o=this.cNode,l=e.renderer.coordinateSystem;if(n===O_.NEGATE)return e.format("( - "+s.build(e,r)+" )",i,t);{const u=[];return n===O_.CROSS?u.push(s.build(e,i),a.build(e,i)):l===Ft&&n===O_.STEP?u.push(s.build(e,1===e.getTypeLength(s.getNodeType(e))?"float":r),a.build(e,r)):l!==Ft||n!==O_.MIN&&n!==O_.MAX?n===O_.REFRACT?u.push(s.build(e,r),a.build(e,r),o.build(e,"float")):n===O_.MIX?u.push(s.build(e,r),a.build(e,r),o.build(e,1===e.getTypeLength(o.getNodeType(e))?"float":r)):(l===Ot&&n===O_.ATAN&&null!==a&&(n="atan2"),"fragment"===e.shaderStage||n!==O_.DFDX&&n!==O_.DFDY||(Xt(`TSL: '${n}' is not supported in the ${e.shaderStage} stage.`,this.stackTrace),n="/*"+n+"*/"),u.push(s.build(e,r)),null!==a&&u.push(a.build(e,r)),null!==o&&u.push(o.build(e,r))):u.push(s.build(e,r),a.build(e,1===e.getTypeLength(a.getNodeType(e))?"float":r)),e.format(`${e.getMethod(n,i)}( ${u.join(", ")} )`,i,t)}}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}O_.ALL="all",O_.ANY="any",O_.RADIANS="radians",O_.DEGREES="degrees",O_.EXP="exp",O_.EXP2="exp2",O_.LOG="log",O_.LOG2="log2",O_.SQRT="sqrt",O_.INVERSE_SQRT="inversesqrt",O_.FLOOR="floor",O_.CEIL="ceil",O_.NORMALIZE="normalize",O_.FRACT="fract",O_.SIN="sin",O_.COS="cos",O_.TAN="tan",O_.ASIN="asin",O_.ACOS="acos",O_.ATAN="atan",O_.ABS="abs",O_.SIGN="sign",O_.LENGTH="length",O_.NEGATE="negate",O_.ONE_MINUS="oneMinus",O_.DFDX="dFdx",O_.DFDY="dFdy",O_.ROUND="round",O_.RECIPROCAL="reciprocal",O_.TRUNC="trunc",O_.FWIDTH="fwidth",O_.TRANSPOSE="transpose",O_.DETERMINANT="determinant",O_.INVERSE="inverse",O_.EQUALS="equals",O_.MIN="min",O_.MAX="max",O_.STEP="step",O_.REFLECT="reflect",O_.DISTANCE="distance",O_.DIFFERENCE="difference",O_.DOT="dot",O_.CROSS="cross",O_.POW="pow",O_.TRANSFORM_DIRECTION="transformDirection",O_.MIX="mix",O_.CLAMP="clamp",O_.REFRACT="refract",O_.SMOOTHSTEP="smoothstep",O_.FACEFORWARD="faceforward";const B_=ng(1e-6),k_=ng(Math.PI),z_=Xm(O_,O_.ALL).setParameterLength(1),V_=Xm(O_,O_.ANY).setParameterLength(1),G_=Xm(O_,O_.RADIANS).setParameterLength(1),H_=Xm(O_,O_.DEGREES).setParameterLength(1),j_=Xm(O_,O_.EXP).setParameterLength(1),W_=Xm(O_,O_.EXP2).setParameterLength(1),$_=Xm(O_,O_.LOG).setParameterLength(1),X_=Xm(O_,O_.LOG2).setParameterLength(1),q_=Xm(O_,O_.SQRT).setParameterLength(1),Y_=Xm(O_,O_.INVERSE_SQRT).setParameterLength(1),K_=Xm(O_,O_.FLOOR).setParameterLength(1),Z_=Xm(O_,O_.CEIL).setParameterLength(1),Q_=Xm(O_,O_.NORMALIZE).setParameterLength(1),J_=Xm(O_,O_.FRACT).setParameterLength(1),ev=Xm(O_,O_.SIN).setParameterLength(1),tv=Xm(O_,O_.COS).setParameterLength(1),nv=Xm(O_,O_.TAN).setParameterLength(1),iv=Xm(O_,O_.ASIN).setParameterLength(1),rv=Xm(O_,O_.ACOS).setParameterLength(1),sv=Xm(O_,O_.ATAN).setParameterLength(1,2),av=Xm(O_,O_.ABS).setParameterLength(1),ov=Xm(O_,O_.SIGN).setParameterLength(1),lv=Xm(O_,O_.LENGTH).setParameterLength(1),uv=Xm(O_,O_.NEGATE).setParameterLength(1),cv=Xm(O_,O_.ONE_MINUS).setParameterLength(1),hv=Xm(O_,O_.DFDX).setParameterLength(1),dv=Xm(O_,O_.DFDY).setParameterLength(1),pv=Xm(O_,O_.ROUND).setParameterLength(1),fv=Xm(O_,O_.RECIPROCAL).setParameterLength(1),mv=Xm(O_,O_.TRUNC).setParameterLength(1),gv=Xm(O_,O_.FWIDTH).setParameterLength(1),_v=Xm(O_,O_.TRANSPOSE).setParameterLength(1),vv=Xm(O_,O_.DETERMINANT).setParameterLength(1),yv=Xm(O_,O_.INVERSE).setParameterLength(1),bv=Xm(O_,O_.MIN).setParameterLength(2,1/0),xv=Xm(O_,O_.MAX).setParameterLength(2,1/0),Tv=Xm(O_,O_.STEP).setParameterLength(2),Sv=Xm(O_,O_.REFLECT).setParameterLength(2),Mv=Xm(O_,O_.DISTANCE).setParameterLength(2),Ev=Xm(O_,O_.DIFFERENCE).setParameterLength(2),wv=Xm(O_,O_.DOT).setParameterLength(2),Av=Xm(O_,O_.CROSS).setParameterLength(2),Rv=Xm(O_,O_.POW).setParameterLength(2),Cv=e=>f_(e,e),Nv=e=>f_(e,e,e,e),Pv=Xm(O_,O_.TRANSFORM_DIRECTION).setParameterLength(2),Lv=e=>wv(e,e),Dv=Xm(O_,O_.MIX).setParameterLength(3),Iv=(e,t=0,n=1)=>new O_(O_.CLAMP,Vm(e),Vm(t),Vm(n)),Uv=e=>Iv(e),Fv=Xm(O_,O_.REFRACT).setParameterLength(3),Ov=Xm(O_,O_.SMOOTHSTEP).setParameterLength(3),Bv=Xm(O_,O_.FACEFORWARD).setParameterLength(3),kv=Km(([e])=>{const t=wv(e.xy,ag(12.9898,78.233)),n=g_(t,k_);return J_(ev(n).mul(43758.5453))});pm("all",z_),pm("any",V_),pm("radians",G_),pm("degrees",H_),pm("exp",j_),pm("exp2",W_),pm("log",$_),pm("log2",X_),pm("sqrt",q_),pm("inverseSqrt",Y_),pm("floor",K_),pm("ceil",Z_),pm("normalize",Q_),pm("fract",J_),pm("sin",ev),pm("cos",tv),pm("tan",nv),pm("asin",iv),pm("acos",rv),pm("atan",sv),pm("abs",av),pm("sign",ov),pm("length",lv),pm("lengthSq",Lv),pm("negate",uv),pm("oneMinus",cv),pm("dFdx",hv),pm("dFdy",dv),pm("round",pv),pm("reciprocal",fv),pm("trunc",mv),pm("fwidth",gv),pm("min",bv),pm("max",xv),pm("step",(e,t)=>Tv(t,e)),pm("reflect",Sv),pm("distance",Mv),pm("dot",wv),pm("cross",Av),pm("pow",Rv),pm("pow2",Cv),pm("pow3",e=>f_(e,e,e)),pm("pow4",Nv),pm("transformDirection",Pv),pm("mix",(e,t,n)=>Dv(t,n,e)),pm("clamp",Iv),pm("refract",Fv),pm("smoothstep",(e,t,n)=>Ov(t,n,e)),pm("faceForward",Bv),pm("difference",Ev),pm("saturate",Uv),pm("cbrt",e=>f_(ov(e),Rv(av(e),1/3))),pm("transpose",_v),pm("determinant",vv),pm("inverse",yv),pm("rand",kv);class zv extends Qf{static get type(){return"ConditionalNode"}constructor(e,t,n=null){super(),this.condNode=e,this.ifNode=t,this.elseNode=n}getNodeType(e){const{ifNode:t,elseNode:n}=e.getNodeProperties(this);if(void 0===t)return e.flowBuildStage(this,"setup"),this.getNodeType(e);const i=t.getNodeType(e);if(null!==n){const t=n.getNodeType(e);if(e.getTypeLength(t)>e.getTypeLength(i))return t}return i}setup(e){const t=this.condNode,n=this.ifNode.isolate(),i=this.elseNode?this.elseNode.isolate():null,r=e.context.nodeBlock;e.getDataFromNode(n).parentNodeBlock=r,null!==i&&(e.getDataFromNode(i).parentNodeBlock=r);const s=e.context.uniformFlow,a=e.getNodeProperties(this);a.condNode=t,a.ifNode=s?n:n.context({nodeBlock:n}),a.elseNode=i?s?i:i.context({nodeBlock:i}):null}generate(e,t){const n=this.getNodeType(e),i=e.getDataFromNode(this);if(void 0!==i.nodeProperty)return i.nodeProperty;const{condNode:r,ifNode:s,elseNode:a}=e.getNodeProperties(this),o=e.currentFunctionNode,l="void"!==t,u=l?Tg(n).build(e):"";i.nodeProperty=u;const c=r.build(e,"bool");if(e.context.uniformFlow&&null!==a){const i=s.build(e,n),r=a.build(e,n),o=e.getTernary(c,i,r);return e.format(o,n,t)}e.addFlowCode(`\n${e.tab}if ( ${c} ) {\n\n`).addFlowTab();let h=s.build(e,n);if(h&&(l?h=u+" = "+h+";":(h="return "+h+";",null===o&&(Xt("TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values.",this.stackTrace),h="// "+h))),e.removeFlowTab().addFlowCode(e.tab+"\t"+h+"\n\n"+e.tab+"}"),null!==a){e.addFlowCode(" else {\n\n").addFlowTab();let t=a.build(e,n);t&&(l?t=u+" = "+t+";":(t="return "+t+";",null===o&&(Xt("TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values.",this.stackTrace),t="// "+t))),e.removeFlowTab().addFlowCode(e.tab+"\t"+t+"\n\n"+e.tab+"}\n\n")}else e.addFlowCode("\n\n");return e.format(u,n,t)}}const Vv=Wm(zv).setParameterLength(2,3);pm("select",Vv);class Gv extends Qf{static get type(){return"ContextNode"}constructor(e=null,t={}){super(),this.isContextNode=!0,this.node=e,this.value=t}getScope(){return this.node.getScope()}getNodeType(e){return this.node.getNodeType(e)}getFlowContextData(){const e=[];return this.traverse(t=>{!0===t.isContextNode&&e.push(t.value)}),Object.assign({},...e)}getMemberType(e,t){return this.node.getMemberType(e,t)}analyze(e){const t=e.addContext(this.value);this.node.build(e),e.setContext(t)}setup(e){const t=e.addContext(this.value);this.node.build(e),e.setContext(t)}generate(e,t){const n=e.addContext(this.value),i=this.node.build(e,t);return e.setContext(n),i}}const Hv=(e=null,t={})=>{let n=e;return null!==n&&!0===n.isNode||(t=n||t,n=null),new Gv(n,t)},jv=(e,t)=>Hv(e,{nodeName:t});pm("context",Hv),pm("label",function(e,t){return Xt('TSL: "label()" has been deprecated. Use "setName()" instead.'),jv(e,t)}),pm("uniformFlow",e=>Hv(e,{uniformFlow:!0})),pm("setName",jv),pm("builtinShadowContext",(e,t,n)=>function(e,t,n=null){return Hv(n,{getShadow:({light:n,shadowColorNode:i})=>t===n?i.mul(e):i})}(t,n,e)),pm("builtinAOContext",(e,t)=>function(e,t=null){return Hv(t,{getAO:(t,{material:n})=>!0===n.transparent?t:null!==t?t.mul(e):e})}(t,e));class Wv extends Qf{static get type(){return"VarNode"}constructor(e,t=null,n=!1){super(),this.node=e,this.name=t,this.global=!0,this.isVarNode=!0,this.readOnly=n,this.parents=!0,this.intent=!1}setIntent(e){return this.intent=e,this}isIntent(e){return!0!==e.getDataFromNode(this).forceDeclaration&&this.intent}getIntent(){return this.intent}getMemberType(e,t){return this.node.getMemberType(e,t)}getElementType(e){return this.node.getElementType(e)}getNodeType(e){return this.node.getNodeType(e)}getArrayCount(e){return this.node.getArrayCount(e)}isAssign(e){return e.getDataFromNode(this).assign}build(...e){const t=e[0];if(!1===this._hasStack(t)&&"setup"===t.buildStage&&(t.context.nodeLoop||t.context.nodeBlock)){let e=!1;if(this.node.isShaderCallNodeInternal&&null===this.node.shaderNode.getLayout()&&t.fnCall&&t.fnCall.shaderNode){if(t.getDataFromNode(this.node.shaderNode).hasLoop){t.getDataFromNode(this).forceDeclaration=!0,e=!0}}const n=t.getBaseStack();e?n.addToStackBefore(this):n.addToStack(this)}return this.isIntent(t)&&!0!==this.isAssign(t)?this.node.build(...e):super.build(...e)}generate(e){const{node:t,name:n,readOnly:i}=this,{renderer:r}=e,s=!0===r.backend.isWebGPUBackend;let a=!1,o=!1;i&&(a=e.isDeterministic(t),o=s?i:a);const l=this.getNodeType(e);if("void"==l){!0!==this.isIntent(e)&&qt('TSL: ".toVar()" can not be used with void type.',this.stackTrace);return t.build(e)}const u=e.getVectorType(l),c=t.build(e,u),h=e.getVarFromNode(this,n,u,void 0,o),d=e.getPropertyName(h);let p=d;if(o)if(s)p=a?`const ${d}`:`let ${d}`;else{const n=t.getArrayCount(e);p=`const ${e.getVar(h.type,d,n)}`}return e.addLineFlowCode(`${p} = ${c}`,this),d}_hasStack(e){return void 0!==e.getDataFromNode(this).stack}}const $v=Wm(Wv);pm("toVar",(e,t=null)=>$v(e,t).toStack()),pm("toConst",(e,t=null)=>$v(e,t,!0).toStack()),pm("toVarIntent",e=>$v(e).setIntent(!0).toStack());class Xv extends Qf{static get type(){return"SubBuild"}constructor(e,t,n=null){super(n),this.node=e,this.name=t,this.isSubBuildNode=!0}getNodeType(e){if(null!==this.nodeType)return this.nodeType;e.addSubBuild(this.name);const t=this.node.getNodeType(e);return e.removeSubBuild(),t}build(e,...t){e.addSubBuild(this.name);const n=this.node.build(e,...t);return e.removeSubBuild(),n}}const qv=(e,t,n=null)=>new Xv(Vm(e),t,n);class Yv extends Qf{static get type(){return"VaryingNode"}constructor(e,t=null){super(),this.node=qv(e,"VERTEX"),this.name=t,this.isVaryingNode=!0,this.interpolationType=null,this.interpolationSampling=null,this.global=!0}setInterpolation(e,t=null){return this.interpolationType=e,this.interpolationSampling=t,this}getHash(e){return this.name||super.getHash(e)}getNodeType(e){return this.node.getNodeType(e)}setupVarying(e){const t=e.getNodeProperties(this);let n=t.varying;if(void 0===n){const i=this.name,r=this.getNodeType(e),s=this.interpolationType,a=this.interpolationSampling;t.varying=n=e.getVaryingFromNode(this,i,r,s,a),t.node=qv(this.node,"VERTEX")}return n.needsInterpolation||(n.needsInterpolation="fragment"===e.shaderStage),n}setup(e){this.setupVarying(e),e.flowNodeFromShaderStage(kf,this.node)}analyze(e){this.setupVarying(e),e.flowNodeFromShaderStage(kf,this.node)}generate(e){const t=e.getSubBuildProperty("property",e.currentStack),n=e.getNodeProperties(this),i=this.setupVarying(e);if(void 0===n[t]){const r=this.getNodeType(e),s=e.getPropertyName(i,kf);e.flowNodeFromShaderStage(kf,n.node,r,s),n[t]=s}return e.getPropertyName(i)}}const Kv=Wm(Yv).setParameterLength(1,2);pm("toVarying",Kv),pm("toVertexStage",e=>Kv(e));const Zv=Km(([e])=>{const t=e.mul(.9478672986).add(.0521327014).pow(2.4),n=e.mul(.0773993808),i=e.lessThanEqual(.04045);return Dv(t,n,i)}).setLayout({name:"sRGBTransferEOTF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),Qv=Km(([e])=>{const t=e.pow(.41666).mul(1.055).sub(.055),n=e.mul(12.92),i=e.lessThanEqual(.0031308);return Dv(t,n,i)}).setLayout({name:"sRGBTransferOETF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),Jv="WorkingColorSpace";class ey extends tm{static get type(){return"ColorSpaceNode"}constructor(e,t,n){super("vec4"),this.colorNode=e,this.source=t,this.target=n}resolveColorSpace(e,t){return t===Jv?bn.workingColorSpace:"OutputColorSpace"===t?e.context.outputColorSpace||e.renderer.outputColorSpace:t}setup(e){const{colorNode:t}=this,n=this.resolveColorSpace(e,this.source),i=this.resolveColorSpace(e,this.target);let r=t;return!1!==bn.enabled&&n!==i&&n&&i?(bn.getTransfer(n)===St&&(r=fg(Zv(r.rgb),r.a)),bn.getPrimaries(n)!==bn.getPrimaries(i)&&(r=fg(yg(bn._getMatrix(new mn,n,i)).mul(r.rgb),r.a)),bn.getTransfer(i)===St&&(r=fg(Qv(r.rgb),r.a)),r):r}}const ty=(e,t)=>new ey(Vm(e),t,Jv);pm("workingToColorSpace",(e,t)=>new ey(Vm(e),Jv,t)),pm("colorSpaceToWorking",ty);let ny=class extends Jf{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}getNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),n=this.referenceNode.getNodeType(),i=this.getNodeType();return e.format(t,n,i)}};class iy extends Qf{static get type(){return"ReferenceBaseNode"}constructor(e,t,n=null,i=null){super(),this.property=e,this.uniformType=t,this.object=n,this.count=i,this.properties=e.split("."),this.reference=n,this.node=null,this.group=null,this.updateType=Hf}setGroup(e){return this.group=e,this}element(e){return new ny(this,Vm(e))}setNodeType(e){const t=a_(null,e);null!==this.group&&t.setGroup(this.group),this.node=t}getNodeType(e){return null===this.node&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let n=e[t[0]];for(let e=1;enew ry(e,t,n);class ay extends tm{static get type(){return"ToneMappingNode"}constructor(e,t=oy,n=null){super("vec3"),this._toneMapping=e,this.exposureNode=t,this.colorNode=n}customCacheKey(){return Lf(this._toneMapping)}setToneMapping(e){return this._toneMapping=e,this}getToneMapping(){return this._toneMapping}setup(e){const t=this.colorNode||e.context.color,n=this._toneMapping;if(0===n)return t;let i=null;const r=e.renderer.library.getToneMappingFunction(n);return null!==r?i=fg(r(t.rgb,this.exposureNode),t.a):(qt("ToneMappingNode: Unsupported Tone Mapping configuration.",n),i=t),i}}const oy=sy("toneMappingExposure","float");pm("toneMapping",(e,t,n)=>((e,t,n)=>new ay(e,Vm(t),Vm(n)))(t,n,e));const ly=new WeakMap;function uy(e,t){let n=ly.get(e);return void 0===n&&(n=new yr(e,t),ly.set(e,n)),n}class cy extends om{static get type(){return"BufferAttributeNode"}constructor(e,t=null,n=0,i=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferStride=n,this.bufferOffset=i,this.usage=Dt,this.instanced=!1,this.attribute=null,this.global=!0,e&&!0===e.isBufferAttribute&&e.itemSize<=4&&(this.attribute=e,this.usage=e.usage,this.instanced=e.isInstancedBufferAttribute)}getHash(e){if(0===this.bufferStride&&0===this.bufferOffset){let t=e.globalCache.getData(this.value);return void 0===t&&(t={node:this},e.globalCache.setData(this.value,t)),t.node.uuid}return this.uuid}getNodeType(e){return null===this.bufferType&&(this.bufferType=e.getTypeFromAttribute(this.attribute)),this.bufferType}setup(e){if(null!==this.attribute)return;const t=this.getNodeType(e),n=e.getTypeLength(t),i=this.value,r=this.bufferStride||n,s=this.bufferOffset;let a;a=!0===i.isInterleavedBuffer?i:!0===i.isBufferAttribute?uy(i.array,r):uy(i,r);const o=new xr(a,n,s);a.setUsage(this.usage),this.attribute=o,this.attribute.isInstancedBufferAttribute=this.instanced}generate(e){const t=this.getNodeType(e),n=e.getBufferAttributeFromNode(this,t),i=e.getPropertyName(n);let r=null;if("vertex"===e.shaderStage||"compute"===e.shaderStage)this.name=i,r=i;else{r=Kv(this).build(e,t)}return r}getInputType(){return"bufferAttribute"}setUsage(e){return this.usage=e,this.attribute&&!0===this.attribute.isBufferAttribute&&(this.attribute.usage=e),this}setInstanced(e){return this.instanced=e,this}}function hy(e,t=null,n=0,i=0,r=35044,s=!1){return"mat3"===t||null===t&&9===e.itemSize?yg(new cy(e,"vec3",9,0).setUsage(r).setInstanced(s),new cy(e,"vec3",9,3).setUsage(r).setInstanced(s),new cy(e,"vec3",9,6).setUsage(r).setInstanced(s)):"mat4"===t||null===t&&16===e.itemSize?bg(new cy(e,"vec4",16,0).setUsage(r).setInstanced(s),new cy(e,"vec4",16,4).setUsage(r).setInstanced(s),new cy(e,"vec4",16,8).setUsage(r).setInstanced(s),new cy(e,"vec4",16,12).setUsage(r).setInstanced(s)):new cy(e,t,n,i).setUsage(r)}const dy=(e,t=null,n=0,i=0)=>hy(e,t,n,i),py=(e,t=null,n=0,i=0)=>hy(e,t,n,i,Dt,!0),fy=(e,t=null,n=0,i=0)=>hy(e,t,n,i,It,!0);pm("toAttribute",e=>dy(e.value));class my extends Qf{static get type(){return"ComputeNode"}constructor(e,t){super("void"),this.isComputeNode=!0,this.computeNode=e,this.workgroupSize=t,this.count=null,this.version=1,this.name="",this.updateBeforeType=Hf,this.onInitFunction=null}setCount(e){return this.count=e,this}getCount(){return this.count}dispose(){this.dispatchEvent({type:"dispose"})}setName(e){return this.name=e,this}label(e){return Xt('TSL: "label()" has been deprecated. Use "setName()" instead.',new Rf),this.setName(e)}onInit(e){return this.onInitFunction=e,this}updateBefore({renderer:e}){e.compute(this)}setup(e){const t=this.computeNode.build(e);if(t){e.getNodeProperties(this).outputComputeNode=t.outputNode,t.outputNode=null}return t}generate(e,t){const{shaderStage:n}=e;if("compute"===n){const t=this.computeNode.build(e,"void");""!==t&&e.addLineFlowCode(t,this)}else{const n=e.getNodeProperties(this).outputComputeNode;if(n)return n.build(e,t)}}}const gy=(e,t=[64])=>{(0===t.length||t.length>3)&&qt("TSL: compute() workgroupSize must have 1, 2, or 3 elements",new Rf);for(let e=0;egy(e,n).setCount(t)),pm("computeKernel",gy);class _y extends Qf{static get type(){return"IsolateNode"}constructor(e,t=!0){super(),this.node=e,this.parent=t,this.isIsolateNode=!0}getNodeType(e){const t=e.getCache(),n=e.getCacheFromNode(this,this.parent);e.setCache(n);const i=this.node.getNodeType(e);return e.setCache(t),i}build(e,...t){const n=e.getCache(),i=e.getCacheFromNode(this,this.parent);e.setCache(i);const r=this.node.build(e,...t);return e.setCache(n),r}setParent(e){return this.parent=e,this}getParent(){return this.parent}}const vy=e=>new _y(Vm(e));pm("cache",function(e,t=!0){return Xt('TSL: "cache()" has been deprecated. Use "isolate()" instead.'),vy(e).setParent(t)}),pm("isolate",vy);class yy extends Qf{static get type(){return"BypassNode"}constructor(e,t){super(),this.isBypassNode=!0,this.outputNode=e,this.callNode=t}getNodeType(e){return this.outputNode.getNodeType(e)}generate(e){const t=this.callNode.build(e,"void");return""!==t&&e.addLineFlowCode(t,this),this.outputNode.build(e)}}pm("bypass",Wm(yy).setParameterLength(2));class by extends Qf{static get type(){return"RemapNode"}constructor(e,t,n,i=ng(0),r=ng(1)){super(),this.node=e,this.inLowNode=t,this.inHighNode=n,this.outLowNode=i,this.outHighNode=r,this.doClamp=!0}setup(){const{node:e,inLowNode:t,inHighNode:n,outLowNode:i,outHighNode:r,doClamp:s}=this;let a=e.sub(t).div(n.sub(t));return!0===s&&(a=a.clamp()),a.mul(r.sub(i)).add(i)}}const xy=Wm(by,null,null,{doClamp:!1}).setParameterLength(3,5),Ty=Wm(by).setParameterLength(3,5);pm("remap",xy),pm("remapClamp",Ty);class Sy extends Qf{static get type(){return"ExpressionNode"}constructor(e="",t="void"){super(t),this.snippet=e}generate(e,t){const n=this.getNodeType(e),i=this.snippet;if("void"!==n)return e.format(i,n,t);e.addLineFlowCode(i,this)}}const My=Wm(Sy).setParameterLength(1,2);pm("discard",e=>(e?Vv(e,My("discard")):My("discard")).toStack());class Ey extends tm{static get type(){return"RenderOutputNode"}constructor(e,t,n){super("vec4"),this.colorNode=e,this._toneMapping=t,this.outputColorSpace=n,this.isRenderOutputNode=!0}setToneMapping(e){return this._toneMapping=e,this}getToneMapping(){return this._toneMapping}setup({context:e}){let t=this.colorNode||e.color;const n=(null!==this._toneMapping?this._toneMapping:e.toneMapping)||0,i=(null!==this.outputColorSpace?this.outputColorSpace:e.outputColorSpace)||yt;return 0!==n&&(t=t.toneMapping(n)),i!==yt&&i!==bn.workingColorSpace&&(t=t.workingToColorSpace(i)),t}}pm("renderOutput",(e,t=null,n=null)=>new Ey(Vm(e),t,n));class wy extends tm{static get type(){return"DebugNode"}constructor(e,t=null){super(),this.node=e,this.callback=t}getNodeType(e){return this.node.getNodeType(e)}setup(e){return this.node.build(e)}analyze(e){return this.node.build(e)}generate(e){const t=this.callback,n=this.node.build(e);if(null!==t)t(e,n);else{const t="--- TSL debug - "+e.shaderStage+" shader ---",i="-".repeat(t.length);let r="";r+="// #"+t+"#\n",r+=e.flow.code.replace(/^\t/gm,"")+"\n",r+="/* ... */ "+n+" /* ... */\n",r+="// #"+i+"#\n",Wt(r)}return n}}pm("debug",(e,t=null)=>new wy(Vm(e),t).toStack());class Ay{constructor(){this._renderer=null,this.currentFrame=null}get nodeFrame(){return this._renderer._nodes.nodeFrame}setRenderer(e){return this._renderer=e,this}getRenderer(){return this._renderer}init(){}begin(){}finish(){}inspect(){}computeAsync(){}beginCompute(){}finishCompute(){}beginRender(){}finishRender(){}copyTextureToTexture(){}copyFramebufferToTexture(){}}class Ry extends Qf{static get type(){return"InspectorNode"}constructor(e,t="",n=null){super(),this.node=e,this.name=t,this.callback=n,this.updateType=Vf,this.isInspectorNode=!0}getName(){return this.name||this.node.name}update(e){e.renderer.inspector.inspect(this)}getNodeType(e){return this.node.getNodeType(e)}setup(e){let t=this.node;return!0===e.context.inspector&&null!==this.callback&&(t=this.callback(t)),!0!==e.renderer.backend.isWebGPUBackend&&e.renderer.inspector.constructor!==Ay&&Yt('TSL: ".toInspector()" is only available with WebGPU.'),t}}pm("toInspector",function(e,t="",n=null){return(e=Vm(e)).before(new Ry(e,t,n))});class Cy extends Qf{static get type(){return"AttributeNode"}constructor(e,t=null){super(t),this.global=!0,this._attributeName=e}getHash(e){return this.getAttributeName(e)}getNodeType(e){let t=this.nodeType;if(null===t){const n=this.getAttributeName(e);if(e.hasGeometryAttribute(n)){const i=e.geometry.getAttribute(n);t=e.getTypeFromAttribute(i)}else t="float"}return t}setAttributeName(e){return this._attributeName=e,this}getAttributeName(){return this._attributeName}generate(e){const t=this.getAttributeName(e),n=this.getNodeType(e);if(!0===e.hasGeometryAttribute(t)){const i=e.geometry.getAttribute(t),r=e.getTypeFromAttribute(i),s=e.getAttribute(t,r);if("vertex"===e.shaderStage)return e.format(s.name,r,n);return Kv(this).build(e,n)}return Xt(`AttributeNode: Vertex attribute "${t}" not found on geometry.`),e.generateConst(n)}serialize(e){super.serialize(e),e.global=this.global,e._attributeName=this._attributeName}deserialize(e){super.deserialize(e),this.global=e.global,this._attributeName=e._attributeName}}const Ny=(e,t=null)=>new Cy(e,t),Py=(e=0)=>Ny("uv"+(e>0?e:""),"vec2");class Ly extends Qf{static get type(){return"TextureSizeNode"}constructor(e,t=null){super("uvec2"),this.isTextureSizeNode=!0,this.textureNode=e,this.levelNode=t}generate(e,t){const n=this.textureNode.build(e,"property"),i=null===this.levelNode?"0":this.levelNode.build(e,"int");return e.format(`${e.getMethod("textureDimensions")}( ${n}, ${i} )`,this.getNodeType(e),t)}}const Dy=Wm(Ly).setParameterLength(1,2);class Iy extends s_{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=Vf}get textureNode(){return this._textureNode}get texture(){return this._textureNode.value}update(){const e=this.texture,t=e.images,n=t&&t.length>0?t[0]&&t[0].image||t[0]:e.image;if(n&&void 0!==n.width){const{width:e,height:t}=n;this.value=Math.log2(Math.max(e,t))}}}const Uy=Wm(Iy).setParameterLength(1);class Fy extends Error{constructor(e,t=null){super(e),this.name="NodeError",this.stackTrace=t}}const Oy=new Nn;class By extends s_{static get type(){return"TextureNode"}constructor(e=Oy,t=null,n=null,i=null){super(e),this.isTextureNode=!0,this.uvNode=t,this.levelNode=n,this.biasNode=i,this.compareNode=null,this.depthNode=null,this.gradNode=null,this.offsetNode=null,this.sampler=!0,this.updateMatrix=!1,this.updateType=zf,this.referenceNode=null,this._value=e,this._matrixUniform=null,this._flipYUniform=null,this.setUpdateMatrix(null===t)}set value(e){this.referenceNode?this.referenceNode.value=e:this._value=e}get value(){return this.referenceNode?this.referenceNode.value:this._value}getUniformHash(){return this.value.uuid}getNodeType(){return!0===this.value.isDepthTexture?"float":this.value.type===ye?"uvec4":this.value.type===ve?"ivec4":"vec4"}getInputType(){return"texture"}getDefaultUV(){return Py(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return null===this._matrixUniform&&(this._matrixUniform=a_(this.value.matrix)),this._matrixUniform.mul(cg(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this}setupUV(e,t){return e.isFlipY()&&(null===this._flipYUniform&&(this._flipYUniform=a_(!1)),t=t.toVar(),t=this.sampler?this._flipYUniform.select(t.flipY(),t):this._flipYUniform.select(t.setY(ig(Dy(this,this.levelNode).y).sub(t.y).sub(1)),t)),t}setup(e){const t=e.getNodeProperties(this);t.referenceNode=this.referenceNode;const n=this.value;if(!n||!0!==n.isTexture)throw new Fy("THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().",this.stackTrace);const i=Km(()=>{let t=this.uvNode;return null!==t&&!0!==e.context.forceUVContext||!e.context.getUV||(t=e.context.getUV(this,e)),t||(t=this.getDefaultUV()),!0===this.updateMatrix&&(t=this.getTransformedUV(t)),t=this.setupUV(e,t),this.updateType=null!==this._matrixUniform||null!==this._flipYUniform?Hf:zf,t})();let r=this.levelNode;null===r&&e.context.getTextureLevel&&(r=e.context.getTextureLevel(this));let s=null,a=null;if(null!==this.compareNode)if(e.renderer.hasCompatibility(zt))s=this.compareNode;else{const e=n.compareFunction;null===e||e===wt||e===Rt||e===Ct||e===Pt?a=this.compareNode:(s=this.compareNode,Yt('TSL: Only "LessCompare", "LessEqualCompare", "GreaterCompare" and "GreaterEqualCompare" are supported for depth texture comparison fallback.'))}t.uvNode=i,t.levelNode=r,t.biasNode=this.biasNode,t.compareNode=s,t.compareStepNode=a,t.gradNode=this.gradNode,t.depthNode=this.depthNode,t.offsetNode=this.offsetNode}generateUV(e,t){return t.build(e,!0===this.sampler?"vec2":"ivec2")}generateOffset(e,t){return t.build(e,"ivec2")}generateSnippet(e,t,n,i,r,s,a,o,l){const u=this.value;let c;return c=r?e.generateTextureBias(u,t,n,r,s,l):o?e.generateTextureGrad(u,t,n,o,s,l):a?e.generateTextureCompare(u,t,n,a,s,l):!1===this.sampler?e.generateTextureLoad(u,t,n,i,s,l):i?e.generateTextureLevel(u,t,n,i,s,l):e.generateTexture(u,t,n,s,l),c}generate(e,t){const n=this.value,i=e.getNodeProperties(this),r=super.generate(e,"property");if(/^sampler/.test(t))return r+"_sampler";if(e.isReference(t))return r;{const s=e.getDataFromNode(this),a=this.getNodeType(e);let o=s.propertyName;if(void 0===o){const{uvNode:t,levelNode:l,biasNode:u,compareNode:c,compareStepNode:h,depthNode:d,gradNode:p,offsetNode:f}=i,m=this.generateUV(e,t),g=l?l.build(e,"float"):null,_=u?u.build(e,"float"):null,v=d?d.build(e,"int"):null,y=c?c.build(e,"float"):null,b=h?h.build(e,"float"):null,x=p?[p[0].build(e,"vec2"),p[1].build(e,"vec2")]:null,T=f?this.generateOffset(e,f):null,S=e.getVarFromNode(this);o=e.getPropertyName(S);let M=this.generateSnippet(e,r,m,g,_,v,y,x,T);if(null!==b){const t=n.compareFunction;M=t===Ct||t===Pt?Tv(My(M,a),My(b,"float")).build(e,a):Tv(My(b,"float"),My(M,a)).build(e,a)}e.addLineFlowCode(`${o} = ${M}`,this),s.snippet=M,s.propertyName=o}let l=o;return e.needsToWorkingColorSpace(n)&&(l=ty(My(l,a),n.colorSpace).setup(e).build(e,a)),e.format(l,a,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}sample(e){const t=this.clone();return t.uvNode=Vm(e),t.referenceNode=this.getBase(),Vm(t)}load(e){return this.sample(e).setSampler(!1)}blur(e){const t=this.clone();t.biasNode=Vm(e).mul(Uy(t)),t.referenceNode=this.getBase();const n=t.value;return!1===t.generateMipmaps&&(n&&!1===n.generateMipmaps||n.minFilter===le||n.magFilter===le)&&(Xt("TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture."),t.biasNode=null),Vm(t)}level(e){const t=this.clone();return t.levelNode=Vm(e),t.referenceNode=this.getBase(),Vm(t)}size(e){return Dy(this,e)}bias(e){const t=this.clone();return t.biasNode=Vm(e),t.referenceNode=this.getBase(),Vm(t)}getBase(){return this.referenceNode?this.referenceNode.getBase():this}compare(e){const t=this.clone();return t.compareNode=Vm(e),t.referenceNode=this.getBase(),Vm(t)}grad(e,t){const n=this.clone();return n.gradNode=[Vm(e),Vm(t)],n.referenceNode=this.getBase(),Vm(n)}depth(e){const t=this.clone();return t.depthNode=Vm(e),t.referenceNode=this.getBase(),Vm(t)}offset(e){const t=this.clone();return t.offsetNode=Vm(e),t.referenceNode=this.getBase(),Vm(t)}serialize(e){super.serialize(e),e.value=this.value.toJSON(e.meta).uuid,e.sampler=this.sampler,e.updateMatrix=this.updateMatrix,e.updateType=this.updateType}deserialize(e){super.deserialize(e),this.value=e.meta.textures[e.value],this.sampler=e.sampler,this.updateMatrix=e.updateMatrix,this.updateType=e.updateType}update(){const e=this.value,t=this._matrixUniform;null!==t&&(t.value=e.matrix),!0===e.matrixAutoUpdate&&e.updateMatrix();const n=this._flipYUniform;null!==n&&(n.value=e.image instanceof ImageBitmap&&!0===e.flipY||!0===e.isRenderTargetTexture||!0===e.isFramebufferTexture||!0===e.isDepthTexture)}clone(){const e=new this.constructor(this.value,this.uvNode,this.levelNode,this.biasNode);return e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.offsetNode=this.offsetNode,e}}const ky=Wm(By).setParameterLength(1,4).setName("texture"),zy=(e=Oy,t=null,n=null,i=null)=>{let r;return e&&!0===e.isTextureNode?(r=Vm(e.clone()),r.referenceNode=e.getBase(),null!==t&&(r.uvNode=Vm(t)),null!==n&&(r.levelNode=Vm(n)),null!==i&&(r.biasNode=Vm(i))):r=ky(e,t,n,i),r},Vy=(...e)=>zy(...e).setSampler(!1);class Gy extends s_{static get type(){return"BufferNode"}constructor(e,t,n=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferCount=n,this.updateRanges=[]}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}getElementType(e){return this.getNodeType(e)}getInputType(){return"buffer"}}const Hy=(e,t,n)=>new Gy(e,t,n);class jy extends Jf{static get type(){return"UniformArrayElementNode"}constructor(e,t){super(e,t),this.isArrayBufferElementNode=!0}generate(e){const t=super.generate(e),n=this.getNodeType(),i=this.node.getPaddedType();return e.format(t,i,n)}}class Wy extends Gy{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null),this.array=e,this.elementType=null===t?Ff(e[0]):t,this.paddedType=this.getPaddedType(),this.updateType=Gf,this.isArrayBufferNode=!0}getNodeType(){return this.paddedType}getElementType(){return this.elementType}getPaddedType(){const e=this.elementType;let t="vec4";return"mat2"===e?t="mat2":!0===/mat/.test(e)?t="mat4":"i"===e.charAt(0)?t="ivec4":"u"===e.charAt(0)&&(t="uvec4"),t}update(){const{array:e,value:t}=this,n=this.elementType;if("float"===n||"int"===n||"uint"===n)for(let n=0;nnew Wy(e,t);const Xy=Wm(class extends Qf{constructor(e){super("float"),this.name=e,this.isBuiltinNode=!0}generate(){return this.name}}).setParameterLength(1);let qy,Yy;class Ky extends Qf{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this._output=null,this.isViewportNode=!0}getNodeType(){return this.scope===Ky.DPR?"float":this.scope===Ky.VIEWPORT?"vec4":"vec2"}getUpdateType(){let e=zf;return this.scope!==Ky.SIZE&&this.scope!==Ky.VIEWPORT&&this.scope!==Ky.DPR||(e=Gf),this.updateType=e,e}update({renderer:e}){const t=e.getRenderTarget();this.scope===Ky.VIEWPORT?null!==t?Yy.copy(t.viewport):(e.getViewport(Yy),Yy.multiplyScalar(e.getPixelRatio())):this.scope===Ky.DPR?this._output.value=e.getPixelRatio():null!==t?(qy.width=t.width,qy.height=t.height):e.getDrawingBufferSize(qy)}setup(){const e=this.scope;let t=null;return t=e===Ky.SIZE?a_(qy||(qy=new cn)):e===Ky.VIEWPORT?a_(Yy||(Yy=new Pn)):e===Ky.DPR?a_(1):ag(eb.div(Jy)),this._output=t,t}generate(e){if(this.scope===Ky.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const n=e.getNodeProperties(Jy).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${n}.y - ${t}.y )`}return t}return super.generate(e)}}Ky.COORDINATE="coordinate",Ky.VIEWPORT="viewport",Ky.SIZE="size",Ky.UV="uv",Ky.DPR="dpr";const Zy=$m(Ky,Ky.DPR),Qy=$m(Ky,Ky.UV),Jy=$m(Ky,Ky.SIZE),eb=$m(Ky,Ky.COORDINATE),tb=$m(Ky,Ky.VIEWPORT),nb=tb.zw;tb.xy;let ib=null,rb=null,sb=null,ab=null,ob=null,lb=null,ub=null,cb=null;const hb=a_(0,"uint").setName("u_cameraIndex").setGroup(t_("cameraIndex")).toVarying("v_cameraIndex"),db=a_("float").setName("cameraNear").setGroup(i_).onRenderUpdate(({camera:e})=>e.near),pb=a_("float").setName("cameraFar").setGroup(i_).onRenderUpdate(({camera:e})=>e.far),fb=Km(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const n=[];for(const t of e.cameras)n.push(t.projectionMatrix);null===rb?rb=$y(n).setGroup(i_).setName("cameraProjectionMatrices"):rb.array=n,t=rb.element(e.isMultiViewCamera?Xy("gl_ViewID_OVR"):hb).toConst("cameraProjectionMatrix")}else null===ib&&(ib=a_(e.projectionMatrix).setName("cameraProjectionMatrix").setGroup(i_).onRenderUpdate(({camera:e})=>e.projectionMatrix)),t=ib;return t}).once()(),mb=Km(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const n=[];for(const t of e.cameras)n.push(t.projectionMatrixInverse);null===ab?ab=$y(n).setGroup(i_).setName("cameraProjectionMatricesInverse"):ab.array=n,t=ab.element(e.isMultiViewCamera?Xy("gl_ViewID_OVR"):hb).toConst("cameraProjectionMatrixInverse")}else null===sb&&(sb=a_(e.projectionMatrixInverse).setName("cameraProjectionMatrixInverse").setGroup(i_).onRenderUpdate(({camera:e})=>e.projectionMatrixInverse)),t=sb;return t}).once()(),gb=Km(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const n=[];for(const t of e.cameras)n.push(t.matrixWorldInverse);null===lb?lb=$y(n).setGroup(i_).setName("cameraViewMatrices"):lb.array=n,t=lb.element(e.isMultiViewCamera?Xy("gl_ViewID_OVR"):hb).toConst("cameraViewMatrix")}else null===ob&&(ob=a_(e.matrixWorldInverse).setName("cameraViewMatrix").setGroup(i_).onRenderUpdate(({camera:e})=>e.matrixWorldInverse)),t=ob;return t}).once()(),_b=Km(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const n=[];for(let t=0,i=e.cameras.length;t{const n=e.cameras,i=t.array;for(let e=0,t=n.length;et.value.setFromMatrixPosition(e.matrixWorld))),t=ub;return t}).once()(),vb=new cr;class yb extends Qf{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=Hf,this.uniformNode=new s_(null)}getNodeType(){const e=this.scope;return e===yb.WORLD_MATRIX?"mat4":e===yb.POSITION||e===yb.VIEW_POSITION||e===yb.DIRECTION||e===yb.SCALE?"vec3":e===yb.RADIUS?"float":void 0}update(e){const t=this.object3d,n=this.uniformNode,i=this.scope;if(i===yb.WORLD_MATRIX)n.value=t.matrixWorld;else if(i===yb.POSITION)n.value=n.value||new dn,n.value.setFromMatrixPosition(t.matrixWorld);else if(i===yb.SCALE)n.value=n.value||new dn,n.value.setFromMatrixScale(t.matrixWorld);else if(i===yb.DIRECTION)n.value=n.value||new dn,t.getWorldDirection(n.value);else if(i===yb.VIEW_POSITION){const i=e.camera;n.value=n.value||new dn,n.value.setFromMatrixPosition(t.matrixWorld),n.value.applyMatrix4(i.matrixWorldInverse)}else if(i===yb.RADIUS){const i=e.object.geometry;null===i.boundingSphere&&i.computeBoundingSphere(),vb.copy(i.boundingSphere).applyMatrix4(t.matrixWorld),n.value=vb.radius}}generate(e){const t=this.scope;return t===yb.WORLD_MATRIX?this.uniformNode.nodeType="mat4":t===yb.POSITION||t===yb.VIEW_POSITION||t===yb.DIRECTION||t===yb.SCALE?this.uniformNode.nodeType="vec3":t===yb.RADIUS&&(this.uniformNode.nodeType="float"),this.uniformNode.build(e)}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}yb.WORLD_MATRIX="worldMatrix",yb.POSITION="position",yb.SCALE="scale",yb.VIEW_POSITION="viewPosition",yb.DIRECTION="direction",yb.RADIUS="radius";class bb extends yb{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}}const xb=$m(bb,bb.WORLD_MATRIX),Tb=a_(new mn).onObjectUpdate(({object:e},t)=>t.value.getNormalMatrix(e.matrixWorld)),Sb=Km(e=>e.context.modelViewMatrix||Mb).once()().toVar("modelViewMatrix"),Mb=gb.mul(xb),Eb=Km(e=>(e.context.isHighPrecisionModelViewMatrix=!0,a_("mat4").onObjectUpdate(({object:e,camera:t})=>e.modelViewMatrix.multiplyMatrices(t.matrixWorldInverse,e.matrixWorld)))).once()().toVar("highpModelViewMatrix"),wb=Km(e=>{const t=e.context.isHighPrecisionModelViewMatrix;return a_("mat3").onObjectUpdate(({object:e,camera:n})=>(!0!==t&&e.modelViewMatrix.multiplyMatrices(n.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix)))}).once()().toVar("highpModelNormalViewMatrix"),Ab=Km(e=>"fragment"!==e.shaderStage?(Yt("TSL: `clipSpace` is only available in fragment stage."),fg()):e.context.clipSpace.toVarying("v_clipSpace")).once()(),Rb=Ny("position","vec3"),Cb=Rb.toVarying("positionLocal"),Nb=Rb.toVarying("positionPrevious"),Pb=Km(e=>xb.mul(Cb).xyz.toVarying(e.getSubBuildProperty("v_positionWorld")),"vec3").once(["POSITION"])(),Lb=Km(()=>Cb.transformDirection(xb).toVarying("v_positionWorldDirection").normalize().toVar("positionWorldDirection"),"vec3").once(["POSITION"])(),Db=Km(e=>{if("fragment"===e.shaderStage&&e.material.vertexNode){const e=mb.mul(Ab);return e.xyz.div(e.w).toVar("positionView")}return e.context.setupPositionView().toVarying("v_positionView")},"vec3").once(["POSITION","VERTEX"])(),Ib=Km(e=>{let t;return t=e.camera.isOrthographicCamera?cg(0,0,1):Db.negate().toVarying("v_positionViewDirection").normalize(),t.toVar("positionViewDirection")},"vec3").once(["POSITION"])();class Ub extends Qf{static get type(){return"FrontFacingNode"}constructor(){super("bool"),this.isFrontFacingNode=!0}generate(e){if("fragment"!==e.shaderStage)return"true";const{material:t}=e;return 1===t.side?"false":e.getFrontFacing()}}const Fb=ng($m(Ub)).mul(2).sub(1),Ob=Km(([e],{material:t})=>{const n=t.side;return 1===n?e=e.mul(-1):2===n&&(e=e.mul(Fb)),e}),Bb=Ny("normal","vec3"),kb=Km(e=>!1===e.geometry.hasAttribute("normal")?(Xt('TSL: Vertex attribute "normal" not found on geometry.'),cg(0,1,0)):Bb,"vec3").once()().toVar("normalLocal"),zb=Db.dFdx().cross(Db.dFdy()).normalize().toVar("normalFlat"),Vb=Km(e=>{let t;return t=e.isFlatShading()?zb:Xb(kb).toVarying("v_normalViewGeometry").normalize(),t},"vec3").once()().toVar("normalViewGeometry"),Gb=Km(e=>{let t=Vb.transformDirection(gb);return!0!==e.isFlatShading()&&(t=t.toVarying("v_normalWorldGeometry")),t.normalize().toVar("normalWorldGeometry")},"vec3").once()(),Hb=Km(e=>{let t;return"NORMAL"===e.subBuildFn||"VERTEX"===e.subBuildFn?(t=Vb,!0!==e.isFlatShading()&&(t=Ob(t))):t=e.context.setupNormal().context({getUV:null,getTextureLevel:null}),t},"vec3").once(["NORMAL","VERTEX"])().toVar("normalView"),jb=Hb.transformDirection(gb).toVar("normalWorld"),Wb=Km(({subBuildFn:e,context:t})=>{let n;return n="NORMAL"===e||"VERTEX"===e?Hb:t.setupClearcoatNormal().context({getUV:null,getTextureLevel:null}),n},"vec3").once(["NORMAL","VERTEX"])().toVar("clearcoatNormalView"),$b=Km(([e,t=xb])=>{const n=yg(t),i=e.div(cg(n[0].dot(n[0]),n[1].dot(n[1]),n[2].dot(n[2])));return n.mul(i).xyz}),Xb=Km(([e],t)=>{const n=t.context.modelNormalViewMatrix;if(n)return n.transformDirection(e);const i=Tb.mul(e);return gb.transformDirection(i)});Km(()=>(Xt('TSL: "transformedNormalView" is deprecated. Use "normalView" instead.'),Hb)).once(["NORMAL","VERTEX"])(),Km(()=>(Xt('TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.'),jb)).once(["NORMAL","VERTEX"])(),Km(()=>(Xt('TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.'),Wb)).once(["NORMAL","VERTEX"])();const qb=new $n,Yb=new Fn,Kb=a_(0).onReference(({material:e})=>e).onObjectUpdate(({material:e})=>e.refractionRatio),Zb=a_(1).onReference(({material:e})=>e).onObjectUpdate(function({material:e,scene:t}){return e.envMap?e.envMapIntensity:t.environmentIntensity}),Qb=a_(new Fn).onReference(function(e){return e.material}).onObjectUpdate(function({material:e,scene:t}){const n=null!==t.environment&&null===e.envMap?t.environmentRotation:e.envMapRotation;return n?(qb.copy(n),Yb.makeRotationFromEuler(qb)):Yb.identity(),Yb}),Jb=Ib.negate().reflect(Hb),ex=Ib.negate().refract(Hb,Kb),tx=Jb.transformDirection(gb).toVar("reflectVector"),nx=ex.transformDirection(gb).toVar("reflectVector"),ix=new _s;class rx extends By{static get type(){return"CubeTextureNode"}constructor(e,t=null,n=null,i=null){super(e,t,n,i),this.isCubeTextureNode=!0}getInputType(){return!0===this.value.isDepthTexture?"cubeDepthTexture":"cubeTexture"}getDefaultUV(){const e=this.value;return e.mapping===ee?tx:e.mapping===te?nx:(qt('CubeTextureNode: Mapping "%s" not supported.',e.mapping),cg(0,0,0))}setUpdateMatrix(){}setupUV(e,t){const n=this.value;return!0===n.isDepthTexture?e.renderer.coordinateSystem===Ot?cg(t.x,t.y.negate(),t.z):t:(e.renderer.coordinateSystem!==Ot&&n.isRenderTargetTexture||(t=cg(t.x.negate(),t.yz)),Qb.mul(t))}generateUV(e,t){return t.build(e,!0===this.sampler?"vec3":"ivec3")}}const sx=Wm(rx).setParameterLength(1,4).setName("cubeTexture"),ax=(e=ix,t=null,n=null,i=null)=>{let r;return e&&!0===e.isCubeTextureNode?(r=Vm(e.clone()),r.referenceNode=e,null!==t&&(r.uvNode=Vm(t)),null!==n&&(r.levelNode=Vm(n)),null!==i&&(r.biasNode=Vm(i))):r=sx(e,t,n,i),r};class ox extends Jf{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}getNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),n=this.referenceNode.getNodeType(),i=this.getNodeType();return e.format(t,n,i)}}class lx extends Qf{static get type(){return"ReferenceNode"}constructor(e,t,n=null,i=null){super(),this.property=e,this.uniformType=t,this.object=n,this.count=i,this.properties=e.split("."),this.reference=n,this.node=null,this.group=null,this.name=null,this.updateType=Hf}element(e){return new ox(this,Vm(e))}setGroup(e){return this.group=e,this}setName(e){return this.name=e,this}label(e){return Xt('TSL: "label()" has been deprecated. Use "setName()" instead.'),this.setName(e)}setNodeType(e){let t=null;t=null!==this.count?Hy(null,e,this.count):Array.isArray(this.getValueFromReference())?$y(null,e):"texture"===e?zy(null):"cubeTexture"===e?ax(null):a_(null,e),null!==this.group&&t.setGroup(this.group),null!==this.name&&t.setName(this.name),this.node=t}getNodeType(e){return null===this.node&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let n=e[t[0]];for(let e=1;enew lx(e,t,n),cx=(e,t,n,i)=>new lx(e,t,i,n);class hx extends lx{static get type(){return"MaterialReferenceNode"}constructor(e,t,n=null){super(e,t,n),this.material=n,this.isMaterialReferenceNode=!0}updateReference(e){return this.reference=null!==this.material?this.material:e.material,this.reference}}const dx=(e,t,n=null)=>new hx(e,t,n),px=Py(),fx=Db.dFdx(),mx=Db.dFdy(),gx=px.dFdx(),_x=px.dFdy(),vx=Hb,yx=mx.cross(vx),bx=vx.cross(fx),xx=yx.mul(gx.x).add(bx.mul(_x.x)),Tx=yx.mul(gx.y).add(bx.mul(_x.y)),Sx=xx.dot(xx).max(Tx.dot(Tx)),Mx=Sx.equal(0).select(0,Sx.inverseSqrt()),Ex=xx.mul(Mx).toVar("tangentViewFrame"),wx=Tx.mul(Mx).toVar("bitangentViewFrame"),Ax=Ny("tangent","vec4"),Rx=Ax.xyz.toVar("tangentLocal"),Cx=Km(e=>{let t;return t="VERTEX"===e.subBuildFn||e.geometry.hasAttribute("tangent")?Sb.mul(fg(Rx,0)).xyz.toVarying("v_tangentView").normalize():Ex,!0!==e.isFlatShading()&&(t=Ob(t)),t},"vec3").once(["NORMAL","VERTEX"])().toVar("tangentView"),Nx=Km(([e,t],n)=>{let i=e.mul(Ax.w).xyz;return"NORMAL"===n.subBuildFn&&!0!==n.isFlatShading()&&(i=i.toVarying(t)),i}).once(["NORMAL"]),Px=yg(Cx,Km(e=>{let t;return t="VERTEX"===e.subBuildFn||e.geometry.hasAttribute("tangent")?Nx(Hb.cross(Cx),"v_bitangentView").normalize():wx,!0!==e.isFlatShading()&&(t=Ob(t)),t},"vec3").once(["NORMAL","VERTEX"])().toVar("bitangentView"),Hb).toVar("TBNViewMatrix"),Lx=Km(()=>{let e=kg.cross(Ib);return e=e.cross(kg).normalize(),e=Dv(e,Hb,Og.mul(Ag.oneMinus()).oneMinus().pow2().pow2()).normalize(),e}).once()(),Dx=e=>cg(e,q_(Uv(ng(1).sub(wv(e,e)))));class Ix extends tm{static get type(){return"NormalMapNode"}constructor(e,t=null){super("vec3"),this.node=e,this.scaleNode=t,this.normalMapType=0,this.unpackNormalMode=""}setup(e){const{normalMapType:t,scaleNode:n,unpackNormalMode:i}=this;let r=this.node.mul(2).sub(1);if(0===t?"rg"===i?r=Dx(r.xy):"ga"===i?r=Dx(r.yw):""!==i&&console.error(`THREE.NodeMaterial: Unexpected unpack normal mode: ${i}`):""!==i&&console.error(`THREE.NodeMaterial: Normal map type '${t}' is not compatible with unpack normal mode '${i}'`),null!==n){let t=n;!0===e.isFlatShading()&&(t=Ob(t)),r=cg(r.xy.mul(t),r.z)}let s=null;return 1===t?s=Xb(r):0===t?s=Px.mul(r).normalize():(qt(`NodeMaterial: Unsupported normal map type: ${t}`),s=Hb),s}}const Ux=Wm(Ix).setParameterLength(1,2),Fx=Km(({textureNode:e,bumpScale:t})=>{const n=t=>e.isolate().context({getUV:e=>t(e.uvNode||Py()),forceUVContext:!0}),i=ng(n(e=>e));return ag(ng(n(e=>e.add(e.dFdx()))).sub(i),ng(n(e=>e.add(e.dFdy()))).sub(i)).mul(t)}),Ox=Km(e=>{const{surf_pos:t,surf_norm:n,dHdxy:i}=e,r=t.dFdx().normalize(),s=n,a=t.dFdy().normalize().cross(s),o=s.cross(r),l=r.dot(a).mul(Fb),u=l.sign().mul(i.x.mul(a).add(i.y.mul(o)));return l.abs().mul(n).sub(u).normalize()});class Bx extends tm{static get type(){return"BumpMapNode"}constructor(e,t=null){super("vec3"),this.textureNode=e,this.scaleNode=t}setup(){const e=null!==this.scaleNode?this.scaleNode:1,t=Fx({textureNode:this.textureNode,bumpScale:e});return Ox({surf_pos:Db,surf_norm:Hb,dHdxy:t})}}const kx=Wm(Bx).setParameterLength(1,2),zx=new Map;class Vx extends Qf{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}getCache(e,t){let n=zx.get(e);return void 0===n&&(n=dx(e,t),zx.set(e,n)),n}getFloat(e){return this.getCache(e,"float")}getColor(e){return this.getCache(e,"color")}getTexture(e){return this.getCache("map"===e?"map":e+"Map","texture")}setup(e){const t=e.context.material,n=this.scope;let i=null;if(n===Vx.COLOR){const e=void 0!==t.color?this.getColor(n):cg();i=t.map&&!0===t.map.isTexture?e.mul(this.getTexture("map")):e}else if(n===Vx.OPACITY){const e=this.getFloat(n);i=t.alphaMap&&!0===t.alphaMap.isTexture?e.mul(this.getTexture("alpha")):e}else if(n===Vx.SPECULAR_STRENGTH)i=t.specularMap&&!0===t.specularMap.isTexture?this.getTexture("specular").r:ng(1);else if(n===Vx.SPECULAR_INTENSITY){const e=this.getFloat(n);i=t.specularIntensityMap&&!0===t.specularIntensityMap.isTexture?e.mul(this.getTexture(n).a):e}else if(n===Vx.SPECULAR_COLOR){const e=this.getColor(n);i=t.specularColorMap&&!0===t.specularColorMap.isTexture?e.mul(this.getTexture(n).rgb):e}else if(n===Vx.ROUGHNESS){const e=this.getFloat(n);i=t.roughnessMap&&!0===t.roughnessMap.isTexture?e.mul(this.getTexture(n).g):e}else if(n===Vx.METALNESS){const e=this.getFloat(n);i=t.metalnessMap&&!0===t.metalnessMap.isTexture?e.mul(this.getTexture(n).b):e}else if(n===Vx.EMISSIVE){const e=this.getFloat("emissiveIntensity"),r=this.getColor(n).mul(e);i=t.emissiveMap&&!0===t.emissiveMap.isTexture?r.mul(this.getTexture(n)):r}else if(n===Vx.NORMAL)t.normalMap?(i=Ux(this.getTexture("normal"),this.getCache("normalScale","vec2")),i.normalMapType=t.normalMapType,t.normalMap.format!=Ie&&t.normalMap.format!=_t&&t.normalMap.format!=Ke||(i.unpackNormalMode="rg")):i=t.bumpMap?kx(this.getTexture("bump").r,this.getFloat("bumpScale")):Hb;else if(n===Vx.CLEARCOAT){const e=this.getFloat(n);i=t.clearcoatMap&&!0===t.clearcoatMap.isTexture?e.mul(this.getTexture(n).r):e}else if(n===Vx.CLEARCOAT_ROUGHNESS){const e=this.getFloat(n);i=t.clearcoatRoughnessMap&&!0===t.clearcoatRoughnessMap.isTexture?e.mul(this.getTexture(n).r):e}else if(n===Vx.CLEARCOAT_NORMAL)i=t.clearcoatNormalMap?Ux(this.getTexture(n),this.getCache(n+"Scale","vec2")):Hb;else if(n===Vx.SHEEN){const e=this.getColor("sheenColor").mul(this.getFloat("sheen"));i=t.sheenColorMap&&!0===t.sheenColorMap.isTexture?e.mul(this.getTexture("sheenColor").rgb):e}else if(n===Vx.SHEEN_ROUGHNESS){const e=this.getFloat(n);i=t.sheenRoughnessMap&&!0===t.sheenRoughnessMap.isTexture?e.mul(this.getTexture(n).a):e,i=i.clamp(1e-4,1)}else if(n===Vx.ANISOTROPY)if(t.anisotropyMap&&!0===t.anisotropyMap.isTexture){const e=this.getTexture(n);i=vg(MT.x,MT.y,MT.y.negate(),MT.x).mul(e.rg.mul(2).sub(ag(1)).normalize().mul(e.b))}else i=MT;else if(n===Vx.IRIDESCENCE_THICKNESS){const e=ux("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const r=ux("0","float",t.iridescenceThicknessRange);i=e.sub(r).mul(this.getTexture(n).g).add(r)}else i=e}else if(n===Vx.TRANSMISSION){const e=this.getFloat(n);i=t.transmissionMap?e.mul(this.getTexture(n).r):e}else if(n===Vx.THICKNESS){const e=this.getFloat(n);i=t.thicknessMap?e.mul(this.getTexture(n).g):e}else if(n===Vx.IOR)i=this.getFloat(n);else if(n===Vx.LIGHT_MAP)i=this.getTexture(n).rgb.mul(this.getFloat("lightMapIntensity"));else if(n===Vx.AO)i=this.getTexture(n).r.sub(1).mul(this.getFloat("aoMapIntensity")).add(1);else if(n===Vx.LINE_DASH_OFFSET)i=t.dashOffset?this.getFloat(n):ng(0);else{const t=this.getNodeType(e);i=this.getCache(n,t)}return i}}Vx.ALPHA_TEST="alphaTest",Vx.COLOR="color",Vx.OPACITY="opacity",Vx.SHININESS="shininess",Vx.SPECULAR="specular",Vx.SPECULAR_STRENGTH="specularStrength",Vx.SPECULAR_INTENSITY="specularIntensity",Vx.SPECULAR_COLOR="specularColor",Vx.REFLECTIVITY="reflectivity",Vx.ROUGHNESS="roughness",Vx.METALNESS="metalness",Vx.NORMAL="normal",Vx.CLEARCOAT="clearcoat",Vx.CLEARCOAT_ROUGHNESS="clearcoatRoughness",Vx.CLEARCOAT_NORMAL="clearcoatNormal",Vx.EMISSIVE="emissive",Vx.ROTATION="rotation",Vx.SHEEN="sheen",Vx.SHEEN_ROUGHNESS="sheenRoughness",Vx.ANISOTROPY="anisotropy",Vx.IRIDESCENCE="iridescence",Vx.IRIDESCENCE_IOR="iridescenceIOR",Vx.IRIDESCENCE_THICKNESS="iridescenceThickness",Vx.IOR="ior",Vx.TRANSMISSION="transmission",Vx.THICKNESS="thickness",Vx.ATTENUATION_DISTANCE="attenuationDistance",Vx.ATTENUATION_COLOR="attenuationColor",Vx.LINE_SCALE="scale",Vx.LINE_DASH_SIZE="dashSize",Vx.LINE_GAP_SIZE="gapSize",Vx.LINE_WIDTH="linewidth",Vx.LINE_DASH_OFFSET="dashOffset",Vx.POINT_SIZE="size",Vx.DISPERSION="dispersion",Vx.LIGHT_MAP="light",Vx.AO="ao";const Gx=$m(Vx,Vx.ALPHA_TEST),Hx=$m(Vx,Vx.COLOR),jx=$m(Vx,Vx.SHININESS),Wx=$m(Vx,Vx.EMISSIVE),$x=$m(Vx,Vx.OPACITY),Xx=$m(Vx,Vx.SPECULAR),qx=$m(Vx,Vx.SPECULAR_INTENSITY),Yx=$m(Vx,Vx.SPECULAR_COLOR),Kx=$m(Vx,Vx.SPECULAR_STRENGTH),Zx=$m(Vx,Vx.REFLECTIVITY),Qx=$m(Vx,Vx.ROUGHNESS),Jx=$m(Vx,Vx.METALNESS),eT=$m(Vx,Vx.NORMAL),tT=$m(Vx,Vx.CLEARCOAT),nT=$m(Vx,Vx.CLEARCOAT_ROUGHNESS),iT=$m(Vx,Vx.CLEARCOAT_NORMAL),rT=$m(Vx,Vx.ROTATION),sT=$m(Vx,Vx.SHEEN),aT=$m(Vx,Vx.SHEEN_ROUGHNESS),oT=$m(Vx,Vx.ANISOTROPY),lT=$m(Vx,Vx.IRIDESCENCE),uT=$m(Vx,Vx.IRIDESCENCE_IOR),cT=$m(Vx,Vx.IRIDESCENCE_THICKNESS),hT=$m(Vx,Vx.TRANSMISSION),dT=$m(Vx,Vx.THICKNESS),pT=$m(Vx,Vx.IOR),fT=$m(Vx,Vx.ATTENUATION_DISTANCE),mT=$m(Vx,Vx.ATTENUATION_COLOR),gT=$m(Vx,Vx.LINE_SCALE),_T=$m(Vx,Vx.LINE_DASH_SIZE),vT=$m(Vx,Vx.LINE_GAP_SIZE);Vx.LINE_WIDTH;const yT=$m(Vx,Vx.LINE_DASH_OFFSET),bT=$m(Vx,Vx.POINT_SIZE),xT=$m(Vx,Vx.DISPERSION),TT=$m(Vx,Vx.LIGHT_MAP),ST=$m(Vx,Vx.AO),MT=a_(new cn).onReference(function(e){return e.material}).onRenderUpdate(function({material:e}){this.value.set(e.anisotropy*Math.cos(e.anisotropyRotation),e.anisotropy*Math.sin(e.anisotropyRotation))}),ET=Km(e=>e.context.setupModelViewProjection(),"vec4").once()().toVarying("v_modelViewProjection");class wT extends Jf{static get type(){return"StorageArrayElementNode"}constructor(e,t){super(e,t),this.isStorageArrayElementNode=!0}set storageBufferNode(e){this.node=e}get storageBufferNode(){return this.node}getMemberType(e,t){const n=this.storageBufferNode.structTypeNode;return n?n.getMemberType(e,t):"void"}setup(e){return!1===e.isAvailable("storageBuffer")&&!0===this.node.isPBO&&e.setupPBO(this.node),super.setup(e)}generate(e,t){let n;const i=e.context.assign;if(n=!1===e.isAvailable("storageBuffer")?!0!==this.node.isPBO||!0===i||!this.node.value.isInstancedBufferAttribute&&"compute"===e.shaderStage?this.node.build(e):e.generatePBO(this):super.generate(e),!0!==i){const i=this.getNodeType(e);n=e.format(n,i,t)}return n}}const AT=Wm(wT).setParameterLength(2);class RT extends Gy{static get type(){return"StorageBufferNode"}constructor(e,t=null,n=0){let i,r=null;t&&t.isStruct?(i="struct",r=t.layout,(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)&&(n=e.count)):null===t&&(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)?(i=Uf(e.itemSize),n=e.count):i=t,super(e,i,n),this.isStorageBufferNode=!0,this.structTypeNode=r,this.access=$f,this.isAtomic=!1,this.isPBO=!1,this._attribute=null,this._varying=null,this.global=!0,!0!==e.isStorageBufferAttribute&&!0!==e.isStorageInstancedBufferAttribute&&(e.isInstancedBufferAttribute?e.isStorageInstancedBufferAttribute=!0:e.isStorageBufferAttribute=!0)}getHash(e){if(0===this.bufferCount){let t=e.globalCache.getData(this.value);return void 0===t&&(t={node:this},e.globalCache.setData(this.value,t)),t.node.uuid}return this.uuid}getInputType(){return this.value.isIndirectStorageBufferAttribute?"indirectStorageBuffer":"storageBuffer"}element(e){return AT(this,e)}setPBO(e){return this.isPBO=e,this}getPBO(){return this.isPBO}setAccess(e){return this.access=e,this}toReadOnly(){return this.setAccess(jf)}setAtomic(e){return this.isAtomic=e,this}toAtomic(){return this.setAtomic(!0)}getAttributeData(){return null===this._attribute&&(this._attribute=dy(this.value),this._varying=Kv(this._attribute)),{attribute:this._attribute,varying:this._varying}}getNodeType(e){if(null!==this.structTypeNode)return this.structTypeNode.getNodeType(e);if(e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.getNodeType(e);const{attribute:t}=this.getAttributeData();return t.getNodeType(e)}getMemberType(e,t){return null!==this.structTypeNode?this.structTypeNode.getMemberType(e,t):"void"}generate(e){if(null!==this.structTypeNode&&this.structTypeNode.build(e),e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.generate(e);const{attribute:t,varying:n}=this.getAttributeData(),i=n.build(e);return e.registerTransform(i,t),i}}const CT=(e,t=null,n=0)=>new RT(e,t,n);class NT extends Qf{static get type(){return"IndexNode"}constructor(e){super("uint"),this.scope=e,this.isIndexNode=!0}generate(e){const t=this.getNodeType(e),n=this.scope;let i,r;if(n===NT.VERTEX)i=e.getVertexIndex();else if(n===NT.INSTANCE)i=e.getInstanceIndex();else if(n===NT.DRAW)i=e.getDrawIndex();else if(n===NT.INVOCATION_LOCAL)i=e.getInvocationLocalIndex();else if(n===NT.INVOCATION_SUBGROUP)i=e.getInvocationSubgroupIndex();else{if(n!==NT.SUBGROUP)throw new Error("THREE.IndexNode: Unknown scope: "+n);i=e.getSubgroupIndex()}if("vertex"===e.shaderStage||"compute"===e.shaderStage)r=i;else{r=Kv(this).build(e,t)}return r}}NT.VERTEX="vertex",NT.INSTANCE="instance",NT.SUBGROUP="subgroup",NT.INVOCATION_LOCAL="invocationLocal",NT.INVOCATION_SUBGROUP="invocationSubgroup",NT.DRAW="draw";const PT=$m(NT,NT.VERTEX),LT=$m(NT,NT.INSTANCE);NT.SUBGROUP,NT.INVOCATION_SUBGROUP,NT.INVOCATION_LOCAL;const DT=$m(NT,NT.DRAW);class IT extends Qf{static get type(){return"InstanceNode"}constructor(e,t,n=null){super("void"),this.count=e,this.instanceMatrix=t,this.instanceColor=n,this.instanceMatrixNode=null,this.instanceColorNode=null,this.updateType=Vf,this.buffer=null,this.bufferColor=null,this.previousInstanceMatrixNode=null}get isStorageMatrix(){const{instanceMatrix:e}=this;return e&&!0===e.isStorageInstancedBufferAttribute}get isStorageColor(){const{instanceColor:e}=this;return e&&!0===e.isStorageInstancedBufferAttribute}setup(e){let{instanceMatrixNode:t,instanceColorNode:n}=this;null===t&&(t=this._createInstanceMatrixNode(!0,e),this.instanceMatrixNode=t);const{instanceColor:i,isStorageColor:r}=this;if(i&&null===n){if(r)n=CT(i,"vec3",Math.max(i.count,1)).element(LT);else{const e=new qr(i.array,3),t=i.usage===It?fy:py;this.bufferColor=e,n=cg(t(e,"vec3",3,0))}this.instanceColorNode=n}const s=t.mul(Cb).xyz;if(Cb.assign(s),e.needsPreviousData()&&Nb.assign(this.getPreviousInstancedPosition(e)),e.hasGeometryAttribute("normal")){const e=$b(kb,t);kb.assign(e)}null!==this.instanceColorNode&&Sg("vec3","vInstanceColor").assign(this.instanceColorNode)}update(e){null!==this.buffer&&!0!==this.isStorageMatrix&&(this.buffer.clearUpdateRanges(),this.buffer.updateRanges.push(...this.instanceMatrix.updateRanges),this.instanceMatrix.version!==this.buffer.version&&(this.buffer.version=this.instanceMatrix.version)),this.instanceColor&&null!==this.bufferColor&&!0!==this.isStorageColor&&(this.bufferColor.clearUpdateRanges(),this.bufferColor.updateRanges.push(...this.instanceColor.updateRanges),this.instanceColor.version!==this.bufferColor.version&&(this.bufferColor.version=this.instanceColor.version)),null!==this.previousInstanceMatrixNode&&e.object.previousInstanceMatrix.array.set(this.instanceMatrix.array)}getPreviousInstancedPosition(e){const t=e.object;return null===this.previousInstanceMatrixNode&&(t.previousInstanceMatrix=this.instanceMatrix.clone(),this.previousInstanceMatrixNode=this._createInstanceMatrixNode(!1,e)),this.previousInstanceMatrixNode.mul(Nb).xyz}_createInstanceMatrixNode(e,t){let n;const{instanceMatrix:i}=this,{count:r}=i;if(this.isStorageMatrix)n=CT(i,"mat4",Math.max(r,1)).element(LT);else{if(16*r*4<=t.getUniformBufferLimit())n=Hy(i.array,"mat4",Math.max(r,1)).element(LT);else{const t=new za(i.array,16,1);!0===e&&(this.buffer=t);const r=i.usage===It?fy:py,s=[r(t,"vec4",16,0),r(t,"vec4",16,4),r(t,"vec4",16,8),r(t,"vec4",16,12)];n=bg(...s)}}return n}}class UT extends IT{static get type(){return"InstancedMeshNode"}constructor(e){const{count:t,instanceMatrix:n,instanceColor:i}=e;super(t,n,i),this.instancedMesh=e}}const FT=Wm(UT).setParameterLength(1);class OT extends Qf{static get type(){return"BatchNode"}constructor(e){super("void"),this.batchMesh=e,this.batchingIdNode=null}setup(e){null===this.batchingIdNode&&(null===e.getDrawIndex()?this.batchingIdNode=LT:this.batchingIdNode=DT);const t=Km(([e])=>{const t=ig(Dy(Vy(this.batchMesh._indirectTexture),0).x).toConst(),n=ig(e).mod(t).toConst(),i=ig(e).div(t).toConst();return Vy(this.batchMesh._indirectTexture,og(n,i)).x}).setLayout({name:"getIndirectIndex",type:"uint",inputs:[{name:"id",type:"int"}]}),n=t(ig(this.batchingIdNode)),i=this.batchMesh._matricesTexture,r=ig(Dy(Vy(i),0).x).toConst(),s=ng(n).mul(4).toInt().toConst(),a=s.mod(r).toConst(),o=s.div(r).toConst(),l=bg(Vy(i,og(a,o)),Vy(i,og(a.add(1),o)),Vy(i,og(a.add(2),o)),Vy(i,og(a.add(3),o))),u=this.batchMesh._colorsTexture;if(null!==u){const e=Km(([e])=>{const t=ig(Dy(Vy(u),0).x).toConst(),n=e,i=n.mod(t).toConst(),r=n.div(t).toConst();return Vy(u,og(i,r)).rgb}).setLayout({name:"getBatchingColor",type:"vec3",inputs:[{name:"id",type:"int"}]}),t=e(n);Sg("vec3","vBatchColor").assign(t)}const c=yg(l);Cb.assign(l.mul(Cb));const h=kb.div(cg(c[0].dot(c[0]),c[1].dot(c[1]),c[2].dot(c[2]))),d=c.mul(h).xyz;kb.assign(d),e.hasGeometryAttribute("tangent")&&Rx.mulAssign(c)}}const BT=Wm(OT).setParameterLength(1),kT=new WeakMap;class zT extends Qf{static get type(){return"SkinningNode"}constructor(e){super("void"),this.skinnedMesh=e,this.updateType=Hf,this.skinIndexNode=Ny("skinIndex","uvec4"),this.skinWeightNode=Ny("skinWeight","vec4"),this.bindMatrixNode=ux("bindMatrix","mat4"),this.bindMatrixInverseNode=ux("bindMatrixInverse","mat4"),this.boneMatricesNode=cx("skeleton.boneMatrices","mat4",e.skeleton.bones.length),this.positionNode=Cb,this.toPositionNode=Cb,this.previousBoneMatricesNode=null}getSkinnedPosition(e=this.boneMatricesNode,t=this.positionNode){const{skinIndexNode:n,skinWeightNode:i,bindMatrixNode:r,bindMatrixInverseNode:s}=this,a=e.element(n.x),o=e.element(n.y),l=e.element(n.z),u=e.element(n.w),c=r.mul(t),h=d_(a.mul(i.x).mul(c),o.mul(i.y).mul(c),l.mul(i.z).mul(c),u.mul(i.w).mul(c));return s.mul(h).xyz}getSkinnedNormalAndTangent(e=this.boneMatricesNode,t=kb,n=Rx){const{skinIndexNode:i,skinWeightNode:r,bindMatrixNode:s,bindMatrixInverseNode:a}=this,o=e.element(i.x),l=e.element(i.y),u=e.element(i.z),c=e.element(i.w);let h=d_(r.x.mul(o),r.y.mul(l),r.z.mul(u),r.w.mul(c));h=a.mul(h).mul(s);return{skinNormal:h.transformDirection(t).xyz,skinTangent:h.transformDirection(n).xyz}}getPreviousSkinnedPosition(e){const t=e.object;return null===this.previousBoneMatricesNode&&(t.skeleton.previousBoneMatrices=new Float32Array(t.skeleton.boneMatrices),this.previousBoneMatricesNode=cx("skeleton.previousBoneMatrices","mat4",t.skeleton.bones.length)),this.getSkinnedPosition(this.previousBoneMatricesNode,Nb)}setup(e){e.needsPreviousData()&&Nb.assign(this.getPreviousSkinnedPosition(e));const t=this.getSkinnedPosition();if(this.toPositionNode&&this.toPositionNode.assign(t),e.hasGeometryAttribute("normal")){const{skinNormal:t,skinTangent:n}=this.getSkinnedNormalAndTangent();kb.assign(t),e.hasGeometryAttribute("tangent")&&Rx.assign(n)}return t}generate(e,t){if("void"!==t)return super.generate(e,t)}update(e){const t=e.object&&e.object.skeleton?e.object.skeleton:this.skinnedMesh.skeleton;kT.get(t)!==e.frameId&&(kT.set(t,e.frameId),null!==this.previousBoneMatricesNode&&(null===t.previousBoneMatrices&&(t.previousBoneMatrices=new Float32Array(t.boneMatrices)),t.previousBoneMatrices.set(t.boneMatrices)),t.update())}}class VT extends Qf{static get type(){return"LoopNode"}constructor(e=[]){super("void"),this.params=e}getVarName(e){return String.fromCharCode("i".charCodeAt(0)+e)}getProperties(e){const t=e.getNodeProperties(this);if(void 0!==t.stackNode)return t;const n={};for(let e=0,t=this.params.length-1;eNumber(l)?">=":"<")),a)s=`while ( ${l} )`;else{const n={start:o,end:l},i=n.start,r=n.end;let a;const p=()=>h.includes("<")?"+=":"-=";if(null!=d)switch(typeof d){case"function":a=e.flowStagesNode(t.updateNode,"void").code.replace(/\t|;/g,"");break;case"number":a=u+" "+p()+" "+e.generateConst(c,d);break;case"string":a=u+" "+d;break;default:d.isNode?a=u+" "+p()+" "+d.build(e):(qt("TSL: 'Loop( { update: ... } )' is not a function, string or number.",this.stackTrace),a="break /* invalid update */")}else d="int"===c||"uint"===c?h.includes("<")?"++":"--":p()+" 1.",a=u+" "+d;s=`for ( ${e.getVar(c,u)+" = "+i}; ${u+" "+h+" "+r}; ${a} )`}e.addFlowCode((0===i?"\n":"")+e.tab+s+" {\n\n").addFlowTab()}const r=i.build(e,"void");t.returnsNode.build(e,"void"),e.removeFlowTab().addFlowCode("\n"+e.tab+r);for(let t=0,n=this.params.length-1;tnew VT(jm(e,"int")).toStack(),HT=new WeakMap,jT=new Pn,WT=Km(({bufferMap:e,influence:t,stride:n,width:i,depth:r,offset:s})=>{const a=ig(PT).mul(n).add(s),o=a.div(i),l=a.sub(o.mul(i));return Vy(e,og(l,o)).depth(r).xyz.mul(t)});class $T extends Qf{static get type(){return"MorphNode"}constructor(e){super("void"),this.mesh=e,this.morphBaseInfluence=a_(1),this.updateType=Hf}setup(e){const{geometry:t}=e,n=void 0!==t.morphAttributes.position,i=t.hasAttribute("normal")&&void 0!==t.morphAttributes.normal,r=t.morphAttributes.position||t.morphAttributes.normal||t.morphAttributes.color,s=void 0!==r?r.length:0,{texture:a,stride:o,size:l}=function(e){const t=void 0!==e.morphAttributes.position,n=void 0!==e.morphAttributes.normal,i=void 0!==e.morphAttributes.color,r=e.morphAttributes.position||e.morphAttributes.normal||e.morphAttributes.color,s=void 0!==r?r.length:0;let a=HT.get(e);if(void 0===a||a.count!==s){void 0!==a&&a.texture.dispose();const o=e.morphAttributes.position||[],l=e.morphAttributes.normal||[],u=e.morphAttributes.color||[];let c=0;!0===t&&(c=1),!0===n&&(c=2),!0===i&&(c=3);let h=e.attributes.position.count*c,d=1;const p=4096;h>p&&(d=Math.ceil(h/p),h=p);const f=new Float32Array(h*d*4*s),m=new In(f,h,d,s);m.type=be,m.needsUpdate=!0;const g=4*c;for(let v=0;v{const t=ng(0).toVar();this.mesh.count>1&&null!==this.mesh.morphTexture&&void 0!==this.mesh.morphTexture?t.assign(Vy(this.mesh.morphTexture,og(ig(e).add(1),ig(LT))).r):t.assign(ux("morphTargetInfluences","float").element(e).toVar()),Jm(t.notEqual(0),()=>{!0===n&&Cb.addAssign(WT({bufferMap:a,influence:t,stride:o,width:u,depth:e,offset:ig(0)})),!0===i&&kb.addAssign(WT({bufferMap:a,influence:t,stride:o,width:u,depth:e,offset:ig(1)}))})})}update(){const e=this.morphBaseInfluence;this.mesh.geometry.morphTargetsRelative?e.value=1:e.value=1-this.mesh.morphTargetInfluences.reduce((e,t)=>e+t,0)}}const XT=Wm($T).setParameterLength(1);class qT extends Qf{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}}class YT extends qT{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}}class KT extends Gv{static get type(){return"LightingContextNode"}constructor(e,t=null,n=null,i=null){super(e),this.lightingModel=t,this.backdropNode=n,this.backdropAlphaNode=i,this._value=null}getContext(){const{backdropNode:e,backdropAlphaNode:t}=this,n={directDiffuse:cg().toVar("directDiffuse"),directSpecular:cg().toVar("directSpecular"),indirectDiffuse:cg().toVar("indirectDiffuse"),indirectSpecular:cg().toVar("indirectSpecular")};return{radiance:cg().toVar("radiance"),irradiance:cg().toVar("irradiance"),iblIrradiance:cg().toVar("iblIrradiance"),ambientOcclusion:ng(1).toVar("ambientOcclusion"),reflectedLight:n,backdrop:e,backdropAlpha:t}}setup(e){return this.value=this._value||(this._value=this.getContext()),this.value.lightingModel=this.lightingModel||e.context.lightingModel,super.setup(e)}}const ZT=Wm(KT);class QT extends qT{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}}const JT=new cn;class eS extends By{static get type(){return"ViewportTextureNode"}constructor(e=Qy,t=null,n=null){let i=null;null===n?(i=new gs,i.minFilter=pe,n=i):i=n,super(n,e,t),this.generateMipmaps=!1,this.defaultFramebuffer=i,this.isOutputTextureNode=!0,this.updateBeforeType=Gf,this._cacheTextures=new WeakMap}getTextureForReference(e=null){let t,n;if(this.referenceNode?(t=this.referenceNode.defaultFramebuffer,n=this.referenceNode._cacheTextures):(t=this.defaultFramebuffer,n=this._cacheTextures),null===e)return t;if(!1===n.has(e)){const i=t.clone();n.set(e,i)}return n.get(e)}updateReference(e){const t=e.renderer.getRenderTarget();return this.value=this.getTextureForReference(t),this.value}updateBefore(e){const t=e.renderer,n=t.getRenderTarget();null===n?t.getDrawingBufferSize(JT):JT.set(n.width,n.height);const i=this.getTextureForReference(n);i.image.width===JT.width&&i.image.height===JT.height||(i.image.width=JT.width,i.image.height=JT.height,i.needsUpdate=!0);const r=i.generateMipmaps;i.generateMipmaps=this.generateMipmaps,t.copyFramebufferToTexture(i),i.generateMipmaps=r}clone(){const e=new this.constructor(this.uvNode,this.levelNode,this.value);return e.generateMipmaps=this.generateMipmaps,e}}const tS=Wm(eS,null,null,{generateMipmaps:!0}).setParameterLength(0,3),nS=tS(),iS=(e=Qy,t=null)=>nS.sample(e,t);let rS=null;class sS extends eS{static get type(){return"ViewportDepthTextureNode"}constructor(e=Qy,t=null){null===rS&&(rS=new vs),super(e,t,rS)}getTextureForReference(){return rS}}const aS=Wm(sS).setParameterLength(0,2);class oS extends Qf{static get type(){return"ViewportDepthNode"}constructor(e,t=null){super("float"),this.scope=e,this.valueNode=t,this.isViewportDepthNode=!0}generate(e){const{scope:t}=this;return t===oS.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){const{scope:t}=this,n=this.valueNode;let i=null;if(t===oS.DEPTH_BASE)null!==n&&(i=dS().assign(n));else if(t===oS.DEPTH)i=e.isPerspectiveCamera?uS(Db.z,db,pb):lS(Db.z,db,pb);else if(t===oS.LINEAR_DEPTH)if(null!==n)if(e.isPerspectiveCamera){const e=cS(n,db,pb);i=lS(e,db,pb)}else i=n;else i=lS(Db.z,db,pb);return i}}oS.DEPTH_BASE="depthBase",oS.DEPTH="depth",oS.LINEAR_DEPTH="linearDepth";const lS=(e,t,n)=>e.add(t).div(t.sub(n)),uS=(e,t,n)=>t.add(e).mul(n).div(n.sub(t).mul(e)),cS=Km(([e,t,n],i)=>!0===i.renderer.reversedDepthBuffer?t.mul(n).div(t.sub(n).mul(e).sub(t)):t.mul(n).div(n.sub(t).mul(e).sub(n))),hS=(e,t,n)=>{t=t.max(1e-6).toVar();const i=X_(e.negate().div(t)),r=X_(n.div(t));return i.div(r)},dS=Wm(oS,oS.DEPTH_BASE),pS=$m(oS,oS.DEPTH);aS(),pS.assign=e=>dS(e);class fS extends Qf{static get type(){return"ClippingNode"}constructor(e=fS.DEFAULT){super(),this.scope=e}setup(e){super.setup(e);const t=e.clippingContext,{intersectionPlanes:n,unionPlanes:i}=t;return this.hardwareClipping=e.material.hardwareClipping,this.scope===fS.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(n,i):this.scope===fS.HARDWARE?this.setupHardwareClipping(i,e):this.setupDefault(n,i)}setupAlphaToCoverage(e,t){return Km(()=>{const n=ng().toVar("distanceToPlane"),i=ng().toVar("distanceToGradient"),r=ng(1).toVar("clipOpacity"),s=t.length;if(!1===this.hardwareClipping&&s>0){const e=$y(t).setGroup(i_);GT(s,({i:t})=>{const s=e.element(t);n.assign(Db.dot(s.xyz).negate().add(s.w)),i.assign(n.fwidth().div(2)),r.mulAssign(Ov(i.negate(),i,n))})}const a=e.length;if(a>0){const t=$y(e).setGroup(i_),s=ng(1).toVar("intersectionClipOpacity");GT(a,({i:e})=>{const r=t.element(e);n.assign(Db.dot(r.xyz).negate().add(r.w)),i.assign(n.fwidth().div(2)),s.mulAssign(Ov(i.negate(),i,n).oneMinus())}),r.mulAssign(s.oneMinus())}Mg.a.mulAssign(r),Mg.a.equal(0).discard()})()}setupDefault(e,t){return Km(()=>{const n=t.length;if(!1===this.hardwareClipping&&n>0){const e=$y(t).setGroup(i_);GT(n,({i:t})=>{const n=e.element(t);Db.dot(n.xyz).greaterThan(n.w).discard()})}const i=e.length;if(i>0){const t=$y(e).setGroup(i_),n=sg(!0).toVar("clipped");GT(i,({i:e})=>{const i=t.element(e);n.assign(Db.dot(i.xyz).greaterThan(i.w).and(n))}),n.discard()}})()}setupHardwareClipping(e,t){const n=e.length;return t.enableHardwareClipping(n),Km(()=>{const i=$y(e).setGroup(i_),r=Xy(t.getClipDistance());GT(n,({i:e})=>{const t=i.element(e),n=Db.dot(t.xyz).sub(t.w).negate();r.element(e).assign(n)})})()}}fS.ALPHA_TO_COVERAGE="alphaToCoverage",fS.DEFAULT="default",fS.HARDWARE="hardware";const mS=Km(([e])=>J_(f_(1e4,ev(f_(17,e.x).add(f_(.1,e.y)))).mul(d_(.1,av(ev(f_(13,e.y).add(e.x))))))),gS=Km(([e])=>mS(ag(mS(e.xy),e.z))),_S=Km(([e])=>{const t=xv(lv(hv(e.xyz)),lv(dv(e.xyz))),n=ng(1).div(ng(.05).mul(t)).toVar("pixScale"),i=ag(W_(K_(X_(n))),W_(Z_(X_(n)))),r=ag(gS(K_(i.x.mul(e.xyz))),gS(K_(i.y.mul(e.xyz)))),s=J_(X_(n)),a=d_(f_(s.oneMinus(),r.x),f_(s,r.y)),o=bv(s,s.oneMinus()),l=cg(a.mul(a).div(f_(2,o).mul(p_(1,o))),a.sub(f_(.5,o)).div(p_(1,o)),p_(1,p_(1,a).mul(p_(1,a)).div(f_(2,o).mul(p_(1,o))))),u=a.lessThan(o.oneMinus()).select(a.lessThan(o).select(l.x,l.y),l.z);return Iv(u,1e-6,1)}).setLayout({name:"getAlphaHashThreshold",type:"float",inputs:[{name:"position",type:"vec3"}]});class vS extends Cy{static get type(){return"VertexColorNode"}constructor(e){super(null,"vec4"),this.isVertexColorNode=!0,this.index=e}getAttributeName(){const e=this.index;return"color"+(e>0?e:"")}generate(e){const t=this.getAttributeName(e);let n;return n=!0===e.hasGeometryAttribute(t)?super.generate(e):e.generateConst(this.nodeType,new Pn(1,1,1,1)),n}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}}const yS=Km(([e])=>fg(e.rgb.mul(e.a),e.a),{color:"vec4",return:"vec4"});class bS extends Sr{static get type(){return"NodeMaterial"}get type(){return this.constructor.type}set type(e){}constructor(){super(),this.isNodeMaterial=!0,this.fog=!0,this.lights=!1,this.hardwareClipping=!1,this.lightsNode=null,this.envNode=null,this.aoNode=null,this.colorNode=null,this.normalNode=null,this.opacityNode=null,this.backdropNode=null,this.backdropAlphaNode=null,this.alphaTestNode=null,this.maskNode=null,this.maskShadowNode=null,this.positionNode=null,this.geometryNode=null,this.depthNode=null,this.receivedShadowPositionNode=null,this.castShadowPositionNode=null,this.receivedShadowNode=null,this.castShadowNode=null,this.outputNode=null,this.mrtNode=null,this.fragmentNode=null,this.vertexNode=null,this.contextNode=null}_getNodeChildren(){const e=[];for(const t of Object.getOwnPropertyNames(this)){if(!0===t.startsWith("_"))continue;const n=this[t];n&&!0===n.isNode&&e.push({property:t,childNode:n})}return e}customProgramCacheKey(){const e=[];for(const{property:t,childNode:n}of this._getNodeChildren())e.push(Nf(t.slice(0,-4)),n.getCacheKey());return this.type+Pf(e)}build(e){this.setup(e)}setupObserver(e){return new wf(e)}setup(e){e.context.setupNormal=()=>qv(this.setupNormal(e),"NORMAL","vec3"),e.context.setupPositionView=()=>this.setupPositionView(e),e.context.setupModelViewProjection=()=>this.setupModelViewProjection(e);const t=e.renderer,n=t.getRenderTarget();!0===t.contextNode.isContextNode?e.context={...e.context,...t.contextNode.getFlowContextData()}:qt('NodeMaterial: "renderer.contextNode" must be an instance of `context()`.'),null!==this.contextNode&&(!0===this.contextNode.isContextNode?e.context={...e.context,...this.contextNode.getFlowContextData()}:qt('NodeMaterial: "material.contextNode" must be an instance of `context()`.')),e.addStack();const i=this.setupVertex(e),r=qv(this.vertexNode||i,"VERTEX");let s;e.context.clipSpace=r,e.stack.outputNode=r,this.setupHardwareClipping(e),null!==this.geometryNode&&(e.stack.outputNode=e.stack.outputNode.bypass(this.geometryNode)),e.addFlow("vertex",e.removeStack()),e.addStack();const a=this.setupClipping(e);if(!0!==this.depthWrite&&!0!==this.depthTest||(null!==n?!0===n.depthBuffer&&this.setupDepth(e):!0===t.depth&&this.setupDepth(e)),null===this.fragmentNode){this.setupDiffuseColor(e),this.setupVariants(e);const i=this.setupLighting(e);null!==a&&e.stack.addToStack(a);const r=fg(i,Mg.a).max(0);s=this.setupOutput(e,r),jg.assign(s);const o=null!==this.outputNode;if(o&&(s=this.outputNode),e.context.getOutput&&(s=e.context.getOutput(s,e)),null!==n){const e=t.getMRT(),n=this.mrtNode;null!==e?(o&&jg.assign(s),s=e,null!==n&&(s=e.merge(n))):null!==n&&(s=n)}}else{let t=this.fragmentNode;!0!==t.isOutputStructNode&&(t=fg(t)),s=this.setupOutput(e,t)}e.stack.outputNode=s,e.addFlow("fragment",e.removeStack()),e.observer=this.setupObserver(e)}setupClipping(e){if(null===e.clippingContext)return null;const{unionPlanes:t,intersectionPlanes:n}=e.clippingContext;let i=null;if(t.length>0||n.length>0){const t=e.renderer.currentSamples;this.alphaToCoverage&&t>1?i=new fS(fS.ALPHA_TO_COVERAGE):e.stack.addToStack(new fS)}return i}setupHardwareClipping(e){if(this.hardwareClipping=!1,null===e.clippingContext)return;const t=e.clippingContext.unionPlanes.length;t>0&&t<=8&&e.isAvailable("clipDistance")&&(e.stack.addToStack(new fS(fS.HARDWARE)),this.hardwareClipping=!0)}setupDepth(e){const{renderer:t,camera:n}=e;let i=this.depthNode;if(null===i){const e=t.getMRT();e&&e.has("depth")?i=e.get("depth"):!0===t.logarithmicDepthBuffer&&(i=n.isPerspectiveCamera?hS(Db.z,db,pb):lS(Db.z,db,pb))}null!==i&&pS.assign(i).toStack()}setupPositionView(){return Sb.mul(Cb).xyz}setupModelViewProjection(){return fb.mul(Db)}setupVertex(e){return e.addStack(),this.setupPosition(e),e.context.position=e.removeStack(),ET}setupPosition(e){const{object:t,geometry:n}=e;var i;if((n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color)&&XT(t).toStack(),!0===t.isSkinnedMesh&&(i=t,new zT(i)).toStack(),this.displacementMap){const e=dx("displacementMap","texture"),t=dx("displacementScale","float"),n=dx("displacementBias","float");Cb.addAssign(kb.normalize().mul(e.x.mul(t).add(n)))}return t.isBatchedMesh&&BT(t).toStack(),t.isInstancedMesh&&t.instanceMatrix&&!0===t.instanceMatrix.isInstancedBufferAttribute&&FT(t).toStack(),null!==this.positionNode&&Cb.assign(qv(this.positionNode,"POSITION","vec3")),Cb}setupDiffuseColor(e){const{object:t,geometry:n}=e;null!==this.maskNode&&sg(this.maskNode).not().discard();let i=this.colorNode?fg(this.colorNode):Hx;if(!0===this.vertexColors&&n.hasAttribute("color")&&(i=i.mul(((e=0)=>new vS(e))())),t.instanceColor){i=Sg("vec3","vInstanceColor").mul(i)}if(t.isBatchedMesh&&t._colorsTexture){i=Sg("vec3","vBatchColor").mul(i)}Mg.assign(i);const r=this.opacityNode?ng(this.opacityNode):$x;Mg.a.assign(Mg.a.mul(r));let s=null;(null!==this.alphaTestNode||this.alphaTest>0)&&(s=null!==this.alphaTestNode?ng(this.alphaTestNode):Gx,!0===this.alphaToCoverage?(Mg.a=Ov(s,s.add(gv(Mg.a)),Mg.a),Mg.a.lessThanEqual(0).discard()):Mg.a.lessThanEqual(s).discard()),!0===this.alphaHash&&Mg.a.lessThan(_S(Cb)).discard(),e.isOpaque()&&Mg.a.assign(1)}setupVariants(){}setupOutgoingLight(){return!0===this.lights?cg(0):Mg.rgb}setupNormal(){return this.normalNode?cg(this.normalNode):eT}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?dx("envMap","cubeTexture"):dx("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new QT(TT)),t}setupLights(e){const t=[],n=this.setupEnvironment(e);n&&n.isLightingNode&&t.push(n);const i=this.setupLightMap(e);i&&i.isLightingNode&&t.push(i);let r=this.aoNode;null===r&&e.material.aoMap&&(r=ST),e.context.getAO&&(r=e.context.getAO(r,e)),r&&t.push(new YT(r));let s=this.lightsNode||e.lightsNode;return t.length>0&&(s=e.renderer.lighting.createNode([...s.getLights(),...t])),s}setupLightingModel(){}setupLighting(e){const{material:t}=e,{backdropNode:n,backdropAlphaNode:i,emissiveNode:r}=this,s=!0===this.lights||null!==this.lightsNode?this.setupLights(e):null;let a=this.setupOutgoingLight(e);if(s&&s.getScope().hasLights){const t=this.setupLightingModel(e)||null;a=ZT(s,t,n,i)}else null!==n&&(a=cg(null!==i?Dv(a,n,i):n));return(r&&!0===r.isNode||t.emissive&&!0===t.emissive.isColor)&&(wg.assign(cg(r||Wx)),a=a.add(wg)),a}setupFog(e,t){const n=e.fogNode;return n&&(jg.assign(t),t=fg(n.toVar())),t}setupPremultipliedAlpha(e,t){return yS(t)}setupOutput(e,t){return!0===this.fog&&(t=this.setupFog(e,t)),!0===this.premultipliedAlpha&&(t=this.setupPremultipliedAlpha(e,t)),t}setDefaultValues(e){for(const t in e){const n=e[t];void 0===this[t]&&(this[t]=n,n&&n.clone&&(this[t]=n.clone()))}const t=Object.getOwnPropertyDescriptors(e.constructor.prototype);for(const e in t)void 0===Object.getOwnPropertyDescriptor(this.constructor.prototype,e)&&void 0!==t[e].get&&Object.defineProperty(this.constructor.prototype,e,t[e])}toJSON(e){const t=void 0===e||"string"==typeof e;t&&(e={textures:{},images:{},nodes:{}});const n=Sr.prototype.toJSON.call(this,e);n.inputNodes={};for(const{property:t,childNode:i}of this._getNodeChildren())n.inputNodes[t]=i.toJSON(e).uuid;function i(e){const t=[];for(const n in e){const i=e[n];delete i.metadata,t.push(i)}return t}if(t){const t=i(e.textures),r=i(e.images),s=i(e.nodes);t.length>0&&(n.textures=t),r.length>0&&(n.images=r),s.length>0&&(n.nodes=s)}return n}copy(e){return this.lightsNode=e.lightsNode,this.envNode=e.envNode,this.aoNode=e.aoNode,this.colorNode=e.colorNode,this.normalNode=e.normalNode,this.opacityNode=e.opacityNode,this.backdropNode=e.backdropNode,this.backdropAlphaNode=e.backdropAlphaNode,this.alphaTestNode=e.alphaTestNode,this.maskNode=e.maskNode,this.maskShadowNode=e.maskShadowNode,this.positionNode=e.positionNode,this.geometryNode=e.geometryNode,this.depthNode=e.depthNode,this.receivedShadowPositionNode=e.receivedShadowPositionNode,this.castShadowPositionNode=e.castShadowPositionNode,this.receivedShadowNode=e.receivedShadowNode,this.castShadowNode=e.castShadowNode,this.outputNode=e.outputNode,this.mrtNode=e.mrtNode,this.fragmentNode=e.fragmentNode,this.vertexNode=e.vertexNode,this.contextNode=e.contextNode,super.copy(e)}}const xS=new as;class TS extends bS{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.setDefaultValues(xS),this.setValues(e)}}const SS=new na;class MS extends bS{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.setDefaultValues(SS),this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode?ng(this.offsetNode):yT,t=this.dashScaleNode?ng(this.dashScaleNode):gT,n=this.dashSizeNode?ng(this.dashSizeNode):_T,i=this.gapSizeNode?ng(this.gapSizeNode):vT;Wg.assign(n),$g.assign(i);const r=Kv(Ny("lineDistance").mul(t));(e?r.add(e):r).mod(Wg.add($g)).greaterThan(Wg).discard()}}const ES=new Zs;class wS extends bS{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(ES),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?ng(this.opacityNode):$x;Mg.assign(ty(fg(Vm(Hb).mul(.5).add(.5),e),bt))}}const AS=Km(([e=Lb])=>{const t=e.z.atan(e.x).mul(1/(2*Math.PI)).add(.5),n=e.y.clamp(-1,1).asin().mul(1/Math.PI).add(.5);return ag(t,n)});class RS extends Ln{constructor(e=1,t={}){super(e,e,t),this.isCubeRenderTarget=!0;const n={width:e,height:e,depth:1},i=[n,n,n,n,n,n];this.texture=new _s(i),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){const n=t.minFilter,i=t.generateMipmaps;t.generateMipmaps=!0,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;const r=new xs(5,5,5),s=AS(Lb),a=new bS;a.colorNode=zy(t,s,0),a.side=1,a.blending=0;const o=new Wr(r,a),l=new yi;l.add(o),t.minFilter===pe&&(t.minFilter=he);const u=new Fa(1,10,this),c=e.getMRT();return e.setMRT(null),u.update(e,l),e.setMRT(c),t.minFilter=n,t.currentGenerateMipmaps=i,o.geometry.dispose(),o.material.dispose(),this}clear(e,t=!0,n=!0,i=!0){const r=e.getRenderTarget();for(let r=0;r<6;r++)e.setRenderTarget(this,r),e.clear(t,n,i);e.setRenderTarget(r)}}const CS=new WeakMap;class NS extends tm{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=ax(null);const t=new _s;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=Gf}updateBefore(e){const{renderer:t,material:n}=e,i=this.envNode;if(i.isTextureNode||i.isMaterialReferenceNode){const e=i.isTextureNode?i.value:n[i.property];if(e&&e.isTexture){const n=e.mapping;if(n===ne||n===ie){if(CS.has(e)){const t=CS.get(e);LS(t,e.mapping),this._cubeTexture=t}else{const n=e.image;if(function(e){return null!=e&&e.height>0}(n)){const i=new RS(n.height);i.fromEquirectangularTexture(t,e),LS(i.texture,e.mapping),this._cubeTexture=i.texture,CS.set(e,i.texture),e.addEventListener("dispose",PS)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}}function PS(e){const t=e.target;t.removeEventListener("dispose",PS);const n=CS.get(t);void 0!==n&&(CS.delete(t),n.dispose())}function LS(e,t){t===ne?e.mapping=ee:t===ie&&(e.mapping=te)}const DS=Wm(NS).setParameterLength(1);class IS extends qT{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=DS(this.envNode)}}class US extends qT{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){const t=ng(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}}class FS{start(e){e.lightsNode.setupLights(e,e.lightsNode.getLightNodes(e)),this.indirect(e)}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}}class OS extends FS{constructor(){super()}indirect({context:e}){const t=e.ambientOcclusion,n=e.reflectedLight,i=e.irradianceLightMap;n.indirectDiffuse.assign(fg(0)),i?n.indirectDiffuse.addAssign(i):n.indirectDiffuse.addAssign(fg(1,1,1,0)),n.indirectDiffuse.mulAssign(t),n.indirectDiffuse.mulAssign(Mg.rgb)}finish(e){const{material:t,context:n}=e,i=n.outgoingLight,r=e.context.environment;if(r)switch(t.combine){case 0:i.rgb.assign(Dv(i.rgb,i.rgb.mul(r.rgb),Kx.mul(Zx)));break;case 1:i.rgb.assign(Dv(i.rgb,r.rgb,Kx.mul(Zx)));break;case 2:i.rgb.addAssign(r.rgb.mul(Kx.mul(Zx)));break;default:Xt("BasicLightingModel: Unsupported .combine value:",t.combine)}}}const BS=new Dr;class kS extends bS{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(BS),this.setValues(e)}setupNormal(){return Ob(Vb)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new IS(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new US(TT)),t}setupOutgoingLight(){return Mg.rgb}setupLightingModel(){return new OS}}const zS=Km(({f0:e,f90:t,dotVH:n})=>{const i=n.mul(-5.55473).sub(6.98316).mul(n).exp2();return e.mul(i.oneMinus()).add(t.mul(i))}),VS=Km(e=>e.diffuseColor.mul(1/Math.PI)),GS=Km(({dotNH:e})=>Hg.mul(ng(.5)).add(1).mul(ng(1/Math.PI)).mul(e.pow(Hg))),HS=Km(({lightDirection:e})=>{const t=e.add(Ib).normalize(),n=Hb.dot(t).clamp(),i=Ib.dot(t).clamp(),r=zS({f0:zg,f90:1,dotVH:i}),s=ng(.25),a=GS({dotNH:n});return r.mul(s).mul(a)});class jS extends OS{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:n}){const i=Hb.dot(e).clamp().mul(t);n.directDiffuse.addAssign(i.mul(VS({diffuseColor:Mg.rgb}))),!0===this.specular&&n.directSpecular.addAssign(i.mul(HS({lightDirection:e})).mul(Kx))}indirect(e){const{ambientOcclusion:t,irradiance:n,reflectedLight:i}=e.context;i.indirectDiffuse.addAssign(n.mul(VS({diffuseColor:Mg}))),i.indirectDiffuse.mulAssign(t)}}const WS=new Qs;class $S extends bS{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(WS),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new IS(t):null}setupLightingModel(){return new jS(!1)}}const XS=new Ys;class qS extends bS{static get type(){return"MeshPhongNodeMaterial"}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(XS),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new IS(t):null}setupLightingModel(){return new jS}setupVariants(){const e=(this.shininessNode?ng(this.shininessNode):jx).max(1e-4);Hg.assign(e);const t=this.specularNode||Xx;zg.assign(t)}copy(e){return this.shininessNode=e.shininessNode,this.specularNode=e.specularNode,super.copy(e)}}const YS=Km(e=>{if(!1===e.geometry.hasAttribute("normal"))return ng(0);const t=Vb.dFdx().abs().max(Vb.dFdy().abs());return t.x.max(t.y).max(t.z)}),KS=Km(e=>{const{roughness:t}=e,n=YS();let i=t.max(.0525);return i=i.add(n),i=i.min(1),i}),ZS=Km(({alpha:e,dotNL:t,dotNV:n})=>{const i=e.pow2(),r=t.mul(i.add(i.oneMinus().mul(n.pow2())).sqrt()),s=n.mul(i.add(i.oneMinus().mul(t.pow2())).sqrt());return m_(.5,r.add(s).max(B_))}).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),QS=Km(({alphaT:e,alphaB:t,dotTV:n,dotBV:i,dotTL:r,dotBL:s,dotNV:a,dotNL:o})=>{const l=o.mul(cg(e.mul(n),t.mul(i),a).length()),u=a.mul(cg(e.mul(r),t.mul(s),o).length());return m_(.5,l.add(u))}).setLayout({name:"V_GGX_SmithCorrelated_Anisotropic",type:"float",inputs:[{name:"alphaT",type:"float",qualifier:"in"},{name:"alphaB",type:"float",qualifier:"in"},{name:"dotTV",type:"float",qualifier:"in"},{name:"dotBV",type:"float",qualifier:"in"},{name:"dotTL",type:"float",qualifier:"in"},{name:"dotBL",type:"float",qualifier:"in"},{name:"dotNV",type:"float",qualifier:"in"},{name:"dotNL",type:"float",qualifier:"in"}]}),JS=Km(({alpha:e,dotNH:t})=>{const n=e.pow2(),i=t.pow2().mul(n.oneMinus()).oneMinus();return n.div(i.pow2()).mul(1/Math.PI)}).setLayout({name:"D_GGX",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNH",type:"float"}]}),eM=ng(1/Math.PI),tM=Km(({alphaT:e,alphaB:t,dotNH:n,dotTH:i,dotBH:r})=>{const s=e.mul(t),a=cg(t.mul(i),e.mul(r),s.mul(n)),o=a.dot(a),l=s.div(o);return eM.mul(s.mul(l.pow2()))}).setLayout({name:"D_GGX_Anisotropic",type:"float",inputs:[{name:"alphaT",type:"float",qualifier:"in"},{name:"alphaB",type:"float",qualifier:"in"},{name:"dotNH",type:"float",qualifier:"in"},{name:"dotTH",type:"float",qualifier:"in"},{name:"dotBH",type:"float",qualifier:"in"}]}),nM=Km(({lightDirection:e,f0:t,f90:n,roughness:i,f:r,normalView:s=Hb,USE_IRIDESCENCE:a,USE_ANISOTROPY:o})=>{const l=i.pow2(),u=e.add(Ib).normalize(),c=s.dot(e).clamp(),h=s.dot(Ib).clamp(),d=s.dot(u).clamp(),p=Ib.dot(u).clamp();let f,m,g=zS({f0:t,f90:n,dotVH:p});if(km(a)&&(g=Dg.mix(g,r)),km(o)){const t=Bg.dot(e),n=Bg.dot(Ib),i=Bg.dot(u),r=kg.dot(e),s=kg.dot(Ib),a=kg.dot(u);f=QS({alphaT:Fg,alphaB:l,dotTV:n,dotBV:s,dotTL:t,dotBL:r,dotNV:h,dotNL:c}),m=tM({alphaT:Fg,alphaB:l,dotNH:d,dotTH:i,dotBH:a})}else f=ZS({alpha:l,dotNL:c,dotNV:h}),m=JS({alpha:l,dotNH:d});return g.mul(f).mul(m)}),iM=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]);let rM=null;const sM=Km(({roughness:e,dotNV:t})=>{null===rM&&(rM=new Xr(iM,16,16,Ie,xe),rM.name="DFG_LUT",rM.minFilter=he,rM.magFilter=he,rM.wrapS=ae,rM.wrapT=ae,rM.generateMipmaps=!1,rM.needsUpdate=!0);const n=ag(e,t);return zy(rM,n).rg}),aM=Km(({lightDirection:e,f0:t,f90:n,roughness:i,f:r,USE_IRIDESCENCE:s,USE_ANISOTROPY:a})=>{const o=nM({lightDirection:e,f0:t,f90:n,roughness:i,f:r,USE_IRIDESCENCE:s,USE_ANISOTROPY:a}),l=Hb.dot(e).clamp(),u=Hb.dot(Ib).clamp(),c=sM({roughness:i,dotNV:u}),h=sM({roughness:i,dotNV:l}),d=t.mul(c.x).add(n.mul(c.y)),p=t.mul(h.x).add(n.mul(h.y)),f=c.x.add(c.y),m=h.x.add(h.y),g=ng(1).sub(f),_=ng(1).sub(m),v=t.add(t.oneMinus().mul(.047619)),y=d.mul(p).mul(v).div(ng(1).sub(g.mul(_).mul(v).mul(v)).add(B_)),b=g.mul(_),x=y.mul(b);return o.add(x)}),oM=Km(e=>{const{dotNV:t,specularColor:n,specularF90:i,roughness:r}=e,s=sM({dotNV:t,roughness:r});return n.mul(s.x).add(i.mul(s.y))}),lM=Km(({f:e,f90:t,dotVH:n})=>{const i=n.oneMinus().saturate(),r=i.mul(i),s=i.mul(r,r).clamp(0,.9999);return e.sub(cg(t).mul(s)).div(s.oneMinus())}).setLayout({name:"Schlick_to_F0",type:"vec3",inputs:[{name:"f",type:"vec3"},{name:"f90",type:"float"},{name:"dotVH",type:"float"}]}),uM=Km(({roughness:e,dotNH:t})=>{const n=e.pow2(),i=ng(1).div(n),r=t.pow2().oneMinus().max(.0078125);return ng(2).add(i).mul(r.pow(i.mul(.5))).div(2*Math.PI)}).setLayout({name:"D_Charlie",type:"float",inputs:[{name:"roughness",type:"float"},{name:"dotNH",type:"float"}]}),cM=Km(({dotNV:e,dotNL:t})=>ng(1).div(ng(4).mul(t.add(e).sub(t.mul(e))))).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),hM=Km(({lightDirection:e})=>{const t=e.add(Ib).normalize(),n=Hb.dot(e).clamp(),i=Hb.dot(Ib).clamp(),r=Hb.dot(t).clamp(),s=uM({roughness:Lg,dotNH:r}),a=cM({dotNV:i,dotNL:n});return Pg.mul(s).mul(a)}),dM=Km(({N:e,V:t,roughness:n})=>{const i=e.dot(t).saturate(),r=ag(n,i.oneMinus().sqrt());return r.assign(r.mul(.984375).add(.0078125)),r}).setLayout({name:"LTC_Uv",type:"vec2",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"roughness",type:"float"}]}),pM=Km(({f:e})=>{const t=e.length();return xv(t.mul(t).add(e.z).div(t.add(1)),0)}).setLayout({name:"LTC_ClippedSphereFormFactor",type:"float",inputs:[{name:"f",type:"vec3"}]}),fM=Km(({v1:e,v2:t})=>{const n=e.dot(t),i=n.abs().toVar(),r=i.mul(.0145206).add(.4965155).mul(i).add(.8543985).toVar(),s=i.add(4.1616724).mul(i).add(3.417594).toVar(),a=r.div(s),o=n.greaterThan(0).select(a,xv(n.mul(n).oneMinus(),1e-7).inverseSqrt().mul(.5).sub(a));return e.cross(t).mul(o)}).setLayout({name:"LTC_EdgeVectorFormFactor",type:"vec3",inputs:[{name:"v1",type:"vec3"},{name:"v2",type:"vec3"}]}),mM=Km(({N:e,V:t,P:n,mInv:i,p0:r,p1:s,p2:a,p3:o})=>{const l=s.sub(r).toVar(),u=o.sub(r).toVar(),c=l.cross(u),h=cg().toVar();return Jm(c.dot(n.sub(r)).greaterThanEqual(0),()=>{const l=t.sub(e.mul(t.dot(e))).normalize(),u=e.cross(l).negate(),c=i.mul(yg(l,u,e).transpose()).toVar(),d=c.mul(r.sub(n)).normalize().toVar(),p=c.mul(s.sub(n)).normalize().toVar(),f=c.mul(a.sub(n)).normalize().toVar(),m=c.mul(o.sub(n)).normalize().toVar(),g=cg(0).toVar();g.addAssign(fM({v1:d,v2:p})),g.addAssign(fM({v1:p,v2:f})),g.addAssign(fM({v1:f,v2:m})),g.addAssign(fM({v1:m,v2:d})),h.assign(cg(pM({f:g})))}),h}).setLayout({name:"LTC_Evaluate",type:"vec3",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"P",type:"vec3"},{name:"mInv",type:"mat3"},{name:"p0",type:"vec3"},{name:"p1",type:"vec3"},{name:"p2",type:"vec3"},{name:"p3",type:"vec3"}]}),gM=1/6,_M=e=>f_(gM,f_(e,f_(e,e.negate().add(3)).sub(3)).add(1)),vM=e=>f_(gM,f_(e,f_(e,f_(3,e).sub(6))).add(4)),yM=e=>f_(gM,f_(e,f_(e,f_(-3,e).add(3)).add(3)).add(1)),bM=e=>f_(gM,Rv(e,3)),xM=e=>_M(e).add(vM(e)),TM=e=>yM(e).add(bM(e)),SM=e=>d_(-1,vM(e).div(_M(e).add(vM(e)))),MM=e=>d_(1,bM(e).div(yM(e).add(bM(e)))),EM=(e,t,n)=>{const i=e.uvNode,r=f_(i,t.zw).add(.5),s=K_(r),a=J_(r),o=xM(a.x),l=TM(a.x),u=SM(a.x),c=MM(a.x),h=SM(a.y),d=MM(a.y),p=ag(s.x.add(u),s.y.add(h)).sub(.5).mul(t.xy),f=ag(s.x.add(c),s.y.add(h)).sub(.5).mul(t.xy),m=ag(s.x.add(u),s.y.add(d)).sub(.5).mul(t.xy),g=ag(s.x.add(c),s.y.add(d)).sub(.5).mul(t.xy),_=xM(a.y).mul(d_(o.mul(e.sample(p).level(n)),l.mul(e.sample(f).level(n)))),v=TM(a.y).mul(d_(o.mul(e.sample(m).level(n)),l.mul(e.sample(g).level(n))));return _.add(v)},wM=Km(([e,t])=>{const n=ag(e.size(ig(t))),i=ag(e.size(ig(t.add(1)))),r=m_(1,n),s=m_(1,i),a=EM(e,fg(r,n),K_(t)),o=EM(e,fg(s,i),Z_(t));return J_(t).mix(a,o)}),AM=Km(([e,t,n,i,r])=>{const s=cg(Fv(t.negate(),Q_(e),m_(1,i))),a=cg(lv(r[0].xyz),lv(r[1].xyz),lv(r[2].xyz));return Q_(s).mul(n.mul(a))}).setLayout({name:"getVolumeTransmissionRay",type:"vec3",inputs:[{name:"n",type:"vec3"},{name:"v",type:"vec3"},{name:"thickness",type:"float"},{name:"ior",type:"float"},{name:"modelMatrix",type:"mat4"}]}),RM=Km(([e,t])=>e.mul(Iv(t.mul(2).sub(2),0,1))).setLayout({name:"applyIorToRoughness",type:"float",inputs:[{name:"roughness",type:"float"},{name:"ior",type:"float"}]}),CM=tS(),NM=iS(),PM=Km(([e,t,n],{material:i})=>{const r=(1===i.side?CM:NM).sample(e),s=X_(Jy.x).mul(RM(t,n));return wM(r,s)}),LM=Km(([e,t,n])=>(Jm(n.notEqual(0),()=>{const i=$_(t).negate().div(n);return j_(i.negate().mul(e))}),cg(1))).setLayout({name:"volumeAttenuation",type:"vec3",inputs:[{name:"transmissionDistance",type:"float"},{name:"attenuationColor",type:"vec3"},{name:"attenuationDistance",type:"float"}]}),DM=Km(([e,t,n,i,r,s,a,o,l,u,c,h,d,p,f])=>{let m,g;if(f){m=fg().toVar(),g=cg().toVar();const r=c.sub(1).mul(f.mul(.025)),s=cg(c.sub(r),c,c.add(r));GT({start:0,end:3},({i:r})=>{const c=s.element(r),f=AM(e,t,h,c,o),_=a.add(f),v=u.mul(l.mul(fg(_,1))),y=ag(v.xy.div(v.w)).toVar();y.addAssign(1),y.divAssign(2),y.assign(ag(y.x,y.y.oneMinus()));const b=PM(y,n,c);m.element(r).assign(b.element(r)),m.a.addAssign(b.a),g.element(r).assign(i.element(r).mul(LM(lv(f),d,p).element(r)))}),m.a.divAssign(3)}else{const r=AM(e,t,h,c,o),s=a.add(r),f=u.mul(l.mul(fg(s,1))),_=ag(f.xy.div(f.w)).toVar();_.addAssign(1),_.divAssign(2),_.assign(ag(_.x,_.y.oneMinus())),m=PM(_,n,c),g=i.mul(LM(lv(r),d,p))}const _=g.rgb.mul(m.rgb),v=e.dot(t).clamp(),y=cg(oM({dotNV:v,specularColor:r,specularF90:s,roughness:n})),b=g.r.add(g.g,g.b).div(3);return fg(y.oneMinus().mul(_),m.a.oneMinus().mul(b).oneMinus())}),IM=yg(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252),UM=(e,t)=>e.sub(t).div(e.add(t)).pow2(),FM=Km(({outsideIOR:e,eta2:t,cosTheta1:n,thinFilmThickness:i,baseF0:r})=>{const s=Dv(e,t,Ov(0,.03,i)),a=e.div(s).pow2().mul(n.pow2().oneMinus()).oneMinus();Jm(a.lessThan(0),()=>cg(1));const o=a.sqrt(),l=UM(s,e),u=zS({f0:l,f90:1,dotVH:n}),c=u.oneMinus(),h=s.lessThan(e).select(Math.PI,0),d=ng(Math.PI).sub(h),p=(e=>{const t=e.sqrt();return cg(1).add(t).div(cg(1).sub(t))})(r.clamp(0,.9999)),f=UM(p,s.toVec3()),m=zS({f0:f,f90:1,dotVH:o}),g=cg(p.x.lessThan(s).select(Math.PI,0),p.y.lessThan(s).select(Math.PI,0),p.z.lessThan(s).select(Math.PI,0)),_=s.mul(i,o,2),v=cg(d).add(g),y=u.mul(m).clamp(1e-5,.9999),b=y.sqrt(),x=c.pow2().mul(m).div(cg(1).sub(y)),T=u.add(x).toVar(),S=x.sub(c).toVar();return GT({start:1,end:2,condition:"<=",name:"m"},({m:e})=>{S.mulAssign(b);const t=((e,t)=>{const n=e.mul(2*Math.PI*1e-9),i=cg(54856e-17,44201e-17,52481e-17),r=cg(1681e3,1795300,2208400),s=cg(43278e5,93046e5,66121e5),a=ng(9747e-17*Math.sqrt(2*Math.PI*45282e5)).mul(n.mul(2239900).add(t.x).cos()).mul(n.pow2().mul(-45282e5).exp());let o=i.mul(s.mul(2*Math.PI).sqrt()).mul(r.mul(n).add(t).cos()).mul(n.pow2().negate().mul(s).exp());return o=cg(o.x.add(a),o.y,o.z).div(1.0685e-7),IM.mul(o)})(ng(e).mul(_),ng(e).mul(v)).mul(2);T.addAssign(S.mul(t))}),T.max(cg(0))}).setLayout({name:"evalIridescence",type:"vec3",inputs:[{name:"outsideIOR",type:"float"},{name:"eta2",type:"float"},{name:"cosTheta1",type:"float"},{name:"thinFilmThickness",type:"float"},{name:"baseF0",type:"vec3"}]}),OM=Km(({normal:e,viewDir:t,roughness:n})=>{const i=e.dot(t).saturate(),r=n.mul(n),s=n.add(.1).reciprocal(),a=ng(-1.9362).add(n.mul(1.0678)).add(r.mul(.4573)).sub(s.mul(.8469)),o=ng(-.6014).add(n.mul(.5538)).sub(r.mul(.467)).sub(s.mul(.1255));return a.mul(i).add(o).exp().saturate()}),BM=cg(.04),kM=ng(1);class zM extends FS{constructor(e=!1,t=!1,n=!1,i=!1,r=!1,s=!1){super(),this.clearcoat=e,this.sheen=t,this.iridescence=n,this.anisotropy=i,this.transmission=r,this.dispersion=s,this.clearcoatRadiance=null,this.clearcoatSpecularDirect=null,this.clearcoatSpecularIndirect=null,this.sheenSpecularDirect=null,this.sheenSpecularIndirect=null,this.iridescenceFresnel=null,this.iridescenceF0=null,this.iridescenceF0Dielectric=null,this.iridescenceF0Metallic=null}start(e){if(!0===this.clearcoat&&(this.clearcoatRadiance=cg().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=cg().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=cg().toVar("clearcoatSpecularIndirect")),!0===this.sheen&&(this.sheenSpecularDirect=cg().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=cg().toVar("sheenSpecularIndirect")),!0===this.iridescence){const e=Hb.dot(Ib).clamp(),t=FM({outsideIOR:ng(1),eta2:Ig,cosTheta1:e,thinFilmThickness:Ug,baseF0:zg}),n=FM({outsideIOR:ng(1),eta2:Ig,cosTheta1:e,thinFilmThickness:Ug,baseF0:Mg.rgb});this.iridescenceFresnel=Dv(t,n,Rg),this.iridescenceF0Dielectric=lM({f:t,f90:1,dotVH:e}),this.iridescenceF0Metallic=lM({f:n,f90:1,dotVH:e}),this.iridescenceF0=Dv(this.iridescenceF0Dielectric,this.iridescenceF0Metallic,Rg)}if(!0===this.transmission){const t=Pb,n=_b.sub(Pb).normalize(),i=jb,r=e.context;r.backdrop=DM(i,n,Ag,Eg,Vg,Gg,t,xb,gb,fb,Xg,Yg,Zg,Kg,this.dispersion?Qg:null),r.backdropAlpha=qg,Mg.a.mulAssign(Dv(1,r.backdrop.a,qg))}super.start(e)}computeMultiscattering(e,t,n,i,r=null){const s=Hb.dot(Ib).clamp(),a=sM({roughness:Ag,dotNV:s}),o=r?Dg.mix(i,r):i,l=o.mul(a.x).add(n.mul(a.y)),u=a.x.add(a.y).oneMinus(),c=o.add(o.oneMinus().mul(.047619)),h=l.mul(c).div(u.mul(c).oneMinus());e.addAssign(l),t.addAssign(h.mul(u))}direct({lightDirection:e,lightColor:t,reflectedLight:n}){const i=Hb.dot(e).clamp().mul(t).toVar();if(!0===this.sheen){this.sheenSpecularDirect.addAssign(i.mul(hM({lightDirection:e})));const t=OM({normal:Hb,viewDir:Ib,roughness:Lg}),n=OM({normal:Hb,viewDir:e,roughness:Lg}),r=Pg.r.max(Pg.g).max(Pg.b).mul(t.max(n)).oneMinus();i.mulAssign(r)}if(!0===this.clearcoat){const n=Wb.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(n.mul(nM({lightDirection:e,f0:BM,f90:kM,roughness:Ng,normalView:Wb})))}n.directDiffuse.addAssign(i.mul(VS({diffuseColor:Eg}))),n.directSpecular.addAssign(i.mul(aM({lightDirection:e,f0:Vg,f90:1,roughness:Ag,f:this.iridescenceFresnel,USE_IRIDESCENCE:this.iridescence,USE_ANISOTROPY:this.anisotropy})))}directRectArea({lightColor:e,lightPosition:t,halfWidth:n,halfHeight:i,reflectedLight:r,ltc_1:s,ltc_2:a}){const o=t.add(n).sub(i),l=t.sub(n).sub(i),u=t.sub(n).add(i),c=t.add(n).add(i),h=Hb,d=Ib,p=Db.toVar(),f=dM({N:h,V:d,roughness:Ag}),m=s.sample(f).toVar(),g=a.sample(f).toVar(),_=yg(cg(m.x,0,m.y),cg(0,1,0),cg(m.z,0,m.w)).toVar(),v=Vg.mul(g.x).add(Gg.sub(Vg).mul(g.y)).toVar();if(r.directSpecular.addAssign(e.mul(v).mul(mM({N:h,V:d,P:p,mInv:_,p0:o,p1:l,p2:u,p3:c}))),r.directDiffuse.addAssign(e.mul(Eg).mul(mM({N:h,V:d,P:p,mInv:yg(1,0,0,0,1,0,0,0,1),p0:o,p1:l,p2:u,p3:c}))),!0===this.clearcoat){const t=Wb,n=dM({N:t,V:d,roughness:Ng}),i=s.sample(n),r=a.sample(n),h=yg(cg(i.x,0,i.y),cg(0,1,0),cg(i.z,0,i.w)),f=BM.mul(r.x).add(kM.sub(BM).mul(r.y));this.clearcoatSpecularDirect.addAssign(e.mul(f).mul(mM({N:t,V:d,P:p,mInv:h,p0:o,p1:l,p2:u,p3:c})))}}indirect(e){this.indirectDiffuse(e),this.indirectSpecular(e),this.ambientOcclusion(e)}indirectDiffuse(e){const{irradiance:t,reflectedLight:n}=e.context,i=t.mul(VS({diffuseColor:Eg})).toVar();if(!0===this.sheen){const e=OM({normal:Hb,viewDir:Ib,roughness:Lg}),t=Pg.r.max(Pg.g).max(Pg.b).mul(e).oneMinus();i.mulAssign(t)}n.indirectDiffuse.addAssign(i)}indirectSpecular(e){const{radiance:t,iblIrradiance:n,reflectedLight:i}=e.context;if(!0===this.sheen&&this.sheenSpecularIndirect.addAssign(n.mul(Pg,OM({normal:Hb,viewDir:Ib,roughness:Lg}))),!0===this.clearcoat){const e=Wb.dot(Ib).clamp(),t=oM({dotNV:e,specularColor:BM,specularF90:kM,roughness:Ng});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(t))}const r=cg().toVar("singleScatteringDielectric"),s=cg().toVar("multiScatteringDielectric"),a=cg().toVar("singleScatteringMetallic"),o=cg().toVar("multiScatteringMetallic");this.computeMultiscattering(r,s,Gg,zg,this.iridescenceF0Dielectric),this.computeMultiscattering(a,o,Gg,Mg.rgb,this.iridescenceF0Metallic);const l=Dv(r,a,Rg),u=Dv(s,o,Rg),c=r.add(s),h=Eg.mul(c.oneMinus()),d=n.mul(1/Math.PI),p=t.mul(l).add(u.mul(d)).toVar(),f=h.mul(d).toVar();if(!0===this.sheen){const e=OM({normal:Hb,viewDir:Ib,roughness:Lg}),t=Pg.r.max(Pg.g).max(Pg.b).mul(e).oneMinus();p.mulAssign(t),f.mulAssign(t)}i.indirectSpecular.addAssign(p),i.indirectDiffuse.addAssign(f)}ambientOcclusion(e){const{ambientOcclusion:t,reflectedLight:n}=e.context,i=Hb.dot(Ib).clamp().add(t),r=Ag.mul(-16).oneMinus().negate().exp2(),s=t.sub(i.pow(r).oneMinus()).clamp();!0===this.clearcoat&&this.clearcoatSpecularIndirect.mulAssign(t),!0===this.sheen&&this.sheenSpecularIndirect.mulAssign(t),n.indirectDiffuse.mulAssign(t),n.indirectSpecular.mulAssign(s)}finish({context:e}){const{outgoingLight:t}=e;if(!0===this.clearcoat){const e=Wb.dot(Ib).clamp(),n=zS({dotVH:e,f0:BM,f90:kM}),i=t.mul(Cg.mul(n).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(Cg));t.assign(i)}if(!0===this.sheen){const e=t.add(this.sheenSpecularDirect,this.sheenSpecularIndirect.mul(1/Math.PI));t.assign(e)}}}const VM=ng(1),GM=ng(-2),HM=ng(.8),jM=ng(-1),WM=ng(.4),$M=ng(2),XM=ng(.305),qM=ng(3),YM=ng(.21),KM=ng(4),ZM=ng(4),QM=ng(16),JM=Km(([e])=>{const t=cg(av(e)).toVar(),n=ng(-1).toVar();return Jm(t.x.greaterThan(t.z),()=>{Jm(t.x.greaterThan(t.y),()=>{n.assign(Vv(e.x.greaterThan(0),0,3))}).Else(()=>{n.assign(Vv(e.y.greaterThan(0),1,4))})}).Else(()=>{Jm(t.z.greaterThan(t.y),()=>{n.assign(Vv(e.z.greaterThan(0),2,5))}).Else(()=>{n.assign(Vv(e.y.greaterThan(0),1,4))})}),n}).setLayout({name:"getFace",type:"float",inputs:[{name:"direction",type:"vec3"}]}),eE=Km(([e,t])=>{const n=ag().toVar();return Jm(t.equal(0),()=>{n.assign(ag(e.z,e.y).div(av(e.x)))}).ElseIf(t.equal(1),()=>{n.assign(ag(e.x.negate(),e.z.negate()).div(av(e.y)))}).ElseIf(t.equal(2),()=>{n.assign(ag(e.x.negate(),e.y).div(av(e.z)))}).ElseIf(t.equal(3),()=>{n.assign(ag(e.z.negate(),e.y).div(av(e.x)))}).ElseIf(t.equal(4),()=>{n.assign(ag(e.x.negate(),e.z).div(av(e.y)))}).Else(()=>{n.assign(ag(e.x,e.y).div(av(e.z)))}),f_(.5,n.add(1))}).setLayout({name:"getUV",type:"vec2",inputs:[{name:"direction",type:"vec3"},{name:"face",type:"float"}]}),tE=Km(([e])=>{const t=ng(0).toVar();return Jm(e.greaterThanEqual(HM),()=>{t.assign(VM.sub(e).mul(jM.sub(GM)).div(VM.sub(HM)).add(GM))}).ElseIf(e.greaterThanEqual(WM),()=>{t.assign(HM.sub(e).mul($M.sub(jM)).div(HM.sub(WM)).add(jM))}).ElseIf(e.greaterThanEqual(XM),()=>{t.assign(WM.sub(e).mul(qM.sub($M)).div(WM.sub(XM)).add($M))}).ElseIf(e.greaterThanEqual(YM),()=>{t.assign(XM.sub(e).mul(KM.sub(qM)).div(XM.sub(YM)).add(qM))}).Else(()=>{t.assign(ng(-2).mul(X_(f_(1.16,e))))}),t}).setLayout({name:"roughnessToMip",type:"float",inputs:[{name:"roughness",type:"float"}]}),nE=Km(([e,t])=>{const n=e.toVar();n.assign(f_(2,n).sub(1));const i=cg(n,1).toVar();return Jm(t.equal(0),()=>{i.assign(i.zyx)}).ElseIf(t.equal(1),()=>{i.assign(i.xzy),i.xz.mulAssign(-1)}).ElseIf(t.equal(2),()=>{i.x.mulAssign(-1)}).ElseIf(t.equal(3),()=>{i.assign(i.zyx),i.xz.mulAssign(-1)}).ElseIf(t.equal(4),()=>{i.assign(i.xzy),i.xy.mulAssign(-1)}).ElseIf(t.equal(5),()=>{i.z.mulAssign(-1)}),i}).setLayout({name:"getDirection",type:"vec3",inputs:[{name:"uv",type:"vec2"},{name:"face",type:"float"}]}),iE=Km(([e,t,n,i,r,s])=>{const a=ng(n),o=cg(t),l=Iv(tE(a),GM,s),u=J_(l),c=K_(l),h=cg(rE(e,o,c,i,r,s)).toVar();return Jm(u.notEqual(0),()=>{const t=cg(rE(e,o,c.add(1),i,r,s)).toVar();h.assign(Dv(h,t,u))}),h}),rE=Km(([e,t,n,i,r,s])=>{const a=ng(n).toVar(),o=cg(t),l=ng(JM(o)).toVar(),u=ng(xv(ZM.sub(a),0)).toVar();a.assign(xv(a,ZM));const c=ng(W_(a)).toVar(),h=ag(eE(o,l).mul(c.sub(2)).add(1)).toVar();return Jm(l.greaterThan(2),()=>{h.y.addAssign(c),l.subAssign(3)}),h.x.addAssign(l.mul(c)),h.x.addAssign(u.mul(f_(3,QM))),h.y.addAssign(f_(4,W_(s).sub(c))),h.x.mulAssign(i),h.y.mulAssign(r),e.sample(h).grad(ag(),ag())}),sE=Km(({envMap:e,mipInt:t,outputDirection:n,theta:i,axis:r,CUBEUV_TEXEL_WIDTH:s,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:o})=>{const l=tv(i),u=n.mul(l).add(r.cross(n).mul(ev(i))).add(r.mul(r.dot(n).mul(l.oneMinus())));return rE(e,u,t,s,a,o)}),aE=Km(({n:e,latitudinal:t,poleAxis:n,outputDirection:i,weights:r,samples:s,dTheta:a,mipInt:o,envMap:l,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:c,CUBEUV_MAX_MIP:h})=>{const d=cg(Vv(t,n,Av(n,i))).toVar();Jm(d.equal(cg(0)),()=>{d.assign(cg(i.z,0,i.x.negate()))}),d.assign(Q_(d));const p=cg().toVar();return p.addAssign(r.element(0).mul(sE({theta:0,axis:d,outputDirection:i,mipInt:o,envMap:l,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:c,CUBEUV_MAX_MIP:h}))),GT({start:ig(1),end:e},({i:e})=>{Jm(e.greaterThanEqual(s),()=>{My("break").toStack()});const t=ng(a.mul(ng(e))).toVar();p.addAssign(r.element(e).mul(sE({theta:t.mul(-1),axis:d,outputDirection:i,mipInt:o,envMap:l,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:c,CUBEUV_MAX_MIP:h}))),p.addAssign(r.element(e).mul(sE({theta:t,axis:d,outputDirection:i,mipInt:o,envMap:l,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:c,CUBEUV_MAX_MIP:h})))}),fg(p,1)}),oE=Km(([e])=>{const t=rg(e).toVar();return t.assign(t.shiftLeft(rg(16)).bitOr(t.shiftRight(rg(16)))),t.assign(t.bitAnd(rg(1431655765)).shiftLeft(rg(1)).bitOr(t.bitAnd(rg(2863311530)).shiftRight(rg(1)))),t.assign(t.bitAnd(rg(858993459)).shiftLeft(rg(2)).bitOr(t.bitAnd(rg(3435973836)).shiftRight(rg(2)))),t.assign(t.bitAnd(rg(252645135)).shiftLeft(rg(4)).bitOr(t.bitAnd(rg(4042322160)).shiftRight(rg(4)))),t.assign(t.bitAnd(rg(16711935)).shiftLeft(rg(8)).bitOr(t.bitAnd(rg(4278255360)).shiftRight(rg(8)))),ng(t).mul(2.3283064365386963e-10)}),lE=Km(([e,t])=>ag(ng(e).div(ng(t)),oE(e))),uE=Km(([e,t,n])=>{const i=n.mul(n).toConst(),r=cg(1,0,0).toConst(),s=Av(t,r).toConst(),a=q_(e.x).toConst(),o=f_(2,3.14159265359).mul(e.y).toConst(),l=a.mul(tv(o)).toConst(),u=a.mul(ev(o)).toVar(),c=f_(.5,t.z.add(1)).toConst();u.assign(c.oneMinus().mul(q_(l.mul(l).oneMinus())).add(c.mul(u)));const h=r.mul(l).add(s.mul(u)).add(t.mul(q_(xv(0,l.mul(l).add(u.mul(u)).oneMinus()))));return Q_(cg(i.mul(h.x),i.mul(h.y),xv(0,h.z)))}),cE=Km(({roughness:e,mipInt:t,envMap:n,N_immutable:i,GGX_SAMPLES:r,CUBEUV_TEXEL_WIDTH:s,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:o})=>{const l=cg(i).toVar(),u=cg(0).toVar(),c=ng(0).toVar();return Jm(e.lessThan(.001),()=>{u.assign(rE(n,l,t,s,a,o))}).Else(()=>{const i=Vv(av(l.z).lessThan(.999),cg(0,0,1),cg(1,0,0)),h=Q_(Av(i,l)).toVar(),d=Av(l,h).toVar();GT({start:rg(0),end:r},({i:i})=>{const p=lE(i,r),f=uE(p,cg(0,0,1),e),m=Q_(h.mul(f.x).add(d.mul(f.y)).add(l.mul(f.z))),g=Q_(m.mul(wv(l,m).mul(2)).sub(l)),_=xv(wv(l,g),0);Jm(_.greaterThan(0),()=>{const e=rE(n,g,t,s,a,o);u.addAssign(e.mul(_)),c.addAssign(_)})}),Jm(c.greaterThan(0),()=>{u.assign(u.div(c))})}),fg(u,1)}),hE=[.125,.215,.35,.446,.526,.582],dE=20,pE=new Ra(-1,1,1,-1,0,1),fE=new Sa(90,1),mE=new _i;let gE=null,_E=0,vE=0;const yE=new dn,bE=new WeakMap,xE=[3,1,5,0,4,2],TE=nE(Py(),Ny("faceIndex")).normalize(),SE=cg(TE.x,TE.y,TE.z);class ME{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._blurMaterial=null,this._ggxMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._backgroundBox=null}get _hasInitialized(){return this._renderer.hasInitialized()}fromScene(e,t=0,n=.1,i=100,r={}){const{size:s=256,position:a=yE,renderTarget:o=null}=r;if(this._setSize(s),!1===this._hasInitialized){Xt('PMREMGenerator: ".fromScene()" called before the backend is initialized. Try using "await renderer.init()" instead.');const s=o||this._allocateTarget();return r.renderTarget=s,this.fromSceneAsync(e,t,n,i,r),s}gE=this._renderer.getRenderTarget(),_E=this._renderer.getActiveCubeFace(),vE=this._renderer.getActiveMipmapLevel();const l=o||this._allocateTarget();return l.depthBuffer=!0,this._init(l),this._sceneToCubeUV(e,n,i,l,a),t>0&&this._blur(l,0,0,t),this._applyPMREM(l),this._cleanup(l),l}async fromSceneAsync(e,t=0,n=.1,i=100,r={}){return Yt('PMREMGenerator: ".fromSceneAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this.fromScene(e,t,n,i,r)}fromEquirectangular(e,t=null){if(!1===this._hasInitialized){Xt('PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using "await renderer.init()" instead.'),this._setSizeFromTexture(e);const n=t||this._allocateTarget();return this.fromEquirectangularAsync(e,n),n}return this._fromTexture(e,t)}async fromEquirectangularAsync(e,t=null){return Yt('PMREMGenerator: ".fromEquirectangularAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this._fromTexture(e,t)}fromCubemap(e,t=null){if(!1===this._hasInitialized){Xt("PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead."),this._setSizeFromTexture(e);const n=t||this._allocateTarget();return this.fromCubemapAsync(e,t),n}return this._fromTexture(e,t)}async fromCubemapAsync(e,t=null){return Yt('PMREMGenerator: ".fromCubemapAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this._fromTexture(e,t)}async compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=RE(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=CE(),await this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),null!==this._cubemapMaterial&&this._cubemapMaterial.dispose(),null!==this._equirectMaterial&&this._equirectMaterial.dispose(),null!==this._backgroundBox&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSizeFromTexture(e){e.mapping===ee||e.mapping===te?this._setSize(0===e.image.length?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4)}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){null!==this._blurMaterial&&this._blurMaterial.dispose(),null!==this._ggxMaterial&&this._ggxMaterial.dispose(),null!==this._pingPongRenderTarget&&this._pingPongRenderTarget.dispose();for(let e=0;ee-4?o=hE[a-e+4-1]:0===a&&(o=0),n.push(o);const l=1/(s-2),u=-l,c=1+l,h=[u,u,c,u,c,c,u,u,c,c,u,c],d=6,p=6,f=3,m=2,g=1,_=new Float32Array(f*p*d),v=new Float32Array(m*p*d),y=new Float32Array(g*p*d);for(let e=0;e2?0:-1,i=[t,n,0,t+2/3,n,0,t+2/3,n+1,0,t,n,0,t+2/3,n+1,0,t,n+1,0],r=xE[e];_.set(i,f*p*r),v.set(h,m*p*r);const s=[r,r,r,r,r,r];y.set(s,g*p*r)}const b=new vr;b.setAttribute("position",new nr(_,f)),b.setAttribute("uv",new nr(v,m)),b.setAttribute("faceIndex",new nr(y,g)),i.push(new Wr(b,null)),r>4&&r--}return{lodMeshes:i,sizeLods:t,sigmas:n}}(t)),this._blurMaterial=function(e,t,n){const i=$y(new Array(dE).fill(0)),r=a_(new dn(0,1,0)),s=a_(0),a=ng(dE),o=a_(0),l=a_(1),u=zy(),c=a_(0),h=ng(1/t),d=ng(1/n),p=ng(e),f={n:a,latitudinal:o,weights:i,poleAxis:r,outputDirection:SE,dTheta:s,samples:l,envMap:u,mipInt:c,CUBEUV_TEXEL_WIDTH:h,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:p},m=AE("blur");return m.fragmentNode=aE({...f,latitudinal:o.equal(1)}),bE.set(m,f),m}(t,e.width,e.height),this._ggxMaterial=function(e,t,n){const i=zy(),r=a_(0),s=a_(0),a=ng(1/t),o=ng(1/n),l=ng(e),u={envMap:i,roughness:r,mipInt:s,CUBEUV_TEXEL_WIDTH:a,CUBEUV_TEXEL_HEIGHT:o,CUBEUV_MAX_MIP:l},c=AE("ggx");return c.fragmentNode=cE({...u,N_immutable:SE,GGX_SAMPLES:rg(512)}),bE.set(c,u),c}(t,e.width,e.height)}}async _compileMaterial(e){const t=new Wr(new vr,e);await this._renderer.compile(t,pE)}_sceneToCubeUV(e,t,n,i,r){const s=fE;s.near=t,s.far=n;const a=[1,1,1,1,-1,1],o=[1,-1,1,-1,1,-1],l=this._renderer,u=l.autoClear;l.getClearColor(mE),l.autoClear=!1,null===this._backgroundBox&&(this._backgroundBox=new Wr(new xs,new Dr({name:"PMREM.Background",side:1,depthWrite:!1,depthTest:!1})));const c=this._backgroundBox,h=c.material;let d=!1;const p=e.background;p?p.isColor&&(h.color.copy(p),e.background=null,d=!0):(h.color.copy(mE),d=!0),l.setRenderTarget(i),l.clear(),d&&l.render(c,s);for(let t=0;t<6;t++){const n=t%3;0===n?(s.up.set(0,a[t],0),s.position.set(r.x,r.y,r.z),s.lookAt(r.x+o[t],r.y,r.z)):1===n?(s.up.set(0,0,a[t]),s.position.set(r.x,r.y,r.z),s.lookAt(r.x,r.y+o[t],r.z)):(s.up.set(0,a[t],0),s.position.set(r.x,r.y,r.z),s.lookAt(r.x,r.y,r.z+o[t]));const u=this._cubeSize;wE(i,n*u,t>2?u:0,u,u),l.render(e,s)}l.autoClear=u,e.background=p}_textureToCubeUV(e,t){const n=this._renderer,i=e.mapping===ee||e.mapping===te;i?null===this._cubemapMaterial&&(this._cubemapMaterial=RE(e)):null===this._equirectMaterial&&(this._equirectMaterial=CE(e));const r=i?this._cubemapMaterial:this._equirectMaterial;r.fragmentNode.value=e;const s=this._lodMeshes[0];s.material=r;const a=this._cubeSize;wE(t,0,0,3*a,2*a),n.setRenderTarget(t),n.render(s,pE)}_applyPMREM(e){const t=this._renderer,n=t.autoClear;t.autoClear=!1;const i=this._lodMeshes.length;for(let t=1;th-4?n-h+4:0),f=4*(this._cubeSize-d);e.texture.frame=(e.texture.frame||0)+1,o.envMap.value=e.texture,o.roughness.value=c,o.mipInt.value=h-t,wE(r,p,f,3*d,2*d),i.setRenderTarget(r),i.render(a,pE),r.texture.frame=(r.texture.frame||0)+1,o.envMap.value=r.texture,o.roughness.value=0,o.mipInt.value=h-n,wE(e,p,f,3*d,2*d),i.setRenderTarget(e),i.render(a,pE)}_blur(e,t,n,i,r){const s=this._pingPongRenderTarget;this._halfBlur(e,s,t,n,i,"latitudinal",r),this._halfBlur(s,e,n,n,i,"longitudinal",r)}_halfBlur(e,t,n,i,r,s,a){const o=this._renderer,l=this._blurMaterial;"latitudinal"!==s&&"longitudinal"!==s&&qt("blur direction must be either latitudinal or longitudinal!");const u=this._lodMeshes[i];u.material=l;const c=bE.get(l),h=this._sizeLods[n]-1,d=isFinite(r)?Math.PI/(2*h):2*Math.PI/39,p=r/d,f=isFinite(r)?1+Math.floor(3*p):dE;f>dE&&Xt(`sigmaRadians, ${r}, is too large and will clip, as it requested ${f} samples when the maximum is set to 20`);const m=[];let g=0;for(let e=0;e_-4?i-_+4:0),4*(this._cubeSize-v),3*v,2*v),o.setRenderTarget(t),o.render(u,pE)}}function EE(e,t){const n=new Ln(e,t,{magFilter:he,minFilter:he,generateMipmaps:!1,type:xe,format:Ce,colorSpace:xt});return n.texture.mapping=re,n.texture.name="PMREM.cubeUv",n.texture.isPMREMTexture=!0,n.scissorTest=!0,n}function wE(e,t,n,i,r){e.viewport.set(t,n,i,r),e.scissor.set(t,n,i,r)}function AE(e){const t=new bS;return t.depthTest=!1,t.depthWrite=!1,t.blending=0,t.name=`PMREM_${e}`,t}function RE(e){const t=AE("cubemap");return t.fragmentNode=ax(e,SE),t}function CE(e){const t=AE("equirect");return t.fragmentNode=zy(e,AS(SE),0),t}const NE=new WeakMap;function PE(e,t,n){const i=function(e){let t=NE.get(e);void 0===t&&(t=new WeakMap,NE.set(e,t));return t}(t);let r=i.get(e);if((void 0!==r?r.pmremVersion:-1)!==e.pmremVersion){const t=e.image;if(e.isCubeTexture){if(!function(e){if(null==e)return!1;let t=0;const n=6;for(let i=0;i0}(t))return null;r=n.fromEquirectangular(e,r)}r.pmremVersion=e.pmremVersion,i.set(e,r)}return r.texture}class LE extends tm{static get type(){return"PMREMNode"}constructor(e,t=null,n=null){super("vec3"),this._value=e,this._pmrem=null,this.uvNode=t,this.levelNode=n,this._generator=null;const i=new Nn;i.isRenderTargetTexture=!0,this._texture=zy(i),this._width=a_(0),this._height=a_(0),this._maxMip=a_(0),this.updateBeforeType=Gf}set value(e){this._value=e,this._pmrem=null}get value(){return this._value}updateFromTexture(e){const t=function(e){const t=Math.log2(e)-2,n=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,t),112)),texelHeight:n,maxMip:t}}(e.image.height);this._texture.value=e,this._width.value=t.texelWidth,this._height.value=t.texelHeight,this._maxMip.value=t.maxMip}updateBefore(e){let t=this._pmrem;const n=t?t.pmremVersion:-1,i=this._value;n!==i.pmremVersion&&(t=!0===i.isPMREMTexture?i:PE(i,e.renderer,this._generator),null!==t&&(this._pmrem=t,this.updateFromTexture(t)))}setup(e){null===this._generator&&(this._generator=new ME(e.renderer)),this.updateBefore(e);let t=this.uvNode;null===t&&e.context.getUV&&(t=e.context.getUV(this,e)),t=Qb.mul(cg(t.x,t.y.negate(),t.z));let n=this.levelNode;return null===n&&e.context.getTextureLevel&&(n=e.context.getTextureLevel(this)),iE(this._texture,t,n,this._width,this._height,this._maxMip)}dispose(){super.dispose(),null!==this._generator&&this._generator.dispose()}}const DE=Wm(LE).setParameterLength(1,3),IE=new WeakMap;class UE extends qT{static get type(){return"EnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){const{material:t}=e;let n=this.envNode;if(n.isTextureNode||n.isMaterialReferenceNode){const i=n.isTextureNode?n.value:t[n.property],r=this._getPMREMNodeCache(e.renderer);let s=r.get(i);void 0===s&&(s=DE(i),r.set(i,s)),n=s}const i=!0===t.useAnisotropy||t.anisotropy>0?Lx:Hb,r=n.context(FE(Ag,i)).mul(Zb),s=n.context(OE(jb)).mul(Math.PI).mul(Zb),a=vy(r),o=vy(s);e.context.radiance.addAssign(a),e.context.iblIrradiance.addAssign(o);const l=e.context.lightingModel.clearcoatRadiance;if(l){const e=n.context(FE(Ng,Wb)).mul(Zb),t=vy(e);l.addAssign(t)}}_getPMREMNodeCache(e){let t=IE.get(e);return void 0===t&&(t=new WeakMap,IE.set(e,t)),t}}const FE=(e,t)=>{let n=null;return{getUV:()=>(null===n&&(n=Ib.negate().reflect(t),n=Nv(e).mix(n,t).normalize(),n=n.transformDirection(gb)),n),getTextureLevel:()=>e}},OE=e=>({getUV:()=>e,getTextureLevel:()=>ng(1)}),BE=new Xs;class kE extends bS{static get type(){return"MeshStandardNodeMaterial"}constructor(e){super(),this.isMeshStandardNodeMaterial=!0,this.lights=!0,this.emissiveNode=null,this.metalnessNode=null,this.roughnessNode=null,this.setDefaultValues(BE),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return null===t&&e.environmentNode&&(t=e.environmentNode),t?new UE(t):null}setupLightingModel(){return new zM}setupSpecular(){const e=Dv(cg(.04),Mg.rgb,Rg);zg.assign(cg(.04)),Vg.assign(e),Gg.assign(1)}setupVariants(){const e=this.metalnessNode?ng(this.metalnessNode):Jx;Rg.assign(e);let t=this.roughnessNode?ng(this.roughnessNode):Qx;t=KS({roughness:t}),Ag.assign(t),this.setupSpecular(),Eg.assign(Mg.rgb.mul(e.oneMinus()))}copy(e){return this.emissiveNode=e.emissiveNode,this.metalnessNode=e.metalnessNode,this.roughnessNode=e.roughnessNode,super.copy(e)}}const zE=new qs;class VE extends kE{static get type(){return"MeshPhysicalNodeMaterial"}constructor(e){super(),this.isMeshPhysicalNodeMaterial=!0,this.clearcoatNode=null,this.clearcoatRoughnessNode=null,this.clearcoatNormalNode=null,this.sheenNode=null,this.sheenRoughnessNode=null,this.iridescenceNode=null,this.iridescenceIORNode=null,this.iridescenceThicknessNode=null,this.specularIntensityNode=null,this.specularColorNode=null,this.iorNode=null,this.transmissionNode=null,this.thicknessNode=null,this.attenuationDistanceNode=null,this.attenuationColorNode=null,this.dispersionNode=null,this.anisotropyNode=null,this.setDefaultValues(zE),this.setValues(e)}get useClearcoat(){return this.clearcoat>0||null!==this.clearcoatNode}get useIridescence(){return this.iridescence>0||null!==this.iridescenceNode}get useSheen(){return this.sheen>0||null!==this.sheenNode}get useAnisotropy(){return this.anisotropy>0||null!==this.anisotropyNode}get useTransmission(){return this.transmission>0||null!==this.transmissionNode}get useDispersion(){return this.dispersion>0||null!==this.dispersionNode}setupSpecular(){const e=this.iorNode?ng(this.iorNode):pT;Xg.assign(e),zg.assign(bv(Cv(Xg.sub(1).div(Xg.add(1))).mul(Yx),cg(1)).mul(qx)),Vg.assign(Dv(zg,Mg.rgb,Rg)),Gg.assign(Dv(qx,1,Rg))}setupLightingModel(){return new zM(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const e=this.clearcoatNode?ng(this.clearcoatNode):tT,t=this.clearcoatRoughnessNode?ng(this.clearcoatRoughnessNode):nT;Cg.assign(e),Ng.assign(KS({roughness:t}))}if(this.useSheen){const e=this.sheenNode?cg(this.sheenNode):sT,t=this.sheenRoughnessNode?ng(this.sheenRoughnessNode):aT;Pg.assign(e),Lg.assign(t)}if(this.useIridescence){const e=this.iridescenceNode?ng(this.iridescenceNode):lT,t=this.iridescenceIORNode?ng(this.iridescenceIORNode):uT,n=this.iridescenceThicknessNode?ng(this.iridescenceThicknessNode):cT;Dg.assign(e),Ig.assign(t),Ug.assign(n)}if(this.useAnisotropy){const e=(this.anisotropyNode?ag(this.anisotropyNode):oT).toVar();Og.assign(e.length()),Jm(Og.equal(0),()=>{e.assign(ag(1,0))}).Else(()=>{e.divAssign(ag(Og)),Og.assign(Og.saturate())}),Fg.assign(Og.pow2().mix(Ag.pow2(),1)),Bg.assign(Px[0].mul(e.x).add(Px[1].mul(e.y))),kg.assign(Px[1].mul(e.x).sub(Px[0].mul(e.y)))}if(this.useTransmission){const e=this.transmissionNode?ng(this.transmissionNode):hT,t=this.thicknessNode?ng(this.thicknessNode):dT,n=this.attenuationDistanceNode?ng(this.attenuationDistanceNode):fT,i=this.attenuationColorNode?cg(this.attenuationColorNode):mT;if(qg.assign(e),Yg.assign(t),Kg.assign(n),Zg.assign(i),this.useDispersion){const e=this.dispersionNode?ng(this.dispersionNode):xT;Qg.assign(e)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?cg(this.clearcoatNormalNode):iT}setup(e){e.context.setupClearcoatNormal=()=>qv(this.setupClearcoatNormal(e),"NORMAL","vec3"),super.setup(e)}copy(e){return this.clearcoatNode=e.clearcoatNode,this.clearcoatRoughnessNode=e.clearcoatRoughnessNode,this.clearcoatNormalNode=e.clearcoatNormalNode,this.sheenNode=e.sheenNode,this.sheenRoughnessNode=e.sheenRoughnessNode,this.iridescenceNode=e.iridescenceNode,this.iridescenceIORNode=e.iridescenceIORNode,this.iridescenceThicknessNode=e.iridescenceThicknessNode,this.specularIntensityNode=e.specularIntensityNode,this.specularColorNode=e.specularColorNode,this.iorNode=e.iorNode,this.transmissionNode=e.transmissionNode,this.thicknessNode=e.thicknessNode,this.attenuationDistanceNode=e.attenuationDistanceNode,this.attenuationColorNode=e.attenuationColorNode,this.dispersionNode=e.dispersionNode,this.anisotropyNode=e.anisotropyNode,super.copy(e)}}const GE=Km(({normal:e,lightDirection:t,builder:n})=>{const i=e.dot(t),r=ag(i.mul(.5).add(.5),0);if(n.material.gradientMap){const e=dx("gradientMap","texture").context({getUV:()=>r});return cg(e.r)}{const e=r.fwidth().mul(.5);return Dv(cg(.7),cg(1),Ov(ng(.7).sub(e.x),ng(.7).add(e.x),r.x))}});class HE extends FS{direct({lightDirection:e,lightColor:t,reflectedLight:n},i){const r=GE({normal:Bb,lightDirection:e,builder:i}).mul(t);n.directDiffuse.addAssign(r.mul(VS({diffuseColor:Mg.rgb})))}indirect(e){const{ambientOcclusion:t,irradiance:n,reflectedLight:i}=e.context;i.indirectDiffuse.addAssign(n.mul(VS({diffuseColor:Mg}))),i.indirectDiffuse.mulAssign(t)}}const jE=new Ks;class WE extends bS{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues(jE),this.setValues(e)}setupLightingModel(){return new HE}}const $E=Km(()=>{const e=cg(Ib.z,0,Ib.x.negate()).normalize(),t=Ib.cross(e);return ag(e.dot(Hb),t.dot(Hb)).mul(.495).add(.5)}).once(["NORMAL","VERTEX"])().toVar("matcapUV"),XE=new ta;class qE extends bS{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(XE),this.setValues(e)}setupVariants(e){const t=$E;let n;n=e.material.matcap?dx("matcap","texture").context({getUV:()=>t}):cg(Dv(.2,.8,t.y)),Mg.rgb.mulAssign(n.rgb)}}class YE extends tm{static get type(){return"RotateNode"}constructor(e,t){super(),this.positionNode=e,this.rotationNode=t}getNodeType(e){return this.positionNode.getNodeType(e)}setup(e){const{rotationNode:t,positionNode:n}=this;if("vec2"===this.getNodeType(e)){const e=t.cos(),i=t.sin();return vg(e,i,i.negate(),e).mul(n)}{const e=t,i=bg(fg(1,0,0,0),fg(0,tv(e.x),ev(e.x).negate(),0),fg(0,ev(e.x),tv(e.x),0),fg(0,0,0,1)),r=bg(fg(tv(e.y),0,ev(e.y),0),fg(0,1,0,0),fg(ev(e.y).negate(),0,tv(e.y),0),fg(0,0,0,1)),s=bg(fg(tv(e.z),ev(e.z).negate(),0,0),fg(ev(e.z),tv(e.z),0,0),fg(0,0,1,0),fg(0,0,0,1));return i.mul(r).mul(s).mul(fg(n,1)).xyz}}}const KE=Wm(YE).setParameterLength(2),ZE=new Mr;class QE extends bS{static get type(){return"SpriteNodeMaterial"}constructor(e){super(),this.isSpriteNodeMaterial=!0,this._useSizeAttenuation=!0,this.positionNode=null,this.rotationNode=null,this.scaleNode=null,this.transparent=!0,this.setDefaultValues(ZE),this.setValues(e)}setupPositionView(e){const{object:t,camera:n}=e,{positionNode:i,rotationNode:r,scaleNode:s,sizeAttenuation:a}=this,o=Sb.mul(cg(i||0));let l=ag(xb[0].xyz.length(),xb[1].xyz.length());null!==s&&(l=l.mul(ag(s))),n.isPerspectiveCamera&&!1===a&&(l=l.mul(o.z.negate()));let u=Rb.xy;if(t.center&&!0===t.center.isVector2){const e=((e,t,n)=>new iy(e,t,n))("center","vec2",t);u=u.sub(e.sub(.5))}u=u.mul(l);const c=ng(r||rT),h=KE(u,c);return fg(o.xy.add(h),o.zw)}copy(e){return this.positionNode=e.positionNode,this.rotationNode=e.rotationNode,this.scaleNode=e.scaleNode,super.copy(e)}get sizeAttenuation(){return this._useSizeAttenuation}set sizeAttenuation(e){this._useSizeAttenuation!==e&&(this._useSizeAttenuation=e,this.needsUpdate=!0)}}const JE=new ms,ew=new cn;class tw extends QE{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.sizeNode=null,this.isPointsNodeMaterial=!0,this.setDefaultValues(JE),this.setValues(e)}setupPositionView(){const{positionNode:e}=this;return Sb.mul(cg(e||Cb)).xyz}setupVertexSprite(e){const{material:t,camera:n}=e,{rotationNode:i,scaleNode:r,sizeNode:s,sizeAttenuation:a}=this;let o=super.setupVertex(e);if(!0!==t.isNodeMaterial)return o;let l=null!==s?ag(s):bT;l=l.mul(Zy),n.isPerspectiveCamera&&!0===a&&(l=l.mul(nw.div(Db.z.negate()))),r&&r.isNode&&(l=l.mul(ag(r)));let u=Rb.xy;if(i&&i.isNode){const e=ng(i);u=KE(u,e)}return u=u.mul(l),u=u.div(nb.div(2)),u=u.mul(o.w),o=o.add(fg(u,0,0)),o}setupVertex(e){return e.object.isPoints?super.setupVertex(e):this.setupVertexSprite(e)}get alphaToCoverage(){return this._useAlphaToCoverage}set alphaToCoverage(e){this._useAlphaToCoverage!==e&&(this._useAlphaToCoverage=e,this.needsUpdate=!0)}}const nw=a_(1).onFrameUpdate(function({renderer:e}){const t=e.getSize(ew);this.value=.5*t.y});class iw extends FS{constructor(){super(),this.shadowNode=ng(1).toVar("shadowMask")}direct({lightNode:e}){null!==e.shadowNode&&this.shadowNode.mulAssign(e.shadowNode)}finish({context:e}){Mg.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(Mg.rgb)}}const rw=new zs;class sw extends bS{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.transparent=!0,this.setDefaultValues(rw),this.setValues(e)}setupLightingModel(){return new iw}}Tg("vec3"),Tg("vec3"),Tg("vec3");class aw{constructor(e,t,n){this.renderer=e,this.nodes=t,this.info=n,this._context="undefined"!=typeof self?self:null,this._animationLoop=null,this._requestId=null}start(){const e=(t,n)=>{this._requestId=this._context.requestAnimationFrame(e),!0===this.info.autoReset&&this.info.reset(),this.nodes.nodeFrame.update(),this.info.frame=this.nodes.nodeFrame.frameId,this.renderer._inspector.begin(),null!==this._animationLoop&&this._animationLoop(t,n),this.renderer._inspector.finish()};e()}stop(){this._context.cancelAnimationFrame(this._requestId),this._requestId=null}getAnimationLoop(){return this._animationLoop}setAnimationLoop(e){this._animationLoop=e}getContext(){return this._context}setContext(e){this._context=e}dispose(){this.stop()}}class ow{constructor(){this.weakMaps={}}_getWeakMap(e){const t=e.length;let n=this.weakMaps[t];return void 0===n&&(n=new WeakMap,this.weakMaps[t]=n),n}get(e){let t=this._getWeakMap(e);for(let n=0;n{this.dispose()},this.onGeometryDispose=()=>{this.attributes=null,this.attributesId=null},this.material.addEventListener("dispose",this.onMaterialDispose),this.geometry.addEventListener("dispose",this.onGeometryDispose)}updateClipping(e){this.clippingContext=e}get clippingNeedsUpdate(){return null!==this.clippingContext&&this.clippingContext.cacheKey!==this.clippingContextCacheKey&&(this.clippingContextCacheKey=this.clippingContext.cacheKey,!0)}get hardwareClippingPlanes(){return!0===this.material.hardwareClipping?this.clippingContext.unionClippingCount:0}getNodeBuilderState(){return this._nodeBuilderState||(this._nodeBuilderState=this._nodes.getForRender(this))}getMonitor(){return this._monitor||(this._monitor=this.getNodeBuilderState().observer)}getBindings(){return this._bindings||(this._bindings=this.getNodeBuilderState().createBindings())}getBindingGroup(e){for(const t of this.getBindings())if(t.name===e)return t}getIndex(){return this._geometries.getIndex(this)}getIndirect(){return this._geometries.getIndirect(this)}getIndirectOffset(){return this._geometries.getIndirectOffset(this)}getChainArray(){return[this.object,this.material,this.context,this.lightsNode]}setGeometry(e){this.geometry=e,this.attributes=null,this.attributesId=null}getAttributes(){if(null!==this.attributes)return this.attributes;const e=this.getNodeBuilderState().nodeAttributes,t=this.geometry,n=[],i=new Set,r={};for(const s of e){let e;if(s.node&&s.node.attribute?e=s.node.attribute:(e=t.getAttribute(s.name),r[s.name]=e.id),void 0===e)continue;n.push(e);const a=e.isInterleavedBufferAttribute?e.data:e;i.add(a)}return this.attributes=n,this.attributesId=r,this.vertexBuffers=Array.from(i.values()),n}getVertexBuffers(){return null===this.vertexBuffers&&this.getAttributes(),this.vertexBuffers}getDrawParameters(){const{object:e,material:t,geometry:n,group:i,drawRange:r}=this,s=this.drawParams||(this.drawParams={vertexCount:0,firstVertex:0,instanceCount:0,firstInstance:0}),a=this.getIndex(),o=null!==a;let l=1;if(!0===n.isInstancedBufferGeometry?l=n.instanceCount:void 0!==e.count&&(l=Math.max(0,e.count)),0===l)return null;if(s.instanceCount=l,!0===e.isBatchedMesh)return s;let u=1;!0!==t.wireframe||e.isPoints||e.isLineSegments||e.isLine||e.isLineLoop||(u=2);let c=r.start*u,h=(r.start+r.count)*u;null!==i&&(c=Math.max(c,i.start*u),h=Math.min(h,(i.start+i.count)*u));const d=n.attributes.position;let p=1/0;o?p=a.count:null!=d&&(p=d.count),c=Math.max(c,0),h=Math.min(h,p);const f=h-c;return f<0||f===1/0?null:(s.vertexCount=f,s.firstVertex=c,s)}getGeometryCacheKey(){const{geometry:e}=this;let t="";for(const n of Object.keys(e.attributes).sort()){const i=e.attributes[n];t+=n+",",i.data&&(t+=i.data.stride+","),i.offset&&(t+=i.offset+","),i.itemSize&&(t+=i.itemSize+","),i.normalized&&(t+="n,")}for(const n of Object.keys(e.morphAttributes).sort()){const i=e.morphAttributes[n];t+="morph-"+n+",";for(let e=0,n=i.length;e1||Array.isArray(e.morphTargetInfluences))&&(i+=e.uuid+","),i+=this.context.id+",",i+=e.receiveShadow+",",Nf(i)}get needsGeometryUpdate(){if(this.geometry.id!==this.object.geometry.id)return!0;if(null!==this.attributes){const e=this.attributesId;for(const t in e){const n=this.geometry.getAttribute(t);if(void 0===n||e[t]!==n.id)return!0}}return!1}get needsUpdate(){return this.initialNodesCacheKey!==this.getDynamicCacheKey()||this.clippingNeedsUpdate}getDynamicCacheKey(){let e=0;return!0!==this.material.isShadowPassMaterial&&(e=this._nodes.getCacheKey(this.scene,this.lightsNode)),this.camera.isArrayCamera&&(e=Lf(e,this.camera.cameras.length)),this.object.receiveShadow&&(e=Lf(e,1)),e=Lf(e,this.renderer.contextNode.id,this.renderer.contextNode.version),e}getCacheKey(){return this.getMaterialCacheKey()+this.getDynamicCacheKey()}dispose(){this.material.removeEventListener("dispose",this.onMaterialDispose),this.geometry.removeEventListener("dispose",this.onGeometryDispose),this.onDispose()}}const cw=[];class hw{constructor(e,t,n,i,r,s){this.renderer=e,this.nodes=t,this.geometries=n,this.pipelines=i,this.bindings=r,this.info=s,this.chainMaps={}}get(e,t,n,i,r,s,a,o){const l=this.getChainMap(o);cw[0]=e,cw[1]=t,cw[2]=s,cw[3]=r;let u=l.get(cw);return void 0===u?(u=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,n,i,r,s,a,o),l.set(cw,u)):(u.camera=i,u.updateClipping(a),u.needsGeometryUpdate&&u.setGeometry(e.geometry),(u.version!==t.version||u.needsUpdate)&&(u.initialCacheKey!==u.getCacheKey()?(u.dispose(),u=this.get(e,t,n,i,r,s,a,o)):u.version=t.version)),cw[0]=null,cw[1]=null,cw[2]=null,cw[3]=null,u}getChainMap(e="default"){return this.chainMaps[e]||(this.chainMaps[e]=new ow)}dispose(){this.chainMaps={}}createRenderObject(e,t,n,i,r,s,a,o,l,u,c){const h=this.getChainMap(c),d=new uw(e,t,n,i,r,s,a,o,l,u);return d.onDispose=()=>{this.pipelines.delete(d),this.bindings.deleteForRender(d),this.nodes.delete(d),h.delete(d.getChainArray())},d}}class dw{constructor(){this.data=new WeakMap}get(e){let t=this.data.get(e);return void 0===t&&(t={},this.data.set(e,t)),t}delete(e){let t=null;return this.data.has(e)&&(t=this.data.get(e),this.data.delete(e)),t}has(e){return this.data.has(e)}dispose(){this.data=new WeakMap}}const pw=1,fw=2,mw=3,gw=4,_w=16;class vw extends dw{constructor(e){super(),this.backend=e}delete(e){const t=super.delete(e);return null!==t&&this.backend.destroyAttribute(e),t}update(e,t){const n=this.get(e);if(void 0===n.version)t===pw?this.backend.createAttribute(e):t===fw?this.backend.createIndexAttribute(e):t===mw?this.backend.createStorageAttribute(e):t===gw&&this.backend.createIndirectStorageAttribute(e),n.version=this._getBufferAttribute(e).version;else{const t=this._getBufferAttribute(e);(n.version=65535?rr:ir)(t,1);return r.version=yw(e),r.__id=bw(e),r}class Tw extends dw{constructor(e,t){super(),this.attributes=e,this.info=t,this.wireframes=new WeakMap,this.attributeCall=new WeakMap,this._geometryDisposeListeners=new Map}has(e){const t=e.geometry;return super.has(t)&&!0===this.get(t).initialized}updateForRender(e){!1===this.has(e)&&this.initGeometry(e),this.updateAttributes(e)}initGeometry(e){const t=e.geometry;this.get(t).initialized=!0,this.info.memory.geometries++;const n=()=>{this.info.memory.geometries--;const i=t.index,r=e.getAttributes();null!==i&&this.attributes.delete(i);for(const e of r)this.attributes.delete(e);const s=this.wireframes.get(t);void 0!==s&&this.attributes.delete(s),t.removeEventListener("dispose",n),this._geometryDisposeListeners.delete(t)};t.addEventListener("dispose",n),this._geometryDisposeListeners.set(t,n)}updateAttributes(e){const t=e.getAttributes();for(const e of t)e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute?this.updateAttribute(e,mw):this.updateAttribute(e,pw);const n=this.getIndex(e);null!==n&&this.updateAttribute(n,fw);const i=e.geometry.indirect;null!==i&&this.updateAttribute(i,gw)}updateAttribute(e,t){const n=this.info.render.calls;e.isInterleavedBufferAttribute?void 0===this.attributeCall.get(e)?(this.attributes.update(e,t),this.attributeCall.set(e,n)):this.attributeCall.get(e.data)!==n&&(this.attributes.update(e,t),this.attributeCall.set(e.data,n),this.attributeCall.set(e,n)):this.attributeCall.get(e)!==n&&(this.attributes.update(e,t),this.attributeCall.set(e,n))}getIndirect(e){return e.geometry.indirect}getIndirectOffset(e){return e.geometry.indirectOffset}getIndex(e){const{geometry:t,material:n}=e;let i=t.index;if(!0===n.wireframe){const e=this.wireframes;let n=e.get(t);void 0===n?(n=xw(t),e.set(t,n)):n.version===yw(t)&&n.__id===bw(t)||(this.attributes.delete(n),n=xw(t),e.set(t,n)),i=n}return i}dispose(){for(const[e,t]of this._geometryDisposeListeners.entries())e.removeEventListener("dispose",t);this._geometryDisposeListeners.clear()}}class Sw{constructor(){this.autoReset=!0,this.frame=0,this.calls=0,this.render={calls:0,frameCalls:0,drawCalls:0,triangles:0,points:0,lines:0,timestamp:0},this.compute={calls:0,frameCalls:0,timestamp:0},this.memory={geometries:0,textures:0}}update(e,t,n){this.render.drawCalls++,e.isMesh||e.isSprite?this.render.triangles+=n*(t/3):e.isPoints?this.render.points+=n*t:e.isLineSegments?this.render.lines+=n*(t/2):e.isLine?this.render.lines+=n*(t-1):qt("WebGPUInfo: Unknown object type.")}reset(){this.render.drawCalls=0,this.render.frameCalls=0,this.compute.frameCalls=0,this.render.triangles=0,this.render.points=0,this.render.lines=0}dispose(){this.reset(),this.calls=0,this.render.calls=0,this.compute.calls=0,this.render.timestamp=0,this.compute.timestamp=0,this.memory.geometries=0,this.memory.textures=0}}class Mw{constructor(e){this.cacheKey=e,this.usedTimes=0}}class Ew extends Mw{constructor(e,t,n){super(e),this.vertexProgram=t,this.fragmentProgram=n}}class ww extends Mw{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let Aw=0;class Rw{constructor(e,t,n,i=null,r=null){this.id=Aw++,this.code=e,this.stage=t,this.name=n,this.transforms=i,this.attributes=r,this.usedTimes=0}}class Cw extends dw{constructor(e,t){super(),this.backend=e,this.nodes=t,this.bindings=null,this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}getForCompute(e,t){const{backend:n}=this,i=this.get(e);if(this._needsComputeUpdate(e)){const r=i.pipeline;r&&(r.usedTimes--,r.computeProgram.usedTimes--);const s=this.nodes.getForCompute(e);let a=this.programs.compute.get(s.computeShader);void 0===a&&(r&&0===r.computeProgram.usedTimes&&this._releaseProgram(r.computeProgram),a=new Rw(s.computeShader,"compute",e.name,s.transforms,s.nodeAttributes),this.programs.compute.set(s.computeShader,a),n.createProgram(a));const o=this._getComputeCacheKey(e,a);let l=this.caches.get(o);void 0===l&&(r&&0===r.usedTimes&&this._releasePipeline(r),l=this._getComputePipeline(e,a,o,t)),l.usedTimes++,a.usedTimes++,i.version=e.version,i.pipeline=l}return i.pipeline}getForRender(e,t=null){const{backend:n}=this,i=this.get(e);if(this._needsRenderUpdate(e)){const r=i.pipeline;r&&(r.usedTimes--,r.vertexProgram.usedTimes--,r.fragmentProgram.usedTimes--);const s=e.getNodeBuilderState(),a=e.material?e.material.name:"";let o=this.programs.vertex.get(s.vertexShader);void 0===o&&(r&&0===r.vertexProgram.usedTimes&&this._releaseProgram(r.vertexProgram),o=new Rw(s.vertexShader,"vertex",a),this.programs.vertex.set(s.vertexShader,o),n.createProgram(o));let l=this.programs.fragment.get(s.fragmentShader);void 0===l&&(r&&0===r.fragmentProgram.usedTimes&&this._releaseProgram(r.fragmentProgram),l=new Rw(s.fragmentShader,"fragment",a),this.programs.fragment.set(s.fragmentShader,l),n.createProgram(l));const u=this._getRenderCacheKey(e,o,l);let c=this.caches.get(u);void 0===c?(r&&0===r.usedTimes&&this._releasePipeline(r),c=this._getRenderPipeline(e,o,l,u,t)):e.pipeline=c,c.usedTimes++,o.usedTimes++,l.usedTimes++,i.pipeline=c}return i.pipeline}delete(e){const t=this.get(e).pipeline;return t&&(t.usedTimes--,0===t.usedTimes&&this._releasePipeline(t),t.isComputePipeline?(t.computeProgram.usedTimes--,0===t.computeProgram.usedTimes&&this._releaseProgram(t.computeProgram)):(t.fragmentProgram.usedTimes--,t.vertexProgram.usedTimes--,0===t.vertexProgram.usedTimes&&this._releaseProgram(t.vertexProgram),0===t.fragmentProgram.usedTimes&&this._releaseProgram(t.fragmentProgram))),super.delete(e)}dispose(){super.dispose(),this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}updateForRender(e){this.getForRender(e)}_getComputePipeline(e,t,n,i){n=n||this._getComputeCacheKey(e,t);let r=this.caches.get(n);return void 0===r&&(r=new ww(n,t),this.caches.set(n,r),this.backend.createComputePipeline(r,i)),r}_getRenderPipeline(e,t,n,i,r){i=i||this._getRenderCacheKey(e,t,n);let s=this.caches.get(i);return void 0===s&&(s=new Ew(i,t,n),this.caches.set(i,s),e.pipeline=s,this.backend.createRenderPipeline(e,r)),s}_getComputeCacheKey(e,t){return e.id+","+t.id}_getRenderCacheKey(e,t,n){return t.id+","+n.id+","+this.backend.getRenderCacheKey(e)}_releasePipeline(e){this.caches.delete(e.cacheKey)}_releaseProgram(e){const t=e.code,n=e.stage;this.programs[n].delete(t)}_needsComputeUpdate(e){const t=this.get(e);return void 0===t.pipeline||t.version!==e.version}_needsRenderUpdate(e){return void 0===this.get(e).pipeline||this.backend.needsRenderUpdate(e)}}class Nw extends dw{constructor(e,t,n,i,r,s){super(),this.backend=e,this.textures=n,this.pipelines=r,this.attributes=i,this.nodes=t,this.info=s,this.pipelines.bindings=this}getForRender(e){const t=e.getBindings();for(const e of t){const n=this.get(e);void 0===n.bindGroup&&(this._init(e),this.backend.createBindings(e,t,0),n.bindGroup=e)}return t}getForCompute(e){const t=this.nodes.getForCompute(e).bindings;for(const e of t){const n=this.get(e);void 0===n.bindGroup&&(this._init(e),this.backend.createBindings(e,t,0),n.bindGroup=e)}return t}updateForCompute(e){this._updateBindings(this.getForCompute(e))}updateForRender(e){this._updateBindings(this.getForRender(e))}deleteForCompute(e){const t=this.nodes.getForCompute(e).bindings;for(const e of t)this.backend.deleteBindGroupData(e),this.delete(e)}deleteForRender(e){const t=e.getBindings();for(const e of t)this.backend.deleteBindGroupData(e),this.delete(e)}_updateBindings(e){for(const t of e)this._update(t,e)}_init(e){for(const t of e.bindings)if(t.isSampledTexture)this.textures.updateTexture(t.texture);else if(t.isSampler)this.textures.updateSampler(t.texture);else if(t.isStorageBuffer){const e=t.attribute,n=e.isIndirectStorageBufferAttribute?gw:mw;this.attributes.update(e,n)}}_update(e,t){const{backend:n}=this;let i=!1,r=!0,s=0,a=0;for(const t of e.bindings){if(!1!==this.nodes.updateGroup(t)){if(t.isStorageBuffer){const e=t.attribute,r=e.isIndirectStorageBufferAttribute?gw:mw,s=n.get(t);this.attributes.update(e,r),s.attribute!==e&&(s.attribute=e,i=!0)}if(t.isUniformBuffer){t.update()&&n.updateBinding(t)}else if(t.isSampledTexture){const o=t.update(),l=t.texture,u=this.textures.get(l);o&&(this.textures.updateTexture(l),t.generation!==u.generation&&(t.generation=u.generation,i=!0),u.bindGroups.add(e));if(void 0!==n.get(l).externalTexture||u.isDefaultTexture?r=!1:(s=10*s+l.id,a+=l.version),!0===l.isStorageTexture&&!0===l.mipmapsAutoUpdate){const e=this.get(l);!0===t.store?e.needsMipmap=!0:this.textures.needsMipmaps(l)&&!0===e.needsMipmap&&(this.backend.generateMipmaps(l),e.needsMipmap=!1)}}else if(t.isSampler){if(t.update()){const e=this.textures.updateSampler(t.texture);t.samplerKey!==e&&(t.samplerKey=e,i=!0)}}t.isBuffer&&t.updateRanges.length>0&&t.clearUpdateRanges()}}!0===i&&this.backend.updateBindings(e,t,r?s:0,a)}}function Pw(e,t){return e.groupOrder!==t.groupOrder?e.groupOrder-t.groupOrder:e.renderOrder!==t.renderOrder?e.renderOrder-t.renderOrder:e.z!==t.z?e.z-t.z:e.id-t.id}function Lw(e,t){return e.groupOrder!==t.groupOrder?e.groupOrder-t.groupOrder:e.renderOrder!==t.renderOrder?e.renderOrder-t.renderOrder:e.z!==t.z?t.z-e.z:e.id-t.id}function Dw(e){return(e.transmission>0||e.transmissionNode&&e.transmissionNode.isNode)&&2===e.side&&!1===e.forceSinglePass}class Iw{constructor(e,t,n){this.renderItems=[],this.renderItemsIndex=0,this.opaque=[],this.transparentDoublePass=[],this.transparent=[],this.bundles=[],this.lightsNode=e.getNode(t,n),this.lightsArray=[],this.scene=t,this.camera=n,this.occlusionQueryCount=0}begin(){return this.renderItemsIndex=0,this.opaque.length=0,this.transparentDoublePass.length=0,this.transparent.length=0,this.bundles.length=0,this.lightsArray.length=0,this.occlusionQueryCount=0,this}getNextRenderItem(e,t,n,i,r,s,a){let o=this.renderItems[this.renderItemsIndex];return void 0===o?(o={id:e.id,object:e,geometry:t,material:n,groupOrder:i,renderOrder:e.renderOrder,z:r,group:s,clippingContext:a},this.renderItems[this.renderItemsIndex]=o):(o.id=e.id,o.object=e,o.geometry=t,o.material=n,o.groupOrder=i,o.renderOrder=e.renderOrder,o.z=r,o.group=s,o.clippingContext=a),this.renderItemsIndex++,o}push(e,t,n,i,r,s,a){const o=this.getNextRenderItem(e,t,n,i,r,s,a);!0===e.occlusionTest&&this.occlusionQueryCount++,!0===n.transparent||n.transmission>0||n.transmissionNode&&n.transmissionNode.isNode||n.backdropNode&&n.backdropNode.isNode?(Dw(n)&&this.transparentDoublePass.push(o),this.transparent.push(o)):this.opaque.push(o)}unshift(e,t,n,i,r,s,a){const o=this.getNextRenderItem(e,t,n,i,r,s,a);!0===n.transparent||n.transmission>0||n.transmissionNode&&n.transmissionNode.isNode||n.backdropNode&&n.backdropNode.isNode?(Dw(n)&&this.transparentDoublePass.unshift(o),this.transparent.unshift(o)):this.opaque.unshift(o)}pushBundle(e){this.bundles.push(e)}pushLight(e){this.lightsArray.push(e)}sort(e,t){this.opaque.length>1&&this.opaque.sort(e||Pw),this.transparentDoublePass.length>1&&this.transparentDoublePass.sort(t||Lw),this.transparent.length>1&&this.transparent.sort(t||Lw)}finish(){this.lightsNode.setLights(this.lightsArray);for(let e=this.renderItemsIndex,t=this.renderItems.length;e>t,l=a.height>>t;let u=e.depthTexture||r[t];const c=!0===e.depthBuffer||!0===e.stencilBuffer;let h=!1;void 0===u&&c&&(u=new vs,u.format=e.stencilBuffer?Pe:Ne,u.type=e.stencilBuffer?Me:ye,u.image.width=o,u.image.height=l,u.image.depth=a.depth,u.renderTarget=e,u.isArrayTexture=!0===e.multiview&&a.depth>1,r[t]=u),n.width===a.width&&a.height===n.height||(h=!0,u&&(u.needsUpdate=!0,u.image.width=o,u.image.height=l,u.image.depth=u.isArrayTexture?u.image.depth:1)),n.width=a.width,n.height=a.height,n.textures=s,n.depthTexture=u||null,n.depth=e.depthBuffer,n.stencil=e.stencilBuffer,n.renderTarget=e,n.sampleCount!==i&&(h=!0,u&&(u.needsUpdate=!0),n.sampleCount=i);const d={sampleCount:i};if(!0!==e.isXRRenderTarget){for(let e=0;e{this._destroyRenderTarget(e)},e.addEventListener("dispose",n.onDispose))}updateTexture(e,t={}){const n=this.get(e);if(!0===n.initialized&&n.version===e.version)return;const i=e.isRenderTargetTexture||e.isDepthTexture||e.isFramebufferTexture,r=this.backend;if(i&&!0===n.initialized&&r.destroyTexture(e),e.isFramebufferTexture){const t=this.renderer.getRenderTarget();e.type=t?t.texture.type:fe}const{width:s,height:a,depth:o}=this.getSize(e);if(t.width=s,t.height=a,t.depth=o,t.needsMipmaps=this.needsMipmaps(e),t.levels=t.needsMipmaps?this.getMipLevels(e,s,a):1,e.isCubeTexture&&e.mipmaps.length>0&&t.levels++,i||!0===e.isStorageTexture||!0===e.isExternalTexture)r.createTexture(e,t),n.generation=e.version;else if(e.version>0){const i=e.image;if(void 0===i)Xt("Renderer: Texture marked for update but image is undefined.");else if(!1===i.complete)Xt("Renderer: Texture marked for update but image is incomplete.");else{if(e.images){const n=[];for(const t of e.images)n.push(t);t.images=n}else t.image=i;void 0!==n.isDefaultTexture&&!0!==n.isDefaultTexture||(r.createTexture(e,t),n.isDefaultTexture=!1,n.generation=e.version),!0===e.source.dataReady&&r.updateTexture(e,t);const s=!0===e.isStorageTexture&&!1===e.mipmapsAutoUpdate;t.needsMipmaps&&0===e.mipmaps.length&&!s&&r.generateMipmaps(e),e.onUpdate&&e.onUpdate(e)}}else r.createDefaultTexture(e),n.isDefaultTexture=!0,n.generation=e.version;!0!==n.initialized&&(n.initialized=!0,n.generation=e.version,n.bindGroups=new Set,this.info.memory.textures++,e.isVideoTexture&&!0===bn.enabled&&bn.getTransfer(e.colorSpace)!==St&&Xt("WebGPURenderer: Video textures must use a color space with a sRGB transfer function, e.g. SRGBColorSpace."),n.onDispose=()=>{this._destroyTexture(e)},e.addEventListener("dispose",n.onDispose)),n.version=e.version}updateSampler(e){return this.backend.updateSampler(e)}getSize(e,t=Vw){let n=e.images?e.images[0]:e.image;return n?(void 0!==n.image&&(n=n.image),"undefined"!=typeof HTMLVideoElement&&n instanceof HTMLVideoElement?(t.width=n.videoWidth||1,t.height=n.videoHeight||1,t.depth=1):"undefined"!=typeof VideoFrame&&n instanceof VideoFrame?(t.width=n.displayWidth||1,t.height=n.displayHeight||1,t.depth=1):(t.width=n.width||1,t.height=n.height||1,t.depth=e.isCubeTexture?6:n.depth||1)):t.width=t.height=t.depth=1,t}getMipLevels(e,t,n){let i;return i=e.mipmaps.length>0?e.mipmaps.length:!0===e.isCompressedTexture?1:Math.floor(Math.log2(Math.max(t,n)))+1,i}needsMipmaps(e){return!0===e.generateMipmaps||e.mipmaps.length>0}_destroyRenderTarget(e){if(!0===this.has(e)){const t=this.get(e),n=t.textures,i=t.depthTexture;e.removeEventListener("dispose",t.onDispose);for(let e=0;e=2)for(let n=0;n{if(this._currentNode=t,!t.isVarNode||!t.isIntent(e)||!0===t.isAssign(e))if("setup"===i)t.build(e);else if("analyze"===i)t.build(e,this);else if("generate"===i){const n=e.getDataFromNode(t,"any").stages,i=n&&n[e.shaderStage];if(t.isVarNode&&i&&1===i.length&&i[0]&&i[0].isStackNode)return;t.build(e,"void")}},s=[...this.nodes];for(const e of s)r(e);this._currentNode=null;const a=this.nodes.filter(e=>-1===s.indexOf(e));for(const e of a)r(e);let o;return o=this.hasOutput(e)?this.outputNode.build(e,...t):super.build(e,...t),Zm(n),e.removeActiveStack(this),o}}const $w=Wm(Ww).setParameterLength(0,1);class Xw extends tm{static get type(){return"BitcastNode"}constructor(e,t,n=null){super(),this.valueNode=e,this.conversionType=t,this.inputType=n,this.isBitcastNode=!0}getNodeType(e){if(null!==this.inputType){const t=this.valueNode.getNodeType(e),n=e.getTypeLength(t);return e.getTypeFromLength(n,this.conversionType)}return this.conversionType}generate(e){const t=this.getNodeType(e);let n="";if(null!==this.inputType){const t=this.valueNode.getNodeType(e);n=1===e.getTypeLength(t)?this.inputType:e.changeComponentType(t,this.inputType)}else n=this.valueNode.getNodeType(e);return`${e.getBitcastMethod(t,n)}( ${this.valueNode.build(e,n)} )`}}const qw=Xm(Xw).setParameterLength(2),Yw={};class Kw extends O_{static get type(){return"BitcountNode"}constructor(e,t){super(e,t),this.isBitcountNode=!0}_resolveElementType(e,t,n){"int"===n?t.assign(qw(e,"uint")):t.assign(e)}_returnDataNode(e){switch(e){case"uint":return rg;case"int":return ig;case"uvec2":return lg;case"uvec3":return dg;case"uvec4":return gg;case"ivec2":return og;case"ivec3":return hg;case"ivec4":return mg}}_createTrailingZerosBaseLayout(e,t){const n=this._returnDataNode(t),i=Km(([e])=>{const i=rg(0);this._resolveElementType(e,i,t);const r=(e=>new Xw(e,"uint","float"))(ng(i.bitAnd(uv(i)))),s=r.shiftRight(23).sub(127);return n(s)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]});return i}_createLeadingZerosBaseLayout(e,t){const n=this._returnDataNode(t),i=Km(([e])=>{Jm(e.equal(rg(0)),()=>rg(32));const i=rg(0),r=rg(0);return this._resolveElementType(e,i,t),Jm(i.shiftRight(16).equal(0),()=>{r.addAssign(16),i.shiftLeftAssign(16)}),Jm(i.shiftRight(24).equal(0),()=>{r.addAssign(8),i.shiftLeftAssign(8)}),Jm(i.shiftRight(28).equal(0),()=>{r.addAssign(4),i.shiftLeftAssign(4)}),Jm(i.shiftRight(30).equal(0),()=>{r.addAssign(2),i.shiftLeftAssign(2)}),Jm(i.shiftRight(31).equal(0),()=>{r.addAssign(1)}),n(r)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]});return i}_createOneBitsBaseLayout(e,t){const n=this._returnDataNode(t),i=Km(([e])=>{const i=rg(0);this._resolveElementType(e,i,t),i.assign(i.sub(i.shiftRight(rg(1)).bitAnd(rg(1431655765)))),i.assign(i.bitAnd(rg(858993459)).add(i.shiftRight(rg(2)).bitAnd(rg(858993459))));const r=i.add(i.shiftRight(rg(4))).bitAnd(rg(252645135)).mul(rg(16843009)).shiftRight(rg(24));return n(r)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]});return i}_createMainLayout(e,t,n,i){const r=this._returnDataNode(t),s=Km(([e])=>{if(1===n)return r(i(e));{const t=r(0),s=["x","y","z","w"];for(let r=0;rc(n))()}}Kw.COUNT_TRAILING_ZEROS="countTrailingZeros",Kw.COUNT_LEADING_ZEROS="countLeadingZeros",Kw.COUNT_ONE_BITS="countOneBits",new Qr,new dn,new dn,new dn,new Fn,new dn(0,0,-1),new Pn,new dn,new dn,new Pn,new cn;const Zw=new Ln;Qy.flipX(),Zw.depthTexture=new vs(1,1);const Qw=new Ra(-1,1,1,-1,0,1);class Jw extends vr{constructor(e=!1){super();const t=!1===e?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new ar([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new ar(t,2))}}const eA=new Jw;class tA extends Wr{constructor(e=null){super(eA,e),this.camera=Qw,this.isQuadMesh=!0}async renderAsync(e){Yt('QuadMesh: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await e.init(),e.render(this,Qw)}render(e){e.render(this,Qw)}}const nA=Km(([e])=>J_(ng(52.9829189).mul(J_(wv(e,ag(.06711056,.00583715)))))).setLayout({name:"interleavedGradientNoise",type:"float",inputs:[{name:"position",type:"vec2"}]}),iA=Km(([e,t,n])=>{const i=ng(2.399963229728653),r=q_(ng(e).add(.5).div(ng(t))),s=ng(e).mul(i).add(n);return ag(tv(s),ev(s)).mul(r)}).setLayout({name:"vogelDiskSample",type:"vec2",inputs:[{name:"sampleIndex",type:"int"},{name:"samplesCount",type:"int"},{name:"phi",type:"float"}]});class rA extends Qf{static get type(){return"EventNode"}constructor(e,t){super("void"),this.eventType=e,this.callback=t,e===rA.OBJECT?this.updateType=Hf:e===rA.MATERIAL?this.updateType=Gf:e===rA.BEFORE_OBJECT?this.updateBeforeType=Hf:e===rA.BEFORE_MATERIAL&&(this.updateBeforeType=Gf)}update(e){this.callback(e)}updateBefore(e){this.callback(e)}}rA.OBJECT="object",rA.MATERIAL="material",rA.BEFORE_OBJECT="beforeObject",rA.BEFORE_MATERIAL="beforeMaterial";const sA=new $n,aA=new Fn,oA=a_(0).setGroup(i_).onRenderUpdate(({scene:e})=>e.backgroundBlurriness),lA=a_(1).setGroup(i_).onRenderUpdate(({scene:e})=>e.backgroundIntensity),uA=a_(new Fn).setGroup(i_).onRenderUpdate(({scene:e})=>{const t=e.background;return null!==t&&t.isTexture&&300!==t.mapping?(sA.copy(e.backgroundRotation),sA.x*=-1,sA.y*=-1,sA.z*=-1,aA.makeRotationFromEuler(sA)):aA.identity(),aA}),cA=Km(({texture:e,uv:t})=>{const n=1e-4,i=cg().toVar();return Jm(t.x.lessThan(n),()=>{i.assign(cg(1,0,0))}).ElseIf(t.y.lessThan(n),()=>{i.assign(cg(0,1,0))}).ElseIf(t.z.lessThan(n),()=>{i.assign(cg(0,0,1))}).ElseIf(t.x.greaterThan(.9999),()=>{i.assign(cg(-1,0,0))}).ElseIf(t.y.greaterThan(.9999),()=>{i.assign(cg(0,-1,0))}).ElseIf(t.z.greaterThan(.9999),()=>{i.assign(cg(0,0,-1))}).Else(()=>{const n=.01,r=e.sample(t.add(cg(-.01,0,0))).r.sub(e.sample(t.add(cg(n,0,0))).r),s=e.sample(t.add(cg(0,-.01,0))).r.sub(e.sample(t.add(cg(0,n,0))).r),a=e.sample(t.add(cg(0,0,-.01))).r.sub(e.sample(t.add(cg(0,0,n))).r);i.assign(cg(r,s,a))}),i.normalize()});class hA extends By{static get type(){return"Texture3DNode"}constructor(e,t=null,n=null){super(e,t,n),this.isTexture3DNode=!0}getInputType(){return"texture3D"}getDefaultUV(){return cg(.5,.5,.5)}setUpdateMatrix(){}generateUV(e,t){return t.build(e,!0===this.sampler?"vec3":"ivec3")}generateOffset(e,t){return t.build(e,"ivec3")}normal(e){return cA({texture:this,uv:e})}}const dA=Wm(hA).setParameterLength(1,3);Km(([e,t])=>e.mul(t).floor().div(t));const pA=new cn;class fA extends By{static get type(){return"PassTextureNode"}constructor(e,t){super(t),this.passNode=e,this.isPassTextureNode=!0,this.setUpdateMatrix(!1)}setup(e){return e.getNodeProperties(this).passNode=this.passNode,super.setup(e)}clone(){return new this.constructor(this.passNode,this.value)}}class mA extends fA{static get type(){return"PassMultipleTextureNode"}constructor(e,t,n=!1){super(e,null),this.textureName=t,this.previousTexture=n,this.isPassMultipleTextureNode=!0}updateTexture(){this.value=this.previousTexture?this.passNode.getPreviousTexture(this.textureName):this.passNode.getTexture(this.textureName)}setup(e){return this.updateTexture(),super.setup(e)}clone(){const e=new this.constructor(this.passNode,this.textureName,this.previousTexture);return e.uvNode=this.uvNode,e.levelNode=this.levelNode,e.biasNode=this.biasNode,e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.offsetNode=this.offsetNode,e}}class gA extends tm{static get type(){return"PassNode"}constructor(e,t,n,i={}){super("vec4"),this.scope=e,this.scene=t,this.camera=n,this.options=i,this._pixelRatio=1,this._width=1,this._height=1;const r=new vs;r.isRenderTargetTexture=!0,r.name="depth";const s=new Ln(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:xe,...i});s.texture.name="output",s.depthTexture=r,this.renderTarget=s,this.overrideMaterial=null,this.transparent=!0,this.opaque=!0,this.contextNode=null,this._contextNodeCache=null,this._textures={output:s.texture,depth:r},this._textureNodes={},this._linearDepthNodes={},this._viewZNodes={},this._previousTextures={},this._previousTextureNodes={},this._cameraNear=a_(0),this._cameraFar=a_(0),this._mrt=null,this._layers=null,this._resolutionScale=1,this._viewport=null,this._scissor=null,this.isPassNode=!0,this.updateBeforeType=Vf,this.global=!0}setResolutionScale(e){return this._resolutionScale=e,this}getResolutionScale(){return this._resolutionScale}setResolution(e){return Xt("PassNode: .setResolution() is deprecated. Use .setResolutionScale() instead."),this.setResolutionScale(e)}getResolution(){return Xt("PassNode: .getResolution() is deprecated. Use .getResolutionScale() instead."),this.getResolutionScale()}setLayers(e){return this._layers=e,this}getLayers(){return this._layers}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getTexture(e){let t=this._textures[e];if(void 0===t){t=this.renderTarget.texture.clone(),t.name=e,this._textures[e]=t,this.renderTarget.textures.push(t)}return t}getPreviousTexture(e){let t=this._previousTextures[e];return void 0===t&&(t=this.getTexture(e).clone(),this._previousTextures[e]=t),t}toggleTexture(e){const t=this._previousTextures[e];if(void 0!==t){const n=this._textures[e],i=this.renderTarget.textures.indexOf(n);this.renderTarget.textures[i]=t,this._textures[e]=t,this._previousTextures[e]=n,this._textureNodes[e].updateTexture(),this._previousTextureNodes[e].updateTexture()}}getTextureNode(e="output"){let t=this._textureNodes[e];return void 0===t&&(t=new mA(this,e),t.updateTexture(),this._textureNodes[e]=t),t}getPreviousTextureNode(e="output"){let t=this._previousTextureNodes[e];return void 0===t&&(void 0===this._textureNodes[e]&&this.getTextureNode(e),t=new mA(this,e,!0),t.updateTexture(),this._previousTextureNodes[e]=t),t}getViewZNode(e="depth"){let t=this._viewZNodes[e];if(void 0===t){const n=this._cameraNear,i=this._cameraFar;this._viewZNodes[e]=t=cS(this.getTextureNode(e),n,i)}return t}getLinearDepthNode(e="depth"){let t=this._linearDepthNodes[e];if(void 0===t){const n=this._cameraNear,i=this._cameraFar,r=this.getViewZNode(e);this._linearDepthNodes[e]=t=lS(r,n,i)}return t}async compileAsync(e){const t=e.getRenderTarget(),n=e.getMRT();e.setRenderTarget(this.renderTarget),e.setMRT(this._mrt),await e.compileAsync(this.scene,this.camera),e.setRenderTarget(t),e.setMRT(n)}setup({renderer:e}){return this.renderTarget.samples=void 0===this.options.samples?e.samples:this.options.samples,this.renderTarget.texture.type=e.getOutputBufferType(),this.scope===gA.COLOR?this.getTextureNode():this.getLinearDepthNode()}updateBefore(e){const{renderer:t}=e,{scene:n}=this;let i,r;const s=t.getOutputRenderTarget();s&&!0===s.isXRRenderTarget?(r=1,i=t.xr.getCamera(),t.xr.updateCamera(i),pA.set(s.width,s.height)):(i=this.camera,r=t.getPixelRatio(),t.getSize(pA)),this._pixelRatio=r,this.setSize(pA.width,pA.height);const a=t.getRenderTarget(),o=t.getMRT(),l=t.autoClear,u=t.transparent,c=t.opaque,h=i.layers.mask,d=t.contextNode,p=n.overrideMaterial;this._cameraNear.value=i.near,this._cameraFar.value=i.far,null!==this._layers&&(i.layers.mask=this._layers.mask);for(const e in this._previousTextures)this.toggleTexture(e);null!==this.overrideMaterial&&(n.overrideMaterial=this.overrideMaterial),t.setRenderTarget(this.renderTarget),t.setMRT(this._mrt),t.autoClear=!0,t.transparent=this.transparent,t.opaque=this.opaque,null!==this.contextNode&&(null!==this._contextNodeCache&&this._contextNodeCache.version===this.version||(this._contextNodeCache={version:this.version,context:Hv({...t.contextNode.getFlowContextData(),...this.contextNode.getFlowContextData()})}),t.contextNode=this._contextNodeCache.context);const f=n.name;n.name=this.name?this.name:n.name,t.render(n,i),n.name=f,n.overrideMaterial=p,t.setRenderTarget(a),t.setMRT(o),t.autoClear=l,t.transparent=u,t.opaque=c,t.contextNode=d,i.layers.mask=h}setSize(e,t){this._width=e,this._height=t;const n=Math.floor(this._width*this._pixelRatio*this._resolutionScale),i=Math.floor(this._height*this._pixelRatio*this._resolutionScale);this.renderTarget.setSize(n,i),null!==this._scissor&&this.renderTarget.scissor.copy(this._scissor),null!==this._viewport&&this.renderTarget.viewport.copy(this._viewport)}setScissor(e,t,n,i){null===e?this._scissor=null:(null===this._scissor&&(this._scissor=new Pn),e.isVector4?this._scissor.copy(e):this._scissor.set(e,t,n,i),this._scissor.multiplyScalar(this._pixelRatio*this._resolutionScale).floor())}setViewport(e,t,n,i){null===e?this._viewport=null:(null===this._viewport&&(this._viewport=new Pn),e.isVector4?this._viewport.copy(e):this._viewport.set(e,t,n,i),this._viewport.multiplyScalar(this._pixelRatio*this._resolutionScale).floor())}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget.dispose()}}gA.COLOR="color",gA.DEPTH="depth";const _A=Km(([e,t])=>e.mul(t).clamp()).setLayout({name:"linearToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),vA=Km(([e,t])=>(e=e.mul(t)).div(e.add(1)).clamp()).setLayout({name:"reinhardToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),yA=Km(([e,t])=>{const n=(e=(e=e.mul(t)).sub(.004).max(0)).mul(e.mul(6.2).add(.5)),i=e.mul(e.mul(6.2).add(1.7)).add(.06);return n.div(i).pow(2.2)}).setLayout({name:"cineonToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),bA=Km(([e])=>{const t=e.mul(e.add(.0245786)).sub(90537e-9),n=e.mul(e.add(.432951).mul(.983729)).add(.238081);return t.div(n)}),xA=Km(([e,t])=>{const n=yg(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),i=yg(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return e=e.mul(t).div(.6),e=n.mul(e),e=bA(e),(e=i.mul(e)).clamp()}).setLayout({name:"acesFilmicToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),TA=yg(cg(1.6605,-.1246,-.0182),cg(-.5876,1.1329,-.1006),cg(-.0728,-.0083,1.1187)),SA=yg(cg(.6274,.0691,.0164),cg(.3293,.9195,.088),cg(.0433,.0113,.8956)),MA=Km(([e])=>{const t=cg(e).toVar(),n=cg(t.mul(t)).toVar(),i=cg(n.mul(n)).toVar();return ng(15.5).mul(i.mul(n)).sub(f_(40.14,i.mul(t))).add(f_(31.96,i).sub(f_(6.868,n.mul(t))).add(f_(.4298,n).add(f_(.1191,t).sub(.00232))))}),EA=Km(([e,t])=>{const n=cg(e).toVar(),i=yg(cg(.856627153315983,.137318972929847,.11189821299995),cg(.0951212405381588,.761241990602591,.0767994186031903),cg(.0482516061458583,.101439036467562,.811302368396859)),r=yg(cg(1.1271005818144368,-.1413297634984383,-.14132976349843826),cg(-.11060664309660323,1.157823702216272,-.11060664309660294),cg(-.016493938717834573,-.016493938717834257,1.2519364065950405)),s=ng(-12.47393),a=ng(4.026069);return n.mulAssign(t),n.assign(SA.mul(n)),n.assign(i.mul(n)),n.assign(xv(n,1e-10)),n.assign(X_(n)),n.assign(n.sub(s).div(a.sub(s))),n.assign(Iv(n,0,1)),n.assign(MA(n)),n.assign(r.mul(n)),n.assign(Rv(xv(cg(0),n),cg(2.2))),n.assign(TA.mul(n)),n.assign(Iv(n,0,1)),n}).setLayout({name:"agxToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),wA=Km(([e,t])=>{const n=ng(.76),i=ng(.15);e=e.mul(t);const r=bv(e.r,bv(e.g,e.b)),s=Vv(r.lessThan(.08),r.sub(f_(6.25,r.mul(r))),.04);e.subAssign(s);const a=xv(e.r,xv(e.g,e.b));Jm(a.lessThan(n),()=>e);const o=p_(1,n),l=p_(1,o.mul(o).div(a.add(o.sub(n))));e.mulAssign(l.div(a));const u=p_(1,m_(1,i.mul(a.sub(l)).add(1)));return Dv(e,cg(l),u)}).setLayout({name:"neutralToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]});class AA extends Qf{static get type(){return"CodeNode"}constructor(e="",t=[],n=""){super("code"),this.isCodeNode=!0,this.global=!0,this.code=e,this.includes=t,this.language=n}setIncludes(e){return this.includes=e,this}getIncludes(){return this.includes}generate(e){const t=this.getIncludes(e);for(const n of t)n.build(e);const n=e.getCodeFromNode(this,this.getNodeType(e));return n.code=this.code,n.code}serialize(e){super.serialize(e),e.code=this.code,e.language=this.language}deserialize(e){super.deserialize(e),this.code=e.code,this.language=e.language}}class RA extends AA{static get type(){return"FunctionNode"}constructor(e="",t=[],n=""){super(e,t,n)}getNodeType(e){return this.getNodeFunction(e).type}getMemberType(e,t){const n=this.getNodeType(e);return e.getStructTypeNode(n).getMemberType(e,t)}getInputs(e){return this.getNodeFunction(e).inputs}getNodeFunction(e){const t=e.getDataFromNode(this);let n=t.nodeFunction;return void 0===n&&(n=e.parser.parseFunction(this.code),t.nodeFunction=n),n}generate(e,t){super.generate(e);const n=this.getNodeFunction(e),i=n.name,r=n.type,s=e.getCodeFromNode(this,r);""!==i&&(s.name=i);const a=e.getPropertyName(s),o=this.getNodeFunction(e).getCode(a);return s.code=o+"\n","property"===t?a:e.format(`${a}()`,r,t)}}function CA(e){let t;const n=e.context.getViewZ;return void 0!==n&&(t=n(this)),(t||Db.z).negate()}const NA=Km(([e,t],n)=>{const i=CA(n);return Ov(e,t,i)}),PA=Km(([e],t)=>{const n=CA(t);return e.mul(e,n,n).negate().exp().oneMinus()});Km(([e,t],n)=>{const i=CA(n),r=t.sub(Pb.y).max(0).toConst().mul(i).toConst();return e.mul(e,r,r).negate().exp().oneMinus()});const LA=Km(([e,t])=>fg(t.toFloat().mix(jg.rgb,e.toVec3()),jg.a));Wm(class extends Qf{constructor(e){super(),this.scope=e}generate(e){const{scope:t}=this,{renderer:n}=e;!0===n.backend.isWebGLBackend?e.addFlowCode(`\t// ${t}Barrier \n`):e.addLineFlowCode(`${t}Barrier()`,this)}});class DA extends Qf{static get type(){return"AtomicFunctionNode"}constructor(e,t,n){super("uint"),this.method=e,this.pointerNode=t,this.valueNode=n,this.parents=!0}getInputType(e){return this.pointerNode.getNodeType(e)}getNodeType(e){return this.getInputType(e)}generate(e){const t=e.getNodeProperties(this),n=t.parents,i=this.method,r=this.getNodeType(e),s=this.getInputType(e),a=this.pointerNode,o=this.valueNode,l=[];l.push(`&${a.build(e,s)}`),null!==o&&l.push(o.build(e,s));const u=`${e.getMethod(i,r)}( ${l.join(", ")} )`;if(!(!!n&&(1===n.length&&!0===n[0].isStackNode)))return void 0===t.constNode&&(t.constNode=My(u,r).toConst()),t.constNode.build(e);e.addLineFlowCode(u,this)}}DA.ATOMIC_LOAD="atomicLoad",DA.ATOMIC_STORE="atomicStore",DA.ATOMIC_ADD="atomicAdd",DA.ATOMIC_SUB="atomicSub",DA.ATOMIC_MAX="atomicMax",DA.ATOMIC_MIN="atomicMin",DA.ATOMIC_AND="atomicAnd",DA.ATOMIC_OR="atomicOr",DA.ATOMIC_XOR="atomicXor",Wm(DA);class IA extends tm{static get type(){return"SubgroupFunctionNode"}constructor(e,t=null,n=null){super(),this.method=e,this.aNode=t,this.bNode=n}getInputType(e){const t=this.aNode?this.aNode.getNodeType(e):null,n=this.bNode?this.bNode.getNodeType(e):null;return(e.isMatrix(t)?0:e.getTypeLength(t))>(e.isMatrix(n)?0:e.getTypeLength(n))?t:n}getNodeType(e){const t=this.method;return t===IA.SUBGROUP_ELECT?"bool":t===IA.SUBGROUP_BALLOT?"uvec4":this.getInputType(e)}generate(e,t){const n=this.method,i=this.getNodeType(e),r=this.getInputType(e),s=this.aNode,a=this.bNode,o=[];if(n===IA.SUBGROUP_BROADCAST||n===IA.SUBGROUP_SHUFFLE||n===IA.QUAD_BROADCAST){const t=a.getNodeType(e);o.push(s.build(e,i),a.build(e,"float"===t?"int":i))}else n===IA.SUBGROUP_SHUFFLE_XOR||n===IA.SUBGROUP_SHUFFLE_DOWN||n===IA.SUBGROUP_SHUFFLE_UP?o.push(s.build(e,i),a.build(e,"uint")):(null!==s&&o.push(s.build(e,r)),null!==a&&o.push(a.build(e,r)));const l=0===o.length?"()":`( ${o.join(", ")} )`;return e.format(`${e.getMethod(n,i)}${l}`,i,t)}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}let UA;function FA(e){UA=UA||new WeakMap;let t=UA.get(e);return void 0===t&&UA.set(e,t={}),t}function OA(e){const t=FA(e);return t.shadowMatrix||(t.shadowMatrix=a_("mat4").setGroup(i_).onRenderUpdate(t=>(!0===e.castShadow&&!1!==t.renderer.shadowMap.enabled||(e.shadow.camera.coordinateSystem!==t.camera.coordinateSystem&&(e.shadow.camera.coordinateSystem=t.camera.coordinateSystem,e.shadow.camera.updateProjectionMatrix()),e.shadow.updateMatrices(e)),e.shadow.matrix)))}function BA(e){const t=FA(e);return t.position||(t.position=a_(new dn).setGroup(i_).onRenderUpdate((t,n)=>n.value.setFromMatrixPosition(e.matrixWorld)))}function kA(e){const t=FA(e);return t.viewPosition||(t.viewPosition=a_(new dn).setGroup(i_).onRenderUpdate(({camera:t},n)=>{n.value=n.value||new dn,n.value.setFromMatrixPosition(e.matrixWorld),n.value.applyMatrix4(t.matrixWorldInverse)}))}IA.SUBGROUP_ELECT="subgroupElect",IA.SUBGROUP_BALLOT="subgroupBallot",IA.SUBGROUP_ADD="subgroupAdd",IA.SUBGROUP_INCLUSIVE_ADD="subgroupInclusiveAdd",IA.SUBGROUP_EXCLUSIVE_AND="subgroupExclusiveAdd",IA.SUBGROUP_MUL="subgroupMul",IA.SUBGROUP_INCLUSIVE_MUL="subgroupInclusiveMul",IA.SUBGROUP_EXCLUSIVE_MUL="subgroupExclusiveMul",IA.SUBGROUP_AND="subgroupAnd",IA.SUBGROUP_OR="subgroupOr",IA.SUBGROUP_XOR="subgroupXor",IA.SUBGROUP_MIN="subgroupMin",IA.SUBGROUP_MAX="subgroupMax",IA.SUBGROUP_ALL="subgroupAll",IA.SUBGROUP_ANY="subgroupAny",IA.SUBGROUP_BROADCAST_FIRST="subgroupBroadcastFirst",IA.QUAD_SWAP_X="quadSwapX",IA.QUAD_SWAP_Y="quadSwapY",IA.QUAD_SWAP_DIAGONAL="quadSwapDiagonal",IA.SUBGROUP_BROADCAST="subgroupBroadcast",IA.SUBGROUP_SHUFFLE="subgroupShuffle",IA.SUBGROUP_SHUFFLE_XOR="subgroupShuffleXor",IA.SUBGROUP_SHUFFLE_UP="subgroupShuffleUp",IA.SUBGROUP_SHUFFLE_DOWN="subgroupShuffleDown",IA.QUAD_BROADCAST="quadBroadcast";const zA=e=>gb.transformDirection(BA(e).sub(function(e){const t=FA(e);return t.targetPosition||(t.targetPosition=a_(new dn).setGroup(i_).onRenderUpdate((t,n)=>n.value.setFromMatrixPosition(e.target.matrixWorld)))}(e))),VA=(e,t)=>{for(const n of t)if(n.isAnalyticLightNode&&n.light.id===e)return n;return null},GA=new WeakMap,HA=[];class jA extends Qf{static get type(){return"LightsNode"}constructor(){super("vec3"),this.totalDiffuseNode=Tg("vec3","totalDiffuse"),this.totalSpecularNode=Tg("vec3","totalSpecular"),this.outgoingLightNode=Tg("vec3","outgoingLight"),this._lights=[],this._lightNodes=null,this._lightNodesHash=null,this.global=!0}customCacheKey(){const e=this._lights;for(let t=0;te.sort((e,t)=>e.id-t.id))(this._lights),r=e.renderer.library;for(const e of i)if(e.isNode)t.push(Vm(e));else{let i=null;if(null!==n&&(i=VA(e.id,n)),null===i){const n=r.getLightNodeClass(e.constructor);if(null===n){Xt(`LightsNode.setupNodeLights: Light node not found for ${e.constructor.name}`);continue}let i=null;GA.has(e)?i=GA.get(e):(i=new n(e),GA.set(e,i)),t.push(i)}}this._lightNodes=t}setupDirectLight(e,t,n){const{lightingModel:i,reflectedLight:r}=e.context;i.direct({...n,lightNode:t,reflectedLight:r},e)}setupDirectRectAreaLight(e,t,n){const{lightingModel:i,reflectedLight:r}=e.context;i.directRectArea({...n,lightNode:t,reflectedLight:r},e)}setupLights(e,t){for(const n of t)n.build(e)}getLightNodes(e){return null===this._lightNodes&&this.setupLightsNode(e),this._lightNodes}setup(e){const t=e.lightsNode;e.lightsNode=this;let n=this.outgoingLightNode;const i=e.context,r=i.lightingModel,s=e.getNodeProperties(this);if(r){const{totalDiffuseNode:t,totalSpecularNode:a}=this;i.outgoingLight=n;const o=e.addStack();s.nodes=o.nodes,r.start(e);const{backdrop:l,backdropAlpha:u}=i,{directDiffuse:c,directSpecular:h,indirectDiffuse:d,indirectSpecular:p}=i.reflectedLight;let f=c.add(d);null!==l&&(f=cg(null!==u?u.mix(f,l):l)),t.assign(f),a.assign(h.add(p)),n.assign(t.add(a)),r.finish(e),n=n.bypass(e.removeStack())}else s.nodes=[];return e.lightsNode=t,n}setLights(e){return this._lights=e,this._lightNodes=null,this._lightNodesHash=null,this}getLights(){return this._lights}get hasLights(){return this._lights.length>0}}class WA extends Qf{static get type(){return"ShadowBaseNode"}constructor(e){super(),this.light=e,this.updateBeforeType=Gf,this.isShadowBaseNode=!0}setupShadowPosition({context:e,material:t}){$A.assign(t.receivedShadowPositionNode||e.shadowPositionWorld||Pb)}}const $A=Tg("vec3","shadowPositionWorld");function XA(e,t){return t=function(e,t={}){return t.toneMapping=e.toneMapping,t.toneMappingExposure=e.toneMappingExposure,t.outputColorSpace=e.outputColorSpace,t.renderTarget=e.getRenderTarget(),t.activeCubeFace=e.getActiveCubeFace(),t.activeMipmapLevel=e.getActiveMipmapLevel(),t.renderObjectFunction=e.getRenderObjectFunction(),t.pixelRatio=e.getPixelRatio(),t.mrt=e.getMRT(),t.clearColor=e.getClearColor(t.clearColor||new _i),t.clearAlpha=e.getClearAlpha(),t.autoClear=e.autoClear,t.scissorTest=e.getScissorTest(),t}(e,t),e.setMRT(null),e.setRenderObjectFunction(null),e.setClearColor(0,1),e.autoClear=!0,t}const qA=new WeakMap,YA=Km(({depthTexture:e,shadowCoord:t,depthLayer:n})=>{let i=zy(e,t.xy).setName("t_basic");return e.isArrayTexture&&(i=i.depth(n)),i.compare(t.z)}),KA=Km(({depthTexture:e,shadowCoord:t,shadow:n,depthLayer:i})=>{const r=(t,n)=>{let r=zy(e,t);return e.isArrayTexture&&(r=r.depth(i)),r.compare(n)},s=ux("mapSize","vec2",n).setGroup(i_),a=ux("radius","float",n).setGroup(i_),o=ag(1).div(s),l=a.mul(o.x),u=nA(eb.xy).mul(6.28318530718);return d_(r(t.xy.add(iA(0,5,u).mul(l)),t.z),r(t.xy.add(iA(1,5,u).mul(l)),t.z),r(t.xy.add(iA(2,5,u).mul(l)),t.z),r(t.xy.add(iA(3,5,u).mul(l)),t.z),r(t.xy.add(iA(4,5,u).mul(l)),t.z)).mul(.2)}),ZA=Km(({depthTexture:e,shadowCoord:t,shadow:n,depthLayer:i})=>{const r=(t,n)=>{let r=zy(e,t);return e.isArrayTexture&&(r=r.depth(i)),r.compare(n)},s=ux("mapSize","vec2",n).setGroup(i_),a=ag(1).div(s),o=a.x,l=a.y,u=t.xy,c=J_(u.mul(s).add(.5));return u.subAssign(c.mul(a)),d_(r(u,t.z),r(u.add(ag(o,0)),t.z),r(u.add(ag(0,l)),t.z),r(u.add(a),t.z),Dv(r(u.add(ag(o.negate(),0)),t.z),r(u.add(ag(o.mul(2),0)),t.z),c.x),Dv(r(u.add(ag(o.negate(),l)),t.z),r(u.add(ag(o.mul(2),l)),t.z),c.x),Dv(r(u.add(ag(0,l.negate())),t.z),r(u.add(ag(0,l.mul(2))),t.z),c.y),Dv(r(u.add(ag(o,l.negate())),t.z),r(u.add(ag(o,l.mul(2))),t.z),c.y),Dv(Dv(r(u.add(ag(o.negate(),l.negate())),t.z),r(u.add(ag(o.mul(2),l.negate())),t.z),c.x),Dv(r(u.add(ag(o.negate(),l.mul(2))),t.z),r(u.add(ag(o.mul(2),l.mul(2))),t.z),c.x),c.y)).mul(1/9)}),QA=Km(({depthTexture:e,shadowCoord:t,depthLayer:n},i)=>{let r=zy(e).sample(t.xy);e.isArrayTexture&&(r=r.depth(n)),r=r.rg;const s=r.x,a=xv(1e-7,r.y.mul(r.y)),o=i.renderer.reversedDepthBuffer?Tv(s,t.z):Tv(t.z,s),l=ng(1).toVar();return Jm(o.notEqual(1),()=>{const e=t.z.sub(s);let n=a.div(a.add(e.mul(e)));n=Iv(p_(n,.3).div(.65)),l.assign(xv(o,n))}),l}),JA=new ow,eR=[],tR=Km(({samples:e,radius:t,size:n,shadowPass:i,depthLayer:r})=>{const s=ng(0).toVar("meanVertical"),a=ng(0).toVar("squareMeanVertical"),o=e.lessThanEqual(ng(1)).select(ng(0),ng(2).div(e.sub(1))),l=e.lessThanEqual(ng(1)).select(ng(0),ng(-1));GT({start:ig(0),end:ig(e),type:"int",condition:"<"},({i:e})=>{const u=l.add(ng(e).mul(o));let c=i.sample(d_(eb.xy,ag(0,u).mul(t)).div(n));i.value.isArrayTexture&&(c=c.depth(r)),c=c.x,s.addAssign(c),a.addAssign(c.mul(c))}),s.divAssign(e),a.divAssign(e);const u=q_(a.sub(s.mul(s)).max(0));return ag(s,u)}),nR=Km(({samples:e,radius:t,size:n,shadowPass:i,depthLayer:r})=>{const s=ng(0).toVar("meanHorizontal"),a=ng(0).toVar("squareMeanHorizontal"),o=e.lessThanEqual(ng(1)).select(ng(0),ng(2).div(e.sub(1))),l=e.lessThanEqual(ng(1)).select(ng(0),ng(-1));GT({start:ig(0),end:ig(e),type:"int",condition:"<"},({i:e})=>{const u=l.add(ng(e).mul(o));let c=i.sample(d_(eb.xy,ag(u,0).mul(t)).div(n));i.value.isArrayTexture&&(c=c.depth(r)),s.addAssign(c.x),a.addAssign(d_(c.y.mul(c.y),c.x.mul(c.x)))}),s.divAssign(e),a.divAssign(e);const u=q_(a.sub(s.mul(s)).max(0));return ag(s,u)}),iR=[YA,KA,ZA,QA];let rR;const sR=new tA;class aR extends WA{static get type(){return"ShadowNode"}constructor(e,t=null){super(e),this.shadow=t||e.shadow,this.shadowMap=null,this.vsmShadowMapVertical=null,this.vsmShadowMapHorizontal=null,this.vsmMaterialVertical=null,this.vsmMaterialHorizontal=null,this._node=null,this._currentShadowType=null,this._cameraFrameId=new WeakMap,this.isShadowNode=!0,this.depthLayer=0}setupShadowFilter(e,{filterFn:t,depthTexture:n,shadowCoord:i,shadow:r,depthLayer:s}){const a=i.x.greaterThanEqual(0).and(i.x.lessThanEqual(1)).and(i.y.greaterThanEqual(0)).and(i.y.lessThanEqual(1)).and(i.z.lessThanEqual(1)),o=t({depthTexture:n,shadowCoord:i,shadow:r,depthLayer:s});return a.select(o,ng(1))}setupShadowCoord(e,t){const{shadow:n}=this,{renderer:i}=e,r=n.biasNode||ux("bias","float",n).setGroup(i_);let s,a=t;if(n.camera.isOrthographicCamera||!0!==i.logarithmicDepthBuffer)a=a.xyz.div(a.w),s=a.z;else{const e=a.w;a=a.xy.div(e);const t=ux("near","float",n.camera).setGroup(i_),i=ux("far","float",n.camera).setGroup(i_);s=hS(e.negate(),t,i)}return a=cg(a.x,a.y.oneMinus(),i.reversedDepthBuffer?s.sub(r):s.add(r)),a}getShadowFilterFn(e){return iR[e]}setupRenderTarget(e,t){const n=new vs(e.mapSize.width,e.mapSize.height);n.name="ShadowDepthTexture",n.compareFunction=t.renderer.reversedDepthBuffer?Pt:Rt;const i=t.createRenderTarget(e.mapSize.width,e.mapSize.height);return i.texture.name="ShadowMap",i.texture.type=e.mapType,i.depthTexture=n,{shadowMap:i,depthTexture:n}}setupShadow(e){const{renderer:t,camera:n}=e,{light:i,shadow:r}=this,{depthTexture:s,shadowMap:a}=this.setupRenderTarget(r,e),o=t.shadowMap.type,l=t.hasCompatibility(zt);if(1!==o&&2!==o||!l?(s.minFilter=le,s.magFilter=le):(s.minFilter=he,s.magFilter=he),r.camera.coordinateSystem=n.coordinateSystem,r.camera.updateProjectionMatrix(),3===o&&!0!==r.isPointLightShadow){s.compareFunction=null,a.depth>1?(a._vsmShadowMapVertical||(a._vsmShadowMapVertical=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:Ie,type:xe,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapVertical.texture.name="VSMVertical"),this.vsmShadowMapVertical=a._vsmShadowMapVertical,a._vsmShadowMapHorizontal||(a._vsmShadowMapHorizontal=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:Ie,type:xe,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapHorizontal.texture.name="VSMHorizontal"),this.vsmShadowMapHorizontal=a._vsmShadowMapHorizontal):(this.vsmShadowMapVertical=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:Ie,type:xe,depthBuffer:!1}),this.vsmShadowMapHorizontal=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:Ie,type:xe,depthBuffer:!1}));let t=zy(s);s.isArrayTexture&&(t=t.depth(this.depthLayer));let n=zy(this.vsmShadowMapVertical.texture);s.isArrayTexture&&(n=n.depth(this.depthLayer));const i=ux("blurSamples","float",r).setGroup(i_),o=ux("radius","float",r).setGroup(i_),l=ux("mapSize","vec2",r).setGroup(i_);let u=this.vsmMaterialVertical||(this.vsmMaterialVertical=new bS);u.fragmentNode=tR({samples:i,radius:o,size:l,shadowPass:t,depthLayer:this.depthLayer}).context(e.getSharedContext()),u.name="VSMVertical",u=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new bS),u.fragmentNode=nR({samples:i,radius:o,size:l,shadowPass:n,depthLayer:this.depthLayer}).context(e.getSharedContext()),u.name="VSMHorizontal"}const u=ux("intensity","float",r).setGroup(i_),c=ux("normalBias","float",r).setGroup(i_),h=OA(i).mul($A.add(jb.mul(c))),d=this.setupShadowCoord(e,h),p=r.filterNode||this.getShadowFilterFn(t.shadowMap.type)||null;if(null===p)throw new Error("THREE.WebGPURenderer: Shadow map type not supported yet.");const f=3===o&&!0!==r.isPointLightShadow?this.vsmShadowMapHorizontal.texture:s,m=this.setupShadowFilter(e,{filterFn:p,shadowTexture:a.texture,depthTexture:f,shadowCoord:d,shadow:r,depthLayer:this.depthLayer});let g,_;!0===t.shadowMap.transmitted&&(a.texture.isCubeTexture?g=ax(a.texture,d.xyz):(g=zy(a.texture,d),s.isArrayTexture&&(g=g.depth(this.depthLayer)))),_=g?Dv(1,m.rgb.mix(g,1),u.mul(g.a)).toVar():Dv(1,m,u).toVar(),this.shadowMap=a,this.shadow.map=a;const v=`${this.light.type} Shadow [ ${this.light.name||"ID: "+this.light.id} ]`;return g&&_.toInspector(`${v} / Color`,()=>this.shadowMap.texture.isCubeTexture?ax(this.shadowMap.texture):zy(this.shadowMap.texture)),_.toInspector(`${v} / Depth`,()=>this.shadowMap.texture.isCubeTexture?ax(this.shadowMap.texture).r.oneMinus():Vy(this.shadowMap.depthTexture,Py().mul(Dy(zy(this.shadowMap.depthTexture)))).r.oneMinus())}setup(e){if(!1!==e.renderer.shadowMap.enabled)return Km(()=>{const t=e.renderer.shadowMap.type;this._currentShadowType!==t&&(this._reset(),this._node=null);let n=this._node;return this.setupShadowPosition(e),null===n&&(this._node=n=this.setupShadow(e),this._currentShadowType=t),e.material.receivedShadowNode&&(n=e.material.receivedShadowNode(n)),n})()}renderShadow(e){const{shadow:t,shadowMap:n,light:i}=this,{renderer:r,scene:s}=e;t.updateMatrices(i),n.setSize(t.mapSize.width,t.mapSize.height,n.depth);const a=s.name;s.name=`Shadow Map [ ${i.name||"ID: "+i.id} ]`,r.render(s,t.camera),s.name=a}updateShadow(e){const{shadowMap:t,light:n,shadow:i}=this,{renderer:r,scene:s,camera:a}=e,o=r.shadowMap.type,l=t.depthTexture.version;this._depthVersionCached=l;const u=i.camera.layers.mask;4294967294&i.camera.layers.mask||(i.camera.layers.mask=a.layers.mask);const c=r.getRenderObjectFunction(),h=r.getMRT(),d=!!h&&h.has("velocity");rR=function(e,t,n){return n=function(e,t){return t=function(e,t={}){return t.background=e.background,t.backgroundNode=e.backgroundNode,t.overrideMaterial=e.overrideMaterial,t}(e,t),e.background=null,e.backgroundNode=null,e.overrideMaterial=null,t}(t,n=XA(e,n)),n}(r,s,rR),s.overrideMaterial=(e=>{let t=qA.get(e);return void 0===t&&(t=new bS,t.colorNode=fg(0,0,0,1),t.isShadowPassMaterial=!0,t.name="ShadowMaterial",t.blending=0,t.fog=!1,qA.set(e,t)),t})(n),r.setRenderObjectFunction(((e,t,n,i)=>{eR[0]=e,eR[1]=t;let r=JA.get(eR);return void 0!==r&&r.shadowType===n&&r.useVelocity===i||(r=(r,s,a,o,l,u,...c)=>{(!0===r.castShadow||r.receiveShadow&&3===n)&&(i&&(Bf(r).useVelocity=!0),r.onBeforeShadow(e,r,a,t.camera,o,s.overrideMaterial,u),e.renderObject(r,s,a,o,l,u,...c),r.onAfterShadow(e,r,a,t.camera,o,s.overrideMaterial,u))},r.shadowType=n,r.useVelocity=i,JA.set(eR,r)),eR[0]=null,eR[1]=null,r})(r,i,o,d)),r.setClearColor(0,0),r.setRenderTarget(t),this.renderShadow(e),r.setRenderObjectFunction(c),3===o&&!0!==i.isPointLightShadow&&this.vsmPass(r),i.camera.layers.mask=u,function(e,t,n){!function(e,t){e.toneMapping=t.toneMapping,e.toneMappingExposure=t.toneMappingExposure,e.outputColorSpace=t.outputColorSpace,e.setRenderTarget(t.renderTarget,t.activeCubeFace,t.activeMipmapLevel),e.setRenderObjectFunction(t.renderObjectFunction),e.setPixelRatio(t.pixelRatio),e.setMRT(t.mrt),e.setClearColor(t.clearColor,t.clearAlpha),e.autoClear=t.autoClear,e.setScissorTest(t.scissorTest)}(e,n),function(e,t){e.background=t.background,e.backgroundNode=t.backgroundNode,e.overrideMaterial=t.overrideMaterial}(t,n)}(r,s,rR)}vsmPass(e){const{shadow:t}=this,n=this.shadowMap.depth;this.vsmShadowMapVertical.setSize(t.mapSize.width,t.mapSize.height,n),this.vsmShadowMapHorizontal.setSize(t.mapSize.width,t.mapSize.height,n),e.setRenderTarget(this.vsmShadowMapVertical),sR.material=this.vsmMaterialVertical,sR.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),sR.material=this.vsmMaterialHorizontal,sR.render(e)}dispose(){this._reset(),super.dispose()}_reset(){this._currentShadowType=null,(e=>{const t=qA.get(e);void 0!==t&&(t.dispose(),qA.delete(e))})(this.light),this.shadowMap&&(this.shadowMap.dispose(),this.shadowMap=null),null!==this.vsmShadowMapVertical&&(this.vsmShadowMapVertical.dispose(),this.vsmShadowMapVertical=null,this.vsmMaterialVertical.dispose(),this.vsmMaterialVertical=null),null!==this.vsmShadowMapHorizontal&&(this.vsmShadowMapHorizontal.dispose(),this.vsmShadowMapHorizontal=null,this.vsmMaterialHorizontal.dispose(),this.vsmMaterialHorizontal=null)}updateBefore(e){const{shadow:t}=this;let n=t.needsUpdate||t.autoUpdate;n&&(this._cameraFrameId[e.camera]===e.frameId&&(n=!1),this._cameraFrameId[e.camera]=e.frameId),n&&(this.updateShadow(e),this.shadowMap.depthTexture.version===this._depthVersionCached&&(t.needsUpdate=!1))}}const oR=new _i,lR=new Fn,uR=new dn,cR=new dn,hR=[new dn(1,0,0),new dn(-1,0,0),new dn(0,-1,0),new dn(0,1,0),new dn(0,0,1),new dn(0,0,-1)],dR=[new dn(0,-1,0),new dn(0,-1,0),new dn(0,0,-1),new dn(0,0,1),new dn(0,-1,0),new dn(0,-1,0)],pR=[new dn(1,0,0),new dn(-1,0,0),new dn(0,1,0),new dn(0,-1,0),new dn(0,0,1),new dn(0,0,-1)],fR=[new dn(0,-1,0),new dn(0,-1,0),new dn(0,0,1),new dn(0,0,-1),new dn(0,-1,0),new dn(0,-1,0)],mR=Km(({depthTexture:e,bd3D:t,dp:n})=>ax(e,t).compare(n)),gR=Km(({depthTexture:e,bd3D:t,dp:n,shadow:i})=>{const r=ux("radius","float",i).setGroup(i_),s=ux("mapSize","vec2",i).setGroup(i_),a=r.div(s.x),o=av(t),l=Q_(Av(t,o.x.greaterThan(o.z).select(cg(0,1,0),cg(1,0,0)))),u=Av(t,l),c=nA(eb.xy).mul(6.28318530718),h=iA(0,5,c),d=iA(1,5,c),p=iA(2,5,c),f=iA(3,5,c),m=iA(4,5,c);return ax(e,t.add(l.mul(h.x).add(u.mul(h.y)).mul(a))).compare(n).add(ax(e,t.add(l.mul(d.x).add(u.mul(d.y)).mul(a))).compare(n)).add(ax(e,t.add(l.mul(p.x).add(u.mul(p.y)).mul(a))).compare(n)).add(ax(e,t.add(l.mul(f.x).add(u.mul(f.y)).mul(a))).compare(n)).add(ax(e,t.add(l.mul(m.x).add(u.mul(m.y)).mul(a))).compare(n)).mul(.2)}),_R=Km(({filterFn:e,depthTexture:t,shadowCoord:n,shadow:i},r)=>{const s=n.xyz.toConst(),a=s.abs().toConst(),o=a.x.max(a.y).max(a.z),l=a_("float").setGroup(i_).onRenderUpdate(()=>i.camera.near),u=a_("float").setGroup(i_).onRenderUpdate(()=>i.camera.far),c=ux("bias","float",i).setGroup(i_),h=ng(1).toVar();return Jm(o.sub(u).lessThanEqual(0).and(o.sub(l).greaterThanEqual(0)),()=>{let n;r.renderer.reversedDepthBuffer?(n=((e,t,n)=>t.mul(e.add(n)).div(e.mul(t.sub(n))))(o.negate(),l,u),n.subAssign(c)):(n=uS(o.negate(),l,u),n.addAssign(c));const a=s.normalize();h.assign(e({depthTexture:t,bd3D:a,dp:n,shadow:i}))}),h});class vR extends aR{static get type(){return"PointShadowNode"}constructor(e,t=null){super(e,t)}getShadowFilterFn(e){return 0===e?mR:gR}setupShadowCoord(e,t){return t}setupShadowFilter(e,{filterFn:t,depthTexture:n,shadowCoord:i,shadow:r}){return _R({filterFn:t,depthTexture:n,shadowCoord:i,shadow:r})}setupRenderTarget(e,t){const n=new ys(e.mapSize.width);n.name="PointShadowDepthTexture",n.compareFunction=t.renderer.reversedDepthBuffer?Pt:Rt;const i=t.createCubeRenderTarget(e.mapSize.width);return i.texture.name="PointShadowMap",i.depthTexture=n,{shadowMap:i,depthTexture:n}}renderShadow(e){const{shadow:t,shadowMap:n,light:i}=this,{renderer:r,scene:s}=e,a=t.camera,o=t.matrix,l=r.coordinateSystem===Ot,u=l?hR:pR,c=l?dR:fR;n.setSize(t.mapSize.width,t.mapSize.width);const h=r.autoClear,d=r.getClearColor(oR),p=r.getClearAlpha();r.autoClear=!1,r.setClearColor(t.clearColor,t.clearAlpha);for(let e=0;e<6;e++){r.setRenderTarget(n,e),r.clear();const l=i.distance||a.far;l!==a.far&&(a.far=l,a.updateProjectionMatrix()),uR.setFromMatrixPosition(i.matrixWorld),a.position.copy(uR),cR.copy(a.position),cR.add(u[e]),a.up.copy(c[e]),a.lookAt(cR),a.updateMatrixWorld(),o.makeTranslation(-uR.x,-uR.y,-uR.z),lR.multiplyMatrices(a.projectionMatrix,a.matrixWorldInverse),t._frustum.setFromProjectionMatrix(lR,a.coordinateSystem,a.reversedDepth);const h=s.name;s.name=`Point Light Shadow [ ${i.name||"ID: "+i.id} ] - Face ${e+1}`,r.render(s,a),s.name=h}r.autoClear=h,r.setClearColor(d,p)}}class yR extends qT{static get type(){return"AnalyticLightNode"}constructor(e=null){super(),this.light=e,this.color=new _i,this.colorNode=e&&e.colorNode||a_(this.color).setGroup(i_),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0,this.updateType=Vf,e&&e.shadow&&(this._shadowDisposeListener=()=>{this.disposeShadow()},e.addEventListener("dispose",this._shadowDisposeListener))}dispose(){this._shadowDisposeListener&&this.light.removeEventListener("dispose",this._shadowDisposeListener),super.dispose()}disposeShadow(){null!==this.shadowNode&&(this.shadowNode.dispose(),this.shadowNode=null),this.shadowColorNode=null,null!==this.baseColorNode&&(this.colorNode=this.baseColorNode,this.baseColorNode=null)}getHash(){return this.light.uuid}getLightVector(e){return kA(this.light).sub(e.context.positionView||Db)}setupDirect(){}setupDirectRectArea(){}setupShadowNode(){return((e,t)=>new aR(e,t))(this.light)}setupShadow(e){const{renderer:t}=e;if(!1===t.shadowMap.enabled)return;let n=this.shadowColorNode;if(null===n){const e=this.light.shadow.shadowNode;let t;t=void 0!==e?Vm(e):this.setupShadowNode(),this.shadowNode=t,this.shadowColorNode=n=this.colorNode.mul(t),this.baseColorNode=this.colorNode}e.context.getShadow&&(n=e.context.getShadow(this,e)),this.colorNode=n}setup(e){this.colorNode=this.baseColorNode||this.colorNode,this.light.castShadow?e.object.receiveShadow&&this.setupShadow(e):null!==this.shadowNode&&(this.shadowNode.dispose(),this.shadowNode=null,this.shadowColorNode=null);const t=this.setupDirect(e),n=this.setupDirectRectArea(e);t&&e.lightsNode.setupDirectLight(e,this,t),n&&e.lightsNode.setupDirectRectAreaLight(e,this,n)}update(){const{light:e}=this;this.color.copy(e.color).multiplyScalar(e.intensity)}}const bR=Km(({lightDistance:e,cutoffDistance:t,decayExponent:n})=>{const i=e.pow(n).max(.01).reciprocal();return t.greaterThan(0).select(i.mul(e.div(t).pow4().oneMinus().clamp().pow2()),i)});class xR extends yR{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=a_(0).setGroup(i_),this.decayExponentNode=a_(2).setGroup(i_)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setupShadowNode(){return((e,t)=>new vR(e,t))(this.light)}setupDirect(e){return(({color:e,lightVector:t,cutoffDistance:n,decayExponent:i})=>{const r=t.normalize(),s=t.length(),a=bR({lightDistance:s,cutoffDistance:n,decayExponent:i});return{lightDirection:r,lightColor:e.mul(a)}})({color:this.colorNode,lightVector:this.getLightVector(e),cutoffDistance:this.cutoffDistanceNode,decayExponent:this.decayExponentNode})}}Km(([e=Py()],{renderer:t,material:n})=>{const i=Lv(e.mul(2).sub(1));let r;if(n.alphaToCoverage&&t.currentSamples>0){const e=ng(i.fwidth()).toVar();r=Ov(e.oneMinus(),e.add(1),i).oneMinus()}else r=Vv(i.greaterThan(1),0,1);return r});const TR=Km(([e,t])=>{const n=e.x,i=e.y,r=e.z;let s=t.element(0).mul(.886227);return s=s.add(t.element(1).mul(1.023328).mul(i)),s=s.add(t.element(2).mul(1.023328).mul(r)),s=s.add(t.element(3).mul(1.023328).mul(n)),s=s.add(t.element(4).mul(.858086).mul(n).mul(i)),s=s.add(t.element(5).mul(.858086).mul(i).mul(r)),s=s.add(t.element(6).mul(r.mul(r).mul(.743125).sub(.247708))),s=s.add(t.element(7).mul(.858086).mul(n).mul(r)),s=s.add(t.element(8).mul(.429043).mul(f_(n,n).sub(f_(i,i)))),s}),SR=new Hw;class MR extends dw{constructor(e,t){super(),this.renderer=e,this.nodes=t}update(e,t,n){const i=this.renderer,r=this.nodes.getBackgroundNode(e)||e.background;let s=!1;if(null===r)i._clearColor.getRGB(SR),SR.a=i._clearColor.a;else if(!0===r.isColor)r.getRGB(SR),SR.a=1,s=!0;else if(!0===r.isNode){const o=this.get(e),l=r;SR.copy(i._clearColor);let u=o.backgroundMesh;if(void 0===u){const h=fg(l).mul(lA).context({getUV:()=>uA.mul(Gb),getTextureLevel:()=>oA}),d=fb.element(3).element(3).equal(1),p=m_(1,fb.element(1).element(1)).mul(3),f=d.select(Cb.mul(p),Cb),m=Sb.mul(fg(f,0));let g=fb.mul(fg(m.xyz,1));g=g.setZ(g.w);const _=new bS;function v(){r.removeEventListener("dispose",v),u.material.dispose(),u.geometry.dispose()}_.name="Background.material",_.side=1,_.depthTest=!1,_.depthWrite=!1,_.allowOverride=!1,_.fog=!1,_.lights=!1,_.vertexNode=g,_.colorNode=h,o.backgroundMeshNode=h,o.backgroundMesh=u=new Wr(new Bs(1,32,32),_),u.frustumCulled=!1,u.name="Background.mesh",r.addEventListener("dispose",v)}const c=l.getCacheKey();o.backgroundCacheKey!==c&&(o.backgroundMeshNode.node=fg(l).mul(lA),o.backgroundMeshNode.needsUpdate=!0,u.material.needsUpdate=!0,o.backgroundCacheKey=c),t.unshift(u,u.geometry,u.material,0,0,null,null)}else qt("Renderer: Unsupported background configuration.",r);const a=i.xr.getEnvironmentBlendMode();if("additive"===a?SR.set(0,0,0,1):"alpha-blend"===a&&SR.set(0,0,0,0),!0===i.autoClear||!0===s){const y=n.clearColorValue;y.r=SR.r,y.g=SR.g,y.b=SR.b,y.a=SR.a,!0!==i.backend.isWebGLBackend&&!0!==i.alpha||(y.r*=y.a,y.g*=y.a,y.b*=y.a),n.depthClearValue=i.getClearDepth(),n.stencilClearValue=i.getClearStencil(),n.clearColor=!0===i.autoClearColor,n.clearDepth=!0===i.autoClearDepth,n.clearStencil=!0===i.autoClearStencil}else n.clearColor=!1,n.clearDepth=!1,n.clearStencil=!1}}let ER=0;class wR{constructor(e="",t=[],n=0){this.name=e,this.bindings=t,this.index=n,this.id=ER++}}class AR{constructor(e,t,n,i,r,s,a,o,l,u=[]){this.vertexShader=e,this.fragmentShader=t,this.computeShader=n,this.transforms=u,this.nodeAttributes=i,this.bindings=r,this.updateNodes=s,this.updateBeforeNodes=a,this.updateAfterNodes=o,this.observer=l,this.usedTimes=0}createBindings(){const e=[];for(const t of this.bindings){if(!0!==t.bindings[0].groupNode.shared){const n=new wR(t.name,[],t.index);e.push(n);for(const e of t.bindings)n.bindings.push(e.clone())}else e.push(t)}return e}}class RR{constructor(e,t,n=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=n}}class CR{constructor(e,t,n){this.isNodeUniform=!0,this.name=e,this.type=t,this.node=n}get value(){return this.node.value}set value(e){this.node.value=e}get id(){return this.node.id}get groupNode(){return this.node.groupNode}}class NR{constructor(e,t,n=!1,i=null){this.isNodeVar=!0,this.name=e,this.type=t,this.readOnly=n,this.count=i}}class PR extends NR{constructor(e,t,n=null,i=null){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0,this.interpolationType=n,this.interpolationSampling=i}}class LR{constructor(e,t,n=""){this.name=e,this.type=t,this.code=n,Object.defineProperty(this,"isNodeCode",{value:!0})}}let DR=0;class IR{constructor(e=null){this.id=DR++,this.nodesData=new WeakMap,this.parent=e}getData(e){let t=this.nodesData.get(e);return void 0===t&&null!==this.parent&&(t=this.parent.getData(e)),t}setData(e,t){this.nodesData.set(e,t)}}class UR{constructor(e,t){this.name=e,this.members=t,this.output=!1}}class FR{constructor(e,t){this.name=e,this.value=t,this.boundary=0,this.itemSize=0,this.offset=0,this.index=-1}setValue(e){this.value=e}getValue(){return this.value}}class OR extends FR{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}}class BR extends FR{constructor(e,t=new cn){super(e,t),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class kR extends FR{constructor(e,t=new dn){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class zR extends FR{constructor(e,t=new Pn){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class VR extends FR{constructor(e,t=new _i){super(e,t),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class GR extends FR{constructor(e,t=new $a){super(e,t),this.isMatrix2Uniform=!0,this.boundary=8,this.itemSize=4}}class HR extends FR{constructor(e,t=new mn){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class jR extends FR{constructor(e,t=new Fn){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class WR extends OR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class $R extends BR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class XR extends kR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class qR extends zR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class YR extends VR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class KR extends GR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class ZR extends HR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class QR extends jR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}let JR=0;const eC=new WeakMap,tC=new WeakMap,nC=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),iC=e=>/e/g.test(e)?String(e).replace(/\+/g,""):(e=Number(e))+(e%1?"":".0");class rC{constructor(e,t,n){this.object=e,this.material=e&&e.material||null,this.geometry=e&&e.geometry||null,this.renderer=t,this.parser=n,this.scene=null,this.camera=null,this.nodes=[],this.sequentialNodes=[],this.updateNodes=[],this.updateBeforeNodes=[],this.updateAfterNodes=[],this.hashNodes={},this.observer=null,this.lightsNode=null,this.environmentNode=null,this.fogNode=null,this.clippingContext=null,this.vertexShader=null,this.fragmentShader=null,this.computeShader=null,this.flowNodes={vertex:[],fragment:[],compute:[]},this.flowCode={vertex:"",fragment:"",compute:""},this.uniforms={vertex:[],fragment:[],compute:[],index:0},this.structs={vertex:[],fragment:[],compute:[],index:0},this.types={vertex:[],fragment:[],compute:[],index:0},this.bindings={vertex:{},fragment:{},compute:{}},this.bindingsIndexes={},this.bindGroups=null,this.attributes=[],this.bufferAttributes=[],this.varyings=[],this.codes={},this.vars={},this.declarations={},this.flow={code:""},this.chaining=[],this.stack=$w(),this.stacks=[],this.tab="\t",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new IR,this.globalCache=this.cache,this.flowsData=new WeakMap,this.shaderStage=null,this.buildStage=null,this.subBuildLayers=[],this.activeStacks=[],this.subBuildFn=null,this.fnCall=null,Object.defineProperty(this,"id",{value:JR++})}isFlatShading(){return!0===this.material.flatShading||!1===this.geometry.hasAttribute("normal")}isOpaque(){const e=this.material;return!1===e.transparent&&1===e.blending&&!1===e.alphaToCoverage}createRenderTarget(e,t,n){return new Ln(e,t,n)}createCubeRenderTarget(e,t){return new RS(e,t)}includes(e){return this.nodes.includes(e)}getOutputStructName(){}_getBindGroup(e,t){const n=t[0].groupNode;let i,r=n.shared;if(r)for(let e=1;ee.nodeUniform.node.id-t.nodeUniform.node.id);for(const t of e.uniforms)n+=t.nodeUniform.node.id}else n+=e.nodeUniform.id;const r=this.renderer._currentRenderContext||this.renderer;let s=eC.get(r);void 0===s&&(s=new Map,eC.set(r,s));const a=Nf(n);i=s.get(a),void 0===i&&(i=new wR(e,t,this.bindingsIndexes[e].group),s.set(a,i))}else i=new wR(e,t,this.bindingsIndexes[e].group);return i}getBindGroupArray(e,t){const n=this.bindings[t];let i=n[e];return void 0===i&&(void 0===this.bindingsIndexes[e]&&(this.bindingsIndexes[e]={binding:0,group:Object.keys(this.bindingsIndexes).length}),n[e]=i=[]),i}getBindings(){let e=this.bindGroups;if(null===e){const t={},n=this.bindings;for(const e of qf)for(const i in n[e]){const r=n[e][i],s=t[i]||(t[i]=[]);for(const e of r)!1===s.includes(e)&&s.push(e)}e=[];for(const n in t){const i=t[n],r=this._getBindGroup(n,i);e.push(r)}this.bindGroups=e}return e}sortBindingGroups(){const e=this.getBindings();e.sort((e,t)=>e.bindings[0].groupNode.order-t.bindings[0].groupNode.order);for(let t=0;t=0?`${Math.round(t)}u`:"0u";if("bool"===e)return t?"true":"false";if("color"===e)return`${this.getType("vec3")}( ${iC(t.r)}, ${iC(t.g)}, ${iC(t.b)} )`;const n=this.getTypeLength(e),i=this.getComponentType(e),r=e=>this.generateConst(i,e);if(2===n)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)} )`;if(3===n)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)}, ${r(t.z)} )`;if(4===n&&"mat2"!==e)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)}, ${r(t.z)}, ${r(t.w)} )`;if(n>=4&&t&&(t.isMatrix2||t.isMatrix3||t.isMatrix4))return`${this.getType(e)}( ${t.elements.map(r).join(", ")} )`;if(n>4)return`${this.getType(e)}()`;throw new Error(`NodeBuilder: Type '${e}' not found in generate constant attempt.`)}getType(e){return"color"===e?"vec3":e}hasGeometryAttribute(e){return this.geometry&&void 0!==this.geometry.getAttribute(e)}getAttribute(e,t){const n=this.attributes;for(const t of n)if(t.name===e)return t;const i=new RR(e,t);return this.registerDeclaration(i),n.push(i),i}getPropertyName(e){return e.name}isVector(e){return/vec\d/.test(e)}isMatrix(e){return/mat\d/.test(e)}isReference(e){return"void"===e||"property"===e||"sampler"===e||"samplerComparison"===e||"texture"===e||"cubeTexture"===e||"storageTexture"===e||"depthTexture"===e||"texture3D"===e}needsToWorkingColorSpace(){return!1}getComponentTypeFromTexture(e){const t=e.type;if(e.isDataTexture){if(t===ve)return"int";if(t===ye)return"uint"}return"float"}getElementType(e){return"mat2"===e?"vec2":"mat3"===e?"vec3":"mat4"===e?"vec4":this.getComponentType(e)}getComponentType(e){if("float"===(e=this.getVectorType(e))||"bool"===e||"int"===e||"uint"===e)return e;const t=/(b|i|u|)(vec|mat)([2-4])/.exec(e);return null===t?null:"b"===t[1]?"bool":"i"===t[1]?"int":"u"===t[1]?"uint":"float"}getVectorType(e){return"color"===e?"vec3":"texture"===e||"cubeTexture"===e||"storageTexture"===e||"texture3D"===e?"vec4":e}getTypeFromLength(e,t="float"){if(1===e)return t;let n=Uf(e);const i="float"===t?"":t[0];return!0===/mat2/.test(t)&&(n=n.replace("vec","mat")),i+n}getTypeFromArray(e){return nC.get(e.constructor)}isInteger(e){return/int|uint|(i|u)vec/.test(e)}getTypeFromAttribute(e){let t=e;e.isInterleavedBufferAttribute&&(t=e.data);const n=t.array,i=e.itemSize,r=e.normalized;let s;return e instanceof sr||!0===r||(s=this.getTypeFromArray(n)),this.getTypeFromLength(i,s)}getTypeLength(e){const t=this.getVectorType(e),n=/vec([2-4])/.exec(t);return null!==n?Number(n[1]):"float"===t||"bool"===t||"int"===t||"uint"===t?1:!0===/mat2/.test(e)?4:!0===/mat3/.test(e)?9:!0===/mat4/.test(e)?16:0}getVectorFromMatrix(e){return e.replace("mat","vec")}changeComponentType(e,t){return this.getTypeFromLength(this.getTypeLength(e),t)}getIntegerType(e){const t=this.getComponentType(e);return"int"===t||"uint"===t?e:this.changeComponentType(e,"int")}setActiveStack(e){this.activeStacks.push(e)}removeActiveStack(e){if(this.activeStacks[this.activeStacks.length-1]!==e)throw new Error("NodeBuilder: Invalid active stack removal.");this.activeStacks.pop()}getActiveStack(){return this.activeStacks[this.activeStacks.length-1]}getBaseStack(){return this.activeStacks[0]}addStack(){this.stack=$w(this.stack);const e=Qm();return this.stacks.push(e),Zm(this.stack),this.stack}removeStack(){const e=this.stack;for(const t of e.nodes){this.getDataFromNode(t).stack=e}return this.stack=e.parent,Zm(this.stacks.pop()),e}getDataFromNode(e,t=this.shaderStage,n=null){let i=(n=null===n?e.isGlobal(this)?this.globalCache:this.cache:n).getData(e);void 0===i&&(i={},n.setData(e,i)),void 0===i[t]&&(i[t]={});let r=i[t];const s=i.any?i.any.subBuilds:null,a=this.getClosestSubBuild(s);return a&&(void 0===r.subBuildsCache&&(r.subBuildsCache={}),r=r.subBuildsCache[a]||(r.subBuildsCache[a]={}),r.subBuilds=s),r}getNodeProperties(e,t="any"){const n=this.getDataFromNode(e,t);return n.properties||(n.properties={outputNode:null})}getBufferAttributeFromNode(e,t){const n=this.getDataFromNode(e,"vertex");let i=n.bufferAttribute;if(void 0===i){const r=this.uniforms.index++;i=new RR("nodeAttribute"+r,t,e),this.bufferAttributes.push(i),n.bufferAttribute=i}return i}getStructTypeNode(e,t=this.shaderStage){return this.types[t][e]||null}getStructTypeFromNode(e,t,n=null,i=this.shaderStage){const r=this.getDataFromNode(e,i,this.globalCache);let s=r.structType;if(void 0===s){const a=this.structs.index++;null===n&&(n="StructType"+a),s=new UR(n,t),this.structs[i].push(s),this.types[i][n]=e,r.structType=s}return s}getOutputStructTypeFromNode(e,t){const n=this.getStructTypeFromNode(e,t,"OutputType","fragment");return n.output=!0,n}getUniformFromNode(e,t,n=this.shaderStage,i=null){const r=this.getDataFromNode(e,n,this.globalCache);let s=r.uniform;if(void 0===s){const a=this.uniforms.index++;s=new CR(i||"nodeUniform"+a,t,e),this.uniforms[n].push(s),this.registerDeclaration(s),r.uniform=s}return s}getVarFromNode(e,t=null,n=e.getNodeType(this),i=this.shaderStage,r=!1){const s=this.getDataFromNode(e,i),a=this.getSubBuildProperty("variable",s.subBuilds);let o=s[a];if(void 0===o){const l=r?"_const":"_var",u=this.vars[i]||(this.vars[i]=[]),c=this.vars[l]||(this.vars[l]=0);null===t&&(t=(r?"nodeConst":"nodeVar")+c,this.vars[l]++),"variable"!==a&&(t=this.getSubBuildProperty(t,s.subBuilds));const h=e.getArrayCount(this);o=new NR(t,n,r,h),r||u.push(o),this.registerDeclaration(o),s[a]=o}return o}isDeterministic(e){if(e.isMathNode)return this.isDeterministic(e.aNode)&&(!e.bNode||this.isDeterministic(e.bNode))&&(!e.cNode||this.isDeterministic(e.cNode));if(e.isOperatorNode)return this.isDeterministic(e.aNode)&&(!e.bNode||this.isDeterministic(e.bNode));if(e.isArrayNode){if(null!==e.values)for(const t of e.values)if(!this.isDeterministic(t))return!1;return!0}return!!e.isConstNode}getVaryingFromNode(e,t=null,n=e.getNodeType(this),i=null,r=null){const s=this.getDataFromNode(e,"any"),a=this.getSubBuildProperty("varying",s.subBuilds);let o=s[a];if(void 0===o){const e=this.varyings,l=e.length;null===t&&(t="nodeVarying"+l),"varying"!==a&&(t=this.getSubBuildProperty(t,s.subBuilds)),o=new PR(t,n,i,r),e.push(o),this.registerDeclaration(o),s[a]=o}return o}registerDeclaration(e){const t=this.shaderStage,n=this.declarations[t]||(this.declarations[t]={}),i=this.getPropertyName(e);let r=1,s=i;for(;void 0!==n[s];)s=i+"_"+r++;r>1&&(e.name=s,Xt(`TSL: Declaration name '${i}' of '${e.type}' already in use. Renamed to '${s}'.`)),n[s]=e}getCodeFromNode(e,t,n=this.shaderStage){const i=this.getDataFromNode(e);let r=i.code;if(void 0===r){const e=this.codes[n]||(this.codes[n]=[]),s=e.length;r=new LR("nodeCode"+s,t),e.push(r),i.code=r}return r}addFlowCodeHierarchy(e,t){const{flowCodes:n,flowCodeBlock:i}=this.getDataFromNode(e);let r=!0,s=t;for(;s;){if(!0===i.get(s)){r=!1;break}s=this.getDataFromNode(s).parentNodeBlock}if(r)for(const e of n)this.addLineFlowCode(e)}addLineFlowCodeBlock(e,t,n){const i=this.getDataFromNode(e),r=i.flowCodes||(i.flowCodes=[]),s=i.flowCodeBlock||(i.flowCodeBlock=new WeakMap);r.push(t),s.set(n,!0)}addLineFlowCode(e,t=null){return""===e||(null!==t&&this.context.nodeBlock&&this.addLineFlowCodeBlock(t,e,this.context.nodeBlock),e=this.tab+e,/;\s*$/.test(e)||(e+=";\n"),this.flow.code+=e),this}addFlowCode(e){return this.flow.code+=e,this}addFlowTab(){return this.tab+="\t",this}removeFlowTab(){return this.tab=this.tab.slice(0,-1),this}getFlowData(e){return this.flowsData.get(e)}flowNode(e){const t=e.getNodeType(this),n=this.flowChildNode(e,t);return this.flowsData.set(e,n),n}addInclude(e){null!==this.currentFunctionNode&&this.currentFunctionNode.includes.push(e)}buildFunctionNode(e){const t=new RA,n=this.currentFunctionNode;return this.currentFunctionNode=t,t.code=this.buildFunctionCode(e),this.currentFunctionNode=n,t}flowShaderNode(e){const t=e.layout,n={[Symbol.iterator](){let e=0;const t=Object.values(this);return{next:()=>({value:t[e],done:e++>=t.length})}}};for(const e of t.inputs)n[e.name]=new jw(e.type,e.name);e.layout=null;const i=e.call(n),r=this.flowStagesNode(i,t.type);return e.layout=t,r}flowBuildStage(e,t,n=null){const i=this.getBuildStage();this.setBuildStage(t);const r=e.build(this,n);return this.setBuildStage(i),r}flowStagesNode(e,t=null){const n=this.flow,i=this.vars,r=this.declarations,s=this.cache,a=this.buildStage,o=this.stack,l={code:""};this.flow=l,this.vars={},this.declarations={},this.cache=new IR,this.stack=$w();for(const n of Xf)this.setBuildStage(n),l.result=e.build(this,t);return l.vars=this.getVars(this.shaderStage),this.flow=n,this.vars=i,this.declarations=r,this.cache=s,this.stack=o,this.setBuildStage(a),l}getFunctionOperator(){return null}buildFunctionCode(){Xt("Abstract function.")}flowChildNode(e,t=null){const n=this.flow,i={code:""};return this.flow=i,i.result=e.build(this,t),this.flow=n,i}flowNodeFromShaderStage(e,t,n=null,i=null){const r=this.tab,s=this.cache,a=this.shaderStage,o=this.context;this.setShaderStage(e);const l={...this.context};delete l.nodeBlock,this.cache=this.globalCache,this.tab="\t",this.context=l;let u=null;if("generate"===this.buildStage){const r=this.flowChildNode(t,n);null!==i&&(r.code+=`${this.tab+i} = ${r.result};\n`),this.flowCode[e]=this.flowCode[e]+r.code,u=r}else u=t.build(this);return this.setShaderStage(a),this.cache=s,this.tab=r,this.context=o,u}getAttributesArray(){return this.attributes.concat(this.bufferAttributes)}getAttributes(){Xt("Abstract function.")}getVaryings(){Xt("Abstract function.")}getVar(e,t,n=null){return`${null!==n?this.generateArrayDeclaration(e,n):this.getType(e)} ${t}`}getVars(e){let t="";const n=this.vars[e];if(void 0!==n)for(const e of n)t+=`${this.getVar(e.type,e.name)}; `;return t}getUniforms(){Xt("Abstract function.")}getCodes(e){const t=this.codes[e];let n="";if(void 0!==t)for(const e of t)n+=e.code+"\n";return n}getHash(){return this.vertexShader+this.fragmentShader+this.computeShader}setShaderStage(e){this.shaderStage=e}getShaderStage(){return this.shaderStage}setBuildStage(e){this.buildStage=e}getBuildStage(){return this.buildStage}buildCode(){Xt("Abstract function.")}get subBuild(){return this.subBuildLayers[this.subBuildLayers.length-1]||null}addSubBuild(e){this.subBuildLayers.push(e)}removeSubBuild(){return this.subBuildLayers.pop()}getClosestSubBuild(e){let t;if(t=e&&e.isNode?e.isShaderCallNodeInternal?e.shaderNode.subBuilds:e.isStackNode?[e.subBuild]:this.getDataFromNode(e,"any").subBuilds:e instanceof Set?[...e]:e,!t)return null;const n=this.subBuildLayers;for(let e=t.length-1;e>=0;e--){const i=t[e];if(n.includes(i))return i}return null}getSubBuildOutput(e){return this.getSubBuildProperty("outputNode",e)}getSubBuildProperty(e="",t=null){let n,i;return n=null!==t?this.getClosestSubBuild(t):this.subBuildFn,i=n?e?n+"_"+e:n:e,i}build(){const{object:e,material:t,renderer:n}=this;if(null!==t){let e=n.library.fromMaterial(t);null===e&&(qt(`NodeMaterial: Material "${t.type}" is not compatible.`),e=new bS),e.build(this)}else this.addFlow("compute",e);for(const e of Xf){this.setBuildStage(e),this.context.position&&this.context.position.isNode&&this.flowNodeFromShaderStage("vertex",this.context.position);for(const t of qf){this.setShaderStage(t);const n=this.flowNodes[t];for(const t of n)"generate"===e?this.flowNode(t):t.build(this)}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}getSharedDataFromNode(e){let t=tC.get(e);return void 0===t&&(t={}),t}getNodeUniform(e,t){const n=this.getSharedDataFromNode(e);let i=n.cache;if(void 0===i){if("float"===t||"int"===t||"uint"===t)i=new WR(e);else if("vec2"===t||"ivec2"===t||"uvec2"===t)i=new $R(e);else if("vec3"===t||"ivec3"===t||"uvec3"===t)i=new XR(e);else if("vec4"===t||"ivec4"===t||"uvec4"===t)i=new qR(e);else if("color"===t)i=new YR(e);else if("mat2"===t)i=new KR(e);else if("mat3"===t)i=new ZR(e);else{if("mat4"!==t)throw new Error(`Uniform "${t}" not implemented.`);i=new QR(e)}n.cache=i}return i}format(e,t,n){if((t=this.getVectorType(t))===(n=this.getVectorType(n))||null===n||this.isReference(n))return e;const i=this.getTypeLength(t),r=this.getTypeLength(n);return 16===i&&9===r?`${this.getType(n)}( ${e}[ 0 ].xyz, ${e}[ 1 ].xyz, ${e}[ 2 ].xyz )`:9===i&&4===r?`${this.getType(n)}( ${e}[ 0 ].xy, ${e}[ 1 ].xy )`:i>4||r>4||0===r?e:i===r?`${this.getType(n)}( ${e} )`:i>r?(e="bool"===n?`all( ${e} )`:`${e}.${"xyz".slice(0,r)}`,this.format(e,this.getTypeFromLength(r,this.getComponentType(t)),n)):4===r&&i>1?`${this.getType(n)}( ${this.format(e,t,"vec3")}, 1.0 )`:2===i?`${this.getType(n)}( ${this.format(e,t,"vec2")}, 0.0 )`:(1===i&&r>1&&t!==this.getComponentType(n)&&(e=`${this.getType(this.getComponentType(n))}( ${e} )`),`${this.getType(n)}( ${e} )`)}getSignature(){return`// Three.js r${s} - Node System\n`}needsPreviousData(){const e=this.renderer.getMRT();return e&&e.has("velocity")||!0===Bf(this.object).useVelocity}}class sC{constructor(){this.time=0,this.deltaTime=0,this.frameId=0,this.renderId=0,this.updateMap=new WeakMap,this.updateBeforeMap=new WeakMap,this.updateAfterMap=new WeakMap,this.renderer=null,this.material=null,this.camera=null,this.object=null,this.scene=null}_getMaps(e,t){let n=e.get(t);return void 0===n&&(n={renderId:0,frameId:0},e.set(t,n)),n}updateBeforeNode(e){const t=e.getUpdateBeforeType(),n=e.updateReference(this);if(t===Vf){const t=this._getMaps(this.updateBeforeMap,n);if(t.frameId!==this.frameId){const n=t.frameId;t.frameId=this.frameId,!1===e.updateBefore(this)&&(t.frameId=n)}}else if(t===Gf){const t=this._getMaps(this.updateBeforeMap,n);if(t.renderId!==this.renderId){const n=t.renderId;t.renderId=this.renderId,!1===e.updateBefore(this)&&(t.renderId=n)}}else t===Hf&&e.updateBefore(this)}updateAfterNode(e){const t=e.getUpdateAfterType(),n=e.updateReference(this);if(t===Vf){const t=this._getMaps(this.updateAfterMap,n);t.frameId!==this.frameId&&!1!==e.updateAfter(this)&&(t.frameId=this.frameId)}else if(t===Gf){const t=this._getMaps(this.updateAfterMap,n);t.renderId!==this.renderId&&!1!==e.updateAfter(this)&&(t.renderId=this.renderId)}else t===Hf&&e.updateAfter(this)}updateNode(e){const t=e.getUpdateType(),n=e.updateReference(this);if(t===Vf){const t=this._getMaps(this.updateMap,n);t.frameId!==this.frameId&&!1!==e.update(this)&&(t.frameId=this.frameId)}else if(t===Gf){const t=this._getMaps(this.updateMap,n);t.renderId!==this.renderId&&!1!==e.update(this)&&(t.renderId=this.renderId)}else t===Hf&&e.update(this)}update(){this.frameId++,void 0===this.lastTime&&(this.lastTime=performance.now()),this.deltaTime=(performance.now()-this.lastTime)/1e3,this.lastTime=performance.now(),this.time+=this.deltaTime}}class aC{constructor(e,t,n=null,i="",r=!1){this.type=e,this.name=t,this.count=n,this.qualifier=i,this.isConst=r}}aC.isNodeFunctionInput=!0;class oC extends yR{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}class lC extends yR{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setupDirect(){const e=this.colorNode;return{lightDirection:zA(this.light),lightColor:e}}}class uC extends yR{static get type(){return"HemisphereLightNode"}constructor(e=null){super(e),this.lightPositionNode=BA(e),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=a_(new _i).setGroup(i_)}update(e){const{light:t}=this;super.update(e),this.lightPositionNode.object3d=t,this.groundColorNode.value.copy(t.groundColor).multiplyScalar(t.intensity)}setup(e){const{colorNode:t,groundColorNode:n,lightDirectionNode:i}=this,r=jb.dot(i).mul(.5).add(.5),s=Dv(n,t,r);e.context.irradiance.addAssign(s)}}class cC extends yR{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=a_(0).setGroup(i_),this.penumbraCosNode=a_(0).setGroup(i_),this.cutoffDistanceNode=a_(0).setGroup(i_),this.decayExponentNode=a_(0).setGroup(i_),this.colorNode=a_(this.color).setGroup(i_)}update(e){super.update(e);const{light:t}=this;this.coneCosNode.value=Math.cos(t.angle),this.penumbraCosNode.value=Math.cos(t.angle*(1-t.penumbra)),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}getSpotAttenuation(e,t){const{coneCosNode:n,penumbraCosNode:i}=this;return Ov(n,i,t)}getLightCoord(e){const t=e.getNodeProperties(this);let n=t.projectionUV;return void 0===n&&(n=function(e,t=Pb){const n=OA(e).mul(t);return n.xyz.div(n.w)}(this.light,e.context.positionWorld),t.projectionUV=n),n}setupDirect(e){const{colorNode:t,cutoffDistanceNode:n,decayExponentNode:i,light:r}=this,s=this.getLightVector(e),a=s.normalize(),o=a.dot(zA(r)),l=this.getSpotAttenuation(e,o),u=s.length(),c=bR({lightDistance:u,cutoffDistance:n,decayExponent:i});let h,d,p=t.mul(l).mul(c);if(r.colorNode?(d=this.getLightCoord(e),h=r.colorNode(d)):r.map&&(d=this.getLightCoord(e),h=zy(r.map,d.xy).onRenderUpdate(()=>r.map)),h){p=d.mul(2).sub(1).abs().lessThan(1).all().select(p.mul(h),p)}return{lightColor:p,lightDirection:a}}}class hC extends cC{static get type(){return"IESSpotLightNode"}getSpotAttenuation(e,t){const n=this.light.iesMap;let i=null;if(n&&!0===n.isTexture){const e=t.acos().mul(1/Math.PI);i=zy(n,ag(e,0),0).r}else i=super.getSpotAttenuation(t);return i}}class dC extends yR{static get type(){return"LightProbeNode"}constructor(e=null){super(e);const t=[];for(let e=0;e<9;e++)t.push(new dn);this.lightProbe=$y(t)}update(e){const{light:t}=this;super.update(e);for(let e=0;e<9;e++)this.lightProbe.array[e].copy(t.sh.coefficients[e]).multiplyScalar(t.intensity)}setup(e){const t=TR(jb,this.lightProbe);e.context.irradiance.addAssign(t)}}const pC=Km(([e,t])=>{const n=e.abs().sub(t);return lv(xv(n,0)).add(bv(xv(n.x,n.y),0))});class fC extends cC{static get type(){return"ProjectorLightNode"}update(e){super.update(e);const t=this.light;if(this.penumbraCosNode.value=Math.min(Math.cos(t.angle*(1-t.penumbra)),.99999),null===t.aspect){let e=1;null!==t.map&&(e=t.map.width/t.map.height),t.shadow.aspect=e}else t.shadow.aspect=t.aspect}getSpotAttenuation(e){const t=ng(0),n=this.penumbraCosNode,i=OA(this.light).mul(e.context.positionWorld||Pb);return Jm(i.w.greaterThan(0),()=>{const e=i.xyz.div(i.w),r=pC(e.xy.sub(ag(.5)),ag(.5)),s=m_(-1,p_(1,rv(n)).sub(1));t.assign(Uv(r.mul(-2).mul(s)))}),t}}const mC=new Fn,gC=new Fn;let _C=null;class vC extends yR{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=a_(new dn).setGroup(i_),this.halfWidth=a_(new dn).setGroup(i_),this.updateType=Gf}update(e){super.update(e);const{light:t}=this,n=e.camera.matrixWorldInverse;gC.identity(),mC.copy(t.matrixWorld),mC.premultiply(n),gC.extractRotation(mC),this.halfWidth.value.set(.5*t.width,0,0),this.halfHeight.value.set(0,.5*t.height,0),this.halfWidth.value.applyMatrix4(gC),this.halfHeight.value.applyMatrix4(gC)}setupDirectRectArea(e){let t,n;e.isAvailable("float32Filterable")?(t=zy(_C.LTC_FLOAT_1),n=zy(_C.LTC_FLOAT_2)):(t=zy(_C.LTC_HALF_1),n=zy(_C.LTC_HALF_2));const{colorNode:i,light:r}=this;return{lightColor:i,lightPosition:kA(r),halfWidth:this.halfWidth,halfHeight:this.halfHeight,ltc_1:t,ltc_2:n}}static setLTC(e){_C=e}}class yC{parseFunction(){Xt("Abstract function.")}}class bC{constructor(e,t,n="",i=""){this.type=e,this.inputs=t,this.name=n,this.precision=i}getCode(){Xt("Abstract function.")}}bC.isNodeFunction=!0;const xC=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,TC=/[a-z_0-9]+/gi,SC="#pragma main";class MC extends bC{constructor(e){const{type:t,inputs:n,name:i,precision:r,inputsCode:s,blockCode:a,headerCode:o}=(e=>{const t=(e=e.trim()).indexOf(SC),n=-1!==t?e.slice(t+12):e,i=n.match(xC);if(null!==i&&5===i.length){const r=i[4],s=[];let a=null;for(;null!==(a=TC.exec(r));)s.push(a);const o=[];let l=0;for(;l{const n=this.backend.createNodeBuilder(e.object,this.renderer);return n.scene=e.scene,n.material=t,n.camera=e.camera,n.context.material=t,n.lightsNode=e.lightsNode,n.environmentNode=this.getEnvironmentNode(e.scene),n.fogNode=this.getFogNode(e.scene),n.clippingContext=e.clippingContext,this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview&&n.enableMultiview(),n};let s=t(e.material);try{s.build()}catch(e){s=t(new bS),s.build();let n=e.stackTrace;!n&&e.stack&&(n=new Rf(e.stack)),qt("TSL: "+e,n)}n=this._createNodeBuilderState(s),i.set(r,n)}n.usedTimes++,t.nodeBuilderState=n}return n}delete(e){if(e.isRenderObject){const t=this.get(e).nodeBuilderState;t.usedTimes--,0===t.usedTimes&&this.nodeBuilderCache.delete(this.getForRenderCacheKey(e))}return super.delete(e)}getForCompute(e){const t=this.get(e);let n=t.nodeBuilderState;if(void 0===n){const i=this.backend.createNodeBuilder(e,this.renderer);i.build(),n=this._createNodeBuilderState(i),t.nodeBuilderState=n}return n}_createNodeBuilderState(e){return new AR(e.vertexShader,e.fragmentShader,e.computeShader,e.getAttributesArray(),e.getBindings(),e.updateNodes,e.updateBeforeNodes,e.updateAfterNodes,e.observer,e.transforms)}getEnvironmentNode(e){this.updateEnvironment(e);let t=null;if(e.environmentNode&&e.environmentNode.isNode)t=e.environmentNode;else{const n=this.get(e);n.environmentNode&&(t=n.environmentNode)}return t}getBackgroundNode(e){this.updateBackground(e);let t=null;if(e.backgroundNode&&e.backgroundNode.isNode)t=e.backgroundNode;else{const n=this.get(e);n.backgroundNode&&(t=n.backgroundNode)}return t}getFogNode(e){return this.updateFog(e),e.fogNode||this.get(e).fogNode||null}getCacheKey(e,t){AC[0]=e,AC[1]=t;const n=this.renderer.info.calls,i=this.callHashCache.get(AC)||{};if(i.callId!==n){const r=this.getEnvironmentNode(e),s=this.getFogNode(e);t&&RC.push(t.getCacheKey(!0)),r&&RC.push(r.getCacheKey()),s&&RC.push(s.getCacheKey()),RC.push(this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview?1:0),RC.push(this.renderer.shadowMap.enabled?1:0),RC.push(this.renderer.shadowMap.type),i.callId=n,i.cacheKey=Pf(RC),this.callHashCache.set(AC,i),RC.length=0}return AC[0]=null,AC[1]=null,i.cacheKey}get isToneMappingState(){return!this.renderer.getRenderTarget()}updateBackground(e){const t=this.get(e),n=e.background;if(n){const i=0===e.backgroundBlurriness&&t.backgroundBlurriness>0||e.backgroundBlurriness>0&&0===t.backgroundBlurriness;if(t.background!==n||i){const r=this.getCacheNode("background",n,()=>{if(!0===n.isCubeTexture||n.mapping===ne||n.mapping===ie||n.mapping===re){if(e.backgroundBlurriness>0||n.mapping===re)return DE(n);{let e;return e=!0===n.isCubeTexture?ax(n):zy(n),DS(e)}}if(!0===n.isTexture)return zy(n,Qy.flipY()).setUpdateMatrix(!0);!0!==n.isColor&&qt("WebGPUNodes: Unsupported background configuration.",n)},i);t.backgroundNode=r,t.background=n,t.backgroundBlurriness=e.backgroundBlurriness}}else t.backgroundNode&&(delete t.backgroundNode,delete t.background)}getCacheNode(e,t,n,i=!1){const r=this.cacheLib[e]||(this.cacheLib[e]=new WeakMap);let s=r.get(t);return(void 0===s||i)&&(s=n(),r.set(t,s)),s}updateFog(e){const t=this.get(e),n=e.fog;if(n){if(t.fog!==n){const e=this.getCacheNode("fog",n,()=>{if(n.isFogExp2){const e=ux("color","color",n).setGroup(i_),t=ux("density","float",n).setGroup(i_);return LA(e,PA(t))}if(n.isFog){const e=ux("color","color",n).setGroup(i_),t=ux("near","float",n).setGroup(i_),i=ux("far","float",n).setGroup(i_);return LA(e,NA(t,i))}qt("Renderer: Unsupported fog configuration.",n)});t.fogNode=e,t.fog=n}}else delete t.fogNode,delete t.fog}updateEnvironment(e){const t=this.get(e),n=e.environment;if(n){if(t.environment!==n){const e=this.getCacheNode("environment",n,()=>!0===n.isCubeTexture?ax(n):!0===n.isTexture?zy(n):void qt("Nodes: Unsupported environment configuration.",n));t.environmentNode=e,t.environment=n}}else t.environmentNode&&(delete t.environmentNode,delete t.environment)}getNodeFrame(e=this.renderer,t=null,n=null,i=null,r=null){const s=this.nodeFrame;return s.renderer=e,s.scene=t,s.object=n,s.camera=i,s.material=r,s}getNodeFrameForRender(e){return this.getNodeFrame(e.renderer,e.scene,e.object,e.camera,e.material)}getOutputCacheKey(){const e=this.renderer;return e.toneMapping+","+e.currentColorSpace+","+e.xr.isPresenting}hasOutputChange(e){return wC.get(e)!==this.getOutputCacheKey()}getOutputNode(e){const t=this.renderer,n=this.getOutputCacheKey(),i=e.isArrayTexture?dA(e,cg(Qy,Xy("gl_ViewID_OVR"))).renderOutput(t.toneMapping,t.currentColorSpace):zy(e,Qy).renderOutput(t.toneMapping,t.currentColorSpace);return wC.set(e,n),i}updateBefore(e){const t=e.getNodeBuilderState();for(const n of t.updateBeforeNodes)this.getNodeFrameForRender(e).updateBeforeNode(n)}updateAfter(e){const t=e.getNodeBuilderState();for(const n of t.updateAfterNodes)this.getNodeFrameForRender(e).updateAfterNode(n)}updateForCompute(e){const t=this.getNodeFrame(),n=this.getForCompute(e);for(const e of n.updateNodes)t.updateNode(e)}updateForRender(e){const t=this.getNodeFrameForRender(e),n=e.getNodeBuilderState();for(const e of n.updateNodes)t.updateNode(e)}needsRefresh(e){const t=this.getNodeFrameForRender(e);return e.getMonitor().needsRefresh(e,t)}dispose(){super.dispose(),this.nodeFrame=new sC,this.nodeBuilderCache=new Map,this.cacheLib={}}}const NC=new Qr;class PC{constructor(e=null){this.version=0,this.clipIntersection=null,this.cacheKey="",this.shadowPass=!1,this.viewNormalMatrix=new mn,this.clippingGroupContexts=new WeakMap,this.intersectionPlanes=[],this.unionPlanes=[],this.parentVersion=null,null!==e&&(this.viewNormalMatrix=e.viewNormalMatrix,this.clippingGroupContexts=e.clippingGroupContexts,this.shadowPass=e.shadowPass,this.viewMatrix=e.viewMatrix)}projectPlanes(e,t,n){const i=e.length;for(let r=0;r0,alpha:!0,depth:t.depth,stencil:t.stencil,framebufferScaleFactor:this.getFramebufferScaleFactor()},r=new XRWebGLLayer(e,i,n);this._glBaseLayer=r,e.updateRenderState({baseLayer:r}),t.setPixelRatio(1),t._setXRLayerSize(r.framebufferWidth,r.framebufferHeight),this._xrRenderTarget=new kC(r.framebufferWidth,r.framebufferHeight,{format:Ce,type:fe,colorSpace:t.outputColorSpace,stencilBuffer:t.stencil,resolveDepthBuffer:!1===r.ignoreDepthValues,resolveStencilBuffer:!1===r.ignoreDepthValues}),this._xrRenderTarget._isOpaqueFramebuffer=!0,this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType())}this.setFoveation(this.getFoveation()),t._animation.setAnimationLoop(this._onAnimationFrame),t._animation.setContext(e),t._animation.start(),this.isPresenting=!0,this.dispatchEvent({type:"sessionstart"})}}updateCamera(e){const t=this._session;if(null===t)return;const n=e.near,i=e.far,r=this._cameraXR,s=this._cameraL,a=this._cameraR;r.near=a.near=s.near=n,r.far=a.far=s.far=i,r.isMultiViewCamera=this._useMultiview,this._currentDepthNear===r.near&&this._currentDepthFar===r.far||(t.updateRenderState({depthNear:r.near,depthFar:r.far}),this._currentDepthNear=r.near,this._currentDepthFar=r.far),r.layers.mask=6|e.layers.mask,s.layers.mask=-5&r.layers.mask,a.layers.mask=-3&r.layers.mask;const o=e.parent,l=r.cameras;HC(r,o);for(let e=0;e=0&&(n[s]=null,t[s].disconnect(r))}for(let i=0;i=n.length){n.push(r),s=e;break}if(null===n[e]){n[e]=r,s=e;break}}if(-1===s)break}const a=t[s];a&&a.connect(r)}}function XC(e){return"quad"===e.type?this._glBinding.createQuadLayer({transform:new XRRigidTransform(e.translation,e.quaternion),width:e.width/2,height:e.height/2,space:this._referenceSpace,viewPixelWidth:e.pixelwidth,viewPixelHeight:e.pixelheight,clearOnAccess:!1}):this._glBinding.createCylinderLayer({transform:new XRRigidTransform(e.translation,e.quaternion),radius:e.radius,centralAngle:e.centralAngle,aspectRatio:e.aspectRatio,space:this._referenceSpace,viewPixelWidth:e.pixelwidth,viewPixelHeight:e.pixelheight,clearOnAccess:!1})}function qC(e,t){if(void 0===t)return;const n=this._cameraXR,i=this._renderer,r=i.backend,s=this._glBaseLayer,a=this.getReferenceSpace(),o=t.getViewerPose(a);if(this._xrFrame=t,null!==o){const e=o.views;null!==this._glBaseLayer&&r.setXRTarget(s.framebuffer);let t=!1;e.length!==n.cameras.length&&(n.cameras.length=0,t=!0);for(let i=0;i{await this.compileAsync(e,t);const i=this._renderLists.get(e,t),r=this._renderContexts.get(this._renderTarget,this._mrt),s=e.overrideMaterial||n.material,a=this._objects.get(n,s,e,t,i.lightsNode,r,r.clippingContext),{fragmentShader:o,vertexShader:l}=a.getNodeBuilderState();return{fragmentShader:o,vertexShader:l}}}}async init(){return null!==this._initPromise||(this._initPromise=new Promise(async(e,t)=>{let n=this.backend;try{await n.init(this)}catch(e){if(null===this._getFallback)return void t(e);try{this.backend=n=this._getFallback(e),await n.init(this)}catch(e){return void t(e)}}this._nodes=new CC(this,n),this._animation=new aw(this,this._nodes,this.info),this._attributes=new vw(n),this._background=new MR(this,this._nodes),this._geometries=new Tw(this._attributes,this.info),this._textures=new Gw(this,n,this.info),this._pipelines=new Cw(n,this._nodes),this._bindings=new Nw(n,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new hw(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new Fw(this.lighting),this._bundles=new IC,this._renderContexts=new zw(this),this._animation.start(),this._initialized=!0,this._inspector.init(),e(this)})),this._initPromise}get domElement(){return this._canvasTarget.domElement}get coordinateSystem(){return this.backend.coordinateSystem}async compileAsync(e,t,n=null){if(!0===this._isDeviceLost)return;!1===this._initialized&&await this.init();const i=this._nodes.nodeFrame,r=i.renderId,s=this._currentRenderContext,a=this._currentRenderObjectFunction,o=this._handleObjectFunction,l=this._compilationPromises,u=!0===e.isScene?e:KC;null===n&&(n=e);const c=this._renderTarget,h=this._renderContexts.get(c,this._mrt),d=this._activeMipmapLevel,p=[];this._currentRenderContext=h,this._currentRenderObjectFunction=this.renderObject,this._handleObjectFunction=this._createObjectPipeline,this._compilationPromises=p,i.renderId++,i.update(),h.depth=this.depth,h.stencil=this.stencil,h.clippingContext||(h.clippingContext=new PC),h.clippingContext.updateGlobal(u,t),u.onBeforeRender(this,e,t,c);const f=this._renderLists.get(e,t);if(f.begin(),this._projectObject(e,t,0,f,h.clippingContext),n!==e&&n.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&f.pushLight(e)}),f.finish(),null!==c){this._textures.updateRenderTarget(c,d);const e=this._textures.get(c);h.textures=e.textures,h.depthTexture=e.depthTexture}else h.textures=null,h.depthTexture=null;n!==e?this._background.update(n,f,h):this._background.update(u,f,h);const m=f.opaque,g=f.transparent,_=f.transparentDoublePass,v=f.lightsNode;!0===this.opaque&&m.length>0&&this._renderObjects(m,t,u,v),!0===this.transparent&&g.length>0&&this._renderTransparents(g,_,t,u,v),i.renderId=r,this._currentRenderContext=s,this._currentRenderObjectFunction=a,this._handleObjectFunction=o,this._compilationPromises=l,await Promise.all(p)}async renderAsync(e,t){Yt('Renderer: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.render(e,t)}async waitForGPU(){qt("Renderer: waitForGPU() has been removed. Read https://github.com/mrdoob/three.js/issues/32012 for more information.")}set inspector(e){null!==this._inspector&&this._inspector.setRenderer(null),this._inspector=e,this._inspector.setRenderer(this)}get inspector(){return this._inspector}set highPrecision(e){const t=this.contextNode.value;!0===e?(t.modelViewMatrix=Eb,t.modelNormalViewMatrix=wb):this.highPrecision&&(delete t.modelViewMatrix,delete t.modelNormalViewMatrix)}get highPrecision(){const e=this.contextNode.value;return e.modelViewMatrix===Eb&&e.modelNormalViewMatrix===wb}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getOutputBufferType(){return this._outputBufferType}getColorBufferType(){return Yt('Renderer: ".getColorBufferType()" has been renamed to ".getOutputBufferType()".'),this.getOutputBufferType()}_onDeviceLost(e){let t=`THREE.WebGPURenderer: ${e.api} Device Lost:\n\nMessage: ${e.message}`;e.reason&&(t+=`\nReason: ${e.reason}`),qt(t),this._isDeviceLost=!0}_renderBundle(e,t,n){const{bundleGroup:i,camera:r,renderList:s}=e,a=this._currentRenderContext,o=this._bundles.get(i,r),l=this.backend.get(o);void 0===l.renderContexts&&(l.renderContexts=new Set);const u=i.version!==l.version,c=!1===l.renderContexts.has(a)||u;if(l.renderContexts.add(a),c){this.backend.beginBundle(a),(void 0===l.renderObjects||u)&&(l.renderObjects=[]),this._currentRenderBundle=o;const{transparentDoublePass:e,transparent:c,opaque:h}=s;!0===this.opaque&&h.length>0&&this._renderObjects(h,r,t,n),!0===this.transparent&&c.length>0&&this._renderTransparents(c,e,r,t,n),this._currentRenderBundle=null,this.backend.finishBundle(a,o),l.version=i.version}else{const{renderObjects:e}=l;for(let t=0,n=e.length;t>=d,f.viewportValue.height>>=d,f.viewportValue.minDepth=b,f.viewportValue.maxDepth=x,f.viewport=!1===f.viewportValue.equals(QC),f.scissorValue.copy(v).multiplyScalar(y).floor(),f.scissor=g._scissorTest&&!1===f.scissorValue.equals(QC),f.scissorValue.width>>=d,f.scissorValue.height>>=d,f.clippingContext||(f.clippingContext=new PC),f.clippingContext.updateGlobal(u,t),u.onBeforeRender(this,e,t,p);const T=t.isArrayCamera?eN:JC;t.isArrayCamera||(tN.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),T.setFromProjectionMatrix(tN,t.coordinateSystem,t.reversedDepth));const S=this._renderLists.get(e,t);if(S.begin(),this._projectObject(e,t,0,S,f.clippingContext),S.finish(),!0===this.sortObjects&&S.sort(this._opaqueSort,this._transparentSort),null!==p){this._textures.updateRenderTarget(p,d);const e=this._textures.get(p);f.textures=e.textures,f.depthTexture=e.depthTexture,f.width=e.width,f.height=e.height,f.renderTarget=p,f.depth=p.depthBuffer,f.stencil=p.stencilBuffer}else f.textures=null,f.depthTexture=null,f.width=ZC.width,f.height=ZC.height,f.depth=this.depth,f.stencil=this.stencil;f.width>>=d,f.height>>=d,f.activeCubeFace=h,f.activeMipmapLevel=d,f.occlusionQueryCount=S.occlusionQueryCount,f.scissorValue.max(nN.set(0,0,0,0)),f.scissorValue.x+f.scissorValue.width>f.width&&(f.scissorValue.width=Math.max(f.width-f.scissorValue.x,0)),f.scissorValue.y+f.scissorValue.height>f.height&&(f.scissorValue.height=Math.max(f.height-f.scissorValue.y,0)),this._background.update(u,S,f),f.camera=t,this.backend.beginRender(f);const{bundles:M,lightsNode:E,transparentDoublePass:w,transparent:A,opaque:R}=S;return M.length>0&&this._renderBundles(M,u,E),!0===this.opaque&&R.length>0&&this._renderObjects(R,t,u,E),!0===this.transparent&&A.length>0&&this._renderTransparents(A,w,t,u,E),this.backend.finishRender(f),r.renderId=s,this._currentRenderContext=a,this._currentRenderObjectFunction=o,this._handleObjectFunction=l,this._callDepth--,null!==i&&(this.setRenderTarget(c,h,d),this._renderOutput(p)),u.onAfterRender(this,e,t,p),this.inspector.finishRender(this.backend.getTimestampUID(f)),f}_setXRLayerSize(e,t){this._canvasTarget._width=e,this._canvasTarget._height=t,this.setViewport(0,0,e,t)}_renderOutput(e){const t=this._quad;this._nodes.hasOutputChange(e.texture)&&(t.material.fragmentNode=this._nodes.getOutputNode(e.texture),t.material.needsUpdate=!0);const n=this.autoClear,i=this.xr.enabled;this.autoClear=!1,this.xr.enabled=!1,this._renderScene(t,t.camera,!1),this.autoClear=n,this.xr.enabled=i}getMaxAnisotropy(){return this.backend.getMaxAnisotropy()}getActiveCubeFace(){return this._activeCubeFace}getActiveMipmapLevel(){return this._activeMipmapLevel}async setAnimationLoop(e){!1===this._initialized&&await this.init(),this._animation.setAnimationLoop(e)}getAnimationLoop(){return this._animation.getAnimationLoop()}async getArrayBufferAsync(e){return await this.backend.getArrayBufferAsync(e)}getContext(){return this.backend.getContext()}getPixelRatio(){return this._canvasTarget.getPixelRatio()}getDrawingBufferSize(e){return this._canvasTarget.getDrawingBufferSize(e)}getSize(e){return this._canvasTarget.getSize(e)}setPixelRatio(e=1){this._canvasTarget.setPixelRatio(e)}setDrawingBufferSize(e,t,n){this.xr&&this.xr.isPresenting||this._canvasTarget.setDrawingBufferSize(e,t,n)}setSize(e,t,n=!0){this.xr&&this.xr.isPresenting||this._canvasTarget.setSize(e,t,n)}setOpaqueSort(e){this._opaqueSort=e}setTransparentSort(e){this._transparentSort=e}getScissor(e){return this._canvasTarget.getScissor(e)}setScissor(e,t,n,i){this._canvasTarget.setScissor(e,t,n,i)}getScissorTest(){return this._canvasTarget.getScissorTest()}setScissorTest(e){this._canvasTarget.setScissorTest(e),this.backend.setScissorTest(e)}getViewport(e){return this._canvasTarget.getViewport(e)}setViewport(e,t,n,i,r=0,s=1){this._canvasTarget.setViewport(e,t,n,i,r,s)}getClearColor(e){return e.copy(this._clearColor)}setClearColor(e,t=1){this._clearColor.set(e),this._clearColor.a=t}getClearAlpha(){return this._clearColor.a}setClearAlpha(e){this._clearColor.a=e}getClearDepth(){return!0===this.reversedDepthBuffer?1-this._clearDepth:this._clearDepth}setClearDepth(e){this._clearDepth=e}getClearStencil(){return this._clearStencil}setClearStencil(e){this._clearStencil=e}isOccluded(e){const t=this._currentRenderContext;return t&&this.backend.isOccluded(t,e)}clear(e=!0,t=!0,n=!0){if(!1===this._initialized)throw new Error('Renderer: .clear() called before the backend is initialized. Use "await renderer.init();" before before using this method.');const i=this._renderTarget||this._getFrameBufferTarget();let r=null;if(null!==i){this._textures.updateRenderTarget(i);const e=this._textures.get(i);r=this._renderContexts.get(i),r.textures=e.textures,r.depthTexture=e.depthTexture,r.width=e.width,r.height=e.height,r.renderTarget=i,r.depth=i.depthBuffer,r.stencil=i.stencilBuffer;const t=this.backend.getClearColor();r.clearColorValue.r=t.r,r.clearColorValue.g=t.g,r.clearColorValue.b=t.b,r.clearColorValue.a=t.a,r.clearDepthValue=this.getClearDepth(),r.clearStencilValue=this.getClearStencil(),r.activeCubeFace=this.getActiveCubeFace(),r.activeMipmapLevel=this.getActiveMipmapLevel()}this.backend.clear(e,t,n,r),null!==i&&null===this._renderTarget&&this._renderOutput(i)}clearColor(){this.clear(!0,!1,!1)}clearDepth(){this.clear(!1,!0,!1)}clearStencil(){this.clear(!1,!1,!0)}async clearAsync(e=!0,t=!0,n=!0){Yt('Renderer: "clearAsync()" has been deprecated. Use "clear()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.clear(e,t,n)}async clearColorAsync(){Yt('Renderer: "clearColorAsync()" has been deprecated. Use "clearColor()" and "await renderer.init();" when creating the renderer.'),this.clear(!0,!1,!1)}async clearDepthAsync(){Yt('Renderer: "clearDepthAsync()" has been deprecated. Use "clearDepth()" and "await renderer.init();" when creating the renderer.'),this.clear(!1,!0,!1)}async clearStencilAsync(){Yt('Renderer: "clearStencilAsync()" has been deprecated. Use "clearStencil()" and "await renderer.init();" when creating the renderer.'),this.clear(!1,!1,!0)}get needsFrameBufferTarget(){const e=0!==this.currentToneMapping,t=this.currentColorSpace!==bn.workingColorSpace;return e||t}get samples(){return this._samples}get currentSamples(){let e=this._samples;return null!==this._renderTarget?e=this._renderTarget.samples:this.needsFrameBufferTarget&&(e=0),e}get currentToneMapping(){return this.isOutputTarget?this.toneMapping:0}get currentColorSpace(){return this.isOutputTarget?this.outputColorSpace:bn.workingColorSpace}get isOutputTarget(){return this._renderTarget===this._outputRenderTarget||null===this._renderTarget}dispose(){!0===this._initialized&&(this.info.dispose(),this.backend.dispose(),this._animation.dispose(),this._objects.dispose(),this._geometries.dispose(),this._pipelines.dispose(),this._nodes.dispose(),this._bindings.dispose(),this._renderLists.dispose(),this._renderContexts.dispose(),this._textures.dispose(),null!==this._frameBufferTarget&&this._frameBufferTarget.dispose(),Object.values(this.backend.timestampQueryPool).forEach(e=>{null!==e&&e.dispose()})),this.setRenderTarget(null),this.setAnimationLoop(null)}setRenderTarget(e,t=0,n=0){this._renderTarget=e,this._activeCubeFace=t,this._activeMipmapLevel=n}getRenderTarget(){return this._renderTarget}setOutputRenderTarget(e){this._outputRenderTarget=e}getOutputRenderTarget(){return this._outputRenderTarget}setCanvasTarget(e){this._canvasTarget.removeEventListener("resize",this._onCanvasTargetResize),this._canvasTarget=e,this._canvasTarget.addEventListener("resize",this._onCanvasTargetResize)}getCanvasTarget(){return this._canvasTarget}_resetXRState(){this.backend.setXRTarget(null),this.setOutputRenderTarget(null),this.setRenderTarget(null),this._frameBufferTarget.dispose(),this._frameBufferTarget=null}setRenderObjectFunction(e){this._renderObjectFunction=e}getRenderObjectFunction(){return this._renderObjectFunction}compute(e,t=null){if(!0===this._isDeviceLost)return;if(!1===this._initialized)return Xt("Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead."),this.computeAsync(e,t);const n=this._nodes.nodeFrame,i=n.renderId;this.info.calls++,this.info.compute.calls++,this.info.compute.frameCalls++,n.renderId=this.info.calls,this.backend.updateTimeStampUID(e),this.inspector.beginCompute(this.backend.getTimestampUID(e),e);const r=this.backend,s=this._pipelines,a=this._bindings,o=this._nodes,l=Array.isArray(e)?e:[e];if(void 0===l[0]||!0!==l[0].isComputeNode)throw new Error("THREE.Renderer: .compute() expects a ComputeNode.");r.beginCompute(e);for(const n of l){if(!1===s.has(n)){const e=()=>{n.removeEventListener("dispose",e),s.delete(n),a.deleteForCompute(n),o.delete(n)};n.addEventListener("dispose",e);const t=n.onInitFunction;null!==t&&t.call(n,{renderer:this})}o.updateForCompute(n),a.updateForCompute(n);const i=a.getForCompute(n),l=s.getForCompute(n,i);r.compute(e,n,i,l,t)}r.finishCompute(e),n.renderId=i,this.inspector.finishCompute(this.backend.getTimestampUID(e))}async computeAsync(e,t=null){!1===this._initialized&&await this.init(),this.compute(e,t)}async hasFeatureAsync(e){return Yt('Renderer: "hasFeatureAsync()" has been deprecated. Use "hasFeature()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.hasFeature(e)}async resolveTimestampsAsync(e="render"){return!1===this._initialized&&await this.init(),this.backend.resolveTimestampsAsync(e)}hasFeature(e){if(!1===this._initialized)throw new Error('Renderer: .hasFeature() called before the backend is initialized. Use "await renderer.init();" before before using this method.');return this.backend.hasFeature(e)}hasInitialized(){return this._initialized}async initTextureAsync(e){Yt('Renderer: "initTextureAsync()" has been deprecated. Use "initTexture()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.initTexture(e)}initTexture(e){if(!1===this._initialized)throw new Error('Renderer: .initTexture() called before the backend is initialized. Use "await renderer.init();" before before using this method.');this._textures.updateTexture(e)}initRenderTarget(e){if(!1===this._initialized)throw new Error('Renderer: .initRenderTarget() called before the backend is initialized. Use "await renderer.init();" before before using this method.');this._textures.updateRenderTarget(e);const t=this._textures.get(e),n=this._renderContexts.get(e);n.textures=t.textures,n.depthTexture=t.depthTexture,n.width=t.width,n.height=t.height,n.renderTarget=e,n.depth=e.depthBuffer,n.stencil=e.stencilBuffer,this.backend.initRenderTarget(n)}copyFramebufferToTexture(e,t=null){if(null!==t)if(t.isVector2)t=nN.set(t.x,t.y,e.image.width,e.image.height).floor();else{if(!t.isVector4)return void qt("Renderer.copyFramebufferToTexture: Invalid rectangle.");t=nN.copy(t).floor()}else t=nN.set(0,0,e.image.width,e.image.height);let n,i=this._currentRenderContext;null!==i?n=i.renderTarget:(n=this._renderTarget||this._getFrameBufferTarget(),null!==n&&(this._textures.updateRenderTarget(n),i=this._textures.get(n))),this._textures.updateTexture(e,{renderTarget:n}),this.backend.copyFramebufferToTexture(e,i,t),this._inspector.copyFramebufferToTexture(e)}copyTextureToTexture(e,t,n=null,i=null,r=0,s=0){this._textures.updateTexture(e),this._textures.updateTexture(t),this.backend.copyTextureToTexture(e,t,n,i,r,s),this._inspector.copyTextureToTexture(e,t)}async readRenderTargetPixelsAsync(e,t,n,i,r,s=0,a=0){return this.backend.copyTextureToBuffer(e.textures[s],t,n,i,r,a)}_projectObject(e,t,n,i,r){if(!1===e.visible)return;if(e.layers.test(t.layers))if(e.isGroup)n=e.renderOrder,e.isClippingGroup&&e.enabled&&(r=r.getGroupContext(e));else if(e.isLOD)!0===e.autoUpdate&&e.update(t);else if(e.isLight)i.pushLight(e);else if(e.isSprite){const s=t.isArrayCamera?eN:JC;if(!e.frustumCulled||s.intersectsSprite(e,t)){!0===this.sortObjects&&nN.setFromMatrixPosition(e.matrixWorld).applyMatrix4(tN);const{geometry:t,material:s}=e;s.visible&&i.push(e,t,s,n,nN.z,null,r)}}else if(e.isLineLoop)qt("Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.");else if(e.isMesh||e.isLine||e.isPoints){const s=t.isArrayCamera?eN:JC;if(!e.frustumCulled||s.intersectsObject(e,t)){const{geometry:t,material:s}=e;if(!0===this.sortObjects&&(null===t.boundingSphere&&t.computeBoundingSphere(),nN.copy(t.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(tN)),Array.isArray(s)){const a=t.groups;for(let o=0,l=a.length;o0){for(const{material:e}of t)e.side=1;this._renderObjects(t,n,i,r,"backSide");for(const{material:e}of t)e.side=0;this._renderObjects(e,n,i,r);for(const{material:e}of t)e.side=2}else this._renderObjects(e,n,i,r)}_renderObjects(e,t,n,i,r=null){for(let s=0,a=e.length;s(t.not().discard(),e))(l)}}e.depthNode&&e.depthNode.isNode&&(u=e.depthNode),e.castShadowPositionNode&&e.castShadowPositionNode.isNode?o=e.castShadowPositionNode:e.positionNode&&e.positionNode.isNode&&(o=e.positionNode),n={version:t,colorNode:l,depthNode:u,positionNode:o},this._cacheShadowNodes.set(e,n)}return n}renderObject(e,t,n,i,r,s,a,o=null,l=null){let u,c,h,d,p=!1;if(e.onBeforeRender(this,t,n,i,r,s),!0===r.allowOverride&&null!==t.overrideMaterial){const e=t.overrideMaterial;if(p=!0,u=e.isNodeMaterial?e.colorNode:null,c=e.isNodeMaterial?e.depthNode:null,h=e.isNodeMaterial?e.positionNode:null,d=t.overrideMaterial.side,r.positionNode&&r.positionNode.isNode&&(e.positionNode=r.positionNode),e.alphaTest=r.alphaTest,e.alphaMap=r.alphaMap,e.transparent=r.transparent||r.transmission>0||r.transmissionNode&&r.transmissionNode.isNode||r.backdropNode&&r.backdropNode.isNode,e.isShadowPassMaterial){const{colorNode:t,depthNode:n,positionNode:i}=this._getShadowNodes(r);3===this.shadowMap.type?e.side=null!==r.shadowSide?r.shadowSide:r.side:e.side=null!==r.shadowSide?r.shadowSide:iN[r.side],null!==t&&(e.colorNode=t),null!==n&&(e.depthNode=n),null!==i&&(e.positionNode=i)}r=e}!0===r.transparent&&2===r.side&&!1===r.forceSinglePass?(r.side=1,this._handleObjectFunction(e,r,t,n,a,s,o,"backSide"),r.side=0,this._handleObjectFunction(e,r,t,n,a,s,o,l),r.side=2):this._handleObjectFunction(e,r,t,n,a,s,o,l),p&&(t.overrideMaterial.colorNode=u,t.overrideMaterial.depthNode=c,t.overrideMaterial.positionNode=h,t.overrideMaterial.side=d),e.onAfterRender(this,t,n,i,r,s)}hasCompatibility(e){return this.backend.hasCompatibility(e)}_renderObjectDirect(e,t,n,i,r,s,a,o){const l=this._objects.get(e,t,n,i,r,this._currentRenderContext,a,o);if(l.drawRange=e.geometry.drawRange,l.group=s,null!==this._currentRenderBundle){this.backend.get(this._currentRenderBundle).renderObjects.push(l),l.bundle=this._currentRenderBundle.bundleGroup}const u=this._nodes.needsRefresh(l);u&&(this._nodes.updateBefore(l),this._geometries.updateForRender(l),this._nodes.updateForRender(l),this._bindings.updateForRender(l)),this._pipelines.updateForRender(l),this.backend.draw(l,this.info),u&&this._nodes.updateAfter(l)}_createObjectPipeline(e,t,n,i,r,s,a,o){const l=this._objects.get(e,t,n,i,r,this._currentRenderContext,a,o);l.drawRange=e.geometry.drawRange,l.group=s,this._nodes.updateBefore(l),this._geometries.updateForRender(l),this._nodes.updateForRender(l),this._bindings.updateForRender(l),this._pipelines.getForRender(l,this._compilationPromises),this._nodes.updateAfter(l)}_onCanvasTargetResize(){this._initialized&&this.backend.updateSize()}get compile(){return this.compileAsync}}class sN{constructor(e=""){this.name=e,this.visibility=0}setVisibility(e){this.visibility|=e}getVisibility(){return this.visibility}clone(){return Object.assign(new this.constructor,this)}}class aN extends sN{constructor(e,t=null){super(e),this.isBuffer=!0,this.bytesPerElement=Float32Array.BYTES_PER_ELEMENT,this._buffer=t,this._updateRanges=[]}get updateRanges(){return this._updateRanges}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}get byteLength(){return(e=this._buffer.byteLength)+(_w-e%_w)%_w;var e}get buffer(){return this._buffer}update(){return!0}}class oN extends aN{constructor(e,t=null){super(e,t),this.isUniformBuffer=!0}}let lN=0;class uN extends oN{constructor(e,t){super("UniformBuffer_"+lN++,e?e.value:null),this.nodeUniform=e,this.groupNode=t,this.isNodeUniformBuffer=!0}set updateRanges(e){this.nodeUniform.updateRanges=e}get updateRanges(){return this.nodeUniform.updateRanges}addUpdateRange(e,t){this.nodeUniform.addUpdateRange(e,t)}clearUpdateRanges(){this.nodeUniform.clearUpdateRanges()}get buffer(){return this.nodeUniform.value}}class cN extends oN{constructor(e){super(e),this.isUniformsGroup=!0,this._values=null,this.uniforms=[],this._updateRangeCache=new Map}addUniformUpdateRange(e){const t=e.index;if(!0!==this._updateRangeCache.has(t)){const n=this.updateRanges,i={start:e.offset,count:e.itemSize};n.push(i),this._updateRangeCache.set(t,i)}}clearUpdateRanges(){this._updateRangeCache.clear(),super.clearUpdateRanges()}addUniform(e){return this.uniforms.push(e),this}removeUniform(e){const t=this.uniforms.indexOf(e);return-1!==t&&this.uniforms.splice(t,1),this}get values(){return null===this._values&&(this._values=Array.from(this.buffer)),this._values}get buffer(){let e=this._buffer;if(null===e){const t=this.byteLength;e=new Float32Array(new ArrayBuffer(t)),this._buffer=e}return e}get byteLength(){const e=this.bytesPerElement;let t=0;for(let n=0,i=this.uniforms.length;n{this.generation=null,this.version=-1},this.texture=t,this.version=t?t.version:-1,this.generation=null,this.samplerKey="",this.isSampler=!0}set texture(e){this._texture!==e&&(this._texture&&this._texture.removeEventListener("dispose",this._onTextureDispose),this._texture=e,this.generation=null,this.version=-1,this._texture&&this._texture.addEventListener("dispose",this._onTextureDispose))}get texture(){return this._texture}update(){const{texture:e,version:t}=this;return t!==e.version&&(this.version=e.version,!0)}clone(){const e=super.clone();return e._texture=null,e._onTextureDispose=()=>{e.generation=null,e.version=-1},e.texture=this.texture,e}}let fN=0;class mN extends pN{constructor(e,t){super(e,t),this.id=fN++,this.store=!1,this.mipLevel=0,this.isSampledTexture=!0}}class gN extends mN{constructor(e,t,n,i=null){super(e,t?t.value:null),this.textureNode=t,this.groupNode=n,this.access=i}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}}class _N extends gN{constructor(e,t,n,i=null){super(e,t,n,i),this.isSampledCubeTexture=!0}}class vN extends gN{constructor(e,t,n,i=null){super(e,t,n,i),this.isSampledTexture3D=!0}}const yN={bitcast_int_uint:new AA("uint tsl_bitcast_int_to_uint ( int x ) { return floatBitsToUint( intBitsToFloat ( x ) ); }"),bitcast_uint_int:new AA("uint tsl_bitcast_uint_to_int ( uint x ) { return floatBitsToInt( uintBitsToFloat ( x ) ); }")},bN={textureDimensions:"textureSize",equals:"equal",bitcast_float_int:"floatBitsToInt",bitcast_int_float:"intBitsToFloat",bitcast_uint_float:"uintBitsToFloat",bitcast_float_uint:"floatBitsToUint",bitcast_uint_int:"tsl_bitcast_uint_to_int",bitcast_int_uint:"tsl_bitcast_int_to_uint",floatpack_snorm_2x16:"packSnorm2x16",floatpack_unorm_2x16:"packUnorm2x16",floatpack_float16_2x16:"packHalf2x16",floatunpack_snorm_2x16:"unpackSnorm2x16",floatunpack_unorm_2x16:"unpackUnorm2x16",floatunpack_float16_2x16:"unpackHalf2x16"},xN={low:"lowp",medium:"mediump",high:"highp"},TN={swizzleAssign:!0,storageBuffer:!1},SN={perspective:"smooth",linear:"noperspective"},MN={centroid:"centroid"},EN="\nprecision highp float;\nprecision highp int;\nprecision highp sampler2D;\nprecision highp sampler3D;\nprecision highp samplerCube;\nprecision highp sampler2DArray;\n\nprecision highp usampler2D;\nprecision highp usampler3D;\nprecision highp usamplerCube;\nprecision highp usampler2DArray;\n\nprecision highp isampler2D;\nprecision highp isampler3D;\nprecision highp isamplerCube;\nprecision highp isampler2DArray;\n\nprecision highp sampler2DShadow;\nprecision highp sampler2DArrayShadow;\nprecision highp samplerCubeShadow;\n";class wN extends rC{constructor(e,t){super(e,t,new EC),this.uniformGroups={},this.transforms=[],this.extensions={},this.builtins={vertex:[],fragment:[],compute:[]}}needsToWorkingColorSpace(e){return!0===e.isVideoTexture&&e.colorSpace!==yt}_include(e){const t=yN[e];return t.build(this),this.addInclude(t),t}getMethod(e){return void 0!==yN[e]&&this._include(e),bN[e]||e}getBitcastMethod(e,t){return this.getMethod(`bitcast_${t}_${e}`)}getFloatPackingMethod(e){return this.getMethod(`floatpack_${e}_2x16`)}getFloatUnpackingMethod(e){return this.getMethod(`floatunpack_${e}_2x16`)}getTernary(e,t,n){return`${e} ? ${t} : ${n}`}getOutputStructName(){return""}buildFunctionCode(e){const t=e.layout,n=this.flowShaderNode(e),i=[];for(const e of t.inputs)i.push(this.getType(e.type)+" "+e.name);return`${this.getType(t.type)} ${t.name}( ${i.join(", ")} ) {\n\n\t${n.vars}\n\n${n.code}\n\treturn ${n.result};\n\n}`}setupPBO(e){const t=e.value;if(void 0===t.pbo){const e=t.array,n=t.count*t.itemSize,{itemSize:i}=t,r=t.array.constructor.name.toLowerCase().includes("int");let s=r?De:Le;2===i?s=r?Ue:Ie:3===i?s=r?1032:Re:4===i&&(s=r?Fe:Ce);const a={Float32Array:be,Uint8Array:fe,Uint16Array:_e,Uint32Array:ye,Int8Array:me,Int16Array:ge,Int32Array:ve,Uint8ClampedArray:fe},o=Math.pow(2,Math.ceil(Math.log2(Math.sqrt(n/i))));let l=Math.ceil(n/i/o);o*l*i0?r:"";t=`${n.name} {\n\t${i} ${e.name}[${s}];\n};\n`}else{const t=e.groupNode.name;if(void 0===i[t]){const e=this.uniformGroups[t];if(void 0!==e){const n=[];for(const t of e.uniforms){const e=t.getType(),i=this.getVectorType(e),r=t.nodeUniform.node.precision;let s=`${i} ${t.name};`;null!==r&&(s=xN[r]+" "+s),n.push("\t"+s)}i[t]=n}}r=!0}if(!r){const i=e.node.precision;null!==i&&(t=xN[i]+" "+t),t="uniform "+t,n.push(t)}}let r="";for(const e in i){const t=i[e];r+=this._getGLSLUniformStruct(e,t.join("\n"))+"\n"}return r+=n.join("\n"),r}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==ve){let n=e;e.isInterleavedBufferAttribute&&(n=e.data);const i=n.array;!1==(i instanceof Uint32Array||i instanceof Int32Array)&&(t=t.slice(1))}return t}getAttributes(e){let t="";if("vertex"===e||"compute"===e){const e=this.getAttributesArray();let n=0;for(const i of e)t+=`layout( location = ${n++} ) in ${i.type} ${i.name};\n`}return t}getStructMembers(e){const t=[];for(const n of e.members)t.push(`\t${n.type} ${n.name};`);return t.join("\n")}getStructs(e){const t=[],n=this.structs[e],i=[];for(const e of n)if(e.output)for(const t of e.members)i.push(`layout( location = ${t.index} ) out ${t.type} ${t.name};`);else{let n="struct "+e.name+" {\n";n+=this.getStructMembers(e),n+="\n};\n",t.push(n)}return 0===i.length&&i.push("layout( location = 0 ) out vec4 fragColor;"),"\n"+i.join("\n")+"\n\n"+t.join("\n")}getVaryings(e){let t="";const n=this.varyings;if("vertex"===e||"compute"===e)for(const i of n){"compute"===e&&(i.needsInterpolation=!0);const n=this.getType(i.type);if(i.needsInterpolation)if(i.interpolationType){t+=`${SN[i.interpolationType]||i.interpolationType} ${MN[i.interpolationSampling]||""} out ${n} ${i.name};\n`}else{t+=`${n.includes("int")||n.includes("uv")||n.includes("iv")?"flat ":""}out ${n} ${i.name};\n`}else t+=`${n} ${i.name};\n`}else if("fragment"===e)for(const e of n)if(e.needsInterpolation){const n=this.getType(e.type);if(e.interpolationType){t+=`${SN[e.interpolationType]||e.interpolationType} ${MN[e.interpolationSampling]||""} in ${n} ${e.name};\n`}else{t+=`${n.includes("int")||n.includes("uv")||n.includes("iv")?"flat ":""}in ${n} ${e.name};\n`}}for(const n of this.builtins[e])t+=`${n};\n`;return t}getVertexIndex(){return"uint( gl_VertexID )"}getInstanceIndex(){return"uint( gl_InstanceID )"}getInvocationLocalIndex(){return`uint( gl_InstanceID ) % ${this.object.workgroupSize.reduce((e,t)=>e*t,1)}u`}getSubgroupSize(){qt("GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node")}getInvocationSubgroupIndex(){qt("GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node")}getSubgroupIndex(){qt("GLSLNodeBuilder: WebGLBackend does not support the subgroupIndex node")}getDrawIndex(){return this.renderer.backend.extensions.has("WEBGL_multi_draw")?"uint( gl_DrawID )":null}getFrontFacing(){return"gl_FrontFacing"}getFragCoord(){return"gl_FragCoord.xy"}getFragDepth(){return"gl_FragDepth"}enableExtension(e,t,n=this.shaderStage){const i=this.extensions[n]||(this.extensions[n]=new Map);!1===i.has(e)&&i.set(e,{name:e,behavior:t})}getExtensions(e){const t=[];if("vertex"===e){const t=this.renderer.backend.extensions;this.object.isBatchedMesh&&t.has("WEBGL_multi_draw")&&this.enableExtension("GL_ANGLE_multi_draw","require",e)}const n=this.extensions[e];if(void 0!==n)for(const{name:e,behavior:i}of n.values())t.push(`#extension ${e} : ${i}`);return t.join("\n")}getClipDistance(){return"gl_ClipDistance"}isAvailable(e){let t=TN[e];if(void 0===t){let n;switch(t=!1,e){case"float32Filterable":n="OES_texture_float_linear";break;case"clipDistance":n="WEBGL_clip_cull_distance"}if(void 0!==n){const e=this.renderer.backend.extensions;e.has(n)&&(e.get(n),t=!0)}TN[e]=t}return t}isFlipY(){return!0}getUniformBufferLimit(){const e=this.renderer.backend.gl;return e.getParameter(e.MAX_UNIFORM_BLOCK_SIZE)}enableHardwareClipping(e){this.enableExtension("GL_ANGLE_clip_cull_distance","require"),this.builtins.vertex.push(`out float gl_ClipDistance[ ${e} ]`)}enableMultiview(){this.enableExtension("GL_OVR_multiview2","require","fragment"),this.enableExtension("GL_OVR_multiview2","require","vertex"),this.builtins.vertex.push("layout(num_views = 2) in")}registerTransform(e,t){this.transforms.push({varyingName:e,attributeNode:t})}getTransforms(){const e=this.transforms;let t="";for(let n=0;n0&&(n+="\n"),n+=`\t// flow -> ${s}\n\t`),n+=`${i.code}\n\t`,e===r&&"compute"!==t&&(n+="// result\n\t","vertex"===t?(n+="gl_Position = ",n+=`${i.result};`):"fragment"===t&&(e.outputNode.isOutputStructNode||(n+="fragColor = ",n+=`${i.result};`)))}const s=e[t];s.extensions=this.getExtensions(t),s.uniforms=this.getUniforms(t),s.attributes=this.getAttributes(t),s.varyings=this.getVaryings(t),s.vars=this.getVars(t),s.structs=this.getStructs(t),s.codes=this.getCodes(t),s.transforms=this.getTransforms(t),s.flow=n}null!==this.material?(this.vertexShader=this._getGLSLVertexCode(e.vertex),this.fragmentShader=this._getGLSLFragmentCode(e.fragment)):this.computeShader=this._getGLSLVertexCode(e.compute)}getUniformFromNode(e,t,n,i=null){const r=super.getUniformFromNode(e,t,n,i),s=this.getDataFromNode(e,n,this.globalCache);let a=s.uniformGPU;if(void 0===a){const i=e.groupNode,o=i.name,l=this.getBindGroupArray(o,n);if("texture"===t)a=new gN(r.name,r.node,i),l.push(a);else if("cubeTexture"===t||"cubeDepthTexture"===t)a=new _N(r.name,r.node,i),l.push(a);else if("texture3D"===t)a=new vN(r.name,r.node,i),l.push(a);else if("buffer"===t){r.name=`buffer${e.id}`;const t=this.getSharedDataFromNode(e);let n=t.buffer;void 0===n&&(e.name=`NodeBuffer_${e.id}`,n=new uN(e,i),n.name=e.name,t.buffer=n),l.push(n),a=n}else{let e=this.uniformGroups[o];void 0===e?(e=new dN(o,i),this.uniformGroups[o]=e,l.push(e)):-1===l.indexOf(e)&&l.push(e),a=this.getNodeUniform(r,t);const n=a.name,s=e.uniforms.some(e=>e.name===n);s||e.addUniform(a)}s.uniformGPU=a}return r}}let AN=null,RN=null;class CN{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null,this.timestampQueryPool={[kt]:null,[Bt]:null},this.trackTimestamp=!0===e.trackTimestamp}async init(e){this.renderer=e}get coordinateSystem(){}beginRender(){}finishRender(){}beginCompute(){}finishCompute(){}draw(){}compute(){}createProgram(){}destroyProgram(){}createBindings(){}updateBindings(){}updateBinding(){}createRenderPipeline(){}createComputePipeline(){}needsRenderUpdate(){}getRenderCacheKey(){}createNodeBuilder(){}updateSampler(){}createDefaultTexture(){}createTexture(){}updateTexture(){}generateMipmaps(){}destroyTexture(){}async copyTextureToBuffer(){}copyTextureToTexture(){}copyFramebufferToTexture(){}createAttribute(){}createIndexAttribute(){}createStorageAttribute(){}updateAttribute(){}destroyAttribute(){}getContext(){}updateSize(){}updateViewport(){}updateTimeStampUID(e){const t=this.get(e),n=this.renderer.info.frame;let i;i=!0===e.isComputeNode?"c:"+this.renderer.info.compute.frameCalls:"r:"+this.renderer.info.render.frameCalls,t.timestampUID=i+":"+e.id+":f"+n}getTimestampUID(e){return this.get(e).timestampUID}getTimestampFrames(e){const t=this.timestampQueryPool[e];return t?t.getTimestampFrames():[]}_getQueryPool(e){const t=e.startsWith("c:")?Bt:kt;return this.timestampQueryPool[t]}getTimestamp(e){return this._getQueryPool(e).getTimestamp(e)}hasTimestamp(e){return this._getQueryPool(e).hasTimestamp(e)}isOccluded(){}async resolveTimestampsAsync(e="render"){if(!this.trackTimestamp)return void Yt("WebGPURenderer: Timestamp tracking is disabled.");const t=this.timestampQueryPool[e];if(!t)return;const n=await t.resolveQueriesAsync();return this.renderer.info[e].timestamp=n,n}async getArrayBufferAsync(){}async hasFeatureAsync(){}hasFeature(){}getMaxAnisotropy(){}getDrawingBufferSize(){return AN=AN||new cn,this.renderer.getDrawingBufferSize(AN)}setScissorTest(){}getClearColor(){const e=this.renderer;return RN=RN||new Hw,e.getClearColor(RN),RN.getRGB(RN),RN}getDomElement(){let e=this.domElement;return null===e&&(e=void 0!==this.parameters.canvas?this.parameters.canvas:Ht(),"setAttribute"in e&&e.setAttribute("data-engine",`three.js r${s} webgpu`),this.domElement=e),e}hasCompatibility(){return!1}initRenderTarget(){}set(e,t){this.data.set(e,t)}get(e){let t=this.data.get(e);return void 0===t&&(t={},this.data.set(e,t)),t}has(e){return this.data.has(e)}delete(e){this.data.delete(e)}deleteBindGroupData(){}dispose(){}}let NN,PN,LN=0;class DN{constructor(e,t){this.buffers=[e.bufferGPU,t],this.type=e.type,this.bufferType=e.bufferType,this.pbo=e.pbo,this.byteLength=e.byteLength,this.bytesPerElement=e.BYTES_PER_ELEMENT,this.version=e.version,this.isInteger=e.isInteger,this.activeBufferIndex=0,this.baseId=e.id}get id(){return`${this.baseId}|${this.activeBufferIndex}`}get bufferGPU(){return this.buffers[this.activeBufferIndex]}get transformBuffer(){return this.buffers[1^this.activeBufferIndex]}switchBuffers(){this.activeBufferIndex^=1}}class IN{constructor(e){this.backend=e}createAttribute(e,t){const n=this.backend,{gl:i}=n,r=e.array,s=e.usage||i.STATIC_DRAW,a=e.isInterleavedBufferAttribute?e.data:e,o=n.get(a);let l,u=o.bufferGPU;if(void 0===u&&(u=this._createBuffer(i,t,r,s),o.bufferGPU=u,o.bufferType=t,o.version=a.version),r instanceof Float32Array)l=i.FLOAT;else if("undefined"!=typeof Float16Array&&r instanceof Float16Array)l=i.HALF_FLOAT;else if(r instanceof Uint16Array)l=e.isFloat16BufferAttribute?i.HALF_FLOAT:i.UNSIGNED_SHORT;else if(r instanceof Int16Array)l=i.SHORT;else if(r instanceof Uint32Array)l=i.UNSIGNED_INT;else if(r instanceof Int32Array)l=i.INT;else if(r instanceof Int8Array)l=i.BYTE;else if(r instanceof Uint8Array)l=i.UNSIGNED_BYTE;else{if(!(r instanceof Uint8ClampedArray))throw new Error("THREE.WebGLBackend: Unsupported buffer data format: "+r);l=i.UNSIGNED_BYTE}let c={bufferGPU:u,bufferType:t,type:l,byteLength:r.byteLength,bytesPerElement:r.BYTES_PER_ELEMENT,version:e.version,pbo:e.pbo,isInteger:l===i.INT||l===i.UNSIGNED_INT||e.gpuType===ve,id:LN++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const e=this._createBuffer(i,t,r,s);c=new DN(c,e)}n.set(e,c)}updateAttribute(e){const t=this.backend,{gl:n}=t,i=e.array,r=e.isInterleavedBufferAttribute?e.data:e,s=t.get(r),a=s.bufferType,o=e.isInterleavedBufferAttribute?e.data.updateRanges:e.updateRanges;if(n.bindBuffer(a,s.bufferGPU),0===o.length)n.bufferSubData(a,0,i);else{for(let e=0,t=o.length;e0?this.enable(i.SAMPLE_ALPHA_TO_COVERAGE):this.disable(i.SAMPLE_ALPHA_TO_COVERAGE),n>0&&this.currentClippingPlanes!==n){const e=12288;for(let t=0;t<8;t++)t{!function r(){const s=e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0);if(s===e.WAIT_FAILED)return e.deleteSync(t),void i();s!==e.TIMEOUT_EXPIRED?(e.deleteSync(t),n()):requestAnimationFrame(r)}()})}}let ON,BN,kN,zN=!1;class VN{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},this._srcFramebuffer=null,this._dstFramebuffer=null,!1===zN&&(this._init(),zN=!0)}_init(){const e=this.gl;ON={[se]:e.REPEAT,[ae]:e.CLAMP_TO_EDGE,[oe]:e.MIRRORED_REPEAT},BN={[le]:e.NEAREST,[ue]:e.NEAREST_MIPMAP_NEAREST,[ce]:e.NEAREST_MIPMAP_LINEAR,[he]:e.LINEAR,[de]:e.LINEAR_MIPMAP_NEAREST,[pe]:e.LINEAR_MIPMAP_LINEAR},kN={[Et]:e.NEVER,[Lt]:e.ALWAYS,[wt]:e.LESS,[Rt]:e.LEQUAL,[At]:e.EQUAL,[Pt]:e.GEQUAL,[Ct]:e.GREATER,[Nt]:e.NOTEQUAL}}getGLTextureType(e){const{gl:t}=this;let n;return n=!0===e.isCubeTexture?t.TEXTURE_CUBE_MAP:!0===e.isArrayTexture||!0===e.isDataArrayTexture||!0===e.isCompressedArrayTexture?t.TEXTURE_2D_ARRAY:!0===e.isData3DTexture?t.TEXTURE_3D:t.TEXTURE_2D,n}getInternalFormat(e,t,n,i,r=!1){const{gl:s,extensions:a}=this;if(null!==e){if(void 0!==s[e])return s[e];Xt("WebGLBackend: Attempt to use non-existing WebGL internal format '"+e+"'")}let o=t;if(t===s.RED&&(n===s.FLOAT&&(o=s.R32F),n===s.HALF_FLOAT&&(o=s.R16F),n===s.UNSIGNED_BYTE&&(o=s.R8),n===s.UNSIGNED_SHORT&&(o=s.R16),n===s.UNSIGNED_INT&&(o=s.R32UI),n===s.BYTE&&(o=s.R8I),n===s.SHORT&&(o=s.R16I),n===s.INT&&(o=s.R32I)),t===s.RED_INTEGER&&(n===s.UNSIGNED_BYTE&&(o=s.R8UI),n===s.UNSIGNED_SHORT&&(o=s.R16UI),n===s.UNSIGNED_INT&&(o=s.R32UI),n===s.BYTE&&(o=s.R8I),n===s.SHORT&&(o=s.R16I),n===s.INT&&(o=s.R32I)),t===s.RG&&(n===s.FLOAT&&(o=s.RG32F),n===s.HALF_FLOAT&&(o=s.RG16F),n===s.UNSIGNED_BYTE&&(o=s.RG8),n===s.UNSIGNED_SHORT&&(o=s.RG16),n===s.UNSIGNED_INT&&(o=s.RG32UI),n===s.BYTE&&(o=s.RG8I),n===s.SHORT&&(o=s.RG16I),n===s.INT&&(o=s.RG32I)),t===s.RG_INTEGER&&(n===s.UNSIGNED_BYTE&&(o=s.RG8UI),n===s.UNSIGNED_SHORT&&(o=s.RG16UI),n===s.UNSIGNED_INT&&(o=s.RG32UI),n===s.BYTE&&(o=s.RG8I),n===s.SHORT&&(o=s.RG16I),n===s.INT&&(o=s.RG32I)),t===s.RGB){const e=r?Tt:bn.getTransfer(i);n===s.FLOAT&&(o=s.RGB32F),n===s.HALF_FLOAT&&(o=s.RGB16F),n===s.UNSIGNED_BYTE&&(o=s.RGB8),n===s.UNSIGNED_SHORT&&(o=s.RGB16),n===s.UNSIGNED_INT&&(o=s.RGB32UI),n===s.BYTE&&(o=s.RGB8I),n===s.SHORT&&(o=s.RGB16I),n===s.INT&&(o=s.RGB32I),n===s.UNSIGNED_BYTE&&(o=e===St?s.SRGB8:s.RGB8),n===s.UNSIGNED_SHORT_5_6_5&&(o=s.RGB565),n===s.UNSIGNED_SHORT_5_5_5_1&&(o=s.RGB5_A1),n===s.UNSIGNED_SHORT_4_4_4_4&&(o=s.RGB4),n===s.UNSIGNED_INT_5_9_9_9_REV&&(o=s.RGB9_E5),n===s.UNSIGNED_INT_10F_11F_11F_REV&&(o=s.R11F_G11F_B10F)}if(t===s.RGB_INTEGER&&(n===s.UNSIGNED_BYTE&&(o=s.RGB8UI),n===s.UNSIGNED_SHORT&&(o=s.RGB16UI),n===s.UNSIGNED_INT&&(o=s.RGB32UI),n===s.BYTE&&(o=s.RGB8I),n===s.SHORT&&(o=s.RGB16I),n===s.INT&&(o=s.RGB32I)),t===s.RGBA){const e=r?Tt:bn.getTransfer(i);n===s.FLOAT&&(o=s.RGBA32F),n===s.HALF_FLOAT&&(o=s.RGBA16F),n===s.UNSIGNED_BYTE&&(o=s.RGBA8),n===s.UNSIGNED_SHORT&&(o=s.RGBA16),n===s.UNSIGNED_INT&&(o=s.RGBA32UI),n===s.BYTE&&(o=s.RGBA8I),n===s.SHORT&&(o=s.RGBA16I),n===s.INT&&(o=s.RGBA32I),n===s.UNSIGNED_BYTE&&(o=e===St?s.SRGB8_ALPHA8:s.RGBA8),n===s.UNSIGNED_SHORT_4_4_4_4&&(o=s.RGBA4),n===s.UNSIGNED_SHORT_5_5_5_1&&(o=s.RGB5_A1)}return t===s.RGBA_INTEGER&&(n===s.UNSIGNED_BYTE&&(o=s.RGBA8UI),n===s.UNSIGNED_SHORT&&(o=s.RGBA16UI),n===s.UNSIGNED_INT&&(o=s.RGBA32UI),n===s.BYTE&&(o=s.RGBA8I),n===s.SHORT&&(o=s.RGBA16I),n===s.INT&&(o=s.RGBA32I)),t===s.DEPTH_COMPONENT&&(n===s.UNSIGNED_SHORT&&(o=s.DEPTH_COMPONENT16),n===s.UNSIGNED_INT&&(o=s.DEPTH_COMPONENT24),n===s.FLOAT&&(o=s.DEPTH_COMPONENT32F)),t===s.DEPTH_STENCIL&&n===s.UNSIGNED_INT_24_8&&(o=s.DEPTH24_STENCIL8),o!==s.R16F&&o!==s.R32F&&o!==s.RG16F&&o!==s.RG32F&&o!==s.RGBA16F&&o!==s.RGBA32F||a.get("EXT_color_buffer_float"),o}setTextureParameters(e,t){const{gl:n,extensions:i,backend:r}=this,s=bn.getPrimaries(bn.workingColorSpace),a=t.colorSpace===yt?null:bn.getPrimaries(t.colorSpace),o=t.colorSpace===yt||s===a?n.NONE:n.BROWSER_DEFAULT_WEBGL;n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,t.flipY),n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),n.pixelStorei(n.UNPACK_ALIGNMENT,t.unpackAlignment),n.pixelStorei(n.UNPACK_COLORSPACE_CONVERSION_WEBGL,o),n.texParameteri(e,n.TEXTURE_WRAP_S,ON[t.wrapS]),n.texParameteri(e,n.TEXTURE_WRAP_T,ON[t.wrapT]),e!==n.TEXTURE_3D&&e!==n.TEXTURE_2D_ARRAY||t.isArrayTexture||n.texParameteri(e,n.TEXTURE_WRAP_R,ON[t.wrapR]),n.texParameteri(e,n.TEXTURE_MAG_FILTER,BN[t.magFilter]);const l=void 0!==t.mipmaps&&t.mipmaps.length>0,u=t.minFilter===he&&l?pe:t.minFilter;if(n.texParameteri(e,n.TEXTURE_MIN_FILTER,BN[u]),t.compareFunction&&(n.texParameteri(e,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE),n.texParameteri(e,n.TEXTURE_COMPARE_FUNC,kN[t.compareFunction])),!0===i.has("EXT_texture_filter_anisotropic")){if(t.magFilter===le)return;if(t.minFilter!==ce&&t.minFilter!==pe)return;if(t.type===be&&!1===i.has("OES_texture_float_linear"))return;if(t.anisotropy>1){const s=i.get("EXT_texture_filter_anisotropic");n.texParameterf(e,s.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(t.anisotropy,r.getMaxAnisotropy()))}}}createDefaultTexture(e){const{gl:t,backend:n,defaultTextures:i}=this,r=this.getGLTextureType(e);let s=i[r];void 0===s&&(s=t.createTexture(),n.state.bindTexture(r,s),t.texParameteri(r,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(r,t.TEXTURE_MAG_FILTER,t.NEAREST),i[r]=s),n.set(e,{textureGPU:s,glTextureType:r})}createTexture(e,t){const{gl:n,backend:i}=this,{levels:r,width:s,height:a,depth:o}=t,l=i.utils.convert(e.format,e.colorSpace),u=i.utils.convert(e.type),c=this.getInternalFormat(e.internalFormat,l,u,e.colorSpace,e.isVideoTexture),h=n.createTexture(),d=this.getGLTextureType(e);i.state.bindTexture(d,h),this.setTextureParameters(d,e),e.isArrayTexture||e.isDataArrayTexture||e.isCompressedArrayTexture?n.texStorage3D(n.TEXTURE_2D_ARRAY,r,c,s,a,o):e.isData3DTexture?n.texStorage3D(n.TEXTURE_3D,r,c,s,a,o):e.isVideoTexture||n.texStorage2D(d,r,c,s,a),i.set(e,{textureGPU:h,glTextureType:d,glFormat:l,glType:u,glInternalFormat:c})}copyBufferToTexture(e,t){const{gl:n,backend:i}=this,{textureGPU:r,glTextureType:s,glFormat:a,glType:o}=i.get(t),{width:l,height:u}=t.source.data;n.bindBuffer(n.PIXEL_UNPACK_BUFFER,e),i.state.bindTexture(s,r),n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,!1),n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),n.texSubImage2D(s,0,0,0,l,u,a,o,0),n.bindBuffer(n.PIXEL_UNPACK_BUFFER,null),i.state.unbindTexture()}updateTexture(e,t){const{gl:n}=this,{width:i,height:r}=t,{textureGPU:s,glTextureType:a,glFormat:o,glType:l,glInternalFormat:u}=this.backend.get(e);if(!e.isRenderTargetTexture&&void 0!==s)if(this.backend.state.bindTexture(a,s),this.setTextureParameters(a,e),e.isCompressedTexture){const i=e.mipmaps,r=t.image;for(let t=0;t0){const t=qa(i.width,i.height,e.format,e.type);for(const r of e.layerUpdates){const e=i.data.subarray(r*t/i.data.BYTES_PER_ELEMENT,(r+1)*t/i.data.BYTES_PER_ELEMENT);n.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,r,i.width,i.height,1,o,l,e)}e.clearLayerUpdates()}else n.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,0,i.width,i.height,i.depth,o,l,i.data)}else if(e.isData3DTexture){const e=t.image;n.texSubImage3D(n.TEXTURE_3D,0,0,0,0,e.width,e.height,e.depth,o,l,e.data)}else if(e.isVideoTexture)e.update(),n.texImage2D(a,0,u,o,l,t.image);else{const s=e.mipmaps;if(s.length>0)for(let e=0,t=s.length;e0,h=t.renderTarget?t.renderTarget.height:this.backend.getDrawingBufferSize().y;if(c){const n=0!==a||0!==o;let c,d;if(!0===e.isDepthTexture?(c=i.DEPTH_BUFFER_BIT,d=i.DEPTH_ATTACHMENT,t.stencil&&(c|=i.STENCIL_BUFFER_BIT)):(c=i.COLOR_BUFFER_BIT,d=i.COLOR_ATTACHMENT0),n){const e=this.backend.get(t.renderTarget),n=e.framebuffers[t.getCacheKey()],d=e.msaaFrameBuffer;r.bindFramebuffer(i.DRAW_FRAMEBUFFER,n),r.bindFramebuffer(i.READ_FRAMEBUFFER,d);const p=h-o-u;i.blitFramebuffer(a,p,a+l,p+u,a,p,a+l,p+u,c,i.NEAREST),r.bindFramebuffer(i.READ_FRAMEBUFFER,n),r.bindTexture(i.TEXTURE_2D,s),i.copyTexSubImage2D(i.TEXTURE_2D,0,0,0,a,p,l,u),r.unbindTexture()}else{const e=i.createFramebuffer();r.bindFramebuffer(i.DRAW_FRAMEBUFFER,e),i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,d,i.TEXTURE_2D,s,0),i.blitFramebuffer(0,0,l,u,0,0,l,u,c,i.NEAREST),i.deleteFramebuffer(e)}}else r.bindTexture(i.TEXTURE_2D,s),i.copyTexSubImage2D(i.TEXTURE_2D,0,0,0,a,h-u-o,l,u),r.unbindTexture();e.generateMipmaps&&this.generateMipmaps(e),this.backend._setFramebuffer(t)}setupRenderBufferStorage(e,t,n,i=!1){const{gl:r}=this,s=t.renderTarget,{depthTexture:a,depthBuffer:o,stencilBuffer:l,width:u,height:c}=s;if(r.bindRenderbuffer(r.RENDERBUFFER,e),o&&!l){let t=r.DEPTH_COMPONENT24;if(!0===i){this.extensions.get("WEBGL_multisampled_render_to_texture").renderbufferStorageMultisampleEXT(r.RENDERBUFFER,s.samples,t,u,c)}else n>0?(a&&a.isDepthTexture&&a.type===r.FLOAT&&(t=r.DEPTH_COMPONENT32F),r.renderbufferStorageMultisample(r.RENDERBUFFER,n,t,u,c)):r.renderbufferStorage(r.RENDERBUFFER,t,u,c);r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.RENDERBUFFER,e)}else o&&l&&(n>0?r.renderbufferStorageMultisample(r.RENDERBUFFER,n,r.DEPTH24_STENCIL8,u,c):r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_STENCIL,u,c),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_STENCIL_ATTACHMENT,r.RENDERBUFFER,e));r.bindRenderbuffer(r.RENDERBUFFER,null)}async copyTextureToBuffer(e,t,n,i,r,s){const{backend:a,gl:o}=this,{textureGPU:l,glFormat:u,glType:c}=this.backend.get(e),h=o.createFramebuffer();a.state.bindFramebuffer(o.READ_FRAMEBUFFER,h);const d=e.isCubeTexture?o.TEXTURE_CUBE_MAP_POSITIVE_X+s:o.TEXTURE_2D;o.framebufferTexture2D(o.READ_FRAMEBUFFER,o.COLOR_ATTACHMENT0,d,l,0);const p=this._getTypedArrayType(c),f=i*r*this._getBytesPerTexel(c,u),m=o.createBuffer();o.bindBuffer(o.PIXEL_PACK_BUFFER,m),o.bufferData(o.PIXEL_PACK_BUFFER,f,o.STREAM_READ),o.readPixels(t,n,i,r,u,c,0),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),await a.utils._clientWaitAsync();const g=new p(f/p.BYTES_PER_ELEMENT);return o.bindBuffer(o.PIXEL_PACK_BUFFER,m),o.getBufferSubData(o.PIXEL_PACK_BUFFER,0,g),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),a.state.bindFramebuffer(o.READ_FRAMEBUFFER,null),o.deleteFramebuffer(h),g}_getTypedArrayType(e){const{gl:t}=this;if(e===t.UNSIGNED_BYTE)return Uint8Array;if(e===t.UNSIGNED_SHORT_4_4_4_4)return Uint16Array;if(e===t.UNSIGNED_SHORT_5_5_5_1)return Uint16Array;if(e===t.UNSIGNED_SHORT_5_6_5)return Uint16Array;if(e===t.UNSIGNED_SHORT)return Uint16Array;if(e===t.UNSIGNED_INT)return Uint32Array;if(e===t.HALF_FLOAT)return Uint16Array;if(e===t.FLOAT)return Float32Array;throw new Error(`Unsupported WebGL type: ${e}`)}_getBytesPerTexel(e,t){const{gl:n}=this;let i=0;return e===n.UNSIGNED_BYTE&&(i=1),e!==n.UNSIGNED_SHORT_4_4_4_4&&e!==n.UNSIGNED_SHORT_5_5_5_1&&e!==n.UNSIGNED_SHORT_5_6_5&&e!==n.UNSIGNED_SHORT&&e!==n.HALF_FLOAT||(i=2),e!==n.UNSIGNED_INT&&e!==n.FLOAT||(i=4),t===n.RGBA?4*i:t===n.RGB?3*i:t===n.ALPHA?i:void 0}dispose(){const{gl:e}=this;null!==this._srcFramebuffer&&e.deleteFramebuffer(this._srcFramebuffer),null!==this._dstFramebuffer&&e.deleteFramebuffer(this._dstFramebuffer)}}function GN(e){return e.isDataTexture?e.image.data:"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas?e:e.data}class HN{constructor(e){this.backend=e,this.gl=this.backend.gl,this.availableExtensions=this.gl.getSupportedExtensions(),this.extensions={}}get(e){let t=this.extensions[e];return void 0===t&&(t=this.gl.getExtension(e),this.extensions[e]=t),t}has(e){return this.availableExtensions.includes(e)}}class jN{constructor(e){this.backend=e,this.maxAnisotropy=null}getMaxAnisotropy(){if(null!==this.maxAnisotropy)return this.maxAnisotropy;const e=this.backend.gl,t=this.backend.extensions;if(!0===t.has("EXT_texture_filter_anisotropic")){const n=t.get("EXT_texture_filter_anisotropic");this.maxAnisotropy=e.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else this.maxAnisotropy=0;return this.maxAnisotropy}}const WN={WEBGL_multi_draw:"WEBGL_multi_draw",WEBGL_compressed_texture_astc:"texture-compression-astc",WEBGL_compressed_texture_etc:"texture-compression-etc2",WEBGL_compressed_texture_etc1:"texture-compression-etc1",WEBGL_compressed_texture_pvrtc:"texture-compression-pvrtc",WEBGL_compressed_texture_s3tc:"texture-compression-s3tc",EXT_texture_compression_bptc:"texture-compression-bc",EXT_disjoint_timer_query_webgl2:"timestamp-query",OVR_multiview2:"OVR_multiview2"};class $N{constructor(e){this.gl=e.gl,this.extensions=e.extensions,this.info=e.renderer.info,this.mode=null,this.index=0,this.type=null,this.object=null}render(e,t){const{gl:n,mode:i,object:r,type:s,info:a,index:o}=this;0!==o?n.drawElements(i,t,s,e):n.drawArrays(i,e,t),a.update(r,t,1)}renderInstances(e,t,n){const{gl:i,mode:r,type:s,index:a,object:o,info:l}=this;0!==n&&(0!==a?i.drawElementsInstanced(r,t,s,e,n):i.drawArraysInstanced(r,e,t,n),l.update(o,t,n))}renderMultiDraw(e,t,n){const{extensions:i,mode:r,object:s,info:a}=this;if(0===n)return;const o=i.get("WEBGL_multi_draw");if(null===o)for(let i=0;ithis.maxQueries)return Yt(`WebGPUTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryStates.set(t,"inactive"),this.queryOffsets.set(e,t),t}beginQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e);if(null==t)return;if(null!==this.activeQuery)return;const n=this.queries[t];if(n)try{"inactive"===this.queryStates.get(t)&&(this.gl.beginQuery(this.ext.TIME_ELAPSED_EXT,n),this.activeQuery=t,this.queryStates.set(t,"started"))}catch(e){qt("Error in beginQuery:",e),this.activeQuery=null,this.queryStates.set(t,"inactive")}}endQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e);if(null!=t&&this.activeQuery===t)try{this.gl.endQuery(this.ext.TIME_ELAPSED_EXT),this.queryStates.set(t,"ended"),this.activeQuery=null}catch(e){qt("Error in endQuery:",e),this.queryStates.set(t,"inactive"),this.activeQuery=null}}async resolveQueriesAsync(){if(!this.trackTimestamp||this.pendingResolve)return this.lastValue;this.pendingResolve=!0;try{const e=new Map;for(const[t,n]of this.queryOffsets){if("ended"===this.queryStates.get(n)){const i=this.queries[n];e.set(t,this.resolveQuery(i))}}if(0===e.size)return this.lastValue;const t={},n=[];for(const[i,r]of e){const e=i.match(/^(.*):f(\d+)$/),s=parseInt(e[2]);!1===n.includes(s)&&n.push(s),void 0===t[s]&&(t[s]=0);const a=await r;this.timestamps.set(i,a),t[s]+=a}const i=t[n[n.length-1]];return this.lastValue=i,this.frames=n,this.currentQueryIndex=0,this.queryOffsets.clear(),this.queryStates.clear(),this.activeQuery=null,i}catch(e){return qt("Error resolving queries:",e),this.lastValue}finally{this.pendingResolve=!1}}async resolveQuery(e){return new Promise(t=>{if(this.isDisposed)return void t(this.lastValue);let n,i=!1;const r=e=>{i||(i=!0,n&&(clearTimeout(n),n=null),t(e))},s=()=>{if(this.isDisposed)r(this.lastValue);else try{if(this.gl.getParameter(this.ext.GPU_DISJOINT_EXT))return void r(this.lastValue);if(!this.gl.getQueryParameter(e,this.gl.QUERY_RESULT_AVAILABLE))return void(n=setTimeout(s,1));const i=this.gl.getQueryParameter(e,this.gl.QUERY_RESULT);t(Number(i)/1e6)}catch(e){qt("Error checking query:",e),t(this.lastValue)}};s()})}dispose(){if(!this.isDisposed&&(this.isDisposed=!0,this.trackTimestamp)){for(const e of this.queries)this.gl.deleteQuery(e);this.queries=[],this.queryStates.clear(),this.queryOffsets.clear(),this.lastValue=0,this.activeQuery=null}}}class YN extends CN{constructor(e={}){super(e),this.isWebGLBackend=!0,this.attributeUtils=null,this.extensions=null,this.capabilities=null,this.textureUtils=null,this.bufferRenderer=null,this.gl=null,this.state=null,this.utils=null,this.vaoCache={},this.transformFeedbackCache={},this.discard=!1,this.disjoint=null,this.parallel=null,this._currentContext=null,this._knownBindings=new WeakSet,this._supportsInvalidateFramebuffer="undefined"!=typeof navigator&&/OculusBrowser/g.test(navigator.userAgent),this._xrFramebuffer=null}init(e){super.init(e);const t=this.parameters,n={antialias:e.currentSamples>0,alpha:!0,depth:e.depth,stencil:e.stencil},i=void 0!==t.context?t.context:e.domElement.getContext("webgl2",n);function r(t){t.preventDefault();const n={api:"WebGL",message:t.statusMessage||"Unknown reason",reason:null,originalEvent:t};e.onDeviceLost(n)}this._onContextLost=r,e.domElement.addEventListener("webglcontextlost",r,!1),this.gl=i,this.extensions=new HN(this),this.capabilities=new jN(this),this.attributeUtils=new IN(this),this.textureUtils=new VN(this),this.bufferRenderer=new $N(this),this.state=new UN(this),this.utils=new FN(this),this.extensions.get("EXT_color_buffer_float"),this.extensions.get("WEBGL_clip_cull_distance"),this.extensions.get("OES_texture_float_linear"),this.extensions.get("EXT_color_buffer_half_float"),this.extensions.get("WEBGL_multisampled_render_to_texture"),this.extensions.get("WEBGL_render_shared_exponent"),this.extensions.get("WEBGL_multi_draw"),this.extensions.get("OVR_multiview2"),this.extensions.get("EXT_clip_control"),this.disjoint=this.extensions.get("EXT_disjoint_timer_query_webgl2"),this.parallel=this.extensions.get("KHR_parallel_shader_compile"),this.drawBuffersIndexedExt=this.extensions.get("OES_draw_buffers_indexed"),!0===t.reversedDepthBuffer&&this.extensions.has("EXT_clip_control")&&this.state.setReversedDepth(!0)}get coordinateSystem(){return Ft}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}async makeXRCompatible(){!0!==this.gl.getContextAttributes().xrCompatible&&await this.gl.makeXRCompatible()}setXRTarget(e){this._xrFramebuffer=e}setXRRenderTargetTextures(e,t,n=null){const i=this.gl;if(this.set(e.texture,{textureGPU:t,glInternalFormat:i.RGBA8}),null!==n){const t=e.stencilBuffer?i.DEPTH24_STENCIL8:i.DEPTH_COMPONENT24;this.set(e.depthTexture,{textureGPU:n,glInternalFormat:t}),!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!0===e._autoAllocateDepthBuffer&&!1===e.multiview&&Xt("WebGLBackend: Render-to-texture extension was disabled because an external texture was provided"),e._autoAllocateDepthBuffer=!1}}initTimestampQuery(e,t){if(!this.disjoint||!this.trackTimestamp)return;this.timestampQueryPool[e]||(this.timestampQueryPool[e]=new qN(this.gl,e,2048));const n=this.timestampQueryPool[e];null!==n.allocateQueriesForContext(t)&&n.beginQuery(t)}prepareTimestampBuffer(e,t){if(!this.disjoint||!this.trackTimestamp)return;this.timestampQueryPool[e].endQuery(t)}getContext(){return this.gl}beginRender(e){const{state:t}=this,n=this.get(e);if(e.viewport)this.updateViewport(e);else{const{width:e,height:n}=this.getDrawingBufferSize();t.viewport(0,0,e,n)}if(e.scissor)this.updateScissor(e);else{const{width:e,height:n}=this.getDrawingBufferSize();t.scissor(0,0,e,n)}this.initTimestampQuery(kt,this.getTimestampUID(e)),n.previousContext=this._currentContext,this._currentContext=e,this._setFramebuffer(e),this.clear(e.clearColor,e.clearDepth,e.clearStencil,e,!1);const i=e.occlusionQueryCount;i>0&&(n.currentOcclusionQueries=n.occlusionQueries,n.currentOcclusionQueryObjects=n.occlusionQueryObjects,n.lastOcclusionObject=null,n.occlusionQueries=new Array(i),n.occlusionQueryObjects=new Array(i),n.occlusionQueryIndex=0)}finishRender(e){const{gl:t,state:n}=this,i=this.get(e),r=i.previousContext;n.resetVertexState();const s=e.occlusionQueryCount;s>0&&(s>i.occlusionQueryIndex&&t.endQuery(t.ANY_SAMPLES_PASSED),this.resolveOccludedAsync(e));const a=e.textures;if(null!==a)for(let e=0;e{let a=0;for(let t=0;t{t.isBatchedMesh?null!==t._multiDrawInstances?(Yt("WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),v.renderMultiDrawInstances(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount,t._multiDrawInstances)):this.hasFeature("WEBGL_multi_draw")?v.renderMultiDraw(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount):Yt("WebGLBackend: WEBGL_multi_draw not supported."):b>1?v.renderInstances(x,y,b):v.render(x,y)};if(!0===e.camera.isArrayCamera&&e.camera.cameras.length>0&&!1===e.camera.isMultiViewCamera){const n=this.get(e.camera),i=e.camera.cameras,r=e.getBindingGroup("cameraIndex").bindings[0];if(void 0===n.indexesGPU||n.indexesGPU.length!==i.length){const e=new Uint32Array([0,0,0,0]),t=[];for(let n=0,r=i.length;n{const r=this.parallel,s=()=>{n.getProgramParameter(a,r.COMPLETION_STATUS_KHR)?(this._completeCompile(e,i),t()):requestAnimationFrame(s)};s()});return void t.push(r)}this._completeCompile(e,i)}_handleSource(e,t){const n=e.split("\n"),i=[],r=Math.max(t-6,0),s=Math.min(t+6,n.length);for(let e=r;e":" "} ${r}: ${n[e]}`)}return i.join("\n")}_getShaderErrors(e,t,n){const i=e.getShaderParameter(t,e.COMPILE_STATUS),r=(e.getShaderInfoLog(t)||"").trim();if(i&&""===r)return"";const s=/ERROR: 0:(\d+)/.exec(r);if(s){const i=parseInt(s[1]);return n.toUpperCase()+"\n\n"+r+"\n\n"+this._handleSource(e.getShaderSource(t),i)}return r}_logProgramError(e,t,n){if(this.renderer.debug.checkShaderErrors){const i=this.gl,r=(i.getProgramInfoLog(e)||"").trim();if(!1===i.getProgramParameter(e,i.LINK_STATUS))if("function"==typeof this.renderer.debug.onShaderError)this.renderer.debug.onShaderError(i,e,n,t);else{const s=this._getShaderErrors(i,n,"vertex"),a=this._getShaderErrors(i,t,"fragment");qt("THREE.WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(e,i.VALIDATE_STATUS)+"\n\nProgram Info Log: "+r+"\n"+s+"\n"+a)}else""!==r&&Xt("WebGLProgram: Program Info Log:",r)}}_completeCompile(e,t){const{state:n,gl:i}=this,r=this.get(t),{programGPU:s,fragmentShader:a,vertexShader:o}=r;!1===i.getProgramParameter(s,i.LINK_STATUS)&&this._logProgramError(s,a,o),n.useProgram(s);const l=e.getBindings();this._setupBindings(l,s),this.set(t,{programGPU:s})}createComputePipeline(e,t){const{state:n,gl:i}=this,r={stage:"fragment",code:"#version 300 es\nprecision highp float;\nvoid main() {}"};this.createProgram(r);const{computeProgram:s}=e,a=i.createProgram(),o=this.get(r).shaderGPU,l=this.get(s).shaderGPU,u=s.transforms,c=[],h=[];for(let e=0;eWN[t]===e),n=this.extensions;for(let e=0;e1,d=!0===r.isXRRenderTarget,p=!0===d&&!0===r._hasExternalTextures;let f=s.msaaFrameBuffer,m=s.depthRenderbuffer;const g=this.extensions.get("WEBGL_multisampled_render_to_texture"),_=this.extensions.get("OVR_multiview2"),v=this._useMultisampledExtension(r),y=kw(e);let b;if(u?(s.cubeFramebuffers||(s.cubeFramebuffers={}),b=s.cubeFramebuffers[y]):d&&!1===p?b=this._xrFramebuffer:(s.framebuffers||(s.framebuffers={}),b=s.framebuffers[y]),void 0===b){b=t.createFramebuffer(),n.bindFramebuffer(t.FRAMEBUFFER,b);const i=e.textures,o=[];if(u){s.cubeFramebuffers[y]=b;const{textureGPU:e}=this.get(i[0]),n=this.renderer._activeCubeFace,r=this.renderer._activeMipmapLevel;t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+n,e,r)}else{s.framebuffers[y]=b;for(let n=0;n0&&!1===v&&!r.multiview){if(void 0===f){const i=[];f=t.createFramebuffer(),n.bindFramebuffer(t.FRAMEBUFFER,f);const r=[],u=e.textures;for(let n=0;n0&&!1===this._useMultisampledExtension(i)){const s=r.framebuffers[e.getCacheKey()];let a=t.COLOR_BUFFER_BIT;i.resolveDepthBuffer&&(i.depthBuffer&&(a|=t.DEPTH_BUFFER_BIT),i.stencilBuffer&&i.resolveStencilBuffer&&(a|=t.STENCIL_BUFFER_BIT));const o=r.msaaFrameBuffer,l=r.msaaRenderbuffers,u=e.textures,c=u.length>1;if(n.bindFramebuffer(t.READ_FRAMEBUFFER,o),n.bindFramebuffer(t.DRAW_FRAMEBUFFER,s),c)for(let e=0;e0&&!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!1!==e._autoAllocateDepthBuffer}dispose(){null!==this.textureUtils&&this.textureUtils.dispose();const e=this.extensions.get("WEBGL_lose_context");e&&e.loseContext(),this.renderer.domElement.removeEventListener("webglcontextlost",this._onContextLost)}}const KN="point-list",ZN="line-list",QN="line-strip",JN="triangle-list",eP="undefined"!=typeof self&&self.GPUShaderStage?self.GPUShaderStage:{VERTEX:1,FRAGMENT:2,COMPUTE:4},tP="never",nP="less",iP="equal",rP="less-equal",sP="greater",aP="not-equal",oP="greater-equal",lP="always",uP="store",cP="load",hP="clear",dP="ccw",pP="cw",fP="none",mP="back",gP="uint16",_P="uint32",vP="r8unorm",yP="r8snorm",bP="r8uint",xP="r8sint",TP="r16uint",SP="r16sint",MP="r16float",EP="rg8unorm",wP="rg8snorm",AP="rg8uint",RP="rg8sint",CP="r32uint",NP="r32sint",PP="r32float",LP="rg16uint",DP="rg16sint",IP="rg16float",UP="rgba8unorm",FP="rgba8unorm-srgb",OP="rgba8snorm",BP="rgba8uint",kP="rgba8sint",zP="bgra8unorm",VP="bgra8unorm-srgb",GP="rgb9e5ufloat",HP="rgb10a2unorm",jP="rg11b10ufloat",WP="rg32uint",$P="rg32sint",XP="rg32float",qP="rgba16uint",YP="rgba16sint",KP="rgba16float",ZP="rgba32uint",QP="rgba32sint",JP="rgba32float",eL="depth16unorm",tL="depth24plus",nL="depth24plus-stencil8",iL="depth32float",rL="depth32float-stencil8",sL="bc1-rgba-unorm",aL="bc1-rgba-unorm-srgb",oL="bc2-rgba-unorm",lL="bc2-rgba-unorm-srgb",uL="bc3-rgba-unorm",cL="bc3-rgba-unorm-srgb",hL="bc4-r-unorm",dL="bc4-r-snorm",pL="bc5-rg-unorm",fL="bc5-rg-snorm",mL="bc6h-rgb-ufloat",gL="bc6h-rgb-float",_L="bc7-rgba-unorm",vL="bc7-rgba-unorm-srgb",yL="etc2-rgb8unorm",bL="etc2-rgb8unorm-srgb",xL="etc2-rgb8a1unorm",TL="etc2-rgb8a1unorm-srgb",SL="etc2-rgba8unorm",ML="etc2-rgba8unorm-srgb",EL="eac-r11unorm",wL="eac-r11snorm",AL="eac-rg11unorm",RL="eac-rg11snorm",CL="astc-4x4-unorm",NL="astc-4x4-unorm-srgb",PL="astc-5x4-unorm",LL="astc-5x4-unorm-srgb",DL="astc-5x5-unorm",IL="astc-5x5-unorm-srgb",UL="astc-6x5-unorm",FL="astc-6x5-unorm-srgb",OL="astc-6x6-unorm",BL="astc-6x6-unorm-srgb",kL="astc-8x5-unorm",zL="astc-8x5-unorm-srgb",VL="astc-8x6-unorm",GL="astc-8x6-unorm-srgb",HL="astc-8x8-unorm",jL="astc-8x8-unorm-srgb",WL="astc-10x5-unorm",$L="astc-10x5-unorm-srgb",XL="astc-10x6-unorm",qL="astc-10x6-unorm-srgb",YL="astc-10x8-unorm",KL="astc-10x8-unorm-srgb",ZL="astc-10x10-unorm",QL="astc-10x10-unorm-srgb",JL="astc-12x10-unorm",eD="astc-12x10-unorm-srgb",tD="astc-12x12-unorm",nD="astc-12x12-unorm-srgb",iD="clamp-to-edge",rD="repeat",sD="mirror-repeat",aD="linear",oD="nearest",lD="zero",uD="one",cD="src",hD="one-minus-src",dD="src-alpha",pD="one-minus-src-alpha",fD="dst",mD="one-minus-dst",gD="dst-alpha",_D="one-minus-dst-alpha",vD="src-alpha-saturated",yD="constant",bD="one-minus-constant",xD="add",TD="subtract",SD="reverse-subtract",MD="min",ED="max",wD=0,AD=15,RD="keep",CD="zero",ND="replace",PD="invert",LD="increment-clamp",DD="decrement-clamp",ID="increment-wrap",UD="decrement-wrap",FD="storage",OD="read-only-storage",BD="write-only",kD="read-only",zD="read-write",VD="non-filtering",GD="comparison",HD="float",jD="unfilterable-float",WD="depth",$D="sint",XD="uint",qD="2d",YD="3d",KD="2d",ZD="2d-array",QD="cube",JD="3d",eI="all",tI="vertex",nI="instance",iI={CoreFeaturesAndLimits:"core-features-and-limits",DepthClipControl:"depth-clip-control",Depth32FloatStencil8:"depth32float-stencil8",TextureCompressionBC:"texture-compression-bc",TextureCompressionBCSliced3D:"texture-compression-bc-sliced-3d",TextureCompressionETC2:"texture-compression-etc2",TextureCompressionASTC:"texture-compression-astc",TextureCompressionASTCSliced3D:"texture-compression-astc-sliced-3d",TimestampQuery:"timestamp-query",IndirectFirstInstance:"indirect-first-instance",ShaderF16:"shader-f16",RG11B10UFloat:"rg11b10ufloat-renderable",BGRA8UNormStorage:"bgra8unorm-storage",Float32Filterable:"float32-filterable",Float32Blendable:"float32-blendable",ClipDistances:"clip-distances",DualSourceBlending:"dual-source-blending",Subgroups:"subgroups",TextureFormatsTier1:"texture-formats-tier1",TextureFormatsTier2:"texture-formats-tier2"},rI={"texture-compression-s3tc":"texture-compression-bc","texture-compression-etc1":"texture-compression-etc2"};class sI extends pN{constructor(e,t,n){super(e,t?t.value:null),this.textureNode=t,this.groupNode=n}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}}class aI extends aN{constructor(e,t){super(e,t?t.array:null),this._attribute=t,this.isStorageBuffer=!0}get attribute(){return this._attribute}}let oI=0;class lI extends aI{constructor(e,t){super("StorageBuffer_"+oI++,e?e.value:null),this.nodeUniform=e,this.access=e?e.access:$f,this.groupNode=t}get attribute(){return this.nodeUniform.value}get buffer(){return this.nodeUniform.value.array}}class uI extends dw{constructor(e){super(),this.device=e;this.mipmapSampler=e.createSampler({minFilter:aD}),this.flipYSampler=e.createSampler({minFilter:oD}),this.flipUniformBuffer=e.createBuffer({size:4,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),e.queue.writeBuffer(this.flipUniformBuffer,0,new Uint32Array([1])),this.noFlipUniformBuffer=e.createBuffer({size:4,usage:GPUBufferUsage.UNIFORM}),this.transferPipelines={},this.mipmapShaderModule=e.createShaderModule({label:"mipmap",code:"\nstruct VarysStruct {\n\t@builtin( position ) Position: vec4f,\n\t@location( 0 ) vTex : vec2f,\n\t@location( 1 ) @interpolate(flat, either) vBaseArrayLayer: u32,\n};\n\n@group( 0 ) @binding ( 2 )\nvar flipY: u32;\n\n@vertex\nfn mainVS(\n\t\t@builtin( vertex_index ) vertexIndex : u32,\n\t\t@builtin( instance_index ) instanceIndex : u32 ) -> VarysStruct {\n\n\tvar Varys : VarysStruct;\n\n\tvar pos = array(\n\t\tvec2f( -1, -1 ),\n\t\tvec2f( -1, 3 ),\n\t\tvec2f( 3, -1 ),\n\t);\n\n\tlet p = pos[ vertexIndex ];\n\tlet mult = select( vec2f( 0.5, -0.5 ), vec2f( 0.5, 0.5 ), flipY != 0 );\n\tVarys.vTex = p * mult + vec2f( 0.5 );\n\tVarys.Position = vec4f( p, 0, 1 );\n\tVarys.vBaseArrayLayer = instanceIndex;\n\n\treturn Varys;\n\n}\n\n@group( 0 ) @binding( 0 )\nvar imgSampler : sampler;\n\n@group( 0 ) @binding( 1 )\nvar img2d : texture_2d;\n\n@fragment\nfn main_2d( Varys: VarysStruct ) -> @location( 0 ) vec4 {\n\n\treturn textureSample( img2d, imgSampler, Varys.vTex );\n\n}\n\n@group( 0 ) @binding( 1 )\nvar img2dArray : texture_2d_array;\n\n@fragment\nfn main_2d_array( Varys: VarysStruct ) -> @location( 0 ) vec4 {\n\n\treturn textureSample( img2dArray, imgSampler, Varys.vTex, Varys.vBaseArrayLayer );\n\n}\n\nconst faceMat = array(\n mat3x3f( 0, 0, -2, 0, -2, 0, 1, 1, 1 ), // pos-x\n mat3x3f( 0, 0, 2, 0, -2, 0, -1, 1, -1 ), // neg-x\n mat3x3f( 2, 0, 0, 0, 0, 2, -1, 1, -1 ), // pos-y\n mat3x3f( 2, 0, 0, 0, 0, -2, -1, -1, 1 ), // neg-y\n mat3x3f( 2, 0, 0, 0, -2, 0, -1, 1, 1 ), // pos-z\n mat3x3f( -2, 0, 0, 0, -2, 0, 1, 1, -1 ), // neg-z\n);\n\n@group( 0 ) @binding( 1 )\nvar imgCube : texture_cube;\n\n@fragment\nfn main_cube( Varys: VarysStruct ) -> @location( 0 ) vec4 {\n\n\treturn textureSample( imgCube, imgSampler, faceMat[ Varys.vBaseArrayLayer ] * vec3f( fract( Varys.vTex ), 1 ) );\n\n}\n"})}getTransferPipeline(e,t){const n=`${e}-${t=t||"2d-array"}`;let i=this.transferPipelines[n];return void 0===i&&(i=this.device.createRenderPipeline({label:`mipmap-${e}-${t}`,vertex:{module:this.mipmapShaderModule},fragment:{module:this.mipmapShaderModule,entryPoint:`main_${t.replace("-","_")}`,targets:[{format:e}]},layout:"auto"}),this.transferPipelines[n]=i),i}flipY(e,t,n=0){const i=t.format,{width:r,height:s}=t.size,a=this.device.createTexture({size:{width:r,height:s},format:i,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),o=this.getTransferPipeline(i,e.textureBindingViewDimension),l=this.getTransferPipeline(i,a.textureBindingViewDimension),u=this.device.createCommandEncoder({}),c=(e,t,n,i,r,s)=>{const a=e.getBindGroupLayout(0),o=this.device.createBindGroup({layout:a,entries:[{binding:0,resource:this.flipYSampler},{binding:1,resource:t.createView({dimension:t.textureBindingViewDimension||"2d-array",baseMipLevel:0,mipLevelCount:1})},{binding:2,resource:{buffer:s?this.flipUniformBuffer:this.noFlipUniformBuffer}}]}),l=u.beginRenderPass({colorAttachments:[{view:i.createView({dimension:"2d",baseMipLevel:0,mipLevelCount:1,baseArrayLayer:r,arrayLayerCount:1}),loadOp:hP,storeOp:uP}]});l.setPipeline(e),l.setBindGroup(0,o),l.draw(3,1,0,n),l.end()};c(o,e,n,a,0,!1),c(l,a,0,e,n,!0),this.device.queue.submit([u.finish()]),a.destroy()}generateMipmaps(e,t=null){const n=this.get(e),i=n.layers||this._mipmapCreateBundles(e),r=t||this.device.createCommandEncoder({label:"mipmapEncoder"});this._mipmapRunBundles(r,i),null===t&&this.device.queue.submit([r.finish()]),n.layers=i}_mipmapCreateBundles(e){const t=e.textureBindingViewDimension||"2d-array",n=this.getTransferPipeline(e.format,t),i=n.getBindGroupLayout(0),r=[];for(let s=1;s0)for(let t=0,s=i.length;t0)for(let t=0,s=i.length;t0?e.width:n.size.width,u=a>0?e.height:n.size.height;try{o.queue.copyExternalImageToTexture({source:e,flipY:r},{texture:t,mipLevel:a,origin:{x:0,y:0,z:i},premultipliedAlpha:s},{width:l,height:u,depthOrArrayLayers:1})}catch(e){}}_getPassUtils(){let e=this._passUtils;return null===e&&(this._passUtils=e=new uI(this.backend.device)),e}_generateMipmaps(e,t=null){this._getPassUtils().generateMipmaps(e,t)}_flipY(e,t,n=0){this._getPassUtils().flipY(e,t,n)}_copyBufferToTexture(e,t,n,i,r,s=0,a=0){const o=this.backend.device,l=e.data,u=this._getBytesPerTexel(n.format),c=e.width*u;o.queue.writeTexture({texture:t,mipLevel:a,origin:{x:0,y:0,z:i}},l,{offset:e.width*e.height*u*s,bytesPerRow:c},{width:e.width,height:e.height,depthOrArrayLayers:1}),!0===r&&this._flipY(t,n,i)}_copyCompressedBufferToTexture(e,t,n){const i=this.backend.device,r=this._getBlockData(n.format),s=n.size.depthOrArrayLayers>1;for(let a=0;a]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,mI=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/gi,gI={f32:"float",i32:"int",u32:"uint",bool:"bool","vec2":"vec2","vec2":"ivec2","vec2":"uvec2","vec2":"bvec2",vec2f:"vec2",vec2i:"ivec2",vec2u:"uvec2",vec2b:"bvec2","vec3":"vec3","vec3":"ivec3","vec3":"uvec3","vec3":"bvec3",vec3f:"vec3",vec3i:"ivec3",vec3u:"uvec3",vec3b:"bvec3","vec4":"vec4","vec4":"ivec4","vec4":"uvec4","vec4":"bvec4",vec4f:"vec4",vec4i:"ivec4",vec4u:"uvec4",vec4b:"bvec4","mat2x2":"mat2",mat2x2f:"mat2","mat3x3":"mat3",mat3x3f:"mat3","mat4x4":"mat4",mat4x4f:"mat4",sampler:"sampler",texture_1d:"texture",texture_2d:"texture",texture_2d_array:"texture",texture_multisampled_2d:"cubeTexture",texture_depth_2d:"depthTexture",texture_depth_2d_array:"depthTexture",texture_depth_multisampled_2d:"depthTexture",texture_depth_cube:"depthTexture",texture_depth_cube_array:"depthTexture",texture_3d:"texture3D",texture_cube:"cubeTexture",texture_cube_array:"cubeTexture",texture_storage_1d:"storageTexture",texture_storage_2d:"storageTexture",texture_storage_2d_array:"storageTexture",texture_storage_3d:"storageTexture"};class _I extends bC{constructor(e){const{type:t,inputs:n,name:i,inputsCode:r,blockCode:s,outputType:a}=(e=>{const t=(e=e.trim()).match(fI);if(null!==t&&4===t.length){const n=t[2],i=[];let r=null;for(;null!==(r=mI.exec(n));)i.push({name:r[1],type:r[2]});const s=[];for(let e=0;e "+this.outputType:"";return`fn ${e} ( ${this.inputsCode.trim()} ) ${t}`+this.blockCode}}class vI extends yC{parseFunction(e){return new _I(e)}}const yI={[jf]:"read",[Wf]:"write",[$f]:"read_write"},bI={[se]:"repeat",[ae]:"clamp",[oe]:"mirror"},xI={vertex:eP.VERTEX,fragment:eP.FRAGMENT,compute:eP.COMPUTE},TI={instance:!0,swizzleAssign:!1,storageBuffer:!0},SI={"^^":"tsl_xor"},MI={float:"f32",int:"i32",uint:"u32",bool:"bool",color:"vec3",vec2:"vec2",ivec2:"vec2",uvec2:"vec2",bvec2:"vec2",vec3:"vec3",ivec3:"vec3",uvec3:"vec3",bvec3:"vec3",vec4:"vec4",ivec4:"vec4",uvec4:"vec4",bvec4:"vec4",mat2:"mat2x2",mat3:"mat3x3",mat4:"mat4x4"},EI={},wI={tsl_xor:new AA("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new AA("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new AA("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new AA("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new AA("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new AA("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new AA("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2 { return vec2( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new AA("fn tsl_equals_bvec3( a : vec3f, b : vec3f ) -> vec3 { return vec3( a.x == b.x, a.y == b.y, a.z == b.z ); }"),equals_bvec4:new AA("fn tsl_equals_bvec4( a : vec4f, b : vec4f ) -> vec4 { return vec4( a.x == b.x, a.y == b.y, a.z == b.z, a.w == b.w ); }"),repeatWrapping_float:new AA("fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }"),mirrorWrapping_float:new AA("fn tsl_mirrorWrapping_float( coord: f32 ) -> f32 { let mirrored = fract( coord * 0.5 ) * 2.0; return 1.0 - abs( 1.0 - mirrored ); }"),clampWrapping_float:new AA("fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }"),biquadraticTexture:new AA("\nfn tsl_biquadraticTexture( map : texture_2d, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {\n\n\tlet res = vec2f( iRes );\n\n\tlet uvScaled = coord * res;\n\tlet uvWrapping = ( ( uvScaled % res ) + res ) % res;\n\n\t// https://www.shadertoy.com/view/WtyXRy\n\n\tlet uv = uvWrapping - 0.5;\n\tlet iuv = floor( uv );\n\tlet f = fract( uv );\n\n\tlet rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );\n\tlet rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );\n\tlet rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );\n\tlet rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );\n\n\treturn mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );\n\n}\n"),biquadraticTextureArray:new AA("\nfn tsl_biquadraticTexture_array( map : texture_2d_array, coord : vec2f, iRes : vec2u, layer : u32, level : u32 ) -> vec4f {\n\n\tlet res = vec2f( iRes );\n\n\tlet uvScaled = coord * res;\n\tlet uvWrapping = ( ( uvScaled % res ) + res ) % res;\n\n\t// https://www.shadertoy.com/view/WtyXRy\n\n\tlet uv = uvWrapping - 0.5;\n\tlet iuv = floor( uv );\n\tlet f = fract( uv );\n\n\tlet rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, layer, level );\n\tlet rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, layer, level );\n\tlet rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, layer, level );\n\tlet rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, layer, level );\n\n\treturn mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );\n\n}\n")},AI={dFdx:"dpdx",dFdy:"- dpdy",mod_float:"tsl_mod_float",mod_vec2:"tsl_mod_vec2",mod_vec3:"tsl_mod_vec3",mod_vec4:"tsl_mod_vec4",equals_bool:"tsl_equals_bool",equals_bvec2:"tsl_equals_bvec2",equals_bvec3:"tsl_equals_bvec3",equals_bvec4:"tsl_equals_bvec4",inversesqrt:"inverseSqrt",bitcast:"bitcast",floatpack_snorm_2x16:"pack2x16snorm",floatpack_unorm_2x16:"pack2x16unorm",floatpack_float16_2x16:"pack2x16float",floatunpack_snorm_2x16:"unpack2x16snorm",floatunpack_unorm_2x16:"unpack2x16unorm",floatunpack_float16_2x16:"unpack2x16float"};let RI="";!0!==("undefined"!=typeof navigator&&/Firefox|Deno/g.test(navigator.userAgent))&&(RI+="diagnostic( off, derivative_uniformity );\n");class CI extends rC{constructor(e,t){super(e,t,new vI),this.uniformGroups={},this.uniformGroupsBindings={},this.builtins={},this.directives={},this.scopedArrays=new Map}_generateTextureSample(e,t,n,i,r,s=this.shaderStage){return"fragment"===s?i?r?`textureSample( ${t}, ${t}_sampler, ${n}, ${i}, ${r} )`:`textureSample( ${t}, ${t}_sampler, ${n}, ${i} )`:r?`textureSample( ${t}, ${t}_sampler, ${n}, ${r} )`:`textureSample( ${t}, ${t}_sampler, ${n} )`:this.generateTextureSampleLevel(e,t,n,"0",i)}generateTextureSampleLevel(e,t,n,i,r,s){return!1===this.isUnfilterable(e)?r?s?`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${r}, ${i}, ${s} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${r}, ${i} )`:s?`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${i}, ${s} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${i} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,n,s,i,r):this.generateTextureLod(e,t,n,r,s,i)}generateWrapFunction(e){const t=`tsl_coord_${bI[e.wrapS]}S_${bI[e.wrapT]}_${e.is3DTexture||e.isData3DTexture?"3d":"2d"}T`;let n=EI[t];if(void 0===n){const i=[],r=e.is3DTexture||e.isData3DTexture?"vec3f":"vec2f";let s=`fn ${t}( coord : ${r} ) -> ${r} {\n\n\treturn ${r}(\n`;const a=(e,t)=>{e===se?(i.push(wI.repeatWrapping_float),s+=`\t\ttsl_repeatWrapping_float( coord.${t} )`):e===ae?(i.push(wI.clampWrapping_float),s+=`\t\ttsl_clampWrapping_float( coord.${t} )`):e===oe?(i.push(wI.mirrorWrapping_float),s+=`\t\ttsl_mirrorWrapping_float( coord.${t} )`):(s+=`\t\tcoord.${t}`,Xt(`WebGPURenderer: Unsupported texture wrap type "${e}" for vertex shader.`))};a(e.wrapS,"x"),s+=",\n",a(e.wrapT,"y"),(e.is3DTexture||e.isData3DTexture)&&(s+=",\n",a(e.wrapR,"z")),s+="\n\t);\n\n}\n",EI[t]=n=new AA(s,i)}return n.build(this),t}generateArrayDeclaration(e,t){return`array< ${this.getType(e)}, ${t} >`}generateTextureDimension(e,t,n){const i=this.getDataFromNode(e,this.shaderStage,this.globalCache);void 0===i.dimensionsSnippet&&(i.dimensionsSnippet={});let r=i.dimensionsSnippet[n];if(void 0===i.dimensionsSnippet[n]){let s,a;const{primarySamples:o}=this.renderer.backend.utils.getTextureSampleData(e),l=o>1;a=e.is3DTexture||e.isData3DTexture?"vec3":"vec2",s=l||e.isStorageTexture?t:`${t}${n?`, u32( ${n} )`:""}`,r=new Wv(new Sy(`textureDimensions( ${s} )`,a)),i.dimensionsSnippet[n]=r,(e.isArrayTexture||e.isDataArrayTexture||e.is3DTexture||e.isData3DTexture)&&(i.arrayLayerCount=new Wv(new Sy(`textureNumLayers(${t})`,"u32"))),e.isTextureCube&&(i.cubeFaceCount=new Wv(new Sy("6u","u32")))}return r.build(this)}generateFilteredTexture(e,t,n,i,r="0u",s){const a=this.generateWrapFunction(e),o=this.generateTextureDimension(e,t,r);return i&&(n=`${n} + vec2(${i}) / ${o}`),s?(this._include("biquadraticTextureArray"),`tsl_biquadraticTexture_array( ${t}, ${a}( ${n} ), ${o}, u32( ${s} ), u32( ${r} ) )`):(this._include("biquadraticTexture"),`tsl_biquadraticTexture( ${t}, ${a}( ${n} ), ${o}, u32( ${r} ) )`)}generateTextureLod(e,t,n,i,r,s="0u"){if(!0===e.isCubeTexture){r&&(n=`${n} + vec3(${r})`);return`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${e.isDepthTexture?"u32":"f32"}( ${s} ) )`}const a=this.generateWrapFunction(e),o=this.generateTextureDimension(e,t,s),l=e.is3DTexture||e.isData3DTexture?"vec3":"vec2";r&&(n=`${n} + ${l}(${r}) / ${l}( ${o} )`);return n=`${l}( clamp( floor( ${a}( ${n} ) * ${l}( ${o} ) ), ${`${l}( 0 )`}, ${`${l}( ${o} - ${"vec3"===l?"vec3( 1, 1, 1 )":"vec2( 1, 1 )"} )`} ) )`,this.generateTextureLoad(e,t,n,s,i,null)}generateStorageTextureLoad(e,t,n,i,r,s){let a;return s&&(n=`${n} + ${s}`),a=r?`textureLoad( ${t}, ${n}, ${r} )`:`textureLoad( ${t}, ${n} )`,a}generateTextureLoad(e,t,n,i,r,s){let a;return null===i&&(i="0u"),s&&(n=`${n} + ${s}`),r?a=`textureLoad( ${t}, ${n}, ${r}, u32( ${i} ) )`:(a=`textureLoad( ${t}, ${n}, u32( ${i} ) )`,this.renderer.backend.compatibilityMode&&e.isDepthTexture&&(a+=".x")),a}generateTextureStore(e,t,n,i,r){let s;return s=i?`textureStore( ${t}, ${n}, ${i}, ${r} )`:`textureStore( ${t}, ${n}, ${r} )`,s}isSampleCompare(e){return!0===e.isDepthTexture&&null!==e.compareFunction&&this.renderer.hasCompatibility(zt)}isUnfilterable(e){return"float"!==this.getComponentTypeFromTexture(e)||!this.isAvailable("float32Filterable")&&!0===e.isDataTexture&&e.type===be||!1===this.isSampleCompare(e)&&e.minFilter===le&&e.magFilter===le||this.renderer.backend.utils.getTextureSampleData(e).primarySamples>1}generateTexture(e,t,n,i,r,s=this.shaderStage){let a=null;return a=this.isUnfilterable(e)?this.generateTextureLod(e,t,n,i,r,"0",s):this._generateTextureSample(e,t,n,i,r,s),a}generateTextureGrad(e,t,n,i,r,s,a=this.shaderStage){if("fragment"===a)return r?s?`textureSampleGrad( ${t}, ${t}_sampler, ${n}, ${r}, ${i[0]}, ${i[1]}, ${s} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${n}, ${r}, ${i[0]}, ${i[1]} )`:s?`textureSampleGrad( ${t}, ${t}_sampler, ${n}, ${i[0]}, ${i[1]}, ${s} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${n}, ${i[0]}, ${i[1]} )`;qt(`WebGPURenderer: THREE.TextureNode.gradient() does not support ${a} shader.`)}generateTextureCompare(e,t,n,i,r,s,a=this.shaderStage){if("fragment"===a)return!0===e.isDepthTexture&&!0===e.isArrayTexture?s?`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${r}, ${i}, ${s} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${r}, ${i} )`:s?`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${i}, ${s} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${i} )`;qt(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${a} shader.`)}generateTextureLevel(e,t,n,i,r,s){return!1===this.isUnfilterable(e)?r?s?`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${r}, ${i}, ${s} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${r}, ${i} )`:s?`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${i}, ${s} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${i} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,n,s,i,r):this.generateTextureLod(e,t,n,r,s,i)}generateTextureBias(e,t,n,i,r,s,a=this.shaderStage){if("fragment"===a)return r?s?`textureSampleBias( ${t}, ${t}_sampler, ${n}, ${r}, ${i}, ${s} )`:`textureSampleBias( ${t}, ${t}_sampler, ${n}, ${r}, ${i} )`:s?`textureSampleBias( ${t}, ${t}_sampler, ${n}, ${i}, ${s} )`:`textureSampleBias( ${t}, ${t}_sampler, ${n}, ${i} )`;qt(`WebGPURenderer: THREE.TextureNode.biasNode does not support ${a} shader.`)}getPropertyName(e,t=this.shaderStage){if(!0===e.isNodeVarying&&!0===e.needsInterpolation){if("vertex"===t)return`varyings.${e.name}`}else if(!0===e.isNodeUniform){const t=e.name,n=e.type;return"texture"===n||"cubeTexture"===n||"cubeDepthTexture"===n||"storageTexture"===n||"texture3D"===n?t:"buffer"===n||"storageBuffer"===n||"indirectStorageBuffer"===n?this.isCustomStruct(e)?t:t+".value":e.groupNode.name+"."+t}return super.getPropertyName(e)}getOutputStructName(){return"output"}getFunctionOperator(e){const t=SI[e];return void 0!==t?(this._include(t),t):null}getNodeAccess(e,t){return"compute"!==t?!0===e.isAtomic?(Xt("WebGPURenderer: Atomic operations are only supported in compute shaders."),$f):jf:e.access}getStorageAccess(e,t){return yI[this.getNodeAccess(e,t)]}getUniformFromNode(e,t,n,i=null){const r=super.getUniformFromNode(e,t,n,i),s=this.getDataFromNode(e,n,this.globalCache);if(void 0===s.uniformGPU){let a;const o=e.groupNode,l=o.name,u=this.getBindGroupArray(l,n);if("texture"===t||"cubeTexture"===t||"cubeDepthTexture"===t||"storageTexture"===t||"texture3D"===t){let i=null;const s=this.getNodeAccess(e,n);"texture"===t||"storageTexture"===t?i=!0===e.value.is3DTexture?new vN(r.name,r.node,o,s):new gN(r.name,r.node,o,s):"cubeTexture"===t||"cubeDepthTexture"===t?i=new _N(r.name,r.node,o,s):"texture3D"===t&&(i=new vN(r.name,r.node,o,s)),i.store=!0===e.isStorageTextureNode,i.mipLevel=i.store?e.mipLevel:0,i.setVisibility(xI[n]);if(!0===e.value.isCubeTexture||!1===this.isUnfilterable(e.value)&&!1===i.store){const e=new sI(`${r.name}_sampler`,r.node,o);e.setVisibility(xI[n]),u.push(e,i),a=[e,i]}else u.push(i),a=[i]}else if("buffer"===t||"storageBuffer"===t||"indirectStorageBuffer"===t){const s=this.getSharedDataFromNode(e);let l=s.buffer;if(void 0===l){l=new("buffer"===t?uN:lI)(e,o),s.buffer=l}l.setVisibility(l.getVisibility()|xI[n]),u.push(l),a=l,r.name=i||"NodeBuffer_"+r.id}else{let e=this.uniformGroups[l];void 0===e&&(e=new dN(l,o),e.setVisibility(eP.VERTEX|eP.FRAGMENT|eP.COMPUTE),this.uniformGroups[l]=e),-1===u.indexOf(e)&&u.push(e),a=this.getNodeUniform(r,t);const n=a.name,i=e.uniforms.some(e=>e.name===n);i||e.addUniform(a)}s.uniformGPU=a}return r}getBuiltin(e,t,n,i=this.shaderStage){const r=this.builtins[i]||(this.builtins[i]=new Map);return!1===r.has(e)&&r.set(e,{name:e,property:t,type:n}),t}hasBuiltin(e,t=this.shaderStage){return void 0!==this.builtins[t]&&this.builtins[t].has(e)}getVertexIndex(){return"vertex"===this.shaderStage?this.getBuiltin("vertex_index","vertexIndex","u32","attribute"):"vertexIndex"}buildFunctionCode(e){const t=e.layout,n=this.flowShaderNode(e),i=[];for(const e of t.inputs)i.push(e.name+" : "+this.getType(e.type));let r=`fn ${t.name}( ${i.join(", ")} ) -> ${this.getType(t.type)} {\n${n.vars}\n${n.code}\n`;return n.result&&(r+=`\treturn ${n.result};\n`),r+="\n}\n",r}getInstanceIndex(){return"vertex"===this.shaderStage?this.getBuiltin("instance_index","instanceIndex","u32","attribute"):"instanceIndex"}getInvocationLocalIndex(){return this.getBuiltin("local_invocation_index","invocationLocalIndex","u32","attribute")}getSubgroupSize(){return this.enableSubGroups(),this.getBuiltin("subgroup_size","subgroupSize","u32","attribute")}getInvocationSubgroupIndex(){return this.enableSubGroups(),this.getBuiltin("subgroup_invocation_id","invocationSubgroupIndex","u32","attribute")}getSubgroupIndex(){return this.enableSubGroups(),this.getBuiltin("subgroup_id","subgroupIndex","u32","attribute")}getDrawIndex(){return null}getFrontFacing(){return this.getBuiltin("front_facing","isFront","bool")}getFragCoord(){return this.getBuiltin("position","fragCoord","vec4")+".xy"}getFragDepth(){return"output."+this.getBuiltin("frag_depth","depth","f32","output")}getClipDistance(){return"varyings.hw_clip_distances"}isFlipY(){return!1}enableDirective(e,t=this.shaderStage){(this.directives[t]||(this.directives[t]=new Set)).add(e)}getDirectives(e){const t=[],n=this.directives[e];if(void 0!==n)for(const e of n)t.push(`enable ${e};`);return t.join("\n")}enableSubGroups(){this.enableDirective("subgroups")}enableSubgroupsF16(){this.enableDirective("subgroups-f16")}enableClipDistances(){this.enableDirective("clip_distances")}enableShaderF16(){this.enableDirective("f16")}enableDualSourceBlending(){this.enableDirective("dual_source_blending")}enableHardwareClipping(e){this.enableClipDistances(),this.getBuiltin("clip_distances","hw_clip_distances",`array`,"vertex")}getBuiltins(e){const t=[],n=this.builtins[e];if(void 0!==n)for(const{name:e,property:i,type:r}of n.values())t.push(`@builtin( ${e} ) ${i} : ${r}`);return t.join(",\n\t")}getScopedArray(e,t,n,i){return!1===this.scopedArrays.has(e)&&this.scopedArrays.set(e,{name:e,scope:t,bufferType:n,bufferCount:i}),e}getScopedArrays(e){if("compute"!==e)return;const t=[];for(const{name:e,scope:n,bufferType:i,bufferCount:r}of this.scopedArrays.values()){const s=this.getType(i);t.push(`var<${n}> ${e}: array< ${s}, ${r} >;`)}return t.join("\n")}getAttributes(e){const t=[];if("compute"===e&&(this.getBuiltin("global_invocation_id","globalId","vec3","attribute"),this.getBuiltin("workgroup_id","workgroupId","vec3","attribute"),this.getBuiltin("local_invocation_id","localId","vec3","attribute"),this.getBuiltin("num_workgroups","numWorkgroups","vec3","attribute"),this.renderer.hasFeature("subgroups")&&(this.enableDirective("subgroups",e),this.getBuiltin("subgroup_size","subgroupSize","u32","attribute"))),"vertex"===e||"compute"===e){const e=this.getBuiltins("attribute");e&&t.push(e);const n=this.getAttributesArray();for(let e=0,i=n.length;e"),t.push(`\t${i+n.name} : ${r}`)}return e.output&&t.push(`\t${this.getBuiltins("output")}`),t.join(",\n")}getStructs(e){let t="";const n=this.structs[e];if(n.length>0){const e=[];for(const t of n){let n=`struct ${t.name} {\n`;n+=this.getStructMembers(t),n+="\n};",e.push(n)}t="\n"+e.join("\n\n")+"\n"}return t}getVar(e,t,n=null){let i=`var ${t} : `;return i+=null!==n?this.generateArrayDeclaration(e,n):this.getType(e),i}getVars(e){const t=[],n=this.vars[e];if(void 0!==n)for(const e of n)t.push(`\t${this.getVar(e.type,e.name,e.count)};`);return`\n${t.join("\n")}\n`}getVaryings(e){const t=[];if("vertex"===e&&this.getBuiltin("position","builtinClipSpace","vec4","vertex"),"vertex"===e||"fragment"===e){const n=this.varyings,i=this.vars[e];for(let r=0;rn.value.itemSize;return i&&!r}getUniforms(e){const t=this.uniforms[e],n=[],i=[],r=[],s={};for(const r of t){const t=r.groupNode.name,a=this.bindingsIndexes[t];if("texture"===r.type||"cubeTexture"===r.type||"cubeDepthTexture"===r.type||"storageTexture"===r.type||"texture3D"===r.type){const t=r.node.value;let i;(!0===t.isCubeTexture||!1===this.isUnfilterable(t)&&!0!==r.node.isStorageTextureNode)&&(this.isSampleCompare(t)?n.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var ${r.name}_sampler : sampler_comparison;`):n.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var ${r.name}_sampler : sampler;`));let s="";const{primarySamples:o}=this.renderer.backend.utils.getTextureSampleData(t);if(o>1&&(s="_multisampled"),!0===t.isCubeTexture&&!0===t.isDepthTexture)i="texture_depth_cube";else if(!0===t.isCubeTexture)i="texture_cube";else if(!0===t.isDepthTexture)i=this.renderer.backend.compatibilityMode&&null===t.compareFunction?`texture${s}_2d`:`texture_depth${s}_2d${!0===t.isArrayTexture?"_array":""}`;else if(!0===r.node.isStorageTextureNode){const n=pI(t),s=this.getStorageAccess(r.node,e),a=r.node.value.is3DTexture,o=r.node.value.isArrayTexture;i=`texture_storage_${a?"3d":"2d"+(o?"_array":"")}<${n}, ${s}>`}else if(!0===t.isArrayTexture||!0===t.isDataArrayTexture||!0===t.isCompressedArrayTexture)i="texture_2d_array";else if(!0===t.is3DTexture||!0===t.isData3DTexture)i="texture_3d";else{i=`texture${s}_2d<${this.getComponentTypeFromTexture(t).charAt(0)}32>`}n.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var ${r.name} : ${i};`)}else if("buffer"===r.type||"storageBuffer"===r.type||"indirectStorageBuffer"===r.type){const t=r.node,n=this.getType(t.getNodeType(this)),s=t.bufferCount,o=s>0&&"buffer"===r.type?", "+s:"",l=t.isStorageBufferNode?`storage, ${this.getStorageAccess(t,e)}`:"uniform";if(this.isCustomStruct(r))i.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var<${l}> ${r.name} : ${n};`);else{const e=`\tvalue : array< ${t.isAtomic?`atomic<${n}>`:`${n}`}${o} >`;i.push(this._getWGSLStructBinding(r.name,e,l,a.binding++,a.group))}}else{const e=r.groupNode.name;if(void 0===s[e]){const t=this.uniformGroups[e];if(void 0!==t){const n=[];for(const e of t.uniforms){const t=e.getType(),i=this.getType(this.getVectorType(t));n.push(`\t${e.name} : ${i}`)}let i=this.uniformGroupsBindings[e];void 0===i&&(i={index:a.binding++,id:a.group},this.uniformGroupsBindings[e]=i),s[e]={index:i.index,id:i.id,snippets:n}}}}}for(const e in s){const t=s[e];r.push(this._getWGSLStructBinding(e,t.snippets.join(",\n"),"uniform",t.index,t.id))}return[...n,...i,...r].join("\n")}buildCode(){const e=null!==this.material?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){this.shaderStage=t;const n=e[t];n.uniforms=this.getUniforms(t),n.attributes=this.getAttributes(t),n.varyings=this.getVaryings(t),n.structs=this.getStructs(t),n.vars=this.getVars(t),n.codes=this.getCodes(t),n.directives=this.getDirectives(t),n.scopedArrays=this.getScopedArrays(t);let i="// code\n\n";i+=this.flowCode[t];const r=this.flowNodes[t],s=r[r.length-1],a=s.outputNode,o=void 0!==a&&!0===a.isOutputStructNode;for(const e of r){const r=this.getFlowData(e),l=e.name;if(l&&(i.length>0&&(i+="\n"),i+=`\t// flow -> ${l}\n`),i+=`${r.code}\n\t`,e===s&&"compute"!==t)if(i+="// result\n\n\t","vertex"===t)i+=`varyings.builtinClipSpace = ${r.result};`;else if("fragment"===t)if(o)n.returnType=a.getNodeType(this),n.structs+="var output : "+n.returnType+";",i+=`return ${r.result};`;else{let e="\t@location(0) color: vec4";const t=this.getBuiltins("output");t&&(e+=",\n\t"+t),n.returnType="OutputStruct",n.structs+=this._getWGSLStruct("OutputStruct",e),n.structs+="\nvar output : OutputStruct;",i+=`output.color = ${r.result};\n\n\treturn output;`}}n.flow=i}if(this.shaderStage=null,null!==this.material)this.vertexShader=this._getWGSLVertexCode(e.vertex),this.fragmentShader=this._getWGSLFragmentCode(e.fragment);else{const t=this.object.workgroupSize;this.computeShader=this._getWGSLComputeCode(e.compute,t)}}getMethod(e,t=null){let n;return null!==t&&(n=this._getWGSLMethod(e+"_"+t)),void 0===n&&(n=this._getWGSLMethod(e)),n||e}getBitcastMethod(e){return`bitcast<${this.getType(e)}>`}getFloatPackingMethod(e){return this.getMethod(`floatpack_${e}_2x16`)}getFloatUnpackingMethod(e){return this.getMethod(`floatunpack_${e}_2x16`)}getTernary(e,t,n){return`select( ${n}, ${t}, ${e} )`}getType(e){return MI[e]||e}isAvailable(e){let t=TI[e];return void 0===t&&("float32Filterable"===e?t=this.renderer.hasFeature("float32-filterable"):"clipDistance"===e&&(t=this.renderer.hasFeature("clip-distances")),TI[e]=t),t}getUniformBufferLimit(){return this.renderer.backend.device.limits.maxUniformBufferBindingSize}_getWGSLMethod(e){return void 0!==wI[e]&&this._include(e),AI[e]}_include(e){const t=wI[e];return t.build(this),this.addInclude(t),t}_getWGSLVertexCode(e){return`${this.getSignature()}\n// directives\n${e.directives}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\nvar varyings : VaryingsStruct;\n\n// codes\n${e.codes}\n\n@vertex\nfn main( ${e.attributes} ) -> VaryingsStruct {\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n\treturn varyings;\n\n}\n`}_getWGSLFragmentCode(e){return`${this.getSignature()}\n// global\n${RI}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// codes\n${e.codes}\n\n@fragment\nfn main( ${e.varyings} ) -> ${e.returnType} {\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLComputeCode(e,t){const[n,i,r]=t;return`${this.getSignature()}\n// directives\n${e.directives}\n\n// system\nvar instanceIndex : u32;\n\n// locals\n${e.scopedArrays}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// codes\n${e.codes}\n\n@compute @workgroup_size( ${n}, ${i}, ${r} )\nfn main( ${e.attributes} ) {\n\n\t// system\n\tinstanceIndex = globalId.x\n\t\t+ globalId.y * ( ${n} * numWorkgroups.x )\n\t\t+ globalId.z * ( ${n} * numWorkgroups.x ) * ( ${i} * numWorkgroups.y );\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLStruct(e,t){return`\nstruct ${e} {\n${t}\n};`}_getWGSLStructBinding(e,t,n,i=0,r=0){const s=e+"Struct";return`${this._getWGSLStruct(s,t)}\n@binding( ${i} ) @group( ${r} )\nvar<${n}> ${e} : ${s};`}}class NI{constructor(e){this.backend=e}getCurrentDepthStencilFormat(e){let t;return e.depth&&(t=null!==e.depthTexture?this.getTextureFormatGPU(e.depthTexture):e.stencil?nL:tL),t}getTextureFormatGPU(e){return this.backend.get(e).format}getTextureSampleData(e){let t;if(e.isFramebufferTexture)t=1;else if(e.isDepthTexture&&!e.renderTarget){const e=this.backend.renderer,n=e.getRenderTarget();t=n?n.samples:e.currentSamples}else e.renderTarget&&(t=e.renderTarget.samples);t=t||1;const n=t>1&&null!==e.renderTarget&&!0!==e.isDepthTexture&&!0!==e.isFramebufferTexture;return{samples:t,primarySamples:n?1:t,isMSAA:n}}getCurrentColorFormat(e){let t;return t=null!==e.textures?this.getTextureFormatGPU(e.textures[0]):this.getPreferredCanvasFormat(),t}getCurrentColorFormats(e){return null!==e.textures?e.textures.map(e=>this.getTextureFormatGPU(e)):[this.getPreferredCanvasFormat()]}getCurrentColorSpace(e){return null!==e.textures?e.textures[0].colorSpace:this.backend.renderer.outputColorSpace}getPrimitiveTopology(e,t){return e.isPoints?KN:e.isLineSegments||e.isMesh&&!0===t.wireframe?ZN:e.isLine?QN:e.isMesh?JN:void 0}getSampleCount(e){return e>=4?4:1}getSampleCountRenderContext(e){return null!==e.textures?this.getSampleCount(e.sampleCount):this.getSampleCount(this.backend.renderer.currentSamples)}getPreferredCanvasFormat(){const e=this.backend.parameters.outputType;if(void 0===e)return navigator.gpu.getPreferredCanvasFormat();if(e===fe)return zP;if(e===xe)return KP;throw new Error("Unsupported output buffer type.")}}const PI=new Map([[Int8Array,["sint8","snorm8"]],[Uint8Array,["uint8","unorm8"]],[Int16Array,["sint16","snorm16"]],[Uint16Array,["uint16","unorm16"]],[Int32Array,["sint32","snorm32"]],[Uint32Array,["uint32","unorm32"]],[Float32Array,["float32"]]]);"undefined"!=typeof Float16Array&&PI.set(Float16Array,["float16"]);const LI=new Map([[sr,["float16"]]]),DI=new Map([[Int32Array,"sint32"],[Int16Array,"sint32"],[Uint32Array,"uint32"],[Uint16Array,"uint32"],[Float32Array,"float32"]]);class II{constructor(e){this.backend=e}createAttribute(e,t){const n=this._getBufferAttribute(e),i=this.backend,r=i.get(n);let s=r.buffer;if(void 0===s){const a=i.device;let o=n.array;if(!1===e.normalized)if(o.constructor===Int16Array||o.constructor===Int8Array)o=new Int32Array(o);else if((o.constructor===Uint16Array||o.constructor===Uint8Array)&&(o=new Uint32Array(o),t&GPUBufferUsage.INDEX))for(let e=0;e0&&(void 0===s.groups&&(s.groups=[],s.versions=[]),s.versions[n]===i&&(o=s.groups[n])),void 0===o&&(o=this.createBindGroup(e,a),n>0&&(s.groups[n]=o,s.versions[n]=i)),s.group=o}updateBinding(e){const t=this.backend,n=t.device,i=e.buffer,r=t.get(e).buffer,s=e.updateRanges;if(0===s.length)n.queue.writeBuffer(r,0,i,0);else{const e=Vt(i),t=e?1:i.BYTES_PER_ELEMENT;for(let a=0,o=s.length;a1&&(r+=`-${e.texture.depthOrArrayLayers}`),r+=`-${n}-${i}`,a=e[r],void 0===a){const s=eI;let o;o=t.isSampledCubeTexture?QD:t.isSampledTexture3D?JD:t.texture.isArrayTexture||t.texture.isDataArrayTexture||t.texture.isCompressedArrayTexture?ZD:KD,a=e[r]=e.texture.createView({aspect:s,dimension:o,mipLevelCount:n,baseMipLevel:i})}}s.push({binding:r,resource:a})}else if(t.isSampler){const e=n.get(t.texture);s.push({binding:r,resource:e.sampler})}r++}return i.createBindGroup({label:"bindGroup_"+e.name,layout:t,entries:s})}_createLayoutEntries(e){const t=[];let n=0;for(const i of e.bindings){const e=this.backend,r={binding:n,visibility:i.visibility};if(i.isUniformBuffer||i.isStorageBuffer){const e={};i.isStorageBuffer&&(i.visibility&eP.COMPUTE&&(i.access===$f||i.access===Wf)?e.type=FD:e.type=OD),r.buffer=e}else if(i.isSampledTexture&&i.store){const e={};e.format=this.backend.get(i.texture).texture.format;const t=i.access;e.access=t===$f?zD:t===Wf?BD:kD,i.texture.isArrayTexture?e.viewDimension=ZD:i.texture.is3DTexture&&(e.viewDimension=JD),r.storageTexture=e}else if(i.isSampledTexture){const t={},{primarySamples:n}=e.utils.getTextureSampleData(i.texture);if(n>1&&(t.multisampled=!0,i.texture.isDepthTexture||(t.sampleType=jD)),i.texture.isDepthTexture)e.compatibilityMode&&null===i.texture.compareFunction?t.sampleType=jD:t.sampleType=WD;else if(i.texture.isDataTexture||i.texture.isDataArrayTexture||i.texture.isData3DTexture){const e=i.texture.type;e===ve?t.sampleType=$D:e===ye?t.sampleType=XD:e===be&&(this.backend.hasFeature("float32-filterable")?t.sampleType=HD:t.sampleType=jD)}i.isSampledCubeTexture?t.viewDimension=QD:i.texture.isArrayTexture||i.texture.isDataArrayTexture||i.texture.isCompressedArrayTexture?t.viewDimension=ZD:i.isSampledTexture3D&&(t.viewDimension=JD),r.texture=t}else if(i.isSampler){const t={};i.texture.isDepthTexture&&(null!==i.texture.compareFunction&&e.hasCompatibility(zt)?t.type=GD:t.type=VD),r.sampler=t}else qt(`WebGPUBindingUtils: Unsupported binding "${i}".`);t.push(r),n++}return t}deleteBindGroupData(e){const{backend:t}=this,n=t.get(e);n.layout&&(n.layout.usedTimes--,0===n.layout.usedTimes&&this._bindGroupLayoutCache.delete(n.layoutKey),n.layout=void 0,n.layoutKey=void 0)}dispose(){this._bindGroupLayoutCache.clear()}}class OI{constructor(e){this.backend=e,this._activePipelines=new WeakMap}setPipeline(e,t){this._activePipelines.get(e)!==t&&(e.setPipeline(t),this._activePipelines.set(e,t))}_getSampleCount(e){return this.backend.utils.getSampleCountRenderContext(e)}createRenderPipeline(e,t){const{object:n,material:i,geometry:r,pipeline:s}=e,{vertexProgram:a,fragmentProgram:o}=s,l=this.backend,u=l.device,c=l.utils,h=l.get(s),d=[];for(const t of e.getBindings()){const e=l.get(t),{layoutGPU:n}=e.layout;d.push(n)}const p=l.attributeUtils.createShaderVertexBuffers(e);let f;0===i.blending||1===i.blending&&!1===i.transparent||(f=this._getBlending(i));let m={};!0===i.stencilWrite&&(m={compare:this._getStencilCompare(i),failOp:this._getStencilOperation(i.stencilFail),depthFailOp:this._getStencilOperation(i.stencilZFail),passOp:this._getStencilOperation(i.stencilZPass)});const g=this._getColorWriteMask(i),_=[];if(null!==e.context.textures){const t=e.context.textures,n=e.context.mrt;for(let e=0;e1},layout:u.createPipelineLayout({bindGroupLayouts:d})},E={},w=e.context.depth,A=e.context.stencil;if(!0!==w&&!0!==A||(!0===w&&(E.format=T,E.depthWriteEnabled=i.depthWrite,E.depthCompare=x),!0===A&&(E.stencilFront=m,E.stencilBack=m,E.stencilReadMask=i.stencilFuncMask,E.stencilWriteMask=i.stencilWriteMask),!0===i.polygonOffset&&(E.depthBias=i.polygonOffsetUnits,E.depthBiasSlopeScale=i.polygonOffsetFactor,E.depthBiasClamp=0),M.depthStencil=E),u.pushErrorScope("validation"),null===t)h.pipeline=u.createRenderPipeline(M),u.popErrorScope().then(e=>{null!==e&&(h.error=!0,qt(e.message))});else{const e=new Promise(async e=>{try{h.pipeline=await u.createRenderPipelineAsync(M)}catch(e){}const t=await u.popErrorScope();null!==t&&(h.error=!0,qt(t.message)),e()});t.push(e)}}createBundleEncoder(e,t="renderBundleEncoder"){const n=this.backend,{utils:i,device:r}=n,s=i.getCurrentDepthStencilFormat(e),a={label:t,colorFormats:i.getCurrentColorFormats(e),depthStencilFormat:s,sampleCount:this._getSampleCount(e)};return r.createRenderBundleEncoder(a)}createComputePipeline(e,t){const n=this.backend,i=n.device,r=n.get(e.computeProgram).module,s=n.get(e),a=[];for(const e of t){const t=n.get(e),{layoutGPU:i}=t.layout;a.push(i)}s.pipeline=i.createComputePipeline({compute:r,layout:i.createPipelineLayout({bindGroupLayouts:a})})}_getBlending(e){let t,n;const i=e.blending,r=e.blendSrc,s=e.blendDst,a=e.blendEquation;if(5===i){const i=null!==e.blendSrcAlpha?e.blendSrcAlpha:r,o=null!==e.blendDstAlpha?e.blendDstAlpha:s,l=null!==e.blendEquationAlpha?e.blendEquationAlpha:a;t={srcFactor:this._getBlendFactor(r),dstFactor:this._getBlendFactor(s),operation:this._getBlendOperation(a)},n={srcFactor:this._getBlendFactor(i),dstFactor:this._getBlendFactor(o),operation:this._getBlendOperation(l)}}else{const r=(e,i,r,s)=>{t={srcFactor:e,dstFactor:i,operation:xD},n={srcFactor:r,dstFactor:s,operation:xD}};if(e.premultipliedAlpha)switch(i){case 1:r(uD,pD,uD,pD);break;case 2:r(uD,uD,uD,uD);break;case 3:r(lD,hD,lD,uD);break;case 4:r(fD,pD,lD,uD)}else switch(i){case 1:r(dD,pD,uD,pD);break;case 2:r(dD,uD,uD,uD);break;case 3:qt(`WebGPURenderer: "SubtractiveBlending" requires "${e.isMaterial?"material":"blendMode"}.premultipliedAlpha = true".`);break;case 4:qt(`WebGPURenderer: "MultiplyBlending" requires "${e.isMaterial?"material":"blendMode"}.premultipliedAlpha = true".`)}}if(void 0!==t&&void 0!==n)return{color:t,alpha:n};qt("WebGPURenderer: Invalid blending: ",i)}_getBlendFactor(e){let t;switch(e){case x:t=lD;break;case 201:t=uD;break;case 202:t=cD;break;case 203:t=hD;break;case E:t=dD;break;case w:t=pD;break;case 208:t=fD;break;case 209:t=mD;break;case 206:t=gD;break;case 207:t=_D;break;case 210:t=vD;break;case 211:t=yD;break;case 212:t=bD;break;default:qt("WebGPURenderer: Blend factor not supported.",e)}return t}_getStencilCompare(e){let t;const n=e.stencilFunc;switch(n){case 512:t=tP;break;case 519:t=lP;break;case 513:t=nP;break;case 515:t=rP;break;case 514:t=iP;break;case 518:t=oP;break;case 516:t=sP;break;case 517:t=aP;break;default:qt("WebGPURenderer: Invalid stencil function.",n)}return t}_getStencilOperation(e){let t;switch(e){case Mt:t=RD;break;case 0:t=CD;break;case 7681:t=ND;break;case 5386:t=PD;break;case 7682:t=LD;break;case 7683:t=DD;break;case 34055:t=ID;break;case 34056:t=UD;break;default:qt("WebGPURenderer: Invalid stencil operation.",t)}return t}_getBlendOperation(e){let t;switch(e){case v:t=xD;break;case 101:t=TD;break;case 102:t=SD;break;case 103:t=MD;break;case 104:t=ED;break;default:qt("WebGPUPipelineUtils: Blend equation not supported.",e)}return t}_getPrimitiveState(e,t,n){const i={},r=this.backend.utils;i.topology=r.getPrimitiveTopology(e,n),null!==t.index&&!0===e.isLine&&!0!==e.isLineSegments&&(i.stripIndexFormat=t.index.array instanceof Uint16Array?gP:_P);let s=1===n.side;return e.isMesh&&e.matrixWorld.determinant()<0&&(s=!s),i.frontFace=!0===s?pP:dP,i.cullMode=2===n.side?fP:mP,i}_getColorWriteMask(e){return!0===e.colorWrite?AD:wD}_getDepthCompare(e){let t;if(!1===e.depthTest)t=lP;else{const n=this.backend.parameters.reversedDepthBuffer?Kt[e.depthFunc]:e.depthFunc;switch(n){case 0:t=tP;break;case 1:t=lP;break;case 2:t=nP;break;case 3:t=rP;break;case 4:t=iP;break;case 5:t=oP;break;case 6:t=sP;break;case 7:t=aP;break;default:qt("WebGPUPipelineUtils: Invalid depth function.",n)}}return t}}class BI extends XN{constructor(e,t,n=2048){super(n),this.device=e,this.type=t,this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxQueries,label:`queryset_global_timestamp_${t}`});const i=8*this.maxQueries;this.resolveBuffer=this.device.createBuffer({label:`buffer_timestamp_resolve_${t}`,size:i,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.resultBuffer=this.device.createBuffer({label:`buffer_timestamp_result_${t}`,size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ})}allocateQueriesForContext(e){if(!this.trackTimestamp||this.isDisposed)return null;if(this.currentQueryIndex+2>this.maxQueries)return Yt(`WebGPUTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryOffsets.set(e,t),t}async resolveQueriesAsync(){if(!this.trackTimestamp||0===this.currentQueryIndex||this.isDisposed)return this.lastValue;if(this.pendingResolve)return this.pendingResolve;this.pendingResolve=this._resolveQueries();try{return await this.pendingResolve}finally{this.pendingResolve=null}}async _resolveQueries(){if(this.isDisposed)return this.lastValue;try{if("unmapped"!==this.resultBuffer.mapState)return this.lastValue;const e=new Map(this.queryOffsets),t=this.currentQueryIndex,n=8*t;this.currentQueryIndex=0,this.queryOffsets.clear();const i=this.device.createCommandEncoder();i.resolveQuerySet(this.querySet,0,t,this.resolveBuffer,0),i.copyBufferToBuffer(this.resolveBuffer,0,this.resultBuffer,0,n);const r=i.finish();if(this.device.queue.submit([r]),"unmapped"!==this.resultBuffer.mapState)return this.lastValue;if(await this.resultBuffer.mapAsync(GPUMapMode.READ,0,n),this.isDisposed)return"mapped"===this.resultBuffer.mapState&&this.resultBuffer.unmap(),this.lastValue;const s=new BigUint64Array(this.resultBuffer.getMappedRange(0,n)),a={},o=[];for(const[t,n]of e){const e=t.match(/^(.*):f(\d+)$/),i=parseInt(e[2]);!1===o.includes(i)&&o.push(i),void 0===a[i]&&(a[i]=0);const r=s[n],l=s[n+1],u=Number(l-r)/1e6;this.timestamps.set(t,u),a[i]+=u}const l=a[o[o.length-1]];return this.resultBuffer.unmap(),this.lastValue=l,this.frames=o,l}catch(e){return qt("Error resolving queries:",e),"mapped"===this.resultBuffer.mapState&&this.resultBuffer.unmap(),this.lastValue}}async dispose(){if(!this.isDisposed){if(this.isDisposed=!0,this.pendingResolve)try{await this.pendingResolve}catch(e){qt("Error waiting for pending resolve:",e)}if(this.resultBuffer&&"mapped"===this.resultBuffer.mapState)try{this.resultBuffer.unmap()}catch(e){qt("Error unmapping buffer:",e)}this.querySet&&(this.querySet.destroy(),this.querySet=null),this.resolveBuffer&&(this.resolveBuffer.destroy(),this.resolveBuffer=null),this.resultBuffer&&(this.resultBuffer.destroy(),this.resultBuffer=null),this.queryOffsets.clear(),this.pendingResolve=null}}}class kI extends CN{constructor(e={}){super(e),this.isWebGPUBackend=!0,this.parameters.alpha=void 0===e.alpha||e.alpha,this.parameters.requiredLimits=void 0===e.requiredLimits?{}:e.requiredLimits,this.compatibilityMode=null,this.device=null,this.defaultRenderPassdescriptor=null,this.utils=new NI(this),this.attributeUtils=new II(this),this.bindingUtils=new FI(this),this.pipelineUtils=new OI(this),this.textureUtils=new dI(this),this.occludedResolveCache=new Map;const t="undefined"==typeof navigator||!1===/Android/.test(navigator.userAgent);this._compatibility={[zt]:t}}async init(e){await super.init(e);const t=this.parameters;let n;if(void 0===t.device){const e={powerPreference:t.powerPreference,featureLevel:"compatibility"},i="undefined"!=typeof navigator?await navigator.gpu.requestAdapter(e):null;if(null===i)throw new Error("WebGPUBackend: Unable to create WebGPU adapter.");const r=Object.values(iI),s=[];for(const e of r)i.features.has(e)&&s.push(e);const a={requiredFeatures:s,requiredLimits:t.requiredLimits};n=await i.requestDevice(a)}else n=t.device;this.compatibilityMode=!n.features.has("core-features-and-limits"),this.compatibilityMode&&(e._samples=0),n.lost.then(t=>{if("destroyed"===t.reason)return;const n={api:"WebGPU",message:t.message||"Unknown reason",reason:t.reason||null,originalEvent:t};e.onDeviceLost(n)}),this.device=n,this.trackTimestamp=this.trackTimestamp&&this.hasFeature(iI.TimestampQuery),this.updateSize()}get context(){const e=this.renderer.getCanvasTarget(),t=this.get(e);let n=t.context;if(void 0===n){const i=this.parameters;n=!0===e.isDefaultCanvasTarget&&void 0!==i.context?i.context:e.domElement.getContext("webgpu"),"setAttribute"in e.domElement&&e.domElement.setAttribute("data-engine",`three.js r${s} webgpu`);const r=i.alpha?"premultiplied":"opaque",a=i.outputType===xe?"extended":"standard";n.configure({device:this.device,format:this.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:r,toneMapping:{mode:a}}),t.context=n}return n}get coordinateSystem(){return Ot}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}getContext(){return this.context}_getDefaultRenderPassDescriptor(){const e=this.renderer,t=e.getCanvasTarget(),n=this.get(t),i=e.currentSamples;let r=n.descriptor;if(void 0===r||n.samples!==i){r={colorAttachments:[{view:null}]},!0!==e.depth&&!0!==e.stencil||(r.depthStencilAttachment={view:this.textureUtils.getDepthBuffer(e.depth,e.stencil).createView()});const t=r.colorAttachments[0];i>0?t.view=this.textureUtils.getColorBuffer().createView():t.resolveTarget=void 0,n.descriptor=r,n.samples=i}const s=r.colorAttachments[0];return i>0?s.resolveTarget=this.context.getCurrentTexture().createView():s.view=this.context.getCurrentTexture().createView(),r}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.image.depth>1&&e.camera.isArrayCamera}_getRenderPassDescriptor(e,t={}){const n=e.renderTarget,i=this.get(n);let r=i.descriptors;void 0!==r&&i.width===n.width&&i.height===n.height&&i.samples===n.samples||(r={},i.descriptors=r);const s=e.getCacheKey();let a=r[s];if(void 0===a){const t=e.textures,o=[];let l;const u=this._isRenderCameraDepthArray(e);for(let i=0;i1)if(!0===u){const t=e.camera.cameras;for(let e=0;e0&&(t.currentOcclusionQuerySet&&t.currentOcclusionQuerySet.destroy(),t.currentOcclusionQueryBuffer&&t.currentOcclusionQueryBuffer.destroy(),t.currentOcclusionQuerySet=t.occlusionQuerySet,t.currentOcclusionQueryBuffer=t.occlusionQueryBuffer,t.currentOcclusionQueryObjects=t.occlusionQueryObjects,r=n.createQuerySet({type:"occlusion",count:i,label:`occlusionQuerySet_${e.id}`}),t.occlusionQuerySet=r,t.occlusionQueryIndex=0,t.occlusionQueryObjects=new Array(i),t.lastOcclusionObject=null),s=null===e.textures?this._getDefaultRenderPassDescriptor():this._getRenderPassDescriptor(e,{loadOp:cP}),this.initTimestampQuery(kt,this.getTimestampUID(e),s),s.occlusionQuerySet=r;const a=s.depthStencilAttachment;if(null!==e.textures){const t=s.colorAttachments;for(let n=0;n0&&t.currentPass.executeBundles(t.renderBundles),n>t.occlusionQueryIndex&&t.currentPass.endOcclusionQuery();const i=t.encoder;if(!0===this._isRenderCameraDepthArray(e)){const n=[];for(let e=0;e0){const i=8*n;let r=this.occludedResolveCache.get(i);void 0===r&&(r=this.device.createBuffer({size:i,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.occludedResolveCache.set(i,r));const s=this.device.createBuffer({size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});t.encoder.resolveQuerySet(t.occlusionQuerySet,0,n,r,0),t.encoder.copyBufferToBuffer(r,0,s,0,i),t.occlusionQueryBuffer=s,this.resolveOccludedAsync(e)}if(this.device.queue.submit([t.encoder.finish()]),null!==e.textures){const t=e.textures;for(let e=0;eo&&(r[0]=Math.min(a,o),r[1]=Math.ceil(a/o)),s.dispatchSize=r}r=s.dispatchSize}a.dispatchWorkgroups(r[0],r[1]||1,r[2]||1)}finishCompute(e){const t=this.get(e);t.passEncoderGPU.end(),this.device.queue.submit([t.cmdEncoderGPU.finish()])}draw(e,t){const{object:n,material:i,context:r,pipeline:s}=e,a=e.getBindings(),o=this.get(r),l=this.get(s),u=l.pipeline;if(!0===l.error)return;const c=e.getIndex(),h=null!==c,d=e.getDrawParameters();if(null===d)return;const p=(t,n)=>{this.pipelineUtils.setPipeline(t,u),n.pipeline=u;const s=n.bindingGroups;for(let e=0,n=a.length;e{if(p(r,s),!0===n.isBatchedMesh){const e=n._multiDrawStarts,s=n._multiDrawCounts,a=n._multiDrawCount,o=n._multiDrawInstances;null!==o&&Yt("WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.");let l=!0===h?c.array.BYTES_PER_ELEMENT:1;i.wireframe&&(l=n.geometry.attributes.position.count>65535?4:2);for(let i=0;i1?0:i;!0===h?r.drawIndexed(s[i],a,e[i]/l,0,u):r.draw(s[i],a,e[i],u),t.update(n,s[i],a)}}else if(!0===h){const{vertexCount:i,instanceCount:s,firstVertex:a}=d,o=e.getIndirect();if(null!==o){const t=this.get(o).buffer,n=e.getIndirectOffset(),i=Array.isArray(n)?n:[n];for(let e=0;e0){const t=this.get(e.camera),i=e.camera.cameras,s=e.getBindingGroup("cameraIndex");if(void 0===t.indexesGPU||t.indexesGPU.length!==i.length){const e=this.get(s),n=[],r=new Uint32Array([0,0,0,0]);for(let t=0,s=i.length;t(Xt("WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new YN(e)));super(new t(e),e),this.library=new GI,this.isWebGPURenderer=!0,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}}const jI={type:"change"},WI={type:"start"},$I={type:"end"},XI=1e-6,qI=-1,YI=0,KI=1,ZI=2,QI=3,JI=4,eU=new cn,tU=new cn,nU=new dn,iU=new dn,rU=new dn,sU=new hn,aU=new dn,oU=new dn,lU=new dn,uU=new dn;class cU extends Xa{constructor(e,t=null){super(e,t),this.screen={left:0,top:0,width:0,height:0},this.rotateSpeed=1,this.zoomSpeed=1.2,this.panSpeed=.3,this.noRotate=!1,this.noZoom=!1,this.noPan=!1,this.staticMoving=!1,this.dynamicDampingFactor=.2,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.keys=["KeyA","KeyS","KeyD"],this.mouseButtons={LEFT:a,MIDDLE:o,RIGHT:l},this.target=new dn,this.state=qI,this.keyState=qI,this._lastPosition=new dn,this._lastZoom=1,this._touchZoomDistanceStart=0,this._touchZoomDistanceEnd=0,this._lastAngle=0,this._eye=new dn,this._movePrev=new cn,this._moveCurr=new cn,this._lastAxis=new dn,this._zoomStart=new cn,this._zoomEnd=new cn,this._panStart=new cn,this._panEnd=new cn,this._pointers=[],this._pointerPositions={},this._onPointerMove=dU.bind(this),this._onPointerDown=hU.bind(this),this._onPointerUp=pU.bind(this),this._onPointerCancel=fU.bind(this),this._onContextMenu=xU.bind(this),this._onMouseWheel=bU.bind(this),this._onKeyDown=gU.bind(this),this._onKeyUp=mU.bind(this),this._onTouchStart=TU.bind(this),this._onTouchMove=SU.bind(this),this._onTouchEnd=MU.bind(this),this._onMouseDown=_U.bind(this),this._onMouseMove=vU.bind(this),this._onMouseUp=yU.bind(this),this._target0=this.target.clone(),this._position0=this.object.position.clone(),this._up0=this.object.up.clone(),this._zoom0=this.object.zoom,null!==t&&(this.connect(t),this.handleResize()),this.update()}connect(e){super.connect(e),window.addEventListener("keydown",this._onKeyDown),window.addEventListener("keyup",this._onKeyUp),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerCancel),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction="none"}disconnect(){window.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("keyup",this._onKeyUp),this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerCancel),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction="auto"}dispose(){this.disconnect()}handleResize(){const e=this.domElement.getBoundingClientRect(),t=this.domElement.ownerDocument.documentElement;this.screen.left=e.left+window.pageXOffset-t.clientLeft,this.screen.top=e.top+window.pageYOffset-t.clientTop,this.screen.width=e.width,this.screen.height=e.height}update(){this._eye.subVectors(this.object.position,this.target),this.noRotate||this._rotateCamera(),this.noZoom||this._zoomCamera(),this.noPan||this._panCamera(),this.object.position.addVectors(this.target,this._eye),this.object.isPerspectiveCamera?(this._checkDistances(),this.object.lookAt(this.target),this._lastPosition.distanceToSquared(this.object.position)>XI&&(this.dispatchEvent(jI),this._lastPosition.copy(this.object.position))):this.object.isOrthographicCamera?(this.object.lookAt(this.target),(this._lastPosition.distanceToSquared(this.object.position)>XI||this._lastZoom!==this.object.zoom)&&(this.dispatchEvent(jI),this._lastPosition.copy(this.object.position),this._lastZoom=this.object.zoom)):console.warn("THREE.TrackballControls: Unsupported camera type.")}reset(){this.state=qI,this.keyState=qI,this.target.copy(this._target0),this.object.position.copy(this._position0),this.object.up.copy(this._up0),this.object.zoom=this._zoom0,this.object.updateProjectionMatrix(),this._eye.subVectors(this.object.position,this.target),this.object.lookAt(this.target),this.dispatchEvent(jI),this._lastPosition.copy(this.object.position),this._lastZoom=this.object.zoom}_panCamera(){if(tU.copy(this._panEnd).sub(this._panStart),tU.lengthSq()){if(this.object.isOrthographicCamera){const e=(this.object.right-this.object.left)/this.object.zoom/this.domElement.clientWidth,t=(this.object.top-this.object.bottom)/this.object.zoom/this.domElement.clientWidth;tU.x*=e,tU.y*=t}tU.multiplyScalar(this._eye.length()*this.panSpeed),iU.copy(this._eye).cross(this.object.up).setLength(tU.x),iU.add(nU.copy(this.object.up).setLength(tU.y)),this.object.position.add(iU),this.target.add(iU),this.staticMoving?this._panStart.copy(this._panEnd):this._panStart.add(tU.subVectors(this._panEnd,this._panStart).multiplyScalar(this.dynamicDampingFactor))}}_rotateCamera(){uU.set(this._moveCurr.x-this._movePrev.x,this._moveCurr.y-this._movePrev.y,0);let e=uU.length();e?(this._eye.copy(this.object.position).sub(this.target),aU.copy(this._eye).normalize(),oU.copy(this.object.up).normalize(),lU.crossVectors(oU,aU).normalize(),oU.setLength(this._moveCurr.y-this._movePrev.y),lU.setLength(this._moveCurr.x-this._movePrev.x),uU.copy(oU.add(lU)),rU.crossVectors(uU,this._eye).normalize(),e*=this.rotateSpeed,sU.setFromAxisAngle(rU,e),this._eye.applyQuaternion(sU),this.object.up.applyQuaternion(sU),this._lastAxis.copy(rU),this._lastAngle=e):!this.staticMoving&&this._lastAngle&&(this._lastAngle*=Math.sqrt(1-this.dynamicDampingFactor),this._eye.copy(this.object.position).sub(this.target),sU.setFromAxisAngle(this._lastAxis,this._lastAngle),this._eye.applyQuaternion(sU),this.object.up.applyQuaternion(sU)),this._movePrev.copy(this._moveCurr)}_zoomCamera(){let e;this.state===JI?(e=this._touchZoomDistanceStart/this._touchZoomDistanceEnd,this._touchZoomDistanceStart=this._touchZoomDistanceEnd,this.object.isPerspectiveCamera?this._eye.multiplyScalar(e):this.object.isOrthographicCamera?(this.object.zoom=un.clamp(this.object.zoom/e,this.minZoom,this.maxZoom),this._lastZoom!==this.object.zoom&&this.object.updateProjectionMatrix()):console.warn("THREE.TrackballControls: Unsupported camera type")):(e=1+(this._zoomEnd.y-this._zoomStart.y)*this.zoomSpeed,1!==e&&e>0&&(this.object.isPerspectiveCamera?this._eye.multiplyScalar(e):this.object.isOrthographicCamera?(this.object.zoom=un.clamp(this.object.zoom/e,this.minZoom,this.maxZoom),this._lastZoom!==this.object.zoom&&this.object.updateProjectionMatrix()):console.warn("THREE.TrackballControls: Unsupported camera type")),this.staticMoving?this._zoomStart.copy(this._zoomEnd):this._zoomStart.y+=(this._zoomEnd.y-this._zoomStart.y)*this.dynamicDampingFactor)}_getMouseOnScreen(e,t){return eU.set((e-this.screen.left)/this.screen.width,(t-this.screen.top)/this.screen.height),eU}_getMouseOnCircle(e,t){return eU.set((e-.5*this.screen.width-this.screen.left)/(.5*this.screen.width),(this.screen.height+2*(this.screen.top-t))/this.screen.width),eU}_addPointer(e){this._pointers.push(e)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;tthis.maxDistance*this.maxDistance&&(this.object.position.addVectors(this.target,this._eye.setLength(this.maxDistance)),this._zoomStart.copy(this._zoomEnd)),this._eye.lengthSq()Math.PI&&(n-=LU),i<-Math.PI?i+=LU:i>Math.PI&&(i-=LU),this._spherical.theta=n<=i?Math.max(n,Math.min(i,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(),!0===this.enableDamping?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 r=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const e=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),r=e!=this._spherical.radius}if(PU.setFromSpherical(this._spherical),PU.applyQuaternion(this._quatInverse),t.copy(this.target).add(PU),this.object.lookAt(this.target),!0===this.enableDamping?(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 e=null;if(this.object.isPerspectiveCamera){const t=PU.length();e=this._clampDistance(t*this._scale);const n=t-e;this.object.position.addScaledVector(this._dollyDirection,n),this.object.updateMatrixWorld(),r=!!n}else if(this.object.isOrthographicCamera){const t=new dn(this._mouse.x,this._mouse.y,0);t.unproject(this.object);const n=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),r=n!==this.object.zoom;const i=new dn(this._mouse.x,this._mouse.y,0);i.unproject(this.object),this.object.position.sub(i).add(t),this.object.updateMatrixWorld(),e=PU.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;null!==e&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(e).add(this.object.position):(RU.origin.copy(this.object.position),RU.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(RU.direction))VU||8*(1-this._lastQuaternion.dot(this.object.quaternion))>VU||this._lastTargetPosition.distanceToSquared(this.target)>VU)&&(this.dispatchEvent(EU),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0)}_getAutoRotationAngle(e){return null!==e?LU/60*this.autoRotateSpeed*e:LU/60/60*this.autoRotateSpeed}_getZoomScale(e){const t=Math.abs(.01*e);return Math.pow(.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){PU.setFromMatrixColumn(t,0),PU.multiplyScalar(-e),this._panOffset.add(PU)}_panUp(e,t){!0===this.screenSpacePanning?PU.setFromMatrixColumn(t,1):(PU.setFromMatrixColumn(t,0),PU.crossVectors(this.object.up,PU)),PU.multiplyScalar(e),this._panOffset.add(PU)}_pan(e,t){const n=this.domElement;if(this.object.isPerspectiveCamera){const i=this.object.position;PU.copy(i).sub(this.target);let r=PU.length();r*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*r/n.clientHeight,this.object.matrix),this._panUp(2*t*r/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;const n=this.domElement.getBoundingClientRect(),i=e-n.left,r=t-n.top,s=n.width,a=n.height;this._mouse.x=i/s*2-1,this._mouse.y=-r/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);const t=this.domElement;this._rotateLeft(LU*this._rotateDelta.x/t.clientHeight),this._rotateUp(LU*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(LU*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(-LU*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(LU*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(-LU*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),t=!0}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(1===this._pointers.length)this._rotateStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._rotateStart.set(n,i)}}_handleTouchStartPan(e){if(1===this._pointers.length)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._panStart.set(n,i)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,i=e.pageY-t.y,r=Math.sqrt(n*n+i*i);this._dollyStart.set(0,r)}_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(1==this._pointers.length)this._rotateEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._rotateEnd.set(n,i)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(LU*this._rotateDelta.x/t.clientHeight),this._rotateUp(LU*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(1===this._pointers.length)this._panEnd.set(e.pageX,e.pageY);else{const 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){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,i=e.pageY-t.y,r=Math.sqrt(n*n+i*i);this._dollyEnd.set(0,r),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const s=.5*(e.pageX+t.x),a=.5*(e.pageY+t.y);this._updateZoomParameters(s,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;tnF||8*(1-this._lastQuaternion.dot(t.quaternion))>nF)&&(this.dispatchEvent(tF),this._lastQuaternion.copy(t.quaternion),this._lastPosition.copy(t.position))}_updateMovementVector(){const e=this._moveState.forward||this.autoForward&&!this._moveState.back?1:0;this._moveVector.x=-this._moveState.left+this._moveState.right,this._moveVector.y=-this._moveState.down+this._moveState.up,this._moveVector.z=-e+this._moveState.back}_updateRotationVector(){this._rotationVector.x=-this._moveState.pitchDown+this._moveState.pitchUp,this._rotationVector.y=-this._moveState.yawRight+this._moveState.yawLeft,this._rotationVector.z=-this._moveState.rollRight+this._moveState.rollLeft}_getContainerDimensions(){return this.domElement!=document?{size:[this.domElement.offsetWidth,this.domElement.offsetHeight],offset:[this.domElement.offsetLeft,this.domElement.offsetTop]}:{size:[window.innerWidth,window.innerHeight],offset:[0,0]}}}function sF(e){if(!e.altKey&&!1!==this.enabled){switch(e.code){case"ShiftLeft":case"ShiftRight":this.movementSpeedMultiplier=.1;break;case"KeyW":this._moveState.forward=1;break;case"KeyS":this._moveState.back=1;break;case"KeyA":this._moveState.left=1;break;case"KeyD":this._moveState.right=1;break;case"KeyR":this._moveState.up=1;break;case"KeyF":this._moveState.down=1;break;case"ArrowUp":this._moveState.pitchUp=1;break;case"ArrowDown":this._moveState.pitchDown=1;break;case"ArrowLeft":this._moveState.yawLeft=1;break;case"ArrowRight":this._moveState.yawRight=1;break;case"KeyQ":this._moveState.rollLeft=1;break;case"KeyE":this._moveState.rollRight=1}this._updateMovementVector(),this._updateRotationVector()}}function aF(e){if(!1!==this.enabled){switch(e.code){case"ShiftLeft":case"ShiftRight":this.movementSpeedMultiplier=1;break;case"KeyW":this._moveState.forward=0;break;case"KeyS":this._moveState.back=0;break;case"KeyA":this._moveState.left=0;break;case"KeyD":this._moveState.right=0;break;case"KeyR":this._moveState.up=0;break;case"KeyF":this._moveState.down=0;break;case"ArrowUp":this._moveState.pitchUp=0;break;case"ArrowDown":this._moveState.pitchDown=0;break;case"ArrowLeft":this._moveState.yawLeft=0;break;case"ArrowRight":this._moveState.yawRight=0;break;case"KeyQ":this._moveState.rollLeft=0;break;case"KeyE":this._moveState.rollRight=0}this._updateMovementVector(),this._updateRotationVector()}}function oF(e){if(!1!==this.enabled)if(this.dragToLook)this._status++;else{switch(e.button){case 0:this._moveState.forward=1;break;case 2:this._moveState.back=1}this._updateMovementVector()}}function lF(e){if(!1!==this.enabled&&(!this.dragToLook||this._status>0)){const t=this._getContainerDimensions(),n=t.size[0]/2,i=t.size[1]/2;this._moveState.yawLeft=-(e.pageX-t.offset[0]-n)/n,this._moveState.pitchDown=(e.pageY-t.offset[1]-i)/i,this._updateRotationVector()}}function uF(e){if(!1!==this.enabled){if(this.dragToLook)this._status--,this._moveState.yawLeft=this._moveState.pitchDown=0;else{switch(e.button){case 0:this._moveState.forward=0;break;case 2:this._moveState.back=0}this._updateMovementVector()}this._updateRotationVector()}}function cF(){!1!==this.enabled&&(this.dragToLook?(this._status=0,this._moveState.yawLeft=this._moveState.pitchDown=0):(this._moveState.forward=0,this._moveState.back=0,this._updateMovementVector()),this._updateRotationVector())}function hF(e){!1!==this.enabled&&e.preventDefault()}const dF={name:"CopyShader",uniforms:{tDiffuse:{value:null},opacity:{value:1}},vertexShader:"\n\n\t\tvarying vec2 vUv;\n\n\t\tvoid main() {\n\n\t\t\tvUv = uv;\n\t\t\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\n\t\t}",fragmentShader:"\n\n\t\tuniform float opacity;\n\n\t\tuniform sampler2D tDiffuse;\n\n\t\tvarying vec2 vUv;\n\n\t\tvoid main() {\n\n\t\t\tvec4 texel = texture2D( tDiffuse, vUv );\n\t\t\tgl_FragColor = opacity * texel;\n\n\n\t\t}"};class pF{constructor(){this.isPass=!0,this.enabled=!0,this.needsSwap=!0,this.clear=!1,this.renderToScreen=!1}setSize(){}render(){console.error("THREE.Pass: .render() must be implemented in derived pass.")}dispose(){}}const fF=new Ra(-1,1,1,-1,0,1);const mF=new class extends vr{constructor(){super(),this.setAttribute("position",new ar([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new ar([0,2,0,0,2,0],2))}};class gF{constructor(e){this._mesh=new Wr(mF,e)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,fF)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}}class _F extends pF{constructor(e,t="tDiffuse"){super(),this.textureID=t,this.uniforms=null,this.material=null,e instanceof Ws?(this.uniforms=e.uniforms,this.material=e):e&&(this.uniforms=js.clone(e.uniforms),this.material=new Ws({name:void 0!==e.name?e.name:"unspecified",defines:Object.assign({},e.defines),uniforms:this.uniforms,vertexShader:e.vertexShader,fragmentShader:e.fragmentShader})),this._fsQuad=new gF(this.material)}render(e,t,n){this.uniforms[this.textureID]&&(this.uniforms[this.textureID].value=n.texture),this._fsQuad.material=this.material,this.renderToScreen?(e.setRenderTarget(null),this._fsQuad.render(e)):(e.setRenderTarget(t),this.clear&&e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil),this._fsQuad.render(e))}dispose(){this.material.dispose(),this._fsQuad.dispose()}}class vF extends pF{constructor(e,t){super(),this.scene=e,this.camera=t,this.clear=!0,this.needsSwap=!1,this.inverse=!1}render(e,t,n){const i=e.getContext(),r=e.state;let s,a;r.buffers.color.setMask(!1),r.buffers.depth.setMask(!1),r.buffers.color.setLocked(!0),r.buffers.depth.setLocked(!0),this.inverse?(s=0,a=1):(s=1,a=0),r.buffers.stencil.setTest(!0),r.buffers.stencil.setOp(i.REPLACE,i.REPLACE,i.REPLACE),r.buffers.stencil.setFunc(i.ALWAYS,s,4294967295),r.buffers.stencil.setClear(a),r.buffers.stencil.setLocked(!0),e.setRenderTarget(n),this.clear&&e.clear(),e.render(this.scene,this.camera),e.setRenderTarget(t),this.clear&&e.clear(),e.render(this.scene,this.camera),r.buffers.color.setLocked(!1),r.buffers.depth.setLocked(!1),r.buffers.color.setMask(!0),r.buffers.depth.setMask(!0),r.buffers.stencil.setLocked(!1),r.buffers.stencil.setFunc(i.EQUAL,1,4294967295),r.buffers.stencil.setOp(i.KEEP,i.KEEP,i.KEEP),r.buffers.stencil.setLocked(!0)}}class yF extends pF{constructor(){super(),this.needsSwap=!1}render(e){e.state.buffers.stencil.setLocked(!1),e.state.buffers.stencil.setTest(!1)}}class bF{constructor(e,t){if(this.renderer=e,this._pixelRatio=e.getPixelRatio(),void 0===t){const n=e.getSize(new cn);this._width=n.width,this._height=n.height,(t=new Dn(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:xe})).texture.name="EffectComposer.rt1"}else this._width=t.width,this._height=t.height;this.renderTarget1=t,this.renderTarget2=t.clone(),this.renderTarget2.texture.name="EffectComposer.rt2",this.writeBuffer=this.renderTarget1,this.readBuffer=this.renderTarget2,this.renderToScreen=!0,this.passes=[],this.copyPass=new _F(dF),this.copyPass.material.blending=0,this.timer=new Ba}swapBuffers(){const e=this.readBuffer;this.readBuffer=this.writeBuffer,this.writeBuffer=e}addPass(e){this.passes.push(e),e.setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}insertPass(e,t){this.passes.splice(t,0,e),e.setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}removePass(e){const t=this.passes.indexOf(e);-1!==t&&this.passes.splice(t,1)}isLastEnabledPass(e){for(let t=e+1;t1?i-1:0),s=1;s=0&&r<1?(o=s,l=a):r>=1&&r<2?(o=a,l=s):r>=2&&r<3?(l=s,u=a):r>=3&&r<4?(l=a,u=s):r>=4&&r<5?(o=a,u=s):r>=5&&r<6&&(o=s,u=a);var c=n-s/2;return i(o+c,l+c,u+c)}var DF={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"00ffff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"0000ff",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"00ffff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"ff00ff",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"789",lightslategrey:"789",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"0f0",limegreen:"32cd32",linen:"faf0e6",magenta:"f0f",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"639",red:"f00",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"fff",whitesmoke:"f5f5f5",yellow:"ff0",yellowgreen:"9acd32"};var IF=/^#[a-fA-F0-9]{6}$/,UF=/^#[a-fA-F0-9]{8}$/,FF=/^#[a-fA-F0-9]{3}$/,OF=/^#[a-fA-F0-9]{4}$/,BF=/^rgb\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*\)$/i,kF=/^rgb(?:a)?\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i,zF=/^hsl\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*\)$/i,VF=/^hsl(?:a)?\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i;function GF(e){if("string"!=typeof e)throw new CF(3);var t=function(e){if("string"!=typeof e)return e;var t=e.toLowerCase();return DF[t]?"#"+DF[t]:e}(e);if(t.match(IF))return{red:parseInt(""+t[1]+t[2],16),green:parseInt(""+t[3]+t[4],16),blue:parseInt(""+t[5]+t[6],16)};if(t.match(UF)){var n=parseFloat((parseInt(""+t[7]+t[8],16)/255).toFixed(2));return{red:parseInt(""+t[1]+t[2],16),green:parseInt(""+t[3]+t[4],16),blue:parseInt(""+t[5]+t[6],16),alpha:n}}if(t.match(FF))return{red:parseInt(""+t[1]+t[1],16),green:parseInt(""+t[2]+t[2],16),blue:parseInt(""+t[3]+t[3],16)};if(t.match(OF)){var i=parseFloat((parseInt(""+t[4]+t[4],16)/255).toFixed(2));return{red:parseInt(""+t[1]+t[1],16),green:parseInt(""+t[2]+t[2],16),blue:parseInt(""+t[3]+t[3],16),alpha:i}}var r=BF.exec(t);if(r)return{red:parseInt(""+r[1],10),green:parseInt(""+r[2],10),blue:parseInt(""+r[3],10)};var s=kF.exec(t.substring(0,50));if(s)return{red:parseInt(""+s[1],10),green:parseInt(""+s[2],10),blue:parseInt(""+s[3],10),alpha:parseFloat(""+s[4])>1?parseFloat(""+s[4])/100:parseFloat(""+s[4])};var a=zF.exec(t);if(a){var o="rgb("+LF(parseInt(""+a[1],10),parseInt(""+a[2],10)/100,parseInt(""+a[3],10)/100)+")",l=BF.exec(o);if(!l)throw new CF(4,t,o);return{red:parseInt(""+l[1],10),green:parseInt(""+l[2],10),blue:parseInt(""+l[3],10)}}var u=VF.exec(t.substring(0,50));if(u){var c="rgb("+LF(parseInt(""+u[1],10),parseInt(""+u[2],10)/100,parseInt(""+u[3],10)/100)+")",h=BF.exec(c);if(!h)throw new CF(4,t,c);return{red:parseInt(""+h[1],10),green:parseInt(""+h[2],10),blue:parseInt(""+h[3],10),alpha:parseFloat(""+u[4])>1?parseFloat(""+u[4])/100:parseFloat(""+u[4])}}throw new CF(5)}function HF(e){return function(e){var t,n=e.red/255,i=e.green/255,r=e.blue/255,s=Math.max(n,i,r),a=Math.min(n,i,r),o=(s+a)/2;if(s===a)return void 0!==e.alpha?{hue:0,saturation:0,lightness:o,alpha:e.alpha}:{hue:0,saturation:0,lightness:o};var l=s-a,u=o>.5?l/(2-s-a):l/(s+a);switch(s){case n:t=(i-r)/l+(i=1?YF(e.red,e.green,e.blue):"rgba("+e.red+","+e.green+","+e.blue+","+e.alpha+")";throw new CF(7)}function ZF(e){if("object"!=typeof e)throw new CF(8);if(function(e){return"number"==typeof e.red&&"number"==typeof e.green&&"number"==typeof e.blue&&"number"==typeof e.alpha}(e))return KF(e);if(function(e){return"number"==typeof e.red&&"number"==typeof e.green&&"number"==typeof e.blue&&("number"!=typeof e.alpha||void 0===e.alpha)}(e))return YF(e);if(function(e){return"number"==typeof e.hue&&"number"==typeof e.saturation&&"number"==typeof e.lightness&&"number"==typeof e.alpha}(e))return function(e,t,n,i){if("object"==typeof e&&void 0===t&&void 0===n&&void 0===i)return e.alpha>=1?qF(e.hue,e.saturation,e.lightness):"rgba("+LF(e.hue,e.saturation,e.lightness)+","+e.alpha+")";throw new CF(2)}(e);if(function(e){return"number"==typeof e.hue&&"number"==typeof e.saturation&&"number"==typeof e.lightness&&("number"!=typeof e.alpha||void 0===e.alpha)}(e))return function(e,t,n){if("object"==typeof e&&void 0===t&&void 0===n)return qF(e.hue,e.saturation,e.lightness);throw new CF(1)}(e);throw new CF(8)}function QF(e,t,n){return function(){var i=n.concat(Array.prototype.slice.call(arguments));return i.length>=t?e.apply(this,i):QF(e,t,i)}}function JF(e){return QF(e,e.length,[])}function eO(e,t,n){return Math.max(e,Math.min(t,n))}JF(function(e,t){if("transparent"===t)return t;var n=HF(t);return ZF(TF({},n,{hue:n.hue+parseFloat(e)}))}),JF(function(e,t){if("transparent"===t)return t;var n=HF(t);return ZF(TF({},n,{lightness:eO(0,1,n.lightness-parseFloat(e))}))}),JF(function(e,t){if("transparent"===t)return t;var n=HF(t);return ZF(TF({},n,{saturation:eO(0,1,n.saturation-parseFloat(e))}))}),JF(function(e,t){if("transparent"===t)return t;var n=HF(t);return ZF(TF({},n,{lightness:eO(0,1,n.lightness+parseFloat(e))}))});var tO=JF(function(e,t,n){if("transparent"===t)return n;if("transparent"===n)return t;if(0===e)return n;var i=GF(t),r=TF({},i,{alpha:"number"==typeof i.alpha?i.alpha:1}),s=GF(n),a=TF({},s,{alpha:"number"==typeof s.alpha?s.alpha:1}),o=r.alpha-a.alpha,l=2*parseFloat(e)-1,u=((l*o===-1?l:l+o)/(1+l*o)+1)/2,c=1-u;return KF({red:Math.floor(r.red*u+a.red*c),green:Math.floor(r.green*u+a.green*c),blue:Math.floor(r.blue*u+a.blue*c),alpha:r.alpha*parseFloat(e)+a.alpha*(1-parseFloat(e))})}),nO=tO;var iO=JF(function(e,t){if("transparent"===t)return t;var n=GF(t);return KF(TF({},n,{alpha:eO(0,1,(100*("number"==typeof n.alpha?n.alpha:1)+100*parseFloat(e))/100)}))}),rO=iO;JF(function(e,t){if("transparent"===t)return t;var n=HF(t);return ZF(TF({},n,{saturation:eO(0,1,n.saturation+parseFloat(e))}))}),JF(function(e,t){return"transparent"===t?t:ZF(TF({},HF(t),{hue:parseFloat(e)}))}),JF(function(e,t){return"transparent"===t?t:ZF(TF({},HF(t),{lightness:parseFloat(e)}))}),JF(function(e,t){return"transparent"===t?t:ZF(TF({},HF(t),{saturation:parseFloat(e)}))}),JF(function(e,t){return"transparent"===t?t:nO(parseFloat(e),"rgb(0, 0, 0)",t)}),JF(function(e,t){return"transparent"===t?t:nO(parseFloat(e),"rgb(255, 255, 255)",t)}),JF(function(e,t){if("transparent"===t)return t;var n=GF(t);return KF(TF({},n,{alpha:eO(0,1,+(100*("number"==typeof n.alpha?n.alpha:1)-100*parseFloat(e)).toFixed(2)/100)}))});var sO=Object.freeze({Linear:Object.freeze({None:function(e){return e},In:function(e){return e},Out:function(e){return e},InOut:function(e){return e}}),Quadratic:Object.freeze({In:function(e){return e*e},Out:function(e){return e*(2-e)},InOut:function(e){return(e*=2)<1?.5*e*e:-.5*(--e*(e-2)-1)}}),Cubic:Object.freeze({In:function(e){return e*e*e},Out:function(e){return--e*e*e+1},InOut:function(e){return(e*=2)<1?.5*e*e*e:.5*((e-=2)*e*e+2)}}),Quartic:Object.freeze({In:function(e){return e*e*e*e},Out:function(e){return 1- --e*e*e*e},InOut:function(e){return(e*=2)<1?.5*e*e*e*e:-.5*((e-=2)*e*e*e-2)}}),Quintic:Object.freeze({In:function(e){return e*e*e*e*e},Out:function(e){return--e*e*e*e*e+1},InOut:function(e){return(e*=2)<1?.5*e*e*e*e*e:.5*((e-=2)*e*e*e*e+2)}}),Sinusoidal:Object.freeze({In:function(e){return 1-Math.sin((1-e)*Math.PI/2)},Out:function(e){return Math.sin(e*Math.PI/2)},InOut:function(e){return.5*(1-Math.sin(Math.PI*(.5-e)))}}),Exponential:Object.freeze({In:function(e){return 0===e?0:Math.pow(1024,e-1)},Out:function(e){return 1===e?1:1-Math.pow(2,-10*e)},InOut:function(e){return 0===e?0:1===e?1:(e*=2)<1?.5*Math.pow(1024,e-1):.5*(2-Math.pow(2,-10*(e-1)))}}),Circular:Object.freeze({In:function(e){return 1-Math.sqrt(1-e*e)},Out:function(e){return Math.sqrt(1- --e*e)},InOut:function(e){return(e*=2)<1?-.5*(Math.sqrt(1-e*e)-1):.5*(Math.sqrt(1-(e-=2)*e)+1)}}),Elastic:Object.freeze({In:function(e){return 0===e?0:1===e?1:-Math.pow(2,10*(e-1))*Math.sin(5*(e-1.1)*Math.PI)},Out:function(e){return 0===e?0:1===e?1:Math.pow(2,-10*e)*Math.sin(5*(e-.1)*Math.PI)+1},InOut:function(e){return 0===e?0:1===e?1:(e*=2)<1?-.5*Math.pow(2,10*(e-1))*Math.sin(5*(e-1.1)*Math.PI):.5*Math.pow(2,-10*(e-1))*Math.sin(5*(e-1.1)*Math.PI)+1}}),Back:Object.freeze({In:function(e){var t=1.70158;return 1===e?1:e*e*((t+1)*e-t)},Out:function(e){var t=1.70158;return 0===e?0:--e*e*((t+1)*e+t)+1},InOut:function(e){var t=2.5949095;return(e*=2)<1?e*e*((t+1)*e-t)*.5:.5*((e-=2)*e*((t+1)*e+t)+2)}}),Bounce:Object.freeze({In:function(e){return 1-sO.Bounce.Out(1-e)},Out:function(e){return e<1/2.75?7.5625*e*e:e<2/2.75?7.5625*(e-=1.5/2.75)*e+.75:e<2.5/2.75?7.5625*(e-=2.25/2.75)*e+.9375:7.5625*(e-=2.625/2.75)*e+.984375},InOut:function(e){return e<.5?.5*sO.Bounce.In(2*e):.5*sO.Bounce.Out(2*e-1)+.5}}),generatePow:function(e){return void 0===e&&(e=4),e=(e=e1e4?1e4:e,{In:function(t){return Math.pow(t,e)},Out:function(t){return 1-Math.pow(1-t,e)},InOut:function(t){return t<.5?Math.pow(2*t,e)/2:(1-Math.pow(2-2*t,e))/2+.5}}}}),aO=function(){return performance.now()},oO=function(){function e(){for(var e=[],t=0;t0;){this._tweensAddedDuringUpdate={};for(var i=0;i1?s(e[n],e[n-1],n-i):s(e[r],e[r+1>n?n:r+1],i-r)},Utils:{Linear:function(e,t,n){return(t-e)*n+e}}},uO=function(){function e(){}return e.nextId=function(){return e._nextId++},e._nextId=0,e}(),cO=new oO,hO=function(){function e(e,t){this._isPaused=!1,this._pauseStart=0,this._valuesStart={},this._valuesEnd={},this._valuesStartRepeat={},this._duration=1e3,this._isDynamic=!1,this._initialRepeat=0,this._repeat=0,this._yoyo=!1,this._isPlaying=!1,this._reversed=!1,this._delayTime=0,this._startTime=0,this._easingFunction=sO.Linear.None,this._interpolationFunction=lO.Linear,this._chainedTweens=[],this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._id=uO.nextId(),this._isChainStopped=!1,this._propertiesAreSetUp=!1,this._goToEnd=!1,this._object=e,"object"==typeof t?(this._group=t,t.add(this)):!0===t&&(this._group=cO,cO.add(this))}return e.prototype.getId=function(){return this._id},e.prototype.isPlaying=function(){return this._isPlaying},e.prototype.isPaused=function(){return this._isPaused},e.prototype.getDuration=function(){return this._duration},e.prototype.to=function(e,t){if(void 0===t&&(t=1e3),this._isPlaying)throw new Error("Can not call Tween.to() while Tween is already started or paused. Stop the Tween first.");return this._valuesEnd=e,this._propertiesAreSetUp=!1,this._duration=t<0?0:t,this},e.prototype.duration=function(e){return void 0===e&&(e=1e3),this._duration=e<0?0:e,this},e.prototype.dynamic=function(e){return void 0===e&&(e=!1),this._isDynamic=e,this},e.prototype.start=function(e,t){if(void 0===e&&(e=aO()),void 0===t&&(t=!1),this._isPlaying)return this;if(this._repeat=this._initialRepeat,this._reversed)for(var n in this._reversed=!1,this._valuesStartRepeat)this._swapEndStartRepeatValues(n),this._valuesStart[n]=this._valuesStartRepeat[n];if(this._isPlaying=!0,this._isPaused=!1,this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._isChainStopped=!1,this._startTime=e,this._startTime+=this._delayTime,!this._propertiesAreSetUp||t){if(this._propertiesAreSetUp=!0,!this._isDynamic){var i={};for(var r in this._valuesEnd)i[r]=this._valuesEnd[r];this._valuesEnd=i}this._setupProperties(this._object,this._valuesStart,this._valuesEnd,this._valuesStartRepeat,t)}return this},e.prototype.startFromCurrentValues=function(e){return this.start(e,!0)},e.prototype._setupProperties=function(e,t,n,i,r){for(var s in n){var a=e[s],o=Array.isArray(a),l=o?"array":typeof a,u=!o&&Array.isArray(n[s]);if("undefined"!==l&&"function"!==l){if(u){if(0===(g=n[s]).length)continue;for(var c=[a],h=0,d=g.length;hl)return 1;var e=Math.trunc(a/o),t=a-e*o,n=Math.min(t/s._duration,1);return 0===n&&a===s._duration?1:n}(),c=this._easingFunction(u);if(this._updateProperties(this._object,this._valuesStart,this._valuesEnd,c),this._onUpdateCallback&&this._onUpdateCallback(this._object,u),0===this._duration||a>=this._duration){if(this._repeat>0){var h=Math.min(Math.trunc((a-this._duration)/o)+1,this._repeat);for(r in isFinite(this._repeat)&&(this._repeat-=h),this._valuesStartRepeat)this._yoyo||"string"!=typeof this._valuesEnd[r]||(this._valuesStartRepeat[r]=this._valuesStartRepeat[r]+parseFloat(this._valuesEnd[r])),this._yoyo&&this._swapEndStartRepeatValues(r),this._valuesStart[r]=this._valuesStartRepeat[r];return this._yoyo&&(this._reversed=!this._reversed),this._startTime+=o*h,this._onRepeatCallback&&this._onRepeatCallback(this._object),this._onEveryStartCallbackFired=!1,!0}this._onCompleteCallback&&this._onCompleteCallback(this._object);for(var d=0,p=this._chainedTweens.length;d=0&&"xmlns"!==(t=e.slice(0,n))&&(e=e.slice(n+1)),fO.hasOwnProperty(t)?{space:fO[t],local:e}:e}function gO(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===pO&&t.documentElement.namespaceURI===pO?t.createElement(e):t.createElementNS(n,e)}}function _O(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function vO(e){var t=mO(e);return(t.local?_O:gO)(t)}function yO(){}function bO(e){return null==e?yO:function(){return this.querySelector(e)}}function xO(){return[]}function TO(e){return function(){return function(e){return null==e?[]:Array.isArray(e)?e:Array.from(e)}(e.apply(this,arguments))}}function SO(e){return function(t){return t.matches(e)}}var MO=Array.prototype.find;function EO(){return this.firstElementChild}var wO=Array.prototype.filter;function AO(){return Array.from(this.children)}function RO(e){return new Array(e.length)}function CO(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}function NO(e,t,n,i,r,s){for(var a,o=0,l=t.length,u=s.length;ot?1:e>=t?0:NaN}function UO(e){return function(){this.removeAttribute(e)}}function FO(e){return function(){this.removeAttributeNS(e.space,e.local)}}function OO(e,t){return function(){this.setAttribute(e,t)}}function BO(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function kO(e,t){return function(){var n=t.apply(this,arguments);null==n?this.removeAttribute(e):this.setAttribute(e,n)}}function zO(e,t){return function(){var n=t.apply(this,arguments);null==n?this.removeAttributeNS(e.space,e.local):this.setAttributeNS(e.space,e.local,n)}}function VO(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function GO(e){return function(){this.style.removeProperty(e)}}function HO(e,t,n){return function(){this.style.setProperty(e,t,n)}}function jO(e,t,n){return function(){var i=t.apply(this,arguments);null==i?this.style.removeProperty(e):this.style.setProperty(e,i,n)}}function WO(e){return function(){delete this[e]}}function $O(e,t){return function(){this[e]=t}}function XO(e,t){return function(){var n=t.apply(this,arguments);null==n?delete this[e]:this[e]=n}}function qO(e){return e.trim().split(/^|\s+/)}function YO(e){return e.classList||new KO(e)}function KO(e){this._node=e,this._names=qO(e.getAttribute("class")||"")}function ZO(e,t){for(var n=YO(e),i=-1,r=t.length;++i=0&&(this._names.splice(t,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(e){return this._names.indexOf(e)>=0}};var yB=[null];function bB(e,t){this._groups=e,this._parents=t}bB.prototype={constructor:bB,select:function(e){"function"!=typeof e&&(e=bO(e));for(var t=this._groups,n=t.length,i=new Array(n),r=0;r=b&&(b=y+1);!(v=g[b])&&++b=0;)(i=r[s])&&(a&&4^i.compareDocumentPosition(a)&&a.parentNode.insertBefore(i,a),a=i);return this},sort:function(e){function t(t,n){return t&&n?e(t.__data__,n.__data__):!t-!n}e||(e=IO);for(var n=this._groups,i=n.length,r=new Array(i),s=0;s1?this.each((null==t?GO:"function"==typeof t?jO:HO)(e,t,null==n?"":n)):function(e,t){return e.style.getPropertyValue(t)||VO(e).getComputedStyle(e,null).getPropertyValue(t)}(this.node(),e)},property:function(e,t){return arguments.length>1?this.each((null==t?WO:"function"==typeof t?XO:$O)(e,t)):this.node()[e]},classed:function(e,t){var n=qO(e+"");if(arguments.length<2){for(var i=YO(this.node()),r=-1,s=n.length;++r=0&&(t=e.slice(n+1),e=e.slice(0,n)),{type:e,name:t}})}(e+""),a=s.length;if(!(arguments.length<2)){for(o=t?mB:fB,i=0;it&&EB.sort(RB),e=EB.shift(),t=EB.length,$B(e)}finally{EB.length=YB.__r=0}}function KB(e,t,n,i,r,s,a,o,l,u,c){var h,d,p,f,m,g,_,v=i&&i.__k||OB,y=t.length;for(l=ZB(n,t,v,l,y),h=0;h0?a=e.__k[s]=GB(a.type,a.props,a.key,a.ref?a.ref:null,a.__v):e.__k[s]=a,l=s+d,a.__=e,a.__b=e.__b+1,o=null,-1!=(u=a.__i=JB(a,n,l,h))&&(h--,(o=n[u])&&(o.__u|=2)),null==o||null==o.__v?(-1==u&&(r>c?d--:rl?d--:d++,a.__u|=4))):e.__k[s]=null;if(h)for(s=0;s(c?1:0))for(r=n-1,s=n+1;r>=0||s=0?r--:s++])&&!(2&u.__u)&&o==u.key&&l==u.type)return a;return-1}function ek(e,t,n){"-"==t[0]?e.setProperty(t,null==n?"":n):e[t]=null==n?"":"number"!=typeof n||BB.test(t)?n:n+"px"}function tk(e,t,n,i,r){var s,a;e:if("style"==t)if("string"==typeof n)e.style.cssText=n;else{if("string"==typeof i&&(e.style.cssText=i=""),i)for(t in i)n&&t in n||ek(e.style,t,"");if(n)for(t in n)i&&n[t]==i[t]||ek(e.style,t,n[t])}else if("o"==t[0]&&"n"==t[1])s=t!=(t=t.replace(LB,"$1")),a=t.toLowerCase(),t=a in e||"onFocusOut"==t||"onFocusIn"==t?a.slice(2):t.slice(2),e.l||(e.l={}),e.l[t+s]=n,n?i?n[PB]=i[PB]:(n[PB]=DB,e.addEventListener(t,s?UB:IB,s)):e.removeEventListener(t,s?UB:IB,s);else{if("http://www.w3.org/2000/svg"==r)t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if("width"!=t&&"height"!=t&&"href"!=t&&"list"!=t&&"form"!=t&&"tabIndex"!=t&&"download"!=t&&"rowSpan"!=t&&"colSpan"!=t&&"role"!=t&&"popover"!=t&&t in e)try{e[t]=null==n?"":n;break e}catch(e){}"function"==typeof n||(null==n||!1===n&&"-"!=t[4]?e.removeAttribute(t):e.setAttribute(t,"popover"==t&&1==n?"":n))}}function nk(e){return function(t){if(this.l){var n=this.l[t.type+e];if(null==t[NB])t[NB]=DB++;else if(t[NB]0?e:kB(e)?e.map(ak):zB({},e)}function ok(e,t,n,i,r,s,a,o,l){var u,c,h,d,p,f,m,g=n.props||FB,_=t.props,v=t.type;if("svg"==v?r="http://www.w3.org/2000/svg":"math"==v?r="http://www.w3.org/1998/Math/MathML":r||(r="http://www.w3.org/1999/xhtml"),null!=s)for(u=0;u2&&(a.children=arguments.length>3?xB.call(arguments,2):n),"function"==typeof e&&null!=e.defaultProps)for(s in e.defaultProps)void 0===a[s]&&(a[s]=e.defaultProps[s]);return GB(e,a,i,r,null)}(HB,null,[e]),i||FB,FB,t.namespaceURI,i?null:t.firstChild?xB.call(t.childNodes):null,r,i?i.__e:t.firstChild,false,s),sk(r,e,s)}function dk(e,t,n){var i,r,s,a,o=zB({},e.props);for(s in e.type&&e.type.defaultProps&&(a=e.type.defaultProps),t)"key"==s?i=t[s]:"ref"==s?r=t[s]:o[s]=void 0===t[s]&&null!=a?a[s]:t[s];return arguments.length>2&&(o.children=arguments.length>3?xB.call(arguments,2):n),GB(e.type,o,i||e.key,r||e.ref,null)}function pk(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n2&&void 0!==arguments[2]?arguments[2]:{}).style,i=void 0===n?{}:n,r=function(e){return"string"==typeof e?new bB([[document.querySelector(e)]],[document.documentElement]):new bB([[e]],yB)}(!!e&&"object"===_k(e)&&!!e.node&&"function"==typeof e.node?e.node():e);"static"===r.style("position")&&r.style("position","relative"),t.tooltipEl=r.append("div").attr("class","float-tooltip-kap"),Object.entries(i).forEach(function(e){var n=gk(e,2),i=n[0],r=n[1];return t.tooltipEl.style(i,r)}),t.tooltipEl.style("left","-10000px").style("display","none");var s="tooltip-".concat(Math.round(1e12*Math.random()));t.mouseInside=!1,r.on("mousemove.".concat(s),function(e){t.mouseInside=!0;var n=function(e,t){if(e=function(e){let t;for(;t=e.sourceEvent;)e=t;return e}(e),void 0===t&&(t=e.currentTarget),t){var n=t.ownerSVGElement||t;if(n.createSVGPoint){var i=n.createSVGPoint();return i.x=e.clientX,i.y=e.clientY,[(i=i.matrixTransform(t.getScreenCTM().inverse())).x,i.y]}if(t.getBoundingClientRect){var r=t.getBoundingClientRect();return[e.clientX-r.left-t.clientLeft,e.clientY-r.top-t.clientTop]}}return[e.pageX,e.pageY]}(e),i=r.node(),s=i.offsetWidth,a=i.offsetHeight,o=[null===t.offsetX||void 0===t.offsetX?"-".concat(n[0]/s*100,"%"):"number"==typeof t.offsetX?"calc(-50% + ".concat(t.offsetX,"px)"):t.offsetX,null===t.offsetY||void 0===t.offsetY?a>130&&a-n[1]<100?"calc(-100% - 6px)":"21px":"number"==typeof t.offsetY?t.offsetY<0?"calc(-100% - ".concat(Math.abs(t.offsetY),"px)"):"".concat(t.offsetY,"px"):t.offsetY];t.tooltipEl.style("left",n[0]+"px").style("top",n[1]+"px").style("transform","translate(".concat(o.join(","),")")),t.content&&t.tooltipEl.style("display","inline")}),r.on("mouseover.".concat(s),function(){t.mouseInside=!0,t.content&&t.tooltipEl.style("display","inline")}),r.on("mouseout.".concat(s),function(){t.mouseInside=!1,t.tooltipEl.style("display","none")})},update:function(e){var t,n;e.tooltipEl.style("display",e.content&&e.mouseInside?"inline":"none"),e.content?e.content instanceof HTMLElement?(e.tooltipEl.text(""),e.tooltipEl.append(function(){return e.content})):"string"==typeof e.content?e.tooltipEl.html(e.content):!function(e){return MB(dk(e))}(e.content)?(e.tooltipEl.style("display","none"),console.warn("Tooltip content is invalid, skipping.",e.content,e.content.toString())):(e.tooltipEl.text(""),t=e.content,delete(n=e.tooltipEl.node()).__k,hk(vk(t),n)):e.tooltipEl.text("")}});function bk(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n0),d=!!n.morphAttributes.position,p=!!n.morphAttributes.normal,f=!!n.morphAttributes.color;let m=0;i.toneMapped&&(null!==C&&!0!==C.isXRRenderTarget||(m=E.toneMapping));const g=n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color,_=void 0!==g?g.length:0,v=re.get(i),y=x.state.lights;if(!0===$&&(!0===X||e!==P)){const t=e===P&&i.id===N;be.setState(i,e,t)}let b=!1;i.version===v.__version?v.needsLights&&v.lightsStateVersion!==y.state.version||v.outputColorSpace!==o||r.isBatchedMesh&&!1===v.batching?b=!0:r.isBatchedMesh||!0!==v.batching?r.isBatchedMesh&&!0===v.batchingColor&&null===r.colorTexture||r.isBatchedMesh&&!1===v.batchingColor&&null!==r.colorTexture||r.isInstancedMesh&&!1===v.instancing?b=!0:r.isInstancedMesh||!0!==v.instancing?r.isSkinnedMesh&&!1===v.skinning?b=!0:r.isSkinnedMesh||!0!==v.skinning?r.isInstancedMesh&&!0===v.instancingColor&&null===r.instanceColor||r.isInstancedMesh&&!1===v.instancingColor&&null!==r.instanceColor||r.isInstancedMesh&&!0===v.instancingMorph&&null===r.morphTexture||r.isInstancedMesh&&!1===v.instancingMorph&&null!==r.morphTexture||v.envMap!==u||!0===i.fog&&v.fog!==s?b=!0:void 0===v.numClippingPlanes||v.numClippingPlanes===be.numPlanes&&v.numIntersection===be.numIntersection?(v.vertexAlphas!==c||v.vertexTangents!==h||v.morphTargets!==d||v.morphNormals!==p||v.morphColors!==f||v.toneMapping!==m||v.morphTargetsCount!==_)&&(b=!0):b=!0:b=!0:b=!0:b=!0:(b=!0,v.__version=i.version);let T=v.currentProgram;!0===b&&(T=tt(i,t,r));let S=!1,M=!1,w=!1;const A=T.getUniforms(),R=v.uniforms;ne.useProgram(T.program)&&(S=!0,M=!0,w=!0);i.id!==N&&(N=i.id,M=!0);if(S||P!==e){ne.buffers.depth.getReversed()&&!0!==e.reversedDepth&&(e._reversedDepth=!0,e.updateProjectionMatrix()),A.setValue(Oe,"projectionMatrix",e.projectionMatrix),A.setValue(Oe,"viewMatrix",e.matrixWorldInverse);const t=A.map.cameraPosition;void 0!==t&&t.setValue(Oe,Y.setFromMatrixPosition(e.matrixWorld)),te.logarithmicDepthBuffer&&A.setValue(Oe,"logDepthBufFC",2/(Math.log(e.far+1)/Math.LN2)),(i.isMeshPhongMaterial||i.isMeshToonMaterial||i.isMeshLambertMaterial||i.isMeshBasicMaterial||i.isMeshStandardMaterial||i.isShaderMaterial)&&A.setValue(Oe,"isOrthographic",!0===e.isOrthographicCamera),P!==e&&(P=e,M=!0,w=!0)}v.needsLights&&(y.state.directionalShadowMap.length>0&&A.setValue(Oe,"directionalShadowMap",y.state.directionalShadowMap,se),y.state.spotShadowMap.length>0&&A.setValue(Oe,"spotShadowMap",y.state.spotShadowMap,se),y.state.pointShadowMap.length>0&&A.setValue(Oe,"pointShadowMap",y.state.pointShadowMap,se));if(r.isSkinnedMesh){A.setOptional(Oe,r,"bindMatrix"),A.setOptional(Oe,r,"bindMatrixInverse");const e=r.skeleton;e&&(null===e.boneTexture&&e.computeBoneTexture(),A.setValue(Oe,"boneTexture",e.boneTexture,se))}r.isBatchedMesh&&(A.setOptional(Oe,r,"batchingTexture"),A.setValue(Oe,"batchingTexture",r._matricesTexture,se),A.setOptional(Oe,r,"batchingIdTexture"),A.setValue(Oe,"batchingIdTexture",r._indirectTexture,se),A.setOptional(Oe,r,"batchingColorTexture"),null!==r._colorsTexture&&A.setValue(Oe,"batchingColorTexture",r._colorsTexture,se));const L=n.morphAttributes;void 0===L.position&&void 0===L.normal&&void 0===L.color||Ae.update(r,n,T);(M||v.receiveShadow!==r.receiveShadow)&&(v.receiveShadow=r.receiveShadow,A.setValue(Oe,"receiveShadow",r.receiveShadow));(i.isMeshStandardMaterial||i.isMeshLambertMaterial||i.isMeshPhongMaterial)&&null===i.envMap&&null!==t.environment&&(R.envMapIntensity.value=t.environmentIntensity);void 0!==R.dfgLUT&&(R.dfgLUT.value=(null===Vu&&(Vu=new Xr(zu,16,16,Ie,xe),Vu.name="DFG_LUT",Vu.minFilter=he,Vu.magFilter=he,Vu.wrapS=ae,Vu.wrapT=ae,Vu.generateMipmaps=!1,Vu.needsUpdate=!0),Vu));M&&(A.setValue(Oe,"toneMappingExposure",E.toneMappingExposure),v.needsLights&&(I=w,(D=R).ambientLightColor.needsUpdate=I,D.lightProbe.needsUpdate=I,D.directionalLights.needsUpdate=I,D.directionalLightShadows.needsUpdate=I,D.pointLights.needsUpdate=I,D.pointLightShadows.needsUpdate=I,D.spotLights.needsUpdate=I,D.spotLightShadows.needsUpdate=I,D.rectAreaLights.needsUpdate=I,D.hemisphereLights.needsUpdate=I),s&&!0===i.fog&&me.refreshFogUniforms(R,s),me.refreshMaterialUniforms(R,i,k,B,x.state.transmissionRenderTarget[e.id]),Bl.upload(Oe,nt(v),R,se));var D,I;i.isShaderMaterial&&!0===i.uniformsNeedUpdate&&(Bl.upload(Oe,nt(v),R,se),i.uniformsNeedUpdate=!1);i.isSpriteMaterial&&A.setValue(Oe,"center",r.center);if(A.setValue(Oe,"modelViewMatrix",r.modelViewMatrix),A.setValue(Oe,"normalMatrix",r.normalMatrix),A.setValue(Oe,"modelMatrix",r.matrixWorld),i.isShaderMaterial||i.isRawShaderMaterial){const e=i.uniformsGroups;for(let t=0,n=e.length;t{function n(){i.forEach(function(e){re.get(e).currentProgram.isReady()&&i.delete(e)}),0!==i.size?setTimeout(n,10):t(e)}null!==ee.get("KHR_parallel_shader_compile")?n():setTimeout(n,10)})};let $e=null;function Xe(){Ye.stop()}function qe(){Ye.start()}const Ye=new Ya;function Ke(e,t,n,i){if(!1===e.visible)return;if(e.layers.test(t.layers))if(e.isGroup)n=e.renderOrder;else if(e.isLOD)!0===e.autoUpdate&&e.update(t);else if(e.isLight)x.pushLight(e),e.castShadow&&x.pushShadow(e);else if(e.isSprite){if(!e.frustumCulled||W.intersectsSprite(e)){i&&K.setFromMatrixPosition(e.matrixWorld).applyMatrix4(q);const t=ce.update(e),r=e.material;r.visible&&b.push(e,t,r,n,K.z,null)}}else if((e.isMesh||e.isLine||e.isPoints)&&(!e.frustumCulled||W.intersectsObject(e))){const t=ce.update(e),r=e.material;if(i&&(void 0!==e.boundingSphere?(null===e.boundingSphere&&e.computeBoundingSphere(),K.copy(e.boundingSphere.center)):(null===t.boundingSphere&&t.computeBoundingSphere(),K.copy(t.boundingSphere.center)),K.applyMatrix4(e.matrixWorld).applyMatrix4(q)),Array.isArray(r)){const i=t.groups;for(let s=0,a=i.length;s0&&Je(r,t,n),s.length>0&&Je(s,t,n),a.length>0&&Je(a,t,n),ne.buffers.depth.setTest(!0),ne.buffers.depth.setMask(!0),ne.buffers.color.setMask(!0),ne.setPolygonOffset(!1)}function Qe(e,t,n,i){if(null!==(!0===n.isScene?n.overrideMaterial:null))return;if(void 0===x.state.transmissionRenderTarget[i.id]){const e=ee.has("EXT_color_buffer_half_float")||ee.has("EXT_color_buffer_float");x.state.transmissionRenderTarget[i.id]=new Dn(1,1,{generateMipmaps:!0,type:e?xe:fe,minFilter:pe,samples:Math.max(4,te.samples),stencilBuffer:r,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:bn.workingColorSpace})}const s=x.state.transmissionRenderTarget[i.id],a=i.viewport||L;s.setSize(a.z*E.transmissionResolutionScale,a.w*E.transmissionResolutionScale);const o=E.getRenderTarget(),l=E.getActiveCubeFace(),u=E.getActiveMipmapLevel();E.setRenderTarget(s),E.getClearColor(U),F=E.getClearAlpha(),F<1&&E.setClearColor(16777215,.5),E.clear(),Q&&we.render(n);const c=E.toneMapping;E.toneMapping=0;const h=i.viewport;if(void 0!==i.viewport&&(i.viewport=void 0),x.setupLightsView(i),!0===$&&be.setGlobalState(E.clippingPlanes,i),Je(e,n,i),se.updateMultisampleRenderTarget(s),se.updateRenderTargetMipmap(s),!1===ee.has("WEBGL_multisampled_render_to_texture")){let e=!1;for(let r=0,s=t.length;r0)for(let t=0,s=r.length;t0&&Qe(n,i,e,t),Q&&we.render(e),Ze(b,e,t)}null!==C&&0===R&&(se.updateMultisampleRenderTarget(C),se.updateRenderTargetMipmap(C)),i&&M.end(E),!0===e.isScene&&e.onAfterRender(E,e,t),Pe.resetDefaultState(),N=-1,P=null,S.pop(),S.length>0?(x=S[S.length-1],!0===$&&be.setGlobalState(E.clippingPlanes,x.state.camera)):x=null,T.pop(),b=T.length>0?T[T.length-1]:null},this.getActiveCubeFace=function(){return A},this.getActiveMipmapLevel=function(){return R},this.getRenderTarget=function(){return C},this.setRenderTargetTextures=function(e,t,n){const i=re.get(e);i.__autoAllocateDepthBuffer=!1===e.resolveDepthBuffer,!1===i.__autoAllocateDepthBuffer&&(i.__useRenderToTexture=!1),re.get(e.texture).__webglTexture=t,re.get(e.depthTexture).__webglTexture=i.__autoAllocateDepthBuffer?void 0:n,i.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(e,t){const n=re.get(e);n.__webglFramebuffer=t,n.__useDefaultFramebuffer=void 0===t};const rt=Oe.createFramebuffer();this.setRenderTarget=function(e,t=0,n=0){C=e,A=t,R=n;let i=null,r=!1,s=!1;if(e){const a=re.get(e);if(void 0!==a.__useDefaultFramebuffer)return ne.bindFramebuffer(Oe.FRAMEBUFFER,a.__webglFramebuffer),L.copy(e.viewport),D.copy(e.scissor),I=e.scissorTest,ne.viewport(L),ne.scissor(D),ne.setScissorTest(I),void(N=-1);if(void 0===a.__webglFramebuffer)se.setupRenderTarget(e);else if(a.__hasExternalTextures)se.rebindTextures(e,re.get(e.texture).__webglTexture,re.get(e.depthTexture).__webglTexture);else if(e.depthBuffer){const t=e.depthTexture;if(a.__boundDepthTexture!==t){if(null!==t&&re.has(t)&&(e.width!==t.image.width||e.height!==t.image.height))throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");se.setupDepthRenderbuffer(e)}}const o=e.texture;(o.isData3DTexture||o.isDataArrayTexture||o.isCompressedArrayTexture)&&(s=!0);const l=re.get(e).__webglFramebuffer;e.isWebGLCubeRenderTarget?(i=Array.isArray(l[t])?l[t][n]:l[t],r=!0):i=e.samples>0&&!1===se.useMultisampledRTT(e)?re.get(e).__webglMultisampledFramebuffer:Array.isArray(l)?l[n]:l,L.copy(e.viewport),D.copy(e.scissor),I=e.scissorTest}else L.copy(G).multiplyScalar(k).floor(),D.copy(H).multiplyScalar(k).floor(),I=j;0!==n&&(i=rt);if(ne.bindFramebuffer(Oe.FRAMEBUFFER,i)&&ne.drawBuffers(e,i),ne.viewport(L),ne.scissor(D),ne.setScissorTest(I),r){const i=re.get(e.texture);Oe.framebufferTexture2D(Oe.FRAMEBUFFER,Oe.COLOR_ATTACHMENT0,Oe.TEXTURE_CUBE_MAP_POSITIVE_X+t,i.__webglTexture,n)}else if(s){const i=t;for(let t=0;t1&&Oe.readBuffer(Oe.COLOR_ATTACHMENT0+o),!te.textureFormatReadable(l))return void qt("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");if(!te.textureTypeReadable(u))return void qt("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");t>=0&&t<=e.width-i&&n>=0&&n<=e.height-r&&Oe.readPixels(t,n,i,r,Ne.convert(l),Ne.convert(u),s)}finally{const e=null!==C?re.get(C).__webglFramebuffer:null;ne.bindFramebuffer(Oe.FRAMEBUFFER,e)}}},this.readRenderTargetPixelsAsync=async function(e,t,n,i,r,s,a,o=0){if(!e||!e.isWebGLRenderTarget)throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let l=re.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&void 0!==a&&(l=l[a]),l){if(t>=0&&t<=e.width-i&&n>=0&&n<=e.height-r){ne.bindFramebuffer(Oe.FRAMEBUFFER,l);const a=e.textures[o],u=a.format,c=a.type;if(e.textures.length>1&&Oe.readBuffer(Oe.COLOR_ATTACHMENT0+o),!te.textureFormatReadable(u))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!te.textureTypeReadable(c))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const h=Oe.createBuffer();Oe.bindBuffer(Oe.PIXEL_PACK_BUFFER,h),Oe.bufferData(Oe.PIXEL_PACK_BUFFER,s.byteLength,Oe.STREAM_READ),Oe.readPixels(t,n,i,r,Ne.convert(u),Ne.convert(c),0);const d=null!==C?re.get(C).__webglFramebuffer:null;ne.bindFramebuffer(Oe.FRAMEBUFFER,d);const p=Oe.fenceSync(Oe.SYNC_GPU_COMMANDS_COMPLETE,0);return Oe.flush(),await function(e,t,n){return new Promise(function(i,r){setTimeout(function s(){switch(e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0)){case e.WAIT_FAILED:r();break;case e.TIMEOUT_EXPIRED:setTimeout(s,n);break;default:i()}},n)})}(Oe,p,4),Oe.bindBuffer(Oe.PIXEL_PACK_BUFFER,h),Oe.getBufferSubData(Oe.PIXEL_PACK_BUFFER,0,s),Oe.deleteBuffer(h),Oe.deleteSync(p),s}throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")}},this.copyFramebufferToTexture=function(e,t=null,n=0){const i=Math.pow(2,-n),r=Math.floor(e.image.width*i),s=Math.floor(e.image.height*i),a=null!==t?t.x:0,o=null!==t?t.y:0;se.setTexture2D(e,0),Oe.copyTexSubImage2D(Oe.TEXTURE_2D,n,0,0,a,o,r,s),ne.unbindTexture()};const st=Oe.createFramebuffer(),at=Oe.createFramebuffer();this.copyTextureToTexture=function(e,t,n=null,i=null,r=0,s=0){let a,o,l,u,c,h,d,p,f;const m=e.isCompressedTexture?e.mipmaps[s]:e.image;if(null!==n)a=n.max.x-n.min.x,o=n.max.y-n.min.y,l=n.isBox3?n.max.z-n.min.z:1,u=n.min.x,c=n.min.y,h=n.isBox3?n.min.z:0;else{const t=Math.pow(2,-r);a=Math.floor(m.width*t),o=Math.floor(m.height*t),l=e.isDataArrayTexture?m.depth:e.isData3DTexture?Math.floor(m.depth*t):1,u=0,c=0,h=0}null!==i?(d=i.x,p=i.y,f=i.z):(d=0,p=0,f=0);const g=Ne.convert(t.format),_=Ne.convert(t.type);let v;t.isData3DTexture?(se.setTexture3D(t,0),v=Oe.TEXTURE_3D):t.isDataArrayTexture||t.isCompressedArrayTexture?(se.setTexture2DArray(t,0),v=Oe.TEXTURE_2D_ARRAY):(se.setTexture2D(t,0),v=Oe.TEXTURE_2D),Oe.pixelStorei(Oe.UNPACK_FLIP_Y_WEBGL,t.flipY),Oe.pixelStorei(Oe.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),Oe.pixelStorei(Oe.UNPACK_ALIGNMENT,t.unpackAlignment);const y=Oe.getParameter(Oe.UNPACK_ROW_LENGTH),b=Oe.getParameter(Oe.UNPACK_IMAGE_HEIGHT),x=Oe.getParameter(Oe.UNPACK_SKIP_PIXELS),T=Oe.getParameter(Oe.UNPACK_SKIP_ROWS),S=Oe.getParameter(Oe.UNPACK_SKIP_IMAGES);Oe.pixelStorei(Oe.UNPACK_ROW_LENGTH,m.width),Oe.pixelStorei(Oe.UNPACK_IMAGE_HEIGHT,m.height),Oe.pixelStorei(Oe.UNPACK_SKIP_PIXELS,u),Oe.pixelStorei(Oe.UNPACK_SKIP_ROWS,c),Oe.pixelStorei(Oe.UNPACK_SKIP_IMAGES,h);const M=e.isDataArrayTexture||e.isData3DTexture,E=t.isDataArrayTexture||t.isData3DTexture;if(e.isDepthTexture){const n=re.get(e),i=re.get(t),m=re.get(n.__renderTarget),g=re.get(i.__renderTarget);ne.bindFramebuffer(Oe.READ_FRAMEBUFFER,m.__webglFramebuffer),ne.bindFramebuffer(Oe.DRAW_FRAMEBUFFER,g.__webglFramebuffer);for(let n=0;n=e.pointerRaycasterThrottleMs){e.lastRaycasterCheck=t;var n=null;if(e.hoverDuringDrag||!e.isPointerDragging){var i=this.intersectingObjects(e.pointerPos.x,e.pointerPos.y);e.hoverOrderComparator&&i.sort(function(t,n){return e.hoverOrderComparator(t.object,n.object)});var r=i.find(function(t){return e.hoverFilter(t.object)})||null;n=r?r.object:null,e.intersection=r||null}n!==e.hoverObj&&(e.onHover(n,e.hoverObj,e.intersection),e.tooltip.content(n&&Ld(e.tooltipContent)(n,e.intersection)||null),e.hoverObj=n)}e.tweenGroup.update()}return this},getPointerPos:function(e){var t=e.pointerPos;return{x:t.x,y:t.y}},cameraPosition:function(e,t,n,i){var r=e.camera;if(t&&e.initialised){var s=t,a=n||{x:0,y:0,z:0};if(i){var o=Object.assign({},r.position),l=h();e.tweenGroup.add(new hO(o).to(s,i).easing(sO.Quadratic.Out).onUpdate(u).onComplete(function(){e.tweenGroup.remove(this)}).start()),e.tweenGroup.add(new hO(l).to(a,i/3).easing(sO.Quadratic.Out).onUpdate(c).onComplete(function(){e.tweenGroup.remove(this)}).start())}else u(s),c(a);return this}return Object.assign({},r.position,{lookAt:h()});function u(e){var t=e.x,n=e.y,i=e.z;void 0!==t&&(r.position.x=t),void 0!==n&&(r.position.y=n),void 0!==i&&(r.position.z=i)}function c(t){var n=new Ak.Vector3(t.x,t.y,t.z);e.controls.enabled&&e.controls.target?e.controls.target=n:r.lookAt(n)}function h(){return Object.assign(new Ak.Vector3(0,0,-1e3).applyQuaternion(r.quaternion).add(r.position))}},zoomToFit:function(e){for(var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:10,i=arguments.length,r=new Array(i>3?i-3:0),s=3;s2&&void 0!==arguments[2]?arguments[2]:0,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:10,r=e.camera;if(t){var s=new Ak.Vector3(0,0,0),a=2*Math.max.apply(Math,Sk(Object.entries(t).map(function(e){var t=Tk(e,2),n=t[0],i=t[1];return Math.max.apply(Math,Sk(i.map(function(e){return Math.abs(s[n]-e)})))}))),o=(1-2*i/e.height)*r.fov,l=a/Math.atan(o*Math.PI/180),u=l/r.aspect,c=Math.max(l,u);if(c>0){var h=s.clone().sub(r.position).normalize().multiplyScalar(-c);this.cameraPosition(h,s,n)}}return this},getBbox:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(){return!0},n=new Ak.Box3(new Ak.Vector3(0,0,0),new Ak.Vector3(0,0,0)),i=e.objects.filter(t);return i.length?(i.forEach(function(e){return n.expandByObject(e)}),Object.assign.apply(Object,Sk(["x","y","z"].map(function(e){return xk({},e,[n.min[e],n.max[e]])})))):null},getScreenCoords:function(e,t,n,i){var r=new Ak.Vector3(t,n,i);return r.project(this.camera()),{x:(r.x+1)*e.width/2,y:-(r.y-1)*e.height/2}},getSceneCoords:function(e,t,n){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,r=new Ak.Vector2(t/e.width*2-1,-n/e.height*2+1),s=new Ak.Raycaster;return s.setFromCamera(r,e.camera),Object.assign({},s.ray.at(i,new Ak.Vector3))},intersectingObjects:function(e,t,n){var i=new Ak.Vector2(t/e.width*2-1,-n/e.height*2+1),r=new Ak.Raycaster;return r.params.Line.threshold=e.lineHoverPrecision,r.params.Points.threshold=e.pointsHoverPrecision,r.setFromCamera(i,e.camera),r.intersectObjects(e.objects,!0)},renderer:function(e){return e.renderer},scene:function(e){return e.scene},camera:function(e){return e.camera},postProcessingComposer:function(e){return e.postProcessingComposer},controls:function(e){return e.controls},tbControls:function(e){return e.controls},_destructor:function(e){var t,n,i;!function(e){for(;e.children.length;){var t=e.children[0];e.remove(t),wk(t)}}(e.scene),null===(t=e.controls)||void 0===t||t.dispose(),null===(n=e.renderer)||void 0===n||n.dispose(),null===(i=e.postProcessingComposer)||void 0===i||i.dispose()}},stateInit:function(){return{scene:new Ak.Scene,camera:new Ak.PerspectiveCamera,timer:new Ak.Timer,tweenGroup:new oO,lastRaycasterCheck:0}},init:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=n.controlType,r=void 0===i?"trackball":i,s=n.useWebGPU,a=void 0!==s&&s,o=n.rendererConfig,l=void 0===o?{}:o,u=n.extraRenderers,c=void 0===u?[]:u,h=n.waitForLoadComplete,d=void 0===h||h;e.innerHTML="",e.appendChild(t.container=document.createElement("div")),t.container.className="scene-container",t.container.style.position="relative",t.container.appendChild(t.navInfo=document.createElement("div")),t.navInfo.className="scene-nav-info",t.navInfo.textContent={orbit:"Left-click: rotate, Mouse-wheel/middle-click: zoom, Right-click: pan",trackball:"Left-click: rotate, Mouse-wheel/middle-click: zoom, Right-click: pan",fly:"WASD: move, R|F: up | down, Q|E: roll, up|down: pitch, left|right: yaw"}[r]||"",t.navInfo.style.display=t.showNavInfo?null:"none",t.tooltip=new yk(t.container),t.pointerPos=new Ak.Vector2,t.pointerPos.x=-2,t.pointerPos.y=-2,["pointermove","pointerdown"].forEach(function(e){return t.container.addEventListener(e,function(n){if("pointerdown"===e&&(t.isPointerPressed=!0),!t.isPointerDragging&&"pointermove"===n.type&&(n.pressure>0||t.isPointerPressed)&&("mouse"===n.pointerType||void 0===n.movementX||[n.movementX,n.movementY].some(function(e){return Math.abs(e)>1}))&&(t.isPointerDragging=!0),t.enablePointerInteraction){var i=(r=t.container,s=r.getBoundingClientRect(),a=window.pageXOffset||document.documentElement.scrollLeft,o=window.pageYOffset||document.documentElement.scrollTop,{top:s.top+o,left:s.left+a});t.pointerPos.x=n.pageX-i.left,t.pointerPos.y=n.pageY-i.top}var r,s,a,o},{passive:!0})}),t.container.addEventListener("pointerup",function(e){t.isPointerPressed&&(t.isPointerPressed=!1,t.isPointerDragging&&(t.isPointerDragging=!1,!t.clickAfterDrag)||requestAnimationFrame(function(){0===e.button&&t.onClick(t.hoverObj||null,e,t.intersection),2===e.button&&t.onRightClick&&t.onRightClick(t.hoverObj||null,e,t.intersection)}))},{passive:!0,capture:!0}),t.container.addEventListener("contextmenu",function(e){t.onRightClick&&e.preventDefault()}),t.renderer=new(a?HI:Ak.WebGLRenderer)(Object.assign({antialias:!0,alpha:!0},l)),t.renderer.setPixelRatio(Math.min(2,window.devicePixelRatio)),t.container.appendChild(t.renderer.domElement),t.extraRenderers=c,t.extraRenderers.forEach(function(e){e.domElement.style.position="absolute",e.domElement.style.top="0px",e.domElement.style.pointerEvents="none",t.container.appendChild(e.domElement)}),t.postProcessingComposer=new bF(t.renderer),t.postProcessingComposer.addPass(new xF(t.scene,t.camera)),t.controls=new{trackball:cU,orbit:GU,fly:rF}[r](t.camera,t.renderer.domElement),"fly"===r&&(t.controls.movementSpeed=300,t.controls.rollSpeed=Math.PI/6,t.controls.dragToLook=!0),"trackball"!==r&&"orbit"!==r||(t.controls.minDistance=.1,t.controls.maxDistance=t.skyRadius,t.controls.addEventListener("start",function(){t.controlsEngaged=!0}),t.controls.addEventListener("change",function(){t.controlsEngaged&&(t.controlsDragging=!0)}),t.controls.addEventListener("end",function(){t.controlsEngaged=!1,t.controlsDragging=!1})),[t.renderer,t.postProcessingComposer].concat(Sk(t.extraRenderers)).forEach(function(e){return e.setSize(t.width,t.height)}),t.camera.aspect=t.width/t.height,t.camera.updateProjectionMatrix(),t.camera.position.z=1e3,t.scene.add(t.skysphere=new Ak.Mesh),t.skysphere.visible=!1,t.loadComplete=t.scene.visible=!d,window.scene=t.scene},update:function(e,t){if(e.width&&e.height&&(t.hasOwnProperty("width")||t.hasOwnProperty("height"))){var n,i=e.width,r=e.height;e.container.style.width="".concat(i,"px"),e.container.style.height="".concat(r,"px"),[e.renderer,e.postProcessingComposer].concat(Sk(e.extraRenderers)).forEach(function(e){return e.setSize(i,r)}),e.camera.aspect=i/r;var s=e.viewOffset.slice(0,2);s.some(function(e){return e})&&(n=e.camera).setViewOffset.apply(n,[i,r].concat(Sk(s),[i,r])),e.camera.updateProjectionMatrix()}if(t.hasOwnProperty("viewOffset")){var a,o=e.width,l=e.height,u=e.viewOffset.slice(0,2);u.some(function(e){return e})?(a=e.camera).setViewOffset.apply(a,[o,l].concat(Sk(u),[o,l])):e.camera.clearViewOffset()}if(t.hasOwnProperty("skyRadius")&&e.skyRadius&&(e.controls.hasOwnProperty("maxDistance")&&t.skyRadius&&(e.controls.maxDistance=Math.min(e.controls.maxDistance,e.skyRadius)),e.camera.far=2.5*e.skyRadius,e.camera.updateProjectionMatrix(),e.skysphere.geometry=new Ak.SphereGeometry(e.skyRadius)),t.hasOwnProperty("backgroundColor")){var c=GF(e.backgroundColor).alpha;void 0===c&&(c=1),e.renderer.setClearColor(new Ak.Color(rO(1,e.backgroundColor)),c)}function h(){e.loadComplete=e.scene.visible=!0}t.hasOwnProperty("backgroundImageUrl")&&(e.backgroundImageUrl?(new Ak.TextureLoader).load(e.backgroundImageUrl,function(t){t.colorSpace=Ak.SRGBColorSpace,e.skysphere.material=new Ak.MeshBasicMaterial({map:t,side:Ak.BackSide}),e.skysphere.visible=!0,e.onBackgroundImageLoaded&&setTimeout(e.onBackgroundImageLoaded),!e.loadComplete&&h()}):(e.skysphere.visible=!1,e.skysphere.material.map=null,!e.loadComplete&&h())),t.hasOwnProperty("showNavInfo")&&(e.navInfo.style.display=e.showNavInfo?null:"none"),t.hasOwnProperty("lights")&&((t.lights||[]).forEach(function(t){return e.scene.remove(t)}),e.lights.forEach(function(t){return e.scene.add(t)})),t.hasOwnProperty("objects")&&((t.objects||[]).forEach(function(t){return e.scene.remove(t)}),e.objects.forEach(function(t){return e.scene.add(t)}))}});function Ck(e,t){var n=new t;return n._destructor&&n._destructor(),{linkProp:function(t){return{default:n[t](),onChange:function(n,i){i[e][t](n)},triggerUpdate:!1}},linkMethod:function(t){return function(n){for(var i=n[e],r=arguments.length,s=new Array(r>1?r-1:0),a=1;a3?r-3:0),a=3;a/references/, and the always-on injection blocks # under graphify/always_on/. There is no graphify/skills//SKILL.md in the # repo, so no SKILL.md glob is needed here. -graphify = ["skill.md", "skill-codex.md", "skill-opencode.md", "skill-kilo.md", "command-kilo.md", "skill-aider.md", "skill-amp.md", "skill-agents.md", "skill-copilot.md", "skill-claw.md", "skill-windows.md", "skill-droid.md", "skill-trae.md", "skill-kiro.md", "skill-vscode.md", "skill-pi.md", "skill-devin.md", "skills/*/references/*.md", "always_on/*.md"] +graphify = ["skill.md", "skill-codex.md", "skill-opencode.md", "skill-kilo.md", "command-kilo.md", "skill-aider.md", "skill-amp.md", "skill-agents.md", "skill-copilot.md", "skill-claw.md", "skill-windows.md", "skill-droid.md", "skill-trae.md", "skill-kiro.md", "skill-vscode.md", "skill-pi.md", "skill-devin.md", "skills/*/references/*.md", "always_on/*.md", "vendor/*.js", "vendor/*.txt"] [tool.pytest.ini_options] testpaths = ["tests"] diff --git a/tests/test_cli_export.py b/tests/test_cli_export.py index 6173a61aa..a6d2411b0 100644 --- a/tests/test_cli_export.py +++ b/tests/test_cli_export.py @@ -70,6 +70,29 @@ def test_export_html_creates_file(tmp_path): assert html.stat().st_size > 0 +def test_export_html_3d_creates_a_fully_offline_file(tmp_path): + _make_graph(tmp_path) + result = _run(["export", "html", "--viz", "3d"], tmp_path) + assert result.returncode == 0, result.stderr + content = (tmp_path / "graphify-out" / "graph.html").read_text() + assert "ForceGraph3D" in content + assert "', file_type="py") + G.add_node("c", label="plain", file_type="py") + G.add_edge('a"b', "c", relation="calls", confidence="EXTRACTED") + content = render("3d", G=G, communities={0: ['a"b', "c"]}) + # The embedded JSON must not be able to close the script tag early. + assert "" in content + + +def test_over_limit_aggregation_keeps_the_requested_mode(): + """The community-aggregation fallback re-enters to_html; it must not drop + back to the 2D renderer when the caller asked for 3D.""" + G = make_graph() + communities = cluster(G) + if len(communities) < 2: + pytest.skip("fixture collapses to a single community") + with tempfile.TemporaryDirectory() as tmp: + out = Path(tmp) / "graph.html" + to_html(G, communities, str(out), node_limit=1, mode="3d") + content = out.read_text(encoding="utf-8") + assert "3d-force-graph" in content + assert "vis-network" not in content + + +@pytest.mark.parametrize("raw,expected", [ + (None, "2d"), ("", "2d"), ("2d", "2d"), ("3d", "3d"), + ("3D", "3d"), (" 3d ", "3d"), ("webgl", "2d"), ("nonsense", "2d"), +]) +def test_resolve_viz_mode(raw, expected): + assert _resolve_viz_mode(raw) == expected + + +def test_viz_mode_env_var(monkeypatch): + monkeypatch.setenv("GRAPHIFY_VIZ_MODE", "3d") + assert "3d-force-graph" in render() + # An explicit argument still wins over the environment. + assert "vis-network" in render("2d") + monkeypatch.setenv("GRAPHIFY_VIZ_MODE", "bogus") + assert "vis-network" in render() + + +def test_cli_viz_modes_match_the_exporter(): + """cli.py hardcodes the accepted values to keep networkx off the startup + path; the two lists must not drift.""" + from graphify.cli import _VIZ_MODES + assert tuple(_VIZ_MODES) == tuple(VIZ_MODES) diff --git a/tools/skillgen/expected/graphify__skill-agents.md b/tools/skillgen/expected/graphify__skill-agents.md index afb4ecc12..35e6079fb 100644 --- a/tools/skillgen/expected/graphify__skill-agents.md +++ b/tools/skillgen/expected/graphify__skill-agents.md @@ -21,6 +21,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti /graphify --whisper-model medium # use a larger Whisper model for better transcription accuracy /graphify --cluster-only # rerun clustering on existing graph /graphify --no-viz # skip visualization, just report + JSON +/graphify --viz 3d # render graph.html as an interactive 3D WebGL view /graphify --html # (HTML is generated by default - this flag is a no-op) /graphify --svg # also export graph.svg (embeds in Notion, GitHub) /graphify --graphml # export graph.graphml (Gephi, yEd) @@ -532,6 +533,7 @@ Generate the HTML graph (always, unless `--no-viz`): ```bash graphify export html # auto-aggregates to community view if graph > 5000 nodes # or: graphify export html --no-viz +# or: graphify export html --viz 3d # only when the user asked for --viz 3d ``` ### Steps 6b-8 - Wiki, Neo4j, FalkorDB, SVG, GraphML, MCP, benchmark (only on their flags) diff --git a/tools/skillgen/expected/graphify__skill-amp.md b/tools/skillgen/expected/graphify__skill-amp.md index afb4ecc12..35e6079fb 100644 --- a/tools/skillgen/expected/graphify__skill-amp.md +++ b/tools/skillgen/expected/graphify__skill-amp.md @@ -21,6 +21,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti /graphify --whisper-model medium # use a larger Whisper model for better transcription accuracy /graphify --cluster-only # rerun clustering on existing graph /graphify --no-viz # skip visualization, just report + JSON +/graphify --viz 3d # render graph.html as an interactive 3D WebGL view /graphify --html # (HTML is generated by default - this flag is a no-op) /graphify --svg # also export graph.svg (embeds in Notion, GitHub) /graphify --graphml # export graph.graphml (Gephi, yEd) @@ -532,6 +533,7 @@ Generate the HTML graph (always, unless `--no-viz`): ```bash graphify export html # auto-aggregates to community view if graph > 5000 nodes # or: graphify export html --no-viz +# or: graphify export html --viz 3d # only when the user asked for --viz 3d ``` ### Steps 6b-8 - Wiki, Neo4j, FalkorDB, SVG, GraphML, MCP, benchmark (only on their flags) diff --git a/tools/skillgen/expected/graphify__skill-claw.md b/tools/skillgen/expected/graphify__skill-claw.md index d98865cc8..149f68207 100644 --- a/tools/skillgen/expected/graphify__skill-claw.md +++ b/tools/skillgen/expected/graphify__skill-claw.md @@ -21,6 +21,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti /graphify --whisper-model medium # use a larger Whisper model for better transcription accuracy /graphify --cluster-only # rerun clustering on existing graph /graphify --no-viz # skip visualization, just report + JSON +/graphify --viz 3d # render graph.html as an interactive 3D WebGL view /graphify --html # (HTML is generated by default - this flag is a no-op) /graphify --svg # also export graph.svg (embeds in Notion, GitHub) /graphify --graphml # export graph.graphml (Gephi, yEd) @@ -535,6 +536,7 @@ Generate the HTML graph (always, unless `--no-viz`): ```bash graphify export html # auto-aggregates to community view if graph > 5000 nodes # or: graphify export html --no-viz +# or: graphify export html --viz 3d # only when the user asked for --viz 3d ``` ### Steps 6b-8 - Wiki, Neo4j, FalkorDB, SVG, GraphML, MCP, benchmark (only on their flags) diff --git a/tools/skillgen/expected/graphify__skill-codex.md b/tools/skillgen/expected/graphify__skill-codex.md index 0c821a278..49c3bcc01 100644 --- a/tools/skillgen/expected/graphify__skill-codex.md +++ b/tools/skillgen/expected/graphify__skill-codex.md @@ -21,6 +21,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti /graphify --whisper-model medium # use a larger Whisper model for better transcription accuracy /graphify --cluster-only # rerun clustering on existing graph /graphify --no-viz # skip visualization, just report + JSON +/graphify --viz 3d # render graph.html as an interactive 3D WebGL view /graphify --html # (HTML is generated by default - this flag is a no-op) /graphify --svg # also export graph.svg (embeds in Notion, GitHub) /graphify --graphml # export graph.graphml (Gephi, yEd) @@ -532,6 +533,7 @@ Generate the HTML graph (always, unless `--no-viz`): ```bash graphify export html # auto-aggregates to community view if graph > 5000 nodes # or: graphify export html --no-viz +# or: graphify export html --viz 3d # only when the user asked for --viz 3d ``` ### Steps 6b-8 - Wiki, Neo4j, FalkorDB, SVG, GraphML, MCP, benchmark (only on their flags) diff --git a/tools/skillgen/expected/graphify__skill-copilot.md b/tools/skillgen/expected/graphify__skill-copilot.md index d98865cc8..149f68207 100644 --- a/tools/skillgen/expected/graphify__skill-copilot.md +++ b/tools/skillgen/expected/graphify__skill-copilot.md @@ -21,6 +21,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti /graphify --whisper-model medium # use a larger Whisper model for better transcription accuracy /graphify --cluster-only # rerun clustering on existing graph /graphify --no-viz # skip visualization, just report + JSON +/graphify --viz 3d # render graph.html as an interactive 3D WebGL view /graphify --html # (HTML is generated by default - this flag is a no-op) /graphify --svg # also export graph.svg (embeds in Notion, GitHub) /graphify --graphml # export graph.graphml (Gephi, yEd) @@ -535,6 +536,7 @@ Generate the HTML graph (always, unless `--no-viz`): ```bash graphify export html # auto-aggregates to community view if graph > 5000 nodes # or: graphify export html --no-viz +# or: graphify export html --viz 3d # only when the user asked for --viz 3d ``` ### Steps 6b-8 - Wiki, Neo4j, FalkorDB, SVG, GraphML, MCP, benchmark (only on their flags) diff --git a/tools/skillgen/expected/graphify__skill-droid.md b/tools/skillgen/expected/graphify__skill-droid.md index c3815d556..1f464bb8a 100644 --- a/tools/skillgen/expected/graphify__skill-droid.md +++ b/tools/skillgen/expected/graphify__skill-droid.md @@ -21,6 +21,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti /graphify --whisper-model medium # use a larger Whisper model for better transcription accuracy /graphify --cluster-only # rerun clustering on existing graph /graphify --no-viz # skip visualization, just report + JSON +/graphify --viz 3d # render graph.html as an interactive 3D WebGL view /graphify --html # (HTML is generated by default - this flag is a no-op) /graphify --svg # also export graph.svg (embeds in Notion, GitHub) /graphify --graphml # export graph.graphml (Gephi, yEd) @@ -532,6 +533,7 @@ Generate the HTML graph (always, unless `--no-viz`): ```bash graphify export html # auto-aggregates to community view if graph > 5000 nodes # or: graphify export html --no-viz +# or: graphify export html --viz 3d # only when the user asked for --viz 3d ``` ### Steps 6b-8 - Wiki, Neo4j, FalkorDB, SVG, GraphML, MCP, benchmark (only on their flags) diff --git a/tools/skillgen/expected/graphify__skill-kilo.md b/tools/skillgen/expected/graphify__skill-kilo.md index dbb4658ca..ebc336896 100644 --- a/tools/skillgen/expected/graphify__skill-kilo.md +++ b/tools/skillgen/expected/graphify__skill-kilo.md @@ -21,6 +21,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti /graphify --whisper-model medium # use a larger Whisper model for better transcription accuracy /graphify --cluster-only # rerun clustering on existing graph /graphify --no-viz # skip visualization, just report + JSON +/graphify --viz 3d # render graph.html as an interactive 3D WebGL view /graphify --html # (HTML is generated by default - this flag is a no-op) /graphify --svg # also export graph.svg (embeds in Notion, GitHub) /graphify --graphml # export graph.graphml (Gephi, yEd) @@ -535,6 +536,7 @@ Generate the HTML graph (always, unless `--no-viz`): ```bash graphify export html # auto-aggregates to community view if graph > 5000 nodes # or: graphify export html --no-viz +# or: graphify export html --viz 3d # only when the user asked for --viz 3d ``` ### Steps 6b-8 - Wiki, Neo4j, FalkorDB, SVG, GraphML, MCP, benchmark (only on their flags) diff --git a/tools/skillgen/expected/graphify__skill-kiro.md b/tools/skillgen/expected/graphify__skill-kiro.md index d98865cc8..149f68207 100644 --- a/tools/skillgen/expected/graphify__skill-kiro.md +++ b/tools/skillgen/expected/graphify__skill-kiro.md @@ -21,6 +21,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti /graphify --whisper-model medium # use a larger Whisper model for better transcription accuracy /graphify --cluster-only # rerun clustering on existing graph /graphify --no-viz # skip visualization, just report + JSON +/graphify --viz 3d # render graph.html as an interactive 3D WebGL view /graphify --html # (HTML is generated by default - this flag is a no-op) /graphify --svg # also export graph.svg (embeds in Notion, GitHub) /graphify --graphml # export graph.graphml (Gephi, yEd) @@ -535,6 +536,7 @@ Generate the HTML graph (always, unless `--no-viz`): ```bash graphify export html # auto-aggregates to community view if graph > 5000 nodes # or: graphify export html --no-viz +# or: graphify export html --viz 3d # only when the user asked for --viz 3d ``` ### Steps 6b-8 - Wiki, Neo4j, FalkorDB, SVG, GraphML, MCP, benchmark (only on their flags) diff --git a/tools/skillgen/expected/graphify__skill-opencode.md b/tools/skillgen/expected/graphify__skill-opencode.md index cf5dae440..fc4055b00 100644 --- a/tools/skillgen/expected/graphify__skill-opencode.md +++ b/tools/skillgen/expected/graphify__skill-opencode.md @@ -21,6 +21,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti /graphify --whisper-model medium # use a larger Whisper model for better transcription accuracy /graphify --cluster-only # rerun clustering on existing graph /graphify --no-viz # skip visualization, just report + JSON +/graphify --viz 3d # render graph.html as an interactive 3D WebGL view /graphify --html # (HTML is generated by default - this flag is a no-op) /graphify --svg # also export graph.svg (embeds in Notion, GitHub) /graphify --graphml # export graph.graphml (Gephi, yEd) @@ -527,6 +528,7 @@ Generate the HTML graph (always, unless `--no-viz`): ```bash graphify export html # auto-aggregates to community view if graph > 5000 nodes # or: graphify export html --no-viz +# or: graphify export html --viz 3d # only when the user asked for --viz 3d ``` ### Steps 6b-8 - Wiki, Neo4j, FalkorDB, SVG, GraphML, MCP, benchmark (only on their flags) diff --git a/tools/skillgen/expected/graphify__skill-pi.md b/tools/skillgen/expected/graphify__skill-pi.md index d98865cc8..149f68207 100644 --- a/tools/skillgen/expected/graphify__skill-pi.md +++ b/tools/skillgen/expected/graphify__skill-pi.md @@ -21,6 +21,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti /graphify --whisper-model medium # use a larger Whisper model for better transcription accuracy /graphify --cluster-only # rerun clustering on existing graph /graphify --no-viz # skip visualization, just report + JSON +/graphify --viz 3d # render graph.html as an interactive 3D WebGL view /graphify --html # (HTML is generated by default - this flag is a no-op) /graphify --svg # also export graph.svg (embeds in Notion, GitHub) /graphify --graphml # export graph.graphml (Gephi, yEd) @@ -535,6 +536,7 @@ Generate the HTML graph (always, unless `--no-viz`): ```bash graphify export html # auto-aggregates to community view if graph > 5000 nodes # or: graphify export html --no-viz +# or: graphify export html --viz 3d # only when the user asked for --viz 3d ``` ### Steps 6b-8 - Wiki, Neo4j, FalkorDB, SVG, GraphML, MCP, benchmark (only on their flags) diff --git a/tools/skillgen/expected/graphify__skill-trae.md b/tools/skillgen/expected/graphify__skill-trae.md index b0cbeb122..c3746b44b 100644 --- a/tools/skillgen/expected/graphify__skill-trae.md +++ b/tools/skillgen/expected/graphify__skill-trae.md @@ -21,6 +21,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti /graphify --whisper-model medium # use a larger Whisper model for better transcription accuracy /graphify --cluster-only # rerun clustering on existing graph /graphify --no-viz # skip visualization, just report + JSON +/graphify --viz 3d # render graph.html as an interactive 3D WebGL view /graphify --html # (HTML is generated by default - this flag is a no-op) /graphify --svg # also export graph.svg (embeds in Notion, GitHub) /graphify --graphml # export graph.graphml (Gephi, yEd) @@ -533,6 +534,7 @@ Generate the HTML graph (always, unless `--no-viz`): ```bash graphify export html # auto-aggregates to community view if graph > 5000 nodes # or: graphify export html --no-viz +# or: graphify export html --viz 3d # only when the user asked for --viz 3d ``` ### Steps 6b-8 - Wiki, Neo4j, FalkorDB, SVG, GraphML, MCP, benchmark (only on their flags) diff --git a/tools/skillgen/expected/graphify__skill-vscode.md b/tools/skillgen/expected/graphify__skill-vscode.md index 3e6bc6b7b..cebe01559 100644 --- a/tools/skillgen/expected/graphify__skill-vscode.md +++ b/tools/skillgen/expected/graphify__skill-vscode.md @@ -21,6 +21,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti /graphify --whisper-model medium # use a larger Whisper model for better transcription accuracy /graphify --cluster-only # rerun clustering on existing graph /graphify --no-viz # skip visualization, just report + JSON +/graphify --viz 3d # render graph.html as an interactive 3D WebGL view /graphify --html # (HTML is generated by default - this flag is a no-op) /graphify --svg # also export graph.svg (embeds in Notion, GitHub) /graphify --graphml # export graph.graphml (Gephi, yEd) @@ -531,6 +532,7 @@ Generate the HTML graph (always, unless `--no-viz`): ```bash graphify export html # auto-aggregates to community view if graph > 5000 nodes # or: graphify export html --no-viz +# or: graphify export html --viz 3d # only when the user asked for --viz 3d ``` ### Steps 6b-8 - Wiki, Neo4j, FalkorDB, SVG, GraphML, MCP, benchmark (only on their flags) diff --git a/tools/skillgen/expected/graphify__skill-windows.md b/tools/skillgen/expected/graphify__skill-windows.md index 574384576..452bb1275 100644 --- a/tools/skillgen/expected/graphify__skill-windows.md +++ b/tools/skillgen/expected/graphify__skill-windows.md @@ -21,6 +21,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti /graphify --whisper-model medium # use a larger Whisper model for better transcription accuracy /graphify --cluster-only # rerun clustering on existing graph /graphify --no-viz # skip visualization, just report + JSON +/graphify --viz 3d # render graph.html as an interactive 3D WebGL view /graphify --html # (HTML is generated by default - this flag is a no-op) /graphify --svg # also export graph.svg (embeds in Notion, GitHub) /graphify --graphml # export graph.graphml (Gephi, yEd) @@ -557,6 +558,7 @@ Generate the HTML graph (always, unless `--no-viz`): ```bash graphify export html # auto-aggregates to community view if graph > 5000 nodes # or: graphify export html --no-viz +# or: graphify export html --viz 3d # only when the user asked for --viz 3d ``` ### Steps 6b-8 - Wiki, Neo4j, FalkorDB, SVG, GraphML, MCP, benchmark (only on their flags) diff --git a/tools/skillgen/expected/graphify__skill.md b/tools/skillgen/expected/graphify__skill.md index d98865cc8..149f68207 100644 --- a/tools/skillgen/expected/graphify__skill.md +++ b/tools/skillgen/expected/graphify__skill.md @@ -21,6 +21,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti /graphify --whisper-model medium # use a larger Whisper model for better transcription accuracy /graphify --cluster-only # rerun clustering on existing graph /graphify --no-viz # skip visualization, just report + JSON +/graphify --viz 3d # render graph.html as an interactive 3D WebGL view /graphify --html # (HTML is generated by default - this flag is a no-op) /graphify --svg # also export graph.svg (embeds in Notion, GitHub) /graphify --graphml # export graph.graphml (Gephi, yEd) @@ -535,6 +536,7 @@ Generate the HTML graph (always, unless `--no-viz`): ```bash graphify export html # auto-aggregates to community view if graph > 5000 nodes # or: graphify export html --no-viz +# or: graphify export html --viz 3d # only when the user asked for --viz 3d ``` ### Steps 6b-8 - Wiki, Neo4j, FalkorDB, SVG, GraphML, MCP, benchmark (only on their flags) diff --git a/tools/skillgen/fragments/core/core.md b/tools/skillgen/fragments/core/core.md index e28910728..06fdc04dc 100644 --- a/tools/skillgen/fragments/core/core.md +++ b/tools/skillgen/fragments/core/core.md @@ -18,6 +18,7 @@ Turn any folder of files into a navigable knowledge graph with community detecti /graphify --whisper-model medium # use a larger Whisper model for better transcription accuracy /graphify --cluster-only # rerun clustering on existing graph /graphify --no-viz # skip visualization, just report + JSON +/graphify --viz 3d # render graph.html as an interactive 3D WebGL view /graphify --html # (HTML is generated by default - this flag is a no-op) /graphify --svg # also export graph.svg (embeds in Notion, GitHub) /graphify --graphml # export graph.graphml (Gephi, yEd) @@ -470,6 +471,7 @@ Generate the HTML graph (always, unless `--no-viz`): ```bash graphify export html # auto-aggregates to community view if graph > 5000 nodes # or: graphify export html --no-viz +# or: graphify export html --viz 3d # only when the user asked for --viz 3d ``` ### Steps 6b-8 - Wiki, Neo4j, FalkorDB, SVG, GraphML, MCP, benchmark (only on their flags)